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