E-Hentai Downloader

Download E-Hentai archive as zip file

2015-08-30 일자. 최신 버전을 확인하세요.

  1. // ==UserScript==
  2. // @name E-Hentai Downloader
  3. // @version 1.17.4
  4. // @description Download E-Hentai archive as zip file
  5. // @author 864907600cc
  6. // @icon https://secure.gravatar.com/avatar/147834caf9ccb0a66b2505c753747867
  7. // @match http://exhentai.org/g/*
  8. // @match http://g.e-hentai.org/g/*
  9. // @match http://r.e-hentai.org/g/*
  10. // @include http://exhentai.org/g/*
  11. // @include http://g.e-hentai.org/g/*
  12. // @include http://r.e-hentai.org/g/*
  13. // @namespace http://ext.ccloli.com
  14. // @supportURL https://github.com/ccloli/E-Hentai-Downloader/issues
  15. // @grant GM_getValue
  16. // @grant GM_setValue
  17. // @grant GM_xmlhttpRequest
  18. // @grant GM_info
  19. // ==/UserScript==
  20.  
  21. // This script using JSZip & FileSaver.js
  22.  
  23. 'use strict';
  24.  
  25. console.log('[EHD] E-Hentai Downloader is running.');
  26. console.log('[EHD] Bugs Report >', 'https://github.com/ccloli/E-Hentai-Downloader/issues | https://greasyfork.org/scripts/10379-e-hentai-downloader/feedback');
  27. console.log('[EHD] To report a bug, showing all the "[EHD]" logs is wonderful. =w=');
  28.  
  29. // Opera 12- (Presto) doesn't support generating blob url, and if generate as data url, it may cause crashes.
  30. if (navigator.userAgent.indexOf('Presto') >= 0) {
  31. alert('Your Opera doesn\'t support E-Hentai Downloader. You need to update it to Opera 15+.');
  32. throw console.error('[EHD] Opera 12- (Presto) doesn\'t support E-Hentai Downloader. UserAgent > ' + navigator.userAgent);
  33. }
  34.  
  35. // Remove IE support
  36. else if (navigator.userAgent.indexOf('Trident') >= 0) {
  37. alert('Your browser doesn\'t support E-Hentai Downloader. You need to switch to other browsers.');
  38. throw console.error('[EHD] IE doesn\'t support E-Hentai Downloader. UserAgent > ' + navigator.userAgent);
  39. }
  40.  
  41. // Simple fixed not working on Violentmonkey
  42. // Not sure why these GM_* APIs are working now... OTL
  43. /*
  44. else if ((navigator.userAgent.indexOf('OPR') >= 0 || navigator.userAgent.indexOf('Maxthon') >= 0) && !GM_info) {
  45. var GM_getValue = GM_getValue || function(i) {
  46. return localStorage.getItem(i);
  47. }
  48. var GM_setValue = GM_setValue || function(i, j) {
  49. return localStorage.setItem(i, j);
  50. }
  51. var GM_info = GM_info || {script: {}, scriptHandler: 'Violentmonkey'};
  52. //var unsafeWindow = window;
  53. }
  54. */
  55. // GreaseMonkey 3.2 beta 1 and older version can't load content of GM_xhr.response, and this can't be fix.
  56. else if (
  57. (!GM_info.scriptHandler || GM_info.scriptHandler.indexOf('GreaseMonkey') >= 0) && GM_info.version != null && (
  58. GM_info.version.split('.')[0] - 0 < 3 || (
  59. GM_info.version.split('.')[0] - 0 == 3 && (
  60. GM_info.version.split('.')[1].split('beta')[0] - 0 <= 2 &&
  61. GM_info.version.indexOf('beta') >= 0 &&
  62. GM_info.version.split('beta')[1] - 0 < 2
  63. )
  64. )
  65. )
  66. ) {
  67. alert('Your GreaseMonkey doesn\'t support E-Hentai Downloader. The first supported version is GreaseMonkey 3.2 beta 2. Please update your GreaseMonkey to enjoy. =w=');
  68. throw console.error('[EHD] GreaseMonkey doesn\'t support E-Hentai Downloader. GreaseMonkey Version > ' + GM_info.version);
  69. }
  70.  
  71. // ==========---------- JSZip Begin ----------========== //
  72. /*!
  73.  
  74. JSZip - A Javascript class for generating and reading zip files
  75. <http://stuartk.com/jszip>
  76.  
  77. (c) 2009-2014 Stuart Knightley <stuart [at] stuartk.com>
  78. Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
  79.  
  80. JSZip uses the library pako released under the MIT license :
  81. https://github.com/nodeca/pako/blob/master/LICENSE
  82. */
  83. !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){
  84. 'use strict';
  85. // private property
  86. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  87.  
  88.  
  89. // public method for encoding
  90. exports.encode = function(input, utf8) {
  91. var output = "";
  92. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  93. var i = 0;
  94.  
  95. while (i < input.length) {
  96.  
  97. chr1 = input.charCodeAt(i++);
  98. chr2 = input.charCodeAt(i++);
  99. chr3 = input.charCodeAt(i++);
  100.  
  101. enc1 = chr1 >> 2;
  102. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  103. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  104. enc4 = chr3 & 63;
  105.  
  106. if (isNaN(chr2)) {
  107. enc3 = enc4 = 64;
  108. }
  109. else if (isNaN(chr3)) {
  110. enc4 = 64;
  111. }
  112.  
  113. output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
  114.  
  115. }
  116.  
  117. return output;
  118. };
  119.  
  120. // public method for decoding
  121. exports.decode = function(input, utf8) {
  122. var output = "";
  123. var chr1, chr2, chr3;
  124. var enc1, enc2, enc3, enc4;
  125. var i = 0;
  126.  
  127. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  128.  
  129. while (i < input.length) {
  130.  
  131. enc1 = _keyStr.indexOf(input.charAt(i++));
  132. enc2 = _keyStr.indexOf(input.charAt(i++));
  133. enc3 = _keyStr.indexOf(input.charAt(i++));
  134. enc4 = _keyStr.indexOf(input.charAt(i++));
  135.  
  136. chr1 = (enc1 << 2) | (enc2 >> 4);
  137. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  138. chr3 = ((enc3 & 3) << 6) | enc4;
  139.  
  140. output = output + String.fromCharCode(chr1);
  141.  
  142. if (enc3 != 64) {
  143. output = output + String.fromCharCode(chr2);
  144. }
  145. if (enc4 != 64) {
  146. output = output + String.fromCharCode(chr3);
  147. }
  148.  
  149. }
  150.  
  151. return output;
  152.  
  153. };
  154.  
  155. },{}],2:[function(_dereq_,module,exports){
  156. 'use strict';
  157. function CompressedObject() {
  158. this.compressedSize = 0;
  159. this.uncompressedSize = 0;
  160. this.crc32 = 0;
  161. this.compressionMethod = null;
  162. this.compressedContent = null;
  163. }
  164.  
  165. CompressedObject.prototype = {
  166. /**
  167. * Return the decompressed content in an unspecified format.
  168. * The format will depend on the decompressor.
  169. * @return {Object} the decompressed content.
  170. */
  171. getContent: function() {
  172. return null; // see implementation
  173. },
  174. /**
  175. * Return the compressed content in an unspecified format.
  176. * The format will depend on the compressed conten source.
  177. * @return {Object} the compressed content.
  178. */
  179. getCompressedContent: function() {
  180. return null; // see implementation
  181. }
  182. };
  183. module.exports = CompressedObject;
  184.  
  185. },{}],3:[function(_dereq_,module,exports){
  186. 'use strict';
  187. exports.STORE = {
  188. magic: "\x00\x00",
  189. compress: function(content, compressionOptions) {
  190. return content; // no compression
  191. },
  192. uncompress: function(content) {
  193. return content; // no compression
  194. },
  195. compressInputType: null,
  196. uncompressInputType: null
  197. };
  198. exports.DEFLATE = _dereq_('./flate');
  199.  
  200. },{"./flate":8}],4:[function(_dereq_,module,exports){
  201. 'use strict';
  202.  
  203. var utils = _dereq_('./utils');
  204.  
  205. var table = [
  206. 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
  207. 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
  208. 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
  209. 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
  210. 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
  211. 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
  212. 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
  213. 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
  214. 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
  215. 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
  216. 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
  217. 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
  218. 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
  219. 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
  220. 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
  221. 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
  222. 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
  223. 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
  224. 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
  225. 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
  226. 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
  227. 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
  228. 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
  229. 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
  230. 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
  231. 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
  232. 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
  233. 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
  234. 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
  235. 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
  236. 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
  237. 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
  238. 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
  239. 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
  240. 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
  241. 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
  242. 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
  243. 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
  244. 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
  245. 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
  246. 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
  247. 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
  248. 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
  249. 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
  250. 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
  251. 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
  252. 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
  253. 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
  254. 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
  255. 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
  256. 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
  257. 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
  258. 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
  259. 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
  260. 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
  261. 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
  262. 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
  263. 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
  264. 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
  265. 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
  266. 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
  267. 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
  268. 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
  269. 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
  270. ];
  271.  
  272. /**
  273. *
  274. * Javascript crc32
  275. * http://www.webtoolkit.info/
  276. *
  277. */
  278. module.exports = function crc32(input, crc) {
  279. if (typeof input === "undefined" || !input.length) {
  280. return 0;
  281. }
  282.  
  283. var isArray = utils.getTypeOf(input) !== "string";
  284.  
  285. if (typeof(crc) == "undefined") {
  286. crc = 0;
  287. }
  288. var x = 0;
  289. var y = 0;
  290. var b = 0;
  291.  
  292. crc = crc ^ (-1);
  293. for (var i = 0, iTop = input.length; i < iTop; i++) {
  294. b = isArray ? input[i] : input.charCodeAt(i);
  295. y = (crc ^ b) & 0xFF;
  296. x = table[y];
  297. crc = (crc >>> 8) ^ x;
  298. }
  299.  
  300. return crc ^ (-1);
  301. };
  302. // vim: set shiftwidth=4 softtabstop=4:
  303.  
  304. },{"./utils":21}],5:[function(_dereq_,module,exports){
  305. 'use strict';
  306. var utils = _dereq_('./utils');
  307.  
  308. function DataReader(data) {
  309. this.data = null; // type : see implementation
  310. this.length = 0;
  311. this.index = 0;
  312. }
  313. DataReader.prototype = {
  314. /**
  315. * Check that the offset will not go too far.
  316. * @param {string} offset the additional offset to check.
  317. * @throws {Error} an Error if the offset is out of bounds.
  318. */
  319. checkOffset: function(offset) {
  320. this.checkIndex(this.index + offset);
  321. },
  322. /**
  323. * Check that the specifed index will not be too far.
  324. * @param {string} newIndex the index to check.
  325. * @throws {Error} an Error if the index is out of bounds.
  326. */
  327. checkIndex: function(newIndex) {
  328. if (this.length < newIndex || newIndex < 0) {
  329. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  330. }
  331. },
  332. /**
  333. * Change the index.
  334. * @param {number} newIndex The new index.
  335. * @throws {Error} if the new index is out of the data.
  336. */
  337. setIndex: function(newIndex) {
  338. this.checkIndex(newIndex);
  339. this.index = newIndex;
  340. },
  341. /**
  342. * Skip the next n bytes.
  343. * @param {number} n the number of bytes to skip.
  344. * @throws {Error} if the new index is out of the data.
  345. */
  346. skip: function(n) {
  347. this.setIndex(this.index + n);
  348. },
  349. /**
  350. * Get the byte at the specified index.
  351. * @param {number} i the index to use.
  352. * @return {number} a byte.
  353. */
  354. byteAt: function(i) {
  355. // see implementations
  356. },
  357. /**
  358. * Get the next number with a given byte size.
  359. * @param {number} size the number of bytes to read.
  360. * @return {number} the corresponding number.
  361. */
  362. readInt: function(size) {
  363. var result = 0,
  364. i;
  365. this.checkOffset(size);
  366. for (i = this.index + size - 1; i >= this.index; i--) {
  367. result = (result << 8) + this.byteAt(i);
  368. }
  369. this.index += size;
  370. return result;
  371. },
  372. /**
  373. * Get the next string with a given byte size.
  374. * @param {number} size the number of bytes to read.
  375. * @return {string} the corresponding string.
  376. */
  377. readString: function(size) {
  378. return utils.transformTo("string", this.readData(size));
  379. },
  380. /**
  381. * Get raw data without conversion, <size> bytes.
  382. * @param {number} size the number of bytes to read.
  383. * @return {Object} the raw data, implementation specific.
  384. */
  385. readData: function(size) {
  386. // see implementations
  387. },
  388. /**
  389. * Find the last occurence of a zip signature (4 bytes).
  390. * @param {string} sig the signature to find.
  391. * @return {number} the index of the last occurence, -1 if not found.
  392. */
  393. lastIndexOfSignature: function(sig) {
  394. // see implementations
  395. },
  396. /**
  397. * Get the next date.
  398. * @return {Date} the date.
  399. */
  400. readDate: function() {
  401. var dostime = this.readInt(4);
  402. return new Date(
  403. ((dostime >> 25) & 0x7f) + 1980, // year
  404. ((dostime >> 21) & 0x0f) - 1, // month
  405. (dostime >> 16) & 0x1f, // day
  406. (dostime >> 11) & 0x1f, // hour
  407. (dostime >> 5) & 0x3f, // minute
  408. (dostime & 0x1f) << 1); // second
  409. }
  410. };
  411. module.exports = DataReader;
  412.  
  413. },{"./utils":21}],6:[function(_dereq_,module,exports){
  414. 'use strict';
  415. exports.base64 = false;
  416. exports.binary = false;
  417. exports.dir = false;
  418. exports.createFolders = false;
  419. exports.date = null;
  420. exports.compression = null;
  421. exports.compressionOptions = null;
  422. exports.comment = null;
  423. exports.unixPermissions = null;
  424. exports.dosPermissions = null;
  425.  
  426. },{}],7:[function(_dereq_,module,exports){
  427. 'use strict';
  428. var utils = _dereq_('./utils');
  429.  
  430. /**
  431. * @deprecated
  432. * This function will be removed in a future version without replacement.
  433. */
  434. exports.string2binary = function(str) {
  435. return utils.string2binary(str);
  436. };
  437.  
  438. /**
  439. * @deprecated
  440. * This function will be removed in a future version without replacement.
  441. */
  442. exports.string2Uint8Array = function(str) {
  443. return utils.transformTo("uint8array", str);
  444. };
  445.  
  446. /**
  447. * @deprecated
  448. * This function will be removed in a future version without replacement.
  449. */
  450. exports.uint8Array2String = function(array) {
  451. return utils.transformTo("string", array);
  452. };
  453.  
  454. /**
  455. * @deprecated
  456. * This function will be removed in a future version without replacement.
  457. */
  458. exports.string2Blob = function(str) {
  459. var buffer = utils.transformTo("arraybuffer", str);
  460. return utils.arrayBuffer2Blob(buffer);
  461. };
  462.  
  463. /**
  464. * @deprecated
  465. * This function will be removed in a future version without replacement.
  466. */
  467. exports.arrayBuffer2Blob = function(buffer) {
  468. return utils.arrayBuffer2Blob(buffer);
  469. };
  470.  
  471. /**
  472. * @deprecated
  473. * This function will be removed in a future version without replacement.
  474. */
  475. exports.transformTo = function(outputType, input) {
  476. return utils.transformTo(outputType, input);
  477. };
  478.  
  479. /**
  480. * @deprecated
  481. * This function will be removed in a future version without replacement.
  482. */
  483. exports.getTypeOf = function(input) {
  484. return utils.getTypeOf(input);
  485. };
  486.  
  487. /**
  488. * @deprecated
  489. * This function will be removed in a future version without replacement.
  490. */
  491. exports.checkSupport = function(type) {
  492. return utils.checkSupport(type);
  493. };
  494.  
  495. /**
  496. * @deprecated
  497. * This value will be removed in a future version without replacement.
  498. */
  499. exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS;
  500.  
  501. /**
  502. * @deprecated
  503. * This value will be removed in a future version without replacement.
  504. */
  505. exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS;
  506.  
  507.  
  508. /**
  509. * @deprecated
  510. * This function will be removed in a future version without replacement.
  511. */
  512. exports.pretty = function(str) {
  513. return utils.pretty(str);
  514. };
  515.  
  516. /**
  517. * @deprecated
  518. * This function will be removed in a future version without replacement.
  519. */
  520. exports.findCompression = function(compressionMethod) {
  521. return utils.findCompression(compressionMethod);
  522. };
  523.  
  524. /**
  525. * @deprecated
  526. * This function will be removed in a future version without replacement.
  527. */
  528. exports.isRegExp = function (object) {
  529. return utils.isRegExp(object);
  530. };
  531.  
  532.  
  533. },{"./utils":21}],8:[function(_dereq_,module,exports){
  534. 'use strict';
  535. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  536.  
  537. var pako = _dereq_("pako");
  538. exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  539. exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  540.  
  541. exports.magic = "\x08\x00";
  542. exports.compress = function(input, compressionOptions) {
  543. return pako.deflateRaw(input, {
  544. level : compressionOptions.level || -1 // default compression
  545. });
  546. };
  547. exports.uncompress = function(input) {
  548. return pako.inflateRaw(input);
  549. };
  550.  
  551. },{"pako":24}],9:[function(_dereq_,module,exports){
  552. 'use strict';
  553.  
  554. var base64 = _dereq_('./base64');
  555.  
  556. /**
  557. Usage:
  558. zip = new JSZip();
  559. zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing");
  560. zip.folder("images").file("smile.gif", base64Data, {base64: true});
  561. zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
  562. zip.remove("tempfile");
  563.  
  564. base64zip = zip.generate();
  565.  
  566. **/
  567.  
  568. /**
  569. * Representation a of zip file in js
  570. * @constructor
  571. * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional).
  572. * @param {Object=} options the options for creating this objects (optional).
  573. */
  574. function JSZip(data, options) {
  575. // if this constructor is used without `new`, it adds `new` before itself:
  576. if(!(this instanceof JSZip)) return new JSZip(data, options);
  577.  
  578. // object containing the files :
  579. // {
  580. // "folder/" : {...},
  581. // "folder/data.txt" : {...}
  582. // }
  583. this.files = {};
  584.  
  585. this.comment = null;
  586.  
  587. // Where we are in the hierarchy
  588. this.root = "";
  589. if (data) {
  590. this.load(data, options);
  591. }
  592. this.clone = function() {
  593. var newObj = new JSZip();
  594. for (var i in this) {
  595. if (typeof this[i] !== "function") {
  596. newObj[i] = this[i];
  597. }
  598. }
  599. return newObj;
  600. };
  601. }
  602. JSZip.prototype = _dereq_('./object');
  603. JSZip.prototype.load = _dereq_('./load');
  604. JSZip.support = _dereq_('./support');
  605. JSZip.defaults = _dereq_('./defaults');
  606.  
  607. /**
  608. * @deprecated
  609. * This namespace will be removed in a future version without replacement.
  610. */
  611. JSZip.utils = _dereq_('./deprecatedPublicUtils');
  612.  
  613. JSZip.base64 = {
  614. /**
  615. * @deprecated
  616. * This method will be removed in a future version without replacement.
  617. */
  618. encode : function(input) {
  619. return base64.encode(input);
  620. },
  621. /**
  622. * @deprecated
  623. * This method will be removed in a future version without replacement.
  624. */
  625. decode : function(input) {
  626. return base64.decode(input);
  627. }
  628. };
  629. JSZip.compressions = _dereq_('./compressions');
  630. module.exports = JSZip;
  631.  
  632. },{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(_dereq_,module,exports){
  633. 'use strict';
  634. var base64 = _dereq_('./base64');
  635. var ZipEntries = _dereq_('./zipEntries');
  636. module.exports = function(data, options) {
  637. var files, zipEntries, i, input;
  638. options = options || {};
  639. if (options.base64) {
  640. data = base64.decode(data);
  641. }
  642.  
  643. zipEntries = new ZipEntries(data, options);
  644. files = zipEntries.files;
  645. for (i = 0; i < files.length; i++) {
  646. input = files[i];
  647. this.file(input.fileName, input.decompressed, {
  648. binary: true,
  649. optimizedBinaryString: true,
  650. date: input.date,
  651. dir: input.dir,
  652. comment : input.fileComment.length ? input.fileComment : null,
  653. unixPermissions : input.unixPermissions,
  654. dosPermissions : input.dosPermissions,
  655. createFolders: options.createFolders
  656. });
  657. }
  658. if (zipEntries.zipComment.length) {
  659. this.comment = zipEntries.zipComment;
  660. }
  661.  
  662. return this;
  663. };
  664.  
  665. },{"./base64":1,"./zipEntries":22}],11:[function(_dereq_,module,exports){
  666. (function (Buffer){
  667. 'use strict';
  668. module.exports = function(data, encoding){
  669. return new Buffer(data, encoding);
  670. };
  671. module.exports.test = function(b){
  672. return Buffer.isBuffer(b);
  673. };
  674.  
  675. }).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined))
  676. },{}],12:[function(_dereq_,module,exports){
  677. 'use strict';
  678. var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
  679.  
  680. function NodeBufferReader(data) {
  681. this.data = data;
  682. this.length = this.data.length;
  683. this.index = 0;
  684. }
  685. NodeBufferReader.prototype = new Uint8ArrayReader();
  686.  
  687. /**
  688. * @see DataReader.readData
  689. */
  690. NodeBufferReader.prototype.readData = function(size) {
  691. this.checkOffset(size);
  692. var result = this.data.slice(this.index, this.index + size);
  693. this.index += size;
  694. return result;
  695. };
  696. module.exports = NodeBufferReader;
  697.  
  698. },{"./uint8ArrayReader":18}],13:[function(_dereq_,module,exports){
  699. 'use strict';
  700. var support = _dereq_('./support');
  701. var utils = _dereq_('./utils');
  702. var crc32 = _dereq_('./crc32');
  703. var signature = _dereq_('./signature');
  704. var defaults = _dereq_('./defaults');
  705. var base64 = _dereq_('./base64');
  706. var compressions = _dereq_('./compressions');
  707. var CompressedObject = _dereq_('./compressedObject');
  708. var nodeBuffer = _dereq_('./nodeBuffer');
  709. var utf8 = _dereq_('./utf8');
  710. var StringWriter = _dereq_('./stringWriter');
  711. var Uint8ArrayWriter = _dereq_('./uint8ArrayWriter');
  712.  
  713. /**
  714. * Returns the raw data of a ZipObject, decompress the content if necessary.
  715. * @param {ZipObject} file the file to use.
  716. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  717. */
  718. var getRawData = function(file) {
  719. if (file._data instanceof CompressedObject) {
  720. file._data = file._data.getContent();
  721. file.options.binary = true;
  722. file.options.base64 = false;
  723.  
  724. if (utils.getTypeOf(file._data) === "uint8array") {
  725. var copy = file._data;
  726. // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
  727. // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
  728. file._data = new Uint8Array(copy.length);
  729. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  730. if (copy.length !== 0) {
  731. file._data.set(copy, 0);
  732. }
  733. }
  734. }
  735. return file._data;
  736. };
  737.  
  738. /**
  739. * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
  740. * @param {ZipObject} file the file to use.
  741. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  742. */
  743. var getBinaryData = function(file) {
  744. var result = getRawData(file),
  745. type = utils.getTypeOf(result);
  746. if (type === "string") {
  747. if (!file.options.binary) {
  748. // unicode text !
  749. // unicode string => binary string is a painful process, check if we can avoid it.
  750. if (support.nodebuffer) {
  751. return nodeBuffer(result, "utf-8");
  752. }
  753. }
  754. return file.asBinary();
  755. }
  756. return result;
  757. };
  758.  
  759. /**
  760. * Transform this._data into a string.
  761. * @param {function} filter a function String -> String, applied if not null on the result.
  762. * @return {String} the string representing this._data.
  763. */
  764. var dataToString = function(asUTF8) {
  765. var result = getRawData(this);
  766. if (result === null || typeof result === "undefined") {
  767. return "";
  768. }
  769. // if the data is a base64 string, we decode it before checking the encoding !
  770. if (this.options.base64) {
  771. result = base64.decode(result);
  772. }
  773. if (asUTF8 && this.options.binary) {
  774. // JSZip.prototype.utf8decode supports arrays as input
  775. // skip to array => string step, utf8decode will do it.
  776. result = out.utf8decode(result);
  777. }
  778. else {
  779. // no utf8 transformation, do the array => string step.
  780. result = utils.transformTo("string", result);
  781. }
  782.  
  783. if (!asUTF8 && !this.options.binary) {
  784. result = utils.transformTo("string", out.utf8encode(result));
  785. }
  786. return result;
  787. };
  788. /**
  789. * A simple object representing a file in the zip file.
  790. * @constructor
  791. * @param {string} name the name of the file
  792. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  793. * @param {Object} options the options of the file
  794. */
  795. var ZipObject = function(name, data, options) {
  796. this.name = name;
  797. this.dir = options.dir;
  798. this.date = options.date;
  799. this.comment = options.comment;
  800. this.unixPermissions = options.unixPermissions;
  801. this.dosPermissions = options.dosPermissions;
  802.  
  803. this._data = data;
  804. this.options = options;
  805.  
  806. /*
  807. * This object contains initial values for dir and date.
  808. * With them, we can check if the user changed the deprecated metadata in
  809. * `ZipObject#options` or not.
  810. */
  811. this._initialMetadata = {
  812. dir : options.dir,
  813. date : options.date
  814. };
  815. };
  816.  
  817. ZipObject.prototype = {
  818. /**
  819. * Return the content as UTF8 string.
  820. * @return {string} the UTF8 string.
  821. */
  822. asText: function() {
  823. return dataToString.call(this, true);
  824. },
  825. /**
  826. * Returns the binary content.
  827. * @return {string} the content as binary.
  828. */
  829. asBinary: function() {
  830. return dataToString.call(this, false);
  831. },
  832. /**
  833. * Returns the content as a nodejs Buffer.
  834. * @return {Buffer} the content as a Buffer.
  835. */
  836. asNodeBuffer: function() {
  837. var result = getBinaryData(this);
  838. return utils.transformTo("nodebuffer", result);
  839. },
  840. /**
  841. * Returns the content as an Uint8Array.
  842. * @return {Uint8Array} the content as an Uint8Array.
  843. */
  844. asUint8Array: function() {
  845. var result = getBinaryData(this);
  846. return utils.transformTo("uint8array", result);
  847. },
  848. /**
  849. * Returns the content as an ArrayBuffer.
  850. * @return {ArrayBuffer} the content as an ArrayBufer.
  851. */
  852. asArrayBuffer: function() {
  853. return this.asUint8Array().buffer;
  854. }
  855. };
  856.  
  857. /**
  858. * Transform an integer into a string in hexadecimal.
  859. * @private
  860. * @param {number} dec the number to convert.
  861. * @param {number} bytes the number of bytes to generate.
  862. * @returns {string} the result.
  863. */
  864. var decToHex = function(dec, bytes) {
  865. var hex = "",
  866. i;
  867. for (i = 0; i < bytes; i++) {
  868. hex += String.fromCharCode(dec & 0xff);
  869. dec = dec >>> 8;
  870. }
  871. return hex;
  872. };
  873.  
  874. /**
  875. * Merge the objects passed as parameters into a new one.
  876. * @private
  877. * @param {...Object} var_args All objects to merge.
  878. * @return {Object} a new object with the data of the others.
  879. */
  880. var extend = function() {
  881. var result = {}, i, attr;
  882. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  883. for (attr in arguments[i]) {
  884. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  885. result[attr] = arguments[i][attr];
  886. }
  887. }
  888. }
  889. return result;
  890. };
  891.  
  892. /**
  893. * Transforms the (incomplete) options from the user into the complete
  894. * set of options to create a file.
  895. * @private
  896. * @param {Object} o the options from the user.
  897. * @return {Object} the complete set of options.
  898. */
  899. var prepareFileAttrs = function(o) {
  900. o = o || {};
  901. if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
  902. o.binary = true;
  903. }
  904. o = extend(o, defaults);
  905. o.date = o.date || new Date();
  906. if (o.compression !== null) o.compression = o.compression.toUpperCase();
  907.  
  908. return o;
  909. };
  910.  
  911. /**
  912. * Add a file in the current folder.
  913. * @private
  914. * @param {string} name the name of the file
  915. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  916. * @param {Object} o the options of the file
  917. * @return {Object} the new file.
  918. */
  919. var fileAdd = function(name, data, o) {
  920. // be sure sub folders exist
  921. var dataType = utils.getTypeOf(data),
  922. parent;
  923.  
  924. o = prepareFileAttrs(o);
  925.  
  926. if (typeof o.unixPermissions === "string") {
  927. o.unixPermissions = parseInt(o.unixPermissions, 8);
  928. }
  929.  
  930. // UNX_IFDIR 0040000 see zipinfo.c
  931. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  932. o.dir = true;
  933. }
  934. // Bit 4 Directory
  935. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  936. o.dir = true;
  937. }
  938.  
  939. if (o.dir) {
  940. name = forceTrailingSlash(name);
  941. }
  942.  
  943. if (o.createFolders && (parent = parentFolder(name))) {
  944. folderAdd.call(this, parent, true);
  945. }
  946.  
  947. if (o.dir || data === null || typeof data === "undefined") {
  948. o.base64 = false;
  949. o.binary = false;
  950. data = null;
  951. dataType = null;
  952. }
  953. else if (dataType === "string") {
  954. if (o.binary && !o.base64) {
  955. // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
  956. if (o.optimizedBinaryString !== true) {
  957. // this is a string, not in a base64 format.
  958. // Be sure that this is a correct "binary string"
  959. data = utils.string2binary(data);
  960. }
  961. }
  962. }
  963. else { // arraybuffer, uint8array, ...
  964. o.base64 = false;
  965. o.binary = true;
  966.  
  967. if (!dataType && !(data instanceof CompressedObject)) {
  968. throw new Error("The data of '" + name + "' is in an unsupported format !");
  969. }
  970.  
  971. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  972. if (dataType === "arraybuffer") {
  973. data = utils.transformTo("uint8array", data);
  974. }
  975. }
  976.  
  977. var object = new ZipObject(name, data, o);
  978. this.files[name] = object;
  979. return object;
  980. };
  981.  
  982. /**
  983. * Find the parent folder of the path.
  984. * @private
  985. * @param {string} path the path to use
  986. * @return {string} the parent folder, or ""
  987. */
  988. var parentFolder = function (path) {
  989. if (path.slice(-1) == '/') {
  990. path = path.substring(0, path.length - 1);
  991. }
  992. var lastSlash = path.lastIndexOf('/');
  993. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  994. };
  995.  
  996.  
  997. /**
  998. * Returns the path with a slash at the end.
  999. * @private
  1000. * @param {String} path the path to check.
  1001. * @return {String} the path with a trailing slash.
  1002. */
  1003. var forceTrailingSlash = function(path) {
  1004. // Check the name ends with a /
  1005. if (path.slice(-1) != "/") {
  1006. path += "/"; // IE doesn't like substr(-1)
  1007. }
  1008. return path;
  1009. };
  1010. /**
  1011. * Add a (sub) folder in the current folder.
  1012. * @private
  1013. * @param {string} name the folder's name
  1014. * @param {boolean=} [createFolders] If true, automatically create sub
  1015. * folders. Defaults to false.
  1016. * @return {Object} the new folder.
  1017. */
  1018. var folderAdd = function(name, createFolders) {
  1019. createFolders = (typeof createFolders !== 'undefined') ? createFolders : false;
  1020.  
  1021. name = forceTrailingSlash(name);
  1022.  
  1023. // Does this folder already exist?
  1024. if (!this.files[name]) {
  1025. fileAdd.call(this, name, null, {
  1026. dir: true,
  1027. createFolders: createFolders
  1028. });
  1029. }
  1030. return this.files[name];
  1031. };
  1032.  
  1033. /**
  1034. * Generate a JSZip.CompressedObject for a given zipOject.
  1035. * @param {ZipObject} file the object to read.
  1036. * @param {JSZip.compression} compression the compression to use.
  1037. * @param {Object} compressionOptions the options to use when compressing.
  1038. * @return {JSZip.CompressedObject} the compressed result.
  1039. */
  1040. var generateCompressedObjectFrom = function(file, compression, compressionOptions) {
  1041. var result = new CompressedObject(),
  1042. content;
  1043.  
  1044. // the data has not been decompressed, we might reuse things !
  1045. if (file._data instanceof CompressedObject) {
  1046. result.uncompressedSize = file._data.uncompressedSize;
  1047. result.crc32 = file._data.crc32;
  1048.  
  1049. if (result.uncompressedSize === 0 || file.dir) {
  1050. compression = compressions['STORE'];
  1051. result.compressedContent = "";
  1052. result.crc32 = 0;
  1053. }
  1054. else if (file._data.compressionMethod === compression.magic) {
  1055. result.compressedContent = file._data.getCompressedContent();
  1056. }
  1057. else {
  1058. content = file._data.getContent();
  1059. // need to decompress / recompress
  1060. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
  1061. }
  1062. }
  1063. else {
  1064. // have uncompressed data
  1065. content = getBinaryData(file);
  1066. if (!content || content.length === 0 || file.dir) {
  1067. compression = compressions['STORE'];
  1068. content = "";
  1069. }
  1070. result.uncompressedSize = content.length;
  1071. result.crc32 = crc32(content);
  1072. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
  1073. }
  1074.  
  1075. result.compressedSize = result.compressedContent.length;
  1076. result.compressionMethod = compression.magic;
  1077.  
  1078. return result;
  1079. };
  1080.  
  1081.  
  1082.  
  1083.  
  1084. /**
  1085. * Generate the UNIX part of the external file attributes.
  1086. * @param {Object} unixPermissions the unix permissions or null.
  1087. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  1088. * @return {Number} a 32 bit integer.
  1089. *
  1090. * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  1091. *
  1092. * TTTTsstrwxrwxrwx0000000000ADVSHR
  1093. * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  1094. * ^^^_________________________ setuid, setgid, sticky
  1095. * ^^^^^^^^^________________ permissions
  1096. * ^^^^^^^^^^______ not used ?
  1097. * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  1098. */
  1099. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  1100.  
  1101. var result = unixPermissions;
  1102. if (!unixPermissions) {
  1103. // I can't use octal values in strict mode, hence the hexa.
  1104. // 040775 => 0x41fd
  1105. // 0100664 => 0x81b4
  1106. result = isDir ? 0x41fd : 0x81b4;
  1107. }
  1108.  
  1109. return (result & 0xFFFF) << 16;
  1110. };
  1111.  
  1112. /**
  1113. * Generate the DOS part of the external file attributes.
  1114. * @param {Object} dosPermissions the dos permissions or null.
  1115. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  1116. * @return {Number} a 32 bit integer.
  1117. *
  1118. * Bit 0 Read-Only
  1119. * Bit 1 Hidden
  1120. * Bit 2 System
  1121. * Bit 3 Volume Label
  1122. * Bit 4 Directory
  1123. * Bit 5 Archive
  1124. */
  1125. var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  1126.  
  1127. // the dir flag is already set for compatibility
  1128.  
  1129. return (dosPermissions || 0) & 0x3F;
  1130. };
  1131.  
  1132. /**
  1133. * Generate the various parts used in the construction of the final zip file.
  1134. * @param {string} name the file name.
  1135. * @param {ZipObject} file the file content.
  1136. * @param {JSZip.CompressedObject} compressedObject the compressed object.
  1137. * @param {number} offset the current offset from the start of the zip file.
  1138. * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  1139. * @return {object} the zip parts.
  1140. */
  1141. var generateZipParts = function(name, file, compressedObject, offset, platform) {
  1142. var data = compressedObject.compressedContent,
  1143. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  1144. comment = file.comment || "",
  1145. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  1146. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  1147. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  1148. o = file.options,
  1149. dosTime,
  1150. dosDate,
  1151. extraFields = "",
  1152. unicodePathExtraField = "",
  1153. unicodeCommentExtraField = "",
  1154. dir, date;
  1155.  
  1156.  
  1157. // handle the deprecated options.dir
  1158. if (file._initialMetadata.dir !== file.dir) {
  1159. dir = file.dir;
  1160. } else {
  1161. dir = o.dir;
  1162. }
  1163.  
  1164. // handle the deprecated options.date
  1165. if(file._initialMetadata.date !== file.date) {
  1166. date = file.date;
  1167. } else {
  1168. date = o.date;
  1169. }
  1170.  
  1171. var extFileAttr = 0;
  1172. var versionMadeBy = 0;
  1173. if (dir) {
  1174. // dos or unix, we set the dos dir flag
  1175. extFileAttr |= 0x00010;
  1176. }
  1177. if(platform === "UNIX") {
  1178. versionMadeBy = 0x031E; // UNIX, version 3.0
  1179. extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  1180. } else { // DOS or other, fallback to DOS
  1181. versionMadeBy = 0x0014; // DOS, version 2.0
  1182. extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  1183. }
  1184.  
  1185. // date
  1186. // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  1187. // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  1188. // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  1189.  
  1190. dosTime = date.getHours();
  1191. dosTime = dosTime << 6;
  1192. dosTime = dosTime | date.getMinutes();
  1193. dosTime = dosTime << 5;
  1194. dosTime = dosTime | date.getSeconds() / 2;
  1195.  
  1196. dosDate = date.getFullYear() - 1980;
  1197. dosDate = dosDate << 4;
  1198. dosDate = dosDate | (date.getMonth() + 1);
  1199. dosDate = dosDate << 5;
  1200. dosDate = dosDate | date.getDate();
  1201.  
  1202. if (useUTF8ForFileName) {
  1203. // set the unicode path extra field. unzip needs at least one extra
  1204. // field to correctly handle unicode path, so using the path is as good
  1205. // as any other information. This could improve the situation with
  1206. // other archive managers too.
  1207. // This field is usually used without the utf8 flag, with a non
  1208. // unicode path in the header (winrar, winzip). This helps (a bit)
  1209. // with the messy Windows' default compressed folders feature but
  1210. // breaks on p7zip which doesn't seek the unicode path extra field.
  1211. // So for now, UTF-8 everywhere !
  1212. unicodePathExtraField =
  1213. // Version
  1214. decToHex(1, 1) +
  1215. // NameCRC32
  1216. decToHex(crc32(utfEncodedFileName), 4) +
  1217. // UnicodeName
  1218. utfEncodedFileName;
  1219.  
  1220. extraFields +=
  1221. // Info-ZIP Unicode Path Extra Field
  1222. "\x75\x70" +
  1223. // size
  1224. decToHex(unicodePathExtraField.length, 2) +
  1225. // content
  1226. unicodePathExtraField;
  1227. }
  1228.  
  1229. if(useUTF8ForComment) {
  1230.  
  1231. unicodeCommentExtraField =
  1232. // Version
  1233. decToHex(1, 1) +
  1234. // CommentCRC32
  1235. decToHex(this.crc32(utfEncodedComment), 4) +
  1236. // UnicodeName
  1237. utfEncodedComment;
  1238.  
  1239. extraFields +=
  1240. // Info-ZIP Unicode Path Extra Field
  1241. "\x75\x63" +
  1242. // size
  1243. decToHex(unicodeCommentExtraField.length, 2) +
  1244. // content
  1245. unicodeCommentExtraField;
  1246. }
  1247.  
  1248. var header = "";
  1249.  
  1250. // version needed to extract
  1251. header += "\x0A\x00";
  1252. // general purpose bit flag
  1253. // set bit 11 if utf8
  1254. header += (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00";
  1255. // compression method
  1256. header += compressedObject.compressionMethod;
  1257. // last mod file time
  1258. header += decToHex(dosTime, 2);
  1259. // last mod file date
  1260. header += decToHex(dosDate, 2);
  1261. // crc-32
  1262. header += decToHex(compressedObject.crc32, 4);
  1263. // compressed size
  1264. header += decToHex(compressedObject.compressedSize, 4);
  1265. // uncompressed size
  1266. header += decToHex(compressedObject.uncompressedSize, 4);
  1267. // file name length
  1268. header += decToHex(utfEncodedFileName.length, 2);
  1269. // extra field length
  1270. header += decToHex(extraFields.length, 2);
  1271.  
  1272.  
  1273. var fileRecord = signature.LOCAL_FILE_HEADER + header + utfEncodedFileName + extraFields;
  1274.  
  1275. var dirRecord = signature.CENTRAL_FILE_HEADER +
  1276. // version made by (00: DOS)
  1277. decToHex(versionMadeBy, 2) +
  1278. // file header (common to file and central directory)
  1279. header +
  1280. // file comment length
  1281. decToHex(utfEncodedComment.length, 2) +
  1282. // disk number start
  1283. "\x00\x00" +
  1284. // internal file attributes TODO
  1285. "\x00\x00" +
  1286. // external file attributes
  1287. decToHex(extFileAttr, 4) +
  1288. // relative offset of local header
  1289. decToHex(offset, 4) +
  1290. // file name
  1291. utfEncodedFileName +
  1292. // extra field
  1293. extraFields +
  1294. // file comment
  1295. utfEncodedComment;
  1296.  
  1297. return {
  1298. fileRecord: fileRecord,
  1299. dirRecord: dirRecord,
  1300. compressedObject: compressedObject
  1301. };
  1302. };
  1303.  
  1304.  
  1305. // return the actual prototype of JSZip
  1306. var out = {
  1307. /**
  1308. * Read an existing zip and merge the data in the current JSZip object.
  1309. * The implementation is in jszip-load.js, don't forget to include it.
  1310. * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load
  1311. * @param {Object} options Options for loading the stream.
  1312. * options.base64 : is the stream in base64 ? default : false
  1313. * @return {JSZip} the current JSZip object
  1314. */
  1315. load: function(stream, options) {
  1316. throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
  1317. },
  1318.  
  1319. /**
  1320. * Filter nested files/folders with the specified function.
  1321. * @param {Function} search the predicate to use :
  1322. * function (relativePath, file) {...}
  1323. * It takes 2 arguments : the relative path and the file.
  1324. * @return {Array} An array of matching elements.
  1325. */
  1326. filter: function(search) {
  1327. var result = [],
  1328. filename, relativePath, file, fileClone;
  1329. for (filename in this.files) {
  1330. if (!this.files.hasOwnProperty(filename)) {
  1331. continue;
  1332. }
  1333. file = this.files[filename];
  1334. // return a new object, don't let the user mess with our internal objects :)
  1335. fileClone = new ZipObject(file.name, file._data, extend(file.options));
  1336. relativePath = filename.slice(this.root.length, filename.length);
  1337. if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
  1338. search(relativePath, fileClone)) { // and the file matches the function
  1339. result.push(fileClone);
  1340. }
  1341. }
  1342. return result;
  1343. },
  1344.  
  1345. /**
  1346. * Add a file to the zip file, or search a file.
  1347. * @param {string|RegExp} name The name of the file to add (if data is defined),
  1348. * the name of the file to find (if no data) or a regex to match files.
  1349. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  1350. * @param {Object} o File options
  1351. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  1352. * a file (when searching by string) or an array of files (when searching by regex).
  1353. */
  1354. file: function(name, data, o) {
  1355. if (arguments.length === 1) {
  1356. if (utils.isRegExp(name)) {
  1357. var regexp = name;
  1358. return this.filter(function(relativePath, file) {
  1359. return !file.dir && regexp.test(relativePath);
  1360. });
  1361. }
  1362. else { // text
  1363. return this.filter(function(relativePath, file) {
  1364. return !file.dir && relativePath === name;
  1365. })[0] || null;
  1366. }
  1367. }
  1368. else { // more than one argument : we have data !
  1369. name = this.root + name;
  1370. fileAdd.call(this, name, data, o);
  1371. }
  1372. return this;
  1373. },
  1374.  
  1375. /**
  1376. * Add a directory to the zip file, or search.
  1377. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  1378. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  1379. */
  1380. folder: function(arg) {
  1381. if (!arg) {
  1382. return this;
  1383. }
  1384.  
  1385. if (utils.isRegExp(arg)) {
  1386. return this.filter(function(relativePath, file) {
  1387. return file.dir && arg.test(relativePath);
  1388. });
  1389. }
  1390.  
  1391. // else, name is a new folder
  1392. var name = this.root + arg;
  1393. var newFolder = folderAdd.call(this, name);
  1394.  
  1395. // Allow chaining by returning a new object with this folder as the root
  1396. var ret = this.clone();
  1397. ret.root = newFolder.name;
  1398. return ret;
  1399. },
  1400.  
  1401. /**
  1402. * Delete a file, or a directory and all sub-files, from the zip
  1403. * @param {string} name the name of the file to delete
  1404. * @return {JSZip} this JSZip object
  1405. */
  1406. remove: function(name) {
  1407. name = this.root + name;
  1408. var file = this.files[name];
  1409. if (!file) {
  1410. // Look for any folders
  1411. if (name.slice(-1) != "/") {
  1412. name += "/";
  1413. }
  1414. file = this.files[name];
  1415. }
  1416.  
  1417. if (file && !file.dir) {
  1418. // file
  1419. delete this.files[name];
  1420. } else {
  1421. // maybe a folder, delete recursively
  1422. var kids = this.filter(function(relativePath, file) {
  1423. return file.name.slice(0, name.length) === name;
  1424. });
  1425. for (var i = 0; i < kids.length; i++) {
  1426. delete this.files[kids[i].name];
  1427. }
  1428. }
  1429.  
  1430. return this;
  1431. },
  1432.  
  1433. /**
  1434. * Generate the complete zip file
  1435. * @param {Object} options the options to generate the zip file :
  1436. * - base64, (deprecated, use type instead) true to generate base64.
  1437. * - compression, "STORE" by default.
  1438. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1439. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  1440. */
  1441. generate: function(options) {
  1442. options = extend(options || {}, {
  1443. base64: true,
  1444. compression: "STORE",
  1445. compressionOptions : null,
  1446. type: "base64",
  1447. platform: "DOS",
  1448. comment: null,
  1449. mimeType: 'application/zip'
  1450. });
  1451.  
  1452. utils.checkSupport(options.type);
  1453.  
  1454. // accept nodejs `process.platform`
  1455. if(
  1456. options.platform === 'darwin' ||
  1457. options.platform === 'freebsd' ||
  1458. options.platform === 'linux' ||
  1459. options.platform === 'sunos'
  1460. ) {
  1461. options.platform = "UNIX";
  1462. }
  1463. if (options.platform === 'win32') {
  1464. options.platform = "DOS";
  1465. }
  1466.  
  1467. var zipData = [],
  1468. localDirLength = 0,
  1469. centralDirLength = 0,
  1470. writer, i,
  1471. utfEncodedComment = utils.transformTo("string", this.utf8encode(options.comment || this.comment || ""));
  1472.  
  1473. // first, generate all the zip parts.
  1474. for (var name in this.files) {
  1475. if (!this.files.hasOwnProperty(name)) {
  1476. continue;
  1477. }
  1478. var file = this.files[name];
  1479.  
  1480. var compressionName = file.options.compression || options.compression.toUpperCase();
  1481. var compression = compressions[compressionName];
  1482. if (!compression) {
  1483. throw new Error(compressionName + " is not a valid compression method !");
  1484. }
  1485. var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  1486.  
  1487. var compressedObject = generateCompressedObjectFrom.call(this, file, compression, compressionOptions);
  1488.  
  1489. var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform);
  1490. localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
  1491. centralDirLength += zipPart.dirRecord.length;
  1492. zipData.push(zipPart);
  1493. }
  1494.  
  1495. var dirEnd = "";
  1496.  
  1497. // end of central dir signature
  1498. dirEnd = signature.CENTRAL_DIRECTORY_END +
  1499. // number of this disk
  1500. "\x00\x00" +
  1501. // number of the disk with the start of the central directory
  1502. "\x00\x00" +
  1503. // total number of entries in the central directory on this disk
  1504. decToHex(zipData.length, 2) +
  1505. // total number of entries in the central directory
  1506. decToHex(zipData.length, 2) +
  1507. // size of the central directory 4 bytes
  1508. decToHex(centralDirLength, 4) +
  1509. // offset of start of central directory with respect to the starting disk number
  1510. decToHex(localDirLength, 4) +
  1511. // .ZIP file comment length
  1512. decToHex(utfEncodedComment.length, 2) +
  1513. // .ZIP file comment
  1514. utfEncodedComment;
  1515.  
  1516.  
  1517. // we have all the parts (and the total length)
  1518. // time to create a writer !
  1519. var typeName = options.type.toLowerCase();
  1520. if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") {
  1521. writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
  1522. }else{
  1523. writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
  1524. }
  1525.  
  1526. for (i = 0; i < zipData.length; i++) {
  1527. writer.append(zipData[i].fileRecord);
  1528. writer.append(zipData[i].compressedObject.compressedContent);
  1529. }
  1530. for (i = 0; i < zipData.length; i++) {
  1531. writer.append(zipData[i].dirRecord);
  1532. }
  1533.  
  1534. writer.append(dirEnd);
  1535.  
  1536. var zip = writer.finalize();
  1537.  
  1538.  
  1539.  
  1540. switch(options.type.toLowerCase()) {
  1541. // case "zip is an Uint8Array"
  1542. case "uint8array" :
  1543. case "arraybuffer" :
  1544. case "nodebuffer" :
  1545. return utils.transformTo(options.type.toLowerCase(), zip);
  1546. case "blob" :
  1547. return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType);
  1548. // case "zip is a string"
  1549. case "base64" :
  1550. return (options.base64) ? base64.encode(zip) : zip;
  1551. default : // case "string" :
  1552. return zip;
  1553. }
  1554.  
  1555. },
  1556.  
  1557. /**
  1558. * @deprecated
  1559. * This method will be removed in a future version without replacement.
  1560. */
  1561. crc32: function (input, crc) {
  1562. return crc32(input, crc);
  1563. },
  1564.  
  1565. /**
  1566. * @deprecated
  1567. * This method will be removed in a future version without replacement.
  1568. */
  1569. utf8encode: function (string) {
  1570. return utils.transformTo("string", utf8.utf8encode(string));
  1571. },
  1572.  
  1573. /**
  1574. * @deprecated
  1575. * This method will be removed in a future version without replacement.
  1576. */
  1577. utf8decode: function (input) {
  1578. return utf8.utf8decode(input);
  1579. }
  1580. };
  1581. module.exports = out;
  1582.  
  1583. },{"./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){
  1584. 'use strict';
  1585. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  1586. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  1587. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  1588. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  1589. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  1590. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  1591.  
  1592. },{}],15:[function(_dereq_,module,exports){
  1593. 'use strict';
  1594. var DataReader = _dereq_('./dataReader');
  1595. var utils = _dereq_('./utils');
  1596.  
  1597. function StringReader(data, optimizedBinaryString) {
  1598. this.data = data;
  1599. if (!optimizedBinaryString) {
  1600. this.data = utils.string2binary(this.data);
  1601. }
  1602. this.length = this.data.length;
  1603. this.index = 0;
  1604. }
  1605. StringReader.prototype = new DataReader();
  1606. /**
  1607. * @see DataReader.byteAt
  1608. */
  1609. StringReader.prototype.byteAt = function(i) {
  1610. return this.data.charCodeAt(i);
  1611. };
  1612. /**
  1613. * @see DataReader.lastIndexOfSignature
  1614. */
  1615. StringReader.prototype.lastIndexOfSignature = function(sig) {
  1616. return this.data.lastIndexOf(sig);
  1617. };
  1618. /**
  1619. * @see DataReader.readData
  1620. */
  1621. StringReader.prototype.readData = function(size) {
  1622. this.checkOffset(size);
  1623. // this will work because the constructor applied the "& 0xff" mask.
  1624. var result = this.data.slice(this.index, this.index + size);
  1625. this.index += size;
  1626. return result;
  1627. };
  1628. module.exports = StringReader;
  1629.  
  1630. },{"./dataReader":5,"./utils":21}],16:[function(_dereq_,module,exports){
  1631. 'use strict';
  1632.  
  1633. var utils = _dereq_('./utils');
  1634.  
  1635. /**
  1636. * An object to write any content to a string.
  1637. * @constructor
  1638. */
  1639. var StringWriter = function() {
  1640. this.data = [];
  1641. };
  1642. StringWriter.prototype = {
  1643. /**
  1644. * Append any content to the current string.
  1645. * @param {Object} input the content to add.
  1646. */
  1647. append: function(input) {
  1648. input = utils.transformTo("string", input);
  1649. this.data.push(input);
  1650. },
  1651. /**
  1652. * Finalize the construction an return the result.
  1653. * @return {string} the generated string.
  1654. */
  1655. finalize: function() {
  1656. return this.data.join("");
  1657. }
  1658. };
  1659.  
  1660. module.exports = StringWriter;
  1661.  
  1662. },{"./utils":21}],17:[function(_dereq_,module,exports){
  1663. (function (Buffer){
  1664. 'use strict';
  1665. exports.base64 = true;
  1666. exports.array = true;
  1667. exports.string = true;
  1668. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  1669. // contains true if JSZip can read/generate nodejs Buffer, false otherwise.
  1670. // Browserify will provide a Buffer implementation for browsers, which is
  1671. // an augmented Uint8Array (i.e., can be used as either Buffer or U8).
  1672. exports.nodebuffer = typeof Buffer !== "undefined";
  1673. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  1674. exports.uint8array = typeof Uint8Array !== "undefined";
  1675.  
  1676. if (typeof ArrayBuffer === "undefined") {
  1677. exports.blob = false;
  1678. }
  1679. else {
  1680. var buffer = new ArrayBuffer(0);
  1681. try {
  1682. exports.blob = new Blob([buffer], {
  1683. type: "application/zip"
  1684. }).size === 0;
  1685. }
  1686. catch (e) {
  1687. try {
  1688. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  1689. var builder = new Builder();
  1690. builder.append(buffer);
  1691. exports.blob = builder.getBlob('application/zip').size === 0;
  1692. }
  1693. catch (e) {
  1694. exports.blob = false;
  1695. }
  1696. }
  1697. }
  1698.  
  1699. }).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined))
  1700. },{}],18:[function(_dereq_,module,exports){
  1701. 'use strict';
  1702. var DataReader = _dereq_('./dataReader');
  1703.  
  1704. function Uint8ArrayReader(data) {
  1705. if (data) {
  1706. this.data = data;
  1707. this.length = this.data.length;
  1708. this.index = 0;
  1709. }
  1710. }
  1711. Uint8ArrayReader.prototype = new DataReader();
  1712. /**
  1713. * @see DataReader.byteAt
  1714. */
  1715. Uint8ArrayReader.prototype.byteAt = function(i) {
  1716. return this.data[i];
  1717. };
  1718. /**
  1719. * @see DataReader.lastIndexOfSignature
  1720. */
  1721. Uint8ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  1722. var sig0 = sig.charCodeAt(0),
  1723. sig1 = sig.charCodeAt(1),
  1724. sig2 = sig.charCodeAt(2),
  1725. sig3 = sig.charCodeAt(3);
  1726. for (var i = this.length - 4; i >= 0; --i) {
  1727. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  1728. return i;
  1729. }
  1730. }
  1731.  
  1732. return -1;
  1733. };
  1734. /**
  1735. * @see DataReader.readData
  1736. */
  1737. Uint8ArrayReader.prototype.readData = function(size) {
  1738. this.checkOffset(size);
  1739. if(size === 0) {
  1740. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  1741. return new Uint8Array(0);
  1742. }
  1743. var result = this.data.subarray(this.index, this.index + size);
  1744. this.index += size;
  1745. return result;
  1746. };
  1747. module.exports = Uint8ArrayReader;
  1748.  
  1749. },{"./dataReader":5}],19:[function(_dereq_,module,exports){
  1750. 'use strict';
  1751.  
  1752. var utils = _dereq_('./utils');
  1753.  
  1754. /**
  1755. * An object to write any content to an Uint8Array.
  1756. * @constructor
  1757. * @param {number} length The length of the array.
  1758. */
  1759. var Uint8ArrayWriter = function(length) {
  1760. this.data = new Uint8Array(length);
  1761. this.index = 0;
  1762. };
  1763. Uint8ArrayWriter.prototype = {
  1764. /**
  1765. * Append any content to the current array.
  1766. * @param {Object} input the content to add.
  1767. */
  1768. append: function(input) {
  1769. if (input.length !== 0) {
  1770. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  1771. input = utils.transformTo("uint8array", input);
  1772. this.data.set(input, this.index);
  1773. this.index += input.length;
  1774. }
  1775. },
  1776. /**
  1777. * Finalize the construction an return the result.
  1778. * @return {Uint8Array} the generated array.
  1779. */
  1780. finalize: function() {
  1781. return this.data;
  1782. }
  1783. };
  1784.  
  1785. module.exports = Uint8ArrayWriter;
  1786.  
  1787. },{"./utils":21}],20:[function(_dereq_,module,exports){
  1788. 'use strict';
  1789.  
  1790. var utils = _dereq_('./utils');
  1791. var support = _dereq_('./support');
  1792. var nodeBuffer = _dereq_('./nodeBuffer');
  1793.  
  1794. /**
  1795. * The following functions come from pako, from pako/lib/utils/strings
  1796. * released under the MIT license, see pako https://github.com/nodeca/pako/
  1797. */
  1798.  
  1799. // Table with utf8 lengths (calculated by first byte of sequence)
  1800. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  1801. // because max possible codepoint is 0x10ffff
  1802. var _utf8len = new Array(256);
  1803. for (var i=0; i<256; i++) {
  1804. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  1805. }
  1806. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  1807.  
  1808. // convert string to array (typed, when possible)
  1809. var string2buf = function (str) {
  1810. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  1811.  
  1812. // count binary size
  1813. for (m_pos = 0; m_pos < str_len; m_pos++) {
  1814. c = str.charCodeAt(m_pos);
  1815. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  1816. c2 = str.charCodeAt(m_pos+1);
  1817. if ((c2 & 0xfc00) === 0xdc00) {
  1818. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  1819. m_pos++;
  1820. }
  1821. }
  1822. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  1823. }
  1824.  
  1825. // allocate buffer
  1826. if (support.uint8array) {
  1827. buf = new Uint8Array(buf_len);
  1828. } else {
  1829. buf = new Array(buf_len);
  1830. }
  1831.  
  1832. // convert
  1833. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  1834. c = str.charCodeAt(m_pos);
  1835. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  1836. c2 = str.charCodeAt(m_pos+1);
  1837. if ((c2 & 0xfc00) === 0xdc00) {
  1838. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  1839. m_pos++;
  1840. }
  1841. }
  1842. if (c < 0x80) {
  1843. /* one byte */
  1844. buf[i++] = c;
  1845. } else if (c < 0x800) {
  1846. /* two bytes */
  1847. buf[i++] = 0xC0 | (c >>> 6);
  1848. buf[i++] = 0x80 | (c & 0x3f);
  1849. } else if (c < 0x10000) {
  1850. /* three bytes */
  1851. buf[i++] = 0xE0 | (c >>> 12);
  1852. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  1853. buf[i++] = 0x80 | (c & 0x3f);
  1854. } else {
  1855. /* four bytes */
  1856. buf[i++] = 0xf0 | (c >>> 18);
  1857. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  1858. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  1859. buf[i++] = 0x80 | (c & 0x3f);
  1860. }
  1861. }
  1862.  
  1863. return buf;
  1864. };
  1865.  
  1866. // Calculate max possible position in utf8 buffer,
  1867. // that will not break sequence. If that's not possible
  1868. // - (very small limits) return max size as is.
  1869. //
  1870. // buf[] - utf8 bytes array
  1871. // max - length limit (mandatory);
  1872. var utf8border = function(buf, max) {
  1873. var pos;
  1874.  
  1875. max = max || buf.length;
  1876. if (max > buf.length) { max = buf.length; }
  1877.  
  1878. // go back from last position, until start of sequence found
  1879. pos = max-1;
  1880. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  1881.  
  1882. // Fuckup - very small and broken sequence,
  1883. // return max, because we should return something anyway.
  1884. if (pos < 0) { return max; }
  1885.  
  1886. // If we came to start of buffer - that means vuffer is too small,
  1887. // return max too.
  1888. if (pos === 0) { return max; }
  1889.  
  1890. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  1891. };
  1892.  
  1893. // convert array to string
  1894. var buf2string = function (buf) {
  1895. var str, i, out, c, c_len;
  1896. var len = buf.length;
  1897.  
  1898. // Reserve max possible length (2 words per char)
  1899. // NB: by unknown reasons, Array is significantly faster for
  1900. // String.fromCharCode.apply than Uint16Array.
  1901. var utf16buf = new Array(len*2);
  1902.  
  1903. for (out=0, i=0; i<len;) {
  1904. c = buf[i++];
  1905. // quick process ascii
  1906. if (c < 0x80) { utf16buf[out++] = c; continue; }
  1907.  
  1908. c_len = _utf8len[c];
  1909. // skip 5 & 6 byte codes
  1910. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  1911.  
  1912. // apply mask on first byte
  1913. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  1914. // join the rest
  1915. while (c_len > 1 && i < len) {
  1916. c = (c << 6) | (buf[i++] & 0x3f);
  1917. c_len--;
  1918. }
  1919.  
  1920. // terminated by end of string?
  1921. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  1922.  
  1923. if (c < 0x10000) {
  1924. utf16buf[out++] = c;
  1925. } else {
  1926. c -= 0x10000;
  1927. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  1928. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  1929. }
  1930. }
  1931.  
  1932. // shrinkBuf(utf16buf, out)
  1933. if (utf16buf.length !== out) {
  1934. if(utf16buf.subarray) {
  1935. utf16buf = utf16buf.subarray(0, out);
  1936. } else {
  1937. utf16buf.length = out;
  1938. }
  1939. }
  1940.  
  1941. // return String.fromCharCode.apply(null, utf16buf);
  1942. return utils.applyFromCharCode(utf16buf);
  1943. };
  1944.  
  1945.  
  1946. // That's all for the pako functions.
  1947.  
  1948.  
  1949. /**
  1950. * Transform a javascript string into an array (typed if possible) of bytes,
  1951. * UTF-8 encoded.
  1952. * @param {String} str the string to encode
  1953. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  1954. */
  1955. exports.utf8encode = function utf8encode(str) {
  1956. if (support.nodebuffer) {
  1957. return nodeBuffer(str, "utf-8");
  1958. }
  1959.  
  1960. return string2buf(str);
  1961. };
  1962.  
  1963.  
  1964. /**
  1965. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  1966. * string into a javascript string.
  1967. * @param {Array|Uint8Array|Buffer} buf the data de decode
  1968. * @return {String} the decoded string.
  1969. */
  1970. exports.utf8decode = function utf8decode(buf) {
  1971. if (support.nodebuffer) {
  1972. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  1973. }
  1974.  
  1975. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  1976.  
  1977. // return buf2string(buf);
  1978. // Chrome prefers to work with "small" chunks of data
  1979. // for the method buf2string.
  1980. // Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
  1981. var result = [], k = 0, len = buf.length, chunk = 65536;
  1982. while (k < len) {
  1983. var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
  1984. if (support.uint8array) {
  1985. result.push(buf2string(buf.subarray(k, nextBoundary)));
  1986. } else {
  1987. result.push(buf2string(buf.slice(k, nextBoundary)));
  1988. }
  1989. k = nextBoundary;
  1990. }
  1991. return result.join("");
  1992.  
  1993. };
  1994. // vim: set shiftwidth=4 softtabstop=4:
  1995.  
  1996. },{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(_dereq_,module,exports){
  1997. 'use strict';
  1998. var support = _dereq_('./support');
  1999. var compressions = _dereq_('./compressions');
  2000. var nodeBuffer = _dereq_('./nodeBuffer');
  2001. /**
  2002. * Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
  2003. * @param {string} str the string to transform.
  2004. * @return {String} the binary string.
  2005. */
  2006. exports.string2binary = function(str) {
  2007. var result = "";
  2008. for (var i = 0; i < str.length; i++) {
  2009. result += String.fromCharCode(str.charCodeAt(i) & 0xff);
  2010. }
  2011. return result;
  2012. };
  2013. exports.arrayBuffer2Blob = function(buffer, mimeType) {
  2014. exports.checkSupport("blob");
  2015. mimeType = mimeType || 'application/zip';
  2016.  
  2017. try {
  2018. // Blob constructor
  2019. return new Blob([buffer], {
  2020. type: mimeType
  2021. });
  2022. }
  2023. catch (e) {
  2024.  
  2025. try {
  2026. // deprecated, browser only, old way
  2027. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  2028. var builder = new Builder();
  2029. builder.append(buffer);
  2030. return builder.getBlob(mimeType);
  2031. }
  2032. catch (e) {
  2033.  
  2034. // well, fuck ?!
  2035. throw new Error("Bug : can't construct the Blob.");
  2036. }
  2037. }
  2038.  
  2039.  
  2040. };
  2041. /**
  2042. * The identity function.
  2043. * @param {Object} input the input.
  2044. * @return {Object} the same input.
  2045. */
  2046. function identity(input) {
  2047. return input;
  2048. }
  2049.  
  2050. /**
  2051. * Fill in an array with a string.
  2052. * @param {String} str the string to use.
  2053. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  2054. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  2055. */
  2056. function stringToArrayLike(str, array) {
  2057. for (var i = 0; i < str.length; ++i) {
  2058. array[i] = str.charCodeAt(i) & 0xFF;
  2059. }
  2060. return array;
  2061. }
  2062.  
  2063. /**
  2064. * Transform an array-like object to a string.
  2065. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  2066. * @return {String} the result.
  2067. */
  2068. function arrayLikeToString(array) {
  2069. // Performances notes :
  2070. // --------------------
  2071. // String.fromCharCode.apply(null, array) is the fastest, see
  2072. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  2073. // but the stack is limited (and we can get huge arrays !).
  2074. //
  2075. // result += String.fromCharCode(array[i]); generate too many strings !
  2076. //
  2077. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  2078. var chunk = 65536;
  2079. var result = [],
  2080. len = array.length,
  2081. type = exports.getTypeOf(array),
  2082. k = 0,
  2083. canUseApply = true;
  2084. try {
  2085. switch(type) {
  2086. case "uint8array":
  2087. String.fromCharCode.apply(null, new Uint8Array(0));
  2088. break;
  2089. case "nodebuffer":
  2090. String.fromCharCode.apply(null, nodeBuffer(0));
  2091. break;
  2092. }
  2093. } catch(e) {
  2094. canUseApply = false;
  2095. }
  2096.  
  2097. // no apply : slow and painful algorithm
  2098. // default browser on android 4.*
  2099. if (!canUseApply) {
  2100. var resultStr = "";
  2101. for(var i = 0; i < array.length;i++) {
  2102. resultStr += String.fromCharCode(array[i]);
  2103. }
  2104. return resultStr;
  2105. }
  2106. while (k < len && chunk > 1) {
  2107. try {
  2108. if (type === "array" || type === "nodebuffer") {
  2109. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  2110. }
  2111. else {
  2112. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  2113. }
  2114. k += chunk;
  2115. }
  2116. catch (e) {
  2117. chunk = Math.floor(chunk / 2);
  2118. }
  2119. }
  2120. return result.join("");
  2121. }
  2122.  
  2123. exports.applyFromCharCode = arrayLikeToString;
  2124.  
  2125.  
  2126. /**
  2127. * Copy the data from an array-like to an other array-like.
  2128. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  2129. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  2130. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  2131. */
  2132. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  2133. for (var i = 0; i < arrayFrom.length; i++) {
  2134. arrayTo[i] = arrayFrom[i];
  2135. }
  2136. return arrayTo;
  2137. }
  2138.  
  2139. // a matrix containing functions to transform everything into everything.
  2140. var transform = {};
  2141.  
  2142. // string to ?
  2143. transform["string"] = {
  2144. "string": identity,
  2145. "array": function(input) {
  2146. return stringToArrayLike(input, new Array(input.length));
  2147. },
  2148. "arraybuffer": function(input) {
  2149. return transform["string"]["uint8array"](input).buffer;
  2150. },
  2151. "uint8array": function(input) {
  2152. return stringToArrayLike(input, new Uint8Array(input.length));
  2153. },
  2154. "nodebuffer": function(input) {
  2155. return stringToArrayLike(input, nodeBuffer(input.length));
  2156. }
  2157. };
  2158.  
  2159. // array to ?
  2160. transform["array"] = {
  2161. "string": arrayLikeToString,
  2162. "array": identity,
  2163. "arraybuffer": function(input) {
  2164. return (new Uint8Array(input)).buffer;
  2165. },
  2166. "uint8array": function(input) {
  2167. return new Uint8Array(input);
  2168. },
  2169. "nodebuffer": function(input) {
  2170. return nodeBuffer(input);
  2171. }
  2172. };
  2173.  
  2174. // arraybuffer to ?
  2175. transform["arraybuffer"] = {
  2176. "string": function(input) {
  2177. return arrayLikeToString(new Uint8Array(input));
  2178. },
  2179. "array": function(input) {
  2180. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  2181. },
  2182. "arraybuffer": identity,
  2183. "uint8array": function(input) {
  2184. return new Uint8Array(input);
  2185. },
  2186. "nodebuffer": function(input) {
  2187. return nodeBuffer(new Uint8Array(input));
  2188. }
  2189. };
  2190.  
  2191. // uint8array to ?
  2192. transform["uint8array"] = {
  2193. "string": arrayLikeToString,
  2194. "array": function(input) {
  2195. return arrayLikeToArrayLike(input, new Array(input.length));
  2196. },
  2197. "arraybuffer": function(input) {
  2198. return input.buffer;
  2199. },
  2200. "uint8array": identity,
  2201. "nodebuffer": function(input) {
  2202. return nodeBuffer(input);
  2203. }
  2204. };
  2205.  
  2206. // nodebuffer to ?
  2207. transform["nodebuffer"] = {
  2208. "string": arrayLikeToString,
  2209. "array": function(input) {
  2210. return arrayLikeToArrayLike(input, new Array(input.length));
  2211. },
  2212. "arraybuffer": function(input) {
  2213. return transform["nodebuffer"]["uint8array"](input).buffer;
  2214. },
  2215. "uint8array": function(input) {
  2216. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  2217. },
  2218. "nodebuffer": identity
  2219. };
  2220.  
  2221. /**
  2222. * Transform an input into any type.
  2223. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  2224. * If no output type is specified, the unmodified input will be returned.
  2225. * @param {String} outputType the output type.
  2226. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  2227. * @throws {Error} an Error if the browser doesn't support the requested output type.
  2228. */
  2229. exports.transformTo = function(outputType, input) {
  2230. if (!input) {
  2231. // undefined, null, etc
  2232. // an empty string won't harm.
  2233. input = "";
  2234. }
  2235. if (!outputType) {
  2236. return input;
  2237. }
  2238. exports.checkSupport(outputType);
  2239. var inputType = exports.getTypeOf(input);
  2240. var result = transform[inputType][outputType](input);
  2241. return result;
  2242. };
  2243.  
  2244. /**
  2245. * Return the type of the input.
  2246. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  2247. * @param {Object} input the input to identify.
  2248. * @return {String} the (lowercase) type of the input.
  2249. */
  2250. exports.getTypeOf = function(input) {
  2251. if (typeof input === "string") {
  2252. return "string";
  2253. }
  2254. if (Object.prototype.toString.call(input) === "[object Array]") {
  2255. return "array";
  2256. }
  2257. if (support.nodebuffer && nodeBuffer.test(input)) {
  2258. return "nodebuffer";
  2259. }
  2260. if (support.uint8array && input instanceof Uint8Array) {
  2261. return "uint8array";
  2262. }
  2263. if (support.arraybuffer && input instanceof ArrayBuffer) {
  2264. return "arraybuffer";
  2265. }
  2266. };
  2267.  
  2268. /**
  2269. * Throw an exception if the type is not supported.
  2270. * @param {String} type the type to check.
  2271. * @throws {Error} an Error if the browser doesn't support the requested type.
  2272. */
  2273. exports.checkSupport = function(type) {
  2274. var supported = support[type.toLowerCase()];
  2275. if (!supported) {
  2276. throw new Error(type + " is not supported by this browser");
  2277. }
  2278. };
  2279. exports.MAX_VALUE_16BITS = 65535;
  2280. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  2281.  
  2282. /**
  2283. * Prettify a string read as binary.
  2284. * @param {string} str the string to prettify.
  2285. * @return {string} a pretty string.
  2286. */
  2287. exports.pretty = function(str) {
  2288. var res = '',
  2289. code, i;
  2290. for (i = 0; i < (str || "").length; i++) {
  2291. code = str.charCodeAt(i);
  2292. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  2293. }
  2294. return res;
  2295. };
  2296.  
  2297. /**
  2298. * Find a compression registered in JSZip.
  2299. * @param {string} compressionMethod the method magic to find.
  2300. * @return {Object|null} the JSZip compression object, null if none found.
  2301. */
  2302. exports.findCompression = function(compressionMethod) {
  2303. for (var method in compressions) {
  2304. if (!compressions.hasOwnProperty(method)) {
  2305. continue;
  2306. }
  2307. if (compressions[method].magic === compressionMethod) {
  2308. return compressions[method];
  2309. }
  2310. }
  2311. return null;
  2312. };
  2313. /**
  2314. * Cross-window, cross-Node-context regular expression detection
  2315. * @param {Object} object Anything
  2316. * @return {Boolean} true if the object is a regular expression,
  2317. * false otherwise
  2318. */
  2319. exports.isRegExp = function (object) {
  2320. return Object.prototype.toString.call(object) === "[object RegExp]";
  2321. };
  2322.  
  2323.  
  2324. },{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(_dereq_,module,exports){
  2325. 'use strict';
  2326. var StringReader = _dereq_('./stringReader');
  2327. var NodeBufferReader = _dereq_('./nodeBufferReader');
  2328. var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
  2329. var utils = _dereq_('./utils');
  2330. var sig = _dereq_('./signature');
  2331. var ZipEntry = _dereq_('./zipEntry');
  2332. var support = _dereq_('./support');
  2333. var jszipProto = _dereq_('./object');
  2334. // class ZipEntries {{{
  2335. /**
  2336. * All the entries in the zip file.
  2337. * @constructor
  2338. * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
  2339. * @param {Object} loadOptions Options for loading the stream.
  2340. */
  2341. function ZipEntries(data, loadOptions) {
  2342. this.files = [];
  2343. this.loadOptions = loadOptions;
  2344. if (data) {
  2345. this.load(data);
  2346. }
  2347. }
  2348. ZipEntries.prototype = {
  2349. /**
  2350. * Check that the reader is on the speficied signature.
  2351. * @param {string} expectedSignature the expected signature.
  2352. * @throws {Error} if it is an other signature.
  2353. */
  2354. checkSignature: function(expectedSignature) {
  2355. var signature = this.reader.readString(4);
  2356. if (signature !== expectedSignature) {
  2357. throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  2358. }
  2359. },
  2360. /**
  2361. * Read the end of the central directory.
  2362. */
  2363. readBlockEndOfCentral: function() {
  2364. this.diskNumber = this.reader.readInt(2);
  2365. this.diskWithCentralDirStart = this.reader.readInt(2);
  2366. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  2367. this.centralDirRecords = this.reader.readInt(2);
  2368. this.centralDirSize = this.reader.readInt(4);
  2369. this.centralDirOffset = this.reader.readInt(4);
  2370.  
  2371. this.zipCommentLength = this.reader.readInt(2);
  2372. // warning : the encoding depends of the system locale
  2373. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  2374. // On a windows machine, this field is encoded with the localized windows code page.
  2375. this.zipComment = this.reader.readString(this.zipCommentLength);
  2376. // To get consistent behavior with the generation part, we will assume that
  2377. // this is utf8 encoded.
  2378. this.zipComment = jszipProto.utf8decode(this.zipComment);
  2379. },
  2380. /**
  2381. * Read the end of the Zip 64 central directory.
  2382. * Not merged with the method readEndOfCentral :
  2383. * The end of central can coexist with its Zip64 brother,
  2384. * I don't want to read the wrong number of bytes !
  2385. */
  2386. readBlockZip64EndOfCentral: function() {
  2387. this.zip64EndOfCentralSize = this.reader.readInt(8);
  2388. this.versionMadeBy = this.reader.readString(2);
  2389. this.versionNeeded = this.reader.readInt(2);
  2390. this.diskNumber = this.reader.readInt(4);
  2391. this.diskWithCentralDirStart = this.reader.readInt(4);
  2392. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  2393. this.centralDirRecords = this.reader.readInt(8);
  2394. this.centralDirSize = this.reader.readInt(8);
  2395. this.centralDirOffset = this.reader.readInt(8);
  2396.  
  2397. this.zip64ExtensibleData = {};
  2398. var extraDataSize = this.zip64EndOfCentralSize - 44,
  2399. index = 0,
  2400. extraFieldId,
  2401. extraFieldLength,
  2402. extraFieldValue;
  2403. while (index < extraDataSize) {
  2404. extraFieldId = this.reader.readInt(2);
  2405. extraFieldLength = this.reader.readInt(4);
  2406. extraFieldValue = this.reader.readString(extraFieldLength);
  2407. this.zip64ExtensibleData[extraFieldId] = {
  2408. id: extraFieldId,
  2409. length: extraFieldLength,
  2410. value: extraFieldValue
  2411. };
  2412. }
  2413. },
  2414. /**
  2415. * Read the end of the Zip 64 central directory locator.
  2416. */
  2417. readBlockZip64EndOfCentralLocator: function() {
  2418. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  2419. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  2420. this.disksCount = this.reader.readInt(4);
  2421. if (this.disksCount > 1) {
  2422. throw new Error("Multi-volumes zip are not supported");
  2423. }
  2424. },
  2425. /**
  2426. * Read the local files, based on the offset read in the central part.
  2427. */
  2428. readLocalFiles: function() {
  2429. var i, file;
  2430. for (i = 0; i < this.files.length; i++) {
  2431. file = this.files[i];
  2432. this.reader.setIndex(file.localHeaderOffset);
  2433. this.checkSignature(sig.LOCAL_FILE_HEADER);
  2434. file.readLocalPart(this.reader);
  2435. file.handleUTF8();
  2436. file.processAttributes();
  2437. }
  2438. },
  2439. /**
  2440. * Read the central directory.
  2441. */
  2442. readCentralDir: function() {
  2443. var file;
  2444.  
  2445. this.reader.setIndex(this.centralDirOffset);
  2446. while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) {
  2447. file = new ZipEntry({
  2448. zip64: this.zip64
  2449. }, this.loadOptions);
  2450. file.readCentralPart(this.reader);
  2451. this.files.push(file);
  2452. }
  2453. },
  2454. /**
  2455. * Read the end of central directory.
  2456. */
  2457. readEndOfCentral: function() {
  2458. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  2459. if (offset === -1) {
  2460. // Check if the content is a truncated zip or complete garbage.
  2461. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  2462. // extractible zip for example) but it can give a good hint.
  2463. // If an ajax request was used without responseType, we will also
  2464. // get unreadable data.
  2465. var isGarbage = true;
  2466. try {
  2467. this.reader.setIndex(0);
  2468. this.checkSignature(sig.LOCAL_FILE_HEADER);
  2469. isGarbage = false;
  2470. } catch (e) {}
  2471.  
  2472. if (isGarbage) {
  2473. throw new Error("Can't find end of central directory : is this a zip file ? " +
  2474. "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html");
  2475. } else {
  2476. throw new Error("Corrupted zip : can't find end of central directory");
  2477. }
  2478. }
  2479. this.reader.setIndex(offset);
  2480. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  2481. this.readBlockEndOfCentral();
  2482.  
  2483.  
  2484. /* extract from the zip spec :
  2485. 4) If one of the fields in the end of central directory
  2486. record is too small to hold required data, the field
  2487. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  2488. ZIP64 format record should be created.
  2489. 5) The end of central directory record and the
  2490. Zip64 end of central directory locator record must
  2491. reside on the same disk when splitting or spanning
  2492. an archive.
  2493. */
  2494. 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) {
  2495. this.zip64 = true;
  2496.  
  2497. /*
  2498. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  2499. the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
  2500. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  2501. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  2502. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  2503. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  2504. */
  2505.  
  2506. // should look for a zip64 EOCD locator
  2507. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  2508. if (offset === -1) {
  2509. throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
  2510. }
  2511. this.reader.setIndex(offset);
  2512. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  2513. this.readBlockZip64EndOfCentralLocator();
  2514.  
  2515. // now the zip64 EOCD record
  2516. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  2517. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  2518. this.readBlockZip64EndOfCentral();
  2519. }
  2520. },
  2521. prepareReader: function(data) {
  2522. var type = utils.getTypeOf(data);
  2523. if (type === "string" && !support.uint8array) {
  2524. this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString);
  2525. }
  2526. else if (type === "nodebuffer") {
  2527. this.reader = new NodeBufferReader(data);
  2528. }
  2529. else {
  2530. this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data));
  2531. }
  2532. },
  2533. /**
  2534. * Read a zip file and create ZipEntries.
  2535. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  2536. */
  2537. load: function(data) {
  2538. this.prepareReader(data);
  2539. this.readEndOfCentral();
  2540. this.readCentralDir();
  2541. this.readLocalFiles();
  2542. }
  2543. };
  2544. // }}} end of ZipEntries
  2545. module.exports = ZipEntries;
  2546.  
  2547. },{"./nodeBufferReader":12,"./object":13,"./signature":14,"./stringReader":15,"./support":17,"./uint8ArrayReader":18,"./utils":21,"./zipEntry":23}],23:[function(_dereq_,module,exports){
  2548. 'use strict';
  2549. var StringReader = _dereq_('./stringReader');
  2550. var utils = _dereq_('./utils');
  2551. var CompressedObject = _dereq_('./compressedObject');
  2552. var jszipProto = _dereq_('./object');
  2553.  
  2554. var MADE_BY_DOS = 0x00;
  2555. var MADE_BY_UNIX = 0x03;
  2556.  
  2557. // class ZipEntry {{{
  2558. /**
  2559. * An entry in the zip file.
  2560. * @constructor
  2561. * @param {Object} options Options of the current file.
  2562. * @param {Object} loadOptions Options for loading the stream.
  2563. */
  2564. function ZipEntry(options, loadOptions) {
  2565. this.options = options;
  2566. this.loadOptions = loadOptions;
  2567. }
  2568. ZipEntry.prototype = {
  2569. /**
  2570. * say if the file is encrypted.
  2571. * @return {boolean} true if the file is encrypted, false otherwise.
  2572. */
  2573. isEncrypted: function() {
  2574. // bit 1 is set
  2575. return (this.bitFlag & 0x0001) === 0x0001;
  2576. },
  2577. /**
  2578. * say if the file has utf-8 filename/comment.
  2579. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  2580. */
  2581. useUTF8: function() {
  2582. // bit 11 is set
  2583. return (this.bitFlag & 0x0800) === 0x0800;
  2584. },
  2585. /**
  2586. * Prepare the function used to generate the compressed content from this ZipFile.
  2587. * @param {DataReader} reader the reader to use.
  2588. * @param {number} from the offset from where we should read the data.
  2589. * @param {number} length the length of the data to read.
  2590. * @return {Function} the callback to get the compressed content (the type depends of the DataReader class).
  2591. */
  2592. prepareCompressedContent: function(reader, from, length) {
  2593. return function() {
  2594. var previousIndex = reader.index;
  2595. reader.setIndex(from);
  2596. var compressedFileData = reader.readData(length);
  2597. reader.setIndex(previousIndex);
  2598.  
  2599. return compressedFileData;
  2600. };
  2601. },
  2602. /**
  2603. * Prepare the function used to generate the uncompressed content from this ZipFile.
  2604. * @param {DataReader} reader the reader to use.
  2605. * @param {number} from the offset from where we should read the data.
  2606. * @param {number} length the length of the data to read.
  2607. * @param {JSZip.compression} compression the compression used on this file.
  2608. * @param {number} uncompressedSize the uncompressed size to expect.
  2609. * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).
  2610. */
  2611. prepareContent: function(reader, from, length, compression, uncompressedSize) {
  2612. return function() {
  2613.  
  2614. var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
  2615. var uncompressedFileData = compression.uncompress(compressedFileData);
  2616.  
  2617. if (uncompressedFileData.length !== uncompressedSize) {
  2618. throw new Error("Bug : uncompressed data size mismatch");
  2619. }
  2620.  
  2621. return uncompressedFileData;
  2622. };
  2623. },
  2624. /**
  2625. * Read the local part of a zip file and add the info in this object.
  2626. * @param {DataReader} reader the reader to use.
  2627. */
  2628. readLocalPart: function(reader) {
  2629. var compression, localExtraFieldsLength;
  2630.  
  2631. // we already know everything from the central dir !
  2632. // If the central dir data are false, we are doomed.
  2633. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  2634. // The less data we get here, the more reliable this should be.
  2635. // Let's skip the whole header and dash to the data !
  2636. reader.skip(22);
  2637. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  2638. // Strangely, the filename here is OK.
  2639. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  2640. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  2641. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  2642. // the internet.
  2643. //
  2644. // I think I see the logic here : the central directory is used to display
  2645. // content and the local directory is used to extract the files. Mixing / and \
  2646. // may be used to display \ to windows users and use / when extracting the files.
  2647. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  2648. this.fileNameLength = reader.readInt(2);
  2649. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  2650. this.fileName = reader.readString(this.fileNameLength);
  2651. reader.skip(localExtraFieldsLength);
  2652.  
  2653. if (this.compressedSize == -1 || this.uncompressedSize == -1) {
  2654. throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
  2655. }
  2656.  
  2657. compression = utils.findCompression(this.compressionMethod);
  2658. if (compression === null) { // no compression found
  2659. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")");
  2660. }
  2661. this.decompressed = new CompressedObject();
  2662. this.decompressed.compressedSize = this.compressedSize;
  2663. this.decompressed.uncompressedSize = this.uncompressedSize;
  2664. this.decompressed.crc32 = this.crc32;
  2665. this.decompressed.compressionMethod = this.compressionMethod;
  2666. this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
  2667. this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
  2668.  
  2669. // we need to compute the crc32...
  2670. if (this.loadOptions.checkCRC32) {
  2671. this.decompressed = utils.transformTo("string", this.decompressed.getContent());
  2672. if (jszipProto.crc32(this.decompressed) !== this.crc32) {
  2673. throw new Error("Corrupted zip : CRC32 mismatch");
  2674. }
  2675. }
  2676. },
  2677.  
  2678. /**
  2679. * Read the central part of a zip file and add the info in this object.
  2680. * @param {DataReader} reader the reader to use.
  2681. */
  2682. readCentralPart: function(reader) {
  2683. this.versionMadeBy = reader.readInt(2);
  2684. this.versionNeeded = reader.readInt(2);
  2685. this.bitFlag = reader.readInt(2);
  2686. this.compressionMethod = reader.readString(2);
  2687. this.date = reader.readDate();
  2688. this.crc32 = reader.readInt(4);
  2689. this.compressedSize = reader.readInt(4);
  2690. this.uncompressedSize = reader.readInt(4);
  2691. this.fileNameLength = reader.readInt(2);
  2692. this.extraFieldsLength = reader.readInt(2);
  2693. this.fileCommentLength = reader.readInt(2);
  2694. this.diskNumberStart = reader.readInt(2);
  2695. this.internalFileAttributes = reader.readInt(2);
  2696. this.externalFileAttributes = reader.readInt(4);
  2697. this.localHeaderOffset = reader.readInt(4);
  2698.  
  2699. if (this.isEncrypted()) {
  2700. throw new Error("Encrypted zip are not supported");
  2701. }
  2702.  
  2703. this.fileName = reader.readString(this.fileNameLength);
  2704. this.readExtraFields(reader);
  2705. this.parseZIP64ExtraField(reader);
  2706. this.fileComment = reader.readString(this.fileCommentLength);
  2707. },
  2708.  
  2709. /**
  2710. * Parse the external file attributes and get the unix/dos permissions.
  2711. */
  2712. processAttributes: function () {
  2713. this.unixPermissions = null;
  2714. this.dosPermissions = null;
  2715. var madeBy = this.versionMadeBy >> 8;
  2716.  
  2717. // Check if we have the DOS directory flag set.
  2718. // We look for it in the DOS and UNIX permissions
  2719. // but some unknown platform could set it as a compatibility flag.
  2720. this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  2721.  
  2722. if(madeBy === MADE_BY_DOS) {
  2723. // first 6 bits (0 to 5)
  2724. this.dosPermissions = this.externalFileAttributes & 0x3F;
  2725. }
  2726.  
  2727. if(madeBy === MADE_BY_UNIX) {
  2728. this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  2729. // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  2730. }
  2731.  
  2732. // fail safe : if the name ends with a / it probably means a folder
  2733. if (!this.dir && this.fileName.slice(-1) === '/') {
  2734. this.dir = true;
  2735. }
  2736. },
  2737.  
  2738. /**
  2739. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  2740. * @param {DataReader} reader the reader to use.
  2741. */
  2742. parseZIP64ExtraField: function(reader) {
  2743.  
  2744. if (!this.extraFields[0x0001]) {
  2745. return;
  2746. }
  2747.  
  2748. // should be something, preparing the extra reader
  2749. var extraReader = new StringReader(this.extraFields[0x0001].value);
  2750.  
  2751. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  2752. // won't let us have more.
  2753. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  2754. this.uncompressedSize = extraReader.readInt(8);
  2755. }
  2756. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  2757. this.compressedSize = extraReader.readInt(8);
  2758. }
  2759. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  2760. this.localHeaderOffset = extraReader.readInt(8);
  2761. }
  2762. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  2763. this.diskNumberStart = extraReader.readInt(4);
  2764. }
  2765. },
  2766. /**
  2767. * Read the central part of a zip file and add the info in this object.
  2768. * @param {DataReader} reader the reader to use.
  2769. */
  2770. readExtraFields: function(reader) {
  2771. var start = reader.index,
  2772. extraFieldId,
  2773. extraFieldLength,
  2774. extraFieldValue;
  2775.  
  2776. this.extraFields = this.extraFields || {};
  2777.  
  2778. while (reader.index < start + this.extraFieldsLength) {
  2779. extraFieldId = reader.readInt(2);
  2780. extraFieldLength = reader.readInt(2);
  2781. extraFieldValue = reader.readString(extraFieldLength);
  2782.  
  2783. this.extraFields[extraFieldId] = {
  2784. id: extraFieldId,
  2785. length: extraFieldLength,
  2786. value: extraFieldValue
  2787. };
  2788. }
  2789. },
  2790. /**
  2791. * Apply an UTF8 transformation if needed.
  2792. */
  2793. handleUTF8: function() {
  2794. if (this.useUTF8()) {
  2795. this.fileName = jszipProto.utf8decode(this.fileName);
  2796. this.fileComment = jszipProto.utf8decode(this.fileComment);
  2797. } else {
  2798. var upath = this.findExtraFieldUnicodePath();
  2799. if (upath !== null) {
  2800. this.fileName = upath;
  2801. }
  2802. var ucomment = this.findExtraFieldUnicodeComment();
  2803. if (ucomment !== null) {
  2804. this.fileComment = ucomment;
  2805. }
  2806. }
  2807. },
  2808.  
  2809. /**
  2810. * Find the unicode path declared in the extra field, if any.
  2811. * @return {String} the unicode path, null otherwise.
  2812. */
  2813. findExtraFieldUnicodePath: function() {
  2814. var upathField = this.extraFields[0x7075];
  2815. if (upathField) {
  2816. var extraReader = new StringReader(upathField.value);
  2817.  
  2818. // wrong version
  2819. if (extraReader.readInt(1) !== 1) {
  2820. return null;
  2821. }
  2822.  
  2823. // the crc of the filename changed, this field is out of date.
  2824. if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
  2825. return null;
  2826. }
  2827.  
  2828. return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
  2829. }
  2830. return null;
  2831. },
  2832.  
  2833. /**
  2834. * Find the unicode comment declared in the extra field, if any.
  2835. * @return {String} the unicode comment, null otherwise.
  2836. */
  2837. findExtraFieldUnicodeComment: function() {
  2838. var ucommentField = this.extraFields[0x6375];
  2839. if (ucommentField) {
  2840. var extraReader = new StringReader(ucommentField.value);
  2841.  
  2842. // wrong version
  2843. if (extraReader.readInt(1) !== 1) {
  2844. return null;
  2845. }
  2846.  
  2847. // the crc of the comment changed, this field is out of date.
  2848. if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
  2849. return null;
  2850. }
  2851.  
  2852. return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
  2853. }
  2854. return null;
  2855. }
  2856. };
  2857. module.exports = ZipEntry;
  2858.  
  2859. },{"./compressedObject":2,"./object":13,"./stringReader":15,"./utils":21}],24:[function(_dereq_,module,exports){
  2860. // Top level file is just a mixin of submodules & constants
  2861. 'use strict';
  2862.  
  2863. var assign = _dereq_('./lib/utils/common').assign;
  2864.  
  2865. var deflate = _dereq_('./lib/deflate');
  2866. var inflate = _dereq_('./lib/inflate');
  2867. var constants = _dereq_('./lib/zlib/constants');
  2868.  
  2869. var pako = {};
  2870.  
  2871. assign(pako, deflate, inflate, constants);
  2872.  
  2873. module.exports = pako;
  2874. },{"./lib/deflate":25,"./lib/inflate":26,"./lib/utils/common":27,"./lib/zlib/constants":30}],25:[function(_dereq_,module,exports){
  2875. 'use strict';
  2876.  
  2877.  
  2878. var zlib_deflate = _dereq_('./zlib/deflate.js');
  2879. var utils = _dereq_('./utils/common');
  2880. var strings = _dereq_('./utils/strings');
  2881. var msg = _dereq_('./zlib/messages');
  2882. var zstream = _dereq_('./zlib/zstream');
  2883.  
  2884.  
  2885. /* Public constants ==========================================================*/
  2886. /* ===========================================================================*/
  2887.  
  2888. var Z_NO_FLUSH = 0;
  2889. var Z_FINISH = 4;
  2890.  
  2891. var Z_OK = 0;
  2892. var Z_STREAM_END = 1;
  2893.  
  2894. var Z_DEFAULT_COMPRESSION = -1;
  2895.  
  2896. var Z_DEFAULT_STRATEGY = 0;
  2897.  
  2898. var Z_DEFLATED = 8;
  2899.  
  2900. /* ===========================================================================*/
  2901.  
  2902.  
  2903. /**
  2904. * class Deflate
  2905. *
  2906. * Generic JS-style wrapper for zlib calls. If you don't need
  2907. * streaming behaviour - use more simple functions: [[deflate]],
  2908. * [[deflateRaw]] and [[gzip]].
  2909. **/
  2910.  
  2911. /* internal
  2912. * Deflate.chunks -> Array
  2913. *
  2914. * Chunks of output data, if [[Deflate#onData]] not overriden.
  2915. **/
  2916.  
  2917. /**
  2918. * Deflate.result -> Uint8Array|Array
  2919. *
  2920. * Compressed result, generated by default [[Deflate#onData]]
  2921. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  2922. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  2923. **/
  2924.  
  2925. /**
  2926. * Deflate.err -> Number
  2927. *
  2928. * Error code after deflate finished. 0 (Z_OK) on success.
  2929. * You will not need it in real life, because deflate errors
  2930. * are possible only on wrong options or bad `onData` / `onEnd`
  2931. * custom handlers.
  2932. **/
  2933.  
  2934. /**
  2935. * Deflate.msg -> String
  2936. *
  2937. * Error message, if [[Deflate.err]] != 0
  2938. **/
  2939.  
  2940.  
  2941. /**
  2942. * new Deflate(options)
  2943. * - options (Object): zlib deflate options.
  2944. *
  2945. * Creates new deflator instance with specified params. Throws exception
  2946. * on bad params. Supported options:
  2947. *
  2948. * - `level`
  2949. * - `windowBits`
  2950. * - `memLevel`
  2951. * - `strategy`
  2952. *
  2953. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  2954. * for more information on these.
  2955. *
  2956. * Additional options, for internal needs:
  2957. *
  2958. * - `chunkSize` - size of generated data chunks (16K by default)
  2959. * - `raw` (Boolean) - do raw deflate
  2960. * - `gzip` (Boolean) - create gzip wrapper
  2961. * - `to` (String) - if equal to 'string', then result will be "binary string"
  2962. * (each char code [0..255])
  2963. * - `header` (Object) - custom header for gzip
  2964. * - `text` (Boolean) - true if compressed data believed to be text
  2965. * - `time` (Number) - modification time, unix timestamp
  2966. * - `os` (Number) - operation system code
  2967. * - `extra` (Array) - array of bytes with extra data (max 65536)
  2968. * - `name` (String) - file name (binary string)
  2969. * - `comment` (String) - comment (binary string)
  2970. * - `hcrc` (Boolean) - true if header crc should be added
  2971. *
  2972. * ##### Example:
  2973. *
  2974. * ```javascript
  2975. * var pako = require('pako')
  2976. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  2977. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  2978. *
  2979. * var deflate = new pako.Deflate({ level: 3});
  2980. *
  2981. * deflate.push(chunk1, false);
  2982. * deflate.push(chunk2, true); // true -> last chunk
  2983. *
  2984. * if (deflate.err) { throw new Error(deflate.err); }
  2985. *
  2986. * console.log(deflate.result);
  2987. * ```
  2988. **/
  2989. var Deflate = function(options) {
  2990.  
  2991. this.options = utils.assign({
  2992. level: Z_DEFAULT_COMPRESSION,
  2993. method: Z_DEFLATED,
  2994. chunkSize: 16384,
  2995. windowBits: 15,
  2996. memLevel: 8,
  2997. strategy: Z_DEFAULT_STRATEGY,
  2998. to: ''
  2999. }, options || {});
  3000.  
  3001. var opt = this.options;
  3002.  
  3003. if (opt.raw && (opt.windowBits > 0)) {
  3004. opt.windowBits = -opt.windowBits;
  3005. }
  3006.  
  3007. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  3008. opt.windowBits += 16;
  3009. }
  3010.  
  3011. this.err = 0; // error code, if happens (0 = Z_OK)
  3012. this.msg = ''; // error message
  3013. this.ended = false; // used to avoid multiple onEnd() calls
  3014. this.chunks = []; // chunks of compressed data
  3015.  
  3016. this.strm = new zstream();
  3017. this.strm.avail_out = 0;
  3018.  
  3019. var status = zlib_deflate.deflateInit2(
  3020. this.strm,
  3021. opt.level,
  3022. opt.method,
  3023. opt.windowBits,
  3024. opt.memLevel,
  3025. opt.strategy
  3026. );
  3027.  
  3028. if (status !== Z_OK) {
  3029. throw new Error(msg[status]);
  3030. }
  3031.  
  3032. if (opt.header) {
  3033. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  3034. }
  3035. };
  3036.  
  3037. /**
  3038. * Deflate#push(data[, mode]) -> Boolean
  3039. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  3040. * utf8 byte sequence.
  3041. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  3042. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  3043. *
  3044. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  3045. * new compressed chunks. Returns `true` on success. The last data block must have
  3046. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  3047. * [[Deflate#onEnd]].
  3048. *
  3049. * On fail call [[Deflate#onEnd]] with error code and return false.
  3050. *
  3051. * We strongly recommend to use `Uint8Array` on input for best speed (output
  3052. * array format is detected automatically). Also, don't skip last param and always
  3053. * use the same type in your code (boolean or number). That will improve JS speed.
  3054. *
  3055. * For regular `Array`-s make sure all elements are [0..255].
  3056. *
  3057. * ##### Example
  3058. *
  3059. * ```javascript
  3060. * push(chunk, false); // push one of data chunks
  3061. * ...
  3062. * push(chunk, true); // push last chunk
  3063. * ```
  3064. **/
  3065. Deflate.prototype.push = function(data, mode) {
  3066. var strm = this.strm;
  3067. var chunkSize = this.options.chunkSize;
  3068. var status, _mode;
  3069.  
  3070. if (this.ended) { return false; }
  3071.  
  3072. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  3073.  
  3074. // Convert data if needed
  3075. if (typeof data === 'string') {
  3076. // If we need to compress text, change encoding to utf8.
  3077. strm.input = strings.string2buf(data);
  3078. } else {
  3079. strm.input = data;
  3080. }
  3081.  
  3082. strm.next_in = 0;
  3083. strm.avail_in = strm.input.length;
  3084.  
  3085. do {
  3086. if (strm.avail_out === 0) {
  3087. strm.output = new utils.Buf8(chunkSize);
  3088. strm.next_out = 0;
  3089. strm.avail_out = chunkSize;
  3090. }
  3091. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  3092.  
  3093. if (status !== Z_STREAM_END && status !== Z_OK) {
  3094. this.onEnd(status);
  3095. this.ended = true;
  3096. return false;
  3097. }
  3098. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  3099. if (this.options.to === 'string') {
  3100. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  3101. } else {
  3102. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  3103. }
  3104. }
  3105. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  3106.  
  3107. // Finalize on the last chunk.
  3108. if (_mode === Z_FINISH) {
  3109. status = zlib_deflate.deflateEnd(this.strm);
  3110. this.onEnd(status);
  3111. this.ended = true;
  3112. return status === Z_OK;
  3113. }
  3114.  
  3115. return true;
  3116. };
  3117.  
  3118.  
  3119. /**
  3120. * Deflate#onData(chunk) -> Void
  3121. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  3122. * on js engine support. When string output requested, each chunk
  3123. * will be string.
  3124. *
  3125. * By default, stores data blocks in `chunks[]` property and glue
  3126. * those in `onEnd`. Override this handler, if you need another behaviour.
  3127. **/
  3128. Deflate.prototype.onData = function(chunk) {
  3129. this.chunks.push(chunk);
  3130. };
  3131.  
  3132.  
  3133. /**
  3134. * Deflate#onEnd(status) -> Void
  3135. * - status (Number): deflate status. 0 (Z_OK) on success,
  3136. * other if not.
  3137. *
  3138. * Called once after you tell deflate that input stream complete
  3139. * or error happenned. By default - join collected chunks,
  3140. * free memory and fill `results` / `err` properties.
  3141. **/
  3142. Deflate.prototype.onEnd = function(status) {
  3143. // On success - join
  3144. if (status === Z_OK) {
  3145. if (this.options.to === 'string') {
  3146. this.result = this.chunks.join('');
  3147. } else {
  3148. this.result = utils.flattenChunks(this.chunks);
  3149. }
  3150. }
  3151. this.chunks = [];
  3152. this.err = status;
  3153. this.msg = this.strm.msg;
  3154. };
  3155.  
  3156.  
  3157. /**
  3158. * deflate(data[, options]) -> Uint8Array|Array|String
  3159. * - data (Uint8Array|Array|String): input data to compress.
  3160. * - options (Object): zlib deflate options.
  3161. *
  3162. * Compress `data` with deflate alrorythm and `options`.
  3163. *
  3164. * Supported options are:
  3165. *
  3166. * - level
  3167. * - windowBits
  3168. * - memLevel
  3169. * - strategy
  3170. *
  3171. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  3172. * for more information on these.
  3173. *
  3174. * Sugar (options):
  3175. *
  3176. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  3177. * negative windowBits implicitly.
  3178. * - `to` (String) - if equal to 'string', then result will be "binary string"
  3179. * (each char code [0..255])
  3180. *
  3181. * ##### Example:
  3182. *
  3183. * ```javascript
  3184. * var pako = require('pako')
  3185. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  3186. *
  3187. * console.log(pako.deflate(data));
  3188. * ```
  3189. **/
  3190. function deflate(input, options) {
  3191. var deflator = new Deflate(options);
  3192.  
  3193. deflator.push(input, true);
  3194.  
  3195. // That will never happens, if you don't cheat with options :)
  3196. if (deflator.err) { throw deflator.msg; }
  3197.  
  3198. return deflator.result;
  3199. }
  3200.  
  3201.  
  3202. /**
  3203. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  3204. * - data (Uint8Array|Array|String): input data to compress.
  3205. * - options (Object): zlib deflate options.
  3206. *
  3207. * The same as [[deflate]], but creates raw data, without wrapper
  3208. * (header and adler32 crc).
  3209. **/
  3210. function deflateRaw(input, options) {
  3211. options = options || {};
  3212. options.raw = true;
  3213. return deflate(input, options);
  3214. }
  3215.  
  3216.  
  3217. /**
  3218. * gzip(data[, options]) -> Uint8Array|Array|String
  3219. * - data (Uint8Array|Array|String): input data to compress.
  3220. * - options (Object): zlib deflate options.
  3221. *
  3222. * The same as [[deflate]], but create gzip wrapper instead of
  3223. * deflate one.
  3224. **/
  3225. function gzip(input, options) {
  3226. options = options || {};
  3227. options.gzip = true;
  3228. return deflate(input, options);
  3229. }
  3230.  
  3231.  
  3232. exports.Deflate = Deflate;
  3233. exports.deflate = deflate;
  3234. exports.deflateRaw = deflateRaw;
  3235. exports.gzip = gzip;
  3236. },{"./utils/common":27,"./utils/strings":28,"./zlib/deflate.js":32,"./zlib/messages":37,"./zlib/zstream":39}],26:[function(_dereq_,module,exports){
  3237. 'use strict';
  3238.  
  3239.  
  3240. var zlib_inflate = _dereq_('./zlib/inflate.js');
  3241. var utils = _dereq_('./utils/common');
  3242. var strings = _dereq_('./utils/strings');
  3243. var c = _dereq_('./zlib/constants');
  3244. var msg = _dereq_('./zlib/messages');
  3245. var zstream = _dereq_('./zlib/zstream');
  3246. var gzheader = _dereq_('./zlib/gzheader');
  3247.  
  3248.  
  3249. /**
  3250. * class Inflate
  3251. *
  3252. * Generic JS-style wrapper for zlib calls. If you don't need
  3253. * streaming behaviour - use more simple functions: [[inflate]]
  3254. * and [[inflateRaw]].
  3255. **/
  3256.  
  3257. /* internal
  3258. * inflate.chunks -> Array
  3259. *
  3260. * Chunks of output data, if [[Inflate#onData]] not overriden.
  3261. **/
  3262.  
  3263. /**
  3264. * Inflate.result -> Uint8Array|Array|String
  3265. *
  3266. * Uncompressed result, generated by default [[Inflate#onData]]
  3267. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  3268. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  3269. **/
  3270.  
  3271. /**
  3272. * Inflate.err -> Number
  3273. *
  3274. * Error code after inflate finished. 0 (Z_OK) on success.
  3275. * Should be checked if broken data possible.
  3276. **/
  3277.  
  3278. /**
  3279. * Inflate.msg -> String
  3280. *
  3281. * Error message, if [[Inflate.err]] != 0
  3282. **/
  3283.  
  3284.  
  3285. /**
  3286. * new Inflate(options)
  3287. * - options (Object): zlib inflate options.
  3288. *
  3289. * Creates new inflator instance with specified params. Throws exception
  3290. * on bad params. Supported options:
  3291. *
  3292. * - `windowBits`
  3293. *
  3294. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  3295. * for more information on these.
  3296. *
  3297. * Additional options, for internal needs:
  3298. *
  3299. * - `chunkSize` - size of generated data chunks (16K by default)
  3300. * - `raw` (Boolean) - do raw inflate
  3301. * - `to` (String) - if equal to 'string', then result will be converted
  3302. * from utf8 to utf16 (javascript) string. When string output requested,
  3303. * chunk length can differ from `chunkSize`, depending on content.
  3304. *
  3305. * By default, when no options set, autodetect deflate/gzip data format via
  3306. * wrapper header.
  3307. *
  3308. * ##### Example:
  3309. *
  3310. * ```javascript
  3311. * var pako = require('pako')
  3312. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  3313. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  3314. *
  3315. * var inflate = new pako.Inflate({ level: 3});
  3316. *
  3317. * inflate.push(chunk1, false);
  3318. * inflate.push(chunk2, true); // true -> last chunk
  3319. *
  3320. * if (inflate.err) { throw new Error(inflate.err); }
  3321. *
  3322. * console.log(inflate.result);
  3323. * ```
  3324. **/
  3325. var Inflate = function(options) {
  3326.  
  3327. this.options = utils.assign({
  3328. chunkSize: 16384,
  3329. windowBits: 0,
  3330. to: ''
  3331. }, options || {});
  3332.  
  3333. var opt = this.options;
  3334.  
  3335. // Force window size for `raw` data, if not set directly,
  3336. // because we have no header for autodetect.
  3337. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  3338. opt.windowBits = -opt.windowBits;
  3339. if (opt.windowBits === 0) { opt.windowBits = -15; }
  3340. }
  3341.  
  3342. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  3343. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  3344. !(options && options.windowBits)) {
  3345. opt.windowBits += 32;
  3346. }
  3347.  
  3348. // Gzip header has no info about windows size, we can do autodetect only
  3349. // for deflate. So, if window size not set, force it to max when gzip possible
  3350. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  3351. // bit 3 (16) -> gzipped data
  3352. // bit 4 (32) -> autodetect gzip/deflate
  3353. if ((opt.windowBits & 15) === 0) {
  3354. opt.windowBits |= 15;
  3355. }
  3356. }
  3357.  
  3358. this.err = 0; // error code, if happens (0 = Z_OK)
  3359. this.msg = ''; // error message
  3360. this.ended = false; // used to avoid multiple onEnd() calls
  3361. this.chunks = []; // chunks of compressed data
  3362.  
  3363. this.strm = new zstream();
  3364. this.strm.avail_out = 0;
  3365.  
  3366. var status = zlib_inflate.inflateInit2(
  3367. this.strm,
  3368. opt.windowBits
  3369. );
  3370.  
  3371. if (status !== c.Z_OK) {
  3372. throw new Error(msg[status]);
  3373. }
  3374.  
  3375. this.header = new gzheader();
  3376.  
  3377. zlib_inflate.inflateGetHeader(this.strm, this.header);
  3378. };
  3379.  
  3380. /**
  3381. * Inflate#push(data[, mode]) -> Boolean
  3382. * - data (Uint8Array|Array|String): input data
  3383. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  3384. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  3385. *
  3386. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  3387. * new output chunks. Returns `true` on success. The last data block must have
  3388. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  3389. * [[Inflate#onEnd]].
  3390. *
  3391. * On fail call [[Inflate#onEnd]] with error code and return false.
  3392. *
  3393. * We strongly recommend to use `Uint8Array` on input for best speed (output
  3394. * format is detected automatically). Also, don't skip last param and always
  3395. * use the same type in your code (boolean or number). That will improve JS speed.
  3396. *
  3397. * For regular `Array`-s make sure all elements are [0..255].
  3398. *
  3399. * ##### Example
  3400. *
  3401. * ```javascript
  3402. * push(chunk, false); // push one of data chunks
  3403. * ...
  3404. * push(chunk, true); // push last chunk
  3405. * ```
  3406. **/
  3407. Inflate.prototype.push = function(data, mode) {
  3408. var strm = this.strm;
  3409. var chunkSize = this.options.chunkSize;
  3410. var status, _mode;
  3411. var next_out_utf8, tail, utf8str;
  3412.  
  3413. if (this.ended) { return false; }
  3414. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  3415.  
  3416. // Convert data if needed
  3417. if (typeof data === 'string') {
  3418. // Only binary strings can be decompressed on practice
  3419. strm.input = strings.binstring2buf(data);
  3420. } else {
  3421. strm.input = data;
  3422. }
  3423.  
  3424. strm.next_in = 0;
  3425. strm.avail_in = strm.input.length;
  3426.  
  3427. do {
  3428. if (strm.avail_out === 0) {
  3429. strm.output = new utils.Buf8(chunkSize);
  3430. strm.next_out = 0;
  3431. strm.avail_out = chunkSize;
  3432. }
  3433.  
  3434. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  3435.  
  3436. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  3437. this.onEnd(status);
  3438. this.ended = true;
  3439. return false;
  3440. }
  3441.  
  3442. if (strm.next_out) {
  3443. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  3444.  
  3445. if (this.options.to === 'string') {
  3446.  
  3447. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  3448.  
  3449. tail = strm.next_out - next_out_utf8;
  3450. utf8str = strings.buf2string(strm.output, next_out_utf8);
  3451.  
  3452. // move tail
  3453. strm.next_out = tail;
  3454. strm.avail_out = chunkSize - tail;
  3455. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  3456.  
  3457. this.onData(utf8str);
  3458.  
  3459. } else {
  3460. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  3461. }
  3462. }
  3463. }
  3464. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  3465.  
  3466. if (status === c.Z_STREAM_END) {
  3467. _mode = c.Z_FINISH;
  3468. }
  3469. // Finalize on the last chunk.
  3470. if (_mode === c.Z_FINISH) {
  3471. status = zlib_inflate.inflateEnd(this.strm);
  3472. this.onEnd(status);
  3473. this.ended = true;
  3474. return status === c.Z_OK;
  3475. }
  3476.  
  3477. return true;
  3478. };
  3479.  
  3480.  
  3481. /**
  3482. * Inflate#onData(chunk) -> Void
  3483. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  3484. * on js engine support. When string output requested, each chunk
  3485. * will be string.
  3486. *
  3487. * By default, stores data blocks in `chunks[]` property and glue
  3488. * those in `onEnd`. Override this handler, if you need another behaviour.
  3489. **/
  3490. Inflate.prototype.onData = function(chunk) {
  3491. this.chunks.push(chunk);
  3492. };
  3493.  
  3494.  
  3495. /**
  3496. * Inflate#onEnd(status) -> Void
  3497. * - status (Number): inflate status. 0 (Z_OK) on success,
  3498. * other if not.
  3499. *
  3500. * Called once after you tell inflate that input stream complete
  3501. * or error happenned. By default - join collected chunks,
  3502. * free memory and fill `results` / `err` properties.
  3503. **/
  3504. Inflate.prototype.onEnd = function(status) {
  3505. // On success - join
  3506. if (status === c.Z_OK) {
  3507. if (this.options.to === 'string') {
  3508. // Glue & convert here, until we teach pako to send
  3509. // utf8 alligned strings to onData
  3510. this.result = this.chunks.join('');
  3511. } else {
  3512. this.result = utils.flattenChunks(this.chunks);
  3513. }
  3514. }
  3515. this.chunks = [];
  3516. this.err = status;
  3517. this.msg = this.strm.msg;
  3518. };
  3519.  
  3520.  
  3521. /**
  3522. * inflate(data[, options]) -> Uint8Array|Array|String
  3523. * - data (Uint8Array|Array|String): input data to decompress.
  3524. * - options (Object): zlib inflate options.
  3525. *
  3526. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  3527. * format via wrapper header by default. That's why we don't provide
  3528. * separate `ungzip` method.
  3529. *
  3530. * Supported options are:
  3531. *
  3532. * - windowBits
  3533. *
  3534. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  3535. * for more information.
  3536. *
  3537. * Sugar (options):
  3538. *
  3539. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  3540. * negative windowBits implicitly.
  3541. * - `to` (String) - if equal to 'string', then result will be converted
  3542. * from utf8 to utf16 (javascript) string. When string output requested,
  3543. * chunk length can differ from `chunkSize`, depending on content.
  3544. *
  3545. *
  3546. * ##### Example:
  3547. *
  3548. * ```javascript
  3549. * var pako = require('pako')
  3550. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  3551. * , output;
  3552. *
  3553. * try {
  3554. * output = pako.inflate(input);
  3555. * } catch (err)
  3556. * console.log(err);
  3557. * }
  3558. * ```
  3559. **/
  3560. function inflate(input, options) {
  3561. var inflator = new Inflate(options);
  3562.  
  3563. inflator.push(input, true);
  3564.  
  3565. // That will never happens, if you don't cheat with options :)
  3566. if (inflator.err) { throw inflator.msg; }
  3567.  
  3568. return inflator.result;
  3569. }
  3570.  
  3571.  
  3572. /**
  3573. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  3574. * - data (Uint8Array|Array|String): input data to decompress.
  3575. * - options (Object): zlib inflate options.
  3576. *
  3577. * The same as [[inflate]], but creates raw data, without wrapper
  3578. * (header and adler32 crc).
  3579. **/
  3580. function inflateRaw(input, options) {
  3581. options = options || {};
  3582. options.raw = true;
  3583. return inflate(input, options);
  3584. }
  3585.  
  3586.  
  3587. /**
  3588. * ungzip(data[, options]) -> Uint8Array|Array|String
  3589. * - data (Uint8Array|Array|String): input data to decompress.
  3590. * - options (Object): zlib inflate options.
  3591. *
  3592. * Just shortcut to [[inflate]], because it autodetects format
  3593. * by header.content. Done for convenience.
  3594. **/
  3595.  
  3596.  
  3597. exports.Inflate = Inflate;
  3598. exports.inflate = inflate;
  3599. exports.inflateRaw = inflateRaw;
  3600. exports.ungzip = inflate;
  3601.  
  3602. },{"./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){
  3603. 'use strict';
  3604.  
  3605.  
  3606. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  3607. (typeof Uint16Array !== 'undefined') &&
  3608. (typeof Int32Array !== 'undefined');
  3609.  
  3610.  
  3611. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  3612. var sources = Array.prototype.slice.call(arguments, 1);
  3613. while (sources.length) {
  3614. var source = sources.shift();
  3615. if (!source) { continue; }
  3616.  
  3617. if (typeof(source) !== 'object') {
  3618. throw new TypeError(source + 'must be non-object');
  3619. }
  3620.  
  3621. for (var p in source) {
  3622. if (source.hasOwnProperty(p)) {
  3623. obj[p] = source[p];
  3624. }
  3625. }
  3626. }
  3627.  
  3628. return obj;
  3629. };
  3630.  
  3631.  
  3632. // reduce buffer size, avoiding mem copy
  3633. exports.shrinkBuf = function (buf, size) {
  3634. if (buf.length === size) { return buf; }
  3635. if (buf.subarray) { return buf.subarray(0, size); }
  3636. buf.length = size;
  3637. return buf;
  3638. };
  3639.  
  3640.  
  3641. var fnTyped = {
  3642. arraySet: function (dest, src, src_offs, len, dest_offs) {
  3643. if (src.subarray && dest.subarray) {
  3644. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  3645. return;
  3646. }
  3647. // Fallback to ordinary array
  3648. for(var i=0; i<len; i++) {
  3649. dest[dest_offs + i] = src[src_offs + i];
  3650. }
  3651. },
  3652. // Join array of chunks to single array.
  3653. flattenChunks: function(chunks) {
  3654. var i, l, len, pos, chunk, result;
  3655.  
  3656. // calculate data length
  3657. len = 0;
  3658. for (i=0, l=chunks.length; i<l; i++) {
  3659. len += chunks[i].length;
  3660. }
  3661.  
  3662. // join chunks
  3663. result = new Uint8Array(len);
  3664. pos = 0;
  3665. for (i=0, l=chunks.length; i<l; i++) {
  3666. chunk = chunks[i];
  3667. result.set(chunk, pos);
  3668. pos += chunk.length;
  3669. }
  3670.  
  3671. return result;
  3672. }
  3673. };
  3674.  
  3675. var fnUntyped = {
  3676. arraySet: function (dest, src, src_offs, len, dest_offs) {
  3677. for(var i=0; i<len; i++) {
  3678. dest[dest_offs + i] = src[src_offs + i];
  3679. }
  3680. },
  3681. // Join array of chunks to single array.
  3682. flattenChunks: function(chunks) {
  3683. return [].concat.apply([], chunks);
  3684. }
  3685. };
  3686.  
  3687.  
  3688. // Enable/Disable typed arrays use, for testing
  3689. //
  3690. exports.setTyped = function (on) {
  3691. if (on) {
  3692. exports.Buf8 = Uint8Array;
  3693. exports.Buf16 = Uint16Array;
  3694. exports.Buf32 = Int32Array;
  3695. exports.assign(exports, fnTyped);
  3696. } else {
  3697. exports.Buf8 = Array;
  3698. exports.Buf16 = Array;
  3699. exports.Buf32 = Array;
  3700. exports.assign(exports, fnUntyped);
  3701. }
  3702. };
  3703.  
  3704. exports.setTyped(TYPED_OK);
  3705. },{}],28:[function(_dereq_,module,exports){
  3706. // String encode/decode helpers
  3707. 'use strict';
  3708.  
  3709.  
  3710. var utils = _dereq_('./common');
  3711.  
  3712.  
  3713. // Quick check if we can use fast array to bin string conversion
  3714. //
  3715. // - apply(Array) can fail on Android 2.2
  3716. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  3717. //
  3718. var STR_APPLY_OK = true;
  3719. var STR_APPLY_UIA_OK = true;
  3720.  
  3721. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  3722. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  3723.  
  3724.  
  3725. // Table with utf8 lengths (calculated by first byte of sequence)
  3726. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  3727. // because max possible codepoint is 0x10ffff
  3728. var _utf8len = new utils.Buf8(256);
  3729. for (var i=0; i<256; i++) {
  3730. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  3731. }
  3732. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  3733.  
  3734.  
  3735. // convert string to array (typed, when possible)
  3736. exports.string2buf = function (str) {
  3737. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  3738.  
  3739. // count binary size
  3740. for (m_pos = 0; m_pos < str_len; m_pos++) {
  3741. c = str.charCodeAt(m_pos);
  3742. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  3743. c2 = str.charCodeAt(m_pos+1);
  3744. if ((c2 & 0xfc00) === 0xdc00) {
  3745. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  3746. m_pos++;
  3747. }
  3748. }
  3749. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  3750. }
  3751.  
  3752. // allocate buffer
  3753. buf = new utils.Buf8(buf_len);
  3754.  
  3755. // convert
  3756. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  3757. c = str.charCodeAt(m_pos);
  3758. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  3759. c2 = str.charCodeAt(m_pos+1);
  3760. if ((c2 & 0xfc00) === 0xdc00) {
  3761. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  3762. m_pos++;
  3763. }
  3764. }
  3765. if (c < 0x80) {
  3766. /* one byte */
  3767. buf[i++] = c;
  3768. } else if (c < 0x800) {
  3769. /* two bytes */
  3770. buf[i++] = 0xC0 | (c >>> 6);
  3771. buf[i++] = 0x80 | (c & 0x3f);
  3772. } else if (c < 0x10000) {
  3773. /* three bytes */
  3774. buf[i++] = 0xE0 | (c >>> 12);
  3775. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  3776. buf[i++] = 0x80 | (c & 0x3f);
  3777. } else {
  3778. /* four bytes */
  3779. buf[i++] = 0xf0 | (c >>> 18);
  3780. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  3781. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  3782. buf[i++] = 0x80 | (c & 0x3f);
  3783. }
  3784. }
  3785.  
  3786. return buf;
  3787. };
  3788.  
  3789. // Helper (used in 2 places)
  3790. function buf2binstring(buf, len) {
  3791. // use fallback for big arrays to avoid stack overflow
  3792. if (len < 65537) {
  3793. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  3794. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  3795. }
  3796. }
  3797.  
  3798. var result = '';
  3799. for(var i=0; i < len; i++) {
  3800. result += String.fromCharCode(buf[i]);
  3801. }
  3802. return result;
  3803. }
  3804.  
  3805.  
  3806. // Convert byte array to binary string
  3807. exports.buf2binstring = function(buf) {
  3808. return buf2binstring(buf, buf.length);
  3809. };
  3810.  
  3811.  
  3812. // Convert binary string (typed, when possible)
  3813. exports.binstring2buf = function(str) {
  3814. var buf = new utils.Buf8(str.length);
  3815. for(var i=0, len=buf.length; i < len; i++) {
  3816. buf[i] = str.charCodeAt(i);
  3817. }
  3818. return buf;
  3819. };
  3820.  
  3821.  
  3822. // convert array to string
  3823. exports.buf2string = function (buf, max) {
  3824. var i, out, c, c_len;
  3825. var len = max || buf.length;
  3826.  
  3827. // Reserve max possible length (2 words per char)
  3828. // NB: by unknown reasons, Array is significantly faster for
  3829. // String.fromCharCode.apply than Uint16Array.
  3830. var utf16buf = new Array(len*2);
  3831.  
  3832. for (out=0, i=0; i<len;) {
  3833. c = buf[i++];
  3834. // quick process ascii
  3835. if (c < 0x80) { utf16buf[out++] = c; continue; }
  3836.  
  3837. c_len = _utf8len[c];
  3838. // skip 5 & 6 byte codes
  3839. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  3840.  
  3841. // apply mask on first byte
  3842. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  3843. // join the rest
  3844. while (c_len > 1 && i < len) {
  3845. c = (c << 6) | (buf[i++] & 0x3f);
  3846. c_len--;
  3847. }
  3848.  
  3849. // terminated by end of string?
  3850. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  3851.  
  3852. if (c < 0x10000) {
  3853. utf16buf[out++] = c;
  3854. } else {
  3855. c -= 0x10000;
  3856. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  3857. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  3858. }
  3859. }
  3860.  
  3861. return buf2binstring(utf16buf, out);
  3862. };
  3863.  
  3864.  
  3865. // Calculate max possible position in utf8 buffer,
  3866. // that will not break sequence. If that's not possible
  3867. // - (very small limits) return max size as is.
  3868. //
  3869. // buf[] - utf8 bytes array
  3870. // max - length limit (mandatory);
  3871. exports.utf8border = function(buf, max) {
  3872. var pos;
  3873.  
  3874. max = max || buf.length;
  3875. if (max > buf.length) { max = buf.length; }
  3876.  
  3877. // go back from last position, until start of sequence found
  3878. pos = max-1;
  3879. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  3880.  
  3881. // Fuckup - very small and broken sequence,
  3882. // return max, because we should return something anyway.
  3883. if (pos < 0) { return max; }
  3884.  
  3885. // If we came to start of buffer - that means vuffer is too small,
  3886. // return max too.
  3887. if (pos === 0) { return max; }
  3888.  
  3889. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  3890. };
  3891.  
  3892. },{"./common":27}],29:[function(_dereq_,module,exports){
  3893. 'use strict';
  3894.  
  3895. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  3896. // It doesn't worth to make additional optimizationa as in original.
  3897. // Small size is preferable.
  3898.  
  3899. function adler32(adler, buf, len, pos) {
  3900. var s1 = (adler & 0xffff) |0
  3901. , s2 = ((adler >>> 16) & 0xffff) |0
  3902. , n = 0;
  3903.  
  3904. while (len !== 0) {
  3905. // Set limit ~ twice less than 5552, to keep
  3906. // s2 in 31-bits, because we force signed ints.
  3907. // in other case %= will fail.
  3908. n = len > 2000 ? 2000 : len;
  3909. len -= n;
  3910.  
  3911. do {
  3912. s1 = (s1 + buf[pos++]) |0;
  3913. s2 = (s2 + s1) |0;
  3914. } while (--n);
  3915.  
  3916. s1 %= 65521;
  3917. s2 %= 65521;
  3918. }
  3919.  
  3920. return (s1 | (s2 << 16)) |0;
  3921. }
  3922.  
  3923.  
  3924. module.exports = adler32;
  3925. },{}],30:[function(_dereq_,module,exports){
  3926. module.exports = {
  3927.  
  3928. /* Allowed flush values; see deflate() and inflate() below for details */
  3929. Z_NO_FLUSH: 0,
  3930. Z_PARTIAL_FLUSH: 1,
  3931. Z_SYNC_FLUSH: 2,
  3932. Z_FULL_FLUSH: 3,
  3933. Z_FINISH: 4,
  3934. Z_BLOCK: 5,
  3935. Z_TREES: 6,
  3936.  
  3937. /* Return codes for the compression/decompression functions. Negative values
  3938. * are errors, positive values are used for special but normal events.
  3939. */
  3940. Z_OK: 0,
  3941. Z_STREAM_END: 1,
  3942. Z_NEED_DICT: 2,
  3943. Z_ERRNO: -1,
  3944. Z_STREAM_ERROR: -2,
  3945. Z_DATA_ERROR: -3,
  3946. //Z_MEM_ERROR: -4,
  3947. Z_BUF_ERROR: -5,
  3948. //Z_VERSION_ERROR: -6,
  3949.  
  3950. /* compression levels */
  3951. Z_NO_COMPRESSION: 0,
  3952. Z_BEST_SPEED: 1,
  3953. Z_BEST_COMPRESSION: 9,
  3954. Z_DEFAULT_COMPRESSION: -1,
  3955.  
  3956.  
  3957. Z_FILTERED: 1,
  3958. Z_HUFFMAN_ONLY: 2,
  3959. Z_RLE: 3,
  3960. Z_FIXED: 4,
  3961. Z_DEFAULT_STRATEGY: 0,
  3962.  
  3963. /* Possible values of the data_type field (though see inflate()) */
  3964. Z_BINARY: 0,
  3965. Z_TEXT: 1,
  3966. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  3967. Z_UNKNOWN: 2,
  3968.  
  3969. /* The deflate compression method */
  3970. Z_DEFLATED: 8
  3971. //Z_NULL: null // Use -1 or null inline, depending on var type
  3972. };
  3973. },{}],31:[function(_dereq_,module,exports){
  3974. 'use strict';
  3975.  
  3976. // Note: we can't get significant speed boost here.
  3977. // So write code to minimize size - no pregenerated tables
  3978. // and array tools dependencies.
  3979.  
  3980.  
  3981. // Use ordinary array, since untyped makes no boost here
  3982. function makeTable() {
  3983. var c, table = [];
  3984.  
  3985. for(var n =0; n < 256; n++){
  3986. c = n;
  3987. for(var k =0; k < 8; k++){
  3988. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  3989. }
  3990. table[n] = c;
  3991. }
  3992.  
  3993. return table;
  3994. }
  3995.  
  3996. // Create table on load. Just 255 signed longs. Not a problem.
  3997. var crcTable = makeTable();
  3998.  
  3999.  
  4000. function crc32(crc, buf, len, pos) {
  4001. var t = crcTable
  4002. , end = pos + len;
  4003.  
  4004. crc = crc ^ (-1);
  4005.  
  4006. for (var i = pos; i < end; i++ ) {
  4007. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  4008. }
  4009.  
  4010. return (crc ^ (-1)); // >>> 0;
  4011. }
  4012.  
  4013.  
  4014. module.exports = crc32;
  4015. },{}],32:[function(_dereq_,module,exports){
  4016. 'use strict';
  4017.  
  4018. var utils = _dereq_('../utils/common');
  4019. var trees = _dereq_('./trees');
  4020. var adler32 = _dereq_('./adler32');
  4021. var crc32 = _dereq_('./crc32');
  4022. var msg = _dereq_('./messages');
  4023.  
  4024. /* Public constants ==========================================================*/
  4025. /* ===========================================================================*/
  4026.  
  4027.  
  4028. /* Allowed flush values; see deflate() and inflate() below for details */
  4029. var Z_NO_FLUSH = 0;
  4030. var Z_PARTIAL_FLUSH = 1;
  4031. //var Z_SYNC_FLUSH = 2;
  4032. var Z_FULL_FLUSH = 3;
  4033. var Z_FINISH = 4;
  4034. var Z_BLOCK = 5;
  4035. //var Z_TREES = 6;
  4036.  
  4037.  
  4038. /* Return codes for the compression/decompression functions. Negative values
  4039. * are errors, positive values are used for special but normal events.
  4040. */
  4041. var Z_OK = 0;
  4042. var Z_STREAM_END = 1;
  4043. //var Z_NEED_DICT = 2;
  4044. //var Z_ERRNO = -1;
  4045. var Z_STREAM_ERROR = -2;
  4046. var Z_DATA_ERROR = -3;
  4047. //var Z_MEM_ERROR = -4;
  4048. var Z_BUF_ERROR = -5;
  4049. //var Z_VERSION_ERROR = -6;
  4050.  
  4051.  
  4052. /* compression levels */
  4053. //var Z_NO_COMPRESSION = 0;
  4054. //var Z_BEST_SPEED = 1;
  4055. //var Z_BEST_COMPRESSION = 9;
  4056. var Z_DEFAULT_COMPRESSION = -1;
  4057.  
  4058.  
  4059. var Z_FILTERED = 1;
  4060. var Z_HUFFMAN_ONLY = 2;
  4061. var Z_RLE = 3;
  4062. var Z_FIXED = 4;
  4063. var Z_DEFAULT_STRATEGY = 0;
  4064.  
  4065. /* Possible values of the data_type field (though see inflate()) */
  4066. //var Z_BINARY = 0;
  4067. //var Z_TEXT = 1;
  4068. //var Z_ASCII = 1; // = Z_TEXT
  4069. var Z_UNKNOWN = 2;
  4070.  
  4071.  
  4072. /* The deflate compression method */
  4073. var Z_DEFLATED = 8;
  4074.  
  4075. /*============================================================================*/
  4076.  
  4077.  
  4078. var MAX_MEM_LEVEL = 9;
  4079. /* Maximum value for memLevel in deflateInit2 */
  4080. var MAX_WBITS = 15;
  4081. /* 32K LZ77 window */
  4082. var DEF_MEM_LEVEL = 8;
  4083.  
  4084.  
  4085. var LENGTH_CODES = 29;
  4086. /* number of length codes, not counting the special END_BLOCK code */
  4087. var LITERALS = 256;
  4088. /* number of literal bytes 0..255 */
  4089. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  4090. /* number of Literal or Length codes, including the END_BLOCK code */
  4091. var D_CODES = 30;
  4092. /* number of distance codes */
  4093. var BL_CODES = 19;
  4094. /* number of codes used to transfer the bit lengths */
  4095. var HEAP_SIZE = 2*L_CODES + 1;
  4096. /* maximum heap size */
  4097. var MAX_BITS = 15;
  4098. /* All codes must not exceed MAX_BITS bits */
  4099.  
  4100. var MIN_MATCH = 3;
  4101. var MAX_MATCH = 258;
  4102. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  4103.  
  4104. var PRESET_DICT = 0x20;
  4105.  
  4106. var INIT_STATE = 42;
  4107. var EXTRA_STATE = 69;
  4108. var NAME_STATE = 73;
  4109. var COMMENT_STATE = 91;
  4110. var HCRC_STATE = 103;
  4111. var BUSY_STATE = 113;
  4112. var FINISH_STATE = 666;
  4113.  
  4114. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  4115. var BS_BLOCK_DONE = 2; /* block flush performed */
  4116. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  4117. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  4118.  
  4119. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  4120.  
  4121. function err(strm, errorCode) {
  4122. strm.msg = msg[errorCode];
  4123. return errorCode;
  4124. }
  4125.  
  4126. function rank(f) {
  4127. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  4128. }
  4129.  
  4130. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  4131.  
  4132.  
  4133. /* =========================================================================
  4134. * Flush as much pending output as possible. All deflate() output goes
  4135. * through this function so some applications may wish to modify it
  4136. * to avoid allocating a large strm->output buffer and copying into it.
  4137. * (See also read_buf()).
  4138. */
  4139. function flush_pending(strm) {
  4140. var s = strm.state;
  4141.  
  4142. //_tr_flush_bits(s);
  4143. var len = s.pending;
  4144. if (len > strm.avail_out) {
  4145. len = strm.avail_out;
  4146. }
  4147. if (len === 0) { return; }
  4148.  
  4149. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  4150. strm.next_out += len;
  4151. s.pending_out += len;
  4152. strm.total_out += len;
  4153. strm.avail_out -= len;
  4154. s.pending -= len;
  4155. if (s.pending === 0) {
  4156. s.pending_out = 0;
  4157. }
  4158. }
  4159.  
  4160.  
  4161. function flush_block_only (s, last) {
  4162. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  4163. s.block_start = s.strstart;
  4164. flush_pending(s.strm);
  4165. }
  4166.  
  4167.  
  4168. function put_byte(s, b) {
  4169. s.pending_buf[s.pending++] = b;
  4170. }
  4171.  
  4172.  
  4173. /* =========================================================================
  4174. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  4175. * IN assertion: the stream state is correct and there is enough room in
  4176. * pending_buf.
  4177. */
  4178. function putShortMSB(s, b) {
  4179. // put_byte(s, (Byte)(b >> 8));
  4180. // put_byte(s, (Byte)(b & 0xff));
  4181. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  4182. s.pending_buf[s.pending++] = b & 0xff;
  4183. }
  4184.  
  4185.  
  4186. /* ===========================================================================
  4187. * Read a new buffer from the current input stream, update the adler32
  4188. * and total number of bytes read. All deflate() input goes through
  4189. * this function so some applications may wish to modify it to avoid
  4190. * allocating a large strm->input buffer and copying from it.
  4191. * (See also flush_pending()).
  4192. */
  4193. function read_buf(strm, buf, start, size) {
  4194. var len = strm.avail_in;
  4195.  
  4196. if (len > size) { len = size; }
  4197. if (len === 0) { return 0; }
  4198.  
  4199. strm.avail_in -= len;
  4200.  
  4201. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  4202. if (strm.state.wrap === 1) {
  4203. strm.adler = adler32(strm.adler, buf, len, start);
  4204. }
  4205.  
  4206. else if (strm.state.wrap === 2) {
  4207. strm.adler = crc32(strm.adler, buf, len, start);
  4208. }
  4209.  
  4210. strm.next_in += len;
  4211. strm.total_in += len;
  4212.  
  4213. return len;
  4214. }
  4215.  
  4216.  
  4217. /* ===========================================================================
  4218. * Set match_start to the longest match starting at the given string and
  4219. * return its length. Matches shorter or equal to prev_length are discarded,
  4220. * in which case the result is equal to prev_length and match_start is
  4221. * garbage.
  4222. * IN assertions: cur_match is the head of the hash chain for the current
  4223. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  4224. * OUT assertion: the match length is not greater than s->lookahead.
  4225. */
  4226. function longest_match(s, cur_match) {
  4227. var chain_length = s.max_chain_length; /* max hash chain length */
  4228. var scan = s.strstart; /* current string */
  4229. var match; /* matched string */
  4230. var len; /* length of current match */
  4231. var best_len = s.prev_length; /* best match length so far */
  4232. var nice_match = s.nice_match; /* stop if match long enough */
  4233. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  4234. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  4235.  
  4236. var _win = s.window; // shortcut
  4237.  
  4238. var wmask = s.w_mask;
  4239. var prev = s.prev;
  4240.  
  4241. /* Stop when cur_match becomes <= limit. To simplify the code,
  4242. * we prevent matches with the string of window index 0.
  4243. */
  4244.  
  4245. var strend = s.strstart + MAX_MATCH;
  4246. var scan_end1 = _win[scan + best_len - 1];
  4247. var scan_end = _win[scan + best_len];
  4248.  
  4249. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  4250. * It is easy to get rid of this optimization if necessary.
  4251. */
  4252. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  4253.  
  4254. /* Do not waste too much time if we already have a good match: */
  4255. if (s.prev_length >= s.good_match) {
  4256. chain_length >>= 2;
  4257. }
  4258. /* Do not look for matches beyond the end of the input. This is necessary
  4259. * to make deflate deterministic.
  4260. */
  4261. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  4262.  
  4263. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  4264.  
  4265. do {
  4266. // Assert(cur_match < s->strstart, "no future");
  4267. match = cur_match;
  4268.  
  4269. /* Skip to next match if the match length cannot increase
  4270. * or if the match length is less than 2. Note that the checks below
  4271. * for insufficient lookahead only occur occasionally for performance
  4272. * reasons. Therefore uninitialized memory will be accessed, and
  4273. * conditional jumps will be made that depend on those values.
  4274. * However the length of the match is limited to the lookahead, so
  4275. * the output of deflate is not affected by the uninitialized values.
  4276. */
  4277.  
  4278. if (_win[match + best_len] !== scan_end ||
  4279. _win[match + best_len - 1] !== scan_end1 ||
  4280. _win[match] !== _win[scan] ||
  4281. _win[++match] !== _win[scan + 1]) {
  4282. continue;
  4283. }
  4284.  
  4285. /* The check at best_len-1 can be removed because it will be made
  4286. * again later. (This heuristic is not always a win.)
  4287. * It is not necessary to compare scan[2] and match[2] since they
  4288. * are always equal when the other bytes match, given that
  4289. * the hash keys are equal and that HASH_BITS >= 8.
  4290. */
  4291. scan += 2;
  4292. match++;
  4293. // Assert(*scan == *match, "match[2]?");
  4294.  
  4295. /* We check for insufficient lookahead only every 8th comparison;
  4296. * the 256th check will be made at strstart+258.
  4297. */
  4298. do {
  4299. /*jshint noempty:false*/
  4300. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  4301. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  4302. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  4303. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  4304. scan < strend);
  4305.  
  4306. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  4307.  
  4308. len = MAX_MATCH - (strend - scan);
  4309. scan = strend - MAX_MATCH;
  4310.  
  4311. if (len > best_len) {
  4312. s.match_start = cur_match;
  4313. best_len = len;
  4314. if (len >= nice_match) {
  4315. break;
  4316. }
  4317. scan_end1 = _win[scan + best_len - 1];
  4318. scan_end = _win[scan + best_len];
  4319. }
  4320. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  4321.  
  4322. if (best_len <= s.lookahead) {
  4323. return best_len;
  4324. }
  4325. return s.lookahead;
  4326. }
  4327.  
  4328.  
  4329. /* ===========================================================================
  4330. * Fill the window when the lookahead becomes insufficient.
  4331. * Updates strstart and lookahead.
  4332. *
  4333. * IN assertion: lookahead < MIN_LOOKAHEAD
  4334. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  4335. * At least one byte has been read, or avail_in == 0; reads are
  4336. * performed for at least two bytes (required for the zip translate_eol
  4337. * option -- not supported here).
  4338. */
  4339. function fill_window(s) {
  4340. var _w_size = s.w_size;
  4341. var p, n, m, more, str;
  4342.  
  4343. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  4344.  
  4345. do {
  4346. more = s.window_size - s.lookahead - s.strstart;
  4347.  
  4348. // JS ints have 32 bit, block below not needed
  4349. /* Deal with !@#$% 64K limit: */
  4350. //if (sizeof(int) <= 2) {
  4351. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  4352. // more = wsize;
  4353. //
  4354. // } else if (more == (unsigned)(-1)) {
  4355. // /* Very unlikely, but possible on 16 bit machine if
  4356. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  4357. // */
  4358. // more--;
  4359. // }
  4360. //}
  4361.  
  4362.  
  4363. /* If the window is almost full and there is insufficient lookahead,
  4364. * move the upper half to the lower one to make room in the upper half.
  4365. */
  4366. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  4367.  
  4368. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  4369. s.match_start -= _w_size;
  4370. s.strstart -= _w_size;
  4371. /* we now have strstart >= MAX_DIST */
  4372. s.block_start -= _w_size;
  4373.  
  4374. /* Slide the hash table (could be avoided with 32 bit values
  4375. at the expense of memory usage). We slide even when level == 0
  4376. to keep the hash table consistent if we switch back to level > 0
  4377. later. (Using level 0 permanently is not an optimal usage of
  4378. zlib, so we don't care about this pathological case.)
  4379. */
  4380.  
  4381. n = s.hash_size;
  4382. p = n;
  4383. do {
  4384. m = s.head[--p];
  4385. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  4386. } while (--n);
  4387.  
  4388. n = _w_size;
  4389. p = n;
  4390. do {
  4391. m = s.prev[--p];
  4392. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  4393. /* If n is not on any hash chain, prev[n] is garbage but
  4394. * its value will never be used.
  4395. */
  4396. } while (--n);
  4397.  
  4398. more += _w_size;
  4399. }
  4400. if (s.strm.avail_in === 0) {
  4401. break;
  4402. }
  4403.  
  4404. /* If there was no sliding:
  4405. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  4406. * more == window_size - lookahead - strstart
  4407. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  4408. * => more >= window_size - 2*WSIZE + 2
  4409. * In the BIG_MEM or MMAP case (not yet supported),
  4410. * window_size == input_size + MIN_LOOKAHEAD &&
  4411. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  4412. * Otherwise, window_size == 2*WSIZE so more >= 2.
  4413. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  4414. */
  4415. //Assert(more >= 2, "more < 2");
  4416. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  4417. s.lookahead += n;
  4418.  
  4419. /* Initialize the hash value now that we have some input: */
  4420. if (s.lookahead + s.insert >= MIN_MATCH) {
  4421. str = s.strstart - s.insert;
  4422. s.ins_h = s.window[str];
  4423.  
  4424. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  4425. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  4426. //#if MIN_MATCH != 3
  4427. // Call update_hash() MIN_MATCH-3 more times
  4428. //#endif
  4429. while (s.insert) {
  4430. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  4431. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  4432.  
  4433. s.prev[str & s.w_mask] = s.head[s.ins_h];
  4434. s.head[s.ins_h] = str;
  4435. str++;
  4436. s.insert--;
  4437. if (s.lookahead + s.insert < MIN_MATCH) {
  4438. break;
  4439. }
  4440. }
  4441. }
  4442. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  4443. * but this is not important since only literal bytes will be emitted.
  4444. */
  4445.  
  4446. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  4447.  
  4448. /* If the WIN_INIT bytes after the end of the current data have never been
  4449. * written, then zero those bytes in order to avoid memory check reports of
  4450. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  4451. * the longest match routines. Update the high water mark for the next
  4452. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  4453. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  4454. */
  4455. // if (s.high_water < s.window_size) {
  4456. // var curr = s.strstart + s.lookahead;
  4457. // var init = 0;
  4458. //
  4459. // if (s.high_water < curr) {
  4460. // /* Previous high water mark below current data -- zero WIN_INIT
  4461. // * bytes or up to end of window, whichever is less.
  4462. // */
  4463. // init = s.window_size - curr;
  4464. // if (init > WIN_INIT)
  4465. // init = WIN_INIT;
  4466. // zmemzero(s->window + curr, (unsigned)init);
  4467. // s->high_water = curr + init;
  4468. // }
  4469. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  4470. // /* High water mark at or above current data, but below current data
  4471. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  4472. // * to end of window, whichever is less.
  4473. // */
  4474. // init = (ulg)curr + WIN_INIT - s->high_water;
  4475. // if (init > s->window_size - s->high_water)
  4476. // init = s->window_size - s->high_water;
  4477. // zmemzero(s->window + s->high_water, (unsigned)init);
  4478. // s->high_water += init;
  4479. // }
  4480. // }
  4481. //
  4482. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  4483. // "not enough room for search");
  4484. }
  4485.  
  4486. /* ===========================================================================
  4487. * Copy without compression as much as possible from the input stream, return
  4488. * the current block state.
  4489. * This function does not insert new strings in the dictionary since
  4490. * uncompressible data is probably not useful. This function is used
  4491. * only for the level=0 compression option.
  4492. * NOTE: this function should be optimized to avoid extra copying from
  4493. * window to pending_buf.
  4494. */
  4495. function deflate_stored(s, flush) {
  4496. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  4497. * to pending_buf_size, and each stored block has a 5 byte header:
  4498. */
  4499. var max_block_size = 0xffff;
  4500.  
  4501. if (max_block_size > s.pending_buf_size - 5) {
  4502. max_block_size = s.pending_buf_size - 5;
  4503. }
  4504.  
  4505. /* Copy as much as possible from input to output: */
  4506. for (;;) {
  4507. /* Fill the window as much as possible: */
  4508. if (s.lookahead <= 1) {
  4509.  
  4510. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  4511. // s->block_start >= (long)s->w_size, "slide too late");
  4512. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  4513. // s.block_start >= s.w_size)) {
  4514. // throw new Error("slide too late");
  4515. // }
  4516.  
  4517. fill_window(s);
  4518. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  4519. return BS_NEED_MORE;
  4520. }
  4521.  
  4522. if (s.lookahead === 0) {
  4523. break;
  4524. }
  4525. /* flush the current block */
  4526. }
  4527. //Assert(s->block_start >= 0L, "block gone");
  4528. // if (s.block_start < 0) throw new Error("block gone");
  4529.  
  4530. s.strstart += s.lookahead;
  4531. s.lookahead = 0;
  4532.  
  4533. /* Emit a stored block if pending_buf will be full: */
  4534. var max_start = s.block_start + max_block_size;
  4535.  
  4536. if (s.strstart === 0 || s.strstart >= max_start) {
  4537. /* strstart == 0 is possible when wraparound on 16-bit machine */
  4538. s.lookahead = s.strstart - max_start;
  4539. s.strstart = max_start;
  4540. /*** FLUSH_BLOCK(s, 0); ***/
  4541. flush_block_only(s, false);
  4542. if (s.strm.avail_out === 0) {
  4543. return BS_NEED_MORE;
  4544. }
  4545. /***/
  4546.  
  4547.  
  4548. }
  4549. /* Flush if we may have to slide, otherwise block_start may become
  4550. * negative and the data will be gone:
  4551. */
  4552. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  4553. /*** FLUSH_BLOCK(s, 0); ***/
  4554. flush_block_only(s, false);
  4555. if (s.strm.avail_out === 0) {
  4556. return BS_NEED_MORE;
  4557. }
  4558. /***/
  4559. }
  4560. }
  4561.  
  4562. s.insert = 0;
  4563.  
  4564. if (flush === Z_FINISH) {
  4565. /*** FLUSH_BLOCK(s, 1); ***/
  4566. flush_block_only(s, true);
  4567. if (s.strm.avail_out === 0) {
  4568. return BS_FINISH_STARTED;
  4569. }
  4570. /***/
  4571. return BS_FINISH_DONE;
  4572. }
  4573.  
  4574. if (s.strstart > s.block_start) {
  4575. /*** FLUSH_BLOCK(s, 0); ***/
  4576. flush_block_only(s, false);
  4577. if (s.strm.avail_out === 0) {
  4578. return BS_NEED_MORE;
  4579. }
  4580. /***/
  4581. }
  4582.  
  4583. return BS_NEED_MORE;
  4584. }
  4585.  
  4586. /* ===========================================================================
  4587. * Compress as much as possible from the input stream, return the current
  4588. * block state.
  4589. * This function does not perform lazy evaluation of matches and inserts
  4590. * new strings in the dictionary only for unmatched strings or for short
  4591. * matches. It is used only for the fast compression options.
  4592. */
  4593. function deflate_fast(s, flush) {
  4594. var hash_head; /* head of the hash chain */
  4595. var bflush; /* set if current block must be flushed */
  4596.  
  4597. for (;;) {
  4598. /* Make sure that we always have enough lookahead, except
  4599. * at the end of the input file. We need MAX_MATCH bytes
  4600. * for the next match, plus MIN_MATCH bytes to insert the
  4601. * string following the next match.
  4602. */
  4603. if (s.lookahead < MIN_LOOKAHEAD) {
  4604. fill_window(s);
  4605. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  4606. return BS_NEED_MORE;
  4607. }
  4608. if (s.lookahead === 0) {
  4609. break; /* flush the current block */
  4610. }
  4611. }
  4612.  
  4613. /* Insert the string window[strstart .. strstart+2] in the
  4614. * dictionary, and set hash_head to the head of the hash chain:
  4615. */
  4616. hash_head = 0/*NIL*/;
  4617. if (s.lookahead >= MIN_MATCH) {
  4618. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  4619. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  4620. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  4621. s.head[s.ins_h] = s.strstart;
  4622. /***/
  4623. }
  4624.  
  4625. /* Find the longest match, discarding those <= prev_length.
  4626. * At this point we have always match_length < MIN_MATCH
  4627. */
  4628. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  4629. /* To simplify the code, we prevent matches with the string
  4630. * of window index 0 (in particular we have to avoid a match
  4631. * of the string with itself at the start of the input file).
  4632. */
  4633. s.match_length = longest_match(s, hash_head);
  4634. /* longest_match() sets match_start */
  4635. }
  4636. if (s.match_length >= MIN_MATCH) {
  4637. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  4638.  
  4639. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  4640. s.match_length - MIN_MATCH, bflush); ***/
  4641. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  4642.  
  4643. s.lookahead -= s.match_length;
  4644.  
  4645. /* Insert new strings in the hash table only if the match length
  4646. * is not too large. This saves time but degrades compression.
  4647. */
  4648. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  4649. s.match_length--; /* string at strstart already in table */
  4650. do {
  4651. s.strstart++;
  4652. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  4653. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  4654. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  4655. s.head[s.ins_h] = s.strstart;
  4656. /***/
  4657. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  4658. * always MIN_MATCH bytes ahead.
  4659. */
  4660. } while (--s.match_length !== 0);
  4661. s.strstart++;
  4662. } else
  4663. {
  4664. s.strstart += s.match_length;
  4665. s.match_length = 0;
  4666. s.ins_h = s.window[s.strstart];
  4667. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  4668. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  4669.  
  4670. //#if MIN_MATCH != 3
  4671. // Call UPDATE_HASH() MIN_MATCH-3 more times
  4672. //#endif
  4673. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  4674. * matter since it will be recomputed at next deflate call.
  4675. */
  4676. }
  4677. } else {
  4678. /* No match, output a literal byte */
  4679. //Tracevv((stderr,"%c", s.window[s.strstart]));
  4680. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  4681. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  4682.  
  4683. s.lookahead--;
  4684. s.strstart++;
  4685. }
  4686. if (bflush) {
  4687. /*** FLUSH_BLOCK(s, 0); ***/
  4688. flush_block_only(s, false);
  4689. if (s.strm.avail_out === 0) {
  4690. return BS_NEED_MORE;
  4691. }
  4692. /***/
  4693. }
  4694. }
  4695. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  4696. if (flush === Z_FINISH) {
  4697. /*** FLUSH_BLOCK(s, 1); ***/
  4698. flush_block_only(s, true);
  4699. if (s.strm.avail_out === 0) {
  4700. return BS_FINISH_STARTED;
  4701. }
  4702. /***/
  4703. return BS_FINISH_DONE;
  4704. }
  4705. if (s.last_lit) {
  4706. /*** FLUSH_BLOCK(s, 0); ***/
  4707. flush_block_only(s, false);
  4708. if (s.strm.avail_out === 0) {
  4709. return BS_NEED_MORE;
  4710. }
  4711. /***/
  4712. }
  4713. return BS_BLOCK_DONE;
  4714. }
  4715.  
  4716. /* ===========================================================================
  4717. * Same as above, but achieves better compression. We use a lazy
  4718. * evaluation for matches: a match is finally adopted only if there is
  4719. * no better match at the next window position.
  4720. */
  4721. function deflate_slow(s, flush) {
  4722. var hash_head; /* head of hash chain */
  4723. var bflush; /* set if current block must be flushed */
  4724.  
  4725. var max_insert;
  4726.  
  4727. /* Process the input block. */
  4728. for (;;) {
  4729. /* Make sure that we always have enough lookahead, except
  4730. * at the end of the input file. We need MAX_MATCH bytes
  4731. * for the next match, plus MIN_MATCH bytes to insert the
  4732. * string following the next match.
  4733. */
  4734. if (s.lookahead < MIN_LOOKAHEAD) {
  4735. fill_window(s);
  4736. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  4737. return BS_NEED_MORE;
  4738. }
  4739. if (s.lookahead === 0) { break; } /* flush the current block */
  4740. }
  4741.  
  4742. /* Insert the string window[strstart .. strstart+2] in the
  4743. * dictionary, and set hash_head to the head of the hash chain:
  4744. */
  4745. hash_head = 0/*NIL*/;
  4746. if (s.lookahead >= MIN_MATCH) {
  4747. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  4748. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  4749. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  4750. s.head[s.ins_h] = s.strstart;
  4751. /***/
  4752. }
  4753.  
  4754. /* Find the longest match, discarding those <= prev_length.
  4755. */
  4756. s.prev_length = s.match_length;
  4757. s.prev_match = s.match_start;
  4758. s.match_length = MIN_MATCH-1;
  4759.  
  4760. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  4761. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  4762. /* To simplify the code, we prevent matches with the string
  4763. * of window index 0 (in particular we have to avoid a match
  4764. * of the string with itself at the start of the input file).
  4765. */
  4766. s.match_length = longest_match(s, hash_head);
  4767. /* longest_match() sets match_start */
  4768.  
  4769. if (s.match_length <= 5 &&
  4770. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  4771.  
  4772. /* If prev_match is also MIN_MATCH, match_start is garbage
  4773. * but we will ignore the current match anyway.
  4774. */
  4775. s.match_length = MIN_MATCH-1;
  4776. }
  4777. }
  4778. /* If there was a match at the previous step and the current
  4779. * match is not better, output the previous match:
  4780. */
  4781. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  4782. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  4783. /* Do not insert strings in hash table beyond this. */
  4784.  
  4785. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  4786.  
  4787. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  4788. s.prev_length - MIN_MATCH, bflush);***/
  4789. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  4790. /* Insert in hash table all strings up to the end of the match.
  4791. * strstart-1 and strstart are already inserted. If there is not
  4792. * enough lookahead, the last two strings are not inserted in
  4793. * the hash table.
  4794. */
  4795. s.lookahead -= s.prev_length-1;
  4796. s.prev_length -= 2;
  4797. do {
  4798. if (++s.strstart <= max_insert) {
  4799. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  4800. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  4801. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  4802. s.head[s.ins_h] = s.strstart;
  4803. /***/
  4804. }
  4805. } while (--s.prev_length !== 0);
  4806. s.match_available = 0;
  4807. s.match_length = MIN_MATCH-1;
  4808. s.strstart++;
  4809.  
  4810. if (bflush) {
  4811. /*** FLUSH_BLOCK(s, 0); ***/
  4812. flush_block_only(s, false);
  4813. if (s.strm.avail_out === 0) {
  4814. return BS_NEED_MORE;
  4815. }
  4816. /***/
  4817. }
  4818.  
  4819. } else if (s.match_available) {
  4820. /* If there was no match at the previous position, output a
  4821. * single literal. If there was a match but the current match
  4822. * is longer, truncate the previous match to a single literal.
  4823. */
  4824. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  4825. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  4826. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  4827.  
  4828. if (bflush) {
  4829. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  4830. flush_block_only(s, false);
  4831. /***/
  4832. }
  4833. s.strstart++;
  4834. s.lookahead--;
  4835. if (s.strm.avail_out === 0) {
  4836. return BS_NEED_MORE;
  4837. }
  4838. } else {
  4839. /* There is no previous match to compare with, wait for
  4840. * the next step to decide.
  4841. */
  4842. s.match_available = 1;
  4843. s.strstart++;
  4844. s.lookahead--;
  4845. }
  4846. }
  4847. //Assert (flush != Z_NO_FLUSH, "no flush?");
  4848. if (s.match_available) {
  4849. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  4850. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  4851. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  4852.  
  4853. s.match_available = 0;
  4854. }
  4855. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  4856. if (flush === Z_FINISH) {
  4857. /*** FLUSH_BLOCK(s, 1); ***/
  4858. flush_block_only(s, true);
  4859. if (s.strm.avail_out === 0) {
  4860. return BS_FINISH_STARTED;
  4861. }
  4862. /***/
  4863. return BS_FINISH_DONE;
  4864. }
  4865. if (s.last_lit) {
  4866. /*** FLUSH_BLOCK(s, 0); ***/
  4867. flush_block_only(s, false);
  4868. if (s.strm.avail_out === 0) {
  4869. return BS_NEED_MORE;
  4870. }
  4871. /***/
  4872. }
  4873.  
  4874. return BS_BLOCK_DONE;
  4875. }
  4876.  
  4877.  
  4878. /* ===========================================================================
  4879. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  4880. * one. Do not maintain a hash table. (It will be regenerated if this run of
  4881. * deflate switches away from Z_RLE.)
  4882. */
  4883. function deflate_rle(s, flush) {
  4884. var bflush; /* set if current block must be flushed */
  4885. var prev; /* byte at distance one to match */
  4886. var scan, strend; /* scan goes up to strend for length of run */
  4887.  
  4888. var _win = s.window;
  4889.  
  4890. for (;;) {
  4891. /* Make sure that we always have enough lookahead, except
  4892. * at the end of the input file. We need MAX_MATCH bytes
  4893. * for the longest run, plus one for the unrolled loop.
  4894. */
  4895. if (s.lookahead <= MAX_MATCH) {
  4896. fill_window(s);
  4897. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  4898. return BS_NEED_MORE;
  4899. }
  4900. if (s.lookahead === 0) { break; } /* flush the current block */
  4901. }
  4902.  
  4903. /* See how many times the previous byte repeats */
  4904. s.match_length = 0;
  4905. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  4906. scan = s.strstart - 1;
  4907. prev = _win[scan];
  4908. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  4909. strend = s.strstart + MAX_MATCH;
  4910. do {
  4911. /*jshint noempty:false*/
  4912. } while (prev === _win[++scan] && prev === _win[++scan] &&
  4913. prev === _win[++scan] && prev === _win[++scan] &&
  4914. prev === _win[++scan] && prev === _win[++scan] &&
  4915. prev === _win[++scan] && prev === _win[++scan] &&
  4916. scan < strend);
  4917. s.match_length = MAX_MATCH - (strend - scan);
  4918. if (s.match_length > s.lookahead) {
  4919. s.match_length = s.lookahead;
  4920. }
  4921. }
  4922. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  4923. }
  4924.  
  4925. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  4926. if (s.match_length >= MIN_MATCH) {
  4927. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  4928.  
  4929. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  4930. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  4931.  
  4932. s.lookahead -= s.match_length;
  4933. s.strstart += s.match_length;
  4934. s.match_length = 0;
  4935. } else {
  4936. /* No match, output a literal byte */
  4937. //Tracevv((stderr,"%c", s->window[s->strstart]));
  4938. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  4939. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  4940.  
  4941. s.lookahead--;
  4942. s.strstart++;
  4943. }
  4944. if (bflush) {
  4945. /*** FLUSH_BLOCK(s, 0); ***/
  4946. flush_block_only(s, false);
  4947. if (s.strm.avail_out === 0) {
  4948. return BS_NEED_MORE;
  4949. }
  4950. /***/
  4951. }
  4952. }
  4953. s.insert = 0;
  4954. if (flush === Z_FINISH) {
  4955. /*** FLUSH_BLOCK(s, 1); ***/
  4956. flush_block_only(s, true);
  4957. if (s.strm.avail_out === 0) {
  4958. return BS_FINISH_STARTED;
  4959. }
  4960. /***/
  4961. return BS_FINISH_DONE;
  4962. }
  4963. if (s.last_lit) {
  4964. /*** FLUSH_BLOCK(s, 0); ***/
  4965. flush_block_only(s, false);
  4966. if (s.strm.avail_out === 0) {
  4967. return BS_NEED_MORE;
  4968. }
  4969. /***/
  4970. }
  4971. return BS_BLOCK_DONE;
  4972. }
  4973.  
  4974. /* ===========================================================================
  4975. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  4976. * (It will be regenerated if this run of deflate switches away from Huffman.)
  4977. */
  4978. function deflate_huff(s, flush) {
  4979. var bflush; /* set if current block must be flushed */
  4980.  
  4981. for (;;) {
  4982. /* Make sure that we have a literal to write. */
  4983. if (s.lookahead === 0) {
  4984. fill_window(s);
  4985. if (s.lookahead === 0) {
  4986. if (flush === Z_NO_FLUSH) {
  4987. return BS_NEED_MORE;
  4988. }
  4989. break; /* flush the current block */
  4990. }
  4991. }
  4992.  
  4993. /* Output a literal byte */
  4994. s.match_length = 0;
  4995. //Tracevv((stderr,"%c", s->window[s->strstart]));
  4996. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  4997. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  4998. s.lookahead--;
  4999. s.strstart++;
  5000. if (bflush) {
  5001. /*** FLUSH_BLOCK(s, 0); ***/
  5002. flush_block_only(s, false);
  5003. if (s.strm.avail_out === 0) {
  5004. return BS_NEED_MORE;
  5005. }
  5006. /***/
  5007. }
  5008. }
  5009. s.insert = 0;
  5010. if (flush === Z_FINISH) {
  5011. /*** FLUSH_BLOCK(s, 1); ***/
  5012. flush_block_only(s, true);
  5013. if (s.strm.avail_out === 0) {
  5014. return BS_FINISH_STARTED;
  5015. }
  5016. /***/
  5017. return BS_FINISH_DONE;
  5018. }
  5019. if (s.last_lit) {
  5020. /*** FLUSH_BLOCK(s, 0); ***/
  5021. flush_block_only(s, false);
  5022. if (s.strm.avail_out === 0) {
  5023. return BS_NEED_MORE;
  5024. }
  5025. /***/
  5026. }
  5027. return BS_BLOCK_DONE;
  5028. }
  5029.  
  5030. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  5031. * the desired pack level (0..9). The values given below have been tuned to
  5032. * exclude worst case performance for pathological files. Better values may be
  5033. * found for specific files.
  5034. */
  5035. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  5036. this.good_length = good_length;
  5037. this.max_lazy = max_lazy;
  5038. this.nice_length = nice_length;
  5039. this.max_chain = max_chain;
  5040. this.func = func;
  5041. };
  5042.  
  5043. var configuration_table;
  5044.  
  5045. configuration_table = [
  5046. /* good lazy nice chain */
  5047. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  5048. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  5049. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  5050. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  5051.  
  5052. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  5053. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  5054. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  5055. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  5056. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  5057. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  5058. ];
  5059.  
  5060.  
  5061. /* ===========================================================================
  5062. * Initialize the "longest match" routines for a new zlib stream
  5063. */
  5064. function lm_init(s) {
  5065. s.window_size = 2 * s.w_size;
  5066.  
  5067. /*** CLEAR_HASH(s); ***/
  5068. zero(s.head); // Fill with NIL (= 0);
  5069.  
  5070. /* Set the default configuration parameters:
  5071. */
  5072. s.max_lazy_match = configuration_table[s.level].max_lazy;
  5073. s.good_match = configuration_table[s.level].good_length;
  5074. s.nice_match = configuration_table[s.level].nice_length;
  5075. s.max_chain_length = configuration_table[s.level].max_chain;
  5076.  
  5077. s.strstart = 0;
  5078. s.block_start = 0;
  5079. s.lookahead = 0;
  5080. s.insert = 0;
  5081. s.match_length = s.prev_length = MIN_MATCH - 1;
  5082. s.match_available = 0;
  5083. s.ins_h = 0;
  5084. }
  5085.  
  5086.  
  5087. function DeflateState() {
  5088. this.strm = null; /* pointer back to this zlib stream */
  5089. this.status = 0; /* as the name implies */
  5090. this.pending_buf = null; /* output still pending */
  5091. this.pending_buf_size = 0; /* size of pending_buf */
  5092. this.pending_out = 0; /* next pending byte to output to the stream */
  5093. this.pending = 0; /* nb of bytes in the pending buffer */
  5094. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  5095. this.gzhead = null; /* gzip header information to write */
  5096. this.gzindex = 0; /* where in extra, name, or comment */
  5097. this.method = Z_DEFLATED; /* can only be DEFLATED */
  5098. this.last_flush = -1; /* value of flush param for previous deflate call */
  5099.  
  5100. this.w_size = 0; /* LZ77 window size (32K by default) */
  5101. this.w_bits = 0; /* log2(w_size) (8..16) */
  5102. this.w_mask = 0; /* w_size - 1 */
  5103.  
  5104. this.window = null;
  5105. /* Sliding window. Input bytes are read into the second half of the window,
  5106. * and move to the first half later to keep a dictionary of at least wSize
  5107. * bytes. With this organization, matches are limited to a distance of
  5108. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  5109. * performed with a length multiple of the block size.
  5110. */
  5111.  
  5112. this.window_size = 0;
  5113. /* Actual size of window: 2*wSize, except when the user input buffer
  5114. * is directly used as sliding window.
  5115. */
  5116.  
  5117. this.prev = null;
  5118. /* Link to older string with same hash index. To limit the size of this
  5119. * array to 64K, this link is maintained only for the last 32K strings.
  5120. * An index in this array is thus a window index modulo 32K.
  5121. */
  5122.  
  5123. this.head = null; /* Heads of the hash chains or NIL. */
  5124.  
  5125. this.ins_h = 0; /* hash index of string to be inserted */
  5126. this.hash_size = 0; /* number of elements in hash table */
  5127. this.hash_bits = 0; /* log2(hash_size) */
  5128. this.hash_mask = 0; /* hash_size-1 */
  5129.  
  5130. this.hash_shift = 0;
  5131. /* Number of bits by which ins_h must be shifted at each input
  5132. * step. It must be such that after MIN_MATCH steps, the oldest
  5133. * byte no longer takes part in the hash key, that is:
  5134. * hash_shift * MIN_MATCH >= hash_bits
  5135. */
  5136.  
  5137. this.block_start = 0;
  5138. /* Window position at the beginning of the current output block. Gets
  5139. * negative when the window is moved backwards.
  5140. */
  5141.  
  5142. this.match_length = 0; /* length of best match */
  5143. this.prev_match = 0; /* previous match */
  5144. this.match_available = 0; /* set if previous match exists */
  5145. this.strstart = 0; /* start of string to insert */
  5146. this.match_start = 0; /* start of matching string */
  5147. this.lookahead = 0; /* number of valid bytes ahead in window */
  5148.  
  5149. this.prev_length = 0;
  5150. /* Length of the best match at previous step. Matches not greater than this
  5151. * are discarded. This is used in the lazy match evaluation.
  5152. */
  5153.  
  5154. this.max_chain_length = 0;
  5155. /* To speed up deflation, hash chains are never searched beyond this
  5156. * length. A higher limit improves compression ratio but degrades the
  5157. * speed.
  5158. */
  5159.  
  5160. this.max_lazy_match = 0;
  5161. /* Attempt to find a better match only when the current match is strictly
  5162. * smaller than this value. This mechanism is used only for compression
  5163. * levels >= 4.
  5164. */
  5165. // That's alias to max_lazy_match, don't use directly
  5166. //this.max_insert_length = 0;
  5167. /* Insert new strings in the hash table only if the match length is not
  5168. * greater than this length. This saves time but degrades compression.
  5169. * max_insert_length is used only for compression levels <= 3.
  5170. */
  5171.  
  5172. this.level = 0; /* compression level (1..9) */
  5173. this.strategy = 0; /* favor or force Huffman coding*/
  5174.  
  5175. this.good_match = 0;
  5176. /* Use a faster search when the previous match is longer than this */
  5177.  
  5178. this.nice_match = 0; /* Stop searching when current match exceeds this */
  5179.  
  5180. /* used by trees.c: */
  5181.  
  5182. /* Didn't use ct_data typedef below to suppress compiler warning */
  5183.  
  5184. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  5185. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  5186. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  5187.  
  5188. // Use flat array of DOUBLE size, with interleaved fata,
  5189. // because JS does not support effective
  5190. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  5191. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  5192. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  5193. zero(this.dyn_ltree);
  5194. zero(this.dyn_dtree);
  5195. zero(this.bl_tree);
  5196.  
  5197. this.l_desc = null; /* desc. for literal tree */
  5198. this.d_desc = null; /* desc. for distance tree */
  5199. this.bl_desc = null; /* desc. for bit length tree */
  5200.  
  5201. //ush bl_count[MAX_BITS+1];
  5202. this.bl_count = new utils.Buf16(MAX_BITS+1);
  5203. /* number of codes at each bit length for an optimal tree */
  5204.  
  5205. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  5206. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  5207. zero(this.heap);
  5208.  
  5209. this.heap_len = 0; /* number of elements in the heap */
  5210. this.heap_max = 0; /* element of largest frequency */
  5211. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  5212. * The same heap array is used to build all trees.
  5213. */
  5214.  
  5215. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  5216. zero(this.depth);
  5217. /* Depth of each subtree used as tie breaker for trees of equal frequency
  5218. */
  5219.  
  5220. this.l_buf = 0; /* buffer index for literals or lengths */
  5221.  
  5222. this.lit_bufsize = 0;
  5223. /* Size of match buffer for literals/lengths. There are 4 reasons for
  5224. * limiting lit_bufsize to 64K:
  5225. * - frequencies can be kept in 16 bit counters
  5226. * - if compression is not successful for the first block, all input
  5227. * data is still in the window so we can still emit a stored block even
  5228. * when input comes from standard input. (This can also be done for
  5229. * all blocks if lit_bufsize is not greater than 32K.)
  5230. * - if compression is not successful for a file smaller than 64K, we can
  5231. * even emit a stored file instead of a stored block (saving 5 bytes).
  5232. * This is applicable only for zip (not gzip or zlib).
  5233. * - creating new Huffman trees less frequently may not provide fast
  5234. * adaptation to changes in the input data statistics. (Take for
  5235. * example a binary file with poorly compressible code followed by
  5236. * a highly compressible string table.) Smaller buffer sizes give
  5237. * fast adaptation but have of course the overhead of transmitting
  5238. * trees more frequently.
  5239. * - I can't count above 4
  5240. */
  5241.  
  5242. this.last_lit = 0; /* running index in l_buf */
  5243.  
  5244. this.d_buf = 0;
  5245. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  5246. * the same number of elements. To use different lengths, an extra flag
  5247. * array would be necessary.
  5248. */
  5249.  
  5250. this.opt_len = 0; /* bit length of current block with optimal trees */
  5251. this.static_len = 0; /* bit length of current block with static trees */
  5252. this.matches = 0; /* number of string matches in current block */
  5253. this.insert = 0; /* bytes at end of window left to insert */
  5254.  
  5255.  
  5256. this.bi_buf = 0;
  5257. /* Output buffer. bits are inserted starting at the bottom (least
  5258. * significant bits).
  5259. */
  5260. this.bi_valid = 0;
  5261. /* Number of valid bits in bi_buf. All bits above the last valid bit
  5262. * are always zero.
  5263. */
  5264.  
  5265. // Used for window memory init. We safely ignore it for JS. That makes
  5266. // sense only for pointers and memory check tools.
  5267. //this.high_water = 0;
  5268. /* High water mark offset in window for initialized bytes -- bytes above
  5269. * this are set to zero in order to avoid memory check warnings when
  5270. * longest match routines access bytes past the input. This is then
  5271. * updated to the new high water mark.
  5272. */
  5273. }
  5274.  
  5275.  
  5276. function deflateResetKeep(strm) {
  5277. var s;
  5278.  
  5279. if (!strm || !strm.state) {
  5280. return err(strm, Z_STREAM_ERROR);
  5281. }
  5282.  
  5283. strm.total_in = strm.total_out = 0;
  5284. strm.data_type = Z_UNKNOWN;
  5285.  
  5286. s = strm.state;
  5287. s.pending = 0;
  5288. s.pending_out = 0;
  5289.  
  5290. if (s.wrap < 0) {
  5291. s.wrap = -s.wrap;
  5292. /* was made negative by deflate(..., Z_FINISH); */
  5293. }
  5294. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  5295. strm.adler = (s.wrap === 2) ?
  5296. 0 // crc32(0, Z_NULL, 0)
  5297. :
  5298. 1; // adler32(0, Z_NULL, 0)
  5299. s.last_flush = Z_NO_FLUSH;
  5300. trees._tr_init(s);
  5301. return Z_OK;
  5302. }
  5303.  
  5304.  
  5305. function deflateReset(strm) {
  5306. var ret = deflateResetKeep(strm);
  5307. if (ret === Z_OK) {
  5308. lm_init(strm.state);
  5309. }
  5310. return ret;
  5311. }
  5312.  
  5313.  
  5314. function deflateSetHeader(strm, head) {
  5315. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  5316. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  5317. strm.state.gzhead = head;
  5318. return Z_OK;
  5319. }
  5320.  
  5321.  
  5322. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  5323. if (!strm) { // === Z_NULL
  5324. return Z_STREAM_ERROR;
  5325. }
  5326. var wrap = 1;
  5327.  
  5328. if (level === Z_DEFAULT_COMPRESSION) {
  5329. level = 6;
  5330. }
  5331.  
  5332. if (windowBits < 0) { /* suppress zlib wrapper */
  5333. wrap = 0;
  5334. windowBits = -windowBits;
  5335. }
  5336.  
  5337. else if (windowBits > 15) {
  5338. wrap = 2; /* write gzip wrapper instead */
  5339. windowBits -= 16;
  5340. }
  5341.  
  5342.  
  5343. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  5344. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  5345. strategy < 0 || strategy > Z_FIXED) {
  5346. return err(strm, Z_STREAM_ERROR);
  5347. }
  5348.  
  5349.  
  5350. if (windowBits === 8) {
  5351. windowBits = 9;
  5352. }
  5353. /* until 256-byte window bug fixed */
  5354.  
  5355. var s = new DeflateState();
  5356.  
  5357. strm.state = s;
  5358. s.strm = strm;
  5359.  
  5360. s.wrap = wrap;
  5361. s.gzhead = null;
  5362. s.w_bits = windowBits;
  5363. s.w_size = 1 << s.w_bits;
  5364. s.w_mask = s.w_size - 1;
  5365.  
  5366. s.hash_bits = memLevel + 7;
  5367. s.hash_size = 1 << s.hash_bits;
  5368. s.hash_mask = s.hash_size - 1;
  5369. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  5370.  
  5371. s.window = new utils.Buf8(s.w_size * 2);
  5372. s.head = new utils.Buf16(s.hash_size);
  5373. s.prev = new utils.Buf16(s.w_size);
  5374.  
  5375. // Don't need mem init magic for JS.
  5376. //s.high_water = 0; /* nothing written to s->window yet */
  5377.  
  5378. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  5379.  
  5380. s.pending_buf_size = s.lit_bufsize * 4;
  5381. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  5382.  
  5383. s.d_buf = s.lit_bufsize >> 1;
  5384. s.l_buf = (1 + 2) * s.lit_bufsize;
  5385.  
  5386. s.level = level;
  5387. s.strategy = strategy;
  5388. s.method = method;
  5389.  
  5390. return deflateReset(strm);
  5391. }
  5392.  
  5393. function deflateInit(strm, level) {
  5394. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  5395. }
  5396.  
  5397.  
  5398. function deflate(strm, flush) {
  5399. var old_flush, s;
  5400. var beg, val; // for gzip header write only
  5401.  
  5402. if (!strm || !strm.state ||
  5403. flush > Z_BLOCK || flush < 0) {
  5404. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  5405. }
  5406.  
  5407. s = strm.state;
  5408.  
  5409. if (!strm.output ||
  5410. (!strm.input && strm.avail_in !== 0) ||
  5411. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  5412. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  5413. }
  5414.  
  5415. s.strm = strm; /* just in case */
  5416. old_flush = s.last_flush;
  5417. s.last_flush = flush;
  5418.  
  5419. /* Write the header */
  5420. if (s.status === INIT_STATE) {
  5421.  
  5422. if (s.wrap === 2) { // GZIP header
  5423. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  5424. put_byte(s, 31);
  5425. put_byte(s, 139);
  5426. put_byte(s, 8);
  5427. if (!s.gzhead) { // s->gzhead == Z_NULL
  5428. put_byte(s, 0);
  5429. put_byte(s, 0);
  5430. put_byte(s, 0);
  5431. put_byte(s, 0);
  5432. put_byte(s, 0);
  5433. put_byte(s, s.level === 9 ? 2 :
  5434. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  5435. 4 : 0));
  5436. put_byte(s, OS_CODE);
  5437. s.status = BUSY_STATE;
  5438. }
  5439. else {
  5440. put_byte(s, (s.gzhead.text ? 1 : 0) +
  5441. (s.gzhead.hcrc ? 2 : 0) +
  5442. (!s.gzhead.extra ? 0 : 4) +
  5443. (!s.gzhead.name ? 0 : 8) +
  5444. (!s.gzhead.comment ? 0 : 16)
  5445. );
  5446. put_byte(s, s.gzhead.time & 0xff);
  5447. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  5448. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  5449. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  5450. put_byte(s, s.level === 9 ? 2 :
  5451. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  5452. 4 : 0));
  5453. put_byte(s, s.gzhead.os & 0xff);
  5454. if (s.gzhead.extra && s.gzhead.extra.length) {
  5455. put_byte(s, s.gzhead.extra.length & 0xff);
  5456. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  5457. }
  5458. if (s.gzhead.hcrc) {
  5459. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  5460. }
  5461. s.gzindex = 0;
  5462. s.status = EXTRA_STATE;
  5463. }
  5464. }
  5465. else // DEFLATE header
  5466. {
  5467. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  5468. var level_flags = -1;
  5469.  
  5470. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  5471. level_flags = 0;
  5472. } else if (s.level < 6) {
  5473. level_flags = 1;
  5474. } else if (s.level === 6) {
  5475. level_flags = 2;
  5476. } else {
  5477. level_flags = 3;
  5478. }
  5479. header |= (level_flags << 6);
  5480. if (s.strstart !== 0) { header |= PRESET_DICT; }
  5481. header += 31 - (header % 31);
  5482.  
  5483. s.status = BUSY_STATE;
  5484. putShortMSB(s, header);
  5485.  
  5486. /* Save the adler32 of the preset dictionary: */
  5487. if (s.strstart !== 0) {
  5488. putShortMSB(s, strm.adler >>> 16);
  5489. putShortMSB(s, strm.adler & 0xffff);
  5490. }
  5491. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  5492. }
  5493. }
  5494.  
  5495. //#ifdef GZIP
  5496. if (s.status === EXTRA_STATE) {
  5497. if (s.gzhead.extra/* != Z_NULL*/) {
  5498. beg = s.pending; /* start of bytes to update crc */
  5499.  
  5500. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  5501. if (s.pending === s.pending_buf_size) {
  5502. if (s.gzhead.hcrc && s.pending > beg) {
  5503. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  5504. }
  5505. flush_pending(strm);
  5506. beg = s.pending;
  5507. if (s.pending === s.pending_buf_size) {
  5508. break;
  5509. }
  5510. }
  5511. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  5512. s.gzindex++;
  5513. }
  5514. if (s.gzhead.hcrc && s.pending > beg) {
  5515. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  5516. }
  5517. if (s.gzindex === s.gzhead.extra.length) {
  5518. s.gzindex = 0;
  5519. s.status = NAME_STATE;
  5520. }
  5521. }
  5522. else {
  5523. s.status = NAME_STATE;
  5524. }
  5525. }
  5526. if (s.status === NAME_STATE) {
  5527. if (s.gzhead.name/* != Z_NULL*/) {
  5528. beg = s.pending; /* start of bytes to update crc */
  5529. //int val;
  5530.  
  5531. do {
  5532. if (s.pending === s.pending_buf_size) {
  5533. if (s.gzhead.hcrc && s.pending > beg) {
  5534. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  5535. }
  5536. flush_pending(strm);
  5537. beg = s.pending;
  5538. if (s.pending === s.pending_buf_size) {
  5539. val = 1;
  5540. break;
  5541. }
  5542. }
  5543. // JS specific: little magic to add zero terminator to end of string
  5544. if (s.gzindex < s.gzhead.name.length) {
  5545. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  5546. } else {
  5547. val = 0;
  5548. }
  5549. put_byte(s, val);
  5550. } while (val !== 0);
  5551.  
  5552. if (s.gzhead.hcrc && s.pending > beg){
  5553. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  5554. }
  5555. if (val === 0) {
  5556. s.gzindex = 0;
  5557. s.status = COMMENT_STATE;
  5558. }
  5559. }
  5560. else {
  5561. s.status = COMMENT_STATE;
  5562. }
  5563. }
  5564. if (s.status === COMMENT_STATE) {
  5565. if (s.gzhead.comment/* != Z_NULL*/) {
  5566. beg = s.pending; /* start of bytes to update crc */
  5567. //int val;
  5568.  
  5569. do {
  5570. if (s.pending === s.pending_buf_size) {
  5571. if (s.gzhead.hcrc && s.pending > beg) {
  5572. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  5573. }
  5574. flush_pending(strm);
  5575. beg = s.pending;
  5576. if (s.pending === s.pending_buf_size) {
  5577. val = 1;
  5578. break;
  5579. }
  5580. }
  5581. // JS specific: little magic to add zero terminator to end of string
  5582. if (s.gzindex < s.gzhead.comment.length) {
  5583. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  5584. } else {
  5585. val = 0;
  5586. }
  5587. put_byte(s, val);
  5588. } while (val !== 0);
  5589.  
  5590. if (s.gzhead.hcrc && s.pending > beg) {
  5591. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  5592. }
  5593. if (val === 0) {
  5594. s.status = HCRC_STATE;
  5595. }
  5596. }
  5597. else {
  5598. s.status = HCRC_STATE;
  5599. }
  5600. }
  5601. if (s.status === HCRC_STATE) {
  5602. if (s.gzhead.hcrc) {
  5603. if (s.pending + 2 > s.pending_buf_size) {
  5604. flush_pending(strm);
  5605. }
  5606. if (s.pending + 2 <= s.pending_buf_size) {
  5607. put_byte(s, strm.adler & 0xff);
  5608. put_byte(s, (strm.adler >> 8) & 0xff);
  5609. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  5610. s.status = BUSY_STATE;
  5611. }
  5612. }
  5613. else {
  5614. s.status = BUSY_STATE;
  5615. }
  5616. }
  5617. //#endif
  5618.  
  5619. /* Flush as much pending output as possible */
  5620. if (s.pending !== 0) {
  5621. flush_pending(strm);
  5622. if (strm.avail_out === 0) {
  5623. /* Since avail_out is 0, deflate will be called again with
  5624. * more output space, but possibly with both pending and
  5625. * avail_in equal to zero. There won't be anything to do,
  5626. * but this is not an error situation so make sure we
  5627. * return OK instead of BUF_ERROR at next call of deflate:
  5628. */
  5629. s.last_flush = -1;
  5630. return Z_OK;
  5631. }
  5632.  
  5633. /* Make sure there is something to do and avoid duplicate consecutive
  5634. * flushes. For repeated and useless calls with Z_FINISH, we keep
  5635. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  5636. */
  5637. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  5638. flush !== Z_FINISH) {
  5639. return err(strm, Z_BUF_ERROR);
  5640. }
  5641.  
  5642. /* User must not provide more input after the first FINISH: */
  5643. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  5644. return err(strm, Z_BUF_ERROR);
  5645. }
  5646.  
  5647. /* Start a new block or continue the current one.
  5648. */
  5649. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  5650. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  5651. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  5652. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  5653. configuration_table[s.level].func(s, flush));
  5654.  
  5655. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  5656. s.status = FINISH_STATE;
  5657. }
  5658. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  5659. if (strm.avail_out === 0) {
  5660. s.last_flush = -1;
  5661. /* avoid BUF_ERROR next call, see above */
  5662. }
  5663. return Z_OK;
  5664. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  5665. * of deflate should use the same flush parameter to make sure
  5666. * that the flush is complete. So we don't have to output an
  5667. * empty block here, this will be done at next call. This also
  5668. * ensures that for a very small output buffer, we emit at most
  5669. * one empty block.
  5670. */
  5671. }
  5672. if (bstate === BS_BLOCK_DONE) {
  5673. if (flush === Z_PARTIAL_FLUSH) {
  5674. trees._tr_align(s);
  5675. }
  5676. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  5677.  
  5678. trees._tr_stored_block(s, 0, 0, false);
  5679. /* For a full flush, this empty block will be recognized
  5680. * as a special marker by inflate_sync().
  5681. */
  5682. if (flush === Z_FULL_FLUSH) {
  5683. /*** CLEAR_HASH(s); ***/ /* forget history */
  5684. zero(s.head); // Fill with NIL (= 0);
  5685.  
  5686. if (s.lookahead === 0) {
  5687. s.strstart = 0;
  5688. s.block_start = 0;
  5689. s.insert = 0;
  5690. }
  5691. }
  5692. }
  5693. flush_pending(strm);
  5694. if (strm.avail_out === 0) {
  5695. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  5696. return Z_OK;
  5697. }
  5698. }
  5699. }
  5700. //Assert(strm->avail_out > 0, "bug2");
  5701. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  5702.  
  5703. if (flush !== Z_FINISH) { return Z_OK; }
  5704. if (s.wrap <= 0) { return Z_STREAM_END; }
  5705.  
  5706. /* Write the trailer */
  5707. if (s.wrap === 2) {
  5708. put_byte(s, strm.adler & 0xff);
  5709. put_byte(s, (strm.adler >> 8) & 0xff);
  5710. put_byte(s, (strm.adler >> 16) & 0xff);
  5711. put_byte(s, (strm.adler >> 24) & 0xff);
  5712. put_byte(s, strm.total_in & 0xff);
  5713. put_byte(s, (strm.total_in >> 8) & 0xff);
  5714. put_byte(s, (strm.total_in >> 16) & 0xff);
  5715. put_byte(s, (strm.total_in >> 24) & 0xff);
  5716. }
  5717. else
  5718. {
  5719. putShortMSB(s, strm.adler >>> 16);
  5720. putShortMSB(s, strm.adler & 0xffff);
  5721. }
  5722.  
  5723. flush_pending(strm);
  5724. /* If avail_out is zero, the application will call deflate again
  5725. * to flush the rest.
  5726. */
  5727. if (s.wrap > 0) { s.wrap = -s.wrap; }
  5728. /* write the trailer only once! */
  5729. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  5730. }
  5731.  
  5732. function deflateEnd(strm) {
  5733. var status;
  5734.  
  5735. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  5736. return Z_STREAM_ERROR;
  5737. }
  5738.  
  5739. status = strm.state.status;
  5740. if (status !== INIT_STATE &&
  5741. status !== EXTRA_STATE &&
  5742. status !== NAME_STATE &&
  5743. status !== COMMENT_STATE &&
  5744. status !== HCRC_STATE &&
  5745. status !== BUSY_STATE &&
  5746. status !== FINISH_STATE
  5747. ) {
  5748. return err(strm, Z_STREAM_ERROR);
  5749. }
  5750.  
  5751. strm.state = null;
  5752.  
  5753. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  5754. }
  5755.  
  5756. /* =========================================================================
  5757. * Copy the source state to the destination state
  5758. */
  5759. //function deflateCopy(dest, source) {
  5760. //
  5761. //}
  5762.  
  5763. exports.deflateInit = deflateInit;
  5764. exports.deflateInit2 = deflateInit2;
  5765. exports.deflateReset = deflateReset;
  5766. exports.deflateResetKeep = deflateResetKeep;
  5767. exports.deflateSetHeader = deflateSetHeader;
  5768. exports.deflate = deflate;
  5769. exports.deflateEnd = deflateEnd;
  5770. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  5771.  
  5772. /* Not implemented
  5773. exports.deflateBound = deflateBound;
  5774. exports.deflateCopy = deflateCopy;
  5775. exports.deflateSetDictionary = deflateSetDictionary;
  5776. exports.deflateParams = deflateParams;
  5777. exports.deflatePending = deflatePending;
  5778. exports.deflatePrime = deflatePrime;
  5779. exports.deflateTune = deflateTune;
  5780. */
  5781. },{"../utils/common":27,"./adler32":29,"./crc32":31,"./messages":37,"./trees":38}],33:[function(_dereq_,module,exports){
  5782. 'use strict';
  5783.  
  5784.  
  5785. function GZheader() {
  5786. /* true if compressed data believed to be text */
  5787. this.text = 0;
  5788. /* modification time */
  5789. this.time = 0;
  5790. /* extra flags (not used when writing a gzip file) */
  5791. this.xflags = 0;
  5792. /* operating system */
  5793. this.os = 0;
  5794. /* pointer to extra field or Z_NULL if none */
  5795. this.extra = null;
  5796. /* extra field length (valid if extra != Z_NULL) */
  5797. this.extra_len = 0; // Actually, we don't need it in JS,
  5798. // but leave for few code modifications
  5799.  
  5800. //
  5801. // Setup limits is not necessary because in js we should not preallocate memory
  5802. // for inflate use constant limit in 65536 bytes
  5803. //
  5804.  
  5805. /* space at extra (only when reading header) */
  5806. // this.extra_max = 0;
  5807. /* pointer to zero-terminated file name or Z_NULL */
  5808. this.name = '';
  5809. /* space at name (only when reading header) */
  5810. // this.name_max = 0;
  5811. /* pointer to zero-terminated comment or Z_NULL */
  5812. this.comment = '';
  5813. /* space at comment (only when reading header) */
  5814. // this.comm_max = 0;
  5815. /* true if there was or will be a header crc */
  5816. this.hcrc = 0;
  5817. /* true when done reading gzip header (not used when writing a gzip file) */
  5818. this.done = false;
  5819. }
  5820.  
  5821. module.exports = GZheader;
  5822. },{}],34:[function(_dereq_,module,exports){
  5823. 'use strict';
  5824.  
  5825. // See state defs from inflate.js
  5826. var BAD = 30; /* got a data error -- remain here until reset */
  5827. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  5828.  
  5829. /*
  5830. Decode literal, length, and distance codes and write out the resulting
  5831. literal and match bytes until either not enough input or output is
  5832. available, an end-of-block is encountered, or a data error is encountered.
  5833. When large enough input and output buffers are supplied to inflate(), for
  5834. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  5835. inflate execution time is spent in this routine.
  5836.  
  5837. Entry assumptions:
  5838.  
  5839. state.mode === LEN
  5840. strm.avail_in >= 6
  5841. strm.avail_out >= 258
  5842. start >= strm.avail_out
  5843. state.bits < 8
  5844.  
  5845. On return, state.mode is one of:
  5846.  
  5847. LEN -- ran out of enough output space or enough available input
  5848. TYPE -- reached end of block code, inflate() to interpret next block
  5849. BAD -- error in block data
  5850.  
  5851. Notes:
  5852.  
  5853. - The maximum input bits used by a length/distance pair is 15 bits for the
  5854. length code, 5 bits for the length extra, 15 bits for the distance code,
  5855. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  5856. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  5857. checking for available input while decoding.
  5858.  
  5859. - The maximum bytes that a single length/distance pair can output is 258
  5860. bytes, which is the maximum length that can be coded. inflate_fast()
  5861. requires strm.avail_out >= 258 for each loop to avoid checking for
  5862. output space.
  5863. */
  5864. module.exports = function inflate_fast(strm, start) {
  5865. var state;
  5866. var _in; /* local strm.input */
  5867. var last; /* have enough input while in < last */
  5868. var _out; /* local strm.output */
  5869. var beg; /* inflate()'s initial strm.output */
  5870. var end; /* while out < end, enough space available */
  5871. //#ifdef INFLATE_STRICT
  5872. var dmax; /* maximum distance from zlib header */
  5873. //#endif
  5874. var wsize; /* window size or zero if not using window */
  5875. var whave; /* valid bytes in the window */
  5876. var wnext; /* window write index */
  5877. var window; /* allocated sliding window, if wsize != 0 */
  5878. var hold; /* local strm.hold */
  5879. var bits; /* local strm.bits */
  5880. var lcode; /* local strm.lencode */
  5881. var dcode; /* local strm.distcode */
  5882. var lmask; /* mask for first level of length codes */
  5883. var dmask; /* mask for first level of distance codes */
  5884. var here; /* retrieved table entry */
  5885. var op; /* code bits, operation, extra bits, or */
  5886. /* window position, window bytes to copy */
  5887. var len; /* match length, unused bytes */
  5888. var dist; /* match distance */
  5889. var from; /* where to copy match from */
  5890. var from_source;
  5891.  
  5892.  
  5893. var input, output; // JS specific, because we have no pointers
  5894.  
  5895. /* copy state to local variables */
  5896. state = strm.state;
  5897. //here = state.here;
  5898. _in = strm.next_in;
  5899. input = strm.input;
  5900. last = _in + (strm.avail_in - 5);
  5901. _out = strm.next_out;
  5902. output = strm.output;
  5903. beg = _out - (start - strm.avail_out);
  5904. end = _out + (strm.avail_out - 257);
  5905. //#ifdef INFLATE_STRICT
  5906. dmax = state.dmax;
  5907. //#endif
  5908. wsize = state.wsize;
  5909. whave = state.whave;
  5910. wnext = state.wnext;
  5911. window = state.window;
  5912. hold = state.hold;
  5913. bits = state.bits;
  5914. lcode = state.lencode;
  5915. dcode = state.distcode;
  5916. lmask = (1 << state.lenbits) - 1;
  5917. dmask = (1 << state.distbits) - 1;
  5918.  
  5919.  
  5920. /* decode literals and length/distances until end-of-block or not enough
  5921. input data or output space */
  5922.  
  5923. top:
  5924. do {
  5925. if (bits < 15) {
  5926. hold += input[_in++] << bits;
  5927. bits += 8;
  5928. hold += input[_in++] << bits;
  5929. bits += 8;
  5930. }
  5931.  
  5932. here = lcode[hold & lmask];
  5933.  
  5934. dolen:
  5935. for (;;) { // Goto emulation
  5936. op = here >>> 24/*here.bits*/;
  5937. hold >>>= op;
  5938. bits -= op;
  5939. op = (here >>> 16) & 0xff/*here.op*/;
  5940. if (op === 0) { /* literal */
  5941. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  5942. // "inflate: literal '%c'\n" :
  5943. // "inflate: literal 0x%02x\n", here.val));
  5944. output[_out++] = here & 0xffff/*here.val*/;
  5945. }
  5946. else if (op & 16) { /* length base */
  5947. len = here & 0xffff/*here.val*/;
  5948. op &= 15; /* number of extra bits */
  5949. if (op) {
  5950. if (bits < op) {
  5951. hold += input[_in++] << bits;
  5952. bits += 8;
  5953. }
  5954. len += hold & ((1 << op) - 1);
  5955. hold >>>= op;
  5956. bits -= op;
  5957. }
  5958. //Tracevv((stderr, "inflate: length %u\n", len));
  5959. if (bits < 15) {
  5960. hold += input[_in++] << bits;
  5961. bits += 8;
  5962. hold += input[_in++] << bits;
  5963. bits += 8;
  5964. }
  5965. here = dcode[hold & dmask];
  5966.  
  5967. dodist:
  5968. for (;;) { // goto emulation
  5969. op = here >>> 24/*here.bits*/;
  5970. hold >>>= op;
  5971. bits -= op;
  5972. op = (here >>> 16) & 0xff/*here.op*/;
  5973.  
  5974. if (op & 16) { /* distance base */
  5975. dist = here & 0xffff/*here.val*/;
  5976. op &= 15; /* number of extra bits */
  5977. if (bits < op) {
  5978. hold += input[_in++] << bits;
  5979. bits += 8;
  5980. if (bits < op) {
  5981. hold += input[_in++] << bits;
  5982. bits += 8;
  5983. }
  5984. }
  5985. dist += hold & ((1 << op) - 1);
  5986. //#ifdef INFLATE_STRICT
  5987. if (dist > dmax) {
  5988. strm.msg = 'invalid distance too far back';
  5989. state.mode = BAD;
  5990. break top;
  5991. }
  5992. //#endif
  5993. hold >>>= op;
  5994. bits -= op;
  5995. //Tracevv((stderr, "inflate: distance %u\n", dist));
  5996. op = _out - beg; /* max distance in output */
  5997. if (dist > op) { /* see if copy from window */
  5998. op = dist - op; /* distance back in window */
  5999. if (op > whave) {
  6000. if (state.sane) {
  6001. strm.msg = 'invalid distance too far back';
  6002. state.mode = BAD;
  6003. break top;
  6004. }
  6005.  
  6006. // (!) This block is disabled in zlib defailts,
  6007. // don't enable it for binary compatibility
  6008. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  6009. // if (len <= op - whave) {
  6010. // do {
  6011. // output[_out++] = 0;
  6012. // } while (--len);
  6013. // continue top;
  6014. // }
  6015. // len -= op - whave;
  6016. // do {
  6017. // output[_out++] = 0;
  6018. // } while (--op > whave);
  6019. // if (op === 0) {
  6020. // from = _out - dist;
  6021. // do {
  6022. // output[_out++] = output[from++];
  6023. // } while (--len);
  6024. // continue top;
  6025. // }
  6026. //#endif
  6027. }
  6028. from = 0; // window index
  6029. from_source = window;
  6030. if (wnext === 0) { /* very common case */
  6031. from += wsize - op;
  6032. if (op < len) { /* some from window */
  6033. len -= op;
  6034. do {
  6035. output[_out++] = window[from++];
  6036. } while (--op);
  6037. from = _out - dist; /* rest from output */
  6038. from_source = output;
  6039. }
  6040. }
  6041. else if (wnext < op) { /* wrap around window */
  6042. from += wsize + wnext - op;
  6043. op -= wnext;
  6044. if (op < len) { /* some from end of window */
  6045. len -= op;
  6046. do {
  6047. output[_out++] = window[from++];
  6048. } while (--op);
  6049. from = 0;
  6050. if (wnext < len) { /* some from start of window */
  6051. op = wnext;
  6052. len -= op;
  6053. do {
  6054. output[_out++] = window[from++];
  6055. } while (--op);
  6056. from = _out - dist; /* rest from output */
  6057. from_source = output;
  6058. }
  6059. }
  6060. }
  6061. else { /* contiguous in window */
  6062. from += wnext - op;
  6063. if (op < len) { /* some from window */
  6064. len -= op;
  6065. do {
  6066. output[_out++] = window[from++];
  6067. } while (--op);
  6068. from = _out - dist; /* rest from output */
  6069. from_source = output;
  6070. }
  6071. }
  6072. while (len > 2) {
  6073. output[_out++] = from_source[from++];
  6074. output[_out++] = from_source[from++];
  6075. output[_out++] = from_source[from++];
  6076. len -= 3;
  6077. }
  6078. if (len) {
  6079. output[_out++] = from_source[from++];
  6080. if (len > 1) {
  6081. output[_out++] = from_source[from++];
  6082. }
  6083. }
  6084. }
  6085. else {
  6086. from = _out - dist; /* copy direct from output */
  6087. do { /* minimum length is three */
  6088. output[_out++] = output[from++];
  6089. output[_out++] = output[from++];
  6090. output[_out++] = output[from++];
  6091. len -= 3;
  6092. } while (len > 2);
  6093. if (len) {
  6094. output[_out++] = output[from++];
  6095. if (len > 1) {
  6096. output[_out++] = output[from++];
  6097. }
  6098. }
  6099. }
  6100. }
  6101. else if ((op & 64) === 0) { /* 2nd level distance code */
  6102. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  6103. continue dodist;
  6104. }
  6105. else {
  6106. strm.msg = 'invalid distance code';
  6107. state.mode = BAD;
  6108. break top;
  6109. }
  6110.  
  6111. break; // need to emulate goto via "continue"
  6112. }
  6113. }
  6114. else if ((op & 64) === 0) { /* 2nd level length code */
  6115. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  6116. continue dolen;
  6117. }
  6118. else if (op & 32) { /* end-of-block */
  6119. //Tracevv((stderr, "inflate: end of block\n"));
  6120. state.mode = TYPE;
  6121. break top;
  6122. }
  6123. else {
  6124. strm.msg = 'invalid literal/length code';
  6125. state.mode = BAD;
  6126. break top;
  6127. }
  6128.  
  6129. break; // need to emulate goto via "continue"
  6130. }
  6131. } while (_in < last && _out < end);
  6132.  
  6133. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  6134. len = bits >> 3;
  6135. _in -= len;
  6136. bits -= len << 3;
  6137. hold &= (1 << bits) - 1;
  6138.  
  6139. /* update state and return */
  6140. strm.next_in = _in;
  6141. strm.next_out = _out;
  6142. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  6143. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  6144. state.hold = hold;
  6145. state.bits = bits;
  6146. return;
  6147. };
  6148.  
  6149. },{}],35:[function(_dereq_,module,exports){
  6150. 'use strict';
  6151.  
  6152.  
  6153. var utils = _dereq_('../utils/common');
  6154. var adler32 = _dereq_('./adler32');
  6155. var crc32 = _dereq_('./crc32');
  6156. var inflate_fast = _dereq_('./inffast');
  6157. var inflate_table = _dereq_('./inftrees');
  6158.  
  6159. var CODES = 0;
  6160. var LENS = 1;
  6161. var DISTS = 2;
  6162.  
  6163. /* Public constants ==========================================================*/
  6164. /* ===========================================================================*/
  6165.  
  6166.  
  6167. /* Allowed flush values; see deflate() and inflate() below for details */
  6168. //var Z_NO_FLUSH = 0;
  6169. //var Z_PARTIAL_FLUSH = 1;
  6170. //var Z_SYNC_FLUSH = 2;
  6171. //var Z_FULL_FLUSH = 3;
  6172. var Z_FINISH = 4;
  6173. var Z_BLOCK = 5;
  6174. var Z_TREES = 6;
  6175.  
  6176.  
  6177. /* Return codes for the compression/decompression functions. Negative values
  6178. * are errors, positive values are used for special but normal events.
  6179. */
  6180. var Z_OK = 0;
  6181. var Z_STREAM_END = 1;
  6182. var Z_NEED_DICT = 2;
  6183. //var Z_ERRNO = -1;
  6184. var Z_STREAM_ERROR = -2;
  6185. var Z_DATA_ERROR = -3;
  6186. var Z_MEM_ERROR = -4;
  6187. var Z_BUF_ERROR = -5;
  6188. //var Z_VERSION_ERROR = -6;
  6189.  
  6190. /* The deflate compression method */
  6191. var Z_DEFLATED = 8;
  6192.  
  6193.  
  6194. /* STATES ====================================================================*/
  6195. /* ===========================================================================*/
  6196.  
  6197.  
  6198. var HEAD = 1; /* i: waiting for magic header */
  6199. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  6200. var TIME = 3; /* i: waiting for modification time (gzip) */
  6201. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  6202. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  6203. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  6204. var NAME = 7; /* i: waiting for end of file name (gzip) */
  6205. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  6206. var HCRC = 9; /* i: waiting for header crc (gzip) */
  6207. var DICTID = 10; /* i: waiting for dictionary check value */
  6208. var DICT = 11; /* waiting for inflateSetDictionary() call */
  6209. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  6210. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  6211. var STORED = 14; /* i: waiting for stored size (length and complement) */
  6212. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  6213. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  6214. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  6215. var LENLENS = 18; /* i: waiting for code length code lengths */
  6216. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  6217. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  6218. var LEN = 21; /* i: waiting for length/lit/eob code */
  6219. var LENEXT = 22; /* i: waiting for length extra bits */
  6220. var DIST = 23; /* i: waiting for distance code */
  6221. var DISTEXT = 24; /* i: waiting for distance extra bits */
  6222. var MATCH = 25; /* o: waiting for output space to copy string */
  6223. var LIT = 26; /* o: waiting for output space to write literal */
  6224. var CHECK = 27; /* i: waiting for 32-bit check value */
  6225. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  6226. var DONE = 29; /* finished check, done -- remain here until reset */
  6227. var BAD = 30; /* got a data error -- remain here until reset */
  6228. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  6229. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  6230.  
  6231. /* ===========================================================================*/
  6232.  
  6233.  
  6234.  
  6235. var ENOUGH_LENS = 852;
  6236. var ENOUGH_DISTS = 592;
  6237. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  6238.  
  6239. var MAX_WBITS = 15;
  6240. /* 32K LZ77 window */
  6241. var DEF_WBITS = MAX_WBITS;
  6242.  
  6243.  
  6244. function ZSWAP32(q) {
  6245. return (((q >>> 24) & 0xff) +
  6246. ((q >>> 8) & 0xff00) +
  6247. ((q & 0xff00) << 8) +
  6248. ((q & 0xff) << 24));
  6249. }
  6250.  
  6251.  
  6252. function InflateState() {
  6253. this.mode = 0; /* current inflate mode */
  6254. this.last = false; /* true if processing last block */
  6255. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  6256. this.havedict = false; /* true if dictionary provided */
  6257. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  6258. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  6259. this.check = 0; /* protected copy of check value */
  6260. this.total = 0; /* protected copy of output count */
  6261. // TODO: may be {}
  6262. this.head = null; /* where to save gzip header information */
  6263.  
  6264. /* sliding window */
  6265. this.wbits = 0; /* log base 2 of requested window size */
  6266. this.wsize = 0; /* window size or zero if not using window */
  6267. this.whave = 0; /* valid bytes in the window */
  6268. this.wnext = 0; /* window write index */
  6269. this.window = null; /* allocated sliding window, if needed */
  6270.  
  6271. /* bit accumulator */
  6272. this.hold = 0; /* input bit accumulator */
  6273. this.bits = 0; /* number of bits in "in" */
  6274.  
  6275. /* for string and stored block copying */
  6276. this.length = 0; /* literal or length of data to copy */
  6277. this.offset = 0; /* distance back to copy string from */
  6278.  
  6279. /* for table and code decoding */
  6280. this.extra = 0; /* extra bits needed */
  6281.  
  6282. /* fixed and dynamic code tables */
  6283. this.lencode = null; /* starting table for length/literal codes */
  6284. this.distcode = null; /* starting table for distance codes */
  6285. this.lenbits = 0; /* index bits for lencode */
  6286. this.distbits = 0; /* index bits for distcode */
  6287.  
  6288. /* dynamic table building */
  6289. this.ncode = 0; /* number of code length code lengths */
  6290. this.nlen = 0; /* number of length code lengths */
  6291. this.ndist = 0; /* number of distance code lengths */
  6292. this.have = 0; /* number of code lengths in lens[] */
  6293. this.next = null; /* next available space in codes[] */
  6294.  
  6295. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  6296. this.work = new utils.Buf16(288); /* work area for code table building */
  6297.  
  6298. /*
  6299. because we don't have pointers in js, we use lencode and distcode directly
  6300. as buffers so we don't need codes
  6301. */
  6302. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  6303. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  6304. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  6305. this.sane = 0; /* if false, allow invalid distance too far */
  6306. this.back = 0; /* bits back of last unprocessed length/lit */
  6307. this.was = 0; /* initial length of match */
  6308. }
  6309.  
  6310. function inflateResetKeep(strm) {
  6311. var state;
  6312.  
  6313. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  6314. state = strm.state;
  6315. strm.total_in = strm.total_out = state.total = 0;
  6316. strm.msg = ''; /*Z_NULL*/
  6317. if (state.wrap) { /* to support ill-conceived Java test suite */
  6318. strm.adler = state.wrap & 1;
  6319. }
  6320. state.mode = HEAD;
  6321. state.last = 0;
  6322. state.havedict = 0;
  6323. state.dmax = 32768;
  6324. state.head = null/*Z_NULL*/;
  6325. state.hold = 0;
  6326. state.bits = 0;
  6327. //state.lencode = state.distcode = state.next = state.codes;
  6328. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  6329. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  6330.  
  6331. state.sane = 1;
  6332. state.back = -1;
  6333. //Tracev((stderr, "inflate: reset\n"));
  6334. return Z_OK;
  6335. }
  6336.  
  6337. function inflateReset(strm) {
  6338. var state;
  6339.  
  6340. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  6341. state = strm.state;
  6342. state.wsize = 0;
  6343. state.whave = 0;
  6344. state.wnext = 0;
  6345. return inflateResetKeep(strm);
  6346.  
  6347. }
  6348.  
  6349. function inflateReset2(strm, windowBits) {
  6350. var wrap;
  6351. var state;
  6352.  
  6353. /* get the state */
  6354. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  6355. state = strm.state;
  6356.  
  6357. /* extract wrap request from windowBits parameter */
  6358. if (windowBits < 0) {
  6359. wrap = 0;
  6360. windowBits = -windowBits;
  6361. }
  6362. else {
  6363. wrap = (windowBits >> 4) + 1;
  6364. if (windowBits < 48) {
  6365. windowBits &= 15;
  6366. }
  6367. }
  6368.  
  6369. /* set number of window bits, free window if different */
  6370. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  6371. return Z_STREAM_ERROR;
  6372. }
  6373. if (state.window !== null && state.wbits !== windowBits) {
  6374. state.window = null;
  6375. }
  6376.  
  6377. /* update state and reset the rest of it */
  6378. state.wrap = wrap;
  6379. state.wbits = windowBits;
  6380. return inflateReset(strm);
  6381. }
  6382.  
  6383. function inflateInit2(strm, windowBits) {
  6384. var ret;
  6385. var state;
  6386.  
  6387. if (!strm) { return Z_STREAM_ERROR; }
  6388. //strm.msg = Z_NULL; /* in case we return an error */
  6389.  
  6390. state = new InflateState();
  6391.  
  6392. //if (state === Z_NULL) return Z_MEM_ERROR;
  6393. //Tracev((stderr, "inflate: allocated\n"));
  6394. strm.state = state;
  6395. state.window = null/*Z_NULL*/;
  6396. ret = inflateReset2(strm, windowBits);
  6397. if (ret !== Z_OK) {
  6398. strm.state = null/*Z_NULL*/;
  6399. }
  6400. return ret;
  6401. }
  6402.  
  6403. function inflateInit(strm) {
  6404. return inflateInit2(strm, DEF_WBITS);
  6405. }
  6406.  
  6407.  
  6408. /*
  6409. Return state with length and distance decoding tables and index sizes set to
  6410. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  6411. If BUILDFIXED is defined, then instead this routine builds the tables the
  6412. first time it's called, and returns those tables the first time and
  6413. thereafter. This reduces the size of the code by about 2K bytes, in
  6414. exchange for a little execution time. However, BUILDFIXED should not be
  6415. used for threaded applications, since the rewriting of the tables and virgin
  6416. may not be thread-safe.
  6417. */
  6418. var virgin = true;
  6419.  
  6420. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  6421.  
  6422. function fixedtables(state) {
  6423. /* build fixed huffman tables if first call (may not be thread safe) */
  6424. if (virgin) {
  6425. var sym;
  6426.  
  6427. lenfix = new utils.Buf32(512);
  6428. distfix = new utils.Buf32(32);
  6429.  
  6430. /* literal/length table */
  6431. sym = 0;
  6432. while (sym < 144) { state.lens[sym++] = 8; }
  6433. while (sym < 256) { state.lens[sym++] = 9; }
  6434. while (sym < 280) { state.lens[sym++] = 7; }
  6435. while (sym < 288) { state.lens[sym++] = 8; }
  6436.  
  6437. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  6438.  
  6439. /* distance table */
  6440. sym = 0;
  6441. while (sym < 32) { state.lens[sym++] = 5; }
  6442.  
  6443. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  6444.  
  6445. /* do this just once */
  6446. virgin = false;
  6447. }
  6448.  
  6449. state.lencode = lenfix;
  6450. state.lenbits = 9;
  6451. state.distcode = distfix;
  6452. state.distbits = 5;
  6453. }
  6454.  
  6455.  
  6456. /*
  6457. Update the window with the last wsize (normally 32K) bytes written before
  6458. returning. If window does not exist yet, create it. This is only called
  6459. when a window is already in use, or when output has been written during this
  6460. inflate call, but the end of the deflate stream has not been reached yet.
  6461. It is also called to create a window for dictionary data when a dictionary
  6462. is loaded.
  6463.  
  6464. Providing output buffers larger than 32K to inflate() should provide a speed
  6465. advantage, since only the last 32K of output is copied to the sliding window
  6466. upon return from inflate(), and since all distances after the first 32K of
  6467. output will fall in the output data, making match copies simpler and faster.
  6468. The advantage may be dependent on the size of the processor's data caches.
  6469. */
  6470. function updatewindow(strm, src, end, copy) {
  6471. var dist;
  6472. var state = strm.state;
  6473.  
  6474. /* if it hasn't been done already, allocate space for the window */
  6475. if (state.window === null) {
  6476. state.wsize = 1 << state.wbits;
  6477. state.wnext = 0;
  6478. state.whave = 0;
  6479.  
  6480. state.window = new utils.Buf8(state.wsize);
  6481. }
  6482.  
  6483. /* copy state->wsize or less output bytes into the circular window */
  6484. if (copy >= state.wsize) {
  6485. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  6486. state.wnext = 0;
  6487. state.whave = state.wsize;
  6488. }
  6489. else {
  6490. dist = state.wsize - state.wnext;
  6491. if (dist > copy) {
  6492. dist = copy;
  6493. }
  6494. //zmemcpy(state->window + state->wnext, end - copy, dist);
  6495. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  6496. copy -= dist;
  6497. if (copy) {
  6498. //zmemcpy(state->window, end - copy, copy);
  6499. utils.arraySet(state.window,src, end - copy, copy, 0);
  6500. state.wnext = copy;
  6501. state.whave = state.wsize;
  6502. }
  6503. else {
  6504. state.wnext += dist;
  6505. if (state.wnext === state.wsize) { state.wnext = 0; }
  6506. if (state.whave < state.wsize) { state.whave += dist; }
  6507. }
  6508. }
  6509. return 0;
  6510. }
  6511.  
  6512. function inflate(strm, flush) {
  6513. var state;
  6514. var input, output; // input/output buffers
  6515. var next; /* next input INDEX */
  6516. var put; /* next output INDEX */
  6517. var have, left; /* available input and output */
  6518. var hold; /* bit buffer */
  6519. var bits; /* bits in bit buffer */
  6520. var _in, _out; /* save starting available input and output */
  6521. var copy; /* number of stored or match bytes to copy */
  6522. var from; /* where to copy match bytes from */
  6523. var from_source;
  6524. var here = 0; /* current decoding table entry */
  6525. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  6526. //var last; /* parent table entry */
  6527. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  6528. var len; /* length to copy for repeats, bits to drop */
  6529. var ret; /* return code */
  6530. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  6531. var opts;
  6532.  
  6533. var n; // temporary var for NEED_BITS
  6534.  
  6535. var order = /* permutation of code lengths */
  6536. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  6537.  
  6538.  
  6539. if (!strm || !strm.state || !strm.output ||
  6540. (!strm.input && strm.avail_in !== 0)) {
  6541. return Z_STREAM_ERROR;
  6542. }
  6543.  
  6544. state = strm.state;
  6545. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  6546.  
  6547.  
  6548. //--- LOAD() ---
  6549. put = strm.next_out;
  6550. output = strm.output;
  6551. left = strm.avail_out;
  6552. next = strm.next_in;
  6553. input = strm.input;
  6554. have = strm.avail_in;
  6555. hold = state.hold;
  6556. bits = state.bits;
  6557. //---
  6558.  
  6559. _in = have;
  6560. _out = left;
  6561. ret = Z_OK;
  6562.  
  6563. inf_leave: // goto emulation
  6564. for (;;) {
  6565. switch (state.mode) {
  6566. case HEAD:
  6567. if (state.wrap === 0) {
  6568. state.mode = TYPEDO;
  6569. break;
  6570. }
  6571. //=== NEEDBITS(16);
  6572. while (bits < 16) {
  6573. if (have === 0) { break inf_leave; }
  6574. have--;
  6575. hold += input[next++] << bits;
  6576. bits += 8;
  6577. }
  6578. //===//
  6579. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  6580. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  6581. //=== CRC2(state.check, hold);
  6582. hbuf[0] = hold & 0xff;
  6583. hbuf[1] = (hold >>> 8) & 0xff;
  6584. state.check = crc32(state.check, hbuf, 2, 0);
  6585. //===//
  6586.  
  6587. //=== INITBITS();
  6588. hold = 0;
  6589. bits = 0;
  6590. //===//
  6591. state.mode = FLAGS;
  6592. break;
  6593. }
  6594. state.flags = 0; /* expect zlib header */
  6595. if (state.head) {
  6596. state.head.done = false;
  6597. }
  6598. if (!(state.wrap & 1) || /* check if zlib header allowed */
  6599. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  6600. strm.msg = 'incorrect header check';
  6601. state.mode = BAD;
  6602. break;
  6603. }
  6604. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  6605. strm.msg = 'unknown compression method';
  6606. state.mode = BAD;
  6607. break;
  6608. }
  6609. //--- DROPBITS(4) ---//
  6610. hold >>>= 4;
  6611. bits -= 4;
  6612. //---//
  6613. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  6614. if (state.wbits === 0) {
  6615. state.wbits = len;
  6616. }
  6617. else if (len > state.wbits) {
  6618. strm.msg = 'invalid window size';
  6619. state.mode = BAD;
  6620. break;
  6621. }
  6622. state.dmax = 1 << len;
  6623. //Tracev((stderr, "inflate: zlib header ok\n"));
  6624. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  6625. state.mode = hold & 0x200 ? DICTID : TYPE;
  6626. //=== INITBITS();
  6627. hold = 0;
  6628. bits = 0;
  6629. //===//
  6630. break;
  6631. case FLAGS:
  6632. //=== NEEDBITS(16); */
  6633. while (bits < 16) {
  6634. if (have === 0) { break inf_leave; }
  6635. have--;
  6636. hold += input[next++] << bits;
  6637. bits += 8;
  6638. }
  6639. //===//
  6640. state.flags = hold;
  6641. if ((state.flags & 0xff) !== Z_DEFLATED) {
  6642. strm.msg = 'unknown compression method';
  6643. state.mode = BAD;
  6644. break;
  6645. }
  6646. if (state.flags & 0xe000) {
  6647. strm.msg = 'unknown header flags set';
  6648. state.mode = BAD;
  6649. break;
  6650. }
  6651. if (state.head) {
  6652. state.head.text = ((hold >> 8) & 1);
  6653. }
  6654. if (state.flags & 0x0200) {
  6655. //=== CRC2(state.check, hold);
  6656. hbuf[0] = hold & 0xff;
  6657. hbuf[1] = (hold >>> 8) & 0xff;
  6658. state.check = crc32(state.check, hbuf, 2, 0);
  6659. //===//
  6660. }
  6661. //=== INITBITS();
  6662. hold = 0;
  6663. bits = 0;
  6664. //===//
  6665. state.mode = TIME;
  6666. /* falls through */
  6667. case TIME:
  6668. //=== NEEDBITS(32); */
  6669. while (bits < 32) {
  6670. if (have === 0) { break inf_leave; }
  6671. have--;
  6672. hold += input[next++] << bits;
  6673. bits += 8;
  6674. }
  6675. //===//
  6676. if (state.head) {
  6677. state.head.time = hold;
  6678. }
  6679. if (state.flags & 0x0200) {
  6680. //=== CRC4(state.check, hold)
  6681. hbuf[0] = hold & 0xff;
  6682. hbuf[1] = (hold >>> 8) & 0xff;
  6683. hbuf[2] = (hold >>> 16) & 0xff;
  6684. hbuf[3] = (hold >>> 24) & 0xff;
  6685. state.check = crc32(state.check, hbuf, 4, 0);
  6686. //===
  6687. }
  6688. //=== INITBITS();
  6689. hold = 0;
  6690. bits = 0;
  6691. //===//
  6692. state.mode = OS;
  6693. /* falls through */
  6694. case OS:
  6695. //=== NEEDBITS(16); */
  6696. while (bits < 16) {
  6697. if (have === 0) { break inf_leave; }
  6698. have--;
  6699. hold += input[next++] << bits;
  6700. bits += 8;
  6701. }
  6702. //===//
  6703. if (state.head) {
  6704. state.head.xflags = (hold & 0xff);
  6705. state.head.os = (hold >> 8);
  6706. }
  6707. if (state.flags & 0x0200) {
  6708. //=== CRC2(state.check, hold);
  6709. hbuf[0] = hold & 0xff;
  6710. hbuf[1] = (hold >>> 8) & 0xff;
  6711. state.check = crc32(state.check, hbuf, 2, 0);
  6712. //===//
  6713. }
  6714. //=== INITBITS();
  6715. hold = 0;
  6716. bits = 0;
  6717. //===//
  6718. state.mode = EXLEN;
  6719. /* falls through */
  6720. case EXLEN:
  6721. if (state.flags & 0x0400) {
  6722. //=== NEEDBITS(16); */
  6723. while (bits < 16) {
  6724. if (have === 0) { break inf_leave; }
  6725. have--;
  6726. hold += input[next++] << bits;
  6727. bits += 8;
  6728. }
  6729. //===//
  6730. state.length = hold;
  6731. if (state.head) {
  6732. state.head.extra_len = hold;
  6733. }
  6734. if (state.flags & 0x0200) {
  6735. //=== CRC2(state.check, hold);
  6736. hbuf[0] = hold & 0xff;
  6737. hbuf[1] = (hold >>> 8) & 0xff;
  6738. state.check = crc32(state.check, hbuf, 2, 0);
  6739. //===//
  6740. }
  6741. //=== INITBITS();
  6742. hold = 0;
  6743. bits = 0;
  6744. //===//
  6745. }
  6746. else if (state.head) {
  6747. state.head.extra = null/*Z_NULL*/;
  6748. }
  6749. state.mode = EXTRA;
  6750. /* falls through */
  6751. case EXTRA:
  6752. if (state.flags & 0x0400) {
  6753. copy = state.length;
  6754. if (copy > have) { copy = have; }
  6755. if (copy) {
  6756. if (state.head) {
  6757. len = state.head.extra_len - state.length;
  6758. if (!state.head.extra) {
  6759. // Use untyped array for more conveniend processing later
  6760. state.head.extra = new Array(state.head.extra_len);
  6761. }
  6762. utils.arraySet(
  6763. state.head.extra,
  6764. input,
  6765. next,
  6766. // extra field is limited to 65536 bytes
  6767. // - no need for additional size check
  6768. copy,
  6769. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  6770. len
  6771. );
  6772. //zmemcpy(state.head.extra + len, next,
  6773. // len + copy > state.head.extra_max ?
  6774. // state.head.extra_max - len : copy);
  6775. }
  6776. if (state.flags & 0x0200) {
  6777. state.check = crc32(state.check, input, copy, next);
  6778. }
  6779. have -= copy;
  6780. next += copy;
  6781. state.length -= copy;
  6782. }
  6783. if (state.length) { break inf_leave; }
  6784. }
  6785. state.length = 0;
  6786. state.mode = NAME;
  6787. /* falls through */
  6788. case NAME:
  6789. if (state.flags & 0x0800) {
  6790. if (have === 0) { break inf_leave; }
  6791. copy = 0;
  6792. do {
  6793. // TODO: 2 or 1 bytes?
  6794. len = input[next + copy++];
  6795. /* use constant limit because in js we should not preallocate memory */
  6796. if (state.head && len &&
  6797. (state.length < 65536 /*state.head.name_max*/)) {
  6798. state.head.name += String.fromCharCode(len);
  6799. }
  6800. } while (len && copy < have);
  6801.  
  6802. if (state.flags & 0x0200) {
  6803. state.check = crc32(state.check, input, copy, next);
  6804. }
  6805. have -= copy;
  6806. next += copy;
  6807. if (len) { break inf_leave; }
  6808. }
  6809. else if (state.head) {
  6810. state.head.name = null;
  6811. }
  6812. state.length = 0;
  6813. state.mode = COMMENT;
  6814. /* falls through */
  6815. case COMMENT:
  6816. if (state.flags & 0x1000) {
  6817. if (have === 0) { break inf_leave; }
  6818. copy = 0;
  6819. do {
  6820. len = input[next + copy++];
  6821. /* use constant limit because in js we should not preallocate memory */
  6822. if (state.head && len &&
  6823. (state.length < 65536 /*state.head.comm_max*/)) {
  6824. state.head.comment += String.fromCharCode(len);
  6825. }
  6826. } while (len && copy < have);
  6827. if (state.flags & 0x0200) {
  6828. state.check = crc32(state.check, input, copy, next);
  6829. }
  6830. have -= copy;
  6831. next += copy;
  6832. if (len) { break inf_leave; }
  6833. }
  6834. else if (state.head) {
  6835. state.head.comment = null;
  6836. }
  6837. state.mode = HCRC;
  6838. /* falls through */
  6839. case HCRC:
  6840. if (state.flags & 0x0200) {
  6841. //=== NEEDBITS(16); */
  6842. while (bits < 16) {
  6843. if (have === 0) { break inf_leave; }
  6844. have--;
  6845. hold += input[next++] << bits;
  6846. bits += 8;
  6847. }
  6848. //===//
  6849. if (hold !== (state.check & 0xffff)) {
  6850. strm.msg = 'header crc mismatch';
  6851. state.mode = BAD;
  6852. break;
  6853. }
  6854. //=== INITBITS();
  6855. hold = 0;
  6856. bits = 0;
  6857. //===//
  6858. }
  6859. if (state.head) {
  6860. state.head.hcrc = ((state.flags >> 9) & 1);
  6861. state.head.done = true;
  6862. }
  6863. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  6864. state.mode = TYPE;
  6865. break;
  6866. case DICTID:
  6867. //=== NEEDBITS(32); */
  6868. while (bits < 32) {
  6869. if (have === 0) { break inf_leave; }
  6870. have--;
  6871. hold += input[next++] << bits;
  6872. bits += 8;
  6873. }
  6874. //===//
  6875. strm.adler = state.check = ZSWAP32(hold);
  6876. //=== INITBITS();
  6877. hold = 0;
  6878. bits = 0;
  6879. //===//
  6880. state.mode = DICT;
  6881. /* falls through */
  6882. case DICT:
  6883. if (state.havedict === 0) {
  6884. //--- RESTORE() ---
  6885. strm.next_out = put;
  6886. strm.avail_out = left;
  6887. strm.next_in = next;
  6888. strm.avail_in = have;
  6889. state.hold = hold;
  6890. state.bits = bits;
  6891. //---
  6892. return Z_NEED_DICT;
  6893. }
  6894. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  6895. state.mode = TYPE;
  6896. /* falls through */
  6897. case TYPE:
  6898. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  6899. /* falls through */
  6900. case TYPEDO:
  6901. if (state.last) {
  6902. //--- BYTEBITS() ---//
  6903. hold >>>= bits & 7;
  6904. bits -= bits & 7;
  6905. //---//
  6906. state.mode = CHECK;
  6907. break;
  6908. }
  6909. //=== NEEDBITS(3); */
  6910. while (bits < 3) {
  6911. if (have === 0) { break inf_leave; }
  6912. have--;
  6913. hold += input[next++] << bits;
  6914. bits += 8;
  6915. }
  6916. //===//
  6917. state.last = (hold & 0x01)/*BITS(1)*/;
  6918. //--- DROPBITS(1) ---//
  6919. hold >>>= 1;
  6920. bits -= 1;
  6921. //---//
  6922.  
  6923. switch ((hold & 0x03)/*BITS(2)*/) {
  6924. case 0: /* stored block */
  6925. //Tracev((stderr, "inflate: stored block%s\n",
  6926. // state.last ? " (last)" : ""));
  6927. state.mode = STORED;
  6928. break;
  6929. case 1: /* fixed block */
  6930. fixedtables(state);
  6931. //Tracev((stderr, "inflate: fixed codes block%s\n",
  6932. // state.last ? " (last)" : ""));
  6933. state.mode = LEN_; /* decode codes */
  6934. if (flush === Z_TREES) {
  6935. //--- DROPBITS(2) ---//
  6936. hold >>>= 2;
  6937. bits -= 2;
  6938. //---//
  6939. break inf_leave;
  6940. }
  6941. break;
  6942. case 2: /* dynamic block */
  6943. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  6944. // state.last ? " (last)" : ""));
  6945. state.mode = TABLE;
  6946. break;
  6947. case 3:
  6948. strm.msg = 'invalid block type';
  6949. state.mode = BAD;
  6950. }
  6951. //--- DROPBITS(2) ---//
  6952. hold >>>= 2;
  6953. bits -= 2;
  6954. //---//
  6955. break;
  6956. case STORED:
  6957. //--- BYTEBITS() ---// /* go to byte boundary */
  6958. hold >>>= bits & 7;
  6959. bits -= bits & 7;
  6960. //---//
  6961. //=== NEEDBITS(32); */
  6962. while (bits < 32) {
  6963. if (have === 0) { break inf_leave; }
  6964. have--;
  6965. hold += input[next++] << bits;
  6966. bits += 8;
  6967. }
  6968. //===//
  6969. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  6970. strm.msg = 'invalid stored block lengths';
  6971. state.mode = BAD;
  6972. break;
  6973. }
  6974. state.length = hold & 0xffff;
  6975. //Tracev((stderr, "inflate: stored length %u\n",
  6976. // state.length));
  6977. //=== INITBITS();
  6978. hold = 0;
  6979. bits = 0;
  6980. //===//
  6981. state.mode = COPY_;
  6982. if (flush === Z_TREES) { break inf_leave; }
  6983. /* falls through */
  6984. case COPY_:
  6985. state.mode = COPY;
  6986. /* falls through */
  6987. case COPY:
  6988. copy = state.length;
  6989. if (copy) {
  6990. if (copy > have) { copy = have; }
  6991. if (copy > left) { copy = left; }
  6992. if (copy === 0) { break inf_leave; }
  6993. //--- zmemcpy(put, next, copy); ---
  6994. utils.arraySet(output, input, next, copy, put);
  6995. //---//
  6996. have -= copy;
  6997. next += copy;
  6998. left -= copy;
  6999. put += copy;
  7000. state.length -= copy;
  7001. break;
  7002. }
  7003. //Tracev((stderr, "inflate: stored end\n"));
  7004. state.mode = TYPE;
  7005. break;
  7006. case TABLE:
  7007. //=== NEEDBITS(14); */
  7008. while (bits < 14) {
  7009. if (have === 0) { break inf_leave; }
  7010. have--;
  7011. hold += input[next++] << bits;
  7012. bits += 8;
  7013. }
  7014. //===//
  7015. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  7016. //--- DROPBITS(5) ---//
  7017. hold >>>= 5;
  7018. bits -= 5;
  7019. //---//
  7020. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  7021. //--- DROPBITS(5) ---//
  7022. hold >>>= 5;
  7023. bits -= 5;
  7024. //---//
  7025. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  7026. //--- DROPBITS(4) ---//
  7027. hold >>>= 4;
  7028. bits -= 4;
  7029. //---//
  7030. //#ifndef PKZIP_BUG_WORKAROUND
  7031. if (state.nlen > 286 || state.ndist > 30) {
  7032. strm.msg = 'too many length or distance symbols';
  7033. state.mode = BAD;
  7034. break;
  7035. }
  7036. //#endif
  7037. //Tracev((stderr, "inflate: table sizes ok\n"));
  7038. state.have = 0;
  7039. state.mode = LENLENS;
  7040. /* falls through */
  7041. case LENLENS:
  7042. while (state.have < state.ncode) {
  7043. //=== NEEDBITS(3);
  7044. while (bits < 3) {
  7045. if (have === 0) { break inf_leave; }
  7046. have--;
  7047. hold += input[next++] << bits;
  7048. bits += 8;
  7049. }
  7050. //===//
  7051. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  7052. //--- DROPBITS(3) ---//
  7053. hold >>>= 3;
  7054. bits -= 3;
  7055. //---//
  7056. }
  7057. while (state.have < 19) {
  7058. state.lens[order[state.have++]] = 0;
  7059. }
  7060. // We have separate tables & no pointers. 2 commented lines below not needed.
  7061. //state.next = state.codes;
  7062. //state.lencode = state.next;
  7063. // Switch to use dynamic table
  7064. state.lencode = state.lendyn;
  7065. state.lenbits = 7;
  7066.  
  7067. opts = {bits: state.lenbits};
  7068. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  7069. state.lenbits = opts.bits;
  7070.  
  7071. if (ret) {
  7072. strm.msg = 'invalid code lengths set';
  7073. state.mode = BAD;
  7074. break;
  7075. }
  7076. //Tracev((stderr, "inflate: code lengths ok\n"));
  7077. state.have = 0;
  7078. state.mode = CODELENS;
  7079. /* falls through */
  7080. case CODELENS:
  7081. while (state.have < state.nlen + state.ndist) {
  7082. for (;;) {
  7083. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  7084. here_bits = here >>> 24;
  7085. here_op = (here >>> 16) & 0xff;
  7086. here_val = here & 0xffff;
  7087.  
  7088. if ((here_bits) <= bits) { break; }
  7089. //--- PULLBYTE() ---//
  7090. if (have === 0) { break inf_leave; }
  7091. have--;
  7092. hold += input[next++] << bits;
  7093. bits += 8;
  7094. //---//
  7095. }
  7096. if (here_val < 16) {
  7097. //--- DROPBITS(here.bits) ---//
  7098. hold >>>= here_bits;
  7099. bits -= here_bits;
  7100. //---//
  7101. state.lens[state.have++] = here_val;
  7102. }
  7103. else {
  7104. if (here_val === 16) {
  7105. //=== NEEDBITS(here.bits + 2);
  7106. n = here_bits + 2;
  7107. while (bits < n) {
  7108. if (have === 0) { break inf_leave; }
  7109. have--;
  7110. hold += input[next++] << bits;
  7111. bits += 8;
  7112. }
  7113. //===//
  7114. //--- DROPBITS(here.bits) ---//
  7115. hold >>>= here_bits;
  7116. bits -= here_bits;
  7117. //---//
  7118. if (state.have === 0) {
  7119. strm.msg = 'invalid bit length repeat';
  7120. state.mode = BAD;
  7121. break;
  7122. }
  7123. len = state.lens[state.have - 1];
  7124. copy = 3 + (hold & 0x03);//BITS(2);
  7125. //--- DROPBITS(2) ---//
  7126. hold >>>= 2;
  7127. bits -= 2;
  7128. //---//
  7129. }
  7130. else if (here_val === 17) {
  7131. //=== NEEDBITS(here.bits + 3);
  7132. n = here_bits + 3;
  7133. while (bits < n) {
  7134. if (have === 0) { break inf_leave; }
  7135. have--;
  7136. hold += input[next++] << bits;
  7137. bits += 8;
  7138. }
  7139. //===//
  7140. //--- DROPBITS(here.bits) ---//
  7141. hold >>>= here_bits;
  7142. bits -= here_bits;
  7143. //---//
  7144. len = 0;
  7145. copy = 3 + (hold & 0x07);//BITS(3);
  7146. //--- DROPBITS(3) ---//
  7147. hold >>>= 3;
  7148. bits -= 3;
  7149. //---//
  7150. }
  7151. else {
  7152. //=== NEEDBITS(here.bits + 7);
  7153. n = here_bits + 7;
  7154. while (bits < n) {
  7155. if (have === 0) { break inf_leave; }
  7156. have--;
  7157. hold += input[next++] << bits;
  7158. bits += 8;
  7159. }
  7160. //===//
  7161. //--- DROPBITS(here.bits) ---//
  7162. hold >>>= here_bits;
  7163. bits -= here_bits;
  7164. //---//
  7165. len = 0;
  7166. copy = 11 + (hold & 0x7f);//BITS(7);
  7167. //--- DROPBITS(7) ---//
  7168. hold >>>= 7;
  7169. bits -= 7;
  7170. //---//
  7171. }
  7172. if (state.have + copy > state.nlen + state.ndist) {
  7173. strm.msg = 'invalid bit length repeat';
  7174. state.mode = BAD;
  7175. break;
  7176. }
  7177. while (copy--) {
  7178. state.lens[state.have++] = len;
  7179. }
  7180. }
  7181. }
  7182.  
  7183. /* handle error breaks in while */
  7184. if (state.mode === BAD) { break; }
  7185.  
  7186. /* check for end-of-block code (better have one) */
  7187. if (state.lens[256] === 0) {
  7188. strm.msg = 'invalid code -- missing end-of-block';
  7189. state.mode = BAD;
  7190. break;
  7191. }
  7192.  
  7193. /* build code tables -- note: do not change the lenbits or distbits
  7194. values here (9 and 6) without reading the comments in inftrees.h
  7195. concerning the ENOUGH constants, which depend on those values */
  7196. state.lenbits = 9;
  7197.  
  7198. opts = {bits: state.lenbits};
  7199. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  7200. // We have separate tables & no pointers. 2 commented lines below not needed.
  7201. // state.next_index = opts.table_index;
  7202. state.lenbits = opts.bits;
  7203. // state.lencode = state.next;
  7204.  
  7205. if (ret) {
  7206. strm.msg = 'invalid literal/lengths set';
  7207. state.mode = BAD;
  7208. break;
  7209. }
  7210.  
  7211. state.distbits = 6;
  7212. //state.distcode.copy(state.codes);
  7213. // Switch to use dynamic table
  7214. state.distcode = state.distdyn;
  7215. opts = {bits: state.distbits};
  7216. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  7217. // We have separate tables & no pointers. 2 commented lines below not needed.
  7218. // state.next_index = opts.table_index;
  7219. state.distbits = opts.bits;
  7220. // state.distcode = state.next;
  7221.  
  7222. if (ret) {
  7223. strm.msg = 'invalid distances set';
  7224. state.mode = BAD;
  7225. break;
  7226. }
  7227. //Tracev((stderr, 'inflate: codes ok\n'));
  7228. state.mode = LEN_;
  7229. if (flush === Z_TREES) { break inf_leave; }
  7230. /* falls through */
  7231. case LEN_:
  7232. state.mode = LEN;
  7233. /* falls through */
  7234. case LEN:
  7235. if (have >= 6 && left >= 258) {
  7236. //--- RESTORE() ---
  7237. strm.next_out = put;
  7238. strm.avail_out = left;
  7239. strm.next_in = next;
  7240. strm.avail_in = have;
  7241. state.hold = hold;
  7242. state.bits = bits;
  7243. //---
  7244. inflate_fast(strm, _out);
  7245. //--- LOAD() ---
  7246. put = strm.next_out;
  7247. output = strm.output;
  7248. left = strm.avail_out;
  7249. next = strm.next_in;
  7250. input = strm.input;
  7251. have = strm.avail_in;
  7252. hold = state.hold;
  7253. bits = state.bits;
  7254. //---
  7255.  
  7256. if (state.mode === TYPE) {
  7257. state.back = -1;
  7258. }
  7259. break;
  7260. }
  7261. state.back = 0;
  7262. for (;;) {
  7263. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  7264. here_bits = here >>> 24;
  7265. here_op = (here >>> 16) & 0xff;
  7266. here_val = here & 0xffff;
  7267.  
  7268. if (here_bits <= bits) { break; }
  7269. //--- PULLBYTE() ---//
  7270. if (have === 0) { break inf_leave; }
  7271. have--;
  7272. hold += input[next++] << bits;
  7273. bits += 8;
  7274. //---//
  7275. }
  7276. if (here_op && (here_op & 0xf0) === 0) {
  7277. last_bits = here_bits;
  7278. last_op = here_op;
  7279. last_val = here_val;
  7280. for (;;) {
  7281. here = state.lencode[last_val +
  7282. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  7283. here_bits = here >>> 24;
  7284. here_op = (here >>> 16) & 0xff;
  7285. here_val = here & 0xffff;
  7286.  
  7287. if ((last_bits + here_bits) <= bits) { break; }
  7288. //--- PULLBYTE() ---//
  7289. if (have === 0) { break inf_leave; }
  7290. have--;
  7291. hold += input[next++] << bits;
  7292. bits += 8;
  7293. //---//
  7294. }
  7295. //--- DROPBITS(last.bits) ---//
  7296. hold >>>= last_bits;
  7297. bits -= last_bits;
  7298. //---//
  7299. state.back += last_bits;
  7300. }
  7301. //--- DROPBITS(here.bits) ---//
  7302. hold >>>= here_bits;
  7303. bits -= here_bits;
  7304. //---//
  7305. state.back += here_bits;
  7306. state.length = here_val;
  7307. if (here_op === 0) {
  7308. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  7309. // "inflate: literal '%c'\n" :
  7310. // "inflate: literal 0x%02x\n", here.val));
  7311. state.mode = LIT;
  7312. break;
  7313. }
  7314. if (here_op & 32) {
  7315. //Tracevv((stderr, "inflate: end of block\n"));
  7316. state.back = -1;
  7317. state.mode = TYPE;
  7318. break;
  7319. }
  7320. if (here_op & 64) {
  7321. strm.msg = 'invalid literal/length code';
  7322. state.mode = BAD;
  7323. break;
  7324. }
  7325. state.extra = here_op & 15;
  7326. state.mode = LENEXT;
  7327. /* falls through */
  7328. case LENEXT:
  7329. if (state.extra) {
  7330. //=== NEEDBITS(state.extra);
  7331. n = state.extra;
  7332. while (bits < n) {
  7333. if (have === 0) { break inf_leave; }
  7334. have--;
  7335. hold += input[next++] << bits;
  7336. bits += 8;
  7337. }
  7338. //===//
  7339. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  7340. //--- DROPBITS(state.extra) ---//
  7341. hold >>>= state.extra;
  7342. bits -= state.extra;
  7343. //---//
  7344. state.back += state.extra;
  7345. }
  7346. //Tracevv((stderr, "inflate: length %u\n", state.length));
  7347. state.was = state.length;
  7348. state.mode = DIST;
  7349. /* falls through */
  7350. case DIST:
  7351. for (;;) {
  7352. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  7353. here_bits = here >>> 24;
  7354. here_op = (here >>> 16) & 0xff;
  7355. here_val = here & 0xffff;
  7356.  
  7357. if ((here_bits) <= bits) { break; }
  7358. //--- PULLBYTE() ---//
  7359. if (have === 0) { break inf_leave; }
  7360. have--;
  7361. hold += input[next++] << bits;
  7362. bits += 8;
  7363. //---//
  7364. }
  7365. if ((here_op & 0xf0) === 0) {
  7366. last_bits = here_bits;
  7367. last_op = here_op;
  7368. last_val = here_val;
  7369. for (;;) {
  7370. here = state.distcode[last_val +
  7371. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  7372. here_bits = here >>> 24;
  7373. here_op = (here >>> 16) & 0xff;
  7374. here_val = here & 0xffff;
  7375.  
  7376. if ((last_bits + here_bits) <= bits) { break; }
  7377. //--- PULLBYTE() ---//
  7378. if (have === 0) { break inf_leave; }
  7379. have--;
  7380. hold += input[next++] << bits;
  7381. bits += 8;
  7382. //---//
  7383. }
  7384. //--- DROPBITS(last.bits) ---//
  7385. hold >>>= last_bits;
  7386. bits -= last_bits;
  7387. //---//
  7388. state.back += last_bits;
  7389. }
  7390. //--- DROPBITS(here.bits) ---//
  7391. hold >>>= here_bits;
  7392. bits -= here_bits;
  7393. //---//
  7394. state.back += here_bits;
  7395. if (here_op & 64) {
  7396. strm.msg = 'invalid distance code';
  7397. state.mode = BAD;
  7398. break;
  7399. }
  7400. state.offset = here_val;
  7401. state.extra = (here_op) & 15;
  7402. state.mode = DISTEXT;
  7403. /* falls through */
  7404. case DISTEXT:
  7405. if (state.extra) {
  7406. //=== NEEDBITS(state.extra);
  7407. n = state.extra;
  7408. while (bits < n) {
  7409. if (have === 0) { break inf_leave; }
  7410. have--;
  7411. hold += input[next++] << bits;
  7412. bits += 8;
  7413. }
  7414. //===//
  7415. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  7416. //--- DROPBITS(state.extra) ---//
  7417. hold >>>= state.extra;
  7418. bits -= state.extra;
  7419. //---//
  7420. state.back += state.extra;
  7421. }
  7422. //#ifdef INFLATE_STRICT
  7423. if (state.offset > state.dmax) {
  7424. strm.msg = 'invalid distance too far back';
  7425. state.mode = BAD;
  7426. break;
  7427. }
  7428. //#endif
  7429. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  7430. state.mode = MATCH;
  7431. /* falls through */
  7432. case MATCH:
  7433. if (left === 0) { break inf_leave; }
  7434. copy = _out - left;
  7435. if (state.offset > copy) { /* copy from window */
  7436. copy = state.offset - copy;
  7437. if (copy > state.whave) {
  7438. if (state.sane) {
  7439. strm.msg = 'invalid distance too far back';
  7440. state.mode = BAD;
  7441. break;
  7442. }
  7443. // (!) This block is disabled in zlib defailts,
  7444. // don't enable it for binary compatibility
  7445. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  7446. // Trace((stderr, "inflate.c too far\n"));
  7447. // copy -= state.whave;
  7448. // if (copy > state.length) { copy = state.length; }
  7449. // if (copy > left) { copy = left; }
  7450. // left -= copy;
  7451. // state.length -= copy;
  7452. // do {
  7453. // output[put++] = 0;
  7454. // } while (--copy);
  7455. // if (state.length === 0) { state.mode = LEN; }
  7456. // break;
  7457. //#endif
  7458. }
  7459. if (copy > state.wnext) {
  7460. copy -= state.wnext;
  7461. from = state.wsize - copy;
  7462. }
  7463. else {
  7464. from = state.wnext - copy;
  7465. }
  7466. if (copy > state.length) { copy = state.length; }
  7467. from_source = state.window;
  7468. }
  7469. else { /* copy from output */
  7470. from_source = output;
  7471. from = put - state.offset;
  7472. copy = state.length;
  7473. }
  7474. if (copy > left) { copy = left; }
  7475. left -= copy;
  7476. state.length -= copy;
  7477. do {
  7478. output[put++] = from_source[from++];
  7479. } while (--copy);
  7480. if (state.length === 0) { state.mode = LEN; }
  7481. break;
  7482. case LIT:
  7483. if (left === 0) { break inf_leave; }
  7484. output[put++] = state.length;
  7485. left--;
  7486. state.mode = LEN;
  7487. break;
  7488. case CHECK:
  7489. if (state.wrap) {
  7490. //=== NEEDBITS(32);
  7491. while (bits < 32) {
  7492. if (have === 0) { break inf_leave; }
  7493. have--;
  7494. // Use '|' insdead of '+' to make sure that result is signed
  7495. hold |= input[next++] << bits;
  7496. bits += 8;
  7497. }
  7498. //===//
  7499. _out -= left;
  7500. strm.total_out += _out;
  7501. state.total += _out;
  7502. if (_out) {
  7503. strm.adler = state.check =
  7504. /*UPDATE(state.check, put - _out, _out);*/
  7505. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  7506.  
  7507. }
  7508. _out = left;
  7509. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  7510. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  7511. strm.msg = 'incorrect data check';
  7512. state.mode = BAD;
  7513. break;
  7514. }
  7515. //=== INITBITS();
  7516. hold = 0;
  7517. bits = 0;
  7518. //===//
  7519. //Tracev((stderr, "inflate: check matches trailer\n"));
  7520. }
  7521. state.mode = LENGTH;
  7522. /* falls through */
  7523. case LENGTH:
  7524. if (state.wrap && state.flags) {
  7525. //=== NEEDBITS(32);
  7526. while (bits < 32) {
  7527. if (have === 0) { break inf_leave; }
  7528. have--;
  7529. hold += input[next++] << bits;
  7530. bits += 8;
  7531. }
  7532. //===//
  7533. if (hold !== (state.total & 0xffffffff)) {
  7534. strm.msg = 'incorrect length check';
  7535. state.mode = BAD;
  7536. break;
  7537. }
  7538. //=== INITBITS();
  7539. hold = 0;
  7540. bits = 0;
  7541. //===//
  7542. //Tracev((stderr, "inflate: length matches trailer\n"));
  7543. }
  7544. state.mode = DONE;
  7545. /* falls through */
  7546. case DONE:
  7547. ret = Z_STREAM_END;
  7548. break inf_leave;
  7549. case BAD:
  7550. ret = Z_DATA_ERROR;
  7551. break inf_leave;
  7552. case MEM:
  7553. return Z_MEM_ERROR;
  7554. case SYNC:
  7555. /* falls through */
  7556. default:
  7557. return Z_STREAM_ERROR;
  7558. }
  7559. }
  7560.  
  7561. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  7562.  
  7563. /*
  7564. Return from inflate(), updating the total counts and the check value.
  7565. If there was no progress during the inflate() call, return a buffer
  7566. error. Call updatewindow() to create and/or update the window state.
  7567. Note: a memory error from inflate() is non-recoverable.
  7568. */
  7569.  
  7570. //--- RESTORE() ---
  7571. strm.next_out = put;
  7572. strm.avail_out = left;
  7573. strm.next_in = next;
  7574. strm.avail_in = have;
  7575. state.hold = hold;
  7576. state.bits = bits;
  7577. //---
  7578.  
  7579. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  7580. (state.mode < CHECK || flush !== Z_FINISH))) {
  7581. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  7582. state.mode = MEM;
  7583. return Z_MEM_ERROR;
  7584. }
  7585. }
  7586. _in -= strm.avail_in;
  7587. _out -= strm.avail_out;
  7588. strm.total_in += _in;
  7589. strm.total_out += _out;
  7590. state.total += _out;
  7591. if (state.wrap && _out) {
  7592. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  7593. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  7594. }
  7595. strm.data_type = state.bits + (state.last ? 64 : 0) +
  7596. (state.mode === TYPE ? 128 : 0) +
  7597. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  7598. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  7599. ret = Z_BUF_ERROR;
  7600. }
  7601. return ret;
  7602. }
  7603.  
  7604. function inflateEnd(strm) {
  7605.  
  7606. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  7607. return Z_STREAM_ERROR;
  7608. }
  7609.  
  7610. var state = strm.state;
  7611. if (state.window) {
  7612. state.window = null;
  7613. }
  7614. strm.state = null;
  7615. return Z_OK;
  7616. }
  7617.  
  7618. function inflateGetHeader(strm, head) {
  7619. var state;
  7620.  
  7621. /* check state */
  7622. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7623. state = strm.state;
  7624. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  7625.  
  7626. /* save header structure */
  7627. state.head = head;
  7628. head.done = false;
  7629. return Z_OK;
  7630. }
  7631.  
  7632.  
  7633. exports.inflateReset = inflateReset;
  7634. exports.inflateReset2 = inflateReset2;
  7635. exports.inflateResetKeep = inflateResetKeep;
  7636. exports.inflateInit = inflateInit;
  7637. exports.inflateInit2 = inflateInit2;
  7638. exports.inflate = inflate;
  7639. exports.inflateEnd = inflateEnd;
  7640. exports.inflateGetHeader = inflateGetHeader;
  7641. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  7642.  
  7643. /* Not implemented
  7644. exports.inflateCopy = inflateCopy;
  7645. exports.inflateGetDictionary = inflateGetDictionary;
  7646. exports.inflateMark = inflateMark;
  7647. exports.inflatePrime = inflatePrime;
  7648. exports.inflateSetDictionary = inflateSetDictionary;
  7649. exports.inflateSync = inflateSync;
  7650. exports.inflateSyncPoint = inflateSyncPoint;
  7651. exports.inflateUndermine = inflateUndermine;
  7652. */
  7653. },{"../utils/common":27,"./adler32":29,"./crc32":31,"./inffast":34,"./inftrees":36}],36:[function(_dereq_,module,exports){
  7654. 'use strict';
  7655.  
  7656.  
  7657. var utils = _dereq_('../utils/common');
  7658.  
  7659. var MAXBITS = 15;
  7660. var ENOUGH_LENS = 852;
  7661. var ENOUGH_DISTS = 592;
  7662. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  7663.  
  7664. var CODES = 0;
  7665. var LENS = 1;
  7666. var DISTS = 2;
  7667.  
  7668. var lbase = [ /* Length codes 257..285 base */
  7669. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  7670. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  7671. ];
  7672.  
  7673. var lext = [ /* Length codes 257..285 extra */
  7674. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  7675. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  7676. ];
  7677.  
  7678. var dbase = [ /* Distance codes 0..29 base */
  7679. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  7680. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  7681. 8193, 12289, 16385, 24577, 0, 0
  7682. ];
  7683.  
  7684. var dext = [ /* Distance codes 0..29 extra */
  7685. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  7686. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  7687. 28, 28, 29, 29, 64, 64
  7688. ];
  7689.  
  7690. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  7691. {
  7692. var bits = opts.bits;
  7693. //here = opts.here; /* table entry for duplication */
  7694.  
  7695. var len = 0; /* a code's length in bits */
  7696. var sym = 0; /* index of code symbols */
  7697. var min = 0, max = 0; /* minimum and maximum code lengths */
  7698. var root = 0; /* number of index bits for root table */
  7699. var curr = 0; /* number of index bits for current table */
  7700. var drop = 0; /* code bits to drop for sub-table */
  7701. var left = 0; /* number of prefix codes available */
  7702. var used = 0; /* code entries in table used */
  7703. var huff = 0; /* Huffman code */
  7704. var incr; /* for incrementing code, index */
  7705. var fill; /* index for replicating entries */
  7706. var low; /* low bits for current root entry */
  7707. var mask; /* mask for low root bits */
  7708. var next; /* next available space in table */
  7709. var base = null; /* base value table to use */
  7710. var base_index = 0;
  7711. // var shoextra; /* extra bits table to use */
  7712. var end; /* use base and extra for symbol > end */
  7713. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  7714. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  7715. var extra = null;
  7716. var extra_index = 0;
  7717.  
  7718. var here_bits, here_op, here_val;
  7719.  
  7720. /*
  7721. Process a set of code lengths to create a canonical Huffman code. The
  7722. code lengths are lens[0..codes-1]. Each length corresponds to the
  7723. symbols 0..codes-1. The Huffman code is generated by first sorting the
  7724. symbols by length from short to long, and retaining the symbol order
  7725. for codes with equal lengths. Then the code starts with all zero bits
  7726. for the first code of the shortest length, and the codes are integer
  7727. increments for the same length, and zeros are appended as the length
  7728. increases. For the deflate format, these bits are stored backwards
  7729. from their more natural integer increment ordering, and so when the
  7730. decoding tables are built in the large loop below, the integer codes
  7731. are incremented backwards.
  7732.  
  7733. This routine assumes, but does not check, that all of the entries in
  7734. lens[] are in the range 0..MAXBITS. The caller must assure this.
  7735. 1..MAXBITS is interpreted as that code length. zero means that that
  7736. symbol does not occur in this code.
  7737.  
  7738. The codes are sorted by computing a count of codes for each length,
  7739. creating from that a table of starting indices for each length in the
  7740. sorted table, and then entering the symbols in order in the sorted
  7741. table. The sorted table is work[], with that space being provided by
  7742. the caller.
  7743.  
  7744. The length counts are used for other purposes as well, i.e. finding
  7745. the minimum and maximum length codes, determining if there are any
  7746. codes at all, checking for a valid set of lengths, and looking ahead
  7747. at length counts to determine sub-table sizes when building the
  7748. decoding tables.
  7749. */
  7750.  
  7751. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  7752. for (len = 0; len <= MAXBITS; len++) {
  7753. count[len] = 0;
  7754. }
  7755. for (sym = 0; sym < codes; sym++) {
  7756. count[lens[lens_index + sym]]++;
  7757. }
  7758.  
  7759. /* bound code lengths, force root to be within code lengths */
  7760. root = bits;
  7761. for (max = MAXBITS; max >= 1; max--) {
  7762. if (count[max] !== 0) { break; }
  7763. }
  7764. if (root > max) {
  7765. root = max;
  7766. }
  7767. if (max === 0) { /* no symbols to code at all */
  7768. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  7769. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  7770. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  7771. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  7772.  
  7773.  
  7774. //table.op[opts.table_index] = 64;
  7775. //table.bits[opts.table_index] = 1;
  7776. //table.val[opts.table_index++] = 0;
  7777. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  7778.  
  7779. opts.bits = 1;
  7780. return 0; /* no symbols, but wait for decoding to report error */
  7781. }
  7782. for (min = 1; min < max; min++) {
  7783. if (count[min] !== 0) { break; }
  7784. }
  7785. if (root < min) {
  7786. root = min;
  7787. }
  7788.  
  7789. /* check for an over-subscribed or incomplete set of lengths */
  7790. left = 1;
  7791. for (len = 1; len <= MAXBITS; len++) {
  7792. left <<= 1;
  7793. left -= count[len];
  7794. if (left < 0) {
  7795. return -1;
  7796. } /* over-subscribed */
  7797. }
  7798. if (left > 0 && (type === CODES || max !== 1)) {
  7799. return -1; /* incomplete set */
  7800. }
  7801.  
  7802. /* generate offsets into symbol table for each length for sorting */
  7803. offs[1] = 0;
  7804. for (len = 1; len < MAXBITS; len++) {
  7805. offs[len + 1] = offs[len] + count[len];
  7806. }
  7807.  
  7808. /* sort symbols by length, by symbol order within each length */
  7809. for (sym = 0; sym < codes; sym++) {
  7810. if (lens[lens_index + sym] !== 0) {
  7811. work[offs[lens[lens_index + sym]]++] = sym;
  7812. }
  7813. }
  7814.  
  7815. /*
  7816. Create and fill in decoding tables. In this loop, the table being
  7817. filled is at next and has curr index bits. The code being used is huff
  7818. with length len. That code is converted to an index by dropping drop
  7819. bits off of the bottom. For codes where len is less than drop + curr,
  7820. those top drop + curr - len bits are incremented through all values to
  7821. fill the table with replicated entries.
  7822.  
  7823. root is the number of index bits for the root table. When len exceeds
  7824. root, sub-tables are created pointed to by the root entry with an index
  7825. of the low root bits of huff. This is saved in low to check for when a
  7826. new sub-table should be started. drop is zero when the root table is
  7827. being filled, and drop is root when sub-tables are being filled.
  7828.  
  7829. When a new sub-table is needed, it is necessary to look ahead in the
  7830. code lengths to determine what size sub-table is needed. The length
  7831. counts are used for this, and so count[] is decremented as codes are
  7832. entered in the tables.
  7833.  
  7834. used keeps track of how many table entries have been allocated from the
  7835. provided *table space. It is checked for LENS and DIST tables against
  7836. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  7837. the initial root table size constants. See the comments in inftrees.h
  7838. for more information.
  7839.  
  7840. sym increments through all symbols, and the loop terminates when
  7841. all codes of length max, i.e. all codes, have been processed. This
  7842. routine permits incomplete codes, so another loop after this one fills
  7843. in the rest of the decoding tables with invalid code markers.
  7844. */
  7845.  
  7846. /* set up for code type */
  7847. // poor man optimization - use if-else instead of switch,
  7848. // to avoid deopts in old v8
  7849. if (type === CODES) {
  7850. base = extra = work; /* dummy value--not used */
  7851. end = 19;
  7852. } else if (type === LENS) {
  7853. base = lbase;
  7854. base_index -= 257;
  7855. extra = lext;
  7856. extra_index -= 257;
  7857. end = 256;
  7858. } else { /* DISTS */
  7859. base = dbase;
  7860. extra = dext;
  7861. end = -1;
  7862. }
  7863.  
  7864. /* initialize opts for loop */
  7865. huff = 0; /* starting code */
  7866. sym = 0; /* starting code symbol */
  7867. len = min; /* starting code length */
  7868. next = table_index; /* current table to fill in */
  7869. curr = root; /* current table index bits */
  7870. drop = 0; /* current bits to drop from code for index */
  7871. low = -1; /* trigger new sub-table when len > root */
  7872. used = 1 << root; /* use root table entries */
  7873. mask = used - 1; /* mask for comparing low */
  7874.  
  7875. /* check available table space */
  7876. if ((type === LENS && used > ENOUGH_LENS) ||
  7877. (type === DISTS && used > ENOUGH_DISTS)) {
  7878. return 1;
  7879. }
  7880.  
  7881. var i=0;
  7882. /* process all codes and make table entries */
  7883. for (;;) {
  7884. i++;
  7885. /* create table entry */
  7886. here_bits = len - drop;
  7887. if (work[sym] < end) {
  7888. here_op = 0;
  7889. here_val = work[sym];
  7890. }
  7891. else if (work[sym] > end) {
  7892. here_op = extra[extra_index + work[sym]];
  7893. here_val = base[base_index + work[sym]];
  7894. }
  7895. else {
  7896. here_op = 32 + 64; /* end of block */
  7897. here_val = 0;
  7898. }
  7899.  
  7900. /* replicate for those indices with low len bits equal to huff */
  7901. incr = 1 << (len - drop);
  7902. fill = 1 << curr;
  7903. min = fill; /* save offset to next table */
  7904. do {
  7905. fill -= incr;
  7906. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  7907. } while (fill !== 0);
  7908.  
  7909. /* backwards increment the len-bit code huff */
  7910. incr = 1 << (len - 1);
  7911. while (huff & incr) {
  7912. incr >>= 1;
  7913. }
  7914. if (incr !== 0) {
  7915. huff &= incr - 1;
  7916. huff += incr;
  7917. } else {
  7918. huff = 0;
  7919. }
  7920.  
  7921. /* go to next symbol, update count, len */
  7922. sym++;
  7923. if (--count[len] === 0) {
  7924. if (len === max) { break; }
  7925. len = lens[lens_index + work[sym]];
  7926. }
  7927.  
  7928. /* create new sub-table if needed */
  7929. if (len > root && (huff & mask) !== low) {
  7930. /* if first time, transition to sub-tables */
  7931. if (drop === 0) {
  7932. drop = root;
  7933. }
  7934.  
  7935. /* increment past last table */
  7936. next += min; /* here min is 1 << curr */
  7937.  
  7938. /* determine length of next table */
  7939. curr = len - drop;
  7940. left = 1 << curr;
  7941. while (curr + drop < max) {
  7942. left -= count[curr + drop];
  7943. if (left <= 0) { break; }
  7944. curr++;
  7945. left <<= 1;
  7946. }
  7947.  
  7948. /* check for enough space */
  7949. used += 1 << curr;
  7950. if ((type === LENS && used > ENOUGH_LENS) ||
  7951. (type === DISTS && used > ENOUGH_DISTS)) {
  7952. return 1;
  7953. }
  7954.  
  7955. /* point entry in root table to sub-table */
  7956. low = huff & mask;
  7957. /*table.op[low] = curr;
  7958. table.bits[low] = root;
  7959. table.val[low] = next - opts.table_index;*/
  7960. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  7961. }
  7962. }
  7963.  
  7964. /* fill in remaining table entry if code is incomplete (guaranteed to have
  7965. at most one remaining entry, since if the code is incomplete, the
  7966. maximum code length that was allowed to get this far is one bit) */
  7967. if (huff !== 0) {
  7968. //table.op[next + huff] = 64; /* invalid code marker */
  7969. //table.bits[next + huff] = len - drop;
  7970. //table.val[next + huff] = 0;
  7971. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  7972. }
  7973.  
  7974. /* set return parameters */
  7975. //opts.table_index += used;
  7976. opts.bits = root;
  7977. return 0;
  7978. };
  7979.  
  7980. },{"../utils/common":27}],37:[function(_dereq_,module,exports){
  7981. 'use strict';
  7982.  
  7983. module.exports = {
  7984. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  7985. '1': 'stream end', /* Z_STREAM_END 1 */
  7986. '0': '', /* Z_OK 0 */
  7987. '-1': 'file error', /* Z_ERRNO (-1) */
  7988. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  7989. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  7990. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  7991. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  7992. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  7993. };
  7994. },{}],38:[function(_dereq_,module,exports){
  7995. 'use strict';
  7996.  
  7997.  
  7998. var utils = _dereq_('../utils/common');
  7999.  
  8000. /* Public constants ==========================================================*/
  8001. /* ===========================================================================*/
  8002.  
  8003.  
  8004. //var Z_FILTERED = 1;
  8005. //var Z_HUFFMAN_ONLY = 2;
  8006. //var Z_RLE = 3;
  8007. var Z_FIXED = 4;
  8008. //var Z_DEFAULT_STRATEGY = 0;
  8009.  
  8010. /* Possible values of the data_type field (though see inflate()) */
  8011. var Z_BINARY = 0;
  8012. var Z_TEXT = 1;
  8013. //var Z_ASCII = 1; // = Z_TEXT
  8014. var Z_UNKNOWN = 2;
  8015.  
  8016. /*============================================================================*/
  8017.  
  8018.  
  8019. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  8020.  
  8021. // From zutil.h
  8022.  
  8023. var STORED_BLOCK = 0;
  8024. var STATIC_TREES = 1;
  8025. var DYN_TREES = 2;
  8026. /* The three kinds of block type */
  8027.  
  8028. var MIN_MATCH = 3;
  8029. var MAX_MATCH = 258;
  8030. /* The minimum and maximum match lengths */
  8031.  
  8032. // From deflate.h
  8033. /* ===========================================================================
  8034. * Internal compression state.
  8035. */
  8036.  
  8037. var LENGTH_CODES = 29;
  8038. /* number of length codes, not counting the special END_BLOCK code */
  8039.  
  8040. var LITERALS = 256;
  8041. /* number of literal bytes 0..255 */
  8042.  
  8043. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  8044. /* number of Literal or Length codes, including the END_BLOCK code */
  8045.  
  8046. var D_CODES = 30;
  8047. /* number of distance codes */
  8048.  
  8049. var BL_CODES = 19;
  8050. /* number of codes used to transfer the bit lengths */
  8051.  
  8052. var HEAP_SIZE = 2*L_CODES + 1;
  8053. /* maximum heap size */
  8054.  
  8055. var MAX_BITS = 15;
  8056. /* All codes must not exceed MAX_BITS bits */
  8057.  
  8058. var Buf_size = 16;
  8059. /* size of bit buffer in bi_buf */
  8060.  
  8061.  
  8062. /* ===========================================================================
  8063. * Constants
  8064. */
  8065.  
  8066. var MAX_BL_BITS = 7;
  8067. /* Bit length codes must not exceed MAX_BL_BITS bits */
  8068.  
  8069. var END_BLOCK = 256;
  8070. /* end of block literal code */
  8071.  
  8072. var REP_3_6 = 16;
  8073. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  8074.  
  8075. var REPZ_3_10 = 17;
  8076. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  8077.  
  8078. var REPZ_11_138 = 18;
  8079. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  8080.  
  8081. var extra_lbits = /* extra bits for each length code */
  8082. [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];
  8083.  
  8084. var extra_dbits = /* extra bits for each distance code */
  8085. [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];
  8086.  
  8087. var extra_blbits = /* extra bits for each bit length code */
  8088. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  8089.  
  8090. var bl_order =
  8091. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  8092. /* The lengths of the bit length codes are sent in order of decreasing
  8093. * probability, to avoid transmitting the lengths for unused bit length codes.
  8094. */
  8095.  
  8096. /* ===========================================================================
  8097. * Local data. These are initialized only once.
  8098. */
  8099.  
  8100. // We pre-fill arrays with 0 to avoid uninitialized gaps
  8101.  
  8102. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  8103.  
  8104. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  8105. var static_ltree = new Array((L_CODES+2) * 2);
  8106. zero(static_ltree);
  8107. /* The static literal tree. Since the bit lengths are imposed, there is no
  8108. * need for the L_CODES extra codes used during heap construction. However
  8109. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  8110. * below).
  8111. */
  8112.  
  8113. var static_dtree = new Array(D_CODES * 2);
  8114. zero(static_dtree);
  8115. /* The static distance tree. (Actually a trivial tree since all codes use
  8116. * 5 bits.)
  8117. */
  8118.  
  8119. var _dist_code = new Array(DIST_CODE_LEN);
  8120. zero(_dist_code);
  8121. /* Distance codes. The first 256 values correspond to the distances
  8122. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  8123. * the 15 bit distances.
  8124. */
  8125.  
  8126. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  8127. zero(_length_code);
  8128. /* length code for each normalized match length (0 == MIN_MATCH) */
  8129.  
  8130. var base_length = new Array(LENGTH_CODES);
  8131. zero(base_length);
  8132. /* First normalized length for each code (0 = MIN_MATCH) */
  8133.  
  8134. var base_dist = new Array(D_CODES);
  8135. zero(base_dist);
  8136. /* First normalized distance for each code (0 = distance of 1) */
  8137.  
  8138.  
  8139. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  8140.  
  8141. this.static_tree = static_tree; /* static tree or NULL */
  8142. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  8143. this.extra_base = extra_base; /* base index for extra_bits */
  8144. this.elems = elems; /* max number of elements in the tree */
  8145. this.max_length = max_length; /* max bit length for the codes */
  8146.  
  8147. // show if `static_tree` has data or dummy - needed for monomorphic objects
  8148. this.has_stree = static_tree && static_tree.length;
  8149. };
  8150.  
  8151.  
  8152. var static_l_desc;
  8153. var static_d_desc;
  8154. var static_bl_desc;
  8155.  
  8156.  
  8157. var TreeDesc = function(dyn_tree, stat_desc) {
  8158. this.dyn_tree = dyn_tree; /* the dynamic tree */
  8159. this.max_code = 0; /* largest code with non zero frequency */
  8160. this.stat_desc = stat_desc; /* the corresponding static tree */
  8161. };
  8162.  
  8163.  
  8164.  
  8165. function d_code(dist) {
  8166. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  8167. }
  8168.  
  8169.  
  8170. /* ===========================================================================
  8171. * Output a short LSB first on the stream.
  8172. * IN assertion: there is enough room in pendingBuf.
  8173. */
  8174. function put_short (s, w) {
  8175. // put_byte(s, (uch)((w) & 0xff));
  8176. // put_byte(s, (uch)((ush)(w) >> 8));
  8177. s.pending_buf[s.pending++] = (w) & 0xff;
  8178. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  8179. }
  8180.  
  8181.  
  8182. /* ===========================================================================
  8183. * Send a value on a given number of bits.
  8184. * IN assertion: length <= 16 and value fits in length bits.
  8185. */
  8186. function send_bits(s, value, length) {
  8187. if (s.bi_valid > (Buf_size - length)) {
  8188. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  8189. put_short(s, s.bi_buf);
  8190. s.bi_buf = value >> (Buf_size - s.bi_valid);
  8191. s.bi_valid += length - Buf_size;
  8192. } else {
  8193. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  8194. s.bi_valid += length;
  8195. }
  8196. }
  8197.  
  8198.  
  8199. function send_code(s, c, tree) {
  8200. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  8201. }
  8202.  
  8203.  
  8204. /* ===========================================================================
  8205. * Reverse the first len bits of a code, using straightforward code (a faster
  8206. * method would use a table)
  8207. * IN assertion: 1 <= len <= 15
  8208. */
  8209. function bi_reverse(code, len) {
  8210. var res = 0;
  8211. do {
  8212. res |= code & 1;
  8213. code >>>= 1;
  8214. res <<= 1;
  8215. } while (--len > 0);
  8216. return res >>> 1;
  8217. }
  8218.  
  8219.  
  8220. /* ===========================================================================
  8221. * Flush the bit buffer, keeping at most 7 bits in it.
  8222. */
  8223. function bi_flush(s) {
  8224. if (s.bi_valid === 16) {
  8225. put_short(s, s.bi_buf);
  8226. s.bi_buf = 0;
  8227. s.bi_valid = 0;
  8228.  
  8229. } else if (s.bi_valid >= 8) {
  8230. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  8231. s.bi_buf >>= 8;
  8232. s.bi_valid -= 8;
  8233. }
  8234. }
  8235.  
  8236.  
  8237. /* ===========================================================================
  8238. * Compute the optimal bit lengths for a tree and update the total bit length
  8239. * for the current block.
  8240. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  8241. * above are the tree nodes sorted by increasing frequency.
  8242. * OUT assertions: the field len is set to the optimal bit length, the
  8243. * array bl_count contains the frequencies for each bit length.
  8244. * The length opt_len is updated; static_len is also updated if stree is
  8245. * not null.
  8246. */
  8247. function gen_bitlen(s, desc)
  8248. // deflate_state *s;
  8249. // tree_desc *desc; /* the tree descriptor */
  8250. {
  8251. var tree = desc.dyn_tree;
  8252. var max_code = desc.max_code;
  8253. var stree = desc.stat_desc.static_tree;
  8254. var has_stree = desc.stat_desc.has_stree;
  8255. var extra = desc.stat_desc.extra_bits;
  8256. var base = desc.stat_desc.extra_base;
  8257. var max_length = desc.stat_desc.max_length;
  8258. var h; /* heap index */
  8259. var n, m; /* iterate over the tree elements */
  8260. var bits; /* bit length */
  8261. var xbits; /* extra bits */
  8262. var f; /* frequency */
  8263. var overflow = 0; /* number of elements with bit length too large */
  8264.  
  8265. for (bits = 0; bits <= MAX_BITS; bits++) {
  8266. s.bl_count[bits] = 0;
  8267. }
  8268.  
  8269. /* In a first pass, compute the optimal bit lengths (which may
  8270. * overflow in the case of the bit length tree).
  8271. */
  8272. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  8273.  
  8274. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  8275. n = s.heap[h];
  8276. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  8277. if (bits > max_length) {
  8278. bits = max_length;
  8279. overflow++;
  8280. }
  8281. tree[n*2 + 1]/*.Len*/ = bits;
  8282. /* We overwrite tree[n].Dad which is no longer needed */
  8283.  
  8284. if (n > max_code) { continue; } /* not a leaf node */
  8285.  
  8286. s.bl_count[bits]++;
  8287. xbits = 0;
  8288. if (n >= base) {
  8289. xbits = extra[n-base];
  8290. }
  8291. f = tree[n * 2]/*.Freq*/;
  8292. s.opt_len += f * (bits + xbits);
  8293. if (has_stree) {
  8294. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  8295. }
  8296. }
  8297. if (overflow === 0) { return; }
  8298.  
  8299. // Trace((stderr,"\nbit length overflow\n"));
  8300. /* This happens for example on obj2 and pic of the Calgary corpus */
  8301.  
  8302. /* Find the first bit length which could increase: */
  8303. do {
  8304. bits = max_length-1;
  8305. while (s.bl_count[bits] === 0) { bits--; }
  8306. s.bl_count[bits]--; /* move one leaf down the tree */
  8307. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  8308. s.bl_count[max_length]--;
  8309. /* The brother of the overflow item also moves one step up,
  8310. * but this does not affect bl_count[max_length]
  8311. */
  8312. overflow -= 2;
  8313. } while (overflow > 0);
  8314.  
  8315. /* Now recompute all bit lengths, scanning in increasing frequency.
  8316. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  8317. * lengths instead of fixing only the wrong ones. This idea is taken
  8318. * from 'ar' written by Haruhiko Okumura.)
  8319. */
  8320. for (bits = max_length; bits !== 0; bits--) {
  8321. n = s.bl_count[bits];
  8322. while (n !== 0) {
  8323. m = s.heap[--h];
  8324. if (m > max_code) { continue; }
  8325. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  8326. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  8327. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  8328. tree[m*2 + 1]/*.Len*/ = bits;
  8329. }
  8330. n--;
  8331. }
  8332. }
  8333. }
  8334.  
  8335.  
  8336. /* ===========================================================================
  8337. * Generate the codes for a given tree and bit counts (which need not be
  8338. * optimal).
  8339. * IN assertion: the array bl_count contains the bit length statistics for
  8340. * the given tree and the field len is set for all tree elements.
  8341. * OUT assertion: the field code is set for all tree elements of non
  8342. * zero code length.
  8343. */
  8344. function gen_codes(tree, max_code, bl_count)
  8345. // ct_data *tree; /* the tree to decorate */
  8346. // int max_code; /* largest code with non zero frequency */
  8347. // ushf *bl_count; /* number of codes at each bit length */
  8348. {
  8349. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  8350. var code = 0; /* running code value */
  8351. var bits; /* bit index */
  8352. var n; /* code index */
  8353.  
  8354. /* The distribution counts are first used to generate the code values
  8355. * without bit reversal.
  8356. */
  8357. for (bits = 1; bits <= MAX_BITS; bits++) {
  8358. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  8359. }
  8360. /* Check that the bit counts in bl_count are consistent. The last code
  8361. * must be all ones.
  8362. */
  8363. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  8364. // "inconsistent bit counts");
  8365. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  8366.  
  8367. for (n = 0; n <= max_code; n++) {
  8368. var len = tree[n*2 + 1]/*.Len*/;
  8369. if (len === 0) { continue; }
  8370. /* Now reverse the bits */
  8371. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  8372.  
  8373. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  8374. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  8375. }
  8376. }
  8377.  
  8378.  
  8379. /* ===========================================================================
  8380. * Initialize the various 'constant' tables.
  8381. */
  8382. function tr_static_init() {
  8383. var n; /* iterates over tree elements */
  8384. var bits; /* bit counter */
  8385. var length; /* length value */
  8386. var code; /* code value */
  8387. var dist; /* distance index */
  8388. var bl_count = new Array(MAX_BITS+1);
  8389. /* number of codes at each bit length for an optimal tree */
  8390.  
  8391. // do check in _tr_init()
  8392. //if (static_init_done) return;
  8393.  
  8394. /* For some embedded targets, global variables are not initialized: */
  8395. /*#ifdef NO_INIT_GLOBAL_POINTERS
  8396. static_l_desc.static_tree = static_ltree;
  8397. static_l_desc.extra_bits = extra_lbits;
  8398. static_d_desc.static_tree = static_dtree;
  8399. static_d_desc.extra_bits = extra_dbits;
  8400. static_bl_desc.extra_bits = extra_blbits;
  8401. #endif*/
  8402.  
  8403. /* Initialize the mapping length (0..255) -> length code (0..28) */
  8404. length = 0;
  8405. for (code = 0; code < LENGTH_CODES-1; code++) {
  8406. base_length[code] = length;
  8407. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  8408. _length_code[length++] = code;
  8409. }
  8410. }
  8411. //Assert (length == 256, "tr_static_init: length != 256");
  8412. /* Note that the length 255 (match length 258) can be represented
  8413. * in two different ways: code 284 + 5 bits or code 285, so we
  8414. * overwrite length_code[255] to use the best encoding:
  8415. */
  8416. _length_code[length-1] = code;
  8417.  
  8418. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  8419. dist = 0;
  8420. for (code = 0 ; code < 16; code++) {
  8421. base_dist[code] = dist;
  8422. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  8423. _dist_code[dist++] = code;
  8424. }
  8425. }
  8426. //Assert (dist == 256, "tr_static_init: dist != 256");
  8427. dist >>= 7; /* from now on, all distances are divided by 128 */
  8428. for ( ; code < D_CODES; code++) {
  8429. base_dist[code] = dist << 7;
  8430. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  8431. _dist_code[256 + dist++] = code;
  8432. }
  8433. }
  8434. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  8435.  
  8436. /* Construct the codes of the static literal tree */
  8437. for (bits = 0; bits <= MAX_BITS; bits++) {
  8438. bl_count[bits] = 0;
  8439. }
  8440.  
  8441. n = 0;
  8442. while (n <= 143) {
  8443. static_ltree[n*2 + 1]/*.Len*/ = 8;
  8444. n++;
  8445. bl_count[8]++;
  8446. }
  8447. while (n <= 255) {
  8448. static_ltree[n*2 + 1]/*.Len*/ = 9;
  8449. n++;
  8450. bl_count[9]++;
  8451. }
  8452. while (n <= 279) {
  8453. static_ltree[n*2 + 1]/*.Len*/ = 7;
  8454. n++;
  8455. bl_count[7]++;
  8456. }
  8457. while (n <= 287) {
  8458. static_ltree[n*2 + 1]/*.Len*/ = 8;
  8459. n++;
  8460. bl_count[8]++;
  8461. }
  8462. /* Codes 286 and 287 do not exist, but we must include them in the
  8463. * tree construction to get a canonical Huffman tree (longest code
  8464. * all ones)
  8465. */
  8466. gen_codes(static_ltree, L_CODES+1, bl_count);
  8467.  
  8468. /* The static distance tree is trivial: */
  8469. for (n = 0; n < D_CODES; n++) {
  8470. static_dtree[n*2 + 1]/*.Len*/ = 5;
  8471. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  8472. }
  8473.  
  8474. // Now data ready and we can init static trees
  8475. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  8476. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  8477. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  8478.  
  8479. //static_init_done = true;
  8480. }
  8481.  
  8482.  
  8483. /* ===========================================================================
  8484. * Initialize a new block.
  8485. */
  8486. function init_block(s) {
  8487. var n; /* iterates over tree elements */
  8488.  
  8489. /* Initialize the trees. */
  8490. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  8491. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  8492. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  8493.  
  8494. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  8495. s.opt_len = s.static_len = 0;
  8496. s.last_lit = s.matches = 0;
  8497. }
  8498.  
  8499.  
  8500. /* ===========================================================================
  8501. * Flush the bit buffer and align the output on a byte boundary
  8502. */
  8503. function bi_windup(s)
  8504. {
  8505. if (s.bi_valid > 8) {
  8506. put_short(s, s.bi_buf);
  8507. } else if (s.bi_valid > 0) {
  8508. //put_byte(s, (Byte)s->bi_buf);
  8509. s.pending_buf[s.pending++] = s.bi_buf;
  8510. }
  8511. s.bi_buf = 0;
  8512. s.bi_valid = 0;
  8513. }
  8514.  
  8515. /* ===========================================================================
  8516. * Copy a stored block, storing first the length and its
  8517. * one's complement if requested.
  8518. */
  8519. function copy_block(s, buf, len, header)
  8520. //DeflateState *s;
  8521. //charf *buf; /* the input data */
  8522. //unsigned len; /* its length */
  8523. //int header; /* true if block header must be written */
  8524. {
  8525. bi_windup(s); /* align on byte boundary */
  8526.  
  8527. if (header) {
  8528. put_short(s, len);
  8529. put_short(s, ~len);
  8530. }
  8531. // while (len--) {
  8532. // put_byte(s, *buf++);
  8533. // }
  8534. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  8535. s.pending += len;
  8536. }
  8537.  
  8538. /* ===========================================================================
  8539. * Compares to subtrees, using the tree depth as tie breaker when
  8540. * the subtrees have equal frequency. This minimizes the worst case length.
  8541. */
  8542. function smaller(tree, n, m, depth) {
  8543. var _n2 = n*2;
  8544. var _m2 = m*2;
  8545. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  8546. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  8547. }
  8548.  
  8549. /* ===========================================================================
  8550. * Restore the heap property by moving down the tree starting at node k,
  8551. * exchanging a node with the smallest of its two sons if necessary, stopping
  8552. * when the heap property is re-established (each father smaller than its
  8553. * two sons).
  8554. */
  8555. function pqdownheap(s, tree, k)
  8556. // deflate_state *s;
  8557. // ct_data *tree; /* the tree to restore */
  8558. // int k; /* node to move down */
  8559. {
  8560. var v = s.heap[k];
  8561. var j = k << 1; /* left son of k */
  8562. while (j <= s.heap_len) {
  8563. /* Set j to the smallest of the two sons: */
  8564. if (j < s.heap_len &&
  8565. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  8566. j++;
  8567. }
  8568. /* Exit if v is smaller than both sons */
  8569. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  8570.  
  8571. /* Exchange v with the smallest son */
  8572. s.heap[k] = s.heap[j];
  8573. k = j;
  8574.  
  8575. /* And continue down the tree, setting j to the left son of k */
  8576. j <<= 1;
  8577. }
  8578. s.heap[k] = v;
  8579. }
  8580.  
  8581.  
  8582. // inlined manually
  8583. // var SMALLEST = 1;
  8584.  
  8585. /* ===========================================================================
  8586. * Send the block data compressed using the given Huffman trees
  8587. */
  8588. function compress_block(s, ltree, dtree)
  8589. // deflate_state *s;
  8590. // const ct_data *ltree; /* literal tree */
  8591. // const ct_data *dtree; /* distance tree */
  8592. {
  8593. var dist; /* distance of matched string */
  8594. var lc; /* match length or unmatched char (if dist == 0) */
  8595. var lx = 0; /* running index in l_buf */
  8596. var code; /* the code to send */
  8597. var extra; /* number of extra bits to send */
  8598.  
  8599. if (s.last_lit !== 0) {
  8600. do {
  8601. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  8602. lc = s.pending_buf[s.l_buf + lx];
  8603. lx++;
  8604.  
  8605. if (dist === 0) {
  8606. send_code(s, lc, ltree); /* send a literal byte */
  8607. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  8608. } else {
  8609. /* Here, lc is the match length - MIN_MATCH */
  8610. code = _length_code[lc];
  8611. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  8612. extra = extra_lbits[code];
  8613. if (extra !== 0) {
  8614. lc -= base_length[code];
  8615. send_bits(s, lc, extra); /* send the extra length bits */
  8616. }
  8617. dist--; /* dist is now the match distance - 1 */
  8618. code = d_code(dist);
  8619. //Assert (code < D_CODES, "bad d_code");
  8620.  
  8621. send_code(s, code, dtree); /* send the distance code */
  8622. extra = extra_dbits[code];
  8623. if (extra !== 0) {
  8624. dist -= base_dist[code];
  8625. send_bits(s, dist, extra); /* send the extra distance bits */
  8626. }
  8627. } /* literal or match pair ? */
  8628.  
  8629. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  8630. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  8631. // "pendingBuf overflow");
  8632.  
  8633. } while (lx < s.last_lit);
  8634. }
  8635.  
  8636. send_code(s, END_BLOCK, ltree);
  8637. }
  8638.  
  8639.  
  8640. /* ===========================================================================
  8641. * Construct one Huffman tree and assigns the code bit strings and lengths.
  8642. * Update the total bit length for the current block.
  8643. * IN assertion: the field freq is set for all tree elements.
  8644. * OUT assertions: the fields len and code are set to the optimal bit length
  8645. * and corresponding code. The length opt_len is updated; static_len is
  8646. * also updated if stree is not null. The field max_code is set.
  8647. */
  8648. function build_tree(s, desc)
  8649. // deflate_state *s;
  8650. // tree_desc *desc; /* the tree descriptor */
  8651. {
  8652. var tree = desc.dyn_tree;
  8653. var stree = desc.stat_desc.static_tree;
  8654. var has_stree = desc.stat_desc.has_stree;
  8655. var elems = desc.stat_desc.elems;
  8656. var n, m; /* iterate over heap elements */
  8657. var max_code = -1; /* largest code with non zero frequency */
  8658. var node; /* new node being created */
  8659.  
  8660. /* Construct the initial heap, with least frequent element in
  8661. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  8662. * heap[0] is not used.
  8663. */
  8664. s.heap_len = 0;
  8665. s.heap_max = HEAP_SIZE;
  8666.  
  8667. for (n = 0; n < elems; n++) {
  8668. if (tree[n * 2]/*.Freq*/ !== 0) {
  8669. s.heap[++s.heap_len] = max_code = n;
  8670. s.depth[n] = 0;
  8671.  
  8672. } else {
  8673. tree[n*2 + 1]/*.Len*/ = 0;
  8674. }
  8675. }
  8676.  
  8677. /* The pkzip format requires that at least one distance code exists,
  8678. * and that at least one bit should be sent even if there is only one
  8679. * possible code. So to avoid special checks later on we force at least
  8680. * two codes of non zero frequency.
  8681. */
  8682. while (s.heap_len < 2) {
  8683. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  8684. tree[node * 2]/*.Freq*/ = 1;
  8685. s.depth[node] = 0;
  8686. s.opt_len--;
  8687.  
  8688. if (has_stree) {
  8689. s.static_len -= stree[node*2 + 1]/*.Len*/;
  8690. }
  8691. /* node is 0 or 1 so it does not have extra bits */
  8692. }
  8693. desc.max_code = max_code;
  8694.  
  8695. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  8696. * establish sub-heaps of increasing lengths:
  8697. */
  8698. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  8699.  
  8700. /* Construct the Huffman tree by repeatedly combining the least two
  8701. * frequent nodes.
  8702. */
  8703. node = elems; /* next internal node of the tree */
  8704. do {
  8705. //pqremove(s, tree, n); /* n = node of least frequency */
  8706. /*** pqremove ***/
  8707. n = s.heap[1/*SMALLEST*/];
  8708. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  8709. pqdownheap(s, tree, 1/*SMALLEST*/);
  8710. /***/
  8711.  
  8712. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  8713.  
  8714. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  8715. s.heap[--s.heap_max] = m;
  8716.  
  8717. /* Create a new node father of n and m */
  8718. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  8719. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  8720. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  8721.  
  8722. /* and insert the new node in the heap */
  8723. s.heap[1/*SMALLEST*/] = node++;
  8724. pqdownheap(s, tree, 1/*SMALLEST*/);
  8725.  
  8726. } while (s.heap_len >= 2);
  8727.  
  8728. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  8729.  
  8730. /* At this point, the fields freq and dad are set. We can now
  8731. * generate the bit lengths.
  8732. */
  8733. gen_bitlen(s, desc);
  8734.  
  8735. /* The field len is now set, we can generate the bit codes */
  8736. gen_codes(tree, max_code, s.bl_count);
  8737. }
  8738.  
  8739.  
  8740. /* ===========================================================================
  8741. * Scan a literal or distance tree to determine the frequencies of the codes
  8742. * in the bit length tree.
  8743. */
  8744. function scan_tree(s, tree, max_code)
  8745. // deflate_state *s;
  8746. // ct_data *tree; /* the tree to be scanned */
  8747. // int max_code; /* and its largest code of non zero frequency */
  8748. {
  8749. var n; /* iterates over all tree elements */
  8750. var prevlen = -1; /* last emitted length */
  8751. var curlen; /* length of current code */
  8752.  
  8753. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  8754.  
  8755. var count = 0; /* repeat count of the current code */
  8756. var max_count = 7; /* max repeat count */
  8757. var min_count = 4; /* min repeat count */
  8758.  
  8759. if (nextlen === 0) {
  8760. max_count = 138;
  8761. min_count = 3;
  8762. }
  8763. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  8764.  
  8765. for (n = 0; n <= max_code; n++) {
  8766. curlen = nextlen;
  8767. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  8768.  
  8769. if (++count < max_count && curlen === nextlen) {
  8770. continue;
  8771.  
  8772. } else if (count < min_count) {
  8773. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  8774.  
  8775. } else if (curlen !== 0) {
  8776.  
  8777. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  8778. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  8779.  
  8780. } else if (count <= 10) {
  8781. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  8782.  
  8783. } else {
  8784. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  8785. }
  8786.  
  8787. count = 0;
  8788. prevlen = curlen;
  8789.  
  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. * Send a literal or distance tree in compressed form, using the codes in
  8808. * bl_tree.
  8809. */
  8810. function send_tree(s, tree, max_code)
  8811. // deflate_state *s;
  8812. // ct_data *tree; /* the tree to be scanned */
  8813. // int max_code; /* and its largest code of non zero frequency */
  8814. {
  8815. var n; /* iterates over all tree elements */
  8816. var prevlen = -1; /* last emitted length */
  8817. var curlen; /* length of current code */
  8818.  
  8819. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  8820.  
  8821. var count = 0; /* repeat count of the current code */
  8822. var max_count = 7; /* max repeat count */
  8823. var min_count = 4; /* min repeat count */
  8824.  
  8825. /* tree[max_code+1].Len = -1; */ /* guard already set */
  8826. if (nextlen === 0) {
  8827. max_count = 138;
  8828. min_count = 3;
  8829. }
  8830.  
  8831. for (n = 0; n <= max_code; n++) {
  8832. curlen = nextlen;
  8833. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  8834.  
  8835. if (++count < max_count && curlen === nextlen) {
  8836. continue;
  8837.  
  8838. } else if (count < min_count) {
  8839. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  8840.  
  8841. } else if (curlen !== 0) {
  8842. if (curlen !== prevlen) {
  8843. send_code(s, curlen, s.bl_tree);
  8844. count--;
  8845. }
  8846. //Assert(count >= 3 && count <= 6, " 3_6?");
  8847. send_code(s, REP_3_6, s.bl_tree);
  8848. send_bits(s, count-3, 2);
  8849.  
  8850. } else if (count <= 10) {
  8851. send_code(s, REPZ_3_10, s.bl_tree);
  8852. send_bits(s, count-3, 3);
  8853.  
  8854. } else {
  8855. send_code(s, REPZ_11_138, s.bl_tree);
  8856. send_bits(s, count-11, 7);
  8857. }
  8858.  
  8859. count = 0;
  8860. prevlen = curlen;
  8861. if (nextlen === 0) {
  8862. max_count = 138;
  8863. min_count = 3;
  8864.  
  8865. } else if (curlen === nextlen) {
  8866. max_count = 6;
  8867. min_count = 3;
  8868.  
  8869. } else {
  8870. max_count = 7;
  8871. min_count = 4;
  8872. }
  8873. }
  8874. }
  8875.  
  8876.  
  8877. /* ===========================================================================
  8878. * Construct the Huffman tree for the bit lengths and return the index in
  8879. * bl_order of the last bit length code to send.
  8880. */
  8881. function build_bl_tree(s) {
  8882. var max_blindex; /* index of last bit length code of non zero freq */
  8883.  
  8884. /* Determine the bit length frequencies for literal and distance trees */
  8885. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  8886. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  8887.  
  8888. /* Build the bit length tree: */
  8889. build_tree(s, s.bl_desc);
  8890. /* opt_len now includes the length of the tree representations, except
  8891. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  8892. */
  8893.  
  8894. /* Determine the number of bit length codes to send. The pkzip format
  8895. * requires that at least 4 bit length codes be sent. (appnote.txt says
  8896. * 3 but the actual value used is 4.)
  8897. */
  8898. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  8899. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  8900. break;
  8901. }
  8902. }
  8903. /* Update opt_len to include the bit length tree and counts */
  8904. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  8905. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  8906. // s->opt_len, s->static_len));
  8907.  
  8908. return max_blindex;
  8909. }
  8910.  
  8911.  
  8912. /* ===========================================================================
  8913. * Send the header for a block using dynamic Huffman trees: the counts, the
  8914. * lengths of the bit length codes, the literal tree and the distance tree.
  8915. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  8916. */
  8917. function send_all_trees(s, lcodes, dcodes, blcodes)
  8918. // deflate_state *s;
  8919. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  8920. {
  8921. var rank; /* index in bl_order */
  8922.  
  8923. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  8924. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  8925. // "too many codes");
  8926. //Tracev((stderr, "\nbl counts: "));
  8927. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  8928. send_bits(s, dcodes-1, 5);
  8929. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  8930. for (rank = 0; rank < blcodes; rank++) {
  8931. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  8932. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  8933. }
  8934. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  8935.  
  8936. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  8937. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  8938.  
  8939. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  8940. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  8941. }
  8942.  
  8943.  
  8944. /* ===========================================================================
  8945. * Check if the data type is TEXT or BINARY, using the following algorithm:
  8946. * - TEXT if the two conditions below are satisfied:
  8947. * a) There are no non-portable control characters belonging to the
  8948. * "black list" (0..6, 14..25, 28..31).
  8949. * b) There is at least one printable character belonging to the
  8950. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  8951. * - BINARY otherwise.
  8952. * - The following partially-portable control characters form a
  8953. * "gray list" that is ignored in this detection algorithm:
  8954. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  8955. * IN assertion: the fields Freq of dyn_ltree are set.
  8956. */
  8957. function detect_data_type(s) {
  8958. /* black_mask is the bit mask of black-listed bytes
  8959. * set bits 0..6, 14..25, and 28..31
  8960. * 0xf3ffc07f = binary 11110011111111111100000001111111
  8961. */
  8962. var black_mask = 0xf3ffc07f;
  8963. var n;
  8964.  
  8965. /* Check for non-textual ("black-listed") bytes. */
  8966. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  8967. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  8968. return Z_BINARY;
  8969. }
  8970. }
  8971.  
  8972. /* Check for textual ("white-listed") bytes. */
  8973. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  8974. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  8975. return Z_TEXT;
  8976. }
  8977. for (n = 32; n < LITERALS; n++) {
  8978. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  8979. return Z_TEXT;
  8980. }
  8981. }
  8982.  
  8983. /* There are no "black-listed" or "white-listed" bytes:
  8984. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  8985. */
  8986. return Z_BINARY;
  8987. }
  8988.  
  8989.  
  8990. var static_init_done = false;
  8991.  
  8992. /* ===========================================================================
  8993. * Initialize the tree data structures for a new zlib stream.
  8994. */
  8995. function _tr_init(s)
  8996. {
  8997.  
  8998. if (!static_init_done) {
  8999. tr_static_init();
  9000. static_init_done = true;
  9001. }
  9002.  
  9003. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  9004. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  9005. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  9006.  
  9007. s.bi_buf = 0;
  9008. s.bi_valid = 0;
  9009.  
  9010. /* Initialize the first block of the first file: */
  9011. init_block(s);
  9012. }
  9013.  
  9014.  
  9015. /* ===========================================================================
  9016. * Send a stored block
  9017. */
  9018. function _tr_stored_block(s, buf, stored_len, last)
  9019. //DeflateState *s;
  9020. //charf *buf; /* input block */
  9021. //ulg stored_len; /* length of input block */
  9022. //int last; /* one if this is the last block for a file */
  9023. {
  9024. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  9025. copy_block(s, buf, stored_len, true); /* with header */
  9026. }
  9027.  
  9028.  
  9029. /* ===========================================================================
  9030. * Send one empty static block to give enough lookahead for inflate.
  9031. * This takes 10 bits, of which 7 may remain in the bit buffer.
  9032. */
  9033. function _tr_align(s) {
  9034. send_bits(s, STATIC_TREES<<1, 3);
  9035. send_code(s, END_BLOCK, static_ltree);
  9036. bi_flush(s);
  9037. }
  9038.  
  9039.  
  9040. /* ===========================================================================
  9041. * Determine the best encoding for the current block: dynamic trees, static
  9042. * trees or store, and output the encoded block to the zip file.
  9043. */
  9044. function _tr_flush_block(s, buf, stored_len, last)
  9045. //DeflateState *s;
  9046. //charf *buf; /* input block, or NULL if too old */
  9047. //ulg stored_len; /* length of input block */
  9048. //int last; /* one if this is the last block for a file */
  9049. {
  9050. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  9051. var max_blindex = 0; /* index of last bit length code of non zero freq */
  9052.  
  9053. /* Build the Huffman trees unless a stored block is forced */
  9054. if (s.level > 0) {
  9055.  
  9056. /* Check if the file is binary or text */
  9057. if (s.strm.data_type === Z_UNKNOWN) {
  9058. s.strm.data_type = detect_data_type(s);
  9059. }
  9060.  
  9061. /* Construct the literal and distance trees */
  9062. build_tree(s, s.l_desc);
  9063. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  9064. // s->static_len));
  9065.  
  9066. build_tree(s, s.d_desc);
  9067. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  9068. // s->static_len));
  9069. /* At this point, opt_len and static_len are the total bit lengths of
  9070. * the compressed block data, excluding the tree representations.
  9071. */
  9072.  
  9073. /* Build the bit length tree for the above two trees, and get the index
  9074. * in bl_order of the last bit length code to send.
  9075. */
  9076. max_blindex = build_bl_tree(s);
  9077.  
  9078. /* Determine the best encoding. Compute the block lengths in bytes. */
  9079. opt_lenb = (s.opt_len+3+7) >>> 3;
  9080. static_lenb = (s.static_len+3+7) >>> 3;
  9081.  
  9082. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  9083. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  9084. // s->last_lit));
  9085.  
  9086. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  9087.  
  9088. } else {
  9089. // Assert(buf != (char*)0, "lost buf");
  9090. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  9091. }
  9092.  
  9093. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  9094. /* 4: two words for the lengths */
  9095.  
  9096. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  9097. * Otherwise we can't have processed more than WSIZE input bytes since
  9098. * the last block flush, because compression would have been
  9099. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  9100. * transform a block into a stored block.
  9101. */
  9102. _tr_stored_block(s, buf, stored_len, last);
  9103.  
  9104. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  9105.  
  9106. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  9107. compress_block(s, static_ltree, static_dtree);
  9108.  
  9109. } else {
  9110. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  9111. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  9112. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  9113. }
  9114. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  9115. /* The above check is made mod 2^32, for files larger than 512 MB
  9116. * and uLong implemented on 32 bits.
  9117. */
  9118. init_block(s);
  9119.  
  9120. if (last) {
  9121. bi_windup(s);
  9122. }
  9123. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  9124. // s->compressed_len-7*last));
  9125. }
  9126.  
  9127. /* ===========================================================================
  9128. * Save the match info and tally the frequency counts. Return true if
  9129. * the current block must be flushed.
  9130. */
  9131. function _tr_tally(s, dist, lc)
  9132. // deflate_state *s;
  9133. // unsigned dist; /* distance of matched string */
  9134. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  9135. {
  9136. //var out_length, in_length, dcode;
  9137.  
  9138. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  9139. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  9140.  
  9141. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  9142. s.last_lit++;
  9143.  
  9144. if (dist === 0) {
  9145. /* lc is the unmatched char */
  9146. s.dyn_ltree[lc*2]/*.Freq*/++;
  9147. } else {
  9148. s.matches++;
  9149. /* Here, lc is the match length - MIN_MATCH */
  9150. dist--; /* dist = match distance - 1 */
  9151. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  9152. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  9153. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  9154.  
  9155. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  9156. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  9157. }
  9158.  
  9159. // (!) This block is disabled in zlib defailts,
  9160. // don't enable it for binary compatibility
  9161.  
  9162. //#ifdef TRUNCATE_BLOCK
  9163. // /* Try to guess if it is profitable to stop the current block here */
  9164. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  9165. // /* Compute an upper bound for the compressed length */
  9166. // out_length = s.last_lit*8;
  9167. // in_length = s.strstart - s.block_start;
  9168. //
  9169. // for (dcode = 0; dcode < D_CODES; dcode++) {
  9170. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  9171. // }
  9172. // out_length >>>= 3;
  9173. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  9174. // // s->last_lit, in_length, out_length,
  9175. // // 100L - out_length*100L/in_length));
  9176. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  9177. // return true;
  9178. // }
  9179. // }
  9180. //#endif
  9181.  
  9182. return (s.last_lit === s.lit_bufsize-1);
  9183. /* We avoid equality with lit_bufsize because of wraparound at 64K
  9184. * on 16 bit machines and because stored blocks are restricted to
  9185. * 64K-1 bytes.
  9186. */
  9187. }
  9188.  
  9189. exports._tr_init = _tr_init;
  9190. exports._tr_stored_block = _tr_stored_block;
  9191. exports._tr_flush_block = _tr_flush_block;
  9192. exports._tr_tally = _tr_tally;
  9193. exports._tr_align = _tr_align;
  9194. },{"../utils/common":27}],39:[function(_dereq_,module,exports){
  9195. 'use strict';
  9196.  
  9197.  
  9198. function ZStream() {
  9199. /* next input byte */
  9200. this.input = null; // JS specific, because we have no pointers
  9201. this.next_in = 0;
  9202. /* number of bytes available at input */
  9203. this.avail_in = 0;
  9204. /* total number of input bytes read so far */
  9205. this.total_in = 0;
  9206. /* next output byte should be put there */
  9207. this.output = null; // JS specific, because we have no pointers
  9208. this.next_out = 0;
  9209. /* remaining free space at output */
  9210. this.avail_out = 0;
  9211. /* total number of bytes output so far */
  9212. this.total_out = 0;
  9213. /* last error message, NULL if no error */
  9214. this.msg = ''/*Z_NULL*/;
  9215. /* not visible by applications */
  9216. this.state = null;
  9217. /* best guess about the data type: binary or text */
  9218. this.data_type = 2/*Z_UNKNOWN*/;
  9219. /* adler32 value of the uncompressed data */
  9220. this.adler = 0;
  9221. }
  9222.  
  9223. module.exports = ZStream;
  9224. },{}]},{},[9])
  9225. (9)
  9226. });
  9227. // ==========---------- JSZip End ----------========== //
  9228.  
  9229. // ==========---------- FileSaver.js Begin ----------========== //
  9230.  
  9231. /* FileSaver.js
  9232. * A saveAs() FileSaver implementation.
  9233. * 1.1.20150716
  9234. *
  9235. * By Eli Grey, http://eligrey.com
  9236. * License: X11/MIT
  9237. * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
  9238. */
  9239.  
  9240. /*global self */
  9241. /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
  9242.  
  9243. /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
  9244.  
  9245. var saveAs = saveAs || (function(view) {
  9246. "use strict";
  9247. // IE <10 is explicitly unsupported
  9248. if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
  9249. return;
  9250. }
  9251. var
  9252. doc = view.document
  9253. // only get URL when necessary in case Blob.js hasn't overridden it yet
  9254. , get_URL = function() {
  9255. return view.URL || view.webkitURL || view;
  9256. }
  9257. , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
  9258. , can_use_save_link = "download" in save_link
  9259. , click = function(node) {
  9260. var event = new MouseEvent("click");
  9261. node.dispatchEvent(event);
  9262. }
  9263. , webkit_req_fs = view.webkitRequestFileSystem
  9264. , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
  9265. , throw_outside = function(ex) {
  9266. (view.setImmediate || view.setTimeout)(function() {
  9267. throw ex;
  9268. }, 0);
  9269. }
  9270. , force_saveable_type = "application/octet-stream"
  9271. , fs_min_size = 0
  9272. // See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and
  9273. // https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047
  9274. // for the reasoning behind the timeout and revocation flow
  9275. , arbitrary_revoke_timeout = 500 // in ms
  9276. , revoke = function(file) {
  9277. var revoker = function() {
  9278. if (typeof file === "string") { // file is an object URL
  9279. get_URL().revokeObjectURL(file);
  9280. } else { // file is a File
  9281. file.remove();
  9282. }
  9283. };
  9284. if (view.chrome) {
  9285. revoker();
  9286. } else {
  9287. setTimeout(revoker, arbitrary_revoke_timeout);
  9288. }
  9289. }
  9290. , dispatch = function(filesaver, event_types, event) {
  9291. event_types = [].concat(event_types);
  9292. var i = event_types.length;
  9293. while (i--) {
  9294. var listener = filesaver["on" + event_types[i]];
  9295. if (typeof listener === "function") {
  9296. try {
  9297. listener.call(filesaver, event || filesaver);
  9298. } catch (ex) {
  9299. throw_outside(ex);
  9300. }
  9301. }
  9302. }
  9303. }
  9304. , auto_bom = function(blob) {
  9305. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  9306. if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  9307. return new Blob(["\ufeff", blob], {type: blob.type});
  9308. }
  9309. return blob;
  9310. }
  9311. , FileSaver = function(blob, name, no_auto_bom) {
  9312. if (!no_auto_bom) {
  9313. blob = auto_bom(blob);
  9314. }
  9315. // First try a.download, then web filesystem, then object URLs
  9316. var
  9317. filesaver = this
  9318. , type = blob.type
  9319. , blob_changed = false
  9320. , object_url
  9321. , target_view
  9322. , dispatch_all = function() {
  9323. dispatch(filesaver, "writestart progress write writeend".split(" "));
  9324. }
  9325. // on any filesys errors revert to saving with object URLs
  9326. , fs_error = function() {
  9327. // don't create more object URLs than needed
  9328. if (blob_changed || !object_url) {
  9329. object_url = get_URL().createObjectURL(blob);
  9330. }
  9331. if (target_view) {
  9332. target_view.location.href = object_url;
  9333. } else {
  9334. var new_tab = view.open(object_url, "_blank");
  9335. if (new_tab == undefined && typeof safari !== "undefined") {
  9336. //Apple do not allow window.open, see http://bit.ly/1kZffRI
  9337. view.location.href = object_url
  9338. }
  9339. }
  9340. filesaver.readyState = filesaver.DONE;
  9341. dispatch_all();
  9342. revoke(object_url);
  9343. }
  9344. , abortable = function(func) {
  9345. return function() {
  9346. if (filesaver.readyState !== filesaver.DONE) {
  9347. return func.apply(this, arguments);
  9348. }
  9349. };
  9350. }
  9351. , create_if_not_found = {create: true, exclusive: false}
  9352. , slice
  9353. ;
  9354. filesaver.readyState = filesaver.INIT;
  9355. if (!name) {
  9356. name = "download";
  9357. }
  9358. if (can_use_save_link) {
  9359. object_url = get_URL().createObjectURL(blob);
  9360. save_link.href = object_url;
  9361. save_link.download = name;
  9362. setTimeout(function() {
  9363. click(save_link);
  9364. dispatch_all();
  9365. revoke(object_url);
  9366. filesaver.readyState = filesaver.DONE;
  9367. });
  9368. return;
  9369. }
  9370. // Object and web filesystem URLs have a problem saving in Google Chrome when
  9371. // viewed in a tab, so I force save with application/octet-stream
  9372. // http://code.google.com/p/chromium/issues/detail?id=91158
  9373. // Update: Google errantly closed 91158, I submitted it again:
  9374. // https://code.google.com/p/chromium/issues/detail?id=389642
  9375. if (view.chrome && type && type !== force_saveable_type) {
  9376. slice = blob.slice || blob.webkitSlice;
  9377. blob = slice.call(blob, 0, blob.size, force_saveable_type);
  9378. blob_changed = true;
  9379. }
  9380. // Since I can't be sure that the guessed media type will trigger a download
  9381. // in WebKit, I append .download to the filename.
  9382. // https://bugs.webkit.org/show_bug.cgi?id=65440
  9383. if (webkit_req_fs && name !== "download") {
  9384. name += ".download";
  9385. }
  9386. if (type === force_saveable_type || webkit_req_fs) {
  9387. target_view = view;
  9388. }
  9389. if (!req_fs) {
  9390. fs_error();
  9391. return;
  9392. }
  9393. fs_min_size += blob.size;
  9394. req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
  9395. fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
  9396. var save = function() {
  9397. dir.getFile(name, create_if_not_found, abortable(function(file) {
  9398. file.createWriter(abortable(function(writer) {
  9399. writer.onwriteend = function(event) {
  9400. target_view.location.href = file.toURL();
  9401. filesaver.readyState = filesaver.DONE;
  9402. dispatch(filesaver, "writeend", event);
  9403. revoke(file);
  9404. };
  9405. writer.onerror = function() {
  9406. var error = writer.error;
  9407. if (error.code !== error.ABORT_ERR) {
  9408. fs_error();
  9409. }
  9410. };
  9411. "writestart progress write abort".split(" ").forEach(function(event) {
  9412. writer["on" + event] = filesaver["on" + event];
  9413. });
  9414. writer.write(blob);
  9415. filesaver.abort = function() {
  9416. writer.abort();
  9417. filesaver.readyState = filesaver.DONE;
  9418. };
  9419. filesaver.readyState = filesaver.WRITING;
  9420. }), fs_error);
  9421. }), fs_error);
  9422. };
  9423. dir.getFile(name, {create: false}, abortable(function(file) {
  9424. // delete file if it already exists
  9425. file.remove();
  9426. save();
  9427. }), abortable(function(ex) {
  9428. if (ex.code === ex.NOT_FOUND_ERR) {
  9429. save();
  9430. } else {
  9431. fs_error();
  9432. }
  9433. }));
  9434. }), fs_error);
  9435. }), fs_error);
  9436. }
  9437. , FS_proto = FileSaver.prototype
  9438. , saveAs = function(blob, name, no_auto_bom) {
  9439. return new FileSaver(blob, name, no_auto_bom);
  9440. }
  9441. ;
  9442. // IE 10+ (native saveAs)
  9443. if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
  9444. return function(blob, name, no_auto_bom) {
  9445. if (!no_auto_bom) {
  9446. blob = auto_bom(blob);
  9447. }
  9448. return navigator.msSaveOrOpenBlob(blob, name || "download");
  9449. };
  9450. }
  9451.  
  9452. FS_proto.abort = function() {
  9453. var filesaver = this;
  9454. filesaver.readyState = filesaver.DONE;
  9455. dispatch(filesaver, "abort");
  9456. };
  9457. FS_proto.readyState = FS_proto.INIT = 0;
  9458. FS_proto.WRITING = 1;
  9459. FS_proto.DONE = 2;
  9460.  
  9461. FS_proto.error =
  9462. FS_proto.onwritestart =
  9463. FS_proto.onprogress =
  9464. FS_proto.onwrite =
  9465. FS_proto.onabort =
  9466. FS_proto.onerror =
  9467. FS_proto.onwriteend =
  9468. null;
  9469.  
  9470. return saveAs;
  9471. }(
  9472. typeof self !== "undefined" && self
  9473. || typeof window !== "undefined" && window
  9474. || this.content
  9475. ));
  9476. // `self` is undefined in Firefox for Android content script context
  9477. // while `this` is nsIContentFrameMessageManager
  9478. // with an attribute `content` that corresponds to the window
  9479.  
  9480. if (typeof module !== "undefined" && module.exports) {
  9481. module.exports.saveAs = saveAs;
  9482. } else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
  9483. define([], function() {
  9484. return saveAs;
  9485. });
  9486. }
  9487.  
  9488. // ==========---------- FileSaver.js End ----------========== //
  9489.  
  9490. /* TrixIE Fix. Because of GM_xhr bug in TrixIE, there is no way to make this script compatible with IE */
  9491. /*if (navigator.userAgent.indexOf('Trident') >= 0) {
  9492. var GM_getValue = function(i) {
  9493. return localStorage.getItem(i);
  9494. }
  9495. var GM_setValue = function(i, j) {
  9496. return localStorage.setItem(i, j);
  9497. }
  9498. var GM_info = {script: {}};
  9499. var unsafeWindow = window;
  9500. }*/
  9501.  
  9502. var zip;
  9503. //var index = 1;
  9504. var retryCount = 0;
  9505. var imageList = [];
  9506. var imageData = [];
  9507. var logStr;
  9508. var origin = window.location.origin;
  9509. var setting = GM_getValue('ehD-setting') ? JSON.parse(GM_getValue('ehD-setting')) : {};
  9510. var fetchCount = 0;
  9511. var downloadedCount = 0;
  9512. var fetchThread = [];
  9513. var dirName;
  9514. var fileName;
  9515. var failedCount = 0;
  9516. var progressTable = null;
  9517. var isREH = false;
  9518. var needNumberImages = setting['number-images'];
  9519. var pagesRange = [];
  9520. var isDownloading = false;
  9521. var pageURLsList = [];
  9522. var getAllPagesURLFin = false;
  9523. var xhr = new XMLHttpRequest();
  9524.  
  9525. console.log('[EHD] UserAgent >', navigator.userAgent);
  9526. console.log('[EHD] Script Handler >', GM_info.scriptHandler || (navigator.userAgent.indexOf('Firefox') >= 0 ? 'GreaseMonkey' : undefined)); // (Only Tampermonkey supports GM_info.scriptHandler)
  9527. console.log('[EHD] GreaseMonkey / Tampermonkey Version >', GM_info.version);
  9528. console.log('[EHD] E-Hentai Downloader Version >', GM_info.script.version);
  9529. console.log('[EHD] E-Hentai Downloader Setting >', JSON.stringify(setting));
  9530. console.log('[EHD] Current URL >', window.location.href);
  9531. console.log('[EHD] Is Logged In >', unsafeWindow.apiuid != -1);
  9532.  
  9533. // 不知道是哪里出问题干脆直接设置默认值了 orz
  9534. if (setting['enable-multi-threading'] === undefined) setting['enable-multi-threading'] = true;
  9535.  
  9536. if (origin == 'http://r.e-hentai.org') {
  9537. origin = 'http://g.e-hentai.org';
  9538. isREH = true;
  9539. }
  9540.  
  9541. String.prototype.replaceHTMLEntites = function() {
  9542. var matchEntity = function(entity) {
  9543. var entitesList = {
  9544. 'euro': '€',
  9545. 'nbsp': ' ',
  9546. 'quot': '"',
  9547. 'amp': '&',
  9548. 'lt': '<',
  9549. 'gt': '>',
  9550. 'iexcl': '¡',
  9551. 'cent': '¢',
  9552. 'pound': '£',
  9553. 'curren': '¤',
  9554. 'yen': '¥',
  9555. 'brvbar': '¦',
  9556. 'sect': '§',
  9557. 'uml': '¨',
  9558. 'copy': '©',
  9559. 'ordf': 'ª',
  9560. 'not': '¬',
  9561. 'shy': String.fromCharCode(173),
  9562. 'reg': '®',
  9563. 'macr': '¯',
  9564. 'deg': '°',
  9565. 'plusmn': '±',
  9566. 'sup2': '²',
  9567. 'sup3': '³',
  9568. 'acute': '´',
  9569. 'micro': 'µ',
  9570. 'para': '¶',
  9571. 'middot': '·',
  9572. 'cedil': '¸',
  9573. 'sup1': '¹',
  9574. 'ordm': 'º',
  9575. 'raquo': '»',
  9576. 'frac14': '¼',
  9577. 'frac12': '½',
  9578. 'frac34': '¾',
  9579. 'iquest': '¿',
  9580. 'Agrave': 'À',
  9581. 'Aacute': 'Á',
  9582. 'Acirc': 'Â',
  9583. 'Atilde': 'Ã',
  9584. 'Auml': 'Ä',
  9585. 'Aring': 'Å',
  9586. 'AElig': 'Æ',
  9587. 'Ccedil': 'Ç',
  9588. 'Egrave': 'È',
  9589. 'Eacute': 'É',
  9590. 'Ecirc': 'Ê',
  9591. 'Euml': 'Ë',
  9592. 'Igrave': 'Ì',
  9593. 'Iacute': 'Í',
  9594. 'Icirc': 'Î',
  9595. 'Iuml': 'Ï',
  9596. 'ETH': 'Ð',
  9597. 'Ntilde': 'Ñ',
  9598. 'Ograve': 'Ò',
  9599. 'Oacute': 'Ó',
  9600. 'Ocirc': 'Ô',
  9601. 'Otilde': 'Õ',
  9602. 'Ouml': 'Ö',
  9603. 'times': '×',
  9604. 'Oslash': 'Ø',
  9605. 'Ugrave': 'Ù',
  9606. 'Uacute': 'Ú',
  9607. 'Ucirc': 'Û',
  9608. 'Uuml': 'Ü',
  9609. 'Yacute': 'Ý',
  9610. 'THORN': 'Þ',
  9611. 'szlig': 'ß',
  9612. 'agrave': 'à',
  9613. 'aacute': 'á',
  9614. 'acirc': 'â',
  9615. 'atilde': 'ã',
  9616. 'auml': 'ä',
  9617. 'aring': 'å',
  9618. 'aelig': 'æ',
  9619. 'ccedil': 'ç',
  9620. 'egrave': 'è',
  9621. 'eacute': 'é',
  9622. 'ecirc': 'ê',
  9623. 'euml': 'ë',
  9624. 'igrave': 'ì',
  9625. 'iacute': 'í',
  9626. 'icirc': 'î',
  9627. 'iuml': 'ï',
  9628. 'eth': 'ð',
  9629. 'ntilde': 'ñ',
  9630. 'ograve': 'ò',
  9631. 'oacute': 'ó',
  9632. 'ocirc': 'ô',
  9633. 'otilde': 'õ',
  9634. 'ouml': 'ö',
  9635. 'divide': '÷',
  9636. 'oslash': 'ø',
  9637. 'ugrave': 'ù',
  9638. 'uacute': 'ú',
  9639. 'ucirc': 'û',
  9640. 'uuml': 'ü',
  9641. 'yacute': 'ý',
  9642. 'thorn': 'þ'
  9643. }
  9644. if (entitesList[entity]) return entitesList[entity];
  9645. else if (entity.match(/#\d+/)) {
  9646. var charCode = entity.match(/#(\d+)/)[1] - 0;
  9647. return String.fromCharCode(charCode);
  9648. }
  9649. else return '&' + entity + ';';
  9650. }
  9651. var result = this.replace(/&(#\d+|[a-zA-Z]+);/g, function(match, entity) {
  9652. return matchEntity(entity);
  9653. });
  9654. return result;
  9655. }
  9656.  
  9657. // Fixed cross origin in r.e-hentai.org
  9658. // 发现 prototype 好方便 _(:3
  9659. String.prototype.replaceOrigin = function() {
  9660. return isREH ? this.replace('g.e-hentai.org', 'r.e-hentai.org').toString() : this.toString();
  9661. }
  9662.  
  9663. /*
  9664. function pushDialog(str, str2) {
  9665. if (str2 == null) logStr += str;
  9666. else {
  9667. lastIndex = logStr.lastIndexOf(str);
  9668. logStr = logStr.substr(0, lastIndex) + str + str2 + logStr.substr(lastIndex + str.length);
  9669. }
  9670. ehDownloadDialog.innerHTML = logStr.replace(/\n/gi, '<br>');
  9671. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  9672. }
  9673. */
  9674. function pushDialog(str) {
  9675. ehDownloadDialog.innerHTML += str.replace(/\n/gi, '<br>');
  9676. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  9677. }
  9678.  
  9679. function getReplacedName(str) {
  9680. return str.replace(/\{gid\}/gi, unsafeWindow.gid)
  9681. .replace(/\{token\}/gi, unsafeWindow.token)
  9682. .replace(/\{title\}/gi, document.getElementById('gn').textContent.replace(/[:"*?|<>\/\\\n]/g, '-'))
  9683. .replace(/\{subtitle\}/gi, document.getElementById('gj').textContent ? document.getElementById('gj').textContent.replace(/[:"*?|<>\/\\\n]/g, '-') : document.getElementById('gn').textContent.replace(/[:"*?|<>\/\\\n]/g, '-'))
  9684. .replace(/\{tag\}/gi, document.querySelector('.ic').getAttribute('alt').toUpperCase())
  9685. .replace(/\{uploader\}/gi, document.querySelector('#gdn a').textContent.replace(/[:"*?|<>\/\\\n]/g, '-'))
  9686. .replaceHTMLEntites();
  9687. }
  9688.  
  9689. function PageData(pageURL, imageURL, imageName, nextNL, realIndex) {
  9690. this.pageURL = pageURL.split('?')[0];
  9691. this.imageURL = imageURL;
  9692. /*if (!setting['number-images']) imageList.some(function(elem) {
  9693. if (elem != null && elem.imageName == imageName) {
  9694. var nameParts = imageName.split('.');
  9695. nameParts[nameParts.length - 2] += ' (' + (++elem.equalCount) + ')';
  9696. imageName = nameParts.join('.');
  9697. return 1;
  9698. }
  9699. });*/
  9700. this.imageName = imageName.trim().replace(/[:"*?|<>\/\\\n]/g, '-');
  9701. this.equalCount = 1;
  9702. this.nextNL = nextNL;
  9703. this.realIndex = realIndex;
  9704. this.imageNumber = '';
  9705. }
  9706.  
  9707. function renameImages() {
  9708. imageList.forEach(function(elem, index) {
  9709. if (!needNumberImages) {
  9710. for (var i = 0; i < index; i++) {
  9711. if (elem != null && elem.imageName.toLowerCase() == imageList[i]['imageName'].toLowerCase()) {
  9712. var nameParts = elem.imageName.split('.');
  9713. nameParts[nameParts.length - 2] += ' (' + (++imageList[i].equalCount) + ')';
  9714. elem.imageName = nameParts.join('.');
  9715. break;
  9716. }
  9717. }
  9718. }
  9719. else elem['imageName'] = elem['imageNumber'] + (setting['number-separator'] ? setting['number-separator'] : ':') + elem['imageName'];
  9720. });
  9721. }
  9722. /*
  9723. function storePageData(content) {
  9724. var imageURL = (unsafeWindow.apiuid != -1 && content.indexOf('fullimg.php') >= 0) ? content.match(RegExp('<a href="(' + origin.replace(/\./gi, '\\.') + '\/fullimg\\.php\\?\\S+?)"'))[1].replace(/&amp;/gi, '&') : content.indexOf('id="img"') > -1 ? content.match(/<img id="img" src="(\S+?)"/)[1] : content.split('href="' + nextFetchURL + '"><img', 1)[2].split('src="', 2)[1].split('"', 1)[0]; // Sometimes preview image may not have id="img", thanks to 8qwe24657913
  9725. var fileName = content.match(/g\/l.png" \/><\/a><\/div><div>([\s\S]+?) :: /)[1];
  9726. imageList.push(new PageData(fetchURL, imageURL, fileName));
  9727. pushDialog('Succeed!\nImage ' + index + ': ' + imageURL + '\n');
  9728. }
  9729. */
  9730. function storeRes(res, index) {
  9731. if (!setting['enable-multi-threading']) {
  9732. if (!needNumberImages) {
  9733. for (var i = 0; i < imageList.length, i < index - 1; i++) {
  9734. var elem = imageList[i];
  9735. if (elem != null && elem.imageName.toLowerCase() == imageList[index - 1]['imageName'].toLowerCase()) {
  9736. var nameParts = imageName.split('.');
  9737. nameParts[nameParts.length - 2] += ' (' + (++elem.equalCount) + ')';
  9738. imageName = nameParts.join('.');
  9739. break;
  9740. }
  9741. }
  9742. }
  9743. else imageList[index - 1]['imageName'] = imageList[index - 1]['imageNumber'] + (setting['number-separator'] ? setting['number-separator'] : ':') + imageList[index - 1]['imageName'];
  9744. zip.folder(dirName).file(imageList[index - 1]['imageName'], res.response);
  9745. //pushDialog('Succeed!\n');
  9746. if (index < imageList.length) {
  9747. //pushDialog('Fetching Image ' + (++index) + ': ' + imageList[index - 1]['imageName'] + ' ... ');
  9748. fetchOriginalImage(++index);
  9749. }
  9750. else {
  9751. pushDialog('Fetch images successful!');
  9752. generateZip();
  9753. zip.remove(dirName);
  9754. isDownloading = false;
  9755. //window.onbeforeunload = null;
  9756. insertCloseButton();
  9757. }
  9758. }
  9759. else {
  9760. imageData[index - 1] = res.response;
  9761. downloadedCount++;
  9762. console.log('[EHD] Index >', index, ' | RealIndex >', imageList[index - 1]['realIndex'], ' | Name >', imageList[index - 1]['imageName'], ' | RetryCount >', retryCount[index - 1], ' | DownloadedCount >', downloadedCount, ' | FetchCount >', fetchCount, ' | FailedCount >', failedCount);
  9763. fetchCount--;
  9764. /*var preStr = 'Fetching Image ' + (index) + ': ' + imageList[index - 1]['imageName'] + ' ... ';
  9765. for (var i = 0; i < retryCount[index - 1]; i++) preStr += 'Failed! Retrying... ';
  9766. pushDialog(preStr, 'Succeed!');*/
  9767. if (downloadedCount + failedCount < imageList.length) {
  9768. for (var i = fetchCount; i < (setting['thread-count'] != null ? setting['thread-count'] : 5); i++) {
  9769. for (var j = 0; j < imageList.length; j++) {
  9770. if (imageData[j] == null) {
  9771. imageData[j] = 'Fetching';
  9772. //pushDialog('Fetching Image ' + (j + 1) + ': ' + imageList[j]['imageName'] + ' ... \n');
  9773. fetchOriginalImage(j + 1);
  9774. fetchCount++;
  9775. break;
  9776. }
  9777. }
  9778. }
  9779. }
  9780. else if (failedCount > 0) {
  9781. if (fetchCount == 0) {
  9782. for (var i = 0; i < fetchThread.length; i++) fetchThread[i].abort();
  9783. if (confirm('Some images were failed to download. Would you like to try them again?')) {
  9784. retryAllFailed();
  9785. }
  9786. else {
  9787. pushDialog('\nFetch images failed.');
  9788. if (confirm('Fetch images failed, Please try again later.\n\nWould you like to download downloaded images?')) {
  9789. //window.open('data:text/plain,' + logStr);
  9790. renameImages();
  9791. for (var j = 0; j < imageData.length; j++) {
  9792. if (imageData[j] != null && imageData[j] != 'Fetching') {
  9793. zip.folder(dirName).file(imageList[j]['imageName'], imageData[j]);
  9794. imageData[j] = null;
  9795. }
  9796. }
  9797. generateZip();
  9798. }
  9799. zip.remove(dirName);
  9800. isDownloading = false;
  9801. //window.onbeforeunload = null;
  9802. insertCloseButton();
  9803. }
  9804. }
  9805. }
  9806. else {
  9807. renameImages();
  9808. for (var j = 0; j < imageList.length; j++) {
  9809. zip.folder(dirName).file(imageList[j]['imageName'], imageData.shift());
  9810. }
  9811. generateZip();
  9812. zip.remove(dirName);
  9813. isDownloading = false;
  9814. //window.onbeforeunload = null;
  9815. insertCloseButton();
  9816. }
  9817. }
  9818. }
  9819.  
  9820. function generateZip(){
  9821. imageList.forEach(function(elem, index){
  9822. logStr += '\n\nPage ' + elem['realIndex'] + ': ' + elem['pageURL'] + '\nImage ' + elem['realIndex'] + ': ' + elem['imageName'] + '\nImage URL: ' + elem['imageURL'];
  9823. });
  9824. pushDialog('\n\nFinish downloading at ' + new Date());
  9825. logStr += '\n\nFinish downloading at ' + new Date() + '\n\nGenerated by E-Hentai Downloader. https://github.com/ccloli/E-Hentai-Downloader';
  9826. zip.folder(dirName).file('info.txt', logStr.replace(/\n/gi, '\r\n'));
  9827. var data = zip.generate({type: 'blob', compression: setting['compression-level'] ? 'DEFLATE' : 'STORE', compressionOptions: {level: setting['compression-level'] > 0 ? (setting['compression-level'] < 10 ? setting['compression-level'] : 9) : 1}});
  9828. saveAs(data, fileName + '.zip');
  9829. pushDialog('\n\nNot download? <a href="' + window.URL.createObjectURL(data) + '" download="' + fileName + '.zip" style="color: #ffffff; font-weight: bold;">Click here to download</a>\n\n');
  9830. }
  9831.  
  9832. function failedFetching(index, node){
  9833. //console.log(downloadedCount, failedCount)
  9834. 'abort' in fetchThread[index - 1] && fetchThread[index - 1].abort();
  9835. if (!setting['enable-multi-threading']) {
  9836. if (retryCount < (setting['retry-count'] != null ? setting['retry-count'] : 3)) {
  9837. //pushDialog('Failed! Retrying... ');
  9838. retryCount++;
  9839. fetchOriginalImage(index, node);
  9840. }
  9841. else {
  9842. node.innerHTML = '<td>#' + imageList[index - 1]['realIndex'] + ': ' + imageList[index - 1]['imageName'] + '</td><td width="210"><progress style="width: 200px;" value="0"></progress></td><td style="color: #ff0000;">Failed!</td>';
  9843. pushDialog('\nFetch images failed.');
  9844. if (confirm('Fetch images failed, Please try again later.\n\nWould you like to download downloaded images?')) {
  9845. //window.open('data:text/plain,' + logStr);
  9846. generateZip();
  9847. }
  9848. zip.remove(dirName);
  9849. isDownloading = false;
  9850. //window.onbeforeunload = null;
  9851. insertCloseButton();
  9852. }
  9853. }
  9854. else {
  9855. console.error('[EHD] Index >', index, ' | RealIndex >', imageList[index - 1]['realIndex'], ' | Name >', imageList[index - 1]['imageName'], ' | RetryCount >', retryCount[index - 1], ' | DownloadedCount >', downloadedCount, ' | FetchCount >', fetchCount, ' | FailedCount >', failedCount);
  9856. if (retryCount[index - 1] < (setting['retry-count'] != null ? setting['retry-count'] : 3)) {
  9857. /*var preStr = 'Fetching Image ' + index + ': ' + imageList[index - 1]['imageName'] + ' ... ';
  9858. for (var i = 0; i < retryCount[index - 1]; i++) preStr += 'Failed! Retrying... ';
  9859. pushDialog(preStr, 'Failed! Retrying... ');*/
  9860. retryCount[index - 1]++;
  9861. fetchOriginalImage(index, node);
  9862. }
  9863. else {
  9864. //pushDialog('Fetching Image ' + index + ': ' + imageList[index - 1]['imageName'] + ' ... Failed! Retrying... Failed! Retrying... Failed! Retrying... ', 'Failed!');
  9865. node.innerHTML = '<td>#' + imageList[index - 1]['realIndex'] + ': ' + imageList[index - 1]['imageName'] + '</td><td width="210"><progress style="width: 200px;" value="0"></progress></td><td style="color: #ff0000;">Failed!</td>';
  9866. imageList[index - 1]['imageFinalURL'] = null;
  9867. failedCount++;
  9868. fetchCount--;
  9869. if (fetchCount == 0) {
  9870. for (var i = 0; i < fetchThread.length; i++) fetchThread[i].abort();
  9871. if (confirm('Some images were failed to download. Would you like to try them again?')) {
  9872. retryAllFailed();
  9873. }
  9874. else {
  9875. pushDialog('\nFetch images failed.');
  9876. if (confirm('Fetch images failed, Please try again later.\n\nWould you like to download downloaded images?')) {
  9877. //window.open('data:text/plain,' + logStr);
  9878. renameImages();
  9879. for (var j = 0; j < imageData.length; j++) {
  9880. if (imageData[j] != null && imageData[j] != 'Fetching') {
  9881. zip.folder(dirName).file(imageList[j]['imageName'], imageData[j]);
  9882. imageData[j] = null;
  9883. }
  9884. }
  9885. generateZip();
  9886. }
  9887. zip.remove(dirName);
  9888. isDownloading = false;
  9889. //window.onbeforeunload = null;
  9890. insertCloseButton();
  9891. }
  9892. }
  9893. else {
  9894. if (downloadedCount + failedCount < imageList.length) {
  9895. for (var i = fetchCount; i < (setting['thread-count'] != null ? setting['thread-count'] : 5); i++) {
  9896. for (var j = 0; j < imageList.length; j++) {
  9897. if (imageData[j] == null) {
  9898. imageData[j] = 'Fetching';
  9899. //pushDialog('Fetching Image ' + (j + 1) + ': ' + imageList[j]['imageName'] + ' ... \n');
  9900. fetchOriginalImage(j + 1);
  9901. fetchCount++;
  9902. break;
  9903. }
  9904. }
  9905. }
  9906. }
  9907. }
  9908. }
  9909. }
  9910. }
  9911.  
  9912. function fetchOriginalImage(index, node) {
  9913. // GM_xhr 于 GreaseMonkey 2.3 / 2.4 中开始支持 responseType 以获取返回类型为 ArrayBuffer 的请求
  9914. // GM_xhr support responseType to fetch ArrayBuffer request on 2.3 / 2.4
  9915. // https://github.com/greasemonkey/greasemonkey/issues/1834
  9916. //console.log(imageList[index - 1]);
  9917. if (retryCount[index - 1] == null) retryCount[index - 1] = 0;
  9918. if (node == null) {
  9919. var node = document.createElement('tr');
  9920. node.innerHTML = '<td>#' + imageList[index - 1]['realIndex'] + ': ' + imageList[index - 1]['imageName'] + '</td><td width="210"><progress style="width: 200px;"></progress></td><td>Pending...</td>';
  9921. progressTable.appendChild(node);
  9922. }
  9923. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  9924. //console.log(retryCount);
  9925. fetchThread[index - 1] = GM_xmlhttpRequest({
  9926. method: 'GET',
  9927. url: imageList[index - 1]['imageFinalURL'] || imageList[index - 1]['imageURL'],
  9928. responseType: 'arraybuffer',
  9929. //overrideMimeType: window.MSBlobBuilder ? 'text/plain; charset=x-user-defined' : undefined,
  9930. // timeout is failed in Chrome Tampermonkey
  9931. timeout: setting['timeout'] != null ? Number(setting['timeout']) * 1000 : 300000,
  9932. headers: {
  9933. /*'Upgrade-Insecure-Requests': 1,
  9934. 'Cache-Control': 'max-age=0'*/
  9935. 'Referer': imageList[index - 1]['pageURL'],
  9936. 'X-Alt-Referer': imageList[index - 1]['pageURL']
  9937. },
  9938. onprogress: function(res) {
  9939. node.innerHTML = '<td>#' + imageList[index - 1]['realIndex'] + ': ' + imageList[index - 1]['imageName'] + '</td><td width="210"><progress style="width: 200px;" value="' + (res.lengthComputable ? res.loaded / res.total : '') + '"></progress></td><td>' + (retryCount[index - 1] == 0 ? 'Downloading...' : 'Retrying (' + (!setting['enable-multi-threading'] ? retryCount : retryCount[index - 1]) + '/' + (setting['retry-count'] != null ? setting['retry-count'] : 3) +') ...') + '</td>';
  9940. },
  9941. onload: function(res) {
  9942. //console.log(res);
  9943. if (res.responseHeaders.split('Content-Type:')[1].split('\n')[0].split('/')[0].trim() != 'image') {
  9944. console.log('[EHD] #' + index + ': Wrong Content-Type');
  9945. console.log('[EHD] #' + index + ': RealIndex >', imageList[index - 1]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nResposeHeaders >' + res.responseHeaders);
  9946. node.innerHTML = '<td>#' + imageList[index - 1]['realIndex'] + ': ' + imageList[index - 1]['imageName'] + '</td><td width="210"><progress style="width: 200px;" value="0"></progress></td><td style="color: #ffff00;">Failed! (Wrong MIME)</td>';
  9947. return failedFetching(index, node);
  9948. }
  9949. if (!res.response) {
  9950. var data = {
  9951. response: new ArrayBuffer(res.responseText.length),
  9952. readyState: res.readyState,
  9953. status: res.status,
  9954. statusText: res.statusText,
  9955. responseHeaders: res.responseHeaders
  9956. };
  9957. var uint8data = new Uint8Array(data.response);
  9958. for (var i = 0, len = res.responseText.length; i < len; ++i) {
  9959. uint8data[i] = res.responseText.charCodeAt(i) & 0xff;
  9960. }
  9961. var res = data;
  9962. }
  9963. if (res.response.byteLength == 925) { // '403 Access Denied' Image Byte Size
  9964. //fetchThread[index - 1].dispatchEvent(new Event('error'));
  9965. // GM_xhr only support abort()
  9966. console.log('[EHD] #' + index + ': 403 Access Denied');
  9967. console.log('[EHD] #' + index + ': RealIndex >', imageList[index - 1]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nResposeHeaders >' + res.responseHeaders);
  9968. node.innerHTML = '<td>#' + imageList[index - 1]['realIndex'] + ': ' + imageList[index - 1]['imageName'] + '</td><td width="210"><progress style="width: 200px;" value="0"></progress></td><td style="color: #ffff00;">Failed! (Error 403)</td>';
  9969. return failedFetching(index, node);
  9970. }
  9971. else if (res.response.byteLength == 28) { // 'An error has occurred. (403)' Length
  9972. console.log('[EHD] #' + index + ': An error has occurred. (403)');
  9973. console.log('[EHD] #' + index + ': RealIndex >', imageList[index - 1]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nResposeHeaders >' + res.responseHeaders);
  9974. node.innerHTML = '<td>#' + imageList[index - 1]['realIndex'] + ': ' + imageList[index - 1]['imageName'] + '</td><td width="210"><progress style="width: 200px;" value="0"></progress></td><td style="color: #ffff00;">Failed! (Error 403)</td>';
  9975. return failedFetching(index, node);
  9976. }
  9977. else if (res.response.byteLength == 141) { // Image Viewing Limits String Byte Size
  9978. for (var i = 0; i < fetchThread.length; i++) fetchThread[i].abort();
  9979. console.log('[EHD] #' + index + ': Exceed Image Viewing Limits');
  9980. console.log('[EHD] #' + index + ': RealIndex >', imageList[index - 1]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nResposeHeaders >' + res.responseHeaders);
  9981. node.innerHTML = '<td>#' + imageList[index - 1]['realIndex'] + ': ' + imageList[index - 1]['imageName'] + '</td><td width="210"><progress style="width: 200px;" value="0"></progress></td><td style="color: #ffff00;">Failed! (Exceed Limits)</td>';
  9982. pushDialog('\nYou have exceeded your image viewing limits.');
  9983. if (confirm('You have exceeded your image viewing limits. You can reset these limits at home page.\n\nWould you like to save downloaded images?')) {
  9984. renameImages();
  9985. for (var j = 0; j < imageData.length; j++) {
  9986. if (imageData[j] != null && imageData[j] != 'Fetching') {
  9987. zip.folder(dirName).file(imageList[j]['imageName'], imageData[j]);
  9988. imageData[j] = null;
  9989. }
  9990. }
  9991. generateZip();
  9992. }
  9993. zip.remove(dirName);
  9994. isDownloading = false;
  9995. //window.onbeforeunload = null;
  9996. insertCloseButton();
  9997. return;
  9998. }
  9999. else if (res.response.byteLength == 28658) { // '509 Bandwidth Exceeded' Image Byte Size
  10000. for (var i = 0; i < fetchThread.length; i++) fetchThread[i].abort();
  10001. console.log('[EHD] #' + index + ': 509 Bandwidth Exceeded');
  10002. console.log('[EHD] #' + index + ': RealIndex >', imageList[index - 1]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nResposeHeaders >' + res.responseHeaders);
  10003. node.innerHTML = '<td>#' + imageList[index - 1]['realIndex'] + ': ' + imageList[index - 1]['imageName'] + '</td><td width="210"><progress style="width: 200px;" value="0"></progress></td><td style="color: #ffff00;">Failed! (Error 509)</td>';
  10004. pushDialog('\nYou have exceeded your bandwidth limits.');
  10005. if (confirm('You have temporarily reached the limit for how many images you can browse. You can\n- Sign up/in E-Hentai account at E-Hentai Forums to get double daily quota if you are not sign in.\n- Run the Hentai@Home to support E-Hentai and get more points to increase your limit.\n- Check back in a few hours, and you will be able to download more.\n\nWould you like to save downloaded images?')) {
  10006. renameImages();
  10007. for (var j = 0; j < imageData.length; j++) {
  10008. if (imageData[j] != null && imageData[j] != 'Fetching') {
  10009. zip.folder(dirName).file(imageList[j]['imageName'], imageData[j]);
  10010. imageData[j] = null;
  10011. }
  10012. }
  10013. generateZip();
  10014. }
  10015. zip.remove(dirName);
  10016. isDownloading = false;
  10017. //window.onbeforeunload = null;
  10018. insertCloseButton();
  10019. return;
  10020. }
  10021. // if (imageList.indexOf('fullimg.php') >= 0) imageList[index - 1]['imageFinalURL'] = res.finalUrl; // 看起来没什么用
  10022. imageList[index - 1]['imageName'] = res.responseHeaders.match(/filename=([\s\S]+?)\n/) ? res.responseHeaders.match(/filename=([\s\S]+?)\n/)[1].trim().replace(/[:"*?|<>\/\\\n]/g, '-') : imageList[index - 1]['imageName'];
  10023. node.innerHTML = '<td>#' + imageList[index - 1]['realIndex'] + ': ' + imageList[index - 1]['imageName'] + '</td><td width="210"><progress style="width: 200px;" value="1"></progress></td><td style="color: #00ff00;">Succeed!</td>';
  10024. storeRes(res, index);
  10025. },
  10026. onerror: function(res){
  10027. console.log('[EHD] #' + index + ': Network Error');
  10028. console.log('[EHD] #' + index + ': RealIndex >', imageList[index - 1]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nResposeHeaders >' + res.responseHeaders);
  10029. node.innerHTML = '<td>#' + imageList[index - 1]['realIndex'] + ': ' + imageList[index - 1]['imageName'] + '</td><td width="210"><progress style="width: 200px;" value="0"></progress></td><td style="color: #ffff00;">Failed! (Network Error)</td>';
  10030. if (imageList[index - 1]['imageURL'].indexOf('fullimg.php') >= 0) imageList[index - 1]['imageFinalURL'] = res.finalUrl;
  10031. failedFetching(index, node);
  10032. },
  10033. ontimeout: function(res){
  10034. console.log('[EHD] #' + index + ': Timed Out');
  10035. console.log('[EHD] #' + index + ': RealIndex >', imageList[index - 1]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nResposeHeaders >' + res.responseHeaders);
  10036. node.innerHTML = '<td>#' + imageList[index - 1]['realIndex'] + ': ' + imageList[index - 1]['imageName'] + '</td><td width="210"><progress style="width: 200px;" value="0"></progress></td><td style="color: #ffff00;">Failed! (Timed out)</td>';
  10037. if (imageList[index - 1]['imageURL'].indexOf('fullimg.php') >= 0) imageList[index - 1]['imageFinalURL'] = res.finalUrl;
  10038. failedFetching(index, node);
  10039. }
  10040. });
  10041. }
  10042.  
  10043. function retryAllFailed(){
  10044. //failedCount = 0;
  10045. var index, refetch = 0;
  10046. progressTable = document.createElement('table');
  10047. progressTable.style.width = '100%';
  10048. if (!setting['never-new-url']) {
  10049. //var xhr = new XMLHttpRequest();
  10050. xhr.onload = function() {
  10051. var imageURL = (unsafeWindow.apiuid != -1 && xhr.responseText.indexOf('fullimg.php') >= 0 && !setting['force-resized']) ? xhr.responseText.match(RegExp('<a href="(' + origin.replace(/\./gi, '\\.') + '\/fullimg\\.php\\?\\S+?)"'))[1].replaceHTMLEntites() : xhr.responseText.indexOf('id="img"') > -1 ? xhr.responseText.match(/<img id="img" src="(\S+?)"/)[1].replaceHTMLEntites() : xhr.responseText.match(/<\/iframe><a[\s\S]+?><img src="(\S+?)"/)[1].replaceHTMLEntites(); // Sometimes preview image may not have id="img"
  10052. imageList[index]['imageURL'] = imageURL;
  10053. var nextNL = /return nl\('[\d-]+'\)/.test(xhr.responseText) ? xhr.responseText.match(/return nl\('([\d-]+)'\)/)[1] : null;
  10054. imageList[index]['nextNL'] = nextNL;
  10055. failedCount--;
  10056. pushDialog('Succeed!\nImage ' + (index + 1) + ': ' + imageURL + '\n');
  10057. if (failedCount == 0) {
  10058. ehDownloadDialog.appendChild(progressTable);
  10059. for (var i = fetchCount; i < (setting['thread-count'] != null ? setting['thread-count'] : 5); i++) {
  10060. for (var j = 0; j < imageList.length; j++) {
  10061. if (imageData[j] == null) {
  10062. imageData[j] = 'Fetching';
  10063. //pushDialog('Fetching Image ' + (j + 1) + ': ' + imageList[j]['imageName'] + ' ... \n');
  10064. fetchOriginalImage(j + 1);
  10065. fetchCount++;
  10066. break;
  10067. }
  10068. }
  10069. }
  10070. }
  10071. else {
  10072. /*var _index = ++index;
  10073. for (; index < imageData.length; index++) {
  10074. if (imageData[index] == 'Fetching') {
  10075. imageData[index] = null;
  10076. retryCount[index] = 0;
  10077. //console.log(j);
  10078. }
  10079. }*/
  10080. ++index;
  10081. for (/*index = _index*/; index < imageData.length; index++) {
  10082. if (imageData[index] == null) {
  10083. if (!setting['never-new-url']) {
  10084. if (imageList[index]['imageURL'].indexOf('fullimg.php') < 0) {
  10085. var _fetchURL = (imageList[index]['pageURL'] + ((!setting['never-send-nl'] && imageList[index]['nextNL']) ? (imageList[index]['pageURL'].indexOf('?') >= 0 ? '&' : '?') + 'nl=' + imageList[index]['nextNL'] : '')).replaceHTMLEntites();
  10086. imageList[index]['pageURL'] = _fetchURL;
  10087. pushDialog('Fetching Page ' + (index + 1) + ': ' + _fetchURL + ' ... ');
  10088. xhr.open('GET', _fetchURL);
  10089. xhr.timeout = 30000;
  10090. xhr.send();
  10091. refetch = 1;
  10092. break;
  10093. }
  10094. else failedCount--;
  10095. }
  10096. }
  10097. }
  10098. }
  10099. }
  10100. xhr.onerror = xhr.ontimeout = function() {
  10101. if (retryCount < (setting['retry-count'] != null ? setting['retry-count'] : 3)) {
  10102. pushDialog('Failed! Retrying... ');
  10103. retryCount++;
  10104. xhr.open('GET', fetchURL);
  10105. xhr.timeout = 30000;
  10106. xhr.send();
  10107. }
  10108. else {
  10109. pushDialog('Failed! Skip and continue...');
  10110. refetch = 0;
  10111. ++index;
  10112. /*var _index = ++index;
  10113. for (; index < imageData.length; index++) {
  10114. if (imageData[index] == 'Fetching') {
  10115. imageData[index] = null;
  10116. retryCount[index] = 0;
  10117. //console.log(j);
  10118. }
  10119. }*/
  10120. for (/*index = _index*/; index < imageData.length; index++) {
  10121. if (imageData[index] == null) {
  10122. if (!setting['never-new-url']) {
  10123. if (imageList[index]['imageURL'].indexOf('fullimg.php') < 0) {
  10124. var _fetchURL = (imageList[index]['pageURL'] + ((!setting['never-send-nl'] && imageList[index]['nextNL']) ? (imageList[index]['pageURL'].indexOf('?') >= 0 ? '&' : '?') + 'nl=' + imageList[index]['nextNL'] : '')).replaceHTMLEntites();
  10125. imageList[index]['pageURL'] = _fetchURL;
  10126. pushDialog('Fetching Page ' + (index + 1) + ': ' + _fetchURL + ' ... ');
  10127. xhr.open('GET', _fetchURL);
  10128. xhr.timeout = 30000;
  10129. xhr.send();
  10130. refetch = 1;
  10131. break;
  10132. }
  10133. else failedCount--;
  10134. }
  10135. }
  10136. }
  10137. if (!refetch) {
  10138. ehDownloadDialog.appendChild(progressTable);
  10139. for (var i = fetchCount; i < (setting['thread-count'] != null ? setting['thread-count'] : 5); i++) {
  10140. for (var j = 0; j < imageList.length; j++) {
  10141. if (imageData[j] == null) {
  10142. imageData[j] = 'Fetching';
  10143. //pushDialog('Fetching Image ' + (j + 1) + ': ' + imageList[j]['imageName'] + ' ... \n');
  10144. fetchOriginalImage(j + 1);
  10145. fetchCount++;
  10146. break;
  10147. }
  10148. }
  10149. }
  10150. }
  10151. }
  10152. }
  10153. }
  10154. for (index = 0; index < imageData.length; index++) {
  10155. if (imageData[index] == 'Fetching') {
  10156. imageData[index] = null;
  10157. retryCount[index] = 0;
  10158. /*retryCount[j] = 0;*/
  10159. //console.log(j);
  10160. }
  10161. }
  10162. for (index = 0; index < imageData.length; index++) {
  10163. if (imageData[index] == null) {
  10164. if (!setting['never-new-url']) {
  10165. if (imageList[index]['imageURL'].indexOf('fullimg.php') < 0) {
  10166. var _fetchURL = (imageList[index]['pageURL'] + ((!setting['never-send-nl'] && imageList[index]['nextNL']) ? (imageList[index]['pageURL'].indexOf('?') >= 0 ? '&' : '?') + 'nl=' + imageList[index]['nextNL'] : '')).replaceHTMLEntites();
  10167. imageList[index]['pageURL'] = _fetchURL;
  10168. pushDialog('Fetching Page ' + (index + 1) + ': ' + _fetchURL + ' ... ');
  10169. xhr.open('GET', _fetchURL);
  10170. xhr.timeout = 30000;
  10171. xhr.send();
  10172. refetch = 1;
  10173. break;
  10174. }
  10175. else failedCount--;
  10176. }
  10177. }
  10178. }
  10179. if (!refetch) {
  10180. ehDownloadDialog.appendChild(progressTable);
  10181. for (var i = fetchCount; i < (setting['thread-count'] != null ? setting['thread-count'] : 5); i++) {
  10182. for (var j = 0; j < imageList.length; j++) {
  10183. if (imageData[j] == null) {
  10184. imageData[j] = 'Fetching';
  10185. //pushDialog('Fetching Image ' + (j + 1) + ': ' + imageList[j]['imageName'] + ' ... \n');
  10186. fetchOriginalImage(j + 1);
  10187. fetchCount++;
  10188. break;
  10189. }
  10190. }
  10191. }
  10192. }
  10193. }
  10194.  
  10195. function insertCloseButton() {
  10196. var exitButton = document.createElement('button');
  10197. exitButton.style.display = 'block';
  10198. exitButton.style.margin = '0 auto';
  10199. exitButton.textContent = 'Close';
  10200. exitButton.onclick = function(){
  10201. ehDownloadDialog.removeChild(exitButton);
  10202. ehDownloadDialog.style.display = 'none';
  10203. }
  10204. ehDownloadDialog.appendChild(exitButton);
  10205. ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight;
  10206. }
  10207.  
  10208. function getAllPagesURL() {
  10209. pagesRange = [];
  10210. var pagesRangeText = ehDownloadRange.querySelector('input').value.replace(/,/g, ',').trim();
  10211. console.log('[EHD] Pages Range >', pagesRangeText);
  10212. if (!/^(\d+(-\d+)?\s*?,\s*?)*\d+(-\d+)?$/.test(pagesRangeText)) return alert('Pages Range is not correct.');
  10213. var pagesRangeScale = pagesRangeText.match(/\d+-\d+|\d+/g);
  10214. pagesRangeScale.forEach(function(elem){
  10215. if (elem.indexOf('-') < 0) {
  10216. var curElem = Number(elem);
  10217. if (!pagesRange.some(function(e){ return curElem == e; })) pagesRange.push(curElem);
  10218. }
  10219. else {
  10220. for (var i = Number(elem.split('-')[0]); i <= Number(elem.split('-')[1]); Number(elem.split('-')[0]) < Number(elem.split('-')[1]) ? i++ : i--) {
  10221. if (!pagesRange.some(function(e){ return i == e; })) pagesRange.push(i);
  10222. }
  10223. }
  10224. });
  10225. pagesRange.sort(function(a, b){ return a > b ? 1 : -1; });
  10226. ehDownloadDialog.style.display = 'block';
  10227. if (!getAllPagesURLFin) {
  10228. pageURLsList = [];
  10229. var pagesCount = [].reduce.call(document.querySelectorAll('.ptt td'), function(x, y){
  10230. var i = Number(y.textContent);
  10231. //console.log(i);
  10232. if (!isNaN(i)) return x > i ? x : i;
  10233. else return x;
  10234. });
  10235. var curPage = 0;
  10236. retryCount = 0;
  10237. //var xhr = new XMLHttpRequest();
  10238. xhr.onload = function(){
  10239. var pagesURL = xhr.responseText.split('<div id="gdt">')[1].split('<div class="c">')[0].match(/(?:<a href=").+?(?=")/gi);
  10240. for (var i = 0; i < pagesURL.length; i++) {
  10241. pageURLsList.push(pagesURL[i].split('"')[1].replaceHTMLEntites().replaceOrigin());
  10242. }
  10243. pushDialog('Succeed!');
  10244. curPage++;
  10245. if (curPage == pagesCount) {
  10246. getAllPagesURLFin = true;
  10247. var wrongPages = pagesRange.filter(function(elem){ return elem > pageURLsList.length; });
  10248. if (wrongPages.length != 0) {
  10249. pagesRange = pagesRange.filter(function(elem){ return elem <= pageURLsList.length; });
  10250. alert('Page ' + wrongPages.join(', ') + (wrongPages.length > 1 ? ' are' : ' is') + ' not exist, and will be ignored.');
  10251. }
  10252. pushDialog('\n\n');
  10253. ehDownload();
  10254. }
  10255. else {
  10256. xhr.open('GET', location.pathname + '?p=' + curPage);
  10257. xhr.send();
  10258. pushDialog('\nFetching Archive Pages URL (' + (curPage + 1) + '/' + pagesCount + ') ... ');
  10259. }
  10260. }
  10261. xhr.ontimeout = xhr.onerror = function(){
  10262. if (retryCount < (setting['retry-count'] != null ? setting['retry-count'] : 3)) {
  10263. pushDialog('Failed! Retrying... ');
  10264. retryCount++;
  10265. xhr.open('GET', location.pathname + '?p=' + curPage);
  10266. xhr.timeout = 30000;
  10267. xhr.send();
  10268. }
  10269. else {
  10270. pushDialog('Failed!\nFetch Pages\' URL failed, Please try again later.');
  10271. isDownloading = false;
  10272. //window.onbeforeunload = null;
  10273. insertCloseButton();
  10274. alert('Fetch Pages\' URL failed, Please try again later.');
  10275. }
  10276. }
  10277. xhr.open('GET', location.pathname + '?p=' + curPage);
  10278. xhr.timeout = 30000;
  10279. xhr.send();
  10280. pushDialog('\nFetching Archive Pages URL (' + (curPage + 1) + '/' + pagesCount + ') ... ');
  10281. }
  10282. else {
  10283. var wrongPages = pagesRange.filter(function(elem){ return elem > pageURLsList.length; });
  10284. if (wrongPages.length != 0) {
  10285. pagesRange = pagesRange.filter(function(elem){ return elem <= pageURLsList.length; });
  10286. alert('Page ' + wrongPages.join(', ') + (wrongPages.length > 1 ? ' are' : ' is') + ' not exist, and will be ignored.');
  10287. }
  10288. ehDownload();
  10289. }
  10290. }
  10291.  
  10292. function ehDownload() {
  10293. xhr.abort();
  10294. for (var i = 0; i < fetchThread.length; i++) fetchThread[i].abort();
  10295. imageList = [];
  10296. imageData = [];
  10297. fetchThread = [];
  10298. zip = new JSZip();
  10299. var index = 0;
  10300. dirName = getReplacedName((!setting['dir-name'] || setting['dir-name'] == '') ? '{gid}_{token}' : setting['dir-name']);
  10301. fileName = getReplacedName((!setting['file-name'] || setting['file-name'] == '') ? '{title}' : setting['file-name']);
  10302. if (dirName == '/') dirName = '';
  10303. retryCount = downloadedCount = fetchCount = failedCount = 0;
  10304. needNumberImages = ehDownloadNumberInput.querySelector('input').checked;
  10305. //console.log(needNumberImages);
  10306. logStr = document.getElementById('gn').textContent.replaceHTMLEntites() + '\n'
  10307. + document.getElementById('gj').textContent.replaceHTMLEntites() + '\n'
  10308. + window.location.href.replaceHTMLEntites() + '\n\n'
  10309. + 'Category: ' + document.getElementsByClassName('ic')[0].getAttribute('alt').toUpperCase() + '\n'
  10310. + 'Uploader: ' + document.querySelector('#gdn a').textContent.replaceHTMLEntites() + '\n';
  10311. var metaNodes = document.querySelectorAll('#gdd tr');
  10312. for (var i = 0; i < metaNodes.length; i++) {
  10313. var c1 = metaNodes[i].getElementsByClassName('gdt1')[0].textContent.replaceHTMLEntites();
  10314. var c2 = metaNodes[i].getElementsByClassName('gdt2')[0].textContent.replaceHTMLEntites();
  10315. logStr += c1 + ' ' + c2 + '\n';
  10316. if (c1 == 'File Size:' && ((c2.indexOf('TB') > 0 || c2.indexOf('GB') > 0 || (c2.indexOf('MB') > 0 && parseFloat(c2) >= 500)))) {
  10317. if (!confirm('This archive is too large (original size), please consider downloading this archive in other way.\n\nMaximum allowed file size: Chrome / Opera 15+ 500MiB | IE 10+ 600 MiB | Firefox 20+ 800 MiB\n(From FileSaver.js introduction)\n\nAre you sure to continue downloading? Please also consider your operating system\'s free memory, it may takes about double size of archive file size when generating ZIP file.')) return;
  10318. }
  10319. }
  10320. logStr += 'Rating: ' + unsafeWindow.original_rating + '\n\n';
  10321. if (document.getElementById("comment_0")) {
  10322. logStr += 'Uploader Comment:\n' + document.getElementById("comment_0").innerHTML.replace(/<br>|<br \/>/gi, '\n') + '\n\n';
  10323. }
  10324. isDownloading = true;
  10325. progressTable = document.createElement('table');
  10326. progressTable.style.width = '100%';
  10327. ehDownloadDialog.style.display = 'block';
  10328. pushDialog(logStr);
  10329. if (getAllPagesURLFin) {
  10330. var rangeIndex = 0;
  10331. if (pagesRange.length == 0) var fetchURL = pageURLsList[rangeIndex];
  10332. else var fetchURL = pageURLsList[pagesRange[rangeIndex] - 1];
  10333. }
  10334. else {
  10335. pageURLsList = [];
  10336. var fetchURL = document.querySelector('#gdt a').getAttribute('href').replaceHTMLEntites().replaceOrigin();
  10337. }
  10338. //console.log(fetchURL);
  10339. //var xhr = new XMLHttpRequest();
  10340. xhr.onload = function() {
  10341. if (index == 0) {
  10342. index = 1;
  10343. if (!getAllPagesURLFin) {
  10344. var firstURL = xhr.responseText.match(RegExp('<div class="sn"><a[\\s\\S]+?href="(' + origin.replace(/\./gi, '\\.') + '\\/s\\/\\S+?)"'))[1].replaceHTMLEntites().replaceOrigin();
  10345. //console.log(firstURL);
  10346. //console.log(fetchURL == firstURL)
  10347. if (firstURL != fetchURL) {
  10348. pushDialog('Error! This is not the first page!\n');
  10349. pushDialog('Fetching Page 1: ' + firstURL + ' ... ');
  10350. fetchURL = firstURL;
  10351. xhr.open('GET', firstURL);
  10352. xhr.timeout = 30000;
  10353. xhr.send();
  10354. return;
  10355. }
  10356. }
  10357. }
  10358. retryCount = 0;
  10359. var realIndex = (pagesRange.length != 0 ? pagesRange[Math.min(rangeIndex, pagesRange.length - 1)] : index);
  10360. //storePageData(xhr.responseText);
  10361. if (getAllPagesURLFin) {
  10362. rangeIndex++;
  10363. if (pagesRange.length == 0) var nextFetchURL = pageURLsList[Math.min(rangeIndex, pageURLsList.length - 1)];
  10364. else var nextFetchURL = pageURLsList[pagesRange[Math.min(rangeIndex, pagesRange.length - 1)] - 1];
  10365. }
  10366. else {
  10367. pageURLsList.push(fetchURL);
  10368. var nextFetchURL = xhr.responseText.indexOf('<a id="next"') >= 0 ? xhr.responseText.match(RegExp('<a id="next"[\\s\\S]+?href="(' + origin.replace(/\./gi, '\\.') + '\\/s\\/\\S+?)"'))[1].replaceHTMLEntites().replaceOrigin() : xhr.responseText.match(RegExp('<a href="(' + origin.replace(/\./gi, '\\.') + '\\/s\\/\\S+?)"><img src="http://ehgt.org/g/n.png"'))[1].replaceHTMLEntites().replaceOrigin();
  10369. }
  10370. var imageURL = (unsafeWindow.apiuid != -1 && xhr.responseText.indexOf('fullimg.php') >= 0 && !setting['force-resized']) ? xhr.responseText.match(RegExp('<a href="(' + origin.replace(/\./gi, '\\.') + '\/fullimg\\.php\\?\\S+?)"'))[1].replaceHTMLEntites().replaceOrigin() : xhr.responseText.indexOf('id="img"') > -1 ? xhr.responseText.match(/<img id="img" src="(\S+?)"/)[1].replaceHTMLEntites() : xhr.responseText.match(/<\/iframe><a[\s\S]+?><img src="(\S+?)"/)[1].replaceHTMLEntites(); // Sometimes preview image may not have id="img"
  10371. var fileName = xhr.responseText.match(/g\/l.png" \/><\/a><\/div><div>([\s\S]+?) :: /)[1].replaceHTMLEntites();
  10372. var nextNL = /return nl\('[\d-]+'\)/.test(xhr.responseText) ? xhr.responseText.match(/return nl\('([\d-]+)'\)/)[1] : null;
  10373. imageList.push(new PageData(fetchURL, imageURL, fileName, nextNL, realIndex));
  10374. index++;
  10375. pushDialog('Succeed!\nImage ' + realIndex + ': ' + imageURL + '\n');
  10376. if (nextFetchURL != fetchURL) {
  10377. fetchURL = nextFetchURL;
  10378. pushDialog('Fetching Page ' + (pagesRange.length != 0 ? pagesRange[Math.min(rangeIndex, pagesRange.length - 1)] : index) + ': ' + fetchURL + ' ... ');
  10379. xhr.open('GET', fetchURL);
  10380. xhr.timeout = 30000;
  10381. xhr.send();
  10382. }
  10383. else {
  10384. getAllPagesURLFin = true;
  10385. index = 1;
  10386. if (needNumberImages) {
  10387. // Number images, thanks to JingJang@GitHub, source: https://github.com/JingJang/E-Hentai-Downloader
  10388. if (pagesRange.length == 0 || !setting['number-real-index']) {
  10389. var len = imageList.length.toString().length + 1,
  10390. padding = new Array(len + 1).join('0');
  10391. /*for (var j = 0; j < imageList.length; j++) {
  10392. imageList[j]['imageName'] = (padding + imageList[j].pageURL.match(/\d+$/)[0]).slice(0 - len) + (setting['number-separator'] ? setting['number-separator'] : '>') + imageList[j]['imageName'];
  10393. }*/
  10394. imageList.forEach(function(elem, index) {
  10395. return elem['imageNumber'] = (padding + (index + 1)).slice(0 - len);
  10396. });
  10397. }
  10398. else {
  10399. var len = pageURLsList.length.toString().length + 1,
  10400. padding = new Array(len + 1).join('0');
  10401. imageList.forEach(function(elem) {
  10402. return elem['imageNumber'] = (padding + (elem['realIndex'])).slice(0 - len);
  10403. });
  10404. }
  10405. }
  10406. pushDialog('\n');
  10407. ehDownloadDialog.appendChild(progressTable);
  10408. if ('enable-multi-threading' in setting && !setting['enable-multi-threading']) {
  10409. //pushDialog('\nFetching Image 1: ' + imageList[0]['imageName'] + ' ... ');
  10410. fetchOriginalImage(index);
  10411. }
  10412. else {
  10413. retryCount = [];
  10414. //pushDialog('\n');
  10415. for (var i = fetchCount; i < (setting['thread-count'] != null ? setting['thread-count'] : 5); i++) {
  10416. for (var j = 0; j < imageList.length; j++) {
  10417. if (imageData[j] == null) {
  10418. imageData[j] = 'Fetching';
  10419. //pushDialog('Fetching Image ' + (j + 1) + ': ' + imageList[j]['imageName'] + ' ... \n');
  10420. fetchOriginalImage(j + 1);
  10421. fetchCount++;
  10422. break;
  10423. }
  10424. }
  10425. }
  10426. }
  10427. }
  10428. }
  10429. xhr.onerror = xhr.ontimeout = function() {
  10430. if (retryCount < (setting['retry-count'] != null ? setting['retry-count'] : 3)) {
  10431. pushDialog('Failed! Retrying... ');
  10432. retryCount++;
  10433. xhr.open('GET', fetchURL);
  10434. xhr.timeout = 30000;
  10435. xhr.send();
  10436. }
  10437. else {
  10438. pushDialog('Failed!\nFetch images\' URL failed, Please try again later.');
  10439. isDownloading = false;
  10440. //window.onbeforeunload = null;
  10441. insertCloseButton();
  10442. alert('Fetch images\' URL failed, Please try again later.');
  10443. }
  10444. }
  10445. pushDialog('Start downloading at ' + new Date() + '\nStart fetching images\' URL...\nFetching Page 1: ' + fetchURL + ' ... ');
  10446. xhr.open('GET', fetchURL);
  10447. xhr.timeout = 30000;
  10448. xhr.send();
  10449. /*window.onbeforeunload = function(){
  10450. return 'E-Hentai Downloader is still running, please don\'t close this tab before it finish downloading.\n\nE-Hentai Downloader 仍在工作中,在完成下载前请勿关闭此标签页。';
  10451. }*/
  10452. }
  10453.  
  10454. function ehDownloadSet() {
  10455. var ehDownloadSettingPanel = document.createElement('div');
  10456. ehDownloadSettingPanel.className = 'ehD-setting';
  10457. ehDownloadSettingPanel.innerHTML = '\
  10458. <div class="g2"><label><input type="checkbox" data-ehd-setting="enable-multi-threading"> Enable multi-thread download (recommended)</label></div>\
  10459. <div class="g2"><label>Multi-thread download threads count <input type="number" data-ehd-setting="thread-count" min="1" placeholder="5" style="width: 51px;"> (<=5 is advised)</label></div>\
  10460. <div class="g2"><label>Abort fetching current image after <input type="number" data-ehd-setting="timeout" min="0" placeholder="300" style="width: 51px;"> second(s) (0 is never abort)</label></div>\
  10461. <div class="g2"' + (GM_info.scriptHandler && GM_info.scriptHandler == 'Violentmonkey' && ' style="opacity: 0.75;" title="Violentmonkey may not support this feature"') + '><label>Skip current image when retried <input type="number" data-ehd-setting="retry-count" min="1" placeholder="3" style="width: 51px;"> time(s)</label></div>\
  10462. <div class="g2"><label>Set folder name as <input type="text" data-ehd-setting="dir-name" placeholder="{gid}_{token}"> (if you don\'t want to create folder, use "/") *</label></div>\
  10463. <div class="g2"><label>Set Zip file name as <input type="text" data-ehd-setting="file-name" placeholder="{title}"> *</label></div>\
  10464. <div class="g2"><label>Set compression level as <input type="number" data-ehd-setting="compression-level" min="0" max="9" placeholder="0" style="width: 51px;"> (0 ~ 9, 0 is only store, not recommended to enable)</label></div>\
  10465. <div class="g2"><label><input type="checkbox" data-ehd-setting="number-images"> Number images (00101.jpg, 00201_theme.jpg, 00302.jpg...) (Separator <input type="text" data-ehd-setting="number-separator" style="width: 51px;" placeholder=":">)</label></div>\
  10466. <div class="g2"><label><input type="checkbox" data-ehd-setting="number-real-index"> Number images with original page number if pages range is set</label></div>\
  10467. <div class="g2"><label><input type="checkbox" data-ehd-setting="force-resized"> Force download resized image (never download original image) **</label></div>\
  10468. <div class="g2"><label><input type="checkbox" data-ehd-setting="never-new-url"> Never get new image URL when failed downloading image **</label></div>\
  10469. <div class="g2"><label><input type="checkbox" data-ehd-setting="never-send-nl"> Never send "nl" GET parameter when getting new image URL **</label></div>\
  10470. <div class="g2">\
  10471. * Enabled tags: \
  10472. <span title="You can find GID and token at the address bar like this: exhentai.org/g/[GID]/[Token]/">{gid} Archive\'s GID</sapn> | \
  10473. <span title="You can find GID and token at the address bar like this: exhentai.org/g/[GID]/[Token]/">{token} Archive\'s token</sapn> | \
  10474. <span title="This title is the English title or Latin transliteration, you can find it as the first line of the title.">{title} Archive\'s title</span> | \
  10475. <span title="This title is the original language title, you can find it as the second line of the title.">{subtitle} Archive\'s sub-title</span> | \
  10476. <span title="This tag means the sort name of the archive, and its output string is upper.">{tag} Archive\'s tag</span> | \
  10477. <span title="You can find it at the left of the archive page.">{uploader} Archive\'s uploader</span>\
  10478. </div>\
  10479. <div class="g2">\
  10480. ** Enable these options may save your image viewing limits <a href="https://github.com/ccloli/E-Hentai-Downloader/wiki/E%E2%88%92Hentai-Image-Viewing-Limits" target="_blank" style="text-decoration: underline; color: #ffffff;">(See wiki)</a>, but may also cause some download problems.\
  10481. </div>\
  10482. <div style="text-align: center"><button>Save</button> <button>Cancel</button></div>';
  10483. document.body.appendChild(ehDownloadSettingPanel);
  10484. for (var i in setting) {
  10485. var element = ehDownloadSettingPanel.querySelector('input[data-ehd-setting="' + i + '"]');
  10486. if (!element) continue;
  10487. if (element.getAttribute('type') == 'checkbox') ((setting[i]) && (element.setAttribute('checked', 'checked')));
  10488. else element.setAttribute('value', setting[i]);
  10489. }
  10490. ehDownloadSettingPanel.addEventListener('click', function(event){
  10491. if (event.target.tagName.toLowerCase() == 'button') {
  10492. if (event.target.textContent == 'Save') {
  10493. var inputs = ehDownloadSettingPanel.querySelectorAll('input[data-ehd-setting]');
  10494. setting = {};
  10495. for (var i = 0; i < inputs.length; i++) {
  10496. if (inputs[i].getAttribute('type') != 'checkbox' && inputs[i].value == '') continue;
  10497. setting[inputs[i].dataset.ehdSetting] = inputs[i].getAttribute('type') == 'checkbox' ? inputs[i].checked : inputs[i].getAttribute('type') == 'number' ? Number(inputs[i].value) : inputs[i].value;
  10498. }
  10499. GM_setValue('ehD-setting', JSON.stringify(setting));
  10500. }
  10501. document.body.removeChild(ehDownloadSettingPanel);
  10502. }
  10503. });
  10504. }
  10505.  
  10506. // EHD Box, thanks to JingJang@GitHub, source: https://github.com/JingJang/E-Hentai-Downloader
  10507. var ehDownloadBox = document.createElement('fieldset');
  10508. ehDownloadBox.style.border = '1px groove #000000';
  10509. ehDownloadBox.className = 'ehD-box';
  10510. ehDownloadBox.innerHTML = '<legend style="' + (origin == "http://exhentai.org" ? 'color: #ffff00; ' : '') + 'font-weight: 700;">E-Hentai Downloader</legend>\
  10511. <style>\
  10512. .ehD-box { margin: 20px auto; width: 732px; box-sizing: border-box; font-size: 12px; }\
  10513. .ehD-box a { cursor: pointer; }\
  10514. .ehD-box .g2 { display: inline-block; margin: 10px; padding: 0; }\
  10515. .ehD-setting { position: fixed; left: 0; right: 0; top: 0; bottom: 0; padding: 5px; border: 1px solid #000000; background: #34353b; color: #dddddd; width: 550px; height: 500px; max-width: 100%; max-height: 100%; overflow: auto; box-sizing: border-box; margin: auto; z-index: 999; text-align: left; font-size: 12px; }\
  10516. .ehD-setting .g2 { padding-bottom: 10px; }\
  10517. .ehD-setting input, .ehD-box input { vertical-align: middle; }\
  10518. </style>';
  10519. // Use a lazy way to set stylesheet.
  10520.  
  10521. var ehDownloadAction = document.createElement('div');
  10522. ehDownloadAction.className = 'g2';
  10523. ehDownloadAction.innerHTML = '<img src="data:image/gif;base64,R0lGODlhBQAHALMAAK6vr7OztK+urra2tkJCQsDAwEZGRrKyskdHR0FBQUhISP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAFAAcAAAQUUI1FlREVpbOUSkTgbZ0CUEhBLREAOw=="> <a>Download Archive</a>';
  10524. ehDownloadAction.addEventListener('click', function(event){
  10525. event.preventDefault();
  10526. if (isDownloading && !confirm('E-Hentai Downloader is working now, are you sure to stop downloading and start a new download?')) return;
  10527. if (unsafeWindow.apiuid == -1 && !confirm('You are not log in to E-Hentai Forums, so you can\'t download original image. Continue?')) return;
  10528. ehDownloadDialog.innerHTML = '';
  10529. if (ehDownloadRange.querySelector('input').value.trim() == '') {
  10530. if (pagesRange.length) pagesRange = [];
  10531. ehDownload();
  10532. }
  10533. else getAllPagesURL();
  10534. });
  10535. /*document.getElementById('gd5')*/ehDownloadBox.appendChild(ehDownloadAction);
  10536.  
  10537. var ehDownloadNumberInput = document.createElement('div');
  10538. ehDownloadNumberInput.className = 'g2';
  10539. ehDownloadNumberInput.innerHTML = '<img src="data:image/gif;base64,R0lGODlhBQAHALMAAK6vr7OztK+urra2tkJCQsDAwEZGRrKyskdHR0FBQUhISP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAFAAcAAAQUUI1FlREVpbOUSkTgbZ0CUEhBLREAOw=="> <a><label><input type="checkbox" style="vertical-align: middle; margin: 0;"' + (needNumberImages ? ' checked="checked' : '') + '"> Number Images<label></a>';
  10540. ehDownloadBox.appendChild(ehDownloadNumberInput);
  10541.  
  10542. var ehDownloadRange = document.createElement('div');
  10543. ehDownloadRange.className = 'g2';
  10544. ehDownloadRange.innerHTML = '<img src="data:image/gif;base64,R0lGODlhBQAHALMAAK6vr7OztK+urra2tkJCQsDAwEZGRrKyskdHR0FBQUhISP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAFAAcAAAQUUI1FlREVpbOUSkTgbZ0CUEhBLREAOw=="> <a><label>Pages Range <input type="text" placeholder="eg. 1-10,12,14-20,27,30"></label></a>';
  10545. /*document.getElementById('gd5')*/ehDownloadBox.appendChild(ehDownloadRange);
  10546.  
  10547. var ehDownloadSetting = document.createElement('div');
  10548. ehDownloadSetting.className = 'g2';
  10549. ehDownloadSetting.innerHTML = '<img src="data:image/gif;base64,R0lGODlhBQAHALMAAK6vr7OztK+urra2tkJCQsDAwEZGRrKyskdHR0FBQUhISP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAFAAcAAAQUUI1FlREVpbOUSkTgbZ0CUEhBLREAOw=="> <a>Settings</a>';
  10550. ehDownloadSetting.addEventListener('click', function(event){
  10551. event.preventDefault();
  10552. ehDownloadSet();
  10553. });
  10554. /*document.getElementById('gd5')*/ehDownloadBox.appendChild(ehDownloadSetting);
  10555.  
  10556. var ehDownloadFeedback = document.createElement('div');
  10557. ehDownloadFeedback.className = 'g2';
  10558. ehDownloadFeedback.innerHTML = '<img src="data:image/gif;base64,R0lGODlhBQAHALMAAK6vr7OztK+urra2tkJCQsDAwEZGRrKyskdHR0FBQUhISP///wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAFAAcAAAQUUI1FlREVpbOUSkTgbZ0CUEhBLREAOw=="> <a href="https://github.com/ccloli/E-Hentai-Downloader/issues" target="_blank">Feedback</a>';
  10559. /*document.getElementById('gd5')*/ehDownloadBox.appendChild(ehDownloadFeedback);
  10560.  
  10561. //document.getElementById('gd5').appendChild(ehDownloadBox);
  10562. document.body.insertBefore(ehDownloadBox, document.getElementById('asm'));
  10563.  
  10564. // Fixed overflow in g.e-hentai.org
  10565. //document.getElementById('gright').style.height = 'auto';
  10566.  
  10567. var ehDownloadDialog = document.createElement('div');
  10568. ehDownloadDialog.style.cssText = 'position: fixed; right: 0; bottom: 0; display: none; padding: 5px; border: 1px solid #000000; background: #34353b; color: #dddddd; width: 550px; height: 300px; overflow: auto; z-index: 999;';
  10569. document.body.appendChild(ehDownloadDialog);
  10570.  
  10571. window.onbeforeunload = function(){
  10572. if (isDownloading) return 'E-Hentai Downloader is still running, please don\'t close this tab before it finish downloading.\n\nE-Hentai Downloader 仍在工作中,在完成下载前请勿关闭此标签页。';
  10573. };