From 4ab35c4a0512d27e24d2cdcc90519ec6c9f78243 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 12 Nov 2026 22:32:09 +0900 Subject: [PATCH] =?UTF-8?q?fix(test):=20=ED=85=9C=ED=94=8C=EB=A6=BF=20?= =?UTF-8?q?=EC=8B=9C=ED=97=98=EC=9D=B4=20=EC=82=AC=EB=B3=B8=EC=97=90=20?= =?UTF-8?q?=EB=A7=8C=EB=93=9C=EB=8A=94=20=EA=B8=B0=EB=8A=A5=20ID=EB=A5=BC?= =?UTF-8?q?=20=EC=98=88=EC=95=BD=20=EC=A0=91=EB=91=90=EC=96=B4=EB=A1=9C=20?= =?UTF-8?q?=EC=98=AE=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 템플릿 시험과 드릴이 저장소 사본에 고정 ID로 기능을 만든다. 매뉴얼 코드 조각 시험은 매뉴얼 예시 invoice-feature를(FE-GATE-005), 생성 기능 e2e·청크 복구·부팅 실패 spec은 order-feature를(FE-GATE-008), scaffold 드릴은 scaffold-feature를(FE-GATE-020) 쓴다. 사본에는 제품 기능이 들어 있고 create:feature는 같은 ID나 같은 접두어를 거부한다. 그래서 매뉴얼 1단계 예시대로 invoice-feature를 만든 제품은 기능 코드와 상관없이 merge 게이트에서 막힌다. 고른 방법: 사본에 만드는 기능 ID를 모두 이미 정한 예약 접두어 typecheck-probe-로 옮기고 scripts/lib/template-probe-features.ts 한 곳에 둔다. 매뉴얼 조각은 invoice-feature 기준 그대로 두고, 시험이 조각과 검사 파일의 이름(INVOICE_, Invoice, invoice-, invoice)을 예약 기능의 이름으로 바꿔 넣는다(renameFeatureText). 생성 기능 e2e는 메시지 키와 계약 이름을 ID에서 만든다. 버린 대안: 사본에서 제품의 같은 이름 기능을 먼저 지우기(등록·조립 파일까지 지워야 해 사본이 제품과 달라진다), create:feature가 흔한 이름을 거부하기(제품 이름을 막는다). 위험·한계: 이름 바꾸기는 낱말 단위 치환이라 조각의 영어 문장 속 invoice도 바뀐다(조각과 검사가 함께 바뀌어 결과는 같다). 제품이 typecheck-probe-로 시작하는 기능을 만들면 다시 부딪친다. 매뉴얼과 create-feature 참조에 쓰지 말라고 적었고 생성 명령이 막지는 않는다. measure-feature-shape-growth의 s000-feature 꼴 ID는 그대로 뒀다. 검증: desktop에서 RED(이 커밋의 시험을 기준 커밋에 얹음)와 GREEN, 제품 상태(invoice-feature·order-feature를 만든 사본)의 FE-GATE-005·008 재현은 PR 본문에 적는다. Refs: 1112/08-02 --- docs/manual/01-add-a-feature.md | 3 +- docs/manual/02-decision-tables.md | 2 +- docs/manual/reference/create-feature.md | 4 +- docs/work/new-feature.md | 2 +- docs/work/reference/defect-patterns.md | 2 +- docs/work/reference/testing.md | 2 +- scripts/create-feature.ts | 2 +- scripts/lib/generated-feature.ts | 40 ++++--- scripts/lib/template-probe-features.ts | 49 ++++++++ scripts/test-feature-scaffold.ts | 9 +- scripts/test-sample-removal.ts | 3 +- tests/e2e/generated-feature.spec.ts | 23 ++-- tests/unit/manual-code-blocks.test.ts | 19 ++- ...template-feature-removal-documents.test.ts | 13 ++- tests/unit/template-probe-features.test.ts | 109 ++++++++++++++++++ 15 files changed, 239 insertions(+), 43 deletions(-) create mode 100644 scripts/lib/template-probe-features.ts create mode 100644 tests/unit/template-probe-features.test.ts diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index d298aeb7..f0ce2bd3 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -10,7 +10,7 @@ 생성 명령은 이 문제를 미리 피한 파일을 쓴다. 템플릿에는 복사해 볼 기능 샘플이 없다. 생성 뼈대에 없는 모양은 이 매뉴얼 안의 코드 조각으로 보인다. 코드 조각 위의 `manual-code-block` 표식이 그 조각을 둘 자리다. 조각은 `create:feature invoice-feature --with-create`로 만든 기능을 기준으로 쓴다. -`tests/unit/manual-code-blocks.test.ts`가 그 기능을 저장소 사본에 만들고 조각을 그 자리에 그대로 넣어 타입 검사와 동작 시험을 돌린다. +`tests/unit/manual-code-blocks.test.ts`가 저장소 사본에 예약 이름의 같은 기능(`typecheck-probe-invoice-feature`)을 만들고, 조각의 이름만 그 기능 이름으로 바꿔 그 자리에 넣은 뒤 타입 검사와 동작 시험을 돌린다. 사본에 제품이 만든 `invoice-feature`가 있어도 부딪치지 않는다. ## 전체 흐름 @@ -72,6 +72,7 @@ - `ApplicationFeatureInputs`의 키 - `config/runtime/.json`의 `FEATURE_OVERRIDES` 키 - ID가 `-feature`로 끝나면 생성 명령은 그 앞부분을 접두어로 쓴다. `invoice-feature`면 `invoice`, `INVOICE_`, `Invoice`다. +- `typecheck-probe-`로 시작하는 ID는 쓰지 않는다. 템플릿 시험이 저장소 복사본에 만드는 기능 이름이다(`scripts/lib/template-probe-features.ts`). 그 밖의 이름은 이 매뉴얼의 예시(`invoice-feature`)를 포함해 모두 쓸 수 있다. - 근거: `scale-architecture.md` §5(모듈 소유), §7(개수 예산), §9(라우터 구조). ③ **잡는 검사 / 못 잡는 것** diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 145996e6..56da9ac5 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -326,7 +326,7 @@ export function mapInvoiceCreateProblem( } ``` -- 이 두 조각은 `tests/unit/manual-code-blocks.test.ts`가 시험한다. 저장소 사본에 `create:feature invoice-feature --with-create`로 기능을 만들고, 조각을 위 경로에 그대로 넣어 타입 검사를 하고, 분류와 매핑이 위 설명대로인지 돌려 본다(`tests/fixtures/manual-code-blocks/`). +- 이 두 조각은 `tests/unit/manual-code-blocks.test.ts`가 시험한다. 저장소 사본에 예약 이름의 같은 기능(`typecheck-probe-invoice-feature`)을 `--with-create`로 만들고, 조각의 이름만 그 기능 이름으로 바꿔 위 경로에 넣어 타입 검사를 하고, 분류와 매핑이 위 설명대로인지 돌려 본다(`tests/fixtures/manual-code-blocks/`). **틀리면** diff --git a/docs/manual/reference/create-feature.md b/docs/manual/reference/create-feature.md index c57895af..dc754a5c 100644 --- a/docs/manual/reference/create-feature.md +++ b/docs/manual/reference/create-feature.md @@ -12,7 +12,7 @@ corepack pnpm create:feature [--context ] [--with-create [--key | 인자 | 규칙 | |---|---| -| `` | 케밥 표기, 40자 이하. 기존 기능·context ID와 겹치면 거부 | +| `` | 케밥 표기, 40자 이하. 기존 기능·context ID와 겹치면 거부. `typecheck-probe-`로 시작하는 ID는 템플릿 시험이 복사본에 만드는 이름이라 쓰지 않는다(`scripts/lib/template-probe-features.ts`) | | `--context` | 기존 context ID. 없으면 `-context`를 새로 만든다 | | `--with-create` | 짝 백엔드 `new-feature.sh`의 작성(`POST /`)·상세(`GET //{id}`)와 그 페이지를 더한다. 작성은 `NEVER` | | `--keyed` | `--with-create`와 함께만. 작성을 `KEYED`로 만든다. 백엔드 create를 멱등성 executor 뒤에 둔 뒤에 쓴다 | @@ -164,5 +164,5 @@ node scripts/write-dev-release-manifest.ts # dev manifest에서 그 기능의 ## 알려진 한계 -- 드릴은 브라우저 테스트(FE-GATE-008·009의 `test:e2e`, `test:a11y` 등)와 `test:system`을 돌리지 않는다. `check:bundle`(FE-GATE-012)은 돈다. 브라우저에서의 동작은 위 e2e spec이 고정한 이름(`order-feature`)의 기능 하나로만 본다. +- 드릴은 브라우저 테스트(FE-GATE-008·009의 `test:e2e`, `test:a11y` 등)와 `test:system`을 돌리지 않는다. `check:bundle`(FE-GATE-012)은 돈다. 브라우저에서의 동작은 위 e2e spec이 고정한 이름(`typecheck-probe-order-feature`, `scripts/lib/generated-feature.ts`)의 기능 하나로만 본다. - 새 context는 앱이 하나일 때만 만든다. 앱이 여럿이면 `--context`로 기존 context를 고른다. diff --git a/docs/work/new-feature.md b/docs/work/new-feature.md index 3d0124ba..ca06fcd3 100644 --- a/docs/work/new-feature.md +++ b/docs/work/new-feature.md @@ -56,7 +56,7 @@ - 생성 명령이 거부하면 `docs/manual/reference/errors.md`에서 메시지를 찾는다. 고칠 파일이 적혀 있다. - 짝 백엔드 응답 모양·오류 code가 문서와 다르면 코드(백엔드 생성기, 이 repo의 `src/adapters/http/backend-envelope.ts`)까지 따라가 사실을 적고 묻는다. 문서만 보고 판정 표를 정하지 않는다. - 기능 폴더 밖을 고쳐야만 되면 거기서 멈추고 [README](README.md) 5절 형식으로 묻는다. -- brief가 매뉴얼 예시 이름(`invoice-feature` 등)을 기능 ID로 주면 그대로 만들지 말고 묻는다. 템플릿 시험(`tests/unit/manual-code-blocks.test.ts`)이 저장소 사본에 그 이름으로 기능을 만든다. +- brief가 기능 ID를 `typecheck-probe-`로 시작하게 주면 그대로 만들지 말고 묻는다. 템플릿 시험이 저장소 사본에 만드는 예약 이름이다(`scripts/lib/template-probe-features.ts`). 매뉴얼 예시 이름(`invoice-feature`)은 써도 된다. ## 8. 보고 형식 diff --git a/docs/work/reference/defect-patterns.md b/docs/work/reference/defect-patterns.md index c36d9002..9b132814 100644 --- a/docs/work/reference/defect-patterns.md +++ b/docs/work/reference/defect-patterns.md @@ -37,7 +37,7 @@ | T4 | 브라우저의 추정에 기댄다 | WebKit이 load 3초 뒤 한 번 하는 preload 추정에 기대 곧 쓰일 preload로 실패하고, 정말 안 쓴 preload는 놓친다 | 1103/11-09 | 추정 대신 확인하려는 사실을 직접 검사한다(`testing.md` 5절) | 10, 21 | | T5 | 그리는 중인 화면을 누른다 | 앱 뒤에 붙인 버튼이 렌더링 중 밀려 클릭이 닿지 않는다 | 1103/11-10 | 테스트가 붙이는 조작 요소는 고정 층에(`testing.md` 5절) | 10, 21 | | T6 | 테스트 대역이 실제 상대와 다르다 | 메모리 IndexedDB, fake, 백엔드 문서에서 옮긴 MSW 응답이 실제와 달라 결함을 숨긴다 | 0925/05-08, 0925/06-01, 1103/05-04, 1103/16-01, 1105/01-01 | 실제 짝 백엔드 응답으로 맞추기는 미조치(1105 README 9절) | 10, 17, 12 | -| T7 | 플랫폼 테스트가 샘플·특정 파일·예시 이름에 묶인다 | 샘플을 지우면 테스트가 같이 사라지거나 게이트가 깨진다. 템플릿 테스트의 글자가 매뉴얼 예시 기능 이름과 부딪힌다 | 0925/14-01, 0929/10-02, 1101/16-02, 1105/10-01, 1105/16-04 | 테스트 전용 라우트와 플랫폼 소유 MSW 카탈로그(`testing.md` 2절). 탐침 이름은 예약 접두어 `typecheck-probe-*` | 27, 10, 21, 20 | +| T7 | 플랫폼 테스트가 샘플·특정 파일·예시 이름에 묶인다 | 샘플을 지우면 테스트가 같이 사라지거나 게이트가 깨진다. 템플릿 테스트의 글자가 매뉴얼 예시 기능 이름과 부딪힌다 | 0925/14-01, 0929/10-02, 1101/16-02, 1105/10-01, 1105/16-04, 1112/08-02 | 테스트 전용 라우트와 플랫폼 소유 MSW 카탈로그(`testing.md` 2절). 템플릿 시험이 사본에 만드는 기능·탐침 이름은 예약 접두어 `typecheck-probe-*` | 27, 10, 21, 20 | | T8 | 빠른 계층에 느린 테스트가 섞인다 | unit에 프로세스를 띄우는 도구 테스트, 실제 시계로 기다리는 테스트가 섞이고 같은 파일을 두 번 돈다 | 1101/10-05, 1101/10-06, 1101/10-07, 1101/15-04 | 없음. `testing.md` 6절 | 14, 20, 10 | | T9 | 깨끗한 clone·다른 호스트에서 실패한다 | gitignore된 생성물, 기준선을 만든 CPU, 실행기가 넣는 npm 환경변수에 기댄다 | 0924 6.0절, 0925/10-01, 0925/11-03, 1101/15-05 | 한 파일 실행도 `scripts/run-vitest.ts`로. merge 판정은 깨끗한 checkout에서(`gates.md` 2·3절) | 10, 21, 20 | | T10 | 지우거나 바꾼 코드가 지키던 검사·테스트를 같이 잃는다 | 삭제·이름 변경이 실행 동작만 옮기고, 지운 행·테스트가 지키던 규칙은 옮기지 않는다 | 1103/07-01, 1103/10-04, 1105/04-01, 1105/10-01 | `structure.md` 9절 | 10, 21, 17 | diff --git a/docs/work/reference/testing.md b/docs/work/reference/testing.md index 3dcff9a1..c2edeea8 100644 --- a/docs/work/reference/testing.md +++ b/docs/work/reference/testing.md @@ -39,7 +39,7 @@ - 스크립트 테스트가 자식 프로세스를 띄우면 그 suite가 자기 timeout을 선언한다. 전역 timeout을 올리지 않는다. - 값은 desktop에서 잰 가장 긴 실행으로 정한다: `childProcessTimeout()`(`tests/helpers/child-process-timeout.ts`). 부하가 높은 desktop에서 자식 프로세스 테스트가 평소보다 몇 배 느려진 실측을 근거로 둔다. - 기본 timeout인 테스트가 자식 프로세스를 띄우면 `tests/setup.ts`가 그 호출에서 실패시킨다. helper나 import한 스크립트가 띄워도 같다. hook(`beforeAll` 등)은 보지 않는다. -- 플랫폼을 지키는 테스트는 기능·스타터 화면에 묶지 않는다. 테스트 전용 라우트와 플랫폼 소유 MSW 카탈로그(`tests/mocks/`)를 쓴다(결함 패턴 T7). 생성물 탐침 이름은 예약 접두어(`typecheck-probe-*`)를 쓴다. +- 플랫폼을 지키는 테스트는 기능·스타터 화면에 묶지 않는다. 테스트 전용 라우트와 플랫폼 소유 MSW 카탈로그(`tests/mocks/`)를 쓴다(결함 패턴 T7). 템플릿 시험이 저장소 사본에 만드는 기능과 생성물 탐침의 이름은 예약 접두어(`typecheck-probe-*`, `scripts/lib/template-probe-features.ts`)를 쓴다. 사본에는 제품 기능이 들어 있어, 흔한 업무 이름이나 매뉴얼 예시 이름을 쓰면 그 이름의 기능을 만든 제품에서 생성 명령이 거부한다. - 기능 테스트가 지워도 되는 문서를 읽으면 제거 드릴이 깨진다([structure.md](structure.md) 4절). - 테스트 작성의 편집 직후 규칙은 `.claude/rules/tests.md`다(Claude Code는 테스트 파일을 열 때 읽는다). diff --git a/scripts/create-feature.ts b/scripts/create-feature.ts index 63b02aac..c05d60a0 100644 --- a/scripts/create-feature.ts +++ b/scripts/create-feature.ts @@ -139,7 +139,7 @@ function baseOf(id: string): string { : id; } -function namesOf(id: string) { +export function namesOf(id: string) { const base = baseOf(id); const pascal = base .split("-") diff --git a/scripts/lib/generated-feature.ts b/scripts/lib/generated-feature.ts index 8430f836..02cec085 100644 --- a/scripts/lib/generated-feature.ts +++ b/scripts/lib/generated-feature.ts @@ -5,9 +5,11 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; +import { namesOf } from "../create-feature.ts"; import { localBuildEnvironment } from "./build-environment.ts"; import { linkFixtureNodeModules } from "./fixture-node-modules.ts"; import { REMOVAL_FIXTURE_COPY_TARGETS } from "./removal-fixture.ts"; +import { TEMPLATE_PROBE_PREFIX } from "./template-probe-features.ts"; /** * 2026-11-07. The template ships no feature. What needs one in a real build @@ -19,8 +21,19 @@ import { REMOVAL_FIXTURE_COPY_TARGETS } from "./removal-fixture.ts"; * (scripts/scale/browser-soak.ts, `buildWithGeneratedFeature`). A change of * the generator's output fails there. The `--keyed` write slice is the widest * one the command makes. + * + * 1112/08-02. The id begins with the reserved probe prefix: the copy holds + * the product's own features, and a product that had built `order-feature` + * made create:feature refuse this one. */ -export const GENERATED_FEATURE_ID = "order-feature"; +export const GENERATED_FEATURE_ID = `${TEMPLATE_PROBE_PREFIX}order-feature`; + +const NAMES = namesOf(GENERATED_FEATURE_ID); + +/** The key of one of the feature's words (`.list.title`). */ +export function generatedMessageKey(suffix: string): string { + return `${NAMES.camel}.${suffix}`; +} export type GeneratedRoute = Readonly<{ routeId: string; @@ -48,7 +61,7 @@ function node(root: string, args: readonly string[]): string { return result.stdout; } -/** The edit of a fixture build: `corepack pnpm create:feature order-feature --with-create --keyed`. */ +/** The edit of a fixture build: `corepack pnpm create:feature --with-create --keyed`. */ export async function addGeneratedFeature(root: string): Promise { node(root, ["scripts/generate-product-feature-index.ts"]); node(root, ["scripts/create-feature.ts", GENERATED_FEATURE_ID, "--with-create", "--keyed"]); @@ -62,23 +75,24 @@ export async function addGeneratedFeature(root: string): Promise { export function generatedFeature(root: string): GeneratedFeature { const feature = path.join(root, "src/features", GENERATED_FEATURE_ID); const module = (file: string) => JSON.stringify(pathToFileURL(path.join(feature, file)).href); + const { base, upper } = NAMES; const source = ` - const { ORDER_FEATURE_CONTRACT } = await import(${module("contracts/order-feature-contract.ts")}); - const { ORDER_MESSAGE_CATALOGS } = await import(${module("contracts/order-message-catalog.ts")}); - const { ORDER_LIST_ITEMS_CONTRACT } = await import(${module("contracts/order-contract-contribution.ts")}); + const { ${upper}_FEATURE_CONTRACT: CONTRACT } = await import(${module(`contracts/${GENERATED_FEATURE_ID}-contract.ts`)}); + const { ${upper}_MESSAGE_CATALOGS: CATALOGS } = await import(${module(`contracts/${base}-message-catalog.ts`)}); + const { ${upper}_LIST_ITEMS_CONTRACT: LIST_ITEMS } = await import(${module(`contracts/${base}-contract-contribution.ts`)}); const { API_BASE_URL } = JSON.parse(await (await import("node:fs/promises")).readFile("config/runtime/local.json", "utf8")); const route = (id) => ({ routeId: id, - path: ORDER_FEATURE_CONTRACT.routes[id].path, - chunkId: ORDER_FEATURE_CONTRACT.routes[id].chunkId, - moduleId: ORDER_FEATURE_CONTRACT.routeRuntimeContracts[id].moduleId, + path: CONTRACT.routes[id].path, + chunkId: CONTRACT.routes[id].chunkId, + moduleId: CONTRACT.routeRuntimeContracts[id].moduleId, }); process.stdout.write(JSON.stringify({ - list: route("ORDER_LIST"), - detail: route("ORDER_DETAIL"), - create: route("ORDER_CREATE"), - messages: ORDER_MESSAGE_CATALOGS, - api: new URL(ORDER_LIST_ITEMS_CONTRACT.contract.pathTemplate.slice(1), API_BASE_URL).href, + list: route("${upper}_LIST"), + detail: route("${upper}_DETAIL"), + create: route("${upper}_CREATE"), + messages: CATALOGS, + api: new URL(LIST_ITEMS.contract.pathTemplate.slice(1), API_BASE_URL).href, })); `; return JSON.parse(node(root, ["--input-type=module", "-e", source])) as GeneratedFeature; diff --git a/scripts/lib/template-probe-features.ts b/scripts/lib/template-probe-features.ts new file mode 100644 index 00000000..027a7f61 --- /dev/null +++ b/scripts/lib/template-probe-features.ts @@ -0,0 +1,49 @@ +import { namesOf } from "../create-feature.ts"; + +/** + * 1112/08-02. Feature ids the template's own tests and drills create in a + * copy of the repository. The copy holds the product's features, and + * create:feature refuses an id a feature there already has, or one with the + * same prefix. A template test that used the manual's example + * (`invoice-feature`) or a plain business word (`order-feature`) therefore + * failed FE-GATE-005 and FE-GATE-008 in every product that had built a + * feature by that name. Each id here begins with the prefix the template + * reserves for its probes; docs/manual/reference/create-feature.md tells a + * product not to use it. + */ +export const TEMPLATE_PROBE_PREFIX = "typecheck-probe-"; + +/** The feature the manual's code blocks are written for (docs/manual/01-add-a-feature.md). */ +export const MANUAL_EXAMPLE_FEATURE_ID = "invoice-feature"; +/** What tests/unit/manual-code-blocks.test.ts creates and renames the blocks to. */ +export const MANUAL_PROBE_FEATURE_ID = `${TEMPLATE_PROBE_PREFIX}${MANUAL_EXAMPLE_FEATURE_ID}`; +/** The sample tests/unit/template-feature-removal-documents.test.ts lists and deletes. */ +export const LISTED_SAMPLE_PROBE_FEATURE_ID = `${TEMPLATE_PROBE_PREFIX}listed-sample-feature`; +/** What FE-GATE-020's scaffold drill (scripts/test-feature-scaffold.ts, test:sample-removal) creates. */ +export const SCAFFOLD_PROBE_FEATURE_ID = `${TEMPLATE_PROBE_PREFIX}scaffold-feature`; +/** The scaffold drill's `--with-create --keyed` feature. */ +export const SCAFFOLD_WRITE_PROBE_FEATURE_ID = `${TEMPLATE_PROBE_PREFIX}scaffold-write-feature`; + +function escape(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); +} + +/** + * `text` written for feature `fromId`, with every spelling create:feature + * derives from an id (`INVOICE_`, `Invoice`, `invoice-`, `invoice`) moved to + * the spelling it derives from `toId`. Prose that uses the word moves too; + * what matters is that the names a block defines and the names it imports + * from the generated feature move together. + */ +export function renameFeatureText(text: string, fromId: string, toId: string): string { + const from = namesOf(fromId); + const to = namesOf(toId); + const spellings = new Map([ + [from.upper, to.upper], + [from.pascal, to.pascal], + [`${from.base}-`, `${to.base}-`], + [from.camel, to.camel], + ]); + const pattern = new RegExp([...spellings.keys()].map(escape).join("|"), "gu"); + return text.replace(pattern, (match) => spellings.get(match) ?? match); +} diff --git a/scripts/test-feature-scaffold.ts b/scripts/test-feature-scaffold.ts index 77dd67f7..8a1539b8 100644 --- a/scripts/test-feature-scaffold.ts +++ b/scripts/test-feature-scaffold.ts @@ -4,6 +4,10 @@ import { mkdir, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { loadCiGateContract } from "./contracts/ci-gates.ts"; +import { + SCAFFOLD_PROBE_FEATURE_ID, + SCAFFOLD_WRITE_PROBE_FEATURE_ID, +} from "./lib/template-probe-features.ts"; import { runScaffoldDrillCommand, scaffoldDrillCommands, @@ -37,9 +41,10 @@ import { * test:sample-removal repeats the generation after deleting the sample * (decision 4), which proves the command needs nothing from it. */ -const FEATURE_ID = "scaffold-feature"; +/** 1112/08-02. Reserved probe ids: the copy holds the product's own features. */ +const FEATURE_ID = SCAFFOLD_PROBE_FEATURE_ID; /** 1103/09-06. The `--with-create --keyed` slice, in its own context. */ -const WRITE_FEATURE_ID = "scaffold-write-feature"; +const WRITE_FEATURE_ID = SCAFFOLD_WRITE_PROBE_FEATURE_ID; const REPORT = "artifacts/tests/feature-scaffold.xml"; const pnpmCli = requireRemovalFixtureEnvironment("npm_execpath"); diff --git a/scripts/test-sample-removal.ts b/scripts/test-sample-removal.ts index e60d011d..87a0ade0 100644 --- a/scripts/test-sample-removal.ts +++ b/scripts/test-sample-removal.ts @@ -32,6 +32,7 @@ import { type RemovalCheck, } from "./lib/removal-fixture.ts"; import { REMOVABLE_TEMPLATE_FEATURES } from "./lib/removable-template-features.ts"; +import { SCAFFOLD_PROBE_FEATURE_ID } from "./lib/template-probe-features.ts"; /** * 09-07 (D-10). Removes one installed feature, `--feature=`, from a copy @@ -528,7 +529,7 @@ try { // 1103/09-06. With the write slice (NEVER), which needs nothing from // the sample either. const created = check("scaffold-create-feature", "create:feature", [ - "scaffold-feature", + SCAFFOLD_PROBE_FEATURE_ID, "--with-create", ]); checks.push(created); diff --git a/tests/e2e/generated-feature.spec.ts b/tests/e2e/generated-feature.spec.ts index f80d424f..d0fc977e 100644 --- a/tests/e2e/generated-feature.spec.ts +++ b/tests/e2e/generated-feature.spec.ts @@ -11,6 +11,7 @@ import { import { addGeneratedFeature, generatedFeature, + generatedMessageKey, routePath, type GeneratedFeature, } from "../../scripts/lib/generated-feature.ts"; @@ -122,10 +123,10 @@ async function signInAt(page: Page, path: string, heading: string) { await expect(page.getByRole("heading", { level: 1 })).toHaveText(heading); } -const openForm = (page: Page) => signInAt(page, routePath(feature.create), word("order.form.title")); +const openForm = (page: Page) => signInAt(page, routePath(feature.create), word(generatedMessageKey("form.title"))); const nameField = (page: Page) => - page.getByRole("textbox", { name: new RegExp(word("order.form.name"), "u") }); -const saveButton = (page: Page) => page.getByRole("button", { name: word("order.form.save") }); + page.getByRole("textbox", { name: new RegExp(word(generatedMessageKey("form.name")), "u") }); +const saveButton = (page: Page) => page.getByRole("button", { name: word(generatedMessageKey("form.save")) }); async function expectNoBlockingViolations(page: Page) { const results = await new AxeBuilder({ page }).withTags(WCAG_TAGS).analyze(); @@ -154,7 +155,7 @@ async function saveFromKeyboard(page: Page, firstAction: string) { test.describe("the route", () => { test("opens the protected list through the local demo sign-in", async ({ page }) => { await answerReads(page); - await signInAt(page, routePath(feature.list), word("order.list.title")); + await signInAt(page, routePath(feature.list), word(generatedMessageKey("list.title"))); // The closed menu drawer holds a second copy of the status (08-01). await expect( @@ -167,16 +168,16 @@ test.describe("the route", () => { // 08-04. Feature screens take their words from the catalog. test("draws its screens without Korean copy in en-US", async ({ page }) => { await answerReads(page); - await signInAt(page, routePath(feature.list), word("order.list.title")); + await signInAt(page, routePath(feature.list), word(generatedMessageKey("list.title"))); await page.getByRole("combobox", { name: "언어" }).first().selectOption("en-US"); const main = page.getByRole("main"); const english = feature.messages["en-US"]; - await expect(main.getByRole("heading", { level: 1 })).toHaveText(english["order.list.title"]!); + await expect(main.getByRole("heading", { level: 1 })).toHaveText(english[generatedMessageKey("list.title")]!); await expect(main).not.toContainText(/[가-힣]/u); - await main.getByRole("link", { name: english["order.list.create"]! }).click(); - await expect(main.getByRole("button", { name: english["order.form.save"]! })).toBeVisible(); + await main.getByRole("link", { name: english[generatedMessageKey("list.create")]! }).click(); + await expect(main.getByRole("button", { name: english[generatedMessageKey("form.save")]! })).toBeVisible(); await expect(main).not.toContainText(/[가-힣]/u); }); }); @@ -196,7 +197,7 @@ test.describe("the form", () => { await nameField(page).fill("Unsaved order"); await page .getByRole("navigation", { name: KO_MESSAGES["template.breadcrumb"] }) - .getByRole("link", { name: word("order.list.title") }) + .getByRole("link", { name: word(generatedMessageKey("list.title")) }) .click(); const dialog = page.getByRole("dialog", { name: KO_MESSAGES["form.unsaved.title"] }); @@ -331,7 +332,7 @@ test.describe("the save", () => { await page.keyboard.press("Enter"); - await expect(page.getByRole("heading", { level: 1 })).toHaveText(word("order.list.title")); + await expect(page.getByRole("heading", { level: 1 })).toHaveText(word(generatedMessageKey("list.title"))); await expect(page.getByRole("link", { name: ITEM.name })).toBeVisible(); expect(calls).toHaveLength(1); }); @@ -350,7 +351,7 @@ test.describe("accessibility", () => { ] as const) { test(`@a11y list ${state} state has no blocking violations`, async ({ page }) => { await answerReads(page, list); - await signInAt(page, routePath(feature.list), word("order.list.title")); + await signInAt(page, routePath(feature.list), word(generatedMessageKey("list.title"))); await expect(page.getByRole("main")).toContainText(visible); await expectNoBlockingViolations(page); }); diff --git a/tests/unit/manual-code-blocks.test.ts b/tests/unit/manual-code-blocks.test.ts index 43cf272e..c0182600 100644 --- a/tests/unit/manual-code-blocks.test.ts +++ b/tests/unit/manual-code-blocks.test.ts @@ -9,6 +9,11 @@ import { afterAll, describe, expect, it } from "vitest"; import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts"; import { REMOVAL_FIXTURE_COPY_TARGETS } from "../../scripts/lib/removal-fixture.ts"; import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts"; +import { + MANUAL_EXAMPLE_FEATURE_ID, + MANUAL_PROBE_FEATURE_ID, + renameFeatureText, +} from "../../scripts/lib/template-probe-features.ts"; /** * 2026-11-07. The template ships no sample feature: what the generated @@ -19,9 +24,15 @@ import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts"; * block goes to its path unchanged, and the app and test typecheck programs, * lint and the feature's tests run on it. A block that is a test runs as it * is; what the other blocks do is checked by tests/fixtures/manual-code-blocks. + * + * 1112/08-02. The copy holds the product's own features, and a product may + * well have built `invoice-feature`. So the copy gets the reserved probe + * feature instead, and every block and check is renamed to it on the way in + * (`renameFeatureText`): paths, constants, types and words alike. */ const MANUAL = "docs/manual"; -const FEATURE_ID = "invoice-feature"; +const FEATURE_ID = MANUAL_PROBE_FEATURE_ID; +const toProbe = (text: string) => renameFeatureText(text, MANUAL_EXAMPLE_FEATURE_ID, FEATURE_ID); const CHECKS = "tests/fixtures/manual-code-blocks"; const MARKED_BLOCK = /\n```tsx?\n([\s\S]*?)\n```/gu; @@ -100,18 +111,18 @@ describe("docs/manual code blocks, pasted into a generated feature", () => { expect(created.status, created.output).toBe(0); for (const [target, block] of blocks) { - const file = path.join(root, target); + const file = path.join(root, toProbe(target)); // A block adds a file; it never stands in for one the command wrote. expect(existsSync(file), `${target} exists before the block is pasted`).toBe(false); await mkdir(path.dirname(file), { recursive: true }); - await writeFile(file, block); + await writeFile(file, toProbe(block)); } const checks = (await readdir(CHECKS)).filter((name) => name.endsWith(".check.tsx")); expect(checks.length).toBeGreaterThan(0); for (const check of checks) { await writeFile( path.join(root, "tests/features", FEATURE_ID, check.replace(/\.check\.tsx$/u, ".test.tsx")), - (await readFile(path.join(CHECKS, check), "utf8")).replaceAll("{{feature}}", FEATURE_ID), + toProbe((await readFile(path.join(CHECKS, check), "utf8")).replaceAll("{{feature}}", MANUAL_EXAMPLE_FEATURE_ID)), ); } diff --git a/tests/unit/template-feature-removal-documents.test.ts b/tests/unit/template-feature-removal-documents.test.ts index 97871646..2a1b7332 100644 --- a/tests/unit/template-feature-removal-documents.test.ts +++ b/tests/unit/template-feature-removal-documents.test.ts @@ -16,6 +16,7 @@ import { REMOVAL_FIXTURE_DOCUMENT_TARGETS, } from "../../scripts/lib/removal-fixture.ts"; import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts"; +import { LISTED_SAMPLE_PROBE_FEATURE_ID } from "../../scripts/lib/template-probe-features.ts"; /** * 1105/14-01. A copy that deleted a sample listed in @@ -23,15 +24,18 @@ import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts"; * the FE-GATE-005 copy of it ("passes the documents as they are") wherever * the documents named the sample's folders. The template lists no sample * since 2026-11-07, so the copy here gets one: the feature `create:feature` - * writes, listed and named in a document, then deleted. + * writes, listed and named in a document, then deleted. Its id begins with + * the reserved probe prefix, so a product's own features never clash with it + * (1112/08-02). */ const CHECKER = "scripts/verify-documentation-readiness.ts"; /** What verify:documentation reads besides the code: the documents a drill copies. */ const DOCUMENTS = REMOVAL_FIXTURE_DOCUMENT_TARGETS; +const LISTED_SAMPLE_BASE = LISTED_SAMPLE_PROBE_FEATURE_ID.replace(/-feature$/u, ""); const LISTED_SAMPLE = Object.freeze({ - featureId: "listed-sample-feature", - contextDirectory: "src/contexts/listed-sample-context", + featureId: LISTED_SAMPLE_PROBE_FEATURE_ID, + contextDirectory: `src/contexts/${LISTED_SAMPLE_BASE}-context`, extraPaths: Object.freeze([]), scripts: Object.freeze([]), }); @@ -87,7 +91,8 @@ async function copyWithListedSample() { for (const entry of removableTemplateFeaturePaths(LISTED_SAMPLE)) { await rm(path.join(root, entry), { recursive: true, force: true }); } - await rm(path.join(root, "docs/accessibility/route-reviews/LISTED_SAMPLE_LIST.md"), { force: true }); + const listRoute = `${LISTED_SAMPLE_BASE.toUpperCase().replaceAll("-", "_")}_LIST`; + await rm(path.join(root, `docs/accessibility/route-reviews/${listRoute}.md`), { force: true }); expect(node(["scripts/generate-product-feature-index.ts"]).status).toBe(0); }, cleanUp: () => rm(parent, { recursive: true, force: true }), diff --git a/tests/unit/template-probe-features.test.ts b/tests/unit/template-probe-features.test.ts new file mode 100644 index 00000000..2afd684a --- /dev/null +++ b/tests/unit/template-probe-features.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from "vitest"; + +import { planFeature, type InstalledFacts } from "../../scripts/create-feature.ts"; +import { GENERATED_FEATURE_ID } from "../../scripts/lib/generated-feature.ts"; +import { + LISTED_SAMPLE_PROBE_FEATURE_ID, + MANUAL_EXAMPLE_FEATURE_ID, + MANUAL_PROBE_FEATURE_ID, + SCAFFOLD_PROBE_FEATURE_ID, + SCAFFOLD_WRITE_PROBE_FEATURE_ID, + TEMPLATE_PROBE_PREFIX, + renameFeatureText, +} from "../../scripts/lib/template-probe-features.ts"; + +/** + * 1112/08-02. The template's own tests add a feature to a copy of the + * repository, and that copy holds the product's features. create:feature + * refuses an id a feature there has, or one with the same prefix, so a + * template test that used the manual's example (`invoice-feature`) or a plain + * business word (`order-feature`) failed FE-GATE-005 and FE-GATE-008 in a + * product that had built a feature by that name. + */ +const PROBE_IDS = Object.freeze([ + GENERATED_FEATURE_ID, + MANUAL_PROBE_FEATURE_ID, + LISTED_SAMPLE_PROBE_FEATURE_ID, + SCAFFOLD_PROBE_FEATURE_ID, + SCAFFOLD_WRITE_PROBE_FEATURE_ID, +]); + +const TOPIC_SUFFIX = "abcdefghjkmnpqrstvwxyz0123"; + +/** A product that built features by the names a business app would pick. */ +const PRODUCT: InstalledFacts = Object.freeze({ + appIds: ["template-app"], + featureIds: [ + "invoice-feature", + "order-feature", + "orders-feature", + "scaffold-feature", + "listed-sample-feature", + "invoice", + "order", + ], + contexts: [ + { id: "invoice-context", routePath: "invoices/*" }, + { id: "order-context", routePath: "orders/*" }, + ], + contextDirectories: ["invoice-context", "order-context"], + routes: [ + { routeId: "INVOICE_LIST", path: "/invoices", chunkId: "route-invoice-list", navigationOrder: 50 }, + { routeId: "ORDER_LIST", path: "/orders", chunkId: "route-order-list", navigationOrder: 60 }, + ], + topics: [], + messageKeys: ["invoice.list.title", "order.list.title"], +}); + +/** The template as it ships: no feature. */ +const TEMPLATE: InstalledFacts = Object.freeze({ + appIds: ["template-app"], + featureIds: [], + contexts: [], + contextDirectories: [], + routes: [], + topics: [], + messageKeys: [], +}); + +describe("feature ids the template's tests create in a copy", () => { + it("all begin with the reserved probe prefix", () => { + for (const id of PROBE_IDS) expect(id.startsWith(TEMPLATE_PROBE_PREFIX), id).toBe(true); + expect(new Set(PROBE_IDS).size).toBe(PROBE_IDS.length); + }); + + it("are accepted in a product that built features by business names", () => { + for (const id of PROBE_IDS) { + expect(() => planFeature({ id, write: "KEYED" }, PRODUCT, () => TOPIC_SUFFIX), id).not.toThrow(); + } + }); +}); + +describe("renameFeatureText", () => { + it("moves every spelling of the manual's example to the probe's", () => { + const text = [ + "src/features/invoice-feature/presentation/use-invoice-list-filters.ts", + "INVOICE_LIST INVOICE_CREATE_EFFECT InvoiceProblem useInvoiceListFilters", + "invoiceListSearchSchema invoice.list.title /invoices invoice-create-v1", + ].join("\n"); + + expect(renameFeatureText(text, MANUAL_EXAMPLE_FEATURE_ID, MANUAL_PROBE_FEATURE_ID)).toBe( + [ + "src/features/typecheck-probe-invoice-feature/presentation/use-typecheck-probe-invoice-list-filters.ts", + "TYPECHECK_PROBE_INVOICE_LIST TYPECHECK_PROBE_INVOICE_CREATE_EFFECT TypecheckProbeInvoiceProblem useTypecheckProbeInvoiceListFilters", + "typecheckProbeInvoiceListSearchSchema typecheckProbeInvoice.list.title /typecheckProbeInvoices typecheck-probe-invoice-create-v1", + ].join("\n"), + ); + }); + + it("gives the names create:feature writes for the probe", () => { + const manual = planFeature({ id: MANUAL_EXAMPLE_FEATURE_ID, write: "NEVER" }, TEMPLATE, () => TOPIC_SUFFIX); + const probe = planFeature({ id: MANUAL_PROBE_FEATURE_ID, write: "NEVER" }, TEMPLATE, () => TOPIC_SUFFIX); + + expect( + [...manual.files.keys()].map((file) => + renameFeatureText(file, MANUAL_EXAMPLE_FEATURE_ID, MANUAL_PROBE_FEATURE_ID), + ), + ).toEqual([...probe.files.keys()]); + }); +});