UNPKG

288 kBJavaScriptView Raw
1/*
2
3JSZip - A Javascript class for generating and reading zip files
4<http://stuartk.com/jszip>
5
6(c) 2009-2014 Stuart Knightley <stuart [at] stuartk.com>
7Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
8
9JSZip uses the library pako released under the MIT license :
10https://github.com/nodeca/pako/blob/master/LICENSE
11
12Note: since JSZip 3 removed critical functionality, this version assigns to the
13`JSZipSync` variable. Another JSZip version can be loaded in parallel.
14*/
15(function(e){
16 if("object"==typeof exports&&"undefined"!=typeof module&&"undefined"==typeof DO_NOT_EXPORT_JSZIP)module.exports=e();
17 else if("function"==typeof define&&define.amd&&"undefined"==typeof DO_NOT_EXPORT_JSZIP){JSZipSync=e();define('j',[],e);}
18 else{
19 var f;
20 "undefined"!=typeof globalThis?f=globalThis:
21 "undefined"!=typeof window?f=window:
22 "undefined"!=typeof global?f=global:
23 "undefined"!=typeof $ && $.global?f=$.global:
24 "undefined"!=typeof self&&(f=self),f.JSZipSync=e()
25 }
26}(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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(_dereq_,module,exports){
27'use strict';
28// private property
29var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
30
31
32// public method for encoding
33exports.encode = function(input, utf8) {
34 var output = "";
35 var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
36 var i = 0;
37
38 while (i < input.length) {
39
40 chr1 = input.charCodeAt(i++);
41 chr2 = input.charCodeAt(i++);
42 chr3 = input.charCodeAt(i++);
43
44 enc1 = chr1 >> 2;
45 enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
46 enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
47 enc4 = chr3 & 63;
48
49 if (isNaN(chr2)) {
50 enc3 = enc4 = 64;
51 }
52 else if (isNaN(chr3)) {
53 enc4 = 64;
54 }
55
56 output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
57
58 }
59
60 return output;
61};
62
63// public method for decoding
64exports.decode = function(input, utf8) {
65 var output = "";
66 var chr1, chr2, chr3;
67 var enc1, enc2, enc3, enc4;
68 var i = 0;
69
70 input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
71
72 while (i < input.length) {
73
74 enc1 = _keyStr.indexOf(input.charAt(i++));
75 enc2 = _keyStr.indexOf(input.charAt(i++));
76 enc3 = _keyStr.indexOf(input.charAt(i++));
77 enc4 = _keyStr.indexOf(input.charAt(i++));
78
79 chr1 = (enc1 << 2) | (enc2 >> 4);
80 chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
81 chr3 = ((enc3 & 3) << 6) | enc4;
82
83 output = output + String.fromCharCode(chr1);
84
85 if (enc3 != 64) {
86 output = output + String.fromCharCode(chr2);
87 }
88 if (enc4 != 64) {
89 output = output + String.fromCharCode(chr3);
90 }
91
92 }
93
94 return output;
95
96};
97
98},{}],2:[function(_dereq_,module,exports){
99'use strict';
100function CompressedObject() {
101 this.compressedSize = 0;
102 this.uncompressedSize = 0;
103 this.crc32 = 0;
104 this.compressionMethod = null;
105 this.compressedContent = null;
106}
107
108CompressedObject.prototype = {
109 /**
110 * Return the decompressed content in an unspecified format.
111 * The format will depend on the decompressor.
112 * @return {Object} the decompressed content.
113 */
114 getContent: function() {
115 return null; // see implementation
116 },
117 /**
118 * Return the compressed content in an unspecified format.
119 * The format will depend on the compressed conten source.
120 * @return {Object} the compressed content.
121 */
122 getCompressedContent: function() {
123 return null; // see implementation
124 }
125};
126module.exports = CompressedObject;
127
128},{}],3:[function(_dereq_,module,exports){
129'use strict';
130exports.STORE = {
131 magic: "\x00\x00",
132 compress: function(content) {
133 return content; // no compression
134 },
135 uncompress: function(content) {
136 return content; // no compression
137 },
138 compressInputType: null,
139 uncompressInputType: null
140};
141exports.DEFLATE = _dereq_('./flate');
142
143},{"./flate":8}],4:[function(_dereq_,module,exports){
144'use strict';
145
146var utils = _dereq_('./utils');
147
148var table = [
149 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
150 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
151 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
152 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
153 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
154 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
155 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
156 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
157 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
158 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
159 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
160 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
161 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
162 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
163 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
164 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
165 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
166 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
167 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
168 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
169 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
170 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
171 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
172 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
173 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
174 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
175 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
176 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
177 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
178 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
179 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
180 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
181 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
182 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
183 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
184 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
185 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
186 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
187 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
188 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
189 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
190 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
191 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
192 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
193 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
194 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
195 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
196 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
197 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
198 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
199 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
200 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
201 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
202 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
203 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
204 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
205 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
206 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
207 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
208 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
209 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
210 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
211 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
212 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
213];
214
215/**
216 *
217 * Javascript crc32
218 * http://www.webtoolkit.info/
219 *
220 */
221module.exports = function crc32(input, crc) {
222 if (typeof input === "undefined" || !input.length) {
223 return 0;
224 }
225
226 var isArray = utils.getTypeOf(input) !== "string";
227
228 if (typeof(crc) == "undefined") {
229 crc = 0;
230 }
231 var x = 0;
232 var y = 0;
233 var b = 0;
234
235 crc = crc ^ (-1);
236 for (var i = 0, iTop = input.length; i < iTop; i++) {
237 b = isArray ? input[i] : input.charCodeAt(i);
238 y = (crc ^ b) & 0xFF;
239 x = table[y];
240 crc = (crc >>> 8) ^ x;
241 }
242
243 return crc ^ (-1);
244};
245// vim: set shiftwidth=4 softtabstop=4:
246
247},{"./utils":21}],5:[function(_dereq_,module,exports){
248'use strict';
249var utils = _dereq_('./utils');
250
251function DataReader(data) {
252 this.data = null; // type : see implementation
253 this.length = 0;
254 this.index = 0;
255}
256DataReader.prototype = {
257 /**
258 * Check that the offset will not go too far.
259 * @param {string} offset the additional offset to check.
260 * @throws {Error} an Error if the offset is out of bounds.
261 */
262 checkOffset: function(offset) {
263 this.checkIndex(this.index + offset);
264 },
265 /**
266 * Check that the specifed index will not be too far.
267 * @param {string} newIndex the index to check.
268 * @throws {Error} an Error if the index is out of bounds.
269 */
270 checkIndex: function(newIndex) {
271 if (this.length < newIndex || newIndex < 0) {
272 throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
273 }
274 },
275 /**
276 * Change the index.
277 * @param {number} newIndex The new index.
278 * @throws {Error} if the new index is out of the data.
279 */
280 setIndex: function(newIndex) {
281 this.checkIndex(newIndex);
282 this.index = newIndex;
283 },
284 /**
285 * Skip the next n bytes.
286 * @param {number} n the number of bytes to skip.
287 * @throws {Error} if the new index is out of the data.
288 */
289 skip: function(n) {
290 this.setIndex(this.index + n);
291 },
292 /**
293 * Get the byte at the specified index.
294 * @param {number} i the index to use.
295 * @return {number} a byte.
296 */
297 byteAt: function(i) {
298 // see implementations
299 },
300 /**
301 * Get the next number with a given byte size.
302 * @param {number} size the number of bytes to read.
303 * @return {number} the corresponding number.
304 */
305 readInt: function(size) {
306 var result = 0,
307 i;
308 this.checkOffset(size);
309 for (i = this.index + size - 1; i >= this.index; i--) {
310 result = (result << 8) + this.byteAt(i);
311 }
312 this.index += size;
313 return result;
314 },
315 /**
316 * Get the next string with a given byte size.
317 * @param {number} size the number of bytes to read.
318 * @return {string} the corresponding string.
319 */
320 readString: function(size) {
321 return utils.transformTo("string", this.readData(size));
322 },
323 /**
324 * Get raw data without conversion, <size> bytes.
325 * @param {number} size the number of bytes to read.
326 * @return {Object} the raw data, implementation specific.
327 */
328 readData: function(size) {
329 // see implementations
330 },
331 /**
332 * Find the last occurrence of a zip signature (4 bytes).
333 * @param {string} sig the signature to find.
334 * @return {number} the index of the last occurrence, -1 if not found.
335 */
336 lastIndexOfSignature: function(sig) {
337 // see implementations
338 },
339 /**
340 * Get the next date.
341 * @return {Date} the date.
342 */
343 readDate: function() {
344 var dostime = this.readInt(4);
345 return new Date(
346 ((dostime >> 25) & 0x7f) + 1980, // year
347 ((dostime >> 21) & 0x0f) - 1, // month
348 (dostime >> 16) & 0x1f, // day
349 (dostime >> 11) & 0x1f, // hour
350 (dostime >> 5) & 0x3f, // minute
351 (dostime & 0x1f) << 1); // second
352 }
353};
354module.exports = DataReader;
355
356},{"./utils":21}],6:[function(_dereq_,module,exports){
357'use strict';
358exports.base64 = false;
359exports.binary = false;
360exports.dir = false;
361exports.createFolders = false;
362exports.date = null;
363exports.compression = null;
364exports.comment = null;
365
366},{}],7:[function(_dereq_,module,exports){
367'use strict';
368var utils = _dereq_('./utils');
369
370/**
371 * @deprecated
372 * This function will be removed in a future version without replacement.
373 */
374exports.string2binary = function(str) {
375 return utils.string2binary(str);
376};
377
378/**
379 * @deprecated
380 * This function will be removed in a future version without replacement.
381 */
382exports.string2Uint8Array = function(str) {
383 return utils.transformTo("uint8array", str);
384};
385
386/**
387 * @deprecated
388 * This function will be removed in a future version without replacement.
389 */
390exports.uint8Array2String = function(array) {
391 return utils.transformTo("string", array);
392};
393
394/**
395 * @deprecated
396 * This function will be removed in a future version without replacement.
397 */
398exports.string2Blob = function(str) {
399 var buffer = utils.transformTo("arraybuffer", str);
400 return utils.arrayBuffer2Blob(buffer);
401};
402
403/**
404 * @deprecated
405 * This function will be removed in a future version without replacement.
406 */
407exports.arrayBuffer2Blob = function(buffer) {
408 return utils.arrayBuffer2Blob(buffer);
409};
410
411/**
412 * @deprecated
413 * This function will be removed in a future version without replacement.
414 */
415exports.transformTo = function(outputType, input) {
416 return utils.transformTo(outputType, input);
417};
418
419/**
420 * @deprecated
421 * This function will be removed in a future version without replacement.
422 */
423exports.getTypeOf = function(input) {
424 return utils.getTypeOf(input);
425};
426
427/**
428 * @deprecated
429 * This function will be removed in a future version without replacement.
430 */
431exports.checkSupport = function(type) {
432 return utils.checkSupport(type);
433};
434
435/**
436 * @deprecated
437 * This value will be removed in a future version without replacement.
438 */
439exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS;
440
441/**
442 * @deprecated
443 * This value will be removed in a future version without replacement.
444 */
445exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS;
446
447
448/**
449 * @deprecated
450 * This function will be removed in a future version without replacement.
451 */
452exports.pretty = function(str) {
453 return utils.pretty(str);
454};
455
456/**
457 * @deprecated
458 * This function will be removed in a future version without replacement.
459 */
460exports.findCompression = function(compressionMethod) {
461 return utils.findCompression(compressionMethod);
462};
463
464/**
465 * @deprecated
466 * This function will be removed in a future version without replacement.
467 */
468exports.isRegExp = function (object) {
469 return utils.isRegExp(object);
470};
471
472
473},{"./utils":21}],8:[function(_dereq_,module,exports){
474'use strict';
475var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
476
477var pako = _dereq_("pako");
478exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
479exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
480
481exports.magic = "\x08\x00";
482exports.compress = function(input) {
483 return pako.deflateRaw(input);
484};
485exports.uncompress = function(input) {
486 return pako.inflateRaw(input);
487};
488
489},{"pako":24}],9:[function(_dereq_,module,exports){
490'use strict';
491
492var base64 = _dereq_('./base64');
493
494/**
495Usage:
496 zip = new JSZip();
497 zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing");
498 zip.folder("images").file("smile.gif", base64Data, {base64: true});
499 zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
500 zip.remove("tempfile");
501
502 base64zip = zip.generate();
503
504**/
505
506/**
507 * Representation a of zip file in js
508 * @constructor
509 * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional).
510 * @param {Object=} options the options for creating this objects (optional).
511 */
512function JSZipSync(data, options) {
513 // if this constructor is used without `new`, it adds `new` before itself:
514 if(!(this instanceof JSZipSync)) return new JSZipSync(data, options);
515
516 // object containing the files :
517 // {
518 // "folder/" : {...},
519 // "folder/data.txt" : {...}
520 // }
521 this.files = {};
522
523 this.comment = null;
524
525 // Where we are in the hierarchy
526 this.root = "";
527 if (data) {
528 this.load(data, options);
529 }
530 this.clone = function() {
531 var newObj = new JSZipSync();
532 for (var i in this) {
533 if (typeof this[i] !== "function") {
534 newObj[i] = this[i];
535 }
536 }
537 return newObj;
538 };
539}
540JSZipSync.prototype = _dereq_('./object');
541JSZipSync.prototype.load = _dereq_('./load');
542JSZipSync.support = _dereq_('./support');
543JSZipSync.defaults = _dereq_('./defaults');
544
545/**
546 * @deprecated
547 * This namespace will be removed in a future version without replacement.
548 */
549JSZipSync.utils = _dereq_('./deprecatedPublicUtils');
550
551JSZipSync.base64 = {
552 /**
553 * @deprecated
554 * This method will be removed in a future version without replacement.
555 */
556 encode : function(input) {
557 return base64.encode(input);
558 },
559 /**
560 * @deprecated
561 * This method will be removed in a future version without replacement.
562 */
563 decode : function(input) {
564 return base64.decode(input);
565 }
566};
567JSZipSync.compressions = _dereq_('./compressions');
568module.exports = JSZipSync;
569
570},{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(_dereq_,module,exports){
571'use strict';
572var base64 = _dereq_('./base64');
573var ZipEntries = _dereq_('./zipEntries');
574module.exports = function(data, options) {
575 var files, zipEntries, i, input;
576 options = options || {};
577 if (options.base64) {
578 data = base64.decode(data);
579 }
580
581 zipEntries = new ZipEntries(data, options);
582 files = zipEntries.files;
583 for (i = 0; i < files.length; i++) {
584 input = files[i];
585 this.file(input.fileName, input.decompressed, {
586 binary: true,
587 optimizedBinaryString: true,
588 date: input.date,
589 dir: input.dir,
590 comment : input.fileComment.length ? input.fileComment : null,
591 createFolders: options.createFolders
592 });
593 }
594 if (zipEntries.zipComment.length) {
595 this.comment = zipEntries.zipComment;
596 }
597
598 return this;
599};
600
601},{"./base64":1,"./zipEntries":22}],11:[function(_dereq_,module,exports){
602(function (Buffer){
603'use strict';
604var Buffer_from = /*::(*/function(){}/*:: :any)*/;
605if(typeof Buffer !== 'undefined') {
606 var nbfs = !Buffer.from;
607 if(!nbfs) try { Buffer.from("foo", "utf8"); } catch(e) { nbfs = true; }
608 Buffer_from = nbfs ? function(buf, enc) { return (enc) ? new Buffer(buf, enc) : new Buffer(buf); } : Buffer.from.bind(Buffer);
609 // $FlowIgnore
610 if(!Buffer.alloc) Buffer.alloc = function(n) { return new Buffer(n); };
611}
612module.exports = function(data, encoding){
613 return typeof data == 'number' ? Buffer.alloc(data) : Buffer_from(data, encoding);
614};
615module.exports.test = function(b){
616 return Buffer.isBuffer(b);
617};
618}).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined))
619},{}],12:[function(_dereq_,module,exports){
620'use strict';
621var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
622
623function NodeBufferReader(data) {
624 this.data = data;
625 this.length = this.data.length;
626 this.index = 0;
627}
628NodeBufferReader.prototype = new Uint8ArrayReader();
629
630/**
631 * @see DataReader.readData
632 */
633NodeBufferReader.prototype.readData = function(size) {
634 this.checkOffset(size);
635 var result = this.data.slice(this.index, this.index + size);
636 this.index += size;
637 return result;
638};
639module.exports = NodeBufferReader;
640
641},{"./uint8ArrayReader":18}],13:[function(_dereq_,module,exports){
642'use strict';
643var support = _dereq_('./support');
644var utils = _dereq_('./utils');
645var crc32 = _dereq_('./crc32');
646var signature = _dereq_('./signature');
647var defaults = _dereq_('./defaults');
648var base64 = _dereq_('./base64');
649var compressions = _dereq_('./compressions');
650var CompressedObject = _dereq_('./compressedObject');
651var nodeBuffer = _dereq_('./nodeBuffer');
652var utf8 = _dereq_('./utf8');
653var StringWriter = _dereq_('./stringWriter');
654var Uint8ArrayWriter = _dereq_('./uint8ArrayWriter');
655
656/**
657 * Returns the raw data of a ZipObject, decompress the content if necessary.
658 * @param {ZipObject} file the file to use.
659 * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
660 */
661var getRawData = function(file) {
662 if (file._data instanceof CompressedObject) {
663 file._data = file._data.getContent();
664 file.options.binary = true;
665 file.options.base64 = false;
666
667 if (utils.getTypeOf(file._data) === "uint8array") {
668 var copy = file._data;
669 // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
670 // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
671 file._data = new Uint8Array(copy.length);
672 // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
673 if (copy.length !== 0) {
674 file._data.set(copy, 0);
675 }
676 }
677 }
678 return file._data;
679};
680
681/**
682 * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
683 * @param {ZipObject} file the file to use.
684 * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
685 */
686var getBinaryData = function(file) {
687 var result = getRawData(file),
688 type = utils.getTypeOf(result);
689 if (type === "string") {
690 if (!file.options.binary) {
691 // unicode text !
692 // unicode string => binary string is a painful process, check if we can avoid it.
693 if (support.nodebuffer) {
694 return nodeBuffer(result, "utf-8");
695 }
696 }
697 return file.asBinary();
698 }
699 return result;
700};
701
702/**
703 * Transform this._data into a string.
704 * @param {function} filter a function String -> String, applied if not null on the result.
705 * @return {String} the string representing this._data.
706 */
707var dataToString = function(asUTF8) {
708 var result = getRawData(this);
709 if (result === null || typeof result === "undefined") {
710 return "";
711 }
712 // if the data is a base64 string, we decode it before checking the encoding !
713 if (this.options.base64) {
714 result = base64.decode(result);
715 }
716 if (asUTF8 && this.options.binary) {
717 // JSZip.prototype.utf8decode supports arrays as input
718 // skip to array => string step, utf8decode will do it.
719 result = out.utf8decode(result);
720 }
721 else {
722 // no utf8 transformation, do the array => string step.
723 result = utils.transformTo("string", result);
724 }
725
726 if (!asUTF8 && !this.options.binary) {
727 result = utils.transformTo("string", out.utf8encode(result));
728 }
729 return result;
730};
731/**
732 * A simple object representing a file in the zip file.
733 * @constructor
734 * @param {string} name the name of the file
735 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
736 * @param {Object} options the options of the file
737 */
738var ZipObject = function(name, data, options) {
739 this.name = name;
740 this.dir = options.dir;
741 this.date = options.date;
742 this.comment = options.comment;
743
744 this._data = data;
745 this.options = options;
746
747 /*
748 * This object contains initial values for dir and date.
749 * With them, we can check if the user changed the deprecated metadata in
750 * `ZipObject#options` or not.
751 */
752 this._initialMetadata = {
753 dir : options.dir,
754 date : options.date
755 };
756};
757
758ZipObject.prototype = {
759 /**
760 * Return the content as UTF8 string.
761 * @return {string} the UTF8 string.
762 */
763 asText: function() {
764 return dataToString.call(this, true);
765 },
766 /**
767 * Returns the binary content.
768 * @return {string} the content as binary.
769 */
770 asBinary: function() {
771 return dataToString.call(this, false);
772 },
773 /**
774 * Returns the content as a nodejs Buffer.
775 * @return {Buffer} the content as a Buffer.
776 */
777 asNodeBuffer: function() {
778 var result = getBinaryData(this);
779 return utils.transformTo("nodebuffer", result);
780 },
781 /**
782 * Returns the content as an Uint8Array.
783 * @return {Uint8Array} the content as an Uint8Array.
784 */
785 asUint8Array: function() {
786 var result = getBinaryData(this);
787 return utils.transformTo("uint8array", result);
788 },
789 /**
790 * Returns the content as an ArrayBuffer.
791 * @return {ArrayBuffer} the content as an ArrayBufer.
792 */
793 asArrayBuffer: function() {
794 return this.asUint8Array().buffer;
795 }
796};
797
798/**
799 * Transform an integer into a string in hexadecimal.
800 * @private
801 * @param {number} dec the number to convert.
802 * @param {number} bytes the number of bytes to generate.
803 * @returns {string} the result.
804 */
805var decToHex = function(dec, bytes) {
806 var hex = "",
807 i;
808 for (i = 0; i < bytes; i++) {
809 hex += String.fromCharCode(dec & 0xff);
810 dec = dec >>> 8;
811 }
812 return hex;
813};
814
815/**
816 * Merge the objects passed as parameters into a new one.
817 * @private
818 * @param {...Object} var_args All objects to merge.
819 * @return {Object} a new object with the data of the others.
820 */
821var extend = function() {
822 var result = {}, i, attr;
823 for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
824 for (attr in arguments[i]) {
825 if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
826 result[attr] = arguments[i][attr];
827 }
828 }
829 }
830 return result;
831};
832
833/**
834 * Transforms the (incomplete) options from the user into the complete
835 * set of options to create a file.
836 * @private
837 * @param {Object} o the options from the user.
838 * @return {Object} the complete set of options.
839 */
840var prepareFileAttrs = function(o) {
841 o = o || {};
842 if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
843 o.binary = true;
844 }
845 o = extend(o, defaults);
846 o.date = o.date || new Date();
847 if (o.compression !== null) o.compression = o.compression.toUpperCase();
848
849 return o;
850};
851
852/**
853 * Add a file in the current folder.
854 * @private
855 * @param {string} name the name of the file
856 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
857 * @param {Object} o the options of the file
858 * @return {Object} the new file.
859 */
860var fileAdd = function(name, data, o) {
861 // be sure sub folders exist
862 var dataType = utils.getTypeOf(data),
863 parent;
864
865 o = prepareFileAttrs(o);
866
867 if (o.createFolders && (parent = parentFolder(name))) {
868 folderAdd.call(this, parent, true);
869 }
870
871 if (o.dir || data === null || typeof data === "undefined") {
872 o.base64 = false;
873 o.binary = false;
874 data = null;
875 }
876 else if (dataType === "string") {
877 if (o.binary && !o.base64) {
878 // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
879 if (o.optimizedBinaryString !== true) {
880 // this is a string, not in a base64 format.
881 // Be sure that this is a correct "binary string"
882 data = utils.string2binary(data);
883 }
884 }
885 }
886 else { // arraybuffer, uint8array, ...
887 o.base64 = false;
888 o.binary = true;
889
890 if (!dataType && !(data instanceof CompressedObject)) {
891 throw new Error("The data of '" + name + "' is in an unsupported format !");
892 }
893
894 // special case : it's way easier to work with Uint8Array than with ArrayBuffer
895 if (dataType === "arraybuffer") {
896 data = utils.transformTo("uint8array", data);
897 }
898 }
899
900 var object = new ZipObject(name, data, o);
901 this.files[name] = object;
902 return object;
903};
904
905/**
906 * Find the parent folder of the path.
907 * @private
908 * @param {string} path the path to use
909 * @return {string} the parent folder, or ""
910 */
911var parentFolder = function (path) {
912 if (path.slice(-1) == '/') {
913 path = path.substring(0, path.length - 1);
914 }
915 var lastSlash = path.lastIndexOf('/');
916 return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
917};
918
919/**
920 * Add a (sub) folder in the current folder.
921 * @private
922 * @param {string} name the folder's name
923 * @param {boolean=} [createFolders] If true, automatically create sub
924 * folders. Defaults to false.
925 * @return {Object} the new folder.
926 */
927var folderAdd = function(name, createFolders) {
928 // Check the name ends with a /
929 if (name.slice(-1) != "/") {
930 name += "/"; // IE doesn't like substr(-1)
931 }
932
933 createFolders = (typeof createFolders !== 'undefined') ? createFolders : false;
934
935 // Does this folder already exist?
936 if (!this.files[name]) {
937 fileAdd.call(this, name, null, {
938 dir: true,
939 createFolders: createFolders
940 });
941 }
942 return this.files[name];
943};
944
945/**
946 * Generate a JSZip.CompressedObject for a given zipOject.
947 * @param {ZipObject} file the object to read.
948 * @param {JSZip.compression} compression the compression to use.
949 * @return {JSZip.CompressedObject} the compressed result.
950 */
951var generateCompressedObjectFrom = function(file, compression) {
952 var result = new CompressedObject(),
953 content;
954
955 // the data has not been decompressed, we might reuse things !
956 if (file._data instanceof CompressedObject) {
957 result.uncompressedSize = file._data.uncompressedSize;
958 result.crc32 = file._data.crc32;
959
960 if (result.uncompressedSize === 0 || file.dir) {
961 compression = compressions['STORE'];
962 result.compressedContent = "";
963 result.crc32 = 0;
964 }
965 else if (file._data.compressionMethod === compression.magic) {
966 result.compressedContent = file._data.getCompressedContent();
967 }
968 else {
969 content = file._data.getContent();
970 // need to decompress / recompress
971 result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content));
972 }
973 }
974 else {
975 // have uncompressed data
976 content = getBinaryData(file);
977 if (!content || content.length === 0 || file.dir) {
978 compression = compressions['STORE'];
979 content = "";
980 }
981 result.uncompressedSize = content.length;
982 result.crc32 = crc32(content);
983 result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content));
984 }
985
986 result.compressedSize = result.compressedContent.length;
987 result.compressionMethod = compression.magic;
988
989 return result;
990};
991
992/**
993 * Generate the various parts used in the construction of the final zip file.
994 * @param {string} name the file name.
995 * @param {ZipObject} file the file content.
996 * @param {JSZip.CompressedObject} compressedObject the compressed object.
997 * @param {number} offset the current offset from the start of the zip file.
998 * @return {object} the zip parts.
999 */
1000var generateZipParts = function(name, file, compressedObject, offset) {
1001 var data = compressedObject.compressedContent,
1002 utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
1003 comment = file.comment || "",
1004 utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
1005 useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
1006 useUTF8ForComment = utfEncodedComment.length !== comment.length,
1007 o = file.options,
1008 dosTime,
1009 dosDate,
1010 extraFields = "",
1011 unicodePathExtraField = "",
1012 unicodeCommentExtraField = "",
1013 dir, date;
1014
1015
1016 // handle the deprecated options.dir
1017 if (file._initialMetadata.dir !== file.dir) {
1018 dir = file.dir;
1019 } else {
1020 dir = o.dir;
1021 }
1022
1023 // handle the deprecated options.date
1024 if(file._initialMetadata.date !== file.date) {
1025 date = file.date;
1026 } else {
1027 date = o.date;
1028 }
1029
1030
1031 dosTime = date.getHours();
1032 dosTime = dosTime << 6;
1033 dosTime = dosTime | date.getMinutes();
1034 dosTime = dosTime << 5;
1035 dosTime = dosTime | date.getSeconds() / 2;
1036
1037 dosDate = date.getFullYear() - 1980;
1038 dosDate = dosDate << 4;
1039 dosDate = dosDate | (date.getMonth() + 1);
1040 dosDate = dosDate << 5;
1041 dosDate = dosDate | date.getDate();
1042
1043 if (useUTF8ForFileName) {
1044 // set the unicode path extra field. unzip needs at least one extra
1045 // field to correctly handle unicode path, so using the path is as good
1046 // as any other information. This could improve the situation with
1047 // other archive managers too.
1048 // This field is usually used without the utf8 flag, with a non
1049 // unicode path in the header (winrar, winzip). This helps (a bit)
1050 // with the messy Windows' default compressed folders feature but
1051 // breaks on p7zip which doesn't seek the unicode path extra field.
1052 // So for now, UTF-8 everywhere !
1053 unicodePathExtraField =
1054 // Version
1055 decToHex(1, 1) +
1056 // NameCRC32
1057 decToHex(crc32(utfEncodedFileName), 4) +
1058 // UnicodeName
1059 utfEncodedFileName;
1060
1061 extraFields +=
1062 // Info-ZIP Unicode Path Extra Field
1063 "\x75\x70" +
1064 // size
1065 decToHex(unicodePathExtraField.length, 2) +
1066 // content
1067 unicodePathExtraField;
1068 }
1069
1070 if(useUTF8ForComment) {
1071
1072 unicodeCommentExtraField =
1073 // Version
1074 decToHex(1, 1) +
1075 // CommentCRC32
1076 decToHex(this.crc32(utfEncodedComment), 4) +
1077 // UnicodeName
1078 utfEncodedComment;
1079
1080 extraFields +=
1081 // Info-ZIP Unicode Path Extra Field
1082 "\x75\x63" +
1083 // size
1084 decToHex(unicodeCommentExtraField.length, 2) +
1085 // content
1086 unicodeCommentExtraField;
1087 }
1088
1089 var header = "";
1090
1091 // version needed to extract
1092 header += "\x0A\x00";
1093 // general purpose bit flag
1094 // set bit 11 if utf8
1095 header += (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00";
1096 // compression method
1097 header += compressedObject.compressionMethod;
1098 // last mod file time
1099 header += decToHex(dosTime, 2);
1100 // last mod file date
1101 header += decToHex(dosDate, 2);
1102 // crc-32
1103 header += decToHex(compressedObject.crc32, 4);
1104 // compressed size
1105 header += decToHex(compressedObject.compressedSize, 4);
1106 // uncompressed size
1107 header += decToHex(compressedObject.uncompressedSize, 4);
1108 // file name length
1109 header += decToHex(utfEncodedFileName.length, 2);
1110 // extra field length
1111 header += decToHex(extraFields.length, 2);
1112
1113
1114 var fileRecord = signature.LOCAL_FILE_HEADER + header + utfEncodedFileName + extraFields;
1115
1116 var dirRecord = signature.CENTRAL_FILE_HEADER +
1117 // version made by (00: DOS)
1118 "\x14\x00" +
1119 // file header (common to file and central directory)
1120 header +
1121 // file comment length
1122 decToHex(utfEncodedComment.length, 2) +
1123 // disk number start
1124 "\x00\x00" +
1125 // internal file attributes TODO
1126 "\x00\x00" +
1127 // external file attributes
1128 (dir === true ? "\x10\x00\x00\x00" : "\x00\x00\x00\x00") +
1129 // relative offset of local header
1130 decToHex(offset, 4) +
1131 // file name
1132 utfEncodedFileName +
1133 // extra field
1134 extraFields +
1135 // file comment
1136 utfEncodedComment;
1137
1138 return {
1139 fileRecord: fileRecord,
1140 dirRecord: dirRecord,
1141 compressedObject: compressedObject
1142 };
1143};
1144
1145
1146// return the actual prototype of JSZip
1147var out = {
1148 /**
1149 * Read an existing zip and merge the data in the current JSZip object.
1150 * The implementation is in jszip-load.js, don't forget to include it.
1151 * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load
1152 * @param {Object} options Options for loading the stream.
1153 * options.base64 : is the stream in base64 ? default : false
1154 * @return {JSZip} the current JSZip object
1155 */
1156 load: function(stream, options) {
1157 throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
1158 },
1159
1160 /**
1161 * Filter nested files/folders with the specified function.
1162 * @param {Function} search the predicate to use :
1163 * function (relativePath, file) {...}
1164 * It takes 2 arguments : the relative path and the file.
1165 * @return {Array} An array of matching elements.
1166 */
1167 filter: function(search) {
1168 var result = [],
1169 filename, relativePath, file, fileClone;
1170 for (filename in this.files) {
1171 if (!this.files.hasOwnProperty(filename)) {
1172 continue;
1173 }
1174 file = this.files[filename];
1175 // return a new object, don't let the user mess with our internal objects :)
1176 fileClone = new ZipObject(file.name, file._data, extend(file.options));
1177 relativePath = filename.slice(this.root.length, filename.length);
1178 if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
1179 search(relativePath, fileClone)) { // and the file matches the function
1180 result.push(fileClone);
1181 }
1182 }
1183 return result;
1184 },
1185
1186 /**
1187 * Add a file to the zip file, or search a file.
1188 * @param {string|RegExp} name The name of the file to add (if data is defined),
1189 * the name of the file to find (if no data) or a regex to match files.
1190 * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
1191 * @param {Object} o File options
1192 * @return {JSZip|Object|Array} this JSZip object (when adding a file),
1193 * a file (when searching by string) or an array of files (when searching by regex).
1194 */
1195 file: function(name, data, o) {
1196 if (arguments.length === 1) {
1197 if (utils.isRegExp(name)) {
1198 var regexp = name;
1199 return this.filter(function(relativePath, file) {
1200 return !file.dir && regexp.test(relativePath);
1201 });
1202 }
1203 else { // text
1204 return this.filter(function(relativePath, file) {
1205 return !file.dir && relativePath === name;
1206 })[0] || null;
1207 }
1208 }
1209 else { // more than one argument : we have data !
1210 name = this.root + name;
1211 fileAdd.call(this, name, data, o);
1212 }
1213 return this;
1214 },
1215
1216 /**
1217 * Add a directory to the zip file, or search.
1218 * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
1219 * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
1220 */
1221 folder: function(arg) {
1222 if (!arg) {
1223 return this;
1224 }
1225
1226 if (utils.isRegExp(arg)) {
1227 return this.filter(function(relativePath, file) {
1228 return file.dir && arg.test(relativePath);
1229 });
1230 }
1231
1232 // else, name is a new folder
1233 var name = this.root + arg;
1234 var newFolder = folderAdd.call(this, name);
1235
1236 // Allow chaining by returning a new object with this folder as the root
1237 var ret = this.clone();
1238 ret.root = newFolder.name;
1239 return ret;
1240 },
1241
1242 /**
1243 * Delete a file, or a directory and all sub-files, from the zip
1244 * @param {string} name the name of the file to delete
1245 * @return {JSZip} this JSZip object
1246 */
1247 remove: function(name) {
1248 name = this.root + name;
1249 var file = this.files[name];
1250 if (!file) {
1251 // Look for any folders
1252 if (name.slice(-1) != "/") {
1253 name += "/";
1254 }
1255 file = this.files[name];
1256 }
1257
1258 if (file && !file.dir) {
1259 // file
1260 delete this.files[name];
1261 } else {
1262 // maybe a folder, delete recursively
1263 var kids = this.filter(function(relativePath, file) {
1264 return file.name.slice(0, name.length) === name;
1265 });
1266 for (var i = 0; i < kids.length; i++) {
1267 delete this.files[kids[i].name];
1268 }
1269 }
1270
1271 return this;
1272 },
1273
1274 /**
1275 * Generate the complete zip file
1276 * @param {Object} options the options to generate the zip file :
1277 * - base64, (deprecated, use type instead) true to generate base64.
1278 * - compression, "STORE" by default.
1279 * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
1280 * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
1281 */
1282 generate: function(options) {
1283 options = extend(options || {}, {
1284 base64: true,
1285 compression: "STORE",
1286 type: "base64",
1287 comment: null
1288 });
1289
1290 utils.checkSupport(options.type);
1291
1292 var zipData = [],
1293 localDirLength = 0,
1294 centralDirLength = 0,
1295 writer, i,
1296 utfEncodedComment = utils.transformTo("string", this.utf8encode(options.comment || this.comment || ""));
1297
1298 // first, generate all the zip parts.
1299 for (var name in this.files) {
1300 if (!this.files.hasOwnProperty(name)) {
1301 continue;
1302 }
1303 var file = this.files[name];
1304
1305 var compressionName = file.options.compression || options.compression.toUpperCase();
1306 var compression = compressions[compressionName];
1307 if (!compression) {
1308 throw new Error(compressionName + " is not a valid compression method !");
1309 }
1310
1311 var compressedObject = generateCompressedObjectFrom.call(this, file, compression);
1312
1313 var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength);
1314 localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
1315 centralDirLength += zipPart.dirRecord.length;
1316 zipData.push(zipPart);
1317 }
1318
1319 var dirEnd = "";
1320
1321 // end of central dir signature
1322 dirEnd = signature.CENTRAL_DIRECTORY_END +
1323 // number of this disk
1324 "\x00\x00" +
1325 // number of the disk with the start of the central directory
1326 "\x00\x00" +
1327 // total number of entries in the central directory on this disk
1328 decToHex(zipData.length, 2) +
1329 // total number of entries in the central directory
1330 decToHex(zipData.length, 2) +
1331 // size of the central directory 4 bytes
1332 decToHex(centralDirLength, 4) +
1333 // offset of start of central directory with respect to the starting disk number
1334 decToHex(localDirLength, 4) +
1335 // .ZIP file comment length
1336 decToHex(utfEncodedComment.length, 2) +
1337 // .ZIP file comment
1338 utfEncodedComment;
1339
1340
1341 // we have all the parts (and the total length)
1342 // time to create a writer !
1343 var typeName = options.type.toLowerCase();
1344 if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") {
1345 writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
1346 }else{
1347 writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
1348 }
1349
1350 for (i = 0; i < zipData.length; i++) {
1351 writer.append(zipData[i].fileRecord);
1352 writer.append(zipData[i].compressedObject.compressedContent);
1353 }
1354 for (i = 0; i < zipData.length; i++) {
1355 writer.append(zipData[i].dirRecord);
1356 }
1357
1358 writer.append(dirEnd);
1359
1360 var zip = writer.finalize();
1361
1362
1363
1364 switch(options.type.toLowerCase()) {
1365 // case "zip is an Uint8Array"
1366 case "uint8array" :
1367 case "arraybuffer" :
1368 case "nodebuffer" :
1369 return utils.transformTo(options.type.toLowerCase(), zip);
1370 case "blob" :
1371 return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip));
1372 // case "zip is a string"
1373 case "base64" :
1374 return (options.base64) ? base64.encode(zip) : zip;
1375 default : // case "string" :
1376 return zip;
1377 }
1378
1379 },
1380
1381 /**
1382 * @deprecated
1383 * This method will be removed in a future version without replacement.
1384 */
1385 crc32: function (input, crc) {
1386 return crc32(input, crc);
1387 },
1388
1389 /**
1390 * @deprecated
1391 * This method will be removed in a future version without replacement.
1392 */
1393 utf8encode: function (string) {
1394 return utils.transformTo("string", utf8.utf8encode(string));
1395 },
1396
1397 /**
1398 * @deprecated
1399 * This method will be removed in a future version without replacement.
1400 */
1401 utf8decode: function (input) {
1402 return utf8.utf8decode(input);
1403 }
1404};
1405module.exports = out;
1406
1407},{"./base64":1,"./compressedObject":2,"./compressions":3,"./crc32":4,"./defaults":6,"./nodeBuffer":11,"./signature":14,"./stringWriter":16,"./support":17,"./uint8ArrayWriter":19,"./utf8":20,"./utils":21}],14:[function(_dereq_,module,exports){
1408'use strict';
1409exports.LOCAL_FILE_HEADER = "PK\x03\x04";
1410exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
1411exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
1412exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
1413exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
1414exports.DATA_DESCRIPTOR = "PK\x07\x08";
1415
1416},{}],15:[function(_dereq_,module,exports){
1417'use strict';
1418var DataReader = _dereq_('./dataReader');
1419var utils = _dereq_('./utils');
1420
1421function StringReader(data, optimizedBinaryString) {
1422 this.data = data;
1423 if (!optimizedBinaryString) {
1424 this.data = utils.string2binary(this.data);
1425 }
1426 this.length = this.data.length;
1427 this.index = 0;
1428}
1429StringReader.prototype = new DataReader();
1430/**
1431 * @see DataReader.byteAt
1432 */
1433StringReader.prototype.byteAt = function(i) {
1434 return this.data.charCodeAt(i);
1435};
1436/**
1437 * @see DataReader.lastIndexOfSignature
1438 */
1439StringReader.prototype.lastIndexOfSignature = function(sig) {
1440 return this.data.lastIndexOf(sig);
1441};
1442/**
1443 * @see DataReader.readData
1444 */
1445StringReader.prototype.readData = function(size) {
1446 this.checkOffset(size);
1447 // this will work because the constructor applied the "& 0xff" mask.
1448 var result = this.data.slice(this.index, this.index + size);
1449 this.index += size;
1450 return result;
1451};
1452module.exports = StringReader;
1453
1454},{"./dataReader":5,"./utils":21}],16:[function(_dereq_,module,exports){
1455'use strict';
1456
1457var utils = _dereq_('./utils');
1458
1459/**
1460 * An object to write any content to a string.
1461 * @constructor
1462 */
1463var StringWriter = function() {
1464 this.data = [];
1465};
1466StringWriter.prototype = {
1467 /**
1468 * Append any content to the current string.
1469 * @param {Object} input the content to add.
1470 */
1471 append: function(input) {
1472 input = utils.transformTo("string", input);
1473 this.data.push(input);
1474 },
1475 /**
1476 * Finalize the construction an return the result.
1477 * @return {string} the generated string.
1478 */
1479 finalize: function() {
1480 return this.data.join("");
1481 }
1482};
1483
1484module.exports = StringWriter;
1485
1486},{"./utils":21}],17:[function(_dereq_,module,exports){
1487(function (Buffer){
1488'use strict';
1489exports.base64 = true;
1490exports.array = true;
1491exports.string = true;
1492exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
1493// contains true if JSZip can read/generate nodejs Buffer, false otherwise.
1494// Browserify will provide a Buffer implementation for browsers, which is
1495// an augmented Uint8Array (i.e., can be used as either Buffer or U8).
1496exports.nodebuffer = typeof Buffer !== "undefined";
1497// contains true if JSZip can read/generate Uint8Array, false otherwise.
1498exports.uint8array = typeof Uint8Array !== "undefined";
1499
1500if (typeof ArrayBuffer === "undefined") {
1501 exports.blob = false;
1502}
1503else {
1504 var buffer = new ArrayBuffer(0);
1505 try {
1506 exports.blob = new Blob([buffer], {
1507 type: "application/zip"
1508 }).size === 0;
1509 }
1510 catch (e) {
1511 try {
1512 var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
1513 var builder = new Builder();
1514 builder.append(buffer);
1515 exports.blob = builder.getBlob('application/zip').size === 0;
1516 }
1517 catch (e) {
1518 exports.blob = false;
1519 }
1520 }
1521}
1522
1523}).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined))
1524},{}],18:[function(_dereq_,module,exports){
1525'use strict';
1526var DataReader = _dereq_('./dataReader');
1527
1528function Uint8ArrayReader(data) {
1529 if (data) {
1530 this.data = data;
1531 this.length = this.data.length;
1532 this.index = 0;
1533 }
1534}
1535Uint8ArrayReader.prototype = new DataReader();
1536/**
1537 * @see DataReader.byteAt
1538 */
1539Uint8ArrayReader.prototype.byteAt = function(i) {
1540 return this.data[i];
1541};
1542/**
1543 * @see DataReader.lastIndexOfSignature
1544 */
1545Uint8ArrayReader.prototype.lastIndexOfSignature = function(sig) {
1546 var sig0 = sig.charCodeAt(0),
1547 sig1 = sig.charCodeAt(1),
1548 sig2 = sig.charCodeAt(2),
1549 sig3 = sig.charCodeAt(3);
1550 for (var i = this.length - 4; i >= 0; --i) {
1551 if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
1552 return i;
1553 }
1554 }
1555
1556 return -1;
1557};
1558/**
1559 * @see DataReader.readData
1560 */
1561Uint8ArrayReader.prototype.readData = function(size) {
1562 this.checkOffset(size);
1563 if(size === 0) {
1564 // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
1565 return new Uint8Array(0);
1566 }
1567 var result = this.data.subarray(this.index, this.index + size);
1568 this.index += size;
1569 return result;
1570};
1571module.exports = Uint8ArrayReader;
1572
1573},{"./dataReader":5}],19:[function(_dereq_,module,exports){
1574'use strict';
1575
1576var utils = _dereq_('./utils');
1577
1578/**
1579 * An object to write any content to an Uint8Array.
1580 * @constructor
1581 * @param {number} length The length of the array.
1582 */
1583var Uint8ArrayWriter = function(length) {
1584 this.data = new Uint8Array(length);
1585 this.index = 0;
1586};
1587Uint8ArrayWriter.prototype = {
1588 /**
1589 * Append any content to the current array.
1590 * @param {Object} input the content to add.
1591 */
1592 append: function(input) {
1593 if (input.length !== 0) {
1594 // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
1595 input = utils.transformTo("uint8array", input);
1596 this.data.set(input, this.index);
1597 this.index += input.length;
1598 }
1599 },
1600 /**
1601 * Finalize the construction an return the result.
1602 * @return {Uint8Array} the generated array.
1603 */
1604 finalize: function() {
1605 return this.data;
1606 }
1607};
1608
1609module.exports = Uint8ArrayWriter;
1610
1611},{"./utils":21}],20:[function(_dereq_,module,exports){
1612'use strict';
1613
1614var utils = _dereq_('./utils');
1615var support = _dereq_('./support');
1616var nodeBuffer = _dereq_('./nodeBuffer');
1617
1618/**
1619 * The following functions come from pako, from pako/lib/utils/strings
1620 * released under the MIT license, see pako https://github.com/nodeca/pako/
1621 */
1622
1623// Table with utf8 lengths (calculated by first byte of sequence)
1624// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
1625// because max possible codepoint is 0x10ffff
1626var _utf8len = new Array(256);
1627for (var i=0; i<256; i++) {
1628 _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
1629}
1630_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
1631
1632// convert string to array (typed, when possible)
1633var string2buf = function (str) {
1634 var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
1635
1636 // count binary size
1637 for (m_pos = 0; m_pos < str_len; m_pos++) {
1638 c = str.charCodeAt(m_pos);
1639 if (((c & 0xfc00) === 0xd800) && (m_pos+1 < str_len)) {
1640 c2 = str.charCodeAt(m_pos+1);
1641 if ((c2 & 0xfc00) === 0xdc00) {
1642 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
1643 m_pos++;
1644 }
1645 }
1646 buf_len += (c < 0x80) ? 1 : ((c < 0x800) ? 2 : ((c < 0x10000) ? 3 : 4));
1647 }
1648
1649 // allocate buffer
1650 if (support.uint8array) {
1651 buf = new Uint8Array(buf_len);
1652 } else {
1653 buf = new Array(buf_len);
1654 }
1655
1656 // convert
1657 for (i=0, m_pos = 0; i < buf_len; m_pos++) {
1658 c = str.charCodeAt(m_pos);
1659 if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
1660 c2 = str.charCodeAt(m_pos+1);
1661 if ((c2 & 0xfc00) === 0xdc00) {
1662 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
1663 m_pos++;
1664 }
1665 }
1666 if (c < 0x80) {
1667 /* one byte */
1668 buf[i++] = c;
1669 } else if (c < 0x800) {
1670 /* two bytes */
1671 buf[i++] = 0xC0 | (c >>> 6);
1672 buf[i++] = 0x80 | (c & 0x3f);
1673 } else if (c < 0x10000) {
1674 /* three bytes */
1675 buf[i++] = 0xE0 | (c >>> 12);
1676 buf[i++] = 0x80 | ((c >>> 6) & 0x3f);
1677 buf[i++] = 0x80 | (c & 0x3f);
1678 } else {
1679 /* four bytes */
1680 buf[i++] = 0xf0 | (c >>> 18);
1681 buf[i++] = 0x80 | ((c >>> 12) & 0x3f);
1682 buf[i++] = 0x80 | ((c >>> 6) & 0x3f);
1683 buf[i++] = 0x80 | (c & 0x3f);
1684 }
1685 }
1686
1687 return buf;
1688};
1689
1690// Calculate max possible position in utf8 buffer,
1691// that will not break sequence. If that's not possible
1692// - (very small limits) return max size as is.
1693//
1694// buf[] - utf8 bytes array
1695// max - length limit (mandatory);
1696var utf8border = function(buf, max) {
1697 var pos;
1698
1699 max = max || buf.length;
1700 if (max > buf.length) { max = buf.length; }
1701
1702 // go back from last position, until start of sequence found
1703 pos = max-1;
1704 while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
1705
1706 // Fuckup - very small and broken sequence,
1707 // return max, because we should return something anyway.
1708 if (pos < 0) { return max; }
1709
1710 // If we came to start of buffer - that means vuffer is too small,
1711 // return max too.
1712 if (pos === 0) { return max; }
1713
1714 return (pos + _utf8len[buf[pos]] > max) ? pos : max;
1715};
1716
1717// convert array to string
1718var buf2string = function (buf) {
1719 var str, i, out, c, c_len;
1720 var len = buf.length;
1721
1722 // Reserve max possible length (2 words per char)
1723 // NB: by unknown reasons, Array is significantly faster for
1724 // String.fromCharCode.apply than Uint16Array.
1725 var utf16buf = new Array(len*2);
1726
1727 for (out=0, i=0; i<len;) {
1728 c = buf[i++];
1729 // quick process ascii
1730 if (c < 0x80) { utf16buf[out++] = c; continue; }
1731
1732 c_len = _utf8len[c];
1733 // skip 5 & 6 byte codes
1734 if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
1735
1736 // apply mask on first byte
1737 c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
1738 // join the rest
1739 while (c_len > 1 && i < len) {
1740 c = (c << 6) | (buf[i++] & 0x3f);
1741 c_len--;
1742 }
1743
1744 // terminated by end of string?
1745 if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
1746
1747 if (c < 0x10000) {
1748 utf16buf[out++] = c;
1749 } else {
1750 c -= 0x10000;
1751 utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
1752 utf16buf[out++] = 0xdc00 | (c & 0x3ff);
1753 }
1754 }
1755
1756 // shrinkBuf(utf16buf, out)
1757 if (utf16buf.length !== out) {
1758 if(utf16buf.subarray) {
1759 utf16buf = utf16buf.subarray(0, out);
1760 } else {
1761 utf16buf.length = out;
1762 }
1763 }
1764
1765 // return String.fromCharCode.apply(null, utf16buf);
1766 return utils.applyFromCharCode(utf16buf);
1767};
1768
1769
1770// That's all for the pako functions.
1771
1772
1773/**
1774 * Transform a javascript string into an array (typed if possible) of bytes,
1775 * UTF-8 encoded.
1776 * @param {String} str the string to encode
1777 * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
1778 */
1779exports.utf8encode = function utf8encode(str) {
1780 if (support.nodebuffer) {
1781 return nodeBuffer(str, "utf-8");
1782 }
1783
1784 return string2buf(str);
1785};
1786
1787
1788/**
1789 * Transform a bytes array (or a representation) representing an UTF-8 encoded
1790 * string into a javascript string.
1791 * @param {Array|Uint8Array|Buffer} buf the data de decode
1792 * @return {String} the decoded string.
1793 */
1794exports.utf8decode = function utf8decode(buf) {
1795 if (support.nodebuffer) {
1796 return utils.transformTo("nodebuffer", buf).toString("utf-8");
1797 }
1798
1799 buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
1800
1801 // return buf2string(buf);
1802 // Chrome prefers to work with "small" chunks of data
1803 // for the method buf2string.
1804 // Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
1805 var result = [], k = 0, len = buf.length, chunk = 65536;
1806 while (k < len) {
1807 var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
1808 if (support.uint8array) {
1809 result.push(buf2string(buf.subarray(k, nextBoundary)));
1810 } else {
1811 result.push(buf2string(buf.slice(k, nextBoundary)));
1812 }
1813 k = nextBoundary;
1814 }
1815 return result.join("");
1816
1817};
1818// vim: set shiftwidth=4 softtabstop=4:
1819
1820},{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(_dereq_,module,exports){
1821'use strict';
1822var support = _dereq_('./support');
1823var compressions = _dereq_('./compressions');
1824var nodeBuffer = _dereq_('./nodeBuffer');
1825/**
1826 * Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
1827 * @param {string} str the string to transform.
1828 * @return {String} the binary string.
1829 */
1830exports.string2binary = function(str) {
1831 var result = "";
1832 for (var i = 0; i < str.length; i++) {
1833 result += String.fromCharCode(str.charCodeAt(i) & 0xff);
1834 }
1835 return result;
1836};
1837exports.arrayBuffer2Blob = function(buffer) {
1838 exports.checkSupport("blob");
1839
1840 try {
1841 // Blob constructor
1842 return new Blob([buffer], {
1843 type: "application/zip"
1844 });
1845 }
1846 catch (e) {
1847
1848 try {
1849 // deprecated, browser only, old way
1850 var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
1851 var builder = new Builder();
1852 builder.append(buffer);
1853 return builder.getBlob('application/zip');
1854 }
1855 catch (e) {
1856
1857 // well, fuck ?!
1858 throw new Error("Bug : can't construct the Blob.");
1859 }
1860 }
1861
1862
1863};
1864/**
1865 * The identity function.
1866 * @param {Object} input the input.
1867 * @return {Object} the same input.
1868 */
1869function identity(input) {
1870 return input;
1871}
1872
1873/**
1874 * Fill in an array with a string.
1875 * @param {String} str the string to use.
1876 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
1877 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
1878 */
1879function stringToArrayLike(str, array) {
1880 for (var i = 0; i < str.length; ++i) {
1881 array[i] = str.charCodeAt(i) & 0xFF;
1882 }
1883 return array;
1884}
1885
1886/**
1887 * Transform an array-like object to a string.
1888 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
1889 * @return {String} the result.
1890 */
1891function arrayLikeToString(array) {
1892 // Performances notes :
1893 // --------------------
1894 // String.fromCharCode.apply(null, array) is the fastest, see
1895 // see http://jsperf.com/converting-a-uint8array-to-a-string/2
1896 // but the stack is limited (and we can get huge arrays !).
1897 //
1898 // result += String.fromCharCode(array[i]); generate too many strings !
1899 //
1900 // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
1901 var chunk = 65536;
1902 var result = [],
1903 len = array.length,
1904 type = exports.getTypeOf(array),
1905 k = 0,
1906 canUseApply = true;
1907 try {
1908 switch(type) {
1909 case "uint8array":
1910 String.fromCharCode.apply(null, new Uint8Array(0));
1911 break;
1912 case "nodebuffer":
1913 String.fromCharCode.apply(null, nodeBuffer(0));
1914 break;
1915 }
1916 } catch(e) {
1917 canUseApply = false;
1918 }
1919
1920 // no apply : slow and painful algorithm
1921 // default browser on android 4.*
1922 if (!canUseApply) {
1923 var resultStr = "";
1924 for(var i = 0; i < array.length;i++) {
1925 resultStr += String.fromCharCode(array[i]);
1926 }
1927 return resultStr;
1928 }
1929 while (k < len && chunk > 1) {
1930 try {
1931 if (type === "array" || type === "nodebuffer") {
1932 result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
1933 }
1934 else {
1935 result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
1936 }
1937 k += chunk;
1938 }
1939 catch (e) {
1940 chunk = Math.floor(chunk / 2);
1941 }
1942 }
1943 return result.join("");
1944}
1945
1946exports.applyFromCharCode = arrayLikeToString;
1947
1948
1949/**
1950 * Copy the data from an array-like to an other array-like.
1951 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
1952 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
1953 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
1954 */
1955function arrayLikeToArrayLike(arrayFrom, arrayTo) {
1956 for (var i = 0; i < arrayFrom.length; i++) {
1957 arrayTo[i] = arrayFrom[i];
1958 }
1959 return arrayTo;
1960}
1961
1962// a matrix containing functions to transform everything into everything.
1963var transform = {};
1964
1965// string to ?
1966transform["string"] = {
1967 "string": identity,
1968 "array": function(input) {
1969 return stringToArrayLike(input, new Array(input.length));
1970 },
1971 "arraybuffer": function(input) {
1972 return transform["string"]["uint8array"](input).buffer;
1973 },
1974 "uint8array": function(input) {
1975 return stringToArrayLike(input, new Uint8Array(input.length));
1976 },
1977 "nodebuffer": function(input) {
1978 return stringToArrayLike(input, nodeBuffer(input.length));
1979 }
1980};
1981
1982// array to ?
1983transform["array"] = {
1984 "string": arrayLikeToString,
1985 "array": identity,
1986 "arraybuffer": function(input) {
1987 return (new Uint8Array(input)).buffer;
1988 },
1989 "uint8array": function(input) {
1990 return new Uint8Array(input);
1991 },
1992 "nodebuffer": function(input) {
1993 return nodeBuffer(input);
1994 }
1995};
1996
1997// arraybuffer to ?
1998transform["arraybuffer"] = {
1999 "string": function(input) {
2000 return arrayLikeToString(new Uint8Array(input));
2001 },
2002 "array": function(input) {
2003 return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
2004 },
2005 "arraybuffer": identity,
2006 "uint8array": function(input) {
2007 return new Uint8Array(input);
2008 },
2009 "nodebuffer": function(input) {
2010 return nodeBuffer(new Uint8Array(input));
2011 }
2012};
2013
2014// uint8array to ?
2015transform["uint8array"] = {
2016 "string": arrayLikeToString,
2017 "array": function(input) {
2018 return arrayLikeToArrayLike(input, new Array(input.length));
2019 },
2020 "arraybuffer": function(input) {
2021 return input.buffer;
2022 },
2023 "uint8array": identity,
2024 "nodebuffer": function(input) {
2025 return nodeBuffer(input);
2026 }
2027};
2028
2029// nodebuffer to ?
2030transform["nodebuffer"] = {
2031 "string": arrayLikeToString,
2032 "array": function(input) {
2033 return arrayLikeToArrayLike(input, new Array(input.length));
2034 },
2035 "arraybuffer": function(input) {
2036 return transform["nodebuffer"]["uint8array"](input).buffer;
2037 },
2038 "uint8array": function(input) {
2039 return arrayLikeToArrayLike(input, new Uint8Array(input.length));
2040 },
2041 "nodebuffer": identity
2042};
2043
2044/**
2045 * Transform an input into any type.
2046 * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
2047 * If no output type is specified, the unmodified input will be returned.
2048 * @param {String} outputType the output type.
2049 * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
2050 * @throws {Error} an Error if the browser doesn't support the requested output type.
2051 */
2052exports.transformTo = function(outputType, input) {
2053 if (!input) {
2054 // undefined, null, etc
2055 // an empty string won't harm.
2056 input = "";
2057 }
2058 if (!outputType) {
2059 return input;
2060 }
2061 exports.checkSupport(outputType);
2062 var inputType = exports.getTypeOf(input);
2063 var result = transform[inputType][outputType](input);
2064 return result;
2065};
2066
2067/**
2068 * Return the type of the input.
2069 * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
2070 * @param {Object} input the input to identify.
2071 * @return {String} the (lowercase) type of the input.
2072 */
2073exports.getTypeOf = function(input) {
2074 if (typeof input === "string") {
2075 return "string";
2076 }
2077 if (Object.prototype.toString.call(input) === "[object Array]") {
2078 return "array";
2079 }
2080 if (support.nodebuffer && nodeBuffer.test(input)) {
2081 return "nodebuffer";
2082 }
2083 if (support.uint8array && input instanceof Uint8Array) {
2084 return "uint8array";
2085 }
2086 if (support.arraybuffer && input instanceof ArrayBuffer) {
2087 return "arraybuffer";
2088 }
2089};
2090
2091/**
2092 * Throw an exception if the type is not supported.
2093 * @param {String} type the type to check.
2094 * @throws {Error} an Error if the browser doesn't support the requested type.
2095 */
2096exports.checkSupport = function(type) {
2097 var supported = support[type.toLowerCase()];
2098 if (!supported) {
2099 throw new Error(type + " is not supported by this browser");
2100 }
2101};
2102exports.MAX_VALUE_16BITS = 65535;
2103exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
2104
2105/**
2106 * Prettify a string read as binary.
2107 * @param {string} str the string to prettify.
2108 * @return {string} a pretty string.
2109 */
2110exports.pretty = function(str) {
2111 var res = '',
2112 code, i;
2113 for (i = 0; i < (str || "").length; i++) {
2114 code = str.charCodeAt(i);
2115 res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
2116 }
2117 return res;
2118};
2119
2120/**
2121 * Find a compression registered in JSZip.
2122 * @param {string} compressionMethod the method magic to find.
2123 * @return {Object|null} the JSZip compression object, null if none found.
2124 */
2125exports.findCompression = function(compressionMethod) {
2126 for (var method in compressions) {
2127 if (!compressions.hasOwnProperty(method)) {
2128 continue;
2129 }
2130 if (compressions[method].magic === compressionMethod) {
2131 return compressions[method];
2132 }
2133 }
2134 return null;
2135};
2136/**
2137* Cross-window, cross-Node-context regular expression detection
2138* @param {Object} object Anything
2139* @return {Boolean} true if the object is a regular expression,
2140* false otherwise
2141*/
2142exports.isRegExp = function (object) {
2143 return Object.prototype.toString.call(object) === "[object RegExp]";
2144};
2145
2146
2147},{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(_dereq_,module,exports){
2148'use strict';
2149var StringReader = _dereq_('./stringReader');
2150var NodeBufferReader = _dereq_('./nodeBufferReader');
2151var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
2152var utils = _dereq_('./utils');
2153var sig = _dereq_('./signature');
2154var ZipEntry = _dereq_('./zipEntry');
2155var support = _dereq_('./support');
2156var jszipProto = _dereq_('./object');
2157// class ZipEntries {{{
2158/**
2159 * All the entries in the zip file.
2160 * @constructor
2161 * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
2162 * @param {Object} loadOptions Options for loading the stream.
2163 */
2164function ZipEntries(data, loadOptions) {
2165 this.files = [];
2166 this.loadOptions = loadOptions;
2167 if (data) {
2168 this.load(data);
2169 }
2170}
2171ZipEntries.prototype = {
2172 /**
2173 * Check that the reader is on the speficied signature.
2174 * @param {string} expectedSignature the expected signature.
2175 * @throws {Error} if it is an other signature.
2176 */
2177 checkSignature: function(expectedSignature) {
2178 var signature = this.reader.readString(4);
2179 if (signature !== expectedSignature) {
2180 throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
2181 }
2182 },
2183 /**
2184 * Read the end of the central directory.
2185 */
2186 readBlockEndOfCentral: function() {
2187 this.diskNumber = this.reader.readInt(2);
2188 this.diskWithCentralDirStart = this.reader.readInt(2);
2189 this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
2190 this.centralDirRecords = this.reader.readInt(2);
2191 this.centralDirSize = this.reader.readInt(4);
2192 this.centralDirOffset = this.reader.readInt(4);
2193
2194 this.zipCommentLength = this.reader.readInt(2);
2195 // warning : the encoding depends of the system locale
2196 // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
2197 // On a windows machine, this field is encoded with the localized windows code page.
2198 this.zipComment = this.reader.readString(this.zipCommentLength);
2199 // To get consistent behavior with the generation part, we will assume that
2200 // this is utf8 encoded.
2201 this.zipComment = jszipProto.utf8decode(this.zipComment);
2202 },
2203 /**
2204 * Read the end of the Zip 64 central directory.
2205 * Not merged with the method readEndOfCentral :
2206 * The end of central can coexist with its Zip64 brother,
2207 * I don't want to read the wrong number of bytes !
2208 */
2209 readBlockZip64EndOfCentral: function() {
2210 this.zip64EndOfCentralSize = this.reader.readInt(8);
2211 this.versionMadeBy = this.reader.readString(2);
2212 this.versionNeeded = this.reader.readInt(2);
2213 this.diskNumber = this.reader.readInt(4);
2214 this.diskWithCentralDirStart = this.reader.readInt(4);
2215 this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
2216 this.centralDirRecords = this.reader.readInt(8);
2217 this.centralDirSize = this.reader.readInt(8);
2218 this.centralDirOffset = this.reader.readInt(8);
2219
2220 this.zip64ExtensibleData = {};
2221 var extraDataSize = this.zip64EndOfCentralSize - 44,
2222 index = 0,
2223 extraFieldId,
2224 extraFieldLength,
2225 extraFieldValue;
2226 while (index < extraDataSize) {
2227 extraFieldId = this.reader.readInt(2);
2228 extraFieldLength = this.reader.readInt(4);
2229 extraFieldValue = this.reader.readString(extraFieldLength);
2230 this.zip64ExtensibleData[extraFieldId] = {
2231 id: extraFieldId,
2232 length: extraFieldLength,
2233 value: extraFieldValue
2234 };
2235 }
2236 },
2237 /**
2238 * Read the end of the Zip 64 central directory locator.
2239 */
2240 readBlockZip64EndOfCentralLocator: function() {
2241 this.diskWithZip64CentralDirStart = this.reader.readInt(4);
2242 this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
2243 this.disksCount = this.reader.readInt(4);
2244 if (this.disksCount > 1) {
2245 throw new Error("Multi-volumes zip are not supported");
2246 }
2247 },
2248 /**
2249 * Read the local files, based on the offset read in the central part.
2250 */
2251 readLocalFiles: function() {
2252 var i, file;
2253 for (i = 0; i < this.files.length; i++) {
2254 file = this.files[i];
2255 this.reader.setIndex(file.localHeaderOffset);
2256 this.checkSignature(sig.LOCAL_FILE_HEADER);
2257 file.readLocalPart(this.reader);
2258 file.handleUTF8();
2259 }
2260 },
2261 /**
2262 * Read the central directory.
2263 */
2264 readCentralDir: function() {
2265 var file;
2266
2267 this.reader.setIndex(this.centralDirOffset);
2268 while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) {
2269 file = new ZipEntry({
2270 zip64: this.zip64
2271 }, this.loadOptions);
2272 file.readCentralPart(this.reader);
2273 this.files.push(file);
2274 }
2275 },
2276 /**
2277 * Read the end of central directory.
2278 */
2279 readEndOfCentral: function() {
2280 var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
2281 if (offset === -1) {
2282 throw new Error("Corrupted zip : can't find end of central directory");
2283 }
2284 this.reader.setIndex(offset);
2285 this.checkSignature(sig.CENTRAL_DIRECTORY_END);
2286 this.readBlockEndOfCentral();
2287
2288
2289 /* extract from the zip spec :
2290 4) If one of the fields in the end of central directory
2291 record is too small to hold required data, the field
2292 should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
2293 ZIP64 format record should be created.
2294 5) The end of central directory record and the
2295 Zip64 end of central directory locator record must
2296 reside on the same disk when splitting or spanning
2297 an archive.
2298 */
2299 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) {
2300 this.zip64 = true;
2301
2302 /*
2303 Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
2304 the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
2305 all numbers as 64-bit double precision IEEE 754 floating point numbers.
2306 So, we have 53bits for integers and bitwise operations treat everything as 32bits.
2307 see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
2308 and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
2309 */
2310
2311 // should look for a zip64 EOCD locator
2312 offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
2313 if (offset === -1) {
2314 throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
2315 }
2316 this.reader.setIndex(offset);
2317 this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
2318 this.readBlockZip64EndOfCentralLocator();
2319
2320 // now the zip64 EOCD record
2321 this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
2322 this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
2323 this.readBlockZip64EndOfCentral();
2324 }
2325 },
2326 prepareReader: function(data) {
2327 var type = utils.getTypeOf(data);
2328 if (type === "string" && !support.uint8array) {
2329 this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString);
2330 }
2331 else if (type === "nodebuffer") {
2332 this.reader = new NodeBufferReader(data);
2333 }
2334 else {
2335 this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data));
2336 }
2337 },
2338 /**
2339 * Read a zip file and create ZipEntries.
2340 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
2341 */
2342 load: function(data) {
2343 this.prepareReader(data);
2344 this.readEndOfCentral();
2345 this.readCentralDir();
2346 this.readLocalFiles();
2347 }
2348};
2349// }}} end of ZipEntries
2350module.exports = ZipEntries;
2351
2352},{"./nodeBufferReader":12,"./object":13,"./signature":14,"./stringReader":15,"./support":17,"./uint8ArrayReader":18,"./utils":21,"./zipEntry":23}],23:[function(_dereq_,module,exports){
2353'use strict';
2354var StringReader = _dereq_('./stringReader');
2355var utils = _dereq_('./utils');
2356var CompressedObject = _dereq_('./compressedObject');
2357var jszipProto = _dereq_('./object');
2358// class ZipEntry {{{
2359/**
2360 * An entry in the zip file.
2361 * @constructor
2362 * @param {Object} options Options of the current file.
2363 * @param {Object} loadOptions Options for loading the stream.
2364 */
2365function ZipEntry(options, loadOptions) {
2366 this.options = options;
2367 this.loadOptions = loadOptions;
2368}
2369ZipEntry.prototype = {
2370 /**
2371 * say if the file is encrypted.
2372 * @return {boolean} true if the file is encrypted, false otherwise.
2373 */
2374 isEncrypted: function() {
2375 // bit 1 is set
2376 return (this.bitFlag & 0x0001) === 0x0001;
2377 },
2378 /**
2379 * say if the file has utf-8 filename/comment.
2380 * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
2381 */
2382 useUTF8: function() {
2383 // bit 11 is set
2384 return (this.bitFlag & 0x0800) === 0x0800;
2385 },
2386 /**
2387 * Prepare the function used to generate the compressed content from this ZipFile.
2388 * @param {DataReader} reader the reader to use.
2389 * @param {number} from the offset from where we should read the data.
2390 * @param {number} length the length of the data to read.
2391 * @return {Function} the callback to get the compressed content (the type depends of the DataReader class).
2392 */
2393 prepareCompressedContent: function(reader, from, length) {
2394 return function() {
2395 var previousIndex = reader.index;
2396 reader.setIndex(from);
2397 var compressedFileData = reader.readData(length);
2398 reader.setIndex(previousIndex);
2399
2400 return compressedFileData;
2401 };
2402 },
2403 /**
2404 * Prepare the function used to generate the uncompressed content from this ZipFile.
2405 * @param {DataReader} reader the reader to use.
2406 * @param {number} from the offset from where we should read the data.
2407 * @param {number} length the length of the data to read.
2408 * @param {JSZip.compression} compression the compression used on this file.
2409 * @param {number} uncompressedSize the uncompressed size to expect.
2410 * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).
2411 */
2412 prepareContent: function(reader, from, length, compression, uncompressedSize) {
2413 return function() {
2414
2415 var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
2416 var uncompressedFileData = compression.uncompress(compressedFileData);
2417
2418 if (uncompressedFileData.length !== uncompressedSize) {
2419 throw new Error("Bug : uncompressed data size mismatch");
2420 }
2421
2422 return uncompressedFileData;
2423 };
2424 },
2425 /**
2426 * Read the local part of a zip file and add the info in this object.
2427 * @param {DataReader} reader the reader to use.
2428 */
2429 readLocalPart: function(reader) {
2430 var compression, localExtraFieldsLength;
2431
2432 // we already know everything from the central dir !
2433 // If the central dir data are false, we are doomed.
2434 // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
2435 // The less data we get here, the more reliable this should be.
2436 // Let's skip the whole header and dash to the data !
2437 reader.skip(22);
2438 // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
2439 // Strangely, the filename here is OK.
2440 // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
2441 // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
2442 // Search "unzip mismatching "local" filename continuing with "central" filename version" on
2443 // the internet.
2444 //
2445 // I think I see the logic here : the central directory is used to display
2446 // content and the local directory is used to extract the files. Mixing / and \
2447 // may be used to display \ to windows users and use / when extracting the files.
2448 // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
2449 this.fileNameLength = reader.readInt(2);
2450 localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
2451 this.fileName = reader.readString(this.fileNameLength);
2452 reader.skip(localExtraFieldsLength);
2453
2454 if (this.compressedSize == -1 || this.uncompressedSize == -1) {
2455 throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
2456 }
2457
2458 compression = utils.findCompression(this.compressionMethod);
2459 if (compression === null) { // no compression found
2460 throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")");
2461 }
2462 this.decompressed = new CompressedObject();
2463 this.decompressed.compressedSize = this.compressedSize;
2464 this.decompressed.uncompressedSize = this.uncompressedSize;
2465 this.decompressed.crc32 = this.crc32;
2466 this.decompressed.compressionMethod = this.compressionMethod;
2467 this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
2468 this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
2469
2470 // we need to compute the crc32...
2471 if (this.loadOptions.checkCRC32) {
2472 this.decompressed = utils.transformTo("string", this.decompressed.getContent());
2473 if (jszipProto.crc32(this.decompressed) !== this.crc32) {
2474 throw new Error("Corrupted zip : CRC32 mismatch");
2475 }
2476 }
2477 },
2478
2479 /**
2480 * Read the central part of a zip file and add the info in this object.
2481 * @param {DataReader} reader the reader to use.
2482 */
2483 readCentralPart: function(reader) {
2484 this.versionMadeBy = reader.readString(2);
2485 this.versionNeeded = reader.readInt(2);
2486 this.bitFlag = reader.readInt(2);
2487 this.compressionMethod = reader.readString(2);
2488 this.date = reader.readDate();
2489 this.crc32 = reader.readInt(4);
2490 this.compressedSize = reader.readInt(4);
2491 this.uncompressedSize = reader.readInt(4);
2492 this.fileNameLength = reader.readInt(2);
2493 this.extraFieldsLength = reader.readInt(2);
2494 this.fileCommentLength = reader.readInt(2);
2495 this.diskNumberStart = reader.readInt(2);
2496 this.internalFileAttributes = reader.readInt(2);
2497 this.externalFileAttributes = reader.readInt(4);
2498 this.localHeaderOffset = reader.readInt(4);
2499
2500 if (this.isEncrypted()) {
2501 throw new Error("Encrypted zip are not supported");
2502 }
2503
2504 this.fileName = reader.readString(this.fileNameLength);
2505 this.readExtraFields(reader);
2506 this.parseZIP64ExtraField(reader);
2507 this.fileComment = reader.readString(this.fileCommentLength);
2508
2509 // warning, this is true only for zip with madeBy == DOS (plateform dependent feature)
2510 this.dir = this.externalFileAttributes & 0x00000010 ? true : false;
2511 },
2512 /**
2513 * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
2514 * @param {DataReader} reader the reader to use.
2515 */
2516 parseZIP64ExtraField: function(reader) {
2517
2518 if (!this.extraFields[0x0001]) {
2519 return;
2520 }
2521
2522 // should be something, preparing the extra reader
2523 var extraReader = new StringReader(this.extraFields[0x0001].value);
2524
2525 // I really hope that these 64bits integer can fit in 32 bits integer, because js
2526 // won't let us have more.
2527 if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
2528 this.uncompressedSize = extraReader.readInt(8);
2529 }
2530 if (this.compressedSize === utils.MAX_VALUE_32BITS) {
2531 this.compressedSize = extraReader.readInt(8);
2532 }
2533 if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
2534 this.localHeaderOffset = extraReader.readInt(8);
2535 }
2536 if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
2537 this.diskNumberStart = extraReader.readInt(4);
2538 }
2539 },
2540 /**
2541 * Read the central part of a zip file and add the info in this object.
2542 * @param {DataReader} reader the reader to use.
2543 */
2544 readExtraFields: function(reader) {
2545 var start = reader.index,
2546 extraFieldId,
2547 extraFieldLength,
2548 extraFieldValue;
2549
2550 this.extraFields = this.extraFields || {};
2551
2552 while (reader.index < start + this.extraFieldsLength) {
2553 extraFieldId = reader.readInt(2);
2554 extraFieldLength = reader.readInt(2);
2555 extraFieldValue = reader.readString(extraFieldLength);
2556
2557 this.extraFields[extraFieldId] = {
2558 id: extraFieldId,
2559 length: extraFieldLength,
2560 value: extraFieldValue
2561 };
2562 }
2563 },
2564 /**
2565 * Apply an UTF8 transformation if needed.
2566 */
2567 handleUTF8: function() {
2568 if (this.useUTF8()) {
2569 this.fileName = jszipProto.utf8decode(this.fileName);
2570 this.fileComment = jszipProto.utf8decode(this.fileComment);
2571 } else {
2572 var upath = this.findExtraFieldUnicodePath();
2573 if (upath !== null) {
2574 this.fileName = upath;
2575 }
2576 var ucomment = this.findExtraFieldUnicodeComment();
2577 if (ucomment !== null) {
2578 this.fileComment = ucomment;
2579 }
2580 }
2581 },
2582
2583 /**
2584 * Find the unicode path declared in the extra field, if any.
2585 * @return {String} the unicode path, null otherwise.
2586 */
2587 findExtraFieldUnicodePath: function() {
2588 var upathField = this.extraFields[0x7075];
2589 if (upathField) {
2590 var extraReader = new StringReader(upathField.value);
2591
2592 // wrong version
2593 if (extraReader.readInt(1) !== 1) {
2594 return null;
2595 }
2596
2597 // the crc of the filename changed, this field is out of date.
2598 if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
2599 return null;
2600 }
2601
2602 return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
2603 }
2604 return null;
2605 },
2606
2607 /**
2608 * Find the unicode comment declared in the extra field, if any.
2609 * @return {String} the unicode comment, null otherwise.
2610 */
2611 findExtraFieldUnicodeComment: function() {
2612 var ucommentField = this.extraFields[0x6375];
2613 if (ucommentField) {
2614 var extraReader = new StringReader(ucommentField.value);
2615
2616 // wrong version
2617 if (extraReader.readInt(1) !== 1) {
2618 return null;
2619 }
2620
2621 // the crc of the comment changed, this field is out of date.
2622 if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
2623 return null;
2624 }
2625
2626 return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
2627 }
2628 return null;
2629 }
2630};
2631module.exports = ZipEntry;
2632
2633},{"./compressedObject":2,"./object":13,"./stringReader":15,"./utils":21}],24:[function(_dereq_,module,exports){
2634// Top level file is just a mixin of submodules & constants
2635'use strict';
2636
2637var assign = _dereq_('./lib/utils/common').assign;
2638
2639var deflate = _dereq_('./lib/deflate');
2640var inflate = _dereq_('./lib/inflate');
2641var constants = _dereq_('./lib/zlib/constants');
2642
2643var pako = {};
2644
2645assign(pako, deflate, inflate, constants);
2646
2647module.exports = pako;
2648},{"./lib/deflate":25,"./lib/inflate":26,"./lib/utils/common":27,"./lib/zlib/constants":30}],25:[function(_dereq_,module,exports){
2649'use strict';
2650
2651
2652var zlib_deflate = _dereq_('./zlib/deflate.js');
2653var utils = _dereq_('./utils/common');
2654var strings = _dereq_('./utils/strings');
2655var msg = _dereq_('./zlib/messages');
2656var zstream = _dereq_('./zlib/zstream');
2657
2658
2659/* Public constants ==========================================================*/
2660/* ===========================================================================*/
2661
2662var Z_NO_FLUSH = 0;
2663var Z_FINISH = 4;
2664
2665var Z_OK = 0;
2666var Z_STREAM_END = 1;
2667
2668var Z_DEFAULT_COMPRESSION = -1;
2669
2670var Z_DEFAULT_STRATEGY = 0;
2671
2672var Z_DEFLATED = 8;
2673
2674/* ===========================================================================*/
2675
2676
2677/**
2678 * class Deflate
2679 *
2680 * Generic JS-style wrapper for zlib calls. If you don't need
2681 * streaming behaviour - use more simple functions: [[deflate]],
2682 * [[deflateRaw]] and [[gzip]].
2683 **/
2684
2685/* internal
2686 * Deflate.chunks -> Array
2687 *
2688 * Chunks of output data, if [[Deflate#onData]] not overriden.
2689 **/
2690
2691/**
2692 * Deflate.result -> Uint8Array|Array
2693 *
2694 * Compressed result, generated by default [[Deflate#onData]]
2695 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
2696 * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
2697 **/
2698
2699/**
2700 * Deflate.err -> Number
2701 *
2702 * Error code after deflate finished. 0 (Z_OK) on success.
2703 * You will not need it in real life, because deflate errors
2704 * are possible only on wrong options or bad `onData` / `onEnd`
2705 * custom handlers.
2706 **/
2707
2708/**
2709 * Deflate.msg -> String
2710 *
2711 * Error message, if [[Deflate.err]] != 0
2712 **/
2713
2714
2715/**
2716 * new Deflate(options)
2717 * - options (Object): zlib deflate options.
2718 *
2719 * Creates new deflator instance with specified params. Throws exception
2720 * on bad params. Supported options:
2721 *
2722 * - `level`
2723 * - `windowBits`
2724 * - `memLevel`
2725 * - `strategy`
2726 *
2727 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
2728 * for more information on these.
2729 *
2730 * Additional options, for internal needs:
2731 *
2732 * - `chunkSize` - size of generated data chunks (16K by default)
2733 * - `raw` (Boolean) - do raw deflate
2734 * - `gzip` (Boolean) - create gzip wrapper
2735 * - `to` (String) - if equal to 'string', then result will be "binary string"
2736 * (each char code [0..255])
2737 * - `header` (Object) - custom header for gzip
2738 * - `text` (Boolean) - true if compressed data believed to be text
2739 * - `time` (Number) - modification time, unix timestamp
2740 * - `os` (Number) - operation system code
2741 * - `extra` (Array) - array of bytes with extra data (max 65536)
2742 * - `name` (String) - file name (binary string)
2743 * - `comment` (String) - comment (binary string)
2744 * - `hcrc` (Boolean) - true if header crc should be added
2745 *
2746 * ##### Example:
2747 *
2748 * ```javascript
2749 * var pako = require('pako')
2750 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
2751 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
2752 *
2753 * var deflate = new pako.Deflate({ level: 3});
2754 *
2755 * deflate.push(chunk1, false);
2756 * deflate.push(chunk2, true); // true -> last chunk
2757 *
2758 * if (deflate.err) { throw new Error(deflate.err); }
2759 *
2760 * console.log(deflate.result);
2761 * ```
2762 **/
2763var Deflate = function(options) {
2764
2765 this.options = utils.assign({
2766 level: Z_DEFAULT_COMPRESSION,
2767 method: Z_DEFLATED,
2768 chunkSize: 16384,
2769 windowBits: 15,
2770 memLevel: 8,
2771 strategy: Z_DEFAULT_STRATEGY,
2772 to: ''
2773 }, options || {});
2774
2775 var opt = this.options;
2776
2777 if (opt.raw && (opt.windowBits > 0)) {
2778 opt.windowBits = -opt.windowBits;
2779 }
2780
2781 else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
2782 opt.windowBits += 16;
2783 }
2784
2785 this.err = 0; // error code, if happens (0 = Z_OK)
2786 this.msg = ''; // error message
2787 this.ended = false; // used to avoid multiple onEnd() calls
2788 this.chunks = []; // chunks of compressed data
2789
2790 this.strm = new zstream();
2791 this.strm.avail_out = 0;
2792
2793 var status = zlib_deflate.deflateInit2(
2794 this.strm,
2795 opt.level,
2796 opt.method,
2797 opt.windowBits,
2798 opt.memLevel,
2799 opt.strategy
2800 );
2801
2802 if (status !== Z_OK) {
2803 throw new Error(msg[status]);
2804 }
2805
2806 if (opt.header) {
2807 zlib_deflate.deflateSetHeader(this.strm, opt.header);
2808 }
2809};
2810
2811/**
2812 * Deflate#push(data[, mode]) -> Boolean
2813 * - data (Uint8Array|Array|String): input data. Strings will be converted to
2814 * utf8 byte sequence.
2815 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
2816 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
2817 *
2818 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
2819 * new compressed chunks. Returns `true` on success. The last data block must have
2820 * mode Z_FINISH (or `true`). That flush internal pending buffers and call
2821 * [[Deflate#onEnd]].
2822 *
2823 * On fail call [[Deflate#onEnd]] with error code and return false.
2824 *
2825 * We strongly recommend to use `Uint8Array` on input for best speed (output
2826 * array format is detected automatically). Also, don't skip last param and always
2827 * use the same type in your code (boolean or number). That will improve JS speed.
2828 *
2829 * For regular `Array`-s make sure all elements are [0..255].
2830 *
2831 * ##### Example
2832 *
2833 * ```javascript
2834 * push(chunk, false); // push one of data chunks
2835 * ...
2836 * push(chunk, true); // push last chunk
2837 * ```
2838 **/
2839Deflate.prototype.push = function(data, mode) {
2840 var strm = this.strm;
2841 var chunkSize = this.options.chunkSize;
2842 var status, _mode;
2843
2844 if (this.ended) { return false; }
2845
2846 _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
2847
2848 // Convert data if needed
2849 if (typeof data === 'string') {
2850 // If we need to compress text, change encoding to utf8.
2851 strm.input = strings.string2buf(data);
2852 } else {
2853 strm.input = data;
2854 }
2855
2856 strm.next_in = 0;
2857 strm.avail_in = strm.input.length;
2858
2859 do {
2860 if (strm.avail_out === 0) {
2861 strm.output = new utils.Buf8(chunkSize);
2862 strm.next_out = 0;
2863 strm.avail_out = chunkSize;
2864 }
2865 status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
2866
2867 if (status !== Z_STREAM_END && status !== Z_OK) {
2868 this.onEnd(status);
2869 this.ended = true;
2870 return false;
2871 }
2872 if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
2873 if (this.options.to === 'string') {
2874 this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
2875 } else {
2876 this.onData(utils.shrinkBuf(strm.output, strm.next_out));
2877 }
2878 }
2879 } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
2880
2881 // Finalize on the last chunk.
2882 if (_mode === Z_FINISH) {
2883 status = zlib_deflate.deflateEnd(this.strm);
2884 this.onEnd(status);
2885 this.ended = true;
2886 return status === Z_OK;
2887 }
2888
2889 return true;
2890};
2891
2892
2893/**
2894 * Deflate#onData(chunk) -> Void
2895 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
2896 * on js engine support. When string output requested, each chunk
2897 * will be string.
2898 *
2899 * By default, stores data blocks in `chunks[]` property and glue
2900 * those in `onEnd`. Override this handler, if you need another behaviour.
2901 **/
2902Deflate.prototype.onData = function(chunk) {
2903 this.chunks.push(chunk);
2904};
2905
2906
2907/**
2908 * Deflate#onEnd(status) -> Void
2909 * - status (Number): deflate status. 0 (Z_OK) on success,
2910 * other if not.
2911 *
2912 * Called once after you tell deflate that input stream complete
2913 * or error happenned. By default - join collected chunks,
2914 * free memory and fill `results` / `err` properties.
2915 **/
2916Deflate.prototype.onEnd = function(status) {
2917 // On success - join
2918 if (status === Z_OK) {
2919 if (this.options.to === 'string') {
2920 this.result = this.chunks.join('');
2921 } else {
2922 this.result = utils.flattenChunks(this.chunks);
2923 }
2924 }
2925 this.chunks = [];
2926 this.err = status;
2927 this.msg = this.strm.msg;
2928};
2929
2930
2931/**
2932 * deflate(data[, options]) -> Uint8Array|Array|String
2933 * - data (Uint8Array|Array|String): input data to compress.
2934 * - options (Object): zlib deflate options.
2935 *
2936 * Compress `data` with deflate alrorythm and `options`.
2937 *
2938 * Supported options are:
2939 *
2940 * - level
2941 * - windowBits
2942 * - memLevel
2943 * - strategy
2944 *
2945 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
2946 * for more information on these.
2947 *
2948 * Sugar (options):
2949 *
2950 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
2951 * negative windowBits implicitly.
2952 * - `to` (String) - if equal to 'string', then result will be "binary string"
2953 * (each char code [0..255])
2954 *
2955 * ##### Example:
2956 *
2957 * ```javascript
2958 * var pako = require('pako')
2959 * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
2960 *
2961 * console.log(pako.deflate(data));
2962 * ```
2963 **/
2964function deflate(input, options) {
2965 var deflator = new Deflate(options);
2966
2967 deflator.push(input, true);
2968
2969 // That will never happens, if you don't cheat with options :)
2970 if (deflator.err) { throw deflator.msg; }
2971
2972 return deflator.result;
2973}
2974
2975
2976/**
2977 * deflateRaw(data[, options]) -> Uint8Array|Array|String
2978 * - data (Uint8Array|Array|String): input data to compress.
2979 * - options (Object): zlib deflate options.
2980 *
2981 * The same as [[deflate]], but creates raw data, without wrapper
2982 * (header and adler32 crc).
2983 **/
2984function deflateRaw(input, options) {
2985 options = options || {};
2986 options.raw = true;
2987 return deflate(input, options);
2988}
2989
2990
2991/**
2992 * gzip(data[, options]) -> Uint8Array|Array|String
2993 * - data (Uint8Array|Array|String): input data to compress.
2994 * - options (Object): zlib deflate options.
2995 *
2996 * The same as [[deflate]], but create gzip wrapper instead of
2997 * deflate one.
2998 **/
2999function gzip(input, options) {
3000 options = options || {};
3001 options.gzip = true;
3002 return deflate(input, options);
3003}
3004
3005
3006exports.Deflate = Deflate;
3007exports.deflate = deflate;
3008exports.deflateRaw = deflateRaw;
3009exports.gzip = gzip;
3010},{"./utils/common":27,"./utils/strings":28,"./zlib/deflate.js":32,"./zlib/messages":37,"./zlib/zstream":39}],26:[function(_dereq_,module,exports){
3011'use strict';
3012
3013
3014var zlib_inflate = _dereq_('./zlib/inflate.js');
3015var utils = _dereq_('./utils/common');
3016var strings = _dereq_('./utils/strings');
3017var c = _dereq_('./zlib/constants');
3018var msg = _dereq_('./zlib/messages');
3019var zstream = _dereq_('./zlib/zstream');
3020var gzheader = _dereq_('./zlib/gzheader');
3021
3022
3023/**
3024 * class Inflate
3025 *
3026 * Generic JS-style wrapper for zlib calls. If you don't need
3027 * streaming behaviour - use more simple functions: [[inflate]]
3028 * and [[inflateRaw]].
3029 **/
3030
3031/* internal
3032 * inflate.chunks -> Array
3033 *
3034 * Chunks of output data, if [[Inflate#onData]] not overriden.
3035 **/
3036
3037/**
3038 * Inflate.result -> Uint8Array|Array|String
3039 *
3040 * Uncompressed result, generated by default [[Inflate#onData]]
3041 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
3042 * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
3043 **/
3044
3045/**
3046 * Inflate.err -> Number
3047 *
3048 * Error code after inflate finished. 0 (Z_OK) on success.
3049 * Should be checked if broken data possible.
3050 **/
3051
3052/**
3053 * Inflate.msg -> String
3054 *
3055 * Error message, if [[Inflate.err]] != 0
3056 **/
3057
3058
3059/**
3060 * new Inflate(options)
3061 * - options (Object): zlib inflate options.
3062 *
3063 * Creates new inflator instance with specified params. Throws exception
3064 * on bad params. Supported options:
3065 *
3066 * - `windowBits`
3067 *
3068 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
3069 * for more information on these.
3070 *
3071 * Additional options, for internal needs:
3072 *
3073 * - `chunkSize` - size of generated data chunks (16K by default)
3074 * - `raw` (Boolean) - do raw inflate
3075 * - `to` (String) - if equal to 'string', then result will be converted
3076 * from utf8 to utf16 (javascript) string. When string output requested,
3077 * chunk length can differ from `chunkSize`, depending on content.
3078 *
3079 * By default, when no options set, autodetect deflate/gzip data format via
3080 * wrapper header.
3081 *
3082 * ##### Example:
3083 *
3084 * ```javascript
3085 * var pako = require('pako')
3086 * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
3087 * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
3088 *
3089 * var inflate = new pako.Inflate({ level: 3});
3090 *
3091 * inflate.push(chunk1, false);
3092 * inflate.push(chunk2, true); // true -> last chunk
3093 *
3094 * if (inflate.err) { throw new Error(inflate.err); }
3095 *
3096 * console.log(inflate.result);
3097 * ```
3098 **/
3099var Inflate = function(options) {
3100
3101 this.options = utils.assign({
3102 chunkSize: 16384,
3103 windowBits: 0,
3104 to: ''
3105 }, options || {});
3106
3107 var opt = this.options;
3108
3109 // Force window size for `raw` data, if not set directly,
3110 // because we have no header for autodetect.
3111 if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
3112 opt.windowBits = -opt.windowBits;
3113 if (opt.windowBits === 0) { opt.windowBits = -15; }
3114 }
3115
3116 // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
3117 if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
3118 !(options && options.windowBits)) {
3119 opt.windowBits += 32;
3120 }
3121
3122 // Gzip header has no info about windows size, we can do autodetect only
3123 // for deflate. So, if window size not set, force it to max when gzip possible
3124 if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
3125 // bit 3 (16) -> gzipped data
3126 // bit 4 (32) -> autodetect gzip/deflate
3127 if ((opt.windowBits & 15) === 0) {
3128 opt.windowBits |= 15;
3129 }
3130 }
3131
3132 this.err = 0; // error code, if happens (0 = Z_OK)
3133 this.msg = ''; // error message
3134 this.ended = false; // used to avoid multiple onEnd() calls
3135 this.chunks = []; // chunks of compressed data
3136
3137 this.strm = new zstream();
3138 this.strm.avail_out = 0;
3139
3140 var status = zlib_inflate.inflateInit2(
3141 this.strm,
3142 opt.windowBits
3143 );
3144
3145 if (status !== c.Z_OK) {
3146 throw new Error(msg[status]);
3147 }
3148
3149 this.header = new gzheader();
3150
3151 zlib_inflate.inflateGetHeader(this.strm, this.header);
3152};
3153
3154/**
3155 * Inflate#push(data[, mode]) -> Boolean
3156 * - data (Uint8Array|Array|String): input data
3157 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
3158 * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
3159 *
3160 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
3161 * new output chunks. Returns `true` on success. The last data block must have
3162 * mode Z_FINISH (or `true`). That flush internal pending buffers and call
3163 * [[Inflate#onEnd]].
3164 *
3165 * On fail call [[Inflate#onEnd]] with error code and return false.
3166 *
3167 * We strongly recommend to use `Uint8Array` on input for best speed (output
3168 * format is detected automatically). Also, don't skip last param and always
3169 * use the same type in your code (boolean or number). That will improve JS speed.
3170 *
3171 * For regular `Array`-s make sure all elements are [0..255].
3172 *
3173 * ##### Example
3174 *
3175 * ```javascript
3176 * push(chunk, false); // push one of data chunks
3177 * ...
3178 * push(chunk, true); // push last chunk
3179 * ```
3180 **/
3181Inflate.prototype.push = function(data, mode) {
3182 var strm = this.strm;
3183 var chunkSize = this.options.chunkSize;
3184 var status, _mode;
3185 var next_out_utf8, tail, utf8str;
3186
3187 if (this.ended) { return false; }
3188 _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
3189
3190 // Convert data if needed
3191 if (typeof data === 'string') {
3192 // Only binary strings can be decompressed on practice
3193 strm.input = strings.binstring2buf(data);
3194 } else {
3195 strm.input = data;
3196 }
3197
3198 strm.next_in = 0;
3199 strm.avail_in = strm.input.length;
3200
3201 do {
3202 if (strm.avail_out === 0) {
3203 strm.output = new utils.Buf8(chunkSize);
3204 strm.next_out = 0;
3205 strm.avail_out = chunkSize;
3206 }
3207
3208 status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
3209
3210 if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
3211 this.onEnd(status);
3212 this.ended = true;
3213 return false;
3214 }
3215
3216 if (strm.next_out) {
3217 if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
3218
3219 if (this.options.to === 'string') {
3220
3221 next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
3222
3223 tail = strm.next_out - next_out_utf8;
3224 utf8str = strings.buf2string(strm.output, next_out_utf8);
3225
3226 // move tail
3227 strm.next_out = tail;
3228 strm.avail_out = chunkSize - tail;
3229 if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
3230
3231 this.onData(utf8str);
3232
3233 } else {
3234 this.onData(utils.shrinkBuf(strm.output, strm.next_out));
3235 }
3236 }
3237 }
3238 } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
3239
3240 if (status === c.Z_STREAM_END) {
3241 _mode = c.Z_FINISH;
3242 }
3243 // Finalize on the last chunk.
3244 if (_mode === c.Z_FINISH) {
3245 status = zlib_inflate.inflateEnd(this.strm);
3246 this.onEnd(status);
3247 this.ended = true;
3248 return status === c.Z_OK;
3249 }
3250
3251 return true;
3252};
3253
3254
3255/**
3256 * Inflate#onData(chunk) -> Void
3257 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
3258 * on js engine support. When string output requested, each chunk
3259 * will be string.
3260 *
3261 * By default, stores data blocks in `chunks[]` property and glue
3262 * those in `onEnd`. Override this handler, if you need another behaviour.
3263 **/
3264Inflate.prototype.onData = function(chunk) {
3265 this.chunks.push(chunk);
3266};
3267
3268
3269/**
3270 * Inflate#onEnd(status) -> Void
3271 * - status (Number): inflate status. 0 (Z_OK) on success,
3272 * other if not.
3273 *
3274 * Called once after you tell inflate that input stream complete
3275 * or error happenned. By default - join collected chunks,
3276 * free memory and fill `results` / `err` properties.
3277 **/
3278Inflate.prototype.onEnd = function(status) {
3279 // On success - join
3280 if (status === c.Z_OK) {
3281 if (this.options.to === 'string') {
3282 // Glue & convert here, until we teach pako to send
3283 // utf8 alligned strings to onData
3284 this.result = this.chunks.join('');
3285 } else {
3286 this.result = utils.flattenChunks(this.chunks);
3287 }
3288 }
3289 this.chunks = [];
3290 this.err = status;
3291 this.msg = this.strm.msg;
3292};
3293
3294
3295/**
3296 * inflate(data[, options]) -> Uint8Array|Array|String
3297 * - data (Uint8Array|Array|String): input data to decompress.
3298 * - options (Object): zlib inflate options.
3299 *
3300 * Decompress `data` with inflate/ungzip and `options`. Autodetect
3301 * format via wrapper header by default. That's why we don't provide
3302 * separate `ungzip` method.
3303 *
3304 * Supported options are:
3305 *
3306 * - windowBits
3307 *
3308 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
3309 * for more information.
3310 *
3311 * Sugar (options):
3312 *
3313 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
3314 * negative windowBits implicitly.
3315 * - `to` (String) - if equal to 'string', then result will be converted
3316 * from utf8 to utf16 (javascript) string. When string output requested,
3317 * chunk length can differ from `chunkSize`, depending on content.
3318 *
3319 *
3320 * ##### Example:
3321 *
3322 * ```javascript
3323 * var pako = require('pako')
3324 * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
3325 * , output;
3326 *
3327 * try {
3328 * output = pako.inflate(input);
3329 * } catch (err)
3330 * console.log(err);
3331 * }
3332 * ```
3333 **/
3334function inflate(input, options) {
3335 var inflator = new Inflate(options);
3336
3337 inflator.push(input, true);
3338
3339 // That will never happens, if you don't cheat with options :)
3340 if (inflator.err) { throw inflator.msg; }
3341
3342 return inflator.result;
3343}
3344
3345
3346/**
3347 * inflateRaw(data[, options]) -> Uint8Array|Array|String
3348 * - data (Uint8Array|Array|String): input data to decompress.
3349 * - options (Object): zlib inflate options.
3350 *
3351 * The same as [[inflate]], but creates raw data, without wrapper
3352 * (header and adler32 crc).
3353 **/
3354function inflateRaw(input, options) {
3355 options = options || {};
3356 options.raw = true;
3357 return inflate(input, options);
3358}
3359
3360
3361/**
3362 * ungzip(data[, options]) -> Uint8Array|Array|String
3363 * - data (Uint8Array|Array|String): input data to decompress.
3364 * - options (Object): zlib inflate options.
3365 *
3366 * Just shortcut to [[inflate]], because it autodetects format
3367 * by header.content. Done for convenience.
3368 **/
3369
3370
3371exports.Inflate = Inflate;
3372exports.inflate = inflate;
3373exports.inflateRaw = inflateRaw;
3374exports.ungzip = inflate;
3375
3376},{"./utils/common":27,"./utils/strings":28,"./zlib/constants":30,"./zlib/gzheader":33,"./zlib/inflate.js":35,"./zlib/messages":37,"./zlib/zstream":39}],27:[function(_dereq_,module,exports){
3377'use strict';
3378
3379
3380var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
3381 (typeof Uint16Array !== 'undefined') &&
3382 (typeof Int32Array !== 'undefined');
3383
3384
3385exports.assign = function (obj /*from1, from2, from3, ...*/) {
3386 var sources = Array.prototype.slice.call(arguments, 1);
3387 while (sources.length) {
3388 var source = sources.shift();
3389 if (!source) { continue; }
3390
3391 if (typeof(source) !== 'object') {
3392 throw new TypeError(source + 'must be non-object');
3393 }
3394
3395 for (var p in source) {
3396 if (source.hasOwnProperty(p)) {
3397 obj[p] = source[p];
3398 }
3399 }
3400 }
3401
3402 return obj;
3403};
3404
3405
3406// reduce buffer size, avoiding mem copy
3407exports.shrinkBuf = function (buf, size) {
3408 if (buf.length === size) { return buf; }
3409 if (buf.subarray) { return buf.subarray(0, size); }
3410 buf.length = size;
3411 return buf;
3412};
3413
3414
3415var fnTyped = {
3416 arraySet: function (dest, src, src_offs, len, dest_offs) {
3417 if (src.subarray && dest.subarray) {
3418 dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
3419 return;
3420 }
3421 // Fallback to ordinary array
3422 for(var i=0; i<len; i++) {
3423 dest[dest_offs + i] = src[src_offs + i];
3424 }
3425 },
3426 // Join array of chunks to single array.
3427 flattenChunks: function(chunks) {
3428 var i, l, len, pos, chunk, result;
3429
3430 // calculate data length
3431 len = 0;
3432 for (i=0, l=chunks.length; i<l; i++) {
3433 len += chunks[i].length;
3434 }
3435
3436 // join chunks
3437 result = new Uint8Array(len);
3438 pos = 0;
3439 for (i=0, l=chunks.length; i<l; i++) {
3440 chunk = chunks[i];
3441 result.set(chunk, pos);
3442 pos += chunk.length;
3443 }
3444
3445 return result;
3446 }
3447};
3448
3449var fnUntyped = {
3450 arraySet: function (dest, src, src_offs, len, dest_offs) {
3451 for(var i=0; i<len; i++) {
3452 dest[dest_offs + i] = src[src_offs + i];
3453 }
3454 },
3455 // Join array of chunks to single array.
3456 flattenChunks: function(chunks) {
3457 return [].concat.apply([], chunks);
3458 }
3459};
3460
3461
3462// Enable/Disable typed arrays use, for testing
3463//
3464exports.setTyped = function (on) {
3465 if (on) {
3466 exports.Buf8 = Uint8Array;
3467 exports.Buf16 = Uint16Array;
3468 exports.Buf32 = Int32Array;
3469 exports.assign(exports, fnTyped);
3470 } else {
3471 exports.Buf8 = Array;
3472 exports.Buf16 = Array;
3473 exports.Buf32 = Array;
3474 exports.assign(exports, fnUntyped);
3475 }
3476};
3477
3478exports.setTyped(TYPED_OK);
3479},{}],28:[function(_dereq_,module,exports){
3480// String encode/decode helpers
3481'use strict';
3482
3483
3484var utils = _dereq_('./common');
3485
3486
3487// Quick check if we can use fast array to bin string conversion
3488//
3489// - apply(Array) can fail on Android 2.2
3490// - apply(Uint8Array) can fail on iOS 5.1 Safary
3491//
3492var STR_APPLY_OK = true;
3493var STR_APPLY_UIA_OK = true;
3494
3495try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
3496try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
3497
3498
3499// Table with utf8 lengths (calculated by first byte of sequence)
3500// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
3501// because max possible codepoint is 0x10ffff
3502var _utf8len = new utils.Buf8(256);
3503for (var i=0; i<256; i++) {
3504 _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
3505}
3506_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
3507
3508
3509// convert string to array (typed, when possible)
3510exports.string2buf = function (str) {
3511 var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
3512
3513 // count binary size
3514 for (m_pos = 0; m_pos < str_len; m_pos++) {
3515 c = str.charCodeAt(m_pos);
3516 if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
3517 c2 = str.charCodeAt(m_pos+1);
3518 if ((c2 & 0xfc00) === 0xdc00) {
3519 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
3520 m_pos++;
3521 }
3522 }
3523 buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
3524 }
3525
3526 // allocate buffer
3527 buf = new utils.Buf8(buf_len);
3528
3529 // convert
3530 for (i=0, m_pos = 0; i < buf_len; m_pos++) {
3531 c = str.charCodeAt(m_pos);
3532 if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
3533 c2 = str.charCodeAt(m_pos+1);
3534 if ((c2 & 0xfc00) === 0xdc00) {
3535 c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
3536 m_pos++;
3537 }
3538 }
3539 if (c < 0x80) {
3540 /* one byte */
3541 buf[i++] = c;
3542 } else if (c < 0x800) {
3543 /* two bytes */
3544 buf[i++] = 0xC0 | (c >>> 6);
3545 buf[i++] = 0x80 | (c & 0x3f);
3546 } else if (c < 0x10000) {
3547 /* three bytes */
3548 buf[i++] = 0xE0 | (c >>> 12);
3549 buf[i++] = 0x80 | (c >>> 6 & 0x3f);
3550 buf[i++] = 0x80 | (c & 0x3f);
3551 } else {
3552 /* four bytes */
3553 buf[i++] = 0xf0 | (c >>> 18);
3554 buf[i++] = 0x80 | (c >>> 12 & 0x3f);
3555 buf[i++] = 0x80 | (c >>> 6 & 0x3f);
3556 buf[i++] = 0x80 | (c & 0x3f);
3557 }
3558 }
3559
3560 return buf;
3561};
3562
3563// Helper (used in 2 places)
3564function buf2binstring(buf, len) {
3565 // use fallback for big arrays to avoid stack overflow
3566 if (len < 65537) {
3567 if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
3568 return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
3569 }
3570 }
3571
3572 var result = '';
3573 for(var i=0; i < len; i++) {
3574 result += String.fromCharCode(buf[i]);
3575 }
3576 return result;
3577}
3578
3579
3580// Convert byte array to binary string
3581exports.buf2binstring = function(buf) {
3582 return buf2binstring(buf, buf.length);
3583};
3584
3585
3586// Convert binary string (typed, when possible)
3587exports.binstring2buf = function(str) {
3588 var buf = new utils.Buf8(str.length);
3589 for(var i=0, len=buf.length; i < len; i++) {
3590 buf[i] = str.charCodeAt(i);
3591 }
3592 return buf;
3593};
3594
3595
3596// convert array to string
3597exports.buf2string = function (buf, max) {
3598 var i, out, c, c_len;
3599 var len = max || buf.length;
3600
3601 // Reserve max possible length (2 words per char)
3602 // NB: by unknown reasons, Array is significantly faster for
3603 // String.fromCharCode.apply than Uint16Array.
3604 var utf16buf = new Array(len*2);
3605
3606 for (out=0, i=0; i<len;) {
3607 c = buf[i++];
3608 // quick process ascii
3609 if (c < 0x80) { utf16buf[out++] = c; continue; }
3610
3611 c_len = _utf8len[c];
3612 // skip 5 & 6 byte codes
3613 if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
3614
3615 // apply mask on first byte
3616 c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
3617 // join the rest
3618 while (c_len > 1 && i < len) {
3619 c = (c << 6) | (buf[i++] & 0x3f);
3620 c_len--;
3621 }
3622
3623 // terminated by end of string?
3624 if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
3625
3626 if (c < 0x10000) {
3627 utf16buf[out++] = c;
3628 } else {
3629 c -= 0x10000;
3630 utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
3631 utf16buf[out++] = 0xdc00 | (c & 0x3ff);
3632 }
3633 }
3634
3635 return buf2binstring(utf16buf, out);
3636};
3637
3638
3639// Calculate max possible position in utf8 buffer,
3640// that will not break sequence. If that's not possible
3641// - (very small limits) return max size as is.
3642//
3643// buf[] - utf8 bytes array
3644// max - length limit (mandatory);
3645exports.utf8border = function(buf, max) {
3646 var pos;
3647
3648 max = max || buf.length;
3649 if (max > buf.length) { max = buf.length; }
3650
3651 // go back from last position, until start of sequence found
3652 pos = max-1;
3653 while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
3654
3655 // Fuckup - very small and broken sequence,
3656 // return max, because we should return something anyway.
3657 if (pos < 0) { return max; }
3658
3659 // If we came to start of buffer - that means vuffer is too small,
3660 // return max too.
3661 if (pos === 0) { return max; }
3662
3663 return (pos + _utf8len[buf[pos]] > max) ? pos : max;
3664};
3665
3666},{"./common":27}],29:[function(_dereq_,module,exports){
3667'use strict';
3668
3669// Note: adler32 takes 12% for level 0 and 2% for level 6.
3670// It doesn't worth to make additional optimizationa as in original.
3671// Small size is preferable.
3672
3673function adler32(adler, buf, len, pos) {
3674 var s1 = (adler & 0xffff) |0
3675 , s2 = ((adler >>> 16) & 0xffff) |0
3676 , n = 0;
3677
3678 while (len !== 0) {
3679 // Set limit ~ twice less than 5552, to keep
3680 // s2 in 31-bits, because we force signed ints.
3681 // in other case %= will fail.
3682 n = len > 2000 ? 2000 : len;
3683 len -= n;
3684
3685 do {
3686 s1 = (s1 + buf[pos++]) |0;
3687 s2 = (s2 + s1) |0;
3688 } while (--n);
3689
3690 s1 %= 65521;
3691 s2 %= 65521;
3692 }
3693
3694 return (s1 | (s2 << 16)) |0;
3695}
3696
3697
3698module.exports = adler32;
3699},{}],30:[function(_dereq_,module,exports){
3700module.exports = {
3701
3702 /* Allowed flush values; see deflate() and inflate() below for details */
3703 Z_NO_FLUSH: 0,
3704 Z_PARTIAL_FLUSH: 1,
3705 Z_SYNC_FLUSH: 2,
3706 Z_FULL_FLUSH: 3,
3707 Z_FINISH: 4,
3708 Z_BLOCK: 5,
3709 Z_TREES: 6,
3710
3711 /* Return codes for the compression/decompression functions. Negative values
3712 * are errors, positive values are used for special but normal events.
3713 */
3714 Z_OK: 0,
3715 Z_STREAM_END: 1,
3716 Z_NEED_DICT: 2,
3717 Z_ERRNO: -1,
3718 Z_STREAM_ERROR: -2,
3719 Z_DATA_ERROR: -3,
3720 //Z_MEM_ERROR: -4,
3721 Z_BUF_ERROR: -5,
3722 //Z_VERSION_ERROR: -6,
3723
3724 /* compression levels */
3725 Z_NO_COMPRESSION: 0,
3726 Z_BEST_SPEED: 1,
3727 Z_BEST_COMPRESSION: 9,
3728 Z_DEFAULT_COMPRESSION: -1,
3729
3730
3731 Z_FILTERED: 1,
3732 Z_HUFFMAN_ONLY: 2,
3733 Z_RLE: 3,
3734 Z_FIXED: 4,
3735 Z_DEFAULT_STRATEGY: 0,
3736
3737 /* Possible values of the data_type field (though see inflate()) */
3738 Z_BINARY: 0,
3739 Z_TEXT: 1,
3740 //Z_ASCII: 1, // = Z_TEXT (deprecated)
3741 Z_UNKNOWN: 2,
3742
3743 /* The deflate compression method */
3744 Z_DEFLATED: 8
3745 //Z_NULL: null // Use -1 or null inline, depending on var type
3746};
3747},{}],31:[function(_dereq_,module,exports){
3748'use strict';
3749
3750// Note: we can't get significant speed boost here.
3751// So write code to minimize size - no pregenerated tables
3752// and array tools dependencies.
3753
3754
3755// Use ordinary array, since untyped makes no boost here
3756function makeTable() {
3757 var c, table = [];
3758
3759 for(var n =0; n < 256; n++){
3760 c = n;
3761 for(var k =0; k < 8; k++){
3762 c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
3763 }
3764 table[n] = c;
3765 }
3766
3767 return table;
3768}
3769
3770// Create table on load. Just 255 signed longs. Not a problem.
3771var crcTable = makeTable();
3772
3773
3774function crc32(crc, buf, len, pos) {
3775 var t = crcTable
3776 , end = pos + len;
3777
3778 crc = crc ^ (-1);
3779
3780 for (var i = pos; i < end; i++ ) {
3781 crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
3782 }
3783
3784 return (crc ^ (-1)); // >>> 0;
3785}
3786
3787
3788module.exports = crc32;
3789},{}],32:[function(_dereq_,module,exports){
3790'use strict';
3791
3792var utils = _dereq_('../utils/common');
3793var trees = _dereq_('./trees');
3794var adler32 = _dereq_('./adler32');
3795var crc32 = _dereq_('./crc32');
3796var msg = _dereq_('./messages');
3797
3798/* Public constants ==========================================================*/
3799/* ===========================================================================*/
3800
3801
3802/* Allowed flush values; see deflate() and inflate() below for details */
3803var Z_NO_FLUSH = 0;
3804var Z_PARTIAL_FLUSH = 1;
3805//var Z_SYNC_FLUSH = 2;
3806var Z_FULL_FLUSH = 3;
3807var Z_FINISH = 4;
3808var Z_BLOCK = 5;
3809//var Z_TREES = 6;
3810
3811
3812/* Return codes for the compression/decompression functions. Negative values
3813 * are errors, positive values are used for special but normal events.
3814 */
3815var Z_OK = 0;
3816var Z_STREAM_END = 1;
3817//var Z_NEED_DICT = 2;
3818//var Z_ERRNO = -1;
3819var Z_STREAM_ERROR = -2;
3820var Z_DATA_ERROR = -3;
3821//var Z_MEM_ERROR = -4;
3822var Z_BUF_ERROR = -5;
3823//var Z_VERSION_ERROR = -6;
3824
3825
3826/* compression levels */
3827//var Z_NO_COMPRESSION = 0;
3828//var Z_BEST_SPEED = 1;
3829//var Z_BEST_COMPRESSION = 9;
3830var Z_DEFAULT_COMPRESSION = -1;
3831
3832
3833var Z_FILTERED = 1;
3834var Z_HUFFMAN_ONLY = 2;
3835var Z_RLE = 3;
3836var Z_FIXED = 4;
3837var Z_DEFAULT_STRATEGY = 0;
3838
3839/* Possible values of the data_type field (though see inflate()) */
3840//var Z_BINARY = 0;
3841//var Z_TEXT = 1;
3842//var Z_ASCII = 1; // = Z_TEXT
3843var Z_UNKNOWN = 2;
3844
3845
3846/* The deflate compression method */
3847var Z_DEFLATED = 8;
3848
3849/*============================================================================*/
3850
3851
3852var MAX_MEM_LEVEL = 9;
3853/* Maximum value for memLevel in deflateInit2 */
3854var MAX_WBITS = 15;
3855/* 32K LZ77 window */
3856var DEF_MEM_LEVEL = 8;
3857
3858
3859var LENGTH_CODES = 29;
3860/* number of length codes, not counting the special END_BLOCK code */
3861var LITERALS = 256;
3862/* number of literal bytes 0..255 */
3863var L_CODES = LITERALS + 1 + LENGTH_CODES;
3864/* number of Literal or Length codes, including the END_BLOCK code */
3865var D_CODES = 30;
3866/* number of distance codes */
3867var BL_CODES = 19;
3868/* number of codes used to transfer the bit lengths */
3869var HEAP_SIZE = 2*L_CODES + 1;
3870/* maximum heap size */
3871var MAX_BITS = 15;
3872/* All codes must not exceed MAX_BITS bits */
3873
3874var MIN_MATCH = 3;
3875var MAX_MATCH = 258;
3876var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
3877
3878var PRESET_DICT = 0x20;
3879
3880var INIT_STATE = 42;
3881var EXTRA_STATE = 69;
3882var NAME_STATE = 73;
3883var COMMENT_STATE = 91;
3884var HCRC_STATE = 103;
3885var BUSY_STATE = 113;
3886var FINISH_STATE = 666;
3887
3888var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
3889var BS_BLOCK_DONE = 2; /* block flush performed */
3890var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
3891var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
3892
3893var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
3894
3895function err(strm, errorCode) {
3896 strm.msg = msg[errorCode];
3897 return errorCode;
3898}
3899
3900function rank(f) {
3901 return ((f) << 1) - ((f) > 4 ? 9 : 0);
3902}
3903
3904function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
3905
3906
3907/* =========================================================================
3908 * Flush as much pending output as possible. All deflate() output goes
3909 * through this function so some applications may wish to modify it
3910 * to avoid allocating a large strm->output buffer and copying into it.
3911 * (See also read_buf()).
3912 */
3913function flush_pending(strm) {
3914 var s = strm.state;
3915
3916 //_tr_flush_bits(s);
3917 var len = s.pending;
3918 if (len > strm.avail_out) {
3919 len = strm.avail_out;
3920 }
3921 if (len === 0) { return; }
3922
3923 utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
3924 strm.next_out += len;
3925 s.pending_out += len;
3926 strm.total_out += len;
3927 strm.avail_out -= len;
3928 s.pending -= len;
3929 if (s.pending === 0) {
3930 s.pending_out = 0;
3931 }
3932}
3933
3934
3935function flush_block_only (s, last) {
3936 trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
3937 s.block_start = s.strstart;
3938 flush_pending(s.strm);
3939}
3940
3941
3942function put_byte(s, b) {
3943 s.pending_buf[s.pending++] = b;
3944}
3945
3946
3947/* =========================================================================
3948 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
3949 * IN assertion: the stream state is correct and there is enough room in
3950 * pending_buf.
3951 */
3952function putShortMSB(s, b) {
3953// put_byte(s, (Byte)(b >> 8));
3954// put_byte(s, (Byte)(b & 0xff));
3955 s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
3956 s.pending_buf[s.pending++] = b & 0xff;
3957}
3958
3959
3960/* ===========================================================================
3961 * Read a new buffer from the current input stream, update the adler32
3962 * and total number of bytes read. All deflate() input goes through
3963 * this function so some applications may wish to modify it to avoid
3964 * allocating a large strm->input buffer and copying from it.
3965 * (See also flush_pending()).
3966 */
3967function read_buf(strm, buf, start, size) {
3968 var len = strm.avail_in;
3969
3970 if (len > size) { len = size; }
3971 if (len === 0) { return 0; }
3972
3973 strm.avail_in -= len;
3974
3975 utils.arraySet(buf, strm.input, strm.next_in, len, start);
3976 if (strm.state.wrap === 1) {
3977 strm.adler = adler32(strm.adler, buf, len, start);
3978 }
3979
3980 else if (strm.state.wrap === 2) {
3981 strm.adler = crc32(strm.adler, buf, len, start);
3982 }
3983
3984 strm.next_in += len;
3985 strm.total_in += len;
3986
3987 return len;
3988}
3989
3990
3991/* ===========================================================================
3992 * Set match_start to the longest match starting at the given string and
3993 * return its length. Matches shorter or equal to prev_length are discarded,
3994 * in which case the result is equal to prev_length and match_start is
3995 * garbage.
3996 * IN assertions: cur_match is the head of the hash chain for the current
3997 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
3998 * OUT assertion: the match length is not greater than s->lookahead.
3999 */
4000function longest_match(s, cur_match) {
4001 var chain_length = s.max_chain_length; /* max hash chain length */
4002 var scan = s.strstart; /* current string */
4003 var match; /* matched string */
4004 var len; /* length of current match */
4005 var best_len = s.prev_length; /* best match length so far */
4006 var nice_match = s.nice_match; /* stop if match long enough */
4007 var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
4008 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
4009
4010 var _win = s.window; // shortcut
4011
4012 var wmask = s.w_mask;
4013 var prev = s.prev;
4014
4015 /* Stop when cur_match becomes <= limit. To simplify the code,
4016 * we prevent matches with the string of window index 0.
4017 */
4018
4019 var strend = s.strstart + MAX_MATCH;
4020 var scan_end1 = _win[scan + best_len - 1];
4021 var scan_end = _win[scan + best_len];
4022
4023 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
4024 * It is easy to get rid of this optimization if necessary.
4025 */
4026 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
4027
4028 /* Do not waste too much time if we already have a good match: */
4029 if (s.prev_length >= s.good_match) {
4030 chain_length >>= 2;
4031 }
4032 /* Do not look for matches beyond the end of the input. This is necessary
4033 * to make deflate deterministic.
4034 */
4035 if (nice_match > s.lookahead) { nice_match = s.lookahead; }
4036
4037 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
4038
4039 do {
4040 // Assert(cur_match < s->strstart, "no future");
4041 match = cur_match;
4042
4043 /* Skip to next match if the match length cannot increase
4044 * or if the match length is less than 2. Note that the checks below
4045 * for insufficient lookahead only occur occasionally for performance
4046 * reasons. Therefore uninitialized memory will be accessed, and
4047 * conditional jumps will be made that depend on those values.
4048 * However the length of the match is limited to the lookahead, so
4049 * the output of deflate is not affected by the uninitialized values.
4050 */
4051
4052 if (_win[match + best_len] !== scan_end ||
4053 _win[match + best_len - 1] !== scan_end1 ||
4054 _win[match] !== _win[scan] ||
4055 _win[++match] !== _win[scan + 1]) {
4056 continue;
4057 }
4058
4059 /* The check at best_len-1 can be removed because it will be made
4060 * again later. (This heuristic is not always a win.)
4061 * It is not necessary to compare scan[2] and match[2] since they
4062 * are always equal when the other bytes match, given that
4063 * the hash keys are equal and that HASH_BITS >= 8.
4064 */
4065 scan += 2;
4066 match++;
4067 // Assert(*scan == *match, "match[2]?");
4068
4069 /* We check for insufficient lookahead only every 8th comparison;
4070 * the 256th check will be made at strstart+258.
4071 */
4072 do {
4073 /*jshint noempty:false*/
4074 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
4075 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
4076 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
4077 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
4078 scan < strend);
4079
4080 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
4081
4082 len = MAX_MATCH - (strend - scan);
4083 scan = strend - MAX_MATCH;
4084
4085 if (len > best_len) {
4086 s.match_start = cur_match;
4087 best_len = len;
4088 if (len >= nice_match) {
4089 break;
4090 }
4091 scan_end1 = _win[scan + best_len - 1];
4092 scan_end = _win[scan + best_len];
4093 }
4094 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
4095
4096 if (best_len <= s.lookahead) {
4097 return best_len;
4098 }
4099 return s.lookahead;
4100}
4101
4102
4103/* ===========================================================================
4104 * Fill the window when the lookahead becomes insufficient.
4105 * Updates strstart and lookahead.
4106 *
4107 * IN assertion: lookahead < MIN_LOOKAHEAD
4108 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
4109 * At least one byte has been read, or avail_in == 0; reads are
4110 * performed for at least two bytes (required for the zip translate_eol
4111 * option -- not supported here).
4112 */
4113function fill_window(s) {
4114 var _w_size = s.w_size;
4115 var p, n, m, more, str;
4116
4117 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
4118
4119 do {
4120 more = s.window_size - s.lookahead - s.strstart;
4121
4122 // JS ints have 32 bit, block below not needed
4123 /* Deal with !@#$% 64K limit: */
4124 //if (sizeof(int) <= 2) {
4125 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
4126 // more = wsize;
4127 //
4128 // } else if (more == (unsigned)(-1)) {
4129 // /* Very unlikely, but possible on 16 bit machine if
4130 // * strstart == 0 && lookahead == 1 (input done a byte at time)
4131 // */
4132 // more--;
4133 // }
4134 //}
4135
4136
4137 /* If the window is almost full and there is insufficient lookahead,
4138 * move the upper half to the lower one to make room in the upper half.
4139 */
4140 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
4141
4142 utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
4143 s.match_start -= _w_size;
4144 s.strstart -= _w_size;
4145 /* we now have strstart >= MAX_DIST */
4146 s.block_start -= _w_size;
4147
4148 /* Slide the hash table (could be avoided with 32 bit values
4149 at the expense of memory usage). We slide even when level == 0
4150 to keep the hash table consistent if we switch back to level > 0
4151 later. (Using level 0 permanently is not an optimal usage of
4152 zlib, so we don't care about this pathological case.)
4153 */
4154
4155 n = s.hash_size;
4156 p = n;
4157 do {
4158 m = s.head[--p];
4159 s.head[p] = (m >= _w_size ? m - _w_size : 0);
4160 } while (--n);
4161
4162 n = _w_size;
4163 p = n;
4164 do {
4165 m = s.prev[--p];
4166 s.prev[p] = (m >= _w_size ? m - _w_size : 0);
4167 /* If n is not on any hash chain, prev[n] is garbage but
4168 * its value will never be used.
4169 */
4170 } while (--n);
4171
4172 more += _w_size;
4173 }
4174 if (s.strm.avail_in === 0) {
4175 break;
4176 }
4177
4178 /* If there was no sliding:
4179 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
4180 * more == window_size - lookahead - strstart
4181 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
4182 * => more >= window_size - 2*WSIZE + 2
4183 * In the BIG_MEM or MMAP case (not yet supported),
4184 * window_size == input_size + MIN_LOOKAHEAD &&
4185 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
4186 * Otherwise, window_size == 2*WSIZE so more >= 2.
4187 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
4188 */
4189 //Assert(more >= 2, "more < 2");
4190 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
4191 s.lookahead += n;
4192
4193 /* Initialize the hash value now that we have some input: */
4194 if (s.lookahead + s.insert >= MIN_MATCH) {
4195 str = s.strstart - s.insert;
4196 s.ins_h = s.window[str];
4197
4198 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
4199 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
4200//#if MIN_MATCH != 3
4201// Call update_hash() MIN_MATCH-3 more times
4202//#endif
4203 while (s.insert) {
4204 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
4205 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
4206
4207 s.prev[str & s.w_mask] = s.head[s.ins_h];
4208 s.head[s.ins_h] = str;
4209 str++;
4210 s.insert--;
4211 if (s.lookahead + s.insert < MIN_MATCH) {
4212 break;
4213 }
4214 }
4215 }
4216 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
4217 * but this is not important since only literal bytes will be emitted.
4218 */
4219
4220 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
4221
4222 /* If the WIN_INIT bytes after the end of the current data have never been
4223 * written, then zero those bytes in order to avoid memory check reports of
4224 * the use of uninitialized (or uninitialised as Julian writes) bytes by
4225 * the longest match routines. Update the high water mark for the next
4226 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
4227 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
4228 */
4229// if (s.high_water < s.window_size) {
4230// var curr = s.strstart + s.lookahead;
4231// var init = 0;
4232//
4233// if (s.high_water < curr) {
4234// /* Previous high water mark below current data -- zero WIN_INIT
4235// * bytes or up to end of window, whichever is less.
4236// */
4237// init = s.window_size - curr;
4238// if (init > WIN_INIT)
4239// init = WIN_INIT;
4240// zmemzero(s->window + curr, (unsigned)init);
4241// s->high_water = curr + init;
4242// }
4243// else if (s->high_water < (ulg)curr + WIN_INIT) {
4244// /* High water mark at or above current data, but below current data
4245// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
4246// * to end of window, whichever is less.
4247// */
4248// init = (ulg)curr + WIN_INIT - s->high_water;
4249// if (init > s->window_size - s->high_water)
4250// init = s->window_size - s->high_water;
4251// zmemzero(s->window + s->high_water, (unsigned)init);
4252// s->high_water += init;
4253// }
4254// }
4255//
4256// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
4257// "not enough room for search");
4258}
4259
4260/* ===========================================================================
4261 * Copy without compression as much as possible from the input stream, return
4262 * the current block state.
4263 * This function does not insert new strings in the dictionary since
4264 * uncompressible data is probably not useful. This function is used
4265 * only for the level=0 compression option.
4266 * NOTE: this function should be optimized to avoid extra copying from
4267 * window to pending_buf.
4268 */
4269function deflate_stored(s, flush) {
4270 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
4271 * to pending_buf_size, and each stored block has a 5 byte header:
4272 */
4273 var max_block_size = 0xffff;
4274
4275 if (max_block_size > s.pending_buf_size - 5) {
4276 max_block_size = s.pending_buf_size - 5;
4277 }
4278
4279 /* Copy as much as possible from input to output: */
4280 for (;;) {
4281 /* Fill the window as much as possible: */
4282 if (s.lookahead <= 1) {
4283
4284 //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
4285 // s->block_start >= (long)s->w_size, "slide too late");
4286// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
4287// s.block_start >= s.w_size)) {
4288// throw new Error("slide too late");
4289// }
4290
4291 fill_window(s);
4292 if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
4293 return BS_NEED_MORE;
4294 }
4295
4296 if (s.lookahead === 0) {
4297 break;
4298 }
4299 /* flush the current block */
4300 }
4301 //Assert(s->block_start >= 0L, "block gone");
4302// if (s.block_start < 0) throw new Error("block gone");
4303
4304 s.strstart += s.lookahead;
4305 s.lookahead = 0;
4306
4307 /* Emit a stored block if pending_buf will be full: */
4308 var max_start = s.block_start + max_block_size;
4309
4310 if (s.strstart === 0 || s.strstart >= max_start) {
4311 /* strstart == 0 is possible when wraparound on 16-bit machine */
4312 s.lookahead = s.strstart - max_start;
4313 s.strstart = max_start;
4314 /*** FLUSH_BLOCK(s, 0); ***/
4315 flush_block_only(s, false);
4316 if (s.strm.avail_out === 0) {
4317 return BS_NEED_MORE;
4318 }
4319 /***/
4320
4321
4322 }
4323 /* Flush if we may have to slide, otherwise block_start may become
4324 * negative and the data will be gone:
4325 */
4326 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
4327 /*** FLUSH_BLOCK(s, 0); ***/
4328 flush_block_only(s, false);
4329 if (s.strm.avail_out === 0) {
4330 return BS_NEED_MORE;
4331 }
4332 /***/
4333 }
4334 }
4335
4336 s.insert = 0;
4337
4338 if (flush === Z_FINISH) {
4339 /*** FLUSH_BLOCK(s, 1); ***/
4340 flush_block_only(s, true);
4341 if (s.strm.avail_out === 0) {
4342 return BS_FINISH_STARTED;
4343 }
4344 /***/
4345 return BS_FINISH_DONE;
4346 }
4347
4348 if (s.strstart > s.block_start) {
4349 /*** FLUSH_BLOCK(s, 0); ***/
4350 flush_block_only(s, false);
4351 if (s.strm.avail_out === 0) {
4352 return BS_NEED_MORE;
4353 }
4354 /***/
4355 }
4356
4357 return BS_NEED_MORE;
4358}
4359
4360/* ===========================================================================
4361 * Compress as much as possible from the input stream, return the current
4362 * block state.
4363 * This function does not perform lazy evaluation of matches and inserts
4364 * new strings in the dictionary only for unmatched strings or for short
4365 * matches. It is used only for the fast compression options.
4366 */
4367function deflate_fast(s, flush) {
4368 var hash_head; /* head of the hash chain */
4369 var bflush; /* set if current block must be flushed */
4370
4371 for (;;) {
4372 /* Make sure that we always have enough lookahead, except
4373 * at the end of the input file. We need MAX_MATCH bytes
4374 * for the next match, plus MIN_MATCH bytes to insert the
4375 * string following the next match.
4376 */
4377 if (s.lookahead < MIN_LOOKAHEAD) {
4378 fill_window(s);
4379 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
4380 return BS_NEED_MORE;
4381 }
4382 if (s.lookahead === 0) {
4383 break; /* flush the current block */
4384 }
4385 }
4386
4387 /* Insert the string window[strstart .. strstart+2] in the
4388 * dictionary, and set hash_head to the head of the hash chain:
4389 */
4390 hash_head = 0/*NIL*/;
4391 if (s.lookahead >= MIN_MATCH) {
4392 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
4393 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
4394 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
4395 s.head[s.ins_h] = s.strstart;
4396 /***/
4397 }
4398
4399 /* Find the longest match, discarding those <= prev_length.
4400 * At this point we have always match_length < MIN_MATCH
4401 */
4402 if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
4403 /* To simplify the code, we prevent matches with the string
4404 * of window index 0 (in particular we have to avoid a match
4405 * of the string with itself at the start of the input file).
4406 */
4407 s.match_length = longest_match(s, hash_head);
4408 /* longest_match() sets match_start */
4409 }
4410 if (s.match_length >= MIN_MATCH) {
4411 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
4412
4413 /*** _tr_tally_dist(s, s.strstart - s.match_start,
4414 s.match_length - MIN_MATCH, bflush); ***/
4415 bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
4416
4417 s.lookahead -= s.match_length;
4418
4419 /* Insert new strings in the hash table only if the match length
4420 * is not too large. This saves time but degrades compression.
4421 */
4422 if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
4423 s.match_length--; /* string at strstart already in table */
4424 do {
4425 s.strstart++;
4426 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
4427 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
4428 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
4429 s.head[s.ins_h] = s.strstart;
4430 /***/
4431 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
4432 * always MIN_MATCH bytes ahead.
4433 */
4434 } while (--s.match_length !== 0);
4435 s.strstart++;
4436 } else
4437 {
4438 s.strstart += s.match_length;
4439 s.match_length = 0;
4440 s.ins_h = s.window[s.strstart];
4441 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
4442 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
4443
4444//#if MIN_MATCH != 3
4445// Call UPDATE_HASH() MIN_MATCH-3 more times
4446//#endif
4447 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
4448 * matter since it will be recomputed at next deflate call.
4449 */
4450 }
4451 } else {
4452 /* No match, output a literal byte */
4453 //Tracevv((stderr,"%c", s.window[s.strstart]));
4454 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
4455 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
4456
4457 s.lookahead--;
4458 s.strstart++;
4459 }
4460 if (bflush) {
4461 /*** FLUSH_BLOCK(s, 0); ***/
4462 flush_block_only(s, false);
4463 if (s.strm.avail_out === 0) {
4464 return BS_NEED_MORE;
4465 }
4466 /***/
4467 }
4468 }
4469 s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
4470 if (flush === Z_FINISH) {
4471 /*** FLUSH_BLOCK(s, 1); ***/
4472 flush_block_only(s, true);
4473 if (s.strm.avail_out === 0) {
4474 return BS_FINISH_STARTED;
4475 }
4476 /***/
4477 return BS_FINISH_DONE;
4478 }
4479 if (s.last_lit) {
4480 /*** FLUSH_BLOCK(s, 0); ***/
4481 flush_block_only(s, false);
4482 if (s.strm.avail_out === 0) {
4483 return BS_NEED_MORE;
4484 }
4485 /***/
4486 }
4487 return BS_BLOCK_DONE;
4488}
4489
4490/* ===========================================================================
4491 * Same as above, but achieves better compression. We use a lazy
4492 * evaluation for matches: a match is finally adopted only if there is
4493 * no better match at the next window position.
4494 */
4495function deflate_slow(s, flush) {
4496 var hash_head; /* head of hash chain */
4497 var bflush; /* set if current block must be flushed */
4498
4499 var max_insert;
4500
4501 /* Process the input block. */
4502 for (;;) {
4503 /* Make sure that we always have enough lookahead, except
4504 * at the end of the input file. We need MAX_MATCH bytes
4505 * for the next match, plus MIN_MATCH bytes to insert the
4506 * string following the next match.
4507 */
4508 if (s.lookahead < MIN_LOOKAHEAD) {
4509 fill_window(s);
4510 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
4511 return BS_NEED_MORE;
4512 }
4513 if (s.lookahead === 0) { break; } /* flush the current block */
4514 }
4515
4516 /* Insert the string window[strstart .. strstart+2] in the
4517 * dictionary, and set hash_head to the head of the hash chain:
4518 */
4519 hash_head = 0/*NIL*/;
4520 if (s.lookahead >= MIN_MATCH) {
4521 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
4522 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
4523 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
4524 s.head[s.ins_h] = s.strstart;
4525 /***/
4526 }
4527
4528 /* Find the longest match, discarding those <= prev_length.
4529 */
4530 s.prev_length = s.match_length;
4531 s.prev_match = s.match_start;
4532 s.match_length = MIN_MATCH-1;
4533
4534 if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
4535 s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
4536 /* To simplify the code, we prevent matches with the string
4537 * of window index 0 (in particular we have to avoid a match
4538 * of the string with itself at the start of the input file).
4539 */
4540 s.match_length = longest_match(s, hash_head);
4541 /* longest_match() sets match_start */
4542
4543 if (s.match_length <= 5 &&
4544 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
4545
4546 /* If prev_match is also MIN_MATCH, match_start is garbage
4547 * but we will ignore the current match anyway.
4548 */
4549 s.match_length = MIN_MATCH-1;
4550 }
4551 }
4552 /* If there was a match at the previous step and the current
4553 * match is not better, output the previous match:
4554 */
4555 if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
4556 max_insert = s.strstart + s.lookahead - MIN_MATCH;
4557 /* Do not insert strings in hash table beyond this. */
4558
4559 //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
4560
4561 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
4562 s.prev_length - MIN_MATCH, bflush);***/
4563 bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
4564 /* Insert in hash table all strings up to the end of the match.
4565 * strstart-1 and strstart are already inserted. If there is not
4566 * enough lookahead, the last two strings are not inserted in
4567 * the hash table.
4568 */
4569 s.lookahead -= s.prev_length-1;
4570 s.prev_length -= 2;
4571 do {
4572 if (++s.strstart <= max_insert) {
4573 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
4574 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
4575 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
4576 s.head[s.ins_h] = s.strstart;
4577 /***/
4578 }
4579 } while (--s.prev_length !== 0);
4580 s.match_available = 0;
4581 s.match_length = MIN_MATCH-1;
4582 s.strstart++;
4583
4584 if (bflush) {
4585 /*** FLUSH_BLOCK(s, 0); ***/
4586 flush_block_only(s, false);
4587 if (s.strm.avail_out === 0) {
4588 return BS_NEED_MORE;
4589 }
4590 /***/
4591 }
4592
4593 } else if (s.match_available) {
4594 /* If there was no match at the previous position, output a
4595 * single literal. If there was a match but the current match
4596 * is longer, truncate the previous match to a single literal.
4597 */
4598 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
4599 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
4600 bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
4601
4602 if (bflush) {
4603 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
4604 flush_block_only(s, false);
4605 /***/
4606 }
4607 s.strstart++;
4608 s.lookahead--;
4609 if (s.strm.avail_out === 0) {
4610 return BS_NEED_MORE;
4611 }
4612 } else {
4613 /* There is no previous match to compare with, wait for
4614 * the next step to decide.
4615 */
4616 s.match_available = 1;
4617 s.strstart++;
4618 s.lookahead--;
4619 }
4620 }
4621 //Assert (flush != Z_NO_FLUSH, "no flush?");
4622 if (s.match_available) {
4623 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
4624 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
4625 bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
4626
4627 s.match_available = 0;
4628 }
4629 s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
4630 if (flush === Z_FINISH) {
4631 /*** FLUSH_BLOCK(s, 1); ***/
4632 flush_block_only(s, true);
4633 if (s.strm.avail_out === 0) {
4634 return BS_FINISH_STARTED;
4635 }
4636 /***/
4637 return BS_FINISH_DONE;
4638 }
4639 if (s.last_lit) {
4640 /*** FLUSH_BLOCK(s, 0); ***/
4641 flush_block_only(s, false);
4642 if (s.strm.avail_out === 0) {
4643 return BS_NEED_MORE;
4644 }
4645 /***/
4646 }
4647
4648 return BS_BLOCK_DONE;
4649}
4650
4651
4652/* ===========================================================================
4653 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
4654 * one. Do not maintain a hash table. (It will be regenerated if this run of
4655 * deflate switches away from Z_RLE.)
4656 */
4657function deflate_rle(s, flush) {
4658 var bflush; /* set if current block must be flushed */
4659 var prev; /* byte at distance one to match */
4660 var scan, strend; /* scan goes up to strend for length of run */
4661
4662 var _win = s.window;
4663
4664 for (;;) {
4665 /* Make sure that we always have enough lookahead, except
4666 * at the end of the input file. We need MAX_MATCH bytes
4667 * for the longest run, plus one for the unrolled loop.
4668 */
4669 if (s.lookahead <= MAX_MATCH) {
4670 fill_window(s);
4671 if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
4672 return BS_NEED_MORE;
4673 }
4674 if (s.lookahead === 0) { break; } /* flush the current block */
4675 }
4676
4677 /* See how many times the previous byte repeats */
4678 s.match_length = 0;
4679 if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
4680 scan = s.strstart - 1;
4681 prev = _win[scan];
4682 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
4683 strend = s.strstart + MAX_MATCH;
4684 do {
4685 /*jshint noempty:false*/
4686 } while (prev === _win[++scan] && prev === _win[++scan] &&
4687 prev === _win[++scan] && prev === _win[++scan] &&
4688 prev === _win[++scan] && prev === _win[++scan] &&
4689 prev === _win[++scan] && prev === _win[++scan] &&
4690 scan < strend);
4691 s.match_length = MAX_MATCH - (strend - scan);
4692 if (s.match_length > s.lookahead) {
4693 s.match_length = s.lookahead;
4694 }
4695 }
4696 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
4697 }
4698
4699 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
4700 if (s.match_length >= MIN_MATCH) {
4701 //check_match(s, s.strstart, s.strstart - 1, s.match_length);
4702
4703 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
4704 bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
4705
4706 s.lookahead -= s.match_length;
4707 s.strstart += s.match_length;
4708 s.match_length = 0;
4709 } else {
4710 /* No match, output a literal byte */
4711 //Tracevv((stderr,"%c", s->window[s->strstart]));
4712 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
4713 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
4714
4715 s.lookahead--;
4716 s.strstart++;
4717 }
4718 if (bflush) {
4719 /*** FLUSH_BLOCK(s, 0); ***/
4720 flush_block_only(s, false);
4721 if (s.strm.avail_out === 0) {
4722 return BS_NEED_MORE;
4723 }
4724 /***/
4725 }
4726 }
4727 s.insert = 0;
4728 if (flush === Z_FINISH) {
4729 /*** FLUSH_BLOCK(s, 1); ***/
4730 flush_block_only(s, true);
4731 if (s.strm.avail_out === 0) {
4732 return BS_FINISH_STARTED;
4733 }
4734 /***/
4735 return BS_FINISH_DONE;
4736 }
4737 if (s.last_lit) {
4738 /*** FLUSH_BLOCK(s, 0); ***/
4739 flush_block_only(s, false);
4740 if (s.strm.avail_out === 0) {
4741 return BS_NEED_MORE;
4742 }
4743 /***/
4744 }
4745 return BS_BLOCK_DONE;
4746}
4747
4748/* ===========================================================================
4749 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
4750 * (It will be regenerated if this run of deflate switches away from Huffman.)
4751 */
4752function deflate_huff(s, flush) {
4753 var bflush; /* set if current block must be flushed */
4754
4755 for (;;) {
4756 /* Make sure that we have a literal to write. */
4757 if (s.lookahead === 0) {
4758 fill_window(s);
4759 if (s.lookahead === 0) {
4760 if (flush === Z_NO_FLUSH) {
4761 return BS_NEED_MORE;
4762 }
4763 break; /* flush the current block */
4764 }
4765 }
4766
4767 /* Output a literal byte */
4768 s.match_length = 0;
4769 //Tracevv((stderr,"%c", s->window[s->strstart]));
4770 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
4771 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
4772 s.lookahead--;
4773 s.strstart++;
4774 if (bflush) {
4775 /*** FLUSH_BLOCK(s, 0); ***/
4776 flush_block_only(s, false);
4777 if (s.strm.avail_out === 0) {
4778 return BS_NEED_MORE;
4779 }
4780 /***/
4781 }
4782 }
4783 s.insert = 0;
4784 if (flush === Z_FINISH) {
4785 /*** FLUSH_BLOCK(s, 1); ***/
4786 flush_block_only(s, true);
4787 if (s.strm.avail_out === 0) {
4788 return BS_FINISH_STARTED;
4789 }
4790 /***/
4791 return BS_FINISH_DONE;
4792 }
4793 if (s.last_lit) {
4794 /*** FLUSH_BLOCK(s, 0); ***/
4795 flush_block_only(s, false);
4796 if (s.strm.avail_out === 0) {
4797 return BS_NEED_MORE;
4798 }
4799 /***/
4800 }
4801 return BS_BLOCK_DONE;
4802}
4803
4804/* Values for max_lazy_match, good_match and max_chain_length, depending on
4805 * the desired pack level (0..9). The values given below have been tuned to
4806 * exclude worst case performance for pathological files. Better values may be
4807 * found for specific files.
4808 */
4809var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
4810 this.good_length = good_length;
4811 this.max_lazy = max_lazy;
4812 this.nice_length = nice_length;
4813 this.max_chain = max_chain;
4814 this.func = func;
4815};
4816
4817var configuration_table;
4818
4819configuration_table = [
4820 /* good lazy nice chain */
4821 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
4822 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
4823 new Config(4, 5, 16, 8, deflate_fast), /* 2 */
4824 new Config(4, 6, 32, 32, deflate_fast), /* 3 */
4825
4826 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
4827 new Config(8, 16, 32, 32, deflate_slow), /* 5 */
4828 new Config(8, 16, 128, 128, deflate_slow), /* 6 */
4829 new Config(8, 32, 128, 256, deflate_slow), /* 7 */
4830 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
4831 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
4832];
4833
4834
4835/* ===========================================================================
4836 * Initialize the "longest match" routines for a new zlib stream
4837 */
4838function lm_init(s) {
4839 s.window_size = 2 * s.w_size;
4840
4841 /*** CLEAR_HASH(s); ***/
4842 zero(s.head); // Fill with NIL (= 0);
4843
4844 /* Set the default configuration parameters:
4845 */
4846 s.max_lazy_match = configuration_table[s.level].max_lazy;
4847 s.good_match = configuration_table[s.level].good_length;
4848 s.nice_match = configuration_table[s.level].nice_length;
4849 s.max_chain_length = configuration_table[s.level].max_chain;
4850
4851 s.strstart = 0;
4852 s.block_start = 0;
4853 s.lookahead = 0;
4854 s.insert = 0;
4855 s.match_length = s.prev_length = MIN_MATCH - 1;
4856 s.match_available = 0;
4857 s.ins_h = 0;
4858}
4859
4860
4861function DeflateState() {
4862 this.strm = null; /* pointer back to this zlib stream */
4863 this.status = 0; /* as the name implies */
4864 this.pending_buf = null; /* output still pending */
4865 this.pending_buf_size = 0; /* size of pending_buf */
4866 this.pending_out = 0; /* next pending byte to output to the stream */
4867 this.pending = 0; /* nb of bytes in the pending buffer */
4868 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
4869 this.gzhead = null; /* gzip header information to write */
4870 this.gzindex = 0; /* where in extra, name, or comment */
4871 this.method = Z_DEFLATED; /* can only be DEFLATED */
4872 this.last_flush = -1; /* value of flush param for previous deflate call */
4873
4874 this.w_size = 0; /* LZ77 window size (32K by default) */
4875 this.w_bits = 0; /* log2(w_size) (8..16) */
4876 this.w_mask = 0; /* w_size - 1 */
4877
4878 this.window = null;
4879 /* Sliding window. Input bytes are read into the second half of the window,
4880 * and move to the first half later to keep a dictionary of at least wSize
4881 * bytes. With this organization, matches are limited to a distance of
4882 * wSize-MAX_MATCH bytes, but this ensures that IO is always
4883 * performed with a length multiple of the block size.
4884 */
4885
4886 this.window_size = 0;
4887 /* Actual size of window: 2*wSize, except when the user input buffer
4888 * is directly used as sliding window.
4889 */
4890
4891 this.prev = null;
4892 /* Link to older string with same hash index. To limit the size of this
4893 * array to 64K, this link is maintained only for the last 32K strings.
4894 * An index in this array is thus a window index modulo 32K.
4895 */
4896
4897 this.head = null; /* Heads of the hash chains or NIL. */
4898
4899 this.ins_h = 0; /* hash index of string to be inserted */
4900 this.hash_size = 0; /* number of elements in hash table */
4901 this.hash_bits = 0; /* log2(hash_size) */
4902 this.hash_mask = 0; /* hash_size-1 */
4903
4904 this.hash_shift = 0;
4905 /* Number of bits by which ins_h must be shifted at each input
4906 * step. It must be such that after MIN_MATCH steps, the oldest
4907 * byte no longer takes part in the hash key, that is:
4908 * hash_shift * MIN_MATCH >= hash_bits
4909 */
4910
4911 this.block_start = 0;
4912 /* Window position at the beginning of the current output block. Gets
4913 * negative when the window is moved backwards.
4914 */
4915
4916 this.match_length = 0; /* length of best match */
4917 this.prev_match = 0; /* previous match */
4918 this.match_available = 0; /* set if previous match exists */
4919 this.strstart = 0; /* start of string to insert */
4920 this.match_start = 0; /* start of matching string */
4921 this.lookahead = 0; /* number of valid bytes ahead in window */
4922
4923 this.prev_length = 0;
4924 /* Length of the best match at previous step. Matches not greater than this
4925 * are discarded. This is used in the lazy match evaluation.
4926 */
4927
4928 this.max_chain_length = 0;
4929 /* To speed up deflation, hash chains are never searched beyond this
4930 * length. A higher limit improves compression ratio but degrades the
4931 * speed.
4932 */
4933
4934 this.max_lazy_match = 0;
4935 /* Attempt to find a better match only when the current match is strictly
4936 * smaller than this value. This mechanism is used only for compression
4937 * levels >= 4.
4938 */
4939 // That's alias to max_lazy_match, don't use directly
4940 //this.max_insert_length = 0;
4941 /* Insert new strings in the hash table only if the match length is not
4942 * greater than this length. This saves time but degrades compression.
4943 * max_insert_length is used only for compression levels <= 3.
4944 */
4945
4946 this.level = 0; /* compression level (1..9) */
4947 this.strategy = 0; /* favor or force Huffman coding*/
4948
4949 this.good_match = 0;
4950 /* Use a faster search when the previous match is longer than this */
4951
4952 this.nice_match = 0; /* Stop searching when current match exceeds this */
4953
4954 /* used by trees.c: */
4955
4956 /* Didn't use ct_data typedef below to suppress compiler warning */
4957
4958 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
4959 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
4960 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
4961
4962 // Use flat array of DOUBLE size, with interleaved fata,
4963 // because JS does not support effective
4964 this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
4965 this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
4966 this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
4967 zero(this.dyn_ltree);
4968 zero(this.dyn_dtree);
4969 zero(this.bl_tree);
4970
4971 this.l_desc = null; /* desc. for literal tree */
4972 this.d_desc = null; /* desc. for distance tree */
4973 this.bl_desc = null; /* desc. for bit length tree */
4974
4975 //ush bl_count[MAX_BITS+1];
4976 this.bl_count = new utils.Buf16(MAX_BITS+1);
4977 /* number of codes at each bit length for an optimal tree */
4978
4979 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
4980 this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
4981 zero(this.heap);
4982
4983 this.heap_len = 0; /* number of elements in the heap */
4984 this.heap_max = 0; /* element of largest frequency */
4985 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
4986 * The same heap array is used to build all trees.
4987 */
4988
4989 this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
4990 zero(this.depth);
4991 /* Depth of each subtree used as tie breaker for trees of equal frequency
4992 */
4993
4994 this.l_buf = 0; /* buffer index for literals or lengths */
4995
4996 this.lit_bufsize = 0;
4997 /* Size of match buffer for literals/lengths. There are 4 reasons for
4998 * limiting lit_bufsize to 64K:
4999 * - frequencies can be kept in 16 bit counters
5000 * - if compression is not successful for the first block, all input
5001 * data is still in the window so we can still emit a stored block even
5002 * when input comes from standard input. (This can also be done for
5003 * all blocks if lit_bufsize is not greater than 32K.)
5004 * - if compression is not successful for a file smaller than 64K, we can
5005 * even emit a stored file instead of a stored block (saving 5 bytes).
5006 * This is applicable only for zip (not gzip or zlib).
5007 * - creating new Huffman trees less frequently may not provide fast
5008 * adaptation to changes in the input data statistics. (Take for
5009 * example a binary file with poorly compressible code followed by
5010 * a highly compressible string table.) Smaller buffer sizes give
5011 * fast adaptation but have of course the overhead of transmitting
5012 * trees more frequently.
5013 * - I can't count above 4
5014 */
5015
5016 this.last_lit = 0; /* running index in l_buf */
5017
5018 this.d_buf = 0;
5019 /* Buffer index for distances. To simplify the code, d_buf and l_buf have
5020 * the same number of elements. To use different lengths, an extra flag
5021 * array would be necessary.
5022 */
5023
5024 this.opt_len = 0; /* bit length of current block with optimal trees */
5025 this.static_len = 0; /* bit length of current block with static trees */
5026 this.matches = 0; /* number of string matches in current block */
5027 this.insert = 0; /* bytes at end of window left to insert */
5028
5029
5030 this.bi_buf = 0;
5031 /* Output buffer. bits are inserted starting at the bottom (least
5032 * significant bits).
5033 */
5034 this.bi_valid = 0;
5035 /* Number of valid bits in bi_buf. All bits above the last valid bit
5036 * are always zero.
5037 */
5038
5039 // Used for window memory init. We safely ignore it for JS. That makes
5040 // sense only for pointers and memory check tools.
5041 //this.high_water = 0;
5042 /* High water mark offset in window for initialized bytes -- bytes above
5043 * this are set to zero in order to avoid memory check warnings when
5044 * longest match routines access bytes past the input. This is then
5045 * updated to the new high water mark.
5046 */
5047}
5048
5049
5050function deflateResetKeep(strm) {
5051 var s;
5052
5053 if (!strm || !strm.state) {
5054 return err(strm, Z_STREAM_ERROR);
5055 }
5056
5057 strm.total_in = strm.total_out = 0;
5058 strm.data_type = Z_UNKNOWN;
5059
5060 s = strm.state;
5061 s.pending = 0;
5062 s.pending_out = 0;
5063
5064 if (s.wrap < 0) {
5065 s.wrap = -s.wrap;
5066 /* was made negative by deflate(..., Z_FINISH); */
5067 }
5068 s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
5069 strm.adler = (s.wrap === 2) ?
5070 0 // crc32(0, Z_NULL, 0)
5071 :
5072 1; // adler32(0, Z_NULL, 0)
5073 s.last_flush = Z_NO_FLUSH;
5074 trees._tr_init(s);
5075 return Z_OK;
5076}
5077
5078
5079function deflateReset(strm) {
5080 var ret = deflateResetKeep(strm);
5081 if (ret === Z_OK) {
5082 lm_init(strm.state);
5083 }
5084 return ret;
5085}
5086
5087
5088function deflateSetHeader(strm, head) {
5089 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
5090 if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
5091 strm.state.gzhead = head;
5092 return Z_OK;
5093}
5094
5095
5096function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
5097 if (!strm) { // === Z_NULL
5098 return Z_STREAM_ERROR;
5099 }
5100 var wrap = 1;
5101
5102 if (level === Z_DEFAULT_COMPRESSION) {
5103 level = 6;
5104 }
5105
5106 if (windowBits < 0) { /* suppress zlib wrapper */
5107 wrap = 0;
5108 windowBits = -windowBits;
5109 }
5110
5111 else if (windowBits > 15) {
5112 wrap = 2; /* write gzip wrapper instead */
5113 windowBits -= 16;
5114 }
5115
5116
5117 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
5118 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
5119 strategy < 0 || strategy > Z_FIXED) {
5120 return err(strm, Z_STREAM_ERROR);
5121 }
5122
5123
5124 if (windowBits === 8) {
5125 windowBits = 9;
5126 }
5127 /* until 256-byte window bug fixed */
5128
5129 var s = new DeflateState();
5130
5131 strm.state = s;
5132 s.strm = strm;
5133
5134 s.wrap = wrap;
5135 s.gzhead = null;
5136 s.w_bits = windowBits;
5137 s.w_size = 1 << s.w_bits;
5138 s.w_mask = s.w_size - 1;
5139
5140 s.hash_bits = memLevel + 7;
5141 s.hash_size = 1 << s.hash_bits;
5142 s.hash_mask = s.hash_size - 1;
5143 s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
5144
5145 s.window = new utils.Buf8(s.w_size * 2);
5146 s.head = new utils.Buf16(s.hash_size);
5147 s.prev = new utils.Buf16(s.w_size);
5148
5149 // Don't need mem init magic for JS.
5150 //s.high_water = 0; /* nothing written to s->window yet */
5151
5152 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
5153
5154 s.pending_buf_size = s.lit_bufsize * 4;
5155 s.pending_buf = new utils.Buf8(s.pending_buf_size);
5156
5157 s.d_buf = s.lit_bufsize >> 1;
5158 s.l_buf = (1 + 2) * s.lit_bufsize;
5159
5160 s.level = level;
5161 s.strategy = strategy;
5162 s.method = method;
5163
5164 return deflateReset(strm);
5165}
5166
5167function deflateInit(strm, level) {
5168 return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
5169}
5170
5171
5172function deflate(strm, flush) {
5173 var old_flush, s;
5174 var beg, val; // for gzip header write only
5175
5176 if (!strm || !strm.state ||
5177 flush > Z_BLOCK || flush < 0) {
5178 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
5179 }
5180
5181 s = strm.state;
5182
5183 if (!strm.output ||
5184 (!strm.input && strm.avail_in !== 0) ||
5185 (s.status === FINISH_STATE && flush !== Z_FINISH)) {
5186 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
5187 }
5188
5189 s.strm = strm; /* just in case */
5190 old_flush = s.last_flush;
5191 s.last_flush = flush;
5192
5193 /* Write the header */
5194 if (s.status === INIT_STATE) {
5195
5196 if (s.wrap === 2) { // GZIP header
5197 strm.adler = 0; //crc32(0L, Z_NULL, 0);
5198 put_byte(s, 31);
5199 put_byte(s, 139);
5200 put_byte(s, 8);
5201 if (!s.gzhead) { // s->gzhead == Z_NULL
5202 put_byte(s, 0);
5203 put_byte(s, 0);
5204 put_byte(s, 0);
5205 put_byte(s, 0);
5206 put_byte(s, 0);
5207 put_byte(s, s.level === 9 ? 2 :
5208 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
5209 4 : 0));
5210 put_byte(s, OS_CODE);
5211 s.status = BUSY_STATE;
5212 }
5213 else {
5214 put_byte(s, (s.gzhead.text ? 1 : 0) +
5215 (s.gzhead.hcrc ? 2 : 0) +
5216 (!s.gzhead.extra ? 0 : 4) +
5217 (!s.gzhead.name ? 0 : 8) +
5218 (!s.gzhead.comment ? 0 : 16)
5219 );
5220 put_byte(s, s.gzhead.time & 0xff);
5221 put_byte(s, (s.gzhead.time >> 8) & 0xff);
5222 put_byte(s, (s.gzhead.time >> 16) & 0xff);
5223 put_byte(s, (s.gzhead.time >> 24) & 0xff);
5224 put_byte(s, s.level === 9 ? 2 :
5225 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
5226 4 : 0));
5227 put_byte(s, s.gzhead.os & 0xff);
5228 if (s.gzhead.extra && s.gzhead.extra.length) {
5229 put_byte(s, s.gzhead.extra.length & 0xff);
5230 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
5231 }
5232 if (s.gzhead.hcrc) {
5233 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
5234 }
5235 s.gzindex = 0;
5236 s.status = EXTRA_STATE;
5237 }
5238 }
5239 else // DEFLATE header
5240 {
5241 var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
5242 var level_flags = -1;
5243
5244 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
5245 level_flags = 0;
5246 } else if (s.level < 6) {
5247 level_flags = 1;
5248 } else if (s.level === 6) {
5249 level_flags = 2;
5250 } else {
5251 level_flags = 3;
5252 }
5253 header |= (level_flags << 6);
5254 if (s.strstart !== 0) { header |= PRESET_DICT; }
5255 header += 31 - (header % 31);
5256
5257 s.status = BUSY_STATE;
5258 putShortMSB(s, header);
5259
5260 /* Save the adler32 of the preset dictionary: */
5261 if (s.strstart !== 0) {
5262 putShortMSB(s, strm.adler >>> 16);
5263 putShortMSB(s, strm.adler & 0xffff);
5264 }
5265 strm.adler = 1; // adler32(0L, Z_NULL, 0);
5266 }
5267 }
5268
5269//#ifdef GZIP
5270 if (s.status === EXTRA_STATE) {
5271 if (s.gzhead.extra/* != Z_NULL*/) {
5272 beg = s.pending; /* start of bytes to update crc */
5273
5274 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
5275 if (s.pending === s.pending_buf_size) {
5276 if (s.gzhead.hcrc && s.pending > beg) {
5277 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
5278 }
5279 flush_pending(strm);
5280 beg = s.pending;
5281 if (s.pending === s.pending_buf_size) {
5282 break;
5283 }
5284 }
5285 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
5286 s.gzindex++;
5287 }
5288 if (s.gzhead.hcrc && s.pending > beg) {
5289 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
5290 }
5291 if (s.gzindex === s.gzhead.extra.length) {
5292 s.gzindex = 0;
5293 s.status = NAME_STATE;
5294 }
5295 }
5296 else {
5297 s.status = NAME_STATE;
5298 }
5299 }
5300 if (s.status === NAME_STATE) {
5301 if (s.gzhead.name/* != Z_NULL*/) {
5302 beg = s.pending; /* start of bytes to update crc */
5303 //int val;
5304
5305 do {
5306 if (s.pending === s.pending_buf_size) {
5307 if (s.gzhead.hcrc && s.pending > beg) {
5308 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
5309 }
5310 flush_pending(strm);
5311 beg = s.pending;
5312 if (s.pending === s.pending_buf_size) {
5313 val = 1;
5314 break;
5315 }
5316 }
5317 // JS specific: little magic to add zero terminator to end of string
5318 if (s.gzindex < s.gzhead.name.length) {
5319 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
5320 } else {
5321 val = 0;
5322 }
5323 put_byte(s, val);
5324 } while (val !== 0);
5325
5326 if (s.gzhead.hcrc && s.pending > beg){
5327 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
5328 }
5329 if (val === 0) {
5330 s.gzindex = 0;
5331 s.status = COMMENT_STATE;
5332 }
5333 }
5334 else {
5335 s.status = COMMENT_STATE;
5336 }
5337 }
5338 if (s.status === COMMENT_STATE) {
5339 if (s.gzhead.comment/* != Z_NULL*/) {
5340 beg = s.pending; /* start of bytes to update crc */
5341 //int val;
5342
5343 do {
5344 if (s.pending === s.pending_buf_size) {
5345 if (s.gzhead.hcrc && s.pending > beg) {
5346 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
5347 }
5348 flush_pending(strm);
5349 beg = s.pending;
5350 if (s.pending === s.pending_buf_size) {
5351 val = 1;
5352 break;
5353 }
5354 }
5355 // JS specific: little magic to add zero terminator to end of string
5356 if (s.gzindex < s.gzhead.comment.length) {
5357 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
5358 } else {
5359 val = 0;
5360 }
5361 put_byte(s, val);
5362 } while (val !== 0);
5363
5364 if (s.gzhead.hcrc && s.pending > beg) {
5365 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
5366 }
5367 if (val === 0) {
5368 s.status = HCRC_STATE;
5369 }
5370 }
5371 else {
5372 s.status = HCRC_STATE;
5373 }
5374 }
5375 if (s.status === HCRC_STATE) {
5376 if (s.gzhead.hcrc) {
5377 if (s.pending + 2 > s.pending_buf_size) {
5378 flush_pending(strm);
5379 }
5380 if (s.pending + 2 <= s.pending_buf_size) {
5381 put_byte(s, strm.adler & 0xff);
5382 put_byte(s, (strm.adler >> 8) & 0xff);
5383 strm.adler = 0; //crc32(0L, Z_NULL, 0);
5384 s.status = BUSY_STATE;
5385 }
5386 }
5387 else {
5388 s.status = BUSY_STATE;
5389 }
5390 }
5391//#endif
5392
5393 /* Flush as much pending output as possible */
5394 if (s.pending !== 0) {
5395 flush_pending(strm);
5396 if (strm.avail_out === 0) {
5397 /* Since avail_out is 0, deflate will be called again with
5398 * more output space, but possibly with both pending and
5399 * avail_in equal to zero. There won't be anything to do,
5400 * but this is not an error situation so make sure we
5401 * return OK instead of BUF_ERROR at next call of deflate:
5402 */
5403 s.last_flush = -1;
5404 return Z_OK;
5405 }
5406
5407 /* Make sure there is something to do and avoid duplicate consecutive
5408 * flushes. For repeated and useless calls with Z_FINISH, we keep
5409 * returning Z_STREAM_END instead of Z_BUF_ERROR.
5410 */
5411 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
5412 flush !== Z_FINISH) {
5413 return err(strm, Z_BUF_ERROR);
5414 }
5415
5416 /* User must not provide more input after the first FINISH: */
5417 if (s.status === FINISH_STATE && strm.avail_in !== 0) {
5418 return err(strm, Z_BUF_ERROR);
5419 }
5420
5421 /* Start a new block or continue the current one.
5422 */
5423 if (strm.avail_in !== 0 || s.lookahead !== 0 ||
5424 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
5425 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
5426 (s.strategy === Z_RLE ? deflate_rle(s, flush) :
5427 configuration_table[s.level].func(s, flush));
5428
5429 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
5430 s.status = FINISH_STATE;
5431 }
5432 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
5433 if (strm.avail_out === 0) {
5434 s.last_flush = -1;
5435 /* avoid BUF_ERROR next call, see above */
5436 }
5437 return Z_OK;
5438 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
5439 * of deflate should use the same flush parameter to make sure
5440 * that the flush is complete. So we don't have to output an
5441 * empty block here, this will be done at next call. This also
5442 * ensures that for a very small output buffer, we emit at most
5443 * one empty block.
5444 */
5445 }
5446 if (bstate === BS_BLOCK_DONE) {
5447 if (flush === Z_PARTIAL_FLUSH) {
5448 trees._tr_align(s);
5449 }
5450 else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
5451
5452 trees._tr_stored_block(s, 0, 0, false);
5453 /* For a full flush, this empty block will be recognized
5454 * as a special marker by inflate_sync().
5455 */
5456 if (flush === Z_FULL_FLUSH) {
5457 /*** CLEAR_HASH(s); ***/ /* forget history */
5458 zero(s.head); // Fill with NIL (= 0);
5459
5460 if (s.lookahead === 0) {
5461 s.strstart = 0;
5462 s.block_start = 0;
5463 s.insert = 0;
5464 }
5465 }
5466 }
5467 flush_pending(strm);
5468 if (strm.avail_out === 0) {
5469 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
5470 return Z_OK;
5471 }
5472 }
5473 }
5474 //Assert(strm->avail_out > 0, "bug2");
5475 //if (strm.avail_out <= 0) { throw new Error("bug2");}
5476
5477 if (flush !== Z_FINISH) { return Z_OK; }
5478 if (s.wrap <= 0) { return Z_STREAM_END; }
5479
5480 /* Write the trailer */
5481 if (s.wrap === 2) {
5482 put_byte(s, strm.adler & 0xff);
5483 put_byte(s, (strm.adler >> 8) & 0xff);
5484 put_byte(s, (strm.adler >> 16) & 0xff);
5485 put_byte(s, (strm.adler >> 24) & 0xff);
5486 put_byte(s, strm.total_in & 0xff);
5487 put_byte(s, (strm.total_in >> 8) & 0xff);
5488 put_byte(s, (strm.total_in >> 16) & 0xff);
5489 put_byte(s, (strm.total_in >> 24) & 0xff);
5490 }
5491 else
5492 {
5493 putShortMSB(s, strm.adler >>> 16);
5494 putShortMSB(s, strm.adler & 0xffff);
5495 }
5496
5497 flush_pending(strm);
5498 /* If avail_out is zero, the application will call deflate again
5499 * to flush the rest.
5500 */
5501 if (s.wrap > 0) { s.wrap = -s.wrap; }
5502 /* write the trailer only once! */
5503 return s.pending !== 0 ? Z_OK : Z_STREAM_END;
5504}
5505
5506function deflateEnd(strm) {
5507 var status;
5508
5509 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
5510 return Z_STREAM_ERROR;
5511 }
5512
5513 status = strm.state.status;
5514 if (status !== INIT_STATE &&
5515 status !== EXTRA_STATE &&
5516 status !== NAME_STATE &&
5517 status !== COMMENT_STATE &&
5518 status !== HCRC_STATE &&
5519 status !== BUSY_STATE &&
5520 status !== FINISH_STATE
5521 ) {
5522 return err(strm, Z_STREAM_ERROR);
5523 }
5524
5525 strm.state = null;
5526
5527 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
5528}
5529
5530/* =========================================================================
5531 * Copy the source state to the destination state
5532 */
5533//function deflateCopy(dest, source) {
5534//
5535//}
5536
5537exports.deflateInit = deflateInit;
5538exports.deflateInit2 = deflateInit2;
5539exports.deflateReset = deflateReset;
5540exports.deflateResetKeep = deflateResetKeep;
5541exports.deflateSetHeader = deflateSetHeader;
5542exports.deflate = deflate;
5543exports.deflateEnd = deflateEnd;
5544exports.deflateInfo = 'pako deflate (from Nodeca project)';
5545
5546/* Not implemented
5547exports.deflateBound = deflateBound;
5548exports.deflateCopy = deflateCopy;
5549exports.deflateSetDictionary = deflateSetDictionary;
5550exports.deflateParams = deflateParams;
5551exports.deflatePending = deflatePending;
5552exports.deflatePrime = deflatePrime;
5553exports.deflateTune = deflateTune;
5554*/
5555},{"../utils/common":27,"./adler32":29,"./crc32":31,"./messages":37,"./trees":38}],33:[function(_dereq_,module,exports){
5556'use strict';
5557
5558
5559function GZheader() {
5560 /* true if compressed data believed to be text */
5561 this.text = 0;
5562 /* modification time */
5563 this.time = 0;
5564 /* extra flags (not used when writing a gzip file) */
5565 this.xflags = 0;
5566 /* operating system */
5567 this.os = 0;
5568 /* pointer to extra field or Z_NULL if none */
5569 this.extra = null;
5570 /* extra field length (valid if extra != Z_NULL) */
5571 this.extra_len = 0; // Actually, we don't need it in JS,
5572 // but leave for few code modifications
5573
5574 //
5575 // Setup limits is not necessary because in js we should not preallocate memory
5576 // for inflate use constant limit in 65536 bytes
5577 //
5578
5579 /* space at extra (only when reading header) */
5580 // this.extra_max = 0;
5581 /* pointer to zero-terminated file name or Z_NULL */
5582 this.name = '';
5583 /* space at name (only when reading header) */
5584 // this.name_max = 0;
5585 /* pointer to zero-terminated comment or Z_NULL */
5586 this.comment = '';
5587 /* space at comment (only when reading header) */
5588 // this.comm_max = 0;
5589 /* true if there was or will be a header crc */
5590 this.hcrc = 0;
5591 /* true when done reading gzip header (not used when writing a gzip file) */
5592 this.done = false;
5593}
5594
5595module.exports = GZheader;
5596},{}],34:[function(_dereq_,module,exports){
5597'use strict';
5598
5599// See state defs from inflate.js
5600var BAD = 30; /* got a data error -- remain here until reset */
5601var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
5602
5603/*
5604 Decode literal, length, and distance codes and write out the resulting
5605 literal and match bytes until either not enough input or output is
5606 available, an end-of-block is encountered, or a data error is encountered.
5607 When large enough input and output buffers are supplied to inflate(), for
5608 example, a 16K input buffer and a 64K output buffer, more than 95% of the
5609 inflate execution time is spent in this routine.
5610
5611 Entry assumptions:
5612
5613 state.mode === LEN
5614 strm.avail_in >= 6
5615 strm.avail_out >= 258
5616 start >= strm.avail_out
5617 state.bits < 8
5618
5619 On return, state.mode is one of:
5620
5621 LEN -- ran out of enough output space or enough available input
5622 TYPE -- reached end of block code, inflate() to interpret next block
5623 BAD -- error in block data
5624
5625 Notes:
5626
5627 - The maximum input bits used by a length/distance pair is 15 bits for the
5628 length code, 5 bits for the length extra, 15 bits for the distance code,
5629 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
5630 Therefore if strm.avail_in >= 6, then there is enough input to avoid
5631 checking for available input while decoding.
5632
5633 - The maximum bytes that a single length/distance pair can output is 258
5634 bytes, which is the maximum length that can be coded. inflate_fast()
5635 requires strm.avail_out >= 258 for each loop to avoid checking for
5636 output space.
5637 */
5638module.exports = function inflate_fast(strm, start) {
5639 var state;
5640 var _in; /* local strm.input */
5641 var last; /* have enough input while in < last */
5642 var _out; /* local strm.output */
5643 var beg; /* inflate()'s initial strm.output */
5644 var end; /* while out < end, enough space available */
5645//#ifdef INFLATE_STRICT
5646 var dmax; /* maximum distance from zlib header */
5647//#endif
5648 var wsize; /* window size or zero if not using window */
5649 var whave; /* valid bytes in the window */
5650 var wnext; /* window write index */
5651 var window; /* allocated sliding window, if wsize != 0 */
5652 var hold; /* local strm.hold */
5653 var bits; /* local strm.bits */
5654 var lcode; /* local strm.lencode */
5655 var dcode; /* local strm.distcode */
5656 var lmask; /* mask for first level of length codes */
5657 var dmask; /* mask for first level of distance codes */
5658 var here; /* retrieved table entry */
5659 var op; /* code bits, operation, extra bits, or */
5660 /* window position, window bytes to copy */
5661 var len; /* match length, unused bytes */
5662 var dist; /* match distance */
5663 var from; /* where to copy match from */
5664 var from_source;
5665
5666
5667 var input, output; // JS specific, because we have no pointers
5668
5669 /* copy state to local variables */
5670 state = strm.state;
5671 //here = state.here;
5672 _in = strm.next_in;
5673 input = strm.input;
5674 last = _in + (strm.avail_in - 5);
5675 _out = strm.next_out;
5676 output = strm.output;
5677 beg = _out - (start - strm.avail_out);
5678 end = _out + (strm.avail_out - 257);
5679//#ifdef INFLATE_STRICT
5680 dmax = state.dmax;
5681//#endif
5682 wsize = state.wsize;
5683 whave = state.whave;
5684 wnext = state.wnext;
5685 window = state.window;
5686 hold = state.hold;
5687 bits = state.bits;
5688 lcode = state.lencode;
5689 dcode = state.distcode;
5690 lmask = (1 << state.lenbits) - 1;
5691 dmask = (1 << state.distbits) - 1;
5692
5693
5694 /* decode literals and length/distances until end-of-block or not enough
5695 input data or output space */
5696
5697 top:
5698 do {
5699 if (bits < 15) {
5700 hold += input[_in++] << bits;
5701 bits += 8;
5702 hold += input[_in++] << bits;
5703 bits += 8;
5704 }
5705
5706 here = lcode[hold & lmask];
5707
5708 dolen:
5709 for (;;) { // Goto emulation
5710 op = here >>> 24/*here.bits*/;
5711 hold >>>= op;
5712 bits -= op;
5713 op = (here >>> 16) & 0xff/*here.op*/;
5714 if (op === 0) { /* literal */
5715 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
5716 // "inflate: literal '%c'\n" :
5717 // "inflate: literal 0x%02x\n", here.val));
5718 output[_out++] = here & 0xffff/*here.val*/;
5719 }
5720 else if (op & 16) { /* length base */
5721 len = here & 0xffff/*here.val*/;
5722 op &= 15; /* number of extra bits */
5723 if (op) {
5724 if (bits < op) {
5725 hold += input[_in++] << bits;
5726 bits += 8;
5727 }
5728 len += hold & ((1 << op) - 1);
5729 hold >>>= op;
5730 bits -= op;
5731 }
5732 //Tracevv((stderr, "inflate: length %u\n", len));
5733 if (bits < 15) {
5734 hold += input[_in++] << bits;
5735 bits += 8;
5736 hold += input[_in++] << bits;
5737 bits += 8;
5738 }
5739 here = dcode[hold & dmask];
5740
5741 dodist:
5742 for (;;) { // goto emulation
5743 op = here >>> 24/*here.bits*/;
5744 hold >>>= op;
5745 bits -= op;
5746 op = (here >>> 16) & 0xff/*here.op*/;
5747
5748 if (op & 16) { /* distance base */
5749 dist = here & 0xffff/*here.val*/;
5750 op &= 15; /* number of extra bits */
5751 if (bits < op) {
5752 hold += input[_in++] << bits;
5753 bits += 8;
5754 if (bits < op) {
5755 hold += input[_in++] << bits;
5756 bits += 8;
5757 }
5758 }
5759 dist += hold & ((1 << op) - 1);
5760//#ifdef INFLATE_STRICT
5761 if (dist > dmax) {
5762 strm.msg = 'invalid distance too far back';
5763 state.mode = BAD;
5764 break top;
5765 }
5766//#endif
5767 hold >>>= op;
5768 bits -= op;
5769 //Tracevv((stderr, "inflate: distance %u\n", dist));
5770 op = _out - beg; /* max distance in output */
5771 if (dist > op) { /* see if copy from window */
5772 op = dist - op; /* distance back in window */
5773 if (op > whave) {
5774 if (state.sane) {
5775 strm.msg = 'invalid distance too far back';
5776 state.mode = BAD;
5777 break top;
5778 }
5779
5780// (!) This block is disabled in zlib defailts,
5781// don't enable it for binary compatibility
5782//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
5783// if (len <= op - whave) {
5784// do {
5785// output[_out++] = 0;
5786// } while (--len);
5787// continue top;
5788// }
5789// len -= op - whave;
5790// do {
5791// output[_out++] = 0;
5792// } while (--op > whave);
5793// if (op === 0) {
5794// from = _out - dist;
5795// do {
5796// output[_out++] = output[from++];
5797// } while (--len);
5798// continue top;
5799// }
5800//#endif
5801 }
5802 from = 0; // window index
5803 from_source = window;
5804 if (wnext === 0) { /* very common case */
5805 from += wsize - op;
5806 if (op < len) { /* some from window */
5807 len -= op;
5808 do {
5809 output[_out++] = window[from++];
5810 } while (--op);
5811 from = _out - dist; /* rest from output */
5812 from_source = output;
5813 }
5814 }
5815 else if (wnext < op) { /* wrap around window */
5816 from += wsize + wnext - op;
5817 op -= wnext;
5818 if (op < len) { /* some from end of window */
5819 len -= op;
5820 do {
5821 output[_out++] = window[from++];
5822 } while (--op);
5823 from = 0;
5824 if (wnext < len) { /* some from start of window */
5825 op = wnext;
5826 len -= op;
5827 do {
5828 output[_out++] = window[from++];
5829 } while (--op);
5830 from = _out - dist; /* rest from output */
5831 from_source = output;
5832 }
5833 }
5834 }
5835 else { /* contiguous in window */
5836 from += wnext - op;
5837 if (op < len) { /* some from window */
5838 len -= op;
5839 do {
5840 output[_out++] = window[from++];
5841 } while (--op);
5842 from = _out - dist; /* rest from output */
5843 from_source = output;
5844 }
5845 }
5846 while (len > 2) {
5847 output[_out++] = from_source[from++];
5848 output[_out++] = from_source[from++];
5849 output[_out++] = from_source[from++];
5850 len -= 3;
5851 }
5852 if (len) {
5853 output[_out++] = from_source[from++];
5854 if (len > 1) {
5855 output[_out++] = from_source[from++];
5856 }
5857 }
5858 }
5859 else {
5860 from = _out - dist; /* copy direct from output */
5861 do { /* minimum length is three */
5862 output[_out++] = output[from++];
5863 output[_out++] = output[from++];
5864 output[_out++] = output[from++];
5865 len -= 3;
5866 } while (len > 2);
5867 if (len) {
5868 output[_out++] = output[from++];
5869 if (len > 1) {
5870 output[_out++] = output[from++];
5871 }
5872 }
5873 }
5874 }
5875 else if ((op & 64) === 0) { /* 2nd level distance code */
5876 here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
5877 continue dodist;
5878 }
5879 else {
5880 strm.msg = 'invalid distance code';
5881 state.mode = BAD;
5882 break top;
5883 }
5884
5885 break; // need to emulate goto via "continue"
5886 }
5887 }
5888 else if ((op & 64) === 0) { /* 2nd level length code */
5889 here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
5890 continue dolen;
5891 }
5892 else if (op & 32) { /* end-of-block */
5893 //Tracevv((stderr, "inflate: end of block\n"));
5894 state.mode = TYPE;
5895 break top;
5896 }
5897 else {
5898 strm.msg = 'invalid literal/length code';
5899 state.mode = BAD;
5900 break top;
5901 }
5902
5903 break; // need to emulate goto via "continue"
5904 }
5905 } while (_in < last && _out < end);
5906
5907 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
5908 len = bits >> 3;
5909 _in -= len;
5910 bits -= len << 3;
5911 hold &= (1 << bits) - 1;
5912
5913 /* update state and return */
5914 strm.next_in = _in;
5915 strm.next_out = _out;
5916 strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
5917 strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
5918 state.hold = hold;
5919 state.bits = bits;
5920 return;
5921};
5922
5923},{}],35:[function(_dereq_,module,exports){
5924'use strict';
5925
5926
5927var utils = _dereq_('../utils/common');
5928var adler32 = _dereq_('./adler32');
5929var crc32 = _dereq_('./crc32');
5930var inflate_fast = _dereq_('./inffast');
5931var inflate_table = _dereq_('./inftrees');
5932
5933var CODES = 0;
5934var LENS = 1;
5935var DISTS = 2;
5936
5937/* Public constants ==========================================================*/
5938/* ===========================================================================*/
5939
5940
5941/* Allowed flush values; see deflate() and inflate() below for details */
5942//var Z_NO_FLUSH = 0;
5943//var Z_PARTIAL_FLUSH = 1;
5944//var Z_SYNC_FLUSH = 2;
5945//var Z_FULL_FLUSH = 3;
5946var Z_FINISH = 4;
5947var Z_BLOCK = 5;
5948var Z_TREES = 6;
5949
5950
5951/* Return codes for the compression/decompression functions. Negative values
5952 * are errors, positive values are used for special but normal events.
5953 */
5954var Z_OK = 0;
5955var Z_STREAM_END = 1;
5956var Z_NEED_DICT = 2;
5957//var Z_ERRNO = -1;
5958var Z_STREAM_ERROR = -2;
5959var Z_DATA_ERROR = -3;
5960var Z_MEM_ERROR = -4;
5961var Z_BUF_ERROR = -5;
5962//var Z_VERSION_ERROR = -6;
5963
5964/* The deflate compression method */
5965var Z_DEFLATED = 8;
5966
5967
5968/* STATES ====================================================================*/
5969/* ===========================================================================*/
5970
5971
5972var HEAD = 1; /* i: waiting for magic header */
5973var FLAGS = 2; /* i: waiting for method and flags (gzip) */
5974var TIME = 3; /* i: waiting for modification time (gzip) */
5975var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
5976var EXLEN = 5; /* i: waiting for extra length (gzip) */
5977var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
5978var NAME = 7; /* i: waiting for end of file name (gzip) */
5979var COMMENT = 8; /* i: waiting for end of comment (gzip) */
5980var HCRC = 9; /* i: waiting for header crc (gzip) */
5981var DICTID = 10; /* i: waiting for dictionary check value */
5982var DICT = 11; /* waiting for inflateSetDictionary() call */
5983var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
5984var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
5985var STORED = 14; /* i: waiting for stored size (length and complement) */
5986var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
5987var COPY = 16; /* i/o: waiting for input or output to copy stored block */
5988var TABLE = 17; /* i: waiting for dynamic block table lengths */
5989var LENLENS = 18; /* i: waiting for code length code lengths */
5990var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
5991var LEN_ = 20; /* i: same as LEN below, but only first time in */
5992var LEN = 21; /* i: waiting for length/lit/eob code */
5993var LENEXT = 22; /* i: waiting for length extra bits */
5994var DIST = 23; /* i: waiting for distance code */
5995var DISTEXT = 24; /* i: waiting for distance extra bits */
5996var MATCH = 25; /* o: waiting for output space to copy string */
5997var LIT = 26; /* o: waiting for output space to write literal */
5998var CHECK = 27; /* i: waiting for 32-bit check value */
5999var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
6000var DONE = 29; /* finished check, done -- remain here until reset */
6001var BAD = 30; /* got a data error -- remain here until reset */
6002var MEM = 31; /* got an inflate() memory error -- remain here until reset */
6003var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
6004
6005/* ===========================================================================*/
6006
6007
6008
6009var ENOUGH_LENS = 852;
6010var ENOUGH_DISTS = 592;
6011//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
6012
6013var MAX_WBITS = 15;
6014/* 32K LZ77 window */
6015var DEF_WBITS = MAX_WBITS;
6016
6017
6018function ZSWAP32(q) {
6019 return (((q >>> 24) & 0xff) +
6020 ((q >>> 8) & 0xff00) +
6021 ((q & 0xff00) << 8) +
6022 ((q & 0xff) << 24));
6023}
6024
6025
6026function InflateState() {
6027 this.mode = 0; /* current inflate mode */
6028 this.last = false; /* true if processing last block */
6029 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
6030 this.havedict = false; /* true if dictionary provided */
6031 this.flags = 0; /* gzip header method and flags (0 if zlib) */
6032 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
6033 this.check = 0; /* protected copy of check value */
6034 this.total = 0; /* protected copy of output count */
6035 // TODO: may be {}
6036 this.head = null; /* where to save gzip header information */
6037
6038 /* sliding window */
6039 this.wbits = 0; /* log base 2 of requested window size */
6040 this.wsize = 0; /* window size or zero if not using window */
6041 this.whave = 0; /* valid bytes in the window */
6042 this.wnext = 0; /* window write index */
6043 this.window = null; /* allocated sliding window, if needed */
6044
6045 /* bit accumulator */
6046 this.hold = 0; /* input bit accumulator */
6047 this.bits = 0; /* number of bits in "in" */
6048
6049 /* for string and stored block copying */
6050 this.length = 0; /* literal or length of data to copy */
6051 this.offset = 0; /* distance back to copy string from */
6052
6053 /* for table and code decoding */
6054 this.extra = 0; /* extra bits needed */
6055
6056 /* fixed and dynamic code tables */
6057 this.lencode = null; /* starting table for length/literal codes */
6058 this.distcode = null; /* starting table for distance codes */
6059 this.lenbits = 0; /* index bits for lencode */
6060 this.distbits = 0; /* index bits for distcode */
6061
6062 /* dynamic table building */
6063 this.ncode = 0; /* number of code length code lengths */
6064 this.nlen = 0; /* number of length code lengths */
6065 this.ndist = 0; /* number of distance code lengths */
6066 this.have = 0; /* number of code lengths in lens[] */
6067 this.next = null; /* next available space in codes[] */
6068
6069 this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
6070 this.work = new utils.Buf16(288); /* work area for code table building */
6071
6072 /*
6073 because we don't have pointers in js, we use lencode and distcode directly
6074 as buffers so we don't need codes
6075 */
6076 //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
6077 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
6078 this.distdyn = null; /* dynamic table for distance codes (JS specific) */
6079 this.sane = 0; /* if false, allow invalid distance too far */
6080 this.back = 0; /* bits back of last unprocessed length/lit */
6081 this.was = 0; /* initial length of match */
6082}
6083
6084function inflateResetKeep(strm) {
6085 var state;
6086
6087 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
6088 state = strm.state;
6089 strm.total_in = strm.total_out = state.total = 0;
6090 strm.msg = ''; /*Z_NULL*/
6091 if (state.wrap) { /* to support ill-conceived Java test suite */
6092 strm.adler = state.wrap & 1;
6093 }
6094 state.mode = HEAD;
6095 state.last = 0;
6096 state.havedict = 0;
6097 state.dmax = 32768;
6098 state.head = null/*Z_NULL*/;
6099 state.hold = 0;
6100 state.bits = 0;
6101 //state.lencode = state.distcode = state.next = state.codes;
6102 state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
6103 state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
6104
6105 state.sane = 1;
6106 state.back = -1;
6107 //Tracev((stderr, "inflate: reset\n"));
6108 return Z_OK;
6109}
6110
6111function inflateReset(strm) {
6112 var state;
6113
6114 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
6115 state = strm.state;
6116 state.wsize = 0;
6117 state.whave = 0;
6118 state.wnext = 0;
6119 return inflateResetKeep(strm);
6120
6121}
6122
6123function inflateReset2(strm, windowBits) {
6124 var wrap;
6125 var state;
6126
6127 /* get the state */
6128 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
6129 state = strm.state;
6130
6131 /* extract wrap request from windowBits parameter */
6132 if (windowBits < 0) {
6133 wrap = 0;
6134 windowBits = -windowBits;
6135 }
6136 else {
6137 wrap = (windowBits >> 4) + 1;
6138 if (windowBits < 48) {
6139 windowBits &= 15;
6140 }
6141 }
6142
6143 /* set number of window bits, free window if different */
6144 if (windowBits && (windowBits < 8 || windowBits > 15)) {
6145 return Z_STREAM_ERROR;
6146 }
6147 if (state.window !== null && state.wbits !== windowBits) {
6148 state.window = null;
6149 }
6150
6151 /* update state and reset the rest of it */
6152 state.wrap = wrap;
6153 state.wbits = windowBits;
6154 return inflateReset(strm);
6155}
6156
6157function inflateInit2(strm, windowBits) {
6158 var ret;
6159 var state;
6160
6161 if (!strm) { return Z_STREAM_ERROR; }
6162 //strm.msg = Z_NULL; /* in case we return an error */
6163
6164 state = new InflateState();
6165
6166 //if (state === Z_NULL) return Z_MEM_ERROR;
6167 //Tracev((stderr, "inflate: allocated\n"));
6168 strm.state = state;
6169 state.window = null/*Z_NULL*/;
6170 ret = inflateReset2(strm, windowBits);
6171 if (ret !== Z_OK) {
6172 strm.state = null/*Z_NULL*/;
6173 }
6174 return ret;
6175}
6176
6177function inflateInit(strm) {
6178 return inflateInit2(strm, DEF_WBITS);
6179}
6180
6181
6182/*
6183 Return state with length and distance decoding tables and index sizes set to
6184 fixed code decoding. Normally this returns fixed tables from inffixed.h.
6185 If BUILDFIXED is defined, then instead this routine builds the tables the
6186 first time it's called, and returns those tables the first time and
6187 thereafter. This reduces the size of the code by about 2K bytes, in
6188 exchange for a little execution time. However, BUILDFIXED should not be
6189 used for threaded applications, since the rewriting of the tables and virgin
6190 may not be thread-safe.
6191 */
6192var virgin = true;
6193
6194var lenfix, distfix; // We have no pointers in JS, so keep tables separate
6195
6196function fixedtables(state) {
6197 /* build fixed huffman tables if first call (may not be thread safe) */
6198 if (virgin) {
6199 var sym;
6200
6201 lenfix = new utils.Buf32(512);
6202 distfix = new utils.Buf32(32);
6203
6204 /* literal/length table */
6205 sym = 0;
6206 while (sym < 144) { state.lens[sym++] = 8; }
6207 while (sym < 256) { state.lens[sym++] = 9; }
6208 while (sym < 280) { state.lens[sym++] = 7; }
6209 while (sym < 288) { state.lens[sym++] = 8; }
6210
6211 inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
6212
6213 /* distance table */
6214 sym = 0;
6215 while (sym < 32) { state.lens[sym++] = 5; }
6216
6217 inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
6218
6219 /* do this just once */
6220 virgin = false;
6221 }
6222
6223 state.lencode = lenfix;
6224 state.lenbits = 9;
6225 state.distcode = distfix;
6226 state.distbits = 5;
6227}
6228
6229
6230/*
6231 Update the window with the last wsize (normally 32K) bytes written before
6232 returning. If window does not exist yet, create it. This is only called
6233 when a window is already in use, or when output has been written during this
6234 inflate call, but the end of the deflate stream has not been reached yet.
6235 It is also called to create a window for dictionary data when a dictionary
6236 is loaded.
6237
6238 Providing output buffers larger than 32K to inflate() should provide a speed
6239 advantage, since only the last 32K of output is copied to the sliding window
6240 upon return from inflate(), and since all distances after the first 32K of
6241 output will fall in the output data, making match copies simpler and faster.
6242 The advantage may be dependent on the size of the processor's data caches.
6243 */
6244function updatewindow(strm, src, end, copy) {
6245 var dist;
6246 var state = strm.state;
6247
6248 /* if it hasn't been done already, allocate space for the window */
6249 if (state.window === null) {
6250 state.wsize = 1 << state.wbits;
6251 state.wnext = 0;
6252 state.whave = 0;
6253
6254 state.window = new utils.Buf8(state.wsize);
6255 }
6256
6257 /* copy state->wsize or less output bytes into the circular window */
6258 if (copy >= state.wsize) {
6259 utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
6260 state.wnext = 0;
6261 state.whave = state.wsize;
6262 }
6263 else {
6264 dist = state.wsize - state.wnext;
6265 if (dist > copy) {
6266 dist = copy;
6267 }
6268 //zmemcpy(state->window + state->wnext, end - copy, dist);
6269 utils.arraySet(state.window,src, end - copy, dist, state.wnext);
6270 copy -= dist;
6271 if (copy) {
6272 //zmemcpy(state->window, end - copy, copy);
6273 utils.arraySet(state.window,src, end - copy, copy, 0);
6274 state.wnext = copy;
6275 state.whave = state.wsize;
6276 }
6277 else {
6278 state.wnext += dist;
6279 if (state.wnext === state.wsize) { state.wnext = 0; }
6280 if (state.whave < state.wsize) { state.whave += dist; }
6281 }
6282 }
6283 return 0;
6284}
6285
6286function inflate(strm, flush) {
6287 var state;
6288 var input, output; // input/output buffers
6289 var next; /* next input INDEX */
6290 var put; /* next output INDEX */
6291 var have, left; /* available input and output */
6292 var hold; /* bit buffer */
6293 var bits; /* bits in bit buffer */
6294 var _in, _out; /* save starting available input and output */
6295 var copy; /* number of stored or match bytes to copy */
6296 var from; /* where to copy match bytes from */
6297 var from_source;
6298 var here = 0; /* current decoding table entry */
6299 var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
6300 //var last; /* parent table entry */
6301 var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
6302 var len; /* length to copy for repeats, bits to drop */
6303 var ret; /* return code */
6304 var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
6305 var opts;
6306
6307 var n; // temporary var for NEED_BITS
6308
6309 var order = /* permutation of code lengths */
6310 [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
6311
6312
6313 if (!strm || !strm.state || !strm.output ||
6314 (!strm.input && strm.avail_in !== 0)) {
6315 return Z_STREAM_ERROR;
6316 }
6317
6318 state = strm.state;
6319 if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
6320
6321
6322 //--- LOAD() ---
6323 put = strm.next_out;
6324 output = strm.output;
6325 left = strm.avail_out;
6326 next = strm.next_in;
6327 input = strm.input;
6328 have = strm.avail_in;
6329 hold = state.hold;
6330 bits = state.bits;
6331 //---
6332
6333 _in = have;
6334 _out = left;
6335 ret = Z_OK;
6336
6337 inf_leave: // goto emulation
6338 for (;;) {
6339 switch (state.mode) {
6340 case HEAD:
6341 if (state.wrap === 0) {
6342 state.mode = TYPEDO;
6343 break;
6344 }
6345 //=== NEEDBITS(16);
6346 while (bits < 16) {
6347 if (have === 0) { break inf_leave; }
6348 have--;
6349 hold += input[next++] << bits;
6350 bits += 8;
6351 }
6352 //===//
6353 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
6354 state.check = 0/*crc32(0L, Z_NULL, 0)*/;
6355 //=== CRC2(state.check, hold);
6356 hbuf[0] = hold & 0xff;
6357 hbuf[1] = (hold >>> 8) & 0xff;
6358 state.check = crc32(state.check, hbuf, 2, 0);
6359 //===//
6360
6361 //=== INITBITS();
6362 hold = 0;
6363 bits = 0;
6364 //===//
6365 state.mode = FLAGS;
6366 break;
6367 }
6368 state.flags = 0; /* expect zlib header */
6369 if (state.head) {
6370 state.head.done = false;
6371 }
6372 if (!(state.wrap & 1) || /* check if zlib header allowed */
6373 (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
6374 strm.msg = 'incorrect header check';
6375 state.mode = BAD;
6376 break;
6377 }
6378 if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
6379 strm.msg = 'unknown compression method';
6380 state.mode = BAD;
6381 break;
6382 }
6383 //--- DROPBITS(4) ---//
6384 hold >>>= 4;
6385 bits -= 4;
6386 //---//
6387 len = (hold & 0x0f)/*BITS(4)*/ + 8;
6388 if (state.wbits === 0) {
6389 state.wbits = len;
6390 }
6391 else if (len > state.wbits) {
6392 strm.msg = 'invalid window size';
6393 state.mode = BAD;
6394 break;
6395 }
6396 state.dmax = 1 << len;
6397 //Tracev((stderr, "inflate: zlib header ok\n"));
6398 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
6399 state.mode = hold & 0x200 ? DICTID : TYPE;
6400 //=== INITBITS();
6401 hold = 0;
6402 bits = 0;
6403 //===//
6404 break;
6405 case FLAGS:
6406 //=== NEEDBITS(16); */
6407 while (bits < 16) {
6408 if (have === 0) { break inf_leave; }
6409 have--;
6410 hold += input[next++] << bits;
6411 bits += 8;
6412 }
6413 //===//
6414 state.flags = hold;
6415 if ((state.flags & 0xff) !== Z_DEFLATED) {
6416 strm.msg = 'unknown compression method';
6417 state.mode = BAD;
6418 break;
6419 }
6420 if (state.flags & 0xe000) {
6421 strm.msg = 'unknown header flags set';
6422 state.mode = BAD;
6423 break;
6424 }
6425 if (state.head) {
6426 state.head.text = ((hold >> 8) & 1);
6427 }
6428 if (state.flags & 0x0200) {
6429 //=== CRC2(state.check, hold);
6430 hbuf[0] = hold & 0xff;
6431 hbuf[1] = (hold >>> 8) & 0xff;
6432 state.check = crc32(state.check, hbuf, 2, 0);
6433 //===//
6434 }
6435 //=== INITBITS();
6436 hold = 0;
6437 bits = 0;
6438 //===//
6439 state.mode = TIME;
6440 /* falls through */
6441 case TIME:
6442 //=== NEEDBITS(32); */
6443 while (bits < 32) {
6444 if (have === 0) { break inf_leave; }
6445 have--;
6446 hold += input[next++] << bits;
6447 bits += 8;
6448 }
6449 //===//
6450 if (state.head) {
6451 state.head.time = hold;
6452 }
6453 if (state.flags & 0x0200) {
6454 //=== CRC4(state.check, hold)
6455 hbuf[0] = hold & 0xff;
6456 hbuf[1] = (hold >>> 8) & 0xff;
6457 hbuf[2] = (hold >>> 16) & 0xff;
6458 hbuf[3] = (hold >>> 24) & 0xff;
6459 state.check = crc32(state.check, hbuf, 4, 0);
6460 //===
6461 }
6462 //=== INITBITS();
6463 hold = 0;
6464 bits = 0;
6465 //===//
6466 state.mode = OS;
6467 /* falls through */
6468 case OS:
6469 //=== NEEDBITS(16); */
6470 while (bits < 16) {
6471 if (have === 0) { break inf_leave; }
6472 have--;
6473 hold += input[next++] << bits;
6474 bits += 8;
6475 }
6476 //===//
6477 if (state.head) {
6478 state.head.xflags = (hold & 0xff);
6479 state.head.os = (hold >> 8);
6480 }
6481 if (state.flags & 0x0200) {
6482 //=== CRC2(state.check, hold);
6483 hbuf[0] = hold & 0xff;
6484 hbuf[1] = (hold >>> 8) & 0xff;
6485 state.check = crc32(state.check, hbuf, 2, 0);
6486 //===//
6487 }
6488 //=== INITBITS();
6489 hold = 0;
6490 bits = 0;
6491 //===//
6492 state.mode = EXLEN;
6493 /* falls through */
6494 case EXLEN:
6495 if (state.flags & 0x0400) {
6496 //=== NEEDBITS(16); */
6497 while (bits < 16) {
6498 if (have === 0) { break inf_leave; }
6499 have--;
6500 hold += input[next++] << bits;
6501 bits += 8;
6502 }
6503 //===//
6504 state.length = hold;
6505 if (state.head) {
6506 state.head.extra_len = hold;
6507 }
6508 if (state.flags & 0x0200) {
6509 //=== CRC2(state.check, hold);
6510 hbuf[0] = hold & 0xff;
6511 hbuf[1] = (hold >>> 8) & 0xff;
6512 state.check = crc32(state.check, hbuf, 2, 0);
6513 //===//
6514 }
6515 //=== INITBITS();
6516 hold = 0;
6517 bits = 0;
6518 //===//
6519 }
6520 else if (state.head) {
6521 state.head.extra = null/*Z_NULL*/;
6522 }
6523 state.mode = EXTRA;
6524 /* falls through */
6525 case EXTRA:
6526 if (state.flags & 0x0400) {
6527 copy = state.length;
6528 if (copy > have) { copy = have; }
6529 if (copy) {
6530 if (state.head) {
6531 len = state.head.extra_len - state.length;
6532 if (!state.head.extra) {
6533 // Use untyped array for more conveniend processing later
6534 state.head.extra = new Array(state.head.extra_len);
6535 }
6536 utils.arraySet(
6537 state.head.extra,
6538 input,
6539 next,
6540 // extra field is limited to 65536 bytes
6541 // - no need for additional size check
6542 copy,
6543 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
6544 len
6545 );
6546 //zmemcpy(state.head.extra + len, next,
6547 // len + copy > state.head.extra_max ?
6548 // state.head.extra_max - len : copy);
6549 }
6550 if (state.flags & 0x0200) {
6551 state.check = crc32(state.check, input, copy, next);
6552 }
6553 have -= copy;
6554 next += copy;
6555 state.length -= copy;
6556 }
6557 if (state.length) { break inf_leave; }
6558 }
6559 state.length = 0;
6560 state.mode = NAME;
6561 /* falls through */
6562 case NAME:
6563 if (state.flags & 0x0800) {
6564 if (have === 0) { break inf_leave; }
6565 copy = 0;
6566 do {
6567 // TODO: 2 or 1 bytes?
6568 len = input[next + copy++];
6569 /* use constant limit because in js we should not preallocate memory */
6570 if (state.head && len &&
6571 (state.length < 65536 /*state.head.name_max*/)) {
6572 state.head.name += String.fromCharCode(len);
6573 }
6574 } while (len && copy < have);
6575
6576 if (state.flags & 0x0200) {
6577 state.check = crc32(state.check, input, copy, next);
6578 }
6579 have -= copy;
6580 next += copy;
6581 if (len) { break inf_leave; }
6582 }
6583 else if (state.head) {
6584 state.head.name = null;
6585 }
6586 state.length = 0;
6587 state.mode = COMMENT;
6588 /* falls through */
6589 case COMMENT:
6590 if (state.flags & 0x1000) {
6591 if (have === 0) { break inf_leave; }
6592 copy = 0;
6593 do {
6594 len = input[next + copy++];
6595 /* use constant limit because in js we should not preallocate memory */
6596 if (state.head && len &&
6597 (state.length < 65536 /*state.head.comm_max*/)) {
6598 state.head.comment += String.fromCharCode(len);
6599 }
6600 } while (len && copy < have);
6601 if (state.flags & 0x0200) {
6602 state.check = crc32(state.check, input, copy, next);
6603 }
6604 have -= copy;
6605 next += copy;
6606 if (len) { break inf_leave; }
6607 }
6608 else if (state.head) {
6609 state.head.comment = null;
6610 }
6611 state.mode = HCRC;
6612 /* falls through */
6613 case HCRC:
6614 if (state.flags & 0x0200) {
6615 //=== NEEDBITS(16); */
6616 while (bits < 16) {
6617 if (have === 0) { break inf_leave; }
6618 have--;
6619 hold += input[next++] << bits;
6620 bits += 8;
6621 }
6622 //===//
6623 if (hold !== (state.check & 0xffff)) {
6624 strm.msg = 'header crc mismatch';
6625 state.mode = BAD;
6626 break;
6627 }
6628 //=== INITBITS();
6629 hold = 0;
6630 bits = 0;
6631 //===//
6632 }
6633 if (state.head) {
6634 state.head.hcrc = ((state.flags >> 9) & 1);
6635 state.head.done = true;
6636 }
6637 strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
6638 state.mode = TYPE;
6639 break;
6640 case DICTID:
6641 //=== NEEDBITS(32); */
6642 while (bits < 32) {
6643 if (have === 0) { break inf_leave; }
6644 have--;
6645 hold += input[next++] << bits;
6646 bits += 8;
6647 }
6648 //===//
6649 strm.adler = state.check = ZSWAP32(hold);
6650 //=== INITBITS();
6651 hold = 0;
6652 bits = 0;
6653 //===//
6654 state.mode = DICT;
6655 /* falls through */
6656 case DICT:
6657 if (state.havedict === 0) {
6658 //--- RESTORE() ---
6659 strm.next_out = put;
6660 strm.avail_out = left;
6661 strm.next_in = next;
6662 strm.avail_in = have;
6663 state.hold = hold;
6664 state.bits = bits;
6665 //---
6666 return Z_NEED_DICT;
6667 }
6668 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
6669 state.mode = TYPE;
6670 /* falls through */
6671 case TYPE:
6672 if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
6673 /* falls through */
6674 case TYPEDO:
6675 if (state.last) {
6676 //--- BYTEBITS() ---//
6677 hold >>>= bits & 7;
6678 bits -= bits & 7;
6679 //---//
6680 state.mode = CHECK;
6681 break;
6682 }
6683 //=== NEEDBITS(3); */
6684 while (bits < 3) {
6685 if (have === 0) { break inf_leave; }
6686 have--;
6687 hold += input[next++] << bits;
6688 bits += 8;
6689 }
6690 //===//
6691 state.last = (hold & 0x01)/*BITS(1)*/;
6692 //--- DROPBITS(1) ---//
6693 hold >>>= 1;
6694 bits -= 1;
6695 //---//
6696
6697 switch ((hold & 0x03)/*BITS(2)*/) {
6698 case 0: /* stored block */
6699 //Tracev((stderr, "inflate: stored block%s\n",
6700 // state.last ? " (last)" : ""));
6701 state.mode = STORED;
6702 break;
6703 case 1: /* fixed block */
6704 fixedtables(state);
6705 //Tracev((stderr, "inflate: fixed codes block%s\n",
6706 // state.last ? " (last)" : ""));
6707 state.mode = LEN_; /* decode codes */
6708 if (flush === Z_TREES) {
6709 //--- DROPBITS(2) ---//
6710 hold >>>= 2;
6711 bits -= 2;
6712 //---//
6713 break inf_leave;
6714 }
6715 break;
6716 case 2: /* dynamic block */
6717 //Tracev((stderr, "inflate: dynamic codes block%s\n",
6718 // state.last ? " (last)" : ""));
6719 state.mode = TABLE;
6720 break;
6721 case 3:
6722 strm.msg = 'invalid block type';
6723 state.mode = BAD;
6724 }
6725 //--- DROPBITS(2) ---//
6726 hold >>>= 2;
6727 bits -= 2;
6728 //---//
6729 break;
6730 case STORED:
6731 //--- BYTEBITS() ---// /* go to byte boundary */
6732 hold >>>= bits & 7;
6733 bits -= bits & 7;
6734 //---//
6735 //=== NEEDBITS(32); */
6736 while (bits < 32) {
6737 if (have === 0) { break inf_leave; }
6738 have--;
6739 hold += input[next++] << bits;
6740 bits += 8;
6741 }
6742 //===//
6743 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
6744 strm.msg = 'invalid stored block lengths';
6745 state.mode = BAD;
6746 break;
6747 }
6748 state.length = hold & 0xffff;
6749 //Tracev((stderr, "inflate: stored length %u\n",
6750 // state.length));
6751 //=== INITBITS();
6752 hold = 0;
6753 bits = 0;
6754 //===//
6755 state.mode = COPY_;
6756 if (flush === Z_TREES) { break inf_leave; }
6757 /* falls through */
6758 case COPY_:
6759 state.mode = COPY;
6760 /* falls through */
6761 case COPY:
6762 copy = state.length;
6763 if (copy) {
6764 if (copy > have) { copy = have; }
6765 if (copy > left) { copy = left; }
6766 if (copy === 0) { break inf_leave; }
6767 //--- zmemcpy(put, next, copy); ---
6768 utils.arraySet(output, input, next, copy, put);
6769 //---//
6770 have -= copy;
6771 next += copy;
6772 left -= copy;
6773 put += copy;
6774 state.length -= copy;
6775 break;
6776 }
6777 //Tracev((stderr, "inflate: stored end\n"));
6778 state.mode = TYPE;
6779 break;
6780 case TABLE:
6781 //=== NEEDBITS(14); */
6782 while (bits < 14) {
6783 if (have === 0) { break inf_leave; }
6784 have--;
6785 hold += input[next++] << bits;
6786 bits += 8;
6787 }
6788 //===//
6789 state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
6790 //--- DROPBITS(5) ---//
6791 hold >>>= 5;
6792 bits -= 5;
6793 //---//
6794 state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
6795 //--- DROPBITS(5) ---//
6796 hold >>>= 5;
6797 bits -= 5;
6798 //---//
6799 state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
6800 //--- DROPBITS(4) ---//
6801 hold >>>= 4;
6802 bits -= 4;
6803 //---//
6804//#ifndef PKZIP_BUG_WORKAROUND
6805 if (state.nlen > 286 || state.ndist > 30) {
6806 strm.msg = 'too many length or distance symbols';
6807 state.mode = BAD;
6808 break;
6809 }
6810//#endif
6811 //Tracev((stderr, "inflate: table sizes ok\n"));
6812 state.have = 0;
6813 state.mode = LENLENS;
6814 /* falls through */
6815 case LENLENS:
6816 while (state.have < state.ncode) {
6817 //=== NEEDBITS(3);
6818 while (bits < 3) {
6819 if (have === 0) { break inf_leave; }
6820 have--;
6821 hold += input[next++] << bits;
6822 bits += 8;
6823 }
6824 //===//
6825 state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
6826 //--- DROPBITS(3) ---//
6827 hold >>>= 3;
6828 bits -= 3;
6829 //---//
6830 }
6831 while (state.have < 19) {
6832 state.lens[order[state.have++]] = 0;
6833 }
6834 // We have separate tables & no pointers. 2 commented lines below not needed.
6835 //state.next = state.codes;
6836 //state.lencode = state.next;
6837 // Switch to use dynamic table
6838 state.lencode = state.lendyn;
6839 state.lenbits = 7;
6840
6841 opts = {bits: state.lenbits};
6842 ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
6843 state.lenbits = opts.bits;
6844
6845 if (ret) {
6846 strm.msg = 'invalid code lengths set';
6847 state.mode = BAD;
6848 break;
6849 }
6850 //Tracev((stderr, "inflate: code lengths ok\n"));
6851 state.have = 0;
6852 state.mode = CODELENS;
6853 /* falls through */
6854 case CODELENS:
6855 while (state.have < state.nlen + state.ndist) {
6856 for (;;) {
6857 here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
6858 here_bits = here >>> 24;
6859 here_op = (here >>> 16) & 0xff;
6860 here_val = here & 0xffff;
6861
6862 if ((here_bits) <= bits) { break; }
6863 //--- PULLBYTE() ---//
6864 if (have === 0) { break inf_leave; }
6865 have--;
6866 hold += input[next++] << bits;
6867 bits += 8;
6868 //---//
6869 }
6870 if (here_val < 16) {
6871 //--- DROPBITS(here.bits) ---//
6872 hold >>>= here_bits;
6873 bits -= here_bits;
6874 //---//
6875 state.lens[state.have++] = here_val;
6876 }
6877 else {
6878 if (here_val === 16) {
6879 //=== NEEDBITS(here.bits + 2);
6880 n = here_bits + 2;
6881 while (bits < n) {
6882 if (have === 0) { break inf_leave; }
6883 have--;
6884 hold += input[next++] << bits;
6885 bits += 8;
6886 }
6887 //===//
6888 //--- DROPBITS(here.bits) ---//
6889 hold >>>= here_bits;
6890 bits -= here_bits;
6891 //---//
6892 if (state.have === 0) {
6893 strm.msg = 'invalid bit length repeat';
6894 state.mode = BAD;
6895 break;
6896 }
6897 len = state.lens[state.have - 1];
6898 copy = 3 + (hold & 0x03);//BITS(2);
6899 //--- DROPBITS(2) ---//
6900 hold >>>= 2;
6901 bits -= 2;
6902 //---//
6903 }
6904 else if (here_val === 17) {
6905 //=== NEEDBITS(here.bits + 3);
6906 n = here_bits + 3;
6907 while (bits < n) {
6908 if (have === 0) { break inf_leave; }
6909 have--;
6910 hold += input[next++] << bits;
6911 bits += 8;
6912 }
6913 //===//
6914 //--- DROPBITS(here.bits) ---//
6915 hold >>>= here_bits;
6916 bits -= here_bits;
6917 //---//
6918 len = 0;
6919 copy = 3 + (hold & 0x07);//BITS(3);
6920 //--- DROPBITS(3) ---//
6921 hold >>>= 3;
6922 bits -= 3;
6923 //---//
6924 }
6925 else {
6926 //=== NEEDBITS(here.bits + 7);
6927 n = here_bits + 7;
6928 while (bits < n) {
6929 if (have === 0) { break inf_leave; }
6930 have--;
6931 hold += input[next++] << bits;
6932 bits += 8;
6933 }
6934 //===//
6935 //--- DROPBITS(here.bits) ---//
6936 hold >>>= here_bits;
6937 bits -= here_bits;
6938 //---//
6939 len = 0;
6940 copy = 11 + (hold & 0x7f);//BITS(7);
6941 //--- DROPBITS(7) ---//
6942 hold >>>= 7;
6943 bits -= 7;
6944 //---//
6945 }
6946 if (state.have + copy > state.nlen + state.ndist) {
6947 strm.msg = 'invalid bit length repeat';
6948 state.mode = BAD;
6949 break;
6950 }
6951 while (copy--) {
6952 state.lens[state.have++] = len;
6953 }
6954 }
6955 }
6956
6957 /* handle error breaks in while */
6958 if (state.mode === BAD) { break; }
6959
6960 /* check for end-of-block code (better have one) */
6961 if (state.lens[256] === 0) {
6962 strm.msg = 'invalid code -- missing end-of-block';
6963 state.mode = BAD;
6964 break;
6965 }
6966
6967 /* build code tables -- note: do not change the lenbits or distbits
6968 values here (9 and 6) without reading the comments in inftrees.h
6969 concerning the ENOUGH constants, which depend on those values */
6970 state.lenbits = 9;
6971
6972 opts = {bits: state.lenbits};
6973 ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
6974 // We have separate tables & no pointers. 2 commented lines below not needed.
6975 // state.next_index = opts.table_index;
6976 state.lenbits = opts.bits;
6977 // state.lencode = state.next;
6978
6979 if (ret) {
6980 strm.msg = 'invalid literal/lengths set';
6981 state.mode = BAD;
6982 break;
6983 }
6984
6985 state.distbits = 6;
6986 //state.distcode.copy(state.codes);
6987 // Switch to use dynamic table
6988 state.distcode = state.distdyn;
6989 opts = {bits: state.distbits};
6990 ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
6991 // We have separate tables & no pointers. 2 commented lines below not needed.
6992 // state.next_index = opts.table_index;
6993 state.distbits = opts.bits;
6994 // state.distcode = state.next;
6995
6996 if (ret) {
6997 strm.msg = 'invalid distances set';
6998 state.mode = BAD;
6999 break;
7000 }
7001 //Tracev((stderr, 'inflate: codes ok\n'));
7002 state.mode = LEN_;
7003 if (flush === Z_TREES) { break inf_leave; }
7004 /* falls through */
7005 case LEN_:
7006 state.mode = LEN;
7007 /* falls through */
7008 case LEN:
7009 if (have >= 6 && left >= 258) {
7010 //--- RESTORE() ---
7011 strm.next_out = put;
7012 strm.avail_out = left;
7013 strm.next_in = next;
7014 strm.avail_in = have;
7015 state.hold = hold;
7016 state.bits = bits;
7017 //---
7018 inflate_fast(strm, _out);
7019 //--- LOAD() ---
7020 put = strm.next_out;
7021 output = strm.output;
7022 left = strm.avail_out;
7023 next = strm.next_in;
7024 input = strm.input;
7025 have = strm.avail_in;
7026 hold = state.hold;
7027 bits = state.bits;
7028 //---
7029
7030 if (state.mode === TYPE) {
7031 state.back = -1;
7032 }
7033 break;
7034 }
7035 state.back = 0;
7036 for (;;) {
7037 here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
7038 here_bits = here >>> 24;
7039 here_op = (here >>> 16) & 0xff;
7040 here_val = here & 0xffff;
7041
7042 if (here_bits <= bits) { break; }
7043 //--- PULLBYTE() ---//
7044 if (have === 0) { break inf_leave; }
7045 have--;
7046 hold += input[next++] << bits;
7047 bits += 8;
7048 //---//
7049 }
7050 if (here_op && (here_op & 0xf0) === 0) {
7051 last_bits = here_bits;
7052 last_op = here_op;
7053 last_val = here_val;
7054 for (;;) {
7055 here = state.lencode[last_val +
7056 ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
7057 here_bits = here >>> 24;
7058 here_op = (here >>> 16) & 0xff;
7059 here_val = here & 0xffff;
7060
7061 if ((last_bits + here_bits) <= bits) { break; }
7062 //--- PULLBYTE() ---//
7063 if (have === 0) { break inf_leave; }
7064 have--;
7065 hold += input[next++] << bits;
7066 bits += 8;
7067 //---//
7068 }
7069 //--- DROPBITS(last.bits) ---//
7070 hold >>>= last_bits;
7071 bits -= last_bits;
7072 //---//
7073 state.back += last_bits;
7074 }
7075 //--- DROPBITS(here.bits) ---//
7076 hold >>>= here_bits;
7077 bits -= here_bits;
7078 //---//
7079 state.back += here_bits;
7080 state.length = here_val;
7081 if (here_op === 0) {
7082 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
7083 // "inflate: literal '%c'\n" :
7084 // "inflate: literal 0x%02x\n", here.val));
7085 state.mode = LIT;
7086 break;
7087 }
7088 if (here_op & 32) {
7089 //Tracevv((stderr, "inflate: end of block\n"));
7090 state.back = -1;
7091 state.mode = TYPE;
7092 break;
7093 }
7094 if (here_op & 64) {
7095 strm.msg = 'invalid literal/length code';
7096 state.mode = BAD;
7097 break;
7098 }
7099 state.extra = here_op & 15;
7100 state.mode = LENEXT;
7101 /* falls through */
7102 case LENEXT:
7103 if (state.extra) {
7104 //=== NEEDBITS(state.extra);
7105 n = state.extra;
7106 while (bits < n) {
7107 if (have === 0) { break inf_leave; }
7108 have--;
7109 hold += input[next++] << bits;
7110 bits += 8;
7111 }
7112 //===//
7113 state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
7114 //--- DROPBITS(state.extra) ---//
7115 hold >>>= state.extra;
7116 bits -= state.extra;
7117 //---//
7118 state.back += state.extra;
7119 }
7120 //Tracevv((stderr, "inflate: length %u\n", state.length));
7121 state.was = state.length;
7122 state.mode = DIST;
7123 /* falls through */
7124 case DIST:
7125 for (;;) {
7126 here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
7127 here_bits = here >>> 24;
7128 here_op = (here >>> 16) & 0xff;
7129 here_val = here & 0xffff;
7130
7131 if ((here_bits) <= bits) { break; }
7132 //--- PULLBYTE() ---//
7133 if (have === 0) { break inf_leave; }
7134 have--;
7135 hold += input[next++] << bits;
7136 bits += 8;
7137 //---//
7138 }
7139 if ((here_op & 0xf0) === 0) {
7140 last_bits = here_bits;
7141 last_op = here_op;
7142 last_val = here_val;
7143 for (;;) {
7144 here = state.distcode[last_val +
7145 ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
7146 here_bits = here >>> 24;
7147 here_op = (here >>> 16) & 0xff;
7148 here_val = here & 0xffff;
7149
7150 if ((last_bits + here_bits) <= bits) { break; }
7151 //--- PULLBYTE() ---//
7152 if (have === 0) { break inf_leave; }
7153 have--;
7154 hold += input[next++] << bits;
7155 bits += 8;
7156 //---//
7157 }
7158 //--- DROPBITS(last.bits) ---//
7159 hold >>>= last_bits;
7160 bits -= last_bits;
7161 //---//
7162 state.back += last_bits;
7163 }
7164 //--- DROPBITS(here.bits) ---//
7165 hold >>>= here_bits;
7166 bits -= here_bits;
7167 //---//
7168 state.back += here_bits;
7169 if (here_op & 64) {
7170 strm.msg = 'invalid distance code';
7171 state.mode = BAD;
7172 break;
7173 }
7174 state.offset = here_val;
7175 state.extra = (here_op) & 15;
7176 state.mode = DISTEXT;
7177 /* falls through */
7178 case DISTEXT:
7179 if (state.extra) {
7180 //=== NEEDBITS(state.extra);
7181 n = state.extra;
7182 while (bits < n) {
7183 if (have === 0) { break inf_leave; }
7184 have--;
7185 hold += input[next++] << bits;
7186 bits += 8;
7187 }
7188 //===//
7189 state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
7190 //--- DROPBITS(state.extra) ---//
7191 hold >>>= state.extra;
7192 bits -= state.extra;
7193 //---//
7194 state.back += state.extra;
7195 }
7196//#ifdef INFLATE_STRICT
7197 if (state.offset > state.dmax) {
7198 strm.msg = 'invalid distance too far back';
7199 state.mode = BAD;
7200 break;
7201 }
7202//#endif
7203 //Tracevv((stderr, "inflate: distance %u\n", state.offset));
7204 state.mode = MATCH;
7205 /* falls through */
7206 case MATCH:
7207 if (left === 0) { break inf_leave; }
7208 copy = _out - left;
7209 if (state.offset > copy) { /* copy from window */
7210 copy = state.offset - copy;
7211 if (copy > state.whave) {
7212 if (state.sane) {
7213 strm.msg = 'invalid distance too far back';
7214 state.mode = BAD;
7215 break;
7216 }
7217// (!) This block is disabled in zlib defailts,
7218// don't enable it for binary compatibility
7219//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
7220// Trace((stderr, "inflate.c too far\n"));
7221// copy -= state.whave;
7222// if (copy > state.length) { copy = state.length; }
7223// if (copy > left) { copy = left; }
7224// left -= copy;
7225// state.length -= copy;
7226// do {
7227// output[put++] = 0;
7228// } while (--copy);
7229// if (state.length === 0) { state.mode = LEN; }
7230// break;
7231//#endif
7232 }
7233 if (copy > state.wnext) {
7234 copy -= state.wnext;
7235 from = state.wsize - copy;
7236 }
7237 else {
7238 from = state.wnext - copy;
7239 }
7240 if (copy > state.length) { copy = state.length; }
7241 from_source = state.window;
7242 }
7243 else { /* copy from output */
7244 from_source = output;
7245 from = put - state.offset;
7246 copy = state.length;
7247 }
7248 if (copy > left) { copy = left; }
7249 left -= copy;
7250 state.length -= copy;
7251 do {
7252 output[put++] = from_source[from++];
7253 } while (--copy);
7254 if (state.length === 0) { state.mode = LEN; }
7255 break;
7256 case LIT:
7257 if (left === 0) { break inf_leave; }
7258 output[put++] = state.length;
7259 left--;
7260 state.mode = LEN;
7261 break;
7262 case CHECK:
7263 if (state.wrap) {
7264 //=== NEEDBITS(32);
7265 while (bits < 32) {
7266 if (have === 0) { break inf_leave; }
7267 have--;
7268 // Use '|' insdead of '+' to make sure that result is signed
7269 hold |= input[next++] << bits;
7270 bits += 8;
7271 }
7272 //===//
7273 _out -= left;
7274 strm.total_out += _out;
7275 state.total += _out;
7276 if (_out) {
7277 strm.adler = state.check =
7278 /*UPDATE(state.check, put - _out, _out);*/
7279 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
7280
7281 }
7282 _out = left;
7283 // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
7284 if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
7285 strm.msg = 'incorrect data check';
7286 state.mode = BAD;
7287 break;
7288 }
7289 //=== INITBITS();
7290 hold = 0;
7291 bits = 0;
7292 //===//
7293 //Tracev((stderr, "inflate: check matches trailer\n"));
7294 }
7295 state.mode = LENGTH;
7296 /* falls through */
7297 case LENGTH:
7298 if (state.wrap && state.flags) {
7299 //=== NEEDBITS(32);
7300 while (bits < 32) {
7301 if (have === 0) { break inf_leave; }
7302 have--;
7303 hold += input[next++] << bits;
7304 bits += 8;
7305 }
7306 //===//
7307 if (hold !== (state.total & 0xffffffff)) {
7308 strm.msg = 'incorrect length check';
7309 state.mode = BAD;
7310 break;
7311 }
7312 //=== INITBITS();
7313 hold = 0;
7314 bits = 0;
7315 //===//
7316 //Tracev((stderr, "inflate: length matches trailer\n"));
7317 }
7318 state.mode = DONE;
7319 /* falls through */
7320 case DONE:
7321 ret = Z_STREAM_END;
7322 break inf_leave;
7323 case BAD:
7324 ret = Z_DATA_ERROR;
7325 break inf_leave;
7326 case MEM:
7327 return Z_MEM_ERROR;
7328 case SYNC:
7329 /* falls through */
7330 default:
7331 return Z_STREAM_ERROR;
7332 }
7333 }
7334
7335 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
7336
7337 /*
7338 Return from inflate(), updating the total counts and the check value.
7339 If there was no progress during the inflate() call, return a buffer
7340 error. Call updatewindow() to create and/or update the window state.
7341 Note: a memory error from inflate() is non-recoverable.
7342 */
7343
7344 //--- RESTORE() ---
7345 strm.next_out = put;
7346 strm.avail_out = left;
7347 strm.next_in = next;
7348 strm.avail_in = have;
7349 state.hold = hold;
7350 state.bits = bits;
7351 //---
7352
7353 if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
7354 (state.mode < CHECK || flush !== Z_FINISH))) {
7355 if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
7356 state.mode = MEM;
7357 return Z_MEM_ERROR;
7358 }
7359 }
7360 _in -= strm.avail_in;
7361 _out -= strm.avail_out;
7362 strm.total_in += _in;
7363 strm.total_out += _out;
7364 state.total += _out;
7365 if (state.wrap && _out) {
7366 strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
7367 (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
7368 }
7369 strm.data_type = state.bits + (state.last ? 64 : 0) +
7370 (state.mode === TYPE ? 128 : 0) +
7371 (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
7372 if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
7373 ret = Z_BUF_ERROR;
7374 }
7375 return ret;
7376}
7377
7378function inflateEnd(strm) {
7379
7380 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
7381 return Z_STREAM_ERROR;
7382 }
7383
7384 var state = strm.state;
7385 if (state.window) {
7386 state.window = null;
7387 }
7388 strm.state = null;
7389 return Z_OK;
7390}
7391
7392function inflateGetHeader(strm, head) {
7393 var state;
7394
7395 /* check state */
7396 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
7397 state = strm.state;
7398 if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
7399
7400 /* save header structure */
7401 state.head = head;
7402 head.done = false;
7403 return Z_OK;
7404}
7405
7406
7407exports.inflateReset = inflateReset;
7408exports.inflateReset2 = inflateReset2;
7409exports.inflateResetKeep = inflateResetKeep;
7410exports.inflateInit = inflateInit;
7411exports.inflateInit2 = inflateInit2;
7412exports.inflate = inflate;
7413exports.inflateEnd = inflateEnd;
7414exports.inflateGetHeader = inflateGetHeader;
7415exports.inflateInfo = 'pako inflate (from Nodeca project)';
7416
7417/* Not implemented
7418exports.inflateCopy = inflateCopy;
7419exports.inflateGetDictionary = inflateGetDictionary;
7420exports.inflateMark = inflateMark;
7421exports.inflatePrime = inflatePrime;
7422exports.inflateSetDictionary = inflateSetDictionary;
7423exports.inflateSync = inflateSync;
7424exports.inflateSyncPoint = inflateSyncPoint;
7425exports.inflateUndermine = inflateUndermine;
7426*/
7427},{"../utils/common":27,"./adler32":29,"./crc32":31,"./inffast":34,"./inftrees":36}],36:[function(_dereq_,module,exports){
7428'use strict';
7429
7430
7431var utils = _dereq_('../utils/common');
7432
7433var MAXBITS = 15;
7434var ENOUGH_LENS = 852;
7435var ENOUGH_DISTS = 592;
7436//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
7437
7438var CODES = 0;
7439var LENS = 1;
7440var DISTS = 2;
7441
7442var lbase = [ /* Length codes 257..285 base */
7443 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
7444 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
7445];
7446
7447var lext = [ /* Length codes 257..285 extra */
7448 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
7449 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
7450];
7451
7452var dbase = [ /* Distance codes 0..29 base */
7453 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
7454 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
7455 8193, 12289, 16385, 24577, 0, 0
7456];
7457
7458var dext = [ /* Distance codes 0..29 extra */
7459 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
7460 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
7461 28, 28, 29, 29, 64, 64
7462];
7463
7464module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
7465{
7466 var bits = opts.bits;
7467 //here = opts.here; /* table entry for duplication */
7468
7469 var len = 0; /* a code's length in bits */
7470 var sym = 0; /* index of code symbols */
7471 var min = 0, max = 0; /* minimum and maximum code lengths */
7472 var root = 0; /* number of index bits for root table */
7473 var curr = 0; /* number of index bits for current table */
7474 var drop = 0; /* code bits to drop for sub-table */
7475 var left = 0; /* number of prefix codes available */
7476 var used = 0; /* code entries in table used */
7477 var huff = 0; /* Huffman code */
7478 var incr; /* for incrementing code, index */
7479 var fill; /* index for replicating entries */
7480 var low; /* low bits for current root entry */
7481 var mask; /* mask for low root bits */
7482 var next; /* next available space in table */
7483 var base = null; /* base value table to use */
7484 var base_index = 0;
7485// var shoextra; /* extra bits table to use */
7486 var end; /* use base and extra for symbol > end */
7487 var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
7488 var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
7489 var extra = null;
7490 var extra_index = 0;
7491
7492 var here_bits, here_op, here_val;
7493
7494 /*
7495 Process a set of code lengths to create a canonical Huffman code. The
7496 code lengths are lens[0..codes-1]. Each length corresponds to the
7497 symbols 0..codes-1. The Huffman code is generated by first sorting the
7498 symbols by length from short to long, and retaining the symbol order
7499 for codes with equal lengths. Then the code starts with all zero bits
7500 for the first code of the shortest length, and the codes are integer
7501 increments for the same length, and zeros are appended as the length
7502 increases. For the deflate format, these bits are stored backwards
7503 from their more natural integer increment ordering, and so when the
7504 decoding tables are built in the large loop below, the integer codes
7505 are incremented backwards.
7506
7507 This routine assumes, but does not check, that all of the entries in
7508 lens[] are in the range 0..MAXBITS. The caller must assure this.
7509 1..MAXBITS is interpreted as that code length. zero means that that
7510 symbol does not occur in this code.
7511
7512 The codes are sorted by computing a count of codes for each length,
7513 creating from that a table of starting indices for each length in the
7514 sorted table, and then entering the symbols in order in the sorted
7515 table. The sorted table is work[], with that space being provided by
7516 the caller.
7517
7518 The length counts are used for other purposes as well, i.e. finding
7519 the minimum and maximum length codes, determining if there are any
7520 codes at all, checking for a valid set of lengths, and looking ahead
7521 at length counts to determine sub-table sizes when building the
7522 decoding tables.
7523 */
7524
7525 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
7526 for (len = 0; len <= MAXBITS; len++) {
7527 count[len] = 0;
7528 }
7529 for (sym = 0; sym < codes; sym++) {
7530 count[lens[lens_index + sym]]++;
7531 }
7532
7533 /* bound code lengths, force root to be within code lengths */
7534 root = bits;
7535 for (max = MAXBITS; max >= 1; max--) {
7536 if (count[max] !== 0) { break; }
7537 }
7538 if (root > max) {
7539 root = max;
7540 }
7541 if (max === 0) { /* no symbols to code at all */
7542 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
7543 //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
7544 //table.val[opts.table_index++] = 0; //here.val = (var short)0;
7545 table[table_index++] = (1 << 24) | (64 << 16) | 0;
7546
7547
7548 //table.op[opts.table_index] = 64;
7549 //table.bits[opts.table_index] = 1;
7550 //table.val[opts.table_index++] = 0;
7551 table[table_index++] = (1 << 24) | (64 << 16) | 0;
7552
7553 opts.bits = 1;
7554 return 0; /* no symbols, but wait for decoding to report error */
7555 }
7556 for (min = 1; min < max; min++) {
7557 if (count[min] !== 0) { break; }
7558 }
7559 if (root < min) {
7560 root = min;
7561 }
7562
7563 /* check for an over-subscribed or incomplete set of lengths */
7564 left = 1;
7565 for (len = 1; len <= MAXBITS; len++) {
7566 left <<= 1;
7567 left -= count[len];
7568 if (left < 0) {
7569 return -1;
7570 } /* over-subscribed */
7571 }
7572 if (left > 0 && (type === CODES || max !== 1)) {
7573 return -1; /* incomplete set */
7574 }
7575
7576 /* generate offsets into symbol table for each length for sorting */
7577 offs[1] = 0;
7578 for (len = 1; len < MAXBITS; len++) {
7579 offs[len + 1] = offs[len] + count[len];
7580 }
7581
7582 /* sort symbols by length, by symbol order within each length */
7583 for (sym = 0; sym < codes; sym++) {
7584 if (lens[lens_index + sym] !== 0) {
7585 work[offs[lens[lens_index + sym]]++] = sym;
7586 }
7587 }
7588
7589 /*
7590 Create and fill in decoding tables. In this loop, the table being
7591 filled is at next and has curr index bits. The code being used is huff
7592 with length len. That code is converted to an index by dropping drop
7593 bits off of the bottom. For codes where len is less than drop + curr,
7594 those top drop + curr - len bits are incremented through all values to
7595 fill the table with replicated entries.
7596
7597 root is the number of index bits for the root table. When len exceeds
7598 root, sub-tables are created pointed to by the root entry with an index
7599 of the low root bits of huff. This is saved in low to check for when a
7600 new sub-table should be started. drop is zero when the root table is
7601 being filled, and drop is root when sub-tables are being filled.
7602
7603 When a new sub-table is needed, it is necessary to look ahead in the
7604 code lengths to determine what size sub-table is needed. The length
7605 counts are used for this, and so count[] is decremented as codes are
7606 entered in the tables.
7607
7608 used keeps track of how many table entries have been allocated from the
7609 provided *table space. It is checked for LENS and DIST tables against
7610 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
7611 the initial root table size constants. See the comments in inftrees.h
7612 for more information.
7613
7614 sym increments through all symbols, and the loop terminates when
7615 all codes of length max, i.e. all codes, have been processed. This
7616 routine permits incomplete codes, so another loop after this one fills
7617 in the rest of the decoding tables with invalid code markers.
7618 */
7619
7620 /* set up for code type */
7621 // poor man optimization - use if-else instead of switch,
7622 // to avoid deopts in old v8
7623 if (type === CODES) {
7624 base = extra = work; /* dummy value--not used */
7625 end = 19;
7626 } else if (type === LENS) {
7627 base = lbase;
7628 base_index -= 257;
7629 extra = lext;
7630 extra_index -= 257;
7631 end = 256;
7632 } else { /* DISTS */
7633 base = dbase;
7634 extra = dext;
7635 end = -1;
7636 }
7637
7638 /* initialize opts for loop */
7639 huff = 0; /* starting code */
7640 sym = 0; /* starting code symbol */
7641 len = min; /* starting code length */
7642 next = table_index; /* current table to fill in */
7643 curr = root; /* current table index bits */
7644 drop = 0; /* current bits to drop from code for index */
7645 low = -1; /* trigger new sub-table when len > root */
7646 used = 1 << root; /* use root table entries */
7647 mask = used - 1; /* mask for comparing low */
7648
7649 /* check available table space */
7650 if ((type === LENS && used > ENOUGH_LENS) ||
7651 (type === DISTS && used > ENOUGH_DISTS)) {
7652 return 1;
7653 }
7654
7655 var i=0;
7656 /* process all codes and make table entries */
7657 for (;;) {
7658 i++;
7659 /* create table entry */
7660 here_bits = len - drop;
7661 if (work[sym] < end) {
7662 here_op = 0;
7663 here_val = work[sym];
7664 }
7665 else if (work[sym] > end) {
7666 here_op = extra[extra_index + work[sym]];
7667 here_val = base[base_index + work[sym]];
7668 }
7669 else {
7670 here_op = 32 + 64; /* end of block */
7671 here_val = 0;
7672 }
7673
7674 /* replicate for those indices with low len bits equal to huff */
7675 incr = 1 << (len - drop);
7676 fill = 1 << curr;
7677 min = fill; /* save offset to next table */
7678 do {
7679 fill -= incr;
7680 table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
7681 } while (fill !== 0);
7682
7683 /* backwards increment the len-bit code huff */
7684 incr = 1 << (len - 1);
7685 while (huff & incr) {
7686 incr >>= 1;
7687 }
7688 if (incr !== 0) {
7689 huff &= incr - 1;
7690 huff += incr;
7691 } else {
7692 huff = 0;
7693 }
7694
7695 /* go to next symbol, update count, len */
7696 sym++;
7697 if (--count[len] === 0) {
7698 if (len === max) { break; }
7699 len = lens[lens_index + work[sym]];
7700 }
7701
7702 /* create new sub-table if needed */
7703 if (len > root && (huff & mask) !== low) {
7704 /* if first time, transition to sub-tables */
7705 if (drop === 0) {
7706 drop = root;
7707 }
7708
7709 /* increment past last table */
7710 next += min; /* here min is 1 << curr */
7711
7712 /* determine length of next table */
7713 curr = len - drop;
7714 left = 1 << curr;
7715 while (curr + drop < max) {
7716 left -= count[curr + drop];
7717 if (left <= 0) { break; }
7718 curr++;
7719 left <<= 1;
7720 }
7721
7722 /* check for enough space */
7723 used += 1 << curr;
7724 if ((type === LENS && used > ENOUGH_LENS) ||
7725 (type === DISTS && used > ENOUGH_DISTS)) {
7726 return 1;
7727 }
7728
7729 /* point entry in root table to sub-table */
7730 low = huff & mask;
7731 /*table.op[low] = curr;
7732 table.bits[low] = root;
7733 table.val[low] = next - opts.table_index;*/
7734 table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
7735 }
7736 }
7737
7738 /* fill in remaining table entry if code is incomplete (guaranteed to have
7739 at most one remaining entry, since if the code is incomplete, the
7740 maximum code length that was allowed to get this far is one bit) */
7741 if (huff !== 0) {
7742 //table.op[next + huff] = 64; /* invalid code marker */
7743 //table.bits[next + huff] = len - drop;
7744 //table.val[next + huff] = 0;
7745 table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
7746 }
7747
7748 /* set return parameters */
7749 //opts.table_index += used;
7750 opts.bits = root;
7751 return 0;
7752};
7753
7754},{"../utils/common":27}],37:[function(_dereq_,module,exports){
7755'use strict';
7756
7757module.exports = {
7758 '2': 'need dictionary', /* Z_NEED_DICT 2 */
7759 '1': 'stream end', /* Z_STREAM_END 1 */
7760 '0': '', /* Z_OK 0 */
7761 '-1': 'file error', /* Z_ERRNO (-1) */
7762 '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
7763 '-3': 'data error', /* Z_DATA_ERROR (-3) */
7764 '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
7765 '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
7766 '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
7767};
7768},{}],38:[function(_dereq_,module,exports){
7769'use strict';
7770
7771
7772var utils = _dereq_('../utils/common');
7773
7774/* Public constants ==========================================================*/
7775/* ===========================================================================*/
7776
7777
7778//var Z_FILTERED = 1;
7779//var Z_HUFFMAN_ONLY = 2;
7780//var Z_RLE = 3;
7781var Z_FIXED = 4;
7782//var Z_DEFAULT_STRATEGY = 0;
7783
7784/* Possible values of the data_type field (though see inflate()) */
7785var Z_BINARY = 0;
7786var Z_TEXT = 1;
7787//var Z_ASCII = 1; // = Z_TEXT
7788var Z_UNKNOWN = 2;
7789
7790/*============================================================================*/
7791
7792
7793function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
7794
7795// From zutil.h
7796
7797var STORED_BLOCK = 0;
7798var STATIC_TREES = 1;
7799var DYN_TREES = 2;
7800/* The three kinds of block type */
7801
7802var MIN_MATCH = 3;
7803var MAX_MATCH = 258;
7804/* The minimum and maximum match lengths */
7805
7806// From deflate.h
7807/* ===========================================================================
7808 * Internal compression state.
7809 */
7810
7811var LENGTH_CODES = 29;
7812/* number of length codes, not counting the special END_BLOCK code */
7813
7814var LITERALS = 256;
7815/* number of literal bytes 0..255 */
7816
7817var L_CODES = LITERALS + 1 + LENGTH_CODES;
7818/* number of Literal or Length codes, including the END_BLOCK code */
7819
7820var D_CODES = 30;
7821/* number of distance codes */
7822
7823var BL_CODES = 19;
7824/* number of codes used to transfer the bit lengths */
7825
7826var HEAP_SIZE = 2*L_CODES + 1;
7827/* maximum heap size */
7828
7829var MAX_BITS = 15;
7830/* All codes must not exceed MAX_BITS bits */
7831
7832var Buf_size = 16;
7833/* size of bit buffer in bi_buf */
7834
7835
7836/* ===========================================================================
7837 * Constants
7838 */
7839
7840var MAX_BL_BITS = 7;
7841/* Bit length codes must not exceed MAX_BL_BITS bits */
7842
7843var END_BLOCK = 256;
7844/* end of block literal code */
7845
7846var REP_3_6 = 16;
7847/* repeat previous bit length 3-6 times (2 bits of repeat count) */
7848
7849var REPZ_3_10 = 17;
7850/* repeat a zero length 3-10 times (3 bits of repeat count) */
7851
7852var REPZ_11_138 = 18;
7853/* repeat a zero length 11-138 times (7 bits of repeat count) */
7854
7855var extra_lbits = /* extra bits for each length code */
7856 [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];
7857
7858var extra_dbits = /* extra bits for each distance code */
7859 [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];
7860
7861var extra_blbits = /* extra bits for each bit length code */
7862 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
7863
7864var bl_order =
7865 [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
7866/* The lengths of the bit length codes are sent in order of decreasing
7867 * probability, to avoid transmitting the lengths for unused bit length codes.
7868 */
7869
7870/* ===========================================================================
7871 * Local data. These are initialized only once.
7872 */
7873
7874// We pre-fill arrays with 0 to avoid uninitialized gaps
7875
7876var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
7877
7878// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
7879var static_ltree = new Array((L_CODES+2) * 2);
7880zero(static_ltree);
7881/* The static literal tree. Since the bit lengths are imposed, there is no
7882 * need for the L_CODES extra codes used during heap construction. However
7883 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
7884 * below).
7885 */
7886
7887var static_dtree = new Array(D_CODES * 2);
7888zero(static_dtree);
7889/* The static distance tree. (Actually a trivial tree since all codes use
7890 * 5 bits.)
7891 */
7892
7893var _dist_code = new Array(DIST_CODE_LEN);
7894zero(_dist_code);
7895/* Distance codes. The first 256 values correspond to the distances
7896 * 3 .. 258, the last 256 values correspond to the top 8 bits of
7897 * the 15 bit distances.
7898 */
7899
7900var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
7901zero(_length_code);
7902/* length code for each normalized match length (0 == MIN_MATCH) */
7903
7904var base_length = new Array(LENGTH_CODES);
7905zero(base_length);
7906/* First normalized length for each code (0 = MIN_MATCH) */
7907
7908var base_dist = new Array(D_CODES);
7909zero(base_dist);
7910/* First normalized distance for each code (0 = distance of 1) */
7911
7912
7913var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
7914
7915 this.static_tree = static_tree; /* static tree or NULL */
7916 this.extra_bits = extra_bits; /* extra bits for each code or NULL */
7917 this.extra_base = extra_base; /* base index for extra_bits */
7918 this.elems = elems; /* max number of elements in the tree */
7919 this.max_length = max_length; /* max bit length for the codes */
7920
7921 // show if `static_tree` has data or dummy - needed for monomorphic objects
7922 this.has_stree = static_tree && static_tree.length;
7923};
7924
7925
7926var static_l_desc;
7927var static_d_desc;
7928var static_bl_desc;
7929
7930
7931var TreeDesc = function(dyn_tree, stat_desc) {
7932 this.dyn_tree = dyn_tree; /* the dynamic tree */
7933 this.max_code = 0; /* largest code with non zero frequency */
7934 this.stat_desc = stat_desc; /* the corresponding static tree */
7935};
7936
7937
7938
7939function d_code(dist) {
7940 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
7941}
7942
7943
7944/* ===========================================================================
7945 * Output a short LSB first on the stream.
7946 * IN assertion: there is enough room in pendingBuf.
7947 */
7948function put_short (s, w) {
7949// put_byte(s, (uch)((w) & 0xff));
7950// put_byte(s, (uch)((ush)(w) >> 8));
7951 s.pending_buf[s.pending++] = (w) & 0xff;
7952 s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
7953}
7954
7955
7956/* ===========================================================================
7957 * Send a value on a given number of bits.
7958 * IN assertion: length <= 16 and value fits in length bits.
7959 */
7960function send_bits(s, value, length) {
7961 if (s.bi_valid > (Buf_size - length)) {
7962 s.bi_buf |= (value << s.bi_valid) & 0xffff;
7963 put_short(s, s.bi_buf);
7964 s.bi_buf = value >> (Buf_size - s.bi_valid);
7965 s.bi_valid += length - Buf_size;
7966 } else {
7967 s.bi_buf |= (value << s.bi_valid) & 0xffff;
7968 s.bi_valid += length;
7969 }
7970}
7971
7972
7973function send_code(s, c, tree) {
7974 send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
7975}
7976
7977
7978/* ===========================================================================
7979 * Reverse the first len bits of a code, using straightforward code (a faster
7980 * method would use a table)
7981 * IN assertion: 1 <= len <= 15
7982 */
7983function bi_reverse(code, len) {
7984 var res = 0;
7985 do {
7986 res |= code & 1;
7987 code >>>= 1;
7988 res <<= 1;
7989 } while (--len > 0);
7990 return res >>> 1;
7991}
7992
7993
7994/* ===========================================================================
7995 * Flush the bit buffer, keeping at most 7 bits in it.
7996 */
7997function bi_flush(s) {
7998 if (s.bi_valid === 16) {
7999 put_short(s, s.bi_buf);
8000 s.bi_buf = 0;
8001 s.bi_valid = 0;
8002
8003 } else if (s.bi_valid >= 8) {
8004 s.pending_buf[s.pending++] = s.bi_buf & 0xff;
8005 s.bi_buf >>= 8;
8006 s.bi_valid -= 8;
8007 }
8008}
8009
8010
8011/* ===========================================================================
8012 * Compute the optimal bit lengths for a tree and update the total bit length
8013 * for the current block.
8014 * IN assertion: the fields freq and dad are set, heap[heap_max] and
8015 * above are the tree nodes sorted by increasing frequency.
8016 * OUT assertions: the field len is set to the optimal bit length, the
8017 * array bl_count contains the frequencies for each bit length.
8018 * The length opt_len is updated; static_len is also updated if stree is
8019 * not null.
8020 */
8021function gen_bitlen(s, desc)
8022// deflate_state *s;
8023// tree_desc *desc; /* the tree descriptor */
8024{
8025 var tree = desc.dyn_tree;
8026 var max_code = desc.max_code;
8027 var stree = desc.stat_desc.static_tree;
8028 var has_stree = desc.stat_desc.has_stree;
8029 var extra = desc.stat_desc.extra_bits;
8030 var base = desc.stat_desc.extra_base;
8031 var max_length = desc.stat_desc.max_length;
8032 var h; /* heap index */
8033 var n, m; /* iterate over the tree elements */
8034 var bits; /* bit length */
8035 var xbits; /* extra bits */
8036 var f; /* frequency */
8037 var overflow = 0; /* number of elements with bit length too large */
8038
8039 for (bits = 0; bits <= MAX_BITS; bits++) {
8040 s.bl_count[bits] = 0;
8041 }
8042
8043 /* In a first pass, compute the optimal bit lengths (which may
8044 * overflow in the case of the bit length tree).
8045 */
8046 tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
8047
8048 for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
8049 n = s.heap[h];
8050 bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
8051 if (bits > max_length) {
8052 bits = max_length;
8053 overflow++;
8054 }
8055 tree[n*2 + 1]/*.Len*/ = bits;
8056 /* We overwrite tree[n].Dad which is no longer needed */
8057
8058 if (n > max_code) { continue; } /* not a leaf node */
8059
8060 s.bl_count[bits]++;
8061 xbits = 0;
8062 if (n >= base) {
8063 xbits = extra[n-base];
8064 }
8065 f = tree[n * 2]/*.Freq*/;
8066 s.opt_len += f * (bits + xbits);
8067 if (has_stree) {
8068 s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
8069 }
8070 }
8071 if (overflow === 0) { return; }
8072
8073 // Trace((stderr,"\nbit length overflow\n"));
8074 /* This happens for example on obj2 and pic of the Calgary corpus */
8075
8076 /* Find the first bit length which could increase: */
8077 do {
8078 bits = max_length-1;
8079 while (s.bl_count[bits] === 0) { bits--; }
8080 s.bl_count[bits]--; /* move one leaf down the tree */
8081 s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
8082 s.bl_count[max_length]--;
8083 /* The brother of the overflow item also moves one step up,
8084 * but this does not affect bl_count[max_length]
8085 */
8086 overflow -= 2;
8087 } while (overflow > 0);
8088
8089 /* Now recompute all bit lengths, scanning in increasing frequency.
8090 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
8091 * lengths instead of fixing only the wrong ones. This idea is taken
8092 * from 'ar' written by Haruhiko Okumura.)
8093 */
8094 for (bits = max_length; bits !== 0; bits--) {
8095 n = s.bl_count[bits];
8096 while (n !== 0) {
8097 m = s.heap[--h];
8098 if (m > max_code) { continue; }
8099 if (tree[m*2 + 1]/*.Len*/ !== bits) {
8100 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
8101 s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
8102 tree[m*2 + 1]/*.Len*/ = bits;
8103 }
8104 n--;
8105 }
8106 }
8107}
8108
8109
8110/* ===========================================================================
8111 * Generate the codes for a given tree and bit counts (which need not be
8112 * optimal).
8113 * IN assertion: the array bl_count contains the bit length statistics for
8114 * the given tree and the field len is set for all tree elements.
8115 * OUT assertion: the field code is set for all tree elements of non
8116 * zero code length.
8117 */
8118function gen_codes(tree, max_code, bl_count)
8119// ct_data *tree; /* the tree to decorate */
8120// int max_code; /* largest code with non zero frequency */
8121// ushf *bl_count; /* number of codes at each bit length */
8122{
8123 var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
8124 var code = 0; /* running code value */
8125 var bits; /* bit index */
8126 var n; /* code index */
8127
8128 /* The distribution counts are first used to generate the code values
8129 * without bit reversal.
8130 */
8131 for (bits = 1; bits <= MAX_BITS; bits++) {
8132 next_code[bits] = code = (code + bl_count[bits-1]) << 1;
8133 }
8134 /* Check that the bit counts in bl_count are consistent. The last code
8135 * must be all ones.
8136 */
8137 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
8138 // "inconsistent bit counts");
8139 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
8140
8141 for (n = 0; n <= max_code; n++) {
8142 var len = tree[n*2 + 1]/*.Len*/;
8143 if (len === 0) { continue; }
8144 /* Now reverse the bits */
8145 tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
8146
8147 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
8148 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
8149 }
8150}
8151
8152
8153/* ===========================================================================
8154 * Initialize the various 'constant' tables.
8155 */
8156function tr_static_init() {
8157 var n; /* iterates over tree elements */
8158 var bits; /* bit counter */
8159 var length; /* length value */
8160 var code; /* code value */
8161 var dist; /* distance index */
8162 var bl_count = new Array(MAX_BITS+1);
8163 /* number of codes at each bit length for an optimal tree */
8164
8165 // do check in _tr_init()
8166 //if (static_init_done) return;
8167
8168 /* For some embedded targets, global variables are not initialized: */
8169/*#ifdef NO_INIT_GLOBAL_POINTERS
8170 static_l_desc.static_tree = static_ltree;
8171 static_l_desc.extra_bits = extra_lbits;
8172 static_d_desc.static_tree = static_dtree;
8173 static_d_desc.extra_bits = extra_dbits;
8174 static_bl_desc.extra_bits = extra_blbits;
8175#endif*/
8176
8177 /* Initialize the mapping length (0..255) -> length code (0..28) */
8178 length = 0;
8179 for (code = 0; code < LENGTH_CODES-1; code++) {
8180 base_length[code] = length;
8181 for (n = 0; n < (1<<extra_lbits[code]); n++) {
8182 _length_code[length++] = code;
8183 }
8184 }
8185 //Assert (length == 256, "tr_static_init: length != 256");
8186 /* Note that the length 255 (match length 258) can be represented
8187 * in two different ways: code 284 + 5 bits or code 285, so we
8188 * overwrite length_code[255] to use the best encoding:
8189 */
8190 _length_code[length-1] = code;
8191
8192 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
8193 dist = 0;
8194 for (code = 0 ; code < 16; code++) {
8195 base_dist[code] = dist;
8196 for (n = 0; n < (1<<extra_dbits[code]); n++) {
8197 _dist_code[dist++] = code;
8198 }
8199 }
8200 //Assert (dist == 256, "tr_static_init: dist != 256");
8201 dist >>= 7; /* from now on, all distances are divided by 128 */
8202 for ( ; code < D_CODES; code++) {
8203 base_dist[code] = dist << 7;
8204 for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
8205 _dist_code[256 + dist++] = code;
8206 }
8207 }
8208 //Assert (dist == 256, "tr_static_init: 256+dist != 512");
8209
8210 /* Construct the codes of the static literal tree */
8211 for (bits = 0; bits <= MAX_BITS; bits++) {
8212 bl_count[bits] = 0;
8213 }
8214
8215 n = 0;
8216 while (n <= 143) {
8217 static_ltree[n*2 + 1]/*.Len*/ = 8;
8218 n++;
8219 bl_count[8]++;
8220 }
8221 while (n <= 255) {
8222 static_ltree[n*2 + 1]/*.Len*/ = 9;
8223 n++;
8224 bl_count[9]++;
8225 }
8226 while (n <= 279) {
8227 static_ltree[n*2 + 1]/*.Len*/ = 7;
8228 n++;
8229 bl_count[7]++;
8230 }
8231 while (n <= 287) {
8232 static_ltree[n*2 + 1]/*.Len*/ = 8;
8233 n++;
8234 bl_count[8]++;
8235 }
8236 /* Codes 286 and 287 do not exist, but we must include them in the
8237 * tree construction to get a canonical Huffman tree (longest code
8238 * all ones)
8239 */
8240 gen_codes(static_ltree, L_CODES+1, bl_count);
8241
8242 /* The static distance tree is trivial: */
8243 for (n = 0; n < D_CODES; n++) {
8244 static_dtree[n*2 + 1]/*.Len*/ = 5;
8245 static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
8246 }
8247
8248 // Now data ready and we can init static trees
8249 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
8250 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
8251 static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
8252
8253 //static_init_done = true;
8254}
8255
8256
8257/* ===========================================================================
8258 * Initialize a new block.
8259 */
8260function init_block(s) {
8261 var n; /* iterates over tree elements */
8262
8263 /* Initialize the trees. */
8264 for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
8265 for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
8266 for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
8267
8268 s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
8269 s.opt_len = s.static_len = 0;
8270 s.last_lit = s.matches = 0;
8271}
8272
8273
8274/* ===========================================================================
8275 * Flush the bit buffer and align the output on a byte boundary
8276 */
8277function bi_windup(s)
8278{
8279 if (s.bi_valid > 8) {
8280 put_short(s, s.bi_buf);
8281 } else if (s.bi_valid > 0) {
8282 //put_byte(s, (Byte)s->bi_buf);
8283 s.pending_buf[s.pending++] = s.bi_buf;
8284 }
8285 s.bi_buf = 0;
8286 s.bi_valid = 0;
8287}
8288
8289/* ===========================================================================
8290 * Copy a stored block, storing first the length and its
8291 * one's complement if requested.
8292 */
8293function copy_block(s, buf, len, header)
8294//DeflateState *s;
8295//charf *buf; /* the input data */
8296//unsigned len; /* its length */
8297//int header; /* true if block header must be written */
8298{
8299 bi_windup(s); /* align on byte boundary */
8300
8301 if (header) {
8302 put_short(s, len);
8303 put_short(s, ~len);
8304 }
8305// while (len--) {
8306// put_byte(s, *buf++);
8307// }
8308 utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
8309 s.pending += len;
8310}
8311
8312/* ===========================================================================
8313 * Compares to subtrees, using the tree depth as tie breaker when
8314 * the subtrees have equal frequency. This minimizes the worst case length.
8315 */
8316function smaller(tree, n, m, depth) {
8317 var _n2 = n*2;
8318 var _m2 = m*2;
8319 return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
8320 (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
8321}
8322
8323/* ===========================================================================
8324 * Restore the heap property by moving down the tree starting at node k,
8325 * exchanging a node with the smallest of its two sons if necessary, stopping
8326 * when the heap property is re-established (each father smaller than its
8327 * two sons).
8328 */
8329function pqdownheap(s, tree, k)
8330// deflate_state *s;
8331// ct_data *tree; /* the tree to restore */
8332// int k; /* node to move down */
8333{
8334 var v = s.heap[k];
8335 var j = k << 1; /* left son of k */
8336 while (j <= s.heap_len) {
8337 /* Set j to the smallest of the two sons: */
8338 if (j < s.heap_len &&
8339 smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
8340 j++;
8341 }
8342 /* Exit if v is smaller than both sons */
8343 if (smaller(tree, v, s.heap[j], s.depth)) { break; }
8344
8345 /* Exchange v with the smallest son */
8346 s.heap[k] = s.heap[j];
8347 k = j;
8348
8349 /* And continue down the tree, setting j to the left son of k */
8350 j <<= 1;
8351 }
8352 s.heap[k] = v;
8353}
8354
8355
8356// inlined manually
8357// var SMALLEST = 1;
8358
8359/* ===========================================================================
8360 * Send the block data compressed using the given Huffman trees
8361 */
8362function compress_block(s, ltree, dtree)
8363// deflate_state *s;
8364// const ct_data *ltree; /* literal tree */
8365// const ct_data *dtree; /* distance tree */
8366{
8367 var dist; /* distance of matched string */
8368 var lc; /* match length or unmatched char (if dist == 0) */
8369 var lx = 0; /* running index in l_buf */
8370 var code; /* the code to send */
8371 var extra; /* number of extra bits to send */
8372
8373 if (s.last_lit !== 0) {
8374 do {
8375 dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
8376 lc = s.pending_buf[s.l_buf + lx];
8377 lx++;
8378
8379 if (dist === 0) {
8380 send_code(s, lc, ltree); /* send a literal byte */
8381 //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
8382 } else {
8383 /* Here, lc is the match length - MIN_MATCH */
8384 code = _length_code[lc];
8385 send_code(s, code+LITERALS+1, ltree); /* send the length code */
8386 extra = extra_lbits[code];
8387 if (extra !== 0) {
8388 lc -= base_length[code];
8389 send_bits(s, lc, extra); /* send the extra length bits */
8390 }
8391 dist--; /* dist is now the match distance - 1 */
8392 code = d_code(dist);
8393 //Assert (code < D_CODES, "bad d_code");
8394
8395 send_code(s, code, dtree); /* send the distance code */
8396 extra = extra_dbits[code];
8397 if (extra !== 0) {
8398 dist -= base_dist[code];
8399 send_bits(s, dist, extra); /* send the extra distance bits */
8400 }
8401 } /* literal or match pair ? */
8402
8403 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
8404 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
8405 // "pendingBuf overflow");
8406
8407 } while (lx < s.last_lit);
8408 }
8409
8410 send_code(s, END_BLOCK, ltree);
8411}
8412
8413
8414/* ===========================================================================
8415 * Construct one Huffman tree and assigns the code bit strings and lengths.
8416 * Update the total bit length for the current block.
8417 * IN assertion: the field freq is set for all tree elements.
8418 * OUT assertions: the fields len and code are set to the optimal bit length
8419 * and corresponding code. The length opt_len is updated; static_len is
8420 * also updated if stree is not null. The field max_code is set.
8421 */
8422function build_tree(s, desc)
8423// deflate_state *s;
8424// tree_desc *desc; /* the tree descriptor */
8425{
8426 var tree = desc.dyn_tree;
8427 var stree = desc.stat_desc.static_tree;
8428 var has_stree = desc.stat_desc.has_stree;
8429 var elems = desc.stat_desc.elems;
8430 var n, m; /* iterate over heap elements */
8431 var max_code = -1; /* largest code with non zero frequency */
8432 var node; /* new node being created */
8433
8434 /* Construct the initial heap, with least frequent element in
8435 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
8436 * heap[0] is not used.
8437 */
8438 s.heap_len = 0;
8439 s.heap_max = HEAP_SIZE;
8440
8441 for (n = 0; n < elems; n++) {
8442 if (tree[n * 2]/*.Freq*/ !== 0) {
8443 s.heap[++s.heap_len] = max_code = n;
8444 s.depth[n] = 0;
8445
8446 } else {
8447 tree[n*2 + 1]/*.Len*/ = 0;
8448 }
8449 }
8450
8451 /* The pkzip format requires that at least one distance code exists,
8452 * and that at least one bit should be sent even if there is only one
8453 * possible code. So to avoid special checks later on we force at least
8454 * two codes of non zero frequency.
8455 */
8456 while (s.heap_len < 2) {
8457 node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
8458 tree[node * 2]/*.Freq*/ = 1;
8459 s.depth[node] = 0;
8460 s.opt_len--;
8461
8462 if (has_stree) {
8463 s.static_len -= stree[node*2 + 1]/*.Len*/;
8464 }
8465 /* node is 0 or 1 so it does not have extra bits */
8466 }
8467 desc.max_code = max_code;
8468
8469 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
8470 * establish sub-heaps of increasing lengths:
8471 */
8472 for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
8473
8474 /* Construct the Huffman tree by repeatedly combining the least two
8475 * frequent nodes.
8476 */
8477 node = elems; /* next internal node of the tree */
8478 do {
8479 //pqremove(s, tree, n); /* n = node of least frequency */
8480 /*** pqremove ***/
8481 n = s.heap[1/*SMALLEST*/];
8482 s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
8483 pqdownheap(s, tree, 1/*SMALLEST*/);
8484 /***/
8485
8486 m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
8487
8488 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
8489 s.heap[--s.heap_max] = m;
8490
8491 /* Create a new node father of n and m */
8492 tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
8493 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
8494 tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
8495
8496 /* and insert the new node in the heap */
8497 s.heap[1/*SMALLEST*/] = node++;
8498 pqdownheap(s, tree, 1/*SMALLEST*/);
8499
8500 } while (s.heap_len >= 2);
8501
8502 s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
8503
8504 /* At this point, the fields freq and dad are set. We can now
8505 * generate the bit lengths.
8506 */
8507 gen_bitlen(s, desc);
8508
8509 /* The field len is now set, we can generate the bit codes */
8510 gen_codes(tree, max_code, s.bl_count);
8511}
8512
8513
8514/* ===========================================================================
8515 * Scan a literal or distance tree to determine the frequencies of the codes
8516 * in the bit length tree.
8517 */
8518function scan_tree(s, tree, max_code)
8519// deflate_state *s;
8520// ct_data *tree; /* the tree to be scanned */
8521// int max_code; /* and its largest code of non zero frequency */
8522{
8523 var n; /* iterates over all tree elements */
8524 var prevlen = -1; /* last emitted length */
8525 var curlen; /* length of current code */
8526
8527 var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
8528
8529 var count = 0; /* repeat count of the current code */
8530 var max_count = 7; /* max repeat count */
8531 var min_count = 4; /* min repeat count */
8532
8533 if (nextlen === 0) {
8534 max_count = 138;
8535 min_count = 3;
8536 }
8537 tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
8538
8539 for (n = 0; n <= max_code; n++) {
8540 curlen = nextlen;
8541 nextlen = tree[(n+1)*2 + 1]/*.Len*/;
8542
8543 if (++count < max_count && curlen === nextlen) {
8544 continue;
8545
8546 } else if (count < min_count) {
8547 s.bl_tree[curlen * 2]/*.Freq*/ += count;
8548
8549 } else if (curlen !== 0) {
8550
8551 if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
8552 s.bl_tree[REP_3_6*2]/*.Freq*/++;
8553
8554 } else if (count <= 10) {
8555 s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
8556
8557 } else {
8558 s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
8559 }
8560
8561 count = 0;
8562 prevlen = curlen;
8563
8564 if (nextlen === 0) {
8565 max_count = 138;
8566 min_count = 3;
8567
8568 } else if (curlen === nextlen) {
8569 max_count = 6;
8570 min_count = 3;
8571
8572 } else {
8573 max_count = 7;
8574 min_count = 4;
8575 }
8576 }
8577}
8578
8579
8580/* ===========================================================================
8581 * Send a literal or distance tree in compressed form, using the codes in
8582 * bl_tree.
8583 */
8584function send_tree(s, tree, max_code)
8585// deflate_state *s;
8586// ct_data *tree; /* the tree to be scanned */
8587// int max_code; /* and its largest code of non zero frequency */
8588{
8589 var n; /* iterates over all tree elements */
8590 var prevlen = -1; /* last emitted length */
8591 var curlen; /* length of current code */
8592
8593 var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
8594
8595 var count = 0; /* repeat count of the current code */
8596 var max_count = 7; /* max repeat count */
8597 var min_count = 4; /* min repeat count */
8598
8599 /* tree[max_code+1].Len = -1; */ /* guard already set */
8600 if (nextlen === 0) {
8601 max_count = 138;
8602 min_count = 3;
8603 }
8604
8605 for (n = 0; n <= max_code; n++) {
8606 curlen = nextlen;
8607 nextlen = tree[(n+1)*2 + 1]/*.Len*/;
8608
8609 if (++count < max_count && curlen === nextlen) {
8610 continue;
8611
8612 } else if (count < min_count) {
8613 do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
8614
8615 } else if (curlen !== 0) {
8616 if (curlen !== prevlen) {
8617 send_code(s, curlen, s.bl_tree);
8618 count--;
8619 }
8620 //Assert(count >= 3 && count <= 6, " 3_6?");
8621 send_code(s, REP_3_6, s.bl_tree);
8622 send_bits(s, count-3, 2);
8623
8624 } else if (count <= 10) {
8625 send_code(s, REPZ_3_10, s.bl_tree);
8626 send_bits(s, count-3, 3);
8627
8628 } else {
8629 send_code(s, REPZ_11_138, s.bl_tree);
8630 send_bits(s, count-11, 7);
8631 }
8632
8633 count = 0;
8634 prevlen = curlen;
8635 if (nextlen === 0) {
8636 max_count = 138;
8637 min_count = 3;
8638
8639 } else if (curlen === nextlen) {
8640 max_count = 6;
8641 min_count = 3;
8642
8643 } else {
8644 max_count = 7;
8645 min_count = 4;
8646 }
8647 }
8648}
8649
8650
8651/* ===========================================================================
8652 * Construct the Huffman tree for the bit lengths and return the index in
8653 * bl_order of the last bit length code to send.
8654 */
8655function build_bl_tree(s) {
8656 var max_blindex; /* index of last bit length code of non zero freq */
8657
8658 /* Determine the bit length frequencies for literal and distance trees */
8659 scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
8660 scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
8661
8662 /* Build the bit length tree: */
8663 build_tree(s, s.bl_desc);
8664 /* opt_len now includes the length of the tree representations, except
8665 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
8666 */
8667
8668 /* Determine the number of bit length codes to send. The pkzip format
8669 * requires that at least 4 bit length codes be sent. (appnote.txt says
8670 * 3 but the actual value used is 4.)
8671 */
8672 for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
8673 if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
8674 break;
8675 }
8676 }
8677 /* Update opt_len to include the bit length tree and counts */
8678 s.opt_len += 3*(max_blindex+1) + 5+5+4;
8679 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
8680 // s->opt_len, s->static_len));
8681
8682 return max_blindex;
8683}
8684
8685
8686/* ===========================================================================
8687 * Send the header for a block using dynamic Huffman trees: the counts, the
8688 * lengths of the bit length codes, the literal tree and the distance tree.
8689 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
8690 */
8691function send_all_trees(s, lcodes, dcodes, blcodes)
8692// deflate_state *s;
8693// int lcodes, dcodes, blcodes; /* number of codes for each tree */
8694{
8695 var rank; /* index in bl_order */
8696
8697 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
8698 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
8699 // "too many codes");
8700 //Tracev((stderr, "\nbl counts: "));
8701 send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
8702 send_bits(s, dcodes-1, 5);
8703 send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
8704 for (rank = 0; rank < blcodes; rank++) {
8705 //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
8706 send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
8707 }
8708 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
8709
8710 send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
8711 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
8712
8713 send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
8714 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
8715}
8716
8717
8718/* ===========================================================================
8719 * Check if the data type is TEXT or BINARY, using the following algorithm:
8720 * - TEXT if the two conditions below are satisfied:
8721 * a) There are no non-portable control characters belonging to the
8722 * "black list" (0..6, 14..25, 28..31).
8723 * b) There is at least one printable character belonging to the
8724 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
8725 * - BINARY otherwise.
8726 * - The following partially-portable control characters form a
8727 * "gray list" that is ignored in this detection algorithm:
8728 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
8729 * IN assertion: the fields Freq of dyn_ltree are set.
8730 */
8731function detect_data_type(s) {
8732 /* black_mask is the bit mask of black-listed bytes
8733 * set bits 0..6, 14..25, and 28..31
8734 * 0xf3ffc07f = binary 11110011111111111100000001111111
8735 */
8736 var black_mask = 0xf3ffc07f;
8737 var n;
8738
8739 /* Check for non-textual ("black-listed") bytes. */
8740 for (n = 0; n <= 31; n++, black_mask >>>= 1) {
8741 if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
8742 return Z_BINARY;
8743 }
8744 }
8745
8746 /* Check for textual ("white-listed") bytes. */
8747 if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
8748 s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
8749 return Z_TEXT;
8750 }
8751 for (n = 32; n < LITERALS; n++) {
8752 if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
8753 return Z_TEXT;
8754 }
8755 }
8756
8757 /* There are no "black-listed" or "white-listed" bytes:
8758 * this stream either is empty or has tolerated ("gray-listed") bytes only.
8759 */
8760 return Z_BINARY;
8761}
8762
8763
8764var static_init_done = false;
8765
8766/* ===========================================================================
8767 * Initialize the tree data structures for a new zlib stream.
8768 */
8769function _tr_init(s)
8770{
8771
8772 if (!static_init_done) {
8773 tr_static_init();
8774 static_init_done = true;
8775 }
8776
8777 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
8778 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
8779 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
8780
8781 s.bi_buf = 0;
8782 s.bi_valid = 0;
8783
8784 /* Initialize the first block of the first file: */
8785 init_block(s);
8786}
8787
8788
8789/* ===========================================================================
8790 * Send a stored block
8791 */
8792function _tr_stored_block(s, buf, stored_len, last)
8793//DeflateState *s;
8794//charf *buf; /* input block */
8795//ulg stored_len; /* length of input block */
8796//int last; /* one if this is the last block for a file */
8797{
8798 send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
8799 copy_block(s, buf, stored_len, true); /* with header */
8800}
8801
8802
8803/* ===========================================================================
8804 * Send one empty static block to give enough lookahead for inflate.
8805 * This takes 10 bits, of which 7 may remain in the bit buffer.
8806 */
8807function _tr_align(s) {
8808 send_bits(s, STATIC_TREES<<1, 3);
8809 send_code(s, END_BLOCK, static_ltree);
8810 bi_flush(s);
8811}
8812
8813
8814/* ===========================================================================
8815 * Determine the best encoding for the current block: dynamic trees, static
8816 * trees or store, and output the encoded block to the zip file.
8817 */
8818function _tr_flush_block(s, buf, stored_len, last)
8819//DeflateState *s;
8820//charf *buf; /* input block, or NULL if too old */
8821//ulg stored_len; /* length of input block */
8822//int last; /* one if this is the last block for a file */
8823{
8824 var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
8825 var max_blindex = 0; /* index of last bit length code of non zero freq */
8826
8827 /* Build the Huffman trees unless a stored block is forced */
8828 if (s.level > 0) {
8829
8830 /* Check if the file is binary or text */
8831 if (s.strm.data_type === Z_UNKNOWN) {
8832 s.strm.data_type = detect_data_type(s);
8833 }
8834
8835 /* Construct the literal and distance trees */
8836 build_tree(s, s.l_desc);
8837 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
8838 // s->static_len));
8839
8840 build_tree(s, s.d_desc);
8841 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
8842 // s->static_len));
8843 /* At this point, opt_len and static_len are the total bit lengths of
8844 * the compressed block data, excluding the tree representations.
8845 */
8846
8847 /* Build the bit length tree for the above two trees, and get the index
8848 * in bl_order of the last bit length code to send.
8849 */
8850 max_blindex = build_bl_tree(s);
8851
8852 /* Determine the best encoding. Compute the block lengths in bytes. */
8853 opt_lenb = (s.opt_len+3+7) >>> 3;
8854 static_lenb = (s.static_len+3+7) >>> 3;
8855
8856 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
8857 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
8858 // s->last_lit));
8859
8860 if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
8861
8862 } else {
8863 // Assert(buf != (char*)0, "lost buf");
8864 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
8865 }
8866
8867 if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
8868 /* 4: two words for the lengths */
8869
8870 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
8871 * Otherwise we can't have processed more than WSIZE input bytes since
8872 * the last block flush, because compression would have been
8873 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
8874 * transform a block into a stored block.
8875 */
8876 _tr_stored_block(s, buf, stored_len, last);
8877
8878 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
8879
8880 send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
8881 compress_block(s, static_ltree, static_dtree);
8882
8883 } else {
8884 send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
8885 send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
8886 compress_block(s, s.dyn_ltree, s.dyn_dtree);
8887 }
8888 // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
8889 /* The above check is made mod 2^32, for files larger than 512 MB
8890 * and uLong implemented on 32 bits.
8891 */
8892 init_block(s);
8893
8894 if (last) {
8895 bi_windup(s);
8896 }
8897 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
8898 // s->compressed_len-7*last));
8899}
8900
8901/* ===========================================================================
8902 * Save the match info and tally the frequency counts. Return true if
8903 * the current block must be flushed.
8904 */
8905function _tr_tally(s, dist, lc)
8906// deflate_state *s;
8907// unsigned dist; /* distance of matched string */
8908// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
8909{
8910 //var out_length, in_length, dcode;
8911
8912 s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
8913 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
8914
8915 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
8916 s.last_lit++;
8917
8918 if (dist === 0) {
8919 /* lc is the unmatched char */
8920 s.dyn_ltree[lc*2]/*.Freq*/++;
8921 } else {
8922 s.matches++;
8923 /* Here, lc is the match length - MIN_MATCH */
8924 dist--; /* dist = match distance - 1 */
8925 //Assert((ush)dist < (ush)MAX_DIST(s) &&
8926 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
8927 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
8928
8929 s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
8930 s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
8931 }
8932
8933// (!) This block is disabled in zlib defailts,
8934// don't enable it for binary compatibility
8935
8936//#ifdef TRUNCATE_BLOCK
8937// /* Try to guess if it is profitable to stop the current block here */
8938// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
8939// /* Compute an upper bound for the compressed length */
8940// out_length = s.last_lit*8;
8941// in_length = s.strstart - s.block_start;
8942//
8943// for (dcode = 0; dcode < D_CODES; dcode++) {
8944// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
8945// }
8946// out_length >>>= 3;
8947// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
8948// // s->last_lit, in_length, out_length,
8949// // 100L - out_length*100L/in_length));
8950// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
8951// return true;
8952// }
8953// }
8954//#endif
8955
8956 return (s.last_lit === s.lit_bufsize-1);
8957 /* We avoid equality with lit_bufsize because of wraparound at 64K
8958 * on 16 bit machines and because stored blocks are restricted to
8959 * 64K-1 bytes.
8960 */
8961}
8962
8963exports._tr_init = _tr_init;
8964exports._tr_stored_block = _tr_stored_block;
8965exports._tr_flush_block = _tr_flush_block;
8966exports._tr_tally = _tr_tally;
8967exports._tr_align = _tr_align;
8968},{"../utils/common":27}],39:[function(_dereq_,module,exports){
8969'use strict';
8970
8971
8972function ZStream() {
8973 /* next input byte */
8974 this.input = null; // JS specific, because we have no pointers
8975 this.next_in = 0;
8976 /* number of bytes available at input */
8977 this.avail_in = 0;
8978 /* total number of input bytes read so far */
8979 this.total_in = 0;
8980 /* next output byte should be put there */
8981 this.output = null; // JS specific, because we have no pointers
8982 this.next_out = 0;
8983 /* remaining free space at output */
8984 this.avail_out = 0;
8985 /* total number of bytes output so far */
8986 this.total_out = 0;
8987 /* last error message, NULL if no error */
8988 this.msg = ''/*Z_NULL*/;
8989 /* not visible by applications */
8990 this.state = null;
8991 /* best guess about the data type: binary or text */
8992 this.data_type = 2/*Z_UNKNOWN*/;
8993 /* adler32 value of the uncompressed data */
8994 this.adler = 0;
8995}
8996
8997module.exports = ZStream;
8998},{}]},{},[9])
8999(9)
9000}));