Files
clean-architecture-frontend…/tests/scripts/generate-product-feature-index.test.ts
T
DongHyeonka ca161878f2 feat(routes): 기능이 홈을 대신하고 context가 자기 레이아웃을 선언한다 (1101/09-03)
문제: 라우터는 모든 context gateway를 `AppShell` 하나 아래에 붙이고 플랫폼
`/`를 index로 둔다. 기능이 `APP_HOME`을 선언하면 `composeUniqueRecord`가
throw한다. 그래서 제품 홈이 기능 화면이거나 화면이 `AppShell`이 아닌 자기
셸을 쓰면 제품이 템플릿 라우터와 조립 카탈로그를 고쳐야 한다. memento는
카탈로그 브리지(`APP_HOME` 허용 목록)와 라우터 브리지(`ownsShell`)를 넣고
동기화마다 병합한다. tech-log는 라우터를 PUBLIC/STUDIO 그룹 라우터로 통째로
바꿔 생성기 설치 경로(context gateway)를 쓰지 못한다.

고른 방법: 리뷰 4.3의 (B). 선언 두 개를 연다.
- 홈 대체: 플랫폼이 기능이 대신할 수 있는 라우트 id를 선언한다
  (`FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS = ["APP_HOME"]`,
  src/contracts/routes.ts). 그 id를 선언한 기능의 정의가 플랫폼 정의를
  대신한다. 둘이 선언하면 카탈로그를 읽을 때 두 기능 id를 담아 throw한다
  (`withoutTakenOverPlatformRoutes`). 다른 플랫폼 id는 지금처럼 중복 오류다.
  라우터는 대체된 라우트를 소유 context와 함께 그 경로에 붙인다.
- context 레이아웃: `BoundedContextRouteModule.loadLayout`(선택). 생성기는
  `src/contexts/<context>/context-layout.tsx`가 있으면 그 `CONTEXT_LAYOUT`을
  지연 import로 싣는다. 라우터는 그 context를 `AppShell` 형제인 `/` 레이아웃
  라우트 아래, 기능의 등록 경로마다 붙인다. 그래서 모르는 URL은 여전히
  `AppShell`의 NOT_FOUND로 간다. 선언이 없으면 지금처럼 `AppShell` 아래 루트에
  붙는다. 레이아웃 청크 실패는 라우트 청크와 같은 reload-once 복구를 받는다.
- 09-06 불변식을 레이아웃으로 넓힌다. 레이아웃 라우트는 모두 `/`의
  형제라서 루트는 레이아웃과 상관없이 그 아래 URL을 가진다. 그래서 기존
  루트 검사가 모든 레이아웃에 걸친다. 한 레이아웃 아래 루트 여럿(같은
  컴포넌트를 싣는 context들)은 허용한다. 대체된 플랫폼 라우트는 라우터가
  경로에 직접 붙이므로 루트 검사에서 뺀다(09-06 재검토 조건).
- tests/unit/product-features.test.ts의 "플랫폼 라우트는 소유자가 없다"
  검사가 대체 가능한 id는 건너뛴다. memento가 고쳤던 템플릿 테스트다.
- `ContextRouteModule`에 `featureIds`가 생겨서, `TEMPLATE_APP_MODULE`을
  손으로 mock하며 필수 필드 `features`를 빼먹은 두 테스트
  (context-route-gateway, context-boundary-diagnostics)에 `features: []`를
  넣었다.

버린 대안:
- (A) 현 상태: 제품마다 브리지를 넣고 동기화마다 병합한다.
- (C) `AppShell` 통째 교체: 레이아웃 그룹이 둘인 tech-log를 담지 못한다.
- 같은 레이아웃을 쓰는 context를 로더 함수로 묶어 레이아웃 라우트 하나에
  모으기: 만들었다가 지웠다. React 19는 같은 컴포넌트로 풀린 lazy 타입을 같은
  타입으로 맞춰 레이아웃 인스턴스를 그대로 둔다. 묶지 않은 변이로 테스트가
  그대로 통과해서 쓸모없는 코드였다.
- `CONTEXT_LAYOUT_ID` 리터럴로 다른 context의 레이아웃을 가리키기: 같은
  컴포넌트를 내보내는 파일 두 개로 같은 결과가 나와 선언을 하나 덜 둔다.
- 레이아웃 라우트를 `AppShell`보다 앞에 두기(memento 브리지 순서): 경로가
  같으면 기능이 플랫폼 라우트를 조용히 가린다. `AppShell`을 앞에 두어
  지금처럼 플랫폼이 이긴다.

위험·한계:
- 레이아웃이 skip link와 `<main id="main-content">` 하나를 그리는 것은
  계약(타입 주석, starter-experience.md)과 테스트 fixture로만 지킨다. 실행 중
  검사는 없다. 레이아웃 로딩·실패 화면에는 `<main>`이 없다(`AppShell`의
  errorElement와 같다).
