Files
clean-architecture-frontend…/docs/architecture/starter-experience.md
T
donghyeon.kang 79dc945a67 refactor(layout): 루트 경로 목록을 등록부 하나에서 고르고 schemas/를 옮긴다
루트 항목 하나를 옮기려면 코드 7곳의 루트 경로 목록을 같이 고쳐야
했다(복사 대상, 비밀값 검사 범위, 공급망 시험의 필수 입력, 이력 문서
검사, 규모 입력, vite 입력, TS 전용 규칙). 서로 다른 부분집합이고 한
곳에서 선언하지 않았다. 목록이 갈라져 공급망 생성이 깨진 적도 있다
(removal-fixture.ts 주석). 루트에는 JSON Schema 5개만 담은 `schemas/`가
`config/` 옆에 따로 있었다. `artifacts/`(출력 폴더)에는 사람이 쓴 수동
a11y 기록이, `config/hosting/`(호스트 계약)에는 시험 fixture가 섞였다.

고른 방법(design-docs repo-structure/04-frontend-layout.md 9.2절 3단계,
11절 R1·R2, 소유자 승인 2026-11-07):
- `config/repository-layout.json`이 루트 항목마다 종류·역할·읽는 곳과
  들어가는 목록(`sets`, 항목 안 경로는 `setPaths`)을 적는다.
  `scripts/lib/repository-layout.ts`가 읽고 검증한다. 6곳은 이름 붙은
  집합을 고른다. JSON인 비밀값 검사 정책은 집합의 사본을 두고 시험이
  같은지 본다(정책 파일은 릴리스 후보에 실려 형식을 바꾸지 않았다).
  공급망 시험의 필수 입력 목록은 그 시험으로 대신한다.
- `tests/unit/repository-layout.test.ts`: 등록부에 없는 루트 항목이
  추적되면 실패(R1). 7곳이 등록부 모듈을 쓰고 루트 이름 둘 이상의
  문자열 배열을 갖지 않는지(R2).
- `schemas/artifacts/` → `config/schemas/artifacts/`, recipe 카탈로그
  스키마 → `config/schemas/recipes/`. 정책 입력 순서(ASCII)에 맞춰
  `config/schemas/`가 `config/security/` 앞에 온다.
- 수동 a11y 기록 3개 → `docs/accessibility/route-reviews/`. `artifacts/`는
  `.gitkeep`만 추적한다. 기록은 단위 시험이 읽어서 drill 사본에도
  복사한다(`fixture-copy` 집합의 `docs/accessibility/route-reviews`).
- `config/hosting/response-headers.fixture.json` →
  `tests/fixtures/hosting/response-headers.json`.

버린 것: 비밀값 검사 정책이 집합 이름을 참조하게 바꾸는 방법. 정책
파일은 릴리스 후보와 로컬 증거 평가가 읽는 형식이라 바꾸면 릴리스
증거 계약이 바뀐다. 루트 항목이 지워졌는데 등록부에 남는 경우는
시험하지 않았다. drill 사본은 일부만 복사해 그 방향을 볼 수 없다.
그런 항목은 그 집합을 쓰는 곳(복사, 비밀값 검사)에서 실패한다.

위험: 하네스 작업(fe-c)이 더할 `AGENTS.md`·`.claude/`를 미리 등록했다
(optional). 등록부가 이력 문서(`SPEC.md`)와 `CLAUDE.md` 이름을 적어서
이력 문서 검사에서 등록부 파일은 뺐다. 다운스트림은 자기 루트 항목을
등록부에 더해야 한다(CHANGELOG). CI 계약 기준선을 다시 받았다(a11y
기록 산출물 id·경로).

검증(desktop): 아래 4단계 커밋까지 쌓은 트리에서 test:unit,
check:types, check:ci, lint, verify:documentation을 돌렸다(그 커밋에
적음). 이 커밋 단독으로 test:unit·check:ci·check:types를 돌렸다.

