Files
clean-architecture-frontend…/scripts/build-frontend.ts
DongHyeonka 3b3396ea07 fix(service-worker): public/ 사본을 사전 캐시와 assets 폴더에서 뺀다
Vite는 public/을 그대로 복사한다. public/assets/x는 dist assets/x가
되어 Vite의 hash 파일 옆에 자기 이름으로 놓인다. 그 이름이
HASHED_STATIC_ASSET_NAME과 맞으면 Service Worker가 immutable로 사전
캐시하고(REV-FE-0043), 호스팅 계약(config/hosting/cache-policy.json
hashedAsset)도 /assets/* 전체에 1년 immutable 헤더를 준다
(REV-FE-0044). 제품이 다음 release에서 이름은 두고 바이트만 바꾸면
worker와 브라우저·CDN이 옛 바이트를 낸다.

두 곳에서 막는다.
- 사전 캐시: 생성기가 dist 파일 가운데 public/에도 같은 경로로 있는
  파일을 뺀다. collectStaticAssets와 countPrecachedAssets가 같은 목록
  (precachedFiles)을 읽는다.
- 빌드: scripts/build-frontend.ts가 Vite 전에 public/ 아래
  BUILD_ASSET_DIRECTORY 이름의 폴더를 찾으면, 소스에서 import하거나
  public/의 다른 폴더로 옮기라는 메시지로 실패한다
  (scripts/lib/public-asset-directory.ts).
public/ 이름은 PUBLIC_DIRECTORY 한 값으로 두고, vite.config.ts의
publicDir와 같은지 시험이 본다. Mmax 측정법 2단계는 public/assets/로
채우던 것을 빌드가 import하는 소스 자산(new URL(..., ?no-inline))으로
바꾸고, 채우기 모듈이 URL 배열을 globalThis 속성 하나에 대입한다고
적는다.

시험은 두 검사를 실제 진입점으로도 부른다. 임시 프로젝트 폴더에서
scripts/build-frontend.ts가 0단계에서 거절하고 dist를 만들지 않는지,
scripts/generate-service-worker-assets.ts <dist>가 인자 없는 기본
public/로 사본을 빼는지(목록과 countPrecachedAssets 둘 다) 본다.

버린 안:
- Vite manifest(.vite/manifest.json)의 file·css·assets로 사전 캐시를
  고른다: desktop 실빌드에서 Web Worker 출력(assets/<이름>-<hash>.js)이
  manifest에 없어 빠진다.
- 호스팅 계약에 파일별 목록을 둔다: 호스팅마다 설정 방식이 달라
  템플릿이 덮지 못한다.
- 문서로만 금지한다: 지키는지 보는 곳이 없다.
- 검사를 check:bundle이나 FE-GATE-019에 둔다: 게이트 없이 pnpm
  build만 하는 배포를 막지 못하고, 019는 production 단계다.
- 카드마다 커밋 하나: 두 검사가 같은 PUBLIC_DIRECTORY를 읽는 것이
  수정의 일부라, 나누면 중간 커밋에 상수가 둘 생긴다.

위험·한계: public/assets/를 둔 파생 프로젝트는 빌드가 실패로 바뀐다
(CHANGELOG 「먼저 할 일」). publicDir를 바꾼 제품은 PUBLIC_DIRECTORY도
바꿔야 한다. scripts/check-bundle.ts는 아직 "public" 글자를 직접
쓴다(REV-FE-0010 파일, 이 커밋 밖). Mmax 측정법의 채우기 모듈 청크는
초기 JS로 세어진다(측정 트리에서 200,765 B, 예산 안). 실제 호스팅
헤더는 재지 않았다(FE-GATE-019는 production 단계).

검증(트리 fd833429):
- RED: 8bb30d2a + 사전 캐시 변경만(트리 f0b1076c)에서
  public/assets/brand-wordmark.svg를 둔 desktop 빌드가 rc=0이고 dist
  assets/brand-wordmark.svg가 같은 바이트로 생긴다. 검사를 넣은
  트리(105919e1)에서는 build refused 메시지로 rc=1, 0단계를 지운 변이는
  다시 rc=0이다.
- 사전 캐시: 고치기 전 생성기에서 시험 2 failed → 6 passed, 변이 5개
  실패(82b959ff 위). 고친 생성기 실빌드에서 사전 캐시 28 → 27이고
  빠진 것은 assets/brand-wordmark.svg 하나, Web Worker 출력은 남는다.
- 빌드 검사 단위: tests/unit/public-asset-directory.test.ts 10 passed.
  변이 6개(검사 제거, "assets" 글자 둘, public/ 자체, ENOENT 실패,
  이름 바꾸기) 모두 실패. build-frontend.ts 0단계와 import를 지운
  변이는 진입점 시험 1 failed.
- 생성기 진입점: service-worker-asset-bounds 8 passed. 기본 public
  경로를 "public-missing"으로 바꾼 변이(collectStaticAssets 쪽,
  countPrecachedAssets 쪽, 둘 다)가 각각 1·1·2 failed.
- 자식 프로세스 시한: desktop JSON reporter로 잰 가장 긴 값 527.3 ms·
  302.3 ms(unit, coverage보다 길다)를 childProcessTimeout(528)·(303)로.
- Mmax(새 채우기): 사전 캐시 256개, 23,417 B, 다섯 자리 23,441 B,
  handler 둘 23,439 B → 1 KiB 올림 23,552로 예산 그대로.
- desktop merge 단계 14개 rc=0, desktop verify:documentation rc=0.
  노트북 test:unit 4,090개, check:types, lint, check:architecture,
  verify:documentation, scripts/verify.sh docs rc=0.

Refs: REV-FE-0043, REV-FE-0044
2026-11-23 17:02:06 +09:00

115 lines
4.9 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { rm, writeFile } from "node:fs/promises";
import process from "node:process";
import { SERVICE_WORKER_SCRIPT_PATH } from "../src/contracts/service-worker.ts";
import { INSTALLED_RUNTIME_CAPABILITIES } from "../src/features/installed-runtime-capabilities.ts";
import { makeDistFilesPublic } from "./lib/dist-permissions.ts";
import { publicAssetDirectoryProblem } from "./lib/public-asset-directory.ts";
import { runOutputPath } from "./lib/run-isolation.ts";
import { SELF_UNREGISTERING_SERVICE_WORKER } from "./lib/self-unregistering-service-worker.ts";
/**
* §17.2.2. Deterministic two-pass build.
*
* The Service Worker needs the exact hashed asset list at compile time, so the
* order is fixed:
*
* 0. refuse a `public/` folder named like the assets directory (REV-FE-0044)
* 1. clean dist and .generated/frontend-runtime
* 2. generate contractSet and build-info source
* 3. Vite app build (emptyOutDir = true)
* 4. materialize dist/config.json from the declared APP_PROFILE
* 5. scan app dist and generate the static asset source
* 6. ACTIVE only: Vite Service Worker build (emptyOutDir = false,
* publicDir = false: it must not copy `public/` over step 4, 0929/06-01)
* REMOVE_REGISTRATION only: write the self-unregistering worker (06-03)
* 7. generate Release Manifest V2 and the build manifest
* 8. make every dist file readable by other users (13-02)
*
* Steps 5 and 6 are skipped for `REMOVE_REGISTRATION`, `PURGE_OWNED_RESOURCES`
* and `null`: those modes never run an active worker build.
* `REMOVE_REGISTRATION` still ships a `service-worker.js` so the browser's
* update check can replace a worker that stops the page from booting (D-5).
*
* Step 4 has to follow the Vite build. Vite copies `public/` verbatim, so
* without it every build — including a production one — ships the local
* runtime document. The Service Worker asset scan excludes `config.json`
* (`scripts/generate-service-worker-assets.ts`), so the order against step 5
* is not what keeps the profile out of the worker cache (13-15). Step 6 reads
* the release manifest URL from the `dist/config.json` step 4 wrote, and fails
* if its `APP_ENV` is not `APP_PROFILE` (06-10).
*
* Step 0 runs before Vite because of the same verbatim copy: `public/assets/`
* would land in dist `assets/` under the files' own names, next to Vite's
* hashed files, and the hosting contract serves everything there as
* immutable for a year (`config/hosting/cache-policy.json` `hashedAsset`).
* The folder is `BUILD_ASSET_DIRECTORY` under `PUBLIC_DIRECTORY`
* (`scripts/lib/public-asset-directory.ts`).
*
* 1105/12-04. With `RUN_OUTPUT_ROOT` set (a Playwright config sets it for its
* web server under `TEST_RUN_ID`), every path above — `dist`,
* `.generated/frontend-runtime` and the build's `artifacts/` evidence — is
* under that folder instead, so a second build in the same checkout does not
* empty the first one's `dist`. Every step reads the same variable
* (`scripts/lib/run-isolation.ts`). Unset, the paths are the ones above.
*/
const selection = INSTALLED_RUNTIME_CAPABILITIES.serviceWorker;
const buildsActiveWorker = selection?.mode === "ACTIVE";
const dist = runOutputPath("dist");
function run(command: string, args: readonly string[]): void {
const result = spawnSync(command, [...args], {
stdio: "inherit",
env: process.env,
});
if (result.status !== 0) {
process.stderr.write(`build step failed: ${command} ${args.join(" ")}\n`);
process.exit(result.status ?? 1);
}
}
// 0. no public/ folder that lands in the hashed assets directory
const publicAssetProblem = await publicAssetDirectoryProblem();
if (publicAssetProblem !== undefined) {
process.stderr.write(`build refused: ${publicAssetProblem}\n`);
process.exit(1);
}
// 1. clean
await rm(dist, { recursive: true, force: true });
await rm(runOutputPath(".generated/frontend-runtime"), { recursive: true, force: true });
// 2. contract set + build info
run("node", ["scripts/generate-contract-set.ts"]);
// 3. app build
run("npx", ["vite", "build"]);
// 4. runtime config for the declared profile
run("node", ["scripts/generate-runtime-config.ts"]);
if (buildsActiveWorker) {
// 5. hashed asset inventory
run("node", ["scripts/generate-service-worker-assets.ts", dist]);
// 6. service worker build
run("npx", ["vite", "build", "--config", "vite.service-worker.config.ts"]);
} else if (selection?.mode === "REMOVE_REGISTRATION") {
// 6. self-unregistering worker in place of the active one
await writeFile(
`${dist}/${SERVICE_WORKER_SCRIPT_PATH}`,
SELF_UNREGISTERING_SERVICE_WORKER,
);
} else {
process.stdout.write(
`service worker mode ${selection?.mode ?? "null"}: skipping worker build\n`,
);
}
// 7. release + build manifest
run("node", ["scripts/generate-build-manifest.ts"]);
// 8. publishable permissions: the validated writer creates 0600 files
await makeDistFilesPublic(dist);