/** * zlibmt: multi-threaded zlib, the block-parallel layout of zmat and jdai. * * A zlibmt stream is an ordinary zlib stream (any zlib reads it): the payload is deflated in * independent blocks (payload/16, from 256 KiB to 4 MiB, so the stream depends on the payload * alone, not on the number of threads), each but the last ended by a full flush (the empty stored * block 00 00 FF FF), joined after one zlib header, with the Adler-32 of the whole payload. * Encoding deflates the blocks in parallel; decoding inflates the stretches between such marks in * parallel, from any zlib stream, and keeps the result only when the lengths and the Adler-32 * agree (otherwise it inflates the stream as a whole), so every stream decodes correctly. * * Threads: Node's zlib thread pool (UV_THREADPOOL_SIZE, default 4) in Node.js; Web Workers * running this same script in browsers; else one thread (pako), still asynchronous. * * Copyright (c) 2019-2026 Qianqian Fang . BSD 3-clause license. */ import * as pako from 'pako'; declare const process: any, require: any, document: any, self: any, Worker: any, Blob: any, URL: any, navigator: any; declare const WorkerGlobalScope: any; /** Node's zlib module when running in Node.js (faster than pako), else null. */ export function nodeZlibModule(): any { try { if (typeof process !== 'undefined' && process.versions && process.versions.node) { if (typeof require === 'function') { return require('zlib'); } if (typeof process.getBuiltinModule === 'function') { return process.getBuiltinModule('zlib'); // (an ES module, Node.js 20.16 and later) } } } catch (e) { // (a bundle for the browser) } return null; } const NZ: any = nodeZlibModule(); // ---- Adler-32 ----------------------------------------------------------------------------------- /** The Adler-32 of bytes (from a, default 1). */ export function adler32(b: Uint8Array, a: number = 1): number { let s1 = a & 0xffff, s2 = a >>> 16; const n = b.length; let i = 0; while (i < n) { // (5552 bytes: the most before the sums can pass 2^32) const e = Math.min(n, i + 5552); for (; i + 8 <= e; i += 8) { s1 += b[i]; s2 += s1; s1 += b[i + 1]; s2 += s1; s1 += b[i + 2]; s2 += s1; s1 += b[i + 3]; s2 += s1; s1 += b[i + 4]; s2 += s1; s1 += b[i + 5]; s2 += s1; s1 += b[i + 6]; s2 += s1; s1 += b[i + 7]; s2 += s1; } for (; i < e; i++) { s1 += b[i]; s2 += s1; } s1 %= 65521; s2 %= 65521; } return ((s2 << 16) | s1) >>> 0; } /** The Adler-32 of a followed by b, from their sums and b's length (zlib's adler32_combine). */ export function adler32Combine(a1: number, a2: number, len2: number): number { const BASE = 65521; const rem = len2 % BASE; let sum1 = a1 & 0xffff; let sum2 = (rem * sum1) % BASE; sum1 += (a2 & 0xffff) + BASE - 1; sum2 += (a1 >>> 16) + (a2 >>> 16) + BASE - rem; if (sum1 >= BASE) { sum1 -= BASE; } if (sum1 >= BASE) { sum1 -= BASE; } if (sum2 >= 2 * BASE) { sum2 -= 2 * BASE; } if (sum2 >= BASE) { sum2 -= BASE; } return ((sum2 << 16) | sum1) >>> 0; } // ---- the operations (on any thread) --------------------------------------------------------------- export interface Task { op: 'inflate' | 'gunzip' | 'deflate' | 'gzip' | 'deflateRaw' | 'inflateRaw'; data: Uint8Array; level?: number; /** deflateRaw: the last block (ends the stream) */ last?: boolean; /** inflateRaw: the expected output size, when known */ size?: number; /** also return the Adler-32 of the output (or, for deflateRaw, of the input) */ sum?: boolean; } export interface Done { out: Uint8Array; sum?: number; } const Z_SYNC_FLUSH = 2, Z_FULL_FLUSH = 3, Z_FINISH = 4; function joined(chunks: Uint8Array[]): Uint8Array { if (chunks.length === 1) { return chunks[0]; } let n = 0; for (const c of chunks) { n += c.length; } const out = new Uint8Array(n); let at = 0; for (const c of chunks) { out.set(c, at); at += c.length; } return out; } /** A plain Uint8Array view of a Node Buffer (no copy). */ function plain(b: any): Uint8Array { return b.constructor === Uint8Array ? b : new Uint8Array(b.buffer, b.byteOffset, b.byteLength); } /** Runs a task on this thread (Node's zlib when present, else pako). */ export function execute(t: Task): Done { const d = t.data; const level = t.level === undefined ? 6 : t.level; let out: Uint8Array; switch (t.op) { case 'inflate': out = NZ ? plain(NZ.inflateSync(d)) : pako.inflate(d); break; case 'gunzip': out = NZ ? plain(NZ.gunzipSync(d)) : pako.ungzip(d); break; case 'deflate': out = NZ ? plain(NZ.deflateSync(d, { level })) : pako.deflate(d, { level: level as any }); break; case 'gzip': out = NZ ? plain(NZ.gzipSync(d, { level })) : pako.gzip(d, { level: level as any }); break; case 'deflateRaw': { if (NZ) { out = plain(NZ.deflateRawSync(d, { level, finishFlush: t.last ? Z_FINISH : Z_FULL_FLUSH })); break; } const z: any = new pako.Deflate({ level: level as any, raw: true }); z.push(d, t.last ? Z_FINISH : Z_FULL_FLUSH); if (z.err) { throw new Error('jdata: deflate: ' + z.msg); } out = t.last ? z.result : joined(z.chunks); break; } case 'inflateRaw': { // a stretch of a stream from a block boundary, with no history: a back-reference // before its start is an error if (NZ) { out = plain(NZ.inflateRawSync(d, { finishFlush: Z_SYNC_FLUSH })); break; } const z: any = new pako.Inflate({ raw: true, chunkSize: Math.max(65536, Math.min(t.size || 0, 1 << 26)) }); z.push(d, Z_SYNC_FLUSH); if (z.err) { throw new Error('jdata: inflate: ' + z.msg); } if (z.ended) { out = z.result; } else { const s = z.strm; if (s.next_out > 0 && s.avail_out > 0) { z.chunks.push(s.output.subarray(0, s.next_out)); } out = joined(z.chunks); } break; } default: throw new Error('jdata: unknown operation ' + (t as any).op); } const r: Done = { out }; if (t.sum) { r.sum = adler32(t.op === 'deflateRaw' ? d : out); } return r; } // ---- runners: Node's thread pool, Web Workers, or this thread ------------------------------------ export interface Runner { threads: number; /** the runner computes Adler-32 sums on its threads (else the caller does, here) */ sums: boolean; run(t: Task): Promise; } function nodeRunner(threads: number): Runner { const fn: any = { inflate: NZ.inflate, gunzip: NZ.gunzip, deflate: NZ.deflate, gzip: NZ.gzip, deflateRaw: NZ.deflateRaw, inflateRaw: NZ.inflateRaw }; return { threads, sums: false, run: (t) => new Promise((resolve, reject) => { const level = t.level === undefined ? 6 : t.level; const o: any = t.op === 'inflateRaw' ? { finishFlush: Z_SYNC_FLUSH } : t.op === 'deflateRaw' ? { level, finishFlush: t.last ? Z_FINISH : Z_FULL_FLUSH } : t.op === 'deflate' || t.op === 'gzip' ? { level } : {}; fn[t.op].call(NZ, t.data, o, (e: any, r: any) => (e ? reject(e) : resolve({ out: plain(r) }))); }) }; } const inline: Runner = { threads: 1, sums: true, run: (t) => new Promise((resolve, reject) => { try { resolve(execute(t)); } catch (e) { reject(e); } }) }; // the URL of this script (a classic script) or module, for its workers let SELF_URL: string | undefined; let SELF_MODULE = false; try { if (typeof document !== 'undefined' && document.currentScript && document.currentScript.src) { SELF_URL = document.currentScript.src; } } catch (e) { // (none) } if (!SELF_URL) { try { const u = (import.meta as any).url; if (typeof u === 'string' && /^(https?|blob|data):/.test(u)) { SELF_URL = u; SELF_MODULE = true; } } catch (e) { // (not a module) } } interface PoolWorker { w: any; ready: Promise; busy: boolean; } let pool: PoolWorker[] = []; let poolBroken = false; let nextId = 1; /** Starts a worker running this script (a blob that loads it, so CDN scripts work as well). */ function startWorker(url: string, module: boolean): PoolWorker { const src = module ? 'self.__jdaPool=1;import(' + JSON.stringify(url) + ');' : 'self.__jdaPool=1;importScripts(' + JSON.stringify(url) + ');'; const blob = URL.createObjectURL(new Blob([src], { type: 'text/javascript' })); const w = new Worker(blob, module ? { type: 'module' } : undefined); const p: PoolWorker = { w, busy: false, ready: Promise.resolve() }; p.ready = new Promise((resolve, reject) => { const ok = (e: any) => { if (e.data && e.data.jdaReady) { w.removeEventListener('message', ok); resolve(); } }; w.addEventListener('message', ok); w.addEventListener('error', (e: any) => { if (e && e.preventDefault) { e.preventDefault(); } reject(new Error('jdata: a worker failed to start' + (e && e.message ? ': ' + e.message : ''))); }); }); p.ready.catch(() => undefined); return p; } function workerRunner(threads: number, url: string, module: boolean): Runner { while (pool.length < threads) { pool.push(startWorker(url, module)); } const queue: Array<{ t: Task; resolve: (d: Done) => void; reject: (e: any) => void }> = []; const pump = () => { for (const p of pool.slice(0, threads)) { if (p.busy || !queue.length) { continue; } const job = queue.shift()!; p.busy = true; const id = nextId++; const done = (e: any) => { const m = e.data; if (!m || m.jda !== id) { return; } p.w.removeEventListener('message', done); p.busy = false; if (m.err) { job.reject(new Error(m.err)); } else { job.resolve({ out: m.out, sum: m.sum }); } pump(); }; p.ready.then(() => { p.w.addEventListener('message', done); // (the data is a copy of its own: transferred, not copied again) const d = job.t.data; const data = d.byteOffset === 0 && d.byteLength === d.buffer.byteLength ? d : d.slice(); p.w.postMessage(Object.assign({}, job.t, { jda: id, data }), [data.buffer]); }, (err) => { poolBroken = true; p.busy = false; // (this thread instead) inline.run(job.t).then(job.resolve, job.reject); pump(); void err; }); } }; return { threads, sums: true, run: (t) => new Promise((resolve, reject) => { queue.push({ t, resolve, reject }); pump(); }) }; } /** Stops the Web Workers jda started (they are kept for later calls). */ export function closeWorkers(): void { for (const p of pool) { p.w.terminate(); } pool = []; poolBroken = false; } // in a worker started by jda: run the tasks it is sent if (typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof WorkerGlobalScope && self.__jdaPool) { self.addEventListener('message', (e: any) => { const m = e.data; if (!m || m.jda === undefined) { return; } try { const r = execute(m); const out = r.out.byteOffset === 0 && r.out.byteLength === r.out.buffer.byteLength ? r.out : r.out.slice(); self.postMessage({ jda: m.jda, out, sum: r.sum }, [out.buffer]); } catch (err) { self.postMessage({ jda: m.jda, err: String(err && (err as any).message ? (err as any).message : err) }); } }); self.postMessage({ jdaReady: true }); } export interface ThreadOptions { /** the most threads to use (default: the processors; in Node.js, at most UV_THREADPOOL_SIZE) */ threads?: number; /** browsers: the URL of jdata.js (or jdata.mjs, with workerModule) for the workers (default: * this script's own URL; needed when jda is bundled) */ workerURL?: string; workerModule?: boolean; } function processors(): number { try { if (typeof navigator !== 'undefined' && navigator.hardwareConcurrency) { return navigator.hardwareConcurrency; } if (NZ && typeof process !== 'undefined') { return Number(process.env.UV_THREADPOOL_SIZE) || 4; } } catch (e) { // (none) } return 4; } export function runner(o: ThreadOptions): Runner { let n = o.threads === undefined ? processors() : Math.max(1, Math.floor(o.threads)); if (NZ) { n = Math.min(n, typeof process !== 'undefined' ? Number(process.env.UV_THREADPOOL_SIZE) || 4 : 4); return nodeRunner(n); } const url = o.workerURL || SELF_URL; if (n > 1 && url && !poolBroken && typeof Worker !== 'undefined' && typeof Blob !== 'undefined' && typeof URL !== 'undefined') { return workerRunner(Math.min(n, 16), url, o.workerURL ? !!o.workerModule : SELF_MODULE); } return inline; } // ---- zlibmt --------------------------------------------------------------------------------------- /** The zlibmt block size for a payload of n bytes: n/16, from 256 KiB to 4 MiB (as jdai). */ export function zlibmtBlockSize(n: number): number { return Math.min(4 << 20, Math.max(256 << 10, Math.floor(n / 16))); } function zlibHeader(level: number): Uint8Array { const flevel = level >= 0 && level <= 1 ? 0 : level >= 2 && level <= 5 ? 1 : level === 6 || level < 0 ? 2 : 3; let flg = flevel << 6; flg += (31 - ((0x78 << 8) | flg) % 31) % 31; return new Uint8Array([0x78, flg]); } /** A zlib stream of bytes in zlibmt blocks, deflated on the runner's threads. */ export async function zlibmtEncode(b: Uint8Array, level: number, R: Runner): Promise { const n = b.length, bs = zlibmtBlockSize(n); if (n <= bs) { return (await R.run({ op: 'deflate', data: b, level })).out; } const jobs: Promise[] = []; for (let at = 0; at < n; at += bs) { jobs.push(R.run({ op: 'deflateRaw', data: b.subarray(at, Math.min(n, at + bs)), level, last: at + bs >= n, sum: R.sums })); } // (Node: the threads deflate while this one sums) let sum = R.sums ? 0 : adler32(b); const done = await Promise.all(jobs); if (R.sums) { sum = done[0].sum as number; for (let k = 1; k < done.length; k++) { sum = adler32Combine(sum, done[k].sum as number, Math.min(bs, n - k * bs)); } } const parts = [zlibHeader(level)]; for (const d of done) { parts.push(d.out); } parts.push(new Uint8Array([sum >>> 24, (sum >>> 16) & 255, (sum >>> 8) & 255, sum & 255])); return joined(parts); } /** The same stream, deflated here (for encode() with zlibmt: true). */ export function zlibmtEncodeSync(b: Uint8Array, level: number): Uint8Array { const n = b.length, bs = zlibmtBlockSize(n); if (n <= bs) { return execute({ op: 'deflate', data: b, level }).out; } const parts = [zlibHeader(level)]; for (let at = 0; at < n; at += bs) { parts.push(execute({ op: 'deflateRaw', data: b.subarray(at, Math.min(n, at + bs)), level, last: at + bs >= n }).out); } const sum = adler32(b); parts.push(new Uint8Array([sum >>> 24, (sum >>> 16) & 255, (sum >>> 8) & 255, sum & 255])); return joined(parts); } /** The bytes of a zlib stream, inflated in parallel between full-flush marks where it can be. */ export async function zlibmtDecode(z: Uint8Array, size: number | undefined, R: Runner): Promise { const n = z.length; const whole = async () => (await R.run({ op: 'inflate', data: z })).out; if (R.threads <= 1 || n < (1 << 20) || (z[0] & 0x0f) !== 8 || (z[1] & 0x20)) { return whole(); } // starts: just after a 00 00 FF FF, a stretch apart const end = n - 4; // (the Adler-32) const stretch = Math.max(64 << 10, Math.floor((end - 2) / (R.threads * 4))); const starts = [2]; for (let i = 2 + stretch; i < end - 4;) { const j = z.indexOf(0, i); if (j < 0 || j > end - 4) { break; } if (z[j + 1] === 0 && z[j + 2] === 0xff && z[j + 3] === 0xff) { starts.push(j + 4); i = j + 4 + stretch; } else { i = j + 1; } } if (starts.length < 2) { return whole(); } starts.push(end); try { const jobs: Promise[] = []; for (let k = 0; k + 1 < starts.length; k++) { const p = R.run({ op: 'inflateRaw', data: z.subarray(starts[k], starts[k + 1]), size: size ? Math.ceil(size / (starts.length - 1)) : undefined, sum: R.sums }); // (Node: each stretch summed here as it arrives) jobs.push(R.sums ? p : p.then((d) => ({ out: d.out, sum: adler32(d.out) }))); } const done = await Promise.all(jobs); let total = 0, sum = 1; for (const d of done) { total += d.out.length; sum = total === d.out.length ? d.sum as number : adler32Combine(sum, d.sum as number, d.out.length); } const want = ((z[end] << 24) | (z[end + 1] << 16) | (z[end + 2] << 8) | z[end + 3]) >>> 0; if ((size !== undefined && total !== size) || sum !== want) { return whole(); // (a mark by chance, or blocks that refer back across marks) } return joined(done.map((d) => d.out)); } catch (e) { return whole(); } } // ---- the API --------------------------------------------------------------------------------------- /** A zlib stream of bytes in zlibmt blocks, deflated on threads (any zlib inflates it). */ export function deflate(bytes: Uint8Array, opts: ThreadOptions & { level?: number } = {}): Promise { return zlibmtEncode(bytes, opts.level === undefined ? 6 : opts.level, runner(opts)); } /** The bytes of a zlib stream, inflated on threads where its blocks allow (size: the expected * size, when known). */ export function inflate(bytes: Uint8Array, opts: ThreadOptions & { size?: number } = {}): Promise { return zlibmtDecode(bytes, opts.size, runner(opts)); }