Files
clean-architecture-frontend…/docs/architecture/starter-experience.md
T
DongHyeonka 298201f3ee perf(features)!: 기능 실행부를 초기 청크에서 떼어 라우트 진입 때 적재한다 (15-01)
문제
초기 JS는 203,572 / 204,800 B(gzip)였다. 생성 인덱스가 각 기능의
feature-module.ts를 정적으로 import하고, 그 파일이 계약(zod 스키마·mapper
포함), HTTP 계약 contribution, application input 팩토리, route codec까지
모두 끌고 왔다. 참조 모양 기능 1개를 더하면 +3,922 B가 늘어 첫 기능에서
예산을 넘었다.

고른 방법
- 기능을 두 부분으로 나눈다. 선언(FeatureModule: route 표, route runtime
  계약, invalidation, 문구, 부팅 때 release manifest와 맞춰 볼
  contractPackages)은 초기 청크에 남는다. 실행부(FeatureRuntime: V2 API
  계약, adapter contribution, contract contribution)는 feature-runtime.ts로
  옮기고 loadRuntime이 동적 import한다. route codec은 context-routes.ts의
  route handle에 실어 route와 함께 적재한다.
- 적재 시점은 그 기능의 route에 들어갈 때다. ContextRouteGateway가 route
  모듈과 함께 application.features.load(featureId)를 부르고, 끝난 뒤에
  화면을 그린다(공개 포트에는 load만 추가). 들어온 URL의 기능은 route
  모듈과 병렬로 적재해 왕복을 늘리지 않는다. 런타임 설정으로 꺼진 기능은
  적재하지 않는다.
- 조립부는 기능별 로더를 만든다(installed-feature-adapters.ts). contract
  registry는 기능이 적재될 때마다 전체를 다시 합쳐 검증한다
  (installed-contract-contributions.ts). 선언하지 않은 contract package를
  적재하면 거절한다.
- 모든 실행부를 한꺼번에 읽는 registry(V2 API, contract contribution)는
  installed-feature-runtime-registries.ts의 async 함수로, Node·테스트·
  registry 거버넌스용 상수는 top-level await 모듈 loaded-feature-runtimes.ts로
  둔다. src에서 후자를 import하면 새 아키텍처 규칙
  boot-does-not-load-every-feature-runtime이 막는다. 플랫폼 구성 화면은
  route 로더에서 async 함수를 불러 결과를 prop으로 받는다.
- vite.config.ts에 청크 그룹 2개를 둔다. rolldown은 부팅 그래프와 lazy
  청크가 같이 쓰는 모듈을 importer 집합마다 따로 청크로 뗀다. 그대로 두면
  기능마다 선언 청크가 하나씩 늘고(기능당 +1,471 B), 실행부와 공유하는
  플랫폼 모듈(HTTP executor, contract runtime, zod)이 6개 청크로 쪼개져
  템플릿 자체가 +438 B 커졌다. feature-declarations는 모든 기능의 선언을,
  feature-platform은 실행부가 같이 쓰는 부팅 모듈을 한 청크로 묶는다.
  render-boot-failure.tsx가 쓰는 모듈은 feature-platform에서 뺀다(09-03:
  애플리케이션 그래프가 평가 중 던져도 실패 화면은 떠야 한다).

버린 대안
- 부팅 때 feature 청크를 미리 동적 import하고 기다린 뒤 렌더: 분류기는
  lazy로 세지만 첫 렌더 경로의 바이트는 그대로다. 예산을 속이는 것이라
  버렸다.
- 실행부 일부만 지연(adapter와 contribution만): 모두 같은 zod 스키마를
  공유해 줄지 않았다. 실측 +4,031 B로 오히려 늘었다.
- 선언과 실행부를 같은 lazy 청크(context-routes)에 두기: 기능당
  -60 B 수준이라 그룹 없이 목표에 못 미쳤다.
- 페이지 문구까지 실행부로 옮기기: 기능당 약 300~450 B를 더 줄이지만
  i18n catalog를 런타임 등록 구조로 바꿔야 해 이번 범위에서 뺐다.
- boot.tsx를 별도 진입점으로 추가: 분류기가 boot의 동적 import를 모두
  초기로 세어 218,303 B가 됐다.