Refs: design-docs repo-structure/04-frontend-layout.md 2.4·9.2·11절, README.md 3.4절
2026-11-08 17:41:07 +09:00

300 lines
20 KiB
Markdown

# Starter experience contract
The repository provides a runnable, domain-neutral application rather than
only infrastructure contracts. The starter experience is intentionally
replaceable at the page level while the shell, providers, boundaries,
primitives, and state surfaces remain reusable.
## Runtime composition
```text
validated config + coherent release manifest
-> concrete adapters
-> QueryClientProvider
-> ApplicationProvider
-> RouterProvider
-> ThemeProvider
-> SessionProvider
-> AppShell
-> lazy route boundary
```
Boot stops before product mount when configuration or release coherence fails.
Each lazy page renders inside Suspense and a telemetry-aware route boundary.
Route changes move focus to the new page heading; the skip link and landmarks
remain stable in the shell.
## Registered routes
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 platform overview page (`/examples/platform`) shows the
composed list at runtime, so this document does not keep a copy of it.
Navigation labels and order come from `ROUTE_REGISTRY`; the sidebar does not
maintain a second route list. The client access decision never claims to be
authorization.
## Authentication seam
The session port exposes state subscription, sign-in start, sign-out,
credential attachment, recovery, and unauthenticated notification. Credentials
remain opaque to the application and presentation layers.
- `demo`: local/development-only state transition with no credentials
- `external`: delegates to `globalThis.__CA_FRONTEND_AUTH_OWNER__`
- missing/invalid external owner: fails closed as `integration-failed`
An external owner implements `readState`, `readSubject`, `subscribe`,
`beginSignIn`, `signOut`, `attachCredential`, `recoverSession`, and
`notifyUnauthenticated`. It owns token acquisition and storage. An owner that
lacks any of these methods is rejected, and the session fails closed as
`integration-failed`.
The state transitions an owner makes, and what `recover()` leaves behind for
each answer, are written on `SessionState` and `SessionGateway.recover` in
`src/application/ports/auth-session-port.ts`. For the paired backend's two
authentication modes there are owners to copy, not to write:
`recipes/session-owners/oidc-pkce-session-owner.ts` (JWT mode: Keycloak,
authorization code with PKCE, `EXTERNAL_BEARER`) and
`recipes/session-owners/cookie-session-owner.ts` (Redis session mode: the
session cookie, plus `SESSION_COOKIE_*` profiles and the `X-XSRF-TOKEN`
provider). `docs/manual/04-paired-backend-session.md` wires them and lists
what the backend template does not ship (a browser client in its realm; the
sign-in, sign-out and session endpoints).
`readSubject()` is required. The server-state cache is cleared only when the
session state or the subject changes, so a token refresh for the same user
keeps cached data. `readSubject()` must return:
- an opaque, non-empty string that stays the same for one user across token
refreshes and differs between users: the OIDC `sub` claim, Supabase
`session.user.id`, or Firebase `user.uid`
- `null` when nobody is signed in
- never an access token, refresh token, or any other credential
If `readSubject()` returns `null` or `""` while the owner reports
`authenticated`, the runtime cannot tell a refresh from an account switch. It
fails closed: every such notification clears server state, and each one records
the `cache.operation.failed` diagnostic with `operation: SCOPE_FENCE` and
`reason: SUBJECT_MISSING`. Seeing that diagnostic means the owner is not
reporting its subject. The `demo` adapter reports one fixed demo user as its
subject.
Migration: `readSubject()` used to be optional. An owner written for an earlier
release must add it; without it the owner is rejected at startup (the session
becomes `integration-failed`) and a TypeScript owner no longer compiles
against `ExternalSessionOwner`. A code path that implements `AuthSessionPort`
or `SessionGateway` directly must add `getSubject()` the same way.
## Extending the starter
New platform work should follow
[routing, page templates, and reusable patterns](./routing-pages-and-patterns.md)
and the
[TypeScript, state, and data-flow target](./typescript-state-and-data-flow.md)
rather than adding another independent route or data-loading convention.
### Replacing the starter screens
`/` (`src/presentation/pages/home-page.tsx`) is the platform's `APP_HOME`; a
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 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
route. It describes the installed registries, and the lab gate (FE-GATE-026)
times entering it: a feature route's first entry also loads its context's
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`.
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
Features, contexts and apps are discovered by
`scripts/generate-product-feature-index.ts`. Each boundary declares only its
parent, as exported string or integer literals the generator reads:
| File | Exports |
| --- | --- |
| `src/apps/<app>/app-module.ts` | `APP_MODULE_ID`, `APP_MAX_CONTEXTS` |
| `src/contexts/<context>/context-module.ts` | `CONTEXT_MODULE_ID`, `CONTEXT_APP_ID`, `CONTEXT_ROUTE_PATH`, `CONTEXT_MAX_FEATURES` |
| `src/features/<feature>/feature-module.ts` | `FEATURE_MODULE_ID`, `FEATURE_CONTEXT_ID`, `FEATURE_MODULE` |
| `src/features/<feature>/feature-runtime.ts` | `FEATURE_RUNTIME` (imported only by `feature-module.ts`, dynamically) |
| `src/features/<feature>/context-routes.ts` | `FEATURE_CONTEXT_ROUTES` |
| `src/contexts/<context>/context-layout.tsx` (optional) | `CONTEXT_LAYOUT`, the context's own layout ("Product home and layouts") |
The generator writes `src/.generated/` (git-ignored): the feature index the
installed catalogs import, the context index the router loads lazily, and the
selected app. Every build and check script runs it first; run it yourself with
`corepack pnpm generate:feature-index`. It fails, naming the file, when:
- a directory under `src/features/` has no `feature-module.ts`. Code that
is no feature (the IndexedDB consumer the tests compose,
`tests/fixtures/indexeddb-consumer`) lives outside `src/features/`;
- a feature names an undeclared context, or a context an undeclared app;
- a context or app exceeds its declared budget;
- `VITE_PRODUCT_FEATURES` names a feature the app does not declare. The
variable narrows the installed set here, before anything is compiled.
### Adding a feature
1. Create `src/features/<feature>/feature-module.ts`. Build `FEATURE_MODULE`
with `defineFeatureModule` (`src/features/feature-module.ts`). This is the
feature's declaration, and it is in the initial chunk, so it holds data
only: the declaration contract (routes, route runtime contracts,
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.
`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
(`defineFeatureAdapterContribution`, with `needs` naming the platform
capabilities it receives) and the contract contributions (the HTTP
operations). The router loads
it (`application.features.load`) when one of the feature's routes is
entered. Do not import it statically from anywhere: each feature would add
its whole executable code to the initial chunk again, about 3.9 KB gzip
(`tests/unit/feature-shape-growth.test.ts` bounds one feature at 1 KiB).
An HTTP API is written once, as its contract contribution descriptor: it
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` 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
(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`).
4. Name the owning context in `FEATURE_CONTEXT_ID`. Use an existing context or
add `src/contexts/<context>/context-module.ts` owned by the app.
Every route path in the feature contract must sit at or under that
context's `CONTEXT_ROUTE_PATH` and must not fall under another context's
identical or more specific root: the router renders feature routes only
inside the owning context. No platform route may answer it either: the
router tries `AppShell`'s platform routes first, so the same path as a
platform route, `/` under an id other than `APP_HOME`, or a `*` root
without a layout (the not-found route takes every URL) never renders the
feature. The app module refuses anything else when it loads, naming the
route, feature and context (`src/apps/deployable-app-module.ts`). A route
that takes over the platform home is the exception ("Product home and
layouts").
5. If the feature has application input, augment `ApplicationFeatureInputs`
from the feature (the IndexedDB consumer fixture does it in
`tests/fixtures/indexeddb-consumer/application/local-draft-api.ts`).
6. Run `corepack pnpm check:architecture`, `corepack pnpm check:types`,
`corepack pnpm check:registries` and the tests. `tests/unit/two-feature-install-typecheck.test.ts`
keeps the installed catalogs compiling with more than one feature.
7. Run `corepack pnpm test:sample-removal -- --feature=<feature id>` to prove
the product still builds and passes its gates without the feature.
Files outside the feature directory. Everything else a feature needs is in
`src/features/<feature>/` and `tests/features/<feature>/`.
| File | When | What fails without it |
| --- | --- | --- |
| `src/.generated/*` | never by hand: every build and check script regenerates it | — |
| `public/release-manifest.json` (tracked, the dev server's manifest) | every added or removed feature: `create:feature` rewrites it (`node scripts/write-dev-release-manifest.ts`). Commit it with the feature. Two feature branches change its `setDigest` line; on a merge conflict take either side and run the command again (1105/16-01) | `test:unit` (`tests/unit/dev-release-manifest.test.ts`) names the command; the dev server does not boot (`CONTRACT_SET_PACKAGE_MISSING`) |
| `config/scale/feature-shape-ceilings.json` `initialJavascript` (tracked) | every added or removed feature, and every template change that moves the initial JavaScript: `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`. Commit it with the change; on a merge conflict run the command again | `test:unit` (the feature-shape growth test compares it with a build) |
| `src/contexts/<context>/context-module.ts` | the feature needs a new context | `generate:feature-index`: `Feature <id> belongs to undeclared context <context>` |
| `src/contexts/<context>/context-layout.tsx` | the context needs its own frame instead of `AppShell` (see "Product home and layouts" below) | nothing: without it the context renders in `AppShell` |
| `docs/accessibility/route-reviews/<ROUTE_ID>.md` | every route the feature adds. Copy a record and reset it to `Status: pending-manual-review` | `test:unit` (`tests/unit/manual-a11y-evidence.test.ts`), `verify:documentation` (names the route IDs) and FE-GATE-009 (`review:a11y-manual -- --format-only`). FE-GATE-028 requires the signed review at release |
| `tests/e2e/accessibility.spec.ts` | never per feature (1103/16-03): it fills every path parameter with one value and answers each API request from the installed descriptor, a list read with an empty list in its `responseEnvelope` frame. Edit it only for a protected page that sends something other than an installed GET before it renders | `test:a11y` (FE-GATE-009): a request no installed GET declares fails the route; so does an alert box (`role="alert"`) on a page that read only lists |
| `src/features/product-capabilities.ts` (product-owned) | `needs` names a capability the template does not build: type it in `ProductFeaturePlatformCapabilities`. `FeaturePlatformCapabilities` extends it, so the app, scripts and tests typecheck programs all see the key (an augmentation inside `product-composition.ts` is not seen by the scripts' program) | `check:types`: `Type '"<capability>"' is not assignable to type 'keyof FeaturePlatformCapabilities'` in the feature |
| `src/bootstrap/product-composition.ts` (product-owned) | `needs` names a capability the template does not build: return the capability here, typed in `product-capabilities.ts`. `indexedDb` is built as in `recipes/frontend-capabilities/indexeddb-feature-capability.ts`. Credentials for a product auth profile are returned here too. A product that owns the session (a BFF's httpOnly cookie) returns its session owner from `composeProductSessionOwner` instead of installing it on the host global before boot | `check:types`; at runtime `feature <id> needs <capability>, which the host did not provide`. Without the session owner, `AUTH_MODE: "external"` boots with the session `integration-failed` |
| `src/contracts/product-contracts.ts` (product-owned) | a product auth profile, or a product runtime-config key and its FE-REG-ENV row (`PRODUCT_ENV_REGISTRY`) | auth profile: every gate that loads the operation, with `Installed contract contribution is not composable: <featureId>/<operationId>: unknown authProfileId <id>`. Config key: `check:types` where it is read. Give the key a `.default()` or make it `.optional()`: template tests build their config with `tests/helpers/runtime-config.ts`, which fills the product's defaults, and a required key without a default fails them. FE-REG-ENV row: `check:registries` checks its fields, and `tests/unit/env-registry-coverage.test.ts` (`test:unit`) requires a row for every key, with the schema's `required` and `defaultValue` |
| `config/runtime/<profile>.json` | optional: a `FEATURE_OVERRIDES` entry switches the feature off | nothing |
| `package.json`, the lockfile, `config/security/dependency-change-evidence.json` | the contract contribution imports a generated `@org-contracts/*` package as a production dependency | `generate:supply-chain` (in `check:bundle`): `high-risk dependency missing review: add:<package>` |
The central catalogs (`src/features/installed-*.ts`) and the registry
governance file do not change: consumer directories there are globs over every
feature (`src/features/*/adapters`, `config/contracts/registry-governance.json`).
A route's params/search schema ids are checked against the schemas the feature
registers, and its `loadingSurface` only has to be a kebab-case name, so a
route with its own schema and loading surface needs no governance edit either.
The registry baseline does not change either. New routes, API operations,
schemas and invalidation topics, namespaces and edges are additive registry
changes; `update:registry-baseline` or breaking evidence is needed only to
remove or change a row or graph item.
`tests/unit/second-api-feature-registries.test.ts` adds such a feature (an API
operation, a route with its own search schema and loading surface, and an
invalidation topic) to a copy of the repository and runs `check:registries` on
it.
Schema, operation, mapper, route and chunk ids and invalidation topics are
global. Prefix them with the feature; `create:feature` writes
`<Pascal>NoRequest`, so a bare `NoRequest` would collide between features. MSW scenarios for the feature's own operations come from
`createHttpScenarioHandler` (`tests/mocks/handlers/http-scenarios.ts`) with
the feature's installed contract; the shared scenario catalog does not change.
### Product home and layouts
A product whose home is a feature screen, or whose screens use a frame other
than `AppShell`, declares it. The router and the catalogs do not change.
- **Home.** A feature takes over the platform home by declaring a route with
the id `APP_HOME` in its contract. The platform names the routes a feature
may take over (`FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS` in
`src/contracts/routes.ts`); any other platform route id is still a
duplicate. Two features declaring `APP_HOME` fail when the catalogs load,
naming both. The router mounts the route at its own path with the owning
context, whatever that context's route root. Leaving the feature out of the
build (`VITE_PRODUCT_FEATURES`) brings the platform home back; switching it
off at runtime shows the disabled-feature page at its path.
- **Layout.** A context with `src/contexts/<context>/context-layout.tsx`
exporting `CONTEXT_LAYOUT` (a component) renders under that layout instead
of `AppShell`. The generated index loads the file lazily, when one of the
context's routes is entered. The router mounts the context at each
registered path of its features under the layout, so an unknown URL still
gets the not-found page in `AppShell`. Contexts whose layout files export the
same component keep one layout instance when the user moves between them,
so several route roots can share a layout.
- **Accessibility.** The layout renders a skip link to `#main-content` and
exactly one `<main id="main-content" tabIndex={-1}>` around `<Outlet />`.
The router moves focus there on every route change. Layout routes are
siblings of `AppShell`, never inside it.
`tests/component/layout-landmarks.test.tsx` renders `AppShell` and the
layout of every installed context and fails one without them.
- **Failures.** A layout chunk a deploy removed gets the reload-once recovery
of a route chunk. Route and feature boundaries work as they do in
`AppShell`.
- The route root rule of step 4 spans every layout: a root takes the URLs
under it whichever layout either context has.
`tests/component/context-layouts.test.tsx` installs a product declared this
way (`tests/helpers/fixture-layout-product.tsx`).
### Before shipping
- Use the semantic tokens, UI primitives, and state surfaces before adding a
project-specific variant.
- Add component behavior, all-engine E2E, automated axe, and signed manual
route evidence.
Theme preference is the public `COLOR_SCHEME` storage contract. Authentication
tokens and other secrets remain forbidden storage keys.