UNPKG

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