문제: 라우터는 모든 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
443 lines
18 KiB
TypeScript
443 lines
18 KiB
TypeScript
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
|
|
import { dirname, relative, resolve } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
import { selectCompiledProductFeatures } from "../src/contracts/product-features.ts";
|
|
|
|
export type FeatureImportEntry = Readonly<{
|
|
id: string;
|
|
importPath: string;
|
|
}>;
|
|
|
|
export type FeatureIndexEntry = FeatureImportEntry & Readonly<{
|
|
directory: string;
|
|
contextId: string;
|
|
contextRoutePath: string;
|
|
contextMaxFeatures: number;
|
|
/** 09-03. Present when the context has a `context-layout.tsx`. */
|
|
contextLayoutImportPath?: string;
|
|
}>;
|
|
|
|
/**
|
|
* `declaredIds` is every feature the app declares, selected or not, so a build
|
|
* that left one out still reports it as `NOT_INSTALLED` without importing it.
|
|
*/
|
|
export function renderFeatureIndex(
|
|
entries: readonly FeatureImportEntry[],
|
|
declaredIds: readonly string[] = entries.map((entry) => entry.id),
|
|
): string {
|
|
const sorted = [...entries].sort((left, right) => left.id.localeCompare(right.id));
|
|
const declared = [...declaredIds]
|
|
.sort((left, right) => left.localeCompare(right))
|
|
.map((id) => JSON.stringify(id))
|
|
.join(", ");
|
|
const imports = sorted
|
|
.map(
|
|
(entry, index) =>
|
|
`import { FEATURE_MODULE as featureModule${index} } from ${JSON.stringify(entry.importPath)};`,
|
|
)
|
|
.join("\n");
|
|
const modules = sorted.map((_, index) => ` featureModule${index},`).join("\n");
|
|
const featureImports = imports.length > 0 ? `${imports}\n` : "";
|
|
return `// Generated by scripts/generate-product-feature-index.ts. Do not edit by hand.\nimport type { FeatureModule } from "../features/feature-module.ts";\n${featureImports}\nexport const DECLARED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze([${declared}]);\n\nexport const PRODUCT_FEATURE_MODULES = Object.freeze([\n${modules}\n] as const);\n\ntype GeneratedProductFeatureModule = (typeof PRODUCT_FEATURE_MODULES)[number];\nexport type ProductFeatureModule =\n [GeneratedProductFeatureModule] extends [never]\n ? FeatureModule\n : GeneratedProductFeatureModule;\n`;
|
|
}
|
|
|
|
export function renderContextIndex(entries: readonly FeatureIndexEntry[]): string {
|
|
if (entries.length === 0) {
|
|
return `// Generated by scripts/generate-product-feature-index.ts. Do not edit by hand.\nexport const PRODUCT_CONTEXT_MODULES = Object.freeze([] as const);\n`;
|
|
}
|
|
const sorted = [...entries].sort((left, right) => left.id.localeCompare(right.id));
|
|
const imports = sorted
|
|
.map(
|
|
(entry, index) =>
|
|
`import { FEATURE_MODULE as featureModule${index} } from ${JSON.stringify(entry.importPath)};`,
|
|
)
|
|
.join("\n");
|
|
const indexById = new Map(sorted.map((entry, index) => [entry.id, index] as const));
|
|
const grouped = new Map<string, FeatureIndexEntry[]>();
|
|
for (const entry of sorted) {
|
|
const group = grouped.get(entry.contextId) ?? [];
|
|
group.push(entry);
|
|
grouped.set(entry.contextId, group);
|
|
}
|
|
|
|
const contexts = [...grouped.entries()]
|
|
.sort(([left], [right]) => left.localeCompare(right))
|
|
.map(([contextId, features]) => {
|
|
const first = features[0];
|
|
if (!first) throw new Error(`Context ${contextId} has no features`);
|
|
for (const feature of features) {
|
|
if (feature.contextRoutePath !== first.contextRoutePath) {
|
|
throw new Error(
|
|
`Context ${contextId} has conflicting route paths: ${first.contextRoutePath}, ${feature.contextRoutePath}`,
|
|
);
|
|
}
|
|
if (feature.contextMaxFeatures !== first.contextMaxFeatures) {
|
|
throw new Error(
|
|
`Context ${contextId} has conflicting maxFeatures budgets: ${first.contextMaxFeatures}, ${feature.contextMaxFeatures}`,
|
|
);
|
|
}
|
|
}
|
|
if (features.length > first.contextMaxFeatures) {
|
|
throw new Error(
|
|
`Context ${contextId} feature cardinality ${features.length} exceeds budget ${first.contextMaxFeatures}`,
|
|
);
|
|
}
|
|
const featureRefs = features
|
|
.map((feature) => `featureModule${indexById.get(feature.id)}`)
|
|
.join(", ");
|
|
const routeImports = features
|
|
.map(
|
|
(feature, index) =>
|
|
` import(${JSON.stringify(`../features/${feature.directory}/context-routes.ts`)})${index < features.length - 1 ? "," : ""}`,
|
|
)
|
|
.join("\n");
|
|
const routeSpreads = features
|
|
.map((_, index) => ` ...routeModule${index}.FEATURE_CONTEXT_ROUTES,`)
|
|
.join("\n");
|
|
const routeBindings = features
|
|
.map((_, index) => `routeModule${index}`)
|
|
.join(", ");
|
|
const layout = first.contextLayoutImportPath
|
|
? ` loadLayout: async () => (await import(${JSON.stringify(first.contextLayoutImportPath)})).CONTEXT_LAYOUT,\n`
|
|
: "";
|
|
return ` defineBoundedContextModule({\n id: ${JSON.stringify(contextId)},\n features: Object.freeze([${featureRefs}]),\n budget: Object.freeze({ maxFeatures: ${first.contextMaxFeatures} }),\n route: Object.freeze({\n path: ${JSON.stringify(first.contextRoutePath)},\n${layout} async loadRoutes() {\n const [${routeBindings}] = await Promise.all([\n${routeImports}\n ]);\n return Object.freeze([\n${routeSpreads}\n ]);\n },\n }),\n }),`;
|
|
})
|
|
.join("\n");
|
|
|
|
const featureImports = imports.length > 0 ? `${imports}\n` : "";
|
|
return `// Generated by scripts/generate-product-feature-index.ts. Do not edit by hand.\nimport { defineBoundedContextModule } from "../contexts/bounded-context-module.ts";\n${featureImports}\nexport const PRODUCT_CONTEXT_MODULES = Object.freeze([\n${contexts}\n] as const);\n`;
|
|
}
|
|
|
|
/**
|
|
* Ownership declarations the generator reads, documented in
|
|
* docs/architecture/starter-experience.md ("Ownership declarations"). Each boundary
|
|
* declares only its parent:
|
|
*
|
|
* src/apps/<app>/app-module.ts APP_MODULE_ID, APP_MAX_CONTEXTS
|
|
* src/contexts/<context>/context-module.ts CONTEXT_MODULE_ID, CONTEXT_APP_ID,
|
|
* CONTEXT_ROUTE_PATH, CONTEXT_MAX_FEATURES
|
|
* src/contexts/<context>/context-layout.tsx CONTEXT_LAYOUT (optional, 09-03:
|
|
* the context's own layout)
|
|
* src/features/<feature>/feature-module.ts FEATURE_MODULE_ID, FEATURE_CONTEXT_ID
|
|
*
|
|
* The generated indexes describe exactly one deployable app: the contexts it
|
|
* owns and the features those contexts own. Features of other apps are never
|
|
* imported, so global growth elsewhere cannot enter this app's compile or
|
|
* boot graph.
|
|
*/
|
|
export type AppDeclaration = Readonly<{ id: string; maxContexts: number }>;
|
|
export type ContextDeclaration = Readonly<{
|
|
id: string;
|
|
appId: string;
|
|
routePath: string;
|
|
maxFeatures: number;
|
|
layoutImportPath?: string;
|
|
}>;
|
|
export type FeatureDeclaration = Readonly<{
|
|
id: string;
|
|
contextId: string;
|
|
directory: string;
|
|
}>;
|
|
|
|
/**
|
|
* Ownership-indexed view of the declarations. The generator only asks for one
|
|
* app, that app's contexts and those contexts' features, so its work and its
|
|
* output are local to the selected app.
|
|
*/
|
|
export interface TopologyDeclarationSource {
|
|
appIds(): readonly string[];
|
|
app(appId: string): AppDeclaration | undefined;
|
|
contextsOf(appId: string): readonly ContextDeclaration[];
|
|
featuresOf(contextId: string): readonly FeatureDeclaration[];
|
|
}
|
|
|
|
export type SelectedAppIndexes = Readonly<{
|
|
app: AppDeclaration;
|
|
entries: readonly FeatureIndexEntry[];
|
|
featureIndex: string;
|
|
contextIndex: string;
|
|
appIndex: string;
|
|
}>;
|
|
|
|
export function renderAppIndex(app: AppDeclaration): string {
|
|
return `// Generated by scripts/generate-product-feature-index.ts. Do not edit by hand.
|
|
export const PRODUCT_APP = Object.freeze({
|
|
id: ${JSON.stringify(app.id)},
|
|
maxContexts: ${app.maxContexts},
|
|
} as const);
|
|
`;
|
|
}
|
|
|
|
export function resolveSelectedApp(
|
|
source: TopologyDeclarationSource,
|
|
requested: string | undefined,
|
|
): string {
|
|
if (requested) {
|
|
if (!source.app(requested)) throw new Error(`Unknown deployable app: ${requested}`);
|
|
return requested;
|
|
}
|
|
const ids = source.appIds();
|
|
if (ids.length !== 1) {
|
|
throw new Error(
|
|
`Select a deployable app with --app=<id> or PRODUCT_APP_ID (declared: ${ids.join(", ") || "none"})`,
|
|
);
|
|
}
|
|
return ids[0] as string;
|
|
}
|
|
|
|
/**
|
|
* The production selection: one app -> its direct contexts -> their features,
|
|
* narrowed by `VITE_PRODUCT_FEATURES` (09-02, D-9). The narrowing happens here
|
|
* so the bundle, the Node build scripts and the context router all import the
|
|
* same set, and a misspelt id fails the first build step.
|
|
*/
|
|
export function selectAppIndexes(
|
|
source: TopologyDeclarationSource,
|
|
appId: string,
|
|
productFeatures?: string,
|
|
): SelectedAppIndexes {
|
|
const app = source.app(appId);
|
|
if (!app) throw new Error(`Unknown deployable app: ${appId}`);
|
|
const contexts = [...source.contextsOf(appId)].sort((left, right) =>
|
|
left.id.localeCompare(right.id),
|
|
);
|
|
const entries: FeatureIndexEntry[] = [];
|
|
let populatedContexts = 0;
|
|
for (const context of contexts) {
|
|
const features = source.featuresOf(context.id);
|
|
if (features.length === 0) continue;
|
|
populatedContexts += 1;
|
|
if (features.length > context.maxFeatures) {
|
|
throw new Error(
|
|
`Context ${context.id} feature cardinality ${features.length} exceeds budget ${context.maxFeatures}`,
|
|
);
|
|
}
|
|
for (const feature of features) {
|
|
entries.push({
|
|
id: feature.id,
|
|
importPath: `../features/${feature.directory}/feature-module.ts`,
|
|
directory: feature.directory,
|
|
contextId: context.id,
|
|
contextRoutePath: context.routePath,
|
|
contextMaxFeatures: context.maxFeatures,
|
|
...(context.layoutImportPath
|
|
? { contextLayoutImportPath: context.layoutImportPath }
|
|
: {}),
|
|
});
|
|
}
|
|
}
|
|
if (populatedContexts > app.maxContexts) {
|
|
throw new Error(
|
|
`App ${app.id} context cardinality ${populatedContexts} exceeds budget ${app.maxContexts}`,
|
|
);
|
|
}
|
|
const ids = entries.map((entry) => entry.id);
|
|
if (new Set(ids).size !== ids.length) {
|
|
throw new Error(`Duplicate generated feature ids: ${ids.join(", ")}`);
|
|
}
|
|
const selected = selectCompiledProductFeatures(
|
|
entries.map((entry) => Object.freeze({ featureId: entry.id, entry })),
|
|
productFeatures,
|
|
).map(({ entry }) => entry);
|
|
return Object.freeze({
|
|
app,
|
|
entries: Object.freeze(selected),
|
|
featureIndex: renderFeatureIndex(selected, ids),
|
|
contextIndex: renderContextIndex(selected),
|
|
appIndex: renderAppIndex(app),
|
|
});
|
|
}
|
|
|
|
function requiredLiteral(source: string, name: string, file: string): string {
|
|
const match = source.match(
|
|
new RegExp(`export\\s+const\\s+${name}\\s*=\\s*["']([^"']+)["']`),
|
|
);
|
|
if (!match?.[1]) {
|
|
throw new Error(`${file} must export a literal ${name}`);
|
|
}
|
|
return match[1];
|
|
}
|
|
|
|
function requiredInteger(source: string, name: string, file: string): number {
|
|
const match = source.match(
|
|
new RegExp(`export\\s+const\\s+${name}\\s*=\\s*(\\d+)`),
|
|
);
|
|
const parsed = match?.[1] ? Number.parseInt(match[1], 10) : Number.NaN;
|
|
if (!Number.isSafeInteger(parsed) || parsed < 1) {
|
|
throw new Error(`${file} must export a positive integer ${name}`);
|
|
}
|
|
return parsed;
|
|
}
|
|
|
|
/**
|
|
* 09-07 (D-10). A feature directory must declare itself or say it is not
|
|
* installed. A missing or misspelt `feature-module.ts` used to drop the
|
|
* feature from the product without a word.
|
|
*/
|
|
export const NOT_INSTALLED_MARKER = "NOT_INSTALLED";
|
|
|
|
async function readDeclarations(
|
|
directory: string,
|
|
fileName: string,
|
|
requiredUnless?: string,
|
|
): Promise<readonly Readonly<{ directory: string; file: string; source: string }>[]> {
|
|
const found: { directory: string; file: string; source: string }[] = [];
|
|
let items;
|
|
try {
|
|
items = await readdir(directory, { withFileTypes: true });
|
|
} catch {
|
|
return found;
|
|
}
|
|
for (const item of items) {
|
|
if (!item.isDirectory()) continue;
|
|
const file = resolve(directory, item.name, fileName);
|
|
try {
|
|
found.push({ directory: item.name, file, source: await readFile(file, "utf8") });
|
|
} catch {
|
|
if (requiredUnless === undefined) continue;
|
|
const marker = await readFile(resolve(directory, item.name, requiredUnless))
|
|
.then(() => true, () => false);
|
|
if (marker) continue;
|
|
throw new Error(
|
|
`src/features/${item.name} has no ${fileName}; add one or mark the directory with ${requiredUnless}`,
|
|
);
|
|
}
|
|
}
|
|
return found;
|
|
}
|
|
|
|
/**
|
|
* Filesystem declaration source. Declarations are small literal headers, so
|
|
* reading them is a metadata scan; only the selected app's features are ever
|
|
* imported by the generated output.
|
|
*/
|
|
export async function createFileSystemDeclarationSource(
|
|
root: string,
|
|
): Promise<TopologyDeclarationSource> {
|
|
const apps = new Map<string, AppDeclaration>();
|
|
for (const declaration of await readDeclarations(resolve(root, "src/apps"), "app-module.ts")) {
|
|
const id = requiredLiteral(declaration.source, "APP_MODULE_ID", declaration.file);
|
|
if (apps.has(id)) throw new Error(`Duplicate app id: ${id}`);
|
|
apps.set(id, {
|
|
id,
|
|
maxContexts: requiredInteger(declaration.source, "APP_MAX_CONTEXTS", declaration.file),
|
|
});
|
|
}
|
|
const contextsByApp = new Map<string, ContextDeclaration[]>();
|
|
const contextIds = new Set<string>();
|
|
for (const declaration of await readDeclarations(resolve(root, "src/contexts"), "context-module.ts")) {
|
|
let context: ContextDeclaration = {
|
|
id: requiredLiteral(declaration.source, "CONTEXT_MODULE_ID", declaration.file),
|
|
appId: requiredLiteral(declaration.source, "CONTEXT_APP_ID", declaration.file),
|
|
routePath: requiredLiteral(declaration.source, "CONTEXT_ROUTE_PATH", declaration.file),
|
|
maxFeatures: requiredInteger(declaration.source, "CONTEXT_MAX_FEATURES", declaration.file),
|
|
};
|
|
const layout = `${declaration.directory}/context-layout.tsx`;
|
|
if (await readFile(resolve(root, "src/contexts", layout)).then(() => true, () => false)) {
|
|
context = { ...context, layoutImportPath: `../contexts/${layout}` };
|
|
}
|
|
if (contextIds.has(context.id)) throw new Error(`Duplicate context id: ${context.id}`);
|
|
if (!apps.has(context.appId)) {
|
|
throw new Error(`Context ${context.id} belongs to undeclared app ${context.appId}`);
|
|
}
|
|
contextIds.add(context.id);
|
|
const owned = contextsByApp.get(context.appId) ?? [];
|
|
owned.push(context);
|
|
contextsByApp.set(context.appId, owned);
|
|
}
|
|
const featuresByContext = new Map<string, FeatureDeclaration[]>();
|
|
const featureIds = new Set<string>();
|
|
for (const declaration of await readDeclarations(
|
|
resolve(root, "src/features"),
|
|
"feature-module.ts",
|
|
NOT_INSTALLED_MARKER,
|
|
)) {
|
|
const feature: FeatureDeclaration = {
|
|
id: requiredLiteral(declaration.source, "FEATURE_MODULE_ID", declaration.file),
|
|
contextId: requiredLiteral(declaration.source, "FEATURE_CONTEXT_ID", declaration.file),
|
|
directory: declaration.directory,
|
|
};
|
|
if (featureIds.has(feature.id)) throw new Error(`Duplicate generated feature ids: ${feature.id}`);
|
|
if (!contextIds.has(feature.contextId)) {
|
|
throw new Error(`Feature ${feature.id} belongs to undeclared context ${feature.contextId}`);
|
|
}
|
|
featureIds.add(feature.id);
|
|
const owned = featuresByContext.get(feature.contextId) ?? [];
|
|
owned.push(feature);
|
|
featuresByContext.set(feature.contextId, owned);
|
|
}
|
|
return Object.freeze({
|
|
appIds: () => [...apps.keys()].sort(),
|
|
app: (appId: string) => apps.get(appId),
|
|
contextsOf: (appId: string) => contextsByApp.get(appId) ?? [],
|
|
featuresOf: (contextId: string) => featuresByContext.get(contextId) ?? [],
|
|
});
|
|
}
|
|
|
|
export async function generateAppIndexes(
|
|
root: string,
|
|
requestedApp: string | undefined,
|
|
productFeatures?: string,
|
|
): Promise<SelectedAppIndexes> {
|
|
const source = await createFileSystemDeclarationSource(root);
|
|
return selectAppIndexes(
|
|
source,
|
|
resolveSelectedApp(source, requestedApp),
|
|
productFeatures,
|
|
);
|
|
}
|
|
|
|
async function main(): Promise<void> {
|
|
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
|
// `--root=` points the same production command at another checkout (used by
|
|
// the multi-app topology evidence); the default is this repository.
|
|
const rootArgument = process.argv
|
|
.find((argument) => argument.startsWith("--root="))
|
|
?.slice("--root=".length);
|
|
const root = rootArgument ? resolve(rootArgument) : resolve(scriptDir, "..");
|
|
const outputRoot = resolve(root, "src/.generated");
|
|
const outputs = {
|
|
feature: resolve(outputRoot, "product-feature-index.ts"),
|
|
context: resolve(outputRoot, "product-context-index.ts"),
|
|
app: resolve(outputRoot, "product-app.ts"),
|
|
};
|
|
const requestedApp =
|
|
process.argv.find((argument) => argument.startsWith("--app="))?.slice("--app=".length) ||
|
|
process.env["PRODUCT_APP_ID"] ||
|
|
undefined;
|
|
const selected = await generateAppIndexes(
|
|
root,
|
|
requestedApp,
|
|
process.env["VITE_PRODUCT_FEATURES"],
|
|
);
|
|
const rendered = {
|
|
feature: selected.featureIndex,
|
|
context: selected.contextIndex,
|
|
app: selected.appIndex,
|
|
};
|
|
await mkdir(outputRoot, { recursive: true });
|
|
|
|
if (process.argv.includes("--check")) {
|
|
const stale: string[] = [];
|
|
for (const key of ["feature", "context", "app"] as const) {
|
|
const current = await readFile(outputs[key], "utf8").catch(() => "");
|
|
if (current !== rendered[key]) stale.push(relative(root, outputs[key]));
|
|
}
|
|
if (stale.length > 0) {
|
|
throw new Error(`Generated topology index is stale: ${stale.join(", ")}`);
|
|
}
|
|
return;
|
|
}
|
|
|
|
await Promise.all(
|
|
(["feature", "context", "app"] as const).map((key) =>
|
|
writeFile(outputs[key], rendered[key], "utf8"),
|
|
),
|
|
);
|
|
}
|
|
|
|
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
await main();
|
|
}
|