Files
clean-architecture-frontend…/tests/unit/check-bundle-output.test.ts
DongHyeonka 81447354cd fix(bundle): check:bundle이 Service Worker와 manifest 밖 JS를 잰다
check:bundle은 Vite manifest의 chunk만 잰다. Service Worker를 켠 제품의
worker와 public·Web Worker 출력은 크기가 얼마든 FE-GATE-012를 통과한다.

빌드가 만든 Service Worker는 새 key `bundle.serviceWorkerGzipBytes`로,
assets/에 빌드가 만든 hash 이름 파일은 파일마다 lazy 예산으로 잰다.
public/ 사본은 이름이 hash처럼 보이거나 service-worker.js여도 빌드
출력이 아니므로, 그 밖의 예산 없는 JS와 함께 경로를 대고 실패한다.
이름만 보는 안은 HTML이 바로 읽는 public JS 221,678 B가 통과해 버렸다.
새 key가 없으면 파일과 key를 대고 실패한다.

예산 값은 자산 목록을 상한까지(채운 이름은 줄기 16자 무작위) 채우고
build·release id를 128자로 준 worker(Mmax)를 1 KiB 단위로 올림한
값이다(review 판정 2026-11-23, 소유자 결정 아님). 100 B 단위 올림은
기능을 더한 제품이 코드 변경 없이 막히고, 긴 이름에 맞춰 올리거나
id를 512자로 재는 안은 worker 코드 증가를 더 숨긴다. 목록과 코드를
나눠 재는 안은 빌드 구조를 바꿔서 버렸다.

위험: 자산 목록이 상한에 가까우면 이름이 길고 다양하거나 id가 길 때
예산을 넘을 수 있다. 기본 id로도 넘는 조합을 쟀다. 자산이 적은
빌드에서는 목록 몫만큼 worker 코드 증가를 못 잡는다. 기본 선택이
null이라 템플릿 CI는 worker 값을 재지 않는다.

검증: 고치기 전 코드에 이 커밋의 시험을 얹으면 세 파일 47개 가운데
25개가 실패하고 이 트리에서 통과한다. 보호 규칙 변이 15개가 실패한다.
노트북 check:types, lint, check:architecture, test:unit, test:contract,
test:runtime-schema, verify:documentation 통과. desktop에서 worker
입력이 같은 트리의 Mmax 23404 B, 자산 길이 다섯 자리 23442 B, handler
둘 23424 B가 예산 안이고 zod를 넣은 worker는 실패했다. merge 단계와
FE-GATE-029·030은 커밋 때 돌리지 않았다.

Refs: REV-FE-0010
2026-11-23 06:00:49 +09:00

