import { execFileSync } from "node:child_process"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { uniqueNames, zipStream } from "../src/lib/zip.js"; async function collect(stream: NodeJS.ReadableStream): Promise { const parts: Buffer[] = []; for await (const c of stream) parts.push(c as Buffer); return Buffer.concat(parts); } describe("zip", () => { it("makes names unique and safe", () => { expect(uniqueNames(["a.jpg", "A.jpg", "b/c.jpg", "a.jpg"])).toEqual(["a.jpg", "A_2.jpg", "b_c.jpg", "a_3.jpg"]); }); it("writes an archive that unzip reads back byte for byte", async () => { const dir = mkdtempSync(join(tmpdir(), "zip-")); const one = join(dir, "1.jpg"); const two = join(dir, "2.jpg"); writeFileSync(one, Buffer.alloc(200_000, 7)); writeFileSync(two, "olá"); const { stream, size } = await zipStream([ { name: "Benfica x Porto_001.jpg", path: one }, { name: "Benfica x Porto_001.jpg", path: two }, { name: "Ação.jpg", path: two }, ]); const zip = await collect(stream); expect(zip.length).toBe(size); const file = join(dir, "out.zip"); writeFileSync(file, zip); const test = execFileSync("unzip", ["-t", file]).toString(); expect(test).toContain("No errors detected"); expect(execFileSync("unzip", ["-p", file, "Benfica x Porto_001_2.jpg"]).toString()).toBe("olá"); // Accented names must survive any locale (the CI runner's is UTF-8, a plain C one prints the bytes as they are). const utf8 = { env: { ...process.env, LC_ALL: "C.UTF-8" } }; expect(execFileSync("unzip", ["-Z1", file], utf8).toString().trim().split("\n")).toEqual(["Benfica x Porto_001.jpg", "Benfica x Porto_001_2.jpg", "Ação.jpg"]); }); });