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
172 lines
7.1 KiB
TypeScript
172 lines
7.1 KiB
TypeScript
import { spawnSync } from "node:child_process";
|
|
import { existsSync } from "node:fs";
|
|
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
|
|
import {
|
|
PUBLIC_DIRECTORY,
|
|
publicAssetDirectoryProblem,
|
|
} from "../../scripts/lib/public-asset-directory.ts";
|
|
import viteConfig from "../../vite.config.ts";
|
|
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
|
|
|
|
/**
|
|
* REV-FE-0044. Vite copies `public/assets/x` to dist `assets/x` under its own
|
|
* name, and the hosting contract (`config/hosting/cache-policy.json`
|
|
* `hashedAsset`, path `/assets/*`) serves every file there as `immutable` for
|
|
* a year. A product that kept `brand-wordmark.svg` there and changed its
|
|
* bytes in the next release got the old file from browsers and CDNs. A path
|
|
* rule cannot give the copy other headers, so `scripts/build-frontend.ts`
|
|
* stops before Vite when `public/` has a folder of the assets directory's
|
|
* name (`BUILD_ASSET_DIRECTORY`).
|
|
*/
|
|
const roots: string[] = [];
|
|
afterEach(async () => {
|
|
vi.doUnmock("../../src/contracts/service-worker.ts");
|
|
vi.resetModules();
|
|
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
|
});
|
|
|
|
/** A `public/` folder with these files, and the template's own two. */
|
|
async function publicWith(...files: string[]): Promise<string> {
|
|
const root = await mkdtemp(path.join(tmpdir(), "public-asset-directory-"));
|
|
roots.push(root);
|
|
const publicDirectory = path.join(root, "public");
|
|
for (const relative of ["config.json", "release-manifest.json", ...files]) {
|
|
await mkdir(path.dirname(path.join(publicDirectory, relative)), { recursive: true });
|
|
await writeFile(path.join(publicDirectory, relative), "public bytes");
|
|
}
|
|
return publicDirectory;
|
|
}
|
|
|
|
describe("a public/ folder named like the assets directory", () => {
|
|
it("is refused with its path and both ways out", async () => {
|
|
const publicDirectory = await publicWith(
|
|
"assets/brand-wordmark.svg",
|
|
"assets/icons/icon-notification.png",
|
|
"icons/android-chrome-192x192.png",
|
|
);
|
|
|
|
const problem = await publicAssetDirectoryProblem(publicDirectory);
|
|
|
|
expect(problem).toContain(`${path.join(publicDirectory, "assets")}/`);
|
|
expect(problem).toContain("import each file from source so Vite gives it a hashed name");
|
|
expect(problem).toContain("move it to another folder of public/");
|
|
});
|
|
|
|
it("is refused even when it holds no file", async () => {
|
|
const publicDirectory = await publicWith();
|
|
await mkdir(path.join(publicDirectory, "assets"));
|
|
|
|
expect(await publicAssetDirectoryProblem(publicDirectory)).toContain(
|
|
`${path.join(publicDirectory, "assets")}/`,
|
|
);
|
|
});
|
|
|
|
it("leaves other folders of public/ alone, the same name deeper down too", async () => {
|
|
const publicDirectory = await publicWith(
|
|
"icons/android-chrome-192x192.png",
|
|
"assets-legacy/brand-wordmark.svg",
|
|
"brand/assets/brand-wordmark.svg",
|
|
"favicon.svg",
|
|
);
|
|
|
|
expect(await publicAssetDirectoryProblem(publicDirectory)).toBeUndefined();
|
|
});
|
|
|
|
it("leaves a project without public/ alone", async () => {
|
|
const root = await mkdtemp(path.join(tmpdir(), "public-asset-directory-"));
|
|
roots.push(root);
|
|
|
|
expect(await publicAssetDirectoryProblem(path.join(root, "public"))).toBeUndefined();
|
|
});
|
|
|
|
it("leaves the template's own public/ alone", async () => {
|
|
expect(await publicAssetDirectoryProblem()).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// The check above stops nothing unless the build calls it: step 0 of
|
|
// scripts/build-frontend.ts, before it cleans dist or starts Vite. The build
|
|
// runs here in a folder with nothing but public/assets/, so it ends at step 0
|
|
// and builds nothing. Without step 0 it goes on to step 2, which this folder
|
|
// does not have, and fails with another message.
|
|
describe("scripts/build-frontend.ts in a project with public/assets/", { timeout: childProcessTimeout(528) }, () => {
|
|
it("refuses before it builds and leaves no dist", async () => {
|
|
const root = await mkdtemp(path.join(tmpdir(), "build-frontend-public-assets-"));
|
|
roots.push(root);
|
|
await mkdir(path.join(root, "public", "assets"), { recursive: true });
|
|
await writeFile(path.join(root, "public", "assets", "brand-wordmark.svg"), "public bytes");
|
|
|
|
const result = spawnSync(process.execPath, [path.resolve("scripts/build-frontend.ts")], {
|
|
cwd: root,
|
|
encoding: "utf8",
|
|
// Empty is unset (scripts/lib/run-isolation.ts): the build's dist is <root>/dist.
|
|
env: { ...process.env, RUN_OUTPUT_ROOT: "" },
|
|
});
|
|
|
|
expect(result.stderr).toContain(`build refused: ${path.join("public", "assets")}/`);
|
|
expect(result.status).toBe(1);
|
|
expect(existsSync(path.join(root, "dist"))).toBe(false);
|
|
});
|
|
});
|
|
|
|
// C2. The build calls the check with no argument, so the folder it refuses
|
|
// must come from BUILD_ASSET_DIRECTORY, not from the word `assets`.
|
|
describe("the assets directory name comes from BUILD_ASSET_DIRECTORY", () => {
|
|
async function checkWithAssetDirectory(assetDirectory: string) {
|
|
vi.resetModules();
|
|
vi.doMock("../../src/contracts/service-worker.ts", async (importOriginal) => ({
|
|
...(await importOriginal<typeof import("../../src/contracts/service-worker.ts")>()),
|
|
BUILD_ASSET_DIRECTORY: assetDirectory,
|
|
}));
|
|
return (await import("../../scripts/lib/public-asset-directory.ts"))
|
|
.publicAssetDirectoryProblem;
|
|
}
|
|
|
|
it("refuses public/static/ when the assets directory is static/", async () => {
|
|
const check = await checkWithAssetDirectory("static/");
|
|
const publicDirectory = await publicWith("static/brand-wordmark.svg");
|
|
|
|
expect(await check(publicDirectory)).toContain(`${path.join(publicDirectory, "static")}/`);
|
|
});
|
|
|
|
it("leaves public/assets/ alone when the assets directory is static/", async () => {
|
|
const check = await checkWithAssetDirectory("static/");
|
|
const publicDirectory = await publicWith("assets/brand-wordmark.svg");
|
|
|
|
expect(await check(publicDirectory)).toBeUndefined();
|
|
});
|
|
|
|
it("refuses the nested folder of a nested assets directory", async () => {
|
|
const check = await checkWithAssetDirectory("static/hashed/");
|
|
const publicDirectory = await publicWith(
|
|
"static/robots.txt",
|
|
"static/hashed/brand-wordmark.svg",
|
|
);
|
|
|
|
expect(await check(publicDirectory)).toContain(
|
|
`${path.join(publicDirectory, "static", "hashed")}/`,
|
|
);
|
|
});
|
|
});
|
|
|
|
// REV-FE-0043, REV-FE-0044. Both the precache generator and this check take
|
|
// the `public/` folder name as fixed. A product that sets `publicDir` in
|
|
// vite.config.ts changes PUBLIC_DIRECTORY with it; this fails until it does.
|
|
describe("vite.config.ts publicDir is PUBLIC_DIRECTORY", () => {
|
|
const VITE_DEFAULT_PUBLIC_DIR = "public";
|
|
|
|
it("names the folder the build checks and the generator reads", async () => {
|
|
const config =
|
|
typeof viteConfig === "function"
|
|
? await viteConfig({ command: "build", mode: "production", isSsrBuild: false, isPreview: false })
|
|
: viteConfig;
|
|
|
|
expect(config.publicDir ?? VITE_DEFAULT_PUBLIC_DIR).toBe(PUBLIC_DIRECTORY);
|
|
});
|
|
});
|