UNPKG

83.1 kBJavaScriptView Raw
1// DEFLATE is a complex format; to read this code, you should probably check the RFC first:
2// https://tools.ietf.org/html/rfc1951
3// You may also wish to take a look at the guide I made about this program:
4// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad
5// Some of the following code is similar to that of UZIP.js:
6// https://github.com/photopea/UZIP.js
7// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.
8// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint
9// is better for memory in most engines (I *think*).
10var ch2 = {};
11var durl = function (c) { return URL.createObjectURL(new Blob([c], { type: 'text/javascript' })); };
12var cwk = function (u) { return new Worker(u); };
13try {
14 URL.revokeObjectURL(durl(''));
15}
16catch (e) {
17 // We're in Deno or a very old browser
18 durl = function (c) { return 'data:application/javascript;charset=UTF-8,' + encodeURI(c); };
19 // If Deno, this is necessary; if not, this changes nothing
20 cwk = function (u) { return new Worker(u, { type: 'module' }); };
21}
22var wk = (function (c, id, msg, transfer, cb) {
23 var w = cwk(ch2[id] || (ch2[id] = durl(c)));
24 w.onerror = function (e) { return cb(e.error, null); };
25 w.onmessage = function (e) { return cb(null, e.data); };
26 w.postMessage(msg, transfer);
27 return w;
28});
29
30// aliases for shorter compressed code (most minifers don't do this)
31var u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;
32// fixed length extra bits
33var fleb = new u8([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, /* unused */ 0, 0, /* impossible */ 0]);
34// fixed distance extra bits
35// see fleb note
36var fdeb = new u8([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, /* unused */ 0, 0]);
37// code length index map
38var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
39// get base, reverse index map from extra bits
40var freb = function (eb, start) {
41 var b = new u16(31);
42 for (var i = 0; i < 31; ++i) {
43 b[i] = start += 1 << eb[i - 1];
44 }
45 // numbers here are at max 18 bits
46 var r = new u32(b[30]);
47 for (var i = 1; i < 30; ++i) {
48 for (var j = b[i]; j < b[i + 1]; ++j) {
49 r[j] = ((j - b[i]) << 5) | i;
50 }
51 }
52 return [b, r];
53};
54var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];
55// we can ignore the fact that the other numbers are wrong; they never happen anyway
56fl[28] = 258, revfl[258] = 28;
57var _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1];
58// map of value to reverse (assuming 16 bits)
59var rev = new u16(32768);
60for (var i = 0; i < 32768; ++i) {
61 // reverse table algorithm from SO
62 var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1);
63 x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2);
64 x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4);
65 rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;
66}
67// create huffman tree from u8 "map": index -> code length for code index
68// mb (max bits) must be at most 15
69// TODO: optimize/split up?
70var hMap = (function (cd, mb, r) {
71 var s = cd.length;
72 // index
73 var i = 0;
74 // u16 "map": index -> # of codes with bit length = index
75 var l = new u16(mb);
76 // length of cd must be 288 (total # of codes)
77 for (; i < s; ++i)
78 ++l[cd[i] - 1];
79 // u16 "map": index -> minimum code for bit length = index
80 var le = new u16(mb);
81 for (i = 0; i < mb; ++i) {
82 le[i] = (le[i - 1] + l[i - 1]) << 1;
83 }
84 var co;
85 if (r) {
86 // u16 "map": index -> number of actual bits, symbol for code
87 co = new u16(1 << mb);
88 // bits to remove for reverser
89 var rvb = 15 - mb;
90 for (i = 0; i < s; ++i) {
91 // ignore 0 lengths
92 if (cd[i]) {
93 // num encoding both symbol and bits read
94 var sv = (i << 4) | cd[i];
95 // free bits
96 var r_1 = mb - cd[i];
97 // start value
98 var v = le[cd[i] - 1]++ << r_1;
99 // m is end value
100 for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {
101 // every 16 bit value starting with the code yields the same result
102 co[rev[v] >>> rvb] = sv;
103 }
104 }
105 }
106 }
107 else {
108 co = new u16(s);
109 for (i = 0; i < s; ++i) {
110 if (cd[i]) {
111 co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]);
112 }
113 }
114 }
115 return co;
116});
117// fixed length tree
118var flt = new u8(288);
119for (var i = 0; i < 144; ++i)
120 flt[i] = 8;
121for (var i = 144; i < 256; ++i)
122 flt[i] = 9;
123for (var i = 256; i < 280; ++i)
124 flt[i] = 7;
125for (var i = 280; i < 288; ++i)
126 flt[i] = 8;
127// fixed distance tree
128var fdt = new u8(32);
129for (var i = 0; i < 32; ++i)
130 fdt[i] = 5;
131// fixed length map
132var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);
133// fixed distance map
134var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
135// find max of array
136var max = function (a) {
137 var m = a[0];
138 for (var i = 1; i < a.length; ++i) {
139 if (a[i] > m)
140 m = a[i];
141 }
142 return m;
143};
144// read d, starting at bit p and mask with m
145var bits = function (d, p, m) {
146 var o = (p / 8) | 0;
147 return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;
148};
149// read d, starting at bit p continuing for at least 16 bits
150var bits16 = function (d, p) {
151 var o = (p / 8) | 0;
152 return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));
153};
154// get end of byte
155var shft = function (p) { return ((p / 8) | 0) + (p & 7 && 1); };
156// typed array slice - allows garbage collector to free original reference,
157// while being more compatible than .slice
158var slc = function (v, s, e) {
159 if (s == null || s < 0)
160 s = 0;
161 if (e == null || e > v.length)
162 e = v.length;
163 // can't use .constructor in case user-supplied
164 var n = new (v instanceof u16 ? u16 : v instanceof u32 ? u32 : u8)(e - s);
165 n.set(v.subarray(s, e));
166 return n;
167};
168// expands raw DEFLATE data
169var inflt = function (dat, buf, st) {
170 // source length
171 var sl = dat.length;
172 if (!sl || (st && !st.l && sl < 5))
173 return buf || new u8(0);
174 // have to estimate size
175 var noBuf = !buf || st;
176 // no state
177 var noSt = !st || st.i;
178 if (!st)
179 st = {};
180 // Assumes roughly 33% compression ratio average
181 if (!buf)
182 buf = new u8(sl * 3);
183 // ensure buffer can fit at least l elements
184 var cbuf = function (l) {
185 var bl = buf.length;
186 // need to increase size to fit
187 if (l > bl) {
188 // Double or set to necessary, whichever is greater
189 var nbuf = new u8(Math.max(bl * 2, l));
190 nbuf.set(buf);
191 buf = nbuf;
192 }
193 };
194 // last chunk bitpos bytes
195 var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
196 // total bits
197 var tbts = sl * 8;
198 do {
199 if (!lm) {
200 // BFINAL - this is only 1 when last chunk is next
201 st.f = final = bits(dat, pos, 1);
202 // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman
203 var type = bits(dat, pos + 1, 3);
204 pos += 3;
205 if (!type) {
206 // go to end of byte boundary
207 var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;
208 if (t > sl) {
209 if (noSt)
210 throw 'unexpected EOF';
211 break;
212 }
213 // ensure size
214 if (noBuf)
215 cbuf(bt + l);
216 // Copy over uncompressed data
217 buf.set(dat.subarray(s, t), bt);
218 // Get new bitpos, update byte count
219 st.b = bt += l, st.p = pos = t * 8;
220 continue;
221 }
222 else if (type == 1)
223 lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
224 else if (type == 2) {
225 // literal lengths
226 var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
227 var tl = hLit + bits(dat, pos + 5, 31) + 1;
228 pos += 14;
229 // length+distance tree
230 var ldt = new u8(tl);
231 // code length tree
232 var clt = new u8(19);
233 for (var i = 0; i < hcLen; ++i) {
234 // use index map to get real code
235 clt[clim[i]] = bits(dat, pos + i * 3, 7);
236 }
237 pos += hcLen * 3;
238 // code lengths bits
239 var clb = max(clt), clbmsk = (1 << clb) - 1;
240 // code lengths map
241 var clm = hMap(clt, clb, 1);
242 for (var i = 0; i < tl;) {
243 var r = clm[bits(dat, pos, clbmsk)];
244 // bits read
245 pos += r & 15;
246 // symbol
247 var s = r >>> 4;
248 // code length to copy
249 if (s < 16) {
250 ldt[i++] = s;
251 }
252 else {
253 // copy count
254 var c = 0, n = 0;
255 if (s == 16)
256 n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
257 else if (s == 17)
258 n = 3 + bits(dat, pos, 7), pos += 3;
259 else if (s == 18)
260 n = 11 + bits(dat, pos, 127), pos += 7;
261 while (n--)
262 ldt[i++] = c;
263 }
264 }
265 // length tree distance tree
266 var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
267 // max length bits
268 lbt = max(lt);
269 // max dist bits
270 dbt = max(dt);
271 lm = hMap(lt, lbt, 1);
272 dm = hMap(dt, dbt, 1);
273 }
274 else
275 throw 'invalid block type';
276 if (pos > tbts) {
277 if (noSt)
278 throw 'unexpected EOF';
279 break;
280 }
281 }
282 // Make sure the buffer can hold this + the largest possible addition
283 // Maximum chunk size (practically, theoretically infinite) is 2^17;
284 if (noBuf)
285 cbuf(bt + 131072);
286 var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
287 var lpos = pos;
288 for (;; lpos = pos) {
289 // bits read, code
290 var c = lm[bits16(dat, pos) & lms], sym = c >>> 4;
291 pos += c & 15;
292 if (pos > tbts) {
293 if (noSt)
294 throw 'unexpected EOF';
295 break;
296 }
297 if (!c)
298 throw 'invalid length/literal';
299 if (sym < 256)
300 buf[bt++] = sym;
301 else if (sym == 256) {
302 lpos = pos, lm = null;
303 break;
304 }
305 else {
306 var add = sym - 254;
307 // no extra bits needed if less
308 if (sym > 264) {
309 // index
310 var i = sym - 257, b = fleb[i];
311 add = bits(dat, pos, (1 << b) - 1) + fl[i];
312 pos += b;
313 }
314 // dist
315 var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4;
316 if (!d)
317 throw 'invalid distance';
318 pos += d & 15;
319 var dt = fd[dsym];
320 if (dsym > 3) {
321 var b = fdeb[dsym];
322 dt += bits16(dat, pos) & ((1 << b) - 1), pos += b;
323 }
324 if (pos > tbts) {
325 if (noSt)
326 throw 'unexpected EOF';
327 break;
328 }
329 if (noBuf)
330 cbuf(bt + 131072);
331 var end = bt + add;
332 for (; bt < end; bt += 4) {
333 buf[bt] = buf[bt - dt];
334 buf[bt + 1] = buf[bt + 1 - dt];
335 buf[bt + 2] = buf[bt + 2 - dt];
336 buf[bt + 3] = buf[bt + 3 - dt];
337 }
338 bt = end;
339 }
340 }
341 st.l = lm, st.p = lpos, st.b = bt;
342 if (lm)
343 final = 1, st.m = lbt, st.d = dm, st.n = dbt;
344 } while (!final);
345 return bt == buf.length ? buf : slc(buf, 0, bt);
346};
347// starting at p, write the minimum number of bits that can hold v to d
348var wbits = function (d, p, v) {
349 v <<= p & 7;
350 var o = (p / 8) | 0;
351 d[o] |= v;
352 d[o + 1] |= v >>> 8;
353};
354// starting at p, write the minimum number of bits (>8) that can hold v to d
355var wbits16 = function (d, p, v) {
356 v <<= p & 7;
357 var o = (p / 8) | 0;
358 d[o] |= v;
359 d[o + 1] |= v >>> 8;
360 d[o + 2] |= v >>> 16;
361};
362// creates code lengths from a frequency table
363var hTree = function (d, mb) {
364 // Need extra info to make a tree
365 var t = [];
366 for (var i = 0; i < d.length; ++i) {
367 if (d[i])
368 t.push({ s: i, f: d[i] });
369 }
370 var s = t.length;
371 var t2 = t.slice();
372 if (!s)
373 return [et, 0];
374 if (s == 1) {
375 var v = new u8(t[0].s + 1);
376 v[t[0].s] = 1;
377 return [v, 1];
378 }
379 t.sort(function (a, b) { return a.f - b.f; });
380 // after i2 reaches last ind, will be stopped
381 // freq must be greater than largest possible number of symbols
382 t.push({ s: -1, f: 25001 });
383 var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;
384 t[0] = { s: -1, f: l.f + r.f, l: l, r: r };
385 // efficient algorithm from UZIP.js
386 // i0 is lookbehind, i2 is lookahead - after processing two low-freq
387 // symbols that combined have high freq, will start processing i2 (high-freq,
388 // non-composite) symbols instead
389 // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/
390 while (i1 != s - 1) {
391 l = t[t[i0].f < t[i2].f ? i0++ : i2++];
392 r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
393 t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };
394 }
395 var maxSym = t2[0].s;
396 for (var i = 1; i < s; ++i) {
397 if (t2[i].s > maxSym)
398 maxSym = t2[i].s;
399 }
400 // code lengths
401 var tr = new u16(maxSym + 1);
402 // max bits in tree
403 var mbt = ln(t[i1 - 1], tr, 0);
404 if (mbt > mb) {
405 // more algorithms from UZIP.js
406 // TODO: find out how this code works (debt)
407 // ind debt
408 var i = 0, dt = 0;
409 // left cost
410 var lft = mbt - mb, cst = 1 << lft;
411 t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });
412 for (; i < s; ++i) {
413 var i2_1 = t2[i].s;
414 if (tr[i2_1] > mb) {
415 dt += cst - (1 << (mbt - tr[i2_1]));
416 tr[i2_1] = mb;
417 }
418 else
419 break;
420 }
421 dt >>>= lft;
422 while (dt > 0) {
423 var i2_2 = t2[i].s;
424 if (tr[i2_2] < mb)
425 dt -= 1 << (mb - tr[i2_2]++ - 1);
426 else
427 ++i;
428 }
429 for (; i >= 0 && dt; --i) {
430 var i2_3 = t2[i].s;
431 if (tr[i2_3] == mb) {
432 --tr[i2_3];
433 ++dt;
434 }
435 }
436 mbt = mb;
437 }
438 return [new u8(tr), mbt];
439};
440// get the max length and assign length codes
441var ln = function (n, l, d) {
442 return n.s == -1
443 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))
444 : (l[n.s] = d);
445};
446// length codes generation
447var lc = function (c) {
448 var s = c.length;
449 // Note that the semicolon was intentional
450 while (s && !c[--s])
451 ;
452 var cl = new u16(++s);
453 // ind num streak
454 var cli = 0, cln = c[0], cls = 1;
455 var w = function (v) { cl[cli++] = v; };
456 for (var i = 1; i <= s; ++i) {
457 if (c[i] == cln && i != s)
458 ++cls;
459 else {
460 if (!cln && cls > 2) {
461 for (; cls > 138; cls -= 138)
462 w(32754);
463 if (cls > 2) {
464 w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);
465 cls = 0;
466 }
467 }
468 else if (cls > 3) {
469 w(cln), --cls;
470 for (; cls > 6; cls -= 6)
471 w(8304);
472 if (cls > 2)
473 w(((cls - 3) << 5) | 8208), cls = 0;
474 }
475 while (cls--)
476 w(cln);
477 cls = 1;
478 cln = c[i];
479 }
480 }
481 return [cl.subarray(0, cli), s];
482};
483// calculate the length of output from tree, code lengths
484var clen = function (cf, cl) {
485 var l = 0;
486 for (var i = 0; i < cl.length; ++i)
487 l += cf[i] * cl[i];
488 return l;
489};
490// writes a fixed block
491// returns the new bit pos
492var wfblk = function (out, pos, dat) {
493 // no need to write 00 as type: TypedArray defaults to 0
494 var s = dat.length;
495 var o = shft(pos + 2);
496 out[o] = s & 255;
497 out[o + 1] = s >>> 8;
498 out[o + 2] = out[o] ^ 255;
499 out[o + 3] = out[o + 1] ^ 255;
500 for (var i = 0; i < s; ++i)
501 out[o + i + 4] = dat[i];
502 return (o + 4 + s) * 8;
503};
504// writes a block
505var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
506 wbits(out, p++, final);
507 ++lf[256];
508 var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1];
509 var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1];
510 var _c = lc(dlt), lclt = _c[0], nlc = _c[1];
511 var _d = lc(ddt), lcdt = _d[0], ndc = _d[1];
512 var lcfreq = new u16(19);
513 for (var i = 0; i < lclt.length; ++i)
514 lcfreq[lclt[i] & 31]++;
515 for (var i = 0; i < lcdt.length; ++i)
516 lcfreq[lcdt[i] & 31]++;
517 var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1];
518 var nlcc = 19;
519 for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
520 ;
521 var flen = (bl + 5) << 3;
522 var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
523 var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]);
524 if (flen <= ftlen && flen <= dtlen)
525 return wfblk(out, p, dat.subarray(bs, bs + bl));
526 var lm, ll, dm, dl;
527 wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
528 if (dtlen < ftlen) {
529 lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
530 var llm = hMap(lct, mlcb, 0);
531 wbits(out, p, nlc - 257);
532 wbits(out, p + 5, ndc - 1);
533 wbits(out, p + 10, nlcc - 4);
534 p += 14;
535 for (var i = 0; i < nlcc; ++i)
536 wbits(out, p + 3 * i, lct[clim[i]]);
537 p += 3 * nlcc;
538 var lcts = [lclt, lcdt];
539 for (var it = 0; it < 2; ++it) {
540 var clct = lcts[it];
541 for (var i = 0; i < clct.length; ++i) {
542 var len = clct[i] & 31;
543 wbits(out, p, llm[len]), p += lct[len];
544 if (len > 15)
545 wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12;
546 }
547 }
548 }
549 else {
550 lm = flm, ll = flt, dm = fdm, dl = fdt;
551 }
552 for (var i = 0; i < li; ++i) {
553 if (syms[i] > 255) {
554 var len = (syms[i] >>> 18) & 31;
555 wbits16(out, p, lm[len + 257]), p += ll[len + 257];
556 if (len > 7)
557 wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len];
558 var dst = syms[i] & 31;
559 wbits16(out, p, dm[dst]), p += dl[dst];
560 if (dst > 3)
561 wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst];
562 }
563 else {
564 wbits16(out, p, lm[syms[i]]), p += ll[syms[i]];
565 }
566 }
567 wbits16(out, p, lm[256]);
568 return p + ll[256];
569};
570// deflate options (nice << 13) | chain
571var deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
572// empty
573var et = /*#__PURE__*/ new u8(0);
574// compresses data into a raw DEFLATE buffer
575var dflt = function (dat, lvl, plvl, pre, post, lst) {
576 var s = dat.length;
577 var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);
578 // writing to this writes to the output buffer
579 var w = o.subarray(pre, o.length - post);
580 var pos = 0;
581 if (!lvl || s < 8) {
582 for (var i = 0; i <= s; i += 65535) {
583 // end
584 var e = i + 65535;
585 if (e < s) {
586 // write full block
587 pos = wfblk(w, pos, dat.subarray(i, e));
588 }
589 else {
590 // write final block
591 w[i] = lst;
592 pos = wfblk(w, pos, dat.subarray(i, s));
593 }
594 }
595 }
596 else {
597 var opt = deo[lvl - 1];
598 var n = opt >>> 13, c = opt & 8191;
599 var msk_1 = (1 << plvl) - 1;
600 // prev 2-byte val map curr 2-byte val map
601 var prev = new u16(32768), head = new u16(msk_1 + 1);
602 var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
603 var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };
604 // 24576 is an arbitrary number of maximum symbols per block
605 // 424 buffer for last block
606 var syms = new u32(25000);
607 // length/literal freq distance freq
608 var lf = new u16(288), df = new u16(32);
609 // l/lcnt exbits index l/lind waitdx bitpos
610 var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0;
611 for (; i < s; ++i) {
612 // hash value
613 // deopt when i > s - 3 - at end, deopt acceptable
614 var hv = hsh(i);
615 // index mod 32768 previous index mod
616 var imod = i & 32767, pimod = head[hv];
617 prev[imod] = pimod;
618 head[hv] = imod;
619 // We always should modify head and prev, but only add symbols if
620 // this data is not yet processed ("wait" for wait index)
621 if (wi <= i) {
622 // bytes remaining
623 var rem = s - i;
624 if ((lc_1 > 7000 || li > 24576) && rem > 423) {
625 pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
626 li = lc_1 = eb = 0, bs = i;
627 for (var j = 0; j < 286; ++j)
628 lf[j] = 0;
629 for (var j = 0; j < 30; ++j)
630 df[j] = 0;
631 }
632 // len dist chain
633 var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767;
634 if (rem > 2 && hv == hsh(i - dif)) {
635 var maxn = Math.min(n, rem) - 1;
636 var maxd = Math.min(32767, i);
637 // max possible length
638 // not capped at dif because decompressors implement "rolling" index population
639 var ml = Math.min(258, rem);
640 while (dif <= maxd && --ch_1 && imod != pimod) {
641 if (dat[i + l] == dat[i + l - dif]) {
642 var nl = 0;
643 for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)
644 ;
645 if (nl > l) {
646 l = nl, d = dif;
647 // break out early when we reach "nice" (we are satisfied enough)
648 if (nl > maxn)
649 break;
650 // now, find the rarest 2-byte sequence within this
651 // length of literals and search for that instead.
652 // Much faster than just using the start
653 var mmd = Math.min(dif, nl - 2);
654 var md = 0;
655 for (var j = 0; j < mmd; ++j) {
656 var ti = (i - dif + j + 32768) & 32767;
657 var pti = prev[ti];
658 var cd = (ti - pti + 32768) & 32767;
659 if (cd > md)
660 md = cd, pimod = ti;
661 }
662 }
663 }
664 // check the previous match
665 imod = pimod, pimod = prev[imod];
666 dif += (imod - pimod + 32768) & 32767;
667 }
668 }
669 // d will be nonzero only when a match was found
670 if (d) {
671 // store both dist and len data in one Uint32
672 // Make sure this is recognized as a len/dist with 28th bit (2^28)
673 syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];
674 var lin = revfl[l] & 31, din = revfd[d] & 31;
675 eb += fleb[lin] + fdeb[din];
676 ++lf[257 + lin];
677 ++df[din];
678 wi = i + l;
679 ++lc_1;
680 }
681 else {
682 syms[li++] = dat[i];
683 ++lf[dat[i]];
684 }
685 }
686 }
687 pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
688 // this is the easiest way to avoid needing to maintain state
689 if (!lst && pos & 7)
690 pos = wfblk(w, pos + 1, et);
691 }
692 return slc(o, 0, pre + shft(pos) + post);
693};
694// CRC32 table
695var crct = /*#__PURE__*/ (function () {
696 var t = new u32(256);
697 for (var i = 0; i < 256; ++i) {
698 var c = i, k = 9;
699 while (--k)
700 c = ((c & 1) && 0xEDB88320) ^ (c >>> 1);
701 t[i] = c;
702 }
703 return t;
704})();
705// CRC32
706var crc = function () {
707 var c = -1;
708 return {
709 p: function (d) {
710 // closures have awful performance
711 var cr = c;
712 for (var i = 0; i < d.length; ++i)
713 cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);
714 c = cr;
715 },
716 d: function () { return ~c; }
717 };
718};
719// Alder32
720var adler = function () {
721 var a = 1, b = 0;
722 return {
723 p: function (d) {
724 // closures have awful performance
725 var n = a, m = b;
726 var l = d.length;
727 for (var i = 0; i != l;) {
728 var e = Math.min(i + 2655, l);
729 for (; i < e; ++i)
730 m += n += d[i];
731 n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);
732 }
733 a = n, b = m;
734 },
735 d: function () {
736 a %= 65521, b %= 65521;
737 return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8);
738 }
739 };
740};
741;
742// deflate with opts
743var dopt = function (dat, opt, pre, post, st) {
744 return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st);
745};
746// Walmart object spread
747var mrg = function (a, b) {
748 var o = {};
749 for (var k in a)
750 o[k] = a[k];
751 for (var k in b)
752 o[k] = b[k];
753 return o;
754};
755// worker clone
756// This is possibly the craziest part of the entire codebase, despite how simple it may seem.
757// The only parameter to this function is a closure that returns an array of variables outside of the function scope.
758// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.
759// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).
760// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.
761// This took me three weeks to figure out how to do.
762var wcln = function (fn, fnStr, td) {
763 var dt = fn();
764 var st = fn.toString();
765 var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/ /g, '').split(',');
766 for (var i = 0; i < dt.length; ++i) {
767 var v = dt[i], k = ks[i];
768 if (typeof v == 'function') {
769 fnStr += ';' + k + '=';
770 var st_1 = v.toString();
771 if (v.prototype) {
772 // for global objects
773 if (st_1.indexOf('[native code]') != -1) {
774 var spInd = st_1.indexOf(' ', 8) + 1;
775 fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));
776 }
777 else {
778 fnStr += st_1;
779 for (var t in v.prototype)
780 fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();
781 }
782 }
783 else
784 fnStr += st_1;
785 }
786 else
787 td[k] = v;
788 }
789 return [fnStr, td];
790};
791var ch = [];
792// clone bufs
793var cbfs = function (v) {
794 var tl = [];
795 for (var k in v) {
796 if (v[k] instanceof u8 || v[k] instanceof u16 || v[k] instanceof u32)
797 tl.push((v[k] = new v[k].constructor(v[k])).buffer);
798 }
799 return tl;
800};
801// use a worker to execute code
802var wrkr = function (fns, init, id, cb) {
803 var _a;
804 if (!ch[id]) {
805 var fnStr = '', td_1 = {}, m = fns.length - 1;
806 for (var i = 0; i < m; ++i)
807 _a = wcln(fns[i], fnStr, td_1), fnStr = _a[0], td_1 = _a[1];
808 ch[id] = wcln(fns[m], fnStr, td_1);
809 }
810 var td = mrg({}, ch[id][1]);
811 return wk(ch[id][0] + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);
812};
813// base async inflate fn
814var bInflt = function () { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, hMap, max, bits, bits16, shft, slc, inflt, inflateSync, pbf, gu8]; };
815var bDflt = function () { return [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };
816// gzip extra
817var gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };
818// gunzip extra
819var guze = function () { return [gzs, gzl]; };
820// zlib extra
821var zle = function () { return [zlh, wbytes, adler]; };
822// unzlib extra
823var zule = function () { return [zlv]; };
824// post buf
825var pbf = function (msg) { return postMessage(msg, [msg.buffer]); };
826// get u8
827var gu8 = function (o) { return o && o.size && new u8(o.size); };
828// async helper
829var cbify = function (dat, opts, fns, init, id, cb) {
830 var w = wrkr(fns, init, id, function (err, dat) {
831 w.terminate();
832 cb(err, dat);
833 });
834 w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);
835 return function () { w.terminate(); };
836};
837// auto stream
838var astrm = function (strm) {
839 strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };
840 return function (ev) { return strm.push(ev.data[0], ev.data[1]); };
841};
842// async stream attach
843var astrmify = function (fns, strm, opts, init, id) {
844 var t;
845 var w = wrkr(fns, init, id, function (err, dat) {
846 if (err)
847 w.terminate(), strm.ondata.call(strm, err);
848 else {
849 if (dat[1])
850 w.terminate();
851 strm.ondata.call(strm, err, dat[0], dat[1]);
852 }
853 });
854 w.postMessage(opts);
855 strm.push = function (d, f) {
856 if (t)
857 throw 'stream finished';
858 if (!strm.ondata)
859 throw 'no stream handler';
860 w.postMessage([d, t = f], [d.buffer]);
861 };
862 strm.terminate = function () { w.terminate(); };
863};
864// read 2 bytes
865var b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };
866// read 4 bytes
867var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };
868var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };
869// write bytes
870var wbytes = function (d, b, v) {
871 for (; v; ++b)
872 d[b] = v, v >>>= 8;
873};
874// gzip header
875var gzh = function (c, o) {
876 var fn = o.filename;
877 c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix
878 if (o.mtime != 0)
879 wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));
880 if (fn) {
881 c[3] = 8;
882 for (var i = 0; i <= fn.length; ++i)
883 c[i + 10] = fn.charCodeAt(i);
884 }
885};
886// gzip footer: -8 to -4 = CRC, -4 to -0 is length
887// gzip start
888var gzs = function (d) {
889 if (d[0] != 31 || d[1] != 139 || d[2] != 8)
890 throw 'invalid gzip data';
891 var flg = d[3];
892 var st = 10;
893 if (flg & 4)
894 st += d[10] | (d[11] << 8) + 2;
895 for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])
896 ;
897 return st + (flg & 2);
898};
899// gzip length
900var gzl = function (d) {
901 var l = d.length;
902 return ((d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16) | (d[l - 1] << 24)) >>> 0;
903};
904// gzip header length
905var gzhl = function (o) { return 10 + ((o.filename && (o.filename.length + 1)) || 0); };
906// zlib header
907var zlh = function (c, o) {
908 var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
909 c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1);
910};
911// zlib valid
912var zlv = function (d) {
913 if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31))
914 throw 'invalid zlib data';
915 if (d[1] & 32)
916 throw 'invalid zlib data: preset dictionaries not supported';
917};
918function AsyncCmpStrm(opts, cb) {
919 if (!cb && typeof opts == 'function')
920 cb = opts, opts = {};
921 this.ondata = cb;
922 return opts;
923}
924// zlib footer: -4 to -0 is Adler32
925/**
926 * Streaming DEFLATE compression
927 */
928var Deflate = /*#__PURE__*/ (function () {
929 function Deflate(opts, cb) {
930 if (!cb && typeof opts == 'function')
931 cb = opts, opts = {};
932 this.ondata = cb;
933 this.o = opts || {};
934 }
935 Deflate.prototype.p = function (c, f) {
936 this.ondata(dopt(c, this.o, 0, 0, !f), f);
937 };
938 /**
939 * Pushes a chunk to be deflated
940 * @param chunk The chunk to push
941 * @param final Whether this is the last chunk
942 */
943 Deflate.prototype.push = function (chunk, final) {
944 if (this.d)
945 throw 'stream finished';
946 if (!this.ondata)
947 throw 'no stream handler';
948 this.d = final;
949 this.p(chunk, final || false);
950 };
951 return Deflate;
952}());
953export { Deflate };
954/**
955 * Asynchronous streaming DEFLATE compression
956 */
957var AsyncDeflate = /*#__PURE__*/ (function () {
958 function AsyncDeflate(opts, cb) {
959 astrmify([
960 bDflt,
961 function () { return [astrm, Deflate]; }
962 ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {
963 var strm = new Deflate(ev.data);
964 onmessage = astrm(strm);
965 }, 6);
966 }
967 return AsyncDeflate;
968}());
969export { AsyncDeflate };
970export function deflate(data, opts, cb) {
971 if (!cb)
972 cb = opts, opts = {};
973 if (typeof cb != 'function')
974 throw 'no callback';
975 return cbify(data, opts, [
976 bDflt,
977 ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);
978}
979/**
980 * Compresses data with DEFLATE without any wrapper
981 * @param data The data to compress
982 * @param opts The compression options
983 * @returns The deflated version of the data
984 */
985export function deflateSync(data, opts) {
986 return dopt(data, opts || {}, 0, 0);
987}
988/**
989 * Streaming DEFLATE decompression
990 */
991var Inflate = /*#__PURE__*/ (function () {
992 /**
993 * Creates an inflation stream
994 * @param cb The callback to call whenever data is inflated
995 */
996 function Inflate(cb) {
997 this.s = {};
998 this.p = new u8(0);
999 this.ondata = cb;
1000 }
1001 Inflate.prototype.e = function (c) {
1002 if (this.d)
1003 throw 'stream finished';
1004 if (!this.ondata)
1005 throw 'no stream handler';
1006 var l = this.p.length;
1007 var n = new u8(l + c.length);
1008 n.set(this.p), n.set(c, l), this.p = n;
1009 };
1010 Inflate.prototype.c = function (final) {
1011 this.d = this.s.i = final || false;
1012 var bts = this.s.b;
1013 var dt = inflt(this.p, this.o, this.s);
1014 this.ondata(slc(dt, bts, this.s.b), this.d);
1015 this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
1016 this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;
1017 };
1018 /**
1019 * Pushes a chunk to be inflated
1020 * @param chunk The chunk to push
1021 * @param final Whether this is the final chunk
1022 */
1023 Inflate.prototype.push = function (chunk, final) {
1024 this.e(chunk), this.c(final);
1025 };
1026 return Inflate;
1027}());
1028export { Inflate };
1029/**
1030 * Asynchronous streaming DEFLATE decompression
1031 */
1032var AsyncInflate = /*#__PURE__*/ (function () {
1033 /**
1034 * Creates an asynchronous inflation stream
1035 * @param cb The callback to call whenever data is deflated
1036 */
1037 function AsyncInflate(cb) {
1038 this.ondata = cb;
1039 astrmify([
1040 bInflt,
1041 function () { return [astrm, Inflate]; }
1042 ], this, 0, function () {
1043 var strm = new Inflate();
1044 onmessage = astrm(strm);
1045 }, 7);
1046 }
1047 return AsyncInflate;
1048}());
1049export { AsyncInflate };
1050export function inflate(data, opts, cb) {
1051 if (!cb)
1052 cb = opts, opts = {};
1053 if (typeof cb != 'function')
1054 throw 'no callback';
1055 return cbify(data, opts, [
1056 bInflt
1057 ], function (ev) { return pbf(inflateSync(ev.data[0], gu8(ev.data[1]))); }, 1, cb);
1058}
1059/**
1060 * Expands DEFLATE data with no wrapper
1061 * @param data The data to decompress
1062 * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.
1063 * @returns The decompressed version of the data
1064 */
1065export function inflateSync(data, out) {
1066 return inflt(data, out);
1067}
1068// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.
1069/**
1070 * Streaming GZIP compression
1071 */
1072var Gzip = /*#__PURE__*/ (function () {
1073 function Gzip(opts, cb) {
1074 this.c = crc();
1075 this.l = 0;
1076 this.v = 1;
1077 Deflate.call(this, opts, cb);
1078 }
1079 /**
1080 * Pushes a chunk to be GZIPped
1081 * @param chunk The chunk to push
1082 * @param final Whether this is the last chunk
1083 */
1084 Gzip.prototype.push = function (chunk, final) {
1085 Deflate.prototype.push.call(this, chunk, final);
1086 };
1087 Gzip.prototype.p = function (c, f) {
1088 this.c.p(c);
1089 this.l += c.length;
1090 var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, !f);
1091 if (this.v)
1092 gzh(raw, this.o), this.v = 0;
1093 if (f)
1094 wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);
1095 this.ondata(raw, f);
1096 };
1097 return Gzip;
1098}());
1099export { Gzip };
1100/**
1101 * Asynchronous streaming GZIP compression
1102 */
1103var AsyncGzip = /*#__PURE__*/ (function () {
1104 function AsyncGzip(opts, cb) {
1105 astrmify([
1106 bDflt,
1107 gze,
1108 function () { return [astrm, Deflate, Gzip]; }
1109 ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {
1110 var strm = new Gzip(ev.data);
1111 onmessage = astrm(strm);
1112 }, 8);
1113 }
1114 return AsyncGzip;
1115}());
1116export { AsyncGzip };
1117export function gzip(data, opts, cb) {
1118 if (!cb)
1119 cb = opts, opts = {};
1120 if (typeof cb != 'function')
1121 throw 'no callback';
1122 return cbify(data, opts, [
1123 bDflt,
1124 gze,
1125 function () { return [gzipSync]; }
1126 ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);
1127}
1128/**
1129 * Compresses data with GZIP
1130 * @param data The data to compress
1131 * @param opts The compression options
1132 * @returns The gzipped version of the data
1133 */
1134export function gzipSync(data, opts) {
1135 if (!opts)
1136 opts = {};
1137 var c = crc(), l = data.length;
1138 c.p(data);
1139 var d = dopt(data, opts, gzhl(opts), 8), s = d.length;
1140 return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;
1141}
1142/**
1143 * Streaming GZIP decompression
1144 */
1145var Gunzip = /*#__PURE__*/ (function () {
1146 /**
1147 * Creates a GUNZIP stream
1148 * @param cb The callback to call whenever data is inflated
1149 */
1150 function Gunzip(cb) {
1151 this.v = 1;
1152 Inflate.call(this, cb);
1153 }
1154 /**
1155 * Pushes a chunk to be GUNZIPped
1156 * @param chunk The chunk to push
1157 * @param final Whether this is the last chunk
1158 */
1159 Gunzip.prototype.push = function (chunk, final) {
1160 Inflate.prototype.e.call(this, chunk);
1161 if (this.v) {
1162 var s = this.p.length > 3 ? gzs(this.p) : 4;
1163 if (s >= this.p.length && !final)
1164 return;
1165 this.p = this.p.subarray(s), this.v = 0;
1166 }
1167 if (final) {
1168 if (this.p.length < 8)
1169 throw 'invalid gzip stream';
1170 this.p = this.p.subarray(0, -8);
1171 }
1172 // necessary to prevent TS from using the closure value
1173 // This allows for workerization to function correctly
1174 Inflate.prototype.c.call(this, final);
1175 };
1176 return Gunzip;
1177}());
1178export { Gunzip };
1179/**
1180 * Asynchronous streaming GZIP decompression
1181 */
1182var AsyncGunzip = /*#__PURE__*/ (function () {
1183 /**
1184 * Creates an asynchronous GUNZIP stream
1185 * @param cb The callback to call whenever data is deflated
1186 */
1187 function AsyncGunzip(cb) {
1188 this.ondata = cb;
1189 astrmify([
1190 bInflt,
1191 guze,
1192 function () { return [astrm, Inflate, Gunzip]; }
1193 ], this, 0, function () {
1194 var strm = new Gunzip();
1195 onmessage = astrm(strm);
1196 }, 9);
1197 }
1198 return AsyncGunzip;
1199}());
1200export { AsyncGunzip };
1201export function gunzip(data, opts, cb) {
1202 if (!cb)
1203 cb = opts, opts = {};
1204 if (typeof cb != 'function')
1205 throw 'no callback';
1206 return cbify(data, opts, [
1207 bInflt,
1208 guze,
1209 function () { return [gunzipSync]; }
1210 ], function (ev) { return pbf(gunzipSync(ev.data[0])); }, 3, cb);
1211}
1212/**
1213 * Expands GZIP data
1214 * @param data The data to decompress
1215 * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory.
1216 * @returns The decompressed version of the data
1217 */
1218export function gunzipSync(data, out) {
1219 return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data)));
1220}
1221/**
1222 * Streaming Zlib compression
1223 */
1224var Zlib = /*#__PURE__*/ (function () {
1225 function Zlib(opts, cb) {
1226 this.c = adler();
1227 this.v = 1;
1228 Deflate.call(this, opts, cb);
1229 }
1230 /**
1231 * Pushes a chunk to be zlibbed
1232 * @param chunk The chunk to push
1233 * @param final Whether this is the last chunk
1234 */
1235 Zlib.prototype.push = function (chunk, final) {
1236 Deflate.prototype.push.call(this, chunk, final);
1237 };
1238 Zlib.prototype.p = function (c, f) {
1239 this.c.p(c);
1240 var raw = dopt(c, this.o, this.v && 2, f && 4, !f);
1241 if (this.v)
1242 zlh(raw, this.o), this.v = 0;
1243 if (f)
1244 wbytes(raw, raw.length - 4, this.c.d());
1245 this.ondata(raw, f);
1246 };
1247 return Zlib;
1248}());
1249export { Zlib };
1250/**
1251 * Asynchronous streaming Zlib compression
1252 */
1253var AsyncZlib = /*#__PURE__*/ (function () {
1254 function AsyncZlib(opts, cb) {
1255 astrmify([
1256 bDflt,
1257 zle,
1258 function () { return [astrm, Deflate, Zlib]; }
1259 ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {
1260 var strm = new Zlib(ev.data);
1261 onmessage = astrm(strm);
1262 }, 10);
1263 }
1264 return AsyncZlib;
1265}());
1266export { AsyncZlib };
1267export function zlib(data, opts, cb) {
1268 if (!cb)
1269 cb = opts, opts = {};
1270 if (typeof cb != 'function')
1271 throw 'no callback';
1272 return cbify(data, opts, [
1273 bDflt,
1274 zle,
1275 function () { return [zlibSync]; }
1276 ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);
1277}
1278/**
1279 * Compress data with Zlib
1280 * @param data The data to compress
1281 * @param opts The compression options
1282 * @returns The zlib-compressed version of the data
1283 */
1284export function zlibSync(data, opts) {
1285 if (!opts)
1286 opts = {};
1287 var a = adler();
1288 a.p(data);
1289 var d = dopt(data, opts, 2, 4);
1290 return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;
1291}
1292/**
1293 * Streaming Zlib decompression
1294 */
1295var Unzlib = /*#__PURE__*/ (function () {
1296 /**
1297 * Creates a Zlib decompression stream
1298 * @param cb The callback to call whenever data is inflated
1299 */
1300 function Unzlib(cb) {
1301 this.v = 1;
1302 Inflate.call(this, cb);
1303 }
1304 /**
1305 * Pushes a chunk to be unzlibbed
1306 * @param chunk The chunk to push
1307 * @param final Whether this is the last chunk
1308 */
1309 Unzlib.prototype.push = function (chunk, final) {
1310 Inflate.prototype.e.call(this, chunk);
1311 if (this.v) {
1312 if (this.p.length < 2 && !final)
1313 return;
1314 this.p = this.p.subarray(2), this.v = 0;
1315 }
1316 if (final) {
1317 if (this.p.length < 4)
1318 throw 'invalid zlib stream';
1319 this.p = this.p.subarray(0, -4);
1320 }
1321 // necessary to prevent TS from using the closure value
1322 // This allows for workerization to function correctly
1323 Inflate.prototype.c.call(this, final);
1324 };
1325 return Unzlib;
1326}());
1327export { Unzlib };
1328/**
1329 * Asynchronous streaming Zlib decompression
1330 */
1331var AsyncUnzlib = /*#__PURE__*/ (function () {
1332 /**
1333 * Creates an asynchronous Zlib decompression stream
1334 * @param cb The callback to call whenever data is deflated
1335 */
1336 function AsyncUnzlib(cb) {
1337 this.ondata = cb;
1338 astrmify([
1339 bInflt,
1340 zule,
1341 function () { return [astrm, Inflate, Unzlib]; }
1342 ], this, 0, function () {
1343 var strm = new Unzlib();
1344 onmessage = astrm(strm);
1345 }, 11);
1346 }
1347 return AsyncUnzlib;
1348}());
1349export { AsyncUnzlib };
1350export function unzlib(data, opts, cb) {
1351 if (!cb)
1352 cb = opts, opts = {};
1353 if (typeof cb != 'function')
1354 throw 'no callback';
1355 return cbify(data, opts, [
1356 bInflt,
1357 zule,
1358 function () { return [unzlibSync]; }
1359 ], function (ev) { return pbf(unzlibSync(ev.data[0], gu8(ev.data[1]))); }, 5, cb);
1360}
1361/**
1362 * Expands Zlib data
1363 * @param data The data to decompress
1364 * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.
1365 * @returns The decompressed version of the data
1366 */
1367export function unzlibSync(data, out) {
1368 return inflt((zlv(data), data.subarray(2, -4)), out);
1369}
1370// Default algorithm for compression (used because having a known output size allows faster decompression)
1371export { gzip as compress, AsyncGzip as AsyncCompress };
1372// Default algorithm for compression (used because having a known output size allows faster decompression)
1373export { gzipSync as compressSync, Gzip as Compress };
1374/**
1375 * Streaming GZIP, Zlib, or raw DEFLATE decompression
1376 */
1377var Decompress = /*#__PURE__*/ (function () {
1378 /**
1379 * Creates a decompression stream
1380 * @param cb The callback to call whenever data is decompressed
1381 */
1382 function Decompress(cb) {
1383 this.G = Gunzip;
1384 this.I = Inflate;
1385 this.Z = Unzlib;
1386 this.ondata = cb;
1387 }
1388 /**
1389 * Pushes a chunk to be decompressed
1390 * @param chunk The chunk to push
1391 * @param final Whether this is the last chunk
1392 */
1393 Decompress.prototype.push = function (chunk, final) {
1394 if (!this.ondata)
1395 throw 'no stream handler';
1396 if (!this.s) {
1397 if (this.p && this.p.length) {
1398 var n = new u8(this.p.length + chunk.length);
1399 n.set(this.p), n.set(chunk, this.p.length);
1400 }
1401 else
1402 this.p = chunk;
1403 if (this.p.length > 2) {
1404 var _this_1 = this;
1405 var cb = function () { _this_1.ondata.apply(_this_1, arguments); };
1406 this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)
1407 ? new this.G(cb)
1408 : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))
1409 ? new this.I(cb)
1410 : new this.Z(cb);
1411 this.s.push(this.p, final);
1412 this.p = null;
1413 }
1414 }
1415 else
1416 this.s.push(chunk, final);
1417 };
1418 return Decompress;
1419}());
1420export { Decompress };
1421/**
1422 * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression
1423 */
1424var AsyncDecompress = /*#__PURE__*/ (function () {
1425 /**
1426 * Creates an asynchronous decompression stream
1427 * @param cb The callback to call whenever data is decompressed
1428 */
1429 function AsyncDecompress(cb) {
1430 this.G = AsyncGunzip;
1431 this.I = AsyncInflate;
1432 this.Z = AsyncUnzlib;
1433 this.ondata = cb;
1434 }
1435 /**
1436 * Pushes a chunk to be decompressed
1437 * @param chunk The chunk to push
1438 * @param final Whether this is the last chunk
1439 */
1440 AsyncDecompress.prototype.push = function (chunk, final) {
1441 Decompress.prototype.push.call(this, chunk, final);
1442 };
1443 return AsyncDecompress;
1444}());
1445export { AsyncDecompress };
1446export function decompress(data, opts, cb) {
1447 if (!cb)
1448 cb = opts, opts = {};
1449 if (typeof cb != 'function')
1450 throw 'no callback';
1451 return (data[0] == 31 && data[1] == 139 && data[2] == 8)
1452 ? gunzip(data, opts, cb)
1453 : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))
1454 ? inflate(data, opts, cb)
1455 : unzlib(data, opts, cb);
1456}
1457/**
1458 * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format
1459 * @param data The data to decompress
1460 * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.
1461 * @returns The decompressed version of the data
1462 */
1463export function decompressSync(data, out) {
1464 return (data[0] == 31 && data[1] == 139 && data[2] == 8)
1465 ? gunzipSync(data, out)
1466 : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))
1467 ? inflateSync(data, out)
1468 : unzlibSync(data, out);
1469}
1470// flatten a directory structure
1471var fltn = function (d, p, t, o) {
1472 for (var k in d) {
1473 var val = d[k], n = p + k;
1474 if (val instanceof u8)
1475 t[n] = [val, o];
1476 else if (Array.isArray(val))
1477 t[n] = [val[0], mrg(o, val[1])];
1478 else
1479 fltn(val, n + '/', t, o);
1480 }
1481};
1482// text encoder
1483var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();
1484// text decoder
1485var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();
1486// text decoder stream
1487var tds = 0;
1488try {
1489 td.decode(et, { stream: true });
1490 tds = 1;
1491}
1492catch (e) { }
1493// decode UTF8
1494var dutf8 = function (d) {
1495 for (var r = '', i = 0;;) {
1496 var c = d[i++];
1497 var eb = (c > 127) + (c > 223) + (c > 239);
1498 if (i + eb > d.length)
1499 return [r, slc(d, i - 1)];
1500 if (!eb)
1501 r += String.fromCharCode(c);
1502 else if (eb == 3) {
1503 c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,
1504 r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));
1505 }
1506 else if (eb & 1)
1507 r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));
1508 else
1509 r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));
1510 }
1511};
1512/**
1513 * Streaming UTF-8 decoding
1514 */
1515var DecodeUTF8 = /*#__PURE__*/ (function () {
1516 /**
1517 * Creates a UTF-8 decoding stream
1518 * @param cb The callback to call whenever data is decoded
1519 */
1520 function DecodeUTF8(cb) {
1521 this.ondata = cb;
1522 if (tds)
1523 this.t = new TextDecoder();
1524 else
1525 this.p = et;
1526 }
1527 /**
1528 * Pushes a chunk to be decoded from UTF-8 binary
1529 * @param chunk The chunk to push
1530 * @param final Whether this is the last chunk
1531 */
1532 DecodeUTF8.prototype.push = function (chunk, final) {
1533 if (!this.ondata)
1534 throw 'no callback';
1535 final = !!final;
1536 if (this.t) {
1537 this.ondata(this.t.decode(chunk, { stream: true }), final);
1538 if (final) {
1539 if (this.t.decode().length)
1540 throw 'invalid utf-8 data';
1541 this.t = null;
1542 }
1543 return;
1544 }
1545 if (!this.p)
1546 throw 'stream finished';
1547 var dat = new u8(this.p.length + chunk.length);
1548 dat.set(this.p);
1549 dat.set(chunk, this.p.length);
1550 var _a = dutf8(dat), ch = _a[0], np = _a[1];
1551 if (final) {
1552 if (np.length)
1553 throw 'invalid utf-8 data';
1554 this.p = null;
1555 }
1556 else
1557 this.p = np;
1558 this.ondata(ch, final);
1559 };
1560 return DecodeUTF8;
1561}());
1562export { DecodeUTF8 };
1563/**
1564 * Streaming UTF-8 encoding
1565 */
1566var EncodeUTF8 = /*#__PURE__*/ (function () {
1567 /**
1568 * Creates a UTF-8 decoding stream
1569 * @param cb The callback to call whenever data is encoded
1570 */
1571 function EncodeUTF8(cb) {
1572 this.ondata = cb;
1573 }
1574 /**
1575 * Pushes a chunk to be encoded to UTF-8
1576 * @param chunk The string data to push
1577 * @param final Whether this is the last chunk
1578 */
1579 EncodeUTF8.prototype.push = function (chunk, final) {
1580 if (!this.ondata)
1581 throw 'no callback';
1582 if (this.d)
1583 throw 'stream finished';
1584 this.ondata(strToU8(chunk), this.d = final || false);
1585 };
1586 return EncodeUTF8;
1587}());
1588export { EncodeUTF8 };
1589/**
1590 * Converts a string into a Uint8Array for use with compression/decompression methods
1591 * @param str The string to encode
1592 * @param latin1 Whether or not to interpret the data as Latin-1. This should
1593 * not need to be true unless decoding a binary string.
1594 * @returns The string encoded in UTF-8/Latin-1 binary
1595 */
1596export function strToU8(str, latin1) {
1597 if (latin1) {
1598 var ar_1 = new u8(str.length);
1599 for (var i = 0; i < str.length; ++i)
1600 ar_1[i] = str.charCodeAt(i);
1601 return ar_1;
1602 }
1603 if (te)
1604 return te.encode(str);
1605 var l = str.length;
1606 var ar = new u8(str.length + (str.length >> 1));
1607 var ai = 0;
1608 var w = function (v) { ar[ai++] = v; };
1609 for (var i = 0; i < l; ++i) {
1610 if (ai + 5 > ar.length) {
1611 var n = new u8(ai + 8 + ((l - i) << 1));
1612 n.set(ar);
1613 ar = n;
1614 }
1615 var c = str.charCodeAt(i);
1616 if (c < 128 || latin1)
1617 w(c);
1618 else if (c < 2048)
1619 w(192 | (c >> 6)), w(128 | (c & 63));
1620 else if (c > 55295 && c < 57344)
1621 c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),
1622 w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));
1623 else
1624 w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));
1625 }
1626 return slc(ar, 0, ai);
1627}
1628/**
1629 * Converts a Uint8Array to a string
1630 * @param dat The data to decode to string
1631 * @param latin1 Whether or not to interpret the data as Latin-1. This should
1632 * not need to be true unless encoding to binary string.
1633 * @returns The original UTF-8/Latin-1 string
1634 */
1635export function strFromU8(dat, latin1) {
1636 if (latin1) {
1637 var r = '';
1638 for (var i = 0; i < dat.length; i += 16384)
1639 r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));
1640 return r;
1641 }
1642 else if (td)
1643 return td.decode(dat);
1644 else {
1645 var _a = dutf8(dat), out = _a[0], ext = _a[1];
1646 if (ext.length)
1647 throw 'invalid utf-8 data';
1648 return out;
1649 }
1650}
1651;
1652// deflate bit flag
1653var dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };
1654// skip local zip header
1655var slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };
1656// read zip header
1657var zh = function (d, b, z) {
1658 var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);
1659 var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];
1660 return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];
1661};
1662// read zip64 extra field
1663var z64e = function (d, b) {
1664 for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))
1665 ;
1666 return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];
1667};
1668// extra field length
1669var exfl = function (ex) {
1670 var le = 0;
1671 if (ex) {
1672 for (var k in ex) {
1673 var l = ex[k].length;
1674 if (l > 65535)
1675 throw 'extra field too long';
1676 le += l + 4;
1677 }
1678 }
1679 return le;
1680};
1681// write zip header
1682var wzh = function (d, b, f, fn, u, c, ce, co) {
1683 var fl = fn.length, ex = f.extra, col = co && co.length;
1684 var exl = exfl(ex);
1685 wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;
1686 if (ce != null)
1687 d[b++] = 20, d[b++] = f.os;
1688 d[b] = 20, b += 2; // spec compliance? what's that?
1689 d[b++] = (f.flag << 1) | (c == null && 8), d[b++] = u && 8;
1690 d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
1691 var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
1692 if (y < 0 || y > 119)
1693 throw 'date not in range 1980-2099';
1694 wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >>> 1)), b += 4;
1695 if (c != null) {
1696 wbytes(d, b, f.crc);
1697 wbytes(d, b + 4, c);
1698 wbytes(d, b + 8, f.size);
1699 }
1700 wbytes(d, b + 12, fl);
1701 wbytes(d, b + 14, exl), b += 16;
1702 if (ce != null) {
1703 wbytes(d, b, col);
1704 wbytes(d, b + 6, f.attrs);
1705 wbytes(d, b + 10, ce), b += 14;
1706 }
1707 d.set(fn, b);
1708 b += fl;
1709 if (exl) {
1710 for (var k in ex) {
1711 var exf = ex[k], l = exf.length;
1712 wbytes(d, b, +k);
1713 wbytes(d, b + 2, l);
1714 d.set(exf, b + 4), b += 4 + l;
1715 }
1716 }
1717 if (col)
1718 d.set(co, b), b += col;
1719 return b;
1720};
1721// write zip footer (end of central directory)
1722var wzf = function (o, b, c, d, e) {
1723 wbytes(o, b, 0x6054B50); // skip disk
1724 wbytes(o, b + 8, c);
1725 wbytes(o, b + 10, c);
1726 wbytes(o, b + 12, d);
1727 wbytes(o, b + 16, e);
1728};
1729/**
1730 * A pass-through stream to keep data uncompressed in a ZIP archive.
1731 */
1732var ZipPassThrough = /*#__PURE__*/ (function () {
1733 /**
1734 * Creates a pass-through stream that can be added to ZIP archives
1735 * @param filename The filename to associate with this data stream
1736 */
1737 function ZipPassThrough(filename) {
1738 this.filename = filename;
1739 this.c = crc();
1740 this.size = 0;
1741 this.compression = 0;
1742 }
1743 /**
1744 * Processes a chunk and pushes to the output stream. You can override this
1745 * method in a subclass for custom behavior, but by default this passes
1746 * the data through. You must call this.ondata(err, chunk, final) at some
1747 * point in this method.
1748 * @param chunk The chunk to process
1749 * @param final Whether this is the last chunk
1750 */
1751 ZipPassThrough.prototype.process = function (chunk, final) {
1752 this.ondata(null, chunk, final);
1753 };
1754 /**
1755 * Pushes a chunk to be added. If you are subclassing this with a custom
1756 * compression algorithm, note that you must push data from the source
1757 * file only, pre-compression.
1758 * @param chunk The chunk to push
1759 * @param final Whether this is the last chunk
1760 */
1761 ZipPassThrough.prototype.push = function (chunk, final) {
1762 if (!this.ondata)
1763 throw 'no callback - add to ZIP archive before pushing';
1764 this.c.p(chunk);
1765 this.size += chunk.length;
1766 if (final)
1767 this.crc = this.c.d();
1768 this.process(chunk, final || false);
1769 };
1770 return ZipPassThrough;
1771}());
1772export { ZipPassThrough };
1773// I don't extend because TypeScript extension adds 1kB of runtime bloat
1774/**
1775 * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate
1776 * for better performance
1777 */
1778var ZipDeflate = /*#__PURE__*/ (function () {
1779 /**
1780 * Creates a DEFLATE stream that can be added to ZIP archives
1781 * @param filename The filename to associate with this data stream
1782 * @param opts The compression options
1783 */
1784 function ZipDeflate(filename, opts) {
1785 var _this_1 = this;
1786 if (!opts)
1787 opts = {};
1788 ZipPassThrough.call(this, filename);
1789 this.d = new Deflate(opts, function (dat, final) {
1790 _this_1.ondata(null, dat, final);
1791 });
1792 this.compression = 8;
1793 this.flag = dbf(opts.level);
1794 }
1795 ZipDeflate.prototype.process = function (chunk, final) {
1796 try {
1797 this.d.push(chunk, final);
1798 }
1799 catch (e) {
1800 this.ondata(e, null, final);
1801 }
1802 };
1803 /**
1804 * Pushes a chunk to be deflated
1805 * @param chunk The chunk to push
1806 * @param final Whether this is the last chunk
1807 */
1808 ZipDeflate.prototype.push = function (chunk, final) {
1809 ZipPassThrough.prototype.push.call(this, chunk, final);
1810 };
1811 return ZipDeflate;
1812}());
1813export { ZipDeflate };
1814/**
1815 * Asynchronous streaming DEFLATE compression for ZIP archives
1816 */
1817var AsyncZipDeflate = /*#__PURE__*/ (function () {
1818 /**
1819 * Creates a DEFLATE stream that can be added to ZIP archives
1820 * @param filename The filename to associate with this data stream
1821 * @param opts The compression options
1822 */
1823 function AsyncZipDeflate(filename, opts) {
1824 var _this_1 = this;
1825 if (!opts)
1826 opts = {};
1827 ZipPassThrough.call(this, filename);
1828 this.d = new AsyncDeflate(opts, function (err, dat, final) {
1829 _this_1.ondata(err, dat, final);
1830 });
1831 this.compression = 8;
1832 this.flag = dbf(opts.level);
1833 this.terminate = this.d.terminate;
1834 }
1835 AsyncZipDeflate.prototype.process = function (chunk, final) {
1836 this.d.push(chunk, final);
1837 };
1838 /**
1839 * Pushes a chunk to be deflated
1840 * @param chunk The chunk to push
1841 * @param final Whether this is the last chunk
1842 */
1843 AsyncZipDeflate.prototype.push = function (chunk, final) {
1844 ZipPassThrough.prototype.push.call(this, chunk, final);
1845 };
1846 return AsyncZipDeflate;
1847}());
1848export { AsyncZipDeflate };
1849// TODO: Better tree shaking
1850/**
1851 * A zippable archive to which files can incrementally be added
1852 */
1853var Zip = /*#__PURE__*/ (function () {
1854 /**
1855 * Creates an empty ZIP archive to which files can be added
1856 * @param cb The callback to call whenever data for the generated ZIP archive
1857 * is available
1858 */
1859 function Zip(cb) {
1860 this.ondata = cb;
1861 this.u = [];
1862 this.d = 1;
1863 }
1864 /**
1865 * Adds a file to the ZIP archive
1866 * @param file The file stream to add
1867 */
1868 Zip.prototype.add = function (file) {
1869 var _this_1 = this;
1870 if (this.d & 2)
1871 throw 'stream finished';
1872 var f = strToU8(file.filename), fl = f.length;
1873 var com = file.comment, o = com && strToU8(com);
1874 var u = fl != file.filename.length || (o && (com.length != o.length));
1875 var hl = fl + exfl(file.extra) + 30;
1876 if (fl > 65535)
1877 throw 'filename too long';
1878 var header = new u8(hl);
1879 wzh(header, 0, file, f, u);
1880 var chks = [header];
1881 var pAll = function () {
1882 for (var _i = 0, chks_1 = chks; _i < chks_1.length; _i++) {
1883 var chk = chks_1[_i];
1884 _this_1.ondata(null, chk, false);
1885 }
1886 chks = [];
1887 };
1888 var tr = this.d;
1889 this.d = 0;
1890 var ind = this.u.length;
1891 var uf = mrg(file, {
1892 f: f,
1893 u: u,
1894 o: o,
1895 t: function () {
1896 if (file.terminate)
1897 file.terminate();
1898 },
1899 r: function () {
1900 pAll();
1901 if (tr) {
1902 var nxt = _this_1.u[ind + 1];
1903 if (nxt)
1904 nxt.r();
1905 else
1906 _this_1.d = 1;
1907 }
1908 tr = 1;
1909 }
1910 });
1911 var cl = 0;
1912 file.ondata = function (err, dat, final) {
1913 if (err) {
1914 _this_1.ondata(err, dat, final);
1915 _this_1.terminate();
1916 }
1917 else {
1918 cl += dat.length;
1919 chks.push(dat);
1920 if (final) {
1921 var dd = new u8(16);
1922 wbytes(dd, 0, 0x8074B50);
1923 wbytes(dd, 4, file.crc);
1924 wbytes(dd, 8, cl);
1925 wbytes(dd, 12, file.size);
1926 chks.push(dd);
1927 uf.c = cl, uf.b = hl + cl + 16, uf.crc = file.crc, uf.size = file.size;
1928 if (tr)
1929 uf.r();
1930 tr = 1;
1931 }
1932 else if (tr)
1933 pAll();
1934 }
1935 };
1936 this.u.push(uf);
1937 };
1938 /**
1939 * Ends the process of adding files and prepares to emit the final chunks.
1940 * This *must* be called after adding all desired files for the resulting
1941 * ZIP file to work properly.
1942 */
1943 Zip.prototype.end = function () {
1944 var _this_1 = this;
1945 if (this.d & 2) {
1946 if (this.d & 1)
1947 throw 'stream finishing';
1948 throw 'stream finished';
1949 }
1950 if (this.d)
1951 this.e();
1952 else
1953 this.u.push({
1954 r: function () {
1955 if (!(_this_1.d & 1))
1956 return;
1957 _this_1.u.splice(-1, 1);
1958 _this_1.e();
1959 },
1960 t: function () { }
1961 });
1962 this.d = 3;
1963 };
1964 Zip.prototype.e = function () {
1965 var bt = 0, l = 0, tl = 0;
1966 for (var _i = 0, _a = this.u; _i < _a.length; _i++) {
1967 var f = _a[_i];
1968 tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);
1969 }
1970 var out = new u8(tl + 22);
1971 for (var _b = 0, _c = this.u; _b < _c.length; _b++) {
1972 var f = _c[_b];
1973 wzh(out, bt, f, f.f, f.u, f.c, l, f.o);
1974 bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;
1975 }
1976 wzf(out, bt, this.u.length, tl, l);
1977 this.ondata(null, out, true);
1978 this.d = 2;
1979 };
1980 /**
1981 * A method to terminate any internal workers used by the stream. Subsequent
1982 * calls to add() will fail.
1983 */
1984 Zip.prototype.terminate = function () {
1985 for (var _i = 0, _a = this.u; _i < _a.length; _i++) {
1986 var f = _a[_i];
1987 f.t();
1988 }
1989 this.d = 2;
1990 };
1991 return Zip;
1992}());
1993export { Zip };
1994export function zip(data, opts, cb) {
1995 if (!cb)
1996 cb = opts, opts = {};
1997 if (typeof cb != 'function')
1998 throw 'no callback';
1999 var r = {};
2000 fltn(data, '', r, opts);
2001 var k = Object.keys(r);
2002 var lft = k.length, o = 0, tot = 0;
2003 var slft = lft, files = new Array(lft);
2004 var term = [];
2005 var tAll = function () {
2006 for (var i = 0; i < term.length; ++i)
2007 term[i]();
2008 };
2009 var cbf = function () {
2010 var out = new u8(tot + 22), oe = o, cdl = tot - o;
2011 tot = 0;
2012 for (var i = 0; i < slft; ++i) {
2013 var f = files[i];
2014 try {
2015 var l = f.c.length;
2016 wzh(out, tot, f, f.f, f.u, l);
2017 var badd = 30 + f.f.length + exfl(f.extra);
2018 var loc = tot + badd;
2019 out.set(f.c, loc);
2020 wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;
2021 }
2022 catch (e) {
2023 return cb(e, null);
2024 }
2025 }
2026 wzf(out, o, files.length, cdl, oe);
2027 cb(null, out);
2028 };
2029 if (!lft)
2030 cbf();
2031 var _loop_1 = function (i) {
2032 var fn = k[i];
2033 var _a = r[fn], file = _a[0], p = _a[1];
2034 var c = crc(), size = file.length;
2035 c.p(file);
2036 var f = strToU8(fn), s = f.length;
2037 var com = p.comment, m = com && strToU8(com), ms = m && m.length;
2038 var exl = exfl(p.extra);
2039 var compression = p.level == 0 ? 0 : 8;
2040 var cbl = function (e, d) {
2041 if (e) {
2042 tAll();
2043 cb(e, null);
2044 }
2045 else {
2046 var l = d.length;
2047 files[i] = mrg(p, {
2048 size: size,
2049 crc: c.d(),
2050 c: d,
2051 f: f,
2052 m: m,
2053 u: s != fn.length || (m && (com.length != ms)),
2054 compression: compression
2055 });
2056 o += 30 + s + exl + l;
2057 tot += 76 + 2 * (s + exl) + (ms || 0) + l;
2058 if (!--lft)
2059 cbf();
2060 }
2061 };
2062 if (s > 65535)
2063 cbl('filename too long', null);
2064 if (!compression)
2065 cbl(null, file);
2066 else if (size < 160000) {
2067 try {
2068 cbl(null, deflateSync(file, p));
2069 }
2070 catch (e) {
2071 cbl(e, null);
2072 }
2073 }
2074 else
2075 term.push(deflate(file, p, cbl));
2076 };
2077 // Cannot use lft because it can decrease
2078 for (var i = 0; i < slft; ++i) {
2079 _loop_1(i);
2080 }
2081 return tAll;
2082}
2083/**
2084 * Synchronously creates a ZIP file. Prefer using `zip` for better performance
2085 * with more than one file.
2086 * @param data The directory structure for the ZIP archive
2087 * @param opts The main options, merged with per-file options
2088 * @returns The generated ZIP archive
2089 */
2090export function zipSync(data, opts) {
2091 if (!opts)
2092 opts = {};
2093 var r = {};
2094 var files = [];
2095 fltn(data, '', r, opts);
2096 var o = 0;
2097 var tot = 0;
2098 for (var fn in r) {
2099 var _a = r[fn], file = _a[0], p = _a[1];
2100 var compression = p.level == 0 ? 0 : 8;
2101 var f = strToU8(fn), s = f.length;
2102 var com = p.comment, m = com && strToU8(com), ms = m && m.length;
2103 var exl = exfl(p.extra);
2104 if (s > 65535)
2105 throw 'filename too long';
2106 var d = compression ? deflateSync(file, p) : file, l = d.length;
2107 var c = crc();
2108 c.p(file);
2109 files.push(mrg(p, {
2110 size: file.length,
2111 crc: c.d(),
2112 c: d,
2113 f: f,
2114 m: m,
2115 u: s != fn.length || (m && (com.length != ms)),
2116 o: o,
2117 compression: compression
2118 }));
2119 o += 30 + s + exl + l;
2120 tot += 76 + 2 * (s + exl) + (ms || 0) + l;
2121 }
2122 var out = new u8(tot + 22), oe = o, cdl = tot - o;
2123 for (var i = 0; i < files.length; ++i) {
2124 var f = files[i];
2125 wzh(out, f.o, f, f.f, f.u, f.c.length);
2126 var badd = 30 + f.f.length + exfl(f.extra);
2127 out.set(f.c, f.o + badd);
2128 wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
2129 }
2130 wzf(out, o, files.length, cdl, oe);
2131 return out;
2132}
2133/**
2134 * Streaming pass-through decompression for ZIP archives
2135 */
2136var UnzipPassThrough = /*#__PURE__*/ (function () {
2137 function UnzipPassThrough() {
2138 }
2139 UnzipPassThrough.prototype.push = function (data, final) {
2140 this.ondata(null, data, final);
2141 };
2142 UnzipPassThrough.compression = 0;
2143 return UnzipPassThrough;
2144}());
2145export { UnzipPassThrough };
2146/**
2147 * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for
2148 * better performance.
2149 */
2150var UnzipInflate = /*#__PURE__*/ (function () {
2151 /**
2152 * Creates a DEFLATE decompression that can be used in ZIP archives
2153 */
2154 function UnzipInflate() {
2155 var _this_1 = this;
2156 this.i = new Inflate(function (dat, final) {
2157 _this_1.ondata(null, dat, final);
2158 });
2159 }
2160 UnzipInflate.prototype.push = function (data, final) {
2161 try {
2162 this.i.push(data, final);
2163 }
2164 catch (e) {
2165 this.ondata(e, data, final);
2166 }
2167 };
2168 UnzipInflate.compression = 8;
2169 return UnzipInflate;
2170}());
2171export { UnzipInflate };
2172/**
2173 * Asynchronous streaming DEFLATE decompression for ZIP archives
2174 */
2175var AsyncUnzipInflate = /*#__PURE__*/ (function () {
2176 /**
2177 * Creates a DEFLATE decompression that can be used in ZIP archives
2178 */
2179 function AsyncUnzipInflate(_, sz) {
2180 var _this_1 = this;
2181 if (sz < 320000) {
2182 this.i = new Inflate(function (dat, final) {
2183 _this_1.ondata(null, dat, final);
2184 });
2185 }
2186 else {
2187 this.i = new AsyncInflate(function (err, dat, final) {
2188 _this_1.ondata(err, dat, final);
2189 });
2190 this.terminate = this.i.terminate;
2191 }
2192 }
2193 AsyncUnzipInflate.prototype.push = function (data, final) {
2194 if (this.i.terminate)
2195 data = slc(data, 0);
2196 this.i.push(data, final);
2197 };
2198 AsyncUnzipInflate.compression = 8;
2199 return AsyncUnzipInflate;
2200}());
2201export { AsyncUnzipInflate };
2202/**
2203 * A ZIP archive decompression stream that emits files as they are discovered
2204 */
2205var Unzip = /*#__PURE__*/ (function () {
2206 /**
2207 * Creates a ZIP decompression stream
2208 * @param cb The callback to call whenever a file in the ZIP archive is found
2209 */
2210 function Unzip(cb) {
2211 this.onfile = cb;
2212 this.k = [];
2213 this.o = {
2214 0: UnzipPassThrough
2215 };
2216 this.p = et;
2217 }
2218 /**
2219 * Pushes a chunk to be unzipped
2220 * @param chunk The chunk to push
2221 * @param final Whether this is the last chunk
2222 */
2223 Unzip.prototype.push = function (chunk, final) {
2224 var _this_1 = this;
2225 if (!this.onfile)
2226 throw 'no callback';
2227 if (!this.p)
2228 throw 'stream finished';
2229 if (this.c > 0) {
2230 var len = Math.min(this.c, chunk.length);
2231 var toAdd = chunk.subarray(0, len);
2232 this.c -= len;
2233 if (this.d)
2234 this.d.push(toAdd, !this.c);
2235 else
2236 this.k[0].push(toAdd);
2237 chunk = chunk.subarray(len);
2238 if (chunk.length)
2239 return this.push(chunk, final);
2240 }
2241 else {
2242 var f = 0, i = 0, is = void 0, buf = void 0;
2243 if (!this.p.length)
2244 buf = chunk;
2245 else if (!chunk.length)
2246 buf = this.p;
2247 else {
2248 buf = new u8(this.p.length + chunk.length);
2249 buf.set(this.p), buf.set(chunk, this.p.length);
2250 }
2251 var l = buf.length, oc = this.c, add = oc && this.d;
2252 var _loop_2 = function () {
2253 var _a;
2254 var sig = b4(buf, i);
2255 if (sig == 0x4034B50) {
2256 f = 1, is = i;
2257 this_1.d = null;
2258 this_1.c = 0;
2259 var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);
2260 if (l > i + 30 + fnl + es) {
2261 var chks_2 = [];
2262 this_1.k.unshift(chks_2);
2263 f = 2;
2264 var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);
2265 var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);
2266 if (sc_1 == 4294967295) {
2267 _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];
2268 }
2269 else if (dd)
2270 sc_1 = -1;
2271 i += es;
2272 this_1.c = sc_1;
2273 var d_1;
2274 var file_1 = {
2275 name: fn_1,
2276 compression: cmp_1,
2277 start: function () {
2278 if (!file_1.ondata)
2279 throw 'no callback';
2280 if (!sc_1)
2281 file_1.ondata(null, et, true);
2282 else {
2283 var ctr = _this_1.o[cmp_1];
2284 if (!ctr)
2285 throw 'unknown compression type ' + cmp_1;
2286 d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);
2287 d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };
2288 for (var _i = 0, chks_3 = chks_2; _i < chks_3.length; _i++) {
2289 var dat = chks_3[_i];
2290 d_1.push(dat, false);
2291 }
2292 if (_this_1.k[0] == chks_2 && _this_1.c)
2293 _this_1.d = d_1;
2294 else
2295 d_1.push(et, true);
2296 }
2297 },
2298 terminate: function () {
2299 if (d_1 && d_1.terminate)
2300 d_1.terminate();
2301 }
2302 };
2303 if (sc_1 >= 0)
2304 file_1.size = sc_1, file_1.originalSize = su_1;
2305 this_1.onfile(file_1);
2306 }
2307 return "break";
2308 }
2309 else if (oc) {
2310 if (sig == 0x8074B50) {
2311 is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;
2312 return "break";
2313 }
2314 else if (sig == 0x2014B50) {
2315 is = i -= 4, f = 3, this_1.c = 0;
2316 return "break";
2317 }
2318 }
2319 };
2320 var this_1 = this;
2321 for (; i < l - 4; ++i) {
2322 var state_1 = _loop_2();
2323 if (state_1 === "break")
2324 break;
2325 }
2326 this.p = et;
2327 if (oc < 0) {
2328 var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);
2329 if (add)
2330 add.push(dat, !!f);
2331 else
2332 this.k[+(f == 2)].push(dat);
2333 }
2334 if (f & 2)
2335 return this.push(buf.subarray(i), final);
2336 this.p = buf.subarray(i);
2337 }
2338 if (final) {
2339 if (this.c)
2340 throw 'invalid zip file';
2341 this.p = null;
2342 }
2343 };
2344 /**
2345 * Registers a decoder with the stream, allowing for files compressed with
2346 * the compression type provided to be expanded correctly
2347 * @param decoder The decoder constructor
2348 */
2349 Unzip.prototype.register = function (decoder) {
2350 this.o[decoder.compression] = decoder;
2351 };
2352 return Unzip;
2353}());
2354export { Unzip };
2355/**
2356 * Asynchronously decompresses a ZIP archive
2357 * @param data The raw compressed ZIP file
2358 * @param cb The callback to call with the decompressed files
2359 * @returns A function that can be used to immediately terminate the unzipping
2360 */
2361export function unzip(data, cb) {
2362 if (typeof cb != 'function')
2363 throw 'no callback';
2364 var term = [];
2365 var tAll = function () {
2366 for (var i = 0; i < term.length; ++i)
2367 term[i]();
2368 };
2369 var files = {};
2370 var e = data.length - 22;
2371 for (; b4(data, e) != 0x6054B50; --e) {
2372 if (!e || data.length - e > 65558) {
2373 cb('invalid zip file', null);
2374 return;
2375 }
2376 }
2377 ;
2378 var lft = b2(data, e + 8);
2379 if (!lft)
2380 cb(null, {});
2381 var c = lft;
2382 var o = b4(data, e + 16);
2383 var z = o == 4294967295;
2384 if (z) {
2385 e = b4(data, e - 12);
2386 if (b4(data, e) != 0x6064B50) {
2387 cb('invalid zip file', null);
2388 return;
2389 }
2390 c = lft = b4(data, e + 32);
2391 o = b4(data, e + 48);
2392 }
2393 var _loop_3 = function (i) {
2394 var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
2395 o = no;
2396 var cbl = function (e, d) {
2397 if (e) {
2398 tAll();
2399 cb(e, null);
2400 }
2401 else {
2402 files[fn] = d;
2403 if (!--lft)
2404 cb(null, files);
2405 }
2406 };
2407 if (!c_1)
2408 cbl(null, slc(data, b, b + sc));
2409 else if (c_1 == 8) {
2410 var infl = data.subarray(b, b + sc);
2411 if (sc < 320000) {
2412 try {
2413 cbl(null, inflateSync(infl, new u8(su)));
2414 }
2415 catch (e) {
2416 cbl(e, null);
2417 }
2418 }
2419 else
2420 term.push(inflate(infl, { size: su }, cbl));
2421 }
2422 else
2423 cbl('unknown compression type ' + c_1, null);
2424 };
2425 for (var i = 0; i < c; ++i) {
2426 _loop_3(i);
2427 }
2428 return tAll;
2429}
2430/**
2431 * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better
2432 * performance with more than one file.
2433 * @param data The raw compressed ZIP file
2434 * @returns The decompressed files
2435 */
2436export function unzipSync(data) {
2437 var files = {};
2438 var e = data.length - 22;
2439 for (; b4(data, e) != 0x6054B50; --e) {
2440 if (!e || data.length - e > 65558)
2441 throw 'invalid zip file';
2442 }
2443 ;
2444 var c = b2(data, e + 8);
2445 if (!c)
2446 return {};
2447 var o = b4(data, e + 16);
2448 var z = o == 4294967295;
2449 if (z) {
2450 e = b4(data, e - 12);
2451 if (b4(data, e) != 0x6064B50)
2452 throw 'invalid zip file';
2453 c = b4(data, e + 32);
2454 o = b4(data, e + 48);
2455 }
2456 for (var i = 0; i < c; ++i) {
2457 var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
2458 o = no;
2459 if (!c_2)
2460 files[fn] = slc(data, b, b + sc);
2461 else if (c_2 == 8)
2462 files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su));
2463 else
2464 throw 'unknown compression type ' + c_2;
2465 }
2466 return files;
2467}
2468
\No newline at end of file