chore(review): 리뷰 기준으로 두 작업 브랜치를 합친다

문제
2026-11-03 전체 리뷰는 출시될 코드 전체를 봐야 한다. 오늘 고친 것이 두 브랜치에
나뉘어 있다. claude/happy-easley-233d07(Envelope, V2 삭제, 거절 표, CSRF·KEYED
재전송)과 fix/ui-design-audit-2026-11-01(남은 위험 16커밋)이다. 사용자가 두
브랜치를 합친 상태를 리뷰 기준으로 골랐다.

고른 방법
새 브랜치 review/2026-11-03-merged에서 두 브랜치를 합쳤다. 원래 두 브랜치는
건드리지 않았다. 충돌은 계약 문서 4.1·6절 두 곳이었다.
- 4.1: 백엔드 기준 SHA(5786126c) 문장은 fix 쪽을, Envelope를 읽는 곳은 V2가
  없어진 이쪽을 택했다.
- 6절: 거절 판정 위치는 backend-envelope.ts 표다.
- 6.1 "프론트 판정과 표가 다른 곳"에서 3261208이 고친 두 항목을 지웠다.

위험·한계
- 이 합치기는 리뷰 기준을 고정하려는 것이다. 어느 브랜치를 main에 합칠지는
  사용자가 정한다.