- 레이아웃 렌더 결함(청크 실패가 아닌 것)은 라우트 errorElement로 가고
  진단을 남기지 않는다. `AppShell` 렌더 결함과 같다.
- 홈을 대신한 기능을 실행 중에 끄면 `/`는 비활성 기능 화면이 된다. 빌드에서
  빼면(`VITE_PRODUCT_FEATURES`) 플랫폼 홈이 돌아온다.
- tech-log의 PUBLIC 셸 안 NOT_FOUND는 표현하지 않는다. 모르는 URL은
  `AppShell`의 NOT_FOUND다. STUDIO의 `/studio/*` 라우트는 STUDIO 레이아웃
  아래에서 동작한다. tech-log는 기능 하나를 레이아웃 그룹별 기능 둘(context
  둘)로 나눠야 한다.
- 플랫폼 라우트와 기능 라우트의 같은 경로는 여전히 검사하지 않는다(7139c7c
  한계). 루트 `*` context에서 `APP_HOME`이 아닌 id로 `/`를 선언하면 플랫폼
  홈에 가려진다.
- 초기 JS gzip +349 B(204,586 -> 204,935 B). 예산 204,800 B를 135 B
  넘는다(이전 여유 214 B). boot 청크 +228(라우터·앱 모듈),
  installed-feature-contracts 청크 +121. 같은 worktree에서 HEAD 파일로
  `vite build`를 한 번 더 해서 청크별로 비교했다. 예산은 고치지 않았다.

검증:
- RED: tests/component/context-layouts.test.tsx는 파일 적재에서
  "Duplicate route registry key: APP_HOME"으로 실패.
  tests/architecture/context-route-roots.test.ts 15건 중 3건 실패(APP_HOME
  루트 예외 "not under the route root", 대체 함수가 없어 2건).
  tests/scripts/generate-product-feature-index.test.ts 새 1건이 HEAD 생성기로
  "expected ... to contain 'loadLayout: async () => (await import…'"로 실패.
- GREEN: 세 파일 37건 통과(생성기 15, 루트 16, context-layouts 6).
- 변이: 라우터가 `loadLayout`을 무시하면 context-layouts 6건 중 5건 실패.
  topics 레이아웃을 다른 컴포넌트로 바꾸면 "keeps one layout instance" 실패.
- 회귀: tests/{architecture,unit,features,platform,component,contract,
  runtime-schema,integration,scripts,scale}(pnpm을 띄우는 4개 제외)
  300 files, 3,451건 통과. check-registries, check-adapter-inventory,
  verify-documentation-readiness(PASS_SCOPED) 통과.
- tsc app·test·node 통과. 바꾼 파일 eslint 통과. 생성기 --check 통과.
- check:architecture는 pnpm이 필요해 돌리지 않았다.

Refs: docs/reviews/2026-11-01-maturity-review/09-app-core.md 09-03, 4.3
2026-11-03 01:52:18 +09:00

273 lines
11 KiB
TypeScript