위험·한계
- FeatureModule 모양이 바뀐다. 다운스트림 기능은 feature-runtime.ts로
  실행부를 옮겨야 한다(BREAKING CHANGE).
- 기능 계약 간 중복(operation, schema, contribution) 검사가 부팅이 아니라
  그 기능의 적재 시점과 Node 검사(loaded-feature-runtimes를 읽는 스크립트·
  테스트)로 옮겨 간다.
- 기능 route에 처음 들어갈 때 실행부 청크(약 5 KB gzip)를 받는다. 플랫폼
  구성 화면은 모든 기능의 실행부를 받은 뒤 그린다. lab 게이트(FE-GATE-026)가
  재는 화면이라 LCP가 조금 늘 수 있다. 측정하지 않았다.
- 청크 그룹은 rolldown 자동 분할을 일부 대신한다. feature-declarations가
  비면 기능당 증가 상한 테스트가 실패한다. feature-platform이 비면 템플릿
  총량(약 2 KB)만 늘고 번들 예산 검사가 잡는다.
- config/contracts/registry-baseline.json의 FE-REG-API/SCHEMA source는 아직
  installed-feature-contracts.ts다. 승인 digest가 걸려 있어 소유자 재승인
  때 고친다. check-registries는 통과한다.
- 예산 안에 들어가는 참조 모양 기능은 약 3개다. 플랫폼 자체가 예산의
  98.8%다.

수치 (vite build, classifyViteJavascript + gzipSync 기본 수준)
- 템플릿: 203,572 B(13파일) -> 202,361 B(16파일), -1,211 B
- 참조 복사본 +1: 207,494 B(+3,922) -> 203,102 B(+741)
- 참조 복사본 +2: 210,818 B(+3,324) -> 203,750 B(+648)
- 참조 복사본 +5: 205,629 B
- lazy JS: 23,516 B -> 28,204 B

검증
- RED: node scripts/run-vitest.ts run tests/unit/feature-shape-growth.test.ts
  "adds at most 1 KiB ... (15-01)" 실패: expected 3934 to be less than or
  equal to 1024
- GREEN: 같은 테스트 통과(+741 B)
- node scripts/run-vitest.ts run tests/unit: 168파일 2,383 통과
- node scripts/run-vitest.ts run tests/component tests/features
  tests/integration tests/contract tests/runtime-schema tests/architecture
  tests/platform tests/recipes (security-followup-archive 제외, pnpm 호출):
  109파일 787 통과
- npx tsc --noEmit: app, node, test, recipes, web-worker, service-worker 통과
- npx eslint 바뀐 파일 통과
- check-architecture.ts(pnpm exec 대신 eslint를 부르는 shim): PASS, 새 규칙이
  boot.tsx의 import를 거절하는 것 확인
- check-adapter-inventory, check-registries, verify-documentation-readiness,
  check-ci-contract: PASS
- e2e Chromium 전체(pnpm 없는 build-frontend + vite preview, 별도 포트):
  55 통과
- storybook build 성공
- 미실행: Firefox·WebKit e2e, 시각 회귀, lab 성능(FE-GATE-026),
  pnpm 경로의 check:bundle, test:system

BREAKING CHANGE: FeatureModule은 id, contracts(선언), routes, messages,
  loadRuntime만 가진다. adapters, contractContributions와 V2 API 계약
  (apiOperations, schemas, runtimeSchemas, mappers)은 defineFeatureRuntime으로
  만든 feature-runtime.ts로, route codec은 context-routes.ts의 route handle
  codecs로 옮긴다. contracts에는 contractPackages를 추가한다.
Refs: docs/reviews/2026-11-01-maturity-review/15-performance.md 15-01,
  16-structure-patterns.md 9절
2026-11-01 21:57:53 +09:00

8.4 KiB

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

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 and the TypeScript, state, and data-flow target rather than adding another independent route or data-loading convention.

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

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).
  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).
  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.
  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:

File Change
src/.generated/* regenerated automatically
src/contexts/<context>/context-module.ts only when the feature needs a new context
config/runtime/<profile>.json optional FEATURE_OVERRIDES entry to switch the feature off
src/bootstrap/runtime-adapters.ts only when needs includes indexedDb: add the capability, built as in recipes/frontend-capabilities/indexeddb-feature-capability.ts

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).

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.