Files
clean-architecture-frontend…/scripts/generate-service-worker-assets.ts
T
DongHyeonka 9012da0e9f feat(scale): 기능 모양 기록에 Service Worker precache 축을 측정으로 더한다
앞 커밋은 precache 상한 실패 문구만 고쳤다. 1112/06-02 완료 기준의 둘째
「기록에 SW 축과 그 기능 수가 있고, 측정이 그 값을 다시 쓴다」가 남았다(확인
리뷰). 기록은 SW를 켜면 상한이 먼저 올 수 있다고만 적고 몇 개에서인지는
없었다.

고른 방법: SW가 precache할 파일의 판정을 generate-service-worker-assets.ts의
함수 하나로 빼고(collectStaticAssets와 새 countPrecachedAssets가 같이 쓴다),
기능 모양 측정이 초기 JavaScript를 재는 같은 빌드 넷에서 그 수를 센다.
`--initial-baseline --write`가 serviceWorkerPrecache(assets, firstFeatureAssets,
perFeatureAssets, perContextAssets)를 기록에 쓰고, unit 시험이 매번 빌드와
정확히 대조한다. 기록의 축 설명은 상한에서 몇 개가 들어가는지 계산하는 법을
적고 숫자는 옮기지 않는다. 버린 대안: SW를 켠 빌드를 따로 더 재기(unit 시험이
빌드 둘을 더 돈다. 등록 코드 파일 몇 개 차이는 축 설명에 적었다).

측정 결과(desktop, 이 커밋의 기록): 템플릿 24개, 첫 기능 +14, 기능 하나당
+12, context 하나당 +0. 상한 256이면 기능 19개 안팎에서 닿는다. 상한과
precache 범위는 Service Worker 계약이라 바꾸지 않았다.

위험·한계: 기능 템플릿이 lazy 파일을 늘리면 unit 시험이 기록과 달라져
실패한다. 그때 측정 스크립트로 기록을 다시 쓴다(초기 JavaScript와 같은 방식).

검증: 새 시험(판정 함수, 기록 대조, 기록 차이 문구)이 고치기 전 코드에서
실패하고, 측정으로 쓴 기록에서 통과한다(desktop, PR 본문).

Refs: 1112/06-02
2026-11-13 04:08:34 +09:00

208 lines
7.5 KiB
TypeScript

