문제: build manifest 작성과 release 검사 둘은 route 청크를 Vite manifest
`entry.name === moduleId`로 찾았다. 청크 이름이 선언 없이 계약이 되어,
vite.config.ts가 route 청크에 이름을 붙이면(tech-log 방식) 빌드가 이유 없는
`Missing built route chunk: <routeId>`로 멈췄다.
고친 것: `scripts/lib/build-manifest-outputs.ts`의 `findRouteChunk` 하나가 dynamic
entry 중 소스 파일(manifest 키 또는 `src`) 이름이 route runtime의
`moduleId`인 것을 찾는다. 셋(build manifest, verify-release, local release
evidence)이 그것을 쓴다. 새 파일을 두지 않은 것은 release 후보
archive의 검증기 소스 목록(`config/ci/gates.json` member 집합)을 바꾸지
않기 위해서다. 못 찾으면 규칙("moduleId는 그 라우트가 import하는
페이지 파일 이름")을, 둘이면 두 소스 경로를 적는다.
위험·한계: moduleId가 페이지 파일 이름이라는 규약은 그대로다(생성기와
`route-runtime.tsx`가 이미 그렇게 쓴다).
검증: desktop `node scripts/run-vitest.ts run tests/unit/route-chunks.test.ts`
통과(다른 청크 이름, 없음, 중복, 계약 없음, 세 사용처).
Refs: 0929/13-03
238 lines
8.2 KiB
TypeScript
238 lines
8.2 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { lstat, readFile, realpath } from "node:fs/promises";
|
|
import path from "node:path";
|
|
|
|
import type { BuildManifestArtifact } from "../../src/contracts/release-artifacts.ts";
|
|
import { moduleInventoryArtifactSchema } from "../contracts/release-artifacts.ts";
|
|
|
|
type VerifyBuildManifestOutputsDependencies = Readonly<{
|
|
repositoryRoot?: string;
|
|
readBytes?: (target: string) => Promise<Buffer>;
|
|
realpathPath?: (target: string) => Promise<string>;
|
|
assertRegularFile?: (target: string) => Promise<void>;
|
|
assertDirectory?: (target: string) => Promise<void>;
|
|
}>;
|
|
|
|
export const CANONICAL_VITE_MANIFEST_PATH = "dist/.vite/manifest.json";
|
|
|
|
function isSafeRelativePath(value: string): boolean {
|
|
return (
|
|
value.length > 0 &&
|
|
!path.posix.isAbsolute(value) &&
|
|
!path.win32.isAbsolute(value) &&
|
|
!value.includes("\\") &&
|
|
!value.includes("\0") &&
|
|
path.posix.normalize(value) === value &&
|
|
value !== ".." &&
|
|
!value.startsWith("../")
|
|
);
|
|
}
|
|
|
|
function isWithinRoot(root: string, target: string): boolean {
|
|
const relative = path.relative(root, target);
|
|
return (
|
|
relative === "" ||
|
|
(relative !== ".." &&
|
|
!relative.startsWith(`..${path.sep}`) &&
|
|
!path.isAbsolute(relative))
|
|
);
|
|
}
|
|
|
|
function belongsToApprovedRoot(value: string, approvedRoot: string): boolean {
|
|
return value.startsWith(`${approvedRoot}/`);
|
|
}
|
|
|
|
async function defaultAssertRegularFile(target: string): Promise<void> {
|
|
const metadata = await lstat(target);
|
|
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
|
throw new TypeError("not a regular file");
|
|
}
|
|
}
|
|
|
|
async function defaultAssertDirectory(target: string): Promise<void> {
|
|
const metadata = await lstat(target);
|
|
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
throw new TypeError("not a directory");
|
|
}
|
|
}
|
|
|
|
export async function verifyBuildManifestOutputs(
|
|
manifest: BuildManifestArtifact,
|
|
dependencies: VerifyBuildManifestOutputsDependencies = {},
|
|
): Promise<string[]> {
|
|
const repositoryRoot = path.resolve(dependencies.repositoryRoot ?? process.cwd());
|
|
const readBytes = dependencies.readBytes ?? readFile;
|
|
const realpathPath = dependencies.realpathPath ?? realpath;
|
|
const assertRegularFile = dependencies.assertRegularFile ?? defaultAssertRegularFile;
|
|
const assertDirectory = dependencies.assertDirectory ?? defaultAssertDirectory;
|
|
const mismatches: string[] = [];
|
|
const resolvedRoot = await realpathPath(repositoryRoot);
|
|
const approvedRoots = new Map<string, Promise<string | null>>();
|
|
|
|
function resolveApprovedRoot(relativeRoot: string): Promise<string | null> {
|
|
const existing = approvedRoots.get(relativeRoot);
|
|
if (existing) return existing;
|
|
const pending = (async () => {
|
|
const absoluteRoot = path.resolve(repositoryRoot, relativeRoot);
|
|
try {
|
|
await assertDirectory(absoluteRoot);
|
|
const resolvedApprovedRoot = await realpathPath(absoluteRoot);
|
|
return isWithinRoot(resolvedRoot, resolvedApprovedRoot)
|
|
? resolvedApprovedRoot
|
|
: null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
})();
|
|
approvedRoots.set(relativeRoot, pending);
|
|
return pending;
|
|
}
|
|
|
|
async function confinedPath(
|
|
label: string,
|
|
relativePath: string,
|
|
kind: "file" | "directory",
|
|
approvedRoot?: string,
|
|
): Promise<string | null> {
|
|
if (
|
|
!isSafeRelativePath(relativePath) ||
|
|
(approvedRoot !== undefined &&
|
|
!belongsToApprovedRoot(relativePath, approvedRoot))
|
|
) {
|
|
mismatches.push(`buildManifest:${label}:path`);
|
|
return null;
|
|
}
|
|
const absolutePath = path.resolve(repositoryRoot, relativePath);
|
|
if (!isWithinRoot(repositoryRoot, absolutePath)) {
|
|
mismatches.push(`buildManifest:${label}:path`);
|
|
return null;
|
|
}
|
|
try {
|
|
if (kind === "file") await assertRegularFile(absolutePath);
|
|
else await assertDirectory(absolutePath);
|
|
const resolvedPath = await realpathPath(absolutePath);
|
|
const resolvedApprovedRoot = approvedRoot
|
|
? await resolveApprovedRoot(approvedRoot)
|
|
: resolvedRoot;
|
|
if (
|
|
resolvedApprovedRoot === null ||
|
|
!isWithinRoot(resolvedRoot, resolvedPath) ||
|
|
!isWithinRoot(resolvedApprovedRoot, resolvedPath)
|
|
) {
|
|
mismatches.push(`buildManifest:${label}:path`);
|
|
return null;
|
|
}
|
|
return absolutePath;
|
|
} catch {
|
|
mismatches.push(`buildManifest:${label}:missing`);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
if (manifest.outputs.directory !== "dist") {
|
|
mismatches.push("buildManifest:directory:path");
|
|
} else {
|
|
await confinedPath("directory", manifest.outputs.directory, "directory");
|
|
}
|
|
if (manifest.outputs.viteManifest !== CANONICAL_VITE_MANIFEST_PATH) {
|
|
mismatches.push("buildManifest:viteManifest:path");
|
|
} else {
|
|
await confinedPath(
|
|
"viteManifest",
|
|
manifest.outputs.viteManifest,
|
|
"file",
|
|
"dist",
|
|
);
|
|
}
|
|
await confinedPath(
|
|
"runtimeConfigSchema",
|
|
manifest.outputs.runtimeConfigSchema,
|
|
"file",
|
|
"dist",
|
|
);
|
|
for (const [chunkId, chunkPath] of Object.entries(manifest.outputs.routeChunks)) {
|
|
if (!isSafeRelativePath(chunkPath)) {
|
|
mismatches.push(`buildManifest:routeChunk:${chunkId}:path`);
|
|
continue;
|
|
}
|
|
await confinedPath(
|
|
`routeChunk:${chunkId}`,
|
|
path.posix.join(manifest.outputs.directory, chunkPath),
|
|
"file",
|
|
"dist",
|
|
);
|
|
}
|
|
const moduleInventoryPath = await confinedPath(
|
|
"moduleInventory",
|
|
manifest.outputs.moduleInventory,
|
|
"file",
|
|
"artifacts/quality",
|
|
);
|
|
if (moduleInventoryPath) {
|
|
try {
|
|
const bytes = await readBytes(moduleInventoryPath);
|
|
const digest = createHash("sha256").update(bytes).digest("hex");
|
|
if (digest !== manifest.moduleInventoryHash) {
|
|
mismatches.push("buildManifest:moduleInventoryHash");
|
|
}
|
|
try {
|
|
moduleInventoryArtifactSchema.parse(JSON.parse(bytes.toString("utf8")));
|
|
} catch {
|
|
mismatches.push("buildManifest:moduleInventory:invalid");
|
|
}
|
|
} catch {
|
|
mismatches.push("buildManifest:moduleInventory:missing");
|
|
}
|
|
}
|
|
return mismatches;
|
|
}
|
|
|
|
/**
|
|
* 0929/13-03. The built chunk of a route's lazy page, for the build manifest
|
|
* and the two release checks that compare its `routeChunks`. A route runtime's
|
|
* `moduleId` is the file name of the page it imports
|
|
* (`src/presentation/routes/route-runtime.tsx`, a generated feature's
|
|
* `<id>-route-runtime.ts`), so the chunk is the dynamic entry whose source
|
|
* file — the Vite manifest key — has that name. The chunk's own `name` used to
|
|
* be matched instead, so a chunk-naming change in vite.config.ts stopped the
|
|
* build with a reason-less `Missing built route chunk`.
|
|
*/
|
|
export type RouteChunkLookup = Readonly<{ file: string }> | Readonly<{ error: string }>;
|
|
|
|
const SOURCE_EXTENSION = /\.(?:tsx|ts|jsx|js)$/u;
|
|
|
|
export function findRouteChunk(
|
|
manifest: Readonly<Record<string, unknown>>,
|
|
routeId: string,
|
|
moduleId: string | undefined,
|
|
): RouteChunkLookup {
|
|
if (moduleId === undefined) {
|
|
return { error: `Missing built route chunk: ${routeId} has no route runtime contract (ROUTE_RUNTIME_CONTRACT)` };
|
|
}
|
|
const matches: { source: string; file: string }[] = [];
|
|
for (const [key, entry] of Object.entries(manifest)) {
|
|
if (!isManifestRecord(entry) || entry["isDynamicEntry"] !== true || typeof entry["file"] !== "string") continue;
|
|
const source = typeof entry["src"] === "string" ? entry["src"] : key;
|
|
if (path.posix.basename(source).replace(SOURCE_EXTENSION, "") === moduleId) {
|
|
matches.push({ source, file: entry["file"] });
|
|
}
|
|
}
|
|
if (matches.length === 1) return { file: matches[0]!.file };
|
|
if (matches.length === 0) {
|
|
return {
|
|
error:
|
|
`Missing built route chunk: ${routeId}: no lazily imported module in the Vite manifest has the source ` +
|
|
`file ${moduleId}.tsx (or .ts). A route runtime's moduleId must be the file name of the page it imports.`,
|
|
};
|
|
}
|
|
return {
|
|
error:
|
|
`Ambiguous built route chunk: ${routeId}: the lazily imported modules ` +
|
|
`${matches.map(({ source }) => source).join(", ")} are all named ${moduleId}.`,
|
|
};
|
|
}
|
|
|
|
function isManifestRecord(value: unknown): value is Record<string, unknown> {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
}
|