TrinetraLabs/Placebo_AI
0
1"use strict";2 3var support = require("./support");4var base64 = require("./base64");5var nodejsUtils = require("./nodejsUtils");6var external = require("./external");7require("setimmediate");8 9 10/**11 * Convert a string that pass as a "binary string": it should represent a byte12 * array but may have > 255 char codes. Be sure to take only the first byte13 * and returns the byte array.14 * @param {String} str the string to transform.15 * @return {Array|Uint8Array} the string in a binary format.16 */17function string2binary(str) {18 var result = null;19 if (support.uint8array) {20 result = new Uint8Array(str.length);21 } else {22 result = new Array(str.length);23 }24 return stringToArrayLike(str, result);25}26 27/**28 * Create a new blob with the given content and the given type.29 * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use30 * an Uint8Array because the stock browser of android 4 won't accept it (it31 * will be silently converted to a string, "[object Uint8Array]").32 *33 * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge:34 * when a large amount of Array is used to create the Blob, the amount of35 * memory consumed is nearly 100 times the original data amount.36 *37 * @param {String} type the mime type of the blob.38 * @return {Blob} the created blob.39 */40exports.newBlob = function(part, type) {41 exports.checkSupport("blob");42 43 try {44 // Blob constructor45 return new Blob([part], {46 type: type47 });48 }49 catch (e) {50 51 try {52 // deprecated, browser only, old way53 var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;54 var builder = new Builder();55 builder.append(part);56 return builder.getBlob(type);57 }58 catch (e) {59 60 // well, fuck ?!61 throw new Error("Bug : can't construct the Blob.");62 }63 }64 65 66};67/**68 * The identity function.69 * @param {Object} input the input.70 * @return {Object} the same input.71 */72function identity(input) {73 return input;74}75 76/**77 * Fill in an array with a string.78 * @param {String} str the string to use.79 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).80 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.81 */82function stringToArrayLike(str, array) {83 for (var i = 0; i < str.length; ++i) {84 array[i] = str.charCodeAt(i) & 0xFF;85 }86 return array;87}88 89/**90 * An helper for the function arrayLikeToString.91 * This contains static information and functions that92 * can be optimized by the browser JIT compiler.93 */94var arrayToStringHelper = {95 /**96 * Transform an array of int into a string, chunk by chunk.97 * See the performances notes on arrayLikeToString.98 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.99 * @param {String} type the type of the array.100 * @param {Integer} chunk the chunk size.101 * @return {String} the resulting string.102 * @throws Error if the chunk is too big for the stack.103 */104 stringifyByChunk: function(array, type, chunk) {105 var result = [], k = 0, len = array.length;106 // shortcut107 if (len <= chunk) {108 return String.fromCharCode.apply(null, array);109 }110 while (k < len) {111 if (type === "array" || type === "nodebuffer") {112 result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));113 }114 else {115 result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));116 }117 k += chunk;118 }119 return result.join("");120 },121 /**122 * Call String.fromCharCode on every item in the array.123 * This is the naive implementation, which generate A LOT of intermediate string.124 * This should be used when everything else fail.125 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.126 * @return {String} the result.127 */128 stringifyByChar: function(array){129 var resultStr = "";130 for(var i = 0; i < array.length; i++) {131 resultStr += String.fromCharCode(array[i]);132 }133 return resultStr;134 },135 applyCanBeUsed : {136 /**137 * true if the browser accepts to use String.fromCharCode on Uint8Array138 */139 uint8array : (function () {140 try {141 return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;142 } catch (e) {143 return false;144 }145 })(),146 /**147 * true if the browser accepts to use String.fromCharCode on nodejs Buffer.148 */149 nodebuffer : (function () {150 try {151 return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1;152 } catch (e) {153 return false;154 }155 })()156 }157};158 159/**160 * Transform an array-like object to a string.161 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.162 * @return {String} the result.163 */164function arrayLikeToString(array) {165 // Performances notes :166 // --------------------167 // String.fromCharCode.apply(null, array) is the fastest, see168 // see http://jsperf.com/converting-a-uint8array-to-a-string/2169 // but the stack is limited (and we can get huge arrays !).170 //171 // result += String.fromCharCode(array[i]); generate too many strings !172 //173 // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2174 // TODO : we now have workers that split the work. Do we still need that ?175 var chunk = 65536,176 type = exports.getTypeOf(array),177 canUseApply = true;178 if (type === "uint8array") {179 canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;180 } else if (type === "nodebuffer") {181 canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;182 }183 184 if (canUseApply) {185 while (chunk > 1) {186 try {187 return arrayToStringHelper.stringifyByChunk(array, type, chunk);188 } catch (e) {189 chunk = Math.floor(chunk / 2);190 }191 }192 }193 194 // no apply or chunk error : slow and painful algorithm195 // default browser on android 4.*196 return arrayToStringHelper.stringifyByChar(array);197}198 199exports.applyFromCharCode = arrayLikeToString;200 201 202/**203 * Copy the data from an array-like to an other array-like.204 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.205 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.206 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.207 */208function arrayLikeToArrayLike(arrayFrom, arrayTo) {209 for (var i = 0; i < arrayFrom.length; i++) {210 arrayTo[i] = arrayFrom[i];211 }212 return arrayTo;213}214 215// a matrix containing functions to transform everything into everything.216var transform = {};217 218// string to ?219transform["string"] = {220 "string": identity,221 "array": function(input) {222 return stringToArrayLike(input, new Array(input.length));223 },224 "arraybuffer": function(input) {225 return transform["string"]["uint8array"](input).buffer;226 },227 "uint8array": function(input) {228 return stringToArrayLike(input, new Uint8Array(input.length));229 },230 "nodebuffer": function(input) {231 return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length));232 }233};234 235// array to ?236transform["array"] = {237 "string": arrayLikeToString,238 "array": identity,239 "arraybuffer": function(input) {240 return (new Uint8Array(input)).buffer;241 },242 "uint8array": function(input) {243 return new Uint8Array(input);244 },245 "nodebuffer": function(input) {246 return nodejsUtils.newBufferFrom(input);247 }248};249 250// arraybuffer to ?251transform["arraybuffer"] = {252 "string": function(input) {253 return arrayLikeToString(new Uint8Array(input));254 },255 "array": function(input) {256 return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));257 },258 "arraybuffer": identity,259 "uint8array": function(input) {260 return new Uint8Array(input);261 },262 "nodebuffer": function(input) {263 return nodejsUtils.newBufferFrom(new Uint8Array(input));264 }265};266 267// uint8array to ?268transform["uint8array"] = {269 "string": arrayLikeToString,270 "array": function(input) {271 return arrayLikeToArrayLike(input, new Array(input.length));272 },273 "arraybuffer": function(input) {274 return input.buffer;275 },276 "uint8array": identity,277 "nodebuffer": function(input) {278 return nodejsUtils.newBufferFrom(input);279 }280};281 282// nodebuffer to ?283transform["nodebuffer"] = {284 "string": arrayLikeToString,285 "array": function(input) {286 return arrayLikeToArrayLike(input, new Array(input.length));287 },288 "arraybuffer": function(input) {289 return transform["nodebuffer"]["uint8array"](input).buffer;290 },291 "uint8array": function(input) {292 return arrayLikeToArrayLike(input, new Uint8Array(input.length));293 },294 "nodebuffer": identity295};296 297/**298 * Transform an input into any type.299 * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.300 * If no output type is specified, the unmodified input will be returned.301 * @param {String} outputType the output type.302 * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.303 * @throws {Error} an Error if the browser doesn't support the requested output type.304 */305exports.transformTo = function(outputType, input) {306 if (!input) {307 // undefined, null, etc308 // an empty string won't harm.309 input = "";310 }311 if (!outputType) {312 return input;313 }314 exports.checkSupport(outputType);315 var inputType = exports.getTypeOf(input);316 var result = transform[inputType][outputType](input);317 return result;318};319 320/**321 * Resolve all relative path components, "." and "..", in a path. If these relative components322 * traverse above the root then the resulting path will only contain the final path component.323 *324 * All empty components, e.g. "//", are removed.325 * @param {string} path A path with / or \ separators326 * @returns {string} The path with all relative path components resolved.327 */328exports.resolve = function(path) {329 var parts = path.split("/");330 var result = [];331 for (var index = 0; index < parts.length; index++) {332 var part = parts[index];333 // Allow the first and last component to be empty for trailing slashes.334 if (part === "." || (part === "" && index !== 0 && index !== parts.length - 1)) {335 continue;336 } else if (part === "..") {337 result.pop();338 } else {339 result.push(part);340 }341 }342 return result.join("/");343};344 345/**346 * Return the type of the input.347 * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.348 * @param {Object} input the input to identify.349 * @return {String} the (lowercase) type of the input.350 */351exports.getTypeOf = function(input) {352 if (typeof input === "string") {353 return "string";354 }355 if (Object.prototype.toString.call(input) === "[object Array]") {356 return "array";357 }358 if (support.nodebuffer && nodejsUtils.isBuffer(input)) {359 return "nodebuffer";360 }361 if (support.uint8array && input instanceof Uint8Array) {362 return "uint8array";363 }364 if (support.arraybuffer && input instanceof ArrayBuffer) {365 return "arraybuffer";366 }367};368 369/**370 * Throw an exception if the type is not supported.371 * @param {String} type the type to check.372 * @throws {Error} an Error if the browser doesn't support the requested type.373 */374exports.checkSupport = function(type) {375 var supported = support[type.toLowerCase()];376 if (!supported) {377 throw new Error(type + " is not supported by this platform");378 }379};380 381exports.MAX_VALUE_16BITS = 65535;382exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1383 384/**385 * Prettify a string read as binary.386 * @param {string} str the string to prettify.387 * @return {string} a pretty string.388 */389exports.pretty = function(str) {390 var res = "",391 code, i;392 for (i = 0; i < (str || "").length; i++) {393 code = str.charCodeAt(i);394 res += "\\x" + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();395 }396 return res;397};398 399/**400 * Defer the call of a function.401 * @param {Function} callback the function to call asynchronously.402 * @param {Array} args the arguments to give to the callback.403 */404exports.delay = function(callback, args, self) {405 setImmediate(function () {406 callback.apply(self || null, args || []);407 });408};409 410/**411 * Extends a prototype with an other, without calling a constructor with412 * side effects. Inspired by nodejs' `utils.inherits`413 * @param {Function} ctor the constructor to augment414 * @param {Function} superCtor the parent constructor to use415 */416exports.inherits = function (ctor, superCtor) {417 var Obj = function() {};418 Obj.prototype = superCtor.prototype;419 ctor.prototype = new Obj();420};421 422/**423 * Merge the objects passed as parameters into a new one.424 * @private425 * @param {...Object} var_args All objects to merge.426 * @return {Object} a new object with the data of the others.427 */428exports.extend = function() {429 var result = {}, i, attr;430 for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers431 for (attr in arguments[i]) {432 if (Object.prototype.hasOwnProperty.call(arguments[i], attr) && typeof result[attr] === "undefined") {433 result[attr] = arguments[i][attr];434 }435 }436 }437 return result;438};439 440/**441 * Transform arbitrary content into a Promise.442 * @param {String} name a name for the content being processed.443 * @param {Object} inputData the content to process.444 * @param {Boolean} isBinary true if the content is not an unicode string445 * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.446 * @param {Boolean} isBase64 true if the string content is encoded with base64.447 * @return {Promise} a promise in a format usable by JSZip.448 */449exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {450 451 // if inputData is already a promise, this flatten it.452 var promise = external.Promise.resolve(inputData).then(function(data) {453 454 455 var isBlob = support.blob && (data instanceof Blob || ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(data)) !== -1);456 457 if (isBlob && typeof FileReader !== "undefined") {458 return new external.Promise(function (resolve, reject) {459 var reader = new FileReader();460 461 reader.onload = function(e) {462 resolve(e.target.result);463 };464 reader.onerror = function(e) {465 reject(e.target.error);466 };467 reader.readAsArrayBuffer(data);468 });469 } else {470 return data;471 }472 });473 474 return promise.then(function(data) {475 var dataType = exports.getTypeOf(data);476 477 if (!dataType) {478 return external.Promise.reject(479 new Error("Can't read the data of '" + name + "'. Is it " +480 "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")481 );482 }483 // special case : it's way easier to work with Uint8Array than with ArrayBuffer484 if (dataType === "arraybuffer") {485 data = exports.transformTo("uint8array", data);486 } else if (dataType === "string") {487 if (isBase64) {488 data = base64.decode(data);489 }490 else if (isBinary) {491 // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask492 if (isOptimizedBinaryString !== true) {493 // this is a string, not in a base64 format.494 // Be sure that this is a correct "binary string"495 data = string2binary(data);496 }497 }498 }499 return data;500 });501};502 