chore(features): 참조 기능과 예제 화면을 지우고 레지스트리를 다시 승인한다

소유자 결정(2026-11-07, design-docs repo-structure/README.md 3.4절)으로
템플릿 샘플을 지운다. 샘플이 맡던 시험 대상은 앞 커밋들이 옮겼다.

참조 기능과 예제 화면, 두 context, 그 시험, e2e 3개, 수동 접근성 기록
7개, 런타임 프로필 키, test:reference-feature(명령, 산출물, 게이트
참조), 커버리지 정책 행을 지웠다. removable-template-features 목록은
비우고 장치는 남겼다: test:sample-removal은 인자가 없으면 목록을
하나씩 지우고, 비면 SKIP을 출력하고 보고서에 건너뛴 사례를 남긴다.
기능 스위치 시험과 홈 시작 링크 스위치 시험은 시험 전용 fixture 기능으로
옮겼다. browser soak은 생성 기능을 넣은 빌드에서 돈다. 문서의 샘플
경로를 고쳤다. 날짜가 붙은 설계·리뷰 기록의 본문은 그대로 두었다.
레지스트리 기준선(update:registry-baseline, OWNER DongHyeonka), CI 계약
기준선과 workflow, 초기 JS 기록(194,354B, 17파일, 첫 기능 6,327B, 기능
539B, context 4B)을 다시 받았다.

위험: 레지스트리 행 삭제는 breaking이다. 샘플을 고쳐 쓰는 다운스트림은
수정/삭제 충돌을 만난다. 성능 lab의 기능 라우트 측정은 템플릿에
공개 기능 라우트가 없어 measured:false다. TEMPLATE_FIXTURE 출처는
플랫폼 코드에 남았다.

