Files
clean-architecture-frontend…/scripts/lib/performance-budgets.ts
T
DongHyeonka 46dfe23f69 fix(bundle): 예산을 넘으면 넘은 한도와 초과량을 출력하고 초기 파일 수를 막는다
문제: 초기 JS가 예산을 넘으면 check:bundle은
"Bundle budget or manifest integrity failed: " 한 줄만 쓰고 콜론 뒤가
비어 있었다. 측정값과 한도는 artifacts/performance/bundle.json에만 있어
예산 실패인지 manifest 무결성 실패인지, 몇 바이트 넘었는지 알 수 없었다.
또 초기 JS 파일 수에는 상한이 없어 08-08처럼 파일을 16개에서 25개로
늘리는 변경도 모든 게이트를 통과했다. 템플릿은 HTTP/2를 전제로 초기
청크를 나눠 두었는데, 파일 수를 늘리는 결정이 어디에도 드러나지 않았다.

고른 방법: 예산 실패와 무결성 실패를 다른 문장으로 쓴다. 예산 실패는
넘은 한도마다 측정값·한도·초과량을 한 줄로 쓴다
(describeBundleBudgetFailures). config/performance/budgets.json에
initialJsFiles(지금 25)를 두고 check:bundle이 entry를 포함한 초기 파일
수를 센다. bundle.json 스키마는 측정값·한도·결과와 자가 검사 fixture를
하나씩 더 가진다. 두 변경은 같은 함수와 스키마를 고치므로 한 커밋에
넣었다.
버린 대안: 파일 수를 문서에만 적기. 08-08이 그 상태에서 파일을 늘렸다.

위험·한계: 초기 파일을 하나라도 늘리는 변경은 이제 budgets.json을 같이
고쳐야 통과한다. 그것이 목적이다. HTTP/2 확인 자체는 이 커밋에 없다
(13-02에서 probe에 넣는다).

검증: tests/unit/check-bundle-output.test.ts가 손으로 만든 빌드 출력에
check-bundle.ts를 돌려 통과·초기 바이트 초과·lazy 초과·파일 수 초과·
무결성 실패의 출력을 본다(고치기 전 4건 실패). bundle-artifact-contract,
performance-budgets 통과. 실제 빌드에서 check:bundle PASS(25 / 25 files).

Refs: docs/reviews/2026-11-03-maturity-review/15-performance.md 15-03, 15-05
2026-11-04 20:22:27 +09:00

155 lines
4.7 KiB
TypeScript

export type BundleMeasurements = Readonly<{
initialJsGzipBytes: number;
initialJsFiles: number;
lazyChunks: readonly Readonly<{ path: string; gzipBytes: number }>[];
}>;
/**
* 1103/15-05. `initialJsFiles` bounds the number of initial JavaScript files
* (entry included). The entry preloads them in parallel, which costs no round
* trip over HTTP/2 and queues them six at a time over HTTP/1.1
* (docs/operations/performance-evidence.md, "초기 청크 수와 HTTP/1.1").
*/
export type BundleThresholds = Readonly<{
initialJsGzipBytes: number;
initialJsFiles: number;
lazyChunkGzipBytes: number;
}>;
export function evaluateBundleBudget(
measurements: BundleMeasurements,
thresholds: BundleThresholds,
) {
const initialPassed =
measurements.initialJsGzipBytes <= thresholds.initialJsGzipBytes;
const initialFilesPassed = measurements.initialJsFiles <= thresholds.initialJsFiles;
const lazyResults = measurements.lazyChunks.map((chunk) => ({
...chunk,
threshold: thresholds.lazyChunkGzipBytes,
passed: chunk.gzipBytes <= thresholds.lazyChunkGzipBytes,
}));
return Object.freeze({
initialPassed,
initialFilesPassed,
lazyResults: Object.freeze(lazyResults),
passed: initialPassed && initialFilesPassed && lazyResults.every((chunk) => chunk.passed),
});
}
/**
* 1103/15-03. One line per exceeded limit with the measured value, the limit
* and the excess, so a failed check:bundle says what to cut without opening
* artifacts/performance/bundle.json.
*/
export function describeBundleBudgetFailures(
measurements: BundleMeasurements,
thresholds: BundleThresholds,
): string[] {
const over = (label: string, measured: number, limit: number, unit = " gzip bytes") =>
`${label} ${measured}${unit} > budget ${limit} (over by ${measured - limit})`;
const lines: string[] = [];
if (measurements.initialJsGzipBytes > thresholds.initialJsGzipBytes) {
lines.push(over("initial JavaScript", measurements.initialJsGzipBytes, thresholds.initialJsGzipBytes));
}
if (measurements.initialJsFiles > thresholds.initialJsFiles) {
lines.push(over("initial JavaScript files", measurements.initialJsFiles, thresholds.initialJsFiles, ""));
}
for (const chunk of measurements.lazyChunks) {
if (chunk.gzipBytes > thresholds.lazyChunkGzipBytes) {
lines.push(over(`lazy chunk ${chunk.path}`, chunk.gzipBytes, thresholds.lazyChunkGzipBytes));
}
}
return lines;
}
export type LabMetrics = Readonly<{
lcpMs: number;
cls: number;
namedInteractionMs: number;
}>;
export function evaluateLabBudget(
report: Readonly<{
context?: Readonly<Record<string, unknown>>;
metrics: LabMetrics;
}>,
thresholds: LabMetrics,
) {
const requiredContext = [
"runner",
"browser",
"viewport",
"network",
"cpu",
"cache",
"build",
];
const missingContext = requiredContext.filter(
(field) => report.context?.[field] === undefined,
);
const results = {
lcp: report.metrics.lcpMs <= thresholds.lcpMs,
cls: report.metrics.cls <= thresholds.cls,
namedInteraction:
report.metrics.namedInteractionMs <= thresholds.namedInteractionMs,
};
return Object.freeze({
missingContext: Object.freeze(missingContext),
results: Object.freeze(results),
passed: missingContext.length === 0 && Object.values(results).every(Boolean),
});
}
export function percentile75(values: readonly number[]): number | null {
if (values.length === 0) return null;
const sorted = [...values].sort((left, right) => left - right);
return sorted[Math.ceil(sorted.length * 0.75) - 1];
}
export type FieldMetrics = Readonly<{
p75LcpMs: number | null;
p75Cls: number | null;
p75InpMs: number | null;
}>;
export type FieldThresholds = Readonly<{
p75LcpMs: number;
p75Cls: number;
p75InpMs: number;
minimumEligibleSamples: number | null;
}>;
export type FieldBudgetResult = Readonly<{
status: "PASS" | "FAIL_THRESHOLD" | "FAIL_UNVERIFIED";
passed: boolean;
}>;
export function evaluateFieldBudget(
report: Readonly<{ metrics: FieldMetrics; eligibleSamples: number }>,
thresholds: FieldThresholds,
): FieldBudgetResult {
if (
thresholds.minimumEligibleSamples === null ||
report.eligibleSamples < thresholds.minimumEligibleSamples ||
Object.values(report.metrics).some((value) => value === null)
) {
return Object.freeze({
status: "FAIL_UNVERIFIED",
passed: false,
});
}
const metrics = report.metrics as Readonly<{
p75LcpMs: number;
p75Cls: number;
p75InpMs: number;
}>;
const passed =
metrics.p75LcpMs <= thresholds.p75LcpMs &&
metrics.p75Cls <= thresholds.p75Cls &&
metrics.p75InpMs <= thresholds.p75InpMs;
return Object.freeze({
status: passed ? "PASS" : "FAIL_THRESHOLD",
passed,
});
}