From aaa384c145d447775e4f4a65654310a2b7eff974 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Wed, 23 Sep 2026 12:42:10 +0900 Subject: [PATCH] =?UTF-8?q?refactor:=20=ED=85=9C=ED=94=8C=EB=A6=BF?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=EA=B8=B0=EB=B3=B8=EC=A0=81=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EC=A0=9C=EA=B3=B5=ED=95=98=EA=B3=A0=20=EC=9E=88?= =?UTF-8?q?=EB=8A=94=20=EC=9B=8C=ED=81=AC=20=ED=94=8C=EB=A1=9C=EC=9A=B0?= =?UTF-8?q?=EC=97=90=20=EB=94=94=EC=9E=90=EC=9D=B8=EA=B3=BC=20=EB=9D=BC?= =?UTF-8?q?=EC=9A=B0=ED=8C=85=20=ED=9D=A1=EC=88=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...21-tech-log-template-utilization-review.md | 654 ++++++++++ ...-tech-log-template-utilization-rereview.md | 121 ++ ...-tech-log-template-utilization-rereview.md | 185 +++ ...9-23-tech-log-application-boundary-i18n.md | 148 +++ ...ch-log-application-boundary-i18n-design.md | 398 ++++++ package.json | 2 +- public/release-manifest.json | 4 +- scripts/check-design-system.ts | 9 +- scripts/check-i18n.ts | 25 +- scripts/check-tech-log-route-literals.ts | 65 + scripts/lib/tech-log-i18n-policy.ts | 75 ++ src/adapters/http/feature-http-binding.ts | 8 +- src/application/view-models/async-state.ts | 5 +- src/bootstrap/main.tsx | 2 + src/bootstrap/runtime-adapters.ts | 71 +- src/contracts/errors.ts | 5 + src/contracts/server-state.ts | 5 + .../adapters/create-tech-log-feature-input.ts | 31 +- .../adapters/http/http-management-gateway.ts | 324 +++-- .../http/http-public-content-gateway.ts | 231 ++-- .../http/http-studio-asset-gateway.ts | 39 +- .../adapters/http/http-studio-gateway.ts | 43 +- .../adapters/http/studio-error-mapping.ts | 43 + .../adapters/http/tech-log-http-binding.ts | 130 ++ .../tech-log/adapters/static/content.ts | 4 +- .../tech-log/adapters/static/public-query.ts | 39 +- .../application/ports/management-gateway.ts | 224 +++- .../ports/public-content-queries.ts | 27 + .../application/studio-application.ts | 243 ++++ .../application/tech-log-feature-input.ts | 10 +- .../management/canonical-source.json | 2 +- .../tech-log/contracts/management/contract.ts | 2 + .../contracts/management/generated.ts | 10 +- .../management/management-api.openapi.yaml | 34 + ...ch-log-management-contract-contribution.ts | 32 +- .../contracts/tech-log-message-catalog.ts | 556 ++++++++- .../tech-log-public-contract-contribution.ts | 24 +- .../tech-log-studio-contract-contribution.ts | 36 +- .../public/components/explore-filter-form.tsx | 23 +- .../public/components/fatal-error-state.tsx | 19 +- .../public/components/latest-index.tsx | 14 +- .../public/components/project-navigation.tsx | 14 +- .../public/components/project-page-header.tsx | 3 +- .../public/components/project-path.tsx | 3 +- .../components/public-document-header.tsx | 21 +- .../public/components/search-dialog.tsx | 103 +- .../public/components/site-header.tsx | 22 +- .../public/pages/explore-kind-page.tsx | 8 +- .../public/pages/explore-page.tsx | 5 +- .../presentation/public/pages/home-page.tsx | 50 +- .../public/pages/profile-page.tsx | 14 +- .../public/pages/project-activity-page.tsx | 3 +- .../public/pages/project-decisions-page.tsx | 9 +- .../public/pages/project-overview-page.tsx | 10 +- .../public/pages/projects-page.tsx | 12 +- .../public/pages/public-not-found-page.tsx | 5 +- .../public/pages/release-page.tsx | 7 +- .../public/pages/releases-page.tsx | 9 +- .../presentation/public/pages/search-page.tsx | 11 +- .../public/pages/topic-variant-page.tsx | 3 +- .../presentation/public/pages/topics-page.tsx | 6 +- .../presentation/public/public-routes.ts | 124 ++ .../presentation/public/public-shell.tsx | 3 +- .../shared/public-render/code-block.tsx | 5 +- .../shared/public-render/evidence-figure.tsx | 47 +- .../public-render/public-record-renderer.tsx | 14 +- .../studio/components/asset-library.tsx | 533 +++----- .../studio/components/asset-picker-dialog.tsx | 84 +- .../studio/components/asset-picker.tsx | 85 +- .../studio/components/asset-upload-dialog.tsx | 302 ++--- .../studio/components/case-fields.tsx | 30 +- .../components/catalog-property-picker.tsx | 21 +- .../components/common-document-fields.tsx | 9 +- .../studio/components/concept-fields.tsx | 15 +- .../components/destructive-confirm-dialog.tsx | 111 +- .../components/document-editor-screen.tsx | 521 ++++---- .../studio/components/document-list.tsx | 553 +++----- .../studio/components/document-status-bar.tsx | 31 +- .../studio/components/guarded-studio-link.tsx | 5 +- .../studio/components/home-focus-editor.tsx | 473 ++++--- .../components/markdown-block-editor.tsx | 31 +- .../studio/components/markdown-toolbar.tsx | 5 +- .../studio/components/new-document-form.tsx | 121 +- .../studio/components/ordered-text-list.tsx | 24 +- .../components/project-decision-fields.tsx | 9 +- .../studio/components/project-editor.tsx | 486 +++----- .../components/public-preview-screen.tsx | 265 ++-- .../publication-event-preview-screen.tsx | 102 +- .../studio/components/publication-list.tsx | 169 ++- .../studio/components/publish-screen.tsx | 197 ++- .../studio/components/question-fields.tsx | 19 +- .../studio/components/reference-fields.tsx | 15 +- .../studio/components/relation-editor.tsx | 20 +- .../studio/components/release-editor.tsx | 465 ++++--- .../studio/components/release-manager.tsx | 262 ++-- .../studio/components/setup-fields.tsx | 21 +- .../studio/components/studio-dashboard.tsx | 64 +- .../studio/components/studio-header.tsx | 83 +- .../studio/components/studio-pagination.tsx | 84 +- .../studio/components/taxonomy-manager.tsx | 423 ++----- .../studio/components/topic-editor.tsx | 570 ++++----- .../studio/components/unpublish-dialog.tsx | 123 +- .../components/unsaved-leave-dialog.tsx | 107 +- .../studio/components/use-before-unload.ts | 13 - .../studio/components/validation-report.tsx | 7 +- .../studio/components/validation-screen.tsx | 171 ++- .../components/warning-acknowledgements.tsx | 7 +- .../use-asset-library-controller.ts | 314 +++++ .../use-document-list-controller.ts | 265 ++++ .../use-project-editor-controller.ts | 248 ++++ .../controllers/use-taxonomy-controller.ts | 212 ++++ .../use-topic-editor-controller.ts | 296 +++++ .../presentation/studio/management-labels.ts | 39 + .../presentation/studio/next-action.ts | 26 +- .../presentation/studio/pages/assets-page.tsx | 6 +- .../studio/pages/studio-not-found-page.tsx | 29 +- .../studio/studio-asset-server-state.ts | 351 ++++++ .../presentation/studio/studio-copy.ts | 71 ++ .../studio/studio-document-server-state.ts | 378 ++++++ .../studio/studio-management-server-state.ts | 1110 +++++++++++++++++ .../presentation/studio/studio-provider.tsx | 135 +- .../presentation/studio/studio-routes.ts | 80 ++ .../studio/studio-runtime-boundary.tsx | 52 +- .../studio/studio-server-state-support.ts | 85 ++ .../presentation/studio/studio-shell.tsx | 16 +- .../studio/studio-workspace-server-state.ts | 345 +++++ .../presentation/studio/use-studio.ts | 37 +- .../tech-log/presentation/styles/globals.css | 221 ++-- .../styles/publication-flow.module.css | 51 +- .../presentation/styles/studio-editor.css | 117 +- .../tech-log/presentation/styles/studio.css | 305 ++++- .../presentation/styles/tech-log-theme.css | 118 ++ .../presentation/tech-log-message.tsx | 9 + .../presentation/tech-log-navigation.ts | 28 +- .../adapters/query/application-query.ts | 43 +- src/presentation/design-system/index.ts | 3 + .../patterns/common-patterns.tsx | 7 +- .../design-system/primitives/core.tsx | 100 +- .../design-system/primitives/forms.tsx | 44 +- .../design-system/primitives/navigation.tsx | 97 +- src/presentation/forms/use-app-form.ts | 2 +- .../forms/use-dirty-navigation-guard.tsx | 76 +- src/presentation/i18n/message-contract.ts | 11 + src/presentation/layouts/app-shell.tsx | 13 +- src/presentation/routes/route-codecs.ts | 107 +- src/presentation/routes/route-url-builder.ts | 63 + src/presentation/templates/page-templates.tsx | 18 +- tests/component/application-query.test.tsx | 46 + tests/component/async-surface.test.tsx | 1 + .../features/tech-log/asset-library.test.tsx | 26 +- tests/features/tech-log/asset-picker.test.tsx | 103 +- .../tech-log/asset-upload-transport.test.ts | 5 +- tests/features/tech-log/feature-input.test.ts | 4 +- .../tech-log/home-focus-choices.test.ts | 4 +- .../tech-log/http-studio-gateway.test.ts | 22 +- .../management-delete-routing.test.ts | 40 +- .../tech-log/mock-dependency-revision.test.ts | 5 +- .../tech-log/navigation-derivation.test.ts | 11 +- .../tech-log/public-question-mapping.test.ts | 7 +- tests/features/tech-log/public-shell.test.tsx | 4 +- .../features/tech-log/route-contract.test.ts | 18 +- .../tech-log/runtime-composition.test.ts | 22 +- .../studio-application-boundary.test.ts | 58 + .../tech-log/studio-asset-gateway.test.ts | 27 +- .../tech-log/studio-csrf-composition.test.ts | 124 +- .../studio-decision-authoring.test.tsx | 21 +- .../tech-log/studio-editor-smoke.test.tsx | 25 +- .../tech-log/studio-publication-flow.test.tsx | 23 +- .../tech-log/studio-save-navigation.test.tsx | 37 +- .../tech-log/studio-screens-smoke.test.tsx | 31 +- .../tech-log/studio-shell-smoke.test.tsx | 18 +- .../studio-validation-preview.test.tsx | 27 +- .../features/tech-log/style-contract.test.ts | 59 +- .../tech-log/taxonomy-projection.test.tsx | 99 ++ .../tech-log/topic-variant-wiring.test.ts | 53 +- .../use-studio-asset-gateway.test.tsx | 46 +- tests/helpers/query-providers.tsx | 103 +- .../studio-application-gateway-adapter.ts | 65 + tests/helpers/studio-install-context.ts | 2 +- tests/helpers/studio-test-provider.tsx | 51 + tests/unit/tech-log-i18n-gate.test.ts | 49 + 181 files changed, 12553 insertions(+), 5280 deletions(-) create mode 100644 docs/reviews/2026-09-21-tech-log-template-utilization-review.md create mode 100644 docs/reviews/2026-09-22-tech-log-template-utilization-rereview.md create mode 100644 docs/reviews/2026-09-23-tech-log-template-utilization-rereview.md create mode 100644 docs/superpowers/plans/2026-09-23-tech-log-application-boundary-i18n.md create mode 100644 docs/superpowers/specs/2026-09-23-tech-log-application-boundary-i18n-design.md create mode 100644 scripts/check-tech-log-route-literals.ts create mode 100644 scripts/lib/tech-log-i18n-policy.ts create mode 100644 src/features/tech-log/adapters/http/tech-log-http-binding.ts create mode 100644 src/features/tech-log/application/studio-application.ts create mode 100644 src/features/tech-log/presentation/public/public-routes.ts delete mode 100644 src/features/tech-log/presentation/studio/components/use-before-unload.ts create mode 100644 src/features/tech-log/presentation/studio/controllers/use-asset-library-controller.ts create mode 100644 src/features/tech-log/presentation/studio/controllers/use-document-list-controller.ts create mode 100644 src/features/tech-log/presentation/studio/controllers/use-project-editor-controller.ts create mode 100644 src/features/tech-log/presentation/studio/controllers/use-taxonomy-controller.ts create mode 100644 src/features/tech-log/presentation/studio/controllers/use-topic-editor-controller.ts create mode 100644 src/features/tech-log/presentation/studio/management-labels.ts create mode 100644 src/features/tech-log/presentation/studio/studio-asset-server-state.ts create mode 100644 src/features/tech-log/presentation/studio/studio-copy.ts create mode 100644 src/features/tech-log/presentation/studio/studio-document-server-state.ts create mode 100644 src/features/tech-log/presentation/studio/studio-management-server-state.ts create mode 100644 src/features/tech-log/presentation/studio/studio-routes.ts create mode 100644 src/features/tech-log/presentation/studio/studio-server-state-support.ts create mode 100644 src/features/tech-log/presentation/studio/studio-workspace-server-state.ts create mode 100644 src/features/tech-log/presentation/styles/tech-log-theme.css create mode 100644 src/features/tech-log/presentation/tech-log-message.tsx create mode 100644 src/presentation/routes/route-url-builder.ts create mode 100644 tests/features/tech-log/studio-application-boundary.test.ts create mode 100644 tests/features/tech-log/taxonomy-projection.test.tsx create mode 100644 tests/helpers/studio-application-gateway-adapter.ts create mode 100644 tests/helpers/studio-test-provider.tsx create mode 100644 tests/unit/tech-log-i18n-gate.test.ts diff --git a/docs/reviews/2026-09-21-tech-log-template-utilization-review.md b/docs/reviews/2026-09-21-tech-log-template-utilization-review.md new file mode 100644 index 0000000..6ff534d --- /dev/null +++ b/docs/reviews/2026-09-21-tech-log-template-utilization-review.md @@ -0,0 +1,654 @@ +# TechLog Frontend — template capability 활용 및 리팩터링 리뷰 + +- 날짜: 2026-09-21 +- 대상: `/shared/codebase/tech-log-frontend` +- 범위: TechLog public / Studio presentation, route 구성, server-state 사용, management/asset gateway 경계, 하드코딩·중복 조회·수동 네트워크 상태 관리 +- 기준: clean-architecture-frontend-template이 제공하는 route contract, server-state query/mutation runtime, failure/idempotency/cancellation 경계를 TechLog 도메인이 우회하지 않는가 + +## 결론 + +이번 검토에서 확인된 핵심 문제는 단순한 컴포넌트 중복보다 **TechLog presentation이 템플릿이 이미 제공하는 runtime 경계를 여러 군데에서 직접 다시 구현하고 있었다는 점**이었다. + +현재 worktree 기준으로 다음 항목은 정리되었다. + +1. Studio presentation의 직접 `StudioGateway` 호출: **0건** +2. Studio presentation의 직접 `ManagementGateway` 호출: **0건** +3. Studio presentation의 직접 `StudioAssetGateway` 호출: **0건** +4. Studio presentation의 수동 `AbortController` 네트워크 lifecycle: **0건** +5. public presentation의 `searchPublicContent("")` 기반 전체 catalog 우회: **0건** +6. Public/Studio route 문자열 직접 조립 방지: **route contract 기반 builder + 정적 검사로 전환** +7. app/test TypeScript, ESLint, architecture, TechLog contract sync, `git diff --check`: **PASS** + +따라서 **template capability를 사용하지 않고 TechLog가 자체 구현으로 우회하던 주요 경계는 현재 정리된 상태**다. + +저장소 기본 Coka 런타임은 Node `v22.23.2`지만, 시스템 Node를 변경하지 않고 `pnpm dlx node@24.11.0`으로 저장소가 요구하는 Node `24.11.0`을 일회성 실행했다. 이 환경에서 TechLog Vitest 전체 **60 files / 416 tests가 모두 통과**했고, template 공통 계층의 component regression도 **27 files / 154 tests가 모두 통과**했다. + +따라서 TechLog의 route/server-state/network lifecycle/template primitive 활용과 Taxonomy N+1 제거는 런타임 테스트까지 검증됐다. 별도로 남는 것은 backend 공통 SpotBugs analysis classpath 문제와, 기준 소스 앱이 없어 새 증거를 만들 수 없는 browser source-parity뿐이다. + +--- + +## 1. Public read model — 검색 API를 projection 대용으로 사용하던 문제 + +### 기존 문제 + +Home/Profile/Projects/Releases 계열에서 필요한 데이터가 “검색 결과”가 아님에도 public search 경로를 전체 catalog 조회처럼 사용하는 흔적이 있었다. + +대표적인 문제는 다음과 같다. + +- 빈 검색어를 전체 데이터 조회처럼 사용 +- Home에 필요한 latest/focus와 검색용 entity catalog의 의미가 섞임 +- Projects/Releases 목록이 검색 도메인의 반환 구조에 의존 +- API 의도가 presentation 요구사항과 맞지 않아 이후 pagination/cache 정책도 검색 정책에 끌려감 + +### 반영 + +`PublicContentQueries`에 화면 의도가 드러나는 read model을 추가했다. + +- `listCatalog()` +- `getLatestEntries()` +- `getHomeFocusItems()` +- `listProjects()` +- `listReleases()` + +HTTP adapter와 static adapter도 같은 port를 구현하도록 맞췄고 public pages는 이 projection을 직접 사용하도록 변경했다. + +### 현재 판단 + +**완료.** + +정적 검색 기준 `src/features/tech-log/presentation` 아래 `searchPublicContent("")` 호출은 0건이다. + +검색은 검색에 사용하고, Home/Projects/Releases projection은 각각 자신의 read model을 사용하게 되었다. + +--- + +## 2. Studio server-state — 컴포넌트가 직접 gateway/useEffect를 소유하던 문제 + +### 기존 문제 + +Studio의 여러 화면이 다음 패턴을 각자 반복하고 있었다. + +```text +useEffect + -> AbortController 생성 + -> gateway 직접 호출 + -> loading/error/data local state + -> cleanup에서 abort +``` + +이 방식은 개별 화면만 보면 동작하지만 template이 제공하는 공통 server-state runtime을 우회한다. + +그 결과 다음 기능이 화면마다 따로 구현됐다. + +- cancellation +- stale response 방지 +- loading/error state +- retry +- duplicate mutation 보호 +- idempotency key 생성/전달 +- mutation failure effect +- query ownership + +### 반영 + +TechLog Studio에 역할별 server-state adapter를 분리했다. + +- `studio-document-server-state.ts` +- `studio-workspace-server-state.ts` +- `studio-management-server-state.ts` +- `studio-asset-server-state.ts` +- `studio-server-state-support.ts` + +이 레이어에서 template의 다음 기능을 사용한다. + +- `bindQuery` +- `useApplicationQuery` +- `useApplicationMutation` +- `useServerStateScope` +- mutation intent / idempotency +- query/mutation failure normalization + +### 이동한 주요 화면 + +- Studio dashboard +- document list +- document editor +- validation +- preview +- publish +- publication list / snapshot +- new document +- Home Focus +- Project editor +- Topic editor +- Release list/editor +- Taxonomy +- Asset picker/library/upload + +DocumentEditor의 TOPIC/PROJECT/RELATION/EVIDENCE catalog도 더 이상 별도 `AbortController + Promise.all`을 소유하지 않고 각각 `useStudioCatalogQuery`로 읽는다. + +### 현재 판단 + +**완료.** + +최종 정적 검색 결과: + +```text +direct ManagementGateway calls in Studio presentation: 0 +direct StudioAssetGateway calls in Studio presentation: 0 +direct StudioGateway operations in Studio components: 0 +manual AbortController in Studio presentation: 0 +``` + +--- + +## 3. ManagementGateway — template mutation runtime을 써도 실제 HTTP까지 보호가 전달되지 않던 문제 + +### 기존 문제 + +Management presentation을 `useApplicationMutation`으로 감싸더라도 port 자체가 signal/idempotency를 받지 않으면 보호가 adapter 직전에서 끊긴다. + +기존 ManagementGateway는 mutation 메서드에 다음 정보가 없었다. + +- `AbortSignal` +- `idempotencyKey` + +즉 화면 레벨에서 공통 mutation runtime을 사용해도 실제 관리 API 요청은 그 intent를 전달받지 못하는 구조였다. + +### 반영 + +ManagementGateway read에는 `RequestOptions`, mutation에는 `IdempotentOptions`를 전달하도록 계약을 강화했다. + +HTTP management adapter는 mutation마다: + +```text +useApplicationMutation + -> MutationIntent + -> Idempotency-Key + -> ManagementGateway + -> StudioOperationExecutor +``` + +경로로 이어진다. + +테스트 타입 오류로 드러난 기존 테스트도 수정했고, management delete / topic variant wiring 테스트는 idempotency key가 executor intent까지 전달되는 형태로 보강했다. + +### 삭제 precondition도 controller로 이동 + +Document list는 목록 계약에 version이 없기 때문에 삭제 직전 최신 document detail을 읽어 `expectedVersion`을 확보해야 한다. + +처음에는 이 한 건만 presentation에서 직접 `gateway.getDocument()`를 호출했지만 최종적으로 composite command: + +`deleteWorkspaceDocument` + +뒤로 이동했다. + +따라서 화면은 “이 document를 삭제한다”는 의도만 전달하고 다음 조립은 controller가 수행한다. + +1. 최신 document 조회 +2. expectedVersion 획득 +3. PROJECT_DECISION이면 project 경로 사용 +4. 나머지는 document kind별 management delete +5. 같은 mutation intent/idempotency key 전달 + +### 현재 판단 + +**완료.** + +--- + +## 4. Asset — 자체 네트워크 상태 머신 중복 + +### 기존 문제 + +Asset 영역은 port 자체는 비교적 잘 분리되어 있었지만 presentation이 다시 네트워크 lifecycle을 직접 관리했다. + +- 목록 검색 +- cursor “더 보기” +- 상세 조회 +- alt/decorative metadata 저장 +- archive +- delete +- upload + +특히 upload는 multipart라 일반 JSON operation과 경로가 다르지만, 이미 `StudioAssetGateway`가 signal/idempotency 계약을 지원하고 있었다. + +### 반영 + +`studio-asset-server-state.ts`로 read/mutation ownership을 이동했다. + +- 기본 list query +- next-page query +- detail query +- update metadata mutation +- delete mutation +- upload mutation + +업로드 mutation identity에는 File 객체 자체만 의존하지 않고 다음 값을 명시적으로 포함한다. + +- file name +- MIME type +- size +- lastModified + +서로 다른 파일이 동일한 in-flight mutation identity로 취급될 가능성을 줄였다. + +AssetLibrary의 cursor append/focus UX는 유지했다. + +### 현재 판단 + +**완료.** + +--- + +## 5. Route — Public/Studio URL SSOT + +### 기존 문제 + +route registry/runtime contract가 이미 있는데 presentation이 URL 문자열을 직접 만들면 route 정의가 두 군데가 된다. + +특히 다음 변경에 취약하다. + +- path rename +- param rename +- query codec 변경 +- URL encoding +- canonical query serialization + +### 반영 + +공통 builder: + +- `src/presentation/routes/route-url-builder.ts` + +TechLog Studio facade: + +- `src/features/tech-log/presentation/studio/studio-routes.ts` +- `src/features/tech-log/presentation/public/public-routes.ts` + +를 추가했다. + +`studioRoutes.documentEdit(id)`, `publicRoutes.project(slug)`처럼 route ID + codec을 통해 URL을 만든다. + +또한 `scripts/check-tech-log-route-literals.ts`를 architecture check에 연결해 TechLog route registry에서 실제 route root를 파생해 Public/Studio route literal을 다시 하드코딩하면 검사가 실패하도록 했다. + +### 현재 판단 + +**완료.** + +주석 안의 `/studio/documents/*` 설명 문자열은 runtime route literal이 아니므로 검사 대상에서 제외된다. + +--- + +## 5.1 후속 리뷰 반영 — form/theme/i18n/Asset boundary + +후속 검토에서 기존 완료 판정을 다시 대조했고 다음 잔여 항목까지 반영했다. + +- Public route도 `public-routes.ts`에서 contract/codec 기반으로 생성한다. +- Project/Topic/Release 편집 lifecycle을 template `useAppForm`으로 통일했다. +- concrete palette는 `tech-log-theme.css` 한 곳에 두고 feature CSS는 semantic token만 사용한다. +- route/navigation/status/failure copy를 TechLog message catalog와 locale hook으로 이동했다. +- Asset UI는 `StudioAssetGateway` prop을 받지 않고 server-state hook을 통해 Provider 경계에서만 gateway를 사용한다. +- raw `
` / ``은 TechLog presentation 기준 0건이다. + +Markdown block, ordered list, asset card처럼 도메인 편집 자체를 표현하는 low-level native control은 기존 DOM/CSS 계약을 보존했다. 공통 lifecycle을 재구현하는 지점만 template capability로 이동하는 것이 적용 기준이다. + +**상태: 완료.** + +--- + +## 6. 하드코딩 검토 + +### 정리된 하드코딩 + +- Studio route path 직접 문자열 +- public 빈 검색어를 이용한 전체 catalog 조회 +- document kind를 좁히는 unsafe cast 기반 delete routing +- 화면별 수동 idempotency key 생성 +- 화면별 수동 request cancellation +- Project activity 허용값의 frontend 독립 배열 +- Release change type 허용값의 frontend 독립 배열 + +### activity/change type도 계약 source-of-truth로 이동 + +이전에는 management OpenAPI가 activityType과 changeTypes[]를 단순 string으로 노출했다. 그래서 frontend는 백엔드가 허용하는 값 집합을 별도 배열로 다시 적어야 했고, 서버 제약과 UI가 서로 어긋나도 TypeScript가 잡을 수 없었다. + +이번 작업에서 backend management OpenAPI에 실제 애플리케이션이 허용하는 값을 enum으로 명시했다. + +- Project activity: PHASE_CHANGED, QUESTION_OPENED, QUESTION_RESOLVED, DECISION_ACCEPTED, CASE_PUBLISHED, REFERENCE_PUBLISHED, MILESTONE_REACHED, PROJECT_PAUSED, PROJECT_RESUMED +- Release change: FEATURE, FIX, REFACTOR, DOCS, INFRA, BREAKING + +frontend generated contract는 이제 이 필드를 literal union으로 생성한다. presentation의 한국어 문구는 Record으로만 관리하므로 값이 추가되거나 빠지면 compile 단계에서 label map도 함께 수정해야 한다. + +즉 **값의 허용 범위는 management contract**, **표시 문구는 presentation**이 소유한다. 같은 도메인 값 집합을 component마다 다시 선언하는 구조는 제거됐다. + +--- + +## 7. 성능/조회 구조 검토 + +### 개선된 부분 + +- empty search를 전체 catalog API처럼 호출하던 경로 제거 +- query cancellation/dedup ownership을 공통 runtime으로 이동 +- 검색 입력과 제출 query 분리 유지 +- Asset pagination append 유지 +- 화면마다 중복되던 request lifecycle 제거 +- server-state query가 같은 scope/identity로 관리됨 + +### Taxonomy project-topic N+1 제거 + +기존 Taxonomy 구조 탭은 ProjectIndexItem에 topicIds가 없어 다음 요청을 만들었다. + +1. topics 목록 1회 +2. projects 목록 1회 +3. project 수만큼 getProjectForEdit 상세 조회 + +Promise.all로 병렬화해도 API 호출 수는 2 + N이었다. + +이번에는 management 목록 계약 자체를 확장했다. + +- ProjectIndexItem.topicIds: uuid[] 추가 +- 목록에서 공개 경로를 연결할 때 필요한 ProjectIndexItem.slug도 정식 계약에 추가 +- frontend Taxonomy는 topics 1회 + projects 1회만 호출 +- project-topic 연결은 ProjectIndexItem.topicIds에서 바로 구성 +- per-project getProjectForEdit 호출 제거 + +backend persistence도 단순히 N+1을 서버 내부로 옮기지 않았다. 현재 페이지의 project 목록을 읽은 뒤 project_topic을 project_id IN (:projectIds)로 한 번에 조회해 project id별로 조립한다. + +따라서 한 Taxonomy 조회에서 project 수가 증가해도 project 목록 관련 DB query count는 다음으로 고정된다. + +1. project index 1회 +2. 현재 페이지 project들의 project-topic relation bulk 조회 1회 + +frontend 회귀 테스트는 getProject를 호출하면 실패하도록 구성했고, backend PostgreSQL integration test는 index projection이 slug와 topicIds 순서를 실제로 보존하는지 검증하도록 추가했다. + +**구현 상태: 완료. 최종 테스트 결과는 아래 검증 절에 기록한다.** + +--- + +## 8. 런타임 검증에서 추가로 발견한 template 통합 결함 + +정적 검사만으로는 드러나지 않았지만 Node 24에서 실제 TechLog suite를 실행하면서 다음 통합 결함이 확인됐다. 모두 수정 후 회귀 테스트를 통과했다. + +### nullable query + +`useApplicationQuery`가 `null`을 “아직 데이터가 없음”으로 해석하고 있었다. TechLog의 `Preview 없음 = null`은 정상 성공값이므로 화면이 영구 `initial-loading`에 머물 수 있었다. + +현재는 `undefined`만 미수신 상태로 보고, `null`은 수신된 empty value로 처리한다. 공통 async-state 테스트에 `data: null -> empty` 계약을 추가했다. + +### host object mutation identity + +Asset upload payload는 `File`을 포함한다. 공통 mutation이 전송 input 전체를 canonicalize하면 plain object가 아닌 `File`에서 identity 생성이 실패한다. + +`BoundMutation`에 `identity(input)` projection을 추가해 전송 payload와 command identity를 분리했다. Asset upload는 `File` 자체를 전송하되 identity에는 `fileIdentity`, `kind`, `decorative`, `altText`만 사용한다. 공통 application-query 테스트로 이 계약을 고정했다. + +### mutation mount timing + +mutation controller가 mount된 직후 effect가 unknown-effect channel을 publish하기 전에 사용자가 submit하면 정상 command도 channel limit failure로 거절될 수 있었다. + +submit 경로에서도 현재 scope에 대해 channel을 lazy-acquire하도록 수정했다. scope 충돌이나 registry saturation은 그대로 fail-closed 한다. + +### Dashboard result budget + +Dashboard query는 결과 객체 하나를 반환하지만 내부 row 개수를 `itemCount`로 계산해 `maxResultItems=1` budget을 정상 응답이 초과할 수 있었다. + +`itemCount=1`로 수정하고 내부 row 수는 estimated bytes에만 반영했다. + +### Dialog / Pagination primitive + +공통 `Dialog`에 initial focus, focus return, Tab boundary trap, 별도 accessible title을 보강했다. Public Search, Evidence zoom, Asset Upload, Asset Picker가 동일 lifecycle을 사용한다. + +공통 `Pagination`은 기본 link semantics를 유지하면서 `pageControl="button"`과 `pageAccessibleLabel`을 지원하도록 확장했다. Studio는 기존 UX 계약대로 숫자는 짧게 보이고 접근성 이름은 `N 페이지`로 유지한다. + +### test composition + +production app은 `ServerStateGenerationProvider` 아래에서 실행되는데 일부 TechLog component test는 직접 `StudioProvider`만 렌더하고 있었다. 테스트 helper를 실제 provider stack과 동일한 QueryClient / MutationIntent / ServerStateScope / QueryInvalidation 구조로 맞췄다. + +--- + +## 9. 검증 결과 + +### frontend 정적/빌드 — PASS + +실행한 게이트: +- check:types +- lint +- check:architecture +- check:design-system +- check:tech-log-contract +- check:i18n +- build:app-only +- git diff --check + +최종 결과: + +~~~text +Static import graph: 500 modules, 1775 dependencies, all imports resolved +Architecture graph fixtures: 14 regression checks PASS +TypeScript-only source policy: PASS +Architecture fixtures: allowed PASS, 9 forbidden rejected +TechLog route source-of-truth: PASS +Design system contract: 48 tokens and vendor boundaries PASS +I18n contract: 282 keys across 4 locales PASS +production Vite build: PASS +git diff --check: PASS +~~~ + +Contract sync: + +~~~text +@tech-log/studio-contract@3.1.0 — 19 operations +@tech-log/public-contract@2.1.0 — 22 operations +@tech-log/management-contract@1.0.0 — 87 operations +contracts are in sync +~~~ + +추가 정적 검색: + +~~~text +raw in TechLog presentation: 0 +manual AbortController in TechLog presentation: 0 +searchPublicContent("") in TechLog: 0 +getProject(project.id) Taxonomy fan-out: 0 +frontend ACTIVITY_TYPES 허용값 배열: 0 +frontend CHANGE_TYPES 허용값 배열: 0 +~~~ + +### Node 24 TechLog Vitest — PASS + +시스템 Node는 변경하지 않고 one-off Node 24.11.0으로 실행했다. + +~~~text +Test Files 60 passed (60) +Tests 416 passed (416) +~~~ + +새 taxonomy-projection.test.tsx는 Taxonomy가 project index의 topicIds만으로 구조를 만들고 project detail gateway를 호출하지 않는 것을 고정한다. + +**상태: 완료.** + +### template 공통 회귀 테스트 — PASS + +~~~text +application-query.test.tsx 29 passed +async-surface.test.tsx 17 passed +design-system-platform.test.tsx 8 passed +locale-platform.test.tsx 3 passed +합계 57 passed +~~~ + +**상태: 완료.** + +### backend management projection — PASS + +Taxonomy N+1 제거를 위해 backend management 계약과 persistence projection까지 확장했다. + +- ProjectIndexItemView에 slug, topicIds 추가 +- project 목록 1회 + project_topic bulk 조회 1회로 조립 +- management OpenAPI에 ProjectIndexItem.topicIds 추가 +- project activity / release change 허용값을 OpenAPI enum으로 고정 +- generated web model과 application string 경계 mapper 연결 +- PostgreSQL integration test에 project index slug/topicIds 검증 추가 + +실제 PostgreSQL management integration: + +~~~text +:adapter:outbound:persistence-jpa:postgresqlTechLogManagementPersistenceIntegrationTest +BUILD SUCCESSFUL +~~~ + +변경 모듈의 test / checkstyle / spotless: + +~~~text +application-core +persistence-jpa +inbound-web + +BUILD SUCCESSFUL in 19s +36 actionable tasks: 6 executed, 30 up-to-date +~~~ + +**상태: 완료.** + +### backend repository 전체 check — 기존 SpotBugs classpath issue + +backend 전체 ./gradlew check는 이번 변경 파일의 컴파일/테스트 오류가 아니라 다음 기존 분석 classpath 문제에서 중단됐다. + +~~~text +:app-bootstrap:spotbugsFunctionalTest +missing analysis class: +dev.caskeleton.shared.error.ApiErrorCarrier +dev.caskeleton.shared.error.ApiErrorCode +~~~ + +변경 모듈을 별도로 검증했을 때도 application-core:spotbugsMain이 동일 계열의 shared-contract 분석 class 누락으로 실패한다. + +따라서 이번 management projection 변경은 PostgreSQL integration, module test, checkstyle, spotless로 검증 완료했으며 repository 전체 SpotBugs classpath 문제는 별도 build-qualification 이슈다. + +### browser source-parity — 실행 조건 부족 + +browser parity runner가 요구하는 기준 source app이 현재 Coka 환경에 없다. + +~~~text +source: http://127.0.0.1:4375 +target: http://127.0.0.1:4174 +source root: /home/donghyeon/workspace/techlog-studio-frontend +~~~ + +기준 source root와 두 서버가 준비되지 않은 상태에서 실행하면 ERR_CONNECTION_REFUSED가 발생한다. + +이 항목은 구현 미완료가 아니라 외부 비교 기준 부재로 증거를 새로 생성할 수 없는 상태다. + +--- + +## 10. 최종 상태 + +| 검토 항목 | 상태 | +|---|---| +| template HTTP binding 활용 | 완료 | +| template route capability 활용 | 완료 | +| Studio server-state capability 활용 | 완료 | +| mutation idempotency / host-object identity | 완료 | +| cancellation ownership | 완료 | +| shared Dialog / Pagination / Form primitive 활용 | 완료 | +| semantic design token 연결 | 완료 | +| ManagementGateway presentation 직접 호출 제거 | 완료 | +| StudioGateway presentation 직접 호출 제거 | 완료 | +| AssetGateway presentation 직접 호출 제거 | 완료 | +| public empty-search projection 우회 제거 | 완료 | +| route hardcoding guard | 완료 | +| activity/change type contract enum화 | 완료 | +| Taxonomy project-topic N+1 제거 | 완료 | +| frontend typecheck | 완료 | +| frontend lint | 완료 | +| architecture check | 완료 | +| design-system check | 완료 | +| TechLog contract sync | 완료 | +| repository i18n gate | 완료 | +| production Vite build | 완료 | +| Node 24 TechLog Vitest 416/416 | 완료 | +| template component regression 154/154 | 완료 | +| backend PostgreSQL management integration | 완료 | +| backend 변경 모듈 test/checkstyle/spotless | 완료 | +| backend repository 전체 SpotBugs | 아직 더 봐야댐 — 기존 shared-contract 분석 classpath 문제 | +| browser source-parity evidence | 아직 더 봐야댐 — baseline/source app 부재 | + +## 11. 남은 범위 + +이번 리뷰에서 확인한 TechLog frontend/template 활용, Taxonomy N+1, 관리 계약 허용값 하드코딩, i18n gate는 완료했다. + +**Frontend 코드 수정으로 남은 TechLog 리뷰 항목은 없다.** 현재 별도로 남는 것은 두 가지 외부/공통 검증 조건이다. + +1. backend build-qualification의 SpotBugs analysis classpath 누락 문제 +2. browser source-parity용 원본 source app 및 source/target 서버 준비 + +둘 다 이번 TechLog presentation/refactor 구현의 미완료 항목과는 분리된다. + +--- + +## 12. 2026-09-22 재검수 종료 + +2026-09-22 재검수에서 이전에 남아 있던 네 축을 다시 확인했다. + +- TechLogFeatureInput은 raw gateway factory 대신 createStudioApplication()을 노출한다. +- StudioContextValue는 studioApplication만 노출하며 presentation component/controller의 raw gateway 직접 호출은 0건이다. +- TechLog presentation의 raw button/input/select/textarea, form, dialog는 모두 0건이다. +- 일반 행동 문구는 message catalog를 사용한다. 최종 검색에 남은 게시/공개/검증/검색 등의 직접 문자열은 상태명, field label, heading 등 이번 리뷰의 behavioral copy 대상에서 제외한 표현이다. +- AssetLibrary, TaxonomyManager, ProjectEditor, TopicEditor, DocumentList 다섯 화면 모두 controller hook 경계를 가진다. +- DocumentList의 search params, query composition, pagination, delete orchestration, search/filter synchronization은 use-document-list-controller.ts가 소유한다. + +정적 증거: + +~~~text +raw native control = 0 +raw form = 0 +raw dialog = 0 +gateway port import = 0 +component gateway direct call = 0 +controller files = 5 +behavioral action literal = 0 +~~~ + +Node 24.11.0 최종 검증: + +~~~text +types=PASS +lint=PASS +architecture=PASS +design=PASS +contract=PASS +i18n=PASS +techlog-tests=PASS +component-tests=PASS +build=PASS +diff=PASS + +TechLog tests: 60 files / 416 tests PASS +Component tests: 27 files / 154 tests PASS +~~~ + +| 리뷰 항목 | 판정 | +|---|---| +| template HTTP binding 활용 | 완료 | +| Public/Studio route capability 및 route hardcoding 제거 | 완료 | +| Studio server-state / cancellation ownership | 완료 | +| TechLogFeatureInput / StudioContext application boundary | 완료 | +| design-system native control / Form / Dialog primitive 적용 | 완료 | +| behavioral action/error/loading/empty copy i18n | 완료 | +| 대형 Studio component controller/view-state 분리 | 완료 | +| management contract 기반 허용값 SSOT | 완료 | +| Taxonomy project-topic N+1 제거 | 완료 | +| TechLog/component/정적/빌드 회귀 검증 | 완료 | + +완료: 10 +아직 더 봐야댐: 0 + +이 판정은 TechLog frontend/template 활용 재검수 10개 축에 대한 것이다. 기존 문서에 기록된 backend 공통 SpotBugs classpath와 browser source-parity 실행 조건은 이 10개 축의 구현 미완료 항목으로 계산하지 않는다. + +--- + +## 작업트리 주의 + +이번 검토를 시작할 때 저장소에는 이미 여러 변경이 존재했다. 기존 변경을 보존한 상태에서 작업했으며 destructive git 명령, reset, checkout, commit, merge는 수행하지 않았다. + +따라서 현재 전체 `git diff`를 전부 이번 리뷰의 신규 변경이라고 간주하면 안 된다. 이 문서는 이번 세션에서 직접 확인한 구조적 문제와 현재 worktree에서 검증된 최종 상태를 기준으로 작성했다. diff --git a/docs/reviews/2026-09-22-tech-log-template-utilization-rereview.md b/docs/reviews/2026-09-22-tech-log-template-utilization-rereview.md new file mode 100644 index 0000000..2aac417 --- /dev/null +++ b/docs/reviews/2026-09-22-tech-log-template-utilization-rereview.md @@ -0,0 +1,121 @@ +# TechLog Frontend — template 활용 재검수 + +- 날짜: 2026-09-22 +- 대상: /shared/codebase/tech-log-frontend +- 기준 문서: docs/reviews/2026-09-21-tech-log-template-utilization-review.md +- 목적: 이전 재검수에서 남아 있던 4개 축을 닫고 기존 완료 항목까지 포함해 10개 축을 최종 판정한다. + +## 결론 + +| 리뷰 항목 | 판정 | +|---|---| +| template HTTP binding 활용 | 완료 | +| Public/Studio route capability 및 route hardcoding 제거 | 완료 | +| Studio server-state / cancellation ownership | 완료 | +| TechLogFeatureInput / StudioContext application boundary | 완료 | +| design-system native control / Form / Dialog primitive 적용 | 완료 | +| behavioral action/error/loading/empty copy i18n | 완료 | +| 대형 Studio component controller/view-state 분리 | 완료 | +| management contract 기반 허용값 SSOT | 완료 | +| Taxonomy project-topic N+1 제거 | 완료 | +| TechLog/component/정적/빌드 회귀 검증 | 완료 | + +완료: 10 +아직 더 봐야댐: 0 + +## 남았던 4개 축 + +### 1. TechLogFeatureInput / StudioContext raw gateway 노출 + +TechLogFeatureInput은 raw gateway factory를 노출하지 않고 createStudioApplication()으로 application facade를 만든다. StudioContextValue도 studioApplication만 노출한다. + +최종 정적 결과: + +~~~text +gateway port import = 0 +component gateway direct call = 0 +~~~ + +Studio의 studio-*-server-state.ts 내부에는 application facade가 캡슐화한 gateway 호출이 존재하지만, component/controller가 gateway를 직접 호출하는 구조는 아니다. + +판정: 완료 + +### 2. design-system primitive + +TechLog presentation에서 native control과 raw form/dialog를 다시 검색했다. + +~~~text +raw native control = 0 +raw form = 0 +raw dialog = 0 +~~~ + +기존 DOM/CSS를 보존해야 하는 화면은 template primitive의 visualPolicy=inherit 경로를 사용한다. + +판정: 완료 + +### 3. behavioral copy i18n + +일반 행동 버튼과 action prop의 저장, 추가, 검색, 취소, 다시 시도, 삭제, 더 보기, 닫기, 업로드, 게시, 공개, 검증, 적용, 삽입, 필터 초기화 등을 message catalog로 이동했다. + +최종 검색에 남는 동일 단어는 publication 상태명, field label, heading, 동적 noun 기반 버튼 등 리뷰에서 behavioral copy 대상으로 잡지 않은 표현이다. + +Unsaved navigation의 기존 접근성 이름 저장 중도 별도 catalog key로 유지해 i18n 이동 때문에 UI 계약이 바뀌지 않도록 했다. + +판정: 완료 + +### 4. 대형 Studio component controller/view-state 분리 + +다음 5개 controller가 존재한다. + +~~~text +use-asset-library-controller.ts +use-taxonomy-controller.ts +use-project-editor-controller.ts +use-topic-editor-controller.ts +use-document-list-controller.ts +~~~ + +DocumentList의 useSearchParams, query composition, pagination, pageOverride, delete orchestration, search/filter synchronization은 controller가 소유한다. component는 controller state를 렌더하고 action을 호출하는 역할로 남아 있다. + +판정: 완료 + +## 최종 검증 + +Node 24.11.0 기준: + +~~~text +types=PASS +lint=PASS +architecture=PASS +design=PASS +contract=PASS +i18n=PASS +techlog-tests=PASS +component-tests=PASS +build=PASS +diff=PASS +~~~ + +테스트: + +~~~text +TechLog: 60 files / 416 tests PASS +Component regression: 27 files / 154 tests PASS +~~~ + +정적 증거: + +~~~text +raw native control = 0 +raw form = 0 +raw dialog = 0 +gateway port import = 0 +component gateway direct call = 0 +controller files = 5 +behavioral action literal = 0 +~~~ + +## 범위 주의 + +기존 리뷰 문서에 기록된 backend 공통 SpotBugs analysis classpath 문제와 browser source-parity 실행 조건 부족은 이번 TechLog frontend/template 활용 10개 축과 별도다. 이번 재검수에서 frontend 코드 수정으로 남은 항목은 없다. diff --git a/docs/reviews/2026-09-23-tech-log-template-utilization-rereview.md b/docs/reviews/2026-09-23-tech-log-template-utilization-rereview.md new file mode 100644 index 0000000..d8dd81d --- /dev/null +++ b/docs/reviews/2026-09-23-tech-log-template-utilization-rereview.md @@ -0,0 +1,185 @@ +# TechLog Frontend — 2026-09-23 재검수 및 구현 결과 + +- 대상: `/shared/codebase/tech-log-frontend` +- 기준: 2026-09-23 재검수에서 `완료: 8`, `아직 더 봐야댐: 2`로 판정한 10개 항목 +- 수정 대상: application boundary, behavioral action/error/loading/empty copy i18n +- 검증 런타임: Node `v24.11.0` +- 기존 작업트리: 보존. reset / checkout / clean / commit 수행하지 않음 + +## 결론 + +2026-09-23 재검수 당시 남아 있던 두 항목을 구현하고 현재 worktree에서 다시 검증했다. + +| 항목 | 판정 | +|---|---| +| template HTTP binding | 완료 | +| route capability / hardcoding 제거 | 완료 | +| Studio server-state | 완료 | +| application boundary | 완료 | +| design-system primitive | 완료 | +| behavioral copy i18n | 완료 | +| controller/view-state 분리 | 완료 | +| management allowed-value SSOT | 완료 | +| Taxonomy N+1 제거 | 완료 | +| 회귀 검증 | 완료 | + +완료: 10 +아직 더 봐야댐: 0 + +## 1. Application boundary + +### 이전 상태 + +`TechLogStudioApplication`이 아래 outbound port를 그대로 노출했다. + +```text +documents: StudioGateway +assets: StudioAssetGateway +management: ManagementGateway +``` + +따라서 이름은 application facade였지만 presentation server-state가 다시 raw outbound port를 꺼낼 수 있었다. + +### 현재 상태 + +`TechLogStudioApplication`은 application-owned capability만 노출한다. + +```text +workspaceQueries +workspaceCommands +documentQueries +documentCommands +assetQueries +assetCommands +managementQueries +managementCommands +``` + +`StudioGateway`, `StudioAssetGateway`, `ManagementGateway`는 `createTechLogStudioApplication(...)`의 내부 dependency로만 사용한다. factory dependency 타입도 export하지 않는다. + +`create-tech-log-feature-input.ts`는 세 adapter를 만든 뒤 application factory에 주입한다. Studio presentation은 더 이상 `.documents`, `.assets`, `.management`를 꺼내지 않고 application capability를 사용한다. + +기존 테스트가 gateway test-double을 직접 조작해야 하는 경우는 `tests/helpers/studio-application-gateway-adapter.ts`에서만 gateway-shaped test adapter를 만든다. 이 adapter는 production presentation 경계를 우회하지 않는다. + +정적 증거: + +```text +application_public_gateway_tokens=0 +application_dependency_export=0 +presentation_gateway_port_import=0 +presentation_old_app_property=0 +component_controller_gateway_call=0 +``` + +판정: 완료 + +## 2. Behavioral copy i18n + +### 이전 상태 + +message catalog가 존재했지만 TechLog feature presentation은 `scripts/check-i18n.ts`의 hardcoded-locale 검사 범위에 포함되지 않았다. 따라서 `check:i18n=PASS`만으로는 TechLog behavioral copy 이관 완료를 증명할 수 없었다. + +실제 새 gate를 처음 적용했을 때 action/error/loading/empty/not-found/announcement 계열 위반이 다수 확인됐다. + +### 현재 상태 + +`src/features/tech-log/contracts/tech-log-message-catalog.ts`에 behavioral copy를 ko-KR/en-US 쌍으로 이동했다. 동적 성공 announcement도 `{title}`, `{name}`, `{version}` interpolation으로 이동했다. + +추가된 검사 경계: + +- `scripts/lib/tech-log-i18n-policy.ts` +- `tests/unit/tech-log-i18n-gate.test.ts` +- `scripts/check-i18n.ts`의 `src/features/tech-log/presentation` 별도 behavioral scan + +공통 presentation의 기존 blanket Korean literal 검사는 그대로 유지한다. TechLog에는 별도 targeted policy를 적용해 다음은 차단한다. + +- direct `setRequestAnnouncement`, `setNotice`, `setSuccess` literal +- 동적 template/문자열 조합 announcement +- static Button/Link action text +- `pendingLabel`, `closeLabel`, `resetLabel`, `clearLabel` 등 action prop literal +- error/failure fallback literal +- public error/empty/not-found behavioral surface literal + +반대로 heading, field label, publication/domain status 같은 editorial/domain copy는 blanket 금지하지 않는다. + +최종 증거: + +```text +behavioral_literal_violations=0 +checked_techlog_presentation_files=148 +I18n contract: 460 keys across 4 locales PASS +I18n policy tests: 1 file / 3 tests PASS +``` + +판정: 완료 + +## 3. 기존 완료 항목 회귀 + +이번 수정 후에도 기존 구조적 완료 조건을 다시 확인했다. + +```text +raw_native_control=0 +raw_form=0 +raw_dialog=0 +controllers=5 +``` + +application boundary 변경 후 component/controller에는 raw gateway 직접 호출이 없다. design-system native control/Form/Dialog 경계와 controller 분리도 유지된다. + +판정: 완료 + +## 4. 최종 회귀 검증 + +Node `v24.11.0`에서 현재 worktree를 다시 실행했다. + +```text +check:types PASS +lint PASS +check:architecture PASS +check:design-system PASS +check:tech-log-contract PASS +check:i18n PASS +i18n policy unit tests PASS +test:tech-log PASS +test:component PASS +build:app-only PASS +git diff --check PASS +``` + +테스트 수: + +```text +TechLog: 61 files / 417 tests PASS +Component: 27 files / 154 tests PASS +I18n policy: 1 file / 3 tests PASS +``` + +TechLog suite는 application boundary regression test가 추가되어 이전 60 files / 416 tests에서 61 files / 417 tests로 증가했다. + +최종 전체 로그: + +```text +/shared/.coka-logs/tech-log-frontend-final-verification-v4-20260923.log +``` + +판정: 완료 + +## 5. 작업트리 주의 + +현재 `git status --short` 기준: + +```text +status_total=177 +modified_entries=149 +untracked=27 +deleted_entries=1 +``` + +이 수치는 이번 작업 이전부터 존재하던 대규모 미커밋 변경과 이번 구현 변경을 함께 포함한다. 기존 사용자 변경을 reset, checkout, clean 하지 않았다. commit도 생성하지 않았다. + +## 최종 판정 + +2026-09-23 재검수 당시 `아직 더 봐야댐`이었던 application boundary와 behavioral copy i18n 두 항목은 현재 구현과 검증 기준에서 완료다. + +완료: 10 +아직 더 봐야댐: 0 diff --git a/docs/superpowers/plans/2026-09-23-tech-log-application-boundary-i18n.md b/docs/superpowers/plans/2026-09-23-tech-log-application-boundary-i18n.md new file mode 100644 index 0000000..fbe501b --- /dev/null +++ b/docs/superpowers/plans/2026-09-23-tech-log-application-boundary-i18n.md @@ -0,0 +1,148 @@ +# TechLog Application Boundary + Behavioral i18n Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox syntax for tracking. + +**Goal:** Close the two remaining TechLog re-review items so the application API hides outbound gateways and TechLog behavioral copy is catalog-driven and enforced by `check:i18n`. + +**Architecture:** `createTechLogStudioApplication()` owns `StudioGateway`, `StudioAssetGateway`, and `ManagementGateway` privately and exposes application-owned query/command capability objects. TechLog presentation keeps using server-state hooks, but server-state calls application capabilities rather than extracting gateway ports. Behavioral copy moves to the TechLog message catalog with interpolation, and `scripts/check-i18n.ts` gains a targeted TechLog behavioral scanner rather than a blanket Korean-literal ban. + +**Tech Stack:** TypeScript 7, React, Vitest, pnpm, custom architecture/i18n check scripts. + +**Spec:** `docs/superpowers/specs/2026-09-23-tech-log-application-boundary-i18n-design.md` + +## Global Constraints + +- Preserve all existing user changes; no reset/checkout/clean/commit/merge. +- Use Node 24.11.0 for verification without changing repository configuration. +- Do not intentionally change visible Korean copy or accessibility names. +- `TechLogStudioApplication` must not expose, alias, extend, or return `StudioGateway`, `StudioAssetGateway`, or `ManagementGateway` objects. +- Components/controllers must not gain direct gateway/application orchestration that belongs in server-state. +- TechLog i18n gate targets behavioral copy only; headings, field labels, help text, domain status labels, and dynamic noun labels remain allowed. + +## Review Focus + +- Application capability methods preserve signal/idempotency options exactly; focused delegation test covers both query and mutation paths. +- Management capability split does not drop any operation currently consumed by `studio-management-server-state.ts`; typecheck and TechLog tests pin the full surface. +- Dynamic delete announcements preserve interpolation values and Korean rendering. +- i18n gate rejects direct behavioral announcements/actions but permits headings/field labels/domain status literals. +- Existing accessible copy such as `저장 중` remains byte-for-byte unchanged. + +--- + +### Task 1: Application-owned Studio capability boundary + +**Files:** +- Modify: `src/features/tech-log/application/studio-application.ts` +- Modify: `src/features/tech-log/adapters/create-tech-log-feature-input.ts` +- Modify: `src/features/tech-log/presentation/studio/studio-workspace-server-state.ts` +- Modify: `src/features/tech-log/presentation/studio/studio-document-server-state.ts` +- Modify: `src/features/tech-log/presentation/studio/studio-asset-server-state.ts` +- Modify: `src/features/tech-log/presentation/studio/studio-management-server-state.ts` +- Test: `tests/features/tech-log/studio-application-boundary.test.ts` + +**Interfaces:** +- Produces: `createTechLogStudioApplication({ studio, assets, management }): TechLogStudioApplication` +- Produces capability properties: `workspaceQueries`, `workspaceCommands`, `documentQueries`, `documentCommands`, `assetQueries`, `assetCommands`, `managementQueries`, `managementCommands`. +- Consumes existing DTOs/return types and request/idempotency option types; outbound port types are private factory dependencies only. + +- [ ] **Step 1: Write failing boundary/delegation test** + +Create a focused test that constructs spy-like in-memory gateways, calls representative application capability methods, and asserts delegation. Add static assertions that the public application value has no `documents`, `assets`, or `management` properties. + +- [ ] **Step 2: Run the focused test and verify RED** + +Run under Node 24.11.0: +`corepack pnpm exec vitest run tests/features/tech-log/studio-application-boundary.test.ts` +Expected: FAIL because `createTechLogStudioApplication` / application-owned capability properties do not exist yet. + +- [ ] **Step 3: Implement minimal application capability API** + +Define application-owned query/command capability types with explicit method signatures copied from current port operations, then implement `createTechLogStudioApplication()` with frozen capability objects delegating to the private gateways. + +- [ ] **Step 4: Wire composition root and server-state** + +Change `create-tech-log-feature-input.ts` to call the factory. Replace all `application.documents/assets/management` extraction in Studio server-state with the corresponding query/command capability object. Do not change component/controller public APIs unless type propagation requires it. + +- [ ] **Step 5: Run focused + type/architecture checks** + +Run: +`corepack pnpm exec vitest run tests/features/tech-log/studio-application-boundary.test.ts` +`corepack pnpm check:types` +`corepack pnpm check:architecture` +Expected: PASS. + +### Task 2: TechLog behavioral copy catalog migration and i18n gate + +**Files:** +- Modify: `src/features/tech-log/contracts/tech-log-message-catalog.ts` +- Modify: affected files under `src/features/tech-log/presentation/studio/**` +- Modify: affected files under `src/features/tech-log/presentation/public/**` +- Modify: `scripts/check-i18n.ts` +- Modify/Create: `tests/unit/i18n-contract.test.ts` and/or `tests/fixtures/i18n/**` as appropriate to the existing checker test harness. + +**Interfaces:** +- Consumes: existing `useTechLogCopy()` / locale message interpolation API. +- Produces: catalog keys for behavioral notices/failures/public error states and interpolation keys for dynamic deletion announcements. +- Produces: targeted TechLog behavioral checker integrated into `check:i18n`. + +- [ ] **Step 1: Add failing i18n checker tests/fixtures** + +Add one forbidden fixture representing a direct TechLog behavioral literal such as `setNotice("삭제했습니다.")` and one allowed fixture representing a heading/field label/domain status literal. Ensure the checker distinguishes them. + +- [ ] **Step 2: Run i18n test/check and verify RED** + +Run `corepack pnpm check:i18n` and the focused i18n unit test command used by `tests/unit/i18n-contract.test.ts`. +Expected: the new behavioral negative fixture is not detected yet. + +- [ ] **Step 3: Implement targeted TechLog behavioral scanner** + +Keep the existing common-presentation blanket scan unchanged. Add TechLog presentation files as a separate source set and inspect targeted contexts: static Button action text, action-label props, `setRequestAnnouncement`, `setNotice`, `setSuccess`, failure/error/loading/empty/not-found fallback literals, and public error/retry surfaces. Catalog calls and interpolated message calls must pass. Editorial/domain literals must pass. + +- [ ] **Step 4: Migrate actual behavioral literals** + +Move the currently identified Studio/Public notices/failures/error states into `tech-log-message-catalog.ts` for `ko-KR` and `en-US`. Convert dynamic delete announcements to message interpolation. Preserve rendered Korean strings and existing accessibility names. + +- [ ] **Step 5: Run focused i18n + TechLog tests** + +Run: +`corepack pnpm check:i18n` +`corepack pnpm test:tech-log` +Expected: PASS with zero TechLog behavioral literal violations. + +### Task 3: Final regression and re-review evidence + +**Files:** +- Modify: `docs/reviews/2026-09-22-tech-log-template-utilization-rereview.md` +- Create or update: `docs/reviews/2026-09-23-tech-log-template-utilization-rereview.md` + +**Interfaces:** +- Consumes Tasks 1-2 outputs. +- Produces final 10-item re-review evidence only after fresh verification passes. + +- [ ] **Step 1: Run all required checks under Node 24.11.0** + +Run exactly: +`corepack pnpm check:types` +`corepack pnpm lint` +`corepack pnpm check:architecture` +`corepack pnpm check:design-system` +`corepack pnpm check:tech-log-contract` +`corepack pnpm check:i18n` +`corepack pnpm test:tech-log` +`corepack pnpm test:component` +`corepack pnpm build:app-only` +`git diff --check` +Expected: all PASS. + +- [ ] **Step 2: Collect static evidence** + +Record counts for application gateway type exposure, presentation gateway port imports, raw gateway extraction, component/controller gateway direct calls, TechLog behavioral literal violations, raw native controls/form/dialog, and controller files. +Expected: gateway/i18n/raw DOM violations 0; controllers 5. + +- [ ] **Step 3: Update re-review docs** + +Only after fresh verification, update the review from `완료: 8 / 아직 더 봐야댐: 2` to `완료: 10 / 아직 더 봐야댐: 0`, with actual current test counts and commands. + +- [ ] **Step 4: No commit** + +Do not commit. Preserve the user's existing dirty worktree and report only changed files and fresh verification evidence. diff --git a/docs/superpowers/specs/2026-09-23-tech-log-application-boundary-i18n-design.md b/docs/superpowers/specs/2026-09-23-tech-log-application-boundary-i18n-design.md new file mode 100644 index 0000000..c0f1608 --- /dev/null +++ b/docs/superpowers/specs/2026-09-23-tech-log-application-boundary-i18n-design.md @@ -0,0 +1,398 @@ +# TechLog Application Boundary and Behavioral i18n Design + +## Context + +The 2026-09-23 TechLog frontend re-review re-opened two items that had previously been marked complete: + +1. `TechLogFeatureInput / StudioContext application boundary` +2. `behavioral action/error/loading/empty copy i18n` + +The current implementation is otherwise considered complete for the remaining eight review axes. This design intentionally limits scope to these two open items and the regression evidence required to close them. + +The existing worktree contains substantial unrelated user changes. Those changes must be preserved. No reset, checkout, clean, commit, merge, or other destructive Git operation is part of this work. + +## Goals + +### Goal A — Hide outbound gateway ports behind an application-owned API + +`TechLogStudioApplication` must stop exposing `StudioGateway`, `StudioAssetGateway`, and `ManagementGateway` as public properties. + +Presentation server-state code must consume application-owned query/command capabilities instead of extracting raw outbound ports from the application facade. + +### Goal B — Make TechLog behavioral copy verifiably catalog-driven + +Behavioral action, success, error, loading, empty-state, not-found, and validation-facing copy in TechLog presentation must use the TechLog message catalog, including dynamic announcements through interpolation. + +`check:i18n` must include a TechLog-specific behavioral-copy gate so a passing i18n check is actual evidence that these literals are not reintroduced. + +## Non-goals + +This work does not migrate every Korean literal in TechLog presentation into the catalog. + +The following remain intentionally allowed when they are domain/editorial copy rather than behavioral UI copy: + +- headings +- long-form explanatory text +- help text +- field labels +- publication/domain status labels +- document titles and other content values +- dynamic noun-based labels where the noun itself is domain content + +This work does not redesign HTTP, route, design-system, server-state runtime, Taxonomy projection, controller boundaries, or management allowed-value SSOT beyond changes strictly required by the two open review items. + +## Current problem 1 — Application facade leaks outbound ports + +The current public type is effectively: + +```ts +export type TechLogStudioApplication = Readonly<{ + documents: StudioGateway; + assets: StudioAssetGateway; + management: ManagementGateway; +}>; +``` + +Although `TechLogFeatureInput` and `StudioContextValue` no longer expose three gateway factories directly, server-state code still performs operations such as: + +```ts +const { documents: gateway } = useStudioApplication(); +const gateway = application.assets; +``` + +This means presentation still receives outbound port objects. The boundary has been renamed but not raised to an application use-case API. + +## Application boundary design + +### Public application shape + +`TechLogStudioApplication` will expose application-owned query and command capabilities, grouped by responsibility rather than by outbound adapter. + +The target shape is: + +```ts +export type TechLogStudioApplication = Readonly<{ + workspaceQueries: StudioWorkspaceQueries; + workspaceCommands: StudioWorkspaceCommands; + documentQueries: StudioDocumentQueries; + documentCommands: StudioDocumentCommands; + assetQueries: StudioAssetQueries; + assetCommands: StudioAssetCommands; + managementQueries: StudioManagementQueries; + managementCommands: StudioManagementCommands; +}>; +``` + +The exact grouping follows current server-state responsibilities. The grouping is an application API; none of these exported capability types may alias, extend, or expose `StudioGateway`, `StudioAssetGateway`, or `ManagementGateway`. + +### Capability ownership + +#### `StudioWorkspaceQueries` + +Owns read operations used by dashboard/list/publication/catalog workflows, including the current equivalents of: + +- get dashboard +- list documents +- list publications +- get publication snapshot +- get catalog + +#### `StudioWorkspaceCommands` + +Owns workspace-level mutations currently used outside the document editor lifecycle, including the current equivalents of: + +- create document +- unpublish publication + +#### `StudioDocumentQueries` + +Owns document-editor reads: + +- get document +- get current preview + +#### `StudioDocumentCommands` + +Owns document-editor mutations: + +- save document +- validate document +- create preview +- publish document + +#### `StudioAssetQueries` + +Owns asset reads: + +- list assets +- get asset + +#### `StudioAssetCommands` + +Owns asset mutations: + +- upload asset +- update asset metadata +- delete asset + +#### `StudioManagementQueries` and `StudioManagementCommands` + +Expose the management read/write operations currently consumed by `studio-management-server-state.ts`, grouped by query versus mutation ownership. + +The public application contract can preserve current command/query DTOs and return values where they already represent application-level concepts. The requirement is specifically that the outbound gateway interfaces themselves are hidden. + +### Factory + +A dedicated application factory will own outbound ports as private dependencies: + +```ts +export function createTechLogStudioApplication(dependencies: Readonly<{ + studio: StudioGateway; + assets: StudioAssetGateway; + management: ManagementGateway; +}>): TechLogStudioApplication +``` + +The implementation will build frozen capability objects whose methods delegate to the private dependencies. + +`create-tech-log-feature-input.ts` will construct the three adapters as it does today and pass them into `createTechLogStudioApplication(...)`. It will no longer construct an object literal that exposes the gateways. + +### Presentation integration + +`StudioContextValue` continues to expose one `studioApplication` value. + +Server-state modules will switch from raw port extraction: + +```ts +application.documents +application.assets +application.management +``` + +to application capabilities: + +```ts +application.workspaceQueries +application.workspaceCommands +application.documentQueries +application.documentCommands +application.assetQueries +application.assetCommands +application.managementQueries +application.managementCommands +``` + +Components and controllers continue to consume server-state hooks and must not gain direct application capability orchestration that belongs in server-state. + +### Boundary invariants + +The final implementation must satisfy all of these: + +```text +TechLogStudioApplication references to *Gateway public property types = 0 +presentation imports from application/ports/*gateway* = 0 +presentation raw .documents/.assets/.management application extraction = 0 +component gateway direct calls = 0 +controller gateway direct calls = 0 +``` + +Outbound gateway types may remain in adapter/application implementation files where dependency inversion requires them. + +## Current problem 2 — Behavioral i18n has feature-level blind spots + +The TechLog catalog already contains many action/state/failure keys, but direct behavioral literals remain in presentation. + +Observed examples include: + +```text +저장하지 못했습니다. 다시 시도해 주세요. +검증하지 못했습니다. 다시 시도해 주세요. +Public Preview를 만들지 못했습니다. 다시 시도해 주세요. +게시하지 못했습니다. 다시 시도해 주세요. +게시했습니다. +홈에 표시할 항목을 저장했습니다. +보관했습니다. +삭제했습니다. +대체 텍스트를 저장했습니다. +페이지를 찾을 수 없습니다. +최근 기록을 불러오지 못했습니다. +페이지를 불러오지 못했습니다. +``` + +Dynamic announcements also remain, for example deletion messages containing release, variant, document, topic, or project names. + +The current `scripts/check-i18n.ts` hardcoded-locale scan checks shared `src/presentation/*` directories but not `src/features/tech-log/presentation`, so `check:i18n=PASS` does not prove TechLog behavioral-copy completeness. + +## Behavioral i18n design + +### Catalog migration + +Behavioral literals will move into `tech-log-message-catalog.ts` for both `ko-KR` and `en-US`. + +Static messages use ordinary keys, for example: + +```text +techLog.notice.published +techLog.notice.homeFocusSaved +techLog.notice.assetArchived +techLog.notice.assetDeleted +techLog.notice.assetAltTextSaved +techLog.failure.saveRetry +techLog.failure.validationRetry +techLog.failure.previewRetry +techLog.failure.publishRetry +techLog.public.notFound +techLog.public.latestLoadFailed +techLog.public.pageLoadFailed +``` + +Existing semantically equivalent keys must be reused instead of duplicated. + +### Interpolated announcements + +Dynamic success/announcement copy must use interpolation parameters rather than template literals in presentation. + +Representative target pattern: + +```ts +copy("techLog.notice.documentDeleted", { + title: item.title || copy("techLog.state.untitled"), +}); +``` + +with matching locale entries such as: + +```text +ko-KR: 작업본 {title} 을(를) 삭제했습니다. +en-US: Deleted working copy {title}. +``` + +The exact key naming may follow the existing catalog organization, but interpolation parameter names must match across locales and continue to pass the existing catalog interpolation contract check. + +### TechLog-specific i18n gate + +`check-i18n.ts` will keep the existing blanket common-presentation scan unchanged for shared UI. + +TechLog presentation will be added through a separate behavioral rule set, not through the blanket Korean-literal regex. This avoids falsely rejecting allowed domain/editorial Korean copy. + +The TechLog behavioral gate must detect direct user-facing behavioral literals in at least these contexts: + +- static `Button` action text +- action-like props such as `pendingLabel`, `closeLabel`, `resetLabel`, and similar control labels +- `setRequestAnnouncement("...")` +- `setNotice("...")` +- `setSuccess("...")` +- direct fallback strings used for error/failure/loading/empty/not-found behavior +- direct behavioral literals in public error/empty/retry surfaces + +The rule must permit catalog calls and interpolated message calls. + +The gate should be implemented as a targeted source checker rather than a blanket ban on Korean literals under the whole feature directory. + +### Gate testability + +The checker must have negative fixtures or equivalent explicit test inputs demonstrating that it fails for representative TechLog behavioral literals and does not fail for allowed domain/editorial copy. + +At minimum, fixture coverage must pin these two distinctions: + +1. a direct behavioral announcement/action literal fails; +2. a heading/field-label/domain-status literal is allowed. + +## Compatibility requirements + +The refactor must not intentionally change visible Korean copy or accessibility names unless an existing copy contract is already inconsistent. + +If moving a string to the catalog would change punctuation, ellipsis, spacing, or an accessible button name, preserve the existing rendered value with a dedicated key rather than changing tests to accept the new copy. + +The existing `저장 중` versus `저장 중…` regression is the precedent: preserve the concrete UI contract and represent distinct copy as distinct keys when necessary. + +## Test strategy + +### Application boundary tests + +Add or update focused tests that prove the application factory delegates through application-owned capabilities without exposing outbound ports. + +Static architecture checks must prove: + +```text +TechLogStudioApplication public gateway type exposure = 0 +presentation raw gateway extraction = 0 +presentation gateway port imports = 0 +``` + +Existing server-state behavior tests should continue to pass unchanged where observable behavior has not changed. + +### i18n tests + +Add or update checker fixtures/tests so `check:i18n` fails when TechLog behavioral literals are introduced into guarded contexts. + +Catalog interpolation parity across locales must remain enforced. + +### Full regression + +Use Node 24.11.0 without changing repository configuration and run: + +```text +corepack pnpm check:types +corepack pnpm lint +corepack pnpm check:architecture +corepack pnpm check:design-system +corepack pnpm check:tech-log-contract +corepack pnpm check:i18n +corepack pnpm test:tech-log +corepack pnpm test:component +corepack pnpm build:app-only +git diff --check +``` + +Expected baseline: + +```text +TechLog: 60 files / 416 tests PASS +Component: 27 files / 154 tests PASS +``` + +If test counts change because new focused tests are added, the new larger counts become the final evidence. + +## Final static evidence + +The re-review is complete only when all final evidence is collected from the current worktree: + +```text +application gateway type exposure = 0 +presentation gateway port import = 0 +presentation raw gateway extraction = 0 +component/controller gateway direct call = 0 +behavioral literal violations = 0 +raw native control = 0 +raw form = 0 +raw dialog = 0 +controller files = 5 +``` + +## Completion criteria + +The two re-opened review axes can be marked complete only when: + +1. `TechLogStudioApplication` exposes application-owned query/command capabilities and no raw outbound gateway object; +2. Studio/Public behavioral literals are catalog-driven, including dynamic announcements; +3. `check:i18n` actively checks TechLog feature presentation behavioral copy; +4. targeted i18n gate tests/fixtures demonstrate the rule catches regressions without blanket-rejecting domain/editorial copy; +5. Node 24 full regression passes; +6. final static evidence reports zero violations for the application-boundary and behavioral-i18n criteria. + +At that point the 2026-09-23 re-review may move from: + +```text +완료: 8 +아직 더 봐야댐: 2 +``` + +to: + +```text +완료: 10 +아직 더 봐야댐: 0 +``` + +No completion claim is allowed before those checks pass. diff --git a/package.json b/package.json index b9ef85c..e7cb634 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "preview": "node dist/server.mjs", "verify:tech-log-source-parity": "node tests/support/browser/verify-tech-log-source-parity.ts", "lint": "eslint src scripts tests recipes .storybook vite.config.ts vitest.config.ts playwright*.config.ts --max-warnings=0", - "check:architecture": "node scripts/check-architecture.ts", + "check:architecture": "node scripts/check-architecture.ts && node scripts/check-tech-log-route-literals.ts", "check:design-system": "node scripts/check-design-system.ts", "check:design-system:fixture": "node scripts/check-design-system.ts --fixture", "check:i18n": "node scripts/check-i18n.ts", diff --git a/public/release-manifest.json b/public/release-manifest.json index 3fedbd2..ce7fc79 100644 --- a/public/release-manifest.json +++ b/public/release-manifest.json @@ -38,12 +38,12 @@ }, "contractSet": { "setAlgorithm": "CA_CONTRACT_SET_V1", - "setDigest": "sha256:bc0766de75feb10ebc689402840def8689d4653f10d3c42cfbe5f553c7844890", + "setDigest": "sha256:814aa5919d81b699adc0727ebb2d39ab422df5ac9388be3284243fff7cb92f0c", "packages": [ { "packageId": "@tech-log/management-contract", "version": "1.0.0", - "digest": "sha256:0c226600c45b06433480a8a2ef3d812480dce3850c333bfcab5f626143ce77ea", + "digest": "sha256:6036a41879ccf161ba3b7db184be3897684c19e8890f3446460293f1f1f7ab3d", "runtimeProtocolVersion": 1, "sourceRevision": "a0dac96" }, diff --git a/scripts/check-design-system.ts b/scripts/check-design-system.ts index 718203e..e766a57 100644 --- a/scripts/check-design-system.ts +++ b/scripts/check-design-system.ts @@ -82,11 +82,16 @@ async function listSourceFiles(directory: string): Promise { 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 (/\.(?:ts|tsx|mts|cts)$/.test(entry.name)) result.push(target); + else if (/\.(?:ts|tsx|mts|cts|css)$/.test(entry.name)) result.push(target); } return result; } +const rawPaletteSourceFiles = new Set([ + ...Object.values(tokenFiles), + "src/features/tech-log/presentation/styles/tech-log-theme.css", +]); + const sources = fixtureMode ? await listSourceFiles("tests/fixtures/design-system/forbidden") : await listSourceFiles("src"); @@ -109,7 +114,7 @@ for (const file of sources) { failures.push(`design-system deep import in ${file}`); } if ( - !file.includes("src/presentation/design-system/tokens/") && + !rawPaletteSourceFiles.has(file) && containsRawPaletteValue(source) ) { failures.push(`raw palette value in ${file}`); diff --git a/scripts/check-i18n.ts b/scripts/check-i18n.ts index ae62611..61434c8 100644 --- a/scripts/check-i18n.ts +++ b/scripts/check-i18n.ts @@ -2,6 +2,7 @@ import { mkdir, readFile, readdir } from "node:fs/promises"; import { i18nReportArtifactSchema } from "./contracts/release-artifacts.ts"; import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts"; +import { findTechLogBehavioralLiteralViolations } from "./lib/tech-log-i18n-policy.ts"; import path from "node:path"; import { EN_MESSAGES, KO_MESSAGES, MESSAGE_CATALOGS } from "../src/presentation/i18n/catalog.ts"; @@ -61,13 +62,17 @@ const commonDirectories = [ "src/presentation/routes", "src/presentation/templates", ]; -const sources = fixtureMode +const commonSources = fixtureMode ? await listSourceFiles("tests/fixtures/i18n/forbidden") : ( await Promise.all(commonDirectories.map((directory) => listSourceFiles(directory))) ).flat(); +const techLogSources = fixtureMode + ? [] + : await listSourceFiles("src/features/tech-log/presentation"); +const sources = [...commonSources, ...techLogSources]; -for (const file of sources) { +for (const file of commonSources) { const source = await readFile(file, "utf8"); if (koreanLiteral.test(source)) { failures.push(`hardcoded common user-facing locale literal in ${file}`); @@ -80,6 +85,22 @@ for (const file of sources) { } } + +for (const file of techLogSources) { + const source = await readFile(file, "utf8"); + for (const violation of findTechLogBehavioralLiteralViolations(source)) { + failures.push( + `hardcoded TechLog behavioral locale literal in ${file}:${violation.kind}:${violation.text}`, + ); + } + 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 = i18nReportArtifactSchema.parse({ schemaVersion: 1, mode: fixtureMode ? "negative-fixture" : "source", diff --git a/scripts/check-tech-log-route-literals.ts b/scripts/check-tech-log-route-literals.ts new file mode 100644 index 0000000..89423cb --- /dev/null +++ b/scripts/check-tech-log-route-literals.ts @@ -0,0 +1,65 @@ +import fs from "node:fs"; +import path from "node:path"; + +import { TECH_LOG_ROUTE_REGISTRY } from "../src/features/tech-log/contracts/tech-log-route-contract.ts"; + +const ROOT = path.resolve("src/features/tech-log/presentation"); +const EXTENSIONS = new Set([".ts", ".tsx"]); +const TECH_LOG_ROUTE_ROOTS = new Set( + Object.values(TECH_LOG_ROUTE_REGISTRY) + .map(({ path: routePath }) => /^\/([^/:*]+)/.exec(routePath)?.[1]) + .filter((segment): segment is string => Boolean(segment)), +); + +type RouteLiteralViolation = Readonly<{ + file: string; + line: number; + value: string; +}>; + +const violations: RouteLiteralViolation[] = []; + +function visitFile(filePath: string): void { + const source = fs.readFileSync(filePath, "utf8"); + const withoutComments = source + .replace(/\/\*[\s\S]*?\*\//g, "") + .replace(/\/\/.*$/gm, ""); + // Only strings beginning with a real TechLog route family are forbidden. + // Media paths (/media/...), Markdown command examples (/problem, /context), + // generated metadata paths, etc. are slash-prefixed strings too, but they + // are not navigation URLs and must not be classified as route duplication. + const pattern = /(["'`])(\/([A-Za-z0-9-]+))(?=[/?#"'`])/g; + for (const match of withoutComments.matchAll(pattern)) { + const routeRoot = match[3]; + if (!routeRoot || !TECH_LOG_ROUTE_ROOTS.has(routeRoot)) continue; + + const before = withoutComments.slice(0, match.index ?? 0); + const line = before.split("\n").length; + violations.push({ + file: path.relative(process.cwd(), filePath), + line, + value: match[2] ?? match[0], + }); + } +} + +function walk(directory: string): void { + for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { + const filePath = path.join(directory, entry.name); + if (entry.isDirectory()) walk(filePath); + else if (EXTENSIONS.has(path.extname(entry.name))) visitFile(filePath); + } +} + +walk(ROOT); + +if (violations.length > 0) { + console.error("TechLog route source-of-truth check failed."); + console.error("Build internal TechLog URLs through publicRoutes/studioRoutes instead of presentation literals."); + for (const violation of violations) { + console.error(`- ${violation.file}:${violation.line} ${JSON.stringify(violation.value)}`); + } + process.exit(1); +} + +console.log("TechLog route source-of-truth: PASS"); diff --git a/scripts/lib/tech-log-i18n-policy.ts b/scripts/lib/tech-log-i18n-policy.ts new file mode 100644 index 0000000..7d17755 --- /dev/null +++ b/scripts/lib/tech-log-i18n-policy.ts @@ -0,0 +1,75 @@ +export type TechLogBehavioralLiteralViolation = Readonly<{ + kind: string; + index: number; + text: string; +}>; + +const korean = /[가-힣]/; +const behavioralState = + /(다시 시도|찾을 수 없|불러오지 못|못했습니다|만들지 못|없습니다|저장했습니다|삭제했습니다|게시했습니다|보관했습니다|저장 중|처리 중|불러오는 중|검증 중|생성 중|업로드 중|준비하고 있습니다)/; + +function add( + violations: TechLogBehavioralLiteralViolation[], + kind: string, + index: number, + text: string, +): void { + const normalized = text.trim(); + if (!korean.test(normalized)) return; + violations.push(Object.freeze({ kind, index, text: normalized })); +} + +function literalBody(match: RegExpMatchArray, bodyIndex: number): string { + return match[bodyIndex] ?? ""; +} + +export function findTechLogBehavioralLiteralViolations( + source: string, +): readonly TechLogBehavioralLiteralViolation[] { + const violations: TechLogBehavioralLiteralViolation[] = []; + + for (const match of source.matchAll( + /(?:\b[A-Za-z_$][\w$]*\.)?(?:setRequestAnnouncement|setNotice|setSuccess)\(\s*(["'`])([\s\S]*?)\1\s*\)/g, + )) { + const body = literalBody(match, 2); + add(violations, "announcement", match.index ?? 0, body); + } + + for (const match of source.matchAll( + /\b(?:pendingLabel|closeLabel|resetLabel|clearLabel|actionLabel|confirmLabel)\s*=\s*(["'`])([\s\S]*?)\1/g, + )) { + const body = literalBody(match, 2); + add(violations, "action-prop", match.index ?? 0, body); + } + + for (const match of source.matchAll(/<(Button|Link)\b[^>]*>\s*([^<{][^<{}]*?)\s*<\/\1>/g)) { + add(violations, "action-text", match.index ?? 0, match[2] ?? ""); + } + + for (const match of source.matchAll( + /(?:studioFailureMessage|managementFailureMessage)\([\s\S]{0,600}?,\s*(["'`])([\s\S]*?)\1\s*\)/g, + )) { + const body = literalBody(match, 2); + add(violations, "failure-fallback", match.index ?? 0, body); + } + + for (const match of source.matchAll( + /<(h1|h2|h3|p|span)\b[^>]*>\s*([^<{][^<{}]*[가-힣][^<{}]*)\s*<\/\1>/g, + )) { + const body = (match[2] ?? "").trim(); + if (behavioralState.test(body)) { + add(violations, "behavioral-surface", match.index ?? 0, body); + } + } + + for (const match of source.matchAll( + /\b(?:title|description|message|empty|emptyLabel|error|errorLabel|loading|loadingLabel)\s*=\s*(["'`])([^"'`\n]*[가-힣][^"'`\n]*)\1/g, + )) { + const body = match[2] ?? ""; + if (behavioralState.test(body)) { + add(violations, "behavioral-prop", match.index ?? 0, body); + } + } + + return Object.freeze(violations); +} diff --git a/src/adapters/http/feature-http-binding.ts b/src/adapters/http/feature-http-binding.ts index 838a461..5766727 100644 --- a/src/adapters/http/feature-http-binding.ts +++ b/src/adapters/http/feature-http-binding.ts @@ -71,6 +71,7 @@ export type InstalledHttpOperationExecutor = Readonly<{ export type FeatureHttpProblemMapping = Readonly<{ kind: FailureKind; code: string; + detail?: string; }>; type FeatureHttpOperationSpec< @@ -306,7 +307,11 @@ function projectExecutionOutcome( mapped?.kind ?? kindForStatus(outcome.metadata.status), operationId, mapped?.code ?? "CONTRACT_PROBLEM", - { httpStatus: outcome.metadata.status, effect: outcome.effect }, + { + ...(mapped?.detail === undefined ? {} : { detail: mapped.detail }), + httpStatus: outcome.metadata.status, + effect: outcome.effect, + }, ); } case "UNAUTHENTICATED": @@ -388,6 +393,7 @@ function failure( operationId: string, code: string, details: Readonly<{ + detail?: string; httpStatus?: number; retryAfterMs?: number; effect?: FailureEffectCertainty; diff --git a/src/application/view-models/async-state.ts b/src/application/view-models/async-state.ts index 3a30cde..2b04f4d 100644 --- a/src/application/view-models/async-state.ts +++ b/src/application/view-models/async-state.ts @@ -80,10 +80,11 @@ export type AsyncState = Readonly<{ }>; export function deriveAsyncState(signals: AsyncSignals): AsyncState { - const hasData = signals.data !== undefined && signals.data !== null; + const hasData = signals.data !== undefined; const empty = hasData && - ((Array.isArray(signals.data) && signals.data.length === 0) || + (signals.data === null || + (Array.isArray(signals.data) && signals.data.length === 0) || signals.data === ""); const base = diff --git a/src/bootstrap/main.tsx b/src/bootstrap/main.tsx index 8157f1b..06b216f 100644 --- a/src/bootstrap/main.tsx +++ b/src/bootstrap/main.tsx @@ -5,6 +5,8 @@ import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.tsx" import "pretendard/dist/web/variable/pretendardvariable.css"; import "@fontsource/ibm-plex-mono/400.css"; import "@fontsource/ibm-plex-mono/500.css"; +import "../presentation/styles/theme.css"; +import "../features/tech-log/presentation/styles/tech-log-theme.css"; import "../features/tech-log/presentation/styles/globals.css"; import "../features/tech-log/presentation/styles/studio.css"; import "../features/tech-log/presentation/styles/studio-editor.css"; diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 2eb6377..452bc67 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -33,7 +33,6 @@ import { attachStudioSessionCredentials, invalidateTechLogCsrfOnOutcome, } from "../features/tech-log/adapters/http/studio-session-credentials.ts"; -import type { StudioOperationExecutor as TechLogStudioOperationExecutor } from "../features/tech-log/adapters/http/http-studio-gateway.ts"; import type { AuthSessionPort } from "../application/ports/auth-session-port.ts"; import type { ReleaseInfo } from "../application/ports/release-info-port.ts"; import { @@ -41,7 +40,6 @@ import { INSTALLED_REST_AUTH_PROFILES, } from "../contracts/rest-profiles.ts"; import type { ClockPort } from "../application/ports/clock-port.ts"; -import type { MutationIntent } from "../contracts/mutation-intent.ts"; import { createInstalledFeatureInputs } from "../features/installed-feature-adapters.ts"; import { INVALIDATION_REGISTRY, @@ -64,6 +62,7 @@ import { import type { RuntimeConfigLoadResult } from "./load-runtime-config.ts"; import { createServerStateGenerationStore } from "./server-state-generation-store.ts"; import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../features/installed-contract-contributions.ts"; +import { TECH_LOG_STUDIO_SESSION_CONTRACT } from "../features/tech-log/contracts/tech-log-studio-contract-contribution.ts"; import { indexInvalidationRegistry, indexInvalidationTopicVersions, @@ -452,10 +451,10 @@ export async function createRuntimeAdapters( * entirely and must set the header itself. If each built its own provider, * one Studio session would hold two different tokens. * - * `execute` calls `getStudioSession` through `techLogOperations`, which is + * `execute` calls `getStudioSession` through `contractOperations`, which is * assigned further below — a real ordering hazard, since `attachCredentials` * (needed to build `contractHttp`, needed to build `contractOperations`, - * needed to build `techLogOperations`) needs this provider first. + * needed to build `contractOperations`) needs this provider first. * * Fix round 1 (C1). The original comment here claimed "`getStudioSession` * is a SAFE operation and needs no CSRF, so there is no true cycle" — that @@ -478,18 +477,18 @@ export async function createRuntimeAdapters( * `await` between this declaration and the real assignment, where a stub * fails loudly instead. */ - let techLogOperations: TechLogStudioOperationExecutor = Object.freeze({ + let contractOperations: InstalledHttpOperationExecutor = Object.freeze({ async execute() { throw new Error( - "techLogOperations used before assignment in createRuntimeAdapters — " + + "contractOperations used before assignment in createRuntimeAdapters — " + "construction order regressed.", ); }, }); const techLogCsrf = createCsrfTokenProvider({ async execute(options) { - const outcome = await techLogOperations.execute( - "getStudioSession", + const outcome = await contractOperations.execute( + TECH_LOG_STUDIO_SESSION_CONTRACT, {}, { routeId: "TECH_LOG_STUDIO", @@ -499,8 +498,14 @@ export async function createRuntimeAdapters( if (outcome.kind !== "SUCCESS") { throw new Error("studio session is unavailable"); } - const value = outcome.value as { csrfToken: string; csrfHeaderName: string }; - return { csrfToken: value.csrfToken, csrfHeaderName: value.csrfHeaderName }; + const value = outcome.value as { + csrfToken: string; + csrfHeaderName: string; + }; + return { + csrfToken: value.csrfToken, + csrfHeaderName: value.csrfHeaderName, + }; }, }); const contractHttp = createContractHttpExecutor({ @@ -570,7 +575,7 @@ export async function createRuntimeAdapters( }, observe: createHttpObservationProjector({ diagnostics, telemetry }), }); - const contractOperations: InstalledHttpOperationExecutor = Object.freeze({ + contractOperations = Object.freeze({ async execute(operation, input, executionContext) { const installed = COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.get( @@ -622,52 +627,8 @@ export async function createRuntimeAdapters( return outcome; }, }); - /** - * Template sync (ebea300). The platform executor above now takes the - * installed contract itself, so a feature's Input/WireOutput/Problem types - * flow through `createFeatureHttpBinding`. TechLog's four HTTP gateways - * still address operations by id through its own `StudioOperationExecutor`, - * so the id is resolved to the installed contract here — at the one place - * that already owns the registry — instead of being resolved inside the - * platform executor for every caller. Porting those gateways onto the typed - * binding is its own change; nothing about it is decided here. - * - * `!installed` returns the same `FINAL_REQUEST_INVARIANT_FAILED` violation - * the platform executor returns for an operation that is not installed, so - * an unregistered id fails identically on both paths. - */ - techLogOperations = Object.freeze({ - async execute( - operationId: string, - input: unknown, - executionContext: Readonly<{ - routeId: string; - signal?: AbortSignal; - intent?: MutationIntent; - }>, - ) { - const installed = - COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.get(operationId); - if (!installed) { - return Object.freeze({ - kind: "CONTRACT_VIOLATION" as const, - effect: "NOT_STARTED" as const, - violation: Object.freeze({ - kind: "FINAL_REQUEST_INVARIANT_FAILED" as const, - operation: "REQUEST" as const, - }), - }); - } - return contractOperations.execute( - installed as Parameters[0], - input, - executionContext, - ); - }, - }); const featureInputs = createInstalledFeatureInputs({ http: contractOperations, - contractOperations: techLogOperations, studioSource: config.TECH_LOG_STUDIO_SOURCE, publicSource: config.TECH_LOG_PUBLIC_SOURCE, apiBaseUrl: config.API_BASE_URL, diff --git a/src/contracts/errors.ts b/src/contracts/errors.ts index 6ef354a..dbfce82 100644 --- a/src/contracts/errors.ts +++ b/src/contracts/errors.ts @@ -238,6 +238,7 @@ export type FailureEffectCertainty = export type AppFailure = Readonly<{ kind: FailureKind; code: string; + detail?: string; httpStatus?: number; retryable: boolean; operationId: string; @@ -261,6 +262,7 @@ export type ApiFailure = AppFailure; export type FailureDetails = Readonly<{ code?: string; + detail?: string; httpStatus?: number; requestId?: string; traceId?: string; @@ -280,6 +282,9 @@ export function createFailure( return Object.freeze({ kind: definition.kind, code: typeof details.code === "string" ? details.code : definition.kind, + ...(typeof details.detail === "string" && details.detail.length > 0 + ? { detail: details.detail.slice(0, 5_000) } + : {}), retryable: details.effect === "MAYBE_APPLIED" || details.effect === "APPLIED_CONFIRMED" diff --git a/src/contracts/server-state.ts b/src/contracts/server-state.ts index f7476c6..361a9de 100644 --- a/src/contracts/server-state.ts +++ b/src/contracts/server-state.ts @@ -239,6 +239,11 @@ export type BoundMutation = Readonly<{ owner: string; duplicatePolicy: MutationDuplicatePolicy; scope: CacheScopeSnapshot; + /** + * Projects a transport input to a canonical, serializable command identity. + * Use this when the transport payload contains host objects such as File. + */ + identity?: (input: Input) => unknown; execute( input: Input, context: Readonly<{ signal: AbortSignal; intent: MutationIntent }>, diff --git a/src/features/tech-log/adapters/create-tech-log-feature-input.ts b/src/features/tech-log/adapters/create-tech-log-feature-input.ts index 194670e..f98ba9d 100644 --- a/src/features/tech-log/adapters/create-tech-log-feature-input.ts +++ b/src/features/tech-log/adapters/create-tech-log-feature-input.ts @@ -3,12 +3,12 @@ import { type TechLogFeatureInput, } from "../application/tech-log-feature-input.ts"; import type { Asset } from "../contracts/studio/contract.ts"; +import { createTechLogStudioApplication } from "../application/studio-application.ts"; +import type { InstalledHttpOperationExecutor } from "../../../adapters/http/index.ts"; +import { createTechLogHttpBinding } from "./http/tech-log-http-binding.ts"; import { createAssetUploadTransport } from "./http/asset-upload-transport.ts"; import { createHttpStudioAssetGateway } from "./http/http-studio-asset-gateway.ts"; -import { - createHttpStudioGateway, - type StudioOperationExecutor, -} from "./http/http-studio-gateway.ts"; +import { createHttpStudioGateway } from "./http/http-studio-gateway.ts"; import type { CsrfTokenProvider } from "./http/studio-session-csrf.ts"; import { createMockStudioAssetGateway } from "./mock/mock-studio-asset-gateway.ts"; import { createMockStudioGateway } from "./mock/mock-studio-gateway.ts"; @@ -30,7 +30,7 @@ import { publicContentQueries } from "./static/public-query.ts"; export type TechLogInstallContext = Readonly<{ studioSource: "MOCK" | "HTTP"; publicSource: "MOCK" | "HTTP"; - contractOperations: StudioOperationExecutor; + http: InstalledHttpOperationExecutor; apiBaseUrl: string; requestTimeoutMs: number; csrf: CsrfTokenProvider; @@ -51,12 +51,14 @@ export function createTechLogFeatureInstalledInput( // lifetime — shares it, the same way a real backend's asset store outlives // any one editing session. It is never read on the HTTP branch. const mockAssets = new Map(); + const http = createTechLogHttpBinding(context.http); + const createStudioAssetGateway = () => context.studioSource === "MOCK" ? createMockStudioAssetGateway(mockAssets) : createHttpStudioAssetGateway({ - operations: context.contractOperations, + http, csrf: context.csrf, upload: createAssetUploadTransport({ baseUrl: context.apiBaseUrl, @@ -67,7 +69,7 @@ export function createTechLogFeatureInstalledInput( const createStudioGateway = () => context.studioSource === "MOCK" ? createMockStudioGateway({ assets: mockAssets }) - : createHttpStudioGateway({ operations: context.contractOperations }); + : createHttpStudioGateway({ http }); // The public read source switches independently of Studio: the two are // different services, and the combination that matters today is an authoring @@ -75,16 +77,21 @@ export function createTechLogFeatureInstalledInput( const publicContent = context.publicSource === "MOCK" ? publicContentQueries - : createHttpPublicContentGateway({ operations: context.contractOperations }); + : createHttpPublicContentGateway({ http }); const createManagementGateway = () => - createHttpManagementGateway({ operations: context.contractOperations }); + createHttpManagementGateway({ http }); + + const createStudioApplication = () => + createTechLogStudioApplication({ + studio: createStudioGateway(), + assets: createStudioAssetGateway(), + management: createManagementGateway(), + }); const input: TechLogFeatureInput = Object.freeze({ publicContent, - createManagementGateway, - createStudioGateway, - createStudioAssetGateway, + createStudioApplication, }); return Object.freeze({ diff --git a/src/features/tech-log/adapters/http/http-management-gateway.ts b/src/features/tech-log/adapters/http/http-management-gateway.ts index b23ce45..1693b45 100644 --- a/src/features/tech-log/adapters/http/http-management-gateway.ts +++ b/src/features/tech-log/adapters/http/http-management-gateway.ts @@ -22,18 +22,18 @@ import type { ManagementGateway, } from "../../application/ports/management-gateway.ts"; import { ManagementGatewayError } from "../../application/ports/management-gateway-error.ts"; -import type { StudioOperationExecutor } from "./http-studio-gateway.ts"; +import type { + IdempotentOptions, + RequestOptions, +} from "../../application/ports/studio-gateway.ts"; +import { mutationIntent } from "./http-studio-gateway.ts"; +import type { + TechLogHttpBinding, + TechLogHttpOperationId, +} from "./tech-log-http-binding.ts"; export type { ManagementGateway }; -const ROUTE_ID = "TECH_LOG_STUDIO"; - -/** - * 주제·프로젝트 관리 게이트웨이. - * - *

Studio 게이트웨이와 같은 실패 규약을 쓴다 — 실패는 던지고, 화면은 `usePublicContent` 가 아니라 - * Studio 쪽 상태 처리를 그대로 쓴다. 여기서 Result 로 감싸면 이 표면만 다른 규약이 된다. - */ export { ManagementGatewayError, @@ -41,131 +41,227 @@ export { } from "../../application/ports/management-gateway-error.ts"; export function createHttpManagementGateway( - deps: Readonly<{ operations: StudioOperationExecutor }>, + deps: Readonly<{ http: TechLogHttpBinding }>, ): ManagementGateway { - async function run(operationId: string, input: unknown): Promise { - const outcome = await deps.operations.execute(operationId, input, { routeId: ROUTE_ID }); - if (outcome.kind === "SUCCESS") return outcome.value as T; - if (outcome.kind === "PROBLEM") { - // The management surface answers with the ADR-006 envelope, which nests - // the code under `error` — reading `problem.code` found nothing and every - // failure surfaced as the literal "PROBLEM", matching no i18n key. - const body = outcome.problem as - | Readonly<{ - code?: unknown; - detail?: unknown; - error?: Readonly<{ code?: unknown; message?: unknown }>; - }> - | null; - const code = - typeof body?.code === "string" - ? body.code - : typeof body?.error?.code === "string" - ? body.error.code - : "PROBLEM"; - const detail = - typeof body?.error?.message === "string" - ? body.error.message - : typeof body?.detail === "string" - ? body.detail - : ""; - throw new ManagementGatewayError(operationId, code, detail); - } - throw new ManagementGatewayError(operationId, outcome.kind, ""); + async function read( + operationId: TechLogHttpOperationId, + input: unknown, + options?: RequestOptions, + ): Promise { + const result = await deps.http.execute(operationId, input, { + ...(options?.signal ? { signal: options.signal } : {}), + }); + if (result.ok) return result.value as T; + throw new ManagementGatewayError( + operationId, + result.error.code, + result.error.detail ?? "", + ); + } + + async function command( + operationId: TechLogHttpOperationId, + input: unknown, + options: IdempotentOptions, + ): Promise { + const result = await deps.http.execute(operationId, input, { + intent: mutationIntent(operationId, options.idempotencyKey, input), + ...(options.signal ? { signal: options.signal } : {}), + }); + if (result.ok) return result.value as T; + throw new ManagementGatewayError( + operationId, + result.error.code, + result.error.detail ?? "", + ); } return Object.freeze({ - listTopics: () => run("listStudioTopics", {}), - createTopic: (input: TopicEdit) => run("createTopic", input), - updateTopic: (id: string, body: TopicEdit) => run("updateTopic", { id, body }), - listTopicVariants: (topicId: string) => - run("listTopicVariants", { id: topicId }), - createTopicVariant: (topicId: string, body: TopicVariantEdit) => - run("createTopicVariant", { id: topicId, body }), - updateTopicVariant: (topicId: string, variantId: string, body: TopicVariantEdit) => - run("updateTopicVariant", { id: topicId, variantId, body }), - deleteTopicVariant: async (topicId: string, variantId: string, expectedVersion: number) => { - await run("deleteTopicVariant", { id: topicId, variantId, expectedVersion }); + listTopics: (options) => read("listStudioTopics", {}, options), + createTopic: (input, options) => + command("createTopic", input, options), + updateTopic: (id, body, options) => + command("updateTopic", { id, body }, options), + deleteTopic: async (id, expectedVersion, options) => { + await command("deleteTopic", { id, expectedVersion }, options); }, - deleteTopic: async (id: string, expectedVersion: number) => { - await run("deleteTopic", { id, expectedVersion }); + + listTopicVariants: (topicId, options) => + read("listTopicVariants", { id: topicId }, options), + createTopicVariant: (topicId, body, options) => + command( + "createTopicVariant", + { id: topicId, body }, + options, + ), + updateTopicVariant: (topicId, variantId, body, options) => + command( + "updateTopicVariant", + { id: topicId, variantId, body }, + options, + ), + deleteTopicVariant: async ( + topicId, + variantId, + expectedVersion, + options, + ) => { + await command( + "deleteTopicVariant", + { id: topicId, variantId, expectedVersion }, + options, + ); }, - listProjects: (page?: number, size?: number) => - run("listStudioProjects", { ...(page !== undefined ? { page } : {}), ...(size !== undefined ? { size } : {}) }), - listQuestions: (page?: number, size?: number) => - run("listStudioQuestions", { - ...(page !== undefined ? { page } : {}), - ...(size !== undefined ? { size } : {}), - }), - listProjectDecisions: (projectId: string) => - run("listStudioProjectDecisions", { id: projectId }), - getProject: (id: string) => run("getProjectForEdit", { id }), - createProject: (title: string) => run("createProject", { title }), - updateProject: (id: string, body: ProjectUpdateRequest) => - run("updateProject", { id, body }), - listReleases: (page?: number, size?: number) => - run("listStudioReleases", { ...(page !== undefined ? { page } : {}), ...(size !== undefined ? { size } : {}) }), - getRelease: (id: string) => run("getReleaseForEdit", { id }), - createRelease: (title: string) => run("createRelease", { title }), - updateRelease: (id: string, body: ReleaseUpdateRequest) => - run("updateRelease", { id, body }), - deleteRelease: async (id: string, expectedVersion: number) => { - await run("deleteRelease", { id, expectedVersion }); - }, - listProjectActivities: (id: string) => - run("listStudioProjectActivities", { id }), - createProjectActivity: (id: string, body: ProjectActivityRequest) => - run("createProjectActivity", { id, body }), - updateProjectActivity: ( - id: string, - activityId: string, - body: UpdateProjectActivityRequest, - ) => run("updateProjectActivity", { id, activityId, body }), - deleteProjectActivity: async (id: string, activityId: string, expectedVersion: number) => { - await run("deleteProjectActivity", { id, activityId, expectedVersion }); + + listProjects: (page, size, options) => + read( + "listStudioProjects", + { + ...(page !== undefined ? { page } : {}), + ...(size !== undefined ? { size } : {}), + }, + options, + ), + listQuestions: (page, size, options) => + read( + "listStudioQuestions", + { + ...(page !== undefined ? { page } : {}), + ...(size !== undefined ? { size } : {}), + }, + options, + ), + listProjectDecisions: (projectId, options) => + read( + "listStudioProjectDecisions", + { id: projectId }, + options, + ), + + getProject: (id, options) => + read("getProjectForEdit", { id }, options), + createProject: (title, options) => + command("createProject", { title }, options), + updateProject: (id, body, options) => + command("updateProject", { id, body }, options), + deleteProject: async (id, expectedVersion, options) => { + await command("deleteProject", { id, expectedVersion }, options); }, publishProject: ( - id: string, - expectedVersion: number, - visibility: "PUBLIC" | "UNLISTED" = "PUBLIC", - ) => run("publishProject", { id, expectedVersion, visibility }), - unpublishProject: (id: string, expectedVersion: number) => - run("unpublishProject", { id, expectedVersion }), - getHomeFocus: () => run("getHomeFocus", {}), - updateHomeFocus: (body: HomeFocusRequest) => - run("updateHomeFocus", body), - publishRelease: (id: string, expectedVersion: number) => - run("publishRelease", { id, expectedVersion }), - archiveRelease: (id: string, expectedVersion: number) => - run("archiveRelease", { id, expectedVersion }), + id, + expectedVersion, + visibility = "PUBLIC", + options, + ) => + command( + "publishProject", + { id, expectedVersion, visibility }, + options, + ), + unpublishProject: (id, expectedVersion, options) => + command( + "unpublishProject", + { id, expectedVersion }, + options, + ), + + listProjectActivities: (id, options) => + read( + "listStudioProjectActivities", + { id }, + options, + ), + createProjectActivity: (id, body, options) => + command( + "createProjectActivity", + { id, body }, + options, + ), + updateProjectActivity: (id, activityId, body, options) => + command( + "updateProjectActivity", + { id, activityId, body }, + options, + ), + deleteProjectActivity: async ( + id, + activityId, + expectedVersion, + options, + ) => { + await command( + "deleteProjectActivity", + { id, activityId, expectedVersion }, + options, + ); + }, + + getHomeFocus: (options) => + read("getHomeFocus", {}, options), + updateHomeFocus: (body, options) => + command("updateHomeFocus", body, options), + + listReleases: (page, size, options) => + read( + "listStudioReleases", + { + ...(page !== undefined ? { page } : {}), + ...(size !== undefined ? { size } : {}), + }, + options, + ), + getRelease: (id, options) => + read("getReleaseForEdit", { id }, options), + createRelease: (title, options) => + command("createRelease", { title }, options), + updateRelease: (id, body, options) => + command("updateRelease", { id, body }, options), + deleteRelease: async (id, expectedVersion, options) => { + await command("deleteRelease", { id, expectedVersion }, options); + }, + publishRelease: (id, expectedVersion, options) => + command( + "publishRelease", + { id, expectedVersion }, + options, + ), + archiveRelease: (id, expectedVersion, options) => + command( + "archiveRelease", + { id, expectedVersion }, + options, + ), + deleteDocument: async ( kind: DeletableDocumentKind, id: string, expectedVersion: number, + options: IdempotentOptions, ) => { - /* - 삼항으로 이어 붙이면 마지막 else 가 모르는 종류를 다 받아 간다 — 개념이 그렇게 질문 - 삭제로 떨어졌고, 「질문을 찾을 수 없습니다」가 났다. 표로 두면 종류가 늘 때 빠진 - 자리를 타입이 잡는다. - - 메서드 매개변수는 TypeScript 에서 bivariant 라, 이 자리에 좁은 종류를 적어도 넓은 - 포트 시그니처를 만족한 것으로 통과한다 — 그래서 타입 검사가 이 결함을 잡지 못했다. - 아래 표가 `Record` 인 것이 실제로 종류를 강제하는 지점이다. - */ - const OPERATIONS: Record = { + const OPERATIONS: Record = { CASE: "deleteCaseDraft", REFERENCE: "deleteReferenceDraft", QUESTION: "deleteQuestion", CONCEPT: "deleteConceptDraft", SETUP: "deleteSetupDraft", }; - await run(OPERATIONS[kind], { id, expectedVersion }); + await command( + OPERATIONS[kind], + { id, expectedVersion }, + options, + ); }, - deleteDecision: async (projectId: string, decisionId: string, expectedVersion: number) => { - await run("deleteProjectDecision", { id: projectId, decisionId, expectedVersion }); - }, - deleteProject: async (id: string, expectedVersion: number) => { - await run("deleteProject", { id, expectedVersion }); + deleteDecision: async ( + projectId, + decisionId, + expectedVersion, + options, + ) => { + await command( + "deleteProjectDecision", + { id: projectId, decisionId, expectedVersion }, + options, + ); }, }); } diff --git a/src/features/tech-log/adapters/http/http-public-content-gateway.ts b/src/features/tech-log/adapters/http/http-public-content-gateway.ts index 24e315a..1616ad0 100644 --- a/src/features/tech-log/adapters/http/http-public-content-gateway.ts +++ b/src/features/tech-log/adapters/http/http-public-content-gateway.ts @@ -1,6 +1,9 @@ import type { HomeFocusItem, LatestRecordEntry, + PublicHomeView, + PublicProjectSummary, + PublicReleaseSummary, ProjectActivity, ProjectDecision, Project, @@ -30,10 +33,12 @@ import { } from "./public-content-mapping.ts"; import { cardSummary } from "../../domain/content-format/card-summary.ts"; import type { components } from "../../contracts/public/generated.ts"; -import type { StudioOperationExecutor } from "./http-studio-gateway.ts"; +import type { + TechLogHttpBinding, + TechLogHttpOperationId, +} from "./tech-log-http-binding.ts"; import { projectStageLabel } from "../../domain/public/project-phase-labels.ts"; -const ROUTE_ID = "TECH_LOG_PUBLIC"; /** * A missing slug is an answer, not a failure. @@ -53,19 +58,6 @@ function gatewayError(operationId: string, detail: string): PublicContentGateway return error; } -/** - * Reads the backend's error code out of either response shape — RFC7807 puts it - * at the top level, the ADR-006 envelope nests it under `error`. Without this - * every failure was reported as the literal "PROBLEM", which told a reader - * nothing and matched no i18n key. - */ -function problemCode(problem: unknown): string { - if (!problem || typeof problem !== "object") return "PROBLEM"; - const body = problem as Readonly<{ code?: unknown; error?: Readonly<{ code?: unknown }> }>; - if (typeof body.code === "string") return body.code; - if (typeof body.error?.code === "string") return body.error.code; - return "PROBLEM"; -} /* 관계 묶음의 이름을 사람이 읽는 말로 바꾼다. 라벨이 없으면 계약의 키가 그대로 화면에 나온다 — @@ -105,26 +97,22 @@ export const QUESTION_RELATION_LABELS = Object.freeze({ }); export function createHttpPublicContentGateway( - deps: Readonly<{ operations: StudioOperationExecutor }>, + deps: Readonly<{ http: TechLogHttpBinding }>, ): PublicContentQueries { - async function read(operationId: string, input: unknown): Promise { - const outcome = await deps.operations.execute(operationId, input, { routeId: ROUTE_ID }); - if (outcome.kind === "SUCCESS") return outcome.value as T; - if (outcome.kind === "PROBLEM") { - // The HTTP status is the authoritative signal, and the only one that - // holds across both shapes this surface answers with. RFC7807 carries - // `status` in the body; the ADR-006 envelope does not — it puts the - // reason in `error.category` and a backend-specific string in - // `error.code` (PUBLIC_RESOURCE_NOT_FOUND, not NOT_FOUND). The old - // body-only check matched neither, so every 404 raised the terminal - // error surface on a page whose real state was "this does not exist". - if (outcome.metadata.status === 404) return NOT_FOUND; - throw gatewayError(operationId, problemCode(outcome.problem)); - } - throw gatewayError(operationId, outcome.kind); + async function read( + operationId: TechLogHttpOperationId, + input: unknown, + ): Promise { + const result = await deps.http.execute(operationId, input); + if (result.ok) return result.value as T; + if (result.error.httpStatus === 404) return NOT_FOUND; + throw gatewayError(operationId, result.error.code); } - async function readOrThrow(operationId: string, input: unknown): Promise { + async function readOrThrow( + operationId: TechLogHttpOperationId, + input: unknown, + ): Promise { const value = await read(operationId, input); if (value === NOT_FOUND) throw gatewayError(operationId, "NOT_FOUND"); return value; @@ -185,7 +173,7 @@ export function createHttpPublicContentGateway( 표로 두면 종류가 늘 때 빠진 자리를 타입이 잡는다. */ - const OPERATIONS: Record = { + const OPERATIONS: Record = { CASE: "getPublicCase", REFERENCE: "getPublicReference", QUESTION: "getPublicQuestion", @@ -533,23 +521,29 @@ export function createHttpPublicContentGateway( }); } - /** - * 공개 투영이 고른 최근 기록. `entryType` 은 계약이 네 값만 허용하므로 그대로 믿고 쓴다 — - * 서버가 이미 걸러 보낸다. - */ - async function getLatestEntries(): Promise { - const home = await read>[] }>>( - "getPublicHome", - {}, - ); - if (home === NOT_FOUND) return []; + type PublicHomeProjection = Readonly<{ + latestEntries?: readonly Readonly>[]; + focus?: Readonly>; + }>; + + function latestEntriesFromHome( + home: PublicHomeProjection, + ): LatestRecordEntry[] { return (home.latestEntries ?? []).map((entry) => { - const topic = entry.primaryTopic as Readonly> | null | undefined; - const project = entry.primaryProject as Readonly> | null | undefined; + const topic = entry.primaryTopic as + | Readonly> + | null + | undefined; + const project = entry.primaryProject as + | Readonly> + | null + | undefined; const path = String(entry.path ?? ""); return Object.freeze({ id: `${String(entry.entryType ?? "")}:${path}`, - entryType: String(entry.entryType ?? "CASE") as LatestRecordEntry["entryType"], + entryType: String( + entry.entryType ?? "CASE", + ) as LatestRecordEntry["entryType"], title: String(entry.title ?? ""), summary: String(entry.summary ?? ""), path, @@ -560,13 +554,10 @@ export function createHttpPublicContentGateway( }); } - async function getHomeFocusItems(): Promise { - const home = await read> }>>( - "getPublicHome", - {}, - ); - if (home === NOT_FOUND) return []; - const focus = (home.focus ?? {}) as Readonly>>>; + function focusItemsFromHome(home: PublicHomeProjection): HomeFocusItem[] { + const focus = (home.focus ?? {}) as Readonly< + Record>> + >; const items: HomeFocusItem[] = []; const work = focus.currentWork; if (work) { @@ -577,19 +568,21 @@ export function createHttpPublicContentGateway( title: String(work.projectName ?? ""), summary: String(work.purpose ?? ""), details: Object.freeze([ - /* - 단계는 저장하는 값(`DESIGN`)이지 방문자에게 할 말이 아니다. 홈의 「지금 집중하는 - 것」이 그 상수를 그대로 찍고 있었다 — 프로젝트 화면은 같은 값을 「설계」로 부르고 - 있어서, 한 사이트가 같은 것을 두 이름으로 말했다. - */ - { label: "단계", value: projectStageLabel(String(work.phase ?? "")) }, - { label: "현재 목표", value: String(work.currentObjective ?? "") }, + { + label: "단계", + value: projectStageLabel(String(work.phase ?? "")), + }, + { + label: "현재 목표", + value: String(work.currentObjective ?? ""), + }, { label: "다음 작업", value: String(work.nextStep ?? "") }, ]), targetPath: String(work.projectPath ?? "/projects"), }), ); } + const question = focus.openQuestion; if (question) { items.push( @@ -599,14 +592,28 @@ export function createHttpPublicContentGateway( title: String(question.question ?? ""), summary: String(question.summary ?? ""), details: Object.freeze([ - { label: "확인한 사실", value: ((question.knownFacts as readonly string[]) ?? []).join(" · ") }, - { label: "미해결", value: ((question.unresolvedPoints as readonly string[]) ?? []).join(" · ") }, - { label: "다음 검증", value: String(question.nextVerification ?? "") }, + { + label: "확인한 사실", + value: ( + (question.knownFacts as readonly string[]) ?? [] + ).join(" · "), + }, + { + label: "미해결", + value: ( + (question.unresolvedPoints as readonly string[]) ?? [] + ).join(" · "), + }, + { + label: "다음 검증", + value: String(question.nextVerification ?? ""), + }, ]), targetPath: String(question.questionPath ?? "/explore/questions"), }), ); } + const decision = focus.recentDecision; if (decision) { items.push( @@ -616,8 +623,16 @@ export function createHttpPublicContentGateway( title: String(decision.statement ?? ""), summary: String(decision.rationale ?? ""), details: Object.freeze([ - { label: "결정일", value: dateLabel(decision.decidedAt as string) }, - { label: "영향", value: ((decision.consequences as readonly string[]) ?? []).join(" · ") }, + { + label: "결정일", + value: dateLabel(decision.decidedAt as string), + }, + { + label: "영향", + value: ( + (decision.consequences as readonly string[]) ?? [] + ).join(" · "), + }, ]), targetPath: String(decision.decisionPath ?? "/projects"), }), @@ -626,27 +641,56 @@ export function createHttpPublicContentGateway( return items; } - /** - * 빈 검색어는 검색이 아니라 "카탈로그 전부"라는 뜻이다. - * - * 픽스처가 그렇게 동작했고 화면들이 그 의미에 기대어 쓰고 있다 — 홈 타임라인, - * 프로젝트 목록, 릴리즈 목록, 탐색 필터가 전부 `searchPublicContent("")` 로 카탈로그를 - * 받아 간다. 계약에는 그런 의미가 없고 `q` 는 필수라, 그대로 보내면 400 - * (`PUBLIC_REQUEST_INVALID`) 이 오고 홈을 포함한 네 화면이 통째로 오류 화면이 된다. - * - * 그래서 빈 검색어는 검색 엔드포인트로 보내지 않고, 계약이 이미 가진 목록 - * 엔드포인트에서 조립한다. 검색어가 있으면 그때는 서버 검색을 쓴다 — 클라이언트에서 - * 거르면 페이지 밖의 결과를 영영 못 찾는다. - */ - async function searchPublicContent(query: string): Promise { - const trimmed = query.trim(); - if (trimmed.length > 0) { - const page = await read("searchPublicResources", { q: trimmed }); - if (page === NOT_FOUND) return []; - return (page.items ?? []).map(searchItemToEntity); + async function getHome(): Promise { + const home = await read("getPublicHome", {}); + if (home === NOT_FOUND) { + return Object.freeze({ + focusItems: Object.freeze([]), + latestEntries: Object.freeze([]), + }); } + return Object.freeze({ + focusItems: Object.freeze(focusItemsFromHome(home)), + latestEntries: Object.freeze(latestEntriesFromHome(home)), + }); + } - const [knowledge, questions, projects, releases] = await Promise.all([ + async function listProjects(): Promise { + const page = await read("listPublicProjects", {}); + if (page === NOT_FOUND) return []; + return (page.items ?? []).map((item) => + Object.freeze({ + slug: String(item.slug ?? ""), + title: String(item.name ?? ""), + summary: String(item.oneLinePurpose ?? ""), + path: String(item.path ?? `/projects/${String(item.slug ?? "")}`), + }), + ); + } + + async function getLatestEntries(): Promise { + return [...(await getHome()).latestEntries]; + } + + async function getHomeFocusItems(): Promise { + return [...(await getHome()).focusItems]; + } + + async function listReleases(): Promise { + const page = await read("listPublicReleases", {}); + if (page === NOT_FOUND) return []; + return (page.items ?? []).map((item) => + Object.freeze({ + version: String(item.version ?? ""), + title: String(item.title ?? ""), + summary: String(item.summary ?? ""), + path: String(item.path ?? `/releases/${String(item.version ?? "")}`), + }), + ); + } + + async function listCatalog(): Promise { + const [knowledge, questions, projectPage, releasePage] = await Promise.all([ read("exploreKnowledge", {}), read("exploreQuestions", {}), read("listPublicProjects", {}), @@ -663,7 +707,7 @@ export function createHttpPublicContentGateway( for (const item of items(questions)) { entities.push(recordToEntity(questionListItemToRecord(item))); } - for (const item of items(projects)) { + for (const item of items(projectPage)) { entities.push( Object.freeze({ contentType: "PROJECT", @@ -673,7 +717,7 @@ export function createHttpPublicContentGateway( }), ); } - for (const item of items(releases)) { + for (const item of items(releasePage)) { entities.push( Object.freeze({ contentType: "RELEASE", @@ -686,6 +730,17 @@ export function createHttpPublicContentGateway( return entities; } + async function searchPublicContent( + query: string, + ): Promise { + const trimmed = query.trim(); + if (trimmed.length === 0) return listCatalog(); + + const page = await read("searchPublicResources", { q: trimmed }); + if (page === NOT_FOUND) return []; + return (page.items ?? []).map(searchItemToEntity); + } + function recordToEntity(record: PublicRecord): SearchablePublicEntity { return Object.freeze({ contentType: record.kind, @@ -709,6 +764,10 @@ export function createHttpPublicContentGateway( getProjectRecords, getProjectDecisions, getProjectActivity, + getHome, + listProjects, + listReleases, + listCatalog, getHomeFocusItems, getLatestEntries, searchPublicContent, diff --git a/src/features/tech-log/adapters/http/http-studio-asset-gateway.ts b/src/features/tech-log/adapters/http/http-studio-asset-gateway.ts index 143904c..0c5ed91 100644 --- a/src/features/tech-log/adapters/http/http-studio-asset-gateway.ts +++ b/src/features/tech-log/adapters/http/http-studio-asset-gateway.ts @@ -11,8 +11,12 @@ import type { } from "../../application/ports/studio-asset-gateway.ts"; import type { IdempotentOptions, RequestOptions } from "../../application/ports/studio-gateway.ts"; import { isStudioGatewayError } from "../../application/ports/studio-gateway-error.ts"; -import { toStudioGatewayError } from "./studio-error-mapping.ts"; -import { mutationIntent, type StudioOperationExecutor } from "./http-studio-gateway.ts"; +import { toStudioGatewayErrorFromFailure } from "./studio-error-mapping.ts"; +import { mutationIntent } from "./http-studio-gateway.ts"; +import type { + TechLogHttpBinding, + TechLogHttpOperationId, +} from "./tech-log-http-binding.ts"; import type { CsrfTokenProvider } from "./studio-session-csrf.ts"; export type StudioAssetUploadTransport = Readonly<{ @@ -24,35 +28,38 @@ export type StudioAssetUploadTransport = Readonly<{ }>; export type HttpStudioAssetGatewayDependencies = Readonly<{ - operations: StudioOperationExecutor; + http: TechLogHttpBinding; csrf: CsrfTokenProvider; upload: StudioAssetUploadTransport; }>; -const ROUTE_ID = "TECH_LOG_STUDIO_ASSETS"; export function createHttpStudioAssetGateway( deps: HttpStudioAssetGatewayDependencies, ): StudioAssetGateway { - async function read(operationId: string, input: unknown, options?: RequestOptions) { - const outcome = await deps.operations.execute(operationId, input, { - routeId: ROUTE_ID, + async function read( + operationId: TechLogHttpOperationId, + input: unknown, + options?: RequestOptions, + ) { + const result = await deps.http.execute(operationId, input, { ...(options?.signal ? { signal: options.signal } : {}), }); - if (outcome.kind !== "SUCCESS") throw toStudioGatewayError(outcome, operationId); - return outcome.value as T; + if (!result.ok) throw toStudioGatewayErrorFromFailure(result.error); + return result.value as T; } - async function command(operationId: string, input: unknown, options: IdempotentOptions) { - // Task 4와 동일한 규칙: 헤더는 gateway가 만들지 않는다. `Idempotency-Key`는 - // intent에서, `x-csrf-token`은 credential collaborator에서 온다. - const outcome = await deps.operations.execute(operationId, input, { - routeId: ROUTE_ID, + async function command( + operationId: TechLogHttpOperationId, + input: unknown, + options: IdempotentOptions, + ) { + const result = await deps.http.execute(operationId, input, { intent: mutationIntent(operationId, options.idempotencyKey, input), ...(options.signal ? { signal: options.signal } : {}), }); - if (outcome.kind === "SUCCESS") return outcome.value as T; - throw toStudioGatewayError(outcome, operationId); + if (result.ok) return result.value as T; + throw toStudioGatewayErrorFromFailure(result.error); } const gateway: StudioAssetGateway = { diff --git a/src/features/tech-log/adapters/http/http-studio-gateway.ts b/src/features/tech-log/adapters/http/http-studio-gateway.ts index 225b9ca..d4ec4dc 100644 --- a/src/features/tech-log/adapters/http/http-studio-gateway.ts +++ b/src/features/tech-log/adapters/http/http-studio-gateway.ts @@ -4,33 +4,22 @@ import { MUTATION_INTENT_BOUNDS, type MutationIntent, } from "../../../../contracts/mutation-intent.ts"; -import type { HttpExecutionOutcome } from "../../../../adapters/http/index.ts"; import { stableStringify } from "../stable-stringify.ts"; import type { IdempotentOptions, RequestOptions, StudioGateway, } from "../../application/ports/studio-gateway.ts"; -import { toStudioGatewayError } from "./studio-error-mapping.ts"; - -export type StudioOperationExecutor = Readonly<{ - execute( - operationId: string, - input: unknown, - context: Readonly<{ - routeId: string; - signal?: AbortSignal; - intent?: MutationIntent; - }>, - ): Promise>; -}>; +import { toStudioGatewayErrorFromFailure } from "./studio-error-mapping.ts"; +import type { + TechLogHttpBinding, + TechLogHttpOperationId, +} from "./tech-log-http-binding.ts"; export type HttpStudioGatewayDependencies = Readonly<{ - operations: StudioOperationExecutor; + http: TechLogHttpBinding; }>; -const ROUTE_ID = "TECH_LOG_STUDIO"; - const IDENTITY_ENCODER = new TextEncoder(); const IDENTITY_DECODER = new TextDecoder(); @@ -42,7 +31,7 @@ const IDENTITY_DECODER = new TextDecoder(); * "A caller-supplied value is never trimmed, regenerated or silently dropped"). */ export function mutationIntent( - operationId: string, + operationId: TechLogHttpOperationId, idempotencyKey: string, input: unknown, ): MutationIntent { @@ -85,30 +74,28 @@ export function createHttpStudioGateway( deps: HttpStudioGatewayDependencies, ): StudioGateway { async function read( - operationId: string, + operationId: TechLogHttpOperationId, input: unknown, options?: RequestOptions, ): Promise { - const outcome = await deps.operations.execute(operationId, input, { - routeId: ROUTE_ID, + const result = await deps.http.execute(operationId, input, { ...(options?.signal ? { signal: options.signal } : {}), }); - if (outcome.kind !== "SUCCESS") throw toStudioGatewayError(outcome, operationId); - return outcome.value as T; + if (!result.ok) throw toStudioGatewayErrorFromFailure(result.error); + return result.value as T; } async function command( - operationId: string, + operationId: TechLogHttpOperationId, input: unknown, options: IdempotentOptions, ): Promise { - const outcome = await deps.operations.execute(operationId, input, { - routeId: ROUTE_ID, + const result = await deps.http.execute(operationId, input, { intent: mutationIntent(operationId, options.idempotencyKey, input), ...(options.signal ? { signal: options.signal } : {}), }); - if (outcome.kind === "SUCCESS") return outcome.value as T; - throw toStudioGatewayError(outcome, operationId); + if (result.ok) return result.value as T; + throw toStudioGatewayErrorFromFailure(result.error); } const gateway: StudioGateway = { diff --git a/src/features/tech-log/adapters/http/studio-error-mapping.ts b/src/features/tech-log/adapters/http/studio-error-mapping.ts index 7967580..cde8256 100644 --- a/src/features/tech-log/adapters/http/studio-error-mapping.ts +++ b/src/features/tech-log/adapters/http/studio-error-mapping.ts @@ -1,4 +1,5 @@ import type { HttpExecutionOutcome } from "../../../../adapters/http/index.ts"; +import type { AppFailure } from "../../../../contracts/errors.ts"; import { StudioGatewayError } from "../../application/ports/studio-gateway-error.ts"; import type { ProblemDetails } from "../../contracts/studio/contract.ts"; @@ -92,3 +93,45 @@ export function toStudioGatewayError( throw new Error(`${operationId}: success outcome is not an error`); } } + + +function fallbackStatus(failure: AppFailure): number { + if (failure.httpStatus !== undefined) return failure.httpStatus; + switch (failure.kind) { + case "AUTH_REQUIRED": + return 401; + case "FORBIDDEN": + return 403; + case "RATE_LIMITED": + return 429; + case "REQUEST_ABORTED": + return 499; + case "REQUEST_TIMEOUT": + return 504; + case "NETWORK_UNREACHABLE": + case "SERVER_FAILURE": + return 503; + default: + return 502; + } +} + +export function toStudioGatewayErrorFromFailure( + failure: AppFailure, +): StudioGatewayError { + const status = fallbackStatus(failure); + const code: ProblemDetails["code"] = + CODES.has(failure.code) + ? failure.code as ProblemDetails["code"] + : failure.kind === "AUTH_REQUIRED" + ? "AUTHENTICATION_REQUIRED" + : failure.kind === "FORBIDDEN" + ? "STUDIO_ACCESS_DENIED" + : "STUDIO_UNAVAILABLE"; + return synthetic( + code, + status, + failure.detail ?? (failure.operationId + ": " + failure.code), + failure.retryable, + ); +} diff --git a/src/features/tech-log/adapters/http/tech-log-http-binding.ts b/src/features/tech-log/adapters/http/tech-log-http-binding.ts new file mode 100644 index 0000000..d285455 --- /dev/null +++ b/src/features/tech-log/adapters/http/tech-log-http-binding.ts @@ -0,0 +1,130 @@ +import { + createFeatureHttpBinding, + defineFeatureHttpOperation, + type FeatureHttpBinding, + type FeatureHttpOperation, + type InstalledHttpOperationExecutor, + type SafeResponseMetadata, +} from "../../../../adapters/http/index.ts"; +import { mappingSuccess } from "../../../../contracts/boundary-mapper.ts"; +import { kindForStatus } from "../../../../contracts/errors.ts"; +import type { ProblemDetails } from "../../contracts/studio/contract.ts"; +import { TECH_LOG_MANAGEMENT_HTTP_CONTRACTS } from "../../contracts/tech-log-management-contract-contribution.ts"; +import { TECH_LOG_PUBLIC_HTTP_CONTRACTS } from "../../contracts/tech-log-public-contract-contribution.ts"; +import { TECH_LOG_STUDIO_HTTP_CONTRACTS } from "../../contracts/tech-log-studio-contract-contribution.ts"; + +const TECH_LOG_HTTP_CONTRACTS = Object.freeze([ + ...TECH_LOG_STUDIO_HTTP_CONTRACTS, + ...TECH_LOG_PUBLIC_HTTP_CONTRACTS, + ...TECH_LOG_MANAGEMENT_HTTP_CONTRACTS, +] as const); + +type TechLogHttpContract = (typeof TECH_LOG_HTTP_CONTRACTS)[number]; + +export type TechLogHttpOperationId = + TechLogHttpContract["contract"]["operationId"]; + +type ContractFor = + Extract< + TechLogHttpContract, + Readonly<{ + contract: Readonly<{ operationId: OperationId }>; + }> + >; + +type TechLogRouteId = + | "TECH_LOG_STUDIO" + | "TECH_LOG_STUDIO_ASSETS" + | "TECH_LOG_PUBLIC"; + +type TechLogHttpOperations = Readonly<{ + [OperationId in TechLogHttpOperationId]: FeatureHttpOperation< + ContractFor, + unknown, + TechLogRouteId + >; +}>; + +const ASSET_OPERATION_IDS = new Set([ + "listStudioAssets", + "getStudioAsset", + "updateStudioAsset", + "deleteStudioAsset", +]); + +const PUBLIC_OPERATION_IDS = new Set( + TECH_LOG_PUBLIC_HTTP_CONTRACTS.map( + (contract) => contract.contract.operationId as TechLogHttpOperationId, + ), +); + +function routeIdFor(operationId: TechLogHttpOperationId): TechLogRouteId { + if (PUBLIC_OPERATION_IDS.has(operationId)) return "TECH_LOG_PUBLIC"; + if (ASSET_OPERATION_IDS.has(operationId)) return "TECH_LOG_STUDIO_ASSETS"; + return "TECH_LOG_STUDIO"; +} + +function problemCode(problem: unknown): string { + if (!problem || typeof problem !== "object") return "CONTRACT_PROBLEM"; + const candidate = problem as Readonly<{ + code?: unknown; + error?: Readonly<{ code?: unknown }>; + }>; + if (typeof candidate.code === "string") return candidate.code; + if (typeof candidate.error?.code === "string") return candidate.error.code; + return "CONTRACT_PROBLEM"; +} + +function problemDetail(problem: unknown): string | undefined { + if (!problem || typeof problem !== "object") return undefined; + const candidate = problem as Partial & + Readonly<{ error?: Readonly<{ message?: unknown }> }>; + if (typeof candidate.detail === "string" && candidate.detail.length > 0) { + return candidate.detail; + } + return typeof candidate.error?.message === "string" && + candidate.error.message.length > 0 + ? candidate.error.message + : undefined; +} + +function mapProblem(problem: unknown, metadata: SafeResponseMetadata) { + const detail = problemDetail(problem); + return Object.freeze({ + kind: kindForStatus(metadata.status), + code: problemCode(problem), + ...(detail === undefined ? {} : { detail }), + }); +} + +function buildOperations(): TechLogHttpOperations { + const registry: Record> = + Object.create(null); + + for (const contract of TECH_LOG_HTTP_CONTRACTS) { + const operationId = contract.contract.operationId as TechLogHttpOperationId; + if (Object.hasOwn(registry, operationId)) { + throw new TypeError("Duplicate TechLog HTTP operation: " + operationId); + } + registry[operationId] = defineFeatureHttpOperation({ + contract, + routeId: routeIdFor(operationId), + mapSuccess: mappingSuccess, + mapProblem, + }) as FeatureHttpOperation; + } + + return Object.freeze(registry) as unknown as TechLogHttpOperations; +} + +export const TECH_LOG_HTTP_OPERATIONS = buildOperations(); + +export type TechLogHttpBinding = FeatureHttpBinding< + typeof TECH_LOG_HTTP_OPERATIONS +>; + +export function createTechLogHttpBinding( + executor: InstalledHttpOperationExecutor, +): TechLogHttpBinding { + return createFeatureHttpBinding(executor, TECH_LOG_HTTP_OPERATIONS); +} diff --git a/src/features/tech-log/adapters/static/content.ts b/src/features/tech-log/adapters/static/content.ts index 43e3363..dde0369 100644 --- a/src/features/tech-log/adapters/static/content.ts +++ b/src/features/tech-log/adapters/static/content.ts @@ -1,5 +1,5 @@ import { projects, publicRecords, releases } from "./public-content.ts"; -import { getHomeFocusItems, searchPublicContent } from "./public-query.ts"; +import { getHomeFocusItems, listCatalog } from "./public-query.ts"; export { publicSiteConfig as siteConfig } from "../../contracts/public-site-config.ts"; @@ -82,7 +82,7 @@ export const exploreEntries = [ }, ] as const; -export const searchEntries = searchPublicContent(""); +export const searchEntries = listCatalog(); const fetchJoinCase = publicRecords.find( (record) => diff --git a/src/features/tech-log/adapters/static/public-query.ts b/src/features/tech-log/adapters/static/public-query.ts index 43c2c2e..72ef0d3 100644 --- a/src/features/tech-log/adapters/static/public-query.ts +++ b/src/features/tech-log/adapters/static/public-query.ts @@ -326,13 +326,17 @@ function releaseSearchEntity(release: Release): SearchablePublicEntity { }; } -export function searchPublicContent(query: string): SearchablePublicEntity[] { - const normalizedQuery = query.trim().toLocaleLowerCase("ko-KR"); - const entities = [ +export function listCatalog(): SearchablePublicEntity[] { + return [ ...publicRecords.map(recordSearchEntity), ...projects.map(projectSearchEntity), ...releases.map(releaseSearchEntity), ]; +} + +export function searchPublicContent(query: string): SearchablePublicEntity[] { + const normalizedQuery = query.trim().toLocaleLowerCase("ko-KR"); + const entities = listCatalog(); if (!normalizedQuery) return entities; @@ -393,6 +397,35 @@ export const publicContentQueries = Object.freeze({ async getTopicDetail(slug: string) { return getTopicDetail(slug); }, + async getHome() { + return Object.freeze({ + focusItems: Object.freeze(getHomeFocusItems()), + latestEntries: Object.freeze(getLatestEntries()), + }); + }, + async listProjects() { + return projects.map((project) => + Object.freeze({ + slug: project.slug, + title: project.title, + summary: project.summary, + path: `/projects/${project.slug}`, + }), + ); + }, + async listReleases() { + return releases.map((release) => + Object.freeze({ + version: release.version, + title: release.title, + summary: release.summary, + path: release.path, + }), + ); + }, + async listCatalog() { + return listCatalog(); + }, async getLatestEntries() { return getLatestEntries(); }, diff --git a/src/features/tech-log/application/ports/management-gateway.ts b/src/features/tech-log/application/ports/management-gateway.ts index 3987580..334c588 100644 --- a/src/features/tech-log/application/ports/management-gateway.ts +++ b/src/features/tech-log/application/ports/management-gateway.ts @@ -17,92 +17,182 @@ import type { TopicEdit, TopicVariantEdit, } from "../../contracts/management/contract.ts"; +import type { + IdempotentOptions, + RequestOptions, +} from "./studio-gateway.ts"; /** * 주제·프로젝트·릴리즈·작업본 삭제 관리 표면. * - *

Studio 게이트웨이와 같은 실패 규약이다 — 실패는 던지고, 화면이 잡는다. MOCK 대응물을 두지 - * 않는 것도 의도다: 이 표면은 백엔드가 없으면 존재할 이유가 없고, 픽스처를 만들면 실제로는 만들 - * 수 없는 주제를 화면이 보여주게 된다. + * 읽기와 명령 모두 Studio server-state runtime의 cancellation/idempotency + * 계약을 끝까지 전달할 수 있어야 한다. presentation이 공통 mutation + * coordinator를 사용해도 이 포트에서 옵션을 버리면 실제 HTTP 실행은 그 + * 보호를 받지 못한다. */ -/** 이 게이트웨이로 지울 수 있는 문서 종류. 결정은 프로젝트 경로를 요구하므로 별도 메서드다. */ -export type DeletableDocumentKind = "CASE" | "REFERENCE" | "QUESTION" | "CONCEPT" | "SETUP"; +export type DeletableDocumentKind = + | "CASE" + | "REFERENCE" + | "QUESTION" + | "CONCEPT" + | "SETUP"; export type ManagementGateway = Readonly<{ - listTopics(): Promise; - createTopic(input: TopicEdit): Promise; - updateTopic(id: string, body: TopicEdit): Promise; - deleteTopic(id: string, expectedVersion: number): Promise; - /* - 주제 안의 축. 「구조」「조회 전략」처럼 주제마다 이름이 다른 축 하나가 접근 하나고, 기록은 - 거기에 걸린다. 아무 축에도 걸리지 않은 기록은 그 주제의 공통 기록이다. - */ - listTopicVariants(topicId: string): Promise; - createTopicVariant(topicId: string, body: TopicVariantEdit): Promise; + listTopics(options?: RequestOptions): Promise; + createTopic( + input: TopicEdit, + options: IdempotentOptions, + ): Promise; + updateTopic( + id: string, + body: TopicEdit, + options: IdempotentOptions, + ): Promise; + deleteTopic( + id: string, + expectedVersion: number, + options: IdempotentOptions, + ): Promise; + + listTopicVariants( + topicId: string, + options?: RequestOptions, + ): Promise; + createTopicVariant( + topicId: string, + body: TopicVariantEdit, + options: IdempotentOptions, + ): Promise; updateTopicVariant( topicId: string, variantId: string, body: TopicVariantEdit, + options: IdempotentOptions, ): Promise; - deleteTopicVariant(topicId: string, variantId: string, expectedVersion: number): Promise; - listProjects(page?: number, size?: number): Promise; - /* - 홈 「지금 집중하는 것」 편집기가 쓰는 둘. 질문 항목은 `primaryProject` 를 들고 오므로 그것으로 - 거르고, 결정은 경로 자체가 프로젝트를 요구하므로 고른 프로젝트의 것만 온다. - */ - listQuestions(page?: number, size?: number): Promise; - listProjectDecisions(projectId: string): Promise; - getProject(id: string): Promise; - createProject(title: string): Promise; - updateProject(id: string, body: ProjectUpdateRequest): Promise; - deleteProject(id: string, expectedVersion: number): Promise; - /** - * 프로젝트 게시. 프로젝트는 Studio 문서가 아니라 게시 파이프라인 밖에 있고, 그래서 문서를 - * 게시해도 그 문서가 속한 프로젝트는 비공개로 남는다 — 공개 화면(프로젝트 목록·프로필의 - * "현재 프로젝트"·홈의 focus)은 모두 게시된 프로젝트만 읽으므로, 이 호출 없이는 어디에도 - * 나타나지 않는다. - */ + deleteTopicVariant( + topicId: string, + variantId: string, + expectedVersion: number, + options: IdempotentOptions, + ): Promise; + + listProjects( + page?: number, + size?: number, + options?: RequestOptions, + ): Promise; + listQuestions( + page?: number, + size?: number, + options?: RequestOptions, + ): Promise; + listProjectDecisions( + projectId: string, + options?: RequestOptions, + ): Promise; + + getProject( + id: string, + options?: RequestOptions, + ): Promise; + createProject( + title: string, + options: IdempotentOptions, + ): Promise; + updateProject( + id: string, + body: ProjectUpdateRequest, + options: IdempotentOptions, + ): Promise; + deleteProject( + id: string, + expectedVersion: number, + options: IdempotentOptions, + ): Promise; publishProject( id: string, expectedVersion: number, - visibility?: "PUBLIC" | "UNLISTED", + visibility: "PUBLIC" | "UNLISTED" | undefined, + options: IdempotentOptions, ): Promise; - unpublishProject(id: string, expectedVersion: number): Promise; - /** - * 프로젝트 활동. 공개 프로젝트 화면의 "활동" 은 이 목록을 투영 없이 직접 읽으므로, 여기서 - * 만든 줄이 곧 그 화면이다. - */ - listProjectActivities(id: string): Promise; - createProjectActivity(id: string, body: ProjectActivityRequest): Promise; + unpublishProject( + id: string, + expectedVersion: number, + options: IdempotentOptions, + ): Promise; + + listProjectActivities( + id: string, + options?: RequestOptions, + ): Promise; + createProjectActivity( + id: string, + body: ProjectActivityRequest, + options: IdempotentOptions, + ): Promise; updateProjectActivity( id: string, activityId: string, body: UpdateProjectActivityRequest, + options: IdempotentOptions, ): Promise; - deleteProjectActivity(id: string, activityId: string, expectedVersion: number): Promise; - /** 공개 홈이 무엇을 앞에 둘지. 세 슬롯이 모두 비면 홈은 그 영역을 아예 그리지 않는다. */ - getHomeFocus(): Promise; - updateHomeFocus(body: HomeFocusRequest): Promise; - listReleases(page?: number, size?: number): Promise; - getRelease(id: string): Promise; - createRelease(title: string): Promise; - updateRelease(id: string, body: ReleaseUpdateRequest): Promise; - deleteRelease(id: string, expectedVersion: number): Promise; - publishRelease(id: string, expectedVersion: number): Promise; - archiveRelease(id: string, expectedVersion: number): Promise; - /** - * 작업본 삭제. 종류마다 다른 endpoint 인 것은 계약의 모양이자 저장 구조다 — Case 와 Reference - * 는 한 테이블을 나눠 쓰고 Question 은 다른 테이블이다. Decision 은 계약에 삭제가 없다: - * 그쪽 수명주기는 수락·기각·대체이고, 그건 지우는 것이 아니라 무슨 일이 있었는지 남기는 것이다. - */ - /** - * 작업본 삭제. 종류를 손으로 나열하지 않는다 — 개념을 더했을 때 이 목록이 셋에 머물러 - * 있었고, 부르는 쪽이 `as` 로 캐스팅해 넘기는 바람에 개념이 질문 삭제로 떨어졌다. - */ - deleteDocument(kind: DeletableDocumentKind, id: string, expectedVersion: number): Promise; - /** - * Decision 은 프로젝트에 속하므로 경로가 둘을 요구한다. 다른 종류처럼 한 번에 묶지 않는 이유는 - * 계약이 그렇게 선언했고, 실제로도 프로젝트 밖의 Decision 은 존재하지 않기 때문이다. - */ - deleteDecision(projectId: string, decisionId: string, expectedVersion: number): Promise; + deleteProjectActivity( + id: string, + activityId: string, + expectedVersion: number, + options: IdempotentOptions, + ): Promise; + + getHomeFocus(options?: RequestOptions): Promise; + updateHomeFocus( + body: HomeFocusRequest, + options: IdempotentOptions, + ): Promise; + + listReleases( + page?: number, + size?: number, + options?: RequestOptions, + ): Promise; + getRelease( + id: string, + options?: RequestOptions, + ): Promise; + createRelease( + title: string, + options: IdempotentOptions, + ): Promise; + updateRelease( + id: string, + body: ReleaseUpdateRequest, + options: IdempotentOptions, + ): Promise; + deleteRelease( + id: string, + expectedVersion: number, + options: IdempotentOptions, + ): Promise; + publishRelease( + id: string, + expectedVersion: number, + options: IdempotentOptions, + ): Promise; + archiveRelease( + id: string, + expectedVersion: number, + options: IdempotentOptions, + ): Promise; + + deleteDocument( + kind: DeletableDocumentKind, + id: string, + expectedVersion: number, + options: IdempotentOptions, + ): Promise; + deleteDecision( + projectId: string, + decisionId: string, + expectedVersion: number, + options: IdempotentOptions, + ): Promise; }>; diff --git a/src/features/tech-log/application/ports/public-content-queries.ts b/src/features/tech-log/application/ports/public-content-queries.ts index 9d1a4b6..c7ed1f0 100644 --- a/src/features/tech-log/application/ports/public-content-queries.ts +++ b/src/features/tech-log/application/ports/public-content-queries.ts @@ -325,6 +325,25 @@ export type HomeFocusItem = { targetPath: string; }; +export type PublicHomeView = Readonly<{ + focusItems: readonly HomeFocusItem[]; + latestEntries: readonly LatestRecordEntry[]; +}>; + +export type PublicProjectSummary = Readonly<{ + slug: string; + title: string; + summary: string; + path: string; +}>; + +export type PublicReleaseSummary = Readonly<{ + version: string; + title: string; + summary: string; + path: string; +}>; + export type RecordFilters = { kind?: RecordKind; topic?: string; @@ -388,6 +407,14 @@ export type PublicContentQueries = Readonly<{ listContacts(): Promise; /** 주제 한 편. 주제가 없으면 `undefined`. */ getTopicDetail(slug: string): Promise; + /** 홈 투영은 한 번 읽어 focus/latest를 같은 snapshot에서 돌려준다. */ + getHome(): Promise; + /** 검색과 분리된 명시적 프로젝트 목록 use case. */ + listProjects(): Promise; + /** 검색과 분리된 명시적 릴리즈 목록 use case. */ + listReleases(): Promise; + /** type-ahead/filter가 로컬에서 거를 공개 카탈로그 snapshot. */ + listCatalog(): Promise; getLatestEntries(): Promise; getHomeFocusItems(): Promise; searchPublicContent(query: string): Promise; diff --git a/src/features/tech-log/application/studio-application.ts b/src/features/tech-log/application/studio-application.ts new file mode 100644 index 0000000..5f3cee3 --- /dev/null +++ b/src/features/tech-log/application/studio-application.ts @@ -0,0 +1,243 @@ +import type { + ManagementGateway, + DeletableDocumentKind, +} from "./ports/management-gateway.ts"; +import { ManagementGatewayError } from "./ports/management-gateway-error.ts"; +import type { + StudioAssetGateway, + ListAssetsQuery, + UploadAssetForm, +} from "./ports/studio-asset-gateway.ts"; +import type { + StudioGateway, + CatalogQuery, + ListDocumentsQuery, + ListPublicationsQuery, +} from "./ports/studio-gateway.ts"; +import { isStudioGatewayError } from "./ports/studio-gateway-error.ts"; +import type { + Asset, + AssetDetail, + AssetPage, + CatalogPage, + CreateDocumentInput, + CreatePreviewCommand, + DocumentPage, + PreviewDetail, + PublicationPage, + PublicationSnapshot, + PublicPreview, + PublishDocumentCommand, + PublishResult, + SaveDocumentCommand, + StudioDashboard, + UnpublishCommand, + UpdateAssetCommand, + ValidationReport, + ValidateDocumentCommand, + WorkingCopy, + WorkingCopyDetail, +} from "../contracts/studio/contract.ts"; +import type { + CreateDraftResponse, + DecisionResponse, + HomeFocusRequest, + HomeFocusResponse, + ProjectActivityRequest, + ProjectActivityResponse, + ProjectEditResponse, + ProjectIndexPage, + ProjectUpdateRequest, + PublishResponse, + QuestionIndexPage, + ReleaseEditResponse, + ReleaseIndexPage, + ReleaseUpdateRequest, + TopicEdit, + TopicVariantEdit, + UpdateProjectActivityRequest, +} from "../contracts/management/contract.ts"; + +export type StudioQueryContext = Readonly<{ signal?: AbortSignal }>; +export type StudioCommandContext = Readonly<{ + signal?: AbortSignal; + idempotencyKey: string; +}>; + +export type StudioWorkspaceQueries = Readonly<{ + getDashboard(context?: StudioQueryContext): Promise; + listDocuments(query: ListDocumentsQuery, context?: StudioQueryContext): Promise; + listPublications(query: ListPublicationsQuery, context?: StudioQueryContext): Promise; + getPublicationSnapshot(publicationEventId: string, context?: StudioQueryContext): Promise; + getCatalog(query: CatalogQuery, context?: StudioQueryContext): Promise; +}>; + +export type StudioWorkspaceCommands = Readonly<{ + createDocument(input: CreateDocumentInput, context: StudioCommandContext): Promise; + unpublishPublication(publicationId: string, command: UnpublishCommand, context: StudioCommandContext): Promise; +}>; + +export type StudioDocumentQueries = Readonly<{ + getDocument(documentId: string, context?: StudioQueryContext): Promise; + getCurrentPreview(documentId: string, context?: StudioQueryContext): Promise; +}>; + +export type StudioDocumentCommands = Readonly<{ + saveDocument(documentId: string, command: SaveDocumentCommand, context: StudioCommandContext): Promise; + validateDocument(documentId: string, command: ValidateDocumentCommand, context: StudioCommandContext): Promise; + createPreview(documentId: string, command: CreatePreviewCommand, context: StudioCommandContext): Promise; + publishDocument(documentId: string, command: PublishDocumentCommand, context: StudioCommandContext): Promise; +}>; + +export type StudioAssetQueries = Readonly<{ + listAssets(query: ListAssetsQuery, context?: StudioQueryContext): Promise; + getAsset(assetId: string, context?: StudioQueryContext): Promise; +}>; + +export type StudioAssetCommands = Readonly<{ + uploadAsset(form: UploadAssetForm, context: StudioCommandContext): Promise; + updateAssetMetadata(assetId: string, command: UpdateAssetCommand, context: StudioCommandContext): Promise; + deleteAsset(assetId: string, context: StudioCommandContext): Promise; +}>; + +export type StudioManagementQueries = Readonly<{ + listTopics(context?: StudioQueryContext): Promise; + listTopicVariants(topicId: string, context?: StudioQueryContext): Promise; + listProjects(page?: number, size?: number, context?: StudioQueryContext): Promise; + listQuestions(page?: number, size?: number, context?: StudioQueryContext): Promise; + listProjectDecisions(projectId: string, context?: StudioQueryContext): Promise; + getProject(id: string, context?: StudioQueryContext): Promise; + listProjectActivities(id: string, context?: StudioQueryContext): Promise; + getHomeFocus(context?: StudioQueryContext): Promise; + listReleases(page?: number, size?: number, context?: StudioQueryContext): Promise; + getRelease(id: string, context?: StudioQueryContext): Promise; +}>; + +export type StudioManagementCommands = Readonly<{ + createTopic(input: TopicEdit, context: StudioCommandContext): Promise; + updateTopic(id: string, body: TopicEdit, context: StudioCommandContext): Promise; + deleteTopic(id: string, expectedVersion: number, context: StudioCommandContext): Promise; + createTopicVariant(topicId: string, body: TopicVariantEdit, context: StudioCommandContext): Promise; + updateTopicVariant(topicId: string, variantId: string, body: TopicVariantEdit, context: StudioCommandContext): Promise; + deleteTopicVariant(topicId: string, variantId: string, expectedVersion: number, context: StudioCommandContext): Promise; + createProject(title: string, context: StudioCommandContext): Promise; + updateProject(id: string, body: ProjectUpdateRequest, context: StudioCommandContext): Promise; + deleteProject(id: string, expectedVersion: number, context: StudioCommandContext): Promise; + publishProject(id: string, expectedVersion: number, visibility: "PUBLIC" | "UNLISTED" | undefined, context: StudioCommandContext): Promise; + unpublishProject(id: string, expectedVersion: number, context: StudioCommandContext): Promise; + createProjectActivity(id: string, body: ProjectActivityRequest, context: StudioCommandContext): Promise; + updateProjectActivity(id: string, activityId: string, body: UpdateProjectActivityRequest, context: StudioCommandContext): Promise; + deleteProjectActivity(id: string, activityId: string, expectedVersion: number, context: StudioCommandContext): Promise; + updateHomeFocus(body: HomeFocusRequest, context: StudioCommandContext): Promise; + createRelease(title: string, context: StudioCommandContext): Promise; + updateRelease(id: string, body: ReleaseUpdateRequest, context: StudioCommandContext): Promise; + deleteRelease(id: string, expectedVersion: number, context: StudioCommandContext): Promise; + publishRelease(id: string, expectedVersion: number, context: StudioCommandContext): Promise; + archiveRelease(id: string, expectedVersion: number, context: StudioCommandContext): Promise; + deleteDocument(kind: DeletableDocumentKind, id: string, expectedVersion: number, context: StudioCommandContext): Promise; + deleteDecision(projectId: string, decisionId: string, expectedVersion: number, context: StudioCommandContext): Promise; +}>; + +export type TechLogStudioApplication = Readonly<{ + workspaceQueries: StudioWorkspaceQueries; + workspaceCommands: StudioWorkspaceCommands; + documentQueries: StudioDocumentQueries; + documentCommands: StudioDocumentCommands; + assetQueries: StudioAssetQueries; + assetCommands: StudioAssetCommands; + managementQueries: StudioManagementQueries; + managementCommands: StudioManagementCommands; +}>; + +type TechLogStudioApplicationDependencies = Readonly<{ + studio: StudioGateway; + assets: StudioAssetGateway; + management: ManagementGateway; +}>; + +export function createTechLogStudioApplication({ + studio, + assets, + management, +}: TechLogStudioApplicationDependencies): TechLogStudioApplication { + return Object.freeze({ + workspaceQueries: Object.freeze({ + getDashboard: (context?: StudioQueryContext) => studio.getDashboard(context), + listDocuments: (query: ListDocumentsQuery, context?: StudioQueryContext) => studio.listDocuments(query, context), + listPublications: (query: ListPublicationsQuery, context?: StudioQueryContext) => studio.listPublications(query, context), + getPublicationSnapshot: (id: string, context?: StudioQueryContext) => studio.getPublicationSnapshot(id, context), + getCatalog: (query: CatalogQuery, context?: StudioQueryContext) => studio.getCatalog(query, context), + }), + workspaceCommands: Object.freeze({ + createDocument: (input: CreateDocumentInput, context: StudioCommandContext) => studio.createDocument(input, context), + unpublishPublication: (id: string, command: UnpublishCommand, context: StudioCommandContext) => studio.unpublishPublication(id, command, context), + }), + documentQueries: Object.freeze({ + getDocument: (id: string, context?: StudioQueryContext) => studio.getDocument(id, context), + getCurrentPreview: (id: string, context?: StudioQueryContext) => studio.getCurrentPreview(id, context), + }), + documentCommands: Object.freeze({ + saveDocument: (id: string, command: SaveDocumentCommand, context: StudioCommandContext) => studio.saveDocument(id, command, context), + validateDocument: (id: string, command: ValidateDocumentCommand, context: StudioCommandContext) => studio.validateDocument(id, command, context), + createPreview: (id: string, command: CreatePreviewCommand, context: StudioCommandContext) => studio.createPreview(id, command, context), + publishDocument: (id: string, command: PublishDocumentCommand, context: StudioCommandContext) => studio.publishDocument(id, command, context), + }), + assetQueries: Object.freeze({ + listAssets: (query: ListAssetsQuery, context?: StudioQueryContext) => assets.listAssets(query, context), + getAsset: (id: string, context?: StudioQueryContext) => assets.getAsset(id, context), + }), + assetCommands: Object.freeze({ + uploadAsset: (form: UploadAssetForm, context: StudioCommandContext) => assets.uploadAsset(form, context), + updateAssetMetadata: (id: string, command: UpdateAssetCommand, context: StudioCommandContext) => assets.updateAssetMetadata(id, command, context), + deleteAsset: (id: string, context: StudioCommandContext) => assets.deleteAsset(id, context), + }), + managementQueries: Object.freeze({ + listTopics: (context?: StudioQueryContext) => management.listTopics(context), + listTopicVariants: (topicId: string, context?: StudioQueryContext) => management.listTopicVariants(topicId, context), + listProjects: (page?: number, size?: number, context?: StudioQueryContext) => management.listProjects(page, size, context), + listQuestions: (page?: number, size?: number, context?: StudioQueryContext) => management.listQuestions(page, size, context), + listProjectDecisions: (projectId: string, context?: StudioQueryContext) => management.listProjectDecisions(projectId, context), + getProject: (id: string, context?: StudioQueryContext) => management.getProject(id, context), + listProjectActivities: (id: string, context?: StudioQueryContext) => management.listProjectActivities(id, context), + getHomeFocus: (context?: StudioQueryContext) => management.getHomeFocus(context), + listReleases: (page?: number, size?: number, context?: StudioQueryContext) => management.listReleases(page, size, context), + getRelease: (id: string, context?: StudioQueryContext) => management.getRelease(id, context), + }), + managementCommands: Object.freeze({ + createTopic: (input: TopicEdit, context: StudioCommandContext) => management.createTopic(input, context), + updateTopic: (id: string, body: TopicEdit, context: StudioCommandContext) => management.updateTopic(id, body, context), + deleteTopic: (id: string, version: number, context: StudioCommandContext) => management.deleteTopic(id, version, context), + createTopicVariant: (topicId: string, body: TopicVariantEdit, context: StudioCommandContext) => management.createTopicVariant(topicId, body, context), + updateTopicVariant: (topicId: string, variantId: string, body: TopicVariantEdit, context: StudioCommandContext) => management.updateTopicVariant(topicId, variantId, body, context), + deleteTopicVariant: (topicId: string, variantId: string, version: number, context: StudioCommandContext) => management.deleteTopicVariant(topicId, variantId, version, context), + createProject: (title: string, context: StudioCommandContext) => management.createProject(title, context), + updateProject: (id: string, body: ProjectUpdateRequest, context: StudioCommandContext) => management.updateProject(id, body, context), + deleteProject: (id: string, version: number, context: StudioCommandContext) => management.deleteProject(id, version, context), + publishProject: (id: string, version: number, visibility: "PUBLIC" | "UNLISTED" | undefined, context: StudioCommandContext) => management.publishProject(id, version, visibility, context), + unpublishProject: (id: string, version: number, context: StudioCommandContext) => management.unpublishProject(id, version, context), + createProjectActivity: (id: string, body: ProjectActivityRequest, context: StudioCommandContext) => management.createProjectActivity(id, body, context), + updateProjectActivity: (id: string, activityId: string, body: UpdateProjectActivityRequest, context: StudioCommandContext) => management.updateProjectActivity(id, activityId, body, context), + deleteProjectActivity: (id: string, activityId: string, version: number, context: StudioCommandContext) => management.deleteProjectActivity(id, activityId, version, context), + updateHomeFocus: (body: HomeFocusRequest, context: StudioCommandContext) => management.updateHomeFocus(body, context), + createRelease: (title: string, context: StudioCommandContext) => management.createRelease(title, context), + updateRelease: (id: string, body: ReleaseUpdateRequest, context: StudioCommandContext) => management.updateRelease(id, body, context), + deleteRelease: (id: string, version: number, context: StudioCommandContext) => management.deleteRelease(id, version, context), + publishRelease: (id: string, version: number, context: StudioCommandContext) => management.publishRelease(id, version, context), + archiveRelease: (id: string, version: number, context: StudioCommandContext) => management.archiveRelease(id, version, context), + deleteDocument: (kind: DeletableDocumentKind, id: string, version: number, context: StudioCommandContext) => management.deleteDocument(kind, id, version, context), + deleteDecision: (projectId: string, decisionId: string, version: number, context: StudioCommandContext) => management.deleteDecision(projectId, decisionId, version, context), + }), + }); +} + +export type { + CatalogQuery, + DeletableDocumentKind, + ListAssetsQuery, + ListDocumentsQuery, + ListPublicationsQuery, + UploadAssetForm, +}; + +export const isStudioApplicationError = isStudioGatewayError; +export const StudioManagementError = ManagementGatewayError; diff --git a/src/features/tech-log/application/tech-log-feature-input.ts b/src/features/tech-log/application/tech-log-feature-input.ts index fadb72c..e471002 100644 --- a/src/features/tech-log/application/tech-log-feature-input.ts +++ b/src/features/tech-log/application/tech-log-feature-input.ts @@ -1,17 +1,11 @@ import type { PublicContentQueries } from "./ports/public-content-queries.ts"; -import type { StudioAssetGateway } from "./ports/studio-asset-gateway.ts"; -import type { ManagementGateway } from "./ports/management-gateway.ts"; -import type { StudioGateway } from "./ports/studio-gateway.ts"; +import type { TechLogStudioApplication } from "./studio-application.ts"; export const TECH_LOG_FEATURE_ID = "tech-log" as const; export type TechLogFeatureInput = Readonly<{ publicContent: PublicContentQueries; - createStudioGateway(): StudioGateway; - createStudioAssetGateway(): StudioAssetGateway; - // 주제·프로젝트 관리. MOCK 대응물이 없다 — 이 표면은 백엔드가 없으면 존재할 이유가 없고, - // 픽스처를 만들면 실제로는 못 만드는 주제를 화면이 보여주게 된다. - createManagementGateway(): ManagementGateway; + createStudioApplication(): TechLogStudioApplication; }>; declare module "../../../application/ports/in/application-api.ts" { diff --git a/src/features/tech-log/contracts/management/canonical-source.json b/src/features/tech-log/contracts/management/canonical-source.json index 921f238..6710fbc 100644 --- a/src/features/tech-log/contracts/management/canonical-source.json +++ b/src/features/tech-log/contracts/management/canonical-source.json @@ -1,7 +1,7 @@ { "packageId": "@tech-log/management-contract", "version": "1.0.0", - "digest": "sha256:0c226600c45b06433480a8a2ef3d812480dce3850c333bfcab5f626143ce77ea", + "digest": "sha256:6036a41879ccf161ba3b7db184be3897684c19e8890f3446460293f1f1f7ab3d", "sourceRevision": "a0dac96", "operationIds": [ "createCaseDraft", diff --git a/src/features/tech-log/contracts/management/contract.ts b/src/features/tech-log/contracts/management/contract.ts index 5f916bc..bc87ca7 100644 --- a/src/features/tech-log/contracts/management/contract.ts +++ b/src/features/tech-log/contracts/management/contract.ts @@ -23,3 +23,5 @@ export type HomeFocusResponse = Schemas["HomeFocusResponse"]; export type ProjectActivityRequest = Schemas["ProjectActivityRequest"]; export type UpdateProjectActivityRequest = Schemas["UpdateProjectActivityRequest"]; export type ProjectActivityResponse = Schemas["ProjectActivityResponse"]; +export type ReleaseChangeType = ReleaseUpdateRequest["changeTypes"][number]; +export type ProjectActivityType = ProjectActivityRequest["activityType"]; diff --git a/src/features/tech-log/contracts/management/generated.ts b/src/features/tech-log/contracts/management/generated.ts index 4a453cb..fda60d0 100644 --- a/src/features/tech-log/contracts/management/generated.ts +++ b/src/features/tech-log/contracts/management/generated.ts @@ -1484,7 +1484,7 @@ export interface components { summary: string; /** Format: date */ releasedOn?: string; - changeTypes: string[]; + changeTypes: ("FEATURE" | "FIX" | "REFACTOR" | "DOCS" | "INFRA" | "BREAKING")[]; reasonMarkdown?: string; changesMarkdown: string; userImpactMarkdown?: string; @@ -1626,6 +1626,8 @@ export interface components { * 맞출 방법이 없다 — 홈 편집기가 고른 프로젝트의 질문만 거르지 못한 이유가 그것이다. * */ slug?: string; + /** @description Taxonomy 구조 화면이 상세 조회 없이 project-topic 관계를 그리기 위한 목록 projection. */ + topicIds: string[]; phase: string; workflowStatus: string; targetVisibility: string; @@ -1733,7 +1735,8 @@ export interface components { ProjectActivityRequest: { /** Format: int64 */ expectedProjectVersion: number; - activityType: string; + /** @enum {string} */ + activityType: "PHASE_CHANGED" | "QUESTION_OPENED" | "QUESTION_RESOLVED" | "DECISION_ACCEPTED" | "CASE_PUBLISHED" | "REFERENCE_PUBLISHED" | "MILESTONE_REACHED" | "PROJECT_PAUSED" | "PROJECT_RESUMED"; title: string; summary?: string; /** @enum {string} */ @@ -1749,7 +1752,8 @@ export interface components { id: string; /** Format: uuid */ projectId: string; - activityType: string; + /** @enum {string} */ + activityType: "PHASE_CHANGED" | "QUESTION_OPENED" | "QUESTION_RESOLVED" | "DECISION_ACCEPTED" | "CASE_PUBLISHED" | "REFERENCE_PUBLISHED" | "MILESTONE_REACHED" | "PROJECT_PAUSED" | "PROJECT_RESUMED"; title: string; summary?: string; visibility: string; diff --git a/src/features/tech-log/contracts/management/management-api.openapi.yaml b/src/features/tech-log/contracts/management/management-api.openapi.yaml index d053182..8c13bc2 100644 --- a/src/features/tech-log/contracts/management/management-api.openapi.yaml +++ b/src/features/tech-log/contracts/management/management-api.openapi.yaml @@ -6958,6 +6958,13 @@ components: type: array items: type: string + enum: + - FEATURE + - FIX + - REFACTOR + - DOCS + - INFRA + - BREAKING reasonMarkdown: type: string changesMarkdown: @@ -7260,6 +7267,7 @@ components: required: - id - name + - topicIds - phase - workflowStatus - targetVisibility @@ -7278,6 +7286,12 @@ components: 이 프로젝트의 공개 이름. 다른 목록이 프로젝트를 가리킬 때 쓰는 것이 id 가 아니라 이 값이라(`ProjectSummary` 에는 id 가 없다), 목록 행이 이것을 싣지 않으면 두 목록을 맞출 방법이 없다 — 홈 편집기가 고른 프로젝트의 질문만 거르지 못한 이유가 그것이다. + topicIds: + type: array + description: Taxonomy 구조 화면이 상세 조회 없이 project-topic 관계를 그리기 위한 목록 projection. + items: + type: string + format: uuid phase: type: string workflowStatus: @@ -7536,6 +7550,16 @@ components: format: int64 activityType: type: string + enum: + - PHASE_CHANGED + - QUESTION_OPENED + - QUESTION_RESOLVED + - DECISION_ACCEPTED + - CASE_PUBLISHED + - REFERENCE_PUBLISHED + - MILESTONE_REACHED + - PROJECT_PAUSED + - PROJECT_RESUMED title: type: string maxLength: 180 @@ -7575,6 +7599,16 @@ components: format: uuid activityType: type: string + enum: + - PHASE_CHANGED + - QUESTION_OPENED + - QUESTION_RESOLVED + - DECISION_ACCEPTED + - CASE_PUBLISHED + - REFERENCE_PUBLISHED + - MILESTONE_REACHED + - PROJECT_PAUSED + - PROJECT_RESUMED title: type: string summary: diff --git a/src/features/tech-log/contracts/tech-log-management-contract-contribution.ts b/src/features/tech-log/contracts/tech-log-management-contract-contribution.ts index f01f5ed..e95fcfe 100644 --- a/src/features/tech-log/contracts/tech-log-management-contract-contribution.ts +++ b/src/features/tech-log/contracts/tech-log-management-contract-contribution.ts @@ -13,6 +13,14 @@ import { } from "./tech-log-studio-contract-contribution.ts"; import { TECH_LOG_STUDIO_SESSION_AUTH_PROFILE_ID } from "../adapters/http/studio-session-credentials.ts"; + +type NamedInstalledHttpContract = + InstalledHttpContract & + Readonly<{ + contract: InstalledHttpContract["contract"] & + Readonly<{ operationId: OperationId }>; + }>; + type PathValues = Readonly>; type QueryEntries = readonly (readonly [string, string])[]; @@ -60,13 +68,13 @@ const COMMAND_EFFECT: CommandEffectDescriptor = Object.freeze({ * 공유한다. 부트스트랩 프로필은 쓰지 않는다: CSRF 토큰을 발급하는 것은 `getStudioSession` * 하나뿐이고, 이 표면은 그 뒤에만 호출된다. */ -function readOperation( - operationId: string, +function readOperation( + operationId: OperationId, pathTemplate: string, responseByteLimit: number, project: (input: never) => Readonly<{ pathValues: PathValues; queryEntries: QueryEntries }> = () => Object.freeze({ pathValues: NO_PATH, queryEntries: NO_QUERY }), -): InstalledHttpContract { +): NamedInstalledHttpContract { return Object.freeze({ contract: Object.freeze({ operationId, @@ -95,7 +103,7 @@ function readOperation( authProfileId: TECH_LOG_STUDIO_SESSION_AUTH_PROFILE_ID, diagnosticsOperation: `techLog.management.${operationId}`, }), - }) as InstalledHttpContract; + }) as NamedInstalledHttpContract; } /** @@ -103,8 +111,8 @@ function readOperation( * 이 맡는다. 그래서 `NOT_IDEMPOTENT` 가 아니라 재시도 예산 0 으로 둔다: 응답을 못 본 재시도가 * 두 번째 생성을 만들 수 있는 표면이다. */ -function writeOperation( - operationId: string, +function writeOperation( + operationId: OperationId, method: "POST" | "PUT" | "DELETE", pathTemplate: string, options: Readonly<{ @@ -118,7 +126,7 @@ function writeOperation( queryEntries: QueryEntries; body: unknown; }>, -): InstalledHttpContract { +): NamedInstalledHttpContract { return Object.freeze({ contract: Object.freeze({ operationId, @@ -155,7 +163,7 @@ function writeOperation( }), // read 쪽과 달리 여기서만 unknown 을 거친다: `emptyBodyStatuses` 유무로 responseBody 가 // 갈리는 삼항이 union 타입을 만들어, 컴파일러가 리터럴을 대상 타입과 겹친다고 보지 않는다. - }) as unknown as InstalledHttpContract; + }) as unknown as NamedInstalledHttpContract; } const byId = (input: never) => { @@ -168,7 +176,7 @@ const P = "/api/v1/studio/projects"; const R = "/api/v1/studio/releases"; const D = "/api/v1/studio"; -const HTTP_CONTRACTS = Object.freeze([ +export const TECH_LOG_MANAGEMENT_HTTP_CONTRACTS = Object.freeze([ readOperation("listStudioTopics", T, 131_072), writeOperation( "createTopic", @@ -625,10 +633,10 @@ const HTTP_CONTRACTS = Object.freeze([ }); }, ), -]); +] as const); export const TECH_LOG_MANAGEMENT_OPERATION_IDS = Object.freeze( - HTTP_CONTRACTS.map((entry) => entry.contract.operationId), + TECH_LOG_MANAGEMENT_HTTP_CONTRACTS.map((entry) => entry.contract.operationId), ); export const TECH_LOG_MANAGEMENT_CONTRIBUTION: InstalledContractContribution = Object.freeze({ @@ -644,6 +652,6 @@ export const TECH_LOG_MANAGEMENT_CONTRIBUTION: InstalledContractContribution = O sourceRevision: canonicalSource.sourceRevision, }), }), - http: HTTP_CONTRACTS, + http: TECH_LOG_MANAGEMENT_HTTP_CONTRACTS, events: Object.freeze([]), }); diff --git a/src/features/tech-log/contracts/tech-log-message-catalog.ts b/src/features/tech-log/contracts/tech-log-message-catalog.ts index a1f7488..7854856 100644 --- a/src/features/tech-log/contracts/tech-log-message-catalog.ts +++ b/src/features/tech-log/contracts/tech-log-message-catalog.ts @@ -7,18 +7,560 @@ export type TechLogRouteMessageKey = | `route.${TechLogRouteId}.title` | `route.${TechLogRouteId}.navigation`; -function createCatalog(): Readonly> { +const EN_ROUTE_COPY = Object.freeze({ + TECH_LOG_HOME: { title: "TechLog" }, + TECH_LOG_EXPLORE: { title: "Explore", navigation: "Explore" }, + TECH_LOG_EXPLORE_KIND: { title: "Explore by type" }, + TECH_LOG_CASE: { title: "Case" }, + TECH_LOG_REFERENCE: { title: "Reference" }, + TECH_LOG_CONCEPT: { title: "Concept" }, + TECH_LOG_SETUP: { title: "Setup" }, + TECH_LOG_QUESTION: { title: "Open Question" }, + TECH_LOG_TOPICS: { title: "Topics", navigation: "Topics" }, + TECH_LOG_TOPIC: { title: "Topic" }, + TECH_LOG_TOPIC_VARIANT: { title: "Topic" }, + TECH_LOG_PROJECTS: { title: "Projects", navigation: "Projects" }, + TECH_LOG_PROJECT: { title: "Project" }, + TECH_LOG_PROJECT_RECORDS: { title: "Project records" }, + TECH_LOG_PROJECT_DECISIONS: { title: "Project decisions" }, + TECH_LOG_PROJECT_ACTIVITY: { title: "Project activity" }, + TECH_LOG_RELEASES: { title: "Release notes" }, + TECH_LOG_RELEASE: { title: "Release notes" }, + TECH_LOG_PROFILE: { title: "Profile", navigation: "Profile" }, + TECH_LOG_SEARCH: { title: "Search" }, + TECH_LOG_STUDIO_HOME: { title: "TechLog Studio" }, + TECH_LOG_STUDIO_DOCUMENTS: { + title: "Working copies", + navigation: "Working copies", + }, + TECH_LOG_STUDIO_DOCUMENT_NEW: { + title: "New document", + navigation: "New document", + }, + TECH_LOG_STUDIO_DOCUMENT_EDIT: { title: "Edit document" }, + TECH_LOG_STUDIO_DOCUMENT_VALIDATION: { title: "Validate document" }, + TECH_LOG_STUDIO_DOCUMENT_PREVIEW: { title: "Public Preview" }, + TECH_LOG_STUDIO_DOCUMENT_PUBLISH: { title: "Publish" }, + TECH_LOG_STUDIO_PUBLICATIONS: { + title: "Publication history", + navigation: "Publication history", + }, + TECH_LOG_STUDIO_PUBLICATION_PREVIEW: { title: "Publication Snapshot" }, + TECH_LOG_STUDIO_ASSETS: { title: "Asset", navigation: "Asset" }, + TECH_LOG_STUDIO_TAXONOMY: { + title: "Topics and projects", + navigation: "Topics · Projects", + }, + TECH_LOG_STUDIO_PROJECT_EDIT: { title: "Edit project" }, + TECH_LOG_STUDIO_TOPIC_EDIT: { title: "Edit topic" }, + TECH_LOG_STUDIO_RELEASES: { title: "Releases", navigation: "Releases" }, + TECH_LOG_STUDIO_RELEASE_EDIT: { title: "Edit release" }, + TECH_LOG_STUDIO_NOT_FOUND: { title: "Studio page not found" }, + NOT_FOUND: { title: "Page not found" }, +} as const satisfies Readonly< + Record> +>); + +function createRouteCatalog( + locale: "ko-KR" | "en-US", +): Readonly> { return Object.freeze( Object.fromEntries( - Object.values(TECH_LOG_ROUTE_REGISTRY).flatMap((definition) => [ - [`route.${definition.routeId}.title`, definition.title], - [`route.${definition.routeId}.navigation`, definition.title], - ]), + Object.values(TECH_LOG_ROUTE_REGISTRY).flatMap((definition) => { + const routeId = definition.routeId as TechLogRouteId; + const localized: Readonly<{ + title: string; + navigation?: string; + }> | null = locale === "en-US" ? EN_ROUTE_COPY[routeId] : null; + const title = localized?.title ?? definition.title; + const navigation = + localized?.navigation ?? + definition.navigationLabel ?? + title; + return [ + [`route.${routeId}.title`, title], + [`route.${routeId}.navigation`, navigation], + ]; + }), ), ) as Readonly>; } +/* + * Product copy that is behavioral rather than editorial lives in the feature + * catalog. Long-form explanations remain next to the screen that owns them. + */ +const KO_UI_MESSAGES = Object.freeze({ + "techLog.public.home": "TechLog 홈", + "techLog.public.primaryNavigation": "주요 탐색", + "techLog.public.mobileNavigation": "모바일 주요 탐색", + "techLog.action.retry": "다시 시도", + "techLog.action.search": "검색", + "techLog.action.save": "저장", + "techLog.action.saving": "저장 중…", + "techLog.action.savingBeforeNavigate": "저장 중", + "techLog.action.loading": "불러오는 중", + "techLog.action.publish": "게시", + "techLog.action.republish": "다시 게시", + "techLog.action.publishing": "게시 중…", + "techLog.action.processing": "처리 중", + "techLog.action.delete": "삭제", + "techLog.action.moveUp": "위로", + "techLog.action.moveDown": "아래로", + "techLog.action.close": "닫기", + "techLog.action.apply": "적용", + "techLog.action.insert": "삽입", + "techLog.action.unpublish": "게시 취소", + "techLog.action.viewLarge": "크게 보기", + "techLog.action.resetFilters": "필터 초기화", + "techLog.action.archive": "보관", + "techLog.state.documentNotFound": "작업본을 찾을 수 없습니다", + "techLog.state.topicNotFound": "주제를 찾을 수 없습니다", + "techLog.state.validationLoadFailed": "검증 화면을 불러오지 못했습니다", + "techLog.state.publicPreviewLoadFailed": "Public Preview를 불러오지 못했습니다", + "techLog.state.documentLoadFailed": "문서를 불러오지 못했습니다", + "techLog.state.publicationLoadFailed": "게시 정보를 불러오지 못했습니다", + "techLog.state.assetListLoadFailed": "Asset 목록을 불러오지 못했습니다", + "techLog.state.assetListLoading": "Asset 목록을 불러오는 중입니다.", + "techLog.state.projectLoading": "프로젝트를 불러오는 중입니다.", + "techLog.state.topicLoading": "주제를 불러오는 중입니다.", + "techLog.state.publicationLoading": "게시 준비 정보를 불러오는 중입니다.", + "techLog.state.validationLoading": "검증 정보를 불러오는 중입니다.", + "techLog.state.publicPreviewLoading": "Public Preview를 불러오는 중입니다.", + "techLog.state.publicationListLoading": "게시 기록을 불러오는 중입니다.", + "techLog.state.publicationListLoadFailed": "게시 기록을 불러오지 못했습니다", + "techLog.state.assetNextLoadFailed": "다음 Asset을 불러오지 못했습니다.", + "techLog.state.assetDetailLoadFailed": "Asset 상세를 불러오지 못했습니다.", + "techLog.state.topicLoadFailed": "주제를 불러오지 못했습니다.", + "techLog.state.taxonomyLoadFailed": "주제와 프로젝트를 불러오지 못했습니다.", + "techLog.state.projectLoadFailed": "프로젝트를 불러오지 못했습니다.", + "techLog.failure.archiveFailed": "보관하지 못했습니다.", + "techLog.failure.deleteFailed": "삭제하지 못했습니다.", + "techLog.failure.saveFailed": "저장하지 못했습니다.", + "techLog.failure.variantSaveFailed": "축을 저장하지 못했습니다.", + "techLog.failure.variantDeleteFailed": "축을 삭제하지 못했습니다.", + "techLog.failure.topicDeleteFailed": "주제를 삭제하지 못했습니다.", + "techLog.failure.projectDeleteFailed": "프로젝트를 삭제하지 못했습니다.", + "techLog.failure.projectUnpublishFailed": "프로젝트를 비공개로 되돌리지 못했습니다.", + "techLog.failure.projectPublishFailed": "프로젝트를 게시하지 못했습니다.", + "techLog.action.deleteBlock": "블록 삭제", + "techLog.action.restart": "다시 시작", + "techLog.action.addVersion": "+ 버전 추가", + "techLog.action.addBlock": "+ 블록 추가", + "techLog.action.createWorkingCopy": "작업본 만들기", + "techLog.action.insertAsset": "본문에 자료 넣기", + "techLog.action.saveHome": "홈 설정 저장", + "techLog.action.upload": "업로드", + "techLog.action.uploading": "업로드 중", + "techLog.action.add": "추가", + "techLog.action.addTopic": "주제 추가", + "techLog.action.addProject": "프로젝트 추가", + "techLog.action.more": "더 보기", + "techLog.action.saveAltText": "대체 텍스트 저장", + "techLog.action.makePublic": "공개", + "techLog.action.removeFromPublic": "공개에서 내리기", + "techLog.action.cancel": "취소", + "techLog.action.stay": "이 페이지에 머무르기", + "techLog.action.discard": "변경 버리기", + "techLog.action.saveThenNavigate": "저장 후 이동", + "techLog.action.expand": "펼치기", + "techLog.action.collapse": "접기", + "techLog.action.validate": "검증", + "techLog.action.revalidate": "다시 검증", + "techLog.action.validating": "검증 중…", + "techLog.action.createPreview": "Preview 만들기", + "techLog.action.recreatePreview": "Preview 다시 만들기", + "techLog.action.creating": "생성 중…", + "techLog.action.keepPublished": "계속 게시", + "techLog.action.confirmUnpublish": "게시 취소 확인", + "techLog.action.addOption": "+ 선택지", + "techLog.action.addCriterion": "+ 판단 기준", + "techLog.state.studioNotFound": "Studio 화면을 찾을 수 없습니다", + "techLog.state.studioLoadFailed": "Studio 화면을 불러오지 못했습니다", + "techLog.state.homeLoadFailed": "홈 설정을 불러오지 못했습니다", + "techLog.state.homeLoading": "홈 설정을 불러오는 중입니다.", + "techLog.state.homePreparing": "홈 설정을 준비하고 있습니다.", + "techLog.state.openQuestionsLoadFailed": "열린 질문을 불러오지 못했습니다. 새로고침해 주세요.", + "techLog.state.decisionsLoadFailed": "결정을 불러오지 못했습니다. 새로고침해 주세요.", + "techLog.state.releaseLoadFailed": "릴리즈를 불러오지 못했습니다", + "techLog.state.releaseLoading": "릴리즈를 불러오는 중입니다.", + "techLog.state.documentListLoadFailed": "작업본을 불러오지 못했습니다.", + "techLog.state.documentListLoading": "작업본을 불러오는 중입니다.", + "techLog.state.dashboardLoadFailed": "작업 흐름을 불러오지 못했습니다", + "techLog.state.dashboardLoading": "Studio 요약을 불러오는 중입니다.", + "techLog.state.publicationSnapshotLoading": "게시 Snapshot을 불러오는 중입니다.", + "techLog.state.publicationRecordNotFound": "게시 기록을 찾을 수 없습니다", + "techLog.state.publicationSnapshotLoadFailed": "게시 Snapshot을 불러오지 못했습니다", + "techLog.state.emptyPublicationList": "조건에 맞는 게시 기록이 없습니다", + "techLog.state.emptySearchResult": "검색 결과가 없습니다.", + "techLog.state.taxonomyLoading": "주제와 프로젝트를 불러오는 중입니다.", + "techLog.state.emptyDocumentList": "조건에 맞는 작업본이 없습니다", + "techLog.state.emptyDocumentListHint": "검색어 또는 필터를 바꾸거나 새 문서를 만드세요.", + "techLog.state.emptyAssetSearch": "조건에 맞는 Asset이 없습니다", + "techLog.state.emptyAssetSearchHint": "검색어를 바꾸거나 비우면 전체 Asset을 다시 볼 수 있습니다.", + "techLog.state.emptyAssetLibrary": "등록된 Asset이 없습니다", + "techLog.state.emptyAssetLibraryHint": "Case 편집 화면에서 Asset을 업로드하면 여기에서 관리할 수 있습니다.", + "techLog.state.emptyPublicationHistory": "아직 게시 기록이 없습니다.", + "techLog.state.emptyPublicationListHint": "검색어 또는 이벤트 필터를 바꿔 보세요.", + "techLog.studio.group.work": "작업", + "techLog.studio.group.structure": "구조", + "techLog.studio.group.assets": "자료", + "techLog.studio.group.publish": "게시", + "techLog.studio.publicSite": "공개 사이트 보기", + "techLog.studio.primaryNavigation": "Studio 주 탐색", + "techLog.studio.mobileNavigation": "Studio 모바일 탐색", + "techLog.studio.menuOpen": "Studio 메뉴 열기", + "techLog.studio.menuClose": "Studio 메뉴 닫기", + "techLog.editor.status.clean": "저장됨", + "techLog.editor.status.dirty": "저장되지 않음", + "techLog.editor.status.saving": "저장 중…", + "techLog.editor.status.conflict": "저장 충돌", + "techLog.editor.statusLabel": "편집 상태", + "techLog.editor.workStatus": "작업 상태", + "techLog.failure.documentNotFound": "작업본을 찾을 수 없습니다.", + "techLog.failure.versionConflict": + "다른 변경이 먼저 저장되었습니다. 최신 버전을 다시 확인해 주세요.", + "techLog.failure.validationRejected": + "입력값을 확인한 뒤 다시 시도해 주세요.", + "techLog.failure.validationStale": + "저장 버전이 바뀌었습니다. 현재 버전으로 다시 검증해 주세요.", + "techLog.failure.previewStale": + "미리보기가 현재 저장 버전과 다릅니다. 다시 만들어 주세요.", + "techLog.failure.previewExpired": + "미리보기가 만료되었습니다. 다시 만들어 주세요.", + "techLog.failure.publicationConflict": + "게시 상태가 변경되었습니다. 최신 상태를 다시 확인해 주세요.", + "techLog.failure.studioUnavailable": "Studio가 잠시 응답하지 않습니다.", + "techLog.failure.assetInUse": "사용 중인 Asset은 삭제할 수 없습니다.", + "techLog.failure.duplicateInFlight": "같은 작업을 처리하고 있습니다.", + "techLog.public.error.pageLoadTitle": "페이지를 불러오지 못했습니다.", + "techLog.public.error.pageLoadHelp": "잠시 후 다시 시도해 주세요. 문제가 계속되면 아래 Trace ID를 함께 전달해 주세요.", + "techLog.action.exploreAllRecords": "모든 기록 탐색", + "techLog.state.latestLoadFailed": "최근 기록을 불러오지 못했습니다.", + "techLog.state.noPublishedRecords": "아직 공개된 기록이 없습니다.", + "techLog.action.clearSearch": "검색어 지우기", + "techLog.state.noMatchingPublicRecords": "일치하는 공개 기록이 없습니다.", + "techLog.action.backToExplore": "전체 탐색으로 돌아가기", + "techLog.action.browseProjects": "프로젝트 둘러보기", + "techLog.action.exploreRecords": "기록 탐색", + "techLog.state.noPublishedProjects": "아직 공개된 프로젝트가 없습니다.", + "techLog.state.noRegisteredTopics": "아직 등록한 주제가 없습니다.", + "techLog.state.noProjectPublishedRecords": "아직 이 프로젝트에서 공개한 기록이 없습니다.", + "techLog.state.noDecisions": "아직 확정한 결정이 없습니다.", + "techLog.state.noOpenQuestions": "아직 열린 질문도 없습니다. 이 프로젝트의 조사는 기록을 모으는 단계입니다.", + "techLog.state.noImpact": "남긴 영향이 없습니다.", + "techLog.state.noEvidence": "연결한 근거 기록이 없습니다.", + "techLog.state.noConclusion": "아직 정리한 결론이 없습니다. 아래 조사 지도가 지금까지 모은 기록을 보여 줍니다.", + "techLog.public.notFound": "페이지를 찾을 수 없습니다.", + "techLog.public.notFoundDetail": "요청한 공개 페이지가 없습니다.", + "techLog.action.changeLog": "변경 기록", + "techLog.public.releaseBreadcrumb": "변경 기록 경로", + "techLog.state.noPublishedReleases": "아직 공개된 릴리즈가 없습니다.", + "techLog.state.noPublishedTopics": "아직 공개된 주제가 없습니다.", + "techLog.state.noAssumptions": "현재 기록된 가정이 없습니다.", + "techLog.state.noUnknowns": "해결 과정에서 남은 미지수가 없습니다.", + "techLog.state.irreversible": "되돌릴 수 없습니다.", + "techLog.notice.published": "게시했습니다.", + "techLog.failure.saveRetry": "저장하지 못했습니다. 다시 시도해 주세요.", + "techLog.failure.saveBeforePublish": "게시 전에 변경사항을 저장하지 못했습니다.", + "techLog.failure.validationBeforePublish": "게시 전에 문서를 검증하지 못했습니다.", + "techLog.failure.previewBeforePublish": "게시 전에 Public Preview를 만들지 못했습니다.", + "techLog.failure.publishRetry": "게시하지 못했습니다. 다시 시도해 주세요.", + "techLog.state.editorPreparing": "문서 편집기를 준비하고 있습니다.", + "techLog.state.sessionDocumentMissing": "이 작업본은 현재 Studio 세션에 없습니다.", + "techLog.failure.publishFieldsRequired": "게시할 수 없습니다. 표시한 칸을 채워 주세요.", + "techLog.notice.homeFocusSaved": "홈에 표시할 항목을 저장했습니다.", + "techLog.action.savingPlain": "저장하는 중", + "techLog.action.creatingPlain": "만드는 중…", + "techLog.state.emptyOrderedText": "아직 입력한 항목이 없습니다.", + "techLog.state.projectTopicsEmpty": "아직 주제가 없습니다. 주제·프로젝트 화면에서 먼저 만듭니다.", + "techLog.notice.previewCreated": "현재 저장 버전의 Public Preview를 만들었습니다.", + "techLog.failure.previewRetry": "Public Preview를 만들지 못했습니다. 다시 시도해 주세요.", + "techLog.notice.unpublished": "게시를 취소했습니다.", + "techLog.failure.unpublishFailed": "게시를 취소하지 못했습니다.", + "techLog.notice.releaseUnpublished": "릴리즈를 공개에서 내렸습니다.", + "techLog.failure.releasePublishFields": "공개하지 못했습니다. 버전, 제목, 한 줄 요약, 변경 유형, 변경 내용, 검증, 공개일을 확인해 주세요.", + "techLog.failure.releaseUnpublishFailed": "공개에서 내리지 못했습니다.", + "techLog.notice.releaseDraftCreated": "릴리즈 {title} 초안을 만들었습니다. 목록에서 편집을 눌러 내용을 채웁니다.", + "techLog.notice.releaseDeleted": "릴리즈 {version} 을(를) 삭제했습니다.", + "techLog.action.adding": "추가 중…", + "techLog.state.releasesEmpty": "아직 릴리즈가 없습니다.", + "techLog.state.dashboardContinueEmpty": "이어서 작성할 문서가 없습니다.", + "techLog.state.dashboardValidateEmpty": "현재 검증할 문서가 없습니다.", + "techLog.state.dashboardReadyEmpty": "게시 준비가 끝난 문서가 없습니다.", + "techLog.state.groupedTopicsEmpty": "묶은 주제가 없습니다.", + "techLog.state.topicsCreateFirst": "아직 주제가 없습니다. 위에서 하나 만들어 주세요.", + "techLog.state.projectsEmpty": "아직 프로젝트가 없습니다.", + "techLog.action.addingPlain": "추가 중", + "techLog.action.unpublishing": "취소 처리 중…", + "techLog.state.validationClean": "오류와 경고가 없습니다.", + "techLog.notice.validationComplete": "저장된 문서 검증이 완료되었습니다.", + "techLog.failure.validationRetry": "검증하지 못했습니다. 다시 시도해 주세요.", + "techLog.state.validationRecordEmpty": "검증 기록이 없습니다", + "techLog.state.warningsEmpty": "확인할 경고가 없습니다.", + "techLog.notice.assetArchived": "보관했습니다.", + "techLog.notice.assetDeleted": "삭제했습니다.", + "techLog.notice.assetAltTextSaved": "대체 텍스트를 저장했습니다.", + "techLog.notice.topicSavedVersion": "주제를 버전 {version}으로 저장했습니다.", + "techLog.notice.itemAdded": "{title} 을(를) 추가했습니다.", + "techLog.notice.itemSaved": "{title} 을(를) 저장했습니다.", + "techLog.notice.itemDeleted": "{title} 을(를) 삭제했습니다.", + "techLog.notice.topicCreated": "주제 {name} 을(를) 만들었습니다.", + "techLog.notice.projectCreated": "프로젝트 {title} 을(를) 만들었습니다.", + "techLog.notice.topicDeleted": "주제 {name} 을(를) 삭제했습니다.", + "techLog.notice.projectDeleted": "프로젝트 {name} 을(를) 삭제했습니다.", + "techLog.notice.savedVersion": "버전 {version}으로 저장했습니다.", + "techLog.management.conflict": + "다른 변경이 먼저 반영되었습니다. 최신 상태를 다시 확인해 주세요.", + "techLog.management.notFound": "대상을 찾을 수 없습니다.", + "techLog.management.validationRejected": "입력값을 확인해 주세요.", + "techLog.management.authRequired": "Studio 로그인이 필요합니다.", + "techLog.management.forbidden": "이 작업을 수행할 권한이 없습니다.", + "techLog.management.serverFailure": + "관리 API와 통신하지 못했습니다. 다시 시도해 주세요.", +} as const); + +const EN_UI_MESSAGES = Object.freeze({ + "techLog.public.home": "TechLog home", + "techLog.public.primaryNavigation": "Primary navigation", + "techLog.public.mobileNavigation": "Mobile primary navigation", + "techLog.action.retry": "Try again", + "techLog.action.search": "Search", + "techLog.action.save": "Save", + "techLog.action.saving": "Saving…", + "techLog.action.savingBeforeNavigate": "Saving", + "techLog.action.loading": "Loading", + "techLog.action.publish": "Publish", + "techLog.action.republish": "Republish", + "techLog.action.publishing": "Publishing…", + "techLog.action.processing": "Processing", + "techLog.action.delete": "Delete", + "techLog.action.moveUp": "Move up", + "techLog.action.moveDown": "Move down", + "techLog.action.close": "Close", + "techLog.action.apply": "Apply", + "techLog.action.insert": "Insert", + "techLog.action.unpublish": "Unpublish", + "techLog.action.viewLarge": "View larger", + "techLog.action.resetFilters": "Reset filters", + "techLog.action.archive": "Archive", + "techLog.state.documentNotFound": "The working copy could not be found.", + "techLog.state.topicNotFound": "The topic could not be found.", + "techLog.state.validationLoadFailed": "The validation screen could not be loaded.", + "techLog.state.publicPreviewLoadFailed": "The public preview could not be loaded.", + "techLog.state.documentLoadFailed": "The document could not be loaded.", + "techLog.state.publicationLoadFailed": "Publication information could not be loaded.", + "techLog.state.assetListLoadFailed": "The asset list could not be loaded.", + "techLog.state.assetListLoading": "Loading assets.", + "techLog.state.projectLoading": "Loading the project.", + "techLog.state.topicLoading": "Loading the topic.", + "techLog.state.publicationLoading": "Loading publication readiness.", + "techLog.state.validationLoading": "Loading validation information.", + "techLog.state.publicPreviewLoading": "Loading the public preview.", + "techLog.state.publicationListLoading": "Loading publications.", + "techLog.state.publicationListLoadFailed": "Publications could not be loaded.", + "techLog.state.assetNextLoadFailed": "The next assets could not be loaded.", + "techLog.state.assetDetailLoadFailed": "Asset details could not be loaded.", + "techLog.state.topicLoadFailed": "The topic could not be loaded.", + "techLog.state.taxonomyLoadFailed": "Topics and projects could not be loaded.", + "techLog.state.projectLoadFailed": "The project could not be loaded.", + "techLog.failure.archiveFailed": "The item could not be archived.", + "techLog.failure.deleteFailed": "The item could not be deleted.", + "techLog.failure.saveFailed": "The item could not be saved.", + "techLog.failure.variantSaveFailed": "The variant could not be saved.", + "techLog.failure.variantDeleteFailed": "The variant could not be deleted.", + "techLog.failure.topicDeleteFailed": "The topic could not be deleted.", + "techLog.failure.projectDeleteFailed": "The project could not be deleted.", + "techLog.failure.projectUnpublishFailed": "The project could not be made private.", + "techLog.failure.projectPublishFailed": "The project could not be published.", + "techLog.action.deleteBlock": "Delete block", + "techLog.action.restart": "Restart", + "techLog.action.addVersion": "+ Add version", + "techLog.action.addBlock": "+ Add block", + "techLog.action.createWorkingCopy": "Create working copy", + "techLog.action.insertAsset": "Insert asset into content", + "techLog.action.saveHome": "Save home settings", + "techLog.action.upload": "Upload", + "techLog.action.uploading": "Uploading", + "techLog.action.add": "Add", + "techLog.action.addTopic": "Add topic", + "techLog.action.addProject": "Add project", + "techLog.action.more": "Show more", + "techLog.action.saveAltText": "Save alt text", + "techLog.action.makePublic": "Make public", + "techLog.action.removeFromPublic": "Remove from public", + "techLog.action.cancel": "Cancel", + "techLog.action.stay": "Stay on this page", + "techLog.action.discard": "Discard changes", + "techLog.action.saveThenNavigate": "Save and continue", + "techLog.action.expand": "Expand", + "techLog.action.collapse": "Collapse", + "techLog.action.validate": "Validate", + "techLog.action.revalidate": "Validate again", + "techLog.action.validating": "Validating…", + "techLog.action.createPreview": "Create preview", + "techLog.action.recreatePreview": "Recreate preview", + "techLog.action.creating": "Creating…", + "techLog.action.keepPublished": "Keep published", + "techLog.action.confirmUnpublish": "Confirm unpublish", + "techLog.action.addOption": "+ Option", + "techLog.action.addCriterion": "+ Criterion", + "techLog.state.studioNotFound": "The Studio screen could not be found", + "techLog.state.studioLoadFailed": "The Studio screen could not be loaded", + "techLog.state.homeLoadFailed": "Home settings could not be loaded", + "techLog.state.homeLoading": "Loading home settings.", + "techLog.state.homePreparing": "Preparing home settings.", + "techLog.state.openQuestionsLoadFailed": "Open questions could not be loaded. Refresh and try again.", + "techLog.state.decisionsLoadFailed": "Decisions could not be loaded. Refresh and try again.", + "techLog.state.releaseLoadFailed": "The release could not be loaded", + "techLog.state.releaseLoading": "Loading the release.", + "techLog.state.documentListLoadFailed": "Working copies could not be loaded.", + "techLog.state.documentListLoading": "Loading working copies.", + "techLog.state.dashboardLoadFailed": "The work flow could not be loaded", + "techLog.state.dashboardLoading": "Loading the Studio summary.", + "techLog.state.publicationSnapshotLoading": "Loading the publication snapshot.", + "techLog.state.publicationRecordNotFound": "The publication record could not be found", + "techLog.state.publicationSnapshotLoadFailed": "The publication snapshot could not be loaded", + "techLog.state.emptyPublicationList": "No publication records match the current filters", + "techLog.state.emptySearchResult": "No search results.", + "techLog.state.taxonomyLoading": "Loading topics and projects.", + "techLog.state.emptyDocumentList": "No working copies match the current filters", + "techLog.state.emptyDocumentListHint": "Change the search or filters, or create a new document.", + "techLog.state.emptyAssetSearch": "No assets match the current search", + "techLog.state.emptyAssetSearchHint": "Change or clear the search to see all assets.", + "techLog.state.emptyAssetLibrary": "No assets have been registered", + "techLog.state.emptyAssetLibraryHint": "Upload an asset from a Case editor to manage it here.", + "techLog.state.emptyPublicationHistory": "No publication history yet.", + "techLog.state.emptyPublicationListHint": "Change the search or event filter.", + "techLog.studio.group.work": "Work", + "techLog.studio.group.structure": "Structure", + "techLog.studio.group.assets": "Assets", + "techLog.studio.group.publish": "Publish", + "techLog.studio.publicSite": "View public site", + "techLog.studio.primaryNavigation": "Studio primary navigation", + "techLog.studio.mobileNavigation": "Studio mobile navigation", + "techLog.studio.menuOpen": "Open Studio menu", + "techLog.studio.menuClose": "Close Studio menu", + "techLog.editor.status.clean": "Saved", + "techLog.editor.status.dirty": "Unsaved", + "techLog.editor.status.saving": "Saving…", + "techLog.editor.status.conflict": "Save conflict", + "techLog.editor.statusLabel": "Editing status", + "techLog.editor.workStatus": "Work status", + "techLog.failure.documentNotFound": "The working copy could not be found.", + "techLog.failure.versionConflict": + "Another change was saved first. Reload the latest version and try again.", + "techLog.failure.validationRejected": + "Review the entered values and try again.", + "techLog.failure.validationStale": + "The saved version changed. Validate the current version again.", + "techLog.failure.previewStale": + "The preview does not match the current saved version. Create it again.", + "techLog.failure.previewExpired": + "The preview expired. Create it again.", + "techLog.failure.publicationConflict": + "The publication state changed. Reload the latest state and try again.", + "techLog.failure.studioUnavailable": + "Studio is temporarily unavailable.", + "techLog.failure.assetInUse": + "An asset that is in use cannot be deleted.", + "techLog.failure.duplicateInFlight": + "The same operation is already in progress.", + "techLog.public.error.pageLoadTitle": "The page could not be loaded.", + "techLog.public.error.pageLoadHelp": "Try again shortly. If the problem continues, include the Trace ID below when asking for help.", + "techLog.action.exploreAllRecords": "Explore all records", + "techLog.state.latestLoadFailed": "Recent records could not be loaded.", + "techLog.state.noPublishedRecords": "No records have been published yet.", + "techLog.action.clearSearch": "Clear search", + "techLog.state.noMatchingPublicRecords": "No public records match the search.", + "techLog.action.backToExplore": "Back to explore", + "techLog.action.browseProjects": "Browse projects", + "techLog.action.exploreRecords": "Explore records", + "techLog.state.noPublishedProjects": "No projects have been published yet.", + "techLog.state.noRegisteredTopics": "No topics have been registered yet.", + "techLog.state.noProjectPublishedRecords": "This project has no published records yet.", + "techLog.state.noDecisions": "No decisions have been finalized yet.", + "techLog.state.noOpenQuestions": "There are no open questions yet. This project is still gathering records.", + "techLog.state.noImpact": "No impact has been recorded.", + "techLog.state.noEvidence": "No evidence records are linked.", + "techLog.state.noConclusion": "No conclusion has been written yet. The research map below shows the records gathered so far.", + "techLog.public.notFound": "The page could not be found.", + "techLog.public.notFoundDetail": "The requested public page does not exist.", + "techLog.action.changeLog": "Change log", + "techLog.public.releaseBreadcrumb": "Release change log path", + "techLog.state.noPublishedReleases": "No releases have been published yet.", + "techLog.state.noPublishedTopics": "No topics have been published yet.", + "techLog.state.noAssumptions": "No assumptions have been recorded.", + "techLog.state.noUnknowns": "No unresolved unknowns remain in this record.", + "techLog.state.irreversible": "This action cannot be undone.", + "techLog.notice.published": "Published.", + "techLog.failure.saveRetry": "The document could not be saved. Try again.", + "techLog.failure.saveBeforePublish": "Changes could not be saved before publishing.", + "techLog.failure.validationBeforePublish": "The document could not be validated before publishing.", + "techLog.failure.previewBeforePublish": "The public preview could not be created before publishing.", + "techLog.failure.publishRetry": "The document could not be published. Try again.", + "techLog.state.editorPreparing": "Preparing the document editor.", + "techLog.state.sessionDocumentMissing": "This working copy is not available in the current Studio session.", + "techLog.failure.publishFieldsRequired": "The document cannot be published. Complete the highlighted fields.", + "techLog.notice.homeFocusSaved": "The home focus was saved.", + "techLog.action.savingPlain": "Saving", + "techLog.action.creatingPlain": "Creating…", + "techLog.state.emptyOrderedText": "No items have been entered yet.", + "techLog.state.projectTopicsEmpty": "No topics exist yet. Create one from Topics · Projects first.", + "techLog.notice.previewCreated": "Created a public preview for the current saved version.", + "techLog.failure.previewRetry": "The public preview could not be created. Try again.", + "techLog.notice.unpublished": "Publication cancelled.", + "techLog.failure.unpublishFailed": "The publication could not be cancelled.", + "techLog.notice.releaseUnpublished": "The release was removed from public view.", + "techLog.failure.releasePublishFields": "The release could not be published. Check its version, title, summary, change type, changes, validation, and publication date.", + "techLog.failure.releaseUnpublishFailed": "The release could not be removed from public view.", + "techLog.notice.releaseDraftCreated": "Created release draft {title}. Edit it from the list to complete the details.", + "techLog.notice.releaseDeleted": "Deleted release {version}.", + "techLog.action.adding": "Adding…", + "techLog.state.releasesEmpty": "No releases yet.", + "techLog.state.dashboardContinueEmpty": "No documents are waiting to be continued.", + "techLog.state.dashboardValidateEmpty": "No documents currently need validation.", + "techLog.state.dashboardReadyEmpty": "No documents are ready to publish.", + "techLog.state.groupedTopicsEmpty": "No grouped topics.", + "techLog.state.topicsCreateFirst": "No topics yet. Create one above.", + "techLog.state.projectsEmpty": "No projects yet.", + "techLog.action.addingPlain": "Adding", + "techLog.action.unpublishing": "Cancelling publication…", + "techLog.state.validationClean": "No errors or warnings.", + "techLog.notice.validationComplete": "Validation of the saved document is complete.", + "techLog.failure.validationRetry": "Validation failed. Try again.", + "techLog.state.validationRecordEmpty": "No validation record", + "techLog.state.warningsEmpty": "No warnings require acknowledgement.", + "techLog.notice.assetArchived": "Archived.", + "techLog.notice.assetDeleted": "Deleted.", + "techLog.notice.assetAltTextSaved": "Alternative text saved.", + "techLog.notice.topicSavedVersion": "Saved the topic as version {version}.", + "techLog.notice.itemAdded": "Added {title}.", + "techLog.notice.itemSaved": "Saved {title}.", + "techLog.notice.itemDeleted": "Deleted {title}.", + "techLog.notice.topicCreated": "Created topic {name}.", + "techLog.notice.projectCreated": "Created project {title}.", + "techLog.notice.topicDeleted": "Deleted topic {name}.", + "techLog.notice.projectDeleted": "Deleted project {name}.", + "techLog.notice.savedVersion": "Saved as version {version}.", + "techLog.management.conflict": + "Another change was applied first. Reload the latest state and try again.", + "techLog.management.notFound": "The requested item could not be found.", + "techLog.management.validationRejected": "Review the entered values.", + "techLog.management.authRequired": "Studio sign-in is required.", + "techLog.management.forbidden": + "You are not allowed to perform this operation.", + "techLog.management.serverFailure": + "The management API is unavailable. Try again shortly.", +} as const satisfies Record); + export const TECH_LOG_MESSAGE_CATALOGS = Object.freeze({ - "ko-KR": createCatalog(), - "en-US": createCatalog(), + "ko-KR": Object.freeze({ + ...createRouteCatalog("ko-KR"), + ...KO_UI_MESSAGES, + }), + "en-US": Object.freeze({ + ...createRouteCatalog("en-US"), + ...EN_UI_MESSAGES, + }), }); diff --git a/src/features/tech-log/contracts/tech-log-public-contract-contribution.ts b/src/features/tech-log/contracts/tech-log-public-contract-contribution.ts index faada8a..ce4d39b 100644 --- a/src/features/tech-log/contracts/tech-log-public-contract-contribution.ts +++ b/src/features/tech-log/contracts/tech-log-public-contract-contribution.ts @@ -6,6 +6,14 @@ import { TECH_LOG_FEATURE_ID } from "../application/tech-log-feature-input.ts"; import canonicalSource from "./public/canonical-source.json" with { type: "json" }; import { envelopeData, envelopeError, passthroughInput } from "./tech-log-studio-contract-contribution.ts"; + +type NamedInstalledHttpContract = + InstalledHttpContract & + Readonly<{ + contract: InstalledHttpContract["contract"] & + Readonly<{ operationId: OperationId }>; + }>; + type PathValues = Readonly>; type QueryEntries = readonly (readonly [string, string])[]; @@ -41,13 +49,13 @@ function queryOf(input: Readonly>): QueryEntries { * sending the session cookie on a public read fails the profile check rather * than silently making the cache-friendly surface user-specific. */ -function publicRead( - operationId: string, +function publicRead( + operationId: OperationId, pathTemplate: string, responseByteLimit: number, project: (input: never) => Readonly<{ pathValues: PathValues; queryEntries: QueryEntries }> = () => Object.freeze({ pathValues: NO_PATH, queryEntries: NO_QUERY }), -): InstalledHttpContract { +): NamedInstalledHttpContract { return Object.freeze({ contract: Object.freeze({ operationId, @@ -78,7 +86,7 @@ function publicRead( authProfileId: "ANONYMOUS", diagnosticsOperation: `techLog.public.${operationId}`, }), - }) as InstalledHttpContract; + }) as NamedInstalledHttpContract; } const bySlug = (input: never) => { @@ -91,7 +99,7 @@ const bySlug = (input: never) => { const P = "/api/v1/public"; -const HTTP_CONTRACTS = Object.freeze([ +export const TECH_LOG_PUBLIC_HTTP_CONTRACTS = Object.freeze([ publicRead("getPublicSite", `${P}/site`, 32_768), publicRead("getPublicHome", `${P}/home`, 262_144), publicRead("exploreKnowledge", `${P}/explore/knowledge`, 262_144, (input: never) => { @@ -147,10 +155,10 @@ const HTTP_CONTRACTS = Object.freeze([ const value = input as unknown as Readonly<{ q?: string; page?: number; size?: number }>; return Object.freeze({ pathValues: NO_PATH, queryEntries: queryOf(value ?? {}) }); }), -]); +] as const); export const TECH_LOG_PUBLIC_OPERATION_IDS = Object.freeze( - HTTP_CONTRACTS.map((entry) => entry.contract.operationId), + TECH_LOG_PUBLIC_HTTP_CONTRACTS.map((entry) => entry.contract.operationId), ); export type TechLogPublicOperationId = @@ -170,6 +178,6 @@ export const TECH_LOG_PUBLIC_CONTRIBUTION: InstalledContractContribution = sourceRevision: canonicalSource.sourceRevision, }), }), - http: HTTP_CONTRACTS, + http: TECH_LOG_PUBLIC_HTTP_CONTRACTS, events: Object.freeze([]), }); diff --git a/src/features/tech-log/contracts/tech-log-studio-contract-contribution.ts b/src/features/tech-log/contracts/tech-log-studio-contract-contribution.ts index 45df5ca..45c6e97 100644 --- a/src/features/tech-log/contracts/tech-log-studio-contract-contribution.ts +++ b/src/features/tech-log/contracts/tech-log-studio-contract-contribution.ts @@ -146,11 +146,19 @@ const COMMAND_EFFECT: CommandEffectDescriptor = }, }); + +type NamedInstalledHttpContract = + InstalledHttpContract & + Readonly<{ + contract: InstalledHttpContract["contract"] & + Readonly<{ operationId: OperationId }>; + }>; + type PathValues = Readonly>; type QueryEntries = readonly (readonly [string, string])[]; -function safeOperation( - operationId: string, +function safeOperation( + operationId: OperationId, pathTemplate: string, responseByteLimit: number, project: (input: never) => Readonly<{ pathValues: PathValues; queryEntries: QueryEntries }>, @@ -159,7 +167,7 @@ function safeOperation( // of `TECH_LOG_STUDIO_BOOTSTRAP`. Every other safe/keyed operation keeps // the default `TECH_LOG_STUDIO_SESSION`. authProfileId: TechLogStudioAuthProfileId = TECH_LOG_STUDIO_SESSION_AUTH_PROFILE_ID, -): InstalledHttpContract { +): NamedInstalledHttpContract { return Object.freeze({ contract: Object.freeze({ operationId, @@ -189,11 +197,11 @@ function safeOperation( authProfileId, diagnosticsOperation: `techLog.studio.${operationId}`, }), - }) as InstalledHttpContract; + }) as NamedInstalledHttpContract; } -function keyedOperation( - operationId: string, +function keyedOperation( + operationId: OperationId, method: "POST" | "PUT" | "DELETE", pathTemplate: string, options: Readonly<{ @@ -207,7 +215,7 @@ function keyedOperation( queryEntries: QueryEntries; body: unknown; }>, -): InstalledHttpContract { +): NamedInstalledHttpContract { return Object.freeze({ contract: Object.freeze({ operationId, @@ -238,7 +246,7 @@ function keyedOperation( authProfileId: TECH_LOG_STUDIO_SESSION_AUTH_PROFILE_ID, diagnosticsOperation: `techLog.studio.${operationId}`, }), - }) as InstalledHttpContract; + }) as NamedInstalledHttpContract; } const NO_PATH = Object.freeze({}); @@ -265,6 +273,8 @@ const GET_STUDIO_SESSION = safeOperation( TECH_LOG_STUDIO_BOOTSTRAP_AUTH_PROFILE_ID, ); +export const TECH_LOG_STUDIO_SESSION_CONTRACT = GET_STUDIO_SESSION; + const GET_STUDIO_DASHBOARD = safeOperation( "getStudioDashboard", "/api/v1/studio/dashboard", @@ -616,7 +626,7 @@ const DELETE_STUDIO_ASSET = keyedOperation( // Contribution assembly // --------------------------------------------------------------------------- -const HTTP_CONTRACTS = Object.freeze([ +export const TECH_LOG_STUDIO_HTTP_CONTRACTS = Object.freeze([ GET_STUDIO_SESSION, GET_STUDIO_DASHBOARD, LIST_STUDIO_DOCUMENTS, @@ -635,19 +645,19 @@ const HTTP_CONTRACTS = Object.freeze([ GET_STUDIO_ASSET, UPDATE_STUDIO_ASSET, DELETE_STUDIO_ASSET, -]); +] as const); // Fix round 2, item 3. Fails composition closed rather than letting a wrong // assignment (two operations, or zero) reach production undetected. assertExactlyOneTechLogStudioBootstrapOperation( - HTTP_CONTRACTS.map((entry) => ({ + TECH_LOG_STUDIO_HTTP_CONTRACTS.map((entry) => ({ operationId: entry.contract.operationId, authProfileId: entry.frontend.authProfileId, })), ); export const TECH_LOG_STUDIO_OPERATION_IDS = Object.freeze( - HTTP_CONTRACTS.map((entry) => entry.contract.operationId), + TECH_LOG_STUDIO_HTTP_CONTRACTS.map((entry) => entry.contract.operationId), ); export type TechLogStudioOperationId = @@ -667,6 +677,6 @@ export const TECH_LOG_STUDIO_CONTRIBUTION: InstalledContractContribution = sourceRevision: canonicalSource.sourceRevision, }), }), - http: HTTP_CONTRACTS, + http: TECH_LOG_STUDIO_HTTP_CONTRACTS, events: Object.freeze([]), }); diff --git a/src/features/tech-log/presentation/public/components/explore-filter-form.tsx b/src/features/tech-log/presentation/public/components/explore-filter-form.tsx index 9864490..5a668c4 100644 --- a/src/features/tech-log/presentation/public/components/explore-filter-form.tsx +++ b/src/features/tech-log/presentation/public/components/explore-filter-form.tsx @@ -1,8 +1,12 @@ +import { Button, SelectControl } from "../../../../../presentation/design-system/index.ts"; import { Link, useNavigate } from "react-router-dom"; +import { Form } from "../../../../../presentation/forms/index.ts"; +import { useLocale } from "../../../../../presentation/i18n/index.ts"; import type { RecordKind } from "../../../application/ports/public-content-queries.ts"; import { usePublicContent } from "../use-public-content.tsx"; import { DOCUMENT_KIND_LABELS } from "../../shared/document-kind-labels.ts"; +import { publicRoutePrefixes } from "../public-routes.ts"; /* 탐색이 거를 수 있는 종류. 이름은 공용 표에서 가져온다 — 예전에는 이 목록만 「개념」이라 @@ -41,16 +45,17 @@ export function ExploreFilterForm({ showType?: boolean; }) { const navigate = useNavigate(); + const { message } = useLocale(); // This form sits inside a page that renders its own loading state, so it does // not hand back a fallback of its own — that would put a second skeleton // inside a screen already showing one, and move the layout under it. It // renders its real structure immediately with empty option lists and fills // them in when the catalog arrives. const view = usePublicContent(["tech-log", "explore-filters"], async (queries) => { - const projectPrefix = "/projects/"; + const projectPrefix = publicRoutePrefixes.project; const [records, entities] = await Promise.all([ queries.listRecords(), - queries.searchPublicContent(""), + queries.listCatalog(), ]); const projectSlugs = entities .filter((entity) => entity.contentType === "PROJECT") @@ -110,7 +115,7 @@ export function ExploreFilterForm({ } return ( - {showType ? ( - + ) : null} - - - - {hasActiveFilter ? 필터 초기화 : null} - + + + + {hasActiveFilter ? {message("techLog.action.resetFilters")} : null} + ); } diff --git a/src/features/tech-log/presentation/public/components/fatal-error-state.tsx b/src/features/tech-log/presentation/public/components/fatal-error-state.tsx index ae61240..4677907 100644 --- a/src/features/tech-log/presentation/public/components/fatal-error-state.tsx +++ b/src/features/tech-log/presentation/public/components/fatal-error-state.tsx @@ -1,4 +1,6 @@ +import { Button } from "../../../../../presentation/design-system/index.ts"; import { Link } from "react-router-dom"; +import { useLocale } from "../../../../../presentation/i18n/index.ts"; type FatalErrorStateProps = { traceId: string; @@ -11,25 +13,24 @@ export function FatalErrorState({ onRetry, retryHref = "/", }: FatalErrorStateProps) { + const { message } = useLocale(); + return (

Service error

-

페이지를 불러오지 못했습니다.

-

- 잠시 후 다시 시도해 주세요. 문제가 계속되면 아래 Trace ID를 함께 - 전달해 주세요. -

+

{message("techLog.public.error.pageLoadTitle")}

+

{message("techLog.public.error.pageLoadHelp")}

Trace ID {traceId}

{onRetry ? ( - + ) : ( - 다시 시도 + {message("techLog.action.retry")} )}
diff --git a/src/features/tech-log/presentation/public/components/latest-index.tsx b/src/features/tech-log/presentation/public/components/latest-index.tsx index 654a03d..8ac1225 100644 --- a/src/features/tech-log/presentation/public/components/latest-index.tsx +++ b/src/features/tech-log/presentation/public/components/latest-index.tsx @@ -1,6 +1,8 @@ import { Link } from "react-router-dom"; import { cardSummary } from "../../../domain/content-format/card-summary.ts"; +import { publicRoutes } from "../public-routes.ts"; +import { TechLogMessage } from "../../tech-log-message.tsx"; export type LatestEntry = { id: string; typeLabel: string; @@ -34,21 +36,21 @@ export function LatestIndex({

Index

최근 기록

- - 모든 기록 탐색 + + {} {status === "error" ? (
-

최근 기록을 불러오지 못했습니다.

- - 다시 시도 +

{}

+ + {}
) : entries.length === 0 ? (

- 아직 공개된 기록이 없습니다. + {}

) : (
    diff --git a/src/features/tech-log/presentation/public/components/project-navigation.tsx b/src/features/tech-log/presentation/public/components/project-navigation.tsx index c453e13..0ad4568 100644 --- a/src/features/tech-log/presentation/public/components/project-navigation.tsx +++ b/src/features/tech-log/presentation/public/components/project-navigation.tsx @@ -1,21 +1,21 @@ import { Link, useLocation } from "react-router-dom"; import type { Project } from "../../../application/ports/public-content-queries.ts"; +import { publicRoutes } from "../public-routes.ts"; export type ProjectSection = "overview" | "records" | "decisions" | "activity"; const sections = [ - { key: "overview", label: "개요", suffix: "" }, - { key: "records", label: "기록", suffix: "/records" }, - { key: "decisions", label: "결정", suffix: "/decisions" }, - { key: "activity", label: "활동", suffix: "/activity" }, + { key: "overview", label: "개요", route: publicRoutes.project }, + { key: "records", label: "기록", route: publicRoutes.projectRecords }, + { key: "decisions", label: "결정", route: publicRoutes.projectDecisions }, + { key: "activity", label: "활동", route: publicRoutes.projectActivity }, ] as const; export function ProjectNavigation({ project }: { project: Project }) { const { pathname } = useLocation(); - const basePath = `/projects/${project.slug}`; const current = - sections.find((section) => pathname === `${basePath}${section.suffix}`)?.key ?? + sections.find((section) => pathname === section.route(project.slug))?.key ?? "overview"; return ( @@ -23,7 +23,7 @@ export function ProjectNavigation({ project }: { project: Project }) { {sections.map((section) => ( {section.label} diff --git a/src/features/tech-log/presentation/public/components/project-page-header.tsx b/src/features/tech-log/presentation/public/components/project-page-header.tsx index 5871368..ccccfed 100644 --- a/src/features/tech-log/presentation/public/components/project-page-header.tsx +++ b/src/features/tech-log/presentation/public/components/project-page-header.tsx @@ -3,6 +3,7 @@ import { Link } from "react-router-dom"; import type { Project } from "../../../application/ports/public-content-queries.ts"; import { ProjectNavigation } from "./project-navigation.tsx"; +import { publicRoutes } from "../public-routes.ts"; export function ProjectPageHeader({ project, title, @@ -13,7 +14,7 @@ export function ProjectPageHeader({ return (

    - Projects + Projects {project.title}

    diff --git a/src/features/tech-log/presentation/public/components/project-path.tsx b/src/features/tech-log/presentation/public/components/project-path.tsx index 9498aab..d9fe7c1 100644 --- a/src/features/tech-log/presentation/public/components/project-path.tsx +++ b/src/features/tech-log/presentation/public/components/project-path.tsx @@ -5,6 +5,7 @@ import type { PublicTopic, } from "../../../application/ports/public-content-queries.ts"; +import { publicRoutes } from "../public-routes.ts"; type TopicRef = Readonly<{ name: string; slug: string }>; /** @@ -80,7 +81,7 @@ export function ProjectPath({
    {topic.slug ? ( - {topic.name} + {topic.name} ) : ( {topic.name} )} diff --git a/src/features/tech-log/presentation/public/components/public-document-header.tsx b/src/features/tech-log/presentation/public/components/public-document-header.tsx index b48fa74..311f949 100644 --- a/src/features/tech-log/presentation/public/components/public-document-header.tsx +++ b/src/features/tech-log/presentation/public/components/public-document-header.tsx @@ -4,6 +4,7 @@ import type { PublicRecord } from "../../../application/ports/public-content-que import type { components } from "../../../contracts/studio/generated.ts"; import { ProseText } from "../../shared/public-render/prose-text.tsx"; import { DOCUMENT_KIND_LABELS } from "../../shared/document-kind-labels.ts"; +import { publicRoutePrefixes, publicRoutes } from "../public-routes.ts"; type TargetKind = components["schemas"]["ResolvedRelation"]["targetKind"]; @@ -15,17 +16,23 @@ type TargetKind = components["schemas"]["ResolvedRelation"]["targetKind"]; * 더할 때 짝을 빠뜨리는 일이 이 저장소에서만 다섯 번 있었다. */ const PATH_PREFIX_KINDS: ReadonlyArray = [ - ["/cases/", "CASE"], - ["/references/", "REFERENCE"], - ["/questions/", "QUESTION"], - ["/concepts/", "CONCEPT"], + [publicRoutePrefixes.case, "CASE"], + [publicRoutePrefixes.reference, "REFERENCE"], + [publicRoutePrefixes.question, "QUESTION"], + [publicRoutePrefixes.concept, "CONCEPT"], ]; +const PROJECT_ROUTE_PROBE = "__project__"; +const DECISION_RELATION_MARKER = + publicRoutes + .projectDecisions(PROJECT_ROUTE_PROBE) + .slice(publicRoutes.project(PROJECT_ROUTE_PROBE).length) + "#"; + function targetKindOf(path: string): TargetKind { const matched = PATH_PREFIX_KINDS.find(([prefix]) => path.startsWith(prefix)); if (matched) return matched[1]; // 결정은 프로젝트 화면 안의 앵커로 산다. 그래서 앞머리가 아니라 조각으로 가른다. - return path.includes("/decisions#") ? "PROJECT_DECISION" : "PROJECT"; + return path.includes(DECISION_RELATION_MARKER) ? "PROJECT_DECISION" : "PROJECT"; } export function publicRenderModelBase( @@ -46,13 +53,13 @@ export function publicRenderModelBase( 주제든 자기 화면이 있다. */ publicPath: record.topicSlug - ? `/topics/${encodeURIComponent(record.topicSlug)}` + ? publicRoutes.topic(record.topicSlug) : null, }, project: { id: `project-${record.projectSlug}`, label: record.projectTitle, - publicPath: `/projects/${record.projectSlug}`, + publicPath: publicRoutes.project(record.projectSlug), }, relations: record.relations.map((relation, index) => ({ id: `public-relation-${index + 1}-${relation.path}`, diff --git a/src/features/tech-log/presentation/public/components/search-dialog.tsx b/src/features/tech-log/presentation/public/components/search-dialog.tsx index 0563c87..ab63e83 100644 --- a/src/features/tech-log/presentation/public/components/search-dialog.tsx +++ b/src/features/tech-log/presentation/public/components/search-dialog.tsx @@ -1,10 +1,17 @@ -import { useId, useRef, useState } from "react"; +import { useRef, useState } from "react"; import { Link } from "react-router-dom"; import { usePublicContent } from "../use-public-content.tsx"; import { HighlightMatch } from "../../shared/highlight-match.tsx"; import { cardSummary } from "../../../domain/content-format/card-summary.ts"; +import { + Button, + Dialog, + SearchField, +} from "../../../../../presentation/design-system/index.ts"; +import { publicRoutes } from "../public-routes.ts"; +import { useLocale } from "../../../../../presentation/i18n/index.ts"; type SearchDialogProps = { className?: string; onBeforeOpen?: () => void; @@ -14,10 +21,10 @@ export function SearchDialog({ className = "", onBeforeOpen, }: SearchDialogProps) { - const dialogId = useId(); - const dialogRef = useRef(null); + const { message } = useLocale(); const inputRef = useRef(null); const triggerRef = useRef(null); + const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); const normalizedQuery = query.trim().toLocaleLowerCase("ko-KR"); // Keyed on the empty query, then filtered here, rather than one request per @@ -26,7 +33,7 @@ export function SearchDialog({ // than a stale-free local filter. The predicate is the same one the catalog // applies for a non-empty query, so the visible result set is unchanged. const view = usePublicContent(["tech-log", "search", "dialog"], async (queries) => ({ - entities: await queries.searchPublicContent(""), + entities: await queries.listCatalog(), })); const results = (view.data?.entities ?? []).filter((entity) => normalizedQuery @@ -36,67 +43,50 @@ export function SearchDialog({ : true, ); - function open() { + function openDialog() { onBeforeOpen?.(); - dialogRef.current?.showModal(); - requestAnimationFrame(() => inputRef.current?.focus()); + setOpen(true); } - function close() { - dialogRef.current?.close(); + function closeDialog() { + setOpen(false); } return ( <> - - + triggerRef.current?.focus()} - onKeyDown={(event) => { - if (event.key === "Escape") { - event.preventDefault(); - close(); - } - }} - onClick={(event) => { - if (event.target === event.currentTarget) close(); - }} + closeLabel={message("techLog.action.close")} + initialFocusRef={inputRef} + eyebrow={

    Public records

    } + onClose={closeDialog} + open={open} + returnFocusRef={triggerRef} + title="TechLog 검색" >
    -
    -
    -

    Public records

    -

    TechLog 검색

    -
    - -
    - + setQuery("")} + onChange={(event) => setQuery(event.currentTarget.value)} + placeholder="제목, 요약, 주제, 프로젝트 검색" + value={query} + />

    {results.length}개의 공개 기록

    @@ -105,13 +95,16 @@ export function SearchDialog({
      {results.map((entry) => (
    • - + {entry.contentType}

      - +

    • @@ -120,18 +113,18 @@ export function SearchDialog({ {normalizedQuery ? ( 전체 검색 결과 보기 ) : null} ) : ( -

      일치하는 공개 기록이 없습니다.

      +

      {message("techLog.state.noMatchingPublicRecords")}

      )}
    -
    +
    ); } diff --git a/src/features/tech-log/presentation/public/components/site-header.tsx b/src/features/tech-log/presentation/public/components/site-header.tsx index cb285fb..1ca87e9 100644 --- a/src/features/tech-log/presentation/public/components/site-header.tsx +++ b/src/features/tech-log/presentation/public/components/site-header.tsx @@ -1,26 +1,32 @@ import { useRef } from "react"; import { Link, useLocation } from "react-router-dom"; +import { useLocale } from "../../../../../presentation/i18n/index.ts"; + import { publicSiteConfig } from "../../../contracts/public-site-config.ts"; import { techLogNavigation } from "../../tech-log-navigation.ts"; import { SearchDialog } from "./search-dialog.tsx"; +import { publicRoutes } from "../public-routes.ts"; // Derived from the route contract rather than repeated here; see // `tech-log-navigation.ts` for why. const navigation = techLogNavigation("PUBLIC"); export function SiteHeader({ currentPath }: { currentPath?: string }) { + const { message } = useLocale(); const location = useLocation(); const activePath = currentPath ?? - (location.pathname.startsWith("/topics/") ? "/explore" : location.pathname); + (location.pathname.startsWith(publicRoutes.topics() + "/") + ? publicRoutes.explore() + : location.pathname); const menuRef = useRef(null); const summaryRef = useRef(null); function isCurrent(path: string) { return ( activePath === path || - (path !== "/" && activePath.startsWith(path + "/")) + (path !== publicRoutes.home() && activePath.startsWith(path + "/")) ); } @@ -34,13 +40,13 @@ export function SiteHeader({ currentPath }: { currentPath?: string }) {
    - + {publicSiteConfig.brandTitle}
    -
    - + 전체 보기
    @@ -184,7 +172,7 @@ export function HomePage() { ))} ) : ( -

    아직 공개된 프로젝트가 없습니다.

    +

    {}

    )} diff --git a/src/features/tech-log/presentation/public/pages/profile-page.tsx b/src/features/tech-log/presentation/public/pages/profile-page.tsx index cc61352..a07822d 100644 --- a/src/features/tech-log/presentation/public/pages/profile-page.tsx +++ b/src/features/tech-log/presentation/public/pages/profile-page.tsx @@ -6,6 +6,8 @@ import { publicSiteConfig } from "../../../contracts/public-site-config.ts"; import { usePublicContent } from "../use-public-content.tsx"; import { useApplication } from "../../../../../presentation/providers/application-provider.tsx"; +import { publicRoutes } from "../public-routes.ts"; +import { TechLogMessage } from "../../tech-log-message.tsx"; const principles = [ { title: "확인된 사실과 남아 있는 가정", @@ -30,11 +32,9 @@ export function ProfilePage() { // and rendered nothing but an error. "Current projects" means the published // ones, so read them from the catalogue the projects index already reads. const view = usePublicContent(["tech-log", "profile"], async (queries) => { - const entries = (await queries.searchPublicContent("")).filter( - (item) => item.contentType === "PROJECT", - ); + const entries = await queries.listProjects(); const [resolved, topics, contacts] = await Promise.all([ - Promise.all(entries.map((item) => queries.getProject(item.path.replace("/projects/", "")))), + Promise.all(entries.map((item) => queries.getProject(item.slug))), queries.listTopics(), queries.listContacts(), ]); @@ -83,12 +83,12 @@ export function ProfilePage() { {!view.ready ? ( view.fallback ) : view.data.currentProjects.length === 0 ? ( -

    아직 공개된 프로젝트가 없습니다.

    +

    {}

    ) : (
      {view.data.currentProjects.map((project) => (
    • - +
      {project.title} {projectStageLabel(project.stage)} @@ -111,7 +111,7 @@ export function ProfilePage() { {!view.ready ? ( view.fallback ) : view.data.topics.length === 0 ? ( -

      아직 등록한 주제가 없습니다.

      +

      {}

      ) : (
        {view.data.topics.map((topic) => ( diff --git a/src/features/tech-log/presentation/public/pages/project-activity-page.tsx b/src/features/tech-log/presentation/public/pages/project-activity-page.tsx index 75d6c54..77d90ac 100644 --- a/src/features/tech-log/presentation/public/pages/project-activity-page.tsx +++ b/src/features/tech-log/presentation/public/pages/project-activity-page.tsx @@ -9,6 +9,7 @@ import { projectActivityLabel } from "../../shared/project-activity-labels.ts"; import { ProjectPageHeader } from "../components/project-page-header.tsx"; import { usePublicContent } from "../use-public-content.tsx"; +import { TechLogMessage } from "../../tech-log-message.tsx"; export function ProjectActivityPage() { const { params } = useRouteInput<"TECH_LOG_PROJECT_ACTIVITY">(); const slug = typeof params.slug === "string" ? params.slug : ""; @@ -34,7 +35,7 @@ export function ProjectActivityPage() {
        {activity.length === 0 ? ( -

        아직 이 프로젝트에서 공개한 기록이 없습니다.

        +

        {}

        ) : (
          {activity.map((item) => ( diff --git a/src/features/tech-log/presentation/public/pages/project-decisions-page.tsx b/src/features/tech-log/presentation/public/pages/project-decisions-page.tsx index 4489c52..158e6b6 100644 --- a/src/features/tech-log/presentation/public/pages/project-decisions-page.tsx +++ b/src/features/tech-log/presentation/public/pages/project-decisions-page.tsx @@ -9,6 +9,7 @@ import { ProseText } from "../../shared/public-render/prose-text.tsx"; import { ProjectPageHeader } from "../components/project-page-header.tsx"; import { usePublicContent } from "../use-public-content.tsx"; +import { TechLogMessage } from "../../tech-log-message.tsx"; export function ProjectDecisionsPage() { const { params } = useRouteInput<"TECH_LOG_PROJECT_DECISIONS">(); const slug = typeof params.slug === "string" ? params.slug : ""; @@ -55,7 +56,7 @@ export function ProjectDecisionsPage() {
          -

          아직 확정한 결정이 없습니다.

          +

          {}

          {openQuestions.length > 0 ? ( <>

          {`결정으로 이어질 수 있는 열린 질문이 ${openQuestions.length}개 있습니다.`}

          @@ -69,7 +70,7 @@ export function ProjectDecisionsPage() { ) : (

          - 아직 열린 질문도 없습니다. 이 프로젝트의 조사는 기록을 모으는 단계입니다. + {}

          )}
          @@ -127,7 +128,7 @@ export function ProjectDecisionsPage() { ))}
      ) : ( -

      남긴 영향이 없습니다.

      +

      {}

      )}
      @@ -141,7 +142,7 @@ export function ProjectDecisionsPage() { ))}
    ) : ( -

    연결한 근거 기록이 없습니다.

    +

    {}

    )} diff --git a/src/features/tech-log/presentation/public/pages/project-overview-page.tsx b/src/features/tech-log/presentation/public/pages/project-overview-page.tsx index 30bf56b..607aa5e 100644 --- a/src/features/tech-log/presentation/public/pages/project-overview-page.tsx +++ b/src/features/tech-log/presentation/public/pages/project-overview-page.tsx @@ -10,6 +10,8 @@ import { ProjectPath } from "../components/project-path.tsx"; import { ProseText } from "../../shared/public-render/prose-text.tsx"; import { usePublicContent } from "../use-public-content.tsx"; +import { publicRoutes } from "../public-routes.ts"; +import { TechLogMessage } from "../../tech-log-message.tsx"; export function ProjectOverviewPage() { const { params } = useRouteInput<"TECH_LOG_PROJECT">(); const slug = typeof params.slug === "string" ? params.slug : ""; @@ -109,7 +111,7 @@ export function ProjectOverviewPage() { ) : (

    - 아직 정리한 결론이 없습니다. 아래 조사 지도가 지금까지 모은 기록을 보여 줍니다. + {}

    )} @@ -135,15 +137,15 @@ export function ProjectOverviewPage() { 두 번 나왔고, 둘 중 어디서 읽어야 하는지는 화면이 말해 주지 않았다. */}
    - + {records.length} 공개 기록 - + {decisions.length} 설계 결정 - + {activity.length} 활동 기록 diff --git a/src/features/tech-log/presentation/public/pages/projects-page.tsx b/src/features/tech-log/presentation/public/pages/projects-page.tsx index 42f9656..a3932d3 100644 --- a/src/features/tech-log/presentation/public/pages/projects-page.tsx +++ b/src/features/tech-log/presentation/public/pages/projects-page.tsx @@ -3,12 +3,12 @@ import { projectStageLabel } from "../../../domain/public/project-phase-labels.t import { usePublicContent } from "../use-public-content.tsx"; +import { publicRoutes } from "../public-routes.ts"; +import { TechLogMessage } from "../../tech-log-message.tsx"; export function ProjectsPage() { const view = usePublicContent(["tech-log", "projects"], async (queries) => { - const entries = (await queries.searchPublicContent("")).filter( - (item) => item.contentType === "PROJECT", - ); - const slugs = entries.map((item) => item.path.replace("/projects/", "")); + const entries = await queries.listProjects(); + const slugs = entries.map((item) => item.slug); /* 목록에도 조사의 상태를 싣는다. 이름과 단계만 있던 동안 한 줄이 차지하는 높이에 비해 말하는 것이 너무 적었다 — 넓은 여백이 남고, 읽는 사람은 그 프로젝트가 지금 어디쯤인지 @@ -55,12 +55,12 @@ export function ProjectsPage() { {!view.ready ? ( view.fallback ) : view.data.projects.length === 0 ? ( -

    아직 공개된 프로젝트가 없습니다.

    +

    {}

    ) : (
      {view.data.projects.map(({ project, records, decisions, open }, index) => (
    1. - + {String(index + 1).padStart(2, "0")}
      diff --git a/src/features/tech-log/presentation/public/pages/public-not-found-page.tsx b/src/features/tech-log/presentation/public/pages/public-not-found-page.tsx index 8559ef8..0be1a61 100644 --- a/src/features/tech-log/presentation/public/pages/public-not-found-page.tsx +++ b/src/features/tech-log/presentation/public/pages/public-not-found-page.tsx @@ -1,10 +1,11 @@ +import { TechLogMessage } from "../../tech-log-message.tsx"; export function PublicNotFoundPage() { return (

      404

      -

      페이지를 찾을 수 없습니다.

      -

      요청한 공개 페이지가 없습니다.

      +

      {}

      +

      {}

      ); diff --git a/src/features/tech-log/presentation/public/pages/release-page.tsx b/src/features/tech-log/presentation/public/pages/release-page.tsx index de9616c..73f154f 100644 --- a/src/features/tech-log/presentation/public/pages/release-page.tsx +++ b/src/features/tech-log/presentation/public/pages/release-page.tsx @@ -8,7 +8,10 @@ import { usePublicContent } from "../use-public-content.tsx"; import { ProseText } from "../../shared/public-render/prose-text.tsx"; import { useDocumentMetadata } from "../../shared/use-document-metadata.ts"; +import { publicRoutes } from "../public-routes.ts"; +import { useLocale } from "../../../../../presentation/i18n/index.ts"; export function ReleasePage() { + const { message } = useLocale(); const { params } = useRouteInput<"TECH_LOG_RELEASE">(); const version = typeof params.version === "string" ? params.version : ""; const view = usePublicContent(["tech-log", "release", version], async (queries) => ({ @@ -30,8 +33,8 @@ export function ReleasePage() { return (
      -
      {topics.length === 0 ? ( -

      아직 공개된 주제가 없습니다.

      +

      {}

      ) : (
        {topics.map((topic) => (
      • - + {topic.name} {/* 논지가 있으면 그것이 이 주제를 고르는 근거다. 아직 쓰지 않았으면 설명으로 diff --git a/src/features/tech-log/presentation/public/public-routes.ts b/src/features/tech-log/presentation/public/public-routes.ts new file mode 100644 index 0000000..2b50a9b --- /dev/null +++ b/src/features/tech-log/presentation/public/public-routes.ts @@ -0,0 +1,124 @@ +import { buildRouteUrlFromContract } from "../../../../presentation/routes/route-url-builder.ts"; +import { PLATFORM_ROUTE_CODECS } from "../../../../presentation/routes/platform-route-codecs.ts"; +import { + TECH_LOG_ROUTE_REGISTRY, + TECH_LOG_ROUTE_RUNTIME_CONTRACT, + type TechLogRouteId, +} from "../../contracts/tech-log-route-contract.ts"; +import { TECH_LOG_ROUTE_CODECS } from "../tech-log-route-codecs.ts"; + +const routeCodecs = Object.freeze({ + ...PLATFORM_ROUTE_CODECS, + ...TECH_LOG_ROUTE_CODECS, +}); + +function parameterPrefix( + routeId: TechLogRouteId, + parameter: string, +): string { + const template = TECH_LOG_ROUTE_REGISTRY[routeId].path; + const marker = `:${parameter}`; + const markerIndex = template.indexOf(marker); + if (markerIndex < 0) { + throw new TypeError( + `Route ${routeId} does not declare parameter ${parameter}.`, + ); + } + return template.slice(0, markerIndex); +} + +export const publicRoutePrefixes = Object.freeze({ + case: parameterPrefix("TECH_LOG_CASE", "slug"), + reference: parameterPrefix("TECH_LOG_REFERENCE", "slug"), + concept: parameterPrefix("TECH_LOG_CONCEPT", "slug"), + question: parameterPrefix("TECH_LOG_QUESTION", "slug"), + project: parameterPrefix("TECH_LOG_PROJECT", "slug"), +}); + +function buildPublicRoute( + routeId: TechLogRouteId, + input: Readonly<{ + params?: Readonly>; + search?: Readonly>; + }> = {}, +): string { + return buildRouteUrlFromContract( + TECH_LOG_ROUTE_REGISTRY[routeId], + TECH_LOG_ROUTE_RUNTIME_CONTRACT[routeId], + routeCodecs, + input, + ); +} + +export const publicRoutes = Object.freeze({ + home(search: Readonly> = {}): string { + return buildPublicRoute("TECH_LOG_HOME", { search }); + }, + explore(search: Readonly> = {}): string { + return buildPublicRoute("TECH_LOG_EXPLORE", { search }); + }, + exploreKind( + kind: string, + search: Readonly> = {}, + ): string { + return buildPublicRoute("TECH_LOG_EXPLORE_KIND", { + params: { kind }, + search, + }); + }, + case(slug: string, search: Readonly> = {}): string { + return buildPublicRoute("TECH_LOG_CASE", { params: { slug }, search }); + }, + reference(slug: string): string { + return buildPublicRoute("TECH_LOG_REFERENCE", { params: { slug } }); + }, + concept(slug: string): string { + return buildPublicRoute("TECH_LOG_CONCEPT", { params: { slug } }); + }, + setup(slug: string): string { + return buildPublicRoute("TECH_LOG_SETUP", { params: { slug } }); + }, + question(slug: string): string { + return buildPublicRoute("TECH_LOG_QUESTION", { params: { slug } }); + }, + topics(): string { + return buildPublicRoute("TECH_LOG_TOPICS"); + }, + topic(slug: string): string { + return buildPublicRoute("TECH_LOG_TOPIC", { params: { slug } }); + }, + topicVariant(slug: string, variant: string): string { + return buildPublicRoute("TECH_LOG_TOPIC_VARIANT", { + params: { slug, variant }, + }); + }, + projects(): string { + return buildPublicRoute("TECH_LOG_PROJECTS"); + }, + project(slug: string): string { + return buildPublicRoute("TECH_LOG_PROJECT", { params: { slug } }); + }, + projectRecords(slug: string): string { + return buildPublicRoute("TECH_LOG_PROJECT_RECORDS", { params: { slug } }); + }, + projectDecisions(slug: string): string { + return buildPublicRoute("TECH_LOG_PROJECT_DECISIONS", { + params: { slug }, + }); + }, + projectActivity(slug: string): string { + return buildPublicRoute("TECH_LOG_PROJECT_ACTIVITY", { params: { slug } }); + }, + releases(): string { + return buildPublicRoute("TECH_LOG_RELEASES"); + }, + release(version: string): string { + return buildPublicRoute("TECH_LOG_RELEASE", { params: { version } }); + }, + profile(): string { + return buildPublicRoute("TECH_LOG_PROFILE"); + }, + search(search: Readonly> = {}): string { + return buildPublicRoute("TECH_LOG_SEARCH", { search }); + }, +}); diff --git a/src/features/tech-log/presentation/public/public-shell.tsx b/src/features/tech-log/presentation/public/public-shell.tsx index e9b5c7e..1f7dd8f 100644 --- a/src/features/tech-log/presentation/public/public-shell.tsx +++ b/src/features/tech-log/presentation/public/public-shell.tsx @@ -4,6 +4,7 @@ import { Link } from "react-router-dom"; import { publicSiteConfig } from "../../contracts/public-site-config.ts"; import { SiteHeader } from "./components/site-header.tsx"; +import { TechLogMessage } from "../tech-log-message.tsx"; type PublicShellProps = { children: ReactNode; currentPath?: string; @@ -29,7 +30,7 @@ export function PublicShell({ children, currentPath }: PublicShellProps) { {publicSiteConfig.contactLabel} - 변경 기록 + {}
    diff --git a/src/features/tech-log/presentation/shared/public-render/code-block.tsx b/src/features/tech-log/presentation/shared/public-render/code-block.tsx index bbcd3c9..9ef03e1 100644 --- a/src/features/tech-log/presentation/shared/public-render/code-block.tsx +++ b/src/features/tech-log/presentation/shared/public-render/code-block.tsx @@ -1,3 +1,4 @@ +import { Button } from "../../../../../presentation/design-system/index.ts"; import { useEffect, useRef, useState } from "react"; type CodeBlockProps = { @@ -47,9 +48,9 @@ export function CodeBlock({
    {language} {label} - +
             {code}
    diff --git a/src/features/tech-log/presentation/shared/public-render/evidence-figure.tsx b/src/features/tech-log/presentation/shared/public-render/evidence-figure.tsx
    index c597115..39a1bfc 100644
    --- a/src/features/tech-log/presentation/shared/public-render/evidence-figure.tsx
    +++ b/src/features/tech-log/presentation/shared/public-render/evidence-figure.tsx
    @@ -1,6 +1,11 @@
    -import { useId, useRef } from "react";
    +import { useId, useRef, useState } from "react";
     
     import type { ResolveEvidenceAsset } from "../../../domain/public-render-content.ts";
    +import {
    +  Button,
    +  Dialog,
    +} from "../../../../../presentation/design-system/index.ts";
    +import { useLocale } from "../../../../../presentation/i18n/index.ts";
     
     type PublicEvidenceFigureProps = {
       evidenceKey: string;
    @@ -17,18 +22,11 @@ export function PublicEvidenceFigure({
       zoom,
       resolveEvidenceAsset,
     }: PublicEvidenceFigureProps) {
    +  const { message } = useLocale();
       const asset = resolveEvidenceAsset(evidenceKey);
       const descriptionId = useId();
       const triggerRef = useRef(null);
    -  const dialogRef = useRef(null);
    -
    -  function open() {
    -    dialogRef.current?.showModal();
    -  }
    -
    -  function close() {
    -    dialogRef.current?.close();
    -  }
    +  const [open, setOpen] = useState(false);
     
       /**
        * 치수를 아는 그림만 자리를 미리 잡는다. 모르는데 숫자를 적으면 그 상자가 진짜 크기가 되고,
    @@ -61,40 +59,37 @@ export function PublicEvidenceFigure({
       return (
         <>
           
    - +
    {caption}
    - triggerRef.current?.focus()} - onClick={(event) => { - if (event.target === event.currentTarget) close(); - }} + closeLabel={message("techLog.action.close")} + onClose={() => setOpen(false)} + open={open} + returnFocusRef={triggerRef} + title={asset.dialogLabel} > -
    - +
    {alt}

    {caption}

    -
    +
); } diff --git a/src/features/tech-log/presentation/shared/public-render/public-record-renderer.tsx b/src/features/tech-log/presentation/shared/public-render/public-record-renderer.tsx index de1c462..dd2512a 100644 --- a/src/features/tech-log/presentation/shared/public-render/public-record-renderer.tsx +++ b/src/features/tech-log/presentation/shared/public-render/public-record-renderer.tsx @@ -18,6 +18,8 @@ import { import { DOCUMENT_KIND_LABELS } from "../document-kind-labels.ts"; import { useDocumentMetadata } from "../use-document-metadata.ts"; +import { publicRoutes } from "../../public/public-routes.ts"; +import { useLocale } from "../../../../../presentation/i18n/index.ts"; type PublicRenderModel = components["schemas"]["PublicRenderModel"]; type PublicRenderModelBase = components["schemas"]["PublicRenderModelBase"]; type ResolvedRelation = components["schemas"]["ResolvedRelation"]; @@ -563,6 +565,7 @@ function QuestionDocument({ resolvePublishedLabel: ResolvePublishedLabel; navigation?: RecordNavigation; }) { + const { message } = useLocale(); const resolutionPath = model.resolution?.evidenceTarget.publicPath; const Root = embedded ? "div" : "main"; const railSections = [ @@ -611,14 +614,14 @@ function QuestionDocument({

가정

남은 미지수

@@ -680,6 +683,7 @@ function ProjectDecisionDocument({ model: ProjectDecisionPublicRenderModel; embedded: boolean; }) { + const { message } = useLocale(); const Root = embedded ? "div" : "main"; const evidence = publicRelations(model.relations); return ( @@ -688,7 +692,7 @@ function ProjectDecisionDocument({ className={`shell project-page${embedded ? " public-record-embedded" : ""}`} >

영향

- +

근거 기록

@@ -738,7 +742,7 @@ function ProjectDecisionDocument({ ))} ) : ( -

연결한 근거 기록이 없습니다.

+

{message("techLog.state.noEvidence")}

)}
diff --git a/src/features/tech-log/presentation/studio/components/asset-library.tsx b/src/features/tech-log/presentation/studio/components/asset-library.tsx index 114af00..0b605d6 100644 --- a/src/features/tech-log/presentation/studio/components/asset-library.tsx +++ b/src/features/tech-log/presentation/studio/components/asset-library.tsx @@ -1,12 +1,20 @@ -import { useEffect, useId, useRef, useState, type FormEvent } from "react"; +import { useTechLogCopy } from "../studio-copy.ts"; +import { studioRoutes } from "../studio-routes.ts"; import { DestructiveConfirmDialog } from "./destructive-confirm-dialog.tsx"; +import { useAssetLibraryController } from "../controllers/use-asset-library-controller.ts"; import type { Asset, AssetDetail } from "../../../contracts/studio/contract.ts"; type AssetKind = Asset["kind"]; -import type { StudioAssetGateway } from "../../../application/ports/studio-asset-gateway.ts"; -import { isStudioGatewayError } from "../../../application/ports/studio-gateway-error.ts"; -import { createLocalId } from "../../../domain/studio/local-id.ts"; +import { + Button, + Checkbox, + SearchFilterToolbar, + Select, + TextArea, + TextField, +} from "../../../../../presentation/design-system/index.ts"; +import { Form } from "../../../../../presentation/forms/index.ts"; /** 관리 상태. 화면에 영문 상수가 그대로 나오던 자리다. */ const ASSET_STATUS_LABELS: Record = { @@ -31,9 +39,6 @@ function byteLabel(bytes: number): string { return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; } -/** `document-list.tsx`'s page size for the same screen shape. */ -const PAGE_SIZE = 20; - /** * 공개 이력이 있거나 사용 중인 Asset은 hard delete하지 않는다. 서버도 같은 * 규칙으로 `ASSET_IN_USE`를 던지므로 화면은 시도 자체를 막아 왕복을 줄인다. @@ -46,267 +51,43 @@ export function canHardDelete(detail: AssetDetail): boolean { ); } -function isAbortError(error: unknown): boolean { - return error instanceof DOMException && error.name === "AbortError"; -} - -export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) { - const [assets, setAssets] = useState([]); - const [listStatus, setListStatus] = useState<"LOADING" | "ERROR" | "READY">( - "LOADING", - ); - // Alignment follow-up, item 1. `q` is the *submitted* query, `searchDraft` - // what the user is currently typing. Only `q` is an effect dependency, so - // typing costs nothing -- `document-list.tsx` splits the same pair for the - // same reason, and it is a stronger guarantee than a debounce: exactly one - // request per deliberate search, never a trailing one after the user stops. - const [searchDraft, setSearchDraft] = useState(""); - const [q, setQ] = useState(""); - /* - 종류는 서버가 걸러 준다(`kind`). 쓰임 여부는 계약에 없는 조건이라 받아 온 목록에서 거른다 — - 다음 쪽에 있는 것까지 세지는 못하므로 그 사실을 화면에 적는다. 없는 필터를 있는 척하는 것이 - 가장 나쁘다. - */ - const [kindFilter, setKindFilter] = useState(""); - const [usageFilter, setUsageFilter] = useState<"" | "USED" | "UNUSED">(""); - const [nextCursor, setNextCursor] = useState(null); - const [morePending, setMorePending] = useState(false); - const [selected, setSelected] = useState(null); - const [pending, setPending] = useState(false); - const [notice, setNotice] = useState(""); - const [confirmDelete, setConfirmDelete] = useState(false); - // Wrapped in an object, not a bare `string | null`: the "no appended row to - // land on" case still needs a focus move (to the page heading), and a bare - // null cannot express "a move is pending, target unknown". - const [moreFocus, setMoreFocus] = useState<{ id: string | null } | null>(null); - const triggerRef = useRef(null); - const detailHeadingRef = useRef(null); - const pageHeadingRef = useRef(null); - const rowRefs = useRef(new Map()); - const openAssetId = useRef(null); - const searchId = useId(); - - useEffect(() => { - const controller = new AbortController(); - // `active` rather than the abort signal alone: `RequestOptions.signal` is - // advisory -- an adapter that ignores it still resolves, and a search the - // user has already replaced would then paint stale rows over the newer - // ones. This flag flips synchronously the moment `q` changes, so an - // abandoned response can never reach `setAssets`. - let active = true; - setListStatus("LOADING"); - props.gateway - .listAssets( - { ...(q ? { q } : {}), ...(kindFilter ? { kind: kindFilter } : {}), limit: PAGE_SIZE }, - { signal: controller.signal }, - ) - .then((page) => { - if (!active) return; - setAssets(page.items); - setNextCursor(page.nextCursor); - setListStatus("READY"); - }) - .catch((error: unknown) => { - if (!active || isAbortError(error)) return; - // The `role="alert"` paragraph below is the sole announcement for a - // load failure -- also routing it through `notice`'s `role="status"` - // paragraph would announce the same sentence twice. - setListStatus("ERROR"); - }); - return () => { - active = false; - controller.abort(); - }; - }, [props.gateway, q, kindFilter]); - - // A freshly opened detail panel should take focus so keyboard and screen - // reader users land on it without hunting; re-rendering the same asset - // (e.g. after archiving it) must not steal focus back from whatever the - // user is doing next. - useEffect(() => { - if (selected && openAssetId.current !== selected.asset.id) { - detailHeadingRef.current?.focus(); - } - openAssetId.current = selected?.asset.id ?? null; - }, [selected]); - - // Alignment follow-up, item 1. "더 보기" disappears once the server reports - // no further cursor, so keeping focus on it would strand focus on `` - // exactly when the last page arrives. Moving to the first appended row is - // unconditional -- it cannot depend on whether the control survived -- and - // it puts the user at the content they asked for. Run as an effect (not - // inline after `await`) so the row is committed and its ref attached. - useEffect(() => { - if (!moreFocus) return; - const row = moreFocus.id ? rowRefs.current.get(moreFocus.id) : undefined; - // The page heading is the fallback the delete path already relies on: the - // one node in this screen that survives every list change. - (row ?? pageHeadingRef.current)?.focus(); - setMoreFocus(null); - }, [moreFocus]); - - async function openDetail(asset: Asset, trigger: HTMLButtonElement) { - triggerRef.current = trigger; - try { - const detail = await props.gateway.getAsset(asset.id); - setSelected(detail); - } catch { - setNotice("Asset 상세를 불러오지 못했습니다."); - } - } - - function submitSearch(event: FormEvent) { - event.preventDefault(); - // A new query restarts paging: `nextCursor` was issued against the old - // query's ordering and means nothing under the new one. - setSelected(null); - setNextCursor(null); - setQ(searchDraft.trim()); - } - - async function loadMore() { - if (!nextCursor || morePending) return; - const cursor = nextCursor; - setMorePending(true); - try { - const page = await props.gateway.listAssets({ - ...(q ? { q } : {}), - ...(kindFilter ? { kind: kindFilter } : {}), - cursor, - limit: PAGE_SIZE, - }); - // Append, never replace -- and drop anything already on screen so a - // server that re-sends a boundary row cannot produce a duplicate React - // key (or a duplicate row for the reader). The dedupe lives inside the - // updater so it reads the committed list; the focus target is derived - // separately from the rendered `assets`, because a state updater is not - // invoked synchronously and must stay free of side effects. - const known = new Set(assets.map((item) => item.id)); - const appended = page.items.filter((item) => !known.has(item.id)); - setAssets((current) => { - const seen = new Set(current.map((item) => item.id)); - return [...current, ...page.items.filter((item) => !seen.has(item.id))]; - }); - setNextCursor(page.nextCursor); - setMoreFocus({ id: appended[0]?.id ?? page.items[0]?.id ?? null }); - } catch (error) { - setNotice( - isStudioGatewayError(error) - ? error.problem.detail - : "다음 Asset을 불러오지 못했습니다.", - ); - } finally { - setMorePending(false); - } - } - - // Dismissing the panel without changing the list (cancel/close): the row - // that opened it is still on screen, so restore focus there. - function closeDetail() { - setSelected(null); - queueMicrotask(() => triggerRef.current?.focus()); - } - - // Fix round 1 (I1). A successful delete removes the row from `assets`, so - // by the time this runs `triggerRef.current` -- still set, since React - // never nulls a plain ref -- points at a button that is no longer attached - // to the document. `.focus()` on a detached element is a silent no-op, so - // reusing `closeDetail` here left focus stranded on ``. The page - // heading is the one thing in this screen guaranteed to survive any list - // change (the list itself can disappear into the empty state), so a - // deletion moves focus there instead of trying to reuse a node it just - // destroyed. - function closeDetailAfterRemoval() { - setSelected(null); - queueMicrotask(() => pageHeadingRef.current?.focus()); - } - - async function archive(detail: AssetDetail) { - setPending(true); - try { - const updated = await props.gateway.updateAssetMetadata( - detail.asset.id, - { expectedVersion: detail.asset.version, managementStatus: "ARCHIVED" }, - { idempotencyKey: createLocalId("studio-asset-archive") }, - ); - setAssets((current) => - current.map((item) => (item.id === updated.id ? updated : item)), - ); - setSelected({ ...detail, asset: updated }); - setNotice("보관했습니다."); - } catch (error) { - setNotice( - isStudioGatewayError(error) ? error.problem.detail : "보관하지 못했습니다.", - ); - } finally { - setPending(false); - } - } - - async function remove(detail: AssetDetail) { - setPending(true); - try { - await props.gateway.deleteAsset(detail.asset.id, { - idempotencyKey: createLocalId("studio-asset-delete"), - }); - setAssets((current) => current.filter((item) => item.id !== detail.asset.id)); - setNotice("삭제했습니다."); - setConfirmDelete(false); - closeDetailAfterRemoval(); - } catch (error) { - setNotice( - isStudioGatewayError(error) ? error.problem.detail : "삭제하지 못했습니다.", - ); - } finally { - setPending(false); - } - } - - const [altDraft, setAltDraft] = useState(""); - const [decorativeDraft, setDecorativeDraft] = useState(false); - - /* 상세를 열 때마다 그 자료의 값으로 칸을 맞춘다 — 앞서 보던 자료의 글이 남아 있으면 안 된다. */ - useEffect(() => { - setAltDraft(selected?.asset.altText ?? ""); - setDecorativeDraft(selected?.asset.decorative ?? false); - }, [selected?.asset.id, selected?.asset.altText, selected?.asset.decorative]); - - const saveAltText = async () => { - const detail = selected; - if (!detail || pending) return; - setPending(true); - setNotice(""); - try { - const updated = await props.gateway.updateAssetMetadata( - detail.asset.id, - { - expectedVersion: detail.asset.version, - altText: altDraft.trim() ? altDraft : null, - decorative: decorativeDraft, - }, - { idempotencyKey: createLocalId("studio-asset-alt") }, - ); - setAssets((current) => - current.map((item) => (item.id === updated.id ? updated : item)), - ); - setSelected({ ...detail, asset: updated }); - setNotice("대체 텍스트를 저장했습니다."); - } catch (error) { - setNotice( - isStudioGatewayError(error) ? error.problem.detail : "저장하지 못했습니다.", - ); - } finally { - setPending(false); - } - }; - - const visibleAssets = assets.filter((asset) => - usageFilter === "USED" - ? asset.usageCount > 0 - : usageFilter === "UNUSED" - ? asset.usageCount === 0 - : true, - ); +export function AssetLibrary() { + const copy = useTechLogCopy(); + const { + assets, + assetResultCount, + altDraft, + archive, + closeDetail, + confirmDelete, + decorativeDraft, + detailHeadingRef, + kindFilter, + listStatus, + loadMore, + morePending, + nextCursor, + notice, + openDetail, + pageHeadingRef, + pending, + q, + remove, + resetFilters, + rowRefs, + saveAltText, + searchDraft, + selected, + setAltDraft, + setConfirmDelete, + setDecorativeDraft, + setKindFilter, + setSearchDraft, + setUsageFilter, + submitSearch, + usageFilter, + visibleAssets, + } = useAssetLibraryController(); return (
@@ -319,55 +100,66 @@ export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) {

-
-
- -
- setSearchDraft(event.target.value)} - /> - -
-
- {/* - 종류는 서버가 걸러 준다. 쓰임 여부는 계약에 없어 받아 온 목록에서 거르므로, 다음 쪽에 - 있는 것까지 세지 못한다는 사실을 함께 적는다 — 없는 필터를 있는 척하지 않는다. - */} -
- - - {usageFilter ? ( - 불러온 목록 안에서만 거릅니다. - ) : null} -
-
+ /> +
+ } + /> {/* 확인 창이 열려 있는 동안에는 같은 문구를 창 안에서만 말한다. 두 벌이 화면에 남으면 읽는 @@ -379,30 +171,25 @@ export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) { {listStatus === "LOADING" ? (

- Asset 목록을 불러오는 중입니다. + {copy("techLog.state.assetListLoading")}

) : null} {listStatus === "ERROR" ? (

- Asset 목록을 불러오지 못했습니다. + {copy("techLog.state.assetListLoadFailed")}

) : null} - {/* The list changing is otherwise silent: a search replaces every row - and "더 보기" appends without moving anything the reader can see. */} -

- {listStatus === "READY" ? `${assets.length}개의 Asset` : ""} -

{listStatus === "READY" && assets.length === 0 ? (
{q ? ( <> -

조건에 맞는 Asset이 없습니다

-

검색어를 바꾸거나 비우면 전체 Asset을 다시 볼 수 있습니다.

+

{copy("techLog.state.emptyAssetSearch")}

+

{copy("techLog.state.emptyAssetSearchHint")}

) : ( <> -

등록된 Asset이 없습니다

-

Case 편집 화면에서 Asset을 업로드하면 여기에서 관리할 수 있습니다.

+

{copy("techLog.state.emptyAssetLibrary")}

+

{copy("techLog.state.emptyAssetLibraryHint")}

)}
@@ -433,23 +220,22 @@ export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) { 가리키는 불변 식별자이지 사람이 기억하는 이름이 아니다. 이름을 앞에 두고 key 는 아래에 작게 남긴다. */} - + {ASSET_STATUS_LABELS[asset.managementStatus]} {/* 쓰이지 않는 자료는 지워도 되는 것이고, 쓰이는 자료는 지우면 화면이 깨진다. 그 @@ -465,14 +251,17 @@ export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) { ) : null} {nextCursor && listStatus === "READY" ? ( - + {copy("techLog.action.more")} + ) : null} {selected ? ( @@ -508,35 +297,43 @@ export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) { 설명(caption)은 여기 없다. 같은 그림을 다른 기록에서 다른 말로 설명할 수 있어서 자료가 아니라 본문이 갖는 값이다(`:::evidence caption=…`). */} -
{ event.preventDefault(); void saveAltText(); }} > - -