검증(desktop): check:types, lint, check:architecture, check:registries,
check:ci, verify:documentation, test:unit, test:component,
test:contract, test:integration, test:recipes, test:coverage(Risk
coverage PASS 378/378, 문턱 68개), test:e2e 183, test:a11y, test:visual,
test:storybook, test:browser-capabilities, test:feature-scaffold PASS(76
checks), test:sample-removal SKIP, build, check:bundle.
This commit is contained in:
DongHyeonka
2026-11-08 14:07:58 +09:00
parent b2042de9be
commit e3c8db48ae
126 changed files with 630 additions and 7607 deletions
+2 -2
View File
@@ -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
+19 -18
View File
@@ -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,7 +105,7 @@ 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 | `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` |
@@ -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/<id>`; 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 <id>` 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=<id>` 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
@@ -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.
@@ -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.
@@ -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.
@@ -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.
@@ -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.
@@ -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.
@@ -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.
+5 -5
View File
@@ -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"
}
-44
View File
@@ -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"
],
@@ -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"
}
+24 -318
View File
@@ -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",
+1 -3
View File
@@ -13,7 +13,5 @@
"SERVICE_WORKER": "DEFAULT",
"OFFLINE_COMMANDS": "DEFAULT"
},
"FEATURE_OVERRIDES": {
"reference-feature": "DEFAULT"
}
"FEATURE_OVERRIDES": {}
}
+1 -3
View File
@@ -13,7 +13,5 @@
"SERVICE_WORKER": "DEFAULT",
"OFFLINE_COMMANDS": "DEFAULT"
},
"FEATURE_OVERRIDES": {
"reference-feature": "DEFAULT"
}
"FEATURE_OVERRIDES": {}
}
+1 -3
View File
@@ -14,7 +14,5 @@
"SERVICE_WORKER": "DEFAULT",
"OFFLINE_COMMANDS": "DEFAULT"
},
"FEATURE_OVERRIDES": {
"reference-feature": "DEFAULT"
}
"FEATURE_OVERRIDES": {}
}
+1 -3
View File
@@ -14,7 +14,5 @@
"SERVICE_WORKER": "DEFAULT",
"OFFLINE_COMMANDS": "DEFAULT"
},
"FEATURE_OVERRIDES": {
"reference-feature": "DEFAULT"
}
"FEATURE_OVERRIDES": {}
}
+5 -5
View File
@@ -39,10 +39,10 @@
}
],
"initialJavascript": {
"gzipBytes": 204266,
"files": 27,
"firstFeatureGzipBytes": 797,
"perFeatureGzipBytes": 521,
"perContextGzipBytes": 12
"gzipBytes": 194354,
"files": 17,
"firstFeatureGzipBytes": 6327,
"perFeatureGzipBytes": 539,
"perContextGzipBytes": 4
}
}
-11
View File
@@ -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",
+3 -3
View File
@@ -51,9 +51,9 @@ checkout이 없거나 그 커밋이 없으면 실패 대신 확인하지 못한
지난 상태를 적는 문서라 빼고, git이 무시하는 생성 산출물과 복사한 프로젝트가 지운 작업 이력은
없어도 된다. 설명·수치가 코드와 맞는지는 검사하지 않는다. 규칙과 예외의 정본은
`scripts/verify-documentation-readiness.ts`다.
복사한 프로젝트가 지울 수 있는 템플릿 기능(참조 기능, 예제 화면. 목록은
`scripts/lib/removable-template-features.ts`)의 경로와 script는 그 기능이 설치돼 있을 때
(`src/features/<id>/feature-module.ts`가 있을 때) 검사하고, 지운 뒤에는 없어도 된다.
프로젝트가 지울 예정인 샘플 기능(목록은 `scripts/lib/removable-template-features.ts`, 템플릿은
비어 있다)의 경로와 script는 그 기능이 설치돼 있을 때(`src/features/<id>/feature-module.ts`가
있을 때) 검사하고, 지운 뒤에는 없어도 된다.
게이트가 직접 읽는 파일이라 지우거나 옮기면 게이트가 실패한다.
+6 -6
View File
@@ -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.
@@ -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 <id>`가 만든다. 짝 백엔드 `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` |
| `<BASE>_LIST_ITEMS` | `GET /<plural>` | `200`, Envelope 안의 항목 배열과 `meta.page` |
| `<BASE>_GET_ITEM` (`--with-create`) | `GET /<plural>/{<camel>Id}` | `200`, Envelope 안의 항목 |
| `<BASE>_CREATE_ITEM` (`--with-create`) | `POST /<plural>` | `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 <id> --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 제약을
@@ -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 <id> --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/<base>-feature-api.ts`
- `contracts/<base>-mapper.ts`
- `adapters/<base>-http-gateway.ts`
- `adapters/create-<base>-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.
+2 -2
View File
@@ -101,8 +101,8 @@ Feature-specific contracts stay inside the vertical slice:
`features/<feature>/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
@@ -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`,
@@ -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.
@@ -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/<id>` | 제품 기능의 수직 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/<id>`)가 소유하고, generic
installed catalog만 bootstrap과 router에 노출된다. 제거 gate는 feature와 test를
삭제한 복제본에서 전체 P0 경로를 다시 실행한다.
@@ -351,7 +351,7 @@ src/
platform/
features/
reference-feature/
<feature>/
domain/
application/
ports/
@@ -376,8 +376,8 @@ src/
application capability만 둔다. `shared`, `common`, `utils` 같은 이름으로
기술과 업무 규칙을 무제한 혼합하지 않는다.
`features/reference-feature`는 구조를 설명하기 위한 완전한 수직
슬라이스다. 이 폴더를 삭제하고 route 등록 한 곳만 제거했을 때
`features/<feature>`는 구조를 설명하기 위한 완전한 수직
슬라이스다(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/<feature>` 전체 삭제
2. reference route registration 삭제
3. reference test 삭제 또는 제외
4. 잔여 import와 registry owner 검색
+21 -24
View File
@@ -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
@@ -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>/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/<feature>/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 <id> --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`).
@@ -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 <id> --with-create`가 만드는 `presentation/use-<base>-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 <id> --with-create`의
`presentation/<base>-form.ts`
- 실제 create page: 같은 판의 `presentation/<base>-create-page.tsx`
`ApiFailure.validationIssues`는 HTTP 경계가 투영한 `path`와 `code`만 담는다.
backend message와 알 수 없는 path는 field copy로 사용하지 않는다.
+1 -1
View File
@@ -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 | `<camel>ItemDtoSchema` in `contracts/<base>-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` |
+6 -3
View File
@@ -156,10 +156,13 @@ node scripts/write-dev-release-manifest.ts # dev manifest에서 그 기능의
- `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=<id>` (`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)을 본다. 생성기 출력이 바뀌면 여기서 잡힌다.
## 알려진 한계
- 드릴은 브라우저 테스트(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를 고른다.
@@ -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
+11 -7
View File
@@ -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 <id> --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는 지금 진입을
통과시키고, 같은 크기의 묶음이 하나 더 붙으면 넘는다.
+2 -2
View File
@@ -62,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.
@@ -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/<id>/`)과 `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회와
생성 기능의 `<base>-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를 검증한다.
+1 -1
View File
@@ -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
+5 -9
View File
@@ -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"],
+1 -2
View File
@@ -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": {
+1 -3
View File
@@ -15,7 +15,5 @@
"SERVICE_WORKER": "DEFAULT",
"OFFLINE_COMMANDS": "DEFAULT"
},
"FEATURE_OVERRIDES": {
"reference-feature": "DEFAULT"
}
"FEATURE_OVERRIDES": {}
}
-7
View File
@@ -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": {
@@ -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",
),
},
{
+2 -3
View File
@@ -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 : ".";
+1 -1
View File
@@ -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.
*/
+2 -2
View File
@@ -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, "\\$&");
@@ -1,14 +1,24 @@
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. The browser checks that one
* feature works end to end (its route, form and save, a save whose result is
* lost) run on the feature `create:feature` writes: a fixture build
* (fixture-builds.ts) gets it with `addGeneratedFeature` as its edit, so a
* change of the generator's output fails here. The `--keyed` write slice is
* the widest one the command makes.
* 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";
@@ -78,3 +88,39 @@ export function generatedFeature(root: string): GeneratedFeature {
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<void> }>
> {
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;
}
}
+12 -39
View File
@@ -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[] {
+1 -1
View File
@@ -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.
+49 -34
View File
@@ -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<SoakArtifact> {
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<void> {
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=<a feature's protected list path in that build>");
}
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(
+93 -67
View File
@@ -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=<id>` (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=<id>`, 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,
`<?xml version="1.0" encoding="UTF-8"?>\n` +
`<testsuite name="sample-removal" tests="1" failures="0" skipped="1">` +
`<testcase name="listed-samples"><skipped message="scripts/lib/removable-template-features.ts lists no sample" /></testcase>` +
`</testsuite>\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<string[]> {
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<Record<string, FeatureExtras>> = 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) {
+6 -9
View File
@@ -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`),
);
-1
View File
@@ -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",
@@ -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;
@@ -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;
@@ -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],
}),
}),
),
);
@@ -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);
@@ -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);
@@ -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;
@@ -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);
@@ -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).
<section className="ui-page" lang="ko-KR">
<PageHeader
title="인증 연동"
description="스켈레톤은 자격 증명을 소유하지 않고 외부 인증 구현이 연결될 포트와 화면 상태만 제공합니다."
/>
<section className="ui-panel auth-example" aria-labelledby="auth-state-title">
<div>
<h2 id="auth-state-title">현재 세션 상태</h2>
<output className="session-status" data-state={sessionState}>
{sessionState}
</output>
</div>
<div className="button-row">
<button
className="ui-button"
type="button"
disabled={pending || sessionState === "integration-failed"}
onClick={() => run("sign-in")}
>
로그인 시작
</button>
<button
className="ui-button ui-button--secondary"
type="button"
disabled={pending || sessionState !== "authenticated"}
onClick={() => run("sign-out")}
>
로그아웃
</button>
<button
className="ui-button ui-button--secondary"
type="button"
disabled={pending || sessionState !== "recovery-pending"}
onClick={() => run("recover")}
>
세션 복구
</button>
</div>
{sessionState === "integration-failed" ? (
<p role="status">
외부 인증 소유자가 연결되지 않았습니다. 런타임 호스트의 인증
계약을 연결하세요.
</p>
) : null}
{failed ? <p role="alert">인증 작업을 완료하지 못했습니다.</p> : null}
</section>
</section>
);
}
@@ -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;
@@ -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).
<section className="ui-page" lang="ko-KR">
<PageHeader
title="화면 상태"
description="로딩, 빈 화면, 오류, 인증 필요와 권한 없음 상태가 다음 행동까지 일관되게 안내합니다."
/>
<section className="gallery-section" aria-labelledby="async-states-title">
<header className="gallery-section__header">
<h2 id="async-states-title">비동기 데이터 상태</h2>
<p>초기 로딩과 백그라운드 갱신을 구분해 기존 콘텐츠를 보존합니다.</p>
</header>
<div className="component-grid component-grid--two">
<Card title="초기 로딩">
<LoadingSurface label="예제 데이터를 불러오는 중" />
</Card>
<Card title="백그라운드 갱신">
<AsyncSurface headingLevel={4} state={refreshingState}>
<div className="state-preview-content">기존 콘텐츠는 계속 표시됩니다.</div>
</AsyncSurface>
</Card>
<Card title="빈 화면">
<EmptySurface
headingLevel={4}
title="아직 표시할 항목이 없습니다."
description="첫 항목을 추가하거나 필터를 초기화할 수 있습니다."
action={
<Button onClick={() => setLastAction("빈 화면 작업을 실행했습니다.")}>
첫 작업 시작
</Button>
}
/>
</Card>
<Card title="복구 가능한 오류">
<TerminalErrorSurface
headingLevel={4}
userMessageKey={
createFailure("NETWORK_UNREACHABLE", "EXAMPLE", 0)
.userMessageKey
}
action="retry"
onAction={() => setLastAction("오류 요청을 다시 시도했습니다.")}
/>
</Card>
</div>
</section>
<section className="gallery-section" aria-labelledby="access-states-title">
<header className="gallery-section__header">
<h2 id="access-states-title">접근과 탐색 상태</h2>
<p>인증 여부와 서버 권한 결과를 서로 다른 상태로 전달합니다.</p>
</header>
<div className="component-grid component-grid--three">
<AuthRequiredSurface
headingLevel={3}
onSignIn={() => setLastAction("로그인 연동 작업을 시작했습니다.")}
/>
<ForbiddenSurface
headingLevel={3}
onNavigate={() => setLastAction("접근 가능한 화면으로 이동합니다.")}
/>
<NotFoundSurface
headingLevel={3}
onNavigate={() => setLastAction("시작 화면으로 이동합니다.")}
/>
</div>
</section>
<output className="gallery-notice" aria-live="polite">
{lastAction}
</output>
</section>
);
}
@@ -1,318 +0,0 @@
import { useState, type FormEvent } from "react";
import {
Alert,
Badge,
Button,
Card,
Checkbox,
Dialog,
Menu,
PageHeader,
ProgressBar,
RadioGroup,
Select,
Switch,
Tabs,
TextArea,
TextField,
ToastProvider,
Tooltip,
useToast,
} from "../../../presentation/design-system/index.ts";
const COLOR_TOKENS = Object.freeze([
["Surface", "--color-surface"],
["Muted surface", "--color-surface-muted"],
["Content", "--color-content"],
["Muted content", "--color-content-muted"],
["Action", "--color-action"],
["Danger", "--color-danger"],
["Focus", "--color-focus"],
]);
export default function UiGalleryPage() {
return (
<ToastProvider>
<UiGalleryContent />
</ToastProvider>
);
}
function UiGalleryContent() {
const toast = useToast();
const [projectName, setProjectName] = useState("");
const [description, setDescription] = useState("");
const [template, setTemplate] = useState("application");
const [reviewed, setReviewed] = useState(false);
const [notifications, setNotifications] = useState(true);
const [density, setDensity] = useState("comfortable");
const [fieldTouched, setFieldTouched] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const [notice, setNotice] = useState(
"구성요소를 조작하면 결과가 여기에 표시됩니다.",
);
const [alertVisible, setAlertVisible] = useState(true);
const fieldError =
fieldTouched && projectName.trim().length === 0
? "프로젝트 이름을 입력해 주세요."
: undefined;
function submitExample(event: FormEvent<HTMLFormElement>): void {
event.preventDefault();
setFieldTouched(true);
if (projectName.trim().length === 0) {
setNotice("입력값을 확인해 주세요.");
return;
}
setNotice(`“${projectName.trim()}” 입력을 확인했습니다.`);
}
return (
// 08-07. Example copy is Korean in every locale (outside the catalog).
<section className="ui-page" lang="ko-KR">
<PageHeader
title="UI 구성요소"
description="제품 도메인과 독립적인 공통 컨트롤, 피드백, 표면과 디자인 토큰을 직접 조작할 수 있습니다."
/>
<section className="gallery-section" aria-labelledby="controls-title">
<header className="gallery-section__header">
<h2 id="controls-title">버튼과 입력</h2>
<p>키보드, 비활성 상태, 오류 설명을 포함한 기본 상호작용입니다.</p>
</header>
<div className="component-grid component-grid--two">
<Card title="버튼" description="의미와 위험도에 따라 변형을 선택합니다.">
<div className="button-row">
<Button onClick={() => setNotice("기본 작업을 실행했습니다.")}>
기본 작업
</Button>
<Button
variant="secondary"
onClick={() => setNotice("보조 작업을 실행했습니다.")}
>
보조 작업
</Button>
<Button
variant="danger"
onClick={() => setNotice("위험 작업 예제를 선택했습니다.")}
>
위험 작업
</Button>
<Button disabled>사용 불가</Button>
</div>
</Card>
<Card title="입력창" description="레이블과 도움말, 오류가 입력에 연결됩니다.">
<form className="example-form" noValidate onSubmit={submitExample}>
<TextField
label="프로젝트 이름"
description="새 도메인을 연결할 때 사용할 중립적인 예제입니다."
error={fieldError}
value={projectName}
required
onChange={(event) => setProjectName(event.currentTarget.value)}
/>
<Button type="submit">입력 확인</Button>
</form>
</Card>
</div>
</section>
<section className="gallery-section" aria-labelledby="form-controls-title">
<header className="gallery-section__header">
<h2 id="form-controls-title">폼과 선택 컨트롤</h2>
<p>native semantics, 설명·오류 연결과 controlled 상태를 제공합니다.</p>
</header>
<div className="component-grid component-grid--two">
<Card title="긴 입력과 선택">
<div className="component-stack">
<TextArea
label="설명"
maxLength={120}
value={description}
onChange={(event) => setDescription(event.currentTarget.value)}
/>
<Select
label="시작 템플릿"
options={[
{ value: "application", label: "Application" },
{ value: "library", label: "Library" },
]}
value={template}
onChange={(event) => setTemplate(event.currentTarget.value)}
/>
<Checkbox
checked={reviewed}
label="접근성 계약을 확인했습니다."
onChange={(event) => setReviewed(event.currentTarget.checked)}
/>
</div>
</Card>
<Card title="단일 선택과 설정">
<div className="component-stack">
<RadioGroup
label="화면 밀도"
name="density"
onChange={setDensity}
options={[
{ value: "comfortable", label: "여유롭게" },
{ value: "compact", label: "조밀하게" },
]}
value={density}
/>
<Switch
checked={notifications}
description="boolean 설정에만 switch를 사용합니다."
label="알림 사용"
onChange={setNotifications}
/>
<ProgressBar label="설정 준비도" max={4} value={3} />
</div>
</Card>
</div>
</section>
<section className="gallery-section" aria-labelledby="feedback-title">
<header className="gallery-section__header">
<h2 id="feedback-title">피드백과 모달</h2>
<p>상태 전달은 색에만 의존하지 않으며, 모든 제어에는 이름이 있습니다.</p>
</header>
<div className="component-grid component-grid--two">
<Card title="알림과 배지" description="짧은 상태와 문맥형 피드백입니다.">
<div className="component-stack">
{alertVisible ? (
<Alert
title="설정이 저장되었습니다."
variant="success"
onDismiss={() => setAlertVisible(false)}
>
<p>운영 환경에는 실제 저장 포트를 연결하세요.</p>
</Alert>
) : (
<Button
variant="secondary"
onClick={() => setAlertVisible(true)}
>
알림 다시 표시
</Button>
)}
<div className="badge-row" aria-label="배지 변형">
<Badge>중립</Badge>
<Badge variant="info">정보</Badge>
<Badge variant="success">준비됨</Badge>
<Badge variant="warning">확인 필요</Badge>
<Badge variant="danger">실패</Badge>
</div>
</div>
</Card>
<Card title="모달" description="배경과 키보드 Esc로 닫고 포커스를 복원합니다.">
<div className="button-row">
<Button onClick={() => setDialogOpen(true)}>모달 열기</Button>
<Menu
items={[
{
id: "inspect",
label: "상태 확인",
onSelect: () => setNotice("메뉴 작업을 실행했습니다."),
},
{
id: "notify",
label: "Toast 표시",
onSelect: () =>
toast.push({
id: "gallery-saved",
title: "예제가 저장되었습니다.",
tone: "success",
}),
},
]}
triggerLabel="작업 메뉴"
/>
<Tooltip content="이 설명은 필수 정보가 아닙니다.">
<Button variant="ghost">도움말</Button>
</Tooltip>
</div>
<Dialog
open={dialogOpen}
onClose={() => setDialogOpen(false)}
title="연동 확인"
description="도메인 작업을 실행하기 전 확인 화면의 기본 구조입니다."
actions={
<>
<Button
variant="secondary"
onClick={() => setDialogOpen(false)}
>
취소
</Button>
<Button
onClick={() => {
setNotice("모달의 확인 작업을 실행했습니다.");
setDialogOpen(false);
}}
>
확인
</Button>
</>
}
>
<p>민감한 값이나 구현 세부정보는 확인 문구에 포함하지 않습니다.</p>
</Dialog>
</Card>
</div>
</section>
<section className="gallery-section" aria-labelledby="navigation-title">
<header className="gallery-section__header">
<h2 id="navigation-title">탐색 패턴</h2>
<p>화살표 키와 명시적인 활성화 정책을 갖는 탭 예제입니다.</p>
</header>
<Tabs
activation="manual"
label="디자인 시스템 계층"
tabs={[
{
id: "tokens",
label: "토큰",
panel: <p>원시 값에서 의미와 컴포넌트 토큰을 파생합니다.</p>,
},
{
id: "primitives",
label: "프리미티브",
panel: <p>native semantics와 interaction을 닫습니다.</p>,
},
{
id: "patterns",
label: "패턴",
panel: <p>반복되는 사용자 문제를 조합으로 해결합니다.</p>,
},
]}
/>
</section>
<section className="gallery-section" aria-labelledby="tokens-title">
<header className="gallery-section__header">
<h2 id="tokens-title">디자인 토큰</h2>
<p>구성요소가 사용하는 의미 기반 색상과 형태 토큰입니다.</p>
</header>
<div className="token-grid">
{COLOR_TOKENS.map(([label, token]) => (
<article className="token-swatch" key={token}>
<span
className="token-swatch__color"
style={{ backgroundColor: `var(${token})` }}
aria-hidden="true"
/>
<strong>{label}</strong>
<code>{token}</code>
</article>
))}
</div>
</section>
<output className="gallery-notice" aria-live="polite">
{notice}
</output>
</section>
);
}
-92
View File
@@ -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<Value, Failure = AppFailure>`로 반환한다.
`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 순환 의존을 각각 거절해야 통과한다.
@@ -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,
});
@@ -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<ReferenceFeatureRouteId>();
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,
);
},
});
}
@@ -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<string, ReferenceError>);
/**
* 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;
}
}
@@ -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<Value> = Result<Value>;
export type ReferenceCreateCommand = Readonly<{
name: string;
note?: string;
}>;
export type ReferenceFeatureInput = Readonly<{
listResources(
filters: ReferenceListFilters,
context?: ReferenceCallContext,
): Promise<ReferenceResult<readonly ReferenceResourceView[]>>;
createResource(
command: ReferenceCreateCommand,
context?: ReferenceCallContext & Readonly<{ intent?: MutationIntent }>,
): Promise<ReferenceResult<ReferenceResourceView>>;
getResource(
resourceId: string,
context?: ReferenceCallContext,
): Promise<ReferenceResult<ReferenceResourceView>>;
}>;
declare module "../../../application/ports/in/application-api.ts" {
interface ApplicationFeatureInputs {
"reference-feature": ReferenceFeatureInput;
}
}
export type ReferenceGateway = Readonly<{
list(
filters: ReferenceListFilters,
context?: ReferenceCallContext,
): Promise<ReferenceResult<readonly ReferenceResource[]>>;
create(
command: ReferenceCreateCommand,
context?: ReferenceCallContext & Readonly<{ intent?: MutationIntent }>,
): Promise<ReferenceResult<ReferenceResource>>;
get(
resourceId: string,
context?: ReferenceCallContext,
): Promise<ReferenceResult<ReferenceResource>>;
}>;
/**
* 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;
},
});
}
@@ -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,
}),
});
}),
);
@@ -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/<service>-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<string> = 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<ReferenceProblem> = 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<typeof referenceResourceListQuerySchema>) {
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<typeof referenceResourceListQuerySchema>,
readonly z.output<typeof referenceResourceDtoSchema>[],
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<typeof referenceResourceParamsSchema>) {
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<typeof referenceResourceParamsSchema>,
z.output<typeof referenceResourceDtoSchema>,
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<typeof createReferenceResourceCommandSchema>) {
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<typeof createReferenceResourceCommandSchema>,
z.output<typeof referenceResourceDtoSchema>,
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<unknown, unknown, unknown>[],
events: Object.freeze([]),
});
@@ -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);
@@ -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<ReferenceResource> {
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<readonly ReferenceResource[]> {
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,
});
}
@@ -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);
@@ -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",
}),
});
@@ -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<typeof referenceProblemSchema>;
export const createReferenceResourceCommandSchema = z
.object({
name: z.string().trim().min(1).max(120),
note: z.string().trim().max(500).optional(),
})
.strict();
@@ -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 });
}
@@ -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;
@@ -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);
@@ -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,
});
@@ -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 (
<DetailPage
key={resourceId}
breadcrumb={
<Link to={referenceRouteUrl("REFERENCE_RESOURCE_LIST")}>
{message("reference.list.resources")}
</Link>
}
heading={{
eyebrow: message("reference.detail.eyebrow"),
title: resource?.title ?? message("reference.detail.titlePending"),
description: message("reference.detail.description"),
}}
metadata={
resource ? (
<dl>
<dt>{message("reference.detail.resourceId")}</dt>
<dd>{resource.resourceId}</dd>
<dt>{message("reference.detail.createdAt")}</dt>
<dd>
{resource.createdAt
? date(new Date(resource.createdAt))
: message("common.noDisplayValue")}
</dd>
</dl>
) : (
<p>{message("reference.detail.summaryPending")}</p>
)
}
feedback={
<AsyncSurface
state={query.state}
onAction={failureAction}
onRetry={query.retry}
>
{resource ? (
<p>{message("reference.detail.sectionSlot")}</p>
) : null}
</AsyncSurface>
}
aside={<p>{message("reference.detail.aside")}</p>}
/>
);
}
@@ -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<keyof ReferenceResourceFormValues, string>;
const mutation = useReferenceCreate();
const invalidation = useQueryInvalidationCoordinator();
const submit = useCallback(
(command: ReturnType<typeof toCreateReferenceCommand>) =>
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 = (
<p>
<Link
to={referenceRouteUrl("REFERENCE_RESOURCE_LIST")}
onClick={() => {
void invalidation
?.invalidate([REFERENCE_RESOURCE_INVALIDATION_TOPIC])
.catch(() => {});
}}
>
{message("reference.form.reloadList")}
</Link>
</p>
);
return (
<Form
id={form.formId}
pending={form.pending}
onSubmit={(event) => {
if (mutationBlocked) {
event.preventDefault();
return;
}
void form.submitForm(event);
}}
>
<FormPage
feedbackId={form.feedbackId}
breadcrumb={
<button
className="ui-button ui-button--ghost"
type="button"
onClick={() => navigate(referenceRouteUrl("REFERENCE_RESOURCE_LIST"))}
>
{message("reference.form.back")}
</button>
}
heading={{
eyebrow: message("reference.form.eyebrow"),
title: message("reference.form.title"),
description: message("reference.form.description"),
}}
errorSummary={
<ErrorSummary
fieldErrors={form.fieldErrors}
formErrors={form.formErrors}
fieldLabels={fieldLabels}
fieldId={form.fieldId}
onFocusField={form.focusField}
/>
}
fields={
<>
<FormField
{...form.field("name")}
label={fieldLabels.name}
description={message("reference.form.nameDescription")}
autoComplete="off"
required
/>
<FormField
{...form.field("note")}
label={fieldLabels.note}
description={message("reference.form.noteDescription")}
autoComplete="off"
/>
</>
}
formActions={
<FormActions sticky>
<Button
variant="secondary"
onClick={() => navigate(referenceRouteUrl("REFERENCE_RESOURCE_LIST"))}
disabled={form.pending || mutationBlocked}
>
{message("reference.form.cancel")}
</Button>
{/* 1103/08-02. Busy, not disabled, while saving: a disabled
button drops keyboard focus. The form refuses a second
submit itself. */}
<Button
type="submit"
pending={form.pending}
pendingLabel={message("reference.form.saving")}
disabled={mutationEffectUnknown || otherSaveRunning}
>
{message("reference.form.save")}
</Button>
<Button
variant="ghost"
onClick={() => form.reset()}
disabled={!form.dirty || form.pending || mutationBlocked}
>
{message("reference.form.reset")}
</Button>
</FormActions>
}
feedback={
form.failure ? (
<FormFailureStatus
failure={form.failure}
onAction={
form.result === "retry-later"
? () => void form.submitForm()
: failureAction
}
/>
) : mutationEffectUnknown ? (
<>
<AsyncSurface
state={mutation.state}
supportReference={form.supportReference}
onReconcileUnknownEffect={(resolution) => {
void mutation
.reconcileUnknownEffect(resolution)
.then(form.settleApplied);
}}
onResendUnknownEffect={() => {
void form.resendUnknown(mutation.resendUnknownEffect);
}}
/>
{reloadList}
</>
) : form.result === "success" ? (
<p role="status">{message("reference.form.saved")}</p>
) : form.result === "conflict" ? (
<p role="status">{message("reference.form.conflict")}</p>
) : 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.
<AsyncSurface state={mutation.state} />
) : otherSaveSeen ? (
reloadList
) : null
}
aside={
<p>{message("reference.form.privacy")}</p>
}
guard={<DirtyNavigationDialog guard={guard} />}
/>
</Form>
);
}
@@ -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 } : {}),
});
}
@@ -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 (
<CollectionPage
heading={{
eyebrow: message("reference.list.eyebrow"),
title: message("reference.list.title"),
description: message("reference.list.description"),
}}
actions={[
{
kind: "button",
label: message("reference.list.create"),
onAction: () => navigate(referenceRouteUrl("REFERENCE_RESOURCE_FORM")),
},
]}
activeFilters={
<p data-testid="reference-filter">
{message("reference.list.filterLimit", { limit: filters.limit })}
{filters.tags?.length
? ` · ${message("reference.list.filterTags", {
tags: filters.tags.join(", "),
})}`
: ""}
</p>
}
toolbar={
<Button onClick={() => void query.retry()}>
{message("reference.list.refresh")}
</Button>
}
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
}
>
<AsyncSurface
state={query.state}
onAction={failureAction}
onRetry={query.retry}
>
<ul aria-label={message("reference.list.resources")}>
{(query.data ?? []).map((resource) => (
<li key={resource.resourceId}>
<Link
to={referenceRouteUrl("REFERENCE_RESOURCE_DETAIL", {
params: { resourceId: resource.resourceId },
})}
>
{resource.title}
</Link>
</li>
))}
</ul>
</AsyncSurface>
</CollectionPage>
);
}
@@ -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 (
<StatusPage
variant="maintenance"
heading={{
eyebrow: message("reference.status.eyebrow"),
title: message("reference.status.title"),
description: message("reference.status.description"),
}}
primaryAction={{
kind: "button",
label: message("reference.status.back"),
onAction: () => navigate(referenceRouteUrl("REFERENCE_RESOURCE_LIST")),
}}
supportReference={supportReference}
/>
);
}
@@ -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;
@@ -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<typeof buildRouteUrl>[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;
}
@@ -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;
}
@@ -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<ReferenceCreateCommand, ReferenceResourceView>,
"scope" | "execute"
>;
function bindReferenceCreateMutation(
binding: ReferenceCreateMutationBinding,
): BoundMutation<ReferenceCreateCommand, ReferenceResourceView> {
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 });
}
+1 -2
View File
@@ -12,8 +12,7 @@
line-height: 1.65;
}
.starter-actions,
.auth-example {
.starter-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
+6 -6
View File
@@ -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(<LinkButton to="/examples/states">States</LinkButton>);
renderInRouter(<LinkButton to="/examples/platform">States</LinkButton>);
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(
<StandardPage
actions={[
{ kind: "link", label: "Open states", to: "/examples/states" },
{ kind: "link", label: "Open states", to: "/examples/platform" },
{ kind: "link", label: "External", href: "https://example.com" },
]}
heading={{ title: "Page" }}
@@ -98,10 +98,10 @@ describe("design-system links inside the router", () => {
"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$/,
);
});
+71 -25
View File
@@ -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<Record<string, (typeof ROUTE_REGISTRY)[keyof typeof ROUTE_REGISTRY]>> =
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<Record<string, string>>)[
"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();
});
});
+1 -1
View File
@@ -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,
@@ -8,7 +9,6 @@ import {
removeFixtureBuilds,
type FixtureBuilds,
} from "./support/fixture-builds.ts";
import { addGeneratedFeature } from "./support/generated-feature.ts";
import { startBuildServer } from "./support/service-worker-builds.ts";
/**
+2 -2
View File
@@ -13,7 +13,7 @@ import {
generatedFeature,
routePath,
type GeneratedFeature,
} from "./support/generated-feature.ts";
} from "../../scripts/lib/generated-feature.ts";
import { startBuildServer } from "./support/service-worker-builds.ts";
/**
@@ -23,7 +23,7 @@ import { startBuildServer } from "./support/service-worker-builds.ts";
* 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
* (support/generated-feature.ts). The API answers are the paired backend's
* (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" });
+2 -2
View File
@@ -15,7 +15,7 @@ import {
import {
addGeneratedFeature,
generatedFeature,
} from "./support/generated-feature.ts";
} from "../../scripts/lib/generated-feature.ts";
import { startBuildServer } from "./support/service-worker-builds.ts";
/**
@@ -29,7 +29,7 @@ import { startBuildServer } from "./support/service-worker-builds.ts";
// 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 (support/generated-feature.ts)
// 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<Record<string, RouteDefinition>> = ROUTE_REGISTRY;
+2 -2
View File
@@ -3,6 +3,7 @@ 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";
@@ -11,7 +12,6 @@ import {
removeFixtureBuilds,
type FixtureBuilds,
} from "./support/fixture-builds.ts";
import { addGeneratedFeature } from "./support/generated-feature.ts";
import { startBuildServer } from "./support/service-worker-builds.ts";
/**
@@ -141,7 +141,7 @@ test("counts the chunks a route preloads and then runs as used", async ({
* 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 template installs no
* feature, so this runs on a build of a copy with the one `create:feature`
* writes (support/generated-feature.ts).
* writes (scripts/lib/generated-feature.ts).
*/
let featureBuild: FixtureBuilds<"a"> | undefined;
-150
View File
@@ -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);
});
-36
View File
@@ -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();
});
-237
View File
@@ -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<void>)[],
): Promise<CreateCall[]> {
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);
});
});
@@ -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(
<ApplicationProvider application={application}>
<PreferenceProviders>
<AppRouter />
</PreferenceProviders>
</ApplicationProvider>,
);
}
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(<StateGalleryPage />);
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(["비동기 데이터 상태", "접근과 탐색 상태"]);
});
});
@@ -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(
<LocaleProvider>
<UiGalleryPage />
</LocaleProvider>,
);
// The Alert is a status too; the page's notice line is the `<output>`.
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 <progress value={3} max={4}>; 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("이 설명은 필수 정보가 아닙니다.");
});
});
@@ -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개 항목");
});
});

Some files were not shown because too many files have changed in this diff Show More