UNPKG

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