363 lines
14 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
/**
* 1103/15-03. An over-budget build printed only
* "Bundle budget or manifest integrity failed: " with nothing after the
* colon, so the first budget failure a project meets named neither the limit
* nor the excess. check-bundle runs here on a hand-made build output.
*/
const roots: string[] = [];
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
type Output = Readonly<{ path: string; gzipBytes: number }>;
async function checkBundle(
options: Readonly<{
outputs: readonly Output[];
manifest: Record<string, unknown>;
budgets: Record<string, number>;
/** Files of the project's public/, which Vite copies to dist as they are. */
publicFiles?: readonly string[];
/** RUN_OUTPUT_ROOT for the run, and the build written under it. */
runOutput?: Readonly<{ root: string; outputs: readonly Output[] }>;
}>,
) {
const root = await mkdtemp(path.join(tmpdir(), "check-bundle-output-"));
roots.push(root);
const write = async (file: string, value: unknown) => {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await writeFile(path.join(root, file), `${JSON.stringify(value, null, 2)}\n`);
};
const writeBuild = async (buildRoot: string, outputs: readonly Output[]) => {
await write(path.posix.join(buildRoot, "dist/.vite/manifest.json"), options.manifest);
await write(path.posix.join(buildRoot, "artifacts/performance/bundle.json"), {
schemaVersion: 1,
generatedAt: "2026-11-04T00:00:00.000Z",
context: { nodeVersion: "v24.14.0", packageManager: "pnpm@11.17.0", runnerImage: "fixture" },
outputs: outputs.map((output) => ({
path: `dist/${output.path}`,
bytes: output.gzipBytes * 3,
gzipBytes: output.gzipBytes,
sha256: "a".repeat(64),
})),
});
};
await write("config/performance/budgets.json", { schemaVersion: 1, bundle: options.budgets });
await writeBuild(".", options.outputs);
for (const file of options.publicFiles ?? []) await write(path.posix.join("public", file), {});
if (options.runOutput) await writeBuild(options.runOutput.root, options.runOutput.outputs);
const result = spawnSync(process.execPath, [path.resolve("scripts/check-bundle.ts")], {
cwd: root,
encoding: "utf8",
// Empty is unset (scripts/lib/run-isolation.ts), whatever the runner has.
env: { ...process.env, RUN_OUTPUT_ROOT: options.runOutput?.root ?? "" },
});
return { status: result.status, stdout: result.stdout, stderr: result.stderr };
}
const MANIFEST = {
"index.html": {
file: "assets/index-Aa11Bb22.js",
isEntry: true,
imports: ["_boot"],
},
// The entry's own dynamic imports are initial (09-03); a route's are lazy.
_boot: { file: "assets/boot-Cc33Dd44.js", dynamicImports: ["src/lazy.tsx"] },
"src/lazy.tsx": { file: "assets/lazy-Ee55Ff66.js" },
};
const OUTPUTS = [
{ path: "assets/index-Aa11Bb22.js", gzipBytes: 400 },
{ path: "assets/boot-Cc33Dd44.js", gzipBytes: 500 },
{ path: "assets/lazy-Ee55Ff66.js", gzipBytes: 300 },
];
const BUDGETS = {
initialJsGzipBytes: 1_000,
initialJsFiles: 2,
lazyChunkGzipBytes: 400,
serviceWorkerGzipBytes: 200,
};
describe("check:bundle failure output (1103/15-03)", { timeout: childProcessTimeout(730) }, () => {
it("passes and prints the total within budget", async () => {
const result = await checkBundle({ outputs: OUTPUTS, manifest: MANIFEST, budgets: BUDGETS });
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
expect(result.stdout).toContain("initial JS 900 / 1000 gzip bytes");
});
it("names the measured initial total, the budget and the excess", async () => {
const result = await checkBundle({
outputs: OUTPUTS,
manifest: MANIFEST,
budgets: { ...BUDGETS, initialJsGzipBytes: 899 },
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("Bundle budget failed (config/performance/budgets.json):");
expect(result.stderr).toContain("initial JavaScript 900 gzip bytes > budget 899 (over by 1)");
expect(result.stderr).not.toContain("manifest integrity");
});
it("names each lazy chunk over its budget", async () => {
const result = await checkBundle({
outputs: OUTPUTS,
manifest: MANIFEST,
budgets: { ...BUDGETS, lazyChunkGzipBytes: 250 },
});
expect(result.status).toBe(1);
expect(result.stderr).toContain(
"lazy chunk assets/lazy-Ee55Ff66.js 300 gzip bytes > budget 250 (over by 50)",
);
});
// 1103/15-05. The entry preloads every initial file at once; over HTTP/1.1
// they queue for six connections. A change that adds an initial file is a
// decision recorded in the budget, not a side effect.
it("fails when the initial JavaScript has more files than the budget", async () => {
const result = await checkBundle({
outputs: OUTPUTS,
manifest: MANIFEST,
budgets: { ...BUDGETS, initialJsFiles: 1 },
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("initial JavaScript files 2 > budget 1 (over by 1)");
});
it("reports a manifest integrity failure apart from the budget", async () => {
const result = await checkBundle({
outputs: OUTPUTS.filter(({ path: file }) => file !== "assets/boot-Cc33Dd44.js"),
manifest: MANIFEST,
budgets: BUDGETS,
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("Bundle manifest integrity failed:");
expect(result.stderr).toContain("output missing from the inventory: assets/boot-Cc33Dd44.js");
expect(result.stderr).not.toContain("Bundle budget failed");
});
});
/**
* REV-FE-0010. check:bundle judged only the JavaScript in the app's Vite
* manifest. The Service Worker is a second build without one, so a worker of
* any size passed, and so did every other JavaScript file outside the manifest.
*/
describe("check:bundle outside the app manifest (REV-FE-0010)", { timeout: childProcessTimeout(730) }, () => {
it("measures the Service Worker against its own budget, which it may reach", async () => {
const result = await checkBundle({
outputs: [...OUTPUTS, { path: "service-worker.js", gzipBytes: 200 }],
manifest: MANIFEST,
budgets: BUDGETS,
});
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
expect(result.stdout).toContain("service worker 200 / 200 gzip bytes");
});
it("fails a Service Worker one byte over its budget, under the lazy chunk budget", async () => {
const result = await checkBundle({
outputs: [...OUTPUTS, { path: "service-worker.js", gzipBytes: 201 }],
manifest: MANIFEST,
budgets: BUDGETS,
});
expect(result.status).toBe(1);
expect(result.stderr).toContain(
"service worker service-worker.js 201 gzip bytes > budget 200 (over by 1)",
);
expect(result.stderr).not.toContain("manifest integrity");
});
// Only the dist root's service-worker.js is the worker, and only a hashed name
// under assets/ is a build chunk. Any other file fails whatever its size.
it.each([
"assets/unhashed.js",
"assets/service-worker.js",
"stray.mjs",
"stray-Ab12Cd34.js",
"vendor/stray.cjs",
])(
"names %s, which no budget covers",
async (file) => {
const result = await checkBundle({
outputs: [...OUTPUTS, { path: file, gzipBytes: 1 }],
manifest: MANIFEST,
budgets: BUDGETS,
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("Bundle manifest integrity failed:");
expect(result.stderr).toContain(`JavaScript output without a budget: ${file}`);
expect(result.stderr).not.toContain("Bundle budget failed");
},
);
// Vite writes a Web Worker under assets/ with a hashed name and no manifest row.
it("measures a Web Worker chunk against the lazy chunk budget, which it may reach", async () => {
const result = await checkBundle({
outputs: [...OUTPUTS, { path: "assets/worker-Ab12Cd34.js", gzipBytes: 400 }],
manifest: MANIFEST,
budgets: BUDGETS,
});
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
});
it("fails a Web Worker chunk over the lazy chunk budget by its path", async () => {
const result = await checkBundle({
outputs: [...OUTPUTS, { path: "assets/worker-Ab12Cd34.js", gzipBytes: 401 }],
manifest: MANIFEST,
budgets: BUDGETS,
});
expect(result.status).toBe(1);
expect(result.stderr).toContain(
"lazy chunk assets/worker-Ab12Cd34.js 401 gzip bytes > budget 400 (over by 1)",
);
expect(result.stderr).not.toContain("manifest integrity");
});
// A file of public/ keeps its name and is no build output, whatever the name looks like.
it.each([
["assets/vendor-analytics.js", 1],
// Over the lazy chunk budget, and still no lazy chunk.
["assets/pdf.worker-Ab12Cd34.js", 401],
["service-worker.js", 1],
] as const)(
"names %s copied from public/, which no budget covers",
async (file, gzipBytes) => {
const result = await checkBundle({
outputs: [...OUTPUTS, { path: file, gzipBytes }],
manifest: MANIFEST,
budgets: BUDGETS,
publicFiles: [file],
});
expect(result.status).toBe(1);
expect(result.stderr).toContain(`JavaScript output without a budget: ${file}`);
expect(result.stderr).not.toContain("Bundle budget failed");
},
);
it("names every file copied from public/, whatever the order of the inventory", async () => {
const copies = ["service-worker.js", "assets/vendor-analytics.js", "assets/pdf.worker-Ab12Cd34.js"];
const result = await checkBundle({
outputs: [...OUTPUTS, ...copies.map((file) => ({ path: file, gzipBytes: 1 }))],
manifest: MANIFEST,
budgets: BUDGETS,
publicFiles: copies,
});
expect(result.status).toBe(1);
const named = [...result.stderr.matchAll(/JavaScript output without a budget: (\S+)/g)];
expect(named.map((match) => match[1])).toEqual([
"assets/pdf.worker-Ab12Cd34.js",
"assets/vendor-analytics.js",
"service-worker.js",
]);
});
it("measures every Web Worker chunk, whatever the order of the inventory", async () => {
const workers = ["zeta-Zz99Yy88", "alpha-Aa00Bb11", "mid-Mm55Nn44"].map((name) => ({
path: `assets/${name}.js`,
gzipBytes: 400,
}));
const result = await checkBundle({
outputs: [...workers, ...OUTPUTS],
manifest: MANIFEST,
budgets: BUDGETS,
});
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
});
it("names every JavaScript file without a budget, sorted", async () => {
const result = await checkBundle({
outputs: [...OUTPUTS, ...["z.js", "m.MJS", "a.cjs"].map((file) => ({ path: file, gzipBytes: 1 }))],
manifest: MANIFEST,
budgets: BUDGETS,
});
expect(result.status).toBe(1);
const named = [...result.stderr.matchAll(/JavaScript output without a budget: (\S+)/g)];
expect(named.map((match) => match[1])).toEqual(["a.cjs", "m.MJS", "z.js"]);
});
it("names the budget file and the key a project has not added", async () => {
const { serviceWorkerGzipBytes: _missing, ...budgets } = BUDGETS;
const result = await checkBundle({ outputs: OUTPUTS, manifest: MANIFEST, budgets });
expect(result.status).toBe(1);
expect(result.stderr).toContain("Bundle budget is invalid (config/performance/budgets.json):");
expect(result.stderr).toContain("bundle.serviceWorkerGzipBytes");
expect(result.stderr).not.toContain("ZodError");
});
it("leaves files that are not JavaScript alone", async () => {
const result = await checkBundle({
outputs: [
...OUTPUTS,
...["assets/index-A.css", "assets/index-Aa11Bb22.js.map", "config.json"].map((file) => ({
path: file,
gzipBytes: 900,
})),
],
manifest: MANIFEST,
budgets: BUDGETS,
});
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
});
});
/**
* 1106/12-02. Under RUN_OUTPUT_ROOT scripts/build-frontend.ts writes the build
* below that folder, and check:bundle (scripts/generate-supply-chain.ts, then
* scripts/check-bundle.ts) read the checkout's dist/ and artifacts/ anyway: a
* build over budget under .tmp/ passed on the checkout's earlier build
* (review run 12-R2). Both stop and name the variable instead.
*/
describe("check:bundle with RUN_OUTPUT_ROOT (1106/12-02)", { timeout: childProcessTimeout(1_041) }, () => {
it("does not pass the checkout's earlier build while the build writes elsewhere", async () => {
const result = await checkBundle({
outputs: OUTPUTS,
manifest: MANIFEST,
budgets: BUDGETS,
runOutput: {
root: ".tmp/runs/other",
outputs: OUTPUTS.map((output) => ({ ...output, gzipBytes: output.gzipBytes * 4 })),
},
});
expect(result.stdout).not.toContain("Bundle budget: PASS");
expect(result.status).toBe(1);
expect(result.stderr).toContain("RUN_OUTPUT_ROOT=.tmp/runs/other");
});
it("measures the checkout's build when the output root is the checkout", async () => {
const result = await checkBundle({
outputs: OUTPUTS,
manifest: MANIFEST,
budgets: BUDGETS,
runOutput: { root: ".", outputs: OUTPUTS },
});
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
expect(result.stdout).toContain("initial JS 900 / 1000 gzip bytes");
});
it("stops scripts/generate-supply-chain.ts before it reads the checkout's build", async () => {
const root = await mkdtemp(path.join(tmpdir(), "generate-supply-chain-output-root-"));
roots.push(root);
const result = spawnSync(process.execPath, [path.resolve("scripts/generate-supply-chain.ts")], {
cwd: root,
encoding: "utf8",
env: { ...process.env, RUN_OUTPUT_ROOT: ".tmp/runs/other" },
});
expect(result.status).toBe(1);
expect(result.stderr).toContain(
"scripts/generate-supply-chain.ts reads the build at this checkout's paths",
);
expect(result.stderr).toContain("RUN_OUTPUT_ROOT=.tmp/runs/other");
});
});