검증
- check:types 통과. 나머지 게이트는 리뷰 기록(9절)에 적는다.
This commit is contained in:
DongHyeonka
2026-11-03 22:49:20 +09:00
36 changed files with 1443 additions and 121 deletions
+1 -1
View File
@@ -15,7 +15,7 @@
},
{
"script": "check:remediation-ledger",
"reason": "Checks the prose ledger of the 2026-08-14 adapter re-review (docs/operations/adapter-remediation-ledger.md) against test-file markers and the file-transfer bundle budget. Later fixes removed those markers and the budget is re-set at integration, so the check reports stale claims at this commit. It is a history record run by hand, not a current contract; wiring it into a gate first needs the ledger or the markers brought up to date."
"reason": "Checks the prose ledger of the 2026-08-14 adapter re-review (docs/operations/adapter-remediation-ledger.md) against test-file markers and the file-transfer bundle budget. It passes at this commit, but it is a history record run by hand, not a current contract: it fails when a product removes the optional file-transfer recipe or when a test split moves a marked test to another file, and neither should block a merge. Run it after moving those tests or changing that budget, and point the ledger rows at the new files."
},
{
"script": "check:scale:baseline",
@@ -165,14 +165,14 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정
- 정본: [`clean-architecture-backend-template/docs/web/http-contract.md`](../../../clean-architecture-backend-template/docs/web/http-contract.md)
1절 "Envelope 키 존재 규칙"
- 기준 버전: 백엔드 성숙도 리뷰 2026-11-01의 15절 결정(2026-11-03)을 반영한 본.
값이 null인 필드는 키째 생략한다. 백엔드에 이 변경의 커밋이 생기면 그 SHA로
바꾼다.
- 프론트에서 Envelope를 읽는 곳: `src/adapters/http/backend-envelope.ts`
(스키마는 `schema-registry.ts`). V2 `client.ts`는 늘 이것을 쓴다. V3 실행기는
descriptor가 `responseEnvelope: "ENVELOPE_V1"`일 때만 쓴다. `create:feature`가
만든 기능은 이 값을 선언한다. 참조 기능은 선언하지 않고 DTO와 problem
details를 검증한다.
- 기준 커밋: 백엔드 `5786126c`. `http-contract.md`는 `34565130`에서 들어왔고
`1400dc15`에서 마지막으로 바뀌었다. 값이 null인 필드는 키째 생략한다. 백엔드
기준 커밋을 올리면 6.1절 표를 같은 변경에서 다시 확인한다.
- 프론트에서 Envelope를 읽는 곳: `src/adapters/http/backend-envelope.ts`(스키마와
해석). V3 실행기는 descriptor가 `responseEnvelope: "ENVELOPE_V1"`일 때 쓴다.
`create:feature`가 만든 기능은 이 값을 선언한다. 참조 기능은 선언하지 않고
DTO와 problem details를 검증한다.
- 실패 Envelope의 `error.code`가 "적용 안 됨"인지는 6.1절이 정한다.
### 4.2 Status와 error
@@ -243,7 +243,7 @@ backend idempotency를 대체하지 않는다.
- 정본: [`clean-architecture-backend-template/docs/web/http-contract.md`](../../../clean-architecture-backend-template/docs/web/http-contract.md)
2절 "멱등성 응답", 4절 "web 전용 오류 코드"
- 기준 버전: 4.1절과 같다(백엔드 리뷰 2026-11-01 15절 결정, 2026-11-03).
- 기준 커밋: 4.1절과 같다(백엔드 `5786126c`).
- 프론트가 그 응답을 읽는 곳:
- 키 생성·검사: `src/contracts/mutation-intent.ts` `isValidIdempotencyKey`
- 결과 불명 재전송이 같은 키를 쓰고 `Retry-After`까지 기다리는 곳:
@@ -254,6 +254,65 @@ backend idempotency를 대체하지 않는다.
(effect), `src/features/reference-feature/adapters/reference-http-gateway.ts`
(code)
### 6.1 거절 code와 적용 여부
mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐는지 정해야 한다.
- `NOT_APPLIED`: 쓰기 전에 거절됐다. 다음 저장은 새 `Idempotency-Key`를 쓴다.
- `MAYBE_APPLIED`: 쓰기 뒤에도 나올 수 있다. mutation 코디네이터가 키를 붙들고
결과 불명으로 보인다. effect가 없는 실패도 이 값이다.
백엔드 `http-contract.md`는 code가 어느 단계에서 나오는지 적지 않는다. 아래 표는
프론트가 백엔드 `5786126c`의 코드를 읽고 정한 판정이다. 같은 code가 쓰기 전과
뒤에서 모두 나오면 "쓰기 뒤 가능"으로 둔다. 프론트는 code만 보고 둘을 가를 수
없다.
| code (status) | 나오는 곳 | 단계 | 프론트 결과 | 백엔드 파일:줄 |
| --- | --- | --- | --- | --- |
| `VALIDATION_FAILED` (400), details = 필드 목록 | 요청 본문 `@Valid` 실패, 컨트롤러 파라미터 제약 실패. 컨트롤러 메서드가 불리기 전 | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:218-231`, `:346-368` |
| `VALIDATION_FAILED` (400), details = 필드 목록 | `ConstraintViolationException`. 어느 층에서 던져도 이 handler가 받는다. 요청 경로에서 던지는 코드는 없다(application bean에 `@Validated` 없음, JPA entity에 Bean Validation 제약 없음, 직접 throw 없음) | 쓰기 전(현재 출처 없음) | `NOT_APPLIED` | `GlobalExceptionHandler.java:101-106` |
| `VALIDATION_FAILED` (400), details = `{cause}` 또는 없음 | 본문을 읽지 못함(`HttpMessageNotReadableException`) | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:233-251` |
| `VALIDATION_FAILED` (400), details = `{field, code}` | 페이지·정렬 파라미터. 목록 GET 컨트롤러가 use case 전에 검사한다 | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:149-153`, `PageParams.java:27-33`, `SortParam.java:16-43` |
| `IDEMPOTENCY_KEY_INVALID` (400) | KEYED 컨트롤러 첫 줄의 키 파싱 | 쓰기 전 | `NOT_APPLIED` | `IdempotencyKeyHeader.java:32-38`, `PosterImagePublicationController.java:64` |
| `IDEMPOTENT_REQUEST_MISMATCH` (422) | 멱등성 executor가 action 전에 판정 | 쓰기 전 | `NOT_APPLIED` | `IdempotencyExecutor.java:102-103`, `:134-135` |
| `IDEMPOTENT_IN_FLIGHT` (409) | 멱등성 executor가 action 전에 판정. 같은 키의 앞선 요청이 실행 중이다 | 이번 요청은 쓰기 전. 앞선 요청은 적용될 수 있다 | `MAYBE_APPLIED` | `IdempotencyExecutor.java:104-105`, `:136-137` |
| `BAD_PARAMETER` (400) | 타입 변환 실패, 필수 파라미터·헤더 없음(쓰기 전). **어느 층이든 `IllegalArgumentException`**(use case·domain 포함) | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `GlobalExceptionHandler.java:92-99`, `:108-116`, `:397-438` |
| `MAPPING_FAILED` (400) | web 매퍼(쓰기 전), outbound ACL 매퍼(use case 안), 멱등성 응답 직렬화(action이 끝난 뒤) | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `WorkLogWebMapper.java:36`, `RepoStatsAclMapper.java:14`, `JsonIdempotentResponseCodec.java:32`, `IdempotencyExecutor.java:229` |
| `DB_SERIALIZATION_FAILURE`, `DB_DEADLOCK`, `DB_LOCK_TIMEOUT`, `DB_NULL_VIOLATION`, `DB_FK_VIOLATION`, `DB_UNIQUE_VIOLATION`, `DB_CHECK_VIOLATION`, `DB_OPTIMISTIC_CONFLICT` (409) | persistence 어댑터가 SQL·JPA 실패를 바꾼 것. 트랜잭션 안이나 commit에서 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `FailureCategory.java:79-95`, `StandardSqlStateErrorMapping.java:46-52`, `PersistenceExceptionTranslator.java:131` |
| `LOCK_ACQUISITION_TIMEOUT` (409) | 분산 락 대기 초과. use case 안 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `LockRegistryDistributedLock.java:50`, `:53` |
| 참조 도메인 `WORKLOG_INVALID`, `POSTER_INVALID_STATE`, `POSTER_IMAGE_REQUIRED` (400), `WORKLOG_CONFLICT`, `POSTER_ALREADY_EXISTS`, `POSTER_IMAGE_ALREADY_PUBLISHED` (409) | application·domain 예외 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `DomainExceptionHandler.java:52-90` |
| 선택 모듈 web-advanced `PATCH_REJECTED` (400), `PATCH_TEST_FAILED` (409) | patch 라이브러리. 부르는 코드가 단계를 정한다 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `src/adapter/inbound/web-advanced/README.md` 「오류 응답」 |
| 선택 모듈 fileserver `BAD_REQUEST` (400), `FILE_ALREADY_EXISTS`, `FILE_NOT_READY`, `UPLOAD_OFFSET_MISMATCH`, `CONCURRENT_MODIFICATION` (409), `INTEGRITY_MISMATCH`, `MALWARE_DETECTED`, `INVALID_PATH`, `PATH_OUTSIDE_NAMESPACE` (422) | application·outbound 층. `INTEGRITY_MISMATCH`·`MALWARE_DETECTED`는 레코드를 `REJECTED`로 쓴 뒤 던진다 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `FileserverErrorCode.java:26-44`, `FinalizeUploadApplicationUseCase.java:211-224`, `:336-341` |
- application-notification의 `VALIDATION_FAILED`(`NotificationFailureCode`)는
`ApiErrorCarrier`가 아니다. HTTP로는 500 `INTERNAL_ERROR`로 나가므로 표에 없다.
- 표에 없는 400·409·422 code는 `MAYBE_APPLIED`로 본다.
- 파일 위치(백엔드 repo 기준):
- `GlobalExceptionHandler.java`: `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/`
- `PageParams.java`, `SortParam.java`: 같은 모듈 `.../web/pagination/`
- `IdempotencyKeyHeader.java`: 같은 모듈 `.../web/http/`
- `IdempotencyExecutor.java`: `src/application-core/src/main/java/dev/caskeleton/application/idempotency/`
- `JsonIdempotentResponseCodec.java`: `src/adapter/inbound/web-advanced/.../advanced/idempotency/`
- `FailureCategory.java`, `StandardSqlStateErrorMapping.java`,
`PersistenceExceptionTranslator.java`, `LockRegistryDistributedLock.java`:
`src/adapter/outbound/persistence-jpa/`
- `PosterImagePublicationController.java`, `WorkLogWebMapper.java`,
`RepoStatsAclMapper.java`, `DomainExceptionHandler.java`: `src/sample-portfolio/`
- `FileserverErrorCode.java`, `FinalizeUploadApplicationUseCase.java`:
`src/application-fileserver/`
프론트 판정과 표가 다른 곳(고치면 이 줄을 지운다):
- 참조 기능 분류기(`classifyProblem`)는 참조 fixture(problem+json)용이라
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 제약을
넣으면, 필드 목록이 있는 400 `VALIDATION_FAILED`가 use case 안에서도 나온다.
백엔드에는 이것을 막는 검사가 없다.
## 7. Cursor pagination과 snapshot
Backend가 pagination을 선택할 때 새 response schema/operation version으로 다음
@@ -176,9 +176,14 @@ The same file is where a product adds any other capability (it augments
`FeaturePlatformCapabilities`) and the credential provider for a product auth
profile. The composition root keeps the order: scope fence, `ANONYMOUS`
profile, product provider, session, scope fence again
(`tests/unit/runtime-adapters-credential-order.test.ts`). Product auth profiles
and runtime-config keys go in `src/contracts/product-contracts.ts`; both join
the template's registries under the same checks
(`tests/unit/runtime-adapters-credential-order.test.ts`). A product that owns
the session itself (a BFF whose session is an httpOnly cookie) returns its
session owner from `composeProductSessionOwner` in the same file. It is asked
first, before `http` exists, only when `AUTH_MODE` is `external`, and it comes
before the host's `__CA_FRONTEND_AUTH_OWNER__`; `null` leaves the session to
that global. Product auth profiles, runtime-config keys and the keys'
FE-REG-ENV rows go in `src/contracts/product-contracts.ts`; each joins the
template's registry under the same checks
(`tests/unit/product-composition-fixture.test.ts`).
## Presentation consumer surface
@@ -1895,11 +1895,11 @@ credential을 보호할 수 있다고 주장하지 않는다.
| `UNSUPPORTED` | browser capability 없음 | declared fallback |
| `OFFLINE` | network hint/attempt failure | online hint 뒤 bounded check |
| `CONNECT_TIMEOUT` | open deadline 초과 | bounded reconnect |
| `IDLE_TIMEOUT` | transport: heartbeat/byte/unsubscribe deadline 초과(operation `RECEIVE`·`SUBSCRIBE`). handoff coordinator의 quiescence·checkpoint·close deadline 초과(operation `RECOVER`·`CLOSE`) | transport: close + bounded reconnect. handoff 마감은 재연결로 풀리지 않는다: 그 전환을 fail-close한다(결과는 kind 기본값대로 retryable). 두 뜻은 `operation`으로 구분한다 |
| `IDLE_TIMEOUT` | transport: heartbeat/byte/unsubscribe deadline 초과(operation `RECEIVE`·`SUBSCRIBE`). 내부 task 마감에는 쓰지 않는다 | close + bounded reconnect |
| `AUTH_REQUIRED` | session expired/recovery 실패 | sign-in UX |
| `FORBIDDEN` | stream/resource 거절 | retry 없음 |
| `RATE_LIMITED` | connection/request/provider limit | bounded server hint |
| `PROVIDER_UNAVAILABLE` | backend/push/hosting unavailable. stream coordinator의 recovery deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: false`) | bounded retry 또는 degraded. stream coordinator 마감은 재연결로 풀리지 않는다: task가 settle할 때까지 `DRAINING`을 유지한다. settle 뒤 recovery 마감은 다음 event가 recovery부터 하고, close 마감은 `CLOSED`가 된다 |
| `PROVIDER_UNAVAILABLE` | backend/push/hosting unavailable. stream coordinator의 recovery deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: false`). live↔Poll handoff coordinator의 checkpoint deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: true`) | bounded retry 또는 degraded. stream coordinator 마감은 재연결로 풀리지 않는다: task가 settle할 때까지 `DRAINING`을 유지한다. settle 뒤 recovery 마감은 다음 event가 recovery부터 하고, close 마감은 `CLOSED`가 된다. handoff checkpoint 마감은 그 전환을 fail-close하므로 새 handoff만 돌 수 있다. handoff close 마감 뒤에는 writer·checkpoint task가 settle하면 다시 부른 `close()`가 성공한다 |
| `PROTOCOL_MISMATCH` | version/subprotocol/content type | terminal/rollout rollback |
| `MALFORMED_EVENT` | state-bearing syntax/schema/exact-key 실패 | cursor 미진행, freshness `UNKNOWN`, close + registered recovery |
| `MAPPING_CONTRACT_VIOLATION` | validated DTO의 registered mapper 실패 | effect/cache/cursor write 0, close + registered recovery |
@@ -1910,7 +1910,7 @@ credential을 보호할 수 있다고 주장하지 않는다.
| `SEQUENCE_GAP` | missing event | snapshot resync |
| `CURSOR_EXPIRED` | replay retention 밖 | snapshot reset |
| `QUEUE_OVERFLOW` | backpressure ceiling | close + registered snapshot/session rebuild |
| `APPLY_FAILED` | feature effect 실패. stream coordinator의 effect deadline 초과(operation `APPLY`, `retryable: false`)도 이 kind다 | cursor 미commit, bounded registered recovery. deadline 초과는 recovery를 바로 하지 않는다: task가 settle할 때까지 `DRAINING`을 유지하고, settle 뒤 다음 event가 recovery부터 한다 |
| `APPLY_FAILED` | feature effect 실패. stream coordinator의 effect deadline 초과(operation `APPLY`, `retryable: false`)도 이 kind다. live↔Poll handoff coordinator에서 이전 writer의 effect가 quiescence deadline 안에 끝나지 않은 것(operation `RECOVER`, `retryable: true`)도 이 kind다 | cursor 미commit, bounded registered recovery. deadline 초과는 recovery를 바로 하지 않는다: task가 settle할 때까지 `DRAINING`을 유지하고, settle 뒤 다음 event가 recovery부터 한다. handoff quiescence 마감은 그 전환을 fail-close하므로 새 handoff만 돌 수 있다 |
| `POLL_BUDGET_EXHAUSTED` | lease 한도 도달 | stale/manual retry |
| `PUSH_PERMISSION_DENIED` | 사용자 거절 | foreground fallback |
| `PUSH_SUBSCRIPTION_STALE` | rotation/expiry/provider gone | bounded re-registration |
@@ -290,6 +290,10 @@ chunk recovery 순서:
"한 번 새로고침" 버튼이 있다(`app-router.tsx`의 `RouteFailureSurface`).
- 복구하지 못한 청크 실패: 같은 형식이다. `ChunkRecoveryBoundary`의
`onUnrecovered`가 같은 ID로 `ui.render.failed`를 기록한다.
- context가 라우트나 레이아웃을 불러오지 못한 실패: `route_id`는 그 URL의 등록
라우트 id다. 등록 라우트가 없는 URL이면 `UNREGISTERED_ROUTE`다. not-found
화면이 실패한 것이 아니므로 `NOT_FOUND`를 쓰지 않는다(`app-router.tsx`의
`failedRouteIdAt`).
- 조회 실패: `AppFailure.requestId`. HTTP 진단의 `correlation_id`와 같은 값이다
(`async-surface.tsx`의 `TerminalErrorSurface`).
+12 -6
View File
@@ -160,10 +160,14 @@ selected app. Every build and check script runs it first; run it yourself with
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").
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 (`src/features/local-draft-feature/application/local-draft-api.ts`).
6. Run `corepack pnpm check:architecture`, `corepack pnpm check:types`,
@@ -182,8 +186,8 @@ Files outside the feature directory. Everything else a feature needs is in
| `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 | `check:types`; at runtime `feature <id> needs <capability>, which the host did not provide` |
| `src/contracts/product-contracts.ts` (product-owned) | a product auth profile or a product runtime-config key | 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 |
| `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>` |
@@ -234,6 +238,8 @@ than `AppShell`, declares it. The router and the catalogs do not change.
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`.
+10
View File
@@ -39,3 +39,13 @@ that the host serves that release; while the slot is empty FE-GATE-019 is
Rollback changes the active pointer only after confirming that the prior
immutable release has a coherent HTML/assets/config/API/manifest tuple.
Serve the app over HTTP/2 or later. The entry preloads about 26 initial
JavaScript files in parallel. Over HTTP/1.1 they queue for six connections per
host, and the first screen on Fast 3G came about one second later than with the
initial chunks grouped (2026-11-03). Over HTTP/2 the difference was under
100 ms, so the template keeps the chunks split. A product that can only serve
HTTP/1.1 groups its initial chunks in `vite.config.ts` and measures again
whenever the shell changes ("초기 청크 수와 HTTP/1.1" in
[`performance-evidence.md`](../operations/performance-evidence.md), review
1101/14.4).
@@ -113,7 +113,7 @@
"previous": "PARTIAL",
"disposition": "FIXED",
"summary": "A source lease that arrives after the delivery ended is closed exactly once by a compensator.",
"evidence": ["tests/unit/presigned-transfer.test.ts"]
"evidence": ["tests/unit/presigned-transfer-delivery.test.ts"]
},
{
"id": "TR-03",
@@ -123,7 +123,7 @@
"markers": ["X-AUDIT-01", "X-AUDIT-02"],
"evidence": [
"tests/unit/abortable-operation.test.ts",
"tests/unit/image-cdn-runtime.test.ts",
"tests/unit/image-cdn-browser-probe.test.ts",
"tests/unit/resumable-upload-fetch-transport.test.ts"
]
},
@@ -132,7 +132,7 @@
"previous": "PARTIAL",
"disposition": "FIXED",
"summary": "Teardown proves quiescence of the raw provider registry, not only of the wrappers that bound it.",
"evidence": ["tests/unit/resumable-upload-runtime.test.ts"]
"evidence": ["tests/unit/resumable-upload-runtime-teardown.test.ts"]
},
{
"id": "TR-05",
@@ -10,7 +10,12 @@
> Test paths are given at their current location. Two suites moved after
> these runs: `ci-artifact-contract.test.ts` from `tests/unit/` to
> `tests/system/ci-runner/`, and `provider-guardian-transaction.test.ts` from
> `tests/unit/` to `tests/integration/`.
> `tests/unit/` to `tests/integration/`. Three suites were split on
> 2026-09-18 (`5cc41467`, `ec7f20e2`) and the third re-review rows follow the
> tests that moved: TR-02 to `presigned-transfer-delivery.test.ts`, TR-03's
> image probe to `image-cdn-browser-probe.test.ts`, TR-04 to
> `resumable-upload-runtime-teardown.test.ts` (all in `tests/unit/`). The run
> commands in the earlier sections keep the file each run used.
## Containment state (plan Task 1, Step 1)
@@ -431,9 +436,9 @@ than authored.
| RT-01 | `PARTIAL` | `FIXED` | `tests/unit/realtime/stream-coordinator.test.ts` — an authority that re-entered `close()` from inside its own invocation got `{ok:true}` while its effect was pending; the task is registered before the collaborator is called. |
| RT-02 | `NEW` | `FIXED` | Same suite — a throwing `scheduleTimeout` started a recovery that overlapped the running apply and made `close()` reject with a native `TypeError`; an uninstallable deadline now fails closed inside the result contract. |
| TR-01 | `PARTIAL` | `FIXED` | `tests/unit/presigned-transfer.test.ts` — a stateful issuer could show an allowed header set to the forbidden-header check and store `Authorization`; the registration and everything nested in it is snapshotted before validation. |
| TR-02 | `PARTIAL` | `FIXED` | Same suite — a source lease that resolved after an abort was never closed; a compensator sharing the holder's close-once latch closes it exactly once. |
| TR-03 | `PARTIAL` | `FIXED` | `tests/unit/abortable-operation.test.ts`, `tests/unit/image-cdn-runtime.test.ts`, `tests/unit/resumable-upload-fetch-transport.test.ts` — the outcome depended on a hard-coded four-microtask drain, and a throwing scheduler rejected `probe()`/`execute()` natively while leaking a caller listener. The primitive now settles once by observation order, and all four consumers use it with construction-time bound timer snapshots. |
| TR-04 | `PARTIAL` | `FIXED` | `tests/unit/resumable-upload-runtime.test.ts` — a provider outliving its attempt deadline let `dispose()` report a drained runtime and close the checkpoint store; raw provider work is now its own registry and both must be quiescent. |
| TR-02 | `PARTIAL` | `FIXED` | `tests/unit/presigned-transfer-delivery.test.ts` — a source lease that resolved after an abort was never closed; a compensator sharing the holder's close-once latch closes it exactly once. |
| TR-03 | `PARTIAL` | `FIXED` | `tests/unit/abortable-operation.test.ts`, `tests/unit/image-cdn-browser-probe.test.ts`, `tests/unit/resumable-upload-fetch-transport.test.ts` — the outcome depended on a hard-coded four-microtask drain, and a throwing scheduler rejected `probe()`/`execute()` natively while leaking a caller listener. The primitive now settles once by observation order, and all four consumers use it with construction-time bound timer snapshots. |
| TR-04 | `PARTIAL` | `FIXED` | `tests/unit/resumable-upload-runtime-teardown.test.ts` — a provider outliving its attempt deadline let `dispose()` report a drained runtime and close the checkpoint store; raw provider work is now its own registry and both must be quiescent. |
| TR-05 | `PARTIAL` | `FIXED` | `tests/unit/resumable-upload-http-control-plane.test.ts` — a stateful `sessionId` passed the regex and returned `../../unsafe`; the decoder validates an owned snapshot read exactly once. |
| SW-01 | `PARTIAL` | `FIXED` | `tests/unit/service-worker-runtime.test.ts` — a single 1 MiB chunk was retained before the 257-byte ceiling was compared, a declared oversize left the body open and the reader lock was never released. |
| SW-02 | `PARTIAL` | `FIXED` | `tests/unit/service-worker-web-push-remediation.test.ts` — the generator emitted `/assets/bad@name-abcdefgh.js` and the decoder then refused the manifest it had just produced; both share one canonical path predicate and the generator self-validates its output. |
@@ -462,12 +462,26 @@ VD-15 목표 runtime을 먼저 구현한다.
`corruptObjects`. 이 report면 그 partition의 bytes는 모두 지워진 것이다.
`chunkSweep`은 없다. 디렉터리는 지웠는데 journal 정리가 실패하면 실패를
반환한다. 같은 purge를 다시 호출하면 이어서 끝난다.
- 한계: lease는 put의 streaming 구간(BEGIN~FINISH)만 막는다. 그 밖에 있던 다른
tab의 같은 partition put은 journal row가 지워져 다음 journal 단계에서
fencing 검사에 걸려 실패할 것으로 본다. 이 경합은 실행으로 확인하지 않았다.
purge가 시작된 뒤 새로 시작한 put의 데이터는 다른 purge처럼 남는다
(point-in-time). purge 전에 그 partition의 쓰기를 멈추는 것이 composition의
몫이다.
- 다른 tab의 put·delete와의 순서: 모든 put·delete는 journal `begin`부터 끝날
때까지 partition lock(Web Lock
`<mutationLockName>:partition:<authorityToken>:<namespaceToken>:<partitionToken>`)을
shared로 쥐고, partition 삭제는 디렉터리·journal 두 단계를 그 lock을
exclusive로 쥔 채 한다. 그래서 진행 중이던 put은 삭제 전에 끝나고 삭제가
그 결과까지 지운다. 삭제가 기다리는 동안 새로 온 put은 삭제 뒤에 돈다
([0929] 05-01, `opfs-byte-store-adapter.ts` `withPartitionLock`).
origin lease는 put의 BEGIN~FINISH만 막으므로 이 lock이 없을 때는, 삭제의
디렉터리 단계가 다른 tab put의 BEGIN보다 먼저 끝나면 그 put이 새 디렉터리에
파일을 쓰고 journal 단계가 그 row를 지워 파일을 치울 주체가 없었다(commit
전이면 manifest·staging receipt·chunk, commit 뒤면 manifest·chunk가 남음).
삭제 전체가 put의 FINISH~commit 사이에 들어가는 경우는 그때도 put이
`CONFLICT`로 실패하고 bytes가 남지 않았다. 막는 테스트:
`tests/unit/opfs-worker-runtime.test.ts` "leaves no partition bytes when an
approved purge meets another tab's put parked before …"(5가지 순서).
- 한계: 삭제는 진행 중인 put·delete를 기다린다. source가 멈춘 put은 put idle
bound(05-07)까지 삭제를 붙잡는다. purge의 `signal`을 abort하면 기다림을
멈추고 `ABORTED`를 반환한다. 삭제가 lock을 요청한 뒤 온 put의 데이터는 다른
purge처럼 남는다(point-in-time). purge 전에 그 partition의 쓰기를 멈추는
것이 composition의 몫이다.
- lock/worker 문제면 OPFS write off → approved capped fallback 또는 online-only
- scope binding mismatch면 affected scope를 read-only로 격리하고 registry/
composition을 forward fix; 다른 token path로 bytes를 이동하거나 추측 복구 금지
+61
View File
@@ -96,3 +96,64 @@ threshold-decision references, and contain only non-negative route-ID samples.
The environment threshold must be a positive integer equal to the approved
decision embedded in the input. Invalid metadata fails as `FAIL_UNVERIFIED`;
the example can never serve as production evidence.
## 초기 청크 수와 HTTP/1.1
리뷰 1101/14.4. 08-08은 초기 JS 바이트를 줄이는 대신 초기 파일 수를 늘렸다
(`vite.config.ts`의 `moduleSideEffects` 주석). HTTP/1.1에서 브라우저는 한
호스트에 연결을 6개까지만 연다. 파일이 많으면 요청이 줄을 서서 왕복이 는다.
그래서 지금 빌드와 작은 초기 청크를 하나로 묶은 빌드를 쟀다(2026-11-03,
커밋 `ec7435c`).
| 빌드 | 초기 JS 파일(entry 포함) | 초기 JS gzip(B) | 첫 화면까지 JS 요청 | Fast 3G 첫 화면 | Fast 4G 첫 화면 |
|---|---:|---:|---:|---:|---:|
| 지금 | 26 | 202,782 | 27 | 5,887 ms | 1,874 ms |
| (가) 08-08이 나눈 초기 primitive 청크 4개(`field`·`button`·`select`·`page-templates`)를 하나로 | 23 | 201,818 | 24 | 5,426 ms | 1,764 ms |
| (나) 묶을 수 있는 초기 청크 14개를 하나로 | 13 | 198,673 | 14 | 4,930 ms | 1,535 ms |
같은 빌드를 HTTP/2로 서빙하면(`node:http2`, 자체 서명 인증서, gzip) 차이가
거의 없다.
| 빌드 | Fast 3G 첫 화면 | Fast 4G 첫 화면 |
|---|---:|---:|
| 지금 | 4,793 ms | 1,444 ms |
| (가) | 4,769 ms | 1,440 ms |
| (나) | 4,708 ms | 1,422 ms |
측정 조건:
- `vite preview`(HTTP/1.1, gzip 응답)로 띄우고 Chromium으로 잰다. 네트워크는
CDP `Network.emulateNetworkConditions`에 DevTools 프리셋 값을 넣었다. Fast
3G는 지연 562.5 ms·내려받기 180,000 B/s, Fast 4G는 165 ms·1,012,500 B/s다.
- 매번 새 browser context에서 캐시 없이 `/`를 연다. 첫 화면은 boot 셸이
사라지고 `#main-content h1[data-route-heading]`가 DOM에 들어온 시각이다
(`performance.now()`).
- 세 빌드를 번갈아 7번씩 재고 중앙값을 적었다. 7번의 범위는 지금 5,866~6,077 ms,
(가) 5,384~5,652 ms, (나) 4,891~5,032 ms다(Fast 3G). loadavg는 HTTP/1.1
측정 때 6~20, HTTP/2 측정 때 3~6이었다. 그래서 두 표끼리는 비교하지 않는다.
- CDP 지연은 요청마다 붙는다. 연결 수립(TCP·TLS) 비용은 따로 재지 않았다.
- (나)에서 묶지 않은 것: entry·`preload-helper`·`boot`, 부트 실패 화면이 쓰는
모듈(`render-boot-failure`·react·react-dom·`jsx-runtime`·`operation-id`·
`diagnostics`·`boot-messages`, 09-03), 15-01의 `feature-declarations`·
`feature-platform`.
판단: 지금은 묶지 않는다.
- HTTP/1.1에서는 묶는 편이 빠르다. Fast 3G에서 (가) 0.46초, (나) 0.96초
빨라지고 초기 JS도 조금 준다.
- 그러나 (가)·(나)는 이 빌드의 청크 안 모듈 목록을 그대로 적어 만들었다.
규칙으로 고르는 방법은 찾지 못했다.
- 모듈 그래프로 boot의 정적 closure를 따라가면 design-system 배럴을 지나
갤러리 전용 primitive까지 잡힌다. 그 primitive가 다시 초기 청크로 간다.
- rolldown의 `$initial` 태그는 entry가 앱을 dynamic import로 읽어서(09-03)
아무것도 잡지 않는다.
- `boot.tsx`를 entry로 더하면 manifest 분류가 lazy 화면까지 초기로 센다
(28개, 216,820 B로 예산 초과).
- 고정 목록은 셸이 쓰는 primitive가 바뀔 때마다 다시 맞춰야 한다. 목록이
낡아도 실패하는 검사가 없다. 08-08이 같은 이유로 `manualChunks` 이름 고정을
버렸다.
- HTTP/2에서는 (나)도 Fast 3G 85 ms, Fast 4G 22 ms 차이다(위 둘째 표).
그래서 템플릿은 HTTP/2 이상으로 서빙한다고 본다. HTTP/1.1로만 서빙해야 하는
제품은 (나)처럼 초기 청크를 묶는 그룹을 `vite.config.ts`에 넣는다. 그 목록은
셸을 바꿀 때마다 위 방법으로 다시 잰다.
@@ -398,12 +398,7 @@ export function createLivePollHandoffCoordinator<Value>(
}
if (quiescence !== "QUIESCED") {
failClosed();
return handoffFailure(
quiescence === "TIMED_OUT"
? "IDLE_TIMEOUT"
: "PROVIDER_UNAVAILABLE",
"RECOVER",
);
return quiescenceFailure(quiescence);
}
quiescing = null;
const checkpoint = await establishCheckpoint(
@@ -497,12 +492,7 @@ export function createLivePollHandoffCoordinator<Value>(
}
if (quiescence !== "QUIESCED") {
failClosed();
return handoffFailure(
quiescence === "TIMED_OUT"
? "IDLE_TIMEOUT"
: "PROVIDER_UNAVAILABLE",
"RECOVER",
);
return quiescenceFailure(quiescence);
}
quiescing = null;
const checkpoint = await establishCheckpoint(
@@ -588,8 +578,10 @@ export function createLivePollHandoffCoordinator<Value>(
return handoffFailure("ABORTED", "RECOVER");
}
if (selected.kind === "TIMEOUT") {
// 1101/04-02. Design 13.1: the checkpoint authority did not answer in
// time, the same kind as when it throws.
candidate.controller.abort();
return handoffFailure("IDLE_TIMEOUT", "RECOVER");
return handoffFailure("PROVIDER_UNAVAILABLE", "RECOVER");
}
if (selected.kind !== "VALUE") {
candidate.controller.abort();
@@ -691,13 +683,12 @@ export function createLivePollHandoffCoordinator<Value>(
quiescing = null;
transitionCandidate = null;
transitioning = false;
if (outcomes.includes("TIMED_OUT")) {
return handoffFailure("IDLE_TIMEOUT", "CLOSE");
}
if (outcomes.includes("TIMER_FAILED")) {
return handoffFailure("PROVIDER_UNAVAILABLE", "CLOSE");
}
return realtimeSuccess(undefined);
// 1101/04-02. A drain past its bound is PROVIDER_UNAVAILABLE/CLOSE, as in
// the stream and reconnect coordinators, never the transport's
// IDLE_TIMEOUT.
return outcomes.every((outcome) => outcome === "QUIESCED")
? realtimeSuccess(undefined)
: handoffFailure("PROVIDER_UNAVAILABLE", "CLOSE");
}
function inspect(): LivePollHandoffInspection {
@@ -871,6 +862,21 @@ function handoffFailure(
: realtimeFailure(kind, operation, retryable);
}
/**
* 1101/04-02. Design 13.1: a prior writer that does not quiesce in time is a
* stalled effect, APPLY_FAILED, never the transport's IDLE_TIMEOUT. Retryable
* as before: the handoff fail-closes and only a new one can run.
*/
function quiescenceFailure(
outcome: Exclude<QuiescenceOutcome, "QUIESCED">,
): Extract<RealtimeResult<never>, { ok: false }> {
return handoffFailure(
outcome === "TIMED_OUT" ? "APPLY_FAILED" : "PROVIDER_UNAVAILABLE",
"RECOVER",
true,
);
}
function remapFailure(
failure: RealtimeFailure,
operation: RealtimeOperation,
@@ -101,6 +101,8 @@ export type OpfsByteStoreDependencies = Readonly<{
* holds an exclusive per-transaction lock from journal `begin` until it
* returns; reconcile only touches rows whose lock it can take at once, so a
* live transaction in any tab is never cleaned up underneath its owner.
* [0929] 05-01. It also holds the partition lock shared over the same span;
* a partition delete takes that lock exclusive (`withPartitionLock`).
*/
lockManager?: Pick<LockManager, "request">;
now?: () => number;
@@ -914,23 +916,30 @@ export function createOpfsByteStoreAdapter(
// under the origin lease and then the partition's journal rows. Both
// are keyed by this partition's tokens alone; no other partition is
// touched. Like that delete, this step is not bounded by the budget.
// Both steps run under the exclusive partition lock, so they first
// wait for every put and delete of the partition in any tab.
const partitionDeleted =
sweeping &&
(corruptObjects > 0 || damaged) &&
!request.signal?.aborted;
if (partitionDeleted) {
const removedFiles = await dependencies.worker.removePartition(
dependencies.scope,
const removed = await withPartitionLock(
"exclusive",
"OBJECT_RECONCILE",
request.signal,
async () => {
const removedFiles = await dependencies.worker.removePartition(
dependencies.scope,
request.signal,
);
if (!removedFiles.ok) return removedFiles;
return await dependencies.journal.removePartition(
dependencies.scope,
);
},
);
if (!removedFiles.ok) {
return rebaseFailure(removedFiles.error, "OBJECT_RECONCILE");
}
const removedRows = await dependencies.journal.removePartition(
dependencies.scope,
);
if (!removedRows.ok) {
return rebaseFailure(removedRows.error, "OBJECT_RECONCILE");
if (!removed.ok) {
return rebaseFailure(removed.error, "OBJECT_RECONCILE");
}
chunkSweep = undefined;
moreObjectsAvailable = false;
@@ -1106,12 +1115,49 @@ export function createOpfsByteStoreAdapter(
// A fresh transaction id is never held; a holder means a duplicate id.
if (!release) return browserDataFailure("CONFLICT", operation);
try {
return await run();
return await withPartitionLock("shared", operation, undefined, run);
} finally {
release();
}
}
/**
* [0929] 05-01. Every put and delete of this partition holds this lock
* shared from journal `begin` until it returns, and the partition delete
* holds it exclusive over both of its steps, so a mutation lies wholly
* before or wholly after that delete. The origin lease covers a put only
* from BEGIN to FINISH: without this, a put begun in another tab wrote its
* files after the directory went, the second step took its journal row, and
* nothing was left to clean those files. Tested by "leaves no partition
* bytes when an approved purge meets another tab's put parked before …".
*/
async function withPartitionLock<Value>(
mode: LockMode,
operation: BrowserDataOperation,
signal: AbortSignal | undefined,
run: () => Promise<BrowserDataResult<Value>>,
): Promise<BrowserDataResult<Value>> {
let granted = false;
try {
return await requestLock(
`${policy.mutationLockName}:partition:${scope.authorityToken}:${scope.namespaceToken}:${scope.partitionToken}`,
{ mode, ...(signal ? { signal } : {}) },
async () => {
granted = true;
return await run();
},
);
} catch (error) {
if (granted) throw error;
return signal?.aborted
? browserDataFailure("ABORTED", operation)
: browserDataFailure("UNAVAILABLE", operation, {
retryable: true,
recovery: "RETRY",
});
}
}
/**
* STO-01. The compensating half of the put saga.
*
+55 -8
View File
@@ -4,7 +4,10 @@ import {
contractRoutePaths,
type BoundedContextModule,
} from "../contexts/bounded-context-module.ts";
import { FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS } from "../contracts/routes.ts";
import {
FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS,
PLATFORM_ROUTE_REGISTRY,
} from "../contracts/routes.ts";
import { assertWithinCardinalityBudget } from "../platform/cardinality/cardinality-budget.ts";
export type DeployableAppModule<Context extends BoundedContextModule = BoundedContextModule> = Readonly<{
@@ -55,6 +58,14 @@ export function defineDeployableAppModule<const Context extends BoundedContextMo
* share a layout, and a root still takes the URLs under it whichever layout
* either context has, so this check spans every layout. A platform route a
* feature took over (its home) is mounted at its own path and is exempt.
*
* 09-03 (1101/14.4). AppShell's platform routes come before every context in
* the router (`app-router.tsx`), so a route a platform route also answers is
* never rendered: the same path, `/` under another id than `APP_HOME`, or any
* route of a `*` root without a layout (NOT_FOUND's splat ties and wins). The
* context is matched where the router mounts it: at its root, or under a
* layout at the route's own path. Two feature routes with one path shape tie
* the same way, and the router renders only the first.
*/
function assertFeatureRoutesReachOwningContext(
contexts: readonly BoundedContextModule[],
@@ -62,18 +73,54 @@ function assertFeatureRoutesReachOwningContext(
const roots = contexts.flatMap((context) =>
context.route ? [{ id: context.id, path: context.route.path }] : [],
);
const featureRouteIds = new Set(
contexts.flatMap((context) =>
context.features.flatMap((feature) =>
contractRoutePaths(feature.contracts).map(([routeId]) => routeId),
),
),
);
const platformRoutes = Object.values(PLATFORM_ROUTE_REGISTRY).flatMap(
({ routeId, path }) =>
FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS.includes(routeId) &&
featureRouteIds.has(routeId)
? []
: [{ id: routeId, path }],
);
const claimed = new Map<string, string>();
for (const context of contexts) {
for (const feature of context.features) {
for (const [routeId, path] of contractRoutePaths(feature.contracts)) {
if (FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS.includes(routeId)) continue;
const reached = matchRoutes(roots, path)?.[0]?.route;
if (reached?.id === context.id) continue;
throw new TypeError(
`Route ${routeId} (${path}) of feature ${feature.id} is not under the route root of its context ${context.id} (${context.route?.path ?? "no route root"}): ` +
(reached
? `context ${reached.id} (${reached.path}) takes that URL.`
: "the router would answer NOT_FOUND."),
);
if (reached?.id !== context.id || !context.route) {
throw new TypeError(
`Route ${routeId} (${path}) of feature ${feature.id} is not under the route root of its context ${context.id} (${context.route?.path ?? "no route root"}): ` +
(reached
? `context ${reached.id} (${reached.path}) takes that URL.`
: "the router would answer NOT_FOUND."),
);
}
const mount = {
id: context.id,
path: context.route.loadLayout ? path : context.route.path,
};
const answered = matchRoutes([...platformRoutes, mount], path)?.[0]?.route;
if (answered !== mount) {
throw new TypeError(
`Route ${routeId} (${path}) of feature ${feature.id} in context ${context.id} is answered by platform route ${answered?.id} (${answered?.path}). ` +
`A feature replaces a platform route only by declaring its id (${FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS.join(", ")}).`,
);
}
// Parameter names do not change how the router ranks a path.
const shape = path.replace(/:[^/]+/g, ":");
const earlier = claimed.get(shape);
if (earlier !== undefined) {
throw new TypeError(
`Route ${routeId} (${path}) of feature ${feature.id} has the same path as route ${earlier}: the router renders only the first.`,
);
}
claimed.set(shape, `${routeId} (${path}) of feature ${feature.id}`);
}
}
}
@@ -1,3 +1,4 @@
import type { ExternalSessionOwner } from "../adapters/auth/index.ts";
import type {
ContractHttpExecutorDependencies,
InstalledHttpOperationExecutor,
@@ -11,6 +12,24 @@ import type { RuntimeConfig } from "./runtime-config-schema.ts";
* profiles and runtime-config keys) and never edits `runtime-adapters.ts`.
*/
/**
* What a product session owner is built from. It is asked first, before
* `http` exists (`http` needs the session), so it gets no capability.
*/
export type ProductSessionOwnerContext = Readonly<{
/** Validated runtime config, product keys included. */
config: RuntimeConfig;
fetcher?: typeof fetch;
}>;
/**
* The session owner when the product owns the session itself, such as a BFF
* whose session is an httpOnly cookie only the backend can read. Asked only
* when `AUTH_MODE` is `external`; it comes before the host's
* `__CA_FRONTEND_AUTH_OWNER__`, and `null` leaves the session to that global.
*/
export type ProductSessionOwner = ExternalSessionOwner | null;
/** Built by the template; a product cannot return or replace them. */
export type TemplatePlatformCapabilityId = "http" | "telemetry";
+8
View File
@@ -1,12 +1,20 @@
import type {
ProductComposition,
ProductCompositionContext,
ProductSessionOwner,
ProductSessionOwnerContext,
} from "./product-composition-contract.ts";
/**
* Product-owned. The template ships it empty and does not change it after a
* copy; the contract is in `product-composition-contract.ts`.
*/
export function composeProductSessionOwner(
context: ProductSessionOwnerContext,
): ProductSessionOwner {
return null;
}
export function composeProduct(context: ProductCompositionContext) {
return {
capabilities: {},
+14 -2
View File
@@ -58,7 +58,10 @@ import {
} from "./load-release-manifest.ts";
import type { RuntimeConfigLoadResult } from "./load-runtime-config.ts";
import { createServerStateGenerationStore } from "./server-state-generation-store.ts";
import { composeProduct } from "./product-composition.ts";
import {
composeProduct,
composeProductSessionOwner,
} from "./product-composition.ts";
import type { ProductComposition } from "./product-composition-contract.ts";
import { createInstalledContractRegistry } from "../features/installed-contract-contributions.ts";
import {
@@ -275,7 +278,16 @@ export async function createRuntimeAdapters(
context.host ?? (globalThis as unknown as Record<string, unknown>);
const config = context.runtime.config;
const mutationIntentFactory = createBrowserMutationIntentFactory();
const externalOwner = externalOwnerFrom(host);
// 09-02. A product that owns the session (a BFF's httpOnly cookie) returns
// its owner before anything resolves the session; the host global is the
// fallback. Demo mode keeps its own session and never asks.
const externalOwner =
config.AUTH_MODE === "demo"
? null
: (composeProductSessionOwner({
config,
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
}) ?? externalOwnerFrom(host));
const authSession =
config.AUTH_MODE === "demo"
? createDemoSessionAdapter()
+25 -2
View File
@@ -1,3 +1,5 @@
import { PRODUCT_ENV_REGISTRY } from "./product-contracts.ts";
/**
* §6.3. Case-insensitive key fragments that can never appear in a client
* configuration document.
@@ -39,7 +41,7 @@ export type EnvironmentDefinition = Readonly<{
defaultValue: unknown;
}>;
export const ENV_REGISTRY = Object.freeze({
export const ENV_REGISTRY = Object.freeze(withProductRows({
// F-6. Required: a staging or production build fails without it
// (scripts/generate-runtime-config.ts). Local and development builds fall
// back to the placeholder, which admission refuses for public targets.
@@ -56,6 +58,11 @@ export const ENV_REGISTRY = Object.freeze({
AUTH_MODE: runtime("public", true, "external"),
CONFIG_SCHEMA_VERSION: runtime("public", true, null),
RELEASE_MANIFEST_URL: runtime("public", true, "/release-manifest.json"),
// F-6. The release identity the build writes into config.json. It must match
// the deployed HTML and release manifest, or boot stops with
// CONFIG_BUILD_MISMATCH (scripts/check-release-admission.ts).
RELEASE_ID: runtime("public-metadata", false, null),
BUILD_ID: runtime("public-metadata", false, null),
// §3.5: overrides may only disable an installed capability, never enable one.
CAPABILITY_OVERRIDES: runtime("public", false, null),
// §3.5: likewise for features — subtractive, keyed by installed feature id.
@@ -64,7 +71,23 @@ export const ENV_REGISTRY = Object.freeze({
// scripts/generate-product-feature-index.ts (09-02). A feature left out here
// is not imported by any registry and never reaches the bundle.
VITE_PRODUCT_FEATURES: build("compile-time", false, null),
});
}));
/**
* 09-02. The product's rows (`product-contracts.ts`) join FE-REG-ENV and are
* checked with it. A product row cannot take a template key's name.
*/
function withProductRows<Rows extends Readonly<Record<string, EnvironmentDefinition>>>(
rows: Rows,
) {
const product: Readonly<Record<string, EnvironmentDefinition>> =
PRODUCT_ENV_REGISTRY;
const reused = Object.keys(product).find((name) => Object.hasOwn(rows, name));
if (reused !== undefined) {
throw new TypeError(`Product env key ${reused} is a template key.`);
}
return { ...rows, ...product };
}
function build(
classification: string,
+9 -1
View File
@@ -1,9 +1,15 @@
/**
* Product-owned. The template ships both values empty and does not change
* Product-owned. The template ships every value empty and does not change
* this file after a copy.
*
* - `PRODUCT_RUNTIME_CONFIG_FIELDS`: zod fields joined to the strict runtime
* config document (`release-artifacts.ts`).
* - `PRODUCT_ENV_REGISTRY`: FE-REG-ENV rows joined to `ENV_REGISTRY`
* (`env.ts`), one per product key, in the template's row shape:
* `KEY: { phase: "runtime", classification: "public", required: false,
* defaultValue: "MOCK" }`, the whole object `as const` so `phase` stays a
* literal. `check:registries` checks them like the template's rows; adding
* rows is additive and needs no baseline change.
* - `PRODUCT_REST_AUTH_PROFILES`: auth profiles installed next to the
* template's (`rest-profiles.ts`); credentials for them come from
* `src/bootstrap/product-composition.ts`.
@@ -11,4 +17,6 @@
export const PRODUCT_RUNTIME_CONFIG_FIELDS = Object.freeze({});
export const PRODUCT_ENV_REGISTRY = Object.freeze({});
export const PRODUCT_REST_AUTH_PROFILES = Object.freeze({});
+8
View File
@@ -97,6 +97,14 @@ export const PLATFORM_ROUTE_REGISTRY = Object.freeze({
}),
});
/**
* 1101/14.3. The `route_id` a render failure reports when no registered route
* names the URL: a context failed to load at an address none of its routes
* has. NOT_FOUND would say the not-found page failed, and a context id is not
* a route id, which telemetry drops.
*/
export const UNREGISTERED_ROUTE_ID = "UNREGISTERED_ROUTE";
/**
* 09-03. Platform routes an installed feature may take over by declaring the
* same route id: a product whose home is a feature screen. The feature's
+24
View File
@@ -37,6 +37,30 @@ const VALIDATION_COPY = Object.freeze({
invalid_type: "form.validation.invalidType",
invalid_format: "form.validation.invalidFormat",
invalid_value: "form.validation.invalidValue",
// 1101/14.4. The paired backend's field codes, every one it can send
// (clean-architecture-backend-template 5786126c,
// ClientSafeValidationDetails.java RULES and INVALID). A code it adds later
// shows form.validation.unknown until it gets a row here.
NOT_NULL: "form.validation.required",
NOT_BLANK: "form.validation.required",
NOT_EMPTY: "form.validation.required",
SIZE: "form.validation.size",
MIN: "form.validation.min",
MAX: "form.validation.max",
POSITIVE: "form.validation.positive",
POSITIVE_OR_ZERO: "form.validation.positiveOrZero",
NEGATIVE: "form.validation.negative",
NEGATIVE_OR_ZERO: "form.validation.negativeOrZero",
PATTERN: "form.validation.invalidFormat",
EMAIL: "form.validation.email",
PAST: "form.validation.past",
PAST_OR_PRESENT: "form.validation.pastOrPresent",
FUTURE: "form.validation.future",
FUTURE_OR_PRESENT: "form.validation.futureOrPresent",
ASSERT_TRUE: "form.validation.invalidValue",
ASSERT_FALSE: "form.validation.invalidValue",
TYPE_MISMATCH: "form.validation.invalidType",
INVALID: "form.validation.invalid",
});
type MessageResolver = (key: ParameterlessMessageKey) => string;
+26
View File
@@ -140,6 +140,19 @@ const PLATFORM_KO_MESSAGES = {
"form.validation.invalidType": "입력 형식을 확인해 주세요.",
"form.validation.invalidFormat": "입력 형식을 확인해 주세요.",
"form.validation.invalidValue": "허용된 값을 선택해 주세요.",
"form.validation.size": "길이나 개수가 허용 범위를 벗어났습니다.",
"form.validation.min": "허용된 최솟값보다 작습니다.",
"form.validation.max": "허용된 최댓값보다 큽니다.",
"form.validation.positive": "0보다 큰 값을 입력해 주세요.",
"form.validation.positiveOrZero": "0 이상의 값을 입력해 주세요.",
"form.validation.negative": "0보다 작은 값을 입력해 주세요.",
"form.validation.negativeOrZero": "0 이하의 값을 입력해 주세요.",
"form.validation.email": "이메일 주소 형식을 확인해 주세요.",
"form.validation.past": "지난 시각을 입력해 주세요.",
"form.validation.pastOrPresent": "앞으로의 시각은 입력할 수 없습니다.",
"form.validation.future": "앞으로의 시각을 입력해 주세요.",
"form.validation.futureOrPresent": "지난 시각은 입력할 수 없습니다.",
"form.validation.invalid": "올바른 값을 입력해 주세요.",
"form.validation.unknown": "입력값을 확인해 주세요.",
"form.validation.retry": "입력값을 다시 확인해 주세요.",
"form.validation.unknownField":
@@ -339,6 +352,19 @@ const PLATFORM_EN_MESSAGES = {
"form.validation.invalidType": "Check the input type.",
"form.validation.invalidFormat": "Check the input format.",
"form.validation.invalidValue": "Choose an allowed value.",
"form.validation.size": "The length or count is outside the allowed range.",
"form.validation.min": "This value is below the allowed minimum.",
"form.validation.max": "This value is above the allowed maximum.",
"form.validation.positive": "Enter a value greater than 0.",
"form.validation.positiveOrZero": "Enter 0 or a greater value.",
"form.validation.negative": "Enter a value less than 0.",
"form.validation.negativeOrZero": "Enter 0 or a smaller value.",
"form.validation.email": "Check the email address format.",
"form.validation.past": "Enter a time in the past.",
"form.validation.pastOrPresent": "A future time is not allowed.",
"form.validation.future": "Enter a time in the future.",
"form.validation.futureOrPresent": "A past time is not allowed.",
"form.validation.invalid": "Enter a valid value.",
"form.validation.unknown": "Check the entered value.",
"form.validation.retry": "Review the entered values.",
"form.validation.unknownField":
+16 -3
View File
@@ -30,6 +30,7 @@ import {
import {
PLATFORM_ROUTE_REGISTRY,
type RouteDefinition,
UNREGISTERED_ROUTE_ID,
} from "../../contracts/routes.ts";
import { TEMPLATE_APP_MODULE } from "../../apps/template-app.ts";
import {
@@ -468,6 +469,18 @@ function registeredRouteIdAt(pathname: string): string | undefined {
return matchRoutes(routes, pathname)?.at(-1)?.route.id;
}
/**
* 1101/14.3. The route a gateway or layout failure is reported under. The
* NOT_FOUND splat matches every URL, but there the context failed, not the
* not-found page.
*/
function failedRouteIdAt(pathname: string): string {
const routeId = registeredRouteIdAt(pathname);
return routeId === undefined || routeId === "NOT_FOUND"
? UNREGISTERED_ROUTE_ID
: routeId;
}
/** The chunk that route recovers, to key chunk recovery on it. */
function routeChunkId(pathname: string): string | undefined {
const routeId = registeredRouteIdAt(pathname);
@@ -567,7 +580,7 @@ function ContextRouteGateway({
buildId={buildId}
onUnrecovered={(incidentId) =>
diagnostics.reportRenderFailure({
routeId: routeModule.id,
routeId: failedRouteIdAt(location.pathname),
buildId,
boundaryName: "route",
incidentId,
@@ -581,7 +594,7 @@ function ContextRouteGateway({
// evaluates, a feature runtime that does not load) escalates to the
// context boundary, which reports it.
withinContext(
registeredRouteIdAt(location.pathname) ?? routeModule.id,
failedRouteIdAt(location.pathname),
<Rethrow error={failure.error} />,
)
);
@@ -639,7 +652,7 @@ function ContextLayout({
buildId={buildId}
onUnrecovered={(incidentId) =>
diagnostics.reportRenderFailure({
routeId: registeredRouteIdAt(pathname) ?? "NOT_FOUND",
routeId: failedRouteIdAt(pathname),
buildId,
boundaryName: "route",
incidentId,
@@ -180,6 +180,87 @@ describe("context route roots under layouts", () => {
});
});
/**
* 09-03 (1101/14.4). AppShell mounts the platform routes ahead of every
* context, so a feature route a platform route also answers is never
* rendered: the router picks the platform route without an error. Only the
* home a feature takes over by its id is allowed.
*/
describe("feature routes and platform routes", () => {
const layout = async () => () => null;
it("rejects a feature route at a platform route's path, naming both", () => {
expect(() =>
app(
context("examples", "examples/*", [
feature("examples-feature", { EXAMPLES_UI_COPY: "/examples/ui" }),
]),
),
).toThrow(/EXAMPLES_UI_COPY.*\/examples\/ui.*examples-feature.*examples.*EXAMPLES_UI/);
});
it("rejects the same path under a layout of its own", () => {
// Layout routes sit after AppShell, so the tie goes to the platform.
expect(() =>
app(
context("examples", "examples/*", [
feature("examples-feature", { EXAMPLES_UI_COPY: "/examples/ui" }),
], layout),
),
).toThrow(/EXAMPLES_UI_COPY.*EXAMPLES_UI/);
});
it("rejects two feature routes with the same path, naming both", () => {
// The router ranks equal paths by order, so the second is never rendered.
// Parameter names do not change the rank.
expect(() =>
app(
context("shop", "shop/*", [
feature("orders", { ORDER_DETAIL: "/shop/items/:orderId" }),
feature("items", { ITEM_DETAIL: "/shop/items/:itemId" }),
]),
),
).toThrow(/ITEM_DETAIL.*\/shop\/items\/:itemId.*items.*ORDER_DETAIL.*orders/);
});
it("accepts a static path next to a parameter at the same depth", () => {
expect(() =>
app(
context("shop", "shop/*", [
feature("items", {
ITEM_NEW: "/shop/items/new",
ITEM_DETAIL: "/shop/items/:itemId",
}),
]),
),
).not.toThrow();
});
it("rejects `/` under another id, which the platform home answers", () => {
expect(() =>
app(context("site", "*", [feature("site", { SITE_HOME: "/" })], layout)),
).toThrow(/SITE_HOME.*\/.*site.*APP_HOME/);
});
it("rejects a `*` root without a layout, which NOT_FOUND answers", () => {
// AppShell's NOT_FOUND splat comes before the context's `*` gateway.
expect(() =>
app(context("site", "*", [feature("site", { EXPLORE: "/explore" })])),
).toThrow(/EXPLORE.*\/explore.*site.*NOT_FOUND/);
});
it("accepts `/` once a feature took over the platform home", () => {
expect(() =>
app(
context("site", "*", [feature("site", { APP_HOME: "/", EXPLORE: "/explore" })], layout),
context("examples", "examples/*", [
feature("examples-feature", { EXAMPLES_REFERENCE: "/examples/reference" }),
]),
),
).not.toThrow();
});
});
/** 09-03. The platform names the routes a feature may take over; one feature may. */
describe("replaceable platform routes", () => {
const contract = (featureId: string, ...routeIds: string[]) => ({
@@ -3,6 +3,7 @@
import { render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { projectTelemetryEvent } from "../../src/contracts/telemetry.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";
@@ -105,10 +106,11 @@ async function expectReportedFailure(
// React logs every caught render error; the assertions below are the point.
vi.spyOn(console, "error").mockImplementation(() => {});
const record = vi.fn();
const emit = vi.fn();
window.history.pushState({}, "", url);
render(
<ApplicationProvider
application={createTestApplication({ diagnostics: { record } })}
application={createTestApplication({ diagnostics: { record }, telemetry: { emit } })}
>
<PreferenceProviders>
<AppRouter buildId="build-a" />
@@ -133,6 +135,9 @@ async function expectReportedFailure(
},
},
]);
// The same failure reaches telemetry, which takes route ids only.
const [telemetry] = emit.mock.calls.filter(([name]) => name === "ui.render.failed");
expect(projectTelemetryEvent(telemetry?.[0], telemetry?.[1])).toMatchObject({ success: true });
}
describe("context gateway failure diagnostics", () => {
@@ -158,9 +163,10 @@ describe("context gateway failure diagnostics", () => {
});
it("reports an unregistered handle refused while the routes load", async () => {
// No feature route owns this URL; the registry's NOT_FOUND splat does.
// 1101/14.3. No registered route names this URL. The context failed, not
// the not-found page, so the report must not say NOT_FOUND.
await expectReportedFailure("/fixture/checked", {
routeId: "NOT_FOUND",
routeId: "UNREGISTERED_ROUTE",
boundary: "route",
});
});
@@ -3,6 +3,7 @@
import { act, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { projectTelemetryEvent } from "../../src/contracts/telemetry.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";
@@ -147,4 +148,38 @@ describe("context route gateway", () => {
await screen.findByText("새 버전으로 한 번만 전환합니다."),
).toBeVisible();
});
// 1101/14.3. Without a new deploy the download stays failed. The report
// names the route at the URL, or UNREGISTERED_ROUTE when no route does
// (not NOT_FOUND, whose page did not fail), and telemetry takes it: it
// accepts route ids only, so the context id was dropped there.
it.each([
["/fixture/items/new", "FIXTURE_ITEM_FORM"],
["/fixture/items/new/unknown", "UNREGISTERED_ROUTE"],
])("reports an unrecovered routes-module download at %s as %s", async (url, routeId) => {
const record = vi.fn();
const emit = vi.fn();
window.history.pushState({}, "", url);
render(
<ApplicationProvider
application={createTestApplication({ diagnostics: { record }, telemetry: { emit } })}
>
<PreferenceProviders>
<AppRouter buildId="build-a" />
</PreferenceProviders>
</ApplicationProvider>,
);
await screen.findByText(/^지원 참조: build-a:[0-9a-f]{8}$/);
expect(record).toHaveBeenCalledWith(
expect.objectContaining({
eventId: "ui.render.failed",
context: expect.objectContaining({ route_id: routeId }),
}),
);
const [telemetry] = emit.mock.calls.filter(([name]) => name === "ui.render.failed");
expect(projectTelemetryEvent(telemetry?.[0], telemetry?.[1])).toMatchObject({
success: true,
});
});
});
+58
View File
@@ -27,7 +27,12 @@ import {
FormField,
useAppForm,
useDirtyNavigationGuard,
validationMessage,
} from "../../src/presentation/forms/index.ts";
import {
formatMessage,
type ParameterlessMessageKey,
} from "../../src/presentation/i18n/index.ts";
/**
* A keyed create that reads the paired backend's Envelope, the shape
@@ -303,6 +308,8 @@ describe("local form facade", () => {
expect(screen.getByRole("textbox", { name: /Note/ })).not.toHaveAttribute(
"aria-invalid",
);
// NOT_BLANK has its own copy, not the "check the value" default.
expect(screen.getByRole("alert")).toHaveTextContent("필수 입력값입니다.");
// A class-level error names no form field.
expect(screen.getByRole("alert")).toHaveTextContent(
"서버가 확인하지 못한 입력 항목",
@@ -545,6 +552,57 @@ describe("local form facade", () => {
});
});
// 1101/14.4. Every code the paired backend can put in a field error's
// details[].code: clean-architecture-backend-template 5786126c,
// ClientSafeValidationDetails.java RULES (18-42) and its INVALID fallback.
// http-contract.md §4 names the shape, not the list. A code missing from the
// form copy table shows the "check the value" default instead.
const BACKEND_FIELD_CODES = [
"NOT_NULL",
"NOT_BLANK",
"NOT_EMPTY",
"SIZE",
"MIN",
"MAX",
"POSITIVE",
"POSITIVE_OR_ZERO",
"NEGATIVE",
"NEGATIVE_OR_ZERO",
"PATTERN",
"EMAIL",
"PAST",
"PAST_OR_PRESENT",
"FUTURE",
"FUTURE_OR_PRESENT",
"ASSERT_TRUE",
"ASSERT_FALSE",
"TYPE_MISMATCH",
"INVALID",
] as const;
describe("paired backend field codes", () => {
it.each(["ko-KR", "en-US"] as const)(
"gives every backend field code its own %s copy",
(locale) => {
const message = (key: ParameterlessMessageKey) =>
formatMessage(locale, key);
const fallback = message("form.validation.unknown");
expect(
BACKEND_FIELD_CODES.filter(
(code) => validationMessage(code, message) === fallback,
),
).toEqual([]);
},
);
it("keeps the default copy for a code it does not know", () => {
expect(validationMessage("SOME_FUTURE_CODE")).toBe(
formatMessage("ko-KR", "form.validation.unknown"),
);
});
});
describe("dirty navigation guard", () => {
it("blocks navigation, restores focus on stay and proceeds explicitly", async () => {
const user = userEvent.setup();
+62
View File
@@ -0,0 +1,62 @@
// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import type { ComponentType } from "react";
import { createMemoryRouter, RouterProvider } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { TEMPLATE_APP_MODULE } from "../../src/apps/template-app.ts";
import { AppShell } from "../../src/presentation/layouts/app-shell.tsx";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
import { SessionProvider } from "../../src/presentation/providers/session-provider.tsx";
import { createTestApplication } from "../helpers/create-test-application.ts";
import { LAYOUT_PRODUCT_CONTEXT_MODULES } from "../helpers/fixture-layout-product.tsx";
/**
* 09-03 (1101/14.4). The router moves focus to `#main-content` on every route
* change, so every layout it mounts has to render a skip link to it and make
* it the one main landmark around the page. The layouts are read from the
* contexts of the installed product and of the fixture product, so a new
* `context-layout.tsx` is checked without being named here.
*/
const contexts = [
...TEMPLATE_APP_MODULE.contexts,
// The fixture's offline layout chunk never arrives, by design.
...LAYOUT_PRODUCT_CONTEXT_MODULES.filter((context) => context.id !== "offline"),
];
const LAYOUTS: readonly (readonly [string, ComponentType])[] = [
["AppShell", AppShell],
...(await Promise.all(
contexts.flatMap((context) => {
const loadLayout = context.route?.loadLayout;
return loadLayout
? [loadLayout().then((Layout) => [`context ${context.id}`, Layout] as const)]
: [];
}),
)),
];
describe("every layout the router mounts", () => {
it.each(LAYOUTS)("%s links its skip link to its one main landmark", async (_name, Layout) => {
const router = createMemoryRouter([
{ path: "/", element: <Layout />, children: [{ index: true, element: <h1>Probe page</h1> }] },
]);
render(
<ApplicationProvider application={createTestApplication()}>
<PreferenceProviders>
<SessionProvider>
<RouterProvider router={router} />
</SessionProvider>
</PreferenceProviders>
</ApplicationProvider>,
);
const page = await screen.findByRole("heading", { name: "Probe page", level: 1 });
const mains = document.querySelectorAll('main, [role="main"]');
expect(mains).toHaveLength(1);
expect(mains[0]).toHaveAttribute("id", "main-content");
expect(mains[0]).toContainElement(page);
expect(document.querySelector('a[href="#main-content"]')).not.toBeNull();
});
});
@@ -0,0 +1,227 @@
// @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/presentation/examples/ui-gallery-page.tsx";
import { LocaleProvider } from "../../src/presentation/i18n/index.ts";
/**
* A starter screen (0929/10-02): `/examples/ui` is template content, so a
* product that replaces it deletes this file 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("이 설명은 필수 정보가 아닙니다.");
});
});
+52 -16
View File
@@ -21,10 +21,9 @@ import { startBuildServer } from "./support/service-worker-builds.ts";
const PLATFORM = ROUTE_REGISTRY.EXAMPLES_PLATFORM;
const UI = ROUTE_REGISTRY.EXAMPLES_UI;
const PAGES = [
"src/presentation/examples/platform-overview-page.tsx",
"src/presentation/examples/ui-gallery-page.tsx",
] as const;
const PLATFORM_PAGE = "src/presentation/examples/platform-overview-page.tsx";
const UI_PAGE = "src/presentation/examples/ui-gallery-page.tsx";
const PAGES = [PLATFORM_PAGE, UI_PAGE] as const;
let builds: FixtureBuilds<"a" | "b"> | undefined;
@@ -60,20 +59,57 @@ async function routeChunk(dist: string, chunkId: string): Promise<string> {
// Each missing page chunk fails its request and the dynamic import. Chromium
// may also log the 404 itself (without its URL), Firefox logs the error
// object React caught, and WebKit logs its own import error without the URL.
// Nothing else is allowed.
// Nothing else is allowed, but for the WebKit warning below.
const MISSING_PAGE = String.raw`/assets/(?:platform-overview|ui-gallery)-page-[\w-]+\.js`;
const MISSING_PAGE_FAILURES = [
String.raw`^requestfailed:GET:${MISSING_PAGE}:`,
String.raw`^console:error:TypeError: Failed to fetch dynamically imported module: http://127\.0\.0\.1:\d+${MISSING_PAGE}$`,
String.raw`^console:error:\[JavaScript Error: "Loading module from “http://127\.0\.0\.1:\d+${MISSING_PAGE}” was blocked`,
String.raw`^console:error:Failed to load resource: the server responded with a status of 404 \(Not Found\)$`,
String.raw`^console:error:JSHandle@object$`,
String.raw`^console:error:TypeError: Importing a module script failed\.$`,
];
/** The chunks Vite preloads with `page`: its static imports in `dist`. */
async function preloadedWith(dist: string, page: string): Promise<string[]> {
const manifest = JSON.parse(
await readFile(path.join(dist, ".vite/manifest.json"), "utf8"),
) as Record<string, { file: string; imports?: string[] }>;
if (!manifest[page]) throw new Error(`${page} is not in ${dist}'s manifest.`);
const files = new Set<string>();
const pending = [...(manifest[page].imports ?? [])];
for (let key = pending.pop(); key !== undefined; key = pending.pop()) {
const entry = manifest[key];
if (!entry || files.has(entry.file)) continue;
files.add(entry.file);
pending.push(...(entry.imports ?? []));
}
return [...files];
}
// WebKit only. Three seconds after a document's load event, WebKit warns once
// for each link-preloaded resource the document has not used yet. Vite
// preloads a page chunk together with the chunks it imports, so a missing page
// leaves the chunks preloaded with it unused: in the A tab those of A's
// platform page (the tab is still on A while recovery reads the release
// manifest), in the B tab those of B's UI page. Whether that check runs before
// the reload, or before the test ends, is timing, so the warnings come and go.
// They are the provoked failure's own effect; only those chunks are allowed.
test.use({
allowedBrowserFailure: new RegExp(
[
String.raw`^requestfailed:GET:${MISSING_PAGE}:`,
String.raw`^console:error:TypeError: Failed to fetch dynamically imported module: http://127\.0\.0\.1:\d+${MISSING_PAGE}$`,
String.raw`^console:error:\[JavaScript Error: "Loading module from “http://127\.0\.0\.1:\d+${MISSING_PAGE}” was blocked`,
String.raw`^console:error:Failed to load resource: the server responded with a status of 404 \(Not Found\)$`,
String.raw`^console:error:JSHandle@object$`,
String.raw`^console:error:TypeError: Importing a module script failed\.$`,
].join("|"),
"u",
),
allowedBrowserFailure: async ({ browserName }, provide) => {
const patterns = [...MISSING_PAGE_FAILURES];
if (browserName === "webkit") {
if (!builds) throw new Error("Fixture builds were not prepared.");
const files = [
...(await preloadedWith(builds.dist.a, PLATFORM_PAGE)),
...(await preloadedWith(builds.dist.b, UI_PAGE)),
].map((file) => file.replaceAll(".", String.raw`\.`));
patterns.push(
String.raw`^console:warning:The resource http://127\.0\.0\.1:\d+/(?:${files.join("|")}) was preloaded using link preload but not used within a few seconds from the window's load event\. Please make sure it wasn't preloaded for nothing\.$`,
);
}
await provide(new RegExp(patterns.join("|"), "u"));
},
});
test("an old tab reloads once into the new build, then stops reloading", async ({
+19
View File
@@ -0,0 +1,19 @@
import { describe, expect, it } from "vitest";
import { ENV_REGISTRY } from "../../src/contracts/env.ts";
import { runtimeConfigV2ArtifactSchema } from "../../src/contracts/release-artifacts.ts";
// 09-02. A key the deployed config.json may carry needs an FE-REG-ENV row, so
// check:registries sees it. A product key added to
// PRODUCT_RUNTIME_CONFIG_FIELDS without a PRODUCT_ENV_REGISTRY row fails here.
describe("FE-REG-ENV coverage", () => {
it("has a runtime row for every V2 runtime config key", () => {
const missing = Object.keys(runtimeConfigV2ArtifactSchema.shape).filter(
(key) =>
!Object.hasOwn(ENV_REGISTRY, key) ||
ENV_REGISTRY[key as keyof typeof ENV_REGISTRY].phase !== "runtime",
);
expect(missing).toEqual([]);
});
});
+161
View File
@@ -2651,8 +2651,169 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh
expect(root.has(partitionPath(scopeP2))).toBe(true);
expect(leases.held).toBe(false);
});
// [0929] 05-01. The origin lease covers a put only from BEGIN to FINISH, and
// the partition delete runs in two steps: the directory under that lease,
// then the journal rows. Another tab's put that had begun before the purge
// was not checked once it left the lease. Each case parks that put at a
// journal step past FINISH, and optionally lets the purge remove the
// directory before the put reaches BEGIN, so the rows go while it is parked.
it.each([
["markFilesReady", false],
["commitPut", false],
["markFilesReady", true],
["commitPut", true],
["complete", true],
] as const)(
"leaves no partition bytes when an approved purge meets another tab's put parked before %s (directory removed before its BEGIN: %s)",
async (parkedStep, directoryFirst) => {
const { root, leases, idb, tab } = sharedRootTabs();
const runtime = () =>
createOpfsWorkerRuntime({
root: root as unknown as FileSystemDirectoryHandle,
crypto: globalThis.crypto,
policy: runtimePolicy,
leaseManager: leases,
dedicatedWorker: true,
supportsSynchronousAccessHandles: false,
});
const journal = createIndexedDbOpfsJournal({
authorityToken: scopeA.authorityToken,
factory: idb.factory,
keyRange: idb.keyRange,
});
const beforeBegin = checkpoint();
const parked = checkpoint();
const rowsPending = checkpoint();
const writerWorker = loopbackGateway(runtime());
const writer = tab("w", {
journal: {
...journal,
[parkedStep]: async (
...input: Parameters<OpfsJournalPort[typeof parkedStep]>
) => {
await parked.pass();
return await (
journal[parkedStep] as (...args: typeof input) => unknown
)(...input);
},
} as OpfsJournalPort,
worker: {
...writerWorker,
async preparePut(input) {
if (directoryFirst) await beforeBegin.pass();
return await writerWorker.preparePut(input);
},
},
});
const purgerWorker = loopbackGateway(runtime());
const purger = tab("p", {
...authority,
worker: {
...purgerWorker,
async removePartition(scope, signal) {
const removed = await purgerWorker.removePartition(scope, signal);
await rowsPending.pass();
return removed;
},
},
});
expect(await putBytes(purger, "object_secret_1", [1, 2, 3])).toMatchObject({ ok: true });
idb.seed("opfs-objects", corruptObjectRow(scopeA, "object_secret_2"));
const settle = (step: Promise<unknown>) =>
Promise.race([
step,
new Promise((resolve) => setTimeout(resolve, 100)),
]);
const put = putBytes(writer, "object_inflight1", [8, 8]);
let purge: ReturnType<typeof purger.maintenance.enforcePolicies>;
if (directoryFirst) {
// The put's journal row is PREPARING; it has written nothing yet.
await beforeBegin.reached;
purge = purger.maintenance.enforcePolicies({ reason: "ACCOUNT_DELETION" });
await settle(rowsPending.reached);
beforeBegin.open();
await parked.reached;
} else {
await parked.reached;
purge = purger.maintenance.enforcePolicies({ reason: "ACCOUNT_DELETION" });
}
rowsPending.open();
await settle(purge);
parked.open();
const [report, written] = await Promise.all([purge, put]);
// The put lies wholly before the partition delete, which then takes it.
expect(written).toMatchObject({ ok: true, value: { generation: 1 } });
expect(report).toMatchObject({
ok: true,
value: { partitionDeleted: true, moreObjectsAvailable: false },
});
expect(filesUnder(root, scopeA)).toEqual([]);
expect(idb.readRaw("opfs-journal", "transaction_w_1")).toBeUndefined();
expect(await openedBytes(writer, "object_inflight1")).toBe("NOT_FOUND");
},
);
it("stops a partition delete that waits on another tab's put when the purge is aborted", async () => {
const { root, idb, tab } = sharedRootTabs();
const purger = tab("p", authority);
expect(await putBytes(purger, "object_secret_1", [1, 2, 3])).toMatchObject({ ok: true });
idb.seed("opfs-objects", corruptObjectRow(scopeA, "object_secret_2"));
const lockName = `${runtimePolicy.mutationLockName}:partition:${scopeA.authorityToken}:${scopeA.namespaceToken}:${scopeA.partitionToken}`;
const putHolding = checkpoint();
// Stands in for a put of this partition in another tab.
const holder = navigator.locks.request(lockName, { mode: "shared" }, () =>
putHolding.pass(),
);
await putHolding.reached;
const controller = new AbortController();
const purge = purger.maintenance.enforcePolicies({
reason: "ACCOUNT_DELETION",
signal: controller.signal,
});
while (
!(await navigator.locks.query()).pending?.some(
(lock) => lock.name === lockName && lock.mode === "exclusive",
)
) {
await new Promise((resolve) => setTimeout(resolve, 1));
}
controller.abort();
expect(await purge).toMatchObject({ ok: false, error: { code: "ABORTED" } });
expect(filesUnder(root, scopeA)).not.toEqual([]);
putHolding.open();
await holder;
});
});
/** A step that parks until opened and says when something reached it. */
function checkpoint(): Readonly<{
reached: Promise<void>;
pass: () => Promise<void>;
open: () => void;
}> {
let reach!: () => void;
const reached = new Promise<void>((resolve) => {
reach = resolve;
});
let open!: () => void;
const opened = new Promise<void>((resolve) => {
open = resolve;
});
return {
reached,
open,
async pass() {
reach();
await opened;
},
};
}
describe("05-07 a put whose source stops lets go of the origin lock", () => {
afterEach(() => {
vi.useRealTimers();
+212 -10
View File
@@ -1,9 +1,13 @@
import { readFile } from "node:fs/promises";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts";
import type {
ProductComposition,
ProductCompositionContext,
ProductSessionOwner,
ProductSessionOwnerContext,
} from "../../src/bootstrap/product-composition-contract.ts";
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
import { validateRuntimeConfig } from "../../src/bootstrap/runtime-config-schema.ts";
@@ -14,11 +18,14 @@ import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts
/**
* 09-02 completion check. The two products' current needs — memento's
* `offsetUpload` and `runtime` capabilities and its BFF cookie XSRF write,
* tech-log's Studio CSRF and its product runtime-config key — expressed by
* filling only the two product-owned files:
* tech-log's Studio CSRF, its product runtime-config key with its FE-REG-ENV
* row, and its BFF session owner installed before boot — expressed by filling
* only the two product-owned files:
*
* - `src/contracts/product-contracts.ts`: product auth profiles and config keys
* - `src/bootstrap/product-composition.ts`: capabilities and credential providers
* - `src/contracts/product-contracts.ts`: product auth profiles, config keys
* and their FE-REG-ENV rows
* - `src/bootstrap/product-composition.ts`: the session owner, capabilities and
* credential providers
*
* Both are replaced below by what a product would write in them. Everything
* else is the template as shipped; only the installed contract set (adds the
@@ -47,6 +54,7 @@ const PRODUCT_NEEDS: readonly FeaturePlatformCapabilityId[] = [
const fixture = vi.hoisted(() => ({
capabilities: undefined as Record<string, unknown> | undefined,
sessionOwnerRequests: 0,
withProfile<T extends { contract: object; frontend: object }>(
contract: T,
operationId: string,
@@ -78,6 +86,15 @@ vi.mock("../../src/contracts/product-contracts.ts", async () => {
PRODUCT_RUNTIME_CONFIG_FIELDS: Object.freeze({
TECH_LOG_STUDIO_SOURCE: z.enum(["MOCK", "HTTP"]).default("MOCK"),
}),
// tech-log added this row to the template's `env.ts`.
PRODUCT_ENV_REGISTRY: Object.freeze({
TECH_LOG_STUDIO_SOURCE: Object.freeze({
phase: "runtime",
classification: "public",
required: false,
defaultValue: "MOCK",
}),
}),
PRODUCT_REST_AUTH_PROFILES: Object.freeze({
MEMENTO_BFF_READ: cookieProfile("MEMENTO_BFF_READ", []),
// The paired backend's default CSRF header (Spring CookieCsrfTokenRepository).
@@ -102,6 +119,47 @@ vi.mock("../../src/bootstrap/product-composition.ts", async () => {
);
const studioSession = fixture.withProfile(detail, ...OPERATIONS.studioSession);
/**
* tech-log's BFF session owner (`bff-session-owner.ts`), which it put on the
* host global from the template's `create-runtime-composition.ts`. The
* session is an httpOnly cookie, so the owner asks the backend.
*/
function composeProductSessionOwner(
context: ProductSessionOwnerContext,
): ProductSessionOwner {
fixture.sessionOwnerRequests += 1;
if (Reflect.get(context.config, "TECH_LOG_STUDIO_SOURCE") !== "HTTP") return null;
const fetcher = context.fetcher ?? fetch;
let state: "recovery-pending" | "authenticated" | "unauthenticated" =
"recovery-pending";
const listeners = new Set<() => void>();
const probe = async () => {
const response = await fetcher(
new URL("api/v1/studio/session", context.config.API_BASE_URL),
{ method: "GET", credentials: "include" },
);
state = response.ok ? "authenticated" : "unauthenticated";
for (const listener of listeners) listener();
return response.ok ? ("restored" as const) : ("no-session" as const);
};
void probe();
return Object.freeze({
readState: () => state,
readSubject: () => (state === "authenticated" ? "studio-user" : null),
subscribe(listener: () => void) {
listeners.add(listener);
return () => listeners.delete(listener);
},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: probe,
notifyUnauthenticated() {
state = "unauthenticated";
},
});
}
function composeProduct(context: ProductCompositionContext) {
// tech-log: one Studio CSRF token per session, fetched through `http` with
// the credential-free bootstrap profile and dropped on 401/403.
@@ -187,7 +245,7 @@ vi.mock("../../src/bootstrap/product-composition.ts", async () => {
},
} satisfies ProductComposition;
}
return { composeProduct };
return { composeProduct, composeProductSessionOwner };
});
vi.mock("../../src/features/installed-contract-contributions.ts", async (importOriginal) => {
@@ -272,16 +330,30 @@ afterEach(() => {
current?.infrastructure.dispose();
current = undefined;
fixture.capabilities = undefined;
fixture.sessionOwnerRequests = 0;
});
async function compose(options: Readonly<{ cookie?: string; studioStatus?: number }> = {}) {
async function compose(
options: Readonly<{
cookie?: string;
studioStatus?: number;
authMode?: "demo" | "external";
studioSource?: "MOCK" | "HTTP";
studioSessionStatus?: number;
host?: Record<string, unknown>;
}> = {},
) {
const validated = validateRuntimeConfig({
...CONFIG_DOCUMENT,
TECH_LOG_STUDIO_SOURCE: "HTTP",
AUTH_MODE: options.authMode ?? CONFIG_DOCUMENT.AUTH_MODE,
TECH_LOG_STUDIO_SOURCE: options.studioSource ?? "HTTP",
});
if (!validated.success) throw new Error(JSON.stringify(validated.issues));
const fetcher = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => {
const url = String(input);
if (url.endsWith("/api/v1/studio/session")) {
return new Response(null, { status: options.studioSessionStatus ?? 200 });
}
if (url.endsWith("/api/test-entities/session")) {
return Response.json({ id: "studio-csrf", name: "session" });
}
@@ -306,7 +378,10 @@ async function compose(options: Readonly<{ cookie?: string; studioStatus?: numbe
validationDurationMs: 0,
},
release,
host: options.cookie === undefined ? {} : { document: { cookie: options.cookie } },
host: {
...options.host,
...(options.cookie === undefined ? {} : { document: { cookie: options.cookie } }),
},
fetcher: fetcher as unknown as typeof fetch,
});
const capabilities = fixture.capabilities;
@@ -436,8 +511,129 @@ describe("09-02 product needs through the product-owned files only", () => {
runtimeConfigV2ArtifactSchema.parse({ ...CONFIG_DOCUMENT, TECH_LOG_STUDIO_SOURCE: "HTTP" }),
).toMatchObject({ TECH_LOG_STUDIO_SOURCE: "HTTP" });
});
it("tech-log: the config key's FE-REG-ENV row joins ENV_REGISTRY", async () => {
// check:registries and vite.config.ts read this same object.
const { ENV_REGISTRY } = await import("../../src/contracts/env.ts");
expect(ENV_REGISTRY).toMatchObject({
APP_ENV: { phase: "runtime", classification: "public", required: true },
TECH_LOG_STUDIO_SOURCE: {
phase: "runtime",
classification: "public",
required: false,
defaultValue: "MOCK",
},
});
});
it("tech-log: the BFF session owner is the session from boot, in external mode only", async () => {
const session = async (options: Parameters<typeof compose>[0]) => {
const { fetcher } = await compose(options);
const port = current?.outputPorts.session;
if (!port) throw new Error("not composed");
await vi.waitFor(() => expect(port.getState()).not.toBe("recovery-pending"));
const state = port.getState();
current?.infrastructure.dispose();
current = undefined;
return { state, fetcher };
};
const signedIn = await session({ authMode: "external" });
expect(signedIn.state).toBe("authenticated");
expect(sent(signedIn.fetcher, 0)).toMatchObject({
url: "http://localhost:8080/api/v1/studio/session",
credentials: "include",
});
await expect(
session({ authMode: "external", studioSessionStatus: 401 }),
).resolves.toMatchObject({ state: "unauthenticated" });
// The product's owner comes before the host's global owner.
await expect(
session({ authMode: "external", host: { __CA_FRONTEND_AUTH_OWNER__: hostOwner() } }),
).resolves.toMatchObject({ state: "authenticated" });
// The product returns none: the host's owner, or no owner, as before.
await expect(
session({
authMode: "external",
studioSource: "MOCK",
host: { __CA_FRONTEND_AUTH_OWNER__: hostOwner() },
}),
).resolves.toMatchObject({ state: "unauthenticated" });
await expect(
session({ authMode: "external", studioSource: "MOCK" }),
).resolves.toMatchObject({ state: "integration-failed" });
expect(fixture.sessionOwnerRequests).toBe(5);
// Demo mode keeps its own session and does not ask the product.
fixture.sessionOwnerRequests = 0;
await expect(session({})).resolves.toMatchObject({ state: "unauthenticated" });
expect(fixture.sessionOwnerRequests).toBe(0);
});
});
/** A host-published owner that is signed out. */
function hostOwner() {
return {
readState: () => "unauthenticated",
readSubject: () => null,
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "no-session",
notifyUnauthenticated() {},
};
}
/**
* The template files tech-log edited (af3d8e6 sync) for the needs above. They
* stay template-owned; this fixture reaches the same result without them.
*/
const TECH_LOG_EDITED_TEMPLATE_FILES = [
"src/contracts/env.ts",
"src/bootstrap/create-runtime-composition.ts",
"src/bootstrap/runtime-config-schema.ts",
"src/bootstrap/runtime-adapters.ts",
];
/** Stand in for an installed feature and observe its capabilities; not product code. */
const INSTALLED_FEATURE_SEAMS = [
"src/features/installed-contract-contributions.ts",
"src/features/installed-feature-adapters.ts",
];
describe("09-02 the fixture replaces product-owned files only", () => {
const source = (file: string) => readFile(new URL(`../../${file}`, import.meta.url), "utf8");
it("mocks the two product-owned files and none tech-log edited", async () => {
const mocked = [
...(await source("tests/unit/product-composition-fixture.test.ts")).matchAll(
/vi\.(?:doMock|mock)\(\s*"\.\.\/\.\.\/(src\/[^"]+)"/g,
),
].flatMap((match) => (match[1] === undefined ? [] : [match[1]]));
const product = [...new Set(mocked)]
.filter((file) => !INSTALLED_FEATURE_SEAMS.includes(file))
.sort();
expect(product).toEqual([
"src/bootstrap/product-composition.ts",
"src/contracts/product-contracts.ts",
]);
for (const file of product) {
expect(await source(file), file).toContain("Product-owned.");
}
for (const file of TECH_LOG_EDITED_TEMPLATE_FILES) {
expect(await source(file), file).not.toContain("Product-owned.");
}
});
});
const EMPTY_PRODUCT = {
PRODUCT_RUNTIME_CONFIG_FIELDS: {},
PRODUCT_REST_AUTH_PROFILES: {},
PRODUCT_ENV_REGISTRY: {},
};
describe("09-02 a product row cannot take a template name", () => {
afterEach(() => {
vi.doUnmock("../../src/contracts/product-contracts.ts");
@@ -448,15 +644,21 @@ describe("09-02 a product row cannot take a template name", () => {
{
registry: "auth profiles",
load: () => import("../../src/contracts/rest-profiles.ts"),
product: { PRODUCT_RUNTIME_CONFIG_FIELDS: {}, PRODUCT_REST_AUTH_PROFILES: { ANONYMOUS: {} } },
product: { ...EMPTY_PRODUCT, PRODUCT_REST_AUTH_PROFILES: { ANONYMOUS: {} } },
error: "Product REST auth profile ANONYMOUS reuses a template profile id.",
},
{
registry: "runtime config",
load: () => import("../../src/contracts/release-artifacts.ts"),
product: { PRODUCT_RUNTIME_CONFIG_FIELDS: { APP_ENV: {} }, PRODUCT_REST_AUTH_PROFILES: {} },
product: { ...EMPTY_PRODUCT, PRODUCT_RUNTIME_CONFIG_FIELDS: { APP_ENV: {} } },
error: "Product runtime config key APP_ENV is a template key.",
},
{
registry: "FE-REG-ENV",
load: () => import("../../src/contracts/env.ts"),
product: { ...EMPTY_PRODUCT, PRODUCT_ENV_REGISTRY: { APP_ENV: {} } },
error: "Product env key APP_ENV is a template key.",
},
])("refuses to load ($registry)", async ({ load, product, error }) => {
vi.resetModules();
vi.doMock("../../src/contracts/product-contracts.ts", () => product);
@@ -266,7 +266,7 @@ describe("live/poll authoritative writer handoff", () => {
harness.clock.advance(100);
await expect(closing).resolves.toMatchObject({
ok: false,
error: { kind: "IDLE_TIMEOUT", operation: "CLOSE" },
error: { kind: "PROVIDER_UNAVAILABLE", operation: "CLOSE", retryable: true },
});
release?.(realtimeSuccess(undefined));
@@ -356,9 +356,11 @@ describe("live/poll authoritative writer handoff", () => {
expect(harness.clock.sleepers).toHaveLength(1);
harness.clock.advance(100);
// 1101/04-02. The prior writer's effect stalled (design 13.1), not the
// transport's IDLE_TIMEOUT.
await expect(transition).resolves.toMatchObject({
ok: false,
error: { kind: "IDLE_TIMEOUT", operation: "RECOVER" },
error: { kind: "APPLY_FAILED", operation: "RECOVER", retryable: true },
});
expect(harness.recover).not.toHaveBeenCalled();
expect(harness.coordinator.inspect()).toMatchObject({
@@ -367,6 +369,32 @@ describe("live/poll authoritative writer handoff", () => {
});
});
it("fails a probe activation closed when poll cannot quiesce before the bound", async () => {
const harness = createHarness({
initial: "POLL",
apply: vi.fn(async ({ writer }) =>
writer === "POLL"
? await new Promise<RealtimeResult<void>>(() => {})
: realtimeSuccess(undefined),
),
});
void harness.coordinator.currentWriter()!.write("hung-poll", 4);
const live = expectProbe(harness.coordinator.beginLiveProbe());
await flush();
const activation = live.activate();
await flush();
expect(harness.clock.sleepers).toHaveLength(1);
harness.clock.advance(100);
await expect(activation).resolves.toMatchObject({
ok: false,
error: { kind: "APPLY_FAILED", operation: "RECOVER", retryable: true },
});
expect(harness.recover).not.toHaveBeenCalled();
expect(harness.coordinator.inspect().state).toBe("CLOSED");
});
it("keeps poll authoritative while probing, then recovers and drains live values serially", async () => {
const firstLive = deferred<RealtimeResult<void>>();
const order: string[] = [];
@@ -550,9 +578,10 @@ describe("live/poll authoritative writer handoff", () => {
expect(harness.clock.sleepers).toHaveLength(1);
harness.clock.advance(100);
// 1101/04-02. The checkpoint authority did not answer in time.
await expect(transition).resolves.toMatchObject({
ok: false,
error: { kind: "IDLE_TIMEOUT", operation: "RECOVER" },
error: { kind: "PROVIDER_UNAVAILABLE", operation: "RECOVER", retryable: true },
});
expect(checkpointIsCurrent?.()).toBe(false);
expect(harness.coordinator.inspect().state).toBe("CLOSED");
@@ -579,7 +608,7 @@ describe("live/poll authoritative writer handoff", () => {
harness.clock.advance(100);
await expect(closing).resolves.toMatchObject({
ok: false,
error: { kind: "IDLE_TIMEOUT", operation: "CLOSE" },
error: { kind: "PROVIDER_UNAVAILABLE", operation: "CLOSE", retryable: true },
});
// RT-RR-03. A second close re-runs rather than replaying a cached verdict.
// The writer is still hung, so it still reports a timeout.
@@ -588,7 +617,7 @@ describe("live/poll authoritative writer handoff", () => {
harness.clock.advance(100);
await expect(second).resolves.toMatchObject({
ok: false,
error: { kind: "IDLE_TIMEOUT", operation: "CLOSE" },
error: { kind: "PROVIDER_UNAVAILABLE", operation: "CLOSE", retryable: true },
});
});
@@ -616,7 +645,7 @@ describe("live/poll authoritative writer handoff", () => {
harness.clock.advance(100);
await expect(first).resolves.toMatchObject({
ok: false,
error: { kind: "IDLE_TIMEOUT", operation: "CLOSE" },
error: { kind: "PROVIDER_UNAVAILABLE", operation: "CLOSE", retryable: true },
});
// The writer finishes after the first close gave up.
@@ -654,7 +683,7 @@ describe("live/poll authoritative writer handoff", () => {
harness.clock.advance(100);
await expect(closing).resolves.toMatchObject({
ok: false,
error: { kind: "IDLE_TIMEOUT", operation: "CLOSE" },
error: { kind: "PROVIDER_UNAVAILABLE", operation: "CLOSE", retryable: true },
});
harness.clock.advance(100);
@@ -77,6 +77,7 @@ vi.mock("../../src/features/installed-feature-adapters.ts", async (importOrigina
/** The product-owned file, filled the way a product fills it. */
vi.mock("../../src/bootstrap/product-composition.ts", () => ({
composeProductSessionOwner: () => null,
composeProduct: () => ({
capabilities: {},
credentialProviders: fixture.providers,
+4 -3
View File
@@ -161,9 +161,10 @@ export default defineConfig(({ mode }) => {
*
* Trade: at 08-08 the initial JavaScript fell by 2,718 gzip bytes
* and the initial chunks rose from 16 to 25. The entry preloads them
* in parallel, so over HTTP/2 they add no round trip. Revisit when
* the app is served over HTTP/1.1, where every chunk costs a
* connection slot.
* in parallel, so over HTTP/2 they add no round trip. Over HTTP/1.1
* they queue for six connections; 1101/14.4 measured that cost and
* why the chunks stay split ("초기 청크 수와 HTTP/1.1" in
* docs/operations/performance-evidence.md).
*/
treeshake: {
moduleSideEffects: [