Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5173b6c8d6 | ||
|
|
2fa0baa577 | ||
|
|
668bf05b48 | ||
|
|
b8c0444217 |
+12
-1
@@ -82,7 +82,10 @@
|
|||||||
{ "script": "check:types:fixture:async-overlay", "expect": "fail" },
|
{ "script": "check:types:fixture:async-overlay", "expect": "fail" },
|
||||||
{ "script": "check:types:fixture:route-runtime", "expect": "fail" },
|
{ "script": "check:types:fixture:route-runtime", "expect": "fail" },
|
||||||
{ "script": "check:types:fixture:page-action", "expect": "fail" },
|
{ "script": "check:types:fixture:page-action", "expect": "fail" },
|
||||||
{ "script": "check:types:fixture:icon-button", "expect": "fail" }
|
{ "script": "check:types:fixture:icon-button", "expect": "fail" },
|
||||||
|
{ "script": "check:types:fixture:i18n-key", "expect": "fail" },
|
||||||
|
{ "script": "check:types:fixture:i18n-params", "expect": "fail" },
|
||||||
|
{ "script": "check:types:fixture:diagnostics", "expect": "fail" }
|
||||||
],
|
],
|
||||||
"logPath": "artifacts/quality/check-types.txt",
|
"logPath": "artifacts/quality/check-types.txt",
|
||||||
"evidence": ["artifacts/quality/check-types.txt"],
|
"evidence": ["artifacts/quality/check-types.txt"],
|
||||||
@@ -154,6 +157,10 @@
|
|||||||
{ "script": "check:architecture", "expect": "pass" },
|
{ "script": "check:architecture", "expect": "pass" },
|
||||||
{ "script": "check:design-system", "expect": "pass" },
|
{ "script": "check:design-system", "expect": "pass" },
|
||||||
{ "script": "check:design-system:fixture", "expect": "fail" },
|
{ "script": "check:design-system:fixture", "expect": "fail" },
|
||||||
|
{ "script": "check:i18n", "expect": "pass" },
|
||||||
|
{ "script": "check:i18n:fixture", "expect": "fail" },
|
||||||
|
{ "script": "check:diagnostics", "expect": "pass" },
|
||||||
|
{ "script": "check:diagnostics:fixture", "expect": "fail" },
|
||||||
{ "script": "check:registries", "expect": "pass" },
|
{ "script": "check:registries", "expect": "pass" },
|
||||||
{ "script": "check:registries:fixture", "expect": "fail" },
|
{ "script": "check:registries:fixture", "expect": "fail" },
|
||||||
{ "script": "check:routes:fixture", "expect": "fail" }
|
{ "script": "check:routes:fixture", "expect": "fail" }
|
||||||
@@ -163,6 +170,10 @@
|
|||||||
"artifacts/quality/dependency-report.json",
|
"artifacts/quality/dependency-report.json",
|
||||||
"artifacts/quality/design-system.json",
|
"artifacts/quality/design-system.json",
|
||||||
"artifacts/quality/design-system-fixture.json",
|
"artifacts/quality/design-system-fixture.json",
|
||||||
|
"artifacts/quality/i18n.json",
|
||||||
|
"artifacts/quality/i18n-fixture.json",
|
||||||
|
"artifacts/quality/diagnostics.json",
|
||||||
|
"artifacts/quality/diagnostics-fixture.json",
|
||||||
"artifacts/quality/registries.json",
|
"artifacts/quality/registries.json",
|
||||||
"artifacts/quality/registry-fixture.json",
|
"artifacts/quality/registry-fixture.json",
|
||||||
"artifacts/quality/route-registry-fixture.json"
|
"artifacts/quality/route-registry-fixture.json"
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
# VD-06: Intl과 typed local message catalog
|
||||||
|
|
||||||
|
- 상태: Accepted
|
||||||
|
- 결정일: 2026-07-26
|
||||||
|
- 적용 브랜치: `feature-frontend-i18n-message-formatting-contract`
|
||||||
|
- 재검토: 승인 locale·복수형 문법·번역 추출 workflow가 local catalog 범위를 넘을 때
|
||||||
|
|
||||||
|
## 배경
|
||||||
|
|
||||||
|
공통 셸, route surface, async/form 상태와 디자인 시스템 기본 문구가 JSX와
|
||||||
|
JavaScript에 분산돼 있었다. 날짜는 일부 application mapper에서 고정 locale로
|
||||||
|
가공되어 presentation이 locale을 바꿀 수 없었고, direction·누락 key·보간 실패
|
||||||
|
정책도 없었다. 반면 현재 skeleton에는 번역 관리 서비스, 실제 번역 승인 절차,
|
||||||
|
복잡한 ICU 문법이라는 제품 요구가 아직 없다. 이 단계에서 i18n vendor를 기본
|
||||||
|
번들에 넣으면 소비 프로젝트가 제거하거나 다시 감싸야 할 의존성만 늘어난다.
|
||||||
|
|
||||||
|
## 결정
|
||||||
|
|
||||||
|
1. 표준 `Intl.DateTimeFormat`, `NumberFormat`, `RelativeTimeFormat`,
|
||||||
|
`ListFormat`, `PluralRules`와 typed local catalog를 기본 엔진으로 사용한다.
|
||||||
|
2. `MessageKey`는 한국어 canonical catalog에서 도출하며 영어와 RTL smoke
|
||||||
|
catalog는 `satisfies Record<MessageKey, string>`으로 compile-time parity를
|
||||||
|
강제한다.
|
||||||
|
3. 보간이 필요한 key는 `MessageParameters`에 key별 parameter object를
|
||||||
|
선언한다. 잘못된 key, 누락·초과 parameter는 TypeScript negative fixture가
|
||||||
|
거절한다.
|
||||||
|
4. 기본 locale은 `ko-KR`, fallback locale도 `ko-KR`이다. 알려지지 않은 locale은
|
||||||
|
language fallback 후 `ko-KR`로 정규화한다. 알려지지 않은 key와 누락 보간은
|
||||||
|
raw key나 외부 값을 출력하지 않고 안전한 공통 fallback을 반환한다.
|
||||||
|
5. `en-XA`는 영어 문구를 확장·accent 처리하는 pseudo locale이고 `ar-EG`는
|
||||||
|
RTL 동작 smoke locale이다. 이 두 locale은 실제 제품 번역 완료를 의미하지
|
||||||
|
않는다.
|
||||||
|
6. 날짜 formatter의 기본 timezone은 테스트와 SSR/브라우저 결과가 흔들리지
|
||||||
|
않도록 `UTC`다. 제품 timezone이 필요하면 호출자가 명시한다. invalid
|
||||||
|
date/number/timezone은 `—`를 반환하고 throw하지 않는다.
|
||||||
|
7. locale state는 React inbound concern이다. `LocaleProvider`가 copy,
|
||||||
|
formatter와 `<html lang/dir>`을 제공하며 application/domain은 미리 번역된
|
||||||
|
문자열 대신 의미 값과 timestamp를 반환한다.
|
||||||
|
8. backend `message`, raw HTML, stack과 내부 key를 catalog 입력으로 신뢰하지
|
||||||
|
않는다. transport/application failure kind를 등록된 사용자 message key로
|
||||||
|
매핑한 뒤 presentation이 해석한다.
|
||||||
|
9. key rename은 즉시 제거하지 않고 `MESSAGE_KEY_ALIASES`에 compatibility alias를
|
||||||
|
둔다. alias는 새 호출의 타입에 포함하지 않아 신규 코드는 canonical key만
|
||||||
|
사용한다.
|
||||||
|
10. extraction, ICU rich message, 번역 SaaS 또는 framework adapter가 필요해지면
|
||||||
|
`presentation/i18n` public API 뒤에서 교체한다. vendor type은 feature와
|
||||||
|
design-system public prop으로 노출하지 않는다.
|
||||||
|
|
||||||
|
## 실행 경계
|
||||||
|
|
||||||
|
```text
|
||||||
|
route/form/failure 의미 값
|
||||||
|
-> presentation message key
|
||||||
|
-> LocaleProvider
|
||||||
|
-> typed catalog / Intl formatter
|
||||||
|
-> text node와 accessible name
|
||||||
|
```
|
||||||
|
|
||||||
|
- canonical catalog: `src/presentation/i18n/catalog.ts`
|
||||||
|
- feature contribution: `src/features/*/contracts/*-message-catalog.js`를
|
||||||
|
`src/features/installed-feature-messages.js`에서 조립
|
||||||
|
- key/보간/fallback/alias: `message-contract.ts`
|
||||||
|
- locale-safe value formatting: `formatters.ts`
|
||||||
|
- React composition과 document metadata: `locale-provider.tsx`
|
||||||
|
- public entry: `src/presentation/i18n/index.ts`
|
||||||
|
|
||||||
|
## 검증
|
||||||
|
|
||||||
|
- `check:i18n`은 catalog key와 placeholder parity, common UI의 한국어 literal,
|
||||||
|
backend message JSX 렌더링과 raw HTML 사용을 검사한다.
|
||||||
|
- `check:i18n:fixture`는 세 금지 사례를 실제로 거절해야 성공으로 인정된다.
|
||||||
|
- type negative fixture는 unknown key와 잘못된 parameter shape를 거절한다.
|
||||||
|
- unit test는 fallback, alias, pseudo 확장, direction과 timezone/number/relative/
|
||||||
|
list/plural/select의 결정성을 검증한다.
|
||||||
|
- component test는 document `lang/dir`, RTL Tabs와 direction-aware pagination,
|
||||||
|
Drawer semantics를 검증한다.
|
||||||
|
- Playwright는 320px pseudo reflow와 RTL compact shell/Drawer/focus restore를
|
||||||
|
Chromium, Firefox, WebKit project에서 실행한다.
|
||||||
|
|
||||||
|
## 한계와 재검토 조건
|
||||||
|
|
||||||
|
현재 catalog는 실제 번역 승인, ICU rich text, locale별 plural 문장 전체 조합,
|
||||||
|
메시지 추출/번역 메모리와 서버 locale negotiation을 제공하지 않는다. 다음 중
|
||||||
|
하나가 확인되면 별도 ADR로 엔진을 재평가한다.
|
||||||
|
|
||||||
|
- 세 개 이상의 실제 승인 locale과 번역 담당 workflow
|
||||||
|
- 복수형·성별·select가 한 문장 안에서 중첩되는 제품 copy
|
||||||
|
- server/client extraction, namespace lazy-loading 또는 번역 SaaS 연동
|
||||||
|
- SSR locale negotiation과 hydration 일치가 필요한 rendering mode
|
||||||
|
|
||||||
|
## Rollback
|
||||||
|
|
||||||
|
`ko-KR` catalog가 기존 기본 문구를 보존하므로 provider를 고정 locale adapter로
|
||||||
|
되돌려도 기본 UX를 유지한다. formatter/vendor 교체 시 public `message`,
|
||||||
|
`date`, `number`, `relativeTime`, `list`, `plural`, `select` 계약과 negative
|
||||||
|
fixture는 유지한다. alias는 migration window 종료 근거 없이 제거하지 않는다.
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# VD-07: Diagnostics와 telemetry exporter 경계
|
||||||
|
|
||||||
|
- 상태: Accepted
|
||||||
|
- 결정일: 2026-07-26
|
||||||
|
- 적용 브랜치: `feature-frontend-diagnostics-telemetry-runtime`
|
||||||
|
- 재검토: 실제 운영 sink, consent가 필요한 analytics 또는 분산 tracing provider가
|
||||||
|
선정될 때
|
||||||
|
|
||||||
|
## 배경
|
||||||
|
|
||||||
|
기존 telemetry registry와 best-effort HTTP queue는 있었지만 운영 진단 record와
|
||||||
|
semantic event의 책임이 하나의 telemetry port에 섞여 있었다. boot, HTTP,
|
||||||
|
cache, storage, route와 release failure의 선언도 실제 production producer와
|
||||||
|
완전히 연결되지 않았다. 이 상태에서는 retry attempt마다 같은 사건을 발행하거나
|
||||||
|
raw URL, query, request body와 오류 객체가 queue에 들어갈 위험이 있다.
|
||||||
|
|
||||||
|
반면 skeleton 단계에는 실제 관측 vendor, endpoint의 운영 보안 정책, analytics
|
||||||
|
consent와 보존 기간이 결정되지 않았다. 특정 SDK를 기본 번들에 설치하는 것은
|
||||||
|
vendor 결정 전에는 안전한 기본값이 아니다.
|
||||||
|
|
||||||
|
## 결정
|
||||||
|
|
||||||
|
1. level 기반 운영 진단은 `DiagnosticsPort`, registry 기반 semantic event는
|
||||||
|
`TelemetryPort`로 분리한다. application은 두 port의 concrete adapter나
|
||||||
|
exporter SDK를 알지 못한다.
|
||||||
|
2. diagnostics의 level, event ID와 context key는 닫힌 registry/allowlist다.
|
||||||
|
telemetry도 event별 required/optional attribute와 value policy를 적용한다.
|
||||||
|
등록되지 않은 event·context·고카디널리티 값은 전송하지 않는다.
|
||||||
|
3. 기본 diagnostics adapter는 bounded in-memory evidence이고 telemetry는
|
||||||
|
설정이 없으면 true no-op이다. endpoint가 있을 때만 bounded oldest-drop
|
||||||
|
queue와 best-effort HTTP sink를 사용한다.
|
||||||
|
4. raw path/URL/query/body/response/storage value, credential, cookie, email,
|
||||||
|
stack과 오류 객체 전체는 context에 넣지 않는다. route ID, operation ID,
|
||||||
|
correlation ID, release ID, error kind, status/attempt/duration bucket만
|
||||||
|
허용한다.
|
||||||
|
5. HTTP logical execution은 success, retry recovery, terminal failure 또는
|
||||||
|
abort마다 `http.request.completed` diagnostics를 정확히 한 번 남긴다.
|
||||||
|
`api.request.failed` telemetry는 retry가 끝난 terminal non-abort failure에만
|
||||||
|
정확히 한 번 발행한다.
|
||||||
|
6. `app.boot.failed`, `ui.render.failed`, `release.mismatch.detected`,
|
||||||
|
`telemetry.delivery.dropped`를 production path에 연결한다. cache와 storage
|
||||||
|
실패는 diagnostics로 기록하되 raw key/value를 기록하지 않는다.
|
||||||
|
7. queue full, invalid event/context, serialization과 sink failure는 제한된
|
||||||
|
reason bucket으로 집계한다. drop observer의 failure는 다시 telemetry를
|
||||||
|
발행하지 않는 nonrecursive 경계다.
|
||||||
|
8. diagnostics와 telemetry failure는 제품 흐름, HTTP 결과, route transition,
|
||||||
|
storage/cache fallback과 React error surface를 바꾸지 않는다.
|
||||||
|
9. mount 전 bootstrap failure는 안전한 build/config/error kind만 별도 evidence로
|
||||||
|
만들며 untrusted error message, stack과 support 입력을 serialize하지 않는다.
|
||||||
|
10. 실제 error reporter, RUM, analytics나 tracing SDK는 같은 port 뒤의 외부
|
||||||
|
adapter로만 추가한다. SDK type과 event API를 application/feature/presentation
|
||||||
|
public contract에 노출하지 않는다.
|
||||||
|
|
||||||
|
## 실행 경계
|
||||||
|
|
||||||
|
```text
|
||||||
|
route/application/HTTP/cache/storage/bootstrap
|
||||||
|
-> typed DiagnosticsPort 또는 TelemetryPort
|
||||||
|
-> registry + allowlist + value policy
|
||||||
|
-> bounded memory/no-op 또는 best-effort HTTP adapter
|
||||||
|
-> 프로젝트가 선택한 외부 sink
|
||||||
|
```
|
||||||
|
|
||||||
|
- diagnostics contract: `src/contracts/diagnostics.ts`
|
||||||
|
- telemetry contract: `src/contracts/telemetry.js`
|
||||||
|
- application ports: `src/application/ports/diagnostics-port.ts`,
|
||||||
|
`telemetry-port.ts`
|
||||||
|
- bounded diagnostics: `src/adapters/diagnostics/bounded-diagnostics.ts`
|
||||||
|
- best-effort telemetry: `src/adapters/telemetry/best-effort-telemetry.js`
|
||||||
|
- composition: `src/bootstrap/runtime-adapters.js`
|
||||||
|
|
||||||
|
## 검증
|
||||||
|
|
||||||
|
- `check:diagnostics`는 모든 registry event에 production producer가 있는지와
|
||||||
|
source의 direct console/sensitive context 우회를 검사한다.
|
||||||
|
- negative source fixture는 direct console, unknown event와 raw context를 실제로
|
||||||
|
거절하며 TypeScript fixture는 잘못된 level/event ID를 거절한다.
|
||||||
|
- unit test는 allowlist, hostile/circular error, bounded diagnostics, no-op,
|
||||||
|
queue full, sink/observer failure와 pre-mount boot evidence를 검증한다.
|
||||||
|
- HTTP integration은 success, retry recovery, terminal failure와 abort의 producer
|
||||||
|
횟수, route/operation/correlation context와 요청 값 비노출을 검증한다.
|
||||||
|
- cache/storage/release/application/runtime test는 각 production wiring과
|
||||||
|
diagnostics failure isolation을 검증한다.
|
||||||
|
|
||||||
|
## 한계와 재검토 조건
|
||||||
|
|
||||||
|
기본 adapter는 운영 log 검색, source map 연계, session replay, distributed span,
|
||||||
|
analytics consent, sampling budget과 장기 보존을 제공하지 않는다. 실제 sink를
|
||||||
|
선정할 때 데이터 처리 지역, 보존 기간, consent, CSP, source map 접근 제어,
|
||||||
|
sampling과 비용 상한을 별도 결정해야 한다.
|
||||||
|
|
||||||
|
## Rollback
|
||||||
|
|
||||||
|
telemetry exporter는 runtime 설정을 끄거나 adapter wiring을 `noOpTelemetry`로
|
||||||
|
바꾸어 독립적으로 제거할 수 있다. 이때도 `DiagnosticsPort`, registry,
|
||||||
|
redaction/value policy, producer-count와 negative fixture는 유지한다. 외부 SDK
|
||||||
|
문제로 application producer와 안전 계약을 함께 되돌리지 않는다.
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
- 기본 번들에 포함할 역량과 필요할 때 설치할 확장 역량을 구분한다.
|
- 기본 번들에 포함할 역량과 필요할 때 설치할 확장 역량을 구분한다.
|
||||||
- 특정 벤더를 채택하더라도 제품 코드가 벤더 API에 직접 결합되지 않는지 확인한다.
|
- 특정 벤더를 채택하더라도 제품 코드가 벤더 API에 직접 결합되지 않는지 확인한다.
|
||||||
|
|
||||||
최초 검토 기준은 `develop`의 `cb195f8`이며, RP-01~RP-04 구현 결과를 이 문서에
|
최초 검토 기준은 `develop`의 `cb195f8`이며, RP-01~RP-08 구현 결과를 이 문서에
|
||||||
누적 반영했다. 이후 구현으로 경로나 세부 내용이 달라질 수 있으므로, 각 항목은
|
누적 반영했다. 이후 구현으로 경로나 세부 내용이 달라질 수 있으므로, 각 항목은
|
||||||
문서의 경로뿐 아니라 해당 테스트와 아키텍처 게이트로 계속 검증해야 한다.
|
문서의 경로뿐 아니라 해당 테스트와 아키텍처 게이트로 계속 검증해야 한다.
|
||||||
|
|
||||||
@@ -33,13 +33,14 @@
|
|||||||
|
|
||||||
특히 다음은 선행 해결이 필요하다.
|
특히 다음은 선행 해결이 필요하다.
|
||||||
|
|
||||||
RP-01~RP-05에서 TypeScript 도구 안전망, application runtime 주입,
|
RP-01~RP-09에서 TypeScript 도구 안전망, application runtime 주입,
|
||||||
query/mutation inbound adapter, HTTP 실행 계약과 executable route/release
|
query/mutation inbound adapter, HTTP 실행 계약과 executable route/release
|
||||||
recovery 계약, 제거 가능한 reference 수직 슬라이스는 구현됐다. 현재 선행 해결
|
recovery 계약, 제거 가능한 reference 수직 슬라이스, form/page, design system과
|
||||||
|
i18n 실행 경계와 diagnostics/telemetry production wiring은 구현됐다. 현재 선행 해결
|
||||||
대상은 다음과 같다.
|
대상은 다음과 같다.
|
||||||
|
|
||||||
1. 폼, 페이지 템플릿, 확장된 디자인 시스템과 컴포넌트 워크벤치
|
1. registry evidence와 실제 compatibility diff
|
||||||
2. 국제화, diagnostics, optional adapter recipe와 심화 품질 게이트
|
2. 공급망과 optional adapter recipe 심화 게이트
|
||||||
|
|
||||||
따라서 현재 상태를 “프론트 공통부가 모두 구현됐다”고 표현하면 범위가 과장된다.
|
따라서 현재 상태를 “프론트 공통부가 모두 구현됐다”고 표현하면 범위가 과장된다.
|
||||||
더 정확한 표현은 다음과 같다.
|
더 정확한 표현은 다음과 같다.
|
||||||
@@ -65,7 +66,7 @@ recovery 계약, 제거 가능한 reference 수직 슬라이스는 구현됐다.
|
|||||||
| 계층 의존 방향 | 부분 준비 | `.dependency-cruiser.cjs`, `src/application/ports` | inbound/outbound 명명과 `contracts` 소유권까지 집행 |
|
| 계층 의존 방향 | 부분 준비 | `.dependency-cruiser.cjs`, `src/application/ports` | inbound/outbound 명명과 `contracts` 소유권까지 집행 |
|
||||||
| application facade | 준비됨 | typed input/output catalog, provider, production composition test | feature input use case를 contribution으로 확장 |
|
| application facade | 준비됨 | typed input/output catalog, provider, production composition test | feature input use case를 contribution으로 확장 |
|
||||||
| HTTP client | 준비됨 | path/search/body projection, runtime timeout/retry, abort/cleanup test | feature gateway 뒤에서 사용 |
|
| HTTP client | 준비됨 | path/search/body projection, runtime timeout/retry, abort/cleanup test | feature gateway 뒤에서 사용 |
|
||||||
| retry | 준비됨 | HTTP 단일 소유, runtime max attempts, Query retry off | RP-09에서 telemetry 연결 |
|
| retry | 준비됨 | HTTP 단일 소유, runtime max attempts, Query retry off, logical execution당 bounded diagnostics | terminal event 중복 방지 계약 유지 |
|
||||||
| 오류 모델 | 부분 준비 | error registry와 normalization 존재 | typed discriminated union과 계층별 mapper |
|
| 오류 모델 | 부분 준비 | error registry와 normalization 존재 | typed discriminated union과 계층별 mapper |
|
||||||
| 검증 | 준비됨 | runtime/API/route/form Zod parse 결과를 실행 경계에서 사용하고 domain invariant와 분리 | feature별 schema 소유권 유지 |
|
| 검증 | 준비됨 | runtime/API/route/form Zod parse 결과를 실행 경계에서 사용하고 domain invariant와 분리 | feature별 schema 소유권 유지 |
|
||||||
| 인증 연동 | 준비됨/프로젝트 선택 | opaque auth owner와 demo seam 존재 | 인증 방식별 recipe; 기본 token 저장소는 추가하지 않음 |
|
| 인증 연동 | 준비됨/프로젝트 선택 | opaque auth owner와 demo seam 존재 | 인증 방식별 recipe; 기본 token 저장소는 추가하지 않음 |
|
||||||
@@ -73,15 +74,15 @@ recovery 계약, 제거 가능한 reference 수직 슬라이스는 구현됐다.
|
|||||||
| 클라이언트 상태 | 부분 준비 | local state, theme context, session external store | 상태 소유권 표와 typed external-store 예제 |
|
| 클라이언트 상태 | 부분 준비 | local state, theme context, session external store | 상태 소유권 표와 typed external-store 예제 |
|
||||||
| 범용 global store | 프로젝트 선택 | 별도 라이브러리 없음 | 필요 조건에 따라 Zustand/Redux Toolkit/state machine 선택 |
|
| 범용 global store | 프로젝트 선택 | 별도 라이브러리 없음 | 필요 조건에 따라 Zustand/Redux Toolkit/state machine 선택 |
|
||||||
| 라우팅 | 준비됨 | Data Router, typed runtime map, codec, metadata consumer, bounded chunk recovery | reference feature route와 release E2E로 사용 범위 확장 |
|
| 라우팅 | 준비됨 | Data Router, typed runtime map, codec, metadata consumer, bounded chunk recovery | reference feature route와 release E2E로 사용 범위 확장 |
|
||||||
| 앱 셸·반응형 | 준비됨 | native modal Drawer, compact/desktop layout, Escape/link dismiss와 focus restore | RP-08에서 RTL/direction 검증 |
|
| 앱 셸·반응형 | 준비됨 | native modal Drawer, compact/desktop layout, Escape/link dismiss/focus restore, pseudo reflow와 RTL direction | compact browser matrix 유지 |
|
||||||
| 페이지 템플릿 | 준비됨 | Standard/Collection/Detail/Form/Status와 public design-system entry | feature별 slot 조합 유지 |
|
| 페이지 템플릿 | 준비됨 | Standard/Collection/Detail/Form/Status와 public design-system entry | feature별 slot 조합 유지 |
|
||||||
| 디자인 토큰 | 준비됨 | primitive/semantic/component CSS, 48-token 자동 계약, dark/forced-colors/reduced-motion | 제품 brand token은 외부 프로젝트에서 확장 |
|
| 디자인 토큰 | 준비됨 | primitive/semantic/component CSS, 48-token 자동 계약, dark/forced-colors/reduced-motion | 제품 brand token은 외부 프로젝트에서 확장 |
|
||||||
| 공통 UI | 준비됨 | action/form/feedback/overlay/navigation primitive와 pattern, compatibility export | Storybook/visual은 RP-10 |
|
| 공통 UI | 준비됨 | action/form/feedback/overlay/navigation primitive와 pattern, compatibility export | Storybook/visual은 RP-10 |
|
||||||
| 아이콘 | 준비됨 | Lucide static vendor facade와 semantic icon/IconButton 접근성 계약 | 의미 icon 추가 시 bundle/접근성 기준 적용 |
|
| 아이콘 | 준비됨 | Lucide static vendor facade와 semantic icon/IconButton 접근성 계약 | 의미 icon 추가 시 bundle/접근성 기준 적용 |
|
||||||
| 폼 | 준비됨 | Zod 기반 local facade, error summary/focus, 422 allowlist, dirty/pending/conflict 정책 | 복합 form 요구가 생기면 VD-04 조건으로 vendor adapter 평가 |
|
| 폼 | 준비됨 | Zod 기반 local facade, error summary/focus, 422 allowlist, dirty/pending/conflict 정책 | 복합 form 요구가 생기면 VD-04 조건으로 vendor adapter 평가 |
|
||||||
| 국제화 | 미제공 | 한국어 문자열·locale이 하드코딩 | typed message/formatter/locale/RTL 경계 |
|
| 국제화 | 준비됨 | 137-key typed catalog, locale provider, Intl formatter, safe fallback/alias, pseudo·RTL gate | 실제 locale·번역 승인은 프로젝트에서 연결 |
|
||||||
| logging/diagnostics | 미제공 | telemetry port는 있으나 logger 없음 | redaction이 적용된 diagnostics/logging 경계 |
|
| logging/diagnostics | 준비됨 | 별도 `DiagnosticsPort`, 8-event registry, allowlist, bounded/no-op adapter와 production producer | 실제 프로젝트의 remote sink는 port 뒤에서 선택 |
|
||||||
| telemetry | 부분 준비 | registry, queue, redaction 존재 | HTTP·boot·cache·storage·route 사건에 실제 연결 |
|
| telemetry | 준비됨/프로젝트 선택 | 5-event registry, bounded queue, redaction/value policy, boot·HTTP·render·release·drop producer | analytics/RUM/error vendor와 consent는 프로젝트에서 선택 |
|
||||||
| 비동기 상태 불변식 | 준비됨 | 배타적 typed overlay, stale latch, 실제 retry/conflict action | reference 화면에서 전체 상태 전시 |
|
| 비동기 상태 불변식 | 준비됨 | 배타적 typed overlay, stale latch, 실제 retry/conflict action | reference 화면에서 전체 상태 전시 |
|
||||||
| 단위·통합·E2E | 준비됨 | Vitest, RTL, MSW, Playwright 3엔진 | TS 테스트 검사, 실제 bootstrap 통합, 위험 시나리오 보강 |
|
| 단위·통합·E2E | 준비됨 | Vitest, RTL, MSW, Playwright 3엔진 | TS 테스트 검사, 실제 bootstrap 통합, 위험 시나리오 보강 |
|
||||||
| UI 회귀 검증 | 미제공 | axe/reflow는 있으나 visual baseline 없음 | Storybook 또는 동급 workshop과 시각 회귀 |
|
| UI 회귀 검증 | 미제공 | axe/reflow는 있으나 visual baseline 없음 | Storybook 또는 동급 workshop과 시각 회귀 |
|
||||||
@@ -216,11 +217,14 @@ guard → browser navigation adapter의 1회 reload로 연결됐다. 일반 rend
|
|||||||
failure는 이 경로에서 제외되고, 반복 실패·offline·malformed manifest·storage
|
failure는 이 경로에서 제외되고, 반복 실패·offline·malformed manifest·storage
|
||||||
실패는 지원 표면으로 fail-closed된다.
|
실패는 지원 표면으로 fail-closed된다.
|
||||||
|
|
||||||
#### telemetry, registry, 공급망 gate의 실행 깊이가 부족하다
|
#### RP-09에서 diagnostics/telemetry 실행 깊이 보강
|
||||||
|
|
||||||
telemetry registry에는 여러 사건이 있지만 실제 production producer는 제한적이다.
|
`DiagnosticsPort`와 `TelemetryPort`를 분리하고 boot, HTTP logical outcome,
|
||||||
boot, API attempt/final failure, auth recovery, storage/cache degradation, release/chunk
|
render, cache, storage, route, release mismatch와 delivery drop을 production
|
||||||
recovery를 registry 사건에 연결해야 한다.
|
producer에 연결했다. HTTP retry는 attempt별 terminal event를 발행하지 않고
|
||||||
|
logical execution 종료 시 한 번만 bounded outcome을 남긴다. allowlist와
|
||||||
|
value policy가 raw URL/query/body/storage value/error object를 거절하고 queue와
|
||||||
|
sink failure는 nonrecursive drop evidence로 제한된다.
|
||||||
|
|
||||||
registry/compatibility 검사는 다음까지 확장한다.
|
registry/compatibility 검사는 다음까지 확장한다.
|
||||||
|
|
||||||
@@ -242,7 +246,7 @@ known vulnerability, license policy, SBOM/provenance를 pinned tool로 검사해
|
|||||||
- token → primitive → pattern → template로 이어지는 디자인 시스템
|
- token → primitive → pattern → template로 이어지는 디자인 시스템
|
||||||
- Lucide를 감싼 local icon registry와 `IconButton`
|
- Lucide를 감싼 local icon registry와 `IconButton`
|
||||||
- typed message key, locale provider, formatter, pseudo-locale/RTL smoke
|
- typed message key, locale provider, formatter, pseudo-locale/RTL smoke
|
||||||
- redacted structured diagnostics/logger와 telemetry wiring
|
- RP-09에서 완료한 redacted structured diagnostics와 telemetry wiring 유지
|
||||||
- Storybook 또는 동급 isolated UI workshop
|
- Storybook 또는 동급 isolated UI workshop
|
||||||
- Playwright visual baseline, shared MSW scenarios, built-dist E2E
|
- Playwright visual baseline, shared MSW scenarios, built-dist E2E
|
||||||
- React Hooks, JSX accessibility, TanStack Query 관련 lint
|
- React Hooks, JSX accessibility, TanStack Query 관련 lint
|
||||||
@@ -250,6 +254,24 @@ known vulnerability, license policy, SBOM/provenance를 pinned tool로 검사해
|
|||||||
- registry/compatibility의 실제 diff와 orphan reference 검사
|
- registry/compatibility의 실제 diff와 orphan reference 검사
|
||||||
- transitive vulnerability, license, SBOM/provenance 공급망 gate
|
- transitive vulnerability, license, SBOM/provenance 공급망 gate
|
||||||
|
|
||||||
|
#### RP-08에서 국제화 실행 경계 구현
|
||||||
|
|
||||||
|
`src/presentation/i18n`은 shell, route, async/form error, page template와
|
||||||
|
design-system 기본 copy의 canonical 경계다. `MessageKey`와 key별
|
||||||
|
`MessageParameters`가 잘못된 key/보간을 compile time에 막고, runtime
|
||||||
|
`resolveMessage`는 unknown locale/key와 누락 보간에서 raw 값 대신 안전한
|
||||||
|
fallback을 반환한다. application mapper는 locale-formatted date를 반환하지
|
||||||
|
않고 timestamp를 유지하며 presentation formatter가 `UTC` 또는 명시 timezone을
|
||||||
|
적용한다.
|
||||||
|
|
||||||
|
`LocaleProvider`는 `ko-KR`, `en-US`, `en-XA`, `ar-EG` smoke set과 document
|
||||||
|
`lang/dir`을 동기화한다. `en-XA`는 긴 문구 reflow, `ar-EG`는 logical CSS,
|
||||||
|
Drawer, Tabs arrow와 pagination 방향 icon을 검증하기 위한 개발 locale이다.
|
||||||
|
실제 아랍어 번역 완료를 뜻하지 않는다. `check:i18n`과 negative fixture는 common
|
||||||
|
UI literal, backend raw message render와 raw HTML interpolation을 거절한다.
|
||||||
|
새 key rename은 canonical type에는 넣지 않고 runtime alias/migration window로
|
||||||
|
호환한다.
|
||||||
|
|
||||||
### 5.3 P2: 경계와 recipe를 제공할 선택 항목
|
### 5.3 P2: 경계와 recipe를 제공할 선택 항목
|
||||||
|
|
||||||
다음 기능을 모든 앱의 초기 번들에 설치할 필요는 없다. 대신 port 또는 local
|
다음 기능을 모든 앱의 초기 번들에 설치할 필요는 없다. 대신 port 또는 local
|
||||||
@@ -361,7 +383,8 @@ bootstrap → React TSX → tests 순서로 이동한다.
|
|||||||
|
|
||||||
- retry: `src/adapters/http/retry-policy.js`, 부분 준비
|
- retry: `src/adapters/http/retry-policy.js`, 부분 준비
|
||||||
- API client: `src/adapters/http/client.js`, 부분 준비
|
- API client: `src/adapters/http/client.js`, 부분 준비
|
||||||
- logger: 없음. telemetry와 분리하거나 diagnostics port로 합치는 결정 필요
|
- logger: `DiagnosticsPort`로 telemetry와 분리해 구현. closed event/level,
|
||||||
|
allowlist와 bounded/no-op adapter 제공
|
||||||
- token manager: 의도적으로 없음. opaque external auth owner가 credential을 소유
|
- token manager: 의도적으로 없음. opaque external auth owner가 credential을 소유
|
||||||
- error: `src/contracts/errors.js`와 HTTP normalization, 부분 준비
|
- error: `src/contracts/errors.js`와 HTTP normalization, 부분 준비
|
||||||
- validation: runtime/API Zod는 존재, route/form/domain 분리는 미완성
|
- validation: runtime/API Zod는 존재, route/form/domain 분리는 미완성
|
||||||
|
|||||||
@@ -651,6 +651,26 @@ token rename은 alias/migration 기간을 두고, vendor adapter와 local API co
|
|||||||
RP-08은 기존 기본 언어 catalog를 fallback으로 유지한다. 번역 catalog를
|
RP-08은 기존 기본 언어 catalog를 fallback으로 유지한다. 번역 catalog를
|
||||||
파괴적으로 덮어쓰지 않는다.
|
파괴적으로 덮어쓰지 않는다.
|
||||||
|
|
||||||
|
**구현 증거 (2026-07-26)**
|
||||||
|
|
||||||
|
- VD-06에서 dependency를 추가하지 않는 browser `Intl` + typed local catalog를
|
||||||
|
채택하고 vendor 재평가 조건, fallback과 key migration 정책을 문서화했다.
|
||||||
|
- `src/presentation/i18n`이 137개 common key, key별 interpolation,
|
||||||
|
`ko-KR` fallback, compatibility alias, date/number/relative/list/plural/select
|
||||||
|
formatter와 `LocaleProvider`를 제공한다.
|
||||||
|
- shell, route lifecycle/access/recovery, async/form error, page template와
|
||||||
|
design-system default copy가 catalog consumer로 연결됐다.
|
||||||
|
- feature route copy는 feature-owned catalog contribution으로 분리되어 reference
|
||||||
|
feature 제거 시 source와 built artifact에 전용 message key가 남지 않는다.
|
||||||
|
- reference application mapper는 locale-formatted date 대신 timestamp를
|
||||||
|
반환하고 presentation formatter가 UTC 또는 명시 timezone을 적용한다.
|
||||||
|
- `check:i18n`과 type negative fixture가 catalog/placeholder 불일치,
|
||||||
|
hardcoded common literal, backend raw message render, unsafe HTML,
|
||||||
|
unknown key와 interpolation mismatch를 거절한다.
|
||||||
|
- unit/component/browser test가 safe fallback, pseudo 320px reflow,
|
||||||
|
document `lang/dir`, RTL Drawer/Tabs/directional icon과 deterministic formatter를
|
||||||
|
검증한다.
|
||||||
|
|
||||||
### 09. `feature-frontend-diagnostics-telemetry-runtime`
|
### 09. `feature-frontend-diagnostics-telemetry-runtime`
|
||||||
|
|
||||||
**목표**
|
**목표**
|
||||||
@@ -703,6 +723,28 @@ render와 release 사건을 실제 producer에 연결한다.
|
|||||||
RP-09는 exporter를 제거하고 즉시 no-op adapter로 전환할 수 있어야 한다.
|
RP-09는 exporter를 제거하고 즉시 no-op adapter로 전환할 수 있어야 한다.
|
||||||
diagnostics port와 redaction test는 유지한다.
|
diagnostics port와 redaction test는 유지한다.
|
||||||
|
|
||||||
|
**구현 증거 (2026-07-26)**
|
||||||
|
|
||||||
|
- VD-07에서 level/event 기반 `DiagnosticsPort`와 semantic `TelemetryPort`를
|
||||||
|
분리하고 bounded memory/no-op 또는 설정 기반 best-effort HTTP exporter를
|
||||||
|
채택했다.
|
||||||
|
- diagnostics 8종과 telemetry 5종의 registry, context/attribute allowlist,
|
||||||
|
고카디널리티 value policy, timestamp와 status/attempt/duration/queue bucket을
|
||||||
|
구현했다.
|
||||||
|
- boot, route, render, HTTP logical outcome, cache, storage, release mismatch와
|
||||||
|
telemetry drop을 production composition에 연결했다. HTTP는 success/recovery/
|
||||||
|
terminal/abort 각각 logical execution당 diagnostics 한 번, terminal
|
||||||
|
non-abort failure telemetry 한 번만 발행한다.
|
||||||
|
- bounded oldest-drop queue, drop reason 집계, sink/observer failure 격리와
|
||||||
|
nonrecursive delivery evidence를 구현했다. exporter가 없으면 network와 queue
|
||||||
|
side effect가 없는 true no-op이다.
|
||||||
|
- `check:diagnostics`, source negative fixture와 TypeScript negative fixture가
|
||||||
|
producer 누락, direct console, unknown event/context, raw URL/query/body/
|
||||||
|
credential 경계를 거절한다.
|
||||||
|
- unit/integration test가 circular/hostile error, pre-mount boot, queue/sink
|
||||||
|
failure, no-op, cache/storage/release producer, success/retry recovery/terminal/
|
||||||
|
abort 횟수와 reference route/operation/correlation context를 검증한다.
|
||||||
|
|
||||||
### 10. `feature-frontend-test-registry-evidence-hardening`
|
### 10. `feature-frontend-test-registry-evidence-hardening`
|
||||||
|
|
||||||
**목표**
|
**목표**
|
||||||
|
|||||||
@@ -178,6 +178,15 @@ template public API이며 feature와 shell은 이 entry만 소비한다. Lucide
|
|||||||
port가 아니다. native Dialog/Drawer/Menu/Tabs의 focus·keyboard 상태도
|
port가 아니다. native Dialog/Drawer/Menu/Tabs의 focus·keyboard 상태도
|
||||||
presentation이 소유하고 use case나 outbound adapter로 올리지 않는다.
|
presentation이 소유하고 use case나 outbound adapter로 올리지 않는다.
|
||||||
|
|
||||||
|
RP-08에서 i18n은 application output port가 아니라 React inbound adapter의
|
||||||
|
local facade로 확정됐다. domain/application은 locale이나 번역 문장을 알지 않고
|
||||||
|
timestamp, number, failure kind 같은 의미 값만 반환한다.
|
||||||
|
`src/presentation/i18n`이 typed message catalog, formatter, fallback,
|
||||||
|
`<html lang/dir>`과 pseudo/RTL smoke를 소유한다. backend raw `message`는
|
||||||
|
application failure registry를 우회해 렌더링할 수 없으며 `check:i18n` negative
|
||||||
|
fixture가 이 경계를 집행한다. 번역 vendor를 나중에 선택해도 이 facade 뒤의
|
||||||
|
adapter만 교체한다.
|
||||||
|
|
||||||
이 문서의 목표 구조는 기존 기반을 폐기하는 것이 아니라 이러한
|
이 문서의 목표 구조는 기존 기반을 폐기하는 것이 아니라 이러한
|
||||||
불일치를 제거하는 것이다.
|
불일치를 제거하는 것이다.
|
||||||
|
|
||||||
@@ -770,22 +779,31 @@ Logger와 telemetry는 같은 것이 아니다.
|
|||||||
- Telemetry: registry에 정의된 semantic event와 metric
|
- Telemetry: registry에 정의된 semantic event와 metric
|
||||||
- Error reporter: 예외 집계와 release correlation
|
- Error reporter: 예외 집계와 release correlation
|
||||||
|
|
||||||
기본 `Logger` output port는 safe context만 받는다.
|
VD-07에 따라 기본 구현은 임의 message 문자열을 받는 `Logger`가 아니라 닫힌
|
||||||
|
event ID와 safe context만 받는 `DiagnosticsPort`다.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
export interface Logger {
|
export interface DiagnosticsPort {
|
||||||
debug(message: string, context?: SafeLogContext): void;
|
record(input: {
|
||||||
info(message: string, context?: SafeLogContext): void;
|
level: DiagnosticLevel;
|
||||||
warn(message: string, context?: SafeLogContext): void;
|
eventId: DiagnosticEventId;
|
||||||
error(message: string, context?: SafeLogContext): void;
|
context?: DiagnosticContext;
|
||||||
|
}): void;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
개발 환경에는 redacted console adapter, production에는 allowlist 기반
|
기본 runtime에는 bounded in-memory diagnostics와 설정 기반 best-effort
|
||||||
remote adapter, 테스트에는 recording 또는 no-op adapter를 연결한다.
|
telemetry adapter, 테스트에는 recording 또는 no-op adapter를 연결한다.
|
||||||
|
direct `console`은 redaction 경계를 우회하므로 source gate가 거절한다.
|
||||||
민감정보 redaction은 각 호출자의 선의가 아니라 adapter와 contract에서
|
민감정보 redaction은 각 호출자의 선의가 아니라 adapter와 contract에서
|
||||||
강제한다.
|
강제한다.
|
||||||
|
|
||||||
|
현재 production producer는 boot, logical HTTP outcome, cache, storage, route,
|
||||||
|
render, release mismatch와 telemetry delivery drop을 포함한다. HTTP terminal
|
||||||
|
telemetry는 모든 retry가 끝난 뒤 한 번만 발행하며 abort에는 발행하지 않는다.
|
||||||
|
raw path/query/body/error 대신 route/operation/correlation ID와
|
||||||
|
status/attempt/duration bucket만 전달한다.
|
||||||
|
|
||||||
## 16. Feature 경계와 removable reference feature
|
## 16. Feature 경계와 removable reference feature
|
||||||
|
|
||||||
Reference feature는 단순 UI fixture가 아니라 다음 경로를 모두 실행해야
|
Reference feature는 단순 UI fixture가 아니라 다음 경로를 모두 실행해야
|
||||||
@@ -1214,9 +1232,10 @@ contract와 실패 분기를 우선한다.
|
|||||||
- [ ] runtime timeout/retry 설정이 실제 HTTP transport에 반영된다.
|
- [ ] runtime timeout/retry 설정이 실제 HTTP transport에 반영된다.
|
||||||
- [ ] QueryClient와 feature query bridge가 실제 route에서 동작한다.
|
- [ ] QueryClient와 feature query bridge가 실제 route에서 동작한다.
|
||||||
- [ ] session UI API와 credential attachment가 분리되어 있다.
|
- [ ] session UI API와 credential attachment가 분리되어 있다.
|
||||||
- [ ] logger와 telemetry가 HTTP/render/storage/cache failure 경로에
|
- [x] diagnostics와 telemetry가 HTTP/render/storage/cache failure 경로에
|
||||||
연결된다.
|
연결된다.
|
||||||
- [ ] page lifecycle에서 필요한 telemetry flush/cleanup이 수행된다.
|
- [x] `pagehide`에서 bounded telemetry queue를 flush하고 adapter `dispose`가
|
||||||
|
lifecycle listener를 정리한다.
|
||||||
|
|
||||||
### 26.3 HTTP와 validation
|
### 26.3 HTTP와 validation
|
||||||
|
|
||||||
|
|||||||
@@ -447,6 +447,13 @@ controller가 소유하지 않는 것:
|
|||||||
| Page Template | 반복 layout/state | 접근성과 반응형 구조 재사용 | data fetching을 template에 포함 |
|
| Page Template | 반복 layout/state | 접근성과 반응형 구조 재사용 | data fetching을 template에 포함 |
|
||||||
| Registry + Runtime Map | route/operation/event | 선언과 실행 완전성 | 모든 설정을 하나의 거대 전역 파일에 집중 |
|
| Registry + Runtime Map | route/operation/event | 선언과 실행 완전성 | 모든 설정을 하나의 거대 전역 파일에 집중 |
|
||||||
|
|
||||||
|
RP-08 이후 route contract의 `title`/`navigation` 필드는 fallback metadata이며
|
||||||
|
실제 document title, navigation, loading/error/access surface는
|
||||||
|
`route.<ROUTE_ID>.title|navigation` typed catalog key를 해석한다. route params,
|
||||||
|
search, backend message를 translation key로 조립하지 않는다. locale 변경은
|
||||||
|
현재 route를 재요청하거나 query key를 바꾸지 않고 document title과 화면 copy만
|
||||||
|
다시 렌더링한다.
|
||||||
|
|
||||||
패턴은 추상화 파일만 만든 것으로 완료되지 않는다. reference usage, negative
|
패턴은 추상화 파일만 만든 것으로 완료되지 않는다. reference usage, negative
|
||||||
architecture test, 실패 상태 test가 있어야 제공된 패턴으로 본다.
|
architecture test, 실패 상태 test가 있어야 제공된 패턴으로 본다.
|
||||||
|
|
||||||
|
|||||||
@@ -468,23 +468,57 @@ raw response body, stack, token, URL query, PII를 사용자 copy나 일반 log
|
|||||||
|
|
||||||
### 7.3 diagnostics와 telemetry
|
### 7.3 diagnostics와 telemetry
|
||||||
|
|
||||||
현재 telemetry event contract와 별도로 개발·진단용 structured logger가 필요하다.
|
VD-07에서 level/event 기반 `DiagnosticsPort`와 semantic
|
||||||
다음 두 설계 중 하나를 ADR로 결정한다.
|
`TelemetryPort`를 분리했다. diagnostics는 8개 event ID와 safe context
|
||||||
|
allowlist를, telemetry는 event별 required/optional attribute와 value policy를
|
||||||
1. `DiagnosticsPort`가 log/event/span을 내부 method로 구분
|
사용한다.
|
||||||
2. `LoggerPort`와 `TelemetryPort`를 분리
|
|
||||||
|
|
||||||
공통 요구:
|
공통 요구:
|
||||||
|
|
||||||
- log level과 event key는 닫힌 union
|
- log level과 event key는 닫힌 union
|
||||||
- attribute allowlist와 중앙 redaction
|
- attribute allowlist와 중앙 redaction
|
||||||
- dev adapter는 console을 사용하되 동일 redaction 적용
|
- 기본 adapter는 bounded memory/no-op이고 endpoint가 있을 때만 best-effort
|
||||||
- production adapter는 provider SDK를 감싸며 앱 코드는 SDK를 import하지 않음
|
HTTP queue를 사용
|
||||||
|
- production provider SDK를 추가할 때도 port 뒤에서 감싸며 앱 코드는 SDK를
|
||||||
|
import하지 않음
|
||||||
- 오류 객체 전체를 그대로 serialize하지 않음
|
- 오류 객체 전체를 그대로 serialize하지 않음
|
||||||
- trace ID/build ID/route ID/operation ID를 허용된 범위에서 연결
|
- trace ID/build ID/route ID/operation ID를 허용된 범위에서 연결
|
||||||
- logging failure가 제품 flow를 실패시키지 않음
|
- logging failure가 제품 flow를 실패시키지 않음
|
||||||
- consent가 필요한 analytics와 essential diagnostics를 분리
|
- consent가 필요한 analytics와 essential diagnostics를 분리
|
||||||
|
|
||||||
|
HTTP는 route/operation/correlation ID를 logical execution context로 생성하고
|
||||||
|
success/recovered/failed/aborted 종료 시 diagnostics를 한 번만 기록한다.
|
||||||
|
terminal non-abort failure만 telemetry를 한 번 발행한다. cache/storage와 boot
|
||||||
|
producer는 raw key, value, message, stack을 버리고 error kind와 bounded
|
||||||
|
operation만 남긴다. queue full과 sink failure는 제한된 reason bucket이며 drop
|
||||||
|
observer가 실패해도 재귀 발행하지 않는다.
|
||||||
|
|
||||||
|
### 7.4 locale, message와 표시 값
|
||||||
|
|
||||||
|
RP-08부터 locale은 presentation-owned React context다. server/application
|
||||||
|
state에 번역된 문자열을 저장하거나 query key에 locale을 넣는 것은 응답 자체가
|
||||||
|
locale별 데이터인 경우에만 허용한다. 공통 UI copy 변경 때문에 query cache를
|
||||||
|
복제하지 않는다.
|
||||||
|
|
||||||
|
```text
|
||||||
|
API timestamp/number/failure kind
|
||||||
|
-> schema + mapper (의미 값 유지)
|
||||||
|
-> application result
|
||||||
|
-> presentation controller
|
||||||
|
-> useLocale().date/number/message
|
||||||
|
```
|
||||||
|
|
||||||
|
- message key는 `MessageKey` union이며 interpolation은 key별 tuple type이다.
|
||||||
|
- unknown external key는 `resolveMessage`에 전달해도 raw key가 표시되지 않는다.
|
||||||
|
- backend `message`는 diagnostic input일 수 있지만 사용자 copy가 아니다.
|
||||||
|
- form validation code는 `ParameterlessMessageKey` allowlist로 mapping한다.
|
||||||
|
- date의 기본 timezone은 UTC이고 제품 timezone은 presentation 호출자가
|
||||||
|
명시한다.
|
||||||
|
- pseudo/RTL locale state는 local interaction state이며 persistence와 server
|
||||||
|
synchronization을 기본 제공하지 않는다.
|
||||||
|
- key rename은 typed canonical key를 먼저 이동하고 runtime alias에 migration
|
||||||
|
기간을 둔다.
|
||||||
|
|
||||||
## 8. 폼 표준
|
## 8. 폼 표준
|
||||||
|
|
||||||
VD-04에 따라 현재 기본 엔진은 React native form event와 controlled value이며
|
VD-04에 따라 현재 기본 엔진은 React native form event와 controlled value이며
|
||||||
@@ -584,4 +618,5 @@ backend message와 알 수 없는 path는 field copy로 사용하지 않는다.
|
|||||||
- 상태 종류별 소유권이 테스트와 문서에서 확인된다.
|
- 상태 종류별 소유권이 테스트와 문서에서 확인된다.
|
||||||
- token은 UI와 일반 storage/store에 노출되지 않는다.
|
- token은 UI와 일반 storage/store에 노출되지 않는다.
|
||||||
- failure와 validation의 각 계층이 typed mapper로 분리된다.
|
- failure와 validation의 각 계층이 typed mapper로 분리된다.
|
||||||
|
- common UI copy, locale formatter와 direction이 typed i18n facade를 통과한다.
|
||||||
- query/mutation/form recipe만으로 새 기능을 만들 수 있다.
|
- query/mutation/form recipe만으로 새 기능을 만들 수 있다.
|
||||||
|
|||||||
@@ -534,8 +534,9 @@ Radix는 overlay와 primitive composition을 중심으로 평가할 수 있다.
|
|||||||
|
|
||||||
## 9. 국제화 계약
|
## 9. 국제화 계약
|
||||||
|
|
||||||
디자인 시스템 primitive는 한국어 문구를 내부 기본값으로 숨기지 않는다.
|
RP-08에서 디자인 시스템 primitive의 닫기, alert, toast, 글자 수 같은 기본
|
||||||
접근성 label이나 오류 문구가 필요하면 명시적인 prop 또는 message key를 받는다.
|
문구는 `useLocale()` typed catalog로 이동했다. 제품 의미를 가진 label은 여전히
|
||||||
|
명시적인 prop으로 받으며 primitive가 feature message key를 소유하지 않는다.
|
||||||
|
|
||||||
필수 국제화 기반:
|
필수 국제화 기반:
|
||||||
|
|
||||||
@@ -551,6 +552,17 @@ Radix는 overlay와 primitive composition을 중심으로 평가할 수 있다.
|
|||||||
- pseudo-locale
|
- pseudo-locale
|
||||||
- RTL story와 E2E smoke
|
- RTL story와 E2E smoke
|
||||||
|
|
||||||
|
현재 구현 위치와 실패 정책:
|
||||||
|
|
||||||
|
- `presentation/i18n/catalog.ts`: 137개 canonical common key와 locale parity
|
||||||
|
- `message-contract.ts`: key별 interpolation, fallback과 compatibility alias
|
||||||
|
- `formatters.ts`: UTC-default date, number, relative time, list, plural/select
|
||||||
|
- `locale-provider.tsx`: document `lang/dir`과 React consumer API
|
||||||
|
- missing key/parameter와 formatter 예외: 빈 문자열이나 raw key 대신 안전한
|
||||||
|
fallback
|
||||||
|
- `en-XA`: 긴 문자열/320px reflow, `ar-EG`: logical layout/RTL keyboard smoke
|
||||||
|
- backend raw message와 translated HTML: 정적 negative gate에서 거절
|
||||||
|
|
||||||
금지 패턴:
|
금지 패턴:
|
||||||
|
|
||||||
- 번역 문장 중간에 JSX 문자열을 연결한다.
|
- 번역 문장 중간에 JSX 문자열을 연결한다.
|
||||||
@@ -559,7 +571,7 @@ Radix는 overlay와 primitive composition을 중심으로 평가할 수 있다.
|
|||||||
- route title, navigation label, toast message를 JSX literal로 분산한다.
|
- route title, navigation label, toast message를 JSX literal로 분산한다.
|
||||||
- 번역 누락 시 빈 문자열을 렌더링한다.
|
- 번역 누락 시 빈 문자열을 렌더링한다.
|
||||||
|
|
||||||
Storybook toolbar에서 최소한 다음 조합을 전환할 수 있어야 한다.
|
RP-10의 Storybook toolbar에서 최소한 다음 조합을 전환할 수 있어야 한다.
|
||||||
|
|
||||||
- `ko-KR`, light
|
- `ko-KR`, light
|
||||||
- `en-US`, light
|
- `en-US`, light
|
||||||
|
|||||||
@@ -410,6 +410,8 @@ Page / AsyncSurface / Form pattern
|
|||||||
- filter 순서가 달라도 canonical key가 같다.
|
- filter 순서가 달라도 canonical key가 같다.
|
||||||
- route unmount 또는 superseded input에서 request를 abort한다.
|
- route unmount 또는 superseded input에서 request를 abort한다.
|
||||||
- aborted request는 terminal error나 telemetry failure로 오분류되지 않는다.
|
- aborted request는 terminal error나 telemetry failure로 오분류되지 않는다.
|
||||||
|
- success와 retry recovery는 terminal failure telemetry를 만들지 않고,
|
||||||
|
exhausted retry는 logical execution당 한 번만 발행한다.
|
||||||
- offline/paused와 loading을 구분한다.
|
- offline/paused와 loading을 구분한다.
|
||||||
- 401 복구는 한 번만 수행한다.
|
- 401 복구는 한 번만 수행한다.
|
||||||
- 재로그인 후 허용된 operation만 다시 실행한다.
|
- 재로그인 후 허용된 operation만 다시 실행한다.
|
||||||
@@ -569,6 +571,23 @@ RP-07의 실행 경로는 `check:design-system`,
|
|||||||
baseline은 VD-08/RP-10에서 추가하며 현재 runtime gallery를 isolated workshop
|
baseline은 VD-08/RP-10에서 추가하며 현재 runtime gallery를 isolated workshop
|
||||||
완료 증거로 사용하지 않는다.
|
완료 증거로 사용하지 않는다.
|
||||||
|
|
||||||
|
RP-08의 국제화 실행 경로는 `check:i18n`, `check:i18n:fixture`,
|
||||||
|
`check:types:fixture:i18n-key`, `check:types:fixture:i18n-params`,
|
||||||
|
`tests/unit/i18n-contract.test.ts`, `tests/component/locale-platform.test.tsx`와
|
||||||
|
`tests/e2e/i18n.spec.js`다.
|
||||||
|
|
||||||
|
- unit: locale catalog/placeholder parity, safe fallback/alias, pseudo expansion,
|
||||||
|
direction과 UTC date/number/relative/list/plural/select
|
||||||
|
- component: document `lang/dir`, RTL tab arrow semantics, direction-aware
|
||||||
|
pagination과 modal Drawer
|
||||||
|
- E2E: 320px pseudo reflow와 compact RTL shell/Drawer/focus restore
|
||||||
|
- negative: common UI locale literal, backend message JSX render, raw translated
|
||||||
|
HTML, unknown key와 잘못된 interpolation parameter
|
||||||
|
|
||||||
|
`ar-EG` catalog가 영어 smoke copy를 재사용하는 것은 RTL behavior 검증용이며
|
||||||
|
번역 품질 PASS가 아니다. 실제 locale catalog에는 언어 담당 승인 evidence가
|
||||||
|
추가되어야 한다.
|
||||||
|
|
||||||
### 10.1 Component behavior
|
### 10.1 Component behavior
|
||||||
|
|
||||||
- native role/name/value
|
- native role/name/value
|
||||||
@@ -1266,7 +1285,8 @@ CI registry에 추가한다.
|
|||||||
- [ ] high-risk module branch 목표를 충족한다.
|
- [ ] high-risk module branch 목표를 충족한다.
|
||||||
- [ ] 신규 코드의 미검증 branch에 승인 없는 예외가 없다.
|
- [ ] 신규 코드의 미검증 branch에 승인 없는 예외가 없다.
|
||||||
- [ ] bundle/performance budget을 통과한다.
|
- [ ] bundle/performance budget을 통과한다.
|
||||||
- [ ] telemetry/error output에 민감 정보가 없다.
|
- [x] diagnostics/telemetry output의 allowlist, value policy와 negative fixture가
|
||||||
|
raw URL/query/body/storage value/error object를 거절한다.
|
||||||
- [ ] 관련 gate와 evidence registry가 갱신되었다.
|
- [ ] 관련 gate와 evidence registry가 갱신되었다.
|
||||||
|
|
||||||
## 19. 금지 패턴
|
## 19. 금지 패턴
|
||||||
|
|||||||
@@ -76,6 +76,8 @@ export default [
|
|||||||
"artifacts/**",
|
"artifacts/**",
|
||||||
"tests/fixtures/typecheck/**",
|
"tests/fixtures/typecheck/**",
|
||||||
"tests/fixtures/architecture/forbidden/**",
|
"tests/fixtures/architecture/forbidden/**",
|
||||||
|
"tests/fixtures/diagnostics/forbidden/**",
|
||||||
|
"tests/fixtures/i18n/forbidden/**",
|
||||||
"tests/fixtures/security/forbidden/**",
|
"tests/fixtures/security/forbidden/**",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -115,6 +117,25 @@ export default [
|
|||||||
"no-unused-vars": "off",
|
"no-unused-vars": "off",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
files: ["**/*.d.ts"],
|
||||||
|
languageOptions: {
|
||||||
|
...commonLanguageOptions,
|
||||||
|
parser: babelParser,
|
||||||
|
parserOptions: {
|
||||||
|
requireConfigFile: false,
|
||||||
|
babelOptions: {
|
||||||
|
plugins: [
|
||||||
|
["@babel/plugin-syntax-typescript", { dts: true }],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
"no-undef": "off",
|
||||||
|
"no-unused-vars": "off",
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
files: ["**/*.tsx"],
|
files: ["**/*.tsx"],
|
||||||
languageOptions: {
|
languageOptions: {
|
||||||
|
|||||||
@@ -17,6 +17,10 @@
|
|||||||
"check:architecture": "node scripts/check-architecture.mjs",
|
"check:architecture": "node scripts/check-architecture.mjs",
|
||||||
"check:design-system": "node scripts/check-design-system.mjs",
|
"check:design-system": "node scripts/check-design-system.mjs",
|
||||||
"check:design-system:fixture": "node scripts/check-design-system.mjs --fixture",
|
"check:design-system:fixture": "node scripts/check-design-system.mjs --fixture",
|
||||||
|
"check:i18n": "node scripts/check-i18n.mjs",
|
||||||
|
"check:i18n:fixture": "node scripts/check-i18n.mjs --fixture",
|
||||||
|
"check:diagnostics": "node scripts/check-diagnostics.mjs",
|
||||||
|
"check:diagnostics:fixture": "node scripts/check-diagnostics.mjs --fixture",
|
||||||
"check:types": "corepack pnpm check:types:app && corepack pnpm check:types:node && corepack pnpm check:types:test",
|
"check:types": "corepack pnpm check:types:app && corepack pnpm check:types:node && corepack pnpm check:types:test",
|
||||||
"check:types:app": "tsc --project tsconfig.app.json",
|
"check:types:app": "tsc --project tsconfig.app.json",
|
||||||
"check:types:node": "tsc --project tsconfig.node.json",
|
"check:types:node": "tsc --project tsconfig.node.json",
|
||||||
@@ -30,6 +34,9 @@
|
|||||||
"check:types:fixture:route-runtime": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-route-runtime.ts",
|
"check:types:fixture:route-runtime": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-route-runtime.ts",
|
||||||
"check:types:fixture:page-action": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --jsx react-jsx tests/fixtures/typecheck/invalid-page-action.tsx",
|
"check:types:fixture:page-action": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --jsx react-jsx tests/fixtures/typecheck/invalid-page-action.tsx",
|
||||||
"check:types:fixture:icon-button": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --jsx react-jsx tests/fixtures/typecheck/invalid-icon-button.tsx",
|
"check:types:fixture:icon-button": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --jsx react-jsx tests/fixtures/typecheck/invalid-icon-button.tsx",
|
||||||
|
"check:types:fixture:i18n-key": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-message-key.ts",
|
||||||
|
"check:types:fixture:i18n-params": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-message-params.ts",
|
||||||
|
"check:types:fixture:diagnostics": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-diagnostics-port.ts",
|
||||||
"test:runtime-schema": "vitest run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests",
|
"test:runtime-schema": "vitest run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests",
|
||||||
"test:unit": "vitest run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml",
|
"test:unit": "vitest run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml",
|
||||||
"test:component": "vitest run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml",
|
"test:component": "vitest run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml",
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
// @ts-expect-error Node 24 executes erasable TypeScript for this build-time gate.
|
||||||
|
import { DIAGNOSTIC_EVENT_REGISTRY } from "../src/contracts/diagnostics.ts";
|
||||||
|
import { TELEMETRY_REGISTRY } from "../src/contracts/telemetry.js";
|
||||||
|
|
||||||
|
const fixtureMode = process.argv.includes("--fixture");
|
||||||
|
const failures = [];
|
||||||
|
const extensions = /\.(?:js|jsx|mjs|ts|tsx|mts)$/;
|
||||||
|
|
||||||
|
/** @param {string} directory @returns {Promise<string[]>} */
|
||||||
|
async function filesBelow(directory) {
|
||||||
|
const result = [];
|
||||||
|
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||||
|
const target = path.join(directory, entry.name);
|
||||||
|
if (entry.isDirectory()) result.push(...(await filesBelow(target)));
|
||||||
|
else if (extensions.test(entry.name)) result.push(target);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
const telemetryProducerFiles =
|
||||||
|
/** @type {Readonly<Record<string, string>>} */ ({
|
||||||
|
"app.boot.failed": "src/adapters/diagnostics/bounded-diagnostics.ts",
|
||||||
|
"api.request.failed": "src/adapters/http/client.js",
|
||||||
|
"ui.render.failed": "src/application/create-application.ts",
|
||||||
|
"release.mismatch.detected": "src/application/create-application.ts",
|
||||||
|
"telemetry.delivery.dropped":
|
||||||
|
"src/adapters/telemetry/best-effort-telemetry.js",
|
||||||
|
});
|
||||||
|
const diagnosticProducerFiles =
|
||||||
|
/** @type {Readonly<Record<string, string>>} */ ({
|
||||||
|
"app.boot.failed": "src/adapters/diagnostics/bounded-diagnostics.ts",
|
||||||
|
"http.request.completed": "src/adapters/http/client.js",
|
||||||
|
"cache.operation.failed":
|
||||||
|
"src/adapters/query-cache/tanstack-query-cache.js",
|
||||||
|
"storage.operation.failed":
|
||||||
|
"src/adapters/storage/browser-storage-adapter.js",
|
||||||
|
"route.changed": "src/application/create-application.ts",
|
||||||
|
"ui.render.failed": "src/application/create-application.ts",
|
||||||
|
"release.mismatch.detected": "src/application/create-application.ts",
|
||||||
|
"telemetry.delivery.dropped": "src/bootstrap/runtime-adapters.js",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!fixtureMode) {
|
||||||
|
for (const eventName of Object.keys(TELEMETRY_REGISTRY)) {
|
||||||
|
const producer = telemetryProducerFiles[eventName];
|
||||||
|
if (!producer) {
|
||||||
|
failures.push(`telemetry event has no declared producer: ${eventName}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const source = await readFile(producer, "utf8");
|
||||||
|
if (!source.includes(`"${eventName}"`)) {
|
||||||
|
failures.push(`telemetry producer is not executable: ${eventName}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const eventId of Object.keys(DIAGNOSTIC_EVENT_REGISTRY)) {
|
||||||
|
const producer = diagnosticProducerFiles[eventId];
|
||||||
|
if (!producer) {
|
||||||
|
failures.push(`diagnostic event has no declared producer: ${eventId}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const source = await readFile(producer, "utf8");
|
||||||
|
if (!source.includes(`"${eventId}"`)) {
|
||||||
|
failures.push(`diagnostic producer is not executable: ${eventId}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const sources = fixtureMode
|
||||||
|
? await filesBelow("tests/fixtures/diagnostics/forbidden")
|
||||||
|
: await filesBelow("src");
|
||||||
|
const sensitiveContext =
|
||||||
|
/\b(?:authorization|cookie|access_token|refresh_token|request_body|response_body|raw_url|query_string|email|user_name)\b/i;
|
||||||
|
for (const file of sources) {
|
||||||
|
const source = await readFile(file, "utf8");
|
||||||
|
if (file.includes("contracts/telemetry.js")) continue;
|
||||||
|
if (source.includes("console.")) {
|
||||||
|
failures.push(`direct console diagnostics bypass in ${file}`);
|
||||||
|
}
|
||||||
|
const calls = source.match(
|
||||||
|
/(?:\.record\(\{|\.emit\()[\s\S]{0,700}?(?:\}\)|\}\);)/g,
|
||||||
|
) ?? [];
|
||||||
|
if (calls.some((call) => sensitiveContext.test(call))) {
|
||||||
|
failures.push(`sensitive diagnostic or telemetry context in ${file}`);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
file.includes("tests/fixtures/diagnostics/forbidden") &&
|
||||||
|
source.includes("UNKNOWN_DIAGNOSTIC_EVENT")
|
||||||
|
) {
|
||||||
|
failures.push(`unknown diagnostic event in ${file}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const report = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
mode: fixtureMode ? "negative-fixture" : "source",
|
||||||
|
telemetryEventCount: Object.keys(TELEMETRY_REGISTRY).length,
|
||||||
|
diagnosticEventCount: Object.keys(DIAGNOSTIC_EVENT_REGISTRY).length,
|
||||||
|
checkedFiles: sources.length,
|
||||||
|
failures,
|
||||||
|
passed: failures.length === 0,
|
||||||
|
};
|
||||||
|
await mkdir("artifacts/quality", { recursive: true });
|
||||||
|
await writeFile(
|
||||||
|
fixtureMode
|
||||||
|
? "artifacts/quality/diagnostics-fixture.json"
|
||||||
|
: "artifacts/quality/diagnostics.json",
|
||||||
|
`${JSON.stringify(report, null, 2)}\n`,
|
||||||
|
);
|
||||||
|
if (failures.length > 0) {
|
||||||
|
process.stderr.write(
|
||||||
|
`Diagnostics contract failed:\n${failures.join("\n")}\n`,
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
process.stdout.write(
|
||||||
|
`Diagnostics contract: ${report.diagnosticEventCount} diagnostics and ${report.telemetryEventCount} telemetry producers PASS\n`,
|
||||||
|
);
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
// @ts-expect-error Node 24 executes erasable TypeScript for this build-time gate.
|
||||||
|
import { EN_MESSAGES, KO_MESSAGES, MESSAGE_CATALOGS } from "../src/presentation/i18n/catalog.ts";
|
||||||
|
|
||||||
|
const fixtureMode = process.argv.includes("--fixture");
|
||||||
|
const failures = [];
|
||||||
|
const sourceExtensions = /\.(?:js|jsx|mjs|ts|tsx|mts)$/;
|
||||||
|
const koreanLiteral = /[가-힣]/;
|
||||||
|
const rawFailureRender =
|
||||||
|
/(?<!\$)\{\s*(?:failure|error|response|backend)(?:\?\.|\.)[\w?.]*message\s*\}/;
|
||||||
|
|
||||||
|
/** @param {string} directory @returns {Promise<string[]>} */
|
||||||
|
async function listSourceFiles(directory) {
|
||||||
|
const result = [];
|
||||||
|
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||||
|
const target = path.join(directory, entry.name);
|
||||||
|
if (entry.isDirectory()) result.push(...(await listSourceFiles(target)));
|
||||||
|
else if (sourceExtensions.test(entry.name)) result.push(target);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} template */
|
||||||
|
function placeholders(template) {
|
||||||
|
return [...template.matchAll(/\{([a-zA-Z][a-zA-Z0-9]*)\}/g)]
|
||||||
|
.map((match) => match[1])
|
||||||
|
.sort();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fixtureMode) {
|
||||||
|
const canonicalKeys = Object.keys(KO_MESSAGES).sort();
|
||||||
|
for (const [locale, catalog] of Object.entries(MESSAGE_CATALOGS)) {
|
||||||
|
const readableCatalog =
|
||||||
|
/** @type {Readonly<Record<string, string>>} */ (catalog);
|
||||||
|
const canonicalCatalog =
|
||||||
|
/** @type {Readonly<Record<string, string>>} */ (KO_MESSAGES);
|
||||||
|
const keys = Object.keys(catalog).sort();
|
||||||
|
if (JSON.stringify(keys) !== JSON.stringify(canonicalKeys)) {
|
||||||
|
failures.push(`${locale} catalog keys do not match ko-KR`);
|
||||||
|
}
|
||||||
|
for (const key of canonicalKeys) {
|
||||||
|
if (
|
||||||
|
JSON.stringify(placeholders(readableCatalog[key] ?? "")) !==
|
||||||
|
JSON.stringify(placeholders(canonicalCatalog[key] ?? ""))
|
||||||
|
) {
|
||||||
|
failures.push(`${locale}:${key} interpolation parameters do not match`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Object.keys(EN_MESSAGES).length !== canonicalKeys.length) {
|
||||||
|
failures.push("en-US catalog key count does not match ko-KR");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const commonDirectories = [
|
||||||
|
"src/presentation/boundaries",
|
||||||
|
"src/presentation/components",
|
||||||
|
"src/presentation/design-system",
|
||||||
|
"src/presentation/forms",
|
||||||
|
"src/presentation/layouts",
|
||||||
|
"src/presentation/routes",
|
||||||
|
"src/presentation/templates",
|
||||||
|
];
|
||||||
|
const sources = fixtureMode
|
||||||
|
? await listSourceFiles("tests/fixtures/i18n/forbidden")
|
||||||
|
: (
|
||||||
|
await Promise.all(commonDirectories.map((directory) => listSourceFiles(directory)))
|
||||||
|
).flat();
|
||||||
|
|
||||||
|
for (const file of sources) {
|
||||||
|
const source = await readFile(file, "utf8");
|
||||||
|
if (koreanLiteral.test(source)) {
|
||||||
|
failures.push(`hardcoded common user-facing locale literal in ${file}`);
|
||||||
|
}
|
||||||
|
if (rawFailureRender.test(source)) {
|
||||||
|
failures.push(`raw backend/error message rendered in ${file}`);
|
||||||
|
}
|
||||||
|
if (source.includes("dangerouslySetInnerHTML")) {
|
||||||
|
failures.push(`untrusted HTML interpolation boundary in ${file}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const report = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
mode: fixtureMode ? "negative-fixture" : "source",
|
||||||
|
localeCount: Object.keys(MESSAGE_CATALOGS).length + 1,
|
||||||
|
messageKeyCount: Object.keys(KO_MESSAGES).length,
|
||||||
|
checkedFiles: sources.length,
|
||||||
|
failures,
|
||||||
|
passed: failures.length === 0,
|
||||||
|
};
|
||||||
|
await mkdir("artifacts/quality", { recursive: true });
|
||||||
|
await writeFile(
|
||||||
|
fixtureMode
|
||||||
|
? "artifacts/quality/i18n-fixture.json"
|
||||||
|
: "artifacts/quality/i18n.json",
|
||||||
|
`${JSON.stringify(report, null, 2)}\n`,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (failures.length > 0) {
|
||||||
|
process.stderr.write(`I18n contract failed:\n${failures.join("\n")}\n`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
process.stdout.write(
|
||||||
|
`I18n contract: ${report.messageKeyCount} keys across ${report.localeCount} locales PASS\n`,
|
||||||
|
);
|
||||||
@@ -89,6 +89,12 @@ export function createInstalledFeatureInputs(_context: FeatureContext) {
|
|||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
const emptyMessages = `export const INSTALLED_MESSAGE_CATALOGS = Object.freeze({
|
||||||
|
"ko-KR": Object.freeze({}),
|
||||||
|
"en-US": Object.freeze({}),
|
||||||
|
});
|
||||||
|
`;
|
||||||
|
|
||||||
/** @param {string} directory @returns {Promise<string[]>} */
|
/** @param {string} directory @returns {Promise<string[]>} */
|
||||||
async function filesBelow(directory) {
|
async function filesBelow(directory) {
|
||||||
const entries = await readdir(directory, { withFileTypes: true });
|
const entries = await readdir(directory, { withFileTypes: true });
|
||||||
@@ -135,6 +141,10 @@ await writeFile(
|
|||||||
path.join(fixtureRoot, "src/features/installed-feature-adapters.ts"),
|
path.join(fixtureRoot, "src/features/installed-feature-adapters.ts"),
|
||||||
emptyAdapters,
|
emptyAdapters,
|
||||||
);
|
);
|
||||||
|
await writeFile(
|
||||||
|
path.join(fixtureRoot, "src/features/installed-feature-messages.js"),
|
||||||
|
emptyMessages,
|
||||||
|
);
|
||||||
|
|
||||||
/** @type {string[]} */
|
/** @type {string[]} */
|
||||||
const residue = [];
|
const residue = [];
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.js";
|
||||||
|
import {
|
||||||
|
projectDiagnosticRecord,
|
||||||
|
safeErrorKind,
|
||||||
|
type DiagnosticRecord,
|
||||||
|
type DiagnosticRecordInput,
|
||||||
|
} from "../../contracts/diagnostics.js";
|
||||||
|
import { projectTelemetryEvent } from "../../contracts/telemetry.js";
|
||||||
|
|
||||||
|
export const noOpDiagnostics: DiagnosticsPort = Object.freeze({
|
||||||
|
record() {},
|
||||||
|
});
|
||||||
|
|
||||||
|
export function createDiagnosticsAdapter(
|
||||||
|
options: Readonly<{
|
||||||
|
maxEntries?: number;
|
||||||
|
now?: () => number;
|
||||||
|
sink?: (record: DiagnosticRecord) => void;
|
||||||
|
}> = {},
|
||||||
|
) {
|
||||||
|
const maxEntries = Math.max(1, options.maxEntries ?? 100);
|
||||||
|
const entries: DiagnosticRecord[] = [];
|
||||||
|
const droppedReasons = new Map<string, number>();
|
||||||
|
|
||||||
|
function drop(reason: string) {
|
||||||
|
droppedReasons.set(reason, (droppedReasons.get(reason) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function record(input: DiagnosticRecordInput) {
|
||||||
|
try {
|
||||||
|
const projected = projectDiagnosticRecord(input, options.now);
|
||||||
|
if (!projected.success) {
|
||||||
|
drop(projected.reason);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (entries.length >= maxEntries) {
|
||||||
|
entries.shift();
|
||||||
|
drop("queue-full");
|
||||||
|
}
|
||||||
|
entries.push(projected.record);
|
||||||
|
try {
|
||||||
|
options.sink?.(projected.record);
|
||||||
|
} catch {
|
||||||
|
drop("sink-failure");
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
drop("serialization-failure");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.freeze({
|
||||||
|
record,
|
||||||
|
entries: () => structuredClone(entries) as readonly DiagnosticRecord[],
|
||||||
|
dropped: () => Object.freeze(Object.fromEntries(droppedReasons)),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
type BootSafeContext = Readonly<{
|
||||||
|
kind?: string;
|
||||||
|
buildId?: string;
|
||||||
|
configSchemaVersion?: string;
|
||||||
|
supportReference?: string;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
let lastBootEvidence:
|
||||||
|
| Readonly<{
|
||||||
|
diagnostic: DiagnosticRecord | null;
|
||||||
|
telemetry: Readonly<Record<string, unknown>> | null;
|
||||||
|
}>
|
||||||
|
| undefined;
|
||||||
|
|
||||||
|
export function recordBootFailure(
|
||||||
|
error: unknown,
|
||||||
|
safe: BootSafeContext,
|
||||||
|
now: () => number = Date.now,
|
||||||
|
) {
|
||||||
|
const errorKind =
|
||||||
|
typeof safe.kind === "string" ? safe.kind : safeErrorKind(error);
|
||||||
|
const attributes = {
|
||||||
|
error_kind: errorKind,
|
||||||
|
build_id: safe.buildId ?? "unknown",
|
||||||
|
config_schema_version: safe.configSchemaVersion ?? "unknown",
|
||||||
|
};
|
||||||
|
const diagnostic = projectDiagnosticRecord(
|
||||||
|
{
|
||||||
|
level: "error",
|
||||||
|
eventId: "app.boot.failed",
|
||||||
|
context: attributes,
|
||||||
|
},
|
||||||
|
now,
|
||||||
|
);
|
||||||
|
const telemetry = projectTelemetryEvent("app.boot.failed", attributes, now);
|
||||||
|
lastBootEvidence = Object.freeze({
|
||||||
|
diagnostic: diagnostic.success ? diagnostic.record : null,
|
||||||
|
telemetry: telemetry.success ? telemetry.event : null,
|
||||||
|
});
|
||||||
|
return lastBootEvidence;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getLastBootEvidence() {
|
||||||
|
return lastBootEvidence ? structuredClone(lastBootEvidence) : undefined;
|
||||||
|
}
|
||||||
+89
-11
@@ -14,6 +14,11 @@ import {
|
|||||||
validateOperationRequest,
|
validateOperationRequest,
|
||||||
} from "./schema-registry.js";
|
} from "./schema-registry.js";
|
||||||
import { buildRequestTarget } from "./request-builder.js";
|
import { buildRequestTarget } from "./request-builder.js";
|
||||||
|
import {
|
||||||
|
attemptBucket,
|
||||||
|
durationBucket,
|
||||||
|
statusGroup,
|
||||||
|
} from "../../contracts/diagnostics.js";
|
||||||
|
|
||||||
const noAuthSession =
|
const noAuthSession =
|
||||||
/** @type {import("../../application/ports/auth-session-port.js").AuthSessionPort} */ ({
|
/** @type {import("../../application/ports/auth-session-port.js").AuthSessionPort} */ ({
|
||||||
@@ -54,7 +59,10 @@ const noAuthSession =
|
|||||||
* timeoutMs?: number,
|
* timeoutMs?: number,
|
||||||
* maxRetryAttempts?: number,
|
* maxRetryAttempts?: number,
|
||||||
* scheduler?: Scheduler,
|
* scheduler?: Scheduler,
|
||||||
* getOperation?: typeof getApiOperation
|
* getOperation?: typeof getApiOperation,
|
||||||
|
* diagnostics?: import("../../application/ports/diagnostics-port.js").DiagnosticsPort,
|
||||||
|
* telemetry?: import("../../application/ports/telemetry-port.js").TelemetryPort,
|
||||||
|
* correlationIdFactory?: () => string
|
||||||
* }} dependencies
|
* }} dependencies
|
||||||
*/
|
*/
|
||||||
export function createHttpClient(dependencies) {
|
export function createHttpClient(dependencies) {
|
||||||
@@ -72,6 +80,11 @@ export function createHttpClient(dependencies) {
|
|||||||
const defaultTimeoutMs = dependencies.timeoutMs ?? 10_000;
|
const defaultTimeoutMs = dependencies.timeoutMs ?? 10_000;
|
||||||
const maxRetryAttempts = dependencies.maxRetryAttempts ?? 2;
|
const maxRetryAttempts = dependencies.maxRetryAttempts ?? 2;
|
||||||
const selectOperation = dependencies.getOperation ?? getApiOperation;
|
const selectOperation = dependencies.getOperation ?? getApiOperation;
|
||||||
|
const diagnostics = dependencies.diagnostics;
|
||||||
|
const telemetry = dependencies.telemetry;
|
||||||
|
const correlationIdFactory =
|
||||||
|
dependencies.correlationIdFactory ??
|
||||||
|
(() => `request-${Math.floor(random() * 1_000_000).toString(36)}`);
|
||||||
const scheduler =
|
const scheduler =
|
||||||
dependencies.scheduler ??
|
dependencies.scheduler ??
|
||||||
/** @type {Scheduler} */ ({
|
/** @type {Scheduler} */ ({
|
||||||
@@ -91,7 +104,8 @@ export function createHttpClient(dependencies) {
|
|||||||
* pathParams?: Record<string, string | number>,
|
* pathParams?: Record<string, string | number>,
|
||||||
* searchParams?: unknown,
|
* searchParams?: unknown,
|
||||||
* signal?: AbortSignal,
|
* signal?: AbortSignal,
|
||||||
* idempotencyKey?: string
|
* idempotencyKey?: string,
|
||||||
|
* correlationId?: string
|
||||||
* }} [legacyInput]
|
* }} [legacyInput]
|
||||||
* @returns {Promise<HttpResult>}
|
* @returns {Promise<HttpResult>}
|
||||||
*/
|
*/
|
||||||
@@ -106,9 +120,55 @@ export function createHttpClient(dependencies) {
|
|||||||
body: legacyInput.body,
|
body: legacyInput.body,
|
||||||
signal: legacyInput.signal,
|
signal: legacyInput.signal,
|
||||||
idempotencyKey: legacyInput.idempotencyKey,
|
idempotencyKey: legacyInput.idempotencyKey,
|
||||||
|
correlationId: legacyInput.correlationId,
|
||||||
}
|
}
|
||||||
: request;
|
: request;
|
||||||
const operation = selectOperation(input.operationId);
|
const operation = selectOperation(input.operationId);
|
||||||
|
const startedAt = clock.now();
|
||||||
|
const correlationId = input.correlationId ?? correlationIdFactory();
|
||||||
|
/**
|
||||||
|
* @param {HttpResult} outcome
|
||||||
|
* @param {"success" | "recovered" | "failed" | "aborted"} outcomeKind
|
||||||
|
*/
|
||||||
|
function finalize(outcome, outcomeKind) {
|
||||||
|
const error = outcome.ok ? undefined : outcome.error;
|
||||||
|
const context = {
|
||||||
|
route_id: input.routeId,
|
||||||
|
operation_id: input.operationId,
|
||||||
|
correlation_id: correlationId,
|
||||||
|
outcome: outcomeKind,
|
||||||
|
error_kind: error?.kind ?? "NONE",
|
||||||
|
http_status_group: statusGroup(error?.httpStatus),
|
||||||
|
attempt_count_bucket: attemptBucket(
|
||||||
|
error?.attemptCount ?? retryCount + 1,
|
||||||
|
),
|
||||||
|
duration_bucket: durationBucket(clock.now() - startedAt),
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
diagnostics?.record({
|
||||||
|
level: error ? "warn" : "info",
|
||||||
|
eventId: "http.request.completed",
|
||||||
|
context,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Diagnostics cannot change the HTTP result.
|
||||||
|
}
|
||||||
|
if (error && outcomeKind !== "aborted") {
|
||||||
|
try {
|
||||||
|
telemetry?.emit("api.request.failed", {
|
||||||
|
error_kind: context.error_kind,
|
||||||
|
http_status_group: context.http_status_group,
|
||||||
|
attempt_count_bucket: context.attempt_count_bucket,
|
||||||
|
route_id: context.route_id,
|
||||||
|
operation_id: context.operation_id,
|
||||||
|
duration_bucket: context.duration_bucket,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Telemetry cannot change the HTTP result.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return outcome;
|
||||||
|
}
|
||||||
const logicalIdempotencyKey =
|
const logicalIdempotencyKey =
|
||||||
operation.idempotency === "keyed"
|
operation.idempotency === "keyed"
|
||||||
? input.idempotencyKey ?? idempotencyKeyFactory()
|
? input.idempotencyKey ?? idempotencyKeyFactory()
|
||||||
@@ -126,28 +186,40 @@ export function createHttpClient(dependencies) {
|
|||||||
idempotencyKey: logicalIdempotencyKey,
|
idempotencyKey: logicalIdempotencyKey,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (outcome.ok) return outcome;
|
if (outcome.ok) {
|
||||||
|
return finalize(
|
||||||
|
outcome,
|
||||||
|
retryCount > 0 || recoveryUsed ? "recovered" : "success",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (outcome.error.httpStatus === 401 && !recoveryUsed) {
|
if (outcome.error.httpStatus === 401 && !recoveryUsed) {
|
||||||
recoveryUsed = true;
|
recoveryUsed = true;
|
||||||
const recovered = await recoverSession(authSession, operation, outcome.error);
|
const recovered = await recoverSession(
|
||||||
if (!recovered.ok) return recovered;
|
authSession,
|
||||||
|
operation,
|
||||||
|
outcome.error,
|
||||||
|
);
|
||||||
|
if (!recovered.ok) return finalize(recovered, "failed");
|
||||||
if (operation.idempotency === "none") {
|
if (operation.idempotency === "none") {
|
||||||
return {
|
return finalize(
|
||||||
|
{
|
||||||
ok: false,
|
ok: false,
|
||||||
error: {
|
error: {
|
||||||
...outcome.error,
|
...outcome.error,
|
||||||
retryable: false,
|
retryable: false,
|
||||||
action: "retry",
|
action: "retry",
|
||||||
},
|
},
|
||||||
};
|
},
|
||||||
|
"failed",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (outcome.error.httpStatus === 401 && recoveryUsed) {
|
if (outcome.error.httpStatus === 401 && recoveryUsed) {
|
||||||
authSession.onUnauthenticated();
|
authSession.onUnauthenticated();
|
||||||
return outcome;
|
return finalize(outcome, "failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
@@ -158,7 +230,10 @@ export function createHttpClient(dependencies) {
|
|||||||
maxRetryAttempts,
|
maxRetryAttempts,
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
return outcome;
|
return finalize(
|
||||||
|
outcome,
|
||||||
|
outcome.error.kind === "REQUEST_ABORTED" ? "aborted" : "failed",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const delay = retryDelay(outcome.error, retryCount, random, clock.now());
|
const delay = retryDelay(outcome.error, retryCount, random, clock.now());
|
||||||
@@ -167,12 +242,15 @@ export function createHttpClient(dependencies) {
|
|||||||
try {
|
try {
|
||||||
await clock.sleep(delay, input.signal);
|
await clock.sleep(delay, input.signal);
|
||||||
} catch {
|
} catch {
|
||||||
return {
|
return finalize(
|
||||||
|
{
|
||||||
ok: false,
|
ok: false,
|
||||||
error: failure("REQUEST_ABORTED", input.operationId, retryCount, {
|
error: failure("REQUEST_ABORTED", input.operationId, retryCount, {
|
||||||
code: "REQUEST_ABORTED",
|
code: "REQUEST_ABORTED",
|
||||||
}),
|
}),
|
||||||
};
|
},
|
||||||
|
"aborted",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ export type OperationRequestInput = Readonly<{
|
|||||||
body?: unknown;
|
body?: unknown;
|
||||||
signal?: AbortSignal;
|
signal?: AbortSignal;
|
||||||
idempotencyKey?: string;
|
idempotencyKey?: string;
|
||||||
|
correlationId?: string;
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
export type RequestTargetResult =
|
export type RequestTargetResult =
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { QueryClient } from "@tanstack/react-query";
|
import { MutationCache, QueryCache, QueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
import { createFailure } from "../../contracts/errors.js";
|
import { createFailure } from "../../contracts/errors.js";
|
||||||
|
import { safeErrorKind } from "../../contracts/diagnostics.js";
|
||||||
|
|
||||||
export const QUERY_CACHE_DEFAULTS = Object.freeze({
|
export const QUERY_CACHE_DEFAULTS = Object.freeze({
|
||||||
staleTime: 30_000,
|
staleTime: 30_000,
|
||||||
@@ -11,8 +12,32 @@ export const QUERY_CACHE_DEFAULTS = Object.freeze({
|
|||||||
persistence: false,
|
persistence: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
export function createQueryClient() {
|
/**
|
||||||
|
* @param {{diagnostics?: import("../../application/ports/diagnostics-port.js").DiagnosticsPort}} [dependencies]
|
||||||
|
*/
|
||||||
|
export function createQueryClient(dependencies = {}) {
|
||||||
|
/** @param {string} operation @param {unknown} error */
|
||||||
|
function report(operation, error) {
|
||||||
|
try {
|
||||||
|
dependencies.diagnostics?.record({
|
||||||
|
level: "warn",
|
||||||
|
eventId: "cache.operation.failed",
|
||||||
|
context: {
|
||||||
|
operation,
|
||||||
|
error_kind: safeErrorKind(error),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Query behavior remains independent from diagnostics.
|
||||||
|
}
|
||||||
|
}
|
||||||
return new QueryClient({
|
return new QueryClient({
|
||||||
|
queryCache: new QueryCache({
|
||||||
|
onError: (error) => report("query", error),
|
||||||
|
}),
|
||||||
|
mutationCache: new MutationCache({
|
||||||
|
onError: (error) => report("mutation", error),
|
||||||
|
}),
|
||||||
defaultOptions: {
|
defaultOptions: {
|
||||||
queries: {
|
queries: {
|
||||||
staleTime: QUERY_CACHE_DEFAULTS.staleTime,
|
staleTime: QUERY_CACHE_DEFAULTS.staleTime,
|
||||||
@@ -29,15 +54,16 @@ export function createQueryClient() {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {QueryClient} queryClient
|
* @param {QueryClient} queryClient
|
||||||
|
* @param {{diagnostics?: import("../../application/ports/diagnostics-port.js").DiagnosticsPort}} [dependencies]
|
||||||
* @returns {import("../../application/ports/query-cache-port.js").QueryCachePort}
|
* @returns {import("../../application/ports/query-cache-port.js").QueryCachePort}
|
||||||
*/
|
*/
|
||||||
export function createQueryCacheAdapter(queryClient) {
|
export function createQueryCacheAdapter(queryClient, dependencies = {}) {
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
read(key) {
|
read(key) {
|
||||||
try {
|
try {
|
||||||
return { ok: true, value: queryClient.getQueryData(key) };
|
return { ok: true, value: queryClient.getQueryData(key) };
|
||||||
} catch {
|
} catch {
|
||||||
return cacheFailure("read", key);
|
return cacheFailure("read", key, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
write(key, value) {
|
write(key, value) {
|
||||||
@@ -45,7 +71,7 @@ export function createQueryCacheAdapter(queryClient) {
|
|||||||
queryClient.setQueryData(key, structuredClone(value));
|
queryClient.setQueryData(key, structuredClone(value));
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
} catch {
|
} catch {
|
||||||
return cacheFailure("write", key);
|
return cacheFailure("write", key, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
async invalidate(namespace) {
|
async invalidate(namespace) {
|
||||||
@@ -53,15 +79,31 @@ export function createQueryCacheAdapter(queryClient) {
|
|||||||
await queryClient.invalidateQueries({ queryKey: namespace, exact: false });
|
await queryClient.invalidateQueries({ queryKey: namespace, exact: false });
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
} catch {
|
} catch {
|
||||||
return cacheFailure("invalidate", namespace);
|
return cacheFailure("invalidate", namespace, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param {string} phase @param {readonly unknown[]} key */
|
/**
|
||||||
function cacheFailure(phase, key) {
|
* @param {string} phase
|
||||||
|
* @param {readonly unknown[]} key
|
||||||
|
* @param {import("../../application/ports/diagnostics-port.js").DiagnosticsPort | undefined} diagnostics
|
||||||
|
*/
|
||||||
|
function cacheFailure(phase, key, diagnostics) {
|
||||||
const namespace = typeof key[0] === "string" ? key[0] : "unknown";
|
const namespace = typeof key[0] === "string" ? key[0] : "unknown";
|
||||||
|
try {
|
||||||
|
diagnostics?.record({
|
||||||
|
level: "warn",
|
||||||
|
eventId: "cache.operation.failed",
|
||||||
|
context: {
|
||||||
|
operation: phase,
|
||||||
|
error_kind: "QUERY_CACHE_FAILURE",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Cache behavior remains independent from diagnostics.
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
ok: /** @type {false} */ (false),
|
ok: /** @type {false} */ (false),
|
||||||
error: createFailure("QUERY_CACHE_FAILURE", "QUERY_CACHE", 0, {
|
error: createFailure("QUERY_CACHE_FAILURE", "QUERY_CACHE", 0, {
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ import { getStorageDefinition } from "../../contracts/storage-keys.js";
|
|||||||
* @param {{
|
* @param {{
|
||||||
* localStorage?: Storage,
|
* localStorage?: Storage,
|
||||||
* sessionStorage?: Storage,
|
* sessionStorage?: Storage,
|
||||||
* now?: () => number
|
* now?: () => number,
|
||||||
|
* diagnostics?: import("../../application/ports/diagnostics-port.js").DiagnosticsPort
|
||||||
* }} [dependencies]
|
* }} [dependencies]
|
||||||
* @returns {import("../../application/ports/storage-port.js").StoragePort}
|
* @returns {import("../../application/ports/storage-port.js").StoragePort}
|
||||||
*/
|
*/
|
||||||
@@ -26,7 +27,7 @@ export function createBrowserStorageAdapter(dependencies = {}) {
|
|||||||
try {
|
try {
|
||||||
definition = getStorageDefinition(logicalName);
|
definition = getStorageDefinition(logicalName);
|
||||||
} catch {
|
} catch {
|
||||||
return unavailable("read", logicalName);
|
return unavailable("read", logicalName, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
|
|
||||||
const backend = backendFor(definition.backend);
|
const backend = backendFor(definition.backend);
|
||||||
@@ -50,7 +51,7 @@ export function createBrowserStorageAdapter(dependencies = {}) {
|
|||||||
}
|
}
|
||||||
return { ok: true, value: structuredClone(envelope.value) };
|
return { ok: true, value: structuredClone(envelope.value) };
|
||||||
} catch {
|
} catch {
|
||||||
return unavailable("read", logicalName);
|
return unavailable("read", logicalName, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -59,7 +60,7 @@ export function createBrowserStorageAdapter(dependencies = {}) {
|
|||||||
try {
|
try {
|
||||||
definition = getStorageDefinition(logicalName);
|
definition = getStorageDefinition(logicalName);
|
||||||
} catch {
|
} catch {
|
||||||
return unavailable("write", logicalName);
|
return unavailable("write", logicalName, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
|
|
||||||
const expiresAt =
|
const expiresAt =
|
||||||
@@ -82,12 +83,24 @@ export function createBrowserStorageAdapter(dependencies = {}) {
|
|||||||
|
|
||||||
if (definition.quotaFallback === "memory") {
|
if (definition.quotaFallback === "memory") {
|
||||||
memory.set(definition.physicalKey, structuredClone(value));
|
memory.set(definition.physicalKey, structuredClone(value));
|
||||||
|
recordStorageFailure(
|
||||||
|
dependencies.diagnostics,
|
||||||
|
"write",
|
||||||
|
logicalName,
|
||||||
|
quota,
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
ok: false,
|
ok: false,
|
||||||
error: storageFailure(quota, "write", logicalName),
|
error: storageFailure(quota, "write", logicalName),
|
||||||
fallback: "memory",
|
fallback: "memory",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
recordStorageFailure(
|
||||||
|
dependencies.diagnostics,
|
||||||
|
"write",
|
||||||
|
logicalName,
|
||||||
|
quota,
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
ok: false,
|
ok: false,
|
||||||
error: storageFailure(quota, "write", logicalName),
|
error: storageFailure(quota, "write", logicalName),
|
||||||
@@ -101,14 +114,14 @@ export function createBrowserStorageAdapter(dependencies = {}) {
|
|||||||
try {
|
try {
|
||||||
definition = getStorageDefinition(logicalName);
|
definition = getStorageDefinition(logicalName);
|
||||||
} catch {
|
} catch {
|
||||||
return unavailable("remove", logicalName);
|
return unavailable("remove", logicalName, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
backendFor(definition.backend)?.removeItem(definition.physicalKey);
|
backendFor(definition.backend)?.removeItem(definition.physicalKey);
|
||||||
memory.delete(definition.physicalKey);
|
memory.delete(definition.physicalKey);
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
} catch {
|
} catch {
|
||||||
return unavailable("remove", logicalName);
|
return unavailable("remove", logicalName, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -128,10 +141,38 @@ function storageFailure(quota, phase, logicalName) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param {string} phase @param {string} logicalName */
|
/**
|
||||||
function unavailable(phase, logicalName) {
|
* @param {string} phase
|
||||||
|
* @param {string} logicalName
|
||||||
|
* @param {import("../../application/ports/diagnostics-port.js").DiagnosticsPort | undefined} diagnostics
|
||||||
|
*/
|
||||||
|
function unavailable(phase, logicalName, diagnostics) {
|
||||||
|
recordStorageFailure(diagnostics, phase, logicalName, false);
|
||||||
return {
|
return {
|
||||||
ok: /** @type {false} */ (false),
|
ok: /** @type {false} */ (false),
|
||||||
error: storageFailure(false, phase, logicalName),
|
error: storageFailure(false, phase, logicalName),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {import("../../application/ports/diagnostics-port.js").DiagnosticsPort | undefined} diagnostics
|
||||||
|
* @param {string} phase
|
||||||
|
* @param {string} logicalName
|
||||||
|
* @param {boolean} quota
|
||||||
|
*/
|
||||||
|
function recordStorageFailure(diagnostics, phase, logicalName, quota) {
|
||||||
|
try {
|
||||||
|
diagnostics?.record({
|
||||||
|
level: "warn",
|
||||||
|
eventId: "storage.operation.failed",
|
||||||
|
context: {
|
||||||
|
operation: `${phase}:${logicalName}`,
|
||||||
|
error_kind: quota
|
||||||
|
? "STORAGE_QUOTA_EXCEEDED"
|
||||||
|
: "STORAGE_UNAVAILABLE",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Storage behavior remains independent from diagnostics.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,14 @@
|
|||||||
import { projectTelemetryEvent } from "../../contracts/telemetry.js";
|
import { projectTelemetryEvent } from "../../contracts/telemetry.js";
|
||||||
|
import { queueSizeBucket } from "../../contracts/diagnostics.js";
|
||||||
|
|
||||||
export const noOpTelemetry = Object.freeze({
|
export const noOpTelemetry = Object.freeze({
|
||||||
emit: () => {},
|
emit: () => {},
|
||||||
|
flush: async () => {},
|
||||||
|
pendingCount: () => 0,
|
||||||
|
droppedCount: () => 0,
|
||||||
|
dropReasons: () => Object.freeze({}),
|
||||||
|
deliveryEvidence: () => null,
|
||||||
|
dispose: () => {},
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -10,22 +17,20 @@ export const noOpTelemetry = Object.freeze({
|
|||||||
* endpoint?: string,
|
* endpoint?: string,
|
||||||
* fetcher?: typeof fetch,
|
* fetcher?: typeof fetch,
|
||||||
* maxQueue?: number,
|
* maxQueue?: number,
|
||||||
* schedule?: (callback: () => void) => void
|
* schedule?: (callback: () => void) => void,
|
||||||
|
* now?: () => number,
|
||||||
|
* onDrop?: (event: Readonly<Record<string, unknown>>) => void,
|
||||||
|
* lifecycle?: Pick<EventTarget, "addEventListener" | "removeEventListener">
|
||||||
* }} options
|
* }} options
|
||||||
*/
|
*/
|
||||||
export function createTelemetryAdapter(options) {
|
export function createTelemetryAdapter(options) {
|
||||||
if (!options.enabled || !options.endpoint) {
|
if (!options.enabled || !options.endpoint) {
|
||||||
return Object.freeze({
|
return noOpTelemetry;
|
||||||
...noOpTelemetry,
|
|
||||||
flush: async () => {},
|
|
||||||
pendingCount: () => 0,
|
|
||||||
droppedCount: () => 0,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const endpoint = /** @type {string} */ (options.endpoint);
|
const endpoint = /** @type {string} */ (options.endpoint);
|
||||||
const fetcher = options.fetcher ?? fetch;
|
const fetcher = options.fetcher ?? fetch;
|
||||||
const maxQueue = options.maxQueue ?? 100;
|
const maxQueue = Math.max(1, options.maxQueue ?? 100);
|
||||||
const schedule = options.schedule ?? queueMicrotask;
|
const schedule = options.schedule ?? queueMicrotask;
|
||||||
const queue =
|
const queue =
|
||||||
/** @type {Array<{eventName: string, attributes: Readonly<Record<string, unknown>>}>} */ (
|
/** @type {Array<{eventName: string, attributes: Readonly<Record<string, unknown>>}>} */ (
|
||||||
@@ -34,18 +39,63 @@ export function createTelemetryAdapter(options) {
|
|||||||
let scheduled = false;
|
let scheduled = false;
|
||||||
let flushing = false;
|
let flushing = false;
|
||||||
let dropped = 0;
|
let dropped = 0;
|
||||||
|
const dropReasons = new Map();
|
||||||
|
let lastDeliveryEvidence =
|
||||||
|
/** @type {Readonly<Record<string, unknown>> | null} */ (null);
|
||||||
|
const lifecycle =
|
||||||
|
options.lifecycle ??
|
||||||
|
(typeof globalThis.addEventListener === "function" &&
|
||||||
|
typeof globalThis.removeEventListener === "function"
|
||||||
|
? globalThis
|
||||||
|
: undefined);
|
||||||
|
|
||||||
|
/** @param {string} reason @param {number} count */
|
||||||
|
function recordDrop(reason, count = 1) {
|
||||||
|
const safeReason =
|
||||||
|
{
|
||||||
|
"queue-full": "queue-full",
|
||||||
|
"sink-failure": "sink-failure",
|
||||||
|
"serialization-failure": "serialization-failure",
|
||||||
|
"unknown-attributes": "invalid-context",
|
||||||
|
"invalid-attribute-value": "invalid-context",
|
||||||
|
"missing-required-attributes": "invalid-context",
|
||||||
|
"unregistered-event": "invalid-event",
|
||||||
|
}[reason] ?? "invalid-event";
|
||||||
|
dropped += count;
|
||||||
|
dropReasons.set(safeReason, (dropReasons.get(safeReason) ?? 0) + count);
|
||||||
|
const internal = projectTelemetryEvent(
|
||||||
|
"telemetry.delivery.dropped",
|
||||||
|
{
|
||||||
|
reason: safeReason,
|
||||||
|
queue_size_bucket: queueSizeBucket(queue.length),
|
||||||
|
},
|
||||||
|
options.now,
|
||||||
|
);
|
||||||
|
if (internal.success) {
|
||||||
|
lastDeliveryEvidence = internal.event;
|
||||||
|
try {
|
||||||
|
options.onDrop?.(internal.event);
|
||||||
|
} catch {
|
||||||
|
// Drop observers are deliberately nonrecursive.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** @param {string} eventName @param {Record<string, unknown>} attributes */
|
/** @param {string} eventName @param {Record<string, unknown>} attributes */
|
||||||
function emit(eventName, attributes) {
|
function emit(eventName, attributes) {
|
||||||
const projected = projectTelemetryEvent(eventName, attributes);
|
const projected = projectTelemetryEvent(
|
||||||
|
eventName,
|
||||||
|
attributes,
|
||||||
|
options.now,
|
||||||
|
);
|
||||||
if (!projected.success) {
|
if (!projected.success) {
|
||||||
dropped += 1;
|
recordDrop(projected.reason);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (queue.length >= maxQueue) {
|
if (queue.length >= maxQueue) {
|
||||||
queue.shift();
|
queue.shift();
|
||||||
dropped += 1;
|
recordDrop("queue-full");
|
||||||
}
|
}
|
||||||
queue.push(projected.event);
|
queue.push(projected.event);
|
||||||
|
|
||||||
@@ -69,19 +119,32 @@ export function createTelemetryAdapter(options) {
|
|||||||
body: JSON.stringify({ events: batch }),
|
body: JSON.stringify({ events: batch }),
|
||||||
keepalive: true,
|
keepalive: true,
|
||||||
});
|
});
|
||||||
if (!response.ok) dropped += batch.length;
|
if (!response.ok) recordDrop("sink-failure", batch.length);
|
||||||
} catch {
|
} catch {
|
||||||
dropped += batch.length;
|
recordDrop("sink-failure", batch.length);
|
||||||
} finally {
|
} finally {
|
||||||
flushing = false;
|
flushing = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const flushBeforePageExit = () => {
|
||||||
|
void flush();
|
||||||
|
};
|
||||||
|
lifecycle?.addEventListener("pagehide", flushBeforePageExit);
|
||||||
|
|
||||||
|
function dispose() {
|
||||||
|
lifecycle?.removeEventListener("pagehide", flushBeforePageExit);
|
||||||
|
}
|
||||||
|
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
emit,
|
emit,
|
||||||
flush,
|
flush,
|
||||||
pendingCount: () => queue.length,
|
pendingCount: () => queue.length,
|
||||||
droppedCount: () => dropped,
|
droppedCount: () => dropped,
|
||||||
|
dropReasons: () => Object.freeze(Object.fromEntries(dropReasons)),
|
||||||
|
deliveryEvidence: () =>
|
||||||
|
lastDeliveryEvidence ? structuredClone(lastDeliveryEvidence) : null,
|
||||||
|
dispose,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import type {
|
|||||||
ApplicationApi,
|
ApplicationApi,
|
||||||
ColorSchemePreference,
|
ColorSchemePreference,
|
||||||
RenderFailureReport,
|
RenderFailureReport,
|
||||||
|
RouteChangedReport,
|
||||||
} from "./ports/in/application-api.js";
|
} from "./ports/in/application-api.js";
|
||||||
import type { ApplicationOutputPorts } from "./ports/out/application-output-ports.js";
|
import type { ApplicationOutputPorts } from "./ports/out/application-output-ports.js";
|
||||||
import { decideChunkRecovery } from "./use-cases/decide-chunk-recovery.js";
|
import { decideChunkRecovery } from "./use-cases/decide-chunk-recovery.js";
|
||||||
@@ -43,7 +44,20 @@ export function createApplication(
|
|||||||
const diagnostics = Object.freeze({
|
const diagnostics = Object.freeze({
|
||||||
reportRenderFailure(report: RenderFailureReport) {
|
reportRenderFailure(report: RenderFailureReport) {
|
||||||
try {
|
try {
|
||||||
outputPorts.diagnostics.emit("ui.render.failed", {
|
outputPorts.diagnostics.record({
|
||||||
|
level: "error",
|
||||||
|
eventId: "ui.render.failed",
|
||||||
|
context: {
|
||||||
|
route_id: report.routeId,
|
||||||
|
build_id: report.buildId,
|
||||||
|
component_boundary: report.boundaryName,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Diagnostics are best-effort and cannot become an application failure.
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
outputPorts.telemetry.emit("ui.render.failed", {
|
||||||
route_id: report.routeId,
|
route_id: report.routeId,
|
||||||
build_id: report.buildId,
|
build_id: report.buildId,
|
||||||
component_boundary: report.boundaryName,
|
component_boundary: report.boundaryName,
|
||||||
@@ -52,6 +66,20 @@ export function createApplication(
|
|||||||
// Diagnostics are best-effort and cannot become an application failure.
|
// Diagnostics are best-effort and cannot become an application failure.
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
reportRouteChanged(report: RouteChangedReport) {
|
||||||
|
try {
|
||||||
|
outputPorts.diagnostics.record({
|
||||||
|
level: "info",
|
||||||
|
eventId: "route.changed",
|
||||||
|
context: {
|
||||||
|
route_id: report.routeId,
|
||||||
|
build_id: report.buildId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Diagnostics are best-effort and cannot become navigation failure.
|
||||||
|
}
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const runtime = Object.freeze({
|
const runtime = Object.freeze({
|
||||||
@@ -74,6 +102,37 @@ export function createApplication(
|
|||||||
try {
|
try {
|
||||||
const current = await outputPorts.releaseInfo.getCurrent();
|
const current = await outputPorts.releaseInfo.getCurrent();
|
||||||
const active = await outputPorts.releaseInfo.refresh();
|
const active = await outputPorts.releaseInfo.refresh();
|
||||||
|
if (
|
||||||
|
current.buildId !== active.buildId ||
|
||||||
|
current.releaseId !== active.releaseId
|
||||||
|
) {
|
||||||
|
const mismatchKind =
|
||||||
|
current.buildId !== active.buildId
|
||||||
|
? "BUILD_MISMATCH"
|
||||||
|
: "RELEASE_MISMATCH";
|
||||||
|
try {
|
||||||
|
outputPorts.diagnostics.record({
|
||||||
|
level: "warn",
|
||||||
|
eventId: "release.mismatch.detected",
|
||||||
|
context: {
|
||||||
|
build_id: current.buildId,
|
||||||
|
active_release_id: active.releaseId,
|
||||||
|
mismatch_kind: mismatchKind,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Recovery remains independent from diagnostics.
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
outputPorts.telemetry.emit("release.mismatch.detected", {
|
||||||
|
build_id: current.buildId,
|
||||||
|
active_release_id: active.releaseId,
|
||||||
|
mismatch_kind: mismatchKind,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Recovery remains independent from telemetry.
|
||||||
|
}
|
||||||
|
}
|
||||||
if (!active.routeChunks[input.chunkId]) {
|
if (!active.routeChunks[input.chunkId]) {
|
||||||
return {
|
return {
|
||||||
action: "support" as const,
|
action: "support" as const,
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import type { DiagnosticRecordInput } from "../../contracts/diagnostics.js";
|
||||||
|
|
||||||
|
export type DiagnosticsPort = Readonly<{
|
||||||
|
record(input: DiagnosticRecordInput): void;
|
||||||
|
}>;
|
||||||
@@ -11,6 +11,11 @@ export type RenderFailureReport = Readonly<{
|
|||||||
boundaryName: "route" | "feature";
|
boundaryName: "route" | "feature";
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
|
export type RouteChangedReport = Readonly<{
|
||||||
|
routeId: string;
|
||||||
|
buildId: string;
|
||||||
|
}>;
|
||||||
|
|
||||||
export type ReleaseSummary = Readonly<{
|
export type ReleaseSummary = Readonly<{
|
||||||
buildId: string;
|
buildId: string;
|
||||||
releaseId: string;
|
releaseId: string;
|
||||||
@@ -34,6 +39,7 @@ export type ApplicationApi = Readonly<{
|
|||||||
}>;
|
}>;
|
||||||
diagnostics: Readonly<{
|
diagnostics: Readonly<{
|
||||||
reportRenderFailure(report: RenderFailureReport): void;
|
reportRenderFailure(report: RenderFailureReport): void;
|
||||||
|
reportRouteChanged(report: RouteChangedReport): void;
|
||||||
}>;
|
}>;
|
||||||
runtime: Readonly<{
|
runtime: Readonly<{
|
||||||
getReleaseSummary(): Promise<ReleaseSummary>;
|
getReleaseSummary(): Promise<ReleaseSummary>;
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { AuthSessionPort } from "../auth-session-port.js";
|
|||||||
import type { ReleaseInfoPort } from "../release-info-port.js";
|
import type { ReleaseInfoPort } from "../release-info-port.js";
|
||||||
import type { StoragePort } from "../storage-port.js";
|
import type { StoragePort } from "../storage-port.js";
|
||||||
import type { TelemetryPort } from "../telemetry-port.js";
|
import type { TelemetryPort } from "../telemetry-port.js";
|
||||||
|
import type { DiagnosticsPort } from "../diagnostics-port.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Capabilities required by application use cases. Implementations live in
|
* Capabilities required by application use cases. Implementations live in
|
||||||
@@ -13,7 +14,8 @@ export type ApplicationOutputPorts = Readonly<{
|
|||||||
"getState" | "subscribe" | "beginSignIn" | "signOut" | "recover"
|
"getState" | "subscribe" | "beginSignIn" | "signOut" | "recover"
|
||||||
>;
|
>;
|
||||||
preferences: StoragePort;
|
preferences: StoragePort;
|
||||||
diagnostics: TelemetryPort;
|
diagnostics: DiagnosticsPort;
|
||||||
|
telemetry: TelemetryPort;
|
||||||
releaseInfo: ReleaseInfoPort;
|
releaseInfo: ReleaseInfoPort;
|
||||||
navigation: Readonly<{ reload(): void }>;
|
navigation: Readonly<{ reload(): void }>;
|
||||||
}>;
|
}>;
|
||||||
|
|||||||
@@ -9,3 +9,4 @@ export type { QueryCachePort } from "../query-cache-port.js";
|
|||||||
export type { ReleaseInfoPort } from "../release-info-port.js";
|
export type { ReleaseInfoPort } from "../release-info-port.js";
|
||||||
export type { StoragePort } from "../storage-port.js";
|
export type { StoragePort } from "../storage-port.js";
|
||||||
export type { TelemetryPort } from "../telemetry-port.js";
|
export type { TelemetryPort } from "../telemetry-port.js";
|
||||||
|
export type { DiagnosticsPort } from "../diagnostics-port.js";
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
/**
|
|
||||||
* @typedef {{ emit(eventName: string, attributes: Record<string, unknown>): void }} TelemetryPort
|
|
||||||
*/
|
|
||||||
|
|
||||||
export {};
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import type { TelemetryEventName } from "../../contracts/telemetry.js";
|
||||||
|
|
||||||
|
export type { TelemetryEventName };
|
||||||
|
|
||||||
|
export type TelemetryPort = Readonly<{
|
||||||
|
emit(
|
||||||
|
eventName: TelemetryEventName,
|
||||||
|
attributes: Record<string, unknown>,
|
||||||
|
): void;
|
||||||
|
}>;
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { createRoot } from "react-dom/client";
|
import { createRoot } from "react-dom/client";
|
||||||
|
|
||||||
|
import { recordBootFailure } from "../adapters/diagnostics/bounded-diagnostics.js";
|
||||||
import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.jsx";
|
import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.jsx";
|
||||||
import { createRuntimeComposition } from "./create-runtime-composition.js";
|
import { createRuntimeComposition } from "./create-runtime-composition.js";
|
||||||
import { initializeColorScheme } from "./initialize-color-scheme.js";
|
import { initializeColorScheme } from "./initialize-color-scheme.js";
|
||||||
@@ -27,6 +28,7 @@ async function boot() {
|
|||||||
? error.safe
|
? error.safe
|
||||||
: { supportReference: "boot:unknown" };
|
: { supportReference: "boot:unknown" };
|
||||||
|
|
||||||
|
recordBootFailure(error, safe);
|
||||||
root.render(<BootErrorShell {...safe} />);
|
root.render(<BootErrorShell {...safe} />);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
createUnavailableSessionAdapter,
|
createUnavailableSessionAdapter,
|
||||||
} from "../adapters/auth/external-session-adapter.js";
|
} from "../adapters/auth/external-session-adapter.js";
|
||||||
import { createHttpClient } from "../adapters/http/client.js";
|
import { createHttpClient } from "../adapters/http/client.js";
|
||||||
|
import { createDiagnosticsAdapter } from "../adapters/diagnostics/bounded-diagnostics.js";
|
||||||
import {
|
import {
|
||||||
createQueryClient,
|
createQueryClient,
|
||||||
} from "../adapters/query-cache/tanstack-query-cache.js";
|
} from "../adapters/query-cache/tanstack-query-cache.js";
|
||||||
@@ -53,6 +54,8 @@ function storageOrUndefined(value) {
|
|||||||
* fetcher?: typeof fetch,
|
* fetcher?: typeof fetch,
|
||||||
* clock?: import("../application/ports/clock-port.js").ClockPort,
|
* clock?: import("../application/ports/clock-port.js").ClockPort,
|
||||||
* scheduler?: Parameters<typeof createHttpClient>[0]["scheduler"]
|
* scheduler?: Parameters<typeof createHttpClient>[0]["scheduler"]
|
||||||
|
* diagnostics?: Parameters<typeof createHttpClient>[0]["diagnostics"],
|
||||||
|
* telemetry?: Parameters<typeof createHttpClient>[0]["telemetry"]
|
||||||
* }} context
|
* }} context
|
||||||
*/
|
*/
|
||||||
export function createRuntimeHttpClient(context, contract = {}) {
|
export function createRuntimeHttpClient(context, contract = {}) {
|
||||||
@@ -64,6 +67,8 @@ export function createRuntimeHttpClient(context, contract = {}) {
|
|||||||
fetcher: context.fetcher,
|
fetcher: context.fetcher,
|
||||||
clock: context.clock,
|
clock: context.clock,
|
||||||
scheduler: context.scheduler,
|
scheduler: context.scheduler,
|
||||||
|
diagnostics: context.diagnostics,
|
||||||
|
telemetry: context.telemetry,
|
||||||
...contract,
|
...contract,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -86,15 +91,28 @@ export async function createRuntimeAdapters(context) {
|
|||||||
: externalOwner
|
: externalOwner
|
||||||
? createExternalAuthSessionAdapter(externalOwner)
|
? createExternalAuthSessionAdapter(externalOwner)
|
||||||
: createUnavailableSessionAdapter();
|
: createUnavailableSessionAdapter();
|
||||||
const queryClient = createQueryClient();
|
const diagnostics = createDiagnosticsAdapter();
|
||||||
const storage = createBrowserStorageAdapter({
|
|
||||||
localStorage: storageOrUndefined(host.localStorage),
|
|
||||||
sessionStorage: storageOrUndefined(host.sessionStorage),
|
|
||||||
});
|
|
||||||
const telemetry = createTelemetryAdapter({
|
const telemetry = createTelemetryAdapter({
|
||||||
enabled: config.TELEMETRY_ENABLED,
|
enabled: config.TELEMETRY_ENABLED,
|
||||||
endpoint: config.TELEMETRY_ENDPOINT,
|
endpoint: config.TELEMETRY_ENDPOINT,
|
||||||
fetcher: context.fetcher,
|
fetcher: context.fetcher,
|
||||||
|
onDrop(event) {
|
||||||
|
const attributes =
|
||||||
|
event.attributes && typeof event.attributes === "object"
|
||||||
|
? event.attributes
|
||||||
|
: {};
|
||||||
|
diagnostics.record({
|
||||||
|
level: "warn",
|
||||||
|
eventId: "telemetry.delivery.dropped",
|
||||||
|
context: /** @type {Record<string, unknown>} */ (attributes),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const queryClient = createQueryClient({ diagnostics });
|
||||||
|
const storage = createBrowserStorageAdapter({
|
||||||
|
localStorage: storageOrUndefined(host.localStorage),
|
||||||
|
sessionStorage: storageOrUndefined(host.sessionStorage),
|
||||||
|
diagnostics,
|
||||||
});
|
});
|
||||||
const releaseInfo = Object.freeze({
|
const releaseInfo = Object.freeze({
|
||||||
async getCurrent() {
|
async getCurrent() {
|
||||||
@@ -125,6 +143,8 @@ export async function createRuntimeAdapters(context) {
|
|||||||
runtime: context.runtime,
|
runtime: context.runtime,
|
||||||
authSession,
|
authSession,
|
||||||
fetcher: context.fetcher,
|
fetcher: context.fetcher,
|
||||||
|
diagnostics,
|
||||||
|
telemetry,
|
||||||
},
|
},
|
||||||
contract,
|
contract,
|
||||||
),
|
),
|
||||||
@@ -134,7 +154,8 @@ export async function createRuntimeAdapters(context) {
|
|||||||
outputPorts: Object.freeze({
|
outputPorts: Object.freeze({
|
||||||
session: authSession,
|
session: authSession,
|
||||||
preferences: storage,
|
preferences: storage,
|
||||||
diagnostics: telemetry,
|
diagnostics,
|
||||||
|
telemetry,
|
||||||
releaseInfo,
|
releaseInfo,
|
||||||
navigation,
|
navigation,
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -0,0 +1,183 @@
|
|||||||
|
export const DIAGNOSTIC_LEVELS = Object.freeze([
|
||||||
|
"debug",
|
||||||
|
"info",
|
||||||
|
"warn",
|
||||||
|
"error",
|
||||||
|
] as const);
|
||||||
|
export type DiagnosticLevel = (typeof DIAGNOSTIC_LEVELS)[number];
|
||||||
|
|
||||||
|
export const DIAGNOSTIC_EVENT_REGISTRY = Object.freeze({
|
||||||
|
"app.boot.failed": Object.freeze({ level: "error" }),
|
||||||
|
"http.request.completed": Object.freeze({ level: "info" }),
|
||||||
|
"cache.operation.failed": Object.freeze({ level: "warn" }),
|
||||||
|
"storage.operation.failed": Object.freeze({ level: "warn" }),
|
||||||
|
"route.changed": Object.freeze({ level: "info" }),
|
||||||
|
"ui.render.failed": Object.freeze({ level: "error" }),
|
||||||
|
"release.mismatch.detected": Object.freeze({ level: "warn" }),
|
||||||
|
"telemetry.delivery.dropped": Object.freeze({ level: "warn" }),
|
||||||
|
});
|
||||||
|
export type DiagnosticEventId = keyof typeof DIAGNOSTIC_EVENT_REGISTRY;
|
||||||
|
|
||||||
|
export const DIAGNOSTIC_CONTEXT_ALLOWLIST = Object.freeze([
|
||||||
|
"app_version",
|
||||||
|
"build_id",
|
||||||
|
"release_id",
|
||||||
|
"active_release_id",
|
||||||
|
"config_schema_version",
|
||||||
|
"api_contract_version",
|
||||||
|
"route_id",
|
||||||
|
"operation_id",
|
||||||
|
"correlation_id",
|
||||||
|
"error_kind",
|
||||||
|
"outcome",
|
||||||
|
"http_status_group",
|
||||||
|
"attempt_count_bucket",
|
||||||
|
"duration_bucket",
|
||||||
|
"component_boundary",
|
||||||
|
"mismatch_kind",
|
||||||
|
"operation",
|
||||||
|
"reason",
|
||||||
|
"queue_size_bucket",
|
||||||
|
] as const);
|
||||||
|
export type DiagnosticContextKey =
|
||||||
|
(typeof DIAGNOSTIC_CONTEXT_ALLOWLIST)[number];
|
||||||
|
export type DiagnosticContext = Readonly<
|
||||||
|
Partial<Record<DiagnosticContextKey, string | number | boolean>>
|
||||||
|
>;
|
||||||
|
|
||||||
|
export type DiagnosticRecordInput = Readonly<{
|
||||||
|
level: DiagnosticLevel;
|
||||||
|
eventId: DiagnosticEventId;
|
||||||
|
context?: Readonly<Record<string, unknown>>;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export type DiagnosticRecord = Readonly<{
|
||||||
|
level: DiagnosticLevel;
|
||||||
|
eventId: DiagnosticEventId;
|
||||||
|
timestamp: string;
|
||||||
|
context: DiagnosticContext;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
const SAFE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,63}$/;
|
||||||
|
|
||||||
|
function projectDiagnosticRecordUnsafe(
|
||||||
|
input: DiagnosticRecordInput,
|
||||||
|
now: () => number = Date.now,
|
||||||
|
):
|
||||||
|
| Readonly<{ success: true; record: DiagnosticRecord }>
|
||||||
|
| Readonly<{ success: false; reason: string }> {
|
||||||
|
if (!Object.hasOwn(DIAGNOSTIC_EVENT_REGISTRY, input.eventId)) {
|
||||||
|
return { success: false, reason: "unregistered-event" };
|
||||||
|
}
|
||||||
|
if (!DIAGNOSTIC_LEVELS.includes(input.level)) {
|
||||||
|
return { success: false, reason: "invalid-level" };
|
||||||
|
}
|
||||||
|
const contextEntries = Object.entries(input.context ?? {});
|
||||||
|
if (contextEntries.length > DIAGNOSTIC_CONTEXT_ALLOWLIST.length) {
|
||||||
|
return { success: false, reason: "invalid-context" };
|
||||||
|
}
|
||||||
|
const projected: Partial<
|
||||||
|
Record<DiagnosticContextKey, string | number | boolean>
|
||||||
|
> = {};
|
||||||
|
for (const [key, value] of contextEntries) {
|
||||||
|
if (
|
||||||
|
!DIAGNOSTIC_CONTEXT_ALLOWLIST.includes(key as DiagnosticContextKey)
|
||||||
|
) {
|
||||||
|
return { success: false, reason: "unknown-context" };
|
||||||
|
}
|
||||||
|
if (typeof value === "string") {
|
||||||
|
if (!SAFE_VALUE.test(value)) {
|
||||||
|
return { success: false, reason: "invalid-context" };
|
||||||
|
}
|
||||||
|
projected[key as DiagnosticContextKey] = value;
|
||||||
|
} else if (typeof value === "number" && Number.isFinite(value)) {
|
||||||
|
projected[key as DiagnosticContextKey] = value;
|
||||||
|
} else if (typeof value === "boolean") {
|
||||||
|
projected[key as DiagnosticContextKey] = value;
|
||||||
|
} else {
|
||||||
|
return { success: false, reason: "invalid-context" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let timestamp: string;
|
||||||
|
try {
|
||||||
|
timestamp = new Date(now()).toISOString();
|
||||||
|
} catch {
|
||||||
|
timestamp = new Date(0).toISOString();
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
record: Object.freeze({
|
||||||
|
level: input.level,
|
||||||
|
eventId: input.eventId,
|
||||||
|
timestamp,
|
||||||
|
context: Object.freeze(projected),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function projectDiagnosticRecord(
|
||||||
|
input: DiagnosticRecordInput,
|
||||||
|
now: () => number = Date.now,
|
||||||
|
): ReturnType<typeof projectDiagnosticRecordUnsafe> {
|
||||||
|
try {
|
||||||
|
return projectDiagnosticRecordUnsafe(input, now);
|
||||||
|
} catch {
|
||||||
|
return { success: false, reason: "serialization-failure" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function safeErrorKind(error: unknown): string {
|
||||||
|
try {
|
||||||
|
if (error && typeof error === "object") {
|
||||||
|
const record = error as Readonly<Record<string, unknown>>;
|
||||||
|
if (
|
||||||
|
typeof record.kind === "string" &&
|
||||||
|
/^[A-Z][A-Z0-9_]{0,63}$/.test(record.kind)
|
||||||
|
) {
|
||||||
|
return record.kind;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
typeof record.name === "string" &&
|
||||||
|
/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(record.name)
|
||||||
|
) {
|
||||||
|
const normalized = record.name
|
||||||
|
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
|
||||||
|
.toUpperCase();
|
||||||
|
return /^[A-Z][A-Z0-9_]{0,63}$/.test(normalized)
|
||||||
|
? normalized
|
||||||
|
: "UNKNOWN_FAILURE";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return "UNKNOWN_FAILURE";
|
||||||
|
}
|
||||||
|
return "UNKNOWN_FAILURE";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function statusGroup(status: number | undefined): string {
|
||||||
|
return typeof status === "number" && Number.isFinite(status)
|
||||||
|
? `${Math.max(0, Math.min(9, Math.floor(status / 100)))}xx`
|
||||||
|
: "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function attemptBucket(attemptCount: number): string {
|
||||||
|
if (attemptCount <= 1) return "1";
|
||||||
|
if (attemptCount === 2) return "2";
|
||||||
|
if (attemptCount <= 4) return "3-4";
|
||||||
|
return "5+";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function durationBucket(durationMs: number): string {
|
||||||
|
if (!Number.isFinite(durationMs) || durationMs < 0) return "unknown";
|
||||||
|
if (durationMs < 100) return "lt100ms";
|
||||||
|
if (durationMs < 500) return "100-499ms";
|
||||||
|
if (durationMs < 2_000) return "500-1999ms";
|
||||||
|
return "gte2000ms";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function queueSizeBucket(size: number): string {
|
||||||
|
if (size <= 0) return "0";
|
||||||
|
if (size <= 10) return "1-10";
|
||||||
|
if (size <= 50) return "11-50";
|
||||||
|
return "51+";
|
||||||
|
}
|
||||||
Vendored
+36
@@ -0,0 +1,36 @@
|
|||||||
|
export type TelemetryEventName =
|
||||||
|
| "app.boot.failed"
|
||||||
|
| "api.request.failed"
|
||||||
|
| "ui.render.failed"
|
||||||
|
| "release.mismatch.detected"
|
||||||
|
| "telemetry.delivery.dropped";
|
||||||
|
|
||||||
|
export type TelemetryDefinition = Readonly<{
|
||||||
|
eventName: TelemetryEventName;
|
||||||
|
trigger: string;
|
||||||
|
requiredAttributes: readonly string[];
|
||||||
|
optionalAttributes: readonly string[];
|
||||||
|
forbiddenAttributes: readonly string[];
|
||||||
|
sampling: string;
|
||||||
|
delivery: "best-effort";
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export type TelemetryEvent = Readonly<{
|
||||||
|
eventName: TelemetryEventName;
|
||||||
|
timestamp: string;
|
||||||
|
attributes: Readonly<Record<string, unknown>>;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export const TELEMETRY_ATTRIBUTE_ALLOWLIST: readonly string[];
|
||||||
|
export const TELEMETRY_FORBIDDEN_ATTRIBUTES: readonly string[];
|
||||||
|
export const TELEMETRY_REGISTRY: Readonly<
|
||||||
|
Record<TelemetryEventName, TelemetryDefinition>
|
||||||
|
>;
|
||||||
|
|
||||||
|
export function projectTelemetryEvent(
|
||||||
|
eventName: string,
|
||||||
|
attributes: Record<string, unknown>,
|
||||||
|
now?: () => number,
|
||||||
|
):
|
||||||
|
| Readonly<{ success: true; event: TelemetryEvent }>
|
||||||
|
| Readonly<{ success: false; reason: string }>;
|
||||||
@@ -81,7 +81,7 @@ export const TELEMETRY_REGISTRY = Object.freeze({
|
|||||||
"http_status_group",
|
"http_status_group",
|
||||||
"attempt_count_bucket",
|
"attempt_count_bucket",
|
||||||
"route_id",
|
"route_id",
|
||||||
]),
|
], ["operation_id", "duration_bucket"]),
|
||||||
"ui.render.failed": event("ui.render.failed", "React boundary catch", [
|
"ui.render.failed": event("ui.render.failed", "React boundary catch", [
|
||||||
"route_id",
|
"route_id",
|
||||||
"build_id",
|
"build_id",
|
||||||
@@ -101,11 +101,44 @@ export const TELEMETRY_REGISTRY = Object.freeze({
|
|||||||
),
|
),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const SAFE_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,63}$/;
|
||||||
|
const ATTRIBUTE_VALUE_POLICIES =
|
||||||
|
/** @type {Readonly<Record<string, (value: string) => boolean>>} */ (
|
||||||
|
Object.freeze({
|
||||||
|
route_id: (value) => /^[A-Z][A-Z0-9_]{0,63}$/.test(value),
|
||||||
|
operation_id: (value) => /^[A-Z][A-Z0-9_]{0,63}$/.test(value),
|
||||||
|
error_kind: (value) => /^[A-Z][A-Z0-9_]{0,63}$/.test(value),
|
||||||
|
http_status_group: (value) => /^(?:[1-5]xx|none)$/.test(value),
|
||||||
|
attempt_count_bucket: (value) => /^(?:1|2|3|3-4|5\+)$/.test(value),
|
||||||
|
duration_bucket: (value) =>
|
||||||
|
/^(?:lt100ms|100-499ms|500-1999ms|gte2000ms|unknown)$/.test(
|
||||||
|
value,
|
||||||
|
),
|
||||||
|
component_boundary: (value) =>
|
||||||
|
/^(?:route|feature|boot)$/.test(value),
|
||||||
|
mismatch_kind: (value) => /^[A-Z][A-Z0-9_]{0,63}$/.test(value),
|
||||||
|
reason: (value) =>
|
||||||
|
/^(?:queue-full|sink-failure|invalid-event|invalid-context|serialization-failure)$/.test(
|
||||||
|
value,
|
||||||
|
),
|
||||||
|
queue_size_bucket: (value) =>
|
||||||
|
/^(?:0|1-10|11-50|51\+)$/.test(value),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
/** @param {string} key @param {unknown} value */
|
||||||
|
function validAttributeValue(key, value) {
|
||||||
|
if (typeof value !== "string") return false;
|
||||||
|
const policy = ATTRIBUTE_VALUE_POLICIES[key];
|
||||||
|
return policy ? policy(value) : SAFE_IDENTIFIER.test(value);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {string} eventName
|
* @param {string} eventName
|
||||||
* @param {Record<string, unknown>} attributes
|
* @param {Record<string, unknown>} attributes
|
||||||
|
* @param {() => number} [now]
|
||||||
*/
|
*/
|
||||||
export function projectTelemetryEvent(eventName, attributes) {
|
function projectTelemetryEventUnsafe(eventName, attributes, now = Date.now) {
|
||||||
const registry =
|
const registry =
|
||||||
/** @type {Record<string, (typeof TELEMETRY_REGISTRY)[keyof typeof TELEMETRY_REGISTRY]>} */ (
|
/** @type {Record<string, (typeof TELEMETRY_REGISTRY)[keyof typeof TELEMETRY_REGISTRY]>} */ (
|
||||||
TELEMETRY_REGISTRY
|
TELEMETRY_REGISTRY
|
||||||
@@ -118,13 +151,47 @@ export function projectTelemetryEvent(eventName, attributes) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const attributeKeys = Object.keys(attributes);
|
||||||
|
if (
|
||||||
|
attributeKeys.length >
|
||||||
|
TELEMETRY_ATTRIBUTE_ALLOWLIST.length +
|
||||||
|
TELEMETRY_FORBIDDEN_ATTRIBUTES.length
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
success: /** @type {false} */ (false),
|
||||||
|
reason: "invalid-attribute-value",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const unknown = attributeKeys.filter(
|
||||||
|
(key) =>
|
||||||
|
!TELEMETRY_ATTRIBUTE_ALLOWLIST.includes(key) &&
|
||||||
|
!TELEMETRY_FORBIDDEN_ATTRIBUTES.includes(key),
|
||||||
|
);
|
||||||
|
if (unknown.length > 0) {
|
||||||
|
return {
|
||||||
|
success: /** @type {false} */ (false),
|
||||||
|
reason: "unknown-attributes",
|
||||||
|
};
|
||||||
|
}
|
||||||
const projected = Object.fromEntries(
|
const projected = Object.fromEntries(
|
||||||
Object.entries(attributes).filter(
|
Object.entries(attributes).filter(
|
||||||
([key]) =>
|
([key, value]) =>
|
||||||
TELEMETRY_ATTRIBUTE_ALLOWLIST.includes(key) &&
|
TELEMETRY_ATTRIBUTE_ALLOWLIST.includes(key) &&
|
||||||
!TELEMETRY_FORBIDDEN_ATTRIBUTES.includes(key),
|
!TELEMETRY_FORBIDDEN_ATTRIBUTES.includes(key) &&
|
||||||
|
validAttributeValue(key, value),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
const invalid = Object.entries(attributes).filter(
|
||||||
|
([key, value]) =>
|
||||||
|
TELEMETRY_ATTRIBUTE_ALLOWLIST.includes(key) &&
|
||||||
|
!validAttributeValue(key, value),
|
||||||
|
);
|
||||||
|
if (invalid.length > 0) {
|
||||||
|
return {
|
||||||
|
success: /** @type {false} */ (false),
|
||||||
|
reason: "invalid-attribute-value",
|
||||||
|
};
|
||||||
|
}
|
||||||
const missing = definition.requiredAttributes.filter(
|
const missing = definition.requiredAttributes.filter(
|
||||||
(key) => projected[key] === undefined,
|
(key) => projected[key] === undefined,
|
||||||
);
|
);
|
||||||
@@ -135,11 +202,34 @@ export function projectTelemetryEvent(eventName, attributes) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let timestamp;
|
||||||
|
try {
|
||||||
|
timestamp = new Date(now()).toISOString();
|
||||||
|
} catch {
|
||||||
|
timestamp = new Date(0).toISOString();
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
success: /** @type {true} */ (true),
|
success: /** @type {true} */ (true),
|
||||||
event: Object.freeze({
|
event: Object.freeze({
|
||||||
eventName,
|
eventName,
|
||||||
|
timestamp,
|
||||||
attributes: Object.freeze(projected),
|
attributes: Object.freeze(projected),
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} eventName
|
||||||
|
* @param {Record<string, unknown>} attributes
|
||||||
|
* @param {() => number} [now]
|
||||||
|
*/
|
||||||
|
export function projectTelemetryEvent(eventName, attributes, now = Date.now) {
|
||||||
|
try {
|
||||||
|
return projectTelemetryEventUnsafe(eventName, attributes, now);
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
success: /** @type {false} */ (false),
|
||||||
|
reason: "serialization-failure",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { REFERENCE_MESSAGE_CATALOGS } from "./reference-feature/contracts/reference-message-catalog.js";
|
||||||
|
|
||||||
|
export const INSTALLED_MESSAGE_CATALOGS = Object.freeze({
|
||||||
|
"ko-KR": Object.freeze({
|
||||||
|
...REFERENCE_MESSAGE_CATALOGS["ko-KR"],
|
||||||
|
}),
|
||||||
|
"en-US": Object.freeze({
|
||||||
|
...REFERENCE_MESSAGE_CATALOGS["en-US"],
|
||||||
|
}),
|
||||||
|
});
|
||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
export type ReferenceResourceView = Readonly<{
|
export type ReferenceResourceView = Readonly<{
|
||||||
resourceId: string;
|
resourceId: string;
|
||||||
title: string;
|
title: string;
|
||||||
createdAtLabel: string | null;
|
createdAt: string | null;
|
||||||
optimistic?: boolean;
|
optimistic?: boolean;
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
@@ -44,14 +44,10 @@ export function mapReferenceOperation(
|
|||||||
|
|
||||||
export function toReferenceView(
|
export function toReferenceView(
|
||||||
resource: ReferenceResource,
|
resource: ReferenceResource,
|
||||||
formatDate: (value: Date) => string = (value) =>
|
|
||||||
new Intl.DateTimeFormat("ko-KR").format(value),
|
|
||||||
): ReferenceResourceView {
|
): ReferenceResourceView {
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
resourceId: resource.id,
|
resourceId: resource.id,
|
||||||
title: resource.displayName,
|
title: resource.displayName,
|
||||||
createdAtLabel: resource.createdAt
|
createdAt: resource.createdAt,
|
||||||
? formatDate(new Date(resource.createdAt))
|
|
||||||
: null,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
export const REFERENCE_MESSAGE_CATALOGS = Object.freeze({
|
||||||
|
"ko-KR": Object.freeze({
|
||||||
|
"route.REFERENCE_RESOURCE_LIST.navigation": "Reference feature",
|
||||||
|
"route.REFERENCE_RESOURCE_LIST.title": "Reference resources",
|
||||||
|
"route.REFERENCE_RESOURCE_DETAIL.navigation": "Reference detail",
|
||||||
|
"route.REFERENCE_RESOURCE_DETAIL.title": "Reference resource detail",
|
||||||
|
"route.REFERENCE_RESOURCE_FORM.navigation": "Reference form",
|
||||||
|
"route.REFERENCE_RESOURCE_FORM.title": "Create reference resource",
|
||||||
|
"route.REFERENCE_RESOURCE_STATUS.navigation": "Reference status",
|
||||||
|
"route.REFERENCE_RESOURCE_STATUS.title": "Reference resource status",
|
||||||
|
}),
|
||||||
|
"en-US": Object.freeze({
|
||||||
|
"route.REFERENCE_RESOURCE_LIST.navigation": "Reference feature",
|
||||||
|
"route.REFERENCE_RESOURCE_LIST.title": "Reference resources",
|
||||||
|
"route.REFERENCE_RESOURCE_DETAIL.navigation": "Reference detail",
|
||||||
|
"route.REFERENCE_RESOURCE_DETAIL.title": "Reference resource detail",
|
||||||
|
"route.REFERENCE_RESOURCE_FORM.navigation": "Reference form",
|
||||||
|
"route.REFERENCE_RESOURCE_FORM.title": "Create reference resource",
|
||||||
|
"route.REFERENCE_RESOURCE_STATUS.navigation": "Reference status",
|
||||||
|
"route.REFERENCE_RESOURCE_STATUS.title": "Reference resource status",
|
||||||
|
}),
|
||||||
|
});
|
||||||
@@ -5,9 +5,11 @@ import {
|
|||||||
DetailPage,
|
DetailPage,
|
||||||
} from "../../../presentation/design-system/index.js";
|
} from "../../../presentation/design-system/index.js";
|
||||||
import { useRouteInput } from "../../../presentation/routes/app-router.js";
|
import { useRouteInput } from "../../../presentation/routes/app-router.js";
|
||||||
|
import { useLocale } from "../../../presentation/i18n/index.js";
|
||||||
import { useReferenceDetail } from "./use-reference-feature.js";
|
import { useReferenceDetail } from "./use-reference-feature.js";
|
||||||
|
|
||||||
export default function ReferenceResourceDetailPage() {
|
export default function ReferenceResourceDetailPage() {
|
||||||
|
const { date, message } = useLocale();
|
||||||
const route = useRouteInput();
|
const route = useRouteInput();
|
||||||
const resourceId = String(route.params.resourceId);
|
const resourceId = String(route.params.resourceId);
|
||||||
const { query } = useReferenceDetail(resourceId);
|
const { query } = useReferenceDetail(resourceId);
|
||||||
@@ -30,7 +32,11 @@ export default function ReferenceResourceDetailPage() {
|
|||||||
<dt>Resource ID</dt>
|
<dt>Resource ID</dt>
|
||||||
<dd>{resource.resourceId}</dd>
|
<dd>{resource.resourceId}</dd>
|
||||||
<dt>Created</dt>
|
<dt>Created</dt>
|
||||||
<dd>{resource.createdAtLabel ?? "표시 정보 없음"}</dd>
|
<dd>
|
||||||
|
{resource.createdAt
|
||||||
|
? date(new Date(resource.createdAt))
|
||||||
|
: message("common.noDisplayValue")}
|
||||||
|
</dd>
|
||||||
</dl>
|
</dl>
|
||||||
) : (
|
) : (
|
||||||
<p>요약 정보를 준비하고 있습니다.</p>
|
<p>요약 정보를 준비하고 있습니다.</p>
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ export function useReferenceFeature() {
|
|||||||
{
|
{
|
||||||
resourceId: `optimistic:${command.name}`,
|
resourceId: `optimistic:${command.name}`,
|
||||||
title: command.name,
|
title: command.name,
|
||||||
createdAtLabel: null,
|
createdAt: null,
|
||||||
optimistic: true,
|
optimistic: true,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { formatMessage } from "../i18n/index.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {{
|
* @param {{
|
||||||
* kind?: string,
|
* kind?: string,
|
||||||
@@ -18,32 +20,36 @@ export function BootErrorShell({
|
|||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<main role="alert">
|
<main role="alert">
|
||||||
<h1>애플리케이션을 시작할 수 없습니다.</h1>
|
<h1>{formatMessage("ko-KR", "boot.failure.title")}</h1>
|
||||||
<dl>
|
<dl>
|
||||||
<dt>오류</dt>
|
<dt>{formatMessage("ko-KR", "boot.field.error")}</dt>
|
||||||
<dd>{kind}</dd>
|
<dd>{kind}</dd>
|
||||||
<dt>코드</dt>
|
<dt>{formatMessage("ko-KR", "boot.field.code")}</dt>
|
||||||
<dd>{code}</dd>
|
<dd>{code}</dd>
|
||||||
{buildId && (
|
{buildId && (
|
||||||
<>
|
<>
|
||||||
<dt>빌드</dt>
|
<dt>{formatMessage("ko-KR", "boot.field.build")}</dt>
|
||||||
<dd>{buildId}</dd>
|
<dd>{buildId}</dd>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{configSchemaVersion && (
|
{configSchemaVersion && (
|
||||||
<>
|
<>
|
||||||
<dt>설정 스키마</dt>
|
<dt>{formatMessage("ko-KR", "boot.field.configSchema")}</dt>
|
||||||
<dd>{configSchemaVersion}</dd>
|
<dd>{configSchemaVersion}</dd>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{releaseId && (
|
{releaseId && (
|
||||||
<>
|
<>
|
||||||
<dt>릴리스</dt>
|
<dt>{formatMessage("ko-KR", "boot.field.release")}</dt>
|
||||||
<dd>{releaseId}</dd>
|
<dd>{releaseId}</dd>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</dl>
|
</dl>
|
||||||
<p>지원 참조: {supportReference}</p>
|
<p>
|
||||||
|
{formatMessage("ko-KR", "boot.supportReference", {
|
||||||
|
reference: supportReference,
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
type ErrorInfo,
|
type ErrorInfo,
|
||||||
type ReactNode,
|
type ReactNode,
|
||||||
} from "react";
|
} from "react";
|
||||||
|
import { useLocale } from "../i18n/index.js";
|
||||||
|
|
||||||
type RecoveryResult =
|
type RecoveryResult =
|
||||||
| Readonly<{ action: "reload-once"; releasePair: string }>
|
| Readonly<{ action: "reload-once"; releasePair: string }>
|
||||||
@@ -71,27 +72,44 @@ export class ChunkRecoveryBoundary extends Component<Props, State> {
|
|||||||
const { error, recovery, reason } = this.state;
|
const { error, recovery, reason } = this.state;
|
||||||
if (error && !isChunkLoadFailure(error)) throw error;
|
if (error && !isChunkLoadFailure(error)) throw error;
|
||||||
if (error && recovery === "checking") {
|
if (error && recovery === "checking") {
|
||||||
return (
|
return <ChunkRecoverySurface recovery="checking" />;
|
||||||
<section className="ui-page" aria-live="polite" aria-busy="true">
|
|
||||||
새 릴리스 정보를 확인하고 있습니다.
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (error && recovery === "reload-requested") {
|
if (error && recovery === "reload-requested") {
|
||||||
return (
|
return <ChunkRecoverySurface recovery="reload-requested" />;
|
||||||
<section className="ui-page" aria-live="polite">
|
|
||||||
새 버전으로 한 번만 전환합니다.
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (error && recovery === "support") {
|
if (error && recovery === "support") {
|
||||||
return (
|
return <ChunkRecoverySurface recovery="support" reason={reason} />;
|
||||||
<section className="ui-page" role="alert" data-recovery-reason={reason}>
|
|
||||||
<h1>화면 자산을 복구하지 못했습니다.</h1>
|
|
||||||
<p>문제가 계속되면 배포 상태와 지원 참조 정보를 확인해 주세요.</p>
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
return this.props.children;
|
return this.props.children;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function ChunkRecoverySurface({
|
||||||
|
recovery,
|
||||||
|
reason,
|
||||||
|
}: Readonly<{
|
||||||
|
recovery: Exclude<State["recovery"], "idle">;
|
||||||
|
reason?: string;
|
||||||
|
}>) {
|
||||||
|
const { message } = useLocale();
|
||||||
|
if (recovery === "checking") {
|
||||||
|
return (
|
||||||
|
<section className="ui-page" aria-live="polite" aria-busy="true">
|
||||||
|
{message("chunk.checking")}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (recovery === "reload-requested") {
|
||||||
|
return (
|
||||||
|
<section className="ui-page" aria-live="polite">
|
||||||
|
{message("chunk.reloadOnce")}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<section className="ui-page" role="alert" data-recovery-reason={reason}>
|
||||||
|
<h1>{message("chunk.failure.title")}</h1>
|
||||||
|
<p>{message("chunk.failure.description")}</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Component } from "react";
|
import { Component } from "react";
|
||||||
|
import { formatMessage } from "../i18n/index.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef {{
|
* @typedef {{
|
||||||
@@ -57,9 +58,9 @@ export class RenderErrorBoundary extends Component {
|
|||||||
return (
|
return (
|
||||||
this.props.fallback ?? (
|
this.props.fallback ?? (
|
||||||
<section role="alert">
|
<section role="alert">
|
||||||
<p>error.render_failure</p>
|
<p>{formatMessage("ko-KR", "error.render_failure")}</p>
|
||||||
<button type="button" onClick={this.reset}>
|
<button type="button" onClick={this.reset}>
|
||||||
retry
|
{formatMessage("ko-KR", "action.retry")}
|
||||||
</button>
|
</button>
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,19 +2,22 @@ import { useId } from "react";
|
|||||||
|
|
||||||
import { errorMessage } from "./error-copy.js";
|
import { errorMessage } from "./error-copy.js";
|
||||||
import { Button } from "./ui/button.jsx";
|
import { Button } from "./ui/button.jsx";
|
||||||
|
import { useLocale } from "../i18n/index.js";
|
||||||
|
|
||||||
/** @param {{ label?: string }} props */
|
/** @param {{ label?: string }} props */
|
||||||
export function LoadingSurface({ label = "불러오는 중" }) {
|
export function LoadingSurface({ label }) {
|
||||||
|
const { message } = useLocale();
|
||||||
|
const accessibleLabel = label ?? message("async.loading");
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
className="state-surface state-surface--loading"
|
className="state-surface state-surface--loading"
|
||||||
aria-busy="true"
|
aria-busy="true"
|
||||||
aria-label={label}
|
aria-label={accessibleLabel}
|
||||||
aria-live="polite"
|
aria-live="polite"
|
||||||
aria-atomic="true"
|
aria-atomic="true"
|
||||||
>
|
>
|
||||||
<div className="ui-skeleton" aria-hidden="true" />
|
<div className="ui-skeleton" aria-hidden="true" />
|
||||||
<span className="visually-hidden">{label}</span>
|
<span className="visually-hidden">{accessibleLabel}</span>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -27,13 +30,14 @@ export function LoadingSurface({ label = "불러오는 중" }) {
|
|||||||
* }} props
|
* }} props
|
||||||
*/
|
*/
|
||||||
export function EmptySurface({
|
export function EmptySurface({
|
||||||
title = "표시할 항목이 없습니다.",
|
title,
|
||||||
description,
|
description,
|
||||||
action,
|
action,
|
||||||
}) {
|
}) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<section className="ui-empty state-surface" aria-live="polite">
|
<section className="ui-empty state-surface" aria-live="polite">
|
||||||
<h2>{title}</h2>
|
<h2>{title ?? message("async.empty")}</h2>
|
||||||
{description ? <p>{description}</p> : null}
|
{description ? <p>{description}</p> : null}
|
||||||
{action}
|
{action}
|
||||||
</section>
|
</section>
|
||||||
@@ -49,13 +53,14 @@ export function EmptySurface({
|
|||||||
* }} props
|
* }} props
|
||||||
*/
|
*/
|
||||||
export function TerminalErrorSurface({ userMessageKey, action, onAction }) {
|
export function TerminalErrorSurface({ userMessageKey, action, onAction }) {
|
||||||
|
const { locale, message } = useLocale();
|
||||||
const messageId = useId();
|
const messageId = useId();
|
||||||
const actionLabels = Object.freeze({
|
const actionLabels = Object.freeze({
|
||||||
retry: "다시 시도",
|
retry: message("action.retry"),
|
||||||
reauth: "로그인",
|
reauth: message("action.reauth"),
|
||||||
navigate: "안전한 화면으로 이동",
|
navigate: message("action.navigateSafe"),
|
||||||
"reload-once": "한 번 새로고침",
|
"reload-once": message("action.reloadOnce"),
|
||||||
"contact-support": "지원 정보 확인",
|
"contact-support": message("action.contactSupport"),
|
||||||
});
|
});
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
@@ -64,7 +69,7 @@ export function TerminalErrorSurface({ userMessageKey, action, onAction }) {
|
|||||||
aria-labelledby={messageId}
|
aria-labelledby={messageId}
|
||||||
data-message-key={userMessageKey}
|
data-message-key={userMessageKey}
|
||||||
>
|
>
|
||||||
<h2 id={messageId}>{errorMessage(userMessageKey)}</h2>
|
<h2 id={messageId}>{errorMessage(userMessageKey, locale)}</h2>
|
||||||
{action !== "none" && onAction && (
|
{action !== "none" && onAction && (
|
||||||
<Button onClick={onAction}>{actionLabels[action]}</Button>
|
<Button onClick={onAction}>{actionLabels[action]}</Button>
|
||||||
)}
|
)}
|
||||||
@@ -88,6 +93,7 @@ export function AsyncSurface({
|
|||||||
onRetry,
|
onRetry,
|
||||||
onResolveConflict,
|
onResolveConflict,
|
||||||
}) {
|
}) {
|
||||||
|
const { message } = useLocale();
|
||||||
if (state.base === "initial-loading") return <LoadingSurface />;
|
if (state.base === "initial-loading") return <LoadingSurface />;
|
||||||
if (state.base === "empty") return <EmptySurface />;
|
if (state.base === "empty") return <EmptySurface />;
|
||||||
if (state.base === "terminal-error" && state.failure) {
|
if (state.base === "terminal-error" && state.failure) {
|
||||||
@@ -104,12 +110,24 @@ export function AsyncSurface({
|
|||||||
<section aria-busy={state.overlay.refreshing || state.overlay.mutationPending}>
|
<section aria-busy={state.overlay.refreshing || state.overlay.mutationPending}>
|
||||||
{state.indicator ? (
|
{state.indicator ? (
|
||||||
<div role="status" aria-live="polite">
|
<div role="status" aria-live="polite">
|
||||||
<span>{state.indicator}</span>
|
<span>
|
||||||
|
{message(
|
||||||
|
state.indicator === "stale-degraded"
|
||||||
|
? "async.staleDegraded"
|
||||||
|
: state.indicator === "mutation-conflict"
|
||||||
|
? "async.mutationConflict"
|
||||||
|
: state.indicator === "mutation-pending"
|
||||||
|
? "async.mutationPending"
|
||||||
|
: "async.refreshing",
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
{state.indicator === "stale-degraded" && onRetry ? (
|
{state.indicator === "stale-degraded" && onRetry ? (
|
||||||
<Button onClick={onRetry}>다시 시도</Button>
|
<Button onClick={onRetry}>{message("action.retry")}</Button>
|
||||||
) : null}
|
) : null}
|
||||||
{state.indicator === "mutation-conflict" && onResolveConflict ? (
|
{state.indicator === "mutation-conflict" && onResolveConflict ? (
|
||||||
<Button onClick={onResolveConflict}>충돌 해결</Button>
|
<Button onClick={onResolveConflict}>
|
||||||
|
{message("action.resolveConflict")}
|
||||||
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -1,26 +1,6 @@
|
|||||||
const ERROR_MESSAGES = Object.freeze({
|
import { resolveMessage } from "../i18n/index.js";
|
||||||
"error.network_unreachable": "네트워크에 연결할 수 없습니다.",
|
|
||||||
"error.request_timeout": "요청 시간이 초과되었습니다.",
|
|
||||||
"error.auth_required": "계속하려면 로그인이 필요합니다.",
|
|
||||||
"error.auth_integration_failure": "로그인 연동을 사용할 수 없습니다.",
|
|
||||||
"error.forbidden": "이 작업을 수행할 권한이 없습니다.",
|
|
||||||
"error.not_found": "요청한 항목을 찾을 수 없습니다.",
|
|
||||||
"error.rate_limited": "요청이 많습니다. 잠시 후 다시 시도해 주세요.",
|
|
||||||
"error.server_failure": "요청을 완료하지 못했습니다.",
|
|
||||||
"error.chunk_load_failure": "새 화면 파일을 불러오지 못했습니다.",
|
|
||||||
"error.build_mismatch": "현재 화면과 활성 빌드가 일치하지 않습니다.",
|
|
||||||
"error.config_mismatch": "런타임 설정 버전이 현재 화면과 일치하지 않습니다.",
|
|
||||||
"error.api_contract_mismatch": "API 계약 버전이 현재 화면과 일치하지 않습니다.",
|
|
||||||
"error.release_mismatch": "현재 화면과 활성 릴리스가 일치하지 않습니다.",
|
|
||||||
"error.asset_mismatch": "화면 자산 구성이 현재 릴리스와 일치하지 않습니다.",
|
|
||||||
"error.render_failure": "화면을 표시하지 못했습니다.",
|
|
||||||
"error.unknown_failure": "예상하지 못한 문제가 발생했습니다.",
|
|
||||||
});
|
|
||||||
|
|
||||||
/** @param {string} messageKey */
|
/** @param {string} messageKey @param {string} [locale] */
|
||||||
export function errorMessage(messageKey) {
|
export function errorMessage(messageKey, locale = "ko-KR") {
|
||||||
const messages = /** @type {Readonly<Record<string, string>>} */ (
|
return resolveMessage(locale, messageKey);
|
||||||
ERROR_MESSAGES
|
|
||||||
);
|
|
||||||
return messages[messageKey] ?? "요청을 완료하지 못했습니다.";
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Button } from "./ui/button.jsx";
|
import { Button } from "./ui/button.jsx";
|
||||||
|
import { useLocale } from "../i18n/index.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {{
|
* @param {{
|
||||||
@@ -30,12 +31,13 @@ function StateSurface({
|
|||||||
|
|
||||||
/** @param {{ onSignIn?: () => void }} props */
|
/** @param {{ onSignIn?: () => void }} props */
|
||||||
export function AuthRequiredSurface({ onSignIn }) {
|
export function AuthRequiredSurface({ onSignIn }) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<StateSurface
|
<StateSurface
|
||||||
eyebrow="401 · 인증 필요"
|
eyebrow={message("access.auth.eyebrow")}
|
||||||
title="로그인이 필요합니다."
|
title={message("access.auth.title")}
|
||||||
description="세션을 시작한 뒤 이전 작업을 안전하게 계속할 수 있습니다."
|
description={message("access.auth.description")}
|
||||||
actionLabel="로그인 시작"
|
actionLabel={message("action.signIn")}
|
||||||
onAction={onSignIn}
|
onAction={onSignIn}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
@@ -43,12 +45,13 @@ export function AuthRequiredSurface({ onSignIn }) {
|
|||||||
|
|
||||||
/** @param {{ onNavigate?: () => void }} props */
|
/** @param {{ onNavigate?: () => void }} props */
|
||||||
export function ForbiddenSurface({ onNavigate }) {
|
export function ForbiddenSurface({ onNavigate }) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<StateSurface
|
<StateSurface
|
||||||
eyebrow="403 · 권한 없음"
|
eyebrow={message("access.forbidden.eyebrow")}
|
||||||
title="접근할 수 없습니다."
|
title={message("access.forbidden.title")}
|
||||||
description="권한을 확인하거나 접근 가능한 화면으로 이동하세요."
|
description={message("access.forbidden.description")}
|
||||||
actionLabel="안전한 화면으로 이동"
|
actionLabel={message("action.navigateSafe")}
|
||||||
onAction={onNavigate}
|
onAction={onNavigate}
|
||||||
tone="warning"
|
tone="warning"
|
||||||
/>
|
/>
|
||||||
@@ -57,12 +60,13 @@ export function ForbiddenSurface({ onNavigate }) {
|
|||||||
|
|
||||||
/** @param {{ onNavigate?: () => void }} props */
|
/** @param {{ onNavigate?: () => void }} props */
|
||||||
export function NotFoundSurface({ onNavigate }) {
|
export function NotFoundSurface({ onNavigate }) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<StateSurface
|
<StateSurface
|
||||||
eyebrow="404 · 찾을 수 없음"
|
eyebrow={message("access.notFound.eyebrow")}
|
||||||
title="요청한 화면이 없습니다."
|
title={message("access.notFound.title")}
|
||||||
description="주소를 확인하거나 시작 화면으로 돌아가세요."
|
description={message("access.notFound.description")}
|
||||||
actionLabel="시작 화면으로 이동"
|
actionLabel={message("action.goHome")}
|
||||||
onAction={onNavigate}
|
onAction={onNavigate}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
|
|
||||||
import { CloseIcon } from "../icons/semantic-icons.js";
|
import { CloseIcon } from "../icons/semantic-icons.js";
|
||||||
|
import { useLocale } from "../../i18n/index.js";
|
||||||
|
|
||||||
export type ButtonVariant = "primary" | "secondary" | "danger" | "ghost";
|
export type ButtonVariant = "primary" | "secondary" | "danger" | "ghost";
|
||||||
export type ButtonSize = "default" | "compact";
|
export type ButtonSize = "default" | "compact";
|
||||||
@@ -277,6 +278,7 @@ export function Alert({
|
|||||||
dismissLabel,
|
dismissLabel,
|
||||||
onDismiss,
|
onDismiss,
|
||||||
}: AlertProps) {
|
}: AlertProps) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
className={`ui-alert ui-alert--${variant}`}
|
className={`ui-alert ui-alert--${variant}`}
|
||||||
@@ -288,7 +290,9 @@ export function Alert({
|
|||||||
</div>
|
</div>
|
||||||
{onDismiss ? (
|
{onDismiss ? (
|
||||||
<IconButton
|
<IconButton
|
||||||
accessibleName={dismissLabel ?? `${title} 알림 닫기`}
|
accessibleName={
|
||||||
|
dismissLabel ?? message("action.alertCloseNamed", { title })
|
||||||
|
}
|
||||||
className="ui-alert__dismiss"
|
className="ui-alert__dismiss"
|
||||||
onClick={onDismiss}
|
onClick={onDismiss}
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -334,8 +338,10 @@ export const Dialog = forwardRef<HTMLDialogElement, DialogProps>(
|
|||||||
},
|
},
|
||||||
forwardedRef,
|
forwardedRef,
|
||||||
) {
|
) {
|
||||||
|
const { message } = useLocale();
|
||||||
const dialogRef = useRef<HTMLDialogElement | null>(null);
|
const dialogRef = useRef<HTMLDialogElement | null>(null);
|
||||||
const previousFocusRef = useRef<HTMLElement | null>(null);
|
const previousFocusRef = useRef<HTMLElement | null>(null);
|
||||||
|
const focusRestoreGenerationRef = useRef(0);
|
||||||
const titleId = useId();
|
const titleId = useId();
|
||||||
const descriptionId = useId();
|
const descriptionId = useId();
|
||||||
useImperativeHandle(forwardedRef, () => dialogRef.current!, []);
|
useImperativeHandle(forwardedRef, () => dialogRef.current!, []);
|
||||||
@@ -343,6 +349,8 @@ export const Dialog = forwardRef<HTMLDialogElement, DialogProps>(
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const dialog = dialogRef.current;
|
const dialog = dialogRef.current;
|
||||||
if (!dialog) return;
|
if (!dialog) return;
|
||||||
|
const generation = focusRestoreGenerationRef.current + 1;
|
||||||
|
focusRestoreGenerationRef.current = generation;
|
||||||
|
|
||||||
if (open) {
|
if (open) {
|
||||||
previousFocusRef.current =
|
previousFocusRef.current =
|
||||||
@@ -364,8 +372,21 @@ export const Dialog = forwardRef<HTMLDialogElement, DialogProps>(
|
|||||||
if (typeof dialog.close === "function") dialog.close();
|
if (typeof dialog.close === "function") dialog.close();
|
||||||
else dialog.removeAttribute("open");
|
else dialog.removeAttribute("open");
|
||||||
}
|
}
|
||||||
previousFocusRef.current?.focus();
|
const previousFocus = previousFocusRef.current;
|
||||||
previousFocusRef.current = null;
|
previousFocusRef.current = null;
|
||||||
|
const restoreFocus = () => {
|
||||||
|
if (
|
||||||
|
focusRestoreGenerationRef.current === generation &&
|
||||||
|
previousFocus?.isConnected
|
||||||
|
) {
|
||||||
|
previousFocus.focus();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (typeof globalThis.requestAnimationFrame === "function") {
|
||||||
|
const frame = globalThis.requestAnimationFrame(restoreFocus);
|
||||||
|
return () => globalThis.cancelAnimationFrame(frame);
|
||||||
|
}
|
||||||
|
queueMicrotask(restoreFocus);
|
||||||
}, [open]);
|
}, [open]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -395,7 +416,9 @@ export const Dialog = forwardRef<HTMLDialogElement, DialogProps>(
|
|||||||
{description ? <p id={descriptionId}>{description}</p> : null}
|
{description ? <p id={descriptionId}>{description}</p> : null}
|
||||||
</div>
|
</div>
|
||||||
<IconButton
|
<IconButton
|
||||||
accessibleName={closeLabel ?? `${title} 닫기`}
|
accessibleName={
|
||||||
|
closeLabel ?? message("action.closeNamed", { title })
|
||||||
|
}
|
||||||
className="ui-dialog__close"
|
className="ui-dialog__close"
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
import { CloseIcon, SearchIcon } from "../icons/semantic-icons.js";
|
import { CloseIcon, SearchIcon } from "../icons/semantic-icons.js";
|
||||||
import { Field, IconButton } from "./core.js";
|
import { Field, IconButton } from "./core.js";
|
||||||
import type { TextFieldProps } from "./core.js";
|
import type { TextFieldProps } from "./core.js";
|
||||||
|
import { useLocale } from "../../i18n/index.js";
|
||||||
|
|
||||||
type FieldCopy = Readonly<{
|
type FieldCopy = Readonly<{
|
||||||
id?: string;
|
id?: string;
|
||||||
@@ -41,6 +42,7 @@ export const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(
|
|||||||
},
|
},
|
||||||
ref,
|
ref,
|
||||||
) {
|
) {
|
||||||
|
const { message } = useLocale();
|
||||||
const [uncontrolledValue, setUncontrolledValue] = useState(
|
const [uncontrolledValue, setUncontrolledValue] = useState(
|
||||||
String(defaultValue ?? ""),
|
String(defaultValue ?? ""),
|
||||||
);
|
);
|
||||||
@@ -80,7 +82,7 @@ export const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(
|
|||||||
<output className="ui-field__counter">
|
<output className="ui-field__counter">
|
||||||
{maxLengthMessage
|
{maxLengthMessage
|
||||||
? maxLengthMessage(remaining)
|
? maxLengthMessage(remaining)
|
||||||
: `${remaining}자 남음`}
|
: message("form.remaining", { count: remaining })}
|
||||||
</output>
|
</output>
|
||||||
) : null}
|
) : null}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useId, useRef, useState } from "react";
|
import { useId, useRef, useState } from "react";
|
||||||
|
|
||||||
|
import { useLocale } from "../../i18n/index.js";
|
||||||
import { NextIcon, PreviousIcon } from "../icons/semantic-icons.js";
|
import { NextIcon, PreviousIcon } from "../icons/semantic-icons.js";
|
||||||
import { IconButton, LinkButton } from "./core.js";
|
import { IconButton, LinkButton } from "./core.js";
|
||||||
|
|
||||||
@@ -62,6 +63,7 @@ export function Tabs({
|
|||||||
const selected = value ?? internalValue;
|
const selected = value ?? internalValue;
|
||||||
const tabRefs = useRef<Array<HTMLButtonElement | null>>([]);
|
const tabRefs = useRef<Array<HTMLButtonElement | null>>([]);
|
||||||
const baseId = useId();
|
const baseId = useId();
|
||||||
|
const { direction } = useLocale();
|
||||||
|
|
||||||
function select(id: string) {
|
function select(id: string) {
|
||||||
if (value === undefined) setInternalValue(id);
|
if (value === undefined) setInternalValue(id);
|
||||||
@@ -98,10 +100,10 @@ export function Tabs({
|
|||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
if (event.key === "ArrowRight") {
|
if (event.key === "ArrowRight") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
move(index, 1);
|
move(index, direction === "rtl" ? -1 : 1);
|
||||||
} else if (event.key === "ArrowLeft") {
|
} else if (event.key === "ArrowLeft") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
move(index, -1);
|
move(index, direction === "rtl" ? 1 : -1);
|
||||||
} else if (
|
} else if (
|
||||||
activation === "manual" &&
|
activation === "manual" &&
|
||||||
(event.key === "Enter" || event.key === " ")
|
(event.key === "Enter" || event.key === " ")
|
||||||
@@ -156,6 +158,10 @@ export function Pagination({
|
|||||||
onChange(page: number): void;
|
onChange(page: number): void;
|
||||||
}>) {
|
}>) {
|
||||||
const pages = Array.from({ length: pageCount }, (_, index) => index + 1);
|
const pages = Array.from({ length: pageCount }, (_, index) => index + 1);
|
||||||
|
const { direction } = useLocale();
|
||||||
|
const PreviousDirectionalIcon =
|
||||||
|
direction === "rtl" ? NextIcon : PreviousIcon;
|
||||||
|
const NextDirectionalIcon = direction === "rtl" ? PreviousIcon : NextIcon;
|
||||||
return (
|
return (
|
||||||
<nav aria-label={label} className="ui-pagination">
|
<nav aria-label={label} className="ui-pagination">
|
||||||
<IconButton
|
<IconButton
|
||||||
@@ -164,7 +170,7 @@ export function Pagination({
|
|||||||
onClick={() => onChange(page - 1)}
|
onClick={() => onChange(page - 1)}
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
>
|
>
|
||||||
<PreviousIcon />
|
<PreviousDirectionalIcon />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
{pages.map((candidate) => (
|
{pages.map((candidate) => (
|
||||||
<LinkButton
|
<LinkButton
|
||||||
@@ -186,7 +192,7 @@ export function Pagination({
|
|||||||
onClick={() => onChange(page + 1)}
|
onClick={() => onChange(page + 1)}
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
>
|
>
|
||||||
<NextIcon />
|
<NextDirectionalIcon />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</nav>
|
</nav>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
|
|
||||||
import { CloseIcon } from "../icons/semantic-icons.js";
|
import { CloseIcon } from "../icons/semantic-icons.js";
|
||||||
import { Button, Dialog, IconButton } from "./core.js";
|
import { Button, Dialog, IconButton } from "./core.js";
|
||||||
|
import { useLocale } from "../../i18n/index.js";
|
||||||
|
|
||||||
export type DrawerProps = Readonly<{
|
export type DrawerProps = Readonly<{
|
||||||
open: boolean;
|
open: boolean;
|
||||||
@@ -343,9 +344,10 @@ function ToastRegion({
|
|||||||
toasts: readonly ToastEntry[];
|
toasts: readonly ToastEntry[];
|
||||||
dismiss(id: string): void;
|
dismiss(id: string): void;
|
||||||
}>) {
|
}>) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
aria-label="Notifications"
|
aria-label={message("toast.region")}
|
||||||
aria-live="polite"
|
aria-live="polite"
|
||||||
className="ui-toast-region"
|
className="ui-toast-region"
|
||||||
>
|
>
|
||||||
@@ -363,6 +365,7 @@ function ToastItem({
|
|||||||
toast: ToastEntry;
|
toast: ToastEntry;
|
||||||
dismiss(id: string): void;
|
dismiss(id: string): void;
|
||||||
}>) {
|
}>) {
|
||||||
|
const { message } = useLocale();
|
||||||
const [paused, setPaused] = useState(false);
|
const [paused, setPaused] = useState(false);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (paused) return;
|
if (paused) return;
|
||||||
@@ -391,7 +394,7 @@ function ToastItem({
|
|||||||
{toast.description ? <p>{toast.description}</p> : null}
|
{toast.description ? <p>{toast.description}</p> : null}
|
||||||
</div>
|
</div>
|
||||||
<IconButton
|
<IconButton
|
||||||
accessibleName={`${toast.title} 닫기`}
|
accessibleName={message("action.closeNamed", { title: toast.title })}
|
||||||
onClick={() => dismiss(toast.id)}
|
onClick={() => dismiss(toast.id)}
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useId, type FormHTMLAttributes, type ReactNode } from "react";
|
import { useId, type FormHTMLAttributes, type ReactNode } from "react";
|
||||||
|
|
||||||
import { TextField } from "../components/ui/text-field.jsx";
|
import { TextField } from "../components/ui/text-field.jsx";
|
||||||
|
import { useLocale } from "../i18n/index.js";
|
||||||
import type {
|
import type {
|
||||||
FieldErrors,
|
FieldErrors,
|
||||||
FieldName,
|
FieldName,
|
||||||
@@ -31,6 +32,7 @@ export function ErrorSummary<Values extends FormValues>(props: Readonly<{
|
|||||||
fieldId(name: FieldName<Values>): string;
|
fieldId(name: FieldName<Values>): string;
|
||||||
onFocusField?(name: FieldName<Values>): void;
|
onFocusField?(name: FieldName<Values>): void;
|
||||||
}>) {
|
}>) {
|
||||||
|
const { message } = useLocale();
|
||||||
const {
|
const {
|
||||||
fieldErrors,
|
fieldErrors,
|
||||||
formErrors = [],
|
formErrors = [],
|
||||||
@@ -50,7 +52,7 @@ export function ErrorSummary<Values extends FormValues>(props: Readonly<{
|
|||||||
role="alert"
|
role="alert"
|
||||||
aria-labelledby={headingId}
|
aria-labelledby={headingId}
|
||||||
>
|
>
|
||||||
<h2 id={headingId}>입력 내용을 확인해 주세요.</h2>
|
<h2 id={headingId}>{message("form.errorSummary")}</h2>
|
||||||
{entries.length > 0 ? (
|
{entries.length > 0 ? (
|
||||||
<ul>
|
<ul>
|
||||||
{entries.map(([name, message]) => (
|
{entries.map(([name, message]) => (
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
import type { ApiFailure } from "../../contracts/errors.js";
|
import type { ApiFailure } from "../../contracts/errors.js";
|
||||||
|
import {
|
||||||
|
formatMessage,
|
||||||
|
type ParameterlessMessageKey,
|
||||||
|
} from "../i18n/index.js";
|
||||||
|
|
||||||
export type FormValues = Readonly<Record<string, unknown>>;
|
export type FormValues = Readonly<Record<string, unknown>>;
|
||||||
export type FieldName<Values extends FormValues> = Extract<keyof Values, string>;
|
export type FieldName<Values extends FormValues> = Extract<keyof Values, string>;
|
||||||
@@ -23,24 +27,32 @@ export type MappedValidationFailure<Values extends FormValues> = Readonly<{
|
|||||||
}>;
|
}>;
|
||||||
|
|
||||||
const VALIDATION_COPY = Object.freeze({
|
const VALIDATION_COPY = Object.freeze({
|
||||||
REQUIRED: "필수 입력값입니다.",
|
REQUIRED: "form.validation.required",
|
||||||
too_small: "입력값이 너무 짧습니다.",
|
too_small: "form.validation.tooSmall",
|
||||||
too_big: "입력값이 너무 깁니다.",
|
too_big: "form.validation.tooBig",
|
||||||
invalid_type: "입력 형식을 확인해 주세요.",
|
invalid_type: "form.validation.invalidType",
|
||||||
invalid_format: "입력 형식을 확인해 주세요.",
|
invalid_format: "form.validation.invalidFormat",
|
||||||
invalid_value: "허용된 값을 선택해 주세요.",
|
invalid_value: "form.validation.invalidValue",
|
||||||
});
|
});
|
||||||
|
|
||||||
export function validationMessage(code: string): string {
|
type MessageResolver = (key: ParameterlessMessageKey) => string;
|
||||||
return (
|
|
||||||
|
const defaultMessage: MessageResolver = (key) => formatMessage("ko-KR", key);
|
||||||
|
|
||||||
|
export function validationMessage(
|
||||||
|
code: string,
|
||||||
|
message: MessageResolver = defaultMessage,
|
||||||
|
): string {
|
||||||
|
return message(
|
||||||
VALIDATION_COPY[code as keyof typeof VALIDATION_COPY] ??
|
VALIDATION_COPY[code as keyof typeof VALIDATION_COPY] ??
|
||||||
"입력값을 확인해 주세요."
|
"form.validation.unknown",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function mapValidationFailureToFields<Values extends FormValues>(
|
export function mapValidationFailureToFields<Values extends FormValues>(
|
||||||
failure: ApiFailure,
|
failure: ApiFailure,
|
||||||
allowedFields: readonly FieldName<Values>[],
|
allowedFields: readonly FieldName<Values>[],
|
||||||
|
message: MessageResolver = defaultMessage,
|
||||||
): MappedValidationFailure<Values> {
|
): MappedValidationFailure<Values> {
|
||||||
if (failure.kind !== "VALIDATION_REJECTED") {
|
if (failure.kind !== "VALIDATION_REJECTED") {
|
||||||
return Object.freeze({ fieldErrors: Object.freeze({}), formErrors: [] });
|
return Object.freeze({ fieldErrors: Object.freeze({}), formErrors: [] });
|
||||||
@@ -51,15 +63,15 @@ export function mapValidationFailureToFields<Values extends FormValues>(
|
|||||||
const issues = failure.validationIssues ?? [];
|
const issues = failure.validationIssues ?? [];
|
||||||
|
|
||||||
if (issues.length === 0) {
|
if (issues.length === 0) {
|
||||||
formErrors.push("입력값을 다시 확인해 주세요.");
|
formErrors.push(message("form.validation.retry"));
|
||||||
}
|
}
|
||||||
for (const issue of issues) {
|
for (const issue of issues) {
|
||||||
const field = issue.path.split(".").at(0) ?? "";
|
const field = issue.path.split(".").at(0) ?? "";
|
||||||
if (allowed.has(field)) {
|
if (allowed.has(field)) {
|
||||||
const name = field as FieldName<Values>;
|
const name = field as FieldName<Values>;
|
||||||
fieldErrors[name] ??= validationMessage(issue.code);
|
fieldErrors[name] ??= validationMessage(issue.code, message);
|
||||||
} else {
|
} else {
|
||||||
formErrors.push("서버가 확인하지 못한 입력 항목이 있습니다.");
|
formErrors.push(message("form.validation.unknownField"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ import {
|
|||||||
type FormEvent,
|
type FormEvent,
|
||||||
} from "react";
|
} from "react";
|
||||||
import type { ZodType, ZodIssue } from "zod";
|
import type { ZodType, ZodIssue } from "zod";
|
||||||
|
import {
|
||||||
|
useLocale,
|
||||||
|
type ParameterlessMessageKey,
|
||||||
|
} from "../i18n/index.js";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
mapValidationFailureToFields,
|
mapValidationFailureToFields,
|
||||||
@@ -37,6 +41,7 @@ export function useAppForm<
|
|||||||
Command,
|
Command,
|
||||||
Output,
|
Output,
|
||||||
>(options: AppFormOptions<Values, Command, Output>) {
|
>(options: AppFormOptions<Values, Command, Output>) {
|
||||||
|
const { message } = useLocale();
|
||||||
const {
|
const {
|
||||||
schema,
|
schema,
|
||||||
defaultValues,
|
defaultValues,
|
||||||
@@ -142,13 +147,14 @@ export function useAppForm<
|
|||||||
const errors = issuesToFieldErrors<Values>(
|
const errors = issuesToFieldErrors<Values>(
|
||||||
parsed.error.issues,
|
parsed.error.issues,
|
||||||
allowedServerFields,
|
allowedServerFields,
|
||||||
|
message,
|
||||||
);
|
);
|
||||||
setFieldErrors(errors);
|
setFieldErrors(errors);
|
||||||
setFormErrors(
|
setFormErrors(
|
||||||
parsed.error.issues.some(
|
parsed.error.issues.some(
|
||||||
(issue) => !allowedServerFields.includes(issue.path[0] as FieldName<Values>),
|
(issue) => !allowedServerFields.includes(issue.path[0] as FieldName<Values>),
|
||||||
)
|
)
|
||||||
? ["입력 구성을 다시 확인해 주세요."]
|
? [message("form.validation.configuration")]
|
||||||
: [],
|
: [],
|
||||||
);
|
);
|
||||||
setTouched(new Set(allowedServerFields));
|
setTouched(new Set(allowedServerFields));
|
||||||
@@ -178,6 +184,7 @@ export function useAppForm<
|
|||||||
const mapped = mapValidationFailureToFields<Values>(
|
const mapped = mapValidationFailureToFields<Values>(
|
||||||
outcome.error,
|
outcome.error,
|
||||||
allowedServerFields,
|
allowedServerFields,
|
||||||
|
message,
|
||||||
);
|
);
|
||||||
setFieldErrors(mapped.fieldErrors);
|
setFieldErrors(mapped.fieldErrors);
|
||||||
setFormErrors(mapped.formErrors);
|
setFormErrors(mapped.formErrors);
|
||||||
@@ -185,11 +192,11 @@ export function useAppForm<
|
|||||||
focusFirstError(mapped.fieldErrors);
|
focusFirstError(mapped.fieldErrors);
|
||||||
} else if (outcome.error.kind === "CONFLICT") {
|
} else if (outcome.error.kind === "CONFLICT") {
|
||||||
setFormErrors([
|
setFormErrors([
|
||||||
"다른 변경과 충돌했습니다. 입력은 유지되었으니 최신 상태를 확인해 주세요.",
|
message("form.conflict"),
|
||||||
]);
|
]);
|
||||||
setResult("conflict");
|
setResult("conflict");
|
||||||
} else {
|
} else {
|
||||||
setFormErrors(["저장하지 못했습니다. 잠시 후 다시 시도해 주세요."]);
|
setFormErrors([message("form.unavailable")]);
|
||||||
setResult("unavailable");
|
setResult("unavailable");
|
||||||
}
|
}
|
||||||
return outcome;
|
return outcome;
|
||||||
@@ -203,6 +210,7 @@ export function useAppForm<
|
|||||||
defaultValues,
|
defaultValues,
|
||||||
focusFirstError,
|
focusFirstError,
|
||||||
mapToCommand,
|
mapToCommand,
|
||||||
|
message,
|
||||||
resetOnSuccess,
|
resetOnSuccess,
|
||||||
schema,
|
schema,
|
||||||
submit,
|
submit,
|
||||||
@@ -231,6 +239,7 @@ export function useAppForm<
|
|||||||
function issuesToFieldErrors<Values extends FormValues>(
|
function issuesToFieldErrors<Values extends FormValues>(
|
||||||
issues: readonly ZodIssue[],
|
issues: readonly ZodIssue[],
|
||||||
allowedFields: readonly FieldName<Values>[],
|
allowedFields: readonly FieldName<Values>[],
|
||||||
|
message: (key: ParameterlessMessageKey) => string,
|
||||||
): FieldErrors<Values> {
|
): FieldErrors<Values> {
|
||||||
const allowed = new Set<PropertyKey>(allowedFields);
|
const allowed = new Set<PropertyKey>(allowedFields);
|
||||||
const errors: Partial<Record<FieldName<Values>, string>> = {};
|
const errors: Partial<Record<FieldName<Values>, string>> = {};
|
||||||
@@ -238,7 +247,7 @@ function issuesToFieldErrors<Values extends FormValues>(
|
|||||||
const field = issue.path[0];
|
const field = issue.path[0];
|
||||||
if (!allowed.has(field)) continue;
|
if (!allowed.has(field)) continue;
|
||||||
const name = field as FieldName<Values>;
|
const name = field as FieldName<Values>;
|
||||||
errors[name] ??= validationMessage(issue.code);
|
errors[name] ??= validationMessage(issue.code, message);
|
||||||
}
|
}
|
||||||
return Object.freeze(errors);
|
return Object.freeze(errors);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { useBeforeUnload, useBlocker } from "react-router-dom";
|
|||||||
|
|
||||||
import { Button } from "../components/ui/button.jsx";
|
import { Button } from "../components/ui/button.jsx";
|
||||||
import { Dialog } from "../components/ui/dialog.jsx";
|
import { Dialog } from "../components/ui/dialog.jsx";
|
||||||
|
import { useLocale } from "../i18n/index.js";
|
||||||
|
|
||||||
export function useDirtyNavigationGuard(when: boolean) {
|
export function useDirtyNavigationGuard(when: boolean) {
|
||||||
const blocker = useBlocker(when);
|
const blocker = useBlocker(when);
|
||||||
@@ -33,19 +34,20 @@ export function useDirtyNavigationGuard(when: boolean) {
|
|||||||
export function DirtyNavigationDialog(props: Readonly<{
|
export function DirtyNavigationDialog(props: Readonly<{
|
||||||
guard: ReturnType<typeof useDirtyNavigationGuard>;
|
guard: ReturnType<typeof useDirtyNavigationGuard>;
|
||||||
}>) {
|
}>) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<Dialog
|
<Dialog
|
||||||
open={props.guard.blocked}
|
open={props.guard.blocked}
|
||||||
onClose={props.guard.stay}
|
onClose={props.guard.stay}
|
||||||
title="저장하지 않은 변경이 있습니다."
|
title={message("form.unsaved.title")}
|
||||||
description="이 화면을 떠나면 입력한 내용이 사라집니다."
|
description={message("form.unsaved.description")}
|
||||||
actions={
|
actions={
|
||||||
<>
|
<>
|
||||||
<Button variant="secondary" onClick={props.guard.stay}>
|
<Button variant="secondary" onClick={props.guard.stay}>
|
||||||
계속 작성
|
{message("action.continueEditing")}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="danger" onClick={props.guard.leave}>
|
<Button variant="danger" onClick={props.guard.leave}>
|
||||||
변경 버리고 이동
|
{message("action.discardAndLeave")}
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,304 @@
|
|||||||
|
import { INSTALLED_MESSAGE_CATALOGS } from "../../features/installed-feature-messages.js";
|
||||||
|
|
||||||
|
const PLATFORM_KO_MESSAGES = {
|
||||||
|
"common.unavailable": "요청한 문구를 표시할 수 없습니다.",
|
||||||
|
"common.processing": "처리 중…",
|
||||||
|
"common.appName": "Frontend Skeleton",
|
||||||
|
"common.noDisplayValue": "표시 정보 없음",
|
||||||
|
"action.retry": "다시 시도",
|
||||||
|
"action.reauth": "로그인",
|
||||||
|
"action.navigateSafe": "안전한 화면으로 이동",
|
||||||
|
"action.reloadOnce": "한 번 새로고침",
|
||||||
|
"action.contactSupport": "지원 정보 확인",
|
||||||
|
"action.resolveConflict": "충돌 해결",
|
||||||
|
"action.continueEditing": "계속 작성",
|
||||||
|
"action.discardAndLeave": "변경 버리고 이동",
|
||||||
|
"action.signIn": "로그인 시작",
|
||||||
|
"action.recoverSession": "세션 복구",
|
||||||
|
"action.signOut": "로그아웃",
|
||||||
|
"action.goHome": "홈으로 이동",
|
||||||
|
"action.closeNamed": "{title} 닫기",
|
||||||
|
"action.alertCloseNamed": "{title} 알림 닫기",
|
||||||
|
"shell.skipToContent": "본문으로 건너뛰기",
|
||||||
|
"shell.menu": "메뉴",
|
||||||
|
"shell.closeMenu": "메뉴 닫기",
|
||||||
|
"shell.sidebar": "사이드바",
|
||||||
|
"shell.primaryNavigation": "주요 탐색",
|
||||||
|
"shell.theme": "색상 테마",
|
||||||
|
"shell.theme.system": "시스템 테마",
|
||||||
|
"shell.theme.light": "라이트 테마",
|
||||||
|
"shell.theme.dark": "다크 테마",
|
||||||
|
"shell.locale": "언어",
|
||||||
|
"shell.locale.ko": "한국어",
|
||||||
|
"shell.locale.en": "English",
|
||||||
|
"shell.locale.pseudo": "Pseudo",
|
||||||
|
"shell.locale.rtl": "RTL smoke",
|
||||||
|
"shell.session.authenticated": "인증됨",
|
||||||
|
"shell.session.unauthenticated": "로그인 전",
|
||||||
|
"shell.session.recoveryPending": "복구 대기",
|
||||||
|
"shell.session.integrationFailed": "연동 필요",
|
||||||
|
"shell.session.actionFailed": "세션 작업을 완료하지 못했습니다.",
|
||||||
|
"route.APP_HOME.navigation": "홈",
|
||||||
|
"route.APP_HOME.title": "Clean Architecture Frontend",
|
||||||
|
"route.EXAMPLES_UI.navigation": "UI 구성요소",
|
||||||
|
"route.EXAMPLES_UI.title": "UI 구성요소",
|
||||||
|
"route.EXAMPLES_STATES.navigation": "화면 상태",
|
||||||
|
"route.EXAMPLES_STATES.title": "화면 상태",
|
||||||
|
"route.EXAMPLES_AUTH.navigation": "인증 연동",
|
||||||
|
"route.EXAMPLES_AUTH.title": "인증 연동",
|
||||||
|
"route.NOT_FOUND.navigation": "찾을 수 없음",
|
||||||
|
"route.NOT_FOUND.title": "페이지를 찾을 수 없습니다.",
|
||||||
|
"async.loading": "불러오는 중",
|
||||||
|
"async.empty": "표시할 항목이 없습니다.",
|
||||||
|
"async.refreshing": "최신 정보를 확인하고 있습니다.",
|
||||||
|
"async.staleDegraded": "기존 정보를 표시하고 있습니다.",
|
||||||
|
"async.mutationPending": "변경 사항을 저장하고 있습니다.",
|
||||||
|
"async.mutationConflict": "다른 변경과 충돌했습니다.",
|
||||||
|
"access.auth.eyebrow": "401 · 인증 필요",
|
||||||
|
"access.auth.title": "로그인이 필요합니다.",
|
||||||
|
"access.auth.description":
|
||||||
|
"세션을 시작한 뒤 이전 작업을 안전하게 계속할 수 있습니다.",
|
||||||
|
"access.forbidden.eyebrow": "403 · 권한 없음",
|
||||||
|
"access.forbidden.title": "접근할 수 없습니다.",
|
||||||
|
"access.forbidden.description":
|
||||||
|
"권한을 확인하거나 접근 가능한 화면으로 이동하세요.",
|
||||||
|
"access.notFound.eyebrow": "404 · 찾을 수 없음",
|
||||||
|
"access.notFound.title": "요청한 화면이 없습니다.",
|
||||||
|
"access.notFound.description":
|
||||||
|
"주소를 확인하거나 시작 화면으로 돌아가세요.",
|
||||||
|
"route.loading": "화면을 준비하고 있습니다.",
|
||||||
|
"route.loadingNamed": "{title} 로딩 중",
|
||||||
|
"route.failure.title": "화면을 표시하지 못했습니다.",
|
||||||
|
"route.failure.description":
|
||||||
|
"잠시 후 다시 시도해 주세요. 문제가 계속되면 운영 지원 참조 정보를 확인하세요.",
|
||||||
|
"route.invalid.title": "올바르지 않은 주소입니다.",
|
||||||
|
"route.invalid.description": "주소의 경로 또는 검색 조건을 확인해 주세요.",
|
||||||
|
"route.invalid.action": "안전한 탐색 링크를 사용해 주세요.",
|
||||||
|
"route.auth.integration.title": "로그인 연동이 필요합니다.",
|
||||||
|
"route.auth.integration.description":
|
||||||
|
"외부 인증 소유자가 연결되면 이 보호 라우트를 사용할 수 있습니다.",
|
||||||
|
"route.auth.recovering.title": "세션을 복구하고 있습니다.",
|
||||||
|
"route.auth.required.title": "세션이 필요합니다.",
|
||||||
|
"route.auth.recovering.description":
|
||||||
|
"기존 세션 확인을 계속하려면 복구를 실행하세요.",
|
||||||
|
"route.auth.required.description":
|
||||||
|
"이 화면은 인증 연동 지점을 확인하기 위한 보호 라우트입니다.",
|
||||||
|
"route.documentTitle": "{title} · {appName}",
|
||||||
|
"chunk.checking": "새 릴리스 정보를 확인하고 있습니다.",
|
||||||
|
"chunk.reloadOnce": "새 버전으로 한 번만 전환합니다.",
|
||||||
|
"chunk.failure.title": "화면 자산을 복구하지 못했습니다.",
|
||||||
|
"chunk.failure.description":
|
||||||
|
"문제가 계속되면 배포 상태와 지원 참조 정보를 확인해 주세요.",
|
||||||
|
"page.notFound.title": "페이지를 찾을 수 없습니다.",
|
||||||
|
"page.notFound.description":
|
||||||
|
"주소를 확인하거나 준비된 시작 화면으로 돌아가세요.",
|
||||||
|
"template.breadcrumb": "현재 위치",
|
||||||
|
"template.relatedInformation": "관련 정보",
|
||||||
|
"template.searchAndFilter": "검색과 필터",
|
||||||
|
"template.pagination": "페이지 탐색",
|
||||||
|
"template.summary": "요약 정보",
|
||||||
|
"template.dangerActions": "위험 작업",
|
||||||
|
"template.supportReference": "지원 참조: {reference}",
|
||||||
|
"form.errorSummary": "입력 내용을 확인해 주세요.",
|
||||||
|
"form.unsaved.title": "저장하지 않은 변경이 있습니다.",
|
||||||
|
"form.unsaved.description": "이 화면을 떠나면 입력한 내용이 사라집니다.",
|
||||||
|
"form.validation.required": "필수 입력값입니다.",
|
||||||
|
"form.validation.tooSmall": "입력값이 너무 짧습니다.",
|
||||||
|
"form.validation.tooBig": "입력값이 너무 깁니다.",
|
||||||
|
"form.validation.invalidType": "입력 형식을 확인해 주세요.",
|
||||||
|
"form.validation.invalidFormat": "입력 형식을 확인해 주세요.",
|
||||||
|
"form.validation.invalidValue": "허용된 값을 선택해 주세요.",
|
||||||
|
"form.validation.unknown": "입력값을 확인해 주세요.",
|
||||||
|
"form.validation.retry": "입력값을 다시 확인해 주세요.",
|
||||||
|
"form.validation.unknownField":
|
||||||
|
"서버가 확인하지 못한 입력 항목이 있습니다.",
|
||||||
|
"form.validation.configuration": "입력 구성을 다시 확인해 주세요.",
|
||||||
|
"form.conflict":
|
||||||
|
"다른 변경과 충돌했습니다. 입력은 유지되었으니 최신 상태를 확인해 주세요.",
|
||||||
|
"form.unavailable": "저장하지 못했습니다. 잠시 후 다시 시도해 주세요.",
|
||||||
|
"form.remaining": "{count}자 남음",
|
||||||
|
"toast.region": "알림",
|
||||||
|
"error.network_unreachable": "네트워크에 연결할 수 없습니다.",
|
||||||
|
"error.request_timeout": "요청 시간이 초과되었습니다.",
|
||||||
|
"error.auth_required": "계속하려면 로그인이 필요합니다.",
|
||||||
|
"error.auth_integration_failure": "로그인 연동을 사용할 수 없습니다.",
|
||||||
|
"error.forbidden": "이 작업을 수행할 권한이 없습니다.",
|
||||||
|
"error.not_found": "요청한 항목을 찾을 수 없습니다.",
|
||||||
|
"error.rate_limited": "요청이 많습니다. 잠시 후 다시 시도해 주세요.",
|
||||||
|
"error.server_failure": "요청을 완료하지 못했습니다.",
|
||||||
|
"error.chunk_load_failure": "새 화면 파일을 불러오지 못했습니다.",
|
||||||
|
"error.build_mismatch": "현재 화면과 활성 빌드가 일치하지 않습니다.",
|
||||||
|
"error.config_mismatch": "런타임 설정 버전이 현재 화면과 일치하지 않습니다.",
|
||||||
|
"error.api_contract_mismatch": "API 계약 버전이 현재 화면과 일치하지 않습니다.",
|
||||||
|
"error.release_mismatch": "현재 화면과 활성 릴리스가 일치하지 않습니다.",
|
||||||
|
"error.asset_mismatch": "화면 자산 구성이 현재 릴리스와 일치하지 않습니다.",
|
||||||
|
"error.render_failure": "화면을 표시하지 못했습니다.",
|
||||||
|
"error.unknown_failure": "예상하지 못한 문제가 발생했습니다.",
|
||||||
|
"boot.failure.title": "애플리케이션을 시작할 수 없습니다.",
|
||||||
|
"boot.field.error": "오류",
|
||||||
|
"boot.field.code": "코드",
|
||||||
|
"boot.field.build": "빌드",
|
||||||
|
"boot.field.configSchema": "설정 스키마",
|
||||||
|
"boot.field.release": "릴리스",
|
||||||
|
"boot.supportReference": "지원 참조: {reference}",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const KO_MESSAGES = {
|
||||||
|
...PLATFORM_KO_MESSAGES,
|
||||||
|
...INSTALLED_MESSAGE_CATALOGS["ko-KR"],
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type MessageKey = keyof typeof KO_MESSAGES;
|
||||||
|
|
||||||
|
const PLATFORM_EN_MESSAGES = {
|
||||||
|
"common.unavailable": "This message is unavailable.",
|
||||||
|
"common.processing": "Processing…",
|
||||||
|
"common.appName": "Frontend Skeleton",
|
||||||
|
"common.noDisplayValue": "No display value",
|
||||||
|
"action.retry": "Try again",
|
||||||
|
"action.reauth": "Sign in",
|
||||||
|
"action.navigateSafe": "Go to an available page",
|
||||||
|
"action.reloadOnce": "Reload once",
|
||||||
|
"action.contactSupport": "View support information",
|
||||||
|
"action.resolveConflict": "Resolve conflict",
|
||||||
|
"action.continueEditing": "Continue editing",
|
||||||
|
"action.discardAndLeave": "Discard and leave",
|
||||||
|
"action.signIn": "Start sign-in",
|
||||||
|
"action.recoverSession": "Recover session",
|
||||||
|
"action.signOut": "Sign out",
|
||||||
|
"action.goHome": "Go home",
|
||||||
|
"action.closeNamed": "Close {title}",
|
||||||
|
"action.alertCloseNamed": "Dismiss {title} alert",
|
||||||
|
"shell.skipToContent": "Skip to content",
|
||||||
|
"shell.menu": "Menu",
|
||||||
|
"shell.closeMenu": "Close menu",
|
||||||
|
"shell.sidebar": "Sidebar",
|
||||||
|
"shell.primaryNavigation": "Primary navigation",
|
||||||
|
"shell.theme": "Color theme",
|
||||||
|
"shell.theme.system": "System theme",
|
||||||
|
"shell.theme.light": "Light theme",
|
||||||
|
"shell.theme.dark": "Dark theme",
|
||||||
|
"shell.locale": "Language",
|
||||||
|
"shell.locale.ko": "한국어",
|
||||||
|
"shell.locale.en": "English",
|
||||||
|
"shell.locale.pseudo": "Pseudo",
|
||||||
|
"shell.locale.rtl": "RTL smoke",
|
||||||
|
"shell.session.authenticated": "Authenticated",
|
||||||
|
"shell.session.unauthenticated": "Signed out",
|
||||||
|
"shell.session.recoveryPending": "Recovery pending",
|
||||||
|
"shell.session.integrationFailed": "Integration required",
|
||||||
|
"shell.session.actionFailed": "The session action could not be completed.",
|
||||||
|
"route.APP_HOME.navigation": "Home",
|
||||||
|
"route.APP_HOME.title": "Clean Architecture Frontend",
|
||||||
|
"route.EXAMPLES_UI.navigation": "UI components",
|
||||||
|
"route.EXAMPLES_UI.title": "UI components",
|
||||||
|
"route.EXAMPLES_STATES.navigation": "Screen states",
|
||||||
|
"route.EXAMPLES_STATES.title": "Screen states",
|
||||||
|
"route.EXAMPLES_AUTH.navigation": "Authentication",
|
||||||
|
"route.EXAMPLES_AUTH.title": "Authentication",
|
||||||
|
"route.NOT_FOUND.navigation": "Not found",
|
||||||
|
"route.NOT_FOUND.title": "Page not found",
|
||||||
|
"async.loading": "Loading",
|
||||||
|
"async.empty": "There are no items to display.",
|
||||||
|
"async.refreshing": "Checking for the latest information.",
|
||||||
|
"async.staleDegraded": "Showing previously loaded information.",
|
||||||
|
"async.mutationPending": "Saving changes.",
|
||||||
|
"async.mutationConflict": "The change conflicts with another update.",
|
||||||
|
"access.auth.eyebrow": "401 · Authentication required",
|
||||||
|
"access.auth.title": "Sign-in is required.",
|
||||||
|
"access.auth.description":
|
||||||
|
"Start a session to safely continue the previous task.",
|
||||||
|
"access.forbidden.eyebrow": "403 · Access denied",
|
||||||
|
"access.forbidden.title": "You cannot access this page.",
|
||||||
|
"access.forbidden.description":
|
||||||
|
"Check your permissions or go to an available page.",
|
||||||
|
"access.notFound.eyebrow": "404 · Not found",
|
||||||
|
"access.notFound.title": "The requested page does not exist.",
|
||||||
|
"access.notFound.description": "Check the address or return to the start page.",
|
||||||
|
"route.loading": "Preparing the page.",
|
||||||
|
"route.loadingNamed": "Loading {title}",
|
||||||
|
"route.failure.title": "The page could not be displayed.",
|
||||||
|
"route.failure.description":
|
||||||
|
"Try again shortly. If the problem continues, check the support reference.",
|
||||||
|
"route.invalid.title": "This address is invalid.",
|
||||||
|
"route.invalid.description": "Check the path and search parameters.",
|
||||||
|
"route.invalid.action": "Use a safe navigation link.",
|
||||||
|
"route.auth.integration.title": "Sign-in integration is required.",
|
||||||
|
"route.auth.integration.description":
|
||||||
|
"This protected route is available after an external authentication owner is connected.",
|
||||||
|
"route.auth.recovering.title": "Recovering the session.",
|
||||||
|
"route.auth.required.title": "A session is required.",
|
||||||
|
"route.auth.recovering.description":
|
||||||
|
"Run recovery to continue checking the existing session.",
|
||||||
|
"route.auth.required.description":
|
||||||
|
"This protected route demonstrates the authentication integration seam.",
|
||||||
|
"route.documentTitle": "{title} · {appName}",
|
||||||
|
"chunk.checking": "Checking the new release information.",
|
||||||
|
"chunk.reloadOnce": "Switching to the new version once.",
|
||||||
|
"chunk.failure.title": "The page assets could not be recovered.",
|
||||||
|
"chunk.failure.description":
|
||||||
|
"If the problem continues, check deployment status and support information.",
|
||||||
|
"page.notFound.title": "Page not found.",
|
||||||
|
"page.notFound.description": "Check the address or return to the start page.",
|
||||||
|
"template.breadcrumb": "Current location",
|
||||||
|
"template.relatedInformation": "Related information",
|
||||||
|
"template.searchAndFilter": "Search and filters",
|
||||||
|
"template.pagination": "Pagination",
|
||||||
|
"template.summary": "Summary information",
|
||||||
|
"template.dangerActions": "Dangerous actions",
|
||||||
|
"template.supportReference": "Support reference: {reference}",
|
||||||
|
"form.errorSummary": "Review the entered information.",
|
||||||
|
"form.unsaved.title": "You have unsaved changes.",
|
||||||
|
"form.unsaved.description":
|
||||||
|
"The entered information will be lost if you leave this page.",
|
||||||
|
"form.validation.required": "This field is required.",
|
||||||
|
"form.validation.tooSmall": "This value is too short.",
|
||||||
|
"form.validation.tooBig": "This value is too long.",
|
||||||
|
"form.validation.invalidType": "Check the input type.",
|
||||||
|
"form.validation.invalidFormat": "Check the input format.",
|
||||||
|
"form.validation.invalidValue": "Choose an allowed value.",
|
||||||
|
"form.validation.unknown": "Check the entered value.",
|
||||||
|
"form.validation.retry": "Review the entered values.",
|
||||||
|
"form.validation.unknownField":
|
||||||
|
"The server reported an unrecognized input field.",
|
||||||
|
"form.validation.configuration": "Review the input configuration.",
|
||||||
|
"form.conflict":
|
||||||
|
"Another update conflicts with this change. Your input has been preserved.",
|
||||||
|
"form.unavailable": "The change could not be saved. Try again shortly.",
|
||||||
|
"form.remaining": "{count} characters remaining",
|
||||||
|
"toast.region": "Notifications",
|
||||||
|
"error.network_unreachable": "The network is unavailable.",
|
||||||
|
"error.request_timeout": "The request timed out.",
|
||||||
|
"error.auth_required": "Sign in to continue.",
|
||||||
|
"error.auth_integration_failure": "Sign-in integration is unavailable.",
|
||||||
|
"error.forbidden": "You are not allowed to perform this action.",
|
||||||
|
"error.not_found": "The requested item could not be found.",
|
||||||
|
"error.rate_limited": "Too many requests were made. Try again shortly.",
|
||||||
|
"error.server_failure": "The request could not be completed.",
|
||||||
|
"error.chunk_load_failure": "The new page assets could not be loaded.",
|
||||||
|
"error.build_mismatch": "The active build does not match this page.",
|
||||||
|
"error.config_mismatch": "The runtime configuration does not match this page.",
|
||||||
|
"error.api_contract_mismatch": "The API contract does not match this page.",
|
||||||
|
"error.release_mismatch": "The active release does not match this page.",
|
||||||
|
"error.asset_mismatch": "The page assets do not match this release.",
|
||||||
|
"error.render_failure": "The page could not be displayed.",
|
||||||
|
"error.unknown_failure": "An unexpected problem occurred.",
|
||||||
|
"boot.failure.title": "The application could not start.",
|
||||||
|
"boot.field.error": "Error",
|
||||||
|
"boot.field.code": "Code",
|
||||||
|
"boot.field.build": "Build",
|
||||||
|
"boot.field.configSchema": "Configuration schema",
|
||||||
|
"boot.field.release": "Release",
|
||||||
|
"boot.supportReference": "Support reference: {reference}",
|
||||||
|
} as const satisfies Record<keyof typeof PLATFORM_KO_MESSAGES, string>;
|
||||||
|
|
||||||
|
export const EN_MESSAGES = {
|
||||||
|
...PLATFORM_EN_MESSAGES,
|
||||||
|
...INSTALLED_MESSAGE_CATALOGS["en-US"],
|
||||||
|
} as const satisfies Record<MessageKey, string>;
|
||||||
|
|
||||||
|
export const MESSAGE_CATALOGS = Object.freeze({
|
||||||
|
"ko-KR": KO_MESSAGES,
|
||||||
|
"en-US": EN_MESSAGES,
|
||||||
|
"ar-EG": EN_MESSAGES,
|
||||||
|
});
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import { normalizeLocale, type SupportedLocale } from "./message-contract.js";
|
||||||
|
|
||||||
|
const FORMAT_FALLBACK = "—";
|
||||||
|
|
||||||
|
export type DateFormatStyle = "short" | "medium" | "long";
|
||||||
|
|
||||||
|
export function formatDate(
|
||||||
|
locale: SupportedLocale,
|
||||||
|
value: Date | number,
|
||||||
|
options: Readonly<{
|
||||||
|
dateStyle?: DateFormatStyle;
|
||||||
|
timeZone?: string;
|
||||||
|
}> = {},
|
||||||
|
): string {
|
||||||
|
try {
|
||||||
|
const date = value instanceof Date ? value : new Date(value);
|
||||||
|
if (Number.isNaN(date.getTime())) return FORMAT_FALLBACK;
|
||||||
|
return new Intl.DateTimeFormat(normalizeLocale(locale), {
|
||||||
|
dateStyle: options.dateStyle ?? "medium",
|
||||||
|
timeZone: options.timeZone ?? "UTC",
|
||||||
|
}).format(date);
|
||||||
|
} catch {
|
||||||
|
return FORMAT_FALLBACK;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatNumber(
|
||||||
|
locale: SupportedLocale,
|
||||||
|
value: number,
|
||||||
|
options: Readonly<{
|
||||||
|
style?: "decimal" | "percent";
|
||||||
|
maximumFractionDigits?: number;
|
||||||
|
}> = {},
|
||||||
|
): string {
|
||||||
|
try {
|
||||||
|
if (!Number.isFinite(value)) return FORMAT_FALLBACK;
|
||||||
|
return new Intl.NumberFormat(normalizeLocale(locale), options).format(value);
|
||||||
|
} catch {
|
||||||
|
return FORMAT_FALLBACK;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatRelativeTime(
|
||||||
|
locale: SupportedLocale,
|
||||||
|
value: number,
|
||||||
|
unit: Intl.RelativeTimeFormatUnit,
|
||||||
|
): string {
|
||||||
|
try {
|
||||||
|
if (!Number.isFinite(value)) return FORMAT_FALLBACK;
|
||||||
|
return new Intl.RelativeTimeFormat(normalizeLocale(locale), {
|
||||||
|
numeric: "auto",
|
||||||
|
}).format(value, unit);
|
||||||
|
} catch {
|
||||||
|
return FORMAT_FALLBACK;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatList(
|
||||||
|
locale: SupportedLocale,
|
||||||
|
values: readonly string[],
|
||||||
|
): string {
|
||||||
|
try {
|
||||||
|
return new Intl.ListFormat(normalizeLocale(locale), {
|
||||||
|
style: "long",
|
||||||
|
type: "conjunction",
|
||||||
|
}).format(values);
|
||||||
|
} catch {
|
||||||
|
return values.join(", ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function selectPlural(
|
||||||
|
locale: SupportedLocale,
|
||||||
|
value: number,
|
||||||
|
choices: Readonly<
|
||||||
|
Partial<Record<Intl.LDMLPluralRule, string>> & { other: string }
|
||||||
|
>,
|
||||||
|
): string {
|
||||||
|
try {
|
||||||
|
if (!Number.isFinite(value)) return choices.other;
|
||||||
|
return choices[
|
||||||
|
new Intl.PluralRules(normalizeLocale(locale)).select(value)
|
||||||
|
] ?? choices.other;
|
||||||
|
} catch {
|
||||||
|
return choices.other;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function selectMessage(
|
||||||
|
value: string,
|
||||||
|
choices: Readonly<Record<string, string> & { other: string }>,
|
||||||
|
): string {
|
||||||
|
return choices[value] ?? choices.other;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { FORMAT_FALLBACK };
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
export { LocaleProvider, useLocale } from "./locale-provider.js";
|
||||||
|
export {
|
||||||
|
catalogKeys,
|
||||||
|
fallbackMessage,
|
||||||
|
formatMessage,
|
||||||
|
localeDirection,
|
||||||
|
MESSAGE_KEY_ALIASES,
|
||||||
|
messagePlaceholders,
|
||||||
|
normalizeLocale,
|
||||||
|
resolveMessage,
|
||||||
|
SUPPORTED_LOCALES,
|
||||||
|
} from "./message-contract.js";
|
||||||
|
export type {
|
||||||
|
MessageArguments,
|
||||||
|
MessageParameters,
|
||||||
|
ParameterlessMessageKey,
|
||||||
|
SupportedLocale,
|
||||||
|
TextDirection,
|
||||||
|
} from "./message-contract.js";
|
||||||
|
export type { MessageKey } from "./catalog.js";
|
||||||
|
export {
|
||||||
|
FORMAT_FALLBACK,
|
||||||
|
formatDate,
|
||||||
|
formatList,
|
||||||
|
formatNumber,
|
||||||
|
formatRelativeTime,
|
||||||
|
selectMessage,
|
||||||
|
selectPlural,
|
||||||
|
} from "./formatters.js";
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useState,
|
||||||
|
} from "react";
|
||||||
|
|
||||||
|
import {
|
||||||
|
formatDate,
|
||||||
|
formatList,
|
||||||
|
formatNumber,
|
||||||
|
formatRelativeTime,
|
||||||
|
selectMessage,
|
||||||
|
selectPlural,
|
||||||
|
} from "./formatters.js";
|
||||||
|
import {
|
||||||
|
formatMessage,
|
||||||
|
localeDirection,
|
||||||
|
normalizeLocale,
|
||||||
|
resolveMessage,
|
||||||
|
type MessageArguments,
|
||||||
|
type SupportedLocale,
|
||||||
|
type TextDirection,
|
||||||
|
} from "./message-contract.js";
|
||||||
|
import type { MessageKey } from "./catalog.js";
|
||||||
|
|
||||||
|
type LocaleContextValue = Readonly<{
|
||||||
|
locale: SupportedLocale;
|
||||||
|
direction: TextDirection;
|
||||||
|
setLocale(locale: SupportedLocale): void;
|
||||||
|
message<Key extends MessageKey>(
|
||||||
|
key: Key,
|
||||||
|
...args: MessageArguments<Key>
|
||||||
|
): string;
|
||||||
|
resolve(key: string): string;
|
||||||
|
date(
|
||||||
|
value: Date | number,
|
||||||
|
options?: Parameters<typeof formatDate>[2],
|
||||||
|
): string;
|
||||||
|
number(value: number, options?: Parameters<typeof formatNumber>[2]): string;
|
||||||
|
relativeTime(
|
||||||
|
value: number,
|
||||||
|
unit: Intl.RelativeTimeFormatUnit,
|
||||||
|
): string;
|
||||||
|
list(values: readonly string[]): string;
|
||||||
|
plural(
|
||||||
|
value: number,
|
||||||
|
choices: Parameters<typeof selectPlural>[2],
|
||||||
|
): string;
|
||||||
|
select(
|
||||||
|
value: string,
|
||||||
|
choices: Readonly<Record<string, string> & { other: string }>,
|
||||||
|
): string;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
const DEFAULT_LOCALE = "ko-KR" as const;
|
||||||
|
const DEFAULT_CONTEXT: LocaleContextValue = Object.freeze({
|
||||||
|
locale: DEFAULT_LOCALE,
|
||||||
|
direction: "ltr",
|
||||||
|
setLocale() {},
|
||||||
|
message: (key, ...args) => formatMessage(DEFAULT_LOCALE, key, ...args),
|
||||||
|
resolve: (key) => resolveMessage(DEFAULT_LOCALE, key),
|
||||||
|
date: (value, options) => formatDate(DEFAULT_LOCALE, value, options),
|
||||||
|
number: (value, options) => formatNumber(DEFAULT_LOCALE, value, options),
|
||||||
|
relativeTime: (value, unit) =>
|
||||||
|
formatRelativeTime(DEFAULT_LOCALE, value, unit),
|
||||||
|
list: (values) => formatList(DEFAULT_LOCALE, values),
|
||||||
|
plural: (value, choices) => selectPlural(DEFAULT_LOCALE, value, choices),
|
||||||
|
select: (value, choices) => selectMessage(value, choices),
|
||||||
|
});
|
||||||
|
const LocaleContext = createContext<LocaleContextValue>(DEFAULT_CONTEXT);
|
||||||
|
|
||||||
|
export function LocaleProvider({
|
||||||
|
children,
|
||||||
|
initialLocale = "ko-KR",
|
||||||
|
}: Readonly<{
|
||||||
|
children: React.ReactNode;
|
||||||
|
initialLocale?: SupportedLocale;
|
||||||
|
}>) {
|
||||||
|
const [locale, setLocaleState] = useState<SupportedLocale>(() =>
|
||||||
|
normalizeLocale(initialLocale),
|
||||||
|
);
|
||||||
|
const direction = localeDirection(locale);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
document.documentElement.lang = locale;
|
||||||
|
document.documentElement.dir = direction;
|
||||||
|
}, [direction, locale]);
|
||||||
|
|
||||||
|
const value = useMemo<LocaleContextValue>(
|
||||||
|
() => ({
|
||||||
|
locale,
|
||||||
|
direction,
|
||||||
|
setLocale: setLocaleState,
|
||||||
|
message: (key, ...args) => formatMessage(locale, key, ...args),
|
||||||
|
resolve: (key) => resolveMessage(locale, key),
|
||||||
|
date: (dateValue, options) => formatDate(locale, dateValue, options),
|
||||||
|
number: (numberValue, options) =>
|
||||||
|
formatNumber(locale, numberValue, options),
|
||||||
|
relativeTime: (relativeValue, unit) =>
|
||||||
|
formatRelativeTime(locale, relativeValue, unit),
|
||||||
|
list: (values) => formatList(locale, values),
|
||||||
|
plural: (pluralValue, choices) =>
|
||||||
|
selectPlural(locale, pluralValue, choices),
|
||||||
|
select: (selectValue, choices) => selectMessage(selectValue, choices),
|
||||||
|
}),
|
||||||
|
[direction, locale],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useLocale(): LocaleContextValue {
|
||||||
|
return useContext(LocaleContext);
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import {
|
||||||
|
EN_MESSAGES,
|
||||||
|
KO_MESSAGES,
|
||||||
|
MESSAGE_CATALOGS,
|
||||||
|
type MessageKey,
|
||||||
|
} from "./catalog.js";
|
||||||
|
|
||||||
|
export const SUPPORTED_LOCALES = Object.freeze([
|
||||||
|
"ko-KR",
|
||||||
|
"en-US",
|
||||||
|
"en-XA",
|
||||||
|
"ar-EG",
|
||||||
|
] as const);
|
||||||
|
export type SupportedLocale = (typeof SUPPORTED_LOCALES)[number];
|
||||||
|
export type TextDirection = "ltr" | "rtl";
|
||||||
|
|
||||||
|
export type MessageParameters = Readonly<{
|
||||||
|
"action.closeNamed": { title: string };
|
||||||
|
"action.alertCloseNamed": { title: string };
|
||||||
|
"route.loadingNamed": { title: string };
|
||||||
|
"route.documentTitle": { title: string; appName: string };
|
||||||
|
"template.supportReference": { reference: string };
|
||||||
|
"form.remaining": { count: number };
|
||||||
|
"boot.supportReference": { reference: string };
|
||||||
|
}>;
|
||||||
|
export type ParameterlessMessageKey = Exclude<
|
||||||
|
MessageKey,
|
||||||
|
keyof MessageParameters
|
||||||
|
>;
|
||||||
|
|
||||||
|
export type MessageArguments<Key extends MessageKey> =
|
||||||
|
Key extends keyof MessageParameters
|
||||||
|
? [parameters: MessageParameters[Key]]
|
||||||
|
: [parameters?: never];
|
||||||
|
|
||||||
|
const PLACEHOLDER_PATTERN = /\{([a-zA-Z][a-zA-Z0-9]*)\}/g;
|
||||||
|
const FALLBACK_LOCALE = "ko-KR" as const;
|
||||||
|
export const MESSAGE_KEY_ALIASES = Object.freeze({
|
||||||
|
"action.login": "action.reauth",
|
||||||
|
"async.pending": "common.processing",
|
||||||
|
} as const satisfies Readonly<Record<string, MessageKey>>);
|
||||||
|
|
||||||
|
export function normalizeLocale(locale: string): SupportedLocale {
|
||||||
|
if ((SUPPORTED_LOCALES as readonly string[]).includes(locale)) {
|
||||||
|
return locale as SupportedLocale;
|
||||||
|
}
|
||||||
|
const language = locale.split("-")[0]?.toLowerCase();
|
||||||
|
if (language === "ko") return "ko-KR";
|
||||||
|
if (language === "ar") return "ar-EG";
|
||||||
|
if (language === "en") return "en-US";
|
||||||
|
return FALLBACK_LOCALE;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function localeDirection(locale: SupportedLocale): TextDirection {
|
||||||
|
return locale === "ar-EG" ? "rtl" : "ltr";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function messagePlaceholders(template: string): readonly string[] {
|
||||||
|
return Object.freeze(
|
||||||
|
[...template.matchAll(PLACEHOLDER_PATTERN)].map((match) => match[1] ?? ""),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveMessage(
|
||||||
|
locale: string,
|
||||||
|
key: string,
|
||||||
|
parameters?: Readonly<Record<string, string | number>>,
|
||||||
|
): string {
|
||||||
|
const normalized = normalizeLocale(locale);
|
||||||
|
const sourceLocale: keyof typeof MESSAGE_CATALOGS =
|
||||||
|
normalized === "en-XA" ? "en-US" : normalized;
|
||||||
|
const catalog =
|
||||||
|
MESSAGE_CATALOGS[sourceLocale] ??
|
||||||
|
MESSAGE_CATALOGS[FALLBACK_LOCALE];
|
||||||
|
const fallback = KO_MESSAGES["common.unavailable"];
|
||||||
|
const canonicalKey =
|
||||||
|
MESSAGE_KEY_ALIASES[key as keyof typeof MESSAGE_KEY_ALIASES] ?? key;
|
||||||
|
const template = catalog[canonicalKey as MessageKey] ?? fallback;
|
||||||
|
const placeholders = messagePlaceholders(template);
|
||||||
|
if (
|
||||||
|
placeholders.some(
|
||||||
|
(placeholder) =>
|
||||||
|
parameters?.[placeholder] === undefined ||
|
||||||
|
parameters?.[placeholder] === null,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
const formatted = template.replace(
|
||||||
|
PLACEHOLDER_PATTERN,
|
||||||
|
(_, placeholder: string) => String(parameters?.[placeholder] ?? ""),
|
||||||
|
);
|
||||||
|
return normalized === "en-XA" ? pseudoLocalize(formatted) : formatted;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatMessage<Key extends MessageKey>(
|
||||||
|
locale: string,
|
||||||
|
key: Key,
|
||||||
|
...args: MessageArguments<Key>
|
||||||
|
): string {
|
||||||
|
return resolveMessage(
|
||||||
|
locale,
|
||||||
|
key,
|
||||||
|
args[0] as Readonly<Record<string, string | number>> | undefined,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pseudoLocalize(value: string): string {
|
||||||
|
const expanded = value.replace(/[A-Za-z]/g, (character) => {
|
||||||
|
const replacements: Readonly<Record<string, string>> = {
|
||||||
|
a: "á",
|
||||||
|
e: "é",
|
||||||
|
i: "í",
|
||||||
|
o: "ó",
|
||||||
|
u: "ú",
|
||||||
|
A: "Á",
|
||||||
|
E: "É",
|
||||||
|
I: "Í",
|
||||||
|
O: "Ó",
|
||||||
|
U: "Ú",
|
||||||
|
};
|
||||||
|
return replacements[character] ?? character;
|
||||||
|
});
|
||||||
|
return `[${expanded} ···]`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function catalogKeys(
|
||||||
|
locale: "ko-KR" | "en-US" | "ar-EG",
|
||||||
|
): MessageKey[] {
|
||||||
|
return Object.keys(MESSAGE_CATALOGS[locale]).sort() as MessageKey[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fallbackMessage() {
|
||||||
|
return EN_MESSAGES["common.unavailable"];
|
||||||
|
}
|
||||||
@@ -12,20 +12,22 @@ import {
|
|||||||
MenuIcon,
|
MenuIcon,
|
||||||
Select,
|
Select,
|
||||||
} from "../design-system/index.js";
|
} from "../design-system/index.js";
|
||||||
|
import { useLocale } from "../i18n/index.js";
|
||||||
import { useSession } from "../providers/session-provider.jsx";
|
import { useSession } from "../providers/session-provider.jsx";
|
||||||
import { useTheme } from "../providers/theme-provider.jsx";
|
import { useTheme } from "../providers/theme-provider.jsx";
|
||||||
|
|
||||||
const SESSION_LABELS = Object.freeze({
|
const SESSION_MESSAGE_KEYS = Object.freeze({
|
||||||
authenticated: "인증됨",
|
authenticated: "shell.session.authenticated",
|
||||||
unauthenticated: "로그인 전",
|
unauthenticated: "shell.session.unauthenticated",
|
||||||
"recovery-pending": "복구 대기",
|
"recovery-pending": "shell.session.recoveryPending",
|
||||||
"integration-failed": "연동 필요",
|
"integration-failed": "shell.session.integrationFailed",
|
||||||
});
|
});
|
||||||
|
|
||||||
export function AppShell() {
|
export function AppShell() {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const { sessionState, beginSignIn, signOut, recover } = useSession();
|
const { sessionState, beginSignIn, signOut, recover } = useSession();
|
||||||
const { preference, setPreference } = useTheme();
|
const { preference, setPreference } = useTheme();
|
||||||
|
const { locale, setLocale, message } = useLocale();
|
||||||
const [navigationOpen, setNavigationOpen] = useState(false);
|
const [navigationOpen, setNavigationOpen] = useState(false);
|
||||||
const [sessionActionPending, setSessionActionPending] = useState(false);
|
const [sessionActionPending, setSessionActionPending] = useState(false);
|
||||||
const [sessionActionFailed, setSessionActionFailed] = useState(false);
|
const [sessionActionFailed, setSessionActionFailed] = useState(false);
|
||||||
@@ -56,20 +58,20 @@ export function AppShell() {
|
|||||||
|
|
||||||
const sessionActionLabel =
|
const sessionActionLabel =
|
||||||
sessionState === "authenticated"
|
sessionState === "authenticated"
|
||||||
? "로그아웃"
|
? message("action.signOut")
|
||||||
: sessionState === "recovery-pending"
|
: sessionState === "recovery-pending"
|
||||||
? "세션 복구"
|
? message("action.recoverSession")
|
||||||
: "로그인";
|
: message("action.reauth");
|
||||||
const integrationAvailable = sessionState !== "integration-failed";
|
const integrationAvailable = sessionState !== "integration-failed";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="app-shell">
|
<div className="app-shell">
|
||||||
<a className="skip-link" href="#main-content">
|
<a className="skip-link" href="#main-content">
|
||||||
본문으로 건너뛰기
|
{message("shell.skipToContent")}
|
||||||
</a>
|
</a>
|
||||||
<header className="app-shell__header">
|
<header className="app-shell__header">
|
||||||
<IconButton
|
<IconButton
|
||||||
accessibleName="메뉴"
|
accessibleName={message("shell.menu")}
|
||||||
className="app-shell__menu-button"
|
className="app-shell__menu-button"
|
||||||
aria-controls="mobile-primary-navigation"
|
aria-controls="mobile-primary-navigation"
|
||||||
aria-expanded={navigationOpen}
|
aria-expanded={navigationOpen}
|
||||||
@@ -79,17 +81,17 @@ export function AppShell() {
|
|||||||
<MenuIcon />
|
<MenuIcon />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
<NavLink className="app-shell__brand" to={routePath("APP_HOME")}>
|
<NavLink className="app-shell__brand" to={routePath("APP_HOME")}>
|
||||||
Frontend Skeleton
|
{message("common.appName")}
|
||||||
</NavLink>
|
</NavLink>
|
||||||
<div className="app-shell__session">
|
<div className="app-shell__session">
|
||||||
<Select
|
<Select
|
||||||
className="theme-selector"
|
className="theme-selector"
|
||||||
id="theme-preference"
|
id="theme-preference"
|
||||||
label="색상 테마"
|
label={message("shell.theme")}
|
||||||
options={[
|
options={[
|
||||||
{ value: "system", label: "시스템 테마" },
|
{ value: "system", label: message("shell.theme.system") },
|
||||||
{ value: "light", label: "라이트 테마" },
|
{ value: "light", label: message("shell.theme.light") },
|
||||||
{ value: "dark", label: "다크 테마" },
|
{ value: "dark", label: message("shell.theme.dark") },
|
||||||
]}
|
]}
|
||||||
value={preference}
|
value={preference}
|
||||||
onChange={(event) =>
|
onChange={(event) =>
|
||||||
@@ -100,8 +102,27 @@ export function AppShell() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<Select
|
||||||
|
className="locale-selector"
|
||||||
|
id="locale-preference"
|
||||||
|
label={message("shell.locale")}
|
||||||
|
options={[
|
||||||
|
{ value: "ko-KR", label: message("shell.locale.ko") },
|
||||||
|
{ value: "en-US", label: message("shell.locale.en") },
|
||||||
|
{ value: "en-XA", label: message("shell.locale.pseudo") },
|
||||||
|
{ value: "ar-EG", label: message("shell.locale.rtl") },
|
||||||
|
]}
|
||||||
|
value={locale}
|
||||||
|
onChange={(event) =>
|
||||||
|
setLocale(
|
||||||
|
/** @type {import("../i18n/index.js").SupportedLocale} */ (
|
||||||
|
event.currentTarget.value
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
<span className="session-status" data-state={sessionState}>
|
<span className="session-status" data-state={sessionState}>
|
||||||
{SESSION_LABELS[sessionState]}
|
{message(SESSION_MESSAGE_KEYS[sessionState])}
|
||||||
</span>
|
</span>
|
||||||
{integrationAvailable ? (
|
{integrationAvailable ? (
|
||||||
<Button
|
<Button
|
||||||
@@ -109,24 +130,29 @@ export function AppShell() {
|
|||||||
onClick={() => void runSessionAction()}
|
onClick={() => void runSessionAction()}
|
||||||
size="compact"
|
size="compact"
|
||||||
>
|
>
|
||||||
{sessionActionPending ? "처리 중…" : sessionActionLabel}
|
{sessionActionPending
|
||||||
|
? message("common.processing")
|
||||||
|
: sessionActionLabel}
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
{sessionActionFailed ? (
|
{sessionActionFailed ? (
|
||||||
<p className="app-shell__session-error" role="alert">
|
<p className="app-shell__session-error" role="alert">
|
||||||
세션 작업을 완료하지 못했습니다.
|
{message("shell.session.actionFailed")}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
</header>
|
</header>
|
||||||
<aside className="app-shell__sidebar" aria-label="사이드바">
|
<aside
|
||||||
|
className="app-shell__sidebar"
|
||||||
|
aria-label={message("shell.sidebar")}
|
||||||
|
>
|
||||||
<PrimaryNavigation id="primary-navigation" />
|
<PrimaryNavigation id="primary-navigation" />
|
||||||
</aside>
|
</aside>
|
||||||
<Drawer
|
<Drawer
|
||||||
closeLabel="메뉴 닫기"
|
closeLabel={message("shell.closeMenu")}
|
||||||
onClose={() => setNavigationOpen(false)}
|
onClose={() => setNavigationOpen(false)}
|
||||||
open={navigationOpen}
|
open={navigationOpen}
|
||||||
title="메뉴"
|
title={message("shell.menu")}
|
||||||
>
|
>
|
||||||
<PrimaryNavigation id="mobile-primary-navigation" />
|
<PrimaryNavigation id="mobile-primary-navigation" />
|
||||||
</Drawer>
|
</Drawer>
|
||||||
@@ -141,8 +167,9 @@ export function AppShell() {
|
|||||||
* @param {{ id: string }} props
|
* @param {{ id: string }} props
|
||||||
*/
|
*/
|
||||||
function PrimaryNavigation({ id }) {
|
function PrimaryNavigation({ id }) {
|
||||||
|
const { resolve, message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<nav id={id} aria-label="주요 탐색">
|
<nav id={id} aria-label={message("shell.primaryNavigation")}>
|
||||||
<ul className="app-navigation">
|
<ul className="app-navigation">
|
||||||
{NAVIGATION_ROUTES.map((definition) => (
|
{NAVIGATION_ROUTES.map((definition) => (
|
||||||
<li key={definition.routeId}>
|
<li key={definition.routeId}>
|
||||||
@@ -153,7 +180,7 @@ function PrimaryNavigation({ id }) {
|
|||||||
end={definition.path === "/"}
|
end={definition.path === "/"}
|
||||||
to={definition.path}
|
to={definition.path}
|
||||||
>
|
>
|
||||||
{definition.navigationLabel}
|
{resolve(`route.${definition.routeId}.navigation`)}
|
||||||
</NavLink>
|
</NavLink>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -2,17 +2,19 @@ import { Link } from "react-router-dom";
|
|||||||
|
|
||||||
import { routePath } from "../../features/installed-feature-contracts.js";
|
import { routePath } from "../../features/installed-feature-contracts.js";
|
||||||
import { PageHeader } from "../design-system/index.js";
|
import { PageHeader } from "../design-system/index.js";
|
||||||
|
import { useLocale } from "../i18n/index.js";
|
||||||
|
|
||||||
export default function NotFoundPage() {
|
export default function NotFoundPage() {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<section className="ui-page">
|
<section className="ui-page">
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title="페이지를 찾을 수 없습니다."
|
title={message("page.notFound.title")}
|
||||||
description="주소를 확인하거나 준비된 시작 화면으로 돌아가세요."
|
description={message("page.notFound.description")}
|
||||||
/>
|
/>
|
||||||
<div>
|
<div>
|
||||||
<Link className="ui-button" to={routePath("APP_HOME")}>
|
<Link className="ui-button" to={routePath("APP_HOME")}>
|
||||||
홈으로 이동
|
{message("action.goHome")}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -28,7 +28,8 @@ import {
|
|||||||
RouteBoundary,
|
RouteBoundary,
|
||||||
} from "../boundaries/render-error-boundary.jsx";
|
} from "../boundaries/render-error-boundary.jsx";
|
||||||
import { ChunkRecoveryBoundary } from "../boundaries/chunk-recovery-boundary.js";
|
import { ChunkRecoveryBoundary } from "../boundaries/chunk-recovery-boundary.js";
|
||||||
import { PageHeader } from "../design-system/index.js";
|
import { Button, PageHeader } from "../design-system/index.js";
|
||||||
|
import { LocaleProvider, useLocale } from "../i18n/index.js";
|
||||||
import { AppShell } from "../layouts/app-shell.jsx";
|
import { AppShell } from "../layouts/app-shell.jsx";
|
||||||
import { useApplication } from "../providers/application-provider.js";
|
import { useApplication } from "../providers/application-provider.js";
|
||||||
import { SessionProvider, useSession } from "../providers/session-provider.jsx";
|
import { SessionProvider, useSession } from "../providers/session-provider.jsx";
|
||||||
@@ -54,6 +55,8 @@ export function useRouteInput(): ParsedRouteInput {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function RouteLoadingSurface({ definition }: { definition: RouteDefinition }) {
|
function RouteLoadingSurface({ definition }: { definition: RouteDefinition }) {
|
||||||
|
const { message, resolve } = useLocale();
|
||||||
|
const title = resolve(`route.${definition.routeId}.title`);
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
className="ui-page route-loading"
|
className="ui-page route-loading"
|
||||||
@@ -62,8 +65,10 @@ function RouteLoadingSurface({ definition }: { definition: RouteDefinition }) {
|
|||||||
data-surface={definition.loadingSurface}
|
data-surface={definition.loadingSurface}
|
||||||
>
|
>
|
||||||
<div className="ui-skeleton" aria-hidden="true" />
|
<div className="ui-skeleton" aria-hidden="true" />
|
||||||
<p>화면을 준비하고 있습니다.</p>
|
<p>{message("route.loading")}</p>
|
||||||
<span className="visually-hidden">{definition.title} 로딩 중</span>
|
<span className="visually-hidden">
|
||||||
|
{message("route.loadingNamed", { title })}
|
||||||
|
</span>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -73,35 +78,48 @@ function RouteFailureSurface({
|
|||||||
}: {
|
}: {
|
||||||
definition?: RouteDefinition;
|
definition?: RouteDefinition;
|
||||||
}) {
|
}) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
className="ui-page"
|
className="ui-page"
|
||||||
data-surface={definition?.errorSurface ?? "route-boundary"}
|
data-surface={definition?.errorSurface ?? "route-boundary"}
|
||||||
>
|
>
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title="화면을 표시하지 못했습니다."
|
title={message("route.failure.title")}
|
||||||
description="잠시 후 다시 시도해 주세요. 문제가 계속되면 운영 지원 참조 정보를 확인하세요."
|
description={message("route.failure.description")}
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function InvalidRouteSurface({ code }: { code: string }) {
|
function InvalidRouteSurface({ code }: { code: string }) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<section className="ui-page" data-surface="invalid-route">
|
<section className="ui-page" data-surface="invalid-route">
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title="올바르지 않은 주소입니다."
|
title={message("route.invalid.title")}
|
||||||
description="주소의 경로 또는 검색 조건을 확인해 주세요."
|
description={message("route.invalid.description")}
|
||||||
/>
|
/>
|
||||||
<p data-route-error={code}>안전한 탐색 링크를 사용해 주세요.</p>
|
<p data-route-error={code}>{message("route.invalid.action")}</p>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function RouteLifecycle({ definition }: { definition: RouteDefinition }) {
|
function RouteLifecycle({
|
||||||
|
definition,
|
||||||
|
buildId,
|
||||||
|
}: {
|
||||||
|
definition: RouteDefinition;
|
||||||
|
buildId: string;
|
||||||
|
}) {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
|
const { message, resolve } = useLocale();
|
||||||
|
const { diagnostics } = useApplication();
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
document.title = `${definition.title} · Frontend Skeleton`;
|
document.title = message("route.documentTitle", {
|
||||||
|
title: resolve(`route.${definition.routeId}.title`),
|
||||||
|
appName: message("common.appName"),
|
||||||
|
});
|
||||||
const main = document.getElementById("main-content");
|
const main = document.getElementById("main-content");
|
||||||
main?.focus({ preventScroll: true });
|
main?.focus({ preventScroll: true });
|
||||||
try {
|
try {
|
||||||
@@ -111,7 +129,19 @@ function RouteLifecycle({ definition }: { definition: RouteDefinition }) {
|
|||||||
} catch {
|
} catch {
|
||||||
// Non-browser test hosts may not implement scrolling.
|
// Non-browser test hosts may not implement scrolling.
|
||||||
}
|
}
|
||||||
}, [definition, location.key, location.pathname]);
|
diagnostics.reportRouteChanged({
|
||||||
|
routeId: definition.routeId,
|
||||||
|
buildId,
|
||||||
|
});
|
||||||
|
}, [
|
||||||
|
buildId,
|
||||||
|
definition,
|
||||||
|
diagnostics,
|
||||||
|
location.key,
|
||||||
|
location.pathname,
|
||||||
|
message,
|
||||||
|
resolve,
|
||||||
|
]);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -146,6 +176,7 @@ function ProtectedRoute({
|
|||||||
}) {
|
}) {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const { sessionState, beginSignIn, recover } = useSession();
|
const { sessionState, beginSignIn, recover } = useSession();
|
||||||
|
const { message } = useLocale();
|
||||||
const [pending, setPending] = useState(false);
|
const [pending, setPending] = useState(false);
|
||||||
const [failed, setFailed] = useState(false);
|
const [failed, setFailed] = useState(false);
|
||||||
const decision = decideRouteAccess(routeId, sessionState);
|
const decision = decideRouteAccess(routeId, sessionState);
|
||||||
@@ -173,8 +204,8 @@ function ProtectedRoute({
|
|||||||
return (
|
return (
|
||||||
<section className="ui-page" data-surface="auth-integration-required">
|
<section className="ui-page" data-surface="auth-integration-required">
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title="로그인 연동이 필요합니다."
|
title={message("route.auth.integration.title")}
|
||||||
description="외부 인증 소유자가 연결되면 이 보호 라우트를 사용할 수 있습니다."
|
description={message("route.auth.integration.description")}
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
@@ -183,24 +214,30 @@ function ProtectedRoute({
|
|||||||
return (
|
return (
|
||||||
<section className="ui-page" data-surface="authentication-required">
|
<section className="ui-page" data-surface="authentication-required">
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title={recovering ? "세션을 복구하고 있습니다." : "세션이 필요합니다."}
|
title={
|
||||||
|
recovering
|
||||||
|
? message("route.auth.recovering.title")
|
||||||
|
: message("route.auth.required.title")
|
||||||
|
}
|
||||||
description={
|
description={
|
||||||
recovering
|
recovering
|
||||||
? "기존 세션 확인을 계속하려면 복구를 실행하세요."
|
? message("route.auth.recovering.description")
|
||||||
: "이 화면은 인증 연동 지점을 확인하기 위한 보호 라우트입니다."
|
: message("route.auth.required.description")
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<button
|
<Button
|
||||||
className="ui-button"
|
|
||||||
type="button"
|
|
||||||
disabled={pending}
|
disabled={pending}
|
||||||
onClick={() => void continueSession()}
|
onClick={() => void continueSession()}
|
||||||
>
|
>
|
||||||
{pending ? "처리 중…" : recovering ? "세션 복구" : "로그인 시작"}
|
{pending
|
||||||
</button>
|
? message("common.processing")
|
||||||
|
: recovering
|
||||||
|
? message("action.recoverSession")
|
||||||
|
: message("action.signIn")}
|
||||||
|
</Button>
|
||||||
{failed ? (
|
{failed ? (
|
||||||
<p className="ui-terminal-error" role="alert">
|
<p className="ui-terminal-error" role="alert">
|
||||||
세션 작업을 완료하지 못했습니다.
|
{message("shell.session.actionFailed")}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
</section>
|
</section>
|
||||||
@@ -226,7 +263,7 @@ function RegisteredRoute({
|
|||||||
const content = (
|
const content = (
|
||||||
<RouteInputContext.Provider value={parsed.data}>
|
<RouteInputContext.Provider value={parsed.data}>
|
||||||
<CanonicalRouteRedirect input={parsed.data} />
|
<CanonicalRouteRedirect input={parsed.data} />
|
||||||
<RouteLifecycle definition={definition} />
|
<RouteLifecycle definition={definition} buildId={buildId} />
|
||||||
<Suspense fallback={<RouteLoadingSurface definition={definition} />}>
|
<Suspense fallback={<RouteLoadingSurface definition={definition} />}>
|
||||||
<ChunkRecoveryBoundary
|
<ChunkRecoveryBoundary
|
||||||
chunkId={definition.chunkId}
|
chunkId={definition.chunkId}
|
||||||
@@ -300,10 +337,12 @@ export function AppRouter({
|
|||||||
[basename, buildId],
|
[basename, buildId],
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
|
<LocaleProvider>
|
||||||
<ThemeProvider>
|
<ThemeProvider>
|
||||||
<SessionProvider>
|
<SessionProvider>
|
||||||
<RouterProvider router={router} />
|
<RouterProvider router={router} />
|
||||||
</SessionProvider>
|
</SessionProvider>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
|
</LocaleProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -131,11 +131,13 @@
|
|||||||
margin-inline-start: auto;
|
margin-inline-start: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.theme-selector {
|
.theme-selector,
|
||||||
|
.locale-selector {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.theme-selector .ui-field__label {
|
.theme-selector .ui-field__label,
|
||||||
|
.locale-selector .ui-field__label {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
width: 1px;
|
width: 1px;
|
||||||
height: 1px;
|
height: 1px;
|
||||||
@@ -147,13 +149,18 @@
|
|||||||
border: 0;
|
border: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.theme-selector .ui-field__input {
|
.theme-selector .ui-field__input,
|
||||||
|
.locale-selector .ui-field__input {
|
||||||
min-height: var(--size-control-sm);
|
min-height: var(--size-control-sm);
|
||||||
max-width: 8.5rem;
|
max-width: 8.5rem;
|
||||||
padding: 0.35rem 2rem 0.35rem 0.65rem;
|
padding: 0.35rem 2rem 0.35rem 0.65rem;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.locale-selector .ui-field__input {
|
||||||
|
max-width: 7rem;
|
||||||
|
}
|
||||||
|
|
||||||
.app-shell__session-error {
|
.app-shell__session-error {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: calc(100% + 0.25rem);
|
top: calc(100% + 0.25rem);
|
||||||
@@ -1340,6 +1347,10 @@
|
|||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.app-shell__session .theme-selector {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
.app-shell__brand {
|
.app-shell__brand {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { ReactNode } from "react";
|
|||||||
|
|
||||||
import { PageHeader } from "../components/page-header.jsx";
|
import { PageHeader } from "../components/page-header.jsx";
|
||||||
import { Button } from "../components/ui/button.jsx";
|
import { Button } from "../components/ui/button.jsx";
|
||||||
|
import { useLocale } from "../i18n/index.js";
|
||||||
|
|
||||||
export type PageHeading = Readonly<{
|
export type PageHeading = Readonly<{
|
||||||
title: string;
|
title: string;
|
||||||
@@ -36,10 +37,14 @@ export type PageTemplateSlots = Readonly<{
|
|||||||
}>;
|
}>;
|
||||||
|
|
||||||
export function StandardPage(props: PageTemplateSlots) {
|
export function StandardPage(props: PageTemplateSlots) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<article className="ui-page page-template page-template--standard">
|
<article className="ui-page page-template page-template--standard">
|
||||||
{props.breadcrumb ? (
|
{props.breadcrumb ? (
|
||||||
<nav className="page-template__breadcrumb" aria-label="현재 위치">
|
<nav
|
||||||
|
className="page-template__breadcrumb"
|
||||||
|
aria-label={message("template.breadcrumb")}
|
||||||
|
>
|
||||||
{props.breadcrumb}
|
{props.breadcrumb}
|
||||||
</nav>
|
</nav>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -64,7 +69,10 @@ export function StandardPage(props: PageTemplateSlots) {
|
|||||||
>
|
>
|
||||||
<div className="page-template__content">{props.children}</div>
|
<div className="page-template__content">{props.children}</div>
|
||||||
{props.aside ? (
|
{props.aside ? (
|
||||||
<aside className="page-template__aside" aria-label="관련 정보">
|
<aside
|
||||||
|
className="page-template__aside"
|
||||||
|
aria-label={message("template.relatedInformation")}
|
||||||
|
>
|
||||||
{props.aside}
|
{props.aside}
|
||||||
</aside>
|
</aside>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -83,6 +91,7 @@ export function CollectionPage(
|
|||||||
pagination?: ReactNode;
|
pagination?: ReactNode;
|
||||||
}>,
|
}>,
|
||||||
) {
|
) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<StandardPage
|
<StandardPage
|
||||||
{...props}
|
{...props}
|
||||||
@@ -92,7 +101,7 @@ export function CollectionPage(
|
|||||||
{props.toolbar ? (
|
{props.toolbar ? (
|
||||||
<section
|
<section
|
||||||
className="collection-page__toolbar"
|
className="collection-page__toolbar"
|
||||||
aria-label="검색과 필터"
|
aria-label={message("template.searchAndFilter")}
|
||||||
>
|
>
|
||||||
{props.toolbar}
|
{props.toolbar}
|
||||||
</section>
|
</section>
|
||||||
@@ -117,7 +126,10 @@ export function CollectionPage(
|
|||||||
>
|
>
|
||||||
<div className="collection-page__results">{props.children}</div>
|
<div className="collection-page__results">{props.children}</div>
|
||||||
{props.pagination ? (
|
{props.pagination ? (
|
||||||
<nav className="collection-page__pagination" aria-label="페이지 탐색">
|
<nav
|
||||||
|
className="collection-page__pagination"
|
||||||
|
aria-label={message("template.pagination")}
|
||||||
|
>
|
||||||
{props.pagination}
|
{props.pagination}
|
||||||
</nav>
|
</nav>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -132,16 +144,23 @@ export function DetailPage(
|
|||||||
destructiveAction?: ReactNode;
|
destructiveAction?: ReactNode;
|
||||||
}>,
|
}>,
|
||||||
) {
|
) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<StandardPage {...props}>
|
<StandardPage {...props}>
|
||||||
{props.metadata ? (
|
{props.metadata ? (
|
||||||
<section className="detail-page__metadata" aria-label="요약 정보">
|
<section
|
||||||
|
className="detail-page__metadata"
|
||||||
|
aria-label={message("template.summary")}
|
||||||
|
>
|
||||||
{props.metadata}
|
{props.metadata}
|
||||||
</section>
|
</section>
|
||||||
) : null}
|
) : null}
|
||||||
<div className="detail-page__sections">{props.children}</div>
|
<div className="detail-page__sections">{props.children}</div>
|
||||||
{props.destructiveAction ? (
|
{props.destructiveAction ? (
|
||||||
<section className="detail-page__danger" aria-label="위험 작업">
|
<section
|
||||||
|
className="detail-page__danger"
|
||||||
|
aria-label={message("template.dangerActions")}
|
||||||
|
>
|
||||||
{props.destructiveAction}
|
{props.destructiveAction}
|
||||||
</section>
|
</section>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -190,6 +209,7 @@ export function StatusPage(
|
|||||||
supportReference?: string;
|
supportReference?: string;
|
||||||
}>,
|
}>,
|
||||||
) {
|
) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
className={`ui-page page-template status-page status-page--${props.variant}`}
|
className={`ui-page page-template status-page status-page--${props.variant}`}
|
||||||
@@ -208,7 +228,9 @@ export function StatusPage(
|
|||||||
) : null}
|
) : null}
|
||||||
{props.supportReference ? (
|
{props.supportReference ? (
|
||||||
<p className="status-page__support">
|
<p className="status-page__support">
|
||||||
지원 참조: <code>{props.supportReference}</code>
|
{message("template.supportReference", {
|
||||||
|
reference: props.supportReference,
|
||||||
|
})}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -50,7 +50,9 @@ describe("async UI state matrix", () => {
|
|||||||
render(<AsyncSurface state={state}>existing content</AsyncSurface>);
|
render(<AsyncSurface state={state}>existing content</AsyncSurface>);
|
||||||
|
|
||||||
expect(screen.getByText("existing content")).toBeVisible();
|
expect(screen.getByText("existing content")).toBeVisible();
|
||||||
expect(screen.getByRole("status")).toHaveTextContent("refreshing");
|
expect(screen.getByRole("status")).toHaveTextContent(
|
||||||
|
"최신 정보를 확인하고 있습니다.",
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("connects stale retry and conflict resolution to real callbacks", async () => {
|
it("connects stale retry and conflict resolution to real callbacks", async () => {
|
||||||
|
|||||||
@@ -60,7 +60,9 @@ describe("chunk recovery boundary classification", () => {
|
|||||||
</FeatureBoundary>,
|
</FeatureBoundary>,
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(screen.getByRole("alert")).toHaveTextContent("error.render_failure");
|
expect(screen.getByRole("alert")).toHaveTextContent(
|
||||||
|
"화면을 표시하지 못했습니다.",
|
||||||
|
);
|
||||||
expect(recover).not.toHaveBeenCalled();
|
expect(recover).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -189,7 +189,7 @@ describe("design-system platform interactions", () => {
|
|||||||
await user.click(screen.getByRole("button", { name: "중복" }));
|
await user.click(screen.getByRole("button", { name: "중복" }));
|
||||||
expect(screen.getByText("×2")).toBeVisible();
|
expect(screen.getByText("×2")).toBeVisible();
|
||||||
await user.click(screen.getByRole("button", { name: "다섯 개" }));
|
await user.click(screen.getByRole("button", { name: "다섯 개" }));
|
||||||
const region = screen.getByRole("region", { name: "Notifications" });
|
const region = screen.getByRole("region", { name: "알림" });
|
||||||
expect(within(region).getAllByRole("article")).toHaveLength(3);
|
expect(within(region).getAllByRole("article")).toHaveLength(3);
|
||||||
expect(within(region).queryByText("알림 0")).not.toBeInTheDocument();
|
expect(within(region).queryByText("알림 0")).not.toBeInTheDocument();
|
||||||
expect(within(region).getByText("알림 4")).toBeVisible();
|
expect(within(region).getByText("알림 4")).toBeVisible();
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Drawer,
|
||||||
|
Pagination,
|
||||||
|
Tabs,
|
||||||
|
} from "../../src/presentation/design-system/index.js";
|
||||||
|
import {
|
||||||
|
LocaleProvider,
|
||||||
|
useLocale,
|
||||||
|
type SupportedLocale,
|
||||||
|
} from "../../src/presentation/i18n/index.js";
|
||||||
|
|
||||||
|
function LocaleHarness() {
|
||||||
|
const { direction, locale, message, setLocale } = useLocale();
|
||||||
|
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<label htmlFor="test-locale">{message("shell.locale")}</label>
|
||||||
|
<select
|
||||||
|
id="test-locale"
|
||||||
|
onChange={(event) =>
|
||||||
|
setLocale(event.currentTarget.value as SupportedLocale)
|
||||||
|
}
|
||||||
|
value={locale}
|
||||||
|
>
|
||||||
|
<option value="ko-KR">한국어</option>
|
||||||
|
<option value="en-US">English</option>
|
||||||
|
<option value="ar-EG">RTL</option>
|
||||||
|
</select>
|
||||||
|
<output>{`${locale}:${direction}`}</output>
|
||||||
|
<Button onClick={() => setDrawerOpen(true)}>
|
||||||
|
{message("shell.menu")}
|
||||||
|
</Button>
|
||||||
|
<Drawer
|
||||||
|
closeLabel={message("shell.closeMenu")}
|
||||||
|
onClose={() => setDrawerOpen(false)}
|
||||||
|
open={drawerOpen}
|
||||||
|
title={message("shell.menu")}
|
||||||
|
>
|
||||||
|
content
|
||||||
|
</Drawer>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("locale provider runtime", () => {
|
||||||
|
it("switches copy and synchronizes the document language and direction", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(
|
||||||
|
<LocaleProvider>
|
||||||
|
<LocaleHarness />
|
||||||
|
</LocaleProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(document.documentElement).toHaveAttribute("lang", "ko-KR");
|
||||||
|
await user.selectOptions(screen.getByLabelText("언어"), "en-US");
|
||||||
|
expect(screen.getByLabelText("Language")).toHaveValue("en-US");
|
||||||
|
expect(document.documentElement).toHaveAttribute("lang", "en-US");
|
||||||
|
expect(document.documentElement).toHaveAttribute("dir", "ltr");
|
||||||
|
|
||||||
|
await user.selectOptions(screen.getByLabelText("Language"), "ar-EG");
|
||||||
|
expect(document.documentElement).toHaveAttribute("lang", "ar-EG");
|
||||||
|
expect(document.documentElement).toHaveAttribute("dir", "rtl");
|
||||||
|
await user.click(screen.getByRole("button", { name: "Menu" }));
|
||||||
|
expect(screen.getByRole("dialog", { name: "Menu" })).toHaveAttribute(
|
||||||
|
"open",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reverses horizontal tab focus semantics in RTL", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(
|
||||||
|
<LocaleProvider initialLocale="ar-EG">
|
||||||
|
<Tabs
|
||||||
|
activation="manual"
|
||||||
|
label="sections"
|
||||||
|
tabs={[
|
||||||
|
{ id: "one", label: "One", panel: "One panel" },
|
||||||
|
{ id: "two", label: "Two", panel: "Two panel" },
|
||||||
|
{ id: "three", label: "Three", panel: "Three panel" },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</LocaleProvider>,
|
||||||
|
);
|
||||||
|
const first = screen.getByRole("tab", { name: "One" });
|
||||||
|
first.focus();
|
||||||
|
await user.keyboard("{ArrowRight}");
|
||||||
|
expect(screen.getByRole("tab", { name: "Three" })).toHaveFocus();
|
||||||
|
await user.keyboard("{ArrowLeft}");
|
||||||
|
expect(first).toHaveFocus();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps pagination semantics while direction-aware icons remain decorative", () => {
|
||||||
|
render(
|
||||||
|
<LocaleProvider initialLocale="ar-EG">
|
||||||
|
<Pagination
|
||||||
|
label="pages"
|
||||||
|
nextLabel="Next page"
|
||||||
|
onChange={() => {}}
|
||||||
|
page={2}
|
||||||
|
pageCount={3}
|
||||||
|
pageLabel={(page) => `Page ${page}`}
|
||||||
|
previousLabel="Previous page"
|
||||||
|
/>
|
||||||
|
</LocaleProvider>,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
screen.getByRole("button", { name: "Previous page" }),
|
||||||
|
).toBeEnabled();
|
||||||
|
expect(screen.getByRole("button", { name: "Next page" })).toBeEnabled();
|
||||||
|
expect(screen.queryByRole("img")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -86,7 +86,7 @@ describe("page template slot contracts", () => {
|
|||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
expect(screen.getByRole("heading", { level: 1, name: "Offline" })).toBeVisible();
|
expect(screen.getByRole("heading", { level: 1, name: "Offline" })).toBeVisible();
|
||||||
expect(screen.getByText("SAFE-123")).toBeVisible();
|
expect(screen.getByText(/SAFE-123/)).toBeVisible();
|
||||||
expect(document.body).not.toHaveTextContent("stack");
|
expect(document.body).not.toHaveTextContent("stack");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -28,7 +28,9 @@ describe("render recovery boundaries", () => {
|
|||||||
</FeatureBoundary>,
|
</FeatureBoundary>,
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(screen.getByRole("alert")).toHaveTextContent("error.render_failure");
|
expect(screen.getByRole("alert")).toHaveTextContent(
|
||||||
|
"화면을 표시하지 못했습니다.",
|
||||||
|
);
|
||||||
expect(onRenderFailure).toHaveBeenCalledWith({
|
expect(onRenderFailure).toHaveBeenCalledWith({
|
||||||
routeId: "APP_HOME",
|
routeId: "APP_HOME",
|
||||||
buildId: "build-a",
|
buildId: "build-a",
|
||||||
@@ -83,7 +85,7 @@ describe("render recovery boundaries", () => {
|
|||||||
</FeatureBoundary>,
|
</FeatureBoundary>,
|
||||||
);
|
);
|
||||||
shouldThrow = false;
|
shouldThrow = false;
|
||||||
await user.click(screen.getByRole("button", { name: "retry" }));
|
await user.click(screen.getByRole("button", { name: "다시 시도" }));
|
||||||
view.rerender(
|
view.rerender(
|
||||||
<FeatureBoundary routeId="APP_HOME" buildId="build-a">
|
<FeatureBoundary routeId="APP_HOME" buildId="build-a">
|
||||||
<Recoverable />
|
<Recoverable />
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { expect, test } from "@playwright/test";
|
||||||
|
|
||||||
|
test("switches the shell locale and keeps pseudo-locale copy within compact layout", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.setViewportSize({ width: 320, height: 720 });
|
||||||
|
await page.goto("/");
|
||||||
|
|
||||||
|
const locale = page.getByRole("combobox", { name: "언어" });
|
||||||
|
await locale.selectOption("en-US");
|
||||||
|
await expect(page.locator("html")).toHaveAttribute("lang", "en-US");
|
||||||
|
await expect(page.locator("html")).toHaveAttribute("dir", "ltr");
|
||||||
|
await expect(page.getByRole("button", { name: "Menu" })).toBeVisible();
|
||||||
|
|
||||||
|
await page.getByRole("combobox", { name: "Language" }).selectOption("en-XA");
|
||||||
|
await expect(page.locator("html")).toHaveAttribute("lang", "en-XA");
|
||||||
|
const dimensions = await page.evaluate(() => ({
|
||||||
|
clientWidth: document.documentElement.clientWidth,
|
||||||
|
scrollWidth: document.documentElement.scrollWidth,
|
||||||
|
}));
|
||||||
|
expect(dimensions.scrollWidth).toBeLessThanOrEqual(dimensions.clientWidth);
|
||||||
|
await expect(page.getByRole("button", { name: /Ménú/ })).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("applies RTL to the shell and modal navigation without changing action semantics", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.setViewportSize({ width: 390, height: 844 });
|
||||||
|
await page.goto("/");
|
||||||
|
await page.getByRole("combobox", { name: "언어" }).selectOption("ar-EG");
|
||||||
|
|
||||||
|
await expect(page.locator("html")).toHaveAttribute("lang", "ar-EG");
|
||||||
|
await expect(page.locator("html")).toHaveAttribute("dir", "rtl");
|
||||||
|
const trigger = page.getByRole("button", { name: "Menu" });
|
||||||
|
await trigger.click();
|
||||||
|
await expect(page.getByRole("dialog", { name: "Menu" })).toBeVisible();
|
||||||
|
await expect(page.getByRole("navigation", { name: "Primary navigation" }))
|
||||||
|
.toHaveCount(1);
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
await expect(trigger).toBeFocused();
|
||||||
|
});
|
||||||
@@ -72,10 +72,10 @@ describe("reference feature boundary contracts", () => {
|
|||||||
createdAt: "2026-07-26T00:00:00.000Z",
|
createdAt: "2026-07-26T00:00:00.000Z",
|
||||||
});
|
});
|
||||||
if (!("id" in model)) throw new Error("expected one model");
|
if (!("id" in model)) throw new Error("expected one model");
|
||||||
expect(toReferenceView(model, () => "formatted")).toEqual({
|
expect(toReferenceView(model)).toEqual({
|
||||||
resourceId: "reference-1",
|
resourceId: "reference-1",
|
||||||
title: "Example",
|
title: "Example",
|
||||||
createdAtLabel: "formatted",
|
createdAt: "2026-07-26T00:00:00.000Z",
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import { createHttpClient } from "../../../src/adapters/http/client.js";
|
||||||
|
import { createReferenceHttpGateway } from "../../../src/features/reference-feature/adapters/reference-http-gateway.js";
|
||||||
|
import { createReferenceFeatureInput } from "../../../src/features/reference-feature/application/reference-feature-api.js";
|
||||||
|
import { REFERENCE_FEATURE_CONTRACT } from "../../../src/features/reference-feature/contracts/reference-feature-contract.js";
|
||||||
|
import { mapReferenceOperation } from "../../../src/features/reference-feature/contracts/reference-mapper.js";
|
||||||
|
import {
|
||||||
|
validateReferencePayload,
|
||||||
|
validateReferenceRequest,
|
||||||
|
} from "../../../src/features/reference-feature/contracts/reference-schemas.js";
|
||||||
|
|
||||||
|
describe("reference feature diagnostics correlation", () => {
|
||||||
|
it("preserves route, operation and request correlation through the vertical path", async () => {
|
||||||
|
const record = vi.fn();
|
||||||
|
const operations =
|
||||||
|
REFERENCE_FEATURE_CONTRACT.apiOperations as Readonly<
|
||||||
|
Record<
|
||||||
|
string,
|
||||||
|
ReturnType<
|
||||||
|
NonNullable<Parameters<typeof createHttpClient>[0]["getOperation"]>
|
||||||
|
>
|
||||||
|
>
|
||||||
|
>;
|
||||||
|
const client = createHttpClient({
|
||||||
|
baseUrl: "https://api.test",
|
||||||
|
fetcher: async () =>
|
||||||
|
Response.json({
|
||||||
|
success: true,
|
||||||
|
data: [{ id: "reference-1", name: "Reference" }],
|
||||||
|
meta: { requestId: "safe-request", traceId: "safe-trace" },
|
||||||
|
}),
|
||||||
|
getOperation(operationId) {
|
||||||
|
const operation = operations[operationId];
|
||||||
|
if (!operation) throw new Error("Unregistered reference operation");
|
||||||
|
return operation;
|
||||||
|
},
|
||||||
|
validatePayload: validateReferencePayload,
|
||||||
|
validateRequest: validateReferenceRequest,
|
||||||
|
mapPayload: mapReferenceOperation,
|
||||||
|
correlationIdFactory: () => "reference-correlation",
|
||||||
|
diagnostics: { record },
|
||||||
|
scheduler: {
|
||||||
|
setTimeout: () => 1,
|
||||||
|
clearTimeout: () => {},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const application = createReferenceFeatureInput(
|
||||||
|
createReferenceHttpGateway(client),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
application.listResources({ limit: 20 }),
|
||||||
|
).resolves.toMatchObject({ ok: true });
|
||||||
|
expect(record).toHaveBeenCalledOnce();
|
||||||
|
expect(record).toHaveBeenCalledWith({
|
||||||
|
level: "info",
|
||||||
|
eventId: "http.request.completed",
|
||||||
|
context: expect.objectContaining({
|
||||||
|
route_id: "REFERENCE_RESOURCE_LIST",
|
||||||
|
operation_id: "LIST_REFERENCE_RESOURCES",
|
||||||
|
correlation_id: "reference-correlation",
|
||||||
|
outcome: "success",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -55,7 +55,7 @@ function inputWith(
|
|||||||
value: {
|
value: {
|
||||||
resourceId: "created",
|
resourceId: "created",
|
||||||
title: name,
|
title: name,
|
||||||
createdAtLabel: null,
|
createdAt: null,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
getResource: async (resourceId) => ({
|
getResource: async (resourceId) => ({
|
||||||
@@ -63,7 +63,7 @@ function inputWith(
|
|||||||
value: {
|
value: {
|
||||||
resourceId,
|
resourceId,
|
||||||
title: "Detail",
|
title: "Detail",
|
||||||
createdAtLabel: null,
|
createdAt: null,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
...overrides,
|
...overrides,
|
||||||
@@ -90,7 +90,7 @@ describe("reference feature page states", () => {
|
|||||||
{
|
{
|
||||||
resourceId: "reference-1",
|
resourceId: "reference-1",
|
||||||
title: "Loaded",
|
title: "Loaded",
|
||||||
createdAtLabel: null,
|
createdAt: null,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
@@ -191,7 +191,7 @@ describe("reference feature page states", () => {
|
|||||||
{
|
{
|
||||||
resourceId: "existing",
|
resourceId: "existing",
|
||||||
title: "Existing",
|
title: "Existing",
|
||||||
createdAtLabel: null,
|
createdAt: null,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
@@ -209,7 +209,7 @@ describe("reference feature page states", () => {
|
|||||||
{
|
{
|
||||||
resourceId: "recovered",
|
resourceId: "recovered",
|
||||||
title: "Recovered",
|
title: "Recovered",
|
||||||
createdAtLabel: null,
|
createdAt: null,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
@@ -217,7 +217,9 @@ describe("reference feature page states", () => {
|
|||||||
await screen.findByText("Existing");
|
await screen.findByText("Existing");
|
||||||
await user.click(screen.getByRole("button", { name: "새로고침" }));
|
await user.click(screen.getByRole("button", { name: "새로고침" }));
|
||||||
|
|
||||||
expect(await screen.findByText("stale-degraded")).toBeVisible();
|
expect(
|
||||||
|
await screen.findByText("기존 정보를 표시하고 있습니다."),
|
||||||
|
).toBeVisible();
|
||||||
expect(screen.getByText("Existing")).toBeVisible();
|
expect(screen.getByText("Existing")).toBeVisible();
|
||||||
await user.click(screen.getByRole("button", { name: "다시 시도" }));
|
await user.click(screen.getByRole("button", { name: "다시 시도" }));
|
||||||
expect(await screen.findByText("Recovered")).toBeVisible();
|
expect(await screen.findByText("Recovered")).toBeVisible();
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export function leakToConsole(token: string) {
|
||||||
|
console.error("UNKNOWN_DIAGNOSTIC_EVENT", token);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
export function leakSensitiveContext(telemetry: {
|
||||||
|
emit(eventName: string, context: Record<string, unknown>): void;
|
||||||
|
}) {
|
||||||
|
telemetry.emit("api.request.failed", {
|
||||||
|
authorization: "Bearer secret",
|
||||||
|
request_body: { email: "private@example.test" },
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
export function UnsafeBackendFailure({
|
||||||
|
failure,
|
||||||
|
}: Readonly<{ failure: { message: string } }>) {
|
||||||
|
return <p>{failure.message}</p>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export function HardcodedCommonAction() {
|
||||||
|
return <button type="button">다시 시도</button>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export function UnsafeTranslatedMarkup({ value }: Readonly<{ value: string }>) {
|
||||||
|
return <p dangerouslySetInnerHTML={{ __html: value }} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import type { DiagnosticsPort } from "../../../src/application/ports/diagnostics-port.js";
|
||||||
|
import type { TelemetryPort } from "../../../src/application/ports/telemetry-port.js";
|
||||||
|
|
||||||
|
declare const diagnostics: DiagnosticsPort;
|
||||||
|
declare const telemetry: TelemetryPort;
|
||||||
|
|
||||||
|
diagnostics.record({
|
||||||
|
level: "fatal",
|
||||||
|
eventId: "UNKNOWN_DIAGNOSTIC_EVENT",
|
||||||
|
});
|
||||||
|
telemetry.emit("unknown.telemetry.event", {});
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { formatMessage } from "../../../src/presentation/i18n/index.js";
|
||||||
|
|
||||||
|
formatMessage("ko-KR", "unknown.translation.key");
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { formatMessage } from "../../../src/presentation/i18n/index.js";
|
||||||
|
|
||||||
|
formatMessage("en-US", "route.documentTitle");
|
||||||
|
formatMessage("en-US", "route.documentTitle", { title: "Missing app name" });
|
||||||
|
formatMessage("en-US", "action.retry", { unexpected: "value" });
|
||||||
@@ -5,7 +5,8 @@ import { createApplication } from "../../src/application/create-application.js";
|
|||||||
* @param {{
|
* @param {{
|
||||||
* session?: import("../../src/application/ports/auth-session-port.js").AuthSessionPort,
|
* session?: import("../../src/application/ports/auth-session-port.js").AuthSessionPort,
|
||||||
* preferences?: import("../../src/application/ports/storage-port.js").StoragePort,
|
* preferences?: import("../../src/application/ports/storage-port.js").StoragePort,
|
||||||
* diagnostics?: import("../../src/application/ports/telemetry-port.js").TelemetryPort,
|
* diagnostics?: import("../../src/application/ports/diagnostics-port.js").DiagnosticsPort,
|
||||||
|
* telemetry?: import("../../src/application/ports/telemetry-port.js").TelemetryPort,
|
||||||
* releaseInfo?: import("../../src/application/ports/release-info-port.js").ReleaseInfoPort,
|
* releaseInfo?: import("../../src/application/ports/release-info-port.js").ReleaseInfoPort,
|
||||||
* navigation?: { reload(): void },
|
* navigation?: { reload(): void },
|
||||||
* featureInputs?: Readonly<Record<string, unknown>>
|
* featureInputs?: Readonly<Record<string, unknown>>
|
||||||
@@ -22,7 +23,8 @@ export function createTestApplication(overrides = {}) {
|
|||||||
write: () => ({ ok: /** @type {const} */ (true) }),
|
write: () => ({ ok: /** @type {const} */ (true) }),
|
||||||
remove: () => ({ ok: /** @type {const} */ (true) }),
|
remove: () => ({ ok: /** @type {const} */ (true) }),
|
||||||
},
|
},
|
||||||
diagnostics: overrides.diagnostics ?? { emit: () => {} },
|
diagnostics: overrides.diagnostics ?? { record: () => {} },
|
||||||
|
telemetry: overrides.telemetry ?? { emit: () => {} },
|
||||||
releaseInfo:
|
releaseInfo:
|
||||||
overrides.releaseInfo ??
|
overrides.releaseInfo ??
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,193 @@
|
|||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import { createHttpClient } from "../../src/adapters/http/client.js";
|
||||||
|
import type { DiagnosticRecordInput } from "../../src/contracts/diagnostics.js";
|
||||||
|
import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.js";
|
||||||
|
|
||||||
|
function successResponse(data: unknown) {
|
||||||
|
return Response.json({
|
||||||
|
success: true,
|
||||||
|
data,
|
||||||
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function failureResponse(status: number) {
|
||||||
|
return Response.json(
|
||||||
|
{
|
||||||
|
success: false,
|
||||||
|
error: { code: "TEMPORARY" },
|
||||||
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||||
|
},
|
||||||
|
{ status },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type EmittedEvent = Readonly<{
|
||||||
|
eventName: string;
|
||||||
|
attributes: Readonly<Record<string, unknown>>;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
function harness(fetcher: typeof fetch, maxRetryAttempts = 1) {
|
||||||
|
const records: DiagnosticRecordInput[] = [];
|
||||||
|
const emitted: EmittedEvent[] = [];
|
||||||
|
let currentTime = 0;
|
||||||
|
const client = createHttpClient({
|
||||||
|
...TEST_HTTP_CONTRACT,
|
||||||
|
baseUrl: "https://api.test",
|
||||||
|
fetcher,
|
||||||
|
maxRetryAttempts,
|
||||||
|
clock: {
|
||||||
|
now: () => currentTime,
|
||||||
|
sleep: async () => {
|
||||||
|
currentTime += 150;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
scheduler: {
|
||||||
|
setTimeout: () => 1,
|
||||||
|
clearTimeout: () => {},
|
||||||
|
},
|
||||||
|
correlationIdFactory: () => "correlation-fixed",
|
||||||
|
diagnostics: {
|
||||||
|
record(input) {
|
||||||
|
records.push(structuredClone(input));
|
||||||
|
},
|
||||||
|
},
|
||||||
|
telemetry: {
|
||||||
|
emit(eventName, attributes) {
|
||||||
|
emitted.push({
|
||||||
|
eventName,
|
||||||
|
attributes: structuredClone(attributes),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return { client, records, emitted };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("HTTP diagnostics and terminal telemetry", () => {
|
||||||
|
it("records one successful reference route outcome and no failure event", async () => {
|
||||||
|
const { client, records, emitted } = harness(
|
||||||
|
vi.fn(async () => successResponse([])),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
client.execute({
|
||||||
|
operationId: "LIST_ENTITIES",
|
||||||
|
routeId: "TEST_ROUTE",
|
||||||
|
}),
|
||||||
|
).resolves.toMatchObject({ ok: true });
|
||||||
|
|
||||||
|
expect(records).toEqual([
|
||||||
|
{
|
||||||
|
level: "info",
|
||||||
|
eventId: "http.request.completed",
|
||||||
|
context: {
|
||||||
|
route_id: "TEST_ROUTE",
|
||||||
|
operation_id: "LIST_ENTITIES",
|
||||||
|
correlation_id: "correlation-fixed",
|
||||||
|
outcome: "success",
|
||||||
|
error_kind: "NONE",
|
||||||
|
http_status_group: "none",
|
||||||
|
attempt_count_bucket: "1",
|
||||||
|
duration_bucket: "lt100ms",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(emitted).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("summarizes retry recovery once without a terminal failure event", async () => {
|
||||||
|
const fetcher = vi
|
||||||
|
.fn<typeof fetch>()
|
||||||
|
.mockResolvedValueOnce(failureResponse(503))
|
||||||
|
.mockResolvedValueOnce(successResponse([]));
|
||||||
|
const { client, records, emitted } = harness(fetcher);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
client.execute({
|
||||||
|
operationId: "LIST_ENTITIES",
|
||||||
|
routeId: "TEST_ROUTE",
|
||||||
|
}),
|
||||||
|
).resolves.toMatchObject({ ok: true });
|
||||||
|
|
||||||
|
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||||
|
expect(records).toHaveLength(1);
|
||||||
|
expect(records[0]).toMatchObject({
|
||||||
|
eventId: "http.request.completed",
|
||||||
|
context: {
|
||||||
|
outcome: "recovered",
|
||||||
|
correlation_id: "correlation-fixed",
|
||||||
|
duration_bucket: "100-499ms",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(emitted).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("emits one bounded terminal failure after all attempts", async () => {
|
||||||
|
const fetcher = vi.fn(async () => failureResponse(503));
|
||||||
|
const { client, records, emitted } = harness(fetcher);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
client.execute({
|
||||||
|
operationId: "CREATE_ENTITY",
|
||||||
|
routeId: "TEST_ROUTE",
|
||||||
|
body: { name: "private user input" },
|
||||||
|
idempotencyKey: "private-idempotency-key",
|
||||||
|
}),
|
||||||
|
).resolves.toMatchObject({
|
||||||
|
ok: false,
|
||||||
|
error: { kind: "SERVER_FAILURE" },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||||
|
expect(records).toHaveLength(1);
|
||||||
|
expect(emitted).toEqual([
|
||||||
|
{
|
||||||
|
eventName: "api.request.failed",
|
||||||
|
attributes: {
|
||||||
|
error_kind: "SERVER_FAILURE",
|
||||||
|
http_status_group: "5xx",
|
||||||
|
attempt_count_bucket: "2",
|
||||||
|
route_id: "TEST_ROUTE",
|
||||||
|
operation_id: "CREATE_ENTITY",
|
||||||
|
duration_bucket: "100-499ms",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(JSON.stringify({ records, emitted })).not.toMatch(
|
||||||
|
/private user input|private-idempotency-key/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("records navigation abort without failure telemetry", async () => {
|
||||||
|
const caller = new AbortController();
|
||||||
|
caller.abort("navigation");
|
||||||
|
const fetcher = vi.fn(async (request: RequestInfo | URL) => {
|
||||||
|
const signal = (request as Request).signal;
|
||||||
|
if (signal.aborted) throw new DOMException("aborted", "AbortError");
|
||||||
|
return successResponse([]);
|
||||||
|
});
|
||||||
|
const { client, records, emitted } = harness(
|
||||||
|
fetcher as unknown as typeof fetch,
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
client.execute({
|
||||||
|
operationId: "LIST_ENTITIES",
|
||||||
|
routeId: "TEST_ROUTE",
|
||||||
|
signal: caller.signal,
|
||||||
|
}),
|
||||||
|
).resolves.toMatchObject({
|
||||||
|
ok: false,
|
||||||
|
error: { kind: "REQUEST_ABORTED" },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(records).toHaveLength(1);
|
||||||
|
expect(records[0]).toMatchObject({
|
||||||
|
eventId: "http.request.completed",
|
||||||
|
context: { outcome: "aborted", error_kind: "REQUEST_ABORTED" },
|
||||||
|
});
|
||||||
|
expect(emitted).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -36,6 +36,7 @@ describe("application input/output boundary", () => {
|
|||||||
it("uses fake output ports for preference, session, and safe diagnostics flows", () => {
|
it("uses fake output ports for preference, session, and safe diagnostics flows", () => {
|
||||||
const write = vi.fn(() => ({ ok: true as const }));
|
const write = vi.fn(() => ({ ok: true as const }));
|
||||||
const emit = vi.fn();
|
const emit = vi.fn();
|
||||||
|
const record = vi.fn();
|
||||||
const ports = {
|
const ports = {
|
||||||
session: {
|
session: {
|
||||||
getState: () => "authenticated" as const,
|
getState: () => "authenticated" as const,
|
||||||
@@ -49,7 +50,8 @@ describe("application input/output boundary", () => {
|
|||||||
write,
|
write,
|
||||||
remove: () => ({ ok: true as const }),
|
remove: () => ({ ok: true as const }),
|
||||||
},
|
},
|
||||||
diagnostics: { emit },
|
diagnostics: { record },
|
||||||
|
telemetry: { emit },
|
||||||
releaseInfo: {
|
releaseInfo: {
|
||||||
getCurrent: async () => ({
|
getCurrent: async () => ({
|
||||||
buildId: "build-a",
|
buildId: "build-a",
|
||||||
@@ -82,20 +84,43 @@ describe("application input/output boundary", () => {
|
|||||||
buildId: "build-a",
|
buildId: "build-a",
|
||||||
boundaryName: "route",
|
boundaryName: "route",
|
||||||
});
|
});
|
||||||
|
expect(record).toHaveBeenCalledWith({
|
||||||
|
level: "error",
|
||||||
|
eventId: "ui.render.failed",
|
||||||
|
context: {
|
||||||
|
route_id: "APP_HOME",
|
||||||
|
build_id: "build-a",
|
||||||
|
component_boundary: "route",
|
||||||
|
},
|
||||||
|
});
|
||||||
expect(emit).toHaveBeenCalledWith("ui.render.failed", {
|
expect(emit).toHaveBeenCalledWith("ui.render.failed", {
|
||||||
route_id: "APP_HOME",
|
route_id: "APP_HOME",
|
||||||
build_id: "build-a",
|
build_id: "build-a",
|
||||||
component_boundary: "route",
|
component_boundary: "route",
|
||||||
});
|
});
|
||||||
|
application.diagnostics.reportRouteChanged({
|
||||||
|
routeId: "APP_HOME",
|
||||||
|
buildId: "build-a",
|
||||||
|
});
|
||||||
|
expect(record).toHaveBeenCalledWith({
|
||||||
|
level: "info",
|
||||||
|
eventId: "route.changed",
|
||||||
|
context: { route_id: "APP_HOME", build_id: "build-a" },
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not let a failing diagnostics output escape into presentation", () => {
|
it("does not let a failing diagnostics output escape into presentation", () => {
|
||||||
const application = createTestApplication({
|
const application = createTestApplication({
|
||||||
diagnostics: {
|
diagnostics: {
|
||||||
emit() {
|
record() {
|
||||||
throw new Error("sink details");
|
throw new Error("sink details");
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
telemetry: {
|
||||||
|
emit() {
|
||||||
|
throw new Error("telemetry details");
|
||||||
|
},
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(() =>
|
expect(() =>
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import { describe, expect, it, vi } from "vitest";
|
|||||||
import { createApplication } from "../../src/application/create-application.js";
|
import { createApplication } from "../../src/application/create-application.js";
|
||||||
import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.js";
|
import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.js";
|
||||||
import type { StoragePort } from "../../src/application/ports/storage-port.js";
|
import type { StoragePort } from "../../src/application/ports/storage-port.js";
|
||||||
|
import type { DiagnosticsPort } from "../../src/application/ports/diagnostics-port.js";
|
||||||
|
import type { TelemetryPort } from "../../src/application/ports/telemetry-port.js";
|
||||||
|
|
||||||
type ReleaseFixture = {
|
type ReleaseFixture = {
|
||||||
buildId: string;
|
buildId: string;
|
||||||
@@ -40,12 +42,15 @@ function applicationWith(options: {
|
|||||||
storage?: StoragePort;
|
storage?: StoragePort;
|
||||||
refresh?: () => Promise<ReturnType<typeof release>>;
|
refresh?: () => Promise<ReturnType<typeof release>>;
|
||||||
reload?: () => void;
|
reload?: () => void;
|
||||||
|
diagnostics?: DiagnosticsPort;
|
||||||
|
telemetry?: TelemetryPort;
|
||||||
}) {
|
}) {
|
||||||
const current = release("build-a", "release-a");
|
const current = release("build-a", "release-a");
|
||||||
return createApplication({
|
return createApplication({
|
||||||
session: createAnonymousSessionAdapter(),
|
session: createAnonymousSessionAdapter(),
|
||||||
preferences: options.storage ?? memoryStorage(),
|
preferences: options.storage ?? memoryStorage(),
|
||||||
diagnostics: { emit: () => {} },
|
diagnostics: options.diagnostics ?? { record: () => {} },
|
||||||
|
telemetry: options.telemetry ?? { emit: () => {} },
|
||||||
releaseInfo: {
|
releaseInfo: {
|
||||||
getCurrent: async () => current,
|
getCurrent: async () => current,
|
||||||
refresh:
|
refresh:
|
||||||
@@ -59,7 +64,13 @@ function applicationWith(options: {
|
|||||||
describe("production chunk recovery application input", () => {
|
describe("production chunk recovery application input", () => {
|
||||||
it("reloads exactly once for one active build/release pair", async () => {
|
it("reloads exactly once for one active build/release pair", async () => {
|
||||||
const reload = vi.fn();
|
const reload = vi.fn();
|
||||||
const application = applicationWith({ reload });
|
const record = vi.fn<DiagnosticsPort["record"]>();
|
||||||
|
const emit = vi.fn<TelemetryPort["emit"]>();
|
||||||
|
const application = applicationWith({
|
||||||
|
reload,
|
||||||
|
diagnostics: { record },
|
||||||
|
telemetry: { emit },
|
||||||
|
});
|
||||||
const input = {
|
const input = {
|
||||||
chunkId: "route-home",
|
chunkId: "route-home",
|
||||||
failureKind: "CHUNK_LOAD_FAILURE" as const,
|
failureKind: "CHUNK_LOAD_FAILURE" as const,
|
||||||
@@ -69,6 +80,20 @@ describe("production chunk recovery application input", () => {
|
|||||||
action: "reload-once",
|
action: "reload-once",
|
||||||
releasePair: "build-a/release-a->build-b/release-b",
|
releasePair: "build-a/release-a->build-b/release-b",
|
||||||
});
|
});
|
||||||
|
expect(record).toHaveBeenCalledWith({
|
||||||
|
level: "warn",
|
||||||
|
eventId: "release.mismatch.detected",
|
||||||
|
context: {
|
||||||
|
build_id: "build-a",
|
||||||
|
active_release_id: "release-b",
|
||||||
|
mismatch_kind: "BUILD_MISMATCH",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(emit).toHaveBeenCalledWith("release.mismatch.detected", {
|
||||||
|
build_id: "build-a",
|
||||||
|
active_release_id: "release-b",
|
||||||
|
mismatch_kind: "BUILD_MISMATCH",
|
||||||
|
});
|
||||||
await expect(application.recovery.recoverChunk(input)).resolves.toEqual({
|
await expect(application.recovery.recoverChunk(input)).resolves.toEqual({
|
||||||
action: "support",
|
action: "support",
|
||||||
reason: "reload-already-attempted",
|
reason: "reload-already-attempted",
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import {
|
||||||
|
createDiagnosticsAdapter,
|
||||||
|
getLastBootEvidence,
|
||||||
|
noOpDiagnostics,
|
||||||
|
recordBootFailure,
|
||||||
|
} from "../../src/adapters/diagnostics/bounded-diagnostics.js";
|
||||||
|
import {
|
||||||
|
projectDiagnosticRecord,
|
||||||
|
safeErrorKind,
|
||||||
|
} from "../../src/contracts/diagnostics.js";
|
||||||
|
|
||||||
|
describe("structured diagnostics contract", () => {
|
||||||
|
it("projects only registered, bounded context with deterministic time", () => {
|
||||||
|
const projected = projectDiagnosticRecord(
|
||||||
|
{
|
||||||
|
level: "info",
|
||||||
|
eventId: "route.changed",
|
||||||
|
context: { route_id: "APP_HOME", build_id: "build-a" },
|
||||||
|
},
|
||||||
|
() => 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(projected).toEqual({
|
||||||
|
success: true,
|
||||||
|
record: {
|
||||||
|
level: "info",
|
||||||
|
eventId: "route.changed",
|
||||||
|
timestamp: "1970-01-01T00:00:00.000Z",
|
||||||
|
context: { route_id: "APP_HOME", build_id: "build-a" },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
projectDiagnosticRecord({
|
||||||
|
level: "error",
|
||||||
|
eventId: "ui.render.failed",
|
||||||
|
context: { raw_url: "https://example.test/private?token=secret" },
|
||||||
|
}),
|
||||||
|
).toEqual({ success: false, reason: "unknown-context" });
|
||||||
|
expect(
|
||||||
|
projectDiagnosticRecord({
|
||||||
|
level: "error",
|
||||||
|
eventId: "ui.render.failed",
|
||||||
|
context: { route_id: "private value with whitespace" },
|
||||||
|
}),
|
||||||
|
).toEqual({ success: false, reason: "invalid-context" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("bounds evidence and isolates throwing sinks and hostile error objects", () => {
|
||||||
|
const sink = vi.fn(() => {
|
||||||
|
throw new Error("sink-secret");
|
||||||
|
});
|
||||||
|
const adapter = createDiagnosticsAdapter({
|
||||||
|
maxEntries: 1,
|
||||||
|
now: () => 0,
|
||||||
|
sink,
|
||||||
|
});
|
||||||
|
const circular: Record<string, unknown> = { name: "TypeError" };
|
||||||
|
circular.self = circular;
|
||||||
|
const hostile = new Proxy(
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
get() {
|
||||||
|
throw new Error("private getter");
|
||||||
|
},
|
||||||
|
ownKeys() {
|
||||||
|
throw new Error("private keys");
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(safeErrorKind(circular)).toBe("TYPE_ERROR");
|
||||||
|
expect(safeErrorKind(hostile)).toBe("UNKNOWN_FAILURE");
|
||||||
|
expect(
|
||||||
|
projectDiagnosticRecord({
|
||||||
|
level: "error",
|
||||||
|
eventId: "ui.render.failed",
|
||||||
|
context: hostile,
|
||||||
|
}),
|
||||||
|
).toEqual({ success: false, reason: "serialization-failure" });
|
||||||
|
expect(() =>
|
||||||
|
adapter.record({
|
||||||
|
level: "info",
|
||||||
|
eventId: "route.changed",
|
||||||
|
context: { route_id: "APP_HOME" },
|
||||||
|
}),
|
||||||
|
).not.toThrow();
|
||||||
|
adapter.record({
|
||||||
|
level: "warn",
|
||||||
|
eventId: "cache.operation.failed",
|
||||||
|
context: { operation: "query", error_kind: "UNKNOWN_FAILURE" },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(adapter.entries()).toHaveLength(1);
|
||||||
|
expect(adapter.entries()[0]?.eventId).toBe("cache.operation.failed");
|
||||||
|
expect(adapter.dropped()).toEqual({
|
||||||
|
"queue-full": 1,
|
||||||
|
"sink-failure": 2,
|
||||||
|
});
|
||||||
|
expect(JSON.stringify(adapter.entries())).not.toMatch(
|
||||||
|
/sink-secret|private getter/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("creates safe pre-mount boot evidence and supports a true no-op", () => {
|
||||||
|
const circular: Record<string, unknown> = {
|
||||||
|
name: "TypeError",
|
||||||
|
token: "credential-value",
|
||||||
|
stack: "private-stack",
|
||||||
|
};
|
||||||
|
circular.self = circular;
|
||||||
|
|
||||||
|
expect(() =>
|
||||||
|
recordBootFailure(
|
||||||
|
circular,
|
||||||
|
{
|
||||||
|
buildId: "build-a",
|
||||||
|
configSchemaVersion: "1",
|
||||||
|
supportReference: "support-private",
|
||||||
|
},
|
||||||
|
() => 0,
|
||||||
|
),
|
||||||
|
).not.toThrow();
|
||||||
|
const evidence = getLastBootEvidence();
|
||||||
|
expect(evidence?.diagnostic?.eventId).toBe("app.boot.failed");
|
||||||
|
expect(evidence?.telemetry).toMatchObject({
|
||||||
|
eventName: "app.boot.failed",
|
||||||
|
timestamp: "1970-01-01T00:00:00.000Z",
|
||||||
|
});
|
||||||
|
expect(JSON.stringify(evidence)).not.toMatch(
|
||||||
|
/credential-value|private-stack|support-private/,
|
||||||
|
);
|
||||||
|
expect(() =>
|
||||||
|
noOpDiagnostics.record({
|
||||||
|
level: "error",
|
||||||
|
eventId: "app.boot.failed",
|
||||||
|
}),
|
||||||
|
).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import {
|
||||||
|
catalogKeys,
|
||||||
|
FORMAT_FALLBACK,
|
||||||
|
formatDate,
|
||||||
|
formatList,
|
||||||
|
formatMessage,
|
||||||
|
formatNumber,
|
||||||
|
formatRelativeTime,
|
||||||
|
localeDirection,
|
||||||
|
messagePlaceholders,
|
||||||
|
normalizeLocale,
|
||||||
|
resolveMessage,
|
||||||
|
selectMessage,
|
||||||
|
selectPlural,
|
||||||
|
} from "../../src/presentation/i18n/index.js";
|
||||||
|
import {
|
||||||
|
EN_MESSAGES,
|
||||||
|
KO_MESSAGES,
|
||||||
|
MESSAGE_CATALOGS,
|
||||||
|
} from "../../src/presentation/i18n/catalog.js";
|
||||||
|
|
||||||
|
describe("internationalization message contract", () => {
|
||||||
|
it("keeps every registered catalog and interpolation contract in parity", () => {
|
||||||
|
expect(catalogKeys("en-US")).toEqual(catalogKeys("ko-KR"));
|
||||||
|
expect(catalogKeys("ar-EG")).toEqual(catalogKeys("ko-KR"));
|
||||||
|
|
||||||
|
for (const key of catalogKeys("ko-KR")) {
|
||||||
|
expect(messagePlaceholders(EN_MESSAGES[key])).toEqual(
|
||||||
|
messagePlaceholders(KO_MESSAGES[key]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
expect(MESSAGE_CATALOGS["ar-EG"]).toBe(EN_MESSAGES);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("formats typed parameters and expands the pseudo locale", () => {
|
||||||
|
expect(
|
||||||
|
formatMessage("en-US", "route.documentTitle", {
|
||||||
|
title: "Settings",
|
||||||
|
appName: "Skeleton",
|
||||||
|
}),
|
||||||
|
).toBe("Settings · Skeleton");
|
||||||
|
const pseudo = formatMessage("en-XA", "action.closeNamed", {
|
||||||
|
title: "Account",
|
||||||
|
});
|
||||||
|
expect(pseudo).toMatch(/^[.+ ···]$/);
|
||||||
|
expect(pseudo.length).toBeGreaterThan("Close Account".length);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back safely for unknown locale, key and missing interpolation", () => {
|
||||||
|
expect(normalizeLocale("fr-FR")).toBe("ko-KR");
|
||||||
|
expect(resolveMessage("fr-FR", "action.retry")).toBe("다시 시도");
|
||||||
|
expect(resolveMessage("en-US", "action.login")).toBe("Sign in");
|
||||||
|
expect(resolveMessage("en-US", "backend.stack.trace")).toBe(
|
||||||
|
"요청한 문구를 표시할 수 없습니다.",
|
||||||
|
);
|
||||||
|
expect(resolveMessage("en-US", "action.closeNamed")).toBe(
|
||||||
|
"요청한 문구를 표시할 수 없습니다.",
|
||||||
|
);
|
||||||
|
expect(resolveMessage("en-US", "backend.stack.trace")).not.toContain(
|
||||||
|
"backend.stack.trace",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("defines direction without inferring it in components", () => {
|
||||||
|
expect(localeDirection("ko-KR")).toBe("ltr");
|
||||||
|
expect(localeDirection("en-XA")).toBe("ltr");
|
||||||
|
expect(localeDirection("ar-EG")).toBe("rtl");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("internationalization formatter contract", () => {
|
||||||
|
const instant = new Date("2026-07-26T23:30:00.000Z");
|
||||||
|
|
||||||
|
it("uses an explicit UTC default and deterministic locale formatting", () => {
|
||||||
|
expect(formatDate("en-US", instant, { dateStyle: "short" })).toBe(
|
||||||
|
"7/26/26",
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
formatDate("en-US", instant, {
|
||||||
|
dateStyle: "short",
|
||||||
|
timeZone: "Asia/Seoul",
|
||||||
|
}),
|
||||||
|
).toBe("7/27/26");
|
||||||
|
expect(formatNumber("en-US", 1234.5)).toBe("1,234.5");
|
||||||
|
expect(formatRelativeTime("en-US", -1, "day")).toBe("yesterday");
|
||||||
|
expect(formatList("en-US", ["one", "two", "three"])).toBe(
|
||||||
|
"one, two, and three",
|
||||||
|
);
|
||||||
|
expect(selectPlural("en-US", 1, { one: "item", other: "items" })).toBe(
|
||||||
|
"item",
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
selectPlural("en-US", 3, { one: "item", other: "items" }),
|
||||||
|
).toBe("items");
|
||||||
|
expect(
|
||||||
|
selectMessage("pending", {
|
||||||
|
ready: "Ready",
|
||||||
|
pending: "Pending",
|
||||||
|
other: "Unknown",
|
||||||
|
}),
|
||||||
|
).toBe("Pending");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not throw or expose invalid formatter input", () => {
|
||||||
|
expect(formatDate("en-US", Number.NaN)).toBe(FORMAT_FALLBACK);
|
||||||
|
expect(formatNumber("en-US", Number.POSITIVE_INFINITY)).toBe(
|
||||||
|
FORMAT_FALLBACK,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
formatDate("en-US", instant, { timeZone: "not/a-time-zone" }),
|
||||||
|
).toBe(FORMAT_FALLBACK);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -52,7 +52,10 @@ describe("TanStack QueryCachePort adapter", () => {
|
|||||||
it("normalizes adapter exceptions without raw key data", async () => {
|
it("normalizes adapter exceptions without raw key data", async () => {
|
||||||
const client = new QueryClient();
|
const client = new QueryClient();
|
||||||
vi.spyOn(client, "invalidateQueries").mockRejectedValue(new Error("secret-key"));
|
vi.spyOn(client, "invalidateQueries").mockRejectedValue(new Error("secret-key"));
|
||||||
const adapter = createQueryCacheAdapter(client);
|
const record = vi.fn();
|
||||||
|
const adapter = createQueryCacheAdapter(client, {
|
||||||
|
diagnostics: { record },
|
||||||
|
});
|
||||||
const result = await adapter.invalidate(["resource", "sensitive-filter"]);
|
const result = await adapter.invalidate(["resource", "sensitive-filter"]);
|
||||||
|
|
||||||
expect(result).toMatchObject({
|
expect(result).toMatchObject({
|
||||||
@@ -60,5 +63,16 @@ describe("TanStack QueryCachePort adapter", () => {
|
|||||||
error: { kind: "QUERY_CACHE_FAILURE" },
|
error: { kind: "QUERY_CACHE_FAILURE" },
|
||||||
});
|
});
|
||||||
expect(JSON.stringify(result)).not.toContain("sensitive-filter");
|
expect(JSON.stringify(result)).not.toContain("sensitive-filter");
|
||||||
|
expect(record).toHaveBeenCalledWith({
|
||||||
|
level: "warn",
|
||||||
|
eventId: "cache.operation.failed",
|
||||||
|
context: {
|
||||||
|
operation: "invalidate",
|
||||||
|
error_kind: "QUERY_CACHE_FAILURE",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(JSON.stringify(record.mock.calls)).not.toMatch(
|
||||||
|
/sensitive-filter|secret-key/,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -46,6 +46,9 @@ describe("runtime adapter composition", () => {
|
|||||||
releaseId: "release-a",
|
releaseId: "release-a",
|
||||||
});
|
});
|
||||||
expect(adapters.infrastructure.queryClient).toBeDefined();
|
expect(adapters.infrastructure.queryClient).toBeDefined();
|
||||||
|
expect(adapters.outputPorts.diagnostics.record).toEqual(expect.any(Function));
|
||||||
|
expect(adapters.outputPorts.telemetry.emit).toEqual(expect.any(Function));
|
||||||
|
expect(adapters.outputPorts.telemetry.pendingCount()).toBe(0);
|
||||||
expect(adapters).not.toHaveProperty("http");
|
expect(adapters).not.toHaveProperty("http");
|
||||||
expect(adapters).not.toHaveProperty("storage");
|
expect(adapters).not.toHaveProperty("storage");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import { createBrowserStorageAdapter } from "../../src/adapters/storage/browser-storage-adapter.js";
|
import { createBrowserStorageAdapter } from "../../src/adapters/storage/browser-storage-adapter.js";
|
||||||
import {
|
import {
|
||||||
@@ -61,13 +61,27 @@ describe("storage registry", () => {
|
|||||||
|
|
||||||
it("falls back to memory when preference storage quota is exceeded", () => {
|
it("falls back to memory when preference storage quota is exceeded", () => {
|
||||||
const localStorage = createStorage({ quota: true });
|
const localStorage = createStorage({ quota: true });
|
||||||
const adapter = createBrowserStorageAdapter({ localStorage });
|
const record = vi.fn();
|
||||||
|
const adapter = createBrowserStorageAdapter({
|
||||||
|
localStorage,
|
||||||
|
diagnostics: { record },
|
||||||
|
});
|
||||||
expect(adapter.write("COLOR_SCHEME", "dark")).toMatchObject({
|
expect(adapter.write("COLOR_SCHEME", "dark")).toMatchObject({
|
||||||
ok: false,
|
ok: false,
|
||||||
fallback: "memory",
|
fallback: "memory",
|
||||||
error: { kind: "STORAGE_QUOTA_EXCEEDED" },
|
error: { kind: "STORAGE_QUOTA_EXCEEDED" },
|
||||||
});
|
});
|
||||||
expect(adapter.read("COLOR_SCHEME")).toEqual({ ok: true, value: "dark" });
|
expect(adapter.read("COLOR_SCHEME")).toEqual({ ok: true, value: "dark" });
|
||||||
|
expect(record).toHaveBeenCalledOnce();
|
||||||
|
expect(record).toHaveBeenCalledWith({
|
||||||
|
level: "warn",
|
||||||
|
eventId: "storage.operation.failed",
|
||||||
|
context: {
|
||||||
|
operation: "write:COLOR_SCHEME",
|
||||||
|
error_kind: "STORAGE_QUOTA_EXCEEDED",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(JSON.stringify(record.mock.calls)).not.toContain("dark");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("discards data from a previous schema version", () => {
|
it("discards data from a previous schema version", () => {
|
||||||
|
|||||||
@@ -33,15 +33,26 @@ describe("telemetry registry and redaction", () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it("uses a default-deny attribute projection", () => {
|
it("redacts forbidden attributes and rejects unknown context", () => {
|
||||||
const projected = projectTelemetryEvent("api.request.failed", {
|
const projected = projectTelemetryEvent("api.request.failed", {
|
||||||
...validAttributes,
|
...validAttributes,
|
||||||
raw_url: "https://api.test/path?token=secret",
|
raw_url: "https://api.test/path?token=secret",
|
||||||
unregistered: "private",
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(projected.success).toBe(true);
|
expect(projected.success).toBe(true);
|
||||||
expect(JSON.stringify(projected)).not.toMatch(/raw_url|token|secret|unregistered/);
|
expect(JSON.stringify(projected)).not.toMatch(/raw_url|token|secret/);
|
||||||
|
expect(
|
||||||
|
projectTelemetryEvent("api.request.failed", {
|
||||||
|
...validAttributes,
|
||||||
|
unregistered: "private",
|
||||||
|
}),
|
||||||
|
).toEqual({ success: false, reason: "unknown-attributes" });
|
||||||
|
expect(
|
||||||
|
projectTelemetryEvent("api.request.failed", {
|
||||||
|
...validAttributes,
|
||||||
|
route_id: "/users/actual-user-id",
|
||||||
|
}),
|
||||||
|
).toEqual({ success: false, reason: "invalid-attribute-value" });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("validates traceparent without exposing invalid values", () => {
|
it("validates traceparent without exposing invalid values", () => {
|
||||||
@@ -71,10 +82,18 @@ describe("best-effort telemetry adapter", () => {
|
|||||||
|
|
||||||
expect(adapter.pendingCount()).toBe(2);
|
expect(adapter.pendingCount()).toBe(2);
|
||||||
expect(adapter.droppedCount()).toBe(1);
|
expect(adapter.droppedCount()).toBe(1);
|
||||||
|
expect(adapter.dropReasons()).toEqual({ "queue-full": 1 });
|
||||||
|
expect(adapter.deliveryEvidence()).toMatchObject({
|
||||||
|
eventName: "telemetry.delivery.dropped",
|
||||||
|
attributes: { reason: "queue-full", queue_size_bucket: "1-10" },
|
||||||
|
});
|
||||||
expect(scheduled).toHaveLength(1);
|
expect(scheduled).toHaveLength(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("degrades on sink failure without throwing or recursive events", async () => {
|
it("degrades on sink failure without throwing or recursive events", async () => {
|
||||||
|
const onDrop = vi.fn(() => {
|
||||||
|
throw new Error("observer unavailable");
|
||||||
|
});
|
||||||
const adapter = createTelemetryAdapter({
|
const adapter = createTelemetryAdapter({
|
||||||
enabled: true,
|
enabled: true,
|
||||||
endpoint: "https://telemetry.test/events",
|
endpoint: "https://telemetry.test/events",
|
||||||
@@ -82,13 +101,50 @@ describe("best-effort telemetry adapter", () => {
|
|||||||
fetcher: async () => {
|
fetcher: async () => {
|
||||||
throw new Error("sink unavailable");
|
throw new Error("sink unavailable");
|
||||||
},
|
},
|
||||||
|
onDrop,
|
||||||
});
|
});
|
||||||
expect(() => adapter.emit("api.request.failed", validAttributes)).not.toThrow();
|
expect(() => adapter.emit("api.request.failed", validAttributes)).not.toThrow();
|
||||||
await expect(adapter.flush()).resolves.toBeUndefined();
|
await expect(adapter.flush()).resolves.toBeUndefined();
|
||||||
expect(adapter.droppedCount()).toBe(1);
|
expect(adapter.droppedCount()).toBe(1);
|
||||||
|
expect(adapter.dropReasons()).toEqual({ "sink-failure": 1 });
|
||||||
|
expect(onDrop).toHaveBeenCalledOnce();
|
||||||
expect(adapter.pendingCount()).toBe(0);
|
expect(adapter.pendingCount()).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("never serializes circular or unbounded event context", () => {
|
||||||
|
const adapter = createTelemetryAdapter({
|
||||||
|
enabled: true,
|
||||||
|
endpoint: "https://telemetry.test/events",
|
||||||
|
schedule: () => {},
|
||||||
|
});
|
||||||
|
const circular = {};
|
||||||
|
circular.self = circular;
|
||||||
|
const hostile = new Proxy(
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
ownKeys() {
|
||||||
|
throw new Error("private proxy value");
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(() =>
|
||||||
|
adapter.emit("api.request.failed", {
|
||||||
|
...validAttributes,
|
||||||
|
unregistered: circular,
|
||||||
|
}),
|
||||||
|
).not.toThrow();
|
||||||
|
expect(adapter.pendingCount()).toBe(0);
|
||||||
|
expect(adapter.dropReasons()).toEqual({ "invalid-context": 1 });
|
||||||
|
expect(() =>
|
||||||
|
adapter.emit("api.request.failed", hostile),
|
||||||
|
).not.toThrow();
|
||||||
|
expect(adapter.dropReasons()).toEqual({
|
||||||
|
"invalid-context": 1,
|
||||||
|
"serialization-failure": 1,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it("performs no network or queue work when disabled", async () => {
|
it("performs no network or queue work when disabled", async () => {
|
||||||
const fetcher = vi.fn();
|
const fetcher = vi.fn();
|
||||||
const adapter = createTelemetryAdapter({
|
const adapter = createTelemetryAdapter({
|
||||||
@@ -102,4 +158,25 @@ describe("best-effort telemetry adapter", () => {
|
|||||||
expect(fetcher).not.toHaveBeenCalled();
|
expect(fetcher).not.toHaveBeenCalled();
|
||||||
expect(adapter.pendingCount()).toBe(0);
|
expect(adapter.pendingCount()).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("flushes on page exit and removes the lifecycle listener", async () => {
|
||||||
|
const lifecycle = new EventTarget();
|
||||||
|
const remove = vi.spyOn(lifecycle, "removeEventListener");
|
||||||
|
const fetcher = vi.fn(async () => new Response(null, { status: 204 }));
|
||||||
|
const adapter = createTelemetryAdapter({
|
||||||
|
enabled: true,
|
||||||
|
endpoint: "https://telemetry.test/events",
|
||||||
|
schedule: () => {},
|
||||||
|
lifecycle,
|
||||||
|
fetcher,
|
||||||
|
});
|
||||||
|
adapter.emit("api.request.failed", validAttributes);
|
||||||
|
|
||||||
|
lifecycle.dispatchEvent(new Event("pagehide"));
|
||||||
|
await vi.waitFor(() => expect(fetcher).toHaveBeenCalledOnce());
|
||||||
|
adapter.dispose();
|
||||||
|
|
||||||
|
expect(adapter.pendingCount()).toBe(0);
|
||||||
|
expect(remove).toHaveBeenCalledWith("pagehide", expect.any(Function));
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user