TrinetraLabs/Placebo_AI
0
1/*!2 3JSZip v3.10.1 - A JavaScript class for generating and reading zip files4<http://stuartk.com/jszip>5 6(c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>7Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.8 9JSZip uses the library pako released under the MIT license :10https://github.com/nodeca/pako/blob/main/LICENSE11*/12 13(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JSZip = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){14"use strict";15var utils = require("./utils");16var support = require("./support");17// private property18var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";19 20 21// public method for encoding22exports.encode = function(input) {23 var output = [];24 var chr1, chr2, chr3, enc1, enc2, enc3, enc4;25 var i = 0, len = input.length, remainingBytes = len;26 27 var isArray = utils.getTypeOf(input) !== "string";28 while (i < input.length) {29 remainingBytes = len - i;30 31 if (!isArray) {32 chr1 = input.charCodeAt(i++);33 chr2 = i < len ? input.charCodeAt(i++) : 0;34 chr3 = i < len ? input.charCodeAt(i++) : 0;35 } else {36 chr1 = input[i++];37 chr2 = i < len ? input[i++] : 0;38 chr3 = i < len ? input[i++] : 0;39 }40 41 enc1 = chr1 >> 2;42 enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);43 enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64;44 enc4 = remainingBytes > 2 ? (chr3 & 63) : 64;45 46 output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4));47 48 }49 50 return output.join("");51};52 53// public method for decoding54exports.decode = function(input) {55 var chr1, chr2, chr3;56 var enc1, enc2, enc3, enc4;57 var i = 0, resultIndex = 0;58 59 var dataUrlPrefix = "data:";60 61 if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) {62 // This is a common error: people give a data url63 // (data:image/png;base64,iVBOR...) with a {base64: true} and64 // wonders why things don't work.65 // We can detect that the string input looks like a data url but we66 // *can't* be sure it is one: removing everything up to the comma would67 // be too dangerous.68 throw new Error("Invalid base64 input, it looks like a data url.");69 }70 71 input = input.replace(/[^A-Za-z0-9+/=]/g, "");72 73 var totalLength = input.length * 3 / 4;74 if(input.charAt(input.length - 1) === _keyStr.charAt(64)) {75 totalLength--;76 }77 if(input.charAt(input.length - 2) === _keyStr.charAt(64)) {78 totalLength--;79 }80 if (totalLength % 1 !== 0) {81 // totalLength is not an integer, the length does not match a valid82 // base64 content. That can happen if:83 // - the input is not a base64 content84 // - the input is *almost* a base64 content, with a extra chars at the85 // beginning or at the end86 // - the input uses a base64 variant (base64url for example)87 throw new Error("Invalid base64 input, bad content length.");88 }89 var output;90 if (support.uint8array) {91 output = new Uint8Array(totalLength|0);92 } else {93 output = new Array(totalLength|0);94 }95 96 while (i < input.length) {97 98 enc1 = _keyStr.indexOf(input.charAt(i++));99 enc2 = _keyStr.indexOf(input.charAt(i++));100 enc3 = _keyStr.indexOf(input.charAt(i++));101 enc4 = _keyStr.indexOf(input.charAt(i++));102 103 chr1 = (enc1 << 2) | (enc2 >> 4);104 chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);105 chr3 = ((enc3 & 3) << 6) | enc4;106 107 output[resultIndex++] = chr1;108 109 if (enc3 !== 64) {110 output[resultIndex++] = chr2;111 }112 if (enc4 !== 64) {113 output[resultIndex++] = chr3;114 }115 116 }117 118 return output;119};120 121},{"./support":30,"./utils":32}],2:[function(require,module,exports){122"use strict";123 124var external = require("./external");125var DataWorker = require("./stream/DataWorker");126var Crc32Probe = require("./stream/Crc32Probe");127var DataLengthProbe = require("./stream/DataLengthProbe");128 129/**130 * Represent a compressed object, with everything needed to decompress it.131 * @constructor132 * @param {number} compressedSize the size of the data compressed.133 * @param {number} uncompressedSize the size of the data after decompression.134 * @param {number} crc32 the crc32 of the decompressed file.135 * @param {object} compression the type of compression, see lib/compressions.js.136 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.137 */138function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {139 this.compressedSize = compressedSize;140 this.uncompressedSize = uncompressedSize;141 this.crc32 = crc32;142 this.compression = compression;143 this.compressedContent = data;144}145 146CompressedObject.prototype = {147 /**148 * Create a worker to get the uncompressed content.149 * @return {GenericWorker} the worker.150 */151 getContentWorker: function () {152 var worker = new DataWorker(external.Promise.resolve(this.compressedContent))153 .pipe(this.compression.uncompressWorker())154 .pipe(new DataLengthProbe("data_length"));155 156 var that = this;157 worker.on("end", function () {158 if (this.streamInfo["data_length"] !== that.uncompressedSize) {159 throw new Error("Bug : uncompressed data size mismatch");160 }161 });162 return worker;163 },164 /**165 * Create a worker to get the compressed content.166 * @return {GenericWorker} the worker.167 */168 getCompressedWorker: function () {169 return new DataWorker(external.Promise.resolve(this.compressedContent))170 .withStreamInfo("compressedSize", this.compressedSize)171 .withStreamInfo("uncompressedSize", this.uncompressedSize)172 .withStreamInfo("crc32", this.crc32)173 .withStreamInfo("compression", this.compression)174 ;175 }176};177 178/**179 * Chain the given worker with other workers to compress the content with the180 * given compression.181 * @param {GenericWorker} uncompressedWorker the worker to pipe.182 * @param {Object} compression the compression object.183 * @param {Object} compressionOptions the options to use when compressing.184 * @return {GenericWorker} the new worker compressing the content.185 */186CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {187 return uncompressedWorker188 .pipe(new Crc32Probe())189 .pipe(new DataLengthProbe("uncompressedSize"))190 .pipe(compression.compressWorker(compressionOptions))191 .pipe(new DataLengthProbe("compressedSize"))192 .withStreamInfo("compression", compression);193};194 195module.exports = CompressedObject;196 197},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(require,module,exports){198"use strict";199 200var GenericWorker = require("./stream/GenericWorker");201 202exports.STORE = {203 magic: "\x00\x00",204 compressWorker : function () {205 return new GenericWorker("STORE compression");206 },207 uncompressWorker : function () {208 return new GenericWorker("STORE decompression");209 }210};211exports.DEFLATE = require("./flate");212 213},{"./flate":7,"./stream/GenericWorker":28}],4:[function(require,module,exports){214"use strict";215 216var utils = require("./utils");217 218/**219 * The following functions come from pako, from pako/lib/zlib/crc32.js220 * released under the MIT license, see pako https://github.com/nodeca/pako/221 */222 223// Use ordinary array, since untyped makes no boost here224function makeTable() {225 var c, table = [];226 227 for(var n =0; n < 256; n++){228 c = n;229 for(var k =0; k < 8; k++){230 c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));231 }232 table[n] = c;233 }234 235 return table;236}237 238// Create table on load. Just 255 signed longs. Not a problem.239var crcTable = makeTable();240 241 242function crc32(crc, buf, len, pos) {243 var t = crcTable, end = pos + len;244 245 crc = crc ^ (-1);246 247 for (var i = pos; i < end; i++ ) {248 crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];249 }250 251 return (crc ^ (-1)); // >>> 0;252}253 254// That's all for the pako functions.255 256/**257 * Compute the crc32 of a string.258 * This is almost the same as the function crc32, but for strings. Using the259 * same function for the two use cases leads to horrible performances.260 * @param {Number} crc the starting value of the crc.261 * @param {String} str the string to use.262 * @param {Number} len the length of the string.263 * @param {Number} pos the starting position for the crc32 computation.264 * @return {Number} the computed crc32.265 */266function crc32str(crc, str, len, pos) {267 var t = crcTable, end = pos + len;268 269 crc = crc ^ (-1);270 271 for (var i = pos; i < end; i++ ) {272 crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];273 }274 275 return (crc ^ (-1)); // >>> 0;276}277 278module.exports = function crc32wrapper(input, crc) {279 if (typeof input === "undefined" || !input.length) {280 return 0;281 }282 283 var isArray = utils.getTypeOf(input) !== "string";284 285 if(isArray) {286 return crc32(crc|0, input, input.length, 0);287 } else {288 return crc32str(crc|0, input, input.length, 0);289 }290};291 292},{"./utils":32}],5:[function(require,module,exports){293"use strict";294exports.base64 = false;295exports.binary = false;296exports.dir = false;297exports.createFolders = true;298exports.date = null;299exports.compression = null;300exports.compressionOptions = null;301exports.comment = null;302exports.unixPermissions = null;303exports.dosPermissions = null;304 305},{}],6:[function(require,module,exports){306"use strict";307 308// load the global object first:309// - it should be better integrated in the system (unhandledRejection in node)310// - the environment may have a custom Promise implementation (see zone.js)311var ES6Promise = null;312if (typeof Promise !== "undefined") {313 ES6Promise = Promise;314} else {315 ES6Promise = require("lie");316}317 318/**319 * Let the user use/change some implementations.320 */321module.exports = {322 Promise: ES6Promise323};324 325},{"lie":37}],7:[function(require,module,exports){326"use strict";327var USE_TYPEDARRAY = (typeof Uint8Array !== "undefined") && (typeof Uint16Array !== "undefined") && (typeof Uint32Array !== "undefined");328 329var pako = require("pako");330var utils = require("./utils");331var GenericWorker = require("./stream/GenericWorker");332 333var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";334 335exports.magic = "\x08\x00";336 337/**338 * Create a worker that uses pako to inflate/deflate.339 * @constructor340 * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate".341 * @param {Object} options the options to use when (de)compressing.342 */343function FlateWorker(action, options) {344 GenericWorker.call(this, "FlateWorker/" + action);345 346 this._pako = null;347 this._pakoAction = action;348 this._pakoOptions = options;349 // the `meta` object from the last chunk received350 // this allow this worker to pass around metadata351 this.meta = {};352}353 354utils.inherits(FlateWorker, GenericWorker);355 356/**357 * @see GenericWorker.processChunk358 */359FlateWorker.prototype.processChunk = function (chunk) {360 this.meta = chunk.meta;361 if (this._pako === null) {362 this._createPako();363 }364 this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);365};366 367/**368 * @see GenericWorker.flush369 */370FlateWorker.prototype.flush = function () {371 GenericWorker.prototype.flush.call(this);372 if (this._pako === null) {373 this._createPako();374 }375 this._pako.push([], true);376};377/**378 * @see GenericWorker.cleanUp379 */380FlateWorker.prototype.cleanUp = function () {381 GenericWorker.prototype.cleanUp.call(this);382 this._pako = null;383};384 385/**386 * Create the _pako object.387 * TODO: lazy-loading this object isn't the best solution but it's the388 * quickest. The best solution is to lazy-load the worker list. See also the389 * issue #446.390 */391FlateWorker.prototype._createPako = function () {392 this._pako = new pako[this._pakoAction]({393 raw: true,394 level: this._pakoOptions.level || -1 // default compression395 });396 var self = this;397 this._pako.onData = function(data) {398 self.push({399 data : data,400 meta : self.meta401 });402 };403};404 405exports.compressWorker = function (compressionOptions) {406 return new FlateWorker("Deflate", compressionOptions);407};408exports.uncompressWorker = function () {409 return new FlateWorker("Inflate", {});410};411 412},{"./stream/GenericWorker":28,"./utils":32,"pako":38}],8:[function(require,module,exports){413"use strict";414 415var utils = require("../utils");416var GenericWorker = require("../stream/GenericWorker");417var utf8 = require("../utf8");418var crc32 = require("../crc32");419var signature = require("../signature");420 421/**422 * Transform an integer into a string in hexadecimal.423 * @private424 * @param {number} dec the number to convert.425 * @param {number} bytes the number of bytes to generate.426 * @returns {string} the result.427 */428var decToHex = function(dec, bytes) {429 var hex = "", i;430 for (i = 0; i < bytes; i++) {431 hex += String.fromCharCode(dec & 0xff);432 dec = dec >>> 8;433 }434 return hex;435};436 437/**438 * Generate the UNIX part of the external file attributes.439 * @param {Object} unixPermissions the unix permissions or null.440 * @param {Boolean} isDir true if the entry is a directory, false otherwise.441 * @return {Number} a 32 bit integer.442 *443 * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :444 *445 * TTTTsstrwxrwxrwx0000000000ADVSHR446 * ^^^^____________________________ file type, see zipinfo.c (UNX_*)447 * ^^^_________________________ setuid, setgid, sticky448 * ^^^^^^^^^________________ permissions449 * ^^^^^^^^^^______ not used ?450 * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only451 */452var generateUnixExternalFileAttr = function (unixPermissions, isDir) {453 454 var result = unixPermissions;455 if (!unixPermissions) {456 // I can't use octal values in strict mode, hence the hexa.457 // 040775 => 0x41fd458 // 0100664 => 0x81b4459 result = isDir ? 0x41fd : 0x81b4;460 }461 return (result & 0xFFFF) << 16;462};463 464/**465 * Generate the DOS part of the external file attributes.466 * @param {Object} dosPermissions the dos permissions or null.467 * @param {Boolean} isDir true if the entry is a directory, false otherwise.468 * @return {Number} a 32 bit integer.469 *470 * Bit 0 Read-Only471 * Bit 1 Hidden472 * Bit 2 System473 * Bit 3 Volume Label474 * Bit 4 Directory475 * Bit 5 Archive476 */477var generateDosExternalFileAttr = function (dosPermissions) {478 // the dir flag is already set for compatibility479 return (dosPermissions || 0) & 0x3F;480};481 482/**483 * Generate the various parts used in the construction of the final zip file.484 * @param {Object} streamInfo the hash with information about the compressed file.485 * @param {Boolean} streamedContent is the content streamed ?486 * @param {Boolean} streamingEnded is the stream finished ?487 * @param {number} offset the current offset from the start of the zip file.488 * @param {String} platform let's pretend we are this platform (change platform dependents fields)489 * @param {Function} encodeFileName the function to encode the file name / comment.490 * @return {Object} the zip parts.491 */492var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {493 var file = streamInfo["file"],494 compression = streamInfo["compression"],495 useCustomEncoding = encodeFileName !== utf8.utf8encode,496 encodedFileName = utils.transformTo("string", encodeFileName(file.name)),497 utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),498 comment = file.comment,499 encodedComment = utils.transformTo("string", encodeFileName(comment)),500 utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),501 useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,502 useUTF8ForComment = utfEncodedComment.length !== comment.length,503 dosTime,504 dosDate,505 extraFields = "",506 unicodePathExtraField = "",507 unicodeCommentExtraField = "",508 dir = file.dir,509 date = file.date;510 511 512 var dataInfo = {513 crc32 : 0,514 compressedSize : 0,515 uncompressedSize : 0516 };517 518 // if the content is streamed, the sizes/crc32 are only available AFTER519 // the end of the stream.520 if (!streamedContent || streamingEnded) {521 dataInfo.crc32 = streamInfo["crc32"];522 dataInfo.compressedSize = streamInfo["compressedSize"];523 dataInfo.uncompressedSize = streamInfo["uncompressedSize"];524 }525 526 var bitflag = 0;527 if (streamedContent) {528 // Bit 3: the sizes/crc32 are set to zero in the local header.529 // The correct values are put in the data descriptor immediately530 // following the compressed data.531 bitflag |= 0x0008;532 }533 if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {534 // Bit 11: Language encoding flag (EFS).535 bitflag |= 0x0800;536 }537 538 539 var extFileAttr = 0;540 var versionMadeBy = 0;541 if (dir) {542 // dos or unix, we set the dos dir flag543 extFileAttr |= 0x00010;544 }545 if(platform === "UNIX") {546 versionMadeBy = 0x031E; // UNIX, version 3.0547 extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);548 } else { // DOS or other, fallback to DOS549 versionMadeBy = 0x0014; // DOS, version 2.0550 extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);551 }552 553 // date554 // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html555 // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html556 // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html557 558 dosTime = date.getUTCHours();559 dosTime = dosTime << 6;560 dosTime = dosTime | date.getUTCMinutes();561 dosTime = dosTime << 5;562 dosTime = dosTime | date.getUTCSeconds() / 2;563 564 dosDate = date.getUTCFullYear() - 1980;565 dosDate = dosDate << 4;566 dosDate = dosDate | (date.getUTCMonth() + 1);567 dosDate = dosDate << 5;568 dosDate = dosDate | date.getUTCDate();569 570 if (useUTF8ForFileName) {571 // set the unicode path extra field. unzip needs at least one extra572 // field to correctly handle unicode path, so using the path is as good573 // as any other information. This could improve the situation with574 // other archive managers too.575 // This field is usually used without the utf8 flag, with a non576 // unicode path in the header (winrar, winzip). This helps (a bit)577 // with the messy Windows' default compressed folders feature but578 // breaks on p7zip which doesn't seek the unicode path extra field.579 // So for now, UTF-8 everywhere !580 unicodePathExtraField =581 // Version582 decToHex(1, 1) +583 // NameCRC32584 decToHex(crc32(encodedFileName), 4) +585 // UnicodeName586 utfEncodedFileName;587 588 extraFields +=589 // Info-ZIP Unicode Path Extra Field590 "\x75\x70" +591 // size592 decToHex(unicodePathExtraField.length, 2) +593 // content594 unicodePathExtraField;595 }596 597 if(useUTF8ForComment) {598 599 unicodeCommentExtraField =600 // Version601 decToHex(1, 1) +602 // CommentCRC32603 decToHex(crc32(encodedComment), 4) +604 // UnicodeName605 utfEncodedComment;606 607 extraFields +=608 // Info-ZIP Unicode Path Extra Field609 "\x75\x63" +610 // size611 decToHex(unicodeCommentExtraField.length, 2) +612 // content613 unicodeCommentExtraField;614 }615 616 var header = "";617 618 // version needed to extract619 header += "\x0A\x00";620 // general purpose bit flag621 header += decToHex(bitflag, 2);622 // compression method623 header += compression.magic;624 // last mod file time625 header += decToHex(dosTime, 2);626 // last mod file date627 header += decToHex(dosDate, 2);628 // crc-32629 header += decToHex(dataInfo.crc32, 4);630 // compressed size631 header += decToHex(dataInfo.compressedSize, 4);632 // uncompressed size633 header += decToHex(dataInfo.uncompressedSize, 4);634 // file name length635 header += decToHex(encodedFileName.length, 2);636 // extra field length637 header += decToHex(extraFields.length, 2);638 639 640 var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;641 642 var dirRecord = signature.CENTRAL_FILE_HEADER +643 // version made by (00: DOS)644 decToHex(versionMadeBy, 2) +645 // file header (common to file and central directory)646 header +647 // file comment length648 decToHex(encodedComment.length, 2) +649 // disk number start650 "\x00\x00" +651 // internal file attributes TODO652 "\x00\x00" +653 // external file attributes654 decToHex(extFileAttr, 4) +655 // relative offset of local header656 decToHex(offset, 4) +657 // file name658 encodedFileName +659 // extra field660 extraFields +661 // file comment662 encodedComment;663 664 return {665 fileRecord: fileRecord,666 dirRecord: dirRecord667 };668};669 670/**671 * Generate the EOCD record.672 * @param {Number} entriesCount the number of entries in the zip file.673 * @param {Number} centralDirLength the length (in bytes) of the central dir.674 * @param {Number} localDirLength the length (in bytes) of the local dir.675 * @param {String} comment the zip file comment as a binary string.676 * @param {Function} encodeFileName the function to encode the comment.677 * @return {String} the EOCD record.678 */679var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {680 var dirEnd = "";681 var encodedComment = utils.transformTo("string", encodeFileName(comment));682 683 // end of central dir signature684 dirEnd = signature.CENTRAL_DIRECTORY_END +685 // number of this disk686 "\x00\x00" +687 // number of the disk with the start of the central directory688 "\x00\x00" +689 // total number of entries in the central directory on this disk690 decToHex(entriesCount, 2) +691 // total number of entries in the central directory692 decToHex(entriesCount, 2) +693 // size of the central directory 4 bytes694 decToHex(centralDirLength, 4) +695 // offset of start of central directory with respect to the starting disk number696 decToHex(localDirLength, 4) +697 // .ZIP file comment length698 decToHex(encodedComment.length, 2) +699 // .ZIP file comment700 encodedComment;701 702 return dirEnd;703};704 705/**706 * Generate data descriptors for a file entry.707 * @param {Object} streamInfo the hash generated by a worker, containing information708 * on the file entry.709 * @return {String} the data descriptors.710 */711var generateDataDescriptors = function (streamInfo) {712 var descriptor = "";713 descriptor = signature.DATA_DESCRIPTOR +714 // crc-32 4 bytes715 decToHex(streamInfo["crc32"], 4) +716 // compressed size 4 bytes717 decToHex(streamInfo["compressedSize"], 4) +718 // uncompressed size 4 bytes719 decToHex(streamInfo["uncompressedSize"], 4);720 721 return descriptor;722};723 724 725/**726 * A worker to concatenate other workers to create a zip file.727 * @param {Boolean} streamFiles `true` to stream the content of the files,728 * `false` to accumulate it.729 * @param {String} comment the comment to use.730 * @param {String} platform the platform to use, "UNIX" or "DOS".731 * @param {Function} encodeFileName the function to encode file names and comments.732 */733function ZipFileWorker(streamFiles, comment, platform, encodeFileName) {734 GenericWorker.call(this, "ZipFileWorker");735 // The number of bytes written so far. This doesn't count accumulated chunks.736 this.bytesWritten = 0;737 // The comment of the zip file738 this.zipComment = comment;739 // The platform "generating" the zip file.740 this.zipPlatform = platform;741 // the function to encode file names and comments.742 this.encodeFileName = encodeFileName;743 // Should we stream the content of the files ?744 this.streamFiles = streamFiles;745 // If `streamFiles` is false, we will need to accumulate the content of the746 // files to calculate sizes / crc32 (and write them *before* the content).747 // This boolean indicates if we are accumulating chunks (it will change a lot748 // during the lifetime of this worker).749 this.accumulate = false;750 // The buffer receiving chunks when accumulating content.751 this.contentBuffer = [];752 // The list of generated directory records.753 this.dirRecords = [];754 // The offset (in bytes) from the beginning of the zip file for the current source.755 this.currentSourceOffset = 0;756 // The total number of entries in this zip file.757 this.entriesCount = 0;758 // the name of the file currently being added, null when handling the end of the zip file.759 // Used for the emitted metadata.760 this.currentFile = null;761 762 763 764 this._sources = [];765}766utils.inherits(ZipFileWorker, GenericWorker);767 768/**769 * @see GenericWorker.push770 */771ZipFileWorker.prototype.push = function (chunk) {772 773 var currentFilePercent = chunk.meta.percent || 0;774 var entriesCount = this.entriesCount;775 var remainingFiles = this._sources.length;776 777 if(this.accumulate) {778 this.contentBuffer.push(chunk);779 } else {780 this.bytesWritten += chunk.data.length;781 782 GenericWorker.prototype.push.call(this, {783 data : chunk.data,784 meta : {785 currentFile : this.currentFile,786 percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100787 }788 });789 }790};791 792/**793 * The worker started a new source (an other worker).794 * @param {Object} streamInfo the streamInfo object from the new source.795 */796ZipFileWorker.prototype.openedSource = function (streamInfo) {797 this.currentSourceOffset = this.bytesWritten;798 this.currentFile = streamInfo["file"].name;799 800 var streamedContent = this.streamFiles && !streamInfo["file"].dir;801 802 // don't stream folders (because they don't have any content)803 if(streamedContent) {804 var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);805 this.push({806 data : record.fileRecord,807 meta : {percent:0}808 });809 } else {810 // we need to wait for the whole file before pushing anything811 this.accumulate = true;812 }813};814 815/**816 * The worker finished a source (an other worker).817 * @param {Object} streamInfo the streamInfo object from the finished source.818 */819ZipFileWorker.prototype.closedSource = function (streamInfo) {820 this.accumulate = false;821 var streamedContent = this.streamFiles && !streamInfo["file"].dir;822 var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);823 824 this.dirRecords.push(record.dirRecord);825 if(streamedContent) {826 // after the streamed file, we put data descriptors827 this.push({828 data : generateDataDescriptors(streamInfo),829 meta : {percent:100}830 });831 } else {832 // the content wasn't streamed, we need to push everything now833 // first the file record, then the content834 this.push({835 data : record.fileRecord,836 meta : {percent:0}837 });838 while(this.contentBuffer.length) {839 this.push(this.contentBuffer.shift());840 }841 }842 this.currentFile = null;843};844 845/**846 * @see GenericWorker.flush847 */848ZipFileWorker.prototype.flush = function () {849 850 var localDirLength = this.bytesWritten;851 for(var i = 0; i < this.dirRecords.length; i++) {852 this.push({853 data : this.dirRecords[i],854 meta : {percent:100}855 });856 }857 var centralDirLength = this.bytesWritten - localDirLength;858 859 var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);860 861 this.push({862 data : dirEnd,863 meta : {percent:100}864 });865};866 867/**868 * Prepare the next source to be read.869 */870ZipFileWorker.prototype.prepareNextSource = function () {871 this.previous = this._sources.shift();872 this.openedSource(this.previous.streamInfo);873 if (this.isPaused) {874 this.previous.pause();875 } else {876 this.previous.resume();877 }878};879 880/**881 * @see GenericWorker.registerPrevious882 */883ZipFileWorker.prototype.registerPrevious = function (previous) {884 this._sources.push(previous);885 var self = this;886 887 previous.on("data", function (chunk) {888 self.processChunk(chunk);889 });890 previous.on("end", function () {891 self.closedSource(self.previous.streamInfo);892 if(self._sources.length) {893 self.prepareNextSource();894 } else {895 self.end();896 }897 });898 previous.on("error", function (e) {899 self.error(e);900 });901 return this;902};903 904/**905 * @see GenericWorker.resume906 */907ZipFileWorker.prototype.resume = function () {908 if(!GenericWorker.prototype.resume.call(this)) {909 return false;910 }911 912 if (!this.previous && this._sources.length) {913 this.prepareNextSource();914 return true;915 }916 if (!this.previous && !this._sources.length && !this.generatedError) {917 this.end();918 return true;919 }920};921 922/**923 * @see GenericWorker.error924 */925ZipFileWorker.prototype.error = function (e) {926 var sources = this._sources;927 if(!GenericWorker.prototype.error.call(this, e)) {928 return false;929 }930 for(var i = 0; i < sources.length; i++) {931 try {932 sources[i].error(e);933 } catch(e) {934 // the `error` exploded, nothing to do935 }936 }937 return true;938};939 940/**941 * @see GenericWorker.lock942 */943ZipFileWorker.prototype.lock = function () {944 GenericWorker.prototype.lock.call(this);945 var sources = this._sources;946 for(var i = 0; i < sources.length; i++) {947 sources[i].lock();948 }949};950 951module.exports = ZipFileWorker;952 953},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(require,module,exports){954"use strict";955 956var compressions = require("../compressions");957var ZipFileWorker = require("./ZipFileWorker");958 959/**960 * Find the compression to use.961 * @param {String} fileCompression the compression defined at the file level, if any.962 * @param {String} zipCompression the compression defined at the load() level.963 * @return {Object} the compression object to use.964 */965var getCompression = function (fileCompression, zipCompression) {966 967 var compressionName = fileCompression || zipCompression;968 var compression = compressions[compressionName];969 if (!compression) {970 throw new Error(compressionName + " is not a valid compression method !");971 }972 return compression;973};974 975/**976 * Create a worker to generate a zip file.977 * @param {JSZip} zip the JSZip instance at the right root level.978 * @param {Object} options to generate the zip file.979 * @param {String} comment the comment to use.980 */981exports.generateWorker = function (zip, options, comment) {982 983 var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);984 var entriesCount = 0;985 try {986 987 zip.forEach(function (relativePath, file) {988 entriesCount++;989 var compression = getCompression(file.options.compression, options.compression);990 var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};991 var dir = file.dir, date = file.date;992 993 file._compressWorker(compression, compressionOptions)994 .withStreamInfo("file", {995 name : relativePath,996 dir : dir,997 date : date,998 comment : file.comment || "",999 unixPermissions : file.unixPermissions,1000 dosPermissions : file.dosPermissions1001 })1002 .pipe(zipFileWorker);1003 });1004 zipFileWorker.entriesCount = entriesCount;1005 } catch (e) {1006 zipFileWorker.error(e);1007 }1008 1009 return zipFileWorker;1010};1011 1012},{"../compressions":3,"./ZipFileWorker":8}],10:[function(require,module,exports){1013"use strict";1014 1015/**1016 * Representation a of zip file in js1017 * @constructor1018 */1019function JSZip() {1020 // if this constructor is used without `new`, it adds `new` before itself:1021 if(!(this instanceof JSZip)) {1022 return new JSZip();1023 }1024 1025 if(arguments.length) {1026 throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");1027 }1028 1029 // object containing the files :1030 // {1031 // "folder/" : {...},1032 // "folder/data.txt" : {...}1033 // }1034 // NOTE: we use a null prototype because we do not1035 // want filenames like "toString" coming from a zip file1036 // to overwrite methods and attributes in a normal Object.1037 this.files = Object.create(null);1038 1039 this.comment = null;1040 1041 // Where we are in the hierarchy1042 this.root = "";1043 this.clone = function() {1044 var newObj = new JSZip();1045 for (var i in this) {1046 if (typeof this[i] !== "function") {1047 newObj[i] = this[i];1048 }1049 }1050 return newObj;1051 };1052}1053JSZip.prototype = require("./object");1054JSZip.prototype.loadAsync = require("./load");1055JSZip.support = require("./support");1056JSZip.defaults = require("./defaults");1057 1058// TODO find a better way to handle this version,1059// a require('package.json').version doesn't work with webpack, see #3271060JSZip.version = "3.10.1";1061 1062JSZip.loadAsync = function (content, options) {1063 return new JSZip().loadAsync(content, options);1064};1065 1066JSZip.external = require("./external");1067module.exports = JSZip;1068 1069},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(require,module,exports){1070"use strict";1071var utils = require("./utils");1072var external = require("./external");1073var utf8 = require("./utf8");1074var ZipEntries = require("./zipEntries");1075var Crc32Probe = require("./stream/Crc32Probe");1076var nodejsUtils = require("./nodejsUtils");1077 1078/**1079 * Check the CRC32 of an entry.1080 * @param {ZipEntry} zipEntry the zip entry to check.1081 * @return {Promise} the result.1082 */1083function checkEntryCRC32(zipEntry) {1084 return new external.Promise(function (resolve, reject) {1085 var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());1086 worker.on("error", function (e) {1087 reject(e);1088 })1089 .on("end", function () {1090 if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {1091 reject(new Error("Corrupted zip : CRC32 mismatch"));1092 } else {1093 resolve();1094 }1095 })1096 .resume();1097 });1098}1099 1100module.exports = function (data, options) {1101 var zip = this;1102 options = utils.extend(options || {}, {1103 base64: false,1104 checkCRC32: false,1105 optimizedBinaryString: false,1106 createFolders: false,1107 decodeFileName: utf8.utf8decode1108 });1109 1110 if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {1111 return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));1112 }1113 1114 return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)1115 .then(function (data) {1116 var zipEntries = new ZipEntries(options);1117 zipEntries.load(data);1118 return zipEntries;1119 }).then(function checkCRC32(zipEntries) {1120 var promises = [external.Promise.resolve(zipEntries)];1121 var files = zipEntries.files;1122 if (options.checkCRC32) {1123 for (var i = 0; i < files.length; i++) {1124 promises.push(checkEntryCRC32(files[i]));1125 }1126 }1127 return external.Promise.all(promises);1128 }).then(function addFiles(results) {1129 var zipEntries = results.shift();1130 var files = zipEntries.files;1131 for (var i = 0; i < files.length; i++) {1132 var input = files[i];1133 1134 var unsafeName = input.fileNameStr;1135 var safeName = utils.resolve(input.fileNameStr);1136 1137 zip.file(safeName, input.decompressed, {1138 binary: true,1139 optimizedBinaryString: true,1140 date: input.date,1141 dir: input.dir,1142 comment: input.fileCommentStr.length ? input.fileCommentStr : null,1143 unixPermissions: input.unixPermissions,1144 dosPermissions: input.dosPermissions,1145 createFolders: options.createFolders1146 });1147 if (!input.dir) {1148 zip.file(safeName).unsafeOriginalName = unsafeName;1149 }1150 }1151 if (zipEntries.zipComment.length) {1152 zip.comment = zipEntries.zipComment;1153 }1154 1155 return zip;1156 });1157};1158 1159},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(require,module,exports){1160"use strict";1161 1162var utils = require("../utils");1163var GenericWorker = require("../stream/GenericWorker");1164 1165/**1166 * A worker that use a nodejs stream as source.1167 * @constructor1168 * @param {String} filename the name of the file entry for this stream.1169 * @param {Readable} stream the nodejs stream.1170 */1171function NodejsStreamInputAdapter(filename, stream) {1172 GenericWorker.call(this, "Nodejs stream input adapter for " + filename);1173 this._upstreamEnded = false;1174 this._bindStream(stream);1175}1176 1177utils.inherits(NodejsStreamInputAdapter, GenericWorker);1178 1179/**1180 * Prepare the stream and bind the callbacks on it.1181 * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.1182 * @param {Stream} stream the nodejs stream to use.1183 */1184NodejsStreamInputAdapter.prototype._bindStream = function (stream) {1185 var self = this;1186 this._stream = stream;1187 stream.pause();1188 stream1189 .on("data", function (chunk) {1190 self.push({1191 data: chunk,1192 meta : {1193 percent : 01194 }1195 });1196 })1197 .on("error", function (e) {1198 if(self.isPaused) {1199 this.generatedError = e;1200 } else {