import { spawnSync } from "node:child_process"; import { cp, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; /** * 1105/12-04. Every build, dev server, type check and test run renders * src/.generated first, so two runs in one checkout render it while the other * run's Vite or tsc reads it. The generator truncated each file in place on * every run, and a reader could see it empty or half written. It now leaves an * unchanged file alone and replaces a changed one with a rename. * * The generator runs against a copy (`--root=`), so the checkout's own index * is never touched while other test files read it. */ const DECLARATIONS = ["src/apps", "src/contexts", "src/features"] as const; const OUTPUTS = [ "product-feature-index.ts", "product-context-index.ts", "product-app.ts", ] as const; const roots: string[] = []; afterEach(async () => { await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); }); async function declarationCopy(): Promise { const root = await mkdtemp(path.join(tmpdir(), "feature-index-write-")); roots.push(root); for (const input of DECLARATIONS) { await cp(input, path.join(root, input), { recursive: true }); } return root; } function generate(root: string): void { const environment: NodeJS.ProcessEnv = { ...process.env }; delete environment["PRODUCT_APP_ID"]; delete environment["VITE_PRODUCT_FEATURES"]; const run = spawnSync( process.execPath, ["scripts/generate-product-feature-index.ts", `--root=${root}`], { encoding: "utf8", env: environment }, ); expect(run.status, run.stderr).toBe(0); } async function identity(file: string): Promise { const metadata = await stat(file, { bigint: true }); return `${metadata.ino}:${metadata.mtimeNs}`; } describe("product feature index writes (1105/12-04)", () => { it("leaves an index that has not changed untouched", async () => { const root = await declarationCopy(); const files = OUTPUTS.map((name) => path.join(root, "src/.generated", name)); generate(root); const before = await Promise.all(files.map(identity)); generate(root); expect(await Promise.all(files.map(identity))).toEqual(before); }); it("replaces a stale index with a new file instead of rewriting it in place", async () => { const root = await declarationCopy(); const file = path.join(root, "src/.generated/product-feature-index.ts"); generate(root); const rendered = await readFile(file, "utf8"); await writeFile(file, "// stale\n", "utf8"); const { ino: staleInode } = await stat(file, { bigint: true }); generate(root); expect(await readFile(file, "utf8")).toBe(rendered); // A reader that opened the stale file keeps reading the stale file. expect((await stat(file, { bigint: true })).ino).not.toBe(staleInode); expect( (await readdir(path.dirname(file))).filter((name) => name.endsWith(".tmp")), ).toEqual([]); }); });