chore(review): 1105 실행 격리 조치 브랜치를 합친다

This commit is contained in:
DongHyeonka
2026-11-06 02:59:02 +09:00
25 changed files with 1071 additions and 68 deletions
+14 -5
View File
@@ -5,6 +5,7 @@ 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 { runOutputPath } from "./lib/run-isolation.ts";
import { SELF_UNREGISTERING_SERVICE_WORKER } from "./lib/self-unregistering-service-worker.ts";
/**
@@ -36,10 +37,18 @@ import { SELF_UNREGISTERING_SERVICE_WORKER } from "./lib/self-unregistering-serv
* 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).
*
* 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], {
@@ -53,8 +62,8 @@ function run(command: string, args: readonly string[]): void {
}
// 1. clean
await rm("dist", { recursive: true, force: true });
await rm(".generated/frontend-runtime", { recursive: true, force: true });
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"]);
@@ -67,13 +76,13 @@ run("node", ["scripts/generate-runtime-config.ts"]);
if (buildsActiveWorker) {
// 5. hashed asset inventory
run("node", ["scripts/generate-service-worker-assets.ts", "dist"]);
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}`,
`${dist}/${SERVICE_WORKER_SCRIPT_PATH}`,
SELF_UNREGISTERING_SERVICE_WORKER,
);
} else {
@@ -86,4 +95,4 @@ if (buildsActiveWorker) {
run("node", ["scripts/generate-build-manifest.ts"]);
// 8. publishable permissions: the validated writer creates 0600 files
await makeDistFilesPublic("dist");
await makeDistFilesPublic(dist);
+18 -12
View File
@@ -21,8 +21,14 @@ import {
} from "./lib/build-environment.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
import { CANONICAL_VITE_MANIFEST_PATH } from "./lib/build-manifest-outputs.ts";
import { runOutputPath } from "./lib/run-isolation.ts";
assertCiBuildEnvironment(process.env);
// 1105/12-04. With RUN_OUTPUT_ROOT set, this build's dist and artifacts are
// under that folder. The manifest still records `dist`, `artifacts/...`:
// its paths are relative to the folder the build wrote, which is the
// checkout when the variable is unset.
const at = (relativePath: string) => runOutputPath(relativePath);
type ViteManifestEntry = Readonly<{
file: string;
name?: string;
@@ -39,10 +45,10 @@ const releaseId = process.env.RELEASE_ID ?? "local-release";
const runnerImage = process.env.CI_RUNNER_IMAGE ?? `${process.platform}-${process.arch}`;
const buildTime = buildDate(process.env);
const builtAt = buildTime.toISOString();
const viteManifest = await readFile(CANONICAL_VITE_MANIFEST_PATH, "utf8");
const viteManifest = await readFile(at(CANONICAL_VITE_MANIFEST_PATH), "utf8");
const viteManifestObject = parseViteManifest(JSON.parse(viteManifest));
const moduleInventory = await readFile(
"dist/.vite/module-inventory.json",
at("dist/.vite/module-inventory.json"),
"utf8",
);
const moduleInventoryDocument = moduleInventoryArtifactSchema.parse(
@@ -56,7 +62,7 @@ const moduleInventoryHash = createHash("sha256")
.update(moduleInventoryBytes)
.digest("hex");
const runtimeConfig = runtimeConfigV2ArtifactSchema.parse(
JSON.parse(await readFile("dist/config.json", "utf8")),
JSON.parse(await readFile(at("dist/config.json"), "utf8")),
);
const routeChunks: Record<string, string> = {};
const runtimeContracts: Readonly<Record<string, { moduleId: string }>> =
@@ -113,36 +119,36 @@ const releaseManifest = releaseManifestV2ArtifactSchema.parse({
contractSet: buildContractSet(),
});
await mkdir("artifacts/release", { recursive: true });
await mkdir("artifacts/quality", { recursive: true });
await mkdir(at("artifacts/release"), { recursive: true });
await mkdir(at("artifacts/quality"), { recursive: true });
await writeValidatedJsonArtifact({
path: "artifacts/quality/vite-module-inventory.json",
path: at("artifacts/quality/vite-module-inventory.json"),
schema: moduleInventoryArtifactSchema,
value: moduleInventoryDocument,
});
await rm("dist/.vite/module-inventory.json");
await rm(at("dist/.vite/module-inventory.json"));
await writeValidatedJsonArtifact({
path: "dist/config.json",
path: at("dist/config.json"),
schema: runtimeConfigV2ArtifactSchema,
value: runtimeConfig,
});
await writeValidatedJsonArtifact({
path: "dist/release-manifest.json",
path: at("dist/release-manifest.json"),
schema: releaseManifestV2ArtifactSchema,
value: releaseManifest,
});
await writeValidatedJsonArtifact({
path: "dist/runtime-config.schema.json",
path: at("dist/runtime-config.schema.json"),
schema: jsonSchemaDocumentArtifactSchema,
value: runtimeConfigJsonSchema,
});
await writeValidatedJsonArtifact({
path: "artifacts/release/runtime-config.schema.json",
path: at("artifacts/release/runtime-config.schema.json"),
schema: jsonSchemaDocumentArtifactSchema,
value: runtimeConfigJsonSchema,
});
await writeValidatedJsonArtifact({
path: "artifacts/release/build-manifest.json",
path: at("artifacts/release/build-manifest.json"),
schema: buildManifestArtifactSchema,
value: manifest,
});
+6 -3
View File
@@ -8,6 +8,7 @@ import {
type ContractSetPackage,
} from "../src/contracts/contract-set-canonical.ts";
import { EXPECTED_CONTRACT_SET_PACKAGES } from "../src/features/installed-contract-contributions.ts";
import { moduleSpecifier, runOutputPath } from "./lib/run-isolation.ts";
/**
* §5.4 / §17.2.2 step 2. Derives the build-time expected contract set from the
@@ -16,6 +17,7 @@ import { EXPECTED_CONTRACT_SET_PACKAGES } from "../src/features/installed-contra
* cannot influence the release digest.
*/
/** Under `RUN_OUTPUT_ROOT` when a run sets one (1105/12-04). */
const OUTPUT = ".generated/frontend-runtime/contract-set.ts";
function sha256(bytes: Uint8Array): Uint8Array {
@@ -38,11 +40,12 @@ export function buildContractSet(
async function main(): Promise<void> {
const contractSet = buildContractSet();
const output = runOutputPath(OUTPUT);
const source = [
"// Generated by scripts/generate-contract-set.ts. Do not edit.",
"// Regenerated from scratch on every build; never committed.",
"",
"import type { ContractSet } from \"../../src/contracts/contract-set.ts\";",
`import type { ContractSet } from "${moduleSpecifier(output, "src/contracts/contract-set.ts")}";`,
"",
`export const BUILD_CONTRACT_SET: ContractSet = ${JSON.stringify(
contractSet,
@@ -52,8 +55,8 @@ async function main(): Promise<void> {
"",
].join("\n");
await mkdir(dirname(OUTPUT), { recursive: true });
await writeFile(OUTPUT, source, "utf8");
await mkdir(dirname(output), { recursive: true });
await writeFile(output, source, "utf8");
process.stdout.write(
`contract set: ${contractSet.packages.length} package(s) ${contractSet.setDigest}\n`,
);
+24 -3
View File
@@ -1,5 +1,6 @@
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
import { dirname, relative, resolve } from "node:path";
import { randomUUID } from "node:crypto";
import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import { basename, dirname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { selectCompiledProductFeatures } from "../src/contracts/product-features.ts";
@@ -404,6 +405,26 @@ export async function generateAppIndexes(
);
}
/**
* 1105/12-04. Every build, dev server, type check and test run renders these
* files first, so two runs in one checkout render them at the same time while
* the other run's Vite or tsc reads them. `writeFile` truncated the file in
* place, and a reader could see it empty or half written. An index that has
* not changed is left alone; a changed one replaces the old file with one
* rename, so a reader sees the old file or the new one, never a part.
*/
export async function writeIndexIfChanged(file: string, content: string): Promise<void> {
if ((await readFile(file, "utf8").catch(() => null)) === content) return;
const temporary = join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`);
try {
await writeFile(temporary, content, { encoding: "utf8", flag: "wx" });
await rename(temporary, file);
} catch (error) {
await rm(temporary, { force: true });
throw error;
}
}
async function main(): Promise<void> {
const scriptDir = dirname(fileURLToPath(import.meta.url));
// `--root=` points the same production command at another checkout (used by
@@ -448,7 +469,7 @@ async function main(): Promise<void> {
await Promise.all(
(["feature", "context", "app"] as const).map((key) =>
writeFile(outputs[key], rendered[key], "utf8"),
writeIndexIfChanged(outputs[key], rendered[key]),
),
);
}
+5 -2
View File
@@ -9,6 +9,7 @@ import {
type DeploymentTarget,
} from "../src/contracts/deployment-admission.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.
@@ -24,6 +25,7 @@ import { runtimeConfigV2ArtifactSchema } from "../src/contracts/release-artifact
*/
const PROFILE_DIRECTORY = "config/runtime";
/** Under `RUN_OUTPUT_ROOT` when a run sets one (1105/12-04). */
const OUTPUT_PATH = "dist/config.json";
/**
@@ -98,9 +100,10 @@ function resolveTarget(environment: NodeJS.ProcessEnv): DeploymentTarget {
async function main(): Promise<void> {
const target = resolveTarget(process.env);
const config = await generateRuntimeConfig(target);
await writeFile(OUTPUT_PATH, `${JSON.stringify(config, null, 2)}\n`, "utf8");
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_PATH} ` +
`runtime config: ${target} profile written to ${output} ` +
`(APP_ENV=${String(config["APP_ENV"])}, AUTH_MODE=${String(config["AUTH_MODE"])})\n`,
);
}
+10 -5
View File
@@ -17,6 +17,7 @@ import {
SERVICE_WORKER_SCRIPT_PATH,
type StaticAssetManifestV1,
} from "../src/contracts/service-worker.ts";
import { moduleSpecifier, runOutputPath } from "./lib/run-isolation.ts";
/**
* §17.2.2 step 4. Scans the completed app `dist` and emits the exact hashed
@@ -27,7 +28,10 @@ import {
* the runtime config and release manifest, which are network-only (§18.4).
*/
/** Read back by tests/e2e/support/service-worker-builds.ts (0929/11-03). */
/**
* Read back by tests/e2e/support/service-worker-builds.ts (0929/11-03). A
* build with `RUN_OUTPUT_ROOT` writes it under that folder (1105/12-04).
*/
export const SERVICE_WORKER_ASSETS_OUTPUT =
".generated/frontend-runtime/service-worker-assets.ts";
@@ -144,7 +148,8 @@ async function walk(root: string, current: string): Promise<string[]> {
}
async function main(): Promise<void> {
const distDirectory = process.argv[2] ?? "dist";
const distDirectory = process.argv[2] ?? runOutputPath("dist");
const output = runOutputPath(SERVICE_WORKER_ASSETS_OUTPUT);
const buildId = process.env.VITE_BUILD_ID ?? "local-build";
const releaseId = process.env.RELEASE_ID ?? "local-release";
const manifest = await collectStaticAssets(
@@ -156,7 +161,7 @@ async function main(): Promise<void> {
const source = [
"// Generated by scripts/generate-service-worker-assets.ts. Do not edit.",
"",
'import type { StaticAssetManifestV1 } from "../../src/contracts/service-worker.ts";',
`import type { StaticAssetManifestV1 } from "${moduleSpecifier(output, "src/contracts/service-worker.ts")}";`,
"",
`export const SERVICE_WORKER_ASSETS: StaticAssetManifestV1 = ${JSON.stringify(
manifest,
@@ -165,8 +170,8 @@ async function main(): Promise<void> {
)} as const;`,
"",
].join("\n");
await mkdir(path.dirname(SERVICE_WORKER_ASSETS_OUTPUT), { recursive: true });
await writeFile(SERVICE_WORKER_ASSETS_OUTPUT, source, "utf8");
await mkdir(path.dirname(output), { recursive: true });
await writeFile(output, source, "utf8");
process.stdout.write(
`service worker assets: ${manifest.assets.length} file(s) ${manifest.setDigest}\n`,
);
+155
View File
@@ -0,0 +1,155 @@
import { createServer } from "node:net";
import path from "node:path";
/**
* 1105/12-04. Where one run writes, so that two runs in one checkout do not
* overwrite each other's build, results and reports.
*
* Two variables, read by different code:
*
* - `TEST_RUN_ID` names a Playwright run. The Playwright configs put its
* results, HTML report, JUnit file and the build its web server serves under
* `.tmp/runs/<id>/`, at the paths they have in the checkout:
* `artifacts/tests/e2e/results` becomes
* `.tmp/runs/<id>/artifacts/tests/e2e/results`, `dist` becomes
* `.tmp/runs/<id>/dist`. Unset, a run writes where it always did, which is
* where the gates, the CI upload and the evidence checks read.
* - `RUN_OUTPUT_ROOT` is what a Playwright config hands its web server. The
* build (`scripts/build-frontend.ts` and every step it runs) writes `dist/`,
* `.generated/frontend-runtime/` and its `artifacts/` evidence under it, and
* Vite keeps its cache there. Build code reads only this variable, never
* `TEST_RUN_ID`: a test that builds a copy of the repository inherits the
* runner's environment and must still build into the copy's own `dist`.
*
* Both roots are `.` or a folder under `.tmp/`. Git ignores `.tmp/`, and so do
* Tailwind's source scan (a Playwright report there would add classes to the
* CSS), Vite's file watcher, Vitest and the e2e helpers that copy the
* repository.
*
* Ports are separate from the run ID: every config serves on a free port
* unless its `TEST_*_PORT` variable pins one (`TEST_PORT_VARIABLES`), so two
* checkouts on one machine do not collide either.
*/
export const TEST_RUN_ID_VARIABLE = "TEST_RUN_ID";
export const RUN_OUTPUT_ROOT_VARIABLE = "RUN_OUTPUT_ROOT";
export const TEST_RUN_DIRECTORY = ".tmp/runs";
type Environment = Readonly<Record<string, string | undefined>>;
const RUN_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
/** `.` without a run ID, `.tmp/runs/<id>` with one. */
export function testRunRoot(environment: Environment = process.env): string {
const runId = environment[TEST_RUN_ID_VARIABLE];
if (runId === undefined || runId === "") return ".";
if (!RUN_ID.test(runId)) {
throw new TypeError(
`${TEST_RUN_ID_VARIABLE} must be 1 to 64 letters, digits, ".", "_" or "-", ` +
`starting with a letter or digit; received ${JSON.stringify(runId)}`,
);
}
return `${TEST_RUN_DIRECTORY}/${runId}`;
}
/** `relativePath` as this run writes it: unchanged without a run ID. */
export function testRunPath(
relativePath: string,
environment: Environment = process.env,
): string {
return path.posix.join(testRunRoot(environment), relativePath);
}
/** `.` when unset; otherwise a normalized folder under `.tmp/`. */
export function runOutputRoot(environment: Environment = process.env): string {
const declared = environment[RUN_OUTPUT_ROOT_VARIABLE];
if (declared === undefined || declared === "") return ".";
const root = path.posix.normalize(declared).replace(/\/+$/u, "");
if (root === ".") return ".";
if (declared.includes("\\") || !root.startsWith(".tmp/") || root.split("/").includes("..")) {
throw new TypeError(
`${RUN_OUTPUT_ROOT_VARIABLE} must be "." or a folder under .tmp/ in this checkout; ` +
`received ${JSON.stringify(declared)}`,
);
}
return root;
}
/** `relativePath` as the build writes it: unchanged without an output root. */
export function runOutputPath(
relativePath: string,
environment: Environment = process.env,
): string {
return path.posix.join(runOutputRoot(environment), relativePath);
}
/**
* The port variable of each Playwright config's web server. Unset, the config
* picks a free port; set, it uses that one (to pin a port while debugging).
*/
export const TEST_PORT_VARIABLES = Object.freeze({
e2e: "TEST_E2E_PORT",
visual: "TEST_VISUAL_PORT",
capabilities: "TEST_CAPABILITIES_PORT",
storybook: "TEST_STORYBOOK_PORT",
dev: "TEST_DEV_PORT",
} as const);
/**
* A port nothing listens on now: the one the kernel gives a socket bound to
* port 0, which is closed again. Another process can still take it before the
* web server binds it. The configs start their servers with `--strictPort`
* (vite) or a fixed `listen` (serve-static) and `reuseExistingServer: false`,
* so that case is a start failure, never a run against someone else's server.
*/
export async function findFreePort(host = "127.0.0.1"): Promise<number> {
return new Promise<number>((resolve, reject) => {
const server = createServer();
server.unref();
server.once("error", reject);
server.listen(0, host, () => {
const address = server.address();
server.close(() => {
if (address !== null && typeof address === "object") resolve(address.port);
else reject(new Error(`no port was bound on ${host}`));
});
});
});
}
/**
* The port one config's web server listens on, kept in `variable`.
*
* Playwright evaluates the config again in each worker process, and the
* workers inherit the runner's environment. The runner's evaluation writes
* the port it picked into `variable`; the workers' evaluations read it, so
* `baseURL` is the same everywhere. A value already set is used as given.
*/
export async function reservePort(
variable: string,
environment: Record<string, string | undefined> = process.env,
find: () => Promise<number> = findFreePort,
): Promise<number> {
const pinned = environment[variable];
if (pinned !== undefined && pinned !== "") {
const port = Number(pinned);
if (!/^\d+$/u.test(pinned) || port < 1 || port > 65_535) {
throw new TypeError(
`${variable} must be a port from 1 to 65535; received ${JSON.stringify(pinned)}`,
);
}
return port;
}
const port = await find();
environment[variable] = String(port);
return port;
}
/**
* The import specifier a generated module at `fromFile` uses for `toFile`,
* both relative to the checkout. A generated module under an output root sits
* deeper than `.generated/` and needs more `../`.
*/
export function moduleSpecifier(fromFile: string, toFile: string): string {
const specifier = path.posix.relative(path.posix.dirname(fromFile), toFile);
return specifier.startsWith(".") ? specifier : `./${specifier}`;
}
@@ -45,6 +45,7 @@ const BUILD_INPUTS = [
"vite.config.ts",
"tsconfig.base.json",
"tsconfig.app.json",
"scripts/lib/run-isolation.ts",
"scripts/lib/vite-module-inventory.ts",
] as const;
// Platform-owned names that only happen to contain "reference".