/** @jest-environment node */ import { Readable } from 'node:stream' import AdmZip from 'adm-zip' import { ExternalZipBusyError, ExternalZipTooLargeError, MAX_ACTIVE_EXTERNAL_ZIPS, MAX_EXTERNAL_ZIP_BYTES, streamExternalZip, } from '@/lib/external-zip-stream' test('ZIP entries open in order without buffering multiple upstream sources', async () => { const opened: string[] = [] let active = 0 let peak = 0 const entries = Array.from({ length: 40 }, (_, index) => ({ name: 'main/' + String(index).padStart(2, '0') + '.jpg', open: async () => { const source = Readable.from((async function* () { active++ peak = Math.max(peak, active) try { yield Buffer.alloc(128 * 1024, index) } finally { active-- } })(), { objectMode: false }) opened.push(String(index)) return source }, })) const stream = await streamExternalZip(entries) const bytes = Buffer.from(await new Response(stream).arrayBuffer()) const zip = new AdmZip(bytes) expect(peak).toBe(1) expect(opened).toEqual(entries.map((_, index) => String(index))) expect(zip.getEntries().map(entry => entry.entryName)).toEqual(entries.map(entry => entry.name)) entries.forEach((entry, index) => expect(zip.readFile(entry.name)?.[0]).toBe(index)) }) test('concurrent slow ZIPs are bounded and cancellation releases the slot', async () => { const entry = { name: 'main/wait.jpg', open: (signal: AbortSignal) => new Promise((_, reject) => { signal.addEventListener('abort', () => reject(signal.reason), { once: true }) }), } const active = await Promise.all(Array.from({ length: MAX_ACTIVE_EXTERNAL_ZIPS }, () => streamExternalZip([entry]))) try { await expect(streamExternalZip([entry])).rejects.toBeInstanceOf(ExternalZipBusyError) await active.shift()!.cancel() await new Promise(resolve => setImmediate(resolve)) await expect(streamExternalZip([]).then(stream => new Response(stream).arrayBuffer())).resolves.toBeDefined() } finally { await Promise.all(active.map(stream => stream.cancel())) } }) test('streams 500 entries sequentially with bounded concurrency and enforces byte limit', async () => { let active = 0 let peak = 0 const entries = Array.from({ length: 500 }, (_, index) => ({ name: `sku/${String(index).padStart(3, '0')}.jpg`, size: 16, open: async () => Readable.from((async function* () { active++ peak = Math.max(peak, active) try { yield Buffer.from(`item-${index}`) } finally { active-- } })(), { objectMode: false }), })) const stream = await streamExternalZip(entries) const bytes = Buffer.from(await new Response(stream).arrayBuffer()) const zip = new AdmZip(bytes) expect(peak).toBe(1) expect(zip.getEntries()).toHaveLength(500) await expect(streamExternalZip([ { name: 'huge.bin', size: MAX_EXTERNAL_ZIP_BYTES + 1, open: async () => Readable.from([]) }, ])).rejects.toBeInstanceOf(ExternalZipTooLargeError) })