import { rm } from "node:fs/promises";
import { afterEach, describe, expect, it } from "vitest";
import {
generateAppIndexes,
renderContextIndex,
renderFeatureIndex,
selectAppIndexes,
type TopologyDeclarationSource,
} from "../../scripts/generate-product-feature-index.ts";
describe("feature index generator", () => {
it("is deterministic by normalized id", () => {
const first = renderFeatureIndex([
{ id: "zeta", importPath: "../features/zeta/feature-module.ts" },
{ id: "alpha", importPath: "../features/alpha/feature-module.ts" },
]);
const second = renderFeatureIndex([
{ id: "alpha", importPath: "../features/alpha/feature-module.ts" },
{ id: "zeta", importPath: "../features/zeta/feature-module.ts" },
]);
expect(first).toBe(second);
expect(first.indexOf("alpha")).toBeLessThan(first.indexOf("zeta"));
});
it("emits a base feature module fallback for an empty product", () => {
const rendered = renderFeatureIndex([]);
expect(rendered).toContain(
'import type { FeatureModule } from "../features/feature-module.ts";',
);
expect(rendered).toContain("type GeneratedProductFeatureModule =");
expect(rendered).toContain(
"[GeneratedProductFeatureModule] extends [never]",
);
expect(rendered).toContain("? FeatureModule");
});
it("groups feature route executables behind one lazy context loader", () => {
const rendered = renderContextIndex([
{
id: "catalog-search",
importPath: "../features/catalog-search/feature-module.ts",
directory: "catalog-search",
contextId: "catalog",
contextRoutePath: "catalog/*",
contextMaxFeatures: 200,
},
{
id: "catalog-detail",
importPath: "../features/catalog-detail/feature-module.ts",
directory: "catalog-detail",
contextId: "catalog",
contextRoutePath: "catalog/*",
contextMaxFeatures: 200,
},
]);
expect(rendered.match(/defineBoundedContextModule\(\{/gu)).toHaveLength(1);
expect(rendered).toContain(
'import("../features/catalog-search/context-routes.ts")',
);
expect(rendered).toContain(
'import("../features/catalog-detail/context-routes.ts")',
);
expect(rendered).not.toContain(
'from "../features/catalog-search/context-routes.ts"',
);
expect(rendered).not.toContain(
'from "../features/catalog-detail/context-routes.ts"',
);
});
it("emits no context loader for an empty product", () => {
expect(renderContextIndex([])).toBe(
"// Generated by scripts/generate-product-feature-index.ts. Do not edit by hand.\n" +
"export const PRODUCT_CONTEXT_MODULES = Object.freeze([] as const);\n",
);
});
});
describe("app-scoped selection from ownership declarations", () => {
// 00-03. The fake repositories used to stay in /tmp.
const temporaryRoots: string[] = [];
afterEach(async () => {
await Promise.all(
temporaryRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
async function repo(files: Record<string, string>) {
const { mkdtemp, mkdir, writeFile } = await import("node:fs/promises");
const { tmpdir } = await import("node:os");
const path = await import("node:path");
const root = await mkdtemp(path.join(tmpdir(), "generator-"));
temporaryRoots.push(root);
for (const [file, content] of Object.entries(files)) {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await writeFile(path.join(root, file), content);
}
return root;
}
const app = (id: string, max = 20) =>
`export const APP_MODULE_ID = "${id}";\nexport const APP_MAX_CONTEXTS = ${max};\n`;
const context = (id: string, appId: string, max = 200) =>
`export const CONTEXT_MODULE_ID = "${id}";\nexport const CONTEXT_APP_ID = "${appId}";\n` +
`export const CONTEXT_ROUTE_PATH = "${id}/*";\nexport const CONTEXT_MAX_FEATURES = ${max};\n`;
const feature = (id: string, contextId: string) =>
`export const FEATURE_MODULE_ID = "${id}";\nexport const FEATURE_CONTEXT_ID = "${contextId}";\n`;
it("rejects a feature owned by an undeclared context", async () => {
const root = await repo({
"src/apps/a/app-module.ts": app("a"),
"src/features/f/feature-module.ts": feature("f", "missing"),
});
await expect(generateAppIndexes(root, "a")).rejects.toThrow(/undeclared context missing/);
});
it("rejects a context owned by an undeclared app", async () => {
const root = await repo({
"src/apps/a/app-module.ts": app("a"),
"src/contexts/c/context-module.ts": context("c", "ghost"),
});
await expect(generateAppIndexes(root, "a")).rejects.toThrow(/undeclared app ghost/);
});
it("enforces the context feature budget and the app context budget", async () => {
const overFeatures = await repo({
"src/apps/a/app-module.ts": app("a"),
"src/contexts/c/context-module.ts": context("c", "a", 1),
"src/features/f1/feature-module.ts": feature("f1", "c"),
"src/features/f2/feature-module.ts": feature("f2", "c"),
});
await expect(generateAppIndexes(overFeatures, "a")).rejects.toThrow(/c feature cardinality 2 exceeds budget 1/);
const overContexts = await repo({
"src/apps/a/app-module.ts": app("a", 1),
"src/contexts/c1/context-module.ts": context("c1", "a"),
"src/contexts/c2/context-module.ts": context("c2", "a"),
"src/features/f1/feature-module.ts": feature("f1", "c1"),
"src/features/f2/feature-module.ts": feature("f2", "c2"),
});
await expect(generateAppIndexes(overContexts, "a")).rejects.toThrow(/App a context cardinality 2 exceeds budget 1/);
});
it("refuses a feature directory without a declaration or NOT_INSTALLED marker (09-07)", async () => {
const files = {
"src/apps/a/app-module.ts": app("a"),
"src/contexts/c/context-module.ts": context("c", "a"),
"src/features/f/feature-module.ts": feature("f", "c"),
// A misspelt declaration file used to drop the feature without a word.
"src/features/typo/feature-modul.ts": feature("typo", "c"),
};
await expect(generateAppIndexes(await repo(files), "a")).rejects.toThrow(
/src\/features\/typo has no feature-module\.ts/u,
);
const marked = await repo({
...files,
"src/features/typo/NOT_INSTALLED": "Composed only by tests.\n",
});
const selected = await generateAppIndexes(marked, "a");
expect(selected.entries.map((entry) => entry.id)).toEqual(["f"]);
});
it("skips contexts without features and never imports another app's features", async () => {
const root = await repo({
"src/apps/a/app-module.ts": app("a"),
"src/apps/b/app-module.ts": app("b"),
"src/contexts/empty/context-module.ts": context("empty", "a"),
"src/contexts/ca/context-module.ts": context("ca", "a"),
"src/contexts/cb/context-module.ts": context("cb", "b"),
"src/features/fa/feature-module.ts": feature("fa", "ca"),
"src/features/fb/feature-module.ts": feature("fb", "cb"),
});
const selected = await generateAppIndexes(root, "a");
expect(selected.entries.map((entry) => entry.id)).toEqual(["fa"]);
expect(selected.contextIndex).not.toContain("empty");
expect(selected.featureIndex).not.toContain("features/fb/");
expect(selected.appIndex).toContain('id: "a"');
});
it("loads a context's own layout lazily when it has a context-layout.tsx (09-03)", async () => {
const layout = "export const CONTEXT_LAYOUT = () => null;\n";
const selected = await generateAppIndexes(
await repo({
"src/apps/a/app-module.ts": app("a"),
"src/contexts/site-dir/context-module.ts": context("site", "a"),
"src/contexts/site-dir/context-layout.tsx": layout,
"src/contexts/topics/context-module.ts": context("topics", "a"),
"src/contexts/topics/context-layout.tsx": layout,
"src/contexts/shop/context-module.ts": context("shop", "a"),
"src/features/fs/feature-module.ts": feature("fs", "site"),
"src/features/ft/feature-module.ts": feature("ft", "topics"),
"src/features/fp/feature-module.ts": feature("fp", "shop"),
}),
"a",
);
const index = selected.contextIndex;
expect(index).toContain(
'loadLayout: async () => (await import("../contexts/site-dir/context-layout.tsx")).CONTEXT_LAYOUT,',
);
expect(index).toContain('import("../contexts/topics/context-layout.tsx")');
expect(index).not.toMatch(/from "\.\.\/contexts\/[^"]+\/context-layout\.tsx"/u);
// The shop context has none and stays under AppShell.
expect(index.match(/loadLayout:/gu)).toHaveLength(2);
});
});
describe("build-time product selection (09-02)", () => {
const source: TopologyDeclarationSource = Object.freeze({
appIds: () => ["a"],
app: (appId: string) =>
appId === "a" ? Object.freeze({ id: "a", maxContexts: 20 }) : undefined,
contextsOf: () => [
Object.freeze({ id: "c", appId: "a", routePath: "c/*", maxFeatures: 200 }),
],
featuresOf: () => [
Object.freeze({ id: "f1", contextId: "c", directory: "f1" }),
Object.freeze({ id: "f2", contextId: "c", directory: "f2" }),
],
});
const declared =
'DECLARED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze(["f1", "f2"])';
it("keeps every declared feature when nothing is selected", () => {
for (const selection of [undefined, "", " "]) {
const selected = selectAppIndexes(source, "a", selection);
expect(selected.entries.map((entry) => entry.id)).toEqual(["f1", "f2"]);
expect(selected.featureIndex).toBe(selectAppIndexes(source, "a").featureIndex);
expect(selected.featureIndex).toContain(declared);
}
});
it("imports only the selected features and still declares the rest", () => {
const selected = selectAppIndexes(source, "a", "f2");
expect(selected.entries.map((entry) => entry.id)).toEqual(["f2"]);
expect(selected.featureIndex).not.toContain("features/f1/");
expect(selected.contextIndex).not.toContain("features/f1/");
expect(selected.contextIndex).toContain("features/f2/context-routes.ts");
expect(selected.featureIndex).toContain(declared);
});
it("imports nothing for an explicit none", () => {
const selected = selectAppIndexes(source, "a", "none");
expect(selected.entries).toEqual([]);
expect(selected.featureIndex).not.toMatch(/features\/f[12]\//u);
expect(selected.contextIndex).toBe(renderContextIndex([]));
expect(selected.featureIndex).toContain(declared);
});
it("fails generation on an id the app does not declare", () => {
expect(() => selectAppIndexes(source, "a", "f1,f3")).toThrow(
/VITE_PRODUCT_FEATURES names features this build does not contain: f3/u,
);
});
it("fails the generator command, the first build step, on a misspelt id", async () => {
const { spawnSync } = await import("node:child_process");
const run = spawnSync(
process.execPath,
["scripts/generate-product-feature-index.ts", "--check"],
{
encoding: "utf8",
env: { ...process.env, VITE_PRODUCT_FEATURES: "reference-featrue" },
},
);
expect(run.status).not.toBe(0);
expect(run.stderr).toMatch(/does not contain: reference-featrue/u);
});
});