PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 4.7.0
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v4.7.0
4.7.0 4.6.1 4.6.0 4.5.5 4.5.4 4.5.3 4.5.2 3.2.20 3.2.21 3.2.22 3.2.3 3.2.5 3.2.6 3.2.7 3.2.9 3.3.0 3.3.1 3.3.2 3.4.0 3.4.1 3.4.2 3.5.0 3.6.0 3.7.0 3.7.1 All 111 releases
wp-optimize / js / jszip / jszip.js

jszip.js in WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance 4.7.0, at js/jszip/jszip.js

11,586 lines 365.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /*!
2
3 JSZip v3.10.2 - 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/main/LICENSE.markdown.
8
9 JSZip uses the library pako released under the MIT license :
10 https://github.com/nodeca/pako/blob/main/LICENSE
11 */
12
13 (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JSZip = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
14 "use strict";
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 Crc32Probe = require("./stream/Crc32Probe");
127 var DataLengthProbe = require("./stream/DataLengthProbe");
128
129 /**
130 * Represent a compressed object, with everything needed to decompress it.
131 * @constructor
132 * @param {number} compressedSize the size of the data compressed.
133 * @param {number} uncompressedSize the size of the data after decompression.
134 * @param {number} crc32 the crc32 of the decompressed file.
135 * @param {object} compression the type of compression, see lib/compressions.js.
136 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.
137 */
138 function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {
139 this.compressedSize = compressedSize;
140 this.uncompressedSize = uncompressedSize;
141 this.crc32 = crc32;
142 this.compression = compression;
143 this.compressedContent = data;
144 }
145
146 CompressedObject.prototype = {
147 /**
148 * Create a worker to get the uncompressed content.
149 * @return {GenericWorker} the worker.
150 */
151 getContentWorker: function () {
152 var worker = new DataWorker(external.Promise.resolve(this.compressedContent))
153 .pipe(this.compression.uncompressWorker())
154 .pipe(new DataLengthProbe("data_length"));
155
156 var that = this;
157 worker.on("end", function () {
158 if (this.streamInfo["data_length"] !== that.uncompressedSize) {
159 throw new Error("Bug : uncompressed data size mismatch");
160 }
161 });
162 return worker;
163 },
164 /**
165 * Create a worker to get the compressed content.
166 * @return {GenericWorker} the worker.
167 */
168 getCompressedWorker: function () {
169 return new DataWorker(external.Promise.resolve(this.compressedContent))
170 .withStreamInfo("compressedSize", this.compressedSize)
171 .withStreamInfo("uncompressedSize", this.uncompressedSize)
172 .withStreamInfo("crc32", this.crc32)
173 .withStreamInfo("compression", this.compression)
174 ;
175 }
176 };
177
178 /**
179 * Chain the given worker with other workers to compress the content with the
180 * given compression.
181 * @param {GenericWorker} uncompressedWorker the worker to pipe.
182 * @param {Object} compression the compression object.
183 * @param {Object} compressionOptions the options to use when compressing.
184 * @return {GenericWorker} the new worker compressing the content.
185 */
186 CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {
187 return uncompressedWorker
188 .pipe(new Crc32Probe())
189 .pipe(new DataLengthProbe("uncompressedSize"))
190 .pipe(compression.compressWorker(compressionOptions))
191 .pipe(new DataLengthProbe("compressedSize"))
192 .withStreamInfo("compression", compression);
193 };
194
195 module.exports = CompressedObject;
196
197 },{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(require,module,exports){
198 "use strict";
199
200 var GenericWorker = require("./stream/GenericWorker");
201
202 exports.STORE = {
203 magic: "\x00\x00",
204 compressWorker : function () {
205 return new GenericWorker("STORE compression");
206 },
207 uncompressWorker : function () {
208 return new GenericWorker("STORE decompression");
209 }
210 };
211 exports.DEFLATE = require("./flate");
212
213 },{"./flate":7,"./stream/GenericWorker":28}],4:[function(require,module,exports){
214 "use strict";
215
216 var utils = require("./utils");
217
218 /**
219 * The following functions come from pako, from pako/lib/zlib/crc32.js
220 * released under the MIT license, see pako https://github.com/nodeca/pako/
221 */
222
223 // Use ordinary array, since untyped makes no boost here
224 function makeTable() {
225 var c, table = [];
226
227 for(var n =0; n < 256; n++){
228 c = n;
229 for(var k =0; k < 8; k++){
230 c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
231 }
232 table[n] = c;
233 }
234
235 return table;
236 }
237
238 // Create table on load. Just 255 signed longs. Not a problem.
239 var crcTable = makeTable();
240
241
242 function crc32(crc, buf, len, pos) {
243 var t = crcTable, end = pos + len;
244
245 crc = crc ^ (-1);
246
247 for (var i = pos; i < end; i++ ) {
248 crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
249 }
250
251 return (crc ^ (-1)); // >>> 0;
252 }
253
254 // That's all for the pako functions.
255
256 /**
257 * Compute the crc32 of a string.
258 * This is almost the same as the function crc32, but for strings. Using the
259 * same function for the two use cases leads to horrible performances.
260 * @param {Number} crc the starting value of the crc.
261 * @param {String} str the string to use.
262 * @param {Number} len the length of the string.
263 * @param {Number} pos the starting position for the crc32 computation.
264 * @return {Number} the computed crc32.
265 */
266 function crc32str(crc, str, len, pos) {
267 var t = crcTable, end = pos + len;
268
269 crc = crc ^ (-1);
270
271 for (var i = pos; i < end; i++ ) {
272 crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];
273 }
274
275 return (crc ^ (-1)); // >>> 0;
276 }
277
278 module.exports = function crc32wrapper(input, crc) {
279 if (typeof input === "undefined" || !input.length) {
280 return 0;
281 }
282
283 var isArray = utils.getTypeOf(input) !== "string";
284
285 if(isArray) {
286 return crc32(crc|0, input, input.length, 0);
287 } else {
288 return crc32str(crc|0, input, input.length, 0);
289 }
290 };
291
292 },{"./utils":32}],5:[function(require,module,exports){
293 "use strict";
294 exports.base64 = false;
295 exports.binary = false;
296 exports.dir = false;
297 exports.createFolders = true;
298 exports.date = null;
299 exports.compression = null;
300 exports.compressionOptions = null;
301 exports.comment = null;
302 exports.unixPermissions = null;
303 exports.dosPermissions = null;
304
305 },{}],6:[function(require,module,exports){
306 "use strict";
307
308 // load the global object first:
309 // - it should be better integrated in the system (unhandledRejection in node)
310 // - the environment may have a custom Promise implementation (see zone.js)
311 var ES6Promise = null;
312 if (typeof Promise !== "undefined") {
313 ES6Promise = Promise;
314 } else {
315 ES6Promise = require("lie");
316 }
317
318 /**
319 * Let the user use/change some implementations.
320 */
321 module.exports = {
322 Promise: ES6Promise
323 };
324
325 },{"lie":37}],7:[function(require,module,exports){
326 "use strict";
327 var USE_TYPEDARRAY = (typeof Uint8Array !== "undefined") && (typeof Uint16Array !== "undefined") && (typeof Uint32Array !== "undefined");
328
329 var pako = require("pako");
330 var utils = require("./utils");
331 var GenericWorker = require("./stream/GenericWorker");
332
333 var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";
334
335 exports.magic = "\x08\x00";
336
337 /**
338 * Create a worker that uses pako to inflate/deflate.
339 * @constructor
340 * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate".
341 * @param {Object} options the options to use when (de)compressing.
342 */
343 function FlateWorker(action, options) {
344 GenericWorker.call(this, "FlateWorker/" + action);
345
346 this._pako = null;
347 this._pakoAction = action;
348 this._pakoOptions = options;
349 // the `meta` object from the last chunk received
350 // this allow this worker to pass around metadata
351 this.meta = {};
352 }
353
354 utils.inherits(FlateWorker, GenericWorker);
355
356 /**
357 * @see GenericWorker.processChunk
358 */
359 FlateWorker.prototype.processChunk = function (chunk) {
360 this.meta = chunk.meta;
361 if (this._pako === null) {
362 this._createPako();
363 }
364 this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);
365 };
366
367 /**
368 * @see GenericWorker.flush
369 */
370 FlateWorker.prototype.flush = function () {
371 GenericWorker.prototype.flush.call(this);
372 if (this._pako === null) {
373 this._createPako();
374 }
375 this._pako.push([], true);
376 };
377 /**
378 * @see GenericWorker.cleanUp
379 */
380 FlateWorker.prototype.cleanUp = function () {
381 GenericWorker.prototype.cleanUp.call(this);
382 this._pako = null;
383 };
384
385 /**
386 * Create the _pako object.
387 * TODO: lazy-loading this object isn't the best solution but it's the
388 * quickest. The best solution is to lazy-load the worker list. See also the
389 * issue #446.
390 */
391 FlateWorker.prototype._createPako = function () {
392 this._pako = new pako[this._pakoAction]({
393 raw: true,
394 level: this._pakoOptions.level || -1 // default compression
395 });
396 var self = this;
397 this._pako.onData = function(data) {
398 self.push({
399 data : data,
400 meta : self.meta
401 });
402 };
403 };
404
405 exports.compressWorker = function (compressionOptions) {
406 return new FlateWorker("Deflate", compressionOptions);
407 };
408 exports.uncompressWorker = function () {
409 return new FlateWorker("Inflate", {});
410 };
411
412 },{"./stream/GenericWorker":28,"./utils":32,"pako":38}],8:[function(require,module,exports){
413 "use strict";
414
415 var utils = require("../utils");
416 var GenericWorker = require("../stream/GenericWorker");
417 var utf8 = require("../utf8");
418 var crc32 = require("../crc32");
419 var signature = require("../signature");
420
421 /**
422 * Transform an integer into a string in hexadecimal.
423 * @private
424 * @param {number} dec the number to convert.
425 * @param {number} bytes the number of bytes to generate.
426 * @returns {string} the result.
427 */
428 var decToHex = function(dec, bytes) {
429 var hex = "", i;
430 for (i = 0; i < bytes; i++) {
431 hex += String.fromCharCode(dec & 0xff);
432 dec = dec >>> 8;
433 }
434 return hex;
435 };
436
437 /**
438 * Generate the UNIX part of the external file attributes.
439 * @param {Object} unixPermissions the unix permissions or null.
440 * @param {Boolean} isDir true if the entry is a directory, false otherwise.
441 * @return {Number} a 32 bit integer.
442 *
443 * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
444 *
445 * TTTTsstrwxrwxrwx0000000000ADVSHR
446 * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
447 * ^^^_________________________ setuid, setgid, sticky
448 * ^^^^^^^^^________________ permissions
449 * ^^^^^^^^^^______ not used ?
450 * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
451 */
452 var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
453
454 var result = unixPermissions;
455 if (!unixPermissions) {
456 // I can't use octal values in strict mode, hence the hexa.
457 // 040775 => 0x41fd
458 // 0100664 => 0x81b4
459 result = isDir ? 0x41fd : 0x81b4;
460 }
461 return (result & 0xFFFF) << 16;
462 };
463
464 /**
465 * Generate the DOS part of the external file attributes.
466 * @param {Object} dosPermissions the dos permissions or null.
467 * @param {Boolean} isDir true if the entry is a directory, false otherwise.
468 * @return {Number} a 32 bit integer.
469 *
470 * Bit 0 Read-Only
471 * Bit 1 Hidden
472 * Bit 2 System
473 * Bit 3 Volume Label
474 * Bit 4 Directory
475 * Bit 5 Archive
476 */
477 var generateDosExternalFileAttr = function (dosPermissions) {
478 // the dir flag is already set for compatibility
479 return (dosPermissions || 0) & 0x3F;
480 };
481
482 /**
483 * Generate the various parts used in the construction of the final zip file.
484 * @param {Object} streamInfo the hash with information about the compressed file.
485 * @param {Boolean} streamedContent is the content streamed ?
486 * @param {Boolean} streamingEnded is the stream finished ?
487 * @param {number} offset the current offset from the start of the zip file.
488 * @param {String} platform let's pretend we are this platform (change platform dependents fields)
489 * @param {Function} encodeFileName the function to encode the file name / comment.
490 * @return {Object} the zip parts.
491 */
492 var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {
493 var file = streamInfo["file"],
494 compression = streamInfo["compression"],
495 useCustomEncoding = encodeFileName !== utf8.utf8encode,
496 encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
497 utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
498 comment = file.comment,
499 encodedComment = utils.transformTo("string", encodeFileName(comment)),
500 utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
501 useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
502 useUTF8ForComment = utfEncodedComment.length !== comment.length,
503 dosTime,
504 dosDate,
505 extraFields = "",
506 unicodePathExtraField = "",
507 unicodeCommentExtraField = "",
508 dir = file.dir,
509 date = file.date;
510
511
512 var dataInfo = {
513 crc32 : 0,
514 compressedSize : 0,
515 uncompressedSize : 0
516 };
517
518 // if the content is streamed, the sizes/crc32 are only available AFTER
519 // the end of the stream.
520 if (!streamedContent || streamingEnded) {
521 dataInfo.crc32 = streamInfo["crc32"];
522 dataInfo.compressedSize = streamInfo["compressedSize"];
523 dataInfo.uncompressedSize = streamInfo["uncompressedSize"];
524 }
525
526 var bitflag = 0;
527 if (streamedContent) {
528 // Bit 3: the sizes/crc32 are set to zero in the local header.
529 // The correct values are put in the data descriptor immediately
530 // following the compressed data.
531 bitflag |= 0x0008;
532 }
533 if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {
534 // Bit 11: Language encoding flag (EFS).
535 bitflag |= 0x0800;
536 }
537
538
539 var extFileAttr = 0;
540 var versionMadeBy = 0;
541 if (dir) {
542 // dos or unix, we set the dos dir flag
543 extFileAttr |= 0x00010;
544 }
545 if(platform === "UNIX") {
546 versionMadeBy = 0x031E; // UNIX, version 3.0
547 extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
548 } else { // DOS or other, fallback to DOS
549 versionMadeBy = 0x0014; // DOS, version 2.0
550 extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
551 }
552
553 // date
554 // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
555 // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
556 // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
557
558 dosTime = date.getUTCHours();
559 dosTime = dosTime << 6;
560 dosTime = dosTime | date.getUTCMinutes();
561 dosTime = dosTime << 5;
562 dosTime = dosTime | date.getUTCSeconds() / 2;
563
564 dosDate = date.getUTCFullYear() - 1980;
565 dosDate = dosDate << 4;
566 dosDate = dosDate | (date.getUTCMonth() + 1);
567 dosDate = dosDate << 5;
568 dosDate = dosDate | date.getUTCDate();
569
570 if (useUTF8ForFileName) {
571 // set the unicode path extra field. unzip needs at least one extra
572 // field to correctly handle unicode path, so using the path is as good
573 // as any other information. This could improve the situation with
574 // other archive managers too.
575 // This field is usually used without the utf8 flag, with a non
576 // unicode path in the header (winrar, winzip). This helps (a bit)
577 // with the messy Windows' default compressed folders feature but
578 // breaks on p7zip which doesn't seek the unicode path extra field.
579 // So for now, UTF-8 everywhere !
580 unicodePathExtraField =
581 // Version
582 decToHex(1, 1) +
583 // NameCRC32
584 decToHex(crc32(encodedFileName), 4) +
585 // UnicodeName
586 utfEncodedFileName;
587
588 extraFields +=
589 // Info-ZIP Unicode Path Extra Field
590 "\x75\x70" +
591 // size
592 decToHex(unicodePathExtraField.length, 2) +
593 // content
594 unicodePathExtraField;
595 }
596
597 if(useUTF8ForComment) {
598
599 unicodeCommentExtraField =
600 // Version
601 decToHex(1, 1) +
602 // CommentCRC32
603 decToHex(crc32(encodedComment), 4) +
604 // UnicodeName
605 utfEncodedComment;
606
607 extraFields +=
608 // Info-ZIP Unicode Path Extra Field
609 "\x75\x63" +
610 // size
611 decToHex(unicodeCommentExtraField.length, 2) +
612 // content
613 unicodeCommentExtraField;
614 }
615
616 var header = "";
617
618 // version needed to extract
619 header += "\x0A\x00";
620 // general purpose bit flag
621 header += decToHex(bitflag, 2);
622 // compression method
623 header += compression.magic;
624 // last mod file time
625 header += decToHex(dosTime, 2);
626 // last mod file date
627 header += decToHex(dosDate, 2);
628 // crc-32
629 header += decToHex(dataInfo.crc32, 4);
630 // compressed size
631 header += decToHex(dataInfo.compressedSize, 4);
632 // uncompressed size
633 header += decToHex(dataInfo.uncompressedSize, 4);
634 // file name length
635 header += decToHex(encodedFileName.length, 2);
636 // extra field length
637 header += decToHex(extraFields.length, 2);
638
639
640 var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
641
642 var dirRecord = signature.CENTRAL_FILE_HEADER +
643 // version made by (00: DOS)
644 decToHex(versionMadeBy, 2) +
645 // file header (common to file and central directory)
646 header +
647 // file comment length
648 decToHex(encodedComment.length, 2) +
649 // disk number start
650 "\x00\x00" +
651 // internal file attributes TODO
652 "\x00\x00" +
653 // external file attributes
654 decToHex(extFileAttr, 4) +
655 // relative offset of local header
656 decToHex(offset, 4) +
657 // file name
658 encodedFileName +
659 // extra field
660 extraFields +
661 // file comment
662 encodedComment;
663
664 return {
665 fileRecord: fileRecord,
666 dirRecord: dirRecord
667 };
668 };
669
670 /**
671 * Generate the EOCD record.
672 * @param {Number} entriesCount the number of entries in the zip file.
673 * @param {Number} centralDirLength the length (in bytes) of the central dir.
674 * @param {Number} localDirLength the length (in bytes) of the local dir.
675 * @param {String} comment the zip file comment as a binary string.
676 * @param {Function} encodeFileName the function to encode the comment.
677 * @return {String} the EOCD record.
678 */
679 var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {
680 var dirEnd = "";
681 var encodedComment = utils.transformTo("string", encodeFileName(comment));
682
683 // end of central dir signature
684 dirEnd = signature.CENTRAL_DIRECTORY_END +
685 // number of this disk
686 "\x00\x00" +
687 // number of the disk with the start of the central directory
688 "\x00\x00" +
689 // total number of entries in the central directory on this disk
690 decToHex(entriesCount, 2) +
691 // total number of entries in the central directory
692 decToHex(entriesCount, 2) +
693 // size of the central directory 4 bytes
694 decToHex(centralDirLength, 4) +
695 // offset of start of central directory with respect to the starting disk number
696 decToHex(localDirLength, 4) +
697 // .ZIP file comment length
698 decToHex(encodedComment.length, 2) +
699 // .ZIP file comment
700 encodedComment;
701
702 return dirEnd;
703 };
704
705 /**
706 * Generate data descriptors for a file entry.
707 * @param {Object} streamInfo the hash generated by a worker, containing information
708 * on the file entry.
709 * @return {String} the data descriptors.
710 */
711 var generateDataDescriptors = function (streamInfo) {
712 var descriptor = "";
713 descriptor = signature.DATA_DESCRIPTOR +
714 // crc-32 4 bytes
715 decToHex(streamInfo["crc32"], 4) +
716 // compressed size 4 bytes
717 decToHex(streamInfo["compressedSize"], 4) +
718 // uncompressed size 4 bytes
719 decToHex(streamInfo["uncompressedSize"], 4);
720
721 return descriptor;
722 };
723
724
725 /**
726 * A worker to concatenate other workers to create a zip file.
727 * @param {Boolean} streamFiles `true` to stream the content of the files,
728 * `false` to accumulate it.
729 * @param {String} comment the comment to use.
730 * @param {String} platform the platform to use, "UNIX" or "DOS".
731 * @param {Function} encodeFileName the function to encode file names and comments.
732 */
733 function ZipFileWorker(streamFiles, comment, platform, encodeFileName) {
734 GenericWorker.call(this, "ZipFileWorker");
735 // The number of bytes written so far. This doesn't count accumulated chunks.
736 this.bytesWritten = 0;
737 // The comment of the zip file
738 this.zipComment = comment;
739 // The platform "generating" the zip file.
740 this.zipPlatform = platform;
741 // the function to encode file names and comments.
742 this.encodeFileName = encodeFileName;
743 // Should we stream the content of the files ?
744 this.streamFiles = streamFiles;
745 // If `streamFiles` is false, we will need to accumulate the content of the
746 // files to calculate sizes / crc32 (and write them *before* the content).
747 // This boolean indicates if we are accumulating chunks (it will change a lot
748 // during the lifetime of this worker).
749 this.accumulate = false;
750 // The buffer receiving chunks when accumulating content.
751 this.contentBuffer = [];
752 // The list of generated directory records.
753 this.dirRecords = [];
754 // The offset (in bytes) from the beginning of the zip file for the current source.
755 this.currentSourceOffset = 0;
756 // The total number of entries in this zip file.
757 this.entriesCount = 0;
758 // the name of the file currently being added, null when handling the end of the zip file.
759 // Used for the emitted metadata.
760 this.currentFile = null;
761
762
763
764 this._sources = [];
765 }
766 utils.inherits(ZipFileWorker, GenericWorker);
767
768 /**
769 * @see GenericWorker.push
770 */
771 ZipFileWorker.prototype.push = function (chunk) {
772
773 var currentFilePercent = chunk.meta.percent || 0;
774 var entriesCount = this.entriesCount;
775 var remainingFiles = this._sources.length;
776
777 if(this.accumulate) {
778 this.contentBuffer.push(chunk);
779 } else {
780 this.bytesWritten += chunk.data.length;
781
782 GenericWorker.prototype.push.call(this, {
783 data : chunk.data,
784 meta : {
785 currentFile : this.currentFile,
786 percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100
787 }
788 });
789 }
790 };
791
792 /**
793 * The worker started a new source (an other worker).
794 * @param {Object} streamInfo the streamInfo object from the new source.
795 */
796 ZipFileWorker.prototype.openedSource = function (streamInfo) {
797 this.currentSourceOffset = this.bytesWritten;
798 this.currentFile = streamInfo["file"].name;
799
800 var streamedContent = this.streamFiles && !streamInfo["file"].dir;
801
802 // don't stream folders (because they don't have any content)
803 if(streamedContent) {
804 var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
805 this.push({
806 data : record.fileRecord,
807 meta : {percent:0}
808 });
809 } else {
810 // we need to wait for the whole file before pushing anything
811 this.accumulate = true;
812 }
813 };
814
815 /**
816 * The worker finished a source (an other worker).
817 * @param {Object} streamInfo the streamInfo object from the finished source.
818 */
819 ZipFileWorker.prototype.closedSource = function (streamInfo) {
820 this.accumulate = false;
821 var streamedContent = this.streamFiles && !streamInfo["file"].dir;
822 var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
823
824 this.dirRecords.push(record.dirRecord);
825 if(streamedContent) {
826 // after the streamed file, we put data descriptors
827 this.push({
828 data : generateDataDescriptors(streamInfo),
829 meta : {percent:100}
830 });
831 } else {
832 // the content wasn't streamed, we need to push everything now
833 // first the file record, then the content
834 this.push({
835 data : record.fileRecord,
836 meta : {percent:0}
837 });
838 while(this.contentBuffer.length) {
839 this.push(this.contentBuffer.shift());
840 }
841 }
842 this.currentFile = null;
843 };
844
845 /**
846 * @see GenericWorker.flush
847 */
848 ZipFileWorker.prototype.flush = function () {
849
850 var localDirLength = this.bytesWritten;
851 for(var i = 0; i < this.dirRecords.length; i++) {
852 this.push({
853 data : this.dirRecords[i],
854 meta : {percent:100}
855 });
856 }
857 var centralDirLength = this.bytesWritten - localDirLength;
858
859 var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);
860
861 this.push({
862 data : dirEnd,
863 meta : {percent:100}
864 });
865 };
866
867 /**
868 * Prepare the next source to be read.
869 */
870 ZipFileWorker.prototype.prepareNextSource = function () {
871 this.previous = this._sources.shift();
872 this.openedSource(this.previous.streamInfo);
873 if (this.isPaused) {
874 this.previous.pause();
875 } else {
876 this.previous.resume();
877 }
878 };
879
880 /**
881 * @see GenericWorker.registerPrevious
882 */
883 ZipFileWorker.prototype.registerPrevious = function (previous) {
884 this._sources.push(previous);
885 var self = this;
886
887 previous.on("data", function (chunk) {
888 self.processChunk(chunk);
889 });
890 previous.on("end", function () {
891 self.closedSource(self.previous.streamInfo);
892 if(self._sources.length) {
893 self.prepareNextSource();
894 } else {
895 self.end();
896 }
897 });
898 previous.on("error", function (e) {
899 self.error(e);
900 });
901 return this;
902 };
903
904 /**
905 * @see GenericWorker.resume
906 */
907 ZipFileWorker.prototype.resume = function () {
908 if(!GenericWorker.prototype.resume.call(this)) {
909 return false;
910 }
911
912 if (!this.previous && this._sources.length) {
913 this.prepareNextSource();
914 return true;
915 }
916 if (!this.previous && !this._sources.length && !this.generatedError) {
917 this.end();
918 return true;
919 }
920 };
921
922 /**
923 * @see GenericWorker.error
924 */
925 ZipFileWorker.prototype.error = function (e) {
926 var sources = this._sources;
927 if(!GenericWorker.prototype.error.call(this, e)) {
928 return false;
929 }
930 for(var i = 0; i < sources.length; i++) {
931 try {
932 sources[i].error(e);
933 } catch(e) {
934 // the `error` exploded, nothing to do
935 }
936 }
937 return true;
938 };
939
940 /**
941 * @see GenericWorker.lock
942 */
943 ZipFileWorker.prototype.lock = function () {
944 GenericWorker.prototype.lock.call(this);
945 var sources = this._sources;
946 for(var i = 0; i < sources.length; i++) {
947 sources[i].lock();
948 }
949 };
950
951 module.exports = ZipFileWorker;
952
953 },{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(require,module,exports){
954 "use strict";
955
956 var compressions = require("../compressions");
957 var ZipFileWorker = require("./ZipFileWorker");
958
959 /**
960 * Find the compression to use.
961 * @param {String} fileCompression the compression defined at the file level, if any.
962 * @param {String} zipCompression the compression defined at the load() level.
963 * @return {Object} the compression object to use.
964 */
965 var getCompression = function (fileCompression, zipCompression) {
966
967 var compressionName = fileCompression || zipCompression;
968 var compression = compressions[compressionName];
969 if (!compression) {
970 throw new Error(compressionName + " is not a valid compression method !");
971 }
972 return compression;
973 };
974
975 /**
976 * Create a worker to generate a zip file.
977 * @param {JSZip} zip the JSZip instance at the right root level.
978 * @param {Object} options to generate the zip file.
979 * @param {String} comment the comment to use.
980 */
981 exports.generateWorker = function (zip, options, comment) {
982
983 var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);
984 var entriesCount = 0;
985 try {
986
987 zip.forEach(function (relativePath, file) {
988 entriesCount++;
989 var compression = getCompression(file.options.compression, options.compression);
990 var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
991 var dir = file.dir, date = file.date;
992
993 file._compressWorker(compression, compressionOptions)
994 .withStreamInfo("file", {
995 name : relativePath,
996 dir : dir,
997 date : date,
998 comment : file.comment || "",
999 unixPermissions : file.unixPermissions,
1000 dosPermissions : file.dosPermissions
1001 })
1002 .pipe(zipFileWorker);
1003 });
1004 zipFileWorker.entriesCount = entriesCount;
1005 } catch (e) {
1006 zipFileWorker.error(e);
1007 }
1008
1009 return zipFileWorker;
1010 };
1011
1012 },{"../compressions":3,"./ZipFileWorker":8}],10:[function(require,module,exports){
1013 "use strict";
1014
1015 /**
1016 * Representation a of zip file in js
1017 * @constructor
1018 */
1019 function JSZip() {
1020 // if this constructor is used without `new`, it adds `new` before itself:
1021 if(!(this instanceof JSZip)) {
1022 return new JSZip();
1023 }
1024
1025 if(arguments.length) {
1026 throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
1027 }
1028
1029 // object containing the files :
1030 // {
1031 // "folder/" : {...},
1032 // "folder/data.txt" : {...}
1033 // }
1034 // NOTE: we use a null prototype because we do not
1035 // want filenames like "toString" coming from a zip file
1036 // to overwrite methods and attributes in a normal Object.
1037 this.files = Object.create(null);
1038
1039 this.comment = null;
1040
1041 // Where we are in the hierarchy
1042 this.root = "";
1043 this.clone = function() {
1044 var newObj = new JSZip();
1045 for (var i in this) {
1046 if (typeof this[i] !== "function") {
1047 newObj[i] = this[i];
1048 }
1049 }
1050 return newObj;
1051 };
1052 }
1053 JSZip.prototype = require("./object");
1054 JSZip.prototype.loadAsync = require("./load");
1055 JSZip.support = require("./support");
1056 JSZip.defaults = require("./defaults");
1057
1058 // TODO find a better way to handle this version,
1059 // a require('package.json').version doesn't work with webpack, see #327
1060 JSZip.version = "3.10.2";
1061
1062 JSZip.loadAsync = function (content, options) {
1063 return new JSZip().loadAsync(content, options);
1064 };
1065
1066 JSZip.external = require("./external");
1067 module.exports = JSZip;
1068
1069 },{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(require,module,exports){
1070 "use strict";
1071 var utils = require("./utils");
1072 var external = require("./external");
1073 var utf8 = require("./utf8");
1074 var ZipEntries = require("./zipEntries");
1075 var Crc32Probe = require("./stream/Crc32Probe");
1076 var nodejsUtils = require("./nodejsUtils");
1077
1078 /**
1079 * Check the CRC32 of an entry.
1080 * @param {ZipEntry} zipEntry the zip entry to check.
1081 * @return {Promise} the result.
1082 */
1083 function checkEntryCRC32(zipEntry) {
1084 return new external.Promise(function (resolve, reject) {
1085 var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
1086 worker.on("error", function (e) {
1087 reject(e);
1088 })
1089 .on("end", function () {
1090 if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
1091 reject(new Error("Corrupted zip : CRC32 mismatch"));
1092 } else {
1093 resolve();
1094 }
1095 })
1096 .resume();
1097 });
1098 }
1099
1100 module.exports = function (data, options) {
1101 var zip = this;
1102 options = utils.extend(options || {}, {
1103 base64: false,
1104 checkCRC32: false,
1105 optimizedBinaryString: false,
1106 createFolders: false,
1107 decodeFileName: utf8.utf8decode
1108 });
1109
1110 if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
1111 return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
1112 }
1113
1114 return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)
1115 .then(function (data) {
1116 var zipEntries = new ZipEntries(options);
1117 zipEntries.load(data);
1118 return zipEntries;
1119 }).then(function checkCRC32(zipEntries) {
1120 var promises = [external.Promise.resolve(zipEntries)];
1121 var files = zipEntries.files;
1122 if (options.checkCRC32) {
1123 for (var i = 0; i < files.length; i++) {
1124 promises.push(checkEntryCRC32(files[i]));
1125 }
1126 }
1127 return external.Promise.all(promises);
1128 }).then(function addFiles(results) {
1129 var zipEntries = results.shift();
1130 var files = zipEntries.files;
1131 for (var i = 0; i < files.length; i++) {
1132 var input = files[i];
1133
1134 var unsafeName = input.fileNameStr;
1135 var safeName = utils.resolve(input.fileNameStr);
1136
1137 zip.file(safeName, input.decompressed, {
1138 binary: true,
1139 optimizedBinaryString: true,
1140 date: input.date,
1141 dir: input.dir,
1142 comment: input.fileCommentStr.length ? input.fileCommentStr : null,
1143 unixPermissions: input.unixPermissions,
1144 dosPermissions: input.dosPermissions,
1145 createFolders: options.createFolders
1146 });
1147 if (!input.dir) {
1148 zip.file(safeName).unsafeOriginalName = unsafeName;
1149 }
1150 }
1151 if (zipEntries.zipComment.length) {
1152 zip.comment = zipEntries.zipComment;
1153 }
1154
1155 return zip;
1156 });
1157 };
1158
1159 },{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(require,module,exports){
1160 "use strict";
1161
1162 var utils = require("../utils");
1163 var GenericWorker = require("../stream/GenericWorker");
1164
1165 /**
1166 * A worker that use a nodejs stream as source.
1167 * @constructor
1168 * @param {String} filename the name of the file entry for this stream.
1169 * @param {Readable} stream the nodejs stream.
1170 */
1171 function NodejsStreamInputAdapter(filename, stream) {
1172 GenericWorker.call(this, "Nodejs stream input adapter for " + filename);
1173 this._upstreamEnded = false;
1174 this._bindStream(stream);
1175 }
1176
1177 utils.inherits(NodejsStreamInputAdapter, GenericWorker);
1178
1179 /**
1180 * Prepare the stream and bind the callbacks on it.
1181 * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.
1182 * @param {Stream} stream the nodejs stream to use.
1183 */
1184 NodejsStreamInputAdapter.prototype._bindStream = function (stream) {
1185 var self = this;
1186 this._stream = stream;
1187 stream.pause();
1188 stream
1189 .on("data", function (chunk) {
1190 self.push({
1191 data: chunk,
1192 meta : {
1193 percent : 0
1194 }
1195 });
1196 })
1197 .on("error", function (e) {
1198 if(self.isPaused) {
1199 this.generatedError = e;
1200 } else {
1201 self.error(e);
1202 }
1203 })
1204 .on("end", function () {
1205 if(self.isPaused) {
1206 self._upstreamEnded = true;
1207 } else {
1208 self.end();
1209 }
1210 });
1211 };
1212 NodejsStreamInputAdapter.prototype.pause = function () {
1213 if(!GenericWorker.prototype.pause.call(this)) {
1214 return false;
1215 }
1216 this._stream.pause();
1217 return true;
1218 };
1219 NodejsStreamInputAdapter.prototype.resume = function () {
1220 if(!GenericWorker.prototype.resume.call(this)) {
1221 return false;
1222 }
1223
1224 if(this._upstreamEnded) {
1225 this.end();
1226 } else {
1227 this._stream.resume();
1228 }
1229
1230 return true;
1231 };
1232
1233 module.exports = NodejsStreamInputAdapter;
1234
1235 },{"../stream/GenericWorker":28,"../utils":32}],13:[function(require,module,exports){
1236 "use strict";
1237
1238 var Readable = require("readable-stream").Readable;
1239
1240 var utils = require("../utils");
1241 utils.inherits(NodejsStreamOutputAdapter, Readable);
1242
1243 /**
1244 * A nodejs stream using a worker as source.
1245 * @see the SourceWrapper in http://nodejs.org/api/stream.html
1246 * @constructor
1247 * @param {StreamHelper} helper the helper wrapping the worker
1248 * @param {Object} options the nodejs stream options
1249 * @param {Function} updateCb the update callback.
1250 */
1251 function NodejsStreamOutputAdapter(helper, options, updateCb) {
1252 Readable.call(this, options);
1253 this._helper = helper;
1254
1255 var self = this;
1256 helper.on("data", function (data, meta) {
1257 if (!self.push(data)) {
1258 self._helper.pause();
1259 }
1260 if(updateCb) {
1261 updateCb(meta);
1262 }
1263 })
1264 .on("error", function(e) {
1265 self.emit("error", e);
1266 })
1267 .on("end", function () {
1268 self.push(null);
1269 });
1270 }
1271
1272
1273 NodejsStreamOutputAdapter.prototype._read = function() {
1274 this._helper.resume();
1275 };
1276
1277 module.exports = NodejsStreamOutputAdapter;
1278
1279 },{"../utils":32,"readable-stream":16}],14:[function(require,module,exports){
1280 "use strict";
1281
1282 module.exports = {
1283 /**
1284 * True if this is running in Nodejs, will be undefined in a browser.
1285 * In a browser, browserify won't include this file and the whole module
1286 * will be resolved an empty object.
1287 */
1288 isNode : typeof Buffer !== "undefined",
1289 /**
1290 * Create a new nodejs Buffer from an existing content.
1291 * @param {Object} data the data to pass to the constructor.
1292 * @param {String} encoding the encoding to use.
1293 * @return {Buffer} a new Buffer.
1294 */
1295 newBufferFrom: function(data, encoding) {
1296 if (Buffer.from && Buffer.from !== Uint8Array.from) {
1297 return Buffer.from(data, encoding);
1298 } else {
1299 if (typeof data === "number") {
1300 // Safeguard for old Node.js versions. On newer versions,
1301 // Buffer.from(number) / Buffer(number, encoding) already throw.
1302 throw new Error("The \"data\" argument must not be a number");
1303 }
1304 return new Buffer(data, encoding);
1305 }
1306 },
1307 /**
1308 * Create a new nodejs Buffer with the specified size.
1309 * @param {Integer} size the size of the buffer.
1310 * @return {Buffer} a new Buffer.
1311 */
1312 allocBuffer: function (size) {
1313 if (Buffer.alloc) {
1314 return Buffer.alloc(size);
1315 } else {
1316 var buf = new Buffer(size);
1317 buf.fill(0);
1318 return buf;
1319 }
1320 },
1321 /**
1322 * Find out if an object is a Buffer.
1323 * @param {Object} b the object to test.
1324 * @return {Boolean} true if the object is a Buffer, false otherwise.
1325 */
1326 isBuffer : function(b){
1327 return Buffer.isBuffer(b);
1328 },
1329
1330 isStream : function (obj) {
1331 return obj &&
1332 typeof obj.on === "function" &&
1333 typeof obj.pause === "function" &&
1334 typeof obj.resume === "function";
1335 }
1336 };
1337
1338 },{}],15:[function(require,module,exports){
1339 "use strict";
1340 var utf8 = require("./utf8");
1341 var utils = require("./utils");
1342 var GenericWorker = require("./stream/GenericWorker");
1343 var StreamHelper = require("./stream/StreamHelper");
1344 var defaults = require("./defaults");
1345 var CompressedObject = require("./compressedObject");
1346 var ZipObject = require("./zipObject");
1347 var generate = require("./generate");
1348 var nodejsUtils = require("./nodejsUtils");
1349 var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter");
1350
1351
1352 /**
1353 * Add a file in the current folder.
1354 * @private
1355 * @param {string} name the name of the file
1356 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
1357 * @param {Object} originalOptions the options of the file
1358 * @return {Object} the new file.
1359 */
1360 var fileAdd = function(name, data, originalOptions) {
1361 // be sure sub folders exist
1362 var dataType = utils.getTypeOf(data),
1363 parent;
1364
1365
1366 /*
1367 * Correct options.
1368 */
1369
1370 var o = utils.extend(originalOptions || {}, defaults);
1371 o.date = o.date || new Date();
1372 if (o.compression !== null) {
1373 o.compression = o.compression.toUpperCase();
1374 }
1375
1376 if (typeof o.unixPermissions === "string") {
1377 o.unixPermissions = parseInt(o.unixPermissions, 8);
1378 }
1379
1380 // UNX_IFDIR 0040000 see zipinfo.c
1381 if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
1382 o.dir = true;
1383 }
1384 // Bit 4 Directory
1385 if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
1386 o.dir = true;
1387 }
1388
1389 if (o.dir) {
1390 name = forceTrailingSlash(name);
1391 }
1392 if (o.createFolders && (parent = parentFolder(name))) {
1393 folderAdd.call(this, parent, true);
1394 }
1395
1396 var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false;
1397 if (!originalOptions || typeof originalOptions.binary === "undefined") {
1398 o.binary = !isUnicodeString;
1399 }
1400
1401
1402 var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;
1403
1404 if (isCompressedEmpty || o.dir || !data || data.length === 0) {
1405 o.base64 = false;
1406 o.binary = true;
1407 data = "";
1408 o.compression = "STORE";
1409 dataType = "string";
1410 }
1411
1412 /*
1413 * Convert content to fit.
1414 */
1415
1416 var zipObjectContent = null;
1417 if (data instanceof CompressedObject || data instanceof GenericWorker) {
1418 zipObjectContent = data;
1419 } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
1420 zipObjectContent = new NodejsStreamInputAdapter(name, data);
1421 } else {
1422 zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);
1423 }
1424
1425 var object = new ZipObject(name, zipObjectContent, o);
1426 this.files[name] = object;
1427 /*
1428 TODO: we can't throw an exception because we have async promises
1429 (we can have a promise of a Date() for example) but returning a
1430 promise is useless because file(name, data) returns the JSZip
1431 object for chaining. Should we break that to allow the user
1432 to catch the error ?
1433
1434 return external.Promise.resolve(zipObjectContent)
1435 .then(function () {
1436 return object;
1437 });
1438 */
1439 };
1440
1441 /**
1442 * Find the parent folder of the path.
1443 * @private
1444 * @param {string} path the path to use
1445 * @return {string} the parent folder, or ""
1446 */
1447 var parentFolder = function (path) {
1448 if (path.slice(-1) === "/") {
1449 path = path.substring(0, path.length - 1);
1450 }
1451 var lastSlash = path.lastIndexOf("/");
1452 return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
1453 };
1454
1455 /**
1456 * Returns the path with a slash at the end.
1457 * @private
1458 * @param {String} path the path to check.
1459 * @return {String} the path with a trailing slash.
1460 */
1461 var forceTrailingSlash = function(path) {
1462 // Check the name ends with a /
1463 if (path.slice(-1) !== "/") {
1464 path += "/"; // IE doesn't like substr(-1)
1465 }
1466 return path;
1467 };
1468
1469 /**
1470 * Add a (sub) folder in the current folder.
1471 * @private
1472 * @param {string} name the folder's name
1473 * @param {boolean=} [createFolders] If true, automatically create sub
1474 * folders. Defaults to false.
1475 * @return {Object} the new folder.
1476 */
1477 var folderAdd = function(name, createFolders) {
1478 createFolders = (typeof createFolders !== "undefined") ? createFolders : defaults.createFolders;
1479
1480 name = forceTrailingSlash(name);
1481
1482 // Does this folder already exist?
1483 if (!this.files[name]) {
1484 fileAdd.call(this, name, null, {
1485 dir: true,
1486 createFolders: createFolders
1487 });
1488 }
1489 return this.files[name];
1490 };
1491
1492 /**
1493 * Cross-window, cross-Node-context regular expression detection
1494 * @param {Object} object Anything
1495 * @return {Boolean} true if the object is a regular expression,
1496 * false otherwise
1497 */
1498 function isRegExp(object) {
1499 return Object.prototype.toString.call(object) === "[object RegExp]";
1500 }
1501
1502 // return the actual prototype of JSZip
1503 var out = {
1504 /**
1505 * @see loadAsync
1506 */
1507 load: function() {
1508 throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
1509 },
1510
1511
1512 /**
1513 * Call a callback function for each entry at this folder level.
1514 * @param {Function} cb the callback function:
1515 * function (relativePath, file) {...}
1516 * It takes 2 arguments : the relative path and the file.
1517 */
1518 forEach: function(cb) {
1519 var filename, relativePath, file;
1520 // ignore warning about unwanted properties because this.files is a null prototype object
1521 /* eslint-disable-next-line guard-for-in */
1522 for (filename in this.files) {
1523 file = this.files[filename];
1524 relativePath = filename.slice(this.root.length, filename.length);
1525 if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root
1526 cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...
1527 }
1528 }
1529 },
1530
1531 /**
1532 * Filter nested files/folders with the specified function.
1533 * @param {Function} search the predicate to use :
1534 * function (relativePath, file) {...}
1535 * It takes 2 arguments : the relative path and the file.
1536 * @return {Array} An array of matching elements.
1537 */
1538 filter: function(search) {
1539 var result = [];
1540 this.forEach(function (relativePath, entry) {
1541 if (search(relativePath, entry)) { // the file matches the function
1542 result.push(entry);
1543 }
1544
1545 });
1546 return result;
1547 },
1548
1549 /**
1550 * Add a file to the zip file, or search a file.
1551 * @param {string|RegExp} name The name of the file to add (if data is defined),
1552 * the name of the file to find (if no data) or a regex to match files.
1553 * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
1554 * @param {Object} o File options
1555 * @return {JSZip|Object|Array} this JSZip object (when adding a file),
1556 * a file (when searching by string) or an array of files (when searching by regex).
1557 */
1558 file: function(name, data, o) {
1559 if (arguments.length === 1) {
1560 if (isRegExp(name)) {
1561 var regexp = name;
1562 return this.filter(function(relativePath, file) {
1563 return !file.dir && regexp.test(relativePath);
1564 });
1565 }
1566 else { // text
1567 var obj = this.files[this.root + name];
1568 if (obj && !obj.dir) {
1569 return obj;
1570 } else {
1571 return null;
1572 }
1573 }
1574 }
1575 else { // more than one argument : we have data !
1576 name = this.root + name;
1577 fileAdd.call(this, name, data, o);
1578 }
1579 return this;
1580 },
1581
1582 /**
1583 * Add a directory to the zip file, or search.
1584 * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
1585 * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
1586 */
1587 folder: function(arg) {
1588 if (!arg) {
1589 return this;
1590 }
1591
1592 if (isRegExp(arg)) {
1593 return this.filter(function(relativePath, file) {
1594 return file.dir && arg.test(relativePath);
1595 });
1596 }
1597
1598 // else, name is a new folder
1599 var name = this.root + arg;
1600 var newFolder = folderAdd.call(this, name);
1601
1602 // Allow chaining by returning a new object with this folder as the root
1603 var ret = this.clone();
1604 ret.root = newFolder.name;
1605 return ret;
1606 },
1607
1608 /**
1609 * Delete a file, or a directory and all sub-files, from the zip
1610 * @param {string} name the name of the file to delete
1611 * @return {JSZip} this JSZip object
1612 */
1613 remove: function(name) {
1614 name = this.root + name;
1615 var file = this.files[name];
1616 if (!file) {
1617 // Look for any folders
1618 if (name.slice(-1) !== "/") {
1619 name += "/";
1620 }
1621 file = this.files[name];
1622 }
1623
1624 if (file && !file.dir) {
1625 // file
1626 delete this.files[name];
1627 } else {
1628 // maybe a folder, delete recursively
1629 var kids = this.filter(function(relativePath, file) {
1630 return file.name.slice(0, name.length) === name;
1631 });
1632 for (var i = 0; i < kids.length; i++) {
1633 delete this.files[kids[i].name];
1634 }
1635 }
1636
1637 return this;
1638 },
1639
1640 /**
1641 * @deprecated This method has been removed in JSZip 3.0, please check the upgrade guide.
1642 */
1643 generate: function() {
1644 throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
1645 },
1646
1647 /**
1648 * Generate the complete zip file as an internal stream.
1649 * @param {Object} options the options to generate the zip file :
1650 * - compression, "STORE" by default.
1651 * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
1652 * @return {StreamHelper} the streamed zip file.
1653 */
1654 generateInternalStream: function(options) {
1655 var worker, opts = {};
1656 try {
1657 opts = utils.extend(options || {}, {
1658 streamFiles: false,
1659 compression: "STORE",
1660 compressionOptions : null,
1661 type: "",
1662 platform: "DOS",
1663 comment: null,
1664 mimeType: "application/zip",
1665 encodeFileName: utf8.utf8encode
1666 });
1667
1668 opts.type = opts.type.toLowerCase();
1669 opts.compression = opts.compression.toUpperCase();
1670
1671 // "binarystring" is preferred but the internals use "string".
1672 if(opts.type === "binarystring") {
1673 opts.type = "string";
1674 }
1675
1676 if (!opts.type) {
1677 throw new Error("No output type specified.");
1678 }
1679
1680 utils.checkSupport(opts.type);
1681
1682 // accept nodejs `process.platform`
1683 if(
1684 opts.platform === "darwin" ||
1685 opts.platform === "freebsd" ||
1686 opts.platform === "linux" ||
1687 opts.platform === "sunos"
1688 ) {
1689 opts.platform = "UNIX";
1690 }
1691 if (opts.platform === "win32") {
1692 opts.platform = "DOS";
1693 }
1694
1695 var comment = opts.comment || this.comment || "";
1696 worker = generate.generateWorker(this, opts, comment);
1697 } catch (e) {
1698 worker = new GenericWorker("error");
1699 worker.error(e);
1700 }
1701 return new StreamHelper(worker, opts.type || "string", opts.mimeType);
1702 },
1703 /**
1704 * Generate the complete zip file asynchronously.
1705 * @see generateInternalStream
1706 */
1707 generateAsync: function(options, onUpdate) {
1708 return this.generateInternalStream(options).accumulate(onUpdate);
1709 },
1710 /**
1711 * Generate the complete zip file asynchronously.
1712 * @see generateInternalStream
1713 */
1714 generateNodeStream: function(options, onUpdate) {
1715 options = options || {};
1716 if (!options.type) {
1717 options.type = "nodebuffer";
1718 }
1719 return this.generateInternalStream(options).toNodejsStream(onUpdate);
1720 }
1721 };
1722 module.exports = out;
1723
1724 },{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(require,module,exports){
1725 "use strict";
1726 /*
1727 * This file is used by module bundlers (browserify/webpack/etc) when
1728 * including a stream implementation. We use "readable-stream" to get a
1729 * consistent behavior between nodejs versions but bundlers often have a shim
1730 * for "stream". Using this shim greatly improve the compatibility and greatly
1731 * reduce the final size of the bundle (only one stream implementation, not
1732 * two).
1733 */
1734 module.exports = require("stream");
1735
1736 },{"stream":undefined}],17:[function(require,module,exports){
1737 "use strict";
1738 var DataReader = require("./DataReader");
1739 var utils = require("../utils");
1740
1741 function ArrayReader(data) {
1742 DataReader.call(this, data);
1743 for(var i = 0; i < this.data.length; i++) {
1744 data[i] = data[i] & 0xFF;
1745 }
1746 }
1747 utils.inherits(ArrayReader, DataReader);
1748 /**
1749 * @see DataReader.byteAt
1750 */
1751 ArrayReader.prototype.byteAt = function(i) {
1752 return this.data[this.zero + i];
1753 };
1754 /**
1755 * @see DataReader.lastIndexOfSignature
1756 */
1757 ArrayReader.prototype.lastIndexOfSignature = function(sig) {
1758 var sig0 = sig.charCodeAt(0),
1759 sig1 = sig.charCodeAt(1),
1760 sig2 = sig.charCodeAt(2),
1761 sig3 = sig.charCodeAt(3);
1762 for (var i = this.length - 4; i >= 0; --i) {
1763 if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
1764 return i - this.zero;
1765 }
1766 }
1767
1768 return -1;
1769 };
1770 /**
1771 * @see DataReader.readAndCheckSignature
1772 */
1773 ArrayReader.prototype.readAndCheckSignature = function (sig) {
1774 var sig0 = sig.charCodeAt(0),
1775 sig1 = sig.charCodeAt(1),
1776 sig2 = sig.charCodeAt(2),
1777 sig3 = sig.charCodeAt(3),
1778 data = this.readData(4);
1779 return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];
1780 };
1781 /**
1782 * @see DataReader.readData
1783 */
1784 ArrayReader.prototype.readData = function(size) {
1785 this.checkOffset(size);
1786 if(size === 0) {
1787 return [];
1788 }
1789 var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
1790 this.index += size;
1791 return result;
1792 };
1793 module.exports = ArrayReader;
1794
1795 },{"../utils":32,"./DataReader":18}],18:[function(require,module,exports){
1796 "use strict";
1797 var utils = require("../utils");
1798
1799 function DataReader(data) {
1800 this.data = data; // type : see implementation
1801 this.length = data.length;
1802 this.index = 0;
1803 this.zero = 0;
1804 }
1805 DataReader.prototype = {
1806 /**
1807 * Check that the offset will not go too far.
1808 * @param {string} offset the additional offset to check.
1809 * @throws {Error} an Error if the offset is out of bounds.
1810 */
1811 checkOffset: function(offset) {
1812 this.checkIndex(this.index + offset);
1813 },
1814 /**
1815 * Check that the specified index will not be too far.
1816 * @param {string} newIndex the index to check.
1817 * @throws {Error} an Error if the index is out of bounds.
1818 */
1819 checkIndex: function(newIndex) {
1820 if (this.length < this.zero + newIndex || newIndex < 0) {
1821 throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
1822 }
1823 },
1824 /**
1825 * Change the index.
1826 * @param {number} newIndex The new index.
1827 * @throws {Error} if the new index is out of the data.
1828 */
1829 setIndex: function(newIndex) {
1830 this.checkIndex(newIndex);
1831 this.index = newIndex;
1832 },
1833 /**
1834 * Skip the next n bytes.
1835 * @param {number} n the number of bytes to skip.
1836 * @throws {Error} if the new index is out of the data.
1837 */
1838 skip: function(n) {
1839 this.setIndex(this.index + n);
1840 },
1841 /**
1842 * Get the byte at the specified index.
1843 * @param {number} i the index to use.
1844 * @return {number} a byte.
1845 */
1846 byteAt: function() {
1847 // see implementations
1848 },
1849 /**
1850 * Get the next number with a given byte size.
1851 * @param {number} size the number of bytes to read.
1852 * @return {number} the corresponding number.
1853 */
1854 readInt: function(size) {
1855 var result = 0,
1856 i;
1857 this.checkOffset(size);
1858 for (i = this.index + size - 1; i >= this.index; i--) {
1859 result = (result << 8) + this.byteAt(i);
1860 }
1861 this.index += size;
1862 return result;
1863 },
1864 /**
1865 * Get the next string with a given byte size.
1866 * @param {number} size the number of bytes to read.
1867 * @return {string} the corresponding string.
1868 */
1869 readString: function(size) {
1870 return utils.transformTo("string", this.readData(size));
1871 },
1872 /**
1873 * Get raw data without conversion, <size> bytes.
1874 * @param {number} size the number of bytes to read.
1875 * @return {Object} the raw data, implementation specific.
1876 */
1877 readData: function() {
1878 // see implementations
1879 },
1880 /**
1881 * Find the last occurrence of a zip signature (4 bytes).
1882 * @param {string} sig the signature to find.
1883 * @return {number} the index of the last occurrence, -1 if not found.
1884 */
1885 lastIndexOfSignature: function() {
1886 // see implementations
1887 },
1888 /**
1889 * Read the signature (4 bytes) at the current position and compare it with sig.
1890 * @param {string} sig the expected signature
1891 * @return {boolean} true if the signature matches, false otherwise.
1892 */
1893 readAndCheckSignature: function() {
1894 // see implementations
1895 },
1896 /**
1897 * Get the next date.
1898 * @return {Date} the date.
1899 */
1900 readDate: function() {
1901 var dostime = this.readInt(4);
1902 return new Date(Date.UTC(
1903 ((dostime >> 25) & 0x7f) + 1980, // year
1904 ((dostime >> 21) & 0x0f) - 1, // month
1905 (dostime >> 16) & 0x1f, // day
1906 (dostime >> 11) & 0x1f, // hour
1907 (dostime >> 5) & 0x3f, // minute
1908 (dostime & 0x1f) << 1)); // second
1909 }
1910 };
1911 module.exports = DataReader;
1912
1913 },{"../utils":32}],19:[function(require,module,exports){
1914 "use strict";
1915 var Uint8ArrayReader = require("./Uint8ArrayReader");
1916 var utils = require("../utils");
1917
1918 function NodeBufferReader(data) {
1919 Uint8ArrayReader.call(this, data);
1920 }
1921 utils.inherits(NodeBufferReader, Uint8ArrayReader);
1922
1923 /**
1924 * @see DataReader.readData
1925 */
1926 NodeBufferReader.prototype.readData = function(size) {
1927 this.checkOffset(size);
1928 var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
1929 this.index += size;
1930 return result;
1931 };
1932 module.exports = NodeBufferReader;
1933
1934 },{"../utils":32,"./Uint8ArrayReader":21}],20:[function(require,module,exports){
1935 "use strict";
1936 var DataReader = require("./DataReader");
1937 var utils = require("../utils");
1938
1939 function StringReader(data) {
1940 DataReader.call(this, data);
1941 }
1942 utils.inherits(StringReader, DataReader);
1943 /**
1944 * @see DataReader.byteAt
1945 */
1946 StringReader.prototype.byteAt = function(i) {
1947 return this.data.charCodeAt(this.zero + i);
1948 };
1949 /**
1950 * @see DataReader.lastIndexOfSignature
1951 */
1952 StringReader.prototype.lastIndexOfSignature = function(sig) {
1953 return this.data.lastIndexOf(sig) - this.zero;
1954 };
1955 /**
1956 * @see DataReader.readAndCheckSignature
1957 */
1958 StringReader.prototype.readAndCheckSignature = function (sig) {
1959 var data = this.readData(4);
1960 return sig === data;
1961 };
1962 /**
1963 * @see DataReader.readData
1964 */
1965 StringReader.prototype.readData = function(size) {
1966 this.checkOffset(size);
1967 // this will work because the constructor applied the "& 0xff" mask.
1968 var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
1969 this.index += size;
1970 return result;
1971 };
1972 module.exports = StringReader;
1973
1974 },{"../utils":32,"./DataReader":18}],21:[function(require,module,exports){
1975 "use strict";
1976 var ArrayReader = require("./ArrayReader");
1977 var utils = require("../utils");
1978
1979 function Uint8ArrayReader(data) {
1980 ArrayReader.call(this, data);
1981 }
1982 utils.inherits(Uint8ArrayReader, ArrayReader);
1983 /**
1984 * @see DataReader.readData
1985 */
1986 Uint8ArrayReader.prototype.readData = function(size) {
1987 this.checkOffset(size);
1988 if(size === 0) {
1989 // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
1990 return new Uint8Array(0);
1991 }
1992 var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
1993 this.index += size;
1994 return result;
1995 };
1996 module.exports = Uint8ArrayReader;
1997
1998 },{"../utils":32,"./ArrayReader":17}],22:[function(require,module,exports){
1999 "use strict";
2000
2001 var utils = require("../utils");
2002 var support = require("../support");
2003 var ArrayReader = require("./ArrayReader");
2004 var StringReader = require("./StringReader");
2005 var NodeBufferReader = require("./NodeBufferReader");
2006 var Uint8ArrayReader = require("./Uint8ArrayReader");
2007
2008 /**
2009 * Create a reader adapted to the data.
2010 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.
2011 * @return {DataReader} the data reader.
2012 */
2013 module.exports = function (data) {
2014 var type = utils.getTypeOf(data);
2015 utils.checkSupport(type);
2016 if (type === "string" && !support.uint8array) {
2017 return new StringReader(data);
2018 }
2019 if (type === "nodebuffer") {
2020 return new NodeBufferReader(data);
2021 }
2022 if (support.uint8array) {
2023 return new Uint8ArrayReader(utils.transformTo("uint8array", data));
2024 }
2025 return new ArrayReader(utils.transformTo("array", data));
2026 };
2027
2028 },{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(require,module,exports){
2029 "use strict";
2030 exports.LOCAL_FILE_HEADER = "PK\x03\x04";
2031 exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
2032 exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
2033 exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
2034 exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
2035 exports.DATA_DESCRIPTOR = "PK\x07\x08";
2036
2037 },{}],24:[function(require,module,exports){
2038 "use strict";
2039
2040 var GenericWorker = require("./GenericWorker");
2041 var utils = require("../utils");
2042
2043 /**
2044 * A worker which convert chunks to a specified type.
2045 * @constructor
2046 * @param {String} destType the destination type.
2047 */
2048 function ConvertWorker(destType) {
2049 GenericWorker.call(this, "ConvertWorker to " + destType);
2050 this.destType = destType;
2051 }
2052 utils.inherits(ConvertWorker, GenericWorker);
2053
2054 /**
2055 * @see GenericWorker.processChunk
2056 */
2057 ConvertWorker.prototype.processChunk = function (chunk) {
2058 this.push({
2059 data : utils.transformTo(this.destType, chunk.data),
2060 meta : chunk.meta
2061 });
2062 };
2063 module.exports = ConvertWorker;
2064
2065 },{"../utils":32,"./GenericWorker":28}],25:[function(require,module,exports){
2066 "use strict";
2067
2068 var GenericWorker = require("./GenericWorker");
2069 var crc32 = require("../crc32");
2070 var utils = require("../utils");
2071
2072 /**
2073 * A worker which calculate the crc32 of the data flowing through.
2074 * @constructor
2075 */
2076 function Crc32Probe() {
2077 GenericWorker.call(this, "Crc32Probe");
2078 this.withStreamInfo("crc32", 0);
2079 }
2080 utils.inherits(Crc32Probe, GenericWorker);
2081
2082 /**
2083 * @see GenericWorker.processChunk
2084 */
2085 Crc32Probe.prototype.processChunk = function (chunk) {
2086 this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);
2087 this.push(chunk);
2088 };
2089 module.exports = Crc32Probe;
2090
2091 },{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(require,module,exports){
2092 "use strict";
2093
2094 var utils = require("../utils");
2095 var GenericWorker = require("./GenericWorker");
2096
2097 /**
2098 * A worker which calculate the total length of the data flowing through.
2099 * @constructor
2100 * @param {String} propName the name used to expose the length
2101 */
2102 function DataLengthProbe(propName) {
2103 GenericWorker.call(this, "DataLengthProbe for " + propName);
2104 this.propName = propName;
2105 this.withStreamInfo(propName, 0);
2106 }
2107 utils.inherits(DataLengthProbe, GenericWorker);
2108
2109 /**
2110 * @see GenericWorker.processChunk
2111 */
2112 DataLengthProbe.prototype.processChunk = function (chunk) {
2113 if(chunk) {
2114 var length = this.streamInfo[this.propName] || 0;
2115 this.streamInfo[this.propName] = length + chunk.data.length;
2116 }
2117 GenericWorker.prototype.processChunk.call(this, chunk);
2118 };
2119 module.exports = DataLengthProbe;
2120
2121
2122 },{"../utils":32,"./GenericWorker":28}],27:[function(require,module,exports){
2123 "use strict";
2124
2125 var utils = require("../utils");
2126 var GenericWorker = require("./GenericWorker");
2127
2128 // the size of the generated chunks
2129 // TODO expose this as a public variable
2130 var DEFAULT_BLOCK_SIZE = 16 * 1024;
2131
2132 /**
2133 * A worker that reads a content and emits chunks.
2134 * @constructor
2135 * @param {Promise} dataP the promise of the data to split
2136 */
2137 function DataWorker(dataP) {
2138 GenericWorker.call(this, "DataWorker");
2139 var self = this;
2140 this.dataIsReady = false;
2141 this.index = 0;
2142 this.max = 0;
2143 this.data = null;
2144 this.type = "";
2145
2146 this._tickScheduled = false;
2147
2148 dataP.then(function (data) {
2149 self.dataIsReady = true;
2150 self.data = data;
2151 self.max = data && data.length || 0;
2152 self.type = utils.getTypeOf(data);
2153 if(!self.isPaused) {
2154 self._tickAndRepeat();
2155 }
2156 }, function (e) {
2157 self.error(e);
2158 });
2159 }
2160
2161 utils.inherits(DataWorker, GenericWorker);
2162
2163 /**
2164 * @see GenericWorker.cleanUp
2165 */
2166 DataWorker.prototype.cleanUp = function () {
2167 GenericWorker.prototype.cleanUp.call(this);
2168 this.data = null;
2169 };
2170
2171 /**
2172 * @see GenericWorker.resume
2173 */
2174 DataWorker.prototype.resume = function () {
2175 if(!GenericWorker.prototype.resume.call(this)) {
2176 return false;
2177 }
2178
2179 if (!this._tickScheduled && this.dataIsReady) {
2180 this._tickScheduled = true;
2181 utils.delay(this._tickAndRepeat, [], this);
2182 }
2183 return true;
2184 };
2185
2186 /**
2187 * Trigger a tick a schedule an other call to this function.
2188 */
2189 DataWorker.prototype._tickAndRepeat = function() {
2190 this._tickScheduled = false;
2191 if(this.isPaused || this.isFinished) {
2192 return;
2193 }
2194 this._tick();
2195 if(!this.isFinished) {
2196 utils.delay(this._tickAndRepeat, [], this);
2197 this._tickScheduled = true;
2198 }
2199 };
2200
2201 /**
2202 * Read and push a chunk.
2203 */
2204 DataWorker.prototype._tick = function() {
2205
2206 if(this.isPaused || this.isFinished) {
2207 return false;
2208 }
2209
2210 var size = DEFAULT_BLOCK_SIZE;
2211 var data = null, nextIndex = Math.min(this.max, this.index + size);
2212 if (this.index >= this.max) {
2213 // EOF
2214 return this.end();
2215 } else {
2216 switch(this.type) {
2217 case "string":
2218 data = this.data.substring(this.index, nextIndex);
2219 break;
2220 case "uint8array":
2221 data = this.data.subarray(this.index, nextIndex);
2222 break;
2223 case "array":
2224 case "nodebuffer":
2225 data = this.data.slice(this.index, nextIndex);
2226 break;
2227 }
2228 this.index = nextIndex;
2229 return this.push({
2230 data : data,
2231 meta : {
2232 percent : this.max ? this.index / this.max * 100 : 0
2233 }
2234 });
2235 }
2236 };
2237
2238 module.exports = DataWorker;
2239
2240 },{"../utils":32,"./GenericWorker":28}],28:[function(require,module,exports){
2241 "use strict";
2242
2243 /**
2244 * A worker that does nothing but passing chunks to the next one. This is like
2245 * a nodejs stream but with some differences. On the good side :
2246 * - it works on IE 6-9 without any issue / polyfill
2247 * - it weights less than the full dependencies bundled with browserify
2248 * - it forwards errors (no need to declare an error handler EVERYWHERE)
2249 *
2250 * A chunk is an object with 2 attributes : `meta` and `data`. The former is an
2251 * object containing anything (`percent` for example), see each worker for more
2252 * details. The latter is the real data (String, Uint8Array, etc).
2253 *
2254 * @constructor
2255 * @param {String} name the name of the stream (mainly used for debugging purposes)
2256 */
2257 function GenericWorker(name) {
2258 // the name of the worker
2259 this.name = name || "default";
2260 // an object containing metadata about the workers chain
2261 this.streamInfo = {};
2262 // an error which happened when the worker was paused
2263 this.generatedError = null;
2264 // an object containing metadata to be merged by this worker into the general metadata
2265 this.extraStreamInfo = {};
2266 // true if the stream is paused (and should not do anything), false otherwise
2267 this.isPaused = true;
2268 // true if the stream is finished (and should not do anything), false otherwise
2269 this.isFinished = false;
2270 // true if the stream is locked to prevent further structure updates (pipe), false otherwise
2271 this.isLocked = false;
2272 // the event listeners
2273 this._listeners = {
2274 "data":[],
2275 "end":[],
2276 "error":[]
2277 };
2278 // the previous worker, if any
2279 this.previous = null;
2280 }
2281
2282 GenericWorker.prototype = {
2283 /**
2284 * Push a chunk to the next workers.
2285 * @param {Object} chunk the chunk to push
2286 */
2287 push : function (chunk) {
2288 this.emit("data", chunk);
2289 },
2290 /**
2291 * End the stream.
2292 * @return {Boolean} true if this call ended the worker, false otherwise.
2293 */
2294 end : function () {
2295 if (this.isFinished) {
2296 return false;
2297 }
2298
2299 this.flush();
2300 try {
2301 this.emit("end");
2302 this.cleanUp();
2303 this.isFinished = true;
2304 } catch (e) {
2305 this.emit("error", e);
2306 }
2307 return true;
2308 },
2309 /**
2310 * End the stream with an error.
2311 * @param {Error} e the error which caused the premature end.
2312 * @return {Boolean} true if this call ended the worker with an error, false otherwise.
2313 */
2314 error : function (e) {
2315 if (this.isFinished) {
2316 return false;
2317 }
2318
2319 if(this.isPaused) {
2320 this.generatedError = e;
2321 } else {
2322 this.isFinished = true;
2323
2324 this.emit("error", e);
2325
2326 // in the workers chain exploded in the middle of the chain,
2327 // the error event will go downward but we also need to notify
2328 // workers upward that there has been an error.
2329 if(this.previous) {
2330 this.previous.error(e);
2331 }
2332
2333 this.cleanUp();
2334 }
2335 return true;
2336 },
2337 /**
2338 * Add a callback on an event.
2339 * @param {String} name the name of the event (data, end, error)
2340 * @param {Function} listener the function to call when the event is triggered
2341 * @return {GenericWorker} the current object for chainability
2342 */
2343 on : function (name, listener) {
2344 this._listeners[name].push(listener);
2345 return this;
2346 },
2347 /**
2348 * Clean any references when a worker is ending.
2349 */
2350 cleanUp : function () {
2351 this.streamInfo = this.generatedError = this.extraStreamInfo = null;
2352 this._listeners = [];
2353 },
2354 /**
2355 * Trigger an event. This will call registered callback with the provided arg.
2356 * @param {String} name the name of the event (data, end, error)
2357 * @param {Object} arg the argument to call the callback with.
2358 */
2359 emit : function (name, arg) {
2360 if (this._listeners[name]) {
2361 for(var i = 0; i < this._listeners[name].length; i++) {
2362 this._listeners[name][i].call(this, arg);
2363 }
2364 }
2365 },
2366 /**
2367 * Chain a worker with an other.
2368 * @param {Worker} next the worker receiving events from the current one.
2369 * @return {worker} the next worker for chainability
2370 */
2371 pipe : function (next) {
2372 return next.registerPrevious(this);
2373 },
2374 /**
2375 * Same as `pipe` in the other direction.
2376 * Using an API with `pipe(next)` is very easy.
2377 * Implementing the API with the point of view of the next one registering
2378 * a source is easier, see the ZipFileWorker.
2379 * @param {Worker} previous the previous worker, sending events to this one
2380 * @return {Worker} the current worker for chainability
2381 */
2382 registerPrevious : function (previous) {
2383 if (this.isLocked) {
2384 throw new Error("The stream '" + this + "' has already been used.");
2385 }
2386
2387 // sharing the streamInfo...
2388 this.streamInfo = previous.streamInfo;
2389 // ... and adding our own bits
2390 this.mergeStreamInfo();
2391 this.previous = previous;
2392 var self = this;
2393 previous.on("data", function (chunk) {
2394 self.processChunk(chunk);
2395 });
2396 previous.on("end", function () {
2397 self.end();
2398 });
2399 previous.on("error", function (e) {
2400 self.error(e);
2401 });
2402 return this;
2403 },
2404 /**
2405 * Pause the stream so it doesn't send events anymore.
2406 * @return {Boolean} true if this call paused the worker, false otherwise.
2407 */
2408 pause : function () {
2409 if(this.isPaused || this.isFinished) {
2410 return false;
2411 }
2412 this.isPaused = true;
2413
2414 if(this.previous) {
2415 this.previous.pause();
2416 }
2417 return true;
2418 },
2419 /**
2420 * Resume a paused stream.
2421 * @return {Boolean} true if this call resumed the worker, false otherwise.
2422 */
2423 resume : function () {
2424 if(!this.isPaused || this.isFinished) {
2425 return false;
2426 }
2427 this.isPaused = false;
2428
2429 // if true, the worker tried to resume but failed
2430 var withError = false;
2431 if(this.generatedError) {
2432 this.error(this.generatedError);
2433 withError = true;
2434 }
2435 if(this.previous) {
2436 this.previous.resume();
2437 }
2438
2439 return !withError;
2440 },
2441 /**
2442 * Flush any remaining bytes as the stream is ending.
2443 */
2444 flush : function () {},
2445 /**
2446 * Process a chunk. This is usually the method overridden.
2447 * @param {Object} chunk the chunk to process.
2448 */
2449 processChunk : function(chunk) {
2450 this.push(chunk);
2451 },
2452 /**
2453 * Add a key/value to be added in the workers chain streamInfo once activated.
2454 * @param {String} key the key to use
2455 * @param {Object} value the associated value
2456 * @return {Worker} the current worker for chainability
2457 */
2458 withStreamInfo : function (key, value) {
2459 this.extraStreamInfo[key] = value;
2460 this.mergeStreamInfo();
2461 return this;
2462 },
2463 /**
2464 * Merge this worker's streamInfo into the chain's streamInfo.
2465 */
2466 mergeStreamInfo : function () {
2467 for(var key in this.extraStreamInfo) {
2468 if (!Object.prototype.hasOwnProperty.call(this.extraStreamInfo, key)) {
2469 continue;
2470 }
2471 this.streamInfo[key] = this.extraStreamInfo[key];
2472 }
2473 },
2474
2475 /**
2476 * Lock the stream to prevent further updates on the workers chain.
2477 * After calling this method, all calls to pipe will fail.
2478 */
2479 lock: function () {
2480 if (this.isLocked) {
2481 throw new Error("The stream '" + this + "' has already been used.");
2482 }
2483 this.isLocked = true;
2484 if (this.previous) {
2485 this.previous.lock();
2486 }
2487 },
2488
2489 /**
2490 *
2491 * Pretty print the workers chain.
2492 */
2493 toString : function () {
2494 var me = "Worker " + this.name;
2495 if (this.previous) {
2496 return this.previous + " -> " + me;
2497 } else {
2498 return me;
2499 }
2500 }
2501 };
2502
2503 module.exports = GenericWorker;
2504
2505 },{}],29:[function(require,module,exports){
2506 "use strict";
2507
2508 var utils = require("../utils");
2509 var ConvertWorker = require("./ConvertWorker");
2510 var GenericWorker = require("./GenericWorker");
2511 var base64 = require("../base64");
2512 var support = require("../support");
2513 var external = require("../external");
2514
2515 var NodejsStreamOutputAdapter = null;
2516 if (support.nodestream) {
2517 try {
2518 NodejsStreamOutputAdapter = require("../nodejs/NodejsStreamOutputAdapter");
2519 } catch(e) {
2520 // ignore
2521 }
2522 }
2523
2524 /**
2525 * Apply the final transformation of the data. If the user wants a Blob for
2526 * example, it's easier to work with an U8intArray and finally do the
2527 * ArrayBuffer/Blob conversion.
2528 * @param {String} type the name of the final type
2529 * @param {String|Uint8Array|Buffer} content the content to transform
2530 * @param {String} mimeType the mime type of the content, if applicable.
2531 * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.
2532 */
2533 function transformZipOutput(type, content, mimeType) {
2534 switch(type) {
2535 case "blob" :
2536 return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType);
2537 case "base64" :
2538 return base64.encode(content);
2539 default :
2540 return utils.transformTo(type, content);
2541 }
2542 }
2543
2544 /**
2545 * Concatenate an array of data of the given type.
2546 * @param {String} type the type of the data in the given array.
2547 * @param {Array} dataArray the array containing the data chunks to concatenate
2548 * @return {String|Uint8Array|Buffer} the concatenated data
2549 * @throws Error if the asked type is unsupported
2550 */
2551 function concat (type, dataArray) {
2552 var i, index = 0, res = null, totalLength = 0;
2553 for(i = 0; i < dataArray.length; i++) {
2554 totalLength += dataArray[i].length;
2555 }
2556 switch(type) {
2557 case "string":
2558 return dataArray.join("");
2559 case "array":
2560 return Array.prototype.concat.apply([], dataArray);
2561 case "uint8array":
2562 res = new Uint8Array(totalLength);
2563 for(i = 0; i < dataArray.length; i++) {
2564 res.set(dataArray[i], index);
2565 index += dataArray[i].length;
2566 }
2567 return res;
2568 case "nodebuffer":
2569 return Buffer.concat(dataArray);
2570 default:
2571 throw new Error("concat : unsupported type '" + type + "'");
2572 }
2573 }
2574
2575 /**
2576 * Listen a StreamHelper, accumulate its content and concatenate it into a
2577 * complete block.
2578 * @param {StreamHelper} helper the helper to use.
2579 * @param {Function} updateCallback a callback called on each update. Called
2580 * with one arg :
2581 * - the metadata linked to the update received.
2582 * @return Promise the promise for the accumulation.
2583 */
2584 function accumulate(helper, updateCallback) {
2585 return new external.Promise(function (resolve, reject){
2586 var dataArray = [];
2587 var chunkType = helper._internalType,
2588 resultType = helper._outputType,
2589 mimeType = helper._mimeType;
2590 helper
2591 .on("data", function (data, meta) {
2592 dataArray.push(data);
2593 if(updateCallback) {
2594 updateCallback(meta);
2595 }
2596 })
2597 .on("error", function(err) {
2598 dataArray = [];
2599 reject(err);
2600 })
2601 .on("end", function (){
2602 try {
2603 var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType);
2604 resolve(result);
2605 } catch (e) {
2606 reject(e);
2607 }
2608 dataArray = [];
2609 })
2610 .resume();
2611 });
2612 }
2613
2614 /**
2615 * An helper to easily use workers outside of JSZip.
2616 * @constructor
2617 * @param {Worker} worker the worker to wrap
2618 * @param {String} outputType the type of data expected by the use
2619 * @param {String} mimeType the mime type of the content, if applicable.
2620 */
2621 function StreamHelper(worker, outputType, mimeType) {
2622 var internalType = outputType;
2623 switch(outputType) {
2624 case "blob":
2625 case "arraybuffer":
2626 internalType = "uint8array";
2627 break;
2628 case "base64":
2629 internalType = "string";
2630 break;
2631 }
2632
2633 try {
2634 // the type used internally
2635 this._internalType = internalType;
2636 // the type used to output results
2637 this._outputType = outputType;
2638 // the mime type
2639 this._mimeType = mimeType;
2640 utils.checkSupport(internalType);
2641 this._worker = worker.pipe(new ConvertWorker(internalType));
2642 // the last workers can be rewired without issues but we need to
2643 // prevent any updates on previous workers.
2644 worker.lock();
2645 } catch(e) {
2646 this._worker = new GenericWorker("error");
2647 this._worker.error(e);
2648 }
2649 }
2650
2651 StreamHelper.prototype = {
2652 /**
2653 * Listen a StreamHelper, accumulate its content and concatenate it into a
2654 * complete block.
2655 * @param {Function} updateCb the update callback.
2656 * @return Promise the promise for the accumulation.
2657 */
2658 accumulate : function (updateCb) {
2659 return accumulate(this, updateCb);
2660 },
2661 /**
2662 * Add a listener on an event triggered on a stream.
2663 * @param {String} evt the name of the event
2664 * @param {Function} fn the listener
2665 * @return {StreamHelper} the current helper.
2666 */
2667 on : function (evt, fn) {
2668 var self = this;
2669
2670 if(evt === "data") {
2671 this._worker.on(evt, function (chunk) {
2672 fn.call(self, chunk.data, chunk.meta);
2673 });
2674 } else {
2675 this._worker.on(evt, function () {
2676 utils.delay(fn, arguments, self);
2677 });
2678 }
2679 return this;
2680 },
2681 /**
2682 * Resume the flow of chunks.
2683 * @return {StreamHelper} the current helper.
2684 */
2685 resume : function () {
2686 utils.delay(this._worker.resume, [], this._worker);
2687 return this;
2688 },
2689 /**
2690 * Pause the flow of chunks.
2691 * @return {StreamHelper} the current helper.
2692 */
2693 pause : function () {
2694 this._worker.pause();
2695 return this;
2696 },
2697 /**
2698 * Return a nodejs stream for this helper.
2699 * @param {Function} updateCb the update callback.
2700 * @return {NodejsStreamOutputAdapter} the nodejs stream.
2701 */
2702 toNodejsStream : function (updateCb) {
2703 utils.checkSupport("nodestream");
2704 if (this._outputType !== "nodebuffer") {
2705 // an object stream containing blob/arraybuffer/uint8array/string
2706 // is strange and I don't know if it would be useful.
2707 // I you find this comment and have a good usecase, please open a
2708 // bug report !
2709 throw new Error(this._outputType + " is not supported by this method");
2710 }
2711
2712 return new NodejsStreamOutputAdapter(this, {
2713 objectMode : this._outputType !== "nodebuffer"
2714 }, updateCb);
2715 }
2716 };
2717
2718
2719 module.exports = StreamHelper;
2720
2721 },{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(require,module,exports){
2722 "use strict";
2723
2724 exports.base64 = true;
2725 exports.array = true;
2726 exports.string = true;
2727 exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
2728 exports.nodebuffer = typeof Buffer !== "undefined";
2729 // contains true if JSZip can read/generate Uint8Array, false otherwise.
2730 exports.uint8array = typeof Uint8Array !== "undefined";
2731
2732 if (typeof ArrayBuffer === "undefined") {
2733 exports.blob = false;
2734 }
2735 else {
2736 var buffer = new ArrayBuffer(0);
2737 try {
2738 exports.blob = new Blob([buffer], {
2739 type: "application/zip"
2740 }).size === 0;
2741 }
2742 catch (e) {
2743 try {
2744 var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
2745 var builder = new Builder();
2746 builder.append(buffer);
2747 exports.blob = builder.getBlob("application/zip").size === 0;
2748 }
2749 catch (e) {
2750 exports.blob = false;
2751 }
2752 }
2753 }
2754
2755 try {
2756 exports.nodestream = !!require("readable-stream").Readable;
2757 } catch(e) {
2758 exports.nodestream = false;
2759 }
2760
2761 },{"readable-stream":16}],31:[function(require,module,exports){
2762 "use strict";
2763
2764 var utils = require("./utils");
2765 var support = require("./support");
2766 var nodejsUtils = require("./nodejsUtils");
2767 var GenericWorker = require("./stream/GenericWorker");
2768
2769 /**
2770 * The following functions come from pako, from pako/lib/utils/strings
2771 * released under the MIT license, see pako https://github.com/nodeca/pako/
2772 */
2773
2774 // Table with utf8 lengths (calculated by first byte of sequence)
2775 // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
2776 // because max possible codepoint is 0x10ffff
2777 var _utf8len = new Array(256);
2778 for (var i=0; i<256; i++) {
2779 _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
2780 }
2781 _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
2782
2783 // convert string to array (typed, when possible)
2784 var string2buf = function (str) {
2785 var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
2786
2787 // count binary size
2788 for (m_pos = 0; m_pos < str_len; m_pos++) {
2789 c = str.charCodeAt(m_pos);
2790 if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
2791 c2 = str.charCodeAt(m_pos+1);
2792 if ((c2 & 0xfc00) === 0xdc00) {
2793 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
2794 m_pos++;
2795 }
2796 }
2797 buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
2798 }
2799
2800 // allocate buffer
2801 if (support.uint8array) {
2802 buf = new Uint8Array(buf_len);
2803 } else {
2804 buf = new Array(buf_len);
2805 }
2806
2807 // convert
2808 for (i=0, m_pos = 0; i < buf_len; m_pos++) {
2809 c = str.charCodeAt(m_pos);
2810 if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
2811 c2 = str.charCodeAt(m_pos+1);
2812 if ((c2 & 0xfc00) === 0xdc00) {
2813 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
2814 m_pos++;
2815 }
2816 }
2817 if (c < 0x80) {
2818 /* one byte */
2819 buf[i++] = c;
2820 } else if (c < 0x800) {
2821 /* two bytes */
2822 buf[i++] = 0xC0 | (c >>> 6);
2823 buf[i++] = 0x80 | (c & 0x3f);
2824 } else if (c < 0x10000) {
2825 /* three bytes */
2826 buf[i++] = 0xE0 | (c >>> 12);
2827 buf[i++] = 0x80 | (c >>> 6 & 0x3f);
2828 buf[i++] = 0x80 | (c & 0x3f);
2829 } else {
2830 /* four bytes */
2831 buf[i++] = 0xf0 | (c >>> 18);
2832 buf[i++] = 0x80 | (c >>> 12 & 0x3f);
2833 buf[i++] = 0x80 | (c >>> 6 & 0x3f);
2834 buf[i++] = 0x80 | (c & 0x3f);
2835 }
2836 }
2837
2838 return buf;
2839 };
2840
2841 // Calculate max possible position in utf8 buffer,
2842 // that will not break sequence. If that's not possible
2843 // - (very small limits) return max size as is.
2844 //
2845 // buf[] - utf8 bytes array
2846 // max - length limit (mandatory);
2847 var utf8border = function(buf, max) {
2848 var pos;
2849
2850 max = max || buf.length;
2851 if (max > buf.length) { max = buf.length; }
2852
2853 // go back from last position, until start of sequence found
2854 pos = max-1;
2855 while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
2856
2857 // Fuckup - very small and broken sequence,
2858 // return max, because we should return something anyway.
2859 if (pos < 0) { return max; }
2860
2861 // If we came to start of buffer - that means vuffer is too small,
2862 // return max too.
2863 if (pos === 0) { return max; }
2864
2865 return (pos + _utf8len[buf[pos]] > max) ? pos : max;
2866 };
2867
2868 // convert array to string
2869 var buf2string = function (buf) {
2870 var i, out, c, c_len;
2871 var len = buf.length;
2872
2873 // Reserve max possible length (2 words per char)
2874 // NB: by unknown reasons, Array is significantly faster for
2875 // String.fromCharCode.apply than Uint16Array.
2876 var utf16buf = new Array(len*2);
2877
2878 for (out=0, i=0; i<len;) {
2879 c = buf[i++];
2880 // quick process ascii
2881 if (c < 0x80) { utf16buf[out++] = c; continue; }
2882
2883 c_len = _utf8len[c];
2884 // skip 5 & 6 byte codes
2885 if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
2886
2887 // apply mask on first byte
2888 c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
2889 // join the rest
2890 while (c_len > 1 && i < len) {
2891 c = (c << 6) | (buf[i++] & 0x3f);
2892 c_len--;
2893 }
2894
2895 // terminated by end of string?
2896 if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
2897
2898 if (c < 0x10000) {
2899 utf16buf[out++] = c;
2900 } else {
2901 c -= 0x10000;
2902 utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
2903 utf16buf[out++] = 0xdc00 | (c & 0x3ff);
2904 }
2905 }
2906
2907 // shrinkBuf(utf16buf, out)
2908 if (utf16buf.length !== out) {
2909 if(utf16buf.subarray) {
2910 utf16buf = utf16buf.subarray(0, out);
2911 } else {
2912 utf16buf.length = out;
2913 }
2914 }
2915
2916 // return String.fromCharCode.apply(null, utf16buf);
2917 return utils.applyFromCharCode(utf16buf);
2918 };
2919
2920
2921 // That's all for the pako functions.
2922
2923
2924 /**
2925 * Transform a javascript string into an array (typed if possible) of bytes,
2926 * UTF-8 encoded.
2927 * @param {String} str the string to encode
2928 * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
2929 */
2930 exports.utf8encode = function utf8encode(str) {
2931 if (support.nodebuffer) {
2932 return nodejsUtils.newBufferFrom(str, "utf-8");
2933 }
2934
2935 return string2buf(str);
2936 };
2937
2938
2939 /**
2940 * Transform a bytes array (or a representation) representing an UTF-8 encoded
2941 * string into a javascript string.
2942 * @param {Array|Uint8Array|Buffer} buf the data de decode
2943 * @return {String} the decoded string.
2944 */
2945 exports.utf8decode = function utf8decode(buf) {
2946 if (support.nodebuffer) {
2947 return utils.transformTo("nodebuffer", buf).toString("utf-8");
2948 }
2949
2950 buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
2951
2952 return buf2string(buf);
2953 };
2954
2955 /**
2956 * A worker to decode utf8 encoded binary chunks into string chunks.
2957 * @constructor
2958 */
2959 function Utf8DecodeWorker() {
2960 GenericWorker.call(this, "utf-8 decode");
2961 // the last bytes if a chunk didn't end with a complete codepoint.
2962 this.leftOver = null;
2963 }
2964 utils.inherits(Utf8DecodeWorker, GenericWorker);
2965
2966 /**
2967 * @see GenericWorker.processChunk
2968 */
2969 Utf8DecodeWorker.prototype.processChunk = function (chunk) {
2970
2971 var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data);
2972
2973 // 1st step, re-use what's left of the previous chunk
2974 if (this.leftOver && this.leftOver.length) {
2975 if(support.uint8array) {
2976 var previousData = data;
2977 data = new Uint8Array(previousData.length + this.leftOver.length);
2978 data.set(this.leftOver, 0);
2979 data.set(previousData, this.leftOver.length);
2980 } else {
2981 data = this.leftOver.concat(data);
2982 }
2983 this.leftOver = null;
2984 }
2985
2986 var nextBoundary = utf8border(data);
2987 var usableData = data;
2988 if (nextBoundary !== data.length) {
2989 if (support.uint8array) {
2990 usableData = data.subarray(0, nextBoundary);
2991 this.leftOver = data.subarray(nextBoundary, data.length);
2992 } else {
2993 usableData = data.slice(0, nextBoundary);
2994 this.leftOver = data.slice(nextBoundary, data.length);
2995 }
2996 }
2997
2998 this.push({
2999 data : exports.utf8decode(usableData),
3000 meta : chunk.meta
3001 });
3002 };
3003
3004 /**
3005 * @see GenericWorker.flush
3006 */
3007 Utf8DecodeWorker.prototype.flush = function () {
3008 if(this.leftOver && this.leftOver.length) {
3009 this.push({
3010 data : exports.utf8decode(this.leftOver),
3011 meta : {}
3012 });
3013 this.leftOver = null;
3014 }
3015 };
3016 exports.Utf8DecodeWorker = Utf8DecodeWorker;
3017
3018 /**
3019 * A worker to endcode string chunks into utf8 encoded binary chunks.
3020 * @constructor
3021 */
3022 function Utf8EncodeWorker() {
3023 GenericWorker.call(this, "utf-8 encode");
3024 }
3025 utils.inherits(Utf8EncodeWorker, GenericWorker);
3026
3027 /**
3028 * @see GenericWorker.processChunk
3029 */
3030 Utf8EncodeWorker.prototype.processChunk = function (chunk) {
3031 this.push({
3032 data : exports.utf8encode(chunk.data),
3033 meta : chunk.meta
3034 });
3035 };
3036 exports.Utf8EncodeWorker = Utf8EncodeWorker;
3037
3038 },{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(require,module,exports){
3039 "use strict";
3040
3041 var support = require("./support");
3042 var base64 = require("./base64");
3043 var nodejsUtils = require("./nodejsUtils");
3044 var external = require("./external");
3045 require("setimmediate");
3046
3047
3048 /**
3049 * Convert a string that pass as a "binary string": it should represent a byte
3050 * array but may have > 255 char codes. Be sure to take only the first byte
3051 * and returns the byte array.
3052 * @param {String} str the string to transform.
3053 * @return {Array|Uint8Array} the string in a binary format.
3054 */
3055 function string2binary(str) {
3056 var result = null;
3057 if (support.uint8array) {
3058 result = new Uint8Array(str.length);
3059 } else {
3060 result = new Array(str.length);
3061 }
3062 return stringToArrayLike(str, result);
3063 }
3064
3065 /**
3066 * Create a new blob with the given content and the given type.
3067 * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use
3068 * an Uint8Array because the stock browser of android 4 won't accept it (it
3069 * will be silently converted to a string, "[object Uint8Array]").
3070 *
3071 * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge:
3072 * when a large amount of Array is used to create the Blob, the amount of
3073 * memory consumed is nearly 100 times the original data amount.
3074 *
3075 * @param {String} type the mime type of the blob.
3076 * @return {Blob} the created blob.
3077 */
3078 exports.newBlob = function(part, type) {
3079 exports.checkSupport("blob");
3080
3081 try {
3082 // Blob constructor
3083 return new Blob([part], {
3084 type: type
3085 });
3086 }
3087 catch (e) {
3088
3089 try {
3090 // deprecated, browser only, old way
3091 var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
3092 var builder = new Builder();
3093 builder.append(part);
3094 return builder.getBlob(type);
3095 }
3096 catch (e) {
3097
3098 // well, fuck ?!
3099 throw new Error("Bug : can't construct the Blob.");
3100 }
3101 }
3102
3103
3104 };
3105 /**
3106 * The identity function.
3107 * @param {Object} input the input.
3108 * @return {Object} the same input.
3109 */
3110 function identity(input) {
3111 return input;
3112 }
3113
3114 /**
3115 * Fill in an array with a string.
3116 * @param {String} str the string to use.
3117 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
3118 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
3119 */
3120 function stringToArrayLike(str, array) {
3121 for (var i = 0; i < str.length; ++i) {
3122 array[i] = str.charCodeAt(i) & 0xFF;
3123 }
3124 return array;
3125 }
3126
3127 /**
3128 * An helper for the function arrayLikeToString.
3129 * This contains static information and functions that
3130 * can be optimized by the browser JIT compiler.
3131 */
3132 var arrayToStringHelper = {
3133 /**
3134 * Transform an array of int into a string, chunk by chunk.
3135 * See the performances notes on arrayLikeToString.
3136 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
3137 * @param {String} type the type of the array.
3138 * @param {Integer} chunk the chunk size.
3139 * @return {String} the resulting string.
3140 * @throws Error if the chunk is too big for the stack.
3141 */
3142 stringifyByChunk: function(array, type, chunk) {
3143 var result = [], k = 0, len = array.length;
3144 // shortcut
3145 if (len <= chunk) {
3146 return String.fromCharCode.apply(null, array);
3147 }
3148 while (k < len) {
3149 if (type === "array" || type === "nodebuffer") {
3150 result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
3151 }
3152 else {
3153 result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
3154 }
3155 k += chunk;
3156 }
3157 return result.join("");
3158 },
3159 /**
3160 * Call String.fromCharCode on every item in the array.
3161 * This is the naive implementation, which generate A LOT of intermediate string.
3162 * This should be used when everything else fail.
3163 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
3164 * @return {String} the result.
3165 */
3166 stringifyByChar: function(array){
3167 var resultStr = "";
3168 for(var i = 0; i < array.length; i++) {
3169 resultStr += String.fromCharCode(array[i]);
3170 }
3171 return resultStr;
3172 },
3173 applyCanBeUsed : {
3174 /**
3175 * true if the browser accepts to use String.fromCharCode on Uint8Array
3176 */
3177 uint8array : (function () {
3178 try {
3179 return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
3180 } catch (e) {
3181 return false;
3182 }
3183 })(),
3184 /**
3185 * true if the browser accepts to use String.fromCharCode on nodejs Buffer.
3186 */
3187 nodebuffer : (function () {
3188 try {
3189 return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1;
3190 } catch (e) {
3191 return false;
3192 }
3193 })()
3194 }
3195 };
3196
3197 /**
3198 * Transform an array-like object to a string.
3199 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
3200 * @return {String} the result.
3201 */
3202 function arrayLikeToString(array) {
3203 // Performances notes :
3204 // --------------------
3205 // String.fromCharCode.apply(null, array) is the fastest, see
3206 // see http://jsperf.com/converting-a-uint8array-to-a-string/2
3207 // but the stack is limited (and we can get huge arrays !).
3208 //
3209 // result += String.fromCharCode(array[i]); generate too many strings !
3210 //
3211 // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
3212 // TODO : we now have workers that split the work. Do we still need that ?
3213 var chunk = 65536,
3214 type = exports.getTypeOf(array),
3215 canUseApply = true;
3216 if (type === "uint8array") {
3217 canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
3218 } else if (type === "nodebuffer") {
3219 canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
3220 }
3221
3222 if (canUseApply) {
3223 while (chunk > 1) {
3224 try {
3225 return arrayToStringHelper.stringifyByChunk(array, type, chunk);
3226 } catch (e) {
3227 chunk = Math.floor(chunk / 2);
3228 }
3229 }
3230 }
3231
3232 // no apply or chunk error : slow and painful algorithm
3233 // default browser on android 4.*
3234 return arrayToStringHelper.stringifyByChar(array);
3235 }
3236
3237 exports.applyFromCharCode = arrayLikeToString;
3238
3239
3240 /**
3241 * Copy the data from an array-like to an other array-like.
3242 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
3243 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
3244 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
3245 */
3246 function arrayLikeToArrayLike(arrayFrom, arrayTo) {
3247 for (var i = 0; i < arrayFrom.length; i++) {
3248 arrayTo[i] = arrayFrom[i];
3249 }
3250 return arrayTo;
3251 }
3252
3253 // a matrix containing functions to transform everything into everything.
3254 var transform = {};
3255
3256 // string to ?
3257 transform["string"] = {
3258 "string": identity,
3259 "array": function(input) {
3260 return stringToArrayLike(input, new Array(input.length));
3261 },
3262 "arraybuffer": function(input) {
3263 return transform["string"]["uint8array"](input).buffer;
3264 },
3265 "uint8array": function(input) {
3266 return stringToArrayLike(input, new Uint8Array(input.length));
3267 },
3268 "nodebuffer": function(input) {
3269 return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length));
3270 }
3271 };
3272
3273 // array to ?
3274 transform["array"] = {
3275 "string": arrayLikeToString,
3276 "array": identity,
3277 "arraybuffer": function(input) {
3278 return (new Uint8Array(input)).buffer;
3279 },
3280 "uint8array": function(input) {
3281 return new Uint8Array(input);
3282 },
3283 "nodebuffer": function(input) {
3284 return nodejsUtils.newBufferFrom(input);
3285 }
3286 };
3287
3288 // arraybuffer to ?
3289 transform["arraybuffer"] = {
3290 "string": function(input) {
3291 return arrayLikeToString(new Uint8Array(input));
3292 },
3293 "array": function(input) {
3294 return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
3295 },
3296 "arraybuffer": identity,
3297 "uint8array": function(input) {
3298 return new Uint8Array(input);
3299 },
3300 "nodebuffer": function(input) {
3301 return nodejsUtils.newBufferFrom(new Uint8Array(input));
3302 }
3303 };
3304
3305 // uint8array to ?
3306 transform["uint8array"] = {
3307 "string": arrayLikeToString,
3308 "array": function(input) {
3309 return arrayLikeToArrayLike(input, new Array(input.length));
3310 },
3311 "arraybuffer": function(input) {
3312 return input.buffer;
3313 },
3314 "uint8array": identity,
3315 "nodebuffer": function(input) {
3316 return nodejsUtils.newBufferFrom(input);
3317 }
3318 };
3319
3320 // nodebuffer to ?
3321 transform["nodebuffer"] = {
3322 "string": arrayLikeToString,
3323 "array": function(input) {
3324 return arrayLikeToArrayLike(input, new Array(input.length));
3325 },
3326 "arraybuffer": function(input) {
3327 return transform["nodebuffer"]["uint8array"](input).buffer;
3328 },
3329 "uint8array": function(input) {
3330 return arrayLikeToArrayLike(input, new Uint8Array(input.length));
3331 },
3332 "nodebuffer": identity
3333 };
3334
3335 /**
3336 * Transform an input into any type.
3337 * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
3338 * If no output type is specified, the unmodified input will be returned.
3339 * @param {String} outputType the output type.
3340 * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
3341 * @throws {Error} an Error if the browser doesn't support the requested output type.
3342 */
3343 exports.transformTo = function(outputType, input) {
3344 if (!input) {
3345 // undefined, null, etc
3346 // an empty string won't harm.
3347 input = "";
3348 }
3349 if (!outputType) {
3350 return input;
3351 }
3352 exports.checkSupport(outputType);
3353 var inputType = exports.getTypeOf(input);
3354 var result = transform[inputType][outputType](input);
3355 return result;
3356 };
3357
3358 /**
3359 * Resolve all relative path components, "." and "..", in a path. If these relative components
3360 * traverse above the root then the resulting path will only contain the final path component.
3361 *
3362 * All empty components, e.g. "//", are removed.
3363 * @param {string} path A path with / or \ separators
3364 * @returns {string} The path with all relative path components resolved.
3365 */
3366 exports.resolve = function(path) {
3367 var parts = path.split("/");
3368 var result = [];
3369 for (var index = 0; index < parts.length; index++) {
3370 var part = parts[index];
3371 // Allow the first and last component to be empty for trailing slashes.
3372 if (part === "." || (part === "" && index !== 0 && index !== parts.length - 1)) {
3373 continue;
3374 } else if (part === "..") {
3375 result.pop();
3376 } else {
3377 result.push(part);
3378 }
3379 }
3380 return result.join("/");
3381 };
3382
3383 /**
3384 * Return the type of the input.
3385 * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
3386 * @param {Object} input the input to identify.
3387 * @return {String} the (lowercase) type of the input.
3388 */
3389 exports.getTypeOf = function(input) {
3390 if (typeof input === "string") {
3391 return "string";
3392 }
3393 var proto = Object.prototype.toString.call(input);
3394 if (proto === "[object Array]") {
3395 return "array";
3396 }
3397 if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
3398 return "nodebuffer";
3399 }
3400 if (support.uint8array && proto === "[object Uint8Array]") {
3401 return "uint8array";
3402 }
3403 if (support.arraybuffer && proto === "[object ArrayBuffer]") {
3404 return "arraybuffer";
3405 }
3406 };
3407
3408 /**
3409 * Throw an exception if the type is not supported.
3410 * @param {String} type the type to check.
3411 * @throws {Error} an Error if the browser doesn't support the requested type.
3412 */
3413 exports.checkSupport = function(type) {
3414 var supported = support[type.toLowerCase()];
3415 if (!supported) {
3416 throw new Error(type + " is not supported by this platform");
3417 }
3418 };
3419
3420 exports.MAX_VALUE_16BITS = 65535;
3421 exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
3422
3423 /**
3424 * Prettify a string read as binary.
3425 * @param {string} str the string to prettify.
3426 * @return {string} a pretty string.
3427 */
3428 exports.pretty = function(str) {
3429 var res = "",
3430 code, i;
3431 for (i = 0; i < (str || "").length; i++) {
3432 code = str.charCodeAt(i);
3433 res += "\\x" + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
3434 }
3435 return res;
3436 };
3437
3438 /**
3439 * Defer the call of a function.
3440 * @param {Function} callback the function to call asynchronously.
3441 * @param {Array} args the arguments to give to the callback.
3442 */
3443 exports.delay = function(callback, args, self) {
3444 setImmediate(function () {
3445 callback.apply(self || null, args || []);
3446 });
3447 };
3448
3449 /**
3450 * Extends a prototype with an other, without calling a constructor with
3451 * side effects. Inspired by nodejs' `utils.inherits`
3452 * @param {Function} ctor the constructor to augment
3453 * @param {Function} superCtor the parent constructor to use
3454 */
3455 exports.inherits = function (ctor, superCtor) {
3456 var Obj = function() {};
3457 Obj.prototype = superCtor.prototype;
3458 ctor.prototype = new Obj();
3459 };
3460
3461 /**
3462 * Merge the objects passed as parameters into a new one.
3463 * @private
3464 * @param {...Object} var_args All objects to merge.
3465 * @return {Object} a new object with the data of the others.
3466 */
3467 exports.extend = function() {
3468 var result = {}, i, attr;
3469 for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
3470 for (attr in arguments[i]) {
3471 if (Object.prototype.hasOwnProperty.call(arguments[i], attr) && typeof result[attr] === "undefined") {
3472 result[attr] = arguments[i][attr];
3473 }
3474 }
3475 }
3476 return result;
3477 };
3478
3479 /**
3480 * Transform arbitrary content into a Promise.
3481 * @param {String} name a name for the content being processed.
3482 * @param {Object} inputData the content to process.
3483 * @param {Boolean} isBinary true if the content is not an unicode string
3484 * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.
3485 * @param {Boolean} isBase64 true if the string content is encoded with base64.
3486 * @return {Promise} a promise in a format usable by JSZip.
3487 */
3488 exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {
3489
3490 // if inputData is already a promise, this flatten it.
3491 var promise = external.Promise.resolve(inputData).then(function(data) {
3492
3493
3494 var isBlob = support.blob && (data instanceof Blob || ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(data)) !== -1);
3495
3496 if (isBlob) {
3497 if (typeof Blob.prototype.arrayBuffer !== "undefined") {
3498 return data.arrayBuffer();
3499 } else if (typeof FileReader !== "undefined") {
3500 return new external.Promise(function (resolve, reject) {
3501 var reader = new FileReader();
3502
3503 reader.onload = function(e) {
3504 resolve(e.target.result);
3505 };
3506 reader.onerror = function(e) {
3507 reject(e.target.error);
3508 };
3509 reader.readAsArrayBuffer(data);
3510 });
3511 } else {
3512 return external.Promise.reject(
3513 new Error(name + " is a Blob, but we have no way of reading it.")
3514 );
3515 }
3516 }
3517
3518 return data;
3519 });
3520
3521 return promise.then(function(data) {
3522 var dataType = exports.getTypeOf(data);
3523
3524 if (!dataType) {
3525 return external.Promise.reject(
3526 new Error("Can't read the data of '" + name + "'. Is it " +
3527 "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")
3528 );
3529 }
3530 // special case : it's way easier to work with Uint8Array than with ArrayBuffer
3531 if (dataType === "arraybuffer") {
3532 data = exports.transformTo("uint8array", data);
3533 } else if (dataType === "string") {
3534 if (isBase64) {
3535 data = base64.decode(data);
3536 }
3537 else if (isBinary) {
3538 // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask
3539 if (isOptimizedBinaryString !== true) {
3540 // this is a string, not in a base64 format.
3541 // Be sure that this is a correct "binary string"
3542 data = string2binary(data);
3543 }
3544 }
3545 }
3546 return data;
3547 });
3548 };
3549
3550 },{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,"setimmediate":54}],33:[function(require,module,exports){
3551 "use strict";
3552 var readerFor = require("./reader/readerFor");
3553 var utils = require("./utils");
3554 var sig = require("./signature");
3555 var ZipEntry = require("./zipEntry");
3556 var support = require("./support");
3557 // class ZipEntries {{{
3558 /**
3559 * All the entries in the zip file.
3560 * @constructor
3561 * @param {Object} loadOptions Options for loading the stream.
3562 */
3563 function ZipEntries(loadOptions) {
3564 this.files = [];
3565 this.loadOptions = loadOptions;
3566 }
3567 ZipEntries.prototype = {
3568 /**
3569 * Check that the reader is on the specified signature.
3570 * @param {string} expectedSignature the expected signature.
3571 * @throws {Error} if it is an other signature.
3572 */
3573 checkSignature: function(expectedSignature) {
3574 if (!this.reader.readAndCheckSignature(expectedSignature)) {
3575 this.reader.index -= 4;
3576 var signature = this.reader.readString(4);
3577 throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
3578 }
3579 },
3580 /**
3581 * Check if the given signature is at the given index.
3582 * @param {number} askedIndex the index to check.
3583 * @param {string} expectedSignature the signature to expect.
3584 * @return {boolean} true if the signature is here, false otherwise.
3585 */
3586 isSignature: function(askedIndex, expectedSignature) {
3587 var currentIndex = this.reader.index;
3588 this.reader.setIndex(askedIndex);
3589 var signature = this.reader.readString(4);
3590 var result = signature === expectedSignature;
3591 this.reader.setIndex(currentIndex);
3592 return result;
3593 },
3594 /**
3595 * Read the end of the central directory.
3596 */
3597 readBlockEndOfCentral: function() {
3598 this.diskNumber = this.reader.readInt(2);
3599 this.diskWithCentralDirStart = this.reader.readInt(2);
3600 this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
3601 this.centralDirRecords = this.reader.readInt(2);
3602 this.centralDirSize = this.reader.readInt(4);
3603 this.centralDirOffset = this.reader.readInt(4);
3604
3605 this.zipCommentLength = this.reader.readInt(2);
3606 // warning : the encoding depends of the system locale
3607 // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
3608 // On a windows machine, this field is encoded with the localized windows code page.
3609 var zipComment = this.reader.readData(this.zipCommentLength);
3610 var decodeParamType = support.uint8array ? "uint8array" : "array";
3611 // To get consistent behavior with the generation part, we will assume that
3612 // this is utf8 encoded unless specified otherwise.
3613 var decodeContent = utils.transformTo(decodeParamType, zipComment);
3614 this.zipComment = this.loadOptions.decodeFileName(decodeContent);
3615 },
3616 /**
3617 * Read the end of the Zip 64 central directory.
3618 * Not merged with the method readEndOfCentral :
3619 * The end of central can coexist with its Zip64 brother,
3620 * I don't want to read the wrong number of bytes !
3621 */
3622 readBlockZip64EndOfCentral: function() {
3623 this.zip64EndOfCentralSize = this.reader.readInt(8);
3624 this.reader.skip(4);
3625 // this.versionMadeBy = this.reader.readString(2);
3626 // this.versionNeeded = this.reader.readInt(2);
3627 this.diskNumber = this.reader.readInt(4);
3628 this.diskWithCentralDirStart = this.reader.readInt(4);
3629 this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
3630 this.centralDirRecords = this.reader.readInt(8);
3631 this.centralDirSize = this.reader.readInt(8);
3632 this.centralDirOffset = this.reader.readInt(8);
3633
3634 this.zip64ExtensibleData = {};
3635 var extraDataSize = this.zip64EndOfCentralSize - 44,
3636 index = 0,
3637 extraFieldId,
3638 extraFieldLength,
3639 extraFieldValue;
3640 while (index < extraDataSize) {
3641 extraFieldId = this.reader.readInt(2);
3642 extraFieldLength = this.reader.readInt(4);
3643 extraFieldValue = this.reader.readData(extraFieldLength);
3644 this.zip64ExtensibleData[extraFieldId] = {
3645 id: extraFieldId,
3646 length: extraFieldLength,
3647 value: extraFieldValue
3648 };
3649 }
3650 },
3651 /**
3652 * Read the end of the Zip 64 central directory locator.
3653 */
3654 readBlockZip64EndOfCentralLocator: function() {
3655 this.diskWithZip64CentralDirStart = this.reader.readInt(4);
3656 this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
3657 this.disksCount = this.reader.readInt(4);
3658 if (this.disksCount > 1) {
3659 throw new Error("Multi-volumes zip are not supported");
3660 }
3661 },
3662 /**
3663 * Read the local files, based on the offset read in the central part.
3664 */
3665 readLocalFiles: function() {
3666 var i, file;
3667 for (i = 0; i < this.files.length; i++) {
3668 file = this.files[i];
3669 this.reader.setIndex(file.localHeaderOffset);
3670 this.checkSignature(sig.LOCAL_FILE_HEADER);
3671 file.readLocalPart(this.reader);
3672 file.handleUTF8();
3673 file.processAttributes();
3674 }
3675 },
3676 /**
3677 * Read the central directory.
3678 */
3679 readCentralDir: function() {
3680 var file;
3681
3682 this.reader.setIndex(this.centralDirOffset);
3683 while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {
3684 file = new ZipEntry({
3685 zip64: this.zip64
3686 }, this.loadOptions);
3687 file.readCentralPart(this.reader);
3688 this.files.push(file);
3689 }
3690
3691 if (this.centralDirRecords !== this.files.length) {
3692 if (this.centralDirRecords !== 0 && this.files.length === 0) {
3693 // We expected some records but couldn't find ANY.
3694 // This is really suspicious, as if something went wrong.
3695 throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
3696 } else {
3697 // We found some records but not all.
3698 // Something is wrong but we got something for the user: no error here.
3699 // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
3700 }
3701 }
3702 },
3703 /**
3704 * Read the end of central directory.
3705 */
3706 readEndOfCentral: function() {
3707 var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
3708 if (offset < 0) {
3709 // Check if the content is a truncated zip or complete garbage.
3710 // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
3711 // extractible zip for example) but it can give a good hint.
3712 // If an ajax request was used without responseType, we will also
3713 // get unreadable data.
3714 var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
3715
3716 if (isGarbage) {
3717 throw new Error("Can't find end of central directory : is this a zip file ? " +
3718 "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");
3719 } else {
3720 throw new Error("Corrupted zip: can't find end of central directory");
3721 }
3722
3723 }
3724 this.reader.setIndex(offset);
3725 var endOfCentralDirOffset = offset;
3726 this.checkSignature(sig.CENTRAL_DIRECTORY_END);
3727 this.readBlockEndOfCentral();
3728
3729
3730 /* extract from the zip spec :
3731 4) If one of the fields in the end of central directory
3732 record is too small to hold required data, the field
3733 should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
3734 ZIP64 format record should be created.
3735 5) The end of central directory record and the
3736 Zip64 end of central directory locator record must
3737 reside on the same disk when splitting or spanning
3738 an archive.
3739 */
3740 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) {
3741 this.zip64 = true;
3742
3743 /*
3744 Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
3745 the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents
3746 all numbers as 64-bit double precision IEEE 754 floating point numbers.
3747 So, we have 53bits for integers and bitwise operations treat everything as 32bits.
3748 see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
3749 and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
3750 */
3751
3752 // should look for a zip64 EOCD locator
3753 offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
3754 if (offset < 0) {
3755 throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
3756 }
3757 this.reader.setIndex(offset);
3758 this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
3759 this.readBlockZip64EndOfCentralLocator();
3760
3761 // now the zip64 EOCD record
3762 if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
3763 // console.warn("ZIP64 end of central directory not where expected.");
3764 this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
3765 if (this.relativeOffsetEndOfZip64CentralDir < 0) {
3766 throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
3767 }
3768 }
3769 this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
3770 this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
3771 this.readBlockZip64EndOfCentral();
3772 }
3773
3774 var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
3775 if (this.zip64) {
3776 expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
3777 expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
3778 }
3779
3780 var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
3781
3782 if (extraBytes > 0) {
3783 // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
3784 if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
3785 // The offsets seem wrong, but we have something at the specified offset.
3786 // So… we keep it.
3787 } else {
3788 // the offset is wrong, update the "zero" of the reader
3789 // this happens if data has been prepended (crx files for example)
3790 this.reader.zero = extraBytes;
3791 }
3792 } else if (extraBytes < 0) {
3793 throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
3794 }
3795 },
3796 prepareReader: function(data) {
3797 this.reader = readerFor(data);
3798 },
3799 /**
3800 * Read a zip file and create ZipEntries.
3801 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
3802 */
3803 load: function(data) {
3804 this.prepareReader(data);
3805 this.readEndOfCentral();
3806 this.readCentralDir();
3807 this.readLocalFiles();
3808 }
3809 };
3810 // }}} end of ZipEntries
3811 module.exports = ZipEntries;
3812
3813 },{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(require,module,exports){
3814 "use strict";
3815 var readerFor = require("./reader/readerFor");
3816 var utils = require("./utils");
3817 var CompressedObject = require("./compressedObject");
3818 var crc32fn = require("./crc32");
3819 var utf8 = require("./utf8");
3820 var compressions = require("./compressions");
3821 var support = require("./support");
3822
3823 var MADE_BY_DOS = 0x00;
3824 var MADE_BY_UNIX = 0x03;
3825
3826 /**
3827 * Find a compression registered in JSZip.
3828 * @param {string} compressionMethod the method magic to find.
3829 * @return {Object|null} the JSZip compression object, null if none found.
3830 */
3831 var findCompression = function(compressionMethod) {
3832 for (var method in compressions) {
3833 if (!Object.prototype.hasOwnProperty.call(compressions, method)) {
3834 continue;
3835 }
3836 if (compressions[method].magic === compressionMethod) {
3837 return compressions[method];
3838 }
3839 }
3840 return null;
3841 };
3842
3843 // class ZipEntry {{{
3844 /**
3845 * An entry in the zip file.
3846 * @constructor
3847 * @param {Object} options Options of the current file.
3848 * @param {Object} loadOptions Options for loading the stream.
3849 */
3850 function ZipEntry(options, loadOptions) {
3851 this.options = options;
3852 this.loadOptions = loadOptions;
3853 }
3854 ZipEntry.prototype = {
3855 /**
3856 * say if the file is encrypted.
3857 * @return {boolean} true if the file is encrypted, false otherwise.
3858 */
3859 isEncrypted: function() {
3860 // bit 1 is set
3861 return (this.bitFlag & 0x0001) === 0x0001;
3862 },
3863 /**
3864 * say if the file has utf-8 filename/comment.
3865 * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
3866 */
3867 useUTF8: function() {
3868 // bit 11 is set
3869 return (this.bitFlag & 0x0800) === 0x0800;
3870 },
3871 /**
3872 * Read the local part of a zip file and add the info in this object.
3873 * @param {DataReader} reader the reader to use.
3874 */
3875 readLocalPart: function(reader) {
3876 var compression, localExtraFieldsLength;
3877
3878 // we already know everything from the central dir !
3879 // If the central dir data are false, we are doomed.
3880 // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
3881 // The less data we get here, the more reliable this should be.
3882 // Let's skip the whole header and dash to the data !
3883 reader.skip(22);
3884 // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
3885 // Strangely, the filename here is OK.
3886 // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
3887 // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
3888 // Search "unzip mismatching "local" filename continuing with "central" filename version" on
3889 // the internet.
3890 //
3891 // I think I see the logic here : the central directory is used to display
3892 // content and the local directory is used to extract the files. Mixing / and \
3893 // may be used to display \ to windows users and use / when extracting the files.
3894 // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
3895 this.fileNameLength = reader.readInt(2);
3896 localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
3897 // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding.
3898 this.fileName = reader.readData(this.fileNameLength);
3899 reader.skip(localExtraFieldsLength);
3900
3901 if (this.compressedSize === -1 || this.uncompressedSize === -1) {
3902 throw new Error("Bug or corrupted zip : didn't get enough information from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)");
3903 }
3904
3905 compression = findCompression(this.compressionMethod);
3906 if (compression === null) { // no compression found
3907 throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")");
3908 }
3909 this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));
3910 },
3911
3912 /**
3913 * Read the central part of a zip file and add the info in this object.
3914 * @param {DataReader} reader the reader to use.
3915 */
3916 readCentralPart: function(reader) {
3917 this.versionMadeBy = reader.readInt(2);
3918 reader.skip(2);
3919 // this.versionNeeded = reader.readInt(2);
3920 this.bitFlag = reader.readInt(2);
3921 this.compressionMethod = reader.readString(2);
3922 this.date = reader.readDate();
3923 this.crc32 = reader.readInt(4);
3924 this.compressedSize = reader.readInt(4);
3925 this.uncompressedSize = reader.readInt(4);
3926 var fileNameLength = reader.readInt(2);
3927 this.extraFieldsLength = reader.readInt(2);
3928 this.fileCommentLength = reader.readInt(2);
3929 this.diskNumberStart = reader.readInt(2);
3930 this.internalFileAttributes = reader.readInt(2);
3931 this.externalFileAttributes = reader.readInt(4);
3932 this.localHeaderOffset = reader.readInt(4);
3933
3934 if (this.isEncrypted()) {
3935 throw new Error("Encrypted zip are not supported");
3936 }
3937
3938 // will be read in the local part, see the comments there
3939 reader.skip(fileNameLength);
3940 this.readExtraFields(reader);
3941 this.parseZIP64ExtraField(reader);
3942 this.fileComment = reader.readData(this.fileCommentLength);
3943 },
3944
3945 /**
3946 * Parse the external file attributes and get the unix/dos permissions.
3947 */
3948 processAttributes: function () {
3949 this.unixPermissions = null;
3950 this.dosPermissions = null;
3951 var madeBy = this.versionMadeBy >> 8;
3952
3953 // Check if we have the DOS directory flag set.
3954 // We look for it in the DOS and UNIX permissions
3955 // but some unknown platform could set it as a compatibility flag.
3956 this.dir = this.externalFileAttributes & 0x0010 ? true : false;
3957
3958 if(madeBy === MADE_BY_DOS) {
3959 // first 6 bits (0 to 5)
3960 this.dosPermissions = this.externalFileAttributes & 0x3F;
3961 }
3962
3963 if(madeBy === MADE_BY_UNIX) {
3964 this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
3965 // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
3966 }
3967
3968 // fail safe : if the name ends with a / it probably means a folder
3969 if (!this.dir && this.fileNameStr.slice(-1) === "/") {
3970 this.dir = true;
3971 }
3972 },
3973
3974 /**
3975 * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
3976 * @param {DataReader} reader the reader to use.
3977 */
3978 parseZIP64ExtraField: function() {
3979 if (!this.extraFields[0x0001]) {
3980 return;
3981 }
3982
3983 // should be something, preparing the extra reader
3984 var extraReader = readerFor(this.extraFields[0x0001].value);
3985
3986 // I really hope that these 64bits integer can fit in 32 bits integer, because js
3987 // won't let us have more.
3988 if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
3989 this.uncompressedSize = extraReader.readInt(8);
3990 }
3991 if (this.compressedSize === utils.MAX_VALUE_32BITS) {
3992 this.compressedSize = extraReader.readInt(8);
3993 }
3994 if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
3995 this.localHeaderOffset = extraReader.readInt(8);
3996 }
3997 if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
3998 this.diskNumberStart = extraReader.readInt(4);
3999 }
4000 },
4001 /**
4002 * Read the central part of a zip file and add the info in this object.
4003 * @param {DataReader} reader the reader to use.
4004 */
4005 readExtraFields: function(reader) {
4006 var end = reader.index + this.extraFieldsLength,
4007 extraFieldId,
4008 extraFieldLength,
4009 extraFieldValue;
4010
4011 if (!this.extraFields) {
4012 this.extraFields = {};
4013 }
4014
4015 while (reader.index + 4 < end) {
4016 extraFieldId = reader.readInt(2);
4017 extraFieldLength = reader.readInt(2);
4018 extraFieldValue = reader.readData(extraFieldLength);
4019
4020 this.extraFields[extraFieldId] = {
4021 id: extraFieldId,
4022 length: extraFieldLength,
4023 value: extraFieldValue
4024 };
4025 }
4026
4027 reader.setIndex(end);
4028 },
4029 /**
4030 * Apply an UTF8 transformation if needed.
4031 */
4032 handleUTF8: function() {
4033 var decodeParamType = support.uint8array ? "uint8array" : "array";
4034 if (this.useUTF8()) {
4035 this.fileNameStr = utf8.utf8decode(this.fileName);
4036 this.fileCommentStr = utf8.utf8decode(this.fileComment);
4037 } else {
4038 var upath = this.findExtraFieldUnicodePath();
4039 if (upath !== null) {
4040 this.fileNameStr = upath;
4041 } else {
4042 // ASCII text or unsupported code page
4043 var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName);
4044 this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
4045 }
4046
4047 var ucomment = this.findExtraFieldUnicodeComment();
4048 if (ucomment !== null) {
4049 this.fileCommentStr = ucomment;
4050 } else {
4051 // ASCII text or unsupported code page
4052 var commentByteArray = utils.transformTo(decodeParamType, this.fileComment);
4053 this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
4054 }
4055 }
4056 },
4057
4058 /**
4059 * Find the unicode path declared in the extra field, if any.
4060 * @return {String} the unicode path, null otherwise.
4061 */
4062 findExtraFieldUnicodePath: function() {
4063 var upathField = this.extraFields[0x7075];
4064 if (upathField) {
4065 var extraReader = readerFor(upathField.value);
4066
4067 // wrong version
4068 if (extraReader.readInt(1) !== 1) {
4069 return null;
4070 }
4071
4072 // the crc of the filename changed, this field is out of date.
4073 if (crc32fn(this.fileName) !== extraReader.readInt(4)) {
4074 return null;
4075 }
4076
4077 return utf8.utf8decode(extraReader.readData(upathField.length - 5));
4078 }
4079 return null;
4080 },
4081
4082 /**
4083 * Find the unicode comment declared in the extra field, if any.
4084 * @return {String} the unicode comment, null otherwise.
4085 */
4086 findExtraFieldUnicodeComment: function() {
4087 var ucommentField = this.extraFields[0x6375];
4088 if (ucommentField) {
4089 var extraReader = readerFor(ucommentField.value);
4090
4091 // wrong version
4092 if (extraReader.readInt(1) !== 1) {
4093 return null;
4094 }
4095
4096 // the crc of the comment changed, this field is out of date.
4097 if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {
4098 return null;
4099 }
4100
4101 return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));
4102 }
4103 return null;
4104 }
4105 };
4106 module.exports = ZipEntry;
4107
4108 },{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(require,module,exports){
4109 "use strict";
4110
4111 var StreamHelper = require("./stream/StreamHelper");
4112 var DataWorker = require("./stream/DataWorker");
4113 var utf8 = require("./utf8");
4114 var CompressedObject = require("./compressedObject");
4115 var GenericWorker = require("./stream/GenericWorker");
4116
4117 /**
4118 * A simple object representing a file in the zip file.
4119 * @constructor
4120 * @param {string} name the name of the file
4121 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
4122 * @param {Object} options the options of the file
4123 */
4124 var ZipObject = function(name, data, options) {
4125 this.name = name;
4126 this.dir = options.dir;
4127 this.date = options.date;
4128 this.comment = options.comment;
4129 this.unixPermissions = options.unixPermissions;
4130 this.dosPermissions = options.dosPermissions;
4131
4132 this._data = data;
4133 this._dataBinary = options.binary;
4134 // keep only the compression
4135 this.options = {
4136 compression : options.compression,
4137 compressionOptions : options.compressionOptions
4138 };
4139 };
4140
4141 ZipObject.prototype = {
4142 /**
4143 * Create an internal stream for the content of this object.
4144 * @param {String} type the type of each chunk.
4145 * @return StreamHelper the stream.
4146 */
4147 internalStream: function (type) {
4148 var result = null, outputType = "string";
4149 try {
4150 if (!type) {
4151 throw new Error("No output type specified.");
4152 }
4153 outputType = type.toLowerCase();
4154 var askUnicodeString = outputType === "string" || outputType === "text";
4155 if (outputType === "binarystring" || outputType === "text") {
4156 outputType = "string";
4157 }
4158 result = this._decompressWorker();
4159
4160 var isUnicodeString = !this._dataBinary;
4161
4162 if (isUnicodeString && !askUnicodeString) {
4163 result = result.pipe(new utf8.Utf8EncodeWorker());
4164 }
4165 if (!isUnicodeString && askUnicodeString) {
4166 result = result.pipe(new utf8.Utf8DecodeWorker());
4167 }
4168 } catch (e) {
4169 result = new GenericWorker("error");
4170 result.error(e);
4171 }
4172
4173 return new StreamHelper(result, outputType, "");
4174 },
4175
4176 /**
4177 * Prepare the content in the asked type.
4178 * @param {String} type the type of the result.
4179 * @param {Function} onUpdate a function to call on each internal update.
4180 * @return Promise the promise of the result.
4181 */
4182 async: function (type, onUpdate) {
4183 return this.internalStream(type).accumulate(onUpdate);
4184 },
4185
4186 /**
4187 * Prepare the content as a nodejs stream.
4188 * @param {String} type the type of each chunk.
4189 * @param {Function} onUpdate a function to call on each internal update.
4190 * @return Stream the stream.
4191 */
4192 nodeStream: function (type, onUpdate) {
4193 return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate);
4194 },
4195
4196 /**
4197 * Return a worker for the compressed content.
4198 * @private
4199 * @param {Object} compression the compression object to use.
4200 * @param {Object} compressionOptions the options to use when compressing.
4201 * @return Worker the worker.
4202 */
4203 _compressWorker: function (compression, compressionOptions) {
4204 if (
4205 this._data instanceof CompressedObject &&
4206 this._data.compression.magic === compression.magic
4207 ) {
4208 return this._data.getCompressedWorker();
4209 } else {
4210 var result = this._decompressWorker();
4211 if(!this._dataBinary) {
4212 result = result.pipe(new utf8.Utf8EncodeWorker());
4213 }
4214 return CompressedObject.createWorkerFrom(result, compression, compressionOptions);
4215 }
4216 },
4217 /**
4218 * Return a worker for the decompressed content.
4219 * @private
4220 * @return Worker the worker.
4221 */
4222 _decompressWorker : function () {
4223 if (this._data instanceof CompressedObject) {
4224 return this._data.getContentWorker();
4225 } else if (this._data instanceof GenericWorker) {
4226 return this._data;
4227 } else {
4228 return new DataWorker(this._data);
4229 }
4230 }
4231 };
4232
4233 var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"];
4234 var removedFn = function () {
4235 throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
4236 };
4237
4238 for(var i = 0; i < removedMethods.length; i++) {
4239 ZipObject.prototype[removedMethods[i]] = removedFn;
4240 }
4241 module.exports = ZipObject;
4242
4243 },{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(require,module,exports){
4244 (function (global){
4245 'use strict';
4246 var Mutation = global.MutationObserver || global.WebKitMutationObserver;
4247
4248 var scheduleDrain;
4249
4250 {
4251 if (Mutation) {
4252 var called = 0;
4253 var observer = new Mutation(nextTick);
4254 var element = global.document.createTextNode('');
4255 observer.observe(element, {
4256 characterData: true
4257 });
4258 scheduleDrain = function () {
4259 element.data = (called = ++called % 2);
4260 };
4261 } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
4262 var channel = new global.MessageChannel();
4263 channel.port1.onmessage = nextTick;
4264 scheduleDrain = function () {
4265 channel.port2.postMessage(0);
4266 };
4267 } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
4268 scheduleDrain = function () {
4269
4270 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
4271 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
4272 var scriptEl = global.document.createElement('script');
4273 scriptEl.onreadystatechange = function () {
4274 nextTick();
4275
4276 scriptEl.onreadystatechange = null;
4277 scriptEl.parentNode.removeChild(scriptEl);
4278 scriptEl = null;
4279 };
4280 global.document.documentElement.appendChild(scriptEl);
4281 };
4282 } else {
4283 scheduleDrain = function () {
4284 setTimeout(nextTick, 0);
4285 };
4286 }
4287 }
4288
4289 var draining;
4290 var queue = [];
4291 //named nextTick for less confusing stack traces
4292 function nextTick() {
4293 draining = true;
4294 var i, oldQueue;
4295 var len = queue.length;
4296 while (len) {
4297 oldQueue = queue;
4298 queue = [];
4299 i = -1;
4300 while (++i < len) {
4301 oldQueue[i]();
4302 }
4303 len = queue.length;
4304 }
4305 draining = false;
4306 }
4307
4308 module.exports = immediate;
4309 function immediate(task) {
4310 if (queue.push(task) === 1 && !draining) {
4311 scheduleDrain();
4312 }
4313 }
4314
4315 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
4316 },{}],37:[function(require,module,exports){
4317 'use strict';
4318 var immediate = require('immediate');
4319
4320 /* istanbul ignore next */
4321 function INTERNAL() {}
4322
4323 var handlers = {};
4324
4325 var REJECTED = ['REJECTED'];
4326 var FULFILLED = ['FULFILLED'];
4327 var PENDING = ['PENDING'];
4328
4329 module.exports = Promise;
4330
4331 function Promise(resolver) {
4332 if (typeof resolver !== 'function') {
4333 throw new TypeError('resolver must be a function');
4334 }
4335 this.state = PENDING;
4336 this.queue = [];
4337 this.outcome = void 0;
4338 if (resolver !== INTERNAL) {
4339 safelyResolveThenable(this, resolver);
4340 }
4341 }
4342
4343 Promise.prototype["finally"] = function (callback) {
4344 if (typeof callback !== 'function') {
4345 return this;
4346 }
4347 var p = this.constructor;
4348 return this.then(resolve, reject);
4349
4350 function resolve(value) {
4351 function yes () {
4352 return value;
4353 }
4354 return p.resolve(callback()).then(yes);
4355 }
4356 function reject(reason) {
4357 function no () {
4358 throw reason;
4359 }
4360 return p.resolve(callback()).then(no);
4361 }
4362 };
4363 Promise.prototype["catch"] = function (onRejected) {
4364 return this.then(null, onRejected);
4365 };
4366 Promise.prototype.then = function (onFulfilled, onRejected) {
4367 if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
4368 typeof onRejected !== 'function' && this.state === REJECTED) {
4369 return this;
4370 }
4371 var promise = new this.constructor(INTERNAL);
4372 if (this.state !== PENDING) {
4373 var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
4374 unwrap(promise, resolver, this.outcome);
4375 } else {
4376 this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
4377 }
4378
4379 return promise;
4380 };
4381 function QueueItem(promise, onFulfilled, onRejected) {
4382 this.promise = promise;
4383 if (typeof onFulfilled === 'function') {
4384 this.onFulfilled = onFulfilled;
4385 this.callFulfilled = this.otherCallFulfilled;
4386 }
4387 if (typeof onRejected === 'function') {
4388 this.onRejected = onRejected;
4389 this.callRejected = this.otherCallRejected;
4390 }
4391 }
4392 QueueItem.prototype.callFulfilled = function (value) {
4393 handlers.resolve(this.promise, value);
4394 };
4395 QueueItem.prototype.otherCallFulfilled = function (value) {
4396 unwrap(this.promise, this.onFulfilled, value);
4397 };
4398 QueueItem.prototype.callRejected = function (value) {
4399 handlers.reject(this.promise, value);
4400 };
4401 QueueItem.prototype.otherCallRejected = function (value) {
4402 unwrap(this.promise, this.onRejected, value);
4403 };
4404
4405 function unwrap(promise, func, value) {
4406 immediate(function () {
4407 var returnValue;
4408 try {
4409 returnValue = func(value);
4410 } catch (e) {
4411 return handlers.reject(promise, e);
4412 }
4413 if (returnValue === promise) {
4414 handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
4415 } else {
4416 handlers.resolve(promise, returnValue);
4417 }
4418 });
4419 }
4420
4421 handlers.resolve = function (self, value) {
4422 var result = tryCatch(getThen, value);
4423 if (result.status === 'error') {
4424 return handlers.reject(self, result.value);
4425 }
4426 var thenable = result.value;
4427
4428 if (thenable) {
4429 safelyResolveThenable(self, thenable);
4430 } else {
4431 self.state = FULFILLED;
4432 self.outcome = value;
4433 var i = -1;
4434 var len = self.queue.length;
4435 while (++i < len) {
4436 self.queue[i].callFulfilled(value);
4437 }
4438 }
4439 return self;
4440 };
4441 handlers.reject = function (self, error) {
4442 self.state = REJECTED;
4443 self.outcome = error;
4444 var i = -1;
4445 var len = self.queue.length;
4446 while (++i < len) {
4447 self.queue[i].callRejected(error);
4448 }
4449 return self;
4450 };
4451
4452 function getThen(obj) {
4453 // Make sure we only access the accessor once as required by the spec
4454 var then = obj && obj.then;
4455 if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
4456 return function appyThen() {
4457 then.apply(obj, arguments);
4458 };
4459 }
4460 }
4461
4462 function safelyResolveThenable(self, thenable) {
4463 // Either fulfill, reject or reject with error
4464 var called = false;
4465 function onError(value) {
4466 if (called) {
4467 return;
4468 }
4469 called = true;
4470 handlers.reject(self, value);
4471 }
4472
4473 function onSuccess(value) {
4474 if (called) {
4475 return;
4476 }
4477 called = true;
4478 handlers.resolve(self, value);
4479 }
4480
4481 function tryToUnwrap() {
4482 thenable(onSuccess, onError);
4483 }
4484
4485 var result = tryCatch(tryToUnwrap);
4486 if (result.status === 'error') {
4487 onError(result.value);
4488 }
4489 }
4490
4491 function tryCatch(func, value) {
4492 var out = {};
4493 try {
4494 out.value = func(value);
4495 out.status = 'success';
4496 } catch (e) {
4497 out.status = 'error';
4498 out.value = e;
4499 }
4500 return out;
4501 }
4502
4503 Promise.resolve = resolve;
4504 function resolve(value) {
4505 if (value instanceof this) {
4506 return value;
4507 }
4508 return handlers.resolve(new this(INTERNAL), value);
4509 }
4510
4511 Promise.reject = reject;
4512 function reject(reason) {
4513 var promise = new this(INTERNAL);
4514 return handlers.reject(promise, reason);
4515 }
4516
4517 Promise.all = all;
4518 function all(iterable) {
4519 var self = this;
4520 if (Object.prototype.toString.call(iterable) !== '[object Array]') {
4521 return this.reject(new TypeError('must be an array'));
4522 }
4523
4524 var len = iterable.length;
4525 var called = false;
4526 if (!len) {
4527 return this.resolve([]);
4528 }
4529
4530 var values = new Array(len);
4531 var resolved = 0;
4532 var i = -1;
4533 var promise = new this(INTERNAL);
4534
4535 while (++i < len) {
4536 allResolver(iterable[i], i);
4537 }
4538 return promise;
4539 function allResolver(value, i) {
4540 self.resolve(value).then(resolveFromAll, function (error) {
4541 if (!called) {
4542 called = true;
4543 handlers.reject(promise, error);
4544 }
4545 });
4546 function resolveFromAll(outValue) {
4547 values[i] = outValue;
4548 if (++resolved === len && !called) {
4549 called = true;
4550 handlers.resolve(promise, values);
4551 }
4552 }
4553 }
4554 }
4555
4556 Promise.race = race;
4557 function race(iterable) {
4558 var self = this;
4559 if (Object.prototype.toString.call(iterable) !== '[object Array]') {
4560 return this.reject(new TypeError('must be an array'));
4561 }
4562
4563 var len = iterable.length;
4564 var called = false;
4565 if (!len) {
4566 return this.resolve([]);
4567 }
4568
4569 var i = -1;
4570 var promise = new this(INTERNAL);
4571
4572 while (++i < len) {
4573 resolver(iterable[i]);
4574 }
4575 return promise;
4576 function resolver(value) {
4577 self.resolve(value).then(function (response) {
4578 if (!called) {
4579 called = true;
4580 handlers.resolve(promise, response);
4581 }
4582 }, function (error) {
4583 if (!called) {
4584 called = true;
4585 handlers.reject(promise, error);
4586 }
4587 });
4588 }
4589 }
4590
4591 },{"immediate":36}],38:[function(require,module,exports){
4592 // Top level file is just a mixin of submodules & constants
4593 'use strict';
4594
4595 var assign = require('./lib/utils/common').assign;
4596
4597 var deflate = require('./lib/deflate');
4598 var inflate = require('./lib/inflate');
4599 var constants = require('./lib/zlib/constants');
4600
4601 var pako = {};
4602
4603 assign(pako, deflate, inflate, constants);
4604
4605 module.exports = pako;
4606
4607 },{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(require,module,exports){
4608 'use strict';
4609
4610
4611 var zlib_deflate = require('./zlib/deflate');
4612 var utils = require('./utils/common');
4613 var strings = require('./utils/strings');
4614 var msg = require('./zlib/messages');
4615 var ZStream = require('./zlib/zstream');
4616
4617 var toString = Object.prototype.toString;
4618
4619 /* Public constants ==========================================================*/
4620 /* ===========================================================================*/
4621
4622 var Z_NO_FLUSH = 0;
4623 var Z_FINISH = 4;
4624
4625 var Z_OK = 0;
4626 var Z_STREAM_END = 1;
4627 var Z_SYNC_FLUSH = 2;
4628
4629 var Z_DEFAULT_COMPRESSION = -1;
4630
4631 var Z_DEFAULT_STRATEGY = 0;
4632
4633 var Z_DEFLATED = 8;
4634
4635 /* ===========================================================================*/
4636
4637
4638 /**
4639 * class Deflate
4640 *
4641 * Generic JS-style wrapper for zlib calls. If you don't need
4642 * streaming behaviour - use more simple functions: [[deflate]],
4643 * [[deflateRaw]] and [[gzip]].
4644 **/
4645
4646 /* internal
4647 * Deflate.chunks -> Array
4648 *
4649 * Chunks of output data, if [[Deflate#onData]] not overriden.
4650 **/
4651
4652 /**
4653 * Deflate.result -> Uint8Array|Array
4654 *
4655 * Compressed result, generated by default [[Deflate#onData]]
4656 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
4657 * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
4658 * push a chunk with explicit flush (call [[Deflate#push]] with
4659 * `Z_SYNC_FLUSH` param).
4660 **/
4661
4662 /**
4663 * Deflate.err -> Number
4664 *
4665 * Error code after deflate finished. 0 (Z_OK) on success.
4666 * You will not need it in real life, because deflate errors
4667 * are possible only on wrong options or bad `onData` / `onEnd`
4668 * custom handlers.
4669 **/
4670
4671 /**
4672 * Deflate.msg -> String
4673 *
4674 * Error message, if [[Deflate.err]] != 0
4675 **/
4676
4677
4678 /**
4679 * new Deflate(options)
4680 * - options (Object): zlib deflate options.
4681 *
4682 * Creates new deflator instance with specified params. Throws exception
4683 * on bad params. Supported options:
4684 *
4685 * - `level`
4686 * - `windowBits`
4687 * - `memLevel`
4688 * - `strategy`
4689 * - `dictionary`
4690 *
4691 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
4692 * for more information on these.
4693 *
4694 * Additional options, for internal needs:
4695 *
4696 * - `chunkSize` - size of generated data chunks (16K by default)
4697 * - `raw` (Boolean) - do raw deflate
4698 * - `gzip` (Boolean) - create gzip wrapper
4699 * - `to` (String) - if equal to 'string', then result will be "binary string"
4700 * (each char code [0..255])
4701 * - `header` (Object) - custom header for gzip
4702 * - `text` (Boolean) - true if compressed data believed to be text
4703 * - `time` (Number) - modification time, unix timestamp
4704 * - `os` (Number) - operation system code
4705 * - `extra` (Array) - array of bytes with extra data (max 65536)
4706 * - `name` (String) - file name (binary string)
4707 * - `comment` (String) - comment (binary string)
4708 * - `hcrc` (Boolean) - true if header crc should be added
4709 *
4710 * ##### Example:
4711 *
4712 * ```javascript
4713 * var pako = require('pako')
4714 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
4715 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
4716 *
4717 * var deflate = new pako.Deflate({ level: 3});
4718 *
4719 * deflate.push(chunk1, false);
4720 * deflate.push(chunk2, true); // true -> last chunk
4721 *
4722 * if (deflate.err) { throw new Error(deflate.err); }
4723 *
4724 * console.log(deflate.result);
4725 * ```
4726 **/
4727 function Deflate(options) {
4728 if (!(this instanceof Deflate)) return new Deflate(options);
4729
4730 this.options = utils.assign({
4731 level: Z_DEFAULT_COMPRESSION,
4732 method: Z_DEFLATED,
4733 chunkSize: 16384,
4734 windowBits: 15,
4735 memLevel: 8,
4736 strategy: Z_DEFAULT_STRATEGY,
4737 to: ''
4738 }, options || {});
4739
4740 var opt = this.options;
4741
4742 if (opt.raw && (opt.windowBits > 0)) {
4743 opt.windowBits = -opt.windowBits;
4744 }
4745
4746 else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
4747 opt.windowBits += 16;
4748 }
4749
4750 this.err = 0; // error code, if happens (0 = Z_OK)
4751 this.msg = ''; // error message
4752 this.ended = false; // used to avoid multiple onEnd() calls
4753 this.chunks = []; // chunks of compressed data
4754
4755 this.strm = new ZStream();
4756 this.strm.avail_out = 0;
4757
4758 var status = zlib_deflate.deflateInit2(
4759 this.strm,
4760 opt.level,
4761 opt.method,
4762 opt.windowBits,
4763 opt.memLevel,
4764 opt.strategy
4765 );
4766
4767 if (status !== Z_OK) {
4768 throw new Error(msg[status]);
4769 }
4770
4771 if (opt.header) {
4772 zlib_deflate.deflateSetHeader(this.strm, opt.header);
4773 }
4774
4775 if (opt.dictionary) {
4776 var dict;
4777 // Convert data if needed
4778 if (typeof opt.dictionary === 'string') {
4779 // If we need to compress text, change encoding to utf8.
4780 dict = strings.string2buf(opt.dictionary);
4781 } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
4782 dict = new Uint8Array(opt.dictionary);
4783 } else {
4784 dict = opt.dictionary;
4785 }
4786
4787 status = zlib_deflate.deflateSetDictionary(this.strm, dict);
4788
4789 if (status !== Z_OK) {
4790 throw new Error(msg[status]);
4791 }
4792
4793 this._dict_set = true;
4794 }
4795 }
4796
4797 /**
4798 * Deflate#push(data[, mode]) -> Boolean
4799 * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
4800 * converted to utf8 byte sequence.
4801 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
4802 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
4803 *
4804 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
4805 * new compressed chunks. Returns `true` on success. The last data block must have
4806 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
4807 * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
4808 * can use mode Z_SYNC_FLUSH, keeping the compression context.
4809 *
4810 * On fail call [[Deflate#onEnd]] with error code and return false.
4811 *
4812 * We strongly recommend to use `Uint8Array` on input for best speed (output
4813 * array format is detected automatically). Also, don't skip last param and always
4814 * use the same type in your code (boolean or number). That will improve JS speed.
4815 *
4816 * For regular `Array`-s make sure all elements are [0..255].
4817 *
4818 * ##### Example
4819 *
4820 * ```javascript
4821 * push(chunk, false); // push one of data chunks
4822 * ...
4823 * push(chunk, true); // push last chunk
4824 * ```
4825 **/
4826 Deflate.prototype.push = function (data, mode) {
4827 var strm = this.strm;
4828 var chunkSize = this.options.chunkSize;
4829 var status, _mode;
4830
4831 if (this.ended) { return false; }
4832
4833 _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
4834
4835 // Convert data if needed
4836 if (typeof data === 'string') {
4837 // If we need to compress text, change encoding to utf8.
4838 strm.input = strings.string2buf(data);
4839 } else if (toString.call(data) === '[object ArrayBuffer]') {
4840 strm.input = new Uint8Array(data);
4841 } else {
4842 strm.input = data;
4843 }
4844
4845 strm.next_in = 0;
4846 strm.avail_in = strm.input.length;
4847
4848 do {
4849 if (strm.avail_out === 0) {
4850 strm.output = new utils.Buf8(chunkSize);
4851 strm.next_out = 0;
4852 strm.avail_out = chunkSize;
4853 }
4854 status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
4855
4856 if (status !== Z_STREAM_END && status !== Z_OK) {
4857 this.onEnd(status);
4858 this.ended = true;
4859 return false;
4860 }
4861 if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
4862 if (this.options.to === 'string') {
4863 this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
4864 } else {
4865 this.onData(utils.shrinkBuf(strm.output, strm.next_out));
4866 }
4867 }
4868 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
4869
4870 // Finalize on the last chunk.
4871 if (_mode === Z_FINISH) {
4872 status = zlib_deflate.deflateEnd(this.strm);
4873 this.onEnd(status);
4874 this.ended = true;
4875 return status === Z_OK;
4876 }
4877
4878 // callback interim results if Z_SYNC_FLUSH.
4879 if (_mode === Z_SYNC_FLUSH) {
4880 this.onEnd(Z_OK);
4881 strm.avail_out = 0;
4882 return true;
4883 }
4884
4885 return true;
4886 };
4887
4888
4889 /**
4890 * Deflate#onData(chunk) -> Void
4891 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
4892 * on js engine support. When string output requested, each chunk
4893 * will be string.
4894 *
4895 * By default, stores data blocks in `chunks[]` property and glue
4896 * those in `onEnd`. Override this handler, if you need another behaviour.
4897 **/
4898 Deflate.prototype.onData = function (chunk) {
4899 this.chunks.push(chunk);
4900 };
4901
4902
4903 /**
4904 * Deflate#onEnd(status) -> Void
4905 * - status (Number): deflate status. 0 (Z_OK) on success,
4906 * other if not.
4907 *
4908 * Called once after you tell deflate that the input stream is
4909 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
4910 * or if an error happened. By default - join collected chunks,
4911 * free memory and fill `results` / `err` properties.
4912 **/
4913 Deflate.prototype.onEnd = function (status) {
4914 // On success - join
4915 if (status === Z_OK) {
4916 if (this.options.to === 'string') {
4917 this.result = this.chunks.join('');
4918 } else {
4919 this.result = utils.flattenChunks(this.chunks);
4920 }
4921 }
4922 this.chunks = [];
4923 this.err = status;
4924 this.msg = this.strm.msg;
4925 };
4926
4927
4928 /**
4929 * deflate(data[, options]) -> Uint8Array|Array|String
4930 * - data (Uint8Array|Array|String): input data to compress.
4931 * - options (Object): zlib deflate options.
4932 *
4933 * Compress `data` with deflate algorithm and `options`.
4934 *
4935 * Supported options are:
4936 *
4937 * - level
4938 * - windowBits
4939 * - memLevel
4940 * - strategy
4941 * - dictionary
4942 *
4943 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
4944 * for more information on these.
4945 *
4946 * Sugar (options):
4947 *
4948 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
4949 * negative windowBits implicitly.
4950 * - `to` (String) - if equal to 'string', then result will be "binary string"
4951 * (each char code [0..255])
4952 *
4953 * ##### Example:
4954 *
4955 * ```javascript
4956 * var pako = require('pako')
4957 * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
4958 *
4959 * console.log(pako.deflate(data));
4960 * ```
4961 **/
4962 function deflate(input, options) {
4963 var deflator = new Deflate(options);
4964
4965 deflator.push(input, true);
4966
4967 // That will never happens, if you don't cheat with options :)
4968 if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
4969
4970 return deflator.result;
4971 }
4972
4973
4974 /**
4975 * deflateRaw(data[, options]) -> Uint8Array|Array|String
4976 * - data (Uint8Array|Array|String): input data to compress.
4977 * - options (Object): zlib deflate options.
4978 *
4979 * The same as [[deflate]], but creates raw data, without wrapper
4980 * (header and adler32 crc).
4981 **/
4982 function deflateRaw(input, options) {
4983 options = options || {};
4984 options.raw = true;
4985 return deflate(input, options);
4986 }
4987
4988
4989 /**
4990 * gzip(data[, options]) -> Uint8Array|Array|String
4991 * - data (Uint8Array|Array|String): input data to compress.
4992 * - options (Object): zlib deflate options.
4993 *
4994 * The same as [[deflate]], but create gzip wrapper instead of
4995 * deflate one.
4996 **/
4997 function gzip(input, options) {
4998 options = options || {};
4999 options.gzip = true;
5000 return deflate(input, options);
5001 }
5002
5003
5004 exports.Deflate = Deflate;
5005 exports.deflate = deflate;
5006 exports.deflateRaw = deflateRaw;
5007 exports.gzip = gzip;
5008
5009 },{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(require,module,exports){
5010 'use strict';
5011
5012
5013 var zlib_inflate = require('./zlib/inflate');
5014 var utils = require('./utils/common');
5015 var strings = require('./utils/strings');
5016 var c = require('./zlib/constants');
5017 var msg = require('./zlib/messages');
5018 var ZStream = require('./zlib/zstream');
5019 var GZheader = require('./zlib/gzheader');
5020
5021 var toString = Object.prototype.toString;
5022
5023 /**
5024 * class Inflate
5025 *
5026 * Generic JS-style wrapper for zlib calls. If you don't need
5027 * streaming behaviour - use more simple functions: [[inflate]]
5028 * and [[inflateRaw]].
5029 **/
5030
5031 /* internal
5032 * inflate.chunks -> Array
5033 *
5034 * Chunks of output data, if [[Inflate#onData]] not overriden.
5035 **/
5036
5037 /**
5038 * Inflate.result -> Uint8Array|Array|String
5039 *
5040 * Uncompressed result, generated by default [[Inflate#onData]]
5041 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
5042 * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
5043 * push a chunk with explicit flush (call [[Inflate#push]] with
5044 * `Z_SYNC_FLUSH` param).
5045 **/
5046
5047 /**
5048 * Inflate.err -> Number
5049 *
5050 * Error code after inflate finished. 0 (Z_OK) on success.
5051 * Should be checked if broken data possible.
5052 **/
5053
5054 /**
5055 * Inflate.msg -> String
5056 *
5057 * Error message, if [[Inflate.err]] != 0
5058 **/
5059
5060
5061 /**
5062 * new Inflate(options)
5063 * - options (Object): zlib inflate options.
5064 *
5065 * Creates new inflator instance with specified params. Throws exception
5066 * on bad params. Supported options:
5067 *
5068 * - `windowBits`
5069 * - `dictionary`
5070 *
5071 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
5072 * for more information on these.
5073 *
5074 * Additional options, for internal needs:
5075 *
5076 * - `chunkSize` - size of generated data chunks (16K by default)
5077 * - `raw` (Boolean) - do raw inflate
5078 * - `to` (String) - if equal to 'string', then result will be converted
5079 * from utf8 to utf16 (javascript) string. When string output requested,
5080 * chunk length can differ from `chunkSize`, depending on content.
5081 *
5082 * By default, when no options set, autodetect deflate/gzip data format via
5083 * wrapper header.
5084 *
5085 * ##### Example:
5086 *
5087 * ```javascript
5088 * var pako = require('pako')
5089 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
5090 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
5091 *
5092 * var inflate = new pako.Inflate({ level: 3});
5093 *
5094 * inflate.push(chunk1, false);
5095 * inflate.push(chunk2, true); // true -> last chunk
5096 *
5097 * if (inflate.err) { throw new Error(inflate.err); }
5098 *
5099 * console.log(inflate.result);
5100 * ```
5101 **/
5102 function Inflate(options) {
5103 if (!(this instanceof Inflate)) return new Inflate(options);
5104
5105 this.options = utils.assign({
5106 chunkSize: 16384,
5107 windowBits: 0,
5108 to: ''
5109 }, options || {});
5110
5111 var opt = this.options;
5112
5113 // Force window size for `raw` data, if not set directly,
5114 // because we have no header for autodetect.
5115 if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
5116 opt.windowBits = -opt.windowBits;
5117 if (opt.windowBits === 0) { opt.windowBits = -15; }
5118 }
5119
5120 // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
5121 if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
5122 !(options && options.windowBits)) {
5123 opt.windowBits += 32;
5124 }
5125
5126 // Gzip header has no info about windows size, we can do autodetect only
5127 // for deflate. So, if window size not set, force it to max when gzip possible
5128 if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
5129 // bit 3 (16) -> gzipped data
5130 // bit 4 (32) -> autodetect gzip/deflate
5131 if ((opt.windowBits & 15) === 0) {
5132 opt.windowBits |= 15;
5133 }
5134 }
5135
5136 this.err = 0; // error code, if happens (0 = Z_OK)
5137 this.msg = ''; // error message
5138 this.ended = false; // used to avoid multiple onEnd() calls
5139 this.chunks = []; // chunks of compressed data
5140
5141 this.strm = new ZStream();
5142 this.strm.avail_out = 0;
5143
5144 var status = zlib_inflate.inflateInit2(
5145 this.strm,
5146 opt.windowBits
5147 );
5148
5149 if (status !== c.Z_OK) {
5150 throw new Error(msg[status]);
5151 }
5152
5153 this.header = new GZheader();
5154
5155 zlib_inflate.inflateGetHeader(this.strm, this.header);
5156 }
5157
5158 /**
5159 * Inflate#push(data[, mode]) -> Boolean
5160 * - data (Uint8Array|Array|ArrayBuffer|String): input data
5161 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
5162 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
5163 *
5164 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
5165 * new output chunks. Returns `true` on success. The last data block must have
5166 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
5167 * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
5168 * can use mode Z_SYNC_FLUSH, keeping the decompression context.
5169 *
5170 * On fail call [[Inflate#onEnd]] with error code and return false.
5171 *
5172 * We strongly recommend to use `Uint8Array` on input for best speed (output
5173 * format is detected automatically). Also, don't skip last param and always
5174 * use the same type in your code (boolean or number). That will improve JS speed.
5175 *
5176 * For regular `Array`-s make sure all elements are [0..255].
5177 *
5178 * ##### Example
5179 *
5180 * ```javascript
5181 * push(chunk, false); // push one of data chunks
5182 * ...
5183 * push(chunk, true); // push last chunk
5184 * ```
5185 **/
5186 Inflate.prototype.push = function (data, mode) {
5187 var strm = this.strm;
5188 var chunkSize = this.options.chunkSize;
5189 var dictionary = this.options.dictionary;
5190 var status, _mode;
5191 var next_out_utf8, tail, utf8str;
5192 var dict;
5193
5194 // Flag to properly process Z_BUF_ERROR on testing inflate call
5195 // when we check that all output data was flushed.
5196 var allowBufError = false;
5197
5198 if (this.ended) { return false; }
5199 _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
5200
5201 // Convert data if needed
5202 if (typeof data === 'string') {
5203 // Only binary strings can be decompressed on practice
5204 strm.input = strings.binstring2buf(data);
5205 } else if (toString.call(data) === '[object ArrayBuffer]') {
5206 strm.input = new Uint8Array(data);
5207 } else {
5208 strm.input = data;
5209 }
5210
5211 strm.next_in = 0;
5212 strm.avail_in = strm.input.length;
5213
5214 do {
5215 if (strm.avail_out === 0) {
5216 strm.output = new utils.Buf8(chunkSize);
5217 strm.next_out = 0;
5218 strm.avail_out = chunkSize;
5219 }
5220
5221 status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
5222
5223 if (status === c.Z_NEED_DICT && dictionary) {
5224 // Convert data if needed
5225 if (typeof dictionary === 'string') {
5226 dict = strings.string2buf(dictionary);
5227 } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
5228 dict = new Uint8Array(dictionary);
5229 } else {
5230 dict = dictionary;
5231 }
5232
5233 status = zlib_inflate.inflateSetDictionary(this.strm, dict);
5234
5235 }
5236
5237 if (status === c.Z_BUF_ERROR && allowBufError === true) {
5238 status = c.Z_OK;
5239 allowBufError = false;
5240 }
5241
5242 if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
5243 this.onEnd(status);
5244 this.ended = true;
5245 return false;
5246 }
5247
5248 if (strm.next_out) {
5249 if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
5250
5251 if (this.options.to === 'string') {
5252
5253 next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
5254
5255 tail = strm.next_out - next_out_utf8;
5256 utf8str = strings.buf2string(strm.output, next_out_utf8);
5257
5258 // move tail
5259 strm.next_out = tail;
5260 strm.avail_out = chunkSize - tail;
5261 if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
5262
5263 this.onData(utf8str);
5264
5265 } else {
5266 this.onData(utils.shrinkBuf(strm.output, strm.next_out));
5267 }
5268 }
5269 }
5270
5271 // When no more input data, we should check that internal inflate buffers
5272 // are flushed. The only way to do it when avail_out = 0 - run one more
5273 // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
5274 // Here we set flag to process this error properly.
5275 //
5276 // NOTE. Deflate does not return error in this case and does not needs such
5277 // logic.
5278 if (strm.avail_in === 0 && strm.avail_out === 0) {
5279 allowBufError = true;
5280 }
5281
5282 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
5283
5284 if (status === c.Z_STREAM_END) {
5285 _mode = c.Z_FINISH;
5286 }
5287
5288 // Finalize on the last chunk.
5289 if (_mode === c.Z_FINISH) {
5290 status = zlib_inflate.inflateEnd(this.strm);
5291 this.onEnd(status);
5292 this.ended = true;
5293 return status === c.Z_OK;
5294 }
5295
5296 // callback interim results if Z_SYNC_FLUSH.
5297 if (_mode === c.Z_SYNC_FLUSH) {
5298 this.onEnd(c.Z_OK);
5299 strm.avail_out = 0;
5300 return true;
5301 }
5302
5303 return true;
5304 };
5305
5306
5307 /**
5308 * Inflate#onData(chunk) -> Void
5309 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
5310 * on js engine support. When string output requested, each chunk
5311 * will be string.
5312 *
5313 * By default, stores data blocks in `chunks[]` property and glue
5314 * those in `onEnd`. Override this handler, if you need another behaviour.
5315 **/
5316 Inflate.prototype.onData = function (chunk) {
5317 this.chunks.push(chunk);
5318 };
5319
5320
5321 /**
5322 * Inflate#onEnd(status) -> Void
5323 * - status (Number): inflate status. 0 (Z_OK) on success,
5324 * other if not.
5325 *
5326 * Called either after you tell inflate that the input stream is
5327 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
5328 * or if an error happened. By default - join collected chunks,
5329 * free memory and fill `results` / `err` properties.
5330 **/
5331 Inflate.prototype.onEnd = function (status) {
5332 // On success - join
5333 if (status === c.Z_OK) {
5334 if (this.options.to === 'string') {
5335 // Glue & convert here, until we teach pako to send
5336 // utf8 alligned strings to onData
5337 this.result = this.chunks.join('');
5338 } else {
5339 this.result = utils.flattenChunks(this.chunks);
5340 }
5341 }
5342 this.chunks = [];
5343 this.err = status;
5344 this.msg = this.strm.msg;
5345 };
5346
5347
5348 /**
5349 * inflate(data[, options]) -> Uint8Array|Array|String
5350 * - data (Uint8Array|Array|String): input data to decompress.
5351 * - options (Object): zlib inflate options.
5352 *
5353 * Decompress `data` with inflate/ungzip and `options`. Autodetect
5354 * format via wrapper header by default. That's why we don't provide
5355 * separate `ungzip` method.
5356 *
5357 * Supported options are:
5358 *
5359 * - windowBits
5360 *
5361 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
5362 * for more information.
5363 *
5364 * Sugar (options):
5365 *
5366 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
5367 * negative windowBits implicitly.
5368 * - `to` (String) - if equal to 'string', then result will be converted
5369 * from utf8 to utf16 (javascript) string. When string output requested,
5370 * chunk length can differ from `chunkSize`, depending on content.
5371 *
5372 *
5373 * ##### Example:
5374 *
5375 * ```javascript
5376 * var pako = require('pako')
5377 * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
5378 * , output;
5379 *
5380 * try {
5381 * output = pako.inflate(input);
5382 * } catch (err)
5383 * console.log(err);
5384 * }
5385 * ```
5386 **/
5387 function inflate(input, options) {
5388 var inflator = new Inflate(options);
5389
5390 inflator.push(input, true);
5391
5392 // That will never happens, if you don't cheat with options :)
5393 if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
5394
5395 return inflator.result;
5396 }
5397
5398
5399 /**
5400 * inflateRaw(data[, options]) -> Uint8Array|Array|String
5401 * - data (Uint8Array|Array|String): input data to decompress.
5402 * - options (Object): zlib inflate options.
5403 *
5404 * The same as [[inflate]], but creates raw data, without wrapper
5405 * (header and adler32 crc).
5406 **/
5407 function inflateRaw(input, options) {
5408 options = options || {};
5409 options.raw = true;
5410 return inflate(input, options);
5411 }
5412
5413
5414 /**
5415 * ungzip(data[, options]) -> Uint8Array|Array|String
5416 * - data (Uint8Array|Array|String): input data to decompress.
5417 * - options (Object): zlib inflate options.
5418 *
5419 * Just shortcut to [[inflate]], because it autodetects format
5420 * by header.content. Done for convenience.
5421 **/
5422
5423
5424 exports.Inflate = Inflate;
5425 exports.inflate = inflate;
5426 exports.inflateRaw = inflateRaw;
5427 exports.ungzip = inflate;
5428
5429 },{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(require,module,exports){
5430 'use strict';
5431
5432
5433 var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
5434 (typeof Uint16Array !== 'undefined') &&
5435 (typeof Int32Array !== 'undefined');
5436
5437
5438 exports.assign = function (obj /*from1, from2, from3, ...*/) {
5439 var sources = Array.prototype.slice.call(arguments, 1);
5440 while (sources.length) {
5441 var source = sources.shift();
5442 if (!source) { continue; }
5443
5444 if (typeof source !== 'object') {
5445 throw new TypeError(source + 'must be non-object');
5446 }
5447
5448 for (var p in source) {
5449 if (source.hasOwnProperty(p)) {
5450 obj[p] = source[p];
5451 }
5452 }
5453 }
5454
5455 return obj;
5456 };
5457
5458
5459 // reduce buffer size, avoiding mem copy
5460 exports.shrinkBuf = function (buf, size) {
5461 if (buf.length === size) { return buf; }
5462 if (buf.subarray) { return buf.subarray(0, size); }
5463 buf.length = size;
5464 return buf;
5465 };
5466
5467
5468 var fnTyped = {
5469 arraySet: function (dest, src, src_offs, len, dest_offs) {
5470 if (src.subarray && dest.subarray) {
5471 dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
5472 return;
5473 }
5474 // Fallback to ordinary array
5475 for (var i = 0; i < len; i++) {
5476 dest[dest_offs + i] = src[src_offs + i];
5477 }
5478 },
5479 // Join array of chunks to single array.
5480 flattenChunks: function (chunks) {
5481 var i, l, len, pos, chunk, result;
5482
5483 // calculate data length
5484 len = 0;
5485 for (i = 0, l = chunks.length; i < l; i++) {
5486 len += chunks[i].length;
5487 }
5488
5489 // join chunks
5490 result = new Uint8Array(len);
5491 pos = 0;
5492 for (i = 0, l = chunks.length; i < l; i++) {
5493 chunk = chunks[i];
5494 result.set(chunk, pos);
5495 pos += chunk.length;
5496 }
5497
5498 return result;
5499 }
5500 };
5501
5502 var fnUntyped = {
5503 arraySet: function (dest, src, src_offs, len, dest_offs) {
5504 for (var i = 0; i < len; i++) {
5505 dest[dest_offs + i] = src[src_offs + i];
5506 }
5507 },
5508 // Join array of chunks to single array.
5509 flattenChunks: function (chunks) {
5510 return [].concat.apply([], chunks);
5511 }
5512 };
5513
5514
5515 // Enable/Disable typed arrays use, for testing
5516 //
5517 exports.setTyped = function (on) {
5518 if (on) {
5519 exports.Buf8 = Uint8Array;
5520 exports.Buf16 = Uint16Array;
5521 exports.Buf32 = Int32Array;
5522 exports.assign(exports, fnTyped);
5523 } else {
5524 exports.Buf8 = Array;
5525 exports.Buf16 = Array;
5526 exports.Buf32 = Array;
5527 exports.assign(exports, fnUntyped);
5528 }
5529 };
5530
5531 exports.setTyped(TYPED_OK);
5532
5533 },{}],42:[function(require,module,exports){
5534 // String encode/decode helpers
5535 'use strict';
5536
5537
5538 var utils = require('./common');
5539
5540
5541 // Quick check if we can use fast array to bin string conversion
5542 //
5543 // - apply(Array) can fail on Android 2.2
5544 // - apply(Uint8Array) can fail on iOS 5.1 Safary
5545 //
5546 var STR_APPLY_OK = true;
5547 var STR_APPLY_UIA_OK = true;
5548
5549 try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
5550 try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
5551
5552
5553 // Table with utf8 lengths (calculated by first byte of sequence)
5554 // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
5555 // because max possible codepoint is 0x10ffff
5556 var _utf8len = new utils.Buf8(256);
5557 for (var q = 0; q < 256; q++) {
5558 _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
5559 }
5560 _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
5561
5562
5563 // convert string to array (typed, when possible)
5564 exports.string2buf = function (str) {
5565 var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
5566
5567 // count binary size
5568 for (m_pos = 0; m_pos < str_len; m_pos++) {
5569 c = str.charCodeAt(m_pos);
5570 if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
5571 c2 = str.charCodeAt(m_pos + 1);
5572 if ((c2 & 0xfc00) === 0xdc00) {
5573 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
5574 m_pos++;
5575 }
5576 }
5577 buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
5578 }
5579
5580 // allocate buffer
5581 buf = new utils.Buf8(buf_len);
5582
5583 // convert
5584 for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
5585 c = str.charCodeAt(m_pos);
5586 if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
5587 c2 = str.charCodeAt(m_pos + 1);
5588 if ((c2 & 0xfc00) === 0xdc00) {
5589 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
5590 m_pos++;
5591 }
5592 }
5593 if (c < 0x80) {
5594 /* one byte */
5595 buf[i++] = c;
5596 } else if (c < 0x800) {
5597 /* two bytes */
5598 buf[i++] = 0xC0 | (c >>> 6);
5599 buf[i++] = 0x80 | (c & 0x3f);
5600 } else if (c < 0x10000) {
5601 /* three bytes */
5602 buf[i++] = 0xE0 | (c >>> 12);
5603 buf[i++] = 0x80 | (c >>> 6 & 0x3f);
5604 buf[i++] = 0x80 | (c & 0x3f);
5605 } else {
5606 /* four bytes */
5607 buf[i++] = 0xf0 | (c >>> 18);
5608 buf[i++] = 0x80 | (c >>> 12 & 0x3f);
5609 buf[i++] = 0x80 | (c >>> 6 & 0x3f);
5610 buf[i++] = 0x80 | (c & 0x3f);
5611 }
5612 }
5613
5614 return buf;
5615 };
5616
5617 // Helper (used in 2 places)
5618 function buf2binstring(buf, len) {
5619 // use fallback for big arrays to avoid stack overflow
5620 if (len < 65537) {
5621 if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
5622 return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
5623 }
5624 }
5625
5626 var result = '';
5627 for (var i = 0; i < len; i++) {
5628 result += String.fromCharCode(buf[i]);
5629 }
5630 return result;
5631 }
5632
5633
5634 // Convert byte array to binary string
5635 exports.buf2binstring = function (buf) {
5636 return buf2binstring(buf, buf.length);
5637 };
5638
5639
5640 // Convert binary string (typed, when possible)
5641 exports.binstring2buf = function (str) {
5642 var buf = new utils.Buf8(str.length);
5643 for (var i = 0, len = buf.length; i < len; i++) {
5644 buf[i] = str.charCodeAt(i);
5645 }
5646 return buf;
5647 };
5648
5649
5650 // convert array to string
5651 exports.buf2string = function (buf, max) {
5652 var i, out, c, c_len;
5653 var len = max || buf.length;
5654
5655 // Reserve max possible length (2 words per char)
5656 // NB: by unknown reasons, Array is significantly faster for
5657 // String.fromCharCode.apply than Uint16Array.
5658 var utf16buf = new Array(len * 2);
5659
5660 for (out = 0, i = 0; i < len;) {
5661 c = buf[i++];
5662 // quick process ascii
5663 if (c < 0x80) { utf16buf[out++] = c; continue; }
5664
5665 c_len = _utf8len[c];
5666 // skip 5 & 6 byte codes
5667 if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
5668
5669 // apply mask on first byte
5670 c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
5671 // join the rest
5672 while (c_len > 1 && i < len) {
5673 c = (c << 6) | (buf[i++] & 0x3f);
5674 c_len--;
5675 }
5676
5677 // terminated by end of string?
5678 if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
5679
5680 if (c < 0x10000) {
5681 utf16buf[out++] = c;
5682 } else {
5683 c -= 0x10000;
5684 utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
5685 utf16buf[out++] = 0xdc00 | (c & 0x3ff);
5686 }
5687 }
5688
5689 return buf2binstring(utf16buf, out);
5690 };
5691
5692
5693 // Calculate max possible position in utf8 buffer,
5694 // that will not break sequence. If that's not possible
5695 // - (very small limits) return max size as is.
5696 //
5697 // buf[] - utf8 bytes array
5698 // max - length limit (mandatory);
5699 exports.utf8border = function (buf, max) {
5700 var pos;
5701
5702 max = max || buf.length;
5703 if (max > buf.length) { max = buf.length; }
5704
5705 // go back from last position, until start of sequence found
5706 pos = max - 1;
5707 while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
5708
5709 // Fuckup - very small and broken sequence,
5710 // return max, because we should return something anyway.
5711 if (pos < 0) { return max; }
5712
5713 // If we came to start of buffer - that means vuffer is too small,
5714 // return max too.
5715 if (pos === 0) { return max; }
5716
5717 return (pos + _utf8len[buf[pos]] > max) ? pos : max;
5718 };
5719
5720 },{"./common":41}],43:[function(require,module,exports){
5721 'use strict';
5722
5723 // Note: adler32 takes 12% for level 0 and 2% for level 6.
5724 // It doesn't worth to make additional optimizationa as in original.
5725 // Small size is preferable.
5726
5727 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
5728 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
5729 //
5730 // This software is provided 'as-is', without any express or implied
5731 // warranty. In no event will the authors be held liable for any damages
5732 // arising from the use of this software.
5733 //
5734 // Permission is granted to anyone to use this software for any purpose,
5735 // including commercial applications, and to alter it and redistribute it
5736 // freely, subject to the following restrictions:
5737 //
5738 // 1. The origin of this software must not be misrepresented; you must not
5739 // claim that you wrote the original software. If you use this software
5740 // in a product, an acknowledgment in the product documentation would be
5741 // appreciated but is not required.
5742 // 2. Altered source versions must be plainly marked as such, and must not be
5743 // misrepresented as being the original software.
5744 // 3. This notice may not be removed or altered from any source distribution.
5745
5746 function adler32(adler, buf, len, pos) {
5747 var s1 = (adler & 0xffff) |0,
5748 s2 = ((adler >>> 16) & 0xffff) |0,
5749 n = 0;
5750
5751 while (len !== 0) {
5752 // Set limit ~ twice less than 5552, to keep
5753 // s2 in 31-bits, because we force signed ints.
5754 // in other case %= will fail.
5755 n = len > 2000 ? 2000 : len;
5756 len -= n;
5757
5758 do {
5759 s1 = (s1 + buf[pos++]) |0;
5760 s2 = (s2 + s1) |0;
5761 } while (--n);
5762
5763 s1 %= 65521;
5764 s2 %= 65521;
5765 }
5766
5767 return (s1 | (s2 << 16)) |0;
5768 }
5769
5770
5771 module.exports = adler32;
5772
5773 },{}],44:[function(require,module,exports){
5774 'use strict';
5775
5776 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
5777 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
5778 //
5779 // This software is provided 'as-is', without any express or implied
5780 // warranty. In no event will the authors be held liable for any damages
5781 // arising from the use of this software.
5782 //
5783 // Permission is granted to anyone to use this software for any purpose,
5784 // including commercial applications, and to alter it and redistribute it
5785 // freely, subject to the following restrictions:
5786 //
5787 // 1. The origin of this software must not be misrepresented; you must not
5788 // claim that you wrote the original software. If you use this software
5789 // in a product, an acknowledgment in the product documentation would be
5790 // appreciated but is not required.
5791 // 2. Altered source versions must be plainly marked as such, and must not be
5792 // misrepresented as being the original software.
5793 // 3. This notice may not be removed or altered from any source distribution.
5794
5795 module.exports = {
5796
5797 /* Allowed flush values; see deflate() and inflate() below for details */
5798 Z_NO_FLUSH: 0,
5799 Z_PARTIAL_FLUSH: 1,
5800 Z_SYNC_FLUSH: 2,
5801 Z_FULL_FLUSH: 3,
5802 Z_FINISH: 4,
5803 Z_BLOCK: 5,
5804 Z_TREES: 6,
5805
5806 /* Return codes for the compression/decompression functions. Negative values
5807 * are errors, positive values are used for special but normal events.
5808 */
5809 Z_OK: 0,
5810 Z_STREAM_END: 1,
5811 Z_NEED_DICT: 2,
5812 Z_ERRNO: -1,
5813 Z_STREAM_ERROR: -2,
5814 Z_DATA_ERROR: -3,
5815 //Z_MEM_ERROR: -4,
5816 Z_BUF_ERROR: -5,
5817 //Z_VERSION_ERROR: -6,
5818
5819 /* compression levels */
5820 Z_NO_COMPRESSION: 0,
5821 Z_BEST_SPEED: 1,
5822 Z_BEST_COMPRESSION: 9,
5823 Z_DEFAULT_COMPRESSION: -1,
5824
5825
5826 Z_FILTERED: 1,
5827 Z_HUFFMAN_ONLY: 2,
5828 Z_RLE: 3,
5829 Z_FIXED: 4,
5830 Z_DEFAULT_STRATEGY: 0,
5831
5832 /* Possible values of the data_type field (though see inflate()) */
5833 Z_BINARY: 0,
5834 Z_TEXT: 1,
5835 //Z_ASCII: 1, // = Z_TEXT (deprecated)
5836 Z_UNKNOWN: 2,
5837
5838 /* The deflate compression method */
5839 Z_DEFLATED: 8
5840 //Z_NULL: null // Use -1 or null inline, depending on var type
5841 };
5842
5843 },{}],45:[function(require,module,exports){
5844 'use strict';
5845
5846 // Note: we can't get significant speed boost here.
5847 // So write code to minimize size - no pregenerated tables
5848 // and array tools dependencies.
5849
5850 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
5851 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
5852 //
5853 // This software is provided 'as-is', without any express or implied
5854 // warranty. In no event will the authors be held liable for any damages
5855 // arising from the use of this software.
5856 //
5857 // Permission is granted to anyone to use this software for any purpose,
5858 // including commercial applications, and to alter it and redistribute it
5859 // freely, subject to the following restrictions:
5860 //
5861 // 1. The origin of this software must not be misrepresented; you must not
5862 // claim that you wrote the original software. If you use this software
5863 // in a product, an acknowledgment in the product documentation would be
5864 // appreciated but is not required.
5865 // 2. Altered source versions must be plainly marked as such, and must not be
5866 // misrepresented as being the original software.
5867 // 3. This notice may not be removed or altered from any source distribution.
5868
5869 // Use ordinary array, since untyped makes no boost here
5870 function makeTable() {
5871 var c, table = [];
5872
5873 for (var n = 0; n < 256; n++) {
5874 c = n;
5875 for (var k = 0; k < 8; k++) {
5876 c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
5877 }
5878 table[n] = c;
5879 }
5880
5881 return table;
5882 }
5883
5884 // Create table on load. Just 255 signed longs. Not a problem.
5885 var crcTable = makeTable();
5886
5887
5888 function crc32(crc, buf, len, pos) {
5889 var t = crcTable,
5890 end = pos + len;
5891
5892 crc ^= -1;
5893
5894 for (var i = pos; i < end; i++) {
5895 crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
5896 }
5897
5898 return (crc ^ (-1)); // >>> 0;
5899 }
5900
5901
5902 module.exports = crc32;
5903
5904 },{}],46:[function(require,module,exports){
5905 'use strict';
5906
5907 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
5908 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
5909 //
5910 // This software is provided 'as-is', without any express or implied
5911 // warranty. In no event will the authors be held liable for any damages
5912 // arising from the use of this software.
5913 //
5914 // Permission is granted to anyone to use this software for any purpose,
5915 // including commercial applications, and to alter it and redistribute it
5916 // freely, subject to the following restrictions:
5917 //
5918 // 1. The origin of this software must not be misrepresented; you must not
5919 // claim that you wrote the original software. If you use this software
5920 // in a product, an acknowledgment in the product documentation would be
5921 // appreciated but is not required.
5922 // 2. Altered source versions must be plainly marked as such, and must not be
5923 // misrepresented as being the original software.
5924 // 3. This notice may not be removed or altered from any source distribution.
5925
5926 var utils = require('../utils/common');
5927 var trees = require('./trees');
5928 var adler32 = require('./adler32');
5929 var crc32 = require('./crc32');
5930 var msg = require('./messages');
5931
5932 /* Public constants ==========================================================*/
5933 /* ===========================================================================*/
5934
5935
5936 /* Allowed flush values; see deflate() and inflate() below for details */
5937 var Z_NO_FLUSH = 0;
5938 var Z_PARTIAL_FLUSH = 1;
5939 //var Z_SYNC_FLUSH = 2;
5940 var Z_FULL_FLUSH = 3;
5941 var Z_FINISH = 4;
5942 var Z_BLOCK = 5;
5943 //var Z_TREES = 6;
5944
5945
5946 /* Return codes for the compression/decompression functions. Negative values
5947 * are errors, positive values are used for special but normal events.
5948 */
5949 var Z_OK = 0;
5950 var Z_STREAM_END = 1;
5951 //var Z_NEED_DICT = 2;
5952 //var Z_ERRNO = -1;
5953 var Z_STREAM_ERROR = -2;
5954 var Z_DATA_ERROR = -3;
5955 //var Z_MEM_ERROR = -4;
5956 var Z_BUF_ERROR = -5;
5957 //var Z_VERSION_ERROR = -6;
5958
5959
5960 /* compression levels */
5961 //var Z_NO_COMPRESSION = 0;
5962 //var Z_BEST_SPEED = 1;
5963 //var Z_BEST_COMPRESSION = 9;
5964 var Z_DEFAULT_COMPRESSION = -1;
5965
5966
5967 var Z_FILTERED = 1;
5968 var Z_HUFFMAN_ONLY = 2;
5969 var Z_RLE = 3;
5970 var Z_FIXED = 4;
5971 var Z_DEFAULT_STRATEGY = 0;
5972
5973 /* Possible values of the data_type field (though see inflate()) */
5974 //var Z_BINARY = 0;
5975 //var Z_TEXT = 1;
5976 //var Z_ASCII = 1; // = Z_TEXT
5977 var Z_UNKNOWN = 2;
5978
5979
5980 /* The deflate compression method */
5981 var Z_DEFLATED = 8;
5982
5983 /*============================================================================*/
5984
5985
5986 var MAX_MEM_LEVEL = 9;
5987 /* Maximum value for memLevel in deflateInit2 */
5988 var MAX_WBITS = 15;
5989 /* 32K LZ77 window */
5990 var DEF_MEM_LEVEL = 8;
5991
5992
5993 var LENGTH_CODES = 29;
5994 /* number of length codes, not counting the special END_BLOCK code */
5995 var LITERALS = 256;
5996 /* number of literal bytes 0..255 */
5997 var L_CODES = LITERALS + 1 + LENGTH_CODES;
5998 /* number of Literal or Length codes, including the END_BLOCK code */
5999 var D_CODES = 30;
6000 /* number of distance codes */
6001 var BL_CODES = 19;
6002 /* number of codes used to transfer the bit lengths */
6003 var HEAP_SIZE = 2 * L_CODES + 1;
6004 /* maximum heap size */
6005 var MAX_BITS = 15;
6006 /* All codes must not exceed MAX_BITS bits */
6007
6008 var MIN_MATCH = 3;
6009 var MAX_MATCH = 258;
6010 var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
6011
6012 var PRESET_DICT = 0x20;
6013
6014 var INIT_STATE = 42;
6015 var EXTRA_STATE = 69;
6016 var NAME_STATE = 73;
6017 var COMMENT_STATE = 91;
6018 var HCRC_STATE = 103;
6019 var BUSY_STATE = 113;
6020 var FINISH_STATE = 666;
6021
6022 var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
6023 var BS_BLOCK_DONE = 2; /* block flush performed */
6024 var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
6025 var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
6026
6027 var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
6028
6029 function err(strm, errorCode) {
6030 strm.msg = msg[errorCode];
6031 return errorCode;
6032 }
6033
6034 function rank(f) {
6035 return ((f) << 1) - ((f) > 4 ? 9 : 0);
6036 }
6037
6038 function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
6039
6040
6041 /* =========================================================================
6042 * Flush as much pending output as possible. All deflate() output goes
6043 * through this function so some applications may wish to modify it
6044 * to avoid allocating a large strm->output buffer and copying into it.
6045 * (See also read_buf()).
6046 */
6047 function flush_pending(strm) {
6048 var s = strm.state;
6049
6050 //_tr_flush_bits(s);
6051 var len = s.pending;
6052 if (len > strm.avail_out) {
6053 len = strm.avail_out;
6054 }
6055 if (len === 0) { return; }
6056
6057 utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
6058 strm.next_out += len;
6059 s.pending_out += len;
6060 strm.total_out += len;
6061 strm.avail_out -= len;
6062 s.pending -= len;
6063 if (s.pending === 0) {
6064 s.pending_out = 0;
6065 }
6066 }
6067
6068
6069 function flush_block_only(s, last) {
6070 trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
6071 s.block_start = s.strstart;
6072 flush_pending(s.strm);
6073 }
6074
6075
6076 function put_byte(s, b) {
6077 s.pending_buf[s.pending++] = b;
6078 }
6079
6080
6081 /* =========================================================================
6082 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
6083 * IN assertion: the stream state is correct and there is enough room in
6084 * pending_buf.
6085 */
6086 function putShortMSB(s, b) {
6087 // put_byte(s, (Byte)(b >> 8));
6088 // put_byte(s, (Byte)(b & 0xff));
6089 s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
6090 s.pending_buf[s.pending++] = b & 0xff;
6091 }
6092
6093
6094 /* ===========================================================================
6095 * Read a new buffer from the current input stream, update the adler32
6096 * and total number of bytes read. All deflate() input goes through
6097 * this function so some applications may wish to modify it to avoid
6098 * allocating a large strm->input buffer and copying from it.
6099 * (See also flush_pending()).
6100 */
6101 function read_buf(strm, buf, start, size) {
6102 var len = strm.avail_in;
6103
6104 if (len > size) { len = size; }
6105 if (len === 0) { return 0; }
6106
6107 strm.avail_in -= len;
6108
6109 // zmemcpy(buf, strm->next_in, len);
6110 utils.arraySet(buf, strm.input, strm.next_in, len, start);
6111 if (strm.state.wrap === 1) {
6112 strm.adler = adler32(strm.adler, buf, len, start);
6113 }
6114
6115 else if (strm.state.wrap === 2) {
6116 strm.adler = crc32(strm.adler, buf, len, start);
6117 }
6118
6119 strm.next_in += len;
6120 strm.total_in += len;
6121
6122 return len;
6123 }
6124
6125
6126 /* ===========================================================================
6127 * Set match_start to the longest match starting at the given string and
6128 * return its length. Matches shorter or equal to prev_length are discarded,
6129 * in which case the result is equal to prev_length and match_start is
6130 * garbage.
6131 * IN assertions: cur_match is the head of the hash chain for the current
6132 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
6133 * OUT assertion: the match length is not greater than s->lookahead.
6134 */
6135 function longest_match(s, cur_match) {
6136 var chain_length = s.max_chain_length; /* max hash chain length */
6137 var scan = s.strstart; /* current string */
6138 var match; /* matched string */
6139 var len; /* length of current match */
6140 var best_len = s.prev_length; /* best match length so far */
6141 var nice_match = s.nice_match; /* stop if match long enough */
6142 var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
6143 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
6144
6145 var _win = s.window; // shortcut
6146
6147 var wmask = s.w_mask;
6148 var prev = s.prev;
6149
6150 /* Stop when cur_match becomes <= limit. To simplify the code,
6151 * we prevent matches with the string of window index 0.
6152 */
6153
6154 var strend = s.strstart + MAX_MATCH;
6155 var scan_end1 = _win[scan + best_len - 1];
6156 var scan_end = _win[scan + best_len];
6157
6158 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
6159 * It is easy to get rid of this optimization if necessary.
6160 */
6161 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
6162
6163 /* Do not waste too much time if we already have a good match: */
6164 if (s.prev_length >= s.good_match) {
6165 chain_length >>= 2;
6166 }
6167 /* Do not look for matches beyond the end of the input. This is necessary
6168 * to make deflate deterministic.
6169 */
6170 if (nice_match > s.lookahead) { nice_match = s.lookahead; }
6171
6172 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
6173
6174 do {
6175 // Assert(cur_match < s->strstart, "no future");
6176 match = cur_match;
6177
6178 /* Skip to next match if the match length cannot increase
6179 * or if the match length is less than 2. Note that the checks below
6180 * for insufficient lookahead only occur occasionally for performance
6181 * reasons. Therefore uninitialized memory will be accessed, and
6182 * conditional jumps will be made that depend on those values.
6183 * However the length of the match is limited to the lookahead, so
6184 * the output of deflate is not affected by the uninitialized values.
6185 */
6186
6187 if (_win[match + best_len] !== scan_end ||
6188 _win[match + best_len - 1] !== scan_end1 ||
6189 _win[match] !== _win[scan] ||
6190 _win[++match] !== _win[scan + 1]) {
6191 continue;
6192 }
6193
6194 /* The check at best_len-1 can be removed because it will be made
6195 * again later. (This heuristic is not always a win.)
6196 * It is not necessary to compare scan[2] and match[2] since they
6197 * are always equal when the other bytes match, given that
6198 * the hash keys are equal and that HASH_BITS >= 8.
6199 */
6200 scan += 2;
6201 match++;
6202 // Assert(*scan == *match, "match[2]?");
6203
6204 /* We check for insufficient lookahead only every 8th comparison;
6205 * the 256th check will be made at strstart+258.
6206 */
6207 do {
6208 /*jshint noempty:false*/
6209 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
6210 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
6211 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
6212 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
6213 scan < strend);
6214
6215 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
6216
6217 len = MAX_MATCH - (strend - scan);
6218 scan = strend - MAX_MATCH;
6219
6220 if (len > best_len) {
6221 s.match_start = cur_match;
6222 best_len = len;
6223 if (len >= nice_match) {
6224 break;
6225 }
6226 scan_end1 = _win[scan + best_len - 1];
6227 scan_end = _win[scan + best_len];
6228 }
6229 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
6230
6231 if (best_len <= s.lookahead) {
6232 return best_len;
6233 }
6234 return s.lookahead;
6235 }
6236
6237
6238 /* ===========================================================================
6239 * Fill the window when the lookahead becomes insufficient.
6240 * Updates strstart and lookahead.
6241 *
6242 * IN assertion: lookahead < MIN_LOOKAHEAD
6243 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
6244 * At least one byte has been read, or avail_in == 0; reads are
6245 * performed for at least two bytes (required for the zip translate_eol
6246 * option -- not supported here).
6247 */
6248 function fill_window(s) {
6249 var _w_size = s.w_size;
6250 var p, n, m, more, str;
6251
6252 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
6253
6254 do {
6255 more = s.window_size - s.lookahead - s.strstart;
6256
6257 // JS ints have 32 bit, block below not needed
6258 /* Deal with !@#$% 64K limit: */
6259 //if (sizeof(int) <= 2) {
6260 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
6261 // more = wsize;
6262 //
6263 // } else if (more == (unsigned)(-1)) {
6264 // /* Very unlikely, but possible on 16 bit machine if
6265 // * strstart == 0 && lookahead == 1 (input done a byte at time)
6266 // */
6267 // more--;
6268 // }
6269 //}
6270
6271
6272 /* If the window is almost full and there is insufficient lookahead,
6273 * move the upper half to the lower one to make room in the upper half.
6274 */
6275 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
6276
6277 utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
6278 s.match_start -= _w_size;
6279 s.strstart -= _w_size;
6280 /* we now have strstart >= MAX_DIST */
6281 s.block_start -= _w_size;
6282
6283 /* Slide the hash table (could be avoided with 32 bit values
6284 at the expense of memory usage). We slide even when level == 0
6285 to keep the hash table consistent if we switch back to level > 0
6286 later. (Using level 0 permanently is not an optimal usage of
6287 zlib, so we don't care about this pathological case.)
6288 */
6289
6290 n = s.hash_size;
6291 p = n;
6292 do {
6293 m = s.head[--p];
6294 s.head[p] = (m >= _w_size ? m - _w_size : 0);
6295 } while (--n);
6296
6297 n = _w_size;
6298 p = n;
6299 do {
6300 m = s.prev[--p];
6301 s.prev[p] = (m >= _w_size ? m - _w_size : 0);
6302 /* If n is not on any hash chain, prev[n] is garbage but
6303 * its value will never be used.
6304 */
6305 } while (--n);
6306
6307 more += _w_size;
6308 }
6309 if (s.strm.avail_in === 0) {
6310 break;
6311 }
6312
6313 /* If there was no sliding:
6314 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
6315 * more == window_size - lookahead - strstart
6316 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
6317 * => more >= window_size - 2*WSIZE + 2
6318 * In the BIG_MEM or MMAP case (not yet supported),
6319 * window_size == input_size + MIN_LOOKAHEAD &&
6320 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
6321 * Otherwise, window_size == 2*WSIZE so more >= 2.
6322 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
6323 */
6324 //Assert(more >= 2, "more < 2");
6325 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
6326 s.lookahead += n;
6327
6328 /* Initialize the hash value now that we have some input: */
6329 if (s.lookahead + s.insert >= MIN_MATCH) {
6330 str = s.strstart - s.insert;
6331 s.ins_h = s.window[str];
6332
6333 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
6334 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
6335 //#if MIN_MATCH != 3
6336 // Call update_hash() MIN_MATCH-3 more times
6337 //#endif
6338 while (s.insert) {
6339 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
6340 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
6341
6342 s.prev[str & s.w_mask] = s.head[s.ins_h];
6343 s.head[s.ins_h] = str;
6344 str++;
6345 s.insert--;
6346 if (s.lookahead + s.insert < MIN_MATCH) {
6347 break;
6348 }
6349 }
6350 }
6351 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
6352 * but this is not important since only literal bytes will be emitted.
6353 */
6354
6355 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
6356
6357 /* If the WIN_INIT bytes after the end of the current data have never been
6358 * written, then zero those bytes in order to avoid memory check reports of
6359 * the use of uninitialized (or uninitialised as Julian writes) bytes by
6360 * the longest match routines. Update the high water mark for the next
6361 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
6362 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
6363 */
6364 // if (s.high_water < s.window_size) {
6365 // var curr = s.strstart + s.lookahead;
6366 // var init = 0;
6367 //
6368 // if (s.high_water < curr) {
6369 // /* Previous high water mark below current data -- zero WIN_INIT
6370 // * bytes or up to end of window, whichever is less.
6371 // */
6372 // init = s.window_size - curr;
6373 // if (init > WIN_INIT)
6374 // init = WIN_INIT;
6375 // zmemzero(s->window + curr, (unsigned)init);
6376 // s->high_water = curr + init;
6377 // }
6378 // else if (s->high_water < (ulg)curr + WIN_INIT) {
6379 // /* High water mark at or above current data, but below current data
6380 // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
6381 // * to end of window, whichever is less.
6382 // */
6383 // init = (ulg)curr + WIN_INIT - s->high_water;
6384 // if (init > s->window_size - s->high_water)
6385 // init = s->window_size - s->high_water;
6386 // zmemzero(s->window + s->high_water, (unsigned)init);
6387 // s->high_water += init;
6388 // }
6389 // }
6390 //
6391 // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
6392 // "not enough room for search");
6393 }
6394
6395 /* ===========================================================================
6396 * Copy without compression as much as possible from the input stream, return
6397 * the current block state.
6398 * This function does not insert new strings in the dictionary since
6399 * uncompressible data is probably not useful. This function is used
6400 * only for the level=0 compression option.
6401 * NOTE: this function should be optimized to avoid extra copying from
6402 * window to pending_buf.
6403 */
6404 function deflate_stored(s, flush) {
6405 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
6406 * to pending_buf_size, and each stored block has a 5 byte header:
6407 */
6408 var max_block_size = 0xffff;
6409
6410 if (max_block_size > s.pending_buf_size - 5) {
6411 max_block_size = s.pending_buf_size - 5;
6412 }
6413
6414 /* Copy as much as possible from input to output: */
6415 for (;;) {
6416 /* Fill the window as much as possible: */
6417 if (s.lookahead <= 1) {
6418
6419 //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
6420 // s->block_start >= (long)s->w_size, "slide too late");
6421 // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
6422 // s.block_start >= s.w_size)) {
6423 // throw new Error("slide too late");
6424 // }
6425
6426 fill_window(s);
6427 if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
6428 return BS_NEED_MORE;
6429 }
6430
6431 if (s.lookahead === 0) {
6432 break;
6433 }
6434 /* flush the current block */
6435 }
6436 //Assert(s->block_start >= 0L, "block gone");
6437 // if (s.block_start < 0) throw new Error("block gone");
6438
6439 s.strstart += s.lookahead;
6440 s.lookahead = 0;
6441
6442 /* Emit a stored block if pending_buf will be full: */
6443 var max_start = s.block_start + max_block_size;
6444
6445 if (s.strstart === 0 || s.strstart >= max_start) {
6446 /* strstart == 0 is possible when wraparound on 16-bit machine */
6447 s.lookahead = s.strstart - max_start;
6448 s.strstart = max_start;
6449 /*** FLUSH_BLOCK(s, 0); ***/
6450 flush_block_only(s, false);
6451 if (s.strm.avail_out === 0) {
6452 return BS_NEED_MORE;
6453 }
6454 /***/
6455
6456
6457 }
6458 /* Flush if we may have to slide, otherwise block_start may become
6459 * negative and the data will be gone:
6460 */
6461 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
6462 /*** FLUSH_BLOCK(s, 0); ***/
6463 flush_block_only(s, false);
6464 if (s.strm.avail_out === 0) {
6465 return BS_NEED_MORE;
6466 }
6467 /***/
6468 }
6469 }
6470
6471 s.insert = 0;
6472
6473 if (flush === Z_FINISH) {
6474 /*** FLUSH_BLOCK(s, 1); ***/
6475 flush_block_only(s, true);
6476 if (s.strm.avail_out === 0) {
6477 return BS_FINISH_STARTED;
6478 }
6479 /***/
6480 return BS_FINISH_DONE;
6481 }
6482
6483 if (s.strstart > s.block_start) {
6484 /*** FLUSH_BLOCK(s, 0); ***/
6485 flush_block_only(s, false);
6486 if (s.strm.avail_out === 0) {
6487 return BS_NEED_MORE;
6488 }
6489 /***/
6490 }
6491
6492 return BS_NEED_MORE;
6493 }
6494
6495 /* ===========================================================================
6496 * Compress as much as possible from the input stream, return the current
6497 * block state.
6498 * This function does not perform lazy evaluation of matches and inserts
6499 * new strings in the dictionary only for unmatched strings or for short
6500 * matches. It is used only for the fast compression options.
6501 */
6502 function deflate_fast(s, flush) {
6503 var hash_head; /* head of the hash chain */
6504 var bflush; /* set if current block must be flushed */
6505
6506 for (;;) {
6507 /* Make sure that we always have enough lookahead, except
6508 * at the end of the input file. We need MAX_MATCH bytes
6509 * for the next match, plus MIN_MATCH bytes to insert the
6510 * string following the next match.
6511 */
6512 if (s.lookahead < MIN_LOOKAHEAD) {
6513 fill_window(s);
6514 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
6515 return BS_NEED_MORE;
6516 }
6517 if (s.lookahead === 0) {
6518 break; /* flush the current block */
6519 }
6520 }
6521
6522 /* Insert the string window[strstart .. strstart+2] in the
6523 * dictionary, and set hash_head to the head of the hash chain:
6524 */
6525 hash_head = 0/*NIL*/;
6526 if (s.lookahead >= MIN_MATCH) {
6527 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
6528 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
6529 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
6530 s.head[s.ins_h] = s.strstart;
6531 /***/
6532 }
6533
6534 /* Find the longest match, discarding those <= prev_length.
6535 * At this point we have always match_length < MIN_MATCH
6536 */
6537 if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
6538 /* To simplify the code, we prevent matches with the string
6539 * of window index 0 (in particular we have to avoid a match
6540 * of the string with itself at the start of the input file).
6541 */
6542 s.match_length = longest_match(s, hash_head);
6543 /* longest_match() sets match_start */
6544 }
6545 if (s.match_length >= MIN_MATCH) {
6546 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
6547
6548 /*** _tr_tally_dist(s, s.strstart - s.match_start,
6549 s.match_length - MIN_MATCH, bflush); ***/
6550 bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
6551
6552 s.lookahead -= s.match_length;
6553
6554 /* Insert new strings in the hash table only if the match length
6555 * is not too large. This saves time but degrades compression.
6556 */
6557 if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
6558 s.match_length--; /* string at strstart already in table */
6559 do {
6560 s.strstart++;
6561 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
6562 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
6563 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
6564 s.head[s.ins_h] = s.strstart;
6565 /***/
6566 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
6567 * always MIN_MATCH bytes ahead.
6568 */
6569 } while (--s.match_length !== 0);
6570 s.strstart++;
6571 } else
6572 {
6573 s.strstart += s.match_length;
6574 s.match_length = 0;
6575 s.ins_h = s.window[s.strstart];
6576 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
6577 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
6578
6579 //#if MIN_MATCH != 3
6580 // Call UPDATE_HASH() MIN_MATCH-3 more times
6581 //#endif
6582 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
6583 * matter since it will be recomputed at next deflate call.
6584 */
6585 }
6586 } else {
6587 /* No match, output a literal byte */
6588 //Tracevv((stderr,"%c", s.window[s.strstart]));
6589 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
6590 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
6591
6592 s.lookahead--;
6593 s.strstart++;
6594 }
6595 if (bflush) {
6596 /*** FLUSH_BLOCK(s, 0); ***/
6597 flush_block_only(s, false);
6598 if (s.strm.avail_out === 0) {
6599 return BS_NEED_MORE;
6600 }
6601 /***/
6602 }
6603 }
6604 s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
6605 if (flush === Z_FINISH) {
6606 /*** FLUSH_BLOCK(s, 1); ***/
6607 flush_block_only(s, true);
6608 if (s.strm.avail_out === 0) {
6609 return BS_FINISH_STARTED;
6610 }
6611 /***/
6612 return BS_FINISH_DONE;
6613 }
6614 if (s.last_lit) {
6615 /*** FLUSH_BLOCK(s, 0); ***/
6616 flush_block_only(s, false);
6617 if (s.strm.avail_out === 0) {
6618 return BS_NEED_MORE;
6619 }
6620 /***/
6621 }
6622 return BS_BLOCK_DONE;
6623 }
6624
6625 /* ===========================================================================
6626 * Same as above, but achieves better compression. We use a lazy
6627 * evaluation for matches: a match is finally adopted only if there is
6628 * no better match at the next window position.
6629 */
6630 function deflate_slow(s, flush) {
6631 var hash_head; /* head of hash chain */
6632 var bflush; /* set if current block must be flushed */
6633
6634 var max_insert;
6635
6636 /* Process the input block. */
6637 for (;;) {
6638 /* Make sure that we always have enough lookahead, except
6639 * at the end of the input file. We need MAX_MATCH bytes
6640 * for the next match, plus MIN_MATCH bytes to insert the
6641 * string following the next match.
6642 */
6643 if (s.lookahead < MIN_LOOKAHEAD) {
6644 fill_window(s);
6645 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
6646 return BS_NEED_MORE;
6647 }
6648 if (s.lookahead === 0) { break; } /* flush the current block */
6649 }
6650
6651 /* Insert the string window[strstart .. strstart+2] in the
6652 * dictionary, and set hash_head to the head of the hash chain:
6653 */
6654 hash_head = 0/*NIL*/;
6655 if (s.lookahead >= MIN_MATCH) {
6656 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
6657 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
6658 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
6659 s.head[s.ins_h] = s.strstart;
6660 /***/
6661 }
6662
6663 /* Find the longest match, discarding those <= prev_length.
6664 */
6665 s.prev_length = s.match_length;
6666 s.prev_match = s.match_start;
6667 s.match_length = MIN_MATCH - 1;
6668
6669 if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
6670 s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
6671 /* To simplify the code, we prevent matches with the string
6672 * of window index 0 (in particular we have to avoid a match
6673 * of the string with itself at the start of the input file).
6674 */
6675 s.match_length = longest_match(s, hash_head);
6676 /* longest_match() sets match_start */
6677
6678 if (s.match_length <= 5 &&
6679 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
6680
6681 /* If prev_match is also MIN_MATCH, match_start is garbage
6682 * but we will ignore the current match anyway.
6683 */
6684 s.match_length = MIN_MATCH - 1;
6685 }
6686 }
6687 /* If there was a match at the previous step and the current
6688 * match is not better, output the previous match:
6689 */
6690 if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
6691 max_insert = s.strstart + s.lookahead - MIN_MATCH;
6692 /* Do not insert strings in hash table beyond this. */
6693
6694 //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
6695
6696 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
6697 s.prev_length - MIN_MATCH, bflush);***/
6698 bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
6699 /* Insert in hash table all strings up to the end of the match.
6700 * strstart-1 and strstart are already inserted. If there is not
6701 * enough lookahead, the last two strings are not inserted in
6702 * the hash table.
6703 */
6704 s.lookahead -= s.prev_length - 1;
6705 s.prev_length -= 2;
6706 do {
6707 if (++s.strstart <= max_insert) {
6708 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
6709 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
6710 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
6711 s.head[s.ins_h] = s.strstart;
6712 /***/
6713 }
6714 } while (--s.prev_length !== 0);
6715 s.match_available = 0;
6716 s.match_length = MIN_MATCH - 1;
6717 s.strstart++;
6718
6719 if (bflush) {
6720 /*** FLUSH_BLOCK(s, 0); ***/
6721 flush_block_only(s, false);
6722 if (s.strm.avail_out === 0) {
6723 return BS_NEED_MORE;
6724 }
6725 /***/
6726 }
6727
6728 } else if (s.match_available) {
6729 /* If there was no match at the previous position, output a
6730 * single literal. If there was a match but the current match
6731 * is longer, truncate the previous match to a single literal.
6732 */
6733 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
6734 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
6735 bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
6736
6737 if (bflush) {
6738 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
6739 flush_block_only(s, false);
6740 /***/
6741 }
6742 s.strstart++;
6743 s.lookahead--;
6744 if (s.strm.avail_out === 0) {
6745 return BS_NEED_MORE;
6746 }
6747 } else {
6748 /* There is no previous match to compare with, wait for
6749 * the next step to decide.
6750 */
6751 s.match_available = 1;
6752 s.strstart++;
6753 s.lookahead--;
6754 }
6755 }
6756 //Assert (flush != Z_NO_FLUSH, "no flush?");
6757 if (s.match_available) {
6758 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
6759 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
6760 bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
6761
6762 s.match_available = 0;
6763 }
6764 s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
6765 if (flush === Z_FINISH) {
6766 /*** FLUSH_BLOCK(s, 1); ***/
6767 flush_block_only(s, true);
6768 if (s.strm.avail_out === 0) {
6769 return BS_FINISH_STARTED;
6770 }
6771 /***/
6772 return BS_FINISH_DONE;
6773 }
6774 if (s.last_lit) {
6775 /*** FLUSH_BLOCK(s, 0); ***/
6776 flush_block_only(s, false);
6777 if (s.strm.avail_out === 0) {
6778 return BS_NEED_MORE;
6779 }
6780 /***/
6781 }
6782
6783 return BS_BLOCK_DONE;
6784 }
6785
6786
6787 /* ===========================================================================
6788 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
6789 * one. Do not maintain a hash table. (It will be regenerated if this run of
6790 * deflate switches away from Z_RLE.)
6791 */
6792 function deflate_rle(s, flush) {
6793 var bflush; /* set if current block must be flushed */
6794 var prev; /* byte at distance one to match */
6795 var scan, strend; /* scan goes up to strend for length of run */
6796
6797 var _win = s.window;
6798
6799 for (;;) {
6800 /* Make sure that we always have enough lookahead, except
6801 * at the end of the input file. We need MAX_MATCH bytes
6802 * for the longest run, plus one for the unrolled loop.
6803 */
6804 if (s.lookahead <= MAX_MATCH) {
6805 fill_window(s);
6806 if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
6807 return BS_NEED_MORE;
6808 }
6809 if (s.lookahead === 0) { break; } /* flush the current block */
6810 }
6811
6812 /* See how many times the previous byte repeats */
6813 s.match_length = 0;
6814 if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
6815 scan = s.strstart - 1;
6816 prev = _win[scan];
6817 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
6818 strend = s.strstart + MAX_MATCH;
6819 do {
6820 /*jshint noempty:false*/
6821 } while (prev === _win[++scan] && prev === _win[++scan] &&
6822 prev === _win[++scan] && prev === _win[++scan] &&
6823 prev === _win[++scan] && prev === _win[++scan] &&
6824 prev === _win[++scan] && prev === _win[++scan] &&
6825 scan < strend);
6826 s.match_length = MAX_MATCH - (strend - scan);
6827 if (s.match_length > s.lookahead) {
6828 s.match_length = s.lookahead;
6829 }
6830 }
6831 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
6832 }
6833
6834 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
6835 if (s.match_length >= MIN_MATCH) {
6836 //check_match(s, s.strstart, s.strstart - 1, s.match_length);
6837
6838 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
6839 bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
6840
6841 s.lookahead -= s.match_length;
6842 s.strstart += s.match_length;
6843 s.match_length = 0;
6844 } else {
6845 /* No match, output a literal byte */
6846 //Tracevv((stderr,"%c", s->window[s->strstart]));
6847 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
6848 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
6849
6850 s.lookahead--;
6851 s.strstart++;
6852 }
6853 if (bflush) {
6854 /*** FLUSH_BLOCK(s, 0); ***/
6855 flush_block_only(s, false);
6856 if (s.strm.avail_out === 0) {
6857 return BS_NEED_MORE;
6858 }
6859 /***/
6860 }
6861 }
6862 s.insert = 0;
6863 if (flush === Z_FINISH) {
6864 /*** FLUSH_BLOCK(s, 1); ***/
6865 flush_block_only(s, true);
6866 if (s.strm.avail_out === 0) {
6867 return BS_FINISH_STARTED;
6868 }
6869 /***/
6870 return BS_FINISH_DONE;
6871 }
6872 if (s.last_lit) {
6873 /*** FLUSH_BLOCK(s, 0); ***/
6874 flush_block_only(s, false);
6875 if (s.strm.avail_out === 0) {
6876 return BS_NEED_MORE;
6877 }
6878 /***/
6879 }
6880 return BS_BLOCK_DONE;
6881 }
6882
6883 /* ===========================================================================
6884 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
6885 * (It will be regenerated if this run of deflate switches away from Huffman.)
6886 */
6887 function deflate_huff(s, flush) {
6888 var bflush; /* set if current block must be flushed */
6889
6890 for (;;) {
6891 /* Make sure that we have a literal to write. */
6892 if (s.lookahead === 0) {
6893 fill_window(s);
6894 if (s.lookahead === 0) {
6895 if (flush === Z_NO_FLUSH) {
6896 return BS_NEED_MORE;
6897 }
6898 break; /* flush the current block */
6899 }
6900 }
6901
6902 /* Output a literal byte */
6903 s.match_length = 0;
6904 //Tracevv((stderr,"%c", s->window[s->strstart]));
6905 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
6906 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
6907 s.lookahead--;
6908 s.strstart++;
6909 if (bflush) {
6910 /*** FLUSH_BLOCK(s, 0); ***/
6911 flush_block_only(s, false);
6912 if (s.strm.avail_out === 0) {
6913 return BS_NEED_MORE;
6914 }
6915 /***/
6916 }
6917 }
6918 s.insert = 0;
6919 if (flush === Z_FINISH) {
6920 /*** FLUSH_BLOCK(s, 1); ***/
6921 flush_block_only(s, true);
6922 if (s.strm.avail_out === 0) {
6923 return BS_FINISH_STARTED;
6924 }
6925 /***/
6926 return BS_FINISH_DONE;
6927 }
6928 if (s.last_lit) {
6929 /*** FLUSH_BLOCK(s, 0); ***/
6930 flush_block_only(s, false);
6931 if (s.strm.avail_out === 0) {
6932 return BS_NEED_MORE;
6933 }
6934 /***/
6935 }
6936 return BS_BLOCK_DONE;
6937 }
6938
6939 /* Values for max_lazy_match, good_match and max_chain_length, depending on
6940 * the desired pack level (0..9). The values given below have been tuned to
6941 * exclude worst case performance for pathological files. Better values may be
6942 * found for specific files.
6943 */
6944 function Config(good_length, max_lazy, nice_length, max_chain, func) {
6945 this.good_length = good_length;
6946 this.max_lazy = max_lazy;
6947 this.nice_length = nice_length;
6948 this.max_chain = max_chain;
6949 this.func = func;
6950 }
6951
6952 var configuration_table;
6953
6954 configuration_table = [
6955 /* good lazy nice chain */
6956 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
6957 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
6958 new Config(4, 5, 16, 8, deflate_fast), /* 2 */
6959 new Config(4, 6, 32, 32, deflate_fast), /* 3 */
6960
6961 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
6962 new Config(8, 16, 32, 32, deflate_slow), /* 5 */
6963 new Config(8, 16, 128, 128, deflate_slow), /* 6 */
6964 new Config(8, 32, 128, 256, deflate_slow), /* 7 */
6965 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
6966 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
6967 ];
6968
6969
6970 /* ===========================================================================
6971 * Initialize the "longest match" routines for a new zlib stream
6972 */
6973 function lm_init(s) {
6974 s.window_size = 2 * s.w_size;
6975
6976 /*** CLEAR_HASH(s); ***/
6977 zero(s.head); // Fill with NIL (= 0);
6978
6979 /* Set the default configuration parameters:
6980 */
6981 s.max_lazy_match = configuration_table[s.level].max_lazy;
6982 s.good_match = configuration_table[s.level].good_length;
6983 s.nice_match = configuration_table[s.level].nice_length;
6984 s.max_chain_length = configuration_table[s.level].max_chain;
6985
6986 s.strstart = 0;
6987 s.block_start = 0;
6988 s.lookahead = 0;
6989 s.insert = 0;
6990 s.match_length = s.prev_length = MIN_MATCH - 1;
6991 s.match_available = 0;
6992 s.ins_h = 0;
6993 }
6994
6995
6996 function DeflateState() {
6997 this.strm = null; /* pointer back to this zlib stream */
6998 this.status = 0; /* as the name implies */
6999 this.pending_buf = null; /* output still pending */
7000 this.pending_buf_size = 0; /* size of pending_buf */
7001 this.pending_out = 0; /* next pending byte to output to the stream */
7002 this.pending = 0; /* nb of bytes in the pending buffer */
7003 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
7004 this.gzhead = null; /* gzip header information to write */
7005 this.gzindex = 0; /* where in extra, name, or comment */
7006 this.method = Z_DEFLATED; /* can only be DEFLATED */
7007 this.last_flush = -1; /* value of flush param for previous deflate call */
7008
7009 this.w_size = 0; /* LZ77 window size (32K by default) */
7010 this.w_bits = 0; /* log2(w_size) (8..16) */
7011 this.w_mask = 0; /* w_size - 1 */
7012
7013 this.window = null;
7014 /* Sliding window. Input bytes are read into the second half of the window,
7015 * and move to the first half later to keep a dictionary of at least wSize
7016 * bytes. With this organization, matches are limited to a distance of
7017 * wSize-MAX_MATCH bytes, but this ensures that IO is always
7018 * performed with a length multiple of the block size.
7019 */
7020
7021 this.window_size = 0;
7022 /* Actual size of window: 2*wSize, except when the user input buffer
7023 * is directly used as sliding window.
7024 */
7025
7026 this.prev = null;
7027 /* Link to older string with same hash index. To limit the size of this
7028 * array to 64K, this link is maintained only for the last 32K strings.
7029 * An index in this array is thus a window index modulo 32K.
7030 */
7031
7032 this.head = null; /* Heads of the hash chains or NIL. */
7033
7034 this.ins_h = 0; /* hash index of string to be inserted */
7035 this.hash_size = 0; /* number of elements in hash table */
7036 this.hash_bits = 0; /* log2(hash_size) */
7037 this.hash_mask = 0; /* hash_size-1 */
7038
7039 this.hash_shift = 0;
7040 /* Number of bits by which ins_h must be shifted at each input
7041 * step. It must be such that after MIN_MATCH steps, the oldest
7042 * byte no longer takes part in the hash key, that is:
7043 * hash_shift * MIN_MATCH >= hash_bits
7044 */
7045
7046 this.block_start = 0;
7047 /* Window position at the beginning of the current output block. Gets
7048 * negative when the window is moved backwards.
7049 */
7050
7051 this.match_length = 0; /* length of best match */
7052 this.prev_match = 0; /* previous match */
7053 this.match_available = 0; /* set if previous match exists */
7054 this.strstart = 0; /* start of string to insert */
7055 this.match_start = 0; /* start of matching string */
7056 this.lookahead = 0; /* number of valid bytes ahead in window */
7057
7058 this.prev_length = 0;
7059 /* Length of the best match at previous step. Matches not greater than this
7060 * are discarded. This is used in the lazy match evaluation.
7061 */
7062
7063 this.max_chain_length = 0;
7064 /* To speed up deflation, hash chains are never searched beyond this
7065 * length. A higher limit improves compression ratio but degrades the
7066 * speed.
7067 */
7068
7069 this.max_lazy_match = 0;
7070 /* Attempt to find a better match only when the current match is strictly
7071 * smaller than this value. This mechanism is used only for compression
7072 * levels >= 4.
7073 */
7074 // That's alias to max_lazy_match, don't use directly
7075 //this.max_insert_length = 0;
7076 /* Insert new strings in the hash table only if the match length is not
7077 * greater than this length. This saves time but degrades compression.
7078 * max_insert_length is used only for compression levels <= 3.
7079 */
7080
7081 this.level = 0; /* compression level (1..9) */
7082 this.strategy = 0; /* favor or force Huffman coding*/
7083
7084 this.good_match = 0;
7085 /* Use a faster search when the previous match is longer than this */
7086
7087 this.nice_match = 0; /* Stop searching when current match exceeds this */
7088
7089 /* used by trees.c: */
7090
7091 /* Didn't use ct_data typedef below to suppress compiler warning */
7092
7093 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
7094 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
7095 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
7096
7097 // Use flat array of DOUBLE size, with interleaved fata,
7098 // because JS does not support effective
7099 this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
7100 this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
7101 this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
7102 zero(this.dyn_ltree);
7103 zero(this.dyn_dtree);
7104 zero(this.bl_tree);
7105
7106 this.l_desc = null; /* desc. for literal tree */
7107 this.d_desc = null; /* desc. for distance tree */
7108 this.bl_desc = null; /* desc. for bit length tree */
7109
7110 //ush bl_count[MAX_BITS+1];
7111 this.bl_count = new utils.Buf16(MAX_BITS + 1);
7112 /* number of codes at each bit length for an optimal tree */
7113
7114 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
7115 this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
7116 zero(this.heap);
7117
7118 this.heap_len = 0; /* number of elements in the heap */
7119 this.heap_max = 0; /* element of largest frequency */
7120 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
7121 * The same heap array is used to build all trees.
7122 */
7123
7124 this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
7125 zero(this.depth);
7126 /* Depth of each subtree used as tie breaker for trees of equal frequency
7127 */
7128
7129 this.l_buf = 0; /* buffer index for literals or lengths */
7130
7131 this.lit_bufsize = 0;
7132 /* Size of match buffer for literals/lengths. There are 4 reasons for
7133 * limiting lit_bufsize to 64K:
7134 * - frequencies can be kept in 16 bit counters
7135 * - if compression is not successful for the first block, all input
7136 * data is still in the window so we can still emit a stored block even
7137 * when input comes from standard input. (This can also be done for
7138 * all blocks if lit_bufsize is not greater than 32K.)
7139 * - if compression is not successful for a file smaller than 64K, we can
7140 * even emit a stored file instead of a stored block (saving 5 bytes).
7141 * This is applicable only for zip (not gzip or zlib).
7142 * - creating new Huffman trees less frequently may not provide fast
7143 * adaptation to changes in the input data statistics. (Take for
7144 * example a binary file with poorly compressible code followed by
7145 * a highly compressible string table.) Smaller buffer sizes give
7146 * fast adaptation but have of course the overhead of transmitting
7147 * trees more frequently.
7148 * - I can't count above 4
7149 */
7150
7151 this.last_lit = 0; /* running index in l_buf */
7152
7153 this.d_buf = 0;
7154 /* Buffer index for distances. To simplify the code, d_buf and l_buf have
7155 * the same number of elements. To use different lengths, an extra flag
7156 * array would be necessary.
7157 */
7158
7159 this.opt_len = 0; /* bit length of current block with optimal trees */
7160 this.static_len = 0; /* bit length of current block with static trees */
7161 this.matches = 0; /* number of string matches in current block */
7162 this.insert = 0; /* bytes at end of window left to insert */
7163
7164
7165 this.bi_buf = 0;
7166 /* Output buffer. bits are inserted starting at the bottom (least
7167 * significant bits).
7168 */
7169 this.bi_valid = 0;
7170 /* Number of valid bits in bi_buf. All bits above the last valid bit
7171 * are always zero.
7172 */
7173
7174 // Used for window memory init. We safely ignore it for JS. That makes
7175 // sense only for pointers and memory check tools.
7176 //this.high_water = 0;
7177 /* High water mark offset in window for initialized bytes -- bytes above
7178 * this are set to zero in order to avoid memory check warnings when
7179 * longest match routines access bytes past the input. This is then
7180 * updated to the new high water mark.
7181 */
7182 }
7183
7184
7185 function deflateResetKeep(strm) {
7186 var s;
7187
7188 if (!strm || !strm.state) {
7189 return err(strm, Z_STREAM_ERROR);
7190 }
7191
7192 strm.total_in = strm.total_out = 0;
7193 strm.data_type = Z_UNKNOWN;
7194
7195 s = strm.state;
7196 s.pending = 0;
7197 s.pending_out = 0;
7198
7199 if (s.wrap < 0) {
7200 s.wrap = -s.wrap;
7201 /* was made negative by deflate(..., Z_FINISH); */
7202 }
7203 s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
7204 strm.adler = (s.wrap === 2) ?
7205 0 // crc32(0, Z_NULL, 0)
7206 :
7207 1; // adler32(0, Z_NULL, 0)
7208 s.last_flush = Z_NO_FLUSH;
7209 trees._tr_init(s);
7210 return Z_OK;
7211 }
7212
7213
7214 function deflateReset(strm) {
7215 var ret = deflateResetKeep(strm);
7216 if (ret === Z_OK) {
7217 lm_init(strm.state);
7218 }
7219 return ret;
7220 }
7221
7222
7223 function deflateSetHeader(strm, head) {
7224 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
7225 if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
7226 strm.state.gzhead = head;
7227 return Z_OK;
7228 }
7229
7230
7231 function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
7232 if (!strm) { // === Z_NULL
7233 return Z_STREAM_ERROR;
7234 }
7235 var wrap = 1;
7236
7237 if (level === Z_DEFAULT_COMPRESSION) {
7238 level = 6;
7239 }
7240
7241 if (windowBits < 0) { /* suppress zlib wrapper */
7242 wrap = 0;
7243 windowBits = -windowBits;
7244 }
7245
7246 else if (windowBits > 15) {
7247 wrap = 2; /* write gzip wrapper instead */
7248 windowBits -= 16;
7249 }
7250
7251
7252 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
7253 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
7254 strategy < 0 || strategy > Z_FIXED) {
7255 return err(strm, Z_STREAM_ERROR);
7256 }
7257
7258
7259 if (windowBits === 8) {
7260 windowBits = 9;
7261 }
7262 /* until 256-byte window bug fixed */
7263
7264 var s = new DeflateState();
7265
7266 strm.state = s;
7267 s.strm = strm;
7268
7269 s.wrap = wrap;
7270 s.gzhead = null;
7271 s.w_bits = windowBits;
7272 s.w_size = 1 << s.w_bits;
7273 s.w_mask = s.w_size - 1;
7274
7275 s.hash_bits = memLevel + 7;
7276 s.hash_size = 1 << s.hash_bits;
7277 s.hash_mask = s.hash_size - 1;
7278 s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
7279
7280 s.window = new utils.Buf8(s.w_size * 2);
7281 s.head = new utils.Buf16(s.hash_size);
7282 s.prev = new utils.Buf16(s.w_size);
7283
7284 // Don't need mem init magic for JS.
7285 //s.high_water = 0; /* nothing written to s->window yet */
7286
7287 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
7288
7289 s.pending_buf_size = s.lit_bufsize * 4;
7290
7291 //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
7292 //s->pending_buf = (uchf *) overlay;
7293 s.pending_buf = new utils.Buf8(s.pending_buf_size);
7294
7295 // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
7296 //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
7297 s.d_buf = 1 * s.lit_bufsize;
7298
7299 //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
7300 s.l_buf = (1 + 2) * s.lit_bufsize;
7301
7302 s.level = level;
7303 s.strategy = strategy;
7304 s.method = method;
7305
7306 return deflateReset(strm);
7307 }
7308
7309 function deflateInit(strm, level) {
7310 return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
7311 }
7312
7313
7314 function deflate(strm, flush) {
7315 var old_flush, s;
7316 var beg, val; // for gzip header write only
7317
7318 if (!strm || !strm.state ||
7319 flush > Z_BLOCK || flush < 0) {
7320 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
7321 }
7322
7323 s = strm.state;
7324
7325 if (!strm.output ||
7326 (!strm.input && strm.avail_in !== 0) ||
7327 (s.status === FINISH_STATE && flush !== Z_FINISH)) {
7328 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
7329 }
7330
7331 s.strm = strm; /* just in case */
7332 old_flush = s.last_flush;
7333 s.last_flush = flush;
7334
7335 /* Write the header */
7336 if (s.status === INIT_STATE) {
7337
7338 if (s.wrap === 2) { // GZIP header
7339 strm.adler = 0; //crc32(0L, Z_NULL, 0);
7340 put_byte(s, 31);
7341 put_byte(s, 139);
7342 put_byte(s, 8);
7343 if (!s.gzhead) { // s->gzhead == Z_NULL
7344 put_byte(s, 0);
7345 put_byte(s, 0);
7346 put_byte(s, 0);
7347 put_byte(s, 0);
7348 put_byte(s, 0);
7349 put_byte(s, s.level === 9 ? 2 :
7350 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
7351 4 : 0));
7352 put_byte(s, OS_CODE);
7353 s.status = BUSY_STATE;
7354 }
7355 else {
7356 put_byte(s, (s.gzhead.text ? 1 : 0) +
7357 (s.gzhead.hcrc ? 2 : 0) +
7358 (!s.gzhead.extra ? 0 : 4) +
7359 (!s.gzhead.name ? 0 : 8) +
7360 (!s.gzhead.comment ? 0 : 16)
7361 );
7362 put_byte(s, s.gzhead.time & 0xff);
7363 put_byte(s, (s.gzhead.time >> 8) & 0xff);
7364 put_byte(s, (s.gzhead.time >> 16) & 0xff);
7365 put_byte(s, (s.gzhead.time >> 24) & 0xff);
7366 put_byte(s, s.level === 9 ? 2 :
7367 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
7368 4 : 0));
7369 put_byte(s, s.gzhead.os & 0xff);
7370 if (s.gzhead.extra && s.gzhead.extra.length) {
7371 put_byte(s, s.gzhead.extra.length & 0xff);
7372 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
7373 }
7374 if (s.gzhead.hcrc) {
7375 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
7376 }
7377 s.gzindex = 0;
7378 s.status = EXTRA_STATE;
7379 }
7380 }
7381 else // DEFLATE header
7382 {
7383 var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
7384 var level_flags = -1;
7385
7386 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
7387 level_flags = 0;
7388 } else if (s.level < 6) {
7389 level_flags = 1;
7390 } else if (s.level === 6) {
7391 level_flags = 2;
7392 } else {
7393 level_flags = 3;
7394 }
7395 header |= (level_flags << 6);
7396 if (s.strstart !== 0) { header |= PRESET_DICT; }
7397 header += 31 - (header % 31);
7398
7399 s.status = BUSY_STATE;
7400 putShortMSB(s, header);
7401
7402 /* Save the adler32 of the preset dictionary: */
7403 if (s.strstart !== 0) {
7404 putShortMSB(s, strm.adler >>> 16);
7405 putShortMSB(s, strm.adler & 0xffff);
7406 }
7407 strm.adler = 1; // adler32(0L, Z_NULL, 0);
7408 }
7409 }
7410
7411 //#ifdef GZIP
7412 if (s.status === EXTRA_STATE) {
7413 if (s.gzhead.extra/* != Z_NULL*/) {
7414 beg = s.pending; /* start of bytes to update crc */
7415
7416 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
7417 if (s.pending === s.pending_buf_size) {
7418 if (s.gzhead.hcrc && s.pending > beg) {
7419 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7420 }
7421 flush_pending(strm);
7422 beg = s.pending;
7423 if (s.pending === s.pending_buf_size) {
7424 break;
7425 }
7426 }
7427 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
7428 s.gzindex++;
7429 }
7430 if (s.gzhead.hcrc && s.pending > beg) {
7431 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7432 }
7433 if (s.gzindex === s.gzhead.extra.length) {
7434 s.gzindex = 0;
7435 s.status = NAME_STATE;
7436 }
7437 }
7438 else {
7439 s.status = NAME_STATE;
7440 }
7441 }
7442 if (s.status === NAME_STATE) {
7443 if (s.gzhead.name/* != Z_NULL*/) {
7444 beg = s.pending; /* start of bytes to update crc */
7445 //int val;
7446
7447 do {
7448 if (s.pending === s.pending_buf_size) {
7449 if (s.gzhead.hcrc && s.pending > beg) {
7450 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7451 }
7452 flush_pending(strm);
7453 beg = s.pending;
7454 if (s.pending === s.pending_buf_size) {
7455 val = 1;
7456 break;
7457 }
7458 }
7459 // JS specific: little magic to add zero terminator to end of string
7460 if (s.gzindex < s.gzhead.name.length) {
7461 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
7462 } else {
7463 val = 0;
7464 }
7465 put_byte(s, val);
7466 } while (val !== 0);
7467
7468 if (s.gzhead.hcrc && s.pending > beg) {
7469 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7470 }
7471 if (val === 0) {
7472 s.gzindex = 0;
7473 s.status = COMMENT_STATE;
7474 }
7475 }
7476 else {
7477 s.status = COMMENT_STATE;
7478 }
7479 }
7480 if (s.status === COMMENT_STATE) {
7481 if (s.gzhead.comment/* != Z_NULL*/) {
7482 beg = s.pending; /* start of bytes to update crc */
7483 //int val;
7484
7485 do {
7486 if (s.pending === s.pending_buf_size) {
7487 if (s.gzhead.hcrc && s.pending > beg) {
7488 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7489 }
7490 flush_pending(strm);
7491 beg = s.pending;
7492 if (s.pending === s.pending_buf_size) {
7493 val = 1;
7494 break;
7495 }
7496 }
7497 // JS specific: little magic to add zero terminator to end of string
7498 if (s.gzindex < s.gzhead.comment.length) {
7499 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
7500 } else {
7501 val = 0;
7502 }
7503 put_byte(s, val);
7504 } while (val !== 0);
7505
7506 if (s.gzhead.hcrc && s.pending > beg) {
7507 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7508 }
7509 if (val === 0) {
7510 s.status = HCRC_STATE;
7511 }
7512 }
7513 else {
7514 s.status = HCRC_STATE;
7515 }
7516 }
7517 if (s.status === HCRC_STATE) {
7518 if (s.gzhead.hcrc) {
7519 if (s.pending + 2 > s.pending_buf_size) {
7520 flush_pending(strm);
7521 }
7522 if (s.pending + 2 <= s.pending_buf_size) {
7523 put_byte(s, strm.adler & 0xff);
7524 put_byte(s, (strm.adler >> 8) & 0xff);
7525 strm.adler = 0; //crc32(0L, Z_NULL, 0);
7526 s.status = BUSY_STATE;
7527 }
7528 }
7529 else {
7530 s.status = BUSY_STATE;
7531 }
7532 }
7533 //#endif
7534
7535 /* Flush as much pending output as possible */
7536 if (s.pending !== 0) {
7537 flush_pending(strm);
7538 if (strm.avail_out === 0) {
7539 /* Since avail_out is 0, deflate will be called again with
7540 * more output space, but possibly with both pending and
7541 * avail_in equal to zero. There won't be anything to do,
7542 * but this is not an error situation so make sure we
7543 * return OK instead of BUF_ERROR at next call of deflate:
7544 */
7545 s.last_flush = -1;
7546 return Z_OK;
7547 }
7548
7549 /* Make sure there is something to do and avoid duplicate consecutive
7550 * flushes. For repeated and useless calls with Z_FINISH, we keep
7551 * returning Z_STREAM_END instead of Z_BUF_ERROR.
7552 */
7553 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
7554 flush !== Z_FINISH) {
7555 return err(strm, Z_BUF_ERROR);
7556 }
7557
7558 /* User must not provide more input after the first FINISH: */
7559 if (s.status === FINISH_STATE && strm.avail_in !== 0) {
7560 return err(strm, Z_BUF_ERROR);
7561 }
7562
7563 /* Start a new block or continue the current one.
7564 */
7565 if (strm.avail_in !== 0 || s.lookahead !== 0 ||
7566 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
7567 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
7568 (s.strategy === Z_RLE ? deflate_rle(s, flush) :
7569 configuration_table[s.level].func(s, flush));
7570
7571 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
7572 s.status = FINISH_STATE;
7573 }
7574 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
7575 if (strm.avail_out === 0) {
7576 s.last_flush = -1;
7577 /* avoid BUF_ERROR next call, see above */
7578 }
7579 return Z_OK;
7580 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
7581 * of deflate should use the same flush parameter to make sure
7582 * that the flush is complete. So we don't have to output an
7583 * empty block here, this will be done at next call. This also
7584 * ensures that for a very small output buffer, we emit at most
7585 * one empty block.
7586 */
7587 }
7588 if (bstate === BS_BLOCK_DONE) {
7589 if (flush === Z_PARTIAL_FLUSH) {
7590 trees._tr_align(s);
7591 }
7592 else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
7593
7594 trees._tr_stored_block(s, 0, 0, false);
7595 /* For a full flush, this empty block will be recognized
7596 * as a special marker by inflate_sync().
7597 */
7598 if (flush === Z_FULL_FLUSH) {
7599 /*** CLEAR_HASH(s); ***/ /* forget history */
7600 zero(s.head); // Fill with NIL (= 0);
7601
7602 if (s.lookahead === 0) {
7603 s.strstart = 0;
7604 s.block_start = 0;
7605 s.insert = 0;
7606 }
7607 }
7608 }
7609 flush_pending(strm);
7610 if (strm.avail_out === 0) {
7611 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
7612 return Z_OK;
7613 }
7614 }
7615 }
7616 //Assert(strm->avail_out > 0, "bug2");
7617 //if (strm.avail_out <= 0) { throw new Error("bug2");}
7618
7619 if (flush !== Z_FINISH) { return Z_OK; }
7620 if (s.wrap <= 0) { return Z_STREAM_END; }
7621
7622 /* Write the trailer */
7623 if (s.wrap === 2) {
7624 put_byte(s, strm.adler & 0xff);
7625 put_byte(s, (strm.adler >> 8) & 0xff);
7626 put_byte(s, (strm.adler >> 16) & 0xff);
7627 put_byte(s, (strm.adler >> 24) & 0xff);
7628 put_byte(s, strm.total_in & 0xff);
7629 put_byte(s, (strm.total_in >> 8) & 0xff);
7630 put_byte(s, (strm.total_in >> 16) & 0xff);
7631 put_byte(s, (strm.total_in >> 24) & 0xff);
7632 }
7633 else
7634 {
7635 putShortMSB(s, strm.adler >>> 16);
7636 putShortMSB(s, strm.adler & 0xffff);
7637 }
7638
7639 flush_pending(strm);
7640 /* If avail_out is zero, the application will call deflate again
7641 * to flush the rest.
7642 */
7643 if (s.wrap > 0) { s.wrap = -s.wrap; }
7644 /* write the trailer only once! */
7645 return s.pending !== 0 ? Z_OK : Z_STREAM_END;
7646 }
7647
7648 function deflateEnd(strm) {
7649 var status;
7650
7651 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
7652 return Z_STREAM_ERROR;
7653 }
7654
7655 status = strm.state.status;
7656 if (status !== INIT_STATE &&
7657 status !== EXTRA_STATE &&
7658 status !== NAME_STATE &&
7659 status !== COMMENT_STATE &&
7660 status !== HCRC_STATE &&
7661 status !== BUSY_STATE &&
7662 status !== FINISH_STATE
7663 ) {
7664 return err(strm, Z_STREAM_ERROR);
7665 }
7666
7667 strm.state = null;
7668
7669 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
7670 }
7671
7672
7673 /* =========================================================================
7674 * Initializes the compression dictionary from the given byte
7675 * sequence without producing any compressed output.
7676 */
7677 function deflateSetDictionary(strm, dictionary) {
7678 var dictLength = dictionary.length;
7679
7680 var s;
7681 var str, n;
7682 var wrap;
7683 var avail;
7684 var next;
7685 var input;
7686 var tmpDict;
7687
7688 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
7689 return Z_STREAM_ERROR;
7690 }
7691
7692 s = strm.state;
7693 wrap = s.wrap;
7694
7695 if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
7696 return Z_STREAM_ERROR;
7697 }
7698
7699 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
7700 if (wrap === 1) {
7701 /* adler32(strm->adler, dictionary, dictLength); */
7702 strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
7703 }
7704
7705 s.wrap = 0; /* avoid computing Adler-32 in read_buf */
7706
7707 /* if dictionary would fill window, just replace the history */
7708 if (dictLength >= s.w_size) {
7709 if (wrap === 0) { /* already empty otherwise */
7710 /*** CLEAR_HASH(s); ***/
7711 zero(s.head); // Fill with NIL (= 0);
7712 s.strstart = 0;
7713 s.block_start = 0;
7714 s.insert = 0;
7715 }
7716 /* use the tail */
7717 // dictionary = dictionary.slice(dictLength - s.w_size);
7718 tmpDict = new utils.Buf8(s.w_size);
7719 utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
7720 dictionary = tmpDict;
7721 dictLength = s.w_size;
7722 }
7723 /* insert dictionary into window and hash */
7724 avail = strm.avail_in;
7725 next = strm.next_in;
7726 input = strm.input;
7727 strm.avail_in = dictLength;
7728 strm.next_in = 0;
7729 strm.input = dictionary;
7730 fill_window(s);
7731 while (s.lookahead >= MIN_MATCH) {
7732 str = s.strstart;
7733 n = s.lookahead - (MIN_MATCH - 1);
7734 do {
7735 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
7736 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
7737
7738 s.prev[str & s.w_mask] = s.head[s.ins_h];
7739
7740 s.head[s.ins_h] = str;
7741 str++;
7742 } while (--n);
7743 s.strstart = str;
7744 s.lookahead = MIN_MATCH - 1;
7745 fill_window(s);
7746 }
7747 s.strstart += s.lookahead;
7748 s.block_start = s.strstart;
7749 s.insert = s.lookahead;
7750 s.lookahead = 0;
7751 s.match_length = s.prev_length = MIN_MATCH - 1;
7752 s.match_available = 0;
7753 strm.next_in = next;
7754 strm.input = input;
7755 strm.avail_in = avail;
7756 s.wrap = wrap;
7757 return Z_OK;
7758 }
7759
7760
7761 exports.deflateInit = deflateInit;
7762 exports.deflateInit2 = deflateInit2;
7763 exports.deflateReset = deflateReset;
7764 exports.deflateResetKeep = deflateResetKeep;
7765 exports.deflateSetHeader = deflateSetHeader;
7766 exports.deflate = deflate;
7767 exports.deflateEnd = deflateEnd;
7768 exports.deflateSetDictionary = deflateSetDictionary;
7769 exports.deflateInfo = 'pako deflate (from Nodeca project)';
7770
7771 /* Not implemented
7772 exports.deflateBound = deflateBound;
7773 exports.deflateCopy = deflateCopy;
7774 exports.deflateParams = deflateParams;
7775 exports.deflatePending = deflatePending;
7776 exports.deflatePrime = deflatePrime;
7777 exports.deflateTune = deflateTune;
7778 */
7779
7780 },{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(require,module,exports){
7781 'use strict';
7782
7783 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
7784 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
7785 //
7786 // This software is provided 'as-is', without any express or implied
7787 // warranty. In no event will the authors be held liable for any damages
7788 // arising from the use of this software.
7789 //
7790 // Permission is granted to anyone to use this software for any purpose,
7791 // including commercial applications, and to alter it and redistribute it
7792 // freely, subject to the following restrictions:
7793 //
7794 // 1. The origin of this software must not be misrepresented; you must not
7795 // claim that you wrote the original software. If you use this software
7796 // in a product, an acknowledgment in the product documentation would be
7797 // appreciated but is not required.
7798 // 2. Altered source versions must be plainly marked as such, and must not be
7799 // misrepresented as being the original software.
7800 // 3. This notice may not be removed or altered from any source distribution.
7801
7802 function GZheader() {
7803 /* true if compressed data believed to be text */
7804 this.text = 0;
7805 /* modification time */
7806 this.time = 0;
7807 /* extra flags (not used when writing a gzip file) */
7808 this.xflags = 0;
7809 /* operating system */
7810 this.os = 0;
7811 /* pointer to extra field or Z_NULL if none */
7812 this.extra = null;
7813 /* extra field length (valid if extra != Z_NULL) */
7814 this.extra_len = 0; // Actually, we don't need it in JS,
7815 // but leave for few code modifications
7816
7817 //
7818 // Setup limits is not necessary because in js we should not preallocate memory
7819 // for inflate use constant limit in 65536 bytes
7820 //
7821
7822 /* space at extra (only when reading header) */
7823 // this.extra_max = 0;
7824 /* pointer to zero-terminated file name or Z_NULL */
7825 this.name = '';
7826 /* space at name (only when reading header) */
7827 // this.name_max = 0;
7828 /* pointer to zero-terminated comment or Z_NULL */
7829 this.comment = '';
7830 /* space at comment (only when reading header) */
7831 // this.comm_max = 0;
7832 /* true if there was or will be a header crc */
7833 this.hcrc = 0;
7834 /* true when done reading gzip header (not used when writing a gzip file) */
7835 this.done = false;
7836 }
7837
7838 module.exports = GZheader;
7839
7840 },{}],48:[function(require,module,exports){
7841 'use strict';
7842
7843 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
7844 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
7845 //
7846 // This software is provided 'as-is', without any express or implied
7847 // warranty. In no event will the authors be held liable for any damages
7848 // arising from the use of this software.
7849 //
7850 // Permission is granted to anyone to use this software for any purpose,
7851 // including commercial applications, and to alter it and redistribute it
7852 // freely, subject to the following restrictions:
7853 //
7854 // 1. The origin of this software must not be misrepresented; you must not
7855 // claim that you wrote the original software. If you use this software
7856 // in a product, an acknowledgment in the product documentation would be
7857 // appreciated but is not required.
7858 // 2. Altered source versions must be plainly marked as such, and must not be
7859 // misrepresented as being the original software.
7860 // 3. This notice may not be removed or altered from any source distribution.
7861
7862 // See state defs from inflate.js
7863 var BAD = 30; /* got a data error -- remain here until reset */
7864 var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
7865
7866 /*
7867 Decode literal, length, and distance codes and write out the resulting
7868 literal and match bytes until either not enough input or output is
7869 available, an end-of-block is encountered, or a data error is encountered.
7870 When large enough input and output buffers are supplied to inflate(), for
7871 example, a 16K input buffer and a 64K output buffer, more than 95% of the
7872 inflate execution time is spent in this routine.
7873
7874 Entry assumptions:
7875
7876 state.mode === LEN
7877 strm.avail_in >= 6
7878 strm.avail_out >= 258
7879 start >= strm.avail_out
7880 state.bits < 8
7881
7882 On return, state.mode is one of:
7883
7884 LEN -- ran out of enough output space or enough available input
7885 TYPE -- reached end of block code, inflate() to interpret next block
7886 BAD -- error in block data
7887
7888 Notes:
7889
7890 - The maximum input bits used by a length/distance pair is 15 bits for the
7891 length code, 5 bits for the length extra, 15 bits for the distance code,
7892 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
7893 Therefore if strm.avail_in >= 6, then there is enough input to avoid
7894 checking for available input while decoding.
7895
7896 - The maximum bytes that a single length/distance pair can output is 258
7897 bytes, which is the maximum length that can be coded. inflate_fast()
7898 requires strm.avail_out >= 258 for each loop to avoid checking for
7899 output space.
7900 */
7901 module.exports = function inflate_fast(strm, start) {
7902 var state;
7903 var _in; /* local strm.input */
7904 var last; /* have enough input while in < last */
7905 var _out; /* local strm.output */
7906 var beg; /* inflate()'s initial strm.output */
7907 var end; /* while out < end, enough space available */
7908 //#ifdef INFLATE_STRICT
7909 var dmax; /* maximum distance from zlib header */
7910 //#endif
7911 var wsize; /* window size or zero if not using window */
7912 var whave; /* valid bytes in the window */
7913 var wnext; /* window write index */
7914 // Use `s_window` instead `window`, avoid conflict with instrumentation tools
7915 var s_window; /* allocated sliding window, if wsize != 0 */
7916 var hold; /* local strm.hold */
7917 var bits; /* local strm.bits */
7918 var lcode; /* local strm.lencode */
7919 var dcode; /* local strm.distcode */
7920 var lmask; /* mask for first level of length codes */
7921 var dmask; /* mask for first level of distance codes */
7922 var here; /* retrieved table entry */
7923 var op; /* code bits, operation, extra bits, or */
7924 /* window position, window bytes to copy */
7925 var len; /* match length, unused bytes */
7926 var dist; /* match distance */
7927 var from; /* where to copy match from */
7928 var from_source;
7929
7930
7931 var input, output; // JS specific, because we have no pointers
7932
7933 /* copy state to local variables */
7934 state = strm.state;
7935 //here = state.here;
7936 _in = strm.next_in;
7937 input = strm.input;
7938 last = _in + (strm.avail_in - 5);
7939 _out = strm.next_out;
7940 output = strm.output;
7941 beg = _out - (start - strm.avail_out);
7942 end = _out + (strm.avail_out - 257);
7943 //#ifdef INFLATE_STRICT
7944 dmax = state.dmax;
7945 //#endif
7946 wsize = state.wsize;
7947 whave = state.whave;
7948 wnext = state.wnext;
7949 s_window = state.window;
7950 hold = state.hold;
7951 bits = state.bits;
7952 lcode = state.lencode;
7953 dcode = state.distcode;
7954 lmask = (1 << state.lenbits) - 1;
7955 dmask = (1 << state.distbits) - 1;
7956
7957
7958 /* decode literals and length/distances until end-of-block or not enough
7959 input data or output space */
7960
7961 top:
7962 do {
7963 if (bits < 15) {
7964 hold += input[_in++] << bits;
7965 bits += 8;
7966 hold += input[_in++] << bits;
7967 bits += 8;
7968 }
7969
7970 here = lcode[hold & lmask];
7971
7972 dolen:
7973 for (;;) { // Goto emulation
7974 op = here >>> 24/*here.bits*/;
7975 hold >>>= op;
7976 bits -= op;
7977 op = (here >>> 16) & 0xff/*here.op*/;
7978 if (op === 0) { /* literal */
7979 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
7980 // "inflate: literal '%c'\n" :
7981 // "inflate: literal 0x%02x\n", here.val));
7982 output[_out++] = here & 0xffff/*here.val*/;
7983 }
7984 else if (op & 16) { /* length base */
7985 len = here & 0xffff/*here.val*/;
7986 op &= 15; /* number of extra bits */
7987 if (op) {
7988 if (bits < op) {
7989 hold += input[_in++] << bits;
7990 bits += 8;
7991 }
7992 len += hold & ((1 << op) - 1);
7993 hold >>>= op;
7994 bits -= op;
7995 }
7996 //Tracevv((stderr, "inflate: length %u\n", len));
7997 if (bits < 15) {
7998 hold += input[_in++] << bits;
7999 bits += 8;
8000 hold += input[_in++] << bits;
8001 bits += 8;
8002 }
8003 here = dcode[hold & dmask];
8004
8005 dodist:
8006 for (;;) { // goto emulation
8007 op = here >>> 24/*here.bits*/;
8008 hold >>>= op;
8009 bits -= op;
8010 op = (here >>> 16) & 0xff/*here.op*/;
8011
8012 if (op & 16) { /* distance base */
8013 dist = here & 0xffff/*here.val*/;
8014 op &= 15; /* number of extra bits */
8015 if (bits < op) {
8016 hold += input[_in++] << bits;
8017 bits += 8;
8018 if (bits < op) {
8019 hold += input[_in++] << bits;
8020 bits += 8;
8021 }
8022 }
8023 dist += hold & ((1 << op) - 1);
8024 //#ifdef INFLATE_STRICT
8025 if (dist > dmax) {
8026 strm.msg = 'invalid distance too far back';
8027 state.mode = BAD;
8028 break top;
8029 }
8030 //#endif
8031 hold >>>= op;
8032 bits -= op;
8033 //Tracevv((stderr, "inflate: distance %u\n", dist));
8034 op = _out - beg; /* max distance in output */
8035 if (dist > op) { /* see if copy from window */
8036 op = dist - op; /* distance back in window */
8037 if (op > whave) {
8038 if (state.sane) {
8039 strm.msg = 'invalid distance too far back';
8040 state.mode = BAD;
8041 break top;
8042 }
8043
8044 // (!) This block is disabled in zlib defailts,
8045 // don't enable it for binary compatibility
8046 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
8047 // if (len <= op - whave) {
8048 // do {
8049 // output[_out++] = 0;
8050 // } while (--len);
8051 // continue top;
8052 // }
8053 // len -= op - whave;
8054 // do {
8055 // output[_out++] = 0;
8056 // } while (--op > whave);
8057 // if (op === 0) {
8058 // from = _out - dist;
8059 // do {
8060 // output[_out++] = output[from++];
8061 // } while (--len);
8062 // continue top;
8063 // }
8064 //#endif
8065 }
8066 from = 0; // window index
8067 from_source = s_window;
8068 if (wnext === 0) { /* very common case */
8069 from += wsize - op;
8070 if (op < len) { /* some from window */
8071 len -= op;
8072 do {
8073 output[_out++] = s_window[from++];
8074 } while (--op);
8075 from = _out - dist; /* rest from output */
8076 from_source = output;
8077 }
8078 }
8079 else if (wnext < op) { /* wrap around window */
8080 from += wsize + wnext - op;
8081 op -= wnext;
8082 if (op < len) { /* some from end of window */
8083 len -= op;
8084 do {
8085 output[_out++] = s_window[from++];
8086 } while (--op);
8087 from = 0;
8088 if (wnext < len) { /* some from start of window */
8089 op = wnext;
8090 len -= op;
8091 do {
8092 output[_out++] = s_window[from++];
8093 } while (--op);
8094 from = _out - dist; /* rest from output */
8095 from_source = output;
8096 }
8097 }
8098 }
8099 else { /* contiguous in window */
8100 from += wnext - op;
8101 if (op < len) { /* some from window */
8102 len -= op;
8103 do {
8104 output[_out++] = s_window[from++];
8105 } while (--op);
8106 from = _out - dist; /* rest from output */
8107 from_source = output;
8108 }
8109 }
8110 while (len > 2) {
8111 output[_out++] = from_source[from++];
8112 output[_out++] = from_source[from++];
8113 output[_out++] = from_source[from++];
8114 len -= 3;
8115 }
8116 if (len) {
8117 output[_out++] = from_source[from++];
8118 if (len > 1) {
8119 output[_out++] = from_source[from++];
8120 }
8121 }
8122 }
8123 else {
8124 from = _out - dist; /* copy direct from output */
8125 do { /* minimum length is three */
8126 output[_out++] = output[from++];
8127 output[_out++] = output[from++];
8128 output[_out++] = output[from++];
8129 len -= 3;
8130 } while (len > 2);
8131 if (len) {
8132 output[_out++] = output[from++];
8133 if (len > 1) {
8134 output[_out++] = output[from++];
8135 }
8136 }
8137 }
8138 }
8139 else if ((op & 64) === 0) { /* 2nd level distance code */
8140 here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
8141 continue dodist;
8142 }
8143 else {
8144 strm.msg = 'invalid distance code';
8145 state.mode = BAD;
8146 break top;
8147 }
8148
8149 break; // need to emulate goto via "continue"
8150 }
8151 }
8152 else if ((op & 64) === 0) { /* 2nd level length code */
8153 here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
8154 continue dolen;
8155 }
8156 else if (op & 32) { /* end-of-block */
8157 //Tracevv((stderr, "inflate: end of block\n"));
8158 state.mode = TYPE;
8159 break top;
8160 }
8161 else {
8162 strm.msg = 'invalid literal/length code';
8163 state.mode = BAD;
8164 break top;
8165 }
8166
8167 break; // need to emulate goto via "continue"
8168 }
8169 } while (_in < last && _out < end);
8170
8171 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
8172 len = bits >> 3;
8173 _in -= len;
8174 bits -= len << 3;
8175 hold &= (1 << bits) - 1;
8176
8177 /* update state and return */
8178 strm.next_in = _in;
8179 strm.next_out = _out;
8180 strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
8181 strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
8182 state.hold = hold;
8183 state.bits = bits;
8184 return;
8185 };
8186
8187 },{}],49:[function(require,module,exports){
8188 'use strict';
8189
8190 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
8191 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
8192 //
8193 // This software is provided 'as-is', without any express or implied
8194 // warranty. In no event will the authors be held liable for any damages
8195 // arising from the use of this software.
8196 //
8197 // Permission is granted to anyone to use this software for any purpose,
8198 // including commercial applications, and to alter it and redistribute it
8199 // freely, subject to the following restrictions:
8200 //
8201 // 1. The origin of this software must not be misrepresented; you must not
8202 // claim that you wrote the original software. If you use this software
8203 // in a product, an acknowledgment in the product documentation would be
8204 // appreciated but is not required.
8205 // 2. Altered source versions must be plainly marked as such, and must not be
8206 // misrepresented as being the original software.
8207 // 3. This notice may not be removed or altered from any source distribution.
8208
8209 var utils = require('../utils/common');
8210 var adler32 = require('./adler32');
8211 var crc32 = require('./crc32');
8212 var inflate_fast = require('./inffast');
8213 var inflate_table = require('./inftrees');
8214
8215 var CODES = 0;
8216 var LENS = 1;
8217 var DISTS = 2;
8218
8219 /* Public constants ==========================================================*/
8220 /* ===========================================================================*/
8221
8222
8223 /* Allowed flush values; see deflate() and inflate() below for details */
8224 //var Z_NO_FLUSH = 0;
8225 //var Z_PARTIAL_FLUSH = 1;
8226 //var Z_SYNC_FLUSH = 2;
8227 //var Z_FULL_FLUSH = 3;
8228 var Z_FINISH = 4;
8229 var Z_BLOCK = 5;
8230 var Z_TREES = 6;
8231
8232
8233 /* Return codes for the compression/decompression functions. Negative values
8234 * are errors, positive values are used for special but normal events.
8235 */
8236 var Z_OK = 0;
8237 var Z_STREAM_END = 1;
8238 var Z_NEED_DICT = 2;
8239 //var Z_ERRNO = -1;
8240 var Z_STREAM_ERROR = -2;
8241 var Z_DATA_ERROR = -3;
8242 var Z_MEM_ERROR = -4;
8243 var Z_BUF_ERROR = -5;
8244 //var Z_VERSION_ERROR = -6;
8245
8246 /* The deflate compression method */
8247 var Z_DEFLATED = 8;
8248
8249
8250 /* STATES ====================================================================*/
8251 /* ===========================================================================*/
8252
8253
8254 var HEAD = 1; /* i: waiting for magic header */
8255 var FLAGS = 2; /* i: waiting for method and flags (gzip) */
8256 var TIME = 3; /* i: waiting for modification time (gzip) */
8257 var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
8258 var EXLEN = 5; /* i: waiting for extra length (gzip) */
8259 var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
8260 var NAME = 7; /* i: waiting for end of file name (gzip) */
8261 var COMMENT = 8; /* i: waiting for end of comment (gzip) */
8262 var HCRC = 9; /* i: waiting for header crc (gzip) */
8263 var DICTID = 10; /* i: waiting for dictionary check value */
8264 var DICT = 11; /* waiting for inflateSetDictionary() call */
8265 var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
8266 var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
8267 var STORED = 14; /* i: waiting for stored size (length and complement) */
8268 var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
8269 var COPY = 16; /* i/o: waiting for input or output to copy stored block */
8270 var TABLE = 17; /* i: waiting for dynamic block table lengths */
8271 var LENLENS = 18; /* i: waiting for code length code lengths */
8272 var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
8273 var LEN_ = 20; /* i: same as LEN below, but only first time in */
8274 var LEN = 21; /* i: waiting for length/lit/eob code */
8275 var LENEXT = 22; /* i: waiting for length extra bits */
8276 var DIST = 23; /* i: waiting for distance code */
8277 var DISTEXT = 24; /* i: waiting for distance extra bits */
8278 var MATCH = 25; /* o: waiting for output space to copy string */
8279 var LIT = 26; /* o: waiting for output space to write literal */
8280 var CHECK = 27; /* i: waiting for 32-bit check value */
8281 var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
8282 var DONE = 29; /* finished check, done -- remain here until reset */
8283 var BAD = 30; /* got a data error -- remain here until reset */
8284 var MEM = 31; /* got an inflate() memory error -- remain here until reset */
8285 var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
8286
8287 /* ===========================================================================*/
8288
8289
8290
8291 var ENOUGH_LENS = 852;
8292 var ENOUGH_DISTS = 592;
8293 //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
8294
8295 var MAX_WBITS = 15;
8296 /* 32K LZ77 window */
8297 var DEF_WBITS = MAX_WBITS;
8298
8299
8300 function zswap32(q) {
8301 return (((q >>> 24) & 0xff) +
8302 ((q >>> 8) & 0xff00) +
8303 ((q & 0xff00) << 8) +
8304 ((q & 0xff) << 24));
8305 }
8306
8307
8308 function InflateState() {
8309 this.mode = 0; /* current inflate mode */
8310 this.last = false; /* true if processing last block */
8311 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
8312 this.havedict = false; /* true if dictionary provided */
8313 this.flags = 0; /* gzip header method and flags (0 if zlib) */
8314 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
8315 this.check = 0; /* protected copy of check value */
8316 this.total = 0; /* protected copy of output count */
8317 // TODO: may be {}
8318 this.head = null; /* where to save gzip header information */
8319
8320 /* sliding window */
8321 this.wbits = 0; /* log base 2 of requested window size */
8322 this.wsize = 0; /* window size or zero if not using window */
8323 this.whave = 0; /* valid bytes in the window */
8324 this.wnext = 0; /* window write index */
8325 this.window = null; /* allocated sliding window, if needed */
8326
8327 /* bit accumulator */
8328 this.hold = 0; /* input bit accumulator */
8329 this.bits = 0; /* number of bits in "in" */
8330
8331 /* for string and stored block copying */
8332 this.length = 0; /* literal or length of data to copy */
8333 this.offset = 0; /* distance back to copy string from */
8334
8335 /* for table and code decoding */
8336 this.extra = 0; /* extra bits needed */
8337
8338 /* fixed and dynamic code tables */
8339 this.lencode = null; /* starting table for length/literal codes */
8340 this.distcode = null; /* starting table for distance codes */
8341 this.lenbits = 0; /* index bits for lencode */
8342 this.distbits = 0; /* index bits for distcode */
8343
8344 /* dynamic table building */
8345 this.ncode = 0; /* number of code length code lengths */
8346 this.nlen = 0; /* number of length code lengths */
8347 this.ndist = 0; /* number of distance code lengths */
8348 this.have = 0; /* number of code lengths in lens[] */
8349 this.next = null; /* next available space in codes[] */
8350
8351 this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
8352 this.work = new utils.Buf16(288); /* work area for code table building */
8353
8354 /*
8355 because we don't have pointers in js, we use lencode and distcode directly
8356 as buffers so we don't need codes
8357 */
8358 //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
8359 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
8360 this.distdyn = null; /* dynamic table for distance codes (JS specific) */
8361 this.sane = 0; /* if false, allow invalid distance too far */
8362 this.back = 0; /* bits back of last unprocessed length/lit */
8363 this.was = 0; /* initial length of match */
8364 }
8365
8366 function inflateResetKeep(strm) {
8367 var state;
8368
8369 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
8370 state = strm.state;
8371 strm.total_in = strm.total_out = state.total = 0;
8372 strm.msg = ''; /*Z_NULL*/
8373 if (state.wrap) { /* to support ill-conceived Java test suite */
8374 strm.adler = state.wrap & 1;
8375 }
8376 state.mode = HEAD;
8377 state.last = 0;
8378 state.havedict = 0;
8379 state.dmax = 32768;
8380 state.head = null/*Z_NULL*/;
8381 state.hold = 0;
8382 state.bits = 0;
8383 //state.lencode = state.distcode = state.next = state.codes;
8384 state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
8385 state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
8386
8387 state.sane = 1;
8388 state.back = -1;
8389 //Tracev((stderr, "inflate: reset\n"));
8390 return Z_OK;
8391 }
8392
8393 function inflateReset(strm) {
8394 var state;
8395
8396 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
8397 state = strm.state;
8398 state.wsize = 0;
8399 state.whave = 0;
8400 state.wnext = 0;
8401 return inflateResetKeep(strm);
8402
8403 }
8404
8405 function inflateReset2(strm, windowBits) {
8406 var wrap;
8407 var state;
8408
8409 /* get the state */
8410 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
8411 state = strm.state;
8412
8413 /* extract wrap request from windowBits parameter */
8414 if (windowBits < 0) {
8415 wrap = 0;
8416 windowBits = -windowBits;
8417 }
8418 else {
8419 wrap = (windowBits >> 4) + 1;
8420 if (windowBits < 48) {
8421 windowBits &= 15;
8422 }
8423 }
8424
8425 /* set number of window bits, free window if different */
8426 if (windowBits && (windowBits < 8 || windowBits > 15)) {
8427 return Z_STREAM_ERROR;
8428 }
8429 if (state.window !== null && state.wbits !== windowBits) {
8430 state.window = null;
8431 }
8432
8433 /* update state and reset the rest of it */
8434 state.wrap = wrap;
8435 state.wbits = windowBits;
8436 return inflateReset(strm);
8437 }
8438
8439 function inflateInit2(strm, windowBits) {
8440 var ret;
8441 var state;
8442
8443 if (!strm) { return Z_STREAM_ERROR; }
8444 //strm.msg = Z_NULL; /* in case we return an error */
8445
8446 state = new InflateState();
8447
8448 //if (state === Z_NULL) return Z_MEM_ERROR;
8449 //Tracev((stderr, "inflate: allocated\n"));
8450 strm.state = state;
8451 state.window = null/*Z_NULL*/;
8452 ret = inflateReset2(strm, windowBits);
8453 if (ret !== Z_OK) {
8454 strm.state = null/*Z_NULL*/;
8455 }
8456 return ret;
8457 }
8458
8459 function inflateInit(strm) {
8460 return inflateInit2(strm, DEF_WBITS);
8461 }
8462
8463
8464 /*
8465 Return state with length and distance decoding tables and index sizes set to
8466 fixed code decoding. Normally this returns fixed tables from inffixed.h.
8467 If BUILDFIXED is defined, then instead this routine builds the tables the
8468 first time it's called, and returns those tables the first time and
8469 thereafter. This reduces the size of the code by about 2K bytes, in
8470 exchange for a little execution time. However, BUILDFIXED should not be
8471 used for threaded applications, since the rewriting of the tables and virgin
8472 may not be thread-safe.
8473 */
8474 var virgin = true;
8475
8476 var lenfix, distfix; // We have no pointers in JS, so keep tables separate
8477
8478 function fixedtables(state) {
8479 /* build fixed huffman tables if first call (may not be thread safe) */
8480 if (virgin) {
8481 var sym;
8482
8483 lenfix = new utils.Buf32(512);
8484 distfix = new utils.Buf32(32);
8485
8486 /* literal/length table */
8487 sym = 0;
8488 while (sym < 144) { state.lens[sym++] = 8; }
8489 while (sym < 256) { state.lens[sym++] = 9; }
8490 while (sym < 280) { state.lens[sym++] = 7; }
8491 while (sym < 288) { state.lens[sym++] = 8; }
8492
8493 inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
8494
8495 /* distance table */
8496 sym = 0;
8497 while (sym < 32) { state.lens[sym++] = 5; }
8498
8499 inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
8500
8501 /* do this just once */
8502 virgin = false;
8503 }
8504
8505 state.lencode = lenfix;
8506 state.lenbits = 9;
8507 state.distcode = distfix;
8508 state.distbits = 5;
8509 }
8510
8511
8512 /*
8513 Update the window with the last wsize (normally 32K) bytes written before
8514 returning. If window does not exist yet, create it. This is only called
8515 when a window is already in use, or when output has been written during this
8516 inflate call, but the end of the deflate stream has not been reached yet.
8517 It is also called to create a window for dictionary data when a dictionary
8518 is loaded.
8519
8520 Providing output buffers larger than 32K to inflate() should provide a speed
8521 advantage, since only the last 32K of output is copied to the sliding window
8522 upon return from inflate(), and since all distances after the first 32K of
8523 output will fall in the output data, making match copies simpler and faster.
8524 The advantage may be dependent on the size of the processor's data caches.
8525 */
8526 function updatewindow(strm, src, end, copy) {
8527 var dist;
8528 var state = strm.state;
8529
8530 /* if it hasn't been done already, allocate space for the window */
8531 if (state.window === null) {
8532 state.wsize = 1 << state.wbits;
8533 state.wnext = 0;
8534 state.whave = 0;
8535
8536 state.window = new utils.Buf8(state.wsize);
8537 }
8538
8539 /* copy state->wsize or less output bytes into the circular window */
8540 if (copy >= state.wsize) {
8541 utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
8542 state.wnext = 0;
8543 state.whave = state.wsize;
8544 }
8545 else {
8546 dist = state.wsize - state.wnext;
8547 if (dist > copy) {
8548 dist = copy;
8549 }
8550 //zmemcpy(state->window + state->wnext, end - copy, dist);
8551 utils.arraySet(state.window, src, end - copy, dist, state.wnext);
8552 copy -= dist;
8553 if (copy) {
8554 //zmemcpy(state->window, end - copy, copy);
8555 utils.arraySet(state.window, src, end - copy, copy, 0);
8556 state.wnext = copy;
8557 state.whave = state.wsize;
8558 }
8559 else {
8560 state.wnext += dist;
8561 if (state.wnext === state.wsize) { state.wnext = 0; }
8562 if (state.whave < state.wsize) { state.whave += dist; }
8563 }
8564 }
8565 return 0;
8566 }
8567
8568 function inflate(strm, flush) {
8569 var state;
8570 var input, output; // input/output buffers
8571 var next; /* next input INDEX */
8572 var put; /* next output INDEX */
8573 var have, left; /* available input and output */
8574 var hold; /* bit buffer */
8575 var bits; /* bits in bit buffer */
8576 var _in, _out; /* save starting available input and output */
8577 var copy; /* number of stored or match bytes to copy */
8578 var from; /* where to copy match bytes from */
8579 var from_source;
8580 var here = 0; /* current decoding table entry */
8581 var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
8582 //var last; /* parent table entry */
8583 var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
8584 var len; /* length to copy for repeats, bits to drop */
8585 var ret; /* return code */
8586 var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
8587 var opts;
8588
8589 var n; // temporary var for NEED_BITS
8590
8591 var order = /* permutation of code lengths */
8592 [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
8593
8594
8595 if (!strm || !strm.state || !strm.output ||
8596 (!strm.input && strm.avail_in !== 0)) {
8597 return Z_STREAM_ERROR;
8598 }
8599
8600 state = strm.state;
8601 if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
8602
8603
8604 //--- LOAD() ---
8605 put = strm.next_out;
8606 output = strm.output;
8607 left = strm.avail_out;
8608 next = strm.next_in;
8609 input = strm.input;
8610 have = strm.avail_in;
8611 hold = state.hold;
8612 bits = state.bits;
8613 //---
8614
8615 _in = have;
8616 _out = left;
8617 ret = Z_OK;
8618
8619 inf_leave: // goto emulation
8620 for (;;) {
8621 switch (state.mode) {
8622 case HEAD:
8623 if (state.wrap === 0) {
8624 state.mode = TYPEDO;
8625 break;
8626 }
8627 //=== NEEDBITS(16);
8628 while (bits < 16) {
8629 if (have === 0) { break inf_leave; }
8630 have--;
8631 hold += input[next++] << bits;
8632 bits += 8;
8633 }
8634 //===//
8635 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
8636 state.check = 0/*crc32(0L, Z_NULL, 0)*/;
8637 //=== CRC2(state.check, hold);
8638 hbuf[0] = hold & 0xff;
8639 hbuf[1] = (hold >>> 8) & 0xff;
8640 state.check = crc32(state.check, hbuf, 2, 0);
8641 //===//
8642
8643 //=== INITBITS();
8644 hold = 0;
8645 bits = 0;
8646 //===//
8647 state.mode = FLAGS;
8648 break;
8649 }
8650 state.flags = 0; /* expect zlib header */
8651 if (state.head) {
8652 state.head.done = false;
8653 }
8654 if (!(state.wrap & 1) || /* check if zlib header allowed */
8655 (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
8656 strm.msg = 'incorrect header check';
8657 state.mode = BAD;
8658 break;
8659 }
8660 if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
8661 strm.msg = 'unknown compression method';
8662 state.mode = BAD;
8663 break;
8664 }
8665 //--- DROPBITS(4) ---//
8666 hold >>>= 4;
8667 bits -= 4;
8668 //---//
8669 len = (hold & 0x0f)/*BITS(4)*/ + 8;
8670 if (state.wbits === 0) {
8671 state.wbits = len;
8672 }
8673 else if (len > state.wbits) {
8674 strm.msg = 'invalid window size';
8675 state.mode = BAD;
8676 break;
8677 }
8678 state.dmax = 1 << len;
8679 //Tracev((stderr, "inflate: zlib header ok\n"));
8680 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
8681 state.mode = hold & 0x200 ? DICTID : TYPE;
8682 //=== INITBITS();
8683 hold = 0;
8684 bits = 0;
8685 //===//
8686 break;
8687 case FLAGS:
8688 //=== NEEDBITS(16); */
8689 while (bits < 16) {
8690 if (have === 0) { break inf_leave; }
8691 have--;
8692 hold += input[next++] << bits;
8693 bits += 8;
8694 }
8695 //===//
8696 state.flags = hold;
8697 if ((state.flags & 0xff) !== Z_DEFLATED) {
8698 strm.msg = 'unknown compression method';
8699 state.mode = BAD;
8700 break;
8701 }
8702 if (state.flags & 0xe000) {
8703 strm.msg = 'unknown header flags set';
8704 state.mode = BAD;
8705 break;
8706 }
8707 if (state.head) {
8708 state.head.text = ((hold >> 8) & 1);
8709 }
8710 if (state.flags & 0x0200) {
8711 //=== CRC2(state.check, hold);
8712 hbuf[0] = hold & 0xff;
8713 hbuf[1] = (hold >>> 8) & 0xff;
8714 state.check = crc32(state.check, hbuf, 2, 0);
8715 //===//
8716 }
8717 //=== INITBITS();
8718 hold = 0;
8719 bits = 0;
8720 //===//
8721 state.mode = TIME;
8722 /* falls through */
8723 case TIME:
8724 //=== NEEDBITS(32); */
8725 while (bits < 32) {
8726 if (have === 0) { break inf_leave; }
8727 have--;
8728 hold += input[next++] << bits;
8729 bits += 8;
8730 }
8731 //===//
8732 if (state.head) {
8733 state.head.time = hold;
8734 }
8735 if (state.flags & 0x0200) {
8736 //=== CRC4(state.check, hold)
8737 hbuf[0] = hold & 0xff;
8738 hbuf[1] = (hold >>> 8) & 0xff;
8739 hbuf[2] = (hold >>> 16) & 0xff;
8740 hbuf[3] = (hold >>> 24) & 0xff;
8741 state.check = crc32(state.check, hbuf, 4, 0);
8742 //===
8743 }
8744 //=== INITBITS();
8745 hold = 0;
8746 bits = 0;
8747 //===//
8748 state.mode = OS;
8749 /* falls through */
8750 case OS:
8751 //=== NEEDBITS(16); */
8752 while (bits < 16) {
8753 if (have === 0) { break inf_leave; }
8754 have--;
8755 hold += input[next++] << bits;
8756 bits += 8;
8757 }
8758 //===//
8759 if (state.head) {
8760 state.head.xflags = (hold & 0xff);
8761 state.head.os = (hold >> 8);
8762 }
8763 if (state.flags & 0x0200) {
8764 //=== CRC2(state.check, hold);
8765 hbuf[0] = hold & 0xff;
8766 hbuf[1] = (hold >>> 8) & 0xff;
8767 state.check = crc32(state.check, hbuf, 2, 0);
8768 //===//
8769 }
8770 //=== INITBITS();
8771 hold = 0;
8772 bits = 0;
8773 //===//
8774 state.mode = EXLEN;
8775 /* falls through */
8776 case EXLEN:
8777 if (state.flags & 0x0400) {
8778 //=== NEEDBITS(16); */
8779 while (bits < 16) {
8780 if (have === 0) { break inf_leave; }
8781 have--;
8782 hold += input[next++] << bits;
8783 bits += 8;
8784 }
8785 //===//
8786 state.length = hold;
8787 if (state.head) {
8788 state.head.extra_len = hold;
8789 }
8790 if (state.flags & 0x0200) {
8791 //=== CRC2(state.check, hold);
8792 hbuf[0] = hold & 0xff;
8793 hbuf[1] = (hold >>> 8) & 0xff;
8794 state.check = crc32(state.check, hbuf, 2, 0);
8795 //===//
8796 }
8797 //=== INITBITS();
8798 hold = 0;
8799 bits = 0;
8800 //===//
8801 }
8802 else if (state.head) {
8803 state.head.extra = null/*Z_NULL*/;
8804 }
8805 state.mode = EXTRA;
8806 /* falls through */
8807 case EXTRA:
8808 if (state.flags & 0x0400) {
8809 copy = state.length;
8810 if (copy > have) { copy = have; }
8811 if (copy) {
8812 if (state.head) {
8813 len = state.head.extra_len - state.length;
8814 if (!state.head.extra) {
8815 // Use untyped array for more conveniend processing later
8816 state.head.extra = new Array(state.head.extra_len);
8817 }
8818 utils.arraySet(
8819 state.head.extra,
8820 input,
8821 next,
8822 // extra field is limited to 65536 bytes
8823 // - no need for additional size check
8824 copy,
8825 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
8826 len
8827 );
8828 //zmemcpy(state.head.extra + len, next,
8829 // len + copy > state.head.extra_max ?
8830 // state.head.extra_max - len : copy);
8831 }
8832 if (state.flags & 0x0200) {
8833 state.check = crc32(state.check, input, copy, next);
8834 }
8835 have -= copy;
8836 next += copy;
8837 state.length -= copy;
8838 }
8839 if (state.length) { break inf_leave; }
8840 }
8841 state.length = 0;
8842 state.mode = NAME;
8843 /* falls through */
8844 case NAME:
8845 if (state.flags & 0x0800) {
8846 if (have === 0) { break inf_leave; }
8847 copy = 0;
8848 do {
8849 // TODO: 2 or 1 bytes?
8850 len = input[next + copy++];
8851 /* use constant limit because in js we should not preallocate memory */
8852 if (state.head && len &&
8853 (state.length < 65536 /*state.head.name_max*/)) {
8854 state.head.name += String.fromCharCode(len);
8855 }
8856 } while (len && copy < have);
8857
8858 if (state.flags & 0x0200) {
8859 state.check = crc32(state.check, input, copy, next);
8860 }
8861 have -= copy;
8862 next += copy;
8863 if (len) { break inf_leave; }
8864 }
8865 else if (state.head) {
8866 state.head.name = null;
8867 }
8868 state.length = 0;
8869 state.mode = COMMENT;
8870 /* falls through */
8871 case COMMENT:
8872 if (state.flags & 0x1000) {
8873 if (have === 0) { break inf_leave; }
8874 copy = 0;
8875 do {
8876 len = input[next + copy++];
8877 /* use constant limit because in js we should not preallocate memory */
8878 if (state.head && len &&
8879 (state.length < 65536 /*state.head.comm_max*/)) {
8880 state.head.comment += String.fromCharCode(len);
8881 }
8882 } while (len && copy < have);
8883 if (state.flags & 0x0200) {
8884 state.check = crc32(state.check, input, copy, next);
8885 }
8886 have -= copy;
8887 next += copy;
8888 if (len) { break inf_leave; }
8889 }
8890 else if (state.head) {
8891 state.head.comment = null;
8892 }
8893 state.mode = HCRC;
8894 /* falls through */
8895 case HCRC:
8896 if (state.flags & 0x0200) {
8897 //=== NEEDBITS(16); */
8898 while (bits < 16) {
8899 if (have === 0) { break inf_leave; }
8900 have--;
8901 hold += input[next++] << bits;
8902 bits += 8;
8903 }
8904 //===//
8905 if (hold !== (state.check & 0xffff)) {
8906 strm.msg = 'header crc mismatch';
8907 state.mode = BAD;
8908 break;
8909 }
8910 //=== INITBITS();
8911 hold = 0;
8912 bits = 0;
8913 //===//
8914 }
8915 if (state.head) {
8916 state.head.hcrc = ((state.flags >> 9) & 1);
8917 state.head.done = true;
8918 }
8919 strm.adler = state.check = 0;
8920 state.mode = TYPE;
8921 break;
8922 case DICTID:
8923 //=== NEEDBITS(32); */
8924 while (bits < 32) {
8925 if (have === 0) { break inf_leave; }
8926 have--;
8927 hold += input[next++] << bits;
8928 bits += 8;
8929 }
8930 //===//
8931 strm.adler = state.check = zswap32(hold);
8932 //=== INITBITS();
8933 hold = 0;
8934 bits = 0;
8935 //===//
8936 state.mode = DICT;
8937 /* falls through */
8938 case DICT:
8939 if (state.havedict === 0) {
8940 //--- RESTORE() ---
8941 strm.next_out = put;
8942 strm.avail_out = left;
8943 strm.next_in = next;
8944 strm.avail_in = have;
8945 state.hold = hold;
8946 state.bits = bits;
8947 //---
8948 return Z_NEED_DICT;
8949 }
8950 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
8951 state.mode = TYPE;
8952 /* falls through */
8953 case TYPE:
8954 if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
8955 /* falls through */
8956 case TYPEDO:
8957 if (state.last) {
8958 //--- BYTEBITS() ---//
8959 hold >>>= bits & 7;
8960 bits -= bits & 7;
8961 //---//
8962 state.mode = CHECK;
8963 break;
8964 }
8965 //=== NEEDBITS(3); */
8966 while (bits < 3) {
8967 if (have === 0) { break inf_leave; }
8968 have--;
8969 hold += input[next++] << bits;
8970 bits += 8;
8971 }
8972 //===//
8973 state.last = (hold & 0x01)/*BITS(1)*/;
8974 //--- DROPBITS(1) ---//
8975 hold >>>= 1;
8976 bits -= 1;
8977 //---//
8978
8979 switch ((hold & 0x03)/*BITS(2)*/) {
8980 case 0: /* stored block */
8981 //Tracev((stderr, "inflate: stored block%s\n",
8982 // state.last ? " (last)" : ""));
8983 state.mode = STORED;
8984 break;
8985 case 1: /* fixed block */
8986 fixedtables(state);
8987 //Tracev((stderr, "inflate: fixed codes block%s\n",
8988 // state.last ? " (last)" : ""));
8989 state.mode = LEN_; /* decode codes */
8990 if (flush === Z_TREES) {
8991 //--- DROPBITS(2) ---//
8992 hold >>>= 2;
8993 bits -= 2;
8994 //---//
8995 break inf_leave;
8996 }
8997 break;
8998 case 2: /* dynamic block */
8999 //Tracev((stderr, "inflate: dynamic codes block%s\n",
9000 // state.last ? " (last)" : ""));
9001 state.mode = TABLE;
9002 break;
9003 case 3:
9004 strm.msg = 'invalid block type';
9005 state.mode = BAD;
9006 }
9007 //--- DROPBITS(2) ---//
9008 hold >>>= 2;
9009 bits -= 2;
9010 //---//
9011 break;
9012 case STORED:
9013 //--- BYTEBITS() ---// /* go to byte boundary */
9014 hold >>>= bits & 7;
9015 bits -= bits & 7;
9016 //---//
9017 //=== NEEDBITS(32); */
9018 while (bits < 32) {
9019 if (have === 0) { break inf_leave; }
9020 have--;
9021 hold += input[next++] << bits;
9022 bits += 8;
9023 }
9024 //===//
9025 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
9026 strm.msg = 'invalid stored block lengths';
9027 state.mode = BAD;
9028 break;
9029 }
9030 state.length = hold & 0xffff;
9031 //Tracev((stderr, "inflate: stored length %u\n",
9032 // state.length));
9033 //=== INITBITS();
9034 hold = 0;
9035 bits = 0;
9036 //===//
9037 state.mode = COPY_;
9038 if (flush === Z_TREES) { break inf_leave; }
9039 /* falls through */
9040 case COPY_:
9041 state.mode = COPY;
9042 /* falls through */
9043 case COPY:
9044 copy = state.length;
9045 if (copy) {
9046 if (copy > have) { copy = have; }
9047 if (copy > left) { copy = left; }
9048 if (copy === 0) { break inf_leave; }
9049 //--- zmemcpy(put, next, copy); ---
9050 utils.arraySet(output, input, next, copy, put);
9051 //---//
9052 have -= copy;
9053 next += copy;
9054 left -= copy;
9055 put += copy;
9056 state.length -= copy;
9057 break;
9058 }
9059 //Tracev((stderr, "inflate: stored end\n"));
9060 state.mode = TYPE;
9061 break;
9062 case TABLE:
9063 //=== NEEDBITS(14); */
9064 while (bits < 14) {
9065 if (have === 0) { break inf_leave; }
9066 have--;
9067 hold += input[next++] << bits;
9068 bits += 8;
9069 }
9070 //===//
9071 state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
9072 //--- DROPBITS(5) ---//
9073 hold >>>= 5;
9074 bits -= 5;
9075 //---//
9076 state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
9077 //--- DROPBITS(5) ---//
9078 hold >>>= 5;
9079 bits -= 5;
9080 //---//
9081 state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
9082 //--- DROPBITS(4) ---//
9083 hold >>>= 4;
9084 bits -= 4;
9085 //---//
9086 //#ifndef PKZIP_BUG_WORKAROUND
9087 if (state.nlen > 286 || state.ndist > 30) {
9088 strm.msg = 'too many length or distance symbols';
9089 state.mode = BAD;
9090 break;
9091 }
9092 //#endif
9093 //Tracev((stderr, "inflate: table sizes ok\n"));
9094 state.have = 0;
9095 state.mode = LENLENS;
9096 /* falls through */
9097 case LENLENS:
9098 while (state.have < state.ncode) {
9099 //=== NEEDBITS(3);
9100 while (bits < 3) {
9101 if (have === 0) { break inf_leave; }
9102 have--;
9103 hold += input[next++] << bits;
9104 bits += 8;
9105 }
9106 //===//
9107 state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
9108 //--- DROPBITS(3) ---//
9109 hold >>>= 3;
9110 bits -= 3;
9111 //---//
9112 }
9113 while (state.have < 19) {
9114 state.lens[order[state.have++]] = 0;
9115 }
9116 // We have separate tables & no pointers. 2 commented lines below not needed.
9117 //state.next = state.codes;
9118 //state.lencode = state.next;
9119 // Switch to use dynamic table
9120 state.lencode = state.lendyn;
9121 state.lenbits = 7;
9122
9123 opts = { bits: state.lenbits };
9124 ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
9125 state.lenbits = opts.bits;
9126
9127 if (ret) {
9128 strm.msg = 'invalid code lengths set';
9129 state.mode = BAD;
9130 break;
9131 }
9132 //Tracev((stderr, "inflate: code lengths ok\n"));
9133 state.have = 0;
9134 state.mode = CODELENS;
9135 /* falls through */
9136 case CODELENS:
9137 while (state.have < state.nlen + state.ndist) {
9138 for (;;) {
9139 here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
9140 here_bits = here >>> 24;
9141 here_op = (here >>> 16) & 0xff;
9142 here_val = here & 0xffff;
9143
9144 if ((here_bits) <= bits) { break; }
9145 //--- PULLBYTE() ---//
9146 if (have === 0) { break inf_leave; }
9147 have--;
9148 hold += input[next++] << bits;
9149 bits += 8;
9150 //---//
9151 }
9152 if (here_val < 16) {
9153 //--- DROPBITS(here.bits) ---//
9154 hold >>>= here_bits;
9155 bits -= here_bits;
9156 //---//
9157 state.lens[state.have++] = here_val;
9158 }
9159 else {
9160 if (here_val === 16) {
9161 //=== NEEDBITS(here.bits + 2);
9162 n = here_bits + 2;
9163 while (bits < n) {
9164 if (have === 0) { break inf_leave; }
9165 have--;
9166 hold += input[next++] << bits;
9167 bits += 8;
9168 }
9169 //===//
9170 //--- DROPBITS(here.bits) ---//
9171 hold >>>= here_bits;
9172 bits -= here_bits;
9173 //---//
9174 if (state.have === 0) {
9175 strm.msg = 'invalid bit length repeat';
9176 state.mode = BAD;
9177 break;
9178 }
9179 len = state.lens[state.have - 1];
9180 copy = 3 + (hold & 0x03);//BITS(2);
9181 //--- DROPBITS(2) ---//
9182 hold >>>= 2;
9183 bits -= 2;
9184 //---//
9185 }
9186 else if (here_val === 17) {
9187 //=== NEEDBITS(here.bits + 3);
9188 n = here_bits + 3;
9189 while (bits < n) {
9190 if (have === 0) { break inf_leave; }
9191 have--;
9192 hold += input[next++] << bits;
9193 bits += 8;
9194 }
9195 //===//
9196 //--- DROPBITS(here.bits) ---//
9197 hold >>>= here_bits;
9198 bits -= here_bits;
9199 //---//
9200 len = 0;
9201 copy = 3 + (hold & 0x07);//BITS(3);
9202 //--- DROPBITS(3) ---//
9203 hold >>>= 3;
9204 bits -= 3;
9205 //---//
9206 }
9207 else {
9208 //=== NEEDBITS(here.bits + 7);
9209 n = here_bits + 7;
9210 while (bits < n) {
9211 if (have === 0) { break inf_leave; }
9212 have--;
9213 hold += input[next++] << bits;
9214 bits += 8;
9215 }
9216 //===//
9217 //--- DROPBITS(here.bits) ---//
9218 hold >>>= here_bits;
9219 bits -= here_bits;
9220 //---//
9221 len = 0;
9222 copy = 11 + (hold & 0x7f);//BITS(7);
9223 //--- DROPBITS(7) ---//
9224 hold >>>= 7;
9225 bits -= 7;
9226 //---//
9227 }
9228 if (state.have + copy > state.nlen + state.ndist) {
9229 strm.msg = 'invalid bit length repeat';
9230 state.mode = BAD;
9231 break;
9232 }
9233 while (copy--) {
9234 state.lens[state.have++] = len;
9235 }
9236 }
9237 }
9238
9239 /* handle error breaks in while */
9240 if (state.mode === BAD) { break; }
9241
9242 /* check for end-of-block code (better have one) */
9243 if (state.lens[256] === 0) {
9244 strm.msg = 'invalid code -- missing end-of-block';
9245 state.mode = BAD;
9246 break;
9247 }
9248
9249 /* build code tables -- note: do not change the lenbits or distbits
9250 values here (9 and 6) without reading the comments in inftrees.h
9251 concerning the ENOUGH constants, which depend on those values */
9252 state.lenbits = 9;
9253
9254 opts = { bits: state.lenbits };
9255 ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
9256 // We have separate tables & no pointers. 2 commented lines below not needed.
9257 // state.next_index = opts.table_index;
9258 state.lenbits = opts.bits;
9259 // state.lencode = state.next;
9260
9261 if (ret) {
9262 strm.msg = 'invalid literal/lengths set';
9263 state.mode = BAD;
9264 break;
9265 }
9266
9267 state.distbits = 6;
9268 //state.distcode.copy(state.codes);
9269 // Switch to use dynamic table
9270 state.distcode = state.distdyn;
9271 opts = { bits: state.distbits };
9272 ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
9273 // We have separate tables & no pointers. 2 commented lines below not needed.
9274 // state.next_index = opts.table_index;
9275 state.distbits = opts.bits;
9276 // state.distcode = state.next;
9277
9278 if (ret) {
9279 strm.msg = 'invalid distances set';
9280 state.mode = BAD;
9281 break;
9282 }
9283 //Tracev((stderr, 'inflate: codes ok\n'));
9284 state.mode = LEN_;
9285 if (flush === Z_TREES) { break inf_leave; }
9286 /* falls through */
9287 case LEN_:
9288 state.mode = LEN;
9289 /* falls through */
9290 case LEN:
9291 if (have >= 6 && left >= 258) {
9292 //--- RESTORE() ---
9293 strm.next_out = put;
9294 strm.avail_out = left;
9295 strm.next_in = next;
9296 strm.avail_in = have;
9297 state.hold = hold;
9298 state.bits = bits;
9299 //---
9300 inflate_fast(strm, _out);
9301 //--- LOAD() ---
9302 put = strm.next_out;
9303 output = strm.output;
9304 left = strm.avail_out;
9305 next = strm.next_in;
9306 input = strm.input;
9307 have = strm.avail_in;
9308 hold = state.hold;
9309 bits = state.bits;
9310 //---
9311
9312 if (state.mode === TYPE) {
9313 state.back = -1;
9314 }
9315 break;
9316 }
9317 state.back = 0;
9318 for (;;) {
9319 here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
9320 here_bits = here >>> 24;
9321 here_op = (here >>> 16) & 0xff;
9322 here_val = here & 0xffff;
9323
9324 if (here_bits <= bits) { break; }
9325 //--- PULLBYTE() ---//
9326 if (have === 0) { break inf_leave; }
9327 have--;
9328 hold += input[next++] << bits;
9329 bits += 8;
9330 //---//
9331 }
9332 if (here_op && (here_op & 0xf0) === 0) {
9333 last_bits = here_bits;
9334 last_op = here_op;
9335 last_val = here_val;
9336 for (;;) {
9337 here = state.lencode[last_val +
9338 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
9339 here_bits = here >>> 24;
9340 here_op = (here >>> 16) & 0xff;
9341 here_val = here & 0xffff;
9342
9343 if ((last_bits + here_bits) <= bits) { break; }
9344 //--- PULLBYTE() ---//
9345 if (have === 0) { break inf_leave; }
9346 have--;
9347 hold += input[next++] << bits;
9348 bits += 8;
9349 //---//
9350 }
9351 //--- DROPBITS(last.bits) ---//
9352 hold >>>= last_bits;
9353 bits -= last_bits;
9354 //---//
9355 state.back += last_bits;
9356 }
9357 //--- DROPBITS(here.bits) ---//
9358 hold >>>= here_bits;
9359 bits -= here_bits;
9360 //---//
9361 state.back += here_bits;
9362 state.length = here_val;
9363 if (here_op === 0) {
9364 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
9365 // "inflate: literal '%c'\n" :
9366 // "inflate: literal 0x%02x\n", here.val));
9367 state.mode = LIT;
9368 break;
9369 }
9370 if (here_op & 32) {
9371 //Tracevv((stderr, "inflate: end of block\n"));
9372 state.back = -1;
9373 state.mode = TYPE;
9374 break;
9375 }
9376 if (here_op & 64) {
9377 strm.msg = 'invalid literal/length code';
9378 state.mode = BAD;
9379 break;
9380 }
9381 state.extra = here_op & 15;
9382 state.mode = LENEXT;
9383 /* falls through */
9384 case LENEXT:
9385 if (state.extra) {
9386 //=== NEEDBITS(state.extra);
9387 n = state.extra;
9388 while (bits < n) {
9389 if (have === 0) { break inf_leave; }
9390 have--;
9391 hold += input[next++] << bits;
9392 bits += 8;
9393 }
9394 //===//
9395 state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
9396 //--- DROPBITS(state.extra) ---//
9397 hold >>>= state.extra;
9398 bits -= state.extra;
9399 //---//
9400 state.back += state.extra;
9401 }
9402 //Tracevv((stderr, "inflate: length %u\n", state.length));
9403 state.was = state.length;
9404 state.mode = DIST;
9405 /* falls through */
9406 case DIST:
9407 for (;;) {
9408 here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
9409 here_bits = here >>> 24;
9410 here_op = (here >>> 16) & 0xff;
9411 here_val = here & 0xffff;
9412
9413 if ((here_bits) <= bits) { break; }
9414 //--- PULLBYTE() ---//
9415 if (have === 0) { break inf_leave; }
9416 have--;
9417 hold += input[next++] << bits;
9418 bits += 8;
9419 //---//
9420 }
9421 if ((here_op & 0xf0) === 0) {
9422 last_bits = here_bits;
9423 last_op = here_op;
9424 last_val = here_val;
9425 for (;;) {
9426 here = state.distcode[last_val +
9427 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
9428 here_bits = here >>> 24;
9429 here_op = (here >>> 16) & 0xff;
9430 here_val = here & 0xffff;
9431
9432 if ((last_bits + here_bits) <= bits) { break; }
9433 //--- PULLBYTE() ---//
9434 if (have === 0) { break inf_leave; }
9435 have--;
9436 hold += input[next++] << bits;
9437 bits += 8;
9438 //---//
9439 }
9440 //--- DROPBITS(last.bits) ---//
9441 hold >>>= last_bits;
9442 bits -= last_bits;
9443 //---//
9444 state.back += last_bits;
9445 }
9446 //--- DROPBITS(here.bits) ---//
9447 hold >>>= here_bits;
9448 bits -= here_bits;
9449 //---//
9450 state.back += here_bits;
9451 if (here_op & 64) {
9452 strm.msg = 'invalid distance code';
9453 state.mode = BAD;
9454 break;
9455 }
9456 state.offset = here_val;
9457 state.extra = (here_op) & 15;
9458 state.mode = DISTEXT;
9459 /* falls through */
9460 case DISTEXT:
9461 if (state.extra) {
9462 //=== NEEDBITS(state.extra);
9463 n = state.extra;
9464 while (bits < n) {
9465 if (have === 0) { break inf_leave; }
9466 have--;
9467 hold += input[next++] << bits;
9468 bits += 8;
9469 }
9470 //===//
9471 state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
9472 //--- DROPBITS(state.extra) ---//
9473 hold >>>= state.extra;
9474 bits -= state.extra;
9475 //---//
9476 state.back += state.extra;
9477 }
9478 //#ifdef INFLATE_STRICT
9479 if (state.offset > state.dmax) {
9480 strm.msg = 'invalid distance too far back';
9481 state.mode = BAD;
9482 break;
9483 }
9484 //#endif
9485 //Tracevv((stderr, "inflate: distance %u\n", state.offset));
9486 state.mode = MATCH;
9487 /* falls through */
9488 case MATCH:
9489 if (left === 0) { break inf_leave; }
9490 copy = _out - left;
9491 if (state.offset > copy) { /* copy from window */
9492 copy = state.offset - copy;
9493 if (copy > state.whave) {
9494 if (state.sane) {
9495 strm.msg = 'invalid distance too far back';
9496 state.mode = BAD;
9497 break;
9498 }
9499 // (!) This block is disabled in zlib defailts,
9500 // don't enable it for binary compatibility
9501 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
9502 // Trace((stderr, "inflate.c too far\n"));
9503 // copy -= state.whave;
9504 // if (copy > state.length) { copy = state.length; }
9505 // if (copy > left) { copy = left; }
9506 // left -= copy;
9507 // state.length -= copy;
9508 // do {
9509 // output[put++] = 0;
9510 // } while (--copy);
9511 // if (state.length === 0) { state.mode = LEN; }
9512 // break;
9513 //#endif
9514 }
9515 if (copy > state.wnext) {
9516 copy -= state.wnext;
9517 from = state.wsize - copy;
9518 }
9519 else {
9520 from = state.wnext - copy;
9521 }
9522 if (copy > state.length) { copy = state.length; }
9523 from_source = state.window;
9524 }
9525 else { /* copy from output */
9526 from_source = output;
9527 from = put - state.offset;
9528 copy = state.length;
9529 }
9530 if (copy > left) { copy = left; }
9531 left -= copy;
9532 state.length -= copy;
9533 do {
9534 output[put++] = from_source[from++];
9535 } while (--copy);
9536 if (state.length === 0) { state.mode = LEN; }
9537 break;
9538 case LIT:
9539 if (left === 0) { break inf_leave; }
9540 output[put++] = state.length;
9541 left--;
9542 state.mode = LEN;
9543 break;
9544 case CHECK:
9545 if (state.wrap) {
9546 //=== NEEDBITS(32);
9547 while (bits < 32) {
9548 if (have === 0) { break inf_leave; }
9549 have--;
9550 // Use '|' insdead of '+' to make sure that result is signed
9551 hold |= input[next++] << bits;
9552 bits += 8;
9553 }
9554 //===//
9555 _out -= left;
9556 strm.total_out += _out;
9557 state.total += _out;
9558 if (_out) {
9559 strm.adler = state.check =
9560 /*UPDATE(state.check, put - _out, _out);*/
9561 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
9562
9563 }
9564 _out = left;
9565 // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
9566 if ((state.flags ? hold : zswap32(hold)) !== state.check) {
9567 strm.msg = 'incorrect data check';
9568 state.mode = BAD;
9569 break;
9570 }
9571 //=== INITBITS();
9572 hold = 0;
9573 bits = 0;
9574 //===//
9575 //Tracev((stderr, "inflate: check matches trailer\n"));
9576 }
9577 state.mode = LENGTH;
9578 /* falls through */
9579 case LENGTH:
9580 if (state.wrap && state.flags) {
9581 //=== NEEDBITS(32);
9582 while (bits < 32) {
9583 if (have === 0) { break inf_leave; }
9584 have--;
9585 hold += input[next++] << bits;
9586 bits += 8;
9587 }
9588 //===//
9589 if (hold !== (state.total & 0xffffffff)) {
9590 strm.msg = 'incorrect length check';
9591 state.mode = BAD;
9592 break;
9593 }
9594 //=== INITBITS();
9595 hold = 0;
9596 bits = 0;
9597 //===//
9598 //Tracev((stderr, "inflate: length matches trailer\n"));
9599 }
9600 state.mode = DONE;
9601 /* falls through */
9602 case DONE:
9603 ret = Z_STREAM_END;
9604 break inf_leave;
9605 case BAD:
9606 ret = Z_DATA_ERROR;
9607 break inf_leave;
9608 case MEM:
9609 return Z_MEM_ERROR;
9610 case SYNC:
9611 /* falls through */
9612 default:
9613 return Z_STREAM_ERROR;
9614 }
9615 }
9616
9617 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
9618
9619 /*
9620 Return from inflate(), updating the total counts and the check value.
9621 If there was no progress during the inflate() call, return a buffer
9622 error. Call updatewindow() to create and/or update the window state.
9623 Note: a memory error from inflate() is non-recoverable.
9624 */
9625
9626 //--- RESTORE() ---
9627 strm.next_out = put;
9628 strm.avail_out = left;
9629 strm.next_in = next;
9630 strm.avail_in = have;
9631 state.hold = hold;
9632 state.bits = bits;
9633 //---
9634
9635 if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
9636 (state.mode < CHECK || flush !== Z_FINISH))) {
9637 if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
9638 state.mode = MEM;
9639 return Z_MEM_ERROR;
9640 }
9641 }
9642 _in -= strm.avail_in;
9643 _out -= strm.avail_out;
9644 strm.total_in += _in;
9645 strm.total_out += _out;
9646 state.total += _out;
9647 if (state.wrap && _out) {
9648 strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
9649 (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
9650 }
9651 strm.data_type = state.bits + (state.last ? 64 : 0) +
9652 (state.mode === TYPE ? 128 : 0) +
9653 (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
9654 if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
9655 ret = Z_BUF_ERROR;
9656 }
9657 return ret;
9658 }
9659
9660 function inflateEnd(strm) {
9661
9662 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
9663 return Z_STREAM_ERROR;
9664 }
9665
9666 var state = strm.state;
9667 if (state.window) {
9668 state.window = null;
9669 }
9670 strm.state = null;
9671 return Z_OK;
9672 }
9673
9674 function inflateGetHeader(strm, head) {
9675 var state;
9676
9677 /* check state */
9678 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
9679 state = strm.state;
9680 if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
9681
9682 /* save header structure */
9683 state.head = head;
9684 head.done = false;
9685 return Z_OK;
9686 }
9687
9688 function inflateSetDictionary(strm, dictionary) {
9689 var dictLength = dictionary.length;
9690
9691 var state;
9692 var dictid;
9693 var ret;
9694
9695 /* check state */
9696 if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
9697 state = strm.state;
9698
9699 if (state.wrap !== 0 && state.mode !== DICT) {
9700 return Z_STREAM_ERROR;
9701 }
9702
9703 /* check for correct dictionary identifier */
9704 if (state.mode === DICT) {
9705 dictid = 1; /* adler32(0, null, 0)*/
9706 /* dictid = adler32(dictid, dictionary, dictLength); */
9707 dictid = adler32(dictid, dictionary, dictLength, 0);
9708 if (dictid !== state.check) {
9709 return Z_DATA_ERROR;
9710 }
9711 }
9712 /* copy dictionary to window using updatewindow(), which will amend the
9713 existing dictionary if appropriate */
9714 ret = updatewindow(strm, dictionary, dictLength, dictLength);
9715 if (ret) {
9716 state.mode = MEM;
9717 return Z_MEM_ERROR;
9718 }
9719 state.havedict = 1;
9720 // Tracev((stderr, "inflate: dictionary set\n"));
9721 return Z_OK;
9722 }
9723
9724 exports.inflateReset = inflateReset;
9725 exports.inflateReset2 = inflateReset2;
9726 exports.inflateResetKeep = inflateResetKeep;
9727 exports.inflateInit = inflateInit;
9728 exports.inflateInit2 = inflateInit2;
9729 exports.inflate = inflate;
9730 exports.inflateEnd = inflateEnd;
9731 exports.inflateGetHeader = inflateGetHeader;
9732 exports.inflateSetDictionary = inflateSetDictionary;
9733 exports.inflateInfo = 'pako inflate (from Nodeca project)';
9734
9735 /* Not implemented
9736 exports.inflateCopy = inflateCopy;
9737 exports.inflateGetDictionary = inflateGetDictionary;
9738 exports.inflateMark = inflateMark;
9739 exports.inflatePrime = inflatePrime;
9740 exports.inflateSync = inflateSync;
9741 exports.inflateSyncPoint = inflateSyncPoint;
9742 exports.inflateUndermine = inflateUndermine;
9743 */
9744
9745 },{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(require,module,exports){
9746 'use strict';
9747
9748 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
9749 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
9750 //
9751 // This software is provided 'as-is', without any express or implied
9752 // warranty. In no event will the authors be held liable for any damages
9753 // arising from the use of this software.
9754 //
9755 // Permission is granted to anyone to use this software for any purpose,
9756 // including commercial applications, and to alter it and redistribute it
9757 // freely, subject to the following restrictions:
9758 //
9759 // 1. The origin of this software must not be misrepresented; you must not
9760 // claim that you wrote the original software. If you use this software
9761 // in a product, an acknowledgment in the product documentation would be
9762 // appreciated but is not required.
9763 // 2. Altered source versions must be plainly marked as such, and must not be
9764 // misrepresented as being the original software.
9765 // 3. This notice may not be removed or altered from any source distribution.
9766
9767 var utils = require('../utils/common');
9768
9769 var MAXBITS = 15;
9770 var ENOUGH_LENS = 852;
9771 var ENOUGH_DISTS = 592;
9772 //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
9773
9774 var CODES = 0;
9775 var LENS = 1;
9776 var DISTS = 2;
9777
9778 var lbase = [ /* Length codes 257..285 base */
9779 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
9780 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
9781 ];
9782
9783 var lext = [ /* Length codes 257..285 extra */
9784 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
9785 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
9786 ];
9787
9788 var dbase = [ /* Distance codes 0..29 base */
9789 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
9790 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
9791 8193, 12289, 16385, 24577, 0, 0
9792 ];
9793
9794 var dext = [ /* Distance codes 0..29 extra */
9795 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
9796 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
9797 28, 28, 29, 29, 64, 64
9798 ];
9799
9800 module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
9801 {
9802 var bits = opts.bits;
9803 //here = opts.here; /* table entry for duplication */
9804
9805 var len = 0; /* a code's length in bits */
9806 var sym = 0; /* index of code symbols */
9807 var min = 0, max = 0; /* minimum and maximum code lengths */
9808 var root = 0; /* number of index bits for root table */
9809 var curr = 0; /* number of index bits for current table */
9810 var drop = 0; /* code bits to drop for sub-table */
9811 var left = 0; /* number of prefix codes available */
9812 var used = 0; /* code entries in table used */
9813 var huff = 0; /* Huffman code */
9814 var incr; /* for incrementing code, index */
9815 var fill; /* index for replicating entries */
9816 var low; /* low bits for current root entry */
9817 var mask; /* mask for low root bits */
9818 var next; /* next available space in table */
9819 var base = null; /* base value table to use */
9820 var base_index = 0;
9821 // var shoextra; /* extra bits table to use */
9822 var end; /* use base and extra for symbol > end */
9823 var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
9824 var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
9825 var extra = null;
9826 var extra_index = 0;
9827
9828 var here_bits, here_op, here_val;
9829
9830 /*
9831 Process a set of code lengths to create a canonical Huffman code. The
9832 code lengths are lens[0..codes-1]. Each length corresponds to the
9833 symbols 0..codes-1. The Huffman code is generated by first sorting the
9834 symbols by length from short to long, and retaining the symbol order
9835 for codes with equal lengths. Then the code starts with all zero bits
9836 for the first code of the shortest length, and the codes are integer
9837 increments for the same length, and zeros are appended as the length
9838 increases. For the deflate format, these bits are stored backwards
9839 from their more natural integer increment ordering, and so when the
9840 decoding tables are built in the large loop below, the integer codes
9841 are incremented backwards.
9842
9843 This routine assumes, but does not check, that all of the entries in
9844 lens[] are in the range 0..MAXBITS. The caller must assure this.
9845 1..MAXBITS is interpreted as that code length. zero means that that
9846 symbol does not occur in this code.
9847
9848 The codes are sorted by computing a count of codes for each length,
9849 creating from that a table of starting indices for each length in the
9850 sorted table, and then entering the symbols in order in the sorted
9851 table. The sorted table is work[], with that space being provided by
9852 the caller.
9853
9854 The length counts are used for other purposes as well, i.e. finding
9855 the minimum and maximum length codes, determining if there are any
9856 codes at all, checking for a valid set of lengths, and looking ahead
9857 at length counts to determine sub-table sizes when building the
9858 decoding tables.
9859 */
9860
9861 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
9862 for (len = 0; len <= MAXBITS; len++) {
9863 count[len] = 0;
9864 }
9865 for (sym = 0; sym < codes; sym++) {
9866 count[lens[lens_index + sym]]++;
9867 }
9868
9869 /* bound code lengths, force root to be within code lengths */
9870 root = bits;
9871 for (max = MAXBITS; max >= 1; max--) {
9872 if (count[max] !== 0) { break; }
9873 }
9874 if (root > max) {
9875 root = max;
9876 }
9877 if (max === 0) { /* no symbols to code at all */
9878 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
9879 //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
9880 //table.val[opts.table_index++] = 0; //here.val = (var short)0;
9881 table[table_index++] = (1 << 24) | (64 << 16) | 0;
9882
9883
9884 //table.op[opts.table_index] = 64;
9885 //table.bits[opts.table_index] = 1;
9886 //table.val[opts.table_index++] = 0;
9887 table[table_index++] = (1 << 24) | (64 << 16) | 0;
9888
9889 opts.bits = 1;
9890 return 0; /* no symbols, but wait for decoding to report error */
9891 }
9892 for (min = 1; min < max; min++) {
9893 if (count[min] !== 0) { break; }
9894 }
9895 if (root < min) {
9896 root = min;
9897 }
9898
9899 /* check for an over-subscribed or incomplete set of lengths */
9900 left = 1;
9901 for (len = 1; len <= MAXBITS; len++) {
9902 left <<= 1;
9903 left -= count[len];
9904 if (left < 0) {
9905 return -1;
9906 } /* over-subscribed */
9907 }
9908 if (left > 0 && (type === CODES || max !== 1)) {
9909 return -1; /* incomplete set */
9910 }
9911
9912 /* generate offsets into symbol table for each length for sorting */
9913 offs[1] = 0;
9914 for (len = 1; len < MAXBITS; len++) {
9915 offs[len + 1] = offs[len] + count[len];
9916 }
9917
9918 /* sort symbols by length, by symbol order within each length */
9919 for (sym = 0; sym < codes; sym++) {
9920 if (lens[lens_index + sym] !== 0) {
9921 work[offs[lens[lens_index + sym]]++] = sym;
9922 }
9923 }
9924
9925 /*
9926 Create and fill in decoding tables. In this loop, the table being
9927 filled is at next and has curr index bits. The code being used is huff
9928 with length len. That code is converted to an index by dropping drop
9929 bits off of the bottom. For codes where len is less than drop + curr,
9930 those top drop + curr - len bits are incremented through all values to
9931 fill the table with replicated entries.
9932
9933 root is the number of index bits for the root table. When len exceeds
9934 root, sub-tables are created pointed to by the root entry with an index
9935 of the low root bits of huff. This is saved in low to check for when a
9936 new sub-table should be started. drop is zero when the root table is
9937 being filled, and drop is root when sub-tables are being filled.
9938
9939 When a new sub-table is needed, it is necessary to look ahead in the
9940 code lengths to determine what size sub-table is needed. The length
9941 counts are used for this, and so count[] is decremented as codes are
9942 entered in the tables.
9943
9944 used keeps track of how many table entries have been allocated from the
9945 provided *table space. It is checked for LENS and DIST tables against
9946 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
9947 the initial root table size constants. See the comments in inftrees.h
9948 for more information.
9949
9950 sym increments through all symbols, and the loop terminates when
9951 all codes of length max, i.e. all codes, have been processed. This
9952 routine permits incomplete codes, so another loop after this one fills
9953 in the rest of the decoding tables with invalid code markers.
9954 */
9955
9956 /* set up for code type */
9957 // poor man optimization - use if-else instead of switch,
9958 // to avoid deopts in old v8
9959 if (type === CODES) {
9960 base = extra = work; /* dummy value--not used */
9961 end = 19;
9962
9963 } else if (type === LENS) {
9964 base = lbase;
9965 base_index -= 257;
9966 extra = lext;
9967 extra_index -= 257;
9968 end = 256;
9969
9970 } else { /* DISTS */
9971 base = dbase;
9972 extra = dext;
9973 end = -1;
9974 }
9975
9976 /* initialize opts for loop */
9977 huff = 0; /* starting code */
9978 sym = 0; /* starting code symbol */
9979 len = min; /* starting code length */
9980 next = table_index; /* current table to fill in */
9981 curr = root; /* current table index bits */
9982 drop = 0; /* current bits to drop from code for index */
9983 low = -1; /* trigger new sub-table when len > root */
9984 used = 1 << root; /* use root table entries */
9985 mask = used - 1; /* mask for comparing low */
9986
9987 /* check available table space */
9988 if ((type === LENS && used > ENOUGH_LENS) ||
9989 (type === DISTS && used > ENOUGH_DISTS)) {
9990 return 1;
9991 }
9992
9993 /* process all codes and make table entries */
9994 for (;;) {
9995 /* create table entry */
9996 here_bits = len - drop;
9997 if (work[sym] < end) {
9998 here_op = 0;
9999 here_val = work[sym];
10000 }
10001 else if (work[sym] > end) {
10002 here_op = extra[extra_index + work[sym]];
10003 here_val = base[base_index + work[sym]];
10004 }
10005 else {
10006 here_op = 32 + 64; /* end of block */
10007 here_val = 0;
10008 }
10009
10010 /* replicate for those indices with low len bits equal to huff */
10011 incr = 1 << (len - drop);
10012 fill = 1 << curr;
10013 min = fill; /* save offset to next table */
10014 do {
10015 fill -= incr;
10016 table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
10017 } while (fill !== 0);
10018
10019 /* backwards increment the len-bit code huff */
10020 incr = 1 << (len - 1);
10021 while (huff & incr) {
10022 incr >>= 1;
10023 }
10024 if (incr !== 0) {
10025 huff &= incr - 1;
10026 huff += incr;
10027 } else {
10028 huff = 0;
10029 }
10030
10031 /* go to next symbol, update count, len */
10032 sym++;
10033 if (--count[len] === 0) {
10034 if (len === max) { break; }
10035 len = lens[lens_index + work[sym]];
10036 }
10037
10038 /* create new sub-table if needed */
10039 if (len > root && (huff & mask) !== low) {
10040 /* if first time, transition to sub-tables */
10041 if (drop === 0) {
10042 drop = root;
10043 }
10044
10045 /* increment past last table */
10046 next += min; /* here min is 1 << curr */
10047
10048 /* determine length of next table */
10049 curr = len - drop;
10050 left = 1 << curr;
10051 while (curr + drop < max) {
10052 left -= count[curr + drop];
10053 if (left <= 0) { break; }
10054 curr++;
10055 left <<= 1;
10056 }
10057
10058 /* check for enough space */
10059 used += 1 << curr;
10060 if ((type === LENS && used > ENOUGH_LENS) ||
10061 (type === DISTS && used > ENOUGH_DISTS)) {
10062 return 1;
10063 }
10064
10065 /* point entry in root table to sub-table */
10066 low = huff & mask;
10067 /*table.op[low] = curr;
10068 table.bits[low] = root;
10069 table.val[low] = next - opts.table_index;*/
10070 table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
10071 }
10072 }
10073
10074 /* fill in remaining table entry if code is incomplete (guaranteed to have
10075 at most one remaining entry, since if the code is incomplete, the
10076 maximum code length that was allowed to get this far is one bit) */
10077 if (huff !== 0) {
10078 //table.op[next + huff] = 64; /* invalid code marker */
10079 //table.bits[next + huff] = len - drop;
10080 //table.val[next + huff] = 0;
10081 table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
10082 }
10083
10084 /* set return parameters */
10085 //opts.table_index += used;
10086 opts.bits = root;
10087 return 0;
10088 };
10089
10090 },{"../utils/common":41}],51:[function(require,module,exports){
10091 'use strict';
10092
10093 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
10094 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
10095 //
10096 // This software is provided 'as-is', without any express or implied
10097 // warranty. In no event will the authors be held liable for any damages
10098 // arising from the use of this software.
10099 //
10100 // Permission is granted to anyone to use this software for any purpose,
10101 // including commercial applications, and to alter it and redistribute it
10102 // freely, subject to the following restrictions:
10103 //
10104 // 1. The origin of this software must not be misrepresented; you must not
10105 // claim that you wrote the original software. If you use this software
10106 // in a product, an acknowledgment in the product documentation would be
10107 // appreciated but is not required.
10108 // 2. Altered source versions must be plainly marked as such, and must not be
10109 // misrepresented as being the original software.
10110 // 3. This notice may not be removed or altered from any source distribution.
10111
10112 module.exports = {
10113 2: 'need dictionary', /* Z_NEED_DICT 2 */
10114 1: 'stream end', /* Z_STREAM_END 1 */
10115 0: '', /* Z_OK 0 */
10116 '-1': 'file error', /* Z_ERRNO (-1) */
10117 '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
10118 '-3': 'data error', /* Z_DATA_ERROR (-3) */
10119 '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
10120 '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
10121 '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
10122 };
10123
10124 },{}],52:[function(require,module,exports){
10125 'use strict';
10126
10127 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
10128 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
10129 //
10130 // This software is provided 'as-is', without any express or implied
10131 // warranty. In no event will the authors be held liable for any damages
10132 // arising from the use of this software.
10133 //
10134 // Permission is granted to anyone to use this software for any purpose,
10135 // including commercial applications, and to alter it and redistribute it
10136 // freely, subject to the following restrictions:
10137 //
10138 // 1. The origin of this software must not be misrepresented; you must not
10139 // claim that you wrote the original software. If you use this software
10140 // in a product, an acknowledgment in the product documentation would be
10141 // appreciated but is not required.
10142 // 2. Altered source versions must be plainly marked as such, and must not be
10143 // misrepresented as being the original software.
10144 // 3. This notice may not be removed or altered from any source distribution.
10145
10146 var utils = require('../utils/common');
10147
10148 /* Public constants ==========================================================*/
10149 /* ===========================================================================*/
10150
10151
10152 //var Z_FILTERED = 1;
10153 //var Z_HUFFMAN_ONLY = 2;
10154 //var Z_RLE = 3;
10155 var Z_FIXED = 4;
10156 //var Z_DEFAULT_STRATEGY = 0;
10157
10158 /* Possible values of the data_type field (though see inflate()) */
10159 var Z_BINARY = 0;
10160 var Z_TEXT = 1;
10161 //var Z_ASCII = 1; // = Z_TEXT
10162 var Z_UNKNOWN = 2;
10163
10164 /*============================================================================*/
10165
10166
10167 function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
10168
10169 // From zutil.h
10170
10171 var STORED_BLOCK = 0;
10172 var STATIC_TREES = 1;
10173 var DYN_TREES = 2;
10174 /* The three kinds of block type */
10175
10176 var MIN_MATCH = 3;
10177 var MAX_MATCH = 258;
10178 /* The minimum and maximum match lengths */
10179
10180 // From deflate.h
10181 /* ===========================================================================
10182 * Internal compression state.
10183 */
10184
10185 var LENGTH_CODES = 29;
10186 /* number of length codes, not counting the special END_BLOCK code */
10187
10188 var LITERALS = 256;
10189 /* number of literal bytes 0..255 */
10190
10191 var L_CODES = LITERALS + 1 + LENGTH_CODES;
10192 /* number of Literal or Length codes, including the END_BLOCK code */
10193
10194 var D_CODES = 30;
10195 /* number of distance codes */
10196
10197 var BL_CODES = 19;
10198 /* number of codes used to transfer the bit lengths */
10199
10200 var HEAP_SIZE = 2 * L_CODES + 1;
10201 /* maximum heap size */
10202
10203 var MAX_BITS = 15;
10204 /* All codes must not exceed MAX_BITS bits */
10205
10206 var Buf_size = 16;
10207 /* size of bit buffer in bi_buf */
10208
10209
10210 /* ===========================================================================
10211 * Constants
10212 */
10213
10214 var MAX_BL_BITS = 7;
10215 /* Bit length codes must not exceed MAX_BL_BITS bits */
10216
10217 var END_BLOCK = 256;
10218 /* end of block literal code */
10219
10220 var REP_3_6 = 16;
10221 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
10222
10223 var REPZ_3_10 = 17;
10224 /* repeat a zero length 3-10 times (3 bits of repeat count) */
10225
10226 var REPZ_11_138 = 18;
10227 /* repeat a zero length 11-138 times (7 bits of repeat count) */
10228
10229 /* eslint-disable comma-spacing,array-bracket-spacing */
10230 var extra_lbits = /* extra bits for each length code */
10231 [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];
10232
10233 var extra_dbits = /* extra bits for each distance code */
10234 [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];
10235
10236 var extra_blbits = /* extra bits for each bit length code */
10237 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
10238
10239 var bl_order =
10240 [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
10241 /* eslint-enable comma-spacing,array-bracket-spacing */
10242
10243 /* The lengths of the bit length codes are sent in order of decreasing
10244 * probability, to avoid transmitting the lengths for unused bit length codes.
10245 */
10246
10247 /* ===========================================================================
10248 * Local data. These are initialized only once.
10249 */
10250
10251 // We pre-fill arrays with 0 to avoid uninitialized gaps
10252
10253 var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
10254
10255 // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
10256 var static_ltree = new Array((L_CODES + 2) * 2);
10257 zero(static_ltree);
10258 /* The static literal tree. Since the bit lengths are imposed, there is no
10259 * need for the L_CODES extra codes used during heap construction. However
10260 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
10261 * below).
10262 */
10263
10264 var static_dtree = new Array(D_CODES * 2);
10265 zero(static_dtree);
10266 /* The static distance tree. (Actually a trivial tree since all codes use
10267 * 5 bits.)
10268 */
10269
10270 var _dist_code = new Array(DIST_CODE_LEN);
10271 zero(_dist_code);
10272 /* Distance codes. The first 256 values correspond to the distances
10273 * 3 .. 258, the last 256 values correspond to the top 8 bits of
10274 * the 15 bit distances.
10275 */
10276
10277 var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
10278 zero(_length_code);
10279 /* length code for each normalized match length (0 == MIN_MATCH) */
10280
10281 var base_length = new Array(LENGTH_CODES);
10282 zero(base_length);
10283 /* First normalized length for each code (0 = MIN_MATCH) */
10284
10285 var base_dist = new Array(D_CODES);
10286 zero(base_dist);
10287 /* First normalized distance for each code (0 = distance of 1) */
10288
10289
10290 function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
10291
10292 this.static_tree = static_tree; /* static tree or NULL */
10293 this.extra_bits = extra_bits; /* extra bits for each code or NULL */
10294 this.extra_base = extra_base; /* base index for extra_bits */
10295 this.elems = elems; /* max number of elements in the tree */
10296 this.max_length = max_length; /* max bit length for the codes */
10297
10298 // show if `static_tree` has data or dummy - needed for monomorphic objects
10299 this.has_stree = static_tree && static_tree.length;
10300 }
10301
10302
10303 var static_l_desc;
10304 var static_d_desc;
10305 var static_bl_desc;
10306
10307
10308 function TreeDesc(dyn_tree, stat_desc) {
10309 this.dyn_tree = dyn_tree; /* the dynamic tree */
10310 this.max_code = 0; /* largest code with non zero frequency */
10311 this.stat_desc = stat_desc; /* the corresponding static tree */
10312 }
10313
10314
10315
10316 function d_code(dist) {
10317 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
10318 }
10319
10320
10321 /* ===========================================================================
10322 * Output a short LSB first on the stream.
10323 * IN assertion: there is enough room in pendingBuf.
10324 */
10325 function put_short(s, w) {
10326 // put_byte(s, (uch)((w) & 0xff));
10327 // put_byte(s, (uch)((ush)(w) >> 8));
10328 s.pending_buf[s.pending++] = (w) & 0xff;
10329 s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
10330 }
10331
10332
10333 /* ===========================================================================
10334 * Send a value on a given number of bits.
10335 * IN assertion: length <= 16 and value fits in length bits.
10336 */
10337 function send_bits(s, value, length) {
10338 if (s.bi_valid > (Buf_size - length)) {
10339 s.bi_buf |= (value << s.bi_valid) & 0xffff;
10340 put_short(s, s.bi_buf);
10341 s.bi_buf = value >> (Buf_size - s.bi_valid);
10342 s.bi_valid += length - Buf_size;
10343 } else {
10344 s.bi_buf |= (value << s.bi_valid) & 0xffff;
10345 s.bi_valid += length;
10346 }
10347 }
10348
10349
10350 function send_code(s, c, tree) {
10351 send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
10352 }
10353
10354
10355 /* ===========================================================================
10356 * Reverse the first len bits of a code, using straightforward code (a faster
10357 * method would use a table)
10358 * IN assertion: 1 <= len <= 15
10359 */
10360 function bi_reverse(code, len) {
10361 var res = 0;
10362 do {
10363 res |= code & 1;
10364 code >>>= 1;
10365 res <<= 1;
10366 } while (--len > 0);
10367 return res >>> 1;
10368 }
10369
10370
10371 /* ===========================================================================
10372 * Flush the bit buffer, keeping at most 7 bits in it.
10373 */
10374 function bi_flush(s) {
10375 if (s.bi_valid === 16) {
10376 put_short(s, s.bi_buf);
10377 s.bi_buf = 0;
10378 s.bi_valid = 0;
10379
10380 } else if (s.bi_valid >= 8) {
10381 s.pending_buf[s.pending++] = s.bi_buf & 0xff;
10382 s.bi_buf >>= 8;
10383 s.bi_valid -= 8;
10384 }
10385 }
10386
10387
10388 /* ===========================================================================
10389 * Compute the optimal bit lengths for a tree and update the total bit length
10390 * for the current block.
10391 * IN assertion: the fields freq and dad are set, heap[heap_max] and
10392 * above are the tree nodes sorted by increasing frequency.
10393 * OUT assertions: the field len is set to the optimal bit length, the
10394 * array bl_count contains the frequencies for each bit length.
10395 * The length opt_len is updated; static_len is also updated if stree is
10396 * not null.
10397 */
10398 function gen_bitlen(s, desc)
10399 // deflate_state *s;
10400 // tree_desc *desc; /* the tree descriptor */
10401 {
10402 var tree = desc.dyn_tree;
10403 var max_code = desc.max_code;
10404 var stree = desc.stat_desc.static_tree;
10405 var has_stree = desc.stat_desc.has_stree;
10406 var extra = desc.stat_desc.extra_bits;
10407 var base = desc.stat_desc.extra_base;
10408 var max_length = desc.stat_desc.max_length;
10409 var h; /* heap index */
10410 var n, m; /* iterate over the tree elements */
10411 var bits; /* bit length */
10412 var xbits; /* extra bits */
10413 var f; /* frequency */
10414 var overflow = 0; /* number of elements with bit length too large */
10415
10416 for (bits = 0; bits <= MAX_BITS; bits++) {
10417 s.bl_count[bits] = 0;
10418 }
10419
10420 /* In a first pass, compute the optimal bit lengths (which may
10421 * overflow in the case of the bit length tree).
10422 */
10423 tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
10424
10425 for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
10426 n = s.heap[h];
10427 bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
10428 if (bits > max_length) {
10429 bits = max_length;
10430 overflow++;
10431 }
10432 tree[n * 2 + 1]/*.Len*/ = bits;
10433 /* We overwrite tree[n].Dad which is no longer needed */
10434
10435 if (n > max_code) { continue; } /* not a leaf node */
10436
10437 s.bl_count[bits]++;
10438 xbits = 0;
10439 if (n >= base) {
10440 xbits = extra[n - base];
10441 }
10442 f = tree[n * 2]/*.Freq*/;
10443 s.opt_len += f * (bits + xbits);
10444 if (has_stree) {
10445 s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
10446 }
10447 }
10448 if (overflow === 0) { return; }
10449
10450 // Trace((stderr,"\nbit length overflow\n"));
10451 /* This happens for example on obj2 and pic of the Calgary corpus */
10452
10453 /* Find the first bit length which could increase: */
10454 do {
10455 bits = max_length - 1;
10456 while (s.bl_count[bits] === 0) { bits--; }
10457 s.bl_count[bits]--; /* move one leaf down the tree */
10458 s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
10459 s.bl_count[max_length]--;
10460 /* The brother of the overflow item also moves one step up,
10461 * but this does not affect bl_count[max_length]
10462 */
10463 overflow -= 2;
10464 } while (overflow > 0);
10465
10466 /* Now recompute all bit lengths, scanning in increasing frequency.
10467 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
10468 * lengths instead of fixing only the wrong ones. This idea is taken
10469 * from 'ar' written by Haruhiko Okumura.)
10470 */
10471 for (bits = max_length; bits !== 0; bits--) {
10472 n = s.bl_count[bits];
10473 while (n !== 0) {
10474 m = s.heap[--h];
10475 if (m > max_code) { continue; }
10476 if (tree[m * 2 + 1]/*.Len*/ !== bits) {
10477 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
10478 s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
10479 tree[m * 2 + 1]/*.Len*/ = bits;
10480 }
10481 n--;
10482 }
10483 }
10484 }
10485
10486
10487 /* ===========================================================================
10488 * Generate the codes for a given tree and bit counts (which need not be
10489 * optimal).
10490 * IN assertion: the array bl_count contains the bit length statistics for
10491 * the given tree and the field len is set for all tree elements.
10492 * OUT assertion: the field code is set for all tree elements of non
10493 * zero code length.
10494 */
10495 function gen_codes(tree, max_code, bl_count)
10496 // ct_data *tree; /* the tree to decorate */
10497 // int max_code; /* largest code with non zero frequency */
10498 // ushf *bl_count; /* number of codes at each bit length */
10499 {
10500 var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
10501 var code = 0; /* running code value */
10502 var bits; /* bit index */
10503 var n; /* code index */
10504
10505 /* The distribution counts are first used to generate the code values
10506 * without bit reversal.
10507 */
10508 for (bits = 1; bits <= MAX_BITS; bits++) {
10509 next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
10510 }
10511 /* Check that the bit counts in bl_count are consistent. The last code
10512 * must be all ones.
10513 */
10514 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
10515 // "inconsistent bit counts");
10516 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
10517
10518 for (n = 0; n <= max_code; n++) {
10519 var len = tree[n * 2 + 1]/*.Len*/;
10520 if (len === 0) { continue; }
10521 /* Now reverse the bits */
10522 tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
10523
10524 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
10525 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
10526 }
10527 }
10528
10529
10530 /* ===========================================================================
10531 * Initialize the various 'constant' tables.
10532 */
10533 function tr_static_init() {
10534 var n; /* iterates over tree elements */
10535 var bits; /* bit counter */
10536 var length; /* length value */
10537 var code; /* code value */
10538 var dist; /* distance index */
10539 var bl_count = new Array(MAX_BITS + 1);
10540 /* number of codes at each bit length for an optimal tree */
10541
10542 // do check in _tr_init()
10543 //if (static_init_done) return;
10544
10545 /* For some embedded targets, global variables are not initialized: */
10546 /*#ifdef NO_INIT_GLOBAL_POINTERS
10547 static_l_desc.static_tree = static_ltree;
10548 static_l_desc.extra_bits = extra_lbits;
10549 static_d_desc.static_tree = static_dtree;
10550 static_d_desc.extra_bits = extra_dbits;
10551 static_bl_desc.extra_bits = extra_blbits;
10552 #endif*/
10553
10554 /* Initialize the mapping length (0..255) -> length code (0..28) */
10555 length = 0;
10556 for (code = 0; code < LENGTH_CODES - 1; code++) {
10557 base_length[code] = length;
10558 for (n = 0; n < (1 << extra_lbits[code]); n++) {
10559 _length_code[length++] = code;
10560 }
10561 }
10562 //Assert (length == 256, "tr_static_init: length != 256");
10563 /* Note that the length 255 (match length 258) can be represented
10564 * in two different ways: code 284 + 5 bits or code 285, so we
10565 * overwrite length_code[255] to use the best encoding:
10566 */
10567 _length_code[length - 1] = code;
10568
10569 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
10570 dist = 0;
10571 for (code = 0; code < 16; code++) {
10572 base_dist[code] = dist;
10573 for (n = 0; n < (1 << extra_dbits[code]); n++) {
10574 _dist_code[dist++] = code;
10575 }
10576 }
10577 //Assert (dist == 256, "tr_static_init: dist != 256");
10578 dist >>= 7; /* from now on, all distances are divided by 128 */
10579 for (; code < D_CODES; code++) {
10580 base_dist[code] = dist << 7;
10581 for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
10582 _dist_code[256 + dist++] = code;
10583 }
10584 }
10585 //Assert (dist == 256, "tr_static_init: 256+dist != 512");
10586
10587 /* Construct the codes of the static literal tree */
10588 for (bits = 0; bits <= MAX_BITS; bits++) {
10589 bl_count[bits] = 0;
10590 }
10591
10592 n = 0;
10593 while (n <= 143) {
10594 static_ltree[n * 2 + 1]/*.Len*/ = 8;
10595 n++;
10596 bl_count[8]++;
10597 }
10598 while (n <= 255) {
10599 static_ltree[n * 2 + 1]/*.Len*/ = 9;
10600 n++;
10601 bl_count[9]++;
10602 }
10603 while (n <= 279) {
10604 static_ltree[n * 2 + 1]/*.Len*/ = 7;
10605 n++;
10606 bl_count[7]++;
10607 }
10608 while (n <= 287) {
10609 static_ltree[n * 2 + 1]/*.Len*/ = 8;
10610 n++;
10611 bl_count[8]++;
10612 }
10613 /* Codes 286 and 287 do not exist, but we must include them in the
10614 * tree construction to get a canonical Huffman tree (longest code
10615 * all ones)
10616 */
10617 gen_codes(static_ltree, L_CODES + 1, bl_count);
10618
10619 /* The static distance tree is trivial: */
10620 for (n = 0; n < D_CODES; n++) {
10621 static_dtree[n * 2 + 1]/*.Len*/ = 5;
10622 static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
10623 }
10624
10625 // Now data ready and we can init static trees
10626 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
10627 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
10628 static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
10629
10630 //static_init_done = true;
10631 }
10632
10633
10634 /* ===========================================================================
10635 * Initialize a new block.
10636 */
10637 function init_block(s) {
10638 var n; /* iterates over tree elements */
10639
10640 /* Initialize the trees. */
10641 for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
10642 for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
10643 for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
10644
10645 s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
10646 s.opt_len = s.static_len = 0;
10647 s.last_lit = s.matches = 0;
10648 }
10649
10650
10651 /* ===========================================================================
10652 * Flush the bit buffer and align the output on a byte boundary
10653 */
10654 function bi_windup(s)
10655 {
10656 if (s.bi_valid > 8) {
10657 put_short(s, s.bi_buf);
10658 } else if (s.bi_valid > 0) {
10659 //put_byte(s, (Byte)s->bi_buf);
10660 s.pending_buf[s.pending++] = s.bi_buf;
10661 }
10662 s.bi_buf = 0;
10663 s.bi_valid = 0;
10664 }
10665
10666 /* ===========================================================================
10667 * Copy a stored block, storing first the length and its
10668 * one's complement if requested.
10669 */
10670 function copy_block(s, buf, len, header)
10671 //DeflateState *s;
10672 //charf *buf; /* the input data */
10673 //unsigned len; /* its length */
10674 //int header; /* true if block header must be written */
10675 {
10676 bi_windup(s); /* align on byte boundary */
10677
10678 if (header) {
10679 put_short(s, len);
10680 put_short(s, ~len);
10681 }
10682 // while (len--) {
10683 // put_byte(s, *buf++);
10684 // }
10685 utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
10686 s.pending += len;
10687 }
10688
10689 /* ===========================================================================
10690 * Compares to subtrees, using the tree depth as tie breaker when
10691 * the subtrees have equal frequency. This minimizes the worst case length.
10692 */
10693 function smaller(tree, n, m, depth) {
10694 var _n2 = n * 2;
10695 var _m2 = m * 2;
10696 return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
10697 (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
10698 }
10699
10700 /* ===========================================================================
10701 * Restore the heap property by moving down the tree starting at node k,
10702 * exchanging a node with the smallest of its two sons if necessary, stopping
10703 * when the heap property is re-established (each father smaller than its
10704 * two sons).
10705 */
10706 function pqdownheap(s, tree, k)
10707 // deflate_state *s;
10708 // ct_data *tree; /* the tree to restore */
10709 // int k; /* node to move down */
10710 {
10711 var v = s.heap[k];
10712 var j = k << 1; /* left son of k */
10713 while (j <= s.heap_len) {
10714 /* Set j to the smallest of the two sons: */
10715 if (j < s.heap_len &&
10716 smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
10717 j++;
10718 }
10719 /* Exit if v is smaller than both sons */
10720 if (smaller(tree, v, s.heap[j], s.depth)) { break; }
10721
10722 /* Exchange v with the smallest son */
10723 s.heap[k] = s.heap[j];
10724 k = j;
10725
10726 /* And continue down the tree, setting j to the left son of k */
10727 j <<= 1;
10728 }
10729 s.heap[k] = v;
10730 }
10731
10732
10733 // inlined manually
10734 // var SMALLEST = 1;
10735
10736 /* ===========================================================================
10737 * Send the block data compressed using the given Huffman trees
10738 */
10739 function compress_block(s, ltree, dtree)
10740 // deflate_state *s;
10741 // const ct_data *ltree; /* literal tree */
10742 // const ct_data *dtree; /* distance tree */
10743 {
10744 var dist; /* distance of matched string */
10745 var lc; /* match length or unmatched char (if dist == 0) */
10746 var lx = 0; /* running index in l_buf */
10747 var code; /* the code to send */
10748 var extra; /* number of extra bits to send */
10749
10750 if (s.last_lit !== 0) {
10751 do {
10752 dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
10753 lc = s.pending_buf[s.l_buf + lx];
10754 lx++;
10755
10756 if (dist === 0) {
10757 send_code(s, lc, ltree); /* send a literal byte */
10758 //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
10759 } else {
10760 /* Here, lc is the match length - MIN_MATCH */
10761 code = _length_code[lc];
10762 send_code(s, code + LITERALS + 1, ltree); /* send the length code */
10763 extra = extra_lbits[code];
10764 if (extra !== 0) {
10765 lc -= base_length[code];
10766 send_bits(s, lc, extra); /* send the extra length bits */
10767 }
10768 dist--; /* dist is now the match distance - 1 */
10769 code = d_code(dist);
10770 //Assert (code < D_CODES, "bad d_code");
10771
10772 send_code(s, code, dtree); /* send the distance code */
10773 extra = extra_dbits[code];
10774 if (extra !== 0) {
10775 dist -= base_dist[code];
10776 send_bits(s, dist, extra); /* send the extra distance bits */
10777 }
10778 } /* literal or match pair ? */
10779
10780 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
10781 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
10782 // "pendingBuf overflow");
10783
10784 } while (lx < s.last_lit);
10785 }
10786
10787 send_code(s, END_BLOCK, ltree);
10788 }
10789
10790
10791 /* ===========================================================================
10792 * Construct one Huffman tree and assigns the code bit strings and lengths.
10793 * Update the total bit length for the current block.
10794 * IN assertion: the field freq is set for all tree elements.
10795 * OUT assertions: the fields len and code are set to the optimal bit length
10796 * and corresponding code. The length opt_len is updated; static_len is
10797 * also updated if stree is not null. The field max_code is set.
10798 */
10799 function build_tree(s, desc)
10800 // deflate_state *s;
10801 // tree_desc *desc; /* the tree descriptor */
10802 {
10803 var tree = desc.dyn_tree;
10804 var stree = desc.stat_desc.static_tree;
10805 var has_stree = desc.stat_desc.has_stree;
10806 var elems = desc.stat_desc.elems;
10807 var n, m; /* iterate over heap elements */
10808 var max_code = -1; /* largest code with non zero frequency */
10809 var node; /* new node being created */
10810
10811 /* Construct the initial heap, with least frequent element in
10812 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
10813 * heap[0] is not used.
10814 */
10815 s.heap_len = 0;
10816 s.heap_max = HEAP_SIZE;
10817
10818 for (n = 0; n < elems; n++) {
10819 if (tree[n * 2]/*.Freq*/ !== 0) {
10820 s.heap[++s.heap_len] = max_code = n;
10821 s.depth[n] = 0;
10822
10823 } else {
10824 tree[n * 2 + 1]/*.Len*/ = 0;
10825 }
10826 }
10827
10828 /* The pkzip format requires that at least one distance code exists,
10829 * and that at least one bit should be sent even if there is only one
10830 * possible code. So to avoid special checks later on we force at least
10831 * two codes of non zero frequency.
10832 */
10833 while (s.heap_len < 2) {
10834 node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
10835 tree[node * 2]/*.Freq*/ = 1;
10836 s.depth[node] = 0;
10837 s.opt_len--;
10838
10839 if (has_stree) {
10840 s.static_len -= stree[node * 2 + 1]/*.Len*/;
10841 }
10842 /* node is 0 or 1 so it does not have extra bits */
10843 }
10844 desc.max_code = max_code;
10845
10846 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
10847 * establish sub-heaps of increasing lengths:
10848 */
10849 for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
10850
10851 /* Construct the Huffman tree by repeatedly combining the least two
10852 * frequent nodes.
10853 */
10854 node = elems; /* next internal node of the tree */
10855 do {
10856 //pqremove(s, tree, n); /* n = node of least frequency */
10857 /*** pqremove ***/
10858 n = s.heap[1/*SMALLEST*/];
10859 s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
10860 pqdownheap(s, tree, 1/*SMALLEST*/);
10861 /***/
10862
10863 m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
10864
10865 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
10866 s.heap[--s.heap_max] = m;
10867
10868 /* Create a new node father of n and m */
10869 tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
10870 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
10871 tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
10872
10873 /* and insert the new node in the heap */
10874 s.heap[1/*SMALLEST*/] = node++;
10875 pqdownheap(s, tree, 1/*SMALLEST*/);
10876
10877 } while (s.heap_len >= 2);
10878
10879 s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
10880
10881 /* At this point, the fields freq and dad are set. We can now
10882 * generate the bit lengths.
10883 */
10884 gen_bitlen(s, desc);
10885
10886 /* The field len is now set, we can generate the bit codes */
10887 gen_codes(tree, max_code, s.bl_count);
10888 }
10889
10890
10891 /* ===========================================================================
10892 * Scan a literal or distance tree to determine the frequencies of the codes
10893 * in the bit length tree.
10894 */
10895 function scan_tree(s, tree, max_code)
10896 // deflate_state *s;
10897 // ct_data *tree; /* the tree to be scanned */
10898 // int max_code; /* and its largest code of non zero frequency */
10899 {
10900 var n; /* iterates over all tree elements */
10901 var prevlen = -1; /* last emitted length */
10902 var curlen; /* length of current code */
10903
10904 var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
10905
10906 var count = 0; /* repeat count of the current code */
10907 var max_count = 7; /* max repeat count */
10908 var min_count = 4; /* min repeat count */
10909
10910 if (nextlen === 0) {
10911 max_count = 138;
10912 min_count = 3;
10913 }
10914 tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
10915
10916 for (n = 0; n <= max_code; n++) {
10917 curlen = nextlen;
10918 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
10919
10920 if (++count < max_count && curlen === nextlen) {
10921 continue;
10922
10923 } else if (count < min_count) {
10924 s.bl_tree[curlen * 2]/*.Freq*/ += count;
10925
10926 } else if (curlen !== 0) {
10927
10928 if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
10929 s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
10930
10931 } else if (count <= 10) {
10932 s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
10933
10934 } else {
10935 s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
10936 }
10937
10938 count = 0;
10939 prevlen = curlen;
10940
10941 if (nextlen === 0) {
10942 max_count = 138;
10943 min_count = 3;
10944
10945 } else if (curlen === nextlen) {
10946 max_count = 6;
10947 min_count = 3;
10948
10949 } else {
10950 max_count = 7;
10951 min_count = 4;
10952 }
10953 }
10954 }
10955
10956
10957 /* ===========================================================================
10958 * Send a literal or distance tree in compressed form, using the codes in
10959 * bl_tree.
10960 */
10961 function send_tree(s, tree, max_code)
10962 // deflate_state *s;
10963 // ct_data *tree; /* the tree to be scanned */
10964 // int max_code; /* and its largest code of non zero frequency */
10965 {
10966 var n; /* iterates over all tree elements */
10967 var prevlen = -1; /* last emitted length */
10968 var curlen; /* length of current code */
10969
10970 var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
10971
10972 var count = 0; /* repeat count of the current code */
10973 var max_count = 7; /* max repeat count */
10974 var min_count = 4; /* min repeat count */
10975
10976 /* tree[max_code+1].Len = -1; */ /* guard already set */
10977 if (nextlen === 0) {
10978 max_count = 138;
10979 min_count = 3;
10980 }
10981
10982 for (n = 0; n <= max_code; n++) {
10983 curlen = nextlen;
10984 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
10985
10986 if (++count < max_count && curlen === nextlen) {
10987 continue;
10988
10989 } else if (count < min_count) {
10990 do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
10991
10992 } else if (curlen !== 0) {
10993 if (curlen !== prevlen) {
10994 send_code(s, curlen, s.bl_tree);
10995 count--;
10996 }
10997 //Assert(count >= 3 && count <= 6, " 3_6?");
10998 send_code(s, REP_3_6, s.bl_tree);
10999 send_bits(s, count - 3, 2);
11000
11001 } else if (count <= 10) {
11002 send_code(s, REPZ_3_10, s.bl_tree);
11003 send_bits(s, count - 3, 3);
11004
11005 } else {
11006 send_code(s, REPZ_11_138, s.bl_tree);
11007 send_bits(s, count - 11, 7);
11008 }
11009
11010 count = 0;
11011 prevlen = curlen;
11012 if (nextlen === 0) {
11013 max_count = 138;
11014 min_count = 3;
11015
11016 } else if (curlen === nextlen) {
11017 max_count = 6;
11018 min_count = 3;
11019
11020 } else {
11021 max_count = 7;
11022 min_count = 4;
11023 }
11024 }
11025 }
11026
11027
11028 /* ===========================================================================
11029 * Construct the Huffman tree for the bit lengths and return the index in
11030 * bl_order of the last bit length code to send.
11031 */
11032 function build_bl_tree(s) {
11033 var max_blindex; /* index of last bit length code of non zero freq */
11034
11035 /* Determine the bit length frequencies for literal and distance trees */
11036 scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
11037 scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
11038
11039 /* Build the bit length tree: */
11040 build_tree(s, s.bl_desc);
11041 /* opt_len now includes the length of the tree representations, except
11042 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
11043 */
11044
11045 /* Determine the number of bit length codes to send. The pkzip format
11046 * requires that at least 4 bit length codes be sent. (appnote.txt says
11047 * 3 but the actual value used is 4.)
11048 */
11049 for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
11050 if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
11051 break;
11052 }
11053 }
11054 /* Update opt_len to include the bit length tree and counts */
11055 s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
11056 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
11057 // s->opt_len, s->static_len));
11058
11059 return max_blindex;
11060 }
11061
11062
11063 /* ===========================================================================
11064 * Send the header for a block using dynamic Huffman trees: the counts, the
11065 * lengths of the bit length codes, the literal tree and the distance tree.
11066 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
11067 */
11068 function send_all_trees(s, lcodes, dcodes, blcodes)
11069 // deflate_state *s;
11070 // int lcodes, dcodes, blcodes; /* number of codes for each tree */
11071 {
11072 var rank; /* index in bl_order */
11073
11074 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
11075 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
11076 // "too many codes");
11077 //Tracev((stderr, "\nbl counts: "));
11078 send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
11079 send_bits(s, dcodes - 1, 5);
11080 send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
11081 for (rank = 0; rank < blcodes; rank++) {
11082 //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
11083 send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
11084 }
11085 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
11086
11087 send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
11088 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
11089
11090 send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
11091 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
11092 }
11093
11094
11095 /* ===========================================================================
11096 * Check if the data type is TEXT or BINARY, using the following algorithm:
11097 * - TEXT if the two conditions below are satisfied:
11098 * a) There are no non-portable control characters belonging to the
11099 * "black list" (0..6, 14..25, 28..31).
11100 * b) There is at least one printable character belonging to the
11101 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
11102 * - BINARY otherwise.
11103 * - The following partially-portable control characters form a
11104 * "gray list" that is ignored in this detection algorithm:
11105 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
11106 * IN assertion: the fields Freq of dyn_ltree are set.
11107 */
11108 function detect_data_type(s) {
11109 /* black_mask is the bit mask of black-listed bytes
11110 * set bits 0..6, 14..25, and 28..31
11111 * 0xf3ffc07f = binary 11110011111111111100000001111111
11112 */
11113 var black_mask = 0xf3ffc07f;
11114 var n;
11115
11116 /* Check for non-textual ("black-listed") bytes. */
11117 for (n = 0; n <= 31; n++, black_mask >>>= 1) {
11118 if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
11119 return Z_BINARY;
11120 }
11121 }
11122
11123 /* Check for textual ("white-listed") bytes. */
11124 if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
11125 s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
11126 return Z_TEXT;
11127 }
11128 for (n = 32; n < LITERALS; n++) {
11129 if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
11130 return Z_TEXT;
11131 }
11132 }
11133
11134 /* There are no "black-listed" or "white-listed" bytes:
11135 * this stream either is empty or has tolerated ("gray-listed") bytes only.
11136 */
11137 return Z_BINARY;
11138 }
11139
11140
11141 var static_init_done = false;
11142
11143 /* ===========================================================================
11144 * Initialize the tree data structures for a new zlib stream.
11145 */
11146 function _tr_init(s)
11147 {
11148
11149 if (!static_init_done) {
11150 tr_static_init();
11151 static_init_done = true;
11152 }
11153
11154 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
11155 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
11156 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
11157
11158 s.bi_buf = 0;
11159 s.bi_valid = 0;
11160
11161 /* Initialize the first block of the first file: */
11162 init_block(s);
11163 }
11164
11165
11166 /* ===========================================================================
11167 * Send a stored block
11168 */
11169 function _tr_stored_block(s, buf, stored_len, last)
11170 //DeflateState *s;
11171 //charf *buf; /* input block */
11172 //ulg stored_len; /* length of input block */
11173 //int last; /* one if this is the last block for a file */
11174 {
11175 send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
11176 copy_block(s, buf, stored_len, true); /* with header */
11177 }
11178
11179
11180 /* ===========================================================================
11181 * Send one empty static block to give enough lookahead for inflate.
11182 * This takes 10 bits, of which 7 may remain in the bit buffer.
11183 */
11184 function _tr_align(s) {
11185 send_bits(s, STATIC_TREES << 1, 3);
11186 send_code(s, END_BLOCK, static_ltree);
11187 bi_flush(s);
11188 }
11189
11190
11191 /* ===========================================================================
11192 * Determine the best encoding for the current block: dynamic trees, static
11193 * trees or store, and output the encoded block to the zip file.
11194 */
11195 function _tr_flush_block(s, buf, stored_len, last)
11196 //DeflateState *s;
11197 //charf *buf; /* input block, or NULL if too old */
11198 //ulg stored_len; /* length of input block */
11199 //int last; /* one if this is the last block for a file */
11200 {
11201 var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
11202 var max_blindex = 0; /* index of last bit length code of non zero freq */
11203
11204 /* Build the Huffman trees unless a stored block is forced */
11205 if (s.level > 0) {
11206
11207 /* Check if the file is binary or text */
11208 if (s.strm.data_type === Z_UNKNOWN) {
11209 s.strm.data_type = detect_data_type(s);
11210 }
11211
11212 /* Construct the literal and distance trees */
11213 build_tree(s, s.l_desc);
11214 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
11215 // s->static_len));
11216
11217 build_tree(s, s.d_desc);
11218 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
11219 // s->static_len));
11220 /* At this point, opt_len and static_len are the total bit lengths of
11221 * the compressed block data, excluding the tree representations.
11222 */
11223
11224 /* Build the bit length tree for the above two trees, and get the index
11225 * in bl_order of the last bit length code to send.
11226 */
11227 max_blindex = build_bl_tree(s);
11228
11229 /* Determine the best encoding. Compute the block lengths in bytes. */
11230 opt_lenb = (s.opt_len + 3 + 7) >>> 3;
11231 static_lenb = (s.static_len + 3 + 7) >>> 3;
11232
11233 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
11234 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
11235 // s->last_lit));
11236
11237 if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
11238
11239 } else {
11240 // Assert(buf != (char*)0, "lost buf");
11241 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
11242 }
11243
11244 if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
11245 /* 4: two words for the lengths */
11246
11247 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
11248 * Otherwise we can't have processed more than WSIZE input bytes since
11249 * the last block flush, because compression would have been
11250 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
11251 * transform a block into a stored block.
11252 */
11253 _tr_stored_block(s, buf, stored_len, last);
11254
11255 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
11256
11257 send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
11258 compress_block(s, static_ltree, static_dtree);
11259
11260 } else {
11261 send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
11262 send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
11263 compress_block(s, s.dyn_ltree, s.dyn_dtree);
11264 }
11265 // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
11266 /* The above check is made mod 2^32, for files larger than 512 MB
11267 * and uLong implemented on 32 bits.
11268 */
11269 init_block(s);
11270
11271 if (last) {
11272 bi_windup(s);
11273 }
11274 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
11275 // s->compressed_len-7*last));
11276 }
11277
11278 /* ===========================================================================
11279 * Save the match info and tally the frequency counts. Return true if
11280 * the current block must be flushed.
11281 */
11282 function _tr_tally(s, dist, lc)
11283 // deflate_state *s;
11284 // unsigned dist; /* distance of matched string */
11285 // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
11286 {
11287 //var out_length, in_length, dcode;
11288
11289 s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
11290 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
11291
11292 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
11293 s.last_lit++;
11294
11295 if (dist === 0) {
11296 /* lc is the unmatched char */
11297 s.dyn_ltree[lc * 2]/*.Freq*/++;
11298 } else {
11299 s.matches++;
11300 /* Here, lc is the match length - MIN_MATCH */
11301 dist--; /* dist = match distance - 1 */
11302 //Assert((ush)dist < (ush)MAX_DIST(s) &&
11303 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
11304 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
11305
11306 s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
11307 s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
11308 }
11309
11310 // (!) This block is disabled in zlib defailts,
11311 // don't enable it for binary compatibility
11312
11313 //#ifdef TRUNCATE_BLOCK
11314 // /* Try to guess if it is profitable to stop the current block here */
11315 // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
11316 // /* Compute an upper bound for the compressed length */
11317 // out_length = s.last_lit*8;
11318 // in_length = s.strstart - s.block_start;
11319 //
11320 // for (dcode = 0; dcode < D_CODES; dcode++) {
11321 // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
11322 // }
11323 // out_length >>>= 3;
11324 // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
11325 // // s->last_lit, in_length, out_length,
11326 // // 100L - out_length*100L/in_length));
11327 // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
11328 // return true;
11329 // }
11330 // }
11331 //#endif
11332
11333 return (s.last_lit === s.lit_bufsize - 1);
11334 /* We avoid equality with lit_bufsize because of wraparound at 64K
11335 * on 16 bit machines and because stored blocks are restricted to
11336 * 64K-1 bytes.
11337 */
11338 }
11339
11340 exports._tr_init = _tr_init;
11341 exports._tr_stored_block = _tr_stored_block;
11342 exports._tr_flush_block = _tr_flush_block;
11343 exports._tr_tally = _tr_tally;
11344 exports._tr_align = _tr_align;
11345
11346 },{"../utils/common":41}],53:[function(require,module,exports){
11347 'use strict';
11348
11349 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
11350 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
11351 //
11352 // This software is provided 'as-is', without any express or implied
11353 // warranty. In no event will the authors be held liable for any damages
11354 // arising from the use of this software.
11355 //
11356 // Permission is granted to anyone to use this software for any purpose,
11357 // including commercial applications, and to alter it and redistribute it
11358 // freely, subject to the following restrictions:
11359 //
11360 // 1. The origin of this software must not be misrepresented; you must not
11361 // claim that you wrote the original software. If you use this software
11362 // in a product, an acknowledgment in the product documentation would be
11363 // appreciated but is not required.
11364 // 2. Altered source versions must be plainly marked as such, and must not be
11365 // misrepresented as being the original software.
11366 // 3. This notice may not be removed or altered from any source distribution.
11367
11368 function ZStream() {
11369 /* next input byte */
11370 this.input = null; // JS specific, because we have no pointers
11371 this.next_in = 0;
11372 /* number of bytes available at input */
11373 this.avail_in = 0;
11374 /* total number of input bytes read so far */
11375 this.total_in = 0;
11376 /* next output byte should be put there */
11377 this.output = null; // JS specific, because we have no pointers
11378 this.next_out = 0;
11379 /* remaining free space at output */
11380 this.avail_out = 0;
11381 /* total number of bytes output so far */
11382 this.total_out = 0;
11383 /* last error message, NULL if no error */
11384 this.msg = ''/*Z_NULL*/;
11385 /* not visible by applications */
11386 this.state = null;
11387 /* best guess about the data type: binary or text */
11388 this.data_type = 2/*Z_UNKNOWN*/;
11389 /* adler32 value of the uncompressed data */
11390 this.adler = 0;
11391 }
11392
11393 module.exports = ZStream;
11394
11395 },{}],54:[function(require,module,exports){
11396 (function (global){
11397 (function (global, undefined) {
11398 "use strict";
11399
11400 if (global.setImmediate) {
11401 return;
11402 }
11403
11404 var nextHandle = 1; // Spec says greater than zero
11405 var tasksByHandle = {};
11406 var currentlyRunningATask = false;
11407 var doc = global.document;
11408 var registerImmediate;
11409
11410 function setImmediate(callback) {
11411 // Callback can either be a function or a string
11412 if (typeof callback !== "function") {
11413 callback = new Function("" + callback);
11414 }
11415 // Copy function arguments
11416 var args = new Array(arguments.length - 1);
11417 for (var i = 0; i < args.length; i++) {
11418 args[i] = arguments[i + 1];
11419 }
11420 // Store and register the task
11421 var task = { callback: callback, args: args };
11422 tasksByHandle[nextHandle] = task;
11423 registerImmediate(nextHandle);
11424 return nextHandle++;
11425 }
11426
11427 function clearImmediate(handle) {
11428 delete tasksByHandle[handle];
11429 }
11430
11431 function run(task) {
11432 var callback = task.callback;
11433 var args = task.args;
11434 switch (args.length) {
11435 case 0:
11436 callback();
11437 break;
11438 case 1:
11439 callback(args[0]);
11440 break;
11441 case 2:
11442 callback(args[0], args[1]);
11443 break;
11444 case 3:
11445 callback(args[0], args[1], args[2]);
11446 break;
11447 default:
11448 callback.apply(undefined, args);
11449 break;
11450 }
11451 }
11452
11453 function runIfPresent(handle) {
11454 // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
11455 // So if we're currently running a task, we'll need to delay this invocation.
11456 if (currentlyRunningATask) {
11457 // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
11458 // "too much recursion" error.
11459 setTimeout(runIfPresent, 0, handle);
11460 } else {
11461 var task = tasksByHandle[handle];
11462 if (task) {
11463 currentlyRunningATask = true;
11464 try {
11465 run(task);
11466 } finally {
11467 clearImmediate(handle);
11468 currentlyRunningATask = false;
11469 }
11470 }
11471 }
11472 }
11473
11474 function installNextTickImplementation() {
11475 registerImmediate = function(handle) {
11476 process.nextTick(function () { runIfPresent(handle); });
11477 };
11478 }
11479
11480 function canUsePostMessage() {
11481 // The test against `importScripts` prevents this implementation from being installed inside a web worker,
11482 // where `global.postMessage` means something completely different and can't be used for this purpose.
11483 if (global.postMessage && !global.importScripts) {
11484 var postMessageIsAsynchronous = true;
11485 var oldOnMessage = global.onmessage;
11486 global.onmessage = function() {
11487 postMessageIsAsynchronous = false;
11488 };
11489 global.postMessage("", "*");
11490 global.onmessage = oldOnMessage;
11491 return postMessageIsAsynchronous;
11492 }
11493 }
11494
11495 function installPostMessageImplementation() {
11496 // Installs an event handler on `global` for the `message` event: see
11497 // * https://developer.mozilla.org/en/DOM/window.postMessage
11498 // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
11499
11500 var messagePrefix = "setImmediate$" + Math.random() + "$";
11501 var onGlobalMessage = function(event) {
11502 if (event.source === global &&
11503 typeof event.data === "string" &&
11504 event.data.indexOf(messagePrefix) === 0) {
11505 runIfPresent(+event.data.slice(messagePrefix.length));
11506 }
11507 };
11508
11509 if (global.addEventListener) {
11510 global.addEventListener("message", onGlobalMessage, false);
11511 } else {
11512 global.attachEvent("onmessage", onGlobalMessage);
11513 }
11514
11515 registerImmediate = function(handle) {
11516 global.postMessage(messagePrefix + handle, "*");
11517 };
11518 }
11519
11520 function installMessageChannelImplementation() {
11521 var channel = new MessageChannel();
11522 channel.port1.onmessage = function(event) {
11523 var handle = event.data;
11524 runIfPresent(handle);
11525 };
11526
11527 registerImmediate = function(handle) {
11528 channel.port2.postMessage(handle);
11529 };
11530 }
11531
11532 function installReadyStateChangeImplementation() {
11533 var html = doc.documentElement;
11534 registerImmediate = function(handle) {
11535 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
11536 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
11537 var script = doc.createElement("script");
11538 script.onreadystatechange = function () {
11539 runIfPresent(handle);
11540 script.onreadystatechange = null;
11541 html.removeChild(script);
11542 script = null;
11543 };
11544 html.appendChild(script);
11545 };
11546 }
11547
11548 function installSetTimeoutImplementation() {
11549 registerImmediate = function(handle) {
11550 setTimeout(runIfPresent, 0, handle);
11551 };
11552 }
11553
11554 // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
11555 var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
11556 attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
11557
11558 // Don't get fooled by e.g. browserify environments.
11559 if ({}.toString.call(global.process) === "[object process]") {
11560 // For Node.js before 0.9
11561 installNextTickImplementation();
11562
11563 } else if (canUsePostMessage()) {
11564 // For non-IE10 modern browsers
11565 installPostMessageImplementation();
11566
11567 } else if (global.MessageChannel) {
11568 // For web workers, where supported
11569 installMessageChannelImplementation();
11570
11571 } else if (doc && "onreadystatechange" in doc.createElement("script")) {
11572 // For IE 6–8
11573 installReadyStateChangeImplementation();
11574
11575 } else {
11576 // For older browsers
11577 installSetTimeoutImplementation();
11578 }
11579
11580 attachTo.setImmediate = setImmediate;
11581 attachTo.clearImmediate = clearImmediate;
11582 }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
11583
11584 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
11585 },{}]},{},[10])(10)
11586 });