xlscfb.flow.js 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698
  1. var DO_NOT_EXPORT_CFB = true;
  2. /*::
  3. declare var Base64:any;
  4. declare var ReadShift:any;
  5. declare var CheckField:any;
  6. declare var prep_blob:any;
  7. declare var __readUInt32LE:any;
  8. declare var __readInt32LE:any;
  9. declare var __toBuffer:any;
  10. declare var __utf16le:any;
  11. declare var bconcat:any;
  12. declare var s2a:any;
  13. declare var chr0:any;
  14. declare var chr1:any;
  15. declare var has_buf:boolean;
  16. declare var new_buf:any;
  17. declare var new_raw_buf:any;
  18. declare var new_unsafe_buf:any;
  19. declare var Buffer_from:any;
  20. */
  21. /* cfb.js (C) 2013-present SheetJS -- http://sheetjs.com */
  22. /* vim: set ts=2: */
  23. /*jshint eqnull:true */
  24. /*exported CFB */
  25. /*global module, require:false, process:false, Buffer:false, Uint8Array:false, Uint16Array:false */
  26. /*::
  27. declare var DO_NOT_EXPORT_CFB:?boolean;
  28. type SectorEntry = {
  29. name?:string;
  30. nodes?:Array<number>;
  31. data:RawBytes;
  32. };
  33. type SectorList = {
  34. [k:string|number]:SectorEntry;
  35. name:?string;
  36. fat_addrs:Array<number>;
  37. ssz:number;
  38. }
  39. type CFBFiles = {[n:string]:CFBEntry};
  40. */
  41. /* crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */
  42. /* vim: set ts=2: */
  43. /*exported CRC32 */
  44. var CRC32;
  45. (function (factory) {
  46. /*jshint ignore:start */
  47. /*eslint-disable */
  48. factory(CRC32 = {});
  49. /*eslint-enable */
  50. /*jshint ignore:end */
  51. }(function(CRC32) {
  52. CRC32.version = '1.2.0';
  53. /* see perf/crc32table.js */
  54. /*global Int32Array */
  55. function signed_crc_table()/*:any*/ {
  56. var c = 0, table/*:Array<number>*/ = new Array(256);
  57. for(var n =0; n != 256; ++n){
  58. c = n;
  59. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  60. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  61. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  62. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  63. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  64. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  65. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  66. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  67. table[n] = c;
  68. }
  69. return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table;
  70. }
  71. var T = signed_crc_table();
  72. function crc32_bstr(bstr/*:string*/, seed/*:number*/)/*:number*/ {
  73. var C = seed ^ -1, L = bstr.length - 1;
  74. for(var i = 0; i < L;) {
  75. C = (C>>>8) ^ T[(C^bstr.charCodeAt(i++))&0xFF];
  76. C = (C>>>8) ^ T[(C^bstr.charCodeAt(i++))&0xFF];
  77. }
  78. if(i === L) C = (C>>>8) ^ T[(C ^ bstr.charCodeAt(i))&0xFF];
  79. return C ^ -1;
  80. }
  81. function crc32_buf(buf/*:Uint8Array|Array<number>*/, seed/*:number*/)/*:number*/ {
  82. if(buf.length > 10000) return crc32_buf_8(buf, seed);
  83. var C = seed ^ -1, L = buf.length - 3;
  84. for(var i = 0; i < L;) {
  85. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  86. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  87. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  88. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  89. }
  90. while(i < L+3) C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  91. return C ^ -1;
  92. }
  93. function crc32_buf_8(buf/*:Uint8Array|Array<number>*/, seed/*:number*/)/*:number*/ {
  94. var C = seed ^ -1, L = buf.length - 7;
  95. for(var i = 0; i < L;) {
  96. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  97. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  98. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  99. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  100. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  101. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  102. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  103. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  104. }
  105. while(i < L+7) C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  106. return C ^ -1;
  107. }
  108. function crc32_str(str/*:string*/, seed/*:number*/)/*:number*/ {
  109. var C = seed ^ -1;
  110. for(var i = 0, L=str.length, c, d; i < L;) {
  111. c = str.charCodeAt(i++);
  112. if(c < 0x80) {
  113. C = (C>>>8) ^ T[(C ^ c)&0xFF];
  114. } else if(c < 0x800) {
  115. C = (C>>>8) ^ T[(C ^ (192|((c>>6)&31)))&0xFF];
  116. C = (C>>>8) ^ T[(C ^ (128|(c&63)))&0xFF];
  117. } else if(c >= 0xD800 && c < 0xE000) {
  118. c = (c&1023)+64; d = str.charCodeAt(i++)&1023;
  119. C = (C>>>8) ^ T[(C ^ (240|((c>>8)&7)))&0xFF];
  120. C = (C>>>8) ^ T[(C ^ (128|((c>>2)&63)))&0xFF];
  121. C = (C>>>8) ^ T[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF];
  122. C = (C>>>8) ^ T[(C ^ (128|(d&63)))&0xFF];
  123. } else {
  124. C = (C>>>8) ^ T[(C ^ (224|((c>>12)&15)))&0xFF];
  125. C = (C>>>8) ^ T[(C ^ (128|((c>>6)&63)))&0xFF];
  126. C = (C>>>8) ^ T[(C ^ (128|(c&63)))&0xFF];
  127. }
  128. }
  129. return C ^ -1;
  130. }
  131. CRC32.table = T;
  132. CRC32.bstr = crc32_bstr;
  133. CRC32.buf = crc32_buf;
  134. CRC32.str = crc32_str;
  135. }));
  136. /* [MS-CFB] v20171201 */
  137. var CFB = (function _CFB(){
  138. var exports/*:CFBModule*/ = /*::(*/{}/*:: :any)*/;
  139. exports.version = '1.2.0';
  140. /* [MS-CFB] 2.6.4 */
  141. function namecmp(l/*:string*/, r/*:string*/)/*:number*/ {
  142. var L = l.split("/"), R = r.split("/");
  143. for(var i = 0, c = 0, Z = Math.min(L.length, R.length); i < Z; ++i) {
  144. if((c = L[i].length - R[i].length)) return c;
  145. if(L[i] != R[i]) return L[i] < R[i] ? -1 : 1;
  146. }
  147. return L.length - R.length;
  148. }
  149. function dirname(p/*:string*/)/*:string*/ {
  150. if(p.charAt(p.length - 1) == "/") return (p.slice(0,-1).indexOf("/") === -1) ? p : dirname(p.slice(0, -1));
  151. var c = p.lastIndexOf("/");
  152. return (c === -1) ? p : p.slice(0, c+1);
  153. }
  154. function filename(p/*:string*/)/*:string*/ {
  155. if(p.charAt(p.length - 1) == "/") return filename(p.slice(0, -1));
  156. var c = p.lastIndexOf("/");
  157. return (c === -1) ? p : p.slice(c+1);
  158. }
  159. /* -------------------------------------------------------------------------- */
  160. /* DOS Date format:
  161. high|YYYYYYYm.mmmddddd.HHHHHMMM.MMMSSSSS|low
  162. add 1980 to stored year
  163. stored second should be doubled
  164. */
  165. /* write JS date to buf as a DOS date */
  166. function write_dos_date(buf/*:CFBlob*/, date/*:Date|string*/) {
  167. if(typeof date === "string") date = new Date(date);
  168. var hms/*:number*/ = date.getHours();
  169. hms = hms << 6 | date.getMinutes();
  170. hms = hms << 5 | (date.getSeconds()>>>1);
  171. buf.write_shift(2, hms);
  172. var ymd/*:number*/ = (date.getFullYear() - 1980);
  173. ymd = ymd << 4 | (date.getMonth()+1);
  174. ymd = ymd << 5 | date.getDate();
  175. buf.write_shift(2, ymd);
  176. }
  177. /* read four bytes from buf and interpret as a DOS date */
  178. function parse_dos_date(buf/*:CFBlob*/)/*:Date*/ {
  179. var hms = buf.read_shift(2) & 0xFFFF;
  180. var ymd = buf.read_shift(2) & 0xFFFF;
  181. var val = new Date();
  182. var d = ymd & 0x1F; ymd >>>= 5;
  183. var m = ymd & 0x0F; ymd >>>= 4;
  184. val.setMilliseconds(0);
  185. val.setFullYear(ymd + 1980);
  186. val.setMonth(m-1);
  187. val.setDate(d);
  188. var S = hms & 0x1F; hms >>>= 5;
  189. var M = hms & 0x3F; hms >>>= 6;
  190. val.setHours(hms);
  191. val.setMinutes(M);
  192. val.setSeconds(S<<1);
  193. return val;
  194. }
  195. function parse_extra_field(blob/*:CFBlob*/)/*:any*/ {
  196. prep_blob(blob, 0);
  197. var o = /*::(*/{}/*:: :any)*/;
  198. var flags = 0;
  199. while(blob.l <= blob.length - 4) {
  200. var type = blob.read_shift(2);
  201. var sz = blob.read_shift(2), tgt = blob.l + sz;
  202. var p = {};
  203. switch(type) {
  204. /* UNIX-style Timestamps */
  205. case 0x5455: {
  206. flags = blob.read_shift(1);
  207. if(flags & 1) p.mtime = blob.read_shift(4);
  208. /* for some reason, CD flag corresponds to LFH */
  209. if(sz > 5) {
  210. if(flags & 2) p.atime = blob.read_shift(4);
  211. if(flags & 4) p.ctime = blob.read_shift(4);
  212. }
  213. if(p.mtime) p.mt = new Date(p.mtime*1000);
  214. }
  215. break;
  216. }
  217. blob.l = tgt;
  218. o[type] = p;
  219. }
  220. return o;
  221. }
  222. var fs/*:: = require('fs'); */;
  223. function get_fs() { return fs || (fs = require('fs')); }
  224. function parse(file/*:RawBytes*/, options/*:CFBReadOpts*/)/*:CFBContainer*/ {
  225. if(file[0] == 0x50 && file[1] == 0x4b) return parse_zip(file, options);
  226. if((file[0] | 0x20) == 0x6d && (file[1]|0x20) == 0x69) return parse_mad(file, options);
  227. if(file.length < 512) throw new Error("CFB file size " + file.length + " < 512");
  228. var mver = 3;
  229. var ssz = 512;
  230. var nmfs = 0; // number of mini FAT sectors
  231. var difat_sec_cnt = 0;
  232. var dir_start = 0;
  233. var minifat_start = 0;
  234. var difat_start = 0;
  235. var fat_addrs/*:Array<number>*/ = []; // locations of FAT sectors
  236. /* [MS-CFB] 2.2 Compound File Header */
  237. var blob/*:CFBlob*/ = /*::(*/file.slice(0,512)/*:: :any)*/;
  238. prep_blob(blob, 0);
  239. /* major version */
  240. var mv = check_get_mver(blob);
  241. mver = mv[0];
  242. switch(mver) {
  243. case 3: ssz = 512; break; case 4: ssz = 4096; break;
  244. case 0: if(mv[1] == 0) return parse_zip(file, options);
  245. /* falls through */
  246. default: throw new Error("Major Version: Expected 3 or 4 saw " + mver);
  247. }
  248. /* reprocess header */
  249. if(ssz !== 512) { blob = /*::(*/file.slice(0,ssz)/*:: :any)*/; prep_blob(blob, 28 /* blob.l */); }
  250. /* Save header for final object */
  251. var header/*:RawBytes*/ = file.slice(0,ssz);
  252. check_shifts(blob, mver);
  253. // Number of Directory Sectors
  254. var dir_cnt/*:number*/ = blob.read_shift(4, 'i');
  255. if(mver === 3 && dir_cnt !== 0) throw new Error('# Directory Sectors: Expected 0 saw ' + dir_cnt);
  256. // Number of FAT Sectors
  257. blob.l += 4;
  258. // First Directory Sector Location
  259. dir_start = blob.read_shift(4, 'i');
  260. // Transaction Signature
  261. blob.l += 4;
  262. // Mini Stream Cutoff Size
  263. blob.chk('00100000', 'Mini Stream Cutoff Size: ');
  264. // First Mini FAT Sector Location
  265. minifat_start = blob.read_shift(4, 'i');
  266. // Number of Mini FAT Sectors
  267. nmfs = blob.read_shift(4, 'i');
  268. // First DIFAT sector location
  269. difat_start = blob.read_shift(4, 'i');
  270. // Number of DIFAT Sectors
  271. difat_sec_cnt = blob.read_shift(4, 'i');
  272. // Grab FAT Sector Locations
  273. for(var q = -1, j = 0; j < 109; ++j) { /* 109 = (512 - blob.l)>>>2; */
  274. q = blob.read_shift(4, 'i');
  275. if(q<0) break;
  276. fat_addrs[j] = q;
  277. }
  278. /** Break the file up into sectors */
  279. var sectors/*:Array<RawBytes>*/ = sectorify(file, ssz);
  280. sleuth_fat(difat_start, difat_sec_cnt, sectors, ssz, fat_addrs);
  281. /** Chains */
  282. var sector_list/*:SectorList*/ = make_sector_list(sectors, dir_start, fat_addrs, ssz);
  283. sector_list[dir_start].name = "!Directory";
  284. if(nmfs > 0 && minifat_start !== ENDOFCHAIN) sector_list[minifat_start].name = "!MiniFAT";
  285. sector_list[fat_addrs[0]].name = "!FAT";
  286. sector_list.fat_addrs = fat_addrs;
  287. sector_list.ssz = ssz;
  288. /* [MS-CFB] 2.6.1 Compound File Directory Entry */
  289. var files/*:CFBFiles*/ = {}, Paths/*:Array<string>*/ = [], FileIndex/*:CFBFileIndex*/ = [], FullPaths/*:Array<string>*/ = [];
  290. read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, minifat_start);
  291. build_full_paths(FileIndex, FullPaths, Paths);
  292. Paths.shift();
  293. var o = {
  294. FileIndex: FileIndex,
  295. FullPaths: FullPaths
  296. };
  297. // $FlowIgnore
  298. if(options && options.raw) o.raw = {header: header, sectors: sectors};
  299. return o;
  300. } // parse
  301. /* [MS-CFB] 2.2 Compound File Header -- read up to major version */
  302. function check_get_mver(blob/*:CFBlob*/)/*:[number, number]*/ {
  303. if(blob[blob.l] == 0x50 && blob[blob.l + 1] == 0x4b) return [0, 0];
  304. // header signature 8
  305. blob.chk(HEADER_SIGNATURE, 'Header Signature: ');
  306. // clsid 16
  307. //blob.chk(HEADER_CLSID, 'CLSID: ');
  308. blob.l += 16;
  309. // minor version 2
  310. var mver/*:number*/ = blob.read_shift(2, 'u');
  311. return [blob.read_shift(2,'u'), mver];
  312. }
  313. function check_shifts(blob/*:CFBlob*/, mver/*:number*/)/*:void*/ {
  314. var shift = 0x09;
  315. // Byte Order
  316. //blob.chk('feff', 'Byte Order: '); // note: some writers put 0xffff
  317. blob.l += 2;
  318. // Sector Shift
  319. switch((shift = blob.read_shift(2))) {
  320. case 0x09: if(mver != 3) throw new Error('Sector Shift: Expected 9 saw ' + shift); break;
  321. case 0x0c: if(mver != 4) throw new Error('Sector Shift: Expected 12 saw ' + shift); break;
  322. default: throw new Error('Sector Shift: Expected 9 or 12 saw ' + shift);
  323. }
  324. // Mini Sector Shift
  325. blob.chk('0600', 'Mini Sector Shift: ');
  326. // Reserved
  327. blob.chk('000000000000', 'Reserved: ');
  328. }
  329. /** Break the file up into sectors */
  330. function sectorify(file/*:RawBytes*/, ssz/*:number*/)/*:Array<RawBytes>*/ {
  331. var nsectors = Math.ceil(file.length/ssz)-1;
  332. var sectors/*:Array<RawBytes>*/ = [];
  333. for(var i=1; i < nsectors; ++i) sectors[i-1] = file.slice(i*ssz,(i+1)*ssz);
  334. sectors[nsectors-1] = file.slice(nsectors*ssz);
  335. return sectors;
  336. }
  337. /* [MS-CFB] 2.6.4 Red-Black Tree */
  338. function build_full_paths(FI/*:CFBFileIndex*/, FP/*:Array<string>*/, Paths/*:Array<string>*/)/*:void*/ {
  339. var i = 0, L = 0, R = 0, C = 0, j = 0, pl = Paths.length;
  340. var dad/*:Array<number>*/ = [], q/*:Array<number>*/ = [];
  341. for(; i < pl; ++i) { dad[i]=q[i]=i; FP[i]=Paths[i]; }
  342. for(; j < q.length; ++j) {
  343. i = q[j];
  344. L = FI[i].L; R = FI[i].R; C = FI[i].C;
  345. if(dad[i] === i) {
  346. if(L !== -1 /*NOSTREAM*/ && dad[L] !== L) dad[i] = dad[L];
  347. if(R !== -1 && dad[R] !== R) dad[i] = dad[R];
  348. }
  349. if(C !== -1 /*NOSTREAM*/) dad[C] = i;
  350. if(L !== -1 && i != dad[i]) { dad[L] = dad[i]; if(q.lastIndexOf(L) < j) q.push(L); }
  351. if(R !== -1 && i != dad[i]) { dad[R] = dad[i]; if(q.lastIndexOf(R) < j) q.push(R); }
  352. }
  353. for(i=1; i < pl; ++i) if(dad[i] === i) {
  354. if(R !== -1 /*NOSTREAM*/ && dad[R] !== R) dad[i] = dad[R];
  355. else if(L !== -1 && dad[L] !== L) dad[i] = dad[L];
  356. }
  357. for(i=1; i < pl; ++i) {
  358. if(FI[i].type === 0 /* unknown */) continue;
  359. j = i;
  360. if(j != dad[j]) do {
  361. j = dad[j];
  362. FP[i] = FP[j] + "/" + FP[i];
  363. } while (j !== 0 && -1 !== dad[j] && j != dad[j]);
  364. dad[i] = -1;
  365. }
  366. FP[0] += "/";
  367. for(i=1; i < pl; ++i) {
  368. if(FI[i].type !== 2 /* stream */) FP[i] += "/";
  369. }
  370. }
  371. function get_mfat_entry(entry/*:CFBEntry*/, payload/*:RawBytes*/, mini/*:?RawBytes*/)/*:CFBlob*/ {
  372. var start = entry.start, size = entry.size;
  373. //return (payload.slice(start*MSSZ, start*MSSZ + size)/*:any*/);
  374. var o = [];
  375. var idx = start;
  376. while(mini && size > 0 && idx >= 0) {
  377. o.push(payload.slice(idx * MSSZ, idx * MSSZ + MSSZ));
  378. size -= MSSZ;
  379. idx = __readInt32LE(mini, idx * 4);
  380. }
  381. if(o.length === 0) return (new_buf(0)/*:any*/);
  382. return (bconcat(o).slice(0, entry.size)/*:any*/);
  383. }
  384. /** Chase down the rest of the DIFAT chain to build a comprehensive list
  385. DIFAT chains by storing the next sector number as the last 32 bits */
  386. function sleuth_fat(idx/*:number*/, cnt/*:number*/, sectors/*:Array<RawBytes>*/, ssz/*:number*/, fat_addrs)/*:void*/ {
  387. var q/*:number*/ = ENDOFCHAIN;
  388. if(idx === ENDOFCHAIN) {
  389. if(cnt !== 0) throw new Error("DIFAT chain shorter than expected");
  390. } else if(idx !== -1 /*FREESECT*/) {
  391. var sector = sectors[idx], m = (ssz>>>2)-1;
  392. if(!sector) return;
  393. for(var i = 0; i < m; ++i) {
  394. if((q = __readInt32LE(sector,i*4)) === ENDOFCHAIN) break;
  395. fat_addrs.push(q);
  396. }
  397. sleuth_fat(__readInt32LE(sector,ssz-4),cnt - 1, sectors, ssz, fat_addrs);
  398. }
  399. }
  400. /** Follow the linked list of sectors for a given starting point */
  401. function get_sector_list(sectors/*:Array<RawBytes>*/, start/*:number*/, fat_addrs/*:Array<number>*/, ssz/*:number*/, chkd/*:?Array<boolean>*/)/*:SectorEntry*/ {
  402. var buf/*:Array<number>*/ = [], buf_chain/*:Array<any>*/ = [];
  403. if(!chkd) chkd = [];
  404. var modulus = ssz - 1, j = 0, jj = 0;
  405. for(j=start; j>=0;) {
  406. chkd[j] = true;
  407. buf[buf.length] = j;
  408. buf_chain.push(sectors[j]);
  409. var addr = fat_addrs[Math.floor(j*4/ssz)];
  410. jj = ((j*4) & modulus);
  411. if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
  412. if(!sectors[addr]) break;
  413. j = __readInt32LE(sectors[addr], jj);
  414. }
  415. return {nodes: buf, data:__toBuffer([buf_chain])};
  416. }
  417. /** Chase down the sector linked lists */
  418. function make_sector_list(sectors/*:Array<RawBytes>*/, dir_start/*:number*/, fat_addrs/*:Array<number>*/, ssz/*:number*/)/*:SectorList*/ {
  419. var sl = sectors.length, sector_list/*:SectorList*/ = ([]/*:any*/);
  420. var chkd/*:Array<boolean>*/ = [], buf/*:Array<number>*/ = [], buf_chain/*:Array<RawBytes>*/ = [];
  421. var modulus = ssz - 1, i=0, j=0, k=0, jj=0;
  422. for(i=0; i < sl; ++i) {
  423. buf = ([]/*:Array<number>*/);
  424. k = (i + dir_start); if(k >= sl) k-=sl;
  425. if(chkd[k]) continue;
  426. buf_chain = [];
  427. var seen = [];
  428. for(j=k; j>=0;) {
  429. seen[j] = true;
  430. chkd[j] = true;
  431. buf[buf.length] = j;
  432. buf_chain.push(sectors[j]);
  433. var addr/*:number*/ = fat_addrs[Math.floor(j*4/ssz)];
  434. jj = ((j*4) & modulus);
  435. if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
  436. if(!sectors[addr]) break;
  437. j = __readInt32LE(sectors[addr], jj);
  438. if(seen[j]) break;
  439. }
  440. sector_list[k] = ({nodes: buf, data:__toBuffer([buf_chain])}/*:SectorEntry*/);
  441. }
  442. return sector_list;
  443. }
  444. /* [MS-CFB] 2.6.1 Compound File Directory Entry */
  445. function read_directory(dir_start/*:number*/, sector_list/*:SectorList*/, sectors/*:Array<RawBytes>*/, Paths/*:Array<string>*/, nmfs, files, FileIndex, mini) {
  446. var minifat_store = 0, pl = (Paths.length?2:0);
  447. var sector = sector_list[dir_start].data;
  448. var i = 0, namelen = 0, name;
  449. for(; i < sector.length; i+= 128) {
  450. var blob/*:CFBlob*/ = /*::(*/sector.slice(i, i+128)/*:: :any)*/;
  451. prep_blob(blob, 64);
  452. namelen = blob.read_shift(2);
  453. name = __utf16le(blob,0,namelen-pl);
  454. Paths.push(name);
  455. var o/*:CFBEntry*/ = ({
  456. name: name,
  457. type: blob.read_shift(1),
  458. color: blob.read_shift(1),
  459. L: blob.read_shift(4, 'i'),
  460. R: blob.read_shift(4, 'i'),
  461. C: blob.read_shift(4, 'i'),
  462. clsid: blob.read_shift(16),
  463. state: blob.read_shift(4, 'i'),
  464. start: 0,
  465. size: 0
  466. });
  467. var ctime/*:number*/ = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
  468. if(ctime !== 0) o.ct = read_date(blob, blob.l-8);
  469. var mtime/*:number*/ = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
  470. if(mtime !== 0) o.mt = read_date(blob, blob.l-8);
  471. o.start = blob.read_shift(4, 'i');
  472. o.size = blob.read_shift(4, 'i');
  473. if(o.size < 0 && o.start < 0) { o.size = o.type = 0; o.start = ENDOFCHAIN; o.name = ""; }
  474. if(o.type === 5) { /* root */
  475. minifat_store = o.start;
  476. if(nmfs > 0 && minifat_store !== ENDOFCHAIN) sector_list[minifat_store].name = "!StreamData";
  477. /*minifat_size = o.size;*/
  478. } else if(o.size >= 4096 /* MSCSZ */) {
  479. o.storage = 'fat';
  480. if(sector_list[o.start] === undefined) sector_list[o.start] = get_sector_list(sectors, o.start, sector_list.fat_addrs, sector_list.ssz);
  481. sector_list[o.start].name = o.name;
  482. o.content = (sector_list[o.start].data.slice(0,o.size)/*:any*/);
  483. } else {
  484. o.storage = 'minifat';
  485. if(o.size < 0) o.size = 0;
  486. else if(minifat_store !== ENDOFCHAIN && o.start !== ENDOFCHAIN && sector_list[minifat_store]) {
  487. o.content = get_mfat_entry(o, sector_list[minifat_store].data, (sector_list[mini]||{}).data);
  488. }
  489. }
  490. if(o.content) prep_blob(o.content, 0);
  491. files[name] = o;
  492. FileIndex.push(o);
  493. }
  494. }
  495. function read_date(blob/*:RawBytes|CFBlob*/, offset/*:number*/)/*:Date*/ {
  496. return new Date(( ( (__readUInt32LE(blob,offset+4)/1e7)*Math.pow(2,32)+__readUInt32LE(blob,offset)/1e7 ) - 11644473600)*1000);
  497. }
  498. function read_file(filename/*:string*/, options/*:CFBReadOpts*/) {
  499. get_fs();
  500. return parse(fs.readFileSync(filename), options);
  501. }
  502. function read(blob/*:RawBytes|string*/, options/*:CFBReadOpts*/) {
  503. switch(options && options.type || "base64") {
  504. case "file": /*:: if(typeof blob !== 'string') throw "Must pass a filename when type='file'"; */return read_file(blob, options);
  505. case "base64": /*:: if(typeof blob !== 'string') throw "Must pass a base64-encoded binary string when type='file'"; */return parse(s2a(Base64.decode(blob)), options);
  506. case "binary": /*:: if(typeof blob !== 'string') throw "Must pass a binary string when type='file'"; */return parse(s2a(blob), options);
  507. }
  508. return parse(/*::typeof blob == 'string' ? new Buffer(blob, 'utf-8') : */blob, options);
  509. }
  510. function init_cfb(cfb/*:CFBContainer*/, opts/*:?any*/)/*:void*/ {
  511. var o = opts || {}, root = o.root || "Root Entry";
  512. if(!cfb.FullPaths) cfb.FullPaths = [];
  513. if(!cfb.FileIndex) cfb.FileIndex = [];
  514. if(cfb.FullPaths.length !== cfb.FileIndex.length) throw new Error("inconsistent CFB structure");
  515. if(cfb.FullPaths.length === 0) {
  516. cfb.FullPaths[0] = root + "/";
  517. cfb.FileIndex[0] = ({ name: root, type: 5 }/*:any*/);
  518. }
  519. if(o.CLSID) cfb.FileIndex[0].clsid = o.CLSID;
  520. seed_cfb(cfb);
  521. }
  522. function seed_cfb(cfb/*:CFBContainer*/)/*:void*/ {
  523. var nm = "\u0001Sh33tJ5";
  524. if(CFB.find(cfb, "/" + nm)) return;
  525. var p = new_buf(4); p[0] = 55; p[1] = p[3] = 50; p[2] = 54;
  526. cfb.FileIndex.push(({ name: nm, type: 2, content:p, size:4, L:69, R:69, C:69 }/*:any*/));
  527. cfb.FullPaths.push(cfb.FullPaths[0] + nm);
  528. rebuild_cfb(cfb);
  529. }
  530. function rebuild_cfb(cfb/*:CFBContainer*/, f/*:?boolean*/)/*:void*/ {
  531. init_cfb(cfb);
  532. var gc = false, s = false;
  533. for(var i = cfb.FullPaths.length - 1; i >= 0; --i) {
  534. var _file = cfb.FileIndex[i];
  535. switch(_file.type) {
  536. case 0:
  537. if(s) gc = true;
  538. else { cfb.FileIndex.pop(); cfb.FullPaths.pop(); }
  539. break;
  540. case 1: case 2: case 5:
  541. s = true;
  542. if(isNaN(_file.R * _file.L * _file.C)) gc = true;
  543. if(_file.R > -1 && _file.L > -1 && _file.R == _file.L) gc = true;
  544. break;
  545. default: gc = true; break;
  546. }
  547. }
  548. if(!gc && !f) return;
  549. var now = new Date(1987, 1, 19), j = 0;
  550. var data/*:Array<[string, CFBEntry]>*/ = [];
  551. for(i = 0; i < cfb.FullPaths.length; ++i) {
  552. if(cfb.FileIndex[i].type === 0) continue;
  553. data.push([cfb.FullPaths[i], cfb.FileIndex[i]]);
  554. }
  555. for(i = 0; i < data.length; ++i) {
  556. var dad = dirname(data[i][0]);
  557. s = false;
  558. for(j = 0; j < data.length; ++j) if(data[j][0] === dad) s = true;
  559. if(!s) data.push([dad, ({
  560. name: filename(dad).replace("/",""),
  561. type: 1,
  562. clsid: HEADER_CLSID,
  563. ct: now, mt: now,
  564. content: null
  565. }/*:any*/)]);
  566. }
  567. data.sort(function(x,y) { return namecmp(x[0], y[0]); });
  568. cfb.FullPaths = []; cfb.FileIndex = [];
  569. for(i = 0; i < data.length; ++i) { cfb.FullPaths[i] = data[i][0]; cfb.FileIndex[i] = data[i][1]; }
  570. for(i = 0; i < data.length; ++i) {
  571. var elt = cfb.FileIndex[i];
  572. var nm = cfb.FullPaths[i];
  573. elt.name = filename(nm).replace("/","");
  574. elt.L = elt.R = elt.C = -(elt.color = 1);
  575. elt.size = elt.content ? elt.content.length : 0;
  576. elt.start = 0;
  577. elt.clsid = (elt.clsid || HEADER_CLSID);
  578. if(i === 0) {
  579. elt.C = data.length > 1 ? 1 : -1;
  580. elt.size = 0;
  581. elt.type = 5;
  582. } else if(nm.slice(-1) == "/") {
  583. for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==nm) break;
  584. elt.C = j >= data.length ? -1 : j;
  585. for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==dirname(nm)) break;
  586. elt.R = j >= data.length ? -1 : j;
  587. elt.type = 1;
  588. } else {
  589. if(dirname(cfb.FullPaths[i+1]||"") == dirname(nm)) elt.R = i + 1;
  590. elt.type = 2;
  591. }
  592. }
  593. }
  594. function _write(cfb/*:CFBContainer*/, options/*:CFBWriteOpts*/)/*:RawBytes|string*/ {
  595. var _opts = options || {};
  596. /* MAD is order-sensitive, skip rebuild and sort */
  597. if(_opts.fileType == 'mad') return write_mad(cfb, _opts);
  598. rebuild_cfb(cfb);
  599. switch(_opts.fileType) {
  600. case 'zip': return write_zip(cfb, _opts);
  601. //case 'mad': return write_mad(cfb, _opts);
  602. }
  603. var L = (function(cfb/*:CFBContainer*/)/*:Array<number>*/{
  604. var mini_size = 0, fat_size = 0;
  605. for(var i = 0; i < cfb.FileIndex.length; ++i) {
  606. var file = cfb.FileIndex[i];
  607. if(!file.content) continue;
  608. /*:: if(file.content == null) throw new Error("unreachable"); */
  609. var flen = file.content.length;
  610. if(flen > 0){
  611. if(flen < 0x1000) mini_size += (flen + 0x3F) >> 6;
  612. else fat_size += (flen + 0x01FF) >> 9;
  613. }
  614. }
  615. var dir_cnt = (cfb.FullPaths.length +3) >> 2;
  616. var mini_cnt = (mini_size + 7) >> 3;
  617. var mfat_cnt = (mini_size + 0x7F) >> 7;
  618. var fat_base = mini_cnt + fat_size + dir_cnt + mfat_cnt;
  619. var fat_cnt = (fat_base + 0x7F) >> 7;
  620. var difat_cnt = fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
  621. while(((fat_base + fat_cnt + difat_cnt + 0x7F) >> 7) > fat_cnt) difat_cnt = ++fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
  622. var L = [1, difat_cnt, fat_cnt, mfat_cnt, dir_cnt, fat_size, mini_size, 0];
  623. cfb.FileIndex[0].size = mini_size << 6;
  624. L[7] = (cfb.FileIndex[0].start=L[0]+L[1]+L[2]+L[3]+L[4]+L[5])+((L[6]+7) >> 3);
  625. return L;
  626. })(cfb);
  627. var o = new_buf(L[7] << 9);
  628. var i = 0, T = 0;
  629. {
  630. for(i = 0; i < 8; ++i) o.write_shift(1, HEADER_SIG[i]);
  631. for(i = 0; i < 8; ++i) o.write_shift(2, 0);
  632. o.write_shift(2, 0x003E);
  633. o.write_shift(2, 0x0003);
  634. o.write_shift(2, 0xFFFE);
  635. o.write_shift(2, 0x0009);
  636. o.write_shift(2, 0x0006);
  637. for(i = 0; i < 3; ++i) o.write_shift(2, 0);
  638. o.write_shift(4, 0);
  639. o.write_shift(4, L[2]);
  640. o.write_shift(4, L[0] + L[1] + L[2] + L[3] - 1);
  641. o.write_shift(4, 0);
  642. o.write_shift(4, 1<<12);
  643. o.write_shift(4, L[3] ? L[0] + L[1] + L[2] - 1: ENDOFCHAIN);
  644. o.write_shift(4, L[3]);
  645. o.write_shift(-4, L[1] ? L[0] - 1: ENDOFCHAIN);
  646. o.write_shift(4, L[1]);
  647. for(i = 0; i < 109; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
  648. }
  649. if(L[1]) {
  650. for(T = 0; T < L[1]; ++T) {
  651. for(; i < 236 + T * 127; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
  652. o.write_shift(-4, T === L[1] - 1 ? ENDOFCHAIN : T + 1);
  653. }
  654. }
  655. var chainit = function(w/*:number*/)/*:void*/ {
  656. for(T += w; i<T-1; ++i) o.write_shift(-4, i+1);
  657. if(w) { ++i; o.write_shift(-4, ENDOFCHAIN); }
  658. };
  659. T = i = 0;
  660. for(T+=L[1]; i<T; ++i) o.write_shift(-4, consts.DIFSECT);
  661. for(T+=L[2]; i<T; ++i) o.write_shift(-4, consts.FATSECT);
  662. chainit(L[3]);
  663. chainit(L[4]);
  664. var j/*:number*/ = 0, flen/*:number*/ = 0;
  665. var file/*:CFBEntry*/ = cfb.FileIndex[0];
  666. for(; j < cfb.FileIndex.length; ++j) {
  667. file = cfb.FileIndex[j];
  668. if(!file.content) continue;
  669. /*:: if(file.content == null) throw new Error("unreachable"); */
  670. flen = file.content.length;
  671. if(flen < 0x1000) continue;
  672. file.start = T;
  673. chainit((flen + 0x01FF) >> 9);
  674. }
  675. chainit((L[6] + 7) >> 3);
  676. while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
  677. T = i = 0;
  678. for(j = 0; j < cfb.FileIndex.length; ++j) {
  679. file = cfb.FileIndex[j];
  680. if(!file.content) continue;
  681. /*:: if(file.content == null) throw new Error("unreachable"); */
  682. flen = file.content.length;
  683. if(!flen || flen >= 0x1000) continue;
  684. file.start = T;
  685. chainit((flen + 0x3F) >> 6);
  686. }
  687. while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
  688. for(i = 0; i < L[4]<<2; ++i) {
  689. var nm = cfb.FullPaths[i];
  690. if(!nm || nm.length === 0) {
  691. for(j = 0; j < 17; ++j) o.write_shift(4, 0);
  692. for(j = 0; j < 3; ++j) o.write_shift(4, -1);
  693. for(j = 0; j < 12; ++j) o.write_shift(4, 0);
  694. continue;
  695. }
  696. file = cfb.FileIndex[i];
  697. if(i === 0) file.start = file.size ? file.start - 1 : ENDOFCHAIN;
  698. var _nm/*:string*/ = (i === 0 && _opts.root) || file.name;
  699. flen = 2*(_nm.length+1);
  700. o.write_shift(64, _nm, "utf16le");
  701. o.write_shift(2, flen);
  702. o.write_shift(1, file.type);
  703. o.write_shift(1, file.color);
  704. o.write_shift(-4, file.L);
  705. o.write_shift(-4, file.R);
  706. o.write_shift(-4, file.C);
  707. if(!file.clsid) for(j = 0; j < 4; ++j) o.write_shift(4, 0);
  708. else o.write_shift(16, file.clsid, "hex");
  709. o.write_shift(4, file.state || 0);
  710. o.write_shift(4, 0); o.write_shift(4, 0);
  711. o.write_shift(4, 0); o.write_shift(4, 0);
  712. o.write_shift(4, file.start);
  713. o.write_shift(4, file.size); o.write_shift(4, 0);
  714. }
  715. for(i = 1; i < cfb.FileIndex.length; ++i) {
  716. file = cfb.FileIndex[i];
  717. /*:: if(!file.content) throw new Error("unreachable"); */
  718. if(file.size >= 0x1000) {
  719. o.l = (file.start+1) << 9;
  720. for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
  721. for(; j & 0x1FF; ++j) o.write_shift(1, 0);
  722. }
  723. }
  724. for(i = 1; i < cfb.FileIndex.length; ++i) {
  725. file = cfb.FileIndex[i];
  726. /*:: if(!file.content) throw new Error("unreachable"); */
  727. if(file.size > 0 && file.size < 0x1000) {
  728. for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
  729. for(; j & 0x3F; ++j) o.write_shift(1, 0);
  730. }
  731. }
  732. while(o.l < o.length) o.write_shift(1, 0);
  733. return o;
  734. }
  735. /* [MS-CFB] 2.6.4 (Unicode 3.0.1 case conversion) */
  736. function find(cfb/*:CFBContainer*/, path/*:string*/)/*:?CFBEntry*/ {
  737. var UCFullPaths/*:Array<string>*/ = cfb.FullPaths.map(function(x) { return x.toUpperCase(); });
  738. var UCPaths/*:Array<string>*/ = UCFullPaths.map(function(x) { var y = x.split("/"); return y[y.length - (x.slice(-1) == "/" ? 2 : 1)]; });
  739. var k/*:boolean*/ = false;
  740. if(path.charCodeAt(0) === 47 /* "/" */) { k = true; path = UCFullPaths[0].slice(0, -1) + path; }
  741. else k = path.indexOf("/") !== -1;
  742. var UCPath/*:string*/ = path.toUpperCase();
  743. var w/*:number*/ = k === true ? UCFullPaths.indexOf(UCPath) : UCPaths.indexOf(UCPath);
  744. if(w !== -1) return cfb.FileIndex[w];
  745. var m = !UCPath.match(chr1);
  746. UCPath = UCPath.replace(chr0,'');
  747. if(m) UCPath = UCPath.replace(chr1,'!');
  748. for(w = 0; w < UCFullPaths.length; ++w) {
  749. if((m ? UCFullPaths[w].replace(chr1,'!') : UCFullPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
  750. if((m ? UCPaths[w].replace(chr1,'!') : UCPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
  751. }
  752. return null;
  753. }
  754. /** CFB Constants */
  755. var MSSZ = 64; /* Mini Sector Size = 1<<6 */
  756. //var MSCSZ = 4096; /* Mini Stream Cutoff Size */
  757. /* 2.1 Compound File Sector Numbers and Types */
  758. var ENDOFCHAIN = -2;
  759. /* 2.2 Compound File Header */
  760. var HEADER_SIGNATURE = 'd0cf11e0a1b11ae1';
  761. var HEADER_SIG = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
  762. var HEADER_CLSID = '00000000000000000000000000000000';
  763. var consts = {
  764. /* 2.1 Compund File Sector Numbers and Types */
  765. MAXREGSECT: -6,
  766. DIFSECT: -4,
  767. FATSECT: -3,
  768. ENDOFCHAIN: ENDOFCHAIN,
  769. FREESECT: -1,
  770. /* 2.2 Compound File Header */
  771. HEADER_SIGNATURE: HEADER_SIGNATURE,
  772. HEADER_MINOR_VERSION: '3e00',
  773. MAXREGSID: -6,
  774. NOSTREAM: -1,
  775. HEADER_CLSID: HEADER_CLSID,
  776. /* 2.6.1 Compound File Directory Entry */
  777. EntryTypes: ['unknown','storage','stream','lockbytes','property','root']
  778. };
  779. function write_file(cfb/*:CFBContainer*/, filename/*:string*/, options/*:CFBWriteOpts*/)/*:void*/ {
  780. get_fs();
  781. var o = _write(cfb, options);
  782. /*:: if(typeof Buffer == 'undefined' || !Buffer.isBuffer(o) || !(o instanceof Buffer)) throw new Error("unreachable"); */
  783. fs.writeFileSync(filename, o);
  784. }
  785. function a2s(o/*:RawBytes*/)/*:string*/ {
  786. var out = new Array(o.length);
  787. for(var i = 0; i < o.length; ++i) out[i] = String.fromCharCode(o[i]);
  788. return out.join("");
  789. }
  790. function write(cfb/*:CFBContainer*/, options/*:CFBWriteOpts*/)/*:RawBytes|string*/ {
  791. var o = _write(cfb, options);
  792. switch(options && options.type || "buffer") {
  793. case "file": get_fs(); fs.writeFileSync(options.filename, (o/*:any*/)); return o;
  794. case "binary": return typeof o == "string" ? o : a2s(o);
  795. case "base64": return Base64.encode(typeof o == "string" ? o : a2s(o));
  796. case "buffer": if(has_buf) return Buffer.isBuffer(o) ? o : Buffer_from(o);
  797. /* falls through */
  798. case "array": return typeof o == "string" ? s2a(o) : o;
  799. }
  800. return o;
  801. }
  802. /* node < 8.1 zlib does not expose bytesRead, so default to pure JS */
  803. var _zlib;
  804. function use_zlib(zlib) { try {
  805. var InflateRaw = zlib.InflateRaw;
  806. var InflRaw = new InflateRaw();
  807. InflRaw._processChunk(new Uint8Array([3, 0]), InflRaw._finishFlushFlag);
  808. if(InflRaw.bytesRead) _zlib = zlib;
  809. else throw new Error("zlib does not expose bytesRead");
  810. } catch(e) {console.error("cannot use native zlib: " + (e.message || e)); } }
  811. function _inflateRawSync(payload, usz) {
  812. if(!_zlib) return _inflate(payload, usz);
  813. var InflateRaw = _zlib.InflateRaw;
  814. var InflRaw = new InflateRaw();
  815. var out = InflRaw._processChunk(payload.slice(payload.l), InflRaw._finishFlushFlag);
  816. payload.l += InflRaw.bytesRead;
  817. return out;
  818. }
  819. function _deflateRawSync(payload) {
  820. return _zlib ? _zlib.deflateRawSync(payload) : _deflate(payload);
  821. }
  822. var CLEN_ORDER = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  823. /* LEN_ID = [ 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285 ]; */
  824. var LEN_LN = [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13 , 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 ];
  825. /* DST_ID = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 ]; */
  826. var DST_LN = [ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 ];
  827. function bit_swap_8(n) { var t = (((((n<<1)|(n<<11)) & 0x22110) | (((n<<5)|(n<<15)) & 0x88440))); return ((t>>16) | (t>>8) |t)&0xFF; }
  828. var use_typed_arrays = typeof Uint8Array !== 'undefined';
  829. var bitswap8 = use_typed_arrays ? new Uint8Array(1<<8) : [];
  830. for(var q = 0; q < (1<<8); ++q) bitswap8[q] = bit_swap_8(q);
  831. function bit_swap_n(n, b) {
  832. var rev = bitswap8[n & 0xFF];
  833. if(b <= 8) return rev >>> (8-b);
  834. rev = (rev << 8) | bitswap8[(n>>8)&0xFF];
  835. if(b <= 16) return rev >>> (16-b);
  836. rev = (rev << 8) | bitswap8[(n>>16)&0xFF];
  837. return rev >>> (24-b);
  838. }
  839. /* helpers for unaligned bit reads */
  840. function read_bits_2(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 6 ? 0 : buf[h+1]<<8))>>>w)& 0x03; }
  841. function read_bits_3(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 5 ? 0 : buf[h+1]<<8))>>>w)& 0x07; }
  842. function read_bits_4(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 4 ? 0 : buf[h+1]<<8))>>>w)& 0x0F; }
  843. function read_bits_5(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 3 ? 0 : buf[h+1]<<8))>>>w)& 0x1F; }
  844. function read_bits_7(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 1 ? 0 : buf[h+1]<<8))>>>w)& 0x7F; }
  845. /* works up to n = 3 * 8 + 1 = 25 */
  846. function read_bits_n(buf, bl, n) {
  847. var w = (bl&7), h = (bl>>>3), f = ((1<<n)-1);
  848. var v = buf[h] >>> w;
  849. if(n < 8 - w) return v & f;
  850. v |= buf[h+1]<<(8-w);
  851. if(n < 16 - w) return v & f;
  852. v |= buf[h+2]<<(16-w);
  853. if(n < 24 - w) return v & f;
  854. v |= buf[h+3]<<(24-w);
  855. return v & f;
  856. }
  857. /* until ArrayBuffer#realloc is a thing, fake a realloc */
  858. function realloc(b, sz/*:number*/) {
  859. var L = b.length, M = 2*L > sz ? 2*L : sz + 5, i = 0;
  860. if(L >= sz) return b;
  861. if(has_buf) {
  862. var o = new_unsafe_buf(M);
  863. // $FlowIgnore
  864. if(b.copy) b.copy(o);
  865. else for(; i < b.length; ++i) o[i] = b[i];
  866. return o;
  867. } else if(use_typed_arrays) {
  868. var a = new Uint8Array(M);
  869. if(a.set) a.set(b);
  870. else for(; i < b.length; ++i) a[i] = b[i];
  871. return a;
  872. }
  873. b.length = M;
  874. return b;
  875. }
  876. /* zero-filled arrays for older browsers */
  877. function zero_fill_array(n) {
  878. var o = new Array(n);
  879. for(var i = 0; i < n; ++i) o[i] = 0;
  880. return o;
  881. }var _deflate = (function() {
  882. var _deflateRaw = (function() {
  883. return function deflateRaw(data, out) {
  884. var boff = 0;
  885. while(boff < data.length) {
  886. var L = Math.min(0xFFFF, data.length - boff);
  887. var h = boff + L == data.length;
  888. /* TODO: this is only type 0 stored */
  889. out.write_shift(1, +h);
  890. out.write_shift(2, L);
  891. out.write_shift(2, (~L) & 0xFFFF);
  892. while(L-- > 0) out[out.l++] = data[boff++];
  893. }
  894. return out.l;
  895. };
  896. })();
  897. return function(data) {
  898. var buf = new_buf(50+Math.floor(data.length*1.1));
  899. var off = _deflateRaw(data, buf);
  900. return buf.slice(0, off);
  901. };
  902. })();
  903. /* modified inflate function also moves original read head */
  904. /* build tree (used for literals and lengths) */
  905. function build_tree(clens, cmap, MAX/*:number*/)/*:number*/ {
  906. var maxlen = 1, w = 0, i = 0, j = 0, ccode = 0, L = clens.length;
  907. var bl_count = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  908. for(i = 0; i < 32; ++i) bl_count[i] = 0;
  909. for(i = L; i < MAX; ++i) clens[i] = 0;
  910. L = clens.length;
  911. var ctree = use_typed_arrays ? new Uint16Array(L) : zero_fill_array(L); // []
  912. /* build code tree */
  913. for(i = 0; i < L; ++i) {
  914. bl_count[(w = clens[i])]++;
  915. if(maxlen < w) maxlen = w;
  916. ctree[i] = 0;
  917. }
  918. bl_count[0] = 0;
  919. for(i = 1; i <= maxlen; ++i) bl_count[i+16] = (ccode = (ccode + bl_count[i-1])<<1);
  920. for(i = 0; i < L; ++i) {
  921. ccode = clens[i];
  922. if(ccode != 0) ctree[i] = bl_count[ccode+16]++;
  923. }
  924. /* cmap[maxlen + 4 bits] = (off&15) + (lit<<4) reverse mapping */
  925. var cleni = 0;
  926. for(i = 0; i < L; ++i) {
  927. cleni = clens[i];
  928. if(cleni != 0) {
  929. ccode = bit_swap_n(ctree[i], maxlen)>>(maxlen-cleni);
  930. for(j = (1<<(maxlen + 4 - cleni)) - 1; j>=0; --j)
  931. cmap[ccode|(j<<cleni)] = (cleni&15) | (i<<4);
  932. }
  933. }
  934. return maxlen;
  935. }
  936. var fix_lmap = use_typed_arrays ? new Uint16Array(512) : zero_fill_array(512);
  937. var fix_dmap = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  938. if(!use_typed_arrays) {
  939. for(var i = 0; i < 512; ++i) fix_lmap[i] = 0;
  940. for(i = 0; i < 32; ++i) fix_dmap[i] = 0;
  941. }
  942. (function() {
  943. var dlens/*:Array<number>*/ = [];
  944. var i = 0;
  945. for(;i<32; i++) dlens.push(5);
  946. build_tree(dlens, fix_dmap, 32);
  947. var clens/*:Array<number>*/ = [];
  948. i = 0;
  949. for(; i<=143; i++) clens.push(8);
  950. for(; i<=255; i++) clens.push(9);
  951. for(; i<=279; i++) clens.push(7);
  952. for(; i<=287; i++) clens.push(8);
  953. build_tree(clens, fix_lmap, 288);
  954. })();
  955. var dyn_lmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  956. var dyn_dmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  957. var dyn_cmap = use_typed_arrays ? new Uint16Array(128) : zero_fill_array(128);
  958. var dyn_len_1 = 1, dyn_len_2 = 1;
  959. /* 5.5.3 Expanding Huffman Codes */
  960. function dyn(data, boff/*:number*/) {
  961. /* nomenclature from RFC1951 refers to bit values; these are offset by the implicit constant */
  962. var _HLIT = read_bits_5(data, boff) + 257; boff += 5;
  963. var _HDIST = read_bits_5(data, boff) + 1; boff += 5;
  964. var _HCLEN = read_bits_4(data, boff) + 4; boff += 4;
  965. var w = 0;
  966. /* grab and store code lengths */
  967. var clens = use_typed_arrays ? new Uint8Array(19) : zero_fill_array(19);
  968. var ctree = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
  969. var maxlen = 1;
  970. var bl_count = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
  971. var next_code = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
  972. var L = clens.length; /* 19 */
  973. for(var i = 0; i < _HCLEN; ++i) {
  974. clens[CLEN_ORDER[i]] = w = read_bits_3(data, boff);
  975. if(maxlen < w) maxlen = w;
  976. bl_count[w]++;
  977. boff += 3;
  978. }
  979. /* build code tree */
  980. var ccode = 0;
  981. bl_count[0] = 0;
  982. for(i = 1; i <= maxlen; ++i) next_code[i] = ccode = (ccode + bl_count[i-1])<<1;
  983. for(i = 0; i < L; ++i) if((ccode = clens[i]) != 0) ctree[i] = next_code[ccode]++;
  984. /* cmap[7 bits from stream] = (off&7) + (lit<<3) */
  985. var cleni = 0;
  986. for(i = 0; i < L; ++i) {
  987. cleni = clens[i];
  988. if(cleni != 0) {
  989. ccode = bitswap8[ctree[i]]>>(8-cleni);
  990. for(var j = (1<<(7-cleni))-1; j>=0; --j) dyn_cmap[ccode|(j<<cleni)] = (cleni&7) | (i<<3);
  991. }
  992. }
  993. /* read literal and dist codes at once */
  994. var hcodes/*:Array<number>*/ = [];
  995. maxlen = 1;
  996. for(; hcodes.length < _HLIT + _HDIST;) {
  997. ccode = dyn_cmap[read_bits_7(data, boff)];
  998. boff += ccode & 7;
  999. switch((ccode >>>= 3)) {
  1000. case 16:
  1001. w = 3 + read_bits_2(data, boff); boff += 2;
  1002. ccode = hcodes[hcodes.length - 1];
  1003. while(w-- > 0) hcodes.push(ccode);
  1004. break;
  1005. case 17:
  1006. w = 3 + read_bits_3(data, boff); boff += 3;
  1007. while(w-- > 0) hcodes.push(0);
  1008. break;
  1009. case 18:
  1010. w = 11 + read_bits_7(data, boff); boff += 7;
  1011. while(w -- > 0) hcodes.push(0);
  1012. break;
  1013. default:
  1014. hcodes.push(ccode);
  1015. if(maxlen < ccode) maxlen = ccode;
  1016. break;
  1017. }
  1018. }
  1019. /* build literal / length trees */
  1020. var h1 = hcodes.slice(0, _HLIT), h2 = hcodes.slice(_HLIT);
  1021. for(i = _HLIT; i < 286; ++i) h1[i] = 0;
  1022. for(i = _HDIST; i < 30; ++i) h2[i] = 0;
  1023. dyn_len_1 = build_tree(h1, dyn_lmap, 286);
  1024. dyn_len_2 = build_tree(h2, dyn_dmap, 30);
  1025. return boff;
  1026. }
  1027. /* return [ data, bytesRead ] */
  1028. function inflate(data, usz/*:number*/) {
  1029. /* shortcircuit for empty buffer [0x03, 0x00] */
  1030. if(data[0] == 3 && !(data[1] & 0x3)) { return [new_raw_buf(usz), 2]; }
  1031. /* bit offset */
  1032. var boff = 0;
  1033. /* header includes final bit and type bits */
  1034. var header = 0;
  1035. var outbuf = new_unsafe_buf(usz ? usz : (1<<18));
  1036. var woff = 0;
  1037. var OL = outbuf.length>>>0;
  1038. var max_len_1 = 0, max_len_2 = 0;
  1039. while((header&1) == 0) {
  1040. header = read_bits_3(data, boff); boff += 3;
  1041. if((header >>> 1) == 0) {
  1042. /* Stored block */
  1043. if(boff & 7) boff += 8 - (boff&7);
  1044. /* 2 bytes sz, 2 bytes bit inverse */
  1045. var sz = data[boff>>>3] | data[(boff>>>3)+1]<<8;
  1046. boff += 32;
  1047. /* push sz bytes */
  1048. if(!usz && OL < woff + sz) { outbuf = realloc(outbuf, woff + sz); OL = outbuf.length; }
  1049. if(typeof data.copy === 'function') {
  1050. // $FlowIgnore
  1051. data.copy(outbuf, woff, boff>>>3, (boff>>>3)+sz);
  1052. woff += sz; boff += 8*sz;
  1053. } else while(sz-- > 0) { outbuf[woff++] = data[boff>>>3]; boff += 8; }
  1054. continue;
  1055. } else if((header >>> 1) == 1) {
  1056. /* Fixed Huffman */
  1057. max_len_1 = 9; max_len_2 = 5;
  1058. } else {
  1059. /* Dynamic Huffman */
  1060. boff = dyn(data, boff);
  1061. max_len_1 = dyn_len_1; max_len_2 = dyn_len_2;
  1062. }
  1063. if(!usz && (OL < woff + 32767)) { outbuf = realloc(outbuf, woff + 32767); OL = outbuf.length; }
  1064. for(;;) { // while(true) is apparently out of vogue in modern JS circles
  1065. /* ingest code and move read head */
  1066. var bits = read_bits_n(data, boff, max_len_1);
  1067. var code = (header>>>1) == 1 ? fix_lmap[bits] : dyn_lmap[bits];
  1068. boff += code & 15; code >>>= 4;
  1069. /* 0-255 are literals, 256 is end of block token, 257+ are copy tokens */
  1070. if(((code>>>8)&0xFF) === 0) outbuf[woff++] = code;
  1071. else if(code == 256) break;
  1072. else {
  1073. code -= 257;
  1074. var len_eb = (code < 8) ? 0 : ((code-4)>>2); if(len_eb > 5) len_eb = 0;
  1075. var tgt = woff + LEN_LN[code];
  1076. /* length extra bits */
  1077. if(len_eb > 0) {
  1078. tgt += read_bits_n(data, boff, len_eb);
  1079. boff += len_eb;
  1080. }
  1081. /* dist code */
  1082. bits = read_bits_n(data, boff, max_len_2);
  1083. code = (header>>>1) == 1 ? fix_dmap[bits] : dyn_dmap[bits];
  1084. boff += code & 15; code >>>= 4;
  1085. var dst_eb = (code < 4 ? 0 : (code-2)>>1);
  1086. var dst = DST_LN[code];
  1087. /* dist extra bits */
  1088. if(dst_eb > 0) {
  1089. dst += read_bits_n(data, boff, dst_eb);
  1090. boff += dst_eb;
  1091. }
  1092. /* in the common case, manual byte copy is faster than TA set / Buffer copy */
  1093. if(!usz && OL < tgt) { outbuf = realloc(outbuf, tgt); OL = outbuf.length; }
  1094. while(woff < tgt) { outbuf[woff] = outbuf[woff - dst]; ++woff; }
  1095. }
  1096. }
  1097. }
  1098. return [usz ? outbuf : outbuf.slice(0, woff), (boff+7)>>>3];
  1099. }
  1100. function _inflate(payload, usz) {
  1101. var data = payload.slice(payload.l||0);
  1102. var out = inflate(data, usz);
  1103. payload.l += out[1];
  1104. return out[0];
  1105. }
  1106. function warn_or_throw(wrn, msg) {
  1107. if(wrn) { if(typeof console !== 'undefined') console.error(msg); }
  1108. else throw new Error(msg);
  1109. }
  1110. function parse_zip(file/*:RawBytes*/, options/*:CFBReadOpts*/)/*:CFBContainer*/ {
  1111. var blob/*:CFBlob*/ = /*::(*/file/*:: :any)*/;
  1112. prep_blob(blob, 0);
  1113. var FileIndex/*:CFBFileIndex*/ = [], FullPaths/*:Array<string>*/ = [];
  1114. var o = {
  1115. FileIndex: FileIndex,
  1116. FullPaths: FullPaths
  1117. };
  1118. init_cfb(o, { root: options.root });
  1119. /* find end of central directory, start just after signature */
  1120. var i = blob.length - 4;
  1121. while((blob[i] != 0x50 || blob[i+1] != 0x4b || blob[i+2] != 0x05 || blob[i+3] != 0x06) && i >= 0) --i;
  1122. blob.l = i + 4;
  1123. /* parse end of central directory */
  1124. blob.l += 4;
  1125. var fcnt = blob.read_shift(2);
  1126. blob.l += 6;
  1127. var start_cd = blob.read_shift(4);
  1128. /* parse central directory */
  1129. blob.l = start_cd;
  1130. for(i = 0; i < fcnt; ++i) {
  1131. /* trust local file header instead of CD entry */
  1132. blob.l += 20;
  1133. var csz = blob.read_shift(4);
  1134. var usz = blob.read_shift(4);
  1135. var namelen = blob.read_shift(2);
  1136. var efsz = blob.read_shift(2);
  1137. var fcsz = blob.read_shift(2);
  1138. blob.l += 8;
  1139. var offset = blob.read_shift(4);
  1140. var EF = parse_extra_field(/*::(*/blob.slice(blob.l+namelen, blob.l+namelen+efsz)/*:: :any)*/);
  1141. blob.l += namelen + efsz + fcsz;
  1142. var L = blob.l;
  1143. blob.l = offset + 4;
  1144. parse_local_file(blob, csz, usz, o, EF);
  1145. blob.l = L;
  1146. }
  1147. return o;
  1148. }
  1149. /* head starts just after local file header signature */
  1150. function parse_local_file(blob/*:CFBlob*/, csz/*:number*/, usz/*:number*/, o/*:CFBContainer*/, EF) {
  1151. /* [local file header] */
  1152. blob.l += 2;
  1153. var flags = blob.read_shift(2);
  1154. var meth = blob.read_shift(2);
  1155. var date = parse_dos_date(blob);
  1156. if(flags & 0x2041) throw new Error("Unsupported ZIP encryption");
  1157. var crc32 = blob.read_shift(4);
  1158. var _csz = blob.read_shift(4);
  1159. var _usz = blob.read_shift(4);
  1160. var namelen = blob.read_shift(2);
  1161. var efsz = blob.read_shift(2);
  1162. // TODO: flags & (1<<11) // UTF8
  1163. var name = ""; for(var i = 0; i < namelen; ++i) name += String.fromCharCode(blob[blob.l++]);
  1164. if(efsz) {
  1165. var ef = parse_extra_field(/*::(*/blob.slice(blob.l, blob.l + efsz)/*:: :any)*/);
  1166. if((ef[0x5455]||{}).mt) date = ef[0x5455].mt;
  1167. if(((EF||{})[0x5455]||{}).mt) date = EF[0x5455].mt;
  1168. }
  1169. blob.l += efsz;
  1170. /* [encryption header] */
  1171. /* [file data] */
  1172. var data = blob.slice(blob.l, blob.l + _csz);
  1173. switch(meth) {
  1174. case 8: data = _inflateRawSync(blob, _usz); break;
  1175. case 0: break;
  1176. default: throw new Error("Unsupported ZIP Compression method " + meth);
  1177. }
  1178. /* [data descriptor] */
  1179. var wrn = false;
  1180. if(flags & 8) {
  1181. crc32 = blob.read_shift(4);
  1182. if(crc32 == 0x08074b50) { crc32 = blob.read_shift(4); wrn = true; }
  1183. _csz = blob.read_shift(4);
  1184. _usz = blob.read_shift(4);
  1185. }
  1186. if(_csz != csz) warn_or_throw(wrn, "Bad compressed size: " + csz + " != " + _csz);
  1187. if(_usz != usz) warn_or_throw(wrn, "Bad uncompressed size: " + usz + " != " + _usz);
  1188. var _crc32 = CRC32.buf(data, 0);
  1189. if((crc32>>0) != (_crc32>>0)) warn_or_throw(wrn, "Bad CRC32 checksum: " + crc32 + " != " + _crc32);
  1190. cfb_add(o, name, data, {unsafe: true, mt: date});
  1191. }
  1192. function write_zip(cfb/*:CFBContainer*/, options/*:CFBWriteOpts*/)/*:RawBytes*/ {
  1193. var _opts = options || {};
  1194. var out = [], cdirs = [];
  1195. var o/*:CFBlob*/ = new_buf(1);
  1196. var method = (_opts.compression ? 8 : 0), flags = 0;
  1197. var desc = false;
  1198. if(desc) flags |= 8;
  1199. var i = 0, j = 0;
  1200. var start_cd = 0, fcnt = 0;
  1201. var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
  1202. var crcs = [];
  1203. var sz_cd = 0;
  1204. for(i = 1; i < cfb.FullPaths.length; ++i) {
  1205. fp = cfb.FullPaths[i].slice(root.length); fi = cfb.FileIndex[i];
  1206. if(!fi.size || !fi.content || fp == "\u0001Sh33tJ5") continue;
  1207. var start = start_cd;
  1208. /* TODO: CP437 filename */
  1209. var namebuf = new_buf(fp.length);
  1210. for(j = 0; j < fp.length; ++j) namebuf.write_shift(1, fp.charCodeAt(j) & 0x7F);
  1211. namebuf = namebuf.slice(0, namebuf.l);
  1212. crcs[fcnt] = CRC32.buf(/*::((*/fi.content/*::||[]):any)*/, 0);
  1213. var outbuf = fi.content/*::||[]*/;
  1214. if(method == 8) outbuf = _deflateRawSync(outbuf);
  1215. /* local file header */
  1216. o = new_buf(30);
  1217. o.write_shift(4, 0x04034b50);
  1218. o.write_shift(2, 20);
  1219. o.write_shift(2, flags);
  1220. o.write_shift(2, method);
  1221. /* TODO: last mod file time/date */
  1222. if(fi.mt) write_dos_date(o, fi.mt);
  1223. else o.write_shift(4, 0);
  1224. o.write_shift(-4, (flags & 8) ? 0 : crcs[fcnt]);
  1225. o.write_shift(4, (flags & 8) ? 0 : outbuf.length);
  1226. o.write_shift(4, (flags & 8) ? 0 : /*::(*/fi.content/*::||[])*/.length);
  1227. o.write_shift(2, namebuf.length);
  1228. o.write_shift(2, 0);
  1229. start_cd += o.length;
  1230. out.push(o);
  1231. start_cd += namebuf.length;
  1232. out.push(namebuf);
  1233. /* TODO: encryption header ? */
  1234. start_cd += outbuf.length;
  1235. out.push(outbuf);
  1236. /* data descriptor */
  1237. if(flags & 8) {
  1238. o = new_buf(12);
  1239. o.write_shift(-4, crcs[fcnt]);
  1240. o.write_shift(4, outbuf.length);
  1241. o.write_shift(4, /*::(*/fi.content/*::||[])*/.length);
  1242. start_cd += o.l;
  1243. out.push(o);
  1244. }
  1245. /* central directory */
  1246. o = new_buf(46);
  1247. o.write_shift(4, 0x02014b50);
  1248. o.write_shift(2, 0);
  1249. o.write_shift(2, 20);
  1250. o.write_shift(2, flags);
  1251. o.write_shift(2, method);
  1252. o.write_shift(4, 0); /* TODO: last mod file time/date */
  1253. o.write_shift(-4, crcs[fcnt]);
  1254. o.write_shift(4, outbuf.length);
  1255. o.write_shift(4, /*::(*/fi.content/*::||[])*/.length);
  1256. o.write_shift(2, namebuf.length);
  1257. o.write_shift(2, 0);
  1258. o.write_shift(2, 0);
  1259. o.write_shift(2, 0);
  1260. o.write_shift(2, 0);
  1261. o.write_shift(4, 0);
  1262. o.write_shift(4, start);
  1263. sz_cd += o.l;
  1264. cdirs.push(o);
  1265. sz_cd += namebuf.length;
  1266. cdirs.push(namebuf);
  1267. ++fcnt;
  1268. }
  1269. /* end of central directory */
  1270. o = new_buf(22);
  1271. o.write_shift(4, 0x06054b50);
  1272. o.write_shift(2, 0);
  1273. o.write_shift(2, 0);
  1274. o.write_shift(2, fcnt);
  1275. o.write_shift(2, fcnt);
  1276. o.write_shift(4, sz_cd);
  1277. o.write_shift(4, start_cd);
  1278. o.write_shift(2, 0);
  1279. return bconcat(([bconcat((out/*:any*/)), bconcat(cdirs), o]/*:any*/));
  1280. }
  1281. var ContentTypeMap = ({
  1282. "htm": "text/html",
  1283. "xml": "text/xml",
  1284. "gif": "image/gif",
  1285. "jpg": "image/jpeg",
  1286. "png": "image/png",
  1287. "mso": "application/x-mso",
  1288. "thmx": "application/vnd.ms-officetheme",
  1289. "sh33tj5": "application/octet-stream"
  1290. }/*:any*/);
  1291. function get_content_type(fi/*:CFBEntry*/, fp/*:string*/)/*:string*/ {
  1292. if(fi.ctype) return fi.ctype;
  1293. var ext = fi.name || "", m = ext.match(/\.([^\.]+)$/);
  1294. if(m && ContentTypeMap[m[1]]) return ContentTypeMap[m[1]];
  1295. if(fp) {
  1296. m = (ext = fp).match(/[\.\\]([^\.\\])+$/);
  1297. if(m && ContentTypeMap[m[1]]) return ContentTypeMap[m[1]];
  1298. }
  1299. return "application/octet-stream";
  1300. }
  1301. /* 76 character chunks TODO: intertwine encoding */
  1302. function write_base64_76(bstr/*:string*/)/*:string*/ {
  1303. var data = Base64.encode(bstr);
  1304. var o = [];
  1305. for(var i = 0; i < data.length; i+= 76) o.push(data.slice(i, i+76));
  1306. return o.join("\r\n") + "\r\n";
  1307. }
  1308. /*
  1309. Rules for QP:
  1310. - escape =## applies for all non-display characters and literal "="
  1311. - space or tab at end of line must be encoded
  1312. - \r\n newlines can be preserved, but bare \r and \n must be escaped
  1313. - lines must not exceed 76 characters, use soft breaks =\r\n
  1314. TODO: Some files from word appear to write line extensions with bare equals:
  1315. ```
  1316. <table class=3DMsoTableGrid border=3D1 cellspacing=3D0 cellpadding=3D0 width=
  1317. ="70%"
  1318. ```
  1319. */
  1320. function write_quoted_printable(text/*:string*/)/*:string*/ {
  1321. var encoded = text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF=]/g, function(c) {
  1322. var w = c.charCodeAt(0).toString(16).toUpperCase();
  1323. return "=" + (w.length == 1 ? "0" + w : w);
  1324. });
  1325. encoded = encoded.replace(/ $/mg, "=20").replace(/\t$/mg, "=09");
  1326. if(encoded.charAt(0) == "\n") encoded = "=0D" + encoded.slice(1);
  1327. encoded = encoded.replace(/\r(?!\n)/mg, "=0D").replace(/\n\n/mg, "\n=0A").replace(/([^\r\n])\n/mg, "$1=0A");
  1328. var o/*:Array<string>*/ = [], split = encoded.split("\r\n");
  1329. for(var si = 0; si < split.length; ++si) {
  1330. var str = split[si];
  1331. if(str.length == 0) { o.push(""); continue; }
  1332. for(var i = 0; i < str.length;) {
  1333. var end = 76;
  1334. var tmp = str.slice(i, i + end);
  1335. if(tmp.charAt(end - 1) == "=") end --;
  1336. else if(tmp.charAt(end - 2) == "=") end -= 2;
  1337. else if(tmp.charAt(end - 3) == "=") end -= 3;
  1338. tmp = str.slice(i, i + end);
  1339. i += end;
  1340. if(i < str.length) tmp += "=";
  1341. o.push(tmp);
  1342. }
  1343. }
  1344. return o.join("\r\n");
  1345. }
  1346. function parse_quoted_printable(data/*:Array<string>*/)/*:RawBytes*/ {
  1347. var o = [];
  1348. /* unify long lines */
  1349. for(var di = 0; di < data.length; ++di) {
  1350. var line = data[di];
  1351. while(di <= data.length && line.charAt(line.length - 1) == "=") line = line.slice(0, line.length - 1) + data[++di];
  1352. o.push(line);
  1353. }
  1354. /* decode */
  1355. for(var oi = 0; oi < o.length; ++oi) o[oi] = o[oi].replace(/=[0-9A-Fa-f]{2}/g, function($$) { return String.fromCharCode(parseInt($$.slice(1), 16)); });
  1356. return s2a(o.join("\r\n"));
  1357. }
  1358. function parse_mime(cfb/*:CFBContainer*/, data/*:Array<string>*/, root/*:string*/)/*:void*/ {
  1359. var fname = "", cte = "", ctype = "", fdata;
  1360. var di = 0;
  1361. for(;di < 10; ++di) {
  1362. var line = data[di];
  1363. if(!line || line.match(/^\s*$/)) break;
  1364. var m = line.match(/^(.*?):\s*([^\s].*)$/);
  1365. if(m) switch(m[1].toLowerCase()) {
  1366. case "content-location": fname = m[2].trim(); break;
  1367. case "content-type": ctype = m[2].trim(); break;
  1368. case "content-transfer-encoding": cte = m[2].trim(); break;
  1369. }
  1370. }
  1371. ++di;
  1372. switch(cte.toLowerCase()) {
  1373. case 'base64': fdata = s2a(Base64.decode(data.slice(di).join(""))); break;
  1374. case 'quoted-printable': fdata = parse_quoted_printable(data.slice(di)); break;
  1375. default: throw new Error("Unsupported Content-Transfer-Encoding " + cte);
  1376. }
  1377. var file = cfb_add(cfb, fname.slice(root.length), fdata, {unsafe: true});
  1378. if(ctype) file.ctype = ctype;
  1379. }
  1380. function parse_mad(file/*:RawBytes*/, options/*:CFBReadOpts*/)/*:CFBContainer*/ {
  1381. if(a2s(file.slice(0,13)).toLowerCase() != "mime-version:") throw new Error("Unsupported MAD header");
  1382. var root = (options && options.root || "");
  1383. // $FlowIgnore
  1384. var data = (has_buf && Buffer.isBuffer(file) ? file.toString("binary") : a2s(file)).split("\r\n");
  1385. var di = 0, row = "";
  1386. /* if root is not specified, scan for the common prefix */
  1387. for(di = 0; di < data.length; ++di) {
  1388. row = data[di];
  1389. if(!/^Content-Location:/i.test(row)) continue;
  1390. row = row.slice(row.indexOf("file"));
  1391. if(!root) root = row.slice(0, row.lastIndexOf("/") + 1);
  1392. if(row.slice(0, root.length) == root) continue;
  1393. while(root.length > 0) {
  1394. root = root.slice(0, root.length - 1);
  1395. root = root.slice(0, root.lastIndexOf("/") + 1);
  1396. if(row.slice(0,root.length) == root) break;
  1397. }
  1398. }
  1399. var mboundary = (data[1] || "").match(/boundary="(.*?)"/);
  1400. if(!mboundary) throw new Error("MAD cannot find boundary");
  1401. var boundary = "--" + (mboundary[1] || "");
  1402. var FileIndex/*:CFBFileIndex*/ = [], FullPaths/*:Array<string>*/ = [];
  1403. var o = {
  1404. FileIndex: FileIndex,
  1405. FullPaths: FullPaths
  1406. };
  1407. init_cfb(o);
  1408. var start_di, fcnt = 0;
  1409. for(di = 0; di < data.length; ++di) {
  1410. var line = data[di];
  1411. if(line !== boundary && line !== boundary + "--") continue;
  1412. if(fcnt++) parse_mime(o, data.slice(start_di, di), root);
  1413. start_di = di;
  1414. }
  1415. return o;
  1416. }
  1417. function write_mad(cfb/*:CFBContainer*/, options/*:CFBWriteOpts*/)/*:string*/ {
  1418. var opts = options || {};
  1419. var boundary = opts.boundary || "SheetJS";
  1420. boundary = '------=' + boundary;
  1421. var out = [
  1422. 'MIME-Version: 1.0',
  1423. 'Content-Type: multipart/related; boundary="' + boundary.slice(2) + '"',
  1424. '',
  1425. '',
  1426. ''
  1427. ];
  1428. var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
  1429. for(var i = 1; i < cfb.FullPaths.length; ++i) {
  1430. fp = cfb.FullPaths[i].slice(root.length);
  1431. fi = cfb.FileIndex[i];
  1432. if(!fi.size || !fi.content || fp == "\u0001Sh33tJ5") continue;
  1433. /* Normalize filename */
  1434. fp = fp.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF]/g, function(c) {
  1435. return "_x" + c.charCodeAt(0).toString(16) + "_";
  1436. }).replace(/[\u0080-\uFFFF]/g, function(u) {
  1437. return "_u" + u.charCodeAt(0).toString(16) + "_";
  1438. });
  1439. /* Extract content as binary string */
  1440. var ca = fi.content;
  1441. // $FlowIgnore
  1442. var cstr = has_buf && Buffer.isBuffer(ca) ? ca.toString("binary") : a2s(ca);
  1443. /* 4/5 of first 1024 chars ascii -> quoted printable, else base64 */
  1444. var dispcnt = 0, L = Math.min(1024, cstr.length), cc = 0;
  1445. for(var csl = 0; csl <= L; ++csl) if((cc=cstr.charCodeAt(csl)) >= 0x20 && cc < 0x80) ++dispcnt;
  1446. var qp = dispcnt >= L * 4 / 5;
  1447. out.push(boundary);
  1448. out.push('Content-Location: ' + (opts.root || 'file:///C:/SheetJS/') + fp);
  1449. out.push('Content-Transfer-Encoding: ' + (qp ? 'quoted-printable' : 'base64'));
  1450. out.push('Content-Type: ' + get_content_type(fi, fp));
  1451. out.push('');
  1452. out.push(qp ? write_quoted_printable(cstr) : write_base64_76(cstr));
  1453. }
  1454. out.push(boundary + '--\r\n');
  1455. return out.join("\r\n");
  1456. }function cfb_new(opts/*:?any*/)/*:CFBContainer*/ {
  1457. var o/*:CFBContainer*/ = ({}/*:any*/);
  1458. init_cfb(o, opts);
  1459. return o;
  1460. }
  1461. function cfb_add(cfb/*:CFBContainer*/, name/*:string*/, content/*:?RawBytes*/, opts/*:?any*/)/*:CFBEntry*/ {
  1462. var unsafe = opts && opts.unsafe;
  1463. if(!unsafe) init_cfb(cfb);
  1464. var file = !unsafe && CFB.find(cfb, name);
  1465. if(!file) {
  1466. var fpath/*:string*/ = cfb.FullPaths[0];
  1467. if(name.slice(0, fpath.length) == fpath) fpath = name;
  1468. else {
  1469. if(fpath.slice(-1) != "/") fpath += "/";
  1470. fpath = (fpath + name).replace("//","/");
  1471. }
  1472. file = ({name: filename(name), type: 2}/*:any*/);
  1473. cfb.FileIndex.push(file);
  1474. cfb.FullPaths.push(fpath);
  1475. if(!unsafe) CFB.utils.cfb_gc(cfb);
  1476. }
  1477. /*:: if(!file) throw new Error("unreachable"); */
  1478. file.content = (content/*:any*/);
  1479. file.size = content ? content.length : 0;
  1480. if(opts) {
  1481. if(opts.CLSID) file.clsid = opts.CLSID;
  1482. if(opts.mt) file.mt = opts.mt;
  1483. if(opts.ct) file.ct = opts.ct;
  1484. }
  1485. return file;
  1486. }
  1487. function cfb_del(cfb/*:CFBContainer*/, name/*:string*/)/*:boolean*/ {
  1488. init_cfb(cfb);
  1489. var file = CFB.find(cfb, name);
  1490. if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
  1491. cfb.FileIndex.splice(j, 1);
  1492. cfb.FullPaths.splice(j, 1);
  1493. return true;
  1494. }
  1495. return false;
  1496. }
  1497. function cfb_mov(cfb/*:CFBContainer*/, old_name/*:string*/, new_name/*:string*/)/*:boolean*/ {
  1498. init_cfb(cfb);
  1499. var file = CFB.find(cfb, old_name);
  1500. if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
  1501. cfb.FileIndex[j].name = filename(new_name);
  1502. cfb.FullPaths[j] = new_name;
  1503. return true;
  1504. }
  1505. return false;
  1506. }
  1507. function cfb_gc(cfb/*:CFBContainer*/)/*:void*/ { rebuild_cfb(cfb, true); }
  1508. exports.find = find;
  1509. exports.read = read;
  1510. exports.parse = parse;
  1511. exports.write = write;
  1512. exports.writeFile = write_file;
  1513. exports.utils = {
  1514. cfb_new: cfb_new,
  1515. cfb_add: cfb_add,
  1516. cfb_del: cfb_del,
  1517. cfb_mov: cfb_mov,
  1518. cfb_gc: cfb_gc,
  1519. ReadShift: ReadShift,
  1520. CheckField: CheckField,
  1521. prep_blob: prep_blob,
  1522. bconcat: bconcat,
  1523. use_zlib: use_zlib,
  1524. _deflateRaw: _deflate,
  1525. _inflateRaw: _inflate,
  1526. consts: consts
  1527. };
  1528. return exports;
  1529. })();
  1530. if(typeof require !== 'undefined' && typeof module !== 'undefined' && typeof DO_NOT_EXPORT_CFB === 'undefined') { module.exports = CFB; }