// @vitest-environment node import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { randomBytes } from "node:crypto"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { BUDGET_BYTES, checkBudget } from "./check-3d-budget.mjs"; const threeChunk = (filler: string) => `/*WebGLRenderer*/window.__THREE__="186";${filler}`; // Hex of random bytes is barely compressible by gzip (about 50 %). const noise = (bytes: number) => randomBytes(bytes).toString("hex"); describe("check-3d-budget", () => { let dir: string; beforeEach(() => { dir = mkdtempSync(path.join(tmpdir(), "budget-")); }); afterEach(() => rmSync(dir, { recursive: true, force: true })); it("passes when the three.js chunk is under budget", () => { writeFileSync(path.join(dir, "a.js"), threeChunk("x".repeat(1000))); writeFileSync(path.join(dir, "other.js"), "console.log(1)"); const result = checkBudget(dir); expect(result.ok).toBe(true); expect(result.file).toBe("a.js"); }); it("fails when the three.js chunk is over budget", () => { writeFileSync(path.join(dir, "big.js"), threeChunk(noise(1000))); const result = checkBudget(dir, 100); expect(result.ok).toBe(false); expect(result.gzipBytes).toBeGreaterThan(100); }); it("measures the largest of several three.js chunks", () => { writeFileSync(path.join(dir, "small.js"), threeChunk("x")); writeFileSync(path.join(dir, "large.js"), threeChunk(noise(2000))); expect(checkBudget(dir).file).toBe("large.js"); }); it("fails when no three.js chunk exists", () => { writeFileSync(path.join(dir, "app.js"), "export const a = 1; // WebGLRenderer only"); const result = checkBudget(dir); expect(result.ok).toBe(false); expect(result.file).toBeNull(); }); it("uses the spec budget of 320 kB by default", () => { expect(BUDGET_BYTES).toBe(320_000); }); });