Diffinery

codician/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

44 lines · 1.9 KBRaw History
1import pako from "pako";
2
3/** zlib-deflate (RFC 1950), the format git uses for loose objects and pack entries. */
4export function deflate(data: Uint8Array): Uint8Array {
5 return pako.deflate(data);
6}
7
8export function inflate(data: Uint8Array): Uint8Array {
9 return pako.inflate(data);
10}
11
12/**
13 * Inflate one zlib stream that starts at `offset` inside `data`, and report how
14 * many input bytes it consumed. Pack files concatenate zlib streams without
15 * lengths, so the consumed count is how we find the next entry.
16 */
17export function inflateAt(data: Uint8Array, offset: number, expectedSize?: number): { out: Uint8Array; consumed: number } {
18 const inflator = new pako.Inflate() as pako.Inflate & { ended: boolean };
19 if (expectedSize !== undefined) {
20 // Stop as soon as the output passes the size the pack declared, so a small zlib stream
21 // can't be made to inflate to gigabytes.
22 const keep = inflator.onData.bind(inflator);
23 let produced = 0;
24 inflator.onData = (chunk) => {
25 produced += (chunk as Uint8Array).length;
26 if (produced > expectedSize) throw new Error(`object at ${offset} is larger than its declared size (${expectedSize} bytes)`);
27 keep(chunk);
28 };
29 }
30 // Feed in bounded windows so a huge trailing buffer is not copied repeatedly.
31 const window = Math.max(64 * 1024, expectedSize ? expectedSize + 1024 : 0);
32 let pos = offset;
33 while (!inflator.ended && pos < data.length) {
34 const end = Math.min(data.length, pos + window);
35 inflator.push(data.subarray(pos, end), false);
36 if (inflator.err) throw new Error(`zlib error at ${offset}: ${inflator.msg}`);
37 pos = end;
38 }
39 if (!inflator.ended) throw new Error(`truncated zlib stream at offset ${offset}`);
40 const strm = (inflator as unknown as { strm: { avail_in: number } }).strm;
41 const consumed = pos - offset - strm.avail_in;
42 const out = inflator.result as Uint8Array;
43 return { out: out ?? new Uint8Array(0), consumed };
44}