import { spawnSync } from "node:child_process"; import { mkdtemp, readFile, readdir, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterAll, describe, expect, it } from "vitest"; import { classifyViteJavascript } from "../../scripts/lib/classify-vite-bundle.ts"; /** * 1101/08-08. A bundler places a module, not an export, in a chunk. A * primitive only a lazy screen renders must not ride the initial JavaScript * because it shares a file, or the barrel, with one the app shell renders. */ const DESIGN_SYSTEM = "src/presentation/design-system"; // Classes that only the primitives the template's lazy screens use render. const LAZY_ONLY_CLASSES = Object.freeze([ "ui-alert", "ui-badge", "ui-breadcrumbs", "ui-card", "ui-data-table", "ui-menu", "ui-popover", "ui-progress", "ui-radio-group", "ui-switch", "ui-tabs", "ui-toast", "ui-tooltip", ]); const roots: string[] = []; afterAll(async () => { await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))); }); async function initialJavascript(): Promise { const outDir = await mkdtemp(path.join(tmpdir(), "design-system-chunk-")); roots.push(outDir); const environment = Object.fromEntries( Object.entries(process.env).filter(([name]) => !name.startsWith("VITE_")), ); const run = spawnSync( path.resolve("node_modules/.bin/vite"), ["build", "--outDir", outDir, "--emptyOutDir", "--logLevel", "error"], { encoding: "utf8", env: environment }, ); expect(run.stderr).toBe(""); expect(run.status).toBe(0); const manifest = JSON.parse( await readFile(path.join(outDir, ".vite/manifest.json"), "utf8"), ) as Parameters[0]; const { initialFiles } = classifyViteJavascript(manifest); const sources = await Promise.all( initialFiles.map((file) => readFile(path.join(outDir, file), "utf8")), ); return sources.join("\n"); } const renders = (code: string, className: string) => new RegExp(`(? { it("leaves the primitives only lazy screens use out of the initial chunks", async () => { const code = await initialJavascript(); // The shell's drawer is initial; without it the check proves nothing. expect(renders(code, "ui-drawer")).toBe(true); expect(LAZY_ONLY_CLASSES.filter((name) => renders(code, name))).toEqual([]); }, 120_000); // vite.config.ts declares these modules free of side effects, so the bundler // drops a module none of whose exports is used. An import kept only for its // effect (a stylesheet, a polyfill, a registration) would vanish with it. it("keeps every design-system module free of imports kept for their effect", async () => { const files = (await readdir(DESIGN_SYSTEM, { recursive: true })) .filter((file) => /\.tsx?$/u.test(file) && !file.includes(".stories.")); expect(files.length).toBeGreaterThan(0); const offenders: string[] = []; for (const file of files) { const source = await readFile(path.join(DESIGN_SYSTEM, file), "utf8"); if (/^\s*import\s*["']/mu.test(source)) offenders.push(file); } expect(offenders).toEqual([]); }); });