Files
clean-architecture-frontend…/docs/architecture/starter-experience.md
T
DongHyeonka ece944d08b feat(bootstrap): 제품 세션 owner와 FE-REG-ENV 행을 제품 파일로 받는다 (1101/09-02)
문제
09-02(da1e128) 뒤에도 tech-log가 하는 일 두 가지는 템플릿 파일을 고쳐야
한다(리뷰 1101 README 14.4 "09-02 이식").
- 제품 설정 키의 FE-REG-ENV 행: tech-log는 템플릿 src/contracts/env.ts의
  ENV_REGISTRY에 TECH_LOG_STUDIO_SOURCE·TECH_LOG_PUBLIC_SOURCE 행을 직접
  넣었다(tech-log env.ts:63-70).
- 부트 전 BFF 세션 owner: 세션이 httpOnly 쿠키라 owner가 백엔드에 묻는다.
  tech-log는 템플릿 create-runtime-composition.ts에서 AUTH_MODE external이고
  Studio가 HTTP일 때 createRuntimeAdapters 전에 host 전역
  __CA_FRONTEND_AUTH_OWNER__에 owner를 넣는다(:2, :36-52,
  bff-session-owner.ts:188-194). composeProduct는 http가 생긴 뒤에 불리고
  http는 세션이 필요해서 이 일을 받을 수 없다.

고른 방법
- product-contracts.ts에 PRODUCT_ENV_REGISTRY를 빈 값으로 둔다. env.ts는
  PRODUCT_REST_AUTH_PROFILES·PRODUCT_RUNTIME_CONFIG_FIELDS와 같은 모양으로
  그 행을 ENV_REGISTRY에 합친다. 템플릿 키와 이름이 겹치면 모듈 로드 때
  throw한다. check:registries와 vite.config.ts가 같은 객체를 읽으므로 제품
  행도 같은 필드 검사를 받는다. 행을 더하기만 하면 additive라 기준선을
  고치지 않는다(실험: 제품 행 2개 → compatibility=additive PASS, 허용 밖
  classification → 실패).
- product-composition.ts에 composeProductSessionOwner(context)를 둔다.
  템플릿은 null을 돌려준다. 조립 루트가 세션을 고르기 전에, AUTH_MODE가
  external일 때만 부른다. 제품 owner가 host 전역보다 먼저다. null이면
  지금처럼 host 전역, 없으면 unavailable이다. demo 모드는 묻지 않는다.
  context는 config와 fetcher뿐이다(http 전이라 capability가 없다).

버린 대안
- owner를 composeProduct 반환값에 넣기: http가 세션을 쓰므로 순서가 꼬인다.
- 제품이 host 전역에 계속 넣게 두고 문서화: 부트 전 훅이 템플릿 파일
  (create-runtime-composition.ts)에 남는다.
- FE-REG-ENV 행을 PRODUCT_RUNTIME_CONFIG_FIELDS에서 자동으로 만들기: zod
  필드로는 classification·required를 알 수 없다.
- 행 타입·도우미를 product-contracts.ts가 env.ts에서 import: 순환 의존
  (no-circular-dependencies)이다. 타입 검사는 env.ts의 대입에서 한다.

위험·한계
- product-composition.ts에 export가 하나 늘었다. 이 파일을 이미 복사한
  제품은 composeProductSessionOwner를 더해야 한다. da1e128은 아직 main에
  없고 두 다운스트림 모두 받지 않았다.
- 제품 행을 as const 없이 쓰면 phase가 string으로 넓어져 tsc 오류가
  env.ts:78(템플릿 파일)에서 난다. 메시지에 키 이름은 나온다. product-
  contracts.ts 주석에 as const를 적었다.
- 제품 설정 키에 FE-REG-ENV 행이 있는지 요구하는 검사는 여전히 없다.
  템플릿 키도 RELEASE_ID·BUILD_ID는 행이 없어서 이 변경에서 넣지 않았다.
- 제품 owner가 throw하면 createRuntimeAdapters가 실패해 부트 실패
  화면이 된다. composeProduct와 같다.
- tech-log의 owner는 subject를 null로 돌려준다(템플릿 동작대로 매 변경
  fence). 이 변경과 무관하다.

검증
- RED: tests/unit/product-composition-fixture.test.ts 13건 중 3건 실패.
  FE-REG-ENV 행 없음, external 모드 세션이 authenticated가 아니라
  integration-failed, env 이름 충돌을 거절하지 않음.
- GREEN: 같은 파일 13/13, runtime-adapters-credential-order 7/7(mock에
  composeProductSessionOwner: () => null 추가).
- fixture는 vi.mock 대상이 제품 소유 두 파일(머리 주석 "Product-owned.")과
  설치 기능 seam 두 개뿐이고, tech-log가 고친 템플릿 파일 4개(env.ts,
  create-runtime-composition.ts, runtime-config-schema.ts,
  runtime-adapters.ts)는 대상이 아님을 이 파일의 소스를 읽어 확인한다.
- 회귀: tests/unit·contract·runtime-schema·integration 198 files 2861
  tests 통과(heavy lock 아래).
- tsc app·node·test 통과, 바꾼 파일 eslint 통과, check:registries PASS
  (compatibility=none, 재승인 불필요), verify:documentation PASS_SCOPED,
  check:adapter-inventory PASS.
- 초기 JS gzip 202,770 → 202,931 B(+161, 예산 204,800). 같은 방법(dist
  manifest의 초기 파일 26개, gzipSync 기본 레벨)으로 전·후를 쟀다.
- 미실행: check:architecture(pnpm 필요), test:component, e2e.
2026-11-03 20:23:14 +09:00

256 lines
16 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`.
`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`) and `/examples/*`
(`src/presentation/examples/`) are template content. Their own tests are the
`tests/component/starter-*.test.tsx` files; delete them together with the
screens. 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 when the starter screens
change. Browser-level checks of the starter screens stay in `tests/e2e` and
`tests/visual`.
### 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` and no
`NOT_INSTALLED` marker file (`src/features/local-draft-feature/NOT_INSTALLED`
is the one intentional example);
- 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.
`src/features/reference-feature/feature-module.ts` is the complete example.
2. Create `src/features/<feature>/feature-runtime.ts` with
`defineFeatureRuntime`: the API contract (operations, schema metadata,
runtime schemas, mappers), the adapter contributions
(`defineFeatureAdapterContribution`, with `needs` naming the platform
capabilities it receives) and the contract contributions. 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 twice: its API contract operation (V2) is what
`check:registries` governs, and its contract contribution descriptor (V3)
is what executes. `tests/unit/http-operation-v2-v3-parity.test.ts` fails
when one exists without the other or when they disagree.
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.
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
`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. 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 (`src/features/local-draft-feature/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 | — |
| `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` |
| `artifacts/tests/a11y-manual/<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` | a route path has a parameter other than `:resourceId`, or a protected page cannot render while every API answers `[]` | `test:a11y` (FE-GATE-009): the spec fills in only `:resourceId` and answers every API with `[]` |
| `src/bootstrap/product-composition.ts` (product-owned) | `needs` names a capability the template does not build: augment `FeaturePlatformCapabilities` and return the capability here. `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 `REST security profiles are incoherent for <operationId>: unknown authProfileId …`. Config key: `check:types` where it is read. FE-REG-ENV row: `check:registries` checks its fields; nothing requires the row |
| `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; `NoRequest` already belongs to the
sample. 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.
- **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.