Files
clean-architecture-frontend…/tests/scripts/generate-product-feature-index.test.ts
DongHyeonka 9edc8307b0 fix(features)!: 기능이 아닌 폴더 표시를 NOT_A_FEATURE로 바꾸고 선언과 함께 두면 실패한다 (1103/09-09)
문제
src/features/<dir>/NOT_INSTALLED 표시는 "기능이 아닌 샘플 폴더"라는 뜻인데,
같은 단어가 런타임 상태 "선언됐지만 빌드·FEATURE_OVERRIDES가 뺀 기능"으로도
쓰였다(product-features.ts). 생성기는 feature-module.ts를 못 읽을 때만 표시를
찾았으므로, 샘플을 졸업시키며 표시를 지우지 않으면 표시가 "설치 안 됨"이라고
말하는 채로 조용히 설치됐다.

고른 방법
- 표시 이름을 NOT_A_FEATURE로 바꾼다(local-draft-feature 파일 이름 변경).
  런타임 상태 NOT_INSTALLED는 그대로 둔다.
- 생성기가 표시와 feature-module.ts가 함께 있으면 둘 중 무엇을 지울지 적고
  실패한다.
- 옛 이름 표시는 받지 않는다. 받으면 같은 다의가 남는다. 옛 표시만 있는
  폴더는 "has no feature-module.ts; … mark the directory with NOT_A_FEATURE"로
  실패해 새 이름을 알려 준다.
README 상태 표, starter-experience, 매뉴얼 errors·patterns 표를 맞췄다.

위험·한계
다운스트림이 자기 폴더에 NOT_INSTALLED 표시를 두었다면 생성 단계가 실패한다.
파일 이름만 바꾸면 된다.

검증
- RED: 생성기 테스트 3건(새 이름 허용, 옛 이름 거절, 동시 존재 거절)이
  수정 전 실패.
- generate-product-feature-index.test.ts 17건 통과. generate:feature-index
  통과. verify:documentation PASS_SCOPED. eslint, tsc(node·test) 통과.

BREAKING CHANGE: src/features/<dir>/NOT_INSTALLED 표시 파일은 더 이상
인식되지 않는다. 같은 자리에 NOT_A_FEATURE라는 이름으로 옮긴다.

Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-09
2026-11-04 20:19:17 +09:00

300 lines
12 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_A_FEATURE 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_A_FEATURE": "Composed only by tests.\n",
});
const selected = await generateAppIndexes(marked, "a");
expect(selected.entries.map((entry) => entry.id)).toEqual(["f"]);
});
it("no longer accepts the old NOT_INSTALLED marker name (1103/09-09)", async () => {
// The word is the runtime state "declared but not selected"; a marker
// under that name is read as a missing declaration, naming the new one.
const root = await repo({
"src/apps/a/app-module.ts": app("a"),
"src/contexts/c/context-module.ts": context("c", "a"),
"src/features/sample/NOT_INSTALLED": "Composed only by tests.\n",
});
await expect(generateAppIndexes(root, "a")).rejects.toThrow(
/src\/features\/sample has no feature-module\.ts; add one or mark the directory with NOT_A_FEATURE/u,
);
});
it("refuses a marked directory that also declares a feature (1103/09-09)", async () => {
// Graduating a sample means deleting the marker; keeping both used to
// install the feature silently while the marker said it was none.
const root = await repo({
"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"),
"src/features/f/NOT_A_FEATURE": "Composed only by tests.\n",
});
await expect(generateAppIndexes(root, "a")).rejects.toThrow(
/src\/features\/f has both feature-module\.ts and NOT_A_FEATURE; delete NOT_A_FEATURE to install it, or feature-module\.ts to keep it out/u,
);
});
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);
});
});