문제 - 93180f6(합친 커밋d3ddc89)이 초기 JS를 늘렸다. 기능 모양 측정 (scripts/scale/measure-feature-shape-growth.ts) 기준으로 기능 0개가 202,376 → 202,526 B(+150)로, 기능 1개 추가분이 960 → 1,029 B로 늘었다. tests/unit/feature-shape-growth.test.ts의 1 KiB 상한을 넘는다. - 원인은 두 가지다. - 부팅 때 도는 composeContractContributions가 검증기마다 생략 표시를 읽고 목록을 만들었다(feature-platform 청크 +164 B). 이 목록을 쓰는 곳은 플랫폼 개요 화면(lazy 라우트)뿐이다. - 공유 zod-validator.ts가 기능이 두 개가 되면 lazy 청크 하나로 따로 나왔다. 모든 context-routes·feature-runtime import의 preload 목록에 파일 이름이 하나 늘어 boot·feature-declarations 청크가 각각 약 25 B 커졌다. 고른 방법 - 목록 계산을 src/contracts/unvalidated-payload.ts의 listUnvalidatedPayloads(composed)로 옮긴다. 플랫폼 개요 화면만 이것을 import한다. 결정의 뜻(생략한 operation이 조립 결과에서 목록으로 나온다)은 그대로다. 계산 시점만 화면이 열릴 때로 미룬다. ComposedContractContributions.unvalidatedPayloads 필드는 뺀다. - unvalidatedPayload 팩토리도 같은 모듈로 옮긴다. - 조립기의 표시 검사도 뺀다. 이유가 빈 생략은 unvalidatedPayload가 만들 때 거부한다(TypeError). 손으로 붙인 표시는 값이 "NONE"이 아니거나 이유가 없어도 목록에 나온다(화면에는 "이유 없음"). 그래서 생략이 숨지 않는다. external-contract-runtime.ts에는 RuntimeValidator의 선택 타입 필드 2개만 남는다. - vite.config.ts에서 zod-validator.ts를 schema-registry.ts와 같은 lazy 청크로 묶는다. 어댑터를 import하는 곳은 이미 schema-registry 청크를 preload한다. includeDependenciesRecursively: false라서 다른 모듈은 끌려오지 않고, 두 모듈 모두 부팅 그래프 밖이다. 버린 대안 - 조립기에 "NONE + 이유" 검사만 남기기: feature-platform 청크 +57 B gzip. 검사를 팩토리와 목록으로 옮기면 0 B다. 손으로 붙인 잘못된 표시를 부팅 때 거부하지 못하지만, 목록에는 나온다. - zodValidator를 schema-registry.ts 안에 정의: 빌드 설정 없이 같은 결과가 나오지만 결정한 위치(src/contracts/zod-validator.ts)와 다르고, 다음 단계의 기능 생성 명령이 그 경로를 쓴다. - 어댑터를 zod.ts에 두기: zod 입구는 초기 청크라 기능 0개 초기 JS가 는다. 위험·한계 - 조립 결과 타입에서 unvalidatedPayloads 필드가 빠진다. 93180f6 뒤 이 필드를 쓴 코드는 listUnvalidatedPayloads로 바꿔야 한다. repo 안에서는 화면과 테스트만 썼다. - 손으로 만든 잘못된 표시(예: validation: "PARTIAL")는 더 이상 조립에서 거부되지 않는다. 목록에만 나온다. 테스트 2건을 이 동작으로 바꿨다. - 청크 묶음은 빌드 설정에 두 파일 경로를 적는다. 파일 이름을 바꾸면 정규식도 함께 바꿔야 한다. 놓치면 바이트만 늘고 동작은 같다. - 플랫폼 개요 화면을 열면 schema-registry 청크에 어댑터(351 B raw)가 같이 온다. 검증 - 기능 모양 측정(0개 / 1개 추가분, gzip B): - ee81c44(07-03 전): 202,376 / 960 - d3ddc89(07-03 합친 뒤): 202,526 / 1,029 - 목록만 부팅 밖으로: 202,407 / 1,035 - 청크 묶음 추가: 202,424 / 983 - 조립기 검사 제거(이 커밋): 202,371 / 958 - feature-shape-growth.test.ts 6건 통과. - 07-03 테스트 3파일 33건 통과(zod-validator, external-contract-runtime, starter-platform-overview-page). - 회귀: tests/unit·contract·component·runtime-schema·features·platform 270파일 3,203건, tests/integration 12파일 158건(pnpm을 띄우는 security-followup-archive 제외), tests/architecture 7파일 33건 통과. - tsc app·node·test·recipes·web-worker·service-worker 오류 0. 바꾼 파일 eslint 0. 아키텍처 그래프 검사(pnpm 대신 exec stub) 413 모듈 PASS. check-registries PASS(compatibility=none). - 본 빌드 초기 JS gzip 202,371 B(26파일). raw 644,782 B로ee81c44측정과 같다. Refs: docs/reviews/2026-11-01-maturity-review/07-contracts.md 07-03
209 lines
8.5 KiB
TypeScript
209 lines
8.5 KiB
TypeScript
import path from "node:path";
|
|
|
|
import { defineConfig, loadEnv } from "vite";
|
|
import react from "@vitejs/plugin-react";
|
|
import tailwindcss from "@tailwindcss/vite";
|
|
|
|
import { viteModuleInventoryPlugin } from "./scripts/lib/vite-module-inventory.ts";
|
|
import { ENV_REGISTRY } from "./src/contracts/env.ts";
|
|
|
|
/**
|
|
* 13-06. Every VITE_* value Vite loads (shell or `.env*`) is public once
|
|
* something bundles it, so a value the build does not declare is refused
|
|
* rather than carried along.
|
|
*/
|
|
function assertDeclaredBuildVariables(mode: string): void {
|
|
const undeclared = Object.keys(loadEnv(mode, process.cwd(), "VITE_"))
|
|
.filter((name) => !Object.hasOwn(ENV_REGISTRY, name))
|
|
.sort();
|
|
if (undeclared.length > 0) {
|
|
throw new Error(
|
|
`Undeclared VITE_* build variables: ${undeclared.join(", ")}. ` +
|
|
"Declare them in ENV_REGISTRY (src/contracts/env.ts) or unset them; " +
|
|
"VITE_ values are published to the browser.",
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* §6.1. One sub-path, declared once.
|
|
*
|
|
* `VITE_ROUTER_BASE_PATH` already drives the router and the Service Worker
|
|
* scope. Vite's asset `base` was left at its default, so a build served from
|
|
* `/app/` emitted root-absolute asset URLs and loaded nothing: the three
|
|
* consumers of the same setting disagreed. They are read from one value here so
|
|
* a sub-path deployment is coherent or fails at build time.
|
|
*/
|
|
function routerBasePath(environment: NodeJS.ProcessEnv): string {
|
|
const declared = environment["VITE_ROUTER_BASE_PATH"];
|
|
if (declared === undefined || declared === "") return "/";
|
|
if (!declared.startsWith("/") || !declared.endsWith("/")) {
|
|
throw new Error(
|
|
`VITE_ROUTER_BASE_PATH must start and end with "/"; received ${declared}`,
|
|
);
|
|
}
|
|
return declared;
|
|
}
|
|
|
|
/**
|
|
* 13-07. The runtime document ships inside dist, which is served under the
|
|
* base path. An explicit root-relative URL outside it would 404 at boot.
|
|
*/
|
|
function assertRuntimeConfigUnderBase(
|
|
environment: NodeJS.ProcessEnv,
|
|
base: string,
|
|
): void {
|
|
const declared = environment["VITE_RUNTIME_CONFIG_URL"];
|
|
if (declared?.startsWith("/") && !declared.startsWith(base)) {
|
|
throw new Error(
|
|
`VITE_RUNTIME_CONFIG_URL ${declared} is outside VITE_ROUTER_BASE_PATH ${base}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
type ModuleGraph = Readonly<{
|
|
getModuleInfo(id: string): Readonly<{
|
|
importedIds: readonly string[];
|
|
dynamicallyImportedIds: readonly string[];
|
|
}> | null;
|
|
}>;
|
|
|
|
function staticClosure(
|
|
graph: ModuleGraph,
|
|
roots: readonly string[],
|
|
within: (id: string) => boolean = () => true,
|
|
): Set<string> {
|
|
const reached = new Set<string>();
|
|
const pending = [...roots];
|
|
for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
|
|
if (reached.has(next) || !within(next)) continue;
|
|
reached.add(next);
|
|
pending.push(...(graph.getModuleInfo(next)?.importedIds ?? []));
|
|
}
|
|
return reached;
|
|
}
|
|
|
|
/**
|
|
* 15-01. Two chunk groups that keep moving the feature runtime halves out of
|
|
* the initial JavaScript from costing more than it saves.
|
|
*
|
|
* - `feature-declarations`: every installed feature's declaration, the static
|
|
* graph under src/features/ that the generated feature index reaches
|
|
* (feature-module.ts, its route contract and messages). A declaration is
|
|
* shared by the boot graph and its own feature's lazy runtime and pages,
|
|
* and rolldown otherwise gives each such set of importers a chunk of its
|
|
* own: one more initial file per feature, which doubled what a feature
|
|
* added to the initial JavaScript.
|
|
* - `feature-platform`: the boot modules the runtime halves also import (HTTP
|
|
* executor, contract runtime, zod). Left to rolldown they split into one
|
|
* initial chunk per set of importers; the per-file gzip overhead and the
|
|
* compression lost across files cost more than the runtime code removed.
|
|
* Modules that the boot-failure screen needs are left out, so
|
|
* render-boot-failure.tsx never depends on this chunk: it must still render
|
|
* when a module of the application graph throws while evaluating (09-03).
|
|
*
|
|
* Both only regroup modules the boot already loads; nothing lazy becomes
|
|
* initial. If feature-declarations comes out empty, the per-feature bound in
|
|
* tests/unit/feature-shape-growth.test.ts fails. feature-platform only moves
|
|
* the platform total (about 2 KB at 15-01), which the bundle budget
|
|
* (FE-GATE-012) checks.
|
|
*/
|
|
function createFeatureChunkGroups(root: string) {
|
|
const at = (file: string) => path.join(root, file);
|
|
const featuresRoot = `${at("src/features")}${path.sep}`;
|
|
let groups: ReadonlyMap<string, string> | undefined;
|
|
const classify = (graph: ModuleGraph): ReadonlyMap<string, string> => {
|
|
const index = graph.getModuleInfo(at("src/.generated/product-feature-index.ts"));
|
|
const declarations = staticClosure(graph, index?.importedIds ?? [], (id) =>
|
|
id.startsWith(featuresRoot),
|
|
);
|
|
const runtimes = staticClosure(
|
|
graph,
|
|
[...declarations].flatMap((id) => graph.getModuleInfo(id)?.dynamicallyImportedIds ?? []),
|
|
);
|
|
const boot = staticClosure(graph, [at("src/bootstrap/boot.tsx")]);
|
|
const bootFailure = staticClosure(graph, [at("src/bootstrap/render-boot-failure.tsx")]);
|
|
const result = new Map<string, string>();
|
|
for (const id of declarations) result.set(id, "feature-declarations");
|
|
for (const id of runtimes) {
|
|
if (boot.has(id) && !bootFailure.has(id) && !declarations.has(id)) {
|
|
result.set(id, "feature-platform");
|
|
}
|
|
}
|
|
return result;
|
|
};
|
|
return (id: string, graph: ModuleGraph): string | null => {
|
|
groups ??= classify(graph);
|
|
return groups.get(id) ?? null;
|
|
};
|
|
}
|
|
|
|
export default defineConfig(({ mode }) => {
|
|
assertDeclaredBuildVariables(mode);
|
|
const base = routerBasePath(process.env);
|
|
assertRuntimeConfigUnderBase(process.env, base);
|
|
return {
|
|
base,
|
|
plugins: [react(), tailwindcss(), viteModuleInventoryPlugin()],
|
|
build: {
|
|
manifest: true,
|
|
sourcemap: false,
|
|
rollupOptions: {
|
|
/**
|
|
* 1101/08-08. The design-system modules have no top-level effects:
|
|
* they declare components, icons and token lists. Declared so, a
|
|
* primitive file none of whose exports a chunk uses is dropped from
|
|
* it, instead of riding the initial chunk because the app shell
|
|
* imports the index that re-exports it. The bundler drops an import
|
|
* kept only for its effect along with its module, so these files hold
|
|
* no such import; tests/unit/design-system-initial-chunk.test.ts
|
|
* checks both. Stylesheets load from bootstrap/main.tsx.
|
|
*
|
|
* Trade: at 08-08 the initial JavaScript fell by 2,718 gzip bytes
|
|
* and the initial chunks rose from 16 to 25. The entry preloads them
|
|
* in parallel, so over HTTP/2 they add no round trip. Revisit when
|
|
* the app is served over HTTP/1.1, where every chunk costs a
|
|
* connection slot.
|
|
*/
|
|
treeshake: {
|
|
moduleSideEffects: [
|
|
{
|
|
test: /[\\/]src[\\/]presentation[\\/]design-system[\\/].+\.tsx?$/,
|
|
sideEffects: false,
|
|
},
|
|
],
|
|
},
|
|
output: {
|
|
codeSplitting: {
|
|
groups: [
|
|
// 09-03. The entry now imports the app dynamically, so Vite's
|
|
// preload helper would land in the entry chunk and every lazy
|
|
// chunk would import the entry, whose hash changes with each
|
|
// build id.
|
|
{ name: "preload-helper", test: /vite[\\/]preload-helper/ },
|
|
// 1101/07-03. Every feature's schemas and runtime half import
|
|
// the shared zod adapter. Alone it becomes a chunk of its own
|
|
// once two features share it, and every route and runtime
|
|
// import then preloads one more file (about 50 gzip bytes of
|
|
// initial JavaScript for the second feature). Those imports
|
|
// already preload schema-registry.ts, so the adapter rides
|
|
// that lazy chunk. Both modules stay off the boot graph.
|
|
{
|
|
name: "schema-registry",
|
|
test: /[\\/]src[\\/]contracts[\\/](?:schema-registry|zod-validator)\.ts$/,
|
|
includeDependenciesRecursively: false,
|
|
},
|
|
{
|
|
name: createFeatureChunkGroups(process.cwd()),
|
|
// The boot-failure screen's modules stay out of
|
|
// feature-platform even when a grouped module imports them.
|
|
includeDependenciesRecursively: false,
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
},
|
|
};
|
|
});
|