Files
clean-architecture-frontend…/scripts/generate-runtime-config.ts
T
DongHyeonka c1a98e9743 fix(build): 빌드 식별값의 기본값을 한 함수로 읽는다
문제: 빌드 ID·커밋·release ID의 기본값을 일곱 곳에서 따로 계산하고
`||`와 `??`가 섞였다. 그래서 VITE_BUILD_ID=""이면 runtime config는
local-build가 되고, build manifest·Service Worker·재현 빌드 기록은 ""가
된다(R-2).

고른 방법: src/contracts/env.ts에 BUILD_IDENTITY_PLACEHOLDERS와
readBuildIdentity(environment)를 두고(빈 값은 없는 것과 같다), 페이지의
getBuildConfig와 빌드 스크립트 다섯·vite.service-worker.config.ts가 모두
그것을 쓴다. ENV_REGISTRY 기본값과 LOCAL_BUILD_IDENTITY도 같은 상수에서
나온다. 시험이 빈 값 규칙과, 읽는 파일마다 자기 기본값을 다시 쓰지
않는지를 본다.
버린 대안: 빈 값을 거절하기 — local 빌드가 쓰는 placeholder 규칙을 바꾸고
admission이 이미 placeholder를 공개 대상에서 거절한다.

위험·한계: generate-build-manifest.ts·verify-reproducible-build.ts는 그룹 C도
고치는 파일이다. 줄은 겹치지 않는다.

검증: desktop 결과는 PR 본문.

Refs: R-2
2026-11-13 20:17:04 +09:00

114 lines
4.4 KiB
TypeScript

import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import process from "node:process";
import {
DEPLOYMENT_TARGETS,
isDeploymentTarget,
PUBLIC_TARGETS,
type DeploymentTarget,
} from "../src/contracts/deployment-admission.ts";
import { readBuildIdentity } from "../src/contracts/env.ts";
import { runtimeConfigV2ArtifactSchema } from "../src/contracts/release-artifacts.ts";
import { runOutputPath } from "./lib/run-isolation.ts";
/**
* §6.4. Materializes `dist/config.json` from the profile the build declares.
*
* `public/` is copied verbatim into `dist/`, so before this step the runtime
* document that shipped with every build was the local one — `APP_ENV: local`,
* `AUTH_MODE: demo`, a loopback API — regardless of what the build was for.
* The profile is the source of truth instead, and the only values a deployment
* may inject are the ones it actually owns: its endpoints and its identity.
*
* The result is validated against the same V2 schema the browser will apply, so
* an override cannot produce a document that only fails at boot.
*/
const PROFILE_DIRECTORY = "config/runtime";
/** Under `RUN_OUTPUT_ROOT` when a run sets one (1105/12-04). */
const OUTPUT_PATH = "dist/config.json";
/**
* Deployment-supplied values. Everything else is fixed by the profile so a
* deployment cannot quietly widen what was reviewed.
*/
export const RUNTIME_OVERRIDES = Object.freeze({
API_BASE_URL: "RUNTIME_API_BASE_URL",
TELEMETRY_ENDPOINT: "RUNTIME_TELEMETRY_ENDPOINT",
} as const);
export async function generateRuntimeConfig(
target: DeploymentTarget,
environment: NodeJS.ProcessEnv = process.env,
): Promise<Record<string, unknown>> {
const profilePath = path.join(PROFILE_DIRECTORY, `${target}.json`);
const source: unknown = JSON.parse(await readFile(profilePath, "utf8"));
if (source === null || typeof source !== "object" || Array.isArray(source)) {
throw new TypeError(`${profilePath}: runtime profile must be an object`);
}
const draft: Record<string, unknown> = { ...(source as Record<string, unknown>) };
if (draft["APP_ENV"] !== target) {
throw new Error(
`${profilePath}: declares APP_ENV ${String(draft["APP_ENV"])}, expected ${target}`,
);
}
for (const [field, variable] of Object.entries(RUNTIME_OVERRIDES)) {
const supplied = environment[variable];
if (supplied !== undefined && supplied !== "") draft[field] = supplied;
}
// 13-07. dist, and the release manifest in it, is served under the router
// base path; a root-relative profile URL is rebased onto it.
const basePath = environment["VITE_ROUTER_BASE_PATH"] || "/";
const manifestUrl = draft["RELEASE_MANIFEST_URL"];
if (
typeof manifestUrl === "string" &&
manifestUrl.startsWith("/") &&
!manifestUrl.startsWith(basePath)
) {
draft["RELEASE_MANIFEST_URL"] = `${basePath}${manifestUrl.slice(1)}`;
}
// F-6. A public build without its own identity would ship the local
// placeholder; fail here instead of at admission.
if (PUBLIC_TARGETS.has(target) && !environment["VITE_BUILD_ID"]) {
throw new Error(`${profilePath}: a ${target} build requires VITE_BUILD_ID`);
}
const { buildId, releaseId } = readBuildIdentity(environment);
draft["BUILD_ID"] = buildId;
draft["RELEASE_ID"] = releaseId;
const parsed = runtimeConfigV2ArtifactSchema.safeParse(draft);
if (!parsed.success) {
const issues = parsed.error.issues
.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`)
.join("\n ");
throw new Error(`${profilePath}: runtime config is invalid\n ${issues}`);
}
return draft;
}
function resolveTarget(environment: NodeJS.ProcessEnv): DeploymentTarget {
const declared = environment["APP_PROFILE"] ?? "local";
if (!isDeploymentTarget(declared)) {
throw new Error(
`APP_PROFILE must be one of ${DEPLOYMENT_TARGETS.join(", ")}; received ${declared}`,
);
}
return declared;
}
async function main(): Promise<void> {
const target = resolveTarget(process.env);
const config = await generateRuntimeConfig(target);
const output = runOutputPath(OUTPUT_PATH);
await writeFile(output, `${JSON.stringify(config, null, 2)}\n`, "utf8");
process.stdout.write(
`runtime config: ${target} profile written to ${output} ` +
`(APP_ENV=${String(config["APP_ENV"])}, AUTH_MODE=${String(config["AUTH_MODE"])})\n`,
);
}
if (process.argv[1] && import.meta.url.endsWith(path.basename(process.argv[1]))) {
await main();
}