문제
- 프론트 create:feature는 GET /api/<base>-items 목록 하나를 만든다. 짝 백엔드
new-feature.sh는 POST /<plural>(201, NOT_IDEMPOTENT)과 GET /<plural>/{id}를
만든다. 경로 규칙도, operation 쌍도 맞지 않는다(03-07).
- 짝 백엔드 모양(Envelope)의 상세 GET·작성 POST·폼·결과 불명 화면 예제는
참조 기능뿐이고, 참조 기능은 problem details 모양이라 옮기면 짝 백엔드에서
쓰이지 않는 분기와 값(400·422 분류, retryBudget 0, Envelope 줄 없음)을
함께 옮긴다(09-06, 16 5.3절).
- 생성된 목록의 "총 N개"는 배열 길이다. 백엔드 meta.page.total을 쓰지
않는다(03-02 수정이 남긴 일).
고른 방법
- 경로: 백엔드 new-feature.sh와 같은 복수형 규칙(backendPathSegment)으로
API_PATH 상수 하나를 둔다. 백엔드 api-base-path는 API_BASE_URL에 붙인다.
- 목록: mapper가 { items, total }을 내고 total은 page?.total ?? 길이다. 빈
목록은 EmptySurface로 같은 빈 상태를 그린다.
- --with-create: 상세 GET, 작성 POST, 상세·작성 라우트와 페이지, 폼 스키마
(이름 100자 = 백엔드 NAME_MAX_LENGTH), 뮤테이션 정책(commandMutationIdentity),
작성 폼 테스트를 만든다. 작성은 백엔드 기본에 맞춰 NEVER(retryBudget 0, 키
없음)다. --keyed는 백엔드 create를 IdempotencyExecutor 뒤에 둔 경우의
KEYED 값(IDEMPOTENCY_REPLAY, retryBudget 1)을 쓴다.
- 작성 descriptor: acceptedStatuses [201], refusedBeforeWrite
["<BASE>_INVALID"], classifyStatus는 401·403·429를 NOT_APPLIED(백엔드
보안 필터·@RequiresPermission 프록시·rate-limit interceptor가 use case 전에
거절한다). mapProblem이 <BASE>_INVALID를 이름 칸 오류로 바꾼다.
- 생성 테스트: gateway 테스트가 세 operation의 백엔드 본문(201 Envelope,
404 <BASE>_NOT_FOUND, 400 <BASE>_INVALID → NOT_APPLIED, 응답 유실 →
MAYBE_APPLIED, NEVER는 키 없음·KEYED는 503 IDEMPOTENCY_UNAVAILABLE 뒤 같은 키
1회 재전송)을 손으로 적는다. 하네스 재시도 상한은 앱 기본값 2다(16-07 (3)).
작성 폼 테스트는 라우터를 거쳐 201 저장 뒤 상세 열기, 400 거절을 이름 칸에
보이고 저장 버튼이 켜진 채 다시 저장, 응답 유실 뒤 결과 불명(NEVER는 다시
보내기 없음, KEYED는 같은 Idempotency-Key로 다시 보내기)을 본다.
- 페이지 테스트의 앱 조립은 <base>-test-app.tsx 하나로 모은다.
- slice 템플릿은 scripts/create-feature-write-slice.ts에 둔다. 리뷰 5.3절
재검토 조건(템플릿 2,000줄)을 넘지 않게 하고, create-feature.ts의 수정을
필요한 자리로 좁힌다.
- X1: 생성한 context 선언을 임시 폴더에 써서 생성기 선언 읽기로 읽고, 그
모듈을 import해 앱 모듈 조립(라우트 루트 검사)이 기능 라우트를 받는지 보는
단위 테스트를 더한다.
버린 대안
- 작성을 기본 KEYED로: 백엔드 생성 create는 키를 읽지 않아, 같은 키 재전송이
새 항목을 만든다. 안전해 보이는 거짓 보장이다.
- 참조 기능을 Envelope로 옮기기(09-06 (2)): 참조 테스트와 MSW fixture를 다수
바꾸고 problem details 예제가 사라진다.
- 목록 값을 배열로 두고 total을 배열 속성으로 싣기: TanStack 구조 공유가 배열
속성을 버린다.
위험·한계
- 백엔드 생성기는 목록 엔드포인트를 만들지 않는다. 백엔드에 GET 페이지 목록을
더하기 전에는 생성 목록이 405를 받는다. descriptor 주석과 매뉴얼에 적었다.
- 생성 기능의 초기 JS: 기본 +647 B, --with-create +964 B(이 브랜치 기준선
203,702 B에서 잰 값, 기능당 1 KiB 안). 기준선의 남은 여유는 1,098 B라
--with-create 기능 하나를 넣으면 134 B가 남는다.
- 두 생성기를 실제로 띄워 붙여 보지는 않았다. 백엔드 템플릿의 응답 본문과
경로를 읽어 생성 테스트에 옮겼다.
검증
- RED: tests/unit/create-feature.test.ts 새 17건 실패 → GREEN 43건 통과.
- 기본·--with-create·--with-create --keyed·--context reference-context
--with-create 네 기능을 만든 상태에서: check:types(app·test·node), lint,
check:registries(additive), check:i18n, check:architecture,
check:design-system, check:diagnostics, verify:documentation 통과. 생성 기능
테스트 77건 통과. 빠른 계층 313파일 3,818건 중 참조 라우팅 테스트 1건만
실패(X1, 다음 커밋).
- 변이: refusedBeforeWrite 삭제 → gateway·폼 테스트 2건 실패. 상세 GET의
responseEnvelope 삭제 → 조립 거절로 테스트와 check:registries 실패. KEYED
retryBudget 0 → 503 재전송 테스트 실패. 정책의 descriptor 상수 오타 → tsc 실패.
- flock 아래 build, check:bundle: 기준 203,702, 기본 기능 204,349, --with-create
기능 204,666 / 204,800 B PASS.
Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-06
Refs: docs/reviews/2026-11-03-maturity-review/03-adapters-http-state.md 03-07
Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-01
503 lines
20 KiB
TypeScript
503 lines
20 KiB
TypeScript
import { access, mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import { pathToFileURL } from "node:url";
|
|
|
|
import { afterEach, describe, expect, it } from "vitest";
|
|
|
|
import {
|
|
CreateFeatureError,
|
|
parseRequest,
|
|
planFeature,
|
|
randomTopicSuffix,
|
|
writeFeatureFiles,
|
|
type FeatureRequest,
|
|
type InstalledFacts,
|
|
} from "../../scripts/create-feature.ts";
|
|
import { createFileSystemDeclarationSource } from "../../scripts/generate-product-feature-index.ts";
|
|
import { PLACEHOLDER_CONTRACT_PACKAGE_DIGEST } from "../../src/contracts/deployment-admission.ts";
|
|
|
|
/**
|
|
* U7. What `pnpm create:feature` renders, checked without touching the
|
|
* repository. test:feature-scaffold writes a feature into a copy and runs the
|
|
* gates on it; this file covers the ids, the topic, the order and the refusals.
|
|
*/
|
|
const INSTALLED: InstalledFacts = Object.freeze({
|
|
appIds: ["template-app"],
|
|
featureIds: ["orders-feature", "drafts-feature"],
|
|
contexts: [
|
|
{ id: "orders-context", routePath: "orders/*" },
|
|
{ id: "billing-context", routePath: "billing/*" },
|
|
],
|
|
contextDirectories: ["orders-context", "billing-context"],
|
|
routes: [
|
|
{ routeId: "APP_HOME", path: "/", chunkId: "route-home", navigationOrder: 10 },
|
|
{ routeId: "ORDERS_LIST", path: "/orders", chunkId: "route-orders-list", navigationOrder: 50 },
|
|
{ routeId: "NOT_FOUND", path: "*", chunkId: "route-not-found", navigationOrder: null },
|
|
],
|
|
topics: ["qinv.0000000000000000000000000a"],
|
|
messageKeys: ["route.APP_HOME.title", "home.list.title"],
|
|
});
|
|
const TOPIC_SUFFIX = "abcdefghjkmnpqrstvwxyz0123";
|
|
|
|
function plan(request: FeatureRequest, installed: InstalledFacts = INSTALLED) {
|
|
return planFeature(request, installed, () => TOPIC_SUFFIX);
|
|
}
|
|
|
|
function rendered(request: FeatureRequest): string {
|
|
return [...plan(request).files.values()].join("\n");
|
|
}
|
|
|
|
describe("create:feature rendering", () => {
|
|
it("prefixes every global id with the feature and carries no sample token", () => {
|
|
const text = rendered({ id: "invoice-feature" });
|
|
|
|
expect(text).not.toMatch(/reference/iu);
|
|
const ids = [
|
|
...text.matchAll(
|
|
/\b(?:schemaId|inputSchemaId|operationId|mapperId|outputContractId|policyId|diagnosticsOperation|definitionId|chunkId|routeId|moduleId|loadingSurface|contributionId|owner)\s*:\s*"([^"]+)"/gu,
|
|
),
|
|
...text.matchAll(/\bzodValidator\(\s*"([^"]+)"/gu),
|
|
...text.matchAll(/defineQueryNamespaceIdentity\(\s*"([^"]+)"/gu),
|
|
...text.matchAll(/kind: "([a-z][^"]*\.[^"]*)"/gu),
|
|
...text.matchAll(/^\s+"((?:route\.)?[A-Za-z_.]+)": "/gmu),
|
|
].map((match) => match[1] ?? "");
|
|
expect(ids.length).toBeGreaterThan(30);
|
|
for (const id of ids) {
|
|
expect(id).toMatch(
|
|
/^(?:INVOICE_|Invoice|invoice[.-]|route\.INVOICE_LIST\.|route-invoice-|feature-frontend-invoice-feature$)/u,
|
|
);
|
|
}
|
|
expect(text).not.toMatch(/"NoRequest"/u);
|
|
});
|
|
|
|
it("names the route, context and topic it creates", () => {
|
|
const created = plan({ id: "invoice-feature" });
|
|
|
|
expect(created).toMatchObject({
|
|
contextId: "invoice-context",
|
|
newContext: true,
|
|
routeId: "INVOICE_LIST",
|
|
routePath: "/invoice",
|
|
topic: `qinv.${TOPIC_SUFFIX}`,
|
|
placeholder: true,
|
|
});
|
|
expect([...created.files.keys()]).toEqual(
|
|
expect.arrayContaining([
|
|
"src/contexts/invoice-context/context-module.ts",
|
|
"src/features/invoice-feature/feature-module.ts",
|
|
"tests/features/invoice-feature/invoice-feature-input.test.ts",
|
|
"tests/features/invoice-feature/invoice-list-page.test.tsx",
|
|
"artifacts/tests/a11y-manual/INVOICE_LIST.md",
|
|
]),
|
|
);
|
|
expect([...created.files.keys()].some((file) => file.includes("/domain/"))).toBe(false);
|
|
expect(created.files.get("src/contexts/invoice-context/context-module.ts")).toContain(
|
|
'CONTEXT_ROUTE_PATH = "invoice/*"',
|
|
);
|
|
expect(created.files.get("artifacts/tests/a11y-manual/INVOICE_LIST.md")).toMatch(
|
|
/^Status: pending-manual-review$/mu,
|
|
);
|
|
});
|
|
|
|
it("generates a fresh lower-case 26-character topic and refuses an installed one", () => {
|
|
const first = randomTopicSuffix();
|
|
expect(first).toMatch(/^[0-9a-hjkmnp-tv-z]{26}$/u);
|
|
expect(randomTopicSuffix()).not.toBe(first);
|
|
expect(() =>
|
|
planFeature({ id: "invoice-feature" }, INSTALLED, () => "0000000000000000000000000a"),
|
|
).toThrow(/qinv\.0000000000000000000000000a is already installed/u);
|
|
});
|
|
|
|
it("places the route after the last navigation entry", () => {
|
|
expect(rendered({ id: "invoice-feature" })).toContain("navigationOrder: 60,");
|
|
});
|
|
|
|
it("adds the route under an existing context's root", () => {
|
|
const created = plan({ id: "invoice-feature", context: "billing-context" });
|
|
|
|
expect(created).toMatchObject({ newContext: false, routePath: "/billing/invoice" });
|
|
expect([...created.files.keys()].some((file) => file.startsWith("src/contexts/"))).toBe(false);
|
|
});
|
|
|
|
it("pins the placeholder through its exported constant, or the given package", () => {
|
|
expect(rendered({ id: "invoice-feature" })).toContain(
|
|
"digest: PLACEHOLDER_CONTRACT_PACKAGE_DIGEST,",
|
|
);
|
|
const digest = `sha256:${"ab".repeat(32)}`;
|
|
const pinned = plan({
|
|
id: "invoice-feature",
|
|
contractPackage: {
|
|
packageId: "@org-contracts/invoice",
|
|
version: "1.4.2",
|
|
digest,
|
|
sourceRevision: "0a1b2c3d",
|
|
},
|
|
});
|
|
const contract = pinned.files.get(
|
|
"src/features/invoice-feature/contracts/invoice-feature-contract.ts",
|
|
);
|
|
expect(pinned.placeholder).toBe(false);
|
|
expect(contract).toContain(`digest: "${digest}",`);
|
|
expect(contract).not.toContain("PLACEHOLDER");
|
|
expect(digest).not.toBe(PLACEHOLDER_CONTRACT_PACKAGE_DIGEST);
|
|
});
|
|
|
|
// 1101 README 14.3. test:feature-scaffold runs the gateway test this renders.
|
|
it("reads the paired backend's Envelope and tests it with the backend's own bodies", () => {
|
|
const { files } = plan({ id: "invoice-feature" });
|
|
const contracts = "src/features/invoice-feature/contracts";
|
|
|
|
expect(files.get(`${contracts}/invoice-contract-contribution.ts`)).toContain(
|
|
'responseEnvelope: "ENVELOPE_V1" as const,',
|
|
);
|
|
expect(files.get(`${contracts}/invoice-schemas.ts`)).toMatch(
|
|
/invoiceProblemSchema = z\s*\.object\(\{\s*code: z\.string\(\)\.regex/u,
|
|
);
|
|
expect(
|
|
files.get("tests/features/invoice-feature/invoice-http-gateway.test.ts"),
|
|
).toContain('success: true, data: [{ id: "item-1", name: "First item" }]');
|
|
});
|
|
|
|
// 1103/03-07. The paired backend's new-feature.sh maps /<plural> (its
|
|
// camel-case name plus s, es or ies); the frontend's list reads the same
|
|
// resource path. The backend's api-base-path belongs in API_BASE_URL.
|
|
it.each([
|
|
["invoice-feature", "/invoices"],
|
|
["purchase-order-feature", "/purchaseOrders"],
|
|
["batch-feature", "/batches"],
|
|
["box-feature", "/boxes"],
|
|
["company-feature", "/companies"],
|
|
["day-feature", "/days"],
|
|
["status-feature", "/statuses"],
|
|
])("lists %s at the backend scaffold's resource path %s", (id, apiPath) => {
|
|
const base = id.slice(0, -"-feature".length);
|
|
const contribution = plan({ id }).files.get(
|
|
`src/features/${id}/contracts/${base}-contract-contribution.ts`,
|
|
);
|
|
|
|
expect(contribution).toContain(`const API_PATH = "${apiPath}";`);
|
|
});
|
|
|
|
// 1103/03-02. A page list's meta.page.total counts every page.
|
|
it("shows the total the backend counted, not the length of the first page", () => {
|
|
const { files } = plan({ id: "invoice-feature" });
|
|
|
|
expect(files.get("src/features/invoice-feature/contracts/invoice-mapper.ts")).toContain(
|
|
"total: page?.total ?? items.length",
|
|
);
|
|
expect(
|
|
files.get("src/features/invoice-feature/presentation/invoice-list-page.tsx"),
|
|
).toContain('message("invoice.list.resultCount", { count: query.data.total })');
|
|
});
|
|
});
|
|
|
|
/**
|
|
* 1103/09-06, 03-07. `--with-create` adds the paired backend scaffold's other
|
|
* two endpoints (POST /<plural>, GET /<plural>/{id}) with a detail page, a
|
|
* create form and the unknown-result handling. test:feature-scaffold and
|
|
* test:sample-removal generate it and run the gates on it.
|
|
*/
|
|
describe("create:feature --with-create", () => {
|
|
const contributionOf = (files: ReadonlyMap<string, string>) =>
|
|
files.get("src/features/invoice-feature/contracts/invoice-contract-contribution.ts") ?? "";
|
|
|
|
it("prefixes every id of the slice and adds its routes, pages and tests", () => {
|
|
const created = plan({ id: "invoice-feature", write: "NEVER" });
|
|
const text = [...created.files.values()].join("\n");
|
|
|
|
// No sample id. (`supportReference` is a platform prop.) Written so this
|
|
// file holds no sample id itself, which test:sample-removal looks for.
|
|
expect(text).not.toMatch(/REFERENCE_|ReferenceResource|reference-(?:feature|context)/u);
|
|
const ids = [
|
|
...text.matchAll(
|
|
/\b(?:schemaId|operationId|policyId|diagnosticsOperation|definitionId|chunkId|routeId|moduleId|loadingSurface|contributionId)\s*:\s*"([^"]+)"/gu,
|
|
),
|
|
...text.matchAll(/\bzodValidator\(\s*"([^"]+)"/gu),
|
|
...text.matchAll(/kind: "([a-z][^"]*\.[^"]*)"/gu),
|
|
...text.matchAll(/^\s+"((?:route\.)?[A-Za-z_.]+)": "/gmu),
|
|
].map((match) => match[1] ?? "");
|
|
expect(ids.length).toBeGreaterThan(50);
|
|
for (const id of ids) {
|
|
expect(id).toMatch(
|
|
/^(?:INVOICE_|Invoice|invoice[.-]|route\.INVOICE_(?:LIST|DETAIL|CREATE)\.|route-invoice-)/u,
|
|
);
|
|
}
|
|
expect([...created.files.keys()]).toEqual(
|
|
expect.arrayContaining([
|
|
"src/features/invoice-feature/presentation/invoice-detail-page.tsx",
|
|
"src/features/invoice-feature/presentation/invoice-create-page.tsx",
|
|
"src/features/invoice-feature/presentation/invoice-form.ts",
|
|
"src/features/invoice-feature/presentation/invoice-route-codecs.ts",
|
|
"src/features/invoice-feature/presentation/use-invoice-item.ts",
|
|
"src/features/invoice-feature/presentation/use-invoice-create.ts",
|
|
"tests/features/invoice-feature/invoice-create-page.test.tsx",
|
|
"artifacts/tests/a11y-manual/INVOICE_DETAIL.md",
|
|
"artifacts/tests/a11y-manual/INVOICE_CREATE.md",
|
|
]),
|
|
);
|
|
expect(created.routes).toEqual([
|
|
{ routeId: "INVOICE_LIST", path: "/invoice" },
|
|
{ routeId: "INVOICE_DETAIL", path: "/invoice/items/:invoiceId" },
|
|
{ routeId: "INVOICE_CREATE", path: "/invoice/new" },
|
|
]);
|
|
});
|
|
|
|
// 1103/16-01. Every generated operation declares the Envelope.
|
|
it("declares the Envelope on every operation it writes", () => {
|
|
const contribution = contributionOf(plan({ id: "invoice-feature", write: "NEVER" }).files);
|
|
|
|
expect(contribution.match(/operationId: "INVOICE_[A-Z_]+",/gu)).toHaveLength(3);
|
|
expect(contribution.match(/responseEnvelope: "ENVELOPE_V1" as const,/gu)).toHaveLength(3);
|
|
expect(contribution).toContain("pathTemplate: `${API_PATH}/{id}`,");
|
|
});
|
|
|
|
// 1103/03-07. new-feature.sh generates a NOT_IDEMPOTENT create: the backend
|
|
// ignores a key, so a same-key resend would create a second item.
|
|
it("matches the backend scaffold's NOT_IDEMPOTENT create with a NEVER command", () => {
|
|
const contribution = contributionOf(plan({ id: "invoice-feature", write: "NEVER" }).files);
|
|
|
|
expect(contribution).toContain('retrySemantics: "NEVER" as const,');
|
|
expect(contribution).toContain("retryBudget: 0 as const,");
|
|
expect(contribution).not.toContain("IDEMPOTENCY_REPLAY");
|
|
expect(contribution).toContain("acceptedStatuses: Object.freeze([201]),");
|
|
// 1103/03-01. The backend checks the name before its transaction.
|
|
expect(contribution).toContain('refusedBeforeWrite: Object.freeze(["INVOICE_INVALID"]),');
|
|
});
|
|
|
|
// 1103/16-07. A backend create made KEYED (IdempotencyExecutor) takes these.
|
|
it("writes the KEYED values for a backend create made KEYED", () => {
|
|
const { files } = plan({ id: "invoice-feature", write: "KEYED" });
|
|
const contribution = contributionOf(files);
|
|
|
|
expect(contribution).toContain('retrySemantics: "KEYED" as const,');
|
|
expect(contribution).toContain('mode: "IDEMPOTENCY_REPLAY" as const,');
|
|
expect(contribution).toContain('operationIdentityField: "idempotencyKey",');
|
|
expect(contribution).toContain("retryBudget: 1 as const,");
|
|
expect(
|
|
files.get("tests/features/invoice-feature/invoice-create-page.test.tsx"),
|
|
).toContain('posts[1]!.headers.get("idempotency-key")');
|
|
expect(
|
|
files.get("src/features/invoice-feature/presentation/use-invoice-create.ts"),
|
|
).toContain("...commandMutationIdentity(INVOICE_CREATE_ITEM_CONTRACT),");
|
|
});
|
|
|
|
it("refuses a slice route that collides with an installed one", () => {
|
|
expect(() =>
|
|
plan(
|
|
{ id: "invoice-feature", write: "NEVER" },
|
|
{
|
|
...INSTALLED,
|
|
routes: [
|
|
...INSTALLED.routes,
|
|
{ routeId: "LEGACY", path: "/invoice/new", chunkId: "route-legacy", navigationOrder: null },
|
|
],
|
|
},
|
|
),
|
|
).toThrow(/route INVOICE_CREATE .* collides with installed route LEGACY/u);
|
|
});
|
|
|
|
it("takes --with-create and --keyed, and --keyed only with --with-create", () => {
|
|
expect(parseRequest(["invoice-feature", "--with-create"])).toMatchObject({
|
|
write: "NEVER",
|
|
});
|
|
expect(parseRequest(["invoice-feature", "--with-create", "--keyed"])).toMatchObject({
|
|
write: "KEYED",
|
|
});
|
|
expect(parseRequest(["invoice-feature"]).write).toBeUndefined();
|
|
expect(() => parseRequest(["invoice-feature", "--keyed"])).toThrow(
|
|
/--keyed needs --with-create/u,
|
|
);
|
|
});
|
|
});
|
|
|
|
/**
|
|
* X1 (2026-11-04). The generated context declaration is executed, not only
|
|
* read as text: the generator's declaration source reads it from disk, and an
|
|
* app module built from its exported route root accepts every route the
|
|
* feature declares (the check the router relies on, 09-06).
|
|
*/
|
|
describe("create:feature context declaration", () => {
|
|
const roots: string[] = [];
|
|
afterEach(async () => {
|
|
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
|
});
|
|
|
|
async function appFor(
|
|
contextId: string,
|
|
routePath: string,
|
|
maxFeatures: number,
|
|
routes: readonly Readonly<{ routeId: string; path: string }>[],
|
|
) {
|
|
const { defineBoundedContextModule } = await import(
|
|
"../../src/contexts/bounded-context-module.ts"
|
|
);
|
|
const { defineDeployableAppModule } = await import("../../src/apps/deployable-app-module.ts");
|
|
return defineDeployableAppModule({
|
|
id: "template-app",
|
|
budget: { maxContexts: 20 },
|
|
contexts: [
|
|
defineBoundedContextModule({
|
|
id: contextId,
|
|
budget: { maxFeatures },
|
|
features: [
|
|
{
|
|
id: "invoice-feature",
|
|
contracts: {
|
|
routes: Object.fromEntries(routes.map((route) => [route.routeId, route])),
|
|
},
|
|
} as never,
|
|
],
|
|
route: { path: routePath, loadRoutes: async () => [] },
|
|
}),
|
|
],
|
|
});
|
|
}
|
|
|
|
it.each([undefined, "NEVER"] as const)(
|
|
"writes a context module the generator reads and whose root holds the routes (write %s)",
|
|
async (write) => {
|
|
const root = await mkdtemp(path.join(tmpdir(), "create-feature-context-"));
|
|
roots.push(root);
|
|
const created = plan({ id: "invoice-feature", write });
|
|
await mkdir(path.join(root, "src/apps/template-app"), { recursive: true });
|
|
await writeFile(
|
|
path.join(root, "src/apps/template-app/app-module.ts"),
|
|
'export const APP_MODULE_ID = "template-app";\nexport const APP_MAX_CONTEXTS = 20;\n',
|
|
);
|
|
await writeFeatureFiles(root, created.files);
|
|
|
|
const source = await createFileSystemDeclarationSource(root);
|
|
expect(source.contextsOf("template-app")).toEqual([
|
|
{ id: "invoice-context", appId: "template-app", routePath: "invoice/*", maxFeatures: 20 },
|
|
]);
|
|
expect(source.featuresOf("invoice-context").map((feature) => feature.id)).toEqual([
|
|
"invoice-feature",
|
|
]);
|
|
const declared = (await import(
|
|
pathToFileURL(path.join(root, "src/contexts/invoice-context/context-module.ts")).href
|
|
)) as Record<string, unknown>;
|
|
expect(declared).toMatchObject({
|
|
CONTEXT_MODULE_ID: "invoice-context",
|
|
CONTEXT_APP_ID: "template-app",
|
|
CONTEXT_ROUTE_PATH: "invoice/*",
|
|
});
|
|
|
|
const app = await appFor(
|
|
String(declared["CONTEXT_MODULE_ID"]),
|
|
String(declared["CONTEXT_ROUTE_PATH"]),
|
|
Number(declared["CONTEXT_MAX_FEATURES"]),
|
|
created.routes,
|
|
);
|
|
expect(app.contexts.map((context) => context.id)).toEqual(["invoice-context"]);
|
|
},
|
|
);
|
|
|
|
it("puts the routes under an existing context's root", async () => {
|
|
const created = plan({ id: "invoice-feature", context: "billing-context", write: "NEVER" });
|
|
|
|
expect(created.routes.map((route) => route.path)).toEqual([
|
|
"/billing/invoice",
|
|
"/billing/invoice/items/:invoiceId",
|
|
"/billing/invoice/new",
|
|
]);
|
|
await expect(appFor("billing-context", "billing/*", 20, created.routes)).resolves.toBeDefined();
|
|
});
|
|
});
|
|
|
|
describe("create:feature refusals", () => {
|
|
it.each(["Invoice", "invoice_feature", "-invoice", "invoice--x", "invoice-", "", "a".repeat(41)])(
|
|
"refuses the id %j",
|
|
(id) => {
|
|
expect(() => plan({ id })).toThrow(/kebab-case/u);
|
|
},
|
|
);
|
|
|
|
it.each([
|
|
[{ id: "orders-feature" }, /already a feature or context/u],
|
|
[{ id: "orders-context" }, /already a feature or context/u],
|
|
[{ id: "orders" }, /prefix its ids with "orders", which orders-feature already uses/u],
|
|
[{ id: "billing-feature" }, /pass --context billing-context/u],
|
|
[{ id: "invoice-feature", context: "orders" }, /already owns the route root orders\/\*/u],
|
|
[{ id: "invoice-feature", context: "drafts-feature" }, /is a feature id/u],
|
|
[{ id: "home-feature" }, /message keys already exist: home\.list\.title/u],
|
|
[
|
|
{
|
|
id: "invoice-feature",
|
|
contractPackage: {
|
|
packageId: "@org-contracts/invoice",
|
|
version: "1.4.2",
|
|
digest: "sha256:abc",
|
|
sourceRevision: "0a1b2c3d",
|
|
},
|
|
},
|
|
/not a pinned identity: invoice-feature: package digest/u,
|
|
],
|
|
] as const)("refuses %j", (request, reason) => {
|
|
expect(() => plan(request)).toThrow(reason);
|
|
});
|
|
|
|
it("refuses a route that collides with an installed one", () => {
|
|
expect(() =>
|
|
plan(
|
|
{ id: "invoice-feature" },
|
|
{
|
|
...INSTALLED,
|
|
routes: [
|
|
...INSTALLED.routes,
|
|
{ routeId: "LEGACY", path: "/invoice", chunkId: "route-legacy", navigationOrder: null },
|
|
],
|
|
},
|
|
),
|
|
).toThrow(/collides with installed route LEGACY/u);
|
|
});
|
|
});
|
|
|
|
describe("create:feature writing", () => {
|
|
const roots: string[] = [];
|
|
afterEach(async () => {
|
|
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
|
});
|
|
|
|
async function emptyRoot(): Promise<string> {
|
|
const root = await mkdtemp(path.join(tmpdir(), "create-feature-"));
|
|
roots.push(root);
|
|
return root;
|
|
}
|
|
|
|
it("refuses to overwrite and writes nothing when one target exists", async () => {
|
|
const root = await emptyRoot();
|
|
const files = plan({ id: "invoice-feature" }).files;
|
|
await mkdir(path.join(root, "artifacts/tests/a11y-manual"), { recursive: true });
|
|
await writeFile(path.join(root, "artifacts/tests/a11y-manual/INVOICE_LIST.md"), "kept\n");
|
|
|
|
await expect(writeFeatureFiles(root, files)).rejects.toThrow(
|
|
/refusing to overwrite: artifacts\/tests\/a11y-manual\/INVOICE_LIST\.md/u,
|
|
);
|
|
expect(await readdir(root)).toEqual(["artifacts"]);
|
|
});
|
|
|
|
it("refuses an existing feature directory", async () => {
|
|
const root = await emptyRoot();
|
|
await mkdir(path.join(root, "src/features/invoice-feature"), { recursive: true });
|
|
|
|
await expect(
|
|
writeFeatureFiles(root, plan({ id: "invoice-feature" }).files, [
|
|
"src/features/invoice-feature",
|
|
]),
|
|
).rejects.toThrow(CreateFeatureError);
|
|
});
|
|
|
|
it("removes what it wrote when a later write fails", async () => {
|
|
const root = await emptyRoot();
|
|
const files = new Map([
|
|
["src/features/broken/first.ts", "export {};\n"],
|
|
// A file cannot be a directory, so this write fails after the first.
|
|
["src/features/broken/first.ts/second.ts", "export {};\n"],
|
|
]);
|
|
|
|
await expect(writeFeatureFiles(root, files)).rejects.toThrow();
|
|
await expect(access(path.join(root, "src"))).rejects.toThrow();
|
|
});
|
|
});
|