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
190 lines
8.2 KiB
TypeScript
190 lines
8.2 KiB
TypeScript
import { spawnSync } from "node:child_process";
|
|
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import { pathToFileURL } from "node:url";
|
|
|
|
import { afterEach, describe, expect, it } from "vitest";
|
|
|
|
import {
|
|
collectStaticAssets,
|
|
countPrecachedAssets,
|
|
SERVICE_WORKER_ASSETS_OUTPUT,
|
|
} from "../../scripts/generate-service-worker-assets.ts";
|
|
import { SERVICE_WORKER_BOUNDS, type StaticAssetManifestV1 } from "../../src/contracts/service-worker.ts";
|
|
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
|
|
|
|
/**
|
|
* 1112/06-02. With the Service Worker on, a product with about 25 generated
|
|
* features passes the precache asset bound and the build stops. The failure
|
|
* said "Static asset count exceeds its bound." with neither the count nor
|
|
* the bound, so nobody could tell how far over it was or which number to
|
|
* look up.
|
|
*/
|
|
const roots: string[] = [];
|
|
afterEach(async () => {
|
|
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
|
});
|
|
|
|
async function distWith(count: number, bytes = 16): Promise<string> {
|
|
const root = await mkdtemp(path.join(tmpdir(), "sw-asset-bounds-"));
|
|
roots.push(root);
|
|
await mkdir(path.join(root, "assets"), { recursive: true });
|
|
for (let index = 0; index < count; index += 1) {
|
|
await writeFile(path.join(root, "assets", `chunk${index}-Abcdefgh.js`), "x".repeat(bytes));
|
|
}
|
|
return root;
|
|
}
|
|
|
|
describe("Service Worker precache bounds", () => {
|
|
it("names the count and the bound when there are too many assets", async () => {
|
|
const over = SERVICE_WORKER_BOUNDS.assets + 1;
|
|
const dist = await distWith(over);
|
|
|
|
await expect(collectStaticAssets(dist, "build-1", "release-1")).rejects.toThrow(
|
|
new RegExp(`${over}\\b.*\\b${SERVICE_WORKER_BOUNDS.assets}\\b`, "u"),
|
|
);
|
|
});
|
|
|
|
it("names the bytes and the bound when the set is too large", async () => {
|
|
const each = SERVICE_WORKER_BOUNDS.singleAssetBytes;
|
|
const count = Math.ceil(SERVICE_WORKER_BOUNDS.assetSetBytes / each) + 1;
|
|
const dist = await distWith(count, each);
|
|
|
|
await expect(collectStaticAssets(dist, "build-1", "release-1")).rejects.toThrow(
|
|
new RegExp(`\\b${count * each}\\b.*\\b${SERVICE_WORKER_BOUNDS.assetSetBytes}\\b`, "u"),
|
|
);
|
|
});
|
|
});
|
|
|
|
// 1112/06-02. The feature-shape measurement counts what the worker would
|
|
// precache with the same rule: hashed names under assets/ with a cacheable
|
|
// type, the worker, the page and public files left out.
|
|
describe("countPrecachedAssets", () => {
|
|
it("counts the files collectStaticAssets precaches", async () => {
|
|
const dist = await distWith(3);
|
|
await writeFile(path.join(dist, "index.html"), "<html></html>");
|
|
await writeFile(path.join(dist, "android-chrome-192x192.png"), "png");
|
|
await writeFile(path.join(dist, "assets", "unhashed.js"), "x");
|
|
await writeFile(path.join(dist, "assets", "notes-Abcdefgh.txt"), "x");
|
|
|
|
const { assets } = await collectStaticAssets(dist, "build-1", "release-1");
|
|
expect(await countPrecachedAssets(dist)).toBe(assets.length);
|
|
expect(assets).toHaveLength(3);
|
|
});
|
|
});
|
|
|
|
// REV-FE-0043. Vite copies `public/assets/x` to dist `assets/x` under its own
|
|
// name. `brand-wordmark.svg` and `icon-notification.png` match the hashed
|
|
// name pattern, so they were precached as immutable, and a product that
|
|
// changed their bytes under the same name could get the old ones from the
|
|
// worker. Vite's manifest does not name a Web Worker's output, so the rule
|
|
// tells a copy by the file `public/` has at the same path. The build now
|
|
// refuses `public/assets/` (REV-FE-0044, public-asset-directory.test.ts);
|
|
// these cases are a dist built without that check.
|
|
describe("files copied from public/assets/", () => {
|
|
async function projectWithPublicAssets() {
|
|
const root = await mkdtemp(path.join(tmpdir(), "sw-public-assets-"));
|
|
roots.push(root);
|
|
const publicDirectory = path.join(root, "public");
|
|
const dist = path.join(root, "dist");
|
|
const copies = ["assets/brand-wordmark.svg", "assets/icons/icon-notification.png"];
|
|
for (const relative of copies) {
|
|
for (const directory of [publicDirectory, dist]) {
|
|
await mkdir(path.dirname(path.join(directory, relative)), { recursive: true });
|
|
await writeFile(path.join(directory, relative), "public bytes");
|
|
}
|
|
}
|
|
await writeFile(path.join(dist, "assets", "index-AbCdEf12.js"), "entry");
|
|
await writeFile(path.join(dist, "assets", "index-AbCdEf12.css"), "style");
|
|
return { root, dist, publicDirectory };
|
|
}
|
|
|
|
it("precaches the files Vite hashed and not the copies of public/assets/", async () => {
|
|
const { dist, publicDirectory } = await projectWithPublicAssets();
|
|
|
|
const { assets } = await collectStaticAssets(dist, "build-1", "release-1", "/", publicDirectory);
|
|
|
|
expect(assets.map((asset) => asset.url)).toEqual([
|
|
"/assets/index-AbCdEf12.css",
|
|
"/assets/index-AbCdEf12.js",
|
|
]);
|
|
});
|
|
|
|
it("counts what collectStaticAssets precaches", async () => {
|
|
const { dist, publicDirectory } = await projectWithPublicAssets();
|
|
|
|
const { assets } = await collectStaticAssets(dist, "build-1", "release-1", "/", publicDirectory);
|
|
|
|
expect(await countPrecachedAssets(dist, publicDirectory)).toBe(assets.length);
|
|
expect(assets).toHaveLength(2);
|
|
});
|
|
|
|
it("precaches every hashed file when the project has no public/", async () => {
|
|
const { root, dist } = await projectWithPublicAssets();
|
|
const missing = path.join(root, "no-public");
|
|
|
|
const { assets } = await collectStaticAssets(dist, "build-1", "release-1", "/", missing);
|
|
|
|
expect(assets).toHaveLength(4);
|
|
expect(await countPrecachedAssets(dist, missing)).toBe(4);
|
|
});
|
|
});
|
|
|
|
// The build does not pass the public/ folder: step 5 of
|
|
// scripts/build-frontend.ts runs `node scripts/generate-service-worker-assets.ts
|
|
// <dist>`, so collectStaticAssets leaves out the copies of the default folder,
|
|
// public/ of the folder the build runs in. The feature-shape measurement
|
|
// calls countPrecachedAssets without it too. The cases above pass the folder;
|
|
// these run the generator in a project folder, as the build does.
|
|
describe("the generator in a project with public/assets/", { timeout: childProcessTimeout(303) }, () => {
|
|
const GENERATOR = path.resolve("scripts/generate-service-worker-assets.ts");
|
|
|
|
/** public/assets/brand-wordmark.svg, its copy in dist and one file Vite hashed. */
|
|
async function project(): Promise<string> {
|
|
const root = await mkdtemp(path.join(tmpdir(), "sw-assets-generator-"));
|
|
roots.push(root);
|
|
for (const directory of ["public", "dist"]) {
|
|
await mkdir(path.join(root, directory, "assets"), { recursive: true });
|
|
await writeFile(path.join(root, directory, "assets", "brand-wordmark.svg"), "public bytes");
|
|
}
|
|
await writeFile(path.join(root, "dist", "assets", "index-AbCdEf12.js"), "entry");
|
|
return root;
|
|
}
|
|
|
|
// Empty is unset (scripts/lib/run-isolation.ts, src/contracts/env.ts): the
|
|
// list is written under the project folder, with URLs under /.
|
|
const env = { ...process.env, RUN_OUTPUT_ROOT: "", VITE_ROUTER_BASE_PATH: "" };
|
|
|
|
it("writes the file Vite hashed and not the copy into the list", async () => {
|
|
const root = await project();
|
|
|
|
const result = spawnSync(process.execPath, [GENERATOR, "dist"], { cwd: root, encoding: "utf8", env });
|
|
|
|
expect(result.stderr).toBe("");
|
|
expect(result.status).toBe(0);
|
|
const source = await readFile(path.join(root, SERVICE_WORKER_ASSETS_OUTPUT), "utf8");
|
|
const listed = /= (\{[\s\S]*\}) as const;/u.exec(source)?.[1] ?? "{}";
|
|
const { assets } = JSON.parse(listed) as Partial<StaticAssetManifestV1>;
|
|
expect(assets?.map((asset) => asset.url)).toEqual(["/assets/index-AbCdEf12.js"]);
|
|
});
|
|
|
|
it("counts the file Vite hashed and not the copy", async () => {
|
|
const root = await project();
|
|
const count = [
|
|
`const { countPrecachedAssets } = await import(${JSON.stringify(pathToFileURL(GENERATOR).href)});`,
|
|
'process.stdout.write(String(await countPrecachedAssets("dist")));',
|
|
].join("\n");
|
|
|
|
const result = spawnSync(process.execPath, ["--input-type=module", "--eval", count], {
|
|
cwd: root,
|
|
encoding: "utf8",
|
|
env,
|
|
});
|
|
|
|
expect(result.stderr).toBe("");
|
|
expect(result.status).toBe(0);
|
|
expect(result.stdout).toBe("1");
|
|
});
|
|
});
|