import { createHash } from "node:crypto";
import {
CACHEABLE_ASSET_CONTENT_TYPES,
canonicalStaticManifestBytes,
decodeStaticAssetManifest,
isCanonicalStaticAssetUrl,
} from "../src/contracts/service-worker-static-manifest.ts";
import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { getBuildConfig } from "../src/contracts/env.ts";
import {
BUILD_ASSET_DIRECTORY,
HASHED_STATIC_ASSET_NAME,
SERVICE_WORKER_BOUNDS,
SERVICE_WORKER_SCRIPT_PATH,
type StaticAssetManifestV1,
} from "../src/contracts/service-worker.ts";
import { moduleSpecifier, runOutputPath } from "./lib/run-isolation.ts";
/**
* §17.2.2 step 4. Scans the completed app `dist` and emits the exact hashed
* asset list under `BUILD_ASSET_DIRECTORY` the Service Worker will verify at
* install time.
*
* `service-worker.js` itself and `index.html` are excluded (§17.2.2), as are
* the runtime config and release manifest, which are network-only (§18.4).
*/
/**
* Read back by tests/e2e/support/service-worker-builds.ts (0929/11-03). A
* build with `RUN_OUTPUT_ROOT` writes it under that folder (1105/12-04).
*/
export const SERVICE_WORKER_ASSETS_OUTPUT =
".generated/frontend-runtime/service-worker-assets.ts";
// SW-RR-03. The generator and the shared decoder read the same table, so a
// manifest this script produces can never be one the runtime contract refuses.
const CACHEABLE_EXTENSIONS = CACHEABLE_ASSET_CONTENT_TYPES;
const EXCLUDED_FILES: ReadonlySet<string> = new Set([
"index.html",
SERVICE_WORKER_SCRIPT_PATH,
"config.json",
"release-manifest.json",
"runtime-config.schema.json",
]);
/**
* Vite emits content-hashed names under its assets directory; only those may
* be treated as immutable. A `public/` file copied to the dist root keeps its
* own name even when it looks hashed (`android-chrome-192x192.png`), and a
* product may change its bytes under that name (1105/06-01).
*/
const HASHED_NAME = HASHED_STATIC_ASSET_NAME;
/**
* `basePath` is the router base path (`VITE_ROUTER_BASE_PATH`): dist, and so
* every asset, is served under it (0929/06-02).
*/
export async function collectStaticAssets(
distDirectory: string,
buildId: string,
releaseId: string,
basePath = "/",
): Promise<StaticAssetManifestV1> {
const files = await walk(distDirectory, distDirectory);
const assets: StaticAssetManifestV1["assets"][number][] = [];
for (const relative of files.sort()) {
const contentType = precachedContentType(relative);
if (!contentType) continue;
const absolute = path.join(distDirectory, relative);
const bytes = await readFile(absolute);
if (bytes.byteLength > SERVICE_WORKER_BOUNDS.singleAssetBytes) {
throw new Error(`Static asset exceeds its byte bound: ${relative}`);
}
// SW-02. The URL is checked against the same predicate the runtime decoder
// applies. Emitting a path the decoder will refuse turned a correct build
// into a runtime contract failure discovered only at install time.
const url = `${basePath}${relative.split(path.sep).join("/")}`;
if (!isCanonicalStaticAssetUrl(url)) {
throw new Error(
`Static asset path is not canonical for the service worker manifest: ${relative}`,
);
}
assets.push({
url,
sha256: `sha256:${createHash("sha256").update(bytes).digest("hex")}`,
bytes: bytes.byteLength,
contentType,
});
}
// 1112/06-02. The count and the bound, so the failure says how far over
// it is. Each generated feature adds its lazy chunks here: with the Service
// Worker on, the asset bound can come before the initial JavaScript budget.
if (assets.length > SERVICE_WORKER_BOUNDS.assets) {
throw new Error(
`Static asset count ${assets.length} exceeds its bound ${SERVICE_WORKER_BOUNDS.assets} (SERVICE_WORKER_BOUNDS.assets, src/contracts/service-worker.ts): every hashed file under ${BUILD_ASSET_DIRECTORY} is precached.`,
);
}
const totalBytes = assets.reduce((sum, asset) => sum + asset.bytes, 0);
if (totalBytes > SERVICE_WORKER_BOUNDS.assetSetBytes) {
throw new Error(
`Static asset set ${totalBytes} bytes exceeds its byte bound ${SERVICE_WORKER_BOUNDS.assetSetBytes} (SERVICE_WORKER_BOUNDS.assetSetBytes, src/contracts/service-worker.ts).`,
);
}
// SW-05. The canonical byte serialization lives in the shared runtime-neutral
// codec so the worker can recompute the identical digest with WebCrypto.
const setDigest: `sha256:${string}` = `sha256:${createHash("sha256")
.update(canonicalStaticManifestBytes(assets))
.digest("hex")}`;
const manifest: StaticAssetManifestV1 = {
schemaVersion: 1,
buildId,
releaseId,
setDigest,
assets,
};
// SW-02. Every manifest this generator returns has already passed the exact
// decoder the runtime will apply to it, so the build stops here rather than
// at install time.
const decoded = decodeStaticAssetManifest(manifest);
if (!decoded.ok) {
throw new Error(
`Generated service worker manifest is not decodable: ${decoded.error.reason}`,
);
}
return manifest;
}
/**
* The content type of a dist file the worker precaches, or undefined: a
* content-hashed name with a cacheable type under `BUILD_ASSET_DIRECTORY`,
* not one of `EXCLUDED_FILES`.
*/
function precachedContentType(relative: string): string | undefined {
const base = path.basename(relative);
if (!relative.split(path.sep).join("/").startsWith(BUILD_ASSET_DIRECTORY)) return undefined;
if (EXCLUDED_FILES.has(base) || !HASHED_NAME.test(base)) return undefined;
return CACHEABLE_EXTENSIONS[path.extname(base).toLowerCase()];
}
/**
* 1112/06-02. How many files of a dist the worker would precache, by the
* rule collectStaticAssets applies, without its bounds. The feature-shape
* measurement records it per feature.
*/
export async function countPrecachedAssets(distDirectory: string): Promise<number> {
return (await walk(distDirectory, distDirectory)).filter(
(relative) => precachedContentType(relative) !== undefined,
).length;
}
async function walk(root: string, current: string): Promise<string[]> {
const entries = await readdir(current, { withFileTypes: true });
const files: string[] = [];
for (const entry of entries) {
const absolute = path.join(current, entry.name);
if (entry.isDirectory()) {
files.push(...(await walk(root, absolute)));
} else if ((await stat(absolute)).isFile()) {
files.push(path.relative(root, absolute));
}
}
return files;
}
async function main(): Promise<void> {
const distDirectory = process.argv[2] ?? runOutputPath("dist");
const output = runOutputPath(SERVICE_WORKER_ASSETS_OUTPUT);
const buildId = process.env.VITE_BUILD_ID ?? "local-build";
const releaseId = process.env.RELEASE_ID ?? "local-release";
const manifest = await collectStaticAssets(
distDirectory,
buildId,
releaseId,
getBuildConfig(process.env).routerBasePath,
);
const source = [
"// Generated by scripts/generate-service-worker-assets.ts. Do not edit.",
"",
`import type { StaticAssetManifestV1 } from "${moduleSpecifier(output, "src/contracts/service-worker.ts")}";`,
"",
`export const SERVICE_WORKER_ASSETS: StaticAssetManifestV1 = ${JSON.stringify(
manifest,
null,
2,
)} as const;`,
"",
].join("\n");
await mkdir(path.dirname(output), { recursive: true });
await writeFile(output, source, "utf8");
process.stdout.write(
`service worker assets: ${manifest.assets.length} file(s) ${manifest.setDigest}\n`,
);
}
if (process.argv[1]?.endsWith("generate-service-worker-assets.ts")) {
await main();
}