diff --git a/.storybook/preview.tsx b/.storybook/preview.tsx index 2d0e8681..b920d0fc 100644 --- a/.storybook/preview.tsx +++ b/.storybook/preview.tsx @@ -86,7 +86,10 @@ const queryClient = createQueryClient(); const preview: Preview = { decorators: [ - (Story) => ( + // A page story (`parameters.page`, the galleries) draws its own + // `.ui-page`, as a route page does inside the shell's `main`; a component + // story gets a padded page around it. + (Story, context) => ( @@ -94,9 +97,15 @@ const preview: Preview = {
-
- -
+ {context.parameters["page"] === true ? ( +
+ +
+ ) : ( +
+ +
+ )} diff --git a/CHANGELOG.md b/CHANGELOG.md index 4691937d..b74de10f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,61 @@ - 괄호 안 ID는 리뷰 발견 ID다. `MMDD/NN-MM`으로 적는다. `MMDD`는 리뷰 폴더 `docs/reviews/YYYY-MM-DD-maturity-review/`의 월일이고, 근거와 재현 조건은 그 폴더의 영역 문서에 있다. 복사한 프로젝트가 README대로 `docs/reviews/`를 지웠다면 이 폴더와 `PRODUCT.md`는 원본 템플릿 repo에서 찾는다. 라운드마다 `NN-MM`을 새로 매기므로 같은 `14-02`라도 라운드가 다르면 다른 결함이다. `F-N`은 그 라운드 `FOLLOW-UP.md`의 ID다. 리뷰 README의 절은 `MMDD README N.N`으로 적고 다시 돌린 항목은 그 뒤에 `X2`처럼 번호를 붙인다. 영역 문서가 따로 매긴 ID는 `MMDD NN 영역 P-NN-NN`, 짝 백엔드 리뷰의 ID는 `백엔드 리뷰 MMDD/NN-MM`으로 적는다. `tests/unit/changelog-review-ids.test.ts`가 라운드 없는 ID와 이 꼴을 벗어난 참조를 막는다. - 0.2.0의 커밋 해시는 브랜치 `fix/maturity-review-2026-09-25`에서 만들었고, `main`에서도 같은 해시로 찾을 수 있다(2026-11-03에 52개 모두 확인). 그 뒤 절은 절 머리에 범위(기준 커밋과 브랜치)를 적고, 그 절의 해시는 모두 그 범위에 있다. 통합에서 해시를 다시 쓴 뒤(fixup 접기, rebase)에는 절의 해시와 범위 커밋 본문의 해시를 `git merge-base --is-ancestor <해시> <브랜치 끝>`으로 하나씩 대조하고, 결과를 그 라운드 리뷰 README의 조치 절에 적는다. 1105 통합은 이 대조를 하지 않아, 올린 커밋 `287dc6f`의 본문이 다시 짓기 전 해시 둘을 가리킨다. 맞는 해시는 그 라운드 리뷰 README의 D7 행에 있다 (1106/14-02, 1105 README 16.2). 0.2.0의 커밋 제목은 라운드 없이 ID만 적었다(`git log --grep '03-03'`). +## 미출시 — `48c7695b` → 정리 단계 + +2026-11-07 소유자가 지시한 저장소 정리다(design-docs `repo-structure/04-frontend-layout.md` 9.2절, 결정은 `repo-structure/README.md` 3.4절). 범위는 `main` `48c7695b`(PR #9 병합) 다음부터다. 1단계(PR #11, `85f941c4`~`121e1125`, `main` `f33e4778`에 합침)와 2단계(브랜치 `chore/layout-2-sample-removal`, `c7e80f2f`부터 브랜치 끝까지)를 담는다. 3단계(합치기)는 아직 없다. 기준점 `48c7695b`를 빼면 이 절의 해시는 모두 이 범위에 있다. + +### 먼저 할 일 (BREAKING) + +아래 절의 "먼저 할 일"을 마친 뒤 순서대로 한다. 단계 끝의 괄호는 아래 표의 근거 커밋이다. 두 다운스트림 코드에 적용해 게이트를 돌려 보지는 않았다(알려진 제한). + +#### 옮기기 전 + +- 템플릿은 참조 기능(`src/features/reference-feature/`, context `src/contexts/reference-context/`)과 예제 화면(`src/features/platform-examples-feature/`, context `src/contexts/platform-examples-context/`)을 지웠다. 받으면 템플릿 쪽 파일의 삭제가 함께 온다. +- 자기 프로젝트가 그 폴더를 고쳐 남겨 두었는지 본다: `git log --oneline <마지막 동기화 기준>..HEAD -- src/features/reference-feature tests/features/reference-feature src/features/platform-examples-feature`. 고친 파일은 병합에서 수정/삭제 충돌이 된다. + +#### 옮기는 법 + +1. **샘플 사본을 쓰지 않으면 지운다.** 충돌한 파일은 삭제 쪽을 고른다(`git rm`). 함께 지울 것: `tests/features/reference-feature/`, `tests/features/platform-examples-feature/`, `tests/e2e/reference-form.spec.ts`·`reference-route.spec.ts`·`reference-save.spec.ts`, 수동 접근성 기록 7개(`artifacts/tests/a11y-manual/REFERENCE_RESOURCE_{LIST,DETAIL,FORM,STATUS}.md`, `EXAMPLES_{UI,STATES,AUTH}.md`), 런타임 프로필 4개와 `public/config.json`의 `FEATURE_OVERRIDES."reference-feature"`, `package.json`의 `test:reference-feature`. 그다음 `corepack pnpm generate:feature-index`, `node scripts/write-dev-release-manifest.ts`를 돈다 (`e3c8db48`) +2. **샘플 사본을 남겨 쓰는 프로젝트(tech-log의 참조 기능 12파일 등)는 자기 기능으로 옮긴다.** 남길 파일이 기대던 템플릿 쪽 파일(위 1단계 목록, 지운 테스트, `TEMPLATE_FIXTURE` 출처)은 다시 생기지 않는다. 계약 기여의 출처를 `EXTERNAL_PACKAGE`로 바꾸지 않았으면 계약 조립이 `: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to only`로 거부한다. 지울 예정이면 `scripts/lib/removable-template-features.ts`에 적는다. 그러면 `test:sample-removal`(FE-GATE-020)이 그 기능을 지운 사본에서 게이트를 돌고, 문서는 그 경로를 지운 뒤에도 통과한다 (`e3c8db48`) +3. **레지스트리 기준선을 다시 승인한다.** 템플릿 기준선은 샘플의 라우트·operation·스키마·무효화 행을 뺀 것이다. 자기 기준선을 쓰는 프로젝트는 병합 뒤 자기 행으로 다시 받는다: `REGISTRY_BASELINE_OWNER=<담당> REGISTRY_BASELINE_REASON="<이유>" corepack pnpm update:registry-baseline`. 행을 빼는 것은 breaking이라 승인 없이 `check:registries`가 `breaking change missing evidence:`로 실패한다 (`e3c8db48`) +4. **CI 계약 기준선과 workflow를 자기 값으로 다시 기록한 프로젝트는 다시 기록한다.** FE-GATE-007에서 `test:reference-feature` 명령과 그 산출물이, FE-GATE-009·028에서 지운 라우트의 수동 접근성 기록 산출물 4개가 빠졌다. `CI_CONTRACT_BASELINE_OWNER=<팀> CI_CONTRACT_BASELINE_REASON=<이유> corepack pnpm update:ci-contract-baseline`, 그다음 `corepack pnpm generate:ci-workflow` (`e3c8db48`) +5. **초기 JS 기록을 다시 쓴다.** `config/scale/feature-shape-ceilings.json`의 `initialJavascript`에 `firstFeatureGzipBytes`가 더해졌고, 측정은 참조 기능 대신 생성 기능을 복사해 잰다. `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`. 다시 쓰지 않으면 `test:unit`이 기록과 빌드가 다르다며 실패한다 (`b2042de9`) +6. **`src/features/` 아래에 기능이 아닌 폴더를 두었으면 밖으로 옮긴다.** 생성기는 `NOT_A_FEATURE` 표식을 더 읽지 않는다. 선언 없는 폴더는 `src/features/ has no feature-module.ts; add one, or keep code that is no feature outside src/features`로 실패한다. 템플릿의 local-draft 샘플은 `tests/fixtures/indexeddb-consumer/`로 옮겼다 (`b72cd7d4`) + +#### 옮긴 뒤 확인 + +1. 로컬 merge 게이트 14개를 돈다. 이 절 때문에 먼저 볼 것: `check:registries`(3단계), `check:ci`(4단계), `test:unit`(5단계), `generate:feature-index`(6단계), `verify:documentation`(지운 샘플 경로를 적은 자기 문서), `test:sample-removal`(인자 없이 돌면 목록이 빈 템플릿에서는 `SKIP`을 출력한다). +2. 시각 골든: 갤러리 두 장(`design-system-gallery-dark`, `state-surfaces-light`)은 이제 Storybook 정적 빌드의 story를 찍는다. 자기 골든을 다시 찍은 프로젝트는 `corepack pnpm test:visual:update`로 그 둘을 다시 찍는다. +3. `/examples/ui`·`/examples/states`·`/examples/auth`를 열던 자기 e2e는 플랫폼 라우트나 자기 화면으로 옮긴다. 템플릿의 그런 spec은 옮겼다(아래 표). + +### 보안·계약 변경 + +| 표시 | 변경 | 영향 경로 | 커밋 | +|---|---|---|---| +| [계약] **BREAKING** | 참조 기능과 예제 화면(`/examples/ui`, `/examples/states`, `/examples/auth`)을 지웠다. 소유자 결정(2026-11-07): 샘플은 매뉴얼과 `create:feature`가 생겼으니 지운다. 샘플이 맡던 시험 대상은 먼저 옮겼다(아래 행들). 레지스트리 기준선과 CI 계약 기준선을 다시 승인했다. 위 "먼저 할 일" 1~4 | `src/features/`, `src/contexts/`, `tests/features/`, `config/contracts/registry-baseline.json`, `config/ci/`, `config/runtime/`, `public/` | `e3c8db48` | +| [계약] | `scripts/lib/removable-template-features.ts` 목록이 비었다. 장치는 남는다: 프로젝트가 자기 샘플을 적으면 `test:sample-removal`(인자 없음, FE-GATE-020)이 하나씩 지워 게이트를 돈다. 목록이 비면 `sample removal: SKIP`을 출력하고 보고서에 건너뛴 사례 하나를 남긴다. `--feature=`의 보고서는 늘 `artifacts/tests/feature-removal-.xml`이다 | `scripts/test-sample-removal.ts`, `scripts/lib/removable-template-features.ts` | `e3c8db48` | +| [계약] | 갤러리를 Storybook story로 옮겼다(`src/presentation/design-system/galleries.stories.tsx`). visual 골든 두 장이 Storybook 정적 빌드를 찍는다. visual 설정이 두 번째 web server(정적 workshop, 포트 변수 `TEST_VISUAL_WORKSHOP_PORT`)를 띄운다. 디자인 토큰 색 하나(`--color-action`)를 바꾸면 새 골든이 어두운 쪽 42,313px, 밝은 쪽 22,359px 차이로 실패하는 것을 확인했다. 옛 골든도 같은 변이를 같은 크기로 잡았다. 갤러리의 브라우저 상호작용 검사는 `tests/storybook/galleries.spec.ts`로 옮겼다. 위 "옮긴 뒤 확인" 2 | `.storybook/preview.tsx`, `playwright.visual.config.ts`, `tests/visual/`, `tests/storybook/`, `scripts/lib/storybook-static.ts` | `c7e80f2f` | +| [계약] | 기능 하나가 실제 브라우저에서 라우트·폼·저장까지 되는지는 `create:feature --with-create --keyed` 기능을 넣은 저장소 사본의 빌드가 맡는다(`tests/e2e/generated-feature.spec.ts`, `scripts/lib/generated-feature.ts`). 오래된 탭의 청크 복구 시험도 그 기능의 목록 라우트를 쓴다. 생성기 출력이 바뀌면 FE-GATE-008이 잡는다 | `tests/e2e/`, `scripts/lib/generated-feature.ts` | `794a51a3` | +| [계약] | 규모 측정이 참조 기능 대신 생성 기능을 복사해 잰다(`planShapeFeatures`). `initialJavascript`에 `firstFeatureGzipBytes`(기능이 없는 템플릿에 첫 기능을 더할 때의 비용)가 생겼고, context 비용은 둘째 기능을 새 context에 둘 때와 같은 context에 둘 때의 차이다. 기록: 템플릿 194,354 B·17파일, 첫 기능 6,327 B, 기능 하나 539 B, context 하나 4 B. 성장 기준선(0·25·100개)도 다시 쟀다. 위 "먼저 할 일" 5 | `scripts/scale/measure-feature-shape-growth.ts`, `config/scale/` | `b2042de9`, `9c87cc4d` | +| [계약] | 생성기가 `NOT_A_FEATURE` 표식을 읽지 않는다. local-draft 샘플은 IndexedDB 소비자 시험 fixture(`tests/fixtures/indexeddb-consumer/`)가 됐다. 위 "먼저 할 일" 6 | `scripts/generate-product-feature-index.ts`, `recipes/frontend-capabilities/indexeddb-feature-capability.ts` | `b72cd7d4` | +| [계약] | 브라우저 soak(`scripts/scale/browser-soak.ts`, nightly 밖)이 기본으로 생성 기능을 넣은 빌드를 만들어 그 목록 라우트에서 실패하는 백엔드를 관찰한다. `--dist`를 주면 `--feature-route`도 준다. 결과 칸 이름이 `featureVisits`·`settledFeatureVisits`·`apiRequestsPerFeatureVisit`으로 바뀌었다 | `scripts/scale/browser-soak.ts` | `e3c8db48` | + +### 그 밖의 수정 + +- 정리 1단계: 읽는 곳 없는 산출물 13개를 지우고 `artifacts/`를 폴더째 무시한다(`85f941c4`). 아무도 읽지 않는 `config/schemas/` JSON Schema 4개를 지웠다(`0805910c`). 루트 `tasks/`와 `.superpowers/` 기록을 `docs/history/`로 옮겼다(`429b8d88`). nginx 설정 예시를 지우고 호스트가 지킬 조건만 남겼다(`121e1125`). +- `/examples/ui`·`/examples/states`를 열던 e2e(반응형, 스크롤 복원, 타이포그래피, 건너뛰기 링크)는 홈과 `/examples/platform`으로 옮겼다 (`e7210c71`). +- 매뉴얼(`docs/manual/`)의 예제 칸은 생성기 출력 경로와 매뉴얼 안 코드 조각을 가리킨다. 코드 조각 일곱 개(problem details 백엔드의 분류와 매핑, 도메인 모델, 검색값 읽기, 실패 행동, 403 페이지 시험)는 `tests/unit/manual-code-blocks.test.ts`가 생성 기능 위에서 타입 검사·lint·아키텍처 검사·동작 시험을 돌린다. problem details 예는 소유자 결정대로 02 결정표 4절에 있다 (`01cac930`). +- 기능 스위치 시험(`tests/component/product-feature-switch.test.tsx`)과 홈 시작 링크의 스위치 시험은 시험 전용 fixture 기능으로 옮겼다 (`e3c8db48`). +- 라우트 런타임 음성 fixture(`tests/fixtures/typecheck/invalid-route-runtime.ts`)는 라우트 하나만 뺀다. 빠진 라우트 수에 따라 TS2739와 TS2740으로 갈리던 진단이 TS2741 하나가 됐고 FE-GATE-003의 기대 진단도 바꿨다. 라우트가 3개로 줄자 옛 기대(TS2740)가 어긋났다 (`e47a0ab2`). + +### 알려진 제한 + +- 두 다운스트림에 시험 병합을 하지 않아 충돌 수를 모른다(S4 가정 F4). +- 성능 lab(FE-GATE-026)의 기능 라우트 측정(`featureRouteInteractionMs`)은 템플릿에 공개 기능 라우트가 없어 `measured: false`다. 제품 기능이 생기면 잰다. +- `TEMPLATE_FIXTURE` 출처와 `REFERENCE_EXTERNAL_BEARER` 별칭이 플랫폼 코드에 남았다. 쓰는 기능이 없다. +- visual 골든의 픽셀 비교는 색 허용치(`threshold` 0.2)를 넘지 않는 미세한 토큰 변경(예: 어두운 테마 `--color-danger` red-500 → red-600)을 잡지 못한다. 옛 골든도 같았다. + ## 미출시 — `bbde570` → 브랜치 `fix/maturity-review-2026-11-06` 2026-11-06 성숙도 리뷰(`docs/reviews/2026-11-06-maturity-review/`) 조치다. 범위는 아래 절의 끝 `bbde570`(PR B, PR #7)부터 브랜치 `fix/maturity-review-2026-11-06`의 끝까지다. 리뷰 기록 커밋 `302d3a5` 위에 조치 브랜치 9개를 합치고, 합친 빌드로 초기 JS 기록을 다시 적었다(`5cfc3a6`). 기준점 `bbde570`을 빼면 이 절의 해시는 모두 이 범위에 있다. PR B는 아직 `main`에 없다. 아래 절을 아직 받지 않은 프로젝트는 아래 절부터 받는다. diff --git a/PRODUCT.md b/PRODUCT.md index 5d612657..d6263b02 100644 --- a/PRODUCT.md +++ b/PRODUCT.md @@ -8,7 +8,7 @@ web ## Users -- **템플릿을 가져다 쓰는 개발자**: 이 템플릿으로 새 서비스를 빠르게 시작하는 사람입니다. 예제 화면(홈, 플랫폼 구성, UI 구성요소, 화면 상태, 인증 연동, Reference feature)은 이 사람이 실행 구조와 공통 동작을 확인하는 용도입니다. +- **템플릿을 가져다 쓰는 개발자**: 이 템플릿으로 새 서비스를 빠르게 시작하는 사람입니다. 기본 화면(홈, 플랫폼 구성)과 Storybook 갤러리(UI 구성요소, 화면 상태)는 이 사람이 실행 구조와 공통 동작을 확인하는 용도입니다. - **파생 서비스의 최종 사용자**: 디자인 시스템(토큰, 프리미티브, 패턴, 레이아웃, 페이지 템플릿)은 이 템플릿으로 만든 서비스를 실제로 쓰는 사람을 기준으로 합니다. ## Product Purpose @@ -30,7 +30,7 @@ web - 하나의 디자인 시스템으로 세 종류의 서비스를 받칩니다. 업무용·관리 도구(대시보드, 어드민, 설정), 일반 사용자용 웹 서비스, 소개·랜딩 페이지입니다. - 디자인 시스템 위치는 `src/presentation/design-system/`입니다. 토큰은 primitive → semantic → component 세 단계로 파생됩니다(`tokens/primitive.css`, `semantic.css`, `component.css`). - 시각 회귀 골든이 `tests/visual/__snapshots__/`에 있습니다. 화면을 바꾸면 골든도 의도적으로 갱신해야 합니다. -- 참조 기능(`src/features/reference-feature/`)은 `test:sample-removal`로 지울 수 있습니다. 예제 화면 3개(`/examples/ui`, `states`, `auth`)도 기능 `platform-examples-feature`라서 같은 드릴(`test:sample-removal -- --feature=platform-examples-feature`)로 지울 수 있습니다. 플랫폼 구성 화면(`/examples/platform`)과 홈은 기본 구성이고 제거 드릴이 없습니다. 그래서 예제 화면 3개에만 넣은 디자인은 예제를 지운 파생 서비스에서 함께 사라지고, 홈과 플랫폼 구성 화면에 넣은 디자인은 남습니다. +- 템플릿에는 샘플 기능이 없습니다(참조 기능과 예제 화면은 2026-11-07에 지웠습니다). 기능은 `create:feature`로 만듭니다. 디자인 시스템 갤러리와 화면 상태 갤러리는 Storybook story(`src/presentation/design-system/galleries.stories.tsx`)이고 시각 회귀 골든의 대상입니다. 플랫폼 구성 화면(`/examples/platform`)과 홈은 기본 구성입니다. 그래서 갤러리와 홈, 플랫폼 구성 화면에 넣은 디자인은 파생 서비스에 남습니다. - 어떤 서비스가 먼저 만들어질지, 서비스별 우선순위는 아직 정하지 않았습니다. ## Brand Commitments diff --git a/README.md b/README.md index b3ed6b05..8b0d536b 100644 --- a/README.md +++ b/README.md @@ -87,8 +87,8 @@ persistent `system` / `light` / `dark` theme selector, and a language selector. The route list is `ROUTE_REGISTRY` (`src/features/installed-feature-contracts.ts`): the platform routes of `src/contracts/routes.ts` plus the routes of every -installed feature, the removable reference feature included. The platform -overview page (`/examples/platform`) shows the composed list at runtime, so +installed feature. The template installs none: `corepack pnpm create:feature` +adds one (`docs/manual/`). The platform overview page (`/examples/platform`) shows the composed list at runtime, so this README keeps no copy of it and adding a feature does not edit it. `AUTH_MODE=demo` is credential-free and accepted only in local/development @@ -105,9 +105,9 @@ design documents use; the next table maps them. | Tier | What it covers | Status words | | --- | --- | --- | -| Default | In the default build and covered by the merge gates: the application shell and example routes, the REST HTTP executor, TanStack Query server state, Local/Session Storage registries, cross-tab invalidation, runtime config profiles and the release manifest check, `AUTH_MODE=external` (`demo` only in local/development), the typed message catalog, and the removable reference feature. `dist/` is served by a static host ([`docs/architecture/static-delivery.md`](docs/architecture/static-delivery.md)) | `COMPOSED` | +| Default | In the default build and covered by the merge gates: the application shell and example routes, the REST HTTP executor, TanStack Query server state, Local/Session Storage registries, cross-tab invalidation, runtime config profiles and the release manifest check, `AUTH_MODE=external` (`demo` only in local/development), the typed message catalog, and `create:feature`, which writes a feature that passes the merge gates. `dist/` is served by a static host ([`docs/architecture/static-delivery.md`](docs/architecture/static-delivery.md)) | `COMPOSED` | | Optional (recipe) | Not installed. A project copies one of the recipes in `config/recipes/frontend-capability-recipes.json` and narrows it ([`docs/architecture/optional-adapter-recipes.md`](docs/architecture/optional-adapter-recipes.md)). `realtime`, `offline-indexeddb`, `service-worker-pwa` and `file-transfer` also ship a tested reference runtime that the default build leaves out | `RECIPE_AVAILABLE`, `NOT_INSTALLED`, `AVAILABLE_NOT_COMPOSED` | -| Experimental | Designed and decided, but the runtime is missing or unfinished; finish it before building on it. GraphQL, gRPC-Web, Connect-Web and Protobuf adapters, Range resumable download, IndexedDB query persistence, the local preview decode-safety probe. `src/features/local-draft-feature` is an architecture sample, not installed | `DESIGNED_NOT_IMPLEMENTED` | +| Experimental | Designed and decided, but the runtime is missing or unfinished; finish it before building on it. GraphQL, gRPC-Web, Connect-Web and Protobuf adapters, Range resumable download, IndexedDB query persistence, the local preview decode-safety probe | `DESIGNED_NOT_IMPLEMENTED` | | Not supported | Deliberately not selected, or browsers cannot guarantee it: SSR, app-managed background upload and download, directory selection, persistent file handles, product query persistence, exactly-once delivery between tabs | `NOT_SELECTED`, `PLATFORM_LIMITED` | The rows come from @@ -121,7 +121,7 @@ and | `COMPOSED` | capability ledger, design documents | wired into the default production path | Default | | `INSTALLED` | a project's own recipe catalog (step 10 of the recipe procedure) | the project added the recipe | Default, for that project | | `RECIPE_AVAILABLE` | recipe catalog `status` | a recipe exists to copy; nothing is installed | Optional | -| `NOT_INSTALLED` | recipe catalog `defaultStatus`; a declared feature the build or `FEATURE_OVERRIDES` left out. A sample directory that is no feature at all carries a `src/features//NOT_A_FEATURE` marker file instead | not part of the build | Optional (recipe) or Experimental (feature) | +| `NOT_INSTALLED` | recipe catalog `defaultStatus`; a declared feature the build or `FEATURE_OVERRIDES` left out | not part of the build | Optional (recipe) or Experimental (feature) | | `AVAILABLE_NOT_COMPOSED` | capability ledger; recipe `referenceRuntime.status` | code and tests exist; the default build leaves it out | Optional | | `DESIGNED_NOT_IMPLEMENTED` | capability ledger, design documents | design approved, runtime missing | Experimental | | `NOT_SELECTED` | capability ledger, design documents | deliberately not chosen | Not supported | @@ -173,12 +173,13 @@ Domain code lives inside each feature; there is no top-level domain folder. See `docs/architecture/frontend-application-foundation.md`, `docs/architecture/overview.md`, `docs/architecture/layers.md`, and -`docs/architecture/starter-experience.md`. The removable vertical slice is -under `src/features/reference-feature`; its domain, application input, HTTP -binding, contracts, route runtime, and presentation own their contributions. -The central installed catalogs only aggregate selected contributions. The -generic starter routes continue to typecheck, test, and build after that -feature is removed. +`docs/architecture/starter-experience.md`. A feature is a vertical slice under +`src/features/`; its domain, application input, HTTP binding, contracts, +route runtime, and presentation own their contributions. The central installed +catalogs only aggregate selected contributions. The template ships no feature +(its reference sample and example screens were deleted on 2026-11-07): +`corepack pnpm create:feature ` writes one, and the generic starter routes +typecheck, test, and build without any. ### Platform capability review @@ -229,15 +230,15 @@ reads them, except the one file noted below | `CLAUDE.md` | review instructions for the template repository itself; replace it with your own | | `PRODUCT.md` | product context of the template itself (users, purpose, principles) for design tools; replace it with your product's | -The reference feature is not in this list: deleting its directory alone -leaves tests, policy entries and CI scripts behind that fail the gates. -`scripts/test-sample-removal.ts` removes it from a copy of -the repository and lists everything that has to go with it (its header comment, -and the files outside the feature's folders in -`scripts/lib/removable-template-features.ts`); do the same in your project and -run the gates. The documents keep naming the sample's paths: the documentation -check accepts them once `src/features/reference-feature/feature-module.ts` is -gone. +A feature is not in this list: deleting its directory alone leaves tests, +policy entries and CI scripts behind that fail the gates. +`corepack pnpm test:sample-removal -- --feature=` removes it from a copy of +the repository and lists everything that has to go with it (the header comment +of `scripts/test-sample-removal.ts`); do the same in your project and run the +gates. A sample your project keeps for a while can be listed in +`scripts/lib/removable-template-features.ts`: the drill then removes it without +`--feature`, and the documentation check accepts its paths once its +`feature-module.ts` is gone. ## Verification diff --git a/artifacts/tests/a11y-manual/EXAMPLES_AUTH.md b/artifacts/tests/a11y-manual/EXAMPLES_AUTH.md deleted file mode 100644 index 8c6efa23..00000000 --- a/artifacts/tests/a11y-manual/EXAMPLES_AUTH.md +++ /dev/null @@ -1,18 +0,0 @@ -# EXAMPLES_AUTH accessibility review - -Status: pending-manual-review -Route ID: EXAMPLES_AUTH -Release ID: -Reviewer: -Reviewed at: -Signature: -Attestation: pending -M1 Keyboard: pending -M2 Visible focus: pending -M3 Route focus: pending -M4 Modal focus: not-applicable (no modal on this route) -M5 Error association: not-applicable (no form error on this route) -M6 Color signal: pending -M7 Reduced motion: pending -Screen reader: pending -Notes: Review session state announcements and unavailable external-integration behavior. diff --git a/artifacts/tests/a11y-manual/EXAMPLES_STATES.md b/artifacts/tests/a11y-manual/EXAMPLES_STATES.md deleted file mode 100644 index b071073a..00000000 --- a/artifacts/tests/a11y-manual/EXAMPLES_STATES.md +++ /dev/null @@ -1,18 +0,0 @@ -# EXAMPLES_STATES accessibility review - -Status: pending-manual-review -Route ID: EXAMPLES_STATES -Release ID: -Reviewer: -Reviewed at: -Signature: -Attestation: pending -M1 Keyboard: pending -M2 Visible focus: pending -M3 Route focus: pending -M4 Modal focus: not-applicable (no modal on this route) -M5 Error association: not-applicable (no form error on this route) -M6 Color signal: pending -M7 Reduced motion: pending -Screen reader: pending -Notes: Review loading, refresh, empty, error, authentication, forbidden, and not-found announcements. diff --git a/artifacts/tests/a11y-manual/EXAMPLES_UI.md b/artifacts/tests/a11y-manual/EXAMPLES_UI.md deleted file mode 100644 index 6f89235c..00000000 --- a/artifacts/tests/a11y-manual/EXAMPLES_UI.md +++ /dev/null @@ -1,18 +0,0 @@ -# EXAMPLES_UI accessibility review - -Status: pending-manual-review -Route ID: EXAMPLES_UI -Release ID: -Reviewer: -Reviewed at: -Signature: -Attestation: pending -M1 Keyboard: pending -M2 Visible focus: pending -M3 Route focus: pending -M4 Modal focus: pending -M5 Error association: pending -M6 Color signal: pending -M7 Reduced motion: pending -Screen reader: pending -Notes: Review form primitives, Menu/Tabs keyboard behavior, Toast announcements, Tooltip supplemental copy, text-field error association and modal focus containment/restoration. diff --git a/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_DETAIL.md b/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_DETAIL.md deleted file mode 100644 index 81ebaae7..00000000 --- a/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_DETAIL.md +++ /dev/null @@ -1,18 +0,0 @@ -# REFERENCE_RESOURCE_DETAIL accessibility review - -Status: pending-manual-review -Route ID: REFERENCE_RESOURCE_DETAIL -Release ID: -Reviewer: -Reviewed at: -Signature: -Attestation: pending -M1 Keyboard: pending -M2 Visible focus: pending -M3 Route focus: pending -M4 Modal focus: not-applicable (no modal on this route) -M5 Error association: not-applicable (no form error on this route) -M6 Color signal: pending -M7 Reduced motion: pending -Screen reader: pending -Notes: Human review pending. diff --git a/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_FORM.md b/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_FORM.md deleted file mode 100644 index e78d1859..00000000 --- a/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_FORM.md +++ /dev/null @@ -1,18 +0,0 @@ -# REFERENCE_RESOURCE_FORM accessibility review - -Status: pending-manual-review -Route ID: REFERENCE_RESOURCE_FORM -Release ID: -Reviewer: -Reviewed at: -Signature: -Attestation: pending -M1 Keyboard: pending -M2 Visible focus: pending -M3 Route focus: pending -M4 Modal focus: pending -M5 Error association: pending -M6 Color signal: pending -M7 Reduced motion: pending -Screen reader: pending -Notes: Human review pending. diff --git a/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_LIST.md b/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_LIST.md deleted file mode 100644 index 74e9ae65..00000000 --- a/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_LIST.md +++ /dev/null @@ -1,18 +0,0 @@ -# REFERENCE_RESOURCE_LIST accessibility review - -Status: pending-manual-review -Route ID: REFERENCE_RESOURCE_LIST -Release ID: -Reviewer: -Reviewed at: -Signature: -Attestation: pending -M1 Keyboard: pending -M2 Visible focus: pending -M3 Route focus: pending -M4 Modal focus: not-applicable (no modal on this route) -M5 Error association: not-applicable (no form error on this route) -M6 Color signal: pending -M7 Reduced motion: pending -Screen reader: pending -Notes: Human review pending. diff --git a/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_STATUS.md b/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_STATUS.md deleted file mode 100644 index 93e37c45..00000000 --- a/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_STATUS.md +++ /dev/null @@ -1,18 +0,0 @@ -# REFERENCE_RESOURCE_STATUS accessibility review - -Status: pending-manual-review -Route ID: REFERENCE_RESOURCE_STATUS -Release ID: -Reviewer: -Reviewed at: -Signature: -Attestation: pending -M1 Keyboard: pending -M2 Visible focus: pending -M3 Route focus: pending -M4 Modal focus: not-applicable (no modal on this route) -M5 Error association: not-applicable (no form error on this route) -M6 Color signal: pending -M7 Reduced motion: pending -Screen reader: pending -Notes: Human review pending. diff --git a/config/ci/contract-baseline.json b/config/ci/contract-baseline.json index 7e1243d0..439cde3c 100644 --- a/config/ci/contract-baseline.json +++ b/config/ci/contract-baseline.json @@ -1,11 +1,11 @@ { "schemaVersion": 1, "owner": "DongHyeonka", - "reason": "1106/13-01: FE-GATE-027 runs the advisory scan before the release admission", + "reason": "2026-11-07 소유자 결정: 템플릿 샘플 삭제. 참조 기능 시험 명령과 그 산출물, 지운 라우트의 수동 a11y 기록 산출물 4개를 뺀다", "gates": 27, - "commands": 100, - "commandReferences": 104, - "artifacts": 110, + "commands": 99, + "commandReferences": 103, + "artifacts": 105, "stages": 5, - "gateShapeSha256": "7f6f3d975c62c022d6a6f8b5f39562f73de9ca0f22aa3d086ac28959e50fa93e" + "gateShapeSha256": "df584fba26f8448c6a77638351c6906ed91869da82e20f12ac71ea7b2037c989" } diff --git a/config/ci/gates.json b/config/ci/gates.json index 500fca74..ab728fce 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -144,7 +144,7 @@ "script": "check:types:fixture:route-runtime", "expect": "fail", "expectedExitCode": 1, - "expectedDiagnosticId": "error TS2740:" + "expectedDiagnosticId": "error TS2741:" }, { "id": "check-types-fixture-page-action", @@ -238,11 +238,6 @@ "script": "test:http-scenario-evidence", "expect": "pass" }, - { - "id": "test-reference-feature", - "script": "test:reference-feature", - "expect": "pass" - }, { "id": "test-recipes", "script": "test:recipes", @@ -1028,15 +1023,6 @@ "test-http-scenario-evidence" ] }, - { - "id": "artifact-artifacts-tests-reference-feature-xml", - "path": "artifacts/tests/reference-feature.xml", - "schemaId": "junit", - "production": "command-generated", - "producerCommandIds": [ - "test-reference-feature" - ] - }, { "id": "artifact-artifacts-tests-optional-recipes-xml", "path": "artifacts/tests/optional-recipes.xml", @@ -1163,30 +1149,6 @@ "schemaId": "markdown", "production": "source-controlled" }, - { - "id": "artifact-artifacts-tests-a11y-manual-EXAMPLES-UI-md", - "path": "artifacts/tests/a11y-manual/EXAMPLES_UI.md", - "schemaId": "markdown", - "production": "source-controlled" - }, - { - "id": "artifact-artifacts-tests-a11y-manual-EXAMPLES-STATES-md", - "path": "artifacts/tests/a11y-manual/EXAMPLES_STATES.md", - "schemaId": "markdown", - "production": "source-controlled" - }, - { - "id": "artifact-artifacts-tests-a11y-manual-EXAMPLES-AUTH-md", - "path": "artifacts/tests/a11y-manual/EXAMPLES_AUTH.md", - "schemaId": "markdown", - "production": "source-controlled" - }, - { - "id": "artifact-artifacts-tests-a11y-manual-REFERENCE-RESOURCE-LIST-md", - "path": "artifacts/tests/a11y-manual/REFERENCE_RESOURCE_LIST.md", - "schemaId": "markdown", - "production": "source-controlled" - }, { "id": "artifact-artifacts-tests-a11y-manual-NOT-FOUND-md", "path": "artifacts/tests/a11y-manual/NOT_FOUND.md", @@ -1875,7 +1837,6 @@ "commandIds": [ "test-integration", "test-http-scenario-evidence", - "test-reference-feature", "test-recipes" ], "logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-007-txt", @@ -1884,7 +1845,6 @@ "artifact-artifacts-tests-http-scenario-executions-json", "artifact-artifacts-quality-http-scenario-evidence-json", "artifact-artifacts-quality-http-scenario-evidence-fixture-json", - "artifact-artifacts-tests-reference-feature-xml", "artifact-artifacts-tests-optional-recipes-xml" ], "retentionClassId": "merge-cycle" @@ -2227,10 +2187,6 @@ "logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-028-txt", "evidenceArtifactIds": [ "artifact-artifacts-tests-a11y-manual-APP-HOME-md", - "artifact-artifacts-tests-a11y-manual-EXAMPLES-UI-md", - "artifact-artifacts-tests-a11y-manual-EXAMPLES-STATES-md", - "artifact-artifacts-tests-a11y-manual-EXAMPLES-AUTH-md", - "artifact-artifacts-tests-a11y-manual-REFERENCE-RESOURCE-LIST-md", "artifact-artifacts-tests-a11y-manual-NOT-FOUND-md", "artifact-artifacts-tests-a11y-manual-report-json" ], diff --git a/config/contracts/registry-baseline.approval.json b/config/contracts/registry-baseline.approval.json index 74247c76..3ffa6989 100644 --- a/config/contracts/registry-baseline.approval.json +++ b/config/contracts/registry-baseline.approval.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, - "snapshotDigest": "319a798ca3c9a87d7e2943177d952b13941622f4faec23c28f36024196a9e91d", + "snapshotDigest": "2430864767622f21490feb7f0b6932f73b82c0062e4b3ec70fe2c3ef3ac76889", "owner": "DongHyeonka", - "reason": "1103/16-04 FE-REG-API problemSchema가 FE-REG-SCHEMA api-problem 행을 참조한다", - "approvedAt": "2026-11-04T14:04:44.377Z" + "reason": "2026-11-07 소유자 결정: 템플릿 샘플 삭제(design-docs repo-structure/README.md 3.4절). 참조 기능과 예제 화면의 라우트·operation·스키마·무효화 행을 지운다", + "approvedAt": "2026-11-08T02:26:50.112Z" } diff --git a/config/contracts/registry-baseline.json b/config/contracts/registry-baseline.json index 6a56a3ef..a054a8b4 100644 --- a/config/contracts/registry-baseline.json +++ b/config/contracts/registry-baseline.json @@ -5,7 +5,7 @@ "registryId": "FE-REG-ROUTE", "owner": "feature-frontend-routing-release-recovery-runtime", "source": "src/features/installed-feature-contracts.ts", - "rowCount": 10, + "rowCount": 3, "contract": { "requiredFields": [ "routeId", @@ -93,19 +93,6 @@ "searchSchema": null, "title": "시작" }, - "EXAMPLES_AUTH": { - "access": "public", - "chunkId": "route-examples-auth", - "errorSurface": "route-boundary", - "loadingSurface": "example-page", - "navigationLabel": "인증 연동", - "navigationOrder": 40, - "paramsSchema": null, - "path": "/examples/auth", - "routeId": "EXAMPLES_AUTH", - "searchSchema": null, - "title": "인증 연동" - }, "EXAMPLES_PLATFORM": { "access": "public", "chunkId": "route-examples-platform", @@ -119,32 +106,6 @@ "searchSchema": null, "title": "플랫폼 구성" }, - "EXAMPLES_STATES": { - "access": "public", - "chunkId": "route-examples-states", - "errorSurface": "route-boundary", - "loadingSurface": "example-page", - "navigationLabel": "화면 상태", - "navigationOrder": 30, - "paramsSchema": null, - "path": "/examples/states", - "routeId": "EXAMPLES_STATES", - "searchSchema": null, - "title": "화면 상태" - }, - "EXAMPLES_UI": { - "access": "public", - "chunkId": "route-examples-ui", - "errorSurface": "route-boundary", - "loadingSurface": "example-page", - "navigationLabel": "UI 구성요소", - "navigationOrder": 20, - "paramsSchema": null, - "path": "/examples/ui", - "routeId": "EXAMPLES_UI", - "searchSchema": null, - "title": "UI 구성요소" - }, "NOT_FOUND": { "access": "public", "chunkId": "route-not-found", @@ -157,58 +118,6 @@ "routeId": "NOT_FOUND", "searchSchema": null, "title": "페이지를 찾을 수 없음" - }, - "REFERENCE_RESOURCE_DETAIL": { - "access": "session-required", - "chunkId": "route-reference-resource-detail", - "errorSurface": "feature-boundary", - "loadingSurface": "reference-resource-detail", - "navigationLabel": null, - "navigationOrder": null, - "paramsSchema": "ReferenceResourceParams", - "path": "/examples/reference-resources/items/:resourceId", - "routeId": "REFERENCE_RESOURCE_DETAIL", - "searchSchema": null, - "title": "Reference detail" - }, - "REFERENCE_RESOURCE_FORM": { - "access": "session-required", - "chunkId": "route-reference-resource-form", - "errorSurface": "feature-boundary", - "loadingSurface": "reference-resource-form", - "navigationLabel": null, - "navigationOrder": null, - "paramsSchema": null, - "path": "/examples/reference-resources/new", - "routeId": "REFERENCE_RESOURCE_FORM", - "searchSchema": null, - "title": "Reference form" - }, - "REFERENCE_RESOURCE_LIST": { - "access": "session-required", - "chunkId": "route-reference-resources", - "errorSurface": "feature-boundary", - "loadingSurface": "reference-resource-list", - "navigationLabel": "Reference feature", - "navigationOrder": 50, - "paramsSchema": null, - "path": "/examples/reference-resources", - "routeId": "REFERENCE_RESOURCE_LIST", - "searchSchema": "ReferenceResourceListQuery", - "title": "Reference feature" - }, - "REFERENCE_RESOURCE_STATUS": { - "access": "session-required", - "chunkId": "route-reference-resource-status", - "errorSurface": "feature-boundary", - "loadingSurface": "reference-resource-status", - "navigationLabel": null, - "navigationOrder": null, - "paramsSchema": null, - "path": "/examples/reference-resources/status", - "routeId": "REFERENCE_RESOURCE_STATUS", - "searchSchema": null, - "title": "Reference status" } } }, @@ -216,7 +125,7 @@ "registryId": "FE-REG-ROUTE-RUNTIME", "owner": "feature-frontend-routing-release-recovery-runtime", "source": "src/features/installed-feature-contracts.ts", - "rowCount": 10, + "rowCount": 3, "contract": { "requiredFields": [ "routeId", @@ -267,59 +176,17 @@ "routeId": "APP_HOME", "searchCodec": "none" }, - "EXAMPLES_AUTH": { - "moduleId": "auth-example-page", - "paramsCodec": "none", - "routeId": "EXAMPLES_AUTH", - "searchCodec": "none" - }, "EXAMPLES_PLATFORM": { "moduleId": "platform-overview-page", "paramsCodec": "none", "routeId": "EXAMPLES_PLATFORM", "searchCodec": "none" }, - "EXAMPLES_STATES": { - "moduleId": "state-gallery-page", - "paramsCodec": "none", - "routeId": "EXAMPLES_STATES", - "searchCodec": "none" - }, - "EXAMPLES_UI": { - "moduleId": "ui-gallery-page", - "paramsCodec": "none", - "routeId": "EXAMPLES_UI", - "searchCodec": "none" - }, "NOT_FOUND": { "moduleId": "not-found-page", "paramsCodec": "NotFoundSplat", "routeId": "NOT_FOUND", "searchCodec": "none" - }, - "REFERENCE_RESOURCE_DETAIL": { - "moduleId": "reference-resource-detail-page", - "paramsCodec": "ReferenceResourceParams", - "routeId": "REFERENCE_RESOURCE_DETAIL", - "searchCodec": "none" - }, - "REFERENCE_RESOURCE_FORM": { - "moduleId": "reference-resource-form-page", - "paramsCodec": "none", - "routeId": "REFERENCE_RESOURCE_FORM", - "searchCodec": "none" - }, - "REFERENCE_RESOURCE_LIST": { - "moduleId": "reference-resource-page", - "paramsCodec": "none", - "routeId": "REFERENCE_RESOURCE_LIST", - "searchCodec": "ReferenceResourceListQuery" - }, - "REFERENCE_RESOURCE_STATUS": { - "moduleId": "reference-resource-status-page", - "paramsCodec": "none", - "routeId": "REFERENCE_RESOURCE_STATUS", - "searchCodec": "none" } } }, @@ -327,7 +194,7 @@ "registryId": "FE-REG-API", "owner": "feature-frontend-api-client-response-envelope-contract", "source": "src/features/loaded-feature-runtimes.ts", - "rowCount": 3, + "rowCount": 0, "contract": { "requiredFields": [ "operationId", @@ -442,113 +309,13 @@ "unvalidated" ] }, - "rows": { - "CREATE_REFERENCE_RESOURCE": { - "acceptedStatuses": [ - 200, - 201 - ], - "authProfileId": "EXTERNAL_BEARER", - "commandEffect": { - "classifiesStatus": true - }, - "commandRecovery": { - "mode": "IDEMPOTENCY_REPLAY", - "operationIdentityField": "idempotencyKey" - }, - "emptyBodyStatuses": [], - "featureId": "reference-feature", - "method": "POST", - "operationId": "CREATE_REFERENCE_RESOURCE", - "path": "/api/reference-resources", - "problemSchema": "ReferenceProblem", - "requestBody": "JSON", - "requestByteLimit": 32768, - "requestSchema": "CreateReferenceResourceCommand", - "responseBody": "REQUIRED_JSON", - "responseByteLimit": 32768, - "responseEnvelope": "NONE", - "responseSchema": "ReferenceResourcePayload", - "retryBudget": 0, - "retrySemantics": "KEYED", - "totalDeadlineMs": 10000, - "traffic": { - "maxConcurrentRequests": 1, - "maxPhysicalRequests": 1, - "maxQueuedRequests": 0, - "maxRetries": 0 - }, - "unvalidated": [] - }, - "GET_REFERENCE_RESOURCE": { - "acceptedStatuses": [ - 200 - ], - "authProfileId": "EXTERNAL_BEARER", - "commandEffect": null, - "commandRecovery": null, - "emptyBodyStatuses": [], - "featureId": "reference-feature", - "method": "GET", - "operationId": "GET_REFERENCE_RESOURCE", - "path": "/api/reference-resources/{resourceId}", - "problemSchema": "ReferenceProblem", - "requestBody": "NONE", - "requestByteLimit": 0, - "requestSchema": "ReferenceResourceParams", - "responseBody": "REQUIRED_JSON", - "responseByteLimit": 32768, - "responseEnvelope": "NONE", - "responseSchema": "ReferenceResourcePayload", - "retryBudget": 2, - "retrySemantics": "SAFE", - "totalDeadlineMs": 10000, - "traffic": { - "maxConcurrentRequests": 1, - "maxPhysicalRequests": 3, - "maxQueuedRequests": 0, - "maxRetries": 2 - }, - "unvalidated": [] - }, - "LIST_REFERENCE_RESOURCES": { - "acceptedStatuses": [ - 200 - ], - "authProfileId": "EXTERNAL_BEARER", - "commandEffect": null, - "commandRecovery": null, - "emptyBodyStatuses": [], - "featureId": "reference-feature", - "method": "GET", - "operationId": "LIST_REFERENCE_RESOURCES", - "path": "/api/reference-resources", - "problemSchema": "ReferenceProblem", - "requestBody": "NONE", - "requestByteLimit": 0, - "requestSchema": "ReferenceResourceListQuery", - "responseBody": "REQUIRED_JSON", - "responseByteLimit": 262144, - "responseEnvelope": "NONE", - "responseSchema": "ReferenceResourceListPayload", - "retryBudget": 2, - "retrySemantics": "SAFE", - "totalDeadlineMs": 10000, - "traffic": { - "maxConcurrentRequests": 1, - "maxPhysicalRequests": 3, - "maxQueuedRequests": 0, - "maxRetries": 2 - }, - "unvalidated": [] - } - } + "rows": {} }, { "registryId": "FE-REG-SCHEMA", "owner": "feature-frontend-contract-schema-registry", "source": "src/features/loaded-feature-runtimes.ts", - "rowCount": 8, + "rowCount": 2, "contract": { "requiredFields": [ "schemaId", @@ -587,15 +354,6 @@ ] }, "rows": { - "CreateReferenceResourceCommand": { - "boundary": "api-request", - "direction": "REQUEST", - "owner": "feature-frontend-reference-feature-vertical-slice", - "runtime": "zod", - "schemaId": "CreateReferenceResourceCommand", - "schemaVersion": 1, - "unknownFieldPolicy": "REJECT_UNKNOWN" - }, "none": { "boundary": "route-params", "owner": "feature-frontend-routing-release-recovery-runtime", @@ -607,51 +365,6 @@ "owner": "feature-frontend-routing-release-recovery-runtime", "runtime": "zod", "schemaId": "NotFoundSplat" - }, - "ReferenceProblem": { - "boundary": "api-problem", - "direction": "RESPONSE", - "owner": "feature-frontend-reference-feature-vertical-slice", - "runtime": "zod", - "schemaId": "ReferenceProblem", - "schemaVersion": 1, - "unknownFieldPolicy": "STRIP_UNKNOWN" - }, - "ReferenceResourceListPayload": { - "boundary": "api-response", - "direction": "RESPONSE", - "owner": "feature-frontend-reference-feature-vertical-slice", - "runtime": "zod", - "schemaId": "ReferenceResourceListPayload", - "schemaVersion": 1, - "unknownFieldPolicy": "STRIP_UNKNOWN" - }, - "ReferenceResourceListQuery": { - "boundary": "route-search-api-request", - "direction": "REQUEST", - "owner": "feature-frontend-reference-feature-vertical-slice", - "runtime": "zod", - "schemaId": "ReferenceResourceListQuery", - "schemaVersion": 1, - "unknownFieldPolicy": "REJECT_UNKNOWN" - }, - "ReferenceResourceParams": { - "boundary": "route-params", - "direction": "REQUEST", - "owner": "feature-frontend-reference-feature-vertical-slice", - "runtime": "zod", - "schemaId": "ReferenceResourceParams", - "schemaVersion": 1, - "unknownFieldPolicy": "REJECT_UNKNOWN" - }, - "ReferenceResourcePayload": { - "boundary": "api-response", - "direction": "RESPONSE", - "owner": "feature-frontend-reference-feature-vertical-slice", - "runtime": "zod", - "schemaId": "ReferenceResourcePayload", - "schemaVersion": 1, - "unknownFieldPolicy": "STRIP_UNKNOWN" } } }, @@ -814,7 +527,7 @@ "registryId": "FE-REG-STORAGE", "owner": "feature-frontend-storage-registry-contract", "source": "src/contracts/storage-keys.ts", - "rowCount": 7, + "rowCount": 8, "contract": { "requiredFields": [ "logicalName", @@ -883,6 +596,19 @@ ] }, "rows": { + "AUTH_REDIRECT_TRANSACTION": { + "backend": "external", + "classification": "opaque-cache", + "logicalName": "AUTH_REDIRECT_TRANSACTION", + "migration": "discard", + "name": "oidc-pkce-transaction", + "physicalKey": "ca-frontend:auth:v1:oidc-pkce-transaction", + "quotaFallback": "no-persist", + "schemaVersion": 1, + "scope": "auth", + "ttl": "session", + "valueCodec": "none" + }, "AUTH_TOKEN": { "backend": "forbidden", "classification": "sensitive-forbidden", @@ -1304,24 +1030,9 @@ }, "rows": { "invalidation-graph": { - "edges": [ - { - "namespace": { - "namespaceId": "reference-resource", - "namespaceVersion": 1 - }, - "topicId": "qinv.01k10f7m3w9p6r2c8v5n4x" - } - ], - "namespaces": [ - { - "namespaceId": "reference-resource", - "namespaceVersion": 1 - } - ], - "topics": [ - "qinv.01k10f7m3w9p6r2c8v5n4x" - ] + "edges": [], + "namespaces": [], + "topics": [] } } }, @@ -1329,7 +1040,7 @@ "registryId": "FE-REG-QUERY-INVALIDATION-TOPIC-VERSION", "owner": "feature-frontend-server-state-caching-contract", "source": "src/features/installed-feature-contracts.ts", - "rowCount": 1, + "rowCount": 0, "contract": { "requiredFields": [ "topicId", @@ -1353,12 +1064,7 @@ "topicId" ] }, - "rows": { - "[\"qinv.01k10f7m3w9p6r2c8v5n4x\"]": { - "topicId": "qinv.01k10f7m3w9p6r2c8v5n4x", - "topicVersion": 1 - } - } + "rows": {} }, { "registryId": "FE-REG-TELEMETRY", diff --git a/config/runtime/development.json b/config/runtime/development.json index 63006b82..d73619fc 100644 --- a/config/runtime/development.json +++ b/config/runtime/development.json @@ -13,7 +13,5 @@ "SERVICE_WORKER": "DEFAULT", "OFFLINE_COMMANDS": "DEFAULT" }, - "FEATURE_OVERRIDES": { - "reference-feature": "DEFAULT" - } + "FEATURE_OVERRIDES": {} } diff --git a/config/runtime/local.json b/config/runtime/local.json index 952aa3c9..6222d0b6 100644 --- a/config/runtime/local.json +++ b/config/runtime/local.json @@ -13,7 +13,5 @@ "SERVICE_WORKER": "DEFAULT", "OFFLINE_COMMANDS": "DEFAULT" }, - "FEATURE_OVERRIDES": { - "reference-feature": "DEFAULT" - } + "FEATURE_OVERRIDES": {} } diff --git a/config/runtime/production.json b/config/runtime/production.json index 46ad7781..a6ee567d 100644 --- a/config/runtime/production.json +++ b/config/runtime/production.json @@ -14,7 +14,5 @@ "SERVICE_WORKER": "DEFAULT", "OFFLINE_COMMANDS": "DEFAULT" }, - "FEATURE_OVERRIDES": { - "reference-feature": "DEFAULT" - } + "FEATURE_OVERRIDES": {} } diff --git a/config/runtime/staging.json b/config/runtime/staging.json index 861f87bd..f1df1789 100644 --- a/config/runtime/staging.json +++ b/config/runtime/staging.json @@ -14,7 +14,5 @@ "SERVICE_WORKER": "DEFAULT", "OFFLINE_COMMANDS": "DEFAULT" }, - "FEATURE_OVERRIDES": { - "reference-feature": "DEFAULT" - } + "FEATURE_OVERRIDES": {} } diff --git a/config/scale/feature-shape-ceilings.json b/config/scale/feature-shape-ceilings.json index 853db542..bc79da8d 100644 --- a/config/scale/feature-shape-ceilings.json +++ b/config/scale/feature-shape-ceilings.json @@ -9,9 +9,9 @@ "axes": [ { "axis": "Typecheck of one app", - "verified": "Linear, about 117k instantiations and 36 MB of tsc memory per feature, up to 100 features", - "condition": "Reference-shaped features, tsconfig.app.json, the host recorded in the baseline", - "notVerified": "200 features (one full context) and beyond; 4,000 (20 x 200) would need on the order of 150 GB by the same slope" + "verified": "Linear, about 101k instantiations and 31 MB of tsc memory per feature, up to 100 features", + "condition": "Copies of the feature create:feature writes with --with-create --keyed (2026-11-07; reference-sample copies before), tsconfig.app.json, the host recorded in the baseline", + "notVerified": "200 features (one full context) and beyond; 4,000 (20 x 200) would need on the order of 125 GB by the same slope" }, { "axis": "Production build", @@ -21,27 +21,28 @@ }, { "axis": "Initial JavaScript", - "verified": "15-01: only each feature's declaration (route table, messages, invalidation identities) loads at boot; its runtime half loads with its routes, and a copy adds no initial file. initialJavascript below is the current template build, what one more feature in an existing context adds (perFeatureGzipBytes) and what a new context adds (perContextGzipBytes); tests/unit/feature-shape-growth.test.ts measures them on every unit run, bounds a feature at 1 KiB and a context at 512 B, and fails when the record no longer matches the build. The 25- and 100-copy runs are in the baseline at its source commit (before 15-01: +3,922 B per copy)", + "verified": "15-01: only each feature's declaration (route table, messages, invalidation identities) loads at boot; its runtime half loads with its routes. initialJavascript below is the current template build, which has no feature; what the first feature adds once (firstFeatureGzipBytes: the code every feature shares joins the initial chunks); what one more feature in an existing context adds (perFeatureGzipBytes); and what a second context adds (perContextGzipBytes). tests/unit/feature-shape-growth.test.ts measures them on every unit run, bounds a feature at 1 KiB and a context at 512 B, and fails when the record no longer matches the build. The 25- and 100-copy runs are in the baseline at its source commit (before 15-01: +3,922 B per copy)", "condition": "Same; the feature-declarations and feature-platform chunk groups in vite.config.ts", - "notVerified": "How many more features fit: the initial budget (config/performance/budgets.json) minus initialJavascript.gzipBytes, divided by perFeatureGzipBytes (plus perContextGzipBytes per new context). The platform itself takes most of the budget" + "notVerified": "How many features fit: the initial budget (config/performance/budgets.json) minus initialJavascript.gzipBytes and firstFeatureGzipBytes, divided by perFeatureGzipBytes (plus perContextGzipBytes per new context). The platform itself takes most of the budget" }, { "axis": "Lazy JavaScript", - "verified": "About 8.5 KB gzip and eight files per feature, every file far below the 120 KiB lazy-chunk budget", + "verified": "About 6.7 KB gzip and nine files per feature, every file far below the 120 KiB lazy-chunk budget", "condition": "Same", "notVerified": "Download cost of many lazy files" }, { "axis": "Routes", - "verified": "4 per feature, composed without conflict", + "verified": "3 per feature (list, detail, create), composed without conflict", "condition": "Same", "notVerified": "Router matching cost at runtime" } ], "initialJavascript": { - "gzipBytes": 204193, - "files": 27, - "perFeatureGzipBytes": 751, - "perContextGzipBytes": 245 + "gzipBytes": 194354, + "files": 17, + "firstFeatureGzipBytes": 6327, + "perFeatureGzipBytes": 539, + "perContextGzipBytes": 4 } } diff --git a/config/scale/feature-shape-growth.json b/config/scale/feature-shape-growth.json index 052374f4..f6b320de 100644 --- a/config/scale/feature-shape-growth.json +++ b/config/scale/feature-shape-growth.json @@ -1,216 +1,213 @@ { "schemaVersion": 1, - "measuredAt": "2026-11-01T14:29:42.148Z", + "measuredAt": "2026-11-08T05:02:36.163Z", "command": "node scripts/scale/measure-feature-shape-growth.ts --sizes=0,25,100 --repeats=2", "environment": { "node": "24.14.0", "platform": "linux", "arch": "x64", - "cpuModel": "Intel(R) Core(TM) Ultra 7 155H", - "logicalCpus": 22, - "availableParallelism": 22, + "cpuModel": "Intel(R) Core(TM) i5-10400F CPU @ 2.90GHz", + "logicalCpus": 12, + "availableParallelism": 12, "typescript": "Version 7.0.2", - "vite": "vite/8.1.5 linux-x64 node-v24.14.0" + "vite": "vite/8.1.6 linux-x64 node-v24.14.0" }, "source": { - "commit": "373b27b09c7c24c50ea81fca0238138f6b8189a8", - "modifiedPaths": [ - "scripts/scale/measure-feature-shape-growth.ts", - "tests/unit/feature-shape-growth.test.ts" - ] + "commit": "e3c8db48ae0000ab63c15d2ee09a672140c408ca", + "modifiedPaths": [] }, - "sourceFeature": "src/features/reference-feature", + "sourceFeature": "create:feature --with-create --keyed", "runs": [ { "repeat": 1, "addedFeatures": 0, - "routes": 10, + "routes": 3, "tsc": { "passed": true, "firstError": null, - "files": 844, - "types": 287435, - "symbols": 794593, - "instantiations": 721205, - "memoryKb": 521732, - "wallMs": 811 + "files": 868, + "types": 270953, + "symbols": 764824, + "instantiations": 660922, + "memoryKb": 507503, + "wallMs": 1149 }, "build": { - "wallMs": 428, - "initialJavascriptFiles": 16, - "initialJavascriptGzipBytes": 203816, - "lazyJavascriptFiles": 17, - "lazyJavascriptGzipBytes": 28413 + "wallMs": 471, + "initialJavascriptFiles": 17, + "initialJavascriptGzipBytes": 194354, + "lazyJavascriptFiles": 6, + "lazyJavascriptGzipBytes": 8881 }, "loadBefore": [ - 2.97, - 7.82, - 8.57 + 2.41, + 12.33, + 13.56 ], "loadAfter": [ - 2.97, - 7.82, - 8.57 + 2.41, + 12.33, + 13.56 ] }, { "repeat": 2, "addedFeatures": 0, - "routes": 10, + "routes": 3, "tsc": { "passed": true, "firstError": null, - "files": 844, - "types": 287435, - "symbols": 794593, - "instantiations": 721205, - "memoryKb": 521779, - "wallMs": 789 + "files": 868, + "types": 270953, + "symbols": 764824, + "instantiations": 660922, + "memoryKb": 507208, + "wallMs": 1115 }, "build": { - "wallMs": 400, - "initialJavascriptFiles": 16, - "initialJavascriptGzipBytes": 203816, - "lazyJavascriptFiles": 17, - "lazyJavascriptGzipBytes": 28413 + "wallMs": 464, + "initialJavascriptFiles": 17, + "initialJavascriptGzipBytes": 194354, + "lazyJavascriptFiles": 6, + "lazyJavascriptGzipBytes": 8881 }, "loadBefore": [ - 2.97, - 7.82, - 8.57 + 2.41, + 12.33, + 13.56 ], "loadAfter": [ - 2.97, - 7.82, - 8.57 + 2.41, + 12.33, + 13.56 ] }, { "repeat": 1, "addedFeatures": 25, - "routes": 110, + "routes": 78, "tsc": { "passed": true, "firstError": null, - "files": 1395, - "types": 1062647, - "symbols": 2897351, - "instantiations": 3645516, - "memoryKb": 1438408, - "wallMs": 2362 + "files": 1419, + "types": 924555, + "symbols": 2579662, + "instantiations": 3222688, + "memoryKb": 1300524, + "wallMs": 3027 }, "build": { - "wallMs": 556, - "initialJavascriptFiles": 16, - "initialJavascriptGzipBytes": 219508, - "lazyJavascriptFiles": 218, - "lazyJavascriptGzipBytes": 239901 + "wallMs": 596, + "initialJavascriptFiles": 21, + "initialJavascriptGzipBytes": 211739, + "lazyJavascriptFiles": 235, + "lazyJavascriptGzipBytes": 185846 }, "loadBefore": [ - 3.13, - 7.78, - 8.55 + 2.41, + 12.33, + 13.56 ], "loadAfter": [ - 3.13, - 7.78, - 8.55 + 2.46, + 12.18, + 13.5 ] }, { "repeat": 2, "addedFeatures": 25, - "routes": 110, + "routes": 78, "tsc": { "passed": true, "firstError": null, - "files": 1395, - "types": 1062647, - "symbols": 2897351, - "instantiations": 3645516, - "memoryKb": 1438614, - "wallMs": 2453 + "files": 1419, + "types": 924555, + "symbols": 2579662, + "instantiations": 3222688, + "memoryKb": 1300579, + "wallMs": 2838 }, "build": { - "wallMs": 546, - "initialJavascriptFiles": 16, - "initialJavascriptGzipBytes": 219508, - "lazyJavascriptFiles": 218, - "lazyJavascriptGzipBytes": 239901 + "wallMs": 607, + "initialJavascriptFiles": 21, + "initialJavascriptGzipBytes": 211739, + "lazyJavascriptFiles": 235, + "lazyJavascriptGzipBytes": 185846 }, "loadBefore": [ - 3.13, - 7.78, - 8.55 + 2.46, + 12.18, + 13.5 ], "loadAfter": [ - 3.2, - 7.71, - 8.52 + 2.58, + 12.04, + 13.45 ] }, { "repeat": 1, "addedFeatures": 100, - "routes": 410, + "routes": 303, "tsc": { "passed": true, "firstError": null, - "files": 3045, - "types": 3373621, - "symbols": 9115707, - "instantiations": 12392128, - "memoryKb": 4264554, - "wallMs": 8403 + "files": 3069, + "types": 2842959, + "symbols": 7904204, + "instantiations": 10789965, + "memoryKb": 3698826, + "wallMs": 9049 }, "build": { - "wallMs": 944, - "initialJavascriptFiles": 16, - "initialJavascriptGzipBytes": 264841, - "lazyJavascriptFiles": 818, - "lazyJavascriptGzipBytes": 873479 + "wallMs": 1021, + "initialJavascriptFiles": 21, + "initialJavascriptGzipBytes": 245687, + "lazyJavascriptFiles": 910, + "lazyJavascriptGzipBytes": 677352 }, "loadBefore": [ - 3.2, - 7.71, - 8.52 + 2.58, + 12.04, + 13.45 ], "loadAfter": [ - 6.72, - 8.32, - 8.71 + 2.95, + 11.81, + 13.36 ] }, { "repeat": 2, "addedFeatures": 100, - "routes": 410, + "routes": 303, "tsc": { "passed": true, "firstError": null, - "files": 3045, - "types": 3373621, - "symbols": 9115707, - "instantiations": 12392128, - "memoryKb": 4263823, - "wallMs": 9717 + "files": 3069, + "types": 2842959, + "symbols": 7904204, + "instantiations": 10789965, + "memoryKb": 3700296, + "wallMs": 9140 }, "build": { - "wallMs": 933, - "initialJavascriptFiles": 16, - "initialJavascriptGzipBytes": 264841, - "lazyJavascriptFiles": 818, - "lazyJavascriptGzipBytes": 873479 + "wallMs": 1028, + "initialJavascriptFiles": 21, + "initialJavascriptGzipBytes": 245687, + "lazyJavascriptFiles": 910, + "lazyJavascriptGzipBytes": 677352 }, "loadBefore": [ - 6.72, - 8.32, - 8.71 + 2.95, + 11.81, + 13.36 ], "loadAfter": [ - 6.3, - 8.17, - 8.66 + 3.9, + 11.72, + 13.31 ] } ] diff --git a/config/testing/risk-coverage.json b/config/testing/risk-coverage.json index 0ba7859c..3cf507f8 100644 --- a/config/testing/risk-coverage.json +++ b/config/testing/risk-coverage.json @@ -129,16 +129,6 @@ "branches": 58 } }, - { - "path": "src/features/reference-feature/adapters/reference-http-gateway.ts", - "owner": "reference-feature", - "minimum": { - "lines": 90, - "statements": 90, - "functions": 90, - "branches": 90 - } - }, { "path": "src/presentation/adapters/query/application-query.ts", "owner": "presentation-runtime", @@ -193,7 +183,6 @@ "src/bootstrap/load-release-manifest.ts", "src/bootstrap/read-bounded-boot-json.ts", "src/contracts/diagnostics.ts", - "src/features/reference-feature/adapters/reference-http-gateway.ts", "src/presentation/adapters/query/application-query.ts", "src/adapters/http/http-contract-bridge.ts", "src/adapters/http/http-retry-lifecycle.ts", diff --git a/docs/README.md b/docs/README.md index 74dc482b..fc22ea81 100644 --- a/docs/README.md +++ b/docs/README.md @@ -51,9 +51,9 @@ checkout이 없거나 그 커밋이 없으면 실패 대신 확인하지 못한 지난 상태를 적는 문서라 빼고, git이 무시하는 생성 산출물과 복사한 프로젝트가 지운 작업 이력은 없어도 된다. 설명·수치가 코드와 맞는지는 검사하지 않는다. 규칙과 예외의 정본은 `scripts/verify-documentation-readiness.ts`다. -복사한 프로젝트가 지울 수 있는 템플릿 기능(참조 기능, 예제 화면. 목록은 -`scripts/lib/removable-template-features.ts`)의 경로와 script는 그 기능이 설치돼 있을 때 -(`src/features//feature-module.ts`가 있을 때) 검사하고, 지운 뒤에는 없어도 된다. +프로젝트가 지울 예정인 샘플 기능(목록은 `scripts/lib/removable-template-features.ts`, 템플릿은 +비어 있다)의 경로와 script는 그 기능이 설치돼 있을 때(`src/features//feature-module.ts`가 +있을 때) 검사하고, 지운 뒤에는 없어도 된다. 게이트가 직접 읽는 파일이라 지우거나 옮기면 게이트가 실패한다. diff --git a/docs/accessibility/manual-checklist.md b/docs/accessibility/manual-checklist.md index 61425334..313cd9b8 100644 --- a/docs/accessibility/manual-checklist.md +++ b/docs/accessibility/manual-checklist.md @@ -57,8 +57,8 @@ The reviewer must verify: - M7: non-essential motion is suppressed with reduced-motion preference - Screen reader: headings, live regions, errors, and actions are announced once -`EXAMPLES_UI` requires real M4 modal and M5 field-error review; those items must -not be marked not-applicable on that route. Passing automated evidence means +A route with a form or a dialog requires real M4 modal and M5 field-error +review; those items must not be marked not-applicable on that route. Passing automated evidence means only that tested pages had no critical or serious axe findings under the recorded Chromium, Firefox, and WebKit runs. @@ -78,7 +78,7 @@ What the automated run scans: route's `paramsSchema` is the input of such a read, the report expects that record from the descriptors alone and fails without it (`scripts/write-a11y-report.ts`). -- The reference sample's list in its success, empty and error states, its - detail, its form with submit errors and its status page, each after that - state is on screen (`tests/e2e/reference-form.spec.ts`, removed with the - sample). +- The list of the feature `create:feature` writes, in its success, empty and + error states, its detail and its form with submit errors, each after that + state is on screen (`tests/e2e/generated-feature.spec.ts`, on a build with + that feature). A product's own features get the route scan above. diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index f6131c85..8f267acc 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -124,36 +124,22 @@ runtime config의 version 문자열 일치만 compatibility 증거로 사용하 artifact digest가 없는 동안에는 실제 staging conformance fixture와 수동 승인 evidence가 필요하다. -## 4. 현재 reference REST 계약 +## 4. 현재 REST 계약 -현재 frontend에 실제 조립된 operation은 다음 세 개다. +템플릿에는 조립된 기능 operation이 없다. 참조 샘플(`LIST_REFERENCE_RESOURCES` 등 +problem details 모양의 세 operation)은 2026-11-07에 지웠다. 기능의 operation은 +`corepack pnpm create:feature `가 만든다. 짝 백엔드 `new-feature.sh`와 같은 경로 +규칙이다(`docs/manual/reference/create-feature.md`). | operation | request | success | | --- | --- | --- | -| `LIST_REFERENCE_RESOURCES` | `GET /api/reference-resources?cursor&limit&tags` | `200 application/json` | -| `GET_REFERENCE_RESOURCE` | `GET /api/reference-resources/{resourceId}` | `200 application/json` | -| `CREATE_REFERENCE_RESOURCE` | `POST /api/reference-resources` | `200` 또는 `201 application/json` | +| `_LIST_ITEMS` | `GET /` | `200`, Envelope 안의 항목 배열과 `meta.page` | +| `_GET_ITEM` (`--with-create`) | `GET //{Id}` | `200`, Envelope 안의 항목 | +| `_CREATE_ITEM` (`--with-create`) | `POST /` | `201`, Envelope 안의 항목 | -현재 list payload는 `ReferenceResource[]`다. `cursor` 입력이 존재하더라도 -`CursorPage` 출력 계약은 아직 아니다. backend가 같은 operation에서 배열을 -page object로 조용히 바꾸면 schema mismatch로 실패한다. - -resource DTO: - -```text -ReferenceResourceDtoV1 - id: non-empty string, maximum 120 characters - name: non-empty string, maximum 240 characters - createdAt?: RFC 3339 date-time -``` - -create command: - -```text -CreateReferenceResourceCommandV1 - name: trimmed string, 1..120 - note?: trimmed string, 0..500 -``` +모든 operation이 `responseEnvelope: "ENVELOPE_V1"`이다. Envelope가 없는 백엔드(DTO와 +problem details)에 붙이는 법은 [매뉴얼 02 결정표 4절](../manual/02-decision-tables.md)의 +「problem details 백엔드의 예」다. Backend는 frontend validation을 신뢰하지 않고 동일하거나 더 좁은 validation과 authorization을 다시 수행한다. @@ -193,8 +179,9 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정 바뀐 파일마다 다시 볼 프론트 위치를 말하며 1로 끝난다(1105/16-02). - 프론트에서 Envelope를 읽는 곳: `src/adapters/http/backend-envelope.ts`(스키마와 해석). V3 실행기는 descriptor가 `responseEnvelope: "ENVELOPE_V1"`일 때 쓴다. - `create:feature`가 만든 기능은 이 값을 선언한다. 참조 기능은 `"NONE"`을 - 선언하고 DTO와 problem details를 검증한다. 이 칸은 descriptor 타입의 필수 + `create:feature`가 만든 기능은 이 값을 선언한다. Envelope가 없는 백엔드의 + operation은 `"NONE"`을 선언하고 DTO와 problem details를 검증한다(매뉴얼 02 + 결정표 4절의 예). 이 칸은 descriptor 타입의 필수 칸이라 빠뜨리면 `check:types`가 실패한다(1103/16-01). - 실패 Envelope의 `error.code`가 "적용 안 됨"인지는 6.1절이 정한다. - 페이지 목록의 `meta.page`(`number`·`size`·`total`·`sort`)는 기능의 @@ -272,7 +259,7 @@ Cross-origin bearer provider 최소 CORS: ## 6. Command와 idempotency -`CREATE_REFERENCE_RESOURCE`는 keyed command다. frontend memory single-flight는 +`create:feature --with-create --keyed`의 작성 operation은 keyed command다. frontend memory single-flight는 backend idempotency를 대체하지 않는다. 멱등성 응답의 status·`error.code`·`retryable`·`Retry-After`와 키 문법은 짝 @@ -287,9 +274,8 @@ backend idempotency를 대체하지 않는다. `src/presentation/adapters/query/application-query.ts` - Envelope operation의 거절 판정: `src/adapters/http/backend-envelope.ts` `REFUSED_BEFORE_WRITE`(6.1절 표) - - 참조 기능(Envelope 없음) 판정: `src/features/reference-feature/contracts/reference-feature-contract-contribution.ts` - (effect), `src/features/reference-feature/adapters/reference-http-gateway.ts` - (code) + - Envelope 없는 operation의 판정: 기능의 `commandEffect.classifyProblem`과 + `mapProblem`(예: [매뉴얼 02 결정표 4절](../manual/02-decision-tables.md)의 코드 조각) ### 6.1 거절 code와 적용 여부 @@ -411,10 +397,10 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐 프론트 판정과 표가 다른 곳(고치면 이 줄을 지운다): -- 참조 기능 분류기(`classifyProblem`)는 참조 fixture(problem+json)용이라 - 400·422를 모두 `NOT_APPLIED`로 본다. 참조 기능은 Envelope operation이 아니라 - 이 표의 대상이 아니다. 짝 백엔드에 붙이는 Envelope operation은 - `src/adapters/http/backend-envelope.ts`의 표가 400·409·422를 정한다(`3261208`). +- 매뉴얼 02 결정표의 problem details 예(`classifyProblem`)는 400·422를 모두 + `NOT_APPLIED`로 본다. Envelope operation이 아니라 이 표의 대상이 아니다. 짝 + 백엔드에 붙이는 Envelope operation은 `src/adapters/http/backend-envelope.ts`의 + 표가 400·409·422를 정한다(`3261208`). 남은 위험: "쓰기 전"은 현재 코드에서 그 handler에 닿는 출처를 센 결과다. 백엔드가 application bean에 `@Validated`를 달거나 JPA entity에 Bean Validation 제약을 diff --git a/docs/architecture/capability-consumer-experience.md b/docs/architecture/capability-consumer-experience.md index 0d6761c0..422fbc66 100644 --- a/docs/architecture/capability-consumer-experience.md +++ b/docs/architecture/capability-consumer-experience.md @@ -8,23 +8,24 @@ These measurements are baselines, not score targets. A lower line count is not automatically better if it hides business semantics or creates a universal repository abstraction. -## Scenario A — reference REST feature +## Scenario A — a REST feature -The existing reference feature is the executable REST consumer. +The REST consumer is the feature `corepack pnpm create:feature --with-create` +writes (the template's reference sample had this role until 2026-11-07). -It covers list/detail/create behavior, mapping, typed operation inputs, -application ports and an optimistic mutation path. +It covers list/detail/create behavior, mapping, typed operation inputs and +application ports. The feature-owned boundary and application source is these four files: -- `application/reference-feature-api.ts` -- `contracts/reference-mapper.ts` -- `adapters/reference-http-gateway.ts` -- `adapters/create-reference-feature-input.ts` +- `application/-feature-api.ts` +- `contracts/-mapper.ts` +- `adapters/-http-gateway.ts` +- `adapters/create--feature-input.ts` This document does not keep their line counts; a hand-typed count drifted -from the code (review 14-07). Measure them with -`wc -l src/features/reference-feature/{application/reference-feature-api.ts,contracts/reference-mapper.ts,adapters/reference-http-gateway.ts,adapters/create-reference-feature-input.ts}`. +from the code (review 14-07). Measure them in a generated feature with +`wc -l` on those four files. The important boundary metric is not the raw total. It is what those files need to know about the platform. @@ -53,13 +54,14 @@ The executable consumer probe is: `tests/contract/consumer-experience/indexeddb-local-draft.test.ts` -It runs and reads the one Local Draft implementation under -`src/features/local-draft-feature`; the isolated fixture copy it used to probe -had drifted from `src` and was removed (09-12). +It runs and reads the one Local Draft implementation, the test fixture +`tests/fixtures/indexeddb-consumer` (the template's former local-draft sample +under `src/features/`, moved there because it is no product feature). An +earlier isolated copy had drifted from it and was removed (09-12). -The feature owns the Local Draft domain/application API and declares the slice +The consumer owns the Local Draft domain/application API and declares the slice of the repository it calls (`LocalDraftRepository` in -`src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts`). The +`tests/fixtures/indexeddb-consumer/adapters/local-draft-indexeddb-store.ts`). The host hands in an `IndexedDbRepositoryPort` through the `indexedDb` capability; the port satisfies that slice structurally. The cross-capability composition contract lives at: @@ -80,7 +82,7 @@ It runs against native browser IndexedDB. The test creates the platform save/find/remove through the feature API. The Local Draft feature still does not import the IndexedDB runtime or native browser API. -Measured on `src/features/local-draft-feature` (09-12): +Measured on the Local Draft consumer, then under `src/features/` (09-12): | Metric | Result | | --- | ---: | diff --git a/docs/architecture/contract-ownership.md b/docs/architecture/contract-ownership.md index 270956b5..a2838c9b 100644 --- a/docs/architecture/contract-ownership.md +++ b/docs/architecture/contract-ownership.md @@ -101,8 +101,8 @@ Feature-specific contracts stay inside the vertical slice: `features//contracts` -The reference feature owns routes, schemas, mapper definitions, message -catalogs and contribution identities. Central installed files aggregate those +A feature owns its routes, schemas, mapper definitions, message catalogs and +contribution identities (`create:feature` writes them under its `contracts/`). Central installed files aggregate those contributions; they do not own their semantics. The message catalog is a deliberate special case: the compiled catalog remains diff --git a/docs/architecture/decisions/VD-06-intl-typed-message-catalog.md b/docs/architecture/decisions/VD-06-intl-typed-message-catalog.md index 9268cff4..92d0c560 100644 --- a/docs/architecture/decisions/VD-06-intl-typed-message-catalog.md +++ b/docs/architecture/decisions/VD-06-intl-typed-message-catalog.md @@ -71,9 +71,9 @@ route/form/failure 의미 값 - `check:i18n`은 catalog key와 placeholder parity, backend message JSX 렌더링을 검사한다. 검사 범위는 공통 UI 디렉터리, `src/presentation/pages`, 모든 `src/features/*/presentation`이다. 플랫폼 구성 화면 - `src/presentation/examples`와 예제 화면 - `src/features/platform-examples-feature/presentation`(1103/09-04)은 화면 - 문구 ESLint 규칙에서 일부러 뺐다(`eslint.config.ts`). + `src/presentation/examples`와 Storybook story(디자인 시스템·화면 상태 갤러리, + 2026-11-07 전에는 예제 화면 기능)는 화면 문구 ESLint 규칙에서 일부러 + 뺐다(`eslint.config.ts`). - 화면 문구가 catalog에서 오는지는 ESLint `no-restricted-syntax`가 본다 (`eslint.config.ts`의 `screenTextSelectors`, 0929/08-02). 대상은 글자가 든 `JSXText`와 표시·접근성 속성(`aria-label`, `title`, `placeholder`, `alt`, diff --git a/docs/architecture/frontend-application-foundation.md b/docs/architecture/frontend-application-foundation.md index b1fae3da..296e497e 100644 --- a/docs/architecture/frontend-application-foundation.md +++ b/docs/architecture/frontend-application-foundation.md @@ -5,8 +5,8 @@ an independent general-purpose SDK. Its architectural role is: > Frontend Application Foundation = Starter / Composition Skeleton + Reusable Capability Platform -The starter side owns bootstrap, routing, providers, project conventions and a -removable reference feature. The capability side owns reusable technical +The starter side owns bootstrap, routing, providers, project conventions and +the `create:feature` command that writes a feature; it ships no sample feature. The capability side owns reusable technical problems such as HTTP execution, Server State, authentication boundaries, IndexedDB/OPFS, Cache Storage, realtime, browser RPC, transfer and diagnostics. @@ -78,9 +78,9 @@ A reusable capability boundary is composed from: - feature-selected policy, - one capability-specific runtime. -The HTTP reference path is the first concrete example. +The HTTP path is the first concrete example. `src/adapters/http/feature-http-binding.ts` owns transport/outcome -normalization. The reference feature contributes only: +normalization. A feature `create:feature` writes contributes only: - operation ID, - route ID, @@ -152,11 +152,11 @@ repository or move dataset/migration/lifecycle policy into the feature. The repository now has two executable contribution shapes: -- Reference feature: `needs: ["http"]` -- Local Draft feature: `needs: ["indexedDb"]` +- A feature `create:feature` writes: `needs: ["http", "telemetry"]` +- The Local Draft consumer: `needs: ["indexedDb"]` -Local Draft is a compiled architecture consumer used to prove the second -capability shape; it is not added to the default product manifest. Its +Local Draft is a test fixture (`tests/fixtures/indexeddb-consumer`) used to +prove the second capability shape; it is not a feature of the product. Its browser-capability test composes the feature over the real `createIndexedDbRuntime` and native IndexedDB, proving that this seam is not limited to an in-memory contract fixture. diff --git a/docs/architecture/frontend-ports-adapters-and-boundaries.md b/docs/architecture/frontend-ports-adapters-and-boundaries.md index 0b64fe76..e633119f 100644 --- a/docs/architecture/frontend-ports-adapters-and-boundaries.md +++ b/docs/architecture/frontend-ports-adapters-and-boundaries.md @@ -124,7 +124,7 @@ bootstrap은 page별 orchestration이나 업무 규칙을 소유하지 않는다 | `src/adapters` | HTTP, auth, storage, cache, telemetry 구현 | outbound adapter | | `src/bootstrap` | runtime config와 구현 조립 | 유일한 composition root | | `src/contracts` | 여러 계층의 registry가 혼재 | 소유 계층으로 분산 | -| `src/features/reference-feature` | 완전한 제거 가능 수직 예제 | installed contribution과 제거 gate 유지 | +| `src/features/` | 제품 기능의 수직 slice. 템플릿은 비어 있고 `create:feature`가 만든다(참조 샘플은 2026-11-07 삭제) | installed contribution과 제거 gate 유지 | 현재 구조가 잘 제공하는 기반은 다음과 같다. @@ -178,7 +178,7 @@ Data Router tree, codec, surface, title, navigation, chunk/release recovery의 단일 조립 입력이며 registry/type/build 검증이 누락과 orphan을 거절한다. RP-05에서 두 번째 불일치도 닫혔다. feature별 domain/application/adapter/ -contract/presentation은 `src/features/reference-feature`가 소유하고, generic +contract/presentation은 그 기능 폴더(`src/features/`)가 소유하고, generic installed catalog만 bootstrap과 router에 노출된다. 제거 gate는 feature와 test를 삭제한 복제본에서 전체 P0 경로를 다시 실행한다. @@ -351,7 +351,7 @@ src/ platform/ features/ - reference-feature/ + / domain/ application/ ports/ @@ -376,8 +376,8 @@ src/ application capability만 둔다. `shared`, `common`, `utils` 같은 이름으로 기술과 업무 규칙을 무제한 혼합하지 않는다. -`features/reference-feature`는 구조를 설명하기 위한 완전한 수직 -슬라이스다. 이 폴더를 삭제하고 route 등록 한 곳만 제거했을 때 +`features/`는 구조를 설명하기 위한 완전한 수직 +슬라이스다(2026-11-07부터 템플릿의 예는 `create:feature`가 만드는 기능이다). 이 폴더를 삭제하고 route 등록 한 곳만 제거했을 때 typecheck, architecture check, test와 build가 모두 통과해야 한다. ## 8. Input port 설계 규칙 @@ -835,6 +835,10 @@ status/attempt/duration bucket만 전달한다. ## 16. Feature 경계와 removable reference feature +> 2026-11-07: 템플릿의 참조 샘플은 지웠다. 이 절이 참조 기능에 요구한 수직 경로와 +> 제거 검증은 `create:feature`가 만드는 기능이 맡는다(`test:feature-scaffold`가 게이트와 +> 제거를, `tests/e2e/generated-feature.spec.ts`가 실제 브라우저 경로를 본다). + Reference feature는 단순 UI fixture가 아니라 다음 경로를 모두 실행해야 한다. @@ -871,7 +875,7 @@ operation을 전역 core registry 안에 하드코딩하지 않는다. 제거 테스트는 다음을 수행해야 한다. -1. `src/features/reference-feature` 전체 삭제 +1. `src/features/` 전체 삭제 2. reference route registration 삭제 3. reference test 삭제 또는 제외 4. 잔여 import와 registry owner 검색 diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index 01843825..ef39a92c 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -101,21 +101,16 @@ rather than adding another independent route or data-loading convention. feature takes it over by declaring that route id (see "Product home and layouts"). Its starter links are the first three screens of the navigation. -The example screens `/examples/ui`, `/examples/states` and `/examples/auth` -are one feature, `src/features/platform-examples-feature/`, in its own context -`src/contexts/platform-examples-context/` (1103/09-04). A product turns them -off like any feature: leave the id out of `VITE_PRODUCT_FEATURES`, or delete -the feature. To delete it, remove those two folders and -`tests/features/platform-examples-feature/` (its component tests), then run -`corepack pnpm generate:feature-index`; -`corepack pnpm test:sample-removal -- --feature=platform-examples-feature` -does the same in a copy of the repository and runs the gates there. Their -routes then leave the registry, the navigation, the bundle and the manual -accessibility list (FE-GATE-028). This document keeps naming the three -folders after they are gone: `verify:documentation` checks the paths of a -removable template feature (`scripts/lib/removable-template-features.ts`) -while the feature is installed and accepts them once its `feature-module.ts` -is gone (1105/14-01). +The template ships no example feature. Its example screens (`/examples/ui`, +`/examples/states`, `/examples/auth`) and its reference sample were deleted on +2026-11-07: the design-system and screen-state galleries are workshop stories +(`src/presentation/design-system/galleries.stories.tsx`), and the manual +(`docs/manual/`) with `create:feature` shows how a feature is built. A sample a +product keeps for a while is listed in +`scripts/lib/removable-template-features.ts`: `verify:documentation` checks its +paths while it is installed and accepts them once its `feature-module.ts` is +gone (1105/14-01), and `corepack pnpm test:sample-removal` removes it in a copy +of the repository and runs the gates there. The platform overview (`/examples/platform`, `src/presentation/examples/platform-overview-page.tsx`) stays a platform @@ -125,11 +120,12 @@ routes module before the page, a second request round the 200 ms budget does not fit. Its tests are the `tests/component/starter-*.test.tsx` files. The platform's component tests (router, boundaries, shell, runtime tree) run -on the pages of the test-only feature in `tests/helpers/fixture-feature.tsx` -and keep passing without the examples. The browser-level checks in -`tests/e2e` and `tests/visual` use the example screens as their pages and run -where the examples are installed: a product that leaves them out points those -specs at its own screens or deletes them. +on the pages of the test-only feature in `tests/helpers/fixture-feature.tsx`. +The browser-level checks in `tests/e2e` and `tests/visual` use the home page, +the platform overview and the gallery stories; what needs a feature +(`tests/e2e/generated-feature.spec.ts`, the chunk recovery spec) builds a copy +of the repository with the one `create:feature` writes +(`scripts/lib/generated-feature.ts`). ### Ownership declarations @@ -151,9 +147,9 @@ installed catalogs import, the context index the router loads lazily, and the selected app. Every build and check script runs it first; run it yourself with `corepack pnpm generate:feature-index`. It fails, naming the file, when: -- a directory under `src/features/` has no `feature-module.ts` and no - `NOT_A_FEATURE` marker file (`src/features/local-draft-feature/NOT_A_FEATURE` - is the one intentional example), or has both; +- a directory under `src/features/` has no `feature-module.ts`. Code that + is no feature (the IndexedDB consumer the tests compose, + `tests/fixtures/indexeddb-consumer`) lives outside `src/features/`; - a feature names an undeclared context, or a context an undeclared app; - a context or app exceeds its declared budget; - `VITE_PRODUCT_FEATURES` names a feature the app does not declare. The @@ -168,7 +164,7 @@ selected app. Every build and check script runs it first; run it yourself with invalidation, topic versions and the external `contractPackages` the release manifest is checked against at boot), its message catalogs, and `loadRuntime`, which imports `feature-runtime.ts` dynamically. - `src/features/reference-feature/feature-module.ts` is the complete example. + `create:feature` writes a complete one. 2. Create `src/features//feature-runtime.ts` with `defineFeatureRuntime`: the `schemas` (FE-REG-SCHEMA rows for the feature's route and API schemas), the adapter contributions @@ -183,13 +179,14 @@ selected app. Every build and check script runs it first; run it yourself with executes, and `check:registries` governs the FE-REG-API row projected from it (`projectApiOperationRows` in `src/contracts/api-operations.ts`). A product feature's contract contribution uses an `EXTERNAL_PACKAGE` - source. `TEMPLATE_FIXTURE` belongs to `reference-feature` only and never - joins the release contract set; the composer rejects it anywhere else. + source. `TEMPLATE_FIXTURE` was the template's reference sample source; it + never joins the release contract set, and the composer rejects it in any + product feature. 3. Create `src/features//context-routes.ts` exporting `FEATURE_CONTEXT_ROUTES`. Page components are imported lazily here, and each route handle carries the route's params/search `codecs`; the owning context loads this file only when its route root is visited - (`src/features/reference-feature/context-routes.ts`). Each handle's + (a `create:feature --with-create` feature's `context-routes.ts`). Each handle's `routeId` must be a route of a feature contract in the same context; the context refuses the routes when they load, naming the route, context and features (`src/contexts/bounded-context-module.ts`). @@ -207,7 +204,8 @@ selected app. Every build and check script runs it first; run it yourself with that takes over the platform home is the exception ("Product home and layouts"). 5. If the feature has application input, augment `ApplicationFeatureInputs` - from the feature (`src/features/local-draft-feature/application/local-draft-api.ts`). + from the feature (the IndexedDB consumer fixture does it in + `tests/fixtures/indexeddb-consumer/application/local-draft-api.ts`). 6. Run `corepack pnpm check:architecture`, `corepack pnpm check:types`, `corepack pnpm check:registries` and the tests. `tests/unit/two-feature-install-typecheck.test.ts` keeps the installed catalogs compiling with more than one feature. @@ -221,7 +219,7 @@ Files outside the feature directory. Everything else a feature needs is in | --- | --- | --- | | `src/.generated/*` | never by hand: every build and check script regenerates it | — | | `public/release-manifest.json` (tracked, the dev server's manifest) | every added or removed feature: `create:feature` rewrites it (`node scripts/write-dev-release-manifest.ts`). Commit it with the feature. Two feature branches change its `setDigest` line; on a merge conflict take either side and run the command again (1105/16-01) | `test:unit` (`tests/unit/dev-release-manifest.test.ts`) names the command; the dev server does not boot (`CONTRACT_SET_PACKAGE_MISSING`) | -| `config/scale/feature-shape-ceilings.json` `initialJavascript` (tracked, only while the sample is installed) | every added or removed feature, and every template change that moves the initial JavaScript: `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`. Commit it with the change; on a merge conflict run the command again | `test:unit` (the feature-shape growth test compares it with a build) | +| `config/scale/feature-shape-ceilings.json` `initialJavascript` (tracked) | every added or removed feature, and every template change that moves the initial JavaScript: `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`. Commit it with the change; on a merge conflict run the command again | `test:unit` (the feature-shape growth test compares it with a build) | | `src/contexts//context-module.ts` | the feature needs a new context | `generate:feature-index`: `Feature belongs to undeclared context ` | | `src/contexts//context-layout.tsx` | the context needs its own frame instead of `AppShell` (see "Product home and layouts" below) | nothing: without it the context renders in `AppShell` | | `artifacts/tests/a11y-manual/.md` | every route the feature adds. Copy a record and reset it to `Status: pending-manual-review` | `test:unit` (`tests/unit/manual-a11y-evidence.test.ts`), `verify:documentation` (names the route IDs) and FE-GATE-009 (`review:a11y-manual -- --format-only`). FE-GATE-028 requires the signed review at release | diff --git a/docs/architecture/typescript-state-and-data-flow.md b/docs/architecture/typescript-state-and-data-flow.md index a3ff6b2d..e845534d 100644 --- a/docs/architecture/typescript-state-and-data-flow.md +++ b/docs/architecture/typescript-state-and-data-flow.md @@ -157,7 +157,7 @@ export interface ApplicationFeatureInputs {} declare module "../../../application/ports/in/application-api.ts" { interface ApplicationFeatureInputs { - "reference-feature": ReferenceFeatureInput; + "invoice-feature": InvoiceFeatureInput; } } ``` @@ -342,8 +342,8 @@ export function useCreateResourceMutation() { `useApplicationMutation`은 bound 정의(`BoundMutation`)만 받는다(1101/08-03). `{ execute }`만 넘기는 raw 형태는 멱등 키와 scope 확인 없이 쓰기를 보내고 결과 불명 뒤 "다시 보내기"가 아무것도 하지 않아 타입에서 막는다. 실제 정의는 -`src/features/reference-feature/presentation/use-reference-feature.ts`의 -`REFERENCE_CREATE_MUTATION_POLICY`를 본다. +`create:feature --with-create`가 만드는 `presentation/use--create.ts`의 +작성 뮤테이션 정책을 본다. 기본 mutation은 navigation만으로 취소됐다고 가정하지 않는다. 서버 작업의 취소가 안전한 operation만 controller가 보관한 `AbortController`와 명시적 cancel action을 @@ -622,10 +622,9 @@ Form 또는 TanStack Form adapter를 평가한다. - controller와 mapping: `src/presentation/forms` - layout-only template: `src/presentation/templates` -- feature form schema/command mapper: - `src/features/reference-feature/presentation/reference-resource-form.ts` -- 실제 create page: - `src/features/reference-feature/presentation/reference-resource-form-page.tsx` +- feature form schema/command mapper: `create:feature --with-create`의 + `presentation/-form.ts` +- 실제 create page: 같은 판의 `presentation/-create-page.tsx` `ApiFailure.validationIssues`는 HTTP 경계가 투영한 `path`와 `code`만 담는다. backend message와 알 수 없는 path는 field copy로 사용하지 않는다. diff --git a/docs/contracts/compatibility.md b/docs/contracts/compatibility.md index 9185fd3b..9c481ac7 100644 --- a/docs/contracts/compatibility.md +++ b/docs/contracts/compatibility.md @@ -25,7 +25,7 @@ reader that accepts it must ship before any writer sends it. | `FEATURE_OVERRIDES` | record; unknown feature id ignored | additive | `featureOverrideArtifactSchema` in `src/contracts/release-artifacts.ts` | | Release manifest V2 | strict object | breaking | `releaseManifestV2ArtifactSchema` in `src/contracts/release-artifacts.ts` | | HTTP success/failure envelope (V3 with `responseEnvelope: "ENVELOPE_V1"`) | strict object (`meta` strips) | breaking | `successEnvelopeSchema`, `failureEnvelopeSchema` in `src/adapters/http/backend-envelope.ts` | -| HTTP V3 response DTO (reference feature) | `.strip()` drops unknown fields | additive | `referenceResourceDtoSchema` in `src/features/reference-feature/contracts/reference-schemas.ts` | +| HTTP V3 response DTO (a feature's) | `.strip()` drops unknown fields | additive | `ItemDtoSchema` in `contracts/-schemas.ts` of a feature `create:feature` writes | | Realtime envelope | exact key set; unknown `eventType` is `MALFORMED_EVENT` | breaking | `decodeUnsafe` in `src/adapters/realtime/event-codec.ts` | | Browser RPC transport error code | closed vocabulary; unknown code is a protocol violation | breaking | `decodeTransportFailure` in `src/adapters/browser-rpc/browser-rpc-runtime.ts` | | Persisted client storage | versioned key; incompatible value discarded | use a new key version | `defineStorageKey` in `src/contracts/storage-keys.ts` | diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index 34d9bff8..7b33b12d 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -5,9 +5,12 @@ - 뼈대는 손으로 만들지 않는다. `corepack pnpm create:feature `로 만든다. - 뼈대를 실제 기능으로 바꾸는 순서가 아래 0~11단계다. -참조 기능(`src/features/reference-feature/`)을 복사해 이름을 바꾸는 방법은 쓰지 않는다. -그 방법은 접두어 없는 전역 ID, 참조 전용 계약 출처, 기능 밖 테스트 의존 때문에 여러 번 막힌다. +다른 기능 폴더를 복사해 이름을 바꾸는 방법은 쓰지 않는다. +그 방법은 접두어 없는 전역 ID, 복사된 계약 출처, 기능 밖 테스트 의존 때문에 여러 번 막힌다. 생성 명령은 이 문제를 미리 피한 파일을 쓴다. +템플릿에는 복사해 볼 기능 샘플이 없다. 생성 뼈대에 없는 모양은 이 매뉴얼 안의 코드 조각으로 보인다. +코드 조각 위의 `manual-code-block` 표식이 그 조각을 둘 자리다. 조각은 `create:feature invoice-feature --with-create`로 만든 기능을 기준으로 쓴다. +`tests/unit/manual-code-blocks.test.ts`가 그 기능을 저장소 사본에 만들고 조각을 그 자리에 그대로 넣어 타입 검사와 동작 시험을 돌린다. ## 전체 흐름 @@ -107,7 +110,7 @@ corepack pnpm create:feature invoice-feature → 만든 파일과 다음 할 일 출력 ``` -- 기능과 함께 커밋할 추적 파일은 둘이다. dev server manifest와, 참조 기능이 있는 동안의 초기 JS 기록이다. 기능 브랜치 둘이 같은 줄에서 충돌하면 명령을 다시 돌린다. 표와 명령은 [03 문서 A](03-outside-feature-folder.md#a-생성-명령이-만든다)에 있다. +- 기능과 함께 커밋할 추적 파일은 둘이다. dev server manifest와 초기 JS 기록이다. 기능 브랜치 둘이 같은 줄에서 충돌하면 명령을 다시 돌린다. 표와 명령은 [03 문서 A](03-outside-feature-folder.md#a-생성-명령이-만든다)에 있다. ① **정할 것** @@ -130,8 +133,6 @@ corepack pnpm create:feature invoice-feature - 생성기가 거부한다. 선언 헤더가 리터럴이 아님, 없는 context, 예산 초과. - 이때 명령은 만든 파일을 모두 지우고 `the feature index generator rejected the feature, nothing was kept:`로 끝난다. - 생성한 context 선언은 `tests/unit/create-feature.test.ts`가 생성기의 선언 읽기와 앱 모듈 조립으로 실행한다. 라우트가 그 루트 밖이면 그 테스트가 실패한다. -- `--context reference-context`로 참조 context에 넣을 수는 있다. 참조 기능의 라우팅 테스트는 참조 기능 자신의 라우트만 본다. - - 다만 경로가 `/examples/reference-resources/`가 된다. 참조 기능을 지우면 context가 그 기능 때문에 남고, 그 경로 문자열이 제거 드릴(`test:sample-removal`)의 잔여 검사(`reference-resource`)에 걸린다(추론, 실행하지 않음). 남길 기능은 제품 context에 둔다. ④ **쓸 스킬**: `clean-architecture`, `codebase-design` @@ -150,12 +151,34 @@ corepack pnpm create:feature invoice-feature - 업무 규칙이 없으면 만들지 않는다. mapper가 DTO를 화면 값으로 바꾸는 것으로 충분하다. - 있으면 `domain/.ts`에 둔다. - 생성 함수에서 불변식을 검사하고 `Object.freeze`로 고정한다. - - 이름은 와이어 필드가 아니라 업무 이름으로 짓는다(참조 기능은 `name`을 `displayName`으로 바꾼다). -- 예제(참조 기능): `src/features/reference-feature/domain/` + - 이름은 와이어 필드가 아니라 업무 이름으로 짓는다(예: 와이어 `name`을 화면 값 `displayName`으로). +- 예: 청구서는 발행일 뒤에만 마감된다. `domain/.ts` 한 파일이다. + + +```ts +export type Invoice = Readonly<{ + invoiceId: string; + /** Calendar dates, YYYY-MM-DD. */ + issuedOn: string; + dueOn: string; +}>; + +/** An invoice falls due on or after the day it is issued. */ +export function createInvoice(input: Invoice): Invoice { + if (!/^\d{4}-\d{2}-\d{2}$/u.test(input.issuedOn) || !/^\d{4}-\d{2}-\d{2}$/u.test(input.dueOn)) { + throw new RangeError("Invoice dates are calendar dates (YYYY-MM-DD)."); + } + if (input.dueOn < input.issuedOn) { + throw new RangeError("An invoice falls due on or after the day it is issued."); + } + return Object.freeze({ ...input }); +} +``` + - 길이 제한(예: 제목 100자)은 domain이 아니라 경계 검증에 둔다. - 경계 검증: 값이 앱에 들어오거나 나가는 자리(요청·응답 스키마, 폼 스키마)에서 하는 검사다. - 서버가 정한 제한이면 `contracts/-schemas.ts`에 상수로 두고 요청 스키마와 폼 스키마가 같은 상수를 쓴다. 숫자가 두 곳에서 갈라지지 않는다. - - 참조 기능도 이름 길이를 스키마(`reference-schemas.ts`)와 폼(`reference-resource-form.ts`)에만 둔다. `domain/`에는 없다. + - 생성 판(`--with-create`)도 이름 길이 상수(`_NAME_MAX_LENGTH`)를 스키마(`contracts/-schemas.ts`)와 폼(`presentation/-form.ts`)에만 둔다. `domain/`에는 없다. - domain에는 서버 제한이 바뀌어도 그대로인 업무 규칙만 둔다(예: "마감일은 시작일 뒤"). ③ **잡는 검사 / 못 잡는 것** @@ -241,7 +264,7 @@ DTO와 problem details(`type`·`title`·`status`)를 감싸지 않고 보내는 2. problem 스키마를 problem details 모양으로 바꾼다. 3. `classifyProblem`이 모든 판정을 정한다. 실행기가 먼저 정하는 판정은 없다. -참조 기능(`src/features/reference-feature/`)이 이 모양이다. 참조 기능의 MSW 본문도 DTO와 problem details다. +problem 스키마, 작성의 `commandEffect`, `mapProblem`의 예는 [02 결정표 4절](02-decision-tables.md#4-결과-불명)의 「problem details 백엔드의 예」에 있다. 그 기능의 MSW 본문도 DTO와 problem details로 손으로 적는다. **입력과 스키마 메타데이터** @@ -305,8 +328,8 @@ projectRequest: (input) => Object.freeze({ - 오류의 `reason`: `/: unknown authProfileId ` - 스키마 ID나 operation ID가 겹치면 적재 때 그 ID를 말하며 실패한다. - 예: `Invalid or duplicate schema definition: `, 계약 조립 `duplicate operation: ` -- `TEMPLATE_FIXTURE` 출처를 참조 기능 밖에서 쓰면 계약 조립이 거부한다. - - 오류의 `reason`: `: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to reference-feature only; pin an EXTERNAL_PACKAGE` +- `TEMPLATE_FIXTURE` 출처를 제품 기능에 쓰면 계약 조립이 거부한다. + - 오류의 `reason`: `: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to only; pin an EXTERNAL_PACKAGE` - zod를 직접 import하면 `check:architecture`가 `zod-is-reached-through-contracts-zod`로 막는다. - 계약 패키지를 다른 파일에서 import하면 `external-contract-package-single-import-path`로 막는다. - 자리표시자 신원은 staging·production 승인(`check:release-admission`, FE-GATE-027)이 거절한다. @@ -376,10 +399,9 @@ projectRequest: (input) => Object.freeze({ - 읽기: 데이터를 그리는 화면. 목록 GET은 목록 route, 상세 GET은 상세 route. - 쓰기: 저장 버튼이 있는 화면. 작성 폼 route가 따로 있으면 그 route. - 여러 화면에서 부르면 주로 부르는 화면 하나를 고른다. 이름표는 하나뿐이다. - - 참조 기능은 생성 operation에 목록 route(`REFERENCE_RESOURCE_LIST`)를 적었다. 실제로 보내는 화면은 폼 route다. 동작은 같고 기록의 이름표만 다르다. 새 기능은 위 기준을 따른다. - `needs`에는 실제로 쓰는 것만 적는다. - 템플릿이 만들지 않는 capability(예: `indexedDb`)는 `src/bootstrap/product-composition.ts`에서 만든다. 제품이 새로 만드는 capability의 타입은 `src/features/product-capabilities.ts`에 적는다. [03 문서](03-outside-feature-folder.md)를 본다. -- 문제 응답 매핑 예제(참조 기능): `src/features/reference-feature/adapters/reference-http-gateway.ts` +- 문제 응답 매핑 예제: 짝 백엔드는 `create:feature --with-create`의 `adapters/-http-gateway.ts`(400 `_INVALID` → 이름 칸). problem details 백엔드는 [02 결정표 4절](02-decision-tables.md#4-결과-불명)의 조각 2. ③ **잡는 검사 / 못 잡는 것** @@ -423,11 +445,49 @@ projectRequest: (input) => Object.freeze({ ② **기준** - 경로는 계약에만 적는다. 페이지와 링크는 route ID와 `buildRouteUrl`로 URL을 만든다. 경로 문자열을 페이지에 다시 적지 않는다. -- 파라미터나 검색값이 있는 라우트는 `context-routes.ts`의 handle에 `codecs`를 싣는다. 예제(참조 기능): `src/features/reference-feature/context-routes.ts`. - - 링크용 URL 함수도 같은 codec을 `buildRouteUrl`의 세 번째 인자로 넘긴다. 기본 생성 판의 목록 라우트는 파라미터가 없어서 넘기지 않는다. `--with-create` 판의 상세 라우트는 codec을 넘긴다. 안 넘기면 `Unregistered route codec: `로 throw한다. codec ID는 계약 `routeRuntimeContracts`의 `paramsCodec`·`searchCodec` 값이다. 예제(참조 기능): `src/features/reference-feature/presentation/reference-routes.ts`. +- 파라미터나 검색값이 있는 라우트는 `context-routes.ts`의 handle에 `codecs`를 싣는다. 예제: `create:feature --with-create`의 `context-routes.ts`(상세 라우트의 params codec). + - 링크용 URL 함수도 같은 codec을 `buildRouteUrl`의 세 번째 인자로 넘긴다. 기본 생성 판의 목록 라우트는 파라미터가 없어서 넘기지 않는다. `--with-create` 판의 상세 라우트는 codec을 넘긴다. 안 넘기면 `Unregistered route codec: `로 throw한다. codec ID는 계약 `routeRuntimeContracts`의 `paramsCodec`·`searchCodec` 값이다. 예제: `--with-create` 판의 `presentation/-routes.ts`. +- 검색값(`?status=open`)을 읽는 목록은 아래 두 조각을 더한다. 생성 뼈대의 목록 라우트에는 검색값이 없다. + - 조각 1(`contracts/-list-search.ts`)이 검색값 스키마다. 그 스키마를 `presentation/-route-codecs.ts`의 `_ROUTE_CODECS`에 `ListSearch`라는 codec ID로 싣는다. + - 계약의 목록 라우트 `searchSchema`와 `routeRuntimeContracts`의 `searchCodec`을 그 codec ID로 바꾼다. 기본 판처럼 `context-routes.ts` handle에 `codecs`가 없으면 `--with-create` 판처럼 싣는다. + - 라우터는 페이지를 그리기 전에 그 codec으로 검색값을 해석한다. 틀린 값이면 페이지 대신 잘못된 경로 화면을 그린다. + - 조각 2(`presentation/use--list-filters.ts`)가 페이지에서 그 값을 타입대로 읽는 hook이다. 같은 codec으로 다시 읽으므로 cast가 없다. + + +```ts +import { z } from "../../../contracts/zod.ts"; + +/** The list route's search values (`?status=open`). Absent means every invoice. */ +export const invoiceListSearchSchema = z + .object({ status: z.enum(["open", "paid"]).optional() }) + .strict(); + +export type InvoiceListSearch = z.output; +``` + + +```ts +import { useMemo } from "react"; + +import { useRouteInput } from "../../../presentation/routes/route-input.tsx"; +import { + invoiceListSearchSchema, + type InvoiceListSearch, +} from "../contracts/invoice-list-search.ts"; + +/** + * The router parsed the search with this codec before the page rendered. + * Reading it back through the same codec gives its type without a cast. + */ +export function useInvoiceListFilters(): InvoiceListSearch { + const { search } = useRouteInput(); + return useMemo(() => invoiceListSearchSchema.parse(search), [search]); +} +``` + - 상세 경로는 목록 경로 뒤에 `/items/:`을 붙인다. 예: `/notice/items/:noticeId`. `/notice/:noticeId`로 두지 않는다. - 라우터(React Router)는 같은 자리에서 정적 경로를 먼저 고른다. 작성 폼 `/notice/new`가 있으면 id가 `new`인 공지는 `/notice/:noticeId`로 열 수 없다. - - `items/`를 끼우면 정적 경로와 겹치지 않는다. 참조 기능도 이렇게 한다(`/examples/reference-resources/items/:resourceId`). + - `items/`를 끼우면 정적 경로와 겹치지 않는다. 생성 판(`--with-create`)의 상세 라우트도 이렇게 한다(`<목록 경로>/items/:Id`). - `tests/e2e/accessibility.spec.ts`는 기능마다 고치지 않는다(1103/16-03). - 이 spec은 등록된 모든 라우트를 열어 axe로 검사한다. 경로 파라미터는 이름과 상관없이 모두 `a11y-1`로 바꾼다. 파라미터 스키마가 이 값을 거부하면 기능 페이지 대신 잘못된 경로 화면을 검사하므로, id 스키마는 짧은 영문·숫자 문자열을 받게 둔다. - API 요청은 설치된 descriptor에서 method와 `pathTemplate`으로 찾아 답한다. 목록 조회에는 빈 목록을 그 operation의 모양(`responseEnvelope: "ENVELOPE_V1"`이면 Envelope)으로 답한다. 그 뒤 경고 상자(`role="alert"`)가 없는지 본다. 그래서 목록 페이지는 빈 상태로 검사된다. @@ -492,7 +552,7 @@ projectRequest: (input) => Object.freeze({ }); ``` - - 예제(참조 기능): `src/features/reference-feature/presentation/use-reference-feature.ts`의 생성 뮤테이션 정책. + - 예제: `create:feature --with-create`의 `presentation/use--create.ts`. ③ **잡는 검사 / 못 잡는 것** @@ -524,7 +584,40 @@ projectRequest: (input) => Object.freeze({ - 화면 문구는 모두 catalog에서 가져온다(`message(key)`). - 링크는 6단계의 URL 함수로 만든다. -- 결과 불명 화면 예제: `create:feature --with-create`의 `presentation/-create-page.tsx`(짝 백엔드 Envelope), 참조 기능의 `src/features/reference-feature/presentation/reference-resource-form-page.tsx`(problem details) +- 결과 불명 화면 예제: `create:feature --with-create`의 `presentation/-create-page.tsx`. problem details 백엔드도 화면은 같다. 다른 것은 `commandEffect`와 `mapProblem`뿐이다([02 결정표 4절](02-decision-tables.md#4-결과-불명)). +- 다시 시도가 아닌 실패 행동(다시 로그인, 안전한 화면으로 이동)의 버튼은 페이지가 handler를 넘길 때만 그려진다. 생성된 목록 페이지는 `onRetry`만 넘긴다. + - 실패의 `action`(`src/contracts/errors.ts`의 `ERROR_REGISTRY`)이 `reauth`(401)·`navigate`(403·404)일 때 쓸 hook이다. `AsyncSurface`에 `onAction={useInvoiceFailureAction(query.state.failure)}`로 넘긴다. + - `retry`는 쿼리(`onRetry`)가, `reload-once`는 청크 복구 경계가 맡는다. 이 hook은 `undefined`를 돌려준다. + + +```ts +import { useCallback } from "react"; +import { useLocation, useNavigate } from "react-router-dom"; + +import type { AppFailure } from "../../../contracts/errors.ts"; +import { useSession } from "../../../presentation/providers/session-provider.tsx"; + +/** Sign in again and come back here, or leave for the home screen. */ +export function useInvoiceFailureAction( + failure: AppFailure | undefined, +): (() => void) | undefined { + const location = useLocation(); + const navigate = useNavigate(); + const { beginSignIn } = useSession(); + const action = failure?.action; + const handleAction = useCallback(() => { + if (action === "reauth") { + const returnTo = `${location.pathname}${location.search}${location.hash}`; + void beginSignIn(returnTo).catch(() => { + void navigate("/"); + }); + return; + } + if (action === "navigate") void navigate("/"); + }, [action, beginSignIn, location.hash, location.pathname, location.search, navigate]); + return action === "reauth" || action === "navigate" ? handleAction : undefined; +} +``` ③ **잡는 검사 / 못 잡는 것** @@ -621,7 +714,38 @@ projectRequest: (input) => Object.freeze({ expect(await posts[0]!.json()).toEqual({ title: "새 공지", body: "본문입니다." }); ``` - - 핸들러를 직접 써서 요청을 모으는 방법도 있다. 예제(참조 기능): `tests/features/reference-feature/reference-production-vertical.test.tsx`의 504 재전송 테스트. + - 핸들러를 직접 써서 요청을 모으는 방법도 있다. 예제: `create:feature --with-create --keyed`의 `tests/features//-create-page.test.tsx`(POST를 받을 때마다 사본을 모으고 같은 키 재전송을 본다). +- 서버 권한 거절(403)은 라우터를 거치는 페이지 테스트로 본다. 생성된 페이지 테스트와 같은 도우미(`-test-app.tsx`)를 쓴다. + - 403은 본문 없이 답한다. 실행기는 401·403의 본문을 읽지 않고 닫는다. 페이지 테스트 환경(jsdom + MSW)에서 본문이 있는 403(공유 시나리오 `forbidden-403`)은 그 닫기가 끝나지 않아 화면이 로딩에 머물렀다(2026-11-08 확인). + + +```tsx +// @vitest-environment jsdom + +import { screen, within } from "@testing-library/react"; +import { http, HttpResponse } from "msw"; +import { setupServer } from "msw/node"; +import { afterAll, afterEach, beforeAll, expect, it } from "vitest"; + +import { invoiceRouteUrl } from "../../../src/features/invoice-feature/presentation/invoice-routes.ts"; +import { KO_MESSAGES } from "../../../src/presentation/i18n/catalog.ts"; +import { API, openSignedIn } from "./invoice-test-app.tsx"; + +const api = setupServer(); +beforeAll(() => api.listen({ onUnhandledRequest: "error" })); +afterEach(() => api.resetHandlers()); +afterAll(() => api.close()); + +it("shows the forbidden state when the backend refuses the list", async () => { + api.use(http.get(`${API}/invoices`, () => new HttpResponse(null, { status: 403 }))); + await openSignedIn(invoiceRouteUrl("INVOICE_LIST")); + + const alert = await screen.findByRole("alert"); + expect( + within(alert).getByRole("heading", { name: KO_MESSAGES["access.forbidden.title"] }), + ).toBeVisible(); +}); +``` - 빠르게 돌리기: `node scripts/run-vitest.ts run tests/features/` - CI에서는 `test:coverage`(FE-GATE-005)가 `tests/features`를 돈다. `test:unit`은 `tests/unit`만 돈다. @@ -683,7 +807,7 @@ corepack pnpm test:sample-removal -- --feature=invoice-feature - 지연 페이지가 셸과 같은 구성요소(`Button`, `SearchField` 등)를 쓰면 그 구성요소가 공유 청크로 떨어져 초기 파일 수도 하나 늘 수 있다. 파일 수 상한(`initialJsFiles`)은 여유가 있다. - 예산은 `config/performance/budgets.json`에 있다. 넘었을 때 고르는 법은 `docs/operations/performance-evidence.md`에 있다. 넘으면 예산을 올리기 전에 팀이 정한다. - 생성 명령의 드릴(`test:feature-scaffold`)도 merge 단계 명령으로 이 검사를 돈다. -- 참조 기능이 설치돼 있으면 초기 JS 기록(`config/scale/feature-shape-ceilings.json`)도 기능과 함께 바뀐다. `test:unit`이 빌드와 대조한다. 생성 명령 출력 `Next:` 3번의 명령으로 다시 쓰고 같은 커밋에 넣는다. 기능 제거 드릴(`test:sample-removal -- --feature=`)은 지운 뒤 기록을 다시 쓰고 검사한다. +- 초기 JS 기록(`config/scale/feature-shape-ceilings.json`)도 기능과 함께 바뀐다. `test:unit`이 빌드와 대조한다. 생성 명령 출력 `Next:` 3번의 명령으로 다시 쓰고 같은 커밋에 넣는다. 기능 제거 드릴(`test:sample-removal -- --feature=`)은 지운 뒤 기록을 다시 쓰고 검사한다. - 로컬에서 FE-GATE-013을 돌리려면 `VITE_COMMIT_SHA=$(git rev-parse HEAD)`를 준다. 없으면 release candidate가 `source.revision`을 거절한다. 실패한 게이트의 로그는 `artifacts/quality/gates/FE-GATE-.txt`에 있다. - workflow와 같은 조건으로 돌리려면 README 로컬 merge 게이트 반복문 아래의 env 블록대로 `CI=true`와 CI 빌드 식별값(`VITE_COMMIT_SHA`, `VITE_BUILD_ID`, `RELEASE_ID`, `CI_RUNNER_IMAGE` digest)을 주고 깨끗한 clone에서 돌린다. 이 값 없이 통과해도 CI에서 떨어질 수 있다(1103/11-07, 11-08). - 게이트는 한 checkout에서 하나씩 돌린다. 게이트와 증거 검사는 `dist`와 `artifacts/`의 고정 경로를 읽는다. diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 10e5d217..991025b1 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -50,9 +50,9 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 | | 배포된 계약 패키지 | 자리표시자 신원 | `TEMPLATE_FIXTURE` | |---|---|---|---| -| 언제 | 백엔드가 `@org-contracts/` 패키지를 배포했다 | 패키지가 아직 없다 | 쓰지 않는다. 참조 기능 전용이다 | +| 언제 | 백엔드가 `@org-contracts/` 패키지를 배포했다 | 패키지가 아직 없다 | 쓰지 않는다. 템플릿이 예전 참조 샘플에 쓰던 출처다 | | 만드는 법 | `create:feature`에 `--package`, `--digest`, `--revision`을 준다 | `create:feature`에 패키지 인자를 주지 않는다 | — | -| 로컬·개발 빌드 | 된다 | 된다 | 참조 기능 밖에서는 계약 조립이 거부한다 | +| 로컬·개발 빌드 | 된다 | 된다 | 제품 기능에 쓰면 계약 조립이 거부한다 | | staging·production 승인 | 된다 | `check:release-admission`(FE-GATE-027)이 거절한다 | — | 자리표시자 값은 `src/contracts/deployment-admission.ts`의 세 상수다. @@ -88,7 +88,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 |---|---|---|---| | 서버 보장 | 멱등 키(`Idempotency-Key` 헤더)로 같은 요청의 중복 적용을 막는다 | 같은 요청을 여러 번 적용해도 결과가 같다 (키 없이) | 중복을 막지 못한다 | | 자동 재시도 | 실제로 보내기 전까지만. 보낸 뒤 결과를 모르면 결과 불명(4절)으로 넘긴다. 예외: 짝 백엔드가 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거절)로 답하면 `retryBudget` 안에서 같은 키로 다시 보낸다 | 된다 | 하지 않는다 | -| descriptor | `commandRecovery: { mode: "IDEMPOTENCY_REPLAY", operationIdentityField }` 필수. 짝 백엔드는 `retryBudget: 1`(아래 표), 참조 기능은 `0` | — | `retryBudget: 0` 필수 | +| descriptor | `commandRecovery: { mode: "IDEMPOTENCY_REPLAY", operationIdentityField }` 필수. 짝 백엔드는 `retryBudget: 1`(아래 표). 503 같은 키 재전송 규칙이 없는 백엔드는 `0` | — | `retryBudget: 0` 필수 | | 뮤테이션 정책 | `...commandMutationIdentity(_CONTRACT)`가 `requiresIdempotencyKey: true`, `resendSafe: true`를 준다 | 같은 함수가 `requiresIdempotencyKey: false`, `resendSafe: true`를 준다 | 같은 함수가 둘 다 `false`로 준다 | | 결과 불명 뒤 | "같은 요청으로 다시 보내기"와 같은 입력 저장이 같은 키로 간다 | 다시 보내기와 같은 입력 저장이 키 없이 간다(1106/03-03) | 확인만 남는다. 같은 입력 저장은 보내지 않는다 | @@ -198,8 +198,8 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 → V3 실행기 ├─ responseEnvelope: "ENVELOPE_V1" (생성한 기능) → 실행기가 MAYBE_APPLIED로 정한다 │ KEYED이고 retryBudget > 0이면 먼저 같은 키로 다시 보낸다(3절). 예산을 다 쓰면 결과 불명 - └─ Envelope 없음 (참조 기능) → 기능의 classifyProblem이 정한다 - 참조 기능: 400·422와 정해 둔 409 code만 NOT_APPLIED → 503은 MAYBE_APPLIED + └─ Envelope 없음 (problem details 백엔드) → 기능의 classifyProblem이 정한다 + 아래 예: 400·422와 정해 둔 409 code만 NOT_APPLIED → 503은 MAYBE_APPLIED → 결과 불명 화면 → "같은 요청으로 다시 보내기"가 같은 키로 보낸다 ``` @@ -210,7 +210,123 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 **정본**: 어떤 status·code가 "적용 안 됨"인지는 `clean-architecture-backend-template/docs/web/http-contract.md` §2다. -**어디에 적나**: `contracts/-contract-contribution.ts`의 `commandEffect`(`classifyProblem`, `classifyStatus`, Envelope operation이면 `refusedBeforeWrite`). 예제(참조 기능): `src/features/reference-feature/contracts/reference-feature-contract-contribution.ts`의 `CREATE_EFFECT`. +**어디에 적나**: `contracts/-contract-contribution.ts`의 `commandEffect`(`classifyProblem`, `classifyStatus`, Envelope operation이면 `refusedBeforeWrite`). 짝 백엔드 예제는 `create:feature --with-create`가 만든 그 파일이다. Envelope가 없는 백엔드의 예는 아래에 있다. + +**problem details 백엔드의 예** + +짝 백엔드가 아닌 백엔드는 DTO와 problem details(RFC 9457의 `type`·`title`·`status`)를 감싸지 않고 보낸다. 그 백엔드의 작성 operation이 쓰는 두 조각이다. 기능 이름은 `invoice-feature`(`create:feature invoice-feature --with-create`로 만든 기능)로 두었다. 자기 기능의 이름으로 바꿔 쓴다. + +- 조각 1은 `contracts/-problem-details.ts`다. problem 스키마와 검증기, 작성의 `commandEffect`를 둔다. + - descriptor마다 `responseEnvelope: "NONE" as const`, `problemValidator: _PROBLEM_VALIDATOR`를 적는다. 작성 descriptor의 `commandEffect`는 `_CREATE_EFFECT`다. Envelope operation 전용인 `refusedBeforeWrite`는 적지 않는다. + - 스키마 ID(`InvoiceProblem`)도 다른 스키마처럼 스키마 메타데이터(`contracts/-schema-metadata.ts`)에 적는다. 없으면 `check:registries`가 실패한다. +- 조각 2는 `adapters/-problem-mapping.ts`다. HTTP 바인딩의 `mapProblem`이 되는 함수다. + - `adapters/-http-gateway.ts`의 작성 operation 정의에 `mapProblem: mapCreateProblem`으로 넘긴다. + - 정하지 않은 status는 `undefined`를 돌려준다. 그러면 실행기가 status로 실패 종류를 정한다. + + +```ts +import { z } from "../../../contracts/zod.ts"; + +import type { CommandEffectDescriptor } from "../../../contracts/external-contract-runtime.ts"; +import { zodValidator } from "../../../contracts/zod-validator.ts"; + +export const invoiceProblemSchema = z + .object({ + type: z.string().min(1).max(512), + title: z.string().min(1).max(240), + status: z.int().min(100).max(599), + code: z.string().min(1).max(120).optional(), + // 422 field issues. The backend's messages are not kept. + issues: z + .array( + z + .object({ + path: z.string().min(1).max(120), + code: z.string().min(1).max(80), + }) + .strip(), + ) + .max(50) + .optional(), + }) + .strip(); + +export type InvoiceProblem = z.output; + +export const INVOICE_PROBLEM_VALIDATOR = zodValidator( + "InvoiceProblem", + invoiceProblemSchema, +); + +/** + * A 409 is not by itself "refused": a resend with the same key can meet the + * first attempt still running. Only the conflict codes the backend sends + * before it writes are NOT_APPLIED; any other 409 stays MAYBE_APPLIED, so the + * next send reuses the key. + */ +const NOT_APPLIED_CONFLICT_CODES: ReadonlySet = new Set(["CONFLICT"]); + +export const INVOICE_CREATE_EFFECT: CommandEffectDescriptor = + Object.freeze({ + successEffect: "APPLIED_CONFIRMED" as const, + classifyProblem({ + status, + problem, + }: Readonly<{ status: number; problem: InvoiceProblem }>) { + if (status === 400 || status === 422) return "NOT_APPLIED"; + if ( + status === 409 && + problem.code !== undefined && + NOT_APPLIED_CONFLICT_CODES.has(problem.code) + ) { + return "NOT_APPLIED"; + } + return "MAYBE_APPLIED"; + }, + // The backend refuses an unauthenticated, forbidden or rate-limited + // create before it touches state. Delete this line if it does not. + classifyStatus: () => "NOT_APPLIED" as const, + }); +``` + + +```ts +import type { + FeatureHttpProblemMapping, + SafeResponseMetadata, +} from "../../../adapters/http/index.ts"; +import type { InvoiceProblem } from "../contracts/invoice-problem-details.ts"; + +export function mapInvoiceCreateProblem( + problem: InvoiceProblem, + metadata: SafeResponseMetadata, +): FeatureHttpProblemMapping | undefined { + if (metadata.status === 409) { + return Object.freeze({ + kind: "CONFLICT" as const, + code: problem.code ?? "INVOICE_CONFLICT", + }); + } + // The executor checked the key before it sent, so this names a key rule + // the two sides disagree on: keep the code for diagnostics. + if (metadata.status === 400 && problem.code === "IDEMPOTENCY_KEY_INVALID") { + return Object.freeze({ + kind: "UNKNOWN_CLIENT_FAILURE" as const, + code: problem.code, + }); + } + if (metadata.status === 422) { + return Object.freeze({ + kind: "VALIDATION_REJECTED" as const, + code: problem.code ?? "INVOICE_REJECTED", + validationIssues: problem.issues ?? [], + }); + } + return undefined; +} +``` + +- 이 두 조각은 `tests/unit/manual-code-blocks.test.ts`가 시험한다. 저장소 사본에 `create:feature invoice-feature --with-create`로 기능을 만들고, 조각을 위 경로에 그대로 넣어 타입 검사를 하고, 분류와 매핑이 위 설명대로인지 돌려 본다(`tests/fixtures/manual-code-blocks/`). **틀리면** diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index 69058b8c..d96aeef6 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -38,7 +38,7 @@ | 파일 | 누가 쓰나 | 다시 쓰는 명령 | 안 넣으면 | |---|---|---|---| | `public/release-manifest.json` (dev server의 manifest) | `create:feature`가 생성 뒤 바로 쓴다. 설치된 계약 패키지 목록(`packages`)과 그 다이제스트(`setDigest`) | `node scripts/write-dev-release-manifest.ts` | `test:unit`(`tests/unit/dev-release-manifest.test.ts`)이 다시 쓰는 명령을 말하며 실패한다. dev server가 `CONTRACT_SET_PACKAGE_MISSING`으로 부팅하지 못한다 | -| `config/scale/feature-shape-ceilings.json`의 `initialJavascript` (초기 JS 기록) | 사람이 명령으로 쓴다. 참조 기능이 설치돼 있는 동안만 있다(참조 기능과 함께 지워진다) | `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write` | `test:unit`이 빌드와 대조해 실패한다 | +| `config/scale/feature-shape-ceilings.json`의 `initialJavascript` (초기 JS 기록) | 사람이 명령으로 쓴다. 기능을 더하거나 뺄 때마다 바뀐다 | `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write` | `test:unit`이 빌드와 대조해 실패한다 | - **브랜치 둘이 충돌한다.** `setDigest`는 설치된 패키지 전체의 해시 한 줄이고, `initialJavascript`는 빌드 전체의 합계다. 기능을 하나씩 더한 두 브랜치는 같은 줄을 다른 값으로 바꾼다. 둘째 브랜치를 합칠 때 텍스트 충돌이 난다. - **충돌하면 손으로 값을 합치지 않는다.** 아무 쪽이나 고른 뒤 위 명령을 다시 돌려 그 결과를 커밋한다. 두 기능이 다 들어간 상태의 값이 나온다. 손으로 합친 값이 틀리면 `test:unit`이 같은 명령을 말하며 실패한다. @@ -212,7 +212,7 @@ src/features/product-capabilities.ts (SERVICE_WORKER = ACTIVE) - `config/testing/risk-coverage.json`에서 그 기능을 가리키는 행 - 그 기능만 쓰던 제품 capability, 제품 인증 프로필, 계약 패키지 의존성 -그다음 dev manifest(`public/release-manifest.json`)의 계약 패키지를 `node scripts/write-dev-release-manifest.ts`로 다시 쓰고, 참조 기능이 설치돼 있으면 초기 JS 기록(`config/scale/feature-shape-ceilings.json`)도 `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`로 다시 쓴다(위 A의 표). 그리고 레지스트리 기준선을 다시 찍는다. 행을 빼는 것은 breaking 변경이다. +그다음 dev manifest(`public/release-manifest.json`)의 계약 패키지를 `node scripts/write-dev-release-manifest.ts`로 다시 쓰고, 초기 JS 기록(`config/scale/feature-shape-ceilings.json`)도 `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`로 다시 쓴다(위 A의 표). 그리고 레지스트리 기준선을 다시 찍는다. 행을 빼는 것은 breaking 변경이다. ```bash REGISTRY_BASELINE_OWNER=<담당> REGISTRY_BASELINE_REASON=" removed" corepack pnpm update:registry-baseline diff --git a/docs/manual/README.md b/docs/manual/README.md index 3b515366..1f1cf753 100644 --- a/docs/manual/README.md +++ b/docs/manual/README.md @@ -75,8 +75,8 @@ README (이 문서) - `docs/architecture/starter-experience.md`의 예전 "폴더 밖 수정" 4행 표와 "governance는 바뀌지 않는다" 문장(2026-11-01 리뷰 시점 판). - 그 판은 실제로 고쳐야 하는 파일을 다 적지 않았다. - 지금 판의 "Adding a feature" 절 표가 정본이다. 03 문서가 이 표를 링크한다. -- 참조 기능 페이지의 경로 문자열과 route 입력 cast. - - 지금은 고쳐졌다. 그래도 이 매뉴얼의 예시는 route ID와 `buildRouteUrl`로만 쓴다. +- 템플릿이 예전에 두던 참조 샘플 기능과 예제 화면을 가리키는 문서와 리뷰 기록. + - 그 샘플은 지웠다. 이 매뉴얼의 예시는 생성 명령 출력과 매뉴얼 안 코드 조각이다(`tests/unit/manual-code-blocks.test.ts`가 시험한다). ## 문서와 코드가 다를 때 diff --git a/docs/manual/reference/create-feature.md b/docs/manual/reference/create-feature.md index eec50049..f515d8f7 100644 --- a/docs/manual/reference/create-feature.md +++ b/docs/manual/reference/create-feature.md @@ -2,7 +2,7 @@ 모든 merge 게이트를 통과하는 가장 작은 기능을 만드는 명령이다. 정본은 `scripts/create-feature.ts`이고, `--with-create`가 더하는 부분은 `scripts/create-feature-write-slice.ts`다. `test:feature-scaffold`가 생성한 기능으로 `config/ci/gates.json`의 merge 단계 명령을 돌려 확인한다. 브라우저 게이트(FE-GATE-008·009의 브라우저 명령)와 `test:system`은 빼고 돈다. 뺀 명령과 이유는 `scripts/lib/feature-scaffold-drill.ts`에 있다. -템플릿 문자열이 두 파일 안에 있고, 참조 기능을 import하지 않는다. 그래서 참조 기능을 지운 프로젝트에서도 동작한다. +템플릿 문자열이 두 파일 안에 있고, 다른 기능을 import하지 않는다. 그래서 기능이 하나도 없는 템플릿에서도 동작한다. ## 사용법 @@ -150,17 +150,19 @@ node scripts/write-dev-release-manifest.ts # dev manifest에서 그 기능의 - `tests/unit/create-feature.test.ts` (`test:unit`, FE-GATE-005) - 렌더 결과만 본다. 저장소를 건드리지 않는다. - - 접두어, 참조 기능 이름이 없음, topic 형식과 충돌, `navigationOrder`, 거부 조건, 덮어쓰기 거부와 되돌리기. + - 접두어, 예전 참조 샘플 이름이 없음, topic 형식과 충돌, `navigationOrder`, 거부 조건, 덮어쓰기 거부와 되돌리기. - 백엔드 경로 규칙, `--with-create`·`--keyed`의 descriptor 값, 모든 operation의 Envelope 선언. - 생성한 context 선언을 임시 폴더에 써서 생성기의 선언 읽기(`createFileSystemDeclarationSource`)로 읽고, 그 모듈을 import해 라우트 루트가 기능 라우트를 모두 받는지 앱 모듈 조립으로 확인한다. - `test:feature-scaffold` (FE-GATE-020) - 저장소 복사본에 기능 둘(기본 하나, `--with-create --keyed` 하나)을 만들고 커밋한 뒤 게이트를 돈다. - 타입, lint, 아키텍처, 레지스트리, i18n, 디자인 시스템, 진단, 문서, unit, component, integration, 기능 테스트, 커버리지, CI 계약, 빌드. -- `test:sample-removal` (FE-GATE-020) - - 참조 기능을 지운 복사본에서 이 명령(`--with-create`)으로 기능을 만들고 같은 게이트를 다시 돈다. 명령과 쓰기 slice가 참조 기능에 기대지 않는다는 증거다. +- `test:sample-removal -- --feature=` (`test:feature-scaffold`가 부른다) + - 위에서 만든 기본 기능을 복사본에서 지우고 같은 게이트를 다시 돈다. 생성 기능이 지워진다는 증거다. + - 인자 없이 돌면(FE-GATE-020) `scripts/lib/removable-template-features.ts`에 적힌 샘플을 하나씩 지우고, 지운 복사본에서 이 명령(`--with-create`)으로 기능을 만들어 게이트를 다시 돈다. 템플릿은 그 목록이 비어 있어 건너뛰었다고(SKIP) 출력한다. +- `tests/e2e/generated-feature.spec.ts` (`test:e2e`, FE-GATE-008) + - 저장소 복사본에 `--with-create --keyed` 기능을 만들어 빌드하고, 실제 브라우저에서 로그인 뒤 목록, 폼 검증, 이탈 확인, 저장(멱등 키), 429 뒤 다시 시도, 결과 불명과 같은 키 재전송, 접근성(axe)을 본다. 생성기 출력이 바뀌면 여기서 잡힌다. ## 알려진 한계 -- `--context reference-context`로 참조 context에 넣은 기능은 경로가 `/examples/reference-resources/`다. 참조 기능을 지우면 context가 남고 그 경로가 제거 드릴의 잔여 검사에 걸린다. 남길 기능은 제품 context에 둔다. -- 드릴은 브라우저 테스트(FE-GATE-008·009의 `test:e2e`, `test:a11y` 등)와 `test:system`을 돌리지 않는다. `check:bundle`(FE-GATE-012)은 돈다. +- 드릴은 브라우저 테스트(FE-GATE-008·009의 `test:e2e`, `test:a11y` 등)와 `test:system`을 돌리지 않는다. `check:bundle`(FE-GATE-012)은 돈다. 브라우저에서의 동작은 위 e2e spec이 고정한 이름(`order-feature`)의 기능 하나로만 본다. - 새 context는 앱이 하나일 때만 만든다. 앱이 여럿이면 `--context`로 기존 context를 고른다. diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index 3595a75f..13f0823c 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -56,8 +56,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | `Context belongs to undeclared app ` | `CONTEXT_APP_ID` 오타 | `src/contexts//context-module.ts` | | ` must export a literal ` | 헤더를 상수 참조나 식으로 썼다. 생성기는 글자로 읽는다 | 그 파일. `export const = "<값>";` 꼴 | | ` must export a positive integer ` | 예산 값이 정수 리터럴이 아니다 | 그 파일 | -| `src/features/ has no feature-module.ts; add one or mark the directory with NOT_A_FEATURE` | 기능 폴더에 선언 파일이 없다 | `feature-module.ts`를 만들거나, 기능이 아닌 샘플 폴더면 `NOT_A_FEATURE` 파일을 둔다 | -| `src/features/ has both feature-module.ts and NOT_A_FEATURE; …` | 기능이 아니라고 표시한 폴더에 선언 파일이 있다 | 기능으로 설치하려면 `NOT_A_FEATURE`를 지운다. 설치하지 않으려면 `feature-module.ts`를 지운다 | +| `src/features/ has no feature-module.ts; add one, or keep code that is no feature outside src/features` | 기능 폴더에 선언 파일이 없다 | `feature-module.ts`를 만든다. 기능이 아닌 코드(시험용 소비자 등)면 `src/features/` 밖으로 옮긴다 | | `Duplicate generated feature ids: ` | 두 폴더가 같은 `FEATURE_MODULE_ID` | 한쪽 `feature-module.ts` | | `Duplicate context id: ` | 두 폴더가 같은 `CONTEXT_MODULE_ID` | 한쪽 `context-module.ts` | | `Context feature cardinality exceeds budget ` | context의 기능 수가 예산을 넘었다 | `CONTEXT_MAX_FEATURES`, 또는 새 context | @@ -96,7 +95,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | `reason` | 원인 | 고칠 곳 | |---|---|---| -| `: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to reference-feature only; pin an EXTERNAL_PACKAGE` | 참조 기능 전용 출처를 다른 기능이 썼다 | `contracts/-contract-contribution.ts`의 `source`를 `EXTERNAL_PACKAGE`로 | +| `: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to only; pin an EXTERNAL_PACKAGE` | 템플릿 fixture 출처(예전 참조 샘플용)를 제품 기능이 썼다 | `contracts/-contract-contribution.ts`의 `source`를 `EXTERNAL_PACKAGE`로 | | `duplicate operation: ` | 두 기여가 같은 operation ID | 접두어를 붙인다 | | `duplicate contributionId: ` | 두 기여가 같은 `contributionId` | `contracts/-contract-contribution.ts` | | `/: unknown authProfileId ` | V3 `frontend.authProfileId`가 없는 프로필 | V3 `frontend.authProfileId` | diff --git a/docs/manual/reference/global-ids.md b/docs/manual/reference/global-ids.md index d4c97522..522b6249 100644 --- a/docs/manual/reference/global-ids.md +++ b/docs/manual/reference/global-ids.md @@ -49,7 +49,7 @@ - 무효화 topic은 새로 만든다. - 형식: `qinv.` + 소문자·숫자 26자. - `scripts/create-feature.ts`의 `randomTopicSuffix`가 같은 형식으로 만든다. - - 다른 기능이나 참조 기능의 값을 복사하지 않는다. + - 다른 기능의 값을 복사하지 않는다. - route ID는 `_<화면>` 꼴로 짓는다(`INVOICE_DETAIL`). 라우트를 더하면 a11y 기록 파일도 더한다(`artifacts/tests/a11y-manual/.md`). - 문구 키는 ko-KR과 en-US에 같은 키를 넣는다. `check:i18n`이 비교한다. diff --git a/docs/manual/reference/patterns.md b/docs/manual/reference/patterns.md index cbcabd14..5bfb9998 100644 --- a/docs/manual/reference/patterns.md +++ b/docs/manual/reference/patterns.md @@ -3,22 +3,22 @@ 기능을 만들 때 쓰는 패턴과, 그 패턴의 정의와 예제가 어디 있는지 적는다. - **정의**: 플랫폼(기능 밖)에서 패턴을 제공하는 파일. -- **예제**: 복사해 볼 수 있는 기능 코드. `생성 뼈대`는 `create:feature`가 만드는 코드다. `쓰기 slice`는 `create:feature --with-create`가 더 만드는 코드다(짝 백엔드 Envelope 모양). `참조 기능`은 `src/features/reference-feature/`다(Envelope가 아닌 problem details 모양). 참조 기능 경로도 다른 경로처럼 백틱으로 적는다. 문서 검사(`verify:documentation`)는 참조 기능이 있는 동안 그 경로가 있는지 확인하고, 참조 기능을 지운 사본에서는 없어도 된다고 본다(`scripts/lib/removable-template-features.ts`). +- **예제**: 복사해 볼 수 있는 기능 코드. `생성 뼈대`는 `create:feature`가 만드는 코드다. `쓰기 slice`는 `create:feature --with-create`가 더 만드는 코드다(짝 백엔드 Envelope 모양). `코드 조각`은 매뉴얼 안의 코드 블록이다. 생성 뼈대에 없는 모양을 보이고, `tests/unit/manual-code-blocks.test.ts`가 생성 기능 위에서 타입 검사와 동작 시험을 돌린다. - 예제가 없는 패턴은 **없음**이라고 적었다. 그 패턴은 정의를 읽고 직접 쓴다. -참조 기능은 예제일 뿐이다. 복사해 이름을 바꾸지 않는다. 모양을 보고 생성 뼈대에 옮긴다. +템플릿에는 복사해 볼 기능 샘플이 없다. 모양을 보고 생성 뼈대에 옮긴다. ## 기능 조립 | 패턴 | 정의 | 예제 | 검사 | |---|---|---|---| | 기능 모듈 등록 | `src/features/feature-module.ts` (`defineFeatureModule`, `defineFeatureRuntime`), 생성기 | 생성 뼈대 `feature-module.ts`, `feature-runtime.ts` | 생성기, 기능 ID와 계약 `featureId` 일치 | -| context 소속 선언 | `src/contexts/bounded-context-module.ts` | 참조 기능의 `src/contexts/reference-context/context-module.ts` | 생성기(없는 context, 예산), 앱 모듈(루트 밖 라우트) | +| context 소속 선언 | `src/contexts/bounded-context-module.ts` | 생성 뼈대 `src/contexts/-context/context-module.ts`(새 context를 만들 때) | 생성기(없는 context, 예산), 앱 모듈(루트 밖 라우트) | | context 전용 레이아웃 | `docs/architecture/starter-experience.md` "Product home and layouts" | `tests/helpers/fixture-layout-product.tsx` (테스트 fixture) | `tests/component/context-layouts.test.tsx` | | 앱 홈 대신하기 | `src/contracts/routes.ts`의 `FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS` | 없음 (기능 예제) | 조립 (두 기능이 `APP_HOME`을 선언하면 실패) | | 조립 기여(`needs`) | `src/features/feature-adapter-contribution.ts` | 생성 뼈대 `adapters/create--feature-input.ts` | 조립 (없는 capability, 다른 기능의 input) | | 제품 capability | `src/features/product-capabilities.ts`(타입), `src/bootstrap/product-composition.ts`(값), `src/bootstrap/product-composition-contract.ts` | `recipes/frontend-capabilities/indexeddb-feature-capability.ts` | `check:types` | -| 기능 끄기 | `config/runtime/.json`의 `FEATURE_OVERRIDES` | `config/runtime/local.json` | 참조 기능의 `tests/component/product-feature-switch.test.tsx` | +| 기능 끄기 | `config/runtime/.json`의 `FEATURE_OVERRIDES` | `config/runtime/local.json` | `tests/component/product-feature-switch.test.tsx`(시험 전용 기능으로 메뉴·홈 링크·직접 주소를 본다) | ## 라우트 @@ -26,9 +26,9 @@ |---|---|---|---| | 라우트 선언 | `src/contracts/routes.ts`, `src/contracts/route-runtime-contract.ts` | 생성 뼈대 계약 `routes`, `routeRuntimeContracts` | 조립(중복 route ID), `check:registries`(경로·chunk 중복) | | context 라우트 적재 | `src/platform/routing/context-route-module.ts` | 생성 뼈대 `context-routes.ts` | context 적재(계약에 없는 handle) | -| route ID로 URL 만들기 | `src/presentation/routes/route-codecs.ts`의 `buildRouteUrl` | 생성 뼈대 `presentation/-routes.ts`, 참조 기능 `presentation/reference-routes.ts` | 타입(기능의 route ID만 받음) | -| 파라미터·검색값 codec | `src/presentation/routes/route-codecs.ts` | 쓰기 slice `presentation/-route-codecs.ts`(상세 params), 참조 기능 `presentation/reference-route-codecs.ts` | 해석 실패 시 잘못된 경로 화면 | -| URL 검색값 읽기 | `src/presentation/routes/route-input.tsx`의 `useRouteInput` + 검색값 codec | 참조 기능 `presentation/reference-routes.ts` | 해석 실패 시 잘못된 경로 화면 | +| route ID로 URL 만들기 | `src/presentation/routes/route-codecs.ts`의 `buildRouteUrl` | 생성 뼈대 `presentation/-routes.ts` | 타입(기능의 route ID만 받음) | +| 파라미터·검색값 codec | `src/presentation/routes/route-codecs.ts` | 쓰기 slice `presentation/-route-codecs.ts`(상세 params). 검색값 codec은 [01 문서 6단계](../01-add-a-feature.md#6단계-라우트)의 코드 조각 | 해석 실패 시 잘못된 경로 화면 | +| URL 검색값 읽기 | `src/presentation/routes/route-input.tsx`의 `useRouteInput` + 검색값 codec | 코드 조각: [01 문서 6단계](../01-add-a-feature.md#6단계-라우트)의 `contracts/-list-search.ts`, `presentation/use--list-filters.ts` | 해석 실패 시 잘못된 경로 화면 | | URL 검색값을 바꾸는 폼 | `buildRouteUrl`의 `search`, 디자인 시스템 `SearchField`, `CollectionPage`의 `toolbar` | 기능 예제 없음. 아래 짧은 예 | 라우터를 거치는 페이지 테스트 | ### URL 검색값을 바꾸는 폼 (짧은 예) @@ -46,7 +46,7 @@ - 목록 라우트의 `searchSchema`와 `routeRuntimeContracts`의 `searchCodec`. - 그 codec을 `context-routes.ts` handle의 `codecs`와 URL 함수(`buildRouteUrl`의 세 번째 인자)에 함께 넘긴다. -- 검색값을 읽는 hook. 참조 기능 `reference-routes.ts`의 `useReferenceListFilters`가 예제다. +- 검색값을 읽는 hook. [01 문서 6단계](../01-add-a-feature.md#6단계-라우트)의 코드 조각 `use--list-filters.ts`가 예제다. ```tsx // 공지 기능의 목록 페이지. noticeRouteUrl은 생성된 -routes.ts의 URL 함수다. @@ -84,9 +84,9 @@ const search = (q: string) => | 검증 생략 | `src/contracts/unvalidated-payload.ts`의 `unvalidatedPayload` | 없음 (기능 예제) | 이유가 비면 throw, `listUnvalidatedPayloads`가 목록을 보임 | | DTO → 화면 값 mapper | `src/contracts/boundary-mapper.ts`의 `BoundaryMappingResult` | 생성 뼈대 `contracts/-mapper.ts` | 타입 검사 | | gateway port + HTTP 어댑터 | `src/adapters/http/index.ts`의 `createFeatureHttpBinding`, `defineFeatureHttpOperationForRoutes` | 생성 뼈대 `adapters/-http-gateway.ts` | 음성 타입 fixture (operation ID, route ID, 입력) | -| 문제 응답 → 업무 실패 | `mapProblem` (HTTP 바인딩) | 쓰기 slice `adapters/-http-gateway.ts`(400 `_INVALID` → 이름 칸), 참조 기능 `adapters/reference-http-gateway.ts` (409, 422) | 기능 테스트 | +| 문제 응답 → 업무 실패 | `mapProblem` (HTTP 바인딩) | 쓰기 slice `adapters/-http-gateway.ts`(400 `_INVALID` → 이름 칸). problem details 백엔드(409, 422)는 [02 결정표 4절](../02-decision-tables.md#4-결과-불명)의 코드 조각 | 기능 테스트 | | 결과와 실패 | `src/contracts/result.ts`, `src/contracts/errors.ts` | 생성 뼈대 `application/-feature-api.ts` | `FailureKind` 닫힌 어휘(타입) | -| 실패 → 화면 행동 | `src/contracts/errors.ts`의 `action` | 참조 기능 `presentation/use-reference-failure-action.ts` | 페이지 테스트 | +| 실패 → 화면 행동 | `src/contracts/errors.ts`의 `action` | 코드 조각: [01 문서 8단계](../01-add-a-feature.md#8단계-페이지)의 `presentation/use--failure-action.ts` | 페이지 테스트 | | 파일 업로드 (짝 백엔드 Fileserver) | `src/adapters/http/index.ts`의 `createFileserverUploadClient` (`POST /v1/files`) | 없음 (기능 예제). 조립은 [02 결정표 7절](../02-decision-tables.md#7-파일-업로드) | `tests/integration/fileserver-upload.test.ts` | ## 서버 상태 @@ -95,29 +95,29 @@ const search = (q: string) => |---|---|---|---| | 쿼리 바인딩 | `src/contracts/server-state.ts`의 `bindQuery`, `src/presentation/adapters/query/application-query.ts` | 생성 뼈대 `presentation/use--items.ts` | profile ID (실행 때). `owner`·`operationId`는 읽는 곳이 없는 `@deprecated` 칸이라 적지 않는다 | | 무효화 topic | `src/contracts/query-invalidation.ts` | 생성 뼈대 계약 `invalidation` | 조립(중복, 고아 topic) | -| 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책(`src/contracts/server-state.ts`의 `commandMutationIdentity`로 operation ID와 키 여부를 descriptor에서 받는다) | 쓰기 slice `--keyed`(`contracts/-contract-contribution.ts`, `presentation/use--create.ts`), 참조 기능 생성 명령(`use-reference-feature.ts`, `reference-feature-contract-contribution.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름, 손으로 적은 operation ID는 `MutationOperationId`가 아니다), 기능 테스트 | -| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 쓰기 slice `presentation/-create-page.tsx`, 참조 기능 `presentation/reference-resource-form-page.tsx` | 기능 테스트만(쓰기 slice는 `-create-page.test.tsx`) | -| 수정·삭제 명령 | 같은 V3 계약 (`PUT`, `PATCH`, `DELETE`) | 없음 (참조 기능은 생성 명령만 있다) | — | +| 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책(`src/contracts/server-state.ts`의 `commandMutationIdentity`로 operation ID와 키 여부를 descriptor에서 받는다) | 쓰기 slice `--keyed`(`contracts/-contract-contribution.ts`, `presentation/use--create.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름, 손으로 적은 operation ID는 `MutationOperationId`가 아니다), 기능 테스트 | +| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 쓰기 slice `presentation/-create-page.tsx` | 기능 테스트만(쓰기 slice는 `-create-page.test.tsx`) | +| 수정·삭제 명령 | 같은 V3 계약 (`PUT`, `PATCH`, `DELETE`) | 없음 (쓰기 slice는 작성 명령만 만든다) | — | | 낙관적 갱신 | `useApplicationMutation`의 `optimistic` 옵션 (`application-query.ts`) | 없음 | 런타임 테스트만 | -| 페이지 넘김 | `src/adapters/query-cache/index.ts`의 `createCursorPaginationRuntime` | 없음 (참조 기능은 커서 필터만, 다음 커서 없음) | 런타임 테스트만 | -| 로컬 저장(IndexedDB) | `recipes/frontend-capabilities/indexeddb-feature-capability.ts` + `product-composition.ts` | `src/features/local-draft-feature/` (`NOT_A_FEATURE`, 기능이 아닌 샘플) | 계약 테스트 | +| 페이지 넘김 | `src/adapters/query-cache/index.ts`의 `createCursorPaginationRuntime` | 없음 (생성 뼈대 목록은 첫 페이지와 `meta.page.total`만 읽는다) | 런타임 테스트만 | +| 로컬 저장(IndexedDB) | `recipes/frontend-capabilities/indexeddb-feature-capability.ts` + `product-composition.ts` | `tests/fixtures/indexeddb-consumer/` (시험이 조립하는 소비자 fixture, 기능 폴더 모양) | 계약 테스트 | ## 화면 | 패턴 | 정의 | 예제 | 검사 | |---|---|---|---| -| 페이지 템플릿 | `src/presentation/templates/page-templates.tsx` | 생성 뼈대 `CollectionPage`, 참조 기능 페이지 4개 | `page-templates-own-layout-only` | +| 페이지 템플릿 | `src/presentation/templates/page-templates.tsx` | 생성 뼈대 `CollectionPage`, 쓰기 slice `DetailPage`·`FormPage` | `page-templates-own-layout-only` | | 비동기 상태 화면 | `src/presentation/components/async-surface.tsx`의 `AsyncSurface` | 생성 뼈대 목록 페이지 | 페이지 테스트 | -| 폼 | `src/presentation/forms/use-app-form.ts`의 `useAppForm` | 쓰기 slice `presentation/-form.ts`와 `-create-page.tsx`, 참조 기능 `presentation/reference-resource-form.ts`와 폼 페이지 | 페이지 테스트(서버 필드 오류, 이탈 확인) | +| 폼 | `src/presentation/forms/use-app-form.ts`의 `useAppForm` | 쓰기 slice `presentation/-form.ts`와 `-create-page.tsx` | 페이지 테스트(서버 필드 오류, 이탈 확인) | | 화면 문구 | `src/presentation/i18n/index.ts`, 기능 문구 catalog | 생성 뼈대 `contracts/-message-catalog.ts` | `lint`(문구 literal), `check:i18n`(ko-KR·en-US 키) | -| 권한 분기 | 라우트 `access`, 서버 403 → 실패 | 참조 기능 403 화면 테스트 | 가드 테스트. 역할·권한 힌트 예제는 없음 | +| 권한 분기 | 라우트 `access`, 서버 403 → 실패 | 코드 조각: [01 문서 10단계](../01-add-a-feature.md#10단계-테스트)의 403 페이지 테스트 `tests/features//-forbidden.test.tsx` | 가드 테스트. 역할·권한 힌트 예제는 없음 | ## 테스트 | 패턴 | 정의 | 예제 | 검사 | |---|---|---|---| | 응답 시나리오 | `tests/mocks/handlers/http-scenarios.ts`의 `createHttpScenarioHandler` | 생성 뼈대 페이지 테스트 | `test:coverage` | -| 보낸 요청(헤더·본문) 확인 | MSW `setupServer().events.on("request:start")` | [01 문서 10단계](../01-add-a-feature.md#10단계-테스트)의 짧은 예. 핸들러에서 모으는 방법은 참조 기능 `reference-production-vertical.test.tsx`의 504 재전송 테스트 | `test:coverage` | +| 보낸 요청(헤더·본문) 확인 | MSW `setupServer().events.on("request:start")` | [01 문서 10단계](../01-add-a-feature.md#10단계-테스트)의 짧은 예. 핸들러에서 모으는 방법은 쓰기 slice `--keyed`의 `tests/features//-create-page.test.tsx` | `test:coverage` | | 같은 멱등 키 재전송 | 시나리오 `in-flight-409` + 위 요청 모으기 | 01 문서 10단계 | `test:coverage` | ## 관측 diff --git a/docs/operations/adapter-remediation-ledger.md b/docs/operations/adapter-remediation-ledger.md index 5e48aab7..4c8016c6 100644 --- a/docs/operations/adapter-remediation-ledger.md +++ b/docs/operations/adapter-remediation-ledger.md @@ -194,7 +194,7 @@ Captured after every correctness task landed. | `git diff --check` | 0 | clean | | `corepack pnpm test:component` | 0 | 126 passed | | `corepack pnpm test:integration` | 0 | 52 passed | -| `corepack pnpm test:reference-feature` | 0 | 26 passed | +| 참조 샘플 기능 시험(그 script는 2026-11-07 샘플과 함께 지웠다) | 0 | 26 passed | | `corepack pnpm test:recipes` | 0 | 17 passed | | `corepack pnpm test:unit` | 1 | 1585 passed / 19 failed tests; the 19 are the unchanged pre-existing `ci-artifact-contract` sandbox failures | | `corepack pnpm check:registries` | 0 | 11 registries PASS | @@ -340,7 +340,7 @@ Run on the landed tree. Only what actually passed is claimed as passing. | `tests/unit` + `tests/integration`, no exclusions | — | 1643 passed / 1747; the 104 failures are the four environmental files below | | `corepack pnpm test:component` | 0 | 126 passed | | `corepack pnpm test:recipes` | 0 | 17 passed | -| `corepack pnpm test:reference-feature` | 0 | 26 passed | +| 참조 샘플 기능 시험(그 script는 2026-11-07 샘플과 함께 지웠다) | 0 | 26 passed | ### Environmental failures, not claimed as green diff --git a/docs/operations/performance-evidence.md b/docs/operations/performance-evidence.md index c1c6b1de..820861f3 100644 --- a/docs/operations/performance-evidence.md +++ b/docs/operations/performance-evidence.md @@ -20,15 +20,16 @@ Performance evidence is deliberately split by measurement context: 보고 예산을 정한다. 기준선 숫자는 이 문서에 적지 않는다. 손으로 적은 숫자는 두 번 낡았다. 기록은 -`config/scale/feature-shape-ceilings.json`의 `initialJavascript` 한 곳이다. 이 파일과 아래 -측정 테스트는 참조 기능을 복사해 재므로 샘플과 함께 지워진다. 문서 검사는 샘플을 지운 사본에서 -이 경로들을 요구하지 않는다(`scripts/lib/removable-template-features.ts`). +`config/scale/feature-shape-ceilings.json`의 `initialJavascript` 한 곳이다. 측정은 +`create:feature --with-create --keyed`가 만드는 기능을 복사해 잰다 +(`scripts/scale/measure-feature-shape-growth.ts`, 2026-11-07 전에는 참조 샘플을 복사했다). | 칸 | 뜻 | |---|---| | `gzipBytes`, `files` | 템플릿 그대로의 초기 JS gzip bytes와 파일 수(entry 포함) | -| `perFeatureGzipBytes` | 있는 context에 참조 기능 모양 기능을 하나 더할 때 느는 초기 JS. 상한 1 KiB | -| `perContextGzipBytes` | 새 context를 하나 더할 때 느는 초기 JS. 상한 512 B | +| `firstFeatureGzipBytes` | 기능이 없는 템플릿에 첫 기능(과 그 context)을 더할 때 느는 초기 JS. 모든 기능이 함께 쓰는 코드가 이때 초기 청크에 들어온다. 한 번만 든다. 상한 없음(전체는 `check:bundle`의 예산이 막는다) | +| `perFeatureGzipBytes` | 있는 context에 생성 기능 모양 기능을 하나 더할 때 느는 초기 JS. 상한 1 KiB | +| `perContextGzipBytes` | 둘째 기능을 같은 context 대신 새 context에 둘 때 느는 초기 JS. 상한 512 B | - `tests/unit/feature-shape-growth.test.ts`(unit, merge 단계)가 매번 빌드해 이 값을 재고, 상한을 넘거나 기록과 다르면(합계 256 B 초과, 파일 수 불일치, 기능· @@ -120,11 +121,14 @@ lab 측정(`scripts/test-performance.ts`, FE-GATE-026)은 local 프로필 build `context.sampling.targetDeepLink`에 남긴다. 예산은 `cls`와 같다(1105/15-01). - 대상 화면(플랫폼 구성)은 기능 코드를 받지 않으므로 기능이 늘어도 수치가 거의 그대로다. 그래서 run마다 설치된 기능이 가진 첫 공개 내비게이션 - 라우트(`labFeatureRoute`, 템플릿에서는 `EXAMPLES_UI`)를 같은 시계로 따로 잰다 + 라우트(`labFeatureRoute`)를 같은 시계로 따로 잰다 (`metrics.featureRouteInteractionMs`, `context.sampling.featureRoute`, 1105/15-04). 그런 라우트가 없으면 `measured: false`로 남기고 판정하지 않는다. + 템플릿은 기능이 없어 재지 않는다(2026-11-07 예제 화면 삭제 뒤. 그 전에는 예제 + 화면 `/examples/ui`가 이 라우트였다). 공개 내비게이션 라우트를 가진 제품 기능이 + 생기면 그 라우트를 잰다. - 예산 `lab.featureRouteInteractionMs`는 500 ms다. 근거: `8a44226`에서 lab - 조건으로 `EXAMPLES_UI`를 5회 재니 중앙값 406 ms(403~410)였다. 그 진입은 요청 + 조건으로 그때의 예제 화면 라우트를 5회 재니 중앙값 406 ms(403~410)였다. 그 진입은 요청 두 묶음이다(context 라우트 모듈과 기능 실행부, 그다음 페이지 청크와 공유 청크). 둘째 묶음이 약 100 ms(클릭 뒤 98~204 ms)다. 500 ms는 지금 진입을 통과시키고, 같은 크기의 묶음이 하나 더 붙으면 넘는다. diff --git a/docs/styling/design-system-platform.md b/docs/styling/design-system-platform.md index 0618086b..d6eedf68 100644 --- a/docs/styling/design-system-platform.md +++ b/docs/styling/design-system-platform.md @@ -38,8 +38,8 @@ - local form facade, field/error summary, dirty navigation dialog - `src/presentation/templates` - Standard, Collection, Detail, Form, Status page template -- `/examples/ui`, `/examples/states` - - 실행 가능한 primitive와 상태 예제 +- `src/presentation/design-system/galleries.stories.tsx` + - 실행 가능한 primitive와 상태 예제(Storybook 갤러리 story) - component/E2E/axe 테스트 - 필드 설명과 오류 연결 - native dialog 닫기와 trigger focus 복원 @@ -623,8 +623,8 @@ RP-10의 Storybook toolbar에서 최소한 다음 조합을 전환할 수 있어 ## 10. Storybook과 시각 검증 -현재 `/examples/ui`는 실행 중인 앱 셸과 primitive 통합을 확인하는 데 유지한다. -그러나 runtime gallery는 isolated component workshop을 대체하지 않는다. +디자인 시스템 갤러리와 화면 상태 갤러리는 Storybook story다. 앱 셸과 primitive의 +통합은 `/`와 `/examples/platform`을 여는 e2e가 확인한다. [Storybook 공식 UI 테스트 문서](https://storybook.js.org/docs/writing-tests)는 story를 기반으로 interaction, accessibility, visual test를 구성하는 방법을 @@ -796,8 +796,8 @@ long-content ### Step 9. 통합 예제를 추가한다 -- `/examples/ui`에는 primitive를 추가한다. -- `/examples/states`에는 새로운 공통 상태를 추가한다. +- 갤러리 story(`galleries.stories.tsx`)의 `DesignSystem`에는 primitive를 추가한다. +- 같은 파일의 `ScreenStates`에는 새로운 공통 상태를 추가한다. - pattern/template은 domain-neutral fixture로 실제 조합을 보여 준다. - production profile에서 예제 route를 제외할 수 있는 계약을 유지한다. @@ -919,7 +919,7 @@ component contract에 기록한다. 예를 들어 `Separator`에는 pending/erro 9. locale provider, pseudo-locale, RTL 검증을 추가한다. 10. Storybook, story a11y, interaction test를 추가한다. 11. pinned browser 환경의 visual regression gate를 추가한다. -12. `/examples/ui`와 `/examples/states`를 통합 smoke gallery로 유지한다. +12. 디자인 시스템·화면 상태 갤러리를 Storybook story로 유지하고 visual 골든의 대상으로 쓴다. 이 순서는 라이브러리 수를 늘리는 것이 목표가 아니다. 각 단계가 제품 개발자가 중복 구현할 문제를 하나씩 제거하고, 외부 공급자를 교체할 수 있는 로컬 계약과 diff --git a/docs/styling/design-tokens.md b/docs/styling/design-tokens.md index 1a2d94c5..dae8bd8e 100644 --- a/docs/styling/design-tokens.md +++ b/docs/styling/design-tokens.md @@ -7,7 +7,8 @@ the dark theme, and `component.css` maps roles to per-component values. `src/presentation/styles/theme.css` only imports the three files and the style files under `src/presentation/styles/theme/`. Components consume semantic color, spacing, typography, status, and radius tokens through static classes. -`/examples/ui` is the executable token and primitive gallery. +The executable token and primitive gallery is the workshop story +`src/presentation/design-system/galleries.stories.tsx` (`corepack pnpm storybook`). ## Rules a rebrand must keep @@ -61,8 +62,8 @@ Arbitrary-value policy: - user-controlled or runtime-composed class strings are forbidden - class variants must be selected from a closed static map -The removable reference feature may demonstrate tokens, but generic production -starter modules do not import its domain, application, adapter, or presentation +A feature may demonstrate tokens, but generic production starter modules do +not import a feature's domain, application, adapter, or presentation implementation. This file documents the currently implemented token and primitive baseline. diff --git a/docs/testing/frontend-platform-testing-strategy.md b/docs/testing/frontend-platform-testing-strategy.md index e031a932..2bf3fb19 100644 --- a/docs/testing/frontend-platform-testing-strategy.md +++ b/docs/testing/frontend-platform-testing-strategy.md @@ -503,8 +503,9 @@ tests/support/query/ helper는 production default를 복사하지 않는다. production factory를 호출하고 필요한 시간·retry만 test override로 주입한다. -RP-05의 executable reference matrix는 -`tests/features/reference-feature`에 모여 있다. 설치 모드에서는 URL codec과 +RP-05의 executable reference matrix는 참조 샘플의 시험 폴더에 모여 있었다(2026-11-07 +샘플과 함께 삭제). 지금 기능 하나의 경로는 `create:feature`가 만든 기능의 시험 +(`tests/features//`)과 `tests/e2e/generated-feature.spec.ts`가 본다. 그때 설치 모드에서는 URL codec과 query key/HTTP search의 동일성, DTO 차단, loading/success/empty/terminal, refreshing/stale, pending/duplicate/optimistic/conflict/rollback과 MSW production composition을 검증한다. 제거 모드는 feature source/tests와 installed @@ -513,8 +514,8 @@ contract/runtime/adapter contribution을 제거한 복제본에서 P0 gate와 bu RP-06 form/page matrix는 `tests/component/form-foundation.test.tsx`, `tests/component/page-templates.test.tsx`, -`tests/features/reference-feature/reference-page.test.tsx`와 -`tests/e2e/reference-form.spec.ts`에 있다. client validation에서 command 0회와 +생성 기능의 `-create-page.test.tsx`와 +`tests/e2e/generated-feature.spec.ts`에 있다(2026-11-07 전에는 참조 샘플의 페이지 시험과 폼 e2e). client validation에서 command 0회와 첫 오류 focus, Zod transform/default, pending 중 중복 제출, 승인된 422 field/unknown field mapping, conflict 입력 보존, reset/dirty, navigation confirmation/focus restore, URL/storage 비노출과 320px reflow를 검증한다. @@ -808,8 +809,10 @@ production runtime config에 `MOCK_MODE`, `SCENARIO`, fake token 같은 key를 ## 12. Storybook 테스트 Storybook은 component를 격리해 state를 열거하고 실제 브라우저 interaction과 -접근성을 검사하는 개발·CI surface다. `/examples/ui`는 앱 통합 smoke로 유지하되 -Storybook을 대신하지 않는다. +접근성을 검사하는 개발·CI surface다. 디자인 시스템 갤러리와 화면 상태 갤러리도 +story다(`src/presentation/design-system/galleries.stories.tsx`). 갤러리의 브라우저 +상호작용 검사는 `tests/storybook/galleries.spec.ts`가, 앱 셸 안의 통합 확인은 +`/`와 `/examples/platform`을 여는 e2e가 맡는다. ### 12.1 Global decorator @@ -945,9 +948,10 @@ Playwright `toHaveScreenshot()`을 사용한다. - `app-shell-wide-light`: `/`, 1440×900, light, 전체 페이지 — wide app shell - `app-shell-compact-pseudo-drawer`: `/`, 390×844, en-XA, 메뉴 서랍 열림 — compact app shell, pseudo-locale, 열린 drawer -- `design-system-gallery-dark`: `/examples/ui`, dark — design-system 갤러리 -- `state-surfaces-light`: `/examples/states` — loading, background refresh, - empty, error, 401, 403, 404 +- `design-system-gallery-dark`: Storybook 정적 빌드의 갤러리 story + `platform-galleries--design-system`, 1280×900, 시스템 dark — design-system 갤러리 +- `state-surfaces-light`: Storybook 정적 빌드의 `platform-galleries--screen-states`, + 1280×1100 — loading, background refresh, empty, error, 401, 403, 404 - `platform-overview-light`: `/examples/platform` — 플랫폼 구성 개요 `check-test-evidence`는 기준선 PNG가 4장 이상인지만 본다. 위 목록의 각 @@ -1034,7 +1038,7 @@ TEST_RUN_ID=a playwright test |---|---|---| | `TEST_RUN_ID` | 다섯 Playwright 설정, `tests/e2e/preload-use.spec.ts` | `dist`, `artifacts/tests/<이름>/` | | `RUN_OUTPUT_ROOT` | 빌드 단계 전부(`scripts/build-frontend.ts`가 부르는 것), `vite.config.ts`. 설정이 web server에만 넘긴다. 빌드 뒤 검사(`scripts/generate-supply-chain.ts`, `scripts/check-bundle.ts`)는 `.`이 아니면 멈춘다 | `.` | -| `TEST_E2E_PORT`, `TEST_VISUAL_PORT`, `TEST_CAPABILITIES_PORT`, `TEST_STORYBOOK_PORT`, `TEST_DEV_PORT` | 각 설정 | 빈 포트 | +| `TEST_E2E_PORT`, `TEST_VISUAL_PORT`, `TEST_VISUAL_WORKSHOP_PORT`, `TEST_CAPABILITIES_PORT`, `TEST_STORYBOOK_PORT`, `TEST_DEV_PORT` | 각 설정(`TEST_VISUAL_WORKSHOP_PORT`는 visual 설정의 두 번째 서버, 갤러리 골든이 여는 Storybook 정적 빌드) | 빈 포트 | - run ID는 글자·숫자·`.`·`_`·`-` 64자 이하이고 글자나 숫자로 시작한다. - 포트 변수를 주면 그 포트를 쓴다. 디버깅할 때 고정하는 용도다. diff --git a/docs/testing/taxonomy.md b/docs/testing/taxonomy.md index f54b4aad..d44b88f2 100644 --- a/docs/testing/taxonomy.md +++ b/docs/testing/taxonomy.md @@ -19,7 +19,7 @@ Each gate is blocking in its declared scope. Failures are not downgraded with `test:all` is the normal product-development loop. It runs, in order, `test:runtime-schema`, `test:unit`, `test:contract`, `test:component`, `test:integration`, the rest of what `test:coverage` runs (`tests/features`, -the reference sample's tests among them, `tests/scripts` and +each installed feature's tests, `tests/scripts` and `tests/scale/browser-soak.contract.test.ts`), `test:platform` (`tests/platform` and `tests/architecture`), `check:release-coherence` and `test:recipes` (`package.json` `test:all`). So every Vitest path the merge gate's coverage diff --git a/eslint.config.ts b/eslint.config.ts index cc8f0336..fbdcd82a 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -458,9 +458,9 @@ const hookRules = { // template literal, a ternary, an object prop such as `heading.title`) is not // seen; review catches those. A product replaces these selectors in its own // config, for example to allow a brand name or to drop the rule for a -// one-locale product. The platform overview (src/presentation/examples), -// the example screens (src/features/platform-examples-feature/presentation) -// and stories are workshop code and stay out; tests are outside these folders. +// one-locale product. The platform overview (src/presentation/examples) and +// stories (the galleries among them) are workshop code and stay out; tests +// are outside these folders. const screenTextDirectories = [ "src/presentation/boundaries", "src/presentation/components", @@ -912,13 +912,9 @@ export default [ `${directory}/**/*.tsx`, `tests/fixtures/i18n/*/${directory}/**/*.tsx`, ]), - // 1103/09-04. The example screens moved from src/presentation/examples - // into this feature and stay workshop code: their copy is Korean in every + // Stories are workshop code: the galleries' copy is Korean in every // locale on purpose (08-07). - ignores: [ - "**/*.stories.tsx", - "src/features/platform-examples-feature/presentation/**", - ], + ignores: ["**/*.stories.tsx"], rules: { "no-restricted-syntax": [ ...commonSecurityRules["no-restricted-syntax"], diff --git a/package.json b/package.json index 4d3c87c7..d3d1440d 100644 --- a/package.json +++ b/package.json @@ -78,7 +78,6 @@ "test:optional-recipe-removal": "node scripts/test-optional-recipe-removal.ts", "test:browser-file-storage-removal": "node scripts/test-browser-file-storage-runtime-removal.ts", "test:realtime-removal": "node scripts/test-realtime-runtime-removal.ts", - "test:reference-feature": "node scripts/run-vitest.ts run tests/features/reference-feature --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/reference-feature.xml --passWithNoTests", "check:v8-coverage-counter-semantics": "node scripts/check-v8-coverage-counter-semantics.ts", "test:coverage": "corepack pnpm check:v8-coverage-counter-semantics && node scripts/run-vitest.ts run tests/runtime-schema tests/unit tests/contract tests/component tests/integration tests/features tests/platform tests/architecture tests/release tests/scripts tests/scale/browser-soak.contract.test.ts --coverage --maxWorkers=4 --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/coverage.xml && node scripts/check-risk-coverage.ts", "check:coverage:fixture": "node scripts/check-risk-coverage.ts --summary tests/fixtures/coverage/below-threshold.json --artifact artifacts/quality/risk-coverage-fixture.json", @@ -149,7 +148,7 @@ "check:request-fanout": "node scripts/check-request-fanout.ts && node scripts/check-request-fanout.ts --fixture", "check:app-build-input": "node scripts/check-app-build-input.ts", "check:app-build-input:bundle": "node scripts/check-app-build-input.ts --require-bundle", - "test:extreme-scale:focused": "node scripts/run-vitest.ts run tests/scale/global-local-independence.test.ts tests/architecture/app-build-input.test.ts tests/architecture/request-fanout.test.ts tests/platform/traffic/request-fanout.test.ts tests/platform/traffic/request-deduplication.test.ts tests/features/reference-feature/reference-request-fanout.test.ts tests/features/reference-feature/reference-request-deduplication.test.ts tests/scripts/generate-product-feature-index.test.ts --reporter=default", + "test:extreme-scale:focused": "node scripts/run-vitest.ts run tests/scale/global-local-independence.test.ts tests/architecture/app-build-input.test.ts tests/architecture/request-fanout.test.ts tests/platform/traffic/request-fanout.test.ts tests/platform/traffic/request-deduplication.test.ts tests/scripts/generate-product-feature-index.test.ts --reporter=default", "check:release-coherence": "node scripts/run-vitest.ts run tests/platform/release tests/release --reporter=default" }, "dependencies": { diff --git a/playwright.storybook.config.ts b/playwright.storybook.config.ts index a36bfb5f..af4eebe9 100644 --- a/playwright.storybook.config.ts +++ b/playwright.storybook.config.ts @@ -4,22 +4,14 @@ import { reservePort, TEST_PORT_VARIABLES, testRunPath, - testRunRoot, } from "./scripts/lib/run-isolation.ts"; +import { storybookStaticServer } from "./scripts/lib/storybook-static.ts"; -// 1105/12-04. Under TEST_RUN_ID the workshop is built into the run's own -// folder (.tmp/runs//artifacts/storybook/static) with build:storybook's -// two steps and another output folder, and the results and report are the -// run's own. Unset, the gate's build:storybook writes artifacts/storybook/static. -// The static server listens on a free port (TEST_STORYBOOK_PORT pins one). -const staticDirectory = testRunPath("artifacts/storybook/static"); +// 1105/12-04. Under TEST_RUN_ID the workshop build (storybookStaticServer), +// the results and the report are the run's own. The static server listens on +// a free port (TEST_STORYBOOK_PORT pins one). const port = await reservePort(TEST_PORT_VARIABLES.storybook); const origin = `http://127.0.0.1:${port}`; -const buildWorkshop = - testRunRoot() === "." - ? "corepack pnpm build:storybook" - : "node scripts/generate-product-feature-index.ts && " + - `corepack pnpm exec storybook build -o ${staticDirectory}`; export default defineConfig({ testDir: "./tests/storybook", @@ -45,8 +37,7 @@ export default defineConfig({ screenshot: "only-on-failure", }, webServer: { - command: - `${buildWorkshop} && node scripts/serve-static.ts ${staticDirectory} ${port}`, + command: storybookStaticServer(port).command, url: origin, reuseExistingServer: false, }, diff --git a/playwright.visual.config.ts b/playwright.visual.config.ts index 977fd864..9330b055 100644 --- a/playwright.visual.config.ts +++ b/playwright.visual.config.ts @@ -10,6 +10,7 @@ import { testRunPath, testRunRoot, } from "./scripts/lib/run-isolation.ts"; +import { storybookStaticServer } from "./scripts/lib/storybook-static.ts"; // 1105/12-04. Under TEST_RUN_ID the results, report and build are the run's // own (.tmp/runs//); the goldens in snapshotDir are shared and only read. @@ -18,6 +19,11 @@ import { const dist = testRunPath("dist"); const port = await reservePort(TEST_PORT_VARIABLES.visual); const origin = `http://127.0.0.1:${port}`; +// The design-system and screen-state galleries are workshop stories +// (src/presentation/design-system/galleries.stories.tsx); their goldens open +// the static workshop, which the second server serves +// (TEST_VISUAL_WORKSHOP_PORT pins its port). +const workshopPort = await reservePort(TEST_PORT_VARIABLES.visualWorkshop); export default defineConfig({ testDir: "./tests/visual", @@ -62,19 +68,26 @@ export default defineConfig({ }, }, }, - webServer: { - // The home page and the platform overview print the build and release - // identity. CI sets VITE_BUILD_ID, VITE_COMMIT_SHA and RELEASE_ID for the - // whole workflow, so its build drew other text than the goldens and every - // CI run failed here. The goldens are the template's shape, captured with - // the local identity. - // 1103/11-08: CI too, or the build is checked as a release build. - env: { ...LOCAL_BUILD_IDENTITY, [RUN_OUTPUT_ROOT_VARIABLE]: testRunRoot() }, - command: - `corepack pnpm build && corepack pnpm preview --host 127.0.0.1 --port ${port} --strictPort --outDir ${dist}`, - url: origin, - reuseExistingServer: false, - }, + webServer: [ + { + // The home page and the platform overview print the build and release + // identity. CI sets VITE_BUILD_ID, VITE_COMMIT_SHA and RELEASE_ID for + // the whole workflow, so its build drew other text than the goldens and + // every CI run failed here. The goldens are the template's shape, + // captured with the local identity. + // 1103/11-08: CI too, or the build is checked as a release build. + env: { ...LOCAL_BUILD_IDENTITY, [RUN_OUTPUT_ROOT_VARIABLE]: testRunRoot() }, + command: + `corepack pnpm build && corepack pnpm preview --host 127.0.0.1 --port ${port} --strictPort --outDir ${dist}`, + url: origin, + reuseExistingServer: false, + }, + { + command: storybookStaticServer(workshopPort).command, + url: `http://127.0.0.1:${workshopPort}`, + reuseExistingServer: false, + }, + ], projects: [ { name: "visual-fonts", testMatch: /fonts\.setup\.ts$/ }, { name: "chromium-visual", dependencies: ["visual-fonts"] }, diff --git a/public/config.json b/public/config.json index e8466b6e..2ad5dfc4 100644 --- a/public/config.json +++ b/public/config.json @@ -15,7 +15,5 @@ "SERVICE_WORKER": "DEFAULT", "OFFLINE_COMMANDS": "DEFAULT" }, - "FEATURE_OVERRIDES": { - "reference-feature": "DEFAULT" - } + "FEATURE_OVERRIDES": {} } diff --git a/public/release-manifest.json b/public/release-manifest.json index 471e2dd2..ed7bd068 100644 --- a/public/release-manifest.json +++ b/public/release-manifest.json @@ -10,13 +10,6 @@ "routeChunks": { "route-home": "src/presentation/pages/home-page.tsx", "route-examples-platform": "src/presentation/examples/platform-overview-page.tsx", - "route-examples-ui": "src/features/platform-examples-feature/presentation/ui-gallery-page.tsx", - "route-examples-states": "src/features/platform-examples-feature/presentation/state-gallery-page.tsx", - "route-examples-auth": "src/features/platform-examples-feature/presentation/auth-example-page.tsx", - "route-reference-resources": "src/features/reference-feature/presentation/reference-resource-page.tsx", - "route-reference-resource-detail": "src/features/reference-feature/presentation/reference-resource-detail-page.tsx", - "route-reference-resource-form": "src/features/reference-feature/presentation/reference-resource-form-page.tsx", - "route-reference-resource-status": "src/features/reference-feature/presentation/reference-resource-status-page.tsx", "route-not-found": "src/presentation/pages/not-found-page.tsx" }, "contractSet": { diff --git a/recipes/frontend-capabilities/indexeddb-feature-capability.ts b/recipes/frontend-capabilities/indexeddb-feature-capability.ts index 380a3e94..3d8c076c 100644 --- a/recipes/frontend-capabilities/indexeddb-feature-capability.ts +++ b/recipes/frontend-capabilities/indexeddb-feature-capability.ts @@ -7,8 +7,8 @@ import { createIndexedDbRepositoryProvider, type IndexedDbRepositoryProvider, } from "../../src/features/feature-adapter-contribution.ts"; -import type {} from "../../src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts"; -import type { LocalDraft } from "../../src/features/local-draft-feature/domain/local-draft.ts"; +import type {} from "../../tests/fixtures/indexeddb-consumer/adapters/create-local-draft-feature-input.ts"; +import type { LocalDraft } from "../../tests/fixtures/indexeddb-consumer/domain/local-draft.ts"; type LocalDraftRuntimeDependencies = IndexedDbRuntimeDependencies< LocalDraft, @@ -21,7 +21,8 @@ type LocalDraftRuntime = ReturnType< /** * 09-05. How a host builds the `indexedDb` feature capability, shown for the - * local-draft sample. IndexedDB is an opt-in reference runtime + * local-draft consumer the tests compose (tests/fixtures/indexeddb-consumer). + * IndexedDB is an opt-in reference runtime * (`offline-indexeddb` in config/recipes/frontend-capability-recipes.json, * `productionComposition: false`), so `src/bootstrap/runtime-adapters.ts` does * not build it. A product that installs a feature with `needs: ["indexedDb"]` diff --git a/scripts/check-browser-file-storage-boundaries.ts b/scripts/check-browser-file-storage-boundaries.ts index 9866e541..1d23ab2f 100644 --- a/scripts/check-browser-file-storage-boundaries.ts +++ b/scripts/check-browser-file-storage-boundaries.ts @@ -141,10 +141,10 @@ const misplacedAdapterResults = [ ), }, { - file: "src/features/reference-feature/adapters/boundary-fixture.ts", + file: "src/features/fixture-feature/adapters/boundary-fixture.ts", result: runEslintSource( objectUrlBypassSource, - "src/features/reference-feature/adapters/boundary-fixture.ts", + "src/features/fixture-feature/adapters/boundary-fixture.ts", ), }, { diff --git a/scripts/check-i18n.ts b/scripts/check-i18n.ts index 0c2c04c7..ab236d6b 100644 --- a/scripts/check-i18n.ts +++ b/scripts/check-i18n.ts @@ -59,9 +59,8 @@ if (!fixtureMode) { // from an ordinary `.message` read. Fixture mode runs the ESLint rule on the // fixture trees too, so this one gate shows the whole i18n contract rejecting // every forbidden file and passing the allowed one. -// `src/presentation/examples` (the platform overview) and the example -// screens (`src/features/platform-examples-feature/presentation`, 1103/09-04) -// are workshop code and stay out of the ESLint rule's scope on purpose. +// `src/presentation/examples` (the platform overview) and the stories are +// workshop code and stay out of the ESLint rule's scope on purpose. const forbiddenFixtureRoot = "tests/fixtures/i18n/forbidden"; const allowedFixtureRoot = "tests/fixtures/i18n/allowed"; const sourceRoot = fixtureMode ? forbiddenFixtureRoot : "."; diff --git a/scripts/create-feature.ts b/scripts/create-feature.ts index 9654aaa6..576ce866 100644 --- a/scripts/create-feature.ts +++ b/scripts/create-feature.ts @@ -1709,7 +1709,7 @@ export const FEATURE_TRACKED_FILE_REWRITES = Object.freeze([ Object.freeze({ path: "config/scale/feature-shape-ceilings.json", command: "node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write", - when: "by hand while the sample is installed (the file goes with it): test:unit compares it with a build", + when: "by hand with the feature: test:unit compares it with a build", }), ]); @@ -1772,7 +1772,7 @@ function report(plan: FeaturePlan): string { " 2. Run the merge gates: corepack pnpm ci:gate -- FE-GATE- for each gate of the merge stage in config/ci/gates.json (README lists the loop). test:feature-scaffold runs them on a generated feature except the browser gates FE-GATE-008/009 and test:system.", ` The feature's own tests: node scripts/run-vitest.ts run tests/features/${plan.id} (test:coverage runs them in CI)`, " A failing gate's log is artifacts/quality/gates/FE-GATE-.txt. Locally FE-GATE-013 needs VITE_COMMIT_SHA=$(git rev-parse HEAD); to run them as CI does, set CI=true and the CI build identity (README).", - " 3. The initial JavaScript changes. While config/scale/feature-shape-ceilings.json exists (the sample is installed), rewrite it with node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write and commit it with the feature; test:unit compares it with a build. corepack pnpm check:bundle checks the budget.", + " 3. The initial JavaScript changes. Rewrite config/scale/feature-shape-ceilings.json with node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write and commit it with the feature; test:unit compares it with a build. corepack pnpm check:bundle checks the budget.", " public/release-manifest.json (the dev server's manifest) now names the feature's contract package; commit it with the feature.", " Two feature branches change the same lines of these files. On a merge conflict, take either side and run the command again:", ...FEATURE_TRACKED_FILE_REWRITES.map((file) => ` ${file.path}: ${file.command}`), diff --git a/scripts/generate-product-feature-index.ts b/scripts/generate-product-feature-index.ts index 26100243..352b1187 100644 --- a/scripts/generate-product-feature-index.ts +++ b/scripts/generate-product-feature-index.ts @@ -272,22 +272,15 @@ function requiredInteger(source: string, name: string, file: string): number { } /** - * 09-07 (D-10). A feature directory must declare itself or say it is not a - * feature. A missing or misspelt `feature-module.ts` used to drop the - * feature from the product without a word. - * - * 1103/09-09. The marker was named `NOT_INSTALLED`, the runtime state of a - * declared feature the build or the runtime document left out - * (`src/contracts/product-features.ts`). It marks something else, a directory - * that is no feature at all (an architecture sample), so it has its own name, - * and a directory may not carry both the marker and a declaration. + * 09-07 (D-10). A feature directory must declare itself. A missing or + * misspelt `feature-module.ts` used to drop the feature from the product + * without a word. Code that is no feature (a test's consumer fixture) lives + * outside src/features. */ -export const NOT_A_FEATURE_MARKER = "NOT_A_FEATURE"; - async function readDeclarations( directory: string, fileName: string, - requiredUnless?: string, + required = false, ): Promise[]> { const found: { directory: string; file: string; source: string }[] = []; let items; @@ -299,24 +292,13 @@ async function readDeclarations( for (const item of items) { if (!item.isDirectory()) continue; const file = resolve(directory, item.name, fileName); - const marker = - requiredUnless !== undefined && - (await readFile(resolve(directory, item.name, requiredUnless)).then( - () => true, - () => false, - )); let source: string; try { source = await readFile(file, "utf8"); } catch { - if (requiredUnless === undefined || marker) continue; + if (!required) continue; throw new Error( - `src/features/${item.name} has no ${fileName}; add one or mark the directory with ${requiredUnless}`, - ); - } - if (marker) { - throw new Error( - `src/features/${item.name} has both ${fileName} and ${requiredUnless}; delete ${requiredUnless} to install it, or ${fileName} to keep it out`, + `src/features/${item.name} has no ${fileName}; add one, or keep code that is no feature outside src/features`, ); } found.push({ directory: item.name, file, source }); @@ -368,7 +350,7 @@ export async function createFileSystemDeclarationSource( for (const declaration of await readDeclarations( resolve(root, "src/features"), "feature-module.ts", - NOT_A_FEATURE_MARKER, + true, )) { const feature: FeatureDeclaration = { id: requiredLiteral(declaration.source, "FEATURE_MODULE_ID", declaration.file), diff --git a/scripts/lib/a11y-data-state.ts b/scripts/lib/a11y-data-state.ts index 07db68ab..e5aee77c 100644 --- a/scripts/lib/a11y-data-state.ts +++ b/scripts/lib/a11y-data-state.ts @@ -113,7 +113,7 @@ type ReadFacts = Readonly<{ * not listed. * * This finds the detail pages that take their params schema from their read - * (the reference sample and every `create:feature --with-create` slice). A + * (every `create:feature --with-create` slice). A * detail page whose params schema differs is not found, and its record alone * decides, as before. */ diff --git a/scripts/lib/feature-residue.ts b/scripts/lib/feature-residue.ts index 459a6262..95202ea2 100644 --- a/scripts/lib/feature-residue.ts +++ b/scripts/lib/feature-residue.ts @@ -34,8 +34,8 @@ import path from "node:path"; * a test title), and no text rule tells that from a reference, so a spec * that names only a one-word ID is not found either. * - * The reference sample keeps its own, wider pattern in - * scripts/test-sample-removal.ts: the template owns all of its files. + * The drill applies the same rule to a sample a project lists in + * scripts/lib/removable-template-features.ts. */ function escapeRegExp(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); diff --git a/scripts/lib/generated-feature.ts b/scripts/lib/generated-feature.ts new file mode 100644 index 00000000..8430f836 --- /dev/null +++ b/scripts/lib/generated-feature.ts @@ -0,0 +1,126 @@ +import { spawnSync } from "node:child_process"; +import { cp, mkdtemp, rename, rm } from "node:fs/promises"; +import { existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +import { localBuildEnvironment } from "./build-environment.ts"; +import { linkFixtureNodeModules } from "./fixture-node-modules.ts"; +import { REMOVAL_FIXTURE_COPY_TARGETS } from "./removal-fixture.ts"; + +/** + * 2026-11-07. The template ships no feature. What needs one in a real build + * runs on the feature `create:feature` writes, added to a copy of the + * repository: the browser checks that one feature works end to end (route, + * form, save, a save whose result is lost; tests/e2e/generated-feature.spec.ts + * and the chunk recovery spec, whose fixture builds take `addGeneratedFeature` + * as their edit) and the browser soak's failing-backend visits + * (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. + */ +export const GENERATED_FEATURE_ID = "order-feature"; + +export type GeneratedRoute = Readonly<{ + routeId: string; + path: string; + chunkId: string; + /** The lazy page's module id (`routeRuntimeContracts`), the name of its chunk. */ + moduleId: string; +}>; + +export type GeneratedFeature = Readonly<{ + list: GeneratedRoute; + detail: GeneratedRoute; + create: GeneratedRoute; + /** The feature's ko-KR and en-US catalogs. */ + messages: Readonly>>>; + /** The collection the operations call: API_BASE_URL of the build plus the path. */ + api: string; +}>; + +function node(root: string, args: readonly string[]): string { + const result = spawnSync(process.execPath, args, { cwd: root, encoding: "utf8" }); + if (result.status !== 0) { + throw new Error(`node ${args.join(" ")} failed in ${root}:\n${result.stdout}\n${result.stderr}`); + } + return result.stdout; +} + +/** The edit of a fixture build: `corepack pnpm create:feature order-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"]); +} + +/** + * What the specs need to drive the feature, read from the copy the command + * wrote it into (node runs that TypeScript as it is): the three routes, the + * words and where its API is. + */ +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 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 { 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, + }); + 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, + })); + `; + return JSON.parse(node(root, ["--input-type=module", "-e", source])) as GeneratedFeature; +} + +/** A route's path with its one parameter filled in. */ +export function routePath(route: GeneratedRoute, id?: string): string { + return id === undefined ? route.path : route.path.replace(/:[A-Za-z][A-Za-z0-9_]*/u, id); +} + +/** + * A production build of a copy of the repository with the generated feature, + * in the local configuration. `remove` deletes the copy. + */ +export async function buildWithGeneratedFeature(prefix: string): Promise< + Readonly<{ dist: string; feature: GeneratedFeature; remove(): Promise }> +> { + const root = await mkdtemp(path.join(tmpdir(), `${prefix}-`)); + const remove = () => rm(root, { recursive: true, force: true }); + try { + for (const entry of REMOVAL_FIXTURE_COPY_TARGETS) { + if (!existsSync(entry)) continue; + await cp(entry, path.join(root, entry), { + recursive: true, + filter: (source) => !source.includes(`${path.sep}.generated`), + }); + } + await linkFixtureNodeModules(root); + await addGeneratedFeature(root); + const build = spawnSync(process.execPath, ["scripts/build-frontend.ts"], { + cwd: root, + encoding: "utf8", + env: localBuildEnvironment(), + }); + if (build.status !== 0) { + throw new Error(`scripts/build-frontend.ts failed in ${root}:\n${build.stdout}\n${build.stderr}`); + } + const dist = path.join(root, "dist-generated-feature"); + await rename(path.join(root, "dist"), dist); + return Object.freeze({ dist, feature: generatedFeature(root), remove }); + } catch (error) { + await remove(); + throw error; + } +} diff --git a/scripts/lib/removable-template-features.ts b/scripts/lib/removable-template-features.ts index 39e5aed2..aea13657 100644 --- a/scripts/lib/removable-template-features.ts +++ b/scripts/lib/removable-template-features.ts @@ -1,14 +1,16 @@ /** - * The features this template ships that a copied project may delete: the - * reference sample (README "Files you can delete after copying") and the - * example screens (docs/architecture/starter-experience.md, CHANGELOG "먼저 - * 할 일" 6). Each owns its folder under `src/features/` and `tests/features/` - * and the context it is the only feature of. The reference sample also owns - * files outside them, which `scripts/test-sample-removal.ts` deletes with it. + * The sample features a project ships and may delete later: each owns its + * folder under `src/features/` and `tests/features/`, the context it is the + * only feature of, and possibly files and package scripts outside them. * - * This is the one list. The removal drill reads the reference sample's paths - * and scripts from it, and the documentation check reads the whole of it: a - * feature counts as deleted once its `feature-module.ts` is gone. + * The template ships none: its reference sample and example screens were + * deleted on 2026-11-07, when the manual and `create:feature` took over their + * roles. A project that keeps a sample of its own lists it here. Then + * `test:sample-removal` without `--feature` (FE-GATE-020) deletes each one + * from a copy of the repository with these paths and scripts and runs the + * gates, and verify:documentation lets the documents name its paths until + * the sample is gone: a sample counts as deleted once its + * `feature-module.ts` is. */ export type RemovableTemplateFeature = Readonly<{ /** Its FEATURE_MODULE_ID, also its folder under src/features and tests/features. */ @@ -21,36 +23,7 @@ export type RemovableTemplateFeature = Readonly<{ scripts: readonly string[]; }>; -export const REMOVABLE_TEMPLATE_FEATURES: readonly RemovableTemplateFeature[] = Object.freeze([ - Object.freeze({ - featureId: "reference-feature", - contextDirectory: "src/contexts/reference-context", - // 0929/10-02. The HTTP scenario catalog (tests/mocks) and the negative - // type fixtures of the feature APIs run on the test contracts, so they - // are platform checks and stay (commonTestPaths in the drill). - extraPaths: Object.freeze([ - "tests/component/product-feature-switch.test.tsx", - "tests/e2e/reference-form.spec.ts", - "tests/e2e/reference-route.spec.ts", - "tests/e2e/reference-save.spec.ts", - // 11-04: the growth measurement copies this sample feature. - "tests/unit/feature-shape-growth.test.ts", - "scripts/scale/measure-feature-shape-growth.ts", - "config/scale/feature-shape-growth.json", - "config/scale/feature-shape-ceilings.json", - ]), - scripts: Object.freeze(["test:reference-feature"]), - }), - // 1103/09-04. The example screens /examples/ui, /examples/states and - // /examples/auth. The platform overview (/examples/platform) is a platform - // route and is not part of it. - Object.freeze({ - featureId: "platform-examples-feature", - contextDirectory: "src/contexts/platform-examples-context", - extraPaths: Object.freeze([]), - scripts: Object.freeze([]), - }), -]); +export const REMOVABLE_TEMPLATE_FEATURES: readonly RemovableTemplateFeature[] = Object.freeze([]); /** Every path removing `feature` deletes: its folders, its context and its extra files. */ export function removableTemplateFeaturePaths(feature: RemovableTemplateFeature): readonly string[] { diff --git a/scripts/lib/removal-fixture.ts b/scripts/lib/removal-fixture.ts index 0fd8afe2..f3246247 100644 --- a/scripts/lib/removal-fixture.ts +++ b/scripts/lib/removal-fixture.ts @@ -40,7 +40,7 @@ export const REMOVAL_FIXTURE_COPY_TARGETS = Object.freeze([ /** * This is the only copy-target list. Each removal script used to keep its own, - * and they drifted: the reference-feature fixture omitted + * and they drifted: the reference sample's fixture omitted * `playwright.capabilities.config.ts`, which the repository file inventory * requires, so supply-chain generation failed inside the fixture and took every * provider suite down with it — twenty-odd failures with one cause. @@ -84,6 +84,8 @@ export const REMOVAL_FIXTURE_DOCUMENT_TESTS = Object.freeze([ "tests/unit/template-feature-removal-documents.test.ts", // 1105/14-02. Reads a code block of docs/manual. "tests/unit/manual-paired-backend-settings.test.ts", + // Reads the marked code blocks of docs/manual. + "tests/unit/manual-code-blocks.test.ts", ] as const); /** The tests a fixture copied from `copyTargets` cannot run. */ diff --git a/scripts/lib/run-isolation.ts b/scripts/lib/run-isolation.ts index d51807bd..15cd263c 100644 --- a/scripts/lib/run-isolation.ts +++ b/scripts/lib/run-isolation.ts @@ -113,15 +113,33 @@ export function checkoutBuildReadFailure( /** * The port variable of each Playwright config's web server. Unset, the config * picks a free port; set, it uses that one (to pin a port while debugging). + * `visualWorkshop` is the visual config's second server, the static workshop + * the gallery goldens open. */ export const TEST_PORT_VARIABLES = Object.freeze({ e2e: "TEST_E2E_PORT", visual: "TEST_VISUAL_PORT", + visualWorkshop: "TEST_VISUAL_WORKSHOP_PORT", capabilities: "TEST_CAPABILITIES_PORT", storybook: "TEST_STORYBOOK_PORT", dev: "TEST_DEV_PORT", } as const); +/** + * The origin of a config's second server, for its specs. The runner reserved + * the port in `variable` (reservePort) and its workers inherit it. + */ +export function reservedOrigin( + variable: string, + environment: Readonly> = process.env, +): string { + const port = environment[variable]; + if (port === undefined || port === "") { + throw new Error(`${variable} is not set: run this spec through its Playwright config`); + } + return `http://127.0.0.1:${port}`; +} + /** * A port nothing listens on now: the one the kernel gives a socket bound to * port 0, which is closed again. Another process can still take it before the diff --git a/scripts/lib/storybook-static.ts b/scripts/lib/storybook-static.ts new file mode 100644 index 00000000..d916d957 --- /dev/null +++ b/scripts/lib/storybook-static.ts @@ -0,0 +1,27 @@ +import { testRunPath, testRunRoot } from "./run-isolation.ts"; + +/** + * The static workshop a Playwright config serves: the workshop tests + * (playwright.storybook.config.ts) and the gallery goldens + * (playwright.visual.config.ts) open the same build. + * + * 1105/12-04. Under TEST_RUN_ID the workshop is built into the run's own + * folder (.tmp/runs//artifacts/storybook/static) with build:storybook's + * two steps and another output folder. Unset, the gate's build:storybook + * writes artifacts/storybook/static. + */ +export function storybookStaticServer(port: number): Readonly<{ + directory: string; + command: string; +}> { + const directory = testRunPath("artifacts/storybook/static"); + const build = + testRunRoot() === "." + ? "corepack pnpm build:storybook" + : "node scripts/generate-product-feature-index.ts && " + + `corepack pnpm exec storybook build -o ${directory}`; + return Object.freeze({ + directory, + command: `${build} && node scripts/serve-static.ts ${directory} ${port}`, + }); +} diff --git a/scripts/scale/browser-soak.ts b/scripts/scale/browser-soak.ts index 66ef7200..0d94bb3d 100644 --- a/scripts/scale/browser-soak.ts +++ b/scripts/scale/browser-soak.ts @@ -4,6 +4,7 @@ import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import path from "node:path"; +import { buildWithGeneratedFeature } from "../lib/generated-feature.ts"; import { classifyCounterSeries, classifyMemorySlope, @@ -13,8 +14,12 @@ import { /** * scale-architecture.md §33 / §44. Browser soak on the existing Playwright runner. * - * Serves the built `dist/` on an OS-assigned 127.0.0.1 port and keeps one - * long-lived page cycling through the app's routes by client-side navigation. + * Serves a build on an OS-assigned 127.0.0.1 port and keeps one long-lived + * page cycling through the app's routes by client-side navigation. One of + * them is a feature's protected list (`featureRoute`), signed in once, whose + * reads fail. The template has no feature: by default the soak builds a copy + * with the one `create:feature` writes (scripts/lib/generated-feature.ts); + * `--dist` with `--feature-route` soaks a build of a product's own. * The served runtime config turns telemetry on (pointed at a local collector) * and points the API at a stub that always answers 503, so every cycle also * exercises bounded retries and telemetry under a sustained backend failure. @@ -51,9 +56,9 @@ export type SoakSummary = Readonly<{ storageKeyDelta: number; storageByteDelta: number; apiRequests: number; - referenceVisits: number; - settledReferenceVisits: number; - apiRequestsPerReferenceVisit: number; + featureVisits: number; + settledFeatureVisits: number; + apiRequestsPerFeatureVisit: number; telemetryPosts: number; telemetryEvents: number; maxTelemetryPostsPerMinute: number; @@ -83,7 +88,7 @@ export const SOAK_LIMITS = Object.freeze({ maxTimerDelta: 10, maxStorageKeyDelta: 2, /** One logical execution: 1 attempt + at most 2 retries. */ - maxApiRequestsPerReferenceVisit: 3, + maxApiRequestsPerFeatureVisit: 3, /** Two bounded pipelines (platform events + feature events) x 20/min. */ maxTelemetryPostsPerMinute: 40, }); @@ -104,8 +109,8 @@ export function summarizeSoak( export type SoakTotals = Readonly<{ cycles: number; navigationFailures: number; - referenceVisits: number; - settledReferenceVisits: number; + featureVisits: number; + settledFeatureVisits: number; finalInFlightRequests: number; apiRequests: number; telemetryPosts: number; @@ -148,12 +153,12 @@ export function evaluateSoak( storageKeyDelta: delta((sample) => sample.storageKeys), storageByteDelta: delta((sample) => sample.storageBytes), apiRequests: totals.apiRequests, - referenceVisits: totals.referenceVisits, - settledReferenceVisits: totals.settledReferenceVisits, - apiRequestsPerReferenceVisit: - totals.referenceVisits === 0 + featureVisits: totals.featureVisits, + settledFeatureVisits: totals.settledFeatureVisits, + apiRequestsPerFeatureVisit: + totals.featureVisits === 0 ? 0 - : Math.round((totals.apiRequests / totals.referenceVisits) * 1_000) / 1_000, + : Math.round((totals.apiRequests / totals.featureVisits) * 1_000) / 1_000, telemetryPosts: totals.telemetryPosts, telemetryEvents: totals.telemetryEvents, maxTelemetryPostsPerMinute, @@ -192,15 +197,15 @@ export function evaluateSoak( { name: "backend failure exercised", passed: - summary.settledReferenceVisits > 0 && summary.apiRequests > 0 && summary.telemetryEvents > 0, - detail: `${summary.settledReferenceVisits} settled visits, ${summary.apiRequests} API requests, ${summary.telemetryEvents} telemetry events`, + summary.settledFeatureVisits > 0 && summary.apiRequests > 0 && summary.telemetryEvents > 0, + detail: `${summary.settledFeatureVisits} settled visits, ${summary.apiRequests} API requests, ${summary.telemetryEvents} telemetry events`, }, { name: "request amplification", passed: - summary.referenceVisits > 0 && - summary.apiRequestsPerReferenceVisit <= SOAK_LIMITS.maxApiRequestsPerReferenceVisit, - detail: `${summary.apiRequests} requests / ${summary.referenceVisits} visits`, + summary.featureVisits > 0 && + summary.apiRequestsPerFeatureVisit <= SOAK_LIMITS.maxApiRequestsPerFeatureVisit, + detail: `${summary.apiRequests} requests / ${summary.featureVisits} visits`, }, { name: "telemetry rate", @@ -348,6 +353,8 @@ export async function runBrowserSoak( intervalMs: number; warmupMs: number; routes: readonly string[]; + /** A feature's protected list: signed in on, then visited with the rest. */ + featureRoute: string; }>, ): Promise { try { @@ -397,13 +404,14 @@ export async function runBrowserSoak( await page.addInitScript(PAGE_PROBES); const cdp = await page.context().newCDPSession(page); await cdp.send("Performance.enable"); - await page.goto(`${baseUrl}/examples/reference-resources`, { waitUntil: "load" }); + await page.goto(`${baseUrl}${options.featureRoute}`, { waitUntil: "load" }); await page.waitForSelector("#root > *", { timeout: 15_000 }); // Protected routes need a session: start the local demo session once, so - // the reference feature really dispatches its (failing) API requests. - const login = page.getByRole("button", { name: /로그인 시작|Sign in|Start sign-in/u }); - if (await login.count()) { - await login.first().click(); + // the feature really dispatches its (failing) API requests. + // The prompt draws once the feature's context routes have loaded. + const login = page.getByRole("button", { name: /로그인 시작|Sign in|Start sign-in/u }).first(); + if (await login.waitFor({ timeout: 10_000 }).then(() => true, () => false)) { + await login.click(); await page.waitForTimeout(500); } @@ -412,8 +420,8 @@ export async function runBrowserSoak( let nextSample = 0; let cycles = 0; let navigationFailures = 0; - let referenceVisits = 0; - let settledReferenceVisits = 0; + let featureVisits = 0; + let settledFeatureVisits = 0; const probe = async () => (await page.evaluate(() => (window as unknown as { __soakProbe: () => Probe }).__soakProbe(), @@ -421,7 +429,7 @@ export async function runBrowserSoak( while (Date.now() - started < options.durationMs) { const route = options.routes[cycles % options.routes.length] ?? "/"; cycles += 1; - if (route === "/examples/reference-resources") referenceVisits += 1; + if (route === options.featureRoute) featureVisits += 1; // Client-side navigation keeps one long-lived document, like a real session. await page.evaluate((target) => { window.history.pushState({}, "", target); @@ -436,10 +444,10 @@ export async function runBrowserSoak( ); if (!rendered) navigationFailures += 1; // Most visits leave after 50ms, which cancels the query (a cancelled - // request is intentionally not reported). Every 5th reference visit + // request is intentionally not reported). Every 5th feature visit // dwells until its interaction settles, so the failing backend is really // observed end to end: bounded retries, then feature/platform telemetry. - if (route === "/examples/reference-resources" && referenceVisits % 5 === 1) { + if (route === options.featureRoute && featureVisits % 5 === 1) { await page.waitForTimeout(200); await page .waitForFunction( @@ -448,7 +456,7 @@ export async function runBrowserSoak( { timeout: 5_000 }, ) .catch(() => undefined); - settledReferenceVisits += 1; + settledFeatureVisits += 1; } const elapsedMs = Date.now() - started; if (elapsedMs >= nextSample) { @@ -483,8 +491,8 @@ export async function runBrowserSoak( { cycles, navigationFailures, - referenceVisits, - settledReferenceVisits, + featureVisits, + settledFeatureVisits, finalInFlightRequests, apiRequests: counters.apiRequests, telemetryPosts: counters.telemetryPosts, @@ -526,16 +534,23 @@ async function main(): Promise { const argument = (name: string, fallback: string) => process.argv.find((entry) => entry.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback; const artifact = path.resolve(argument("artifact", "artifacts/scale/browser-soak.json")); + const ownBuild = argument("dist", ""); + const generated = ownBuild === "" ? await buildWithGeneratedFeature("browser-soak") : undefined; + const featureRoute = generated ? generated.feature.list.path : argument("feature-route", ""); + if (featureRoute === "") { + throw new Error("--dist needs --feature-route="); + } const result = await runBrowserSoak({ - distRoot: argument("dist", "dist"), + distRoot: generated?.dist ?? ownBuild, durationMs: Number(argument("duration-ms", "60000")), intervalMs: Number(argument("interval-ms", "5000")), warmupMs: Number(argument("warmup-ms", "15000")), routes: argument( "routes", - "/,/examples/reference-resources,/examples/platform,/examples/ui,/examples/states,/examples/reference-resources/status", + ["/", featureRoute, "/examples/platform", generated?.feature.create.path ?? "/not-found"].join(","), ).split(","), - }); + featureRoute, + }).finally(() => generated?.remove()); await mkdir(path.dirname(artifact), { recursive: true }); await writeFile(artifact, `${JSON.stringify(result, null, 2)}\n`); process.stdout.write( diff --git a/scripts/scale/measure-feature-shape-growth.ts b/scripts/scale/measure-feature-shape-growth.ts index 0fb5b724..90a3d4ae 100644 --- a/scripts/scale/measure-feature-shape-growth.ts +++ b/scripts/scale/measure-feature-shape-growth.ts @@ -1,10 +1,12 @@ import { spawnSync } from "node:child_process"; -import { cp, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { availableParallelism, cpus, loadavg, tmpdir } from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; import { gzipSync } from "node:zlib"; +import { PLATFORM_ROUTE_REGISTRY } from "../../src/contracts/routes.ts"; +import { planFeature, type InstalledFacts } from "../create-feature.ts"; import { classifyViteJavascript } from "../lib/classify-vite-bundle.ts"; import { linkFixtureNodeModules } from "../lib/fixture-node-modules.ts"; import { VITE_BUILD_INPUTS } from "../lib/vite-build-inputs.ts"; @@ -12,11 +14,13 @@ import { parseTscExtendedDiagnostics, type TscDiagnostics } from "./collect-tsc- /** * 11-04 (D-18). Cost of one app as its feature count grows, measured with - * features shaped like the real one: `src/features/reference-feature` copied N - * times with every feature-owned identifier renamed (feature id, route ids and - * paths, API operations, schemas, query namespace, invalidation topic, - * messages). The copies live in contexts of their own (200 features each, the - * context ceiling) so the reference context is unchanged. + * features shaped like a real one: N copies of the feature `create:feature` + * writes with `--with-create --keyed` (a list, a detail and a create with its + * form), each planned by the command's own planner (`planFeature`) with its + * own ids and its own pinned contract package. The copies live in contexts of + * their own, 200 features each (the context ceiling the baseline records). + * 2026-11-07: the copies were the template's reference sample, renamed; the + * template ships no sample now. * * For each N the script runs the product generator, `tsc --extendedDiagnostics` * over tsconfig.app.json and `vite build`, and records compiler counts, wall @@ -36,70 +40,102 @@ export const FEATURE_SHAPE_BASELINE_PATH = "config/scale/feature-shape-growth.js /** What the declared ceilings rest on, derived by hand from the baseline. */ export const FEATURE_SHAPE_CEILINGS_PATH = "config/scale/feature-shape-ceilings.json"; -const SOURCE_FEATURE = "src/features/reference-feature"; -const FEATURES_PER_CONTEXT = 200; -// Platform-owned names that only happen to contain "reference". -const PLATFORM_TOKENS = [ - "REFERENCE_FEATURE_V1", - "supportReference", -] as const; +/** The command each copy is, as the baseline records it. */ +export const SHAPE_FEATURE_COMMAND = "create:feature --with-create --keyed"; +export const FEATURES_PER_CONTEXT = 200; -/** Renames every feature-owned identifier of the reference feature for copy `id`. */ -export function renameReferenceFeature( - text: string, - id: string, - context: Readonly<{ id: string; routeRoot: string }>, -): string { - const upper = id.toUpperCase(); - // 1101/07-04. Assembly refuses the reference fixture source in any other - // feature, so a copy pins an external package and declares it in its - // contracts, as a product feature would. - const contractPackage = [ - "Object.freeze({", - ` packageId: "@feature-shape/${id}",`, - ' version: "1.0.0",', - ' digest: `sha256:${"0".repeat(64)}`,', - " runtimeProtocolVersion: 1 as const,", - ' sourceRevision: "0000000",', - " })", - ].join("\n"); - let renamed = text - .replace( - /source: Object\.freeze\(\{\s*kind: "TEMPLATE_FIXTURE" as const,\s*fixtureId: "REFERENCE_FEATURE_V1" as const,\s*revision: 1 as const,\s*\}\)/u, - `source: Object.freeze({\n kind: "EXTERNAL_PACKAGE" as const,\n package: ${contractPackage},\n })`, - ) - .replace( - "contractPackages: Object.freeze([]),", - `contractPackages: Object.freeze([${contractPackage}]),`, +/** Copy `index`: its feature id and the context it lands in. */ +export function shapeFeature(index: number, featuresPerContext = FEATURES_PER_CONTEXT) { + const contextNumber = Math.floor(index / featuresPerContext); + return Object.freeze({ + id: `s${String(index).padStart(3, "0")}-feature`, + context: Object.freeze({ id: `shape-context-${contextNumber}`, routeRoot: `shape-${contextNumber}` }), + }); +} + +function contextModule(context: Readonly<{ id: string; routeRoot: string }>): string { + return ( + `export const CONTEXT_MODULE_ID = "${context.id}";\n` + + `export const CONTEXT_APP_ID = "template-app";\n` + + `export const CONTEXT_ROUTE_PATH = "${context.routeRoot}/*";\n` + + `export const CONTEXT_MAX_FEATURES = ${FEATURES_PER_CONTEXT};\n` + ); +} + +/** + * The source files of `features` copies: the context declarations and what + * `create:feature` writes under src/features (its tests and accessibility + * records are not part of a build). Each copy pins `@feature-shape/`, as + * a product feature pins its published package, and gets a topic of its own. + */ +export function planShapeFeatures( + features: number, + featuresPerContext = FEATURES_PER_CONTEXT, +): ReadonlyMap { + const files = new Map(); + const contexts: { id: string; routePath: string }[] = []; + const routes: InstalledFacts["routes"][number][] = Object.values(PLATFORM_ROUTE_REGISTRY).map( + (route) => ({ + routeId: route.routeId, + path: route.path, + chunkId: route.chunkId, + navigationOrder: route.navigationOrder, + }), + ); + const featureIds: string[] = []; + const topics: string[] = []; + for (let index = 0; index < features; index += 1) { + const { id, context } = shapeFeature(index, featuresPerContext); + if (index % featuresPerContext === 0) { + contexts.push({ id: context.id, routePath: `${context.routeRoot}/*` }); + files.set(`src/contexts/${context.id}/context-module.ts`, contextModule(context)); + } + const navigationOrder = + Math.max(0, ...routes.flatMap((route) => (route.navigationOrder === null ? [] : [route.navigationOrder]))) + 10; + const plan = planFeature( + { + id, + context: context.id, + write: "KEYED", + contractPackage: { + packageId: `@feature-shape/${id}`, + version: "1.0.0", + digest: `sha256:${"0".repeat(64)}`, + sourceRevision: "0000000", + }, + }, + { + appIds: ["template-app"], + featureIds, + contexts, + contextDirectories: contexts.map((declared) => declared.id), + routes, + topics, + messageKeys: [], + }, + () => String(index).padStart(26, "0"), ); - PLATFORM_TOKENS.forEach((token, index) => { - renamed = renamed.replaceAll(token, `\u0000${index}\u0000`); - }); - renamed = renamed - .replaceAll("/examples/reference-resources", `/${context.routeRoot}/${id}-resources`) - .replaceAll("qinv.01k10f7m3w9p6r2c8v5n4x", `qinv.shape.${id}`) - .replaceAll("NoRequest", `${upper}NoRequest`) - .replaceAll("reference-context", context.id) - .replaceAll("REFERENCE", upper) - .replaceAll("Reference", upper) - .replaceAll("reference", id); - PLATFORM_TOKENS.forEach((token, index) => { - renamed = renamed.replaceAll(`\u0000${index}\u0000`, token); - }); - return renamed; -} - -async function copyRenamed(from: string, to: string, rename: (text: string) => string) { - await mkdir(to, { recursive: true }); - for (const entry of await readdir(from, { withFileTypes: true })) { - const source = path.join(from, entry.name); - const target = path.join(to, rename(entry.name)); - if (entry.isDirectory()) await copyRenamed(source, target, rename); - else await writeFile(target, rename(await readFile(source, "utf8"))); + for (const [file, content] of plan.files) { + if (file.startsWith("src/")) files.set(file, content); + } + featureIds.push(id); + topics.push(plan.topic); + for (const route of plan.routes) { + routes.push({ + routeId: route.routeId, + path: route.path, + chunkId: `${route.routeId}-chunk`, + navigationOrder: route.routeId === plan.routeId ? navigationOrder : null, + }); + } } + return files; } -async function createFixture(features: number): Promise { +async function createFixture( + features: number, + featuresPerContext = FEATURES_PER_CONTEXT, +): Promise { const root = await mkdtemp(path.join(tmpdir(), `feature-shape-${features}-`)); for (const input of VITE_BUILD_INPUTS) { await mkdir(path.dirname(path.join(root, input)), { recursive: true }); @@ -107,26 +143,9 @@ async function createFixture(features: number): Promise { } await rm(path.join(root, "src/.generated"), { recursive: true, force: true }); await linkFixtureNodeModules(root); - for (let index = 0; index < features; index += 1) { - const contextNumber = Math.floor(index / FEATURES_PER_CONTEXT); - const context = { id: `shape-context-${contextNumber}`, routeRoot: `shape-${contextNumber}` }; - if (index % FEATURES_PER_CONTEXT === 0) { - const contextFile = path.join(root, "src/contexts", context.id, "context-module.ts"); - await mkdir(path.dirname(contextFile), { recursive: true }); - await writeFile( - contextFile, - `export const CONTEXT_MODULE_ID = "${context.id}";\n` + - `export const CONTEXT_APP_ID = "template-app";\n` + - `export const CONTEXT_ROUTE_PATH = "${context.routeRoot}/*";\n` + - `export const CONTEXT_MAX_FEATURES = ${FEATURES_PER_CONTEXT};\n`, - ); - } - const id = `s${String(index).padStart(3, "0")}`; - await copyRenamed( - path.resolve(SOURCE_FEATURE), - path.join(root, "src/features", `${id}-feature`), - (text) => renameReferenceFeature(text, id, context), - ); + for (const [file, content] of planShapeFeatures(features, featuresPerContext)) { + await mkdir(path.dirname(path.join(root, file)), { recursive: true }); + await writeFile(path.join(root, file), content); } return root; } @@ -166,15 +185,15 @@ async function javascriptGzipBytes(root: string, files: readonly string[]) { } /** - * 15-01. Initial JavaScript of the app with `features` reference copies - * added: the generator and `vite build` only, no typecheck. The unit suite + * 15-01. Initial JavaScript of the app with `features` copies added: the generator and `vite build` only, no typecheck. The unit suite * (merge stage) bounds what one more feature adds to the initial chunk with * it, so the growth is caught on the PR instead of at the next release. */ async function measureInitialJavascript( features: number, + featuresPerContext = FEATURES_PER_CONTEXT, ): Promise> { - const root = await createFixture(features); + const root = await createFixture(features, featuresPerContext); try { run(process.execPath, [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], root); run(path.resolve("node_modules/.bin/vite"), ["build", "--logLevel", "error"], root); @@ -187,17 +206,20 @@ async function measureInitialJavascript( } /** - * 1103/15-02, 15-04. The template's initial JavaScript and what one more - * feature and one more context add to it. The first copy lands in a new - * context (shape-context-0) and the second in the same one, so the second - * copy is a feature alone and the rest of the first is the context. - * `initialJavascript` in config/scale/feature-shape-ceilings.json records - * these numbers; tests/unit/feature-shape-growth.test.ts compares them with - * the build on every unit run. + * 1103/15-02, 15-04. The template's initial JavaScript and what features add + * to it. Two copies in one context against one copy are one more feature + * alone; the same two copies in two contexts against that are one more + * context. 2026-11-07: the template has no feature, so the first copy also + * brings the code every feature shares into the initial chunks; that is + * `firstFeatureGzipBytes`, paid once. `initialJavascript` in + * config/scale/feature-shape-ceilings.json records these numbers; + * tests/unit/feature-shape-growth.test.ts compares them with the build on + * every unit run. */ export type InitialJavascriptCosts = Readonly<{ gzipBytes: number; files: number; + firstFeatureGzipBytes: number; perFeatureGzipBytes: number; perContextGzipBytes: number; }>; @@ -205,13 +227,14 @@ export type InitialJavascriptCosts = Readonly<{ export async function measureInitialJavascriptCosts(): Promise { const none = await measureInitialJavascript(0); const one = await measureInitialJavascript(1); - const two = await measureInitialJavascript(2); - const perFeatureGzipBytes = two.gzipBytes - one.gzipBytes; + const twoInOneContext = await measureInitialJavascript(2); + const twoInTwoContexts = await measureInitialJavascript(2, 1); return { gzipBytes: none.gzipBytes, files: none.files, - perFeatureGzipBytes, - perContextGzipBytes: one.gzipBytes - none.gzipBytes - perFeatureGzipBytes, + firstFeatureGzipBytes: one.gzipBytes - none.gzipBytes, + perFeatureGzipBytes: twoInOneContext.gzipBytes - one.gzipBytes, + perContextGzipBytes: twoInTwoContexts.gzipBytes - twoInOneContext.gzipBytes, }; } @@ -228,10 +251,18 @@ export const INITIAL_JAVASCRIPT_RECORD_TOLERANCE_BYTES = 256; /** * Fields of the record that no longer describe the build. The total may be - * INITIAL_JAVASCRIPT_RECORD_TOLERANCE_BYTES off; the per-feature and - * per-context costs are differences of builds with the same id but only a - * few hundred bytes, so 10%; the file count is exact. + * INITIAL_JAVASCRIPT_RECORD_TOLERANCE_BYTES off; the first-feature, + * per-feature and per-context costs are differences of builds with the same + * id, so 10%, and at least COST_RECORD_TOLERANCE_BYTES: a context costs a few + * bytes now, and gzip moves a difference that small by a byte or two when + * the build id changes. The file count is exact. */ +export const COST_RECORD_TOLERANCE_BYTES = 16; + +function costTolerance(bytes: number): number { + return Math.max(Math.abs(bytes) * 0.1, COST_RECORD_TOLERANCE_BYTES); +} + export function initialJavascriptRecordDrift( measured: InitialJavascriptCosts, record: InitialJavascriptCosts, @@ -239,8 +270,9 @@ export function initialJavascriptRecordDrift( const allowed: Readonly> = { gzipBytes: INITIAL_JAVASCRIPT_RECORD_TOLERANCE_BYTES, files: 0, - perFeatureGzipBytes: Math.abs(measured.perFeatureGzipBytes) * 0.1, - perContextGzipBytes: Math.abs(measured.perContextGzipBytes) * 0.1, + firstFeatureGzipBytes: costTolerance(measured.firstFeatureGzipBytes), + perFeatureGzipBytes: costTolerance(measured.perFeatureGzipBytes), + perContextGzipBytes: costTolerance(measured.perContextGzipBytes), }; return (Object.keys(allowed) as (keyof InitialJavascriptCosts)[]) .filter((field) => Math.abs(record[field] - measured[field]) > allowed[field]) @@ -393,7 +425,7 @@ async function main(): Promise { vite: version("vite"), }, source, - sourceFeature: SOURCE_FEATURE, + sourceFeature: SHAPE_FEATURE_COMMAND, runs, }; const output = process.argv.includes("--write") diff --git a/scripts/test-feature-scaffold.ts b/scripts/test-feature-scaffold.ts index 3ed300d6..77dd67f7 100644 --- a/scripts/test-feature-scaffold.ts +++ b/scripts/test-feature-scaffold.ts @@ -71,8 +71,8 @@ try { if (created.passed && createdWrite.passed) { // The generator's Next: 3. A project re-records the initial JavaScript // with its features (config/scale/feature-shape-ceilings.json, which - // test:unit compares with a build) and commits it with them. Without the - // sample there is no record to keep. + // test:unit compares with a build) and commits it with them. A project + // that deleted the measurement has no record to keep. const measurement = "scripts/scale/measure-feature-shape-growth.ts"; if (existsSync(path.join(fixtureRoot, measurement))) { const recorded = spawnSync(process.execPath, [measurement, "--initial-baseline", "--write"], { diff --git a/scripts/test-sample-removal.ts b/scripts/test-sample-removal.ts index 8c4dbc10..e60d011d 100644 --- a/scripts/test-sample-removal.ts +++ b/scripts/test-sample-removal.ts @@ -8,8 +8,10 @@ import { } from "node:fs/promises"; import { spawnSync } from "node:child_process"; import path from "node:path"; +import { fileURLToPath } from "node:url"; import { ROUTE_FEATURE_OWNER } from "../src/features/installed-feature-contracts.ts"; +import { loadCiGateContract } from "./contracts/ci-gates.ts"; import { createFileSystemDeclarationSource } from "./generate-product-feature-index.ts"; import { productFeatureResidue } from "./lib/feature-residue.ts"; import { isProductionModulePath } from "./lib/risk-coverage.ts"; @@ -32,42 +34,92 @@ import { import { REMOVABLE_TEMPLATE_FEATURES } from "./lib/removable-template-features.ts"; /** - * 09-07 (D-10). Removes one installed feature, `--feature=` (default: the - * reference sample), from a copy of the repository and proves the rest still - * typechecks, tests, covers and builds. Every feature loses its directory, its - * tests/features directory, its context when no other feature is left in it, - * its runtime-profile override and its central policy rows. The sample also - * owns the extra paths and scripts listed in SAMPLE_EXTRAS. + * 09-07 (D-10). Removes one installed feature, `--feature=`, from a copy + * of the repository and proves the rest still typechecks, tests, covers and + * builds. Every feature loses its directory, its tests/features directory, + * its context when no other feature is left in it, its runtime-profile + * override and its central policy rows. A sample that + * scripts/lib/removable-template-features.ts lists also loses its extra paths + * and package scripts, with the CI evidence only those scripts produce, and + * the copy then gets a feature from create:feature and runs the gates again. + * + * Without `--feature` (FE-GATE-020) each listed sample is removed in turn. + * The template lists none since its samples were deleted (2026-11-07): the + * run then reports the drill as skipped, not passed, and test:feature-scaffold + * removes a generated feature through `--feature`. */ -const featureId = - process.argv.find((argument) => argument.startsWith("--feature=")) - ?.slice("--feature=".length) ?? "reference-feature"; +const SAMPLE_REPORT = "artifacts/tests/sample-removal.xml"; +const requestedFeature = process.argv + .find((argument) => argument.startsWith("--feature=")) + ?.slice("--feature=".length); + +if (requestedFeature === undefined) { + const checks: RemovalCheck[] = REMOVABLE_TEMPLATE_FEATURES.map((sample) => { + const status = spawnSync( + process.execPath, + [fileURLToPath(import.meta.url), `--feature=${sample.featureId}`], + { stdio: "inherit" }, + ).status; + return status === 0 + ? { name: sample.featureId, passed: true } + : { + name: sample.featureId, + passed: false, + failure: `test:sample-removal -- --feature=${sample.featureId} exited ${status ?? "on a signal"}`, + }; + }); + await mkdir("artifacts/tests", { recursive: true }); + if (checks.length === 0) { + await writeFile( + SAMPLE_REPORT, + `\n` + + `` + + `` + + `\n`, + ); + process.stdout.write( + "sample removal: SKIP (scripts/lib/removable-template-features.ts lists no sample; " + + "test:feature-scaffold removes a generated feature with --feature)\n", + ); + } else { + await writeFile(SAMPLE_REPORT, renderRemovalJunit("sample-removal", checks)); + if (checks.some((check) => !check.passed)) process.exitCode = 1; + } + process.exit(); +} +const featureId: string = requestedFeature; type FeatureExtras = Readonly<{ paths: readonly string[]; ciScripts: readonly string[]; evidencePathFragments: readonly string[]; - residue: RegExp; }>; -// The sample's own files and scripts outside its folders are declared with -// the other removable template features, which verify:documentation reads too. -const REFERENCE_SAMPLE = REMOVABLE_TEMPLATE_FEATURES.find( - (feature) => feature.featureId === "reference-feature", -); -if (REFERENCE_SAMPLE === undefined) { - throw new Error("scripts/lib/removable-template-features.ts does not declare reference-feature"); +/** The CI evidence that only `scripts` produce: it goes with them. */ +async function evidenceOnlyFrom(scripts: readonly string[]): Promise { + if (scripts.length === 0) return []; + const contract = await loadCiGateContract(process.cwd()); + const commandIds = new Set( + contract.commands.filter(({ script }) => scripts.includes(script)).map(({ id }) => id), + ); + return contract.artifacts.flatMap((artifact) => + artifact.production === "command-generated" && + artifact.producerCommandIds.length > 0 && + artifact.producerCommandIds.every((commandId) => commandIds.has(commandId)) + ? [artifact.path] + : [], + ); } -const SAMPLE_EXTRAS: Readonly> = Object.freeze({ - "reference-feature": Object.freeze({ - paths: REFERENCE_SAMPLE.extraPaths, - ciScripts: REFERENCE_SAMPLE.scripts, - evidencePathFragments: [ - "reference-feature.xml", - ], - residue: /REFERENCE_RESOURCE|reference-feature|reference-resource/i, - }), +// The sample's own files and scripts outside its folders, which +// verify:documentation reads too. +const listedSample = REMOVABLE_TEMPLATE_FEATURES.find( + (feature) => feature.featureId === featureId, +); +const extras: FeatureExtras = Object.freeze({ + paths: listedSample?.extraPaths ?? [], + ciScripts: listedSample?.scripts ?? [], + evidencePathFragments: await evidenceOnlyFrom(listedSample?.scripts ?? []), }); function escapeRegExp(value: string): string { @@ -106,15 +158,6 @@ async function locateFeature(id: string) { } const located = await locateFeature(featureId); -const extras: FeatureExtras = SAMPLE_EXTRAS[featureId] ?? Object.freeze({ - paths: [], - ciScripts: [], - evidencePathFragments: [], - residue: new RegExp( - `${escapeRegExp(featureId)}|${escapeRegExp(located.directory)}`, - "i", - ), -}); // Captured from this repository before the copy loses them. const featureRouteIds = Object.entries(ROUTE_FEATURE_OWNER) .filter(([, owner]) => owner === featureId) @@ -124,7 +167,7 @@ const fixtureRoot = await createRemovalFixtureRoot(`${featureId}-removal`); const pnpmCli = requireRemovalFixtureEnvironment("npm_execpath"); const featureSource = `src/features/${located.directory}`; const featureTests = `tests/features/${located.directory}`; -const isSample = featureId in SAMPLE_EXTRAS; +const isSample = listedSample !== undefined; /** * Platform tests that must survive the sample feature's removal. Asserting they * are still present is what stops the removal fixture from "passing" by having @@ -281,12 +324,6 @@ try { const retainedCriticalModules = coveragePolicy.criticalModules.filter( (modulePolicy) => !modulePolicy.path?.startsWith(`${featureSource}/`), ); - if ( - isSample && - retainedCriticalModules.length === coveragePolicy.criticalModules.length - ) { - throw new Error("Reference feature coverage policy is not registered"); - } coveragePolicy.criticalModules = retainedCriticalModules; coveragePolicy.highRiskPaths = coveragePolicy.highRiskPaths.filter( (modulePath) => !modulePath.startsWith(`${featureSource}/`), @@ -299,7 +336,7 @@ try { ); coveragePolicy.repositoryBaseline -= removedProductionModuleCount; if (coveragePolicy.repositoryBaseline <= 0) { - throw new Error("Reference feature removal produced an invalid coverage baseline"); + throw new Error(`${featureId} removal produced an invalid coverage baseline`); } await writeFile( coveragePolicyFile, @@ -400,7 +437,7 @@ try { // JavaScript of the features installed now, and test:unit compares a build // with it. A product re-records it when it adds a feature; removing that // feature changes it again, so the fixture re-records it as the product - // would. The sample removal deletes the measurement with the sample. + // would. const measurement = path.join(fixtureRoot, "scripts/scale/measure-feature-shape-growth.ts"); if (await access(measurement).then(() => true, () => false)) { const measured = spawnSync( @@ -414,22 +451,13 @@ try { } await regenerateRemovalFixtureWorkflow(fixtureRoot); - const residue: string[] = []; - if (isSample) { - for (const root of ["src", "tests"]) { - for (const file of await filesBelow(path.join(fixtureRoot, root))) { - const relative = path.relative(fixtureRoot, file); - const content = await readFile(file, "utf8"); - if (extras.residue.test(`${relative}\n${content}`)) { - residue.push(relative); - } - } - } - } else { - // 1105/16-04. Template tests use example feature IDs as data; only what - // still points at the removed feature counts (scripts/lib/feature-residue.ts). - residue.push(...(await productFeatureResidue(fixtureRoot, featureId, located.directory))); - } + // 1105/16-04. Template tests use example feature IDs as data; only what + // still points at the removed feature counts (scripts/lib/feature-residue.ts). + const residue = await productFeatureResidue(fixtureRoot, featureId, located.directory); + const builtResiduePattern = new RegExp( + `${escapeRegExp(featureId)}|${escapeRegExp(located.directory)}`, + "i", + ); const missingCommonTests: string[] = []; for (const testPath of commonTestPaths) { @@ -471,7 +499,7 @@ try { for (const file of await filesBelow(path.join(fixtureRoot, "dist"))) { if (!/\.(?:js|css|html|json)$/.test(file)) continue; const content = await readFile(file, "utf8"); - if (extras.residue.test(content)) { + if (builtResiduePattern.test(content)) { builtResidue.push(path.relative(fixtureRoot, file)); } } @@ -493,9 +521,9 @@ try { outcome("built-fixture-id-residue", builtResidue, "built residue"), ); - // U7 (decision 4). The same copy, now without the sample, gets one feature - // from create:feature and runs the same gates again: the command and the - // feature it writes need nothing from the sample. + // U7 (decision 4). The same copy, now without the listed sample, gets one + // feature from create:feature and runs the same gates again: the command + // and the feature it writes need nothing from the sample. if (isSample) { // 1103/09-06. With the write slice (NEVER), which needs nothing from // the sample either. @@ -513,9 +541,7 @@ try { const failed = checks.filter((entry) => !entry.passed); await mkdir("artifacts/tests", { recursive: true }); await writeFile( - isSample - ? "artifacts/tests/sample-removal.xml" - : `artifacts/tests/feature-removal-${featureId}.xml`, + `artifacts/tests/feature-removal-${featureId}.xml`, renderRemovalJunit(`${featureId}-removal`, checks), ); if (failed.length > 0) { diff --git a/scripts/verify-documentation-readiness.ts b/scripts/verify-documentation-readiness.ts index 32f4b322..5f72f0df 100644 --- a/scripts/verify-documentation-readiness.ts +++ b/scripts/verify-documentation-readiness.ts @@ -187,15 +187,12 @@ const gateIds = new Set([ ).gates.map((gate) => gate.id), ...RETIRED_GATE_IDS, ]); -// 1105/14-01. A copy may delete the template features listed in -// scripts/lib/removable-template-features.ts, and the CHANGELOG tells -// tech-log to delete the example screens. The documents are the template's: -// a product that edited them to drop the feature's paths would conflict on -// every sync. While a feature is installed (its feature-module.ts exists), -// its paths and scripts are checked like any other; once it is not, they are -// not drift. tech-log keeps the reference sample's folder with its contracts -// but without its module, screens and tests (CHANGELOG "먼저 할 일" 1). A -// misspelt feature folder is not on the list and still fails. +// 1105/14-01. A copy may delete the sample features listed in +// scripts/lib/removable-template-features.ts (the template lists none since +// 2026-11-07). The documents may name a sample's paths: while it is installed +// (its feature-module.ts exists), its paths and scripts are checked like any +// other; once it is not, they are not drift. A misspelt feature folder is not +// on the list and still fails. const removedTemplateFeatures = REMOVABLE_TEMPLATE_FEATURES.filter( (feature) => !exists(`src/features/${feature.featureId}/feature-module.ts`), ); diff --git a/scripts/verify-extreme-scale.ts b/scripts/verify-extreme-scale.ts index 2fc9c913..8bffa3bb 100644 --- a/scripts/verify-extreme-scale.ts +++ b/scripts/verify-extreme-scale.ts @@ -35,7 +35,6 @@ export const EXTREME_SCALE_GATES = Object.freeze([ "check:observability", "check:release-coherence", "test:platform", - "test:reference-feature", "check:scale:pr", "check:scale:main", "check:scale:baseline", diff --git a/src/contexts/platform-examples-context/context-module.ts b/src/contexts/platform-examples-context/context-module.ts deleted file mode 100644 index 930b0859..00000000 --- a/src/contexts/platform-examples-context/context-module.ts +++ /dev/null @@ -1,12 +0,0 @@ -/** - * 1103/09-04. The template's example screens (UI gallery, screen states, - * auth integration) as one removable bounded context. A product leaves - * `platform-examples-feature` out of `VITE_PRODUCT_FEATURES`, or deletes it, - * and the three routes leave the registry, the navigation, the bundle and the - * manual accessibility list together. The root is `examples/*`; the sample - * feature's own context keeps a more specific path below it. - */ -export const CONTEXT_MODULE_ID = "platform-examples-context"; -export const CONTEXT_APP_ID = "template-app"; -export const CONTEXT_ROUTE_PATH = "examples/*"; -export const CONTEXT_MAX_FEATURES = 1; diff --git a/src/contexts/reference-context/context-module.ts b/src/contexts/reference-context/context-module.ts deleted file mode 100644 index 11c6996b..00000000 --- a/src/contexts/reference-context/context-module.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Ownership declaration of the reference bounded context (the rules are in - * docs/architecture/starter-experience.md, "Ownership declarations"): the app - * that owns it, its route root, and its direct-feature budget. Features name - * this id as their owner. - */ -export const CONTEXT_MODULE_ID = "reference-context"; -export const CONTEXT_APP_ID = "template-app"; -export const CONTEXT_ROUTE_PATH = "examples/reference-resources/*"; -export const CONTEXT_MAX_FEATURES = 200; diff --git a/src/features/local-draft-feature/NOT_A_FEATURE b/src/features/local-draft-feature/NOT_A_FEATURE deleted file mode 100644 index 1c481d10..00000000 --- a/src/features/local-draft-feature/NOT_A_FEATURE +++ /dev/null @@ -1,6 +0,0 @@ -local-draft is an architecture sample for the indexedDb feature capability, not -a product feature. It has no feature-module.ts on purpose, so the index -generator (scripts/generate-product-feature-index.ts) leaves it out; its -composition is exercised by tests/contract/reusable-capability and -recipes/frontend-capabilities/indexeddb-feature-capability.ts. To install it, -add feature-module.ts and context-routes.ts and delete this file. diff --git a/src/features/platform-examples-feature/context-routes.ts b/src/features/platform-examples-feature/context-routes.ts deleted file mode 100644 index 1e332afe..00000000 --- a/src/features/platform-examples-feature/context-routes.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { RouteObject } from "react-router-dom"; - -import { PLATFORM_EXAMPLES_CONTRACT } from "./contracts/platform-examples-contract.ts"; -import { PLATFORM_EXAMPLES_ROUTE_RUNTIME } from "./presentation/platform-examples-runtime.ts"; - -export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze( - Object.values(PLATFORM_EXAMPLES_CONTRACT.routes).map((definition) => - Object.freeze({ - id: definition.routeId, - path: definition.path, - handle: Object.freeze({ - routeId: definition.routeId, - runtime: PLATFORM_EXAMPLES_ROUTE_RUNTIME[definition.routeId], - }), - }), - ), -); diff --git a/src/features/platform-examples-feature/contracts/platform-examples-contract.ts b/src/features/platform-examples-feature/contracts/platform-examples-contract.ts deleted file mode 100644 index e98498e4..00000000 --- a/src/features/platform-examples-feature/contracts/platform-examples-contract.ts +++ /dev/null @@ -1,82 +0,0 @@ -export const PLATFORM_EXAMPLES_FEATURE_ID = "platform-examples-feature"; - -/** - * 1103/09-04. Three of the template's example screens, formerly fixed - * platform routes. The platform overview (`EXAMPLES_PLATFORM`) stays a - * platform route: the lab gate (FE-GATE-026) times entering it, and a feature - * route's first entry costs a second request round (its context's routes - * module, then the page). Paths, chunk ids and surfaces are unchanged: the - * visual and e2e tests and the manual accessibility records still name them. - * Declaration only, so it holds data; the pages load with `context-routes.ts`. - */ -export const PLATFORM_EXAMPLES_CONTRACT = Object.freeze({ - featureId: PLATFORM_EXAMPLES_FEATURE_ID, - routes: Object.freeze({ - EXAMPLES_UI: Object.freeze({ - routeId: "EXAMPLES_UI", - path: "/examples/ui", - paramsSchema: null, - searchSchema: null, - access: "public", - loadingSurface: "example-page", - errorSurface: "route-boundary", - chunkId: "route-examples-ui", - title: "UI 구성요소", - navigationLabel: "UI 구성요소", - navigationOrder: 20, - }), - EXAMPLES_STATES: Object.freeze({ - routeId: "EXAMPLES_STATES", - path: "/examples/states", - paramsSchema: null, - searchSchema: null, - access: "public", - loadingSurface: "example-page", - errorSurface: "route-boundary", - chunkId: "route-examples-states", - title: "화면 상태", - navigationLabel: "화면 상태", - navigationOrder: 30, - }), - EXAMPLES_AUTH: Object.freeze({ - routeId: "EXAMPLES_AUTH", - path: "/examples/auth", - paramsSchema: null, - searchSchema: null, - access: "public", - loadingSurface: "example-page", - errorSurface: "route-boundary", - chunkId: "route-examples-auth", - title: "인증 연동", - navigationLabel: "인증 연동", - navigationOrder: 40, - }), - }), - routeRuntimeContracts: Object.freeze({ - EXAMPLES_UI: Object.freeze({ - routeId: "EXAMPLES_UI", - moduleId: "ui-gallery-page", - paramsCodec: "none", - searchCodec: "none", - }), - EXAMPLES_STATES: Object.freeze({ - routeId: "EXAMPLES_STATES", - moduleId: "state-gallery-page", - paramsCodec: "none", - searchCodec: "none", - }), - EXAMPLES_AUTH: Object.freeze({ - routeId: "EXAMPLES_AUTH", - moduleId: "auth-example-page", - paramsCodec: "none", - searchCodec: "none", - }), - }), - invalidation: Object.freeze({ - topics: Object.freeze([]), - namespaces: Object.freeze([]), - edges: Object.freeze([]), - }), - topicVersions: Object.freeze([]), - contractPackages: Object.freeze([]), -} as const); diff --git a/src/features/platform-examples-feature/contracts/platform-examples-message-catalog.ts b/src/features/platform-examples-feature/contracts/platform-examples-message-catalog.ts deleted file mode 100644 index 310c98d4..00000000 --- a/src/features/platform-examples-feature/contracts/platform-examples-message-catalog.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * 1103/09-04. The route titles and navigation labels the shell reads; they - * moved here from the platform catalog with the routes. The pages' own copy - * stays Korean in every locale (08-07). - */ -export const PLATFORM_EXAMPLES_MESSAGE_CATALOGS = Object.freeze({ - "ko-KR": Object.freeze({ - "route.EXAMPLES_UI.navigation": "UI 구성요소", - "route.EXAMPLES_UI.title": "UI 구성요소", - "route.EXAMPLES_STATES.navigation": "화면 상태", - "route.EXAMPLES_STATES.title": "화면 상태", - "route.EXAMPLES_AUTH.navigation": "인증 연동", - "route.EXAMPLES_AUTH.title": "인증 연동", - }), - "en-US": Object.freeze({ - "route.EXAMPLES_UI.navigation": "UI components", - "route.EXAMPLES_UI.title": "UI components", - "route.EXAMPLES_STATES.navigation": "Screen states", - "route.EXAMPLES_STATES.title": "Screen states", - "route.EXAMPLES_AUTH.navigation": "Authentication", - "route.EXAMPLES_AUTH.title": "Authentication", - }), -} as const); diff --git a/src/features/platform-examples-feature/feature-module.ts b/src/features/platform-examples-feature/feature-module.ts deleted file mode 100644 index 7d7b3fc4..00000000 --- a/src/features/platform-examples-feature/feature-module.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { defineFeatureModule } from "../feature-module.ts"; -import { - PLATFORM_EXAMPLES_CONTRACT, - PLATFORM_EXAMPLES_FEATURE_ID, -} from "./contracts/platform-examples-contract.ts"; -import { PLATFORM_EXAMPLES_MESSAGE_CATALOGS } from "./contracts/platform-examples-message-catalog.ts"; - -export const FEATURE_MODULE_ID = - "platform-examples-feature" satisfies typeof PLATFORM_EXAMPLES_FEATURE_ID; -/** Owning bounded context (route root and budget live in its declaration). */ -export const FEATURE_CONTEXT_ID = "platform-examples-context"; - -/** - * 1103/09-04. The template's example screens as a feature, so the product's - * feature selection, `FEATURE_OVERRIDES`, the removal drill and the manual - * accessibility list apply to them like to any feature. Declaration only: - * the pages load with the context routes, and the runtime half is empty. - */ -export const PLATFORM_EXAMPLES_FEATURE_MODULE = defineFeatureModule({ - id: FEATURE_MODULE_ID, - contracts: PLATFORM_EXAMPLES_CONTRACT, - routes: PLATFORM_EXAMPLES_CONTRACT.routes, - messages: PLATFORM_EXAMPLES_MESSAGE_CATALOGS, - loadRuntime: async () => (await import("./feature-runtime.ts")).FEATURE_RUNTIME, -} as const); - -export const FEATURE_MODULE = PLATFORM_EXAMPLES_FEATURE_MODULE; diff --git a/src/features/platform-examples-feature/feature-runtime.ts b/src/features/platform-examples-feature/feature-runtime.ts deleted file mode 100644 index 7ab57e96..00000000 --- a/src/features/platform-examples-feature/feature-runtime.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { defineFeatureRuntime } from "../feature-module.ts"; -import { PLATFORM_EXAMPLES_FEATURE_ID } from "./contracts/platform-examples-contract.ts"; - -/** - * 1103/09-04. The example screens call no feature API: they show the - * design system and the shell's session. The runtime half is empty. - */ -export const FEATURE_RUNTIME = defineFeatureRuntime({ - featureId: PLATFORM_EXAMPLES_FEATURE_ID, - schemas: Object.freeze({}), - adapters: [], - contractContributions: [], -} as const); diff --git a/src/features/platform-examples-feature/presentation/auth-example-page.tsx b/src/features/platform-examples-feature/presentation/auth-example-page.tsx deleted file mode 100644 index b7dcf908..00000000 --- a/src/features/platform-examples-feature/presentation/auth-example-page.tsx +++ /dev/null @@ -1,61 +0,0 @@ -import { PageHeader } from "../../../presentation/design-system/index.ts"; -import { - useSession, - useSessionAction, -} from "../../../presentation/providers/session-provider.tsx"; - -export default function AuthExamplePage() { - const { sessionState } = useSession(); - const { pending, failed, run } = useSessionAction(); - - return ( - // 08-07. Example copy is Korean in every locale (outside the catalog). -
- -
-
-

현재 세션 상태

- - {sessionState} - -
-
- - - -
- {sessionState === "integration-failed" ? ( -

- 외부 인증 소유자가 연결되지 않았습니다. 런타임 호스트의 인증 - 계약을 연결하세요. -

- ) : null} - {failed ?

인증 작업을 완료하지 못했습니다.

: null} -
-
- ); -} diff --git a/src/features/platform-examples-feature/presentation/platform-examples-runtime.ts b/src/features/platform-examples-feature/presentation/platform-examples-runtime.ts deleted file mode 100644 index 36447dd8..00000000 --- a/src/features/platform-examples-feature/presentation/platform-examples-runtime.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { lazy } from "react"; - -/** One lazy chunk per example page, as when they were platform routes. */ -export const PLATFORM_EXAMPLES_ROUTE_RUNTIME = { - EXAMPLES_UI: Object.freeze({ - moduleId: "ui-gallery-page", - Component: lazy(() => import("./ui-gallery-page.tsx")), - }), - EXAMPLES_STATES: Object.freeze({ - moduleId: "state-gallery-page", - Component: lazy(() => import("./state-gallery-page.tsx")), - }), - EXAMPLES_AUTH: Object.freeze({ - moduleId: "auth-example-page", - Component: lazy(() => import("./auth-example-page.tsx")), - }), -} as const; diff --git a/src/features/platform-examples-feature/presentation/state-gallery-page.tsx b/src/features/platform-examples-feature/presentation/state-gallery-page.tsx deleted file mode 100644 index ceec9a9e..00000000 --- a/src/features/platform-examples-feature/presentation/state-gallery-page.tsx +++ /dev/null @@ -1,101 +0,0 @@ -import { useState } from "react"; - -import { deriveAsyncState } from "../../../application/view-models/async-state.ts"; -import { createFailure } from "../../../contracts/errors.ts"; -import { - AsyncSurface, - EmptySurface, - LoadingSurface, - TerminalErrorSurface, - AuthRequiredSurface, - ForbiddenSurface, - NotFoundSurface, - Button, - Card, - PageHeader, -} from "../../../presentation/design-system/index.ts"; - -export default function StateGalleryPage() { - const [lastAction, setLastAction] = useState( - "상태 화면의 작업을 선택하면 결과가 여기에 표시됩니다.", - ); - const refreshingState = deriveAsyncState({ - data: ["기존 데이터"], - isFetching: true, - }); - - return ( - // 08-07. Example copy is Korean in every locale (outside the catalog). -
- - -
-
-

비동기 데이터 상태

-

초기 로딩과 백그라운드 갱신을 구분해 기존 콘텐츠를 보존합니다.

-
-
- - - - - -
기존 콘텐츠는 계속 표시됩니다.
-
-
- - setLastAction("빈 화면 작업을 실행했습니다.")}> - 첫 작업 시작 - - } - /> - - - setLastAction("오류 요청을 다시 시도했습니다.")} - /> - -
-
- -
-
-

접근과 탐색 상태

-

인증 여부와 서버 권한 결과를 서로 다른 상태로 전달합니다.

-
-
- setLastAction("로그인 연동 작업을 시작했습니다.")} - /> - setLastAction("접근 가능한 화면으로 이동합니다.")} - /> - setLastAction("시작 화면으로 이동합니다.")} - /> -
-
- - - {lastAction} - -
- ); -} diff --git a/src/features/reference-feature/README.md b/src/features/reference-feature/README.md deleted file mode 100644 index a966ba79..00000000 --- a/src/features/reference-feature/README.md +++ /dev/null @@ -1,92 +0,0 @@ -# Reference feature ownership and removal - -이 모듈은 제품 도메인이 아니라 새 기능의 수직 경계를 검증하는 제거 가능한 -reference implementation이다. - -## 소유 경계 - -- `domain`: 외부 DTO와 React를 모르는 불변 model -- `application`: UI가 호출하는 list/get/create input과 gateway 계약 -- `adapters`: HTTP executor를 gateway로 투영하는 outbound adapter -- `contracts`: route/API/query contribution, Zod DTO와 request schema, mapper -- `presentation`: route input을 query/form controller로 연결하는 inbound - adapter, 독립 form schema/command mapper와 list/detail/form/status page - -generic application은 비어 있는 `ApplicationFeatureInputs`와 typed -`features.has/get/load` registry만 소유한다. input은 reference route에 처음 -들어갈 때 router가 `features.load`로 실행부를 적재한 뒤에 생긴다. 이 feature의 application API가 module -augmentation으로 `"reference-feature": ReferenceFeatureInput`을 기여하므로 -등록되지 않은 ID와 잘못된 input shape는 typecheck에서 거절된다. feature hook은 -별도 cast나 runtime shape 확인 없이 정확한 input type을 받는다. 다만 동적 호출로 -설치되지 않은 ID가 들어오는 경우를 위해 `get`의 runtime guard도 유지한다. - -예측 가능한 실패는 canonical shared contract인 -`src/contracts/result.ts`의 `Result`로 반환한다. -`src/application/result.ts`는 기존 호출자를 위한 deprecated migration shim일 -뿐 새 코드의 import 경로가 아니다. `AppFailure.kind`는 -`ERROR_REGISTRY` key에서 파생된 닫힌 vocabulary다. 폐기된 별칭 `ApiFailure` -대신 `AppFailure`를 import한다(lint가 막는다). mapper는 `boundary-mapper.ts`의 -`BoundaryMappingResult`를 반환한다. - -HTTP adapter는 `src/adapters/http/feature-http-binding.ts`의 capability-specific -typed binding을 사용한다. feature는 operation ID, route ID, request type, 성공 -value type, mapper만 소유한다. timeout/cancellation/auth/transport/contract -violation을 `AppFailure`로 정규화하는 책임은 reusable HTTP capability가 소유한다. -따라서 gateway 메서드는 transport outcome이나 runtime result guard를 반복 구현하지 -않고도 정확한 결과 타입을 반환한다. - -route codec과 URL builder는 `src/presentation/routes/route-codecs.ts`, route type은 -`route-contract.ts`, React context/provider/hook은 `route-input.tsx`가 각각 -소유한다. reference page는 `app-router.tsx`를 역참조하지 않고 좁은 -`useRouteInput` 경계만 사용하므로 lazy route와 router 사이의 순환 의존을 만들지 -않는다. page는 HTTP client, storage, auth owner, output port나 TanStack API를 -직접 import하지 않는다. - -page는 경로 문자열을 적지 않는다. 경로는 계약의 `path` 한 곳에만 있다. -`presentation/reference-routes.ts`가 다음 helper를 둔다. 이 기능의 route codec은 -`presentation/reference-route-codecs.ts`에 있다. - -- 링크: `referenceRouteUrl(routeId, { params, search })`. 위 `buildRouteUrl`에 - 이 기능의 codec을 넘긴다. -- route 입력: `useReferenceListFilters()`, `useReferenceResourceId()`. 이미 - 통과한 codec으로 다시 읽어 cast 없이 타입을 얻는다. - -## 설치 지점 - -feature가 실제 contribution을 소유한다. - -- 선언(초기 청크, `feature-module.ts`): route 표와 invalidation은 - `reference-feature-contract.ts`, 문구는 `reference-message-catalog.ts` -- 실행부(`feature-runtime.ts`, reference route에 들어갈 때 적재): 스키마 메타데이터 - `reference-schema-metadata.ts`, bootstrap input - `REFERENCE_FEATURE_ADAPTER_CONTRIBUTION`, HTTP contract contribution -- route codec과 page component: `REFERENCE_FEATURE_ROUTE_CODECS`, - `REFERENCE_FEATURE_ROUTE_RUNTIME` (`context-routes.ts`가 route handle에 실어 - lazy로 적재) - -`feature-module.ts`는 `feature-runtime.ts`를 동적 import로만 가리킨다. 정적 -import로 바꾸면 실행부 전체가 다시 초기 청크에 들어간다(15-01). 중앙 파일인 -`installed-feature-contracts.ts`, `installed-feature-adapters.ts`, -`installed-contract-contributions.ts`는 선택된 contribution을 합치는 역할만 -한다. 새 기능의 내부 조립 규칙을 중앙 catalog에 추가하지 않는다. - -## 검증과 제거 - -```sh -corepack pnpm test:reference-feature -corepack pnpm test:sample-removal -``` - -첫 명령은 URL filter와 query key/HTTP request의 동일성, schema/mapper, 모든 -query/mutation/form 상태와 production composition을 검증한다. 두 번째 명령은 임시 -복제본에서 이 source/test 디렉터리를 제거하고 installed catalog를 빈 목록으로 -재생성한다. feature 소유 coverage include, risk-policy 행과 test-evidence -contribution도 제거한 뒤 typecheck, architecture, registry, unit/integration, -coverage, source evidence, home smoke, production build와 source/built fixture ID -잔여 0개를 검사한다. generic feature registry의 성공 경로는 reference와 무관한 -unit test가 소유하므로 feature 삭제 후에도 공통 boundary coverage가 유지된다. - -CI의 negative type fixture는 잘못된 feature ID/input shape, registry에 없는 -failure kind, operation과 route ID의 불일치가 실제로 컴파일 실패하는지도 -검증한다. Architecture fixture는 허용 edge뿐 아니라 unresolved import, 금지 계층 -edge와 TypeScript 순환 의존을 각각 거절해야 통과한다. diff --git a/src/features/reference-feature/adapters/create-reference-feature-input.ts b/src/features/reference-feature/adapters/create-reference-feature-input.ts deleted file mode 100644 index 86621440..00000000 --- a/src/features/reference-feature/adapters/create-reference-feature-input.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { - createFeatureHttpBinding, - type InstalledHttpOperationExecutor, -} from "../../../adapters/http/index.ts"; -import { - defineFeatureAdapterContribution, -} from "../../feature-adapter-contribution.ts"; -import { createReferenceFeatureInput } from "../application/reference-feature-api.ts"; -import type { TelemetryPort } from "../../../platform/telemetry/telemetry-port.ts"; -import { - REFERENCE_FEATURE_ID, -} from "../contracts/reference-feature-contract.ts"; -import { - createReferenceHttpGateway, - REFERENCE_HTTP_OPERATIONS, -} from "./reference-http-gateway.ts"; - -export type InstalledContractOperationExecutor = - InstalledHttpOperationExecutor; - -/** - * Feature-owned composition seam. - * - * The feature receives only the HTTP capability it declares in `needs`. - * HTTP lifecycle/error normalization stays in the reusable capability binding. - */ -export function createReferenceFeatureInstalledInput(context: Readonly<{ - http: InstalledHttpOperationExecutor; - telemetry?: TelemetryPort; -}>) { - const http = createFeatureHttpBinding( - context.http, - REFERENCE_HTTP_OPERATIONS, - ); - - return Object.freeze({ - featureId: REFERENCE_FEATURE_ID, - input: createReferenceFeatureInput( - createReferenceHttpGateway(http), - context.telemetry === undefined ? {} : { telemetry: context.telemetry }, - ), - }); -} - -export const REFERENCE_FEATURE_ADAPTER_CONTRIBUTION = - defineFeatureAdapterContribution({ - featureId: REFERENCE_FEATURE_ID, - needs: ["http", "telemetry"] as const, - createInput: createReferenceFeatureInstalledInput, - }); diff --git a/src/features/reference-feature/adapters/reference-http-gateway.ts b/src/features/reference-feature/adapters/reference-http-gateway.ts deleted file mode 100644 index 152be19c..00000000 --- a/src/features/reference-feature/adapters/reference-http-gateway.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { - defineFeatureHttpOperationForRoutes, - type FeatureHttpBinding, -} from "../../../adapters/http/index.ts"; -import { - CREATE_REFERENCE_RESOURCE_CONTRACT, - GET_REFERENCE_RESOURCE_CONTRACT, - LIST_REFERENCE_RESOURCES_CONTRACT, -} from "../contracts/reference-feature-contract-contribution.ts"; -import { - REFERENCE_FEATURE_CONTRACT, -} from "../contracts/reference-feature-contract.ts"; -import { - mapReferenceResourceListPayload, - mapReferenceResourcePayload, -} from "../contracts/reference-mapper.ts"; -import type { - ReferenceGateway, -} from "../application/reference-feature-api.ts"; - -export type ReferenceFeatureRouteId = - keyof typeof REFERENCE_FEATURE_CONTRACT.routes; - -const defineReferenceHttpOperation = - defineFeatureHttpOperationForRoutes(); - -export const REFERENCE_HTTP_OPERATIONS = Object.freeze({ - LIST_REFERENCE_RESOURCES: defineReferenceHttpOperation({ - contract: LIST_REFERENCE_RESOURCES_CONTRACT, - routeId: "REFERENCE_RESOURCE_LIST", - mapSuccess: mapReferenceResourceListPayload, - }), - CREATE_REFERENCE_RESOURCE: defineReferenceHttpOperation({ - contract: CREATE_REFERENCE_RESOURCE_CONTRACT, - routeId: "REFERENCE_RESOURCE_LIST", - mapSuccess: mapReferenceResourcePayload, - mapProblem(problem, metadata) { - if (metadata.status === 409) { - return Object.freeze({ - kind: "CONFLICT" as const, - code: problem.code ?? "REFERENCE_RESOURCE_CONFLICT", - }); - } - // 백엔드 1101/02-01. The paired backend's answer to a key outside its - // rule. The executor checked the key before sending, so this names a - // rule mismatch between the two sides: keep the code for diagnostics. - if (metadata.status === 400 && problem.code === "IDEMPOTENCY_KEY_INVALID") { - return Object.freeze({ - kind: "UNKNOWN_CLIENT_FAILURE" as const, - code: problem.code, - }); - } - if (metadata.status === 422) { - return Object.freeze({ - kind: "VALIDATION_REJECTED" as const, - code: problem.code ?? "REFERENCE_RESOURCE_REJECTED", - validationIssues: problem.issues ?? [], - }); - } - return undefined; - }, - }), - GET_REFERENCE_RESOURCE: defineReferenceHttpOperation({ - contract: GET_REFERENCE_RESOURCE_CONTRACT, - routeId: "REFERENCE_RESOURCE_DETAIL", - mapSuccess: mapReferenceResourcePayload, - }), -} as const); - -export type ReferenceHttpBinding = FeatureHttpBinding< - typeof REFERENCE_HTTP_OPERATIONS ->; - -export function createReferenceHttpGateway( - http: ReferenceHttpBinding, -): ReferenceGateway { - return Object.freeze({ - list(filters, context) { - return http.execute("LIST_REFERENCE_RESOURCES", filters, context); - }, - create(command, context) { - return http.execute("CREATE_REFERENCE_RESOURCE", command, context); - }, - get(resourceId, context) { - return http.execute( - "GET_REFERENCE_RESOURCE", - Object.freeze({ resourceId }), - context, - ); - }, - }); -} diff --git a/src/features/reference-feature/application/reference-error.ts b/src/features/reference-feature/application/reference-error.ts deleted file mode 100644 index 0ac57401..00000000 --- a/src/features/reference-feature/application/reference-error.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { - defineAppError, - type AppError, -} from "../../../platform/errors/app-error.ts"; -import type { AppFailure } from "../../../contracts/errors.ts"; - -/** - * scale-architecture.md §17–§19. The reference feature's own domain errors. - * - * This union is local to the feature. It satisfies the platform `AppError` - * envelope structurally; nothing central enumerates it, so adding or removing - * this feature never edits a shared error type. - */ -export type ReferenceError = - | (AppError & { - readonly kind: "reference.not-found"; - readonly category: "domain"; - readonly severity: "warning"; - readonly retryability: "never"; - }) - | (AppError & { - readonly kind: "reference.conflict"; - readonly category: "domain"; - readonly severity: "warning"; - readonly retryability: "never"; - }) - | (AppError & { - readonly kind: "reference.rejected"; - readonly category: "validation"; - readonly severity: "warning"; - readonly retryability: "never"; - }); - -export const REFERENCE_ERRORS = Object.freeze({ - NOT_FOUND: defineAppError({ - kind: "reference.not-found", - category: "domain", - severity: "warning", - retryability: "never", - }), - CONFLICT: defineAppError({ - kind: "reference.conflict", - category: "domain", - severity: "warning", - retryability: "never", - }), - REJECTED: defineAppError({ - kind: "reference.rejected", - category: "validation", - severity: "warning", - retryability: "never", - }), -} satisfies Record); - -/** - * Interprets a transport-normalized failure in this feature's own vocabulary. - * Anything that is not a reference domain outcome stays `null`: the platform - * error mapping, not this feature, owns transport/contract failures. - */ -export function toReferenceError(failure: AppFailure): ReferenceError | null { - switch (failure.kind) { - case "NOT_FOUND": - return REFERENCE_ERRORS.NOT_FOUND; - case "CONFLICT": - return REFERENCE_ERRORS.CONFLICT; - case "VALIDATION_REJECTED": - return REFERENCE_ERRORS.REJECTED; - default: - return null; - } -} diff --git a/src/features/reference-feature/application/reference-feature-api.ts b/src/features/reference-feature/application/reference-feature-api.ts deleted file mode 100644 index c896b71e..00000000 --- a/src/features/reference-feature/application/reference-feature-api.ts +++ /dev/null @@ -1,137 +0,0 @@ -import type { Result } from "../../../contracts/result.ts"; -import type {} from "../../../application/ports/in/application-api.ts"; -import { - toReferenceView, - type ReferenceResourceView, -} from "../contracts/reference-mapper.ts"; -import type { ReferenceResource } from "../domain/reference-resource.ts"; -import type { MutationIntent } from "../../../contracts/mutation-intent.ts"; -import type { ExecutionContext } from "../../../platform/execution/execution-context.ts"; -import type { TelemetryPort } from "../../../platform/telemetry/telemetry-port.ts"; -import type { AppFailure } from "../../../contracts/errors.ts"; -import { REFERENCE_FEATURE_ID } from "../contracts/reference-feature-contract.ts"; - -/** - * scale-architecture.md §10. Every call may join a caller-owned interaction so several - * operations share one request/retry/concurrency budget and one deadline. - */ -export type ReferenceCallContext = Readonly<{ - signal?: AbortSignal; - execution?: ExecutionContext; -}>; - -export type ReferenceListFilters = Readonly<{ - cursor?: string; - limit: number; - tags?: readonly string[]; -}>; - -export type ReferenceResult = Result; - -export type ReferenceCreateCommand = Readonly<{ - name: string; - note?: string; -}>; - -export type ReferenceFeatureInput = Readonly<{ - listResources( - filters: ReferenceListFilters, - context?: ReferenceCallContext, - ): Promise>; - createResource( - command: ReferenceCreateCommand, - context?: ReferenceCallContext & Readonly<{ intent?: MutationIntent }>, - ): Promise>; - getResource( - resourceId: string, - context?: ReferenceCallContext, - ): Promise>; -}>; - -declare module "../../../application/ports/in/application-api.ts" { - interface ApplicationFeatureInputs { - "reference-feature": ReferenceFeatureInput; - } -} - -export type ReferenceGateway = Readonly<{ - list( - filters: ReferenceListFilters, - context?: ReferenceCallContext, - ): Promise>; - create( - command: ReferenceCreateCommand, - context?: ReferenceCallContext & Readonly<{ intent?: MutationIntent }>, - ): Promise>; - get( - resourceId: string, - context?: ReferenceCallContext, - ): Promise>; -}>; - -/** - * scale-architecture.md §24. Feature-owned telemetry payload. The platform envelope carries it; - * no central union lists it. Only the bounded failure kind leaves the feature. - */ -export type ReferenceLoadFailedPayload = Readonly<{ - operation: "list" | "detail"; - reason: AppFailure["kind"]; -}>; - -function reportLoadFailure( - telemetry: TelemetryPort | undefined, - operation: ReferenceLoadFailedPayload["operation"], - failure: AppFailure, - context: ReferenceCallContext | undefined, -): void { - if (!telemetry || failure.kind === "REQUEST_ABORTED") return; - const payload: ReferenceLoadFailedPayload = { operation, reason: failure.kind }; - try { - // Fire-and-forget: telemetry never changes the business result. - void Promise.resolve( - telemetry.emit({ - kind: "reference.load.failed", - severity: "warning", - featureId: REFERENCE_FEATURE_ID, - ...(context?.execution === undefined - ? {} - : { interactionId: context.execution.interaction.id }), - payload, - }), - ).catch(() => undefined); - } catch { - // A throwing port is contained at the call site (scale-architecture.md §26). - } -} - -export function createReferenceFeatureInput( - gateway: ReferenceGateway, - observability: Readonly<{ telemetry?: TelemetryPort }> = {}, -): ReferenceFeatureInput { - const { telemetry } = observability; - return Object.freeze({ - async listResources(filters, context) { - const result = await gateway.list(filters, context); - if (!result.ok) reportLoadFailure(telemetry, "list", result.error, context); - return result.ok - ? { - ok: true as const, - value: result.value.map((resource) => toReferenceView(resource)), - } - : result; - }, - async createResource(command, context) { - const result = await gateway.create(command, context); - return result.ok - ? { ok: true as const, value: toReferenceView(result.value) } - : result; - }, - async getResource(resourceId, context) { - const result = await gateway.get(resourceId, context); - if (!result.ok) reportLoadFailure(telemetry, "detail", result.error, context); - return result.ok - ? { ok: true as const, value: toReferenceView(result.value) } - : result; - }, - }); -} diff --git a/src/features/reference-feature/context-routes.ts b/src/features/reference-feature/context-routes.ts deleted file mode 100644 index d5a214df..00000000 --- a/src/features/reference-feature/context-routes.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { RouteObject } from "react-router-dom"; - -import { REFERENCE_FEATURE_CONTRACT } from "./contracts/reference-feature-contract.ts"; -import { REFERENCE_FEATURE_ROUTE_RUNTIME } from "./presentation/reference-feature-runtime.ts"; -import { REFERENCE_FEATURE_ROUTE_CODECS } from "./presentation/reference-route-codecs.ts"; - -export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze( - Object.values(REFERENCE_FEATURE_CONTRACT.routes).map((definition) => { - const runtime = REFERENCE_FEATURE_ROUTE_RUNTIME[ - definition.routeId as keyof typeof REFERENCE_FEATURE_ROUTE_RUNTIME - ]; - return Object.freeze({ - id: definition.routeId, - path: definition.path, - handle: Object.freeze({ - routeId: definition.routeId, - runtime, - // 15-01. The route's params/search codecs load with its routes. - codecs: REFERENCE_FEATURE_ROUTE_CODECS, - }), - }); - }), -); diff --git a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts deleted file mode 100644 index 08ada1ca..00000000 --- a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts +++ /dev/null @@ -1,252 +0,0 @@ -import { z } from "../../../contracts/zod.ts"; - -import type { - CommandEffectDescriptor, - InstalledContractContribution, - InstalledHttpContract, -} from "../../../contracts/external-contract-runtime.ts"; -import { zodValidator } from "../../../contracts/zod-validator.ts"; -import { REFERENCE_FEATURE_ID } from "./reference-feature-contract.ts"; -import { - createReferenceResourceCommandSchema, - referenceProblemSchema, - referenceResourceDtoSchema, - referenceResourceListQuerySchema, - referenceResourceParamsSchema, - type ReferenceProblem, -} from "./reference-schemas.ts"; - -export type { ReferenceProblem } from "./reference-schemas.ts"; - -/** - * §4.8. The single `TEMPLATE_FIXTURE` contribution. It keeps the reference - * HTTP vertical executable as deterministic template data and is excluded from - * `contractSet`. A product feature MUST instead pin an external package and - * import it from its own `contracts/-contract-contribution.ts`. - */ - -const PROBLEM_VALIDATOR = zodValidator( - "ReferenceProblem", - referenceProblemSchema, -); - -/** - * 0929/03-01. A 409 does not by itself mean "refused": a resend with the same - * key can meet the first attempt still running (the paired backend answers - * `409 IDEMPOTENT_IN_FLIGHT`). Only the conflict codes this fixture declares - * are `NOT_APPLIED`; any other 409 stays `MAYBE_APPLIED`, so the coordinator - * keeps the intent and the next send reuses the key. Answering `NOT_APPLIED` - * there would let the next save mint a new key and create the resource twice. - */ -const CREATE_NOT_APPLIED_CONFLICT_CODES: ReadonlySet = new Set([ - "CONFLICT", -]); - -/** - * Fixture-side classifier standing in for the package-provided pure bounded - * classifier. A status the fixture does not describe stays `MAYBE_APPLIED`. - */ -const CREATE_EFFECT: CommandEffectDescriptor = Object.freeze({ - successEffect: "APPLIED_CONFIRMED" as const, - classifyProblem({ - status, - problem, - }: Readonly<{ status: number; problem: ReferenceProblem }>) { - if (status === 400 || status === 422) return "NOT_APPLIED"; - if ( - status === 409 && - problem.code !== undefined && - CREATE_NOT_APPLIED_CONFLICT_CODES.has(problem.code) - ) { - return "NOT_APPLIED"; - } - return "MAYBE_APPLIED"; - }, - /** - * D-2. The reference backend rejects an unauthenticated, forbidden or - * rate-limited create before touching state. - */ - classifyStatus: () => "NOT_APPLIED" as const, -}); - -export const LIST_REFERENCE_RESOURCES_CONTRACT = Object.freeze({ - contract: Object.freeze({ - operationId: "LIST_REFERENCE_RESOURCES", - method: "GET" as const, - pathTemplate: "/api/reference-resources", - inputValidator: zodValidator( - "ReferenceResourceListQuery", - referenceResourceListQuerySchema, - ), - outputValidator: zodValidator( - "ReferenceResourceListPayload", - z.array(referenceResourceDtoSchema).max(100), - ), - problemValidator: PROBLEM_VALIDATOR, - acceptedStatuses: Object.freeze([200]), - emptyBodyStatuses: Object.freeze([]), - retrySemantics: "SAFE" as const, - requestBody: "NONE" as const, - responseBody: "REQUIRED_JSON" as const, - responseEnvelope: "NONE" as const, - commandRecovery: null, - commandEffect: null, - projectRequest(input: z.output) { - const entries: (readonly [string, string])[] = []; - if (input.cursor !== undefined) entries.push(["cursor", input.cursor]); - entries.push(["limit", String(input.limit)]); - for (const tag of input.tags ?? []) entries.push(["tags", tag]); - return Object.freeze({ - pathValues: Object.freeze({}), - queryEntries: Object.freeze(entries), - body: null, - }); - }, - }), - frontend: Object.freeze({ - policyId: "REFERENCE_LIST_V1", - requestByteLimit: 0, - responseByteLimit: 262_144, - totalDeadlineMs: 10_000, - retryBudget: 2 as const, - authProfileId: "EXTERNAL_BEARER", - diagnosticsOperation: "reference.list", - traffic: Object.freeze({ - maxPhysicalRequests: 3, - maxRetries: 2, - maxConcurrentRequests: 1, - maxQueuedRequests: 0, - }), - }), -}) satisfies InstalledHttpContract< - z.output, - readonly z.output[], - ReferenceProblem ->; - -export const GET_REFERENCE_RESOURCE_CONTRACT = Object.freeze({ - contract: Object.freeze({ - operationId: "GET_REFERENCE_RESOURCE", - method: "GET" as const, - pathTemplate: "/api/reference-resources/{resourceId}", - inputValidator: zodValidator( - "ReferenceResourceParams", - referenceResourceParamsSchema, - ), - outputValidator: zodValidator( - "ReferenceResourcePayload", - referenceResourceDtoSchema, - ), - problemValidator: PROBLEM_VALIDATOR, - acceptedStatuses: Object.freeze([200]), - emptyBodyStatuses: Object.freeze([]), - retrySemantics: "SAFE" as const, - requestBody: "NONE" as const, - responseBody: "REQUIRED_JSON" as const, - responseEnvelope: "NONE" as const, - commandRecovery: null, - commandEffect: null, - projectRequest(input: z.output) { - return Object.freeze({ - pathValues: Object.freeze({ resourceId: input.resourceId }), - queryEntries: Object.freeze([]), - body: null, - }); - }, - }), - frontend: Object.freeze({ - policyId: "REFERENCE_DETAIL_V1", - requestByteLimit: 0, - responseByteLimit: 32_768, - totalDeadlineMs: 10_000, - retryBudget: 2 as const, - authProfileId: "EXTERNAL_BEARER", - diagnosticsOperation: "reference.detail", - traffic: Object.freeze({ - maxPhysicalRequests: 3, - maxRetries: 2, - maxConcurrentRequests: 1, - maxQueuedRequests: 0, - }), - }), -}) satisfies InstalledHttpContract< - z.output, - z.output, - ReferenceProblem ->; - -export const CREATE_REFERENCE_RESOURCE_CONTRACT = Object.freeze({ - contract: Object.freeze({ - operationId: "CREATE_REFERENCE_RESOURCE", - method: "POST" as const, - pathTemplate: "/api/reference-resources", - inputValidator: zodValidator( - "CreateReferenceResourceCommand", - createReferenceResourceCommandSchema, - ), - outputValidator: zodValidator( - "ReferenceResourcePayload", - referenceResourceDtoSchema, - ), - problemValidator: PROBLEM_VALIDATOR, - acceptedStatuses: Object.freeze([200, 201]), - emptyBodyStatuses: Object.freeze([]), - retrySemantics: "KEYED" as const, - requestBody: "JSON" as const, - responseBody: "REQUIRED_JSON" as const, - responseEnvelope: "NONE" as const, - commandRecovery: Object.freeze({ - mode: "IDEMPOTENCY_REPLAY" as const, - operationIdentityField: "idempotencyKey", - }), - commandEffect: CREATE_EFFECT, - projectRequest(input: z.output) { - return Object.freeze({ - pathValues: Object.freeze({}), - queryEntries: Object.freeze([]), - body: Object.freeze({ ...input }), - }); - }, - }), - frontend: Object.freeze({ - policyId: "REFERENCE_CREATE_V1", - requestByteLimit: 32_768, - responseByteLimit: 32_768, - totalDeadlineMs: 10_000, - /** - * §8.3. A KEYED command has no automatic retry after a dispatched attempt - * lost its response; the fixture therefore declares a zero budget rather - * than relying on a runtime special case. - */ - retryBudget: 0 as const, - authProfileId: "EXTERNAL_BEARER", - diagnosticsOperation: "reference.create", - traffic: Object.freeze({ - maxPhysicalRequests: 1, - maxRetries: 0, - maxConcurrentRequests: 1, - maxQueuedRequests: 0, - }), - }), -}) satisfies InstalledHttpContract< - z.output, - z.output, - ReferenceProblem ->; - -export const REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION: InstalledContractContribution = - Object.freeze({ - contributionId: "reference-feature-http-v1", - featureId: REFERENCE_FEATURE_ID, - source: Object.freeze({ - kind: "TEMPLATE_FIXTURE" as const, - fixtureId: "REFERENCE_FEATURE_V1" as const, - revision: 1 as const, - }), - http: Object.freeze([ - LIST_REFERENCE_RESOURCES_CONTRACT, - GET_REFERENCE_RESOURCE_CONTRACT, - CREATE_REFERENCE_RESOURCE_CONTRACT, - ]) as readonly InstalledHttpContract[], - events: Object.freeze([]), - }); diff --git a/src/features/reference-feature/contracts/reference-feature-contract.ts b/src/features/reference-feature/contracts/reference-feature-contract.ts deleted file mode 100644 index c9d91d45..00000000 --- a/src/features/reference-feature/contracts/reference-feature-contract.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { defineQueryNamespaceIdentity } from "../../../contracts/query-keys.ts"; -import { defineQueryInvalidationTopic } from "../../../contracts/query-invalidation.ts"; - -export const REFERENCE_FEATURE_ID = "reference-feature"; -export const REFERENCE_RESOURCE_QUERY_NAMESPACE = defineQueryNamespaceIdentity( - "reference-resource", - 1, -); -export const REFERENCE_RESOURCE_INVALIDATION_TOPIC = - defineQueryInvalidationTopic("qinv.01k10f7m3w9p6r2c8v5n4x"); - -/** - * 15-01. The declaration half: what the shell reads before a reference route - * is entered. It is in the initial chunk, so it holds data only. The schema - * metadata is `reference-schema-metadata.ts` and the HTTP operations are - * `reference-feature-contract-contribution.ts`, both loaded with - * `feature-runtime.ts`. - */ -export const REFERENCE_FEATURE_CONTRACT = Object.freeze({ - featureId: REFERENCE_FEATURE_ID, - routes: Object.freeze({ - REFERENCE_RESOURCE_LIST: Object.freeze({ - routeId: "REFERENCE_RESOURCE_LIST", - path: "/examples/reference-resources", - paramsSchema: null, - searchSchema: "ReferenceResourceListQuery", - access: "session-required", - loadingSurface: "reference-resource-list", - errorSurface: "feature-boundary", - chunkId: "route-reference-resources", - title: "Reference feature", - navigationLabel: "Reference feature", - navigationOrder: 50, - }), - REFERENCE_RESOURCE_DETAIL: Object.freeze({ - routeId: "REFERENCE_RESOURCE_DETAIL", - // 08-13. `items/` keeps an id such as `new` or `status` off the static routes. - path: "/examples/reference-resources/items/:resourceId", - paramsSchema: "ReferenceResourceParams", - searchSchema: null, - access: "session-required", - loadingSurface: "reference-resource-detail", - errorSurface: "feature-boundary", - chunkId: "route-reference-resource-detail", - title: "Reference detail", - navigationLabel: null, - navigationOrder: null, - }), - REFERENCE_RESOURCE_FORM: Object.freeze({ - routeId: "REFERENCE_RESOURCE_FORM", - path: "/examples/reference-resources/new", - paramsSchema: null, - searchSchema: null, - access: "session-required", - loadingSurface: "reference-resource-form", - errorSurface: "feature-boundary", - chunkId: "route-reference-resource-form", - title: "Reference form", - navigationLabel: null, - navigationOrder: null, - }), - REFERENCE_RESOURCE_STATUS: Object.freeze({ - routeId: "REFERENCE_RESOURCE_STATUS", - path: "/examples/reference-resources/status", - paramsSchema: null, - searchSchema: null, - access: "session-required", - loadingSurface: "reference-resource-status", - errorSurface: "feature-boundary", - chunkId: "route-reference-resource-status", - title: "Reference status", - navigationLabel: null, - navigationOrder: null, - }), - }), - routeRuntimeContracts: Object.freeze({ - REFERENCE_RESOURCE_LIST: Object.freeze({ - routeId: "REFERENCE_RESOURCE_LIST", - moduleId: "reference-resource-page", - paramsCodec: "none", - searchCodec: "ReferenceResourceListQuery", - }), - REFERENCE_RESOURCE_DETAIL: Object.freeze({ - routeId: "REFERENCE_RESOURCE_DETAIL", - moduleId: "reference-resource-detail-page", - paramsCodec: "ReferenceResourceParams", - searchCodec: "none", - }), - REFERENCE_RESOURCE_FORM: Object.freeze({ - routeId: "REFERENCE_RESOURCE_FORM", - moduleId: "reference-resource-form-page", - paramsCodec: "none", - searchCodec: "none", - }), - REFERENCE_RESOURCE_STATUS: Object.freeze({ - routeId: "REFERENCE_RESOURCE_STATUS", - moduleId: "reference-resource-status-page", - paramsCodec: "none", - searchCodec: "none", - }), - }), - invalidation: Object.freeze({ - topics: Object.freeze([REFERENCE_RESOURCE_INVALIDATION_TOPIC]), - namespaces: Object.freeze([REFERENCE_RESOURCE_QUERY_NAMESPACE]), - edges: Object.freeze([ - Object.freeze({ - topicId: REFERENCE_RESOURCE_INVALIDATION_TOPIC, - namespace: REFERENCE_RESOURCE_QUERY_NAMESPACE, - }), - ]), - }), - topicVersions: Object.freeze([ - Object.freeze({ - topicId: REFERENCE_RESOURCE_INVALIDATION_TOPIC, - topicVersion: 1, - }), - ]), - // TEMPLATE_FIXTURE contributions are not part of the contract set. - contractPackages: Object.freeze([]), -} as const); diff --git a/src/features/reference-feature/contracts/reference-mapper.ts b/src/features/reference-feature/contracts/reference-mapper.ts deleted file mode 100644 index 2527468c..00000000 --- a/src/features/reference-feature/contracts/reference-mapper.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { - createReferenceResource, - type ReferenceResource, -} from "../domain/reference-resource.ts"; -import { - mappingFailure, - mappingSuccess, - type BoundaryMappingResult, -} from "../../../contracts/boundary-mapper.ts"; -import type { ReferenceResourceDto } from "./reference-schemas.ts"; - -export type ReferenceResourceView = Readonly<{ - resourceId: string; - title: string; - createdAt: string | null; - optimistic?: boolean; -}>; - -/** - * Operation-specific mapper. The HTTP contract has already validated the wire - * shape, so this mapper owns only wire -> domain construction. - */ -export function mapReferenceResourcePayload( - dto: ReferenceResourceDto, -): BoundaryMappingResult { - try { - return mappingSuccess( - createReferenceResource({ - id: dto.id, - displayName: dto.name, - createdAt: dto.createdAt ?? null, - }), - ); - } catch { - return mappingFailure("MAPPING_INVARIANT_REJECTED"); - } -} - -export function mapReferenceResourceListPayload( - payload: readonly ReferenceResourceDto[], -): BoundaryMappingResult { - const output: ReferenceResource[] = []; - for (const item of payload) { - const mapped = mapReferenceResourcePayload(item); - if (!mapped.ok) return mapped; - output.push(mapped.value); - } - return mappingSuccess(Object.freeze(output)); -} - -export function toReferenceView( - resource: ReferenceResource, -): ReferenceResourceView { - return Object.freeze({ - resourceId: resource.id, - title: resource.displayName, - createdAt: resource.createdAt, - }); -} diff --git a/src/features/reference-feature/contracts/reference-message-catalog.ts b/src/features/reference-feature/contracts/reference-message-catalog.ts deleted file mode 100644 index d96be057..00000000 --- a/src/features/reference-feature/contracts/reference-message-catalog.ts +++ /dev/null @@ -1,112 +0,0 @@ -export const REFERENCE_MESSAGE_CATALOGS = Object.freeze({ - "ko-KR": Object.freeze({ - "route.REFERENCE_RESOURCE_LIST.navigation": "Reference feature", - "route.REFERENCE_RESOURCE_LIST.title": "Reference resources", - "route.REFERENCE_RESOURCE_DETAIL.navigation": "Reference detail", - "route.REFERENCE_RESOURCE_DETAIL.title": "Reference resource detail", - "route.REFERENCE_RESOURCE_FORM.navigation": "Reference form", - "route.REFERENCE_RESOURCE_FORM.title": "Create reference resource", - "route.REFERENCE_RESOURCE_STATUS.navigation": "Reference status", - "route.REFERENCE_RESOURCE_STATUS.title": "Reference resource status", - "reference.list.eyebrow": "제거 가능한 수직 슬라이스", - "reference.list.description": - "URL codec, application input, HTTP/schema/mapper와 query 상태를 한 경로로 검증합니다.", - "reference.list.create": "새 항목 만들기", - "reference.list.refresh": "새로고침", - "reference.list.resultCount": "총 {count}개 항목", - "reference.list.title": "참조 기능", - "reference.list.filterLimit": "최대 {limit}개", - "reference.list.filterTags": "태그 {tags}", - "reference.list.resources": "참조 리소스 목록", - "reference.form.back": "목록으로 돌아가기", - "reference.form.eyebrow": "폼 페이지", - "reference.form.title": "Reference resource 만들기", - "reference.form.description": - "presentation schema, command mapper, 422/conflict와 dirty navigation 정책을 실행합니다.", - "reference.form.name": "새 항목 이름", - "reference.form.nameDescription": - "앞뒤 공백은 command mapper 전에 제거됩니다.", - "reference.form.note": "설명", - "reference.form.noteDescription": - "선택 입력이며 비어 있으면 command에 포함되지 않습니다.", - "reference.form.cancel": "취소", - "reference.form.save": "저장", - "reference.form.saving": "저장 중…", - "reference.form.reset": "초기화", - "reference.form.reloadList": "목록을 새로 불러와 확인", - "reference.form.saved": "저장했습니다.", - "reference.form.conflict": "충돌을 해결한 뒤 다시 제출할 수 있습니다.", - "reference.form.privacy": - "form value는 URL, storage, telemetry에 저장되지 않고 submit 시에만 application command로 변환됩니다.", - "reference.detail.eyebrow": "상세 페이지", - "reference.detail.titlePending": "참조 상세", - "reference.detail.resourceId": "리소스 ID", - "reference.detail.createdAt": "생성 시각", - "reference.detail.description": - "route param과 detail query의 reset 경계를 확인합니다.", - "reference.detail.summaryPending": "요약 정보를 준비하고 있습니다.", - "reference.detail.sectionSlot": - "이 영역에는 제품별 상세 section을 조립할 수 있습니다.", - "reference.detail.aside": "상세 페이지의 관련 정보 slot입니다.", - "reference.status.eyebrow": "상태 페이지 · 점검", - "reference.status.title": "잠시 사용할 수 없습니다.", - "reference.status.description": - "도메인 데이터나 raw 오류를 노출하지 않는 중립적인 상태 페이지 예시입니다.", - "reference.status.back": "목록으로 이동", - }), - "en-US": Object.freeze({ - "route.REFERENCE_RESOURCE_LIST.navigation": "Reference feature", - "route.REFERENCE_RESOURCE_LIST.title": "Reference resources", - "route.REFERENCE_RESOURCE_DETAIL.navigation": "Reference detail", - "route.REFERENCE_RESOURCE_DETAIL.title": "Reference resource detail", - "route.REFERENCE_RESOURCE_FORM.navigation": "Reference form", - "route.REFERENCE_RESOURCE_FORM.title": "Create reference resource", - "route.REFERENCE_RESOURCE_STATUS.navigation": "Reference status", - "route.REFERENCE_RESOURCE_STATUS.title": "Reference resource status", - "reference.list.eyebrow": "Removable vertical slice", - "reference.list.description": - "Checks the URL codec, application input, HTTP/schema/mapper and query state along one path.", - "reference.list.create": "Create item", - "reference.list.refresh": "Refresh", - "reference.list.resultCount": "Total items: {count}", - "reference.list.title": "Reference feature", - "reference.list.filterLimit": "limit {limit}", - "reference.list.filterTags": "tags {tags}", - "reference.list.resources": "Reference resources", - "reference.form.back": "Back to the list", - "reference.form.eyebrow": "FormPage", - "reference.form.title": "Create a reference resource", - "reference.form.description": - "Runs the presentation schema, command mapper, 422/conflict and dirty navigation policies.", - "reference.form.name": "New item name", - "reference.form.nameDescription": - "Leading and trailing spaces are removed before the command mapper.", - "reference.form.note": "Description", - "reference.form.noteDescription": - "Optional. An empty value is left out of the command.", - "reference.form.cancel": "Cancel", - "reference.form.save": "Save", - "reference.form.saving": "Saving…", - "reference.form.reset": "Reset", - "reference.form.reloadList": "Reload the list to check", - "reference.form.saved": "Saved.", - "reference.form.conflict": "Resolve the conflict, then submit again.", - "reference.form.privacy": - "Form values are never written to the URL, storage or telemetry; they become an application command only on submit.", - "reference.detail.eyebrow": "DetailPage", - "reference.detail.titlePending": "Reference detail", - "reference.detail.resourceId": "Resource ID", - "reference.detail.createdAt": "Created", - "reference.detail.description": - "Checks the reset boundary between the route parameter and the detail query.", - "reference.detail.summaryPending": "Preparing the summary.", - "reference.detail.sectionSlot": - "Product-specific detail sections can be assembled here.", - "reference.detail.aside": "Related information slot of the detail page.", - "reference.status.eyebrow": "StatusPage · maintenance", - "reference.status.title": "Temporarily unavailable.", - "reference.status.description": - "An example of a neutral status page that exposes no domain data or raw errors.", - "reference.status.back": "Go to the list", - }), -} as const); diff --git a/src/features/reference-feature/contracts/reference-schema-metadata.ts b/src/features/reference-feature/contracts/reference-schema-metadata.ts deleted file mode 100644 index f31003ba..00000000 --- a/src/features/reference-feature/contracts/reference-schema-metadata.ts +++ /dev/null @@ -1,63 +0,0 @@ -/** - * FE-REG-SCHEMA rows of the reference feature's route and API schemas. - * Runtime half only (`feature-runtime.ts`); the app boot never imports it. - * The HTTP operations are the V3 descriptors in - * `reference-feature-contract-contribution.ts`; FE-REG-API reads them. - */ -export const REFERENCE_SCHEMA_METADATA = Object.freeze({ - ReferenceResourceParams: Object.freeze({ - schemaId: "ReferenceResourceParams", - boundary: "route-params", - owner: "feature-frontend-reference-feature-vertical-slice", - runtime: "zod", - schemaVersion: 1, - direction: "REQUEST", - unknownFieldPolicy: "REJECT_UNKNOWN", - }), - ReferenceResourceListQuery: Object.freeze({ - schemaId: "ReferenceResourceListQuery", - boundary: "route-search-api-request", - owner: "feature-frontend-reference-feature-vertical-slice", - runtime: "zod", - schemaVersion: 1, - direction: "REQUEST", - unknownFieldPolicy: "REJECT_UNKNOWN", - }), - CreateReferenceResourceCommand: Object.freeze({ - schemaId: "CreateReferenceResourceCommand", - boundary: "api-request", - owner: "feature-frontend-reference-feature-vertical-slice", - runtime: "zod", - schemaVersion: 1, - direction: "REQUEST", - unknownFieldPolicy: "REJECT_UNKNOWN", - }), - ReferenceResourceListPayload: Object.freeze({ - schemaId: "ReferenceResourceListPayload", - boundary: "api-response", - owner: "feature-frontend-reference-feature-vertical-slice", - runtime: "zod", - schemaVersion: 1, - direction: "RESPONSE", - unknownFieldPolicy: "STRIP_UNKNOWN", - }), - ReferenceResourcePayload: Object.freeze({ - schemaId: "ReferenceResourcePayload", - boundary: "api-response", - owner: "feature-frontend-reference-feature-vertical-slice", - runtime: "zod", - schemaVersion: 1, - direction: "RESPONSE", - unknownFieldPolicy: "STRIP_UNKNOWN", - }), - // 1103/16-04. FE-REG-API's problemSchema references this row. - ReferenceProblem: Object.freeze({ - schemaId: "ReferenceProblem", - boundary: "api-problem", - owner: "feature-frontend-reference-feature-vertical-slice", - runtime: "zod", - schemaVersion: 1, - direction: "RESPONSE", - unknownFieldPolicy: "STRIP_UNKNOWN", - }), -}); diff --git a/src/features/reference-feature/contracts/reference-schemas.ts b/src/features/reference-feature/contracts/reference-schemas.ts deleted file mode 100644 index ebe4a491..00000000 --- a/src/features/reference-feature/contracts/reference-schemas.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { z } from "../../../contracts/zod.ts"; - -export const referenceResourceListQuerySchema = z - .object({ - cursor: z.string().min(1).optional(), - limit: z.coerce.number().int().min(1).max(100).default(20), - tags: z - .preprocess( - (value) => - value === undefined - ? undefined - : Array.isArray(value) - ? value - : [value], - z.array(z.string().trim().min(1)).readonly(), - ) - .optional(), - }) - .strict(); - -export const referenceResourceParamsSchema = z - .object({ - resourceId: z.string().trim().min(1).max(120), - }) - .strict(); - -export const referenceResourceDtoSchema = z - .object({ - id: z.string().min(1).max(120), - name: z.string().min(1).max(240), - createdAt: z.string().datetime().optional(), - }) - .strip(); - -export type ReferenceResourceDto = z.output< - typeof referenceResourceDtoSchema ->; - -export const referenceProblemSchema = z - .object({ - type: z.string().min(1).max(512), - title: z.string().min(1).max(240), - status: z.int().min(100).max(599), - code: z.string().min(1).max(120).optional(), - /** 03-04. 422 field issues; backend messages are stripped. */ - issues: z - .array( - z - .object({ - path: z.string().min(1).max(120), - code: z.string().min(1).max(80), - }) - .strip(), - ) - .max(50) - .optional(), - }) - .strip(); - -export type ReferenceProblem = z.output; - -export const createReferenceResourceCommandSchema = z - .object({ - name: z.string().trim().min(1).max(120), - note: z.string().trim().max(500).optional(), - }) - .strict(); diff --git a/src/features/reference-feature/domain/reference-resource.ts b/src/features/reference-feature/domain/reference-resource.ts deleted file mode 100644 index 4aba209b..00000000 --- a/src/features/reference-feature/domain/reference-resource.ts +++ /dev/null @@ -1,14 +0,0 @@ -export type ReferenceResource = Readonly<{ - id: string; - displayName: string; - createdAt: string | null; -}>; - -export function createReferenceResource( - values: ReferenceResource, -): ReferenceResource { - if (!values.id || !values.displayName) { - throw new TypeError("Reference resource invariants require id and displayName"); - } - return Object.freeze({ ...values }); -} diff --git a/src/features/reference-feature/feature-module.ts b/src/features/reference-feature/feature-module.ts deleted file mode 100644 index 78e8e9e4..00000000 --- a/src/features/reference-feature/feature-module.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { defineFeatureModule } from "../feature-module.ts"; -import { - REFERENCE_FEATURE_CONTRACT, - REFERENCE_FEATURE_ID, -} from "./contracts/reference-feature-contract.ts"; -import { REFERENCE_MESSAGE_CATALOGS } from "./contracts/reference-message-catalog.ts"; - -export const FEATURE_MODULE_ID = - "reference-feature" satisfies typeof REFERENCE_FEATURE_ID; -/** Owning bounded context (route root and budget live in its declaration). */ -export const FEATURE_CONTEXT_ID = "reference-context"; - -/** - * 15-01. Declaration only: this file and what it imports statically are in the - * initial chunk. The executable half is `feature-runtime.ts`, imported here - * dynamically and loaded when a reference route is entered. - */ -export const REFERENCE_FEATURE_MODULE = defineFeatureModule({ - id: FEATURE_MODULE_ID, - contracts: REFERENCE_FEATURE_CONTRACT, - routes: REFERENCE_FEATURE_CONTRACT.routes, - messages: REFERENCE_MESSAGE_CATALOGS, - loadRuntime: async () => (await import("./feature-runtime.ts")).FEATURE_RUNTIME, -} as const); - -export const FEATURE_MODULE = REFERENCE_FEATURE_MODULE; diff --git a/src/features/reference-feature/feature-runtime.ts b/src/features/reference-feature/feature-runtime.ts deleted file mode 100644 index 9953e987..00000000 --- a/src/features/reference-feature/feature-runtime.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { defineFeatureRuntime } from "../feature-module.ts"; -import { REFERENCE_FEATURE_ADAPTER_CONTRIBUTION } from "./adapters/create-reference-feature-input.ts"; -import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "./contracts/reference-feature-contract-contribution.ts"; -import { REFERENCE_FEATURE_ID } from "./contracts/reference-feature-contract.ts"; -import { REFERENCE_SCHEMA_METADATA } from "./contracts/reference-schema-metadata.ts"; - -/** - * 15-01. The executable half of the reference feature. `feature-module.ts` - * imports this file dynamically; the router loads it when a reference route - * is entered (`application.features.load`), so none of it is in the initial - * chunk. - */ -export const FEATURE_RUNTIME = defineFeatureRuntime({ - featureId: REFERENCE_FEATURE_ID, - schemas: REFERENCE_SCHEMA_METADATA, - adapters: [REFERENCE_FEATURE_ADAPTER_CONTRIBUTION], - contractContributions: [REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION], -} as const); diff --git a/src/features/reference-feature/presentation/reference-feature-runtime.ts b/src/features/reference-feature/presentation/reference-feature-runtime.ts deleted file mode 100644 index 133683eb..00000000 --- a/src/features/reference-feature/presentation/reference-feature-runtime.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { lazy } from "react"; - -import { REFERENCE_FEATURE_ID } from "../contracts/reference-feature-contract.ts"; -// 16-04. The codecs have their own file: the pages' link helpers need them and -// this file lazy-loads the pages, so a page importing it would close a cycle. -import { REFERENCE_FEATURE_ROUTE_CODECS } from "./reference-route-codecs.ts"; - -export const REFERENCE_FEATURE_ROUTE_RUNTIME = { - REFERENCE_RESOURCE_LIST: Object.freeze({ - moduleId: "reference-resource-page", - Component: lazy(() => import("./reference-resource-page.tsx")), - }), - REFERENCE_RESOURCE_DETAIL: Object.freeze({ - moduleId: "reference-resource-detail-page", - Component: lazy(() => import("./reference-resource-detail-page.tsx")), - }), - REFERENCE_RESOURCE_FORM: Object.freeze({ - moduleId: "reference-resource-form-page", - Component: lazy(() => import("./reference-resource-form-page.tsx")), - }), - REFERENCE_RESOURCE_STATUS: Object.freeze({ - moduleId: "reference-resource-status-page", - Component: lazy(() => import("./reference-resource-status-page.tsx")), - }), -} as const; - -/** Context-owned lazy route modules consume this executable contribution. */ -export const REFERENCE_FEATURE_RUNTIME_CONTRIBUTION = Object.freeze({ - featureId: REFERENCE_FEATURE_ID, - routeCodecs: REFERENCE_FEATURE_ROUTE_CODECS, - routeRuntime: REFERENCE_FEATURE_ROUTE_RUNTIME, -}); diff --git a/src/features/reference-feature/presentation/reference-resource-detail-page.tsx b/src/features/reference-feature/presentation/reference-resource-detail-page.tsx deleted file mode 100644 index 20e1f551..00000000 --- a/src/features/reference-feature/presentation/reference-resource-detail-page.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { Link } from "react-router-dom"; - -import { - AsyncSurface, - DetailPage, -} from "../../../presentation/design-system/index.ts"; -import { useLocale } from "../../../presentation/i18n/index.ts"; -import { - referenceRouteUrl, - useReferenceResourceId, -} from "./reference-routes.ts"; -import { useReferenceFailureAction } from "./use-reference-failure-action.ts"; -import { useReferenceDetail } from "./use-reference-feature.ts"; - -export default function ReferenceResourceDetailPage() { - const { date, message } = useLocale(); - const resourceId = useReferenceResourceId(); - const { query } = useReferenceDetail(resourceId); - const resource = query.data; - const failureAction = useReferenceFailureAction(query.state.failure); - - return ( - - {message("reference.list.resources")} - - } - heading={{ - eyebrow: message("reference.detail.eyebrow"), - title: resource?.title ?? message("reference.detail.titlePending"), - description: message("reference.detail.description"), - }} - metadata={ - resource ? ( -
-
{message("reference.detail.resourceId")}
-
{resource.resourceId}
-
{message("reference.detail.createdAt")}
-
- {resource.createdAt - ? date(new Date(resource.createdAt)) - : message("common.noDisplayValue")} -
-
- ) : ( -

{message("reference.detail.summaryPending")}

- ) - } - feedback={ - - {resource ? ( -

{message("reference.detail.sectionSlot")}

- ) : null} -
- } - aside={

{message("reference.detail.aside")}

} - /> - ); -} diff --git a/src/features/reference-feature/presentation/reference-resource-form-page.tsx b/src/features/reference-feature/presentation/reference-resource-form-page.tsx deleted file mode 100644 index bbdab87f..00000000 --- a/src/features/reference-feature/presentation/reference-resource-form-page.tsx +++ /dev/null @@ -1,215 +0,0 @@ -import { useCallback, useState } from "react"; -import { Link, useNavigate } from "react-router-dom"; - -import { - Button, - AsyncSurface, - DirtyNavigationDialog, - ErrorSummary, - Form, - FormActions, - FormFailureStatus, - FormPage, - FormField, - useAppForm, - useDirtyNavigationGuard, -} from "../../../presentation/design-system/index.ts"; -import { useLocale } from "../../../presentation/i18n/index.ts"; -import { useQueryInvalidationCoordinator } from "../../../presentation/adapters/query/query-invalidation-provider.tsx"; -import { REFERENCE_RESOURCE_INVALIDATION_TOPIC } from "../contracts/reference-feature-contract.ts"; -import { - REFERENCE_FORM_DEFAULTS, - referenceResourceFormSchema, - toCreateReferenceCommand, - type ReferenceResourceFormValues, -} from "./reference-resource-form.ts"; -import { referenceRouteUrl } from "./reference-routes.ts"; -import { useReferenceFailureAction } from "./use-reference-failure-action.ts"; -import { useReferenceCreate } from "./use-reference-feature.ts"; - -export default function ReferenceResourceFormPage() { - const navigate = useNavigate(); - const { message } = useLocale(); - const fieldLabels = { - name: message("reference.form.name"), - note: message("reference.form.note"), - } satisfies Record; - const mutation = useReferenceCreate(); - const invalidation = useQueryInvalidationCoordinator(); - const submit = useCallback( - (command: ReturnType) => - mutation.submit(command), - [mutation], - ); - const form = useAppForm({ - schema: referenceResourceFormSchema, - defaultValues: REFERENCE_FORM_DEFAULTS, - allowedServerFields: ["name", "note"], - mapToCommand: toCreateReferenceCommand, - submit, - }); - const failureAction = useReferenceFailureAction(form.failure ?? undefined); - const mutationEffectUnknown = - mutation.state.indicator === "mutation-effect-unknown"; - const mutationBlocked = - mutationEffectUnknown || mutation.state.indicator === "mutation-pending"; - // 1105/08-04. A save this form did not start holds the coordinator: one - // left running when the user came back to the form, or the check behind - // "confirm applied". The save button is off and, for the first, the - // feedback says a save is running, instead of a click that does nothing. - const otherSaveRunning = - mutation.state.indicator === "mutation-pending" && !form.pending; - // 1106/08-01. The result of that save belongs to the form that started - // it, not to this one. Once it ends, the feedback points to the list, - // which shows whether the item is there, until this form saves itself. - const [otherSaveSeen, setOtherSaveSeen] = useState(false); - if (!otherSaveSeen && otherSaveRunning && form.result === "idle") { - setOtherSaveSeen(true); - } else if (otherSaveSeen && (form.pending || form.result !== "idle")) { - setOtherSaveSeen(false); - } - const guard = useDirtyNavigationGuard(form.dirty && !form.pending); - const reloadList = ( -

- { - void invalidation - ?.invalidate([REFERENCE_RESOURCE_INVALIDATION_TOPIC]) - .catch(() => {}); - }} - > - {message("reference.form.reloadList")} - -

- ); - - return ( -
{ - if (mutationBlocked) { - event.preventDefault(); - return; - } - void form.submitForm(event); - }} - > - navigate(referenceRouteUrl("REFERENCE_RESOURCE_LIST"))} - > - {message("reference.form.back")} - - } - heading={{ - eyebrow: message("reference.form.eyebrow"), - title: message("reference.form.title"), - description: message("reference.form.description"), - }} - errorSummary={ - - } - fields={ - <> - - - - } - formActions={ - - - {/* 1103/08-02. Busy, not disabled, while saving: a disabled - button drops keyboard focus. The form refuses a second - submit itself. */} - - - - } - feedback={ - form.failure ? ( - void form.submitForm() - : failureAction - } - /> - ) : mutationEffectUnknown ? ( - <> - { - void mutation - .reconcileUnknownEffect(resolution) - .then(form.settleApplied); - }} - onResendUnknownEffect={() => { - void form.resendUnknown(mutation.resendUnknownEffect); - }} - /> - {reloadList} - - ) : form.result === "success" ? ( -

{message("reference.form.saved")}

- ) : form.result === "conflict" ? ( -

{message("reference.form.conflict")}

- ) : otherSaveRunning && form.result !== "effect-unknown" ? ( - // 1105/08-04. While this form's own unknown result is being - // checked, the result that follows is shown instead. - - ) : otherSaveSeen ? ( - reloadList - ) : null - } - aside={ -

{message("reference.form.privacy")}

- } - guard={} - /> - - ); -} diff --git a/src/features/reference-feature/presentation/reference-resource-form.ts b/src/features/reference-feature/presentation/reference-resource-form.ts deleted file mode 100644 index 39a2ebaa..00000000 --- a/src/features/reference-feature/presentation/reference-resource-form.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { z } from "../../../contracts/zod.ts"; - -export const referenceResourceFormSchema = z - .object({ - name: z - .string() - .trim() - .min(2) - .max(120), - note: z.string().trim().max(500).default(""), - }) - .strict(); - -export type ReferenceResourceFormValues = z.infer< - typeof referenceResourceFormSchema ->; - -export const REFERENCE_FORM_DEFAULTS: ReferenceResourceFormValues = - Object.freeze({ - name: "", - note: "", - }); - -export function toCreateReferenceCommand(values: ReferenceResourceFormValues) { - return Object.freeze({ - name: values.name, - ...(values.note ? { note: values.note } : {}), - }); -} diff --git a/src/features/reference-feature/presentation/reference-resource-page.tsx b/src/features/reference-feature/presentation/reference-resource-page.tsx deleted file mode 100644 index 06dac7ea..00000000 --- a/src/features/reference-feature/presentation/reference-resource-page.tsx +++ /dev/null @@ -1,79 +0,0 @@ -import { Link, useNavigate } from "react-router-dom"; - -import { - AsyncSurface, - Button, - CollectionPage, -} from "../../../presentation/design-system/index.ts"; -import { useLocale } from "../../../presentation/i18n/index.ts"; -import { referenceRouteUrl } from "./reference-routes.ts"; -import { useReferenceFailureAction } from "./use-reference-failure-action.ts"; -import { useReferenceFeature } from "./use-reference-feature.ts"; - -export default function ReferenceResourcePage() { - const navigate = useNavigate(); - const { message } = useLocale(); - const { filters, query } = useReferenceFeature(); - const failureAction = useReferenceFailureAction(query.state.failure); - - return ( - navigate(referenceRouteUrl("REFERENCE_RESOURCE_FORM")), - }, - ]} - activeFilters={ -

- {message("reference.list.filterLimit", { limit: filters.limit })} - {filters.tags?.length - ? ` · ${message("reference.list.filterTags", { - tags: filters.tags.join(", "), - })}` - : ""} -

- } - toolbar={ - - } - resultCount={ - // 08-09. Counted only from a settled result: a loading, idle or - // failed list has nothing to count. - query.state.base === "success" || query.state.base === "empty" - ? message("reference.list.resultCount", { - count: query.data?.length ?? 0, - }) - : null - } - > - -
    - {(query.data ?? []).map((resource) => ( -
  • - - {resource.title} - -
  • - ))} -
-
-
- ); -} diff --git a/src/features/reference-feature/presentation/reference-resource-status-page.tsx b/src/features/reference-feature/presentation/reference-resource-status-page.tsx deleted file mode 100644 index c616bd1b..00000000 --- a/src/features/reference-feature/presentation/reference-resource-status-page.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { useLocation, useNavigate } from "react-router-dom"; - -import { StatusPage } from "../../../presentation/design-system/index.ts"; -import { useLocale } from "../../../presentation/i18n/index.ts"; -import { referenceRouteUrl } from "./reference-routes.ts"; -import type { ReferenceSupportState } from "./use-reference-failure-action.ts"; - -/** History state is untrusted input: only a string reference is shown. */ -function receivedSupportReference(state: unknown): string | undefined { - const reference = - state && typeof state === "object" - ? (state as ReferenceSupportState).supportReference - : undefined; - return typeof reference === "string" && reference !== "" ? reference : undefined; -} - -export default function ReferenceResourceStatusPage() { - const navigate = useNavigate(); - const location = useLocation(); - const { message } = useLocale(); - // 0929/08-04. Only the id the failed request carried; none when opened directly. - const supportReference = receivedSupportReference(location.state); - - return ( - navigate(referenceRouteUrl("REFERENCE_RESOURCE_LIST")), - }} - supportReference={supportReference} - /> - ); -} diff --git a/src/features/reference-feature/presentation/reference-route-codecs.ts b/src/features/reference-feature/presentation/reference-route-codecs.ts deleted file mode 100644 index 9251b5e9..00000000 --- a/src/features/reference-feature/presentation/reference-route-codecs.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { - referenceResourceListQuerySchema, - referenceResourceParamsSchema, -} from "../contracts/reference-schemas.ts"; - -/** - * 15-01. Route codecs travel with the context routes (`context-routes.ts` puts - * them on each route handle), not with the boot-time feature module: zod - * schemas are executable and the shell needs none of them before a reference - * route is entered. 16-04: the pages' link helpers (`reference-routes.ts`) use - * them too; this file imports no router code, so loading the context routes - * does not pull in the link builder. - */ -export const REFERENCE_FEATURE_ROUTE_CODECS = { - ReferenceResourceListQuery: referenceResourceListQuerySchema, - ReferenceResourceParams: referenceResourceParamsSchema, -} as const; diff --git a/src/features/reference-feature/presentation/reference-routes.ts b/src/features/reference-feature/presentation/reference-routes.ts deleted file mode 100644 index ac5bc987..00000000 --- a/src/features/reference-feature/presentation/reference-routes.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { useMemo } from "react"; - -import { buildRouteUrl } from "../../../presentation/routes/route-codecs.ts"; -import { useRouteInput } from "../../../presentation/routes/route-input.tsx"; -import type { ReferenceListFilters } from "../application/reference-feature-api.ts"; -import type { REFERENCE_FEATURE_CONTRACT } from "../contracts/reference-feature-contract.ts"; -import { REFERENCE_FEATURE_ROUTE_CODECS } from "./reference-route-codecs.ts"; - -/** - * 16-04. A reference link names its route ID. The router's own builder fills - * in the contract's `path` through the codecs that parse it, so the contract - * stays the one place a path is written. - */ -export function referenceRouteUrl( - routeId: keyof typeof REFERENCE_FEATURE_CONTRACT.routes, - input?: Parameters[1], -): string { - return buildRouteUrl(routeId, input, REFERENCE_FEATURE_ROUTE_CODECS); -} - -/** - * 16-04. The router hands pages untyped route input. Reading it back through - * the codec that already accepted it gives the codec's type without a cast. - */ -export function useReferenceListFilters(): ReferenceListFilters { - const { search } = useRouteInput(); - return useMemo( - () => REFERENCE_FEATURE_ROUTE_CODECS.ReferenceResourceListQuery.parse(search), - [search], - ); -} - -export function useReferenceResourceId(): string { - return REFERENCE_FEATURE_ROUTE_CODECS.ReferenceResourceParams.parse( - useRouteInput().params, - ).resourceId; -} diff --git a/src/features/reference-feature/presentation/use-reference-failure-action.ts b/src/features/reference-feature/presentation/use-reference-failure-action.ts deleted file mode 100644 index 1164df44..00000000 --- a/src/features/reference-feature/presentation/use-reference-failure-action.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { useCallback } from "react"; -import { useLocation, useNavigate } from "react-router-dom"; - -import type { AppFailure } from "../../../contracts/errors.ts"; -import { useSession } from "../../../presentation/providers/session-provider.tsx"; -import { referenceRouteUrl } from "./reference-routes.ts"; - -/** 0929/08-04. What the support status page receives as navigation state. */ -export type ReferenceSupportState = Readonly<{ supportReference?: string }>; - -/** - * Reference queries own concrete destinations for generic application failure - * actions. Retry remains query-owned; guarded release reloads remain in the - * chunk recovery boundary. - */ -export function useReferenceFailureAction( - failure: AppFailure | undefined, -): (() => void) | undefined { - const location = useLocation(); - const navigate = useNavigate(); - const { beginSignIn } = useSession(); - const action = failure?.action; - const requestId = failure?.requestId; - const handleAction = useCallback(() => { - if (action === "reauth") { - const returnTo = `${location.pathname}${location.search}${location.hash}`; - void beginSignIn(returnTo).catch(() => { - void navigate("/"); - }); - return; - } - if (action === "navigate") { - void navigate("/"); - return; - } - if (action === "contact-support") { - // The id stays in history state, never in the URL. - const state: ReferenceSupportState = - requestId === undefined ? {} : { supportReference: requestId }; - void navigate(referenceRouteUrl("REFERENCE_RESOURCE_STATUS"), { state }); - } - }, [ - action, - requestId, - beginSignIn, - location.hash, - location.pathname, - location.search, - navigate, - ]); - - return action === "reauth" || - action === "navigate" || - action === "contact-support" - ? handleAction - : undefined; -} diff --git a/src/features/reference-feature/presentation/use-reference-feature.ts b/src/features/reference-feature/presentation/use-reference-feature.ts deleted file mode 100644 index e455765b..00000000 --- a/src/features/reference-feature/presentation/use-reference-feature.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { useApplicationFeature } from "../../../presentation/providers/application-provider.tsx"; -import { - useApplicationMutation, - useApplicationQuery, -} from "../../../presentation/adapters/query/application-query.ts"; -import { - REFERENCE_FEATURE_ID, - REFERENCE_RESOURCE_INVALIDATION_TOPIC, - REFERENCE_RESOURCE_QUERY_NAMESPACE, -} from "../contracts/reference-feature-contract.ts"; -import type { - ReferenceCreateCommand, - ReferenceFeatureInput, - ReferenceListFilters, -} from "../application/reference-feature-api.ts"; -import type { ReferenceResourceView } from "../contracts/reference-mapper.ts"; -import { CREATE_REFERENCE_RESOURCE_CONTRACT } from "../contracts/reference-feature-contract-contribution.ts"; -import { - bindQuery, - commandMutationIdentity, - type BoundMutation, - type QueryResultMeasure, -} from "../../../contracts/server-state.ts"; -import { useServerStateScope } from "../../../presentation/adapters/query/server-state-scope-provider.tsx"; -import { useReferenceListFilters } from "./reference-routes.ts"; - -const UTF8 = new TextEncoder(); - -/** - * §10.4. Feature-owned measurement over the mapped application value. There is - * no generic fallback: bounded string bytes plus fixed primitive width plus a - * small per-item overhead, never `JSON.stringify` or a recursive walker. - */ -function measureResourceView(view: ReferenceResourceView): QueryResultMeasure { - return { - itemCount: 1, - estimatedBytes: - UTF8.encode(view.resourceId).byteLength + - UTF8.encode(view.title).byteLength + - UTF8.encode(view.createdAt ?? "").byteLength + - 32, - }; -} - -function measureResourceList( - views: readonly ReferenceResourceView[], -): QueryResultMeasure { - let estimatedBytes = 16; - for (const view of views) { - estimatedBytes += measureResourceView(view).estimatedBytes; - } - return { itemCount: views.length, estimatedBytes }; -} - -const REFERENCE_CREATE_MUTATION_POLICY = Object.freeze({ - definitionId: "reference-resource-create-v1", - definitionVersion: 1, - // 1103/16-05. The operation id and the key requirement are the - // descriptor's, so a misspelt id cannot pass the type check. - ...commandMutationIdentity(CREATE_REFERENCE_RESOURCE_CONTRACT), - duplicatePolicy: "REJECT_WHILE_ACTIVE" as const, - invalidate: Object.freeze([REFERENCE_RESOURCE_INVALIDATION_TOPIC]), -}); - -type ReferenceCreateMutationBinding = Pick< - BoundMutation, - "scope" | "execute" ->; - -function bindReferenceCreateMutation( - binding: ReferenceCreateMutationBinding, -): BoundMutation { - return Object.freeze({ - ...REFERENCE_CREATE_MUTATION_POLICY, - ...binding, - }); -} - -export function useReferenceFeatureInput(): ReferenceFeatureInput { - return useApplicationFeature(REFERENCE_FEATURE_ID); -} - -export function useReferenceDetail(resourceId: string) { - const input = useReferenceFeatureInput(); - const scope = useServerStateScope(); - const query = useApplicationQuery( - bindQuery( - { - definitionId: "reference-resource-detail-v1", - definitionVersion: 1, - namespace: REFERENCE_RESOURCE_QUERY_NAMESPACE, - profileId: "DETAIL_STANDARD", - measureResult: measureResourceView, - execute: (selectedResourceId: string, { signal }) => - input.getResource(selectedResourceId, { signal }), - }, - resourceId, - scope, - ), - ); - return Object.freeze({ query }); -} - -export function useReferenceCreate() { - const input = useReferenceFeatureInput(); - const scope = useServerStateScope(); - const mutation = bindReferenceCreateMutation({ - scope, - execute: input.createResource, - }); - return useApplicationMutation(mutation); -} - -export function useReferenceFeature() { - const input = useReferenceFeatureInput(); - const scope = useServerStateScope(); - const filters = useReferenceListFilters(); - const query = useApplicationQuery( - bindQuery( - { - definitionId: "reference-resource-list-v1", - definitionVersion: 1, - namespace: REFERENCE_RESOURCE_QUERY_NAMESPACE, - profileId: "LIST_STANDARD", - measureResult: measureResourceList, - execute: (selectedFilters: ReferenceListFilters, { signal }) => - input.listResources(selectedFilters, { signal }), - }, - filters, - scope, - ), - ); - const mutation = useApplicationMutation( - bindReferenceCreateMutation({ - scope, - execute: input.createResource, - }), - ); - return Object.freeze({ filters, query, mutation }); -} diff --git a/src/features/platform-examples-feature/presentation/ui-gallery-page.tsx b/src/presentation/design-system/galleries.stories.tsx similarity index 71% rename from src/features/platform-examples-feature/presentation/ui-gallery-page.tsx rename to src/presentation/design-system/galleries.stories.tsx index 2a569382..7d9bdde1 100644 --- a/src/features/platform-examples-feature/presentation/ui-gallery-page.tsx +++ b/src/presentation/design-system/galleries.stories.tsx @@ -1,25 +1,64 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; import { useState, type FormEvent } from "react"; +import { deriveAsyncState } from "../../application/view-models/async-state.ts"; +import { createFailure } from "../../contracts/errors.ts"; import { Alert, + AsyncSurface, + AuthRequiredSurface, Badge, Button, Card, Checkbox, Dialog, + EmptySurface, + ForbiddenSurface, + LoadingSurface, Menu, + NotFoundSurface, PageHeader, ProgressBar, RadioGroup, Select, Switch, Tabs, + TerminalErrorSurface, TextArea, TextField, ToastProvider, Tooltip, useToast, -} from "../../../presentation/design-system/index.ts"; +} from "./index.ts"; + +/** + * The design-system gallery and the screen-state gallery. They were the + * template's example screens `/examples/ui` and `/examples/states`; the + * visual goldens `design-system-gallery-dark` and `state-surfaces-light` + * (tests/visual/platform.visual.spec.ts) and the workshop tests + * (tests/storybook/galleries.spec.ts) open these stories in the static + * Storybook build. The primitives keep their own suites; these stories show + * them together, with the tokens they draw with. + */ +const meta = { + title: "Platform/Galleries", + parameters: { + layout: "fullscreen", + // Drawn like a route page: the preview's `main` adds no page of its own. + page: true, + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const DesignSystem: Story = { + render: () => , +}; + +export const ScreenStates: Story = { + render: () => , +}; const COLOR_TOKENS = Object.freeze([ ["Surface", "--color-surface"], @@ -31,7 +70,7 @@ const COLOR_TOKENS = Object.freeze([ ["Focus", "--color-focus"], ]); -export default function UiGalleryPage() { +function DesignSystemGallery() { return ( @@ -316,3 +355,88 @@ function UiGalleryContent() { ); } + +function ScreenStateGallery() { + const [lastAction, setLastAction] = useState( + "상태 화면의 작업을 선택하면 결과가 여기에 표시됩니다.", + ); + const refreshingState = deriveAsyncState({ + data: ["기존 데이터"], + isFetching: true, + }); + + return ( + // 08-07. Example copy is Korean in every locale (outside the catalog). +
+ + +
+
+

비동기 데이터 상태

+

초기 로딩과 백그라운드 갱신을 구분해 기존 콘텐츠를 보존합니다.

+
+
+ + + + + +
기존 콘텐츠는 계속 표시됩니다.
+
+
+ + setLastAction("빈 화면 작업을 실행했습니다.")}> + 첫 작업 시작 + + } + /> + + + setLastAction("오류 요청을 다시 시도했습니다.")} + /> + +
+
+ +
+
+

접근과 탐색 상태

+

인증 여부와 서버 권한 결과를 서로 다른 상태로 전달합니다.

+
+
+ setLastAction("로그인 연동 작업을 시작했습니다.")} + /> + setLastAction("접근 가능한 화면으로 이동합니다.")} + /> + setLastAction("시작 화면으로 이동합니다.")} + /> +
+
+ + + {lastAction} + +
+ ); +} diff --git a/src/presentation/styles/theme/pages.css b/src/presentation/styles/theme/pages.css index 511d5b61..207ec36b 100644 --- a/src/presentation/styles/theme/pages.css +++ b/src/presentation/styles/theme/pages.css @@ -12,8 +12,7 @@ line-height: 1.65; } - .starter-actions, - .auth-example { + .starter-actions { display: flex; flex-wrap: wrap; align-items: center; diff --git a/tests/browser-capabilities/local-draft-composition.spec.ts b/tests/browser-capabilities/local-draft-composition.spec.ts index 6319ad6b..b2b284ed 100644 --- a/tests/browser-capabilities/local-draft-composition.spec.ts +++ b/tests/browser-capabilities/local-draft-composition.spec.ts @@ -1,7 +1,7 @@ import type { IndexedDbRuntimeDependencies, } from "../../src/adapters/storage/indexeddb/indexeddb-types.ts"; -import type { LocalDraft } from "../../src/features/local-draft-feature/domain/local-draft.ts"; +import type { LocalDraft } from "../fixtures/indexeddb-consumer/domain/local-draft.ts"; import { expect, test, @@ -21,7 +21,7 @@ test("composes the local-draft feature over the real browser IndexedDB runtime", const contributionModulePath = "/src/features/feature-adapter-contribution.ts"; const localDraftModulePath = - "/src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts"; + "/tests/fixtures/indexeddb-consumer/adapters/create-local-draft-feature-input.ts"; const { createIndexedDbRuntime, @@ -39,7 +39,7 @@ test("composes the local-draft feature over the real browser IndexedDB runtime", LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION, } = (await import( /* @vite-ignore */ localDraftModulePath - )) as typeof import("../../src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts"); + )) as typeof import("../fixtures/indexeddb-consumer/adapters/create-local-draft-feature-input.ts"); const suffix = crypto.randomUUID().replaceAll("-", ""); const scope = Object.freeze({ diff --git a/tests/component/design-system-links.test.tsx b/tests/component/design-system-links.test.tsx index 6cdf0860..72d7d5ee 100644 --- a/tests/component/design-system-links.test.tsx +++ b/tests/component/design-system-links.test.tsx @@ -39,15 +39,15 @@ function renderInRouter(ui: ReactNode, entry = "/app/items?q=term&sort=name") { describe("design-system links inside the router", () => { it("renders LinkButton `to` as a router link that keeps the basename", async () => { const user = userEvent.setup(); - renderInRouter(States); + renderInRouter(States); const link = screen.getByRole("link", { name: "States" }); - expect(link).toHaveAttribute("href", "/app/examples/states"); + expect(link).toHaveAttribute("href", "/app/examples/platform"); expect(link).toHaveClass("ui-button", "ui-button--primary"); await user.click(link); expect(screen.getByTestId("location")).toHaveTextContent( - /^\/examples\/states$/, + /^\/examples\/platform$/, ); }); @@ -86,7 +86,7 @@ describe("design-system links inside the router", () => { renderInRouter( { "https://example.com", ); const link = screen.getByRole("link", { name: "Open states" }); - expect(link).toHaveAttribute("href", "/app/examples/states"); + expect(link).toHaveAttribute("href", "/app/examples/platform"); await user.click(link); expect(screen.getByTestId("location")).toHaveTextContent( - /^\/examples\/states$/, + /^\/examples\/platform$/, ); }); diff --git a/tests/component/product-feature-switch.test.tsx b/tests/component/product-feature-switch.test.tsx index 7ee7e1f9..d731b76c 100644 --- a/tests/component/product-feature-switch.test.tsx +++ b/tests/component/product-feature-switch.test.tsx @@ -1,30 +1,44 @@ // @vitest-environment jsdom -import { render, screen } from "@testing-library/react"; -import { describe, expect, it } from "vitest"; +import { render, screen, within } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts"; import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts"; -import { REFERENCE_FEATURE_ID } from "../../src/features/reference-feature/contracts/reference-feature-contract.ts"; import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx"; import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx"; import { AppRouter } from "../../src/presentation/routes/app-router.tsx"; import { createTestApplication } from "../helpers/create-test-application.ts"; +import { FIXTURE_FEATURE_ID, FIXTURE_FEATURE_MODULE } from "../helpers/fixture-feature.tsx"; import { createProductFeaturesStub } from "../helpers/runtime-capabilities-stub.ts"; +// The test-only feature (tests/helpers/fixture-feature.tsx): the template +// installs none. +vi.mock("../../src/.generated/product-feature-index.ts", async () => ({ + DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"], + PRODUCT_FEATURE_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE], +})); +vi.mock("../../src/.generated/product-context-index.ts", async () => ({ + PRODUCT_CONTEXT_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_CONTEXT_MODULE], +})); + /** * §3.5. The runtime kill switch, exercised through the running app rather than * through the resolver that computes it. * * Withdrawing a feature from navigation is not the same as taking it out of * service: a typed deep link would still mount it. Both halves are asserted - * here, on the same render, so the switch cannot be half-wired. + * here, on the same render, so the switch cannot be half-wired. These ran on + * the template's reference sample and example screens until they were + * deleted (2026-11-07). */ - -// 16-02. The feature that owns FEATURE_ROUTE, not whichever installed feature -// sorts first. -const FEATURE_ID = REFERENCE_FEATURE_ID; -const FEATURE_ROUTE = ROUTE_REGISTRY.REFERENCE_RESOURCE_LIST; +const routes: Readonly> = + ROUTE_REGISTRY; +// A public page of the feature in the primary navigation, and its menu name. +const FEATURE_ROUTE = routes["FIXTURE_FIRST_PAGE"]!; +const FEATURE_LINK = (FIXTURE_FEATURE_MODULE.messages["ko-KR"] as Readonly>)[ + "route.FIXTURE_FIRST_PAGE.navigation" +]!; function renderAt(path: string, disabled: boolean) { window.history.pushState({}, "", path); @@ -35,7 +49,7 @@ function renderAt(path: string, disabled: boolean) { ...(disabled ? { productFeatures: createProductFeaturesStub({ - [FEATURE_ID]: "DISABLED_BY_CONFIG", + [FIXTURE_FEATURE_ID]: "DISABLED_BY_CONFIG", }), } : {}), @@ -48,39 +62,71 @@ function renderAt(path: string, disabled: boolean) { ); } +const disabledSurface = () => + screen.queryByText( + (_, element) => element?.getAttribute("data-disabled-feature") === FIXTURE_FEATURE_ID, + ); + describe("runtime product feature switch", () => { it("advertises the feature's route while the feature is active", async () => { renderAt("/", false); expect( - await screen.findByRole("link", { name: FEATURE_ROUTE.navigationLabel! }), - ).toBeTruthy(); + await screen.findAllByRole("link", { name: FEATURE_LINK }), + ).not.toHaveLength(0); }); it("withdraws the feature's route from navigation when it is disabled", async () => { renderAt("/", true); // The shell itself still renders: disabling a feature is not an outage. - expect(await screen.findByRole("navigation")).toBeTruthy(); + expect(await screen.findAllByRole("navigation")).not.toHaveLength(0); expect( - screen.queryByRole("link", { name: FEATURE_ROUTE.navigationLabel! }), + screen.queryByRole("link", { name: FEATURE_LINK }), ).toBeNull(); }); + // 1105/08-03. The home page's starter links read the same switch as the + // shell's navigation: switched off at runtime, the feature's screens are + // not offered there, and the next active screens take their place. + it("leaves the feature's screens out of the home page's starter links when it is disabled", async () => { + renderAt("/", true); + + const starter = await screen.findByRole("region", { name: "준비된 화면 살펴보기" }); + const starterPaths = within(starter) + .getAllByRole("link") + .map((link) => link.getAttribute("href")); + const [navigation] = screen.getAllByRole("navigation", { name: "주요 탐색" }); + const advertised = within(navigation!) + .getAllByRole("link") + .map((link) => link.getAttribute("href")) + .filter((path) => path !== "/"); + + expect(starterPaths).not.toContain(FEATURE_ROUTE.path); + expect(starterPaths).toEqual(advertised.slice(0, 3)); + }); + + it("offers the feature's screens among the starter links while it is active", async () => { + renderAt("/", false); + + const starter = await screen.findByRole("region", { name: "준비된 화면 살펴보기" }); + expect( + within(starter) + .getAllByRole("link") + .map((link) => link.getAttribute("href")), + ).toContain(FEATURE_ROUTE.path); + }); + it("takes the feature out of service for a direct deep link", async () => { renderAt(FEATURE_ROUTE.path, true); - const surface = await screen.findByText( - (_, element) => - element?.getAttribute("data-disabled-feature") === FEATURE_ID, - ); - expect(surface).toBeTruthy(); + expect( + await screen.findByText( + (_, element) => element?.getAttribute("data-disabled-feature") === FIXTURE_FEATURE_ID, + ), + ).toBeTruthy(); }); it("serves the same deep link while the feature is active", async () => { renderAt(FEATURE_ROUTE.path, false); - expect( - screen.queryByText( - (_, element) => - element?.getAttribute("data-disabled-feature") === FEATURE_ID, - ), - ).toBeNull(); + expect(await screen.findByRole("heading", { level: 1 })).toBeTruthy(); + expect(disabledSurface()).toBeNull(); }); }); diff --git a/tests/contract/consumer-experience/indexeddb-local-draft.test.ts b/tests/contract/consumer-experience/indexeddb-local-draft.test.ts index d2dc3975..e22094dd 100644 --- a/tests/contract/consumer-experience/indexeddb-local-draft.test.ts +++ b/tests/contract/consumer-experience/indexeddb-local-draft.test.ts @@ -7,13 +7,13 @@ import type { BrowserDataResult, IndexedDbRepositoryPort, } from "../../../src/application/ports/browser-file-storage/index.ts"; -import { createLocalDraftStore } from "../../../src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts"; -import type { LocalDraft } from "../../../src/features/local-draft-feature/domain/local-draft.ts"; +import { createLocalDraftStore } from "../../fixtures/indexeddb-consumer/adapters/local-draft-indexeddb-store.ts"; +import type { LocalDraft } from "../../fixtures/indexeddb-consumer/domain/local-draft.ts"; // 09-12. This probe used to exercise a copy of the feature under fixtures/, // which had drifted from src (it returned raw storage failures). It now reads // and runs the one implementation. -const FEATURE_ROOT = "src/features/local-draft-feature"; +const FEATURE_ROOT = "tests/fixtures/indexeddb-consumer"; async function featureSources(directory: string): Promise { const entries = await readdir(directory, { withFileTypes: true }); diff --git a/tests/contract/reusable-capability/feature-adapter-composition.test.ts b/tests/contract/reusable-capability/feature-adapter-composition.test.ts index c800940d..cc05be0e 100644 --- a/tests/contract/reusable-capability/feature-adapter-composition.test.ts +++ b/tests/contract/reusable-capability/feature-adapter-composition.test.ts @@ -13,8 +13,8 @@ import { } from "../../../src/features/feature-adapter-contribution.ts"; import { LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION, -} from "../../../src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts"; -import type { LocalDraft } from "../../../src/features/local-draft-feature/domain/local-draft.ts"; +} from "../../fixtures/indexeddb-consumer/adapters/create-local-draft-feature-input.ts"; +import type { LocalDraft } from "../../fixtures/indexeddb-consumer/domain/local-draft.ts"; type TestHttpFeatureInput = Readonly<{ ping(): Promise<"pong">; diff --git a/tests/e2e/accessibility.spec.ts b/tests/e2e/accessibility.spec.ts index d4c797b1..1c631214 100644 --- a/tests/e2e/accessibility.spec.ts +++ b/tests/e2e/accessibility.spec.ts @@ -110,7 +110,7 @@ test("@a11y keyboard reaches the primary route action with visible focus", async // 08-09. axe's skip-link rule is best-practice, outside WCAG_TAGS, so the only // way past the header and sidebar (WCAG 2.4.1) needs its own check. test("@a11y skip link moves keyboard focus into main", async ({ page }) => { - await page.goto("/examples/ui"); + await page.goto("/examples/platform"); await expect(page.getByRole("heading", { level: 1 })).toBeFocused(); const skipLink = page.getByRole("link", { name: "본문으로 건너뛰기" }); await skipLink.focus(); @@ -135,19 +135,3 @@ test("@a11y reduced-motion policy disables long animation", async ({ page }) => .evaluate((body) => getComputedStyle(body).animationDuration); expect(["0s", "0.00001s", "1e-05s"]).toContain(duration); }); - -test("@a11y opened design-system dialog has no blocking violations", async ({ - page, -}) => { - await page.goto("/examples/ui"); - await page.getByRole("button", { name: "모달 열기" }).click(); - const results = await new AxeBuilder({ page }) - .include(".ui-dialog") - .withTags(WCAG_TAGS) - .analyze(); - expect( - results.violations.filter((violation) => - ["critical", "serious"].includes(violation.impact ?? ""), - ), - ).toEqual([]); -}); diff --git a/tests/e2e/app-shell.spec.ts b/tests/e2e/app-shell.spec.ts index 61a1ad8a..b9d15e8e 100644 --- a/tests/e2e/app-shell.spec.ts +++ b/tests/e2e/app-shell.spec.ts @@ -15,12 +15,12 @@ test("navigates to a registry-backed example without a page reload", async ({ await page.goto("/"); await page .getByRole("navigation", { name: "주요 탐색" }) - .getByRole("link", { name: "화면 상태" }) + .getByRole("link", { name: "플랫폼 구성" }) .click(); - await expect(page).toHaveURL(/\/examples\/states$/); + await expect(page).toHaveURL(/\/examples\/platform$/); await expect( - page.getByRole("heading", { level: 1, name: "화면 상태" }), + page.getByRole("heading", { level: 1, name: "플랫폼 구성" }), ).toBeFocused(); }); @@ -55,11 +55,11 @@ test("moves focus to the new page after a mobile drawer link, not back to the me const navigation = page.getByRole("navigation", { name: "주요 탐색" }); await menu.click(); - await navigation.getByRole("link", { name: "화면 상태" }).click(); + await navigation.getByRole("link", { name: "플랫폼 구성" }).click(); - await expect(page).toHaveURL(/\/examples\/states$/); + await expect(page).toHaveURL(/\/examples\/platform$/); await expect(menu).toHaveAttribute("aria-expanded", "false"); - const heading = page.getByRole("heading", { level: 1, name: "화면 상태" }); + const heading = page.getByRole("heading", { level: 1, name: "플랫폼 구성" }); await expect(heading).toBeFocused(); // Give any late restore (dialog close timer, lazy route commit) time to run. await page.waitForTimeout(300); diff --git a/tests/e2e/boot-module-failure.spec.ts b/tests/e2e/boot-module-failure.spec.ts index 546dc2f3..679affda 100644 --- a/tests/e2e/boot-module-failure.spec.ts +++ b/tests/e2e/boot-module-failure.spec.ts @@ -1,6 +1,7 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; +import { addGeneratedFeature } from "../../scripts/lib/generated-feature.ts"; import { expect, test } from "../support/browser/strict-browser-test.ts"; import { editOnce, @@ -15,7 +16,9 @@ import { startBuildServer } from "./support/service-worker-builds.ts"; * modules evaluate: the installed features are composed twice, so * `installed-feature-messages.ts` meets every message key a second time and * throws at module top level. The static "loading" shell used to stay up - * forever; the boot error shell has to replace it. + * forever; the boot error shell has to replace it. The template installs no + * feature, so the copy gets the one `create:feature` writes first: with none + * there is no key to meet twice. */ let builds: FixtureBuilds<"broken"> | undefined; @@ -25,12 +28,14 @@ test.beforeAll(async () => { builds = await prepareFixtureBuilds("boot-module-failure", [ { name: "broken", - edit: (root) => - editOnce( + edit: async (root) => { + await addGeneratedFeature(root); + await editOnce( path.join(root, "src/features/installed-feature-messages.ts"), "composeInstalledMessageCatalogs(\n INSTALLED_PRODUCT_FEATURE_MODULES,\n)", "composeInstalledMessageCatalogs([\n ...INSTALLED_PRODUCT_FEATURE_MODULES,\n ...INSTALLED_PRODUCT_FEATURE_MODULES,\n])", - ), + ); + }, }, ]); }); diff --git a/tests/e2e/compact-smoke.spec.ts b/tests/e2e/compact-smoke.spec.ts index d084c229..e051ff5f 100644 --- a/tests/e2e/compact-smoke.spec.ts +++ b/tests/e2e/compact-smoke.spec.ts @@ -21,9 +21,9 @@ test("boots and navigates the compact production shell", async ({ page }) => { // accessibility tree while it is open. Scope to the navigation and match the // whole name, or a route call to action on the page behind it also matches. await navigation - .getByRole("link", { name: "UI 구성요소", exact: true }) + .getByRole("link", { name: "플랫폼 구성", exact: true }) .click(); - await expect(page).toHaveURL(/\/examples\/ui$/); + await expect(page).toHaveURL(/\/examples\/platform$/); await expect(page.locator("html")).toHaveAttribute("data-build-id", EXPECTED_BUILD_ID); const overflow = await page.evaluate( () => document.documentElement.scrollWidth - window.innerWidth, diff --git a/tests/e2e/design-system-interactions.spec.ts b/tests/e2e/design-system-interactions.spec.ts deleted file mode 100644 index 08cf8112..00000000 --- a/tests/e2e/design-system-interactions.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { expect, test } from "../support/browser/strict-browser-test.ts"; - -test("runs menu typeahead, tabs and duplicate toast interactions", async ({ - page, -}) => { - await page.goto("/examples/ui"); - - const menuTrigger = page.getByRole("button", { name: "작업 메뉴" }); - await menuTrigger.focus(); - await page.keyboard.press("ArrowDown"); - await page.keyboard.type("toast"); - const toastItem = page.getByRole("menuitem", { name: "Toast 표시" }); - await expect(toastItem).toBeFocused(); - await page.keyboard.press("Enter"); - await expect(page.getByText("예제가 저장되었습니다.")).toBeVisible(); - await expect(menuTrigger).toBeFocused(); - - const tokenTab = page.getByRole("tab", { name: "토큰" }); - await tokenTab.focus(); - await page.keyboard.press("ArrowRight"); - const primitiveTab = page.getByRole("tab", { name: "프리미티브" }); - await expect(primitiveTab).toBeFocused(); - await expect(primitiveTab).toHaveAttribute("aria-selected", "false"); - await page.keyboard.press("Enter"); - await expect(primitiveTab).toHaveAttribute("aria-selected", "true"); - await expect( - page.getByRole("tabpanel", { name: "프리미티브" }), - ).toContainText("native semantics"); -}); diff --git a/tests/e2e/generated-feature.spec.ts b/tests/e2e/generated-feature.spec.ts new file mode 100644 index 00000000..f80d424f --- /dev/null +++ b/tests/e2e/generated-feature.spec.ts @@ -0,0 +1,371 @@ +import AxeBuilder from "@axe-core/playwright"; +import type { Page, Route } from "@playwright/test"; + +import { KO_MESSAGES } from "../../src/presentation/i18n/catalog.ts"; +import { expect, test } from "../support/browser/strict-browser-test.ts"; +import { + prepareFixtureBuilds, + removeFixtureBuilds, + type FixtureBuilds, +} from "./support/fixture-builds.ts"; +import { + addGeneratedFeature, + generatedFeature, + routePath, + type GeneratedFeature, +} from "../../scripts/lib/generated-feature.ts"; +import { startBuildServer } from "./support/service-worker-builds.ts"; + +/** + * 2026-11-07. One feature in a real browser: its protected route through the + * local demo sign-in, its list read through the production codec, mapper and + * query cache, its form, and its save through the production command path + * with the idempotency key. These ran on the template's reference sample + * until it was deleted; now they run on the feature `create:feature` writes + * (`--with-create --keyed`), built into a copy of the repository + * (scripts/lib/generated-feature.ts). The API answers are the paired backend's + * Envelope, written out as in the generated feature's own tests. + */ +const META = Object.freeze({ requestId: "req-e2e", traceId: "0af7651916cd43dd8448eb211c80319c" }); +const ITEM = Object.freeze({ id: "browser-order", name: "Browser order" }); +const WCAG_TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]; + +let builds: FixtureBuilds<"a"> | undefined; +let server: Awaited> | undefined; +let feature: GeneratedFeature; + +test.beforeAll(async () => { + test.setTimeout(300_000); + builds = await prepareFixtureBuilds("generated-feature", [ + { name: "a", edit: addGeneratedFeature }, + ]); + feature = generatedFeature(builds.root); + server = await startBuildServer({ a: builds.dist.a, b: builds.dist.a }); +}); + +test.afterAll(async () => { + await server?.close(); + await removeFixtureBuilds(builds); +}); + +const words = () => feature.messages["ko-KR"]; +const word = (key: string) => { + const value = words()[key]; + if (value === undefined) throw new Error(`the generated catalog has no ${key}`); + return value; +}; + +function envelope(data: unknown) { + return { success: true, data, meta: META }; +} + +function failure(code: string, retryable: boolean) { + return { + success: false, + error: { code, category: "SYSTEM", message: "backend message", retryable }, + meta: META, + }; +} + +/** Answers the list read and, by id, the item read. */ +async function answerReads(page: Page, list: readonly unknown[] = [ITEM]) { + const collection = new URL(feature.api).pathname; + await page.route( + (url) => url.origin === new URL(feature.api).origin && url.pathname.startsWith(collection), + async (route) => { + const request = route.request(); + if (request.method() !== "GET") return route.fallback(); + const { pathname } = new URL(request.url()); + return pathname === collection + ? route.fulfill({ json: envelope(list) }) + : route.fulfill({ json: envelope({ ...ITEM, id: pathname.slice(collection.length + 1) }) }); + }, + ); +} + +type CreateCall = Readonly<{ name: unknown; idempotencyKey: string | null }>; + +/** Answers each create with the next responder and records what was sent. */ +async function answerCreates( + page: Page, + responders: readonly ((route: Route) => Promise)[], +): Promise { + const calls: CreateCall[] = []; + await page.route(feature.api, async (route) => { + const request = route.request(); + if (request.method() !== "POST") return route.fallback(); + calls.push({ + name: (request.postDataJSON() as { name?: unknown }).name, + idempotencyKey: await request.headerValue("idempotency-key"), + }); + const respond = responders[calls.length - 1]; + if (!respond) throw new Error(`unexpected create call ${calls.length}`); + await respond(route); + }); + return calls; +} + +const created = (route: Route) => + route.fulfill({ + status: 201, + headers: { Location: `${feature.api}/${ITEM.id}` }, + json: envelope(ITEM), + }); + +async function signInAt(page: Page, path: string, heading: string) { + if (!server) throw new Error("The generated feature's build is not served."); + await page.goto(`${server.origin}${path}`); + await expect(page.getByRole("heading", { level: 1 })).toHaveText( + KO_MESSAGES["route.auth.required.title"], + ); + await page.getByRole("button", { name: KO_MESSAGES["action.signIn"] }).click(); + await expect(page.getByRole("heading", { level: 1 })).toHaveText(heading); +} + +const openForm = (page: Page) => signInAt(page, routePath(feature.create), word("order.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") }); + +async function expectNoBlockingViolations(page: Page) { + const results = await new AxeBuilder({ page }).withTags(WCAG_TAGS).analyze(); + expect( + results.violations.filter((violation) => + ["critical", "serious"].includes(violation.impact ?? ""), + ), + ).toEqual([]); +} + +/** + * 1103/08-02. Saves from the keyboard and checks where focus lands: in the + * status above the form, one Tab away from its first action, not on the body + * after the page turned the save button busy. + */ +async function saveFromKeyboard(page: Page, firstAction: string) { + await nameField(page).fill(ITEM.name); + await saveButton(page).focus(); + await page.keyboard.press("Enter"); + + await expect(page.locator(".page-template__feedback")).toBeFocused(); + await page.keyboard.press("Tab"); + await expect(page.getByRole("button", { name: firstAction })).toBeFocused(); +} + +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")); + + // The closed menu drawer holds a second copy of the status (08-01). + await expect( + page.getByRole("banner").getByText(KO_MESSAGES["shell.session.authenticated"]), + ).toBeVisible(); + // The answered row went through the production codec, mapper and query cache. + await expect(page.getByRole("link", { name: ITEM.name })).toBeVisible(); + }); + + // 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 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).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 expect(main).not.toContainText(/[가-힣]/u); + }); +}); + +test.describe("the form", () => { + test("focuses the first invalid field when a save fails validation", async ({ page }) => { + await openForm(page); + await saveButton(page).click(); + + await expect(nameField(page)).toBeFocused(); + await expect(nameField(page)).toHaveAttribute("aria-invalid", "true"); + await expect(page.getByRole("alert")).toContainText(KO_MESSAGES["form.errorSummary"]); + }); + + test("asks before leaving unsaved input and stays when writing continues", async ({ page }) => { + await openForm(page); + await nameField(page).fill("Unsaved order"); + await page + .getByRole("navigation", { name: KO_MESSAGES["template.breadcrumb"] }) + .getByRole("link", { name: word("order.list.title") }) + .click(); + + const dialog = page.getByRole("dialog", { name: KO_MESSAGES["form.unsaved.title"] }); + await expect(dialog).toBeVisible(); + await dialog.getByRole("button", { name: KO_MESSAGES["action.continueEditing"] }).click(); + await expect(dialog).toBeHidden(); + await expect(nameField(page)).toHaveValue("Unsaved order"); + expect(new URL(page.url()).pathname).toBe(routePath(feature.create)); + }); + + test("keeps the form template within a 320px viewport", async ({ page }) => { + await page.setViewportSize({ width: 320, height: 720 }); + await openForm(page); + const viewport = await page.evaluate(() => ({ + clientWidth: document.documentElement.clientWidth, + scrollWidth: document.documentElement.scrollWidth, + })); + expect(viewport.scrollWidth).toBeLessThanOrEqual(viewport.clientWidth); + }); +}); + +test.describe("the save", () => { + test("saves through the production command path with an idempotency key", async ({ page }) => { + await answerReads(page); + await openForm(page); + const calls = await answerCreates(page, [created]); + + await nameField(page).fill(` ${ITEM.name} `); + await saveButton(page).click(); + + await expect(page.getByRole("heading", { level: 1 })).toHaveText(ITEM.name); + expect(calls).toEqual([{ name: ITEM.name, idempotencyKey: expect.any(String) }]); + }); + + test.describe("after a rate-limited save", () => { + // Chromium and WebKit log a 4xx fetch response to the console, and the + // client cancels the 429 body unread, which Chromium reports as aborted. + test.use({ + allowedBrowserFailure: + /^console:error:.*status of 429|^requestfailed:POST:\/[^:]*:net::ERR_ABORTED$/u, + }); + + const rateLimited = (route: Route) => + route.fulfill({ + status: 429, + headers: { "retry-after": "1" }, + json: failure("RATE_LIMITED", true), + }); + + test("keeps the input and saves on retry", async ({ page }) => { + await answerReads(page); + await openForm(page); + const calls = await answerCreates(page, [rateLimited, created]); + + await nameField(page).fill(ITEM.name); + await saveButton(page).click(); + + await expect(page.getByText(KO_MESSAGES["error.rate_limited"])).toBeVisible(); + await expect(nameField(page)).toHaveValue(ITEM.name); + await page.getByRole("button", { name: KO_MESSAGES["action.retry"] }).click(); + + await expect(page.getByRole("heading", { level: 1 })).toHaveText(ITEM.name); + expect(calls.map((call) => call.name)).toEqual([ITEM.name, ITEM.name]); + }); + + test("keeps keyboard focus in the failure status", async ({ page }) => { + await openForm(page); + await answerCreates(page, [rateLimited]); + + await saveFromKeyboard(page, KO_MESSAGES["action.retry"]); + }); + }); + + test.describe("after a save whose result is unknown", () => { + // The browsers log the 500 response to the console. + test.use({ allowedBrowserFailure: /^console:error:.*status of 500/u }); + + const lost = (route: Route) => + route.fulfill({ + status: 500, + headers: { + "x-correlation-id": "corr-save-500", + "access-control-expose-headers": "x-correlation-id", + }, + json: failure("INTERNAL_ERROR", false), + }); + + // 0929/08-04. The case a user most wants to report shows the id support + // can find in the server logs. + test("shows the result as unknown with the request id support can find", async ({ page }) => { + await openForm(page); + await answerCreates(page, [lost]); + + await nameField(page).fill(ITEM.name); + await saveButton(page).click(); + + await expect(page.getByText(KO_MESSAGES["async.mutationEffectUnknown"])).toBeVisible(); + await expect(page.getByText(/^지원 참조: /u)).toBeVisible(); + }); + + test("keeps keyboard focus in the unknown-result status", async ({ page }) => { + await openForm(page); + await answerCreates(page, [lost]); + + await saveFromKeyboard(page, KO_MESSAGES["action.confirmMutationApplied"]); + }); + + test("resends with the same key from the keyboard and opens the item", async ({ page }) => { + await answerReads(page); + await openForm(page); + const calls = await answerCreates(page, [lost, created]); + await saveFromKeyboard(page, KO_MESSAGES["action.confirmMutationApplied"]); + await page.keyboard.press("Tab"); + await expect( + page.getByRole("button", { name: KO_MESSAGES["action.resendMutation"] }), + ).toBeFocused(); + + await page.keyboard.press("Enter"); + + await expect(page.getByRole("heading", { level: 1 })).toHaveText(ITEM.name); + expect(calls).toHaveLength(2); + expect(calls[1]?.idempotencyKey).toBe(calls[0]?.idempotencyKey); + }); + + // 1105/08-02. Confirming an unknown create opens the list, which shows + // whether the item was saved. + test("opens the list after the user confirms the save from the keyboard", async ({ page }) => { + await answerReads(page); + await openForm(page); + const calls = await answerCreates(page, [lost]); + await saveFromKeyboard(page, KO_MESSAGES["action.confirmMutationApplied"]); + + await page.keyboard.press("Enter"); + + await expect(page.getByRole("heading", { level: 1 })).toHaveText(word("order.list.title")); + await expect(page.getByRole("link", { name: ITEM.name })).toBeVisible(); + expect(calls).toHaveLength(1); + }); + }); +}); + +// 08-05. The protected screens are scanned signed in and in each state they +// can show. The state must be on screen before axe runs. +test.describe("accessibility", () => { + for (const [state, list, visible] of [ + ["success", [ITEM], ITEM.name], + ["empty", [], KO_MESSAGES["async.empty"]], + // A 200 that breaks the response schema: a 5xx would also log a console + // error, which the strict fixture rejects on its own. + ["error", [{ wrong: true }], KO_MESSAGES["error.schema_mismatch"]], + ] 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 expect(page.getByRole("main")).toContainText(visible); + await expectNoBlockingViolations(page); + }); + } + + test("@a11y detail has no blocking violations", async ({ page }) => { + await answerReads(page); + await signInAt(page, routePath(feature.detail, ITEM.id), ITEM.name); + await expectNoBlockingViolations(page); + }); + + test("@a11y form with submit errors has no blocking violations", async ({ page }) => { + await openForm(page); + await saveButton(page).click(); + await expect(page.getByRole("alert")).toContainText(KO_MESSAGES["form.errorSummary"]); + await expectNoBlockingViolations(page); + }); +}); diff --git a/tests/e2e/i18n.spec.ts b/tests/e2e/i18n.spec.ts index 1b663f5c..168bdc33 100644 --- a/tests/e2e/i18n.spec.ts +++ b/tests/e2e/i18n.spec.ts @@ -54,10 +54,12 @@ test("keeps the header selectors as wide as their options in every locale", asyn } }); -// 08-07. The example screens stay outside the catalog on purpose, so their +// 08-07. The platform overview stays outside the catalog on purpose, so its // copy is Korean in every locale. Under en-US a screen reader would read that -// copy with English rules unless the screen names its own language. -test("marks the Korean-only example screens as Korean under another locale", async ({ +// copy with English rules unless the screen names its own language. (The +// example screens that shared this rule were deleted on 2026-11-07; the +// galleries are workshop stories.) +test("marks the Korean-only platform overview as Korean under another locale", async ({ page, }) => { await page.setViewportSize({ width: 1280, height: 800 }); @@ -66,12 +68,7 @@ test("marks the Korean-only example screens as Korean under another locale", asy await expect(page.locator("html")).toHaveAttribute("lang", "en-US"); const navigation = page.getByRole("navigation", { name: "Primary navigation" }); - for (const label of [ - "Platform composition", - "UI components", - "Screen states", - "Authentication", - ]) { + for (const label of ["Platform composition"]) { await navigation.getByRole("link", { name: label }).click(); await expect(page).toHaveTitle(new RegExp(`^${label} `)); await expect(page.locator("main .ui-page").first(), label).toHaveAttribute( diff --git a/tests/e2e/old-tab-chunk-recovery.spec.ts b/tests/e2e/old-tab-chunk-recovery.spec.ts index 60e87ba5..36dc61d1 100644 --- a/tests/e2e/old-tab-chunk-recovery.spec.ts +++ b/tests/e2e/old-tab-chunk-recovery.spec.ts @@ -12,6 +12,10 @@ import { removeFixtureBuilds, type FixtureBuilds, } from "./support/fixture-builds.ts"; +import { + addGeneratedFeature, + generatedFeature, +} from "../../scripts/lib/generated-feature.ts"; import { startBuildServer } from "./support/service-worker-builds.ts"; /** @@ -23,10 +27,11 @@ import { startBuildServer } from "./support/service-worker-builds.ts"; * recovery failure instead. */ -// 1103/09-04. The platform overview is a platform route; the UI gallery is -// a feature route now, reached through its context gateway. Route ids only: -// the page sources are read from build A's Vite manifest, so this spec names -// no feature folder. +// 1103/09-04. The platform overview is a platform route; a feature route is +// reached through its context gateway. The template has no feature, so both +// builds carry the one `create:feature` writes (scripts/lib/generated-feature.ts) +// and the second page is its list. The page sources are read from build A's +// Vite manifest, so this spec names no feature folder. const installedRoutes: Readonly> = ROUTE_REGISTRY; const runtimeContracts: Readonly> = ROUTE_RUNTIME_CONTRACT; @@ -35,8 +40,27 @@ function installedRoute(routeId: string): RouteDefinition { if (!definition) throw new Error(`${routeId} is not installed.`); return definition; } -const PLATFORM = installedRoute("EXAMPLES_PLATFORM"); -const UI = installedRoute("EXAMPLES_UI"); +type ChunkRoute = Readonly<{ + path: string; + chunkId: string; + moduleId: string; + navigationLabel: string; + title: string; +}>; +const platformRoute = installedRoute("EXAMPLES_PLATFORM"); +const PLATFORM: ChunkRoute = Object.freeze({ + path: platformRoute.path, + chunkId: platformRoute.chunkId, + moduleId: runtimeContracts[platformRoute.routeId]!.moduleId, + navigationLabel: platformRoute.navigationLabel!, + title: platformRoute.title, +}); +/** The generated feature's list, read from build A's copy. */ +let featureList: ChunkRoute | undefined; +function FEATURE(): ChunkRoute { + if (!featureList) throw new Error("Fixture builds were not prepared."); + return featureList; +} type ViteManifest = Record< string, @@ -56,13 +80,12 @@ async function viteManifest(dist: string): Promise { } /** The source of a route's page: the dynamic entry named by its module id. */ -function pageSource(manifest: ViteManifest, route: RouteDefinition): string { - const moduleId = runtimeContracts[route.routeId]?.moduleId; +function pageSource(manifest: ViteManifest, route: ChunkRoute): string { const sources = Object.entries(manifest) - .filter(([, entry]) => entry.isDynamicEntry && entry.name === moduleId) + .filter(([, entry]) => entry.isDynamicEntry && entry.name === route.moduleId) .map(([source]) => source); if (sources.length !== 1) { - throw new Error(`Expected one page chunk for ${route.routeId}: ${sources.join(", ")}`); + throw new Error(`Expected one page chunk for ${route.moduleId}: ${sources.join(", ")}`); } return sources[0]!; } @@ -83,12 +106,23 @@ let builds: FixtureBuilds<"a" | "b"> | undefined; test.beforeAll(async () => { test.setTimeout(300_000); builds = await prepareFixtureBuilds("chunk-recovery", [ - { name: "a" }, + { + name: "a", + edit: async (root) => { + await addGeneratedFeature(root); + const { list, messages } = generatedFeature(root); + featureList = Object.freeze({ + ...list, + navigationLabel: messages["ko-KR"][`route.${list.routeId}.navigation`]!, + title: messages["ko-KR"][`route.${list.routeId}.title`]!, + }); + }, + }, { name: "b", edit: async (root) => { const manifest = await viteManifest(path.join(root, "dist-a")); - for (const route of [PLATFORM, UI]) { + for (const route of [PLATFORM, FEATURE()]) { await appendFile( path.join(root, pageSource(manifest, route)), '\n(globalThis as Record).__caFixtureBuild = "b";\n', @@ -114,17 +148,20 @@ async function routeChunk(dist: string, chunkId: string): Promise { // also log the 404 itself (without its URL), Firefox logs the error object // React caught, and WebKit logs its own import error without the URL. Nothing // else is allowed, but for the WebKit warning below. 1103/09-04: the B tab -// misses the UI gallery's context routes module before its page: that module +// misses the feature's context routes module before its page: that module // names B's new page chunk, so its hash changed too. -const MISSING_PAGE = String.raw`/assets/(?:platform-overview-page|ui-gallery-page|context-routes)-[\w-]+\.js`; -const MISSING_PAGE_FAILURES = [ - String.raw`^requestfailed:GET:${MISSING_PAGE}:`, - String.raw`^console:error:TypeError: Failed to fetch dynamically imported module: http://127\.0\.0\.1:\d+${MISSING_PAGE}$`, - String.raw`^console:error:\[JavaScript Error: "Loading module from “http://127\.0\.0\.1:\d+${MISSING_PAGE}” was blocked`, - String.raw`^console:error:Failed to load resource: the server responded with a status of 404 \(Not Found\)$`, - String.raw`^console:error:JSHandle@object$`, - String.raw`^console:error:TypeError: Importing a module script failed\.$`, -]; +function missingPageFailures(): string[] { + const missingPage = String.raw`/assets/(?:${PLATFORM.moduleId}|${FEATURE().moduleId}|context-routes)-[\w-]+\.js`; + return [ + String.raw`^requestfailed:GET:${missingPage}:`, + String.raw`^console:error:TypeError: Failed to fetch dynamically imported module: http://127\.0\.0\.1:\d+${missingPage}$`, + String.raw`^console:error:\[JavaScript Error: "Loading module from “http://127\.0\.0\.1:\d+${missingPage}” was blocked`, + String.raw`^console:error:Failed to load resource: the server responded with a status of 404 \(Not Found\)$`, + String.raw`^console:error:JSHandle@object$`, + String.raw`^console:error:TypeError: Importing a module script failed\.$`, + String.raw`^preloadunused:${missingPage}$`, + ]; +} /** The chunks Vite preloads with `page`: its static imports in `dist`. */ async function preloadedWith(dist: string, page: string): Promise { @@ -145,7 +182,7 @@ async function preloadedWith(dist: string, page: string): Promise { // missing chunk leaves itself and the chunks preloaded with it unused: in the // A tab those of A's platform page (the tab is still on A while recovery // reads the release manifest), in the B tab those of B's context routes -// module for the UI page. The fixture's preload check reports them in every +// module for the feature's list page. The fixture's preload check reports them in every // engine (WebKit's own three-second warning only did when its timer ran // before the test ended). They are the provoked failure's own effect; only // those chunks are allowed. @@ -158,14 +195,13 @@ test.use({ ...(await preloadedWith(builds.dist.a, pageSource(aManifest, PLATFORM))), ...(await preloadedWith( builds.dist.b, - routesSource(bManifest, pageSource(bManifest, UI)), + routesSource(bManifest, pageSource(bManifest, FEATURE())), )), ].map((file) => file.replaceAll(".", String.raw`\.`)); await provide( new RegExp( [ - ...MISSING_PAGE_FAILURES, - String.raw`^preloadunused:${MISSING_PAGE}$`, + ...missingPageFailures(), String.raw`^preloadunused:/(?:${files.join("|")})$`, ].join("|"), "u", @@ -180,15 +216,15 @@ test("an old tab reloads once into the new build, then stops reloading", async ( if (!builds) throw new Error("Fixture builds were not prepared."); const aPlatform = await routeChunk(builds.dist.a, PLATFORM.chunkId); const bPlatform = await routeChunk(builds.dist.b, PLATFORM.chunkId); - const bUi = await routeChunk(builds.dist.b, UI.chunkId); + const bFeature = await routeChunk(builds.dist.b, FEATURE().chunkId); expect(bPlatform).not.toBe(aPlatform); - expect(bUi).not.toBe(await routeChunk(builds.dist.a, UI.chunkId)); + expect(bFeature).not.toBe(await routeChunk(builds.dist.a, FEATURE().chunkId)); const server = await startBuildServer(builds.dist); try { await page.goto(`${server.origin}/`); await expect( - page.getByRole("link", { name: PLATFORM.navigationLabel!, exact: true }), + page.getByRole("link", { name: PLATFORM.navigationLabel, exact: true }), ).toBeVisible(); let loads = 0; page.on("load", () => { @@ -198,7 +234,7 @@ test("an old tab reloads once into the new build, then stops reloading", async ( // Build B is deployed while the A tab stays open. server.serve("b"); await page - .getByRole("link", { name: PLATFORM.navigationLabel!, exact: true }) + .getByRole("link", { name: PLATFORM.navigationLabel, exact: true }) .click(); await expect(page.getByRole("heading", { name: PLATFORM.title })).toBeVisible(); @@ -212,13 +248,13 @@ test("an old tab reloads once into the new build, then stops reloading", async ( // The replicas alternate: the B tab now meets A, which lacks B's chunk. server.serve("a"); - await page.getByRole("link", { name: UI.navigationLabel!, exact: true }).click(); + await page.getByRole("link", { name: FEATURE().navigationLabel, exact: true }).click(); await expect(page.getByRole("alert")).toContainText( "화면 자산을 복구하지 못했습니다.", ); expect(loads).toBe(1); - expect(page.url()).toBe(`${server.origin}${UI.path}`); + expect(page.url()).toBe(`${server.origin}${FEATURE().path}`); } finally { await server.close(); } diff --git a/tests/e2e/preload-use.spec.ts b/tests/e2e/preload-use.spec.ts index b51d4545..3652cf11 100644 --- a/tests/e2e/preload-use.spec.ts +++ b/tests/e2e/preload-use.spec.ts @@ -1,10 +1,18 @@ import { readFile } from "node:fs/promises"; +import path from "node:path"; import { expect, test, type Page } from "@playwright/test"; +import { addGeneratedFeature } from "../../scripts/lib/generated-feature.ts"; import { testRunPath } from "../../scripts/lib/run-isolation.ts"; import { trackPreloadUse } from "../support/browser/preload-use.ts"; import { test as strictTest } from "../support/browser/strict-browser-test.ts"; +import { + prepareFixtureBuilds, + removeFixtureBuilds, + type FixtureBuilds, +} from "./support/fixture-builds.ts"; +import { startBuildServer } from "./support/service-worker-builds.ts"; /** * 1103/11-09. The strict browser fixture ignores WebKit's "preloaded using @@ -23,14 +31,28 @@ type ManifestEntry = Readonly<{ isEntry?: boolean; }>; -/** The build the preview serves: this run's own under TEST_RUN_ID (1105/12-04). */ -async function buildManifest(): Promise>> { - return JSON.parse(await readFile(testRunPath("dist/.vite/manifest.json"), "utf8")) as Record< +/** + * The build the preview serves: this run's own under TEST_RUN_ID (1105/12-04), + * or `dist`. + */ +async function buildManifest( + dist = testRunPath("dist"), +): Promise>> { + return JSON.parse(await readFile(path.join(dist, ".vite/manifest.json"), "utf8")) as Record< string, ManifestEntry >; } +/** The platform overview has drawn its contract tables, or their empty state. */ +async function expectContractTables(page: Page): Promise { + await expect( + page + .getByRole("table", { name: "설치된 HTTP 오퍼레이션" }) + .or(page.getByText("설치된 HTTP 오퍼레이션이 없습니다.")), + ).toBeVisible(); +} + function staticClosure( manifest: Readonly>, roots: readonly string[], @@ -106,9 +128,7 @@ test("counts the chunks a route preloads and then runs as used", async ({ .getByRole("navigation", { name: "주요 탐색" }) .getByRole("link", { name: "플랫폼 구성" }) .click(); - await expect( - page.getByRole("table", { name: "설치된 HTTP 오퍼레이션" }), - ).toBeVisible(); + await expectContractTables(page); const result = await preloads.check(); expect(result.preloaded.length).toBeGreaterThan(0); @@ -119,53 +139,76 @@ test("counts the chunks a route preloads and then runs as used", async ({ * The 1103/11-09 failure, made deterministic: the route's runtime chunks are * preloaded right after load, and the chunk that imports the deepest one * arrives 3.5 s later. WebKit's check runs in between and warns about a chunk - * the page then runs. The strict fixture must pass. + * the page then runs. The strict fixture must pass. The template installs no + * feature, so this runs on a build of a copy with the one `create:feature` + * writes (scripts/lib/generated-feature.ts). */ -strictTest( - "passes a route whose deepest preloaded chunk is reached after WebKit's check", - async ({ page }) => { - const manifest = await buildManifest(); - const initial = staticClosure(manifest, [ - ...Object.keys(manifest).filter((key) => manifest[key]?.isEntry), - "src/bootstrap/boot.tsx", - ]); - // A feature runtime's static import that itself imports a chunk the - // boot has not loaded: the module graph reaches that chunk only once - // this one has arrived. - const parent = Object.entries(manifest) - .filter(([key]) => /^src\/features\/[^/]+\/feature-runtime\.ts$/u.test(key)) - .flatMap(([, runtime]) => runtime.imports ?? []) - .find( - (key) => - !initial.has(key) && - (manifest[key]?.imports ?? []).some((child) => !initial.has(child)), - ); - // 1105/11-01. Without that chunk there is nothing to delay and this would - // pass as a plain visit. Point it at another chunk with the same shape, or - // remove the test with a reason. - expect( - parent, - "no feature runtime chunk imports a chunk the boot has not loaded", - ).toBeDefined(); +let featureBuild: FixtureBuilds<"a"> | undefined; - await page.goto("/"); - const file = `/${manifest[parent ?? ""]?.file}`; - await page.route( - (url) => url.pathname === file, - async (route) => { - await new Promise((resolve) => setTimeout(resolve, 3_500)); - await route.fallback(); - }, - ); - await page - .getByRole("navigation", { name: "주요 탐색" }) - .getByRole("link", { name: "플랫폼 구성" }) - .click(); - await expect( - page.getByRole("table", { name: "설치된 HTTP 오퍼레이션" }), - ).toBeVisible({ timeout: 15_000 }); - }, -); +strictTest.describe("with a feature installed", () => { + strictTest.beforeAll(async () => { + strictTest.setTimeout(300_000); + featureBuild = await prepareFixtureBuilds("preload-use", [ + { name: "a", edit: addGeneratedFeature }, + ]); + }); + + strictTest.afterAll(async () => { + await removeFixtureBuilds(featureBuild); + }); + + strictTest( + "passes a route whose deepest preloaded chunk is reached after WebKit's check", + async ({ page }) => { + if (!featureBuild) throw new Error("The feature build was not prepared."); + const manifest = await buildManifest(featureBuild.dist.a); + const initial = staticClosure(manifest, [ + ...Object.keys(manifest).filter((key) => manifest[key]?.isEntry), + "src/bootstrap/boot.tsx", + ]); + // A feature runtime's static import that itself imports a chunk the + // boot has not loaded: the module graph reaches that chunk only once + // this one has arrived. + const parent = Object.entries(manifest) + .filter(([key]) => /^src\/features\/[^/]+\/feature-runtime\.ts$/u.test(key)) + .flatMap(([, runtime]) => runtime.imports ?? []) + .find( + (key) => + !initial.has(key) && + (manifest[key]?.imports ?? []).some((child) => !initial.has(child)), + ); + // 1105/11-01. Without that chunk there is nothing to delay and this would + // pass as a plain visit. Point it at another chunk with the same shape, or + // remove the test with a reason. + expect( + parent, + "no feature runtime chunk imports a chunk the boot has not loaded", + ).toBeDefined(); + + const server = await startBuildServer({ a: featureBuild.dist.a, b: featureBuild.dist.a }); + try { + await page.goto(`${server.origin}/`); + const file = `/${manifest[parent ?? ""]?.file}`; + await page.route( + (url) => url.pathname === file, + async (route) => { + await new Promise((resolve) => setTimeout(resolve, 3_500)); + await route.fallback(); + }, + ); + await page + .getByRole("navigation", { name: "주요 탐색" }) + .getByRole("link", { name: "플랫폼 구성" }) + .click(); + await expect( + page.getByRole("table", { name: "설치된 HTTP 오퍼레이션" }), + ).toBeVisible({ timeout: 15_000 }); + } finally { + await server.close(); + } + }, + ); +}); /** * 1105/11-01. The tests above prove the tracker. These prove the strict diff --git a/tests/e2e/production-csp.spec.ts b/tests/e2e/production-csp.spec.ts index c4065fd6..19b180e3 100644 --- a/tests/e2e/production-csp.spec.ts +++ b/tests/e2e/production-csp.spec.ts @@ -63,10 +63,10 @@ test("boots and changes route under the production security headers", async ({ p await page .getByRole("navigation", { name: "주요 탐색" }) - .getByRole("link", { name: "화면 상태" }) + .getByRole("link", { name: "플랫폼 구성" }) .click(); await expect( - page.getByRole("heading", { level: 1, name: "화면 상태" }), + page.getByRole("heading", { level: 1, name: "플랫폼 구성" }), ).toBeFocused(); expect(await cspViolations(page)).toEqual([]); diff --git a/tests/e2e/reference-form.spec.ts b/tests/e2e/reference-form.spec.ts deleted file mode 100644 index ce00a5c0..00000000 --- a/tests/e2e/reference-form.spec.ts +++ /dev/null @@ -1,150 +0,0 @@ -import AxeBuilder from "@axe-core/playwright"; -import type { Page } from "@playwright/test"; -import { expect, test } from "../support/browser/strict-browser-test.ts"; - -async function openReferenceForm(page: Page) { - await page.goto("/examples/reference-resources/new"); - await page.getByRole("button", { name: "로그인 시작" }).click(); - await expect( - page.getByRole("heading", { name: "Reference resource 만들기" }), - ).toBeVisible(); -} - -test("validates a reference form and focuses the first invalid field", async ({ - page, -}) => { - await openReferenceForm(page); - await page.getByRole("button", { name: "저장" }).click(); - - const firstField = page.getByRole("textbox", { name: /새 항목 이름/ }); - await expect(firstField).toBeFocused(); - await expect(firstField).toHaveAttribute("aria-invalid", "true"); - await expect(page.getByRole("alert")).toContainText("입력 내용을 확인해 주세요."); -}); - -test("guards dirty cancellation and restores focus when writing continues", async ({ - page, -}) => { - await openReferenceForm(page); - await page - .getByRole("textbox", { name: /새 항목 이름/ }) - .fill("Unsaved reference"); - const cancel = page.getByRole("button", { name: "취소" }); - await cancel.click(); - - await expect( - page.getByRole("dialog", { name: "저장하지 않은 변경이 있습니다." }), - ).toBeVisible(); - await page.getByRole("button", { name: "계속 작성" }).click(); - await expect(cancel).toBeFocused(); - await expect(page).toHaveURL(/\/examples\/reference-resources\/new$/); -}); - -test("keeps the form template within a 320px viewport", async ({ page }) => { - await page.setViewportSize({ width: 320, height: 720 }); - await openReferenceForm(page); - const viewport = await page.evaluate(() => ({ - clientWidth: document.documentElement.clientWidth, - scrollWidth: document.documentElement.scrollWidth, - })); - expect(viewport.scrollWidth).toBeLessThanOrEqual(viewport.clientWidth); -}); - -// 08-04. Feature screens take their words from the catalog. This lives with -// the sample's specs so removing the sample removes it too. -test("renders the reference screens without Korean copy in en-US", async ({ - page, -}) => { - await page.route("http://localhost:8080/api/reference-resources?*", (route) => - route.fulfill({ - json: [ - { - id: "browser-reference", - name: "Browser reference", - createdAt: "2026-07-26T00:00:00.000Z", - }, - ], - }), - ); - await page.goto("/examples/reference-resources"); - await page.getByRole("button", { name: "로그인 시작" }).click(); - await expect(page.getByRole("link", { name: "Browser reference" })).toBeVisible(); - await page.getByRole("combobox", { name: "언어" }).selectOption("en-US"); - - const main = page.getByRole("main"); - await expect(main.getByRole("status")).toHaveText("Total items: 1"); - await expect(main).not.toContainText(/[가-힣]/); - - await main.getByRole("button", { name: "Create item" }).click(); - await expect(main.getByRole("button", { name: "Save" })).toBeVisible(); - await expect(main).not.toContainText(/[가-힣]/); -}); - -const LIST_PATH = "/examples/reference-resources"; -const LIST_API = "http://localhost:8080/api/reference-resources?*"; -const BROWSER_REFERENCE = { - id: "browser-reference", - name: "Browser reference", - createdAt: "2026-07-26T00:00:00.000Z", -}; - -async function signInAt(page: Page, path: string, heading: string) { - await page.goto(path); - await page.getByRole("button", { name: "로그인 시작" }).click(); - await expect(page.getByRole("heading", { level: 1 })).toHaveText(heading); -} - -async function expectNoBlockingViolations(page: Page) { - const results = await new AxeBuilder({ page }) - .withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]) - .analyze(); - expect( - results.violations.filter((violation) => - ["critical", "serious"].includes(violation.impact ?? ""), - ), - ).toEqual([]); -} - -// 08-05. The protected reference screens are scanned signed in and in each -// state they can show. The state must be on screen before axe runs. -for (const [state, payload, visible] of [ - ["success", [BROWSER_REFERENCE], "Browser reference"], - ["empty", [], "표시할 항목이 없습니다."], - // A 200 that breaks the response schema: a 5xx would also log a console - // error, which the strict fixture rejects on its own. - ["error", [{ wrong: true }], "서버 응답 데이터가 현재 화면과 맞지 않습니다."], -] as const) { - test(`@a11y reference list ${state} state has no blocking violations`, async ({ - page, - }) => { - await page.route(LIST_API, (route) => route.fulfill({ json: payload })); - await signInAt(page, LIST_PATH, "참조 기능"); - await expect(page.getByRole("main")).toContainText(visible); - await expectNoBlockingViolations(page); - }); -} - -test("@a11y reference detail has no blocking violations", async ({ page }) => { - await page.route( - "http://localhost:8080/api/reference-resources/browser-reference", - (route) => route.fulfill({ json: BROWSER_REFERENCE }), - ); - await signInAt(page, `${LIST_PATH}/items/browser-reference`, "Browser reference"); - await expectNoBlockingViolations(page); -}); - -test("@a11y reference form with submit errors has no blocking violations", async ({ - page, -}) => { - await signInAt(page, `${LIST_PATH}/new`, "Reference resource 만들기"); - await page.getByRole("button", { name: "저장" }).click(); - await expect(page.getByRole("alert")).toContainText("입력 내용을 확인해 주세요."); - await expectNoBlockingViolations(page); -}); - -test("@a11y reference status page has no blocking violations", async ({ - page, -}) => { - await signInAt(page, `${LIST_PATH}/status`, "잠시 사용할 수 없습니다."); - await expectNoBlockingViolations(page); -}); diff --git a/tests/e2e/reference-route.spec.ts b/tests/e2e/reference-route.spec.ts deleted file mode 100644 index e1065b7d..00000000 --- a/tests/e2e/reference-route.spec.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { expect, test } from "../support/browser/strict-browser-test.ts"; -import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts"; - -test("opens the protected integration route through the local demo seam", async ({ - page, -}) => { - const protectedRoute = ROUTE_REGISTRY.REFERENCE_RESOURCE_LIST; - await page.route( - "http://localhost:8080/api/reference-resources?*", - (route) => - route.fulfill({ - json: [ - { - id: "browser-reference", - name: "Browser reference", - createdAt: "2026-07-26T00:00:00.000Z", - }, - ], - }), - ); - await page.goto(protectedRoute.path); - await expect( - page.getByRole("heading", { name: "세션이 필요합니다." }), - ).toBeVisible(); - - await page.getByRole("button", { name: "로그인 시작" }).click(); - - // The h1 comes from the ko-KR message catalog, not the route title (0929/08-02). - await expect( - page.getByRole("heading", { level: 1, name: "참조 기능" }), - ).toBeVisible(); - // The closed menu drawer holds a second copy of the status (08-01). - await expect(page.getByRole("banner").getByText("인증됨")).toBeVisible(); - // The mocked row went through the production codec, mapper and query cache. - await expect(page.getByText("Browser reference")).toBeVisible(); -}); diff --git a/tests/e2e/reference-save.spec.ts b/tests/e2e/reference-save.spec.ts deleted file mode 100644 index deef6d4c..00000000 --- a/tests/e2e/reference-save.spec.ts +++ /dev/null @@ -1,237 +0,0 @@ -import type { Page, Route } from "@playwright/test"; -import { expect, test } from "../support/browser/strict-browser-test.ts"; - -const CREATE_URL = "http://localhost:8080/api/reference-resources"; - -type CreateCall = Readonly<{ name: unknown; idempotencyKey: string | null }>; - -async function openForm(page: Page) { - await page.route(`${CREATE_URL}?*`, (route) => route.fulfill({ json: [] })); - await page.goto("/examples/reference-resources/new"); - await page.getByRole("button", { name: "로그인 시작" }).click(); - await expect( - page.getByRole("heading", { name: "Reference resource 만들기" }), - ).toBeVisible(); -} - -/** Answers each POST with the next responder and records what was sent. */ -async function routeCreate( - page: Page, - responders: readonly ((route: Route) => Promise)[], -): Promise { - const calls: CreateCall[] = []; - await page.route(CREATE_URL, async (route) => { - const request = route.request(); - if (request.method() !== "POST") return route.fallback(); - calls.push({ - name: (request.postDataJSON() as { name?: unknown }).name, - idempotencyKey: await request.headerValue("idempotency-key"), - }); - const respond = responders[calls.length - 1]; - if (!respond) throw new Error(`unexpected create call ${calls.length}`); - await respond(route); - }); - return calls; -} - -/** - * 1103/08-02. Saves from the keyboard and checks where focus lands: in the - * failure status above the form, one Tab away from its first action, not on - * the body after the page disabled the save button. - */ -async function saveFromKeyboard(page: Page, expectedFirstAction: string) { - await page - .getByRole("textbox", { name: /새 항목 이름/ }) - .fill("Saved in the browser"); - await page.getByRole("button", { name: "저장" }).focus(); - await page.keyboard.press("Enter"); - - await expect(page.locator(".page-template__feedback")).toBeFocused(); - await page.keyboard.press("Tab"); - await expect( - page.getByRole("button", { name: expectedFirstAction }), - ).toBeFocused(); -} - -const created = (route: Route) => - route.fulfill({ - status: 201, - json: { - id: "browser-created", - name: "Saved in the browser", - createdAt: "2026-07-26T00:00:00.000Z", - }, - }); - -test("saves a new reference resource through the production command path", async ({ - page, -}) => { - await openForm(page); - const calls = await routeCreate(page, [created]); - - await page - .getByRole("textbox", { name: /새 항목 이름/ }) - .fill("Saved in the browser"); - await page.getByRole("button", { name: "저장" }).click(); - - await expect(page.getByRole("status")).toHaveText("저장했습니다."); - expect(calls).toHaveLength(1); - expect(calls[0]?.name).toBe("Saved in the browser"); - expect(calls[0]?.idempotencyKey).toBeTruthy(); -}); - -test.describe("after a rate-limited save", () => { - // Chromium and WebKit log a 4xx fetch response to the console, and the - // client cancels the 429 body unread, which Chromium reports as aborted. - test.use({ - allowedBrowserFailure: - /^console:error:.*status of 429|^requestfailed:POST:\/api\/reference-resources:net::ERR_ABORTED$/u, - }); - - test("keeps the input and saves on retry", async ({ page }) => { - await openForm(page); - const calls = await routeCreate(page, [ - (route) => - route.fulfill({ - status: 429, - headers: { "retry-after": "1" }, - json: { title: "Too many requests" }, - }), - created, - ]); - - const name = page.getByRole("textbox", { name: /새 항목 이름/ }); - await name.fill("Saved in the browser"); - await page.getByRole("button", { name: "저장" }).click(); - - await expect( - page.getByText("요청이 많습니다. 잠시 후 다시 시도해 주세요."), - ).toBeVisible(); - await expect(name).toHaveValue("Saved in the browser"); - await page.getByRole("button", { name: "다시 시도" }).click(); - - await expect(page.getByRole("status")).toHaveText("저장했습니다."); - expect(calls.map((call) => call.name)).toEqual([ - "Saved in the browser", - "Saved in the browser", - ]); - }); - - test("keeps keyboard focus in the failure status", async ({ page }) => { - await openForm(page); - await routeCreate(page, [ - (route) => - route.fulfill({ - status: 429, - headers: { "retry-after": "1" }, - json: { title: "Too many requests" }, - }), - ]); - - await saveFromKeyboard(page, "다시 시도"); - }); - - // 1105/08-01. The retry button goes away with the status once the save - // succeeds; focus stays in the feedback area, not on the body. - test("keeps keyboard focus in the feedback after retrying from the keyboard", async ({ - page, - }) => { - await openForm(page); - await routeCreate(page, [ - (route) => - route.fulfill({ - status: 429, - headers: { "retry-after": "1" }, - json: { title: "Too many requests" }, - }), - created, - ]); - await saveFromKeyboard(page, "다시 시도"); - - await page.keyboard.press("Enter"); - - await expect(page.getByRole("status")).toHaveText("저장했습니다."); - await expect(page.locator(".page-template__feedback")).toBeFocused(); - }); -}); - -test.describe("after a save whose result is unknown", () => { - // The browsers log the 500 response to the console. - test.use({ - allowedBrowserFailure: /^console:error:.*status of 500/u, - }); - - // 0929/08-04. The case a user most wants to report shows the id support - // can find in the server logs. - test("shows the request id the server echoed", async ({ page }) => { - await openForm(page); - await routeCreate(page, [ - (route) => - route.fulfill({ - status: 500, - headers: { - "x-correlation-id": "corr-save-500", - "access-control-expose-headers": "x-correlation-id", - }, - json: { title: "Internal error" }, - }), - ]); - - await page - .getByRole("textbox", { name: /새 항목 이름/ }) - .fill("Saved in the browser"); - await page.getByRole("button", { name: "저장" }).click(); - - await expect(page.getByText("변경 결과를 확인할 수 없습니다.")).toBeVisible(); - await expect(page.getByText("지원 참조: corr-save-500")).toBeVisible(); - }); - - test("keeps keyboard focus in the unknown-result status", async ({ page }) => { - await openForm(page); - await routeCreate(page, [ - (route) => route.fulfill({ status: 500, json: { title: "Internal error" } }), - ]); - - await saveFromKeyboard(page, "변경됨으로 확인"); - }); - - // 1105/08-01. Confirming or resending removes the button that had focus; - // focus stays in the feedback area that shows the result. - test("keeps keyboard focus in the feedback after confirming from the keyboard", async ({ - page, - }) => { - await openForm(page); - const calls = await routeCreate(page, [ - (route) => route.fulfill({ status: 500, json: { title: "Internal error" } }), - ]); - await saveFromKeyboard(page, "변경됨으로 확인"); - - await page.keyboard.press("Enter"); - - await expect(page.getByRole("status")).toHaveText("저장했습니다."); - await expect(page.locator(".page-template__feedback")).toBeFocused(); - expect(calls).toHaveLength(1); - }); - - test("keeps keyboard focus in the feedback after resending from the keyboard", async ({ - page, - }) => { - await openForm(page); - const calls = await routeCreate(page, [ - (route) => route.fulfill({ status: 500, json: { title: "Internal error" } }), - created, - ]); - await saveFromKeyboard(page, "변경됨으로 확인"); - await page.keyboard.press("Tab"); - await expect( - page.getByRole("button", { name: "같은 요청으로 다시 보내기" }), - ).toBeFocused(); - - await page.keyboard.press("Enter"); - - await expect(page.getByRole("status")).toHaveText("저장했습니다."); - await expect(page.locator(".page-template__feedback")).toBeFocused(); - expect(calls).toHaveLength(2); - expect(calls[1]?.idempotencyKey).toBe(calls[0]?.idempotencyKey); - }); -}); diff --git a/tests/e2e/responsive.spec.ts b/tests/e2e/responsive.spec.ts index 574fadab..215322f4 100644 --- a/tests/e2e/responsive.spec.ts +++ b/tests/e2e/responsive.spec.ts @@ -1,12 +1,14 @@ import { expect, test } from "../support/browser/strict-browser-test.ts"; -test("reflows the UI gallery at the 320px minimum without horizontal overflow", async ({ +// The gallery's own 320px reflow is a workshop check +// (tests/storybook/galleries.spec.ts); this one is the shell around a page. +test("reflows the shell at the 320px minimum without horizontal overflow", async ({ page, }) => { await page.setViewportSize({ width: 320, height: 720 }); - await page.goto("/examples/ui"); + await page.goto("/"); await expect( - page.getByRole("heading", { level: 1, name: "UI 구성요소" }), + page.getByRole("heading", { level: 1, name: "Clean Architecture Frontend" }), ).toBeVisible(); await expect( page.getByRole("button", { name: "메뉴", exact: true }), @@ -55,11 +57,11 @@ for (const width of [320, 375, 640]) { }); } -test("keeps desktop navigation and two-column examples at wide viewports", async ({ +test("keeps desktop navigation and two-column sections at wide viewports", async ({ page, }) => { await page.setViewportSize({ width: 1440, height: 900 }); - await page.goto("/examples/ui"); + await page.goto("/examples/platform"); await expect(page.getByRole("navigation", { name: "주요 탐색" })).toBeVisible(); await expect( diff --git a/tests/e2e/scroll-restoration.spec.ts b/tests/e2e/scroll-restoration.spec.ts index f4f99d81..4ba4412d 100644 --- a/tests/e2e/scroll-restoration.spec.ts +++ b/tests/e2e/scroll-restoration.spec.ts @@ -3,30 +3,35 @@ import { expect, test, type Page } from "../support/browser/strict-browser-test. const scrollY = (page: Page) => page.evaluate(() => Math.round(window.scrollY)); // 08-08. Back restores where the user was; a new route starts at the top. +// The platform overview is the template's long page; its contract tables +// fill in after the title, so the test waits for them before it scrolls. test("restores the scroll position when navigating back", async ({ page }) => { const heading = page.getByRole("heading", { level: 1 }); - await page.goto("/examples/ui"); - await expect(heading).toHaveText("UI 구성요소"); + await page.goto("/examples/platform"); + await expect(heading).toHaveText("플랫폼 구성"); + await expect(page.locator("main [aria-busy='true']")).toHaveCount(0); await page.evaluate(() => window.scrollTo(0, 900)); await expect.poll(() => scrollY(page)).toBe(900); await page .getByRole("navigation", { name: "주요 탐색" }) - .getByRole("link", { name: "화면 상태" }) + .getByRole("link", { name: "홈" }) .click(); - await expect(heading).toHaveText("화면 상태"); + await expect(heading).toHaveText("Clean Architecture Frontend"); await expect.poll(() => scrollY(page)).toBe(0); await page.goBack(); - await expect(heading).toHaveText("UI 구성요소"); + await expect(heading).toHaveText("플랫폼 구성"); await expect.poll(() => scrollY(page)).toBe(900); }); +// The first section: the contract tables below it fill in after the page +// draws, and WebKit, which has no scroll anchoring, moves a target below them. test("opens a hash link at its target below the sticky header", async ({ page, }) => { - await page.goto("/examples/ui#tokens-title"); - const target = page.locator("#tokens-title"); + await page.goto("/examples/platform#platform-release-title"); + const target = page.locator("#platform-release-title"); await expect(target).toBeInViewport(); const top = await target.evaluate((element) => Math.round(element.getBoundingClientRect().top), diff --git a/tests/e2e/typography.spec.ts b/tests/e2e/typography.spec.ts index fa707b6a..0fc547e0 100644 --- a/tests/e2e/typography.spec.ts +++ b/tests/e2e/typography.spec.ts @@ -6,7 +6,8 @@ import { expect, test } from "../support/browser/strict-browser-test.ts"; test("steps heading size and weight down from h2 to body copy", async ({ page, }) => { - await page.goto("/examples/states"); + // Section titles (h2) and card titles (h3) on the platform overview. + await page.goto("/examples/platform"); await expect(page.getByRole("heading", { level: 1 })).toBeVisible(); const scale = await page.evaluate(() => { diff --git a/tests/e2e/ui-gallery.spec.ts b/tests/e2e/ui-gallery.spec.ts deleted file mode 100644 index c5a45283..00000000 --- a/tests/e2e/ui-gallery.spec.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { expect, test } from "../support/browser/strict-browser-test.ts"; - -test("validates and reports the common text-field flow", async ({ page }) => { - await page.goto("/examples/ui"); - await page.getByRole("button", { name: "입력 확인" }).click(); - - const field = page.getByRole("textbox", { name: "프로젝트 이름" }); - await expect(field).toHaveAttribute("aria-invalid", "true"); - await expect(field).toHaveAccessibleDescription( - /프로젝트 이름을 입력해 주세요/, - ); - - await field.fill("Starter"); - await page.getByRole("button", { name: "입력 확인" }).click(); - await expect(page.getByText("“Starter” 입력을 확인했습니다.")).toBeVisible(); -}); - -test("traps modal interaction and restores focus to the trigger", async ({ - page, -}) => { - await page.goto("/examples/ui"); - const trigger = page.getByRole("button", { name: "모달 열기" }); - await trigger.click(); - - const dialog = page.getByRole("dialog", { name: "연동 확인" }); - await expect(dialog).toBeVisible(); - await expect( - dialog.getByRole("button", { name: "연동 확인 닫기" }), - ).toBeFocused(); - - await page.keyboard.press("Escape"); - await expect(dialog).toBeHidden(); - await expect(trigger).toBeFocused(); -}); diff --git a/tests/features/platform-examples-feature/example-pages.test.tsx b/tests/features/platform-examples-feature/example-pages.test.tsx deleted file mode 100644 index 03e51085..00000000 --- a/tests/features/platform-examples-feature/example-pages.test.tsx +++ /dev/null @@ -1,117 +0,0 @@ -// @vitest-environment jsdom - -import { render, screen, waitFor, within } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; -import { describe, expect, it, vi } from "vitest"; - -import { createAnonymousSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts"; -import { - ROUTE_FEATURE_OWNER, - ROUTE_REGISTRY, -} from "../../../src/features/installed-feature-contracts.ts"; -import { PLATFORM_EXAMPLES_FEATURE_ID } from "../../../src/features/platform-examples-feature/contracts/platform-examples-contract.ts"; -import StateGalleryPage from "../../../src/features/platform-examples-feature/presentation/state-gallery-page.tsx"; -import { ApplicationProvider } from "../../../src/presentation/providers/application-provider.tsx"; -import { PreferenceProviders } from "../../../src/presentation/providers/preference-providers.tsx"; -import { AppRouter } from "../../../src/presentation/routes/app-router.tsx"; -import { createTestApplication } from "../../helpers/create-test-application.ts"; -import { createProductFeaturesStub } from "../../helpers/runtime-capabilities-stub.ts"; - -/** - * The example screens (`/examples/ui`, `/examples/states`, `/examples/auth`) - * are the template's content, not the platform (0929/10-02). 1103/09-04: - * they are `platform-examples-feature`, and this folder goes with it; the - * platform tests run on the test-only feature's pages and keep passing. - */ - -function renderApp( - url: string, - application = createTestApplication(), -) { - window.history.pushState({}, "", url); - return render( - - - - - , - ); -} - -describe("example pages", () => { - it("reaches the UI gallery from the home page's starter actions", async () => { - const user = userEvent.setup(); - renderApp("/"); - - await user.click( - await screen.findByRole("link", { name: "UI 구성요소 보기" }), - ); - - await waitFor(() => - expect( - screen.getByRole("heading", { name: "UI 구성요소", level: 1 }), - ).toHaveFocus(), - ); - }); - - // 1105/08-03. The home page's starter links read the same switch as the - // shell's navigation: switched off at runtime, this feature's screens are - // not offered there, and the next active screens take their place. - it("leaves this feature's screens out of the home page's starter links when it is switched off", async () => { - renderApp( - "/", - createTestApplication({ - productFeatures: createProductFeaturesStub({ - [PLATFORM_EXAMPLES_FEATURE_ID]: "DISABLED_BY_CONFIG", - }), - }), - ); - - const starter = await screen.findByRole("region", { name: "준비된 화면 살펴보기" }); - const starterPaths = within(starter) - .getAllByRole("link") - .map((link) => link.getAttribute("href")); - const ownPaths = Object.values(ROUTE_REGISTRY) - .filter((route) => ROUTE_FEATURE_OWNER[route.routeId] === PLATFORM_EXAMPLES_FEATURE_ID) - .map((route) => route.path); - const [navigation] = screen.getAllByRole("navigation", { name: "주요 탐색" }); - const advertised = within(navigation!) - .getAllByRole("link") - .map((link) => link.getAttribute("href")) - .filter((path) => path !== "/"); - - expect(ownPaths.length).toBeGreaterThan(0); - expect(starterPaths.some((path) => ownPaths.includes(path ?? ""))).toBe(false); - expect(starterPaths).toEqual(advertised.slice(0, 3)); - }); - - it("returns to the current URL with its hash from the auth example page", async () => { - const user = userEvent.setup(); - const beginSignIn = vi.fn(async () => {}); - renderApp( - "/examples/auth#session", - createTestApplication({ - session: { ...createAnonymousSessionAdapter(), beginSignIn }, - }), - ); - - await user.click( - await screen.findByRole("button", { name: "로그인 시작" }), - ); - expect(beginSignIn).toHaveBeenCalledWith("/examples/auth#session"); - }); - - it("nests the state gallery's titles under the card and section around them (08-05)", () => { - render(); - - expect( - screen.getByRole("heading", { name: "아직 표시할 항목이 없습니다.", level: 4 }), - ).toBeVisible(); - expect(screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent)) - .toEqual(expect.arrayContaining(["빈 화면", "복구 가능한 오류"])); - // Access states sit directly under the section's h2. - expect( - screen.queryAllByRole("heading", { level: 2 }).map((h) => h.textContent), - ).toEqual(["비동기 데이터 상태", "접근과 탐색 상태"]); - }); -}); diff --git a/tests/features/platform-examples-feature/ui-gallery-page.test.tsx b/tests/features/platform-examples-feature/ui-gallery-page.test.tsx deleted file mode 100644 index 52db2d3d..00000000 --- a/tests/features/platform-examples-feature/ui-gallery-page.test.tsx +++ /dev/null @@ -1,227 +0,0 @@ -// @vitest-environment jsdom - -import { render, screen, waitFor, within } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; -import { describe, expect, it } from "vitest"; - -import UiGalleryPage from "../../../src/features/platform-examples-feature/presentation/ui-gallery-page.tsx"; -import { LocaleProvider } from "../../../src/presentation/i18n/index.ts"; - -/** - * A starter screen (0929/10-02): `/examples/ui` is template content - * (`platform-examples-feature`, 1103/09-04), and this file goes with it. The primitives have - * their own suites; this one checks what the page wires them to — the - * validation rule, the shared notice line and the show/hide state. - */ - -function renderPage() { - const user = userEvent.setup(); - const view = render( - - - , - ); - // The Alert is a status too; the page's notice line is the ``. - const notice = view.container.querySelector("output.gallery-notice"); - if (!(notice instanceof HTMLOutputElement)) { - throw new Error("The gallery notice output is missing"); - } - return { user, notice }; -} - -describe("starter UI gallery page", () => { - it("renders every gallery section and the colour token swatches", () => { - const { notice } = renderPage(); - - expect( - screen.getByRole("heading", { level: 1, name: "UI 구성요소" }), - ).toBeVisible(); - for (const section of [ - "버튼과 입력", - "폼과 선택 컨트롤", - "피드백과 모달", - "탐색 패턴", - "디자인 토큰", - ]) { - expect(screen.getByRole("region", { name: section })).toBeVisible(); - } - const tokens = screen.getByRole("region", { name: "디자인 토큰" }); - expect(within(tokens).getAllByRole("article")).toHaveLength(7); - expect(within(tokens).getByText("--color-focus")).toBeVisible(); - expect(notice).toHaveAttribute("aria-live", "polite"); - expect(notice).toHaveTextContent( - "구성요소를 조작하면 결과가 여기에 표시됩니다.", - ); - }); - - it("reports each button action on the notice line", async () => { - const { user, notice } = renderPage(); - - await user.click(screen.getByRole("button", { name: "기본 작업" })); - expect(notice).toHaveTextContent("기본 작업을 실행했습니다."); - await user.click(screen.getByRole("button", { name: "보조 작업" })); - expect(notice).toHaveTextContent("보조 작업을 실행했습니다."); - await user.click(screen.getByRole("button", { name: "위험 작업" })); - expect(notice).toHaveTextContent("위험 작업 예제를 선택했습니다."); - expect(screen.getByRole("button", { name: "사용 불가" })).toBeDisabled(); - }); - - it("rejects a blank project name and accepts a trimmed one", async () => { - const { user, notice } = renderPage(); - const field = screen.getByRole("textbox", { name: "프로젝트 이름" }); - const submit = screen.getByRole("button", { name: "입력 확인" }); - - // Untouched: no error yet, even though the field is empty. - expect(field).not.toHaveAttribute("aria-invalid", "true"); - - await user.click(submit); - expect(field).toHaveAttribute("aria-invalid", "true"); - expect(field).toHaveAccessibleDescription( - /프로젝트 이름을 입력해 주세요\./u, - ); - expect(notice).toHaveTextContent("입력값을 확인해 주세요."); - - // Whitespace is still blank. - await user.type(field, " "); - await user.click(submit); - expect(field).toHaveAttribute("aria-invalid", "true"); - - await user.type(field, "Starter "); - expect(field).not.toHaveAttribute("aria-invalid", "true"); - await user.click(submit); - expect(notice).toHaveTextContent("“Starter” 입력을 확인했습니다."); - }); - - it("keeps the form and choice controls controlled by page state", async () => { - const { user } = renderPage(); - - const description = screen.getByRole("textbox", { name: "설명" }); - await user.type(description, "공통 예제"); - expect(description).toHaveValue("공통 예제"); - - const template = screen.getByRole("combobox", { name: "시작 템플릿" }); - expect(template).toHaveValue("application"); - await user.selectOptions(template, "library"); - expect(template).toHaveValue("library"); - - const reviewed = screen.getByRole("checkbox", { - name: "접근성 계약을 확인했습니다.", - }); - expect(reviewed).not.toBeChecked(); - await user.click(reviewed); - expect(reviewed).toBeChecked(); - - expect(screen.getByRole("radio", { name: "여유롭게" })).toBeChecked(); - await user.click(screen.getByRole("radio", { name: "조밀하게" })); - expect(screen.getByRole("radio", { name: "조밀하게" })).toBeChecked(); - expect(screen.getByRole("radio", { name: "여유롭게" })).not.toBeChecked(); - - const notifications = screen.getByRole("switch", { name: "알림 사용" }); - expect(notifications).toBeChecked(); - await user.click(notifications); - expect(notifications).not.toBeChecked(); - - // Native ; the label shows the rounded share. - const readiness = screen.getByRole("progressbar", { name: "설정 준비도" }); - expect(readiness).toHaveAttribute("value", "3"); - expect(readiness).toHaveAttribute("max", "4"); - expect(screen.getByText("75%")).toBeVisible(); - }); - - it("dismisses the alert and shows it again", async () => { - const { user } = renderPage(); - - await user.click( - screen.getByRole("button", { name: "설정이 저장되었습니다. 알림 닫기" }), - ); - expect( - screen.queryByText("설정이 저장되었습니다."), - ).not.toBeInTheDocument(); - - await user.click(screen.getByRole("button", { name: "알림 다시 표시" })); - expect(screen.getByText("설정이 저장되었습니다.")).toBeVisible(); - expect( - screen.queryByRole("button", { name: "알림 다시 표시" }), - ).not.toBeInTheDocument(); - }); - - it("closes the dialog by cancel, close and confirm, and only confirm reports", async () => { - const { user, notice } = renderPage(); - const trigger = screen.getByRole("button", { name: "모달 열기" }); - const initial = notice.textContent; - - await user.click(trigger); - let dialog = screen.getByRole("dialog", { name: "연동 확인" }); - expect(dialog).toHaveAttribute("open"); - await user.click(within(dialog).getByRole("button", { name: "취소" })); - expect(screen.getByRole("dialog", { hidden: true })).not.toHaveAttribute( - "open", - ); - expect(notice).toHaveTextContent(initial ?? ""); - await waitFor(() => expect(trigger).toHaveFocus()); - - await user.click(trigger); - dialog = screen.getByRole("dialog", { name: "연동 확인" }); - await user.click( - within(dialog).getByRole("button", { name: "연동 확인 닫기" }), - ); - expect(screen.getByRole("dialog", { hidden: true })).not.toHaveAttribute( - "open", - ); - expect(notice).toHaveTextContent(initial ?? ""); - - await user.click(trigger); - dialog = screen.getByRole("dialog", { name: "연동 확인" }); - await user.click(within(dialog).getByRole("button", { name: "확인" })); - expect(screen.getByRole("dialog", { hidden: true })).not.toHaveAttribute( - "open", - ); - expect(notice).toHaveTextContent("모달의 확인 작업을 실행했습니다."); - }); - - it("runs the menu actions: one reports on the notice, one pushes a toast", async () => { - const { user, notice } = renderPage(); - const trigger = screen.getByRole("button", { name: "작업 메뉴" }); - - await user.click(trigger); - await user.click(screen.getByRole("menuitem", { name: "상태 확인" })); - expect(notice).toHaveTextContent("메뉴 작업을 실행했습니다."); - expect(screen.queryByRole("menu")).not.toBeInTheDocument(); - - await user.click(trigger); - await user.click(screen.getByRole("menuitem", { name: "Toast 표시" })); - const region = screen.getByRole("region", { name: "알림" }); - expect( - within(region).getByText("예제가 저장되었습니다."), - ).toBeVisible(); - }); - - it("switches tab panels only on explicit activation", async () => { - const { user } = renderPage(); - const tokens = screen.getByRole("tab", { name: "토큰" }); - expect(tokens).toHaveAttribute("aria-selected", "true"); - - tokens.focus(); - await user.keyboard("{ArrowRight}"); - const primitives = screen.getByRole("tab", { name: "프리미티브" }); - expect(primitives).toHaveFocus(); - expect(primitives).toHaveAttribute("aria-selected", "false"); - - await user.keyboard("{Enter}"); - expect(primitives).toHaveAttribute("aria-selected", "true"); - expect( - screen.getByRole("tabpanel", { name: "프리미티브" }), - ).toHaveTextContent("native semantics와 interaction을 닫습니다."); - }); - - it("describes the help button with its tooltip", async () => { - const { user } = renderPage(); - const help = screen.getByRole("button", { name: "도움말" }); - - await user.hover(help); - expect(screen.getByRole("tooltip")).toHaveTextContent( - "이 설명은 필수 정보가 아닙니다.", - ); - expect(help).toHaveAccessibleDescription("이 설명은 필수 정보가 아닙니다."); - }); -}); diff --git a/tests/features/reference-feature/feature-module.test.ts b/tests/features/reference-feature/feature-module.test.ts deleted file mode 100644 index f77b1a01..00000000 --- a/tests/features/reference-feature/feature-module.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { loadFeatureRuntime } from "../../../src/features/feature-module.ts"; -import { REFERENCE_FEATURE_MODULE } from "../../../src/features/reference-feature/feature-module.ts"; -import { formatMessage } from "../../../src/presentation/i18n/index.ts"; - -describe("REFERENCE_FEATURE_MODULE", () => { - it("owns every install-time contribution under one feature id", async () => { - expect(REFERENCE_FEATURE_MODULE.id).toBe("reference-feature"); - expect(REFERENCE_FEATURE_MODULE.contracts).toBeDefined(); - expect(REFERENCE_FEATURE_MODULE.routes).toBeDefined(); - expect(REFERENCE_FEATURE_MODULE.messages).toBeDefined(); - // 15-01. The executable half arrives through loadRuntime. - const runtime = await loadFeatureRuntime(REFERENCE_FEATURE_MODULE); - expect(runtime.featureId).toBe("reference-feature"); - expect(runtime.adapters.length).toBeGreaterThan(0); - expect(runtime.contractContributions.length).toBeGreaterThan(0); - expect(Object.keys(runtime.schemas).length).toBeGreaterThan(0); - }); - - it("types a feature message's parameters from its catalog placeholders", () => { - // 0929/08-03. `check:types:test` is the assertion: the feature declares - // `{count}` only in its catalog, and the typed call must require it. - // @ts-expect-error the catalog's {count} makes the parameter required. - formatMessage("ko-KR", "reference.list.resultCount"); - expect( - formatMessage("ko-KR", "reference.list.resultCount", { count: 1 }), - ).toBe("총 1개 항목"); - }); -}); diff --git a/tests/features/reference-feature/installed-context-routing.test.ts b/tests/features/reference-feature/installed-context-routing.test.ts deleted file mode 100644 index 49a1661c..00000000 --- a/tests/features/reference-feature/installed-context-routing.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { TEMPLATE_APP_MODULE } from "../../../src/apps/template-app.ts"; -import { REFERENCE_FEATURE_CONTRACT } from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts"; -import { createAppRouteModules } from "../../../src/platform/routing/context-route-module.ts"; - -// 16-02. Other installed features bring their own contexts; only the -// reference context is this sample's to check. -const REFERENCE_CONTEXT_ID = "reference-context"; -// X1 (2026-11-04). A product feature may join the reference context -// (`create:feature --context reference-context`) and load its routes with -// it; only the reference feature's own routes are this sample's to check. -const REFERENCE_ROUTE_IDS: ReadonlySet = new Set( - Object.keys(REFERENCE_FEATURE_CONTRACT.routes), -); - -describe("installed context routing", () => { - it("boots one bounded-context entry instead of flattening feature routes", () => { - const modules = createAppRouteModules(TEMPLATE_APP_MODULE); - expect(modules.map((module) => module.id)).toContain(REFERENCE_CONTEXT_ID); - expect(modules.some((module) => module.id === "REFERENCE_RESOURCE_LIST")).toBe(false); - }); - - it("loads the reference feature routes lazily without changing public URLs", async () => { - const context = createAppRouteModules(TEMPLATE_APP_MODULE).find( - (module) => module.id === REFERENCE_CONTEXT_ID, - ); - expect(context).toBeDefined(); - const routes = (await context!.loadRoutes()).filter((route) => - REFERENCE_ROUTE_IDS.has(String(route.id)), - ); - expect(routes.map((route) => [route.id, route.path])).toEqual([ - ["REFERENCE_RESOURCE_LIST", "/examples/reference-resources"], - ["REFERENCE_RESOURCE_DETAIL", "/examples/reference-resources/items/:resourceId"], - ["REFERENCE_RESOURCE_FORM", "/examples/reference-resources/new"], - ["REFERENCE_RESOURCE_STATUS", "/examples/reference-resources/status"], - ]); - }); -}); diff --git a/tests/features/reference-feature/reference-contract.test.ts b/tests/features/reference-feature/reference-contract.test.ts deleted file mode 100644 index c388871f..00000000 --- a/tests/features/reference-feature/reference-contract.test.ts +++ /dev/null @@ -1,210 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; - -import { - buildRouteUrl, - parseRouteInput, -} from "../../../src/presentation/routes/route-codecs.ts"; -import { - mapReferenceResourcePayload, - toReferenceView, -} from "../../../src/features/reference-feature/contracts/reference-mapper.ts"; -import { - CREATE_REFERENCE_RESOURCE_CONTRACT, - GET_REFERENCE_RESOURCE_CONTRACT, - LIST_REFERENCE_RESOURCES_CONTRACT, - REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION, -} from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts"; -import { - REFERENCE_FEATURE_CONTRACT, - REFERENCE_FEATURE_ID, - REFERENCE_RESOURCE_INVALIDATION_TOPIC, -} from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts"; -import { REFERENCE_FEATURE_ROUTE_CODECS } from "../../../src/features/reference-feature/presentation/reference-route-codecs.ts"; -import type { ReferenceFeatureInput } from "../../../src/features/reference-feature/application/reference-feature-api.ts"; -import { createTestApplication } from "../../helpers/create-test-application.ts"; -import { createReferenceFeatureInstalledInput } from "../../../src/features/reference-feature/adapters/create-reference-feature-input.ts"; -import { oneResourceReadRoutes } from "../../../scripts/lib/a11y-data-state.ts"; - -describe("reference feature boundary contracts", () => { - it("propagates uncertain command effect certainty into the application failure", async () => { - const execute = vi.fn(async () => ({ - kind: "CONTRACT_VIOLATION" as const, - violation: { - kind: "SUCCESS_SCHEMA_INVALID" as const, - operation: "VALIDATION" as const, - }, - effect: "MAYBE_APPLIED" as const, - })); - const installed = createReferenceFeatureInstalledInput({ - http: { execute }, - }); - - await expect( - installed.input.createResource({ name: "uncertain" }), - ).resolves.toMatchObject({ - ok: false, - error: { - effect: "MAYBE_APPLIED", - retryable: false, - action: "contact-support", - }, - }); - }); - - it("round-trips one canonical filter through the URL codec", () => { - const filters = { - tags: ["open", "new"], - cursor: "a/b", - limit: 5, - }; - const url = buildRouteUrl( - "REFERENCE_RESOURCE_LIST", - { search: filters }, - REFERENCE_FEATURE_ROUTE_CODECS, - ); - expect(url).toBe( - "/examples/reference-resources?cursor=a%2Fb&limit=5&tags=open&tags=new", - ); - const parsed = parseRouteInput( - "REFERENCE_RESOURCE_LIST", - {}, - new URL(url, "https://app.test").searchParams, - REFERENCE_FEATURE_ROUTE_CODECS, - ); - expect(parsed).toMatchObject({ - success: true, - data: { search: filters }, - }); - }); - - it("rejects unknown search and malformed DTO before mapping", () => { - expect( - parseRouteInput( - "REFERENCE_RESOURCE_LIST", - {}, - new URLSearchParams("unknown=value"), - REFERENCE_FEATURE_ROUTE_CODECS, - ), - ).toEqual({ success: false, code: "ROUTE_SEARCH_INVALID" }); - expect( - LIST_REFERENCE_RESOURCES_CONTRACT.contract.outputValidator.safeParse([ - { id: "unsafe", name: 42 }, - ]), - ).toMatchObject({ success: false }); - }); - - it("normalizes request input and maps only owned domain fields", () => { - expect( - CREATE_REFERENCE_RESOURCE_CONTRACT.contract.inputValidator.safeParse({ - name: " Example ", - }), - ).toMatchObject({ success: true, data: { name: "Example" } }); - const model = mapReferenceResourcePayload({ - id: "reference-1", - name: "Example", - createdAt: "2026-07-26T00:00:00.000Z", - }); - if (!model.ok) throw new Error("expected one model"); - expect(toReferenceView(model.value)).toEqual({ - resourceId: "reference-1", - title: "Example", - createdAt: "2026-07-26T00:00:00.000Z", - }); - }); - - it("owns route and operation contributions in one removable contract", () => { - expect(Object.keys(REFERENCE_FEATURE_CONTRACT.routes)).toEqual([ - "REFERENCE_RESOURCE_LIST", - "REFERENCE_RESOURCE_DETAIL", - "REFERENCE_RESOURCE_FORM", - "REFERENCE_RESOURCE_STATUS", - ]); - expect( - REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION.http.map( - ({ contract }) => contract.operationId, - ), - ).toEqual([ - "LIST_REFERENCE_RESOURCES", - "GET_REFERENCE_RESOURCE", - "CREATE_REFERENCE_RESOURCE", - ]); - expect(GET_REFERENCE_RESOURCE_CONTRACT.contract).toMatchObject({ - pathTemplate: "/api/reference-resources/{resourceId}", - }); - expect(GET_REFERENCE_RESOURCE_CONTRACT.contract.inputValidator.schemaId).toBe( - "ReferenceResourceParams", - ); - expect(GET_REFERENCE_RESOURCE_CONTRACT.frontend.authProfileId).toBe( - "EXTERNAL_BEARER", - ); - }); - - // 1106/11-01. scripts/write-a11y-report.ts fails when a11y.json would count - // these routes as passed: the accessibility spec has no generic answer for a - // read of one resource and scans the page on its failure state only. - it("has one detail page the a11y report expects under notChecked", () => { - expect( - oneResourceReadRoutes( - Object.values(REFERENCE_FEATURE_CONTRACT.routes), - REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION.http, - ), - ).toEqual([ - { - routeId: "REFERENCE_RESOURCE_DETAIL", - operationIds: ["GET_REFERENCE_RESOURCE"], - }, - ]); - }); - - it("contributes an identity-based invalidation graph and an explicit wire version", () => { - expect(REFERENCE_FEATURE_CONTRACT.invalidation).toEqual({ - topics: [REFERENCE_RESOURCE_INVALIDATION_TOPIC], - namespaces: [ - { namespaceId: "reference-resource", namespaceVersion: 1 }, - ], - edges: [ - { - topicId: REFERENCE_RESOURCE_INVALIDATION_TOPIC, - namespace: { - namespaceId: "reference-resource", - namespaceVersion: 1, - }, - }, - ], - }); - expect(REFERENCE_FEATURE_CONTRACT.topicVersions).toEqual([ - { - topicId: REFERENCE_RESOURCE_INVALIDATION_TOPIC, - topicVersion: 1, - }, - ]); - }); - - it("returns the installed input through the typed application registry", () => { - const featureInput = { - listResources: async () => ({ ok: true as const, value: [] }), - createResource: async ({ name }) => ({ - ok: true as const, - value: { - resourceId: "created", - title: name, - createdAt: null, - }, - }), - getResource: async (resourceId) => ({ - ok: true as const, - value: { - resourceId, - title: "Reference", - createdAt: null, - }, - }), - } satisfies ReferenceFeatureInput; - const application = createTestApplication({ - featureInputs: { [REFERENCE_FEATURE_ID]: featureInput }, - }); - - expect(application.features.has(REFERENCE_FEATURE_ID)).toBe(true); - expect(application.features.get(REFERENCE_FEATURE_ID)).toBe(featureInput); - }); -}); diff --git a/tests/features/reference-feature/reference-diagnostics.test.ts b/tests/features/reference-feature/reference-diagnostics.test.ts deleted file mode 100644 index 4307a400..00000000 --- a/tests/features/reference-feature/reference-diagnostics.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; - -import { createContractHttpExecutor } from "../../../src/adapters/http/index.ts"; -import { createHttpObservationProjector } from "../../../src/bootstrap/runtime-adapters.ts"; -import { createReferenceFeatureInstalledInput } from "../../../src/features/reference-feature/adapters/create-reference-feature-input.ts"; - -function scopeSnapshot() { - return Object.freeze({ - generation: 1, - fingerprint: "reference-scope", - identities: Object.freeze({}) as never, - signal: new AbortController().signal, - isCurrent: () => true, - }); -} - -describe("reference feature HTTP diagnostics", () => { - it("preserves route and operation identity through the installed V3 path", async () => { - const record = vi.fn(); - const contractHttp = createContractHttpExecutor({ - baseUrl: "https://api.test", - maxRetryAttempts: 0, - attachCredentials: () => ({ - kind: "READY" as const, - headers: { authorization: "Bearer diagnostics-test-token" }, - }), - fetcher: (async () => - Response.json([ - { id: "reference-1", name: "Reference" }, - ])) as unknown as typeof fetch, - observe: createHttpObservationProjector({ - diagnostics: { record }, - telemetry: { emit: vi.fn() }, - }), - }); - const installed = createReferenceFeatureInstalledInput({ - http: Object.freeze({ - async execute(operation, input, context) { - return contractHttp.execute(operation, input, { - routeId: context.routeId, - scope: scopeSnapshot(), - ...(context.signal === undefined - ? {} - : { signal: context.signal }), - ...(context.intent === undefined - ? {} - : { intent: context.intent }), - }); - }, - }), - }); - - await expect( - installed.input.listResources({ limit: 20 }), - ).resolves.toMatchObject({ ok: true }); - - expect(record).toHaveBeenCalledOnce(); - expect(record).toHaveBeenCalledWith({ - level: "info", - eventId: "http.request.completed", - context: expect.objectContaining({ - route_id: "REFERENCE_RESOURCE_LIST", - operation_id: "LIST_REFERENCE_RESOURCES", - outcome: "SUCCESS", - }), - }); - }); -}); diff --git a/tests/features/reference-feature/reference-error.test.ts b/tests/features/reference-feature/reference-error.test.ts deleted file mode 100644 index 9d459448..00000000 --- a/tests/features/reference-feature/reference-error.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { readFile, readdir } from "node:fs/promises"; -import path from "node:path"; - -import { describe, expect, it } from "vitest"; - -import { createFailure } from "../../../src/contracts/errors.ts"; -import { isAppError } from "../../../src/platform/errors/app-error.ts"; -import { - REFERENCE_ERRORS, - toReferenceError, - type ReferenceError, -} from "../../../src/features/reference-feature/application/reference-error.ts"; - -describe("reference feature-local errors", () => { - it("keeps concrete error kinds feature-local", () => { - const error: ReferenceError = { - kind: "reference.not-found", - category: "domain", - severity: "warning", - retryability: "never", - }; - - expect(isAppError(error)).toBe(true); - for (const known of Object.values(REFERENCE_ERRORS)) { - expect(isAppError(known)).toBe(true); - } - }); - - it("interprets only its own domain outcomes", () => { - expect(toReferenceError(createFailure("NOT_FOUND", "GET_REFERENCE_RESOURCE", 0))).toBe( - REFERENCE_ERRORS.NOT_FOUND, - ); - expect(toReferenceError(createFailure("CONFLICT", "CREATE_REFERENCE_RESOURCE", 0))).toBe( - REFERENCE_ERRORS.CONFLICT, - ); - expect( - toReferenceError(createFailure("NETWORK_UNREACHABLE", "GET_REFERENCE_RESOURCE", 0)), - ).toBeNull(); - }); - - it("is not referenced by any global or central error union", async () => { - const offenders: string[] = []; - const walk = async (directory: string): Promise => { - for (const entry of await readdir(directory, { withFileTypes: true })) { - const target = path.join(directory, entry.name); - if (entry.isDirectory()) { - if (!target.endsWith(path.join("features", "reference-feature"))) { - await walk(target); - } - continue; - } - if (!/\.tsx?$/u.test(entry.name)) continue; - const source = await readFile(target, "utf8"); - if (/reference-error\.ts|ReferenceError\b(?!Boundary)/u.test(source)) { - offenders.push(target); - } - } - }; - await walk(path.resolve("src")); - expect(offenders).toEqual([]); - }); -}); diff --git a/tests/features/reference-feature/reference-fixture-provenance.test.ts b/tests/features/reference-feature/reference-fixture-provenance.test.ts deleted file mode 100644 index c02f1caa..00000000 --- a/tests/features/reference-feature/reference-fixture-provenance.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { - ContractContributionError, - composeContractContributions, -} from "../../../src/contracts/external-contract-runtime.ts"; -import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts"; - -// 07-04 (§4.8). The product-feature rejection is in -// tests/unit/external-contract-runtime.test.ts. -describe("reference template fixture provenance", () => { - it("installs the fixture outside the release contract set", () => { - const composed = composeContractContributions([ - REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION, - ]); - expect(composed.contributions).toHaveLength(1); - expect(composed.externalPackages).toHaveLength(0); - }); - - it("rejects a second fixture contribution from the same feature", () => { - const second = Object.freeze({ - ...REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION, - contributionId: "reference-feature-http-v2", - http: Object.freeze([]), - }); - let reason: string | undefined; - try { - composeContractContributions([REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION, second]); - } catch (error) { - expect(error).toBeInstanceOf(ContractContributionError); - reason = (error as ContractContributionError).reason; - } - expect(reason).toBe( - "reference-feature: only one TEMPLATE_FIXTURE contribution is allowed", - ); - }); -}); diff --git a/tests/features/reference-feature/reference-http-gateway.test.ts b/tests/features/reference-feature/reference-http-gateway.test.ts deleted file mode 100644 index 182fd35c..00000000 --- a/tests/features/reference-feature/reference-http-gateway.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import type { Result } from "../../../src/contracts/result.ts"; -import { createFailure, type AppFailure } from "../../../src/contracts/errors.ts"; -import { - createReferenceHttpGateway, - type ReferenceHttpBinding, -} from "../../../src/features/reference-feature/adapters/reference-http-gateway.ts"; -import type { ReferenceResource } from "../../../src/features/reference-feature/domain/reference-resource.ts"; - -const resources = Object.freeze({ - first: Object.freeze({ - id: "reference-1", - displayName: "First", - createdAt: null, - }), - created: Object.freeze({ - id: "reference-2", - displayName: "Created", - createdAt: "2026-07-26T00:00:00.000Z", - }), -}) satisfies Readonly>; - -type ScriptedResult = Result< - ReferenceResource | readonly ReferenceResource[], - AppFailure ->; - -function scriptedBinding(results: ScriptedResult[]) { - const calls: Array< - readonly [operationId: string, input: unknown, context: unknown] - > = []; - let index = 0; - const execute = (async ( - operationId: string, - input: unknown, - context?: unknown, - ) => { - calls.push([operationId, input, context]); - const result = results[index]; - index += 1; - if (!result) throw new Error("Missing scripted result"); - return result; - }) as ReferenceHttpBinding["execute"]; - - return { - binding: Object.freeze({ execute }) satisfies ReferenceHttpBinding, - calls, - }; -} - -describe("reference HTTP operation gateway", () => { - it("delegates exact typed feature inputs to the capability binding", async () => { - const scripted = scriptedBinding([ - { ok: true, value: [resources.first] }, - { ok: true, value: resources.created }, - { ok: true, value: resources.first }, - ]); - const gateway = createReferenceHttpGateway(scripted.binding); - const signal = new AbortController().signal; - - await expect( - gateway.list({ cursor: "next", limit: 20, tags: ["active"] }, { signal }), - ).resolves.toEqual({ ok: true, value: [resources.first] }); - await expect( - gateway.create({ name: "Created", note: "safe note" }), - ).resolves.toEqual({ ok: true, value: resources.created }); - await expect( - gateway.get("reference-1", { signal }), - ).resolves.toEqual({ ok: true, value: resources.first }); - - expect(scripted.calls).toEqual([ - [ - "LIST_REFERENCE_RESOURCES", - { cursor: "next", limit: 20, tags: ["active"] }, - { signal }, - ], - [ - "CREATE_REFERENCE_RESOURCE", - { name: "Created", note: "safe note" }, - undefined, - ], - [ - "GET_REFERENCE_RESOURCE", - { resourceId: "reference-1" }, - { signal }, - ], - ]); - }); - - it("preserves a capability-normalized failure across the feature gateway", async () => { - const failure = createFailure( - "SCHEMA_MISMATCH", - "GET_REFERENCE_RESOURCE", - 0, - ); - const scripted = scriptedBinding([{ ok: false, error: failure }]); - const gateway = createReferenceHttpGateway(scripted.binding); - - await expect(gateway.get("invalid")).resolves.toEqual({ - ok: false, - error: failure, - }); - }); -}); diff --git a/tests/features/reference-feature/reference-http-problem-mapping.test.ts b/tests/features/reference-feature/reference-http-problem-mapping.test.ts deleted file mode 100644 index 6ead51b4..00000000 --- a/tests/features/reference-feature/reference-http-problem-mapping.test.ts +++ /dev/null @@ -1,249 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { - createFeatureHttpBinding, - type InstalledHttpOperationExecutor, -} from "../../../src/adapters/http/index.ts"; -import { - createReferenceHttpGateway, - REFERENCE_HTTP_OPERATIONS, -} from "../../../src/features/reference-feature/adapters/reference-http-gateway.ts"; -import { CREATE_REFERENCE_RESOURCE_CONTRACT } from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts"; - -function executorReturning( - outcome: Readonly>, -): InstalledHttpOperationExecutor { - const execute = (async () => outcome) as unknown as - InstalledHttpOperationExecutor["execute"]; - return Object.freeze({ execute }); -} - -describe("reference HTTP business problem mapping", () => { - // 백엔드 1101/02-01. The resend waits on this value. - it("carries the Retry-After of an in-flight 409 onto the unknown failure", async () => { - const executor = executorReturning( - Object.freeze({ - kind: "PROBLEM", - problem: Object.freeze({ - type: "https://api.test/problems/idempotent_in_flight", - title: "IDEMPOTENT_IN_FLIGHT", - status: 409, - code: "IDEMPOTENT_IN_FLIGHT", - }), - metadata: Object.freeze({ status: 409, retryAfterMs: 2_000 }), - effect: "MAYBE_APPLIED", - }), - ); - const gateway = createReferenceHttpGateway( - createFeatureHttpBinding(executor, REFERENCE_HTTP_OPERATIONS), - ); - - await expect(gateway.create({ name: "n" })).resolves.toMatchObject({ - ok: false, - error: { - code: "IDEMPOTENT_IN_FLIGHT", - effect: "MAYBE_APPLIED", - retryAfterMs: 2_000, - }, - }); - }); - - it("maps a typed 409 reference problem to the feature-owned business code", async () => { - const executor = executorReturning( - Object.freeze({ - kind: "PROBLEM", - problem: Object.freeze({ - type: "https://example.test/problems/reference-conflict", - title: "Reference conflict", - status: 409, - code: "REFERENCE_NAME_ALREADY_EXISTS", - }), - metadata: Object.freeze({ status: 409 }), - effect: "NOT_APPLIED", - }), - ); - const gateway = createReferenceHttpGateway( - createFeatureHttpBinding(executor, REFERENCE_HTTP_OPERATIONS), - ); - - await expect( - gateway.create({ name: "duplicate" }), - ).resolves.toMatchObject({ - ok: false, - error: { - kind: "CONFLICT", - code: "REFERENCE_NAME_ALREADY_EXISTS", - httpStatus: 409, - }, - }); - }); - - it.each([ - { - status: 409, - code: undefined, - expectedKind: "CONFLICT", - expectedCode: "REFERENCE_RESOURCE_CONFLICT", - }, - { - status: 422, - code: "REFERENCE_NAME_REJECTED", - expectedKind: "VALIDATION_REJECTED", - expectedCode: "REFERENCE_NAME_REJECTED", - }, - { - status: 422, - code: undefined, - expectedKind: "VALIDATION_REJECTED", - expectedCode: "REFERENCE_RESOURCE_REJECTED", - }, - { - status: 400, - code: "REFERENCE_BAD_REQUEST", - expectedKind: "UNKNOWN_CLIENT_FAILURE", - expectedCode: "CONTRACT_PROBLEM", - }, - ] as const)( - "projects create problem status $status through the feature-owned mapper/fallback", - async ({ status, code, expectedKind, expectedCode }) => { - const executor = executorReturning( - Object.freeze({ - kind: "PROBLEM", - problem: Object.freeze({ - type: "https://example.test/problems/reference-" + status, - title: "Reference request rejected", - status, - ...(code === undefined ? {} : { code }), - }), - metadata: Object.freeze({ status }), - effect: "NOT_APPLIED", - }), - ); - const gateway = createReferenceHttpGateway( - createFeatureHttpBinding(executor, REFERENCE_HTTP_OPERATIONS), - ); - - await expect( - gateway.create({ name: "rejected" }), - ).resolves.toMatchObject({ - ok: false, - error: { - kind: expectedKind, - code: expectedCode, - httpStatus: status, - }, - }); - }, - ); - - // 백엔드 1101/02-01. The paired backend refuses both before it runs the - // command (its docs/web/http-contract.md §2). The failure keeps the cause - // code and does not invite a resend. - it.each([ - { - status: 422, - code: "IDEMPOTENT_REQUEST_MISMATCH", - expectedKind: "VALIDATION_REJECTED", - }, - { - // The executor checked the key before sending: the two rules disagree. - status: 400, - code: "IDEMPOTENCY_KEY_INVALID", - expectedKind: "UNKNOWN_CLIENT_FAILURE", - }, - ] as const)( - "keeps the paired backend's $status $code as a not-applied failure", - async ({ status, code, expectedKind }) => { - const executor = executorReturning( - Object.freeze({ - kind: "PROBLEM", - problem: Object.freeze({ - type: "https://api.test/problems/" + code.toLowerCase(), - title: code, - status, - code, - }), - metadata: Object.freeze({ status }), - effect: "NOT_APPLIED", - }), - ); - const gateway = createReferenceHttpGateway( - createFeatureHttpBinding(executor, REFERENCE_HTTP_OPERATIONS), - ); - - await expect(gateway.create({ name: "n" })).resolves.toMatchObject({ - ok: false, - error: { - kind: expectedKind, - code, - httpStatus: status, - effect: "NOT_APPLIED", - retryable: false, - }, - }); - }, - ); - - it("keeps the platform status fallback when the operation has no problem mapper", async () => { - const executor = executorReturning( - Object.freeze({ - kind: "PROBLEM", - problem: Object.freeze({ - type: "https://example.test/problems/not-found", - title: "Not found", - status: 404, - }), - metadata: Object.freeze({ status: 404 }), - effect: "NOT_APPLIED", - }), - ); - const gateway = createReferenceHttpGateway( - createFeatureHttpBinding(executor, REFERENCE_HTTP_OPERATIONS), - ); - - await expect(gateway.get("missing")).resolves.toMatchObject({ - ok: false, - error: { - kind: "NOT_FOUND", - code: "CONTRACT_PROBLEM", - httpStatus: 404, - }, - }); - }); -}); - -describe("reference create problem effect classification (0929/03-01)", () => { - const classify = (status: number, code?: string) => - CREATE_REFERENCE_RESOURCE_CONTRACT.contract.commandEffect.classifyProblem({ - status, - problem: Object.freeze({ - type: "https://api.test/problems/reference", - title: "Reference problem", - status, - ...(code === undefined ? {} : { code }), - }), - }); - - it.each([ - // The first attempt with this key still runs: the key must stay bound. - { status: 409, code: "IDEMPOTENT_IN_FLIGHT", effect: "MAYBE_APPLIED" }, - // An undeclared 409 may hide a running attempt: safe side. - { status: 409, code: "SOMETHING_NEW", effect: "MAYBE_APPLIED" }, - { status: 409, code: undefined, effect: "MAYBE_APPLIED" }, - // The fixture's declared semantic conflict is the only refused 409. - { status: 409, code: "CONFLICT", effect: "NOT_APPLIED" }, - { status: 400, code: undefined, effect: "NOT_APPLIED" }, - { status: 422, code: "VALIDATION_REJECTED", effect: "NOT_APPLIED" }, - // 백엔드 1101/02-01. Refused before the command ran: this request was - // not applied, so the next save may mint a new key. - { status: 422, code: "IDEMPOTENT_REQUEST_MISMATCH", effect: "NOT_APPLIED" }, - { status: 400, code: "IDEMPOTENCY_KEY_INVALID", effect: "NOT_APPLIED" }, - { status: 404, code: "NOT_FOUND", effect: "MAYBE_APPLIED" }, - { status: 503, code: "SERVER_FAILURE", effect: "MAYBE_APPLIED" }, - ] as const)( - "classifies status $status code $code as $effect", - ({ status, code, effect }) => { - expect(classify(status, code)).toBe(effect); - }, - ); -}); diff --git a/tests/features/reference-feature/reference-installed-executor.test.ts b/tests/features/reference-feature/reference-installed-executor.test.ts deleted file mode 100644 index fc19ee80..00000000 --- a/tests/features/reference-feature/reference-installed-executor.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { - type InstalledHttpOperationExecutor, -} from "../../../src/adapters/http/index.ts"; -import { createReferenceFeatureInstalledInput } from "../../../src/features/reference-feature/adapters/create-reference-feature-input.ts"; - -/** - * This assertion is about the reference feature, not about HTTP observability: - * it names the feature's own route ids. It used to live in - * `tests/integration/http-execution-v3-observability.test.ts`, which meant a - * platform integration file imported the removable feature's installed input. - * Removing the feature then left that file importing a deleted module, and the - * removability fixture failed on typecheck, the unit/integration run, coverage - * and residue at once — four symptoms of one misplaced test. - */ -describe("reference feature installed operation executor", () => { - it("preserves the feature route id through the installed operation executor", async () => { - const seen: Array>> = []; - const implementation = async ( - contract: Readonly<{ contract: Readonly<{ operationId: string }> }>, - _input: unknown, - context: Readonly>, - ) => { - seen.push(Object.freeze({ ...context })); - const value = - contract.contract.operationId === "LIST_REFERENCE_RESOURCES" - ? [] - : { - id: "resource-1", - name: "Resource", - }; - return Object.freeze({ - kind: "SUCCESS" as const, - value, - metadata: Object.freeze({ status: 200 }), - effect: "NOT_APPLICABLE" as const, - }); - }; - const execute = implementation as unknown as - InstalledHttpOperationExecutor["execute"]; - - const installed = createReferenceFeatureInstalledInput({ - http: Object.freeze({ execute }), - }); - - await installed.input.listResources({ limit: 20 }); - await installed.input.getResource("resource-1"); - - expect(seen.map((context) => context.routeId)).toEqual([ - "REFERENCE_RESOURCE_LIST", - "REFERENCE_RESOURCE_DETAIL", - ]); - }); -}); diff --git a/tests/features/reference-feature/reference-page-harness.tsx b/tests/features/reference-feature/reference-page-harness.tsx deleted file mode 100644 index 99433bfe..00000000 --- a/tests/features/reference-feature/reference-page-harness.tsx +++ /dev/null @@ -1,109 +0,0 @@ -import { - QueryClient, - QueryClientProvider, -} from "@tanstack/react-query"; -import { render } from "@testing-library/react"; - -import { createDemoSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts"; -import type { AuthSessionPort } from "../../../src/application/ports/auth-session-port.ts"; -import type { MutationIntentFactory } from "../../../src/application/ports/mutation-intent-factory.ts"; -import type { ReferenceFeatureInput } from "../../../src/features/reference-feature/application/reference-feature-api.ts"; -import { REFERENCE_FEATURE_ID } from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts"; -import type { QueryInvalidationCoordinator } from "../../../src/contracts/query-invalidation.ts"; -import { QueryInvalidationProvider } from "../../../src/presentation/adapters/query/query-invalidation-provider.tsx"; -import { MutationIntentProvider } from "../../../src/presentation/adapters/query/mutation-intent-provider.tsx"; -import { ServerStateScopeProvider } from "../../../src/presentation/adapters/query/server-state-scope-provider.tsx"; -import { createServerStateScopeRuntime } from "../../../src/adapters/query-cache/server-state-scope-runtime.ts"; -import { ApplicationProvider } from "../../../src/presentation/providers/application-provider.tsx"; -import { PreferenceProviders } from "../../../src/presentation/providers/preference-providers.tsx"; -import { AppRouter } from "../../../src/presentation/routes/app-router.tsx"; -import { createTestApplication } from "../../helpers/create-test-application.ts"; - -/** The real router with the providers the reference pages read. */ -export function renderReference( - input: ReferenceFeatureInput, - url = "/examples/reference-resources?limit=5", - session: AuthSessionPort = createDemoSessionAdapter("authenticated"), -) { - window.history.pushState({}, "", url); - const client = new QueryClient({ - defaultOptions: { - queries: { retry: false, gcTime: Infinity }, - mutations: { retry: false }, - }, - }); - const invalidation: QueryInvalidationCoordinator = Object.freeze({ - async invalidate() {}, - beginMutation() { - return Object.freeze({ - async release() {}, - }); - }, - async resetLocal() {}, - dispose() {}, - }); - const serverStateScope = createServerStateScopeRuntime({ - session, - queryInvalidation: invalidation, - }); - let intentSequence = 0; - const mutationIntentFactory: MutationIntentFactory = Object.freeze({ - create(input) { - intentSequence += 1; - return Object.freeze({ - intentId: `reference-page-intent-${intentSequence}`, - operationId: input.operationId, - canonicalInputIdentity: input.canonicalInputIdentity, - ...(input.requiresIdempotencyKey - ? { idempotencyKey: `reference-page-key-${intentSequence}` } - : {}), - createdAtMonotonicMs: intentSequence, - }); - }, - }); - return Object.assign(render( - - - - - - - - - - - - - , - ), { client }); -} - -export function inputWith( - overrides: Partial = {}, -): ReferenceFeatureInput { - return { - listResources: async () => ({ ok: true, value: [] }), - createResource: async ({ name }) => ({ - ok: true, - value: { - resourceId: "created", - title: name, - createdAt: null, - }, - }), - getResource: async (resourceId) => ({ - ok: true, - value: { - resourceId, - title: "Detail", - createdAt: null, - }, - }), - ...overrides, - }; -} diff --git a/tests/features/reference-feature/reference-page.test.tsx b/tests/features/reference-feature/reference-page.test.tsx deleted file mode 100644 index 783915ac..00000000 --- a/tests/features/reference-feature/reference-page.test.tsx +++ /dev/null @@ -1,1044 +0,0 @@ -// @vitest-environment jsdom - -import { screen, waitFor } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; -import { describe, expect, it, vi } from "vitest"; - -import { createDemoSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts"; -import type { - ReferenceFeatureInput, - ReferenceResult, -} from "../../../src/features/reference-feature/application/reference-feature-api.ts"; -import { - REFERENCE_RESOURCE_INVALIDATION_TOPIC, - REFERENCE_RESOURCE_QUERY_NAMESPACE, -} from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts"; -import { INVALIDATION_REGISTRY } from "../../../src/features/installed-feature-contracts.ts"; -import type { ReferenceResourceView } from "../../../src/features/reference-feature/contracts/reference-mapper.ts"; -import { createFailure } from "../../../src/contracts/errors.ts"; -import { KO_MESSAGES } from "../../../src/presentation/i18n/catalog.ts"; -import { inputWith, renderReference } from "./reference-page-harness.tsx"; - -/** - * 0929/08-02. The main area's text and accessible names with every ko-KR - * catalog value and every given data value cut out. The lint rule sees JSX - * text and attributes only; this also sees words passed through props. - */ -function mainTextOutsideCatalog(data: readonly string[]): string { - const main = screen.getByRole("main"); - const names = [...main.querySelectorAll("[aria-label],[title],[placeholder],[alt]")] - .flatMap((element) => - ["aria-label", "title", "placeholder", "alt"].map( - (name) => element.getAttribute(name) ?? "", - ), - ); - return [...data, ...Object.values(KO_MESSAGES)] - .sort((left, right) => right.length - left.length) - .reduce( - (text, known) => text.split(known).join(" "), - [main.textContent ?? "", ...names].join(" "), - ); -} - -describe("reference feature page states", () => { - it("shows no Latin words outside the catalog on the ko-KR screens", async () => { - const resource = { - resourceId: "reference-1", - title: "Loaded", - createdAt: null, - }; - const input = inputWith({ - listResources: async () => ({ ok: true, value: [resource] }), - }); - for (const [url, ready] of [ - ["/examples/reference-resources?limit=5&tags=open", "Loaded"], - ["/examples/reference-resources/items/reference-1", "Detail"], - ["/examples/reference-resources/new", "저장"], - ["/examples/reference-resources/status", "목록으로 이동"], - ] as const) { - const view = renderReference(input, url); - await screen.findAllByText(ready); - expect( - mainTextOutsideCatalog(["reference-1", "Loaded", "Detail", "open"]), - url, - ).not.toMatch(/[A-Za-z]/); - view.unmount(); - } - }); - - it("mounts list and detail keys under the installed governed namespace", async () => { - expect(REFERENCE_RESOURCE_QUERY_NAMESPACE).toEqual({ - namespaceId: "reference-resource", - namespaceVersion: 1, - }); - const installedEdge = INVALIDATION_REGISTRY.edges.find( - (edge) => edge.topicId === REFERENCE_RESOURCE_INVALIDATION_TOPIC, - ); - expect(installedEdge?.namespace).toEqual( - REFERENCE_RESOURCE_QUERY_NAMESPACE, - ); - - const list = renderReference(inputWith()); - await screen.findByRole("heading", { name: "표시할 항목이 없습니다." }); - const listKey = list.client.getQueryCache().getAll()[0]?.queryKey; - expect(listKey?.slice(0, 4)).toEqual([ - "query", - 2, - REFERENCE_RESOURCE_QUERY_NAMESPACE.namespaceId, - REFERENCE_RESOURCE_QUERY_NAMESPACE.namespaceVersion, - ]); - list.unmount(); - - const detail = renderReference( - inputWith(), - "/examples/reference-resources/items/reference-1", - ); - await screen.findByText("Detail"); - const detailKey = detail.client.getQueryCache().getAll()[0]?.queryKey; - expect(detailKey?.slice(0, 4)).toEqual([ - "query", - 2, - installedEdge?.namespace.namespaceId, - installedEdge?.namespace.namespaceVersion, - ]); - detail.unmount(); - }); - - it("renders loading, success and empty states through the installed route", async () => { - let resolveList: - | ((result: ReferenceResult) => void) - | undefined; - const pending = new Promise< - ReferenceResult - >((resolve) => { - resolveList = resolve; - }); - const loaded = renderReference( - inputWith({ listResources: async () => pending }), - ); - expect(await screen.findByLabelText("불러오는 중")).toBeVisible(); - resolveList?.({ - ok: true, - value: [ - { - resourceId: "reference-1", - title: "Loaded", - createdAt: null, - }, - ], - }); - expect(await screen.findByText("Loaded")).toBeVisible(); - loaded.unmount(); - - renderReference(inputWith(), "/examples/reference-resources?limit=10"); - expect( - await screen.findByRole("heading", { - name: "표시할 항목이 없습니다.", - }), - ).toBeVisible(); - }); - - it("rejects invalid URL input before the feature application input", async () => { - const listResources = vi.fn(); - renderReference( - inputWith({ listResources }), - "/examples/reference-resources?limit=invalid", - ); - expect( - await screen.findByRole("heading", { - name: "올바르지 않은 주소입니다.", - }), - ).toBeVisible(); - expect(listResources).not.toHaveBeenCalled(); - }); - - // 08-09. The count is a status only once there is a result to count. - it("shows the result count only for a loaded list", async () => { - const resultCount = () => - document.querySelector(".collection-page__result-count"); - let resolveList: - | ((result: ReferenceResult) => void) - | undefined; - const loading = renderReference( - inputWith({ - listResources: () => - new Promise((resolve) => { - resolveList = resolve; - }), - }), - ); - expect(await screen.findByLabelText("불러오는 중")).toBeVisible(); - expect(resultCount()).toBeNull(); - resolveList?.({ - ok: true, - value: [{ resourceId: "reference-1", title: "Loaded", createdAt: null }], - }); - expect(await screen.findByText("Loaded")).toBeVisible(); - expect(resultCount()).toHaveTextContent("총 1개 항목"); - loading.unmount(); - - renderReference( - inputWith({ - listResources: async () => ({ - ok: false, - error: createFailure("SERVER_FAILURE", "LIST_REFERENCE_RESOURCES", 0), - }), - }), - ); - expect(await screen.findByRole("alert")).toHaveTextContent( - "요청을 완료하지 못했습니다.", - ); - expect(resultCount()).toBeNull(); - }); - - // 08-13. A server id equal to a static segment still opens its detail. - it.each(["new", "status"])( - "opens the detail screen for an item whose id is %s", - async (resourceId) => { - const user = userEvent.setup(); - const getResource = vi.fn(async (id: string) => ({ - ok: true as const, - value: { resourceId: id, title: "Detail", createdAt: null }, - })); - renderReference( - inputWith({ - listResources: async () => ({ - ok: true, - value: [ - { resourceId, title: `Item ${resourceId}`, createdAt: null }, - ], - }), - getResource, - }), - ); - await user.click( - await screen.findByRole("link", { name: `Item ${resourceId}` }), - ); - expect( - await screen.findByRole("heading", { level: 1, name: "Detail" }), - ).toBeVisible(); - expect(getResource.mock.calls[0]?.[0]).toBe(resourceId); - }, - ); - - it("renders backend forbidden even when the client access hint allowed entry", async () => { - const user = userEvent.setup(); - renderReference( - inputWith({ - listResources: async () => ({ - ok: false, - error: createFailure( - "FORBIDDEN", - "LIST_REFERENCE_RESOURCES", - 0, - ), - }), - }), - ); - expect(await screen.findByRole("alert")).toHaveTextContent( - "접근할 수 없습니다.", - ); - await user.click( - screen.getByRole("button", { name: "안전한 화면으로 이동" }), - ); - expect( - await screen.findByRole("heading", { - level: 1, - name: "Clean Architecture Frontend", - }), - ).toBeVisible(); - }); - - it("starts sign-in with the current route for a backend auth failure", async () => { - const user = userEvent.setup(); - const demoSession = createDemoSessionAdapter("authenticated"); - const beginSignIn = vi.fn(async () => {}); - const session = { ...demoSession, beginSignIn }; - renderReference( - inputWith({ - listResources: async () => ({ - ok: false, - error: createFailure( - "AUTH_REQUIRED", - "LIST_REFERENCE_RESOURCES", - 0, - ), - }), - }), - "/examples/reference-resources?limit=5", - session, - ); - - await user.click(await screen.findByRole("button", { name: "로그인 시작" })); - expect(beginSignIn).toHaveBeenCalledWith( - "/examples/reference-resources?limit=5", - ); - }); - - it("falls back to a public route when starting sign-in fails", async () => { - const user = userEvent.setup(); - const demoSession = createDemoSessionAdapter("authenticated"); - const beginSignIn = vi.fn(async () => { - throw new Error("identity provider unavailable"); - }); - renderReference( - inputWith({ - listResources: async () => ({ - ok: false, - error: createFailure( - "AUTH_REQUIRED", - "LIST_REFERENCE_RESOURCES", - 0, - ), - }), - }), - "/examples/reference-resources?limit=5", - { ...demoSession, beginSignIn }, - ); - - await user.click(await screen.findByRole("button", { name: "로그인 시작" })); - expect( - await screen.findByRole("heading", { - level: 1, - name: "Clean Architecture Frontend", - }), - ).toBeVisible(); - }); - - it("deduplicates create, preserves input and surfaces a conflict", async () => { - const user = userEvent.setup(); - let finish: - | ((result: ReferenceResult) => void) - | undefined; - const createResource = vi.fn( - () => - new Promise>((resolve) => { - finish = resolve; - }), - ); - renderReference( - inputWith({ createResource }), - "/examples/reference-resources/new", - ); - await screen.findByRole("heading", { - name: "Reference resource 만들기", - }); - await user.type( - screen.getByRole("textbox", { name: /새 항목 이름/ }), - "Conflicting", - ); - await user.type(screen.getByLabelText("설명"), "Keep this input"); - const submit = screen.getByRole("button", { name: "저장" }); - await user.dblClick(submit); - - await waitFor(() => expect(createResource).toHaveBeenCalledOnce()); - // 1103/08-02. Busy, not disabled: a disabled button drops keyboard focus - // to the body. The second click is refused by the form, not the button. - const saving = screen.getByRole("button", { name: "저장 중…" }); - expect(saving).toHaveAttribute("aria-busy", "true"); - expect(saving).toHaveFocus(); - - finish?.({ - ok: false, - error: createFailure( - "CONFLICT", - "CREATE_REFERENCE_RESOURCE", - 0, - { effect: "NOT_APPLIED" }, - ), - }); - expect(await screen.findByText(/다른 변경과 충돌했습니다/)).toBeVisible(); - expect( - screen.getByRole("textbox", { name: /새 항목 이름/ }), - ).toHaveValue("Conflicting"); - expect(screen.getByLabelText("설명")).toHaveValue("Keep this input"); - }); - - it("blocks a new save and resends an unknown create with the same key", async () => { - const user = userEvent.setup(); - const createResource = vi - .fn() - .mockResolvedValueOnce({ - ok: false, - error: createFailure( - "SERVER_FAILURE", - "CREATE_REFERENCE_RESOURCE", - 0, - { effect: "MAYBE_APPLIED" }, - ), - }) - .mockResolvedValue({ - ok: true, - value: { resourceId: "created", title: "Unknown result", createdAt: null }, - }); - renderReference( - inputWith({ createResource }), - "/examples/reference-resources/new", - ); - const name = await screen.findByRole("textbox", { name: /새 항목 이름/ }); - await user.type(name, "Unknown result"); - await user.click(screen.getByRole("button", { name: "저장" })); - - expect( - await screen.findByText("변경 결과를 확인할 수 없습니다."), - ).toBeVisible(); - expect(screen.getByRole("button", { name: "저장" })).toBeDisabled(); - expect( - screen.queryByText("저장하지 못했습니다. 잠시 후 다시 시도해 주세요."), - ).not.toBeInTheDocument(); - // No path lets the user declare "not applied" without evidence. - expect( - screen.queryByRole("button", { name: "변경되지 않음으로 확인" }), - ).not.toBeInTheDocument(); - // 16-04. Built by the route codec, so the link is already the canonical - // URL the router would redirect to (the default limit is written out). - expect( - screen.getByRole("link", { name: "목록을 새로 불러와 확인" }), - ).toHaveAttribute("href", "/examples/reference-resources?limit=20"); - await user.click(screen.getByRole("button", { name: "저장" })); - expect(createResource).toHaveBeenCalledOnce(); - expect(name).toHaveValue("Unknown result"); - - await user.click( - screen.getByRole("button", { name: "같은 요청으로 다시 보내기" }), - ); - - expect(await screen.findByRole("status")).toHaveTextContent("저장했습니다."); - expect(createResource).toHaveBeenCalledTimes(2); - const [first, second] = createResource.mock.calls; - expect(second?.[0]).toEqual(first?.[0]); - expect(first?.[1]?.intent?.idempotencyKey).toBe("reference-page-key-1"); - expect(second?.[1]?.intent?.idempotencyKey).toBe("reference-page-key-1"); - expect(name).toHaveValue(""); - }); - - /** - * 1106/03-01 (D10 supplement). The form is never held for good after a - * same-key resend. A refusal that may change (429) keeps the result - * unknown and the confirm and resend actions on screen. So does a 422 - * (final review FR-01): this feature's gateway reads every 422 as a field - * error whatever its code, and only the paired backend's own table codes - * settle a resent request. - */ - async function resendAnUnknownCreate(resendAnswer: ReferenceResult) { - const user = userEvent.setup(); - const createResource = vi - .fn() - .mockResolvedValueOnce({ - ok: false, - error: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, { - effect: "MAYBE_APPLIED", - }), - }) - .mockResolvedValueOnce(resendAnswer) - .mockResolvedValue({ - ok: true, - value: { resourceId: "created", title: "Resent", createdAt: null }, - }); - renderReference( - inputWith({ createResource }), - "/examples/reference-resources/new", - ); - const name = await screen.findByRole("textbox", { name: /새 항목 이름/ }); - await user.type(name, "Resent"); - await user.click(screen.getByRole("button", { name: "저장" })); - await user.click( - await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }), - ); - await waitFor(() => expect(createResource).toHaveBeenCalledTimes(2)); - return { user, name, createResource }; - } - - it("keeps the confirm on screen when the resend is refused for now", async () => { - const { user } = await resendAnUnknownCreate({ - ok: false, - error: createFailure("RATE_LIMITED", "CREATE_REFERENCE_RESOURCE", 0, { - effect: "NOT_APPLIED", - httpStatus: 429, - }), - }); - - expect( - await screen.findByText(KO_MESSAGES["form.resendLater"]), - ).toBeVisible(); - expect(screen.getByText("변경 결과를 확인할 수 없습니다.")).toBeVisible(); - expect(screen.getByRole("button", { name: "같은 요청으로 다시 보내기" })).toBeVisible(); - await user.click(screen.getByRole("button", { name: "변경됨으로 확인" })); - - expect(await screen.findByText("저장했습니다.")).toBeVisible(); - }); - - it("keeps the confirm on screen when the resend is refused with a 422", async () => { - const { user, name } = await resendAnUnknownCreate({ - ok: false, - error: createFailure("VALIDATION_REJECTED", "CREATE_REFERENCE_RESOURCE", 0, { - code: "REFERENCE_RESOURCE_REJECTED", - effect: "NOT_APPLIED", - httpStatus: 422, - validationIssues: [{ path: "name", code: "REQUIRED" }], - }), - }); - - expect( - await screen.findByText(KO_MESSAGES["form.resendLater"]), - ).toBeVisible(); - expect(screen.getByText("변경 결과를 확인할 수 없습니다.")).toBeVisible(); - expect(name).not.toHaveAttribute("aria-invalid"); - expect(screen.getByRole("button", { name: "저장" })).toBeDisabled(); - await user.click(screen.getByRole("button", { name: "변경됨으로 확인" })); - - expect(await screen.findByText("저장했습니다.")).toBeVisible(); - }); - - it.each([ - ["AUTH_REQUIRED", "계속하려면 로그인이 필요합니다.", "로그인"], - ["FORBIDDEN", "이 작업을 수행할 권한이 없습니다.", "안전한 화면으로 이동"], - ["RATE_LIMITED", "요청이 많습니다. 잠시 후 다시 시도해 주세요.", "다시 시도"], - ] as const)( - "gives a %s create failure its own copy and action", - async (kind, copy, action) => { - const user = userEvent.setup(); - const demoSession = createDemoSessionAdapter("authenticated"); - const beginSignIn = vi.fn(async () => {}); - const createResource = vi.fn(async () => ({ - ok: false as const, - error: createFailure(kind, "CREATE_REFERENCE_RESOURCE", 0, { - effect: "NOT_APPLIED", - }), - })); - renderReference( - inputWith({ createResource }), - "/examples/reference-resources/new", - { ...demoSession, beginSignIn }, - ); - await user.type( - await screen.findByRole("textbox", { name: /새 항목 이름/ }), - "Rejected", - ); - await user.click(screen.getByRole("button", { name: "저장" })); - - expect(await screen.findByRole("alert")).toHaveTextContent(copy); - expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요."); - expect( - screen.queryByText("변경 결과를 확인할 수 없습니다."), - ).not.toBeInTheDocument(); - await user.click(screen.getByRole("button", { name: action })); - - if (kind === "AUTH_REQUIRED") { - expect(beginSignIn).toHaveBeenCalledWith( - "/examples/reference-resources/new", - ); - } else if (kind === "FORBIDDEN") { - // Leaving still passes the dirty-input guard. - await user.click( - await screen.findByRole("button", { name: "변경 버리고 이동" }), - ); - expect( - await screen.findByRole("heading", { - level: 1, - name: "Clean Architecture Frontend", - }), - ).toBeVisible(); - } else { - await waitFor(() => expect(createResource).toHaveBeenCalledTimes(2)); - } - }, - ); - - /** - * 1103/08-02. A keyboard save whose failure is not a field error used to - * leave focus on a button the result disables, so the browser dropped it - * to the body. Focus now moves to the failure status above the form, and - * one Tab reaches its first recovery action. - */ - it.each([ - { - result: "unknown", - failure: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, { - effect: "MAYBE_APPLIED", - }), - text: "변경 결과를 확인할 수 없습니다.", - firstAction: "변경됨으로 확인", - }, - { - result: "rate-limited", - failure: createFailure("RATE_LIMITED", "CREATE_REFERENCE_RESOURCE", 0, { - effect: "NOT_APPLIED", - httpStatus: 429, - }), - text: "요청이 많습니다. 잠시 후 다시 시도해 주세요.", - firstAction: "다시 시도", - }, - ])("moves focus to the failure status after a keyboard save ($result)", async ({ - failure, - text, - firstAction, - }) => { - const user = userEvent.setup(); - renderReference( - inputWith({ createResource: async () => ({ ok: false, error: failure }) }), - "/examples/reference-resources/new", - ); - await user.type( - await screen.findByRole("textbox", { name: /새 항목 이름/ }), - "Keyboard save", - ); - screen.getByRole("button", { name: "저장" }).focus(); - await user.keyboard("{Enter}"); - - const status = (await screen.findByText(text)).closest( - ".page-template__feedback", - ); - await waitFor(() => expect(status).toHaveFocus()); - await user.tab(); - expect(screen.getByRole("button", { name: firstAction })).toHaveFocus(); - }); - - /** - * 1105/08-01. A recovery action goes away with its status once it has - * done its work, so the browser dropped focus to the body. Focus now stays - * in the feedback area that shows the result. - */ - it.each([ - { - action: "변경됨으로 확인", - tabs: 1, - failure: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, { - effect: "MAYBE_APPLIED", - }), - text: "변경 결과를 확인할 수 없습니다.", - }, - { - action: "같은 요청으로 다시 보내기", - tabs: 2, - failure: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, { - effect: "MAYBE_APPLIED", - }), - text: "변경 결과를 확인할 수 없습니다.", - }, - { - action: "다시 시도", - tabs: 1, - failure: createFailure("RATE_LIMITED", "CREATE_REFERENCE_RESOURCE", 0, { - effect: "NOT_APPLIED", - httpStatus: 429, - }), - text: "요청이 많습니다. 잠시 후 다시 시도해 주세요.", - }, - ])("keeps focus in the feedback after '$action' from the keyboard", async ({ - action, - tabs, - failure, - text, - }) => { - const user = userEvent.setup(); - const createResource = vi - .fn() - .mockResolvedValueOnce({ ok: false, error: failure }) - .mockResolvedValue({ - ok: true, - value: { resourceId: "created", title: "Keyboard save", createdAt: null }, - }); - renderReference( - inputWith({ createResource }), - "/examples/reference-resources/new", - ); - await user.type( - await screen.findByRole("textbox", { name: /새 항목 이름/ }), - "Keyboard save", - ); - screen.getByRole("button", { name: "저장" }).focus(); - await user.keyboard("{Enter}"); - const status = (await screen.findByText(text)).closest( - ".page-template__feedback", - ); - await waitFor(() => expect(status).toHaveFocus()); - for (let tab = 0; tab < tabs; tab += 1) await user.tab(); - expect(screen.getByRole("button", { name: action })).toHaveFocus(); - - await user.keyboard("{Enter}"); - - const saved = await screen.findByText("저장했습니다."); - await waitFor(() => - expect(saved.closest(".page-template__feedback")).toHaveFocus(), - ); - }); - - // 1105/08-04. A save left running when the user leaves and comes back - // still holds the coordinator. The remounted form says a save is running - // and keeps its save off, instead of a save button that does nothing. - it("says a save is running and keeps the save off after coming back during a save", async () => { - const user = userEvent.setup(); - let release: - | ((result: ReferenceResult) => void) - | undefined; - const createResource = vi - .fn() - .mockImplementationOnce( - () => - new Promise>((resolve) => { - release = resolve; - }), - ) - .mockResolvedValue({ - ok: true, - value: { resourceId: "created-2", title: "Second item", createdAt: null }, - }); - renderReference( - inputWith({ createResource }), - "/examples/reference-resources/new", - ); - await user.type( - await screen.findByRole("textbox", { name: /새 항목 이름/ }), - "First item", - ); - await user.click(screen.getByRole("button", { name: "저장" })); - await waitFor(() => expect(createResource).toHaveBeenCalledOnce()); - await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" })); - await waitFor(() => - expect(window.location.pathname).toBe("/examples/reference-resources"), - ); - window.history.pushState({}, "", "/examples/reference-resources/new"); - window.dispatchEvent(new PopStateEvent("popstate")); - await user.type( - await screen.findByRole("textbox", { name: /새 항목 이름/ }), - "Second item", - ); - - expect(await screen.findByText("변경 사항을 저장하고 있습니다.")).toBeVisible(); - expect(screen.getByRole("button", { name: "저장" })).toBeDisabled(); - - release?.({ - ok: true, - value: { resourceId: "created-1", title: "First item", createdAt: null }, - }); - await waitFor(() => - expect(screen.getByRole("button", { name: "저장" })).toBeEnabled(), - ); - expect(screen.queryByText("변경 사항을 저장하고 있습니다.")).not.toBeInTheDocument(); - await user.click(screen.getByRole("button", { name: "저장" })); - - expect(await screen.findByText("저장했습니다.")).toBeVisible(); - expect(createResource).toHaveBeenCalledTimes(2); - }); - - /** - * 1106/08-01. The form the user came back to did not start the save - * still running, and holds none of its result (review probe 08-R1). - */ - async function leaveDuringSaveAndComeBack( - ...laterAnswers: readonly ReferenceResult[] - ) { - const user = userEvent.setup(); - let release: - | ((result: ReferenceResult) => void) - | undefined; - const createResource = vi - .fn() - .mockImplementationOnce( - () => - new Promise>((resolve) => { - release = resolve; - }), - ); - for (const answer of laterAnswers) createResource.mockResolvedValueOnce(answer); - renderReference( - inputWith({ createResource }), - "/examples/reference-resources/new", - ); - await user.type( - await screen.findByRole("textbox", { name: /새 항목 이름/ }), - "First item", - ); - await user.click(screen.getByRole("button", { name: "저장" })); - await waitFor(() => expect(createResource).toHaveBeenCalledOnce()); - await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" })); - await waitFor(() => - expect(window.location.pathname).toBe("/examples/reference-resources"), - ); - window.history.pushState({}, "", "/examples/reference-resources/new"); - window.dispatchEvent(new PopStateEvent("popstate")); - expect(await screen.findByText("변경 사항을 저장하고 있습니다.")).toBeVisible(); - return { - user, - createResource, - release(result: ReferenceResult) { - release?.(result); - }, - }; - } - - // 1106/03-01 (final review FR-01). The remounted form shows other values - // than the save it did not start; its resend sends that save, with its - // key. A 422 IDEMPOTENT_REQUEST_MISMATCH there says the key already - // reached the server, so the first request may have applied: it stays - // unknown and the confirm stays on screen. - it("keeps a resent request unknown on a remounted form when the server answers 422 IDEMPOTENT_REQUEST_MISMATCH", async () => { - const { user, createResource, release } = await leaveDuringSaveAndComeBack({ - ok: false, - error: createFailure("VALIDATION_REJECTED", "CREATE_REFERENCE_RESOURCE", 0, { - code: "IDEMPOTENT_REQUEST_MISMATCH", - effect: "NOT_APPLIED", - httpStatus: 422, - }), - }); - release({ - ok: false, - error: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, { - effect: "MAYBE_APPLIED", - }), - }); - await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }); - await user.type( - screen.getByRole("textbox", { name: /새 항목 이름/ }), - "Second item", - ); - - await user.click( - screen.getByRole("button", { name: "같은 요청으로 다시 보내기" }), - ); - await waitFor(() => expect(createResource).toHaveBeenCalledTimes(2)); - - expect( - await screen.findByText(KO_MESSAGES["form.resendLater"]), - ).toBeVisible(); - expect(screen.getByText("변경 결과를 확인할 수 없습니다.")).toBeVisible(); - expect(screen.getByRole("button", { name: "변경됨으로 확인" })).toBeVisible(); - const [first, second] = createResource.mock.calls; - expect(second?.[0]).toEqual(first?.[0]); - expect(second?.[1]?.intent?.idempotencyKey).toBe( - first?.[1]?.intent?.idempotencyKey, - ); - }); - - // 1106/08-01 (A). Confirming that save from the remounted form used to - // show nothing and drop focus to the body: the form had no submitted - // values to settle. - it("shows the save confirmed on a remounted form and keeps focus in its feedback", async () => { - const { user, release } = await leaveDuringSaveAndComeBack(); - release({ - ok: false, - error: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, { - effect: "MAYBE_APPLIED", - }), - }); - const confirm = await screen.findByRole("button", { name: "변경됨으로 확인" }); - confirm.focus(); - - await user.keyboard("{Enter}"); - - const saved = await screen.findByText("저장했습니다."); - await waitFor(() => - expect(saved.closest(".page-template__feedback")).toHaveFocus(), - ); - }); - - // 1106/08-01, diff review. What the user typed on the remounted form was - // never sent. Confirming the earlier save shows that save and leaves the - // new input, and its leave guard, in place. - it("keeps what the user typed on a remounted form when confirming the earlier save", async () => { - const { user, release } = await leaveDuringSaveAndComeBack(); - release({ - ok: false, - error: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, { - effect: "MAYBE_APPLIED", - }), - }); - await screen.findByRole("button", { name: "변경됨으로 확인" }); - const name = screen.getByRole("textbox", { name: /새 항목 이름/ }); - await user.type(name, "Second item"); - screen.getByRole("button", { name: "변경됨으로 확인" }).focus(); - - await user.keyboard("{Enter}"); - - const saved = await screen.findByText("저장했습니다."); - await waitFor(() => - expect(saved.closest(".page-template__feedback")).toHaveFocus(), - ); - expect(name).toHaveValue("Second item"); - await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" })); - expect( - await screen.findByRole("button", { name: "변경 버리고 이동" }), - ).toBeVisible(); - }); - - // 1106/08-01 (B). That save succeeding left the remounted form saying - // nothing. The form cannot know its result, so it points to the list. - it("points to the list once a save the remounted form did not start ends", async () => { - const { release } = await leaveDuringSaveAndComeBack(); - release({ - ok: true, - value: { resourceId: "created-1", title: "First item", createdAt: null }, - }); - - expect( - await screen.findByRole("link", { name: "목록을 새로 불러와 확인" }), - ).toBeVisible(); - expect(screen.queryByText("변경 사항을 저장하고 있습니다.")).not.toBeInTheDocument(); - expect(screen.getByRole("button", { name: "저장" })).toBeEnabled(); - }); - - // 0929/08-04. The ids a user quotes to support reach the screens that - // need them, and the sample status page shows no made-up reference. - it("shows the request id of an unknown create next to its result", async () => { - const user = userEvent.setup(); - renderReference( - inputWith({ - createResource: async () => ({ - ok: false, - error: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, { - effect: "MAYBE_APPLIED", - requestId: "corr-save-500", - }), - }), - }), - "/examples/reference-resources/new", - ); - await user.type( - await screen.findByRole("textbox", { name: /새 항목 이름/ }), - "Unknown result", - ); - await user.click(screen.getByRole("button", { name: "저장" })); - - expect(await screen.findByText("변경 결과를 확인할 수 없습니다.")).toBeVisible(); - expect(screen.getByText("지원 참조: corr-save-500")).toBeVisible(); - }); - - it("carries a failure's request id to the support status page", async () => { - const user = userEvent.setup(); - renderReference( - inputWith({ - listResources: async () => ({ - ok: false, - error: createFailure("UNKNOWN_CLIENT_FAILURE", "LIST_REFERENCE_RESOURCES", 0, { - requestId: "corr-list-400", - }), - }), - }), - ); - await user.click(await screen.findByRole("button", { name: "지원 정보 확인" })); - - expect( - await screen.findByRole("heading", { level: 1, name: "잠시 사용할 수 없습니다." }), - ).toBeVisible(); - expect(screen.getByText("지원 참조: corr-list-400")).toBeVisible(); - expect(document.body).not.toHaveTextContent("REFERENCE-STATUS-DEMO"); - }); - - it("shows no support reference on a status page opened directly", async () => { - renderReference(inputWith(), "/examples/reference-resources/status"); - - expect( - await screen.findByRole("heading", { level: 1, name: "잠시 사용할 수 없습니다." }), - ).toBeVisible(); - expect(document.body).not.toHaveTextContent("지원 참조"); - }); - - it("settles the form after confirming an unknown create was applied", async () => { - const user = userEvent.setup(); - const createResource = vi.fn(async () => ({ - ok: false as const, - error: createFailure( - "SERVER_FAILURE", - "CREATE_REFERENCE_RESOURCE", - 0, - { effect: "MAYBE_APPLIED" }, - ), - })); - renderReference( - inputWith({ createResource }), - "/examples/reference-resources/new", - ); - const name = await screen.findByRole("textbox", { - name: /새 항목 이름/, - }); - await user.type(name, "Already created"); - await user.click(screen.getByRole("button", { name: "저장" })); - await user.click( - await screen.findByRole("button", { name: "변경됨으로 확인" }), - ); - - expect(await screen.findByRole("status")).toHaveTextContent("저장했습니다."); - expect(name).toHaveValue(""); - await user.click(screen.getByRole("button", { name: "저장" })); - expect(createResource).toHaveBeenCalledOnce(); - }); - - it("treats an applied-confirmed failure as a settled create", async () => { - const user = userEvent.setup(); - const createResource = vi.fn(async () => ({ - ok: false as const, - error: createFailure( - "SERVER_FAILURE", - "CREATE_REFERENCE_RESOURCE", - 0, - { effect: "APPLIED_CONFIRMED" }, - ), - })); - renderReference( - inputWith({ createResource }), - "/examples/reference-resources/new", - ); - const name = await screen.findByRole("textbox", { - name: /새 항목 이름/, - }); - await user.type(name, "Committed despite response"); - await user.click(screen.getByRole("button", { name: "저장" })); - - expect(await screen.findByRole("status")).toHaveTextContent("저장했습니다."); - expect(name).toHaveValue(""); - expect( - screen.queryByText("저장하지 못했습니다. 잠시 후 다시 시도해 주세요."), - ).not.toBeInTheDocument(); - await user.click(screen.getByRole("button", { name: "저장" })); - expect(createResource).toHaveBeenCalledOnce(); - }); - - it("keeps stale data visible during refresh failure and recovers on retry", async () => { - const user = userEvent.setup(); - const listResources = vi - .fn() - .mockResolvedValueOnce({ - ok: true, - value: [ - { - resourceId: "existing", - title: "Existing", - createdAt: null, - }, - ], - }) - .mockResolvedValueOnce({ - ok: false, - error: createFailure( - "SERVER_FAILURE", - "LIST_REFERENCE_RESOURCES", - 0, - ), - }) - .mockResolvedValue({ - ok: true, - value: [ - { - resourceId: "recovered", - title: "Recovered", - createdAt: null, - }, - ], - }); - renderReference(inputWith({ listResources })); - await screen.findByText("Existing"); - await user.click(screen.getByRole("button", { name: "새로고침" })); - - expect( - await screen.findByText("기존 정보를 표시하고 있습니다."), - ).toBeVisible(); - expect(screen.getByText("Existing")).toBeVisible(); - await user.click(screen.getByRole("button", { name: "다시 시도" })); - expect(await screen.findByText("Recovered")).toBeVisible(); - await waitFor(() => - expect(screen.queryByText("stale-degraded")).not.toBeInTheDocument(), - ); - expect(listResources).toHaveBeenCalledTimes(3); - }); -}); diff --git a/tests/features/reference-feature/reference-production-vertical.test.tsx b/tests/features/reference-feature/reference-production-vertical.test.tsx deleted file mode 100644 index 4c7c3fb5..00000000 --- a/tests/features/reference-feature/reference-production-vertical.test.tsx +++ /dev/null @@ -1,442 +0,0 @@ -// @vitest-environment jsdom - -import { render, screen, waitFor } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; -import { http, HttpResponse } from "msw"; -import { - afterAll, - afterEach, - beforeAll, - describe, - expect, - it, - vi, -} from "vitest"; - -import { createRuntimeComposition } from "../../../src/bootstrap/create-runtime-composition.ts"; -import { RuntimeApplication } from "../../../src/bootstrap/runtime-application.tsx"; -import { createBootstrapHandlers } from "../../mocks/handlers/bootstrap.ts"; -import { createReferenceResourceHandlers } from "./reference-resource-handlers.ts"; -import { createStrictMockServer } from "../../mocks/server.ts"; - -const runtimeConfig = { - APP_ENV: "local", - API_BASE_URL: "https://api.test", - REQUEST_TIMEOUT_MS: 10_000, - MAX_RETRY_ATTEMPTS: 0, - TELEMETRY_ENABLED: false, - AUTH_MODE: "demo", - CONFIG_SCHEMA_VERSION: "1", - API_CONTRACT_VERSION: "1", - RELEASE_MANIFEST_URL: "/release-manifest.json", - BUILD_ID: "local-build", - RELEASE_ID: "local-release", -}; -const releaseManifest = { - schemaVersion: 1, - appVersion: "0.2.0", - buildId: "local-build", - commitSha: "local", - configSchemaVersion: "1", - apiContractVersion: "1", - assetManifestHash: "test-hash", - releaseId: "local-release", - builtAt: "2026-07-26T00:00:00.000Z", - routeChunks: { - "route-home": "assets/home.js", - "route-examples-ui": "assets/ui.js", - "route-examples-states": "assets/states.js", - "route-examples-auth": "assets/auth.js", - "route-reference-resources": "assets/reference.js", - "route-reference-resource-detail": "assets/reference-detail.js", - "route-reference-resource-form": "assets/reference-form.js", - "route-reference-resource-status": "assets/reference-status.js", - "route-not-found": "assets/not-found.js", - }, -}; - -const listRequests = vi.fn(); -const createRequests = vi.fn(); -const resources = [{ id: "reference-1", name: "Existing" }]; -const mockApi = createStrictMockServer( - ...createBootstrapHandlers(runtimeConfig, releaseManifest), - ...createReferenceResourceHandlers({ - resources, - onList: listRequests, - onCreate: createRequests, - }), -); - -beforeAll(mockApi.listen); -afterEach(() => { - mockApi.reset(); - listRequests.mockClear(); - createRequests.mockClear(); - resources.splice(1); -}); -afterAll(mockApi.close); - -const absoluteFetch: typeof fetch = (input, init) => { - if (input instanceof Request) return fetch(input, init); - const url = new URL( - input instanceof URL ? input.href : input, - "http://app.test", - ); - return fetch(url, init); -}; - -describe("reference feature production vertical path", () => { - it("traverses bootstrap, router, application, HTTP schema/mapper and query cache", async () => { - const user = userEvent.setup(); - const composition = await createRuntimeComposition({ - fetcher: absoluteFetch, - host: {}, - }); - window.history.pushState( - {}, - "", - "/examples/reference-resources?tags=open&tags=new&limit=5", - ); - render(); - - await user.click( - await screen.findByRole("button", { name: "로그인 시작" }), - ); - expect(await screen.findByText("Existing")).toBeVisible(); - expect(listRequests).toHaveBeenCalledWith( - "?limit=5&tags=open&tags=new", - ); - - await user.click(screen.getByRole("button", { name: "새 항목 만들기" })); - await user.type( - await screen.findByRole("textbox", { name: /새 항목 이름/ }), - " Created ", - ); - await user.click(screen.getByRole("button", { name: "저장" })); - expect(await screen.findByText("저장했습니다.")).toBeVisible(); - await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" })); - expect(await screen.findByText("Created")).toBeVisible(); - expect(createRequests).toHaveBeenCalledWith({ name: "Created" }); - expect(listRequests.mock.calls.length).toBeGreaterThanOrEqual(2); - }); - - it("resends a create whose 504 lost the response with the same Idempotency-Key", async () => { - const user = userEvent.setup(); - const idempotencyKeys: (string | null)[] = []; - mockApi.server.use( - http.post("https://api.test/api/reference-resources", async ({ request }) => { - idempotencyKeys.push(request.headers.get("idempotency-key")); - // The first request reaches the server; only its response is lost. - if (idempotencyKeys.length === 1) { - return new HttpResponse(null, { status: 504 }); - } - const body = (await request.json()) as { name: string }; - return HttpResponse.json( - { - id: "reference-created", - name: body.name, - createdAt: "2026-07-26T00:00:00.000Z", - }, - { status: 201 }, - ); - }), - ); - const composition = await createRuntimeComposition({ - fetcher: absoluteFetch, - host: {}, - }); - window.history.pushState({}, "", "/examples/reference-resources/new"); - render(); - - await user.click( - await screen.findByRole("button", { name: "로그인 시작" }), - ); - await user.type( - await screen.findByRole("textbox", { name: /새 항목 이름/ }), - "Lost response", - ); - await user.click(screen.getByRole("button", { name: "저장" })); - await user.click( - await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }), - ); - - expect(await screen.findByText("저장했습니다.")).toBeVisible(); - expect(idempotencyKeys).toHaveLength(2); - expect(idempotencyKeys[0]).toMatch(/^[\x21-\x7e]+$/u); - expect(idempotencyKeys[1]).toBe(idempotencyKeys[0]); - }); - - // 0929/03-04. A write past its deadline has no server answer to echo an - // id, so the screen shows the id the request itself carried. - it("shows the sent x-correlation-id for a create past its deadline", async () => { - const user = userEvent.setup(); - const sentIds: (string | null)[] = []; - mockApi.server.use( - http.get("http://app.test/config.json", () => - HttpResponse.json({ ...runtimeConfig, REQUEST_TIMEOUT_MS: 200 }), - ), - http.post("https://api.test/api/reference-resources", async ({ request }) => { - sentIds.push(request.headers.get("x-correlation-id")); - // The server is still working when the client deadline ends. - await new Promise((resolve) => { - request.signal.addEventListener("abort", () => resolve(), { once: true }); - }); - return new HttpResponse(null, { status: 504 }); - }), - ); - const composition = await createRuntimeComposition({ - fetcher: absoluteFetch, - host: {}, - }); - window.history.pushState({}, "", "/examples/reference-resources/new"); - render(); - - await user.click( - await screen.findByRole("button", { name: "로그인 시작" }), - ); - await user.type( - await screen.findByRole("textbox", { name: /새 항목 이름/ }), - "Past the deadline", - ); - await user.click(screen.getByRole("button", { name: "저장" })); - - expect( - await screen.findByText("변경 결과를 확인할 수 없습니다."), - ).toBeVisible(); - expect(sentIds).toHaveLength(1); - expect(sentIds[0]).toMatch(/^[A-Za-z0-9._:-]{1,128}$/u); - expect(screen.getByText(`지원 참조: ${sentIds[0]}`)).toBeVisible(); - }); - - it("keeps the key when the resend meets the first attempt still in flight (0929/03-01)", async () => { - const user = userEvent.setup(); - const idempotencyKeys: (string | null)[] = []; - const sentAt: number[] = []; - // A server that deduplicates by key: one receipt per created resource. - const receipts = new Map>(); - let firstAttemptRunning = true; - mockApi.server.use( - http.post("https://api.test/api/reference-resources", async ({ request }) => { - const key = request.headers.get("idempotency-key") ?? ""; - idempotencyKeys.push(key); - sentAt.push(performance.now()); - const receipt = receipts.get(key); - if (receipt) { - if (firstAttemptRunning) { - // The paired backend answers a same-key request while the first - // attempt still runs with 409 IDEMPOTENT_IN_FLIGHT and - // Retry-After (2 there; 1 here to keep the test short). - firstAttemptRunning = false; - return HttpResponse.json( - { - type: "https://api.test/problems/idempotent_in_flight", - title: "IDEMPOTENT_IN_FLIGHT", - status: 409, - code: "IDEMPOTENT_IN_FLIGHT", - }, - { - status: 409, - headers: { - "content-type": "application/problem+json", - "retry-after": "1", - }, - }, - ); - } - return HttpResponse.json(receipt, { status: 201 }); - } - const body = (await request.json()) as { name: string }; - const resource = { - id: `reference-created-${receipts.size + 1}`, - name: body.name, - createdAt: "2026-07-26T00:00:00.000Z", - }; - receipts.set(key, resource); - // The first attempt reaches the server; only its response is lost. - if (receipts.size === 1) return new HttpResponse(null, { status: 504 }); - return HttpResponse.json(resource, { status: 201 }); - }), - ); - const composition = await createRuntimeComposition({ - fetcher: absoluteFetch, - host: {}, - }); - window.history.pushState({}, "", "/examples/reference-resources/new"); - render(); - - await user.click( - await screen.findByRole("button", { name: "로그인 시작" }), - ); - await user.type( - await screen.findByRole("textbox", { name: /새 항목 이름/ }), - "Slow write", - ); - await user.click(screen.getByRole("button", { name: "저장" })); - await user.click( - await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }), - ); - await waitFor(() => expect(idempotencyKeys).toHaveLength(2)); - - // After the 409 the user takes the next step the screen offers. - const next = await waitFor(() => { - const resend = screen.queryByRole("button", { - name: "같은 요청으로 다시 보내기", - }); - if (resend) return resend; - const save = screen.getByRole("button", { name: "저장" }); - expect(save).toBeEnabled(); - return save; - }); - const shownAfterInFlight = { - unknown: screen.queryByText("변경 결과를 확인할 수 없습니다.") !== null, - conflict: screen.queryAllByText(/충돌/).length > 0, - }; - await user.click(next); - await waitFor(() => expect(idempotencyKeys).toHaveLength(3), { - timeout: 3_000, - }); - - const [first] = idempotencyKeys; - expect(idempotencyKeys).toEqual([first, first, first]); - expect(receipts.size).toBe(1); - expect(shownAfterInFlight).toEqual({ unknown: true, conflict: false }); - // 백엔드 1101/02-01. The click came right after the 409; the resend - // waited out its Retry-After instead of meeting the same 409 again. - expect((sentAt[2] ?? 0) - (sentAt[1] ?? 0)).toBeGreaterThanOrEqual(990); - expect(await screen.findByText("저장했습니다.")).toBeVisible(); - }); - - it.each([ - // The demo session treats a server 401 as signed out; the route guard - // then asks for sign-in and the form is gone. - [401, "세션이 필요합니다."], - [403, "이 작업을 수행할 권한이 없습니다."], - [429, "요청이 많습니다. 잠시 후 다시 시도해 주세요."], - ])( - "treats a create rejected with %i as not applied, not unknown", - async (status, guidance) => { - const user = userEvent.setup(); - mockApi.server.use( - http.post( - "https://api.test/api/reference-resources", - () => new HttpResponse(null, { status }), - ), - ); - const composition = await createRuntimeComposition({ - fetcher: absoluteFetch, - host: {}, - }); - window.history.pushState({}, "", "/examples/reference-resources/new"); - render(); - - await user.click( - await screen.findByRole("button", { name: "로그인 시작" }), - ); - await user.type( - await screen.findByRole("textbox", { name: /새 항목 이름/ }), - "Rejected", - ); - await user.click(screen.getByRole("button", { name: "저장" })); - - expect(await screen.findByText(guidance)).toBeVisible(); - expect( - screen.queryByText("변경 결과를 확인할 수 없습니다."), - ).not.toBeInTheDocument(); - expect( - screen.queryByRole("button", { name: "같은 요청으로 다시 보내기" }), - ).not.toBeInTheDocument(); - expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요."); - }, - ); - - it("shows a server 422 field error on its field (03-04)", async () => { - const user = userEvent.setup(); - mockApi.server.use( - http.post("https://api.test/api/reference-resources", () => - HttpResponse.json( - { - type: "https://api.test/problems/validation_rejected", - title: "VALIDATION_REJECTED", - status: 422, - code: "VALIDATION_REJECTED", - issues: [ - { path: "name", code: "too_big", message: "backend copy" }, - { path: "serverOnly", code: "REQUIRED" }, - ], - }, - { status: 422 }, - ), - ), - ); - const composition = await createRuntimeComposition({ - fetcher: absoluteFetch, - host: {}, - }); - window.history.pushState({}, "", "/examples/reference-resources/new"); - render(); - - await user.click( - await screen.findByRole("button", { name: "로그인 시작" }), - ); - const name = await screen.findByRole("textbox", { name: /새 항목 이름/ }); - await user.type(name, "Too long for the server"); - await user.click(screen.getByRole("button", { name: "저장" })); - - const summary = await screen.findByRole("alert"); - expect(summary).toHaveTextContent("새 항목 이름: 입력값이 너무 깁니다."); - expect(summary).toHaveTextContent("서버가 확인하지 못한 입력 항목이 있습니다."); - expect(name).toHaveAttribute("aria-invalid", "true"); - expect(document.body).not.toHaveTextContent("backend copy"); - }); - - // A validation refusal is not an unknown effect: the corrected value can - // be saved (the create classifier answers 422 NOT_APPLIED). - it("saves the corrected value after a server 422 field error", async () => { - const user = userEvent.setup(); - let sent = 0; - mockApi.server.use( - http.post("https://api.test/api/reference-resources", async ({ request }) => { - sent += 1; - if (sent === 1) { - return HttpResponse.json( - { - type: "https://api.test/problems/validation_rejected", - title: "VALIDATION_REJECTED", - status: 422, - code: "VALIDATION_REJECTED", - issues: [{ path: "name", code: "too_big" }], - }, - { status: 422 }, - ); - } - const body = (await request.json()) as { name: string }; - return HttpResponse.json( - { id: "reference-created-1", name: body.name }, - { status: 201 }, - ); - }), - ); - const composition = await createRuntimeComposition({ - fetcher: absoluteFetch, - host: {}, - }); - window.history.pushState({}, "", "/examples/reference-resources/new"); - render(); - - await user.click( - await screen.findByRole("button", { name: "로그인 시작" }), - ); - const name = await screen.findByRole("textbox", { name: /새 항목 이름/ }); - await user.type(name, "Too long for the server"); - await user.click(screen.getByRole("button", { name: "저장" })); - await waitFor(() => expect(name).toHaveAttribute("aria-invalid", "true")); - - await user.clear(name); - await user.type(name, "Short"); - expect(screen.getByRole("button", { name: "저장" })).toBeEnabled(); - await user.click(screen.getByRole("button", { name: "저장" })); - - expect(await screen.findByText("저장했습니다.")).toBeVisible(); - expect(sent).toBe(2); - }); -}); diff --git a/tests/features/reference-feature/reference-request-deduplication.test.ts b/tests/features/reference-feature/reference-request-deduplication.test.ts deleted file mode 100644 index 8dda7deb..00000000 --- a/tests/features/reference-feature/reference-request-deduplication.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; - -import { - createQueryClient, - QUERY_CACHE_DEFAULTS, -} from "../../../src/adapters/query-cache/tanstack-query-cache.ts"; -import { - jsonRows, - networkFailure, - type Transport, -} from "../../helpers/traffic-test-kit.ts"; -import { referenceFeatureOver } from "./reference-traffic-kit.ts"; - -/** - * scale-architecture.md §16. Multiple consumers of one query identity must not imply multiple - * physical requests. TanStack Query owns in-flight coalescing; this suite pins - * that the installed query client plus the real V3 executor keep it that way. - */ -describe("request deduplication and coalescing", () => { - function loadSameQuery( - client: ReturnType, - reference: ReturnType, - key: readonly unknown[] = ["reference", "list", { limit: 20 }], - ) { - return client.fetchQuery({ - queryKey: key, - queryFn: ({ signal }) => reference.listResources({ limit: 20 }, { signal }), - }); - } - - it("coalesces concurrent consumers of the same query identity", async () => { - const transport = vi.fn(async () => jsonRows(3)); - const reference = referenceFeatureOver(transport); - const client = createQueryClient(); - - const results = await Promise.all([ - loadSameQuery(client, reference), - loadSameQuery(client, reference), - loadSameQuery(client, reference), - ]); - - expect(transport).toHaveBeenCalledTimes(1); - expect(results.every((result) => result.ok)).toBe(true); - client.clear(); - }); - - it("keeps distinct query identities as distinct physical requests", async () => { - const transport = vi.fn(async () => jsonRows(1)); - const reference = referenceFeatureOver(transport); - const client = createQueryClient(); - - await Promise.all([ - loadSameQuery(client, reference, ["reference", "list", 1]), - loadSameQuery(client, reference, ["reference", "list", 2]), - ]); - - expect(transport).toHaveBeenCalledTimes(2); - client.clear(); - }); - - it("does not stack a query-layer retry on top of the executor retry budget", async () => { - expect(QUERY_CACHE_DEFAULTS.retry).toBe(false); - expect(QUERY_CACHE_DEFAULTS.mutationRetry).toBe(false); - - const transport = vi.fn(networkFailure); - const reference = referenceFeatureOver(transport, { maxRetryAttempts: 2 }); - const client = createQueryClient(); - - await Promise.all([ - loadSameQuery(client, reference), - loadSameQuery(client, reference), - ]); - - // One coalesced logical execution: 1 attempt + at most 2 executor retries. - expect(transport.mock.calls.length).toBeLessThanOrEqual(3); - client.clear(); - }); -}); diff --git a/tests/features/reference-feature/reference-request-fanout.test.ts b/tests/features/reference-feature/reference-request-fanout.test.ts deleted file mode 100644 index 0d5e759f..00000000 --- a/tests/features/reference-feature/reference-request-fanout.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; - -import { - assertRequestFanoutWithinBudget, - RequestFanoutExceededError, -} from "../../../src/platform/traffic/request-fanout.ts"; -import { - jsonRows, - paginatedCollection, - testExecutionContext, - type Transport, -} from "../../helpers/traffic-test-kit.ts"; -import { referenceFeatureOver } from "./reference-traffic-kit.ts"; - -/** Physical requests one representative collection load may cost. */ -const COLLECTION_LOAD_FANOUT_BUDGET = 1; - -describe("request fan-out budget", () => { - it.each([10, 50, 100, 1_000])( - "loads the first page of a %i-row collection with one physical request", - async (totalRows) => { - const transport = paginatedCollection(totalRows); - const reference = referenceFeatureOver(transport); - - const result = await reference.listResources({ limit: 100 }); - - expect(result).toMatchObject({ ok: true }); - expect(result.ok && result.value).toHaveLength(Math.min(totalRows, 100)); - expect(() => - assertRequestFanoutWithinBudget(transport.calls, COLLECTION_LOAD_FANOUT_BUDGET), - ).not.toThrow(); - }, - ); - - it("walks a 1,000-row collection in page-sized bulk requests, never one per row", async () => { - const transport = paginatedCollection(1_000); - const reference = referenceFeatureOver(transport); - const rows: unknown[] = []; - for (let cursor = 0; ; cursor += 100) { - const page = await reference.listResources({ - limit: 100, - ...(cursor === 0 ? {} : { cursor: String(cursor) }), - }); - expect(page.ok).toBe(true); - if (!page.ok || page.value.length === 0) break; - rows.push(...page.value); - if (page.value.length < 100) break; - } - expect(rows).toHaveLength(1_000); - // ceil(N / pageSize) + one empty terminal page, versus N per-row calls. - expect(transport.calls).toBeLessThanOrEqual(Math.ceil(1_000 / 100) + 1); - }); - - it("rejects a single oversized response in one request without row-proportional fan-out", async () => { - const transport = vi.fn(async () => jsonRows(1_000)); - const reference = referenceFeatureOver(transport); - - const result = await reference.listResources({ limit: 100 }); - - expect(result.ok).toBe(false); - expect(transport).toHaveBeenCalledTimes(1); - }); - - it("keeps a whole interaction's request count bounded while cardinality grows", async () => { - const counts: number[] = []; - for (const rows of [10, 100, 1_000]) { - const transport = vi.fn(paginatedCollection(rows)); - const reference = referenceFeatureOver(transport); - const execution = testExecutionContext({ maxPhysicalRequests: 3 }); - await reference.listResources({ limit: 100 }, { execution }); - counts.push(transport.mock.calls.length); - expect(execution.traffic.requests.consumed).toBe(transport.mock.calls.length); - } - expect(new Set(counts)).toEqual(new Set([1])); - }); - - it("fails loudly when a flow exceeds its fan-out budget", () => { - expect(() => assertRequestFanoutWithinBudget(4, 3)).toThrow( - RequestFanoutExceededError, - ); - expect(() => assertRequestFanoutWithinBudget(4, 3)).toThrow( - /fan-out 4 exceeds 3/, - ); - expect(() => assertRequestFanoutWithinBudget(1, 0)).toThrow(TypeError); - }); -}); diff --git a/tests/features/reference-feature/reference-resource-handlers.ts b/tests/features/reference-feature/reference-resource-handlers.ts deleted file mode 100644 index e58717ac..00000000 --- a/tests/features/reference-feature/reference-resource-handlers.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { http, HttpResponse } from "msw"; - -export type ReferenceResourceFixture = Readonly<{ - id: string; - name: string; - createdAt?: string; -}>; - -const DEFAULT_RESOURCE = Object.freeze({ - id: "reference-1", - name: "Reference", - createdAt: "2026-07-26T00:00:00.000Z", -}); - -/** - * A working reference resource API. Failure scenarios are the platform's HTTP - * scenario catalog (`tests/mocks/scenarios/catalog.ts`), which runs on the - * test contracts; a sample test that needs a failure overrides one route. - */ -export function createReferenceResourceHandlers( - options: Readonly<{ - baseUrl?: string; - resources?: ReferenceResourceFixture[]; - onList?(search: string): void; - onCreate?(body: Readonly>): void; - }> = {}, -) { - const baseUrl = options.baseUrl ?? "https://api.test"; - const resources = options.resources ?? [{ ...DEFAULT_RESOURCE }]; - return [ - http.get(`${baseUrl}/api/reference-resources`, ({ request }) => { - options.onList?.(new URL(request.url).search); - return HttpResponse.json(resources); - }), - http.post(`${baseUrl}/api/reference-resources`, async ({ request }) => { - const rawBody = await request.json(); - const body = - rawBody && typeof rawBody === "object" && !Array.isArray(rawBody) - ? (rawBody as Readonly>) - : {}; - options.onCreate?.(body); - const created = { - id: "reference-created", - name: String(body.name ?? "Created"), - createdAt: "2026-07-26T00:00:00.000Z", - }; - resources.push(created); - return HttpResponse.json(created); - }), - http.get(`${baseUrl}/api/reference-resources/:resourceId`, ({ params }) => - HttpResponse.json( - resources.find((entry) => entry.id === params.resourceId) ?? - DEFAULT_RESOURCE, - ), - ), - ] as const; -} diff --git a/tests/features/reference-feature/reference-route-links.test.tsx b/tests/features/reference-feature/reference-route-links.test.tsx deleted file mode 100644 index f3141761..00000000 --- a/tests/features/reference-feature/reference-route-links.test.tsx +++ /dev/null @@ -1,108 +0,0 @@ -// @vitest-environment jsdom - -import { screen } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; -import { describe, expect, it, vi } from "vitest"; - -import type * as ReferenceContractModule from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts"; -import { createFailure } from "../../../src/contracts/errors.ts"; -import { inputWith, renderReference } from "./reference-page-harness.tsx"; - -/** - * 1101/16-04. The contract's `path` is the only place a reference path is - * written. Every path is moved here, so a page that writes its own path - * string lands on the not-found page instead of the moved route. - */ -vi.mock( - "../../../src/features/reference-feature/contracts/reference-feature-contract.ts", - async (importOriginal) => { - const original = await importOriginal(); - const contract = original.REFERENCE_FEATURE_CONTRACT; - const moved = ( - routeId: keyof typeof contract.routes, - path: string, - ) => Object.freeze({ ...contract.routes[routeId], path }); - return { - ...original, - REFERENCE_FEATURE_CONTRACT: Object.freeze({ - ...contract, - routes: Object.freeze({ - REFERENCE_RESOURCE_LIST: moved( - "REFERENCE_RESOURCE_LIST", - "/examples/reference-resources/all", - ), - REFERENCE_RESOURCE_DETAIL: moved( - "REFERENCE_RESOURCE_DETAIL", - "/examples/reference-resources/entries/:resourceId", - ), - REFERENCE_RESOURCE_FORM: moved( - "REFERENCE_RESOURCE_FORM", - "/examples/reference-resources/create", - ), - REFERENCE_RESOURCE_STATUS: moved( - "REFERENCE_RESOURCE_STATUS", - "/examples/reference-resources/support", - ), - }), - }), - }; - }, -); - -const LIST = "/examples/reference-resources/all?limit=5"; -const LIST_HEADING = { level: 1, name: "참조 기능" } as const; - -describe("reference links follow the contract paths", () => { - it("moves between list, detail and form through the contract", async () => { - const user = userEvent.setup(); - renderReference( - inputWith({ - listResources: async () => ({ - ok: true, - value: [{ resourceId: "reference-1", title: "Loaded", createdAt: null }], - }), - }), - LIST, - ); - - const item = await screen.findByRole("link", { name: "Loaded" }); - expect(item).toHaveAttribute( - "href", - "/examples/reference-resources/entries/reference-1", - ); - await user.click(item); - await screen.findByText("Detail"); - await user.click(screen.getByRole("link", { name: "참조 리소스 목록" })); - await screen.findByRole("heading", LIST_HEADING); - - await user.click(screen.getByRole("button", { name: "새 항목 만들기" })); - await screen.findByRole("heading", { name: "Reference resource 만들기" }); - await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" })); - expect(await screen.findByRole("heading", LIST_HEADING)).toBeVisible(); - }); - - it("opens the support page and returns to the list through the contract", async () => { - const user = userEvent.setup(); - renderReference( - inputWith({ - listResources: async () => ({ - ok: false, - error: createFailure( - "UNKNOWN_CLIENT_FAILURE", - "LIST_REFERENCE_RESOURCES", - 0, - { requestId: "corr-moved" }, - ), - }), - }), - LIST, - ); - - await user.click(await screen.findByRole("button", { name: "지원 정보 확인" })); - expect( - await screen.findByRole("heading", { level: 1, name: "잠시 사용할 수 없습니다." }), - ).toBeVisible(); - await user.click(screen.getByRole("button", { name: "목록으로 이동" })); - expect(await screen.findByRole("heading", LIST_HEADING)).toBeVisible(); - }); -}); diff --git a/tests/features/reference-feature/reference-runtime-composition.test.ts b/tests/features/reference-feature/reference-runtime-composition.test.ts deleted file mode 100644 index bc76418f..00000000 --- a/tests/features/reference-feature/reference-runtime-composition.test.ts +++ /dev/null @@ -1,317 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; - -import type { DemoSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts"; -import { createRuntimeAdapters } from "../../../src/bootstrap/runtime-adapters.ts"; -import { createRuntimeIdentityRegistry } from "../../../src/contracts/query-keys.ts"; -import { bindQuery } from "../../../src/contracts/server-state.ts"; -import type { CacheScopeSnapshot } from "../../../src/contracts/server-state-scope.ts"; -import { - REFERENCE_FEATURE_ID, - REFERENCE_RESOURCE_INVALIDATION_TOPIC, -} from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts"; -import { testRuntimeConfig } from "../../helpers/runtime-config.ts"; - -type Runtime = Parameters[0]["runtime"]; -type Release = Parameters[0]["release"]; - -const runtime: Runtime = { - config: testRuntimeConfig({ - APP_ENV: "local", - API_BASE_URL: "http://localhost:8080", - TELEMETRY_ENABLED: false, - AUTH_MODE: "demo", - REQUEST_TIMEOUT_MS: 4321, - MAX_RETRY_ATTEMPTS: 0, - RELEASE_MANIFEST_URL: "/release-manifest.json", - CONFIG_SCHEMA_VERSION: "2.0", - CAPABILITY_OVERRIDES: { - REALTIME: "DEFAULT", - WEB_WORKER: "DEFAULT", - SERVICE_WORKER: "DEFAULT", - OFFLINE_COMMANDS: "DEFAULT", - }, - FEATURE_OVERRIDES: {}, - }), - configSchema: "V2", - build: { - buildId: "build-a", - commitSha: "abc123", - routerBasePath: "/", - runtimeConfigUrl: "/config.json", - }, - validationDurationMs: 0, -}; - -const release: Release = { - schemaVersion: 2, - appVersion: "0.2.0", - buildId: "build-a", - commitSha: "abc123", - configSchemaVersion: "2.0", - contractSet: { - setAlgorithm: "CA_CONTRACT_SET_V1", - setDigest: `sha256:${"0".repeat(64)}`, - packages: [], - }, - assetManifestHash: "hash-a", - releaseId: "release-a", - builtAt: "2026-07-25T00:00:00Z", - routeChunks: { "route-home": "assets/home.js" }, -}; - -function referenceBoundQueryKey() { - const scope: CacheScopeSnapshot = { - generation: 1, - fingerprint: "runtime-scope-fingerprint-0001", - identities: createRuntimeIdentityRegistry({ - tokenFactory: () => "runtime-identity-token-0001", - }), - signal: new AbortController().signal, - isCurrent: () => true, - }; - return bindQuery( - { - definitionId: "reference-resource-runtime-test-v1", - definitionVersion: 1, - owner: REFERENCE_FEATURE_ID, - namespace: "reference-resource", - namespaceVersion: 1, - operationId: "GET_REFERENCE_RESOURCE", - profileId: "DETAIL_STANDARD", - measureResult: () => ({ itemCount: 1, estimatedBytes: 8 }), - execute: async () => ({ ok: true as const, value: "reference-1" }), - }, - "reference-1", - scope, - ).queryKey; -} - -/** - * The installed feature inputs are partial by design: a feature the product - * manifest did not select supplies none. This suite is about the reference - * feature being composed, so it asserts that first and narrows once. - */ -async function referenceInput( - adapters: Awaited>, -) { - // 15-01. The input is created when the feature's runtime half loads. - const load = adapters.featureLoaders[REFERENCE_FEATURE_ID]; - const input = load ? (await load())[REFERENCE_FEATURE_ID] : undefined; - if (!input) { - throw new Error( - `${REFERENCE_FEATURE_ID} is not installed; the manifest did not select it`, - ); - } - return input; -} - -describe("reference feature runtime composition", () => { - it("invalidates a real bound query through the installed production graph", async () => { - const adapters = await createRuntimeAdapters({ runtime, release, host: {} }); - const queryKey = referenceBoundQueryKey(); - adapters.infrastructure.queryClient.setQueryData(queryKey, { - resourceId: "reference-1", - }); - - await adapters.infrastructure.queryInvalidation.invalidate([ - REFERENCE_RESOURCE_INVALIDATION_TOPIC, - ]); - - expect( - adapters.infrastructure.queryClient.getQueryState(queryKey)?.isInvalidated, - ).toBe(true); - adapters.infrastructure.dispose(); - }); - - it("executes installed feature HTTP through the composed contract registry", async () => { - const fetcher = vi.fn(async () => - Response.json([{ id: "reference-1", name: "Direct contract payload" }]), - ); - const adapters = await createRuntimeAdapters({ - runtime, - release, - host: {}, - fetcher, - }); - await adapters.outputPorts.session.beginSignIn(); - await vi.waitFor(() => - expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), - ); - - await expect( - (await referenceInput(adapters)).listResources({ limit: 20 }), - ).resolves.toEqual({ - ok: true, - value: [ - { - resourceId: "reference-1", - title: "Direct contract payload", - createdAt: null, - }, - ], - }); - expect(fetcher).toHaveBeenCalledWith( - "http://localhost:8080/api/reference-resources?limit=20", - expect.objectContaining({ - method: "GET", - redirect: "error", - cache: "no-store", - }), - ); - adapters.infrastructure.dispose(); - }); - - // 1103/10-04 ①. MAX_RETRY_ATTEMPTS is the operator's dial over every - // contract's retry budget (the list declares 2). Zero must stop retries. - // This drives it through the whole composition; the same rule without the - // sample is in tests/unit/runtime-adapters.test.ts (1105/10-01). - it.each([ - [0, 1], - [1, 2], - ])("honours MAX_RETRY_ATTEMPTS %i: a retryable list read goes out %i time(s)", async (maxRetryAttempts, sends) => { - const fetcher = vi.fn(async (_input: RequestInfo | URL) => - Response.json( - { type: "about:blank", title: "temporary", status: 503 }, - { status: 503 }, - ), - ); - // No backoff wait: the jitter is the random draw times a ceiling. - const random = vi.spyOn(Math, "random").mockReturnValue(0); - try { - const adapters = await createRuntimeAdapters({ - runtime: { - ...runtime, - config: { ...runtime.config, MAX_RETRY_ATTEMPTS: maxRetryAttempts }, - }, - release, - host: {}, - fetcher, - }); - await adapters.outputPorts.session.beginSignIn(); - await vi.waitFor(() => - expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), - ); - - await expect( - (await referenceInput(adapters)).listResources({ limit: 20 }), - ).resolves.toMatchObject({ ok: false, error: { kind: "SERVER_FAILURE" } }); - expect( - fetcher.mock.calls.filter(([url]) => - String(url).includes("/api/reference-resources"), - ), - ).toHaveLength(sends); - adapters.infrastructure.dispose(); - } finally { - random.mockRestore(); - } - }); - - it("keeps private command intent identity out of URLs and diagnostics", async () => { - const requests: Array> = []; - const fetcher = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { - requests.push({ - url: String(input), - headers: new Headers(init?.headers), - }); - return Response.json( - { id: "resource-1", name: "Created resource" }, - { status: 201 }, - ); - }); - const adapters = await createRuntimeAdapters({ - runtime, - release, - host: {}, - fetcher, - }); - await adapters.outputPorts.session.beginSignIn(); - await vi.waitFor(() => - expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), - ); - const intent = Object.freeze({ - intentId: "private-intent-id", - operationId: "CREATE_REFERENCE_RESOURCE", - canonicalInputIdentity: "private-canonical-input", - idempotencyKey: "private-idempotency-key", - createdAtMonotonicMs: 42, - }); - - await expect( - (await referenceInput(adapters)).createResource( - { name: "Created resource" }, - { intent }, - ), - ).resolves.toMatchObject({ ok: true }); - - expect(requests).toHaveLength(1); - expect(requests[0]?.headers.get("Idempotency-Key")).toBe( - "private-idempotency-key", - ); - expect(requests[0]?.url).toBe( - "http://localhost:8080/api/reference-resources", - ); - const safeEvidence = JSON.stringify({ - requests: requests.map((request) => request.url), - diagnostics: adapters.outputPorts.diagnostics.entries(), - }); - expect(safeEvidence).not.toContain("private-intent-id"); - expect(safeEvidence).not.toContain("private-canonical-input"); - expect(safeEvidence).not.toContain("private-idempotency-key"); - adapters.infrastructure.dispose(); - }); - - /** - * R-3.2. A request refused before dispatch because no credential exists is - * not a session verdict. Reporting it to the owner overwrote a recovering - * session and could loop through the scope fence; only a server 401 may. - */ - it("does not report a request refused before dispatch as a sign-out", async () => { - const fetcher = vi.fn(async () => Response.json([])); - const adapters = await createRuntimeAdapters({ - runtime, - release, - host: {}, - fetcher, - }); - const session = adapters.outputPorts.session as DemoSessionAdapter; - session.setState("recovery-pending"); - await vi.waitFor(() => - expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), - ); - const notifications = vi.fn(); - session.subscribe(notifications); - - await expect( - (await referenceInput(adapters)).listResources({ limit: 20 }), - ).resolves.toMatchObject({ ok: false }); - - expect(fetcher).not.toHaveBeenCalled(); - expect(session.getState()).toBe("recovery-pending"); - expect(notifications).not.toHaveBeenCalled(); - adapters.infrastructure.dispose(); - }); - - it("still signs out when the server answers 401", async () => { - const fetcher = vi.fn( - async () => new Response(null, { status: 401 }), - ); - const adapters = await createRuntimeAdapters({ - runtime, - release, - host: {}, - fetcher, - }); - await adapters.outputPorts.session.beginSignIn(); - await vi.waitFor(() => - expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), - ); - - await expect( - (await referenceInput(adapters)).listResources({ limit: 20 }), - ).resolves.toMatchObject({ ok: false }); - - expect(fetcher).toHaveBeenCalledOnce(); - expect(adapters.outputPorts.session.getState()).toBe("unauthenticated"); - adapters.infrastructure.dispose(); - }); -}); diff --git a/tests/features/reference-feature/reference-telemetry.test.ts b/tests/features/reference-feature/reference-telemetry.test.ts deleted file mode 100644 index 7415c894..00000000 --- a/tests/features/reference-feature/reference-telemetry.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; - -import { createReferenceFeatureInput } from "../../../src/features/reference-feature/application/reference-feature-api.ts"; -import { createFailure } from "../../../src/contracts/errors.ts"; -import type { TelemetryPort } from "../../../src/platform/telemetry/telemetry-port.ts"; -import { - createTelemetryPipeline, - type TelemetryTransport, -} from "../../../src/platform/telemetry/telemetry-pipeline.ts"; -import { REFERENCE_FEATURE_ADAPTER_CONTRIBUTION } from "../../../src/features/reference-feature/adapters/create-reference-feature-input.ts"; - -function failingGateway() { - const failure = Object.freeze({ - ok: false as const, - error: createFailure("REQUEST_TIMEOUT", "LIST_REFERENCE_RESOURCES", 0), - }); - return Object.freeze({ - list: vi.fn(async () => failure), - get: vi.fn(async () => failure), - create: vi.fn(async () => failure), - }); -} - -describe("reference feature telemetry through the platform port", () => { - it("declares the provider-neutral telemetry capability", () => { - expect(REFERENCE_FEATURE_ADAPTER_CONTRIBUTION.needs).toContain("telemetry"); - }); - - it("emits a feature-owned event with a bounded payload on load failure", async () => { - const emit = vi.fn(); - const input = createReferenceFeatureInput(failingGateway(), { telemetry: { emit } }); - - const result = await input.listResources({ limit: 20 }); - - expect(result.ok).toBe(false); - expect(emit).toHaveBeenCalledWith({ - kind: "reference.load.failed", - severity: "warning", - featureId: "reference-feature", - payload: { operation: "list", reason: "REQUEST_TIMEOUT" }, - }); - }); - - it("returns the business result even when the port throws or rejects", async () => { - const throwing = createReferenceFeatureInput(failingGateway(), { - telemetry: { - emit() { - throw new Error("port broken"); - }, - }, - }); - const rejecting = createReferenceFeatureInput(failingGateway(), { - telemetry: { emit: () => Promise.reject(new Error("collector down")) }, - }); - - await expect(throwing.getResource("id-1")).resolves.toMatchObject({ ok: false }); - await expect(rejecting.getResource("id-1")).resolves.toMatchObject({ ok: false }); - }); - - it("collapses a failure storm into bounded sends via the pipeline", async () => { - const send = vi.fn(); - const pipeline = createTelemetryPipeline({ transport: { send } }); - const input = createReferenceFeatureInput(failingGateway(), { telemetry: pipeline }); - - for (let i = 0; i < 500; i += 1) await input.listResources({ limit: 20 }); - await pipeline.flush(); - - // The first failure goes out at once; the 499 duplicates ride on the flush. - expect(send).toHaveBeenCalledTimes(2); - const occurrences = send.mock.calls - .flatMap(([batch]) => batch) - .reduce((sum, item) => sum + item.occurrences, 0); - expect(occurrences).toBe(500); - expect(pipeline.stats().deduplicated).toBe(499); - pipeline.dispose(); - }); -}); diff --git a/tests/features/reference-feature/reference-traffic-kit.ts b/tests/features/reference-feature/reference-traffic-kit.ts deleted file mode 100644 index 8ba9f024..00000000 --- a/tests/features/reference-feature/reference-traffic-kit.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { createReferenceFeatureInstalledInput } from "../../../src/features/reference-feature/adapters/create-reference-feature-input.ts"; -import { - scopeSnapshot, - testExecutor, - type Transport, -} from "../../helpers/traffic-test-kit.ts"; - -/** - * The reference feature's real application input, wired to the real V3 - * executor over an injected transport. Used to prove collection loads and - * multi-operation interactions stay bounded end to end. - */ -export function referenceFeatureOver( - transport: Transport, - options: Parameters[1] = {}, -) { - const executor = testExecutor(transport, { - credentialHeaders: { authorization: "Bearer traffic-test-token" }, - ...options, - }); - return createReferenceFeatureInstalledInput({ - http: Object.freeze({ - execute(operation, input, context) { - return executor.execute(operation, input, { - routeId: context.routeId, - scope: scopeSnapshot(), - ...(context.signal === undefined ? {} : { signal: context.signal }), - ...(context.intent === undefined ? {} : { intent: context.intent }), - ...(context.execution === undefined - ? {} - : { execution: context.execution }), - }); - }, - }), - }).input; -} diff --git a/tests/features/reference-feature/reference-traffic-policy.test.ts b/tests/features/reference-feature/reference-traffic-policy.test.ts deleted file mode 100644 index 18256539..00000000 --- a/tests/features/reference-feature/reference-traffic-policy.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { composeContractContributions } from "../../../src/contracts/external-contract-runtime.ts"; -import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts"; - -describe("reference operation traffic policy", () => { - it("declares explicit bounded traffic on every representative reference operation", () => { - const composed = composeContractContributions([ - REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION, - ]); - for (const operationId of [ - "LIST_REFERENCE_RESOURCES", - "GET_REFERENCE_RESOURCE", - "CREATE_REFERENCE_RESOURCE", - ]) { - const traffic = composed.httpByOperationId.get(operationId)?.frontend.traffic; - expect(traffic, operationId).toBeDefined(); - expect(Number.isSafeInteger(traffic?.maxPhysicalRequests)).toBe(true); - } - // A KEYED command never retries automatically; its policy says so too. - expect( - composed.httpByOperationId.get("CREATE_REFERENCE_RESOURCE")?.frontend - .traffic, - ).toMatchObject({ maxPhysicalRequests: 1, maxRetries: 0 }); - }); -}); diff --git a/tests/features/reference-feature/reference-validator-protocol.test.ts b/tests/features/reference-feature/reference-validator-protocol.test.ts deleted file mode 100644 index 91f70658..00000000 --- a/tests/features/reference-feature/reference-validator-protocol.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { - CREATE_REFERENCE_RESOURCE_CONTRACT, - LIST_REFERENCE_RESOURCES_CONTRACT, -} from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts"; - -/** - * Q-6.7-8 characterization. The reference feature's schemas answer through the - * canonical `RuntimeValidator` protocol (array paths) of its HTTP contract. - */ -describe("reference validator protocols", () => { - const badList = [{ id: "unsafe", name: 42 }]; - - it("answers the canonical validator with array paths", () => { - expect( - LIST_REFERENCE_RESOURCES_CONTRACT.contract.outputValidator.safeParse( - badList, - ), - ).toEqual({ - success: false, - issues: [{ path: [0, "name"], code: "invalid_type" }], - }); - expect( - CREATE_REFERENCE_RESOURCE_CONTRACT.contract.inputValidator.safeParse({ - name: " Example ", - }), - ).toEqual({ success: true, data: { name: "Example" } }); - }); -}); diff --git a/src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts b/tests/fixtures/indexeddb-consumer/adapters/create-local-draft-feature-input.ts similarity index 53% rename from src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts rename to tests/fixtures/indexeddb-consumer/adapters/create-local-draft-feature-input.ts index 9b7461cc..1fe0c005 100644 --- a/src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts +++ b/tests/fixtures/indexeddb-consumer/adapters/create-local-draft-feature-input.ts @@ -1,7 +1,7 @@ import { defineFeatureAdapterContribution, -} from "../../feature-adapter-contribution.ts"; -import type {} from "../../feature-adapter-contribution.ts"; +} from "../../../../src/features/feature-adapter-contribution.ts"; +import type {} from "../../../../src/features/feature-adapter-contribution.ts"; import { createLocalDraftFeatureInput, } from "../application/local-draft-api.ts"; @@ -14,7 +14,18 @@ import { type LocalDraftRepository, } from "./local-draft-indexeddb-store.ts"; -declare module "../../feature-adapter-contribution.ts" { +/** + * The IndexedDB consumer the tests compose: a local-draft store shaped like a + * feature's adapters, application and domain folders, with + * `needs: ["indexedDb"]`. It was the template's local-draft sample under + * src/features, a folder the generator skipped; it is a test fixture now. Its users: + * tests/contract/reusable-capability/feature-adapter-composition.test.ts, + * tests/contract/consumer-experience/indexeddb-local-draft.test.ts, + * tests/unit/local-draft-api.test.ts, tests/recipes/indexeddb-feature-capability.test.ts, + * tests/browser-capabilities/local-draft-composition.spec.ts and the recipe + * recipes/frontend-capabilities/indexeddb-feature-capability.ts. + */ +declare module "../../../../src/features/feature-adapter-contribution.ts" { interface FeatureIndexedDbRepositories { "local-draft": LocalDraftRepository; } diff --git a/src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts b/tests/fixtures/indexeddb-consumer/adapters/local-draft-indexeddb-store.ts similarity index 97% rename from src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts rename to tests/fixtures/indexeddb-consumer/adapters/local-draft-indexeddb-store.ts index 9f0fd0a9..bba11a29 100644 --- a/src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts +++ b/tests/fixtures/indexeddb-consumer/adapters/local-draft-indexeddb-store.ts @@ -2,8 +2,8 @@ import { createFailure, type AppFailure, type FailureKind, -} from "../../../contracts/errors.ts"; -import type { Result } from "../../../contracts/result.ts"; +} from "../../../../src/contracts/errors.ts"; +import type { Result } from "../../../../src/contracts/result.ts"; import type { LocalDraftStore, LocalDraftRecord, diff --git a/src/features/local-draft-feature/application/local-draft-api.ts b/tests/fixtures/indexeddb-consumer/application/local-draft-api.ts similarity index 88% rename from src/features/local-draft-feature/application/local-draft-api.ts rename to tests/fixtures/indexeddb-consumer/application/local-draft-api.ts index 3b384b63..bcfb98fd 100644 --- a/src/features/local-draft-feature/application/local-draft-api.ts +++ b/tests/fixtures/indexeddb-consumer/application/local-draft-api.ts @@ -1,6 +1,6 @@ -import { createFailure } from "../../../contracts/errors.ts"; -import type { Result } from "../../../contracts/result.ts"; -import type {} from "../../../application/ports/in/application-api.ts"; +import { createFailure } from "../../../../src/contracts/errors.ts"; +import type { Result } from "../../../../src/contracts/result.ts"; +import type {} from "../../../../src/application/ports/in/application-api.ts"; import { createLocalDraft, type LocalDraft } from "../domain/local-draft.ts"; export type LocalDraftRecord = Readonly<{ @@ -51,7 +51,7 @@ export type LocalDraftFeatureInput = Readonly<{ ): Promise>; }>; -declare module "../../../application/ports/in/application-api.ts" { +declare module "../../../../src/application/ports/in/application-api.ts" { interface ApplicationFeatureInputs { "local-draft": LocalDraftFeatureInput; } diff --git a/src/features/local-draft-feature/contracts/local-draft-contract.ts b/tests/fixtures/indexeddb-consumer/contracts/local-draft-contract.ts similarity index 100% rename from src/features/local-draft-feature/contracts/local-draft-contract.ts rename to tests/fixtures/indexeddb-consumer/contracts/local-draft-contract.ts diff --git a/src/features/local-draft-feature/domain/local-draft.ts b/tests/fixtures/indexeddb-consumer/domain/local-draft.ts similarity index 100% rename from src/features/local-draft-feature/domain/local-draft.ts rename to tests/fixtures/indexeddb-consumer/domain/local-draft.ts diff --git a/tests/fixtures/manual-code-blocks/manual-code-blocks.check.tsx b/tests/fixtures/manual-code-blocks/manual-code-blocks.check.tsx new file mode 100644 index 00000000..6bb0bf89 --- /dev/null +++ b/tests/fixtures/manual-code-blocks/manual-code-blocks.check.tsx @@ -0,0 +1,192 @@ +// @vitest-environment jsdom + +// What the manual's code blocks do. tests/unit/manual-code-blocks.test.ts +// copies this file into the tests folder of the feature the blocks are +// written for, in a repository copy that has that feature and the blocks at +// their marked paths, and puts the feature's folder name for `{{feature}}`. +// The imports resolve there, not here: written out, they would read as a +// product feature's residue to the removal drill (scripts/lib/feature-residue.ts). +import { act, renderHook } from "@testing-library/react"; +import type { ReactNode } from "react"; +import { MemoryRouter, useLocation } from "react-router-dom"; +import { describe, expect, it, vi } from "vitest"; + +import { createAnonymousSessionAdapter } from "../../../src/adapters/auth/index.ts"; +import { createFailure } from "../../../src/contracts/errors.ts"; +import { mapInvoiceCreateProblem } from "../../../src/features/{{feature}}/adapters/invoice-problem-mapping.ts"; +import { invoiceListSearchSchema } from "../../../src/features/{{feature}}/contracts/invoice-list-search.ts"; +import { + INVOICE_CREATE_EFFECT, + INVOICE_PROBLEM_VALIDATOR, +} from "../../../src/features/{{feature}}/contracts/invoice-problem-details.ts"; +import { createInvoice } from "../../../src/features/{{feature}}/domain/invoice.ts"; +import { useInvoiceFailureAction } from "../../../src/features/{{feature}}/presentation/use-invoice-failure-action.ts"; +import { useInvoiceListFilters } from "../../../src/features/{{feature}}/presentation/use-invoice-list-filters.ts"; +import { ApplicationProvider } from "../../../src/presentation/providers/application-provider.tsx"; +import { SessionProvider } from "../../../src/presentation/providers/session-provider.tsx"; +import { RouteInputProvider } from "../../../src/presentation/routes/route-input.tsx"; +import { createTestApplication } from "../../helpers/create-test-application.ts"; + +const PROBLEM = Object.freeze({ + type: "https://problems.example/invoice", + title: "Invoice refused", +}); + +describe("01 step 2: the domain model", () => { + it("keeps an invoice that falls due on or after its issue day, frozen", () => { + const invoice = createInvoice({ invoiceId: "inv-1", issuedOn: "2026-11-01", dueOn: "2026-11-01" }); + + expect(invoice).toEqual({ invoiceId: "inv-1", issuedOn: "2026-11-01", dueOn: "2026-11-01" }); + expect(Object.isFrozen(invoice)).toBe(true); + }); + + it("refuses an invoice due before it is issued, and a date that is no calendar date", () => { + expect(() => + createInvoice({ invoiceId: "inv-1", issuedOn: "2026-11-02", dueOn: "2026-11-01" }), + ).toThrow(RangeError); + expect(() => + createInvoice({ invoiceId: "inv-1", issuedOn: "2026-11-02", dueOn: "next week" }), + ).toThrow(RangeError); + }); +}); + +describe("02 section 4: a problem-details backend", () => { + it("reads a problem details body and keeps only its fields", () => { + const read = INVOICE_PROBLEM_VALIDATOR.safeParse({ + ...PROBLEM, + status: 422, + code: "INVOICE_REJECTED", + detail: "a backend message the screen never shows", + issues: [{ path: "dueOn", code: "BEFORE_ISSUE", message: "dropped" }], + }); + + expect(read).toEqual({ + success: true, + data: { + ...PROBLEM, + status: 422, + code: "INVOICE_REJECTED", + issues: [{ path: "dueOn", code: "BEFORE_ISSUE" }], + }, + }); + expect(INVOICE_PROBLEM_VALIDATOR.safeParse({ type: PROBLEM.type, status: 400 }).success).toBe(false); + expect(INVOICE_PROBLEM_VALIDATOR.schemaId).toBe("InvoiceProblem"); + }); + + it("calls a create refused only for 400, 422 and the declared 409 code", () => { + const classify = (status: number, code?: string) => + INVOICE_CREATE_EFFECT.classifyProblem({ + status, + problem: { ...PROBLEM, status, ...(code === undefined ? {} : { code }) }, + }); + + expect(classify(400)).toBe("NOT_APPLIED"); + expect(classify(422, "INVOICE_REJECTED")).toBe("NOT_APPLIED"); + expect(classify(409, "CONFLICT")).toBe("NOT_APPLIED"); + // A resend that meets the first attempt still running keeps its key. + expect(classify(409, "IDEMPOTENT_IN_FLIGHT")).toBe("MAYBE_APPLIED"); + expect(classify(409)).toBe("MAYBE_APPLIED"); + expect(classify(503, "IDEMPOTENCY_UNAVAILABLE")).toBe("MAYBE_APPLIED"); + expect(classify(500)).toBe("MAYBE_APPLIED"); + expect(INVOICE_CREATE_EFFECT.classifyStatus?.(403)).toBe("NOT_APPLIED"); + }); + + it("maps a conflict, a key rule mismatch and field issues, and leaves the rest to the executor", () => { + const problem = (status: number, extra: Readonly> = {}) => ({ + ...PROBLEM, + status, + ...extra, + }); + + expect(mapInvoiceCreateProblem(problem(409, { code: "CONFLICT" }), { status: 409 })).toEqual({ + kind: "CONFLICT", + code: "CONFLICT", + }); + expect(mapInvoiceCreateProblem(problem(409), { status: 409 })).toEqual({ + kind: "CONFLICT", + code: "INVOICE_CONFLICT", + }); + expect( + mapInvoiceCreateProblem(problem(400, { code: "IDEMPOTENCY_KEY_INVALID" }), { status: 400 }), + ).toEqual({ kind: "UNKNOWN_CLIENT_FAILURE", code: "IDEMPOTENCY_KEY_INVALID" }); + expect( + mapInvoiceCreateProblem(problem(422, { issues: [{ path: "dueOn", code: "BEFORE_ISSUE" }] }), { + status: 422, + }), + ).toEqual({ + kind: "VALIDATION_REJECTED", + code: "INVOICE_REJECTED", + validationIssues: [{ path: "dueOn", code: "BEFORE_ISSUE" }], + }); + expect(mapInvoiceCreateProblem(problem(400), { status: 400 })).toBeUndefined(); + expect(mapInvoiceCreateProblem(problem(503), { status: 503 })).toBeUndefined(); + }); +}); + +describe("01 step 6: reading the list route's search values", () => { + const withSearch = (search: Readonly>) => + function Search({ children }: Readonly<{ children: ReactNode }>) { + return ( + + {children} + + ); + }; + + it("reads the search the codec accepted, typed", () => { + expect(renderHook(useInvoiceListFilters, { wrapper: withSearch({ status: "open" }) }).result.current).toEqual({ + status: "open", + }); + expect(renderHook(useInvoiceListFilters, { wrapper: withSearch({}) }).result.current).toEqual({}); + }); + + it("refuses a value the router must answer with the invalid-route screen", () => { + expect(invoiceListSearchSchema.safeParse({ status: "void" }).success).toBe(false); + expect(invoiceListSearchSchema.safeParse({ status: "open", page: "2" }).success).toBe(false); + }); +}); + +describe("01 step 8: the failure action of a page", () => { + function renderAction(failure: Parameters[0]) { + const beginSignIn = vi.fn(async (_returnTo?: string) => {}); + const application = createTestApplication({ + session: { ...createAnonymousSessionAdapter(), beginSignIn }, + }); + const rendered = renderHook( + () => ({ handle: useInvoiceFailureAction(failure), location: useLocation() }), + { + wrapper: ({ children }: Readonly<{ children: ReactNode }>) => ( + + + {children} + + + ), + }, + ); + return { beginSignIn, rendered }; + } + + it("signs in again and comes back to the same URL", async () => { + const { beginSignIn, rendered } = renderAction(createFailure("AUTH_REQUIRED", "INVOICE_LIST_ITEMS", 0)); + + await act(async () => rendered.result.current.handle?.()); + + expect(beginSignIn).toHaveBeenCalledWith("/invoice?status=open#total"); + }); + + it("leaves a forbidden screen for home", async () => { + const { rendered } = renderAction(createFailure("FORBIDDEN", "INVOICE_LIST_ITEMS", 0)); + + await act(async () => rendered.result.current.handle?.()); + + expect(rendered.result.current.location.pathname).toBe("/"); + }); + + it("gives no handler for a retry or for no failure: the query owns retry", () => { + expect( + renderAction(createFailure("NETWORK_UNREACHABLE", "INVOICE_LIST_ITEMS", 0)).rendered.result.current.handle, + ).toBeUndefined(); + expect(renderAction(undefined).rendered.result.current.handle).toBeUndefined(); + }); +}); diff --git a/tests/fixtures/typecheck/invalid-route-runtime.ts b/tests/fixtures/typecheck/invalid-route-runtime.ts index 9fa3f9de..bc8ec5e0 100644 --- a/tests/fixtures/typecheck/invalid-route-runtime.ts +++ b/tests/fixtures/typecheck/invalid-route-runtime.ts @@ -2,9 +2,12 @@ import { ROUTE_RUNTIME_CONTRACT } from "../../../src/features/installed-feature- type RouteId = keyof typeof ROUTE_RUNTIME_CONTRACT; -export const missingRuntime = { - APP_HOME: true, -} satisfies Record; +// 2026-11-07. Exactly one route is left out. tsc names a short list of +// missing keys (TS2739) and a long one with "and N more" (TS2740), so an +// object that kept one route changed its diagnostic when the template's +// sample routes were deleted. One missing key is TS2741 at any route count. +declare const withoutHome: Omit, "APP_HOME">; +export const missingRuntime: Record = withoutHome; export const orphanRuntime = { ...Object.fromEntries( diff --git a/tests/helpers/playwright-run-isolation.ts b/tests/helpers/playwright-run-isolation.ts index 4e39f623..40c2024a 100644 --- a/tests/helpers/playwright-run-isolation.ts +++ b/tests/helpers/playwright-run-isolation.ts @@ -25,7 +25,14 @@ const PORT_VARIABLES: Readonly> = { storybook: "TEST_STORYBOOK_PORT", dev: "TEST_DEV_PORT", }; -const RUN_VARIABLES = ["TEST_RUN_ID", "RUN_OUTPUT_ROOT", ...Object.values(PORT_VARIABLES)]; +/** The port variables of the configs' second servers. */ +const SECOND_SERVER_PORT_VARIABLES = ["TEST_VISUAL_WORKSHOP_PORT"]; +const RUN_VARIABLES = [ + "TEST_RUN_ID", + "RUN_OUTPUT_ROOT", + ...Object.values(PORT_VARIABLES), + ...SECOND_SERVER_PORT_VARIABLES, +]; const held: Server[] = []; /** For afterEach: forgets the loaded configs and frees the ports `hold` took. */ @@ -111,12 +118,18 @@ function outputs(config: PlaywrightTestConfig) { }; } +/** The config's own server: the first one when it starts more than one. */ export function webServer(config: PlaywrightTestConfig) { - const server = config.webServer; - if (!server || Array.isArray(server)) throw new TypeError("expected one web server"); + const [server] = webServers(config); + if (!server) throw new TypeError("expected a web server"); return server; } +export function webServers(config: PlaywrightTestConfig) { + const servers = config.webServer; + return servers === undefined ? [] : Array.isArray(servers) ? servers : [servers]; +} + /** Each config's results, report and JUnit file, by its folder under artifacts/tests. */ export function describeResultFolders( runs: ConfigRuns, diff --git a/tests/recipes/indexeddb-feature-capability.test.ts b/tests/recipes/indexeddb-feature-capability.test.ts index c386dd6b..5bece537 100644 --- a/tests/recipes/indexeddb-feature-capability.test.ts +++ b/tests/recipes/indexeddb-feature-capability.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { composeFeatureAdapterInputs } from "../../src/features/feature-adapter-contribution.ts"; -import { LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION } from "../../src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts"; +import { LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION } from "../fixtures/indexeddb-consumer/adapters/create-local-draft-feature-input.ts"; import { createLocalDraftIndexedDbCapability } from "../../recipes/frontend-capabilities/indexeddb-feature-capability.ts"; import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts"; diff --git a/tests/scale/browser-soak.contract.test.ts b/tests/scale/browser-soak.contract.test.ts index c84bdef6..e6229dc1 100644 --- a/tests/scale/browser-soak.contract.test.ts +++ b/tests/scale/browser-soak.contract.test.ts @@ -92,8 +92,8 @@ describe("soak evaluation", () => { const totals = { cycles: 1_200, navigationFailures: 0, - referenceVisits: 200, - settledReferenceVisits: 40, + featureVisits: 200, + settledFeatureVisits: 40, finalInFlightRequests: 0, apiRequests: 240, telemetryPosts: 5, @@ -147,6 +147,7 @@ describe("soak evaluation", () => { intervalMs: 1, warmupMs: 0, routes: ["/"], + featureRoute: "/items", }); expect(result.status).toBe("skipped"); }); diff --git a/tests/scripts/generate-product-feature-index.test.ts b/tests/scripts/generate-product-feature-index.test.ts index 53b305d6..9bf4026f 100644 --- a/tests/scripts/generate-product-feature-index.test.ts +++ b/tests/scripts/generate-product-feature-index.test.ts @@ -145,7 +145,7 @@ describe("app-scoped selection from ownership declarations", () => { 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 () => { + it("refuses a feature directory without a declaration (09-07)", async () => { const files = { "src/apps/a/app-module.ts": app("a"), "src/contexts/c/context-module.ts": context("c", "a"), @@ -154,40 +154,20 @@ describe("app-scoped selection from ownership declarations", () => { "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, + /src\/features\/typo has no feature-module\.ts; add one, or keep code that is no feature outside src\/features/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. + it("reads a marker file as a missing declaration", async () => { + // The local-draft sample used to skip the check with a NOT_A_FEATURE + // file; it is a test fixture now and the marker is gone. 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", + "src/features/sample/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, + /src\/features\/sample has no feature-module\.ts/u, ); }); diff --git a/tests/storybook/galleries.spec.ts b/tests/storybook/galleries.spec.ts new file mode 100644 index 00000000..3bbd9f1c --- /dev/null +++ b/tests/storybook/galleries.spec.ts @@ -0,0 +1,113 @@ +import AxeBuilder from "@axe-core/playwright"; + +import { + expect, + test, + type Page, +} from "../support/browser/strict-browser-test.ts"; + +/** + * The design-system gallery (src/presentation/design-system/galleries.stories.tsx) + * in a real browser. These checks ran on the template's example screen + * `/examples/ui` until the galleries became workshop stories; the primitives + * keep their own component suites. The a11y addon's own axe run is switched + * off, as in workshop.spec.ts: the dialog check below owns it. + */ +async function openDesignSystemGallery(page: Page) { + await page.goto( + "/iframe.html?id=platform-galleries--design-system&viewMode=story&globals=a11y.manual:!true", + ); + await expect( + page.getByRole("heading", { level: 1, name: "UI 구성요소" }), + ).toBeVisible(); +} + +test("validates and reports the common text-field flow", async ({ page }) => { + await openDesignSystemGallery(page); + await page.getByRole("button", { name: "입력 확인" }).click(); + + const field = page.getByRole("textbox", { name: "프로젝트 이름" }); + await expect(field).toHaveAttribute("aria-invalid", "true"); + await expect(field).toHaveAccessibleDescription( + /프로젝트 이름을 입력해 주세요/, + ); + + await field.fill("Starter"); + await page.getByRole("button", { name: "입력 확인" }).click(); + await expect(page.getByText("“Starter” 입력을 확인했습니다.")).toBeVisible(); +}); + +test("traps modal interaction and restores focus to the trigger", async ({ + page, +}) => { + await openDesignSystemGallery(page); + const trigger = page.getByRole("button", { name: "모달 열기" }); + await trigger.click(); + + const dialog = page.getByRole("dialog", { name: "연동 확인" }); + await expect(dialog).toBeVisible(); + await expect( + dialog.getByRole("button", { name: "연동 확인 닫기" }), + ).toBeFocused(); + + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + await expect(trigger).toBeFocused(); +}); + +test("opened design-system dialog has no blocking violations", async ({ + page, +}) => { + await openDesignSystemGallery(page); + await page.getByRole("button", { name: "모달 열기" }).click(); + const results = await new AxeBuilder({ page }) + .include(".ui-dialog") + .withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]) + .analyze(); + expect( + results.violations.filter((violation) => + ["critical", "serious"].includes(violation.impact ?? ""), + ), + ).toEqual([]); +}); + +test("runs menu typeahead, tabs and duplicate toast interactions", async ({ + page, +}) => { + await openDesignSystemGallery(page); + + const menuTrigger = page.getByRole("button", { name: "작업 메뉴" }); + await menuTrigger.focus(); + await page.keyboard.press("ArrowDown"); + await page.keyboard.type("toast"); + const toastItem = page.getByRole("menuitem", { name: "Toast 표시" }); + await expect(toastItem).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(page.getByText("예제가 저장되었습니다.")).toBeVisible(); + await expect(menuTrigger).toBeFocused(); + + const tokenTab = page.getByRole("tab", { name: "토큰" }); + await tokenTab.focus(); + await page.keyboard.press("ArrowRight"); + const primitiveTab = page.getByRole("tab", { name: "프리미티브" }); + await expect(primitiveTab).toBeFocused(); + await expect(primitiveTab).toHaveAttribute("aria-selected", "false"); + await page.keyboard.press("Enter"); + await expect(primitiveTab).toHaveAttribute("aria-selected", "true"); + await expect( + page.getByRole("tabpanel", { name: "프리미티브" }), + ).toContainText("native semantics"); +}); + +test("reflows the gallery at the 320px minimum without horizontal overflow", async ({ + page, +}) => { + await page.setViewportSize({ width: 320, height: 720 }); + await openDesignSystemGallery(page); + + const viewport = await page.evaluate(() => ({ + clientWidth: document.documentElement.clientWidth, + scrollWidth: document.documentElement.scrollWidth, + })); + expect(viewport.scrollWidth).toBeLessThanOrEqual(viewport.clientWidth); +}); diff --git a/tests/unit/ci-workflow-generation.test.ts b/tests/unit/ci-workflow-generation.test.ts index 0368ce8d..d8dae090 100644 --- a/tests/unit/ci-workflow-generation.test.ts +++ b/tests/unit/ci-workflow-generation.test.ts @@ -196,11 +196,11 @@ describe("CI gate contract", () => { ).filter((gateId) => gateId !== "FE-GATE-016"), ); expect(contract.jobs).toHaveLength(10); - expect(contract.commands).toHaveLength(100); - expect(contract.gates.reduce((total, gate) => total + gate.commandIds.length, 0)).toBe(104); + expect(contract.commands).toHaveLength(99); + expect(contract.gates.reduce((total, gate) => total + gate.commandIds.length, 0)).toBe(103); expect(contract.commands.filter(({ expect }) => expect === "fail")).toHaveLength(30); - expect(contract.gates.reduce((total, gate) => total + gate.evidenceArtifactIds.length, 0)).toBe(88); - expect(contract.artifacts).toHaveLength(110); + expect(contract.gates.reduce((total, gate) => total + gate.evidenceArtifactIds.length, 0)).toBe(83); + expect(contract.artifacts).toHaveLength(105); expect(contract.stages).toHaveLength(5); expect(contract.retention.classes).toHaveLength(5); expect(index.gates.get("FE-GATE-015")?.commandIds).toHaveLength(2); diff --git a/tests/unit/feature-removal-argument.test.ts b/tests/unit/feature-removal-argument.test.ts index b5db92dc..54db1c99 100644 --- a/tests/unit/feature-removal-argument.test.ts +++ b/tests/unit/feature-removal-argument.test.ts @@ -1,7 +1,12 @@ import { spawnSync } from "node:child_process"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; import { describe, expect, it } from "vitest"; +import { REMOVABLE_TEMPLATE_FEATURES } from "../../scripts/lib/removable-template-features.ts"; + // 09-07 (D-10). The removal gate takes the feature to remove as an argument // instead of hard-coding the sample; an id no feature declares stops it before // any fixture is built. @@ -17,4 +22,26 @@ describe("feature removal argument", () => { /No installed feature declares FEATURE_MODULE_ID "missing-feature"/u, ); }); + + // 2026-11-07. Without --feature (FE-GATE-020) the drill removes the listed + // samples. The template lists none: the run says it skipped, and its report + // counts a skipped case, not a pass. + it("reports the drill as skipped when no sample is listed", async () => { + // A project that lists a sample runs the whole drill in FE-GATE-020. + if (REMOVABLE_TEMPLATE_FEATURES.length > 0) return; + const output = await mkdtemp(path.join(tmpdir(), "sample-removal-skip-")); + try { + const run = spawnSync(process.execPath, [path.resolve("scripts/test-sample-removal.ts")], { + cwd: output, + encoding: "utf8", + }); + expect(run.status, run.stderr).toBe(0); + expect(run.stdout).toMatch(/^sample removal: SKIP /mu); + expect(await readFile(path.join(output, "artifacts/tests/sample-removal.xml"), "utf8")).toMatch( + /tests="1" failures="0" skipped="1">.*; describe("feature-shape growth measurement (11-04)", () => { - it("renames every feature-owned identifier of a reference copy", () => { - const source = [ - 'featureId: "reference-feature"', - 'path: "/examples/reference-resources/:id"', - "REFERENCE_RESOURCE_LIST", - "ReferenceResourcePage", - 'contextId: "reference-context"', - 'topic: "qinv.01k10f7m3w9p6r2c8v5n4x"', - "NoRequest", - ].join("\n"); + it("plans each copy with create:feature, 200 to a context", () => { + const copies = FEATURES_PER_CONTEXT + 1; + const files = planShapeFeatures(copies); + const first = shapeFeature(0); + const last = shapeFeature(copies - 1); - const renamed = renameReferenceFeature(source, "s007", context); - - expect(renamed).not.toMatch(/reference/iu); - expect(renamed).toContain('featureId: "s007-feature"'); - expect(renamed).toContain('path: "/shape-0/s007-resources/:id"'); - expect(renamed).toContain("S007_RESOURCE_LIST"); - expect(renamed).toContain("S007ResourcePage"); - expect(renamed).toContain('contextId: "shape-context-0"'); - expect(renamed).toContain('topic: "qinv.shape.s007"'); - expect(renamed).toContain("S007NoRequest"); + expect([...files.keys()].filter((file) => file.endsWith("/context-module.ts"))).toEqual([ + `src/contexts/${first.context.id}/context-module.ts`, + `src/contexts/${last.context.id}/context-module.ts`, + ]); + expect(last.context.id).not.toBe(first.context.id); + for (const index of [0, FEATURES_PER_CONTEXT - 1, FEATURES_PER_CONTEXT]) { + const { id, context } = shapeFeature(index); + const module = files.get(`src/features/${id}/feature-module.ts`); + expect(module, id).toContain(`FEATURE_CONTEXT_ID = "${context.id}"`); + // The write slice: its detail and create pages are planned too. + expect([...files.keys()].filter((file) => file.startsWith(`src/features/${id}/`))).toEqual( + expect.arrayContaining([ + expect.stringMatching(/-detail-page\.tsx$/u), + expect.stringMatching(/-create-page\.tsx$/u), + ]), + ); + } + // Only what a build reads: no tests, no accessibility records. + expect([...files.keys()].every((file) => file.startsWith("src/"))).toBe(true); }); - // 1101/07-04 made assembly refuse a TEMPLATE_FIXTURE contribution outside - // the reference feature, so every copy must pin an EXTERNAL_PACKAGE the way - // a product feature does. - it("turns the copied fixture source into an external package", () => { - const source = [ - " source: Object.freeze({", - ' kind: "TEMPLATE_FIXTURE" as const,', - ' fixtureId: "REFERENCE_FEATURE_V1" as const,', - " revision: 1 as const,", - " }),", - " contractPackages: Object.freeze([]),", - ].join("\n"); - - const renamed = renameReferenceFeature(source, "s007", context); - - expect(renamed).not.toContain("TEMPLATE_FIXTURE"); - expect(renamed).toContain('kind: "EXTERNAL_PACKAGE" as const'); - expect(renamed.match(/packageId: "@feature-shape\/s007"/gu)).toHaveLength(2); - expect(renamed).not.toContain("contractPackages: Object.freeze([])"); - }); - - it("keeps platform-owned names that only contain the word", () => { - const source = - "REFERENCE_FEATURE_V1 supportReference"; - - expect(renameReferenceFeature(source, "s001", context)).toBe(source); + // 1101/07-04. Assembly refuses the template fixture source in a product + // feature, so every copy pins an external package of its own, and has a + // topic of its own. + it("pins a package and a topic of its own for every copy", () => { + const files = planShapeFeatures(3); + const contracts = [0, 1, 2].map((index) => { + const { id } = shapeFeature(index); + const contract = [...files].find(([file]) => + file.startsWith(`src/features/${id}/contracts/`) && file.endsWith("-feature-contract.ts"), + )?.[1]; + expect(contract, id).toContain(`packageId: "@feature-shape/${id}"`); + return contract ?? ""; + }); + const topics = contracts.map((contract) => /"(qinv\.[0-9a-z]{26})"/u.exec(contract)?.[1]); + expect(new Set(topics).size).toBe(3); + expect(contracts.join("\n")).not.toContain("PLACEHOLDER_CONTRACT_PACKAGE"); }); it("commits a baseline measured at 25 and 100 real-shape features, twice each", async () => { @@ -91,8 +86,11 @@ describe("feature-shape growth measurement (11-04)", () => { ) as Readonly<{ environment: Readonly>; source: unknown; + sourceFeature: unknown; runs: readonly Run[]; }>; + // 2026-11-07. Measured with the generated feature, not the deleted sample. + expect(baseline.sourceFeature).toBe(SHAPE_FEATURE_COMMAND); expect(baseline.environment).toMatchObject({ cpuModel: expect.any(String), logicalCpus: expect.any(Number), @@ -113,7 +111,7 @@ describe("feature-shape growth measurement (11-04)", () => { // A failed typecheck is the result and is not repeated. expect(runs.length).toBeGreaterThanOrEqual(runs[0]?.tsc.passed ? 2 : 1); for (const run of runs) { - // Every copy contributes the reference feature's own routes. + // Every copy contributes the generated feature's own routes. expect((run.routes - origin!.routes) % size).toBe(0); expect(run.routes).toBeGreaterThan(origin!.routes); expect(run.build.lazyJavascriptFiles).toBeGreaterThan( @@ -140,8 +138,12 @@ describe("feature-shape growth measurement (11-04)", () => { * 1103/15-04. The first copy also adds a context (shape-context-0), so one * number mixed a context's cost with a feature's and had 40 B left under * the bound. A second copy in the same context is one more feature alone; - * the rest of the first copy is the context. Each has its own bound and - * the failure names which one grew. + * the second copy in a context of its own is one more context. Each has its + * own bound and the failure names which one grew. 2026-11-07: with no + * feature in the template, the first copy also brings the code all features + * share into the initial chunks (`firstFeatureGzipBytes`); it is paid once + * and recorded, not bounded here: the initial budget (check:bundle) bounds + * the total. * * 1103/15-02. The record in config/scale/feature-shape-ceilings.json is the * one place the documents take the template's baseline from. Written by @@ -176,6 +178,7 @@ describe("feature-shape growth measurement (11-04)", () => { const measured = { gzipBytes: 200_000, files: 25, + firstFeatureGzipBytes: 5_000, perFeatureGzipBytes: 700, perContextGzipBytes: 250, }; @@ -203,6 +206,12 @@ describe("feature-shape growth measurement (11-04)", () => { expect( initialJavascriptRecordDrift(measured, { ...measured, perFeatureGzipBytes: 800 }), ).toEqual(["perFeatureGzipBytes: record 800, build 700"]); + // A cost of a few bytes keeps a floor: gzip moves it by a byte or two. + const tiny = { ...measured, perContextGzipBytes: 4 }; + expect(initialJavascriptRecordDrift(tiny, { ...tiny, perContextGzipBytes: 6 })).toEqual([]); + expect(initialJavascriptRecordDrift(tiny, { ...tiny, perContextGzipBytes: 30 })).toEqual([ + "perContextGzipBytes: record 30, build 4", + ]); }); it("states in the committed rationale what the ceilings rest on", async () => { @@ -218,7 +227,7 @@ describe("feature-shape growth measurement (11-04)", () => { expect(rationale.baseline).toBe(FEATURE_SHAPE_BASELINE_PATH); expect(rationale.ceilings).toEqual({ - contextMaxFeatures: CONTEXT_MAX_FEATURES, + contextMaxFeatures: FEATURES_PER_CONTEXT, appMaxContexts: APP_MAX_CONTEXTS, }); expect(rationale.axes.map((row) => row.axis)).toEqual( diff --git a/tests/unit/feature-tracked-files.test.ts b/tests/unit/feature-tracked-files.test.ts index 3a7eaa1f..6ef9c9ca 100644 --- a/tests/unit/feature-tracked-files.test.ts +++ b/tests/unit/feature-tracked-files.test.ts @@ -6,8 +6,8 @@ import { FEATURE_TRACKED_FILE_REWRITES } from "../../scripts/create-feature.ts"; /** * 1105/16-01. Adding a feature changes two tracked template files: the dev - * server's manifest (`create:feature` rewrites it) and, while the sample is - * installed, the initial JavaScript record (rewritten by command). The 03 + * server's manifest (`create:feature` rewrites it) and the initial + * JavaScript record (rewritten by command). The 03 * manual's section A said the command writes two files outside the feature * folder and named neither, the canonical table in starter-experience.md * had neither, and nothing said what to do when two feature branches change diff --git a/tests/unit/local-build-environment.test.ts b/tests/unit/local-build-environment.test.ts index 18c60e42..77b6ad44 100644 --- a/tests/unit/local-build-environment.test.ts +++ b/tests/unit/local-build-environment.test.ts @@ -41,8 +41,9 @@ describe("local build environment (1103/11-08)", () => { }); it("starts the visual goldens' build as a local build inside a CI job", () => { + // The app preview is the first server; the second serves the workshop. const webServer = visualConfig.webServer; - const env = Array.isArray(webServer) ? undefined : webServer?.env; + const env = (Array.isArray(webServer) ? webServer[0] : webServer)?.env; // Playwright merges a web server's env over the runner's process.env. expect(ciBuildEnvironmentFailures({ ...CI_JOB, ...env })).toEqual([]); diff --git a/tests/unit/local-draft-api.test.ts b/tests/unit/local-draft-api.test.ts index 337f29db..b199a9bc 100644 --- a/tests/unit/local-draft-api.test.ts +++ b/tests/unit/local-draft-api.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest"; import { createLocalDraftFeatureInput, type LocalDraftStore, -} from "../../src/features/local-draft-feature/application/local-draft-api.ts"; +} from "../fixtures/indexeddb-consumer/application/local-draft-api.ts"; function recordingStore() { const save = vi.fn(async () => diff --git a/tests/unit/manual-code-blocks.test.ts b/tests/unit/manual-code-blocks.test.ts new file mode 100644 index 00000000..10ddabc9 --- /dev/null +++ b/tests/unit/manual-code-blocks.test.ts @@ -0,0 +1,140 @@ +import { spawnSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { cp, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +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"; + +/** + * 2026-11-07. The template ships no sample feature: what the generated + * feature does not show, docs/manual shows as code blocks a product copies + * into its feature folder. Each such block has `` + * above it, the path in the feature `create:feature invoice-feature + * --with-create` writes. Here a copy of the repository gets that feature, each + * 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. + */ +const MANUAL = "docs/manual"; +const FEATURE_ID = "invoice-feature"; +const CHECKS = "tests/fixtures/manual-code-blocks"; +const MARKED_BLOCK = /\n```tsx?\n([\s\S]*?)\n```/gu; + +async function manualDocuments(directory: string): Promise { + const documents: string[] = []; + for (const entry of await readdir(directory, { withFileTypes: true })) { + const target = path.join(directory, entry.name); + if (entry.isDirectory()) documents.push(...(await manualDocuments(target))); + else if (entry.name.endsWith(".md")) documents.push(target); + } + return documents.sort(); +} + +/** Each marked block by the path it goes to. */ +async function markedBlocks(): Promise> { + const blocks = new Map(); + for (const document of await manualDocuments(MANUAL)) { + for (const [, target = "", body = ""] of (await readFile(document, "utf8")).matchAll(MARKED_BLOCK)) { + if (blocks.has(target)) throw new Error(`${target} is marked twice in ${MANUAL}`); + blocks.set(target, `${body}\n`); + } + } + return blocks; +} + +const roots: string[] = []; + +afterAll(async () => { + await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))); +}); + +async function copyRepository(): Promise { + const root = await mkdtemp(path.join(tmpdir(), "manual-code-blocks-")); + roots.push(root); + for (const entry of REMOVAL_FIXTURE_COPY_TARGETS) { + // A removal drill runs this test in a copy that has already lost some. + if (!existsSync(path.resolve(entry))) continue; + await cp(path.resolve(entry), path.join(root, entry), { + recursive: true, + filter: (source) => !source.includes(`${path.sep}.generated`), + }); + } + await linkFixtureNodeModules(root); + return root; +} + +function run(root: string, command: string, args: readonly string[]) { + const result = spawnSync(command, args, { cwd: root, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); + return { status: result.status, output: `${result.stdout}${result.stderr}` }; +} + +describe("docs/manual code blocks, pasted into a generated feature", () => { + it("marks each block with a path in the feature it is written for", async () => { + const targets = [...(await markedBlocks()).keys()].sort(); + + expect(targets).toEqual([ + "src/features/invoice-feature/adapters/invoice-problem-mapping.ts", + "src/features/invoice-feature/contracts/invoice-list-search.ts", + "src/features/invoice-feature/contracts/invoice-problem-details.ts", + "src/features/invoice-feature/domain/invoice.ts", + "src/features/invoice-feature/presentation/use-invoice-failure-action.ts", + "src/features/invoice-feature/presentation/use-invoice-list-filters.ts", + "tests/features/invoice-feature/invoice-forbidden.test.tsx", + ]); + }); + + it("typechecks, lints and does what the manual says", async () => { + const blocks = await markedBlocks(); + const root = await copyRepository(); + const node = process.execPath; + + // The generator runs first, as `corepack pnpm create:feature` does. + const indexed = run(root, node, ["scripts/generate-product-feature-index.ts"]); + expect(indexed.status, indexed.output).toBe(0); + const created = run(root, node, ["scripts/create-feature.ts", FEATURE_ID, "--with-create"]); + expect(created.status, created.output).toBe(0); + + for (const [target, block] of blocks) { + const file = path.join(root, 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); + } + 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), + ); + } + + for (const program of ["tsconfig.app.json", "tsconfig.test.json"]) { + const typecheck = run(root, path.resolve("node_modules/.bin/tsc"), ["--project", program]); + expect(typecheck.output, program).toBe(""); + expect(typecheck.status, program).toBe(0); + } + const lint = run(root, path.resolve("node_modules/.bin/eslint"), [ + `src/features/${FEATURE_ID}`, + `tests/features/${FEATURE_ID}`, + "--max-warnings=0", + ]); + expect(lint.output).toBe(""); + expect(lint.status).toBe(0); + const architecture = run(root, node, ["scripts/check-architecture.ts"]); + expect(architecture.status, architecture.output).toBe(0); + + const tests = run(root, node, [ + "scripts/run-vitest.ts", + "run", + `tests/features/${FEATURE_ID}`, + "--reporter=dot", + ]); + expect(tests.status, tests.output).toBe(0); + }, 300_000); +}); diff --git a/tests/unit/playwright-run-isolation.test.ts b/tests/unit/playwright-run-isolation.test.ts index ec91aafb..ce1f3f85 100644 --- a/tests/unit/playwright-run-isolation.test.ts +++ b/tests/unit/playwright-run-isolation.test.ts @@ -8,8 +8,10 @@ import { describeServerPorts, itExitsWhenItsPortIsTaken, itKeepsTheViteCacheInTheRun, + hold, releaseRuns, webServer, + webServers, } from "../helpers/playwright-run-isolation.ts"; /** @@ -87,6 +89,43 @@ describe("the build a run serves", () => { describeServerPorts(runs, ["e2e", "visual", "storybook", "dev"]); +// The gallery goldens open workshop stories: the visual config starts the +// static workshop next to its preview, on a port of its own. +describe("the visual config's workshop server", () => { + const workshop = async (environment: Readonly> = {}) => { + const runner = await runs.loadProcess("visual", environment); + const servers = webServers(runner.config); + expect(servers).toHaveLength(2); + return { runner, server: servers[1]! }; + }; + + it("is a free port of its own the runner hands to its workers", async () => { + const { runner, server } = await workshop(); + const port = Number(runner.after["TEST_VISUAL_WORKSHOP_PORT"]); + + expect(port).toBeGreaterThan(0); + expect(port).not.toBe(Number(runner.after["TEST_VISUAL_PORT"])); + expect(server.url).toBe(`http://127.0.0.1:${port}`); + expect(server.command).toMatch(new RegExp(` ${port}$`, "u")); + expect(server.reuseExistingServer).toBe(false); + }); + + it("moves for a second run while the first run's server holds its port", async () => { + const first = (await workshop()).server.url; + await hold(Number(new URL(String(first)).port)); + + expect((await workshop()).server.url).not.toBe(first); + }); + + it("serves the build the workshop config serves, in the run's folder", async () => { + const pinned = { TEST_VISUAL_WORKSHOP_PORT: "40124", TEST_STORYBOOK_PORT: "40124" }; + for (const environment of [pinned, { ...pinned, TEST_RUN_ID: "a" }]) { + const { server } = await workshop(environment); + expect(server.command).toBe(webServer(await runs.load("storybook", environment)).command); + } + }); +}); + describe("vite servers", () => { itExitsWhenItsPortIsTaken(runs, ["e2e", "visual", "dev"]); }); diff --git a/tests/unit/removal-fixture.test.ts b/tests/unit/removal-fixture.test.ts index 0901a824..d9c54fce 100644 --- a/tests/unit/removal-fixture.test.ts +++ b/tests/unit/removal-fixture.test.ts @@ -75,18 +75,21 @@ async function copyCiContract(prefix: string): Promise { it("prunes removed command and evidence references and re-baselines the contract", async () => { const root = await copyCiContract("removal-fixture-contract-"); + // A command with evidence of its own, as a removed sample's tests had. Not + // one a removal drill deletes: this test also runs inside those copies + // (test:recipes is gone in the optional-recipe removal copy). await pruneRemovalFixtureCiContract({ root, - removedScripts: new Set(["test:reference-feature"]), - removedEvidencePathFragments: ["reference-feature.xml"], + removedScripts: new Set(["test:integration"]), + removedEvidencePathFragments: ["integration.xml"], }); const contract = await loadCiGateContract(root); - expect(contract.commands.some(({ script }) => script === "test:reference-feature")).toBe(false); - expect(contract.artifacts.some(({ path }) => path.includes("reference-feature.xml"))).toBe(false); - expect(contract.gates.some(({ commandIds }) => commandIds.includes("test-reference-feature"))).toBe(false); + expect(contract.commands.some(({ script }) => script === "test:integration")).toBe(false); + expect(contract.artifacts.some(({ path }) => path.includes("integration.xml"))).toBe(false); + expect(contract.gates.some(({ commandIds }) => commandIds.includes("test-integration"))).toBe(false); expect(contract.gates.some(({ evidenceArtifactIds }) => - evidenceArtifactIds.includes("artifact-artifacts-tests-reference-feature-xml") + evidenceArtifactIds.includes("artifact-artifacts-tests-integration-xml") )).toBe(false); const baseline = JSON.parse( await readFile(path.join(root, "config/ci/contract-baseline.json"), "utf8"), @@ -296,7 +299,7 @@ describe("release evidence fixture copy", () => { describe("removal JUnit report (14-08)", () => { it("counts every failure and gives each check its own cause", () => { - const xml = renderRemovalJunit("reference-feature-removal", [ + const xml = renderRemovalJunit("sample-feature-removal", [ { name: "typecheck", passed: false, failure: "corepack pnpm check:types exited 2" }, { name: "architecture", passed: true }, { name: "build", passed: false, failure: "corepack pnpm build exited 1" }, diff --git a/tests/unit/template-feature-removal-documents.test.ts b/tests/unit/template-feature-removal-documents.test.ts index a8de7cc2..f0ba8b96 100644 --- a/tests/unit/template-feature-removal-documents.test.ts +++ b/tests/unit/template-feature-removal-documents.test.ts @@ -14,49 +14,80 @@ import { import { REMOVAL_FIXTURE_COPY_TARGETS } from "../../scripts/lib/removal-fixture.ts"; /** - * 1105/14-01. The CHANGELOG tells a product (tech-log) to delete the example - * screens' feature, and the template's own documents name that feature's - * folders. A copy that deleted them failed verify:documentation and the - * FE-GATE-005 copy of it ("passes the documents as they are"), and only the - * reference sample's removal was ever tried. The features come from - * scripts/lib/removable-template-features.ts, so no feature ID is written - * here: the removal drills refuse a test that still names the removed one. + * 1105/14-01. A copy that deleted a sample listed in + * scripts/lib/removable-template-features.ts failed verify:documentation and + * 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. */ const CHECKER = "scripts/verify-documentation-readiness.ts"; /** What verify:documentation reads besides the code. */ const DOCUMENTS = Object.freeze(["README.md", "CHANGELOG.md", "docs", "artifacts/tests/a11y-manual"]); +const LISTED_SAMPLE = Object.freeze({ + featureId: "listed-sample-feature", + contextDirectory: "src/contexts/listed-sample-context", + extraPaths: Object.freeze([]), + scripts: Object.freeze([]), +}); +const NAMING_DOCUMENT = "docs/architecture/starter-experience.md"; + /** - * Runs verify:documentation in a copy of the repository without `removed`, - * as a product that deleted it has it. The code facts are the copy's: - * tests/unit/documentation-readiness.test.ts copies only the documents and - * looks paths up in this repository, where nothing is deleted. The feature - * index is generated again, as the product does after the deletion. + * A copy of the repository with LISTED_SAMPLE installed, listed and named in + * NAMING_DOCUMENT (its module and a file it does not have). `verify` runs the + * copy's verify:documentation; `remove` deletes the sample as a product does + * (its paths and route records), then generates the feature index again. */ -async function verifyWithout(removed: readonly string[]) { +async function copyWithListedSample() { const parent = await mkdtemp(path.join(tmpdir(), "template-feature-removal-")); const root = path.join(parent, "frontend"); - try { - for (const entry of [...REMOVAL_FIXTURE_COPY_TARGETS, ...DOCUMENTS]) { - // A drill runs this test in a copy that has already lost some of them. - if (!existsSync(entry)) continue; - await cp(entry, path.join(root, entry), { - recursive: true, - filter: (source) => !source.includes(`${path.sep}.generated`), - }); - } - await linkFixtureNodeModules(root); - for (const entry of removed) await rm(path.join(root, entry), { recursive: true, force: true }); - const generated = spawnSync( - process.execPath, - [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], - { encoding: "utf8" }, - ); - expect(generated.status, generated.stderr).toBe(0); - return spawnSync(process.execPath, [path.join(root, CHECKER)], { cwd: root, encoding: "utf8" }); - } finally { - await rm(parent, { recursive: true, force: true }); + for (const entry of [...REMOVAL_FIXTURE_COPY_TARGETS, ...DOCUMENTS]) { + // A drill runs this test in a copy that has already lost some of them. + if (!existsSync(entry)) continue; + await cp(entry, path.join(root, entry), { + recursive: true, + filter: (source) => !source.includes(`${path.sep}.generated`), + }); } + await linkFixtureNodeModules(root); + const node = (args: readonly string[]) => + spawnSync(process.execPath, args, { cwd: root, encoding: "utf8" }); + for (const args of [ + ["scripts/generate-product-feature-index.ts"], + ["scripts/create-feature.ts", LISTED_SAMPLE.featureId], + ]) { + const result = node(args); + expect(result.status, `${result.stdout}${result.stderr}`).toBe(0); + } + const list = path.join(root, "scripts/lib/removable-template-features.ts"); + const listed = (await readFile(list, "utf8")).replace( + "Object.freeze([]);", + `Object.freeze([${JSON.stringify(LISTED_SAMPLE)}]);`, + ); + expect(listed).toContain(LISTED_SAMPLE.featureId); + await writeFile(list, listed); + const named = [ + `src/features/${LISTED_SAMPLE.featureId}/feature-module.ts`, + `src/features/${LISTED_SAMPLE.featureId}/no-such-module.ts`, + ]; + const document = path.join(root, NAMING_DOCUMENT); + await writeFile( + document, + `${await readFile(document, "utf8")}\n${named.map((file) => `- \`${file}\``).join("\n")}\n`, + ); + return { + named, + verify: () => node([CHECKER]), + async remove() { + for (const entry of removableTemplateFeaturePaths(LISTED_SAMPLE)) { + await rm(path.join(root, entry), { recursive: true, force: true }); + } + await rm(path.join(root, "artifacts/tests/a11y-manual/LISTED_SAMPLE_LIST.md"), { force: true }); + expect(node(["scripts/generate-product-feature-index.ts"]).status).toBe(0); + }, + cleanUp: () => rm(parent, { recursive: true, force: true }), + }; } /** @@ -83,34 +114,33 @@ async function verifyDocuments(document: string, mutate: (text: string) => strin } } -describe("verify:documentation after a template feature is deleted (1105/14-01)", () => { - it.each(REMOVABLE_TEMPLATE_FEATURES.map((feature) => [feature.featureId, feature] as const))( - "passes in a copy without %s", - async (_featureId, feature) => { - const result = await verifyWithout(removableTemplateFeaturePaths(feature)); - expect(result.status, result.stderr).toBe(0); - }, - 120_000, - ); +describe("verify:documentation after a listed sample is deleted (1105/14-01)", () => { + // Only a deleted sample's paths are let through. While it is installed a + // missing path under it fails; once it is deleted, the documents that name + // it pass. + it("fails on a missing path under an installed sample and passes once it is deleted", async () => { + const copy = await copyWithListedSample(); + try { + const installed = copy.verify(); + expect(installed.status).toBe(1); + expect(installed.stderr).toContain(`${NAMING_DOCUMENT} names paths that do not exist:`); + expect(installed.stderr).toContain(copy.named[1]); + expect(installed.stderr).not.toContain(copy.named[0]); - // Only a deleted feature's paths are let through. While a feature is - // installed a missing path under it fails, and so does a feature folder - // that is not on the list (a misspelt one). - it("still fails on a missing path under an installed template feature or an unknown folder", async () => { - const document = "docs/architecture/starter-experience.md"; - const missing = [ - ...REMOVABLE_TEMPLATE_FEATURES.filter((feature) => - existsSync(`src/features/${feature.featureId}/feature-module.ts`), - ).map((feature) => `src/features/${feature.featureId}/no-such-module.ts`), - "src/features/no-such-template-feature/feature-module.ts", - ]; - const result = await verifyDocuments( - document, - (text) => `${text}\n${missing.map((file) => `- \`${file}\``).join("\n")}\n`, - ); + await copy.remove(); + const deleted = copy.verify(); + expect(deleted.status, deleted.stderr).toBe(0); + } finally { + await copy.cleanUp(); + } + }, 180_000); + + it("still fails on a feature folder that is not on the list", async () => { + const missing = "src/features/no-such-template-feature/feature-module.ts"; + const result = await verifyDocuments(NAMING_DOCUMENT, (text) => `${text}\n- \`${missing}\`\n`); expect(result.status).toBe(1); - expect(result.stderr).toContain(`${document} names paths that do not exist:`); - for (const file of missing) expect(result.stderr).toContain(file); + expect(result.stderr).toContain(`${NAMING_DOCUMENT} names paths that do not exist:`); + expect(result.stderr).toContain(missing); }, 60_000); }); diff --git a/tests/unit/vite-build-inputs.test.ts b/tests/unit/vite-build-inputs.test.ts index c53cde92..0e716163 100644 --- a/tests/unit/vite-build-inputs.test.ts +++ b/tests/unit/vite-build-inputs.test.ts @@ -3,8 +3,6 @@ import path from "node:path"; import { describe, expect, it } from "vitest"; -import { REMOVABLE_TEMPLATE_FEATURES } from "../../scripts/lib/removable-template-features.ts"; - /** * 1105/15-03. Two copies of the list of files `vite build` reads from the * root (the initial JavaScript measurement and the @@ -15,24 +13,12 @@ import { REMOVABLE_TEMPLATE_FEATURES } from "../../scripts/lib/removable-templat */ const LIST_MODULE = "scripts/lib/vite-build-inputs.ts"; const MEASUREMENT = "scripts/scale/measure-feature-shape-growth.ts"; -// 1106/10-01. The measurement copies the reference sample and is one of its -// files (scripts/lib/removable-template-features.ts), so test:sample-removal -// deletes it with the sample. It is left out only where its owner is not -// installed: the owner's feature-module.ts is gone, the rule -// verify:documentation uses. The build test is a template file and is always -// read. Filtering both on "the file exists" let a renamed consumer drop out of -// the check unnoticed. The owner is found by its files, not written here: the -// sample drill fails on any test that still names the sample. -const MEASUREMENT_OWNER = REMOVABLE_TEMPLATE_FEATURES.find((feature) => - feature.extraPaths.includes(MEASUREMENT), -); -const OWNER_INSTALLED = - MEASUREMENT_OWNER !== undefined && - existsSync(`src/features/${MEASUREMENT_OWNER.featureId}/feature-module.ts`); -const CONSUMERS = [ - "tests/unit/product-feature-selection-build.test.ts", - ...(OWNER_INSTALLED ? [MEASUREMENT] : []), -]; +// The build test and the feature-shape measurement are template files and +// are always read (1106/10-01: filtering on "the file exists" let a renamed +// consumer drop out of the check unnoticed). 2026-11-07: the measurement used +// to copy the reference sample and went with it; it copies the generated +// feature now and stays. +const CONSUMERS = ["tests/unit/product-feature-selection-build.test.ts", MEASUREMENT]; const LOCAL_IMPORT = /\bfrom\s+["'](\.{1,2}\/[^"']+)["']|\bimport\s+["'](\.{1,2}\/[^"']+)["']/gu; @@ -60,8 +46,6 @@ function localImportGraph(entry: string): string[] { describe("vite build inputs (1105/15-03)", () => { it("defines the list in one module that both builds import", () => { - // The measurement may be missing only because a removable feature owns it. - expect(MEASUREMENT_OWNER, `no removable template feature owns ${MEASUREMENT}`).toBeDefined(); for (const consumer of CONSUMERS) { const source = readFileSync(consumer, "utf8"); expect(source, consumer).not.toMatch(/\bconst BUILD_INPUTS\s*=/u); diff --git a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/design-system-gallery-dark-chromium-visual-linux.png b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/design-system-gallery-dark-chromium-visual-linux.png index b5f4a480..9630af27 100644 Binary files a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/design-system-gallery-dark-chromium-visual-linux.png and b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/design-system-gallery-dark-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png index fae126f6..d3f14c04 100644 Binary files a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png and b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png differ diff --git a/tests/visual/platform.visual.spec.ts b/tests/visual/platform.visual.spec.ts index c7f95d78..182b19e3 100644 --- a/tests/visual/platform.visual.spec.ts +++ b/tests/visual/platform.visual.spec.ts @@ -3,6 +3,10 @@ import { test, type Page, } from "../support/browser/strict-browser-test.ts"; +import { + reservedOrigin, + TEST_PORT_VARIABLES, +} from "../../scripts/lib/run-isolation.ts"; import { ROUTE_FEATURE_OWNER, ROUTE_REGISTRY, @@ -14,6 +18,18 @@ async function expectRouteHeading(page: Page, title: string) { await expect(page.getByRole("heading", { level: 1 })).toHaveText(title); } +/** + * A gallery story in the static workshop the config's second server serves + * (src/presentation/design-system/galleries.stories.tsx). The a11y addon's own + * axe run is switched off, as in tests/storybook: it has nothing to draw. + */ +async function openGalleryStory(page: Page, storyId: string, title: string) { + await page.goto( + `${reservedOrigin(TEST_PORT_VARIABLES.visualWorkshop)}/iframe.html?id=${storyId}&viewMode=story&globals=a11y.manual:!true`, + ); + await expect(page.getByRole("heading", { level: 1 })).toHaveText(title); +} + /** `toHaveScreenshot` takes a stylesheet only as a file; a tag does the same. */ async function hide(page: Page, css: string) { if (css !== "") await page.addStyleTag({ content: css }); @@ -76,22 +92,26 @@ test("compact drawer and pseudo-locale visual contract", async ({ page }) => { }); }); -test("design-system gallery dark visual contract", async ({ page }) => { - await page.setViewportSize({ width: 1280, height: 900 }); - await page.goto("/examples/ui"); - await expectRouteHeading(page, "UI 구성요소"); - await page.locator("#theme-preference").selectOption("dark"); - await expect(page.getByRole("main")).toHaveScreenshot( - "design-system-gallery-dark.png", - ); +test.describe("in the dark color scheme", () => { + // The workshop has no theme selector: the theme provider follows the + // system preference there, as the app does until a user picks one. + test.use({ colorScheme: "dark" }); + + test("design-system gallery dark visual contract", async ({ page }) => { + await page.setViewportSize({ width: 1280, height: 900 }); + await openGalleryStory(page, "platform-galleries--design-system", "UI 구성요소"); + await expect(page.locator("html")).toHaveAttribute("data-theme", "dark"); + await expect(page.getByRole("main")).toHaveScreenshot( + "design-system-gallery-dark.png", + ); + }); }); test("loading empty error and access surfaces visual contract", async ({ page, }) => { await page.setViewportSize({ width: 1280, height: 1100 }); - await page.goto("/examples/states"); - await expectRouteHeading(page, "화면 상태"); + await openGalleryStory(page, "platform-galleries--screen-states", "화면 상태"); await expect(page.getByRole("main")).toHaveScreenshot( "state-surfaces-light.png", );