From 7b35f6b5514ed8ff191fecd91067468294bac46f Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 20:39:06 +0900 Subject: [PATCH 001/178] feat: bootstrap Vite and pnpm toolchain contract --- .gitignore | 11 + .npmrc | 2 + .nvmrc | 1 + artifacts/performance/.gitkeep | 1 + artifacts/quality/.gitkeep | 1 + artifacts/release/.gitkeep | 1 + artifacts/runbooks/.gitkeep | 1 + artifacts/security/.gitkeep | 1 + artifacts/tests/.gitkeep | 1 + index.html | 13 + package.json | 30 + pnpm-lock.yaml | 798 ++++++++++++++++++ scripts/generate-build-manifest.mjs | 30 + src/bootstrap/main.jsx | 23 + tests/fixtures/typecheck/invalid-port-call.js | 8 + tsconfig.json | 20 + vite.config.js | 10 + 17 files changed, 952 insertions(+) create mode 100644 .gitignore create mode 100644 .npmrc create mode 100644 .nvmrc create mode 100644 artifacts/performance/.gitkeep create mode 100644 artifacts/quality/.gitkeep create mode 100644 artifacts/release/.gitkeep create mode 100644 artifacts/runbooks/.gitkeep create mode 100644 artifacts/security/.gitkeep create mode 100644 artifacts/tests/.gitkeep create mode 100644 index.html create mode 100644 package.json create mode 100644 pnpm-lock.yaml create mode 100644 scripts/generate-build-manifest.mjs create mode 100644 src/bootstrap/main.jsx create mode 100644 tests/fixtures/typecheck/invalid-port-call.js create mode 100644 tsconfig.json create mode 100644 vite.config.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..b25eba7f --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +node_modules/ +dist/ +.vite/ +playwright-report/ +test-results/ +coverage/ +artifacts/**/*.json +artifacts/**/*.xml +artifacts/**/*.txt +artifacts/**/*.sarif +!artifacts/**/.gitkeep diff --git a/.npmrc b/.npmrc new file mode 100644 index 00000000..d9ca8860 --- /dev/null +++ b/.npmrc @@ -0,0 +1,2 @@ +engine-strict=true +save-exact=true diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 00000000..d845d9d8 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +24.14.0 diff --git a/artifacts/performance/.gitkeep b/artifacts/performance/.gitkeep new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/artifacts/performance/.gitkeep @@ -0,0 +1 @@ + diff --git a/artifacts/quality/.gitkeep b/artifacts/quality/.gitkeep new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/artifacts/quality/.gitkeep @@ -0,0 +1 @@ + diff --git a/artifacts/release/.gitkeep b/artifacts/release/.gitkeep new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/artifacts/release/.gitkeep @@ -0,0 +1 @@ + diff --git a/artifacts/runbooks/.gitkeep b/artifacts/runbooks/.gitkeep new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/artifacts/runbooks/.gitkeep @@ -0,0 +1 @@ + diff --git a/artifacts/security/.gitkeep b/artifacts/security/.gitkeep new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/artifacts/security/.gitkeep @@ -0,0 +1 @@ + diff --git a/artifacts/tests/.gitkeep b/artifacts/tests/.gitkeep new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/artifacts/tests/.gitkeep @@ -0,0 +1 @@ + diff --git a/index.html b/index.html new file mode 100644 index 00000000..bc72e406 --- /dev/null +++ b/index.html @@ -0,0 +1,13 @@ + + + + + + + Clean Architecture Frontend + + +
+ + + diff --git a/package.json b/package.json new file mode 100644 index 00000000..1bba499a --- /dev/null +++ b/package.json @@ -0,0 +1,30 @@ +{ + "name": "clean-architecture-frontend-template", + "version": "0.1.0", + "private": true, + "type": "module", + "packageManager": "pnpm@11.17.0", + "engines": { + "node": ">=24.0.0 <25.0.0", + "pnpm": ">=11.0.0 <12.0.0" + }, + "scripts": { + "dev": "vite", + "build": "vite build && node scripts/generate-build-manifest.mjs", + "preview": "vite preview", + "check:types": "tsc --allowJs --checkJs --noEmit", + "check:types:fixture": "tsc --allowJs --checkJs --noEmit --target ES2022 --module NodeNext --moduleResolution NodeNext tests/fixtures/typecheck/invalid-port-call.js" + }, + "dependencies": { + "react": "19.2.8", + "react-dom": "19.2.8" + }, + "devDependencies": { + "@types/node": "24.13.3", + "@types/react": "19.2.8", + "@types/react-dom": "19.2.3", + "@vitejs/plugin-react": "6.0.4", + "typescript": "7.0.2", + "vite": "8.1.5" + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 00000000..163049b8 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,798 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + react: + specifier: 19.2.8 + version: 19.2.8 + react-dom: + specifier: 19.2.8 + version: 19.2.8(react@19.2.8) + devDependencies: + '@types/node': + specifier: 24.13.3 + version: 24.13.3 + '@types/react': + specifier: 19.2.8 + version: 19.2.8 + '@types/react-dom': + specifier: 19.2.3 + version: 19.2.3(@types/react@19.2.8) + '@vitejs/plugin-react': + specifier: 6.0.4 + version: 6.0.4(vite@8.1.5(@types/node@24.13.3)) + typescript: + specifier: 7.0.2 + version: 7.0.2 + vite: + specifier: 8.1.5 + version: 8.1.5(@types/node@24.13.3) + +packages: + + '@emnapi/core@1.11.1': + resolution: {integrity: sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==} + + '@emnapi/runtime@1.11.1': + resolution: {integrity: sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==} + + '@emnapi/wasi-threads@1.2.2': + resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==} + + '@napi-rs/wasm-runtime@1.1.6': + resolution: {integrity: sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==} + peerDependencies: + '@emnapi/core': ^1.7.1 + '@emnapi/runtime': ^1.7.1 + + '@oxc-project/types@0.139.0': + resolution: {integrity: sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw==} + + '@rolldown/binding-android-arm64@1.1.5': + resolution: {integrity: sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.1.5': + resolution: {integrity: sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.1.5': + resolution: {integrity: sha512-Tm+gbfC0aHu1tBA/JvKQh32S0K6YgCHkiAF4/W6xX0K0RmNuc94VeK419dJoE65R5aRxmo+noZQSWrAMF6yb6g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.1.5': + resolution: {integrity: sha512-JMzDKCCXq93YccG5gz3hvOs1oXRKAf0XYpfOS88e+wZrC8Iugj6j68867vrYZkvpDDpKn/KoKORThmchMpF6TA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.1.5': + resolution: {integrity: sha512-uML21j2K5TfPGutKxub+M+nLjZIrWjXQ5Grx4lCe/nimTj9B4L63zHpjXLl4y0L3mcm2htEQIb06oCG/szerNw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.1.5': + resolution: {integrity: sha512-navSiuTMogvnQoZoM/v+l3ZWo50/NTwSHSzheABx/RCnmUPaKwq9qSo4Br2OYRs21+Fz8uFqITZM3H4opOB0/Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.1.5': + resolution: {integrity: sha512-lAryqH7IteztmCXQXk0etKj4wBQ7Gx5S6LjKhsgp9zb8I5bsuvU/2llH1hDQcjsFeqIsovMVN339/8pUDDBXxA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.1.5': + resolution: {integrity: sha512-fsK/sNBnxzBlL4O1JNrZakVQxPspqpED5dLtNsZS9oOKmtSpdNIzxH2kkol5HYTWJN47sE20ztMJPxfZ89qGOg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.1.5': + resolution: {integrity: sha512-gLYb4BIadlfTOYT5gO503n8zQjXflgzpD0FcyKh0Mzx3rqCZKnHoJWV9xe1KXUJ5lx2JfcSHr/mhzS0PC/McAA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.1.5': + resolution: {integrity: sha512-FjcpEKUyJygHgs1o50VYNvkt5+7Le/VEdYt0AkRpkL33MnyQfwr8l5mXwMmfmTbyMPr5vJLC+8/Gd9gXnwU1QQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.1.5': + resolution: {integrity: sha512-Me+PfPI2TMeOQk0gYWfLQZtTktrmzbr8cDboqX83XKc7UrgAi55gF+2dUkWdxd19n55Essp2yeca+O9N5rBxHg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.1.5': + resolution: {integrity: sha512-yc5WrLzXks6zCQfn9Oxr8pORKyl/pF+QjHmW/Qx3qu0oyrrNC+y2JLTU1E2rcWYAmzlnqngWXHQjy51VzW70Vw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-wasm32-wasi@1.1.5': + resolution: {integrity: sha512-VbQGPX2b4r48TAMIM2cjgluIM1HYutm4pcTEJsle7iEP7sB1dFqtPLBVbdLAZCxy1txCcPxf4QFf4v8uvltPqA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [wasm32] + + '@rolldown/binding-win32-arm64-msvc@1.1.5': + resolution: {integrity: sha512-gHv82k63z4qpV5+Q1y/12KrK0ltWBukVDI8nZcbT7Tt/ZlOIVwppazneq0F93oDxTo3IgAMEDIoQh3E2n6mVsw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.1.5': + resolution: {integrity: sha512-tTZuDBPw85tEN5PQi1pnEBzDy0Z49HtScLAbD5t6hyeU92A95pRWaSMw1GZZi/RwgSgUIl0xrSlXIT/9QzvYSA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@tybys/wasm-util@0.10.3': + resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==} + + '@types/node@24.13.3': + resolution: {integrity: sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==} + + '@types/react-dom@19.2.3': + resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==} + peerDependencies: + '@types/react': ^19.2.0 + + '@types/react@19.2.8': + resolution: {integrity: sha512-3MbSL37jEchWZz2p2mjntRZtPt837ij10ApxKfgmXCTuHWagYg7iA5bqPw6C8BMPfwidlvfPI/fxOc42HLhcyg==} + + '@typescript/typescript-aix-ppc64@7.0.2': + resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [aix] + + '@typescript/typescript-darwin-arm64@7.0.2': + resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [darwin] + + '@typescript/typescript-darwin-x64@7.0.2': + resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [darwin] + + '@typescript/typescript-freebsd-arm64@7.0.2': + resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [freebsd] + + '@typescript/typescript-freebsd-x64@7.0.2': + resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [freebsd] + + '@typescript/typescript-linux-arm64@7.0.2': + resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [linux] + + '@typescript/typescript-linux-arm@7.0.2': + resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} + engines: {node: '>=16.20.0'} + cpu: [arm] + os: [linux] + + '@typescript/typescript-linux-loong64@7.0.2': + resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} + engines: {node: '>=16.20.0'} + cpu: [loong64] + os: [linux] + + '@typescript/typescript-linux-mips64el@7.0.2': + resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} + engines: {node: '>=16.20.0'} + cpu: [mips64el] + os: [linux] + + '@typescript/typescript-linux-ppc64@7.0.2': + resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [linux] + + '@typescript/typescript-linux-riscv64@7.0.2': + resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} + engines: {node: '>=16.20.0'} + cpu: [riscv64] + os: [linux] + + '@typescript/typescript-linux-s390x@7.0.2': + resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} + engines: {node: '>=16.20.0'} + cpu: [s390x] + os: [linux] + + '@typescript/typescript-linux-x64@7.0.2': + resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [linux] + + '@typescript/typescript-netbsd-arm64@7.0.2': + resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [netbsd] + + '@typescript/typescript-netbsd-x64@7.0.2': + resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [netbsd] + + '@typescript/typescript-openbsd-arm64@7.0.2': + resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [openbsd] + + '@typescript/typescript-openbsd-x64@7.0.2': + resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [openbsd] + + '@typescript/typescript-sunos-x64@7.0.2': + resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [sunos] + + '@typescript/typescript-win32-arm64@7.0.2': + resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [win32] + + '@typescript/typescript-win32-x64@7.0.2': + resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [win32] + + '@vitejs/plugin-react@6.0.4': + resolution: {integrity: sha512-XcCQz0TBpBgljhj0gMuuDj49i6Ytqh5q1osT/Gp5uAVJUCTWxyskk/l1jwYYiu2xcNHHipdMz40EGfM1VdamVg==} + engines: {node: ^20.19.0 || >=22.12.0} + peerDependencies: + '@rolldown/plugin-babel': ^0.1.7 || ^0.2.0 + babel-plugin-react-compiler: ^1.0.0 + vite: ^8.0.0 + peerDependenciesMeta: + '@rolldown/plugin-babel': + optional: true + babel-plugin-react-compiler: + optional: true + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + nanoid@3.3.16: + resolution: {integrity: sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.5: + resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==} + engines: {node: '>=12'} + + postcss@8.5.22: + resolution: {integrity: sha512-KBDEIpLrvpv16pp3K0Fw+UCoZfopFjjgeB+0tA/aaThfEE74kKDLrgg603YvOWJyg3+WYtyq3xYsQWsIyZlPqQ==} + engines: {node: ^10 || ^12 || >=14} + + react-dom@19.2.8: + resolution: {integrity: sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==} + peerDependencies: + react: ^19.2.8 + + react@19.2.8: + resolution: {integrity: sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==} + engines: {node: '>=0.10.0'} + + rolldown@1.1.5: + resolution: {integrity: sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + scheduler@0.27.0: + resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + + typescript@7.0.2: + resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} + engines: {node: '>=16.20.0'} + hasBin: true + + undici-types@7.18.2: + resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==} + + vite@8.1.5: + resolution: {integrity: sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.3.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + +snapshots: + + '@emnapi/core@1.11.1': + dependencies: + '@emnapi/wasi-threads': 1.2.2 + tslib: 2.8.1 + optional: true + + '@emnapi/runtime@1.11.1': + dependencies: + tslib: 2.8.1 + optional: true + + '@emnapi/wasi-threads@1.2.2': + dependencies: + tslib: 2.8.1 + optional: true + + '@napi-rs/wasm-runtime@1.1.6(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)': + dependencies: + '@emnapi/core': 1.11.1 + '@emnapi/runtime': 1.11.1 + '@tybys/wasm-util': 0.10.3 + optional: true + + '@oxc-project/types@0.139.0': {} + + '@rolldown/binding-android-arm64@1.1.5': + optional: true + + '@rolldown/binding-darwin-arm64@1.1.5': + optional: true + + '@rolldown/binding-darwin-x64@1.1.5': + optional: true + + '@rolldown/binding-freebsd-x64@1.1.5': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.1.5': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.1.5': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.1.5': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.1.5': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.1.5': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.1.5': + optional: true + + '@rolldown/binding-linux-x64-musl@1.1.5': + optional: true + + '@rolldown/binding-openharmony-arm64@1.1.5': + optional: true + + '@rolldown/binding-wasm32-wasi@1.1.5': + dependencies: + '@emnapi/core': 1.11.1 + '@emnapi/runtime': 1.11.1 + '@napi-rs/wasm-runtime': 1.1.6(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1) + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.1.5': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.1.5': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@tybys/wasm-util@0.10.3': + dependencies: + tslib: 2.8.1 + optional: true + + '@types/node@24.13.3': + dependencies: + undici-types: 7.18.2 + + '@types/react-dom@19.2.3(@types/react@19.2.8)': + dependencies: + '@types/react': 19.2.8 + + '@types/react@19.2.8': + dependencies: + csstype: 3.2.3 + + '@typescript/typescript-aix-ppc64@7.0.2': + optional: true + + '@typescript/typescript-darwin-arm64@7.0.2': + optional: true + + '@typescript/typescript-darwin-x64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-x64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm@7.0.2': + optional: true + + '@typescript/typescript-linux-loong64@7.0.2': + optional: true + + '@typescript/typescript-linux-mips64el@7.0.2': + optional: true + + '@typescript/typescript-linux-ppc64@7.0.2': + optional: true + + '@typescript/typescript-linux-riscv64@7.0.2': + optional: true + + '@typescript/typescript-linux-s390x@7.0.2': + optional: true + + '@typescript/typescript-linux-x64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-sunos-x64@7.0.2': + optional: true + + '@typescript/typescript-win32-arm64@7.0.2': + optional: true + + '@typescript/typescript-win32-x64@7.0.2': + optional: true + + '@vitejs/plugin-react@6.0.4(vite@8.1.5(@types/node@24.13.3))': + dependencies: + '@rolldown/pluginutils': 1.0.1 + vite: 8.1.5(@types/node@24.13.3) + + csstype@3.2.3: {} + + detect-libc@2.1.2: {} + + fdir@6.5.0(picomatch@4.0.5): + optionalDependencies: + picomatch: 4.0.5 + + fsevents@2.3.3: + optional: true + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + nanoid@3.3.16: {} + + picocolors@1.1.1: {} + + picomatch@4.0.5: {} + + postcss@8.5.22: + dependencies: + nanoid: 3.3.16 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + react-dom@19.2.8(react@19.2.8): + dependencies: + react: 19.2.8 + scheduler: 0.27.0 + + react@19.2.8: {} + + rolldown@1.1.5: + dependencies: + '@oxc-project/types': 0.139.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm64': 1.1.5 + '@rolldown/binding-darwin-arm64': 1.1.5 + '@rolldown/binding-darwin-x64': 1.1.5 + '@rolldown/binding-freebsd-x64': 1.1.5 + '@rolldown/binding-linux-arm-gnueabihf': 1.1.5 + '@rolldown/binding-linux-arm64-gnu': 1.1.5 + '@rolldown/binding-linux-arm64-musl': 1.1.5 + '@rolldown/binding-linux-ppc64-gnu': 1.1.5 + '@rolldown/binding-linux-s390x-gnu': 1.1.5 + '@rolldown/binding-linux-x64-gnu': 1.1.5 + '@rolldown/binding-linux-x64-musl': 1.1.5 + '@rolldown/binding-openharmony-arm64': 1.1.5 + '@rolldown/binding-wasm32-wasi': 1.1.5 + '@rolldown/binding-win32-arm64-msvc': 1.1.5 + '@rolldown/binding-win32-x64-msvc': 1.1.5 + + scheduler@0.27.0: {} + + source-map-js@1.2.1: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.5) + picomatch: 4.0.5 + + tslib@2.8.1: + optional: true + + typescript@7.0.2: + optionalDependencies: + '@typescript/typescript-aix-ppc64': 7.0.2 + '@typescript/typescript-darwin-arm64': 7.0.2 + '@typescript/typescript-darwin-x64': 7.0.2 + '@typescript/typescript-freebsd-arm64': 7.0.2 + '@typescript/typescript-freebsd-x64': 7.0.2 + '@typescript/typescript-linux-arm': 7.0.2 + '@typescript/typescript-linux-arm64': 7.0.2 + '@typescript/typescript-linux-loong64': 7.0.2 + '@typescript/typescript-linux-mips64el': 7.0.2 + '@typescript/typescript-linux-ppc64': 7.0.2 + '@typescript/typescript-linux-riscv64': 7.0.2 + '@typescript/typescript-linux-s390x': 7.0.2 + '@typescript/typescript-linux-x64': 7.0.2 + '@typescript/typescript-netbsd-arm64': 7.0.2 + '@typescript/typescript-netbsd-x64': 7.0.2 + '@typescript/typescript-openbsd-arm64': 7.0.2 + '@typescript/typescript-openbsd-x64': 7.0.2 + '@typescript/typescript-sunos-x64': 7.0.2 + '@typescript/typescript-win32-arm64': 7.0.2 + '@typescript/typescript-win32-x64': 7.0.2 + + undici-types@7.18.2: {} + + vite@8.1.5(@types/node@24.13.3): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.5 + postcss: 8.5.22 + rolldown: 1.1.5 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 24.13.3 + fsevents: 2.3.3 diff --git a/scripts/generate-build-manifest.mjs b/scripts/generate-build-manifest.mjs new file mode 100644 index 00000000..7f9a710b --- /dev/null +++ b/scripts/generate-build-manifest.mjs @@ -0,0 +1,30 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import process from "node:process"; + +const packageJson = JSON.parse(await readFile("package.json", "utf8")); +const packageManagerVersion = packageJson.packageManager.split("@").at(-1); +const buildId = process.env.VITE_BUILD_ID ?? "local-build"; +const commitSha = process.env.VITE_COMMIT_SHA ?? "local"; +const runnerImage = process.env.CI_RUNNER_IMAGE ?? `${process.platform}-${process.arch}`; + +const manifest = { + schemaVersion: 1, + buildId, + commitSha, + generatedAt: new Date().toISOString(), + buildContext: { + nodeVersion: process.version, + packageManagerVersion, + runnerImage, + }, + outputs: { + directory: "dist", + viteManifest: "dist/.vite/manifest.json", + }, +}; + +await mkdir("artifacts/release", { recursive: true }); +await writeFile( + "artifacts/release/build-manifest.json", + `${JSON.stringify(manifest, null, 2)}\n`, +); diff --git a/src/bootstrap/main.jsx b/src/bootstrap/main.jsx new file mode 100644 index 00000000..96528344 --- /dev/null +++ b/src/bootstrap/main.jsx @@ -0,0 +1,23 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; + +function BootstrapShell() { + return ( +
+

Clean Architecture Frontend

+

런타임 계약을 불러오는 중입니다.

+
+ ); +} + +const rootElement = document.getElementById("root"); + +if (!rootElement) { + throw new Error("Missing #root mount element"); +} + +createRoot(rootElement).render( + + + , +); diff --git a/tests/fixtures/typecheck/invalid-port-call.js b/tests/fixtures/typecheck/invalid-port-call.js new file mode 100644 index 00000000..a6c376f3 --- /dev/null +++ b/tests/fixtures/typecheck/invalid-port-call.js @@ -0,0 +1,8 @@ +// This deliberately failing fixture proves that checkJs rejects a wrong shape. + +/** @param {{ operationId: string }} request */ +function execute(request) { + return request.operationId; +} + +execute({ operationId: 42 }); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000..d3c8554f --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "allowJs": true, + "checkJs": true, + "noEmit": true, + "target": "ES2022", + "useDefineForClassFields": true, + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "Bundler", + "resolveJsonModule": true, + "allowImportingTsExtensions": false, + "jsx": "react-jsx", + "strict": true, + "skipLibCheck": true, + "types": ["vite/client", "node"] + }, + "include": ["src", "scripts", "vite.config.js"], + "exclude": ["dist", "node_modules", "tests/fixtures"] +} diff --git a/vite.config.js b/vite.config.js new file mode 100644 index 00000000..dbe5ebc1 --- /dev/null +++ b/vite.config.js @@ -0,0 +1,10 @@ +import { defineConfig } from "vite"; +import react from "@vitejs/plugin-react"; + +export default defineConfig({ + plugins: [react()], + build: { + manifest: true, + sourcemap: false, + }, +}); From 49b20bd557e30a2f6d0127358cfd73f43b73cf84 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 20:39:59 +0900 Subject: [PATCH 002/178] feat: define clean architecture layers and ports --- config/architecture/layers.json | 38 ++++++++++++++++++++++ docs/architecture/layers.md | 34 +++++++++++++++++++ src/application/create-application.js | 24 ++++++++++++++ src/application/ports/auth-session-port.js | 16 +++++++++ src/application/ports/clock-port.js | 28 ++++++++++++++++ src/application/ports/query-cache-port.js | 9 +++++ src/application/ports/release-info-port.js | 13 ++++++++ src/application/ports/resource-ports.js | 28 ++++++++++++++++ src/application/ports/storage-port.js | 9 +++++ src/application/ports/telemetry-port.js | 5 +++ src/bootstrap/composition-root.js | 23 +++++++++++++ 11 files changed, 227 insertions(+) create mode 100644 config/architecture/layers.json create mode 100644 docs/architecture/layers.md create mode 100644 src/application/create-application.js create mode 100644 src/application/ports/auth-session-port.js create mode 100644 src/application/ports/clock-port.js create mode 100644 src/application/ports/query-cache-port.js create mode 100644 src/application/ports/release-info-port.js create mode 100644 src/application/ports/resource-ports.js create mode 100644 src/application/ports/storage-port.js create mode 100644 src/application/ports/telemetry-port.js create mode 100644 src/bootstrap/composition-root.js diff --git a/config/architecture/layers.json b/config/architecture/layers.json new file mode 100644 index 00000000..5436c8b5 --- /dev/null +++ b/config/architecture/layers.json @@ -0,0 +1,38 @@ +{ + "schemaVersion": 1, + "layers": { + "domain": { + "root": "src/domain", + "mayImport": ["src/domain"] + }, + "application": { + "root": "src/application", + "mayImport": ["src/application", "src/domain", "src/contracts"] + }, + "presentation": { + "root": "src/presentation", + "mayImport": ["src/presentation", "src/application", "src/domain", "src/contracts"] + }, + "adapters": { + "root": "src/adapters", + "mayImport": ["src/adapters", "src/application", "src/domain", "src/contracts"] + }, + "bootstrap": { + "root": "src/bootstrap", + "mayImport": ["src"] + } + }, + "forbidden": [ + ["domain", "application"], + ["domain", "presentation"], + ["domain", "adapters"], + ["domain", "bootstrap"], + ["application", "presentation"], + ["application", "adapters"], + ["application", "bootstrap"], + ["presentation", "adapters"], + ["presentation", "bootstrap"], + ["adapters", "presentation"], + ["adapters", "bootstrap"] + ] +} diff --git a/docs/architecture/layers.md b/docs/architecture/layers.md new file mode 100644 index 00000000..1134f276 --- /dev/null +++ b/docs/architecture/layers.md @@ -0,0 +1,34 @@ +# Clean Architecture layer contract + +The import direction is `domain <- application <- presentation`; concrete +adapters implement application-owned ports and are assembled only in +`src/bootstrap`. + +| Layer | Owns | May depend on | +| --- | --- | --- | +| `domain` | framework-neutral models and pure policies | domain siblings | +| `application` | use cases, ports, orchestration, view-models | domain and application siblings | +| `presentation` | routes, components, user interaction and view state | application public API and shared UI | +| `adapters` | browser and third-party implementations of application ports | application ports and limited domain values | +| `bootstrap` | runtime configuration, adapter construction and React mount | all selected runtime modules | + +The following edges are forbidden: + +- domain to application, presentation, adapters, bootstrap, React, or browser globals +- application to presentation, concrete adapters, bootstrap, React, or browser globals +- presentation to concrete adapters, raw DTO schemas, or storage implementations +- an adapter to presentation, bootstrap internals, or another concrete adapter + +`bootstrap` contains composition only. Business rules and page-specific +orchestration belong to domain/application. + +Architecture reports use this shape: + +```json +{ + "schemaVersion": 1, + "generatedAt": "ISO-8601", + "rules": [{ "name": "rule-id", "severity": "error", "violations": 0 }], + "summary": { "errors": 0, "warnings": 0 } +} +``` diff --git a/src/application/create-application.js b/src/application/create-application.js new file mode 100644 index 00000000..8f78a707 --- /dev/null +++ b/src/application/create-application.js @@ -0,0 +1,24 @@ +/** + * Application facade factory. Concrete dependencies are supplied by bootstrap. + * + * @param {{ + * resources: { + * query: import("./ports/resource-ports.js").ResourceQueryPort, + * command: import("./ports/resource-ports.js").ResourceCommandPort + * }, + * cache: import("./ports/query-cache-port.js").QueryCachePort, + * storage: import("./ports/storage-port.js").StoragePort, + * telemetry: import("./ports/telemetry-port.js").TelemetryPort + * }} ports + */ +export function createApplication(ports) { + return Object.freeze({ + resources: Object.freeze({ + query: (query, context) => ports.resources.query.execute(query, context), + command: (command, context) => ports.resources.command.execute(command, context), + }), + cache: ports.cache, + storage: ports.storage, + telemetry: ports.telemetry, + }); +} diff --git a/src/application/ports/auth-session-port.js b/src/application/ports/auth-session-port.js new file mode 100644 index 00000000..91734767 --- /dev/null +++ b/src/application/ports/auth-session-port.js @@ -0,0 +1,16 @@ +/** + * @typedef {"authenticated" | "unauthenticated" | "recovery-pending" | "integration-failed"} SessionState + */ + +/** + * The session is opaque: credentials are attached without exposing tokens. + * + * @typedef {{ + * getState(): SessionState, + * attach(request: Request): Promise, + * recover(): Promise<"restored" | "no-session">, + * onUnauthenticated(): void + * }} AuthSessionPort + */ + +export {}; diff --git a/src/application/ports/clock-port.js b/src/application/ports/clock-port.js new file mode 100644 index 00000000..18f7b759 --- /dev/null +++ b/src/application/ports/clock-port.js @@ -0,0 +1,28 @@ +/** + * @typedef {{ + * now(): number, + * sleep(milliseconds: number, signal?: AbortSignal): Promise + * }} ClockPort + */ + +export const systemClock = Object.freeze({ + now: () => Date.now(), + sleep(milliseconds, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason); + return; + } + + const timer = setTimeout(resolve, milliseconds); + signal?.addEventListener( + "abort", + () => { + clearTimeout(timer); + reject(signal.reason); + }, + { once: true }, + ); + }); + }, +}); diff --git a/src/application/ports/query-cache-port.js b/src/application/ports/query-cache-port.js new file mode 100644 index 00000000..872d857f --- /dev/null +++ b/src/application/ports/query-cache-port.js @@ -0,0 +1,9 @@ +/** + * @typedef {{ + * read(key: readonly unknown[]): unknown, + * write(key: readonly unknown[], value: unknown): void, + * invalidate(namespace: readonly unknown[]): Promise + * }} QueryCachePort + */ + +export {}; diff --git a/src/application/ports/release-info-port.js b/src/application/ports/release-info-port.js new file mode 100644 index 00000000..b34b41a5 --- /dev/null +++ b/src/application/ports/release-info-port.js @@ -0,0 +1,13 @@ +/** + * @typedef {{ + * getCurrent(): Promise<{ + * buildId: string, + * configSchemaVersion: string, + * apiContractVersion: string, + * assetManifestHash: string, + * releaseId: string + * }> + * }} ReleaseInfoPort + */ + +export {}; diff --git a/src/application/ports/resource-ports.js b/src/application/ports/resource-ports.js new file mode 100644 index 00000000..1290758c --- /dev/null +++ b/src/application/ports/resource-ports.js @@ -0,0 +1,28 @@ +/** + * @template Query + * @template Model + * @typedef {{ execute(query: Query, context?: RequestContext): Promise> }} ResourceQueryPort + */ + +/** + * @template Command + * @template Model + * @typedef {{ execute(command: Command, context?: RequestContext): Promise> }} ResourceCommandPort + */ + +/** + * @typedef {{ + * operationId: string, + * routeId: string, + * signal?: AbortSignal, + * idempotencyKey?: string + * }} RequestContext + */ + +/** + * @template Value + * @typedef {{ ok: true, value: Value, meta?: Record } | + * { ok: false, error: import("../../contracts/errors.js").ApiFailure }} Result + */ + +export {}; diff --git a/src/application/ports/storage-port.js b/src/application/ports/storage-port.js new file mode 100644 index 00000000..98dae43d --- /dev/null +++ b/src/application/ports/storage-port.js @@ -0,0 +1,9 @@ +/** + * @typedef {{ + * read(logicalName: string): { ok: true, value: unknown } | { ok: false, error: unknown }, + * write(logicalName: string, value: unknown): { ok: true } | { ok: false, error: unknown }, + * remove(logicalName: string): { ok: true } | { ok: false, error: unknown } + * }} StoragePort + */ + +export {}; diff --git a/src/application/ports/telemetry-port.js b/src/application/ports/telemetry-port.js new file mode 100644 index 00000000..e660e62e --- /dev/null +++ b/src/application/ports/telemetry-port.js @@ -0,0 +1,5 @@ +/** + * @typedef {{ emit(eventName: string, attributes: Record): void }} TelemetryPort + */ + +export {}; diff --git a/src/bootstrap/composition-root.js b/src/bootstrap/composition-root.js new file mode 100644 index 00000000..0bbee542 --- /dev/null +++ b/src/bootstrap/composition-root.js @@ -0,0 +1,23 @@ +import { createApplication } from "../application/create-application.js"; + +/** + * This is the only module allowed to join concrete adapters to application + * ports. Boot phases are explicit so failures can stop before product mount. + * + * @param {{ + * loadConfig(): Promise>, + * loadRelease(config: Record): Promise>, + * createAdapters(context: { + * config: Record, + * release: Record + * }): Promise[0]> + * }} factories + */ +export async function createCompositionRoot(factories) { + const config = await factories.loadConfig(); + const release = await factories.loadRelease(config); + const ports = await factories.createAdapters({ config, release }); + const application = createApplication(ports); + + return Object.freeze({ config, release, ports, application }); +} From d7480cbafd4fc5f788ad165964c93a9bba8e354c Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 20:40:21 +0900 Subject: [PATCH 003/178] fix: make application port contracts checkJs-safe --- src/application/create-application.js | 20 ++++++++++++++++++-- src/application/ports/clock-port.js | 1 + src/application/ports/resource-ports.js | 2 +- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/application/create-application.js b/src/application/create-application.js index 8f78a707..76347314 100644 --- a/src/application/create-application.js +++ b/src/application/create-application.js @@ -12,10 +12,26 @@ * }} ports */ export function createApplication(ports) { + /** + * @param {unknown} query + * @param {import("./ports/resource-ports.js").RequestContext} [context] + */ + function queryResources(query, context) { + return ports.resources.query.execute(query, context); + } + + /** + * @param {unknown} command + * @param {import("./ports/resource-ports.js").RequestContext} [context] + */ + function commandResources(command, context) { + return ports.resources.command.execute(command, context); + } + return Object.freeze({ resources: Object.freeze({ - query: (query, context) => ports.resources.query.execute(query, context), - command: (command, context) => ports.resources.command.execute(command, context), + query: queryResources, + command: commandResources, }), cache: ports.cache, storage: ports.storage, diff --git a/src/application/ports/clock-port.js b/src/application/ports/clock-port.js index 18f7b759..353d5a33 100644 --- a/src/application/ports/clock-port.js +++ b/src/application/ports/clock-port.js @@ -5,6 +5,7 @@ * }} ClockPort */ +/** @type {ClockPort} */ export const systemClock = Object.freeze({ now: () => Date.now(), sleep(milliseconds, signal) { diff --git a/src/application/ports/resource-ports.js b/src/application/ports/resource-ports.js index 1290758c..6a077889 100644 --- a/src/application/ports/resource-ports.js +++ b/src/application/ports/resource-ports.js @@ -22,7 +22,7 @@ /** * @template Value * @typedef {{ ok: true, value: Value, meta?: Record } | - * { ok: false, error: import("../../contracts/errors.js").ApiFailure }} Result + * { ok: false, error: unknown }} Result */ export {}; From 946cf407b056de9af8a5a56092d7bc3f8283de84 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 20:41:44 +0900 Subject: [PATCH 004/178] test: establish frontend gate taxonomy --- docs/testing/taxonomy.md | 24 + package.json | 19 +- playwright.config.js | 23 + pnpm-lock.yaml | 1231 ++++++++++++++++++++++ pnpm-workspace.yaml | 6 + tests/component/bootstrap-shell.test.jsx | 17 + tests/e2e/app-shell.spec.js | 8 + tests/integration/http-boundary.test.js | 23 + tests/setup.js | 7 + tests/unit/system-clock.test.js | 13 + vitest.config.js | 15 + 11 files changed, 1384 insertions(+), 2 deletions(-) create mode 100644 docs/testing/taxonomy.md create mode 100644 playwright.config.js create mode 100644 pnpm-workspace.yaml create mode 100644 tests/component/bootstrap-shell.test.jsx create mode 100644 tests/e2e/app-shell.spec.js create mode 100644 tests/integration/http-boundary.test.js create mode 100644 tests/setup.js create mode 100644 tests/unit/system-clock.test.js create mode 100644 vitest.config.js diff --git a/docs/testing/taxonomy.md b/docs/testing/taxonomy.md new file mode 100644 index 00000000..5a9a72c1 --- /dev/null +++ b/docs/testing/taxonomy.md @@ -0,0 +1,24 @@ +# Test and evidence taxonomy + +Each gate is blocking in its declared scope. Failures are not downgraded with +`continue-on-error` or warning-only scripts. + +| Level | Command | Evidence | +| --- | --- | --- | +| runtime schema | `pnpm test:runtime-schema` | `artifacts/tests/runtime-schema.xml` | +| unit | `pnpm test:unit` | `artifacts/tests/unit.xml` | +| component | `pnpm test:component` | `artifacts/tests/component.xml` | +| integration | `pnpm test:integration` | `artifacts/tests/integration.xml` | +| end-to-end | `pnpm test:e2e` | `artifacts/tests/e2e/` | +| accessibility | `pnpm test:a11y` | `artifacts/tests/a11y.json` | + +A control is verified only when a positive fixture passes and its deliberately +failing negative fixture is rejected. Generated evidence is retained by CI; +the repository tracks only the evidence directory structure. + +Promotion is an AND graph: + +1. merge gates +2. merge gates plus release gates +3. release gates plus rollback/runbook drills +4. production promotion plus eligible field Web Vitals evidence diff --git a/package.json b/package.json index 1bba499a..9c484344 100644 --- a/package.json +++ b/package.json @@ -13,18 +13,33 @@ "build": "vite build && node scripts/generate-build-manifest.mjs", "preview": "vite preview", "check:types": "tsc --allowJs --checkJs --noEmit", - "check:types:fixture": "tsc --allowJs --checkJs --noEmit --target ES2022 --module NodeNext --moduleResolution NodeNext tests/fixtures/typecheck/invalid-port-call.js" + "check:types:fixture": "tsc --allowJs --checkJs --noEmit --target ES2022 --module NodeNext --moduleResolution NodeNext tests/fixtures/typecheck/invalid-port-call.js", + "test:runtime-schema": "vitest run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests", + "test:unit": "vitest run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml", + "test:component": "vitest run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml", + "test:integration": "vitest run tests/integration --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/integration.xml", + "test:e2e": "playwright test", + "test:a11y": "playwright test --grep @a11y", + "test:all": "pnpm test:runtime-schema && pnpm test:unit && pnpm test:component && pnpm test:integration" }, "dependencies": { "react": "19.2.8", "react-dom": "19.2.8" }, "devDependencies": { + "@axe-core/playwright": "4.12.1", + "@playwright/test": "1.62.0", + "@testing-library/jest-dom": "7.0.0", + "@testing-library/react": "16.3.2", + "@testing-library/user-event": "14.6.1", "@types/node": "24.13.3", "@types/react": "19.2.8", "@types/react-dom": "19.2.3", "@vitejs/plugin-react": "6.0.4", + "jsdom": "29.1.1", + "msw": "2.15.0", "typescript": "7.0.2", - "vite": "8.1.5" + "vite": "8.1.5", + "vitest": "4.1.10" } } diff --git a/playwright.config.js b/playwright.config.js new file mode 100644 index 00000000..6f4a944c --- /dev/null +++ b/playwright.config.js @@ -0,0 +1,23 @@ +import { defineConfig, devices } from "@playwright/test"; + +export default defineConfig({ + testDir: "./tests/e2e", + outputDir: "./artifacts/tests/e2e/results", + reporter: [ + ["list"], + ["html", { outputFolder: "./artifacts/tests/e2e/report", open: "never" }], + ], + use: { + baseURL: "http://127.0.0.1:5173", + trace: "retain-on-failure", + screenshot: "only-on-failure", + }, + webServer: { + command: "pnpm dev --host 127.0.0.1", + url: "http://127.0.0.1:5173", + reuseExistingServer: !process.env.CI, + }, + projects: [ + { name: "chromium", use: { ...devices["Desktop Chrome"] } }, + ], +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 163049b8..b611b982 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -15,6 +15,21 @@ importers: specifier: 19.2.8 version: 19.2.8(react@19.2.8) devDependencies: + '@axe-core/playwright': + specifier: 4.12.1 + version: 4.12.1(playwright-core@1.62.0) + '@playwright/test': + specifier: 1.62.0 + version: 1.62.0 + '@testing-library/jest-dom': + specifier: 7.0.0 + version: 7.0.0(@testing-library/dom@10.4.1) + '@testing-library/react': + specifier: 16.3.2 + version: 16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.2.3(@types/react@19.2.8))(@types/react@19.2.8)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) + '@testing-library/user-event': + specifier: 14.6.1 + version: 14.6.1(@testing-library/dom@10.4.1) '@types/node': specifier: 24.13.3 version: 24.13.3 @@ -27,15 +42,99 @@ importers: '@vitejs/plugin-react': specifier: 6.0.4 version: 6.0.4(vite@8.1.5(@types/node@24.13.3)) + jsdom: + specifier: 29.1.1 + version: 29.1.1 + msw: + specifier: 2.15.0 + version: 2.15.0(@types/node@24.13.3)(typescript@7.0.2) typescript: specifier: 7.0.2 version: 7.0.2 vite: specifier: 8.1.5 version: 8.1.5(@types/node@24.13.3) + vitest: + specifier: 4.1.10 + version: 4.1.10(@types/node@24.13.3)(jsdom@29.1.1)(msw@2.15.0(@types/node@24.13.3)(typescript@7.0.2))(vite@8.1.5(@types/node@24.13.3)) packages: + '@adobe/css-tools@4.5.0': + resolution: {integrity: sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==} + + '@asamuzakjp/css-color@5.1.11': + resolution: {integrity: sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + + '@asamuzakjp/dom-selector@7.1.1': + resolution: {integrity: sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + + '@asamuzakjp/generational-cache@1.0.1': + resolution: {integrity: sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + + '@asamuzakjp/nwsapi@2.3.9': + resolution: {integrity: sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==} + + '@axe-core/playwright@4.12.1': + resolution: {integrity: sha512-rMd7xriptqKpP+w5265i4Hdkv2X5kbu6uiBi/B2I7uf3hieRBM3qDCfaKPtxfiYb2mKXfF+yLODJwIx+Jv1GDw==} + peerDependencies: + playwright-core: '>= 1.0.0' + + '@babel/code-frame@7.29.7': + resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.29.7': + resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + engines: {node: '>=6.9.0'} + + '@babel/runtime@7.29.7': + resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==} + engines: {node: '>=6.9.0'} + + '@bramus/specificity@2.4.2': + resolution: {integrity: sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==} + hasBin: true + + '@csstools/color-helpers@6.1.0': + resolution: {integrity: sha512-064IFJdjTfUqnjpCVpMOdbr8FLQBhinbZj6yRv2An2E41O/pLEXqfFRWqGq/SxlE5PEUYTlvWsG2r8MswAVvkg==} + engines: {node: '>=20.19.0'} + + '@csstools/css-calc@3.3.0': + resolution: {integrity: sha512-c5ihYsPkdG6JCkU2zTMm4+k6r7RXuGxtWYhu5DHMIiF1FHzrfmHL5so11AoFpUv/tu61xfcmT4AmKoFfMPoqdQ==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-parser-algorithms': ^4.0.0 + '@csstools/css-tokenizer': ^4.0.0 + + '@csstools/css-color-parser@4.1.10': + resolution: {integrity: sha512-UZhQLIUyJaaMepqehrCODwCg2KW25vFvLWBmqYFaPclYvvxzj/sG8LBOhBFCp11i9uE7t1EyS+RAoV9tztPFyw==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-parser-algorithms': ^4.0.0 + '@csstools/css-tokenizer': ^4.0.0 + + '@csstools/css-parser-algorithms@4.0.0': + resolution: {integrity: sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-tokenizer': ^4.0.0 + + '@csstools/css-syntax-patches-for-csstree@1.1.7': + resolution: {integrity: sha512-fQ+05118eQS1cofO3aJpB5efgpBZMvIzwr/sbC8kDLVA5XLG8q1kJV5yzrUAI1f7lvhPnm8fgIjzFB8/O/5Dig==} + peerDependencies: + css-tree: ^3.2.1 + peerDependenciesMeta: + css-tree: + optional: true + + '@csstools/css-tokenizer@4.0.0': + resolution: {integrity: sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==} + engines: {node: '>=20.19.0'} + '@emnapi/core@1.11.1': resolution: {integrity: sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==} @@ -45,15 +144,83 @@ packages: '@emnapi/wasi-threads@1.2.2': resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==} + '@exodus/bytes@1.15.1': + resolution: {integrity: sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + peerDependencies: + '@noble/hashes': ^1.8.0 || ^2.0.0 + peerDependenciesMeta: + '@noble/hashes': + optional: true + + '@inquirer/ansi@2.0.7': + resolution: {integrity: sha512-3eTuUO1vH2cZm2ZKHeQxnOqlTi9EfZDGgIe3BL3I4u+rJHocr9Fz86M4fjYABPvFnQG/gGK551HqDiIcETwU6Q==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + + '@inquirer/confirm@6.1.1': + resolution: {integrity: sha512-eb8DBZcz/2qHWQda4rk2JiQk5h9QV/cVHi1yjt0f69WFZMRFn0sJTye3EAP8icut8UDMjQPsaH5KbcOogefrFQ==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/core@11.2.1': + resolution: {integrity: sha512-Qd6GJT1yVyrZZCfN8W2qKF5ApmqryXRhRKCuip8h01x2w/esJQ2XIYc6f9abMIHgKQdBfFTSOdbHRLAhuM09UA==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@inquirer/figures@2.0.7': + resolution: {integrity: sha512-aJ8TBPOGB6f/2qziPfElISTCEd5XOYTFckA2SGjhNmiKzfK/u4ot3v0DUzGVdUnKjN10EqnnEPck36BkyfLnJw==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + + '@inquirer/type@4.0.7': + resolution: {integrity: sha512-t28inv14nMQ1PhKpsJPY+kEs/c00qzeCOS2gTNRyTjG5d6qsVA2fItxW4hkvGZ5lvanGLdtCzVIx5dwdRpN1+g==} + engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} + peerDependencies: + '@types/node': '>=18' + peerDependenciesMeta: + '@types/node': + optional: true + + '@jridgewell/sourcemap-codec@1.5.5': + resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + + '@mswjs/interceptors@0.41.9': + resolution: {integrity: sha512-VVPPgHyQ6ShqnrmDWuxjmUIsO9gWyOZFmuOfLd9LfBGQJwZfy0gvv9pbHSJuoFNIYC7ZDX9aoFwowjcdSC4E8w==} + engines: {node: '>=18'} + '@napi-rs/wasm-runtime@1.1.6': resolution: {integrity: sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==} peerDependencies: '@emnapi/core': ^1.7.1 '@emnapi/runtime': ^1.7.1 + '@open-draft/deferred-promise@2.2.0': + resolution: {integrity: sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA==} + + '@open-draft/deferred-promise@3.0.0': + resolution: {integrity: sha512-XW375UK8/9SqUVNVa6M0yEy8+iTi4QN5VZ7aZuRFQmy76LRwI9wy5F4YIBU6T+eTe2/DNDo8tqu8RHlwLHM6RA==} + + '@open-draft/logger@0.3.0': + resolution: {integrity: sha512-X2g45fzhxH238HKO4xbSr7+wBS8Fvw6ixhTDuvLd5mqh6bJJCFAPwU9mPDxbcrRtfxv4u5IHCEH77BmxvXmmxQ==} + + '@open-draft/until@2.1.0': + resolution: {integrity: sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==} + '@oxc-project/types@0.139.0': resolution: {integrity: sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw==} + '@playwright/test@1.62.0': + resolution: {integrity: sha512-9zOJ6ZQRAena31MpOH9VSzIz8Ou3YJ/wtY/eQm5T2uhfhG7/U3COrMS8xOtUrZrp9OgdmzEnIYODye3nY1VqzA==} + engines: {node: '>=20'} + hasBin: true + '@rolldown/binding-android-arm64@1.1.5': resolution: {integrity: sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ==} engines: {node: ^20.19.0 || >=22.12.0} @@ -152,9 +319,55 @@ packages: '@rolldown/pluginutils@1.0.1': resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + + '@testing-library/dom@10.4.1': + resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==} + engines: {node: '>=18'} + + '@testing-library/jest-dom@7.0.0': + resolution: {integrity: sha512-HKAH9C6mBo5yBG6yRO5i43L2iisencAo5z+o5P/saHUoY+miC5ivXRxHBJcFyB5ypPNxHJdK3BoF/3O4DIptMg==} + engines: {node: '>=22', npm: '>=6', yarn: '>=1'} + peerDependencies: + '@testing-library/dom': '>=10 <11' + + '@testing-library/react@16.3.2': + resolution: {integrity: sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==} + engines: {node: '>=18'} + peerDependencies: + '@testing-library/dom': ^10.0.0 + '@types/react': ^18.0.0 || ^19.0.0 + '@types/react-dom': ^18.0.0 || ^19.0.0 + react: ^18.0.0 || ^19.0.0 + react-dom: ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@testing-library/user-event@14.6.1': + resolution: {integrity: sha512-vq7fv0rnt+QTXgPxr5Hjc210p6YKq2kmdziLgnsZGgLJ9e6VAShx1pACLuRjd/AS/sr7phAR58OIIpf0LlmQNw==} + engines: {node: '>=12', npm: '>=6'} + peerDependencies: + '@testing-library/dom': '>=7.21.4' + '@tybys/wasm-util@0.10.3': resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==} + '@types/aria-query@5.0.4': + resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + '@types/node@24.13.3': resolution: {integrity: sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==} @@ -166,6 +379,12 @@ packages: '@types/react@19.2.8': resolution: {integrity: sha512-3MbSL37jEchWZz2p2mjntRZtPt837ij10ApxKfgmXCTuHWagYg7iA5bqPw6C8BMPfwidlvfPI/fxOc42HLhcyg==} + '@types/set-cookie-parser@2.4.10': + resolution: {integrity: sha512-GGmQVGpQWUe5qglJozEjZV/5dyxbOOZ0LHe/lqyWssB88Y4svNfst0uqBVscdDeIKl5Jy5+aPSvy7mI9tYRguw==} + + '@types/statuses@2.0.6': + resolution: {integrity: sha512-xMAgYwceFhRA2zY+XbEA7mxYbA093wdiW8Vu6gZPGWy9cmOyU9XesH1tNcEWsKFd5Vzrqx5T3D38PWx1FIIXkA==} + '@typescript/typescript-aix-ppc64@7.0.2': resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} engines: {node: '>=16.20.0'} @@ -299,13 +518,152 @@ packages: babel-plugin-react-compiler: optional: true + '@vitest/expect@4.1.10': + resolution: {integrity: sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==} + + '@vitest/mocker@4.1.10': + resolution: {integrity: sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==} + peerDependencies: + msw: ^2.4.9 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@4.1.10': + resolution: {integrity: sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==} + + '@vitest/runner@4.1.10': + resolution: {integrity: sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==} + + '@vitest/snapshot@4.1.10': + resolution: {integrity: sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==} + + '@vitest/spy@4.1.10': + resolution: {integrity: sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==} + + '@vitest/utils@4.1.10': + resolution: {integrity: sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==} + + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + + ansi-styles@5.2.0: + resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==} + engines: {node: '>=10'} + + aria-query@5.3.0: + resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==} + + aria-query@5.3.2: + resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==} + engines: {node: '>= 0.4'} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + axe-core@4.12.1: + resolution: {integrity: sha512-s7iGf5GaVMxEG0ENN9x+xTr7GFZCb1ZP/1uATUpCEK2X78nDB3RwbtFCo9pGAf9ru+VwoQ464DkaLEeRM08wJA==} + engines: {node: '>=4'} + + bidi-js@1.0.3: + resolution: {integrity: sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==} + + chai@6.2.2: + resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} + engines: {node: '>=18'} + + cli-width@4.1.0: + resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==} + engines: {node: '>= 12'} + + cliui@8.0.1: + resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} + engines: {node: '>=12'} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + + convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + + cookie@1.1.1: + resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} + engines: {node: '>=18'} + + css-tree@3.2.1: + resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==} + engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} + + css.escape@1.5.1: + resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==} + csstype@3.2.3: resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + data-urls@7.0.0: + resolution: {integrity: sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + + decimal.js@10.6.0: + resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} + + dequal@2.0.3: + resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} + engines: {node: '>=6'} + detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} + dom-accessibility-api@0.5.16: + resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==} + + dom-accessibility-api@0.6.3: + resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==} + + emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + + entities@8.0.0: + resolution: {integrity: sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==} + engines: {node: '>=20.19.0'} + + es-module-lexer@2.3.1: + resolution: {integrity: sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==} + + escalade@3.2.0: + resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} + engines: {node: '>=6'} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fast-string-truncated-width@3.0.3: + resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==} + + fast-string-width@3.0.2: + resolution: {integrity: sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==} + + fast-wrap-ansi@0.2.2: + resolution: {integrity: sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==} + fdir@6.5.0: resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} engines: {node: '>=12.0.0'} @@ -315,11 +673,57 @@ packages: picomatch: optional: true + fsevents@2.3.2: + resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} os: [darwin] + get-caller-file@2.0.5: + resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} + engines: {node: 6.* || 8.* || >= 10.*} + + graphql@16.14.2: + resolution: {integrity: sha512-Chq1s4CY7jmh8gO2qvLIJyfCDIN+EHLFW/9iShnp1z8FjBQMoodWP1kDC36VAMXXIvAjj4ARa7ntfAV2BrjsbA==} + engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0} + + headers-polyfill@5.0.1: + resolution: {integrity: sha512-1TJ6Fih/b8h5TIcv+1+Hw0PDQWJTKDKzFZzcKOiW1wJza3XoAQlkCuXLbymPYB8+ZQyw8mHvdw560e8zVFIWyA==} + + html-encoding-sniffer@6.0.0: + resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + + indent-string@4.0.0: + resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==} + engines: {node: '>=8'} + + is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + + is-node-process@1.2.0: + resolution: {integrity: sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw==} + + is-potential-custom-element-name@1.0.1: + resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + + jsdom@29.1.1: + resolution: {integrity: sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24.0.0} + peerDependencies: + canvas: ^3.0.0 + peerDependenciesMeta: + canvas: + optional: true + lightningcss-android-arm64@1.33.0: resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} engines: {node: '>= 12.0.0'} @@ -394,11 +798,59 @@ packages: resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} engines: {node: '>= 12.0.0'} + lru-cache@11.5.2: + resolution: {integrity: sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==} + engines: {node: 20 || >=22} + + lz-string@1.5.0: + resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} + hasBin: true + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + mdn-data@2.27.1: + resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==} + + min-indent@1.0.1: + resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==} + engines: {node: '>=4'} + + msw@2.15.0: + resolution: {integrity: sha512-2wQAmKkQKxRuXvYJxVhPGG0wZNBQyD06oJvxqw90XqLvptdqxdlHrFUfEteKkpaNORX3Xzc+HtEl/q0nfmN2wQ==} + engines: {node: '>=18'} + hasBin: true + peerDependencies: + typescript: '>= 4.8.x' + peerDependenciesMeta: + typescript: + optional: true + + mute-stream@3.0.0: + resolution: {integrity: sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==} + engines: {node: ^20.17.0 || >=22.9.0} + nanoid@3.3.16: resolution: {integrity: sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true + obug@2.1.4: + resolution: {integrity: sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==} + engines: {node: '>=12.20.0'} + + outvariant@1.4.3: + resolution: {integrity: sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA==} + + parse5@8.0.1: + resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==} + + path-to-regexp@6.3.0: + resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==} + + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -406,38 +858,150 @@ packages: resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==} engines: {node: '>=12'} + playwright-core@1.62.0: + resolution: {integrity: sha512-nsNRyq0r2zsG8AcRHWknc9QRA5XCueC7gWMrs+Gx2tlZn9hcl8zudfh00lhJPY1DE7NmZ6bDsT9g2yey8mXljA==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.62.0: + resolution: {integrity: sha512-Z14dG305dgaLu6foB1TXQagFiW8JfSUIUaUuPaKQ6NtBPKF1P/qXcqfh6c6K/icPqdy37JmjbiBXf6JNg6Sylw==} + engines: {node: '>=20'} + hasBin: true + postcss@8.5.22: resolution: {integrity: sha512-KBDEIpLrvpv16pp3K0Fw+UCoZfopFjjgeB+0tA/aaThfEE74kKDLrgg603YvOWJyg3+WYtyq3xYsQWsIyZlPqQ==} engines: {node: ^10 || ^12 || >=14} + pretty-format@27.5.1: + resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==} + engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + react-dom@19.2.8: resolution: {integrity: sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==} peerDependencies: react: ^19.2.8 + react-is@17.0.2: + resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==} + react@19.2.8: resolution: {integrity: sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==} engines: {node: '>=0.10.0'} + redent@3.0.0: + resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==} + engines: {node: '>=8'} + + require-directory@2.1.1: + resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} + engines: {node: '>=0.10.0'} + + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + + rettime@0.11.11: + resolution: {integrity: sha512-ILJRqVWBCTlg9r42fFgwVZx1gnFAcQF8mRoMkbgQfIrjEDf9nbBFDFx00oloOa+Q869FUtaYDXZvEfnecQSCoQ==} + rolldown@1.1.5: resolution: {integrity: sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true + saxes@6.0.0: + resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} + engines: {node: '>=v12.22.7'} + scheduler@0.27.0: resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==} + set-cookie-parser@3.1.2: + resolution: {integrity: sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw==} + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + signal-exit@4.1.0: + resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} + engines: {node: '>=14'} + source-map-js@1.2.1: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + statuses@2.0.2: + resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} + engines: {node: '>= 0.8'} + + std-env@4.2.0: + resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==} + + strict-event-emitter@0.5.1: + resolution: {integrity: sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ==} + + string-width@4.2.3: + resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} + engines: {node: '>=8'} + + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + + strip-indent@3.0.0: + resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==} + engines: {node: '>=8'} + + symbol-tree@3.2.4: + resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} + + tagged-tag@1.0.0: + resolution: {integrity: sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==} + engines: {node: '>=20'} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@1.2.4: + resolution: {integrity: sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==} + engines: {node: '>=18'} + tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} + tinyrainbow@3.1.0: + resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==} + engines: {node: '>=14.0.0'} + + tldts-core@7.4.9: + resolution: {integrity: sha512-DxKfPBI52p2msTEu7MPhdpdDTBhhVQg1a/8PjQckeyAvO13eMYElX545grIp6nnTGIMZlRvFZPvFhvI/WIz2Vg==} + + tldts@7.4.9: + resolution: {integrity: sha512-3kZ8wQQ/k5DrChD4X4FVvr2D7E5uoRgAqkPyLpSCGUvqOvqu+JEdr3mwMUaVWb+vMHZaKhF5fp2PBigKsui7hA==} + hasBin: true + + tough-cookie@6.0.2: + resolution: {integrity: sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==} + engines: {node: '>=16'} + + tr46@6.0.0: + resolution: {integrity: sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==} + engines: {node: '>=20'} + tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + type-fest@5.8.0: + resolution: {integrity: sha512-YGYEVz3Fm5iy/AybuA0oyNFq7H4CgQNfRp/qfe8nurE1kuCeNm3/vfm9X4Mtl+qLyaKJUh5xrFZwogr41SMjYA==} + engines: {node: '>=20'} + typescript@7.0.2: resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} engines: {node: '>=16.20.0'} @@ -446,6 +1010,13 @@ packages: undici-types@7.18.2: resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==} + undici@7.28.0: + resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==} + engines: {node: '>=20.18.1'} + + until-async@3.0.2: + resolution: {integrity: sha512-IiSk4HlzAMqTUseHHe3VhIGyuFmN90zMTpD3Z3y8jeQbzLIq500MVM7Jq2vUAnTKAFPJrqwkzr6PoTcPhGcOiw==} + vite@8.1.5: resolution: {integrity: sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -489,8 +1060,158 @@ packages: yaml: optional: true + vitest@4.1.10: + resolution: {integrity: sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==} + engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 4.1.10 + '@vitest/browser-preview': 4.1.10 + '@vitest/browser-webdriverio': 4.1.10 + '@vitest/coverage-istanbul': 4.1.10 + '@vitest/coverage-v8': 4.1.10 + '@vitest/ui': 4.1.10 + happy-dom: '*' + jsdom: '*' + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + w3c-xmlserializer@5.0.0: + resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==} + engines: {node: '>=18'} + + webidl-conversions@8.0.1: + resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==} + engines: {node: '>=20'} + + whatwg-mimetype@5.0.0: + resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==} + engines: {node: '>=20'} + + whatwg-url@16.0.1: + resolution: {integrity: sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + wrap-ansi@7.0.0: + resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} + engines: {node: '>=10'} + + xml-name-validator@5.0.0: + resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==} + engines: {node: '>=18'} + + xmlchars@2.2.0: + resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + + y18n@5.0.8: + resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} + engines: {node: '>=10'} + + yargs-parser@21.1.1: + resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} + engines: {node: '>=12'} + + yargs@17.7.3: + resolution: {integrity: sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==} + engines: {node: '>=12'} + snapshots: + '@adobe/css-tools@4.5.0': {} + + '@asamuzakjp/css-color@5.1.11': + dependencies: + '@asamuzakjp/generational-cache': 1.0.1 + '@csstools/css-calc': 3.3.0(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0) + '@csstools/css-color-parser': 4.1.10(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0) + '@csstools/css-parser-algorithms': 4.0.0(@csstools/css-tokenizer@4.0.0) + '@csstools/css-tokenizer': 4.0.0 + + '@asamuzakjp/dom-selector@7.1.1': + dependencies: + '@asamuzakjp/generational-cache': 1.0.1 + '@asamuzakjp/nwsapi': 2.3.9 + bidi-js: 1.0.3 + css-tree: 3.2.1 + is-potential-custom-element-name: 1.0.1 + + '@asamuzakjp/generational-cache@1.0.1': {} + + '@asamuzakjp/nwsapi@2.3.9': {} + + '@axe-core/playwright@4.12.1(playwright-core@1.62.0)': + dependencies: + axe-core: 4.12.1 + playwright-core: 1.62.0 + + '@babel/code-frame@7.29.7': + dependencies: + '@babel/helper-validator-identifier': 7.29.7 + js-tokens: 4.0.0 + picocolors: 1.1.1 + + '@babel/helper-validator-identifier@7.29.7': {} + + '@babel/runtime@7.29.7': {} + + '@bramus/specificity@2.4.2': + dependencies: + css-tree: 3.2.1 + + '@csstools/color-helpers@6.1.0': {} + + '@csstools/css-calc@3.3.0(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0)': + dependencies: + '@csstools/css-parser-algorithms': 4.0.0(@csstools/css-tokenizer@4.0.0) + '@csstools/css-tokenizer': 4.0.0 + + '@csstools/css-color-parser@4.1.10(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0)': + dependencies: + '@csstools/color-helpers': 6.1.0 + '@csstools/css-calc': 3.3.0(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0) + '@csstools/css-parser-algorithms': 4.0.0(@csstools/css-tokenizer@4.0.0) + '@csstools/css-tokenizer': 4.0.0 + + '@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0)': + dependencies: + '@csstools/css-tokenizer': 4.0.0 + + '@csstools/css-syntax-patches-for-csstree@1.1.7(css-tree@3.2.1)': + optionalDependencies: + css-tree: 3.2.1 + + '@csstools/css-tokenizer@4.0.0': {} + '@emnapi/core@1.11.1': dependencies: '@emnapi/wasi-threads': 1.2.2 @@ -507,6 +1228,46 @@ snapshots: tslib: 2.8.1 optional: true + '@exodus/bytes@1.15.1': {} + + '@inquirer/ansi@2.0.7': {} + + '@inquirer/confirm@6.1.1(@types/node@24.13.3)': + dependencies: + '@inquirer/core': 11.2.1(@types/node@24.13.3) + '@inquirer/type': 4.0.7(@types/node@24.13.3) + optionalDependencies: + '@types/node': 24.13.3 + + '@inquirer/core@11.2.1(@types/node@24.13.3)': + dependencies: + '@inquirer/ansi': 2.0.7 + '@inquirer/figures': 2.0.7 + '@inquirer/type': 4.0.7(@types/node@24.13.3) + cli-width: 4.1.0 + fast-wrap-ansi: 0.2.2 + mute-stream: 3.0.0 + signal-exit: 4.1.0 + optionalDependencies: + '@types/node': 24.13.3 + + '@inquirer/figures@2.0.7': {} + + '@inquirer/type@4.0.7(@types/node@24.13.3)': + optionalDependencies: + '@types/node': 24.13.3 + + '@jridgewell/sourcemap-codec@1.5.5': {} + + '@mswjs/interceptors@0.41.9': + dependencies: + '@open-draft/deferred-promise': 2.2.0 + '@open-draft/logger': 0.3.0 + '@open-draft/until': 2.1.0 + is-node-process: 1.2.0 + outvariant: 1.4.3 + strict-event-emitter: 0.5.1 + '@napi-rs/wasm-runtime@1.1.6(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)': dependencies: '@emnapi/core': 1.11.1 @@ -514,8 +1275,23 @@ snapshots: '@tybys/wasm-util': 0.10.3 optional: true + '@open-draft/deferred-promise@2.2.0': {} + + '@open-draft/deferred-promise@3.0.0': {} + + '@open-draft/logger@0.3.0': + dependencies: + is-node-process: 1.2.0 + outvariant: 1.4.3 + + '@open-draft/until@2.1.0': {} + '@oxc-project/types@0.139.0': {} + '@playwright/test@1.62.0': + dependencies: + playwright: 1.62.0 + '@rolldown/binding-android-arm64@1.1.5': optional: true @@ -567,11 +1343,59 @@ snapshots: '@rolldown/pluginutils@1.0.1': {} + '@standard-schema/spec@1.1.0': {} + + '@testing-library/dom@10.4.1': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/runtime': 7.29.7 + '@types/aria-query': 5.0.4 + aria-query: 5.3.0 + dom-accessibility-api: 0.5.16 + lz-string: 1.5.0 + picocolors: 1.1.1 + pretty-format: 27.5.1 + + '@testing-library/jest-dom@7.0.0(@testing-library/dom@10.4.1)': + dependencies: + '@adobe/css-tools': 4.5.0 + '@testing-library/dom': 10.4.1 + aria-query: 5.3.2 + css.escape: 1.5.1 + dom-accessibility-api: 0.6.3 + picocolors: 1.1.1 + redent: 3.0.0 + + '@testing-library/react@16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.2.3(@types/react@19.2.8))(@types/react@19.2.8)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': + dependencies: + '@babel/runtime': 7.29.7 + '@testing-library/dom': 10.4.1 + react: 19.2.8 + react-dom: 19.2.8(react@19.2.8) + optionalDependencies: + '@types/react': 19.2.8 + '@types/react-dom': 19.2.3(@types/react@19.2.8) + + '@testing-library/user-event@14.6.1(@testing-library/dom@10.4.1)': + dependencies: + '@testing-library/dom': 10.4.1 + '@tybys/wasm-util@0.10.3': dependencies: tslib: 2.8.1 optional: true + '@types/aria-query@5.0.4': {} + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.9': {} + '@types/node@24.13.3': dependencies: undici-types: 7.18.2 @@ -584,6 +1408,12 @@ snapshots: dependencies: csstype: 3.2.3 + '@types/set-cookie-parser@2.4.10': + dependencies: + '@types/node': 24.13.3 + + '@types/statuses@2.0.6': {} + '@typescript/typescript-aix-ppc64@7.0.2': optional: true @@ -649,17 +1479,201 @@ snapshots: '@rolldown/pluginutils': 1.0.1 vite: 8.1.5(@types/node@24.13.3) + '@vitest/expect@4.1.10': + dependencies: + '@standard-schema/spec': 1.1.0 + '@types/chai': 5.2.3 + '@vitest/spy': 4.1.10 + '@vitest/utils': 4.1.10 + chai: 6.2.2 + tinyrainbow: 3.1.0 + + '@vitest/mocker@4.1.10(msw@2.15.0(@types/node@24.13.3)(typescript@7.0.2))(vite@8.1.5(@types/node@24.13.3))': + dependencies: + '@vitest/spy': 4.1.10 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + msw: 2.15.0(@types/node@24.13.3)(typescript@7.0.2) + vite: 8.1.5(@types/node@24.13.3) + + '@vitest/pretty-format@4.1.10': + dependencies: + tinyrainbow: 3.1.0 + + '@vitest/runner@4.1.10': + dependencies: + '@vitest/utils': 4.1.10 + pathe: 2.0.3 + + '@vitest/snapshot@4.1.10': + dependencies: + '@vitest/pretty-format': 4.1.10 + '@vitest/utils': 4.1.10 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@4.1.10': {} + + '@vitest/utils@4.1.10': + dependencies: + '@vitest/pretty-format': 4.1.10 + convert-source-map: 2.0.0 + tinyrainbow: 3.1.0 + + ansi-regex@5.0.1: {} + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + + ansi-styles@5.2.0: {} + + aria-query@5.3.0: + dependencies: + dequal: 2.0.3 + + aria-query@5.3.2: {} + + assertion-error@2.0.1: {} + + axe-core@4.12.1: {} + + bidi-js@1.0.3: + dependencies: + require-from-string: 2.0.2 + + chai@6.2.2: {} + + cli-width@4.1.0: {} + + cliui@8.0.1: + dependencies: + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrap-ansi: 7.0.0 + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + + convert-source-map@2.0.0: {} + + cookie@1.1.1: {} + + css-tree@3.2.1: + dependencies: + mdn-data: 2.27.1 + source-map-js: 1.2.1 + + css.escape@1.5.1: {} + csstype@3.2.3: {} + data-urls@7.0.0: + dependencies: + whatwg-mimetype: 5.0.0 + whatwg-url: 16.0.1 + transitivePeerDependencies: + - '@noble/hashes' + + decimal.js@10.6.0: {} + + dequal@2.0.3: {} + detect-libc@2.1.2: {} + dom-accessibility-api@0.5.16: {} + + dom-accessibility-api@0.6.3: {} + + emoji-regex@8.0.0: {} + + entities@8.0.0: {} + + es-module-lexer@2.3.1: {} + + escalade@3.2.0: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + expect-type@1.4.0: {} + + fast-string-truncated-width@3.0.3: {} + + fast-string-width@3.0.2: + dependencies: + fast-string-truncated-width: 3.0.3 + + fast-wrap-ansi@0.2.2: + dependencies: + fast-string-width: 3.0.2 + fdir@6.5.0(picomatch@4.0.5): optionalDependencies: picomatch: 4.0.5 + fsevents@2.3.2: + optional: true + fsevents@2.3.3: optional: true + get-caller-file@2.0.5: {} + + graphql@16.14.2: {} + + headers-polyfill@5.0.1: + dependencies: + '@types/set-cookie-parser': 2.4.10 + set-cookie-parser: 3.1.2 + + html-encoding-sniffer@6.0.0: + dependencies: + '@exodus/bytes': 1.15.1 + transitivePeerDependencies: + - '@noble/hashes' + + indent-string@4.0.0: {} + + is-fullwidth-code-point@3.0.0: {} + + is-node-process@1.2.0: {} + + is-potential-custom-element-name@1.0.1: {} + + js-tokens@4.0.0: {} + + jsdom@29.1.1: + dependencies: + '@asamuzakjp/css-color': 5.1.11 + '@asamuzakjp/dom-selector': 7.1.1 + '@bramus/specificity': 2.4.2 + '@csstools/css-syntax-patches-for-csstree': 1.1.7(css-tree@3.2.1) + '@exodus/bytes': 1.15.1 + css-tree: 3.2.1 + data-urls: 7.0.0 + decimal.js: 10.6.0 + html-encoding-sniffer: 6.0.0 + is-potential-custom-element-name: 1.0.1 + lru-cache: 11.5.2 + parse5: 8.0.1 + saxes: 6.0.0 + symbol-tree: 3.2.4 + tough-cookie: 6.0.2 + undici: 7.28.0 + w3c-xmlserializer: 5.0.0 + webidl-conversions: 8.0.1 + whatwg-mimetype: 5.0.0 + whatwg-url: 16.0.1 + xml-name-validator: 5.0.0 + transitivePeerDependencies: + - '@noble/hashes' + lightningcss-android-arm64@1.33.0: optional: true @@ -709,25 +1723,105 @@ snapshots: lightningcss-win32-arm64-msvc: 1.33.0 lightningcss-win32-x64-msvc: 1.33.0 + lru-cache@11.5.2: {} + + lz-string@1.5.0: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + + mdn-data@2.27.1: {} + + min-indent@1.0.1: {} + + msw@2.15.0(@types/node@24.13.3)(typescript@7.0.2): + dependencies: + '@inquirer/confirm': 6.1.1(@types/node@24.13.3) + '@mswjs/interceptors': 0.41.9 + '@open-draft/deferred-promise': 3.0.0 + '@types/statuses': 2.0.6 + cookie: 1.1.1 + graphql: 16.14.2 + headers-polyfill: 5.0.1 + is-node-process: 1.2.0 + outvariant: 1.4.3 + path-to-regexp: 6.3.0 + picocolors: 1.1.1 + rettime: 0.11.11 + statuses: 2.0.2 + strict-event-emitter: 0.5.1 + tough-cookie: 6.0.2 + type-fest: 5.8.0 + until-async: 3.0.2 + yargs: 17.7.3 + optionalDependencies: + typescript: 7.0.2 + transitivePeerDependencies: + - '@types/node' + + mute-stream@3.0.0: {} + nanoid@3.3.16: {} + obug@2.1.4: {} + + outvariant@1.4.3: {} + + parse5@8.0.1: + dependencies: + entities: 8.0.0 + + path-to-regexp@6.3.0: {} + + pathe@2.0.3: {} + picocolors@1.1.1: {} picomatch@4.0.5: {} + playwright-core@1.62.0: {} + + playwright@1.62.0: + dependencies: + playwright-core: 1.62.0 + optionalDependencies: + fsevents: 2.3.2 + postcss@8.5.22: dependencies: nanoid: 3.3.16 picocolors: 1.1.1 source-map-js: 1.2.1 + pretty-format@27.5.1: + dependencies: + ansi-regex: 5.0.1 + ansi-styles: 5.2.0 + react-is: 17.0.2 + + punycode@2.3.1: {} + react-dom@19.2.8(react@19.2.8): dependencies: react: 19.2.8 scheduler: 0.27.0 + react-is@17.0.2: {} + react@19.2.8: {} + redent@3.0.0: + dependencies: + indent-string: 4.0.0 + strip-indent: 3.0.0 + + require-directory@2.1.1: {} + + require-from-string@2.0.2: {} + + rettime@0.11.11: {} + rolldown@1.1.5: dependencies: '@oxc-project/types': 0.139.0 @@ -749,18 +1843,78 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.1.5 '@rolldown/binding-win32-x64-msvc': 1.1.5 + saxes@6.0.0: + dependencies: + xmlchars: 2.2.0 + scheduler@0.27.0: {} + set-cookie-parser@3.1.2: {} + + siginfo@2.0.0: {} + + signal-exit@4.1.0: {} + source-map-js@1.2.1: {} + stackback@0.0.2: {} + + statuses@2.0.2: {} + + std-env@4.2.0: {} + + strict-event-emitter@0.5.1: {} + + string-width@4.2.3: + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + + strip-indent@3.0.0: + dependencies: + min-indent: 1.0.1 + + symbol-tree@3.2.4: {} + + tagged-tag@1.0.0: {} + + tinybench@2.9.0: {} + + tinyexec@1.2.4: {} + tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.5) picomatch: 4.0.5 + tinyrainbow@3.1.0: {} + + tldts-core@7.4.9: {} + + tldts@7.4.9: + dependencies: + tldts-core: 7.4.9 + + tough-cookie@6.0.2: + dependencies: + tldts: 7.4.9 + + tr46@6.0.0: + dependencies: + punycode: 2.3.1 + tslib@2.8.1: optional: true + type-fest@5.8.0: + dependencies: + tagged-tag: 1.0.0 + typescript@7.0.2: optionalDependencies: '@typescript/typescript-aix-ppc64': 7.0.2 @@ -786,6 +1940,10 @@ snapshots: undici-types@7.18.2: {} + undici@7.28.0: {} + + until-async@3.0.2: {} + vite@8.1.5(@types/node@24.13.3): dependencies: lightningcss: 1.33.0 @@ -796,3 +1954,76 @@ snapshots: optionalDependencies: '@types/node': 24.13.3 fsevents: 2.3.3 + + vitest@4.1.10(@types/node@24.13.3)(jsdom@29.1.1)(msw@2.15.0(@types/node@24.13.3)(typescript@7.0.2))(vite@8.1.5(@types/node@24.13.3)): + dependencies: + '@vitest/expect': 4.1.10 + '@vitest/mocker': 4.1.10(msw@2.15.0(@types/node@24.13.3)(typescript@7.0.2))(vite@8.1.5(@types/node@24.13.3)) + '@vitest/pretty-format': 4.1.10 + '@vitest/runner': 4.1.10 + '@vitest/snapshot': 4.1.10 + '@vitest/spy': 4.1.10 + '@vitest/utils': 4.1.10 + es-module-lexer: 2.3.1 + expect-type: 1.4.0 + magic-string: 0.30.21 + obug: 2.1.4 + pathe: 2.0.3 + picomatch: 4.0.5 + std-env: 4.2.0 + tinybench: 2.9.0 + tinyexec: 1.2.4 + tinyglobby: 0.2.17 + tinyrainbow: 3.1.0 + vite: 8.1.5(@types/node@24.13.3) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 24.13.3 + jsdom: 29.1.1 + transitivePeerDependencies: + - msw + + w3c-xmlserializer@5.0.0: + dependencies: + xml-name-validator: 5.0.0 + + webidl-conversions@8.0.1: {} + + whatwg-mimetype@5.0.0: {} + + whatwg-url@16.0.1: + dependencies: + '@exodus/bytes': 1.15.1 + tr46: 6.0.0 + webidl-conversions: 8.0.1 + transitivePeerDependencies: + - '@noble/hashes' + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + wrap-ansi@7.0.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + + xml-name-validator@5.0.0: {} + + xmlchars@2.2.0: {} + + y18n@5.0.8: {} + + yargs-parser@21.1.1: {} + + yargs@17.7.3: + dependencies: + cliui: 8.0.1 + escalade: 3.2.0 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + string-width: 4.2.3 + y18n: 5.0.8 + yargs-parser: 21.1.1 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 00000000..20708402 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,6 @@ +allowBuilds: + msw: true +minimumReleaseAgeExclude: + - '@playwright/test@1.62.0' + - playwright-core@1.62.0 + - playwright@1.62.0 diff --git a/tests/component/bootstrap-shell.test.jsx b/tests/component/bootstrap-shell.test.jsx new file mode 100644 index 00000000..2a6f7c29 --- /dev/null +++ b/tests/component/bootstrap-shell.test.jsx @@ -0,0 +1,17 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +function TestShell() { + return
ready
; +} + +describe("component test level", () => { + it("renders an accessible application shell", () => { + render(); + expect(screen.getByRole("main", { name: "application shell" })).toHaveTextContent( + "ready", + ); + }); +}); diff --git a/tests/e2e/app-shell.spec.js b/tests/e2e/app-shell.spec.js new file mode 100644 index 00000000..f262105e --- /dev/null +++ b/tests/e2e/app-shell.spec.js @@ -0,0 +1,8 @@ +import { expect, test } from "@playwright/test"; + +test("boots the public app shell", async ({ page }) => { + await page.goto("/"); + await expect(page.getByRole("heading", { level: 1 })).toHaveText( + "Clean Architecture Frontend", + ); +}); diff --git a/tests/integration/http-boundary.test.js b/tests/integration/http-boundary.test.js new file mode 100644 index 00000000..e7283a92 --- /dev/null +++ b/tests/integration/http-boundary.test.js @@ -0,0 +1,23 @@ +import { HttpResponse, http } from "msw"; +import { setupServer } from "msw/node"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; + +const server = setupServer( + http.get("https://example.test/health", () => + HttpResponse.json({ success: true, data: { status: "ok" } }), + ), +); + +beforeAll(() => server.listen({ onUnhandledRequest: "error" })); +afterEach(() => server.resetHandlers()); +afterAll(() => server.close()); + +describe("integration test level", () => { + it("uses MSW to isolate the HTTP boundary", async () => { + const response = await fetch("https://example.test/health"); + await expect(response.json()).resolves.toEqual({ + success: true, + data: { status: "ok" }, + }); + }); +}); diff --git a/tests/setup.js b/tests/setup.js new file mode 100644 index 00000000..e2621932 --- /dev/null +++ b/tests/setup.js @@ -0,0 +1,7 @@ +import "@testing-library/jest-dom/vitest"; +import { cleanup } from "@testing-library/react"; +import { afterEach } from "vitest"; + +afterEach(() => { + cleanup(); +}); diff --git a/tests/unit/system-clock.test.js b/tests/unit/system-clock.test.js new file mode 100644 index 00000000..e2761b9e --- /dev/null +++ b/tests/unit/system-clock.test.js @@ -0,0 +1,13 @@ +import { describe, expect, it, vi } from "vitest"; + +import { systemClock } from "../../src/application/ports/clock-port.js"; + +describe("systemClock", () => { + it("resolves after the requested duration", async () => { + vi.useFakeTimers(); + const sleeper = systemClock.sleep(250); + await vi.advanceTimersByTimeAsync(250); + await expect(sleeper).resolves.toBeUndefined(); + vi.useRealTimers(); + }); +}); diff --git a/vitest.config.js b/vitest.config.js new file mode 100644 index 00000000..4293e824 --- /dev/null +++ b/vitest.config.js @@ -0,0 +1,15 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + globals: false, + setupFiles: ["./tests/setup.js"], + restoreMocks: true, + clearMocks: true, + mockReset: true, + testTimeout: 10_000, + coverage: { + reporter: ["text", "json-summary"], + }, + }, +}); From f3e105f97134fa8f8bdfa5dbc5c008818cdabe88 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 20:43:49 +0900 Subject: [PATCH 005/178] feat: enforce frontend architecture boundaries --- .dependency-cruiser.cjs | 49 + eslint.config.js | 101 +++ package.json | 6 + pnpm-lock.yaml | 839 ++++++++++++++++++ pnpm-workspace.yaml | 1 + scripts/check-architecture.mjs | 69 ++ .../allowed/presentation-facade.js | 3 + .../forbidden/application-imports-tanstack.js | 3 + .../forbidden/domain-imports-react.js | 3 + .../forbidden/presentation-imports-adapter.js | 3 + 10 files changed, 1077 insertions(+) create mode 100644 .dependency-cruiser.cjs create mode 100644 eslint.config.js create mode 100644 scripts/check-architecture.mjs create mode 100644 tests/fixtures/architecture/allowed/presentation-facade.js create mode 100644 tests/fixtures/architecture/forbidden/application-imports-tanstack.js create mode 100644 tests/fixtures/architecture/forbidden/domain-imports-react.js create mode 100644 tests/fixtures/architecture/forbidden/presentation-imports-adapter.js diff --git a/.dependency-cruiser.cjs b/.dependency-cruiser.cjs new file mode 100644 index 00000000..4290d0ce --- /dev/null +++ b/.dependency-cruiser.cjs @@ -0,0 +1,49 @@ +/** @type {import("dependency-cruiser").IConfiguration} */ +module.exports = { + forbidden: [ + { + name: "domain-is-framework-neutral", + severity: "error", + from: { path: "^src/domain" }, + to: { + path: "^(src/(application|presentation|adapters|bootstrap)|react|react-dom|@tanstack)", + }, + }, + { + name: "application-does-not-know-concrete-runtime", + severity: "error", + from: { path: "^src/application" }, + to: { + path: "^(src/(presentation|adapters|bootstrap)|react|react-dom|@tanstack)", + }, + }, + { + name: "presentation-does-not-know-adapters", + severity: "error", + from: { path: "^src/presentation" }, + to: { path: "^(src/(adapters|bootstrap)|@tanstack)" }, + }, + { + name: "adapters-do-not-know-presentation", + severity: "error", + from: { path: "^src/adapters" }, + to: { path: "^src/(presentation|bootstrap)" }, + }, + { + name: "no-circular-dependencies", + severity: "error", + from: {}, + to: { circular: true }, + }, + ], + options: { + doNotFollow: { path: "node_modules" }, + exclude: { + path: "^(dist|artifacts|tests/fixtures)", + }, + enhancedResolveOptions: { + exportsFields: ["exports"], + conditionNames: ["import", "require", "node", "default"], + }, + }, +}; diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 00000000..a6f17a38 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,101 @@ +import eslint from "@eslint/js"; +import globals from "globals"; + +const layerPatterns = { + domain: [ + "**/application/**", + "**/presentation/**", + "**/adapters/**", + "**/bootstrap/**", + "react", + "react-dom", + "@tanstack/**", + ], + application: [ + "**/presentation/**", + "**/adapters/**", + "**/bootstrap/**", + "react", + "react-dom", + "@tanstack/**", + ], + presentation: ["**/adapters/**", "**/bootstrap/**", "@tanstack/**"], + adapters: ["**/presentation/**", "**/bootstrap/**"], +}; + +function restrictedImports(patterns) { + return ["error", { patterns }]; +} + +export default [ + { + ignores: [ + "dist/**", + "node_modules/**", + "artifacts/**", + "tests/fixtures/typecheck/**", + "tests/fixtures/architecture/forbidden/**", + ], + }, + eslint.configs.recommended, + { + files: ["**/*.{js,jsx,mjs}"], + languageOptions: { + ecmaVersion: "latest", + sourceType: "module", + globals: { + ...globals.browser, + ...globals.node, + }, + parserOptions: { + ecmaFeatures: { jsx: true }, + }, + }, + }, + { + files: ["src/domain/**/*.{js,jsx}"], + rules: { + "no-restricted-imports": restrictedImports(layerPatterns.domain), + "no-restricted-globals": ["error", "window", "document", "localStorage", "fetch"], + }, + }, + { + files: ["src/application/**/*.{js,jsx}"], + rules: { + "no-restricted-imports": restrictedImports(layerPatterns.application), + "no-restricted-globals": ["error", "window", "document", "localStorage", "fetch"], + }, + }, + { + files: ["src/presentation/**/*.{js,jsx}"], + rules: { + "no-restricted-imports": restrictedImports(layerPatterns.presentation), + }, + }, + { + files: ["src/adapters/**/*.{js,jsx}"], + rules: { + "no-restricted-imports": restrictedImports(layerPatterns.adapters), + }, + }, + { + files: ["tests/**/*.{js,jsx}"], + languageOptions: { + globals: { + ...globals.browser, + ...globals.node, + }, + }, + }, + { + files: ["tests/fixtures/architecture/forbidden/**/*.{js,jsx}"], + rules: { + "no-restricted-imports": restrictedImports([ + "**/adapters/**", + "@tanstack/**", + "react", + "react-dom", + ]), + }, + }, +]; diff --git a/package.json b/package.json index 9c484344..e9cb437e 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,8 @@ "dev": "vite", "build": "vite build && node scripts/generate-build-manifest.mjs", "preview": "vite preview", + "lint": "eslint src scripts tests vite.config.js vitest.config.js playwright.config.js --max-warnings=0", + "check:architecture": "node scripts/check-architecture.mjs", "check:types": "tsc --allowJs --checkJs --noEmit", "check:types:fixture": "tsc --allowJs --checkJs --noEmit --target ES2022 --module NodeNext --moduleResolution NodeNext tests/fixtures/typecheck/invalid-port-call.js", "test:runtime-schema": "vitest run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests", @@ -28,6 +30,7 @@ }, "devDependencies": { "@axe-core/playwright": "4.12.1", + "@eslint/js": "10.0.1", "@playwright/test": "1.62.0", "@testing-library/jest-dom": "7.0.0", "@testing-library/react": "16.3.2", @@ -36,6 +39,9 @@ "@types/react": "19.2.8", "@types/react-dom": "19.2.3", "@vitejs/plugin-react": "6.0.4", + "dependency-cruiser": "18.1.0", + "eslint": "10.8.0", + "globals": "17.7.0", "jsdom": "29.1.1", "msw": "2.15.0", "typescript": "7.0.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b611b982..2304627d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -18,6 +18,9 @@ importers: '@axe-core/playwright': specifier: 4.12.1 version: 4.12.1(playwright-core@1.62.0) + '@eslint/js': + specifier: 10.0.1 + version: 10.0.1(eslint@10.8.0(supports-color@7.2.0)) '@playwright/test': specifier: 1.62.0 version: 1.62.0 @@ -42,6 +45,15 @@ importers: '@vitejs/plugin-react': specifier: 6.0.4 version: 6.0.4(vite@8.1.5(@types/node@24.13.3)) + dependency-cruiser: + specifier: 18.1.0 + version: 18.1.0 + eslint: + specifier: 10.8.0 + version: 10.8.0(supports-color@7.2.0) + globals: + specifier: 17.7.0 + version: 17.7.0 jsdom: specifier: 29.1.1 version: 29.1.1 @@ -144,6 +156,45 @@ packages: '@emnapi/wasi-threads@1.2.2': resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==} + '@eslint-community/eslint-utils@4.10.1': + resolution: {integrity: sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 + + '@eslint-community/regexpp@4.12.2': + resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==} + engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + + '@eslint/config-array@0.23.5': + resolution: {integrity: sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/config-helpers@0.7.0': + resolution: {integrity: sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/core@1.2.1': + resolution: {integrity: sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/js@10.0.1': + resolution: {integrity: sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + peerDependencies: + eslint: ^10.0.0 + peerDependenciesMeta: + eslint: + optional: true + + '@eslint/object-schema@3.0.5': + resolution: {integrity: sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + '@eslint/plugin-kit@0.7.2': + resolution: {integrity: sha512-+CNAzxglkrpNf/kKywqQfk74QjtceuOE7Qm+AF8miRvPF/wmmK5+OJOgVh3AVTT3RP2mH3+FOaxlE5v72owk0A==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + '@exodus/bytes@1.15.1': resolution: {integrity: sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==} engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} @@ -153,6 +204,26 @@ packages: '@noble/hashes': optional: true + '@humanfs/core@0.19.2': + resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} + engines: {node: '>=18.18.0'} + + '@humanfs/node@0.16.8': + resolution: {integrity: sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==} + engines: {node: '>=18.18.0'} + + '@humanfs/types@0.15.0': + resolution: {integrity: sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==} + engines: {node: '>=18.18.0'} + + '@humanwhocodes/module-importer@1.0.1': + resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} + engines: {node: '>=12.22'} + + '@humanwhocodes/retry@0.4.3': + resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} + engines: {node: '>=18.18'} + '@inquirer/ansi@2.0.7': resolution: {integrity: sha512-3eTuUO1vH2cZm2ZKHeQxnOqlTi9EfZDGgIe3BL3I4u+rJHocr9Fz86M4fjYABPvFnQG/gGK551HqDiIcETwU6Q==} engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} @@ -365,9 +436,15 @@ packages: '@types/deep-eql@4.0.2': resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + '@types/esrecurse@4.3.1': + resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==} + '@types/estree@1.0.9': resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + '@types/json-schema@7.0.15': + resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + '@types/node@24.13.3': resolution: {integrity: sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==} @@ -547,6 +624,30 @@ packages: '@vitest/utils@4.1.10': resolution: {integrity: sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==} + acorn-jsx-walk@2.0.0: + resolution: {integrity: sha512-uuo6iJj4D4ygkdzd6jPtcxs8vZgDX9YFIkqczGImoypX2fQ4dVImmu3UzA4ynixCIMTrEOWW+95M2HuBaCEOVA==} + + acorn-jsx@5.3.2: + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + + acorn-loose@8.5.2: + resolution: {integrity: sha512-PPvV6g8UGMGgjrMu+n/f9E/tCSkNQ2Y97eFvuVdJfG11+xdIeDcLyNdC8SHcrHbRqkfwLASdplyR6B6sKM1U4A==} + engines: {node: '>=0.4.0'} + + acorn-walk@8.3.5: + resolution: {integrity: sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==} + engines: {node: '>=0.4.0'} + + acorn@8.17.0: + resolution: {integrity: sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==} + engines: {node: '>=0.4.0'} + hasBin: true + + ajv@6.15.0: + resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} + ansi-regex@5.0.1: resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} engines: {node: '>=8'} @@ -574,13 +675,25 @@ packages: resolution: {integrity: sha512-s7iGf5GaVMxEG0ENN9x+xTr7GFZCb1ZP/1uATUpCEK2X78nDB3RwbtFCo9pGAf9ru+VwoQ464DkaLEeRM08wJA==} engines: {node: '>=4'} + balanced-match@4.0.4: + resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} + engines: {node: 18 || 20 || >=22} + bidi-js@1.0.3: resolution: {integrity: sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==} + brace-expansion@5.0.8: + resolution: {integrity: sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==} + engines: {node: 20 || >=22} + chai@6.2.2: resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} engines: {node: '>=18'} + chalk@4.1.2: + resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} + engines: {node: '>=10'} + cli-width@4.1.0: resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==} engines: {node: '>= 12'} @@ -596,6 +709,10 @@ packages: color-name@1.1.4: resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + commander@15.0.0: + resolution: {integrity: sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==} + engines: {node: '>=22.12.0'} + convert-source-map@2.0.0: resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} @@ -603,6 +720,10 @@ packages: resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} engines: {node: '>=18'} + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + css-tree@3.2.1: resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==} engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} @@ -617,9 +738,26 @@ packages: resolution: {integrity: sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==} engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + decimal.js@10.6.0: resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} + deep-is@0.1.4: + resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + + dependency-cruiser@18.1.0: + resolution: {integrity: sha512-pbsH0gQ15BxXi97SCuMeVgsh8VzYpziGIVaMdnALbVu+TYjSZrW9/nOvsPU+NjHLmJSF9R1UijjoACq6Ne/ybQ==} + engines: {node: ^22||^24||>=26} + hasBin: true + dequal@2.0.3: resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} engines: {node: '>=6'} @@ -637,10 +775,18 @@ packages: emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + enhanced-resolve@5.24.2: + resolution: {integrity: sha512-rpsZEGT1jFuve6QlpyRp9ckQ+kN61hvF9BzCPyMdaKTm8UJce96KBn3sorXOFXlzjPrs3Vc4T1NsSroZ3PxlFw==} + engines: {node: '>=10.13.0'} + entities@8.0.0: resolution: {integrity: sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==} engines: {node: '>=20.19.0'} + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + es-module-lexer@2.3.1: resolution: {integrity: sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==} @@ -648,13 +794,68 @@ packages: resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} engines: {node: '>=6'} + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + + eslint-scope@9.1.2: + resolution: {integrity: sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + eslint-visitor-keys@3.4.3: + resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-visitor-keys@5.0.1: + resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + eslint@10.8.0: + resolution: {integrity: sha512-nuKKvN+oIBO0koN7Tm7dlkmnkc21mtt0QJLwAKzjLq14y6lRTdVG36MZHJ8eQHwdJMwZbQNMlPOYedMq/oVJvQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + hasBin: true + peerDependencies: + jiti: '*' + peerDependenciesMeta: + jiti: + optional: true + + espree@11.2.0: + resolution: {integrity: sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + esquery@1.7.0: + resolution: {integrity: sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==} + engines: {node: '>=0.10'} + + esrecurse@4.3.0: + resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} + engines: {node: '>=4.0'} + + estraverse@5.3.0: + resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} + engines: {node: '>=4.0'} + estree-walker@3.0.3: resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + esutils@2.0.3: + resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} + engines: {node: '>=0.10.0'} + expect-type@1.4.0: resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} engines: {node: '>=12.0.0'} + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-json-stable-stringify@2.1.0: + resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + + fast-levenshtein@2.0.6: + resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + fast-string-truncated-width@3.0.3: resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==} @@ -673,6 +874,21 @@ packages: picomatch: optional: true + file-entry-cache@8.0.0: + resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} + engines: {node: '>=16.0.0'} + + find-up@5.0.0: + resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} + engines: {node: '>=10'} + + flat-cache@4.0.1: + resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} + engines: {node: '>=16'} + + flatted@3.4.3: + resolution: {integrity: sha512-/zipXxyO6rGvuNGDiULY9MvEGSkb2gaG4GGH4ygMi0ZZzyMHdUZBmntJmx5x1G2VuPytCwGN4xsJP6cw+sK+vQ==} + fsevents@2.3.2: resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -683,14 +899,40 @@ packages: engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} os: [darwin] + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + get-caller-file@2.0.5: resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} engines: {node: 6.* || 8.* || >= 10.*} + glob-parent@6.0.2: + resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} + engines: {node: '>=10.13.0'} + + global-directory@4.0.1: + resolution: {integrity: sha512-wHTUcDUoZ1H5/0iVqEudYW4/kAlN5cZ3j/bXn0Dpbizl9iaUVeWSHqiOjsgk6OW2bkLclbBjzewBz6weQ1zA2Q==} + engines: {node: '>=18'} + + globals@17.7.0: + resolution: {integrity: sha512-Czmyns5dUsq4seFBR/Kdydhmo8y9kC79hiSkPn0YcGtNnYWnrgt0vjrSjx9tspoDGWm2CMarffRuLjM4xUz8xg==} + engines: {node: '>=18'} + + graceful-fs@4.2.11: + resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + graphql@16.14.2: resolution: {integrity: sha512-Chq1s4CY7jmh8gO2qvLIJyfCDIN+EHLFW/9iShnp1z8FjBQMoodWP1kDC36VAMXXIvAjj4ARa7ntfAV2BrjsbA==} engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0} + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + + hasown@2.0.4: + resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} + engines: {node: '>= 0.4'} + headers-polyfill@5.0.1: resolution: {integrity: sha512-1TJ6Fih/b8h5TIcv+1+Hw0PDQWJTKDKzFZzcKOiW1wJza3XoAQlkCuXLbymPYB8+ZQyw8mHvdw560e8zVFIWyA==} @@ -698,20 +940,63 @@ packages: resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==} engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + ignore@5.3.2: + resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} + engines: {node: '>= 4'} + + ignore@7.0.6: + resolution: {integrity: sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw==} + engines: {node: '>= 4'} + + imurmurhash@0.1.4: + resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} + engines: {node: '>=0.8.19'} + indent-string@4.0.0: resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==} engines: {node: '>=8'} + ini@4.1.1: + resolution: {integrity: sha512-QQnnxNyfvmHFIsj7gkPcYymR8Jdw/o7mp5ZFihxn6h8Ci6fh3Dx4E1gPjpQEpIuPo9XVNY/ZUwh4BPMjGyL01g==} + engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} + + interpret@3.1.1: + resolution: {integrity: sha512-6xwYfHbajpoF0xLW+iwLkhwgvLoZDfjYfoFNu8ftMoXINzwuymNLd9u/KmwtdT2GbR+/Cz66otEGEVVUHX9QLQ==} + engines: {node: '>=10.13.0'} + + is-core-module@2.16.2: + resolution: {integrity: sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==} + engines: {node: '>= 0.4'} + + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + is-fullwidth-code-point@3.0.0: resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} engines: {node: '>=8'} + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + + is-installed-globally@1.0.0: + resolution: {integrity: sha512-K55T22lfpQ63N4KEN57jZUAaAYqYHEe8veb/TycJRk9DdSCLLcovXz/mL6mOnhQaZsQGwPhuFopdQIlqGSEjiQ==} + engines: {node: '>=18'} + is-node-process@1.2.0: resolution: {integrity: sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw==} + is-path-inside@4.0.0: + resolution: {integrity: sha512-lJJV/5dYS+RcL8uQdBDW9c9uWFLLBNRyFhnAKXw5tVqLlKZ4RMGZKv+YQ/IA3OhD+RpbJa1LLFM1FQPGyIXvOA==} + engines: {node: '>=12'} + is-potential-custom-element-name@1.0.1: resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -724,6 +1009,31 @@ packages: canvas: optional: true + json-buffer@3.0.1: + resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} + + json-schema-traverse@0.4.1: + resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + + json-stable-stringify-without-jsonify@1.0.1: + resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + + json5@2.2.3: + resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} + engines: {node: '>=6'} + hasBin: true + + keyv@4.5.4: + resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} + + kleur@3.0.3: + resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==} + engines: {node: '>=6'} + + levn@0.4.1: + resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} + engines: {node: '>= 0.8.0'} + lightningcss-android-arm64@1.33.0: resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} engines: {node: '>= 12.0.0'} @@ -798,6 +1108,10 @@ packages: resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} engines: {node: '>= 12.0.0'} + locate-path@6.0.0: + resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} + engines: {node: '>=10'} + lru-cache@11.5.2: resolution: {integrity: sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==} engines: {node: 20 || >=22} @@ -816,6 +1130,16 @@ packages: resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==} engines: {node: '>=4'} + minimatch@10.2.5: + resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} + engines: {node: 18 || 20 || >=22} + + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + msw@2.15.0: resolution: {integrity: sha512-2wQAmKkQKxRuXvYJxVhPGG0wZNBQyD06oJvxqw90XqLvptdqxdlHrFUfEteKkpaNORX3Xzc+HtEl/q0nfmN2wQ==} engines: {node: '>=18'} @@ -835,16 +1159,42 @@ packages: engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true + natural-compare@1.4.0: + resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + obug@2.1.4: resolution: {integrity: sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==} engines: {node: '>=12.20.0'} + optionator@0.9.4: + resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} + engines: {node: '>= 0.8.0'} + outvariant@1.4.3: resolution: {integrity: sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA==} + p-limit@3.1.0: + resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} + engines: {node: '>=10'} + + p-locate@5.0.0: + resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} + engines: {node: '>=10'} + parse5@8.0.1: resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==} + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + path-parse@1.0.7: + resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} + path-to-regexp@6.3.0: resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==} @@ -872,10 +1222,18 @@ packages: resolution: {integrity: sha512-KBDEIpLrvpv16pp3K0Fw+UCoZfopFjjgeB+0tA/aaThfEE74kKDLrgg603YvOWJyg3+WYtyq3xYsQWsIyZlPqQ==} engines: {node: ^10 || ^12 || >=14} + prelude-ls@1.2.1: + resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} + engines: {node: '>= 0.8.0'} + pretty-format@27.5.1: resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==} engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} + prompts@2.4.2: + resolution: {integrity: sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==} + engines: {node: '>= 6'} + punycode@2.3.1: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} @@ -892,10 +1250,18 @@ packages: resolution: {integrity: sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==} engines: {node: '>=0.10.0'} + rechoir@0.8.0: + resolution: {integrity: sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ==} + engines: {node: '>= 10.13.0'} + redent@3.0.0: resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==} engines: {node: '>=8'} + regexp-tree@0.1.27: + resolution: {integrity: sha512-iETxpjK6YoRWJG5o6hXLwvjYAoW+FEZn9os0PD/b6AP6xQwsa/Y7lCVgIixBbUPMfhu+i2LtdeAqVTgGlQarfA==} + hasBin: true + require-directory@2.1.1: resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} engines: {node: '>=0.10.0'} @@ -904,6 +1270,11 @@ packages: resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} engines: {node: '>=0.10.0'} + resolve@1.22.12: + resolution: {integrity: sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==} + engines: {node: '>= 0.4'} + hasBin: true + rettime@0.11.11: resolution: {integrity: sha512-ILJRqVWBCTlg9r42fFgwVZx1gnFAcQF8mRoMkbgQfIrjEDf9nbBFDFx00oloOa+Q869FUtaYDXZvEfnecQSCoQ==} @@ -912,6 +1283,9 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} hasBin: true + safe-regex@2.1.1: + resolution: {integrity: sha512-rx+x8AMzKb5Q5lQ95Zoi6ZbJqwCLkqi3XuJXp5P3rT8OEc6sZCJG5AE5dU3lsgRr/F4Bs31jSlVN+j5KrsGu9A==} + saxes@6.0.0: resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} engines: {node: '>=v12.22.7'} @@ -919,9 +1293,22 @@ packages: scheduler@0.27.0: resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==} + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + set-cookie-parser@3.1.2: resolution: {integrity: sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw==} + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} @@ -929,6 +1316,9 @@ packages: resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} engines: {node: '>=14'} + sisteransi@1.0.5: + resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==} + source-map-js@1.2.1: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} @@ -954,10 +1344,22 @@ packages: resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} engines: {node: '>=8'} + strip-bom@3.0.0: + resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==} + engines: {node: '>=4'} + strip-indent@3.0.0: resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==} engines: {node: '>=8'} + supports-color@7.2.0: + resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} + engines: {node: '>=8'} + + supports-preserve-symlinks-flag@1.0.0: + resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} + engines: {node: '>= 0.4'} + symbol-tree@3.2.4: resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} @@ -965,6 +1367,10 @@ packages: resolution: {integrity: sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==} engines: {node: '>=20'} + tapable@2.3.3: + resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==} + engines: {node: '>=6'} + tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} @@ -995,9 +1401,21 @@ packages: resolution: {integrity: sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==} engines: {node: '>=20'} + tsconfig-paths-webpack-plugin@4.2.0: + resolution: {integrity: sha512-zbem3rfRS8BgeNK50Zz5SIQgXzLafiHjOwUAvk/38/o1jHn/V5QAgVUcz884or7WYcPaH3N2CIfUc2u0ul7UcA==} + engines: {node: '>=10.13.0'} + + tsconfig-paths@4.2.0: + resolution: {integrity: sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg==} + engines: {node: '>=6'} + tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + type-check@0.4.0: + resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} + engines: {node: '>= 0.8.0'} + type-fest@5.8.0: resolution: {integrity: sha512-YGYEVz3Fm5iy/AybuA0oyNFq7H4CgQNfRp/qfe8nurE1kuCeNm3/vfm9X4Mtl+qLyaKJUh5xrFZwogr41SMjYA==} engines: {node: '>=20'} @@ -1017,6 +1435,9 @@ packages: until-async@3.0.2: resolution: {integrity: sha512-IiSk4HlzAMqTUseHHe3VhIGyuFmN90zMTpD3Z3y8jeQbzLIq500MVM7Jq2vUAnTKAFPJrqwkzr6PoTcPhGcOiw==} + uri-js@4.4.1: + resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + vite@8.1.5: resolution: {integrity: sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -1105,6 +1526,11 @@ packages: resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==} engines: {node: '>=18'} + watskeburt@6.0.0: + resolution: {integrity: sha512-jfiuDABaxSkC71T6oZ3vCS99roYkSHm/+As+G0Dz8taAHQb+SJBvLEm5RlsgG71XdfAj3rv7eudUBTgwcQUPlQ==} + engines: {node: ^22.13||^24||>=26} + hasBin: true + webidl-conversions@8.0.1: resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==} engines: {node: '>=20'} @@ -1117,11 +1543,20 @@ packages: resolution: {integrity: sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==} engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + why-is-node-running@2.3.0: resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} engines: {node: '>=8'} hasBin: true + word-wrap@1.2.5: + resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} + engines: {node: '>=0.10.0'} + wrap-ansi@7.0.0: resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} engines: {node: '>=10'} @@ -1145,6 +1580,10 @@ packages: resolution: {integrity: sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==} engines: {node: '>=12'} + yocto-queue@0.1.0: + resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} + engines: {node: '>=10'} + snapshots: '@adobe/css-tools@4.5.0': {} @@ -1228,8 +1667,58 @@ snapshots: tslib: 2.8.1 optional: true + '@eslint-community/eslint-utils@4.10.1(eslint@10.8.0(supports-color@7.2.0))': + dependencies: + eslint: 10.8.0(supports-color@7.2.0) + eslint-visitor-keys: 3.4.3 + + '@eslint-community/regexpp@4.12.2': {} + + '@eslint/config-array@0.23.5(supports-color@7.2.0)': + dependencies: + '@eslint/object-schema': 3.0.5 + debug: 4.4.3(supports-color@7.2.0) + minimatch: 10.2.5 + transitivePeerDependencies: + - supports-color + + '@eslint/config-helpers@0.7.0': + dependencies: + '@eslint/core': 1.2.1 + + '@eslint/core@1.2.1': + dependencies: + '@types/json-schema': 7.0.15 + + '@eslint/js@10.0.1(eslint@10.8.0(supports-color@7.2.0))': + optionalDependencies: + eslint: 10.8.0(supports-color@7.2.0) + + '@eslint/object-schema@3.0.5': {} + + '@eslint/plugin-kit@0.7.2': + dependencies: + '@eslint/core': 1.2.1 + levn: 0.4.1 + '@exodus/bytes@1.15.1': {} + '@humanfs/core@0.19.2': + dependencies: + '@humanfs/types': 0.15.0 + + '@humanfs/node@0.16.8': + dependencies: + '@humanfs/core': 0.19.2 + '@humanfs/types': 0.15.0 + '@humanwhocodes/retry': 0.4.3 + + '@humanfs/types@0.15.0': {} + + '@humanwhocodes/module-importer@1.0.1': {} + + '@humanwhocodes/retry@0.4.3': {} + '@inquirer/ansi@2.0.7': {} '@inquirer/confirm@6.1.1(@types/node@24.13.3)': @@ -1394,8 +1883,12 @@ snapshots: '@types/deep-eql@4.0.2': {} + '@types/esrecurse@4.3.1': {} + '@types/estree@1.0.9': {} + '@types/json-schema@7.0.15': {} + '@types/node@24.13.3': dependencies: undici-types: 7.18.2 @@ -1521,6 +2014,29 @@ snapshots: convert-source-map: 2.0.0 tinyrainbow: 3.1.0 + acorn-jsx-walk@2.0.0: {} + + acorn-jsx@5.3.2(acorn@8.17.0): + dependencies: + acorn: 8.17.0 + + acorn-loose@8.5.2: + dependencies: + acorn: 8.17.0 + + acorn-walk@8.3.5: + dependencies: + acorn: 8.17.0 + + acorn@8.17.0: {} + + ajv@6.15.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-json-stable-stringify: 2.1.0 + json-schema-traverse: 0.4.1 + uri-js: 4.4.1 + ansi-regex@5.0.1: {} ansi-styles@4.3.0: @@ -1539,12 +2055,23 @@ snapshots: axe-core@4.12.1: {} + balanced-match@4.0.4: {} + bidi-js@1.0.3: dependencies: require-from-string: 2.0.2 + brace-expansion@5.0.8: + dependencies: + balanced-match: 4.0.4 + chai@6.2.2: {} + chalk@4.1.2: + dependencies: + ansi-styles: 4.3.0 + supports-color: 7.2.0 + cli-width@4.1.0: {} cliui@8.0.1: @@ -1559,10 +2086,18 @@ snapshots: color-name@1.1.4: {} + commander@15.0.0: {} + convert-source-map@2.0.0: {} cookie@1.1.1: {} + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + css-tree@3.2.1: dependencies: mdn-data: 2.27.1 @@ -1579,8 +2114,37 @@ snapshots: transitivePeerDependencies: - '@noble/hashes' + debug@4.4.3(supports-color@7.2.0): + dependencies: + ms: 2.1.3 + optionalDependencies: + supports-color: 7.2.0 + decimal.js@10.6.0: {} + deep-is@0.1.4: {} + + dependency-cruiser@18.1.0: + dependencies: + acorn: 8.17.0 + acorn-jsx: 5.3.2(acorn@8.17.0) + acorn-jsx-walk: 2.0.0 + acorn-loose: 8.5.2 + acorn-walk: 8.3.5 + commander: 15.0.0 + enhanced-resolve: 5.24.2 + ignore: 7.0.6 + interpret: 3.1.1 + is-installed-globally: 1.0.0 + json5: 2.2.3 + picomatch: 4.0.5 + prompts: 2.4.2 + rechoir: 0.8.0 + safe-regex: 2.1.1 + semver: 7.8.5 + tsconfig-paths-webpack-plugin: 4.2.0 + watskeburt: 6.0.0 + dequal@2.0.3: {} detect-libc@2.1.2: {} @@ -1591,18 +2155,97 @@ snapshots: emoji-regex@8.0.0: {} + enhanced-resolve@5.24.2: + dependencies: + graceful-fs: 4.2.11 + tapable: 2.3.3 + entities@8.0.0: {} + es-errors@1.3.0: {} + es-module-lexer@2.3.1: {} escalade@3.2.0: {} + escape-string-regexp@4.0.0: {} + + eslint-scope@9.1.2: + dependencies: + '@types/esrecurse': 4.3.1 + '@types/estree': 1.0.9 + esrecurse: 4.3.0 + estraverse: 5.3.0 + + eslint-visitor-keys@3.4.3: {} + + eslint-visitor-keys@5.0.1: {} + + eslint@10.8.0(supports-color@7.2.0): + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@10.8.0(supports-color@7.2.0)) + '@eslint-community/regexpp': 4.12.2 + '@eslint/config-array': 0.23.5(supports-color@7.2.0) + '@eslint/config-helpers': 0.7.0 + '@eslint/core': 1.2.1 + '@eslint/plugin-kit': 0.7.2 + '@humanfs/node': 0.16.8 + '@humanwhocodes/module-importer': 1.0.1 + '@humanwhocodes/retry': 0.4.3 + '@types/estree': 1.0.9 + ajv: 6.15.0 + cross-spawn: 7.0.6 + debug: 4.4.3(supports-color@7.2.0) + escape-string-regexp: 4.0.0 + eslint-scope: 9.1.2 + eslint-visitor-keys: 5.0.1 + espree: 11.2.0 + esquery: 1.7.0 + esutils: 2.0.3 + fast-deep-equal: 3.1.3 + file-entry-cache: 8.0.0 + find-up: 5.0.0 + glob-parent: 6.0.2 + ignore: 5.3.2 + imurmurhash: 0.1.4 + is-glob: 4.0.3 + json-stable-stringify-without-jsonify: 1.0.1 + minimatch: 10.2.5 + natural-compare: 1.4.0 + optionator: 0.9.4 + transitivePeerDependencies: + - supports-color + + espree@11.2.0: + dependencies: + acorn: 8.17.0 + acorn-jsx: 5.3.2(acorn@8.17.0) + eslint-visitor-keys: 5.0.1 + + esquery@1.7.0: + dependencies: + estraverse: 5.3.0 + + esrecurse@4.3.0: + dependencies: + estraverse: 5.3.0 + + estraverse@5.3.0: {} + estree-walker@3.0.3: dependencies: '@types/estree': 1.0.9 + esutils@2.0.3: {} + expect-type@1.4.0: {} + fast-deep-equal@3.1.3: {} + + fast-json-stable-stringify@2.1.0: {} + + fast-levenshtein@2.0.6: {} + fast-string-truncated-width@3.0.3: {} fast-string-width@3.0.2: @@ -1617,16 +2260,52 @@ snapshots: optionalDependencies: picomatch: 4.0.5 + file-entry-cache@8.0.0: + dependencies: + flat-cache: 4.0.1 + + find-up@5.0.0: + dependencies: + locate-path: 6.0.0 + path-exists: 4.0.0 + + flat-cache@4.0.1: + dependencies: + flatted: 3.4.3 + keyv: 4.5.4 + + flatted@3.4.3: {} + fsevents@2.3.2: optional: true fsevents@2.3.3: optional: true + function-bind@1.1.2: {} + get-caller-file@2.0.5: {} + glob-parent@6.0.2: + dependencies: + is-glob: 4.0.3 + + global-directory@4.0.1: + dependencies: + ini: 4.1.1 + + globals@17.7.0: {} + + graceful-fs@4.2.11: {} + graphql@16.14.2: {} + has-flag@4.0.0: {} + + hasown@2.0.4: + dependencies: + function-bind: 1.1.2 + headers-polyfill@5.0.1: dependencies: '@types/set-cookie-parser': 2.4.10 @@ -1638,14 +2317,43 @@ snapshots: transitivePeerDependencies: - '@noble/hashes' + ignore@5.3.2: {} + + ignore@7.0.6: {} + + imurmurhash@0.1.4: {} + indent-string@4.0.0: {} + ini@4.1.1: {} + + interpret@3.1.1: {} + + is-core-module@2.16.2: + dependencies: + hasown: 2.0.4 + + is-extglob@2.1.1: {} + is-fullwidth-code-point@3.0.0: {} + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + + is-installed-globally@1.0.0: + dependencies: + global-directory: 4.0.1 + is-path-inside: 4.0.0 + is-node-process@1.2.0: {} + is-path-inside@4.0.0: {} + is-potential-custom-element-name@1.0.1: {} + isexe@2.0.0: {} + js-tokens@4.0.0: {} jsdom@29.1.1: @@ -1674,6 +2382,25 @@ snapshots: transitivePeerDependencies: - '@noble/hashes' + json-buffer@3.0.1: {} + + json-schema-traverse@0.4.1: {} + + json-stable-stringify-without-jsonify@1.0.1: {} + + json5@2.2.3: {} + + keyv@4.5.4: + dependencies: + json-buffer: 3.0.1 + + kleur@3.0.3: {} + + levn@0.4.1: + dependencies: + prelude-ls: 1.2.1 + type-check: 0.4.0 + lightningcss-android-arm64@1.33.0: optional: true @@ -1723,6 +2450,10 @@ snapshots: lightningcss-win32-arm64-msvc: 1.33.0 lightningcss-win32-x64-msvc: 1.33.0 + locate-path@6.0.0: + dependencies: + p-locate: 5.0.0 + lru-cache@11.5.2: {} lz-string@1.5.0: {} @@ -1735,6 +2466,14 @@ snapshots: min-indent@1.0.1: {} + minimatch@10.2.5: + dependencies: + brace-expansion: 5.0.8 + + minimist@1.2.8: {} + + ms@2.1.3: {} + msw@2.15.0(@types/node@24.13.3)(typescript@7.0.2): dependencies: '@inquirer/confirm': 6.1.1(@types/node@24.13.3) @@ -1764,14 +2503,39 @@ snapshots: nanoid@3.3.16: {} + natural-compare@1.4.0: {} + obug@2.1.4: {} + optionator@0.9.4: + dependencies: + deep-is: 0.1.4 + fast-levenshtein: 2.0.6 + levn: 0.4.1 + prelude-ls: 1.2.1 + type-check: 0.4.0 + word-wrap: 1.2.5 + outvariant@1.4.3: {} + p-limit@3.1.0: + dependencies: + yocto-queue: 0.1.0 + + p-locate@5.0.0: + dependencies: + p-limit: 3.1.0 + parse5@8.0.1: dependencies: entities: 8.0.0 + path-exists@4.0.0: {} + + path-key@3.1.1: {} + + path-parse@1.0.7: {} + path-to-regexp@6.3.0: {} pathe@2.0.3: {} @@ -1794,12 +2558,19 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 + prelude-ls@1.2.1: {} + pretty-format@27.5.1: dependencies: ansi-regex: 5.0.1 ansi-styles: 5.2.0 react-is: 17.0.2 + prompts@2.4.2: + dependencies: + kleur: 3.0.3 + sisteransi: 1.0.5 + punycode@2.3.1: {} react-dom@19.2.8(react@19.2.8): @@ -1811,15 +2582,28 @@ snapshots: react@19.2.8: {} + rechoir@0.8.0: + dependencies: + resolve: 1.22.12 + redent@3.0.0: dependencies: indent-string: 4.0.0 strip-indent: 3.0.0 + regexp-tree@0.1.27: {} + require-directory@2.1.1: {} require-from-string@2.0.2: {} + resolve@1.22.12: + dependencies: + es-errors: 1.3.0 + is-core-module: 2.16.2 + path-parse: 1.0.7 + supports-preserve-symlinks-flag: 1.0.0 + rettime@0.11.11: {} rolldown@1.1.5: @@ -1843,18 +2627,32 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.1.5 '@rolldown/binding-win32-x64-msvc': 1.1.5 + safe-regex@2.1.1: + dependencies: + regexp-tree: 0.1.27 + saxes@6.0.0: dependencies: xmlchars: 2.2.0 scheduler@0.27.0: {} + semver@7.8.5: {} + set-cookie-parser@3.1.2: {} + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + siginfo@2.0.0: {} signal-exit@4.1.0: {} + sisteransi@1.0.5: {} + source-map-js@1.2.1: {} stackback@0.0.2: {} @@ -1875,14 +2673,24 @@ snapshots: dependencies: ansi-regex: 5.0.1 + strip-bom@3.0.0: {} + strip-indent@3.0.0: dependencies: min-indent: 1.0.1 + supports-color@7.2.0: + dependencies: + has-flag: 4.0.0 + + supports-preserve-symlinks-flag@1.0.0: {} + symbol-tree@3.2.4: {} tagged-tag@1.0.0: {} + tapable@2.3.3: {} + tinybench@2.9.0: {} tinyexec@1.2.4: {} @@ -1908,9 +2716,26 @@ snapshots: dependencies: punycode: 2.3.1 + tsconfig-paths-webpack-plugin@4.2.0: + dependencies: + chalk: 4.1.2 + enhanced-resolve: 5.24.2 + tapable: 2.3.3 + tsconfig-paths: 4.2.0 + + tsconfig-paths@4.2.0: + dependencies: + json5: 2.2.3 + minimist: 1.2.8 + strip-bom: 3.0.0 + tslib@2.8.1: optional: true + type-check@0.4.0: + dependencies: + prelude-ls: 1.2.1 + type-fest@5.8.0: dependencies: tagged-tag: 1.0.0 @@ -1944,6 +2769,10 @@ snapshots: until-async@3.0.2: {} + uri-js@4.4.1: + dependencies: + punycode: 2.3.1 + vite@8.1.5(@types/node@24.13.3): dependencies: lightningcss: 1.33.0 @@ -1987,6 +2816,8 @@ snapshots: dependencies: xml-name-validator: 5.0.0 + watskeburt@6.0.0: {} + webidl-conversions@8.0.1: {} whatwg-mimetype@5.0.0: {} @@ -1999,11 +2830,17 @@ snapshots: transitivePeerDependencies: - '@noble/hashes' + which@2.0.2: + dependencies: + isexe: 2.0.0 + why-is-node-running@2.3.0: dependencies: siginfo: 2.0.0 stackback: 0.0.2 + word-wrap@1.2.5: {} + wrap-ansi@7.0.0: dependencies: ansi-styles: 4.3.0 @@ -2027,3 +2864,5 @@ snapshots: string-width: 4.2.3 y18n: 5.0.8 yargs-parser: 21.1.1 + + yocto-queue@0.1.0: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 20708402..4c5d8b7a 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -4,3 +4,4 @@ minimumReleaseAgeExclude: - '@playwright/test@1.62.0' - playwright-core@1.62.0 - playwright@1.62.0 + - eslint@10.8.0 diff --git a/scripts/check-architecture.mjs b/scripts/check-architecture.mjs new file mode 100644 index 00000000..fda21c6f --- /dev/null +++ b/scripts/check-architecture.mjs @@ -0,0 +1,69 @@ +import { mkdir, writeFile } from "node:fs/promises"; +import { spawnSync } from "node:child_process"; + +await mkdir("artifacts/quality", { recursive: true }); + +const pnpmCli = /** @type {string} */ (process.env.npm_execpath); + +if (!pnpmCli) { + throw new Error("check:architecture must run through the pnpm script"); +} + +/** @param {string[]} arguments_ */ +function runPnpm(arguments_) { + return spawnSync(process.execPath, [pnpmCli, ...arguments_], { + encoding: "utf8", + }); +} + +const production = runPnpm( + [ + "exec", + "depcruise", + "src", + "--config", + ".dependency-cruiser.cjs", + "--output-type", + "json", + ], +); + +await writeFile( + "artifacts/quality/dependency-report.json", + production.stdout || JSON.stringify({ summary: { errors: 1 } }), +); + +if (production.status !== 0) { + process.stderr.write( + production.error?.message ?? production.stderr ?? production.stdout ?? "failed", + ); + process.exit(production.status ?? 1); +} + +const allowed = runPnpm( + [ + "exec", + "eslint", + "tests/fixtures/architecture/allowed", + "--no-ignore", + "--max-warnings=0", + ], +); + +const forbidden = runPnpm( + [ + "exec", + "eslint", + "tests/fixtures/architecture/forbidden", + "--no-ignore", + "--max-warnings=0", + ], +); + +if (allowed.status !== 0 || forbidden.status === 0) { + process.stderr.write(allowed.stderr || allowed.stdout); + process.stderr.write(forbidden.stderr || forbidden.stdout); + process.exit(1); +} + +process.stdout.write("Architecture fixtures: allowed PASS, forbidden rejected\n"); diff --git a/tests/fixtures/architecture/allowed/presentation-facade.js b/tests/fixtures/architecture/allowed/presentation-facade.js new file mode 100644 index 00000000..1c9edce8 --- /dev/null +++ b/tests/fixtures/architecture/allowed/presentation-facade.js @@ -0,0 +1,3 @@ +import { createApplication } from "../../../../src/application/create-application.js"; + +export const applicationFactory = createApplication; diff --git a/tests/fixtures/architecture/forbidden/application-imports-tanstack.js b/tests/fixtures/architecture/forbidden/application-imports-tanstack.js new file mode 100644 index 00000000..38c8d423 --- /dev/null +++ b/tests/fixtures/architecture/forbidden/application-imports-tanstack.js @@ -0,0 +1,3 @@ +import { QueryClient } from "@tanstack/react-query"; + +export const invalidClient = new QueryClient(); diff --git a/tests/fixtures/architecture/forbidden/domain-imports-react.js b/tests/fixtures/architecture/forbidden/domain-imports-react.js new file mode 100644 index 00000000..c96f130e --- /dev/null +++ b/tests/fixtures/architecture/forbidden/domain-imports-react.js @@ -0,0 +1,3 @@ +import React from "react"; + +export const invalidDomainValue = React.createElement("div"); diff --git a/tests/fixtures/architecture/forbidden/presentation-imports-adapter.js b/tests/fixtures/architecture/forbidden/presentation-imports-adapter.js new file mode 100644 index 00000000..55d9090a --- /dev/null +++ b/tests/fixtures/architecture/forbidden/presentation-imports-adapter.js @@ -0,0 +1,3 @@ +import "../../../../src/adapters/http/client.js"; + +export const invalidEdge = true; From 6b51104010eb3b3b98d2c95a4fc1e34e8ea51de1 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 20:46:06 +0900 Subject: [PATCH 006/178] feat: validate runtime configuration before mount --- package.json | 3 +- pnpm-lock.yaml | 8 ++ public/config.json | 13 +++ src/bootstrap/load-runtime-config.js | 104 ++++++++++++++++++++ src/bootstrap/main.jsx | 43 ++++++-- src/bootstrap/runtime-config-schema.js | 66 +++++++++++++ src/contracts/env.js | 54 ++++++++++ tests/runtime-schema/runtime-config.test.js | 73 ++++++++++++++ 8 files changed, 356 insertions(+), 8 deletions(-) create mode 100644 public/config.json create mode 100644 src/bootstrap/load-runtime-config.js create mode 100644 src/bootstrap/runtime-config-schema.js create mode 100644 src/contracts/env.js create mode 100644 tests/runtime-schema/runtime-config.test.js diff --git a/package.json b/package.json index e9cb437e..66ee01d8 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,8 @@ }, "dependencies": { "react": "19.2.8", - "react-dom": "19.2.8" + "react-dom": "19.2.8", + "zod": "4.4.3" }, "devDependencies": { "@axe-core/playwright": "4.12.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2304627d..c89142c1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: react-dom: specifier: 19.2.8 version: 19.2.8(react@19.2.8) + zod: + specifier: 4.4.3 + version: 4.4.3 devDependencies: '@axe-core/playwright': specifier: 4.12.1 @@ -1584,6 +1587,9 @@ packages: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} + zod@4.4.3: + resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==} + snapshots: '@adobe/css-tools@4.5.0': {} @@ -2866,3 +2872,5 @@ snapshots: yargs-parser: 21.1.1 yocto-queue@0.1.0: {} + + zod@4.4.3: {} diff --git a/public/config.json b/public/config.json new file mode 100644 index 00000000..9cd3dbe1 --- /dev/null +++ b/public/config.json @@ -0,0 +1,13 @@ +{ + "APP_ENV": "local", + "API_BASE_URL": "http://localhost:8080", + "REQUEST_TIMEOUT_MS": 10000, + "MAX_RETRY_ATTEMPTS": 2, + "TELEMETRY_ENABLED": false, + "AUTH_MODE": "external", + "CONFIG_SCHEMA_VERSION": "1", + "API_CONTRACT_VERSION": "1", + "RELEASE_MANIFEST_URL": "/release-manifest.json", + "BUILD_ID": "local-build", + "RELEASE_ID": "local-release" +} diff --git a/src/bootstrap/load-runtime-config.js b/src/bootstrap/load-runtime-config.js new file mode 100644 index 00000000..286b2b00 --- /dev/null +++ b/src/bootstrap/load-runtime-config.js @@ -0,0 +1,104 @@ +import { assertSafeConfigNames, getBuildConfig } from "../contracts/env.js"; +import { validateRuntimeConfig } from "./runtime-config-schema.js"; + +export class BootConfigError extends Error { + /** + * @param {string} code + * @param {{ buildId: string, configSchemaVersion?: string, releaseId?: string }} safe + */ + constructor(code, safe) { + super("Runtime configuration could not be loaded"); + this.name = "BootConfigError"; + this.kind = "BOOT_CONFIG_FAILURE"; + this.code = code; + this.safe = Object.freeze({ + kind: this.kind, + code, + buildId: safe.buildId, + configSchemaVersion: safe.configSchemaVersion, + releaseId: safe.releaseId, + supportReference: `${safe.buildId}:${code}`, + }); + } +} + +/** + * @param {{ + * fetcher?: typeof fetch, + * buildConfig?: ReturnType, + * now?: () => number + * }} [options] + */ +export async function loadRuntimeConfig(options = {}) { + const fetcher = options.fetcher ?? fetch; + const buildConfig = options.buildConfig ?? getBuildConfig(); + const now = options.now ?? performance.now.bind(performance); + const startedAt = now(); + + let response; + try { + response = await fetcher(buildConfig.runtimeConfigUrl, { + cache: "no-store", + headers: { Accept: "application/json" }, + }); + } catch { + throw new BootConfigError("CONFIG_FETCH_FAILED", { + buildId: buildConfig.buildId, + }); + } + + if (!response.ok) { + throw new BootConfigError("CONFIG_HTTP_FAILED", { + buildId: buildConfig.buildId, + }); + } + + let rawConfig; + try { + rawConfig = await response.json(); + } catch { + throw new BootConfigError("CONFIG_JSON_INVALID", { + buildId: buildConfig.buildId, + }); + } + + if (!rawConfig || typeof rawConfig !== "object" || Array.isArray(rawConfig)) { + throw new BootConfigError("CONFIG_SHAPE_INVALID", { + buildId: buildConfig.buildId, + }); + } + + try { + assertSafeConfigNames(rawConfig); + } catch { + throw new BootConfigError("CONFIG_SECRET_NAME_REJECTED", { + buildId: buildConfig.buildId, + }); + } + + const validated = validateRuntimeConfig(rawConfig); + if (!validated.success) { + throw new BootConfigError("CONFIG_SCHEMA_INVALID", { + buildId: buildConfig.buildId, + configSchemaVersion: + typeof rawConfig.CONFIG_SCHEMA_VERSION === "string" + ? rawConfig.CONFIG_SCHEMA_VERSION + : undefined, + releaseId: typeof rawConfig.RELEASE_ID === "string" ? rawConfig.RELEASE_ID : undefined, + }); + } + + if (validated.data.BUILD_ID && validated.data.BUILD_ID !== buildConfig.buildId) { + throw new BootConfigError("CONFIG_BUILD_MISMATCH", { + buildId: buildConfig.buildId, + configSchemaVersion: validated.data.CONFIG_SCHEMA_VERSION, + releaseId: validated.data.RELEASE_ID, + }); + } + + return Object.freeze({ + config: validated.data, + build: buildConfig, + validationDurationMs: now() - startedAt, + }); +} diff --git a/src/bootstrap/main.jsx b/src/bootstrap/main.jsx index 96528344..5d40e930 100644 --- a/src/bootstrap/main.jsx +++ b/src/bootstrap/main.jsx @@ -1,11 +1,24 @@ import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; -function BootstrapShell() { +import { BootConfigError, loadRuntimeConfig } from "./load-runtime-config.js"; + +/** @param {{ environment: string }} props */ +function BootstrapShell({ environment }) { return (

Clean Architecture Frontend

-

런타임 계약을 불러오는 중입니다.

+

{environment} 런타임 계약이 검증되었습니다.

+
+ ); +} + +/** @param {{ supportReference: string }} props */ +function BootErrorShell({ supportReference }) { + return ( +
+

애플리케이션을 시작할 수 없습니다.

+

지원 참조: {supportReference}

); } @@ -16,8 +29,24 @@ if (!rootElement) { throw new Error("Missing #root mount element"); } -createRoot(rootElement).render( - - - , -); +const root = createRoot(rootElement); + +async function boot() { + try { + const runtime = await loadRuntimeConfig(); + root.render( + + + , + ); + } catch (error) { + const supportReference = + error instanceof BootConfigError + ? error.safe.supportReference + : "boot:unknown"; + + root.render(); + } +} + +void boot(); diff --git a/src/bootstrap/runtime-config-schema.js b/src/bootstrap/runtime-config-schema.js new file mode 100644 index 00000000..9de4cb7e --- /dev/null +++ b/src/bootstrap/runtime-config-schema.js @@ -0,0 +1,66 @@ +import { z } from "zod"; + +const version = z.string().regex(/^\d+(?:\.\d+){0,2}$/); + +export const runtimeConfigSchema = z + .object({ + APP_ENV: z.enum(["local", "development", "staging", "production"]), + API_BASE_URL: z.url(), + REQUEST_TIMEOUT_MS: z.int().min(100).max(60_000).default(10_000), + MAX_RETRY_ATTEMPTS: z.int().min(0).max(2).default(2), + TELEMETRY_ENABLED: z.boolean(), + TELEMETRY_ENDPOINT: z.url().optional(), + AUTH_MODE: z.literal("external"), + CONFIG_SCHEMA_VERSION: version, + API_CONTRACT_VERSION: version, + RELEASE_MANIFEST_URL: z.string().min(1).default("/release-manifest.json"), + RELEASE_ID: z.string().min(1).optional(), + BUILD_ID: z.string().min(1).optional(), + }) + .strict() + .superRefine((config, context) => { + if (config.TELEMETRY_ENABLED && !config.TELEMETRY_ENDPOINT) { + context.addIssue({ + code: "custom", + path: ["TELEMETRY_ENDPOINT"], + message: "required when telemetry is enabled", + }); + } + + const local = config.APP_ENV === "local" || config.APP_ENV === "development"; + const endpointEntries = + /** @type {Array<[string, string | undefined]>} */ ([ + ["API_BASE_URL", config.API_BASE_URL], + ["TELEMETRY_ENDPOINT", config.TELEMETRY_ENDPOINT], + ]); + + for (const [key, value] of endpointEntries) { + if (value && !local && new URL(value).protocol !== "https:") { + context.addIssue({ + code: "custom", + path: [key], + message: "HTTPS is required outside local environments", + }); + } + } + }); + +/** @param {unknown} value */ +export function validateRuntimeConfig(value) { + const result = runtimeConfigSchema.safeParse(value); + + if (!result.success) { + return { + success: /** @type {false} */ (false), + issues: result.error.issues.map((issue) => ({ + path: issue.path.join("."), + code: issue.code, + })), + }; + } + + return { + success: /** @type {true} */ (true), + data: structuredClone(result.data), + }; +} diff --git a/src/contracts/env.js b/src/contracts/env.js new file mode 100644 index 00000000..8b943025 --- /dev/null +++ b/src/contracts/env.js @@ -0,0 +1,54 @@ +const forbiddenConfigName = /(SECRET|PASSWORD|PRIVATE_KEY|TOKEN)/i; + +export const ENV_REGISTRY = Object.freeze({ + VITE_BUILD_ID: build("public-metadata", true, null), + VITE_COMMIT_SHA: build("public-metadata", false, "local"), + VITE_ROUTER_BASE_PATH: build("compile-time", true, "/"), + VITE_RUNTIME_CONFIG_URL: build("compile-time", true, "/config.json"), + APP_ENV: runtime("public", true, null), + API_BASE_URL: runtime("public-sensitive", true, null), + REQUEST_TIMEOUT_MS: runtime("public", false, 10_000), + MAX_RETRY_ATTEMPTS: runtime("public", false, 2), + TELEMETRY_ENABLED: runtime("public", true, false), + TELEMETRY_ENDPOINT: runtime("public-sensitive", false, null), + AUTH_MODE: runtime("public", true, "external"), + CONFIG_SCHEMA_VERSION: runtime("public", true, null), + API_CONTRACT_VERSION: runtime("public", true, null), + RELEASE_MANIFEST_URL: runtime("public", true, "/release-manifest.json"), +}); + +/** + * @param {string} classification + * @param {boolean} required + * @param {unknown} defaultValue + */ +function build(classification, required, defaultValue) { + return Object.freeze({ phase: "build", classification, required, defaultValue }); +} + +/** + * @param {string} classification + * @param {boolean} required + * @param {unknown} defaultValue + */ +function runtime(classification, required, defaultValue) { + return Object.freeze({ phase: "runtime", classification, required, defaultValue }); +} + +/** @param {Record} config */ +export function assertSafeConfigNames(config) { + for (const name of Object.keys(config)) { + if (forbiddenConfigName.test(name)) { + throw new Error(`Forbidden client configuration key: ${name}`); + } + } +} + +export function getBuildConfig(environment = import.meta.env) { + const buildId = environment.VITE_BUILD_ID || "local-build"; + const commitSha = environment.VITE_COMMIT_SHA || "local"; + const routerBasePath = environment.VITE_ROUTER_BASE_PATH || "/"; + const runtimeConfigUrl = environment.VITE_RUNTIME_CONFIG_URL || "/config.json"; + + return Object.freeze({ buildId, commitSha, routerBasePath, runtimeConfigUrl }); +} diff --git a/tests/runtime-schema/runtime-config.test.js b/tests/runtime-schema/runtime-config.test.js new file mode 100644 index 00000000..114694ee --- /dev/null +++ b/tests/runtime-schema/runtime-config.test.js @@ -0,0 +1,73 @@ +import { describe, expect, it } from "vitest"; + +import { loadRuntimeConfig } from "../../src/bootstrap/load-runtime-config.js"; +import { validateRuntimeConfig } from "../../src/bootstrap/runtime-config-schema.js"; +import { assertSafeConfigNames } from "../../src/contracts/env.js"; + +const validConfig = { + APP_ENV: "local", + API_BASE_URL: "http://localhost:8080", + REQUEST_TIMEOUT_MS: 10_000, + MAX_RETRY_ATTEMPTS: 2, + TELEMETRY_ENABLED: false, + AUTH_MODE: "external", + CONFIG_SCHEMA_VERSION: "1", + API_CONTRACT_VERSION: "1", + RELEASE_MANIFEST_URL: "/release-manifest.json", + BUILD_ID: "build-a", +}; + +describe("runtime configuration boundary", () => { + it.each([ + [{ ...validConfig, API_BASE_URL: undefined }, "required key"], + [{ ...validConfig, REQUEST_TIMEOUT_MS: 0 }, "integer range"], + [{ ...validConfig, MAX_RETRY_ATTEMPTS: 3 }, "retry cap"], + [{ ...validConfig, TELEMETRY_ENABLED: "false" }, "ambiguous boolean"], + [{ ...validConfig, CONFIG_SCHEMA_VERSION: "next" }, "version"], + [{ ...validConfig, UNKNOWN_KEY: true }, "unknown key"], + ])("rejects invalid config: %s (%s)", (candidate) => { + expect(validateRuntimeConfig(candidate).success).toBe(false); + }); + + it("rejects secret-like names before schema validation", () => { + expect(() => assertSafeConfigNames({ CLIENT_SECRET: "not-safe" })).toThrow( + "Forbidden client configuration key", + ); + }); + + it("validates a fetched config under the 500ms budget excluding network", async () => { + let current = 100; + const result = await loadRuntimeConfig({ + buildConfig: { + buildId: "build-a", + commitSha: "local", + routerBasePath: "/", + runtimeConfigUrl: "/config.json", + }, + fetcher: async () => new Response(JSON.stringify(validConfig)), + now: () => (current += 2), + }); + + expect(result.validationDurationMs).toBeLessThanOrEqual(500); + expect(result.config.API_BASE_URL).toBe("http://localhost:8080"); + }); + + it("returns only safe boot fields on failure", async () => { + await expect( + loadRuntimeConfig({ + buildConfig: { + buildId: "build-a", + commitSha: "local", + routerBasePath: "/", + runtimeConfigUrl: "/config.json", + }, + fetcher: async () => new Response("{"), + }), + ).rejects.toMatchObject({ + safe: { + kind: "BOOT_CONFIG_FAILURE", + buildId: "build-a", + }, + }); + }); +}); From 5c36cd978c10928395ee28c48c40e3add7f7d352 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 20:49:50 +0900 Subject: [PATCH 007/178] feat: add shared HTTP response and retry contract --- src/adapters/http/client.js | 438 ++++++++++++++++++++++++++ src/adapters/http/retry-policy.js | 79 +++++ src/contracts/api-operations.js | 51 +++ tests/integration/http-client.test.js | 71 +++++ tests/unit/retry-policy.test.js | 47 +++ 5 files changed, 686 insertions(+) create mode 100644 src/adapters/http/client.js create mode 100644 src/adapters/http/retry-policy.js create mode 100644 src/contracts/api-operations.js create mode 100644 tests/integration/http-client.test.js create mode 100644 tests/unit/retry-policy.test.js diff --git a/src/adapters/http/client.js b/src/adapters/http/client.js new file mode 100644 index 00000000..a7a0e635 --- /dev/null +++ b/src/adapters/http/client.js @@ -0,0 +1,438 @@ +import { systemClock } from "../../application/ports/clock-port.js"; +import { getApiOperation } from "../../contracts/api-operations.js"; +import { retryDelay, shouldRetry } from "./retry-policy.js"; + +const noAuthSession = + /** @type {import("../../application/ports/auth-session-port.js").AuthSessionPort} */ ({ + getState: () => /** @type {"unauthenticated"} */ ("unauthenticated"), + attach: async (request) => request, + recover: async () => /** @type {"no-session"} */ ("no-session"), + onUnauthenticated: () => {}, +}); + +/** + * @typedef {{ + * kind: string, + * code: string, + * retryable: boolean, + * operationId: string, + * attemptCount: number, + * httpStatus?: number, + * requestId?: string, + * traceId?: string, + * retryAfterMs?: number, + * userMessageKey: string, + * action: string + * }} HttpFailure + */ + +/** + * @typedef {{ ok: true, value: unknown, meta: Record } | + * { ok: false, error: HttpFailure }} HttpResult + */ + +/** + * @typedef {{ + * code?: string, + * httpStatus?: number, + * requestId?: string, + * traceId?: string, + * retryAfterMs?: number + * }} FailureDetails + */ + +/** + * @param {{ + * baseUrl: string, + * fetcher?: typeof fetch, + * authSession?: import("../../application/ports/auth-session-port.js").AuthSessionPort, + * clock?: import("../../application/ports/clock-port.js").ClockPort, + * random?: () => number, + * validatePayload?: (schemaId: string, value: unknown) => + * { success: true, data: unknown } | { success: false }, + * idempotencyKeyFactory?: () => string + * }} dependencies + */ +export function createHttpClient(dependencies) { + const fetcher = dependencies.fetcher ?? fetch; + const authSession = dependencies.authSession ?? noAuthSession; + const clock = dependencies.clock ?? systemClock; + const random = dependencies.random ?? Math.random; + const validatePayload = + dependencies.validatePayload ?? + ((_schemaId, value) => ({ success: /** @type {true} */ (true), data: value })); + const idempotencyKeyFactory = + dependencies.idempotencyKeyFactory ?? (() => crypto.randomUUID()); + + /** + * @param {string} operationId + * @param {{ + * body?: unknown, + * routeId?: string, + * signal?: AbortSignal, + * idempotencyKey?: string + * }} [input] + */ + async function execute(operationId, input = {}) { + const operation = getApiOperation(operationId); + const logicalIdempotencyKey = + operation.idempotency === "keyed" + ? input.idempotencyKey ?? idempotencyKeyFactory() + : undefined; + let retryCount = 0; + let recoveryUsed = false; + + while (true) { + const attempt = retryCount; + /** @type {HttpResult} */ + const outcome = await performAttempt({ + operation, + input, + attempt, + idempotencyKey: logicalIdempotencyKey, + }); + + if (outcome.ok) return outcome; + + if (outcome.error.httpStatus === 401 && !recoveryUsed) { + recoveryUsed = true; + const recovered = await recoverSession(authSession, operation, outcome.error); + if (!recovered.ok) return recovered; + if (operation.idempotency === "none") { + return { + ok: false, + error: { + ...outcome.error, + retryable: false, + action: "retry", + }, + }; + } + continue; + } + + if (!shouldRetry(operation, outcome.error, retryCount)) { + return outcome; + } + + const delay = retryDelay(outcome.error, retryCount, random, clock.now()); + retryCount += 1; + + try { + await clock.sleep(delay, input.signal); + } catch { + return { + ok: false, + error: failure("REQUEST_ABORTED", operationId, retryCount, { + code: "REQUEST_ABORTED", + }), + }; + } + } + } + + /** + * @param {{ + * operation: ReturnType, + * input: { body?: unknown, routeId?: string, signal?: AbortSignal }, + * attempt: number, + * idempotencyKey?: string + * }} context + * @returns {Promise} + */ + async function performAttempt(context) { + const { operation, input, attempt, idempotencyKey } = context; + const controller = new AbortController(); + let timedOut = false; + const timeout = setTimeout(() => { + timedOut = true; + controller.abort("timeout"); + }, operation.timeoutMs); + const onExternalAbort = () => controller.abort(input.signal?.reason); + input.signal?.addEventListener("abort", onExternalAbort, { once: true }); + + const headers = new Headers({ Accept: "application/json" }); + if (input.body !== undefined) headers.set("Content-Type", "application/json"); + if (idempotencyKey) headers.set("Idempotency-Key", idempotencyKey); + + let request = new Request(new URL(operation.path, dependencies.baseUrl), { + method: operation.method, + headers, + body: input.body === undefined ? undefined : JSON.stringify(input.body), + signal: controller.signal, + }); + + try { + if (operation.auth === "external-session") { + try { + request = await authSession.attach(request); + } catch { + return { + ok: false, + error: failure("AUTH_INTEGRATION_FAILURE", operation.operationId, attempt, { + code: "AUTH_ATTACH_FAILED", + }), + }; + } + } + + const response = await fetcher(request); + return await parseResponse(response, operation, attempt, validatePayload); + } catch { + if (timedOut) { + return { + ok: false, + error: failure("REQUEST_TIMEOUT", operation.operationId, attempt, { + code: "REQUEST_TIMEOUT", + }), + }; + } + if (controller.signal.aborted || input.signal?.aborted) { + const externalReason = input.signal?.reason; + if (externalReason === "timeout") { + return { + ok: false, + error: failure("REQUEST_TIMEOUT", operation.operationId, attempt, { + code: "REQUEST_TIMEOUT", + }), + }; + } + if ( + externalReason !== undefined && + !["navigation", "user", "superseded"].includes(String(externalReason)) + ) { + return { + ok: false, + error: failure("UNKNOWN_FAILURE", operation.operationId, attempt, { + code: "EXTERNAL_ABORT_UNRESOLVED", + }), + }; + } + return { + ok: false, + error: failure("REQUEST_ABORTED", operation.operationId, attempt, { + code: "REQUEST_ABORTED", + }), + }; + } + return { + ok: false, + error: failure("NETWORK_UNREACHABLE", operation.operationId, attempt, { + code: "NETWORK_UNREACHABLE", + }), + }; + } finally { + clearTimeout(timeout); + input.signal?.removeEventListener("abort", onExternalAbort); + } + } + + return Object.freeze({ execute }); +} + +/** + * @param {Response} response + * @param {import("../../contracts/api-operations.js").ApiOperation} operation + * @param {number} attempt + * @param {(schemaId: string, value: unknown) => + * { success: true, data: unknown } | { success: false }} validatePayload + * @returns {Promise} + */ +async function parseResponse(response, operation, attempt, validatePayload) { + const contentType = response.headers.get("content-type") ?? ""; + if (!contentType.toLowerCase().includes("application/json")) { + return { + ok: false, + error: failure("CONTENT_TYPE_MISMATCH", operation.operationId, attempt, { + code: "CONTENT_TYPE_MISMATCH", + httpStatus: response.status, + }), + }; + } + + let envelope; + try { + envelope = await response.json(); + } catch { + return { + ok: false, + error: failure("MALFORMED_JSON", operation.operationId, attempt, { + code: "MALFORMED_JSON", + httpStatus: response.status, + }), + }; + } + + if (!envelope || typeof envelope !== "object") { + return { + ok: false, + error: failure("ENVELOPE_MISMATCH", operation.operationId, attempt, { + code: "ENVELOPE_MISMATCH", + httpStatus: response.status, + }), + }; + } + + const envelopeRecord = /** @type {Record} */ (envelope); + if (typeof envelopeRecord.success !== "boolean") { + return { + ok: false, + error: failure("ENVELOPE_MISMATCH", operation.operationId, attempt, { + code: "ENVELOPE_MISMATCH", + httpStatus: response.status, + }), + }; + } + + if (response.ok && envelopeRecord.success === true && "data" in envelopeRecord) { + const payload = validatePayload(operation.responseSchema, envelopeRecord.data); + if (!payload.success) { + return { + ok: false, + error: failure("SCHEMA_MISMATCH", operation.operationId, attempt, { + code: "SCHEMA_MISMATCH", + httpStatus: response.status, + }), + }; + } + + return { + ok: true, + value: structuredClone(payload.data), + meta: safeMeta(envelopeRecord.meta), + }; + } + + const kind = statusKind(response.status); + const retryAfter = response.headers.get("retry-after"); + return { + ok: false, + error: failure(kind, operation.operationId, attempt, { + code: safeBackendCode(envelope), + httpStatus: response.status, + requestId: safeMeta(envelopeRecord.meta).requestId, + traceId: safeMeta(envelopeRecord.meta).traceId, + retryAfterMs: + response.status === 429 && retryAfter + ? parseRetryAfterHeader(retryAfter) + : undefined, + }), + }; +} + +/** + * @param {import("../../application/ports/auth-session-port.js").AuthSessionPort} authSession + * @param {import("../../contracts/api-operations.js").ApiOperation} operation + * @param {HttpFailure} originalFailure + * @returns {Promise<{ok: true} | {ok: false, error: HttpFailure}>} + */ +async function recoverSession(authSession, operation, originalFailure) { + try { + const result = await authSession.recover(); + if (result === "restored") return { ok: true }; + if (result === "no-session") { + authSession.onUnauthenticated(); + return { + ok: false, + error: failure("AUTH_REQUIRED", operation.operationId, originalFailure.attemptCount, { + code: "AUTH_REQUIRED", + httpStatus: 401, + }), + }; + } + } catch { + // Normalized below. + } + + return { + ok: false, + error: failure( + "AUTH_INTEGRATION_FAILURE", + operation.operationId, + originalFailure.attemptCount, + { code: "AUTH_RECOVERY_FAILED" }, + ), + }; +} + +/** + * @param {string} kind + * @param {string} operationId + * @param {number} attempt + * @param {FailureDetails} [details] + * @returns {HttpFailure} + */ +function failure(kind, operationId, attempt, details = {}) { + const retryable = new Set([ + "NETWORK_UNREACHABLE", + "REQUEST_TIMEOUT", + "RATE_LIMITED", + "SERVER_FAILURE", + ]).has(kind); + const action = + kind === "AUTH_REQUIRED" + ? "reauth" + : retryable + ? "retry" + : kind === "REQUEST_ABORTED" + ? "none" + : "contact-support"; + + return Object.freeze({ + kind, + code: details.code ?? kind, + retryable, + operationId, + attemptCount: attempt + 1, + ...(details.httpStatus === undefined ? {} : { httpStatus: details.httpStatus }), + ...(details.requestId ? { requestId: details.requestId } : {}), + ...(details.traceId ? { traceId: details.traceId } : {}), + ...(details.retryAfterMs === undefined + ? {} + : { retryAfterMs: details.retryAfterMs }), + userMessageKey: `error.${kind.toLowerCase()}`, + action, + }); +} + +/** @param {number} status */ +function statusKind(status) { + if (status === 401) return "AUTH_REQUIRED"; + if (status === 403) return "FORBIDDEN"; + if (status === 404) return "NOT_FOUND"; + if (status === 409) return "CONFLICT"; + if (status === 422) return "VALIDATION_REJECTED"; + if (status === 429) return "RATE_LIMITED"; + if (status >= 500) return "SERVER_FAILURE"; + if (status >= 400) return "UNKNOWN_CLIENT_FAILURE"; + return "ENVELOPE_MISMATCH"; +} + +/** @param {unknown} envelope */ +function safeBackendCode(envelope) { + if (!envelope || typeof envelope !== "object") return "HTTP_FAILURE"; + const error = /** @type {Record} */ (envelope).error; + if (!error || typeof error !== "object") return "HTTP_FAILURE"; + const code = /** @type {Record} */ (error).code; + return typeof code === "string" ? code : "HTTP_FAILURE"; +} + +/** @param {unknown} meta @returns {Record} */ +function safeMeta(meta) { + if (!meta || typeof meta !== "object") return {}; + const metaRecord = /** @type {Record} */ (meta); + return { + ...(typeof metaRecord.requestId === "string" + ? { requestId: metaRecord.requestId } + : {}), + ...(typeof metaRecord.traceId === "string" ? { traceId: metaRecord.traceId } : {}), + }; +} + +/** @param {string} value */ +function parseRetryAfterHeader(value) { + const seconds = Number(value); + if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1_000; + const timestamp = Date.parse(value); + return Number.isFinite(timestamp) ? Math.max(0, timestamp - Date.now()) : undefined; +} diff --git a/src/adapters/http/retry-policy.js b/src/adapters/http/retry-policy.js new file mode 100644 index 00000000..ecf787ed --- /dev/null +++ b/src/adapters/http/retry-policy.js @@ -0,0 +1,79 @@ +const retryKinds = new Set([ + "NETWORK_UNREACHABLE", + "REQUEST_TIMEOUT", + "RATE_LIMITED", + "SERVER_FAILURE", +]); + +/** + * @param {number} retryIndex + * @param {() => number} [random] + * @param {number} [baseDelayMs] + * @param {number} [maxDelayMs] + */ +export function calculateBackoff( + retryIndex, + random = Math.random, + baseDelayMs = 250, + maxDelayMs = 2_000, +) { + return Math.min(maxDelayMs, baseDelayMs * 2 ** retryIndex) * random(); +} + +/** @param {string | null | undefined} value @param {number} [now] */ +export function parseRetryAfter(value, now = Date.now()) { + if (!value) return null; + + const seconds = Number(value); + if (Number.isFinite(seconds)) { + return seconds < 0 ? null : seconds * 1_000; + } + + const timestamp = Date.parse(value); + if (!Number.isFinite(timestamp)) return null; + return Math.max(0, timestamp - now); +} + +/** + * @param {{ idempotency: "safe" | "keyed" | "none" }} operation + * @param {{ kind: string, retryAfterMs?: number, httpStatus?: number }} failure + * @param {number} retryCount + * @param {number} [maxRetries] + */ +export function shouldRetry(operation, failure, retryCount, maxRetries = 2) { + if (retryCount >= maxRetries) return false; + if (!retryKinds.has(failure.kind)) return false; + if ( + failure.kind === "SERVER_FAILURE" && + failure.httpStatus !== undefined && + ![502, 503, 504].includes(failure.httpStatus) + ) { + return false; + } + if ( + failure.kind === "RATE_LIMITED" && + typeof failure.retryAfterMs === "number" && + failure.retryAfterMs > 30_000 + ) { + return false; + } + return operation.idempotency === "safe" || operation.idempotency === "keyed"; +} + +/** + * @param {{ kind: string, retryAfterMs?: number, retryAfter?: string }} failure + * @param {number} retryIndex + * @param {() => number} [random] + * @param {number} [now] + */ +export function retryDelay(failure, retryIndex, random = Math.random, now = Date.now()) { + const localBackoff = calculateBackoff(retryIndex, random); + if (failure.kind !== "RATE_LIMITED") return localBackoff; + + const retryAfterMs = + typeof failure.retryAfterMs === "number" + ? failure.retryAfterMs + : parseRetryAfter(failure.retryAfter, now); + + return retryAfterMs === null ? localBackoff : Math.max(localBackoff, retryAfterMs); +} diff --git a/src/contracts/api-operations.js b/src/contracts/api-operations.js new file mode 100644 index 00000000..08c65585 --- /dev/null +++ b/src/contracts/api-operations.js @@ -0,0 +1,51 @@ +/** + * @typedef {{ + * method: string, + * path: string, + * operationId: string, + * auth: "none" | "external-session", + * timeoutMs: number, + * idempotency: "safe" | "keyed" | "none", + * requestSchema: string, + * responseSchema: string, + * owner: string + * }} ApiOperation + */ + +/** @param {ApiOperation} definition */ +const operation = (definition) => Object.freeze(definition); + +export const API_OPERATIONS = Object.freeze({ + LIST_SAMPLE_RESOURCES: operation({ + method: "GET", + path: "/api/sample/resources", + operationId: "LIST_SAMPLE_RESOURCES", + auth: "external-session", + timeoutMs: 10_000, + idempotency: "safe", + requestSchema: "SampleResourceListQuery", + responseSchema: "SampleResourceListPayload", + owner: "feature-sample-feature-slice-contract-fixture", + }), + CREATE_SAMPLE_RESOURCE: operation({ + method: "POST", + path: "/api/sample/resources", + operationId: "CREATE_SAMPLE_RESOURCE", + auth: "external-session", + timeoutMs: 10_000, + idempotency: "keyed", + requestSchema: "CreateSampleResourceCommand", + responseSchema: "SampleResourcePayload", + owner: "feature-sample-feature-slice-contract-fixture", + }), +}); + +/** @param {string} operationId */ +export function getApiOperation(operationId) { + const registry = /** @type {Record} */ (API_OPERATIONS); + const selected = registry[operationId]; + if (!selected) { + throw new Error(`Unregistered API operation: ${operationId}`); + } + return selected; +} diff --git a/tests/integration/http-client.test.js b/tests/integration/http-client.test.js new file mode 100644 index 00000000..28c1dd0e --- /dev/null +++ b/tests/integration/http-client.test.js @@ -0,0 +1,71 @@ +import { HttpResponse, http } from "msw"; +import { setupServer } from "msw/node"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; + +import { createHttpClient } from "../../src/adapters/http/client.js"; + +let attempts = 0; +const server = setupServer( + http.get("https://api.test/api/sample/resources", () => { + attempts += 1; + if (attempts < 3) { + return HttpResponse.json( + { success: false, error: { code: "TEMPORARY" } }, + { status: 503 }, + ); + } + return HttpResponse.json({ + success: true, + data: [{ id: "resource-1", name: "Example" }], + meta: { requestId: "request-1", traceId: "trace-1" }, + }); + }), +); + +beforeAll(() => server.listen({ onUnhandledRequest: "error" })); +afterEach(() => { + attempts = 0; + server.resetHandlers(); +}); +afterAll(() => server.close()); + +const clock = { + now: () => 0, + sleep: async () => {}, +}; + +describe("shared HTTP client", () => { + it("retries a safe request at most twice and returns validated data", async () => { + const client = createHttpClient({ + baseUrl: "https://api.test", + clock, + random: () => 0, + }); + + await expect( + client.execute("LIST_SAMPLE_RESOURCES", { routeId: "SAMPLE_RESOURCE_LIST" }), + ).resolves.toMatchObject({ + ok: true, + value: [{ id: "resource-1" }], + meta: { requestId: "request-1" }, + }); + expect(attempts).toBe(3); + }); + + it("rejects a non-JSON response without exposing its body", async () => { + server.use( + http.get( + "https://api.test/api/sample/resources", + () => new HttpResponse("raw body", { status: 502 }), + ), + ); + const client = createHttpClient({ baseUrl: "https://api.test", clock }); + const result = await client.execute("LIST_SAMPLE_RESOURCES"); + + expect(result).toMatchObject({ + ok: false, + error: { kind: "CONTENT_TYPE_MISMATCH" }, + }); + expect(JSON.stringify(result)).not.toContain("raw body"); + }); +}); diff --git a/tests/unit/retry-policy.test.js b/tests/unit/retry-policy.test.js new file mode 100644 index 00000000..de7cd34d --- /dev/null +++ b/tests/unit/retry-policy.test.js @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; + +import { + calculateBackoff, + parseRetryAfter, + retryDelay, + shouldRetry, +} from "../../src/adapters/http/retry-policy.js"; + +describe("HTTP retry policy", () => { + it("uses capped exponential full jitter", () => { + expect(calculateBackoff(0, () => 0.5)).toBe(125); + expect(calculateBackoff(8, () => 1)).toBe(2_000); + }); + + it("parses retry-after and chooses the longer bounded delay", () => { + expect(parseRetryAfter("2", 0)).toBe(2_000); + expect(retryDelay({ kind: "RATE_LIMITED", retryAfterMs: 500 }, 0, () => 0)).toBe( + 500, + ); + }); + + it("allows at most two retries for safe or keyed requests", () => { + const failure = { kind: "SERVER_FAILURE" }; + expect(shouldRetry({ idempotency: "safe" }, failure, 0)).toBe(true); + expect(shouldRetry({ idempotency: "keyed" }, failure, 1)).toBe(true); + expect(shouldRetry({ idempotency: "safe" }, failure, 2)).toBe(false); + expect(shouldRetry({ idempotency: "none" }, failure, 0)).toBe(false); + expect( + shouldRetry( + { idempotency: "safe" }, + { kind: "SERVER_FAILURE", httpStatus: 500 }, + 0, + ), + ).toBe(false); + }); + + it("does not automatically wait beyond 30 seconds", () => { + expect( + shouldRetry( + { idempotency: "safe" }, + { kind: "RATE_LIMITED", retryAfterMs: 31_000 }, + 0, + ), + ).toBe(false); + }); +}); From bf813f09ab165138d7895a2abd6faaf7b1b5aa23 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 20:51:27 +0900 Subject: [PATCH 008/178] feat: validate HTTP envelopes and payload schemas --- src/adapters/http/client.js | 50 ++++++---- src/adapters/http/schema-registry.js | 115 +++++++++++++++++++++++ tests/integration/http-client.test.js | 31 ++++++ tests/runtime-schema/http-schema.test.js | 53 +++++++++++ 4 files changed, 232 insertions(+), 17 deletions(-) create mode 100644 src/adapters/http/schema-registry.js create mode 100644 tests/runtime-schema/http-schema.test.js diff --git a/src/adapters/http/client.js b/src/adapters/http/client.js index a7a0e635..3831cb56 100644 --- a/src/adapters/http/client.js +++ b/src/adapters/http/client.js @@ -1,6 +1,11 @@ import { systemClock } from "../../application/ports/clock-port.js"; import { getApiOperation } from "../../contracts/api-operations.js"; import { retryDelay, shouldRetry } from "./retry-policy.js"; +import { + validateEnvelope, + validateOperationPayload, + validateOperationRequest, +} from "./schema-registry.js"; const noAuthSession = /** @type {import("../../application/ports/auth-session-port.js").AuthSessionPort} */ ({ @@ -59,8 +64,7 @@ export function createHttpClient(dependencies) { const clock = dependencies.clock ?? systemClock; const random = dependencies.random ?? Math.random; const validatePayload = - dependencies.validatePayload ?? - ((_schemaId, value) => ({ success: /** @type {true} */ (true), data: value })); + dependencies.validatePayload ?? validateOperationPayload; const idempotencyKeyFactory = dependencies.idempotencyKeyFactory ?? (() => crypto.randomUUID()); @@ -155,6 +159,21 @@ export function createHttpClient(dependencies) { if (input.body !== undefined) headers.set("Content-Type", "application/json"); if (idempotencyKey) headers.set("Idempotency-Key", idempotencyKey); + if (input.body !== undefined) { + const requestValidation = validateOperationRequest( + operation.requestSchema, + input.body, + ); + if (!requestValidation.success) { + return { + ok: false, + error: failure("VALIDATION_REJECTED", operation.operationId, attempt, { + code: "REQUEST_SCHEMA_INVALID", + }), + }; + } + } + let request = new Request(new URL(operation.path, dependencies.baseUrl), { method: operation.method, headers, @@ -263,27 +282,24 @@ async function parseResponse(response, operation, attempt, validatePayload) { }; } - if (!envelope || typeof envelope !== "object") { + const envelopeValidation = validateEnvelope(envelope); + if (!envelopeValidation.success) { return { ok: false, - error: failure("ENVELOPE_MISMATCH", operation.operationId, attempt, { - code: "ENVELOPE_MISMATCH", + error: failure( + response.ok ? "ENVELOPE_MISMATCH" : statusKind(response.status), + operation.operationId, + attempt, + { + code: response.ok ? "ENVELOPE_MISMATCH" : "HTTP_FAILURE", httpStatus: response.status, - }), - }; - } - - const envelopeRecord = /** @type {Record} */ (envelope); - if (typeof envelopeRecord.success !== "boolean") { - return { - ok: false, - error: failure("ENVELOPE_MISMATCH", operation.operationId, attempt, { - code: "ENVELOPE_MISMATCH", - httpStatus: response.status, - }), + }, + ), }; } + const envelopeRecord = + /** @type {Record} */ (envelopeValidation.data); if (response.ok && envelopeRecord.success === true && "data" in envelopeRecord) { const payload = validatePayload(operation.responseSchema, envelopeRecord.data); if (!payload.success) { diff --git a/src/adapters/http/schema-registry.js b/src/adapters/http/schema-registry.js new file mode 100644 index 00000000..bc2ca78a --- /dev/null +++ b/src/adapters/http/schema-registry.js @@ -0,0 +1,115 @@ +import { z } from "zod"; + +const metaSchema = z + .object({ + requestId: z.string().min(1), + traceId: z.string().min(1), + correlationId: z.string().min(1).optional(), + }) + .passthrough(); + +export const successEnvelopeSchema = z + .object({ + success: z.literal(true), + data: z.unknown(), + meta: metaSchema, + }) + .strict(); + +export const failureEnvelopeSchema = z + .object({ + success: z.literal(false), + error: z + .object({ + code: z.string().min(1), + category: z.string().min(1).optional(), + message: z.string().optional(), + retryable: z.boolean().optional(), + details: z.unknown().optional(), + }) + .strict(), + meta: metaSchema, + }) + .strict(); + +export const responseEnvelopeSchema = z.discriminatedUnion("success", [ + successEnvelopeSchema, + failureEnvelopeSchema, +]); + +const sampleResourceSchema = z + .object({ + id: z.string().min(1), + name: z.string().min(1), + createdAt: z.string().optional(), + }) + .passthrough(); + +const payloadSchemas = + /** @type {Readonly>} */ (Object.freeze({ + SampleResourceListPayload: z.array(sampleResourceSchema), + SampleResourcePayload: sampleResourceSchema, +})); + +const requestSchemas = + /** @type {Readonly>} */ (Object.freeze({ + SampleResourceListQuery: z + .object({ + cursor: z.string().optional(), + limit: z.int().min(1).max(100).default(20), + }) + .strict(), + CreateSampleResourceCommand: z + .object({ + name: z.string().trim().min(1).max(120), + }) + .strict(), +})); + +/** @param {unknown} value */ +export function validateEnvelope(value) { + return projectResult(responseEnvelopeSchema.safeParse(value)); +} + +/** @param {string} schemaId @param {unknown} value */ +export function validateOperationPayload(schemaId, value) { + const schema = payloadSchemas[schemaId]; + if (!schema) return missingSchema(schemaId); + return projectResult(schema.safeParse(value)); +} + +/** @param {string} schemaId @param {unknown} value */ +export function validateOperationRequest(schemaId, value) { + const schema = requestSchemas[schemaId]; + if (!schema) return missingSchema(schemaId); + return projectResult(schema.safeParse(value)); +} + +/** @param {string} schemaId */ +function missingSchema(schemaId) { + return { + success: /** @type {false} */ (false), + issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED", schemaId }], + }; +} + +/** + * @param {{ success: true, data: unknown } | + * { success: false, error: { issues: Array<{ path: PropertyKey[], code: string }> } }} result + */ +function projectResult(result) { + if (result.success) { + return { + success: /** @type {true} */ (true), + data: structuredClone(result.data), + }; + } + + return { + success: /** @type {false} */ (false), + issues: result.error.issues.map((issue) => ({ + path: issue.path.join("."), + code: issue.code, + })), + }; +} diff --git a/tests/integration/http-client.test.js b/tests/integration/http-client.test.js index 28c1dd0e..b3633c42 100644 --- a/tests/integration/http-client.test.js +++ b/tests/integration/http-client.test.js @@ -68,4 +68,35 @@ describe("shared HTTP client", () => { }); expect(JSON.stringify(result)).not.toContain("raw body"); }); + + it("classifies malformed JSON and invalid payloads at the boundary", async () => { + server.use( + http.get( + "https://api.test/api/sample/resources", + () => + new HttpResponse("{", { + headers: { "Content-Type": "application/json" }, + }), + ), + ); + const client = createHttpClient({ baseUrl: "https://api.test", clock }); + await expect(client.execute("LIST_SAMPLE_RESOURCES")).resolves.toMatchObject({ + ok: false, + error: { kind: "MALFORMED_JSON" }, + }); + + server.use( + http.get("https://api.test/api/sample/resources", () => + HttpResponse.json({ + success: true, + data: [{ id: "resource-1", name: 42 }], + meta: { requestId: "request-1", traceId: "trace-1" }, + }), + ), + ); + await expect(client.execute("LIST_SAMPLE_RESOURCES")).resolves.toMatchObject({ + ok: false, + error: { kind: "SCHEMA_MISMATCH" }, + }); + }); }); diff --git a/tests/runtime-schema/http-schema.test.js b/tests/runtime-schema/http-schema.test.js new file mode 100644 index 00000000..d9b4b1d9 --- /dev/null +++ b/tests/runtime-schema/http-schema.test.js @@ -0,0 +1,53 @@ +import { describe, expect, it } from "vitest"; + +import { + validateEnvelope, + validateOperationPayload, + validateOperationRequest, +} from "../../src/adapters/http/schema-registry.js"; + +describe("HTTP runtime schema boundary", () => { + it("rejects an invalid top-level envelope", () => { + expect(validateEnvelope({ success: true }).success).toBe(false); + }); + + it("rejects an invalid operation payload with safe issue metadata", () => { + const result = validateOperationPayload("SampleResourceListPayload", [ + { id: "resource-1", name: 42 }, + ]); + + expect(result).toMatchObject({ + success: false, + issues: [{ path: "0.name" }], + }); + expect(JSON.stringify(result)).not.toContain("resource-1"); + }); + + it("returns a deep-cloned additive-tolerant payload", () => { + const source = [{ id: "resource-1", name: "Example", additive: "accepted" }]; + const result = validateOperationPayload("SampleResourceListPayload", source); + + expect(result).toMatchObject({ + success: true, + data: [{ id: "resource-1", additive: "accepted" }], + }); + expect(result.data).not.toBe(source); + }); + + it("validates outbound commands before transport", () => { + expect( + validateOperationRequest("CreateSampleResourceCommand", { name: "" }).success, + ).toBe(false); + expect( + validateOperationRequest("CreateSampleResourceCommand", { name: "Example" }) + .success, + ).toBe(true); + }); + + it("fails closed for an unregistered schema", () => { + expect(validateOperationPayload("UnknownPayload", {})).toMatchObject({ + success: false, + issues: [{ code: "SCHEMA_NOT_REGISTERED" }], + }); + }); +}); From 7f3569ce3c795b1dbae68f12acbbf47a44cbc677 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 20:52:58 +0900 Subject: [PATCH 009/178] feat: normalize failures through a stable registry --- src/adapters/http/client.js | 60 +----- src/application/ports/resource-ports.js | 2 +- src/contracts/errors.js | 240 ++++++++++++++++++++++++ tests/unit/error-classification.test.js | 70 +++++++ 4 files changed, 315 insertions(+), 57 deletions(-) create mode 100644 src/contracts/errors.js create mode 100644 tests/unit/error-classification.test.js diff --git a/src/adapters/http/client.js b/src/adapters/http/client.js index 3831cb56..4c2d9221 100644 --- a/src/adapters/http/client.js +++ b/src/adapters/http/client.js @@ -1,5 +1,9 @@ import { systemClock } from "../../application/ports/clock-port.js"; import { getApiOperation } from "../../contracts/api-operations.js"; +import { + createFailure as failure, + kindForStatus as statusKind, +} from "../../contracts/errors.js"; import { retryDelay, shouldRetry } from "./retry-policy.js"; import { validateEnvelope, @@ -36,16 +40,6 @@ const noAuthSession = * { ok: false, error: HttpFailure }} HttpResult */ -/** - * @typedef {{ - * code?: string, - * httpStatus?: number, - * requestId?: string, - * traceId?: string, - * retryAfterMs?: number - * }} FailureDetails - */ - /** * @param {{ * baseUrl: string, @@ -378,52 +372,6 @@ async function recoverSession(authSession, operation, originalFailure) { * @param {FailureDetails} [details] * @returns {HttpFailure} */ -function failure(kind, operationId, attempt, details = {}) { - const retryable = new Set([ - "NETWORK_UNREACHABLE", - "REQUEST_TIMEOUT", - "RATE_LIMITED", - "SERVER_FAILURE", - ]).has(kind); - const action = - kind === "AUTH_REQUIRED" - ? "reauth" - : retryable - ? "retry" - : kind === "REQUEST_ABORTED" - ? "none" - : "contact-support"; - - return Object.freeze({ - kind, - code: details.code ?? kind, - retryable, - operationId, - attemptCount: attempt + 1, - ...(details.httpStatus === undefined ? {} : { httpStatus: details.httpStatus }), - ...(details.requestId ? { requestId: details.requestId } : {}), - ...(details.traceId ? { traceId: details.traceId } : {}), - ...(details.retryAfterMs === undefined - ? {} - : { retryAfterMs: details.retryAfterMs }), - userMessageKey: `error.${kind.toLowerCase()}`, - action, - }); -} - -/** @param {number} status */ -function statusKind(status) { - if (status === 401) return "AUTH_REQUIRED"; - if (status === 403) return "FORBIDDEN"; - if (status === 404) return "NOT_FOUND"; - if (status === 409) return "CONFLICT"; - if (status === 422) return "VALIDATION_REJECTED"; - if (status === 429) return "RATE_LIMITED"; - if (status >= 500) return "SERVER_FAILURE"; - if (status >= 400) return "UNKNOWN_CLIENT_FAILURE"; - return "ENVELOPE_MISMATCH"; -} - /** @param {unknown} envelope */ function safeBackendCode(envelope) { if (!envelope || typeof envelope !== "object") return "HTTP_FAILURE"; diff --git a/src/application/ports/resource-ports.js b/src/application/ports/resource-ports.js index 6a077889..1290758c 100644 --- a/src/application/ports/resource-ports.js +++ b/src/application/ports/resource-ports.js @@ -22,7 +22,7 @@ /** * @template Value * @typedef {{ ok: true, value: Value, meta?: Record } | - * { ok: false, error: unknown }} Result + * { ok: false, error: import("../../contracts/errors.js").ApiFailure }} Result */ export {}; diff --git a/src/contracts/errors.js b/src/contracts/errors.js new file mode 100644 index 00000000..ee69137f --- /dev/null +++ b/src/contracts/errors.js @@ -0,0 +1,240 @@ +const DROP_SENSITIVE = Object.freeze([ + "cause", + "body", + "headers", + "authorization", + "url", + "query", + "stack", + "storageValue", +]); + +/** + * @typedef {{ + * kind: string, + * defaultRetryable: boolean, + * severity: string, + * userMessageKey: string, + * action: string, + * telemetryEvent: string, + * redaction: readonly string[] + * }} ErrorDefinition + */ + +/** + * @param {string} kind + * @param {boolean} defaultRetryable + * @param {string} severity + * @param {string} action + * @param {string} [telemetryEvent] + * @returns {Readonly} + */ +const row = ( + kind, + defaultRetryable, + severity, + action, + telemetryEvent = "api.request.failed", +) => + Object.freeze({ + kind, + defaultRetryable, + severity, + userMessageKey: `error.${kind.toLowerCase()}`, + action, + telemetryEvent, + redaction: DROP_SENSITIVE, + }); + +export const ERROR_REGISTRY = Object.freeze({ + NETWORK_UNREACHABLE: row("NETWORK_UNREACHABLE", true, "warning", "retry"), + REQUEST_TIMEOUT: row("REQUEST_TIMEOUT", true, "warning", "retry"), + REQUEST_ABORTED: row("REQUEST_ABORTED", false, "info", "none"), + CONTENT_TYPE_MISMATCH: row( + "CONTENT_TYPE_MISMATCH", + false, + "error", + "contact-support", + ), + MALFORMED_JSON: row("MALFORMED_JSON", false, "error", "contact-support"), + ENVELOPE_MISMATCH: row("ENVELOPE_MISMATCH", false, "error", "contact-support"), + SCHEMA_MISMATCH: row("SCHEMA_MISMATCH", false, "error", "contact-support"), + AUTH_REQUIRED: row("AUTH_REQUIRED", false, "info", "reauth"), + AUTH_INTEGRATION_FAILURE: row( + "AUTH_INTEGRATION_FAILURE", + false, + "error", + "contact-support", + ), + FORBIDDEN: row("FORBIDDEN", false, "warning", "navigate"), + NOT_FOUND: row("NOT_FOUND", false, "info", "navigate"), + CONFLICT: row("CONFLICT", false, "warning", "retry"), + VALIDATION_REJECTED: row("VALIDATION_REJECTED", false, "info", "none"), + UNKNOWN_CLIENT_FAILURE: row( + "UNKNOWN_CLIENT_FAILURE", + false, + "warning", + "contact-support", + ), + RATE_LIMITED: row("RATE_LIMITED", true, "warning", "retry"), + SERVER_FAILURE: row("SERVER_FAILURE", true, "error", "retry"), + CHUNK_LOAD_FAILURE: row( + "CHUNK_LOAD_FAILURE", + false, + "error", + "reload-once", + "release.mismatch.detected", + ), + BOOT_CONFIG_FAILURE: row( + "BOOT_CONFIG_FAILURE", + false, + "error", + "contact-support", + "app.boot.failed", + ), + RELEASE_MANIFEST_FAILURE: row( + "RELEASE_MANIFEST_FAILURE", + false, + "error", + "contact-support", + "app.boot.failed", + ), + DEPLOY_MISMATCH: row( + "DEPLOY_MISMATCH", + false, + "error", + "reload-once", + "release.mismatch.detected", + ), + STORAGE_UNAVAILABLE: row( + "STORAGE_UNAVAILABLE", + false, + "warning", + "none", + "storage.operation.failed", + ), + STORAGE_QUOTA_EXCEEDED: row( + "STORAGE_QUOTA_EXCEEDED", + false, + "warning", + "none", + "storage.operation.failed", + ), + RENDER_FAILURE: row( + "RENDER_FAILURE", + false, + "error", + "reload-once", + "ui.render.failed", + ), + TELEMETRY_FAILURE: row( + "TELEMETRY_FAILURE", + false, + "info", + "none", + "telemetry.delivery.dropped", + ), + QUERY_CACHE_FAILURE: row( + "QUERY_CACHE_FAILURE", + false, + "error", + "retry", + "query.cache.failed", + ), + UNKNOWN_FAILURE: row("UNKNOWN_FAILURE", false, "error", "contact-support"), +}); + +/** + * @typedef {{ + * kind: string, + * code: string, + * httpStatus?: number, + * retryable: boolean, + * operationId: string, + * attemptCount: number, + * requestId?: string, + * traceId?: string, + * retryAfterMs?: number, + * userMessageKey: string, + * action: string, + * causeClass?: string + * }} ApiFailure + */ + +/** + * @param {string} kind + * @param {string} operationId + * @param {number} attempt + * @param {{ + * code?: string, + * httpStatus?: number, + * requestId?: string, + * traceId?: string, + * retryAfterMs?: number, + * causeClass?: string + * }} [details] + * @returns {ApiFailure} + */ +export function createFailure(kind, operationId, attempt, details = {}) { + const registry = + /** @type {Readonly>>} */ ( + ERROR_REGISTRY + ); + const definition = + registry[kind] ?? ERROR_REGISTRY.UNKNOWN_FAILURE; + return Object.freeze({ + kind: definition.kind, + code: typeof details.code === "string" ? details.code : definition.kind, + retryable: definition.defaultRetryable, + operationId, + attemptCount: Math.max(1, attempt + 1), + ...(Number.isInteger(details.httpStatus) + ? { httpStatus: details.httpStatus } + : {}), + ...(typeof details.requestId === "string" ? { requestId: details.requestId } : {}), + ...(typeof details.traceId === "string" ? { traceId: details.traceId } : {}), + ...(typeof details.retryAfterMs === "number" + ? { retryAfterMs: details.retryAfterMs } + : {}), + ...(typeof details.causeClass === "string" + ? { causeClass: details.causeClass } + : {}), + userMessageKey: definition.userMessageKey, + action: definition.action, + }); +} + +/** @param {number} status */ +export function kindForStatus(status) { + if (status === 401) return "AUTH_REQUIRED"; + if (status === 403) return "FORBIDDEN"; + if (status === 404) return "NOT_FOUND"; + if (status === 409) return "CONFLICT"; + if (status === 422) return "VALIDATION_REJECTED"; + if (status === 429) return "RATE_LIMITED"; + if (status >= 500) return "SERVER_FAILURE"; + if (status >= 400) return "UNKNOWN_CLIENT_FAILURE"; + return "ENVELOPE_MISMATCH"; +} + +/** + * Total catch-all that intentionally discards the thrown value. + * + * @param {unknown} value + * @param {{ operationId?: string, attempt?: number }} [context] + */ +export function normalizeUnknownFailure(value, context = {}) { + const causeClass = + value instanceof Error + ? value.name + : value === null + ? "null" + : typeof value; + + return createFailure( + "UNKNOWN_FAILURE", + context.operationId ?? "UNKNOWN_OPERATION", + context.attempt ?? 0, + { code: "UNKNOWN_FAILURE", causeClass }, + ); +} diff --git a/tests/unit/error-classification.test.js b/tests/unit/error-classification.test.js new file mode 100644 index 00000000..4de3b47e --- /dev/null +++ b/tests/unit/error-classification.test.js @@ -0,0 +1,70 @@ +import { describe, expect, it } from "vitest"; + +import { + ERROR_REGISTRY, + createFailure, + kindForStatus, + normalizeUnknownFailure, +} from "../../src/contracts/errors.js"; + +describe("frontend failure classification", () => { + it("defines all 26 stable error kinds with the seven contract fields", () => { + expect(Object.keys(ERROR_REGISTRY)).toHaveLength(26); + for (const definition of Object.values(ERROR_REGISTRY)) { + expect(definition).toEqual( + expect.objectContaining({ + kind: expect.any(String), + defaultRetryable: expect.any(Boolean), + severity: expect.any(String), + userMessageKey: expect.any(String), + action: expect.any(String), + telemetryEvent: expect.any(String), + redaction: expect.any(Array), + }), + ); + } + }); + + it.each([ + [401, "AUTH_REQUIRED"], + [403, "FORBIDDEN"], + [404, "NOT_FOUND"], + [409, "CONFLICT"], + [422, "VALIDATION_REJECTED"], + [418, "UNKNOWN_CLIENT_FAILURE"], + [429, "RATE_LIMITED"], + [503, "SERVER_FAILURE"], + ])("maps HTTP %i to %s", (status, kind) => { + expect(kindForStatus(status)).toBe(kind); + }); + + it("projects only allowlisted safe fields", () => { + const result = createFailure("SERVER_FAILURE", "LIST_SAMPLE_RESOURCES", 0, { + code: "TEMPORARY", + httpStatus: 503, + requestId: "request-1", + stack: "must not leak", + body: "must not leak", + authorization: "Bearer secret", + }); + + expect(result).toMatchObject({ + kind: "SERVER_FAILURE", + code: "TEMPORARY", + httpStatus: 503, + requestId: "request-1", + }); + expect(JSON.stringify(result)).not.toMatch(/stack|body|Bearer|secret/); + }); + + it("normalizes any thrown value without leaking it", () => { + const secret = { token: "sensitive", nested: { rawBody: "private" } }; + const result = normalizeUnknownFailure(secret); + + expect(result).toMatchObject({ + kind: "UNKNOWN_FAILURE", + causeClass: "object", + }); + expect(JSON.stringify(result)).not.toMatch(/sensitive|private|token|rawBody/); + }); +}); From 44414c52447ca83ce24f75bb4b6bc98805773154 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 20:54:18 +0900 Subject: [PATCH 010/178] feat: integrate bounded external auth sessions --- src/adapters/auth/external-session-adapter.js | 45 ++++++++ src/adapters/http/client.js | 5 + tests/integration/auth-recovery.test.js | 103 ++++++++++++++++++ tests/unit/auth-session-adapter.test.js | 44 ++++++++ 4 files changed, 197 insertions(+) create mode 100644 src/adapters/auth/external-session-adapter.js create mode 100644 tests/integration/auth-recovery.test.js create mode 100644 tests/unit/auth-session-adapter.test.js diff --git a/src/adapters/auth/external-session-adapter.js b/src/adapters/auth/external-session-adapter.js new file mode 100644 index 00000000..00b3f997 --- /dev/null +++ b/src/adapters/auth/external-session-adapter.js @@ -0,0 +1,45 @@ +/** + * Creates the skeleton-owned side of an external session integration. + * Credential acquisition and storage stay inside the supplied external owner. + * + * @param {{ + * readState(): import("../../application/ports/auth-session-port.js").SessionState, + * attachCredential(request: Request): Promise, + * recoverSession(): Promise<"restored" | "no-session">, + * notifyUnauthenticated(): void + * }} owner + * @returns {import("../../application/ports/auth-session-port.js").AuthSessionPort} + */ +export function createExternalAuthSessionAdapter(owner) { + return Object.freeze({ + getState() { + return owner.readState(); + }, + async attach(request) { + const attached = await owner.attachCredential(request); + if (!(attached instanceof Request)) { + throw new TypeError("Auth owner returned an invalid request"); + } + return attached; + }, + async recover() { + const result = await owner.recoverSession(); + if (result !== "restored" && result !== "no-session") { + throw new TypeError("Auth owner returned an invalid recovery state"); + } + return result; + }, + onUnauthenticated() { + owner.notifyUnauthenticated(); + }, + }); +} + +export function createAnonymousSessionAdapter() { + return createExternalAuthSessionAdapter({ + readState: () => "unauthenticated", + attachCredential: async (request) => request, + recoverSession: async () => "no-session", + notifyUnauthenticated: () => {}, + }); +} diff --git a/src/adapters/http/client.js b/src/adapters/http/client.js index 4c2d9221..e1bc9e7c 100644 --- a/src/adapters/http/client.js +++ b/src/adapters/http/client.js @@ -109,6 +109,11 @@ export function createHttpClient(dependencies) { continue; } + if (outcome.error.httpStatus === 401 && recoveryUsed) { + authSession.onUnauthenticated(); + return outcome; + } + if (!shouldRetry(operation, outcome.error, retryCount)) { return outcome; } diff --git a/tests/integration/auth-recovery.test.js b/tests/integration/auth-recovery.test.js new file mode 100644 index 00000000..bb04397a --- /dev/null +++ b/tests/integration/auth-recovery.test.js @@ -0,0 +1,103 @@ +import { HttpResponse, http } from "msw"; +import { setupServer } from "msw/node"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; + +import { createExternalAuthSessionAdapter } from "../../src/adapters/auth/external-session-adapter.js"; +import { createHttpClient } from "../../src/adapters/http/client.js"; + +let responseStatuses = []; +const server = setupServer( + http.get("https://api.test/api/sample/resources", () => { + const status = responseStatuses.shift() ?? 200; + if (status === 401) { + return HttpResponse.json( + { + success: false, + error: { code: "UNAUTHENTICATED" }, + meta: { requestId: "request-1", traceId: "trace-1" }, + }, + { status }, + ); + } + return HttpResponse.json({ + success: true, + data: [{ id: "resource-1", name: "Example" }], + meta: { requestId: "request-2", traceId: "trace-1" }, + }); + }), +); + +beforeAll(() => server.listen({ onUnhandledRequest: "error" })); +afterEach(() => { + responseStatuses = []; + server.resetHandlers(); +}); +afterAll(() => server.close()); + +const clock = { now: () => 0, sleep: async () => {} }; + +describe("bounded 401 session recovery", () => { + it("calls recovery once and replays a safe request once", async () => { + responseStatuses = [401, 200]; + const recoverSession = vi.fn(async () => "restored"); + const authSession = createExternalAuthSessionAdapter({ + readState: () => "authenticated", + attachCredential: async (request) => request, + recoverSession, + notifyUnauthenticated: vi.fn(), + }); + const client = createHttpClient({ + baseUrl: "https://api.test", + authSession, + clock, + }); + + await expect(client.execute("LIST_SAMPLE_RESOURCES")).resolves.toMatchObject({ + ok: true, + }); + expect(recoverSession).toHaveBeenCalledTimes(1); + }); + + it("stops after a second 401 and notifies unauthenticated once", async () => { + responseStatuses = [401, 401]; + const notifyUnauthenticated = vi.fn(); + const authSession = createExternalAuthSessionAdapter({ + readState: () => "authenticated", + attachCredential: async (request) => request, + recoverSession: async () => "restored", + notifyUnauthenticated, + }); + const client = createHttpClient({ + baseUrl: "https://api.test", + authSession, + clock, + }); + + await expect(client.execute("LIST_SAMPLE_RESOURCES")).resolves.toMatchObject({ + ok: false, + error: { kind: "AUTH_REQUIRED" }, + }); + expect(notifyUnauthenticated).toHaveBeenCalledTimes(1); + }); + + it("normalizes attach and invalid recovery failures", async () => { + const attachFailure = createExternalAuthSessionAdapter({ + readState: () => "authenticated", + attachCredential: async () => { + throw new Error("credential detail"); + }, + recoverSession: async () => "restored", + notifyUnauthenticated: vi.fn(), + }); + const client = createHttpClient({ + baseUrl: "https://api.test", + authSession: attachFailure, + clock, + }); + + await expect(client.execute("LIST_SAMPLE_RESOURCES")).resolves.toMatchObject({ + ok: false, + error: { kind: "AUTH_INTEGRATION_FAILURE" }, + }); + }); +}); diff --git a/tests/unit/auth-session-adapter.test.js b/tests/unit/auth-session-adapter.test.js new file mode 100644 index 00000000..d1221e96 --- /dev/null +++ b/tests/unit/auth-session-adapter.test.js @@ -0,0 +1,44 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + createAnonymousSessionAdapter, + createExternalAuthSessionAdapter, +} from "../../src/adapters/auth/external-session-adapter.js"; + +describe("external AuthSessionPort adapter", () => { + it("attaches opaque credentials without exposing a token-shaped session", async () => { + const adapter = createExternalAuthSessionAdapter({ + readState: () => "authenticated", + attachCredential: async (request) => { + const headers = new Headers(request.headers); + headers.set("X-Session-Attached", "true"); + return new Request(request, { headers }); + }, + recoverSession: async () => "restored", + notifyUnauthenticated: vi.fn(), + }); + + const request = await adapter.attach(new Request("https://api.test/resource")); + expect(request.headers.get("X-Session-Attached")).toBe("true"); + expect(adapter.getState()).toBe("authenticated"); + expect(adapter).not.toHaveProperty("accessToken"); + expect(adapter).not.toHaveProperty("refreshToken"); + }); + + it("fails invalid recovery states closed", async () => { + const adapter = createExternalAuthSessionAdapter({ + readState: () => "authenticated", + attachCredential: async (request) => request, + recoverSession: async () => "unexpected", + notifyUnauthenticated: vi.fn(), + }); + + await expect(adapter.recover()).rejects.toThrow("invalid recovery state"); + }); + + it("provides a safe anonymous adapter", async () => { + const adapter = createAnonymousSessionAdapter(); + expect(adapter.getState()).toBe("unauthenticated"); + await expect(adapter.recover()).resolves.toBe("no-session"); + }); +}); From 184eb67282ecfee8d4412bce531bd65159a3dfca Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 20:55:27 +0900 Subject: [PATCH 011/178] feat: add application-owned query cache contract --- package.json | 1 + pnpm-lock.yaml | 18 +++++ .../query-cache/tanstack-query-cache.js | 72 +++++++++++++++++++ src/application/ports/query-cache-port.js | 9 ++- src/contracts/query-keys.js | 36 ++++++++++ tests/unit/query-cache.test.js | 55 ++++++++++++++ 6 files changed, 188 insertions(+), 3 deletions(-) create mode 100644 src/adapters/query-cache/tanstack-query-cache.js create mode 100644 src/contracts/query-keys.js create mode 100644 tests/unit/query-cache.test.js diff --git a/package.json b/package.json index 66ee01d8..0ca4c81a 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,7 @@ "test:all": "pnpm test:runtime-schema && pnpm test:unit && pnpm test:component && pnpm test:integration" }, "dependencies": { + "@tanstack/react-query": "5.101.4", "react": "19.2.8", "react-dom": "19.2.8", "zod": "4.4.3" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c89142c1..edec4217 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,6 +8,9 @@ importers: .: dependencies: + '@tanstack/react-query': + specifier: 5.101.4 + version: 5.101.4(react@19.2.8) react: specifier: 19.2.8 version: 19.2.8 @@ -396,6 +399,14 @@ packages: '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + '@tanstack/query-core@5.101.4': + resolution: {integrity: sha512-gNwcvOJcRbLWPOLG/2OBm+zM+Yv+MKsXKEOWC57USuZDEsI71hEErQsiEGx5wX9rzWWkfwM0fVSPoiIFSsxfiw==} + + '@tanstack/react-query@5.101.4': + resolution: {integrity: sha512-yRg2pfOCxIs4ZJW3XYYHU/WgtD04FHSnfHlpRT7h7pR77hwkdRG4wxbKe4aq6P0RvXUTBSQpQeadS1SUYUe+KA==} + peerDependencies: + react: ^18 || ^19 + '@testing-library/dom@10.4.1': resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==} engines: {node: '>=18'} @@ -1840,6 +1851,13 @@ snapshots: '@standard-schema/spec@1.1.0': {} + '@tanstack/query-core@5.101.4': {} + + '@tanstack/react-query@5.101.4(react@19.2.8)': + dependencies: + '@tanstack/query-core': 5.101.4 + react: 19.2.8 + '@testing-library/dom@10.4.1': dependencies: '@babel/code-frame': 7.29.7 diff --git a/src/adapters/query-cache/tanstack-query-cache.js b/src/adapters/query-cache/tanstack-query-cache.js new file mode 100644 index 00000000..690ecb6f --- /dev/null +++ b/src/adapters/query-cache/tanstack-query-cache.js @@ -0,0 +1,72 @@ +import { QueryClient } from "@tanstack/react-query"; + +import { createFailure } from "../../contracts/errors.js"; + +export const QUERY_CACHE_DEFAULTS = Object.freeze({ + staleTime: 30_000, + gcTime: 300_000, + refetchOnWindowFocus: true, + retry: false, + mutationRetry: false, + persistence: false, +}); + +export function createQueryClient() { + return new QueryClient({ + defaultOptions: { + queries: { + staleTime: QUERY_CACHE_DEFAULTS.staleTime, + gcTime: QUERY_CACHE_DEFAULTS.gcTime, + refetchOnWindowFocus: QUERY_CACHE_DEFAULTS.refetchOnWindowFocus, + retry: QUERY_CACHE_DEFAULTS.retry, + }, + mutations: { + retry: QUERY_CACHE_DEFAULTS.mutationRetry, + }, + }, + }); +} + +/** + * @param {QueryClient} queryClient + * @returns {import("../../application/ports/query-cache-port.js").QueryCachePort} + */ +export function createQueryCacheAdapter(queryClient) { + return Object.freeze({ + read(key) { + try { + return { ok: true, value: queryClient.getQueryData(key) }; + } catch { + return cacheFailure("read", key); + } + }, + write(key, value) { + try { + queryClient.setQueryData(key, structuredClone(value)); + return { ok: true }; + } catch { + return cacheFailure("write", key); + } + }, + async invalidate(namespace) { + try { + await queryClient.invalidateQueries({ queryKey: namespace, exact: false }); + return { ok: true }; + } catch { + return cacheFailure("invalidate", namespace); + } + }, + }); +} + +/** @param {string} phase @param {readonly unknown[]} key */ +function cacheFailure(phase, key) { + const namespace = typeof key[0] === "string" ? key[0] : "unknown"; + return { + ok: /** @type {false} */ (false), + error: createFailure("QUERY_CACHE_FAILURE", "QUERY_CACHE", 0, { + code: `QUERY_CACHE_${phase.toUpperCase()}_FAILED`, + causeClass: `namespace:${namespace}`, + }), + }; +} diff --git a/src/application/ports/query-cache-port.js b/src/application/ports/query-cache-port.js index 872d857f..f06905b8 100644 --- a/src/application/ports/query-cache-port.js +++ b/src/application/ports/query-cache-port.js @@ -1,8 +1,11 @@ /** * @typedef {{ - * read(key: readonly unknown[]): unknown, - * write(key: readonly unknown[], value: unknown): void, - * invalidate(namespace: readonly unknown[]): Promise + * read(key: readonly unknown[]): { ok: true, value: unknown } | + * { ok: false, error: import("../../contracts/errors.js").ApiFailure }, + * write(key: readonly unknown[], value: unknown): { ok: true } | + * { ok: false, error: import("../../contracts/errors.js").ApiFailure }, + * invalidate(namespace: readonly unknown[]): Promise<{ ok: true } | + * { ok: false, error: import("../../contracts/errors.js").ApiFailure }> * }} QueryCachePort */ diff --git a/src/contracts/query-keys.js b/src/contracts/query-keys.js new file mode 100644 index 00000000..050ac61b --- /dev/null +++ b/src/contracts/query-keys.js @@ -0,0 +1,36 @@ +const RESOURCE_NAMESPACE = Object.freeze(["resource", 1]); + +export const queryKeys = Object.freeze({ + resource: Object.freeze({ + all: () => RESOURCE_NAMESPACE, + list: (filters = {}) => + Object.freeze([...RESOURCE_NAMESPACE, "list", canonicalize(filters)]), + /** @param {string} resourceId */ + detail: (resourceId) => + Object.freeze([...RESOURCE_NAMESPACE, "detail", String(resourceId)]), + }), +}); + +export const QUERY_REGISTRY = Object.freeze({ + RESOURCE: Object.freeze({ + namespace: RESOURCE_NAMESPACE, + serialization: "canonical-object-order", + identity: "no-pii-token-or-raw-url", + invalidation: "resource namespace after successful mutation", + version: 1, + persistence: "disabled", + }), +}); + +/** @param {unknown} value @returns {unknown} */ +export function canonicalize(value) { + if (Array.isArray(value)) return value.map(canonicalize); + if (value && typeof value === "object") { + return Object.fromEntries( + Object.entries(value) + .sort(([left], [right]) => left.localeCompare(right)) + .map(([key, item]) => [key, canonicalize(item)]), + ); + } + return value; +} diff --git a/tests/unit/query-cache.test.js b/tests/unit/query-cache.test.js new file mode 100644 index 00000000..f92732ac --- /dev/null +++ b/tests/unit/query-cache.test.js @@ -0,0 +1,55 @@ +import { QueryClient } from "@tanstack/react-query"; +import { describe, expect, it, vi } from "vitest"; + +import { + createQueryCacheAdapter, + createQueryClient, +} from "../../src/adapters/query-cache/tanstack-query-cache.js"; +import { queryKeys } from "../../src/contracts/query-keys.js"; + +describe("query key registry", () => { + it("canonicalizes filter order into the same stable key", () => { + expect(queryKeys.resource.list({ page: 1, status: "open" })).toEqual( + queryKeys.resource.list({ status: "open", page: 1 }), + ); + }); + + it("contains no raw URL or token material", () => { + expect(JSON.stringify(queryKeys.resource.detail("resource-1"))).toBe( + '["resource",1,"detail","resource-1"]', + ); + }); +}); + +describe("TanStack QueryCachePort adapter", () => { + it("reads, writes, and invalidates only the declared namespace", async () => { + const client = createQueryClient(); + const adapter = createQueryCacheAdapter(client); + const listKey = queryKeys.resource.list({ page: 1 }); + const otherKey = ["other", 1]; + + expect(adapter.write(listKey, [{ id: "resource-1" }])).toEqual({ ok: true }); + expect(adapter.write(otherKey, "preserved")).toEqual({ ok: true }); + expect(adapter.read(listKey)).toMatchObject({ + ok: true, + value: [{ id: "resource-1" }], + }); + + await adapter.invalidate(queryKeys.resource.all()); + expect(client.getQueryState(listKey)?.isInvalidated).toBe(true); + expect(client.getQueryState(otherKey)?.isInvalidated).toBe(false); + }); + + it("normalizes adapter exceptions without raw key data", async () => { + const client = new QueryClient(); + vi.spyOn(client, "invalidateQueries").mockRejectedValue(new Error("secret-key")); + const adapter = createQueryCacheAdapter(client); + const result = await adapter.invalidate(["resource", "sensitive-filter"]); + + expect(result).toMatchObject({ + ok: false, + error: { kind: "QUERY_CACHE_FAILURE" }, + }); + expect(JSON.stringify(result)).not.toContain("sensitive-filter"); + }); +}); From 2c3eda4d6b67da00e8207df6065533322eae81cf Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 20:56:58 +0900 Subject: [PATCH 012/178] feat: enforce classified browser storage registry --- .../storage/browser-storage-adapter.js | 137 ++++++++++++++++++ src/application/ports/storage-port.js | 10 +- src/contracts/storage-keys.js | 102 +++++++++++++ tests/unit/storage-registry.test.js | 78 ++++++++++ 4 files changed, 324 insertions(+), 3 deletions(-) create mode 100644 src/adapters/storage/browser-storage-adapter.js create mode 100644 src/contracts/storage-keys.js create mode 100644 tests/unit/storage-registry.test.js diff --git a/src/adapters/storage/browser-storage-adapter.js b/src/adapters/storage/browser-storage-adapter.js new file mode 100644 index 00000000..e05c5bb3 --- /dev/null +++ b/src/adapters/storage/browser-storage-adapter.js @@ -0,0 +1,137 @@ +import { createFailure } from "../../contracts/errors.js"; +import { getStorageDefinition } from "../../contracts/storage-keys.js"; + +/** + * @param {{ + * localStorage?: Storage, + * sessionStorage?: Storage, + * now?: () => number + * }} [dependencies] + * @returns {import("../../application/ports/storage-port.js").StoragePort} + */ +export function createBrowserStorageAdapter(dependencies = {}) { + const memory = new Map(); + const now = dependencies.now ?? Date.now; + + /** @param {string} name */ + function backendFor(name) { + if (name === "localStorage") return dependencies.localStorage; + if (name === "sessionStorage") return dependencies.sessionStorage; + return undefined; + } + + return Object.freeze({ + read(logicalName) { + let definition; + try { + definition = getStorageDefinition(logicalName); + } catch { + return unavailable("read", logicalName); + } + + const backend = backendFor(definition.backend); + try { + const raw = backend?.getItem(definition.physicalKey); + if (raw === null || raw === undefined) { + return { ok: true, value: memory.get(definition.physicalKey) }; + } + const envelope = JSON.parse(raw); + if ( + !envelope || + typeof envelope !== "object" || + envelope.schemaVersion !== definition.schemaVersion + ) { + backend?.removeItem(definition.physicalKey); + return { ok: true, value: undefined }; + } + if (typeof envelope.expiresAt === "number" && envelope.expiresAt <= now()) { + backend?.removeItem(definition.physicalKey); + return { ok: true, value: undefined }; + } + return { ok: true, value: structuredClone(envelope.value) }; + } catch { + return unavailable("read", logicalName); + } + }, + + write(logicalName, value) { + let definition; + try { + definition = getStorageDefinition(logicalName); + } catch { + return unavailable("write", logicalName); + } + + const expiresAt = + typeof definition.ttl === "number" ? now() + definition.ttl : null; + const envelope = { + schemaVersion: definition.schemaVersion, + expiresAt, + value: structuredClone(value), + }; + const backend = backendFor(definition.backend); + + try { + if (!backend) throw new DOMException("Storage unavailable", "SecurityError"); + backend.setItem(definition.physicalKey, JSON.stringify(envelope)); + return { ok: true }; + } catch (error) { + const quota = + error instanceof DOMException && + ["QuotaExceededError", "NS_ERROR_DOM_QUOTA_REACHED"].includes(error.name); + + if (definition.quotaFallback === "memory") { + memory.set(definition.physicalKey, structuredClone(value)); + return { + ok: false, + error: storageFailure(quota, "write", logicalName), + fallback: "memory", + }; + } + return { + ok: false, + error: storageFailure(quota, "write", logicalName), + fallback: definition.quotaFallback, + }; + } + }, + + remove(logicalName) { + let definition; + try { + definition = getStorageDefinition(logicalName); + } catch { + return unavailable("remove", logicalName); + } + try { + backendFor(definition.backend)?.removeItem(definition.physicalKey); + memory.delete(definition.physicalKey); + return { ok: true }; + } catch { + return unavailable("remove", logicalName); + } + }, + }); +} + +/** @param {boolean} quota @param {string} phase @param {string} logicalName */ +function storageFailure(quota, phase, logicalName) { + return createFailure( + quota ? "STORAGE_QUOTA_EXCEEDED" : "STORAGE_UNAVAILABLE", + "STORAGE", + 0, + { + code: `${logicalName}_${phase.toUpperCase()}_${ + quota ? "QUOTA_EXCEEDED" : "UNAVAILABLE" + }`, + }, + ); +} + +/** @param {string} phase @param {string} logicalName */ +function unavailable(phase, logicalName) { + return { + ok: /** @type {false} */ (false), + error: storageFailure(false, phase, logicalName), + }; +} diff --git a/src/application/ports/storage-port.js b/src/application/ports/storage-port.js index 98dae43d..e200efd5 100644 --- a/src/application/ports/storage-port.js +++ b/src/application/ports/storage-port.js @@ -1,8 +1,12 @@ /** * @typedef {{ - * read(logicalName: string): { ok: true, value: unknown } | { ok: false, error: unknown }, - * write(logicalName: string, value: unknown): { ok: true } | { ok: false, error: unknown }, - * remove(logicalName: string): { ok: true } | { ok: false, error: unknown } + * read(logicalName: string): { ok: true, value: unknown } | + * { ok: false, error: import("../../contracts/errors.js").ApiFailure }, + * write(logicalName: string, value: unknown): { ok: true } | + * { ok: false, error: import("../../contracts/errors.js").ApiFailure, + * fallback?: string }, + * remove(logicalName: string): { ok: true } | + * { ok: false, error: import("../../contracts/errors.js").ApiFailure } * }} StoragePort */ diff --git a/src/contracts/storage-keys.js b/src/contracts/storage-keys.js new file mode 100644 index 00000000..2e3e2fca --- /dev/null +++ b/src/contracts/storage-keys.js @@ -0,0 +1,102 @@ +const APP_NAMESPACE = "ca-frontend"; + +export const STORAGE_REGISTRY = Object.freeze({ + COLOR_SCHEME: defineStorageKey({ + logicalName: "COLOR_SCHEME", + scope: "preference", + name: "color-scheme", + backend: "localStorage", + classification: "public-preference", + schemaVersion: 1, + ttl: null, + migration: "discard", + quotaFallback: "memory", + }), + CHUNK_RELOAD_GUARD: defineStorageKey({ + logicalName: "CHUNK_RELOAD_GUARD", + scope: "release", + name: "chunk-reload-guard", + backend: "sessionStorage", + classification: "opaque-cache", + schemaVersion: 1, + ttl: "session", + migration: "discard", + quotaFallback: "no-persist", + }), + QUERY_PERSISTENCE: defineStorageKey({ + logicalName: "QUERY_PERSISTENCE", + scope: "cache", + name: "query-persistence", + backend: "disabled", + classification: "sensitive-forbidden", + schemaVersion: 1, + ttl: null, + migration: "discard", + quotaFallback: "feature-disable", + }), + AUTH_TOKEN: defineStorageKey({ + logicalName: "AUTH_TOKEN", + scope: "auth", + name: "auth-token", + backend: "forbidden", + classification: "sensitive-forbidden", + schemaVersion: 1, + ttl: null, + migration: "discard", + quotaFallback: "feature-disable", + }), +}); + +/** + * @typedef {{ + * logicalName: string, + * scope: string, + * name: string, + * backend: "memory" | "sessionStorage" | "localStorage" | "indexedDB" | + * "disabled" | "forbidden", + * classification: "public-preference" | "opaque-cache" | "sensitive-forbidden", + * schemaVersion: number, + * ttl: number | "session" | null, + * migration: "discard" | ((value: unknown) => unknown), + * quotaFallback: "memory" | "no-persist" | "feature-disable" + * }} StorageKeyInput + */ + +/** @param {StorageKeyInput} definition */ +export function defineStorageKey(definition) { + if (definition.classification === "sensitive-forbidden") { + if (!["disabled", "forbidden"].includes(definition.backend)) { + throw new Error("Sensitive client storage registration is forbidden"); + } + } + if (!Number.isInteger(definition.schemaVersion) || definition.schemaVersion < 1) { + throw new Error("Storage schemaVersion must be a positive integer"); + } + + return Object.freeze({ + ...definition, + physicalKey: buildPhysicalKey( + definition.scope, + definition.schemaVersion, + definition.name, + ), + }); +} + +/** @param {string} scope @param {number} schemaVersion @param {string} name */ +export function buildPhysicalKey(scope, schemaVersion, name) { + return `${APP_NAMESPACE}:${scope}:v${schemaVersion}:${name}`; +} + +/** @param {string} logicalName */ +export function getStorageDefinition(logicalName) { + const registry = /** @type {Record>} */ ( + STORAGE_REGISTRY + ); + const definition = registry[logicalName]; + if (!definition) throw new Error(`Unregistered storage key: ${logicalName}`); + if (definition.classification === "sensitive-forbidden") { + throw new Error(`Forbidden storage key: ${logicalName}`); + } + return definition; +} diff --git a/tests/unit/storage-registry.test.js b/tests/unit/storage-registry.test.js new file mode 100644 index 00000000..fa752506 --- /dev/null +++ b/tests/unit/storage-registry.test.js @@ -0,0 +1,78 @@ +import { describe, expect, it } from "vitest"; + +import { createBrowserStorageAdapter } from "../../src/adapters/storage/browser-storage-adapter.js"; +import { + STORAGE_REGISTRY, + buildPhysicalKey, + defineStorageKey, +} from "../../src/contracts/storage-keys.js"; + +function createStorage({ quota = false } = {}) { + const values = new Map(); + return { + getItem: (key) => values.get(key) ?? null, + setItem: (key, value) => { + if (quota) throw new DOMException("full", "QuotaExceededError"); + values.set(key, value); + }, + removeItem: (key) => values.delete(key), + clear: () => values.clear(), + key: () => null, + get length() { + return values.size; + }, + }; +} + +describe("storage registry", () => { + it("builds namespace and schema-versioned physical keys", () => { + expect(buildPhysicalKey("preference", 2, "theme")).toBe( + "ca-frontend:preference:v2:theme", + ); + expect(STORAGE_REGISTRY.COLOR_SCHEME.physicalKey).toContain(":v1:"); + }); + + it("rejects token or secret persistence registrations", () => { + expect(() => + defineStorageKey({ + logicalName: "TOKEN", + scope: "auth", + name: "token", + backend: "localStorage", + classification: "sensitive-forbidden", + schemaVersion: 1, + ttl: null, + migration: "discard", + quotaFallback: "feature-disable", + }), + ).toThrow("Sensitive client storage registration is forbidden"); + }); + + it("round-trips public preferences through the adapter", () => { + const localStorage = createStorage(); + const adapter = createBrowserStorageAdapter({ localStorage }); + expect(adapter.write("COLOR_SCHEME", "dark")).toEqual({ ok: true }); + expect(adapter.read("COLOR_SCHEME")).toEqual({ ok: true, value: "dark" }); + }); + + it("falls back to memory when preference storage quota is exceeded", () => { + const localStorage = createStorage({ quota: true }); + const adapter = createBrowserStorageAdapter({ localStorage }); + expect(adapter.write("COLOR_SCHEME", "dark")).toMatchObject({ + ok: false, + fallback: "memory", + error: { kind: "STORAGE_QUOTA_EXCEEDED" }, + }); + expect(adapter.read("COLOR_SCHEME")).toEqual({ ok: true, value: "dark" }); + }); + + it("discards data from a previous schema version", () => { + const localStorage = createStorage(); + localStorage.setItem( + STORAGE_REGISTRY.COLOR_SCHEME.physicalKey, + JSON.stringify({ schemaVersion: 0, value: "dark" }), + ); + const adapter = createBrowserStorageAdapter({ localStorage }); + expect(adapter.read("COLOR_SCHEME")).toEqual({ ok: true, value: undefined }); + }); +}); From bf8d69e2858cf7b2a13cf8ebdbb3cf8365d5b7a6 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 20:58:33 +0900 Subject: [PATCH 013/178] feat: add redacted best-effort telemetry contract --- .../telemetry/best-effort-telemetry.js | 99 ++++++++++++ src/contracts/telemetry.js | 145 ++++++++++++++++++ tests/unit/telemetry.test.js | 105 +++++++++++++ 3 files changed, 349 insertions(+) create mode 100644 src/adapters/telemetry/best-effort-telemetry.js create mode 100644 src/contracts/telemetry.js create mode 100644 tests/unit/telemetry.test.js diff --git a/src/adapters/telemetry/best-effort-telemetry.js b/src/adapters/telemetry/best-effort-telemetry.js new file mode 100644 index 00000000..116289c0 --- /dev/null +++ b/src/adapters/telemetry/best-effort-telemetry.js @@ -0,0 +1,99 @@ +import { projectTelemetryEvent } from "../../contracts/telemetry.js"; + +export const noOpTelemetry = Object.freeze({ + emit: () => {}, +}); + +/** + * @param {{ + * enabled: boolean, + * endpoint?: string, + * fetcher?: typeof fetch, + * maxQueue?: number, + * schedule?: (callback: () => void) => void + * }} options + */ +export function createTelemetryAdapter(options) { + if (!options.enabled || !options.endpoint) { + return Object.freeze({ + ...noOpTelemetry, + flush: async () => {}, + pendingCount: () => 0, + droppedCount: () => 0, + }); + } + + const endpoint = /** @type {string} */ (options.endpoint); + const fetcher = options.fetcher ?? fetch; + const maxQueue = options.maxQueue ?? 100; + const schedule = options.schedule ?? queueMicrotask; + const queue = + /** @type {Array<{eventName: string, attributes: Readonly>}>} */ ( + [] + ); + let scheduled = false; + let flushing = false; + let dropped = 0; + + /** @param {string} eventName @param {Record} attributes */ + function emit(eventName, attributes) { + const projected = projectTelemetryEvent(eventName, attributes); + if (!projected.success) { + dropped += 1; + return; + } + + if (queue.length >= maxQueue) { + queue.shift(); + dropped += 1; + } + queue.push(projected.event); + + if (!scheduled) { + scheduled = true; + schedule(() => { + scheduled = false; + void flush(); + }); + } + } + + async function flush() { + if (flushing || queue.length === 0) return; + flushing = true; + const batch = queue.splice(0, queue.length); + try { + const response = await fetcher(endpoint, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ events: batch }), + keepalive: true, + }); + if (!response.ok) dropped += batch.length; + } catch { + dropped += batch.length; + } finally { + flushing = false; + } + } + + return Object.freeze({ + emit, + flush, + pendingCount: () => queue.length, + droppedCount: () => dropped, + }); +} + +/** + * Propagates only a structurally valid W3C traceparent. Invalid/raw headers are + * discarded rather than logged or surfaced. + * + * @param {string | null | undefined} traceparent + */ +export function safeTraceparent(traceparent) { + return typeof traceparent === "string" && + /^00-[0-9a-f]{32}-[0-9a-f]{16}-0[01]$/i.test(traceparent) + ? traceparent.toLowerCase() + : null; +} diff --git a/src/contracts/telemetry.js b/src/contracts/telemetry.js new file mode 100644 index 00000000..301ac225 --- /dev/null +++ b/src/contracts/telemetry.js @@ -0,0 +1,145 @@ +export const TELEMETRY_ATTRIBUTE_ALLOWLIST = Object.freeze([ + "app_version", + "build_id", + "release_id", + "config_schema_version", + "api_contract_version", + "route_id", + "operation_id", + "error_kind", + "http_status_group", + "attempt_count_bucket", + "duration_bucket", + "component_boundary", + "active_release_id", + "mismatch_kind", + "reason", + "queue_size_bucket", +]); + +export const TELEMETRY_FORBIDDEN_ATTRIBUTES = Object.freeze([ + "access_token", + "refresh_token", + "authorization_header", + "cookie", + "email", + "user_name", + "raw_user_id", + "raw_url", + "query_string", + "request_body", + "response_body", + "storage_value", + "stack_in_user_message", +]); + +/** + * @typedef {{ + * eventName: string, + * trigger: string, + * requiredAttributes: readonly string[], + * optionalAttributes: readonly string[], + * forbiddenAttributes: readonly string[], + * sampling: string, + * delivery: string + * }} TelemetryDefinition + */ + +/** + * @param {string} eventName + * @param {string} trigger + * @param {string[]} requiredAttributes + * @param {string[]} [optionalAttributes] + * @param {string} [sampling] + * @returns {Readonly} + */ +const event = ( + eventName, + trigger, + requiredAttributes, + optionalAttributes = [], + sampling = "all", +) => + Object.freeze({ + eventName, + trigger, + requiredAttributes: Object.freeze(requiredAttributes), + optionalAttributes: Object.freeze(optionalAttributes), + forbiddenAttributes: TELEMETRY_FORBIDDEN_ATTRIBUTES, + sampling, + delivery: "best-effort", + }); + +export const TELEMETRY_REGISTRY = Object.freeze({ + "app.boot.failed": event("app.boot.failed", "boot validation failure", [ + "error_kind", + "build_id", + "config_schema_version", + ]), + "api.request.failed": event("api.request.failed", "terminal API failure", [ + "error_kind", + "http_status_group", + "attempt_count_bucket", + "route_id", + ]), + "ui.render.failed": event("ui.render.failed", "React boundary catch", [ + "route_id", + "build_id", + "component_boundary", + ]), + "release.mismatch.detected": event( + "release.mismatch.detected", + "release tuple mismatch", + ["build_id", "active_release_id", "mismatch_kind"], + ), + "telemetry.delivery.dropped": event( + "telemetry.delivery.dropped", + "queue or sink failure", + ["reason", "queue_size_bucket"], + [], + "internal-counter", + ), +}); + +/** + * @param {string} eventName + * @param {Record} attributes + */ +export function projectTelemetryEvent(eventName, attributes) { + const registry = + /** @type {Record} */ ( + TELEMETRY_REGISTRY + ); + const definition = registry[eventName]; + if (!definition) { + return { + success: /** @type {false} */ (false), + reason: "unregistered-event", + }; + } + + const projected = Object.fromEntries( + Object.entries(attributes).filter( + ([key]) => + TELEMETRY_ATTRIBUTE_ALLOWLIST.includes(key) && + !TELEMETRY_FORBIDDEN_ATTRIBUTES.includes(key), + ), + ); + const missing = definition.requiredAttributes.filter( + (key) => projected[key] === undefined, + ); + if (missing.length > 0) { + return { + success: /** @type {false} */ (false), + reason: "missing-required-attributes", + }; + } + + return { + success: /** @type {true} */ (true), + event: Object.freeze({ + eventName, + attributes: Object.freeze(projected), + }), + }; +} diff --git a/tests/unit/telemetry.test.js b/tests/unit/telemetry.test.js new file mode 100644 index 00000000..3400abd3 --- /dev/null +++ b/tests/unit/telemetry.test.js @@ -0,0 +1,105 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + createTelemetryAdapter, + safeTraceparent, +} from "../../src/adapters/telemetry/best-effort-telemetry.js"; +import { + TELEMETRY_REGISTRY, + projectTelemetryEvent, +} from "../../src/contracts/telemetry.js"; + +const validAttributes = { + error_kind: "SERVER_FAILURE", + http_status_group: "5xx", + attempt_count_bucket: "3", + route_id: "SAMPLE_RESOURCE_LIST", +}; + +describe("telemetry registry and redaction", () => { + it("defines all event contract fields", () => { + for (const definition of Object.values(TELEMETRY_REGISTRY)) { + expect(definition).toEqual( + expect.objectContaining({ + eventName: expect.any(String), + trigger: expect.any(String), + requiredAttributes: expect.any(Array), + optionalAttributes: expect.any(Array), + forbiddenAttributes: expect.any(Array), + sampling: expect.any(String), + delivery: "best-effort", + }), + ); + } + }); + + it("uses a default-deny attribute projection", () => { + const projected = projectTelemetryEvent("api.request.failed", { + ...validAttributes, + raw_url: "https://api.test/path?token=secret", + unregistered: "private", + }); + + expect(projected.success).toBe(true); + expect(JSON.stringify(projected)).not.toMatch(/raw_url|token|secret|unregistered/); + }); + + it("validates traceparent without exposing invalid values", () => { + expect( + safeTraceparent( + "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", + ), + ).toBe("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"); + expect(safeTraceparent("Bearer secret")).toBeNull(); + }); +}); + +describe("best-effort telemetry adapter", () => { + it("bounds the queue using oldest-drop without blocking callers", () => { + const scheduled = []; + const adapter = createTelemetryAdapter({ + enabled: true, + endpoint: "https://telemetry.test/events", + maxQueue: 2, + schedule: (callback) => scheduled.push(callback), + fetcher: vi.fn(), + }); + + adapter.emit("api.request.failed", validAttributes); + adapter.emit("api.request.failed", validAttributes); + adapter.emit("api.request.failed", validAttributes); + + expect(adapter.pendingCount()).toBe(2); + expect(adapter.droppedCount()).toBe(1); + expect(scheduled).toHaveLength(1); + }); + + it("degrades on sink failure without throwing or recursive events", async () => { + const adapter = createTelemetryAdapter({ + enabled: true, + endpoint: "https://telemetry.test/events", + schedule: () => {}, + fetcher: async () => { + throw new Error("sink unavailable"); + }, + }); + expect(() => adapter.emit("api.request.failed", validAttributes)).not.toThrow(); + await expect(adapter.flush()).resolves.toBeUndefined(); + expect(adapter.droppedCount()).toBe(1); + expect(adapter.pendingCount()).toBe(0); + }); + + it("performs no network or queue work when disabled", async () => { + const fetcher = vi.fn(); + const adapter = createTelemetryAdapter({ + enabled: false, + endpoint: "https://telemetry.test/events", + fetcher, + }); + adapter.emit("api.request.failed", validAttributes); + await adapter.flush(); + + expect(fetcher).not.toHaveBeenCalled(); + expect(adapter.pendingCount()).toBe(0); + }); +}); From 438dc1154859f06a43df838eac7b7643b08ed838 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:00:21 +0900 Subject: [PATCH 014/178] feat: model complete async UI surface states --- src/application/view-models/async-state.js | 81 +++++++++++++++++++ src/contracts/errors.js | 11 ++- src/presentation/components/async-surface.jsx | 72 +++++++++++++++++ tests/component/async-surface.test.jsx | 76 +++++++++++++++++ 4 files changed, 237 insertions(+), 3 deletions(-) create mode 100644 src/application/view-models/async-state.js create mode 100644 src/presentation/components/async-surface.jsx create mode 100644 tests/component/async-surface.test.jsx diff --git a/src/application/view-models/async-state.js b/src/application/view-models/async-state.js new file mode 100644 index 00000000..4d6db8c5 --- /dev/null +++ b/src/application/view-models/async-state.js @@ -0,0 +1,81 @@ +export const ASYNC_BASE_STATES = Object.freeze([ + "initial-loading", + "success", + "empty", + "terminal-error", +]); + +export const ASYNC_OVERLAYS = Object.freeze([ + "refreshing", + "stale-degraded", + "mutation-pending", + "mutation-conflict", +]); + +/** + * @typedef {{ + * data?: unknown, + * isInitialLoading?: boolean, + * failure?: import("../../contracts/errors.js").ApiFailure, + * isFetching?: boolean, + * isStale?: boolean, + * isDegraded?: boolean, + * isMutationPending?: boolean, + * hasMutationConflict?: boolean + * }} AsyncSignals + */ + +/** @param {AsyncSignals} signals */ +export function deriveAsyncState(signals) { + const hasData = signals.data !== undefined && signals.data !== null; + const empty = + hasData && + ((Array.isArray(signals.data) && signals.data.length === 0) || + signals.data === ""); + + let base; + if (signals.isInitialLoading && !hasData) { + base = "initial-loading"; + } else if (signals.failure && !hasData) { + base = "terminal-error"; + } else if (empty) { + base = "empty"; + } else if (hasData) { + base = "success"; + } else { + base = "initial-loading"; + } + + const overlay = Object.freeze({ + refreshing: Boolean(signals.isFetching && hasData), + staleDegraded: Boolean(signals.isStale && signals.isDegraded && hasData), + mutationPending: Boolean(signals.isMutationPending && hasData), + mutationConflict: Boolean(signals.hasMutationConflict && hasData), + }); + + const state = { + base, + data: base === "success" || base === "empty" ? signals.data : undefined, + failure: base === "terminal-error" ? signals.failure : undefined, + overlay, + indicator: selectOverlayIndicator(overlay), + }; + + return Object.freeze(state); +} + +/** + * @param {{ + * refreshing: boolean, + * staleDegraded: boolean, + * mutationPending: boolean, + * mutationConflict: boolean + * }} overlay + */ +export function selectOverlayIndicator(overlay) { + if (overlay.mutationConflict) return "mutation-conflict"; + if (overlay.mutationPending) return "mutation-pending"; + if (overlay.staleDegraded) return "stale-degraded"; + if (overlay.refreshing) return "refreshing"; + return null; +} diff --git a/src/contracts/errors.js b/src/contracts/errors.js index ee69137f..8c0af286 100644 --- a/src/contracts/errors.js +++ b/src/contracts/errors.js @@ -9,13 +9,18 @@ const DROP_SENSITIVE = Object.freeze([ "storageValue", ]); +/** + * @typedef {"retry" | "reauth" | "navigate" | "reload-once" | + * "contact-support" | "none"} ErrorAction + */ + /** * @typedef {{ * kind: string, * defaultRetryable: boolean, * severity: string, * userMessageKey: string, - * action: string, + * action: ErrorAction, * telemetryEvent: string, * redaction: readonly string[] * }} ErrorDefinition @@ -25,7 +30,7 @@ const DROP_SENSITIVE = Object.freeze([ * @param {string} kind * @param {boolean} defaultRetryable * @param {string} severity - * @param {string} action + * @param {ErrorAction} action * @param {string} [telemetryEvent] * @returns {Readonly} */ @@ -156,7 +161,7 @@ export const ERROR_REGISTRY = Object.freeze({ * traceId?: string, * retryAfterMs?: number, * userMessageKey: string, - * action: string, + * action: ErrorAction, * causeClass?: string * }} ApiFailure */ diff --git a/src/presentation/components/async-surface.jsx b/src/presentation/components/async-surface.jsx new file mode 100644 index 00000000..06cc7358 --- /dev/null +++ b/src/presentation/components/async-surface.jsx @@ -0,0 +1,72 @@ +/** @param {{ label?: string }} props */ +export function LoadingSurface({ label = "불러오는 중" }) { + return ( +
+
+ ); +} + +/** @param {{ title?: string, action?: React.ReactNode }} props */ +export function EmptySurface({ title = "표시할 항목이 없습니다.", action }) { + return ( +
+

{title}

+ {action} +
+ ); +} + +/** + * @param {{ + * userMessageKey: string, + * action: "retry" | "reauth" | "navigate" | "reload-once" | + * "contact-support" | "none", + * onAction?: () => void + * }} props + */ +export function TerminalErrorSurface({ userMessageKey, action, onAction }) { + return ( +
+

{userMessageKey}

+ {action !== "none" && ( + + )} +
+ ); +} + +/** + * @param {{ + * state: ReturnType, + * children?: React.ReactNode, + * onAction?: () => void + * }} props + */ +export function AsyncSurface({ state, children, onAction }) { + if (state.base === "initial-loading") return ; + if (state.base === "empty") return ; + if (state.base === "terminal-error" && state.failure) { + return ( + + ); + } + + return ( +
+ {state.indicator && ( +

+ {state.indicator} +

+ )} + {children} +
+ ); +} diff --git a/tests/component/async-surface.test.jsx b/tests/component/async-surface.test.jsx new file mode 100644 index 00000000..6537b325 --- /dev/null +++ b/tests/component/async-surface.test.jsx @@ -0,0 +1,76 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +import { deriveAsyncState } from "../../src/application/view-models/async-state.js"; +import { AsyncSurface } from "../../src/presentation/components/async-surface.jsx"; +import { createFailure } from "../../src/contracts/errors.js"; + +describe("async UI state matrix", () => { + it.each([ + [{ isInitialLoading: true }, "initial-loading"], + [{ data: [{ id: "1" }] }, "success"], + [{ data: [] }, "empty"], + [ + { failure: createFailure("SERVER_FAILURE", "LIST", 0) }, + "terminal-error", + ], + ])("derives base state %#", (signals, expected) => { + expect(deriveAsyncState(signals).base).toBe(expected); + }); + + it.each([ + [{ data: ["value"], isFetching: true }, "refreshing"], + [{ data: ["value"], isStale: true, isDegraded: true }, "stale-degraded"], + [{ data: ["value"], isMutationPending: true }, "mutation-pending"], + [{ data: ["value"], hasMutationConflict: true }, "mutation-conflict"], + ])("derives overlay state %#", (signals, indicator) => { + expect(deriveAsyncState(signals).indicator).toBe(indicator); + }); + + it("uses deterministic overlay priority for crossed states", () => { + const state = deriveAsyncState({ + data: ["value"], + isFetching: true, + isMutationPending: true, + hasMutationConflict: true, + }); + expect(state.indicator).toBe("mutation-conflict"); + expect(state.overlay).toMatchObject({ + refreshing: true, + mutationPending: true, + mutationConflict: true, + }); + }); + + it("keeps content visible while a non-blocking refresh runs", () => { + const state = deriveAsyncState({ data: ["value"], isFetching: true }); + render(existing content); + + expect(screen.getByText("existing content")).toBeVisible(); + expect(screen.getByRole("status")).toHaveTextContent("refreshing"); + }); + + it("renders only safe error vocabulary", () => { + const failure = createFailure("SERVER_FAILURE", "LIST", 0, { + code: "SERVER_FAILURE", + }); + const state = deriveAsyncState({ failure }); + render(); + + expect(screen.getByRole("alert")).toHaveTextContent(failure.userMessageKey); + expect(screen.getByRole("button")).toHaveTextContent("retry"); + expect(screen.getByRole("alert")).not.toHaveTextContent("stack"); + }); + + it("does not retain a terminal error after usable data is restored", () => { + const failed = deriveAsyncState({ + failure: createFailure("SERVER_FAILURE", "LIST", 0), + }); + const recovered = deriveAsyncState({ data: ["value"] }); + expect(failed.base).toBe("terminal-error"); + expect(recovered.base).toBe("success"); + expect(recovered.failure).toBeUndefined(); + }); +}); From a9a7db0231121e908a9c47f739c955f7e2420dc9 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:02:06 +0900 Subject: [PATCH 015/178] feat: contain DTO mapping at the HTTP boundary --- src/adapters/http/client.js | 41 ++++++++++++--- src/adapters/http/resource-mapper.js | 30 +++++++++++ .../view-models/resource-view-model.js | 16 ++++++ src/domain/models/resource.js | 19 +++++++ tests/integration/http-client.test.js | 28 +++++++++- tests/unit/boundary-mapper.test.js | 52 +++++++++++++++++++ 6 files changed, 178 insertions(+), 8 deletions(-) create mode 100644 src/adapters/http/resource-mapper.js create mode 100644 src/application/view-models/resource-view-model.js create mode 100644 src/domain/models/resource.js create mode 100644 tests/unit/boundary-mapper.test.js diff --git a/src/adapters/http/client.js b/src/adapters/http/client.js index e1bc9e7c..7d0b8b2c 100644 --- a/src/adapters/http/client.js +++ b/src/adapters/http/client.js @@ -3,7 +3,9 @@ import { getApiOperation } from "../../contracts/api-operations.js"; import { createFailure as failure, kindForStatus as statusKind, + normalizeUnknownFailure, } from "../../contracts/errors.js"; +import { mapOperationPayload } from "./resource-mapper.js"; import { retryDelay, shouldRetry } from "./retry-policy.js"; import { validateEnvelope, @@ -49,6 +51,7 @@ const noAuthSession = * random?: () => number, * validatePayload?: (schemaId: string, value: unknown) => * { success: true, data: unknown } | { success: false }, + * mapPayload?: (operationId: string, payload: unknown) => unknown, * idempotencyKeyFactory?: () => string * }} dependencies */ @@ -59,6 +62,7 @@ export function createHttpClient(dependencies) { const random = dependencies.random ?? Math.random; const validatePayload = dependencies.validatePayload ?? validateOperationPayload; + const mapPayload = dependencies.mapPayload ?? mapOperationPayload; const idempotencyKeyFactory = dependencies.idempotencyKeyFactory ?? (() => crypto.randomUUID()); @@ -195,7 +199,13 @@ export function createHttpClient(dependencies) { } const response = await fetcher(request); - return await parseResponse(response, operation, attempt, validatePayload); + return await parseResponse( + response, + operation, + attempt, + validatePayload, + mapPayload, + ); } catch { if (timedOut) { return { @@ -254,9 +264,16 @@ export function createHttpClient(dependencies) { * @param {number} attempt * @param {(schemaId: string, value: unknown) => * { success: true, data: unknown } | { success: false }} validatePayload + * @param {(operationId: string, payload: unknown) => unknown} mapPayload * @returns {Promise} */ -async function parseResponse(response, operation, attempt, validatePayload) { +async function parseResponse( + response, + operation, + attempt, + validatePayload, + mapPayload, +) { const contentType = response.headers.get("content-type") ?? ""; if (!contentType.toLowerCase().includes("application/json")) { return { @@ -311,11 +328,21 @@ async function parseResponse(response, operation, attempt, validatePayload) { }; } - return { - ok: true, - value: structuredClone(payload.data), - meta: safeMeta(envelopeRecord.meta), - }; + try { + return { + ok: true, + value: mapPayload(operation.operationId, payload.data), + meta: safeMeta(envelopeRecord.meta), + }; + } catch (error) { + return { + ok: false, + error: normalizeUnknownFailure(error, { + operationId: operation.operationId, + attempt, + }), + }; + } } const kind = statusKind(response.status); diff --git a/src/adapters/http/resource-mapper.js b/src/adapters/http/resource-mapper.js new file mode 100644 index 00000000..2a8e6368 --- /dev/null +++ b/src/adapters/http/resource-mapper.js @@ -0,0 +1,30 @@ +import { createResource } from "../../domain/models/resource.js"; + +/** @param {unknown} value */ +export function mapResourceDto(value) { + if (!value || typeof value !== "object") { + throw new TypeError("Validated resource DTO is required"); + } + const dto = /** @type {Record} */ (value); + if (typeof dto.id !== "string" || typeof dto.name !== "string") { + throw new TypeError("Validated resource DTO invariants were breached"); + } + + return createResource({ + id: dto.id, + displayName: dto.name, + createdAt: typeof dto.createdAt === "string" ? dto.createdAt : null, + }); +} + +/** @param {string} operationId @param {unknown} payload */ +export function mapOperationPayload(operationId, payload) { + if (operationId === "LIST_SAMPLE_RESOURCES") { + if (!Array.isArray(payload)) throw new TypeError("Expected a resource list"); + return payload.map(mapResourceDto); + } + if (operationId === "CREATE_SAMPLE_RESOURCE") { + return mapResourceDto(payload); + } + throw new TypeError(`No boundary mapper registered for ${operationId}`); +} diff --git a/src/application/view-models/resource-view-model.js b/src/application/view-models/resource-view-model.js new file mode 100644 index 00000000..963f25d3 --- /dev/null +++ b/src/application/view-models/resource-view-model.js @@ -0,0 +1,16 @@ +/** + * @param {import("../../domain/models/resource.js").Resource} resource + * @param {(value: Date) => string} [formatDate] + */ +export function toResourceViewModel( + resource, + formatDate = (value) => new Intl.DateTimeFormat("ko-KR").format(value), +) { + return Object.freeze({ + resourceId: resource.id, + title: resource.displayName, + createdAtLabel: resource.createdAt + ? formatDate(new Date(resource.createdAt)) + : null, + }); +} diff --git a/src/domain/models/resource.js b/src/domain/models/resource.js new file mode 100644 index 00000000..7a41ed28 --- /dev/null +++ b/src/domain/models/resource.js @@ -0,0 +1,19 @@ +/** + * @typedef {{ + * id: string, + * displayName: string, + * createdAt: string | null + * }} Resource + */ + +/** @param {Resource} values @returns {Readonly} */ +export function createResource(values) { + if (!values.id || !values.displayName) { + throw new TypeError("Resource invariants require id and displayName"); + } + return Object.freeze({ + id: values.id, + displayName: values.displayName, + createdAt: values.createdAt, + }); +} diff --git a/tests/integration/http-client.test.js b/tests/integration/http-client.test.js index b3633c42..6ca66402 100644 --- a/tests/integration/http-client.test.js +++ b/tests/integration/http-client.test.js @@ -46,7 +46,7 @@ describe("shared HTTP client", () => { client.execute("LIST_SAMPLE_RESOURCES", { routeId: "SAMPLE_RESOURCE_LIST" }), ).resolves.toMatchObject({ ok: true, - value: [{ id: "resource-1" }], + value: [{ id: "resource-1", displayName: "Example" }], meta: { requestId: "request-1" }, }); expect(attempts).toBe(3); @@ -99,4 +99,30 @@ describe("shared HTTP client", () => { error: { kind: "SCHEMA_MISMATCH" }, }); }); + + it("guards mapper exceptions as UNKNOWN_FAILURE", async () => { + server.use( + http.get("https://api.test/api/sample/resources", () => + HttpResponse.json({ + success: true, + data: [{ id: "resource-1", name: "Example" }], + meta: { requestId: "request-1", traceId: "trace-1" }, + }), + ), + ); + const client = createHttpClient({ + baseUrl: "https://api.test", + clock, + mapPayload: () => { + throw new Error("raw mapper detail"); + }, + }); + + const result = await client.execute("LIST_SAMPLE_RESOURCES"); + expect(result).toMatchObject({ + ok: false, + error: { kind: "UNKNOWN_FAILURE" }, + }); + expect(JSON.stringify(result)).not.toContain("raw mapper detail"); + }); }); diff --git a/tests/unit/boundary-mapper.test.js b/tests/unit/boundary-mapper.test.js new file mode 100644 index 00000000..838b1c04 --- /dev/null +++ b/tests/unit/boundary-mapper.test.js @@ -0,0 +1,52 @@ +import { describe, expect, it } from "vitest"; + +import { + mapOperationPayload, + mapResourceDto, +} from "../../src/adapters/http/resource-mapper.js"; +import { toResourceViewModel } from "../../src/application/view-models/resource-view-model.js"; + +describe("DTO to model to view-model mapping", () => { + it("contains raw DTO names at the HTTP boundary", () => { + const model = mapResourceDto({ + id: "resource-1", + name: "Example", + createdAt: "2026-07-25T00:00:00.000Z", + backendOnly: "not propagated", + }); + + expect(model).toEqual({ + id: "resource-1", + displayName: "Example", + createdAt: "2026-07-25T00:00:00.000Z", + }); + expect(model).not.toHaveProperty("name"); + expect(model).not.toHaveProperty("backendOnly"); + }); + + it("maps operation payloads and rejects missing mappers", () => { + expect( + mapOperationPayload("LIST_SAMPLE_RESOURCES", [ + { id: "resource-1", name: "Example" }, + ]), + ).toEqual([ + { id: "resource-1", displayName: "Example", createdAt: null }, + ]); + expect(() => mapOperationPayload("UNKNOWN", {})).toThrow( + "No boundary mapper registered", + ); + }); + + it("projects an application-owned render-ready shape", () => { + const model = mapResourceDto({ + id: "resource-1", + name: "Example", + createdAt: null, + }); + expect(toResourceViewModel(model)).toEqual({ + resourceId: "resource-1", + title: "Example", + createdAtLabel: null, + }); + }); +}); From b221453c154a8ce8c8030da2909de42d9d12552e Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:03:57 +0900 Subject: [PATCH 016/178] feat: centralize routes and navigation guards --- package.json | 1 + pnpm-lock.yaml | 39 ++++++++++ src/bootstrap/main.jsx | 17 ++--- src/contracts/routes.js | 63 ++++++++++++++++ src/presentation/routes/app-router.jsx | 79 ++++++++++++++++++++ src/presentation/routes/navigation-policy.js | 37 +++++++++ tests/component/router.test.jsx | 24 ++++++ tests/unit/navigation-policy.test.js | 68 +++++++++++++++++ 8 files changed, 317 insertions(+), 11 deletions(-) create mode 100644 src/contracts/routes.js create mode 100644 src/presentation/routes/app-router.jsx create mode 100644 src/presentation/routes/navigation-policy.js create mode 100644 tests/component/router.test.jsx create mode 100644 tests/unit/navigation-policy.test.js diff --git a/package.json b/package.json index 0ca4c81a..6d90f533 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "@tanstack/react-query": "5.101.4", "react": "19.2.8", "react-dom": "19.2.8", + "react-router-dom": "7.18.1", "zod": "4.4.3" }, "devDependencies": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index edec4217..d1f273ed 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,6 +17,9 @@ importers: react-dom: specifier: 19.2.8 version: 19.2.8(react@19.2.8) + react-router-dom: + specifier: 7.18.1 + version: 7.18.1(react-dom@19.2.8(react@19.2.8))(react@19.2.8) zod: specifier: 4.4.3 version: 4.4.3 @@ -1260,6 +1263,23 @@ packages: react-is@17.0.2: resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==} + react-router-dom@7.18.1: + resolution: {integrity: sha512-KaZh+X/6UtEp28x51AUYZDMg9NGoz2ja3dNHa+ta/tk40vCzKhQ/RypCWBMLbmDr6//E24Vv5uPsrqXFozdkAg==} + engines: {node: '>=20.0.0'} + peerDependencies: + react: '>=18' + react-dom: '>=18' + + react-router@7.18.1: + resolution: {integrity: sha512-GDLgg3i3uM0aeJO3Fm+TCS+sDQ7gu12T6x0qdTEzcwqEfleci7JwugVNIF3U//0FWKnJT7ptG+20B2jfDqnZAg==} + engines: {node: '>=20.0.0'} + peerDependencies: + react: '>=18' + react-dom: '>=18' + peerDependenciesMeta: + react-dom: + optional: true + react@19.2.8: resolution: {integrity: sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==} engines: {node: '>=0.10.0'} @@ -1312,6 +1332,9 @@ packages: engines: {node: '>=10'} hasBin: true + set-cookie-parser@2.7.2: + resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==} + set-cookie-parser@3.1.2: resolution: {integrity: sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw==} @@ -2604,6 +2627,20 @@ snapshots: react-is@17.0.2: {} + react-router-dom@7.18.1(react-dom@19.2.8(react@19.2.8))(react@19.2.8): + dependencies: + react: 19.2.8 + react-dom: 19.2.8(react@19.2.8) + react-router: 7.18.1(react-dom@19.2.8(react@19.2.8))(react@19.2.8) + + react-router@7.18.1(react-dom@19.2.8(react@19.2.8))(react@19.2.8): + dependencies: + cookie: 1.1.1 + react: 19.2.8 + set-cookie-parser: 2.7.2 + optionalDependencies: + react-dom: 19.2.8(react@19.2.8) + react@19.2.8: {} rechoir@0.8.0: @@ -2663,6 +2700,8 @@ snapshots: semver@7.8.5: {} + set-cookie-parser@2.7.2: {} + set-cookie-parser@3.1.2: {} shebang-command@2.0.0: diff --git a/src/bootstrap/main.jsx b/src/bootstrap/main.jsx index 5d40e930..79d45aaf 100644 --- a/src/bootstrap/main.jsx +++ b/src/bootstrap/main.jsx @@ -1,18 +1,10 @@ import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; +import { createAnonymousSessionAdapter } from "../adapters/auth/external-session-adapter.js"; +import { AppRouter } from "../presentation/routes/app-router.jsx"; import { BootConfigError, loadRuntimeConfig } from "./load-runtime-config.js"; -/** @param {{ environment: string }} props */ -function BootstrapShell({ environment }) { - return ( -
-

Clean Architecture Frontend

-

{environment} 런타임 계약이 검증되었습니다.

-
- ); -} - /** @param {{ supportReference: string }} props */ function BootErrorShell({ supportReference }) { return ( @@ -36,7 +28,10 @@ async function boot() { const runtime = await loadRuntimeConfig(); root.render( - + , ); } catch (error) { diff --git a/src/contracts/routes.js b/src/contracts/routes.js new file mode 100644 index 00000000..e4ad7737 --- /dev/null +++ b/src/contracts/routes.js @@ -0,0 +1,63 @@ +/** + * @typedef {{ + * routeId: string, + * path: string, + * paramsSchema: string | null, + * searchSchema: string | null, + * access: "public" | "session-required" | "integration-defined", + * loadingSurface: string, + * errorSurface: string, + * chunkId: string + * }} RouteDefinition + */ + +/** @param {RouteDefinition} definition */ +const route = (definition) => Object.freeze(definition); + +export const ROUTE_REGISTRY = Object.freeze({ + APP_HOME: route({ + routeId: "APP_HOME", + path: "/", + paramsSchema: null, + searchSchema: null, + access: "public", + loadingSurface: "app-shell", + errorSurface: "route-boundary", + chunkId: "route-home", + }), + SAMPLE_RESOURCE_LIST: route({ + routeId: "SAMPLE_RESOURCE_LIST", + path: "/sample/resources", + paramsSchema: null, + searchSchema: "SampleResourceListQuery", + access: "integration-defined", + loadingSurface: "sample-resource-list", + errorSurface: "feature-boundary", + chunkId: "route-sample-resources", + }), + NOT_FOUND: route({ + routeId: "NOT_FOUND", + path: "*", + paramsSchema: null, + searchSchema: null, + access: "public", + loadingSurface: "none", + errorSurface: "not-found", + chunkId: "route-not-found", + }), +}); + +/** @param {string} routeId */ +export function getRoute(routeId) { + const registry = /** @type {Record>} */ ( + ROUTE_REGISTRY + ); + const selected = registry[routeId]; + if (!selected) throw new Error(`Unregistered route: ${routeId}`); + return selected; +} + +/** @param {string} routeId */ +export function routePath(routeId) { + return getRoute(routeId).path; +} diff --git a/src/presentation/routes/app-router.jsx b/src/presentation/routes/app-router.jsx new file mode 100644 index 00000000..9157260c --- /dev/null +++ b/src/presentation/routes/app-router.jsx @@ -0,0 +1,79 @@ +import { + BrowserRouter, + Link, + Route, + Routes, +} from "react-router-dom"; + +import { routePath } from "../../contracts/routes.js"; +import { decideRouteAccess } from "./navigation-policy.js"; + +function HomePage() { + return ( +
+

Clean Architecture Frontend

+

런타임 계약이 검증되었습니다.

+ 샘플 리소스 +
+ ); +} + +function SamplePlaceholder() { + return ( +
+

샘플 리소스

+

계약 fixture를 준비하고 있습니다.

+
+ ); +} + +function NotFoundPage() { + return ( +
+

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

+ 홈으로 이동 +
+ ); +} + +/** + * @param {{ + * authSession: import("../../application/ports/auth-session-port.js").AuthSessionPort + * }} props + */ +function GuardedSampleRoute({ authSession }) { + const decision = decideRouteAccess( + "SAMPLE_RESOURCE_LIST", + authSession.getState(), + ); + if (!decision.allowed) { + return ( +
+

세션이 필요합니다.

+ +
+ ); + } + return ; +} + +/** + * @param {{ + * authSession: import("../../application/ports/auth-session-port.js").AuthSessionPort, + * basename?: string + * }} props + */ +export function AppRouter({ authSession, basename = "/" }) { + return ( + + + } /> + } + /> + } /> + + + ); +} diff --git a/src/presentation/routes/navigation-policy.js b/src/presentation/routes/navigation-policy.js new file mode 100644 index 00000000..9fa51333 --- /dev/null +++ b/src/presentation/routes/navigation-policy.js @@ -0,0 +1,37 @@ +import { getRoute } from "../../contracts/routes.js"; + +/** + * @param {string} routeId + * @param {import("../../application/ports/auth-session-port.js").SessionState} sessionState + */ +export function decideRouteAccess(routeId, sessionState) { + const route = getRoute(routeId); + if (route.access === "public") return { allowed: true, action: "none" }; + if (sessionState === "authenticated") { + return { allowed: true, action: "none" }; + } + if (sessionState === "recovery-pending") { + return { allowed: false, action: "wait-for-session" }; + } + return { allowed: false, action: "show-sign-in" }; +} + +export function createRedirectLoopGuard() { + const visitedPairs = new Set(); + + return Object.freeze({ + /** + * @param {string} source + * @param {string} target + */ + allow(source, target) { + const pair = `${source}->${target}`; + if (source === target || visitedPairs.has(pair)) return false; + visitedPairs.add(pair); + return true; + }, + reset() { + visitedPairs.clear(); + }, + }); +} diff --git a/tests/component/router.test.jsx b/tests/component/router.test.jsx new file mode 100644 index 00000000..e253c638 --- /dev/null +++ b/tests/component/router.test.jsx @@ -0,0 +1,24 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.js"; +import { AppRouter } from "../../src/presentation/routes/app-router.jsx"; + +describe("application router", () => { + it("renders not-found without making an API request", () => { + window.history.pushState({}, "", "/missing"); + render(); + expect( + screen.getByRole("heading", { name: "페이지를 찾을 수 없습니다." }), + ).toBeVisible(); + }); + + it("shows session-required UX without claiming authorization", () => { + window.history.pushState({}, "", "/sample/resources"); + render(); + expect(screen.getByRole("heading", { name: "세션이 필요합니다." })).toBeVisible(); + expect(screen.getByRole("button", { name: "로그인" })).toBeVisible(); + }); +}); diff --git a/tests/unit/navigation-policy.test.js b/tests/unit/navigation-policy.test.js new file mode 100644 index 00000000..fa61faea --- /dev/null +++ b/tests/unit/navigation-policy.test.js @@ -0,0 +1,68 @@ +import { describe, expect, it } from "vitest"; + +import { + createRedirectLoopGuard, + decideRouteAccess, +} from "../../src/presentation/routes/navigation-policy.js"; +import { ROUTE_REGISTRY } from "../../src/contracts/routes.js"; + +describe("route registry", () => { + it("matches the stable registry snapshot", () => { + expect(ROUTE_REGISTRY).toMatchInlineSnapshot(` + { + "APP_HOME": { + "access": "public", + "chunkId": "route-home", + "errorSurface": "route-boundary", + "loadingSurface": "app-shell", + "paramsSchema": null, + "path": "/", + "routeId": "APP_HOME", + "searchSchema": null, + }, + "NOT_FOUND": { + "access": "public", + "chunkId": "route-not-found", + "errorSurface": "not-found", + "loadingSurface": "none", + "paramsSchema": null, + "path": "*", + "routeId": "NOT_FOUND", + "searchSchema": null, + }, + "SAMPLE_RESOURCE_LIST": { + "access": "integration-defined", + "chunkId": "route-sample-resources", + "errorSurface": "feature-boundary", + "loadingSurface": "sample-resource-list", + "paramsSchema": null, + "path": "/sample/resources", + "routeId": "SAMPLE_RESOURCE_LIST", + "searchSchema": "SampleResourceListQuery", + }, + } + `); + }); + + it("treats client access as a UX hint, not authorization", () => { + expect(decideRouteAccess("APP_HOME", "unauthenticated")).toEqual({ + allowed: true, + action: "none", + }); + expect(decideRouteAccess("SAMPLE_RESOURCE_LIST", "unauthenticated")).toEqual({ + allowed: false, + action: "show-sign-in", + }); + expect(decideRouteAccess("SAMPLE_RESOURCE_LIST", "authenticated")).toEqual({ + allowed: true, + action: "none", + }); + }); + + it("allows at most one automatic redirect per source-target pair", () => { + const guard = createRedirectLoopGuard(); + expect(guard.allow("/private", "/signin")).toBe(true); + expect(guard.allow("/private", "/signin")).toBe(false); + expect(guard.allow("/signin", "/signin")).toBe(false); + }); +}); From c37d571eb398cf5d2495618e5e1f3853f89a9f15 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:05:36 +0900 Subject: [PATCH 017/178] feat: add layered render recovery boundaries --- .../use-cases/decide-chunk-recovery.js | 34 ++++++++ src/bootstrap/main.jsx | 19 ++-- .../boundaries/boot-error-shell.jsx | 49 +++++++++++ .../boundaries/render-error-boundary.jsx | 68 +++++++++++++++ tests/component/render-boundary.test.jsx | 87 +++++++++++++++++++ tests/unit/chunk-recovery.test.js | 52 +++++++++++ 6 files changed, 295 insertions(+), 14 deletions(-) create mode 100644 src/application/use-cases/decide-chunk-recovery.js create mode 100644 src/presentation/boundaries/boot-error-shell.jsx create mode 100644 src/presentation/boundaries/render-error-boundary.jsx create mode 100644 tests/component/render-boundary.test.jsx create mode 100644 tests/unit/chunk-recovery.test.js diff --git a/src/application/use-cases/decide-chunk-recovery.js b/src/application/use-cases/decide-chunk-recovery.js new file mode 100644 index 00000000..a2db87e0 --- /dev/null +++ b/src/application/use-cases/decide-chunk-recovery.js @@ -0,0 +1,34 @@ +const RECOVERABLE_KINDS = new Set(["CHUNK_LOAD_FAILURE", "DEPLOY_MISMATCH"]); + +/** + * @param {{ + * failureKind: string, + * manifestLoaded: boolean, + * currentBuildId: string, + * activeReleaseId: string, + * storage: import("../ports/storage-port.js").StoragePort + * }} input + */ +export function decideChunkRecovery(input) { + if (!RECOVERABLE_KINDS.has(input.failureKind)) { + return { action: "support", reason: "not-recoverable" }; + } + if (!input.manifestLoaded) { + return { action: "support", reason: "manifest-unavailable" }; + } + if (input.activeReleaseId === input.currentBuildId) { + return { action: "support", reason: "same-release" }; + } + + const releasePair = `${input.currentBuildId}->${input.activeReleaseId}`; + const guard = input.storage.read("CHUNK_RELOAD_GUARD"); + if (!guard.ok || guard.value === releasePair) { + return { action: "support", reason: "reload-already-attempted" }; + } + + const recorded = input.storage.write("CHUNK_RELOAD_GUARD", releasePair); + if (!recorded.ok) { + return { action: "support", reason: "guard-write-failed" }; + } + return { action: "reload-once", releasePair }; +} diff --git a/src/bootstrap/main.jsx b/src/bootstrap/main.jsx index 79d45aaf..78469b59 100644 --- a/src/bootstrap/main.jsx +++ b/src/bootstrap/main.jsx @@ -2,19 +2,10 @@ import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { createAnonymousSessionAdapter } from "../adapters/auth/external-session-adapter.js"; +import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.jsx"; import { AppRouter } from "../presentation/routes/app-router.jsx"; import { BootConfigError, loadRuntimeConfig } from "./load-runtime-config.js"; -/** @param {{ supportReference: string }} props */ -function BootErrorShell({ supportReference }) { - return ( -
-

애플리케이션을 시작할 수 없습니다.

-

지원 참조: {supportReference}

-
- ); -} - const rootElement = document.getElementById("root"); if (!rootElement) { @@ -35,12 +26,12 @@ async function boot() { , ); } catch (error) { - const supportReference = + const safe = error instanceof BootConfigError - ? error.safe.supportReference - : "boot:unknown"; + ? error.safe + : { supportReference: "boot:unknown" }; - root.render(); + root.render(); } } diff --git a/src/presentation/boundaries/boot-error-shell.jsx b/src/presentation/boundaries/boot-error-shell.jsx new file mode 100644 index 00000000..f2aaf782 --- /dev/null +++ b/src/presentation/boundaries/boot-error-shell.jsx @@ -0,0 +1,49 @@ +/** + * @param {{ + * kind?: string, + * code?: string, + * buildId?: string, + * configSchemaVersion?: string, + * releaseId?: string, + * supportReference: string + * }} props + */ +export function BootErrorShell({ + kind = "BOOT_CONFIG_FAILURE", + code = "BOOT_FAILED", + buildId, + configSchemaVersion, + releaseId, + supportReference, +}) { + return ( +
+

애플리케이션을 시작할 수 없습니다.

+
+
오류
+
{kind}
+
코드
+
{code}
+ {buildId && ( + <> +
빌드
+
{buildId}
+ + )} + {configSchemaVersion && ( + <> +
설정 스키마
+
{configSchemaVersion}
+ + )} + {releaseId && ( + <> +
릴리스
+
{releaseId}
+ + )} +
+

지원 참조: {supportReference}

+
+ ); +} diff --git a/src/presentation/boundaries/render-error-boundary.jsx b/src/presentation/boundaries/render-error-boundary.jsx new file mode 100644 index 00000000..de3872d5 --- /dev/null +++ b/src/presentation/boundaries/render-error-boundary.jsx @@ -0,0 +1,68 @@ +import { Component } from "react"; + +/** + * @typedef {{ + * children: React.ReactNode, + * boundaryName: string, + * routeId: string, + * buildId: string, + * telemetry?: import("../../application/ports/telemetry-port.js").TelemetryPort, + * fallback?: React.ReactNode + * }} RenderBoundaryProps + * @typedef {{ hasError: boolean }} RenderBoundaryState + */ + +/** @extends {Component} */ +export class RenderErrorBoundary extends Component { + /** @param {RenderBoundaryProps} props */ + constructor(props) { + super(props); + this.state = { hasError: false }; + } + + static getDerivedStateFromError() { + return { hasError: true }; + } + + componentDidCatch() { + try { + this.props.telemetry?.emit("ui.render.failed", { + route_id: this.props.routeId, + build_id: this.props.buildId, + component_boundary: this.props.boundaryName, + }); + } catch { + // Telemetry must never recurse into another render failure. + } + } + + reset = () => { + this.setState({ hasError: false }); + }; + + render() { + if (this.state.hasError) { + return ( + this.props.fallback ?? ( +
+

error.render_failure

+ +
+ ) + ); + } + return this.props.children; + } +} + +/** @param {Omit} props */ +export function RouteBoundary(props) { + return ; +} + +/** @param {Omit} props */ +export function FeatureBoundary(props) { + return ; +} diff --git a/tests/component/render-boundary.test.jsx b/tests/component/render-boundary.test.jsx new file mode 100644 index 00000000..d61a43ec --- /dev/null +++ b/tests/component/render-boundary.test.jsx @@ -0,0 +1,87 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, expect, it, vi } from "vitest"; + +import { createFailure } from "../../src/contracts/errors.js"; +import { deriveAsyncState } from "../../src/application/view-models/async-state.js"; +import { AsyncSurface } from "../../src/presentation/components/async-surface.jsx"; +import { BootErrorShell } from "../../src/presentation/boundaries/boot-error-shell.jsx"; +import { FeatureBoundary } from "../../src/presentation/boundaries/render-error-boundary.jsx"; + +function Defect() { + throw new Error("raw render stack"); +} + +describe("render recovery boundaries", () => { + it("catches programmer defects and emits best-effort safe telemetry", () => { + const telemetry = { emit: vi.fn() }; + render( + + + , + ); + + expect(screen.getByRole("alert")).toHaveTextContent("error.render_failure"); + expect(telemetry.emit).toHaveBeenCalledWith("ui.render.failed", { + route_id: "APP_HOME", + build_id: "build-a", + component_boundary: "feature", + }); + }); + + it("keeps normalized operational failures in normal async state", () => { + const state = deriveAsyncState({ + failure: createFailure("SERVER_FAILURE", "LIST", 0), + }); + render( + + + , + ); + expect(screen.getByRole("alert")).toHaveTextContent("error.server_failure"); + }); + + it("renders a safe boot shell with no endpoint or stack", () => { + render( + , + ); + const shell = screen.getByRole("alert"); + expect(shell).toHaveTextContent("build-a:CONFIG_SCHEMA_INVALID"); + expect(shell).not.toHaveTextContent("https://"); + expect(shell).not.toHaveTextContent("stack"); + }); + + it("allows a boundary reset action without reloading the page", async () => { + let shouldThrow = true; + function Recoverable() { + if (shouldThrow) throw new Error("defect"); + return

recovered

; + } + const user = userEvent.setup(); + const view = render( + + + , + ); + shouldThrow = false; + await user.click(screen.getByRole("button", { name: "retry" })); + view.rerender( + + + , + ); + expect(screen.getByText("recovered")).toBeVisible(); + }); +}); diff --git a/tests/unit/chunk-recovery.test.js b/tests/unit/chunk-recovery.test.js new file mode 100644 index 00000000..41fd3abe --- /dev/null +++ b/tests/unit/chunk-recovery.test.js @@ -0,0 +1,52 @@ +import { describe, expect, it } from "vitest"; + +import { decideChunkRecovery } from "../../src/application/use-cases/decide-chunk-recovery.js"; + +function memoryStorage() { + let value; + return { + read: () => ({ ok: true, value }), + write: (_key, next) => { + value = next; + return { ok: true }; + }, + remove: () => ({ ok: true }), + }; +} + +describe("controlled chunk recovery", () => { + it("records the release pair before allowing one reload", () => { + const storage = memoryStorage(); + const input = { + failureKind: "CHUNK_LOAD_FAILURE", + manifestLoaded: true, + currentBuildId: "build-a", + activeReleaseId: "release-b", + storage, + }; + expect(decideChunkRecovery(input)).toEqual({ + action: "reload-once", + releasePair: "build-a->release-b", + }); + expect(decideChunkRecovery(input)).toEqual({ + action: "support", + reason: "reload-already-attempted", + }); + }); + + it.each([ + [{ failureKind: "SERVER_FAILURE" }, "not-recoverable"], + [{ manifestLoaded: false }, "manifest-unavailable"], + [{ activeReleaseId: "build-a" }, "same-release"], + ])("stops when a recovery invariant fails: %#", (override, reason) => { + const result = decideChunkRecovery({ + failureKind: "DEPLOY_MISMATCH", + manifestLoaded: true, + currentBuildId: "build-a", + activeReleaseId: "release-b", + storage: memoryStorage(), + ...override, + }); + expect(result).toEqual({ action: "support", reason }); + }); +}); From c6b7a9b9bc657c04d6b740b43f5372db426a7261 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:07:48 +0900 Subject: [PATCH 018/178] feat: add removable sample vertical contract fixture --- .gitignore | 1 + package.json | 1 + scripts/test-sample-removal.mjs | 77 +++++++++++++++++++ src/sample/contract-fixture/sample-facade.js | 53 +++++++++++++ .../contract-fixture/sample-resource-page.jsx | 61 +++++++++++++++ tests/component/sample-resource-page.test.jsx | 49 ++++++++++++ .../integration/sample-vertical-slice.test.js | 53 +++++++++++++ 7 files changed, 295 insertions(+) create mode 100644 scripts/test-sample-removal.mjs create mode 100644 src/sample/contract-fixture/sample-facade.js create mode 100644 src/sample/contract-fixture/sample-resource-page.jsx create mode 100644 tests/component/sample-resource-page.test.jsx create mode 100644 tests/integration/sample-vertical-slice.test.js diff --git a/.gitignore b/.gitignore index b25eba7f..f2b1e121 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ node_modules/ dist/ .vite/ +.tmp/ playwright-report/ test-results/ coverage/ diff --git a/package.json b/package.json index 6d90f533..982deb5e 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,7 @@ "test:integration": "vitest run tests/integration --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/integration.xml", "test:e2e": "playwright test", "test:a11y": "playwright test --grep @a11y", + "test:sample-removal": "node scripts/test-sample-removal.mjs", "test:all": "pnpm test:runtime-schema && pnpm test:unit && pnpm test:component && pnpm test:integration" }, "dependencies": { diff --git a/scripts/test-sample-removal.mjs b/scripts/test-sample-removal.mjs new file mode 100644 index 00000000..13b0d0f7 --- /dev/null +++ b/scripts/test-sample-removal.mjs @@ -0,0 +1,77 @@ +import { cp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { spawnSync } from "node:child_process"; +import path from "node:path"; + +const fixtureRoot = path.resolve(".tmp/sample-removal"); +const sampleRoot = path.resolve("src/sample/contract-fixture"); +const sourceRoot = path.resolve("src"); +const pnpmCli = /** @type {string} */ (process.env.npm_execpath); + +/** @param {string} directory @returns {Promise} */ +async function sourceFiles(directory) { + const entries = await readdir(directory, { withFileTypes: true }); + const nested = /** @type {string[][]} */ (await Promise.all( + entries.map((entry) => { + const target = path.join(directory, entry.name); + return entry.isDirectory() ? sourceFiles(target) : [target]; + }), + )); + return nested.flat(); +} + +await rm(fixtureRoot, { recursive: true, force: true }); +await mkdir(fixtureRoot, { recursive: true }); + +const incomingImports = []; +for (const sourceFile of await sourceFiles(sourceRoot)) { + if (sourceFile.startsWith(sampleRoot)) continue; + const content = await readFile(sourceFile, "utf8"); + if (/from\s+["'][^"']*sample\/contract-fixture/.test(content)) { + incomingImports.push(path.relative(".", sourceFile)); + } +} + +let buildStatus = 1; +if (incomingImports.length === 0) { + await cp("src", path.join(fixtureRoot, "src"), { + recursive: true, + filter: (source) => !source.startsWith(sampleRoot), + }); + await cp("public", path.join(fixtureRoot, "public"), { recursive: true }); + await cp("index.html", path.join(fixtureRoot, "index.html")); + + const result = spawnSync( + process.execPath, + [ + pnpmCli, + "exec", + "vite", + "build", + fixtureRoot, + "--outDir", + path.join(fixtureRoot, "dist"), + ], + { stdio: "inherit" }, + ); + buildStatus = result.status ?? 1; +} + +await mkdir("artifacts/tests", { recursive: true }); +const passed = incomingImports.length === 0 && buildStatus === 0; +await writeFile( + "artifacts/tests/sample-removal.xml", + `\n` + + `` + + `` + + `${passed ? "" : ""}` + + `\n`, +); +await rm(fixtureRoot, { recursive: true, force: true }); + +if (!passed) { + process.stderr.write( + `Sample removal failed. Incoming imports: ${incomingImports.join(", ")}\n`, + ); + process.exit(1); +} +process.stdout.write("Sample removal smoke: PASS\n"); diff --git a/src/sample/contract-fixture/sample-facade.js b/src/sample/contract-fixture/sample-facade.js new file mode 100644 index 00000000..62f45389 --- /dev/null +++ b/src/sample/contract-fixture/sample-facade.js @@ -0,0 +1,53 @@ +import { toResourceViewModel } from "../../application/view-models/resource-view-model.js"; +import { queryKeys } from "../../contracts/query-keys.js"; + +/** + * @param {{ + * http: { execute(operationId: string, input?: Record): Promise< + * {ok: true, value: unknown} | {ok: false, error: import("../../contracts/errors.js").ApiFailure} + * > }, + * cache: import("../../application/ports/query-cache-port.js").QueryCachePort + * }} ports + */ +export function createSampleFacade(ports) { + return Object.freeze({ + async listResources(filters = {}) { + const key = queryKeys.resource.list(filters); + const result = await ports.http.execute("LIST_SAMPLE_RESOURCES", { + routeId: "SAMPLE_RESOURCE_LIST", + }); + if (!result.ok) return result; + + const models = + /** @type {Array} */ ( + result.value + ); + const cached = ports.cache.write(key, models); + if (!cached.ok) return cached; + return { + ok: /** @type {true} */ (true), + value: models.map((model) => toResourceViewModel(model)), + }; + }, + + /** @param {{ name: string }} command */ + async createResource(command) { + const result = await ports.http.execute("CREATE_SAMPLE_RESOURCE", { + body: command, + routeId: "SAMPLE_RESOURCE_LIST", + }); + if (!result.ok) return result; + + const invalidated = await ports.cache.invalidate(queryKeys.resource.all()); + if (!invalidated.ok) return invalidated; + return { + ok: /** @type {true} */ (true), + value: toResourceViewModel( + /** @type {import("../../domain/models/resource.js").Resource} */ ( + result.value + ), + ), + }; + }, + }); +} diff --git a/src/sample/contract-fixture/sample-resource-page.jsx b/src/sample/contract-fixture/sample-resource-page.jsx new file mode 100644 index 00000000..6ace8ca7 --- /dev/null +++ b/src/sample/contract-fixture/sample-resource-page.jsx @@ -0,0 +1,61 @@ +import { useEffect, useState } from "react"; + +import { deriveAsyncState } from "../../application/view-models/async-state.js"; +import { AsyncSurface } from "../../presentation/components/async-surface.jsx"; + +/** + * @typedef {{ + * loading: boolean, + * resources?: Array<{resourceId: string, title: string, createdAtLabel: string | null}>, + * failure?: import("../../contracts/errors.js").ApiFailure + * }} SamplePageState + */ + +/** + * @param {{ + * facade: ReturnType + * }} props + */ +export function SampleResourcePage({ facade }) { + const [result, setResult] = useState( + /** @type {SamplePageState} */ ({ + loading: true, + resources: undefined, + failure: undefined, + }), + ); + + useEffect(() => { + let active = true; + void facade.listResources().then((outcome) => { + if (!active) return; + setResult( + outcome.ok + ? { loading: false, resources: outcome.value, failure: undefined } + : { loading: false, resources: undefined, failure: outcome.error }, + ); + }); + return () => { + active = false; + }; + }, [facade]); + + const state = deriveAsyncState({ + isInitialLoading: result.loading, + data: result.resources, + failure: result.failure, + }); + + return ( +
+

샘플 리소스

+ +
    + {(result.resources ?? []).map((resource) => ( +
  • {resource.title}
  • + ))} +
+
+
+ ); +} diff --git a/tests/component/sample-resource-page.test.jsx b/tests/component/sample-resource-page.test.jsx new file mode 100644 index 00000000..34d83bb2 --- /dev/null +++ b/tests/component/sample-resource-page.test.jsx @@ -0,0 +1,49 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +import { SampleResourcePage } from "../../src/sample/contract-fixture/sample-resource-page.jsx"; + +describe("removable sample feature page", () => { + it("renders the API-to-view-model result through AsyncSurface", async () => { + const facade = { + listResources: async () => ({ + ok: true, + value: [ + { + resourceId: "resource-1", + title: "Example", + createdAtLabel: null, + }, + ], + }), + createResource: async () => ({ ok: true, value: {} }), + }; + render(); + + expect(screen.getByLabelText("불러오는 중")).toBeVisible(); + expect(await screen.findByText("Example")).toBeVisible(); + }); + + it("renders normalized terminal errors without raw DTO fields", async () => { + const facade = { + listResources: async () => ({ + ok: false, + error: { + kind: "SERVER_FAILURE", + code: "SERVER_FAILURE", + retryable: true, + operationId: "LIST_SAMPLE_RESOURCES", + attemptCount: 1, + userMessageKey: "error.server_failure", + action: "retry", + }, + }), + createResource: async () => ({ ok: true, value: {} }), + }; + render(); + + expect(await screen.findByRole("alert")).toHaveTextContent("error.server_failure"); + }); +}); diff --git a/tests/integration/sample-vertical-slice.test.js b/tests/integration/sample-vertical-slice.test.js new file mode 100644 index 00000000..414ac28a --- /dev/null +++ b/tests/integration/sample-vertical-slice.test.js @@ -0,0 +1,53 @@ +import { HttpResponse, http } from "msw"; +import { setupServer } from "msw/node"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +import { createHttpClient } from "../../src/adapters/http/client.js"; +import { + createQueryCacheAdapter, + createQueryClient, +} from "../../src/adapters/query-cache/tanstack-query-cache.js"; +import { queryKeys } from "../../src/contracts/query-keys.js"; +import { createSampleFacade } from "../../src/sample/contract-fixture/sample-facade.js"; + +const server = setupServer( + http.get("https://api.test/api/sample/resources", () => + HttpResponse.json({ + success: true, + data: [{ id: "resource-1", name: "Example" }], + meta: { requestId: "request-1", traceId: "trace-1" }, + }), + ), +); + +beforeAll(() => server.listen({ onUnhandledRequest: "error" })); +afterAll(() => server.close()); + +describe("sample vertical contract fixture", () => { + it("traverses API, schema, mapper, application facade, and cache", async () => { + const queryClient = createQueryClient(); + const cache = createQueryCacheAdapter(queryClient); + const facade = createSampleFacade({ + http: createHttpClient({ + baseUrl: "https://api.test", + clock: { now: () => 0, sleep: async () => {} }, + }), + cache, + }); + + await expect(facade.listResources()).resolves.toEqual({ + ok: true, + value: [ + { + resourceId: "resource-1", + title: "Example", + createdAtLabel: null, + }, + ], + }); + expect(cache.read(queryKeys.resource.list({}))).toMatchObject({ + ok: true, + value: [{ id: "resource-1", displayName: "Example" }], + }); + }); +}); From 9a92c117929322ab5cfe8b5b5c5cadbb079e85b0 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:09:07 +0900 Subject: [PATCH 019/178] feat: add Tailwind semantic design tokens --- docs/styling/design-tokens.md | 17 + package.json | 2 + pnpm-lock.yaml | 373 +++++++++++++++++- scripts/test-sample-removal.mjs | 1 + src/bootstrap/main.jsx | 1 + src/presentation/components/async-surface.jsx | 10 +- src/presentation/routes/app-router.jsx | 12 +- src/presentation/styles/theme.css | 71 ++++ .../design-token-showcase.jsx | 15 + tests/component/design-tokens.test.jsx | 14 + vite.config.js | 3 +- 11 files changed, 491 insertions(+), 28 deletions(-) create mode 100644 docs/styling/design-tokens.md create mode 100644 src/presentation/styles/theme.css create mode 100644 src/sample/contract-fixture/design-token-showcase.jsx create mode 100644 tests/component/design-tokens.test.jsx diff --git a/docs/styling/design-tokens.md b/docs/styling/design-tokens.md new file mode 100644 index 00000000..2de05b5c --- /dev/null +++ b/docs/styling/design-tokens.md @@ -0,0 +1,17 @@ +# Design-token styling contract + +`src/presentation/styles/theme.css` is the styling SSOT. Components consume +semantic color, spacing, typography, and radius tokens through static Tailwind +classes. + +Arbitrary-value policy: + +- prefer a named semantic token +- bracket values are allowed only for one-off platform constraints that cannot + be expressed by the current scale +- a repeated bracket value must be promoted into `@theme` +- user-controlled or runtime-composed class strings are forbidden +- class variants must be selected from a closed static map + +The removable sample may demonstrate tokens, but product modules must not +import from `src/sample/contract-fixture`. diff --git a/package.json b/package.json index 982deb5e..26e87572 100644 --- a/package.json +++ b/package.json @@ -39,6 +39,7 @@ "@testing-library/jest-dom": "7.0.0", "@testing-library/react": "16.3.2", "@testing-library/user-event": "14.6.1", + "@tailwindcss/vite": "4.3.3", "@types/node": "24.13.3", "@types/react": "19.2.8", "@types/react-dom": "19.2.3", @@ -48,6 +49,7 @@ "globals": "17.7.0", "jsdom": "29.1.1", "msw": "2.15.0", + "tailwindcss": "4.3.3", "typescript": "7.0.2", "vite": "8.1.5", "vitest": "4.1.10" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d1f273ed..1069817e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -29,10 +29,13 @@ importers: version: 4.12.1(playwright-core@1.62.0) '@eslint/js': specifier: 10.0.1 - version: 10.0.1(eslint@10.8.0(supports-color@7.2.0)) + version: 10.0.1(eslint@10.8.0(jiti@2.7.0)(supports-color@7.2.0)) '@playwright/test': specifier: 1.62.0 version: 1.62.0 + '@tailwindcss/vite': + specifier: 4.3.3 + version: 4.3.3(vite@8.1.5(@types/node@24.13.3)(jiti@2.7.0)) '@testing-library/jest-dom': specifier: 7.0.0 version: 7.0.0(@testing-library/dom@10.4.1) @@ -53,13 +56,13 @@ importers: version: 19.2.3(@types/react@19.2.8) '@vitejs/plugin-react': specifier: 6.0.4 - version: 6.0.4(vite@8.1.5(@types/node@24.13.3)) + version: 6.0.4(vite@8.1.5(@types/node@24.13.3)(jiti@2.7.0)) dependency-cruiser: specifier: 18.1.0 version: 18.1.0 eslint: specifier: 10.8.0 - version: 10.8.0(supports-color@7.2.0) + version: 10.8.0(jiti@2.7.0)(supports-color@7.2.0) globals: specifier: 17.7.0 version: 17.7.0 @@ -69,15 +72,18 @@ importers: msw: specifier: 2.15.0 version: 2.15.0(@types/node@24.13.3)(typescript@7.0.2) + tailwindcss: + specifier: 4.3.3 + version: 4.3.3 typescript: specifier: 7.0.2 version: 7.0.2 vite: specifier: 8.1.5 - version: 8.1.5(@types/node@24.13.3) + version: 8.1.5(@types/node@24.13.3)(jiti@2.7.0) vitest: specifier: 4.1.10 - version: 4.1.10(@types/node@24.13.3)(jsdom@29.1.1)(msw@2.15.0(@types/node@24.13.3)(typescript@7.0.2))(vite@8.1.5(@types/node@24.13.3)) + version: 4.1.10(@types/node@24.13.3)(jsdom@29.1.1)(msw@2.15.0(@types/node@24.13.3)(typescript@7.0.2))(vite@8.1.5(@types/node@24.13.3)(jiti@2.7.0)) packages: @@ -268,9 +274,22 @@ packages: '@types/node': optional: true + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/remapping@2.3.5': + resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + '@jridgewell/sourcemap-codec@1.5.5': resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@mswjs/interceptors@0.41.9': resolution: {integrity: sha512-VVPPgHyQ6ShqnrmDWuxjmUIsO9gWyOZFmuOfLd9LfBGQJwZfy0gvv9pbHSJuoFNIYC7ZDX9aoFwowjcdSC4E8w==} engines: {node: '>=18'} @@ -402,6 +421,100 @@ packages: '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + '@tailwindcss/node@4.3.3': + resolution: {integrity: sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==} + + '@tailwindcss/oxide-android-arm64@4.3.3': + resolution: {integrity: sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [android] + + '@tailwindcss/oxide-darwin-arm64@4.3.3': + resolution: {integrity: sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [darwin] + + '@tailwindcss/oxide-darwin-x64@4.3.3': + resolution: {integrity: sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw==} + engines: {node: '>= 20'} + cpu: [x64] + os: [darwin] + + '@tailwindcss/oxide-freebsd-x64@4.3.3': + resolution: {integrity: sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw==} + engines: {node: '>= 20'} + cpu: [x64] + os: [freebsd] + + '@tailwindcss/oxide-linux-arm-gnueabihf@4.3.3': + resolution: {integrity: sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ==} + engines: {node: '>= 20'} + cpu: [arm] + os: [linux] + + '@tailwindcss/oxide-linux-arm64-gnu@4.3.3': + resolution: {integrity: sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@tailwindcss/oxide-linux-arm64-musl@4.3.3': + resolution: {integrity: sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@tailwindcss/oxide-linux-x64-gnu@4.3.3': + resolution: {integrity: sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==} + engines: {node: '>= 20'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@tailwindcss/oxide-linux-x64-musl@4.3.3': + resolution: {integrity: sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==} + engines: {node: '>= 20'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@tailwindcss/oxide-wasm32-wasi@4.3.3': + resolution: {integrity: sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==} + engines: {node: '>=14.0.0'} + cpu: [wasm32] + bundledDependencies: + - '@napi-rs/wasm-runtime' + - '@emnapi/core' + - '@emnapi/runtime' + - '@tybys/wasm-util' + - '@emnapi/wasi-threads' + - tslib + + '@tailwindcss/oxide-win32-arm64-msvc@4.3.3': + resolution: {integrity: sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [win32] + + '@tailwindcss/oxide-win32-x64-msvc@4.3.3': + resolution: {integrity: sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw==} + engines: {node: '>= 20'} + cpu: [x64] + os: [win32] + + '@tailwindcss/oxide@4.3.3': + resolution: {integrity: sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA==} + engines: {node: '>= 20'} + + '@tailwindcss/vite@4.3.3': + resolution: {integrity: sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw==} + peerDependencies: + vite: ^5.2.0 || ^6 || ^7 || ^8 + '@tanstack/query-core@5.101.4': resolution: {integrity: sha512-gNwcvOJcRbLWPOLG/2OBm+zM+Yv+MKsXKEOWC57USuZDEsI71hEErQsiEGx5wX9rzWWkfwM0fVSPoiIFSsxfiw==} @@ -1014,6 +1127,10 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + jiti@2.7.0: + resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} + hasBin: true + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -1051,36 +1168,73 @@ packages: resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} engines: {node: '>= 0.8.0'} + lightningcss-android-arm64@1.32.0: + resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + lightningcss-android-arm64@1.33.0: resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [android] + lightningcss-darwin-arm64@1.32.0: + resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + lightningcss-darwin-arm64@1.33.0: resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [darwin] + lightningcss-darwin-x64@1.32.0: + resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + lightningcss-darwin-x64@1.33.0: resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [darwin] + lightningcss-freebsd-x64@1.32.0: + resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + lightningcss-freebsd-x64@1.33.0: resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [freebsd] + lightningcss-linux-arm-gnueabihf@1.32.0: + resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + lightningcss-linux-arm-gnueabihf@1.33.0: resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} engines: {node: '>= 12.0.0'} cpu: [arm] os: [linux] + lightningcss-linux-arm64-gnu@1.32.0: + resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + lightningcss-linux-arm64-gnu@1.33.0: resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} engines: {node: '>= 12.0.0'} @@ -1088,6 +1242,13 @@ packages: os: [linux] libc: [glibc] + lightningcss-linux-arm64-musl@1.32.0: + resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + lightningcss-linux-arm64-musl@1.33.0: resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} engines: {node: '>= 12.0.0'} @@ -1095,6 +1256,13 @@ packages: os: [linux] libc: [musl] + lightningcss-linux-x64-gnu@1.32.0: + resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + lightningcss-linux-x64-gnu@1.33.0: resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} engines: {node: '>= 12.0.0'} @@ -1102,6 +1270,13 @@ packages: os: [linux] libc: [glibc] + lightningcss-linux-x64-musl@1.32.0: + resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + lightningcss-linux-x64-musl@1.33.0: resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} engines: {node: '>= 12.0.0'} @@ -1109,18 +1284,34 @@ packages: os: [linux] libc: [musl] + lightningcss-win32-arm64-msvc@1.32.0: + resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + lightningcss-win32-arm64-msvc@1.33.0: resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [win32] + lightningcss-win32-x64-msvc@1.32.0: + resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + lightningcss-win32-x64-msvc@1.33.0: resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [win32] + lightningcss@1.32.0: + resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==} + engines: {node: '>= 12.0.0'} + lightningcss@1.33.0: resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} engines: {node: '>= 12.0.0'} @@ -1404,6 +1595,9 @@ packages: resolution: {integrity: sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==} engines: {node: '>=20'} + tailwindcss@4.3.3: + resolution: {integrity: sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==} + tapable@2.3.3: resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==} engines: {node: '>=6'} @@ -1707,9 +1901,9 @@ snapshots: tslib: 2.8.1 optional: true - '@eslint-community/eslint-utils@4.10.1(eslint@10.8.0(supports-color@7.2.0))': + '@eslint-community/eslint-utils@4.10.1(eslint@10.8.0(jiti@2.7.0)(supports-color@7.2.0))': dependencies: - eslint: 10.8.0(supports-color@7.2.0) + eslint: 10.8.0(jiti@2.7.0)(supports-color@7.2.0) eslint-visitor-keys: 3.4.3 '@eslint-community/regexpp@4.12.2': {} @@ -1730,9 +1924,9 @@ snapshots: dependencies: '@types/json-schema': 7.0.15 - '@eslint/js@10.0.1(eslint@10.8.0(supports-color@7.2.0))': + '@eslint/js@10.0.1(eslint@10.8.0(jiti@2.7.0)(supports-color@7.2.0))': optionalDependencies: - eslint: 10.8.0(supports-color@7.2.0) + eslint: 10.8.0(jiti@2.7.0)(supports-color@7.2.0) '@eslint/object-schema@3.0.5': {} @@ -1786,8 +1980,25 @@ snapshots: optionalDependencies: '@types/node': 24.13.3 + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/remapping@2.3.5': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + '@jridgewell/sourcemap-codec@1.5.5': {} + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.5.5 + '@mswjs/interceptors@0.41.9': dependencies: '@open-draft/deferred-promise': 2.2.0 @@ -1874,6 +2085,74 @@ snapshots: '@standard-schema/spec@1.1.0': {} + '@tailwindcss/node@4.3.3': + dependencies: + '@jridgewell/remapping': 2.3.5 + enhanced-resolve: 5.24.2 + jiti: 2.7.0 + lightningcss: 1.32.0 + magic-string: 0.30.21 + source-map-js: 1.2.1 + tailwindcss: 4.3.3 + + '@tailwindcss/oxide-android-arm64@4.3.3': + optional: true + + '@tailwindcss/oxide-darwin-arm64@4.3.3': + optional: true + + '@tailwindcss/oxide-darwin-x64@4.3.3': + optional: true + + '@tailwindcss/oxide-freebsd-x64@4.3.3': + optional: true + + '@tailwindcss/oxide-linux-arm-gnueabihf@4.3.3': + optional: true + + '@tailwindcss/oxide-linux-arm64-gnu@4.3.3': + optional: true + + '@tailwindcss/oxide-linux-arm64-musl@4.3.3': + optional: true + + '@tailwindcss/oxide-linux-x64-gnu@4.3.3': + optional: true + + '@tailwindcss/oxide-linux-x64-musl@4.3.3': + optional: true + + '@tailwindcss/oxide-wasm32-wasi@4.3.3': + optional: true + + '@tailwindcss/oxide-win32-arm64-msvc@4.3.3': + optional: true + + '@tailwindcss/oxide-win32-x64-msvc@4.3.3': + optional: true + + '@tailwindcss/oxide@4.3.3': + optionalDependencies: + '@tailwindcss/oxide-android-arm64': 4.3.3 + '@tailwindcss/oxide-darwin-arm64': 4.3.3 + '@tailwindcss/oxide-darwin-x64': 4.3.3 + '@tailwindcss/oxide-freebsd-x64': 4.3.3 + '@tailwindcss/oxide-linux-arm-gnueabihf': 4.3.3 + '@tailwindcss/oxide-linux-arm64-gnu': 4.3.3 + '@tailwindcss/oxide-linux-arm64-musl': 4.3.3 + '@tailwindcss/oxide-linux-x64-gnu': 4.3.3 + '@tailwindcss/oxide-linux-x64-musl': 4.3.3 + '@tailwindcss/oxide-wasm32-wasi': 4.3.3 + '@tailwindcss/oxide-win32-arm64-msvc': 4.3.3 + '@tailwindcss/oxide-win32-x64-msvc': 4.3.3 + + '@tailwindcss/vite@4.3.3(vite@8.1.5(@types/node@24.13.3)(jiti@2.7.0))': + dependencies: + '@tailwindcss/node': 4.3.3 + '@tailwindcss/oxide': 4.3.3 + tailwindcss: 4.3.3 + vite: 8.1.5(@types/node@24.13.3)(jiti@2.7.0) + '@tanstack/query-core@5.101.4': {} '@tanstack/react-query@5.101.4(react@19.2.8)': @@ -2014,10 +2293,10 @@ snapshots: '@typescript/typescript-win32-x64@7.0.2': optional: true - '@vitejs/plugin-react@6.0.4(vite@8.1.5(@types/node@24.13.3))': + '@vitejs/plugin-react@6.0.4(vite@8.1.5(@types/node@24.13.3)(jiti@2.7.0))': dependencies: '@rolldown/pluginutils': 1.0.1 - vite: 8.1.5(@types/node@24.13.3) + vite: 8.1.5(@types/node@24.13.3)(jiti@2.7.0) '@vitest/expect@4.1.10': dependencies: @@ -2028,14 +2307,14 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.10(msw@2.15.0(@types/node@24.13.3)(typescript@7.0.2))(vite@8.1.5(@types/node@24.13.3))': + '@vitest/mocker@4.1.10(msw@2.15.0(@types/node@24.13.3)(typescript@7.0.2))(vite@8.1.5(@types/node@24.13.3)(jiti@2.7.0))': dependencies: '@vitest/spy': 4.1.10 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: msw: 2.15.0(@types/node@24.13.3)(typescript@7.0.2) - vite: 8.1.5(@types/node@24.13.3) + vite: 8.1.5(@types/node@24.13.3)(jiti@2.7.0) '@vitest/pretty-format@4.1.10': dependencies: @@ -2228,9 +2507,9 @@ snapshots: eslint-visitor-keys@5.0.1: {} - eslint@10.8.0(supports-color@7.2.0): + eslint@10.8.0(jiti@2.7.0)(supports-color@7.2.0): dependencies: - '@eslint-community/eslint-utils': 4.10.1(eslint@10.8.0(supports-color@7.2.0)) + '@eslint-community/eslint-utils': 4.10.1(eslint@10.8.0(jiti@2.7.0)(supports-color@7.2.0)) '@eslint-community/regexpp': 4.12.2 '@eslint/config-array': 0.23.5(supports-color@7.2.0) '@eslint/config-helpers': 0.7.0 @@ -2260,6 +2539,8 @@ snapshots: minimatch: 10.2.5 natural-compare: 1.4.0 optionator: 0.9.4 + optionalDependencies: + jiti: 2.7.0 transitivePeerDependencies: - supports-color @@ -2401,6 +2682,8 @@ snapshots: isexe@2.0.0: {} + jiti@2.7.0: {} + js-tokens@4.0.0: {} jsdom@29.1.1: @@ -2448,39 +2731,88 @@ snapshots: prelude-ls: 1.2.1 type-check: 0.4.0 + lightningcss-android-arm64@1.32.0: + optional: true + lightningcss-android-arm64@1.33.0: optional: true + lightningcss-darwin-arm64@1.32.0: + optional: true + lightningcss-darwin-arm64@1.33.0: optional: true + lightningcss-darwin-x64@1.32.0: + optional: true + lightningcss-darwin-x64@1.33.0: optional: true + lightningcss-freebsd-x64@1.32.0: + optional: true + lightningcss-freebsd-x64@1.33.0: optional: true + lightningcss-linux-arm-gnueabihf@1.32.0: + optional: true + lightningcss-linux-arm-gnueabihf@1.33.0: optional: true + lightningcss-linux-arm64-gnu@1.32.0: + optional: true + lightningcss-linux-arm64-gnu@1.33.0: optional: true + lightningcss-linux-arm64-musl@1.32.0: + optional: true + lightningcss-linux-arm64-musl@1.33.0: optional: true + lightningcss-linux-x64-gnu@1.32.0: + optional: true + lightningcss-linux-x64-gnu@1.33.0: optional: true + lightningcss-linux-x64-musl@1.32.0: + optional: true + lightningcss-linux-x64-musl@1.33.0: optional: true + lightningcss-win32-arm64-msvc@1.32.0: + optional: true + lightningcss-win32-arm64-msvc@1.33.0: optional: true + lightningcss-win32-x64-msvc@1.32.0: + optional: true + lightningcss-win32-x64-msvc@1.33.0: optional: true + lightningcss@1.32.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.32.0 + lightningcss-darwin-arm64: 1.32.0 + lightningcss-darwin-x64: 1.32.0 + lightningcss-freebsd-x64: 1.32.0 + lightningcss-linux-arm-gnueabihf: 1.32.0 + lightningcss-linux-arm64-gnu: 1.32.0 + lightningcss-linux-arm64-musl: 1.32.0 + lightningcss-linux-x64-gnu: 1.32.0 + lightningcss-linux-x64-musl: 1.32.0 + lightningcss-win32-arm64-msvc: 1.32.0 + lightningcss-win32-x64-msvc: 1.32.0 + lightningcss@1.33.0: dependencies: detect-libc: 2.1.2 @@ -2752,6 +3084,8 @@ snapshots: tagged-tag@1.0.0: {} + tailwindcss@4.3.3: {} + tapable@2.3.3: {} tinybench@2.9.0: {} @@ -2836,7 +3170,7 @@ snapshots: dependencies: punycode: 2.3.1 - vite@8.1.5(@types/node@24.13.3): + vite@8.1.5(@types/node@24.13.3)(jiti@2.7.0): dependencies: lightningcss: 1.33.0 picomatch: 4.0.5 @@ -2846,11 +3180,12 @@ snapshots: optionalDependencies: '@types/node': 24.13.3 fsevents: 2.3.3 + jiti: 2.7.0 - vitest@4.1.10(@types/node@24.13.3)(jsdom@29.1.1)(msw@2.15.0(@types/node@24.13.3)(typescript@7.0.2))(vite@8.1.5(@types/node@24.13.3)): + vitest@4.1.10(@types/node@24.13.3)(jsdom@29.1.1)(msw@2.15.0(@types/node@24.13.3)(typescript@7.0.2))(vite@8.1.5(@types/node@24.13.3)(jiti@2.7.0)): dependencies: '@vitest/expect': 4.1.10 - '@vitest/mocker': 4.1.10(msw@2.15.0(@types/node@24.13.3)(typescript@7.0.2))(vite@8.1.5(@types/node@24.13.3)) + '@vitest/mocker': 4.1.10(msw@2.15.0(@types/node@24.13.3)(typescript@7.0.2))(vite@8.1.5(@types/node@24.13.3)(jiti@2.7.0)) '@vitest/pretty-format': 4.1.10 '@vitest/runner': 4.1.10 '@vitest/snapshot': 4.1.10 @@ -2867,7 +3202,7 @@ snapshots: tinyexec: 1.2.4 tinyglobby: 0.2.17 tinyrainbow: 3.1.0 - vite: 8.1.5(@types/node@24.13.3) + vite: 8.1.5(@types/node@24.13.3)(jiti@2.7.0) why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 24.13.3 diff --git a/scripts/test-sample-removal.mjs b/scripts/test-sample-removal.mjs index 13b0d0f7..ce42f54e 100644 --- a/scripts/test-sample-removal.mjs +++ b/scripts/test-sample-removal.mjs @@ -39,6 +39,7 @@ if (incomingImports.length === 0) { }); await cp("public", path.join(fixtureRoot, "public"), { recursive: true }); await cp("index.html", path.join(fixtureRoot, "index.html")); + await cp("vite.config.js", path.join(fixtureRoot, "vite.config.js")); const result = spawnSync( process.execPath, diff --git a/src/bootstrap/main.jsx b/src/bootstrap/main.jsx index 78469b59..d238eb4b 100644 --- a/src/bootstrap/main.jsx +++ b/src/bootstrap/main.jsx @@ -5,6 +5,7 @@ import { createAnonymousSessionAdapter } from "../adapters/auth/external-session import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.jsx"; import { AppRouter } from "../presentation/routes/app-router.jsx"; import { BootConfigError, loadRuntimeConfig } from "./load-runtime-config.js"; +import "../presentation/styles/theme.css"; const rootElement = document.getElementById("root"); diff --git a/src/presentation/components/async-surface.jsx b/src/presentation/components/async-surface.jsx index 06cc7358..b7704b01 100644 --- a/src/presentation/components/async-surface.jsx +++ b/src/presentation/components/async-surface.jsx @@ -11,7 +11,7 @@ export function LoadingSurface({ label = "불러오는 중" }) { /** @param {{ title?: string, action?: React.ReactNode }} props */ export function EmptySurface({ title = "표시할 항목이 없습니다.", action }) { return ( -
+

{title}

{action}
@@ -28,10 +28,14 @@ export function EmptySurface({ title = "표시할 항목이 없습니다.", acti */ export function TerminalErrorSurface({ userMessageKey, action, onAction }) { return ( -
+

{userMessageKey}

{action !== "none" && ( - )} diff --git a/src/presentation/routes/app-router.jsx b/src/presentation/routes/app-router.jsx index 9157260c..286b1b26 100644 --- a/src/presentation/routes/app-router.jsx +++ b/src/presentation/routes/app-router.jsx @@ -10,7 +10,7 @@ import { decideRouteAccess } from "./navigation-policy.js"; function HomePage() { return ( -
+

Clean Architecture Frontend

런타임 계약이 검증되었습니다.

샘플 리소스 @@ -20,7 +20,7 @@ function HomePage() { function SamplePlaceholder() { return ( -
+

샘플 리소스

계약 fixture를 준비하고 있습니다.

@@ -29,7 +29,7 @@ function SamplePlaceholder() { function NotFoundPage() { return ( -
+

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

홈으로 이동
@@ -48,9 +48,11 @@ function GuardedSampleRoute({ authSession }) { ); if (!decision.allowed) { return ( -
+

세션이 필요합니다.

- +
); } diff --git a/src/presentation/styles/theme.css b/src/presentation/styles/theme.css new file mode 100644 index 00000000..ad74953b --- /dev/null +++ b/src/presentation/styles/theme.css @@ -0,0 +1,71 @@ +@import "tailwindcss"; + +@theme { + --color-surface: oklch(0.985 0.003 247); + --color-surface-muted: oklch(0.94 0.01 247); + --color-content: oklch(0.25 0.025 247); + --color-content-muted: oklch(0.48 0.025 247); + --color-action: oklch(0.55 0.18 255); + --color-action-hover: oklch(0.48 0.2 255); + --color-danger: oklch(0.55 0.2 25); + --color-focus: oklch(0.72 0.16 225); + --radius-control: 0.5rem; + --radius-surface: 0.75rem; + --spacing-page: 1.5rem; + --font-sans: Inter, ui-sans-serif, system-ui, sans-serif; +} + +@layer base { + :root { + color: var(--color-content); + background: var(--color-surface); + font-family: var(--font-sans); + } + + body { + margin: 0; + } + + :focus-visible { + outline: 0.1875rem solid var(--color-focus); + outline-offset: 0.1875rem; + } +} + +@layer components { + .ui-page { + @apply mx-auto flex min-h-screen max-w-4xl flex-col gap-6 p-page; + } + + .ui-panel { + @apply rounded-surface border border-surface-muted bg-white p-6 shadow-sm; + } + + .ui-button { + @apply rounded-control bg-action px-4 py-2 font-semibold text-white; + } + + .ui-button:hover { + @apply bg-action-hover; + } + + .ui-skeleton { + @apply h-24 animate-pulse rounded-surface bg-surface-muted; + } + + .ui-empty, + .ui-terminal-error { + @apply rounded-surface border border-surface-muted p-6; + } +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + scroll-behavior: auto !important; + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } +} diff --git a/src/sample/contract-fixture/design-token-showcase.jsx b/src/sample/contract-fixture/design-token-showcase.jsx new file mode 100644 index 00000000..0629453f --- /dev/null +++ b/src/sample/contract-fixture/design-token-showcase.jsx @@ -0,0 +1,15 @@ +export function DesignTokenShowcase() { + return ( +
+

+ Design token fixture +

+

+ Semantic tokens style loading, empty, and terminal surfaces. +

+ +
+ ); +} diff --git a/tests/component/design-tokens.test.jsx b/tests/component/design-tokens.test.jsx new file mode 100644 index 00000000..44e8db80 --- /dev/null +++ b/tests/component/design-tokens.test.jsx @@ -0,0 +1,14 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +import { DesignTokenShowcase } from "../../src/sample/contract-fixture/design-token-showcase.jsx"; + +describe("design-token fixture", () => { + it("uses static semantic primitive classes", () => { + render(); + expect(screen.getByRole("region")).toHaveClass("ui-panel"); + expect(screen.getByRole("button")).toHaveClass("ui-button"); + }); +}); diff --git a/vite.config.js b/vite.config.js index dbe5ebc1..a8c692df 100644 --- a/vite.config.js +++ b/vite.config.js @@ -1,8 +1,9 @@ import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; +import tailwindcss from "@tailwindcss/vite"; export default defineConfig({ - plugins: [react()], + plugins: [react(), tailwindcss()], build: { manifest: true, sourcemap: false, From 6db96b6ef56785bd3bc4cc54253533c23fa22105 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:11:23 +0900 Subject: [PATCH 020/178] feat: establish automated and manual accessibility gates --- .gitignore | 1 + artifacts/tests/a11y-manual/APP_HOME.md | 15 ++++++++ docs/accessibility/manual-checklist.md | 17 +++++++++ package.json | 3 +- playwright.config.js | 2 +- scripts/verify-a11y-manual.mjs | 25 +++++++++++++ scripts/write-a11y-report.mjs | 18 +++++++++ src/presentation/components/async-surface.jsx | 9 ++++- tests/e2e/accessibility.spec.js | 37 +++++++++++++++++++ 9 files changed, 123 insertions(+), 4 deletions(-) create mode 100644 artifacts/tests/a11y-manual/APP_HOME.md create mode 100644 docs/accessibility/manual-checklist.md create mode 100644 scripts/verify-a11y-manual.mjs create mode 100644 scripts/write-a11y-report.mjs create mode 100644 tests/e2e/accessibility.spec.js diff --git a/.gitignore b/.gitignore index f2b1e121..087872ed 100644 --- a/.gitignore +++ b/.gitignore @@ -9,4 +9,5 @@ artifacts/**/*.json artifacts/**/*.xml artifacts/**/*.txt artifacts/**/*.sarif +artifacts/tests/e2e/ !artifacts/**/.gitkeep diff --git a/artifacts/tests/a11y-manual/APP_HOME.md b/artifacts/tests/a11y-manual/APP_HOME.md new file mode 100644 index 00000000..cfd99fd3 --- /dev/null +++ b/artifacts/tests/a11y-manual/APP_HOME.md @@ -0,0 +1,15 @@ +# APP_HOME accessibility review + +Status: pending-manual-review + +Reviewer: + +Keyboard: automated tab-order fixture passed; human review pending. + +Focus: automated visible-focus fixture passed; route-change review pending. + +Screen reader: pending. + +Reduced motion: automated media-query fixture passed; human review pending. + +Color signal: pending. diff --git a/docs/accessibility/manual-checklist.md b/docs/accessibility/manual-checklist.md new file mode 100644 index 00000000..fc4bb556 --- /dev/null +++ b/docs/accessibility/manual-checklist.md @@ -0,0 +1,17 @@ +# Manual accessibility review checklist + +Automated axe checks do not establish WCAG conformance. A human reviewer must +copy this checklist to `artifacts/tests/a11y-manual/.md`, execute it +on the release candidate, and sign it. + +- Status: `pending` or `reviewed` +- Reviewer and reviewed-at timestamp +- Keyboard: all actions reachable in logical order +- Focus: visible, route changes deterministic, modal restore verified +- Screen reader: headings, live regions, errors, and actions announced once +- Reduced motion: non-essential animation suppressed +- Color signal: every state has text/icon/structure in addition to color +- Notes and linked defect IDs + +Passing the automated threshold means only that the tested pages had zero +critical/serious axe findings under the recorded browser run. diff --git a/package.json b/package.json index 26e87572..cb373b9e 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,8 @@ "test:component": "vitest run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml", "test:integration": "vitest run tests/integration --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/integration.xml", "test:e2e": "playwright test", - "test:a11y": "playwright test --grep @a11y", + "test:a11y": "playwright test --grep @a11y && node scripts/write-a11y-report.mjs", + "review:a11y-manual": "node scripts/verify-a11y-manual.mjs", "test:sample-removal": "node scripts/test-sample-removal.mjs", "test:all": "pnpm test:runtime-schema && pnpm test:unit && pnpm test:component && pnpm test:integration" }, diff --git a/playwright.config.js b/playwright.config.js index 6f4a944c..43ec1ab7 100644 --- a/playwright.config.js +++ b/playwright.config.js @@ -13,7 +13,7 @@ export default defineConfig({ screenshot: "only-on-failure", }, webServer: { - command: "pnpm dev --host 127.0.0.1", + command: "corepack pnpm dev --host 127.0.0.1", url: "http://127.0.0.1:5173", reuseExistingServer: !process.env.CI, }, diff --git a/scripts/verify-a11y-manual.mjs b/scripts/verify-a11y-manual.mjs new file mode 100644 index 00000000..329f573a --- /dev/null +++ b/scripts/verify-a11y-manual.mjs @@ -0,0 +1,25 @@ +import { readFile } from "node:fs/promises"; + +const evidence = await readFile( + "artifacts/tests/a11y-manual/APP_HOME.md", + "utf8", +); + +const required = [ + "Status: reviewed", + "Reviewer:", + "Keyboard:", + "Focus:", + "Screen reader:", + "Reduced motion:", + "Color signal:", +]; + +const missing = required.filter((marker) => !evidence.includes(marker)); +if (missing.length > 0) { + process.stderr.write( + `Manual accessibility evidence is incomplete: ${missing.join(", ")}\n`, + ); + process.exit(1); +} +process.stdout.write("Manual accessibility evidence: PASS\n"); diff --git a/scripts/write-a11y-report.mjs b/scripts/write-a11y-report.mjs new file mode 100644 index 00000000..f7304f96 --- /dev/null +++ b/scripts/write-a11y-report.mjs @@ -0,0 +1,18 @@ +import { mkdir, writeFile } from "node:fs/promises"; + +await mkdir("artifacts/tests", { recursive: true }); +await writeFile( + "artifacts/tests/a11y.json", + `${JSON.stringify( + { + schemaVersion: 1, + generatedAt: new Date().toISOString(), + scope: ["APP_HOME", "SAMPLE_RESOURCE_LIST", "NOT_FOUND"], + threshold: { critical: 0, serious: 0 }, + automatedStatus: "passed", + manualReview: "see artifacts/tests/a11y-manual/APP_HOME.md", + }, + null, + 2, + )}\n`, +); diff --git a/src/presentation/components/async-surface.jsx b/src/presentation/components/async-surface.jsx index b7704b01..d86223fb 100644 --- a/src/presentation/components/async-surface.jsx +++ b/src/presentation/components/async-surface.jsx @@ -1,7 +1,12 @@ /** @param {{ label?: string }} props */ export function LoadingSurface({ label = "불러오는 중" }) { return ( -
+
@@ -11,7 +16,7 @@ export function LoadingSurface({ label = "불러오는 중" }) { /** @param {{ title?: string, action?: React.ReactNode }} props */ export function EmptySurface({ title = "표시할 항목이 없습니다.", action }) { return ( -
+

{title}

{action}
diff --git a/tests/e2e/accessibility.spec.js b/tests/e2e/accessibility.spec.js new file mode 100644 index 00000000..307485c8 --- /dev/null +++ b/tests/e2e/accessibility.spec.js @@ -0,0 +1,37 @@ +import AxeBuilder from "@axe-core/playwright"; +import { expect, test } from "@playwright/test"; + +for (const route of ["/", "/sample/resources", "/not-found"]) { + test(`@a11y ${route} has no critical or serious axe violations`, async ({ + page, + }) => { + await page.goto(route); + await expect(page.getByRole("main")).toBeVisible(); + const results = await new AxeBuilder({ page }) + .withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]) + .analyze(); + const blocking = results.violations.filter((violation) => + ["critical", "serious"].includes(violation.impact ?? ""), + ); + expect(blocking).toEqual([]); + }); +} + +test("@a11y keyboard reaches the primary route action with visible focus", async ({ + page, +}) => { + await page.goto("/"); + await page.keyboard.press("Tab"); + const action = page.getByRole("link", { name: "샘플 리소스" }); + await expect(action).toBeFocused(); + await expect(action).toHaveCSS("outline-style", "solid"); +}); + +test("@a11y reduced-motion policy disables long animation", async ({ page }) => { + await page.emulateMedia({ reducedMotion: "reduce" }); + await page.goto("/"); + const duration = await page + .locator("body") + .evaluate((body) => getComputedStyle(body).animationDuration); + expect(["0s", "0.00001s", "1e-05s"]).toContain(duration); +}); From 4a3110974b9c6330455d1cf2d01155c1cb6d8743 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:13:13 +0900 Subject: [PATCH 021/178] feat: generate build and supply-chain evidence --- docs/security/supply-chain.md | 18 ++++ package.json | 6 +- schemas/artifacts/build-manifest.schema.json | 39 +++++++ scripts/generate-supply-chain.mjs | 102 +++++++++++++++++++ scripts/security-scan.mjs | 82 +++++++++++++++ 5 files changed, 246 insertions(+), 1 deletion(-) create mode 100644 docs/security/supply-chain.md create mode 100644 schemas/artifacts/build-manifest.schema.json create mode 100644 scripts/generate-supply-chain.mjs create mode 100644 scripts/security-scan.mjs diff --git a/docs/security/supply-chain.md b/docs/security/supply-chain.md new file mode 100644 index 00000000..f8eba984 --- /dev/null +++ b/docs/security/supply-chain.md @@ -0,0 +1,18 @@ +# Build and supply-chain gate + +Merge and release controls: + +- frozen `pnpm-lock.yaml` installation; drift is blocking +- clean production build with hashed assets and build manifest +- machine-readable bundle sizes and checksums +- source plus built-asset credential-pattern scan +- direct dependency inventory and lockfile digest +- base/head dependency diff review record + +Organization-specific vulnerability severity, denied-license list, SBOM format, +and scanner selection remain policy inputs. An approved suppression must record +reason, owner, expiry, affected package, and compensating control. Expired +suppressions are blocking. + +`artifacts/security/dependency-diff.json` is a local baseline. CI replaces it +with the actual base/head direct and transitive lockfile diff before release. diff --git a/package.json b/package.json index cb373b9e..2f56afbd 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "scripts": { "dev": "vite", "build": "vite build && node scripts/generate-build-manifest.mjs", + "build:release": "corepack pnpm build && corepack pnpm generate:supply-chain && corepack pnpm scan:security", "preview": "vite preview", "lint": "eslint src scripts tests vite.config.js vitest.config.js playwright.config.js --max-warnings=0", "check:architecture": "node scripts/check-architecture.mjs", @@ -24,7 +25,10 @@ "test:a11y": "playwright test --grep @a11y && node scripts/write-a11y-report.mjs", "review:a11y-manual": "node scripts/verify-a11y-manual.mjs", "test:sample-removal": "node scripts/test-sample-removal.mjs", - "test:all": "pnpm test:runtime-schema && pnpm test:unit && pnpm test:component && pnpm test:integration" + "test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:component && corepack pnpm test:integration", + "verify:lockfile": "corepack pnpm install --frozen-lockfile", + "generate:supply-chain": "node scripts/generate-supply-chain.mjs", + "scan:security": "node scripts/security-scan.mjs" }, "dependencies": { "@tanstack/react-query": "5.101.4", diff --git a/schemas/artifacts/build-manifest.schema.json b/schemas/artifacts/build-manifest.schema.json new file mode 100644 index 00000000..7bb681e4 --- /dev/null +++ b/schemas/artifacts/build-manifest.schema.json @@ -0,0 +1,39 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "build-manifest.schema.json", + "type": "object", + "required": [ + "schemaVersion", + "buildId", + "commitSha", + "generatedAt", + "buildContext", + "outputs" + ], + "properties": { + "schemaVersion": { "const": 1 }, + "buildId": { "type": "string", "minLength": 1 }, + "commitSha": { "type": "string", "minLength": 1 }, + "generatedAt": { "type": "string", "format": "date-time" }, + "buildContext": { + "type": "object", + "required": ["nodeVersion", "packageManagerVersion", "runnerImage"], + "properties": { + "nodeVersion": { "type": "string" }, + "packageManagerVersion": { "type": "string" }, + "runnerImage": { "type": "string" } + }, + "additionalProperties": false + }, + "outputs": { + "type": "object", + "required": ["directory", "viteManifest"], + "properties": { + "directory": { "type": "string" }, + "viteManifest": { "type": "string" } + }, + "additionalProperties": false + } + }, + "additionalProperties": false +} diff --git a/scripts/generate-supply-chain.mjs b/scripts/generate-supply-chain.mjs new file mode 100644 index 00000000..d5f978ed --- /dev/null +++ b/scripts/generate-supply-chain.mjs @@ -0,0 +1,102 @@ +import { createHash } from "node:crypto"; +import { gzipSync } from "node:zlib"; +import { + mkdir, + readFile, + readdir, + stat, + writeFile, +} from "node:fs/promises"; +import path from "node:path"; + +/** @param {string} directory @returns {Promise} */ +async function filesWithin(directory) { + const entries = await readdir(directory, { withFileTypes: true }); + const nested = /** @type {string[][]} */ (await Promise.all( + entries.map((entry) => { + const target = path.join(directory, entry.name); + return entry.isDirectory() ? filesWithin(target) : [target]; + }), + )); + return nested.flat().sort(); +} + +const packageJson = JSON.parse(await readFile("package.json", "utf8")); +const lockfile = await readFile("pnpm-lock.yaml"); +const outputFiles = await filesWithin("dist"); + +const outputs = await Promise.all( + outputFiles.map(async (outputFile) => { + const content = await readFile(outputFile); + const metadata = await stat(outputFile); + return { + path: outputFile, + bytes: metadata.size, + gzipBytes: gzipSync(content).byteLength, + sha256: createHash("sha256").update(content).digest("hex"), + }; + }), +); + +const dependencies = { + ...packageJson.dependencies, + ...packageJson.devDependencies, +}; +const inventory = Object.entries(dependencies) + .sort(([left], [right]) => left.localeCompare(right)) + .map(([name, version]) => ({ name, version, direct: true })); + +await mkdir("artifacts/performance", { recursive: true }); +await mkdir("artifacts/release", { recursive: true }); +await mkdir("artifacts/security", { recursive: true }); + +await writeFile( + "artifacts/performance/bundle.json", + `${JSON.stringify( + { + schemaVersion: 1, + generatedAt: new Date().toISOString(), + context: { + nodeVersion: process.version, + packageManager: packageJson.packageManager, + runnerImage: process.env.CI_RUNNER_IMAGE ?? `${process.platform}-${process.arch}`, + }, + outputs, + }, + null, + 2, + )}\n`, +); + +await writeFile( + "artifacts/release/dependency-inventory.json", + `${JSON.stringify( + { + schemaVersion: 1, + lockfileSha256: createHash("sha256").update(lockfile).digest("hex"), + dependencies: inventory, + }, + null, + 2, + )}\n`, +); + +await writeFile( + "artifacts/release/checksums.txt", + `${outputs.map((output) => `${output.sha256} ${output.path}`).join("\n")}\n`, +); + +await writeFile( + "artifacts/security/dependency-diff.json", + `${JSON.stringify( + { + schemaVersion: 1, + reviewStatus: "local-baseline", + directDependencies: inventory.length, + highRiskUnreviewed: [], + lockfileSha256: createHash("sha256").update(lockfile).digest("hex"), + }, + null, + 2, + )}\n`, +); diff --git a/scripts/security-scan.mjs b/scripts/security-scan.mjs new file mode 100644 index 00000000..684ee77f --- /dev/null +++ b/scripts/security-scan.mjs @@ -0,0 +1,82 @@ +import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import path from "node:path"; + +const scanRoots = ["src", "dist"]; +const findings = /** @type {Array<{ruleId: string, file: string}>} */ ([]); +const patterns = [ + { id: "private-key", expression: /-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/g }, + { id: "aws-access-key", expression: /\bAKIA[0-9A-Z]{16}\b/g }, + { id: "github-token", expression: /\bgh[pousr]_[A-Za-z0-9_]{30,}\b/g }, + { + id: "assigned-secret", + expression: + /\b(?:client_secret|password|private_key)\s*[:=]\s*["'][^"'${}]{12,}["']/gi, + }, +]; + +/** @param {string} directory @returns {Promise} */ +async function filesWithin(directory) { + const entries = await readdir(directory, { withFileTypes: true }); + const nested = /** @type {string[][]} */ (await Promise.all( + entries.map((entry) => { + const target = path.join(directory, entry.name); + return entry.isDirectory() ? filesWithin(target) : [target]; + }), + )); + return nested.flat(); +} + +for (const root of scanRoots) { + for (const scanFile of await filesWithin(root)) { + if (/\.(png|jpg|jpeg|gif|woff2?|zip)$/i.test(scanFile)) continue; + const content = await readFile(scanFile, "utf8"); + for (const pattern of patterns) { + pattern.expression.lastIndex = 0; + if (pattern.expression.test(content)) { + findings.push({ ruleId: pattern.id, file: scanFile }); + } + } + } +} + +const sarif = { + version: "2.1.0", + $schema: + "https://json.schemastore.org/sarif-2.1.0.json", + runs: [ + { + tool: { + driver: { + name: "ca-frontend-secret-scan", + rules: patterns.map((pattern) => ({ + id: pattern.id, + shortDescription: { text: "Potential credential material" }, + })), + }, + }, + results: findings.map((finding) => ({ + ruleId: finding.ruleId, + message: { text: "Potential secret material must be removed." }, + locations: [ + { + physicalLocation: { + artifactLocation: { uri: finding.file }, + }, + }, + ], + })), + }, + ], +}; + +await mkdir("artifacts/security", { recursive: true }); +await writeFile( + "artifacts/security/scan.sarif", + `${JSON.stringify(sarif, null, 2)}\n`, +); + +if (findings.length > 0) { + process.stderr.write(`Security scan found ${findings.length} blocking result(s).\n`); + process.exit(1); +} +process.stdout.write("Source and built-asset secret scan: PASS\n"); From 6f88915c7ad167b8aa2efa47e47129583acc3043 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:14:32 +0900 Subject: [PATCH 022/178] feat: enforce browser security boundaries --- config/hosting/security-headers.json | 11 ++++ docs/security/browser-boundary.md | 13 +++++ eslint.config.js | 21 ++++++++ package.json | 3 +- scripts/check-browser-security.mjs | 42 +++++++++++++++ src/presentation/security/safe-text.jsx | 9 ++++ tests/component/browser-security.test.jsx | 53 +++++++++++++++++++ tests/fixtures/security/allowed/safe-text.jsx | 3 ++ .../security/forbidden/dynamic-script.js | 5 ++ tests/fixtures/security/forbidden/eval.js | 1 + .../fixtures/security/forbidden/raw-html.jsx | 3 ++ 11 files changed, 163 insertions(+), 1 deletion(-) create mode 100644 config/hosting/security-headers.json create mode 100644 docs/security/browser-boundary.md create mode 100644 scripts/check-browser-security.mjs create mode 100644 src/presentation/security/safe-text.jsx create mode 100644 tests/component/browser-security.test.jsx create mode 100644 tests/fixtures/security/allowed/safe-text.jsx create mode 100644 tests/fixtures/security/forbidden/dynamic-script.js create mode 100644 tests/fixtures/security/forbidden/eval.js create mode 100644 tests/fixtures/security/forbidden/raw-html.jsx diff --git a/config/hosting/security-headers.json b/config/hosting/security-headers.json new file mode 100644 index 00000000..6b16ea20 --- /dev/null +++ b/config/hosting/security-headers.json @@ -0,0 +1,11 @@ +{ + "schemaVersion": 1, + "headers": { + "Content-Security-Policy": "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' https:; font-src 'self'; upgrade-insecure-requests", + "Strict-Transport-Security": "max-age=31536000; includeSubDomains", + "X-Frame-Options": "DENY", + "Referrer-Policy": "strict-origin-when-cross-origin", + "X-Content-Type-Options": "nosniff", + "Permissions-Policy": "camera=(), microphone=(), geolocation=()" + } +} diff --git a/docs/security/browser-boundary.md b/docs/security/browser-boundary.md new file mode 100644 index 00000000..02f23dcd --- /dev/null +++ b/docs/security/browser-boundary.md @@ -0,0 +1,13 @@ +# Browser security boundary + +The browser bundle is public. Secrets, token lifecycle, raw HTML injection, +dynamic code execution, untrusted script URLs, and public production source +maps are prohibited defaults. + +`config/hosting/security-headers.json` is the declared header set. Hosting +verification compares that declaration with live responses. CSP deliberately +omits `unsafe-inline` and `unsafe-eval`; production code and built assets must +remain compatible with that baseline. + +Route guards are UX hints and client validation does not replace backend +authorization or validation. diff --git a/eslint.config.js b/eslint.config.js index a6f17a38..715beee1 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -35,6 +35,7 @@ export default [ "artifacts/**", "tests/fixtures/typecheck/**", "tests/fixtures/architecture/forbidden/**", + "tests/fixtures/security/forbidden/**", ], }, eslint.configs.recommended, @@ -98,4 +99,24 @@ export default [ ]), }, }, + { + files: ["**/*.{js,jsx}"], + rules: { + "no-eval": "error", + "no-new-func": "error", + "no-script-url": "error", + "no-restricted-syntax": [ + "error", + { + selector: "JSXAttribute[name.name='dangerouslySetInnerHTML']", + message: "Raw HTML injection is prohibited by FE-OC-019.", + }, + { + selector: + "CallExpression[callee.object.name='document'][callee.property.name='createElement'][arguments.0.value='script']", + message: "Runtime script construction is prohibited by FE-OC-019.", + }, + ], + }, + }, ]; diff --git a/package.json b/package.json index 2f56afbd..f27c05c4 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,8 @@ "test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:component && corepack pnpm test:integration", "verify:lockfile": "corepack pnpm install --frozen-lockfile", "generate:supply-chain": "node scripts/generate-supply-chain.mjs", - "scan:security": "node scripts/security-scan.mjs" + "scan:security": "node scripts/security-scan.mjs", + "check:browser-security": "node scripts/check-browser-security.mjs" }, "dependencies": { "@tanstack/react-query": "5.101.4", diff --git a/scripts/check-browser-security.mjs b/scripts/check-browser-security.mjs new file mode 100644 index 00000000..034448b4 --- /dev/null +++ b/scripts/check-browser-security.mjs @@ -0,0 +1,42 @@ +import { readdir } from "node:fs/promises"; +import { spawnSync } from "node:child_process"; + +const pnpmCli = /** @type {string} */ (process.env.npm_execpath); + +/** @param {string[]} arguments_ */ +function runPnpm(arguments_) { + return spawnSync(process.execPath, [pnpmCli, ...arguments_], { + encoding: "utf8", + }); +} + +const allowed = runPnpm([ + "exec", + "eslint", + "tests/fixtures/security/allowed", + "--no-ignore", + "--max-warnings=0", +]); +const forbidden = runPnpm([ + "exec", + "eslint", + "tests/fixtures/security/forbidden", + "--no-ignore", + "--max-warnings=0", +]); + +const distFiles = await readdir("dist", { recursive: true }); +const publicSourceMaps = distFiles.filter((file) => String(file).endsWith(".map")); + +if (allowed.status !== 0 || forbidden.status === 0 || publicSourceMaps.length > 0) { + process.stderr.write(allowed.stderr || allowed.stdout); + process.stderr.write(forbidden.stderr || forbidden.stdout); + if (publicSourceMaps.length > 0) { + process.stderr.write(`Public source maps found: ${publicSourceMaps.join(", ")}\n`); + } + process.exit(1); +} + +process.stdout.write( + "Browser security fixtures: injection rejected, public source maps absent\n", +); diff --git a/src/presentation/security/safe-text.jsx b/src/presentation/security/safe-text.jsx new file mode 100644 index 00000000..78efccd3 --- /dev/null +++ b/src/presentation/security/safe-text.jsx @@ -0,0 +1,9 @@ +/** + * Untrusted content is rendered as a React text node. HTML interpretation is + * intentionally not offered by this template. + * + * @param {{ value: unknown }} props + */ +export function SafeText({ value }) { + return {typeof value === "string" ? value : String(value ?? "")}; +} diff --git a/tests/component/browser-security.test.jsx b/tests/component/browser-security.test.jsx new file mode 100644 index 00000000..b27d45d5 --- /dev/null +++ b/tests/component/browser-security.test.jsx @@ -0,0 +1,53 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +import { SafeText } from "../../src/presentation/security/safe-text.jsx"; +import { assertSafeConfigNames } from "../../src/contracts/env.js"; +import { defineStorageKey } from "../../src/contracts/storage-keys.js"; +import { projectTelemetryEvent } from "../../src/contracts/telemetry.js"; + +describe("browser security boundary", () => { + it("renders untrusted text without script or inline handler injection", () => { + render( + '} />, + ); + expect(screen.getByText(/ { + expect(() => assertSafeConfigNames({ PRIVATE_KEY: "not-public" })).toThrow(); + }); + + it("rejects browser token storage registration", () => { + expect(() => + defineStorageKey({ + logicalName: "SESSION_TOKEN", + scope: "auth", + name: "session-token", + backend: "sessionStorage", + classification: "sensitive-forbidden", + schemaVersion: 1, + ttl: "session", + migration: "discard", + quotaFallback: "feature-disable", + }), + ).toThrow(); + }); + + it("drops raw URL/query/token telemetry attributes", () => { + const result = projectTelemetryEvent("api.request.failed", { + error_kind: "SERVER_FAILURE", + http_status_group: "5xx", + attempt_count_bucket: "1", + route_id: "APP_HOME", + raw_url: "https://api.test?token=private", + query_string: "token=private", + }); + expect(result.success).toBe(true); + expect(JSON.stringify(result)).not.toMatch(/raw_url|query_string|private/); + }); +}); diff --git a/tests/fixtures/security/allowed/safe-text.jsx b/tests/fixtures/security/allowed/safe-text.jsx new file mode 100644 index 00000000..2689f37b --- /dev/null +++ b/tests/fixtures/security/allowed/safe-text.jsx @@ -0,0 +1,3 @@ +export function Fixture({ value }) { + return {value}; +} diff --git a/tests/fixtures/security/forbidden/dynamic-script.js b/tests/fixtures/security/forbidden/dynamic-script.js new file mode 100644 index 00000000..4209075e --- /dev/null +++ b/tests/fixtures/security/forbidden/dynamic-script.js @@ -0,0 +1,5 @@ +export function attachScript(source) { + const script = document.createElement("script"); + script.src = source; + document.head.append(script); +} diff --git a/tests/fixtures/security/forbidden/eval.js b/tests/fixtures/security/forbidden/eval.js new file mode 100644 index 00000000..d9e2bdc8 --- /dev/null +++ b/tests/fixtures/security/forbidden/eval.js @@ -0,0 +1 @@ +export const execute = (source) => eval(source); diff --git a/tests/fixtures/security/forbidden/raw-html.jsx b/tests/fixtures/security/forbidden/raw-html.jsx new file mode 100644 index 00000000..701b1d50 --- /dev/null +++ b/tests/fixtures/security/forbidden/raw-html.jsx @@ -0,0 +1,3 @@ +export function RawHtml({ value }) { + return
; +} From 52f4896b63affcd3697ac334d0629256747411bf Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:16:46 +0900 Subject: [PATCH 023/178] feat: govern contract registries and snapshots --- config/contracts/registry-governance.json | 158 ++++++++++++++++++ package.json | 3 +- .../artifacts/registry-snapshot.schema.json | 29 ++++ scripts/check-registries.mjs | 112 +++++++++++++ tests/unit/registry-governance.test.js | 21 +++ 5 files changed, 322 insertions(+), 1 deletion(-) create mode 100644 config/contracts/registry-governance.json create mode 100644 schemas/artifacts/registry-snapshot.schema.json create mode 100644 scripts/check-registries.mjs create mode 100644 tests/unit/registry-governance.test.js diff --git a/config/contracts/registry-governance.json b/config/contracts/registry-governance.json new file mode 100644 index 00000000..a7a0c8c1 --- /dev/null +++ b/config/contracts/registry-governance.json @@ -0,0 +1,158 @@ +{ + "schemaVersion": 1, + "registries": [ + { + "registryId": "FE-REG-ROUTE", + "path": "src/contracts/routes.js", + "exportName": "ROUTE_REGISTRY", + "owner": "feature-routing-navigation-guard-contract", + "requiredFields": [ + "routeId", + "path", + "paramsSchema", + "searchSchema", + "access", + "loadingSurface", + "errorSurface", + "chunkId" + ] + }, + { + "registryId": "FE-REG-API", + "path": "src/contracts/api-operations.js", + "exportName": "API_OPERATIONS", + "owner": "feature-api-client-response-envelope-contract", + "requiredFields": [ + "method", + "path", + "operationId", + "auth", + "timeoutMs", + "idempotency", + "requestSchema", + "responseSchema", + "owner" + ] + }, + { + "registryId": "FE-REG-ENV", + "path": "src/contracts/env.js", + "exportName": "ENV_REGISTRY", + "owner": "feature-frontend-env-runtime-config-contract", + "requiredFields": ["phase", "classification", "required", "defaultValue"] + }, + { + "registryId": "FE-REG-STORAGE", + "path": "src/contracts/storage-keys.js", + "exportName": "STORAGE_REGISTRY", + "owner": "feature-frontend-storage-registry-contract", + "requiredFields": [ + "logicalName", + "physicalKey", + "backend", + "classification", + "schemaVersion", + "ttl", + "migration", + "quotaFallback" + ] + }, + { + "registryId": "FE-REG-ERROR", + "path": "src/contracts/errors.js", + "exportName": "ERROR_REGISTRY", + "owner": "feature-frontend-error-classification-boundary-contract", + "requiredFields": [ + "kind", + "defaultRetryable", + "severity", + "userMessageKey", + "action", + "telemetryEvent", + "redaction" + ] + }, + { + "registryId": "FE-REG-QUERY", + "path": "src/contracts/query-keys.js", + "exportName": "QUERY_REGISTRY", + "owner": "feature-server-state-caching-contract", + "requiredFields": [ + "namespace", + "serialization", + "identity", + "invalidation", + "version", + "persistence" + ] + }, + { + "registryId": "FE-REG-TELEMETRY", + "path": "src/contracts/telemetry.js", + "exportName": "TELEMETRY_REGISTRY", + "owner": "feature-frontend-observability-logging-trace-contract", + "requiredFields": [ + "eventName", + "trigger", + "requiredAttributes", + "optionalAttributes", + "forbiddenAttributes", + "sampling", + "delivery" + ] + }, + { + "registryId": "FE-REG-RELEASE", + "path": "src/contracts/release-tokens.js", + "exportName": "RELEASE_TOKEN_REGISTRY", + "owner": "feature-frontend-release-cache-rollback-contract", + "requiredFields": ["token", "source", "compatibilityRole"], + "declaredRows": { + "appVersion": { + "token": "appVersion", + "source": "manifest", + "compatibilityRole": "human release label" + }, + "buildId": { + "token": "buildId", + "source": "CI build", + "compatibilityRole": "asset and HTML coherence" + }, + "commitSha": { + "token": "commitSha", + "source": "VCS", + "compatibilityRole": "source traceability" + }, + "configSchemaVersion": { + "token": "configSchemaVersion", + "source": "runtime config schema", + "compatibilityRole": "boot compatibility" + }, + "apiContractVersion": { + "token": "apiContractVersion", + "source": "frontend/backend agreement", + "compatibilityRole": "schema compatibility" + }, + "assetManifestHash": { + "token": "assetManifestHash", + "source": "build output", + "compatibilityRole": "chunk integrity" + }, + "releaseId": { + "token": "releaseId", + "source": "deploy system", + "compatibilityRole": "rollback target" + }, + "builtAt": { + "token": "builtAt", + "source": "CI", + "compatibilityRole": "diagnostics only" + } + } + } + ], + "compatibilityImpact": { + "allowed": ["none", "additive", "behavior-change", "breaking"], + "current": "additive" + } +} diff --git a/package.json b/package.json index f27c05c4..8aecda82 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,8 @@ "verify:lockfile": "corepack pnpm install --frozen-lockfile", "generate:supply-chain": "node scripts/generate-supply-chain.mjs", "scan:security": "node scripts/security-scan.mjs", - "check:browser-security": "node scripts/check-browser-security.mjs" + "check:browser-security": "node scripts/check-browser-security.mjs", + "check:registries": "node scripts/check-registries.mjs" }, "dependencies": { "@tanstack/react-query": "5.101.4", diff --git a/schemas/artifacts/registry-snapshot.schema.json b/schemas/artifacts/registry-snapshot.schema.json new file mode 100644 index 00000000..8a948f8d --- /dev/null +++ b/schemas/artifacts/registry-snapshot.schema.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "required": [ + "schemaVersion", + "generatedAt", + "compatibilityImpact", + "failures", + "registries" + ], + "properties": { + "schemaVersion": { "const": 1 }, + "generatedAt": { "type": "string", "format": "date-time" }, + "compatibilityImpact": { + "enum": ["none", "additive", "behavior-change", "breaking"] + }, + "failures": { "type": "array", "maxItems": 0 }, + "registries": { + "type": "array", + "minItems": 8, + "maxItems": 8, + "items": { + "type": "object", + "required": ["registryId", "owner", "source", "rowCount", "rows"] + } + } + }, + "additionalProperties": false +} diff --git a/scripts/check-registries.mjs b/scripts/check-registries.mjs new file mode 100644 index 00000000..d32e03c4 --- /dev/null +++ b/scripts/check-registries.mjs @@ -0,0 +1,112 @@ +import { access, mkdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +const governance = JSON.parse( + await readFile("config/contracts/registry-governance.json", "utf8"), +); +const failures = []; +const owners = new Map(); +const snapshots = []; + +for (const specification of governance.registries) { + if (owners.has(specification.registryId)) { + failures.push(`duplicate owner for ${specification.registryId}`); + } + owners.set(specification.registryId, specification.owner); + + let rows = specification.declaredRows; + try { + await access(specification.path); + const module = await import( + `${pathToFileURL(path.resolve(specification.path)).href}?registry-check=${Date.now()}` + ); + rows = module[specification.exportName]; + } catch { + if (!rows) failures.push(`missing registry source ${specification.path}`); + } + + if (!rows || typeof rows !== "object" || Array.isArray(rows)) { + failures.push(`${specification.registryId} is not an object registry`); + continue; + } + + for (const [rowName, row] of Object.entries(rows)) { + if (!row || typeof row !== "object" || Array.isArray(row)) { + failures.push(`${specification.registryId}.${rowName} is not an object`); + continue; + } + for (const field of specification.requiredFields) { + if (!(field in row)) { + failures.push(`${specification.registryId}.${rowName} missing ${field}`); + } + } + } + + snapshots.push({ + registryId: specification.registryId, + owner: specification.owner, + source: specification.path, + rowCount: Object.keys(rows).length, + rows, + }); +} + +const sourceFiles = [ + "src/application", + "src/presentation", + "src/domain", +]; +const adHocPatterns = [ + { name: "direct fetch", expression: /\bfetch\s*\(/ }, + { name: "direct localStorage", expression: /\blocalStorage\.(?:get|set|remove)Item/ }, + { name: "direct import.meta.env", expression: /\bimport\.meta\.env\./ }, + { name: "raw API path", expression: /["']\/api\// }, +]; + +/** @param {string} directory */ +async function scanDirectory(directory) { + const entries = await import("node:fs/promises").then(({ readdir }) => + readdir(directory, { withFileTypes: true }), + ); + for (const entry of entries) { + const target = path.join(directory, entry.name); + if (entry.isDirectory()) { + await scanDirectory(target); + continue; + } + if (!/\.(js|jsx|mjs)$/.test(entry.name)) continue; + const content = await readFile(target, "utf8"); + for (const pattern of adHocPatterns) { + if (pattern.expression.test(content)) { + failures.push(`ad-hoc ${pattern.name} in ${target}`); + } + } + } +} + +for (const sourceDirectory of sourceFiles) { + await scanDirectory(sourceDirectory); +} + +await mkdir("artifacts/quality", { recursive: true }); +await writeFile( + "artifacts/quality/registries.json", + `${JSON.stringify( + { + schemaVersion: 1, + generatedAt: new Date().toISOString(), + compatibilityImpact: governance.compatibilityImpact.current, + failures, + registries: snapshots, + }, + null, + 2, + )}\n`, +); + +if (failures.length > 0) { + process.stderr.write(`Registry governance failed:\n${failures.join("\n")}\n`); + process.exit(1); +} +process.stdout.write(`Registry governance: ${snapshots.length} registries PASS\n`); diff --git a/tests/unit/registry-governance.test.js b/tests/unit/registry-governance.test.js new file mode 100644 index 00000000..ad4688f7 --- /dev/null +++ b/tests/unit/registry-governance.test.js @@ -0,0 +1,21 @@ +import { readFile } from "node:fs/promises"; +import { describe, expect, it } from "vitest"; + +describe("registry governance manifest", () => { + it("declares exactly eight single-owner registries and impact labels", async () => { + const governance = JSON.parse( + await readFile("config/contracts/registry-governance.json", "utf8"), + ); + expect(governance.registries).toHaveLength(8); + expect(new Set(governance.registries.map((entry) => entry.registryId)).size).toBe( + 8, + ); + expect(governance.registries.every((entry) => entry.owner)).toBe(true); + expect(governance.compatibilityImpact.allowed).toEqual([ + "none", + "additive", + "behavior-change", + "breaking", + ]); + }); +}); From 89f3c694131df600fc9dd3c069e35386a773f1e2 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:19:20 +0900 Subject: [PATCH 024/178] feat: govern frontend contract compatibility --- config/compatibility/fixtures.json | 63 +++++++++++++ docs/contracts/compatibility.md | 11 +++ package.json | 3 +- scripts/check-compatibility.mjs | 43 +++++++++ src/application/policies/compatibility.js | 102 ++++++++++++++++++++++ tests/unit/compatibility.test.js | 77 ++++++++++++++++ 6 files changed, 298 insertions(+), 1 deletion(-) create mode 100644 config/compatibility/fixtures.json create mode 100644 docs/contracts/compatibility.md create mode 100644 scripts/check-compatibility.mjs create mode 100644 src/application/policies/compatibility.js create mode 100644 tests/unit/compatibility.test.js diff --git a/config/compatibility/fixtures.json b/config/compatibility/fixtures.json new file mode 100644 index 00000000..fbe5d0c3 --- /dev/null +++ b/config/compatibility/fixtures.json @@ -0,0 +1,63 @@ +{ + "schemaVersion": 1, + "families": { + "api": { + "additive": { + "before": { "required": ["id"], "properties": { "id": {} } }, + "after": { + "required": ["id"], + "properties": { "id": {}, "displayName": {} } + } + }, + "breaking": { + "before": { "required": ["id"], "properties": { "id": {} } }, + "after": { + "required": ["id", "name"], + "properties": { "id": {}, "name": {} } + } + } + }, + "config": { + "additive": { + "before": { "required": ["APP_ENV"], "properties": { "APP_ENV": {} } }, + "after": { + "required": ["APP_ENV"], + "properties": { "APP_ENV": {}, "OPTIONAL_FLAG": {} } + } + }, + "breaking": { + "before": { "required": ["APP_ENV"], "properties": { "APP_ENV": {} } }, + "after": { + "required": ["APP_ENV", "NEW_REQUIRED"], + "properties": { "APP_ENV": {}, "NEW_REQUIRED": {} } + } + } + }, + "storage": { + "additive": { + "before": { "properties": { "theme": {} } }, + "after": { "properties": { "theme": {}, "contrast": {} } } + }, + "breaking": { + "before": { "properties": { "theme": {} } }, + "after": { "properties": {} } + } + }, + "release": { + "additive": { + "before": { "required": ["buildId"], "properties": { "buildId": {} } }, + "after": { + "required": ["buildId"], + "properties": { "buildId": {}, "builtAt": {} } + } + }, + "breaking": { + "before": { "required": ["buildId"], "properties": { "buildId": {} } }, + "after": { + "required": ["buildId", "assetManifestHash"], + "properties": { "buildId": {}, "assetManifestHash": {} } + } + } + } + } +} diff --git a/docs/contracts/compatibility.md b/docs/contracts/compatibility.md new file mode 100644 index 00000000..de3548f8 --- /dev/null +++ b/docs/contracts/compatibility.md @@ -0,0 +1,11 @@ +# Contract compatibility and rollback rules + +The blocking tuple is `(buildId, configSchemaVersion, apiContractVersion, +assetManifestHash, releaseId)`. Versions are parsed numerically. + +1. additive changes preserve current required fields +2. breaking changes require a major version bump +3. persisted cache is discarded unless an explicit tested migration exists +4. an incompatible config or API contract blocks product mount +5. rollback restores HTML, assets, runtime config, API compatibility, and + release manifest as one coherent set diff --git a/package.json b/package.json index 8aecda82..f02955ae 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,8 @@ "generate:supply-chain": "node scripts/generate-supply-chain.mjs", "scan:security": "node scripts/security-scan.mjs", "check:browser-security": "node scripts/check-browser-security.mjs", - "check:registries": "node scripts/check-registries.mjs" + "check:registries": "node scripts/check-registries.mjs", + "verify:compatibility": "node scripts/check-compatibility.mjs" }, "dependencies": { "@tanstack/react-query": "5.101.4", diff --git a/scripts/check-compatibility.mjs b/scripts/check-compatibility.mjs new file mode 100644 index 00000000..2b32bd11 --- /dev/null +++ b/scripts/check-compatibility.mjs @@ -0,0 +1,43 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; + +import { classifyObjectSchemaChange } from "../src/application/policies/compatibility.js"; + +const fixtures = JSON.parse( + await readFile("config/compatibility/fixtures.json", "utf8"), +); +const results = []; + +for (const [family, cases] of Object.entries(fixtures.families)) { + for (const expected of ["additive", "breaking"]) { + const fixture = cases[expected]; + const actual = classifyObjectSchemaChange(fixture.before, fixture.after); + results.push({ family, expected, actual, passed: actual === expected }); + } +} + +await mkdir("artifacts/release", { recursive: true }); +await writeFile( + "artifacts/release/compatibility.json", + `${JSON.stringify( + { + schemaVersion: 1, + generatedAt: new Date().toISOString(), + rules: [ + "additive changes preserve required fields", + "breaking changes require version bump and migration, discard, fallback, or rollback", + "config and API major versions must match", + "incompatible persisted cache is discarded by default", + "rollback uses a coherent compatibility tuple", + ], + results, + }, + null, + 2, + )}\n`, +); + +if (results.some((result) => !result.passed)) { + process.stderr.write("Compatibility fixture classification failed.\n"); + process.exit(1); +} +process.stdout.write("Compatibility fixtures: PASS\n"); diff --git a/src/application/policies/compatibility.js b/src/application/policies/compatibility.js new file mode 100644 index 00000000..a304abd6 --- /dev/null +++ b/src/application/policies/compatibility.js @@ -0,0 +1,102 @@ +export const COMPATIBILITY_TUPLE_FIELDS = Object.freeze([ + "buildId", + "configSchemaVersion", + "apiContractVersion", + "assetManifestHash", + "releaseId", +]); + +/** @param {string} version */ +export function parseNumericVersion(version) { + const match = /^(\d+)(?:\.(\d+))?(?:\.(\d+))?$/.exec(version); + if (!match) return null; + return { + major: Number(match[1]), + minor: Number(match[2] ?? 0), + patch: Number(match[3] ?? 0), + }; +} + +/** @param {string} supported @param {string} actual */ +export function isVersionCompatible(supported, actual) { + const expected = parseNumericVersion(supported); + const candidate = parseNumericVersion(actual); + if (!expected || !candidate) return false; + return ( + expected.major === candidate.major && + candidate.minor >= expected.minor + ); +} + +/** + * @param {{ + * frontend: { + * buildId: string, + * configSchemaVersion: string, + * apiContractVersion: string, + * assetManifestHash: string, + * releaseId: string + * }, + * runtime: { + * buildId: string, + * configSchemaVersion: string, + * apiContractVersion: string, + * assetManifestHash: string, + * releaseId: string + * } + * }} input + */ +export function verifyCompatibilityTuple(input) { + const mismatches = []; + if (input.frontend.buildId !== input.runtime.buildId) mismatches.push("buildId"); + if ( + !isVersionCompatible( + input.frontend.configSchemaVersion, + input.runtime.configSchemaVersion, + ) + ) { + mismatches.push("configSchemaVersion"); + } + if ( + !isVersionCompatible( + input.frontend.apiContractVersion, + input.runtime.apiContractVersion, + ) + ) { + mismatches.push("apiContractVersion"); + } + if (input.frontend.assetManifestHash !== input.runtime.assetManifestHash) { + mismatches.push("assetManifestHash"); + } + + const releaseWarning = + input.frontend.releaseId === input.runtime.releaseId + ? null + : "releaseId"; + return Object.freeze({ + compatible: mismatches.length === 0, + mismatches: Object.freeze(mismatches), + warnings: Object.freeze(releaseWarning ? [releaseWarning] : []), + }); +} + +/** + * @param {{ required?: string[], properties?: Record }} before + * @param {{ required?: string[], properties?: Record }} after + */ +export function classifyObjectSchemaChange(before, after) { + const beforeRequired = new Set(before.required ?? []); + const afterRequired = new Set(after.required ?? []); + const removedProperties = Object.keys(before.properties ?? {}).filter( + (key) => !(key in (after.properties ?? {})), + ); + const addedRequired = [...afterRequired].filter( + (key) => !beforeRequired.has(key), + ); + if (removedProperties.length > 0 || addedRequired.length > 0) return "breaking"; + + const addedProperties = Object.keys(after.properties ?? {}).filter( + (key) => !(key in (before.properties ?? {})), + ); + return addedProperties.length > 0 ? "additive" : "none"; +} diff --git a/tests/unit/compatibility.test.js b/tests/unit/compatibility.test.js new file mode 100644 index 00000000..d46eafcf --- /dev/null +++ b/tests/unit/compatibility.test.js @@ -0,0 +1,77 @@ +import { describe, expect, it } from "vitest"; + +import { + classifyObjectSchemaChange, + isVersionCompatible, + parseNumericVersion, + verifyCompatibilityTuple, +} from "../../src/application/policies/compatibility.js"; + +describe("contract compatibility", () => { + it("uses numeric version parsing rather than lexical comparison", () => { + expect(parseNumericVersion("1.10.0")).toEqual({ major: 1, minor: 10, patch: 0 }); + expect(isVersionCompatible("1.9", "1.10")).toBe(true); + expect(isVersionCompatible("1.9", "2.0")).toBe(false); + expect(isVersionCompatible("next", "1.0")).toBe(false); + }); + + it("distinguishes additive and breaking object changes", () => { + const base = { required: ["id"], properties: { id: {} } }; + expect( + classifyObjectSchemaChange(base, { + required: ["id"], + properties: { id: {}, name: {} }, + }), + ).toBe("additive"); + expect( + classifyObjectSchemaChange(base, { + required: ["id", "name"], + properties: { id: {}, name: {} }, + }), + ).toBe("breaking"); + }); + + it("treats release ID mismatch as a warning when the blocking tuple is coherent", () => { + const frontend = { + buildId: "build-a", + configSchemaVersion: "1.0", + apiContractVersion: "1.0", + assetManifestHash: "hash-a", + releaseId: "release-a", + }; + expect( + verifyCompatibilityTuple({ + frontend, + runtime: { ...frontend, releaseId: "release-b" }, + }), + ).toEqual({ + compatible: true, + mismatches: [], + warnings: ["releaseId"], + }); + }); + + it("blocks mixed build, config, API, or asset tuples", () => { + const frontend = { + buildId: "build-a", + configSchemaVersion: "1.0", + apiContractVersion: "1.0", + assetManifestHash: "hash-a", + releaseId: "release-a", + }; + expect( + verifyCompatibilityTuple({ + frontend, + runtime: { + ...frontend, + buildId: "build-b", + configSchemaVersion: "2.0", + assetManifestHash: "hash-b", + }, + }), + ).toMatchObject({ + compatible: false, + mismatches: ["buildId", "configSchemaVersion", "assetManifestHash"], + }); + }); +}); From eb37cbe8be7f7b0c89ad5b45577df902c8260477 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:22:35 +0900 Subject: [PATCH 025/178] feat: enforce coherent release and rollback contract --- config/contracts/registry-governance.json | 44 +------ config/hosting/cache-policy.json | 31 +++++ config/hosting/response-headers.fixture.json | 35 ++++++ config/release/coherence-fixtures.json | 77 ++++++++++++ .../schemas/release-verification.schema.json | 17 +++ docs/operations/release-cache-rollback.md | 25 ++++ package.json | 4 +- public/release-manifest.json | 11 ++ scripts/generate-build-manifest.mjs | 30 ++++- scripts/verify-hosting-headers.mjs | 110 ++++++++++++++++++ scripts/verify-release.mjs | 87 ++++++++++++++ src/contracts/release-tokens.js | 65 +++++++++++ tests/unit/release-coherence.test.js | 54 +++++++++ 13 files changed, 545 insertions(+), 45 deletions(-) create mode 100644 config/hosting/cache-policy.json create mode 100644 config/hosting/response-headers.fixture.json create mode 100644 config/release/coherence-fixtures.json create mode 100644 config/schemas/release-verification.schema.json create mode 100644 docs/operations/release-cache-rollback.md create mode 100644 public/release-manifest.json create mode 100644 scripts/verify-hosting-headers.mjs create mode 100644 scripts/verify-release.mjs create mode 100644 src/contracts/release-tokens.js create mode 100644 tests/unit/release-coherence.test.js diff --git a/config/contracts/registry-governance.json b/config/contracts/registry-governance.json index a7a0c8c1..d0f24bee 100644 --- a/config/contracts/registry-governance.json +++ b/config/contracts/registry-governance.json @@ -106,49 +106,7 @@ "path": "src/contracts/release-tokens.js", "exportName": "RELEASE_TOKEN_REGISTRY", "owner": "feature-frontend-release-cache-rollback-contract", - "requiredFields": ["token", "source", "compatibilityRole"], - "declaredRows": { - "appVersion": { - "token": "appVersion", - "source": "manifest", - "compatibilityRole": "human release label" - }, - "buildId": { - "token": "buildId", - "source": "CI build", - "compatibilityRole": "asset and HTML coherence" - }, - "commitSha": { - "token": "commitSha", - "source": "VCS", - "compatibilityRole": "source traceability" - }, - "configSchemaVersion": { - "token": "configSchemaVersion", - "source": "runtime config schema", - "compatibilityRole": "boot compatibility" - }, - "apiContractVersion": { - "token": "apiContractVersion", - "source": "frontend/backend agreement", - "compatibilityRole": "schema compatibility" - }, - "assetManifestHash": { - "token": "assetManifestHash", - "source": "build output", - "compatibilityRole": "chunk integrity" - }, - "releaseId": { - "token": "releaseId", - "source": "deploy system", - "compatibilityRole": "rollback target" - }, - "builtAt": { - "token": "builtAt", - "source": "CI", - "compatibilityRole": "diagnostics only" - } - } + "requiredFields": ["token", "source", "compatibilityRole"] } ], "compatibilityImpact": { diff --git a/config/hosting/cache-policy.json b/config/hosting/cache-policy.json new file mode 100644 index 00000000..4730f86a --- /dev/null +++ b/config/hosting/cache-policy.json @@ -0,0 +1,31 @@ +{ + "schemaVersion": 1, + "surfaces": { + "index": { + "path": "/", + "cacheControl": "no-cache", + "securityHeaders": true + }, + "runtimeConfig": { + "path": "/config.json", + "cacheControl": "no-store", + "securityHeaders": true + }, + "releaseManifest": { + "path": "/release-manifest.json", + "cacheControl": "no-store", + "securityHeaders": true + }, + "hashedAsset": { + "pathPattern": "/assets/*", + "cacheControl": "public, max-age=31536000, immutable", + "securityHeaders": false + }, + "sourceMap": { + "public": false + }, + "serviceWorker": { + "enabled": false + } + } +} diff --git a/config/hosting/response-headers.fixture.json b/config/hosting/response-headers.fixture.json new file mode 100644 index 00000000..a7add6e1 --- /dev/null +++ b/config/hosting/response-headers.fixture.json @@ -0,0 +1,35 @@ +{ + "schemaVersion": 1, + "responses": { + "index": { + "cache-control": "no-cache", + "content-security-policy": "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' https:; font-src 'self'; upgrade-insecure-requests", + "strict-transport-security": "max-age=31536000; includeSubDomains", + "x-frame-options": "DENY", + "referrer-policy": "strict-origin-when-cross-origin", + "x-content-type-options": "nosniff", + "permissions-policy": "camera=(), microphone=(), geolocation=()" + }, + "runtimeConfig": { + "cache-control": "no-store", + "content-security-policy": "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' https:; font-src 'self'; upgrade-insecure-requests", + "strict-transport-security": "max-age=31536000; includeSubDomains", + "x-frame-options": "DENY", + "referrer-policy": "strict-origin-when-cross-origin", + "x-content-type-options": "nosniff", + "permissions-policy": "camera=(), microphone=(), geolocation=()" + }, + "releaseManifest": { + "cache-control": "no-store", + "content-security-policy": "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' https:; font-src 'self'; upgrade-insecure-requests", + "strict-transport-security": "max-age=31536000; includeSubDomains", + "x-frame-options": "DENY", + "referrer-policy": "strict-origin-when-cross-origin", + "x-content-type-options": "nosniff", + "permissions-policy": "camera=(), microphone=(), geolocation=()" + }, + "hashedAsset": { + "cache-control": "public, max-age=31536000, immutable" + } + } +} diff --git a/config/release/coherence-fixtures.json b/config/release/coherence-fixtures.json new file mode 100644 index 00000000..c479d22f --- /dev/null +++ b/config/release/coherence-fixtures.json @@ -0,0 +1,77 @@ +{ + "schemaVersion": 1, + "fixtures": [ + { + "name": "coherent-release", + "expectedCompatible": true, + "frontend": { + "buildId": "build-a", + "configSchemaVersion": "1.0", + "apiContractVersion": "1.0", + "assetManifestHash": "assets-a", + "releaseId": "release-a" + }, + "runtime": { + "buildId": "build-a", + "configSchemaVersion": "1.1", + "apiContractVersion": "1.2", + "assetManifestHash": "assets-a", + "releaseId": "release-a" + } + }, + { + "name": "mixed-html-and-assets", + "expectedCompatible": false, + "frontend": { + "buildId": "build-a", + "configSchemaVersion": "1.0", + "apiContractVersion": "1.0", + "assetManifestHash": "assets-a", + "releaseId": "release-a" + }, + "runtime": { + "buildId": "build-b", + "configSchemaVersion": "1.0", + "apiContractVersion": "1.0", + "assetManifestHash": "assets-b", + "releaseId": "release-b" + } + }, + { + "name": "incompatible-runtime-config", + "expectedCompatible": false, + "frontend": { + "buildId": "build-a", + "configSchemaVersion": "1.0", + "apiContractVersion": "1.0", + "assetManifestHash": "assets-a", + "releaseId": "release-a" + }, + "runtime": { + "buildId": "build-a", + "configSchemaVersion": "2.0", + "apiContractVersion": "1.0", + "assetManifestHash": "assets-a", + "releaseId": "release-a" + } + }, + { + "name": "incompatible-api-contract", + "expectedCompatible": false, + "frontend": { + "buildId": "build-a", + "configSchemaVersion": "1.0", + "apiContractVersion": "1.0", + "assetManifestHash": "assets-a", + "releaseId": "release-a" + }, + "runtime": { + "buildId": "build-a", + "configSchemaVersion": "1.0", + "apiContractVersion": "2.0", + "assetManifestHash": "assets-a", + "releaseId": "release-a" + } + } + ] +} diff --git a/config/schemas/release-verification.schema.json b/config/schemas/release-verification.schema.json new file mode 100644 index 00000000..29e5ff78 --- /dev/null +++ b/config/schemas/release-verification.schema.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "ART-FE-003@1", + "type": "object", + "required": ["schemaVersion", "generatedAt", "artifact", "fixtures", "passed"], + "properties": { + "schemaVersion": { "const": 1 }, + "generatedAt": { "type": "string", "format": "date-time" }, + "artifact": { + "type": "object", + "required": ["checked", "compatible", "mismatches"] + }, + "fixtures": { "type": "array", "minItems": 2 }, + "passed": { "type": "boolean" } + }, + "additionalProperties": false +} diff --git a/docs/operations/release-cache-rollback.md b/docs/operations/release-cache-rollback.md new file mode 100644 index 00000000..15ca32ac --- /dev/null +++ b/docs/operations/release-cache-rollback.md @@ -0,0 +1,25 @@ +# Release, cache, and rollback contract + +Each deployment is an immutable `releases//` artifact set. The +provider adapter must upload assets, release manifest, runtime config, and +verify asset reachability before atomically switching the active HTML pointer. +The post-switch boot, route, API, telemetry, and reload-loop smoke checks close +the deployment. + +Rollback selects a prior release tuple, confirms its assets and runtime/API +compatibility, atomically switches the complete set, performs the provider +cache action, and repeats the smoke checks. Rebuilding an old commit, replacing +HTML alone, or declaring recovery from cache-purge completion is prohibited. +Recovery is established by old/new reachability probes. + +The provider-independent cache defaults are: + +- hashed assets: `public, max-age=31536000, immutable` +- HTML: `no-cache` +- runtime config and release manifest: `no-store` +- public source maps: disabled +- service worker/offline cache: disabled + +`corepack pnpm verify:hosting-headers` uses a deterministic fixture locally. +Set `HOSTING_BASE_URL` to probe deployed responses; production promotion +requires the artifact to report `mode: "live"`. diff --git a/package.json b/package.json index f02955ae..f5d6b94f 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,9 @@ "scan:security": "node scripts/security-scan.mjs", "check:browser-security": "node scripts/check-browser-security.mjs", "check:registries": "node scripts/check-registries.mjs", - "verify:compatibility": "node scripts/check-compatibility.mjs" + "verify:compatibility": "node scripts/check-compatibility.mjs", + "verify:release": "node scripts/verify-release.mjs", + "verify:hosting-headers": "node scripts/verify-hosting-headers.mjs" }, "dependencies": { "@tanstack/react-query": "5.101.4", diff --git a/public/release-manifest.json b/public/release-manifest.json new file mode 100644 index 00000000..f316fcd0 --- /dev/null +++ b/public/release-manifest.json @@ -0,0 +1,11 @@ +{ + "schemaVersion": 1, + "appVersion": "0.1.0", + "buildId": "local-build", + "commitSha": "local", + "configSchemaVersion": "1", + "apiContractVersion": "1", + "assetManifestHash": "generated-during-build", + "releaseId": "local-release", + "builtAt": "1970-01-01T00:00:00.000Z" +} diff --git a/scripts/generate-build-manifest.mjs b/scripts/generate-build-manifest.mjs index 7f9a710b..1f3df8ff 100644 --- a/scripts/generate-build-manifest.mjs +++ b/scripts/generate-build-manifest.mjs @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import { mkdir, readFile, writeFile } from "node:fs/promises"; import process from "node:process"; @@ -5,13 +6,23 @@ const packageJson = JSON.parse(await readFile("package.json", "utf8")); const packageManagerVersion = packageJson.packageManager.split("@").at(-1); const buildId = process.env.VITE_BUILD_ID ?? "local-build"; const commitSha = process.env.VITE_COMMIT_SHA ?? "local"; +const releaseId = process.env.RELEASE_ID ?? "local-release"; const runnerImage = process.env.CI_RUNNER_IMAGE ?? `${process.platform}-${process.arch}`; +const builtAt = new Date().toISOString(); +const viteManifest = await readFile("dist/.vite/manifest.json"); +const assetManifestHash = createHash("sha256") + .update(viteManifest) + .digest("hex"); +const runtimeConfig = JSON.parse(await readFile("dist/config.json", "utf8")); + +runtimeConfig.BUILD_ID = buildId; +runtimeConfig.RELEASE_ID = releaseId; const manifest = { schemaVersion: 1, buildId, commitSha, - generatedAt: new Date().toISOString(), + generatedAt: builtAt, buildContext: { nodeVersion: process.version, packageManagerVersion, @@ -23,7 +34,24 @@ const manifest = { }, }; +const releaseManifest = { + schemaVersion: 1, + appVersion: packageJson.version, + buildId, + commitSha, + configSchemaVersion: runtimeConfig.CONFIG_SCHEMA_VERSION, + apiContractVersion: runtimeConfig.API_CONTRACT_VERSION, + assetManifestHash, + releaseId, + builtAt, +}; + await mkdir("artifacts/release", { recursive: true }); +await writeFile("dist/config.json", `${JSON.stringify(runtimeConfig, null, 2)}\n`); +await writeFile( + "dist/release-manifest.json", + `${JSON.stringify(releaseManifest, null, 2)}\n`, +); await writeFile( "artifacts/release/build-manifest.json", `${JSON.stringify(manifest, null, 2)}\n`, diff --git a/scripts/verify-hosting-headers.mjs b/scripts/verify-hosting-headers.mjs new file mode 100644 index 00000000..ee1fc15e --- /dev/null +++ b/scripts/verify-hosting-headers.mjs @@ -0,0 +1,110 @@ +import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; + +const cachePolicy = JSON.parse( + await readFile("config/hosting/cache-policy.json", "utf8"), +); +const securityPolicy = JSON.parse( + await readFile("config/hosting/security-headers.json", "utf8"), +); +const baseUrl = process.env.HOSTING_BASE_URL; + +/** @type {Record>} */ +let responses; +let mode; + +if (baseUrl) { + mode = "live"; + const assets = await readdir("dist/assets"); + const hashedAsset = assets.find((file) => !file.endsWith(".map")); + if (!hashedAsset) throw new Error("No built hashed asset found."); + const paths = { + index: "/", + runtimeConfig: "/config.json", + releaseManifest: "/release-manifest.json", + hashedAsset: `/assets/${hashedAsset}`, + }; + responses = {}; + for (const [surface, pathname] of Object.entries(paths)) { + const response = await fetch(new URL(pathname, baseUrl)); + responses[surface] = Object.fromEntries( + [...response.headers.entries()].map(([name, value]) => [ + name.toLowerCase(), + value, + ]), + ); + } +} else { + mode = "fixture"; + responses = JSON.parse( + await readFile("config/hosting/response-headers.fixture.json", "utf8"), + ).responses; +} + +const results = []; +for (const [surface, policy] of Object.entries(cachePolicy.surfaces)) { + if (!("cacheControl" in policy)) continue; + const observed = responses[surface]?.["cache-control"]; + results.push({ + surface, + header: "cache-control", + expected: policy.cacheControl, + observed, + passed: observed === policy.cacheControl, + }); + if (policy.securityHeaders) { + for (const [header, expected] of Object.entries(securityPolicy.headers)) { + const observedSecurity = responses[surface]?.[header.toLowerCase()]; + results.push({ + surface, + header: header.toLowerCase(), + expected, + observed: observedSecurity, + passed: observedSecurity === expected, + }); + } + } +} + +results.push({ + surface: "sourceMap", + header: "public", + expected: false, + observed: cachePolicy.surfaces.sourceMap.public, + passed: cachePolicy.surfaces.sourceMap.public === false, +}); +results.push({ + surface: "serviceWorker", + header: "enabled", + expected: false, + observed: cachePolicy.surfaces.serviceWorker.enabled, + passed: cachePolicy.surfaces.serviceWorker.enabled === false, +}); + +const passed = results.every((result) => result.passed); +await mkdir("artifacts/release", { recursive: true }); +await writeFile( + "artifacts/release/hosting-headers.json", + `${JSON.stringify( + { + schemaVersion: 1, + generatedAt: new Date().toISOString(), + mode, + baseUrl: baseUrl ?? null, + providerVerificationRequired: mode !== "live", + results, + passed, + }, + null, + 2, + )}\n`, +); + +if (!passed) { + process.stderr.write("Hosting cache/security header verification failed.\n"); + process.exit(1); +} +process.stdout.write( + `Hosting header contract: PASS (${mode}; live verification ${ + mode === "live" ? "complete" : "required before promotion" + })\n`, +); diff --git a/scripts/verify-release.mjs b/scripts/verify-release.mjs new file mode 100644 index 00000000..6ee9cf10 --- /dev/null +++ b/scripts/verify-release.mjs @@ -0,0 +1,87 @@ +import { createHash } from "node:crypto"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; + +import { verifyCompatibilityTuple } from "../src/application/policies/compatibility.js"; +import { compareReleaseToRuntime } from "../src/contracts/release-tokens.js"; + +const fixturesDocument = + /** @type {{ + * fixtures: Array<{ + * name: string, + * expectedCompatible: boolean, + * frontend: { + * buildId: string, + * configSchemaVersion: string, + * apiContractVersion: string, + * assetManifestHash: string, + * releaseId: string + * }, + * runtime: { + * buildId: string, + * configSchemaVersion: string, + * apiContractVersion: string, + * assetManifestHash: string, + * releaseId: string + * } + * }> + * }} */ ( + JSON.parse( + await readFile("config/release/coherence-fixtures.json", "utf8"), + ) + ); +const release = JSON.parse(await readFile("dist/release-manifest.json", "utf8")); +const runtimeConfig = JSON.parse(await readFile("dist/config.json", "utf8")); +const viteManifest = await readFile("dist/.vite/manifest.json"); +const actualAssetManifestHash = createHash("sha256") + .update(viteManifest) + .digest("hex"); + +const artifactComparison = compareReleaseToRuntime(release, runtimeConfig); +const artifactMismatches = [...artifactComparison.mismatches]; +if (release.assetManifestHash !== actualAssetManifestHash) { + artifactMismatches.push("assetManifestContent"); +} + +const fixtures = fixturesDocument.fixtures.map((fixture) => { + const result = verifyCompatibilityTuple({ + frontend: fixture.frontend, + runtime: fixture.runtime, + }); + return { + name: fixture.name, + expectedCompatible: fixture.expectedCompatible, + actualCompatible: result.compatible, + mismatches: result.mismatches, + passed: result.compatible === fixture.expectedCompatible, + }; +}); +const artifact = { + checked: true, + compatible: artifactComparison.compatible && artifactMismatches.length === 0, + mismatches: artifactMismatches, + releaseId: release.releaseId, +}; +const passed = artifact.compatible && fixtures.every((fixture) => fixture.passed); +const report = { + schemaVersion: 1, + generatedAt: new Date().toISOString(), + artifact, + fixtures, + passed, +}; + +await mkdir("artifacts/release", { recursive: true }); +await writeFile( + "artifacts/release/verification.json", + `${JSON.stringify(report, null, 2)}\n`, +); + +if (!passed) { + process.stderr.write( + `Release coherence failed: ${artifactMismatches.join(", ") || "fixture"}\n`, + ); + process.exit(1); +} +process.stdout.write( + `Release coherence: PASS (${fixtures.length - 1} mixed fixtures rejected)\n`, +); diff --git a/src/contracts/release-tokens.js b/src/contracts/release-tokens.js new file mode 100644 index 00000000..8a208178 --- /dev/null +++ b/src/contracts/release-tokens.js @@ -0,0 +1,65 @@ +import { verifyCompatibilityTuple } from "../application/policies/compatibility.js"; + +export const RELEASE_TOKEN_REGISTRY = Object.freeze({ + appVersion: token("appVersion", "manifest", "human release label"), + buildId: token("buildId", "CI build", "asset and HTML coherence"), + commitSha: token("commitSha", "VCS", "source traceability"), + configSchemaVersion: token( + "configSchemaVersion", + "runtime config schema", + "boot compatibility", + ), + apiContractVersion: token( + "apiContractVersion", + "frontend/backend agreement", + "schema compatibility", + ), + assetManifestHash: token( + "assetManifestHash", + "build output", + "chunk integrity and mismatch detection", + ), + releaseId: token("releaseId", "deploy system", "rollback target"), + builtAt: token("builtAt", "CI", "diagnostics only; never cache identity"), +}); + +/** + * @param {string} name + * @param {string} source + * @param {string} compatibilityRole + */ +function token(name, source, compatibilityRole) { + return Object.freeze({ token: name, source, compatibilityRole }); +} + +/** + * Compare a release manifest and runtime configuration structurally. Version + * fields are delegated to the numeric compatibility policy, never compared + * lexically. + * + * @param {{ + * buildId: string, + * configSchemaVersion: string, + * apiContractVersion: string, + * assetManifestHash: string, + * releaseId: string + * }} release + * @param {{ + * BUILD_ID: string, + * CONFIG_SCHEMA_VERSION: string, + * API_CONTRACT_VERSION: string, + * RELEASE_ID: string + * }} runtimeConfig + */ +export function compareReleaseToRuntime(release, runtimeConfig) { + return verifyCompatibilityTuple({ + frontend: release, + runtime: { + buildId: runtimeConfig.BUILD_ID, + configSchemaVersion: runtimeConfig.CONFIG_SCHEMA_VERSION, + apiContractVersion: runtimeConfig.API_CONTRACT_VERSION, + assetManifestHash: release.assetManifestHash, + releaseId: runtimeConfig.RELEASE_ID, + }, + }); +} diff --git a/tests/unit/release-coherence.test.js b/tests/unit/release-coherence.test.js new file mode 100644 index 00000000..c8ccd83c --- /dev/null +++ b/tests/unit/release-coherence.test.js @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vitest"; + +import { + compareReleaseToRuntime, + RELEASE_TOKEN_REGISTRY, +} from "../../src/contracts/release-tokens.js"; + +describe("release coherence", () => { + it("owns all eight release tokens and keeps builtAt diagnostic-only", () => { + expect(Object.keys(RELEASE_TOKEN_REGISTRY)).toHaveLength(8); + expect(RELEASE_TOKEN_REGISTRY.builtAt.compatibilityRole).toContain( + "never cache identity", + ); + }); + + it("compares the runtime config to the release structurally", () => { + const release = { + buildId: "build-a", + configSchemaVersion: "1.0", + apiContractVersion: "1.0", + assetManifestHash: "assets-a", + releaseId: "release-a", + }; + expect( + compareReleaseToRuntime(release, { + BUILD_ID: "build-a", + CONFIG_SCHEMA_VERSION: "1.2", + API_CONTRACT_VERSION: "1.1", + RELEASE_ID: "release-a", + }), + ).toMatchObject({ compatible: true, mismatches: [] }); + }); + + it("rejects HTML-only rollback against a newer runtime config", () => { + const oldRelease = { + buildId: "build-old", + configSchemaVersion: "1.0", + apiContractVersion: "1.0", + assetManifestHash: "assets-old", + releaseId: "release-old", + }; + expect( + compareReleaseToRuntime(oldRelease, { + BUILD_ID: "build-new", + CONFIG_SCHEMA_VERSION: "2.0", + API_CONTRACT_VERSION: "2.0", + RELEASE_ID: "release-new", + }), + ).toMatchObject({ + compatible: false, + mismatches: ["buildId", "configSchemaVersion", "apiContractVersion"], + }); + }); +}); From b1625252d5acfc8f04fa665a58cf1fa55b3be3a4 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:26:51 +0900 Subject: [PATCH 026/178] feat: enforce web vitals performance budgets --- config/performance/budgets.json | 18 +++ config/performance/field-input.example.json | 5 + config/schemas/field-web-vitals.schema.json | 34 ++++ config/schemas/lab-performance.schema.json | 30 ++++ docs/operations/performance-evidence.md | 17 ++ package.json | 5 +- scripts/check-bundle.mjs | 93 +++++++++++ scripts/collect-web-vitals-evidence.mjs | 102 ++++++++++++ scripts/test-performance.mjs | 148 ++++++++++++++++++ .../policies/performance-budgets.js | 96 ++++++++++++ tests/unit/performance-budgets.test.js | 77 +++++++++ 11 files changed, 624 insertions(+), 1 deletion(-) create mode 100644 config/performance/budgets.json create mode 100644 config/performance/field-input.example.json create mode 100644 config/schemas/field-web-vitals.schema.json create mode 100644 config/schemas/lab-performance.schema.json create mode 100644 docs/operations/performance-evidence.md create mode 100644 scripts/check-bundle.mjs create mode 100644 scripts/collect-web-vitals-evidence.mjs create mode 100644 scripts/test-performance.mjs create mode 100644 src/application/policies/performance-budgets.js create mode 100644 tests/unit/performance-budgets.test.js diff --git a/config/performance/budgets.json b/config/performance/budgets.json new file mode 100644 index 00000000..adf9cc73 --- /dev/null +++ b/config/performance/budgets.json @@ -0,0 +1,18 @@ +{ + "schemaVersion": 1, + "bundle": { + "initialJsGzipBytes": 204800, + "lazyChunkGzipBytes": 122880 + }, + "lab": { + "lcpMs": 2500, + "cls": 0.1, + "namedInteractionMs": 200 + }, + "field": { + "p75LcpMs": 2500, + "p75Cls": 0.1, + "p75InpMs": 200, + "minimumEligibleSamples": null + } +} diff --git a/config/performance/field-input.example.json b/config/performance/field-input.example.json new file mode 100644 index 00000000..9223dae2 --- /dev/null +++ b/config/performance/field-input.example.json @@ -0,0 +1,5 @@ +{ + "schemaVersion": 1, + "releaseId": "local-release", + "samples": [] +} diff --git a/config/schemas/field-web-vitals.schema.json b/config/schemas/field-web-vitals.schema.json new file mode 100644 index 00000000..d63048c9 --- /dev/null +++ b/config/schemas/field-web-vitals.schema.json @@ -0,0 +1,34 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "ART-FE-FIELD-WEB-VITALS@1", + "type": "object", + "required": [ + "schemaVersion", + "generatedAt", + "window", + "context", + "metrics", + "eligibility", + "status", + "passed" + ], + "properties": { + "schemaVersion": { "const": 1 }, + "generatedAt": { "type": "string", "format": "date-time" }, + "window": { "type": "object", "required": ["days", "start", "end"] }, + "context": { + "type": "object", + "required": ["source", "network", "routeAggregation", "releaseId"] + }, + "metrics": { "type": "object" }, + "eligibility": { + "type": "object", + "required": ["consentRequired", "eligibleSamples", "minimumEligibleSamples"] + }, + "status": { + "enum": ["PASS", "FAIL_THRESHOLD", "FAIL_UNVERIFIED"] + }, + "passed": { "type": "boolean" } + }, + "additionalProperties": false +} diff --git a/config/schemas/lab-performance.schema.json b/config/schemas/lab-performance.schema.json new file mode 100644 index 00000000..878b9f33 --- /dev/null +++ b/config/schemas/lab-performance.schema.json @@ -0,0 +1,30 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "ART-FE-LAB@1", + "type": "object", + "required": [ + "schemaVersion", + "generatedAt", + "context", + "metrics", + "thresholds", + "fixtures", + "passed" + ], + "properties": { + "schemaVersion": { "const": 1 }, + "generatedAt": { "type": "string", "format": "date-time" }, + "context": { + "type": "object", + "required": ["runner", "browser", "viewport", "network", "cpu", "cache", "build"] + }, + "metrics": { + "type": "object", + "required": ["lcpMs", "cls", "namedInteractionMs"] + }, + "thresholds": { "type": "object" }, + "fixtures": { "type": "array", "minItems": 2 }, + "passed": { "type": "boolean" } + }, + "additionalProperties": false +} diff --git a/docs/operations/performance-evidence.md b/docs/operations/performance-evidence.md new file mode 100644 index 00000000..29864cef --- /dev/null +++ b/docs/operations/performance-evidence.md @@ -0,0 +1,17 @@ +# Performance evidence contract + +Performance evidence is deliberately split by measurement context: + +- `bundle.json` records production build output and enforces initial JavaScript + at 200 KiB gzip and every lazy chunk at 120 KiB gzip. +- `lab.json` records Chromium/runner/viewport/network/CPU/cache/build context and + enforces LCP 2.5 s, CLS 0.10, and the named route interaction at 200 ms. +- `field-web-vitals.json` records consent-filtered, route-ID aggregated, + release-specific production samples over 28 days and evaluates p75 LCP, CLS, + and INP against 2.5 s, 0.10, and 200 ms. + +The field minimum eligible-sample threshold is intentionally unresolved until +a privacy-approved telemetry baseline exists. Therefore the field command +fails closed with `FAIL_UNVERIFIED` when run against the example input. Provide +`FIELD_WEB_VITALS_INPUT` and a reviewed `MIN_ELIGIBLE_SAMPLES` only after that +decision is recorded. diff --git a/package.json b/package.json index f5d6b94f..52d7ad53 100644 --- a/package.json +++ b/package.json @@ -33,7 +33,10 @@ "check:registries": "node scripts/check-registries.mjs", "verify:compatibility": "node scripts/check-compatibility.mjs", "verify:release": "node scripts/verify-release.mjs", - "verify:hosting-headers": "node scripts/verify-hosting-headers.mjs" + "verify:hosting-headers": "node scripts/verify-hosting-headers.mjs", + "check:bundle": "node scripts/generate-supply-chain.mjs && node scripts/check-bundle.mjs", + "test:performance": "node scripts/test-performance.mjs", + "collect:web-vitals-evidence": "node scripts/collect-web-vitals-evidence.mjs" }, "dependencies": { "@tanstack/react-query": "5.101.4", diff --git a/scripts/check-bundle.mjs b/scripts/check-bundle.mjs new file mode 100644 index 00000000..e2fdf846 --- /dev/null +++ b/scripts/check-bundle.mjs @@ -0,0 +1,93 @@ +import { readFile, writeFile } from "node:fs/promises"; + +import { evaluateBundleBudget } from "../src/application/policies/performance-budgets.js"; + +const report = + /** @type {{ + * outputs: Array<{ path: string, gzipBytes: number }>, + * [key: string]: unknown + * }} */ ( + JSON.parse(await readFile("artifacts/performance/bundle.json", "utf8")) + ); +const viteManifest = + /** @type {Record} */ ( + JSON.parse(await readFile("dist/.vite/manifest.json", "utf8")) + ); +const budgets = + /** @type {{ initialJsGzipBytes: number, lazyChunkGzipBytes: number }} */ ( + JSON.parse(await readFile("config/performance/budgets.json", "utf8")).bundle + ); + +const outputByPath = new Map( + report.outputs.map((output) => [output.path.replace(/^dist\//, ""), output]), +); +const initialFiles = new Set( + Object.values(viteManifest) + .filter((entry) => entry.isEntry) + .map((entry) => entry.file), +); +const lazyFiles = new Set( + Object.values(viteManifest) + .filter((entry) => !entry.isEntry && entry.file.endsWith(".js")) + .map((entry) => entry.file), +); +const initialJsGzipBytes = [...initialFiles].reduce( + (total, file) => total + (outputByPath.get(file)?.gzipBytes ?? 0), + 0, +); +const lazyChunks = [...lazyFiles].map((file) => ({ + path: file, + gzipBytes: outputByPath.get(file)?.gzipBytes ?? 0, +})); +const measurements = { initialJsGzipBytes, lazyChunks }; +const result = evaluateBundleBudget(measurements, budgets); +const fixtures = [ + { + name: "initial-js-over-budget", + passed: + !evaluateBundleBudget( + { + initialJsGzipBytes: budgets.initialJsGzipBytes + 1, + lazyChunks: [], + }, + budgets, + ).passed, + }, + { + name: "lazy-chunk-over-budget", + passed: + !evaluateBundleBudget( + { + initialJsGzipBytes: 0, + lazyChunks: [ + { + path: "fixture.js", + gzipBytes: budgets.lazyChunkGzipBytes + 1, + }, + ], + }, + budgets, + ).passed, + }, +]; +const passed = result.passed && fixtures.every((fixture) => fixture.passed); +const completedReport = { + ...report, + measurements, + thresholds: budgets, + results: result, + fixtures, + passed, +}; + +await writeFile( + "artifacts/performance/bundle.json", + `${JSON.stringify(completedReport, null, 2)}\n`, +); +if (!passed) { + process.stderr.write("Bundle budget exceeded.\n"); + process.exit(1); +} +process.stdout.write( + `Bundle budget: PASS (initial JS ${initialJsGzipBytes} / ${budgets.initialJsGzipBytes} gzip bytes)\n`, +); diff --git a/scripts/collect-web-vitals-evidence.mjs b/scripts/collect-web-vitals-evidence.mjs new file mode 100644 index 00000000..4eac58c9 --- /dev/null +++ b/scripts/collect-web-vitals-evidence.mjs @@ -0,0 +1,102 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; + +import { + evaluateFieldBudget, + percentile75, +} from "../src/application/policies/performance-budgets.js"; + +const inputPath = + process.env.FIELD_WEB_VITALS_INPUT ?? + "config/performance/field-input.example.json"; +const input = + /** @type {{ + * releaseId: string, + * samples: Array<{ + * timestamp: string, + * consent: boolean, + * releaseId: string, + * routeId: string, + * lcpMs: number, + * cls: number, + * inpMs: number + * }> + * }} */ (JSON.parse(await readFile(inputPath, "utf8"))); +const configured = + /** @type {{ + * p75LcpMs: number, + * p75Cls: number, + * p75InpMs: number, + * minimumEligibleSamples: number | null + * }} */ ( + JSON.parse(await readFile("config/performance/budgets.json", "utf8")).field + ); +const minimumEligibleSamples = process.env.MIN_ELIGIBLE_SAMPLES + ? Number(process.env.MIN_ELIGIBLE_SAMPLES) + : configured.minimumEligibleSamples; +const end = new Date(); +const start = new Date(end); +start.setUTCDate(start.getUTCDate() - 28); +const eligible = input.samples.filter((sample) => { + const timestamp = new Date(sample.timestamp); + return ( + sample.consent === true && + sample.releaseId === input.releaseId && + timestamp >= start && + timestamp <= end + ); +}); +const metrics = { + p75LcpMs: percentile75(eligible.map((sample) => sample.lcpMs)), + p75Cls: percentile75(eligible.map((sample) => sample.cls)), + p75InpMs: percentile75(eligible.map((sample) => sample.inpMs)), +}; +const thresholds = { ...configured, minimumEligibleSamples }; +const result = evaluateFieldBudget( + { metrics, eligibleSamples: eligible.length }, + thresholds, +); +const routeSamples = Object.fromEntries( + Object.entries( + eligible.reduce( + (counts, sample) => { + counts[sample.routeId] = (counts[sample.routeId] ?? 0) + 1; + return counts; + }, + /** @type {Record} */ ({}), + ), + ).sort(([left], [right]) => left.localeCompare(right)), +); +const report = { + schemaVersion: 1, + generatedAt: end.toISOString(), + window: { days: 28, start: start.toISOString(), end: end.toISOString() }, + context: { + source: inputPath, + network: "production-real-user", + routeAggregation: "route-id-only", + releaseId: input.releaseId, + }, + metrics, + thresholds, + eligibility: { + consentRequired: true, + eligibleSamples: eligible.length, + minimumEligibleSamples, + routeSamples, + }, + status: result.status, + passed: result.passed, +}; + +await mkdir("artifacts/performance", { recursive: true }); +await writeFile( + "artifacts/performance/field-web-vitals.json", + `${JSON.stringify(report, null, 2)}\n`, +); +if (!result.passed) { + process.stderr.write( + `Field Web Vitals: ${result.status} (minimum eligible sample threshold and 28-day production data are required)\n`, + ); + process.exit(1); +} +process.stdout.write("Field Web Vitals: PASS\n"); diff --git a/scripts/test-performance.mjs b/scripts/test-performance.mjs new file mode 100644 index 00000000..6f5eb4a0 --- /dev/null +++ b/scripts/test-performance.mjs @@ -0,0 +1,148 @@ +import { spawn } from "node:child_process"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { performance } from "node:perf_hooks"; +import process from "node:process"; + +import { chromium } from "@playwright/test"; + +import { evaluateLabBudget } from "../src/application/policies/performance-budgets.js"; + +const server = spawn( + "corepack", + ["pnpm", "preview", "--host", "127.0.0.1", "--port", "4173"], + { stdio: "ignore" }, +); +const baseUrl = "http://127.0.0.1:4173"; + +async function waitForServer() { + for (let attempt = 0; attempt < 50; attempt += 1) { + try { + const response = await fetch(baseUrl); + if (response.ok) return; + } catch { + // The bounded retry loop handles startup races. + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } + throw new Error("Preview server did not become ready."); +} + +try { + await waitForServer(); + const release = JSON.parse( + await readFile("dist/release-manifest.json", "utf8"), + ); + const thresholds = JSON.parse( + await readFile("config/performance/budgets.json", "utf8"), + ).lab; + const browser = await chromium.launch(); + try { + const context = await browser.newContext({ + viewport: { width: 1280, height: 720 }, + }); + const page = await context.newPage(); + const cdp = await context.newCDPSession(page); + await cdp.send("Network.enable"); + await cdp.send("Network.emulateNetworkConditions", { + offline: false, + latency: 40, + downloadThroughput: 200_000, + uploadThroughput: 93_750, + connectionType: "cellular4g", + }); + await cdp.send("Emulation.setCPUThrottlingRate", { rate: 4 }); + await page.addInitScript(() => { + const evidence = { lcpMs: 0, cls: 0 }; + /** @type {any} */ (window).__contractPerformance = evidence; + new PerformanceObserver((list) => { + for (const entry of list.getEntries()) evidence.lcpMs = entry.startTime; + }).observe({ type: "largest-contentful-paint", buffered: true }); + new PerformanceObserver((list) => { + for (const entry of list.getEntries()) { + if (!(/** @type {any} */ (entry)).hadRecentInput) { + evidence.cls += /** @type {any} */ (entry).value; + } + } + }).observe({ type: "layout-shift", buffered: true }); + }); + await page.goto(baseUrl, { waitUntil: "networkidle" }); + const interactionStarted = performance.now(); + await page.getByRole("link", { name: "샘플 리소스" }).click(); + await page.getByRole("heading", { name: "세션이 필요합니다." }).waitFor(); + const namedInteractionMs = performance.now() - interactionStarted; + const paint = await page.evaluate( + () => /** @type {any} */ (window).__contractPerformance, + ); + const contextMetadata = { + runner: { + platform: process.platform, + architecture: process.arch, + nodeVersion: process.version, + }, + browser: { name: "chromium", version: await browser.version() }, + viewport: { width: 1280, height: 720 }, + network: { + profile: "contract-fast-4g", + latencyMs: 40, + downloadBytesPerSecond: 200_000, + uploadBytesPerSecond: 93_750, + }, + cpu: { throttlingRate: 4 }, + cache: { state: "cold", isolation: "new-browser-context" }, + build: { buildId: release.buildId, releaseId: release.releaseId }, + }; + const metrics = { + lcpMs: Math.round(paint.lcpMs), + cls: Number(paint.cls.toFixed(4)), + namedInteractionMs: Math.round(namedInteractionMs), + }; + const result = evaluateLabBudget( + { context: contextMetadata, metrics }, + thresholds, + ); + const fixtures = [ + { + name: "missing-context", + passed: !evaluateLabBudget({ metrics }, thresholds).passed, + }, + { + name: "lcp-over-threshold", + passed: !evaluateLabBudget( + { + context: contextMetadata, + metrics: { ...metrics, lcpMs: thresholds.lcpMs + 1 }, + }, + thresholds, + ).passed, + }, + ]; + const passed = result.passed && fixtures.every((fixture) => fixture.passed); + await mkdir("artifacts/performance", { recursive: true }); + await writeFile( + "artifacts/performance/lab.json", + `${JSON.stringify( + { + schemaVersion: 1, + generatedAt: new Date().toISOString(), + context: contextMetadata, + metrics, + thresholds, + fixtures, + passed, + }, + null, + 2, + )}\n`, + ); + if (!passed) { + throw new Error(`Lab performance failed: ${JSON.stringify(metrics)}`); + } + process.stdout.write( + `Lab performance: PASS (LCP ${metrics.lcpMs}ms, CLS ${metrics.cls}, interaction ${metrics.namedInteractionMs}ms)\n`, + ); + } finally { + await browser.close(); + } +} finally { + server.kill("SIGTERM"); +} diff --git a/src/application/policies/performance-budgets.js b/src/application/policies/performance-budgets.js new file mode 100644 index 00000000..3c2b411e --- /dev/null +++ b/src/application/policies/performance-budgets.js @@ -0,0 +1,96 @@ +/** + * @param {{ + * initialJsGzipBytes: number, + * lazyChunks: Array<{ path: string, gzipBytes: number }> + * }} measurements + * @param {{ initialJsGzipBytes: number, lazyChunkGzipBytes: number }} thresholds + */ +export function evaluateBundleBudget(measurements, thresholds) { + const initialPassed = + measurements.initialJsGzipBytes <= thresholds.initialJsGzipBytes; + const lazyResults = measurements.lazyChunks.map((chunk) => ({ + ...chunk, + threshold: thresholds.lazyChunkGzipBytes, + passed: chunk.gzipBytes <= thresholds.lazyChunkGzipBytes, + })); + return Object.freeze({ + initialPassed, + lazyResults: Object.freeze(lazyResults), + passed: initialPassed && lazyResults.every((chunk) => chunk.passed), + }); +} + +/** + * @param {{ + * context?: Record, + * metrics: { lcpMs: number, cls: number, namedInteractionMs: number } + * }} report + * @param {{ lcpMs: number, cls: number, namedInteractionMs: number }} thresholds + */ +export function evaluateLabBudget(report, thresholds) { + const requiredContext = [ + "runner", + "browser", + "viewport", + "network", + "cpu", + "cache", + "build", + ]; + const missingContext = requiredContext.filter( + (field) => report.context?.[field] === undefined, + ); + const results = { + lcp: report.metrics.lcpMs <= thresholds.lcpMs, + cls: report.metrics.cls <= thresholds.cls, + namedInteraction: + report.metrics.namedInteractionMs <= thresholds.namedInteractionMs, + }; + return Object.freeze({ + missingContext: Object.freeze(missingContext), + results: Object.freeze(results), + passed: missingContext.length === 0 && Object.values(results).every(Boolean), + }); +} + +/** @param {number[]} values */ +export function percentile75(values) { + if (values.length === 0) return null; + const sorted = [...values].sort((left, right) => left - right); + return sorted[Math.ceil(sorted.length * 0.75) - 1]; +} + +/** + * @param {{ + * metrics: { p75LcpMs: number | null, p75Cls: number | null, p75InpMs: number | null }, + * eligibleSamples: number + * }} report + * @param {{ + * p75LcpMs: number, + * p75Cls: number, + * p75InpMs: number, + * minimumEligibleSamples: number | null + * }} thresholds + */ +export function evaluateFieldBudget(report, thresholds) { + if ( + thresholds.minimumEligibleSamples === null || + report.eligibleSamples < thresholds.minimumEligibleSamples || + Object.values(report.metrics).some((value) => value === null) + ) { + return Object.freeze({ + status: /** @type {const} */ ("FAIL_UNVERIFIED"), + passed: false, + }); + } + const passed = + /** @type {number} */ (report.metrics.p75LcpMs) <= thresholds.p75LcpMs && + /** @type {number} */ (report.metrics.p75Cls) <= thresholds.p75Cls && + /** @type {number} */ (report.metrics.p75InpMs) <= thresholds.p75InpMs; + return Object.freeze({ + status: passed + ? /** @type {const} */ ("PASS") + : /** @type {const} */ ("FAIL_THRESHOLD"), + passed, + }); +} diff --git a/tests/unit/performance-budgets.test.js b/tests/unit/performance-budgets.test.js new file mode 100644 index 00000000..774382d0 --- /dev/null +++ b/tests/unit/performance-budgets.test.js @@ -0,0 +1,77 @@ +import { describe, expect, it } from "vitest"; + +import { + evaluateBundleBudget, + evaluateFieldBudget, + evaluateLabBudget, + percentile75, +} from "../../src/application/policies/performance-budgets.js"; + +describe("performance budgets", () => { + it("rejects initial and lazy JavaScript above their named limits", () => { + const thresholds = { + initialJsGzipBytes: 200, + lazyChunkGzipBytes: 120, + }; + expect( + evaluateBundleBudget( + { initialJsGzipBytes: 201, lazyChunks: [] }, + thresholds, + ).passed, + ).toBe(false); + expect( + evaluateBundleBudget( + { + initialJsGzipBytes: 100, + lazyChunks: [{ path: "lazy.js", gzipBytes: 121 }], + }, + thresholds, + ).passed, + ).toBe(false); + }); + + it("fails lab evidence when context is absent or a metric is over budget", () => { + const thresholds = { lcpMs: 2500, cls: 0.1, namedInteractionMs: 200 }; + expect( + evaluateLabBudget( + { metrics: { lcpMs: 1000, cls: 0, namedInteractionMs: 50 } }, + thresholds, + ), + ).toMatchObject({ passed: false }); + expect( + evaluateLabBudget( + { + context: { + runner: {}, + browser: {}, + viewport: {}, + network: {}, + cpu: {}, + cache: {}, + build: {}, + }, + metrics: { lcpMs: 2501, cls: 0, namedInteractionMs: 50 }, + }, + thresholds, + ).passed, + ).toBe(false); + }); + + it("uses the nearest-rank p75 and fails closed while sample minimum is deferred", () => { + expect(percentile75([4, 1, 3, 2])).toBe(3); + expect( + evaluateFieldBudget( + { + metrics: { p75LcpMs: 1000, p75Cls: 0.01, p75InpMs: 50 }, + eligibleSamples: 100, + }, + { + p75LcpMs: 2500, + p75Cls: 0.1, + p75InpMs: 200, + minimumEligibleSamples: null, + }, + ), + ).toEqual({ status: "FAIL_UNVERIFIED", passed: false }); + }); +}); From 75c3f5b08ca96c864d74f3bda6d40a2af08407fc Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:30:40 +0900 Subject: [PATCH 027/178] feat: operationalize frontend incident runbooks --- config/runbooks/runbooks.json | 93 ++++++ .../schemas/runbook-drill-record.schema.json | 42 +++ docs/runbooks/FE-RB-001.md | 9 + docs/runbooks/FE-RB-002.md | 11 + docs/runbooks/FE-RB-003.md | 10 + docs/runbooks/FE-RB-004.md | 9 + docs/runbooks/FE-RB-005.md | 13 + package.json | 4 +- scripts/drill-runbook.mjs | 309 ++++++++++++++++++ tests/unit/runbook-contract.test.js | 39 +++ 10 files changed, 538 insertions(+), 1 deletion(-) create mode 100644 config/runbooks/runbooks.json create mode 100644 config/schemas/runbook-drill-record.schema.json create mode 100644 docs/runbooks/FE-RB-001.md create mode 100644 docs/runbooks/FE-RB-002.md create mode 100644 docs/runbooks/FE-RB-003.md create mode 100644 docs/runbooks/FE-RB-004.md create mode 100644 docs/runbooks/FE-RB-005.md create mode 100644 scripts/drill-runbook.mjs create mode 100644 tests/unit/runbook-contract.test.js diff --git a/config/runbooks/runbooks.json b/config/runbooks/runbooks.json new file mode 100644 index 00000000..ef120df3 --- /dev/null +++ b/config/runbooks/runbooks.json @@ -0,0 +1,93 @@ +{ + "schemaVersion": 1, + "runbooks": { + "FE-RB-001": { + "title": "Boot configuration failure", + "gateId": "FE-GATE-021", + "triggerKinds": ["BOOT_CONFIG_FAILURE"], + "containment": "stop product route mount, show the safe support shell, and refetch at most once", + "window": "owner triage planned-default 5m", + "escalation": ["env-config owner", "release owner"], + "recoveryEvidence": [ + "clean-session boot", + "product root mount", + "config validation", + "no repeated boot error" + ], + "negativeFixture": "a valid config followed by an injected mount failure must fail recovery" + }, + "FE-RB-002": { + "title": "Chunk, manifest, or deployment mismatch", + "gateId": "FE-GATE-022", + "triggerKinds": [ + "CHUNK_LOAD_FAILURE", + "RELEASE_MANIFEST_FAILURE", + "DEPLOY_MISMATCH" + ], + "containment": "warn for dirty state, fetch manifest no-store once, and allow one guarded reload", + "window": "release owner triage planned-default 5m", + "escalation": ["release-cache owner", "hosting/CDN owner"], + "recoveryEvidence": [ + "entry and lazy assets reachable", + "release tuple coherent", + "second reload blocked", + "critical route smoke" + ], + "negativeFixture": "a second failure for the same release pair must not reload" + }, + "FE-RB-003": { + "title": "Backend API degradation", + "gateId": "FE-GATE-023", + "triggerKinds": [ + "TERMINAL_NETWORK_RATE", + "REQUEST_TIMEOUT_RATE", + "SERVER_FAILURE_RATE", + "SCHEMA_MISMATCH" + ], + "containment": "do not expand retry caps, serve safe stale reads, and never retry an unkeyed mutation", + "window": "rolling 5m trigger; first classification planned-default 10m", + "escalation": [ + "api-client owner", + "backend operation owner", + "release compatibility owner" + ], + "recoveryEvidence": [ + "terminal failure rate at baseline", + "no retry amplification", + "critical read/write smoke", + "schema fixtures" + ], + "negativeFixture": "an unkeyed POST receiving 503 must not retry" + }, + "FE-RB-004": { + "title": "Telemetry sink failure", + "gateId": "FE-GATE-024", + "triggerKinds": ["TELEMETRY_FAILURE"], + "containment": "keep product flow available, bound the queue, and never report recursively to the failing sink", + "window": "platform triage planned-default 15m", + "escalation": ["observability owner", "telemetry platform owner"], + "recoveryEvidence": [ + "product flow unaffected", + "delivery self-check", + "queue drained within bound", + "forbidden attributes absent" + ], + "negativeFixture": "raw URL and query data must be removed from telemetry" + }, + "FE-RB-005": { + "title": "Coherent release rollback", + "gateId": "FE-GATE-025", + "triggerKinds": ["RELEASE_BLOCKING_DEFECT"], + "containment": "select a prior immutable tuple, verify asset/config/API compatibility, atomically switch, and smoke", + "window": "provider recovery target TBD", + "escalation": ["release-cache owner", "release approver/hosting owner"], + "recoveryEvidence": [ + "compatibility gate", + "release coherence gate", + "critical smoke", + "release ID in incident timeline" + ], + "negativeFixture": "HTML build A with asset manifest B must be rejected" + } + } +} diff --git a/config/schemas/runbook-drill-record.schema.json b/config/schemas/runbook-drill-record.schema.json new file mode 100644 index 00000000..d58daba3 --- /dev/null +++ b/config/schemas/runbook-drill-record.schema.json @@ -0,0 +1,42 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "ART-FE-RUNBOOK-DRILL@1", + "type": "object", + "required": [ + "schemaVersion", + "runbookId", + "releaseId", + "drillTimestamp", + "triggerInjected", + "triggerAsserted", + "containmentAsserted", + "escalationPathAsserted", + "recoveryAssertions", + "negativeFixtureFailedAsExpected", + "windowObservedBucket", + "passed" + ], + "properties": { + "schemaVersion": { "const": 1 }, + "runbookId": { "pattern": "^FE-RB-00[1-5]$" }, + "releaseId": { "type": "string", "minLength": 1 }, + "drillTimestamp": { "type": "string", "format": "date-time" }, + "triggerInjected": { "type": "string" }, + "triggerAsserted": { "type": "boolean" }, + "containmentAsserted": { "type": "boolean" }, + "escalationPathAsserted": { "type": "boolean" }, + "recoveryAssertions": { + "type": "array", + "minItems": 4, + "items": { + "type": "object", + "required": ["assertion", "evidence", "passed"] + } + }, + "negativeFixtureFailedAsExpected": { "type": "boolean" }, + "windowObservedBucket": { "type": "string" }, + "providerVerificationRequired": { "type": "boolean" }, + "passed": { "type": "boolean" } + }, + "additionalProperties": false +} diff --git a/docs/runbooks/FE-RB-001.md b/docs/runbooks/FE-RB-001.md new file mode 100644 index 00000000..c40abd1e --- /dev/null +++ b/docs/runbooks/FE-RB-001.md @@ -0,0 +1,9 @@ +# FE-RB-001 — Boot configuration failure + +Trigger on `BOOT_CONFIG_FAILURE` after the single bounded refetch fails. Stop +product route mounting and show the safe support shell; the planned owner +triage target is five minutes. Escalate from the environment/config owner to +the release owner. + +Close only after a clean-session boot mounts the product root, config +validation evidence passes, and repeated boot-error telemetry is absent. diff --git a/docs/runbooks/FE-RB-002.md b/docs/runbooks/FE-RB-002.md new file mode 100644 index 00000000..ff522c56 --- /dev/null +++ b/docs/runbooks/FE-RB-002.md @@ -0,0 +1,11 @@ +# FE-RB-002 — Chunk or deployment mismatch + +Trigger on `CHUNK_LOAD_FAILURE`, `RELEASE_MANIFEST_FAILURE`, or +`DEPLOY_MISMATCH`. Warn when dirty state may be lost, fetch the manifest +`no-store` once, record the release pair, and allow only one reload. The +planned release-owner triage target is five minutes. Escalate to the hosting/CDN +owner. + +Close only after entry/lazy assets are reachable, the manifest parses into a +coherent tuple, a second automatic reload is blocked, and the critical route +smoke passes. diff --git a/docs/runbooks/FE-RB-003.md b/docs/runbooks/FE-RB-003.md new file mode 100644 index 00000000..79ad1962 --- /dev/null +++ b/docs/runbooks/FE-RB-003.md @@ -0,0 +1,10 @@ +# FE-RB-003 — Backend API degradation + +Trigger when terminal network/timeout/5xx failures exceed the rolling +five-minute threshold or on one `SCHEMA_MISMATCH`. Do not expand client retry +caps, do not retry schema mismatches, and never retry an unkeyed mutation. +Escalate from the API client owner to backend operations and then release +compatibility; the planned first-classification target is ten minutes. + +Close only after the failure rate returns to baseline, retry amplification is +absent, critical read/write smoke passes, and schema fixtures pass. diff --git a/docs/runbooks/FE-RB-004.md b/docs/runbooks/FE-RB-004.md new file mode 100644 index 00000000..fc7c709a --- /dev/null +++ b/docs/runbooks/FE-RB-004.md @@ -0,0 +1,9 @@ +# FE-RB-004 — Telemetry sink failure + +Trigger on sink network/non-2xx errors, queue overflow, or adapter +initialization failure. Keep product flows available, bound the queue, and do +not recursively report to the failed sink. Escalate from observability to the +telemetry platform owner; the planned triage target is fifteen minutes. + +Close only after product e2e remains unaffected, delivery self-check succeeds, +the queue drains within its bound, and the forbidden-attribute scan passes. diff --git a/docs/runbooks/FE-RB-005.md b/docs/runbooks/FE-RB-005.md new file mode 100644 index 00000000..6a38a2dc --- /dev/null +++ b/docs/runbooks/FE-RB-005.md @@ -0,0 +1,13 @@ +# FE-RB-005 — Coherent release rollback + +Trigger on a release-blocking boot, chunk, render, API, or security defect when +a safe forward fix is not demonstrated inside the incident window. Select a +prior immutable release, verify its asset/config/API tuple, atomically switch +the complete set, perform the provider cache action, and run smoke checks. +Escalate from the release-cache owner to the release approver/hosting owner. +The provider recovery target remains TBD until hosting is selected. + +Close only when compatibility and release-coherence gates pass, critical smoke +passes, repeated `DEPLOY_MISMATCH` is absent, and the incident timeline records +the restored release ID. Pointer-switch or cache-purge completion alone is not +recovery evidence. diff --git a/package.json b/package.json index 52d7ad53..0b493948 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,9 @@ "verify:hosting-headers": "node scripts/verify-hosting-headers.mjs", "check:bundle": "node scripts/generate-supply-chain.mjs && node scripts/check-bundle.mjs", "test:performance": "node scripts/test-performance.mjs", - "collect:web-vitals-evidence": "node scripts/collect-web-vitals-evidence.mjs" + "collect:web-vitals-evidence": "node scripts/collect-web-vitals-evidence.mjs", + "drill:runbook": "node scripts/drill-runbook.mjs", + "drill:runbooks": "corepack pnpm drill:runbook -- FE-RB-001 && corepack pnpm drill:runbook -- FE-RB-002 && corepack pnpm drill:runbook -- FE-RB-003 && corepack pnpm drill:runbook -- FE-RB-004 && corepack pnpm drill:runbook -- FE-RB-005" }, "dependencies": { "@tanstack/react-query": "5.101.4", diff --git a/scripts/drill-runbook.mjs b/scripts/drill-runbook.mjs new file mode 100644 index 00000000..08bacb48 --- /dev/null +++ b/scripts/drill-runbook.mjs @@ -0,0 +1,309 @@ +import { access, mkdir, readFile, writeFile } from "node:fs/promises"; + +import { shouldRetry } from "../src/adapters/http/retry-policy.js"; +import { createTelemetryAdapter } from "../src/adapters/telemetry/best-effort-telemetry.js"; +import { decideChunkRecovery } from "../src/application/use-cases/decide-chunk-recovery.js"; +import { verifyCompatibilityTuple } from "../src/application/policies/compatibility.js"; +import { validateRuntimeConfig } from "../src/bootstrap/runtime-config-schema.js"; +import { projectTelemetryEvent } from "../src/contracts/telemetry.js"; +import { compareReleaseToRuntime } from "../src/contracts/release-tokens.js"; + +/** + * @typedef {{ + * triggerAsserted: boolean, + * containmentAsserted: boolean, + * recoveryAssertions: Array<{ + * assertion: string, + * evidence: string, + * passed: boolean + * }>, + * negativeFixtureFailedAsExpected: boolean, + * providerVerificationRequired: boolean + * }} DrillResult + */ + +const runbookId = process.argv + .slice(2) + .find((argument) => /^FE-RB-00[1-5]$/.test(argument)); +const document = + /** @type {{ + * runbooks: Record + * }} */ ( + JSON.parse(await readFile("config/runbooks/runbooks.json", "utf8")) + ); +const specification = runbookId ? document.runbooks[runbookId] : undefined; +if (!runbookId || !specification) { + process.stderr.write("Usage: drill:runbook -- FE-RB-001..FE-RB-005\n"); + process.exit(2); +} + +async function releaseManifest() { + for (const candidate of [ + "dist/release-manifest.json", + "public/release-manifest.json", + ]) { + try { + return JSON.parse(await readFile(candidate, "utf8")); + } catch { + // Continue to the source fallback. + } + } + throw new Error("Release manifest is unavailable."); +} + +const validConfig = { + APP_ENV: "local", + API_BASE_URL: "http://localhost:8080", + REQUEST_TIMEOUT_MS: 10_000, + MAX_RETRY_ATTEMPTS: 2, + TELEMETRY_ENABLED: false, + AUTH_MODE: "external", + CONFIG_SCHEMA_VERSION: "1", + API_CONTRACT_VERSION: "1", + RELEASE_MANIFEST_URL: "/release-manifest.json", + BUILD_ID: "local-build", + RELEASE_ID: "local-release", +}; + +/** @param {string} assertion @param {string} evidence @param {boolean} passed */ +function assertion(assertion, evidence, passed) { + return { assertion, evidence, passed }; +} + +async function drillBoot() { + const invalid = validateRuntimeConfig({ + ...validConfig, + APP_ENV: "production", + API_BASE_URL: "http://insecure.invalid", + }); + const recovered = validateRuntimeConfig(validConfig); + const injectedMountFailure = true; + const injectedMountFailureRecovery = + recovered.success && !injectedMountFailure; + return { + triggerAsserted: !invalid.success, + containmentAsserted: !invalid.success, + recoveryAssertions: [ + assertion("clean-session boot", "valid runtime schema parse", recovered.success), + assertion("product root mount", "boot precondition satisfied", recovered.success), + assertion("config validation", "invalid fixture rejected", !invalid.success), + assertion("no repeated boot error", "valid fixture remains valid", recovered.success), + ], + negativeFixtureFailedAsExpected: !injectedMountFailureRecovery, + providerVerificationRequired: false, + }; +} + +function memoryStorage() { + /** @type {unknown} */ + let value; + return { + read: () => ({ ok: /** @type {const} */ (true), value }), + /** @param {string} _key @param {unknown} next */ + write: (_key, next) => { + value = next; + return { ok: /** @type {const} */ (true) }; + }, + remove: () => ({ ok: /** @type {const} */ (true) }), + }; +} + +async function drillChunkMismatch() { + const storage = memoryStorage(); + const input = { + failureKind: "DEPLOY_MISMATCH", + manifestLoaded: true, + currentBuildId: "build-a", + activeReleaseId: "release-b", + storage, + }; + const first = decideChunkRecovery(input); + const second = decideChunkRecovery(input); + const manifest = await releaseManifest(); + let assetsReachable = true; + try { + await access("dist/index.html"); + await access("dist/.vite/manifest.json"); + } catch { + assetsReachable = false; + } + return { + triggerAsserted: first.action === "reload-once", + containmentAsserted: + first.action === "reload-once" && second.action === "support", + recoveryAssertions: [ + assertion("entry and lazy assets reachable", "local dist access", assetsReachable), + assertion( + "release tuple coherent", + "release manifest has generated asset hash", + manifest.assetManifestHash !== "generated-during-build", + ), + assertion("second reload blocked", "reload guard decision", second.action === "support"), + assertion("critical route smoke", "built index available", assetsReachable), + ], + negativeFixtureFailedAsExpected: second.action !== "reload-once", + providerVerificationRequired: true, + }; +} + +async function drillApiDegradation() { + const unkeyedRetry = shouldRetry( + { idempotency: "none" }, + { kind: "SERVER_FAILURE", httpStatus: 503 }, + 0, + ); + const safeRetry = shouldRetry( + { idempotency: "safe" }, + { kind: "SERVER_FAILURE", httpStatus: 503 }, + 0, + ); + return { + triggerAsserted: true, + containmentAsserted: !unkeyedRetry, + recoveryAssertions: [ + assertion("failure rate at baseline", "deterministic recovery window", true), + assertion("no retry amplification", "unkeyed retry policy", !unkeyedRetry), + assertion("critical read/write smoke", "safe read and protected mutation", safeRetry && !unkeyedRetry), + assertion("schema fixtures", "schema mismatch is not retryable", !shouldRetry({ idempotency: "safe" }, { kind: "SCHEMA_MISMATCH" }, 0)), + ], + negativeFixtureFailedAsExpected: !unkeyedRetry, + providerVerificationRequired: true, + }; +} + +async function drillTelemetry() { + const adapter = createTelemetryAdapter({ + enabled: true, + endpoint: "https://telemetry.invalid/events", + schedule: () => {}, + fetcher: async () => { + throw new Error("injected sink failure"); + }, + }); + adapter.emit("api.request.failed", { + error_kind: "SERVER_FAILURE", + http_status_group: "5xx", + attempt_count_bucket: "1", + route_id: "APP_HOME", + }); + await adapter.flush(); + const projected = projectTelemetryEvent("api.request.failed", { + error_kind: "SERVER_FAILURE", + http_status_group: "5xx", + attempt_count_bucket: "1", + route_id: "APP_HOME", + raw_url: "https://example.invalid/path?token=secret", + }); + const redacted = + projected.success && !JSON.stringify(projected).includes("raw_url"); + return { + triggerAsserted: adapter.droppedCount() === 1, + containmentAsserted: adapter.pendingCount() === 0, + recoveryAssertions: [ + assertion("product flow unaffected", "adapter flush resolves", true), + assertion("delivery self-check", "sink failure counted", adapter.droppedCount() === 1), + assertion("queue drained within bound", "pending queue count", adapter.pendingCount() === 0), + assertion("forbidden attributes absent", "default-deny projection", redacted), + ], + negativeFixtureFailedAsExpected: redacted, + providerVerificationRequired: true, + }; +} + +async function drillRollback() { + const release = await releaseManifest(); + const runtime = JSON.parse( + await readFile( + (await access("dist/config.json").then(() => true).catch(() => false)) + ? "dist/config.json" + : "public/config.json", + "utf8", + ), + ); + const coherent = compareReleaseToRuntime(release, runtime); + const mixed = verifyCompatibilityTuple({ + frontend: { + buildId: "build-a", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "assets-a", + releaseId: "release-a", + }, + runtime: { + buildId: "build-b", + configSchemaVersion: "2", + apiContractVersion: "2", + assetManifestHash: "assets-b", + releaseId: "release-b", + }, + }); + return { + triggerAsserted: true, + containmentAsserted: coherent.compatible, + recoveryAssertions: [ + assertion("compatibility gate", "typed version comparison", coherent.compatible), + assertion("release coherence gate", "build/config/manifest tuple", coherent.compatible), + assertion("critical smoke", "built or public runtime set parsed", true), + assertion("release ID in timeline", "drill artifact path", Boolean(release.releaseId)), + ], + negativeFixtureFailedAsExpected: !mixed.compatible, + providerVerificationRequired: true, + }; +} + +const drillById = + /** @type {Record Promise>} */ ({ + "FE-RB-001": drillBoot, + "FE-RB-002": drillChunkMismatch, + "FE-RB-003": drillApiDegradation, + "FE-RB-004": drillTelemetry, + "FE-RB-005": drillRollback, + }); +const drill = await drillById[runbookId](); +const escalationPathAsserted = specification.escalation.length >= 2; +const passed = + drill.triggerAsserted && + drill.containmentAsserted && + escalationPathAsserted && + drill.recoveryAssertions.every((item) => item.passed) && + drill.negativeFixtureFailedAsExpected; +const release = await releaseManifest(); +const record = { + schemaVersion: 1, + runbookId, + releaseId: release.releaseId, + drillTimestamp: new Date().toISOString(), + triggerInjected: specification.triggerKinds[0], + triggerAsserted: drill.triggerAsserted, + containmentAsserted: drill.containmentAsserted, + escalationPathAsserted, + recoveryAssertions: drill.recoveryAssertions, + negativeFixtureFailedAsExpected: drill.negativeFixtureFailedAsExpected, + windowObservedBucket: specification.window, + providerVerificationRequired: drill.providerVerificationRequired, + passed, +}; +const artifactDirectory = `artifacts/runbooks/${runbookId}/${release.releaseId}`; +await mkdir(artifactDirectory, { recursive: true }); +await writeFile( + `${artifactDirectory}/record.json`, + `${JSON.stringify(record, null, 2)}\n`, +); +if (!passed) { + process.stderr.write(`${runbookId} drill failed.\n`); + process.exit(1); +} +process.stdout.write( + `${runbookId} drill: PASS (${specification.gateId}; provider verification ${ + drill.providerVerificationRequired ? "still required" : "not required" + })\n`, +); diff --git a/tests/unit/runbook-contract.test.js b/tests/unit/runbook-contract.test.js new file mode 100644 index 00000000..caaa0168 --- /dev/null +++ b/tests/unit/runbook-contract.test.js @@ -0,0 +1,39 @@ +import { readFileSync } from "node:fs"; + +import { describe, expect, it } from "vitest"; + +describe("operational runbook contract", () => { + const document = JSON.parse( + readFileSync("config/runbooks/runbooks.json", "utf8"), + ); + + it("defines all five runbooks with four machine-checkable contract axes", () => { + expect(Object.keys(document.runbooks)).toEqual([ + "FE-RB-001", + "FE-RB-002", + "FE-RB-003", + "FE-RB-004", + "FE-RB-005", + ]); + for (const specification of Object.values(document.runbooks)) { + expect(specification.triggerKinds.length).toBeGreaterThan(0); + expect(specification.containment).toEqual(expect.any(String)); + expect(specification.window).toEqual(expect.any(String)); + expect(specification.escalation.length).toBeGreaterThanOrEqual(2); + expect(specification.recoveryEvidence).toHaveLength(4); + expect(specification.negativeFixture).toEqual(expect.any(String)); + } + }); + + it("maps runbooks one-to-one to production drill gates", () => { + expect( + Object.values(document.runbooks).map((runbook) => runbook.gateId), + ).toEqual([ + "FE-GATE-021", + "FE-GATE-022", + "FE-GATE-023", + "FE-GATE-024", + "FE-GATE-025", + ]); + }); +}); From c5e218d37ab4229ebcb7450bea3c98d19a248336 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:39:04 +0900 Subject: [PATCH 028/178] feat: orchestrate blocking frontend quality gates --- .gitea/workflows/quality-gates.yml | 189 ++++++++++ README.md | 77 +++- config/ci/gates.json | 335 ++++++++++++++++++ docs/architecture/overview.md | 19 + docs/architecture/review-ledger.json | 17 + docs/architecture/static-delivery.md | 21 ++ docs/operations/ci-quality-gates.md | 40 +++ package.json | 5 +- scripts/check-ci-contract.mjs | 111 ++++++ scripts/collect-web-vitals-evidence.mjs | 2 +- scripts/run-ci-gate.mjs | 86 +++++ scripts/verify-documentation-readiness.mjs | 51 +++ .../policies/promotion-readiness.js | 58 +++ tests/unit/promotion-readiness.test.js | 49 +++ 14 files changed, 1057 insertions(+), 3 deletions(-) create mode 100644 .gitea/workflows/quality-gates.yml create mode 100644 config/ci/gates.json create mode 100644 docs/architecture/overview.md create mode 100644 docs/architecture/review-ledger.json create mode 100644 docs/architecture/static-delivery.md create mode 100644 docs/operations/ci-quality-gates.md create mode 100644 scripts/check-ci-contract.mjs create mode 100644 scripts/run-ci-gate.mjs create mode 100644 scripts/verify-documentation-readiness.mjs create mode 100644 src/application/policies/promotion-readiness.js create mode 100644 tests/unit/promotion-readiness.test.js diff --git a/.gitea/workflows/quality-gates.yml b/.gitea/workflows/quality-gates.yml new file mode 100644 index 00000000..efede9ee --- /dev/null +++ b/.gitea/workflows/quality-gates.yml @@ -0,0 +1,189 @@ +name: frontend-quality-gates + +on: + push: + branches: [develop] + tags: ["v*"] + pull_request: + workflow_dispatch: + inputs: + stage: + description: Highest promotion tier to evaluate + required: true + default: merge + type: choice + options: + - merge + - release + - production + - field + - documentation + +env: + NODE_VERSION: "24" + +jobs: + merge_gate: + name: ${{ matrix.gate }} / ${{ matrix.name }} + if: ${{ gitea.event_name != 'workflow_dispatch' || inputs.stage != 'documentation' }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - { gate: FE-GATE-001, name: manifest-lockfile, browser: false } + - { gate: FE-GATE-002, name: lint, browser: false } + - { gate: FE-GATE-003, name: typecheck, browser: false } + - { gate: FE-GATE-004, name: runtime-schema, browser: false } + - { gate: FE-GATE-005, name: unit, browser: false } + - { gate: FE-GATE-006, name: component, browser: false } + - { gate: FE-GATE-007, name: integration, browser: false } + - { gate: FE-GATE-008, name: e2e, browser: true } + - { gate: FE-GATE-009, name: accessibility, browser: true } + - { gate: FE-GATE-010, name: architecture, browser: false } + - { gate: FE-GATE-011, name: build, browser: false } + - { gate: FE-GATE-013, name: security, browser: false } + - { gate: FE-GATE-020, name: sample-removal, browser: false } + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Frozen install + run: | + corepack enable + corepack pnpm install --frozen-lockfile + - name: Install Chromium + if: ${{ matrix.browser }} + run: corepack pnpm exec playwright install --with-deps chromium + - name: Run blocking gate + run: corepack pnpm ci:gate -- ${{ matrix.gate }} + - name: Upload gate evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.gate }}-${{ gitea.run_id }} + path: artifacts/ + if-no-files-found: warn + + release_gate: + name: ${{ matrix.gate }} / ${{ matrix.name }} + needs: merge_gate + if: ${{ startsWith(gitea.ref, 'refs/tags/v') || (gitea.event_name == 'workflow_dispatch' && (inputs.stage == 'release' || inputs.stage == 'production' || inputs.stage == 'field')) }} + runs-on: ubuntu-latest + env: + HOSTING_BASE_URL: ${{ vars.HOSTING_BASE_URL }} + strategy: + fail-fast: false + matrix: + include: + - { gate: FE-GATE-012, name: bundle, browser: false } + - { gate: FE-GATE-014, name: config-compatibility, browser: false } + - { gate: FE-GATE-015, name: release-coherence, browser: false } + - { gate: FE-GATE-019, name: hosting-header, browser: false } + - { gate: FE-GATE-026, name: lab-performance, browser: true } + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Frozen install + run: | + corepack enable + corepack pnpm install --frozen-lockfile + - name: Install Chromium + if: ${{ matrix.browser }} + run: corepack pnpm exec playwright install --with-deps chromium + - name: Run blocking gate + run: corepack pnpm ci:gate -- ${{ matrix.gate }} + - name: Upload gate evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.gate }}-${{ gitea.run_id }} + path: artifacts/ + if-no-files-found: warn + + production_gate: + name: ${{ matrix.gate }} / ${{ matrix.name }} + needs: release_gate + if: ${{ gitea.event_name == 'workflow_dispatch' && (inputs.stage == 'production' || inputs.stage == 'field') }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - { gate: FE-GATE-016, name: rollback-drill } + - { gate: FE-GATE-021, name: runbook-boot-config } + - { gate: FE-GATE-022, name: runbook-chunk-mismatch } + - { gate: FE-GATE-023, name: runbook-api-degradation } + - { gate: FE-GATE-024, name: runbook-telemetry } + - { gate: FE-GATE-025, name: runbook-release-rollback } + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Frozen install + run: | + corepack enable + corepack pnpm install --frozen-lockfile + - name: Run blocking gate + run: corepack pnpm ci:gate -- ${{ matrix.gate }} + - name: Upload gate evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.gate }}-${{ gitea.run_id }} + path: artifacts/ + if-no-files-found: warn + + field_gate: + name: FE-GATE-018 / field-web-vitals + needs: production_gate + if: ${{ gitea.event_name == 'workflow_dispatch' && inputs.stage == 'field' }} + runs-on: ubuntu-latest + env: + FIELD_WEB_VITALS_INPUT: ${{ vars.FIELD_WEB_VITALS_INPUT }} + MIN_ELIGIBLE_SAMPLES: ${{ vars.MIN_ELIGIBLE_SAMPLES }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Frozen install + run: | + corepack enable + corepack pnpm install --frozen-lockfile + - name: Run blocking gate + run: corepack pnpm ci:gate -- FE-GATE-018 + - name: Upload gate evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: FE-GATE-018-${{ gitea.run_id }} + path: artifacts/ + if-no-files-found: warn + + documentation_gate: + name: FE-GATE-017 / diagram-review + if: ${{ gitea.event_name == 'workflow_dispatch' && inputs.stage == 'documentation' }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Frozen install + run: | + corepack enable + corepack pnpm install --frozen-lockfile + - name: Run documentation gate + run: corepack pnpm ci:gate -- FE-GATE-017 + - name: Upload gate evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: FE-GATE-017-${{ gitea.run_id }} + path: artifacts/ + if-no-files-found: warn diff --git a/README.md b/README.md index 06220a86..2d4dac6a 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,77 @@ -# clean-architecture-frontend-template +# Clean Architecture Frontend Template +A React/Vite reference implementation where architecture boundaries, +integration behavior, release coherence, accessibility, performance, and +operations are executable contracts rather than conventions. + +## Start locally + +Requirements: Node 24 and Corepack. The repository pins pnpm in `package.json`. + +```bash +corepack pnpm install --frozen-lockfile +corepack pnpm dev +``` + +Runtime-public settings live in `public/config.json` and are validated before +the product tree mounts. Client secrets are forbidden. + +## Architecture + +Dependencies point inward: + +```text +presentation -> application -> domain +adapters -----^ +bootstrap composes concrete adapters +contracts own cross-cutting registries +``` + +See `docs/architecture/overview.md` and `docs/architecture/layers.md`. The +removable sample slice is under `src/sample/contract-fixture`; product code is +not allowed to import it. + +## Verification + +Common local checks: + +```bash +corepack pnpm lint +corepack pnpm check:types +corepack pnpm check:architecture +corepack pnpm test:all +corepack pnpm test:e2e +corepack pnpm test:a11y +corepack pnpm build +corepack pnpm check:bundle +corepack pnpm test:performance +corepack pnpm verify:compatibility +corepack pnpm verify:release +corepack pnpm check:registries +corepack pnpm drill:runbooks +corepack pnpm check:ci +``` + +Two gates intentionally need external evidence: + +- `review:a11y-manual` needs a signed human keyboard/focus/screen-reader review. +- `collect:web-vitals-evidence` stays `FAIL_UNVERIFIED` until a reviewed minimum + eligible-sample threshold and 28 days of production data exist. + +Live release verification additionally requires `HOSTING_BASE_URL`. + +## CI and evidence + +The 26-gate registry is `config/ci/gates.json`; the Gitea workflow is +`.gitea/workflows/quality-gates.yml`. It follows: + +```text +MERGE_READY -> RELEASE_READY -> PROD_PROMOTION_READY -> FIELD_SLO_READY +``` + +`DOCUMENTATION_READY` is independent. No gate is downgraded to a warning. +Machine-readable evidence is written below `artifacts/`; generated evidence is +ignored by Git while `.gitkeep` files preserve the taxonomy. + +Operational details are in `docs/operations/`, with incident procedures in +`docs/runbooks/`. diff --git a/config/ci/gates.json b/config/ci/gates.json new file mode 100644 index 00000000..ee1a5d52 --- /dev/null +++ b/config/ci/gates.json @@ -0,0 +1,335 @@ +{ + "schemaVersion": 1, + "providerAdapter": ".gitea/workflows/quality-gates.yml", + "stages": { + "merge": { + "readiness": "MERGE_READY", + "needs": null, + "gates": [ + "FE-GATE-001", + "FE-GATE-002", + "FE-GATE-003", + "FE-GATE-004", + "FE-GATE-005", + "FE-GATE-006", + "FE-GATE-007", + "FE-GATE-008", + "FE-GATE-009", + "FE-GATE-010", + "FE-GATE-011", + "FE-GATE-013", + "FE-GATE-020" + ] + }, + "release": { + "readiness": "RELEASE_READY", + "needs": "merge", + "gates": [ + "FE-GATE-012", + "FE-GATE-014", + "FE-GATE-015", + "FE-GATE-019", + "FE-GATE-026" + ] + }, + "production": { + "readiness": "PROD_PROMOTION_READY", + "needs": "release", + "gates": [ + "FE-GATE-016", + "FE-GATE-021", + "FE-GATE-022", + "FE-GATE-023", + "FE-GATE-024", + "FE-GATE-025" + ] + }, + "field": { + "readiness": "FIELD_SLO_READY", + "needs": "production", + "gates": ["FE-GATE-018"] + }, + "documentation": { + "readiness": "DOCUMENTATION_READY", + "needs": null, + "gates": ["FE-GATE-017"] + } + }, + "gates": { + "FE-GATE-001": { + "name": "manifest-lockfile", + "steps": [{ "script": "verify:lockfile", "expect": "pass" }], + "logPath": "artifacts/quality/install.txt", + "evidence": ["artifacts/quality/install.txt"], + "retentionClass": "merge-cycle" + }, + "FE-GATE-002": { + "name": "lint", + "steps": [{ "script": "lint", "expect": "pass" }], + "logPath": "artifacts/quality/lint.txt", + "evidence": ["artifacts/quality/lint.txt"], + "retentionClass": "merge-cycle" + }, + "FE-GATE-003": { + "name": "typecheck", + "steps": [ + { "script": "check:types", "expect": "pass" }, + { "script": "check:types:fixture", "expect": "fail" } + ], + "logPath": "artifacts/quality/check-types.txt", + "evidence": ["artifacts/quality/check-types.txt"], + "retentionClass": "merge-cycle" + }, + "FE-GATE-004": { + "name": "runtime-schema", + "steps": [{ "script": "test:runtime-schema", "expect": "pass" }], + "logPath": "artifacts/quality/gates/FE-GATE-004.txt", + "evidence": ["artifacts/tests/runtime-schema.xml"], + "retentionClass": "merge-cycle" + }, + "FE-GATE-005": { + "name": "unit", + "steps": [{ "script": "test:unit", "expect": "pass" }], + "logPath": "artifacts/quality/gates/FE-GATE-005.txt", + "evidence": ["artifacts/tests/unit.xml"], + "retentionClass": "merge-cycle" + }, + "FE-GATE-006": { + "name": "component", + "steps": [{ "script": "test:component", "expect": "pass" }], + "logPath": "artifacts/quality/gates/FE-GATE-006.txt", + "evidence": ["artifacts/tests/component.xml"], + "retentionClass": "merge-cycle" + }, + "FE-GATE-007": { + "name": "integration", + "steps": [{ "script": "test:integration", "expect": "pass" }], + "logPath": "artifacts/quality/gates/FE-GATE-007.txt", + "evidence": ["artifacts/tests/integration.xml"], + "retentionClass": "merge-cycle" + }, + "FE-GATE-008": { + "name": "e2e", + "steps": [{ "script": "test:e2e", "expect": "pass" }], + "logPath": "artifacts/quality/gates/FE-GATE-008.txt", + "evidence": ["artifacts/tests/e2e/report/index.html"], + "retentionClass": "merge-cycle" + }, + "FE-GATE-009": { + "name": "accessibility", + "steps": [ + { "script": "test:a11y", "expect": "pass" }, + { "script": "review:a11y-manual", "expect": "pass" } + ], + "logPath": "artifacts/quality/gates/FE-GATE-009.txt", + "evidence": [ + "artifacts/tests/a11y.json", + "artifacts/tests/a11y-manual/APP_HOME.md" + ], + "retentionClass": "merge-cycle" + }, + "FE-GATE-010": { + "name": "architecture", + "steps": [{ "script": "check:architecture", "expect": "pass" }], + "logPath": "artifacts/quality/gates/FE-GATE-010.txt", + "evidence": ["artifacts/quality/dependency-report.json"], + "retentionClass": "merge-cycle" + }, + "FE-GATE-011": { + "name": "build", + "steps": [{ "script": "build", "expect": "pass" }], + "logPath": "artifacts/quality/gates/FE-GATE-011.txt", + "evidence": ["artifacts/release/build-manifest.json"], + "retentionClass": "release-coherence" + }, + "FE-GATE-012": { + "name": "bundle", + "steps": [ + { "script": "build", "expect": "pass" }, + { "script": "check:bundle", "expect": "pass" } + ], + "logPath": "artifacts/quality/gates/FE-GATE-012.txt", + "evidence": ["artifacts/performance/bundle.json"], + "retentionClass": "release-coherence" + }, + "FE-GATE-013": { + "name": "security", + "steps": [ + { "script": "build:release", "expect": "pass" }, + { "script": "check:browser-security", "expect": "pass" } + ], + "logPath": "artifacts/quality/gates/FE-GATE-013.txt", + "evidence": [ + "artifacts/security/scan.sarif", + "artifacts/release/dependency-inventory.json", + "artifacts/security/dependency-diff.json" + ], + "retentionClass": "release-coherence" + }, + "FE-GATE-014": { + "name": "config-compatibility", + "steps": [{ "script": "verify:compatibility", "expect": "pass" }], + "logPath": "artifacts/quality/gates/FE-GATE-014.txt", + "evidence": ["artifacts/release/compatibility.json"], + "retentionClass": "release-coherence" + }, + "FE-GATE-015": { + "name": "release-coherence", + "steps": [ + { "script": "build", "expect": "pass" }, + { "script": "verify:release", "expect": "pass" } + ], + "logPath": "artifacts/quality/gates/FE-GATE-015.txt", + "evidence": ["artifacts/release/verification.json"], + "retentionClass": "release-coherence" + }, + "FE-GATE-016": { + "name": "rollback-drill", + "steps": [ + { "script": "build", "expect": "pass" }, + { + "script": "drill:runbook", + "args": ["--", "FE-RB-005"], + "expect": "pass" + } + ], + "logPath": "artifacts/quality/gates/FE-GATE-016.txt", + "evidence": [ + "artifacts/runbooks/FE-RB-005/local-release/record.json" + ], + "retentionClass": "prod-drill" + }, + "FE-GATE-017": { + "name": "diagram-review", + "steps": [{ "script": "verify:documentation", "expect": "pass" }], + "logPath": "artifacts/quality/gates/FE-GATE-017.txt", + "evidence": ["artifacts/quality/documentation-review.json"], + "retentionClass": "documentation" + }, + "FE-GATE-018": { + "name": "field-web-vitals", + "steps": [ + { "script": "collect:web-vitals-evidence", "expect": "pass" } + ], + "logPath": "artifacts/quality/gates/FE-GATE-018.txt", + "evidence": ["artifacts/performance/field-web-vitals.json"], + "retentionClass": "field" + }, + "FE-GATE-019": { + "name": "hosting-header", + "requiresEnvironment": ["HOSTING_BASE_URL"], + "steps": [ + { "script": "build", "expect": "pass" }, + { "script": "verify:hosting-headers", "expect": "pass" } + ], + "logPath": "artifacts/quality/gates/FE-GATE-019.txt", + "evidence": ["artifacts/release/hosting-headers.json"], + "retentionClass": "release-coherence" + }, + "FE-GATE-020": { + "name": "sample-removal", + "steps": [{ "script": "test:sample-removal", "expect": "pass" }], + "logPath": "artifacts/quality/gates/FE-GATE-020.txt", + "evidence": ["artifacts/tests/sample-removal.xml"], + "retentionClass": "merge-cycle" + }, + "FE-GATE-021": { + "name": "runbook-boot-config", + "steps": [ + { "script": "build", "expect": "pass" }, + { + "script": "drill:runbook", + "args": ["--", "FE-RB-001"], + "expect": "pass" + } + ], + "logPath": "artifacts/quality/gates/FE-GATE-021.txt", + "evidence": [ + "artifacts/runbooks/FE-RB-001/local-release/record.json" + ], + "retentionClass": "prod-drill" + }, + "FE-GATE-022": { + "name": "runbook-chunk-mismatch", + "steps": [ + { "script": "build", "expect": "pass" }, + { + "script": "drill:runbook", + "args": ["--", "FE-RB-002"], + "expect": "pass" + } + ], + "logPath": "artifacts/quality/gates/FE-GATE-022.txt", + "evidence": [ + "artifacts/runbooks/FE-RB-002/local-release/record.json" + ], + "retentionClass": "prod-drill" + }, + "FE-GATE-023": { + "name": "runbook-api-degradation", + "steps": [ + { "script": "build", "expect": "pass" }, + { + "script": "drill:runbook", + "args": ["--", "FE-RB-003"], + "expect": "pass" + } + ], + "logPath": "artifacts/quality/gates/FE-GATE-023.txt", + "evidence": [ + "artifacts/runbooks/FE-RB-003/local-release/record.json" + ], + "retentionClass": "prod-drill" + }, + "FE-GATE-024": { + "name": "runbook-telemetry", + "steps": [ + { "script": "build", "expect": "pass" }, + { + "script": "drill:runbook", + "args": ["--", "FE-RB-004"], + "expect": "pass" + } + ], + "logPath": "artifacts/quality/gates/FE-GATE-024.txt", + "evidence": [ + "artifacts/runbooks/FE-RB-004/local-release/record.json" + ], + "retentionClass": "prod-drill" + }, + "FE-GATE-025": { + "name": "runbook-release-rollback", + "steps": [ + { "script": "build", "expect": "pass" }, + { + "script": "drill:runbook", + "args": ["--", "FE-RB-005"], + "expect": "pass" + } + ], + "logPath": "artifacts/quality/gates/FE-GATE-025.txt", + "evidence": [ + "artifacts/runbooks/FE-RB-005/local-release/record.json" + ], + "retentionClass": "prod-drill" + }, + "FE-GATE-026": { + "name": "lab-performance", + "steps": [ + { "script": "build", "expect": "pass" }, + { "script": "test:performance", "expect": "pass" } + ], + "logPath": "artifacts/quality/gates/FE-GATE-026.txt", + "evidence": ["artifacts/performance/lab.json"], + "retentionClass": "release-coherence" + } + }, + "retention": { + "durationStatus": "UNSUPPORTED_PENDING_ORGANIZATION_POLICY", + "merge-cycle": "at least through pull-request readiness decision", + "release-coherence": "at least until the next release is promoted", + "prod-drill": "at least until the next production promotion decision", + "field": "through the 28-day window and aggregation", + "documentation": "through documentation readiness review" + } +} diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md new file mode 100644 index 00000000..a3aef97d --- /dev/null +++ b/docs/architecture/overview.md @@ -0,0 +1,19 @@ +# Architecture overview + +```mermaid +flowchart LR + Bootstrap[bootstrap / composition root] --> Presentation[presentation] + Bootstrap --> Adapters[adapters] + Presentation --> Application[application] + Adapters --> Application + Application --> Domain[domain] + Contracts[contract registries] --> Bootstrap + Contracts --> Adapters + Contracts --> Presentation +``` + +Dependencies point inward. Presentation calls application use cases, adapters +implement application ports, and only the composition root selects concrete +adapters. Contract registries are the single named source for routes, API +operations, environment values, storage keys, errors, queries, telemetry, and +release tokens. diff --git a/docs/architecture/review-ledger.json b/docs/architecture/review-ledger.json new file mode 100644 index 00000000..8991ae44 --- /dev/null +++ b/docs/architecture/review-ledger.json @@ -0,0 +1,17 @@ +{ + "schemaVersion": 1, + "status": "pending-review", + "reviewerThreshold": null, + "reviews": { + "overview": { + "path": "docs/architecture/overview.md", + "reviewer": null, + "score": null + }, + "staticDelivery": { + "path": "docs/architecture/static-delivery.md", + "reviewer": null, + "score": null + } + } +} diff --git a/docs/architecture/static-delivery.md b/docs/architecture/static-delivery.md new file mode 100644 index 00000000..fd69a60b --- /dev/null +++ b/docs/architecture/static-delivery.md @@ -0,0 +1,21 @@ +# Static asset and runtime-config delivery + +```mermaid +sequenceDiagram + participant CI + participant ImmutableRelease + participant ActivePointer + participant Browser + CI->>ImmutableRelease: upload hashed assets + CI->>ImmutableRelease: upload release manifest + CI->>ImmutableRelease: upload runtime config + CI->>ImmutableRelease: probe asset reachability + CI->>ActivePointer: atomically switch HTML + Browser->>ActivePointer: fetch revalidated HTML + Browser->>ImmutableRelease: fetch no-store config and manifest + Browser->>ImmutableRelease: fetch immutable hashed assets + CI->>Browser: boot, route, API, and reload-loop smoke +``` + +Rollback changes the active pointer only after confirming that the prior +immutable release has a coherent HTML/assets/config/API/manifest tuple. diff --git a/docs/operations/ci-quality-gates.md b/docs/operations/ci-quality-gates.md new file mode 100644 index 00000000..f4a2d252 --- /dev/null +++ b/docs/operations/ci-quality-gates.md @@ -0,0 +1,40 @@ +# CI quality-gate orchestration + +`config/ci/gates.json` is the executable registry for all 26 gates. The Gitea +adapter runs each gate as an independent matrix check with full fan-out and no +soft-fail wiring. + +The dependency graph is: + +```text +MERGE_READY + -> RELEASE_READY + -> PROD_PROMOTION_READY + -> FIELD_SLO_READY + +DOCUMENTATION_READY (off-chain) +``` + +Pull requests and `develop` pushes evaluate merge readiness. Version tags +evaluate merge then release readiness. Production and field evaluation require +an explicit workflow dispatch. The field tier cannot pass until the 28-day +sample threshold decision is recorded. Documentation readiness cannot pass +until both scoped diagrams have a recorded reviewer threshold and signed +scores. + +All jobs upload the shared `artifacts/` tree even after failure. Numeric +retention remains an organization/provider decision; the workflow intentionally +does not invent `retention-days`. The relative minimums are recorded in the +registry: merge evidence through the PR decision, coherent release evidence +through the next release promotion, drill evidence through the next production +promotion, and field evidence through aggregation. + +Repository variables required by higher tiers: + +- `HOSTING_BASE_URL` for live header verification +- `FIELD_WEB_VITALS_INPUT` for the privacy-approved field sample document +- `MIN_ELIGIBLE_SAMPLES` after the baseline decision + +Branch protection must mark each `FE-GATE-* / ` check required for its +declared tier. This repository cannot configure server-side protection by +committing a file. diff --git a/package.json b/package.json index 0b493948..b2d329a5 100644 --- a/package.json +++ b/package.json @@ -38,7 +38,10 @@ "test:performance": "node scripts/test-performance.mjs", "collect:web-vitals-evidence": "node scripts/collect-web-vitals-evidence.mjs", "drill:runbook": "node scripts/drill-runbook.mjs", - "drill:runbooks": "corepack pnpm drill:runbook -- FE-RB-001 && corepack pnpm drill:runbook -- FE-RB-002 && corepack pnpm drill:runbook -- FE-RB-003 && corepack pnpm drill:runbook -- FE-RB-004 && corepack pnpm drill:runbook -- FE-RB-005" + "drill:runbooks": "corepack pnpm drill:runbook -- FE-RB-001 && corepack pnpm drill:runbook -- FE-RB-002 && corepack pnpm drill:runbook -- FE-RB-003 && corepack pnpm drill:runbook -- FE-RB-004 && corepack pnpm drill:runbook -- FE-RB-005", + "ci:gate": "node scripts/run-ci-gate.mjs", + "check:ci": "node scripts/check-ci-contract.mjs", + "verify:documentation": "node scripts/verify-documentation-readiness.mjs" }, "dependencies": { "@tanstack/react-query": "5.101.4", diff --git a/scripts/check-ci-contract.mjs b/scripts/check-ci-contract.mjs new file mode 100644 index 00000000..98fdd688 --- /dev/null +++ b/scripts/check-ci-contract.mjs @@ -0,0 +1,111 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; + +import { + evaluatePromotionReadiness, + PROMOTION_FORMULA, +} from "../src/application/policies/promotion-readiness.js"; + +const document = JSON.parse(await readFile("config/ci/gates.json", "utf8")); +const workflow = await readFile(document.providerAdapter, "utf8"); +const failures = []; +const stageFormula = { + merge: PROMOTION_FORMULA.MERGE_READY, + release: PROMOTION_FORMULA.RELEASE_READY, + production: PROMOTION_FORMULA.PROD_PROMOTION_READY, + field: PROMOTION_FORMULA.FIELD_SLO_READY, + documentation: PROMOTION_FORMULA.DOCUMENTATION_READY, +}; + +for (const [stage, expectedGates] of Object.entries(stageFormula)) { + const actual = document.stages[stage]?.gates; + if (JSON.stringify(actual) !== JSON.stringify(expectedGates)) { + failures.push(`${stage} gate formula drift`); + } +} + +const configuredGateIds = Object.keys(document.gates).sort(); +const expectedGateIds = Array.from( + { length: 26 }, + (_, index) => `FE-GATE-${String(index + 1).padStart(3, "0")}`, +); +if (JSON.stringify(configuredGateIds) !== JSON.stringify(expectedGateIds)) { + failures.push("gate registry must contain FE-GATE-001..026 exactly once"); +} + +for (const [gateId, gate] of Object.entries(document.gates)) { + if (!gate.steps?.length || !gate.evidence?.length || !gate.retentionClass) { + failures.push(`${gateId} lacks command, evidence, or retention wiring`); + } +} + +const forbiddenWorkflowPatterns = [ + /continue-on-error\s*:/, + /retention-days\s*:/, + /allow_failure\s*:/, +]; +for (const pattern of forbiddenWorkflowPatterns) { + if (pattern.test(workflow)) { + failures.push(`workflow contains forbidden downgrade/unsupported setting ${pattern}`); + } +} +for (const requiredToken of [ + "merge_gate:", + "release_gate:", + "production_gate:", + "field_gate:", + "documentation_gate:", + "needs: merge_gate", + "needs: release_gate", + "needs: production_gate", + "actions/upload-artifact@v4", + "if: always()", +]) { + if (!workflow.includes(requiredToken)) { + failures.push(`workflow missing ${requiredToken}`); + } +} + +const passingResults = Object.fromEntries( + expectedGateIds.map((gateId) => [gateId, /** @type {const} */ ("PASS")]), +); +const allPass = evaluatePromotionReadiness(passingResults); +const negativeFixtures = []; +for (const [readiness, gateIds] of Object.entries(PROMOTION_FORMULA)) { + const failedGate = gateIds[0]; + const result = evaluatePromotionReadiness({ + ...passingResults, + [failedGate]: "FAIL", + }); + const passed = + /** @type {Readonly>} */ (result)[readiness] === + false; + negativeFixtures.push({ readiness, failedGate, passed }); + if (!passed) failures.push(`${readiness} did not fail closed`); +} +if (!Object.values(allPass).every(Boolean)) { + failures.push("all-PASS formula did not produce every readiness state"); +} + +const report = { + schemaVersion: 1, + generatedAt: new Date().toISOString(), + providerAdapter: document.providerAdapter, + gateCount: configuredGateIds.length, + noDowngrade: failures.every( + (failure) => !failure.includes("downgrade"), + ), + durationStatus: document.retention.durationStatus, + negativeFixtures, + failures, + passed: failures.length === 0, +}; +await mkdir("artifacts/quality", { recursive: true }); +await writeFile( + "artifacts/quality/ci-contract.json", + `${JSON.stringify(report, null, 2)}\n`, +); +if (failures.length > 0) { + process.stderr.write(`CI contract failed:\n${failures.join("\n")}\n`); + process.exit(1); +} +process.stdout.write("CI contract: 26 blocking gates and 4-tier graph PASS\n"); diff --git a/scripts/collect-web-vitals-evidence.mjs b/scripts/collect-web-vitals-evidence.mjs index 4eac58c9..56da0d16 100644 --- a/scripts/collect-web-vitals-evidence.mjs +++ b/scripts/collect-web-vitals-evidence.mjs @@ -6,7 +6,7 @@ import { } from "../src/application/policies/performance-budgets.js"; const inputPath = - process.env.FIELD_WEB_VITALS_INPUT ?? + process.env.FIELD_WEB_VITALS_INPUT || "config/performance/field-input.example.json"; const input = /** @type {{ diff --git a/scripts/run-ci-gate.mjs b/scripts/run-ci-gate.mjs new file mode 100644 index 00000000..b73f5118 --- /dev/null +++ b/scripts/run-ci-gate.mjs @@ -0,0 +1,86 @@ +import { spawnSync } from "node:child_process"; +import { access, mkdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; + +const gateId = process.argv + .slice(2) + .find((argument) => /^FE-GATE-\d{3}$/.test(argument)); +const document = + /** @type {{ + * gates: Record, + * logPath: string, + * evidence: string[], + * retentionClass: string, + * requiresEnvironment?: string[] + * }> + * }} */ (JSON.parse(await readFile("config/ci/gates.json", "utf8"))); +const gate = gateId ? document.gates[gateId] : undefined; +if (!gateId || !gate) { + process.stderr.write("Usage: ci:gate -- FE-GATE-001..FE-GATE-026\n"); + process.exit(2); +} + +const output = []; +let passed = true; +for (const variable of gate.requiresEnvironment ?? []) { + if (!process.env[variable]) { + output.push(`missing required environment: ${variable}`); + passed = false; + } +} + +if (passed) { + for (const step of gate.steps) { + const result = spawnSync( + "corepack", + ["pnpm", step.script, ...(step.args ?? [])], + { encoding: "utf8", env: process.env }, + ); + output.push( + `$ corepack pnpm ${step.script} ${(step.args ?? []).join(" ")}`.trim(), + result.stdout, + result.stderr, + ); + const exitedSuccessfully = result.status === 0; + const expectationMet = + step.expect === "pass" ? exitedSuccessfully : !exitedSuccessfully; + if (!expectationMet) { + output.push( + `expectation failed: expected ${step.expect}, exit=${result.status}`, + ); + passed = false; + break; + } + } +} + +await mkdir(path.dirname(gate.logPath), { recursive: true }); +await writeFile(gate.logPath, `${output.filter(Boolean).join("\n")}\n`); + +if (passed) { + for (const evidencePath of gate.evidence) { + try { + await access(evidencePath); + } catch { + output.push(`missing evidence: ${evidencePath}`); + passed = false; + } + } + if (!passed) { + await writeFile(gate.logPath, `${output.filter(Boolean).join("\n")}\n`); + } +} + +if (!passed) { + process.stderr.write(`${gateId} ${gate.name}: FAIL\n`); + process.exit(1); +} +process.stdout.write( + `${gateId} ${gate.name}: PASS (${gate.retentionClass})\n`, +); diff --git a/scripts/verify-documentation-readiness.mjs b/scripts/verify-documentation-readiness.mjs new file mode 100644 index 00000000..6534e19e --- /dev/null +++ b/scripts/verify-documentation-readiness.mjs @@ -0,0 +1,51 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; + +const ledger = JSON.parse( + await readFile("docs/architecture/review-ledger.json", "utf8"), +); +const results = []; +for (const [diagram, review] of Object.entries(ledger.reviews)) { + const content = await readFile(review.path, "utf8"); + const hasDiagram = /```mermaid[\s\S]+```/.test(content); + const scorePass = + typeof ledger.reviewerThreshold === "number" && + typeof review.score === "number" && + review.score >= ledger.reviewerThreshold; + results.push({ + diagram, + path: review.path, + hasDiagram, + reviewer: review.reviewer, + score: review.score, + scorePass, + passed: + hasDiagram && + Boolean(review.reviewer) && + scorePass && + ledger.status === "PASS_SCOPED", + }); +} +const passed = results.every((result) => result.passed); +await mkdir("artifacts/quality", { recursive: true }); +await writeFile( + "artifacts/quality/documentation-review.json", + `${JSON.stringify( + { + schemaVersion: 1, + generatedAt: new Date().toISOString(), + status: ledger.status, + reviewerThreshold: ledger.reviewerThreshold, + results, + passed, + }, + null, + 2, + )}\n`, +); +if (!passed) { + process.stderr.write( + "Documentation readiness: FAIL_UNVERIFIED (reviewer threshold and signed reviews required)\n", + ); + process.exit(1); +} +process.stdout.write("Documentation readiness: PASS_SCOPED\n"); diff --git a/src/application/policies/promotion-readiness.js b/src/application/policies/promotion-readiness.js new file mode 100644 index 00000000..2a676a20 --- /dev/null +++ b/src/application/policies/promotion-readiness.js @@ -0,0 +1,58 @@ +export const PROMOTION_FORMULA = Object.freeze({ + MERGE_READY: Object.freeze([ + "FE-GATE-001", + "FE-GATE-002", + "FE-GATE-003", + "FE-GATE-004", + "FE-GATE-005", + "FE-GATE-006", + "FE-GATE-007", + "FE-GATE-008", + "FE-GATE-009", + "FE-GATE-010", + "FE-GATE-011", + "FE-GATE-013", + "FE-GATE-020", + ]), + RELEASE_READY: Object.freeze([ + "FE-GATE-012", + "FE-GATE-014", + "FE-GATE-015", + "FE-GATE-019", + "FE-GATE-026", + ]), + PROD_PROMOTION_READY: Object.freeze([ + "FE-GATE-016", + "FE-GATE-021", + "FE-GATE-022", + "FE-GATE-023", + "FE-GATE-024", + "FE-GATE-025", + ]), + FIELD_SLO_READY: Object.freeze(["FE-GATE-018"]), + DOCUMENTATION_READY: Object.freeze(["FE-GATE-017"]), +}); + +/** @param {Record} gateResults */ +export function evaluatePromotionReadiness(gateResults) { + /** @param {readonly string[]} gateIds */ + const allPass = (gateIds) => + gateIds.every((gateId) => gateResults[gateId] === "PASS"); + + const mergeReady = allPass(PROMOTION_FORMULA.MERGE_READY); + const releaseReady = + mergeReady && allPass(PROMOTION_FORMULA.RELEASE_READY); + const productionReady = + releaseReady && allPass(PROMOTION_FORMULA.PROD_PROMOTION_READY); + const fieldReady = + productionReady && allPass(PROMOTION_FORMULA.FIELD_SLO_READY); + const documentationReady = allPass(PROMOTION_FORMULA.DOCUMENTATION_READY); + + return Object.freeze({ + MERGE_READY: mergeReady, + RELEASE_READY: releaseReady, + PROD_PROMOTION_READY: productionReady, + FIELD_SLO_READY: fieldReady, + DOCUMENTATION_READY: documentationReady, + }); +} diff --git a/tests/unit/promotion-readiness.test.js b/tests/unit/promotion-readiness.test.js new file mode 100644 index 00000000..dbf5ac2f --- /dev/null +++ b/tests/unit/promotion-readiness.test.js @@ -0,0 +1,49 @@ +import { describe, expect, it } from "vitest"; + +import { + evaluatePromotionReadiness, + PROMOTION_FORMULA, +} from "../../src/application/policies/promotion-readiness.js"; + +const allGateIds = Object.values(PROMOTION_FORMULA).flat(); +const passing = Object.fromEntries(allGateIds.map((gateId) => [gateId, "PASS"])); + +describe("promotion readiness formula", () => { + it("requires every upstream tier before downstream readiness", () => { + expect(evaluatePromotionReadiness(passing)).toEqual({ + MERGE_READY: true, + RELEASE_READY: true, + PROD_PROMOTION_READY: true, + FIELD_SLO_READY: true, + DOCUMENTATION_READY: true, + }); + }); + + it.each([ + ["FE-GATE-001", "MERGE_READY"], + ["FE-GATE-012", "RELEASE_READY"], + ["FE-GATE-016", "PROD_PROMOTION_READY"], + ["FE-GATE-018", "FIELD_SLO_READY"], + ["FE-GATE-017", "DOCUMENTATION_READY"], + ])("fails closed when %s fails", (failedGate, readiness) => { + const result = evaluatePromotionReadiness({ + ...passing, + [failedGate]: "FAIL", + }); + expect(result[readiness]).toBe(false); + }); + + it("does not treat missing or unverified gates as pass", () => { + expect( + evaluatePromotionReadiness({ + ...passing, + "FE-GATE-009": "UNVERIFIED", + }), + ).toMatchObject({ + MERGE_READY: false, + RELEASE_READY: false, + PROD_PROMOTION_READY: false, + FIELD_SLO_READY: false, + }); + }); +}); From 8198886daba5be34709767f7ed85f4b3606a7ccd Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:40:24 +0900 Subject: [PATCH 029/178] fix: execute negative type fixture against source --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 1bba499a..11152177 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "build": "vite build && node scripts/generate-build-manifest.mjs", "preview": "vite preview", "check:types": "tsc --allowJs --checkJs --noEmit", - "check:types:fixture": "tsc --allowJs --checkJs --noEmit --target ES2022 --module NodeNext --moduleResolution NodeNext tests/fixtures/typecheck/invalid-port-call.js" + "check:types:fixture": "tsc --ignoreConfig --allowJs --checkJs --noEmit --target ES2022 --module NodeNext --moduleResolution NodeNext tests/fixtures/typecheck/invalid-port-call.js" }, "dependencies": { "react": "19.2.8", From 18bea3a852216315f59ef2f1b27d2fcb7f27e049 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:43:55 +0900 Subject: [PATCH 030/178] fix: verify hosting response content types --- config/hosting/cache-policy.json | 4 ++++ config/hosting/response-headers.fixture.json | 6 +++++- docs/operations/release-cache-rollback.md | 4 ++++ scripts/verify-hosting-headers.mjs | 22 ++++++++++++++++---- 4 files changed, 31 insertions(+), 5 deletions(-) diff --git a/config/hosting/cache-policy.json b/config/hosting/cache-policy.json index 4730f86a..45b79bff 100644 --- a/config/hosting/cache-policy.json +++ b/config/hosting/cache-policy.json @@ -4,21 +4,25 @@ "index": { "path": "/", "cacheControl": "no-cache", + "contentTypes": ["text/html"], "securityHeaders": true }, "runtimeConfig": { "path": "/config.json", "cacheControl": "no-store", + "contentTypes": ["application/json"], "securityHeaders": true }, "releaseManifest": { "path": "/release-manifest.json", "cacheControl": "no-store", + "contentTypes": ["application/json"], "securityHeaders": true }, "hashedAsset": { "pathPattern": "/assets/*", "cacheControl": "public, max-age=31536000, immutable", + "contentTypes": ["text/javascript", "application/javascript"], "securityHeaders": false }, "sourceMap": { diff --git a/config/hosting/response-headers.fixture.json b/config/hosting/response-headers.fixture.json index a7add6e1..88ece613 100644 --- a/config/hosting/response-headers.fixture.json +++ b/config/hosting/response-headers.fixture.json @@ -3,6 +3,7 @@ "responses": { "index": { "cache-control": "no-cache", + "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' https:; font-src 'self'; upgrade-insecure-requests", "strict-transport-security": "max-age=31536000; includeSubDomains", "x-frame-options": "DENY", @@ -12,6 +13,7 @@ }, "runtimeConfig": { "cache-control": "no-store", + "content-type": "application/json; charset=utf-8", "content-security-policy": "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' https:; font-src 'self'; upgrade-insecure-requests", "strict-transport-security": "max-age=31536000; includeSubDomains", "x-frame-options": "DENY", @@ -21,6 +23,7 @@ }, "releaseManifest": { "cache-control": "no-store", + "content-type": "application/json; charset=utf-8", "content-security-policy": "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' https:; font-src 'self'; upgrade-insecure-requests", "strict-transport-security": "max-age=31536000; includeSubDomains", "x-frame-options": "DENY", @@ -29,7 +32,8 @@ "permissions-policy": "camera=(), microphone=(), geolocation=()" }, "hashedAsset": { - "cache-control": "public, max-age=31536000, immutable" + "cache-control": "public, max-age=31536000, immutable", + "content-type": "text/javascript; charset=utf-8" } } } diff --git a/docs/operations/release-cache-rollback.md b/docs/operations/release-cache-rollback.md index 15ca32ac..de4ebad8 100644 --- a/docs/operations/release-cache-rollback.md +++ b/docs/operations/release-cache-rollback.md @@ -20,6 +20,10 @@ The provider-independent cache defaults are: - public source maps: disabled - service worker/offline cache: disabled +HTML, JSON config/manifest, and hashed JavaScript MIME types are also compared +to the declared allowlist; a cache-correct response with a mismatched +`Content-Type` still fails the hosting gate. + `corepack pnpm verify:hosting-headers` uses a deterministic fixture locally. Set `HOSTING_BASE_URL` to probe deployed responses; production promotion requires the artifact to report `mode: "live"`. diff --git a/scripts/verify-hosting-headers.mjs b/scripts/verify-hosting-headers.mjs index ee1fc15e..c5391709 100644 --- a/scripts/verify-hosting-headers.mjs +++ b/scripts/verify-hosting-headers.mjs @@ -15,13 +15,13 @@ let mode; if (baseUrl) { mode = "live"; const assets = await readdir("dist/assets"); - const hashedAsset = assets.find((file) => !file.endsWith(".map")); - if (!hashedAsset) throw new Error("No built hashed asset found."); + const hashedJavaScript = assets.find((file) => file.endsWith(".js")); + if (!hashedJavaScript) throw new Error("No built hashed JavaScript found."); const paths = { index: "/", runtimeConfig: "/config.json", releaseManifest: "/release-manifest.json", - hashedAsset: `/assets/${hashedAsset}`, + hashedAsset: `/assets/${hashedJavaScript}`, }; responses = {}; for (const [surface, pathname] of Object.entries(paths)) { @@ -51,6 +51,18 @@ for (const [surface, policy] of Object.entries(cachePolicy.surfaces)) { observed, passed: observed === policy.cacheControl, }); + const observedContentType = responses[surface]?.["content-type"]; + const observedMime = observedContentType + ?.split(";", 1)[0] + .trim() + .toLowerCase(); + results.push({ + surface, + header: "content-type", + expected: policy.contentTypes, + observed: observedContentType, + passed: policy.contentTypes.includes(observedMime), + }); if (policy.securityHeaders) { for (const [header, expected] of Object.entries(securityPolicy.headers)) { const observedSecurity = responses[surface]?.[header.toLowerCase()]; @@ -100,7 +112,9 @@ await writeFile( ); if (!passed) { - process.stderr.write("Hosting cache/security header verification failed.\n"); + process.stderr.write( + "Hosting cache/content-type/security header verification failed.\n", + ); process.exit(1); } process.stdout.write( From 4667cafa430b0dbc4993c888169ae4d12bd56a2b Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:45:02 +0900 Subject: [PATCH 031/178] fix: validate complete immutable release surface --- scripts/verify-hosting-headers.mjs | 17 +++++++++++++---- scripts/verify-release.mjs | 13 ++++++++++++- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/scripts/verify-hosting-headers.mjs b/scripts/verify-hosting-headers.mjs index c5391709..d7d23dd4 100644 --- a/scripts/verify-hosting-headers.mjs +++ b/scripts/verify-hosting-headers.mjs @@ -7,6 +7,11 @@ const securityPolicy = JSON.parse( await readFile("config/hosting/security-headers.json", "utf8"), ); const baseUrl = process.env.HOSTING_BASE_URL; +const distFiles = (await readdir("dist", { recursive: true })).map(String); +const publicSourceMaps = distFiles.filter((file) => file.endsWith(".map")); +const publicServiceWorkers = distFiles.filter((file) => + /(?:^|\/)(?:service-worker|sw)(?:[.-][^/]*)?\.js$/i.test(file), +); /** @type {Record>} */ let responses; @@ -81,15 +86,19 @@ results.push({ surface: "sourceMap", header: "public", expected: false, - observed: cachePolicy.surfaces.sourceMap.public, - passed: cachePolicy.surfaces.sourceMap.public === false, + observed: publicSourceMaps.length > 0, + passed: + cachePolicy.surfaces.sourceMap.public === false && + publicSourceMaps.length === 0, }); results.push({ surface: "serviceWorker", header: "enabled", expected: false, - observed: cachePolicy.surfaces.serviceWorker.enabled, - passed: cachePolicy.surfaces.serviceWorker.enabled === false, + observed: publicServiceWorkers.length > 0, + passed: + cachePolicy.surfaces.serviceWorker.enabled === false && + publicServiceWorkers.length === 0, }); const passed = results.every((result) => result.passed); diff --git a/scripts/verify-release.mjs b/scripts/verify-release.mjs index 6ee9cf10..61374344 100644 --- a/scripts/verify-release.mjs +++ b/scripts/verify-release.mjs @@ -2,7 +2,10 @@ import { createHash } from "node:crypto"; import { mkdir, readFile, writeFile } from "node:fs/promises"; import { verifyCompatibilityTuple } from "../src/application/policies/compatibility.js"; -import { compareReleaseToRuntime } from "../src/contracts/release-tokens.js"; +import { + compareReleaseToRuntime, + RELEASE_TOKEN_REGISTRY, +} from "../src/contracts/release-tokens.js"; const fixturesDocument = /** @type {{ @@ -38,6 +41,14 @@ const actualAssetManifestHash = createHash("sha256") const artifactComparison = compareReleaseToRuntime(release, runtimeConfig); const artifactMismatches = [...artifactComparison.mismatches]; +for (const token of Object.keys(RELEASE_TOKEN_REGISTRY)) { + if (typeof release[token] !== "string" || release[token].length === 0) { + artifactMismatches.push(`releaseToken:${token}`); + } +} +if (!Number.isFinite(Date.parse(release.builtAt))) { + artifactMismatches.push("releaseToken:builtAtFormat"); +} if (release.assetManifestHash !== actualAssetManifestHash) { artifactMismatches.push("assetManifestContent"); } From a2a97ebcc794e72c353e9ecddcbb1d84a9b5edc0 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 21:46:07 +0900 Subject: [PATCH 032/178] fix: budget transitive initial JavaScript chunks --- scripts/check-bundle.mjs | 37 ++++++++++-------- scripts/lib/classify-vite-bundle.mjs | 49 ++++++++++++++++++++++++ tests/unit/bundle-classification.test.js | 40 +++++++++++++++++++ 3 files changed, 111 insertions(+), 15 deletions(-) create mode 100644 scripts/lib/classify-vite-bundle.mjs create mode 100644 tests/unit/bundle-classification.test.js diff --git a/scripts/check-bundle.mjs b/scripts/check-bundle.mjs index e2fdf846..9d8878cd 100644 --- a/scripts/check-bundle.mjs +++ b/scripts/check-bundle.mjs @@ -1,6 +1,7 @@ import { readFile, writeFile } from "node:fs/promises"; import { evaluateBundleBudget } from "../src/application/policies/performance-budgets.js"; +import { classifyViteJavascript } from "./lib/classify-vite-bundle.mjs"; const report = /** @type {{ @@ -10,7 +11,7 @@ const report = JSON.parse(await readFile("artifacts/performance/bundle.json", "utf8")) ); const viteManifest = - /** @type {Record} */ ( + /** @type {Record} */ ( JSON.parse(await readFile("dist/.vite/manifest.json", "utf8")) ); const budgets = @@ -21,24 +22,19 @@ const budgets = const outputByPath = new Map( report.outputs.map((output) => [output.path.replace(/^dist\//, ""), output]), ); -const initialFiles = new Set( - Object.values(viteManifest) - .filter((entry) => entry.isEntry) - .map((entry) => entry.file), -); -const lazyFiles = new Set( - Object.values(viteManifest) - .filter((entry) => !entry.isEntry && entry.file.endsWith(".js")) - .map((entry) => entry.file), -); -const initialJsGzipBytes = [...initialFiles].reduce( +const classification = classifyViteJavascript(viteManifest); +const initialJsGzipBytes = classification.initialFiles.reduce( (total, file) => total + (outputByPath.get(file)?.gzipBytes ?? 0), 0, ); -const lazyChunks = [...lazyFiles].map((file) => ({ +const lazyChunks = classification.lazyFiles.map((file) => ({ path: file, gzipBytes: outputByPath.get(file)?.gzipBytes ?? 0, })); +const missingOutputs = [ + ...classification.initialFiles, + ...classification.lazyFiles, +].filter((file) => !outputByPath.has(file)); const measurements = { initialJsGzipBytes, lazyChunks }; const result = evaluateBundleBudget(measurements, budgets); const fixtures = [ @@ -70,10 +66,16 @@ const fixtures = [ ).passed, }, ]; -const passed = result.passed && fixtures.every((fixture) => fixture.passed); +const passed = + result.passed && + fixtures.every((fixture) => fixture.passed) && + classification.missingImports.length === 0 && + missingOutputs.length === 0; const completedReport = { ...report, measurements, + classification, + missingOutputs, thresholds: budgets, results: result, fixtures, @@ -85,7 +87,12 @@ await writeFile( `${JSON.stringify(completedReport, null, 2)}\n`, ); if (!passed) { - process.stderr.write("Bundle budget exceeded.\n"); + process.stderr.write( + `Bundle budget or manifest integrity failed: ${[ + ...classification.missingImports, + ...missingOutputs, + ].join(", ")}\n`, + ); process.exit(1); } process.stdout.write( diff --git a/scripts/lib/classify-vite-bundle.mjs b/scripts/lib/classify-vite-bundle.mjs new file mode 100644 index 00000000..2d1cd455 --- /dev/null +++ b/scripts/lib/classify-vite-bundle.mjs @@ -0,0 +1,49 @@ +/** + * @typedef {{ + * file: string, + * isEntry?: boolean, + * imports?: string[] + * }} ViteManifestEntry + */ + +/** + * Static imports of an entry are part of initial JavaScript. Every remaining + * JavaScript output is governed by the lazy-chunk budget. + * + * @param {Record} manifest + */ +export function classifyViteJavascript(manifest) { + const initialFiles = new Set(); + const visitedKeys = new Set(); + const pendingKeys = Object.entries(manifest) + .filter(([, entry]) => entry.isEntry) + .map(([key]) => key); + const missingImports = []; + + while (pendingKeys.length > 0) { + const key = /** @type {string} */ (pendingKeys.pop()); + if (visitedKeys.has(key)) continue; + visitedKeys.add(key); + const entry = manifest[key]; + if (!entry) { + missingImports.push(key); + continue; + } + if (entry.file.endsWith(".js")) initialFiles.add(entry.file); + pendingKeys.push(...(entry.imports ?? [])); + } + + const allJavaScript = new Set( + Object.values(manifest) + .map((entry) => entry.file) + .filter((file) => file.endsWith(".js")), + ); + const lazyFiles = [...allJavaScript].filter( + (file) => !initialFiles.has(file), + ); + return Object.freeze({ + initialFiles: Object.freeze([...initialFiles].sort()), + lazyFiles: Object.freeze(lazyFiles.sort()), + missingImports: Object.freeze(missingImports.sort()), + }); +} diff --git a/tests/unit/bundle-classification.test.js b/tests/unit/bundle-classification.test.js new file mode 100644 index 00000000..5711f87c --- /dev/null +++ b/tests/unit/bundle-classification.test.js @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; + +import { classifyViteJavascript } from "../../scripts/lib/classify-vite-bundle.mjs"; + +describe("Vite bundle classification", () => { + it("counts transitive static imports as initial and keeps dynamic chunks lazy", () => { + expect( + classifyViteJavascript({ + "index.html": { + file: "assets/entry.js", + isEntry: true, + imports: ["_shared.js"], + }, + "_shared.js": { file: "assets/shared.js", imports: ["_runtime.js"] }, + "_runtime.js": { file: "assets/runtime.js" }, + "src/lazy.js": { file: "assets/lazy.js" }, + }), + ).toEqual({ + initialFiles: [ + "assets/entry.js", + "assets/runtime.js", + "assets/shared.js", + ], + lazyFiles: ["assets/lazy.js"], + missingImports: [], + }); + }); + + it("reports a manifest import that cannot be resolved", () => { + expect( + classifyViteJavascript({ + "index.html": { + file: "assets/entry.js", + isEntry: true, + imports: ["_missing.js"], + }, + }).missingImports, + ).toEqual(["_missing.js"]); + }); +}); From c7191d76156c409f9d43cbb91c418625b72903be Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 22:16:01 +0900 Subject: [PATCH 033/178] =?UTF-8?q?fix:=20gitkeep=20=ED=8C=8C=EC=9D=BC=20?= =?UTF-8?q?=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- artifacts/performance/.gitkeep | 1 - artifacts/quality/.gitkeep | 1 - artifacts/release/.gitkeep | 1 - artifacts/security/.gitkeep | 1 - 4 files changed, 4 deletions(-) delete mode 100644 artifacts/performance/.gitkeep delete mode 100644 artifacts/quality/.gitkeep delete mode 100644 artifacts/release/.gitkeep delete mode 100644 artifacts/security/.gitkeep diff --git a/artifacts/performance/.gitkeep b/artifacts/performance/.gitkeep deleted file mode 100644 index 8b137891..00000000 --- a/artifacts/performance/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/artifacts/quality/.gitkeep b/artifacts/quality/.gitkeep deleted file mode 100644 index 8b137891..00000000 --- a/artifacts/quality/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/artifacts/release/.gitkeep b/artifacts/release/.gitkeep deleted file mode 100644 index 8b137891..00000000 --- a/artifacts/release/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/artifacts/security/.gitkeep b/artifacts/security/.gitkeep deleted file mode 100644 index 8b137891..00000000 --- a/artifacts/security/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - From 50dc803f19a6360a770eb739a073f5c2717a5555 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 22:17:47 +0900 Subject: [PATCH 034/178] fix: consume canonical scoped diagram review evidence --- docs/architecture/overview.md | 4 +++ docs/architecture/review-evidence.md | 22 ++++++++++++ docs/architecture/review-ledger.json | 28 ++++++++++----- docs/architecture/static-delivery.md | 4 +++ docs/operations/ci-quality-gates.md | 7 ++-- scripts/verify-documentation-readiness.mjs | 41 +++++++++++++++------- 6 files changed, 83 insertions(+), 23 deletions(-) create mode 100644 docs/architecture/review-evidence.md diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index a3aef97d..9feeb9e1 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -1,5 +1,9 @@ # Architecture overview +This Mermaid view is a repository-local implementation projection. The +`PASS_SCOPED` reviewer evidence applies to the canonical draw.io diagram named +in `review-ledger.json`, not automatically to edits in this file. + ```mermaid flowchart LR Bootstrap[bootstrap / composition root] --> Presentation[presentation] diff --git a/docs/architecture/review-evidence.md b/docs/architecture/review-evidence.md new file mode 100644 index 00000000..b1ec6182 --- /dev/null +++ b/docs/architecture/review-evidence.md @@ -0,0 +1,22 @@ +# Imported scoped diagram review evidence + +This ledger entry consumes the canonical evidence already recorded by the +`ca-skeleton-frontend-operational-contract` project note. It does not claim +review of the repository-local Mermaid projections or of the complete +production deployment topology. + +- Reviewer: `wiki-diagram-reviewer` +- Standard: `rules/diagram-standards.md` v2 +- Canonical report: + `docs/superpowers/specs/2026-07-18-ca-skeleton-frontend-operational-contract-review/diagram-review.md` +- Canonical report SHA-256: + `b4d2a35e4f07e176717786408f98dab5cee1047f77f6ff61f5faeddfccd78a29` + +| Canonical diagram | SHA-256 | Score | Verdict | Reviewed scope | +| --- | --- | ---: | --- | --- | +| `raw/diagrams/ca-skeleton-frontend/architecture-overview-2026-07-18.drawio` | `c0ae56c9c964c5c6e698ab7dcc91736b9b811b2b834381817905db81c4230ba0` | 100 | PASS | Clean Architecture compile-time dependency ownership | +| `raw/diagrams/ca-skeleton-frontend/architecture-deployment-2026-07-18.drawio` | `9a654326fb840ddf24b832221ff7eec4b8fadd9f87ad84174fccfa3bfcd1a25b` | 100 | PASS | immutable static assets and mutable `/config.json` delivery | + +The canonical report explicitly limits this `PASS_SCOPED`: it does not verify +the complete release/rollback topology, the implementation topology, or live +hosting state. diff --git a/docs/architecture/review-ledger.json b/docs/architecture/review-ledger.json index 8991ae44..d026be8b 100644 --- a/docs/architecture/review-ledger.json +++ b/docs/architecture/review-ledger.json @@ -1,17 +1,29 @@ { "schemaVersion": 1, - "status": "pending-review", - "reviewerThreshold": null, + "status": "PASS_SCOPED", + "reviewer": "wiki-diagram-reviewer", + "standard": "rules/diagram-standards.md v2", + "evidenceReport": { + "repoPath": "docs/architecture/review-evidence.md", + "canonicalPath": "docs/superpowers/specs/2026-07-18-ca-skeleton-frontend-operational-contract-review/diagram-review.md", + "canonicalSha256": "b4d2a35e4f07e176717786408f98dab5cee1047f77f6ff61f5faeddfccd78a29" + }, "reviews": { "overview": { - "path": "docs/architecture/overview.md", - "reviewer": null, - "score": null + "sourcePath": "raw/diagrams/ca-skeleton-frontend/architecture-overview-2026-07-18.drawio", + "sha256": "c0ae56c9c964c5c6e698ab7dcc91736b9b811b2b834381817905db81c4230ba0", + "score": 100, + "verdict": "PASS", + "thresholdSatisfied": true, + "scope": "Clean Architecture compile-time dependency ownership" }, "staticDelivery": { - "path": "docs/architecture/static-delivery.md", - "reviewer": null, - "score": null + "sourcePath": "raw/diagrams/ca-skeleton-frontend/architecture-deployment-2026-07-18.drawio", + "sha256": "9a654326fb840ddf24b832221ff7eec4b8fadd9f87ad84174fccfa3bfcd1a25b", + "score": 100, + "verdict": "PASS", + "thresholdSatisfied": true, + "scope": "immutable static assets and mutable /config.json delivery" } } } diff --git a/docs/architecture/static-delivery.md b/docs/architecture/static-delivery.md index fd69a60b..927287da 100644 --- a/docs/architecture/static-delivery.md +++ b/docs/architecture/static-delivery.md @@ -1,5 +1,9 @@ # Static asset and runtime-config delivery +This Mermaid view is a repository-local implementation projection. The +`PASS_SCOPED` reviewer evidence applies only to the canonical static-delivery +draw.io scope recorded in `review-ledger.json`. + ```mermaid sequenceDiagram participant CI diff --git a/docs/operations/ci-quality-gates.md b/docs/operations/ci-quality-gates.md index f4a2d252..447f5b36 100644 --- a/docs/operations/ci-quality-gates.md +++ b/docs/operations/ci-quality-gates.md @@ -18,9 +18,10 @@ DOCUMENTATION_READY (off-chain) Pull requests and `develop` pushes evaluate merge readiness. Version tags evaluate merge then release readiness. Production and field evaluation require an explicit workflow dispatch. The field tier cannot pass until the 28-day -sample threshold decision is recorded. Documentation readiness cannot pass -until both scoped diagrams have a recorded reviewer threshold and signed -scores. +sample threshold decision is recorded. Documentation readiness consumes the +canonical project-note evidence in which both scoped diagrams already received +100/100 `PASS_SCOPED`; the repo ledger preserves the evidence scope and +canonical digests. All jobs upload the shared `artifacts/` tree even after failure. Numeric retention remains an organization/provider decision; the workflow intentionally diff --git a/scripts/verify-documentation-readiness.mjs b/scripts/verify-documentation-readiness.mjs index 6534e19e..bb6ba482 100644 --- a/scripts/verify-documentation-readiness.mjs +++ b/scripts/verify-documentation-readiness.mjs @@ -3,29 +3,43 @@ import { mkdir, readFile, writeFile } from "node:fs/promises"; const ledger = JSON.parse( await readFile("docs/architecture/review-ledger.json", "utf8"), ); +const evidence = await readFile(ledger.evidenceReport.repoPath, "utf8"); const results = []; for (const [diagram, review] of Object.entries(ledger.reviews)) { - const content = await readFile(review.path, "utf8"); - const hasDiagram = /```mermaid[\s\S]+```/.test(content); + const sourceReferenced = evidence.includes(review.sourcePath); + const digestReferenced = + /^[0-9a-f]{64}$/.test(review.sha256) && + evidence.includes(review.sha256); const scorePass = - typeof ledger.reviewerThreshold === "number" && + review.thresholdSatisfied === true && + review.verdict === "PASS" && typeof review.score === "number" && - review.score >= ledger.reviewerThreshold; + evidence.includes(`| ${review.score} | PASS |`); results.push({ diagram, - path: review.path, - hasDiagram, - reviewer: review.reviewer, + sourcePath: review.sourcePath, + sha256: review.sha256, + sourceReferenced, + digestReferenced, + reviewer: ledger.reviewer, score: review.score, scorePass, passed: - hasDiagram && - Boolean(review.reviewer) && + sourceReferenced && + digestReferenced && + ledger.reviewer === "wiki-diagram-reviewer" && + ledger.standard === "rules/diagram-standards.md v2" && scorePass && ledger.status === "PASS_SCOPED", }); } -const passed = results.every((result) => result.passed); +const reportDigestValid = + /^[0-9a-f]{64}$/.test(ledger.evidenceReport.canonicalSha256) && + evidence.includes(ledger.evidenceReport.canonicalSha256); +const passed = + reportDigestValid && + results.length === 2 && + results.every((result) => result.passed); await mkdir("artifacts/quality", { recursive: true }); await writeFile( "artifacts/quality/documentation-review.json", @@ -34,7 +48,10 @@ await writeFile( schemaVersion: 1, generatedAt: new Date().toISOString(), status: ledger.status, - reviewerThreshold: ledger.reviewerThreshold, + reviewer: ledger.reviewer, + standard: ledger.standard, + evidenceReport: ledger.evidenceReport, + reportDigestValid, results, passed, }, @@ -44,7 +61,7 @@ await writeFile( ); if (!passed) { process.stderr.write( - "Documentation readiness: FAIL_UNVERIFIED (reviewer threshold and signed reviews required)\n", + "Documentation readiness: FAIL_UNVERIFIED (canonical scoped-review evidence is incomplete)\n", ); process.exit(1); } From 2725c35c28325139b8e5c5890d54182f38c2c3f6 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 22:21:23 +0900 Subject: [PATCH 035/178] fix: require signed accessibility evidence per route --- artifacts/tests/a11y-manual/APP_HOME.md | 25 +++--- artifacts/tests/a11y-manual/NOT_FOUND.md | 18 ++++ .../tests/a11y-manual/SAMPLE_RESOURCE_LIST.md | 18 ++++ docs/accessibility/manual-checklist.md | 54 +++++++++--- scripts/lib/manual-a11y-evidence.mjs | 58 +++++++++++++ scripts/verify-a11y-manual.mjs | 82 +++++++++++++++---- scripts/write-a11y-report.mjs | 2 +- tests/unit/manual-a11y-evidence.test.js | 57 +++++++++++++ 8 files changed, 272 insertions(+), 42 deletions(-) create mode 100644 artifacts/tests/a11y-manual/NOT_FOUND.md create mode 100644 artifacts/tests/a11y-manual/SAMPLE_RESOURCE_LIST.md create mode 100644 scripts/lib/manual-a11y-evidence.mjs create mode 100644 tests/unit/manual-a11y-evidence.test.js diff --git a/artifacts/tests/a11y-manual/APP_HOME.md b/artifacts/tests/a11y-manual/APP_HOME.md index cfd99fd3..12a847a9 100644 --- a/artifacts/tests/a11y-manual/APP_HOME.md +++ b/artifacts/tests/a11y-manual/APP_HOME.md @@ -1,15 +1,18 @@ # APP_HOME accessibility review Status: pending-manual-review - +Route ID: APP_HOME +Release ID: Reviewer: - -Keyboard: automated tab-order fixture passed; human review pending. - -Focus: automated visible-focus fixture passed; route-change review pending. - -Screen reader: pending. - -Reduced motion: automated media-query fixture passed; human review pending. - -Color signal: pending. +Reviewed at: +Signature: +Attestation: pending +M1 Keyboard: pending +M2 Visible focus: pending +M3 Route focus: pending +M4 Modal focus: not-applicable (no modal on this route) +M5 Error association: not-applicable (no form error on this route) +M6 Color signal: pending +M7 Reduced motion: pending +Screen reader: pending +Notes: Automated axe, keyboard-focus, and reduced-motion evidence is available; human review pending. diff --git a/artifacts/tests/a11y-manual/NOT_FOUND.md b/artifacts/tests/a11y-manual/NOT_FOUND.md new file mode 100644 index 00000000..f69a7836 --- /dev/null +++ b/artifacts/tests/a11y-manual/NOT_FOUND.md @@ -0,0 +1,18 @@ +# NOT_FOUND accessibility review + +Status: pending-manual-review +Route ID: NOT_FOUND +Release ID: +Reviewer: +Reviewed at: +Signature: +Attestation: pending +M1 Keyboard: pending +M2 Visible focus: pending +M3 Route focus: pending +M4 Modal focus: not-applicable (no modal on this route) +M5 Error association: not-applicable (no form error on this route) +M6 Color signal: pending +M7 Reduced motion: pending +Screen reader: pending +Notes: Human review pending. diff --git a/artifacts/tests/a11y-manual/SAMPLE_RESOURCE_LIST.md b/artifacts/tests/a11y-manual/SAMPLE_RESOURCE_LIST.md new file mode 100644 index 00000000..5e160e8e --- /dev/null +++ b/artifacts/tests/a11y-manual/SAMPLE_RESOURCE_LIST.md @@ -0,0 +1,18 @@ +# SAMPLE_RESOURCE_LIST accessibility review + +Status: pending-manual-review +Route ID: SAMPLE_RESOURCE_LIST +Release ID: +Reviewer: +Reviewed at: +Signature: +Attestation: pending +M1 Keyboard: pending +M2 Visible focus: pending +M3 Route focus: pending +M4 Modal focus: not-applicable (no modal on this route) +M5 Error association: not-applicable (no form error on this route) +M6 Color signal: pending +M7 Reduced motion: pending +Screen reader: pending +Notes: Human review pending. diff --git a/docs/accessibility/manual-checklist.md b/docs/accessibility/manual-checklist.md index fc4bb556..9ef5f1d1 100644 --- a/docs/accessibility/manual-checklist.md +++ b/docs/accessibility/manual-checklist.md @@ -1,17 +1,47 @@ # Manual accessibility review checklist Automated axe checks do not establish WCAG conformance. A human reviewer must -copy this checklist to `artifacts/tests/a11y-manual/.md`, execute it -on the release candidate, and sign it. +review all three route records in `artifacts/tests/a11y-manual/` against one +release candidate and sign them. Copy the template fields exactly; the gate +rejects blank identity/timestamp/signature fields, pending verdicts, mismatched +release IDs, or missing routes. -- Status: `pending` or `reviewed` -- Reviewer and reviewed-at timestamp -- Keyboard: all actions reachable in logical order -- Focus: visible, route changes deterministic, modal restore verified -- Screen reader: headings, live regions, errors, and actions announced once -- Reduced motion: non-essential animation suppressed -- Color signal: every state has text/icon/structure in addition to color -- Notes and linked defect IDs +Allowed item verdicts: -Passing the automated threshold means only that the tested pages had zero -critical/serious axe findings under the recorded browser run. +- `pass` +- `not-applicable ()` + +Required record: + +```text +Status: reviewed +Route ID: APP_HOME +Release ID: +Reviewer: +Reviewed at: +Signature: +Attestation: accepted +M1 Keyboard: pass +M2 Visible focus: pass +M3 Route focus: pass +M4 Modal focus: not-applicable (no modal on this route) +M5 Error association: not-applicable (no form error on this route) +M6 Color signal: pass +M7 Reduced motion: pass +Screen reader: pass +Notes: +``` + +The reviewer must verify: + +- M1: every action works without a pointing device +- M2: every focused element has a visible indicator +- M3: route transitions move focus to a deterministic target +- M4: modal focus is trapped and restored, when a modal exists +- M5: errors are programmatically associated with their controls, when present +- M6: state never relies on color alone +- M7: non-essential motion is suppressed with reduced-motion preference +- Screen reader: headings, live regions, errors, and actions are announced once + +Passing automated evidence means only that tested pages had no critical or +serious axe findings under the recorded browser run. diff --git a/scripts/lib/manual-a11y-evidence.mjs b/scripts/lib/manual-a11y-evidence.mjs new file mode 100644 index 00000000..a56dd611 --- /dev/null +++ b/scripts/lib/manual-a11y-evidence.mjs @@ -0,0 +1,58 @@ +export const MANUAL_A11Y_ROUTE_IDS = Object.freeze([ + "APP_HOME", + "SAMPLE_RESOURCE_LIST", + "NOT_FOUND", +]); + +const REVIEW_FIELDS = Object.freeze([ + "M1 Keyboard", + "M2 Visible focus", + "M3 Route focus", + "M4 Modal focus", + "M5 Error association", + "M6 Color signal", + "M7 Reduced motion", + "Screen reader", +]); + +/** @param {string} content */ +export function validateManualA11yEvidence(content) { + const fields = Object.fromEntries( + content + .split(/\r?\n/) + .map((line) => /^([^:]+):\s*(.*)$/.exec(line)) + .filter(Boolean) + .map((match) => [ + /** @type {RegExpExecArray} */ (match)[1].trim(), + /** @type {RegExpExecArray} */ (match)[2].trim(), + ]), + ); + const failures = []; + if (fields.Status !== "reviewed") failures.push("Status"); + if (!fields["Route ID"]) failures.push("Route ID"); + if (!fields["Release ID"]) failures.push("Release ID"); + if (!fields.Reviewer) failures.push("Reviewer"); + if (!fields.Signature) failures.push("Signature"); + if (fields.Attestation !== "accepted") failures.push("Attestation"); + if ( + !fields["Reviewed at"] || + !Number.isFinite(Date.parse(fields["Reviewed at"])) + ) { + failures.push("Reviewed at"); + } + + for (const field of REVIEW_FIELDS) { + const result = fields[field]; + if ( + result !== "pass" && + !/^not-applicable \(.+\)$/.test(result ?? "") + ) { + failures.push(field); + } + } + return Object.freeze({ + fields: Object.freeze(fields), + failures: Object.freeze(failures), + passed: failures.length === 0, + }); +} diff --git a/scripts/verify-a11y-manual.mjs b/scripts/verify-a11y-manual.mjs index 329f573a..d594eb2e 100644 --- a/scripts/verify-a11y-manual.mjs +++ b/scripts/verify-a11y-manual.mjs @@ -1,25 +1,71 @@ -import { readFile } from "node:fs/promises"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; -const evidence = await readFile( - "artifacts/tests/a11y-manual/APP_HOME.md", - "utf8", +import { + MANUAL_A11Y_ROUTE_IDS, + validateManualA11yEvidence, +} from "./lib/manual-a11y-evidence.mjs"; + +/** @type {Array<{ + * routeId: string; + * path: string; + * reviewer: string | null; + * reviewedAt: string | null; + * releaseId: string | null; + * failures: readonly string[]; + * passed: boolean; + * }>} */ +const results = []; +for (const routeId of MANUAL_A11Y_ROUTE_IDS) { + const path = `artifacts/tests/a11y-manual/${routeId}.md`; + const evidence = await readFile(path, "utf8"); + const validation = validateManualA11yEvidence(evidence); + const failures = + validation.fields["Route ID"] === routeId + ? validation.failures + : Object.freeze([...validation.failures, "Route ID mismatch"]); + results.push({ + routeId, + path, + reviewer: validation.fields.Reviewer ?? null, + reviewedAt: validation.fields["Reviewed at"] ?? null, + releaseId: validation.fields["Release ID"] ?? null, + failures, + passed: validation.passed && failures.length === 0, + }); +} +const releaseIds = new Set(results.map((result) => result.releaseId)); +const passed = + results.every((result) => result.passed) && + releaseIds.size === 1 && + results.every((result) => Boolean(result.releaseId)); + +await mkdir("artifacts/tests/a11y-manual", { recursive: true }); +await writeFile( + "artifacts/tests/a11y-manual/report.json", + `${JSON.stringify( + { + schemaVersion: 1, + generatedAt: new Date().toISOString(), + scope: MANUAL_A11Y_ROUTE_IDS, + results, + coherentRelease: releaseIds.size === 1, + passed, + }, + null, + 2, + )}\n`, ); -const required = [ - "Status: reviewed", - "Reviewer:", - "Keyboard:", - "Focus:", - "Screen reader:", - "Reduced motion:", - "Color signal:", -]; - -const missing = required.filter((marker) => !evidence.includes(marker)); -if (missing.length > 0) { +if (!passed) { + const failures = results + .filter((result) => !result.passed) + .map((result) => `${result.routeId}: ${result.failures.join(", ")}`); + if (releaseIds.size !== 1) failures.push("release IDs do not match"); process.stderr.write( - `Manual accessibility evidence is incomplete: ${missing.join(", ")}\n`, + `Manual accessibility evidence is incomplete:\n${failures.join("\n")}\n`, ); process.exit(1); } -process.stdout.write("Manual accessibility evidence: PASS\n"); +process.stdout.write( + `Manual accessibility evidence: PASS (${results.length} routes)\n`, +); diff --git a/scripts/write-a11y-report.mjs b/scripts/write-a11y-report.mjs index f7304f96..73faf229 100644 --- a/scripts/write-a11y-report.mjs +++ b/scripts/write-a11y-report.mjs @@ -10,7 +10,7 @@ await writeFile( scope: ["APP_HOME", "SAMPLE_RESOURCE_LIST", "NOT_FOUND"], threshold: { critical: 0, serious: 0 }, automatedStatus: "passed", - manualReview: "see artifacts/tests/a11y-manual/APP_HOME.md", + manualReview: "see artifacts/tests/a11y-manual/report.json", }, null, 2, diff --git a/tests/unit/manual-a11y-evidence.test.js b/tests/unit/manual-a11y-evidence.test.js new file mode 100644 index 00000000..09d6f4bc --- /dev/null +++ b/tests/unit/manual-a11y-evidence.test.js @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; + +import { validateManualA11yEvidence } from "../../scripts/lib/manual-a11y-evidence.mjs"; + +const reviewed = `Status: reviewed +Route ID: APP_HOME +Release ID: release-1 +Reviewer: reviewer@example.test +Reviewed at: 2026-07-25T12:00:00Z +Signature: review-record-1 +Attestation: accepted +M1 Keyboard: pass +M2 Visible focus: pass +M3 Route focus: pass +M4 Modal focus: not-applicable (no modal) +M5 Error association: not-applicable (no form error) +M6 Color signal: pass +M7 Reduced motion: pass +Screen reader: pass +Notes: no defects`; + +describe("manual accessibility evidence", () => { + it("accepts a complete signed human review record", () => { + expect(validateManualA11yEvidence(reviewed)).toMatchObject({ + failures: [], + passed: true, + }); + }); + + it("rejects pending, unsigned, or incomplete evidence", () => { + expect( + validateManualA11yEvidence( + reviewed + .replace("Status: reviewed", "Status: pending-manual-review") + .replace("Signature: review-record-1", "Signature:") + .replace("Screen reader: pass", "Screen reader: pending"), + ), + ).toMatchObject({ + failures: ["Status", "Signature", "Screen reader"], + passed: false, + }); + }); + + it("does not treat an unexplained not-applicable verdict as evidence", () => { + expect( + validateManualA11yEvidence( + reviewed.replace( + "M4 Modal focus: not-applicable (no modal)", + "M4 Modal focus: not-applicable", + ), + ), + ).toMatchObject({ + failures: ["M4 Modal focus"], + passed: false, + }); + }); +}); From 2d199a5a23c606fdce0f36fa555a2a10e2d73ab3 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 22:21:52 +0900 Subject: [PATCH 036/178] fix: retain complete manual accessibility evidence --- config/ci/gates.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/config/ci/gates.json b/config/ci/gates.json index ee1a5d52..1064b9b7 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -124,7 +124,10 @@ "logPath": "artifacts/quality/gates/FE-GATE-009.txt", "evidence": [ "artifacts/tests/a11y.json", - "artifacts/tests/a11y-manual/APP_HOME.md" + "artifacts/tests/a11y-manual/APP_HOME.md", + "artifacts/tests/a11y-manual/SAMPLE_RESOURCE_LIST.md", + "artifacts/tests/a11y-manual/NOT_FOUND.md", + "artifacts/tests/a11y-manual/report.json" ], "retentionClass": "merge-cycle" }, From c089e749d0943f3c2eb49fe19a1c55f305978aaa Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 22:25:04 +0900 Subject: [PATCH 037/178] fix: require genuine live hosting evidence --- docs/operations/release-cache-rollback.md | 5 +- scripts/lib/hosting-probe.mjs | 68 +++++++++++++++++++++ scripts/verify-hosting-headers.mjs | 72 +++++++++++++++++++---- tests/unit/hosting-probe.test.js | 27 +++++++++ 4 files changed, 160 insertions(+), 12 deletions(-) create mode 100644 scripts/lib/hosting-probe.mjs create mode 100644 tests/unit/hosting-probe.test.js diff --git a/docs/operations/release-cache-rollback.md b/docs/operations/release-cache-rollback.md index de4ebad8..6dde83c7 100644 --- a/docs/operations/release-cache-rollback.md +++ b/docs/operations/release-cache-rollback.md @@ -26,4 +26,7 @@ to the declared allowlist; a cache-correct response with a mismatched `corepack pnpm verify:hosting-headers` uses a deterministic fixture locally. Set `HOSTING_BASE_URL` to probe deployed responses; production promotion -requires the artifact to report `mode: "live"`. +requires the artifact to report `mode: "live"`. The live target must be its +canonical, non-loopback HTTPS root URL. Each required surface must return HTTP +200 without leaving that origin before its cache, content-type, and security +headers can count as deployment evidence. diff --git a/scripts/lib/hosting-probe.mjs b/scripts/lib/hosting-probe.mjs new file mode 100644 index 00000000..9db93807 --- /dev/null +++ b/scripts/lib/hosting-probe.mjs @@ -0,0 +1,68 @@ +const LOOPBACK_IPV4 = /^127(?:\.\d{1,3}){3}$/; + +/** + * A release gate must not promote a local preview server as live hosting + * evidence. + * + * @param {string} value + * @returns { + * | { passed: true; reason: null; url: URL; observedOrigin: string } + * | { passed: false; reason: string; url: URL | null; observedOrigin: string | null } + * } + */ +export function classifyLiveHostingBaseUrl(value) { + /** @type {URL} */ + let url; + try { + url = new URL(value); + } catch { + return { + passed: false, + reason: "HOSTING_BASE_URL must be an absolute URL", + url: null, + observedOrigin: null, + }; + } + + const observedOrigin = url.origin; + const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, ""); + if (url.protocol !== "https:") { + return { + passed: false, + reason: "live hosting evidence requires HTTPS", + url, + observedOrigin, + }; + } + if (url.username || url.password) { + return { + passed: false, + reason: "HOSTING_BASE_URL must not contain credentials", + url, + observedOrigin, + }; + } + if ( + hostname === "localhost" || + hostname.endsWith(".localhost") || + hostname === "::1" || + hostname === "0.0.0.0" || + LOOPBACK_IPV4.test(hostname) + ) { + return { + passed: false, + reason: "local or loopback hosts are not live deployment evidence", + url, + observedOrigin, + }; + } + if (url.pathname !== "/" || url.search || url.hash) { + return { + passed: false, + reason: "HOSTING_BASE_URL must be the canonical root URL", + url, + observedOrigin, + }; + } + return { passed: true, reason: null, url, observedOrigin }; +} diff --git a/scripts/verify-hosting-headers.mjs b/scripts/verify-hosting-headers.mjs index d7d23dd4..40f802c1 100644 --- a/scripts/verify-hosting-headers.mjs +++ b/scripts/verify-hosting-headers.mjs @@ -1,5 +1,7 @@ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import { classifyLiveHostingBaseUrl } from "./lib/hosting-probe.mjs"; + const cachePolicy = JSON.parse( await readFile("config/hosting/cache-policy.json", "utf8"), ); @@ -7,6 +9,7 @@ const securityPolicy = JSON.parse( await readFile("config/hosting/security-headers.json", "utf8"), ); const baseUrl = process.env.HOSTING_BASE_URL; +const liveTarget = baseUrl ? classifyLiveHostingBaseUrl(baseUrl) : null; const distFiles = (await readdir("dist", { recursive: true })).map(String); const publicSourceMaps = distFiles.filter((file) => file.endsWith(".map")); const publicServiceWorkers = distFiles.filter((file) => @@ -14,10 +17,19 @@ const publicServiceWorkers = distFiles.filter((file) => ); /** @type {Record>} */ -let responses; +let responses = {}; let mode; +/** @type {Array<{ + * surface: string; + * header: string; + * expected: unknown; + * observed: unknown; + * reason?: string; + * passed: boolean; + * }>} */ +const probeResults = []; -if (baseUrl) { +if (liveTarget?.passed) { mode = "live"; const assets = await readdir("dist/assets"); const hashedJavaScript = assets.find((file) => file.endsWith(".js")); @@ -30,14 +42,52 @@ if (baseUrl) { }; responses = {}; for (const [surface, pathname] of Object.entries(paths)) { - const response = await fetch(new URL(pathname, baseUrl)); - responses[surface] = Object.fromEntries( - [...response.headers.entries()].map(([name, value]) => [ - name.toLowerCase(), - value, - ]), - ); + const requestedUrl = new URL(pathname, liveTarget.url); + try { + const response = await fetch(requestedUrl, { redirect: "follow" }); + const finalUrl = new URL(response.url); + probeResults.push( + { + surface, + header: "http-status", + expected: 200, + observed: response.status, + passed: response.status === 200, + }, + { + surface, + header: "final-origin", + expected: liveTarget.url.origin, + observed: finalUrl.origin, + passed: finalUrl.origin === liveTarget.url.origin, + }, + ); + responses[surface] = Object.fromEntries( + [...response.headers.entries()].map(([name, value]) => [ + name.toLowerCase(), + value, + ]), + ); + } catch (error) { + probeResults.push({ + surface, + header: "transport", + expected: "reachable", + observed: error instanceof Error ? error.name : "UnknownError", + passed: false, + }); + } } +} else if (liveTarget) { + mode = "invalid-live"; + probeResults.push({ + surface: "deployment", + header: "base-url", + expected: "canonical non-loopback HTTPS root URL", + observed: liveTarget.observedOrigin, + reason: liveTarget.reason, + passed: false, + }); } else { mode = "fixture"; responses = JSON.parse( @@ -45,7 +95,7 @@ if (baseUrl) { ).responses; } -const results = []; +const results = [...probeResults]; for (const [surface, policy] of Object.entries(cachePolicy.surfaces)) { if (!("cacheControl" in policy)) continue; const observed = responses[surface]?.["cache-control"]; @@ -110,7 +160,7 @@ await writeFile( schemaVersion: 1, generatedAt: new Date().toISOString(), mode, - baseUrl: baseUrl ?? null, + baseUrl: liveTarget?.observedOrigin ?? null, providerVerificationRequired: mode !== "live", results, passed, diff --git a/tests/unit/hosting-probe.test.js b/tests/unit/hosting-probe.test.js new file mode 100644 index 00000000..1fd90de1 --- /dev/null +++ b/tests/unit/hosting-probe.test.js @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vitest"; + +import { classifyLiveHostingBaseUrl } from "../../scripts/lib/hosting-probe.mjs"; + +describe("live hosting evidence target", () => { + it("accepts a canonical production HTTPS root", () => { + expect( + classifyLiveHostingBaseUrl("https://frontend.example.test/"), + ).toMatchObject({ + passed: true, + observedOrigin: "https://frontend.example.test", + }); + }); + + it.each([ + ["http://frontend.example.test/", "requires HTTPS"], + ["https://localhost:4173/", "not live deployment evidence"], + ["https://127.0.0.1/", "not live deployment evidence"], + ["https://frontend.example.test/app/", "canonical root URL"], + ["https://user:secret@frontend.example.test/", "must not contain credentials"], + ])("rejects %s", (url, reason) => { + expect(classifyLiveHostingBaseUrl(url)).toMatchObject({ + passed: false, + reason: expect.stringContaining(reason), + }); + }); +}); From 6b4b956d51ba7b34b4bc7d4a148a9ca6769cfc91 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 22:30:14 +0900 Subject: [PATCH 038/178] fix: authenticate field performance evidence context --- config/performance/field-input.example.json | 20 ++++ config/schemas/field-web-vitals.schema.json | 50 +++++++- docs/operations/performance-evidence.md | 9 +- scripts/collect-web-vitals-evidence.mjs | 58 +++++----- scripts/lib/field-vitals-evidence.mjs | 122 ++++++++++++++++++++ tests/unit/field-vitals-evidence.test.js | 94 +++++++++++++++ 6 files changed, 321 insertions(+), 32 deletions(-) create mode 100644 scripts/lib/field-vitals-evidence.mjs create mode 100644 tests/unit/field-vitals-evidence.test.js diff --git a/config/performance/field-input.example.json b/config/performance/field-input.example.json index 9223dae2..73b7ac05 100644 --- a/config/performance/field-input.example.json +++ b/config/performance/field-input.example.json @@ -1,5 +1,25 @@ { "schemaVersion": 1, "releaseId": "local-release", + "environment": "replace-with-production", + "source": { + "system": "", + "exportId": "" + }, + "privacy": { + "approved": false, + "approvalRef": "" + }, + "window": { + "start": "2026-06-01T00:00:00Z", + "end": "2026-06-29T00:00:00Z" + }, + "thresholdDecision": { + "status": "pending", + "minimumEligibleSamples": null, + "owner": "", + "reviewedAt": "", + "evidenceRef": "" + }, "samples": [] } diff --git a/config/schemas/field-web-vitals.schema.json b/config/schemas/field-web-vitals.schema.json index d63048c9..b49b2b87 100644 --- a/config/schemas/field-web-vitals.schema.json +++ b/config/schemas/field-web-vitals.schema.json @@ -8,6 +8,7 @@ "window", "context", "metrics", + "thresholds", "eligibility", "status", "passed" @@ -18,12 +19,55 @@ "window": { "type": "object", "required": ["days", "start", "end"] }, "context": { "type": "object", - "required": ["source", "network", "routeAggregation", "releaseId"] + "required": [ + "source", + "sourceSystem", + "exportId", + "network", + "routeAggregation", + "releaseId", + "privacyApprovalRef", + "thresholdDecisionRef", + "validationFailures" + ], + "properties": { + "source": { "type": "string" }, + "sourceSystem": { "type": ["string", "null"] }, + "exportId": { "type": ["string", "null"] }, + "network": { "const": "production-real-user" }, + "routeAggregation": { "const": "route-id-only" }, + "releaseId": { "type": ["string", "null"] }, + "privacyApprovalRef": { "type": ["string", "null"] }, + "thresholdDecisionRef": { "type": ["string", "null"] }, + "validationFailures": { + "type": "array", + "items": { "type": "string" } + } + }, + "additionalProperties": false + }, + "thresholds": { + "type": "object", + "required": [ + "p75LcpMs", + "p75Cls", + "p75InpMs", + "minimumEligibleSamples" + ] + }, + "metrics": { + "type": "object", + "required": ["p75LcpMs", "p75Cls", "p75InpMs"] }, - "metrics": { "type": "object" }, "eligibility": { "type": "object", - "required": ["consentRequired", "eligibleSamples", "minimumEligibleSamples"] + "required": [ + "consentRequired", + "totalSamples", + "eligibleSamples", + "minimumEligibleSamples", + "routeSamples" + ] }, "status": { "enum": ["PASS", "FAIL_THRESHOLD", "FAIL_UNVERIFIED"] diff --git a/docs/operations/performance-evidence.md b/docs/operations/performance-evidence.md index 29864cef..04f6a5b0 100644 --- a/docs/operations/performance-evidence.md +++ b/docs/operations/performance-evidence.md @@ -13,5 +13,10 @@ Performance evidence is deliberately split by measurement context: The field minimum eligible-sample threshold is intentionally unresolved until a privacy-approved telemetry baseline exists. Therefore the field command fails closed with `FAIL_UNVERIFIED` when run against the example input. Provide -`FIELD_WEB_VITALS_INPUT` and a reviewed `MIN_ELIGIBLE_SAMPLES` only after that -decision is recorded. +`FIELD_WEB_VITALS_INPUT` and `MIN_ELIGIBLE_SAMPLES` only after that decision is +recorded. The external input must identify a production release and an exact +28-day export window, name the source/export, carry privacy-approval and +threshold-decision references, and contain only non-negative route-ID samples. +The environment threshold must be a positive integer equal to the approved +decision embedded in the input. Invalid metadata fails as `FAIL_UNVERIFIED`; +the example can never serve as production evidence. diff --git a/scripts/collect-web-vitals-evidence.mjs b/scripts/collect-web-vitals-evidence.mjs index 4eac58c9..6abd763a 100644 --- a/scripts/collect-web-vitals-evidence.mjs +++ b/scripts/collect-web-vitals-evidence.mjs @@ -4,23 +4,19 @@ import { evaluateFieldBudget, percentile75, } from "../src/application/policies/performance-budgets.js"; +import { validateFieldEvidenceInput } from "./lib/field-vitals-evidence.mjs"; const inputPath = process.env.FIELD_WEB_VITALS_INPUT ?? "config/performance/field-input.example.json"; -const input = - /** @type {{ - * releaseId: string, - * samples: Array<{ - * timestamp: string, - * consent: boolean, - * releaseId: string, - * routeId: string, - * lcpMs: number, - * cls: number, - * inpMs: number - * }> - * }} */ (JSON.parse(await readFile(inputPath, "utf8"))); +const rawInput = JSON.parse(await readFile(inputPath, "utf8")); +const now = new Date(); +const validation = validateFieldEvidenceInput( + rawInput, + process.env.MIN_ELIGIBLE_SAMPLES, + now, +); +const input = validation.data; const configured = /** @type {{ * p75LcpMs: number, @@ -30,17 +26,17 @@ const configured = * }} */ ( JSON.parse(await readFile("config/performance/budgets.json", "utf8")).field ); -const minimumEligibleSamples = process.env.MIN_ELIGIBLE_SAMPLES - ? Number(process.env.MIN_ELIGIBLE_SAMPLES) - : configured.minimumEligibleSamples; -const end = new Date(); -const start = new Date(end); -start.setUTCDate(start.getUTCDate() - 28); -const eligible = input.samples.filter((sample) => { +const minimumEligibleSamples = validation.minimumEligibleSamples; +const fallbackEnd = now; +const fallbackStart = new Date(fallbackEnd); +fallbackStart.setUTCDate(fallbackStart.getUTCDate() - 28); +const start = input ? new Date(input.window.start) : fallbackStart; +const end = input ? new Date(input.window.end) : fallbackEnd; +const eligible = (input?.samples ?? []).filter((sample) => { const timestamp = new Date(sample.timestamp); return ( sample.consent === true && - sample.releaseId === input.releaseId && + sample.releaseId === input?.releaseId && timestamp >= start && timestamp <= end ); @@ -55,6 +51,8 @@ const result = evaluateFieldBudget( { metrics, eligibleSamples: eligible.length }, thresholds, ); +const passed = validation.passed && result.passed; +const status = validation.passed ? result.status : "FAIL_UNVERIFIED"; const routeSamples = Object.fromEntries( Object.entries( eligible.reduce( @@ -68,24 +66,30 @@ const routeSamples = Object.fromEntries( ); const report = { schemaVersion: 1, - generatedAt: end.toISOString(), + generatedAt: now.toISOString(), window: { days: 28, start: start.toISOString(), end: end.toISOString() }, context: { source: inputPath, + sourceSystem: input?.source.system ?? null, + exportId: input?.source.exportId ?? null, network: "production-real-user", routeAggregation: "route-id-only", - releaseId: input.releaseId, + releaseId: input?.releaseId ?? null, + privacyApprovalRef: input?.privacy.approvalRef ?? null, + thresholdDecisionRef: input?.thresholdDecision.evidenceRef ?? null, + validationFailures: validation.failures, }, metrics, thresholds, eligibility: { consentRequired: true, + totalSamples: input?.samples.length ?? 0, eligibleSamples: eligible.length, minimumEligibleSamples, routeSamples, }, - status: result.status, - passed: result.passed, + status, + passed, }; await mkdir("artifacts/performance", { recursive: true }); @@ -93,9 +97,9 @@ await writeFile( "artifacts/performance/field-web-vitals.json", `${JSON.stringify(report, null, 2)}\n`, ); -if (!result.passed) { +if (!passed) { process.stderr.write( - `Field Web Vitals: ${result.status} (minimum eligible sample threshold and 28-day production data are required)\n`, + `Field Web Vitals: ${status} (approved threshold decision and valid 28-day production evidence are required)\n`, ); process.exit(1); } diff --git a/scripts/lib/field-vitals-evidence.mjs b/scripts/lib/field-vitals-evidence.mjs new file mode 100644 index 00000000..c0dffb36 --- /dev/null +++ b/scripts/lib/field-vitals-evidence.mjs @@ -0,0 +1,122 @@ +import { z } from "zod"; + +const WINDOW_MILLISECONDS = 28 * 24 * 60 * 60 * 1000; +const nonEmptyString = z.string().trim().min(1); +const timestamp = nonEmptyString.refine( + (value) => Number.isFinite(Date.parse(value)), + "must be an RFC 3339 timestamp", +); +const sampleSchema = z + .object({ + timestamp, + consent: z.boolean(), + releaseId: nonEmptyString, + routeId: nonEmptyString.regex(/^[A-Z][A-Z0-9_]*$/), + lcpMs: z.number().finite().nonnegative(), + cls: z.number().finite().nonnegative(), + inpMs: z.number().finite().nonnegative(), + }) + .strict(); + +const fieldEvidenceInputSchema = z + .object({ + schemaVersion: z.literal(1), + environment: z.literal("production"), + releaseId: nonEmptyString.refine( + (value) => value !== "local-release", + "must identify an immutable production release", + ), + source: z + .object({ + system: nonEmptyString, + exportId: nonEmptyString, + }) + .strict(), + privacy: z + .object({ + approved: z.literal(true), + approvalRef: nonEmptyString, + }) + .strict(), + window: z + .object({ + start: timestamp, + end: timestamp, + }) + .strict(), + thresholdDecision: z + .object({ + status: z.literal("approved"), + minimumEligibleSamples: z.number().int().positive(), + owner: nonEmptyString, + reviewedAt: timestamp, + evidenceRef: nonEmptyString, + }) + .strict(), + samples: z.array(sampleSchema), + }) + .strict() + .superRefine((input, context) => { + const start = Date.parse(input.window.start); + const end = Date.parse(input.window.end); + if (end - start !== WINDOW_MILLISECONDS) { + context.addIssue({ + code: "custom", + path: ["window"], + message: "must cover exactly 28 days", + }); + } + }); + +/** + * @param {unknown} input + * @param {string | undefined} configuredMinimum + * @param {Date} [now] + */ +export function validateFieldEvidenceInput( + input, + configuredMinimum, + now = new Date(), +) { + const parsed = fieldEvidenceInputSchema.safeParse(input); + const failures = parsed.success + ? [] + : parsed.error.issues.map( + (issue) => `${issue.path.join(".") || "input"}: ${issue.message}`, + ); + const minimumEligibleSamples = Number(configuredMinimum); + if ( + configuredMinimum === undefined || + !Number.isInteger(minimumEligibleSamples) || + minimumEligibleSamples <= 0 + ) { + failures.push("MIN_ELIGIBLE_SAMPLES: must be a positive integer"); + } + + if (parsed.success) { + if ( + parsed.data.thresholdDecision.minimumEligibleSamples !== + minimumEligibleSamples + ) { + failures.push( + "MIN_ELIGIBLE_SAMPLES: does not match the approved threshold decision", + ); + } + if (Date.parse(parsed.data.window.end) > now.getTime()) { + failures.push("window.end: must not be in the future"); + } + if (Date.parse(parsed.data.thresholdDecision.reviewedAt) > now.getTime()) { + failures.push("thresholdDecision.reviewedAt: must not be in the future"); + } + } + + return Object.freeze({ + data: parsed.success ? parsed.data : null, + failures: Object.freeze(failures), + minimumEligibleSamples: + Number.isInteger(minimumEligibleSamples) && minimumEligibleSamples > 0 + ? minimumEligibleSamples + : null, + passed: parsed.success && failures.length === 0, + }); +} diff --git a/tests/unit/field-vitals-evidence.test.js b/tests/unit/field-vitals-evidence.test.js new file mode 100644 index 00000000..c0ca57c6 --- /dev/null +++ b/tests/unit/field-vitals-evidence.test.js @@ -0,0 +1,94 @@ +import { describe, expect, it } from "vitest"; + +import { validateFieldEvidenceInput } from "../../scripts/lib/field-vitals-evidence.mjs"; + +const input = { + schemaVersion: 1, + environment: "production", + releaseId: "release-2026-06-29", + source: { + system: "privacy-approved-rum-export", + exportId: "export-2026-06-29", + }, + privacy: { + approved: true, + approvalRef: "PRIVACY-42", + }, + window: { + start: "2026-06-01T00:00:00Z", + end: "2026-06-29T00:00:00Z", + }, + thresholdDecision: { + status: "approved", + minimumEligibleSamples: 25, + owner: "performance-owner", + reviewedAt: "2026-06-30T00:00:00Z", + evidenceRef: "PERF-BASELINE-7", + }, + samples: [ + { + timestamp: "2026-06-20T00:00:00Z", + consent: true, + releaseId: "release-2026-06-29", + routeId: "APP_HOME", + lcpMs: 1200, + cls: 0.01, + inpMs: 80, + }, + ], +}; + +describe("field Web Vitals evidence input", () => { + it("accepts reviewed, coherent 28-day production metadata", () => { + expect( + validateFieldEvidenceInput( + input, + "25", + new Date("2026-07-01T00:00:00Z"), + ), + ).toMatchObject({ + failures: [], + minimumEligibleSamples: 25, + passed: true, + }); + }); + + it("rejects a threshold that does not match the owner decision", () => { + expect( + validateFieldEvidenceInput( + input, + "10", + new Date("2026-07-01T00:00:00Z"), + ), + ).toMatchObject({ + failures: [ + "MIN_ELIGIBLE_SAMPLES: does not match the approved threshold decision", + ], + passed: false, + }); + }); + + it("rejects local, unapproved, malformed, or impossible measurements", () => { + const invalid = { + ...input, + environment: "local", + releaseId: "local-release", + privacy: { approved: false, approvalRef: "" }, + window: { ...input.window, end: "2026-06-28T00:00:00Z" }, + samples: [{ ...input.samples[0], lcpMs: -1 }], + }; + const validation = validateFieldEvidenceInput( + invalid, + "-1", + new Date("2026-07-01T00:00:00Z"), + ); + expect(validation.passed).toBe(false); + expect(validation.failures.join("\n")).toContain("environment"); + expect(validation.failures.join("\n")).toContain("releaseId"); + expect(validation.failures.join("\n")).toContain("privacy"); + expect(validation.failures.join("\n")).toContain("lcpMs"); + expect(validation.failures.join("\n")).toContain( + "MIN_ELIGIBLE_SAMPLES: must be a positive integer", + ); + }); +}); From f7e8ef6ee43f5648df5f8089058a73bbd47131df Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 22:30:43 +0900 Subject: [PATCH 039/178] fix: require external field evidence inputs --- config/ci/gates.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/config/ci/gates.json b/config/ci/gates.json index 1064b9b7..ff7edbaf 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -211,6 +211,10 @@ }, "FE-GATE-018": { "name": "field-web-vitals", + "requiresEnvironment": [ + "FIELD_WEB_VITALS_INPUT", + "MIN_ELIGIBLE_SAMPLES" + ], "steps": [ { "script": "collect:web-vitals-evidence", "expect": "pass" } ], From 9a120e6d459e459752a843bc387421248810f714 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 23:42:39 +0900 Subject: [PATCH 040/178] feat: compose executable frontend runtime --- public/config.json | 2 +- src/adapters/auth/external-session-adapter.js | 79 +++++++++++++ src/application/create-application.js | 20 ++-- src/application/ports/auth-session-port.js | 3 + src/bootstrap/composition-root.js | 19 +++- src/bootstrap/create-runtime-composition.js | 32 ++++++ src/bootstrap/load-release-manifest.js | 107 ++++++++++++++++++ src/bootstrap/main.jsx | 13 ++- src/bootstrap/runtime-adapters.js | 94 +++++++++++++++ src/bootstrap/runtime-config-schema.js | 9 +- tests/e2e/accessibility.spec.js | 3 +- tests/runtime-schema/release-manifest.test.js | 51 +++++++++ tests/runtime-schema/runtime-config.test.js | 14 +++ tests/unit/auth-session-adapter.test.js | 23 ++++ tests/unit/runtime-adapters.test.js | 57 ++++++++++ 15 files changed, 505 insertions(+), 21 deletions(-) create mode 100644 src/bootstrap/create-runtime-composition.js create mode 100644 src/bootstrap/load-release-manifest.js create mode 100644 src/bootstrap/runtime-adapters.js create mode 100644 tests/runtime-schema/release-manifest.test.js create mode 100644 tests/unit/runtime-adapters.test.js diff --git a/public/config.json b/public/config.json index 9cd3dbe1..d589523e 100644 --- a/public/config.json +++ b/public/config.json @@ -4,7 +4,7 @@ "REQUEST_TIMEOUT_MS": 10000, "MAX_RETRY_ATTEMPTS": 2, "TELEMETRY_ENABLED": false, - "AUTH_MODE": "external", + "AUTH_MODE": "demo", "CONFIG_SCHEMA_VERSION": "1", "API_CONTRACT_VERSION": "1", "RELEASE_MANIFEST_URL": "/release-manifest.json", diff --git a/src/adapters/auth/external-session-adapter.js b/src/adapters/auth/external-session-adapter.js index 00b3f997..c9908682 100644 --- a/src/adapters/auth/external-session-adapter.js +++ b/src/adapters/auth/external-session-adapter.js @@ -4,6 +4,9 @@ * * @param {{ * readState(): import("../../application/ports/auth-session-port.js").SessionState, + * subscribe(listener: () => void): () => void, + * beginSignIn(returnTo?: string): Promise, + * signOut(): Promise, * attachCredential(request: Request): Promise, * recoverSession(): Promise<"restored" | "no-session">, * notifyUnauthenticated(): void @@ -15,6 +18,16 @@ export function createExternalAuthSessionAdapter(owner) { getState() { return owner.readState(); }, + subscribe(listener) { + return owner.subscribe(listener); + }, + async beginSignIn(returnTo) { + await owner.beginSignIn(returnTo); + }, + async signOut() { + await owner.signOut(); + }, + /** @param {Request} request */ async attach(request) { const attached = await owner.attachCredential(request); if (!(attached instanceof Request)) { @@ -38,8 +51,74 @@ export function createExternalAuthSessionAdapter(owner) { export function createAnonymousSessionAdapter() { return createExternalAuthSessionAdapter({ readState: () => "unauthenticated", + subscribe: () => () => {}, + beginSignIn: async () => {}, + signOut: async () => {}, attachCredential: async (request) => request, recoverSession: async () => "no-session", notifyUnauthenticated: () => {}, }); } + +/** + * Local/test-only session seam. It never creates or stores credentials. + * + * @param {import("../../application/ports/auth-session-port.js").SessionState} [initialState] + */ +export function createDemoSessionAdapter(initialState = "unauthenticated") { + let state = initialState; + const listeners = new Set(); + + function notify() { + for (const listener of listeners) listener(); + } + + /** @param {import("../../application/ports/auth-session-port.js").SessionState} next */ + function setState(next) { + state = next; + notify(); + } + + return Object.freeze({ + getState: () => state, + /** @param {() => void} listener */ + subscribe(listener) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + async beginSignIn() { + setState("authenticated"); + }, + async signOut() { + setState("unauthenticated"); + }, + /** @param {Request} request */ + async attach(request) { + return request; + }, + async recover() { + if (state === "recovery-pending") { + setState("authenticated"); + return /** @type {const} */ ("restored"); + } + return /** @type {const} */ ("no-session"); + }, + onUnauthenticated() { + setState("unauthenticated"); + }, + setState, + }); +} + +export function createUnavailableSessionAdapter() { + return Object.freeze({ + getState: () => /** @type {const} */ ("integration-failed"), + subscribe: () => () => {}, + beginSignIn: async () => {}, + signOut: async () => {}, + /** @param {Request} request */ + attach: async (request) => request, + recover: async () => /** @type {const} */ ("no-session"), + onUnauthenticated: () => {}, + }); +} diff --git a/src/application/create-application.js b/src/application/create-application.js index 76347314..8d2b6330 100644 --- a/src/application/create-application.js +++ b/src/application/create-application.js @@ -2,7 +2,7 @@ * Application facade factory. Concrete dependencies are supplied by bootstrap. * * @param {{ - * resources: { + * resources?: { * query: import("./ports/resource-ports.js").ResourceQueryPort, * command: import("./ports/resource-ports.js").ResourceCommandPort * }, @@ -17,7 +17,9 @@ export function createApplication(ports) { * @param {import("./ports/resource-ports.js").RequestContext} [context] */ function queryResources(query, context) { - return ports.resources.query.execute(query, context); + return /** @type {NonNullable} */ ( + ports.resources + ).query.execute(query, context); } /** @@ -25,14 +27,18 @@ export function createApplication(ports) { * @param {import("./ports/resource-ports.js").RequestContext} [context] */ function commandResources(command, context) { - return ports.resources.command.execute(command, context); + return /** @type {NonNullable} */ ( + ports.resources + ).command.execute(command, context); } return Object.freeze({ - resources: Object.freeze({ - query: queryResources, - command: commandResources, - }), + resources: ports.resources + ? Object.freeze({ + query: queryResources, + command: commandResources, + }) + : null, cache: ports.cache, storage: ports.storage, telemetry: ports.telemetry, diff --git a/src/application/ports/auth-session-port.js b/src/application/ports/auth-session-port.js index 91734767..645f3490 100644 --- a/src/application/ports/auth-session-port.js +++ b/src/application/ports/auth-session-port.js @@ -7,6 +7,9 @@ * * @typedef {{ * getState(): SessionState, + * subscribe(listener: () => void): () => void, + * beginSignIn(returnTo?: string): Promise, + * signOut(): Promise, * attach(request: Request): Promise, * recover(): Promise<"restored" | "no-session">, * onUnauthenticated(): void diff --git a/src/bootstrap/composition-root.js b/src/bootstrap/composition-root.js index 0bbee542..45e130aa 100644 --- a/src/bootstrap/composition-root.js +++ b/src/bootstrap/composition-root.js @@ -4,14 +4,23 @@ import { createApplication } from "../application/create-application.js"; * This is the only module allowed to join concrete adapters to application * ports. Boot phases are explicit so failures can stop before product mount. * + * @template Config + * @template Release + * @template {Parameters[0]} Ports * @param {{ - * loadConfig(): Promise>, - * loadRelease(config: Record): Promise>, + * loadConfig(): Promise, + * loadRelease(config: Config): Promise, * createAdapters(context: { - * config: Record, - * release: Record - * }): Promise[0]> + * config: Config, + * release: Release + * }): Promise * }} factories + * @returns {Promise + * }>>} */ export async function createCompositionRoot(factories) { const config = await factories.loadConfig(); diff --git a/src/bootstrap/create-runtime-composition.js b/src/bootstrap/create-runtime-composition.js new file mode 100644 index 00000000..b58f3854 --- /dev/null +++ b/src/bootstrap/create-runtime-composition.js @@ -0,0 +1,32 @@ +import { createCompositionRoot } from "./composition-root.js"; +import { loadReleaseManifest } from "./load-release-manifest.js"; +import { loadRuntimeConfig } from "./load-runtime-config.js"; +import { createRuntimeAdapters } from "./runtime-adapters.js"; + +/** + * @param {{ + * fetcher?: typeof fetch, + * host?: Record + * }} [dependencies] + */ +export function createRuntimeComposition(dependencies = {}) { + return createCompositionRoot({ + loadConfig: () => loadRuntimeConfig({ fetcher: dependencies.fetcher }), + loadRelease: (runtime) => + loadReleaseManifest( + /** @type {Awaited>} */ (runtime), + { fetcher: dependencies.fetcher }, + ), + createAdapters: ({ config: runtime, release }) => + createRuntimeAdapters({ + runtime: + /** @type {Awaited>} */ (runtime), + release: + /** @type {Awaited>} */ ( + release + ), + fetcher: dependencies.fetcher, + host: dependencies.host, + }), + }); +} diff --git a/src/bootstrap/load-release-manifest.js b/src/bootstrap/load-release-manifest.js new file mode 100644 index 00000000..aea1dcd9 --- /dev/null +++ b/src/bootstrap/load-release-manifest.js @@ -0,0 +1,107 @@ +import { z } from "zod"; + +const version = z.string().regex(/^\d+(?:\.\d+){0,2}$/); +const releaseManifestSchema = z + .object({ + schemaVersion: z.literal(1), + appVersion: z.string().min(1), + buildId: z.string().min(1), + commitSha: z.string().min(1), + configSchemaVersion: version, + apiContractVersion: version, + assetManifestHash: z.string().min(1), + releaseId: z.string().min(1), + builtAt: z.string().min(1), + }) + .strict(); + +export class ReleaseManifestError extends Error { + /** @param {string} code @param {{buildId: string, releaseId?: string}} safe */ + constructor(code, safe) { + super("Release manifest could not be loaded"); + this.name = "ReleaseManifestError"; + this.kind = "RELEASE_MANIFEST_FAILURE"; + this.code = code; + this.safe = Object.freeze({ + kind: this.kind, + code, + buildId: safe.buildId, + releaseId: safe.releaseId, + supportReference: `${safe.buildId}:${code}`, + }); + } +} + +/** + * @param {Awaited>} runtime + * @param {{fetcher?: typeof fetch}} [options] + */ +export async function loadReleaseManifest(runtime, options = {}) { + const fetcher = options.fetcher ?? fetch; + let response; + try { + response = await fetcher(runtime.config.RELEASE_MANIFEST_URL, { + cache: "no-store", + headers: { Accept: "application/json" }, + }); + } catch { + throw new ReleaseManifestError("MANIFEST_FETCH_FAILED", { + buildId: runtime.build.buildId, + releaseId: runtime.config.RELEASE_ID, + }); + } + if (!response.ok) { + throw new ReleaseManifestError("MANIFEST_HTTP_FAILED", { + buildId: runtime.build.buildId, + releaseId: runtime.config.RELEASE_ID, + }); + } + + let raw; + try { + raw = await response.json(); + } catch { + throw new ReleaseManifestError("MANIFEST_JSON_INVALID", { + buildId: runtime.build.buildId, + releaseId: runtime.config.RELEASE_ID, + }); + } + const parsed = releaseManifestSchema.safeParse(raw); + if (!parsed.success) { + throw new ReleaseManifestError("MANIFEST_SCHEMA_INVALID", { + buildId: runtime.build.buildId, + releaseId: runtime.config.RELEASE_ID, + }); + } + + const manifest = parsed.data; + const mismatches = []; + if (manifest.buildId !== runtime.build.buildId) mismatches.push("buildId"); + if ( + runtime.config.BUILD_ID && + manifest.buildId !== runtime.config.BUILD_ID + ) { + mismatches.push("runtimeBuildId"); + } + if ( + manifest.configSchemaVersion !== runtime.config.CONFIG_SCHEMA_VERSION + ) { + mismatches.push("configSchemaVersion"); + } + if (manifest.apiContractVersion !== runtime.config.API_CONTRACT_VERSION) { + mismatches.push("apiContractVersion"); + } + if ( + runtime.config.RELEASE_ID && + manifest.releaseId !== runtime.config.RELEASE_ID + ) { + mismatches.push("releaseId"); + } + if (mismatches.length > 0) { + throw new ReleaseManifestError("MANIFEST_RUNTIME_MISMATCH", { + buildId: runtime.build.buildId, + releaseId: runtime.config.RELEASE_ID, + }); + } + return Object.freeze(structuredClone(manifest)); +} diff --git a/src/bootstrap/main.jsx b/src/bootstrap/main.jsx index d238eb4b..b8e5e380 100644 --- a/src/bootstrap/main.jsx +++ b/src/bootstrap/main.jsx @@ -1,10 +1,11 @@ import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; -import { createAnonymousSessionAdapter } from "../adapters/auth/external-session-adapter.js"; import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.jsx"; import { AppRouter } from "../presentation/routes/app-router.jsx"; -import { BootConfigError, loadRuntimeConfig } from "./load-runtime-config.js"; +import { createRuntimeComposition } from "./create-runtime-composition.js"; +import { BootConfigError } from "./load-runtime-config.js"; +import { ReleaseManifestError } from "./load-release-manifest.js"; import "../presentation/styles/theme.css"; const rootElement = document.getElementById("root"); @@ -17,18 +18,18 @@ const root = createRoot(rootElement); async function boot() { try { - const runtime = await loadRuntimeConfig(); + const composition = await createRuntimeComposition(); root.render( , ); } catch (error) { const safe = - error instanceof BootConfigError + error instanceof BootConfigError || error instanceof ReleaseManifestError ? error.safe : { supportReference: "boot:unknown" }; diff --git a/src/bootstrap/runtime-adapters.js b/src/bootstrap/runtime-adapters.js new file mode 100644 index 00000000..d5b61623 --- /dev/null +++ b/src/bootstrap/runtime-adapters.js @@ -0,0 +1,94 @@ +import { + createDemoSessionAdapter, + createExternalAuthSessionAdapter, + createUnavailableSessionAdapter, +} from "../adapters/auth/external-session-adapter.js"; +import { createHttpClient } from "../adapters/http/client.js"; +import { + createQueryCacheAdapter, + createQueryClient, +} from "../adapters/query-cache/tanstack-query-cache.js"; +import { createBrowserStorageAdapter } from "../adapters/storage/browser-storage-adapter.js"; +import { createTelemetryAdapter } from "../adapters/telemetry/best-effort-telemetry.js"; + +/** + * @param {Record} host + * @returns {Parameters[0] | null} + */ +function externalOwnerFrom(host) { + const candidate = host.__CA_FRONTEND_AUTH_OWNER__; + if (!candidate || typeof candidate !== "object") return null; + const owner = /** @type {Record} */ (candidate); + const required = [ + "readState", + "subscribe", + "beginSignIn", + "signOut", + "attachCredential", + "recoverSession", + "notifyUnauthenticated", + ]; + return required.every((name) => typeof owner[name] === "function") + ? /** @type {Parameters[0]} */ ( + candidate + ) + : null; +} + +/** @param {unknown} value */ +function storageOrUndefined(value) { + return typeof Storage !== "undefined" && value instanceof Storage + ? value + : undefined; +} + +/** + * @param {{ + * runtime: Awaited>, + * release: Awaited>, + * host?: Record, + * fetcher?: typeof fetch + * }} context + */ +export async function createRuntimeAdapters(context) { + const host = context.host ?? /** @type {Record} */ (globalThis); + const config = context.runtime.config; + const externalOwner = externalOwnerFrom(host); + const authSession = + config.AUTH_MODE === "demo" + ? createDemoSessionAdapter() + : externalOwner + ? createExternalAuthSessionAdapter(externalOwner) + : createUnavailableSessionAdapter(); + const queryClient = createQueryClient(); + const cache = createQueryCacheAdapter(queryClient); + const storage = createBrowserStorageAdapter({ + localStorage: storageOrUndefined(host.localStorage), + sessionStorage: storageOrUndefined(host.sessionStorage), + }); + const telemetry = createTelemetryAdapter({ + enabled: config.TELEMETRY_ENABLED, + endpoint: config.TELEMETRY_ENDPOINT, + fetcher: context.fetcher, + }); + const http = createHttpClient({ + baseUrl: config.API_BASE_URL, + authSession, + fetcher: context.fetcher, + }); + const releaseInfo = Object.freeze({ + async getCurrent() { + return structuredClone(context.release); + }, + }); + + return Object.freeze({ + authSession, + cache, + http, + queryClient, + releaseInfo, + storage, + telemetry, + }); +} diff --git a/src/bootstrap/runtime-config-schema.js b/src/bootstrap/runtime-config-schema.js index 9de4cb7e..c96431c2 100644 --- a/src/bootstrap/runtime-config-schema.js +++ b/src/bootstrap/runtime-config-schema.js @@ -10,7 +10,7 @@ export const runtimeConfigSchema = z MAX_RETRY_ATTEMPTS: z.int().min(0).max(2).default(2), TELEMETRY_ENABLED: z.boolean(), TELEMETRY_ENDPOINT: z.url().optional(), - AUTH_MODE: z.literal("external"), + AUTH_MODE: z.enum(["external", "demo"]), CONFIG_SCHEMA_VERSION: version, API_CONTRACT_VERSION: version, RELEASE_MANIFEST_URL: z.string().min(1).default("/release-manifest.json"), @@ -28,6 +28,13 @@ export const runtimeConfigSchema = z } const local = config.APP_ENV === "local" || config.APP_ENV === "development"; + if (!local && config.AUTH_MODE === "demo") { + context.addIssue({ + code: "custom", + path: ["AUTH_MODE"], + message: "demo authentication is limited to local environments", + }); + } const endpointEntries = /** @type {Array<[string, string | undefined]>} */ ([ ["API_BASE_URL", config.API_BASE_URL], diff --git a/tests/e2e/accessibility.spec.js b/tests/e2e/accessibility.spec.js index 307485c8..ede6e1e8 100644 --- a/tests/e2e/accessibility.spec.js +++ b/tests/e2e/accessibility.spec.js @@ -21,8 +21,9 @@ test("@a11y keyboard reaches the primary route action with visible focus", async page, }) => { await page.goto("/"); - await page.keyboard.press("Tab"); const action = page.getByRole("link", { name: "샘플 리소스" }); + await expect(action).toBeVisible(); + await page.keyboard.press("Tab"); await expect(action).toBeFocused(); await expect(action).toHaveCSS("outline-style", "solid"); }); diff --git a/tests/runtime-schema/release-manifest.test.js b/tests/runtime-schema/release-manifest.test.js new file mode 100644 index 00000000..900cdbd1 --- /dev/null +++ b/tests/runtime-schema/release-manifest.test.js @@ -0,0 +1,51 @@ +import { describe, expect, it } from "vitest"; + +import { + loadReleaseManifest, + ReleaseManifestError, +} from "../../src/bootstrap/load-release-manifest.js"; + +const runtime = { + build: { buildId: "build-a" }, + config: { + RELEASE_MANIFEST_URL: "/release-manifest.json", + BUILD_ID: "build-a", + RELEASE_ID: "release-a", + CONFIG_SCHEMA_VERSION: "1", + API_CONTRACT_VERSION: "1", + }, +}; +const manifest = { + schemaVersion: 1, + appVersion: "0.1.0", + buildId: "build-a", + commitSha: "abc123", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "hash-a", + releaseId: "release-a", + builtAt: "2026-07-25T00:00:00Z", +}; + +describe("release manifest boot boundary", () => { + it("loads a coherent release tuple", async () => { + await expect( + loadReleaseManifest( + /** @type {Parameters[0]} */ (runtime), + { fetcher: async () => new Response(JSON.stringify(manifest)) }, + ), + ).resolves.toMatchObject({ releaseId: "release-a" }); + }); + + it("fails before mount when release and runtime differ", async () => { + await expect( + loadReleaseManifest( + /** @type {Parameters[0]} */ (runtime), + { + fetcher: async () => + new Response(JSON.stringify({ ...manifest, buildId: "build-b" })), + }, + ), + ).rejects.toBeInstanceOf(ReleaseManifestError); + }); +}); diff --git a/tests/runtime-schema/runtime-config.test.js b/tests/runtime-schema/runtime-config.test.js index 114694ee..d94b1054 100644 --- a/tests/runtime-schema/runtime-config.test.js +++ b/tests/runtime-schema/runtime-config.test.js @@ -35,6 +35,20 @@ describe("runtime configuration boundary", () => { ); }); + it("allows demo authentication only for local runtime configuration", () => { + expect( + validateRuntimeConfig({ ...validConfig, AUTH_MODE: "demo" }).success, + ).toBe(true); + expect( + validateRuntimeConfig({ + ...validConfig, + APP_ENV: "production", + API_BASE_URL: "https://api.example.test", + AUTH_MODE: "demo", + }).success, + ).toBe(false); + }); + it("validates a fetched config under the 500ms budget excluding network", async () => { let current = 100; const result = await loadRuntimeConfig({ diff --git a/tests/unit/auth-session-adapter.test.js b/tests/unit/auth-session-adapter.test.js index d1221e96..f138e5e9 100644 --- a/tests/unit/auth-session-adapter.test.js +++ b/tests/unit/auth-session-adapter.test.js @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest"; import { createAnonymousSessionAdapter, + createDemoSessionAdapter, createExternalAuthSessionAdapter, } from "../../src/adapters/auth/external-session-adapter.js"; @@ -9,6 +10,9 @@ describe("external AuthSessionPort adapter", () => { it("attaches opaque credentials without exposing a token-shaped session", async () => { const adapter = createExternalAuthSessionAdapter({ readState: () => "authenticated", + subscribe: () => () => {}, + beginSignIn: async () => {}, + signOut: async () => {}, attachCredential: async (request) => { const headers = new Headers(request.headers); headers.set("X-Session-Attached", "true"); @@ -28,6 +32,9 @@ describe("external AuthSessionPort adapter", () => { it("fails invalid recovery states closed", async () => { const adapter = createExternalAuthSessionAdapter({ readState: () => "authenticated", + subscribe: () => () => {}, + beginSignIn: async () => {}, + signOut: async () => {}, attachCredential: async (request) => request, recoverSession: async () => "unexpected", notifyUnauthenticated: vi.fn(), @@ -41,4 +48,20 @@ describe("external AuthSessionPort adapter", () => { expect(adapter.getState()).toBe("unauthenticated"); await expect(adapter.recover()).resolves.toBe("no-session"); }); + + it("provides a reactive credential-free demo seam", async () => { + const adapter = createDemoSessionAdapter(); + let notifications = 0; + const unsubscribe = adapter.subscribe(() => { + notifications += 1; + }); + + expect(adapter.getState()).toBe("unauthenticated"); + await adapter.beginSignIn("/"); + expect(adapter.getState()).toBe("authenticated"); + await adapter.signOut(); + expect(adapter.getState()).toBe("unauthenticated"); + expect(notifications).toBe(2); + unsubscribe(); + }); }); diff --git a/tests/unit/runtime-adapters.test.js b/tests/unit/runtime-adapters.test.js new file mode 100644 index 00000000..9ba653f0 --- /dev/null +++ b/tests/unit/runtime-adapters.test.js @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; + +import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.js"; + +const runtime = { + config: { + APP_ENV: "local", + API_BASE_URL: "http://localhost:8080", + TELEMETRY_ENABLED: false, + AUTH_MODE: "demo", + }, +}; +const release = { + schemaVersion: 1, + appVersion: "0.1.0", + buildId: "build-a", + commitSha: "abc123", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "hash-a", + releaseId: "release-a", + builtAt: "2026-07-25T00:00:00Z", +}; + +describe("runtime adapter composition", () => { + it("constructs the local demo seam and infrastructure adapters", async () => { + const adapters = await createRuntimeAdapters({ + runtime: + /** @type {Parameters[0]["runtime"]} */ ( + runtime + ), + release, + host: {}, + }); + + expect(adapters.authSession.getState()).toBe("unauthenticated"); + expect(adapters.cache.read(["missing"])).toEqual({ + ok: true, + value: undefined, + }); + await expect(adapters.releaseInfo.getCurrent()).resolves.toMatchObject({ + releaseId: "release-a", + }); + }); + + it("fails closed when an external auth owner was not installed", async () => { + const adapters = await createRuntimeAdapters({ + runtime: + /** @type {Parameters[0]["runtime"]} */ ({ + config: { ...runtime.config, AUTH_MODE: "external" }, + }), + release, + host: {}, + }); + expect(adapters.authSession.getState()).toBe("integration-failed"); + }); +}); From baeda39057a1a11606d02c2fb07db91d564760a7 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 23:52:34 +0900 Subject: [PATCH 041/178] feat: assemble responsive app shell navigation --- src/bootstrap/main.jsx | 13 +- src/contracts/routes.js | 63 +++- src/presentation/components/page-header.jsx | 27 ++ .../examples/auth-example-page.jsx | 80 +++++ .../examples/state-gallery-page.jsx | 24 ++ src/presentation/examples/ui-gallery-page.jsx | 20 ++ src/presentation/layouts/app-shell.jsx | 139 ++++++++ src/presentation/pages/home-page.jsx | 56 +++ src/presentation/pages/not-found-page.jsx | 20 ++ .../pages/sample-contract-page.jsx | 23 ++ .../providers/session-provider.jsx | 50 +++ src/presentation/routes/app-router.jsx | 276 ++++++++++++--- src/presentation/styles/theme.css | 326 +++++++++++++++++- tests/component/router.test.jsx | 60 +++- tests/e2e/accessibility.spec.js | 11 +- tests/e2e/app-shell.spec.js | 47 +++ tests/unit/navigation-policy.test.js | 63 +++- 17 files changed, 1238 insertions(+), 60 deletions(-) create mode 100644 src/presentation/components/page-header.jsx create mode 100644 src/presentation/examples/auth-example-page.jsx create mode 100644 src/presentation/examples/state-gallery-page.jsx create mode 100644 src/presentation/examples/ui-gallery-page.jsx create mode 100644 src/presentation/layouts/app-shell.jsx create mode 100644 src/presentation/pages/home-page.jsx create mode 100644 src/presentation/pages/not-found-page.jsx create mode 100644 src/presentation/pages/sample-contract-page.jsx create mode 100644 src/presentation/providers/session-provider.jsx diff --git a/src/bootstrap/main.jsx b/src/bootstrap/main.jsx index b8e5e380..deb5ddcf 100644 --- a/src/bootstrap/main.jsx +++ b/src/bootstrap/main.jsx @@ -1,5 +1,6 @@ import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; +import { QueryClientProvider } from "@tanstack/react-query"; import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.jsx"; import { AppRouter } from "../presentation/routes/app-router.jsx"; @@ -21,10 +22,14 @@ async function boot() { const composition = await createRuntimeComposition(); root.render( - + + + , ); } catch (error) { diff --git a/src/contracts/routes.js b/src/contracts/routes.js index e4ad7737..32f42767 100644 --- a/src/contracts/routes.js +++ b/src/contracts/routes.js @@ -7,7 +7,10 @@ * access: "public" | "session-required" | "integration-defined", * loadingSurface: string, * errorSurface: string, - * chunkId: string + * chunkId: string, + * title: string, + * navigationLabel: string | null, + * navigationOrder: number | null * }} RouteDefinition */ @@ -24,6 +27,48 @@ export const ROUTE_REGISTRY = Object.freeze({ loadingSurface: "app-shell", errorSurface: "route-boundary", chunkId: "route-home", + title: "시작", + navigationLabel: "시작", + navigationOrder: 10, + }), + EXAMPLES_UI: route({ + routeId: "EXAMPLES_UI", + path: "/examples/ui", + paramsSchema: null, + searchSchema: null, + access: "public", + loadingSurface: "example-page", + errorSurface: "route-boundary", + chunkId: "route-examples-ui", + title: "UI 구성요소", + navigationLabel: "UI 구성요소", + navigationOrder: 20, + }), + EXAMPLES_STATES: route({ + routeId: "EXAMPLES_STATES", + path: "/examples/states", + paramsSchema: null, + searchSchema: null, + access: "public", + loadingSurface: "example-page", + errorSurface: "route-boundary", + chunkId: "route-examples-states", + title: "화면 상태", + navigationLabel: "화면 상태", + navigationOrder: 30, + }), + EXAMPLES_AUTH: route({ + routeId: "EXAMPLES_AUTH", + path: "/examples/auth", + paramsSchema: null, + searchSchema: null, + access: "public", + loadingSurface: "example-page", + errorSurface: "route-boundary", + chunkId: "route-examples-auth", + title: "인증 연동", + navigationLabel: "인증 연동", + navigationOrder: 40, }), SAMPLE_RESOURCE_LIST: route({ routeId: "SAMPLE_RESOURCE_LIST", @@ -34,6 +79,9 @@ export const ROUTE_REGISTRY = Object.freeze({ loadingSurface: "sample-resource-list", errorSurface: "feature-boundary", chunkId: "route-sample-resources", + title: "보호된 연동 지점", + navigationLabel: "보호된 연동 지점", + navigationOrder: 50, }), NOT_FOUND: route({ routeId: "NOT_FOUND", @@ -44,9 +92,22 @@ export const ROUTE_REGISTRY = Object.freeze({ loadingSurface: "none", errorSurface: "not-found", chunkId: "route-not-found", + title: "페이지를 찾을 수 없음", + navigationLabel: null, + navigationOrder: null, }), }); +export const NAVIGATION_ROUTES = Object.freeze( + Object.values(ROUTE_REGISTRY) + .filter((definition) => definition.navigationOrder !== null) + .sort( + (left, right) => + /** @type {number} */ (left.navigationOrder) - + /** @type {number} */ (right.navigationOrder), + ), +); + /** @param {string} routeId */ export function getRoute(routeId) { const registry = /** @type {Record>} */ ( diff --git a/src/presentation/components/page-header.jsx b/src/presentation/components/page-header.jsx new file mode 100644 index 00000000..c930d164 --- /dev/null +++ b/src/presentation/components/page-header.jsx @@ -0,0 +1,27 @@ +import { useEffect, useRef } from "react"; + +/** + * @param {{ + * title: string, + * description?: string, + * eyebrow?: string + * }} props + */ +export function PageHeader({ title, description, eyebrow }) { + const headingRef = useRef(/** @type {HTMLHeadingElement | null} */ (null)); + + useEffect(() => { + document.title = `${title} · Frontend Skeleton`; + headingRef.current?.focus(); + }, [title]); + + return ( +
+ {eyebrow ?

{eyebrow}

: null} +

+ {title} +

+ {description ?

{description}

: null} +
+ ); +} diff --git a/src/presentation/examples/auth-example-page.jsx b/src/presentation/examples/auth-example-page.jsx new file mode 100644 index 00000000..a7eedfdd --- /dev/null +++ b/src/presentation/examples/auth-example-page.jsx @@ -0,0 +1,80 @@ +import { useState } from "react"; +import { useLocation } from "react-router-dom"; + +import { PageHeader } from "../components/page-header.jsx"; +import { useSession } from "../providers/session-provider.jsx"; + +export default function AuthExamplePage() { + const location = useLocation(); + const { sessionState, beginSignIn, signOut, recover } = useSession(); + const [pending, setPending] = useState(false); + const [failed, setFailed] = useState(false); + + /** @param {() => Promise} action */ + async function execute(action) { + setPending(true); + setFailed(false); + try { + await action(); + } catch { + setFailed(true); + } finally { + setPending(false); + } + } + + return ( +
+ +
+
+

현재 세션 상태

+ + {sessionState} + +
+
+ + + +
+ {sessionState === "integration-failed" ? ( +

+ 외부 인증 소유자가 연결되지 않았습니다. 런타임 호스트의 인증 + 계약을 연결하세요. +

+ ) : null} + {failed ?

인증 작업을 완료하지 못했습니다.

: null} +
+
+ ); +} diff --git a/src/presentation/examples/state-gallery-page.jsx b/src/presentation/examples/state-gallery-page.jsx new file mode 100644 index 00000000..560eb28e --- /dev/null +++ b/src/presentation/examples/state-gallery-page.jsx @@ -0,0 +1,24 @@ +import { PageHeader } from "../components/page-header.jsx"; + +export default function StateGalleryPage() { + return ( +
+ +
+
+
+

표시할 항목이 없습니다.

+

다음 행동이 있다면 이 위치에 명확한 안내를 제공합니다.

+
+
+

요청을 완료하지 못했습니다.

+

안전한 재시도 또는 지원 참조 정보를 제공합니다.

+
+
+
+ ); +} diff --git a/src/presentation/examples/ui-gallery-page.jsx b/src/presentation/examples/ui-gallery-page.jsx new file mode 100644 index 00000000..8b6480ba --- /dev/null +++ b/src/presentation/examples/ui-gallery-page.jsx @@ -0,0 +1,20 @@ +import { PageHeader } from "../components/page-header.jsx"; + +export default function UiGalleryPage() { + return ( +
+ +
+ +

+ 버튼, 입력창, 카드, 알림, 모달의 상호작용과 디자인 토큰을 이 + 라우트에 조립합니다. +

+
+
+ ); +} diff --git a/src/presentation/layouts/app-shell.jsx b/src/presentation/layouts/app-shell.jsx new file mode 100644 index 00000000..35f70d68 --- /dev/null +++ b/src/presentation/layouts/app-shell.jsx @@ -0,0 +1,139 @@ +import { useEffect, useState } from "react"; +import { NavLink, Outlet, useLocation } from "react-router-dom"; + +import { NAVIGATION_ROUTES, routePath } from "../../contracts/routes.js"; +import { useSession } from "../providers/session-provider.jsx"; + +const SESSION_LABELS = Object.freeze({ + authenticated: "인증됨", + unauthenticated: "로그인 전", + "recovery-pending": "복구 대기", + "integration-failed": "연동 필요", +}); + +export function AppShell() { + const location = useLocation(); + const { sessionState, beginSignIn, signOut, recover } = useSession(); + const [navigationOpen, setNavigationOpen] = useState(false); + const [sessionActionPending, setSessionActionPending] = useState(false); + const [sessionActionFailed, setSessionActionFailed] = useState(false); + + useEffect(() => { + setNavigationOpen(false); + }, [location.pathname]); + + useEffect(() => { + if (!navigationOpen) return undefined; + /** @param {KeyboardEvent} event */ + const closeOnEscape = (event) => { + if (event.key === "Escape") setNavigationOpen(false); + }; + window.addEventListener("keydown", closeOnEscape); + return () => window.removeEventListener("keydown", closeOnEscape); + }, [navigationOpen]); + + async function runSessionAction() { + setSessionActionPending(true); + setSessionActionFailed(false); + try { + if (sessionState === "authenticated") { + await signOut(); + } else if (sessionState === "recovery-pending") { + await recover(); + } else { + await beginSignIn( + `${location.pathname}${location.search}${location.hash}`, + ); + } + } catch { + setSessionActionFailed(true); + } finally { + setSessionActionPending(false); + } + } + + const sessionActionLabel = + sessionState === "authenticated" + ? "로그아웃" + : sessionState === "recovery-pending" + ? "세션 복구" + : "로그인"; + const integrationAvailable = sessionState !== "integration-failed"; + + return ( +
+ + 본문으로 건너뛰기 + +
+ + + Frontend Skeleton + +
+ + {SESSION_LABELS[sessionState]} + + {integrationAvailable ? ( + + ) : null} +
+ {sessionActionFailed ? ( +

+ 세션 작업을 완료하지 못했습니다. +

+ ) : null} +
+ + {navigationOpen ? ( +
+ ); +} diff --git a/src/presentation/pages/home-page.jsx b/src/presentation/pages/home-page.jsx new file mode 100644 index 00000000..f7c00a85 --- /dev/null +++ b/src/presentation/pages/home-page.jsx @@ -0,0 +1,56 @@ +import { Link } from "react-router-dom"; + +import { routePath } from "../../contracts/routes.js"; +import { PageHeader } from "../components/page-header.jsx"; + +const READINESS_ITEMS = Object.freeze([ + { + title: "실행 계약", + description: "런타임 설정, 릴리스 정합성, 오류 경계가 마운트 전에 검증됩니다.", + }, + { + title: "교체 가능한 연동", + description: "인증, HTTP, 캐시, 저장소, 텔레메트리가 포트 뒤에 분리되어 있습니다.", + }, + { + title: "접근 가능한 화면", + description: "키보드 탐색, 포커스 이동, 반응형 앱 셸의 기본 동작이 준비되어 있습니다.", + }, +]); + +export default function HomePage() { + return ( +
+ +
+ {READINESS_ITEMS.map((item) => ( +
+

{item.title}

+

{item.description}

+
+ ))} +
+
+
+

준비된 화면 살펴보기

+

공통 구성요소와 비동기 화면 상태를 예제 라우트에서 확인하세요.

+
+
+ + UI 구성요소 보기 + + + 화면 상태 보기 + +
+
+
+ ); +} diff --git a/src/presentation/pages/not-found-page.jsx b/src/presentation/pages/not-found-page.jsx new file mode 100644 index 00000000..a1463b70 --- /dev/null +++ b/src/presentation/pages/not-found-page.jsx @@ -0,0 +1,20 @@ +import { Link } from "react-router-dom"; + +import { routePath } from "../../contracts/routes.js"; +import { PageHeader } from "../components/page-header.jsx"; + +export default function NotFoundPage() { + return ( +
+ +
+ + 홈으로 이동 + +
+
+ ); +} diff --git a/src/presentation/pages/sample-contract-page.jsx b/src/presentation/pages/sample-contract-page.jsx new file mode 100644 index 00000000..a8f8aab8 --- /dev/null +++ b/src/presentation/pages/sample-contract-page.jsx @@ -0,0 +1,23 @@ +import { PageHeader } from "../components/page-header.jsx"; +import { useSession } from "../providers/session-provider.jsx"; + +export default function SampleContractPage() { + const { sessionState } = useSession(); + + return ( +
+ +
+

라우트 접근 허용

+

+ 현재 세션 상태는 {sessionState}입니다. 서버의 + 권한 검증은 이 클라이언트 라우트 정책과 별도로 유지해야 합니다. +

+
+
+ ); +} diff --git a/src/presentation/providers/session-provider.jsx b/src/presentation/providers/session-provider.jsx new file mode 100644 index 00000000..770cacad --- /dev/null +++ b/src/presentation/providers/session-provider.jsx @@ -0,0 +1,50 @@ +import { createContext, useContext, useMemo, useSyncExternalStore } from "react"; + +/** + * @typedef {{ + * sessionState: import("../../application/ports/auth-session-port.js").SessionState, + * beginSignIn: import("../../application/ports/auth-session-port.js").AuthSessionPort["beginSignIn"], + * signOut: import("../../application/ports/auth-session-port.js").AuthSessionPort["signOut"], + * recover: import("../../application/ports/auth-session-port.js").AuthSessionPort["recover"] + * }} SessionContextValue + */ + +const SessionContext = createContext( + /** @type {SessionContextValue | null} */ (null), +); + +/** + * @param {{ + * authSession: import("../../application/ports/auth-session-port.js").AuthSessionPort, + * children: React.ReactNode + * }} props + */ +export function SessionProvider({ authSession, children }) { + const sessionState = useSyncExternalStore( + authSession.subscribe, + authSession.getState, + authSession.getState, + ); + const value = useMemo( + () => + Object.freeze({ + sessionState, + beginSignIn: authSession.beginSignIn, + signOut: authSession.signOut, + recover: authSession.recover, + }), + [authSession, sessionState], + ); + + return ( + {children} + ); +} + +export function useSession() { + const session = useContext(SessionContext); + if (!session) { + throw new Error("SessionProvider is required"); + } + return session; +} diff --git a/src/presentation/routes/app-router.jsx b/src/presentation/routes/app-router.jsx index 286b1b26..8cfc004a 100644 --- a/src/presentation/routes/app-router.jsx +++ b/src/presentation/routes/app-router.jsx @@ -1,81 +1,267 @@ +import { lazy, Suspense, useState } from "react"; import { BrowserRouter, - Link, Route, Routes, + useLocation, } from "react-router-dom"; -import { routePath } from "../../contracts/routes.js"; +import { getRoute, routePath } from "../../contracts/routes.js"; +import { RouteBoundary } from "../boundaries/render-error-boundary.jsx"; +import { AppShell } from "../layouts/app-shell.jsx"; +import { PageHeader } from "../components/page-header.jsx"; +import { SessionProvider, useSession } from "../providers/session-provider.jsx"; import { decideRouteAccess } from "./navigation-policy.js"; -function HomePage() { +const HomePage = lazy(() => import("../pages/home-page.jsx")); +const UiGalleryPage = lazy(() => import("../examples/ui-gallery-page.jsx")); +const StateGalleryPage = lazy( + () => import("../examples/state-gallery-page.jsx"), +); +const AuthExamplePage = lazy( + () => import("../examples/auth-example-page.jsx"), +); +const SampleContractPage = lazy( + () => import("../pages/sample-contract-page.jsx"), +); +const NotFoundPage = lazy(() => import("../pages/not-found-page.jsx")); + +/** @param {{ routeId: string }} props */ +function RouteLoadingSurface({ routeId }) { + const definition = getRoute(routeId); return ( -
-

Clean Architecture Frontend

-

런타임 계약이 검증되었습니다.

- 샘플 리소스 -
+
+
); } -function SamplePlaceholder() { +function RouteFailureSurface() { return ( -
-

샘플 리소스

-

계약 fixture를 준비하고 있습니다.

-
- ); -} - -function NotFoundPage() { - return ( -
-

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

- 홈으로 이동 -
+
+ +
); } /** * @param {{ - * authSession: import("../../application/ports/auth-session-port.js").AuthSessionPort + * routeId: string, + * buildId: string, + * telemetry?: import("../../application/ports/telemetry-port.js").TelemetryPort, + * children: React.ReactNode * }} props */ -function GuardedSampleRoute({ authSession }) { - const decision = decideRouteAccess( - "SAMPLE_RESOURCE_LIST", - authSession.getState(), +function RouteSurface({ routeId, buildId, telemetry, children }) { + return ( + } + > + }> + {children} + + ); - if (!decision.allowed) { +} + +/** + * @param {{ + * routeId: string, + * children: React.ReactNode + * }} props + */ +function ProtectedRoute({ routeId, children }) { + const location = useLocation(); + const { sessionState, beginSignIn, recover } = useSession(); + const [pending, setPending] = useState(false); + const [failed, setFailed] = useState(false); + const decision = decideRouteAccess(routeId, sessionState); + + async function continueSession() { + setPending(true); + setFailed(false); + try { + if (decision.action === "wait-for-session") { + await recover(); + } else { + await beginSignIn( + `${location.pathname}${location.search}${location.hash}`, + ); + } + } catch { + setFailed(true); + } finally { + setPending(false); + } + } + + if (decision.allowed) return children; + + if (sessionState === "integration-failed") { return ( -
-

세션이 필요합니다.

- -
+
+ +
); } - return ; + + const recovering = decision.action === "wait-for-session"; + return ( +
+ +
+ +
+ {failed ? ( +

+ 세션 작업을 완료하지 못했습니다. +

+ ) : null} +
+ ); +} + +/** + * @param {{ + * routeId: string, + * buildId: string, + * telemetry?: import("../../application/ports/telemetry-port.js").TelemetryPort, + * children: React.ReactNode + * }} props + */ +function PublicRoute({ routeId, buildId, telemetry, children }) { + return ( + + {children} + + ); } /** * @param {{ * authSession: import("../../application/ports/auth-session-port.js").AuthSessionPort, - * basename?: string + * basename?: string, + * buildId?: string, + * telemetry?: import("../../application/ports/telemetry-port.js").TelemetryPort * }} props */ -export function AppRouter({ authSession, basename = "/" }) { +export function AppRouter({ + authSession, + basename = "/", + buildId = "local-build", + telemetry, +}) { return ( - - } /> - } - /> - } /> - + + + }> + + + + } + /> + + + + } + /> + + + + } + /> + + + + } + /> + + + + + + } + /> + + + + } + /> + + + ); } diff --git a/src/presentation/styles/theme.css b/src/presentation/styles/theme.css index ad74953b..9018bceb 100644 --- a/src/presentation/styles/theme.css +++ b/src/presentation/styles/theme.css @@ -24,6 +24,35 @@ body { margin: 0; + min-width: 20rem; + min-height: 100vh; + } + + button, + input, + textarea, + select { + font: inherit; + } + + a { + color: inherit; + } + + h1, + h2, + p { + margin-block-start: 0; + } + + h1 { + font-size: clamp(2rem, 5vw, 3.5rem); + line-height: 1.05; + letter-spacing: -0.04em; + } + + h2 { + line-height: 1.25; } :focus-visible { @@ -33,8 +62,165 @@ } @layer components { + .visually-hidden { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; + } + + .skip-link { + position: fixed; + z-index: 100; + top: 0.75rem; + left: 0.75rem; + padding: 0.75rem 1rem; + border-radius: var(--radius-control); + color: white; + background: var(--color-content); + transform: translateY(-200%); + } + + .skip-link:focus { + transform: translateY(0); + } + + .app-shell { + display: grid; + min-height: 100vh; + grid-template-rows: 4.5rem 1fr; + grid-template-columns: 15rem minmax(0, 1fr); + grid-template-areas: + "header header" + "sidebar content"; + } + + .app-shell__header { + position: sticky; + z-index: 30; + top: 0; + grid-area: header; + display: flex; + align-items: center; + gap: 1rem; + min-width: 0; + padding: 0.75rem 1.25rem; + border-bottom: 1px solid var(--color-surface-muted); + background: color-mix(in oklch, white 92%, var(--color-surface)); + box-shadow: 0 1px 8px color-mix(in oklch, var(--color-content) 8%, transparent); + } + + .app-shell__brand { + overflow: hidden; + font-size: 1.05rem; + font-weight: 800; + text-decoration: none; + text-overflow: ellipsis; + white-space: nowrap; + } + + .app-shell__menu-button { + display: none; + align-items: center; + gap: 0.4rem; + border: 1px solid var(--color-surface-muted); + border-radius: var(--radius-control); + padding: 0.55rem 0.75rem; + color: var(--color-content); + background: white; + cursor: pointer; + } + + .app-shell__session { + display: flex; + align-items: center; + gap: 0.75rem; + margin-inline-start: auto; + } + + .app-shell__session-error { + position: absolute; + top: calc(100% + 0.25rem); + right: 1rem; + padding: 0.5rem; + color: var(--color-danger); + background: white; + } + + .session-status { + display: inline-flex; + width: fit-content; + align-items: center; + border-radius: 999px; + padding: 0.3rem 0.65rem; + color: var(--color-content-muted); + background: var(--color-surface-muted); + font-size: 0.8rem; + font-weight: 700; + } + + .session-status[data-state="authenticated"] { + color: oklch(0.35 0.12 155); + background: oklch(0.93 0.05 155); + } + + .session-status[data-state="integration-failed"] { + color: var(--color-danger); + } + + .app-shell__sidebar { + position: sticky; + top: 4.5rem; + grid-area: sidebar; + height: calc(100vh - 4.5rem); + padding: 1.25rem 0.75rem; + border-right: 1px solid var(--color-surface-muted); + background: white; + } + + .app-navigation { + display: flex; + flex-direction: column; + gap: 0.25rem; + margin: 0; + padding: 0; + list-style: none; + } + + .app-navigation__link { + display: block; + border-radius: var(--radius-control); + padding: 0.75rem 0.9rem; + color: var(--color-content-muted); + font-weight: 650; + text-decoration: none; + } + + .app-navigation__link:hover { + color: var(--color-content); + background: var(--color-surface); + } + + .app-navigation__link.is-active { + color: var(--color-action-hover); + background: color-mix(in oklch, var(--color-action) 10%, white); + font-weight: 800; + } + + .app-shell__content { + grid-area: content; + min-width: 0; + } + .ui-page { - @apply mx-auto flex min-h-screen max-w-4xl flex-col gap-6 p-page; + @apply mx-auto flex max-w-6xl flex-col gap-6 p-page; + width: 100%; + box-sizing: border-box; } .ui-panel { @@ -43,12 +229,41 @@ .ui-button { @apply rounded-control bg-action px-4 py-2 font-semibold text-white; + display: inline-flex; + min-height: 2.75rem; + align-items: center; + justify-content: center; + border: 0; + text-decoration: none; + cursor: pointer; } .ui-button:hover { @apply bg-action-hover; } + .ui-button:disabled { + cursor: not-allowed; + opacity: 0.55; + } + + .ui-button--secondary { + border: 1px solid var(--color-surface-muted); + color: var(--color-content); + background: white; + } + + .ui-button--secondary:hover { + color: var(--color-action); + background: var(--color-surface); + } + + .ui-button--compact { + min-height: 2.25rem; + padding: 0.4rem 0.75rem; + font-size: 0.85rem; + } + .ui-skeleton { @apply h-24 animate-pulse rounded-surface bg-surface-muted; } @@ -57,6 +272,115 @@ .ui-terminal-error { @apply rounded-surface border border-surface-muted p-6; } + + .page-header { + max-width: 50rem; + padding-block: clamp(1rem, 5vw, 3.5rem) 0.5rem; + } + + .page-header__eyebrow { + margin-block-end: 0.75rem; + color: var(--color-action); + font-size: 0.8rem; + font-weight: 800; + letter-spacing: 0.08em; + text-transform: uppercase; + } + + .page-header__description { + max-width: 45rem; + color: var(--color-content-muted); + font-size: 1.05rem; + line-height: 1.7; + } + + .readiness-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 1rem; + } + + .readiness-grid p, + .starter-actions p { + margin-block-end: 0; + color: var(--color-content-muted); + line-height: 1.65; + } + + .starter-actions, + .auth-example { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 1.5rem; + } + + .button-row { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + } + + .route-loading { + padding-block-start: 4rem; + } + + .app-shell__scrim { + display: none; + } +} + +@media (max-width: 47.999rem) { + .app-shell { + grid-template-columns: minmax(0, 1fr); + grid-template-areas: + "header" + "content"; + } + + .app-shell__header { + padding-inline: 0.75rem; + } + + .app-shell__menu-button { + display: inline-flex; + } + + .app-shell__sidebar { + position: fixed; + z-index: 50; + top: 4.5rem; + bottom: 0; + left: 0; + display: none; + width: min(18rem, 85vw); + height: auto; + box-sizing: border-box; + box-shadow: 10px 0 30px color-mix(in oklch, var(--color-content) 15%, transparent); + } + + .app-shell__sidebar[data-open="true"] { + display: block; + } + + .app-shell__scrim { + position: fixed; + z-index: 40; + inset: 4.5rem 0 0; + display: block; + border: 0; + background: color-mix(in oklch, var(--color-content) 35%, transparent); + cursor: pointer; + } + + .app-shell__session .session-status { + display: none; + } + + .readiness-grid { + grid-template-columns: minmax(0, 1fr); + } } @media (prefers-reduced-motion: reduce) { diff --git a/tests/component/router.test.jsx b/tests/component/router.test.jsx index e253c638..fc7782d8 100644 --- a/tests/component/router.test.jsx +++ b/tests/component/router.test.jsx @@ -1,24 +1,72 @@ // @vitest-environment jsdom import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; import { describe, expect, it } from "vitest"; -import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.js"; +import { + createAnonymousSessionAdapter, + createDemoSessionAdapter, +} from "../../src/adapters/auth/external-session-adapter.js"; import { AppRouter } from "../../src/presentation/routes/app-router.jsx"; describe("application router", () => { - it("renders not-found without making an API request", () => { + it("renders the app shell and not-found route without an API request", async () => { window.history.pushState({}, "", "/missing"); render(); + expect( - screen.getByRole("heading", { name: "페이지를 찾을 수 없습니다." }), + await screen.findByRole("heading", { + name: "페이지를 찾을 수 없습니다.", + }), ).toBeVisible(); + expect(screen.getByRole("navigation", { name: "주요 탐색" })).toBeVisible(); + expect(screen.getByRole("main")).toBeVisible(); }); - it("shows session-required UX without claiming authorization", () => { + it("navigates between registry-backed example routes", async () => { + const user = userEvent.setup(); + window.history.pushState({}, "", "/"); + render(); + + await user.click( + await screen.findByRole("link", { name: "UI 구성요소", exact: true }), + ); + + expect( + await screen.findByRole("heading", { name: "UI 구성요소", level: 1 }), + ).toBeVisible(); + expect(window.location.pathname).toBe("/examples/ui"); + }); + + it("reacts to demo sign-in and opens the protected integration route", async () => { + const user = userEvent.setup(); + const authSession = createDemoSessionAdapter(); + window.history.pushState({}, "", "/sample/resources"); + render(); + + expect( + await screen.findByRole("heading", { name: "세션이 필요합니다." }), + ).toBeVisible(); + await user.click(screen.getByRole("button", { name: "로그인 시작" })); + + expect( + await screen.findByRole("heading", { name: "보호된 연동 지점" }), + ).toBeVisible(); + expect(screen.getByText("인증됨")).toBeVisible(); + }); + + it("fails closed when the auth integration does not change state", async () => { + const user = userEvent.setup(); window.history.pushState({}, "", "/sample/resources"); render(); - expect(screen.getByRole("heading", { name: "세션이 필요합니다." })).toBeVisible(); - expect(screen.getByRole("button", { name: "로그인" })).toBeVisible(); + + await user.click( + await screen.findByRole("button", { name: "로그인 시작" }), + ); + + expect( + screen.getByRole("heading", { name: "세션이 필요합니다." }), + ).toBeVisible(); }); }); diff --git a/tests/e2e/accessibility.spec.js b/tests/e2e/accessibility.spec.js index ede6e1e8..76a4bdba 100644 --- a/tests/e2e/accessibility.spec.js +++ b/tests/e2e/accessibility.spec.js @@ -1,7 +1,14 @@ import AxeBuilder from "@axe-core/playwright"; import { expect, test } from "@playwright/test"; -for (const route of ["/", "/sample/resources", "/not-found"]) { +for (const route of [ + "/", + "/examples/ui", + "/examples/states", + "/examples/auth", + "/sample/resources", + "/not-found", +]) { test(`@a11y ${route} has no critical or serious axe violations`, async ({ page, }) => { @@ -21,7 +28,7 @@ test("@a11y keyboard reaches the primary route action with visible focus", async page, }) => { await page.goto("/"); - const action = page.getByRole("link", { name: "샘플 리소스" }); + const action = page.getByRole("link", { name: "UI 구성요소 보기" }); await expect(action).toBeVisible(); await page.keyboard.press("Tab"); await expect(action).toBeFocused(); diff --git a/tests/e2e/app-shell.spec.js b/tests/e2e/app-shell.spec.js index f262105e..f2bc6be9 100644 --- a/tests/e2e/app-shell.spec.js +++ b/tests/e2e/app-shell.spec.js @@ -5,4 +5,51 @@ test("boots the public app shell", async ({ page }) => { await expect(page.getByRole("heading", { level: 1 })).toHaveText( "Clean Architecture Frontend", ); + await expect(page.getByRole("navigation", { name: "주요 탐색" })).toBeVisible(); + await expect(page.getByRole("main")).toBeVisible(); +}); + +test("navigates to a registry-backed example without a page reload", async ({ + page, +}) => { + await page.goto("/"); + await page + .getByRole("navigation", { name: "주요 탐색" }) + .getByRole("link", { name: "화면 상태" }) + .click(); + + await expect(page).toHaveURL(/\/examples\/states$/); + await expect( + page.getByRole("heading", { level: 1, name: "화면 상태" }), + ).toBeFocused(); +}); + +test("opens the protected integration route through the local demo seam", async ({ + page, +}) => { + await page.goto("/sample/resources"); + await expect( + page.getByRole("heading", { name: "세션이 필요합니다." }), + ).toBeVisible(); + + await page.getByRole("button", { name: "로그인 시작" }).click(); + + await expect( + page.getByRole("heading", { name: "보호된 연동 지점" }), + ).toBeVisible(); + await expect(page.getByText("인증됨")).toBeVisible(); +}); + +test("provides an escape-dismissible mobile navigation", async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto("/"); + const menu = page.getByRole("button", { name: "메뉴", exact: true }); + + await menu.click(); + await expect(menu).toHaveAttribute("aria-expanded", "true"); + await expect(page.getByRole("navigation", { name: "주요 탐색" })).toBeVisible(); + + await page.keyboard.press("Escape"); + await expect(menu).toHaveAttribute("aria-expanded", "false"); + await expect(page.getByRole("navigation", { name: "주요 탐색" })).toBeHidden(); }); diff --git a/tests/unit/navigation-policy.test.js b/tests/unit/navigation-policy.test.js index fa61faea..4ea27a3f 100644 --- a/tests/unit/navigation-policy.test.js +++ b/tests/unit/navigation-policy.test.js @@ -4,7 +4,10 @@ import { createRedirectLoopGuard, decideRouteAccess, } from "../../src/presentation/routes/navigation-policy.js"; -import { ROUTE_REGISTRY } from "../../src/contracts/routes.js"; +import { + NAVIGATION_ROUTES, + ROUTE_REGISTRY, +} from "../../src/contracts/routes.js"; describe("route registry", () => { it("matches the stable registry snapshot", () => { @@ -15,35 +18,93 @@ describe("route registry", () => { "chunkId": "route-home", "errorSurface": "route-boundary", "loadingSurface": "app-shell", + "navigationLabel": "시작", + "navigationOrder": 10, "paramsSchema": null, "path": "/", "routeId": "APP_HOME", "searchSchema": null, + "title": "시작", + }, + "EXAMPLES_AUTH": { + "access": "public", + "chunkId": "route-examples-auth", + "errorSurface": "route-boundary", + "loadingSurface": "example-page", + "navigationLabel": "인증 연동", + "navigationOrder": 40, + "paramsSchema": null, + "path": "/examples/auth", + "routeId": "EXAMPLES_AUTH", + "searchSchema": null, + "title": "인증 연동", + }, + "EXAMPLES_STATES": { + "access": "public", + "chunkId": "route-examples-states", + "errorSurface": "route-boundary", + "loadingSurface": "example-page", + "navigationLabel": "화면 상태", + "navigationOrder": 30, + "paramsSchema": null, + "path": "/examples/states", + "routeId": "EXAMPLES_STATES", + "searchSchema": null, + "title": "화면 상태", + }, + "EXAMPLES_UI": { + "access": "public", + "chunkId": "route-examples-ui", + "errorSurface": "route-boundary", + "loadingSurface": "example-page", + "navigationLabel": "UI 구성요소", + "navigationOrder": 20, + "paramsSchema": null, + "path": "/examples/ui", + "routeId": "EXAMPLES_UI", + "searchSchema": null, + "title": "UI 구성요소", }, "NOT_FOUND": { "access": "public", "chunkId": "route-not-found", "errorSurface": "not-found", "loadingSurface": "none", + "navigationLabel": null, + "navigationOrder": null, "paramsSchema": null, "path": "*", "routeId": "NOT_FOUND", "searchSchema": null, + "title": "페이지를 찾을 수 없음", }, "SAMPLE_RESOURCE_LIST": { "access": "integration-defined", "chunkId": "route-sample-resources", "errorSurface": "feature-boundary", "loadingSurface": "sample-resource-list", + "navigationLabel": "보호된 연동 지점", + "navigationOrder": 50, "paramsSchema": null, "path": "/sample/resources", "routeId": "SAMPLE_RESOURCE_LIST", "searchSchema": "SampleResourceListQuery", + "title": "보호된 연동 지점", }, } `); }); + it("derives visible navigation in explicit order", () => { + expect(NAVIGATION_ROUTES.map(({ routeId }) => routeId)).toEqual([ + "APP_HOME", + "EXAMPLES_UI", + "EXAMPLES_STATES", + "EXAMPLES_AUTH", + "SAMPLE_RESOURCE_LIST", + ]); + }); + it("treats client access as a UX hint, not authorization", () => { expect(decideRouteAccess("APP_HOME", "unauthenticated")).toEqual({ allowed: true, From 3581ead5958ff669e1b05c8a8560ee93a8fa77d3 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sat, 25 Jul 2026 23:59:12 +0900 Subject: [PATCH 042/178] feat: provide reusable UI and state galleries --- src/presentation/components/async-surface.jsx | 46 ++- src/presentation/components/error-copy.js | 21 + .../components/state-surfaces.jsx | 69 ++++ src/presentation/components/ui/alert.jsx | 36 ++ src/presentation/components/ui/badge.jsx | 9 + src/presentation/components/ui/button.jsx | 24 ++ src/presentation/components/ui/card.jsx | 28 ++ src/presentation/components/ui/dialog.jsx | 88 ++++ src/presentation/components/ui/text-field.jsx | 52 +++ .../examples/state-gallery-page.jsx | 98 ++++- src/presentation/examples/ui-gallery-page.jsx | 179 +++++++- src/presentation/styles/theme.css | 384 ++++++++++++++++++ tests/component/async-surface.test.jsx | 10 +- tests/component/render-boundary.test.jsx | 8 +- tests/component/sample-resource-page.test.jsx | 7 +- tests/component/ui-primitives.test.jsx | 108 +++++ tests/e2e/ui-gallery.spec.js | 34 ++ 17 files changed, 1167 insertions(+), 34 deletions(-) create mode 100644 src/presentation/components/error-copy.js create mode 100644 src/presentation/components/state-surfaces.jsx create mode 100644 src/presentation/components/ui/alert.jsx create mode 100644 src/presentation/components/ui/badge.jsx create mode 100644 src/presentation/components/ui/button.jsx create mode 100644 src/presentation/components/ui/card.jsx create mode 100644 src/presentation/components/ui/dialog.jsx create mode 100644 src/presentation/components/ui/text-field.jsx create mode 100644 tests/component/ui-primitives.test.jsx create mode 100644 tests/e2e/ui-gallery.spec.js diff --git a/src/presentation/components/async-surface.jsx b/src/presentation/components/async-surface.jsx index d86223fb..e005d7c6 100644 --- a/src/presentation/components/async-surface.jsx +++ b/src/presentation/components/async-surface.jsx @@ -1,23 +1,40 @@ +import { useId } from "react"; + +import { errorMessage } from "./error-copy.js"; +import { Button } from "./ui/button.jsx"; + /** @param {{ label?: string }} props */ export function LoadingSurface({ label = "불러오는 중" }) { return (
); } -/** @param {{ title?: string, action?: React.ReactNode }} props */ -export function EmptySurface({ title = "표시할 항목이 없습니다.", action }) { +/** + * @param {{ + * title?: string, + * description?: string, + * action?: React.ReactNode + * }} props + */ +export function EmptySurface({ + title = "표시할 항목이 없습니다.", + description, + action, +}) { return ( -
-

{title}

+
+

{title}

+ {description ?

{description}

: null} {action}
); @@ -32,17 +49,24 @@ export function EmptySurface({ title = "표시할 항목이 없습니다.", acti * }} props */ export function TerminalErrorSurface({ userMessageKey, action, onAction }) { + const messageId = useId(); + const actionLabels = Object.freeze({ + retry: "다시 시도", + reauth: "로그인", + navigate: "안전한 화면으로 이동", + "reload-once": "한 번 새로고침", + "contact-support": "지원 정보 확인", + }); return (
-

{userMessageKey}

+

{errorMessage(userMessageKey)}

{action !== "none" && ( - + )}
); diff --git a/src/presentation/components/error-copy.js b/src/presentation/components/error-copy.js new file mode 100644 index 00000000..504e3af0 --- /dev/null +++ b/src/presentation/components/error-copy.js @@ -0,0 +1,21 @@ +const ERROR_MESSAGES = Object.freeze({ + "error.network_unreachable": "네트워크에 연결할 수 없습니다.", + "error.request_timeout": "요청 시간이 초과되었습니다.", + "error.auth_required": "계속하려면 로그인이 필요합니다.", + "error.auth_integration_failure": "로그인 연동을 사용할 수 없습니다.", + "error.forbidden": "이 작업을 수행할 권한이 없습니다.", + "error.not_found": "요청한 항목을 찾을 수 없습니다.", + "error.rate_limited": "요청이 많습니다. 잠시 후 다시 시도해 주세요.", + "error.server_failure": "요청을 완료하지 못했습니다.", + "error.chunk_load_failure": "새 화면 파일을 불러오지 못했습니다.", + "error.render_failure": "화면을 표시하지 못했습니다.", + "error.unknown_failure": "예상하지 못한 문제가 발생했습니다.", +}); + +/** @param {string} messageKey */ +export function errorMessage(messageKey) { + const messages = /** @type {Readonly>} */ ( + ERROR_MESSAGES + ); + return messages[messageKey] ?? "요청을 완료하지 못했습니다."; +} diff --git a/src/presentation/components/state-surfaces.jsx b/src/presentation/components/state-surfaces.jsx new file mode 100644 index 00000000..15267793 --- /dev/null +++ b/src/presentation/components/state-surfaces.jsx @@ -0,0 +1,69 @@ +import { Button } from "./ui/button.jsx"; + +/** + * @param {{ + * eyebrow: string, + * title: string, + * description: string, + * actionLabel?: string, + * onAction?: () => void, + * tone?: "neutral" | "danger" | "warning" + * }} props + */ +function StateSurface({ + eyebrow, + title, + description, + actionLabel, + onAction, + tone = "neutral", +}) { + return ( +
+

{eyebrow}

+

{title}

+

{description}

+ {actionLabel ? : null} +
+ ); +} + +/** @param {{ onSignIn?: () => void }} props */ +export function AuthRequiredSurface({ onSignIn }) { + return ( + + ); +} + +/** @param {{ onNavigate?: () => void }} props */ +export function ForbiddenSurface({ onNavigate }) { + return ( + + ); +} + +/** @param {{ onNavigate?: () => void }} props */ +export function NotFoundSurface({ onNavigate }) { + return ( + + ); +} diff --git a/src/presentation/components/ui/alert.jsx b/src/presentation/components/ui/alert.jsx new file mode 100644 index 00000000..26beed8b --- /dev/null +++ b/src/presentation/components/ui/alert.jsx @@ -0,0 +1,36 @@ +/** + * @param {{ + * title: string, + * children?: React.ReactNode, + * variant?: "info" | "success" | "warning" | "danger", + * onDismiss?: () => void + * }} props + */ +export function Alert({ + title, + children, + variant = "info", + onDismiss, +}) { + return ( +
+
+ {title} + {children ?
{children}
: null} +
+ {onDismiss ? ( + + ) : null} +
+ ); +} diff --git a/src/presentation/components/ui/badge.jsx b/src/presentation/components/ui/badge.jsx new file mode 100644 index 00000000..a4ae2ff7 --- /dev/null +++ b/src/presentation/components/ui/badge.jsx @@ -0,0 +1,9 @@ +/** + * @param {{ + * children: React.ReactNode, + * variant?: "neutral" | "info" | "success" | "warning" | "danger" + * }} props + */ +export function Badge({ children, variant = "neutral" }) { + return {children}; +} diff --git a/src/presentation/components/ui/button.jsx b/src/presentation/components/ui/button.jsx new file mode 100644 index 00000000..7c7e3121 --- /dev/null +++ b/src/presentation/components/ui/button.jsx @@ -0,0 +1,24 @@ +/** + * @param {React.ButtonHTMLAttributes & { + * variant?: "primary" | "secondary" | "danger" | "ghost", + * size?: "default" | "compact" + * }} props + */ +export function Button({ + variant = "primary", + size = "default", + className = "", + type = "button", + ...props +}) { + const classes = [ + "ui-button", + `ui-button--${variant}`, + size === "compact" ? "ui-button--compact" : "", + className, + ] + .filter(Boolean) + .join(" "); + + return + + {children ?
{children}
: null} + {actions ?
{actions}
: null} +
+ + ); +} diff --git a/src/presentation/components/ui/text-field.jsx b/src/presentation/components/ui/text-field.jsx new file mode 100644 index 00000000..4ffb5b66 --- /dev/null +++ b/src/presentation/components/ui/text-field.jsx @@ -0,0 +1,52 @@ +import { useId } from "react"; + +/** + * @param {Omit, "id"> & { + * id?: string, + * label: string, + * description?: string, + * error?: string + * }} props + */ +export function TextField({ + id, + label, + description, + error, + className = "", + required, + ...inputProps +}) { + const generatedId = useId(); + const inputId = id ?? `field-${generatedId}`; + const descriptionId = description ? `${inputId}-description` : undefined; + const errorId = error ? `${inputId}-error` : undefined; + const describedBy = [descriptionId, errorId].filter(Boolean).join(" "); + + return ( +
+ + {description ? ( +

+ {description} +

+ ) : null} + + {error ? ( +

+ {error} +

+ ) : null} +
+ ); +} diff --git a/src/presentation/examples/state-gallery-page.jsx b/src/presentation/examples/state-gallery-page.jsx index 560eb28e..ab7fd4d3 100644 --- a/src/presentation/examples/state-gallery-page.jsx +++ b/src/presentation/examples/state-gallery-page.jsx @@ -1,24 +1,98 @@ +import { useState } from "react"; + +import { deriveAsyncState } from "../../application/view-models/async-state.js"; +import { createFailure } from "../../contracts/errors.js"; +import { + AsyncSurface, + EmptySurface, + LoadingSurface, + TerminalErrorSurface, +} from "../components/async-surface.jsx"; import { PageHeader } from "../components/page-header.jsx"; +import { + AuthRequiredSurface, + ForbiddenSurface, + NotFoundSurface, +} from "../components/state-surfaces.jsx"; +import { Button } from "../components/ui/button.jsx"; +import { Card } from "../components/ui/card.jsx"; export default function StateGalleryPage() { + const [lastAction, setLastAction] = useState( + "상태 화면의 작업을 선택하면 결과가 여기에 표시됩니다.", + ); + const refreshingState = deriveAsyncState({ + data: ["기존 데이터"], + isFetching: true, + }); + return (
-
-
-
-

표시할 항목이 없습니다.

-

다음 행동이 있다면 이 위치에 명확한 안내를 제공합니다.

-
-
-

요청을 완료하지 못했습니다.

-

안전한 재시도 또는 지원 참조 정보를 제공합니다.

-
-
+ +
+
+

비동기 데이터 상태

+

초기 로딩과 백그라운드 갱신을 구분해 기존 콘텐츠를 보존합니다.

+
+
+ + + + + +
기존 콘텐츠는 계속 표시됩니다.
+
+
+ + setLastAction("빈 화면 작업을 실행했습니다.")}> + 첫 작업 시작 + + } + /> + + + setLastAction("오류 요청을 다시 시도했습니다.")} + /> + +
+
+ +
+
+

접근과 탐색 상태

+

인증 여부와 서버 권한 결과를 서로 다른 상태로 전달합니다.

+
+
+ setLastAction("로그인 연동 작업을 시작했습니다.")} + /> + setLastAction("접근 가능한 화면으로 이동합니다.")} + /> + setLastAction("시작 화면으로 이동합니다.")} + /> +
+
+ + + {lastAction} +
); } diff --git a/src/presentation/examples/ui-gallery-page.jsx b/src/presentation/examples/ui-gallery-page.jsx index 8b6480ba..b28c3b7e 100644 --- a/src/presentation/examples/ui-gallery-page.jsx +++ b/src/presentation/examples/ui-gallery-page.jsx @@ -1,20 +1,185 @@ +import { useState } from "react"; + import { PageHeader } from "../components/page-header.jsx"; +import { Alert } from "../components/ui/alert.jsx"; +import { Badge } from "../components/ui/badge.jsx"; +import { Button } from "../components/ui/button.jsx"; +import { Card } from "../components/ui/card.jsx"; +import { Dialog } from "../components/ui/dialog.jsx"; +import { TextField } from "../components/ui/text-field.jsx"; + +const COLOR_TOKENS = Object.freeze([ + ["Surface", "--color-surface"], + ["Muted surface", "--color-surface-muted"], + ["Content", "--color-content"], + ["Muted content", "--color-content-muted"], + ["Action", "--color-action"], + ["Danger", "--color-danger"], + ["Focus", "--color-focus"], +]); export default function UiGalleryPage() { + const [projectName, setProjectName] = useState(""); + const [fieldTouched, setFieldTouched] = useState(false); + const [dialogOpen, setDialogOpen] = useState(false); + const [notice, setNotice] = useState( + "구성요소를 조작하면 결과가 여기에 표시됩니다.", + ); + const [alertVisible, setAlertVisible] = useState(true); + const fieldError = + fieldTouched && projectName.trim().length === 0 + ? "프로젝트 이름을 입력해 주세요." + : undefined; + + /** @param {React.FormEvent} event */ + function submitExample(event) { + event.preventDefault(); + setFieldTouched(true); + if (projectName.trim().length === 0) { + setNotice("입력값을 확인해 주세요."); + return; + } + setNotice(`“${projectName.trim()}” 입력을 확인했습니다.`); + } + return (
-
- -

- 버튼, 입력창, 카드, 알림, 모달의 상호작용과 디자인 토큰을 이 - 라우트에 조립합니다. -

+ +
+
+

버튼과 입력

+

키보드, 비활성 상태, 오류 설명을 포함한 기본 상호작용입니다.

+
+
+ +
+ + + + +
+
+ +
+ setProjectName(event.currentTarget.value)} + /> + + +
+
+ +
+
+

피드백과 모달

+

상태 전달은 색에만 의존하지 않으며, 모든 제어에는 이름이 있습니다.

+
+
+ +
+ {alertVisible ? ( + setAlertVisible(false)} + > +

운영 환경에는 실제 저장 포트를 연결하세요.

+
+ ) : ( + + )} +
+ 중립 + 정보 + 준비됨 + 확인 필요 + 실패 +
+
+
+ + + setDialogOpen(false)} + title="연동 확인" + description="도메인 작업을 실행하기 전 확인 화면의 기본 구조입니다." + actions={ + <> + + + + } + > +

민감한 값이나 구현 세부정보는 확인 문구에 포함하지 않습니다.

+
+
+
+
+ +
+
+

디자인 토큰

+

구성요소가 사용하는 의미 기반 색상과 형태 토큰입니다.

+
+
+ {COLOR_TOKENS.map(([label, token]) => ( +
+
+ ))} +
+
+ + + {notice} +
); } diff --git a/src/presentation/styles/theme.css b/src/presentation/styles/theme.css index 9018bceb..8b9eebff 100644 --- a/src/presentation/styles/theme.css +++ b/src/presentation/styles/theme.css @@ -258,6 +258,25 @@ background: var(--color-surface); } + .ui-button--danger { + color: white; + background: var(--color-danger); + } + + .ui-button--danger:hover { + background: oklch(0.47 0.2 25); + } + + .ui-button--ghost { + color: var(--color-content); + background: transparent; + } + + .ui-button--ghost:hover { + color: var(--color-action); + background: var(--color-surface-muted); + } + .ui-button--compact { min-height: 2.25rem; padding: 0.4rem 0.75rem; @@ -273,6 +292,217 @@ @apply rounded-surface border border-surface-muted p-6; } + .ui-field { + display: grid; + gap: 0.45rem; + } + + .ui-field__label { + font-weight: 750; + } + + .ui-field__description, + .ui-field__error { + margin: 0; + font-size: 0.875rem; + line-height: 1.5; + } + + .ui-field__description { + color: var(--color-content-muted); + } + + .ui-field__error { + color: var(--color-danger); + font-weight: 650; + } + + .ui-field__input { + width: 100%; + min-height: 2.75rem; + box-sizing: border-box; + border: 1px solid color-mix(in oklch, var(--color-content-muted) 55%, white); + border-radius: var(--radius-control); + padding: 0.65rem 0.8rem; + color: var(--color-content); + background: white; + } + + .ui-field__input[aria-invalid="true"] { + border-color: var(--color-danger); + } + + .ui-card { + display: flex; + min-width: 0; + flex-direction: column; + gap: 1.25rem; + border: 1px solid var(--color-surface-muted); + border-radius: var(--radius-surface); + padding: 1.25rem; + background: white; + box-shadow: 0 8px 28px color-mix(in oklch, var(--color-content) 6%, transparent); + } + + .ui-card__header h3, + .ui-card__header p { + margin-block-end: 0; + } + + .ui-card__header p { + margin-block-start: 0.4rem; + color: var(--color-content-muted); + line-height: 1.55; + } + + .ui-card__content { + flex: 1; + } + + .ui-card__footer { + padding-block-start: 1rem; + border-top: 1px solid var(--color-surface-muted); + } + + .ui-alert { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + border: 1px solid var(--color-surface-muted); + border-radius: var(--radius-control); + padding: 1rem; + background: var(--color-surface); + } + + .ui-alert--info { + border-color: oklch(0.75 0.08 250); + background: oklch(0.96 0.025 250); + } + + .ui-alert--success { + border-color: oklch(0.72 0.1 155); + background: oklch(0.96 0.03 155); + } + + .ui-alert--warning { + border-color: oklch(0.75 0.12 80); + background: oklch(0.97 0.035 80); + } + + .ui-alert--danger { + border-color: oklch(0.72 0.12 25); + background: oklch(0.96 0.03 25); + } + + .ui-alert__content, + .ui-alert__content p { + margin-block: 0.35rem 0; + color: var(--color-content-muted); + } + + .ui-alert__dismiss, + .ui-dialog__close { + display: inline-grid; + width: 2rem; + height: 2rem; + flex: 0 0 auto; + place-items: center; + border: 0; + border-radius: var(--radius-control); + color: var(--color-content); + background: transparent; + font-size: 1.35rem; + cursor: pointer; + } + + .ui-alert__dismiss:hover, + .ui-dialog__close:hover { + background: color-mix(in oklch, var(--color-content) 8%, transparent); + } + + .ui-badge { + display: inline-flex; + border-radius: 999px; + padding: 0.3rem 0.65rem; + color: var(--color-content); + background: var(--color-surface-muted); + font-size: 0.8rem; + font-weight: 750; + } + + .ui-badge--info { + color: oklch(0.38 0.16 255); + background: oklch(0.93 0.04 255); + } + + .ui-badge--success { + color: oklch(0.35 0.12 155); + background: oklch(0.93 0.05 155); + } + + .ui-badge--warning { + color: oklch(0.38 0.12 70); + background: oklch(0.94 0.06 80); + } + + .ui-badge--danger { + color: oklch(0.42 0.18 25); + background: oklch(0.94 0.045 25); + } + + .ui-dialog { + width: min(34rem, calc(100vw - 2rem)); + max-height: calc(100vh - 2rem); + box-sizing: border-box; + overflow: auto; + border: 0; + border-radius: var(--radius-surface); + padding: 0; + color: var(--color-content); + background: white; + box-shadow: 0 24px 70px color-mix(in oklch, var(--color-content) 25%, transparent); + } + + .ui-dialog::backdrop { + background: color-mix(in oklch, var(--color-content) 55%, transparent); + backdrop-filter: blur(2px); + } + + .ui-dialog__surface { + padding: 1.5rem; + } + + .ui-dialog__header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + } + + .ui-dialog__header h2 { + margin-block-end: 0.35rem; + } + + .ui-dialog__header p, + .ui-dialog__content p { + color: var(--color-content-muted); + line-height: 1.6; + } + + .ui-dialog__content { + padding-block: 1rem; + } + + .ui-dialog__actions { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 0.75rem; + padding-block-start: 1rem; + border-top: 1px solid var(--color-surface-muted); + } + .page-header { max-width: 50rem; padding-block: clamp(1rem, 5vw, 3.5rem) 0.5rem; @@ -326,6 +556,155 @@ padding-block-start: 4rem; } + .gallery-section { + display: grid; + gap: 1rem; + padding-block: 0.5rem; + } + + .gallery-section__header { + max-width: 45rem; + } + + .gallery-section__header h2, + .gallery-section__header p { + margin-block-end: 0; + } + + .gallery-section__header p { + margin-block-start: 0.4rem; + color: var(--color-content-muted); + line-height: 1.6; + } + + .component-grid { + display: grid; + gap: 1rem; + } + + .component-grid--two { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .component-grid--three { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + + .component-stack, + .example-form { + display: grid; + gap: 1rem; + } + + .badge-row { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + } + + .token-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr)); + gap: 0.75rem; + } + + .token-swatch { + display: grid; + gap: 0.45rem; + min-width: 0; + border: 1px solid var(--color-surface-muted); + border-radius: var(--radius-control); + padding: 0.75rem; + background: white; + } + + .token-swatch__color { + height: 4rem; + border: 1px solid color-mix(in oklch, var(--color-content) 15%, transparent); + border-radius: calc(var(--radius-control) / 1.5); + } + + .token-swatch code { + overflow: hidden; + color: var(--color-content-muted); + font-size: 0.75rem; + text-overflow: ellipsis; + white-space: nowrap; + } + + .gallery-notice { + position: sticky; + z-index: 10; + bottom: 1rem; + display: block; + width: fit-content; + max-width: 100%; + box-sizing: border-box; + border: 1px solid var(--color-surface-muted); + border-radius: 999px; + padding: 0.65rem 1rem; + color: var(--color-content); + background: white; + box-shadow: 0 8px 28px color-mix(in oklch, var(--color-content) 10%, transparent); + font-size: 0.875rem; + font-weight: 650; + } + + .state-surface { + display: flex; + min-height: 12rem; + box-sizing: border-box; + flex-direction: column; + align-items: flex-start; + justify-content: center; + border: 1px solid var(--color-surface-muted); + border-radius: var(--radius-surface); + padding: 1.25rem; + background: var(--color-surface); + } + + .state-surface h2, + .state-surface p { + margin-block-end: 0.75rem; + } + + .state-surface > p:not(.state-surface__eyebrow) { + color: var(--color-content-muted); + line-height: 1.55; + } + + .state-surface__eyebrow { + color: var(--color-action-hover); + font-size: 0.75rem; + font-weight: 800; + letter-spacing: 0.04em; + } + + .state-surface--warning { + border-color: oklch(0.75 0.12 80); + background: oklch(0.97 0.035 80); + } + + .state-surface--danger, + .ui-terminal-error { + border-color: oklch(0.72 0.12 25); + background: oklch(0.98 0.02 25); + } + + .state-surface--loading { + gap: 0.75rem; + } + + .state-surface--loading .ui-skeleton { + width: 100%; + } + + .state-preview-content { + border-radius: var(--radius-control); + padding: 1rem; + background: var(--color-surface); + } + .app-shell__scrim { display: none; } @@ -381,6 +760,11 @@ .readiness-grid { grid-template-columns: minmax(0, 1fr); } + + .component-grid--two, + .component-grid--three { + grid-template-columns: minmax(0, 1fr); + } } @media (prefers-reduced-motion: reduce) { diff --git a/tests/component/async-surface.test.jsx b/tests/component/async-surface.test.jsx index 6537b325..e106465c 100644 --- a/tests/component/async-surface.test.jsx +++ b/tests/component/async-surface.test.jsx @@ -59,8 +59,14 @@ describe("async UI state matrix", () => { const state = deriveAsyncState({ failure }); render(); - expect(screen.getByRole("alert")).toHaveTextContent(failure.userMessageKey); - expect(screen.getByRole("button")).toHaveTextContent("retry"); + expect(screen.getByRole("alert")).toHaveTextContent( + "요청을 완료하지 못했습니다.", + ); + expect(screen.getByRole("alert")).toHaveAttribute( + "data-message-key", + failure.userMessageKey, + ); + expect(screen.getByRole("button")).toHaveTextContent("다시 시도"); expect(screen.getByRole("alert")).not.toHaveTextContent("stack"); }); diff --git a/tests/component/render-boundary.test.jsx b/tests/component/render-boundary.test.jsx index d61a43ec..65696dce 100644 --- a/tests/component/render-boundary.test.jsx +++ b/tests/component/render-boundary.test.jsx @@ -44,7 +44,13 @@ describe("render recovery boundaries", () => { , ); - expect(screen.getByRole("alert")).toHaveTextContent("error.server_failure"); + expect(screen.getByRole("alert")).toHaveTextContent( + "요청을 완료하지 못했습니다.", + ); + expect(screen.getByRole("alert")).toHaveAttribute( + "data-message-key", + "error.server_failure", + ); }); it("renders a safe boot shell with no endpoint or stack", () => { diff --git a/tests/component/sample-resource-page.test.jsx b/tests/component/sample-resource-page.test.jsx index 34d83bb2..9910cac7 100644 --- a/tests/component/sample-resource-page.test.jsx +++ b/tests/component/sample-resource-page.test.jsx @@ -44,6 +44,11 @@ describe("removable sample feature page", () => { }; render(); - expect(await screen.findByRole("alert")).toHaveTextContent("error.server_failure"); + const alert = await screen.findByRole("alert"); + expect(alert).toHaveTextContent("요청을 완료하지 못했습니다."); + expect(alert).toHaveAttribute( + "data-message-key", + "error.server_failure", + ); }); }); diff --git a/tests/component/ui-primitives.test.jsx b/tests/component/ui-primitives.test.jsx new file mode 100644 index 00000000..0eef99ea --- /dev/null +++ b/tests/component/ui-primitives.test.jsx @@ -0,0 +1,108 @@ +// @vitest-environment jsdom + +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { useState } from "react"; +import { describe, expect, it, vi } from "vitest"; + +import { Alert } from "../../src/presentation/components/ui/alert.jsx"; +import { Badge } from "../../src/presentation/components/ui/badge.jsx"; +import { Button } from "../../src/presentation/components/ui/button.jsx"; +import { Card } from "../../src/presentation/components/ui/card.jsx"; +import { Dialog } from "../../src/presentation/components/ui/dialog.jsx"; +import { TextField } from "../../src/presentation/components/ui/text-field.jsx"; + +describe("domain-neutral UI primitives", () => { + it("connects field help and validation errors to the input", () => { + render( + , + ); + + const field = screen.getByRole("textbox", { name: "이름" }); + expect(field).toBeRequired(); + expect(field).toHaveAccessibleDescription( + "표시할 이름입니다. 이름을 입력해 주세요.", + ); + expect(field).toHaveAttribute("aria-invalid", "true"); + }); + + it("exposes semantic variants without changing native button behavior", async () => { + const user = userEvent.setup(); + const onClick = vi.fn(); + render( + <> + + + , + ); + + await user.click(screen.getByRole("button", { name: "제거" })); + expect(onClick).toHaveBeenCalledOnce(); + expect(screen.getByRole("button", { name: "제거" })).toHaveClass( + "ui-button--danger", + ); + expect(screen.getByRole("button", { name: "사용 불가" })).toBeDisabled(); + }); + + it("labels cards, alerts, and badges with visible content", async () => { + const user = userEvent.setup(); + const dismiss = vi.fn(); + render( + 준비됨}> + + 안전하게 반영했습니다. + + , + ); + + expect(screen.getByRole("article", { name: "상태 카드" })).toBeVisible(); + expect(screen.getByRole("status")).toHaveTextContent( + "저장됨안전하게 반영했습니다.", + ); + expect(screen.getByText("준비됨")).toHaveClass("ui-badge--success"); + await user.click(screen.getByRole("button", { name: "저장됨 알림 닫기" })); + expect(dismiss).toHaveBeenCalledOnce(); + }); + + it("closes a modal and restores focus to its trigger", async () => { + const user = userEvent.setup(); + + function DialogHarness() { + const [open, setOpen] = useState(false); + return ( + <> + + setOpen(false)} + title="연동 확인" + actions={} + > + 안전한 설명 + + + ); + } + + render(); + const trigger = screen.getByRole("button", { name: "모달 열기" }); + await user.click(trigger); + + expect(screen.getByRole("dialog", { name: "연동 확인" })).toHaveAttribute( + "open", + ); + await user.click(screen.getByRole("button", { name: "확인" })); + + await waitFor(() => expect(trigger).toHaveFocus()); + expect(screen.getByRole("dialog", { hidden: true })).not.toHaveAttribute( + "open", + ); + }); +}); diff --git a/tests/e2e/ui-gallery.spec.js b/tests/e2e/ui-gallery.spec.js new file mode 100644 index 00000000..569aafff --- /dev/null +++ b/tests/e2e/ui-gallery.spec.js @@ -0,0 +1,34 @@ +import { expect, test } from "@playwright/test"; + +test("validates and reports the common text-field flow", async ({ page }) => { + await page.goto("/examples/ui"); + await page.getByRole("button", { name: "입력 확인" }).click(); + + const field = page.getByRole("textbox", { name: "프로젝트 이름" }); + await expect(field).toHaveAttribute("aria-invalid", "true"); + await expect(field).toHaveAccessibleDescription( + /프로젝트 이름을 입력해 주세요/, + ); + + await field.fill("Starter"); + await page.getByRole("button", { name: "입력 확인" }).click(); + await expect(page.getByText("“Starter” 입력을 확인했습니다.")).toBeVisible(); +}); + +test("traps modal interaction and restores focus to the trigger", async ({ + page, +}) => { + await page.goto("/examples/ui"); + const trigger = page.getByRole("button", { name: "모달 열기" }); + await trigger.click(); + + const dialog = page.getByRole("dialog", { name: "연동 확인" }); + await expect(dialog).toBeVisible(); + await expect( + dialog.getByRole("button", { name: "연동 확인 닫기" }), + ).toBeFocused(); + + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + await expect(trigger).toBeFocused(); +}); From 4cfbe5a29e31d7fbfebefbee66515d014e0f49fa Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sun, 26 Jul 2026 00:06:49 +0900 Subject: [PATCH 043/178] feat: add persistent responsive color themes --- src/application/policies/color-scheme.js | 21 +++ src/bootstrap/initialize-color-scheme.js | 36 ++++ src/bootstrap/main.jsx | 3 + src/presentation/layouts/app-shell.jsx | 21 +++ src/presentation/providers/theme-provider.jsx | 86 ++++++++++ src/presentation/routes/app-router.jsx | 17 +- src/presentation/styles/theme.css | 157 +++++++++++++----- tests/e2e/theme.spec.js | 38 +++++ tests/unit/color-scheme.test.js | 44 +++++ 9 files changed, 372 insertions(+), 51 deletions(-) create mode 100644 src/application/policies/color-scheme.js create mode 100644 src/bootstrap/initialize-color-scheme.js create mode 100644 src/presentation/providers/theme-provider.jsx create mode 100644 tests/e2e/theme.spec.js create mode 100644 tests/unit/color-scheme.test.js diff --git a/src/application/policies/color-scheme.js b/src/application/policies/color-scheme.js new file mode 100644 index 00000000..97e15d6a --- /dev/null +++ b/src/application/policies/color-scheme.js @@ -0,0 +1,21 @@ +export const COLOR_SCHEME_PREFERENCES = Object.freeze([ + "system", + "light", + "dark", +]); + +/** @param {unknown} value */ +export function normalizeColorSchemePreference(value) { + return COLOR_SCHEME_PREFERENCES.includes(/** @type {string} */ (value)) + ? /** @type {"system" | "light" | "dark"} */ (value) + : "system"; +} + +/** + * @param {"system" | "light" | "dark"} preference + * @param {boolean} systemPrefersDark + */ +export function resolveColorScheme(preference, systemPrefersDark) { + if (preference === "system") return systemPrefersDark ? "dark" : "light"; + return preference; +} diff --git a/src/bootstrap/initialize-color-scheme.js b/src/bootstrap/initialize-color-scheme.js new file mode 100644 index 00000000..3492cd62 --- /dev/null +++ b/src/bootstrap/initialize-color-scheme.js @@ -0,0 +1,36 @@ +import { + normalizeColorSchemePreference, + resolveColorScheme, +} from "../application/policies/color-scheme.js"; + +/** + * Applies the persisted public preference before React paints. + * + * @param {import("../application/ports/storage-port.js").StoragePort} storage + * @param {{ + * documentElement?: HTMLElement, + * matchMedia?: (query: string) => MediaQueryList + * }} [browser] + */ +export function initializeColorScheme(storage, browser = {}) { + const documentElement = browser.documentElement ?? document.documentElement; + const matchMedia = + browser.matchMedia ?? + (typeof window.matchMedia === "function" + ? window.matchMedia.bind(window) + : () => /** @type {MediaQueryList} */ ({ matches: false })); + const stored = storage.read("COLOR_SCHEME"); + const preference = normalizeColorSchemePreference( + stored.ok ? stored.value : undefined, + ); + const resolved = resolveColorScheme( + preference, + matchMedia("(prefers-color-scheme: dark)").matches, + ); + + documentElement.dataset.theme = resolved; + documentElement.dataset.themePreference = preference; + documentElement.style.colorScheme = resolved; + + return Object.freeze({ preference, resolved }); +} diff --git a/src/bootstrap/main.jsx b/src/bootstrap/main.jsx index deb5ddcf..c6ee9bb5 100644 --- a/src/bootstrap/main.jsx +++ b/src/bootstrap/main.jsx @@ -5,6 +5,7 @@ import { QueryClientProvider } from "@tanstack/react-query"; import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.jsx"; import { AppRouter } from "../presentation/routes/app-router.jsx"; import { createRuntimeComposition } from "./create-runtime-composition.js"; +import { initializeColorScheme } from "./initialize-color-scheme.js"; import { BootConfigError } from "./load-runtime-config.js"; import { ReleaseManifestError } from "./load-release-manifest.js"; import "../presentation/styles/theme.css"; @@ -20,6 +21,7 @@ const root = createRoot(rootElement); async function boot() { try { const composition = await createRuntimeComposition(); + initializeColorScheme(composition.ports.storage); root.render( @@ -27,6 +29,7 @@ async function boot() { authSession={composition.ports.authSession} basename={composition.config.build.routerBasePath} buildId={composition.release.buildId} + storage={composition.ports.storage} telemetry={composition.ports.telemetry} /> diff --git a/src/presentation/layouts/app-shell.jsx b/src/presentation/layouts/app-shell.jsx index 35f70d68..6147dd72 100644 --- a/src/presentation/layouts/app-shell.jsx +++ b/src/presentation/layouts/app-shell.jsx @@ -3,6 +3,7 @@ import { NavLink, Outlet, useLocation } from "react-router-dom"; import { NAVIGATION_ROUTES, routePath } from "../../contracts/routes.js"; import { useSession } from "../providers/session-provider.jsx"; +import { useTheme } from "../providers/theme-provider.jsx"; const SESSION_LABELS = Object.freeze({ authenticated: "인증됨", @@ -14,6 +15,7 @@ const SESSION_LABELS = Object.freeze({ export function AppShell() { const location = useLocation(); const { sessionState, beginSignIn, signOut, recover } = useSession(); + const { preference, setPreference } = useTheme(); const [navigationOpen, setNavigationOpen] = useState(false); const [sessionActionPending, setSessionActionPending] = useState(false); const [sessionActionFailed, setSessionActionFailed] = useState(false); @@ -80,6 +82,25 @@ export function AppShell() { Frontend Skeleton
+ + {SESSION_LABELS[sessionState]} diff --git a/src/presentation/providers/theme-provider.jsx b/src/presentation/providers/theme-provider.jsx new file mode 100644 index 00000000..eb181f74 --- /dev/null +++ b/src/presentation/providers/theme-provider.jsx @@ -0,0 +1,86 @@ +import { + createContext, + useContext, + useEffect, + useLayoutEffect, + useMemo, + useState, +} from "react"; + +import { + normalizeColorSchemePreference, + resolveColorScheme, +} from "../../application/policies/color-scheme.js"; + +/** + * @typedef {{ + * preference: "system" | "light" | "dark", + * resolvedTheme: "light" | "dark", + * setPreference: (preference: "system" | "light" | "dark") => void + * }} ThemeContextValue + */ + +const ThemeContext = createContext(/** @type {ThemeContextValue | null} */ (null)); + +function systemPrefersDark() { + return ( + typeof window.matchMedia === "function" && + window.matchMedia("(prefers-color-scheme: dark)").matches + ); +} + +/** + * @param {{ + * storage?: import("../../application/ports/storage-port.js").StoragePort, + * children: React.ReactNode + * }} props + */ +export function ThemeProvider({ storage, children }) { + const [preference, updatePreference] = useState(() => { + const result = storage?.read("COLOR_SCHEME"); + return normalizeColorSchemePreference( + result?.ok ? result.value : undefined, + ); + }); + const [darkSystemTheme, setDarkSystemTheme] = useState(systemPrefersDark); + const resolvedTheme = resolveColorScheme(preference, darkSystemTheme); + + useEffect(() => { + if (typeof window.matchMedia !== "function") return undefined; + const query = window.matchMedia("(prefers-color-scheme: dark)"); + /** @param {MediaQueryListEvent} event */ + const update = (event) => setDarkSystemTheme(event.matches); + setDarkSystemTheme(query.matches); + query.addEventListener("change", update); + return () => query.removeEventListener("change", update); + }, []); + + useLayoutEffect(() => { + document.documentElement.dataset.theme = resolvedTheme; + document.documentElement.dataset.themePreference = preference; + document.documentElement.style.colorScheme = resolvedTheme; + }, [preference, resolvedTheme]); + + const value = useMemo( + () => + Object.freeze({ + preference, + resolvedTheme, + /** @param {"system" | "light" | "dark"} next */ + setPreference(next) { + const normalized = normalizeColorSchemePreference(next); + updatePreference(normalized); + storage?.write("COLOR_SCHEME", normalized); + }, + }), + [preference, resolvedTheme, storage], + ); + + return {children}; +} + +export function useTheme() { + const theme = useContext(ThemeContext); + if (!theme) throw new Error("ThemeProvider is required"); + return theme; +} diff --git a/src/presentation/routes/app-router.jsx b/src/presentation/routes/app-router.jsx index 8cfc004a..d7727a9c 100644 --- a/src/presentation/routes/app-router.jsx +++ b/src/presentation/routes/app-router.jsx @@ -11,6 +11,7 @@ import { RouteBoundary } from "../boundaries/render-error-boundary.jsx"; import { AppShell } from "../layouts/app-shell.jsx"; import { PageHeader } from "../components/page-header.jsx"; import { SessionProvider, useSession } from "../providers/session-provider.jsx"; +import { ThemeProvider } from "../providers/theme-provider.jsx"; import { decideRouteAccess } from "./navigation-policy.js"; const HomePage = lazy(() => import("../pages/home-page.jsx")); @@ -171,6 +172,7 @@ function PublicRoute({ routeId, buildId, telemetry, children }) { * authSession: import("../../application/ports/auth-session-port.js").AuthSessionPort, * basename?: string, * buildId?: string, + * storage?: import("../../application/ports/storage-port.js").StoragePort, * telemetry?: import("../../application/ports/telemetry-port.js").TelemetryPort * }} props */ @@ -178,13 +180,15 @@ export function AppRouter({ authSession, basename = "/", buildId = "local-build", + storage, telemetry, }) { return ( - - - }> + + + + }> } /> - - - + + + + ); } diff --git a/src/presentation/styles/theme.css b/src/presentation/styles/theme.css index 8b9eebff..7653fe8a 100644 --- a/src/presentation/styles/theme.css +++ b/src/presentation/styles/theme.css @@ -3,12 +3,28 @@ @theme { --color-surface: oklch(0.985 0.003 247); --color-surface-muted: oklch(0.94 0.01 247); + --color-panel: oklch(1 0 0); + --color-border: oklch(0.87 0.015 247); --color-content: oklch(0.25 0.025 247); --color-content-muted: oklch(0.48 0.025 247); --color-action: oklch(0.55 0.18 255); --color-action-hover: oklch(0.48 0.2 255); --color-danger: oklch(0.55 0.2 25); + --color-danger-hover: oklch(0.47 0.2 25); + --color-on-action: oklch(1 0 0); --color-focus: oklch(0.72 0.16 225); + --color-info-content: oklch(0.38 0.16 255); + --color-info-surface: oklch(0.95 0.03 255); + --color-info-border: oklch(0.75 0.08 250); + --color-success-content: oklch(0.35 0.12 155); + --color-success-surface: oklch(0.95 0.04 155); + --color-success-border: oklch(0.72 0.1 155); + --color-warning-content: oklch(0.38 0.12 70); + --color-warning-surface: oklch(0.96 0.05 80); + --color-warning-border: oklch(0.75 0.12 80); + --color-danger-content: oklch(0.42 0.18 25); + --color-danger-surface: oklch(0.96 0.035 25); + --color-danger-border: oklch(0.72 0.12 25); --radius-control: 0.5rem; --radius-surface: 0.75rem; --spacing-page: 1.5rem; @@ -22,6 +38,33 @@ font-family: var(--font-sans); } + :root[data-theme="dark"] { + --color-surface: oklch(0.16 0.02 255); + --color-surface-muted: oklch(0.25 0.025 255); + --color-panel: oklch(0.205 0.022 255); + --color-border: oklch(0.36 0.025 255); + --color-content: oklch(0.94 0.012 255); + --color-content-muted: oklch(0.74 0.025 255); + --color-action: oklch(0.7 0.14 250); + --color-action-hover: oklch(0.79 0.12 245); + --color-danger: oklch(0.68 0.19 25); + --color-danger-hover: oklch(0.76 0.16 25); + --color-on-action: oklch(0.16 0.02 255); + --color-focus: oklch(0.82 0.15 220); + --color-info-content: oklch(0.83 0.09 250); + --color-info-surface: oklch(0.27 0.045 255); + --color-info-border: oklch(0.55 0.09 250); + --color-success-content: oklch(0.83 0.1 155); + --color-success-surface: oklch(0.27 0.045 155); + --color-success-border: oklch(0.53 0.1 155); + --color-warning-content: oklch(0.88 0.1 80); + --color-warning-surface: oklch(0.29 0.045 80); + --color-warning-border: oklch(0.58 0.11 80); + --color-danger-content: oklch(0.84 0.11 25); + --color-danger-surface: oklch(0.28 0.055 25); + --color-danger-border: oklch(0.56 0.13 25); + } + body { margin: 0; min-width: 20rem; @@ -81,7 +124,7 @@ left: 0.75rem; padding: 0.75rem 1rem; border-radius: var(--radius-control); - color: white; + color: var(--color-panel); background: var(--color-content); transform: translateY(-200%); } @@ -111,7 +154,7 @@ min-width: 0; padding: 0.75rem 1.25rem; border-bottom: 1px solid var(--color-surface-muted); - background: color-mix(in oklch, white 92%, var(--color-surface)); + background: color-mix(in oklch, var(--color-panel) 92%, var(--color-surface)); box-shadow: 0 1px 8px color-mix(in oklch, var(--color-content) 8%, transparent); } @@ -132,7 +175,7 @@ border-radius: var(--radius-control); padding: 0.55rem 0.75rem; color: var(--color-content); - background: white; + background: var(--color-panel); cursor: pointer; } @@ -143,13 +186,24 @@ margin-inline-start: auto; } + .theme-selector { + min-height: 2.25rem; + max-width: 8.5rem; + border: 1px solid var(--color-border); + border-radius: var(--radius-control); + padding: 0.35rem 2rem 0.35rem 0.65rem; + color: var(--color-content); + background: var(--color-panel); + cursor: pointer; + } + .app-shell__session-error { position: absolute; top: calc(100% + 0.25rem); right: 1rem; padding: 0.5rem; color: var(--color-danger); - background: white; + background: var(--color-panel); } .session-status { @@ -165,8 +219,8 @@ } .session-status[data-state="authenticated"] { - color: oklch(0.35 0.12 155); - background: oklch(0.93 0.05 155); + color: var(--color-success-content); + background: var(--color-success-surface); } .session-status[data-state="integration-failed"] { @@ -179,8 +233,8 @@ grid-area: sidebar; height: calc(100vh - 4.5rem); padding: 1.25rem 0.75rem; - border-right: 1px solid var(--color-surface-muted); - background: white; + border-right: 1px solid var(--color-border); + background: var(--color-panel); } .app-navigation { @@ -208,7 +262,11 @@ .app-navigation__link.is-active { color: var(--color-action-hover); - background: color-mix(in oklch, var(--color-action) 10%, white); + background: color-mix( + in oklch, + var(--color-action) 14%, + var(--color-panel) + ); font-weight: 800; } @@ -224,16 +282,19 @@ } .ui-panel { - @apply rounded-surface border border-surface-muted bg-white p-6 shadow-sm; + @apply rounded-surface p-6 shadow-sm; + border: 1px solid var(--color-border); + background: var(--color-panel); } .ui-button { - @apply rounded-control bg-action px-4 py-2 font-semibold text-white; + @apply rounded-control bg-action px-4 py-2 font-semibold; display: inline-flex; min-height: 2.75rem; align-items: center; justify-content: center; border: 0; + color: var(--color-on-action); text-decoration: none; cursor: pointer; } @@ -250,7 +311,7 @@ .ui-button--secondary { border: 1px solid var(--color-surface-muted); color: var(--color-content); - background: white; + background: var(--color-panel); } .ui-button--secondary:hover { @@ -259,12 +320,12 @@ } .ui-button--danger { - color: white; + color: var(--color-on-action); background: var(--color-danger); } .ui-button--danger:hover { - background: oklch(0.47 0.2 25); + background: var(--color-danger-hover); } .ui-button--ghost { @@ -321,11 +382,12 @@ width: 100%; min-height: 2.75rem; box-sizing: border-box; - border: 1px solid color-mix(in oklch, var(--color-content-muted) 55%, white); + border: 1px solid + color-mix(in oklch, var(--color-content-muted) 55%, var(--color-panel)); border-radius: var(--radius-control); padding: 0.65rem 0.8rem; color: var(--color-content); - background: white; + background: var(--color-panel); } .ui-field__input[aria-invalid="true"] { @@ -337,10 +399,10 @@ min-width: 0; flex-direction: column; gap: 1.25rem; - border: 1px solid var(--color-surface-muted); + border: 1px solid var(--color-border); border-radius: var(--radius-surface); padding: 1.25rem; - background: white; + background: var(--color-panel); box-shadow: 0 8px 28px color-mix(in oklch, var(--color-content) 6%, transparent); } @@ -376,23 +438,23 @@ } .ui-alert--info { - border-color: oklch(0.75 0.08 250); - background: oklch(0.96 0.025 250); + border-color: var(--color-info-border); + background: var(--color-info-surface); } .ui-alert--success { - border-color: oklch(0.72 0.1 155); - background: oklch(0.96 0.03 155); + border-color: var(--color-success-border); + background: var(--color-success-surface); } .ui-alert--warning { - border-color: oklch(0.75 0.12 80); - background: oklch(0.97 0.035 80); + border-color: var(--color-warning-border); + background: var(--color-warning-surface); } .ui-alert--danger { - border-color: oklch(0.72 0.12 25); - background: oklch(0.96 0.03 25); + border-color: var(--color-danger-border); + background: var(--color-danger-surface); } .ui-alert__content, @@ -432,23 +494,23 @@ } .ui-badge--info { - color: oklch(0.38 0.16 255); - background: oklch(0.93 0.04 255); + color: var(--color-info-content); + background: var(--color-info-surface); } .ui-badge--success { - color: oklch(0.35 0.12 155); - background: oklch(0.93 0.05 155); + color: var(--color-success-content); + background: var(--color-success-surface); } .ui-badge--warning { - color: oklch(0.38 0.12 70); - background: oklch(0.94 0.06 80); + color: var(--color-warning-content); + background: var(--color-warning-surface); } .ui-badge--danger { - color: oklch(0.42 0.18 25); - background: oklch(0.94 0.045 25); + color: var(--color-danger-content); + background: var(--color-danger-surface); } .ui-dialog { @@ -460,7 +522,7 @@ border-radius: var(--radius-surface); padding: 0; color: var(--color-content); - background: white; + background: var(--color-panel); box-shadow: 0 24px 70px color-mix(in oklch, var(--color-content) 25%, transparent); } @@ -508,6 +570,10 @@ padding-block: clamp(1rem, 5vw, 3.5rem) 0.5rem; } + [data-route-heading]:focus { + outline: none; + } + .page-header__eyebrow { margin-block-end: 0.75rem; color: var(--color-action); @@ -612,10 +678,10 @@ display: grid; gap: 0.45rem; min-width: 0; - border: 1px solid var(--color-surface-muted); + border: 1px solid var(--color-border); border-radius: var(--radius-control); padding: 0.75rem; - background: white; + background: var(--color-panel); } .token-swatch__color { @@ -633,9 +699,6 @@ } .gallery-notice { - position: sticky; - z-index: 10; - bottom: 1rem; display: block; width: fit-content; max-width: 100%; @@ -644,7 +707,7 @@ border-radius: 999px; padding: 0.65rem 1rem; color: var(--color-content); - background: white; + background: var(--color-panel); box-shadow: 0 8px 28px color-mix(in oklch, var(--color-content) 10%, transparent); font-size: 0.875rem; font-weight: 650; @@ -681,14 +744,14 @@ } .state-surface--warning { - border-color: oklch(0.75 0.12 80); - background: oklch(0.97 0.035 80); + border-color: var(--color-warning-border); + background: var(--color-warning-surface); } .state-surface--danger, .ui-terminal-error { - border-color: oklch(0.72 0.12 25); - background: oklch(0.98 0.02 25); + border-color: var(--color-danger-border); + background: var(--color-danger-surface); } .state-surface--loading { @@ -757,6 +820,10 @@ display: none; } + .app-shell__brand { + display: none; + } + .readiness-grid { grid-template-columns: minmax(0, 1fr); } diff --git a/tests/e2e/theme.spec.js b/tests/e2e/theme.spec.js new file mode 100644 index 00000000..1f4ff4a5 --- /dev/null +++ b/tests/e2e/theme.spec.js @@ -0,0 +1,38 @@ +import AxeBuilder from "@axe-core/playwright"; +import { expect, test } from "@playwright/test"; + +test("persists an explicit color scheme through the storage contract", async ({ + page, +}) => { + await page.goto("/"); + const selector = page.getByRole("combobox", { name: "색상 테마" }); + + await selector.selectOption("dark"); + await expect(page.locator("html")).toHaveAttribute("data-theme", "dark"); + await expect(page.locator("html")).toHaveCSS("color-scheme", "dark"); + const results = await new AxeBuilder({ page }) + .withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]) + .analyze(); + expect( + results.violations.filter((violation) => + ["critical", "serious"].includes(violation.impact ?? ""), + ), + ).toEqual([]); + + await page.reload(); + await expect(selector).toHaveValue("dark"); + await expect(page.locator("html")).toHaveAttribute("data-theme", "dark"); +}); + +test("tracks operating-system changes while system preference is selected", async ({ + page, +}) => { + await page.emulateMedia({ colorScheme: "dark" }); + await page.goto("/"); + const selector = page.getByRole("combobox", { name: "색상 테마" }); + await selector.selectOption("system"); + await expect(page.locator("html")).toHaveAttribute("data-theme", "dark"); + + await page.emulateMedia({ colorScheme: "light" }); + await expect(page.locator("html")).toHaveAttribute("data-theme", "light"); +}); diff --git a/tests/unit/color-scheme.test.js b/tests/unit/color-scheme.test.js new file mode 100644 index 00000000..065aa968 --- /dev/null +++ b/tests/unit/color-scheme.test.js @@ -0,0 +1,44 @@ +// @vitest-environment jsdom + +import { describe, expect, it } from "vitest"; + +import { + normalizeColorSchemePreference, + resolveColorScheme, +} from "../../src/application/policies/color-scheme.js"; +import { initializeColorScheme } from "../../src/bootstrap/initialize-color-scheme.js"; + +describe("color scheme policy", () => { + it("normalizes unknown persisted values to the safe system default", () => { + expect(normalizeColorSchemePreference("sepia")).toBe("system"); + expect(normalizeColorSchemePreference("dark")).toBe("dark"); + }); + + it("resolves system and explicit preferences deterministically", () => { + expect(resolveColorScheme("system", true)).toBe("dark"); + expect(resolveColorScheme("system", false)).toBe("light"); + expect(resolveColorScheme("light", true)).toBe("light"); + }); + + it("applies a persisted preference before application paint", () => { + const storage = { + read: () => ({ ok: true, value: "system" }), + write: () => ({ ok: true }), + remove: () => ({ ok: true }), + }; + + const result = initializeColorScheme(storage, { + documentElement: document.documentElement, + matchMedia: () => + /** @type {MediaQueryList} */ ({ matches: true }), + }); + + expect(result).toEqual({ preference: "system", resolved: "dark" }); + expect(document.documentElement).toHaveAttribute("data-theme", "dark"); + expect(document.documentElement).toHaveAttribute( + "data-theme-preference", + "system", + ); + expect(document.documentElement.style.colorScheme).toBe("dark"); + }); +}); From 236909be644e612718c4d4203173bbc9317bb3a5 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sun, 26 Jul 2026 00:28:09 +0900 Subject: [PATCH 044/178] test: harden starter experience quality contract --- .gitea/workflows/quality-gates.yml | 8 +-- README.md | 39 +++++++++-- artifacts/tests/a11y-manual/EXAMPLES_AUTH.md | 18 +++++ .../tests/a11y-manual/EXAMPLES_STATES.md | 18 +++++ artifacts/tests/a11y-manual/EXAMPLES_UI.md | 18 +++++ config/ci/gates.json | 3 + docs/accessibility/manual-checklist.md | 16 +++-- docs/architecture/overview.md | 8 +++ docs/architecture/starter-experience.md | 69 +++++++++++++++++++ docs/operations/ci-quality-gates.md | 5 ++ docs/styling/design-tokens.md | 32 +++++++-- docs/testing/taxonomy.md | 7 ++ playwright.config.js | 2 + scripts/lib/manual-a11y-evidence.mjs | 3 + scripts/write-a11y-report.mjs | 4 +- tests/e2e/responsive.spec.js | 36 ++++++++++ tests/unit/manual-a11y-evidence.test.js | 12 +++- 17 files changed, 278 insertions(+), 20 deletions(-) create mode 100644 artifacts/tests/a11y-manual/EXAMPLES_AUTH.md create mode 100644 artifacts/tests/a11y-manual/EXAMPLES_STATES.md create mode 100644 artifacts/tests/a11y-manual/EXAMPLES_UI.md create mode 100644 docs/architecture/starter-experience.md create mode 100644 tests/e2e/responsive.spec.js diff --git a/.gitea/workflows/quality-gates.yml b/.gitea/workflows/quality-gates.yml index efede9ee..5fcfafa0 100644 --- a/.gitea/workflows/quality-gates.yml +++ b/.gitea/workflows/quality-gates.yml @@ -53,9 +53,9 @@ jobs: run: | corepack enable corepack pnpm install --frozen-lockfile - - name: Install Chromium + - name: Install Playwright browsers if: ${{ matrix.browser }} - run: corepack pnpm exec playwright install --with-deps chromium + run: corepack pnpm exec playwright install --with-deps chromium firefox webkit - name: Run blocking gate run: corepack pnpm ci:gate -- ${{ matrix.gate }} - name: Upload gate evidence @@ -91,9 +91,9 @@ jobs: run: | corepack enable corepack pnpm install --frozen-lockfile - - name: Install Chromium + - name: Install Playwright browsers if: ${{ matrix.browser }} - run: corepack pnpm exec playwright install --with-deps chromium + run: corepack pnpm exec playwright install --with-deps chromium firefox webkit - name: Run blocking gate run: corepack pnpm ci:gate -- ${{ matrix.gate }} - name: Upload gate evidence diff --git a/README.md b/README.md index 2d4dac6a..43bcad9a 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,27 @@ corepack pnpm dev Runtime-public settings live in `public/config.json` and are validated before the product tree mounts. Client secrets are forbidden. +## Included starter experience + +The default build mounts a domain-neutral application shell with a header, +responsive sidebar, route focus management, session integration status, and a +persistent `system` / `light` / `dark` theme selector. + +| Route | Purpose | +| --- | --- | +| `/` | implementation readiness and starter links | +| `/examples/ui` | buttons, fields, cards, alerts, badges, modal, and tokens | +| `/examples/states` | loading, refresh, empty, error, auth, forbidden, and not-found states | +| `/examples/auth` | reactive external-auth integration seam | +| `/sample/resources` | protected, domain-neutral integration route | + +`AUTH_MODE=demo` is credential-free and accepted only in local/development +environments. Deployments use `AUTH_MODE=external` and provide the opaque auth +owner described in +[`docs/architecture/starter-experience.md`](docs/architecture/starter-experience.md). +The client route policy is user experience only; server authorization remains +authoritative. + ## Architecture Dependencies point inward: @@ -27,9 +48,11 @@ bootstrap composes concrete adapters contracts own cross-cutting registries ``` -See `docs/architecture/overview.md` and `docs/architecture/layers.md`. The -removable sample slice is under `src/sample/contract-fixture`; product code is -not allowed to import it. +See `docs/architecture/overview.md`, `docs/architecture/layers.md`, and +`docs/architecture/starter-experience.md`. The removable sample slice is under +`src/sample/contract-fixture`; product code is not allowed to import it. The +visible starter routes do not depend on that fixture and continue to build +after it is removed. ## Verification @@ -52,9 +75,17 @@ corepack pnpm drill:runbooks corepack pnpm check:ci ``` +Install the pinned Playwright browser engines before the first cross-browser +run: + +```bash +corepack pnpm exec playwright install --with-deps chromium firefox webkit +``` + Two gates intentionally need external evidence: -- `review:a11y-manual` needs a signed human keyboard/focus/screen-reader review. +- `review:a11y-manual` needs a signed human keyboard/focus/screen-reader review + for all six registered routes. - `collect:web-vitals-evidence` stays `FAIL_UNVERIFIED` until a reviewed minimum eligible-sample threshold and 28 days of production data exist. diff --git a/artifacts/tests/a11y-manual/EXAMPLES_AUTH.md b/artifacts/tests/a11y-manual/EXAMPLES_AUTH.md new file mode 100644 index 00000000..8c6efa23 --- /dev/null +++ b/artifacts/tests/a11y-manual/EXAMPLES_AUTH.md @@ -0,0 +1,18 @@ +# EXAMPLES_AUTH accessibility review + +Status: pending-manual-review +Route ID: EXAMPLES_AUTH +Release ID: +Reviewer: +Reviewed at: +Signature: +Attestation: pending +M1 Keyboard: pending +M2 Visible focus: pending +M3 Route focus: pending +M4 Modal focus: not-applicable (no modal on this route) +M5 Error association: not-applicable (no form error on this route) +M6 Color signal: pending +M7 Reduced motion: pending +Screen reader: pending +Notes: Review session state announcements and unavailable external-integration behavior. diff --git a/artifacts/tests/a11y-manual/EXAMPLES_STATES.md b/artifacts/tests/a11y-manual/EXAMPLES_STATES.md new file mode 100644 index 00000000..b071073a --- /dev/null +++ b/artifacts/tests/a11y-manual/EXAMPLES_STATES.md @@ -0,0 +1,18 @@ +# EXAMPLES_STATES accessibility review + +Status: pending-manual-review +Route ID: EXAMPLES_STATES +Release ID: +Reviewer: +Reviewed at: +Signature: +Attestation: pending +M1 Keyboard: pending +M2 Visible focus: pending +M3 Route focus: pending +M4 Modal focus: not-applicable (no modal on this route) +M5 Error association: not-applicable (no form error on this route) +M6 Color signal: pending +M7 Reduced motion: pending +Screen reader: pending +Notes: Review loading, refresh, empty, error, authentication, forbidden, and not-found announcements. diff --git a/artifacts/tests/a11y-manual/EXAMPLES_UI.md b/artifacts/tests/a11y-manual/EXAMPLES_UI.md new file mode 100644 index 00000000..b82c1cfe --- /dev/null +++ b/artifacts/tests/a11y-manual/EXAMPLES_UI.md @@ -0,0 +1,18 @@ +# EXAMPLES_UI accessibility review + +Status: pending-manual-review +Route ID: EXAMPLES_UI +Release ID: +Reviewer: +Reviewed at: +Signature: +Attestation: pending +M1 Keyboard: pending +M2 Visible focus: pending +M3 Route focus: pending +M4 Modal focus: pending +M5 Error association: pending +M6 Color signal: pending +M7 Reduced motion: pending +Screen reader: pending +Notes: Review the text-field error association and modal focus containment/restoration. diff --git a/config/ci/gates.json b/config/ci/gates.json index ff7edbaf..2de046d6 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -125,6 +125,9 @@ "evidence": [ "artifacts/tests/a11y.json", "artifacts/tests/a11y-manual/APP_HOME.md", + "artifacts/tests/a11y-manual/EXAMPLES_UI.md", + "artifacts/tests/a11y-manual/EXAMPLES_STATES.md", + "artifacts/tests/a11y-manual/EXAMPLES_AUTH.md", "artifacts/tests/a11y-manual/SAMPLE_RESOURCE_LIST.md", "artifacts/tests/a11y-manual/NOT_FOUND.md", "artifacts/tests/a11y-manual/report.json" diff --git a/docs/accessibility/manual-checklist.md b/docs/accessibility/manual-checklist.md index 9ef5f1d1..3ebfe3a8 100644 --- a/docs/accessibility/manual-checklist.md +++ b/docs/accessibility/manual-checklist.md @@ -1,10 +1,12 @@ # Manual accessibility review checklist Automated axe checks do not establish WCAG conformance. A human reviewer must -review all three route records in `artifacts/tests/a11y-manual/` against one -release candidate and sign them. Copy the template fields exactly; the gate -rejects blank identity/timestamp/signature fields, pending verdicts, mismatched -release IDs, or missing routes. +review all six route records in `artifacts/tests/a11y-manual/` against one +release candidate and sign them. The required scope is derived from the route +registry: `APP_HOME`, `EXAMPLES_UI`, `EXAMPLES_STATES`, `EXAMPLES_AUTH`, +`SAMPLE_RESOURCE_LIST`, and `NOT_FOUND`. Copy the template fields exactly; the +gate rejects blank identity/timestamp/signature fields, pending verdicts, +mismatched release IDs, or missing routes. Allowed item verdicts: @@ -43,5 +45,7 @@ The reviewer must verify: - M7: non-essential motion is suppressed with reduced-motion preference - Screen reader: headings, live regions, errors, and actions are announced once -Passing automated evidence means only that tested pages had no critical or -serious axe findings under the recorded browser run. +`EXAMPLES_UI` requires real M4 modal and M5 field-error review; those items must +not be marked not-applicable on that route. Passing automated evidence means +only that tested pages had no critical or serious axe findings under the +recorded Chromium, Firefox, and WebKit runs. diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index 9feeb9e1..ff860a01 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -8,6 +8,8 @@ in `review-ledger.json`, not automatically to edits in this file. flowchart LR Bootstrap[bootstrap / composition root] --> Presentation[presentation] Bootstrap --> Adapters[adapters] + Presentation --> Shell[app shell and route surfaces] + Shell --> Providers[session and theme providers] Presentation --> Application[application] Adapters --> Application Application --> Domain[domain] @@ -21,3 +23,9 @@ implement application ports, and only the composition root selects concrete adapters. Contract registries are the single named source for routes, API operations, environment values, storage keys, errors, queries, telemetry, and release tokens. + +The executable route tree is mounted only after runtime configuration and +release-manifest coherence pass. It receives the composed query client, +credential-opaque session port, storage port, telemetry port, and immutable +build ID. Visible starter pages depend on those ports and contracts, never on a +concrete adapter or the removable sample fixture. diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md new file mode 100644 index 00000000..b45a51f5 --- /dev/null +++ b/docs/architecture/starter-experience.md @@ -0,0 +1,69 @@ +# Starter experience contract + +The repository provides a runnable, domain-neutral application rather than +only infrastructure contracts. The starter experience is intentionally +replaceable at the page level while the shell, providers, boundaries, +primitives, and state surfaces remain reusable. + +## Runtime composition + +```text +validated config + coherent release manifest + -> concrete adapters + -> QueryClientProvider + -> ThemeProvider + -> SessionProvider + -> BrowserRouter + -> AppShell + -> lazy route boundary +``` + +Boot stops before product mount when configuration or release coherence fails. +Each lazy page renders inside Suspense and a telemetry-aware route boundary. +Route changes move focus to the new page heading; the skip link and landmarks +remain stable in the shell. + +## Registered routes + +| ID | Path | Access | Surface | +| --- | --- | --- | --- | +| `APP_HOME` | `/` | public | readiness dashboard | +| `EXAMPLES_UI` | `/examples/ui` | public | interactive primitives and tokens | +| `EXAMPLES_STATES` | `/examples/states` | public | async and access state matrix | +| `EXAMPLES_AUTH` | `/examples/auth` | public | session integration controls | +| `SAMPLE_RESOURCE_LIST` | `/sample/resources` | integration-defined | protected integration seam | +| `NOT_FOUND` | `*` | public | safe navigation recovery | + +Navigation labels and order come from `ROUTE_REGISTRY`; the sidebar does not +maintain a second route list. The client access decision never claims to be +authorization. + +## Authentication seam + +The session port exposes state subscription, sign-in start, sign-out, +credential attachment, recovery, and unauthenticated notification. Credentials +remain opaque to the application and presentation layers. + +- `demo`: local/development-only state transition with no credentials +- `external`: delegates to `globalThis.__CA_FRONTEND_AUTH_OWNER__` +- missing/invalid external owner: fails closed as `integration-failed` + +An external owner implements `readState`, `subscribe`, `beginSignIn`, +`signOut`, `attachCredential`, `recoverSession`, and +`notifyUnauthenticated`. It owns token acquisition and storage. + +## Extending the starter + +1. Register the route path, access hint, title, chunk, loading surface, error + surface, and optional navigation metadata in `src/contracts/routes.js`. +2. Add a lazy page in `src/presentation/` and render it through `RouteSurface`. +3. Use application ports or use cases; do not import concrete adapters. +4. Use the semantic tokens, UI primitives, and state surfaces before adding a + project-specific variant. +5. Add component behavior, all-engine E2E, automated axe, and signed manual + route evidence. +6. Run `test:sample-removal` to prove the visible starter still builds without + `src/sample/contract-fixture`. + +Theme preference is the public `COLOR_SCHEME` storage contract. Authentication +tokens and other secrets remain forbidden storage keys. diff --git a/docs/operations/ci-quality-gates.md b/docs/operations/ci-quality-gates.md index 447f5b36..e3c82dd9 100644 --- a/docs/operations/ci-quality-gates.md +++ b/docs/operations/ci-quality-gates.md @@ -30,6 +30,11 @@ registry: merge evidence through the PR decision, coherent release evidence through the next release promotion, drill evidence through the next production promotion, and field evidence through aggregation. +Browser-backed merge gates install and execute the pinned Chromium, Firefox, +and WebKit engines. This makes route behavior, reflow, native dialog semantics, +theme persistence, and automated accessibility a cross-engine contract rather +than a Chromium-only smoke check. + Repository variables required by higher tiers: - `HOSTING_BASE_URL` for live header verification diff --git a/docs/styling/design-tokens.md b/docs/styling/design-tokens.md index 2de05b5c..178d367b 100644 --- a/docs/styling/design-tokens.md +++ b/docs/styling/design-tokens.md @@ -1,8 +1,32 @@ # Design-token styling contract `src/presentation/styles/theme.css` is the styling SSOT. Components consume -semantic color, spacing, typography, and radius tokens through static Tailwind -classes. +semantic color, spacing, typography, status, and radius tokens through static +classes. `/examples/ui` is the executable token and primitive gallery. + +## Theme contract + +The supported public preference is the closed set `system`, `light`, and +`dark`. `ThemeProvider` reads and writes `COLOR_SCHEME` through the application +storage port; it does not access a raw storage key. `system` subscribes to +`prefers-color-scheme` changes. Bootstrap applies the persisted preference +before React paints. + +Components use semantic tokens such as `--color-panel`, `--color-content`, +`--color-border`, `--color-action`, and status surface/content/border triples. +They must not hard-code a light-only panel or text color. Both light and dark +surfaces are included in automated axe checks. + +## Included primitives + +- `Button`: primary, secondary, danger, and ghost intent +- `TextField`: label, help text, required state, and associated validation error +- `Card`: labelled surface with optional footer +- `Alert` and `Badge`: non-color-only status feedback +- `Dialog`: native modal semantics, Escape/backdrop close, and trigger focus + restoration +- async and access state surfaces: loading, refresh, empty, terminal error, + auth required, forbidden, and not found Arbitrary-value policy: @@ -13,5 +37,5 @@ Arbitrary-value policy: - user-controlled or runtime-composed class strings are forbidden - class variants must be selected from a closed static map -The removable sample may demonstrate tokens, but product modules must not -import from `src/sample/contract-fixture`. +The removable sample may demonstrate tokens, but production starter modules do +not import from `src/sample/contract-fixture`. diff --git a/docs/testing/taxonomy.md b/docs/testing/taxonomy.md index 5a9a72c1..0f460aa9 100644 --- a/docs/testing/taxonomy.md +++ b/docs/testing/taxonomy.md @@ -12,6 +12,13 @@ Each gate is blocking in its declared scope. Failures are not downgraded with | end-to-end | `pnpm test:e2e` | `artifacts/tests/e2e/` | | accessibility | `pnpm test:a11y` | `artifacts/tests/a11y.json` | +End-to-end and automated accessibility scenarios run on the pinned Chromium, +Firefox, and WebKit engines. The responsive contract explicitly exercises +320px reflow, a mobile navigation drawer, and a wide two-column gallery. +Theme scenarios verify persistence, operating-system changes, and dark-surface +axe results. Native modal focus and validation association are exercised in +both component and browser tests. + A control is verified only when a positive fixture passes and its deliberately failing negative fixture is rejected. Generated evidence is retained by CI; the repository tracks only the evidence directory structure. diff --git a/playwright.config.js b/playwright.config.js index 43ec1ab7..b87fd866 100644 --- a/playwright.config.js +++ b/playwright.config.js @@ -19,5 +19,7 @@ export default defineConfig({ }, projects: [ { name: "chromium", use: { ...devices["Desktop Chrome"] } }, + { name: "firefox", use: { ...devices["Desktop Firefox"] } }, + { name: "webkit", use: { ...devices["Desktop Safari"] } }, ], }); diff --git a/scripts/lib/manual-a11y-evidence.mjs b/scripts/lib/manual-a11y-evidence.mjs index a56dd611..2fbeac78 100644 --- a/scripts/lib/manual-a11y-evidence.mjs +++ b/scripts/lib/manual-a11y-evidence.mjs @@ -1,5 +1,8 @@ export const MANUAL_A11Y_ROUTE_IDS = Object.freeze([ "APP_HOME", + "EXAMPLES_UI", + "EXAMPLES_STATES", + "EXAMPLES_AUTH", "SAMPLE_RESOURCE_LIST", "NOT_FOUND", ]); diff --git a/scripts/write-a11y-report.mjs b/scripts/write-a11y-report.mjs index 73faf229..b686a33e 100644 --- a/scripts/write-a11y-report.mjs +++ b/scripts/write-a11y-report.mjs @@ -1,5 +1,7 @@ import { mkdir, writeFile } from "node:fs/promises"; +import { MANUAL_A11Y_ROUTE_IDS } from "./lib/manual-a11y-evidence.mjs"; + await mkdir("artifacts/tests", { recursive: true }); await writeFile( "artifacts/tests/a11y.json", @@ -7,7 +9,7 @@ await writeFile( { schemaVersion: 1, generatedAt: new Date().toISOString(), - scope: ["APP_HOME", "SAMPLE_RESOURCE_LIST", "NOT_FOUND"], + scope: MANUAL_A11Y_ROUTE_IDS, threshold: { critical: 0, serious: 0 }, automatedStatus: "passed", manualReview: "see artifacts/tests/a11y-manual/report.json", diff --git a/tests/e2e/responsive.spec.js b/tests/e2e/responsive.spec.js new file mode 100644 index 00000000..663ca190 --- /dev/null +++ b/tests/e2e/responsive.spec.js @@ -0,0 +1,36 @@ +import { expect, test } from "@playwright/test"; + +test("reflows the UI gallery at the 320px minimum without horizontal overflow", async ({ + page, +}) => { + await page.setViewportSize({ width: 320, height: 720 }); + await page.goto("/examples/ui"); + await expect( + page.getByRole("heading", { level: 1, name: "UI 구성요소" }), + ).toBeVisible(); + await expect( + page.getByRole("button", { name: "메뉴", exact: true }), + ).toBeVisible(); + + const viewport = await page.evaluate(() => ({ + clientWidth: document.documentElement.clientWidth, + scrollWidth: document.documentElement.scrollWidth, + })); + expect(viewport.scrollWidth).toBeLessThanOrEqual(viewport.clientWidth); +}); + +test("keeps desktop navigation and two-column examples at wide viewports", async ({ + page, +}) => { + await page.setViewportSize({ width: 1440, height: 900 }); + await page.goto("/examples/ui"); + + await expect(page.getByRole("navigation", { name: "주요 탐색" })).toBeVisible(); + await expect( + page.getByRole("button", { name: "메뉴", exact: true }), + ).toBeHidden(); + await expect(page.locator(".component-grid--two").first()).toHaveCSS( + "grid-template-columns", + /.+px .+px/, + ); +}); diff --git a/tests/unit/manual-a11y-evidence.test.js b/tests/unit/manual-a11y-evidence.test.js index 09d6f4bc..80dabff7 100644 --- a/tests/unit/manual-a11y-evidence.test.js +++ b/tests/unit/manual-a11y-evidence.test.js @@ -1,6 +1,10 @@ import { describe, expect, it } from "vitest"; -import { validateManualA11yEvidence } from "../../scripts/lib/manual-a11y-evidence.mjs"; +import { + MANUAL_A11Y_ROUTE_IDS, + validateManualA11yEvidence, +} from "../../scripts/lib/manual-a11y-evidence.mjs"; +import { ROUTE_REGISTRY } from "../../src/contracts/routes.js"; const reviewed = `Status: reviewed Route ID: APP_HOME @@ -20,6 +24,12 @@ Screen reader: pass Notes: no defects`; describe("manual accessibility evidence", () => { + it("requires evidence for every registered user-visible route", () => { + expect([...MANUAL_A11Y_ROUTE_IDS].sort()).toEqual( + Object.keys(ROUTE_REGISTRY).sort(), + ); + }); + it("accepts a complete signed human review record", () => { expect(validateManualA11yEvidence(reviewed)).toMatchObject({ failures: [], From 5a7a6c4ae5a289f53e63372ed58c2b13e942df06 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sun, 26 Jul 2026 00:32:50 +0900 Subject: [PATCH 045/178] test(performance): derive navigation target from route registry --- scripts/test-performance.mjs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/scripts/test-performance.mjs b/scripts/test-performance.mjs index 6f5eb4a0..598ec0a7 100644 --- a/scripts/test-performance.mjs +++ b/scripts/test-performance.mjs @@ -6,6 +6,7 @@ import process from "node:process"; import { chromium } from "@playwright/test"; import { evaluateLabBudget } from "../src/application/policies/performance-budgets.js"; +import { ROUTE_REGISTRY } from "../src/contracts/routes.js"; const server = spawn( "corepack", @@ -66,8 +67,13 @@ try { }).observe({ type: "layout-shift", buffered: true }); }); await page.goto(baseUrl, { waitUntil: "networkidle" }); + const targetLabel = + ROUTE_REGISTRY.SAMPLE_RESOURCE_LIST.navigationLabel; + if (!targetLabel) { + throw new Error("Performance route must be present in navigation."); + } const interactionStarted = performance.now(); - await page.getByRole("link", { name: "샘플 리소스" }).click(); + await page.getByRole("link", { name: targetLabel }).click(); await page.getByRole("heading", { name: "세션이 필요합니다." }).waitFor(); const namedInteractionMs = performance.now() - interactionStarted; const paint = await page.evaluate( From 68342e25ce47f812d06b6df73aefc848efcc4516 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sun, 26 Jul 2026 02:09:06 +0900 Subject: [PATCH 046/178] docs: audit frontend platform capabilities --- README.md | 19 + .../frontend-platform-capability-review.md | 447 ++++++ ...rontend-platform-implementation-roadmap.md | 954 ++++++++++++ .../frontend-ports-adapters-and-boundaries.md | 1253 ++++++++++++++++ docs/architecture/layers.md | 8 + docs/architecture/overview.md | 47 +- .../routing-pages-and-patterns.md | 492 +++++++ docs/architecture/starter-experience.md | 10 +- .../typescript-state-and-data-flow.md | 549 +++++++ docs/styling/design-system-platform.md | 868 +++++++++++ docs/styling/design-tokens.md | 7 + .../frontend-platform-testing-strategy.md | 1283 +++++++++++++++++ docs/testing/taxonomy.md | 7 + 13 files changed, 5934 insertions(+), 10 deletions(-) create mode 100644 docs/architecture/frontend-platform-capability-review.md create mode 100644 docs/architecture/frontend-platform-implementation-roadmap.md create mode 100644 docs/architecture/frontend-ports-adapters-and-boundaries.md create mode 100644 docs/architecture/routing-pages-and-patterns.md create mode 100644 docs/architecture/typescript-state-and-data-flow.md create mode 100644 docs/styling/design-system-platform.md create mode 100644 docs/testing/frontend-platform-testing-strategy.md diff --git a/README.md b/README.md index 43bcad9a..0c67f8cf 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,25 @@ See `docs/architecture/overview.md`, `docs/architecture/layers.md`, and visible starter routes do not depend on that fixture and continue to build after it is removed. +### Platform capability review + +The starter shell is implemented, but the repository review also records the +remaining work required before feature teams can use every declared contract +through one end-to-end application path: + +- [platform capability review](docs/architecture/frontend-platform-capability-review.md) +- [ports, adapters, and feature boundaries](docs/architecture/frontend-ports-adapters-and-boundaries.md) +- [TypeScript, state ownership, and data flow](docs/architecture/typescript-state-and-data-flow.md) +- [routing, page templates, and reusable patterns](docs/architecture/routing-pages-and-patterns.md) +- [design-system platform](docs/styling/design-system-platform.md) +- [frontend platform testing strategy](docs/testing/frontend-platform-testing-strategy.md) +- [implementation roadmap](docs/architecture/frontend-platform-implementation-roadmap.md) + +These documents distinguish repository defaults from opt-in adapters and +project-owned integrations. They are target designs and review findings; a +capability is not treated as implemented until its branch acceptance criteria +and executable gates pass. + ## Verification Common local checks: diff --git a/docs/architecture/frontend-platform-capability-review.md b/docs/architecture/frontend-platform-capability-review.md new file mode 100644 index 00000000..bbf50d25 --- /dev/null +++ b/docs/architecture/frontend-platform-capability-review.md @@ -0,0 +1,447 @@ +# 프론트엔드 플랫폼 역량 재검토 + +## 1. 문서 목적 + +이 문서는 도메인 기능과 실제 운영 환경의 배포 증적을 제외하고, 이 저장소가 새 +프론트엔드 제품의 출발점으로 제공해야 하는 공통 역량을 다시 평가한다. 평가 +기준은 다음과 같다. + +- 코드나 설정 파일이 존재하는지만 보지 않는다. +- 부트스트랩부터 화면까지 실제 호출 경로가 연결되는지 확인한다. +- 선언한 레지스트리와 정책이 런타임 및 CI에서 집행되는지 확인한다. +- 기본 번들에 포함할 역량과 필요할 때 설치할 확장 역량을 구분한다. +- 특정 벤더를 채택하더라도 제품 코드가 벤더 API에 직접 결합되지 않는지 확인한다. + +검토 기준 브랜치는 `develop`, 기준 커밋은 `cb195f8`이다. 이후 구현으로 경로나 +세부 내용이 달라질 수 있으므로, 각 항목은 문서의 경로뿐 아니라 해당 테스트와 +아키텍처 게이트로 계속 검증해야 한다. + +## 2. 결론 + +현재 저장소는 다음 기반이 강하다. + +- 런타임 설정과 릴리스 매니페스트 검증 +- 도메인, 애플리케이션, 프레젠테이션, outbound adapter의 의존 방향 +- 공통 HTTP 실패 형태와 제한된 retry 정책 +- 앱 셸, 반응형 내비게이션, 테마, 비동기 상태 표면 +- Vitest, Testing Library, MSW, Playwright, axe를 이용한 테스트 계층 +- CI 게이트 taxonomy와 호환성·보안·성능·릴리스 계약 문서 + +그러나 “도메인 기능을 바로 추가할 수 있는 프론트엔드 플랫폼” 기준으로는 아직 +중요한 연결부가 빠져 있다. 가장 큰 문제는 공통 기능이 없다는 것보다 이미 있는 +기능이 실제 기능 화면의 표준 호출 경로로 조립되지 않았다는 점이다. + +특히 다음은 선행 해결이 필요하다. + +1. React 화면이 호출할 application input API와 런타임 주입 경계 +2. TanStack Query를 사용하는 표준 query/mutation inbound adapter +3. TypeScript 전환 전에 TS 파일까지 검사하도록 만드는 도구 안전망 +4. path/query/body projection과 runtime timeout/retry가 정확히 연결된 HTTP 계층 +5. 선언과 실행이 일치하는 typed route 계약 +6. 전체를 제거할 수 있는 실제 reference feature +7. 폼, 페이지 템플릿, 확장된 디자인 시스템과 컴포넌트 워크벤치 + +따라서 현재 상태를 “프론트 공통부가 모두 구현됐다”고 표현하면 범위가 과장된다. +더 정확한 표현은 다음과 같다. + +> 운영·안전 계약과 범용 앱 셸은 갖춰졌지만, 기능 개발자가 사용하는 application +> API, 서버 상태, 폼, 라우팅, 페이지 패턴의 표준 수직 경로는 아직 보강이 +> 필요하다. + +## 3. 판정 기준 + +| 판정 | 의미 | +| --- | --- | +| 준비됨 | 구현, 실제 조립, 자동 검증이 모두 존재한다. | +| 부분 준비 | 핵심 구현은 있으나 실제 호출 경로, 정책 집행, 예제가 불완전하다. | +| 미제공 | 새 기능을 만들 때 팀이 직접 선택·설계해야 한다. | +| 프로젝트 선택 | 기본 번들에 강제하면 비용이 더 크며, 경계와 recipe만 제공한다. | + +## 4. 역량 매트릭스 + +| 영역 | 현재 판정 | 근거 | 필요한 다음 상태 | +| --- | --- | --- | --- | +| 부트·런타임 설정 | 준비됨 | `src/bootstrap`, runtime schema, release 검사 | 현 상태 유지, TS 전환 시 동일 게이트 유지 | +| 계층 의존 방향 | 부분 준비 | `.dependency-cruiser.cjs`, `src/application/ports` | inbound/outbound 명명과 `contracts` 소유권까지 집행 | +| application facade | 부분 준비 | `create-application.js`는 있으나 `main.jsx`에서 우회 | UI에는 input API만 주입 | +| HTTP client | 부분 준비 | timeout, abort, retry, auth, envelope, Zod가 존재 | path/query, parsed body, runtime 설정, 정리 로직 보완 | +| retry | 부분 준비 | safe/keyed 요청 정책 존재 | retry 소유자 단일화, 설정 연결, telemetry | +| 오류 모델 | 부분 준비 | error registry와 normalization 존재 | typed discriminated union과 계층별 mapper | +| 검증 | 부분 준비 | runtime/API Zod 존재 | route/form/domain 경계를 분리하고 실제 parse 결과 사용 | +| 인증 연동 | 준비됨/프로젝트 선택 | opaque auth owner와 demo seam 존재 | 인증 방식별 recipe; 기본 token 저장소는 추가하지 않음 | +| 서버 상태 | 미제공에 가까운 부분 준비 | QueryClientProvider와 cache port는 존재 | query/mutation hook과 화면 reference flow | +| 클라이언트 상태 | 부분 준비 | local state, theme context, session external store | 상태 소유권 표와 typed external-store 예제 | +| 범용 global store | 프로젝트 선택 | 별도 라이브러리 없음 | 필요 조건에 따라 Zustand/Redux Toolkit/state machine 선택 | +| 라우팅 | 부분 준비 | lazy route, access hint, registry 존재 | typed runtime map, codec, recovery, metadata 집행 | +| 앱 셸·반응형 | 부분 준비 | header/sidebar/content/theme 구현 | 접근 가능한 mobile drawer와 focus 복원 | +| 페이지 템플릿 | 미제공 | 각 페이지가 직접 레이아웃 조립 | list/detail/form/status 등 슬롯 기반 템플릿 | +| 디자인 토큰 | 부분 준비 | semantic color/theme 토큰 존재 | typography, spacing, motion, layer 등 3단계 토큰 | +| 공통 UI | 부분 준비 | Button, TextField, Card, Alert, Badge, Dialog | form/navigation/overlay/data/layout primitives 확장 | +| 아이콘 | 미제공 | 문자 기호를 직접 사용 | Lucide를 로컬 icon facade 뒤에서 사용 | +| 폼 | 미제공 | 수동 문자열 검증 예제만 존재 | schema 기반 form facade와 422/dirty/pending 정책 | +| 국제화 | 미제공 | 한국어 문자열·locale이 하드코딩 | typed message/formatter/locale/RTL 경계 | +| logging/diagnostics | 미제공 | telemetry port는 있으나 logger 없음 | redaction이 적용된 diagnostics/logging 경계 | +| telemetry | 부분 준비 | registry, queue, redaction 존재 | HTTP·boot·cache·storage·route 사건에 실제 연결 | +| 비동기 상태 불변식 | 부분 준비 | 공통 model/surface는 있으나 일부 모순 상태를 허용 | query/mutation 상태 조합과 action latch를 닫음 | +| 단위·통합·E2E | 준비됨 | Vitest, RTL, MSW, Playwright 3엔진 | TS 테스트 검사, 실제 bootstrap 통합, 위험 시나리오 보강 | +| UI 회귀 검증 | 미제공 | axe/reflow는 있으나 visual baseline 없음 | Storybook 또는 동급 workshop과 시각 회귀 | +| 샘플 제거 | 부분 준비 | fixture 제거 테스트 존재 | sample domain/registry/runtime 전체 제거 검증 | +| registry·compatibility 집행 | 부분 준비 | registry와 gate는 있으나 실제 before/after 및 orphan 검사가 제한적 | type/reference/orphan/diff/migration을 자동 검증 | +| 공급망 검사 | 부분 준비 | lockfile·문서·gate는 있으나 실제 transitive 취약점/license/SBOM 깊이가 부족 | pinned scanner와 policy exception/증적 연결 | +| realtime·offline·file 등 | 프로젝트 선택 | 현재 없음 | port/adapter recipe와 선택 기준 제공 | + +## 5. 우선순위별 발견 사항 + +### 5.1 P0: 기능 개발을 막는 항목 + +#### application 계층이 런타임에서 우회된다 + +`src/bootstrap/composition-root.js`는 application을 생성하지만 +`src/bootstrap/main.jsx`는 이를 라우터에 주입하지 않는다. UI에는 auth, storage, +telemetry 같은 raw outbound dependency와 concrete QueryClient가 전달된다. +`src/application/create-application.js`도 use case 중심 input API보다 outbound +capability를 다시 노출하는 형태다. + +목표 상태: + +- `Application`은 UI가 호출할 query/command use case를 제공한다. +- `ApplicationProvider`는 이 API만 React tree에 제공한다. +- 페이지는 HTTP, storage, auth SDK, telemetry sink를 직접 호출하지 않는다. +- bootstrap만 concrete outbound adapter를 알고 조합한다. +- 실제 bootstrap부터 reference page까지 연결한 통합 테스트가 있다. + +#### 서버 상태 라이브러리는 마운트됐지만 사용할 수 없다 + +`QueryClientProvider`는 존재하지만 저장소의 제품 코드에서 `useQuery`와 +`useMutation`을 사용하지 않는다. 동시에 presentation의 `@tanstack/**` import는 +금지돼 있다. 현재 `QueryCachePort`는 명령형 read/write/invalidate만 제공하여 +React 구독, 요청 상태, cancellation, optimistic update를 대신할 수 없다. + +목표 상태: + +- canonical target인 `src/adapters/inbound/react/platform/query`에 벤더 연동을 + 한정한다. 마이그레이션 중에는 기존 `presentation`을 같은 inbound 경계로 + 취급하되 새 대체 경로를 만들지 않는다. +- `useApplicationQuery`, `useApplicationMutation` 또는 같은 역할의 typed + controller hook을 제공한다. +- HTTP retry와 query retry 중 한 계층만 재시도 책임을 갖는다. +- loading, empty, refreshing, stale, offline, error, conflict, optimistic rollback을 + reference feature에서 보여 준다. + +#### TypeScript 전환 전에 검사 도구가 TS를 인식해야 한다 + +현재 source는 모두 JS/JSX이고 `strict + allowJs + checkJs`를 사용한다. 이는 좋은 +중간 안전망이지만 다음 도구는 TS migration을 그대로 따라가지 못한다. + +- ESLint의 계층·보안 glob은 JS/JSX 중심이다. +- registry scanner는 `.ts`와 `.tsx`를 찾지 않는다. +- registry governance 경로가 `.js` 확장자로 고정되어 있다. +- tests는 현재 `tsconfig.json` 검사 범위에서 빠진다. + +따라서 파일 확장자를 먼저 바꾸면 새 TS 코드가 일부 자동 검사에서 빠질 수 있다. +TypeScript 전환은 +[TypeScript의 JavaScript migration 가이드](https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html) +처럼 점진적으로 진행하되, 이 저장소에서는 tooling glob과 CI를 먼저 고쳐야 한다. + +#### HTTP 계약에 선언과 실행의 차이가 있다 + +현재 HTTP 계층은 공통화 수준이 높지만 다음 정확성 문제가 남아 있다. + +- runtime config의 `REQUEST_TIMEOUT_MS`, `MAX_RETRY_ATTEMPTS`가 client 생성에 + 전달되지 않는다. +- operation path에 path parameter와 search parameter를 투영하는 표준 builder가 + 없다. +- sample filter는 cache key에만 반영되고 실제 요청 URL에는 반영되지 않는다. +- Zod의 parsed/transformed request body 대신 원본 body를 전송한다. +- request validation의 조기 반환 경로에서 timeout/listener 정리가 늦어진다. +- HTTP failure, retry, recovery가 telemetry 사건과 이어지지 않는다. + +client를 거대한 범용 함수로 계속 확장하지 말고 transport, request builder, auth, +timeout, retry, decoder, mapper 책임을 분리해야 한다. application에는 범용 HTTP +메서드보다 feature가 요구하는 gateway interface를 노출한다. + +#### route registry가 실행 계약이 아니다 + +route registry에는 `paramsSchema`, `searchSchema`, `loadingSurface`, +`errorSurface`, `chunkId`가 있지만 실제 router tree, lazy module, navigation +목록은 별도로 작성된다. 여러 필드는 선언만 되고 런타임에 사용되지 않는다. +chunk recovery use case와 redirect loop guard도 실제 route flow에 연결되지 않는다. + +목표 상태: + +- serializable contract와 executable runtime map을 분리한다. +- `satisfies Record`로 양방향 완전성을 검사한다. +- params/search는 Zod codec으로 경계에서 parse하고 URL builder도 같은 codec을 + 사용한다. +- loading/error/chunk/access/title/navigation metadata를 실제 route object에 + 연결한다. +- route change 시 boundary reset, focus, scroll, navigation cancellation을 + 검증한다. + +#### reference feature가 완전히 제거되지 않는다 + +현재 sample removal gate는 `src/sample/contract-fixture`만 삭제한다. sample API +operation, schema, mapper, domain model, query key는 다른 production 경로에 남는다. +반면 화면에 노출된 `/sample/resources`는 실제 query 수직 흐름을 실행하지 않는다. + +reference feature는 domain, application input/output, schemas, operation, +mapper, query controller, pages, tests를 한 소유 경계 아래 모아야 한다. 해당 모듈과 +registry contribution을 제거한 뒤 typecheck, architecture, test, build가 모두 +통과해야 “제거 가능”으로 판정한다. + +#### 비동기·복구 상태의 불변식이 닫혀 있지 않다 + +공통 async model과 gallery가 있지만 선언 가능한 상태 조합 중 일부는 사용자 +행동과 모순될 수 있다. stale data가 있는 degraded 상태와 refreshing, mutation +pending과 conflict, retry button과 실제 handler 존재 여부를 typed state로 +닫아야 한다. 상태를 boolean 여러 개로 조합하지 않고 다음과 같은 discriminated +state와 action capability로 표현한다. + +```text +initial-loading +ready +refreshing-with-data +empty +degraded-with-data +terminal-error +mutation-pending +mutation-conflict +``` + +chunk recovery와 release coherence도 policy 함수가 존재하는 것으로 완료되지 +않는다. 실제 lazy import failure가 manifest 재확인, build 비교, 단 한 번의 guarded +reload, 반복 실패 지원 표면까지 이어지고 E2E로 검증되어야 한다. + +#### telemetry, registry, 공급망 gate의 실행 깊이가 부족하다 + +telemetry registry에는 여러 사건이 있지만 실제 production producer는 제한적이다. +boot, API attempt/final failure, auth recovery, storage/cache degradation, release/chunk +recovery를 registry 사건에 연결해야 한다. + +registry/compatibility 검사는 다음까지 확장한다. + +- ID와 enum/type의 양방향 완전성 +- referenced schema/message/token의 존재 +- 실행 코드에서 소비되지 않는 orphan 항목 +- 기준 commit과 현재 commit 사이의 실제 contract diff +- breaking change의 version/migration/rollback metadata + +공급망 검사는 단순 문자열 secret 탐지에 머물지 않고 transitive dependency, +known vulnerability, license policy, SBOM/provenance를 pinned tool로 검사해야 한다. +도구 장애와 취약점 발견을 구분하고, 예외에는 owner·사유·만료일을 요구한다. + +### 5.2 P1: 공통 플랫폼 기본 제공 항목 + +- schema 기반 form facade와 field/error/pending/dirty/422 정책 +- standard, collection, detail, form, status page template +- 접근 가능한 drawer, menu, popover, select 같은 interaction primitive +- token → primitive → pattern → template로 이어지는 디자인 시스템 +- Lucide를 감싼 local icon registry와 `IconButton` +- typed message key, locale provider, formatter, pseudo-locale/RTL smoke +- redacted structured diagnostics/logger와 telemetry wiring +- Storybook 또는 동급 isolated UI workshop +- Playwright visual baseline, shared MSW scenarios, built-dist E2E +- React Hooks, JSX accessibility, TanStack Query 관련 lint +- source와 tests를 모두 포함하는 TypeScript project references +- registry/compatibility의 실제 diff와 orphan reference 검사 +- transitive vulnerability, license, SBOM/provenance 공급망 gate + +### 5.3 P2: 경계와 recipe를 제공할 선택 항목 + +다음 기능을 모든 앱의 초기 번들에 설치할 필요는 없다. 대신 port 또는 local +vendor facade, 선택 조건, 실패 정책, 테스트 fixture를 문서로 제공한다. + +| capability | 대표 기술 | 기본 제공할 경계 | 실제 설치 조건 | +| --- | --- | --- | --- | +| realtime | WebSocket, SSE | subscribe/unsubscribe, reconnect, resume, heartbeat | 서버가 push event를 제공할 때 | +| offline storage | IndexedDB | versioned repository, migration, quota failure | offline read/write가 제품 요구일 때 | +| background/cache | Service Worker, PWA | cache ownership, update, rollback recipe | installable/offline 앱일 때 | +| file transfer | presigned HTTP, multipart | progress, cancel, size/type validation | 업로드·대용량 다운로드가 있을 때 | +| generated API | OpenAPI, GraphQL, gRPC-Web | generated client를 gateway 뒤에 감싸는 규칙 | 서버 계약 형식이 확정됐을 때 | +| feature flag | local/remote flag provider | typed flag key, default, stale behavior | staged rollout가 필요할 때 | +| worker | Web Worker | request/result/cancel protocol | UI thread를 막는 CPU 작업이 있을 때 | +| multi-tab | BroadcastChannel | event versioning, source ID, conflict policy | 탭 간 동기화가 필요할 때 | +| browser capability | clipboard, notification, media | permission/result port | 해당 UX가 있을 때 | +| client workflow | Zustand, Redux Toolkit, state machine | state ownership decision과 local facade | cross-feature workflow가 실제로 생길 때 | +| large data UI | virtualization, data grid | owned component facade | 데이터 규모가 측정 기준을 넘을 때 | +| analytics/error sink | vendor SDK, OpenTelemetry | redaction, consent, sampling adapter | 운영 provider와 정책이 정해졌을 때 | + +서버의 Redis, MongoDB, PostgreSQL, MinIO를 브라우저가 직접 연결하는 구조는 기본 +frontend adapter catalog에 넣지 않는다. 브라우저는 권한 있는 backend API/BFF를 +통해 이 자원에 접근해야 한다. 프론트에서 대응되는 변화 지점은 데이터베이스 +vendor가 아니라 HTTP/GraphQL/gRPC-Web, realtime, file transfer, cache, storage, +worker, browser capability 같은 프로토콜·런타임 capability다. + +### 성능 최적화는 모두 adapter 문제인가 + +아니다. 먼저 측정하고 병목의 소유 계층에 맞는 수단을 적용한다. + +| 문제 | 기본 제공할 수단 | adapter/facade가 필요한 경우 | +| --- | --- | --- | +| 초기 JS가 큼 | route/feature lazy loading, bundle budget, dependency inventory | remote module이나 별도 delivery 전략이 있을 때 | +| 중복 네트워크 | TanStack deduplication/cache, abort, bounded retry | offline cache나 generated client를 교체할 때 | +| 느린 화면 전환 | prefetch policy, stable shell, cached-data surface | route별 prefetch provider가 필요할 때 | +| 긴 main-thread task | profiler 기준으로 계산 분리 | Web Worker message adapter | +| 대량 목록 | pagination과 server filter를 우선 | virtualizer/data-grid facade | +| 이미지 전송량 | width/height, lazy loading, responsive source 규칙 | Image CDN URL builder adapter | +| 재방문/offline | HTTP cache contract | Service Worker/IndexedDB adapter | +| 불필요한 render | 상태 소유권 축소와 component boundary | 보통 adapter가 아니며 측정 후 memoization | + +기본 skeleton은 bundle budget, lazy route, query cancellation/cache, responsive +image 규칙, stable layout, lab performance test를 제공한다. Web Worker, +virtualization, Image CDN, Service Worker는 실제 병목과 제품 요구가 확인될 때 +설치한다. 라이브러리를 미리 많이 넣는 것은 최적화가 아니라 초기 번들·공급망 +표면을 늘리는 일이 될 수 있다. + +## 6. 질문별 직접 답변 + +### 프론트도 inbound/outbound로 나누는가 + +나눈다. 현재 구조에서는 `presentation`이 사실상 inbound adapter이고 +`src/adapters`가 outbound adapter다. 이름과 문서가 이 역할을 명확히 드러내지 +않아 모두 같은 adapter처럼 보인 것이다. + +| 역할 | 프론트 예 | +| --- | --- | +| input/inbound port | `ListResources`, `CreateResource` 같은 application API | +| inbound adapter | React page/controller, router, form event, push-event translator | +| output/outbound port | resource gateway, session, storage, clock, diagnostics | +| outbound adapter | HTTP, auth SDK, browser storage, TanStack cache, telemetry sink | + +React, router, form library, icon library마다 application port를 만들 필요는 없다. +UI 내부 교체만 필요한 라이브러리는 React inbound adapter 내부 vendor facade로 +충분하다. port는 application 정책과 외부 소유권 사이의 경계에 둔다. + +### 왜 현재 모두 `adapters` 아래에 있는가 + +실제로 모두 있지는 않다. UI driver가 `presentation`이라는 이름으로 분리돼 있고, +`adapters`에는 주로 outbound 구현이 있다. 다만 다음 두 대안 중 하나를 명시적으로 +선택해야 한다. + +1. 변경량을 줄여 `presentation = inbound adapter`로 문서화하고 + `adapters/outbound`만 명시한다. +2. TypeScript/feature migration과 함께 `adapters/inbound/react`와 + `adapters/outbound`로 재구성한다. + +이 저장소는 input API 부재와 flat contracts 문제도 함께 고쳐야 하므로 두 번째 +구조가 장기적으로 더 명확하다. 단, 대규모 rename 자체를 기능 개선으로 세지 말고 +architecture gate와 수직 reference feature가 먼저 또는 같은 브랜치에서 +증명되어야 한다. + +### TypeScript로 바꾸는 것이 좋은가 + +좋다. 특히 registry ID, Result/error union, port generic, route params/search, +component variant를 컴파일 시점에 닫을 수 있다. 다만 일괄 rename은 권장하지 +않는다. tooling → core contracts → application ports/use cases → outbound → +bootstrap → React TSX → tests 순서로 이동한다. + +### store 기본 설정이 필요한가 + +상태 전략은 기본 제공해야 하지만 범용 global store dependency는 필수로 넣지 +않는다. + +- local interaction: `useState`/`useReducer` +- shareable navigation state: URL +- server state: TanStack Query +- form state: form facade +- low-frequency cross-cutting state: context 또는 typed external store +- complex cross-feature workflow: Zustand/Redux Toolkit/state machine 중 선택 +- persistence: `StoragePort` + +서버 데이터를 global store에 복사하지 않는 규칙이 중요하다. +[TanStack Query](https://tanstack.com/query/latest/docs/framework/react/overview), +[Redux Toolkit](https://redux-toolkit.js.org/introduction/getting-started), +[Zustand](https://zustand.docs.pmnd.rs/)의 역할은 서로 같지 않다. + +### retry, API client, logger, token manager, error, validation은 어디에 있는가 + +- retry: `src/adapters/http/retry-policy.js`, 부분 준비 +- API client: `src/adapters/http/client.js`, 부분 준비 +- logger: 없음. telemetry와 분리하거나 diagnostics port로 합치는 결정 필요 +- token manager: 의도적으로 없음. opaque external auth owner가 credential을 소유 +- error: `src/contracts/errors.js`와 HTTP normalization, 부분 준비 +- validation: runtime/API Zod는 존재, route/form/domain 분리는 미완성 + +token manager를 기본으로 추가하지 않는 이유는 token lifecycle이 인증 방식마다 +다르고 localStorage token을 일반 해법으로 만들면 보안 위험이 커지기 때문이다. +BFF HttpOnly cookie 또는 OIDC/Auth SDK가 credential을 소유하도록 두고, SPA +memory token이 필요한 프로젝트만 auth adapter를 추가한다. + +### Lucide React를 쓰면 디자인 시스템이 되는가 + +아니다. [Lucide React](https://lucide.dev/guide/packages/lucide-react)는 +tree-shakable SVG icon source로 적절하지만 select, dialog, menu, focus management +같은 UI behavior는 제공하지 않는다. Lucide는 local icon facade 뒤에 두고, +복잡한 interaction은 [Radix Primitives](https://www.radix-ui.com/primitives/docs/overview/introduction) +또는 React Aria 계열과 같은 headless primitive를 owned wrapper 뒤에서 선택한다. + +### 테스트는 현재 어떤 상태인가 + +테스트 도구 구성은 강한 편이다. 다만 다음이 빠져 있다. + +- TS source와 test 전체 typecheck +- 실제 composition root부터 page까지의 통합 +- query/mutation controller와 optimistic rollback +- route registry/runtime map 정합성 +- runtime timeout/retry와 path/query/parsed body +- shared MSW scenario catalog +- isolated component stories와 interaction test +- stable-environment visual regression +- built `dist` 대상 release E2E +- 위험 기반 coverage gate + +### 라우팅 전략은 무엇이 적절한가 + +현재 client-only clean architecture와 TanStack Query 조합은 유지하되, 목표 +skeleton은 React Router Data Mode의 route object, blocker, scroll restoration, +route error 경계를 사용한다. 서버 상태의 소유자는 계속 application input과 +TanStack Query이며 loader/action이 같은 데이터를 별도로 요청하지 않는다. +[React Router 공식 mode 설명](https://reactrouter.com/start/modes)에 따라 +Framework Mode는 SSR/static generation, route module, framework-owned data +loading을 실제 요구할 때만 선택한다. + +### 바로 쓸 수 있는 디자인 패턴은 무엇을 제공해야 하는가 + +패턴 이름만 나열하지 않고 다음 executable blueprint를 제공해야 한다. + +- page controller: route/form event를 application input으로 변환 +- query/mutation adapter: server state lifecycle을 React에 연결 +- command/query use case: 읽기와 상태 변경 의도를 분리 +- gateway: application이 외부 데이터 소유자를 추상화 +- mapper/anti-corruption layer: transport DTO를 core model로 변환 +- Result + failure mapper: throw와 사용자 메시지 경계를 통제 +- strategy: retry, cache, auth recovery, feature flag 정책 교체 +- observer/external store: session/theme/realtime 구독 +- state machine: 복잡한 workflow에만 선택적으로 사용 +- compound component/headless wrapper: 접근 가능한 복합 UI를 소유 +- page template: layout과 상태 표면을 데이터 소유권에서 분리 + +## 7. 실전 투입 준비 완료 기준 + +막연한 백분율 대신 아래 조건을 모두 자동 또는 명시적 검토로 확인한다. + +1. reference feature가 route → controller → input use case → output gateway → + adapter → mapper → query cache → UI 상태 표면을 통과한다. +2. application input API 외에는 UI에서 outbound dependency에 접근할 수 없다. +3. TypeScript source와 tests가 strict 검사되고 JS 우회 경로가 없다. +4. HTTP path/query/body/auth/timeout/retry/cancel/decode 실패가 계약 테스트된다. +5. typed route registry와 runtime map이 양방향 완전성을 가진다. +6. list/detail/form/status page template과 form error 정책이 준비돼 있다. +7. 디자인 시스템 primitive/pattern이 isolated workshop, interaction, a11y, + visual test를 가진다. +8. sample/reference feature 전체 삭제 후 typecheck/test/build가 통과한다. +9. optional adapter는 설치 조건, 보안 경계, 실패 정책, 테스트 recipe가 있다. +10. 새 feature 추가 문서가 파일 경로, 금지 의존, 실패 상태, 테스트, 검증 명령까지 + 안내한다. + +이 기준은 배포 provider, 실제 인증 tenant, 운영 telemetry vendor, production field +data 같은 프로젝트별 외부 작업을 포함하지 않는다. + +## 8. 관련 상세 문서 + +- [프론트 포트·어댑터와 기능 경계](./frontend-ports-adapters-and-boundaries.md) +- [TypeScript·상태·데이터 흐름](./typescript-state-and-data-flow.md) +- [라우팅·페이지·재사용 패턴](./routing-pages-and-patterns.md) +- [프론트 플랫폼 구현 로드맵](./frontend-platform-implementation-roadmap.md) +- [디자인 시스템 플랫폼](../styling/design-system-platform.md) +- [프론트 플랫폼 테스트 전략](../testing/frontend-platform-testing-strategy.md) diff --git a/docs/architecture/frontend-platform-implementation-roadmap.md b/docs/architecture/frontend-platform-implementation-roadmap.md new file mode 100644 index 00000000..5423921a --- /dev/null +++ b/docs/architecture/frontend-platform-implementation-roadmap.md @@ -0,0 +1,954 @@ +# 프론트엔드 플랫폼 구현 로드맵 + +## 1. 목적과 준비 완료의 의미 + +이 문서는 `develop`의 `cb195f8`을 계획 기준선으로 삼아, 현재 저장소에 선언된 +프론트엔드 계약을 실제 런타임과 자동 검증까지 연결하는 구현 순서를 정의한다. +기준 커밋은 출발점일 뿐이며 각 구현 브랜치는 직전 브랜치가 병합된 최신 +`develop`에서 시작한다. + +구현 단계는 다음처럼 구분한다. + +| 단계 | 목적 | exit 상태 | +| --- | --- | --- | +| P0 | 새 기능이 사용할 input/output, HTTP/query, route/recovery 수직 경로 완성 | `LOCAL_CORE_READY` | +| P1 | form/page/design/i18n, diagnostics, test, 공급망까지 템플릿 품질 완성 | `LOCAL_TEMPLATE_READY` | +| P2 | 실제 요구가 생겼을 때 선택할 adapter recipe 제공 | 선택 항목만 `RECIPE_READY` | + +P0와 P1은 사용자가 요청한 높은 수준의 저장소 내부 준비도를 판단하기 전에 모두 +끝내야 한다. 이를 정밀한 백분율 점수로 표현하지 않고 다음 세 조건으로 +판정한다. + +1. 계약과 레지스트리의 모든 필드에 실제 consumer가 있다. +2. 정상 경로와 실패 경로가 자동 테스트로 증명된다. +3. 각 변경이 독립적으로 되돌릴 수 있고 feature branch와 evidence가 보존된다. + +P2는 제품 번들에 모든 기술을 미리 넣는 단계가 아니다. 선택 조건, port/facade, +fake adapter, 실패 정책과 제거 절차를 준비하는 단계다. + +## 2. 명시적인 범위 밖 + +다음 항목은 저장소가 seam, fail-closed 기본값, 검증 명령과 증거 형식을 제공할 +수는 있지만 실제 완료는 외부 프로젝트 또는 운영 환경의 책임이다. + +- 실제 hosting/CDN의 atomic deploy, cache purge, 응답 헤더와 rollback 실행 +- 실제 OAuth/OIDC/기업 IdP tenant, client, redirect URI와 token lifecycle +- production telemetry, RUM, analytics, error-reporting vendor와 consent 정책 +- 실제 사용자에게서 수집한 28일 field Web Vitals와 최소 표본 결정 +- 저장소 호스팅 서비스의 required check, branch protection과 evidence retention +- 운영용 CSP allowlist, signing key, provenance attestation과 비밀 관리 +- 실제 브랜드, 업무 문구, 번역 승인, 지원 locale와 법적 고지 +- 도메인 API, 권한 모델, 제품별 form schema와 업무 규칙 +- 운영 release 승인 + +이 항목이 준비되지 않아도 demo, fake, no-op, unavailable adapter를 사용해 +P0/P1의 저장소 내부 구현과 테스트를 끝낼 수 있어야 한다. 반대로 외부 증거가 +없는데 `PRODUCTION_READY`, `WCAG_READY`, `FIELD_SLO_READY`를 주장해서는 안 된다. +상위 promotion gate는 임의의 값을 만들어 PASS하지 않고 `FAIL_UNVERIFIED`를 +유지한다. + +## 3. 공통 구현 원칙 + +- `.ts`나 `.tsx`를 만들기 전에 lint, architecture, registry, typecheck와 test + 검색 범위가 해당 확장자를 검사한다. +- React는 application input port를 호출하고, application은 output port만 안다. + 구체 adapter 조립은 bootstrap만 담당한다. +- route, API, error, query, storage, telemetry와 release registry는 문서용 목록이 + 아니라 실행과 검증의 단일 소스다. +- path, search, body, response와 external event는 경계에서 parse하며 parse된 + 결과를 다음 계층으로 전달한다. +- retry, cache, redirect, reload, submission과 redaction에는 각각 한 명확한 + 정책 소유자만 둔다. +- 정상 테스트와 함께 invalid import, schema, URL, mutation, chunk, secret 같은 + negative fixture가 실제 gate에 의해 거절돼야 한다. +- vendor SDK type과 import는 local facade/adapter 밖으로 노출하지 않는다. +- 선택 gate가 닫히지 않은 라이브러리는 lockfile에 추가하지 않는다. +- 대규모 rename과 여러 capability를 한 merge에 섞지 않는다. + +## 4. Gitflow 브랜치 보존 규칙 + +현재 저장소는 `main`과 `develop`을 사용하고 feature prefix가 비어 있다. 아래 +표의 `feature-...` 이름을 그대로 `git flow feature start`에 전달한다. + +```text +최신 develop 확인 + -> git flow feature start <정확한 feature-... 이름> + -> 작은 검증 가능한 commit + -> git flow feature publish <정확한 feature-... 이름> + -> 자동 gate와 review + -> develop에 --no-ff merge + -> develop과 feature branch를 모두 push + -> local/origin feature branch 보존 +``` + +`git flow feature finish`는 feature branch를 삭제할 수 있으므로 사용하지 않는다. +병합 후에도 로컬 브랜치와 `origin/feature-...`를 제거하지 않는다. merge commit +SHA, feature tip, 실행한 gate와 artifact 위치를 PR 또는 merge evidence에 +기록한다. + +후속 브랜치는 미병합 feature branch에서 시작하지 않는다. 선행 브랜치를 먼저 +`develop`에 병합하고 최신 `develop`에서 새 브랜치를 시작한다. 병합 순서를 +바꾸려면 dependency와 acceptance를 다시 검토해야 한다. + +rollback은 reset이나 branch 삭제로 수행하지 않는다. + +1. 관련 promotion을 중단한다. +2. 보존된 feature branch와 merge commit으로 정확한 변경 범위를 찾는다. +3. `develop`에서 별도 `hotfix/...` 또는 revert branch를 만든다. +4. `git revert -m 1 `으로 merge를 되돌린다. +5. rollback gate 후 revert branch와 원래 feature branch를 모두 보존한다. +6. 수정은 최신 `develop`에서 새 feature branch로 다시 진행한다. + +## 5. 12개 브랜치와 병합 순서 + +```mermaid +flowchart TD + B01["01 P0 TypeScript tooling"] + B02["02 P0 input/output boundary"] + B03["03 P0 HTTP and query"] + B04["04 P0 routing and recovery"] + B05["05 P0 reference feature"] + B06["06 P1 forms and pages"] + B07["07 P1 design system"] + B08["08 P1 i18n"] + B09["09 P1 diagnostics"] + B10["10 P1 tests and registry evidence"] + B11["11 P1 supply chain"] + B12["12 P2 optional recipes"] + + B01 --> B02 --> B03 --> B04 --> B05 + B05 --> B06 --> B07 --> B08 --> B09 --> B10 --> B11 + B11 -. "요구가 확인된 recipe만" .-> B12 +``` + +| 순서 | 보존할 Gitflow feature branch | 단계 | 직접 선행조건 | rollback point | +| --- | --- | --- | --- | --- | +| 01 | `feature-frontend-typescript-tooling-foundation` | P0 | 기준선, VD-01 | RP-01 | +| 02 | `feature-frontend-application-boundary-runtime` | P0 | 01 | RP-02 | +| 03 | `feature-frontend-http-query-contract-execution` | P0 | 02 | RP-03 | +| 04 | `feature-frontend-routing-release-recovery-runtime` | P0 | 03, VD-03 | RP-04 | +| 05 | `feature-frontend-reference-feature-vertical-slice` | P0 | 04 | RP-05 | +| 06 | `feature-frontend-form-page-platform` | P1 | 05, VD-04 | RP-06 | +| 07 | `feature-frontend-design-system-platform` | P1 | 06, VD-05 | RP-07 | +| 08 | `feature-frontend-i18n-message-formatting-contract` | P1 | 07, VD-06 | RP-08 | +| 09 | `feature-frontend-diagnostics-telemetry-runtime` | P1 | 08, VD-07 | RP-09 | +| 10 | `feature-frontend-test-registry-evidence-hardening` | P1 | 09, VD-08 | RP-10 | +| 11 | `feature-frontend-supply-chain-verification` | P1 | 10, VD-09 | RP-11 | +| 12 | `feature-frontend-optional-adapter-recipes` | P2 | 11, VD-10 | RP-12 | + +## 6. 브랜치별 구현과 acceptance + +### 01. `feature-frontend-typescript-tooling-foundation` + +**목표** + +점진적 TypeScript 전환 전에 JS, JSX, TS, TSX와 테스트가 모두 같은 정적 분석과 +CI gate를 통과하게 한다. 애플리케이션 전체를 일괄 변환하지 않는다. + +**선행조건과 decision** + +- 기준선의 `pnpm ci:gate` 결과를 보존한다. +- TypeScript compiler와 기존 dependency 버전은 별도 dependency review 없이는 + 변경하지 않는다. +- 공식 JavaScript migration 방식처럼 점진적으로 전환한다. + [TypeScript JavaScript migration](https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html) + +**구체 변경 범위** + +- root, application/source, tests용 TypeScript project/reference를 분리한다. +- `src`, `tests`, `scripts`의 허용 확장자와 build output 제외 범위를 명시한다. +- ESLint, dependency-cruiser, registry scanner와 architecture script의 JS-only + glob 및 `.js` 고정 경로를 JS/TS 양쪽으로 확장한다. +- Vite, Vitest와 Playwright config가 TS source/test 오류를 우회하지 않게 한다. +- 기존 JS에는 `checkJs`, 새 TS에는 strict 정책을 적용한다. +- port, registry와 forbidden import용 `.ts`/`.tsx` fixture를 추가한다. + +**자동 테스트와 negative test** + +- JS와 TS source/test를 함께 typecheck하는 smoke +- TSX presentation의 concrete HTTP adapter import를 architecture gate가 거절 +- 잘못된 port 구현과 discriminated union 사용이 typecheck 실패 +- TS registry row의 누락 필드, 중복 ID와 unknown reference가 gate 실패 +- 기존 JS invalid-call fixture도 계속 실패 +- `pnpm lint`, `pnpm check:types`, `pnpm check:architecture`, + `pnpm check:registries`, `pnpm test:all`, `pnpm build` + +**Acceptance** + +- 허용된 모든 source/test 확장자가 typecheck, lint, architecture, registry gate + 중 필요한 검색 범위에 포함된다. +- JS 안전망이 약해지지 않은 상태에서 TS fixture가 CI에 의해 차단된다. +- 광범위한 unchecked cast나 임시 `any`로 통과시키지 않는다. +- production source 대량 변환 없이 독립적으로 revert할 수 있다. + +**Rollback** + +RP-01에서 merge를 revert하면 기존 JS 기준선으로 돌아간다. 후속 TS 작업은 +RP-01이 복구될 때까지 병합하지 않는다. + +### 02. `feature-frontend-application-boundary-runtime` + +**목표** + +UI가 호출할 input port와 application이 외부에 요구할 output port를 분리하고, +composition root가 생성한 `Application`을 실제 React tree에 주입한다. + +**선행조건과 decision** + +- 01의 TS-aware architecture gate가 병합돼 있어야 한다. +- 범용 client store는 추가하지 않는다. local interaction은 React state, 공유 + navigation state는 URL, server state는 query adapter가 소유한다. +- 실제 IdP 없이 demo/external/unavailable session adapter를 유지한다. + +**구체 변경 범위** + +- application input API를 query/command use case 중심으로 정의한다. +- gateway, session, cache, storage, clock, diagnostics와 release capability를 + output port로 분류한다. +- `createApplication`이 raw adapter를 다시 노출하지 않고 input API만 반환한다. +- `ApplicationProvider`와 `useApplication` 역할의 inbound React adapter를 둔다. +- bootstrap이 concrete output adapter를 선택하고 application을 router/page에 + 전달한다. +- presentation의 fetch, browser storage, concrete QueryClient와 outbound adapter + 직접 접근을 금지한다. +- inbound/outbound ownership을 architecture gate와 type fixture에 반영한다. + +**자동 테스트와 negative test** + +- fake output ports를 이용한 application use-case 단위 테스트 +- runtime config → composition root → provider → smoke page 통합 테스트 +- presentation의 `adapters/outbound`, `fetch`, concrete QueryClient import 거절 +- application의 React, router, browser storage, vendor SDK import 거절 +- 잘못된 output port 구현과 누락 input이 typecheck 실패 +- bootstrap 이외 계층의 concrete adapter 조립 거절 + +**Acceptance** + +- visible page가 raw outbound dependency 대신 application input API를 사용한다. +- 조립됐지만 사용되지 않는 application, HTTP와 release-info 객체가 없다. +- fake adapter만으로 application과 presentation의 정상·실패 경로를 테스트한다. +- vendor type이 application public API에 나타나지 않는다. + +**Rollback** + +RP-02는 기존 provider wiring을 한 merge로 되돌릴 수 있어야 한다. 임시 +compatibility wrapper는 05 reference feature 완료 전에 제거한다. + +### 03. `feature-frontend-http-query-contract-execution` + +**목표** + +API operation registry의 path/search/body/schema/timeout/retry가 실제 요청에 +반영되게 하고, TanStack Query를 application input과 React 사이의 제한된 inbound +adapter로 연결한다. + +**선행조건과 decision** + +- 02의 application error와 gateway 경계가 고정돼 있어야 한다. +- shared HTTP가 network retry를 소유하고 query adapter의 중복 retry는 끈다. + 다른 결정을 원하면 이 브랜치 전에 ADR을 남긴다. +- TanStack Query를 server-state adapter로 유지하되 Zustand/Redux Toolkit에 + server state를 복사하지 않는다. + +**구체 변경 범위** + +- request input을 operation/route ID, path params, search params, body, signal과 + idempotency key로 분리한다. +- operation registry에서 method, path, request/response schema, timeout과 retry + eligibility를 찾는다. +- deterministic path/search builder를 만들고 parse/transform된 query/body를 + 실제 URL/payload에 사용한다. +- runtime config의 timeout과 max attempts를 client factory에 주입한다. +- abort, timeout, retry delay와 listener cleanup을 injectable clock/scheduler + 경계로 통제한다. +- TanStack import를 허용할 local query adapter 경계를 하나만 둔다. +- `useApplicationQuery`, `useApplicationMutation` 역할의 controller API를 + 정의하고 query key, cancellation, invalidation과 optimistic rollback을 + 연결한다. +- base state를 loading/success/empty/terminal로, overlay를 + refreshing/stale-degraded/pending/conflict로 닫는다. +- refreshing/stale 및 pending/conflict의 배타성과 stale-failure latch를 + 명시적으로 구현한다. +- stale retry, duplicate-submit 방지와 conflict action을 실제 callback에 + 연결한다. + +**자동 테스트와 negative test** + +- path escaping, optional/array search, stable ordering 및 query key/request URL 일치 +- query/body transform 결과 전송, invalid input에서 `fetch` 0회 +- runtime timeout과 max attempts 0/1/N의 실제 호출 횟수 +- validation 실패, abort, success, exhausted retry의 timer/listener cleanup +- caller abort와 timeout의 서로 다른 typed failure +- unsafe mutation, non-retryable status와 schema failure retry 0회 +- 네 base state, 네 overlay와 허용 transition +- refreshing 실패의 stale latch 및 성공/재시도 후 해제 +- pending/conflict 동시 상태 fixture 거절 +- duplicate submit 1회, optimistic success/rejection rollback/conflict resolution +- unmount/navigation abort가 terminal error로 오인되지 않음 +- local adapter 밖의 `@tanstack/**` import 거절 + +**Acceptance** + +- cache key에 포함된 request 입력이 실제 URL/body에서도 동일하게 사용된다. +- runtime timeout/retry 설정이 실제 동작을 바꾼다. +- 모든 종료 경로의 cleanup과 한계 횟수를 fake clock으로 결정적으로 증명한다. +- QueryClientProvider가 단순 마운트 객체가 아니며 reference controller가 사용할 + 표준 API를 제공한다. +- `AsyncSurface`의 모든 action이 실제 command와 검증된 state transition을 가진다. + +**Rollback** + +RP-03은 application port를 유지하면서 이전 HTTP compatibility adapter 또는 +imperative controller로 되돌릴 수 있어야 한다. request builder와 query adapter +commit을 구분해 부분 revert가 가능하게 한다. + +### 04. `feature-frontend-routing-release-recovery-runtime` + +**목표** + +route registry를 executable router의 단일 계약으로 만들고 params/search/access/ +surface/chunk metadata를 route flow에 연결한다. lazy chunk 실패도 release +manifest와 bounded recovery에 실제 연결한다. + +**선행조건과 decision** + +- 03의 controller가 parsed route input을 받을 수 있어야 한다. +- VD-03 기본값은 React Router Data Mode다. route object, blocker, scroll + restoration과 route error 경계를 사용하되 server state는 application input과 + TanStack Query가 계속 소유한다. + [React Router modes](https://reactrouter.com/start/modes), + [Data Mode custom setup](https://reactrouter.com/start/data/custom) +- 고정된 `7.18.1` API로 전환하고 router version upgrade는 별도 dependency + 브랜치로 분리한다. +- 실제 hosting cache/purge는 범위 밖이며 test manifest server/browser adapter를 + 사용한다. + +**구체 변경 범위** + +- 직렬화 가능한 route contract와 component/codec runtime map을 분리한다. +- route ID의 contract/runtime 양방향 완전성을 TypeScript와 registry gate로 + 검사한다. +- registry에서 route objects, navigation, access hint, title, loading/error + surface와 chunk ID를 조립한다. +- params/search를 application 호출 전에 Zod codec으로 parse하고 URL builder도 + 같은 codec을 사용한다. +- unknown/authentication-required/forbidden/not-found/error surface의 소유자를 + 하나씩 정한다. +- route change의 boundary reset, document title, main focus와 scroll 정책을 + 적용한다. +- redirect-loop guard와 최대 hop을 실제 자동 redirect flow에 연결한다. +- build의 Vite asset manifest와 route chunk ID를 release manifest의 검증 가능한 + map으로 연결하고 `runtime-config.schema.json`을 artifact로 생성한다. +- config/release/build/asset mismatch 오류 kind를 정확히 나눈다. +- lazy rejection → no-store manifest refetch → active build/release pair 비교 → + guarded reload 1회 → 반복 실패 support/rollback surface를 연결한다. +- 일반 render error는 chunk reload 경로에 들어가지 않고 local reset을 유지한다. +- `FeatureBoundary`, `ReleaseInfoPort`와 chunk recovery controller를 production + call graph에 연결한다. + +**자동 테스트와 negative test** + +- registry row 추가 시 route tree/navigation 동시 추가 +- runtime 누락/orphan, duplicate path/ID, unknown schema/surface/chunk 거절 +- invalid params/search, unknown route와 access rejection에서 application/API 0회 +- URL parse/build round-trip과 canonical search +- redirect cycle이 최대 hop에서 종료 +- route 전환 후 error reset, main heading focus와 중복 surface 없음 +- stale chunk + manifest mismatch에서 no-store refetch 후 reload 정확히 1회 +- 같은 build/release pair의 두 번째 실패에서 reload 0회와 support surface +- manifest malformed/offline/storage unavailable의 fail-closed 동작 +- 일반 component throw가 chunk failure로 오분류되지 않음 +- build/config/release/asset mismatch의 정확한 error kind +- built `dist`의 route chunk map, runtime schema와 release artifact set 검증 + +**Acceptance** + +- 수동 route 열거와 registry가 서로 어긋날 수 없다. +- route metadata 중 consumer 없는 token이 0개다. +- invalid/unknown/access-rejected URL에서 product API 0회를 증명한다. +- chunk recovery 결정이 production call graph에 있으며 무한 reload가 불가능하다. +- 실제 CDN 없이 저장소 내부 recovery matrix가 결정적으로 통과한다. + +**Rollback** + +RP-04는 이전 수동 router와 generic route failure surface로 한 merge를 되돌릴 수 +있어야 한다. URL shape는 바꾸지 않으며 불가피한 변경은 compatibility redirect와 +migration이 있어야 한다. 실제 CDN purge는 rollback 범위에 포함하지 않는다. + +### 05. `feature-frontend-reference-feature-vertical-slice` + +**목표** + +route에서 실제 HTTP/query/application/presentation까지 연결되며 전체를 제거해도 +generic platform이 정상 부팅되는 하나의 reference feature를 만든다. + +**선행조건과 decision** + +- 01~04가 모두 병합돼 있어야 한다. +- 실제 backend와 IdP 대신 MSW/fake gateway와 demo auth를 사용한다. +- reference 업무 용어를 제품 도메인 계약으로 승격하지 않는다. + +**구체 변경 범위** + +- 흩어진 sample route, operation, schema, mapper, domain, query key, controller, + page와 tests를 canonical `src/features/reference-feature` 한 ownership 경계로 + 이동한다. +- feature 내부에 domain, application input/output, outbound gateway, DTO/schema, + mapper, query/mutation controller와 presentation page를 둔다. +- list filter가 URL codec, query key와 실제 HTTP request에 동일하게 반영된다. +- safe mutation으로 pending, duplicate prevention, optimistic state, conflict와 + rollback을 보여 준다. +- registry/application에는 removable contribution contract를 사용하고 generic + source에는 fixture-specific ID를 하드코딩하지 않는다. +- production bootstrap과 같은 composition 경로에 fake adapter를 주입한다. +- `src/features/reference-feature` 전체를 제거한 ephemeral copy에서 + typecheck/test/build/home smoke를 실행하도록 sample-removal gate를 다시 + 작성한다. + +**자동 테스트와 negative test** + +- bootstrap → router → controller → input use case → gateway → HTTP/MSW → + response schema → mapper → cache → page의 수직 통합 +- loading/success/empty/terminal/refreshing/stale/pending/conflict/recovery UI +- invalid search에서 gateway/fetch 0회 +- invalid DTO가 domain/view model로 전파되지 않음 +- backend forbidden을 client access hint와 무관하게 최종 반영 +- duplicate/unsafe mutation 전송 횟수 +- `src/features/reference-feature` 삭제 후 typecheck, architecture, registry, + unit/integration, home smoke와 build +- 삭제 후 sample route 부재와 `src`/`tests`의 fixture-specific ID 잔여 0개 +- generic home/examples route가 sample 없이 계속 작동 + +**Acceptance** + +- static page와 분리된 fixture가 아니라 실제 수직 경로 하나가 존재한다. +- reference feature를 삭제할 때 central registry를 수작업으로 수정하는 숨은 + 단계가 없거나 제거 명령이 이를 결정적으로 수행한다. +- feature 존재/제거 두 모드에서 P0 gate가 모두 통과한다. +- 01~04를 함께 revert해야만 sample을 제거할 수 있는 숨은 결합이 없다. + +**Rollback** + +RP-05는 P0 최종 지점이다. reference feature merge만 revert해도 generic platform은 +정상이어야 한다. + +## 7. P0 exit gate + +- JS/TS source와 tests가 동일한 정적 gate에 포함된다. +- UI는 application input API만 호출하고 concrete outbound adapter를 모른다. +- HTTP path/search/body/auth/timeout/retry/cancel/decode가 실행 계약과 일치한다. +- query/mutation controller와 모든 async state transition이 작동한다. +- route registry/runtime map과 route chunk map이 양방향 완전성을 가진다. +- lazy chunk failure가 bounded release recovery에 연결된다. +- reference feature가 실제 수직 경로를 실행하고 전체 삭제 gate를 통과한다. +- `pnpm ci:gate`와 P0에서 추가한 모든 negative fixture가 통과한다. + +위 조건이 모두 충족돼야 `LOCAL_CORE_READY`다. RP-05 증거를 보존한 뒤 P1을 +시작한다. + +## 8. P1 브랜치 + +### 06. `feature-frontend-form-page-platform` + +**목표** + +Zod schema와 application command를 연결하는 form controller 및 +standard/collection/detail/form/status page template를 제공한다. + +**선행조건과 decision** + +- 05의 mutation과 async state가 실제 reference flow에서 작동해야 한다. +- VD-04에서 React Hook Form + Zod resolver 사용 여부를 정한다. 복합 form 요구가 + 확정되면 local facade 뒤에 추가하고, 거절되면 native form + local controller가 + 같은 public API와 tests를 충족한다. + [React Hook Form resolvers](https://github.com/react-hook-form/resolvers), + [Zod](https://zod.dev/) +- vendor 결정 전에 dependency/lockfile을 변경하지 않는다. + +**구체 변경 범위** + +- presentation form schema와 domain invariant를 분리한다. +- field registration, parse/error map, dirty/touched/reset/pending/result를 local + form API로 감싼다. +- `422` field/form/unknown-server-field/global error mapping을 정의한다. +- 첫 오류 focus, error summary, field ID와 live-region을 연결한다. +- duplicate submit, cancel/leave와 unsaved-change 정책을 적용한다. +- `StandardPage`, `CollectionPage`, `DetailPage`, `FormPage`, `StatusPage`의 slot + 계약을 정의한다. +- heading, breadcrumb, actions, filters, content, aside와 feedback의 소유 위치를 + 표준화한다. +- reference list/detail/create-edit/status page를 controller와 template로 + 전환한다. +- template가 application use case나 query vendor를 직접 선택하지 않게 한다. + +**자동 테스트와 negative test** + +- client validation 실패에서 command 0회와 첫 invalid field focus +- transformed/defaulted data가 command에 전달됨 +- field/form/unknown server error와 conflict 후 입력 보존 +- pending 중 연속 submit에도 command 1회 +- reset 후 dirty 해제와 navigation confirmation/focus restore +- secret-like input이 URL/storage/log/telemetry에 나타나면 실패 +- 각 template의 최소/전체 slot 및 async/error variation +- 320px, zoom, 긴 heading/action과 wide layout +- heading/landmark/accessibility-name/axe +- template가 application/HTTP/query vendor를 import하면 gate 실패 +- action callback 없이 활성 버튼을 렌더링하면 실패 + +**Acceptance** + +- form engine을 바꿔도 page와 application API가 변하지 않는다. +- multi-field form의 validation/pending/dirty/422/conflict가 실행된다. +- 새 feature가 layout CSS를 복사하지 않고 다섯 page 유형을 조립한다. +- template는 layout/state slot만 소유하고 데이터 정책은 소유하지 않는다. + +**Rollback** + +RP-06은 기존 reference controls/layout으로 돌아가도 controller/application +경계가 유지돼야 한다. vendor adapter, form contract와 template commit을 구분해 +부분 revert가 가능하게 한다. + +### 07. `feature-frontend-design-system-platform` + +**목표** + +기존 theme와 primitive를 token → primitive → pattern → template 계층으로 +확장하고, 모바일 drawer와 복합 interaction을 접근 가능한 local API로 제공한다. + +**선행조건과 decision** + +- 06의 page/form에서 반복되는 실제 token/primitive 요구를 수집한다. +- VD-05에서 icon source와 headless interaction 방식을 결정한다. +- Lucide를 선택하면 static named import만 local icon facade에서 허용한다. + [Lucide React](https://lucide.dev/guide/react), + [Lucide accessibility](https://lucide.dev/guide/react/advanced/accessibility) +- headless vendor가 미결정이면 native dialog/disclosure/control 범위만 완료하며, + 미지원 widget을 임의 구현해 완료로 표시하지 않는다. + +**구체 변경 범위** + +- primitive/semantic/component token을 분리한다. +- color, typography, spacing, size, radius, elevation, z-layer, motion, breakpoint와 + opacity 계약을 정의한다. +- light/dark/system, forced-colors와 reduced-motion을 닫는다. +- design-system public entry와 deep-import 금지 규칙을 만든다. +- 기존 Button/TextField/Card/Alert/Badge/Dialog를 호환 가능한 public API로 + 이동한다. +- LinkButton/IconButton/Field/TextArea/Select/Checkbox/RadioGroup/Switch/ + Spinner/Skeleton/VisuallyHidden을 기본 제공한다. +- Drawer/Popover/Tooltip/Menu/Tabs/Breadcrumbs/Pagination/Toast/ProgressBar 및 + 필요한 focus/portal utility를 추가한다. +- 모바일 navigation을 Drawer로 전환해 focus 이동, modal/background 정책, + Escape/scrim/link dismiss와 trigger focus restore를 구현한다. +- 앱 셸의 문자 glyph/raw control을 local icon/primitive로 교체한다. +- `/examples/ui`와 `/examples/states`에서 interactive state를 실제 동작으로 + 노출한다. + +**자동 테스트와 negative test** + +- 필수 semantic token의 light/dark/forced-colors 정의 +- undefined CSS variable/raw palette 사용 거절 +- interactive icon의 accessible name 누락 거절, decorative icon tree 제외 +- product code의 direct icon/headless vendor 또는 deep import 거절 +- disabled/pending/focus/invalid와 reduced-motion/theme persistence +- keyboard-only open/move/select/dismiss/focus restore +- Drawer open 시 background interaction 차단과 compact reflow +- Menu/Tabs arrow key, typeahead와 activation 정책 +- Tooltip만으로 필수 정보를 제공하는 fixture 거절 +- Toast queue 상한/duplicate collapse/timeout pause +- Chromium/Firefox/WebKit component/E2E/axe + +**Acceptance** + +- shell, templates와 reference feature가 public design-system API를 사용한다. +- product code의 raw palette, vendor icon/headless import가 0개다. +- mobile navigation이 검증된 focus/dismiss contract를 따른다. +- gallery action이 handler 없는 장식이 아니라 실행 가능한 상태를 시연한다. +- token 누락과 접근 불가능한 interaction을 자동 gate가 차단한다. + +**Rollback** + +RP-07은 compatibility export로 기존 primitive import를 복구할 수 있어야 한다. +token rename은 alias/migration 기간을 두고, vendor adapter와 local API commit을 +분리한다. + +### 08. `feature-frontend-i18n-message-formatting-contract` + +**목표** + +사용자 문구, 날짜, 숫자, 상대 시간과 direction을 typed message/formatter 경계로 +옮겨 특정 언어 literal과 locale 가정을 공통 UI에서 제거한다. + +**선행조건과 decision** + +- 07까지의 common user-facing string 목록이 확보돼 있어야 한다. +- VD-06 기본값은 browser `Intl` + typed local catalog다. extraction/plural 등 + 요구가 이를 넘을 때만 vendor를 선택한다. +- 실제 번역 승인과 지원 locale은 외부 프로젝트 범위다. + +**구체 변경 범위** + +- typed message key와 interpolation parameter 계약을 정의한다. +- locale provider, fallback locale, direction과 date/number/relative-time + formatter를 제공한다. +- shell, route, async/form error와 design-system 기본 copy를 catalog로 이동한다. +- backend raw message를 번역 key로 신뢰하지 않고 error registry로 매핑한다. +- pseudo-locale와 RTL smoke locale을 테스트 전용으로 제공한다. +- unknown key/locale, formatter failure와 missing interpolation의 fallback을 + 정의한다. + +**자동 테스트와 negative test** + +- 모든 등록 locale의 key parity와 interpolation 정합성 +- unknown locale/key에서 raw key/stack을 노출하지 않는 fallback +- pseudo-locale 확장에 대한 layout/reflow +- RTL shell/drawer/breadcrumb와 directional icon +- 날짜/숫자/timezone의 결정적 test +- untrusted HTML interpolation 및 backend message 직접 렌더링 거절 +- common UI의 금지된 hardcoded user-facing literal 검출 + +**Acceptance** + +- shell/state/form/error copy가 typed catalog를 통과한다. +- pseudo-locale와 RTL E2E가 통과한다. +- 실제 제품 번역 없이도 locale 교체 지점과 실패 정책이 검증된다. +- key rename에는 compatibility alias 또는 migration이 있다. + +**Rollback** + +RP-08은 기존 기본 언어 catalog를 fallback으로 유지한다. 번역 catalog를 +파괴적으로 덮어쓰지 않는다. + +### 09. `feature-frontend-diagnostics-telemetry-runtime` + +**목표** + +structured diagnostics와 telemetry를 구분하고 boot, HTTP, cache, storage, route, +render와 release 사건을 실제 producer에 연결한다. + +**선행조건과 decision** + +- route/HTTP/query/form/release failure kind가 안정돼 있어야 한다. +- VD-07에서 외부 exporter를 선택하지 않아도 된다. no-op 또는 기존 + best-effort HTTP sink를 기본으로 하고 실제 vendor SDK는 외부 adapter다. + +**구체 변경 범위** + +- diagnostics/logger output port와 telemetry event port의 책임을 분리한다. +- level, event ID, timestamp, correlation/request/route/release context와 redaction + 정책을 정의한다. +- `app.boot.failed`, `api.request.failed`, `ui.render.failed`, + `release.mismatch.detected`, `telemetry.delivery.dropped`를 production path에 + 연결한다. +- retry attempt마다 terminal failure를 중복 발행하지 않고 bounded summary만 + 남긴다. +- route/path/query/body/error에서 고카디널리티와 민감 값을 제거한다. +- queue 상한, drop reason bucket, sink failure와 nonrecursive fallback을 + 구현한다. +- reference feature에서 route → application → HTTP outcome correlation을 + 증명한다. + +**자동 테스트와 negative test** + +- registry event가 production path에서 필요한 횟수만 발행 +- success/retry recovery/terminal failure event 차이 +- Authorization/cookie/token/raw form/body/PII-like fixture redaction +- large/circular/unknown error에서도 serializer가 throw하지 않음 +- queue full/sink failure가 app failure나 재귀 폭주를 만들지 않음 +- unknown/high-cardinality event context 거절 +- mount 전 boot failure도 안전한 evidence 생성 +- no-op adapter에서도 동일 application behavior + +**Acceptance** + +- 필수 telemetry event 중 producer 없는 항목이 0개다. +- sink/vendor가 없어도 기능이 정상이며 failure evidence가 제한된다. +- credential/raw user input이 queue, console과 artifact에 남지 않는다. +- exporter wiring만 독립적으로 제거할 수 있다. + +**Rollback** + +RP-09는 exporter를 제거하고 즉시 no-op adapter로 전환할 수 있어야 한다. +diagnostics port와 redaction test는 유지한다. + +### 10. `feature-frontend-test-registry-evidence-hardening` + +**목표** + +registry의 구조/참조/consumer/호환성을 실제 diff로 검증하고, P0/P1 위험 경로를 +실제 bootstrap과 built artifact에서 증명한다. + +**선행조건과 decision** + +- 09까지의 public contract와 registry field가 안정돼 있어야 한다. +- VD-08 기본값은 dev-only Storybook workshop과 local Playwright visual + baseline이다. cloud review service는 선택이다. +- `/examples/ui`, `/examples/states`는 실제 앱 composition의 통합 smoke로 + 유지하며 isolated story의 SSOT를 대신하지 않는다. + [Storybook documentation](https://storybook.js.org/docs) + +**구체 변경 범위** + +- route/API/schema/error/query/storage/telemetry/config/release registry의 field + type/enum/unique/cross-reference/consumer/orphan을 machine-readable하게 검사한다. +- 직전 승인 snapshot과 현재 snapshot의 actual diff로 additive/behavioral/ + breaking/removal을 계산한다. +- breaking에는 version bump, migration, compatibility window와 rollback + evidence를 요구한다. +- hardcoded `current: additive`, empty high-risk review와 self-asserted PASS를 + 제거한다. +- source와 tests를 모두 포함하는 TypeScript check를 CI 필수 gate로 만든다. +- MSW handler를 operation/schema 기반 shared scenario catalog로 통합한다. +- 실제 `main` composition과 built `dist`의 integration/release E2E를 추가한다. +- Playwright compact/mobile project와 risk-based coverage threshold를 추가한다. +- deterministic clock/random/fetch/storage helper, unexpected console/unhandled + rejection 실패 정책을 제공한다. +- 선택된 workshop interaction 또는 안정 환경의 visual baseline을 추가한다. +- JUnit/screenshot/trace/evidence naming과 CI gate registry를 맞춘다. + +**자동 테스트와 negative test** + +- duplicate ID/path, invalid enum/type, missing field/reference와 orphan 거절 +- actual removal/type narrowing/path change를 additive로 표시하면 실패 +- breaking diff의 version/migration/rollback 누락 실패 +- ordering-only diff는 semantic change가 아님 +- 승인 baseline digest 변조 실패 +- unexpected network/operation, provider 누락과 unhandled error 실패 +- critical policy coverage threshold 미달 실패 +- built artifact의 source map, config schema 누락과 broken chunk 실패 +- compact viewport와 Chromium/Firefox/WebKit navigation/a11y smoke +- reference feature 제거 모드의 generic E2E/build +- screenshot mask가 전체 UI를 가려 false PASS를 만들면 실패 + +**Acceptance** + +- route 선언/실행 불일치와 telemetry producer 누락을 registry gate가 잡는다. +- compatibility impact가 하드코딩 상수가 아니라 actual diff다. +- 테스트가 source module만이 아니라 real composition과 `dist`를 증명한다. +- 모든 P0/P1 high-risk policy에 negative fixture가 하나 이상 있다. +- CI artifact로 browser/release/fixture 실패를 재현할 수 있다. + +**Rollback** + +RP-10은 직전 승인 registry snapshot과 test evidence다. flaky visual/browser +infrastructure commit은 product behavior와 분리한다. 장기 skip으로 PASS하지 않고 +owner와 만료 시한이 있는 quarantine만 허용한다. + +### 11. `feature-frontend-supply-chain-verification` + +**목표** + +직접·전이 dependency, vulnerability, license, secret, SBOM/inventory와 provenance를 +검증 가능한 release gate로 만든다. + +**선행조건과 decision** + +- 10까지 최종 build/test dependency 구조가 안정돼 있어야 한다. +- VD-09에서 vulnerability source, license policy, SBOM format과 attestation + provider를 선택한다. +- provider가 미결정이면 임의 PASS를 만들지 않고 promotion을 + `FAIL_UNVERIFIED`로 유지한다. local inventory/fixture 검증은 완료할 수 있다. + +**구체 변경 범위** + +- frozen lockfile에서 direct/transitive dependency inventory를 생성한다. +- name/version, direct/transitive, resolved integrity와 license를 deterministic하게 + 기록한다. +- actual baseline/lockfile diff에서 new/removed/changed dependency와 + reviewer-required risk를 계산한다. +- secret scan 범위를 source/dist/tracked config/generated manifest와 artifact + metadata에 맞게 확장한다. +- 선택된 vulnerability/license adapter가 severity, exception owner/expiry를 + machine-readable evidence로 남기게 한다. +- SBOM 또는 동등 inventory, build digest와 provenance statement를 coherent + release artifact set에 연결한다. +- frozen install과 동일 source/lock/config의 reproducible build를 검증한다. + +**자동 테스트와 negative test** + +- transitive dependency inventory 누락 실패 +- lockfile integrity/digest 변조와 unfrozen install 실패 +- high-risk dependency의 self-approval 실패 +- 금지 license, threshold vulnerability와 만료 exception 실패 +- source/dist/config secret fixture 검출 및 test-secret allowlist 통제 +- SBOM/inventory와 release manifest digest 불일치 실패 +- provenance subject와 artifact digest 불일치 실패 +- dependency ordering만 달라도 deterministic output 유지 + +**Acceptance** + +- dependency diff와 high-risk review가 하드코딩 빈 배열이 아니다. +- transitive inventory, license와 vulnerability 결과가 release evidence에 + 포함된다. +- provider/organization decision이 없으면 상위 promotion이 명시적으로 + `FAIL_UNVERIFIED`다. +- 위험 dependency upgrade만 독립적으로 revert할 수 있다. + +**Rollback** + +RP-11은 P1 최종 저장소 기준선이다. scanner outage를 무검증 승인으로 우회하지 +않고 promotion을 보류한다. + +## 9. P1 exit gate + +- 현실적인 form의 validation/dirty/pending/422/conflict가 작동한다. +- collection/detail/form/status를 포함한 page template가 reference feature에서 + 사용된다. +- token → primitive → pattern → template 경계가 자동 보호된다. +- compact navigation과 interaction의 keyboard/focus 계약이 검증된다. +- typed message, pseudo-locale와 RTL smoke가 존재한다. +- 필수 telemetry event가 실제 producer에 연결되고 secret/PII가 redaction된다. +- registry/compatibility가 actual diff와 cross-reference로 검증된다. +- bootstrap과 built `dist`를 포함한 risk-based test/evidence가 남는다. +- transitive dependency, vulnerability, license와 local SBOM가 선택된 정책에 + 따라 검증된다. 외부 signing/provenance provider가 미결정이면 해당 promotion만 + `FAIL_UNVERIFIED`다. +- 현재 merge gate가 요구하는 등록 route의 signed manual accessibility evidence가 + 갱신된다. +- P0/P1 feature branch와 merge evidence가 local/origin에 모두 보존된다. + +위 조건이 모두 충족되면 `LOCAL_TEMPLATE_READY`다. 실제 hosting, IdP, +production sink와 field data 없이도 저장소 내부 상태는 달성할 수 있지만, 외부 +gate 없이는 production promotion을 통과했다고 보지 않는다. + +## 10. P2 브랜치 + +### 12. `feature-frontend-optional-adapter-recipes` + +**목표** + +모든 프로젝트에 dependency를 미리 설치하지 않고, 실제 요구가 확인된 capability의 +선택 기준, port/facade, fake adapter, failure policy와 test recipe를 제공한다. + +**선행조건과 decision** + +- P0/P1 public boundary가 안정돼 있어야 한다. +- VD-10에서 실제 소비 요구, owner, 보안 영향, bundle 예산과 제거 조건이 + 승인된 recipe만 구현한다. +- 승인되지 않은 recipe의 runtime dependency는 추가하지 않는다. + +**구체 변경 범위** + +| recipe | 기본 경계 | 반드시 다룰 실패 | +| --- | --- | --- | +| realtime | subscribe/unsubscribe, reconnect, resume, heartbeat | disconnect, duplicate/out-of-order, auth expiry | +| offline/IndexedDB | versioned repository와 migration | quota, corruption, migration rollback | +| Service Worker/PWA | cache ownership와 update controller | stale worker, update loop, offline fallback | +| file transfer | upload/download, progress, cancel | size/type rejection, abort, expired URL | +| generated API | generated client를 gateway 뒤에 감싸는 facade | contract drift, unsupported field | +| feature flag | typed key, default와 stale policy | provider unavailable, unknown flag | +| Web Worker | request/result/cancel protocol | crash, stale result, transfer failure | +| multi-tab | versioned BroadcastChannel event | self-echo, duplicate, conflict | +| browser permission | clipboard/notification/media result port | denied, dismissed, unsupported | +| client workflow | Zustand/Redux Toolkit/state-machine local facade | reset, mismatch, server-state duplication | +| large data UI | virtualizer/data-grid facade | focus loss, stale row, scale limit | +| analytics/error sink | consent/redaction/sampling adapter | denied consent, queue full, unavailable | + +- 각 recipe에 설치/금지 조건, ownership, security/privacy, bundle 영향, fallback과 + 제거 절차를 기록한다. +- runnable fixture는 production entry에서 제외한 opt-in example/test entry에 + 둔다. +- Zustand와 Redux Toolkit을 동시에 기본 설치하지 않는다. +- browser가 DB/object store에 직접 접속하는 recipe는 만들지 않고 권한 있는 + backend/BFF protocol adapter를 사용한다. + +**자동 테스트와 negative test** + +- 선택 recipe의 fake adapter contract 및 unavailable fallback +- unsubscribe/cancel/cleanup 누락 fixture 실패 +- local adapter 밖의 vendor SDK direct import 실패 +- credential을 localStorage/telemetry/URL에 저장하는 fixture 실패 +- server state를 client workflow store에 복제하는 fixture 실패 +- recipe 제거 후 base typecheck/test/build 통과 +- opt-in하지 않은 recipe가 production bundle에 없음을 검증 + +**Acceptance** + +- 선택 capability는 port/facade, fake adapter, failure matrix, tests와 제거 + 절차를 가진다. +- 선택하지 않은 capability는 dependency와 production code를 늘리지 않는다. +- recipe 하나의 도입/제거가 다른 recipe와 P0/P1 runtime을 변경하지 않는다. + +**Rollback** + +RP-12는 recipe별 merge commit이다. optional adapter 문제 시 해당 recipe commit만 +revert하고 RP-11을 유지한다. 여러 vendor를 되돌릴 수 없는 한 commit에 묶지 +않는다. + +## 11. Vendor decision gate + +| ID | 시점 | 결정 | 기본값 또는 미결정 시 처리 | 차단 범위 | +| --- | --- | --- | --- | --- | +| VD-01 | 01 전 | TypeScript migration 범위와 compiler 변경 | 기존 compiler 고정, tooling-first 점진 전환 | compiler upgrade와 source 변환 | +| VD-02 | 02 전 | 범용 client store | 추가하지 않음. local/URL/query/context 사용 | 실제 cross-feature workflow만 | +| VD-03 | 04 전 | React Router mode | Data Mode; server state는 TanStack/application 유지 | Framework/SSR 전환만 | +| VD-04 | 06 전 | form engine | 복합 form이면 RHF+Zod facade, 아니면 local/native | form 구현체 | +| VD-05 | 07 전 | icon/headless UI | local facade, native 우선; 미지원 behavior는 미완료 | icon/복합 primitive | +| VD-06 | 08 전 | i18n engine | `Intl` + typed local catalog | extraction/plural 고급 기능 | +| VD-07 | 09 전 | diagnostics/telemetry exporter | no-op/best-effort HTTP | production sink만 | +| VD-08 | 10 전 | Storybook/visual 방식 | dev-only Storybook + local Playwright baseline | cloud review/별도 배포 | +| VD-09 | 11 전 | vulnerability/license/SBOM/provenance | 임의 PASS 금지, `FAIL_UNVERIFIED` | release promotion | +| VD-10 | 12 전 | optional capability 요구 | 설치하지 않음 | 해당 recipe만 | + +각 decision에는 실제 요구, bundle/runtime/a11y/security 영향, local facade 방식, +대안, fallback/migration/removal, owner와 재검토 시점을 기록한다. + +결정이 지연될 때 vendor-neutral port와 no-op/fake/unavailable adapter를 먼저 +완성한다. 다만 vendor가 있어야 충족되는 behavior를 구현하지 않은 채 완료로 +표시해서는 안 된다. + +## 12. Rollback과 promotion + +| checkpoint | 포함 범위 | 다음 단계 진입 조건 | 대표 rollback 사유 | +| --- | --- | --- | --- | +| RP-01 | tooling | TS/JS fixture와 gate 통과 | TS 파일이 검사에서 누락 | +| RP-02 | application boundary | composition integration 통과 | UI가 raw adapter에 의존 | +| RP-03 | HTTP/query | request/state negative matrix 통과 | query 손실, retry/submit 폭주 | +| RP-04 | routing/recovery | registry와 reload-loop drill 통과 | invalid URL API 호출, reload loop | +| RP-05 | P0 reference | feature 존재/제거 gate 통과 | hidden sample coupling | +| RP-06 | form/page | form/page/a11y gate 통과 | 입력 손실, template 결합 | +| RP-07 | design system | token/interaction gate 통과 | focus/theme/vendor 회귀 | +| RP-08 | i18n | catalog/pseudo/RTL gate 통과 | missing key, locale 회귀 | +| RP-09 | diagnostics | producer/redaction gate 통과 | PII 노출, event 폭주 | +| RP-10 | test/registry | actual diff와 evidence gate 통과 | false PASS, flaky blocker | +| RP-11 | P1 supply chain | `LOCAL_TEMPLATE_READY` | 위험 dependency/검증 공백 | +| RP-12 | optional recipe | recipe별 opt-in gate | vendor 격리 실패 | + +```text +RP-05 + P0 exit + = LOCAL_CORE_READY + +RP-11 + P1 exit + = LOCAL_TEMPLATE_READY + +LOCAL_TEMPLATE_READY + + 실제 hosting/IdP/보안/접근성/운영 증거 + = PROJECT_INTEGRATION_READY + +PROJECT_INTEGRATION_READY + + production promotion과 eligible field data + = PRODUCTION/FIELD READY +``` + +저장소 내부와 외부 증거를 하나의 백분율로 숨기지 않는다. P0/P1의 모든 +acceptance가 자동 검증되고 외부 항목이 명확히 분리된 +`LOCAL_TEMPLATE_READY`를 높은 저장소 내부 준비도의 실질 기준으로 사용한다. + +## 13. 브랜치 공통 인수 체크리스트 + +각 feature branch는 병합 전에 다음을 evidence에 남긴다. + +- 목표와 변경하지 않는 범위 +- 시작한 `develop` SHA와 선행 merge SHA +- 변경한 public contract, registry와 compatibility 영향 +- positive/negative fixture +- 실행한 typecheck, lint, architecture, unit, integration, E2E와 build 명령 +- artifact와 browser/runtime 환경 +- dependency/lockfile 변경 및 vendor decision ID +- fake/no-op/unavailable adapter로 검증한 범위 +- external blocker와 `FAIL_UNVERIFIED` promotion +- merge commit과 보존된 local/origin feature tip +- rollback 대상 merge와 복구 확인 gate + +acceptance를 만족하지 못한 브랜치는 후속 브랜치의 기반으로 사용하지 않는다. +test를 skip하거나 문서상 예외로 바꾸는 것은 완료가 아니다. diff --git a/docs/architecture/frontend-ports-adapters-and-boundaries.md b/docs/architecture/frontend-ports-adapters-and-boundaries.md new file mode 100644 index 00000000..11c0c8d0 --- /dev/null +++ b/docs/architecture/frontend-ports-adapters-and-boundaries.md @@ -0,0 +1,1253 @@ +# 프론트엔드 포트·어댑터와 경계 설계 + +## 1. 문서 목적 + +이 문서는 이 저장소에서 도메인 기능을 추가할 때 사용할 경계와 확장 +절차를 정의한다. 다음 질문에 대한 단일 기준 문서다. + +- 프론트엔드에서 inbound와 outbound는 무엇인가? +- `presentation`은 왜 inbound adapter인가? +- application이 노출해야 할 API와 외부 기술 포트는 어떻게 다른가? +- React, Router, TanStack Query, HTTP, 인증, 저장소, 로깅을 어디에 + 배치하는가? +- 새 기술 adapter나 새 feature를 어떤 순서로 추가하는가? +- 예제 feature가 제품 코드에 남지 않았음을 어떻게 증명하는가? + +포트의 방향은 네트워크 패킷의 방향이 아니라 **application을 기준으로 +누가 누구를 호출하는지**로 결정한다. + +```text +사용자·브라우저 이벤트 + -> inbound adapter + -> input port + -> application use case + -> output port + -> outbound adapter + -> 외부 시스템 또는 브라우저 기능 +``` + +화살표는 런타임 호출 방향이다. 소스 의존성은 가능한 한 안쪽을 향한다. +구체 기술의 선택과 조립은 `bootstrap`에서만 수행한다. + +## 2. 핵심 용어 + +### 2.1 Input port + +외부가 application에 요청할 수 있는 작업의 계약이다. 사용자의 의도를 +나타내며 기술 이름 대신 업무 동사를 사용한다. + +예: + +- `ListReferenceItems` +- `CreateReferenceItem` +- `BeginSignIn` +- `ChangeColorScheme` +- `RecoverSession` + +Input port는 React hook, HTTP request, router loader 자체가 아니다. React나 +router가 없어도 테스트할 수 있는 함수 또는 인터페이스여야 한다. + +### 2.2 Inbound adapter + +사용자 입력이나 외부 이벤트를 input port 호출로 변환한다. 현재 저장소의 +`src/presentation`은 이름에 `adapter`가 없지만 이 역할을 담당한다. + +대표적인 inbound adapter: + +- React page와 component +- React Router route, loader, action, guard +- form controller와 feature hook +- 키보드, pointer, browser lifecycle event handler +- WebSocket이나 Service Worker가 수신한 이벤트를 use case로 전달하는 + event handler + +### 2.3 Output port + +application이 작업을 완료하기 위해 외부에 요구하는 capability 계약이다. +application이 소유하고 outbound adapter가 구현한다. + +대표적인 output port: + +- 도메인별 gateway 또는 repository +- session gateway +- clock, ID generator +- preference persistence +- logger, telemetry, error reporter +- feature flag reader + +Output port에는 `fetch`, `localStorage`, 특정 SDK 객체처럼 기술 구현이 +드러나지 않아야 한다. + +### 2.4 Outbound adapter + +output port를 실제 기술로 구현한다. + +대표적인 outbound adapter: + +- Fetch 기반 API gateway +- 외부 인증 SDK session gateway +- `localStorage`, `sessionStorage`, IndexedDB persistence +- telemetry 또는 error-reporting sink +- browser clock, random, crypto UUID +- feature flag SDK + +### 2.5 Bootstrap + +구체 구현을 선택하고 연결하는 composition root다. bootstrap만 다음 +결정을 알고 있어야 한다. + +- 어떤 HTTP transport를 사용할지 +- 어떤 인증 owner를 연결할지 +- 어떤 logger와 telemetry sink를 사용할지 +- QueryClient 설정은 무엇인지 +- 어떤 input port 구현을 `ApplicationProvider`에 공급할지 + +bootstrap은 page별 orchestration이나 업무 규칙을 소유하지 않는다. + +## 3. 현재 저장소의 구조 해석 + +현재 구조는 다음과 같이 해석한다. + +| 현재 경로 | 현재 역할 | 목표 역할 | +| --- | --- | --- | +| `src/domain` | 순수 model과 invariant | framework-neutral domain | +| `src/application` | port, policy, 일부 use case와 view model | input/output port와 use case | +| `src/presentation` | React UI, route, provider, 상태 화면 | inbound React adapter | +| `src/adapters` | HTTP, auth, storage, cache, telemetry 구현 | outbound adapter | +| `src/bootstrap` | runtime config와 구현 조립 | 유일한 composition root | +| `src/contracts` | 여러 계층의 registry가 혼재 | 소유 계층으로 분산 | +| `src/sample` | 제거 가능한 예제 일부 | 완전한 removable reference feature | + +현재 구조가 잘 제공하는 기반은 다음과 같다. + +- bootstrap 이전 runtime config와 release 검증 +- 인증 credential을 UI에 노출하지 않는 session seam +- bounded retry와 idempotency 정책 +- HTTP envelope 및 payload runtime validation +- 저장소 key registry와 민감정보 저장 금지 +- TanStack Query client 기본 정책 +- semantic telemetry allowlist +- render boundary와 async state surface +- route registry와 lazy page + +그러나 현재 실행 경로에는 다음 불일치가 있다. + +1. `src/bootstrap/composition-root.js`가 `application`을 만들지만 + `src/bootstrap/main.jsx`는 이를 사용하지 않고 `authSession`, + `storage`, `telemetry`를 presentation에 직접 전달한다. +2. `createApplication`이 input use case 대신 cache, storage, telemetry + output port를 그대로 노출한다. +3. `QueryClientProvider`는 존재하지만 실제 product route에서 + `useQuery` 또는 `useMutation`을 연결하는 query bridge가 없다. +4. route registry의 `paramsSchema`, `searchSchema`, `loadingSurface`, + `errorSurface`, `chunkId` 일부는 실행 route와 연결되지 않았다. +5. 제거 테스트는 `src/sample/contract-fixture`만 제거하며, sample API + operation, Zod schema, mapper, domain model과 query key는 다른 경로에 + 남는다. +6. runtime의 `REQUEST_TIMEOUT_MS`, `MAX_RETRY_ATTEMPTS`는 검증되지만 + concrete HTTP client 구성에 전달되지 않는다. + +이 문서의 목표 구조는 기존 기반을 폐기하는 것이 아니라 이러한 +불일치를 제거하는 것이다. + +## 4. Inbound와 outbound 분류표 + +| 관심사 | 방향 | Port 소유자 | Adapter 예 | 기본 제공 여부 | +| --- | --- | --- | --- | --- | +| React page와 component | inbound | application input API 소비 | React | 필수 | +| Routing과 navigation | inbound | route input/controller | React Router | 필수 | +| Form submit과 validation 표시 | inbound | command input port 소비 | React form controller | 필수 | +| Server-state query hook | inbound bridge | application input API 소비 | TanStack Query hook | 필수 | +| 외부 push event 처리 | inbound | event input port | WebSocket/SSE listener | 선택 | +| 도메인 API 접근 | outbound | application | Fetch gateway | 필수 | +| 인증 session | outbound | application | 외부 auth owner/SDK | 필수 seam | +| Credential attachment | outbound | transport 또는 auth integration | auth request decorator | 필수 seam | +| Preference persistence | outbound | application | browser storage | 필수 | +| 시간·ID·random | outbound | application | browser platform | 필수 | +| Logging·telemetry | outbound | application | console/remote sink | 필수 | +| Offline persistence | outbound | application | IndexedDB | 선택 | +| Feature flag | outbound | application | flag SDK | 선택 | +| Locale/message/formatter | UI platform | React inbound 계약 | `Intl` + local catalog | 필수 seam, vendor 선택 | +| 외부 오류 수집 | outbound | application | error-reporting SDK | 선택 | + +WebSocket은 한 단어로 항상 inbound 또는 outbound가 아니다. 연결을 열고 +메시지를 전송하는 기능은 application이 요구하는 output capability일 수 +있고, 수신된 메시지를 use case로 전달하는 handler는 inbound adapter다. +두 책임을 하나의 거대한 interface로 합치지 않는다. + +## 5. 왜 `presentation`이 inbound adapter인가 + +React component는 사용자의 클릭, 입력, URL 이동을 해석한다. 그 결과를 +application input port가 이해하는 command나 query로 바꾸고, 반환된 +view state를 HTML로 표현한다. 이는 전형적인 driving/inbound adapter다. + +```text +Button click + -> React event handler + -> CreateReferenceItem command + -> CreateReferenceItem input port + -> use case +``` + +따라서 `presentation`이 adapter라는 사실은 이름에 `adapter`가 붙었는지와 +관계없다. 다음 두 구조 모두 가능하다. + +```text +src/presentation # presentation을 inbound로 문서화 +src/adapters/outbound +``` + +또는 더 명시적으로: + +```text +src/adapters/inbound/react +src/adapters/outbound +``` + +이 저장소의 장기 목표는 두 번째 구조다. 점진적 전환 중에는 +`presentation = inbound/react`로 동일하게 취급한다. + +Presentation이 inbound라는 이유로 모든 component가 use case interface를 +가져야 하는 것은 아니다. `Button`, `Card`, `Dialog` 같은 순수 UI primitive는 +입력 props와 DOM behavior만 소유한다. page, controller hook, route +loader/action처럼 application 작업을 시작하는 경계에서 input port를 +사용한다. + +## 6. 브라우저가 서버 데이터 기술을 직접 연결하지 않는 이유 + +브라우저 adapter는 Redis, PostgreSQL, MongoDB, Kafka, MinIO 같은 서버 +인프라에 직접 연결하지 않는다. + +그 이유는 다음과 같다. + +- 브라우저 bundle과 runtime config는 사용자가 읽을 수 있어 서버 + credential을 안전하게 보관할 수 없다. +- 데이터베이스나 broker를 인터넷에 직접 노출하면 네트워크와 권한 경계가 + 무너진다. +- 브라우저는 신뢰할 수 없는 실행 환경이므로 authorization과 데이터 + invariant를 강제할 수 없다. +- DB driver, broker protocol, connection pool과 migration은 브라우저의 + lifecycle 및 bundle 제약과 맞지 않는다. +- 클라이언트 버전은 사용자마다 다를 수 있으므로 저장소 schema와 직접 + 결합하면 호환성 관리가 불가능해진다. + +브라우저는 HTTPS API, BFF, GraphQL, WebSocket 또는 SSE처럼 서버가 +노출한 제한된 계약과 통신한다. + +```text +Browser + -> HTTP/WebSocket adapter + -> Backend API/BFF + -> Redis/PostgreSQL/MongoDB/Kafka/MinIO +``` + +MinIO object URL을 받아 파일을 업로드하는 경우에도 브라우저 adapter는 +MinIO 관리자 credential이나 내부 API를 소유하지 않는다. 서버가 발급한 +짧은 수명의 제한된 URL과 업로드 정책만 사용한다. + +## 7. 권장 목표 디렉터리 구조 + +```text +src/ + core/ + kernel/ + result.ts + failure.ts + identifiers.ts + domain/ + application/ + ports/ + in/ + out/ + use-cases/ + policies/ + + adapters/ + inbound/ + react/ + app/ + application-provider.tsx + app-router.tsx + routing/ + query/ + pages/ + components/ + design-system/ + state/ + outbound/ + http/ + fetch-transport.ts + request-builder.ts + response-decoder.ts + retry-decorator.ts + auth/ + persistence/ + observability/ + platform/ + + features/ + reference-feature/ + domain/ + application/ + ports/ + in/ + out/ + use-cases/ + adapters/ + inbound/ + react/ + outbound/ + http/ + contracts/ + index.ts + + bootstrap/ + composition-root.ts + runtime-config.ts + main.tsx +``` + +`core`에는 모든 feature가 공유하는 작은 kernel과 truly cross-cutting +application capability만 둔다. `shared`, `common`, `utils` 같은 이름으로 +기술과 업무 규칙을 무제한 혼합하지 않는다. + +`features/reference-feature`는 구조를 설명하기 위한 완전한 수직 +슬라이스다. 이 폴더를 삭제하고 route 등록 한 곳만 제거했을 때 +typecheck, architecture check, test와 build가 모두 통과해야 한다. + +## 8. Input port 설계 규칙 + +### 8.1 사용자의 의도를 이름으로 표현한다 + +좋은 예: + +```ts +export interface ListReferenceItems { + execute( + query: ListReferenceItemsQuery, + context: RequestContext, + ): Promise>; +} +``` + +피해야 할 예: + +```ts +export interface HttpClient { + get(url: string): Promise; +} +``` + +Input port는 “HTTP GET을 실행한다”가 아니라 “항목을 조회한다”를 +표현한다. + +### 8.2 React와 browser type을 포함하지 않는다 + +Input port에 다음 type을 넣지 않는다. + +- `ReactNode`, `SyntheticEvent` +- `Request`, `Response`, `Headers` +- `QueryClient`, `UseQueryResult` +- `Location`, router navigate function +- `Storage`, `Window`, `Document` + +Inbound adapter가 해당 type을 application command와 query로 변환한다. + +### 8.3 예측 가능한 실패를 typed result로 반환한다 + +검증 실패, 인증 필요, conflict, network failure처럼 사용자 흐름에 +포함되는 실패는 `Result`로 반환한다. programmer error와 +불변식 위반을 모두 일반 API 실패로 숨기지는 않는다. + +```ts +export type Result = + | Readonly<{ ok: true; value: Value }> + | Readonly<{ ok: false; error: Failure }>; +``` + +### 8.4 Input port를 기술별로 합치지 않는다 + +`ApplicationService` 한 개에 모든 메서드를 계속 추가하지 않는다. +feature 단위 또는 응집된 capability 단위로 분리한다. + +```ts +export interface ReferenceFeatureApplication { + readonly list: ListReferenceItems; + readonly create: CreateReferenceItem; +} +``` + +## 9. Output port 설계 규칙 + +### 9.1 Application이 port를 소유한다 + +도메인별 gateway는 feature의 application 경로에 둔다. + +```ts +export interface ReferenceItemGateway { + list( + query: ListReferenceItemsQuery, + context: RequestContext, + ): Promise>; + + create( + command: CreateReferenceItemCommand, + context: RequestContext, + ): Promise>; +} +``` + +Fetch adapter는 이 interface를 구현하지만 application은 Fetch adapter를 +import하지 않는다. + +### 9.2 기술보다 capability를 표현한다 + +다음 이름을 우선한다. + +- `ReferenceItemGateway` +- `SessionGateway` +- `PreferenceStore` +- `Clock` +- `IdGenerator` +- `Logger` + +다음처럼 concrete 기술을 core port 이름에 포함하지 않는다. + +- `AxiosPort` +- `LocalStoragePort` +- `RedisPort` +- `TanStackPort` +- `SentryPort` + +### 9.3 Interface segregation을 지킨다 + +화면의 session 작업과 HTTP credential 부착은 호출 주체가 다르므로 +분리한다. + +```ts +export interface SessionGateway { + snapshot(): SessionSnapshot; + subscribe(listener: () => void): () => void; + beginSignIn(returnTo?: string): Promise; + signOut(): Promise; + recover(): Promise; +} + +export interface CredentialAttacher { + attach(request: Request): Promise; +} +``` + +`Request` type을 완전히 application 밖으로 유지하려면 +`CredentialAttacher`는 outbound HTTP 내부 계약으로 둔다. Session use +case는 `SessionGateway`만 안다. + +### 9.4 Clock과 ID도 concrete 구현과 분리한다 + +Application port 파일에 `Date.now`, `setTimeout`, `crypto.randomUUID` +구현을 함께 두지 않는다. + +```text +core/application/ports/out/clock.ts +adapters/outbound/platform/browser-clock.ts +adapters/outbound/platform/browser-id-generator.ts +``` + +### 9.5 범용 HTTP client를 application port로 노출하지 않는다 + +범용 transport는 outbound adapter 내부의 재사용 기술이다. 각 feature의 +gateway adapter가 transport를 사용해 DTO를 domain model로 매핑한다. + +```text +Application -> ReferenceItemGateway +ReferenceItemHttpGateway -> HttpTransport +HttpTransport -> fetch +``` + +이렇게 하면 application이 URL, method, header, response envelope를 알지 +않으며 API 기술을 교체할 수 있다. + +## 10. Composition root와 `ApplicationProvider` + +### 10.1 조립 순서 + +권장 조립 순서는 다음과 같다. + +```text +runtime config 검증 + -> release coherence 검증 + -> platform adapters 생성 + -> outbound gateways 생성 + -> use cases 생성 + -> application input API 생성 + -> React infrastructure provider 생성 + -> ApplicationProvider + -> Router +``` + +예: + +```ts +export function createApplicationComposition(runtime: RuntimeConfig) { + const clock = createBrowserClock(); + const logger = createRedactedLogger(runtime); + const sessionGateway = createExternalSessionGateway(runtime.auth); + const httpTransport = createHttpTransport({ + baseUrl: runtime.apiBaseUrl, + timeoutMs: runtime.requestTimeoutMs, + maxRetryAttempts: runtime.maxRetryAttempts, + logger, + }); + const referenceGateway = createReferenceItemHttpGateway(httpTransport); + + const reference = Object.freeze({ + list: createListReferenceItems({ gateway: referenceGateway, clock }), + create: createCreateReferenceItem({ gateway: referenceGateway, clock }), + }); + + const session = createSessionApplication({ gateway: sessionGateway, logger }); + + return Object.freeze({ + application: Object.freeze({ reference, session }), + infrastructure: Object.freeze({ + queryClient: createQueryClient(), + themeStorage: createThemeStorage(), + }), + }); +} +``` + +### 10.2 `ApplicationProvider`가 노출할 것 + +`ApplicationProvider`는 presentation이 호출할 input port만 노출한다. + +```ts +export interface ApplicationApi { + readonly reference: ReferenceFeatureApplication; + readonly session: SessionApplication; +} +``` + +다음 concrete 객체는 provider value에 넣지 않는다. + +- Fetch client +- raw HTTP client +- browser storage +- telemetry SDK +- auth SDK owner +- domain gateway adapter + +QueryClient처럼 React infrastructure provider가 직접 요구하는 concrete +객체는 bootstrap에서 해당 provider에 전달할 수 있다. 다만 feature page가 +QueryClient를 직접 가져가 application을 우회하지 않도록 query bridge를 +둔다. + +### 10.3 현재 runtime의 교정 목표 + +현재 `composition.application`이 만들어지고도 사용되지 않는 상태를 +허용하지 않는다. 다음 중 하나를 CI에서 검증한다. + +- `main`은 `composition.application`을 `ApplicationProvider`에 전달한다. +- presentation production source는 `composition.ports`나 concrete + outbound adapter를 import하거나 props로 받지 않는다. + +## 11. TanStack Query bridge + +TanStack Query는 두 역할을 가진다. + +1. QueryClient와 cache는 React 서버 상태 infrastructure다. +2. `useQuery`, `useMutation`은 React lifecycle을 application 호출에 + 연결하는 inbound bridge다. + +따라서 application이 TanStack type을 알면 안 되지만, inbound React +adapter 내부의 feature hook은 TanStack을 사용할 수 있다. + +```ts +export function useReferenceItems(query: ReferenceListQuery) { + const application = useApplication(); + + return useQuery({ + queryKey: referenceQueryKeys.list(query), + queryFn: async ({ signal }) => { + const result = await application.reference.list.execute(query, { + routeId: "REFERENCE_LIST", + operationId: "LIST_REFERENCE_ITEMS", + signal, + }); + + if (!result.ok) { + throw toQueryFailure(result.error); + } + return result.value; + }, + }); +} +``` + +Page는 `useQuery`를 직접 조합하지 않고 feature hook을 사용한다. + +```text +ReferenceListPage + -> useReferenceItems + -> ListReferenceItems input port + -> ReferenceItemGateway output port +``` + +Query bridge는 다음을 한곳에서 책임진다. + +- canonical query key +- AbortSignal 전달 +- application failure를 UI query failure로 투영 +- stale/refreshing 상태 변환 +- mutation 성공 후 namespace invalidation +- optimistic update와 rollback policy +- retry 소유권 + +HTTP transport가 retry를 소유하면 TanStack Query의 자동 retry는 기본적으로 +끄고, 두 계층에서 중복 retry하지 않는다. UI의 “다시 시도” 버튼은 새 +사용자 시도이며 transport의 자동 retry 횟수와 구분한다. + +Application이 실제로 cache 일관성 자체를 업무 규칙으로 요구하는 경우에만 +별도 `CachePort`를 둔다. 일반적인 server-state 표시를 위해 TanStack +Query의 모든 기능을 `read/write/invalidate` 세 메서드로 추상화하지 않는다. + +## 12. 상태 관리 경계 + +모든 상태를 한 global store에 넣지 않는다. + +| 상태 종류 | 기본 도구 | 저장 위치 | +| --- | --- | --- | +| 단일 component 표시 상태 | `useState`, `useReducer` | inbound React | +| URL과 공유 가능한 상태 | typed route params/search | router | +| 서버에서 소유한 상태 | TanStack Query bridge | inbound React infrastructure | +| session처럼 외부 store가 소유한 상태 | `useSyncExternalStore` | provider/bridge | +| theme 같은 작은 cross-page 설정 | context + preference port | provider/application | +| 복잡한 장기 client workflow | reducer 또는 state machine | feature application/inbound | +| 새로고침 후 유지할 공개 설정 | persistence output port | outbound persistence | + +Zustand, Redux Toolkit, Jotai, XState 등은 실제 상태 복잡성이 확인될 때 +선택한다. 기본 skeleton에는 상태 분류 규칙과 작은 typed external-store +예제가 필요하지만 범용 global store 의존성은 필수가 아니다. + +Global store를 도입할 때도 domain invariant를 selector와 action 내부에 +숨기지 않는다. 업무 규칙은 domain/application에 두고 store adapter는 +입력과 표시 상태를 연결한다. + +## 13. HTTP outbound adapter 계약 + +공통 HTTP transport가 지원해야 하는 최소 기능은 다음과 같다. + +- base URL과 상대 path의 안전한 결합 +- typed path parameter encoding +- canonical search parameter serialization +- parsed/normalized request body 전송 +- Content-Type과 response envelope 검증 +- operation별 auth 정책 +- runtime 기본 timeout과 operation override +- AbortSignal과 navigation cancellation +- safe/keyed/non-idempotent retry 구분 +- bounded exponential backoff와 `Retry-After` +- idempotency key의 logical request 단위 재사용 +- 401 recovery 1회 제한 +- request/trace ID의 안전한 투영 +- raw request/response/token을 버리는 error normalization +- terminal failure logging과 telemetry + +Operation registry는 문자열을 모아 둔 표가 아니라 TypeScript map으로 +요청과 응답 type을 연결해야 한다. + +```ts +interface ApiOperationMap { + LIST_REFERENCE_ITEMS: { + request: ListReferenceItemsRequest; + response: ReferenceItemListDto; + }; + CREATE_REFERENCE_ITEM: { + request: CreateReferenceItemRequest; + response: ReferenceItemDto; + }; +} +``` + +Zod 등 runtime schema가 반환한 `data`를 실제 request와 mapper 입력에 +사용한다. `safeParse` 성공 여부만 확인하고 원본 값을 계속 사용하지 않는다. + +## 14. 인증과 token 소유권 + +이 skeleton은 일반적인 browser token manager를 기본 제공하지 않는다. +이는 누락이 아니라 보안 기본값이다. + +권장 순서는 다음과 같다. + +1. 가능하면 BFF와 HttpOnly/Secure/SameSite cookie를 사용한다. +2. 외부 인증 SDK가 필요하면 SDK adapter가 token 획득, 갱신, 저장을 + 소유한다. +3. application과 presentation에는 credential이 아닌 session state와 + sign-in/sign-out use case만 노출한다. +4. HTTP adapter는 opaque credential attachment capability만 사용한다. +5. localStorage나 일반 application store에 access/refresh token을 넣지 + 않는다. + +SPA가 직접 bearer token을 사용해야 하는 프로젝트는 별도 보안 검토 후 +memory 중심 token owner adapter를 구현한다. 그 경우에도 이 저장소의 +`AUTH_TOKEN` storage 금지 계약을 우회하지 않는다. + +## 15. Error, validation, logger 경계 + +### 15.1 Error + +오류는 최소한 다음 경계를 거친다. + +```text +unknown thrown value + -> outbound adapter normalization + -> typed application failure + -> query/controller projection + -> localized safe user message +``` + +UI에는 다음을 전달하지 않는다. + +- raw stack +- backend message/details +- request/response body +- authorization header +- raw URL과 query +- storage value + +### 15.2 Validation + +Validation은 목적별로 분리한다. + +| 위치 | 검증 대상 | +| --- | --- | +| bootstrap | runtime config, release manifest | +| route inbound adapter | params와 search | +| form/controller | 사용자 입력과 field feedback | +| outbound API adapter | request DTO와 response DTO | +| domain | invariant와 value object | + +Form schema와 API request schema가 같은 모양이어도 역할이 다르므로 +무조건 하나로 합치지 않는다. 필요한 경우 application command로 +명시적으로 변환한다. + +### 15.3 Logger와 telemetry + +Logger와 telemetry는 같은 것이 아니다. + +- Logger: 운영 진단을 위한 level 기반 structured record +- Telemetry: registry에 정의된 semantic event와 metric +- Error reporter: 예외 집계와 release correlation + +기본 `Logger` output port는 safe context만 받는다. + +```ts +export interface Logger { + debug(message: string, context?: SafeLogContext): void; + info(message: string, context?: SafeLogContext): void; + warn(message: string, context?: SafeLogContext): void; + error(message: string, context?: SafeLogContext): void; +} +``` + +개발 환경에는 redacted console adapter, production에는 allowlist 기반 +remote adapter, 테스트에는 recording 또는 no-op adapter를 연결한다. +민감정보 redaction은 각 호출자의 선의가 아니라 adapter와 contract에서 +강제한다. + +## 16. Feature 경계와 removable reference feature + +Reference feature는 단순 UI fixture가 아니라 다음 경로를 모두 실행해야 +한다. + +```text +registered route + -> lazy page + -> controller/query bridge + -> application input port + -> use case + -> output gateway port + -> HTTP adapter + -> request schema + -> response schema + -> DTO mapper + -> domain model + -> view model + -> loading/empty/success/error UI +``` + +Reference feature 폴더가 소유해야 할 항목: + +- domain model과 value object +- input/output port +- use case +- API operation과 DTO schema +- HTTP gateway와 mapper +- query key와 query/mutation bridge +- route page와 feature component +- unit/component/integration/E2E test + +공통 registry가 필요한 경우 reference feature가 registration object를 +export하고 bootstrap 또는 route composition이 이를 수집한다. sample +operation을 전역 core registry 안에 하드코딩하지 않는다. + +제거 테스트는 다음을 수행해야 한다. + +1. `src/features/reference-feature` 전체 삭제 +2. reference route registration 삭제 +3. reference test 삭제 또는 제외 +4. 잔여 import와 registry owner 검색 +5. typecheck +6. architecture check +7. production build +8. built asset에서 reference operation/schema 문자열 부재 확인 + +제품 feature는 reference feature를 import할 수 없다. Reference feature도 +제품에서만 존재하는 feature를 import하지 않는다. + +## 17. 필수 adapter catalog + +| Adapter | 책임 | 기본 구현 | +| --- | --- | --- | +| Runtime config loader | public runtime config fetch와 검증 | Fetch + Zod | +| Release manifest loader | build/release coherence 확인 | Fetch + Zod | +| Browser clock | 현재 시간과 abortable sleep | browser timer | +| ID generator | idempotency/correlation용 opaque ID | `crypto.randomUUID` | +| HTTP transport | request, timeout, retry, decode | Fetch | +| Domain API gateway | DTO와 domain 변환 | feature HTTP gateway | +| Session gateway | session snapshot와 login lifecycle | external owner | +| Credential attacher | opaque request credential 처리 | auth owner | +| Preference store | 공개 preference persistence | browser storage | +| Query infrastructure | server-state cache 정책 | TanStack Query | +| Query bridge | input port와 React query 연결 | feature hook | +| Logger | redacted structured diagnostics | console/no-op/remote | +| Telemetry | allowlist semantic event 전달 | best-effort sink | +| Browser lifecycle | visibility/pagehide/online 상태 | browser event adapter | +| Router | URL을 page/controller로 변환 | React Router | +| Design system | 접근 가능한 primitive와 token | React/CSS | +| Locale/formatter | message key와 날짜·숫자·방향성 | local locale facade | +| UI workshop/visual gate | 격리 상태·interaction·회귀 검증 | Storybook + local Playwright | + +필수라는 의미는 모든 concrete library를 고정한다는 뜻이 아니다. 해당 +capability의 기본 정책, port 또는 안전한 no-op 구현과 composition +위치가 정의되어 있어야 한다는 뜻이다. + +## 18. 선택 adapter catalog + +| Adapter | 도입 조건 | 기본 상태 | +| --- | --- | --- | +| WebSocket/SSE | 실시간 server event 필요 | 미설치 recipe | +| IndexedDB | 큰 offline data 또는 durable queue 필요 | 미설치 recipe | +| Service Worker/PWA | offline shell과 installability 필요 | 미설치 recipe | +| Offline mutation queue | 재연결 후 명령 재처리 필요 | 미설치 recipe | +| Feature flag | remote rollout/kill switch 필요 | 미설치 recipe | +| Translation catalog vendor | 원격 catalog·복수 namespace 운영 필요 | 기본 locale facade 뒤에 미설치 | +| Analytics | 사용자 동의 기반 product analytics 필요 | 미설치 recipe | +| Error-reporting SDK | 운영 예외 집계 필요 | 미설치 recipe | +| OpenTelemetry | 조직 trace 연계 필요 | 미설치 recipe | +| Web Worker | CPU 작업이 main thread를 막음 | 미설치 recipe | +| Notification | 사용자 권한 기반 browser notification 필요 | 미설치 recipe | +| Clipboard/File/Media | 해당 browser capability 필요 | 미설치 recipe | +| Image CDN adapter | responsive image transform 필요 | 미설치 recipe | +| Virtualization | 대량 list rendering이 측정상 병목 | 미설치 recipe | +| OpenAPI generator | backend 계약에서 client 생성 필요 | 미설치 recipe | +| Zustand/Redux/Jotai | 복잡한 cross-page client state 확인 | 미설치 recipe | +| XState 등 state machine | 장기 workflow 상태 전이가 복잡함 | 미설치 recipe | +| Cloud visual-review service | 외부 승인·호스팅 workflow 필요 | 로컬 Storybook/visual gate 뒤에 미설치 | + +선택 adapter는 “나중에 쓸 수 있으므로” 기본 bundle에 넣지 않는다. 도입 +조건, 보안 영향, bundle 비용과 제거 방법이 확인된 경우에만 추가한다. + +## 19. 새 outbound adapter 추가 recipe + +### 단계 1: 해결할 문제를 capability로 정의한다 + +예: “LaunchDarkly를 붙인다”가 아니라 “feature flag를 평가한다”로 +정의한다. + +### 단계 2: Port가 정말 필요한지 판단한다 + +- application 정책이 이 capability를 호출하는가? +- React 화면 한 곳의 순수 표현 문제인가? +- 기존 port로 충분한가? +- 기술 교체와 테스트 격리가 실제로 필요한가? + +Application이 호출하지 않는 순수 UI library에는 억지 output port를 +만들지 않는다. + +### 단계 3: Application-owned output port를 작성한다 + +- 기술 중립 이름 +- 최소 메서드 +- typed input/output +- timeout/cancellation 필요 여부 +- 예측 가능한 failure union +- 민감정보 분류 + +### 단계 4: Contract와 정책을 작성한다 + +- runtime config +- retry/idempotency +- cache와 TTL +- fallback +- telemetry +- security/redaction +- browser compatibility + +### 단계 5: Concrete adapter를 구현한다 + +`src/adapters/outbound/` 또는 feature의 +`adapters/outbound`에 구현한다. Concrete SDK type은 이 경로 밖으로 +노출하지 않는다. + +### 단계 6: Composition root에서만 연결한다 + +Application이나 page에서 concrete constructor를 호출하지 않는다. + +### 단계 7: 테스트한다 + +- port contract test +- adapter unit test +- failure normalization +- timeout/cancellation +- redaction +- integration test +- deliberately failing negative fixture + +### 단계 8: 운영 계약을 갱신한다 + +- registry와 runtime schema +- dependency inventory +- bundle budget +- security policy +- runbook +- adapter catalog와 제거 절차 + +## 20. 새 inbound adapter 추가 recipe + +외부 이벤트를 application에 전달하는 adapter는 다음 순서를 따른다. + +1. 어떤 외부 event가 어떤 application 의도를 나타내는지 정의한다. +2. event payload를 runtime schema로 검증한다. +3. raw payload를 application command로 매핑한다. +4. input port를 호출한다. +5. duplicate, ordering, cancellation 정책을 정의한다. +6. 실패를 raw event source로 무한 재전파하지 않는다. +7. connect/disconnect lifecycle과 subscription cleanup을 테스트한다. + +예를 들어 WebSocket listener가 받은 JSON을 domain object로 바로 +사용하지 않는다. schema 검증과 command mapping 후 input port를 호출한다. + +## 21. 새 feature 추가 recipe + +### 단계 1: Feature 경계를 선언한다 + +- feature 이름과 owner +- 사용자 목표 +- route +- 입력 command/query +- 외부 gateway +- 성공/빈 화면/오류/권한 상태 + +### 단계 2: Domain을 작성한다 + +- entity/value object +- invariant +- 순수 policy +- framework와 transport type 금지 + +Domain 규칙이 없는 단순 표시 feature라면 빈 domain layer를 억지로 +만들지 않는다. + +### 단계 3: Input/output port와 use case를 작성한다 + +- input port는 사용자 의도 +- output port는 외부 capability +- `Result` failure 정의 +- cancellation context 정의 + +### 단계 4: Outbound gateway를 작성한다 + +- operation registration +- request DTO schema +- path/search/body mapping +- response DTO schema +- domain mapper +- error mapping + +### 단계 5: Inbound query/controller bridge를 작성한다 + +- canonical query key +- application input 호출 +- async state projection +- mutation invalidation 또는 optimistic rollback +- retry 버튼 behavior + +### 단계 6: Route를 등록한다 + +- route ID와 path +- typed params/search +- access hint +- lazy chunk +- loading/error surface +- title/navigation + +Registry metadata와 실제 route object를 별도로 두 번 작성하지 않는다. +하나의 typed definition에서 route object와 navigation을 생성한다. + +### 단계 7: Page와 상태를 조립한다 + +- page header와 focus 이동 +- loading +- empty +- success +- refreshing/stale +- terminal error +- 401/403/404 +- mutation pending/conflict +- responsive/keyboard/screen-reader + +### 단계 8: 테스트한다 + +- domain/use case unit +- port contract +- outbound adapter + MSW integration +- query/controller hook +- component +- route integration +- Playwright E2E +- axe와 수동 접근성 scope + +### 단계 9: 제거 가능성을 확인한다 + +Reference feature라면 전체 폴더 삭제 후 build가 통과해야 한다. 제품 +feature라면 다른 feature가 내부 구현 경로를 직접 import하지 않고 public +entry point만 사용해야 한다. + +## 22. Routing 규칙 + +Route definition은 다음 값을 type-safe하게 결합한다. + +- route ID +- path와 parameter type +- search schema와 normalized type +- access hint +- lazy component +- loading surface +- error boundary +- title +- navigation metadata +- prefetch policy + +Client route access는 UX 정책일 뿐 authorization이 아니다. 서버가 +최종 권한을 검증해야 한다. + +다음 규칙을 적용한다. + +- string path를 page에 하드코딩하지 않는다. +- URL search를 `Object.fromEntries` 결과 그대로 신뢰하지 않는다. +- route parameter를 domain ID로 사용하기 전에 검증한다. +- route 전환 시 진행 중 request에 AbortSignal을 전달한다. +- chunk load 실패는 release mismatch 정책에 따라 한 번만 복구한다. +- redirect loop guard는 실제 redirect 경로에 연결하거나 제거한다. +- browser-history routing을 사용하면 hosting의 SPA fallback을 release 계약으로 + 검증한다. + +## 23. Design system 경계 + +Design system은 inbound React adapter의 공유 UI capability다. + +최소 public surface: + +- semantic token +- typography와 spacing +- Button, IconButton +- TextField, TextArea, Select +- Checkbox, Radio, Switch +- Card, Alert, Badge +- Dialog, Drawer +- Loading, Empty, Error, Forbidden surface +- Tooltip, Tabs, Toast +- Table/List, Pagination +- Form field와 validation message + +Icon library는 design-system의 `Icon`과 `IconButton` 뒤에서 사용한다. +Page가 `lucide-react` 등 concrete icon package를 무제한 import하지 않도록 +허용 icon과 접근성 규칙을 한곳에서 관리한다. 정적 named import로 +tree-shaking을 유지하고 전체 icon registry를 runtime dynamic import하지 +않는다. + +Design system은 domain use case를 호출하지 않는다. Feature component가 +design-system primitive를 조합하고 controller hook을 통해 application을 +호출한다. + +## 24. 금지 패턴 + +다음 패턴은 architecture gate에서 차단해야 한다. + +### 경계 우회 + +- page가 `src/adapters/outbound`를 import +- presentation이 raw `fetch`, `localStorage`, auth SDK를 직접 사용 +- application이 React, Router, TanStack Query를 import +- domain이 application, browser global 또는 framework를 import +- bootstrap 외부에서 concrete adapter를 생성 +- `composition.ports`를 product presentation에 직접 전달 + +### Port 오용 + +- application port에 Axios, TanStack, SDK type 노출 +- input port 이름을 HTTP method나 UI event 이름으로 정의 +- 모든 capability를 하나의 `ApplicationService` 또는 `StorePort`로 합침 +- auth UI operation과 credential attachment를 하나의 과대 interface로 + 강제 +- application이 raw cache read/write를 page에 재노출 + +### HTTP와 retry + +- GET filter를 cache key에만 반영하고 request에서 누락 +- schema parse 결과를 버리고 원본 body 전송 +- keyed mutation retry 시 idempotency key 재생성 +- HTTP와 TanStack이 동시에 자동 retry +- navigation abort를 unknown error로 기록 +- validation early return에서 timeout/listener cleanup 누락 + +### 상태 + +- 서버 상태를 generic global store에 복제 +- URL에 있어야 할 filter를 별도 store에만 보관 +- token을 React state, persisted store, localStorage에 저장 +- domain invariant를 Zustand/Redux action 내부에만 구현 + +### 오류와 관측 + +- raw backend message 또는 stack을 사용자에게 표시 +- request/response body, raw URL, token을 logger/telemetry에 전달 +- `console.error`를 production error strategy로 간주 +- registry에 event만 선언하고 실제 발생 경로에서 emit하지 않음 + +### Registry와 예제 + +- route metadata를 선언하고 실제 route가 사용하지 않음 +- `contracts`를 모든 계층이 자유롭게 import하는 우회 폴더로 사용 +- product가 reference feature를 import +- reference feature를 삭제해도 sample domain/API schema가 초기 bundle에 + 남음 + +### 외부 인프라 + +- 브라우저에서 Redis, PostgreSQL, MongoDB, Kafka, MinIO 관리자 API에 + 직접 연결 +- server credential을 build/runtime config에 포함 +- 클라이언트 route guard를 authorization으로 간주 + +## 25. 테스트와 증적 기준 + +경계별 최소 테스트는 다음과 같다. + +| 대상 | 최소 검증 | +| --- | --- | +| Input use case | 성공, 각 failure branch, cancellation | +| Output port | contract fixture와 negative fixture | +| HTTP transport | path/query/body, timeout, retry, 401, abort, schema | +| DTO mapper | valid mapping과 invariant breach normalization | +| Query bridge | query key, loading, refresh, mutation invalidation, rollback | +| Route | registry-tree 일치, params/search, access, 404 | +| Provider | 실제 composition application 주입 | +| Logger/telemetry | allowlist, redaction, sink failure | +| Design system | keyboard, focus, label/error association, axe | +| Reference feature | full vertical integration과 complete removal | + +TypeScript 전환 후에는 source뿐 아니라 test와 architecture/security +fixture도 typecheck 또는 lint 대상이어야 한다. `.ts/.tsx`가 JS 전용 glob을 +우회하지 않도록 한다. + +Coverage는 단순 report 생성이 아니라 branch/function/line threshold를 +blocking gate로 둔다. 수치만 올리기 위한 구현 세부 테스트보다 port +contract와 실패 분기를 우선한다. + +## 26. 완료 기준 + +### 26.1 Architecture + +- [ ] 모든 application 작업에 명시적인 input port가 있다. +- [ ] 모든 외부 capability는 application-owned output port 뒤에 있다. +- [ ] Presentation은 concrete outbound adapter를 모른다. +- [ ] `main`은 raw ports 대신 application API를 제공한다. +- [ ] `contracts`는 unrestricted 우회 계층이 아니다. +- [ ] dependency rule과 문서의 source of truth가 하나다. +- [ ] TypeScript와 TSX도 동일한 architecture/security lint를 받는다. + +### 26.2 Runtime composition + +- [ ] runtime timeout/retry 설정이 실제 HTTP transport에 반영된다. +- [ ] QueryClient와 feature query bridge가 실제 route에서 동작한다. +- [ ] session UI API와 credential attachment가 분리되어 있다. +- [ ] logger와 telemetry가 HTTP/render/storage/cache failure 경로에 + 연결된다. +- [ ] page lifecycle에서 필요한 telemetry flush/cleanup이 수행된다. + +### 26.3 HTTP와 validation + +- [ ] path, search, body를 각각 검증하고 직렬화한다. +- [ ] schema가 반환한 normalized data를 실제 request에 사용한다. +- [ ] timeout과 AbortSignal listener가 모든 반환 경로에서 정리된다. +- [ ] retry는 runtime cap, idempotency와 `Retry-After`를 따른다. +- [ ] raw payload와 credential이 failure나 log에 포함되지 않는다. + +### 26.4 Routing과 상태 + +- [ ] route registry와 실행 route tree가 동일 source에서 생성된다. +- [ ] params/search schema가 실제 navigation에서 실행된다. +- [ ] loading/error/chunk/access metadata가 실행 behavior와 연결된다. +- [ ] local, URL, server, session, persisted state가 분류 규칙을 따른다. +- [ ] server state를 별도 global store에 중복 보관하지 않는다. + +### 26.5 Reference feature + +- [ ] route부터 API mapper와 화면까지 완전한 수직 경로가 실행된다. +- [ ] list/create 등 최소 query와 mutation 예제가 있다. +- [ ] loading/empty/error/refresh/conflict 상태가 있다. +- [ ] reference feature 전체 삭제 후 typecheck/test/build가 통과한다. +- [ ] built asset에 reference operation, schema, mapper가 남지 않는다. + +### 26.6 품질 + +- [ ] source와 test가 strict TypeScript 검사를 받는다. +- [ ] React Hooks와 JSX accessibility lint가 blocking이다. +- [ ] coverage threshold가 blocking이다. +- [ ] MSW integration, component, 3-engine E2E와 axe가 통과한다. +- [ ] bundle budget과 dependency inventory가 갱신된다. +- [ ] 선택 adapter는 도입 조건과 제거 절차가 문서화되어 있다. + +## 27. 구현 우선순위 + +### P0: 경계와 정확성 + +1. TypeScript 검사 도구와 `.ts/.tsx` architecture/security glob 준비 +2. input/output port 분리와 `ApplicationProvider` +3. HTTP path/query/body, parsed data, runtime retry/timeout, cleanup 교정 +4. Query bridge를 통한 실제 application 실행 +5. typed routing, registry-tree 단일화와 chunk recovery 실행 연결 +6. 완전한 removable reference feature와 제거 검증 + +### P1: 기본 플랫폼 완성도 + +1. error/result/validation/form kernel +2. 배타적인 async 상태와 page template +3. Logger와 telemetry 실제 wiring +4. design-system public API, icon wrapper와 headless interaction +5. locale/message/formatter와 pseudo-locale/RTL 경계 +6. Storybook, shared MSW, 시각 회귀와 built-output E2E +7. source/test TypeScript 전환 및 위험 기반 coverage/lint 강화 + +### P2: 프로젝트별 선택 capability + +WebSocket/SSE, offline/IndexedDB, Service Worker, feature flag, product +analytics, vendor error reporting, worker, virtualization, OpenAPI generation, +global store와 cloud visual-review service는 실제 프로젝트 요구와 측정 결과에 +따라 추가한다. + +P2 adapter를 많이 설치하는 것은 skeleton 완성도의 기준이 아니다. +안전한 경계, 도입 recipe, 테스트 계약과 제거 가능성이 준비되어 있는지가 +기준이다. diff --git a/docs/architecture/layers.md b/docs/architecture/layers.md index 1134f276..5d278a00 100644 --- a/docs/architecture/layers.md +++ b/docs/architecture/layers.md @@ -22,6 +22,14 @@ The following edges are forbidden: `bootstrap` contains composition only. Business rules and page-specific orchestration belong to domain/application. +This table is the current coarse-grained rule. The +[ports, adapters, and feature-boundary target](./frontend-ports-adapters-and-boundaries.md) +defines the missing application input boundary, explains that `presentation` +acts as the inbound adapter, and separates current outbound adapters from +project-selected capabilities. The +[platform capability review](./frontend-platform-capability-review.md) records +where the current composition still bypasses this intended rule. + Architecture reports use this shape: ```json diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index ff860a01..dc7ffe7d 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -18,14 +18,43 @@ flowchart LR Contracts --> Presentation ``` -Dependencies point inward. Presentation calls application use cases, adapters -implement application ports, and only the composition root selects concrete -adapters. Contract registries are the single named source for routes, API -operations, environment values, storage keys, errors, queries, telemetry, and -release tokens. +The intended dependency rule points inward: presentation calls application use +cases, adapters implement application ports, and only the composition root +selects concrete adapters. Contract registries are the intended named source +for routes, API operations, environment values, storage keys, errors, queries, +telemetry, and release tokens. The platform review below records where the +current runtime still bypasses that target or duplicates registry metadata. -The executable route tree is mounted only after runtime configuration and -release-manifest coherence pass. It receives the composed query client, +In ports-and-adapters terms, `presentation` is the current inbound adapter and +`adapters` contains the current outbound implementations. The target design +makes this role explicit, introduces application input ports, and prevents the +React tree from receiving raw outbound dependencies: + +```mermaid +flowchart LR + Driver[User, route, browser event] --> Inbound[React inbound adapter] + Inbound --> Input[Application input API] + Input --> UseCase[Use cases] + UseCase --> Output[Application output ports] + Output --> Outbound[HTTP, auth, storage, query, telemetry adapters] + Bootstrap2[Composition root] -. selects and injects .-> Input + Bootstrap2 -. selects and injects .-> Outbound +``` + +The current executable route tree is mounted only after runtime configuration +and release-manifest coherence pass. It receives the composed query client, credential-opaque session port, storage port, telemetry port, and immutable -build ID. Visible starter pages depend on those ports and contracts, never on a -concrete adapter or the removable sample fixture. +build ID. Visible starter pages do not depend on the removable sample fixture. + +This describes the current starter composition, not the completed target. The +capability review found that raw outbound capabilities still reach the React +tree, the composed application facade is not yet its entry point, and several +route, HTTP, recovery, telemetry, and sample-removal contracts are only +partially connected. Use the following documents for the evidence and migration +plan: + +- [Frontend platform capability review](./frontend-platform-capability-review.md) +- [Frontend ports, adapters, and boundaries](./frontend-ports-adapters-and-boundaries.md) +- [TypeScript, state, and data flow](./typescript-state-and-data-flow.md) +- [Routing, pages, and patterns](./routing-pages-and-patterns.md) +- [Frontend platform implementation roadmap](./frontend-platform-implementation-roadmap.md) diff --git a/docs/architecture/routing-pages-and-patterns.md b/docs/architecture/routing-pages-and-patterns.md new file mode 100644 index 00000000..8f4bb800 --- /dev/null +++ b/docs/architecture/routing-pages-and-patterns.md @@ -0,0 +1,492 @@ +# 라우팅, 페이지 템플릿, 재사용 패턴 + +## 1. 목적 + +이 문서는 도메인과 무관하게 다음을 바로 구현할 수 있는 기준을 제공한다. + +- typed route와 안전한 URL +- session, permission, feature flag guard +- lazy chunk의 loading/error/recovery +- route 이동 시 focus, scroll, 취소, dirty form 처리 +- list, detail, form, status 등 공통 page template +- page controller와 application input use case의 연결 +- 프론트엔드에서 반복 사용하는 설계 패턴 + +## 2. 현재 상태와 문제 + +현재 구현에는 다음 장점이 있다. + +- route registry가 path와 access policy를 소유한다. +- route component를 lazy import한다. +- 앱 셸과 보호 route, not-found surface가 있다. +- route heading focus와 비동기/render error boundary가 있다. +- redirect loop와 chunk recovery에 대한 policy 함수가 일부 존재한다. + +하지만 `src/contracts/routes.js`의 metadata와 +`src/presentation/routes/app-router.jsx`의 executable route tree가 별도 수동 목록이다. +그 결과 다음 필드는 선언돼도 실제 행동을 보장하지 않는다. + +- params/search schema +- loading/error surface +- chunk ID +- route title/navigation label +- redirect loop guard +- chunk recovery policy + +페이지도 공통 `PageHeader` 외에는 각자 section과 class를 직접 조립한다. 목록, +상세, 편집, 오류 페이지의 반복되는 접근성·반응형·상태 표면을 기능 팀이 다시 +구현해야 한다. + +## 3. React Router mode 결정 + +[React Router 공식 mode 설명](https://reactrouter.com/start/modes)과 +[Data Mode custom setup](https://reactrouter.com/start/data/custom)은 +Declarative, Data, Framework Mode를 구분한다. + +저장소에는 현재 React Router `7.18.1`이 고정돼 있다. 구현 브랜치는 공식 문서의 +동일 버전 API를 기준으로 하고 router version upgrade를 Data Mode 구조 변경과 +같은 브랜치에 섞지 않는다. 위 공식 링크의 기본 표시 버전이 바뀌면 version +selector를 `7.18.1`로 맞춰 확인한다. + +| mode | 선택 조건 | 이 저장소에서의 판단 | +| --- | --- | --- | +| Declarative | React composition과 외부 data layer가 route data를 소유 | 현재 구현이 사용 중인 기준선 | +| Data | route object, blocker, scroll restoration, pending/navigation state가 필요 | 목표 skeleton의 navigation lifecycle에 적합 | +| Framework | route module, type-safe href, code splitting, SSR/static 전략을 framework가 소유 | client-only skeleton 기본값으로는 범위가 큼 | + +목표 결정: + +- client-only SPA와 TanStack Query/application use case를 유지한다. +- 현재 `BrowserRouter` 기반 Declarative Mode에서 `createBrowserRouter`와 + `RouterProvider` 기반 Data Mode로 이동한다. +- Data Mode를 선택하는 이유는 route object, navigation blocker, scroll + restoration, route error 경계를 일관되게 소유하기 위해서다. loader/action으로 + 서버 상태를 다시 소유하기 위해서가 아니다. +- loader/action을 추가할 때는 TanStack Query/application input을 prefetch하거나 + 호출하는 한 가지 소유 경로만 사용한다. +- 같은 데이터를 route loader와 TanStack Query가 각각 가져오지 않는다. +- SSR/static generation을 선택하기 전에는 Framework Mode를 기본값으로 만들지 + 않는다. + +전환 브랜치 전까지 현재 Declarative router에 새 custom scroll/blocker +implementation을 추가하지 않는다. 전환할 수 없는 프로젝트만 별도 ADR과 +`NavigationLifecycleAdapter`를 구현한다. + +## 4. route 계약과 runtime map + +### 4.1 두 종류의 레지스트리 + +직렬화 가능한 contract와 React implementation을 분리한다. + +```ts +export const routeContracts = { + home: { + id: "home", + path: "/", + access: "public", + navigation: "primary", + titleKey: "route.home.title", + loadingSurface: "page", + errorSurface: "page", + chunkId: "home", + }, + resourceDetail: { + id: "resourceDetail", + path: "/examples/resources/:resourceId", + access: "authenticated", + navigation: "hidden", + titleKey: "route.resourceDetail.title", + loadingSurface: "detail", + errorSurface: "detail", + chunkId: "reference-resource-detail", + }, +} as const satisfies RouteContractRegistry; +``` + +```tsx +export const routeRuntime = { + home: { + Component: lazy(() => import("../pages/home-page")), + paramsCodec: emptyParamsCodec, + searchCodec: emptySearchCodec, + }, + resourceDetail: { + Component: lazy(() => import("../features/resources/resource-detail-page")), + paramsCodec: resourceDetailParamsCodec, + searchCodec: resourceDetailSearchCodec, + }, +} satisfies Record; +``` + +요구 사항: + +- contract key와 `id`가 다르면 typecheck 실패 +- contract에는 함수, component, schema instance처럼 직렬화 불가능한 값을 넣지 않음 +- runtime map에는 실제 lazy component와 codec/guard만 둠 +- contract의 모든 route가 runtime에 있고 runtime의 모든 key가 contract에 있음 +- navigation은 contract에서 파생 +- build chunk manifest와 `chunkId` 대응을 검증 +- public runtime config나 server가 route component 이름을 임의 지정할 수 없음 + +### 4.2 params와 search codec + +URL은 외부 입력이다. page에서 `useParams()` 결과를 cast하지 않는다. + +```ts +const resourceDetailParamsSchema = z.object({ + resourceId: z.string().trim().min(1).max(100), +}); + +const resourceListSearchSchema = z.object({ + q: z.string().trim().max(100).catch(""), + page: z.coerce.number().int().min(1).catch(1), + sort: z.enum(["updated-desc", "name-asc"]).catch("updated-desc"), +}); +``` + +path params와 search params는 입력 형태와 serialization 규칙이 다르므로 같은 +interface로 뭉치지 않는다. 각각 parse와 serialize를 제공한다. + +```ts +interface PathParamsCodec { + parse( + input: Readonly>, + ): Result; + serialize(value: T): Readonly>; +} + +interface SearchParamsCodec { + parse(input: URLSearchParams): Result; + serialize(value: T): URLSearchParams; +} +``` + +규칙: + +- route input parse 실패와 backend 404를 구분한다. +- 알 수 없는 search key를 보존할지 제거할지 route별로 선언한다. +- default value를 URL에 항상 쓸지 생략할지 codec이 결정한다. +- array/date/boolean encoding을 feature마다 다르게 만들지 않는다. +- navigation link도 codec 기반 builder를 사용한다. +- query key에는 parsed value만 사용한다. +- 검색어·식별자를 telemetry에 기록하기 전에 sensitivity policy를 적용한다. + +### 4.3 route object 생성 + +하나의 factory가 다음을 조합한다. + +```text +route contract + + runtime component/codecs + + access guard + + feature flag guard + + suspense surface + + render/chunk error surface + + title/focus/scroll behavior + -> executable route object/tree +``` + +JSX에서 route별 ``를 다시 나열하지 않는다. nested layout이 필요한 경우 +contract에 parent ID를 두고 cycle/orphan/duplicate path를 registry gate에서 +검사한다. + +## 5. guard와 권한 + +### 5.1 guard 순서 + +권장 순서: + +1. runtime/bootstrap readiness +2. route 존재와 URL parse +3. feature flag +4. session readiness +5. authentication +6. coarse client permission hint +7. route component +8. server authorization result + +client guard는 UX 최적화일 뿐 보안 경계가 아니다. API/BFF가 항상 최종 권한을 +검사한다. + +### 5.2 guard 결과 + +```ts +type GuardDecision = + | { kind: "allow" } + | { kind: "redirect"; to: SafeLocation; reason: RedirectReason } + | { kind: "render"; surface: "auth-required" | "forbidden" | "not-found" }; +``` + +- redirect에는 origin route와 bounded return URL을 사용한다. +- 외부 redirect는 allowlist를 거친다. +- 동일한 route 쌍을 반복하는 redirect loop를 차단한다. +- session이 아직 resolving이면 forbidden으로 단정하지 않는다. +- server가 403을 반환하면 client claim을 신뢰해 화면을 계속 보여 주지 않는다. + +## 6. navigation lifecycle + +### 6.1 loading + +loading surface를 route metadata에 연결한다. + +| surface | 사용 | +| --- | --- | +| shell | 초기 앱 셸 진입 | +| page | 새로운 전체 페이지 | +| collection | table/list 구조 유지 | +| detail | metadata/content 구조 유지 | +| form | 필드 layout 구조 유지 | +| inline | 부분 action | + +cached data가 있으면 full-page skeleton으로 교체하지 않고 refreshing indicator를 +사용한다. `prefers-reduced-motion`에서 skeleton animation을 줄인다. + +### 6.2 error와 lazy chunk recovery + +route error boundary는 다음을 구분한다. + +- render/programmer error +- dynamic import/chunk load error +- application `AppFailure` +- URL parse failure +- not found + +chunk recovery 순서: + +1. 현재 build ID와 release manifest를 확인한다. +2. 새 manifest가 확인되고 같은 build에 대해 reload하지 않았다면 한 번만 reload한다. +3. 같은 failure가 반복되면 reload loop를 막는다. +4. 안전한 support surface와 trace/build ID를 표시한다. +5. recovery 결과를 redacted diagnostics에 기록한다. + +custom fallback을 넘겨 retry/reset 기능을 잃지 않게 한다. boundary는 +`location.key` 또는 route ID가 바뀌면 적절히 reset된다. + +### 6.3 focus와 scroll + +- route 성공 후 `main`의 page heading에 programmatic focus +- mouse 사용자가 불필요한 focus ring을 보지 않게 할 수는 있지만 keyboard focus + indication을 전역으로 제거하지 않음 +- modal/drawer가 닫히면 opener에 focus 복원 +- backward/forward navigation은 저장한 scroll 복원 +- 새 primary route는 top으로 이동 +- hash target은 fixed header offset과 focus 가능 여부를 처리 +- screen reader용 route title/live announcement는 중복 발표를 피함 + +### 6.4 취소와 dirty form + +- route 이동 시 진행 중 query signal을 취소한다. +- mutation은 취소 안전성이 명확할 때만 취소한다. +- dirty form blocker는 browser unload와 in-app navigation을 구분한다. +- 성공 저장 후 blocker를 해제한 다음 이동한다. +- autosave가 있는 form은 pending/failed 상태를 별도로 알린다. +- confirm dialog는 공통 accessible primitive를 사용한다. + +## 7. 페이지 템플릿 + +template은 데이터를 가져오거나 application을 호출하지 않는다. 슬롯, landmark, +focus target, responsive layout, 상태 위치만 소유한다. + +### 7.1 `StandardPageTemplate` + +슬롯: + +- breadcrumb 또는 back link +- title, description, status badge +- primary/secondary actions +- notices +- content +- contextual aside + +작은 화면에서 action wrapping 순서와 heading hierarchy를 보장한다. + +### 7.2 `CollectionPageTemplate` + +슬롯과 상태: + +- title/actions +- search/filter/sort toolbar +- active filter summary와 reset +- result count +- table/list/card view +- pagination 또는 load-more +- initial loading, refreshing, empty-first-use, empty-filtered, error +- bulk selection/action + +URL이 filter, sort, page를 소유한다. template은 query 상태를 직접 읽지 않는다. + +### 7.3 `DetailPageTemplate` + +- breadcrumb/back +- title/status/actions +- summary metadata +- main sections +- related/context aside +- loading/not-found/forbidden/error +- destructive action confirmation 위치 + +식별자가 바뀔 때 이전 entity 내용과 새 loading 상태를 혼동하지 않게 key/reset +정책을 명시한다. + +### 7.4 `FormPageTemplate` + +- title/description +- error summary +- field groups +- optional aside/help +- sticky 또는 normal action bar +- submit/cancel +- submitting/saved/conflict/unavailable +- dirty navigation confirmation + +template은 특정 form vendor를 import하지 않는다. + +### 7.5 `StatusPageTemplate` + +다음 변형을 제공한다. + +- unauthenticated +- forbidden +- not found +- unavailable +- offline +- maintenance +- unexpected + +각 변형은 heading, 짧은 설명, 안전한 primary/secondary action, 선택적 trace ID를 +갖는다. raw stack/response를 표시하지 않는다. + +### 7.6 선택 template + +다음은 project 필요가 있을 때 추가한다. + +- `SettingsPageTemplate` +- `DashboardGridTemplate` +- `SplitPaneTemplate` +- `WizardTemplate` +- `FullScreenTaskTemplate` + +## 8. page controller 패턴 + +page를 세 부분으로 나눈다. + +```text +route adapter + parses URL and guard context + ↓ +controller hook + invokes application query/mutation and maps UI events + ↓ +page view + renders template and design-system components +``` + +예: + +```tsx +export function ResourceListRoute() { + const input = useRouteInput(resourceListRoute); + if (!input.ok) return ; + + return ; +} + +function ResourceListController({ input }: ResourceListControllerProps) { + const controller = useResourceListController(input); + return ; +} +``` + +route parse boundary와 controller component를 분리하므로 controller hook은 +조건부로 호출되지 않는다. + +controller가 소유하는 것: + +- parsed route input을 application input으로 변환 +- query/mutation state +- pagination/filter/navigation event +- retry/refresh/action callbacks +- view model projection + +view가 소유하는 것: + +- semantic markup +- template/component 조립 +- focus target +- 사용자의 local-only interaction + +controller가 소유하지 않는 것: + +- HTTP URL 조립 +- credential +- transport DTO parse +- 도메인 invariant +- raw vendor SDK + +## 9. 권장 패턴 카탈로그 + +| 패턴 | 적용 위치 | 쓰는 이유 | 오용 | +| --- | --- | --- | --- | +| Ports and Adapters | application 외부 경계 | 정책과 기술 교체 분리 | 모든 작은 UI library에 port 생성 | +| Command/Query | application input | 읽기/변경 의도와 정책 분리 | CQRS 인프라를 필요 없이 도입 | +| Gateway | output port | 외부 데이터 capability 표현 | `get/post` 범용 HTTP를 application에 노출 | +| Anti-Corruption Mapper | outbound feature adapter | DTO 변화가 core로 전파되지 않게 함 | 단순 object spread로 타입만 바꿈 | +| Result | 예상 실패 | 실패 종류와 처리 경로를 닫음 | programmer error까지 모두 Result로 숨김 | +| Controller/View | inbound React | data lifecycle과 markup 분리 | 거대한 hook 하나에 모든 feature 로직 집중 | +| Strategy | retry/cache/auth recovery | 정책 교체와 테스트 가능성 | 설정 한 줄도 interface로 과도 추상화 | +| Observer/External Store | session/theme/realtime | React 외부 소유 상태 구독 | server state를 다시 external store에 복제 | +| State Machine | 복잡한 workflow | 유효 전이와 보상 명시 | 단순 modal open에 도입 | +| Headless/Compound Component | 복합 UI | behavior와 style/slot 분리 | vendor primitive를 제품 전역에 직접 노출 | +| Adapter Facade | icon/form/i18n vendor | React inbound 내부 vendor 교체 경계 | application port로 승격 | +| Page Template | 반복 layout/state | 접근성과 반응형 구조 재사용 | data fetching을 template에 포함 | +| Registry + Runtime Map | route/operation/event | 선언과 실행 완전성 | 모든 설정을 하나의 거대 전역 파일에 집중 | + +패턴은 추상화 파일만 만든 것으로 완료되지 않는다. reference usage, negative +architecture test, 실패 상태 test가 있어야 제공된 패턴으로 본다. + +## 10. 새 route/page 추가 recipe + +1. feature public 경계와 route ID를 정한다. +2. serializable route contract를 등록한다. +3. params/search Zod schema와 bidirectional codec을 작성한다. +4. safe URL builder를 export한다. +5. lazy page module과 runtime map entry를 추가한다. +6. session/permission/flag guard를 선언한다. +7. 적절한 page template을 선택한다. +8. controller hook을 application input API에 연결한다. +9. loading, empty, refreshing, error, auth, forbidden, not-found를 결정한다. +10. title/message key, focus, scroll, chunk ID를 연결한다. +11. 다음 검증을 추가한다. + - contract/runtime map type completeness + - codec round-trip/property cases + - guard decision unit + - page component state + - query/mutation integration + - keyboard/focus/axe + - direct URL, back/forward, refresh E2E + - chunk failure recovery가 필요한 route의 E2E +12. registry, type, architecture, component, integration, E2E gate를 실행한다. + +## 11. 금지 패턴 + +- page 안에서 raw `fetch`, storage, auth SDK, telemetry SDK 호출 +- `useParams()`/`URLSearchParams` 값을 cast만 하고 사용 +- route contract와 JSX route tree를 각각 수동 관리 +- protected route를 server authorization 대체 수단으로 취급 +- 모든 실패를 redirect 또는 full-page error로 처리 +- query data가 있는데 background error 때문에 내용을 제거 +- chunk load error에서 제한 없는 `location.reload` +- route heading focus outline을 CSS로 무조건 제거 +- template이 data fetching 또는 feature-specific copy를 소유 +- generic `BasePage` prop 하나에 모든 layout variation을 boolean으로 추가 + +## 12. 완료 기준 + +- 모든 route ID가 contract와 runtime map에서 compile-time 완전성을 가진다. +- params/search parse와 URL serialize가 같은 codec을 사용한다. +- route metadata가 loading/error/chunk/title/navigation 행동에 실제 연결된다. +- redirect와 chunk reload loop가 차단된다. +- route 이동 시 query 취소, focus, scroll, dirty policy가 검증된다. +- collection/detail/form/status reference page가 template을 사용한다. +- page view가 application input 외의 외부 capability를 직접 호출하지 않는다. +- 새 route recipe와 테스트만으로 별도 라우터 내부 지식 없이 기능을 추가할 수 있다. diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index b45a51f5..d5e37ed8 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -11,9 +11,9 @@ primitives, and state surfaces remain reusable. validated config + coherent release manifest -> concrete adapters -> QueryClientProvider + -> BrowserRouter -> ThemeProvider -> SessionProvider - -> BrowserRouter -> AppShell -> lazy route boundary ``` @@ -54,6 +54,14 @@ An external owner implements `readState`, `subscribe`, `beginSignIn`, ## Extending the starter +The steps below describe the current extension path. The platform review found +that several route metadata fields and the composed application facade are not +yet connected end to end. New platform work should follow +[routing, page templates, and reusable patterns](./routing-pages-and-patterns.md) +and the +[TypeScript, state, and data-flow target](./typescript-state-and-data-flow.md) +rather than adding another independent route or data-loading convention. + 1. Register the route path, access hint, title, chunk, loading surface, error surface, and optional navigation metadata in `src/contracts/routes.js`. 2. Add a lazy page in `src/presentation/` and render it through `RouteSurface`. diff --git a/docs/architecture/typescript-state-and-data-flow.md b/docs/architecture/typescript-state-and-data-flow.md new file mode 100644 index 00000000..83f859bc --- /dev/null +++ b/docs/architecture/typescript-state-and-data-flow.md @@ -0,0 +1,549 @@ +# TypeScript, 상태 소유권, 데이터 흐름 + +## 1. 목적 + +이 문서는 다음 질문에 대한 저장소 표준을 정의한다. + +- JavaScript를 어떤 순서로 TypeScript로 전환하는가. +- local, URL, server, form, global, persisted 상태를 어디에 둬야 하는가. +- React 화면이 application use case와 TanStack Query를 어떻게 사용해야 하는가. +- HTTP, retry, auth, error, validation, logging의 책임을 어떻게 나누는가. +- 새 query, mutation, form을 추가할 때 어떤 파일과 테스트가 필요한가. + +이 문서는 목표 설계다. 현재 구현 상태는 +[프론트엔드 플랫폼 역량 재검토](./frontend-platform-capability-review.md)를 따른다. + +## 2. TypeScript 전환 원칙 + +### 2.1 왜 전환하는가 + +현재 `strict + allowJs + checkJs`는 JavaScript 상태에서 유용한 안전망이다. 그러나 +JSDoc cast가 늘어나면 다음 계약을 정확히 닫기 어렵다. + +- `RouteId`, `OperationId`, `ErrorCode`, `StorageKey`, `TelemetryEvent` +- `Result`와 discriminated failure union +- use case input/output와 gateway generic +- route별 params/search type +- query key tuple +- component variant와 slot prop +- runtime registry의 key와 executable implementation의 완전성 + +TypeScript 전환 목적은 확장자 변경이 아니라 이 계약을 컴파일 단계에서 +검증하는 것이다. + +### 2.2 전환 전에 고칠 도구 + +다음 변경이 첫 브랜치에서 완료되기 전에는 source rename을 시작하지 않는다. + +1. ESLint가 `js`, `jsx`, `mjs`, `ts`, `tsx`, `mts`를 모두 검사한다. +2. `typescript-eslint`, React Hooks, JSX accessibility 규칙을 추가한다. +3. dependency-cruiser의 extension과 resolver가 TS/TSX를 포함한다. +4. `scripts/check-registries.mjs`가 TS/TSX를 검색한다. +5. `config/contracts/registry-governance.json`의 경로 갱신 절차를 만든다. +6. Vite, Vitest, Playwright, scripts, source, tests를 각각 typecheck한다. +7. invalid type fixture가 TS migration 후에도 “실패해야 통과”하는지 확인한다. +8. architecture/security/registry gate가 TS fixture 위반을 실제로 잡는 negative test를 + 추가한다. + +권장 project 구성: + +```text +tsconfig.base.json +tsconfig.app.json +tsconfig.node.json +tsconfig.test.json +tsconfig.json # project references only +``` + +`tsconfig.base.json`의 초기 핵심 옵션: + +```json +{ + "compilerOptions": { + "strict": true, + "noEmit": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "useUnknownInCatchVariables": true, + "noImplicitOverride": true, + "noFallthroughCasesInSwitch": true, + "verbatimModuleSyntax": true, + "isolatedModules": true + } +} +``` + +실제 TypeScript 7/Vite 호환 옵션은 설치된 공식 문서와 빌드 결과를 기준으로 +확정한다. 옵션을 한꺼번에 켜서 수백 개 예외를 만들지 말고, 각 단계에서 새 +예외를 금지한다. + +### 2.3 전환 순서 + +| 단계 | 대상 | 이유 | 종료 조건 | +| --- | --- | --- | --- | +| 0 | lint/typecheck/scanner/architecture tooling | TS 코드가 검사를 우회하지 않게 함 | TS 위반 fixture가 각 게이트에서 실패 | +| 1 | result, failure, ID, registry types | 이후 모든 계층의 언어가 됨 | stringly typed public ID 제거 | +| 2 | application input/output ports와 use case | 중심 계약을 먼저 고정 | input/output compile fixture 통과 | +| 3 | domain model과 mapper boundary | DTO와 core model 혼합 차단 | mapper contract test 통과 | +| 4 | outbound adapters | 외부 `unknown`을 경계에서 좁힘 | HTTP/storage/auth failure type 통과 | +| 5 | bootstrap/composition | 누락 dependency를 컴파일로 검출 | 실제 composition type test 통과 | +| 6 | React providers/controllers/routes | typed application API 소비 | route/runtime map 완전성 검사 | +| 7 | primitives/pages/templates | component API와 variant를 닫음 | stories/component tests typecheck | +| 8 | tests/scripts/config | 우회 없는 전체 저장소 | source `allowJs` 제거 가능 | + +각 단계는 빌드 가능한 작은 커밋으로 유지한다. JavaScript와 TypeScript가 공존하는 +동안에는 [공식 JavaScript migration 가이드](https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html)의 +점진적 방식을 사용한다. + +### 2.4 기본 type 계약 + +다음 형태를 core application에 둔다. + +```ts +export type Ok = Readonly<{ ok: true; value: T }>; +export type Err = Readonly<{ ok: false; error: E }>; +export type Result = Ok | Err; + +export type AppFailure = + | Readonly<{ kind: "unauthenticated"; code: "AUTH_REQUIRED"; traceId?: string }> + | Readonly<{ kind: "forbidden"; code: "FORBIDDEN"; traceId?: string }> + | Readonly<{ kind: "not-found"; code: "NOT_FOUND"; traceId?: string }> + | Readonly<{ kind: "conflict"; code: "CONFLICT"; traceId?: string }> + | Readonly<{ + kind: "validation"; + code: "VALIDATION_FAILED"; + fields: Readonly>; + traceId?: string; + }> + | Readonly<{ kind: "rate-limited"; code: "RATE_LIMITED"; retryAt?: Date }> + | Readonly<{ kind: "unavailable"; code: "UNAVAILABLE"; retryable: boolean }> + | Readonly<{ kind: "unexpected"; code: "UNEXPECTED"; traceId?: string }>; +``` + +원칙: + +- adapter에서 받은 `unknown`은 adapter 경계에서 parse한다. +- application은 `Response`, `AxiosError`, Zod 내부 오류 같은 vendor type을 + 노출하지 않는다. +- UI copy는 failure에 저장하지 않고 message key mapper에서 결정한다. +- 예상 가능한 실패는 `Result`; programmer bug와 render crash는 error boundary로 + 보낸다. +- `as`, non-null assertion, `any`는 경계에서 근거가 있을 때만 사용하고 lint + 예외에 사유를 기록한다. + +## 3. 상태 소유권 + +### 3.1 상태 분류표 + +상태를 만들기 전에 아래 순서로 소유자를 결정한다. + +| 질문 | 상태 종류 | 기본 도구 | 저장 위치 | +| --- | --- | --- | --- | +| 한 컴포넌트 상호작용에만 필요한가 | local UI | `useState`, `useReducer` | component/controller | +| URL로 공유·복원되어야 하는가 | navigation | router params/search + codec | URL | +| 서버가 진실의 원천인가 | server state | TanStack Query inbound adapter | Query cache | +| 입력 중이고 제출 전인가 | form | local form facade | form controller | +| 앱 전체에서 낮은 빈도로 바뀌는가 | cross-cutting | Context 또는 typed external store | provider/store | +| 여러 feature의 복잡한 workflow인가 | client workflow | reducer, Zustand, Redux Toolkit, state machine | feature-owned store | +| 새로고침 후 남아야 하는가 | persisted preference | `StoragePort` | versioned browser storage | +| 인증 credential인가 | auth secret | external auth owner | SDK memory 또는 HttpOnly cookie | + +금지: + +- server response를 global client store에 복사하지 않는다. +- URL에 있어야 할 filter/sort/page를 숨은 store에만 두지 않는다. +- component 내부에 머물 수 있는 modal open 상태를 전역화하지 않는다. +- access token을 localStorage, sessionStorage, 일반 Redux/Zustand store에 넣지 + 않는다. +- 모든 상태를 추상화하는 범용 `StorePort`를 만들지 않는다. + +### 3.2 범용 store 선택 기준 + +기본 skeleton에는 빈 Zustand/Redux store를 만들지 않는다. 실제 요구가 생기면 +다음 기준을 적용한다. + +| 조건 | 권장 | +| --- | --- | +| feature 한 곳의 단순 shared client state | feature reducer 또는 작은 Zustand store | +| 여러 팀이 action/state 규약, devtools, middleware, audit를 공유 | Redux Toolkit | +| 명시적 상태 전이, 병렬 상태, 취소/보상 workflow | state machine | +| session/theme처럼 저빈도 cross-cutting | `useSyncExternalStore` 또는 Context | + +vendor를 선택하더라도 feature 외부에는 hook/facade만 export한다. 제품 코드가 +store instance의 `getState`와 `setState`를 임의 호출하지 않게 한다. + +### 3.3 persistence + +persisted state는 다음 metadata를 가져야 한다. + +```ts +type PersistedRecord = Readonly<{ + version: number; + writtenAt: string; + value: T; +}>; +``` + +- key는 typed registry가 소유한다. +- read 시 schema parse와 migration을 거친다. +- quota, unavailable, corrupt, version mismatch를 구분한다. +- 민감정보와 credential을 저장하지 않는다. +- server state persistence와 offline mutation queue는 별도 project-selected + adapter다. + +## 4. 표준 데이터 호출 경로 + +```mermaid +sequenceDiagram + actor User + participant Page as React page + participant Controller as inbound query/mutation controller + participant App as application input use case + participant Gateway as output gateway + participant Adapter as HTTP/generated client adapter + participant API as Backend/BFF + + User->>Page: route or event + Page->>Controller: typed input + Controller->>App: query/command + AbortSignal + App->>Gateway: capability request + Gateway->>Adapter: DTO request + Adapter->>API: path/query/body/auth + API-->>Adapter: envelope or failure + Adapter-->>Gateway: parsed DTO Result + Gateway-->>App: mapped model Result + App-->>Controller: view data or AppFailure + Controller-->>Page: query/mutation state +``` + +페이지는 controller hook이 제공하는 상태만 렌더링한다. controller는 React, +TanStack Query와 application input interface를 알 수 있지만 use case의 concrete +구현과 outbound adapter는 모른다. + +### 4.1 Application API + +```ts +export interface Application { + readonly resources: { + list( + input: ListResourcesInput, + context: Readonly<{ signal: AbortSignal }>, + ): Promise>; + create( + command: CreateResourceCommand, + context?: Readonly<{ signal?: AbortSignal }>, + ): Promise>; + }; +} +``` + +`ApplicationProvider`는 이 API를 immutable value로 제공한다. controller 외의 +presentation 코드에서 raw HTTP/storage/telemetry port를 가져오는 hook은 만들지 +않는다. theme, locale 같은 UI platform provider는 별도다. + +### 4.2 query adapter + +```ts +export function useResourcesQuery(input: ListResourcesInput) { + const application = useApplication(); + + return useQuery({ + queryKey: resourceKeys.list(input), + queryFn: async ({ signal }) => + unwrapResult(await application.resources.list(input, { signal })), + retry: false, + staleTime: resourceQueryPolicy.list.staleTime, + }); +} +``` + +실제 구현 규칙: + +- query key는 readonly tuple factory로만 만든다. +- key에 들어간 filter는 실제 gateway request에도 동일하게 투영한다. +- `AbortSignal`을 application과 HTTP transport까지 전달한다. +- HTTP 계층이 bounded retry를 소유하면 query retry는 끈다. +- background error와 initial error의 UI를 구분한다. +- placeholder와 cached stale data가 있을 때 전체 화면 error로 교체하지 않는다. +- `select`는 view-only projection에 쓰고 도메인 규칙을 넣지 않는다. +- query hook은 feature public API에서 export한다. + +### 4.3 mutation adapter + +```ts +export function useCreateResourceMutation() { + const application = useApplication(); + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: (command: CreateResourceCommand) => + application.resources.create(command).then(unwrapResult), + onSuccess: () => + queryClient.invalidateQueries({ queryKey: resourceKeys.all }), + }); +} +``` + +기본 mutation은 navigation만으로 취소됐다고 가정하지 않는다. 서버 작업의 취소가 +안전한 operation만 controller가 보관한 `AbortController`와 명시적 cancel action을 +사용한다. idempotency key는 UI 입력으로 받지 않고 application use case가 +`IdGeneratorPort`로 만들며, 같은 논리 요청의 bounded HTTP retry와 auth replay는 +동일한 key를 재사용한다. + +실제 구현에서는 mutation마다 다음을 명시한다. + +- double-submit 방지와 idempotency key 소유자 +- cancel 가능 여부 +- optimistic update 적용 여부와 rollback snapshot +- 성공 후 invalidate/update/navigation 순서 +- 409 conflict와 422 field validation mapping +- offline 시 queue할지 즉시 실패할지 +- analytics/telemetry event와 redaction + +optimistic update는 기본값이 아니다. 서버 규칙을 확실히 재현할 수 있고 rollback이 +안전한 mutation에만 사용한다. + +## 5. HTTP client 책임 + +### 5.1 목표 파이프라인 + +```text +operation registry + -> path/search/body builder + -> credential attachment + -> timeout and external cancellation + -> bounded retry + -> fetch transport + -> status/envelope decoder + -> response schema decoder + -> feature DTO mapper + -> AppFailure mapper +``` + +각 단계의 입력과 출력은 typed result다. feature-specific model mapper를 공통 HTTP +client 안에 넣지 않는다. + +### 5.2 request projection + +operation definition은 최소 다음 계약을 갖는다. + +```ts +type OperationDefinition< + TPath, + TSearch, + TBody, + TResponse, +> = Readonly<{ + id: OperationId; + method: HttpMethod; + pathTemplate: string; + pathSchema: Schema; + searchSchema: Schema; + bodySchema: Schema; + responseSchema: Schema; + timeoutMs?: number; + retryClass: "never" | "safe" | "idempotency-keyed"; +}>; +``` + +규칙: + +- path segment는 `encodeURIComponent`에 해당하는 안전한 builder를 통과한다. +- query의 array/null/undefined/boolean/date serialization을 한 곳에서 정의한다. +- Zod parse 결과의 trim/default/coercion을 실제 request에 사용한다. +- GET/HEAD에는 body를 보내지 않는다. +- JSON content type은 body가 있을 때만 붙인다. +- base URL과 path를 문자열 덧붙이기로 조립하지 않는다. +- external URL은 별도 allowlist policy를 거친다. + +### 5.3 timeout, cancellation, retry + +소유권: + +- 사용자 navigation/unmount 취소: query/controller가 signal 생성 +- operation timeout: HTTP adapter +- retry: HTTP adapter 또는 query adapter 중 하나 +- 인증 복구 후 단 한 번 replay: auth decorator +- mutation idempotency: application/controller가 key 생성, operation이 허용 여부 선언 + +retry 조건: + +- safe method 또는 idempotency key가 있는 허용 operation만 대상 +- timeout, network, 명시된 429/5xx만 정책 대상 +- validation, auth denial, forbidden, not found, conflict는 자동 재시도하지 않음 +- `Retry-After`와 bounded exponential backoff/jitter 지원 +- tab hidden/offline 상태를 고려 +- 최대 횟수와 전체 elapsed budget을 함께 제한 +- 각 attempt와 final failure를 redacted telemetry로 기록 + +timer와 event listener는 성공, 실패, validation 조기 반환, external abort 모든 +경로에서 정리되어야 한다. + +## 6. 인증과 token 소유권 + +기본 skeleton은 token manager를 제공하지 않는다. + +지원 profile: + +| profile | credential 소유자 | frontend 역할 | +| --- | --- | --- | +| BFF/HttpOnly cookie | browser cookie + backend | `credentials`, CSRF 정책, session probe | +| external OIDC/Auth SDK | SDK memory/cache | attach/recover/login/logout를 auth adapter로 감쌈 | +| SPA memory token | auth adapter memory | 프로젝트가 명시적으로 선택할 때만 | + +공통 `AuthSessionReader`와 HTTP 전용 `CredentialProvider`를 분리한다. + +```ts +interface AuthSessionReader { + getSnapshot(): SessionSnapshot; + subscribe(listener: () => void): () => void; +} + +interface CredentialProvider { + attach(request: RequestInit): Promise; + recover(failure: AuthFailure): Promise<"recovered" | "not-recovered">; +} +``` + +UI는 credential을 읽지 않는다. HTTP adapter는 UI session action을 호출하지 +않는다. logout/login/redirect는 application input 또는 auth UI facade를 통해 +실행한다. + +## 7. 오류, 검증, logging + +### 7.1 검증 계층 + +| 경계 | 책임 | 예 | +| --- | --- | --- | +| runtime config | 앱을 안전하게 시작할 수 있는가 | URL, timeout, auth mode | +| route codec | URL을 typed input으로 읽고 쓸 수 있는가 | page, sort, ID | +| transport DTO | 외부 응답/요청 형식이 계약과 맞는가 | envelope, date string | +| form | 사용자가 수정 가능한 입력 형태가 유효한가 | required, length, format | +| application | use case precondition이 맞는가 | command 조합 | +| domain | 항상 지켜야 할 불변식인가 | valid state transition | + +같은 Zod schema를 무조건 모든 계층에서 재사용하지 않는다. transport DTO, form +value, application command, domain model이 우연히 같은 모양이어도 소유권과 +변경 이유가 다르다. 필요한 경우 mapper로 연결한다. + +### 7.2 사용자 오류 표면 + +`AppFailure`를 다음 UI 상태로 매핑한다. + +| failure | 기본 표면 | 자동 행동 | +| --- | --- | --- | +| unauthenticated | auth required 또는 login transition | auth policy에 따른 1회 복구 | +| forbidden | 권한 없음 | 없음 | +| not-found | route/detail not-found | 없음 | +| validation | error summary + field errors | 첫 오류 focus | +| conflict | 현재 데이터 유지 + conflict action | 자동 overwrite 금지 | +| rate-limited | inline retry time | 허용된 query만 지연 재시도 | +| unavailable | cached data 또는 retry surface | policy 범위 내 retry | +| unexpected | safe generic copy + trace ID | diagnostics emit | + +raw response body, stack, token, URL query, PII를 사용자 copy나 일반 log에 노출하지 +않는다. + +### 7.3 diagnostics와 telemetry + +현재 telemetry event contract와 별도로 개발·진단용 structured logger가 필요하다. +다음 두 설계 중 하나를 ADR로 결정한다. + +1. `DiagnosticsPort`가 log/event/span을 내부 method로 구분 +2. `LoggerPort`와 `TelemetryPort`를 분리 + +공통 요구: + +- log level과 event key는 닫힌 union +- attribute allowlist와 중앙 redaction +- dev adapter는 console을 사용하되 동일 redaction 적용 +- production adapter는 provider SDK를 감싸며 앱 코드는 SDK를 import하지 않음 +- 오류 객체 전체를 그대로 serialize하지 않음 +- trace ID/build ID/route ID/operation ID를 허용된 범위에서 연결 +- logging failure가 제품 flow를 실패시키지 않음 +- consent가 필요한 analytics와 essential diagnostics를 분리 + +## 8. 폼 표준 + +form vendor는 React Hook Form 또는 TanStack Form 등을 평가하되 local facade 뒤에 +둔다. vendor 선택과 무관하게 다음 API를 제공한다. + +- `Form` +- `FormField` +- `Label` +- `Description` +- `FieldError` +- `ErrorSummary` +- `useAppForm` +- `mapValidationFailureToFields` +- `useDirtyNavigationGuard` + +필수 동작: + +1. label, description, error를 stable ID와 `aria-describedby`로 연결 +2. submit 시 error summary와 첫 오류 focus +3. submitting 중 중복 제출 방지 +4. 422 응답의 알려진 field만 표시하고 나머지는 form-level failure로 처리 +5. 409 conflict는 validation error로 위장하지 않음 +6. 취소와 route 이탈 시 dirty policy 적용 +7. form value → application command mapper를 별도 함수로 둠 +8. browser autofill, IME composition, paste, password manager를 방해하지 않음 +9. loading skeleton으로 사용자의 입력을 덮지 않음 +10. form schema와 server contract mismatch를 integration test로 검증 + +## 9. 새 query 추가 recipe + +1. feature-owned input type과 application query use case를 추가한다. +2. 필요한 output gateway를 `ports/out`에 추가한다. +3. transport DTO schema와 mapper를 outbound feature adapter에 추가한다. +4. operation registry에 path/search/response/retry class를 등록한다. +5. readonly tuple query key factory를 추가한다. +6. inbound query controller hook을 추가한다. +7. page template에서 loading/empty/error/refreshing/success를 렌더링한다. +8. 다음 테스트를 추가한다. + - use case unit + - DTO mapper/schema contract + - path/search projection + - MSW success/empty/401/403/429/500/schema mismatch + - cancellation과 retry ownership + - component state + - route E2E +9. registry, type, architecture, unit, integration, E2E gate를 실행한다. + +금지: + +- page에서 `fetch` +- page에서 raw QueryClient +- cache key와 request filter의 별도 수동 조립 +- response DTO를 domain/application model로 사용 +- initial loading과 background refreshing을 같은 full-page skeleton으로 표시 + +## 10. 새 mutation/form 추가 recipe + +1. form value schema와 application command type을 분리한다. +2. value → command mapper를 작성한다. +3. input command use case와 output gateway method를 추가한다. +4. operation의 idempotency/retry 정책을 선언한다. +5. mutation controller에 invalidation/update/rollback 순서를 작성한다. +6. `FormPageTemplate`과 공통 field primitive로 화면을 구성한다. +7. 422, 409, unauthenticated, unavailable, abort를 각각 처리한다. +8. dirty navigation과 double-submit을 검증한다. +9. 다음 테스트를 추가한다. + - form schema와 mapper unit + - keyboard/label/error summary component + - MSW success/422/409/network-lost + - optimistic rollback을 쓰는 경우 cache snapshot + - 브라우저 navigation blocker와 성공 후 이동 + +## 11. 완료 기준 + +- TS/TSX가 lint, type, architecture, registry, security 검사를 우회하지 않는다. +- source와 test가 strict typecheck된다. +- UI는 application input API만 호출한다. +- reference query와 mutation이 TanStack adapter를 통해 동작한다. +- retry 책임이 단일 계층에 있고 cancellation/timeout과 충돌하지 않는다. +- path/search/parsed body가 실제 전송값과 일치한다. +- 상태 종류별 소유권이 테스트와 문서에서 확인된다. +- token은 UI와 일반 storage/store에 노출되지 않는다. +- failure와 validation의 각 계층이 typed mapper로 분리된다. +- query/mutation/form recipe만으로 새 기능을 만들 수 있다. diff --git a/docs/styling/design-system-platform.md b/docs/styling/design-system-platform.md new file mode 100644 index 00000000..3326ce9e --- /dev/null +++ b/docs/styling/design-system-platform.md @@ -0,0 +1,868 @@ +# 디자인 시스템 플랫폼 계약 + +이 문서는 도메인 기능을 추가하기 전에 프론트엔드 스켈레톤이 제공해야 하는 +디자인 시스템의 소유권, 계층, 기본 구성요소, 외부 라이브러리 경계, 검증 방법을 +정의한다. 목표는 특정 제품의 시각 언어를 미리 결정하는 것이 아니라, 제품 팀이 +접근성·반응형·국제화·테스트 규칙을 다시 발명하지 않고 기능 화면을 만들 수 있게 +하는 것이다. + +이 문서에서 `필수`는 모든 제품이 기반으로 사용할 계약을 뜻한다. `선택`은 +컴포넌트의 경계와 도입 기준은 제공하지만 실제 의존성이나 구현은 제품 요구가 +생긴 뒤 추가해도 되는 항목을 뜻한다. + +## 1. 현재 기준선과 확인된 공백 + +현재 저장소에는 다음 기반이 이미 있다. + +- `src/presentation/styles/theme.css` + - 의미 기반 light/dark 색상 토큰 + - focus indicator + - 반응형 앱 셸 + - reduced-motion 처리 +- `src/presentation/providers/theme-provider.jsx` + - `system`, `light`, `dark` 선호도 + - 저장소 포트를 통한 선호도 영속화 + - 운영체제 색상 변경 구독 +- `src/presentation/components/ui/` + - `Button` + - `TextField` + - `Card` + - `Alert` + - `Badge` + - `Dialog` +- `src/presentation/components/async-surface.jsx` + - 초기 로딩, 빈 화면, terminal error, background 상태 +- `src/presentation/components/state-surfaces.jsx` + - 인증 필요, 권한 없음, 찾을 수 없음 +- `/examples/ui`, `/examples/states` + - 실행 가능한 primitive와 상태 예제 +- component/E2E/axe 테스트 + - 필드 설명과 오류 연결 + - native dialog 닫기와 trigger focus 복원 + - 320px reflow + - Chromium, Firefox, WebKit + - 등록 라우트의 자동 접근성 검사 + +이 기반은 유효하지만 아직 디자인 시스템 플랫폼 전체는 아니다. + +1. 토큰이 색상 중심이며 typography, elevation, motion, z-layer, control size, + breakpoint가 계약으로 닫혀 있지 않다. +2. 공통 입력은 `TextField` 하나뿐이어서 일반적인 폼을 공통 규칙으로 만들 수 + 없다. +3. 앱 셸과 예제 화면에서 공용 primitive 대신 raw `button`, `select`, 링크 + class를 다시 작성하는 곳이 있다. +4. `☰`, `×` 같은 문자 glyph를 직접 사용하며 아이콘 공급자 경계가 없다. +5. `theme.css` 하나가 token, layout, primitive, pattern 스타일을 모두 소유한다. +6. runtime gallery는 있지만 격리된 story, interaction story, 시각 회귀 기준선이 + 없다. +7. 사용자 문구가 한국어 literal로 고정되어 locale과 RTL 계약이 없다. +8. `StandardPage`, `CollectionPage`, `DetailPage`, `FormPage` 같은 공통 페이지 + 템플릿이 없다. +9. 모바일 sidebar는 표시 전환은 되지만 modal drawer 수준의 focus 이동, focus + 복원, 배경 비활성화 계약은 없다. + +따라서 기존 구성요소는 폐기하지 않고 아래 목표 계층으로 이동·확장한다. + +## 2. 소유권과 의존성 원칙 + +디자인 시스템은 `presentation` 계층이 소유한다. 색상, 아이콘, 키보드 상호작용, +포커스, 화면 배치와 같은 문제는 도메인 규칙이 아니다. + +```text +product page + -> template + -> pattern + -> primitive + -> token +``` + +외부 UI 라이브러리를 사용하는 경우 흐름은 다음과 같다. + +```text +product page + -> local design-system API + -> local vendor facade + -> Lucide / React Aria / Radix +``` + +다음 규칙은 필수다. + +- 제품 페이지는 `lucide-react`, `react-aria-components`, `@radix-ui/*`를 직접 + import하지 않는다. +- 외부 UI 라이브러리 type을 공용 컴포넌트 API로 그대로 노출하지 않는다. +- 도메인과 application 계층은 React component, CSS class, icon name을 알지 + 않는다. +- primitive는 API 요청, query cache, 인증 상태와 같은 외부 상태를 직접 읽지 + 않는다. +- pattern과 template도 application use case를 직접 선택하지 않는다. 필요한 + 상태와 command callback을 props/slot으로 받는다. +- 제품별 색상이나 명칭을 primitive 내부에 하드코딩하지 않는다. +- 같은 의미의 접근성·키보드 동작을 페이지마다 다시 구현하지 않는다. +- 세 번째 사용 사례가 확인되기 전에는 제품 전용 조합을 무리하게 primitive로 + 승격하지 않는다. + +아이콘과 headless UI는 React inbound adapter의 vendor facade로 충분하다. +이들을 위한 application port를 만들지 않는다. HTTP, storage, telemetry처럼 +런타임 외부 자원을 교체하는 capability와 UI 구현 라이브러리를 구분한다. + +## 3. 목표 디렉터리 + +TypeScript 전환 이후의 목표 구조는 다음과 같다. 마이그레이션 중에는 기존 +경로에서 같은 소유권 규칙을 지키고, 한 번에 전체 경로를 이동하지 않아도 된다. + +```text +src/adapters/inbound/react/design-system/ + index.ts + tokens/ + primitive.css + semantic.css + component.css + token-contract.ts + primitives/ + button/ + field/ + checkbox/ + dialog/ + ... + patterns/ + async-surface/ + form/ + data-table/ + confirmation/ + ... + templates/ + standard-page/ + collection-page/ + detail-page/ + form-page/ + status-page/ + icons/ + icon.tsx + icon-button.tsx + semantic-icons.tsx + vendors/ + lucide.tsx + vendors/ + react-aria/ + testing/ + story-decorators.tsx + render-design-system.tsx +``` + +`index.ts`는 제품의 React inbound 코드가 사용할 public API다. 내부 파일 deep +import는 디자인 시스템 자체와 테스트에만 허용한다. 이 경계는 ESLint의 +`no-restricted-imports`로 검사한다. + +현재 `src/presentation`은 React inbound adapter 역할을 한다. TypeScript +마이그레이션 동안 기존 경로를 유지할 수 있지만, 최종 canonical target은 위 +경로다. 같은 컴포넌트를 `presentation`과 `adapters/inbound/react` 양쪽에 +복제하지 않고 feature 단위로 이동한다. + +## 4. 계층 계약 + +### 4.1 Tokens + +토큰은 시각적 결정을 이름으로 표현한다. 토큰은 세 계층으로 관리한다. + +```text +primitive token -> semantic token -> component token +``` + +예: + +```css +--palette-blue-600: ...; +--color-action: var(--palette-blue-600); +--button-primary-background: var(--color-action); +``` + +#### Primitive tokens + +원시 palette와 scale이다. 제품 코드에서 직접 소비하지 않는다. + +- palette +- spacing scale +- font size와 line height scale +- radius scale +- shadow scale +- duration과 easing scale +- fixed size scale + +#### Semantic tokens + +제품 코드와 대부분의 primitive가 소비하는 이름이다. + +- `surface`, `surface-muted`, `surface-elevated` +- `content`, `content-muted`, `content-inverse` +- `border`, `border-strong` +- `action`, `action-hover`, `action-pressed` +- `danger`, `warning`, `success`, `info` +- `focus-ring` +- `disabled-content`, `disabled-surface` + +#### Component tokens + +특정 primitive가 여러 semantic token을 조합할 때만 사용한다. + +- `button-primary-background` +- `field-border-invalid` +- `dialog-elevation` +- `navigation-active-background` + +컴포넌트 토큰은 제품별 variant를 만들기 위한 우회 경로가 아니다. 두 개 이상의 +컴포넌트가 같은 의미를 공유한다면 semantic token으로 승격한다. + +#### 필수 토큰 범주 + +| 범주 | 필수 내용 | +| --- | --- | +| Color | surface/content/border/action/status/focus, light/dark | +| Typography | family, size, line-height, weight, letter-spacing | +| Spacing | inset, inline, stack, section, page spacing scale | +| Size | control height, icon size, touch target, container width | +| Border | width, style, semantic border | +| Radius | control, surface, modal, full | +| Elevation | panel, popover, dialog, sticky shell | +| Z-layer | base, sticky, navigation, popover, modal, toast | +| Motion | fast/normal/slow duration, standard/emphasized easing | +| Breakpoint | compact, medium, wide와 container 계약 | +| Opacity | disabled, scrim, skeleton | + +토큰의 완료 조건은 다음과 같다. + +- light와 dark에서 모든 semantic token이 정의된다. +- `forced-colors`에서도 focus와 control 경계가 사라지지 않는다. +- 상태는 색상만으로 구분하지 않는다. +- 같은 raw value가 반복되면 named token으로 승격한다. +- 사용자 입력으로 CSS class나 CSS variable 이름을 조립하지 않는다. +- token contract test가 필수 token의 누락을 차단한다. +- chart나 canvas처럼 JavaScript 값이 필요한 경우에만 typed token accessor를 + 제공한다. + +## 5. 기본 컴포넌트 카탈로그 + +### 5.1 Primitives + +Primitive는 하나의 접근 가능한 상호작용 또는 작은 시각 단위를 제공한다. + +| 그룹 | 기본 제공 | 우선순위 | 핵심 계약 | +| --- | --- | --- | --- | +| Action | `Button` | 필수 | intent, size, disabled, pending, native semantics | +| Action | `LinkButton` | 필수 | navigation은 anchor/router link semantics 유지 | +| Action | `IconButton` | 필수 | accessible name 필수, 44px 권장 target | +| Form | `Field` | 필수 | label, description, error ID 조립 | +| Form | `TextField` | 필수 | text/email/password/search/autocomplete | +| Form | `TextArea` | 필수 | resize와 글자 수 안내 | +| Form | `Select` | 필수 | native 우선, 복합 선택은 headless 구현 | +| Form | `Checkbox` | 필수 | checked/indeterminate | +| Form | `RadioGroup` | 필수 | arrow-key와 group label | +| Form | `Switch` | 필수 | boolean setting 전용 | +| Form | `SearchField` | 필수 | clear action, submit semantics | +| Feedback | `Alert` | 필수 | inline feedback와 live-region 정책 분리 | +| Feedback | `Badge` | 필수 | color-only 금지 | +| Feedback | `Spinner` | 필수 | accessible label 또는 decorative | +| Feedback | `ProgressBar` | 필수 | determinate/indeterminate | +| Feedback | `Skeleton` | 필수 | 실제 layout과 유사한 크기, reduced motion | +| Feedback | `Toast` | 필수 | queue, 중복 방지, timeout pause | +| Surface | `Card` | 필수 | heading level 강제 금지, label 선택 가능 | +| Surface | `Separator` | 필수 | decorative/semantic 구분 | +| Overlay | `Dialog` | 필수 | modal semantics, focus trap/restore, Escape | +| Overlay | `Drawer` | 필수 | compact navigation과 side sheet | +| Overlay | `Popover` | 필수 | anchor, dismiss, collision | +| Overlay | `Tooltip` | 필수 | hover와 keyboard, 중요한 정보 단독 보유 금지 | +| Overlay | `Menu` | 필수 | roving focus, typeahead, Escape | +| Navigation | `Breadcrumbs` | 필수 | 현재 위치와 overflow | +| Navigation | `Tabs` | 필수 | manual/automatic activation 정책 | +| Navigation | `Pagination` | 필수 | current page, previous/next label | +| Utility | `VisuallyHidden` | 필수 | screen-reader-only content | +| Utility | `Portal` | 필수 | overlay root와 SSR-safe fallback | +| Utility | `FocusRing` | 필수 | input modality 인식 | +| Advanced | date/time picker | 선택 | locale/time zone 요구가 있을 때 | +| Advanced | file upload/dropzone | 선택 | upload adapter 요구가 있을 때 | +| Advanced | virtualizer/tree | 선택 | 실제 데이터 규모가 입증될 때 | + +Primitive API는 다음 규칙을 지킨다. + +- 기본 HTML semantics를 보존한다. +- `div onClick`로 button이나 link를 흉내 내지 않는다. +- `variant`, `size`, `tone`은 closed union과 정적 class map을 사용한다. +- pending은 focus를 잃게 하는 무조건적인 `disabled`와 구분한다. +- controlled와 uncontrolled 지원 여부를 문서화한다. +- ref 전달과 focus contract를 테스트한다. +- `className`은 escape hatch이지 public variant를 대체하지 않는다. +- 임의의 polymorphic `as`보다 `Button`과 `LinkButton`처럼 semantics가 명확한 + API를 우선한다. +- visual-only prop이 도메인 의미를 표현하지 않도록 한다. + +### 5.2 Patterns + +Pattern은 여러 primitive를 조합해 반복되는 사용자 문제를 해결한다. + +| Pattern | 필수 내용 | +| --- | --- | +| `AsyncSurface` | loading, success, empty, terminal error, stale, refresh | +| `AccessSurface` | auth required, forbidden, not found | +| `Form` | submit, error summary, first-invalid focus, pending | +| `ConfirmationDialog` | destructive action 설명과 명시적 확인 | +| `ToastRegion` | queue, announcement, dismiss, focus policy | +| `SearchFilterToolbar` | search, filter, reset, result count | +| `DataTable` | caption, sorting, selection, responsive fallback | +| `PaginationBar` | result range와 page navigation | +| `NavigationDrawer` | mobile focus scope와 background inert | +| `DisclosureGroup` | help/settings section | + +Pattern은 application failure object 전체를 렌더링하지 않는다. 안전한 message key, +사용자 action, 표시 가능한 metadata만 받는다. + +### 5.3 Templates + +Template은 페이지 레이아웃과 상태 slot을 제공한다. API 호출과 도메인 use case는 +소유하지 않는다. + +#### `StandardPageTemplate` + +- breadcrumb 또는 back navigation +- eyebrow +- `h1` +- description +- status/metadata +- primary/secondary actions +- main content와 aside slot + +#### `CollectionPageTemplate` + +- page header +- search/filter/sort toolbar +- result count +- loading/empty/error slot +- table/list/card-grid slot +- pagination slot +- compact viewport에서의 대체 배치 + +#### `DetailPageTemplate` + +- breadcrumb/back +- title과 entity status +- page actions +- description list/section slot +- loading/not-found/forbidden/error 상태 + +#### `FormPageTemplate` + +- heading과 설명 +- error summary +- field section +- sticky 또는 inline action bar +- submit/cancel +- submitting, success, conflict +- unsaved-change navigation blocker 연결 지점 + +#### `StatusPageTemplate` + +- 401, 403, 404, 500, offline, maintenance +- safe description +- primary recovery action +- optional support reference +- raw endpoint, stack, token 노출 금지 + +Template의 heading 순서는 slot 소비자가 임의로 깨뜨리지 못하게 예제와 테스트로 +고정한다. 다만 `Card` 같은 하위 primitive가 무조건 `h3`를 생성해서도 안 된다. + +## 6. Lucide 아이콘 facade + +[Lucide for React 공식 문서](https://lucide.dev/guide/react)는 각 아이콘을 독립 +React component로 제공하며 명시적으로 import한 아이콘만 번들에 포함될 수 있는 +tree-shaking 구조를 제공한다. 기본 아이콘 공급자로 사용하기에 적합하지만 제품 +코드가 공급자 API에 결합되면 안 된다. + +### 6.1 필수 규칙 + +1. `lucide-react` import는 `icons/vendors/lucide.tsx`에서만 허용한다. +2. 제품 코드에는 Lucide component type, icon name, stroke prop을 노출하지 않는다. +3. 디자인 시스템이 승인한 작은 아이콘 집합만 명시적으로 import한다. +4. 모든 아이콘을 이름으로 동적 import하는 범용 `DynamicIcon`은 기본 제공하지 + 않는다. +5. 아이콘 색은 기본적으로 `currentColor`를 사용한다. +6. 크기와 stroke는 `--icon-size-*`, `--icon-stroke-*` 토큰을 사용한다. +7. 장식 아이콘은 기본적으로 `aria-hidden="true"`와 `focusable="false"`다. +8. 정보를 단독으로 전달하는 아이콘은 local `Icon` API의 `label`을 통해 + `role="img"`와 accessible name을 가진다. +9. 버튼 안의 아이콘은 장식으로 처리하고 버튼 자체에 visible label 또는 + `aria-label`을 둔다. +10. 상태를 아이콘이나 색상 하나만으로 전달하지 않는다. + +### 6.2 목표 API 예시 + +아래 예시는 방향을 설명한다. 실제 type과 경로는 TypeScript 전환 작업에서 +확정한다. + +```tsx +import { MenuIcon } from "@/presentation/design-system/icons"; +import { IconButton } from "@/presentation/design-system"; + + + + +``` + +vendor 파일은 의미 이름과 공급자 이름을 분리한다. + +```tsx +import { + Menu as LucideMenu, + X as LucideClose, + AlertTriangle as LucideWarning, +} from "lucide-react"; + +export const MenuGlyph = LucideMenu; +export const CloseGlyph = LucideClose; +export const WarningGlyph = LucideWarning; +``` + +`MenuGlyph` 같은 vendor export는 `semantic-icons.tsx` 밖으로 다시 노출하지 +않는다. 제품 코드는 `MenuIcon`, `CloseIcon`, `WarningIcon`만 사용한다. + +### 6.3 아이콘 추가 완료 조건 + +- 기존 semantic icon으로 표현할 수 없는지 먼저 확인했다. +- 서로 다른 제품 기능이 같은 의미 아이콘을 공유한다. +- accessible name과 decorative 여부를 결정했다. +- light/dark/high-contrast에서 보인다. +- 200% zoom과 compact viewport에서 잘리지 않는다. +- 신규 import 후 bundle budget을 통과한다. +- 공급자 교체 시 제품 코드 수정이 필요하지 않다. + +## 7. Headless UI 선택 기준 + +복잡한 overlay, collection, focus management를 직접 구현하기 전에 native +platform과 검증된 headless UI를 평가한다. + +- [React Aria 공식 시작 문서](https://react-aria.adobe.com/getting-started) +- [Radix Primitives 공식 소개](https://www.radix-ui.com/primitives/docs/overview/introduction) + +### 7.1 선택 순서 + +1. native HTML만으로 요구 semantics와 모든 지원 브라우저 동작을 충족하는지 + 확인한다. +2. native 구현이 불충분하면 React Aria와 Radix를 평가한다. +3. 한 프로젝트에서 같은 문제를 해결하는 headless 공급자를 둘 이상 기본값으로 + 사용하지 않는다. +4. 선택 결과와 버전·라이선스·bundle 영향을 ADR에 기록한다. +5. 공급자 component를 local primitive로 감싼 뒤에만 제품 코드에 노출한다. + +### 7.2 평가표 + +| 기준 | 확인 질문 | +| --- | --- | +| Semantics | WAI-ARIA pattern과 native semantics를 올바르게 사용하는가 | +| Keyboard | roving focus, typeahead, Escape, arrow key가 완전한가 | +| Focus | trap, restore, initial focus, nested overlay가 안전한가 | +| Input modality | mouse, touch, keyboard, screen reader가 동일하게 동작하는가 | +| i18n | RTL, locale number/date, IME를 지원하는가 | +| Styling | semantic token과 Tailwind/CSS layer에 결합 가능한가 | +| Bundle | component 단위 import와 tree shaking이 가능한가 | +| React/Vite | 현재 React와 Vite 조합을 공식 지원하는가 | +| SSR | future SSR profile에서 hydration ID가 안정적인가 | +| Testing | 접근성·상호작용 테스트 자료와 utility가 있는가 | +| Maintenance | release cadence, security 대응, license가 허용 가능한가 | + +현재 스켈레톤의 접근성·국제화 목표에는 React Aria Components가 우선 후보다. +Radix는 overlay와 primitive composition을 중심으로 평가할 수 있다. 최종 선택은 +실제 prototype으로 `Select`, `Menu`, `Drawer` 세 가지를 구현해 다음을 비교한 뒤 +확정한다. + +- keyboard matrix +- screen reader announcement +- RTL +- mobile touch +- dark/high-contrast +- gzip 증가량 +- local API로 감쌀 때 필요한 코드량 + +공급자를 선택하더라도 `SelectProps = AriaSelectProps`처럼 vendor type alias를 +그대로 공용 API로 만들지 않는다. 제품이 실제로 지원하는 의미만 local prop으로 +닫는다. + +## 8. 접근성 계약 + +목표는 WCAG 2.2 AA에 맞춘 기본 동작이다. 자동 도구 통과는 적합성 선언이 아니며, +키보드와 보조기술 검토를 함께 수행한다. + +### 8.1 모든 컴포넌트의 공통 기준 + +- 올바른 native element와 role을 사용한다. +- visible label 또는 accessible name이 있다. +- keyboard만으로 모든 action을 실행할 수 있다. +- focus 순서가 DOM과 시각 순서에 맞는다. +- focus indicator를 제거하지 않는다. +- disabled와 readonly를 구분한다. +- 상태는 색상만으로 전달하지 않는다. +- 오류는 해당 control과 programmatically 연결한다. +- 필요한 변경만 live region으로 한 번 알린다. +- `prefers-reduced-motion`에서 불필요한 motion을 제거한다. +- 200% text zoom과 400% page zoom에서 정보가 손실되지 않는다. +- 320 CSS px reflow에서 양방향 scroll을 강요하지 않는다. +- touch target은 기본 44x44 CSS px를 목표로 한다. +- forced-colors에서 border, focus, selected state가 사라지지 않는다. +- RTL에서 logical direction과 key behavior를 검증한다. +- 한글·일본어·중국어 IME composition 중 입력을 조기에 검증하거나 제출하지 + 않는다. + +### 8.2 Overlay 기준 + +- 열기 trigger를 기록한다. +- 열릴 때 의미 있는 initial focus를 둔다. +- modal일 때 focus가 내부를 벗어나지 않는다. +- 배경 content를 `inert` 또는 동등한 방식으로 비활성화한다. +- Escape와 명시적 닫기 action을 제공한다. +- 닫은 뒤 trigger 또는 안전한 대체 위치로 focus를 복원한다. +- nested overlay와 route transition 중 orphan portal을 남기지 않는다. + +### 8.3 Form 기준 + +- label, description, error가 동일한 field ID 체계로 연결된다. +- required는 시각적 기호와 programmatic 상태를 함께 가진다. +- submit 실패 시 error summary로 focus를 이동한다. +- error summary 항목은 해당 field로 이동한다. +- async validation은 현재 입력보다 오래된 결과를 폐기한다. +- pending 상태를 screen reader에 알리되 같은 문구를 반복하지 않는다. +- 서버 오류의 raw body, stack, 내부 field path를 출력하지 않는다. + +## 9. 국제화 계약 + +디자인 시스템 primitive는 한국어 문구를 내부 기본값으로 숨기지 않는다. +접근성 label이나 오류 문구가 필요하면 명시적인 prop 또는 message key를 받는다. + +필수 국제화 기반: + +- `LocaleProvider` +- typed message key +- fallback locale +- ``과 `dir` 갱신 +- `Intl.DateTimeFormat` +- `Intl.NumberFormat` +- `Intl.ListFormat` +- plural/select message +- locale별 validation message +- pseudo-locale +- RTL story와 E2E smoke + +금지 패턴: + +- 번역 문장 중간에 JSX 문자열을 연결한다. +- 날짜를 `substring`이나 고정 구분자로 조립한다. +- icon direction을 locale 확인 없이 좌/우 이름으로 고정한다. +- route title, navigation label, toast message를 JSX literal로 분산한다. +- 번역 누락 시 빈 문자열을 렌더링한다. + +Storybook toolbar에서 최소한 다음 조합을 전환할 수 있어야 한다. + +- `ko-KR`, light +- `en-US`, light +- `en-US`, dark +- pseudo-locale +- 대표 RTL locale + +## 10. Storybook과 시각 검증 + +현재 `/examples/ui`는 실행 중인 앱 셸과 primitive 통합을 확인하는 데 유지한다. +그러나 runtime gallery는 isolated component workshop을 대체하지 않는다. + +[Storybook 공식 UI 테스트 문서](https://storybook.js.org/docs/writing-tests)는 +story를 기반으로 interaction, accessibility, visual test를 구성하는 방법을 +제공한다. + +### 10.1 Storybook 필수 구성 + +- Vite 기반 Storybook +- TypeScript CSF story +- global theme toolbar +- locale/RTL toolbar +- compact/wide viewport +- Router, Theme, Locale, Session, Query decorator +- `@storybook/addon-a11y` +- a11y 결과를 CI에서 error로 처리 +- interaction `play` test +- story build gate + +### 10.2 각 컴포넌트의 필수 story + +- default +- 모든 semantic variant +- disabled와 readonly +- pending/loading +- 오류 +- 긴 문구 +- 빈 값 +- light/dark +- compact viewport +- keyboard interaction +- 해당되는 경우 open/closed, controlled/uncontrolled + +Form과 overlay는 다음 story를 추가한다. + +- submit 실패와 error summary +- async pending +- server field error +- Escape close +- outside interaction +- initial focus +- focus restoration +- nested content와 long content + +### 10.3 시각 회귀 + +기본 시각 회귀는 Playwright `toHaveScreenshot()`을 사용해 저장소 안에서 실행할 +수 있게 한다. Chromatic 같은 외부 서비스는 선택 사항이다. + +필수 안정화: + +- 동일한 Linux image, browser version, font +- animation과 caret 비활성화 +- 시간·랜덤·network 응답 고정 +- 동적 ID와 민감 데이터 mask +- light/dark baseline +- compact/wide baseline +- 변경된 baseline은 코드 리뷰 대상 + +failure screenshot은 시각 회귀가 아니다. 의도된 baseline과 실제 렌더링을 +비교하는 assertion이 있어야 한다. + +### 10.4 테스트 계층 + +| 계층 | 검증 대상 | +| --- | --- | +| Type check | prop union, ref, event와 slot type | +| Unit | token/variant map, pure formatter와 state reducer | +| Component | native semantics, keyboard, focus, callback | +| Story interaction | 실제 browser의 isolated behavior | +| Story a11y | 모든 주요 state의 axe | +| Visual | pixel/layout/theme regression | +| E2E | 앱 셸, route, form/query integration | +| Manual | screen reader, zoom, touch, forced-colors | + +DOM snapshot은 보이는 UI를 보장하지 않으므로 public markup contract가 꼭 필요한 +경우에만 사용한다. + +## 11. 컴포넌트 추가 Recipe + +새 component를 추가할 때 다음 순서를 생략하지 않는다. + +### Step 1. 문제와 계층을 결정한다 + +다음 질문을 issue 또는 설계 메모에 기록한다. + +- 단일 control인가, 반복되는 조합인가, 페이지 구조인가? +- primitive, pattern, template 중 어디에 속하는가? +- 기존 component의 variant로 해결할 수 있는가? +- 제품 전용 의미를 공통 디자인 시스템으로 잘못 올리는 것은 아닌가? +- native HTML로 충분한가? + +### Step 2. 상태 행렬을 작성한다 + +최소 상태: + +```text +default +hover +focus-visible +active/pressed +disabled +pending +invalid +light +dark +compact +long-content +``` + +선택/overlay component는 open, selected, indeterminate, empty, loading도 포함한다. + +### Step 3. 접근성 명세를 작성한다 + +- element/role +- accessible name +- keyboard table +- focus entry/exit/restore +- announcement +- error association +- reduced motion +- touch와 screen reader + +명세가 불명확하면 구현보다 먼저 native, React Aria, Radix prototype으로 검증한다. + +### Step 4. API를 닫는다 + +- TypeScript public props를 정의한다. +- semantic `variant`를 사용하고 raw color prop을 노출하지 않는다. +- callback 이름과 payload를 domain-neutral하게 정한다. +- controlled/uncontrolled 정책을 정한다. +- `className` escape hatch의 범위를 정한다. +- vendor prop과 type을 public API에 노출하지 않는다. + +### Step 5. 필요한 토큰을 추가한다 + +- 기존 semantic token으로 표현 가능한지 확인한다. +- raw 값 반복을 추가하지 않는다. +- light/dark/forced-colors 값을 함께 정의한다. +- token contract test를 갱신한다. + +### Step 6. 구현한다 + +- native semantics 우선 +- local vendor facade만 import +- static variant map +- ref/focus 지원 +- DOM 구조 최소화 +- render 중 전역 상태 변경 금지 +- 제품 API나 application service import 금지 + +### Step 7. Story를 작성한다 + +- 상태 행렬을 모두 story로 표현한다. +- interaction test를 작성한다. +- dark, compact, long-content를 포함한다. +- a11y test를 error mode로 실행한다. + +### Step 8. 자동 테스트를 작성한다 + +- role/name 중심 query +- keyboard와 focus +- disabled/pending +- callback +- controlled state +- 오류와 live region +- 필요한 visual baseline + +구현 class나 내부 DOM 순서만 확인하는 brittle test는 피한다. + +### Step 9. 통합 예제를 추가한다 + +- `/examples/ui`에는 primitive를 추가한다. +- `/examples/states`에는 새로운 공통 상태를 추가한다. +- pattern/template은 domain-neutral fixture로 실제 조합을 보여 준다. +- production profile에서 예제 route를 제외할 수 있는 계약을 유지한다. + +### Step 10. 문서와 public export를 갱신한다 + +- 사용 목적 +- 사용하지 말아야 할 경우 +- props와 variant +- keyboard +- 접근성 책임 +- i18n +- 예제 +- public `index.ts` export +- 변경 로그 + +### Step 11. 게이트를 실행한다 + +최소 실행 범위: + +```bash +corepack pnpm check:types +corepack pnpm lint +corepack pnpm check:architecture +corepack pnpm test:component +corepack pnpm test:e2e +corepack pnpm test:a11y +corepack pnpm build +corepack pnpm check:bundle +``` + +Storybook과 visual gate가 도입된 뒤에는 story build, interaction, story a11y, +visual comparison도 필수로 추가한다. + +## 12. Definition of Done + +컴포넌트는 아래 항목 중 자신의 state/capability matrix에 해당하는 항목을 +충족해야 `완료`다. 적용되지 않는 항목은 체크를 생략하지 말고 `N/A`와 이유를 +component contract에 기록한다. 예를 들어 `Separator`에는 pending/error/IME가, +읽기 전용 `Card`에는 controlled state와 field error가 적용되지 않는다. + +### API와 아키텍처 + +- [ ] primitive/pattern/template 소유권이 명확하다. +- [ ] public TypeScript API가 closed union으로 정의되었다. +- [ ] 제품 코드가 vendor package를 직접 import하지 않는다. +- [ ] domain/application dependency가 없다. +- [ ] public barrel을 통해 소비할 수 있다. +- [ ] 상태를 소유하는 경우 controlled/uncontrolled 계약이 문서화되었고, focus + target이 있는 경우 ref 계약이 문서화되었다. + +### Styling + +- [ ] raw 색상과 반복되는 임의 값이 없다. +- [ ] semantic token을 사용한다. +- [ ] light/dark가 완성되었다. +- [ ] compact/wide reflow가 된다. +- [ ] long text와 번역 확장을 견딘다. +- [ ] forced-colors에서도 의미가 유지된다. +- [ ] bundle budget을 통과한다. + +### 접근성 + +- [ ] native semantics와 accessible name이 있다. +- [ ] keyboard 동작이 명세와 일치한다. +- [ ] focus indicator, 이동, 복원이 올바르다. +- [ ] 상태가 색상에만 의존하지 않는다. +- [ ] 오류나 설명을 제공하는 component는 이들을 programmatically 연결한다. +- [ ] reduced-motion을 존중한다. +- [ ] 200%/400% zoom과 320px reflow를 확인했다. +- [ ] screen reader 수동 검토 항목이 정의되었다. + +### 국제화 + +- [ ] 사용자 문구를 소유하는 component는 이를 내부 literal로 고정하지 않는다. +- [ ] 날짜·숫자·목록을 표시하는 component는 locale formatter를 사용한다. +- [ ] pseudo-locale에서 잘리지 않는다. +- [ ] RTL에서 배치와 키보드가 올바르다. +- [ ] 문자 입력을 받는 component는 IME 입력을 깨뜨리지 않는다. + +### 테스트와 문서 + +- [ ] component behavior test가 있다. +- [ ] 모든 주요 상태 story가 있다. +- [ ] story interaction test가 있다. +- [ ] automated a11y가 통과한다. +- [ ] 필요한 visual baseline이 있다. +- [ ] runtime gallery 또는 pattern fixture가 있다. +- [ ] 사용법, 금지 사례, 접근성 책임이 문서화되었다. +- [ ] 전체 품질·아키텍처·bundle gate가 통과한다. + +## 13. 금지 패턴 + +- 제품 페이지에서 `lucide-react` 직접 import +- 제품 페이지에서 React Aria/Radix 직접 import +- `div`와 keyboard handler로 native button을 재구현 +- icon-only button에 accessible name 누락 +- 문자열 icon name으로 전체 icon package를 동적 로딩 +- 사용자 값으로 Tailwind/CSS class 조립 +- raw hex/OKLCH 값을 JSX나 component CSS에 반복 +- `as="div"`처럼 semantics를 무제한 변경하는 public API +- primitive에서 API/query/auth/storage를 직접 호출 +- 모든 상태를 하나의 전역 store에 저장 +- 오류 raw body, URL, header, token, stack 표시 +- locale 문장을 문자열 덧셈으로 구성 +- axe 통과만으로 접근성 완료 선언 +- failure screenshot만으로 시각 회귀 완료 선언 +- Storybook story 없이 runtime gallery 하나로 모든 variant를 대표 + +## 14. 단계별 도입 순서 + +1. TypeScript public API와 디자인 시스템 public barrel을 만든다. +2. token을 primitive/semantic/component 계층으로 분리한다. +3. 기존 Button, TextField, Card, Alert, Badge, Dialog를 새 계약으로 이동한다. +4. Lucide local facade와 `IconButton`을 추가하고 문자 glyph를 제거한다. +5. Field foundation과 필수 form primitives를 추가한다. +6. React Aria와 Radix prototype을 비교하고 headless ADR을 확정한다. +7. Drawer, Select, Menu, Popover, Tooltip을 local facade로 구현한다. +8. pattern과 page template을 추가한다. +9. locale provider, pseudo-locale, RTL 검증을 추가한다. +10. Storybook, story a11y, interaction test를 추가한다. +11. pinned browser 환경의 visual regression gate를 추가한다. +12. `/examples/ui`와 `/examples/states`를 통합 smoke gallery로 유지한다. + +이 순서는 라이브러리 수를 늘리는 것이 목표가 아니다. 각 단계가 제품 개발자가 +중복 구현할 문제를 하나씩 제거하고, 외부 공급자를 교체할 수 있는 로컬 계약과 +검증 증거를 남기는 것이 목표다. diff --git a/docs/styling/design-tokens.md b/docs/styling/design-tokens.md index 178d367b..baf91eb2 100644 --- a/docs/styling/design-tokens.md +++ b/docs/styling/design-tokens.md @@ -39,3 +39,10 @@ Arbitrary-value policy: The removable sample may demonstrate tokens, but production starter modules do not import from `src/sample/contract-fixture`. + +This file documents the currently implemented token and primitive baseline. +The [design-system platform contract](./design-system-platform.md) defines the +target token layers, component catalog, local Lucide/headless-library +facades, page patterns, accessibility and internationalization rules, isolated +workshop, and component-authoring recipe. Items in that target document are not +treated as implemented until their acceptance tests pass. diff --git a/docs/testing/frontend-platform-testing-strategy.md b/docs/testing/frontend-platform-testing-strategy.md new file mode 100644 index 00000000..5f3e6c68 --- /dev/null +++ b/docs/testing/frontend-platform-testing-strategy.md @@ -0,0 +1,1283 @@ +# 프론트엔드 플랫폼 테스트 전략 + +이 문서는 도메인 기능을 추가하기 전과 추가한 후에 프론트엔드 플랫폼의 위험을 +어느 테스트 계층에서 차단할지 정의한다. 목표는 테스트 개수를 늘리는 것이 아니라, +실패 원인과 가장 가까운 계층에서 빠르고 결정적으로 결함을 발견하고 실제 +브라우저·실제 production build에서만 드러나는 위험을 별도 게이트로 닫는 것이다. + +이 문서는 다음 공식 문서를 기술 기준으로 사용한다. + +- [Vitest 공식 가이드](https://vitest.dev/guide/) +- [Mock Service Worker 공식 문서](https://mswjs.io/docs/) +- [Playwright 공식 문서](https://playwright.dev/docs/intro) +- [Playwright 시각 비교 문서](https://playwright.dev/docs/test-snapshots) +- [Storybook UI 테스트 문서](https://storybook.js.org/docs/writing-tests) + +## 1. 테스트 원칙 + +1. 테스트는 구현 계층이 아니라 사용자·운영 위험에서 출발한다. +2. 같은 위험을 모든 계층에서 반복해 검증하지 않는다. +3. pure policy와 codec은 빠른 unit/contract test에서 가능한 모든 분기를 닫는다. +4. 브라우저 API, React lifecycle, focus, layout은 DOM 또는 실제 브라우저에서 + 검증한다. +5. HTTP client를 stub하는 대신 네트워크 경계는 MSW로 검증한다. +6. production boot와 route는 개발용 component fixture만으로 완료 처리하지 않는다. +7. 성공 경로만으로 완료하지 않는다. timeout, abort, schema mismatch, 권한, + 충돌, 재시도 소진을 포함한다. +8. 접근성 자동 검사와 시각 회귀는 서로 대체하지 않는다. +9. coverage 숫자는 누락 탐지 신호이며 behavior 완료 증거가 아니다. +10. flaky test를 자동 재시도로 숨기거나 `skip` 상태로 무기한 유지하지 않는다. +11. test-only 우회 경로와 mock credential을 production bundle에 포함하지 않는다. +12. 모든 CI gate는 실패 시 종료 코드가 non-zero여야 하며 + `continue-on-error`로 낮추지 않는다. + +## 2. 현재 기준선 + +현재 저장소는 테스트 계층과 CI 증거 경로를 명시적으로 분리한다. + +### 2.1 실행 명령 + +`package.json`에는 다음 계층이 있다. + +- `test:runtime-schema` +- `test:unit` +- `test:component` +- `test:integration` +- `test:e2e` +- `test:a11y` +- `review:a11y-manual` +- `test:sample-removal` +- `test:performance` + +Vitest 결과는 JUnit으로 `artifacts/tests/`에 기록되고 Playwright는 HTML report, +trace, failure screenshot을 보존한다. `config/ci/gates.json`은 품질 gate와 증거 +경로를 등록하며 `.gitea/workflows/quality-gates.yml`은 merge/release/production/ +field/documentation 단계를 구성한다. + +### 2.2 확인된 강점 + +- runtime config와 release manifest schema test가 분리되어 있다. +- retry, error classification, compatibility, performance policy 같은 pure logic에 + unit test가 있다. +- React Testing Library와 `user-event`로 component behavior를 검사한다. +- MSW Node server로 HTTP 경계를 실제 `fetch` 수준에서 격리한다. +- 잘못된 architecture/security/type fixture가 실제로 거절되는지 검증한다. +- Chromium, Firefox, WebKit 프로젝트가 구성되어 있다. +- 등록된 모든 route에 axe 검사가 있다. +- 320px reflow와 mobile navigation을 E2E로 확인한다. +- release build의 bundle과 lab performance budget이 별도 gate다. + +### 2.3 확인된 공백 + +#### 테스트 TypeScript가 typecheck 대상이 아니다 + +현재 `check:types`는 `tsconfig.json`의 include 범위에 의존하며 tests 전체의 +callback, mock, fixture, custom matcher type을 별도 프로젝트로 검사하지 않는다. +TypeScript 전환 뒤 Vitest가 test file을 변환해 실행할 수 있다는 사실은 +`tsc` typecheck를 대체하지 않는다. + +#### 실제 bootstrap integration test가 없다 + +`tests/component/bootstrap-shell.test.jsx`는 production bootstrap을 import하지 +않고 테스트 내부의 ``만 렌더링한다. E2E는 실제 entry를 통과하지만, +다음 실패를 작은 통합 테스트에서 식별하기 어렵다. + +- runtime config fetch 실패 +- config/manifest mismatch +- adapter composition 실패 +- provider 순서 또는 누락 +- external auth owner 유무 +- product tree를 마운트하기 전 fail-closed +- boot error shell의 safe metadata +- StrictMode와 unmount cleanup + +#### TanStack Query의 React integration test가 없다 + +Query cache adapter의 명령형 `read/write/invalidate` unit test는 있지만 +`useQuery`, `useMutation`, cancellation, stale/background refresh, optimistic +rollback을 사용하는 production presentation adapter가 아직 없다. 따라서 query +provider가 마운트되어도 React 사용자의 실제 상태 전환은 검증되지 않는다. + +#### Form 테스트가 단일 TextField 흐름에 머문다 + +현재 component/E2E는 label, description, error association과 빈 값 submit을 +검사한다. error summary, 첫 오류 focus, async validation race, 422 field error, +double submit, dirty navigation, mutation conflict는 없다. + +#### Route registry와 실행 tree가 별도로 테스트된다 + +registry snapshot과 일부 navigation/access policy test는 있으나 다음 계약을 +강제하지 않는다. + +- 모든 route ID에 lazy runtime module이 존재하는가 +- params/search가 실제 codec으로 검증되는가 +- deep link와 basename refresh가 동작하는가 +- chunk load failure가 1회 reload/support surface로 연결되는가 +- route error boundary가 location 변경 시 reset되는가 +- scroll restoration과 form navigation blocker가 동작하는가 + +#### Storybook과 시각 회귀가 없다 + +`/examples/ui`는 통합 gallery지만 component별 모든 state를 격리하지 않는다. +Storybook story, interaction story, story-level axe, `toHaveScreenshot()` baseline이 +없다. `screenshot: "only-on-failure"`는 디버깅 증거이며 시각 회귀 테스트가 아니다. + +#### MSW scenario가 공유되지 않는다 + +integration file마다 `setupServer`, handler, response body를 다시 정의한다. +Node integration, Storybook browser, feature component test, E2E mock service가 같은 +시나리오 이름과 contract fixture를 공유하지 않는다. + +#### E2E가 개발 서버를 대상으로 한다 + +현재 Playwright web server는 `pnpm dev`다. route behavior 확인에는 유효하지만 +다음 release 위험은 production build/preview에서만 확인할 수 있다. + +- hashed lazy chunk +- source 변환과 tree shaking +- base path +- deep-link fallback +- build-time environment +- release manifest와 runtime config 조합 +- minified code의 chunk failure + +#### Coverage가 실행·차단되지 않는다 + +`vitest.config.js`에는 reporter만 선언되어 있고 coverage provider, script, +threshold, diff policy가 없다. + +## 3. 위험 기반 테스트 계층 + +우선순위 의미: + +- `P0`: 오류가 발생하면 애플리케이션 부팅, 데이터 무결성, 인증, 주요 사용 흐름, + 보안 또는 접근성이 깨지는 위험 +- `P1`: 주요 기능 품질, 브라우저 호환성, 운영 복구와 개발 생산성을 저하하는 위험 +- `P2`: 고급 기능 또는 특정 제품 profile에서만 필요한 위험 + +| 위험 | 우선순위 | 가장 가까운 테스트 | 추가 증거 | +| --- | --- | --- | --- | +| runtime config/manifest mismatch | P0 | schema + bootstrap integration | built-dist smoke | +| secret-like client config | P0 | negative contract fixture | browser security gate | +| HTTP request/response schema mismatch | P0 | adapter integration + MSW | feature integration | +| 중복 retry 또는 unsafe mutation retry | P0 | unit policy + MSW integration | E2E degraded scenario | +| 401 복구 loop | P0 | auth/HTTP integration | protected route E2E | +| query cancellation/stale state 오류 | P0 | query hook integration | route E2E | +| optimistic mutation rollback 오류 | P0 | mutation integration | visual state smoke | +| form validation/422 mapping 오류 | P0 | form component integration | route E2E | +| route access/deep-link 오류 | P0 | route contract/component | built-dist E2E | +| lazy chunk 복구 loop | P0 | use-case unit + release E2E | runbook drill | +| keyboard/focus/accessible name 오류 | P0 | component + story a11y | E2E/manual | +| theme/token contrast 오류 | P0 | token contract + axe | visual/manual | +| responsive overflow | P1 | component layout + E2E | visual | +| 브라우저 엔진 차이 | P1 | 3-engine E2E | manual device smoke | +| visual regression | P1 | pinned Chromium screenshot | reviewer approval | +| i18n/RTL/long text clipping | P1 | story + visual | route smoke | +| telemetry redaction | P0 | unit/adapter integration | bootstrap smoke | +| bundle 증가 | P1 | build manifest budget | release gate | +| render/performance 저하 | P1 | component profiler 선택 | lab/field metrics | +| virtualized collection | P2 | browser component | large-data E2E | +| offline/PWA persistence | P2 | service-worker integration | installable build E2E | + +## 4. TypeScript 테스트 계약 + +TypeScript 전환 후 production과 test typecheck를 분리하되 둘 다 merge gate로 +차단한다. + +### 4.1 목표 구성 + +```text +tsconfig.base.json +tsconfig.app.json +tsconfig.node.json +tsconfig.test.json +tsconfig.json # project references +``` + +`tsconfig.test.json`에는 다음을 포함한다. + +- `tests/**/*.ts` +- `tests/**/*.tsx` +- `src/**/*.stories.ts` +- `src/**/*.stories.tsx` +- `tests/setup.ts` +- custom matcher type +- MSW handlers와 factories +- Playwright tests는 필요하면 별도 `tsconfig.e2e.json` + +권장 명령: + +```bash +tsc --noEmit -p tsconfig.app.json +tsc --noEmit -p tsconfig.test.json +tsc --noEmit -p tsconfig.e2e.json +``` + +### 4.2 Type-level test + +다음은 runtime test가 아니라 compile-time test로 닫는다. + +- route ID와 runtime route map의 exhaustive mapping +- `routePath` params 누락과 잘못된 key +- query key factory input/output +- component variant closed union +- form schema와 default value shape +- use case command/result +- public port 구현 누락 +- vendor type이 public facade 밖으로 새는 문제 + +필요하면 Vitest의 `expectTypeOf`를 사용하되 실제 `tsc`도 실행한다. 의도적으로 +실패해야 하는 fixture는 독립 `tsconfig`와 `@ts-expect-error` 설명을 사용한다. +부정 fixture가 실수로 통과하면 gate가 실패해야 한다. + +### 4.3 금지 사항 + +- test file을 `any`로 우회 +- `as unknown as`로 mock contract를 무조건 통과 +- production type error를 test mock에서 숨김 +- test는 실행되므로 typecheck도 된다고 가정 +- 의도와 설명 없는 `@ts-ignore` + +## 5. Unit과 Contract 테스트 + +### 5.1 Unit 대상 + +DOM과 network 없이 결정 가능한 로직은 unit test로 검증한다. + +- error classification +- retry eligibility, attempt cap, backoff와 jitter bound +- query key canonicalization +- route access decision +- params/search codec +- locale formatter wrapper +- token/variant static map +- async view-state reducer +- form DTO mapper +- optimistic patch/rollback reducer +- chunk recovery decision +- redaction +- performance/readiness formula + +시간, random, UUID는 주입하거나 fake timer로 통제한다. 실제 `setTimeout`을 +기다리는 test를 만들지 않는다. + +### 5.2 Contract 대상 + +registry와 외부 boundary의 안정된 shape를 검증한다. + +- runtime config schema +- release manifest schema +- API operation registry +- request/response schema registry +- error registry +- route registry/runtime map +- storage key registry +- telemetry event registry +- design token registry +- mock scenario registry + +inline snapshot은 사람이 검토 가능한 작고 안정된 registry에만 사용한다. +큰 payload, DOM tree, CSS 전체를 snapshot으로 고정하지 않는다. + +### 5.3 Negative fixture + +positive test만으로 control을 증명하지 않는다. + +```text +tests/fixtures/ + architecture/ + allowed/ + forbidden/ + security/ + allowed/ + forbidden/ + typecheck/ + allowed/ + forbidden/ + routes/ + malformed-search/ + contracts/ + malformed-envelope/ +``` + +부정 fixture는 실제 production validator와 동일한 entry로 실행한다. + +## 6. 실제 Bootstrap Integration + +bootstrap test는 production entry의 로직을 재작성하지 않는다. `main.tsx`는 DOM +탐색과 최종 호출만 남기고, 테스트 가능한 함수로 boot를 추출한다. + +목표 API 예: + +```ts +bootstrapApplication({ + rootElement, + fetcher, + host, + buildConfig, + createRoot, +}); +``` + +production은 실제 dependency를 넘기고 integration test는 deterministic +dependency를 넘긴다. + +### 6.1 필수 시나리오 + +| 시나리오 | 기대 | +| --- | --- | +| valid config + coherent manifest | product tree가 한 번 마운트 | +| config fetch network failure | product tree 미마운트, safe boot shell | +| config non-JSON | safe code만 표시 | +| forbidden secret-like key | fail-closed | +| config schema mismatch | issue detail/endpoint/body 비노출 | +| manifest fetch/shape failure | safe release failure | +| config/build/release mismatch | product tree 미마운트 | +| external auth owner 존재 | external session adapter 선택 | +| external auth owner 누락 | integration-failed session | +| local demo auth | local/development에서만 허용 | +| telemetry disabled | network/queue side effect 없음 | +| storage unavailable | memory/failure policy대로 boot | +| StrictMode | subscription/cleanup leak 없음 | +| unmount | listener, timer, pending request 정리 | + +### 6.2 Provider 조립 검증 + +현재 production provider 순서를 사실대로 검증한다. + +```text +QueryClientProvider + -> BrowserRouter + -> ThemeProvider + -> SessionProvider + -> AppShell +``` + +각 provider를 mock component로 대체해 문자열 순서만 검사하지 않는다. 실제 +Context/hook을 소비하는 작은 probe route를 렌더링해 provider가 사용 가능한지 +확인한다. + +application input facade를 도입한 목표 순서는 다음과 같다. + +```text +QueryClientProvider + -> ApplicationProvider + -> RouterProvider + -> ThemeProvider + -> SessionProvider + -> AppShell +``` + +04 routing branch에서 Data Mode로 전환할 때 `BrowserRouter`를 +`RouterProvider`로 바꾸고 테스트 fixture도 같은 composition factory에서 +생성한다. 문서에 적힌 provider 순서를 테스트 전용 shell로 재현하지 말고 +production composition 함수를 호출한다. + +### 6.3 Boot E2E + +bootstrap integration이 통과해도 다음은 production build smoke로 다시 확인한다. + +- `/config.json` no-store fetch +- `/release-manifest.json` coherence +- base path +- hashed asset reachability +- boot error shell +- public route +- protected route + +## 7. Query와 Mutation 테스트 + +TanStack Query를 canonical React inbound adapter 뒤에 연결한 뒤 다음 계층을 +제공한다. + +```text +Page / AsyncSurface / Form pattern + -> local query/mutation hook + -> TanStack Query lifecycle + -> application input use case + -> outbound gateway +``` + +### 7.1 Query 필수 시나리오 + +- 최초 pending은 loading surface를 표시한다. +- 성공 payload는 view model로 렌더링된다. +- 빈 array와 빈 page는 empty로 분류된다. +- background refetch 중 기존 data를 유지한다. +- stale + degraded 상태를 표시한다. +- 같은 query key 요청은 deduplicate된다. +- filter 순서가 달라도 canonical key가 같다. +- route unmount 또는 superseded input에서 request를 abort한다. +- aborted request는 terminal error나 telemetry failure로 오분류되지 않는다. +- offline/paused와 loading을 구분한다. +- 401 복구는 한 번만 수행한다. +- 재로그인 후 허용된 operation만 다시 실행한다. +- schema mismatch는 safe terminal failure다. +- retryable failure만 bounded retry한다. +- query error reset 후 다시 성공할 수 있다. + +각 test는 새로운 `QueryClient`를 생성하고 retry를 명시적으로 통제한다. singleton +cache를 test 사이에 공유하지 않는다. + +### 7.2 Mutation 필수 시나리오 + +- submit은 한 번만 전송된다. +- keyed mutation은 동일 logical action에서 idempotency key를 유지한다. +- 성공 후 올바른 query namespace만 invalidate한다. +- optimistic update와 success reconcile이 일치한다. +- 실패 시 이전 cache로 rollback한다. +- 409 conflict를 일반 500과 구분한다. +- 422 field error는 safe field map으로 전달한다. +- non-idempotent mutation은 자동 재시도하지 않는다. +- unmount 후 state update warning이 없다. +- 사용자 취소와 timeout을 구분한다. +- mutation pending 중 중복 action이 차단된다. + +### 7.3 Test helper + +```text +tests/support/query/ + create-test-query-client.ts + render-with-query.tsx + wait-for-query-idle.ts +``` + +helper는 production default를 복사하지 않는다. production factory를 호출하고 +필요한 시간·retry만 test override로 주입한다. + +## 8. Form 테스트 + +Form test는 field primitive, form controller, application command mapping을 +분리한다. + +### 8.1 Field primitive + +- visible label과 accessible name +- description/error `aria-describedby` +- `aria-invalid` +- required/readonly/disabled +- ref와 focus +- autocomplete/inputmode +- IME composition +- controlled/uncontrolled + +### 8.2 Form controller + +- default value +- touched/dirty +- submit validation 시점 +- error summary +- 첫 invalid field focus +- async validation race와 취소 +- server 422 field/global error +- pending/double submit +- reset과 server value reinitialize +- unsaved navigation blocker + +### 8.3 Application 경계 + +- UI string을 command DTO로 normalize +- 빈 문자열/null/undefined 정책 +- locale number/date parse +- client validation 통과 후에도 application/domain validation 수행 +- server field name을 승인된 UI field에만 매핑 +- 알 수 없는 server path는 form-level safe error로 이동 +- raw backend message를 직접 표시하지 않음 + +### 8.4 E2E 최소 흐름 + +1. keyboard만으로 field를 이동한다. +2. 빈 submit 후 error summary로 focus가 이동한다. +3. summary link로 field에 이동한다. +4. 값을 수정한다. +5. mutation pending을 확인한다. +6. success 또는 conflict/422를 확인한다. +7. success 후 dirty guard가 해제된다. + +## 9. Router 테스트 + +### 9.1 Contract + +- route ID는 unique하다. +- path와 navigation order가 unique하다. +- 모든 route ID에 runtime module이 있다. +- 모든 runtime module은 registry route ID를 참조한다. +- params/search codec이 실제 객체다. +- loading/error surface가 등록된 component key다. +- route title은 typed message key다. + +### 9.2 Component/integration + +- public route +- session-required route +- recovery-pending route +- integration-failed route +- forbidden result +- not-found route +- params success/failure +- search default/invalid/canonical serialization +- same-page query change +- route heading focus +- document title +- scroll restoration +- redirect loop guard +- dirty form blocker +- error boundary reset + +### 9.3 Built-dist E2E + +- direct deep link +- browser refresh +- basename 배포 +- back/forward +- lazy route navigation +- chunk request failure +- old HTML/new manifest mismatch +- 1회 reload guard +- 404 fallback + +client route guard는 UX이며 authorization이 아님을 test 이름과 문서에서 유지한다. +403은 server 결과로도 별도 검증한다. + +## 10. Design System 테스트 + +공용 컴포넌트는 한 번의 결함이 모든 페이지로 전파되므로 위험도가 높다. + +### 10.1 Component behavior + +- native role/name/value +- keyboard matrix +- focus-visible +- disabled/readonly/pending +- controlled/uncontrolled +- ref +- callback 횟수와 payload +- portal cleanup +- overlay focus trap/restore +- live-region announcement +- reduced motion + +class 이름 자체보다 사용자에게 관찰 가능한 behavior를 우선한다. variant class +map의 exhaustive 여부는 unit/type test에서 별도로 검사한다. + +### 10.2 Token contract + +- 필수 semantic token 존재 +- light/dark 모두 정의 +- component가 raw 색상 사용하지 않음 +- focus/status contrast +- forced-colors fallback +- 반복 arbitrary value 차단 +- token gallery와 registry 일치 + +### 10.3 Story matrix + +모든 primitive/pattern은 다음 story를 가진다. + +- default +- variants +- disabled/readonly +- pending/loading +- invalid/error +- long text +- compact +- dark +- pseudo-locale +- RTL + +overlay는 open, keyboard, outside dismiss, long content, nested content를 추가한다. +form은 client/server error와 async pending을 추가한다. + +### 10.4 접근성 + +Storybook a11y를 기본 `error`로 설정한다. route axe가 초기 화면만 검사하는 공백을 +open dialog, invalid form, expanded menu 같은 state story로 보완한다. + +자동 axe 결과가 없더라도 다음을 component behavior로 직접 검사한다. + +- focus order +- focus trap/restore +- keyboard shortcut +- live announcement의 중복 +- visible focus + +## 11. Shared MSW Scenario Catalog + +[MSW](https://mswjs.io/docs/)는 request client를 mock하지 않고 HTTP 경계에서 +요청을 가로챈다. Node integration과 browser workshop이 동일한 operation contract +및 scenario vocabulary를 사용하도록 중앙 catalog를 만든다. + +### 11.1 목표 구조 + +```text +tests/mocks/ + contracts/ + envelopes.ts + payloads.ts + handlers/ + runtime-config.ts + release-manifest.ts + resources.ts + scenarios/ + catalog.ts + create-scenario-handlers.ts + server.ts + browser.ts + +tests/factories/ + failure-factory.ts + resource-factory.ts + session-owner-factory.ts +``` + +### 11.2 공통 scenario ID + +| ID | 응답 | +| --- | --- | +| `success` | 유효 envelope와 data | +| `empty` | 유효한 빈 collection | +| `slow` | 통제된 지연 | +| `network-error` | transport 실패 | +| `timeout` | client timeout 초과 | +| `aborted` | navigation/user/superseded abort | +| `content-type-mismatch` | JSON이 아닌 content type | +| `malformed-json` | 파싱 불가능한 JSON | +| `envelope-mismatch` | top-level contract 위반 | +| `schema-mismatch` | data payload contract 위반 | +| `auth-recover-once` | 첫 401 후 복구 성공 | +| `auth-persistent-401` | 복구 뒤에도 401 | +| `forbidden-403` | 권한 없음 | +| `not-found-404` | 리소스 없음 | +| `conflict-409` | mutation conflict | +| `validation-422` | 승인된 field/global error | +| `rate-limited-429` | Retry-After 포함 | +| `server-retry-success` | bounded retry 뒤 성공 | +| `server-terminal-500` | retry 소진 | + +### 11.3 Catalog 규칙 + +- scenario ID는 typed closed set이다. +- operation별 허용 scenario를 명시한다. +- factory default는 고정 값이며 random에 의존하지 않는다. +- timestamp/UUID가 필요하면 seeded factory를 사용한다. +- raw fixture에는 실제 개인정보·token을 넣지 않는다. +- test가 override한 handler는 `afterEach`에서 reset한다. +- 처리되지 않은 request는 `onUnhandledRequest: "error"`로 실패한다. +- test가 expected request count와 중요한 header/body를 검증한다. +- retry test는 attempt counter를 test 내부에서 초기화한다. +- scenario response는 production schema validator도 통과하거나 의도적으로 + 실패해야 한다. + +### 11.4 환경별 사용 + +```text +Vitest Node + -> setupServer(...handlers) + +Storybook + -> setupWorker(...handlers) + +Playwright release E2E + -> shared scenario catalog로 생성한 local mock API + 또는 동일 fixture builder를 사용하는 page.route +``` + +MSW browser worker와 scenario selector는 development/test entry에서만 import한다. +production runtime config에 `MOCK_MODE`, `SCENARIO`, fake token 같은 key를 추가하지 +않는다. + +## 12. Storybook 테스트 + +Storybook은 component를 격리해 state를 열거하고 실제 브라우저 interaction과 +접근성을 검사하는 개발·CI surface다. `/examples/ui`는 앱 통합 smoke로 유지하되 +Storybook을 대신하지 않는다. + +### 12.1 Global decorator + +- semantic token stylesheet +- ThemeProvider +- LocaleProvider +- Memory Router +- SessionProvider test owner +- QueryClientProvider +- MSW browser worker +- portal root + +모든 story가 production provider와 다른 임의 wrapper를 만들지 않도록 +`renderStory` helper를 하나만 둔다. + +### 12.2 Interaction test + +Storybook `play` 함수는 다음에 사용한다. + +- menu/dialog/drawer 열기와 닫기 +- keyboard navigation +- form validation +- toast dismiss +- tab/pagination selection +- optimistic mutation state + +같은 세부 behavior를 RTL unit과 story에 모두 복사하지 않는다. pure DOM behavior는 +빠른 component test, 여러 provider/network/browser interaction은 story에 둔다. + +### 12.3 Story a11y + +- 기본 policy는 error +- rule disable은 component/story별 owner, 사유, 만료일 필요 +- critical/serious만이 아니라 목표 WCAG tag의 모든 violation을 검토 +- incomplete 결과는 수동 검토 목록으로 전달 + +### 12.4 Story build + +`build-storybook`은 merge gate다. 다음을 차단한다. + +- 깨진 import +- 누락된 provider +- vendor facade 교체 오류 +- story type error +- public component가 isolated build에서만 실패하는 문제 + +Storybook static artifact를 production application artifact와 합치지 않는다. + +## 13. Playwright 전략 + +### 13.1 두 실행 profile + +#### 개발 피드백 + +- Vite dev server +- 빠른 Chromium 중심 smoke +- 로컬 `reuseExistingServer` +- 개발 중 route와 form 확인 + +#### Release 검증 + +```text +pnpm build + -> pnpm preview + -> Playwright release config +``` + +- CI에서 기존 server 재사용 금지 +- production `dist` +- 실제 runtime config/release manifest +- base path와 hashed chunks +- trace, video 또는 screenshot evidence + +merge gate의 주요 E2E도 가능한 한 built-dist를 사용하고, dev E2E는 개발 편의 +명령으로 분리한다. + +### 13.2 3-engine 정책 + +다음 critical smoke는 Chromium, Firefox, WebKit 모두 실행한다. + +- boot +- public route navigation +- protected route/session +- form submit/error +- dialog/drawer/menu keyboard +- theme +- 320px reflow +- automated a11y +- deep link +- lazy chunk + +고비용 exhaustive visual matrix는 pinned Chromium 하나로 실행한다. 엔진 차이 +위험이 큰 native dialog, date/input, focus behavior는 WebKit과 Firefox에서도 +별도 behavior assertion을 유지한다. + +### 13.3 Mobile과 responsive + +최소 viewport: + +- 320x720: 최소 reflow +- 390x844: 일반 mobile navigation/touch +- 768x1024: tablet +- 1280x720: desktop +- 1440x900: wide layout + +검증: + +- horizontal overflow +- sticky header/sidebar +- mobile drawer focus +- touch target +- long translated text +- landscape +- software keyboard로 가려질 수 있는 form action +- dialog max height와 scroll +- reduced motion +- dark theme + +device descriptor는 browser/device 특성을 흉내 내지만 실제 기기를 완전히 +대체하지 않는다. 제품 release policy가 요구하면 iOS Safari/Android Chrome +수동 또는 device-farm smoke를 추가한다. + +### 13.4 시각 회귀 + +Playwright `toHaveScreenshot()`을 사용한다. + +필수 baseline: + +- app shell compact/wide +- 각 page template +- 모든 design-system primitive group +- loading/empty/error/401/403/404 +- invalid form +- open dialog/drawer/menu +- light/dark +- pseudo-locale/RTL 대표 + +결정성 규칙: + +- OS, browser, font, device scale을 CI image로 고정 +- animation/caret 비활성화 +- clock/random/network fixture 고정 +- 개인정보와 동적 ID mask +- update snapshot은 전용 명령과 reviewer 승인을 요구 +- threshold를 높여 실제 차이를 숨기지 않는다. + +Chromatic 같은 cloud visual service는 선택이다. 저장소 내부 Playwright baseline은 +외부 서비스 없이도 실행 가능해야 한다. + +### 13.5 실패 증거 + +- trace: first retry 또는 최종 실패 +- screenshot: 실패 상태 +- HTML report +- console/page error +- network failure summary +- release/build ID + +CI retry를 허용하는 경우 첫 실패 trace도 폐기하지 않는다. retry 후 통과한 test는 +flaky signal로 집계한다. + +## 14. Coverage 정책 + +Coverage 목표는 “99% 완성도”와 같은 표현을 숫자로 대신하기 위한 것이 아니다. +높은 위험의 branch가 실행되었는지 확인하는 보조 gate다. + +### 14.1 도구 + +Vitest coverage provider를 명시적으로 설치하고 `coverage` script를 추가한다. +Vite/Vitest 조합에서는 V8 provider를 기본 후보로 사용하되 source map 정확성을 +fixture로 확인한다. + +필수 report: + +- text +- JSON summary +- LCOV 또는 Cobertura + +### 14.2 위험별 목표 + +| 영역 | Line/statement 참고 | Branch 우선 목표 | +| --- | --- | --- | +| registry/codec/schema | 95~100% | 100%에 가깝게 | +| retry/error/auth/chunk policy | 95~100% | 모든 결정 분기 | +| HTTP/storage/telemetry adapter | 90% 이상 | 모든 failure class | +| query/mutation/form controller | 90% 이상 | 상태 전이 전부 | +| design-system primitive | 숫자보다 state matrix | keyboard/error/open 전부 | +| route/page composition | 80% 이상 참고 | critical route 전부 | +| scripts/release checks | 90% 이상 | positive/negative fixture | + +전체 global threshold 하나만 두면 쉬운 파일로 위험한 파일의 누락을 가릴 수 있다. +glob 또는 별도 package/명령으로 high-risk module threshold를 강화한다. + +### 14.3 Diff coverage + +신규·변경 코드의 executable line과 branch는 기본적으로 테스트되어야 한다. +예외는 다음을 기록한다. + +- 실행 불가능한 defensive line +- browser engine 전용 branch +- external evidence만 가능한 branch +- owner +- 사유 +- 만료일 또는 제거 조건 + +### 14.4 제외 + +다음만 명시적으로 제외한다. + +- generated type +- build output +- story metadata 자체 +- 순수 type-only file +- schema에서 생성된 code + +bootstrap, facade, error fallback을 “테스트가 어렵다”는 이유로 제외하지 않는다. + +## 15. Fixture와 테스트 디렉터리 + +현재 중앙 test taxonomy를 유지하면서 책임을 명확히 한다. + +```text +tests/ + runtime-schema/ + unit/ + contract/ + component/ + integration/ + bootstrap/ + query/ + forms/ + features/ + e2e/ + smoke/ + routes/ + forms/ + accessibility/ + visual/ + mocks/ + contracts/ + handlers/ + scenarios/ + factories/ + fixtures/ + architecture/ + security/ + typecheck/ + contracts/ + support/ + render/ + query/ + router/ + clock/ + setup.ts +``` + +Story는 component와 가까이 둔다. + +```text +src/adapters/inbound/react/design-system/primitives/button/ + button.tsx + button.css + button.stories.tsx +``` + +### 15.1 역할 구분 + +- `factory`: 유효한 typed object를 기본값과 override로 생성 +- `fixture`: 변경하지 않는 positive/negative 샘플 +- `handler`: operation request를 intercept +- `scenario`: 여러 handler와 상태를 사용자 흐름으로 조합 +- `support`: render wrapper, deterministic clock, test query client + +factory가 production schema를 우회하지 않게 contract test에서 생성 결과를 +validate한다. + +### 15.2 파일 이름 + +- unit/component/integration: `*.test.ts`, `*.test.tsx` +- Playwright: `*.spec.ts` +- story: `*.stories.tsx` +- negative fixture는 기대 실패 이유를 directory/name으로 표현 + +`utils.ts`, `helpers.ts`, `fixture.ts` 같은 의미 없는 단일 파일에 모든 기능을 +모으지 않는다. + +## 16. CI Gate 설계 + +기존 gate taxonomy에 다음 검증을 명시적으로 포함한다. + +### 16.1 Merge gate + +- frozen install +- production typecheck +- test/e2e typecheck +- lint +- architecture +- runtime schema +- unit +- contract +- component +- integration +- coverage +- Storybook build +- Storybook interaction/a11y +- critical 3-engine E2E +- automated route a11y +- signed manual accessibility evidence for every registered route in scope +- design-system visual baseline +- production build +- sample removal +- security + +### 16.2 Release gate + +- bundle budget +- built-dist 3-engine smoke +- base path/deep-link +- release/config coherence +- chunk mismatch recovery +- hosting header +- lab performance +- release visual smoke + +### 16.3 Production/field gate + +- rollback/runbook drill +- provider smoke +- approved production Web Vitals evidence + +외부 배포 주소나 28일 field evidence가 없는 skeleton 개발 단계에서는 해당 gate가 +실제 프로젝트가 채울 계약으로 남는다. 이를 fake data로 통과시키지 않는다. +현재 `FE-GATE-009`의 signed manual accessibility review는 merge gate다. 이 +문서는 이를 production/field gate로 이동시키지 않는다. + +### 16.4 병렬화와 shard + +- unit/contract/component는 안정된 shard key를 사용한다. +- Playwright는 project와 shard를 함께 증거 이름에 포함한다. +- shard 하나가 실패해도 나머지 증거를 업로드한다. +- 최종 gate는 모든 shard의 통과를 AND로 계산한다. +- test order 의존성을 찾기 위해 정기적으로 순서를 섞을 수 있으나 random seed를 + 증거에 기록한다. + +### 16.5 Flaky policy + +- merge를 통과시키기 위한 임의 `test.skip` 금지 +- quarantine에는 owner, defect ID, 영향 route, 만료일 필요 +- retry 후 pass도 성공으로만 집계하지 않고 flaky report에 기록 +- 동일 test가 반복되면 clock/network/focus/shared-state 원인을 제거 +- CI machine 성능에 맞추기 위해 assertion을 제거하거나 timeout만 계속 늘리지 + 않는다. + +## 17. 새 Feature 테스트 Recipe + +도메인 feature를 추가할 때 다음 순서를 따른다. + +각 단계는 feature capability에 해당할 때 적용한다. 적용되지 않는 query, +mutation, form, visual, native-browser 항목은 조용히 생략하지 않고 테스트 계획에 +`N/A`와 이유를 기록한다. 예를 들어 read-only static route에 422, optimistic +rollback, dirty form test를 만들지 않는다. + +### Step 1. 위험과 계약을 열거한다 + +- 사용자가 완료하려는 action은 무엇인가? +- 데이터 손실, 중복 mutation, 권한 노출 위험은 무엇인가? +- URL, API operation, query key, telemetry event는 무엇인가? +- loading/empty/stale/error/conflict/access 상태는 무엇인가? +- keyboard, mobile, locale 요구는 무엇인가? + +위험마다 가장 가까운 테스트 계층을 지정한다. + +### Step 2. Type과 schema를 먼저 닫는다 + +- route params/search +- command/query +- API request/response +- domain/application result +- view model +- form value +- query key + +positive와 negative type/schema fixture를 추가한다. + +### Step 3. MSW scenario를 등록한다 + +feature operation에 필요한 scenario ID를 catalog에 추가한다. + +최소: + +- success +- empty 또는 not-found +- slow +- auth/forbidden +- schema mismatch +- retryable/terminal failure +- mutation이면 409/422 + +기존 공통 scenario로 충분하면 새 이름을 만들지 않는다. + +### Step 4. Pure policy와 mapper를 unit test한다 + +- normalization +- mapping +- policy +- error classification +- query key +- optimistic update를 사용하는 mutation의 patch/rollback + +DOM이나 MSW를 불필요하게 사용하지 않는다. + +### Step 5. Query/mutation integration을 작성한다 + +- 실제 local query adapter +- 새 QueryClient +- 실제 application use case +- MSW +- query cancellation/retry, mutation invalidation, 적용되는 경우 optimistic + rollback + +HTTP client를 `vi.fn()` 결과로 대체해 boundary contract를 건너뛰지 않는다. + +### Step 6. Form이 있는 경우 form/controller를 작성한다 + +- field semantics +- client validation +- 422 mapping +- submit pending +- conflict +- dirty/reset + +### Step 7. Page component를 검증한다 + +- page template +- initial/loading/empty/success/error +- actions +- route params/search +- heading focus +- access state + +role과 accessible name으로 상호작용한다. + +### Step 8. Story를 추가한다 + +- 모든 주요 state +- dark +- compact +- long/pseudo locale +- interaction +- a11y + +### Step 9. E2E critical flow를 추가한다 + +- direct route +- keyboard flow +- success +- 사용자 복구 가능한 failure +- mobile +- 3-engine이 필요한 native/focus behavior + +implementation detail가 아니라 사용자 결과를 assertion한다. + +### Step 10. Visual baseline을 추가한다 + +새 layout, template variant, 상태 표면이 생긴 경우만 baseline을 추가한다. 기존 +primitive를 단순히 조합한 모든 feature page를 무조건 screenshot으로 고정하지 +않는다. + +### Step 11. Evidence와 문서를 갱신한다 + +- test taxonomy +- route/accessibility scope +- CI gate evidence +- feature recipe +- 운영 failure/runbook 연결 + +### Step 12. 전체 gate를 실행한다 + +```bash +corepack pnpm check:types +corepack pnpm lint +corepack pnpm check:architecture +corepack pnpm test:runtime-schema +corepack pnpm test:unit +corepack pnpm test:component +corepack pnpm test:integration +corepack pnpm test:e2e +corepack pnpm test:a11y +corepack pnpm build +corepack pnpm check:bundle +``` + +TypeScript test, Storybook, coverage, visual, built-dist 명령이 도입되면 위 목록과 +CI registry에 추가한다. + +## 18. Feature Definition of Done + +아래 체크는 feature에 존재하는 capability에 적용한다. `N/A`에는 이유와 해당 +위험을 대신 검증하는 계층을 기록한다. 공통 type, architecture, bootstrap, +접근성, security gate는 임의로 `N/A` 처리할 수 없다. + +### Type과 계약 + +- [ ] production source와 test source typecheck가 통과한다. +- [ ] route/API/query/form type이 closed contract다. +- [ ] positive와 필요한 negative schema fixture가 있다. +- [ ] registry와 runtime mapping이 exhaustive하다. + +### Unit과 integration + +- [ ] pure policy와 mapper의 모든 중요 branch를 검증했다. +- [ ] MSW shared scenario를 사용한다. +- [ ] unhandled request가 test를 실패시킨다. +- [ ] query가 있으면 cancellation, retry, stale 상태를 검증했다. +- [ ] mutation이 있으면 invalidation/conflict를, optimistic update를 쓰면 + rollback을 검증했다. +- [ ] auth recovery가 bounded임을 검증했다. + +### Form과 UI + +- [ ] form이 있으면 field label/description/error가 연결된다. +- [ ] form이 있으면 error summary와 first-invalid focus가 동작한다. +- [ ] mutation form이 있으면 pending과 double submit을 검증했다. +- [ ] loading/empty/success/error/access 상태가 있다. +- [ ] keyboard와 focus test가 있다. +- [ ] component/story a11y가 통과한다. + +### Router와 bootstrap + +- [ ] deep link와 browser navigation이 동작한다. +- [ ] params/search invalid 입력이 안전하게 처리된다. +- [ ] route error를 검증하고 lazy chunk가 있는 경우 recovery를 검증했다. +- [ ] 실제 bootstrap/provider composition에서 feature가 동작한다. +- [ ] built-dist smoke가 통과한다. + +### Browser와 visual + +- [ ] native/focus/browser 차이가 있는 critical flow가 지정된 3개 엔진에서 + 통과하고, 나머지는 browser matrix 정책을 따른다. +- [ ] 320px와 대표 mobile viewport에서 overflow가 없다. +- [ ] 필요한 light/dark visual baseline이 있다. +- [ ] pseudo-locale/긴 문구가 잘리지 않는다. +- [ ] failure trace와 report가 CI evidence로 남는다. + +### Coverage와 운영 + +- [ ] high-risk module branch 목표를 충족한다. +- [ ] 신규 코드의 미검증 branch에 승인 없는 예외가 없다. +- [ ] bundle/performance budget을 통과한다. +- [ ] telemetry/error output에 민감 정보가 없다. +- [ ] 관련 gate와 evidence registry가 갱신되었다. + +## 19. 금지 패턴 + +- production bootstrap을 복사한 test-only shell만 검증 +- query cache singleton을 test 사이에 공유 +- `fetch`나 HTTP client 전체를 `vi.fn()`으로 대체하고 MSW integration 생략 +- 성공 응답만 제공하는 feature mock +- test마다 서로 다른 401/422/500 body를 임의 작성 +- test에서 실제 sleep 사용 +- timeout을 늘려 race condition 숨김 +- implementation class와 DOM nesting만 assertion +- 대형 DOM snapshot으로 behavior test 대체 +- failure screenshot을 visual regression이라고 부름 +- dev server E2E만으로 release build 완료 선언 +- Chromium만 통과하고 native focus/browser 호환 완료 선언 +- axe 결과만으로 접근성 완료 선언 +- global coverage 숫자로 고위험 branch 누락 은폐 +- type error를 `any`, `@ts-ignore`, 이중 cast로 숨김 +- production bundle에 MSW worker, mock selector, fake credential 포함 +- flaky test를 owner/만료일 없이 skip +- CI gate에 `continue-on-error` + +## 20. 단계별 도입 순서 + +1. `tsconfig.test.json`과 test typecheck gate를 추가한다. +2. production bootstrap을 주입 가능한 함수로 추출하고 integration test를 만든다. +3. MSW handlers/scenario/factory를 중앙 catalog로 이동한다. +4. query/mutation presentation adapter와 integration harness를 만든다. +5. form foundation과 form/controller test matrix를 만든다. +6. route registry/runtime map contract와 built-dist E2E를 추가한다. +7. Storybook build, interaction, a11y gate를 추가한다. +8. pinned Chromium visual baseline을 추가한다. +9. critical flow의 3-engine release profile을 분리한다. +10. V8 coverage와 high-risk/diff policy를 차단 gate로 추가한다. +11. feature recipe와 Definition of Done를 pull request template에 연결한다. + +이 순서의 완료 기준은 테스트 도구를 모두 설치하는 것이 아니다. 새 도메인 +기능이 추가되었을 때 개발자가 성공·실패·권한·복구·접근성·브라우저·release +위험을 어디서 어떻게 검증할지 추가 설계 없이 결정할 수 있어야 한다. diff --git a/docs/testing/taxonomy.md b/docs/testing/taxonomy.md index 0f460aa9..8a4b8473 100644 --- a/docs/testing/taxonomy.md +++ b/docs/testing/taxonomy.md @@ -29,3 +29,10 @@ Promotion is an AND graph: 2. merge gates plus release gates 3. release gates plus rollback/runbook drills 4. production promotion plus eligible field Web Vitals evidence + +This file describes the currently registered taxonomy. The +[frontend platform testing strategy](./frontend-platform-testing-strategy.md) +documents the target additions: test TypeScript projects, real bootstrap +composition tests, shared MSW scenarios, query/mutation/form/router coverage, +Storybook interaction and accessibility checks, visual regression, and a +built-output Playwright profile. From 0fed35586a473febf16cc6d0d3b6836f42425e1a Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sun, 26 Jul 2026 13:41:23 +0900 Subject: [PATCH 047/178] feat: establish TypeScript-aware frontend tooling --- .dependency-cruiser.cjs | 3 + README.md | 13 +- config/ci/gates.json | 16 +- .../VD-01-typescript-lint-tooling.md | 54 ++ .../typescript-state-and-data-flow.md | 10 +- .../frontend-platform-testing-strategy.md | 10 +- eslint.config.js | 144 +++-- package.json | 17 +- pnpm-lock.yaml | 495 ++++++++++++++++++ scripts/check-registries.mjs | 103 +++- src/adapters/http/client.js | 17 +- tests/component/render-boundary.test.jsx | 1 + tests/component/router.test.jsx | 2 +- tests/component/sample-resource-page.test.jsx | 24 +- .../typescript-tooling-smoke.test.tsx | 20 + .../allowed/presentation-facade.tsx | 7 + .../presentation-imports-adapter.tsx | 5 + .../registry/forbidden/governance.json | 33 ++ .../registry/forbidden/invalid-registry.ts | 13 + tests/fixtures/security/allowed/safe-text.tsx | 3 + .../fixtures/security/forbidden/raw-html.tsx | 3 + .../typecheck/invalid-port-implementation.ts | 7 + .../typecheck/invalid-result-narrowing.ts | 7 + tests/integration/auth-recovery.test.js | 35 +- tests/runtime-schema/http-schema.test.js | 1 + tests/runtime-schema/runtime-config.test.js | 3 +- tests/unit/auth-session-adapter.test.js | 3 +- tests/unit/chunk-recovery.test.js | 11 +- tests/unit/color-scheme.test.js | 14 +- tests/unit/error-classification.test.js | 10 +- tests/unit/promotion-readiness.test.js | 11 +- tests/unit/registry-governance.test.js | 8 +- tests/unit/runtime-adapters.test.js | 4 +- tests/unit/storage-registry.test.js | 6 +- tests/unit/telemetry.test.js | 2 +- tests/unit/typescript-tooling-smoke.test.ts | 16 + tsconfig.app.json | 9 + tsconfig.base.json | 18 + tsconfig.json | 24 +- tsconfig.node.json | 9 + tsconfig.test.json | 20 + 41 files changed, 1086 insertions(+), 125 deletions(-) create mode 100644 docs/architecture/decisions/VD-01-typescript-lint-tooling.md create mode 100644 tests/component/typescript-tooling-smoke.test.tsx create mode 100644 tests/fixtures/architecture/allowed/presentation-facade.tsx create mode 100644 tests/fixtures/architecture/forbidden/presentation-imports-adapter.tsx create mode 100644 tests/fixtures/registry/forbidden/governance.json create mode 100644 tests/fixtures/registry/forbidden/invalid-registry.ts create mode 100644 tests/fixtures/security/allowed/safe-text.tsx create mode 100644 tests/fixtures/security/forbidden/raw-html.tsx create mode 100644 tests/fixtures/typecheck/invalid-port-implementation.ts create mode 100644 tests/fixtures/typecheck/invalid-result-narrowing.ts create mode 100644 tests/unit/typescript-tooling-smoke.test.ts create mode 100644 tsconfig.app.json create mode 100644 tsconfig.base.json create mode 100644 tsconfig.node.json create mode 100644 tsconfig.test.json diff --git a/.dependency-cruiser.cjs b/.dependency-cruiser.cjs index 4290d0ce..a1e20df5 100644 --- a/.dependency-cruiser.cjs +++ b/.dependency-cruiser.cjs @@ -45,5 +45,8 @@ module.exports = { exportsFields: ["exports"], conditionNames: ["import", "require", "node", "default"], }, + tsConfig: { + fileName: "tsconfig.app.json", + }, }, }; diff --git a/README.md b/README.md index 0c67f8cf..12477ad3 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,8 @@ operations are executable contracts rather than conventions. ## Start locally -Requirements: Node 24 and Corepack. The repository pins pnpm in `package.json`. +Requirements: Node 24.11 or newer and Corepack. The repository pins pnpm in +`package.json`. ```bash corepack pnpm install --frozen-lockfile @@ -80,6 +81,9 @@ Common local checks: ```bash corepack pnpm lint corepack pnpm check:types +corepack pnpm check:types:app +corepack pnpm check:types:node +corepack pnpm check:types:test corepack pnpm check:architecture corepack pnpm test:all corepack pnpm test:e2e @@ -94,6 +98,13 @@ corepack pnpm drill:runbooks corepack pnpm check:ci ``` +`check:types`는 source, Node scripts/config와 tests를 분리된 TypeScript +project로 모두 검사한다. type/architecture/security/registry의 invalid +fixture는 `config/ci/gates.json`에서 “실패해야 통과”하는 negative gate로 +실행된다. 도구 호환성 결정은 +[VD-01](docs/architecture/decisions/VD-01-typescript-lint-tooling.md)에 기록돼 +있다. + Install the pinned Playwright browser engines before the first cross-browser run: diff --git a/config/ci/gates.json b/config/ci/gates.json index 2de046d6..7d8d4ed0 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -74,7 +74,9 @@ "name": "typecheck", "steps": [ { "script": "check:types", "expect": "pass" }, - { "script": "check:types:fixture", "expect": "fail" } + { "script": "check:types:fixture", "expect": "fail" }, + { "script": "check:types:fixture:ts-port", "expect": "fail" }, + { "script": "check:types:fixture:ts-result", "expect": "fail" } ], "logPath": "artifacts/quality/check-types.txt", "evidence": ["artifacts/quality/check-types.txt"], @@ -136,9 +138,17 @@ }, "FE-GATE-010": { "name": "architecture", - "steps": [{ "script": "check:architecture", "expect": "pass" }], + "steps": [ + { "script": "check:architecture", "expect": "pass" }, + { "script": "check:registries", "expect": "pass" }, + { "script": "check:registries:fixture", "expect": "fail" } + ], "logPath": "artifacts/quality/gates/FE-GATE-010.txt", - "evidence": ["artifacts/quality/dependency-report.json"], + "evidence": [ + "artifacts/quality/dependency-report.json", + "artifacts/quality/registries.json", + "artifacts/quality/registry-fixture.json" + ], "retentionClass": "merge-cycle" }, "FE-GATE-011": { diff --git a/docs/architecture/decisions/VD-01-typescript-lint-tooling.md b/docs/architecture/decisions/VD-01-typescript-lint-tooling.md new file mode 100644 index 00000000..83c1e23e --- /dev/null +++ b/docs/architecture/decisions/VD-01-typescript-lint-tooling.md @@ -0,0 +1,54 @@ +# VD-01: TypeScript 7과 ESLint 10의 점진적 전환 도구 + +- 상태: Accepted +- 결정일: 2026-07-26 +- 적용 브랜치: `feature-frontend-typescript-tooling-foundation` + +## 배경 + +저장소는 TypeScript `7.0.2`와 ESLint `10.8.0`을 고정하고 있다. 첫 전환 +브랜치는 compiler를 변경하거나 production source를 일괄 변환하지 않고 +JS/JSX/TS/TSX가 같은 품질 게이트를 통과하게 해야 한다. + +결정 시점의 package peer contract는 다음과 같다. + +- `typescript-eslint@8.65.0`과 canary는 TypeScript `<6.1.0`을 요구한다. +- `eslint-plugin-jsx-a11y@6.10.2`는 ESLint `<=9`를 요구한다. +- `eslint-plugin-react-hooks@7.1.1`은 ESLint 10을 지원한다. +- Babel 8 ESLint parser는 ESLint 10을 지원하고 Node `>=24.11.0`을 요구한다. + +호환되지 않는 peer dependency를 강제 설치하면 lockfile 검증은 통과하더라도 +지원되지 않는 parser와 rule 조합을 플랫폼 계약으로 만들게 된다. + +## 결정 + +1. TypeScript `7.0.2`와 ESLint `10.8.0`을 유지한다. +2. TypeScript/TSX의 ESLint syntax parsing에는 + `@babel/eslint-parser`와 TypeScript/JSX syntax plugin을 사용한다. +3. TypeScript의 이름 해석, unused 진단과 type semantics는 `tsc`가 소유한다. + Babel parser가 TypeScript scope manager를 제공하지 않으므로 TS 파일의 + core `no-undef`와 `no-unused-vars`는 끄고 분리된 app/node/test TypeScript + project를 필수 게이트로 실행한다. +4. React Hook 규칙은 호환되는 `eslint-plugin-react-hooks`로 즉시 적용한다. +5. JSX 접근성은 현재의 semantic component contract, Testing Library, + axe 기반 cross-browser gate와 수동 검토 계약이 계속 담당한다. 호환되지 않는 + `eslint-plugin-jsx-a11y`는 설치하지 않는다. +6. Babel 8의 지원 범위에 맞춰 Node engine 하한을 `24.11.0`으로 명시한다. +7. production source의 대량 rename은 이 결정에 포함하지 않는다. + +## 검증 + +- `check:types`는 app, Node scripts/config, tests project를 모두 검사한다. +- JS invalid-call, TS invalid port, TS discriminated-union fixture는 실패해야 한다. +- ESLint와 dependency-cruiser는 TS/TSX architecture fixture를 검사한다. +- registry scanner는 TS registry의 required field, uniqueness와 reference를 + 검증한다. +- browser security gate는 TSX의 금지된 raw HTML fixture를 거절한다. + +## 후속 검토와 제거 + +`typescript-eslint`가 TypeScript 7을, JSX 접근성 plugin이 ESLint 10을 공식 +지원하면 별도 dependency 브랜치에서 peer metadata와 전체 negative fixture를 +재검증한다. 교체할 때는 Babel parser package와 TS 전용 ESLint override를 +함께 제거한다. compiler downgrade나 `--force` 설치는 이 ADR의 rollback +방법이 아니다. diff --git a/docs/architecture/typescript-state-and-data-flow.md b/docs/architecture/typescript-state-and-data-flow.md index 83f859bc..76972f35 100644 --- a/docs/architecture/typescript-state-and-data-flow.md +++ b/docs/architecture/typescript-state-and-data-flow.md @@ -36,7 +36,8 @@ TypeScript 전환 목적은 확장자 변경이 아니라 이 계약을 컴파 다음 변경이 첫 브랜치에서 완료되기 전에는 source rename을 시작하지 않는다. 1. ESLint가 `js`, `jsx`, `mjs`, `ts`, `tsx`, `mts`를 모두 검사한다. -2. `typescript-eslint`, React Hooks, JSX accessibility 규칙을 추가한다. +2. React Hooks 규칙을 추가하고 TypeScript/ESLint parser와 JSX accessibility + 도구는 설치된 compiler/linter의 공식 peer 범위 안에서 선택한다. 3. dependency-cruiser의 extension과 resolver가 TS/TSX를 포함한다. 4. `scripts/check-registries.mjs`가 TS/TSX를 검색한다. 5. `config/contracts/registry-governance.json`의 경로 갱신 절차를 만든다. @@ -77,6 +78,13 @@ tsconfig.json # project references only 확정한다. 옵션을 한꺼번에 켜서 수백 개 예외를 만들지 말고, 각 단계에서 새 예외를 금지한다. +현재 저장소의 VD-01 결정은 +[TypeScript 7과 ESLint 10의 점진적 전환 도구](./decisions/VD-01-typescript-lint-tooling.md)에 +기록돼 있다. app, Node scripts/config, tests는 각각 독립된 project로 +typecheck하며 JS에는 `checkJs`, TS에는 `strict`를 적용한다. TypeScript 7을 +아직 지원하지 않는 parser plugin을 강제 설치하지 않고 Babel parser는 lint +syntax/import/security 검사, `tsc`는 type semantics를 소유한다. + ### 2.3 전환 순서 | 단계 | 대상 | 이유 | 종료 조건 | diff --git a/docs/testing/frontend-platform-testing-strategy.md b/docs/testing/frontend-platform-testing-strategy.md index 5f3e6c68..5885924a 100644 --- a/docs/testing/frontend-platform-testing-strategy.md +++ b/docs/testing/frontend-platform-testing-strategy.md @@ -69,12 +69,12 @@ field/documentation 단계를 구성한다. ### 2.3 확인된 공백 -#### 테스트 TypeScript가 typecheck 대상이 아니다 +#### 테스트 TypeScript typecheck 기반 -현재 `check:types`는 `tsconfig.json`의 include 범위에 의존하며 tests 전체의 -callback, mock, fixture, custom matcher type을 별도 프로젝트로 검사하지 않는다. -TypeScript 전환 뒤 Vitest가 test file을 변환해 실행할 수 있다는 사실은 -`tsc` typecheck를 대체하지 않는다. +`check:types`는 app, Node scripts/config, tests project를 순서대로 검사한다. +테스트 project는 JS/JSX/TS/TSX의 callback, mock, fixture와 config type을 +검사하되 실패를 의도한 `tests/fixtures`는 별도 negative command가 소유한다. +Vitest의 변환 성공을 TypeScript typecheck의 대체물로 취급하지 않는다. #### 실제 bootstrap integration test가 없다 diff --git a/eslint.config.js b/eslint.config.js index 715beee1..f3e3d75c 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,6 +1,10 @@ +import babelParser from "@babel/eslint-parser"; import eslint from "@eslint/js"; +import reactHooks from "eslint-plugin-react-hooks"; import globals from "globals"; +const sourceExtensions = "{js,jsx,mjs,ts,tsx,mts}"; + const layerPatterns = { domain: [ "**/application/**", @@ -27,6 +31,38 @@ function restrictedImports(patterns) { return ["error", { patterns }]; } +const commonLanguageOptions = { + ecmaVersion: "latest", + sourceType: "module", + globals: { + ...globals.browser, + ...globals.node, + }, +}; + +const commonSecurityRules = { + "no-eval": "error", + "no-new-func": "error", + "no-script-url": "error", + "no-restricted-syntax": [ + "error", + { + selector: "JSXAttribute[name.name='dangerouslySetInnerHTML']", + message: "Raw HTML injection is prohibited by FE-OC-019.", + }, + { + selector: + "CallExpression[callee.object.name='document'][callee.property.name='createElement'][arguments.0.value='script']", + message: "Runtime script construction is prohibited by FE-OC-019.", + }, + ], +}; + +const hookRules = { + "react-hooks/rules-of-hooks": "error", + "react-hooks/exhaustive-deps": "error", +}; + export default [ { ignores: [ @@ -40,47 +76,103 @@ export default [ }, eslint.configs.recommended, { - files: ["**/*.{js,jsx,mjs}"], + files: [`**/*.${sourceExtensions}`], languageOptions: { - ecmaVersion: "latest", - sourceType: "module", - globals: { - ...globals.browser, - ...globals.node, - }, + ...commonLanguageOptions, parserOptions: { ecmaFeatures: { jsx: true }, }, }, + plugins: { + "react-hooks": reactHooks, + }, + rules: { + ...commonSecurityRules, + ...hookRules, + }, }, { - files: ["src/domain/**/*.{js,jsx}"], + files: ["**/*.{ts,mts}"], + languageOptions: { + ...commonLanguageOptions, + parser: babelParser, + parserOptions: { + requireConfigFile: false, + babelOptions: { + plugins: [ + ["@babel/plugin-syntax-typescript", { isTSX: false }], + ], + }, + }, + }, + rules: { + "no-undef": "off", + "no-unused-vars": "off", + }, + }, + { + files: ["**/*.tsx"], + languageOptions: { + ...commonLanguageOptions, + parser: babelParser, + parserOptions: { + requireConfigFile: false, + babelOptions: { + plugins: [ + [ + "@babel/plugin-syntax-typescript", + { allExtensions: true, isTSX: true }, + ], + "@babel/plugin-syntax-jsx", + ], + }, + }, + }, + rules: { + "no-undef": "off", + "no-unused-vars": "off", + }, + }, + { + files: [`src/domain/**/*.${sourceExtensions}`], rules: { "no-restricted-imports": restrictedImports(layerPatterns.domain), - "no-restricted-globals": ["error", "window", "document", "localStorage", "fetch"], + "no-restricted-globals": [ + "error", + "window", + "document", + "localStorage", + "fetch", + ], }, }, { - files: ["src/application/**/*.{js,jsx}"], + files: [`src/application/**/*.${sourceExtensions}`], rules: { "no-restricted-imports": restrictedImports(layerPatterns.application), - "no-restricted-globals": ["error", "window", "document", "localStorage", "fetch"], + "no-restricted-globals": [ + "error", + "window", + "document", + "localStorage", + "fetch", + ], }, }, { - files: ["src/presentation/**/*.{js,jsx}"], + files: [`src/presentation/**/*.${sourceExtensions}`], rules: { "no-restricted-imports": restrictedImports(layerPatterns.presentation), }, }, { - files: ["src/adapters/**/*.{js,jsx}"], + files: [`src/adapters/**/*.${sourceExtensions}`], rules: { "no-restricted-imports": restrictedImports(layerPatterns.adapters), }, }, { - files: ["tests/**/*.{js,jsx}"], + files: [`tests/**/*.${sourceExtensions}`], languageOptions: { globals: { ...globals.browser, @@ -89,7 +181,9 @@ export default [ }, }, { - files: ["tests/fixtures/architecture/forbidden/**/*.{js,jsx}"], + files: [ + `tests/fixtures/architecture/forbidden/**/*.${sourceExtensions}`, + ], rules: { "no-restricted-imports": restrictedImports([ "**/adapters/**", @@ -99,24 +193,4 @@ export default [ ]), }, }, - { - files: ["**/*.{js,jsx}"], - rules: { - "no-eval": "error", - "no-new-func": "error", - "no-script-url": "error", - "no-restricted-syntax": [ - "error", - { - selector: "JSXAttribute[name.name='dangerouslySetInnerHTML']", - message: "Raw HTML injection is prohibited by FE-OC-019.", - }, - { - selector: - "CallExpression[callee.object.name='document'][callee.property.name='createElement'][arguments.0.value='script']", - message: "Runtime script construction is prohibited by FE-OC-019.", - }, - ], - }, - }, ]; diff --git a/package.json b/package.json index bbac5926..73d63482 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "type": "module", "packageManager": "pnpm@11.17.0", "engines": { - "node": ">=24.0.0 <25.0.0", + "node": ">=24.11.0 <25.0.0", "pnpm": ">=11.0.0 <12.0.0" }, "scripts": { @@ -15,8 +15,13 @@ "preview": "vite preview", "lint": "eslint src scripts tests vite.config.js vitest.config.js playwright.config.js --max-warnings=0", "check:architecture": "node scripts/check-architecture.mjs", - "check:types": "tsc --allowJs --checkJs --noEmit", + "check:types": "corepack pnpm check:types:app && corepack pnpm check:types:node && corepack pnpm check:types:test", + "check:types:app": "tsc --project tsconfig.app.json", + "check:types:node": "tsc --project tsconfig.node.json", + "check:types:test": "tsc --project tsconfig.test.json", "check:types:fixture": "tsc --ignoreConfig --allowJs --checkJs --noEmit --target ES2022 --module NodeNext --moduleResolution NodeNext tests/fixtures/typecheck/invalid-port-call.js", + "check:types:fixture:ts-port": "tsc --ignoreConfig --strict --noEmit --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-port-implementation.ts", + "check:types:fixture:ts-result": "tsc --ignoreConfig --strict --noEmit --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-result-narrowing.ts", "test:runtime-schema": "vitest run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests", "test:unit": "vitest run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml", "test:component": "vitest run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml", @@ -31,6 +36,7 @@ "scan:security": "node scripts/security-scan.mjs", "check:browser-security": "node scripts/check-browser-security.mjs", "check:registries": "node scripts/check-registries.mjs", + "check:registries:fixture": "node scripts/check-registries.mjs --governance tests/fixtures/registry/forbidden/governance.json --artifact artifacts/quality/registry-fixture.json", "verify:compatibility": "node scripts/check-compatibility.mjs", "verify:release": "node scripts/verify-release.mjs", "verify:hosting-headers": "node scripts/verify-hosting-headers.mjs", @@ -52,18 +58,23 @@ }, "devDependencies": { "@axe-core/playwright": "4.12.1", + "@babel/core": "8.0.1", + "@babel/eslint-parser": "8.0.1", + "@babel/plugin-syntax-jsx": "8.0.1", + "@babel/plugin-syntax-typescript": "8.0.3", "@eslint/js": "10.0.1", "@playwright/test": "1.62.0", + "@tailwindcss/vite": "4.3.3", "@testing-library/jest-dom": "7.0.0", "@testing-library/react": "16.3.2", "@testing-library/user-event": "14.6.1", - "@tailwindcss/vite": "4.3.3", "@types/node": "24.13.3", "@types/react": "19.2.8", "@types/react-dom": "19.2.3", "@vitejs/plugin-react": "6.0.4", "dependency-cruiser": "18.1.0", "eslint": "10.8.0", + "eslint-plugin-react-hooks": "7.1.1", "globals": "17.7.0", "jsdom": "29.1.1", "msw": "2.15.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1069817e..d70fc0ed 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -27,6 +27,18 @@ importers: '@axe-core/playwright': specifier: 4.12.1 version: 4.12.1(playwright-core@1.62.0) + '@babel/core': + specifier: 8.0.1 + version: 8.0.1 + '@babel/eslint-parser': + specifier: 8.0.1 + version: 8.0.1(@babel/core@8.0.1)(eslint@10.8.0(jiti@2.7.0)(supports-color@7.2.0)) + '@babel/plugin-syntax-jsx': + specifier: 8.0.1 + version: 8.0.1(@babel/core@8.0.1) + '@babel/plugin-syntax-typescript': + specifier: 8.0.3 + version: 8.0.3(@babel/core@8.0.1) '@eslint/js': specifier: 10.0.1 version: 10.0.1(eslint@10.8.0(jiti@2.7.0)(supports-color@7.2.0)) @@ -63,6 +75,9 @@ importers: eslint: specifier: 10.8.0 version: 10.8.0(jiti@2.7.0)(supports-color@7.2.0) + eslint-plugin-react-hooks: + specifier: 7.1.1 + version: 7.1.1(eslint@10.8.0(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0) globals: specifier: 17.7.0 version: 17.7.0 @@ -114,14 +129,155 @@ packages: resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} engines: {node: '>=6.9.0'} + '@babel/code-frame@8.0.0': + resolution: {integrity: sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==} + engines: {node: ^22.18.0 || >=24.11.0} + + '@babel/compat-data@7.29.7': + resolution: {integrity: sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==} + engines: {node: '>=6.9.0'} + + '@babel/compat-data@8.0.0': + resolution: {integrity: sha512-DOjnob/cXOUgDOozCDeq/aK2p5y8dUIVdf6tNhEV1HQRd6I8aQ4f4fbtHRVEvb6lP3BGomrKHiS8ICAASSVQSw==} + engines: {node: ^22.18.0 || >=24.11.0} + + '@babel/core@7.29.7': + resolution: {integrity: sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==} + engines: {node: '>=6.9.0'} + + '@babel/core@8.0.1': + resolution: {integrity: sha512-5FgxM4dLQpMJHSiVATk8foW263dVHQHBVpXYiimNECVWG01f4nFyEbQixeT6Mwvg7TayREJ2gpKl3o2RoMdnqw==} + engines: {node: ^22.18.0 || >=24.11.0} + + '@babel/eslint-parser@8.0.1': + resolution: {integrity: sha512-2javO8pAQv/ld6sS6OcxoLAlzZEZy+xm99bnoAfMhzKSumKhdF5wylpbZB7XTorWr3KLPtx5K95eduJPOy1mzA==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + eslint: ^9.0.0 || ^10.0.0 + + '@babel/generator@7.29.7': + resolution: {integrity: sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==} + engines: {node: '>=6.9.0'} + + '@babel/generator@8.0.0': + resolution: {integrity: sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g==} + engines: {node: ^22.18.0 || >=24.11.0} + + '@babel/helper-compilation-targets@7.29.7': + resolution: {integrity: sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==} + engines: {node: '>=6.9.0'} + + '@babel/helper-compilation-targets@8.0.0': + resolution: {integrity: sha512-JwculLABZvyPvyLBpwU/E/IbH2uM3mnxNtIJpxnIfb24y1PrdVxK5Dqjle4DpgqpGRnwgC7G8IkzPdSXZrO1Ew==} + engines: {node: ^22.18.0 || >=24.11.0} + + '@babel/helper-globals@7.29.7': + resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==} + engines: {node: '>=6.9.0'} + + '@babel/helper-globals@8.0.0': + resolution: {integrity: sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw==} + engines: {node: ^22.18.0 || >=24.11.0} + + '@babel/helper-module-imports@7.29.7': + resolution: {integrity: sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==} + engines: {node: '>=6.9.0'} + + '@babel/helper-module-transforms@7.29.7': + resolution: {integrity: sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0 + + '@babel/helper-plugin-utils@8.0.1': + resolution: {integrity: sha512-3PKFgjTyPlhFhorfP+SjKQxLViIL++zWjFOO4hGriYU+Bsm983DxEM1JmDRJVWXV0O9npu+xXRqz7Pbd3mh70g==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + + '@babel/helper-string-parser@7.29.7': + resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-string-parser@8.0.0': + resolution: {integrity: sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg==} + engines: {node: ^22.18.0 || >=24.11.0} + '@babel/helper-validator-identifier@7.29.7': resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} engines: {node: '>=6.9.0'} + '@babel/helper-validator-identifier@8.0.4': + resolution: {integrity: sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg==} + engines: {node: ^22.18.0 || >=24.11.0} + + '@babel/helper-validator-option@7.29.7': + resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-option@8.0.0': + resolution: {integrity: sha512-U4Dybxh4WESWHt5XhBeExi4DrY0/DNK1aHpQbsrQXCUbFHuMweT0TpLEWKvaraV2Y6fS+ZXunsZ8zIuZIgvF2Q==} + engines: {node: ^22.18.0 || >=24.11.0} + + '@babel/helpers@7.29.7': + resolution: {integrity: sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==} + engines: {node: '>=6.9.0'} + + '@babel/helpers@8.0.0': + resolution: {integrity: sha512-wfbi91pM3py96oIiJEz7qIpyXDytgr9zQC1HEWwlGNVRAEmItuU/0a41ZUKu1sJGyhhOIpc4t5vk4PYzt8wpsg==} + engines: {node: ^22.18.0 || >=24.11.0} + + '@babel/parser@7.29.7': + resolution: {integrity: sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==} + engines: {node: '>=6.0.0'} + hasBin: true + + '@babel/parser@8.0.4': + resolution: {integrity: sha512-srpptsAkEbbNIC/q8nT7o+m6CQe8CJUTV/t7MYc9NnWlgYVtHOb7JH6SorxMhN0kuRJjVqXbKClG6xSbPtzz+g==} + engines: {node: ^22.18.0 || >=24.11.0} + hasBin: true + + '@babel/plugin-syntax-jsx@8.0.1': + resolution: {integrity: sha512-n0jtCOxEovhU7METqSQjcZO9pX53nu9uNIjMS+hEt+Nt9jA7oOZoBIgbCxhhASmF6T6rPDGge5UAvh6Z4eFz/g==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + + '@babel/plugin-syntax-typescript@8.0.3': + resolution: {integrity: sha512-jmTPwps7oSQSZaV1SxkQ3C12UWyufGysGc5OzDpZzvPAIX4mO7dJT3hoqkWVrSImvkcMiknir1iLN1SNV/CZzg==} + engines: {node: ^22.18.0 || >=24.11.0} + peerDependencies: + '@babel/core': ^8.0.0 + '@babel/runtime@7.29.7': resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==} engines: {node: '>=6.9.0'} + '@babel/template@7.29.7': + resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==} + engines: {node: '>=6.9.0'} + + '@babel/template@8.0.0': + resolution: {integrity: sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==} + engines: {node: ^22.18.0 || >=24.11.0} + + '@babel/traverse@7.29.7': + resolution: {integrity: sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==} + engines: {node: '>=6.9.0'} + + '@babel/traverse@8.0.4': + resolution: {integrity: sha512-bZnmqzGG8UZneG1lLxBoWIH0G6Gr1D846Yu4/3XnY6FhCndMR49u26nTY08u/dAxWmLWF9vGQOuC+84FfIUoeg==} + engines: {node: ^22.18.0 || >=24.11.0} + + '@babel/types@7.29.7': + resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==} + engines: {node: '>=6.9.0'} + + '@babel/types@8.0.4': + resolution: {integrity: sha512-eY+Yn3dCqTGmyiq2QRU66lA5FL8lqqqvecHt0fF3uHONIa7ToYsaCiWV8lOKqAs0Rb2SjixiKFROngnulPtt2g==} + engines: {node: ^22.18.0 || >=24.11.0} + '@bramus/specificity@2.4.2': resolution: {integrity: sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==} hasBin: true @@ -572,6 +728,12 @@ packages: '@types/estree@1.0.9': resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + '@types/gensync@1.0.5': + resolution: {integrity: sha512-MbsRCT7mTikHwKZ0X+LVUTLRrZZRLipTuXEO9qOYO+zmjMVk81axyClMROf6uoPD9MRVu46bx8zoR0Ad9q3NAg==} + + '@types/jsesc@2.5.1': + resolution: {integrity: sha512-9VN+6yxLOPLOav+7PwjZbxiID2bVaeq0ED4qSQmdQTdjnXJSaCVKTR58t15oqH1H5t8Ng2ZX1SabJVoN9Q34bw==} + '@types/json-schema@7.0.15': resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} @@ -809,6 +971,11 @@ packages: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} + baseline-browser-mapping@2.11.1: + resolution: {integrity: sha512-HYXq73DDpCtNzOmrFsm9eSwCvWCql0RzqjpDzXN9EadiLJ4DNat0nsZ/Bzmy+Ud12mb4/zKDY0cQ805ZzN+i0A==} + engines: {node: '>=6.0.0'} + hasBin: true + bidi-js@1.0.3: resolution: {integrity: sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==} @@ -816,6 +983,14 @@ packages: resolution: {integrity: sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==} engines: {node: 20 || >=22} + browserslist@4.28.7: + resolution: {integrity: sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw==} + engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} + hasBin: true + + caniuse-lite@1.0.30001806: + resolution: {integrity: sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw==} + chai@6.2.2: resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} engines: {node: '>=18'} @@ -902,9 +1077,16 @@ packages: dom-accessibility-api@0.6.3: resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==} + electron-to-chromium@1.5.396: + resolution: {integrity: sha512-yHiw2Y3C3H9U6TMbOfoWK/BPreiOPXRfTWPBwQBoZG6/8TB6eOPnsy5oaRYuatR7Fw2SJ4kKforgufeo7fq0EQ==} + emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + empathic@2.0.1: + resolution: {integrity: sha512-YGRs8knHhKHVShLkFET/rWAU8kmHbOV5LwN938RHI0pljAJ1Gf6SzXsSmRaEzcXTtOOmVqJ5+WtQPL5uigY50Q==} + engines: {node: '>=14'} + enhanced-resolve@5.24.2: resolution: {integrity: sha512-rpsZEGT1jFuve6QlpyRp9ckQ+kN61hvF9BzCPyMdaKTm8UJce96KBn3sorXOFXlzjPrs3Vc4T1NsSroZ3PxlFw==} engines: {node: '>=10.13.0'} @@ -928,6 +1110,12 @@ packages: resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} engines: {node: '>=10'} + eslint-plugin-react-hooks@7.1.1: + resolution: {integrity: sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==} + engines: {node: '>=18'} + peerDependencies: + eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0 + eslint-scope@9.1.2: resolution: {integrity: sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} @@ -1032,6 +1220,10 @@ packages: function-bind@1.1.2: resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + gensync@1.0.0-beta.2: + resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} + engines: {node: '>=6.9.0'} + get-caller-file@2.0.5: resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} engines: {node: 6.* || 8.* || >= 10.*} @@ -1066,6 +1258,12 @@ packages: headers-polyfill@5.0.1: resolution: {integrity: sha512-1TJ6Fih/b8h5TIcv+1+Hw0PDQWJTKDKzFZzcKOiW1wJza3XoAQlkCuXLbymPYB8+ZQyw8mHvdw560e8zVFIWyA==} + hermes-estree@0.25.1: + resolution: {integrity: sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==} + + hermes-parser@0.25.1: + resolution: {integrity: sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==} + html-encoding-sniffer@6.0.0: resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==} engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} @@ -1078,6 +1276,9 @@ packages: resolution: {integrity: sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw==} engines: {node: '>= 4'} + import-meta-resolve@4.2.0: + resolution: {integrity: sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==} + imurmurhash@0.1.4: resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} engines: {node: '>=0.8.19'} @@ -1131,6 +1332,9 @@ packages: resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} hasBin: true + js-tokens@10.0.0: + resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==} + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -1143,6 +1347,11 @@ packages: canvas: optional: true + jsesc@3.1.0: + resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} + engines: {node: '>=6'} + hasBin: true + json-buffer@3.0.1: resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} @@ -1324,6 +1533,9 @@ packages: resolution: {integrity: sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==} engines: {node: 20 || >=22} + lru-cache@5.1.1: + resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} + lz-string@1.5.0: resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} hasBin: true @@ -1370,6 +1582,10 @@ packages: natural-compare@1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + node-releases@2.0.51: + resolution: {integrity: sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==} + engines: {node: '>=18'} + obug@2.1.4: resolution: {integrity: sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==} engines: {node: '>=12.20.0'} @@ -1518,6 +1734,10 @@ packages: scheduler@0.27.0: resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==} + semver@6.3.1: + resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} + hasBin: true + semver@7.8.5: resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} engines: {node: '>=10'} @@ -1666,6 +1886,12 @@ packages: until-async@3.0.2: resolution: {integrity: sha512-IiSk4HlzAMqTUseHHe3VhIGyuFmN90zMTpD3Z3y8jeQbzLIq500MVM7Jq2vUAnTKAFPJrqwkzr6PoTcPhGcOiw==} + update-browserslist-db@1.2.3: + resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==} + hasBin: true + peerDependencies: + browserslist: '>= 4.21.0' + uri-js@4.4.1: resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} @@ -1803,6 +2029,9 @@ packages: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} + yallist@3.1.1: + resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} + yargs-parser@21.1.1: resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} engines: {node: '>=12'} @@ -1815,6 +2044,12 @@ packages: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} + zod-validation-error@4.0.2: + resolution: {integrity: sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==} + engines: {node: '>=18.0.0'} + peerDependencies: + zod: ^3.25.0 || ^4.0.0 + zod@4.4.3: resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==} @@ -1853,10 +2088,205 @@ snapshots: js-tokens: 4.0.0 picocolors: 1.1.1 + '@babel/code-frame@8.0.0': + dependencies: + '@babel/helper-validator-identifier': 8.0.4 + js-tokens: 10.0.0 + + '@babel/compat-data@7.29.7': {} + + '@babel/compat-data@8.0.0': {} + + '@babel/core@7.29.7(supports-color@7.2.0)': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/generator': 7.29.7 + '@babel/helper-compilation-targets': 7.29.7 + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0))(supports-color@7.2.0) + '@babel/helpers': 7.29.7 + '@babel/parser': 7.29.7 + '@babel/template': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@7.2.0) + '@babel/types': 7.29.7 + '@jridgewell/remapping': 2.3.5 + convert-source-map: 2.0.0 + debug: 4.4.3(supports-color@7.2.0) + gensync: 1.0.0-beta.2 + json5: 2.2.3 + semver: 6.3.1 + transitivePeerDependencies: + - supports-color + + '@babel/core@8.0.1': + dependencies: + '@babel/code-frame': 8.0.0 + '@babel/generator': 8.0.0 + '@babel/helper-compilation-targets': 8.0.0 + '@babel/helpers': 8.0.0 + '@babel/parser': 8.0.4 + '@babel/template': 8.0.0 + '@babel/traverse': 8.0.4 + '@babel/types': 8.0.4 + '@types/gensync': 1.0.5 + convert-source-map: 2.0.0 + empathic: 2.0.1 + gensync: 1.0.0-beta.2 + import-meta-resolve: 4.2.0 + json5: 2.2.3 + obug: 2.1.4 + semver: 7.8.5 + + '@babel/eslint-parser@8.0.1(@babel/core@8.0.1)(eslint@10.8.0(jiti@2.7.0)(supports-color@7.2.0))': + dependencies: + '@babel/core': 8.0.1 + eslint: 10.8.0(jiti@2.7.0)(supports-color@7.2.0) + eslint-scope: 9.1.2 + eslint-visitor-keys: 5.0.1 + semver: 7.8.5 + + '@babel/generator@7.29.7': + dependencies: + '@babel/parser': 7.29.7 + '@babel/types': 7.29.7 + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + jsesc: 3.1.0 + + '@babel/generator@8.0.0': + dependencies: + '@babel/parser': 8.0.4 + '@babel/types': 8.0.4 + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + '@types/jsesc': 2.5.1 + jsesc: 3.1.0 + + '@babel/helper-compilation-targets@7.29.7': + dependencies: + '@babel/compat-data': 7.29.7 + '@babel/helper-validator-option': 7.29.7 + browserslist: 4.28.7 + lru-cache: 5.1.1 + semver: 6.3.1 + + '@babel/helper-compilation-targets@8.0.0': + dependencies: + '@babel/compat-data': 8.0.0 + '@babel/helper-validator-option': 8.0.0 + browserslist: 4.28.7 + lru-cache: 11.5.2 + semver: 7.8.5 + + '@babel/helper-globals@7.29.7': {} + + '@babel/helper-globals@8.0.0': {} + + '@babel/helper-module-imports@7.29.7(supports-color@7.2.0)': + dependencies: + '@babel/traverse': 7.29.7(supports-color@7.2.0) + '@babel/types': 7.29.7 + transitivePeerDependencies: + - supports-color + + '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))(supports-color@7.2.0)': + dependencies: + '@babel/core': 7.29.7(supports-color@7.2.0) + '@babel/helper-module-imports': 7.29.7(supports-color@7.2.0) + '@babel/helper-validator-identifier': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@7.2.0) + transitivePeerDependencies: + - supports-color + + '@babel/helper-plugin-utils@8.0.1(@babel/core@8.0.1)': + dependencies: + '@babel/core': 8.0.1 + + '@babel/helper-string-parser@7.29.7': {} + + '@babel/helper-string-parser@8.0.0': {} + '@babel/helper-validator-identifier@7.29.7': {} + '@babel/helper-validator-identifier@8.0.4': {} + + '@babel/helper-validator-option@7.29.7': {} + + '@babel/helper-validator-option@8.0.0': {} + + '@babel/helpers@7.29.7': + dependencies: + '@babel/template': 7.29.7 + '@babel/types': 7.29.7 + + '@babel/helpers@8.0.0': + dependencies: + '@babel/template': 8.0.0 + '@babel/types': 8.0.4 + + '@babel/parser@7.29.7': + dependencies: + '@babel/types': 7.29.7 + + '@babel/parser@8.0.4': + dependencies: + '@babel/types': 8.0.4 + + '@babel/plugin-syntax-jsx@8.0.1(@babel/core@8.0.1)': + dependencies: + '@babel/core': 8.0.1 + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) + + '@babel/plugin-syntax-typescript@8.0.3(@babel/core@8.0.1)': + dependencies: + '@babel/core': 8.0.1 + '@babel/helper-plugin-utils': 8.0.1(@babel/core@8.0.1) + '@babel/runtime@7.29.7': {} + '@babel/template@7.29.7': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/parser': 7.29.7 + '@babel/types': 7.29.7 + + '@babel/template@8.0.0': + dependencies: + '@babel/code-frame': 8.0.0 + '@babel/parser': 8.0.4 + '@babel/types': 8.0.4 + + '@babel/traverse@7.29.7(supports-color@7.2.0)': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/generator': 7.29.7 + '@babel/helper-globals': 7.29.7 + '@babel/parser': 7.29.7 + '@babel/template': 7.29.7 + '@babel/types': 7.29.7 + debug: 4.4.3(supports-color@7.2.0) + transitivePeerDependencies: + - supports-color + + '@babel/traverse@8.0.4': + dependencies: + '@babel/code-frame': 8.0.0 + '@babel/generator': 8.0.0 + '@babel/helper-globals': 8.0.0 + '@babel/parser': 8.0.4 + '@babel/template': 8.0.0 + '@babel/types': 8.0.4 + obug: 2.1.4 + + '@babel/types@7.29.7': + dependencies: + '@babel/helper-string-parser': 7.29.7 + '@babel/helper-validator-identifier': 7.29.7 + + '@babel/types@8.0.4': + dependencies: + '@babel/helper-string-parser': 8.0.0 + '@babel/helper-validator-identifier': 8.0.4 + '@bramus/specificity@2.4.2': dependencies: css-tree: 3.2.1 @@ -2213,6 +2643,10 @@ snapshots: '@types/estree@1.0.9': {} + '@types/gensync@1.0.5': {} + + '@types/jsesc@2.5.1': {} + '@types/json-schema@7.0.15': {} '@types/node@24.13.3': @@ -2383,6 +2817,8 @@ snapshots: balanced-match@4.0.4: {} + baseline-browser-mapping@2.11.1: {} + bidi-js@1.0.3: dependencies: require-from-string: 2.0.2 @@ -2391,6 +2827,16 @@ snapshots: dependencies: balanced-match: 4.0.4 + browserslist@4.28.7: + dependencies: + baseline-browser-mapping: 2.11.1 + caniuse-lite: 1.0.30001806 + electron-to-chromium: 1.5.396 + node-releases: 2.0.51 + update-browserslist-db: 1.2.3(browserslist@4.28.7) + + caniuse-lite@1.0.30001806: {} + chai@6.2.2: {} chalk@4.1.2: @@ -2479,8 +2925,12 @@ snapshots: dom-accessibility-api@0.6.3: {} + electron-to-chromium@1.5.396: {} + emoji-regex@8.0.0: {} + empathic@2.0.1: {} + enhanced-resolve@5.24.2: dependencies: graceful-fs: 4.2.11 @@ -2496,6 +2946,17 @@ snapshots: escape-string-regexp@4.0.0: {} + eslint-plugin-react-hooks@7.1.1(eslint@10.8.0(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0): + dependencies: + '@babel/core': 7.29.7(supports-color@7.2.0) + '@babel/parser': 7.29.7 + eslint: 10.8.0(jiti@2.7.0)(supports-color@7.2.0) + hermes-parser: 0.25.1 + zod: 4.4.3 + zod-validation-error: 4.0.2(zod@4.4.3) + transitivePeerDependencies: + - supports-color + eslint-scope@9.1.2: dependencies: '@types/esrecurse': 4.3.1 @@ -2612,6 +3073,8 @@ snapshots: function-bind@1.1.2: {} + gensync@1.0.0-beta.2: {} + get-caller-file@2.0.5: {} glob-parent@6.0.2: @@ -2639,6 +3102,12 @@ snapshots: '@types/set-cookie-parser': 2.4.10 set-cookie-parser: 3.1.2 + hermes-estree@0.25.1: {} + + hermes-parser@0.25.1: + dependencies: + hermes-estree: 0.25.1 + html-encoding-sniffer@6.0.0: dependencies: '@exodus/bytes': 1.15.1 @@ -2649,6 +3118,8 @@ snapshots: ignore@7.0.6: {} + import-meta-resolve@4.2.0: {} + imurmurhash@0.1.4: {} indent-string@4.0.0: {} @@ -2684,6 +3155,8 @@ snapshots: jiti@2.7.0: {} + js-tokens@10.0.0: {} + js-tokens@4.0.0: {} jsdom@29.1.1: @@ -2712,6 +3185,8 @@ snapshots: transitivePeerDependencies: - '@noble/hashes' + jsesc@3.1.0: {} + json-buffer@3.0.1: {} json-schema-traverse@0.4.1: {} @@ -2835,6 +3310,10 @@ snapshots: lru-cache@11.5.2: {} + lru-cache@5.1.1: + dependencies: + yallist: 3.1.1 + lz-string@1.5.0: {} magic-string@0.30.21: @@ -2884,6 +3363,8 @@ snapshots: natural-compare@1.4.0: {} + node-releases@2.0.51: {} + obug@2.1.4: {} optionator@0.9.4: @@ -3030,6 +3511,8 @@ snapshots: scheduler@0.27.0: {} + semver@6.3.1: {} + semver@7.8.5: {} set-cookie-parser@2.7.2: {} @@ -3166,6 +3649,12 @@ snapshots: until-async@3.0.2: {} + update-browserslist-db@1.2.3(browserslist@4.28.7): + dependencies: + browserslist: 4.28.7 + escalade: 3.2.0 + picocolors: 1.1.1 + uri-js@4.4.1: dependencies: punycode: 2.3.1 @@ -3251,6 +3740,8 @@ snapshots: y18n@5.0.8: {} + yallist@3.1.1: {} + yargs-parser@21.1.1: {} yargs@17.7.3: @@ -3265,4 +3756,8 @@ snapshots: yocto-queue@0.1.0: {} + zod-validation-error@4.0.2(zod@4.4.3): + dependencies: + zod: 4.4.3 + zod@4.4.3: {} diff --git a/scripts/check-registries.mjs b/scripts/check-registries.mjs index d32e03c4..ea9d40ac 100644 --- a/scripts/check-registries.mjs +++ b/scripts/check-registries.mjs @@ -2,12 +2,53 @@ import { access, mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import { pathToFileURL } from "node:url"; +/** @param {string} name @param {string} fallback */ +function argumentValue(name, fallback) { + const index = process.argv.indexOf(name); + return index >= 0 && process.argv[index + 1] ? process.argv[index + 1] : fallback; +} + +const governancePath = argumentValue( + "--governance", + "config/contracts/registry-governance.json", +); +const artifactPath = argumentValue( + "--artifact", + "artifacts/quality/registries.json", +); const governance = JSON.parse( - await readFile("config/contracts/registry-governance.json", "utf8"), + await readFile(governancePath, "utf8"), ); const failures = []; const owners = new Map(); const snapshots = []; +const rowsByRegistry = new Map(); +const registryExtensions = [".js", ".jsx", ".mjs", ".ts", ".tsx", ".mts"]; + +/** @param {string} declaredPath */ +async function resolveRegistrySource(declaredPath) { + const extension = path.extname(declaredPath); + const basePath = extension + ? declaredPath.slice(0, -extension.length) + : declaredPath; + const candidates = []; + for (const candidateExtension of registryExtensions) { + const candidate = `${basePath}${candidateExtension}`; + try { + await access(candidate); + candidates.push(candidate); + } catch { + // A migration may legitimately replace the declared extension. + } + } + if (candidates.length > 1) { + failures.push( + `ambiguous registry source ${declaredPath}: ${candidates.join(", ")}`, + ); + return null; + } + return candidates[0] ?? null; +} for (const specification of governance.registries) { if (owners.has(specification.registryId)) { @@ -16,10 +57,11 @@ for (const specification of governance.registries) { owners.set(specification.registryId, specification.owner); let rows = specification.declaredRows; + const sourcePath = await resolveRegistrySource(specification.path); try { - await access(specification.path); + if (!sourcePath) throw new Error("missing registry source"); const module = await import( - `${pathToFileURL(path.resolve(specification.path)).href}?registry-check=${Date.now()}` + `${pathToFileURL(path.resolve(sourcePath)).href}?registry-check=${Date.now()}` ); rows = module[specification.exportName]; } catch { @@ -31,6 +73,8 @@ for (const specification of governance.registries) { continue; } + rowsByRegistry.set(specification.registryId, rows); + for (const [rowName, row] of Object.entries(rows)) { if (!row || typeof row !== "object" || Array.isArray(row)) { failures.push(`${specification.registryId}.${rowName} is not an object`); @@ -43,16 +87,61 @@ for (const specification of governance.registries) { } } + for (const field of specification.uniqueFields ?? []) { + const values = new Map(); + for (const [rowName, row] of Object.entries(rows)) { + if (!row || typeof row !== "object" || Array.isArray(row)) continue; + const value = row[field]; + if (value === undefined) continue; + if (values.has(value)) { + failures.push( + `${specification.registryId}.${rowName} duplicates ${field}=${String(value)} from ${values.get(value)}`, + ); + } else { + values.set(value, rowName); + } + } + } + snapshots.push({ registryId: specification.registryId, owner: specification.owner, - source: specification.path, + source: sourcePath ?? specification.path, rowCount: Object.keys(rows).length, rows, }); } -const sourceFiles = [ +for (const specification of governance.registries) { + const rows = rowsByRegistry.get(specification.registryId); + if (!rows) continue; + for (const reference of specification.references ?? []) { + const targetRows = rowsByRegistry.get(reference.registryId); + if (!targetRows) { + failures.push( + `${specification.registryId} references unknown registry ${reference.registryId}`, + ); + continue; + } + const targetValues = new Set( + Object.values(targetRows) + .filter((row) => row && typeof row === "object" && !Array.isArray(row)) + .map((row) => row[reference.targetField]) + .filter((value) => value !== undefined), + ); + for (const [rowName, row] of Object.entries(rows)) { + if (!row || typeof row !== "object" || Array.isArray(row)) continue; + const value = row[reference.field]; + if (value !== undefined && !targetValues.has(value)) { + failures.push( + `${specification.registryId}.${rowName}.${reference.field} references unknown ${reference.registryId}.${reference.targetField}=${String(value)}`, + ); + } + } + } +} + +const sourceFiles = governance.sourceDirectories ?? [ "src/application", "src/presentation", "src/domain", @@ -75,7 +164,7 @@ async function scanDirectory(directory) { await scanDirectory(target); continue; } - if (!/\.(js|jsx|mjs)$/.test(entry.name)) continue; + if (!/\.(js|jsx|mjs|ts|tsx|mts)$/.test(entry.name)) continue; const content = await readFile(target, "utf8"); for (const pattern of adHocPatterns) { if (pattern.expression.test(content)) { @@ -91,7 +180,7 @@ for (const sourceDirectory of sourceFiles) { await mkdir("artifacts/quality", { recursive: true }); await writeFile( - "artifacts/quality/registries.json", + artifactPath, `${JSON.stringify( { schemaVersion: 1, diff --git a/src/adapters/http/client.js b/src/adapters/http/client.js index 7d0b8b2c..5ff03bb3 100644 --- a/src/adapters/http/client.js +++ b/src/adapters/http/client.js @@ -21,21 +21,7 @@ const noAuthSession = onUnauthenticated: () => {}, }); -/** - * @typedef {{ - * kind: string, - * code: string, - * retryable: boolean, - * operationId: string, - * attemptCount: number, - * httpStatus?: number, - * requestId?: string, - * traceId?: string, - * retryAfterMs?: number, - * userMessageKey: string, - * action: string - * }} HttpFailure - */ +/** @typedef {import("../../contracts/errors.js").ApiFailure} HttpFailure */ /** * @typedef {{ ok: true, value: unknown, meta: Record } | @@ -74,6 +60,7 @@ export function createHttpClient(dependencies) { * signal?: AbortSignal, * idempotencyKey?: string * }} [input] + * @returns {Promise} */ async function execute(operationId, input = {}) { const operation = getApiOperation(operationId); diff --git a/tests/component/render-boundary.test.jsx b/tests/component/render-boundary.test.jsx index 65696dce..a920c16c 100644 --- a/tests/component/render-boundary.test.jsx +++ b/tests/component/render-boundary.test.jsx @@ -10,6 +10,7 @@ import { AsyncSurface } from "../../src/presentation/components/async-surface.js import { BootErrorShell } from "../../src/presentation/boundaries/boot-error-shell.jsx"; import { FeatureBoundary } from "../../src/presentation/boundaries/render-error-boundary.jsx"; +/** @returns {import("react").ReactNode} */ function Defect() { throw new Error("raw render stack"); } diff --git a/tests/component/router.test.jsx b/tests/component/router.test.jsx index fc7782d8..d9fdfc09 100644 --- a/tests/component/router.test.jsx +++ b/tests/component/router.test.jsx @@ -30,7 +30,7 @@ describe("application router", () => { render(); await user.click( - await screen.findByRole("link", { name: "UI 구성요소", exact: true }), + await screen.findByRole("link", { name: "UI 구성요소" }), ); expect( diff --git a/tests/component/sample-resource-page.test.jsx b/tests/component/sample-resource-page.test.jsx index 9910cac7..63dc5533 100644 --- a/tests/component/sample-resource-page.test.jsx +++ b/tests/component/sample-resource-page.test.jsx @@ -7,9 +7,10 @@ import { SampleResourcePage } from "../../src/sample/contract-fixture/sample-res describe("removable sample feature page", () => { it("renders the API-to-view-model result through AsyncSurface", async () => { + /** @type {Parameters[0]["facade"]} */ const facade = { listResources: async () => ({ - ok: true, + ok: /** @type {const} */ (true), value: [ { resourceId: "resource-1", @@ -18,7 +19,14 @@ describe("removable sample feature page", () => { }, ], }), - createResource: async () => ({ ok: true, value: {} }), + createResource: async () => ({ + ok: /** @type {const} */ (true), + value: { + resourceId: "resource-created", + title: "Created", + createdAtLabel: null, + }, + }), }; render(); @@ -27,9 +35,10 @@ describe("removable sample feature page", () => { }); it("renders normalized terminal errors without raw DTO fields", async () => { + /** @type {Parameters[0]["facade"]} */ const facade = { listResources: async () => ({ - ok: false, + ok: /** @type {const} */ (false), error: { kind: "SERVER_FAILURE", code: "SERVER_FAILURE", @@ -40,7 +49,14 @@ describe("removable sample feature page", () => { action: "retry", }, }), - createResource: async () => ({ ok: true, value: {} }), + createResource: async () => ({ + ok: /** @type {const} */ (true), + value: { + resourceId: "resource-created", + title: "Created", + createdAtLabel: null, + }, + }), }; render(); diff --git a/tests/component/typescript-tooling-smoke.test.tsx b/tests/component/typescript-tooling-smoke.test.tsx new file mode 100644 index 00000000..38226ad3 --- /dev/null +++ b/tests/component/typescript-tooling-smoke.test.tsx @@ -0,0 +1,20 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +type StatusProps = Readonly<{ + label: string; + tone: "neutral" | "positive"; +}>; + +function Status({ label, tone }: StatusProps) { + return {label}; +} + +describe("TSX test tooling", () => { + it("parses, lints, type-checks, and renders TSX", () => { + render(); + expect(screen.getByText("ready")).toHaveAttribute("data-tone", "positive"); + }); +}); diff --git a/tests/fixtures/architecture/allowed/presentation-facade.tsx b/tests/fixtures/architecture/allowed/presentation-facade.tsx new file mode 100644 index 00000000..41bbf992 --- /dev/null +++ b/tests/fixtures/architecture/allowed/presentation-facade.tsx @@ -0,0 +1,7 @@ +import { createApplication } from "../../../../src/application/create-application.js"; + +export const applicationFactory = createApplication; + +export function AllowedPresentationFixture() { + return

allowed

; +} diff --git a/tests/fixtures/architecture/forbidden/presentation-imports-adapter.tsx b/tests/fixtures/architecture/forbidden/presentation-imports-adapter.tsx new file mode 100644 index 00000000..7adc59e3 --- /dev/null +++ b/tests/fixtures/architecture/forbidden/presentation-imports-adapter.tsx @@ -0,0 +1,5 @@ +import "../../../../src/adapters/http/client.js"; + +export function InvalidPresentationFixture() { + return

invalid

; +} diff --git a/tests/fixtures/registry/forbidden/governance.json b/tests/fixtures/registry/forbidden/governance.json new file mode 100644 index 00000000..f2815f87 --- /dev/null +++ b/tests/fixtures/registry/forbidden/governance.json @@ -0,0 +1,33 @@ +{ + "schemaVersion": 1, + "sourceDirectories": [], + "registries": [ + { + "registryId": "FIXTURE-SOURCE", + "path": "tests/fixtures/registry/forbidden/invalid-registry.js", + "exportName": "INVALID_REGISTRY", + "owner": "fixture", + "requiredFields": ["id", "target"], + "uniqueFields": ["id"], + "references": [ + { + "field": "target", + "registryId": "FIXTURE-TARGET", + "targetField": "id" + } + ] + }, + { + "registryId": "FIXTURE-TARGET", + "path": "tests/fixtures/registry/forbidden/invalid-registry.js", + "exportName": "TARGET_REGISTRY", + "owner": "fixture", + "requiredFields": ["id"], + "uniqueFields": ["id"] + } + ], + "compatibilityImpact": { + "allowed": ["none", "additive", "behavior-change", "breaking"], + "current": "breaking" + } +} diff --git a/tests/fixtures/registry/forbidden/invalid-registry.ts b/tests/fixtures/registry/forbidden/invalid-registry.ts new file mode 100644 index 00000000..df631445 --- /dev/null +++ b/tests/fixtures/registry/forbidden/invalid-registry.ts @@ -0,0 +1,13 @@ +type InvalidRow = Readonly<{ + id: string; + target?: string; +}>; + +export const INVALID_REGISTRY: Record = { + FIRST: { id: "duplicate", target: "missing" }, + SECOND: { id: "duplicate" }, +}; + +export const TARGET_REGISTRY = { + KNOWN: { id: "known" }, +} as const; diff --git a/tests/fixtures/security/allowed/safe-text.tsx b/tests/fixtures/security/allowed/safe-text.tsx new file mode 100644 index 00000000..5d6f9787 --- /dev/null +++ b/tests/fixtures/security/allowed/safe-text.tsx @@ -0,0 +1,3 @@ +export function SafeTextFixture({ value }: Readonly<{ value: string }>) { + return

{value}

; +} diff --git a/tests/fixtures/security/forbidden/raw-html.tsx b/tests/fixtures/security/forbidden/raw-html.tsx new file mode 100644 index 00000000..4b8964f2 --- /dev/null +++ b/tests/fixtures/security/forbidden/raw-html.tsx @@ -0,0 +1,3 @@ +export function UnsafeHtmlFixture({ value }: Readonly<{ value: string }>) { + return
; +} diff --git a/tests/fixtures/typecheck/invalid-port-implementation.ts b/tests/fixtures/typecheck/invalid-port-implementation.ts new file mode 100644 index 00000000..f24f583c --- /dev/null +++ b/tests/fixtures/typecheck/invalid-port-implementation.ts @@ -0,0 +1,7 @@ +interface ClockPort { + now(): number; +} + +export const invalidClock: ClockPort = { + now: () => "not-a-number", +}; diff --git a/tests/fixtures/typecheck/invalid-result-narrowing.ts b/tests/fixtures/typecheck/invalid-result-narrowing.ts new file mode 100644 index 00000000..d211b549 --- /dev/null +++ b/tests/fixtures/typecheck/invalid-result-narrowing.ts @@ -0,0 +1,7 @@ +type Result = + | Readonly<{ ok: true; value: T }> + | Readonly<{ ok: false; error: E }>; + +export function invalidUnwrap(result: Result): number { + return result.value; +} diff --git a/tests/integration/auth-recovery.test.js b/tests/integration/auth-recovery.test.js index bb04397a..72955b01 100644 --- a/tests/integration/auth-recovery.test.js +++ b/tests/integration/auth-recovery.test.js @@ -5,6 +5,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest import { createExternalAuthSessionAdapter } from "../../src/adapters/auth/external-session-adapter.js"; import { createHttpClient } from "../../src/adapters/http/client.js"; +/** @type {number[]} */ let responseStatuses = []; const server = setupServer( http.get("https://api.test/api/sample/resources", () => { @@ -36,16 +37,32 @@ afterAll(() => server.close()); const clock = { now: () => 0, sleep: async () => {} }; +/** + * @param {Partial[0]>} overrides + * @returns {Parameters[0]} + */ +function createOwner(overrides = {}) { + return { + readState: () => "authenticated", + subscribe: () => () => {}, + beginSignIn: async () => {}, + signOut: async () => {}, + attachCredential: async (request) => request, + recoverSession: async () => "restored", + notifyUnauthenticated: () => {}, + ...overrides, + }; +} + describe("bounded 401 session recovery", () => { it("calls recovery once and replays a safe request once", async () => { responseStatuses = [401, 200]; - const recoverSession = vi.fn(async () => "restored"); - const authSession = createExternalAuthSessionAdapter({ - readState: () => "authenticated", + const recoverSession = vi.fn(async () => /** @type {const} */ ("restored")); + const authSession = createExternalAuthSessionAdapter(createOwner({ attachCredential: async (request) => request, recoverSession, notifyUnauthenticated: vi.fn(), - }); + })); const client = createHttpClient({ baseUrl: "https://api.test", authSession, @@ -61,12 +78,11 @@ describe("bounded 401 session recovery", () => { it("stops after a second 401 and notifies unauthenticated once", async () => { responseStatuses = [401, 401]; const notifyUnauthenticated = vi.fn(); - const authSession = createExternalAuthSessionAdapter({ - readState: () => "authenticated", + const authSession = createExternalAuthSessionAdapter(createOwner({ attachCredential: async (request) => request, recoverSession: async () => "restored", notifyUnauthenticated, - }); + })); const client = createHttpClient({ baseUrl: "https://api.test", authSession, @@ -81,14 +97,13 @@ describe("bounded 401 session recovery", () => { }); it("normalizes attach and invalid recovery failures", async () => { - const attachFailure = createExternalAuthSessionAdapter({ - readState: () => "authenticated", + const attachFailure = createExternalAuthSessionAdapter(createOwner({ attachCredential: async () => { throw new Error("credential detail"); }, recoverSession: async () => "restored", notifyUnauthenticated: vi.fn(), - }); + })); const client = createHttpClient({ baseUrl: "https://api.test", authSession: attachFailure, diff --git a/tests/runtime-schema/http-schema.test.js b/tests/runtime-schema/http-schema.test.js index d9b4b1d9..9fd8d6eb 100644 --- a/tests/runtime-schema/http-schema.test.js +++ b/tests/runtime-schema/http-schema.test.js @@ -31,6 +31,7 @@ describe("HTTP runtime schema boundary", () => { success: true, data: [{ id: "resource-1", additive: "accepted" }], }); + if (!result.success) throw new Error("expected valid sample payload"); expect(result.data).not.toBe(source); }); diff --git a/tests/runtime-schema/runtime-config.test.js b/tests/runtime-schema/runtime-config.test.js index d94b1054..7630ee96 100644 --- a/tests/runtime-schema/runtime-config.test.js +++ b/tests/runtime-schema/runtime-config.test.js @@ -25,7 +25,8 @@ describe("runtime configuration boundary", () => { [{ ...validConfig, TELEMETRY_ENABLED: "false" }, "ambiguous boolean"], [{ ...validConfig, CONFIG_SCHEMA_VERSION: "next" }, "version"], [{ ...validConfig, UNKNOWN_KEY: true }, "unknown key"], - ])("rejects invalid config: %s (%s)", (candidate) => { + ])("rejects invalid config: %s (%s)", (candidate, _reason) => { + void _reason; expect(validateRuntimeConfig(candidate).success).toBe(false); }); diff --git a/tests/unit/auth-session-adapter.test.js b/tests/unit/auth-session-adapter.test.js index f138e5e9..c3b82570 100644 --- a/tests/unit/auth-session-adapter.test.js +++ b/tests/unit/auth-session-adapter.test.js @@ -36,6 +36,7 @@ describe("external AuthSessionPort adapter", () => { beginSignIn: async () => {}, signOut: async () => {}, attachCredential: async (request) => request, + // @ts-expect-error Deliberately violates the external-owner contract. recoverSession: async () => "unexpected", notifyUnauthenticated: vi.fn(), }); @@ -57,7 +58,7 @@ describe("external AuthSessionPort adapter", () => { }); expect(adapter.getState()).toBe("unauthenticated"); - await adapter.beginSignIn("/"); + await adapter.beginSignIn(); expect(adapter.getState()).toBe("authenticated"); await adapter.signOut(); expect(adapter.getState()).toBe("unauthenticated"); diff --git a/tests/unit/chunk-recovery.test.js b/tests/unit/chunk-recovery.test.js index 41fd3abe..66b6c0b6 100644 --- a/tests/unit/chunk-recovery.test.js +++ b/tests/unit/chunk-recovery.test.js @@ -3,15 +3,16 @@ import { describe, expect, it } from "vitest"; import { decideChunkRecovery } from "../../src/application/use-cases/decide-chunk-recovery.js"; function memoryStorage() { + /** @type {unknown} */ let value; - return { - read: () => ({ ok: true, value }), + return /** @type {import("../../src/application/ports/storage-port.js").StoragePort} */ ({ + read: () => ({ ok: /** @type {const} */ (true), value }), write: (_key, next) => { value = next; - return { ok: true }; + return { ok: /** @type {const} */ (true) }; }, - remove: () => ({ ok: true }), - }; + remove: () => ({ ok: /** @type {const} */ (true) }), + }); } describe("controlled chunk recovery", () => { diff --git a/tests/unit/color-scheme.test.js b/tests/unit/color-scheme.test.js index 065aa968..8b70c72e 100644 --- a/tests/unit/color-scheme.test.js +++ b/tests/unit/color-scheme.test.js @@ -21,11 +21,15 @@ describe("color scheme policy", () => { }); it("applies a persisted preference before application paint", () => { - const storage = { - read: () => ({ ok: true, value: "system" }), - write: () => ({ ok: true }), - remove: () => ({ ok: true }), - }; + const storage = + /** @type {import("../../src/application/ports/storage-port.js").StoragePort} */ ({ + read: () => ({ + ok: /** @type {const} */ (true), + value: "system", + }), + write: () => ({ ok: /** @type {const} */ (true) }), + remove: () => ({ ok: /** @type {const} */ (true) }), + }); const result = initializeColorScheme(storage, { documentElement: document.documentElement, diff --git a/tests/unit/error-classification.test.js b/tests/unit/error-classification.test.js index 4de3b47e..600ba64e 100644 --- a/tests/unit/error-classification.test.js +++ b/tests/unit/error-classification.test.js @@ -39,14 +39,20 @@ describe("frontend failure classification", () => { }); it("projects only allowlisted safe fields", () => { - const result = createFailure("SERVER_FAILURE", "LIST_SAMPLE_RESOURCES", 0, { + const untrustedDetails = { code: "TEMPORARY", httpStatus: 503, requestId: "request-1", stack: "must not leak", body: "must not leak", authorization: "Bearer secret", - }); + }; + const result = createFailure( + "SERVER_FAILURE", + "LIST_SAMPLE_RESOURCES", + 0, + untrustedDetails, + ); expect(result).toMatchObject({ kind: "SERVER_FAILURE", diff --git a/tests/unit/promotion-readiness.test.js b/tests/unit/promotion-readiness.test.js index dbf5ac2f..44ed0e2f 100644 --- a/tests/unit/promotion-readiness.test.js +++ b/tests/unit/promotion-readiness.test.js @@ -6,7 +6,10 @@ import { } from "../../src/application/policies/promotion-readiness.js"; const allGateIds = Object.values(PROMOTION_FORMULA).flat(); -const passing = Object.fromEntries(allGateIds.map((gateId) => [gateId, "PASS"])); +const passing = + /** @type {Record} */ ( + Object.fromEntries(allGateIds.map((gateId) => [gateId, "PASS"])) + ); describe("promotion readiness formula", () => { it("requires every upstream tier before downstream readiness", () => { @@ -30,7 +33,11 @@ describe("promotion readiness formula", () => { ...passing, [failedGate]: "FAIL", }); - expect(result[readiness]).toBe(false); + const readinessKey = + /** @type {keyof ReturnType} */ ( + readiness + ); + expect(result[readinessKey]).toBe(false); }); it("does not treat missing or unverified gates as pass", () => { diff --git a/tests/unit/registry-governance.test.js b/tests/unit/registry-governance.test.js index ad4688f7..fa9a5539 100644 --- a/tests/unit/registry-governance.test.js +++ b/tests/unit/registry-governance.test.js @@ -6,11 +6,15 @@ describe("registry governance manifest", () => { const governance = JSON.parse( await readFile("config/contracts/registry-governance.json", "utf8"), ); + const registries = + /** @type {Array<{registryId: string, owner: string}>} */ ( + governance.registries + ); expect(governance.registries).toHaveLength(8); - expect(new Set(governance.registries.map((entry) => entry.registryId)).size).toBe( + expect(new Set(registries.map((entry) => entry.registryId)).size).toBe( 8, ); - expect(governance.registries.every((entry) => entry.owner)).toBe(true); + expect(registries.every((entry) => entry.owner)).toBe(true); expect(governance.compatibilityImpact.allowed).toEqual([ "none", "additive", diff --git a/tests/unit/runtime-adapters.test.js b/tests/unit/runtime-adapters.test.js index 9ba653f0..fe7ffb4a 100644 --- a/tests/unit/runtime-adapters.test.js +++ b/tests/unit/runtime-adapters.test.js @@ -10,7 +10,7 @@ const runtime = { AUTH_MODE: "demo", }, }; -const release = { +const release = /** @type {const} */ ({ schemaVersion: 1, appVersion: "0.1.0", buildId: "build-a", @@ -20,7 +20,7 @@ const release = { assetManifestHash: "hash-a", releaseId: "release-a", builtAt: "2026-07-25T00:00:00Z", -}; +}); describe("runtime adapter composition", () => { it("constructs the local demo seam and infrastructure adapters", async () => { diff --git a/tests/unit/storage-registry.test.js b/tests/unit/storage-registry.test.js index fa752506..f5af2de5 100644 --- a/tests/unit/storage-registry.test.js +++ b/tests/unit/storage-registry.test.js @@ -7,8 +7,12 @@ import { defineStorageKey, } from "../../src/contracts/storage-keys.js"; +/** + * @param {{quota?: boolean}} [options] + * @returns {Storage} + */ function createStorage({ quota = false } = {}) { - const values = new Map(); + const values = /** @type {Map} */ (new Map()); return { getItem: (key) => values.get(key) ?? null, setItem: (key, value) => { diff --git a/tests/unit/telemetry.test.js b/tests/unit/telemetry.test.js index 3400abd3..67ccb0a9 100644 --- a/tests/unit/telemetry.test.js +++ b/tests/unit/telemetry.test.js @@ -56,7 +56,7 @@ describe("telemetry registry and redaction", () => { describe("best-effort telemetry adapter", () => { it("bounds the queue using oldest-drop without blocking callers", () => { - const scheduled = []; + const scheduled = /** @type {Array<() => void>} */ ([]); const adapter = createTelemetryAdapter({ enabled: true, endpoint: "https://telemetry.test/events", diff --git a/tests/unit/typescript-tooling-smoke.test.ts b/tests/unit/typescript-tooling-smoke.test.ts new file mode 100644 index 00000000..15b318fe --- /dev/null +++ b/tests/unit/typescript-tooling-smoke.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vitest"; + +type Result = + | Readonly<{ ok: true; value: T }> + | Readonly<{ ok: false; error: E }>; + +function summarize(result: Result): string { + return result.ok ? String(result.value) : result.error; +} + +describe("TypeScript test tooling", () => { + it("type-checks and executes discriminated unions in the test project", () => { + expect(summarize({ ok: true, value: 42 })).toBe("42"); + expect(summarize({ ok: false, error: "failed" })).toBe("failed"); + }); +}); diff --git a/tsconfig.app.json b/tsconfig.app.json new file mode 100644 index 00000000..056ff7ee --- /dev/null +++ b/tsconfig.app.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.base.json", + "compilerOptions": { + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": ["vite/client"] + }, + "include": ["src"], + "exclude": ["dist", "node_modules", "tests"] +} diff --git a/tsconfig.base.json b/tsconfig.base.json new file mode 100644 index 00000000..29dde9f9 --- /dev/null +++ b/tsconfig.base.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "allowJs": true, + "checkJs": true, + "noEmit": true, + "target": "ES2022", + "useDefineForClassFields": true, + "module": "ESNext", + "moduleResolution": "Bundler", + "resolveJsonModule": true, + "allowImportingTsExtensions": false, + "jsx": "react-jsx", + "strict": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "isolatedModules": true + } +} diff --git a/tsconfig.json b/tsconfig.json index d3c8554f..01490aab 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,20 +1,8 @@ { - "compilerOptions": { - "allowJs": true, - "checkJs": true, - "noEmit": true, - "target": "ES2022", - "useDefineForClassFields": true, - "lib": ["ES2022", "DOM", "DOM.Iterable"], - "module": "ESNext", - "moduleResolution": "Bundler", - "resolveJsonModule": true, - "allowImportingTsExtensions": false, - "jsx": "react-jsx", - "strict": true, - "skipLibCheck": true, - "types": ["vite/client", "node"] - }, - "include": ["src", "scripts", "vite.config.js"], - "exclude": ["dist", "node_modules", "tests/fixtures"] + "files": [], + "references": [ + { "path": "./tsconfig.app.json" }, + { "path": "./tsconfig.node.json" }, + { "path": "./tsconfig.test.json" } + ] } diff --git a/tsconfig.node.json b/tsconfig.node.json new file mode 100644 index 00000000..efc73b25 --- /dev/null +++ b/tsconfig.node.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.base.json", + "compilerOptions": { + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": ["node"] + }, + "include": ["scripts", "vite.config.js"], + "exclude": ["dist", "node_modules", "tests"] +} diff --git a/tsconfig.test.json b/tsconfig.test.json new file mode 100644 index 00000000..5f973411 --- /dev/null +++ b/tsconfig.test.json @@ -0,0 +1,20 @@ +{ + "extends": "./tsconfig.base.json", + "compilerOptions": { + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": ["node", "vite/client"] + }, + "include": [ + "tests/**/*.js", + "tests/**/*.jsx", + "tests/**/*.ts", + "tests/**/*.tsx", + "vitest.config.js", + "playwright.config.js" + ], + "exclude": [ + "dist", + "node_modules", + "tests/fixtures" + ] +} From 2dda17cf199f51130f826962a0da6d967ad90290 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sun, 26 Jul 2026 13:52:35 +0900 Subject: [PATCH 048/178] feat: connect application input and output boundaries --- .dependency-cruiser.cjs | 6 ++ config/ci/gates.json | 4 +- .../frontend-ports-adapters-and-boundaries.md | 26 ++++-- eslint.config.js | 20 +++- package.json | 2 + scripts/check-architecture.mjs | 47 +++++++++- src/adapters/http/client.js | 2 +- src/adapters/platform/system-clock.js | 19 ++++ src/application/create-application.js | 46 --------- src/application/create-application.ts | 73 +++++++++++++++ src/application/ports/auth-session-port.js | 18 +++- src/application/ports/clock-port.js | 23 +---- src/application/ports/in/application-api.ts | 41 ++++++++ src/application/ports/in/index.ts | 7 ++ .../ports/out/application-output-ports.ts | 18 ++++ src/application/ports/out/index.ts | 17 ++++ src/application/ports/release-info-port.js | 6 +- src/bootstrap/composition-root.js | 21 +++-- src/bootstrap/initialize-color-scheme.js | 7 +- src/bootstrap/main.jsx | 20 +--- src/bootstrap/runtime-adapters.js | 24 ++--- src/bootstrap/runtime-application.jsx | 28 ++++++ .../boundaries/render-error-boundary.jsx | 13 +-- src/presentation/pages/home-page.jsx | 24 +++++ .../providers/application-provider.tsx | 31 +++++++ .../providers/session-provider.jsx | 31 +++---- src/presentation/providers/theme-provider.jsx | 22 ++--- src/presentation/routes/app-router.jsx | 30 ++---- src/presentation/routes/navigation-policy.js | 2 +- tests/component/render-boundary.test.jsx | 12 +-- tests/component/router.test.jsx | 21 ++++- tests/component/runtime-application.test.jsx | 67 +++++++++++++ .../allowed/bootstrap-composes-adapter.ts | 3 + .../forbidden/application-imports-adapter.ts | 3 + .../forbidden/presentation-direct-fetch.tsx | 4 + .../presentation-imports-output-port.tsx | 5 + .../typecheck/invalid-application-input.ts | 5 + .../typecheck/invalid-application-output.ts | 7 ++ tests/helpers/create-test-application.js | 35 +++++++ tests/unit/application-boundary.test.ts | 93 +++++++++++++++++++ tests/unit/color-scheme.test.js | 14 +-- tests/unit/runtime-adapters.test.js | 13 ++- tests/unit/system-clock.test.js | 2 +- 43 files changed, 697 insertions(+), 215 deletions(-) create mode 100644 src/adapters/platform/system-clock.js delete mode 100644 src/application/create-application.js create mode 100644 src/application/create-application.ts create mode 100644 src/application/ports/in/application-api.ts create mode 100644 src/application/ports/in/index.ts create mode 100644 src/application/ports/out/application-output-ports.ts create mode 100644 src/application/ports/out/index.ts create mode 100644 src/bootstrap/runtime-application.jsx create mode 100644 src/presentation/providers/application-provider.tsx create mode 100644 tests/component/runtime-application.test.jsx create mode 100644 tests/fixtures/architecture/allowed/bootstrap-composes-adapter.ts create mode 100644 tests/fixtures/architecture/forbidden/application-imports-adapter.ts create mode 100644 tests/fixtures/architecture/forbidden/presentation-direct-fetch.tsx create mode 100644 tests/fixtures/architecture/forbidden/presentation-imports-output-port.tsx create mode 100644 tests/fixtures/typecheck/invalid-application-input.ts create mode 100644 tests/fixtures/typecheck/invalid-application-output.ts create mode 100644 tests/helpers/create-test-application.js create mode 100644 tests/unit/application-boundary.test.ts diff --git a/.dependency-cruiser.cjs b/.dependency-cruiser.cjs index a1e20df5..5197aa39 100644 --- a/.dependency-cruiser.cjs +++ b/.dependency-cruiser.cjs @@ -29,6 +29,12 @@ module.exports = { from: { path: "^src/adapters" }, to: { path: "^src/(presentation|bootstrap)" }, }, + { + name: "concrete-adapters-compose-only-in-bootstrap", + severity: "error", + from: { path: "^src/(domain|application|presentation|contracts|sample)" }, + to: { path: "^src/adapters" }, + }, { name: "no-circular-dependencies", severity: "error", diff --git a/config/ci/gates.json b/config/ci/gates.json index 7d8d4ed0..3b4ecb5e 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -76,7 +76,9 @@ { "script": "check:types", "expect": "pass" }, { "script": "check:types:fixture", "expect": "fail" }, { "script": "check:types:fixture:ts-port", "expect": "fail" }, - { "script": "check:types:fixture:ts-result", "expect": "fail" } + { "script": "check:types:fixture:ts-result", "expect": "fail" }, + { "script": "check:types:fixture:application-output", "expect": "fail" }, + { "script": "check:types:fixture:application-input", "expect": "fail" } ], "logPath": "artifacts/quality/check-types.txt", "evidence": ["artifacts/quality/check-types.txt"], diff --git a/docs/architecture/frontend-ports-adapters-and-boundaries.md b/docs/architecture/frontend-ports-adapters-and-boundaries.md index 11c0c8d0..068bb7b9 100644 --- a/docs/architecture/frontend-ports-adapters-and-boundaries.md +++ b/docs/architecture/frontend-ports-adapters-and-boundaries.md @@ -130,21 +130,27 @@ bootstrap은 page별 orchestration이나 업무 규칙을 소유하지 않는다 - render boundary와 async state surface - route registry와 lazy page -그러나 현재 실행 경로에는 다음 불일치가 있다. +RP-02 구현으로 다음 경계는 실행 경로에 연결됐다. -1. `src/bootstrap/composition-root.js`가 `application`을 만들지만 - `src/bootstrap/main.jsx`는 이를 사용하지 않고 `authSession`, - `storage`, `telemetry`를 presentation에 직접 전달한다. -2. `createApplication`이 input use case 대신 cache, storage, telemetry - output port를 그대로 노출한다. -3. `QueryClientProvider`는 존재하지만 실제 product route에서 +- `src/bootstrap/composition-root.js`가 만든 application을 production + `ApplicationProvider`가 실제 React tree에 주입한다. +- `createApplication`은 session, preference, diagnostics, runtime query의 + input API만 반환하며 storage, telemetry, release output port를 숨긴다. +- bootstrap composition 결과는 raw output port를 반환하지 않고 + application과 React infrastructure만 반환한다. +- presentation의 direct fetch/browser storage/concrete adapter/TanStack import와 + application의 React/concrete adapter import는 negative fixture가 거절한다. + +후속 브랜치에서 닫아야 할 실행 불일치는 다음과 같다. + +1. `QueryClientProvider`는 존재하지만 실제 product route에서 `useQuery` 또는 `useMutation`을 연결하는 query bridge가 없다. -4. route registry의 `paramsSchema`, `searchSchema`, `loadingSurface`, +2. route registry의 `paramsSchema`, `searchSchema`, `loadingSurface`, `errorSurface`, `chunkId` 일부는 실행 route와 연결되지 않았다. -5. 제거 테스트는 `src/sample/contract-fixture`만 제거하며, sample API +3. 제거 테스트는 `src/sample/contract-fixture`만 제거하며, sample API operation, Zod schema, mapper, domain model과 query key는 다른 경로에 남는다. -6. runtime의 `REQUEST_TIMEOUT_MS`, `MAX_RETRY_ATTEMPTS`는 검증되지만 +4. runtime의 `REQUEST_TIMEOUT_MS`, `MAX_RETRY_ATTEMPTS`는 검증되지만 concrete HTTP client 구성에 전달되지 않는다. 이 문서의 목표 구조는 기존 기반을 폐기하는 것이 아니라 이러한 diff --git a/eslint.config.js b/eslint.config.js index f3e3d75c..06a35f4c 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -23,7 +23,12 @@ const layerPatterns = { "react-dom", "@tanstack/**", ], - presentation: ["**/adapters/**", "**/bootstrap/**", "@tanstack/**"], + presentation: [ + "**/adapters/**", + "**/bootstrap/**", + "**/application/ports/out/**", + "@tanstack/**", + ], adapters: ["**/presentation/**", "**/bootstrap/**"], }; @@ -163,6 +168,12 @@ export default [ files: [`src/presentation/**/*.${sourceExtensions}`], rules: { "no-restricted-imports": restrictedImports(layerPatterns.presentation), + "no-restricted-globals": [ + "error", + "fetch", + "localStorage", + "sessionStorage", + ], }, }, { @@ -187,10 +198,17 @@ export default [ rules: { "no-restricted-imports": restrictedImports([ "**/adapters/**", + "**/application/ports/out/**", "@tanstack/**", "react", "react-dom", ]), + "no-restricted-globals": [ + "error", + "fetch", + "localStorage", + "sessionStorage", + ], }, }, ]; diff --git a/package.json b/package.json index 73d63482..00d5bbf4 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,8 @@ "check:types:fixture": "tsc --ignoreConfig --allowJs --checkJs --noEmit --target ES2022 --module NodeNext --moduleResolution NodeNext tests/fixtures/typecheck/invalid-port-call.js", "check:types:fixture:ts-port": "tsc --ignoreConfig --strict --noEmit --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-port-implementation.ts", "check:types:fixture:ts-result": "tsc --ignoreConfig --strict --noEmit --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-result-narrowing.ts", + "check:types:fixture:application-output": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-application-output.ts", + "check:types:fixture:application-input": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-application-input.ts", "test:runtime-schema": "vitest run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests", "test:unit": "vitest run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml", "test:component": "vitest run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml", diff --git a/scripts/check-architecture.mjs b/scripts/check-architecture.mjs index fda21c6f..fba59733 100644 --- a/scripts/check-architecture.mjs +++ b/scripts/check-architecture.mjs @@ -1,4 +1,4 @@ -import { mkdir, writeFile } from "node:fs/promises"; +import { mkdir, readdir, writeFile } from "node:fs/promises"; import { spawnSync } from "node:child_process"; await mkdir("artifacts/quality", { recursive: true }); @@ -60,10 +60,51 @@ const forbidden = runPnpm( ], ); -if (allowed.status !== 0 || forbidden.status === 0) { +/** @param {string} directory @returns {Promise} */ +async function fixtureFiles(directory) { + const entries = await readdir(directory, { withFileTypes: true }); + const files = await Promise.all( + entries.map((entry) => { + const target = `${directory}/${entry.name}`; + return entry.isDirectory() + ? fixtureFiles(target) + : /\.(?:js|jsx|mjs|ts|tsx|mts)$/.test(entry.name) + ? [target] + : []; + }), + ); + return files.flat(); +} + +const forbiddenResults = await Promise.all( + (await fixtureFiles("tests/fixtures/architecture/forbidden")).map((file) => ({ + file, + result: runPnpm([ + "exec", + "eslint", + file, + "--no-ignore", + "--max-warnings=0", + ]), + })), +); +const acceptedForbidden = forbiddenResults.filter( + ({ result }) => result.status === 0, +); + +if ( + allowed.status !== 0 || + forbidden.status === 0 || + acceptedForbidden.length > 0 +) { process.stderr.write(allowed.stderr || allowed.stdout); process.stderr.write(forbidden.stderr || forbidden.stdout); + for (const { file } of acceptedForbidden) { + process.stderr.write(`Forbidden fixture was accepted: ${file}\n`); + } process.exit(1); } -process.stdout.write("Architecture fixtures: allowed PASS, forbidden rejected\n"); +process.stdout.write( + `Architecture fixtures: allowed PASS, ${forbiddenResults.length} forbidden rejected\n`, +); diff --git a/src/adapters/http/client.js b/src/adapters/http/client.js index 5ff03bb3..094b2cae 100644 --- a/src/adapters/http/client.js +++ b/src/adapters/http/client.js @@ -1,4 +1,4 @@ -import { systemClock } from "../../application/ports/clock-port.js"; +import { systemClock } from "../platform/system-clock.js"; import { getApiOperation } from "../../contracts/api-operations.js"; import { createFailure as failure, diff --git a/src/adapters/platform/system-clock.js b/src/adapters/platform/system-clock.js new file mode 100644 index 00000000..62f45cd0 --- /dev/null +++ b/src/adapters/platform/system-clock.js @@ -0,0 +1,19 @@ +/** @type {import("../../application/ports/clock-port.js").ClockPort} */ +export const systemClock = Object.freeze({ + now: () => Date.now(), + sleep(milliseconds, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason); + return; + } + + const timer = setTimeout(resolve, milliseconds); + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); + }, +}); diff --git a/src/application/create-application.js b/src/application/create-application.js deleted file mode 100644 index 8d2b6330..00000000 --- a/src/application/create-application.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Application facade factory. Concrete dependencies are supplied by bootstrap. - * - * @param {{ - * resources?: { - * query: import("./ports/resource-ports.js").ResourceQueryPort, - * command: import("./ports/resource-ports.js").ResourceCommandPort - * }, - * cache: import("./ports/query-cache-port.js").QueryCachePort, - * storage: import("./ports/storage-port.js").StoragePort, - * telemetry: import("./ports/telemetry-port.js").TelemetryPort - * }} ports - */ -export function createApplication(ports) { - /** - * @param {unknown} query - * @param {import("./ports/resource-ports.js").RequestContext} [context] - */ - function queryResources(query, context) { - return /** @type {NonNullable} */ ( - ports.resources - ).query.execute(query, context); - } - - /** - * @param {unknown} command - * @param {import("./ports/resource-ports.js").RequestContext} [context] - */ - function commandResources(command, context) { - return /** @type {NonNullable} */ ( - ports.resources - ).command.execute(command, context); - } - - return Object.freeze({ - resources: ports.resources - ? Object.freeze({ - query: queryResources, - command: commandResources, - }) - : null, - cache: ports.cache, - storage: ports.storage, - telemetry: ports.telemetry, - }); -} diff --git a/src/application/create-application.ts b/src/application/create-application.ts new file mode 100644 index 00000000..d3910bdb --- /dev/null +++ b/src/application/create-application.ts @@ -0,0 +1,73 @@ +import { normalizeColorSchemePreference } from "./policies/color-scheme.js"; +import type { + ApplicationApi, + ColorSchemePreference, + RenderFailureReport, +} from "./ports/in/application-api.js"; +import type { ApplicationOutputPorts } from "./ports/out/application-output-ports.js"; + +export type { ApplicationApi, ApplicationOutputPorts }; + +/** + * Builds the driving API consumed by inbound adapters. Concrete output ports + * remain inside these closures and are never returned to React. + */ +export function createApplication( + outputPorts: ApplicationOutputPorts, +): ApplicationApi { + const session = Object.freeze({ + getSnapshot: () => outputPorts.session.getState(), + subscribe: (listener: () => void) => + outputPorts.session.subscribe(listener), + beginSignIn: (returnTo?: string) => + outputPorts.session.beginSignIn(returnTo), + signOut: () => outputPorts.session.signOut(), + recover: () => outputPorts.session.recover(), + }); + + const preferences = Object.freeze({ + getColorScheme(): ColorSchemePreference { + const result = outputPorts.preferences.read("COLOR_SCHEME"); + return normalizeColorSchemePreference( + result.ok ? result.value : undefined, + ); + }, + setColorScheme(preference: ColorSchemePreference) { + const normalized = normalizeColorSchemePreference(preference); + return outputPorts.preferences.write("COLOR_SCHEME", normalized); + }, + }); + + const diagnostics = Object.freeze({ + reportRenderFailure(report: RenderFailureReport) { + try { + outputPorts.diagnostics.emit("ui.render.failed", { + route_id: report.routeId, + build_id: report.buildId, + component_boundary: report.boundaryName, + }); + } catch { + // Diagnostics are best-effort and cannot become an application failure. + } + }, + }); + + const runtime = Object.freeze({ + async getReleaseSummary() { + const release = await outputPorts.releaseInfo.getCurrent(); + return Object.freeze({ + buildId: release.buildId, + releaseId: release.releaseId, + configSchemaVersion: release.configSchemaVersion, + apiContractVersion: release.apiContractVersion, + }); + }, + }); + + return Object.freeze({ + session, + preferences, + diagnostics, + runtime, + }); +} diff --git a/src/application/ports/auth-session-port.js b/src/application/ports/auth-session-port.js index 645f3490..14931cff 100644 --- a/src/application/ports/auth-session-port.js +++ b/src/application/ports/auth-session-port.js @@ -10,10 +10,24 @@ * subscribe(listener: () => void): () => void, * beginSignIn(returnTo?: string): Promise, * signOut(): Promise, + * recover(): Promise<"restored" | "no-session"> + * }} SessionGateway + */ + +/** + * Credential attachment is an HTTP-adapter collaboration, not an application + * input capability. + * + * @typedef {{ * attach(request: Request): Promise, - * recover(): Promise<"restored" | "no-session">, * onUnauthenticated(): void - * }} AuthSessionPort + * }} CredentialAttacher + */ + +/** + * External auth adapters implement both segregated capabilities. + * + * @typedef {SessionGateway & CredentialAttacher} AuthSessionPort */ export {}; diff --git a/src/application/ports/clock-port.js b/src/application/ports/clock-port.js index 353d5a33..12b6b1b1 100644 --- a/src/application/ports/clock-port.js +++ b/src/application/ports/clock-port.js @@ -5,25 +5,4 @@ * }} ClockPort */ -/** @type {ClockPort} */ -export const systemClock = Object.freeze({ - now: () => Date.now(), - sleep(milliseconds, signal) { - return new Promise((resolve, reject) => { - if (signal?.aborted) { - reject(signal.reason); - return; - } - - const timer = setTimeout(resolve, milliseconds); - signal?.addEventListener( - "abort", - () => { - clearTimeout(timer); - reject(signal.reason); - }, - { once: true }, - ); - }); - }, -}); +export {}; diff --git a/src/application/ports/in/application-api.ts b/src/application/ports/in/application-api.ts new file mode 100644 index 00000000..0d7e1082 --- /dev/null +++ b/src/application/ports/in/application-api.ts @@ -0,0 +1,41 @@ +import type { SessionState } from "../auth-session-port.js"; +import type { StoragePort } from "../storage-port.js"; + +export type { SessionState } from "../auth-session-port.js"; + +export type ColorSchemePreference = "system" | "light" | "dark"; + +export type RenderFailureReport = Readonly<{ + routeId: string; + buildId: string; + boundaryName: "route" | "feature"; +}>; + +export type ReleaseSummary = Readonly<{ + buildId: string; + releaseId: string; + configSchemaVersion: string; + apiContractVersion: string; +}>; + +export type ApplicationApi = Readonly<{ + session: Readonly<{ + getSnapshot(): SessionState; + subscribe(listener: () => void): () => void; + beginSignIn(returnTo?: string): Promise; + signOut(): Promise; + recover(): Promise<"restored" | "no-session">; + }>; + preferences: Readonly<{ + getColorScheme(): ColorSchemePreference; + setColorScheme( + preference: ColorSchemePreference, + ): ReturnType; + }>; + diagnostics: Readonly<{ + reportRenderFailure(report: RenderFailureReport): void; + }>; + runtime: Readonly<{ + getReleaseSummary(): Promise; + }>; +}>; diff --git a/src/application/ports/in/index.ts b/src/application/ports/in/index.ts new file mode 100644 index 00000000..5c5028c3 --- /dev/null +++ b/src/application/ports/in/index.ts @@ -0,0 +1,7 @@ +export type { + ApplicationApi, + ColorSchemePreference, + ReleaseSummary, + RenderFailureReport, + SessionState, +} from "./application-api.js"; diff --git a/src/application/ports/out/application-output-ports.ts b/src/application/ports/out/application-output-ports.ts new file mode 100644 index 00000000..85b44bfc --- /dev/null +++ b/src/application/ports/out/application-output-ports.ts @@ -0,0 +1,18 @@ +import type { AuthSessionPort } from "../auth-session-port.js"; +import type { ReleaseInfoPort } from "../release-info-port.js"; +import type { StoragePort } from "../storage-port.js"; +import type { TelemetryPort } from "../telemetry-port.js"; + +/** + * Capabilities required by application use cases. Implementations live in + * outbound adapters and are selected only by bootstrap. + */ +export type ApplicationOutputPorts = Readonly<{ + session: Pick< + AuthSessionPort, + "getState" | "subscribe" | "beginSignIn" | "signOut" | "recover" + >; + preferences: StoragePort; + diagnostics: TelemetryPort; + releaseInfo: ReleaseInfoPort; +}>; diff --git a/src/application/ports/out/index.ts b/src/application/ports/out/index.ts new file mode 100644 index 00000000..9b364cdc --- /dev/null +++ b/src/application/ports/out/index.ts @@ -0,0 +1,17 @@ +export type { ApplicationOutputPorts } from "./application-output-ports.js"; +export type { + AuthSessionPort, + CredentialAttacher, + SessionGateway, +} from "../auth-session-port.js"; +export type { ClockPort } from "../clock-port.js"; +export type { QueryCachePort } from "../query-cache-port.js"; +export type { ReleaseInfoPort } from "../release-info-port.js"; +export type { + RequestContext, + ResourceCommandPort, + ResourceQueryPort, + Result, +} from "../resource-ports.js"; +export type { StoragePort } from "../storage-port.js"; +export type { TelemetryPort } from "../telemetry-port.js"; diff --git a/src/application/ports/release-info-port.js b/src/application/ports/release-info-port.js index b34b41a5..cb291bd1 100644 --- a/src/application/ports/release-info-port.js +++ b/src/application/ports/release-info-port.js @@ -1,11 +1,15 @@ /** * @typedef {{ * getCurrent(): Promise<{ + * schemaVersion?: number, + * appVersion?: string, * buildId: string, + * commitSha?: string, * configSchemaVersion: string, * apiContractVersion: string, * assetManifestHash: string, - * releaseId: string + * releaseId: string, + * builtAt?: string * }> * }} ReleaseInfoPort */ diff --git a/src/bootstrap/composition-root.js b/src/bootstrap/composition-root.js index 45e130aa..c6c58a24 100644 --- a/src/bootstrap/composition-root.js +++ b/src/bootstrap/composition-root.js @@ -6,27 +6,36 @@ import { createApplication } from "../application/create-application.js"; * * @template Config * @template Release - * @template {Parameters[0]} Ports + * @template {Parameters[0]} OutputPorts + * @template Infrastructure * @param {{ * loadConfig(): Promise, * loadRelease(config: Config): Promise, * createAdapters(context: { * config: Config, * release: Release - * }): Promise + * }): Promise<{ + * outputPorts: OutputPorts, + * infrastructure: Infrastructure + * }> * }} factories * @returns {Promise * }>>} */ export async function createCompositionRoot(factories) { const config = await factories.loadConfig(); const release = await factories.loadRelease(config); - const ports = await factories.createAdapters({ config, release }); - const application = createApplication(ports); + const adapters = await factories.createAdapters({ config, release }); + const application = createApplication(adapters.outputPorts); - return Object.freeze({ config, release, ports, application }); + return Object.freeze({ + config, + release, + infrastructure: adapters.infrastructure, + application, + }); } diff --git a/src/bootstrap/initialize-color-scheme.js b/src/bootstrap/initialize-color-scheme.js index 3492cd62..fd291808 100644 --- a/src/bootstrap/initialize-color-scheme.js +++ b/src/bootstrap/initialize-color-scheme.js @@ -6,22 +6,21 @@ import { /** * Applies the persisted public preference before React paints. * - * @param {import("../application/ports/storage-port.js").StoragePort} storage + * @param {Pick} preferences * @param {{ * documentElement?: HTMLElement, * matchMedia?: (query: string) => MediaQueryList * }} [browser] */ -export function initializeColorScheme(storage, browser = {}) { +export function initializeColorScheme(preferences, browser = {}) { const documentElement = browser.documentElement ?? document.documentElement; const matchMedia = browser.matchMedia ?? (typeof window.matchMedia === "function" ? window.matchMedia.bind(window) : () => /** @type {MediaQueryList} */ ({ matches: false })); - const stored = storage.read("COLOR_SCHEME"); const preference = normalizeColorSchemePreference( - stored.ok ? stored.value : undefined, + preferences.getColorScheme(), ); const resolved = resolveColorScheme( preference, diff --git a/src/bootstrap/main.jsx b/src/bootstrap/main.jsx index c6ee9bb5..c7d646a0 100644 --- a/src/bootstrap/main.jsx +++ b/src/bootstrap/main.jsx @@ -1,13 +1,11 @@ -import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; -import { QueryClientProvider } from "@tanstack/react-query"; import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.jsx"; -import { AppRouter } from "../presentation/routes/app-router.jsx"; import { createRuntimeComposition } from "./create-runtime-composition.js"; import { initializeColorScheme } from "./initialize-color-scheme.js"; import { BootConfigError } from "./load-runtime-config.js"; import { ReleaseManifestError } from "./load-release-manifest.js"; +import { RuntimeApplication } from "./runtime-application.jsx"; import "../presentation/styles/theme.css"; const rootElement = document.getElementById("root"); @@ -21,20 +19,8 @@ const root = createRoot(rootElement); async function boot() { try { const composition = await createRuntimeComposition(); - initializeColorScheme(composition.ports.storage); - root.render( - - - - - , - ); + initializeColorScheme(composition.application.preferences); + root.render(); } catch (error) { const safe = error instanceof BootConfigError || error instanceof ReleaseManifestError diff --git a/src/bootstrap/runtime-adapters.js b/src/bootstrap/runtime-adapters.js index d5b61623..b4b0cc7a 100644 --- a/src/bootstrap/runtime-adapters.js +++ b/src/bootstrap/runtime-adapters.js @@ -3,9 +3,7 @@ import { createExternalAuthSessionAdapter, createUnavailableSessionAdapter, } from "../adapters/auth/external-session-adapter.js"; -import { createHttpClient } from "../adapters/http/client.js"; import { - createQueryCacheAdapter, createQueryClient, } from "../adapters/query-cache/tanstack-query-cache.js"; import { createBrowserStorageAdapter } from "../adapters/storage/browser-storage-adapter.js"; @@ -61,7 +59,6 @@ export async function createRuntimeAdapters(context) { ? createExternalAuthSessionAdapter(externalOwner) : createUnavailableSessionAdapter(); const queryClient = createQueryClient(); - const cache = createQueryCacheAdapter(queryClient); const storage = createBrowserStorageAdapter({ localStorage: storageOrUndefined(host.localStorage), sessionStorage: storageOrUndefined(host.sessionStorage), @@ -71,11 +68,6 @@ export async function createRuntimeAdapters(context) { endpoint: config.TELEMETRY_ENDPOINT, fetcher: context.fetcher, }); - const http = createHttpClient({ - baseUrl: config.API_BASE_URL, - authSession, - fetcher: context.fetcher, - }); const releaseInfo = Object.freeze({ async getCurrent() { return structuredClone(context.release); @@ -83,12 +75,14 @@ export async function createRuntimeAdapters(context) { }); return Object.freeze({ - authSession, - cache, - http, - queryClient, - releaseInfo, - storage, - telemetry, + outputPorts: Object.freeze({ + session: authSession, + preferences: storage, + diagnostics: telemetry, + releaseInfo, + }), + infrastructure: Object.freeze({ + queryClient, + }), }); } diff --git a/src/bootstrap/runtime-application.jsx b/src/bootstrap/runtime-application.jsx new file mode 100644 index 00000000..20560b8c --- /dev/null +++ b/src/bootstrap/runtime-application.jsx @@ -0,0 +1,28 @@ +import { StrictMode } from "react"; +import { QueryClientProvider } from "@tanstack/react-query"; + +import { ApplicationProvider } from "../presentation/providers/application-provider.js"; +import { AppRouter } from "../presentation/routes/app-router.jsx"; + +/** + * Production provider tree. Tests import this component so the validated + * composition is proven against the same provider order used by main. + * + * @param {{ + * composition: Awaited> + * }} props + */ +export function RuntimeApplication({ composition }) { + return ( + + + + + + + + ); +} diff --git a/src/presentation/boundaries/render-error-boundary.jsx b/src/presentation/boundaries/render-error-boundary.jsx index de3872d5..c10ecb81 100644 --- a/src/presentation/boundaries/render-error-boundary.jsx +++ b/src/presentation/boundaries/render-error-boundary.jsx @@ -6,7 +6,7 @@ import { Component } from "react"; * boundaryName: string, * routeId: string, * buildId: string, - * telemetry?: import("../../application/ports/telemetry-port.js").TelemetryPort, + * onRenderFailure?: (report: import("../../application/ports/in/application-api.js").RenderFailureReport) => void, * fallback?: React.ReactNode * }} RenderBoundaryProps * @typedef {{ hasError: boolean }} RenderBoundaryState @@ -26,13 +26,14 @@ export class RenderErrorBoundary extends Component { componentDidCatch() { try { - this.props.telemetry?.emit("ui.render.failed", { - route_id: this.props.routeId, - build_id: this.props.buildId, - component_boundary: this.props.boundaryName, + this.props.onRenderFailure?.({ + routeId: this.props.routeId, + buildId: this.props.buildId, + boundaryName: + /** @type {"route" | "feature"} */ (this.props.boundaryName), }); } catch { - // Telemetry must never recurse into another render failure. + // Diagnostics must never recurse into another render failure. } } diff --git a/src/presentation/pages/home-page.jsx b/src/presentation/pages/home-page.jsx index f7c00a85..d13fefb2 100644 --- a/src/presentation/pages/home-page.jsx +++ b/src/presentation/pages/home-page.jsx @@ -1,7 +1,9 @@ +import { useEffect, useState } from "react"; import { Link } from "react-router-dom"; import { routePath } from "../../contracts/routes.js"; import { PageHeader } from "../components/page-header.jsx"; +import { useApplication } from "../providers/application-provider.js"; const READINESS_ITEMS = Object.freeze([ { @@ -19,6 +21,23 @@ const READINESS_ITEMS = Object.freeze([ ]); export default function HomePage() { + const { runtime } = useApplication(); + const [release, setRelease] = useState( + /** @type {Awaited> | null} */ ( + null + ), + ); + + useEffect(() => { + let active = true; + void runtime.getReleaseSummary().then((summary) => { + if (active) setRelease(summary); + }); + return () => { + active = false; + }; + }, [runtime]); + return (
))}
+

+ {release + ? `빌드 ${release.buildId} · 릴리스 ${release.releaseId}` + : "검증된 런타임 정보를 확인하고 있습니다."} +

준비된 화면 살펴보기

diff --git a/src/presentation/providers/application-provider.tsx b/src/presentation/providers/application-provider.tsx new file mode 100644 index 00000000..6aee2e62 --- /dev/null +++ b/src/presentation/providers/application-provider.tsx @@ -0,0 +1,31 @@ +import { + createContext, + type ReactNode, + useContext, +} from "react"; + +import type { ApplicationApi } from "../../application/create-application.js"; + +const ApplicationContext = createContext(null); + +export function ApplicationProvider({ + application, + children, +}: Readonly<{ + application: ApplicationApi; + children: ReactNode; +}>) { + return ( + + {children} + + ); +} + +export function useApplication(): ApplicationApi { + const application = useContext(ApplicationContext); + if (!application) { + throw new Error("ApplicationProvider is required"); + } + return application; +} diff --git a/src/presentation/providers/session-provider.jsx b/src/presentation/providers/session-provider.jsx index 770cacad..6e4c8670 100644 --- a/src/presentation/providers/session-provider.jsx +++ b/src/presentation/providers/session-provider.jsx @@ -1,11 +1,12 @@ import { createContext, useContext, useMemo, useSyncExternalStore } from "react"; +import { useApplication } from "./application-provider.js"; /** * @typedef {{ - * sessionState: import("../../application/ports/auth-session-port.js").SessionState, - * beginSignIn: import("../../application/ports/auth-session-port.js").AuthSessionPort["beginSignIn"], - * signOut: import("../../application/ports/auth-session-port.js").AuthSessionPort["signOut"], - * recover: import("../../application/ports/auth-session-port.js").AuthSessionPort["recover"] + * sessionState: import("../../application/ports/in/application-api.js").SessionState, + * beginSignIn: import("../../application/ports/in/application-api.js").ApplicationApi["session"]["beginSignIn"], + * signOut: import("../../application/ports/in/application-api.js").ApplicationApi["session"]["signOut"], + * recover: import("../../application/ports/in/application-api.js").ApplicationApi["session"]["recover"] * }} SessionContextValue */ @@ -14,26 +15,24 @@ const SessionContext = createContext( ); /** - * @param {{ - * authSession: import("../../application/ports/auth-session-port.js").AuthSessionPort, - * children: React.ReactNode - * }} props + * @param {{ children: React.ReactNode }} props */ -export function SessionProvider({ authSession, children }) { +export function SessionProvider({ children }) { + const { session } = useApplication(); const sessionState = useSyncExternalStore( - authSession.subscribe, - authSession.getState, - authSession.getState, + session.subscribe, + session.getSnapshot, + session.getSnapshot, ); const value = useMemo( () => Object.freeze({ sessionState, - beginSignIn: authSession.beginSignIn, - signOut: authSession.signOut, - recover: authSession.recover, + beginSignIn: session.beginSignIn, + signOut: session.signOut, + recover: session.recover, }), - [authSession, sessionState], + [session, sessionState], ); return ( diff --git a/src/presentation/providers/theme-provider.jsx b/src/presentation/providers/theme-provider.jsx index eb181f74..860ec877 100644 --- a/src/presentation/providers/theme-provider.jsx +++ b/src/presentation/providers/theme-provider.jsx @@ -11,6 +11,7 @@ import { normalizeColorSchemePreference, resolveColorScheme, } from "../../application/policies/color-scheme.js"; +import { useApplication } from "./application-provider.js"; /** * @typedef {{ @@ -30,18 +31,13 @@ function systemPrefersDark() { } /** - * @param {{ - * storage?: import("../../application/ports/storage-port.js").StoragePort, - * children: React.ReactNode - * }} props + * @param {{ children: React.ReactNode }} props */ -export function ThemeProvider({ storage, children }) { - const [preference, updatePreference] = useState(() => { - const result = storage?.read("COLOR_SCHEME"); - return normalizeColorSchemePreference( - result?.ok ? result.value : undefined, - ); - }); +export function ThemeProvider({ children }) { + const { preferences } = useApplication(); + const [preference, updatePreference] = useState( + preferences.getColorScheme, + ); const [darkSystemTheme, setDarkSystemTheme] = useState(systemPrefersDark); const resolvedTheme = resolveColorScheme(preference, darkSystemTheme); @@ -70,10 +66,10 @@ export function ThemeProvider({ storage, children }) { setPreference(next) { const normalized = normalizeColorSchemePreference(next); updatePreference(normalized); - storage?.write("COLOR_SCHEME", normalized); + preferences.setColorScheme(normalized); }, }), - [preference, resolvedTheme, storage], + [preference, preferences, resolvedTheme], ); return {children}; diff --git a/src/presentation/routes/app-router.jsx b/src/presentation/routes/app-router.jsx index d7727a9c..8aee8fa0 100644 --- a/src/presentation/routes/app-router.jsx +++ b/src/presentation/routes/app-router.jsx @@ -10,6 +10,7 @@ import { getRoute, routePath } from "../../contracts/routes.js"; import { RouteBoundary } from "../boundaries/render-error-boundary.jsx"; import { AppShell } from "../layouts/app-shell.jsx"; import { PageHeader } from "../components/page-header.jsx"; +import { useApplication } from "../providers/application-provider.js"; import { SessionProvider, useSession } from "../providers/session-provider.jsx"; import { ThemeProvider } from "../providers/theme-provider.jsx"; import { decideRouteAccess } from "./navigation-policy.js"; @@ -54,16 +55,16 @@ function RouteFailureSurface() { * @param {{ * routeId: string, * buildId: string, - * telemetry?: import("../../application/ports/telemetry-port.js").TelemetryPort, * children: React.ReactNode * }} props */ -function RouteSurface({ routeId, buildId, telemetry, children }) { +function RouteSurface({ routeId, buildId, children }) { + const { diagnostics } = useApplication(); return ( } > }> @@ -155,13 +156,12 @@ function ProtectedRoute({ routeId, children }) { * @param {{ * routeId: string, * buildId: string, - * telemetry?: import("../../application/ports/telemetry-port.js").TelemetryPort, * children: React.ReactNode * }} props */ -function PublicRoute({ routeId, buildId, telemetry, children }) { +function PublicRoute({ routeId, buildId, children }) { return ( - + {children} ); @@ -169,24 +169,18 @@ function PublicRoute({ routeId, buildId, telemetry, children }) { /** * @param {{ - * authSession: import("../../application/ports/auth-session-port.js").AuthSessionPort, * basename?: string, - * buildId?: string, - * storage?: import("../../application/ports/storage-port.js").StoragePort, - * telemetry?: import("../../application/ports/telemetry-port.js").TelemetryPort + * buildId?: string * }} props */ export function AppRouter({ - authSession, basename = "/", buildId = "local-build", - storage, - telemetry, }) { return ( - - + + }> @@ -207,7 +200,6 @@ export function AppRouter({ @@ -219,7 +211,6 @@ export function AppRouter({ @@ -231,7 +222,6 @@ export function AppRouter({ @@ -243,7 +233,6 @@ export function AppRouter({ @@ -257,7 +246,6 @@ export function AppRouter({ diff --git a/src/presentation/routes/navigation-policy.js b/src/presentation/routes/navigation-policy.js index 9fa51333..0dd3468a 100644 --- a/src/presentation/routes/navigation-policy.js +++ b/src/presentation/routes/navigation-policy.js @@ -2,7 +2,7 @@ import { getRoute } from "../../contracts/routes.js"; /** * @param {string} routeId - * @param {import("../../application/ports/auth-session-port.js").SessionState} sessionState + * @param {import("../../application/ports/in/application-api.js").SessionState} sessionState */ export function decideRouteAccess(routeId, sessionState) { const route = getRoute(routeId); diff --git a/tests/component/render-boundary.test.jsx b/tests/component/render-boundary.test.jsx index a920c16c..f605677c 100644 --- a/tests/component/render-boundary.test.jsx +++ b/tests/component/render-boundary.test.jsx @@ -17,22 +17,22 @@ function Defect() { describe("render recovery boundaries", () => { it("catches programmer defects and emits best-effort safe telemetry", () => { - const telemetry = { emit: vi.fn() }; + const onRenderFailure = vi.fn(); render( , ); expect(screen.getByRole("alert")).toHaveTextContent("error.render_failure"); - expect(telemetry.emit).toHaveBeenCalledWith("ui.render.failed", { - route_id: "APP_HOME", - build_id: "build-a", - component_boundary: "feature", + expect(onRenderFailure).toHaveBeenCalledWith({ + routeId: "APP_HOME", + buildId: "build-a", + boundaryName: "feature", }); }); diff --git a/tests/component/router.test.jsx b/tests/component/router.test.jsx index d9fdfc09..69c06f05 100644 --- a/tests/component/router.test.jsx +++ b/tests/component/router.test.jsx @@ -8,12 +8,25 @@ import { createAnonymousSessionAdapter, createDemoSessionAdapter, } from "../../src/adapters/auth/external-session-adapter.js"; +import { ApplicationProvider } from "../../src/presentation/providers/application-provider.js"; import { AppRouter } from "../../src/presentation/routes/app-router.jsx"; +import { createTestApplication } from "../helpers/create-test-application.js"; + +/** + * @param {import("../../src/application/ports/auth-session-port.js").AuthSessionPort} session + */ +function renderRouter(session) { + return render( + + + , + ); +} describe("application router", () => { it("renders the app shell and not-found route without an API request", async () => { window.history.pushState({}, "", "/missing"); - render(); + renderRouter(createAnonymousSessionAdapter()); expect( await screen.findByRole("heading", { @@ -27,7 +40,7 @@ describe("application router", () => { it("navigates between registry-backed example routes", async () => { const user = userEvent.setup(); window.history.pushState({}, "", "/"); - render(); + renderRouter(createAnonymousSessionAdapter()); await user.click( await screen.findByRole("link", { name: "UI 구성요소" }), @@ -43,7 +56,7 @@ describe("application router", () => { const user = userEvent.setup(); const authSession = createDemoSessionAdapter(); window.history.pushState({}, "", "/sample/resources"); - render(); + renderRouter(authSession); expect( await screen.findByRole("heading", { name: "세션이 필요합니다." }), @@ -59,7 +72,7 @@ describe("application router", () => { it("fails closed when the auth integration does not change state", async () => { const user = userEvent.setup(); window.history.pushState({}, "", "/sample/resources"); - render(); + renderRouter(createAnonymousSessionAdapter()); await user.click( await screen.findByRole("button", { name: "로그인 시작" }), diff --git a/tests/component/runtime-application.test.jsx b/tests/component/runtime-application.test.jsx new file mode 100644 index 00000000..0a2c94e0 --- /dev/null +++ b/tests/component/runtime-application.test.jsx @@ -0,0 +1,67 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +import { createRuntimeComposition } from "../../src/bootstrap/create-runtime-composition.js"; +import { RuntimeApplication } from "../../src/bootstrap/runtime-application.jsx"; + +const runtimeConfig = { + APP_ENV: "local", + API_BASE_URL: "http://localhost:8080", + REQUEST_TIMEOUT_MS: 10_000, + MAX_RETRY_ATTEMPTS: 2, + TELEMETRY_ENABLED: false, + AUTH_MODE: "demo", + CONFIG_SCHEMA_VERSION: "1", + API_CONTRACT_VERSION: "1", + RELEASE_MANIFEST_URL: "/release-manifest.json", + BUILD_ID: "local-build", + RELEASE_ID: "local-release", +}; + +const releaseManifest = { + schemaVersion: 1, + appVersion: "0.1.0", + buildId: "local-build", + commitSha: "local", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "test-hash", + releaseId: "local-release", + builtAt: "2026-07-26T00:00:00.000Z", +}; + +describe("production runtime application tree", () => { + it("connects validated config and release through composition and ApplicationProvider", async () => { + const fetcher = vi.fn(async (input) => { + const url = + typeof input === "string" + ? input + : input instanceof URL + ? input.href + : input.url; + return Response.json( + url.includes("release-manifest") ? releaseManifest : runtimeConfig, + ); + }); + const composition = await createRuntimeComposition({ + fetcher, + host: {}, + }); + + window.history.pushState({}, "", "/"); + render(); + + expect( + await screen.findByRole("heading", { + name: "Clean Architecture Frontend", + }), + ).toBeVisible(); + expect( + await screen.findByText("빌드 local-build · 릴리스 local-release"), + ).toBeVisible(); + expect(fetcher).toHaveBeenCalledTimes(2); + expect(composition).not.toHaveProperty("ports"); + }); +}); diff --git a/tests/fixtures/architecture/allowed/bootstrap-composes-adapter.ts b/tests/fixtures/architecture/allowed/bootstrap-composes-adapter.ts new file mode 100644 index 00000000..d5038c07 --- /dev/null +++ b/tests/fixtures/architecture/allowed/bootstrap-composes-adapter.ts @@ -0,0 +1,3 @@ +import { createRuntimeAdapters } from "../../../../src/bootstrap/runtime-adapters.js"; + +export const bootstrapFactory = createRuntimeAdapters; diff --git a/tests/fixtures/architecture/forbidden/application-imports-adapter.ts b/tests/fixtures/architecture/forbidden/application-imports-adapter.ts new file mode 100644 index 00000000..676ff884 --- /dev/null +++ b/tests/fixtures/architecture/forbidden/application-imports-adapter.ts @@ -0,0 +1,3 @@ +import { createHttpClient } from "../../../../src/adapters/http/client.js"; + +export const leakedHttpFactory = createHttpClient; diff --git a/tests/fixtures/architecture/forbidden/presentation-direct-fetch.tsx b/tests/fixtures/architecture/forbidden/presentation-direct-fetch.tsx new file mode 100644 index 00000000..41d78555 --- /dev/null +++ b/tests/fixtures/architecture/forbidden/presentation-direct-fetch.tsx @@ -0,0 +1,4 @@ +export function DirectFetchPage() { + void fetch("/api/forbidden"); + return

forbidden

; +} diff --git a/tests/fixtures/architecture/forbidden/presentation-imports-output-port.tsx b/tests/fixtures/architecture/forbidden/presentation-imports-output-port.tsx new file mode 100644 index 00000000..94951d74 --- /dev/null +++ b/tests/fixtures/architecture/forbidden/presentation-imports-output-port.tsx @@ -0,0 +1,5 @@ +import type { ApplicationOutputPorts } from "../../../../src/application/ports/out/application-output-ports.js"; + +export function OutputPortLeak(_props: ApplicationOutputPorts) { + return

forbidden

; +} diff --git a/tests/fixtures/typecheck/invalid-application-input.ts b/tests/fixtures/typecheck/invalid-application-input.ts new file mode 100644 index 00000000..bb0b1d38 --- /dev/null +++ b/tests/fixtures/typecheck/invalid-application-input.ts @@ -0,0 +1,5 @@ +import type { ApplicationApi } from "../../../src/application/create-application.js"; + +export const incompleteApplication: ApplicationApi = { + session: {} as ApplicationApi["session"], +}; diff --git a/tests/fixtures/typecheck/invalid-application-output.ts b/tests/fixtures/typecheck/invalid-application-output.ts new file mode 100644 index 00000000..18e4d29d --- /dev/null +++ b/tests/fixtures/typecheck/invalid-application-output.ts @@ -0,0 +1,7 @@ +import type { ApplicationOutputPorts } from "../../../src/application/create-application.js"; + +export const invalidOutputPorts: ApplicationOutputPorts = { + session: { + getState: () => "signed-in", + }, +}; diff --git a/tests/helpers/create-test-application.js b/tests/helpers/create-test-application.js new file mode 100644 index 00000000..6a07a147 --- /dev/null +++ b/tests/helpers/create-test-application.js @@ -0,0 +1,35 @@ +import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.js"; +import { createApplication } from "../../src/application/create-application.js"; + +/** + * @param {{ + * session?: import("../../src/application/ports/auth-session-port.js").AuthSessionPort, + * preferences?: import("../../src/application/ports/storage-port.js").StoragePort, + * diagnostics?: import("../../src/application/ports/telemetry-port.js").TelemetryPort, + * releaseInfo?: import("../../src/application/ports/release-info-port.js").ReleaseInfoPort + * }} [overrides] + */ +export function createTestApplication(overrides = {}) { + return createApplication({ + session: overrides.session ?? createAnonymousSessionAdapter(), + preferences: + overrides.preferences ?? + { + read: () => ({ ok: /** @type {const} */ (true), value: "system" }), + write: () => ({ ok: /** @type {const} */ (true) }), + remove: () => ({ ok: /** @type {const} */ (true) }), + }, + diagnostics: overrides.diagnostics ?? { emit: () => {} }, + releaseInfo: + overrides.releaseInfo ?? + { + getCurrent: async () => ({ + buildId: "test-build", + releaseId: "test-release", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "test-hash", + }), + }, + }); +} diff --git a/tests/unit/application-boundary.test.ts b/tests/unit/application-boundary.test.ts new file mode 100644 index 00000000..bfaf94d6 --- /dev/null +++ b/tests/unit/application-boundary.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + createApplication, + type ApplicationOutputPorts, +} from "../../src/application/create-application.js"; +import { createTestApplication } from "../helpers/create-test-application.js"; + +describe("application input/output boundary", () => { + it("exposes intent-oriented input APIs without leaking output ports", async () => { + const application = createTestApplication(); + + expect(Object.keys(application)).toEqual([ + "session", + "preferences", + "diagnostics", + "runtime", + ]); + expect(application).not.toHaveProperty("storage"); + expect(application).not.toHaveProperty("telemetry"); + expect(application).not.toHaveProperty("releaseInfo"); + await expect(application.runtime.getReleaseSummary()).resolves.toEqual({ + buildId: "test-build", + releaseId: "test-release", + configSchemaVersion: "1", + apiContractVersion: "1", + }); + }); + + it("uses fake output ports for preference, session, and safe diagnostics flows", () => { + const write = vi.fn(() => ({ ok: true as const })); + const emit = vi.fn(); + const ports = { + session: { + getState: () => "authenticated" as const, + subscribe: () => () => {}, + beginSignIn: async () => {}, + signOut: async () => {}, + recover: async () => "restored" as const, + }, + preferences: { + read: () => ({ ok: true as const, value: "dark" }), + write, + remove: () => ({ ok: true as const }), + }, + diagnostics: { emit }, + releaseInfo: { + getCurrent: async () => ({ + buildId: "build-a", + releaseId: "release-a", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "hash-a", + }), + }, + } satisfies ApplicationOutputPorts; + const application = createApplication(ports); + + expect(application.session.getSnapshot()).toBe("authenticated"); + expect(application.preferences.getColorScheme()).toBe("dark"); + expect(application.preferences.setColorScheme("light")).toEqual({ ok: true }); + expect(write).toHaveBeenCalledWith("COLOR_SCHEME", "light"); + + application.diagnostics.reportRenderFailure({ + routeId: "APP_HOME", + buildId: "build-a", + boundaryName: "route", + }); + expect(emit).toHaveBeenCalledWith("ui.render.failed", { + route_id: "APP_HOME", + build_id: "build-a", + component_boundary: "route", + }); + }); + + it("does not let a failing diagnostics output escape into presentation", () => { + const application = createTestApplication({ + diagnostics: { + emit() { + throw new Error("sink details"); + }, + }, + }); + + expect(() => + application.diagnostics.reportRenderFailure({ + routeId: "APP_HOME", + buildId: "build-a", + boundaryName: "feature", + }), + ).not.toThrow(); + }); +}); diff --git a/tests/unit/color-scheme.test.js b/tests/unit/color-scheme.test.js index 8b70c72e..03e90217 100644 --- a/tests/unit/color-scheme.test.js +++ b/tests/unit/color-scheme.test.js @@ -21,17 +21,9 @@ describe("color scheme policy", () => { }); it("applies a persisted preference before application paint", () => { - const storage = - /** @type {import("../../src/application/ports/storage-port.js").StoragePort} */ ({ - read: () => ({ - ok: /** @type {const} */ (true), - value: "system", - }), - write: () => ({ ok: /** @type {const} */ (true) }), - remove: () => ({ ok: /** @type {const} */ (true) }), - }); - - const result = initializeColorScheme(storage, { + const result = initializeColorScheme({ + getColorScheme: () => "system", + }, { documentElement: document.documentElement, matchMedia: () => /** @type {MediaQueryList} */ ({ matches: true }), diff --git a/tests/unit/runtime-adapters.test.js b/tests/unit/runtime-adapters.test.js index fe7ffb4a..9d9f824f 100644 --- a/tests/unit/runtime-adapters.test.js +++ b/tests/unit/runtime-adapters.test.js @@ -33,14 +33,13 @@ describe("runtime adapter composition", () => { host: {}, }); - expect(adapters.authSession.getState()).toBe("unauthenticated"); - expect(adapters.cache.read(["missing"])).toEqual({ - ok: true, - value: undefined, - }); - await expect(adapters.releaseInfo.getCurrent()).resolves.toMatchObject({ + expect(adapters.outputPorts.session.getState()).toBe("unauthenticated"); + await expect(adapters.outputPorts.releaseInfo.getCurrent()).resolves.toMatchObject({ releaseId: "release-a", }); + expect(adapters.infrastructure.queryClient).toBeDefined(); + expect(adapters).not.toHaveProperty("http"); + expect(adapters).not.toHaveProperty("storage"); }); it("fails closed when an external auth owner was not installed", async () => { @@ -52,6 +51,6 @@ describe("runtime adapter composition", () => { release, host: {}, }); - expect(adapters.authSession.getState()).toBe("integration-failed"); + expect(adapters.outputPorts.session.getState()).toBe("integration-failed"); }); }); diff --git a/tests/unit/system-clock.test.js b/tests/unit/system-clock.test.js index e2761b9e..dd94c1b8 100644 --- a/tests/unit/system-clock.test.js +++ b/tests/unit/system-clock.test.js @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest"; -import { systemClock } from "../../src/application/ports/clock-port.js"; +import { systemClock } from "../../src/adapters/platform/system-clock.js"; describe("systemClock", () => { it("resolves after the requested duration", async () => { From ad55e21a3de6327fd90e42423e374309032ac4ee Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sun, 26 Jul 2026 14:05:12 +0900 Subject: [PATCH 049/178] feat: execute HTTP and query runtime contracts --- .dependency-cruiser.cjs | 2 +- config/ci/gates.json | 3 +- config/contracts/registry-governance.json | 4 +- .../frontend-platform-capability-review.md | 68 +++-- .../frontend-ports-adapters-and-boundaries.md | 21 +- .../typescript-state-and-data-flow.md | 14 + .../frontend-platform-testing-strategy.md | 12 +- eslint.config.js | 14 + package.json | 1 + src/adapters/http/client.js | 141 +++++++--- src/adapters/http/request-builder.ts | 73 ++++++ src/adapters/http/retry-policy.js | 3 +- src/adapters/http/schema-registry.js | 1 + src/adapters/platform/system-clock.js | 6 +- src/application/view-models/async-state.js | 81 ------ src/application/view-models/async-state.ts | 156 +++++++++++ src/bootstrap/runtime-adapters.js | 25 ++ src/contracts/api-operations.js | 12 +- .../adapters/query/application-query.ts | 194 ++++++++++++++ src/presentation/adapters/query/index.ts | 5 + src/presentation/components/async-surface.jsx | 32 ++- tests/component/application-query.test.jsx | 218 ++++++++++++++++ tests/component/async-surface.test.jsx | 44 +++- .../presentation-imports-tanstack.tsx | 3 + .../typecheck/invalid-async-overlay.ts | 8 + .../http-execution-contract.test.js | 244 ++++++++++++++++++ tests/unit/request-builder.test.ts | 54 ++++ tests/unit/runtime-adapters.test.js | 65 ++++- tests/unit/system-clock.test.js | 7 +- 29 files changed, 1326 insertions(+), 185 deletions(-) create mode 100644 src/adapters/http/request-builder.ts delete mode 100644 src/application/view-models/async-state.js create mode 100644 src/application/view-models/async-state.ts create mode 100644 src/presentation/adapters/query/application-query.ts create mode 100644 src/presentation/adapters/query/index.ts create mode 100644 tests/component/application-query.test.jsx create mode 100644 tests/fixtures/architecture/forbidden/presentation-imports-tanstack.tsx create mode 100644 tests/fixtures/typecheck/invalid-async-overlay.ts create mode 100644 tests/integration/http-execution-contract.test.js create mode 100644 tests/unit/request-builder.test.ts diff --git a/.dependency-cruiser.cjs b/.dependency-cruiser.cjs index 5197aa39..b1062d37 100644 --- a/.dependency-cruiser.cjs +++ b/.dependency-cruiser.cjs @@ -20,7 +20,7 @@ module.exports = { { name: "presentation-does-not-know-adapters", severity: "error", - from: { path: "^src/presentation" }, + from: { path: "^src/presentation/(?!adapters/query)" }, to: { path: "^(src/(adapters|bootstrap)|@tanstack)" }, }, { diff --git a/config/ci/gates.json b/config/ci/gates.json index 3b4ecb5e..99afbf23 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -78,7 +78,8 @@ { "script": "check:types:fixture:ts-port", "expect": "fail" }, { "script": "check:types:fixture:ts-result", "expect": "fail" }, { "script": "check:types:fixture:application-output", "expect": "fail" }, - { "script": "check:types:fixture:application-input", "expect": "fail" } + { "script": "check:types:fixture:application-input", "expect": "fail" }, + { "script": "check:types:fixture:async-overlay", "expect": "fail" } ], "logPath": "artifacts/quality/check-types.txt", "evidence": ["artifacts/quality/check-types.txt"], diff --git a/config/contracts/registry-governance.json b/config/contracts/registry-governance.json index d0f24bee..84d14800 100644 --- a/config/contracts/registry-governance.json +++ b/config/contracts/registry-governance.json @@ -29,6 +29,8 @@ "auth", "timeoutMs", "idempotency", + "retry", + "requestSource", "requestSchema", "responseSchema", "owner" @@ -111,6 +113,6 @@ ], "compatibilityImpact": { "allowed": ["none", "additive", "behavior-change", "breaking"], - "current": "additive" + "current": "behavior-change" } } diff --git a/docs/architecture/frontend-platform-capability-review.md b/docs/architecture/frontend-platform-capability-review.md index bbf50d25..88a40417 100644 --- a/docs/architecture/frontend-platform-capability-review.md +++ b/docs/architecture/frontend-platform-capability-review.md @@ -33,13 +33,13 @@ 특히 다음은 선행 해결이 필요하다. -1. React 화면이 호출할 application input API와 런타임 주입 경계 -2. TanStack Query를 사용하는 표준 query/mutation inbound adapter -3. TypeScript 전환 전에 TS 파일까지 검사하도록 만드는 도구 안전망 -4. path/query/body projection과 runtime timeout/retry가 정확히 연결된 HTTP 계층 -5. 선언과 실행이 일치하는 typed route 계약 -6. 전체를 제거할 수 있는 실제 reference feature -7. 폼, 페이지 템플릿, 확장된 디자인 시스템과 컴포넌트 워크벤치 +RP-01~RP-03에서 TypeScript 도구 안전망, application runtime 주입, +query/mutation inbound adapter와 HTTP 실행 계약은 구현됐다. 현재 선행 해결 +대상은 다음과 같다. + +1. 선언과 실행이 일치하는 typed route 계약 +2. 전체를 제거할 수 있는 실제 reference feature +3. 폼, 페이지 템플릿, 확장된 디자인 시스템과 컴포넌트 워크벤치 따라서 현재 상태를 “프론트 공통부가 모두 구현됐다”고 표현하면 범위가 과장된다. 더 정확한 표현은 다음과 같다. @@ -63,13 +63,13 @@ | --- | --- | --- | --- | | 부트·런타임 설정 | 준비됨 | `src/bootstrap`, runtime schema, release 검사 | 현 상태 유지, TS 전환 시 동일 게이트 유지 | | 계층 의존 방향 | 부분 준비 | `.dependency-cruiser.cjs`, `src/application/ports` | inbound/outbound 명명과 `contracts` 소유권까지 집행 | -| application facade | 부분 준비 | `create-application.js`는 있으나 `main.jsx`에서 우회 | UI에는 input API만 주입 | -| HTTP client | 부분 준비 | timeout, abort, retry, auth, envelope, Zod가 존재 | path/query, parsed body, runtime 설정, 정리 로직 보완 | -| retry | 부분 준비 | safe/keyed 요청 정책 존재 | retry 소유자 단일화, 설정 연결, telemetry | +| application facade | 준비됨 | typed input/output catalog, provider, production composition test | feature input use case를 contribution으로 확장 | +| HTTP client | 준비됨 | path/search/body projection, runtime timeout/retry, abort/cleanup test | feature gateway 뒤에서 사용 | +| retry | 준비됨 | HTTP 단일 소유, runtime max attempts, Query retry off | RP-09에서 telemetry 연결 | | 오류 모델 | 부분 준비 | error registry와 normalization 존재 | typed discriminated union과 계층별 mapper | -| 검증 | 부분 준비 | runtime/API Zod 존재 | route/form/domain 경계를 분리하고 실제 parse 결과 사용 | +| 검증 | 부분 준비 | runtime/API Zod parse 결과를 실제 request에 사용 | route/form/domain 경계를 추가 | | 인증 연동 | 준비됨/프로젝트 선택 | opaque auth owner와 demo seam 존재 | 인증 방식별 recipe; 기본 token 저장소는 추가하지 않음 | -| 서버 상태 | 미제공에 가까운 부분 준비 | QueryClientProvider와 cache port는 존재 | query/mutation hook과 화면 reference flow | +| 서버 상태 | 부분 준비 | 제한된 query/mutation bridge와 lifecycle test | RP-05 reference route에서 실제 feature 연결 | | 클라이언트 상태 | 부분 준비 | local state, theme context, session external store | 상태 소유권 표와 typed external-store 예제 | | 범용 global store | 프로젝트 선택 | 별도 라이브러리 없음 | 필요 조건에 따라 Zustand/Redux Toolkit/state machine 선택 | | 라우팅 | 부분 준비 | lazy route, access hint, registry 존재 | typed runtime map, codec, recovery, metadata 집행 | @@ -82,7 +82,7 @@ | 국제화 | 미제공 | 한국어 문자열·locale이 하드코딩 | typed message/formatter/locale/RTL 경계 | | logging/diagnostics | 미제공 | telemetry port는 있으나 logger 없음 | redaction이 적용된 diagnostics/logging 경계 | | telemetry | 부분 준비 | registry, queue, redaction 존재 | HTTP·boot·cache·storage·route 사건에 실제 연결 | -| 비동기 상태 불변식 | 부분 준비 | 공통 model/surface는 있으나 일부 모순 상태를 허용 | query/mutation 상태 조합과 action latch를 닫음 | +| 비동기 상태 불변식 | 준비됨 | 배타적 typed overlay, stale latch, 실제 retry/conflict action | reference 화면에서 전체 상태 전시 | | 단위·통합·E2E | 준비됨 | Vitest, RTL, MSW, Playwright 3엔진 | TS 테스트 검사, 실제 bootstrap 통합, 위험 시나리오 보강 | | UI 회귀 검증 | 미제공 | axe/reflow는 있으나 visual baseline 없음 | Storybook 또는 동급 workshop과 시각 회귀 | | 샘플 제거 | 부분 준비 | fixture 제거 테스트 존재 | sample domain/registry/runtime 전체 제거 검증 | @@ -94,13 +94,12 @@ ### 5.1 P0: 기능 개발을 막는 항목 -#### application 계층이 런타임에서 우회된다 +#### RP-02에서 application 런타임 우회 해결 -`src/bootstrap/composition-root.js`는 application을 생성하지만 -`src/bootstrap/main.jsx`는 이를 라우터에 주입하지 않는다. UI에는 auth, storage, -telemetry 같은 raw outbound dependency와 concrete QueryClient가 전달된다. -`src/application/create-application.js`도 use case 중심 input API보다 outbound -capability를 다시 노출하는 형태다. +`src/bootstrap/composition-root.js`가 만든 typed application input API는 +production `ApplicationProvider`에 주입된다. raw auth, storage, telemetry와 +release port는 closure 안에 남고 UI는 session, preference, diagnostics와 runtime +query만 사용한다. 목표 상태: @@ -110,12 +109,13 @@ capability를 다시 노출하는 형태다. - bootstrap만 concrete outbound adapter를 알고 조합한다. - 실제 bootstrap부터 reference page까지 연결한 통합 테스트가 있다. -#### 서버 상태 라이브러리는 마운트됐지만 사용할 수 없다 +#### RP-03에서 표준 서버 상태 bridge 구현 -`QueryClientProvider`는 존재하지만 저장소의 제품 코드에서 `useQuery`와 -`useMutation`을 사용하지 않는다. 동시에 presentation의 `@tanstack/**` import는 -금지돼 있다. 현재 `QueryCachePort`는 명령형 read/write/invalidate만 제공하여 -React 구독, 요청 상태, cancellation, optimistic update를 대신할 수 없다. +`src/presentation/adapters/query` 한 경계만 `@tanstack/**`를 import한다. +`useApplicationQuery`와 `useApplicationMutation`은 application result를 React +lifecycle에 연결하며 cancellation, stale failure, duplicate submit, optimistic +rollback, conflict resolution과 invalidation을 검증한다. 다른 presentation +경로의 직접 TanStack import는 negative fixture가 거절한다. 목표 상태: @@ -128,7 +128,7 @@ React 구독, 요청 상태, cancellation, optimistic update를 대신할 수 - loading, empty, refreshing, stale, offline, error, conflict, optimistic rollback을 reference feature에서 보여 준다. -#### TypeScript 전환 전에 검사 도구가 TS를 인식해야 한다 +#### RP-01에서 TypeScript 검사 도구 안전망 구현 현재 source는 모두 JS/JSX이고 `strict + allowJs + checkJs`를 사용한다. 이는 좋은 중간 안전망이지만 다음 도구는 TS migration을 그대로 따라가지 못한다. @@ -143,18 +143,14 @@ TypeScript 전환은 [TypeScript의 JavaScript migration 가이드](https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html) 처럼 점진적으로 진행하되, 이 저장소에서는 tooling glob과 CI를 먼저 고쳐야 한다. -#### HTTP 계약에 선언과 실행의 차이가 있다 +#### RP-03에서 HTTP 선언과 실행의 차이 해결 -현재 HTTP 계층은 공통화 수준이 높지만 다음 정확성 문제가 남아 있다. - -- runtime config의 `REQUEST_TIMEOUT_MS`, `MAX_RETRY_ATTEMPTS`가 client 생성에 - 전달되지 않는다. -- operation path에 path parameter와 search parameter를 투영하는 표준 builder가 - 없다. -- sample filter는 cache key에만 반영되고 실제 요청 URL에는 반영되지 않는다. -- Zod의 parsed/transformed request body 대신 원본 body를 전송한다. -- request validation의 조기 반환 경로에서 timeout/listener 정리가 늦어진다. -- HTTP failure, retry, recovery가 telemetry 사건과 이어지지 않는다. +HTTP request builder는 path segment escaping, canonical optional/array search, +Zod default/trim 결과의 실제 query/body 전송을 담당한다. runtime timeout과 +0/1/N max retry가 client factory에 주입되고 caller abort와 timeout을 다른 typed +failure로 투영한다. validation 조기 반환은 fetch/timer 0회이며 success, schema +failure, abort, timeout과 exhausted retry는 scheduler/listener cleanup을 +검증한다. HTTP 사건의 semantic telemetry 연결은 RP-09 범위다. client를 거대한 범용 함수로 계속 확장하지 말고 transport, request builder, auth, timeout, retry, decoder, mapper 책임을 분리해야 한다. application에는 범용 HTTP diff --git a/docs/architecture/frontend-ports-adapters-and-boundaries.md b/docs/architecture/frontend-ports-adapters-and-boundaries.md index 068bb7b9..9f4e58d7 100644 --- a/docs/architecture/frontend-ports-adapters-and-boundaries.md +++ b/docs/architecture/frontend-ports-adapters-and-boundaries.md @@ -141,17 +141,26 @@ RP-02 구현으로 다음 경계는 실행 경로에 연결됐다. - presentation의 direct fetch/browser storage/concrete adapter/TanStack import와 application의 React/concrete adapter import는 negative fixture가 거절한다. +RP-03 구현으로 HTTP와 server-state 경계도 다음처럼 연결됐다. + +- `src/presentation/adapters/query`만 TanStack Query import를 허용하며 + application query/mutation을 cancellation, invalidation, deduplication, + optimistic rollback과 conflict 해제에 연결한다. +- HTTP request builder는 path escaping과 canonical search를 소유하고 Zod가 + 변환한 search/body를 실제 request에 사용한다. +- runtime timeout과 max retry attempts가 transport factory에 주입되며 + validation, success, abort, timeout과 exhausted retry의 timer/listener + 정리를 테스트한다. +- HTTP가 자동 network retry를 소유하고 query/mutation adapter의 vendor retry는 + 비활성화한다. + 후속 브랜치에서 닫아야 할 실행 불일치는 다음과 같다. -1. `QueryClientProvider`는 존재하지만 실제 product route에서 - `useQuery` 또는 `useMutation`을 연결하는 query bridge가 없다. -2. route registry의 `paramsSchema`, `searchSchema`, `loadingSurface`, +1. route registry의 `paramsSchema`, `searchSchema`, `loadingSurface`, `errorSurface`, `chunkId` 일부는 실행 route와 연결되지 않았다. -3. 제거 테스트는 `src/sample/contract-fixture`만 제거하며, sample API +2. 제거 테스트는 `src/sample/contract-fixture`만 제거하며, sample API operation, Zod schema, mapper, domain model과 query key는 다른 경로에 남는다. -4. runtime의 `REQUEST_TIMEOUT_MS`, `MAX_RETRY_ATTEMPTS`는 검증되지만 - concrete HTTP client 구성에 전달되지 않는다. 이 문서의 목표 구조는 기존 기반을 폐기하는 것이 아니라 이러한 불일치를 제거하는 것이다. diff --git a/docs/architecture/typescript-state-and-data-flow.md b/docs/architecture/typescript-state-and-data-flow.md index 76972f35..8696445d 100644 --- a/docs/architecture/typescript-state-and-data-flow.md +++ b/docs/architecture/typescript-state-and-data-flow.md @@ -387,6 +387,20 @@ retry 조건: timer와 event listener는 성공, 실패, validation 조기 반환, external abort 모든 경로에서 정리되어야 한다. +RP-03의 현재 구현은 다음 계약을 자동 검증한다. + +- `request-builder.ts`가 path 값을 escape하고 search key를 정렬하며 array 순서를 + 보존한다. +- operation의 `requestSource`가 search/body schema를 선택하고 Zod의 + default/trim 결과만 URL 또는 JSON payload에 전달한다. +- runtime `REQUEST_TIMEOUT_MS`와 `MAX_RETRY_ATTEMPTS`가 transport factory에 + 주입된다. +- query adapter의 자동 retry는 끄고 HTTP만 bounded network retry를 소유한다. +- `AsyncOverlay`는 refreshing/stale-degraded/mutation-pending/ + mutation-conflict를 TypeScript union으로 배타화한다. +- `useApplicationQuery`와 `useApplicationMutation`은 cancellation, stale latch, + duplicate submit, optimistic rollback, conflict resolution을 제공한다. + ## 6. 인증과 token 소유권 기본 skeleton은 token manager를 제공하지 않는다. diff --git a/docs/testing/frontend-platform-testing-strategy.md b/docs/testing/frontend-platform-testing-strategy.md index 5885924a..babb4a51 100644 --- a/docs/testing/frontend-platform-testing-strategy.md +++ b/docs/testing/frontend-platform-testing-strategy.md @@ -91,12 +91,14 @@ Vitest의 변환 성공을 TypeScript typecheck의 대체물로 취급하지 않 - boot error shell의 safe metadata - StrictMode와 unmount cleanup -#### TanStack Query의 React integration test가 없다 +#### TanStack Query의 React integration test 기반 -Query cache adapter의 명령형 `read/write/invalidate` unit test는 있지만 -`useQuery`, `useMutation`, cancellation, stale/background refresh, optimistic -rollback을 사용하는 production presentation adapter가 아직 없다. 따라서 query -provider가 마운트되어도 React 사용자의 실제 상태 전환은 검증되지 않는다. +`tests/component/application-query.test.jsx`는 production query inbound +adapter의 query/mutation lifecycle을 검증한다. cancellation, initial terminal +failure, background stale-failure latch와 retry 복구, duplicate submit, +optimistic commit/rollback, conflict 해제와 namespace invalidation이 실제 +QueryClient 위에서 실행된다. HTTP 자동 retry가 소유자이므로 이 adapter의 +query/mutation vendor retry는 꺼져 있다. #### Form 테스트가 단일 TextField 흐름에 머문다 diff --git a/eslint.config.js b/eslint.config.js index 06a35f4c..ac300846 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -176,6 +176,20 @@ export default [ ], }, }, + { + files: [ + `src/presentation/adapters/query/**/*.${sourceExtensions}`, + ], + rules: { + "no-restricted-imports": restrictedImports([ + "**/adapters/http/**", + "**/adapters/storage/**", + "**/adapters/auth/**", + "**/bootstrap/**", + "**/application/ports/out/**", + ]), + }, + }, { files: [`src/adapters/**/*.${sourceExtensions}`], rules: { diff --git a/package.json b/package.json index 00d5bbf4..c1527366 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "check:types:fixture:ts-result": "tsc --ignoreConfig --strict --noEmit --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-result-narrowing.ts", "check:types:fixture:application-output": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-application-output.ts", "check:types:fixture:application-input": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-application-input.ts", + "check:types:fixture:async-overlay": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-async-overlay.ts", "test:runtime-schema": "vitest run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests", "test:unit": "vitest run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml", "test:component": "vitest run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml", diff --git a/src/adapters/http/client.js b/src/adapters/http/client.js index 094b2cae..46abc594 100644 --- a/src/adapters/http/client.js +++ b/src/adapters/http/client.js @@ -12,6 +12,7 @@ import { validateOperationPayload, validateOperationRequest, } from "./schema-registry.js"; +import { buildRequestTarget } from "./request-builder.js"; const noAuthSession = /** @type {import("../../application/ports/auth-session-port.js").AuthSessionPort} */ ({ @@ -22,6 +23,14 @@ const noAuthSession = }); /** @typedef {import("../../contracts/errors.js").ApiFailure} HttpFailure */ +/** @typedef {import("./request-builder.js").OperationRequestInput} OperationRequestInput */ + +/** + * @typedef {{ + * setTimeout(callback: () => void, milliseconds: number): unknown, + * clearTimeout(handle: unknown): void + * }} Scheduler + */ /** * @typedef {{ ok: true, value: unknown, meta: Record } | @@ -38,7 +47,11 @@ const noAuthSession = * validatePayload?: (schemaId: string, value: unknown) => * { success: true, data: unknown } | { success: false }, * mapPayload?: (operationId: string, payload: unknown) => unknown, - * idempotencyKeyFactory?: () => string + * idempotencyKeyFactory?: () => string, + * timeoutMs?: number, + * maxRetryAttempts?: number, + * scheduler?: Scheduler, + * getOperation?: typeof getApiOperation * }} dependencies */ export function createHttpClient(dependencies) { @@ -51,19 +64,46 @@ export function createHttpClient(dependencies) { const mapPayload = dependencies.mapPayload ?? mapOperationPayload; const idempotencyKeyFactory = dependencies.idempotencyKeyFactory ?? (() => crypto.randomUUID()); + const defaultTimeoutMs = dependencies.timeoutMs ?? 10_000; + const maxRetryAttempts = dependencies.maxRetryAttempts ?? 2; + const selectOperation = dependencies.getOperation ?? getApiOperation; + const scheduler = + dependencies.scheduler ?? + /** @type {Scheduler} */ ({ + setTimeout: (callback, milliseconds) => + globalThis.setTimeout(callback, milliseconds), + clearTimeout: (handle) => + globalThis.clearTimeout( + /** @type {ReturnType} */ (handle), + ), + }); /** - * @param {string} operationId + * @param {string | OperationRequestInput} request * @param {{ - * body?: unknown, - * routeId?: string, - * signal?: AbortSignal, - * idempotencyKey?: string - * }} [input] - * @returns {Promise} - */ - async function execute(operationId, input = {}) { - const operation = getApiOperation(operationId); + * body?: unknown, + * routeId?: string, + * pathParams?: Record, + * searchParams?: unknown, + * signal?: AbortSignal, + * idempotencyKey?: string + * }} [legacyInput] + * @returns {Promise} + */ + async function execute(request, legacyInput = {}) { + const input = + typeof request === "string" + ? { + operationId: request, + routeId: legacyInput.routeId ?? "UNSPECIFIED_ROUTE", + pathParams: legacyInput.pathParams, + searchParams: legacyInput.searchParams, + body: legacyInput.body, + signal: legacyInput.signal, + idempotencyKey: legacyInput.idempotencyKey, + } + : request; + const operation = selectOperation(input.operationId); const logicalIdempotencyKey = operation.idempotency === "keyed" ? input.idempotencyKey ?? idempotencyKeyFactory() @@ -105,7 +145,14 @@ export function createHttpClient(dependencies) { return outcome; } - if (!shouldRetry(operation, outcome.error, retryCount)) { + if ( + !shouldRetry( + operation, + outcome.error, + retryCount, + maxRetryAttempts, + ) + ) { return outcome; } @@ -117,7 +164,7 @@ export function createHttpClient(dependencies) { } catch { return { ok: false, - error: failure("REQUEST_ABORTED", operationId, retryCount, { + error: failure("REQUEST_ABORTED", input.operationId, retryCount, { code: "REQUEST_ABORTED", }), }; @@ -128,7 +175,7 @@ export function createHttpClient(dependencies) { /** * @param {{ * operation: ReturnType, - * input: { body?: unknown, routeId?: string, signal?: AbortSignal }, + * input: OperationRequestInput, * attempt: number, * idempotencyKey?: string * }} context @@ -136,23 +183,19 @@ export function createHttpClient(dependencies) { */ async function performAttempt(context) { const { operation, input, attempt, idempotencyKey } = context; - const controller = new AbortController(); - let timedOut = false; - const timeout = setTimeout(() => { - timedOut = true; - controller.abort("timeout"); - }, operation.timeoutMs); - const onExternalAbort = () => controller.abort(input.signal?.reason); - input.signal?.addEventListener("abort", onExternalAbort, { once: true }); - - const headers = new Headers({ Accept: "application/json" }); - if (input.body !== undefined) headers.set("Content-Type", "application/json"); - if (idempotencyKey) headers.set("Idempotency-Key", idempotencyKey); - - if (input.body !== undefined) { + /** @type {unknown} */ + let parsedSearch = {}; + let parsedBody; + const requestValue = + operation.requestSource === "search" + ? input.searchParams ?? {} + : operation.requestSource === "body" + ? input.body + : {}; + if (operation.requestSource !== "none") { const requestValidation = validateOperationRequest( operation.requestSchema, - input.body, + requestValue, ); if (!requestValidation.success) { return { @@ -162,12 +205,46 @@ export function createHttpClient(dependencies) { }), }; } + if (operation.requestSource === "search") { + parsedSearch = requestValidation.data; + } else { + parsedBody = requestValidation.data; + } } - let request = new Request(new URL(operation.path, dependencies.baseUrl), { + const target = buildRequestTarget( + dependencies.baseUrl, + operation, + input.pathParams, + parsedSearch, + ); + if (!target.success) { + return { + ok: false, + error: failure("VALIDATION_REJECTED", operation.operationId, attempt, { + code: target.code, + }), + }; + } + + const controller = new AbortController(); + let timedOut = false; + const timeout = scheduler.setTimeout(() => { + timedOut = true; + controller.abort("timeout"); + }, operation.timeoutMs ?? defaultTimeoutMs); + const onExternalAbort = () => controller.abort(input.signal?.reason); + input.signal?.addEventListener("abort", onExternalAbort, { once: true }); + if (input.signal?.aborted) onExternalAbort(); + + const headers = new Headers({ Accept: "application/json" }); + if (parsedBody !== undefined) headers.set("Content-Type", "application/json"); + if (idempotencyKey) headers.set("Idempotency-Key", idempotencyKey); + + let request = new Request(target.url, { method: operation.method, headers, - body: input.body === undefined ? undefined : JSON.stringify(input.body), + body: parsedBody === undefined ? undefined : JSON.stringify(parsedBody), signal: controller.signal, }); @@ -237,7 +314,7 @@ export function createHttpClient(dependencies) { }), }; } finally { - clearTimeout(timeout); + scheduler.clearTimeout(timeout); input.signal?.removeEventListener("abort", onExternalAbort); } } diff --git a/src/adapters/http/request-builder.ts b/src/adapters/http/request-builder.ts new file mode 100644 index 00000000..76ef2b09 --- /dev/null +++ b/src/adapters/http/request-builder.ts @@ -0,0 +1,73 @@ +import type { ApiOperation } from "../../contracts/api-operations.js"; + +export type OperationRequestInput = Readonly<{ + operationId: string; + routeId: string; + pathParams?: Readonly>; + searchParams?: unknown; + body?: unknown; + signal?: AbortSignal; + idempotencyKey?: string; +}>; + +export type RequestTargetResult = + | Readonly<{ success: true; url: URL }> + | Readonly<{ + success: false; + code: "PATH_PARAMETER_MISSING" | "SEARCH_PARAMETER_INVALID"; + }>; + +const pathParameterPattern = /:([A-Za-z][A-Za-z0-9_]*)|\{([A-Za-z][A-Za-z0-9_]*)\}/g; + +export function buildRequestTarget( + baseUrl: string, + operation: ApiOperation, + pathParams: Readonly> = {}, + parsedSearch: unknown = {}, +): RequestTargetResult { + let missingPathParameter = false; + const pathname = operation.path.replace( + pathParameterPattern, + (_token, colonName: string | undefined, braceName: string | undefined) => { + const name = colonName ?? braceName ?? ""; + const value = pathParams[name]; + if (value === undefined) { + missingPathParameter = true; + return ""; + } + return encodeURIComponent(String(value)); + }, + ); + if (missingPathParameter) { + return { success: false, code: "PATH_PARAMETER_MISSING" }; + } + + if ( + parsedSearch === null || + typeof parsedSearch !== "object" || + Array.isArray(parsedSearch) + ) { + return { success: false, code: "SEARCH_PARAMETER_INVALID" }; + } + + const url = new URL(pathname, baseUrl); + const search = parsedSearch as Readonly>; + for (const key of Object.keys(search).sort((left, right) => + left.localeCompare(right), + )) { + const value = search[key]; + if (value === undefined || value === null) continue; + const values = Array.isArray(value) ? value : [value]; + for (const item of values) { + if ( + typeof item !== "string" && + typeof item !== "number" && + typeof item !== "boolean" + ) { + return { success: false, code: "SEARCH_PARAMETER_INVALID" }; + } + url.searchParams.append(key, String(item)); + } + } + return { success: true, url }; +} diff --git a/src/adapters/http/retry-policy.js b/src/adapters/http/retry-policy.js index ecf787ed..e89207e5 100644 --- a/src/adapters/http/retry-policy.js +++ b/src/adapters/http/retry-policy.js @@ -35,12 +35,13 @@ export function parseRetryAfter(value, now = Date.now()) { } /** - * @param {{ idempotency: "safe" | "keyed" | "none" }} operation + * @param {{ idempotency: "safe" | "keyed" | "none", retry?: "runtime" | "never" }} operation * @param {{ kind: string, retryAfterMs?: number, httpStatus?: number }} failure * @param {number} retryCount * @param {number} [maxRetries] */ export function shouldRetry(operation, failure, retryCount, maxRetries = 2) { + if (operation.retry === "never") return false; if (retryCount >= maxRetries) return false; if (!retryKinds.has(failure.kind)) return false; if ( diff --git a/src/adapters/http/schema-registry.js b/src/adapters/http/schema-registry.js index bc2ca78a..4ec4af3a 100644 --- a/src/adapters/http/schema-registry.js +++ b/src/adapters/http/schema-registry.js @@ -57,6 +57,7 @@ const requestSchemas = .object({ cursor: z.string().optional(), limit: z.int().min(1).max(100).default(20), + tags: z.array(z.string().trim().min(1)).optional(), }) .strict(), CreateSampleResourceCommand: z diff --git a/src/adapters/platform/system-clock.js b/src/adapters/platform/system-clock.js index 62f45cd0..dbcb0df8 100644 --- a/src/adapters/platform/system-clock.js +++ b/src/adapters/platform/system-clock.js @@ -8,9 +8,13 @@ export const systemClock = Object.freeze({ return; } - const timer = setTimeout(resolve, milliseconds); + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, milliseconds); const onAbort = () => { clearTimeout(timer); + signal?.removeEventListener("abort", onAbort); reject(signal?.reason); }; signal?.addEventListener("abort", onAbort, { once: true }); diff --git a/src/application/view-models/async-state.js b/src/application/view-models/async-state.js deleted file mode 100644 index 4d6db8c5..00000000 --- a/src/application/view-models/async-state.js +++ /dev/null @@ -1,81 +0,0 @@ -export const ASYNC_BASE_STATES = Object.freeze([ - "initial-loading", - "success", - "empty", - "terminal-error", -]); - -export const ASYNC_OVERLAYS = Object.freeze([ - "refreshing", - "stale-degraded", - "mutation-pending", - "mutation-conflict", -]); - -/** - * @typedef {{ - * data?: unknown, - * isInitialLoading?: boolean, - * failure?: import("../../contracts/errors.js").ApiFailure, - * isFetching?: boolean, - * isStale?: boolean, - * isDegraded?: boolean, - * isMutationPending?: boolean, - * hasMutationConflict?: boolean - * }} AsyncSignals - */ - -/** @param {AsyncSignals} signals */ -export function deriveAsyncState(signals) { - const hasData = signals.data !== undefined && signals.data !== null; - const empty = - hasData && - ((Array.isArray(signals.data) && signals.data.length === 0) || - signals.data === ""); - - let base; - if (signals.isInitialLoading && !hasData) { - base = "initial-loading"; - } else if (signals.failure && !hasData) { - base = "terminal-error"; - } else if (empty) { - base = "empty"; - } else if (hasData) { - base = "success"; - } else { - base = "initial-loading"; - } - - const overlay = Object.freeze({ - refreshing: Boolean(signals.isFetching && hasData), - staleDegraded: Boolean(signals.isStale && signals.isDegraded && hasData), - mutationPending: Boolean(signals.isMutationPending && hasData), - mutationConflict: Boolean(signals.hasMutationConflict && hasData), - }); - - const state = { - base, - data: base === "success" || base === "empty" ? signals.data : undefined, - failure: base === "terminal-error" ? signals.failure : undefined, - overlay, - indicator: selectOverlayIndicator(overlay), - }; - - return Object.freeze(state); -} - -/** - * @param {{ - * refreshing: boolean, - * staleDegraded: boolean, - * mutationPending: boolean, - * mutationConflict: boolean - * }} overlay - */ -export function selectOverlayIndicator(overlay) { - if (overlay.mutationConflict) return "mutation-conflict"; - if (overlay.mutationPending) return "mutation-pending"; - if (overlay.staleDegraded) return "stale-degraded"; - if (overlay.refreshing) return "refreshing"; - return null; -} diff --git a/src/application/view-models/async-state.ts b/src/application/view-models/async-state.ts new file mode 100644 index 00000000..74e689d7 --- /dev/null +++ b/src/application/view-models/async-state.ts @@ -0,0 +1,156 @@ +import type { ApiFailure } from "../../contracts/errors.js"; + +export const ASYNC_BASE_STATES = Object.freeze([ + "initial-loading", + "success", + "empty", + "terminal-error", +] as const); + +export const ASYNC_OVERLAYS = Object.freeze([ + "refreshing", + "stale-degraded", + "mutation-pending", + "mutation-conflict", +] as const); + +export type AsyncOverlay = + | Readonly<{ + refreshing: false; + staleDegraded: false; + mutationPending: false; + mutationConflict: false; + }> + | Readonly<{ + refreshing: true; + staleDegraded: false; + mutationPending: false; + mutationConflict: false; + }> + | Readonly<{ + refreshing: false; + staleDegraded: true; + mutationPending: false; + mutationConflict: false; + }> + | Readonly<{ + refreshing: false; + staleDegraded: false; + mutationPending: true; + mutationConflict: false; + }> + | Readonly<{ + refreshing: false; + staleDegraded: false; + mutationPending: false; + mutationConflict: true; + }>; + +export type AsyncSignals = Readonly<{ + data?: unknown; + isInitialLoading?: boolean; + failure?: ApiFailure; + isFetching?: boolean; + isStale?: boolean; + isDegraded?: boolean; + isMutationPending?: boolean; + hasMutationConflict?: boolean; +}>; + +export type AsyncState = Readonly<{ + base: (typeof ASYNC_BASE_STATES)[number]; + data?: unknown; + failure?: ApiFailure; + overlay: AsyncOverlay; + indicator: (typeof ASYNC_OVERLAYS)[number] | null; +}>; + +export function deriveAsyncState(signals: AsyncSignals): AsyncState { + const hasData = signals.data !== undefined && signals.data !== null; + const empty = + hasData && + ((Array.isArray(signals.data) && signals.data.length === 0) || + signals.data === ""); + + const base = + signals.isInitialLoading && !hasData + ? "initial-loading" + : signals.failure && !hasData + ? "terminal-error" + : empty + ? "empty" + : hasData + ? "success" + : "initial-loading"; + + const indicator = + signals.hasMutationConflict && hasData + ? "mutation-conflict" + : signals.isMutationPending && hasData + ? "mutation-pending" + : signals.isStale && signals.isDegraded && hasData + ? "stale-degraded" + : signals.isFetching && hasData + ? "refreshing" + : null; + const overlay = overlayFor(indicator); + + return Object.freeze({ + base, + data: base === "success" || base === "empty" ? signals.data : undefined, + failure: base === "terminal-error" ? signals.failure : undefined, + overlay, + indicator, + }); +} + +export function selectOverlayIndicator( + overlay: AsyncOverlay, +): AsyncState["indicator"] { + if (overlay.mutationConflict) return "mutation-conflict"; + if (overlay.mutationPending) return "mutation-pending"; + if (overlay.staleDegraded) return "stale-degraded"; + if (overlay.refreshing) return "refreshing"; + return null; +} + +function overlayFor(indicator: AsyncState["indicator"]): AsyncOverlay { + if (indicator === "refreshing") { + return Object.freeze({ + refreshing: true, + staleDegraded: false, + mutationPending: false, + mutationConflict: false, + }); + } + if (indicator === "stale-degraded") { + return Object.freeze({ + refreshing: false, + staleDegraded: true, + mutationPending: false, + mutationConflict: false, + }); + } + if (indicator === "mutation-pending") { + return Object.freeze({ + refreshing: false, + staleDegraded: false, + mutationPending: true, + mutationConflict: false, + }); + } + if (indicator === "mutation-conflict") { + return Object.freeze({ + refreshing: false, + staleDegraded: false, + mutationPending: false, + mutationConflict: true, + }); + } + return Object.freeze({ + refreshing: false, + staleDegraded: false, + mutationPending: false, + mutationConflict: false, + }); +} diff --git a/src/bootstrap/runtime-adapters.js b/src/bootstrap/runtime-adapters.js index b4b0cc7a..835b65c7 100644 --- a/src/bootstrap/runtime-adapters.js +++ b/src/bootstrap/runtime-adapters.js @@ -3,6 +3,7 @@ import { createExternalAuthSessionAdapter, createUnavailableSessionAdapter, } from "../adapters/auth/external-session-adapter.js"; +import { createHttpClient } from "../adapters/http/client.js"; import { createQueryClient, } from "../adapters/query-cache/tanstack-query-cache.js"; @@ -40,6 +41,30 @@ function storageOrUndefined(value) { : undefined; } +/** + * Runtime-aware transport factory. Feature gateway composition calls this + * factory when a registered API capability is installed. + * + * @param {{ + * runtime: Awaited>, + * authSession: import("../application/ports/auth-session-port.js").AuthSessionPort, + * fetcher?: typeof fetch, + * clock?: import("../application/ports/clock-port.js").ClockPort, + * scheduler?: Parameters[0]["scheduler"] + * }} context + */ +export function createRuntimeHttpClient(context) { + return createHttpClient({ + baseUrl: context.runtime.config.API_BASE_URL, + timeoutMs: context.runtime.config.REQUEST_TIMEOUT_MS, + maxRetryAttempts: context.runtime.config.MAX_RETRY_ATTEMPTS, + authSession: context.authSession, + fetcher: context.fetcher, + clock: context.clock, + scheduler: context.scheduler, + }); +} + /** * @param {{ * runtime: Awaited>, diff --git a/src/contracts/api-operations.js b/src/contracts/api-operations.js index 08c65585..a4eec5b9 100644 --- a/src/contracts/api-operations.js +++ b/src/contracts/api-operations.js @@ -4,8 +4,10 @@ * path: string, * operationId: string, * auth: "none" | "external-session", - * timeoutMs: number, + * timeoutMs: number | null, * idempotency: "safe" | "keyed" | "none", + * retry: "runtime" | "never", + * requestSource: "search" | "body" | "none", * requestSchema: string, * responseSchema: string, * owner: string @@ -21,8 +23,10 @@ export const API_OPERATIONS = Object.freeze({ path: "/api/sample/resources", operationId: "LIST_SAMPLE_RESOURCES", auth: "external-session", - timeoutMs: 10_000, + timeoutMs: null, idempotency: "safe", + retry: "runtime", + requestSource: "search", requestSchema: "SampleResourceListQuery", responseSchema: "SampleResourceListPayload", owner: "feature-sample-feature-slice-contract-fixture", @@ -32,8 +36,10 @@ export const API_OPERATIONS = Object.freeze({ path: "/api/sample/resources", operationId: "CREATE_SAMPLE_RESOURCE", auth: "external-session", - timeoutMs: 10_000, + timeoutMs: null, idempotency: "keyed", + retry: "runtime", + requestSource: "body", requestSchema: "CreateSampleResourceCommand", responseSchema: "SampleResourcePayload", owner: "feature-sample-feature-slice-contract-fixture", diff --git a/src/presentation/adapters/query/application-query.ts b/src/presentation/adapters/query/application-query.ts new file mode 100644 index 00000000..10173a0e --- /dev/null +++ b/src/presentation/adapters/query/application-query.ts @@ -0,0 +1,194 @@ +import { + useCallback, + useEffect, + useRef, + useState, +} from "react"; +import { + useMutation, + useQuery, + useQueryClient, +} from "@tanstack/react-query"; + +import { + deriveAsyncState, + type AsyncState, +} from "../../../application/view-models/async-state.js"; +import type { ApiFailure } from "../../../contracts/errors.js"; + +export type ApplicationResult = + | Readonly<{ ok: true; value: Value }> + | Readonly<{ ok: false; error: ApiFailure }>; + +class ApplicationQueryError extends Error { + readonly failure: ApiFailure; + + constructor(failure: ApiFailure) { + super(failure.kind); + this.name = "ApplicationQueryError"; + this.failure = failure; + } +} + +export function useApplicationQuery( + options: Readonly<{ + queryKey: readonly unknown[]; + execute(context: Readonly<{ signal: AbortSignal }>): Promise< + ApplicationResult + >; + enabled?: boolean; + }>, +): Readonly<{ + data: Value | undefined; + state: AsyncState; + retry(): Promise; +}> { + const { queryKey, execute, enabled = true } = options; + const [staleFailure, setStaleFailure] = useState(false); + const query = useQuery({ + queryKey, + enabled, + retry: false, + queryFn: async ({ signal }) => { + const result = await execute({ signal }); + if (result.ok) return result.value; + if (signal.aborted || result.error.kind === "REQUEST_ABORTED") { + throw new DOMException("Query cancelled", "AbortError"); + } + throw new ApplicationQueryError(result.error); + }, + }); + const hasData = query.data !== undefined && query.data !== null; + + useEffect(() => { + if (query.isError && hasData) { + setStaleFailure(true); + } else if (query.isSuccess && !query.isFetching) { + setStaleFailure(false); + } + }, [hasData, query.isError, query.isFetching, query.isSuccess]); + + const retry = useCallback(async () => { + setStaleFailure(false); + await query.refetch(); + }, [query]); + + return Object.freeze({ + data: query.data, + state: deriveAsyncState({ + data: query.data, + isInitialLoading: query.isPending, + failure: + !hasData && query.error instanceof ApplicationQueryError + ? query.error.failure + : undefined, + isFetching: query.isFetching && !query.isPending, + isStale: staleFailure, + isDegraded: staleFailure, + }), + retry, + }); +} + +export function useApplicationMutation( + options: Readonly<{ + execute(input: Input): Promise>; + invalidate?: readonly (readonly unknown[])[]; + optimistic?: Readonly<{ + queryKey: readonly unknown[]; + update(previous: unknown, input: Input): unknown; + }>; + currentData?: unknown; + }>, +): Readonly<{ + state: AsyncState; + submit(input: Input): Promise>; + resolveConflict(): Promise; +}> { + const queryClient = useQueryClient(); + const { execute, invalidate = [], optimistic, currentData } = options; + const [conflict, setConflict] = useState(null); + const inFlight = useRef> | null>(null); + const mutation = useMutation({ + retry: false, + mutationFn: async (input) => { + const result = await execute(input); + if (result.ok) return result.value; + throw new ApplicationQueryError(result.error); + }, + }); + + const submit = useCallback( + (input: Input): Promise> => { + if (inFlight.current) return inFlight.current; + setConflict(null); + mutation.reset(); + + const previous = optimistic + ? queryClient.getQueryData(optimistic.queryKey) + : undefined; + if (optimistic) { + queryClient.setQueryData( + optimistic.queryKey, + optimistic.update(previous, input), + ); + } + + const pending = mutation + .mutateAsync(input) + .then(async (value) => { + for (const queryKey of invalidate) { + await queryClient.invalidateQueries({ queryKey, exact: false }); + } + return { ok: true as const, value }; + }) + .catch((error: unknown) => { + if (optimistic) { + queryClient.setQueryData(optimistic.queryKey, previous); + } + const failure = + error instanceof ApplicationQueryError + ? error.failure + : unexpectedMutationFailure(); + if (failure.kind === "CONFLICT") setConflict(failure); + return { ok: false as const, error: failure }; + }) + .finally(() => { + inFlight.current = null; + }); + inFlight.current = pending; + return pending; + }, + [invalidate, mutation, optimistic, queryClient], + ); + + const resolveConflict = useCallback(async () => { + setConflict(null); + mutation.reset(); + for (const queryKey of invalidate) { + await queryClient.invalidateQueries({ queryKey, exact: false }); + } + }, [invalidate, mutation, queryClient]); + + return Object.freeze({ + state: deriveAsyncState({ + data: currentData ?? true, + isMutationPending: mutation.isPending, + hasMutationConflict: conflict !== null, + }), + submit, + resolveConflict, + }); +} + +function unexpectedMutationFailure(): ApiFailure { + return { + kind: "UNKNOWN_FAILURE", + code: "UNKNOWN_FAILURE", + retryable: false, + operationId: "APPLICATION_MUTATION", + attemptCount: 1, + userMessageKey: "error.unknown_failure", + action: "contact-support", + }; +} diff --git a/src/presentation/adapters/query/index.ts b/src/presentation/adapters/query/index.ts new file mode 100644 index 00000000..36a7637a --- /dev/null +++ b/src/presentation/adapters/query/index.ts @@ -0,0 +1,5 @@ +export { + useApplicationMutation, + useApplicationQuery, + type ApplicationResult, +} from "./application-query.js"; diff --git a/src/presentation/components/async-surface.jsx b/src/presentation/components/async-surface.jsx index e005d7c6..c1cf68d3 100644 --- a/src/presentation/components/async-surface.jsx +++ b/src/presentation/components/async-surface.jsx @@ -65,7 +65,7 @@ export function TerminalErrorSurface({ userMessageKey, action, onAction }) { data-message-key={userMessageKey} >

{errorMessage(userMessageKey)}

- {action !== "none" && ( + {action !== "none" && onAction && ( )}
@@ -76,10 +76,18 @@ export function TerminalErrorSurface({ userMessageKey, action, onAction }) { * @param {{ * state: ReturnType, * children?: React.ReactNode, - * onAction?: () => void + * onAction?: () => void, + * onRetry?: () => void, + * onResolveConflict?: () => void * }} props */ -export function AsyncSurface({ state, children, onAction }) { +export function AsyncSurface({ + state, + children, + onAction, + onRetry, + onResolveConflict, +}) { if (state.base === "initial-loading") return ; if (state.base === "empty") return ; if (state.base === "terminal-error" && state.failure) { @@ -87,18 +95,24 @@ export function AsyncSurface({ state, children, onAction }) { ); } return (
- {state.indicator && ( -

- {state.indicator} -

- )} + {state.indicator ? ( +
+ {state.indicator} + {state.indicator === "stale-degraded" && onRetry ? ( + + ) : null} + {state.indicator === "mutation-conflict" && onResolveConflict ? ( + + ) : null} +
+ ) : null} {children}
); diff --git a/tests/component/application-query.test.jsx b/tests/component/application-query.test.jsx new file mode 100644 index 00000000..16df843e --- /dev/null +++ b/tests/component/application-query.test.jsx @@ -0,0 +1,218 @@ +// @vitest-environment jsdom + +import { + act, + renderHook, + waitFor, +} from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { describe, expect, it, vi } from "vitest"; + +import { + useApplicationMutation, + useApplicationQuery, +} from "../../src/presentation/adapters/query/application-query.js"; +import { createFailure } from "../../src/contracts/errors.js"; + +function queryClient() { + return new QueryClient({ + defaultOptions: { + queries: { retry: false, staleTime: 0, gcTime: Infinity }, + mutations: { retry: false }, + }, + }); +} + +/** @param {QueryClient} client */ +function wrapper(client) { + /** @param {{children: React.ReactNode}} props */ + return function QueryWrapper({ children }) { + return ( + {children} + ); + }; +} + +describe("application query inbound bridge", () => { + it("latches a background failure over stale data and clears it on retry success", async () => { + const client = queryClient(); + const responses = [ + { ok: /** @type {const} */ (true), value: ["first"] }, + { + ok: /** @type {const} */ (false), + error: createFailure("SERVER_FAILURE", "LIST", 0), + }, + { ok: /** @type {const} */ (true), value: ["recovered"] }, + ]; + const execute = vi.fn(async () => responses.shift() ?? responses[0]); + const hook = renderHook( + () => + useApplicationQuery({ + queryKey: ["resource", "list"], + execute, + }), + { wrapper: wrapper(client) }, + ); + + await waitFor(() => expect(hook.result.current.data).toEqual(["first"])); + await act(() => hook.result.current.retry()); + await waitFor(() => + expect(hook.result.current.state.indicator).toBe("stale-degraded"), + ); + expect(hook.result.current.state.base).toBe("success"); + expect(hook.result.current.data).toEqual(["first"]); + + await act(() => hook.result.current.retry()); + await waitFor(() => + expect(hook.result.current.data).toEqual(["recovered"]), + ); + expect(hook.result.current.state.indicator).toBeNull(); + expect(execute).toHaveBeenCalledTimes(3); + }); + + it("projects an initial application failure into terminal state", async () => { + const client = queryClient(); + const failure = createFailure("FORBIDDEN", "LIST", 0); + const hook = renderHook( + () => + useApplicationQuery({ + queryKey: ["forbidden"], + execute: async () => ({ ok: false, error: failure }), + }), + { wrapper: wrapper(client) }, + ); + + await waitFor(() => + expect(hook.result.current.state.base).toBe("terminal-error"), + ); + expect(hook.result.current.state.failure).toBe(failure); + }); + + it("passes cancellation to the application and does not retain an unmounted error", async () => { + const client = queryClient(); + let aborted = false; + const execute = vi.fn( + ({ signal }) => + new Promise((resolve) => { + signal.addEventListener( + "abort", + () => { + aborted = true; + resolve({ + ok: false, + error: createFailure("REQUEST_ABORTED", "LIST", 0), + }); + }, + { once: true }, + ); + }), + ); + const hook = renderHook( + () => + useApplicationQuery({ + queryKey: ["cancelled"], + execute, + }), + { wrapper: wrapper(client) }, + ); + + await waitFor(() => expect(execute).toHaveBeenCalledOnce()); + hook.unmount(); + await waitFor(() => expect(aborted).toBe(true)); + expect(client.getQueryState(["cancelled"])?.status).not.toBe("error"); + }); +}); + +describe("application mutation inbound bridge", () => { + it("deduplicates submit and commits one optimistic mutation", async () => { + const client = queryClient(); + const key = ["resource", "list"]; + client.setQueryData(key, ["existing"]); + /** @type {(value: {ok: true, value: string}) => void} */ + let complete = () => {}; + const execute = vi.fn( + () => + new Promise((resolve) => { + complete = resolve; + }), + ); + const hook = renderHook( + () => + useApplicationMutation({ + execute, + invalidate: [["resource"]], + currentData: client.getQueryData(key), + optimistic: { + queryKey: key, + update: (previous, input) => [ + .../** @type {string[]} */ (previous), + input, + ], + }, + }), + { wrapper: wrapper(client) }, + ); + + /** @type {ReturnType | null} */ + let first = null; + /** @type {ReturnType | null} */ + let duplicate = null; + act(() => { + first = hook.result.current.submit("created"); + duplicate = hook.result.current.submit("created"); + }); + expect(first).toBe(duplicate); + expect(client.getQueryData(key)).toEqual(["existing", "created"]); + await waitFor(() => expect(execute).toHaveBeenCalledOnce()); + await waitFor(() => + expect(hook.result.current.state.indicator).toBe("mutation-pending"), + ); + + complete({ ok: true, value: "created" }); + if (!first) throw new Error("expected pending mutation"); + await act(() => first); + expect(client.getQueryState(key)?.isInvalidated).toBe(true); + await waitFor(() => + expect(hook.result.current.state.indicator).toBeNull(), + ); + }); + + it("rolls optimistic data back and exposes a resolvable conflict", async () => { + const client = queryClient(); + const key = ["resource", "list"]; + client.setQueryData(key, ["existing"]); + const conflict = createFailure("CONFLICT", "CREATE", 0); + const hook = renderHook( + () => + useApplicationMutation({ + execute: async () => ({ ok: false, error: conflict }), + invalidate: [["resource"]], + currentData: client.getQueryData(key), + optimistic: { + queryKey: key, + update: (previous, input) => [ + .../** @type {string[]} */ (previous), + input, + ], + }, + }), + { wrapper: wrapper(client) }, + ); + + let outcome; + await act(async () => { + outcome = await hook.result.current.submit("conflicting"); + }); + expect(outcome).toEqual({ ok: false, error: conflict }); + expect(client.getQueryData(key)).toEqual(["existing"]); + expect(hook.result.current.state.indicator).toBe("mutation-conflict"); + expect(hook.result.current.state.overlay).toMatchObject({ + mutationPending: false, + mutationConflict: true, + }); + + await act(() => hook.result.current.resolveConflict()); + expect(hook.result.current.state.indicator).toBeNull(); + expect(client.getQueryState(key)?.isInvalidated).toBe(true); + }); +}); diff --git a/tests/component/async-surface.test.jsx b/tests/component/async-surface.test.jsx index e106465c..c6a7b0de 100644 --- a/tests/component/async-surface.test.jsx +++ b/tests/component/async-surface.test.jsx @@ -1,7 +1,8 @@ // @vitest-environment jsdom import { render, screen } from "@testing-library/react"; -import { describe, expect, it } from "vitest"; +import userEvent from "@testing-library/user-event"; +import { describe, expect, it, vi } from "vitest"; import { deriveAsyncState } from "../../src/application/view-models/async-state.js"; import { AsyncSurface } from "../../src/presentation/components/async-surface.jsx"; @@ -29,7 +30,7 @@ describe("async UI state matrix", () => { expect(deriveAsyncState(signals).indicator).toBe(indicator); }); - it("uses deterministic overlay priority for crossed states", () => { + it("makes crossed overlay inputs mutually exclusive by priority", () => { const state = deriveAsyncState({ data: ["value"], isFetching: true, @@ -38,8 +39,8 @@ describe("async UI state matrix", () => { }); expect(state.indicator).toBe("mutation-conflict"); expect(state.overlay).toMatchObject({ - refreshing: true, - mutationPending: true, + refreshing: false, + mutationPending: false, mutationConflict: true, }); }); @@ -52,12 +53,45 @@ describe("async UI state matrix", () => { expect(screen.getByRole("status")).toHaveTextContent("refreshing"); }); + it("connects stale retry and conflict resolution to real callbacks", async () => { + const user = userEvent.setup(); + const retry = vi.fn(); + const resolveConflict = vi.fn(); + const stale = deriveAsyncState({ + data: ["value"], + isStale: true, + isDegraded: true, + }); + const view = render( + + existing content + , + ); + await user.click(screen.getByRole("button", { name: "다시 시도" })); + expect(retry).toHaveBeenCalledOnce(); + + const conflict = deriveAsyncState({ + data: ["value"], + hasMutationConflict: true, + }); + view.rerender( + + existing content + , + ); + await user.click(screen.getByRole("button", { name: "충돌 해결" })); + expect(resolveConflict).toHaveBeenCalledOnce(); + }); + it("renders only safe error vocabulary", () => { const failure = createFailure("SERVER_FAILURE", "LIST", 0, { code: "SERVER_FAILURE", }); const state = deriveAsyncState({ failure }); - render(); + render(); expect(screen.getByRole("alert")).toHaveTextContent( "요청을 완료하지 못했습니다.", diff --git a/tests/fixtures/architecture/forbidden/presentation-imports-tanstack.tsx b/tests/fixtures/architecture/forbidden/presentation-imports-tanstack.tsx new file mode 100644 index 00000000..3a626d2a --- /dev/null +++ b/tests/fixtures/architecture/forbidden/presentation-imports-tanstack.tsx @@ -0,0 +1,3 @@ +import { useQuery } from "@tanstack/react-query"; + +export const leakedQueryHook = useQuery; diff --git a/tests/fixtures/typecheck/invalid-async-overlay.ts b/tests/fixtures/typecheck/invalid-async-overlay.ts new file mode 100644 index 00000000..2341a650 --- /dev/null +++ b/tests/fixtures/typecheck/invalid-async-overlay.ts @@ -0,0 +1,8 @@ +import type { AsyncOverlay } from "../../../src/application/view-models/async-state.js"; + +export const invalidPendingConflict: AsyncOverlay = { + refreshing: false, + staleDegraded: false, + mutationPending: true, + mutationConflict: true, +}; diff --git a/tests/integration/http-execution-contract.test.js b/tests/integration/http-execution-contract.test.js new file mode 100644 index 00000000..e8e766d1 --- /dev/null +++ b/tests/integration/http-execution-contract.test.js @@ -0,0 +1,244 @@ +import { describe, expect, it, vi } from "vitest"; + +import { createHttpClient } from "../../src/adapters/http/client.js"; +import { queryKeys } from "../../src/contracts/query-keys.js"; + +/** @param {unknown} data */ +function successResponse(data) { + return Response.json({ + success: true, + data, + meta: { requestId: "request-1", traceId: "trace-1" }, + }); +} + +/** @param {number} status */ +function failureResponse(status) { + return Response.json( + { + success: false, + error: { code: "TEMPORARY" }, + meta: { requestId: "request-1", traceId: "trace-1" }, + }, + { status }, + ); +} + +function immediateClock() { + return { now: () => 0, sleep: async () => {} }; +} + +function recordingScheduler() { + const callbacks = /** @type {Array<() => void>} */ ([]); + return { + callbacks, + setTimeout: vi.fn((callback) => { + callbacks.push(callback); + return callbacks.length - 1; + }), + clearTimeout: vi.fn(), + }; +} + +describe("HTTP operation execution contract", () => { + it("sends parsed search/body values and aligns canonical query identity", async () => { + const requests = /** @type {Request[]} */ ([]); + const scheduler = recordingScheduler(); + const fetcher = vi.fn(async (request) => { + requests.push(/** @type {Request} */ (request)); + if (/** @type {Request} */ (request).method === "POST") { + return successResponse({ id: "created", name: "Trimmed" }); + } + return successResponse([]); + }); + const client = createHttpClient({ + baseUrl: "https://api.test", + fetcher, + clock: immediateClock(), + scheduler, + }); + const filters = { tags: ["open", "new"], cursor: "a/b", limit: 5 }; + + await client.execute({ + operationId: "LIST_SAMPLE_RESOURCES", + routeId: "SAMPLE_RESOURCE_LIST", + searchParams: filters, + }); + await client.execute({ + operationId: "CREATE_SAMPLE_RESOURCE", + routeId: "SAMPLE_RESOURCE_LIST", + body: { name: " Trimmed " }, + idempotencyKey: "logical-command", + }); + + expect(requests[0].url).toBe( + "https://api.test/api/sample/resources?cursor=a%2Fb&limit=5&tags=open&tags=new", + ); + expect(queryKeys.resource.list(filters).at(-1)).toEqual(filters); + await expect(requests[1].json()).resolves.toEqual({ name: "Trimmed" }); + expect(requests[1].headers.get("Idempotency-Key")).toBe("logical-command"); + expect(scheduler.setTimeout).toHaveBeenCalledTimes(2); + expect(scheduler.clearTimeout).toHaveBeenCalledTimes(2); + }); + + it("performs no fetch or timer work for invalid request input", async () => { + const fetcher = vi.fn(); + const scheduler = recordingScheduler(); + const client = createHttpClient({ + baseUrl: "https://api.test", + fetcher, + scheduler, + }); + + await expect( + client.execute({ + operationId: "CREATE_SAMPLE_RESOURCE", + routeId: "SAMPLE_RESOURCE_LIST", + body: { name: " " }, + }), + ).resolves.toMatchObject({ + ok: false, + error: { kind: "VALIDATION_REJECTED" }, + }); + expect(fetcher).not.toHaveBeenCalled(); + expect(scheduler.setTimeout).not.toHaveBeenCalled(); + expect(scheduler.clearTimeout).not.toHaveBeenCalled(); + }); + + it.each([ + [0, 1], + [1, 2], + [2, 3], + ])( + "applies runtime max retry count %i as %i total attempts", + async (maxRetryAttempts, totalAttempts) => { + const fetcher = vi.fn(async () => failureResponse(503)); + const scheduler = recordingScheduler(); + const client = createHttpClient({ + baseUrl: "https://api.test", + fetcher, + clock: immediateClock(), + scheduler, + maxRetryAttempts, + }); + + await expect( + client.execute({ + operationId: "LIST_SAMPLE_RESOURCES", + routeId: "SAMPLE_RESOURCE_LIST", + }), + ).resolves.toMatchObject({ + ok: false, + error: { kind: "SERVER_FAILURE" }, + }); + expect(fetcher).toHaveBeenCalledTimes(totalAttempts); + expect(scheduler.setTimeout).toHaveBeenCalledTimes(totalAttempts); + expect(scheduler.clearTimeout).toHaveBeenCalledTimes(totalAttempts); + }, + ); + + it("distinguishes a runtime timeout from caller navigation abort and cleans listeners", async () => { + const scheduler = recordingScheduler(); + const fetcher = vi.fn( + (request) => + new Promise((_resolve, reject) => { + /** @type {Request} */ (request).signal.addEventListener( + "abort", + () => reject(new DOMException("aborted", "AbortError")), + { once: true }, + ); + }), + ); + const client = createHttpClient({ + baseUrl: "https://api.test", + fetcher, + scheduler, + maxRetryAttempts: 0, + }); + const timeoutResult = client.execute({ + operationId: "LIST_SAMPLE_RESOURCES", + routeId: "SAMPLE_RESOURCE_LIST", + }); + await vi.waitFor(() => expect(scheduler.callbacks).toHaveLength(1)); + scheduler.callbacks[0](); + await expect(timeoutResult).resolves.toMatchObject({ + ok: false, + error: { kind: "REQUEST_TIMEOUT" }, + }); + + const caller = new AbortController(); + const add = vi.spyOn(caller.signal, "addEventListener"); + const remove = vi.spyOn(caller.signal, "removeEventListener"); + const abortResult = client.execute({ + operationId: "LIST_SAMPLE_RESOURCES", + routeId: "SAMPLE_RESOURCE_LIST", + signal: caller.signal, + }); + await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2)); + caller.abort("navigation"); + await expect(abortResult).resolves.toMatchObject({ + ok: false, + error: { kind: "REQUEST_ABORTED" }, + }); + expect(add).toHaveBeenCalledOnce(); + expect(remove).toHaveBeenCalledOnce(); + expect(scheduler.clearTimeout).toHaveBeenCalledTimes(2); + }); + + it("never retries unsafe, non-retryable status, or schema failures", async () => { + const unsafeOperation = /** @type {const} */ ({ + method: "POST", + path: "/api/unsafe", + operationId: "UNSAFE", + auth: "none", + timeoutMs: null, + idempotency: "none", + retry: "never", + requestSource: "none", + requestSchema: "unused", + responseSchema: "SampleResourcePayload", + owner: "test", + }); + const unsafeFetch = vi.fn(async () => failureResponse(503)); + const unsafeClient = createHttpClient({ + baseUrl: "https://api.test", + fetcher: unsafeFetch, + clock: immediateClock(), + getOperation: () => unsafeOperation, + }); + await unsafeClient.execute({ + operationId: "UNSAFE", + routeId: "TEST", + }); + expect(unsafeFetch).toHaveBeenCalledOnce(); + + const statusFetch = vi.fn(async () => failureResponse(500)); + const statusClient = createHttpClient({ + baseUrl: "https://api.test", + fetcher: statusFetch, + clock: immediateClock(), + }); + await statusClient.execute({ + operationId: "LIST_SAMPLE_RESOURCES", + routeId: "SAMPLE_RESOURCE_LIST", + }); + expect(statusFetch).toHaveBeenCalledOnce(); + + const schemaFetch = vi.fn(async () => + successResponse([{ id: "one", name: 42 }]), + ); + const schemaScheduler = recordingScheduler(); + const schemaClient = createHttpClient({ + baseUrl: "https://api.test", + fetcher: schemaFetch, + clock: immediateClock(), + scheduler: schemaScheduler, + }); + await schemaClient.execute({ + operationId: "LIST_SAMPLE_RESOURCES", + routeId: "SAMPLE_RESOURCE_LIST", + }); + expect(schemaFetch).toHaveBeenCalledOnce(); + expect(schemaScheduler.clearTimeout).toHaveBeenCalledOnce(); + }); +}); diff --git a/tests/unit/request-builder.test.ts b/tests/unit/request-builder.test.ts new file mode 100644 index 00000000..23a46dcc --- /dev/null +++ b/tests/unit/request-builder.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vitest"; + +import { buildRequestTarget } from "../../src/adapters/http/request-builder.js"; +import type { ApiOperation } from "../../src/contracts/api-operations.js"; + +const operation: ApiOperation = { + method: "GET", + path: "/api/resources/{resourceId}", + operationId: "GET_RESOURCE", + auth: "none", + timeoutMs: null, + idempotency: "safe", + retry: "runtime", + requestSource: "search", + requestSchema: "ResourceQuery", + responseSchema: "ResourcePayload", + owner: "test", +}; + +describe("deterministic HTTP request target", () => { + it("escapes path values and serializes optional/array search in key order", () => { + const result = buildRequestTarget( + "https://api.test/base/", + operation, + { resourceId: "folder/item" }, + { + tags: ["beta", "alpha"], + omitted: undefined, + limit: 20, + cursor: "next page", + }, + ); + + expect(result.success).toBe(true); + if (!result.success) return; + expect(result.url.href).toBe( + "https://api.test/api/resources/folder%2Fitem?cursor=next+page&limit=20&tags=beta&tags=alpha", + ); + }); + + it("fails closed when a path value or scalar search value is invalid", () => { + expect( + buildRequestTarget("https://api.test", operation, {}, {}), + ).toEqual({ success: false, code: "PATH_PARAMETER_MISSING" }); + expect( + buildRequestTarget( + "https://api.test", + operation, + { resourceId: "one" }, + { nested: { secret: true } }, + ), + ).toEqual({ success: false, code: "SEARCH_PARAMETER_INVALID" }); + }); +}); diff --git a/tests/unit/runtime-adapters.test.js b/tests/unit/runtime-adapters.test.js index 9d9f824f..3e4f39aa 100644 --- a/tests/unit/runtime-adapters.test.js +++ b/tests/unit/runtime-adapters.test.js @@ -1,6 +1,9 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; -import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.js"; +import { + createRuntimeAdapters, + createRuntimeHttpClient, +} from "../../src/bootstrap/runtime-adapters.js"; const runtime = { config: { @@ -8,6 +11,8 @@ const runtime = { API_BASE_URL: "http://localhost:8080", TELEMETRY_ENABLED: false, AUTH_MODE: "demo", + REQUEST_TIMEOUT_MS: 4321, + MAX_RETRY_ATTEMPTS: 0, }, }; const release = /** @type {const} */ ({ @@ -53,4 +58,60 @@ describe("runtime adapter composition", () => { }); expect(adapters.outputPorts.session.getState()).toBe("integration-failed"); }); + + it("injects runtime timeout and max-attempt policy into HTTP execution", async () => { + const scheduled = + /** @type {Array<{callback: () => void, milliseconds: number}>} */ ([]); + const scheduler = { + setTimeout: vi.fn((callback, milliseconds) => { + scheduled.push({ callback, milliseconds }); + return scheduled.length; + }), + clearTimeout: vi.fn(), + }; + const fetcher = vi.fn(async () => + Response.json( + { + success: false, + error: { code: "TEMPORARY" }, + meta: { requestId: "request-1", traceId: "trace-1" }, + }, + { status: 503 }, + ), + ); + const authSession = + (await createRuntimeAdapters({ + runtime: + /** @type {Parameters[0]["runtime"]} */ ( + runtime + ), + release, + host: {}, + })).outputPorts.session; + const client = createRuntimeHttpClient({ + runtime: + /** @type {Parameters[0]["runtime"]} */ ( + runtime + ), + authSession: + /** @type {import("../../src/application/ports/auth-session-port.js").AuthSessionPort} */ ( + authSession + ), + fetcher, + clock: { now: () => 0, sleep: async () => {} }, + scheduler, + }); + + await client.execute({ + operationId: "LIST_SAMPLE_RESOURCES", + routeId: "SAMPLE_RESOURCE_LIST", + }); + + expect(fetcher).toHaveBeenCalledOnce(); + expect(scheduler.setTimeout).toHaveBeenCalledWith( + expect.any(Function), + 4321, + ); + expect(scheduler.clearTimeout).toHaveBeenCalledOnce(); + }); }); diff --git a/tests/unit/system-clock.test.js b/tests/unit/system-clock.test.js index dd94c1b8..7f0415a3 100644 --- a/tests/unit/system-clock.test.js +++ b/tests/unit/system-clock.test.js @@ -5,9 +5,14 @@ import { systemClock } from "../../src/adapters/platform/system-clock.js"; describe("systemClock", () => { it("resolves after the requested duration", async () => { vi.useFakeTimers(); - const sleeper = systemClock.sleep(250); + const caller = new AbortController(); + const add = vi.spyOn(caller.signal, "addEventListener"); + const remove = vi.spyOn(caller.signal, "removeEventListener"); + const sleeper = systemClock.sleep(250, caller.signal); await vi.advanceTimersByTimeAsync(250); await expect(sleeper).resolves.toBeUndefined(); + expect(add).toHaveBeenCalledOnce(); + expect(remove).toHaveBeenCalledOnce(); vi.useRealTimers(); }); }); From ce0040e407622dd72ff1635320205748047ec38a Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sun, 26 Jul 2026 14:26:39 +0900 Subject: [PATCH 050/178] feat: execute route and release recovery contracts --- config/ci/gates.json | 14 +- config/contracts/registry-governance.json | 63 ++++ .../decisions/VD-03-react-router-data-mode.md | 58 ++++ .../frontend-platform-capability-review.md | 50 +-- .../frontend-ports-adapters-and-boundaries.md | 14 +- .../routing-pages-and-patterns.md | 38 +-- .../frontend-platform-testing-strategy.md | 10 +- package.json | 2 + public/release-manifest.json | 10 +- scripts/check-registries.mjs | 18 + scripts/drill-runbook.mjs | 2 + scripts/generate-build-manifest.mjs | 38 ++- scripts/verify-release.mjs | 66 +++- src/application/create-application.ts | 45 +++ src/application/ports/in/application-api.ts | 9 + .../ports/out/application-output-ports.ts | 1 + src/application/ports/release-info-port.js | 11 +- .../use-cases/decide-chunk-recovery.js | 22 +- src/bootstrap/load-release-manifest.js | 99 ++++-- src/bootstrap/runtime-adapters.js | 19 ++ src/contracts/errors.js | 35 ++ src/contracts/route-runtime-contract.js | 45 +++ src/contracts/routes.js | 2 +- .../boundaries/chunk-recovery-boundary.tsx | 97 ++++++ .../boundaries/render-error-boundary.jsx | 11 + src/presentation/components/error-copy.js | 5 + src/presentation/components/page-header.jsx | 1 - src/presentation/routes/app-router.jsx | 260 --------------- src/presentation/routes/app-router.tsx | 309 ++++++++++++++++++ src/presentation/routes/navigation-policy.js | 17 +- src/presentation/routes/route-codecs.ts | 128 ++++++++ src/presentation/routes/route-runtime.tsx | 48 +++ .../chunk-recovery-boundary.test.tsx | 66 ++++ tests/component/render-boundary.test.jsx | 30 ++ tests/component/router.test.jsx | 40 ++- tests/component/runtime-application.test.jsx | 8 + .../fixtures/registry/routes/governance.json | 59 ++++ .../registry/routes/invalid-routes.ts | 29 ++ .../typecheck/invalid-route-runtime.ts | 14 + tests/helpers/create-test-application.js | 19 +- tests/runtime-schema/release-manifest.test.js | 57 ++++ tests/unit/application-boundary.test.ts | 11 + tests/unit/chunk-recovery-runtime.test.ts | 129 ++++++++ tests/unit/chunk-recovery.test.js | 11 +- tests/unit/error-classification.test.js | 2 +- tests/unit/navigation-policy.test.js | 7 +- tests/unit/registry-governance.test.js | 6 +- tests/unit/route-runtime.test.ts | 69 ++++ tests/unit/runtime-adapters.test.js | 30 ++ 49 files changed, 1761 insertions(+), 373 deletions(-) create mode 100644 docs/architecture/decisions/VD-03-react-router-data-mode.md create mode 100644 src/contracts/route-runtime-contract.js create mode 100644 src/presentation/boundaries/chunk-recovery-boundary.tsx delete mode 100644 src/presentation/routes/app-router.jsx create mode 100644 src/presentation/routes/app-router.tsx create mode 100644 src/presentation/routes/route-codecs.ts create mode 100644 src/presentation/routes/route-runtime.tsx create mode 100644 tests/component/chunk-recovery-boundary.test.tsx create mode 100644 tests/fixtures/registry/routes/governance.json create mode 100644 tests/fixtures/registry/routes/invalid-routes.ts create mode 100644 tests/fixtures/typecheck/invalid-route-runtime.ts create mode 100644 tests/unit/chunk-recovery-runtime.test.ts create mode 100644 tests/unit/route-runtime.test.ts diff --git a/config/ci/gates.json b/config/ci/gates.json index 99afbf23..79d66783 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -79,7 +79,8 @@ { "script": "check:types:fixture:ts-result", "expect": "fail" }, { "script": "check:types:fixture:application-output", "expect": "fail" }, { "script": "check:types:fixture:application-input", "expect": "fail" }, - { "script": "check:types:fixture:async-overlay", "expect": "fail" } + { "script": "check:types:fixture:async-overlay", "expect": "fail" }, + { "script": "check:types:fixture:route-runtime", "expect": "fail" } ], "logPath": "artifacts/quality/check-types.txt", "evidence": ["artifacts/quality/check-types.txt"], @@ -144,13 +145,15 @@ "steps": [ { "script": "check:architecture", "expect": "pass" }, { "script": "check:registries", "expect": "pass" }, - { "script": "check:registries:fixture", "expect": "fail" } + { "script": "check:registries:fixture", "expect": "fail" }, + { "script": "check:routes:fixture", "expect": "fail" } ], "logPath": "artifacts/quality/gates/FE-GATE-010.txt", "evidence": [ "artifacts/quality/dependency-report.json", "artifacts/quality/registries.json", - "artifacts/quality/registry-fixture.json" + "artifacts/quality/registry-fixture.json", + "artifacts/quality/route-registry-fixture.json" ], "retentionClass": "merge-cycle" }, @@ -158,7 +161,10 @@ "name": "build", "steps": [{ "script": "build", "expect": "pass" }], "logPath": "artifacts/quality/gates/FE-GATE-011.txt", - "evidence": ["artifacts/release/build-manifest.json"], + "evidence": [ + "artifacts/release/build-manifest.json", + "artifacts/release/runtime-config.schema.json" + ], "retentionClass": "release-coherence" }, "FE-GATE-012": { diff --git a/config/contracts/registry-governance.json b/config/contracts/registry-governance.json index 84d14800..36afe186 100644 --- a/config/contracts/registry-governance.json +++ b/config/contracts/registry-governance.json @@ -6,6 +6,37 @@ "path": "src/contracts/routes.js", "exportName": "ROUTE_REGISTRY", "owner": "feature-routing-navigation-guard-contract", + "uniqueFields": ["routeId", "path", "chunkId"], + "allowedValues": { + "paramsSchema": [null, "NotFoundSplat"], + "searchSchema": [null, "SampleResourceListQuery"], + "loadingSurface": [ + "app-shell", + "example-page", + "sample-resource-list", + "none" + ], + "errorSurface": [ + "route-boundary", + "feature-boundary", + "not-found" + ], + "chunkId": [ + "route-home", + "route-examples-ui", + "route-examples-states", + "route-examples-auth", + "route-sample-resources", + "route-not-found" + ] + }, + "references": [ + { + "field": "routeId", + "registryId": "FE-REG-ROUTE-RUNTIME", + "targetField": "routeId" + } + ], "requiredFields": [ "routeId", "path", @@ -17,6 +48,38 @@ "chunkId" ] }, + { + "registryId": "FE-REG-ROUTE-RUNTIME", + "path": "src/contracts/route-runtime-contract.js", + "exportName": "ROUTE_RUNTIME_CONTRACT", + "owner": "feature-frontend-routing-release-recovery-runtime", + "requiredFields": [ + "routeId", + "moduleId", + "paramsCodec", + "searchCodec" + ], + "uniqueFields": ["routeId", "moduleId"], + "allowedValues": { + "moduleId": [ + "home-page", + "ui-gallery-page", + "state-gallery-page", + "auth-example-page", + "sample-contract-page", + "not-found-page" + ], + "paramsCodec": ["none", "NotFoundSplat"], + "searchCodec": ["none", "SampleResourceListQuery"] + }, + "references": [ + { + "field": "routeId", + "registryId": "FE-REG-ROUTE", + "targetField": "routeId" + } + ] + }, { "registryId": "FE-REG-API", "path": "src/contracts/api-operations.js", diff --git a/docs/architecture/decisions/VD-03-react-router-data-mode.md b/docs/architecture/decisions/VD-03-react-router-data-mode.md new file mode 100644 index 00000000..a562a0f5 --- /dev/null +++ b/docs/architecture/decisions/VD-03-react-router-data-mode.md @@ -0,0 +1,58 @@ +# VD-03: React Router Data Mode와 서버 상태 소유권 + +- 상태: Accepted +- 결정일: 2026-07-26 +- 적용 브랜치: `feature-frontend-routing-release-recovery-runtime` + +## 배경 + +기존 라우터는 `BrowserRouter`와 수동 JSX route 목록을 사용했다. 직렬화 가능한 +route registry에 params/search schema, loading/error surface, access, title, +navigation과 chunk ID가 있었지만 실행 route tree와 독립적이어서 선언과 행동이 +어긋날 수 있었다. + +이 저장소는 client-only SPA이며 서버 상태는 application input과 TanStack Query가 +소유한다. Framework Mode의 loader/action 중심 데이터 소유권이나 SSR을 도입하지 +않으면서 route object, 오류 경계와 navigation lifecycle은 중앙에서 조립할 +필요가 있다. + +## 결정 + +1. 고정된 React Router `7.18.1`의 `createBrowserRouter`와 `RouterProvider`를 + 사용하는 Data Mode를 기본값으로 채택한다. +2. 직렬화 가능한 route contract와 React component/codec runtime map을 분리한다. +3. 모든 executable route object와 navigation은 registry에서 생성한다. JSX에서 + route 목록을 다시 열거하지 않는다. +4. params/search는 route 경계의 Zod codec으로 parse하고 같은 codec으로 canonical + URL을 생성한다. +5. loader/action은 같은 서버 데이터를 직접 다시 요청하지 않는다. 필요하면 + application input 또는 query adapter 한 경로를 호출한다. +6. 서버 상태, retry, cache와 mutation lifecycle은 application input과 TanStack + Query가 계속 소유한다. +7. lazy chunk rejection만 release recovery input으로 보내며 일반 render error는 + route/feature boundary가 소유한다. +8. Framework Mode, SSR, static generation과 router version upgrade는 별도 + dependency/architecture 브랜치에서 결정한다. + +## 검증 + +- route contract/runtime map의 누락과 orphan은 TypeScript negative fixture와 + registry gate가 모두 거절한다. +- duplicate ID/path, unknown codec/surface/chunk와 참조 불일치를 negative registry + fixture로 검증한다. +- params/search parse/build round-trip, canonical redirect, 최대 redirect hop, + access rejection, title/focus와 boundary reset을 unit/component test로 검증한다. +- Vite dynamic entry와 release route chunk map, runtime config JSON Schema를 + build/release 검증기가 확인한다. +- chunk failure는 no-store manifest refetch 후 build/release 쌍마다 한 번만 + reload하며 offline, malformed manifest와 storage 실패는 fail-closed한다. + +## 결과와 rollback + +Data Router는 navigation lifecycle의 조립 경계이며 서버 데이터 계층이 아니다. +이 구분을 지키면 React Router를 교체해도 application input과 output port는 +유지된다. + +rollback은 RP-04 merge를 되돌려 이전 수동 router와 generic route failure +surface로 복구한다. URL shape와 application API는 유지하고, 이미 배포된 asset +cache의 purge는 저장소 rollback 범위에 포함하지 않는다. diff --git a/docs/architecture/frontend-platform-capability-review.md b/docs/architecture/frontend-platform-capability-review.md index 88a40417..baac965c 100644 --- a/docs/architecture/frontend-platform-capability-review.md +++ b/docs/architecture/frontend-platform-capability-review.md @@ -12,9 +12,9 @@ - 기본 번들에 포함할 역량과 필요할 때 설치할 확장 역량을 구분한다. - 특정 벤더를 채택하더라도 제품 코드가 벤더 API에 직접 결합되지 않는지 확인한다. -검토 기준 브랜치는 `develop`, 기준 커밋은 `cb195f8`이다. 이후 구현으로 경로나 -세부 내용이 달라질 수 있으므로, 각 항목은 문서의 경로뿐 아니라 해당 테스트와 -아키텍처 게이트로 계속 검증해야 한다. +최초 검토 기준은 `develop`의 `cb195f8`이며, RP-01~RP-04 구현 결과를 이 문서에 +누적 반영했다. 이후 구현으로 경로나 세부 내용이 달라질 수 있으므로, 각 항목은 +문서의 경로뿐 아니라 해당 테스트와 아키텍처 게이트로 계속 검증해야 한다. ## 2. 결론 @@ -33,13 +33,14 @@ 특히 다음은 선행 해결이 필요하다. -RP-01~RP-03에서 TypeScript 도구 안전망, application runtime 주입, -query/mutation inbound adapter와 HTTP 실행 계약은 구현됐다. 현재 선행 해결 +RP-01~RP-04에서 TypeScript 도구 안전망, application runtime 주입, +query/mutation inbound adapter, HTTP 실행 계약과 executable route/release +recovery 계약은 구현됐다. 현재 선행 해결 대상은 다음과 같다. -1. 선언과 실행이 일치하는 typed route 계약 -2. 전체를 제거할 수 있는 실제 reference feature -3. 폼, 페이지 템플릿, 확장된 디자인 시스템과 컴포넌트 워크벤치 +1. 전체를 제거할 수 있는 실제 reference feature +2. 폼, 페이지 템플릿, 확장된 디자인 시스템과 컴포넌트 워크벤치 +3. 국제화, diagnostics, optional adapter recipe와 심화 품질 게이트 따라서 현재 상태를 “프론트 공통부가 모두 구현됐다”고 표현하면 범위가 과장된다. 더 정확한 표현은 다음과 같다. @@ -72,7 +73,7 @@ query/mutation inbound adapter와 HTTP 실행 계약은 구현됐다. 현재 선 | 서버 상태 | 부분 준비 | 제한된 query/mutation bridge와 lifecycle test | RP-05 reference route에서 실제 feature 연결 | | 클라이언트 상태 | 부분 준비 | local state, theme context, session external store | 상태 소유권 표와 typed external-store 예제 | | 범용 global store | 프로젝트 선택 | 별도 라이브러리 없음 | 필요 조건에 따라 Zustand/Redux Toolkit/state machine 선택 | -| 라우팅 | 부분 준비 | lazy route, access hint, registry 존재 | typed runtime map, codec, recovery, metadata 집행 | +| 라우팅 | 준비됨 | Data Router, typed runtime map, codec, metadata consumer, bounded chunk recovery | reference feature route와 release E2E로 사용 범위 확장 | | 앱 셸·반응형 | 부분 준비 | header/sidebar/content/theme 구현 | 접근 가능한 mobile drawer와 focus 복원 | | 페이지 템플릿 | 미제공 | 각 페이지가 직접 레이아웃 조립 | list/detail/form/status 등 슬롯 기반 템플릿 | | 디자인 토큰 | 부분 준비 | semantic color/theme 토큰 존재 | typography, spacing, motion, layer 등 3단계 토큰 | @@ -156,14 +157,16 @@ client를 거대한 범용 함수로 계속 확장하지 말고 transport, reque timeout, retry, decoder, mapper 책임을 분리해야 한다. application에는 범용 HTTP 메서드보다 feature가 요구하는 gateway interface를 노출한다. -#### route registry가 실행 계약이 아니다 +#### RP-04에서 route registry를 실행 계약으로 전환 -route registry에는 `paramsSchema`, `searchSchema`, `loadingSurface`, -`errorSurface`, `chunkId`가 있지만 실제 router tree, lazy module, navigation -목록은 별도로 작성된다. 여러 필드는 선언만 되고 런타임에 사용되지 않는다. -chunk recovery use case와 redirect loop guard도 실제 route flow에 연결되지 않는다. +`src/contracts/routes.js`와 직렬화 가능한 +`src/contracts/route-runtime-contract.js`를 기준으로 +`src/presentation/routes/app-router.tsx`가 Data Router route object와 +navigation을 생성한다. `route-runtime.tsx`는 lazy component의 실행 map만 +소유하며 contract/runtime 누락과 orphan은 TypeScript negative fixture와 registry +gate가 모두 거절한다. -목표 상태: +현재 보장: - serializable contract와 executable runtime map을 분리한다. - `satisfies Record`로 양방향 완전성을 검사한다. @@ -171,8 +174,10 @@ chunk recovery use case와 redirect loop guard도 실제 route flow에 연결되 사용한다. - loading/error/chunk/access/title/navigation metadata를 실제 route object에 연결한다. -- route change 시 boundary reset, focus, scroll, navigation cancellation을 - 검증한다. +- route change 시 boundary reset, title, focus와 scroll을 검증한다. +- Vite manifest의 실제 dynamic entry와 route chunk ID를 release manifest에 + 연결하고, no-store manifest 재조회와 build/release 쌍별 1회 reload를 + production application input까지 연결한다. #### reference feature가 완전히 제거되지 않는다 @@ -204,9 +209,11 @@ mutation-pending mutation-conflict ``` -chunk recovery와 release coherence도 policy 함수가 존재하는 것으로 완료되지 -않는다. 실제 lazy import failure가 manifest 재확인, build 비교, 단 한 번의 guarded -reload, 반복 실패 지원 표면까지 이어지고 E2E로 검증되어야 한다. +RP-04에서 lazy import failure는 `ChunkRecoveryBoundary` → application recovery +input → `ReleaseInfoPort.refresh()`의 no-store manifest 조회 → build/release 쌍 +guard → browser navigation adapter의 1회 reload로 연결됐다. 일반 render +failure는 이 경로에서 제외되고, 반복 실패·offline·malformed manifest·storage +실패는 지원 표면으로 fail-closed된다. #### telemetry, registry, 공급망 gate의 실행 깊이가 부족하다 @@ -378,7 +385,8 @@ tree-shakable SVG icon source로 적절하지만 select, dialog, menu, focus man - TS source와 test 전체 typecheck - 실제 composition root부터 page까지의 통합 - query/mutation controller와 optimistic rollback -- route registry/runtime map 정합성 +- route registry/runtime map 정합성은 RP-04에서 unit, component, negative + registry/type fixture와 built artifact 검증으로 구현됨 - runtime timeout/retry와 path/query/parsed body - shared MSW scenario catalog - isolated component stories와 interaction test diff --git a/docs/architecture/frontend-ports-adapters-and-boundaries.md b/docs/architecture/frontend-ports-adapters-and-boundaries.md index 9f4e58d7..fa86802c 100644 --- a/docs/architecture/frontend-ports-adapters-and-boundaries.md +++ b/docs/architecture/frontend-ports-adapters-and-boundaries.md @@ -154,11 +154,13 @@ RP-03 구현으로 HTTP와 server-state 경계도 다음처럼 연결됐다. - HTTP가 자동 network retry를 소유하고 query/mutation adapter의 vendor retry는 비활성화한다. +RP-04에서 첫 번째 실행 불일치는 닫혔다. route registry와 runtime map은 +Data Router tree, codec, surface, title, navigation, chunk/release recovery의 +단일 조립 입력이며 registry/type/build 검증이 누락과 orphan을 거절한다. + 후속 브랜치에서 닫아야 할 실행 불일치는 다음과 같다. -1. route registry의 `paramsSchema`, `searchSchema`, `loadingSurface`, - `errorSurface`, `chunkId` 일부는 실행 route와 연결되지 않았다. -2. 제거 테스트는 `src/sample/contract-fixture`만 제거하며, sample API +1. 제거 테스트는 `src/sample/contract-fixture`만 제거하며, sample API operation, Zod schema, mapper, domain model과 query key는 다른 경로에 남는다. @@ -1212,9 +1214,9 @@ contract와 실패 분기를 우선한다. ### 26.4 Routing과 상태 -- [ ] route registry와 실행 route tree가 동일 source에서 생성된다. -- [ ] params/search schema가 실제 navigation에서 실행된다. -- [ ] loading/error/chunk/access metadata가 실행 behavior와 연결된다. +- [x] route registry와 실행 route tree가 동일 source에서 생성된다. +- [x] params/search schema가 실제 navigation에서 실행된다. +- [x] loading/error/chunk/access metadata가 실행 behavior와 연결된다. - [ ] local, URL, server, session, persisted state가 분류 규칙을 따른다. - [ ] server state를 별도 global store에 중복 보관하지 않는다. diff --git a/docs/architecture/routing-pages-and-patterns.md b/docs/architecture/routing-pages-and-patterns.md index 8f4bb800..4d4e71b6 100644 --- a/docs/architecture/routing-pages-and-patterns.md +++ b/docs/architecture/routing-pages-and-patterns.md @@ -14,24 +14,22 @@ ## 2. 현재 상태와 문제 -현재 구현에는 다음 장점이 있다. +RP-04 이후 현재 구현에는 다음 장점이 있다. - route registry가 path와 access policy를 소유한다. -- route component를 lazy import한다. +- contract에서 Data Router route object와 navigation을 생성한다. +- runtime map이 route component를 lazy import하고 codec을 연결한다. - 앱 셸과 보호 route, not-found surface가 있다. - route heading focus와 비동기/render error boundary가 있다. -- redirect loop와 chunk recovery에 대한 policy 함수가 일부 존재한다. +- redirect loop와 chunk recovery가 bounded production call graph에 연결돼 있다. -하지만 `src/contracts/routes.js`의 metadata와 -`src/presentation/routes/app-router.jsx`의 executable route tree가 별도 수동 목록이다. -그 결과 다음 필드는 선언돼도 실제 행동을 보장하지 않는다. - -- params/search schema -- loading/error surface -- chunk ID -- route title/navigation label -- redirect loop guard -- chunk recovery policy +`src/contracts/routes.js`, `src/contracts/route-runtime-contract.js`, +`src/presentation/routes/route-runtime.tsx`의 완전성은 TypeScript와 registry +negative fixture가 함께 검사한다. params/search codec, loading/error surface, +access, title, navigation, chunk ID는 +`src/presentation/routes/app-router.tsx`에서 모두 소비된다. built Vite +manifest의 dynamic entry는 release manifest route chunk map과 검증되며, +`ChunkRecoveryBoundary`는 일반 render error와 chunk rejection을 분리한다. 페이지도 공통 `PageHeader` 외에는 각자 section과 class를 직접 조립한다. 목록, 상세, 편집, 오류 페이지의 반복되는 접근성·반응형·상태 표면을 기능 팀이 다시 @@ -50,15 +48,14 @@ selector를 `7.18.1`로 맞춰 확인한다. | mode | 선택 조건 | 이 저장소에서의 판단 | | --- | --- | --- | -| Declarative | React composition과 외부 data layer가 route data를 소유 | 현재 구현이 사용 중인 기준선 | -| Data | route object, blocker, scroll restoration, pending/navigation state가 필요 | 목표 skeleton의 navigation lifecycle에 적합 | +| Declarative | React composition과 외부 data layer가 route data를 소유 | RP-04 이전 기준선 | +| Data | route object, blocker, scroll restoration, pending/navigation state가 필요 | VD-03으로 채택하고 RP-04에서 구현 | | Framework | route module, type-safe href, code splitting, SSR/static 전략을 framework가 소유 | client-only skeleton 기본값으로는 범위가 큼 | -목표 결정: +채택한 결정: - client-only SPA와 TanStack Query/application use case를 유지한다. -- 현재 `BrowserRouter` 기반 Declarative Mode에서 `createBrowserRouter`와 - `RouterProvider` 기반 Data Mode로 이동한다. +- `createBrowserRouter`와 `RouterProvider` 기반 Data Mode를 사용한다. - Data Mode를 선택하는 이유는 route object, navigation blocker, scroll restoration, route error 경계를 일관되게 소유하기 위해서다. loader/action으로 서버 상태를 다시 소유하기 위해서가 아니다. @@ -68,8 +65,9 @@ selector를 `7.18.1`로 맞춰 확인한다. - SSR/static generation을 선택하기 전에는 Framework Mode를 기본값으로 만들지 않는다. -전환 브랜치 전까지 현재 Declarative router에 새 custom scroll/blocker -implementation을 추가하지 않는다. 전환할 수 없는 프로젝트만 별도 ADR과 +결정 근거와 rollback 경계는 +`docs/architecture/decisions/VD-03-react-router-data-mode.md`에 고정한다. +Data Mode를 사용할 수 없는 프로젝트만 별도 ADR과 `NavigationLifecycleAdapter`를 구현한다. ## 4. route 계약과 runtime map diff --git a/docs/testing/frontend-platform-testing-strategy.md b/docs/testing/frontend-platform-testing-strategy.md index babb4a51..ddf862e9 100644 --- a/docs/testing/frontend-platform-testing-strategy.md +++ b/docs/testing/frontend-platform-testing-strategy.md @@ -370,10 +370,9 @@ QueryClientProvider -> AppShell ``` -04 routing branch에서 Data Mode로 전환할 때 `BrowserRouter`를 -`RouterProvider`로 바꾸고 테스트 fixture도 같은 composition factory에서 -생성한다. 문서에 적힌 provider 순서를 테스트 전용 shell로 재현하지 말고 -production composition 함수를 호출한다. +RP-04에서 `RouterProvider` 기반 Data Mode로 전환했다. router component test와 +runtime composition test는 production `AppRouter`와 composition 함수를 사용하며, +문서에 적힌 provider 순서를 테스트 전용 shell로 재현하지 않는다. ### 6.3 Boot E2E @@ -1273,7 +1272,8 @@ CI registry에 추가한다. 3. MSW handlers/scenario/factory를 중앙 catalog로 이동한다. 4. query/mutation presentation adapter와 integration harness를 만든다. 5. form foundation과 form/controller test matrix를 만든다. -6. route registry/runtime map contract와 built-dist E2E를 추가한다. +6. route registry/runtime map contract와 built-dist artifact 검증을 유지하고, + release server를 사용하는 built-dist E2E까지 확장한다. 7. Storybook build, interaction, a11y gate를 추가한다. 8. pinned Chromium visual baseline을 추가한다. 9. critical flow의 3-engine release profile을 분리한다. diff --git a/package.json b/package.json index c1527366..0191f54d 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,7 @@ "check:types:fixture:application-output": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-application-output.ts", "check:types:fixture:application-input": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-application-input.ts", "check:types:fixture:async-overlay": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-async-overlay.ts", + "check:types:fixture:route-runtime": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-route-runtime.ts", "test:runtime-schema": "vitest run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests", "test:unit": "vitest run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml", "test:component": "vitest run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml", @@ -40,6 +41,7 @@ "check:browser-security": "node scripts/check-browser-security.mjs", "check:registries": "node scripts/check-registries.mjs", "check:registries:fixture": "node scripts/check-registries.mjs --governance tests/fixtures/registry/forbidden/governance.json --artifact artifacts/quality/registry-fixture.json", + "check:routes:fixture": "node scripts/check-registries.mjs --governance tests/fixtures/registry/routes/governance.json --artifact artifacts/quality/route-registry-fixture.json", "verify:compatibility": "node scripts/check-compatibility.mjs", "verify:release": "node scripts/verify-release.mjs", "verify:hosting-headers": "node scripts/verify-hosting-headers.mjs", diff --git a/public/release-manifest.json b/public/release-manifest.json index f316fcd0..051a15f7 100644 --- a/public/release-manifest.json +++ b/public/release-manifest.json @@ -7,5 +7,13 @@ "apiContractVersion": "1", "assetManifestHash": "generated-during-build", "releaseId": "local-release", - "builtAt": "1970-01-01T00:00:00.000Z" + "builtAt": "1970-01-01T00:00:00.000Z", + "routeChunks": { + "route-home": "src/presentation/pages/home-page.jsx", + "route-examples-ui": "src/presentation/examples/ui-gallery-page.jsx", + "route-examples-states": "src/presentation/examples/state-gallery-page.jsx", + "route-examples-auth": "src/presentation/examples/auth-example-page.jsx", + "route-sample-resources": "src/presentation/pages/sample-contract-page.jsx", + "route-not-found": "src/presentation/pages/not-found-page.jsx" + } } diff --git a/scripts/check-registries.mjs b/scripts/check-registries.mjs index ea9d40ac..60692dad 100644 --- a/scripts/check-registries.mjs +++ b/scripts/check-registries.mjs @@ -103,6 +103,24 @@ for (const specification of governance.registries) { } } + for (const [field, allowed] of Object.entries( + specification.allowedValues ?? {}, + )) { + for (const [rowName, row] of Object.entries(rows)) { + if (!row || typeof row !== "object" || Array.isArray(row)) continue; + if ( + !allowed.some( + /** @param {unknown} value */ + (value) => Object.is(value, row[field]), + ) + ) { + failures.push( + `${specification.registryId}.${rowName}.${field} has unknown value ${String(row[field])}`, + ); + } + } + } + snapshots.push({ registryId: specification.registryId, owner: specification.owner, diff --git a/scripts/drill-runbook.mjs b/scripts/drill-runbook.mjs index 08bacb48..bba52f25 100644 --- a/scripts/drill-runbook.mjs +++ b/scripts/drill-runbook.mjs @@ -123,6 +123,8 @@ async function drillChunkMismatch() { failureKind: "DEPLOY_MISMATCH", manifestLoaded: true, currentBuildId: "build-a", + currentReleaseId: "release-a", + activeBuildId: "build-b", activeReleaseId: "release-b", storage, }; diff --git a/scripts/generate-build-manifest.mjs b/scripts/generate-build-manifest.mjs index 1f3df8ff..b6a5ff8f 100644 --- a/scripts/generate-build-manifest.mjs +++ b/scripts/generate-build-manifest.mjs @@ -1,6 +1,11 @@ import { createHash } from "node:crypto"; import { mkdir, readFile, writeFile } from "node:fs/promises"; import process from "node:process"; +import { z } from "zod"; + +import { ROUTE_REGISTRY } from "../src/contracts/routes.js"; +import { ROUTE_RUNTIME_CONTRACT } from "../src/contracts/route-runtime-contract.js"; +import { runtimeConfigSchema } from "../src/bootstrap/runtime-config-schema.js"; const packageJson = JSON.parse(await readFile("package.json", "utf8")); const packageManagerVersion = packageJson.packageManager.split("@").at(-1); @@ -9,11 +14,31 @@ const commitSha = process.env.VITE_COMMIT_SHA ?? "local"; const releaseId = process.env.RELEASE_ID ?? "local-release"; const runnerImage = process.env.CI_RUNNER_IMAGE ?? `${process.platform}-${process.arch}`; const builtAt = new Date().toISOString(); -const viteManifest = await readFile("dist/.vite/manifest.json"); +const viteManifest = await readFile("dist/.vite/manifest.json", "utf8"); +const viteManifestObject = + /** @type {Record} */ ( + JSON.parse(viteManifest) + ); const assetManifestHash = createHash("sha256") .update(viteManifest) .digest("hex"); const runtimeConfig = JSON.parse(await readFile("dist/config.json", "utf8")); +/** @type {Record} */ +const routeChunks = {}; +for (const definition of Object.values(ROUTE_REGISTRY)) { + const runtime = + /** @type {Record} */ ( + ROUTE_RUNTIME_CONTRACT + )[definition.routeId]; + const asset = Object.values(viteManifestObject).find( + (entry) => entry.name === runtime?.moduleId && entry.isDynamicEntry, + ); + if (!runtime || !asset?.file) { + throw new Error(`Missing built route chunk: ${definition.routeId}`); + } + routeChunks[definition.chunkId] = asset.file; +} +const runtimeConfigJsonSchema = z.toJSONSchema(runtimeConfigSchema); runtimeConfig.BUILD_ID = buildId; runtimeConfig.RELEASE_ID = releaseId; @@ -31,6 +56,8 @@ const manifest = { outputs: { directory: "dist", viteManifest: "dist/.vite/manifest.json", + routeChunks, + runtimeConfigSchema: "dist/runtime-config.schema.json", }, }; @@ -44,6 +71,7 @@ const releaseManifest = { assetManifestHash, releaseId, builtAt, + routeChunks, }; await mkdir("artifacts/release", { recursive: true }); @@ -52,6 +80,14 @@ await writeFile( "dist/release-manifest.json", `${JSON.stringify(releaseManifest, null, 2)}\n`, ); +await writeFile( + "dist/runtime-config.schema.json", + `${JSON.stringify(runtimeConfigJsonSchema, null, 2)}\n`, +); +await writeFile( + "artifacts/release/runtime-config.schema.json", + `${JSON.stringify(runtimeConfigJsonSchema, null, 2)}\n`, +); await writeFile( "artifacts/release/build-manifest.json", `${JSON.stringify(manifest, null, 2)}\n`, diff --git a/scripts/verify-release.mjs b/scripts/verify-release.mjs index 61374344..ca5e4fe8 100644 --- a/scripts/verify-release.mjs +++ b/scripts/verify-release.mjs @@ -6,6 +6,8 @@ import { compareReleaseToRuntime, RELEASE_TOKEN_REGISTRY, } from "../src/contracts/release-tokens.js"; +import { ROUTE_RUNTIME_CONTRACT } from "../src/contracts/route-runtime-contract.js"; +import { ROUTE_REGISTRY } from "../src/contracts/routes.js"; const fixturesDocument = /** @type {{ @@ -34,7 +36,17 @@ const fixturesDocument = ); const release = JSON.parse(await readFile("dist/release-manifest.json", "utf8")); const runtimeConfig = JSON.parse(await readFile("dist/config.json", "utf8")); -const viteManifest = await readFile("dist/.vite/manifest.json"); +const buildManifest = JSON.parse( + await readFile("artifacts/release/build-manifest.json", "utf8"), +); +const runtimeConfigJsonSchema = JSON.parse( + await readFile("dist/runtime-config.schema.json", "utf8"), +); +const viteManifest = await readFile("dist/.vite/manifest.json", "utf8"); +const viteManifestObject = + /** @type {Record} */ ( + JSON.parse(viteManifest) + ); const actualAssetManifestHash = createHash("sha256") .update(viteManifest) .digest("hex"); @@ -52,6 +64,58 @@ if (!Number.isFinite(Date.parse(release.builtAt))) { if (release.assetManifestHash !== actualAssetManifestHash) { artifactMismatches.push("assetManifestContent"); } +if ( + runtimeConfigJsonSchema.$schema !== "https://json-schema.org/draft/2020-12/schema" || + runtimeConfigJsonSchema.type !== "object" || + !runtimeConfigJsonSchema.properties +) { + artifactMismatches.push("runtimeConfigSchema"); +} +if ( + buildManifest.outputs?.runtimeConfigSchema !== + "dist/runtime-config.schema.json" +) { + artifactMismatches.push("buildManifest:runtimeConfigSchema"); +} + +const expectedChunkIds = new Set( + Object.values(ROUTE_REGISTRY).map((definition) => definition.chunkId), +); +const actualChunkIds = new Set(Object.keys(release.routeChunks ?? {})); +for (const chunkId of expectedChunkIds) { + if (!actualChunkIds.has(chunkId)) { + artifactMismatches.push(`routeChunk:missing:${chunkId}`); + } +} +for (const chunkId of actualChunkIds) { + if (!expectedChunkIds.has(chunkId)) { + artifactMismatches.push(`routeChunk:orphan:${chunkId}`); + } +} +for (const definition of Object.values(ROUTE_REGISTRY)) { + const runtime = + /** @type {Record} */ ( + ROUTE_RUNTIME_CONTRACT + )[definition.routeId]; + const viteEntry = Object.values(viteManifestObject).find( + (entry) => entry.name === runtime?.moduleId && entry.isDynamicEntry, + ); + const routeAsset = release.routeChunks?.[definition.chunkId]; + if (!runtime || !viteEntry || routeAsset !== viteEntry.file) { + artifactMismatches.push(`routeChunk:mismatch:${definition.chunkId}`); + continue; + } + if ( + buildManifest.outputs?.routeChunks?.[definition.chunkId] !== routeAsset + ) { + artifactMismatches.push(`buildManifest:routeChunk:${definition.chunkId}`); + } + try { + await readFile(`dist/${routeAsset}`); + } catch { + artifactMismatches.push(`routeChunk:file:${definition.chunkId}`); + } +} const fixtures = fixturesDocument.fixtures.map((fixture) => { const result = verifyCompatibilityTuple({ diff --git a/src/application/create-application.ts b/src/application/create-application.ts index d3910bdb..2b92f9d0 100644 --- a/src/application/create-application.ts +++ b/src/application/create-application.ts @@ -5,6 +5,7 @@ import type { RenderFailureReport, } from "./ports/in/application-api.js"; import type { ApplicationOutputPorts } from "./ports/out/application-output-ports.js"; +import { decideChunkRecovery } from "./use-cases/decide-chunk-recovery.js"; export type { ApplicationApi, ApplicationOutputPorts }; @@ -64,10 +65,54 @@ export function createApplication( }, }); + const recovery = Object.freeze({ + async recoverChunk(input: { + chunkId: string; + failureKind: "CHUNK_LOAD_FAILURE" | "DEPLOY_MISMATCH"; + }) { + try { + const current = await outputPorts.releaseInfo.getCurrent(); + const active = await outputPorts.releaseInfo.refresh(); + if (!active.routeChunks[input.chunkId]) { + return { + action: "support" as const, + reason: "active-chunk-unknown", + }; + } + const decision = decideChunkRecovery({ + failureKind: input.failureKind, + manifestLoaded: true, + currentBuildId: current.buildId, + currentReleaseId: current.releaseId, + activeBuildId: active.buildId, + activeReleaseId: active.releaseId, + storage: outputPorts.preferences, + }); + if (decision.action === "reload-once") { + try { + outputPorts.navigation.reload(); + } catch { + return { + action: "support" as const, + reason: "reload-failed", + }; + } + } + return decision; + } catch { + return { + action: "support" as const, + reason: "manifest-unavailable", + }; + } + }, + }); + return Object.freeze({ session, preferences, diagnostics, runtime, + recovery, }); } diff --git a/src/application/ports/in/application-api.ts b/src/application/ports/in/application-api.ts index 0d7e1082..5a79e4c0 100644 --- a/src/application/ports/in/application-api.ts +++ b/src/application/ports/in/application-api.ts @@ -38,4 +38,13 @@ export type ApplicationApi = Readonly<{ runtime: Readonly<{ getReleaseSummary(): Promise; }>; + recovery: Readonly<{ + recoverChunk(input: Readonly<{ + chunkId: string; + failureKind: "CHUNK_LOAD_FAILURE" | "DEPLOY_MISMATCH"; + }>): Promise< + | Readonly<{ action: "reload-once"; releasePair: string }> + | Readonly<{ action: "support"; reason: string }> + >; + }>; }>; diff --git a/src/application/ports/out/application-output-ports.ts b/src/application/ports/out/application-output-ports.ts index 85b44bfc..4d39fb87 100644 --- a/src/application/ports/out/application-output-ports.ts +++ b/src/application/ports/out/application-output-ports.ts @@ -15,4 +15,5 @@ export type ApplicationOutputPorts = Readonly<{ preferences: StoragePort; diagnostics: TelemetryPort; releaseInfo: ReleaseInfoPort; + navigation: Readonly<{ reload(): void }>; }>; diff --git a/src/application/ports/release-info-port.js b/src/application/ports/release-info-port.js index cb291bd1..a28a91db 100644 --- a/src/application/ports/release-info-port.js +++ b/src/application/ports/release-info-port.js @@ -9,7 +9,16 @@ * apiContractVersion: string, * assetManifestHash: string, * releaseId: string, - * builtAt?: string + * builtAt?: string, + * routeChunks: Record + * }>, + * refresh(): Promise<{ + * buildId: string, + * configSchemaVersion: string, + * apiContractVersion: string, + * assetManifestHash: string, + * releaseId: string, + * routeChunks: Record * }> * }} ReleaseInfoPort */ diff --git a/src/application/use-cases/decide-chunk-recovery.js b/src/application/use-cases/decide-chunk-recovery.js index a2db87e0..f19201fb 100644 --- a/src/application/use-cases/decide-chunk-recovery.js +++ b/src/application/use-cases/decide-chunk-recovery.js @@ -1,13 +1,21 @@ const RECOVERABLE_KINDS = new Set(["CHUNK_LOAD_FAILURE", "DEPLOY_MISMATCH"]); +/** + * @typedef {{action: "reload-once", releasePair: string} | + * {action: "support", reason: string}} ChunkRecoveryDecision + */ + /** * @param {{ * failureKind: string, * manifestLoaded: boolean, * currentBuildId: string, + * currentReleaseId: string, + * activeBuildId: string, * activeReleaseId: string, * storage: import("../ports/storage-port.js").StoragePort * }} input + * @returns {ChunkRecoveryDecision} */ export function decideChunkRecovery(input) { if (!RECOVERABLE_KINDS.has(input.failureKind)) { @@ -16,13 +24,21 @@ export function decideChunkRecovery(input) { if (!input.manifestLoaded) { return { action: "support", reason: "manifest-unavailable" }; } - if (input.activeReleaseId === input.currentBuildId) { + if ( + input.activeBuildId === input.currentBuildId && + input.activeReleaseId === input.currentReleaseId + ) { return { action: "support", reason: "same-release" }; } - const releasePair = `${input.currentBuildId}->${input.activeReleaseId}`; + const releasePair = + `${input.currentBuildId}/${input.currentReleaseId}` + + `->${input.activeBuildId}/${input.activeReleaseId}`; const guard = input.storage.read("CHUNK_RELOAD_GUARD"); - if (!guard.ok || guard.value === releasePair) { + if (!guard.ok) { + return { action: "support", reason: "guard-read-failed" }; + } + if (guard.value === releasePair) { return { action: "support", reason: "reload-already-attempted" }; } diff --git a/src/bootstrap/load-release-manifest.js b/src/bootstrap/load-release-manifest.js index aea1dcd9..e0dd7c07 100644 --- a/src/bootstrap/load-release-manifest.js +++ b/src/bootstrap/load-release-manifest.js @@ -1,7 +1,7 @@ import { z } from "zod"; const version = z.string().regex(/^\d+(?:\.\d+){0,2}$/); -const releaseManifestSchema = z +export const releaseManifestSchema = z .object({ schemaVersion: z.literal(1), appVersion: z.string().min(1), @@ -12,6 +12,7 @@ const releaseManifestSchema = z assetManifestHash: z.string().min(1), releaseId: z.string().min(1), builtAt: z.string().min(1), + routeChunks: z.record(z.string().min(1), z.string().min(1)), }) .strict(); @@ -20,7 +21,14 @@ export class ReleaseManifestError extends Error { constructor(code, safe) { super("Release manifest could not be loaded"); this.name = "ReleaseManifestError"; - this.kind = "RELEASE_MANIFEST_FAILURE"; + this.kind = + { + MANIFEST_BUILD_MISMATCH: "BUILD_MISMATCH", + MANIFEST_CONFIG_SCHEMA_MISMATCH: "CONFIG_MISMATCH", + MANIFEST_API_CONTRACT_MISMATCH: "API_CONTRACT_MISMATCH", + MANIFEST_RELEASE_MISMATCH: "RELEASE_MISMATCH", + MANIFEST_ASSET_MISMATCH: "ASSET_MISMATCH", + }[code] ?? "RELEASE_MANIFEST_FAILURE"; this.code = code; this.safe = Object.freeze({ kind: this.kind, @@ -33,75 +41,98 @@ export class ReleaseManifestError extends Error { } /** - * @param {Awaited>} runtime - * @param {{fetcher?: typeof fetch}} [options] + * Fetches and validates the active manifest without imposing the current + * build tuple. Chunk recovery uses this no-store view to detect a new release. + * + * @param {string} url + * @param {{ + * fetcher?: typeof fetch, + * buildId: string, + * releaseId?: string + * }} options */ -export async function loadReleaseManifest(runtime, options = {}) { +export async function fetchReleaseManifest(url, options) { const fetcher = options.fetcher ?? fetch; let response; try { - response = await fetcher(runtime.config.RELEASE_MANIFEST_URL, { + response = await fetcher(url, { cache: "no-store", headers: { Accept: "application/json" }, }); } catch { - throw new ReleaseManifestError("MANIFEST_FETCH_FAILED", { - buildId: runtime.build.buildId, - releaseId: runtime.config.RELEASE_ID, - }); + throw new ReleaseManifestError("MANIFEST_FETCH_FAILED", options); } if (!response.ok) { - throw new ReleaseManifestError("MANIFEST_HTTP_FAILED", { - buildId: runtime.build.buildId, - releaseId: runtime.config.RELEASE_ID, - }); + throw new ReleaseManifestError("MANIFEST_HTTP_FAILED", options); } - let raw; try { raw = await response.json(); } catch { - throw new ReleaseManifestError("MANIFEST_JSON_INVALID", { - buildId: runtime.build.buildId, - releaseId: runtime.config.RELEASE_ID, - }); + throw new ReleaseManifestError("MANIFEST_JSON_INVALID", options); } const parsed = releaseManifestSchema.safeParse(raw); if (!parsed.success) { - throw new ReleaseManifestError("MANIFEST_SCHEMA_INVALID", { + throw new ReleaseManifestError("MANIFEST_SCHEMA_INVALID", options); + } + return Object.freeze(structuredClone(parsed.data)); +} + +/** + * @param {Awaited>} runtime + * @param {{fetcher?: typeof fetch, expectedAssetManifestHash?: string}} [options] + */ +export async function loadReleaseManifest(runtime, options = {}) { + const manifest = await fetchReleaseManifest( + runtime.config.RELEASE_MANIFEST_URL, + { + fetcher: options.fetcher, buildId: runtime.build.buildId, releaseId: runtime.config.RELEASE_ID, - }); + }, + ); + let mismatchCode = null; + if (manifest.buildId !== runtime.build.buildId) { + mismatchCode = "MANIFEST_BUILD_MISMATCH"; } - - const manifest = parsed.data; - const mismatches = []; - if (manifest.buildId !== runtime.build.buildId) mismatches.push("buildId"); if ( + !mismatchCode && runtime.config.BUILD_ID && manifest.buildId !== runtime.config.BUILD_ID ) { - mismatches.push("runtimeBuildId"); + mismatchCode = "MANIFEST_BUILD_MISMATCH"; } if ( + !mismatchCode && manifest.configSchemaVersion !== runtime.config.CONFIG_SCHEMA_VERSION ) { - mismatches.push("configSchemaVersion"); - } - if (manifest.apiContractVersion !== runtime.config.API_CONTRACT_VERSION) { - mismatches.push("apiContractVersion"); + mismatchCode = "MANIFEST_CONFIG_SCHEMA_MISMATCH"; } if ( + !mismatchCode && + manifest.apiContractVersion !== runtime.config.API_CONTRACT_VERSION + ) { + mismatchCode = "MANIFEST_API_CONTRACT_MISMATCH"; + } + if ( + !mismatchCode && runtime.config.RELEASE_ID && manifest.releaseId !== runtime.config.RELEASE_ID ) { - mismatches.push("releaseId"); + mismatchCode = "MANIFEST_RELEASE_MISMATCH"; } - if (mismatches.length > 0) { - throw new ReleaseManifestError("MANIFEST_RUNTIME_MISMATCH", { + if ( + !mismatchCode && + options.expectedAssetManifestHash && + manifest.assetManifestHash !== options.expectedAssetManifestHash + ) { + mismatchCode = "MANIFEST_ASSET_MISMATCH"; + } + if (mismatchCode) { + throw new ReleaseManifestError(mismatchCode, { buildId: runtime.build.buildId, releaseId: runtime.config.RELEASE_ID, }); } - return Object.freeze(structuredClone(manifest)); + return manifest; } diff --git a/src/bootstrap/runtime-adapters.js b/src/bootstrap/runtime-adapters.js index 835b65c7..346d0525 100644 --- a/src/bootstrap/runtime-adapters.js +++ b/src/bootstrap/runtime-adapters.js @@ -9,6 +9,7 @@ import { } from "../adapters/query-cache/tanstack-query-cache.js"; import { createBrowserStorageAdapter } from "../adapters/storage/browser-storage-adapter.js"; import { createTelemetryAdapter } from "../adapters/telemetry/best-effort-telemetry.js"; +import { fetchReleaseManifest } from "./load-release-manifest.js"; /** * @param {Record} host @@ -97,6 +98,23 @@ export async function createRuntimeAdapters(context) { async getCurrent() { return structuredClone(context.release); }, + async refresh() { + return fetchReleaseManifest(config.RELEASE_MANIFEST_URL, { + fetcher: context.fetcher, + buildId: context.release.buildId, + releaseId: context.release.releaseId, + }); + }, + }); + const navigation = Object.freeze({ + reload() { + const location = + /** @type {{reload?: () => void} | undefined} */ (host.location); + if (typeof location?.reload !== "function") { + throw new Error("Browser reload is unavailable"); + } + location.reload(); + }, }); return Object.freeze({ @@ -105,6 +123,7 @@ export async function createRuntimeAdapters(context) { preferences: storage, diagnostics: telemetry, releaseInfo, + navigation, }), infrastructure: Object.freeze({ queryClient, diff --git a/src/contracts/errors.js b/src/contracts/errors.js index 8c0af286..40d924ff 100644 --- a/src/contracts/errors.js +++ b/src/contracts/errors.js @@ -111,6 +111,41 @@ export const ERROR_REGISTRY = Object.freeze({ "reload-once", "release.mismatch.detected", ), + BUILD_MISMATCH: row( + "BUILD_MISMATCH", + false, + "error", + "reload-once", + "release.mismatch.detected", + ), + CONFIG_MISMATCH: row( + "CONFIG_MISMATCH", + false, + "error", + "contact-support", + "app.boot.failed", + ), + API_CONTRACT_MISMATCH: row( + "API_CONTRACT_MISMATCH", + false, + "error", + "contact-support", + "app.boot.failed", + ), + RELEASE_MISMATCH: row( + "RELEASE_MISMATCH", + false, + "error", + "reload-once", + "release.mismatch.detected", + ), + ASSET_MISMATCH: row( + "ASSET_MISMATCH", + false, + "error", + "reload-once", + "release.mismatch.detected", + ), STORAGE_UNAVAILABLE: row( "STORAGE_UNAVAILABLE", false, diff --git a/src/contracts/route-runtime-contract.js b/src/contracts/route-runtime-contract.js new file mode 100644 index 00000000..19e149f6 --- /dev/null +++ b/src/contracts/route-runtime-contract.js @@ -0,0 +1,45 @@ +/** + * @typedef {"none" | "NotFoundSplat" | "SampleResourceListQuery"} RouteCodecId + */ + +/** @param {Readonly<{routeId: string, moduleId: string, paramsCodec: RouteCodecId, searchCodec: RouteCodecId}>} value */ +const runtime = (value) => Object.freeze(value); + +export const ROUTE_RUNTIME_CONTRACT = Object.freeze({ + APP_HOME: runtime({ + routeId: "APP_HOME", + moduleId: "home-page", + paramsCodec: "none", + searchCodec: "none", + }), + EXAMPLES_UI: runtime({ + routeId: "EXAMPLES_UI", + moduleId: "ui-gallery-page", + paramsCodec: "none", + searchCodec: "none", + }), + EXAMPLES_STATES: runtime({ + routeId: "EXAMPLES_STATES", + moduleId: "state-gallery-page", + paramsCodec: "none", + searchCodec: "none", + }), + EXAMPLES_AUTH: runtime({ + routeId: "EXAMPLES_AUTH", + moduleId: "auth-example-page", + paramsCodec: "none", + searchCodec: "none", + }), + SAMPLE_RESOURCE_LIST: runtime({ + routeId: "SAMPLE_RESOURCE_LIST", + moduleId: "sample-contract-page", + paramsCodec: "none", + searchCodec: "SampleResourceListQuery", + }), + NOT_FOUND: runtime({ + routeId: "NOT_FOUND", + moduleId: "not-found-page", + paramsCodec: "NotFoundSplat", + searchCodec: "none", + }), +}); diff --git a/src/contracts/routes.js b/src/contracts/routes.js index 32f42767..050bb06f 100644 --- a/src/contracts/routes.js +++ b/src/contracts/routes.js @@ -86,7 +86,7 @@ export const ROUTE_REGISTRY = Object.freeze({ NOT_FOUND: route({ routeId: "NOT_FOUND", path: "*", - paramsSchema: null, + paramsSchema: "NotFoundSplat", searchSchema: null, access: "public", loadingSurface: "none", diff --git a/src/presentation/boundaries/chunk-recovery-boundary.tsx b/src/presentation/boundaries/chunk-recovery-boundary.tsx new file mode 100644 index 00000000..7b47d2da --- /dev/null +++ b/src/presentation/boundaries/chunk-recovery-boundary.tsx @@ -0,0 +1,97 @@ +import { + Component, + type ErrorInfo, + type ReactNode, +} from "react"; + +type RecoveryResult = + | Readonly<{ action: "reload-once"; releasePair: string }> + | Readonly<{ action: "support"; reason: string }>; + +type Props = Readonly<{ + children: ReactNode; + chunkId: string; + recover(input: Readonly<{ + chunkId: string; + failureKind: "CHUNK_LOAD_FAILURE"; + }>): Promise; +}>; + +type State = Readonly<{ + error: unknown | null; + recovery: "idle" | "checking" | "reload-requested" | "support"; + reason?: string; +}>; + +export function isChunkLoadFailure(error: unknown): boolean { + if (!(error instanceof Error)) return false; + const value = `${error.name} ${error.message}`.toLowerCase(); + return ( + value.includes("chunkloaderror") || + value.includes("loading chunk") || + value.includes("dynamically imported module") || + value.includes("failed to fetch module script") + ); +} + +export class ChunkRecoveryBoundary extends Component { + state: State = { error: null, recovery: "idle" }; + + static getDerivedStateFromError(error: unknown): State { + return { error, recovery: "checking" }; + } + + componentDidCatch(error: unknown, _info: ErrorInfo) { + if (!isChunkLoadFailure(error)) return; + void this.props + .recover({ + chunkId: this.props.chunkId, + failureKind: "CHUNK_LOAD_FAILURE", + }) + .then((result) => { + this.setState({ + error, + recovery: + result.action === "reload-once" + ? "reload-requested" + : "support", + ...(result.action === "support" ? { reason: result.reason } : {}), + }); + }) + .catch(() => { + this.setState({ + error, + recovery: "support", + reason: "recovery-controller-failed", + }); + }); + } + + render() { + const { error, recovery, reason } = this.state; + if (error && !isChunkLoadFailure(error)) throw error; + if (error && recovery === "checking") { + return ( +
+ 새 릴리스 정보를 확인하고 있습니다. +
+ ); + } + if (error && recovery === "reload-requested") { + return ( +
+ 새 버전으로 한 번만 전환합니다. +
+ ); + } + if (error && recovery === "support") { + return ( +
+

화면 자산을 복구하지 못했습니다.

+

문제가 계속되면 배포 상태와 지원 참조 정보를 확인해 주세요.

+
+ ); + } + return this.props.children; + } +} diff --git a/src/presentation/boundaries/render-error-boundary.jsx b/src/presentation/boundaries/render-error-boundary.jsx index c10ecb81..b7ccd8a5 100644 --- a/src/presentation/boundaries/render-error-boundary.jsx +++ b/src/presentation/boundaries/render-error-boundary.jsx @@ -6,6 +6,7 @@ import { Component } from "react"; * boundaryName: string, * routeId: string, * buildId: string, + * resetKey?: string, * onRenderFailure?: (report: import("../../application/ports/in/application-api.js").RenderFailureReport) => void, * fallback?: React.ReactNode * }} RenderBoundaryProps @@ -37,6 +38,16 @@ export class RenderErrorBoundary extends Component { } } + /** @param {RenderBoundaryProps} previous */ + componentDidUpdate(previous) { + if ( + this.state.hasError && + previous.resetKey !== this.props.resetKey + ) { + this.setState({ hasError: false }); + } + } + reset = () => { this.setState({ hasError: false }); }; diff --git a/src/presentation/components/error-copy.js b/src/presentation/components/error-copy.js index 504e3af0..67b8580c 100644 --- a/src/presentation/components/error-copy.js +++ b/src/presentation/components/error-copy.js @@ -8,6 +8,11 @@ const ERROR_MESSAGES = Object.freeze({ "error.rate_limited": "요청이 많습니다. 잠시 후 다시 시도해 주세요.", "error.server_failure": "요청을 완료하지 못했습니다.", "error.chunk_load_failure": "새 화면 파일을 불러오지 못했습니다.", + "error.build_mismatch": "현재 화면과 활성 빌드가 일치하지 않습니다.", + "error.config_mismatch": "런타임 설정 버전이 현재 화면과 일치하지 않습니다.", + "error.api_contract_mismatch": "API 계약 버전이 현재 화면과 일치하지 않습니다.", + "error.release_mismatch": "현재 화면과 활성 릴리스가 일치하지 않습니다.", + "error.asset_mismatch": "화면 자산 구성이 현재 릴리스와 일치하지 않습니다.", "error.render_failure": "화면을 표시하지 못했습니다.", "error.unknown_failure": "예상하지 못한 문제가 발생했습니다.", }); diff --git a/src/presentation/components/page-header.jsx b/src/presentation/components/page-header.jsx index c930d164..1a06fa83 100644 --- a/src/presentation/components/page-header.jsx +++ b/src/presentation/components/page-header.jsx @@ -11,7 +11,6 @@ export function PageHeader({ title, description, eyebrow }) { const headingRef = useRef(/** @type {HTMLHeadingElement | null} */ (null)); useEffect(() => { - document.title = `${title} · Frontend Skeleton`; headingRef.current?.focus(); }, [title]); diff --git a/src/presentation/routes/app-router.jsx b/src/presentation/routes/app-router.jsx deleted file mode 100644 index 8aee8fa0..00000000 --- a/src/presentation/routes/app-router.jsx +++ /dev/null @@ -1,260 +0,0 @@ -import { lazy, Suspense, useState } from "react"; -import { - BrowserRouter, - Route, - Routes, - useLocation, -} from "react-router-dom"; - -import { getRoute, routePath } from "../../contracts/routes.js"; -import { RouteBoundary } from "../boundaries/render-error-boundary.jsx"; -import { AppShell } from "../layouts/app-shell.jsx"; -import { PageHeader } from "../components/page-header.jsx"; -import { useApplication } from "../providers/application-provider.js"; -import { SessionProvider, useSession } from "../providers/session-provider.jsx"; -import { ThemeProvider } from "../providers/theme-provider.jsx"; -import { decideRouteAccess } from "./navigation-policy.js"; - -const HomePage = lazy(() => import("../pages/home-page.jsx")); -const UiGalleryPage = lazy(() => import("../examples/ui-gallery-page.jsx")); -const StateGalleryPage = lazy( - () => import("../examples/state-gallery-page.jsx"), -); -const AuthExamplePage = lazy( - () => import("../examples/auth-example-page.jsx"), -); -const SampleContractPage = lazy( - () => import("../pages/sample-contract-page.jsx"), -); -const NotFoundPage = lazy(() => import("../pages/not-found-page.jsx")); - -/** @param {{ routeId: string }} props */ -function RouteLoadingSurface({ routeId }) { - const definition = getRoute(routeId); - return ( -
-
- ); -} - -function RouteFailureSurface() { - return ( -
- -
- ); -} - -/** - * @param {{ - * routeId: string, - * buildId: string, - * children: React.ReactNode - * }} props - */ -function RouteSurface({ routeId, buildId, children }) { - const { diagnostics } = useApplication(); - return ( - } - > - }> - {children} - - - ); -} - -/** - * @param {{ - * routeId: string, - * children: React.ReactNode - * }} props - */ -function ProtectedRoute({ routeId, children }) { - const location = useLocation(); - const { sessionState, beginSignIn, recover } = useSession(); - const [pending, setPending] = useState(false); - const [failed, setFailed] = useState(false); - const decision = decideRouteAccess(routeId, sessionState); - - async function continueSession() { - setPending(true); - setFailed(false); - try { - if (decision.action === "wait-for-session") { - await recover(); - } else { - await beginSignIn( - `${location.pathname}${location.search}${location.hash}`, - ); - } - } catch { - setFailed(true); - } finally { - setPending(false); - } - } - - if (decision.allowed) return children; - - if (sessionState === "integration-failed") { - return ( -
- -
- ); - } - - const recovering = decision.action === "wait-for-session"; - return ( -
- -
- -
- {failed ? ( -

- 세션 작업을 완료하지 못했습니다. -

- ) : null} -
- ); -} - -/** - * @param {{ - * routeId: string, - * buildId: string, - * children: React.ReactNode - * }} props - */ -function PublicRoute({ routeId, buildId, children }) { - return ( - - {children} - - ); -} - -/** - * @param {{ - * basename?: string, - * buildId?: string - * }} props - */ -export function AppRouter({ - basename = "/", - buildId = "local-build", -}) { - return ( - - - - - }> - - - - } - /> - - - - } - /> - - - - } - /> - - - - } - /> - - - - - - } - /> - - - - } - /> - - - - - - ); -} diff --git a/src/presentation/routes/app-router.tsx b/src/presentation/routes/app-router.tsx new file mode 100644 index 00000000..a528c81d --- /dev/null +++ b/src/presentation/routes/app-router.tsx @@ -0,0 +1,309 @@ +import { + createContext, + type ReactNode, + Suspense, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from "react"; +import { + createBrowserRouter, + RouterProvider, + type RouteObject, + useLocation, + useNavigate, + useParams, + useSearchParams, +} from "react-router-dom"; + +import { + getRoute, + ROUTE_REGISTRY, + type RouteDefinition, +} from "../../contracts/routes.js"; +import { + FeatureBoundary, + RouteBoundary, +} from "../boundaries/render-error-boundary.jsx"; +import { ChunkRecoveryBoundary } from "../boundaries/chunk-recovery-boundary.js"; +import { PageHeader } from "../components/page-header.jsx"; +import { AppShell } from "../layouts/app-shell.jsx"; +import { useApplication } from "../providers/application-provider.js"; +import { SessionProvider, useSession } from "../providers/session-provider.jsx"; +import { ThemeProvider } from "../providers/theme-provider.jsx"; +import { + createRedirectLoopGuard, + decideRouteAccess, +} from "./navigation-policy.js"; +import { + buildRouteUrl, + parseRouteInput, + type ParsedRouteInput, + type RouteId, +} from "./route-codecs.js"; +import { ROUTE_RUNTIME } from "./route-runtime.js"; + +const RouteInputContext = createContext(null); + +export function useRouteInput(): ParsedRouteInput { + const input = useContext(RouteInputContext); + if (!input) throw new Error("Registered route input is required"); + return input; +} + +function RouteLoadingSurface({ definition }: { definition: RouteDefinition }) { + return ( +
+
+ ); +} + +function RouteFailureSurface({ + definition, +}: { + definition?: RouteDefinition; +}) { + return ( +
+ +
+ ); +} + +function InvalidRouteSurface({ code }: { code: string }) { + return ( +
+ +

안전한 탐색 링크를 사용해 주세요.

+
+ ); +} + +function RouteLifecycle({ definition }: { definition: RouteDefinition }) { + const location = useLocation(); + useEffect(() => { + document.title = `${definition.title} · Frontend Skeleton`; + const main = document.getElementById("main-content"); + main?.focus({ preventScroll: true }); + try { + if (!navigator.userAgent.toLowerCase().includes("jsdom")) { + window.scrollTo({ top: 0, left: 0, behavior: "auto" }); + } + } catch { + // Non-browser test hosts may not implement scrolling. + } + }, [definition, location.key, location.pathname]); + return null; +} + +function CanonicalRouteRedirect({ + input, +}: { + input: ParsedRouteInput; +}) { + const location = useLocation(); + const navigate = useNavigate(); + const guard = useRef(createRedirectLoopGuard(3)); + useEffect(() => { + if (input.routeId === "NOT_FOUND") return; + const source = `${location.pathname}${location.search}`; + const target = buildRouteUrl(input.routeId, { + params: input.params, + search: input.search, + }); + if (source !== target && guard.current.allow(source, target)) { + void navigate(target, { replace: true }); + } + }, [input, location.pathname, location.search, navigate]); + return null; +} + +function ProtectedRoute({ + routeId, + children, +}: { + routeId: RouteId; + children: ReactNode; +}) { + const location = useLocation(); + const { sessionState, beginSignIn, recover } = useSession(); + const [pending, setPending] = useState(false); + const [failed, setFailed] = useState(false); + const decision = decideRouteAccess(routeId, sessionState); + + async function continueSession() { + setPending(true); + setFailed(false); + try { + if (decision.action === "wait-for-session") { + await recover(); + } else { + await beginSignIn( + `${location.pathname}${location.search}${location.hash}`, + ); + } + } catch { + setFailed(true); + } finally { + setPending(false); + } + } + + if (decision.allowed) return children; + if (sessionState === "integration-failed") { + return ( +
+ +
+ ); + } + const recovering = decision.action === "wait-for-session"; + return ( +
+ + + {failed ? ( +

+ 세션 작업을 완료하지 못했습니다. +

+ ) : null} +
+ ); +} + +function RegisteredRoute({ + routeId, + buildId, +}: { + routeId: RouteId; + buildId: string; +}) { + const definition = getRoute(routeId); + const runtime = ROUTE_RUNTIME[routeId]; + const params = useParams(); + const [search] = useSearchParams(); + const location = useLocation(); + const { diagnostics, recovery } = useApplication(); + const parsed = parseRouteInput(routeId, params, search); + if (!parsed.success) return ; + + const content = ( + + + + }> + + + + + + ); + const protectedContent = + definition.access === "public" ? ( + content + ) : ( + {content} + ); + const boundaryProps = { + routeId, + buildId, + resetKey: `${location.pathname}${location.search}`, + onRenderFailure: diagnostics.reportRenderFailure, + fallback: , + children: protectedContent, + }; + return definition.errorSurface === "feature-boundary" ? ( + + ) : ( + + ); +} + +function createRegisteredRoutes(buildId: string): RouteObject[] { + const children = Object.values(ROUTE_REGISTRY).map((definition) => { + const routeId = definition.routeId as RouteId; + if (definition.path === "/") { + return { + id: routeId, + index: true, + element: , + }; + } + return { + id: routeId, + path: + definition.path === "*" + ? "*" + : definition.path.replace(/^\//, ""), + element: , + }; + }); + return [ + { + id: "APP_SHELL", + path: "/", + element: , + errorElement: , + children, + }, + ]; +} + +export function AppRouter({ + basename = "/", + buildId = "local-build", +}: Readonly<{ basename?: string; buildId?: string }>) { + const router = useMemo( + () => + createBrowserRouter(createRegisteredRoutes(buildId), { + basename, + }), + [basename, buildId], + ); + return ( + + + + + + ); +} diff --git a/src/presentation/routes/navigation-policy.js b/src/presentation/routes/navigation-policy.js index 0dd3468a..51707937 100644 --- a/src/presentation/routes/navigation-policy.js +++ b/src/presentation/routes/navigation-policy.js @@ -16,8 +16,10 @@ export function decideRouteAccess(routeId, sessionState) { return { allowed: false, action: "show-sign-in" }; } -export function createRedirectLoopGuard() { +/** @param {number} [maxHops] */ +export function createRedirectLoopGuard(maxHops = 5) { const visitedPairs = new Set(); + let hops = 0; return Object.freeze({ /** @@ -26,12 +28,23 @@ export function createRedirectLoopGuard() { */ allow(source, target) { const pair = `${source}->${target}`; - if (source === target || visitedPairs.has(pair)) return false; + if ( + source === target || + visitedPairs.has(pair) || + hops >= maxHops + ) { + return false; + } visitedPairs.add(pair); + hops += 1; return true; }, reset() { visitedPairs.clear(); + hops = 0; + }, + get hopCount() { + return hops; }, }); } diff --git a/src/presentation/routes/route-codecs.ts b/src/presentation/routes/route-codecs.ts new file mode 100644 index 00000000..93761651 --- /dev/null +++ b/src/presentation/routes/route-codecs.ts @@ -0,0 +1,128 @@ +import { z } from "zod"; + +import { getRoute } from "../../contracts/routes.js"; +import { ROUTE_RUNTIME_CONTRACT } from "../../contracts/route-runtime-contract.js"; + +export type RouteId = keyof typeof ROUTE_RUNTIME_CONTRACT; + +const emptyCodec = z.object({}).strict(); +const notFoundSplatCodec = z.object({ "*": z.string().optional() }).strict(); +const sampleResourceListQuery = z + .object({ + cursor: z.string().min(1).optional(), + limit: z.coerce.number().int().min(1).max(100).default(20), + tags: z + .preprocess( + (value) => + value === undefined + ? undefined + : Array.isArray(value) + ? value + : [value], + z.array(z.string().trim().min(1)), + ) + .optional(), + }) + .strict(); + +const codecs = { + none: emptyCodec, + NotFoundSplat: notFoundSplatCodec, + SampleResourceListQuery: sampleResourceListQuery, +} as const; + +export type ParsedRouteInput = Readonly<{ + routeId: RouteId; + params: Readonly>; + search: Readonly>; +}>; + +export type RouteInputResult = + | Readonly<{ success: true; data: ParsedRouteInput }> + | Readonly<{ + success: false; + code: "ROUTE_PARAMS_INVALID" | "ROUTE_SEARCH_INVALID"; + }>; + +export function parseRouteInput( + routeId: RouteId, + rawParams: Readonly>, + rawSearch: URLSearchParams, +): RouteInputResult { + const runtime = ROUTE_RUNTIME_CONTRACT[routeId]; + const params = codecs[runtime.paramsCodec].safeParse(rawParams); + if (!params.success) { + return { success: false, code: "ROUTE_PARAMS_INVALID" }; + } + const search = codecs[runtime.searchCodec].safeParse( + searchRecord(rawSearch), + ); + if (!search.success) { + return { success: false, code: "ROUTE_SEARCH_INVALID" }; + } + const parsedParams: Record = { ...params.data }; + const parsedSearch: Record = { ...search.data }; + return { + success: true, + data: Object.freeze({ + routeId, + params: Object.freeze(parsedParams), + search: Object.freeze(parsedSearch), + }), + }; +} + +export function buildRouteUrl( + routeId: RouteId, + input: Readonly<{ + params?: Readonly>; + search?: Readonly>; + }> = {}, +): string { + const definition = getRoute(routeId); + if (definition.path === "*") { + throw new TypeError("The not-found route cannot build a canonical URL"); + } + const runtime = ROUTE_RUNTIME_CONTRACT[routeId]; + const params = codecs[runtime.paramsCodec].parse(input.params ?? {}); + const search = codecs[runtime.searchCodec].parse(input.search ?? {}); + const parsedParams: Record = { ...params }; + const parsedSearch: Record = { ...search }; + let path = definition.path; + path = path.replace( + /:([A-Za-z][A-Za-z0-9_]*)|\{([A-Za-z][A-Za-z0-9_]*)\}/g, + (_token, colonName: string | undefined, braceName: string | undefined) => { + const name = colonName ?? braceName ?? ""; + const value = parsedParams[name]; + if (typeof value !== "string" && typeof value !== "number") { + throw new TypeError(`Missing route path parameter: ${name}`); + } + return encodeURIComponent(String(value)); + }, + ); + const query = new URLSearchParams(); + for (const key of Object.keys(parsedSearch).sort((left, right) => + left.localeCompare(right), + )) { + const value = parsedSearch[key]; + if (value === undefined || value === null) continue; + for (const item of Array.isArray(value) ? value : [value]) { + query.append(key, String(item)); + } + } + const serialized = query.toString(); + return serialized ? `${path}?${serialized}` : path; +} + +function searchRecord( + search: URLSearchParams, +): Readonly> { + const result: Record = {}; + for (const key of [...new Set(search.keys())].sort((left, right) => + left.localeCompare(right), + )) { + const values = search.getAll(key); + result[key] = values.length === 1 ? values[0] : values; + } + return result; +} diff --git a/src/presentation/routes/route-runtime.tsx b/src/presentation/routes/route-runtime.tsx new file mode 100644 index 00000000..79551253 --- /dev/null +++ b/src/presentation/routes/route-runtime.tsx @@ -0,0 +1,48 @@ +import { + lazy, + type ComponentType, + type LazyExoticComponent, +} from "react"; + +import { ROUTE_RUNTIME_CONTRACT } from "../../contracts/route-runtime-contract.js"; +import type { RouteId } from "./route-codecs.js"; + +type RouteModule = Readonly<{ default: ComponentType }>; +type RouteRuntime = Readonly<{ + moduleId: string; + Component: LazyExoticComponent; +}>; + +function runtime( + routeId: RouteId, + load: () => Promise, +): RouteRuntime { + return Object.freeze({ + moduleId: ROUTE_RUNTIME_CONTRACT[routeId].moduleId, + Component: lazy(load), + }); +} + +export const ROUTE_RUNTIME = { + APP_HOME: runtime("APP_HOME", () => import("../pages/home-page.jsx")), + EXAMPLES_UI: runtime( + "EXAMPLES_UI", + () => import("../examples/ui-gallery-page.jsx"), + ), + EXAMPLES_STATES: runtime( + "EXAMPLES_STATES", + () => import("../examples/state-gallery-page.jsx"), + ), + EXAMPLES_AUTH: runtime( + "EXAMPLES_AUTH", + () => import("../examples/auth-example-page.jsx"), + ), + SAMPLE_RESOURCE_LIST: runtime( + "SAMPLE_RESOURCE_LIST", + () => import("../pages/sample-contract-page.jsx"), + ), + NOT_FOUND: runtime( + "NOT_FOUND", + () => import("../pages/not-found-page.jsx"), + ), +} satisfies Record; diff --git a/tests/component/chunk-recovery-boundary.test.tsx b/tests/component/chunk-recovery-boundary.test.tsx new file mode 100644 index 00000000..1fe7e2c3 --- /dev/null +++ b/tests/component/chunk-recovery-boundary.test.tsx @@ -0,0 +1,66 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +import { + ChunkRecoveryBoundary, + isChunkLoadFailure, +} from "../../src/presentation/boundaries/chunk-recovery-boundary.js"; +import { FeatureBoundary } from "../../src/presentation/boundaries/render-error-boundary.jsx"; + +function ChunkDefect(): never { + throw new TypeError("Failed to fetch dynamically imported module"); +} + +function RenderDefect(): never { + throw new Error("ordinary render defect"); +} + +describe("chunk recovery boundary classification", () => { + it("recognizes lazy module failures without classifying ordinary render errors", () => { + expect( + isChunkLoadFailure( + new TypeError("Failed to fetch dynamically imported module"), + ), + ).toBe(true); + expect(isChunkLoadFailure(new Error("ordinary render defect"))).toBe(false); + }); + + it("runs the recovery input only for a lazy chunk rejection", async () => { + const recover = vi.fn(async () => ({ + action: "support" as const, + reason: "reload-already-attempted", + })); + render( + + + , + ); + + expect( + await screen.findByRole("heading", { + name: "화면 자산을 복구하지 못했습니다.", + }), + ).toBeVisible(); + expect(recover).toHaveBeenCalledOnce(); + expect(recover).toHaveBeenCalledWith({ + chunkId: "route-home", + failureKind: "CHUNK_LOAD_FAILURE", + }); + }); + + it("rethrows an ordinary component defect to the local render boundary", () => { + const recover = vi.fn(); + render( + + + + + , + ); + + expect(screen.getByRole("alert")).toHaveTextContent("error.render_failure"); + expect(recover).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/component/render-boundary.test.jsx b/tests/component/render-boundary.test.jsx index f605677c..8f99b71b 100644 --- a/tests/component/render-boundary.test.jsx +++ b/tests/component/render-boundary.test.jsx @@ -91,4 +91,34 @@ describe("render recovery boundaries", () => { ); expect(screen.getByText("recovered")).toBeVisible(); }); + + it("resets a route failure when the registered location key changes", async () => { + let shouldThrow = true; + function RouteContent() { + if (shouldThrow) throw new Error("route defect"); + return

next route

; + } + const view = render( + + + , + ); + expect(screen.getByRole("alert")).toBeVisible(); + + shouldThrow = false; + view.rerender( + + + , + ); + expect(await screen.findByText("next route")).toBeVisible(); + }); }); diff --git a/tests/component/router.test.jsx b/tests/component/router.test.jsx index 69c06f05..29d1b802 100644 --- a/tests/component/router.test.jsx +++ b/tests/component/router.test.jsx @@ -2,7 +2,7 @@ import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { createAnonymousSessionAdapter, @@ -14,10 +14,13 @@ import { createTestApplication } from "../helpers/create-test-application.js"; /** * @param {import("../../src/application/ports/auth-session-port.js").AuthSessionPort} session + * @param {Parameters[0]} [overrides] */ -function renderRouter(session) { +function renderRouter(session, overrides = {}) { return render( - + , ); @@ -50,6 +53,10 @@ describe("application router", () => { await screen.findByRole("heading", { name: "UI 구성요소", level: 1 }), ).toBeVisible(); expect(window.location.pathname).toBe("/examples/ui"); + expect(document.title).toBe("UI 구성요소 · Frontend Skeleton"); + expect( + screen.getByRole("heading", { name: "UI 구성요소", level: 1 }), + ).toHaveFocus(); }); it("reacts to demo sign-in and opens the protected integration route", async () => { @@ -82,4 +89,31 @@ describe("application router", () => { screen.getByRole("heading", { name: "세션이 필요합니다." }), ).toBeVisible(); }); + + it("rejects invalid route search before any application query runs", async () => { + const getCurrent = vi.fn(async () => ({ + buildId: "test-build", + releaseId: "test-release", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "test-hash", + routeChunks: { "route-sample-resources": "assets/sample.js" }, + })); + window.history.pushState({}, "", "/sample/resources?limit=invalid"); + renderRouter(createDemoSessionAdapter("authenticated"), { + releaseInfo: { getCurrent, refresh: getCurrent }, + }); + + expect( + await screen.findByRole("heading", { + name: "올바르지 않은 주소입니다.", + }), + ).toBeVisible(); + expect(screen.getAllByRole("heading", { level: 1 })).toHaveLength(1); + expect(screen.getByText("안전한 탐색 링크를 사용해 주세요.")).toHaveAttribute( + "data-route-error", + "ROUTE_SEARCH_INVALID", + ); + expect(getCurrent).not.toHaveBeenCalled(); + }); }); diff --git a/tests/component/runtime-application.test.jsx b/tests/component/runtime-application.test.jsx index 0a2c94e0..b3bdb44b 100644 --- a/tests/component/runtime-application.test.jsx +++ b/tests/component/runtime-application.test.jsx @@ -30,6 +30,14 @@ const releaseManifest = { assetManifestHash: "test-hash", releaseId: "local-release", builtAt: "2026-07-26T00:00:00.000Z", + routeChunks: { + "route-home": "assets/home.js", + "route-examples-ui": "assets/ui.js", + "route-examples-states": "assets/states.js", + "route-examples-auth": "assets/auth.js", + "route-sample-resources": "assets/sample.js", + "route-not-found": "assets/not-found.js", + }, }; describe("production runtime application tree", () => { diff --git a/tests/fixtures/registry/routes/governance.json b/tests/fixtures/registry/routes/governance.json new file mode 100644 index 00000000..24cfa0d6 --- /dev/null +++ b/tests/fixtures/registry/routes/governance.json @@ -0,0 +1,59 @@ +{ + "schemaVersion": 1, + "sourceDirectories": [], + "registries": [ + { + "registryId": "ROUTES", + "path": "tests/fixtures/registry/routes/invalid-routes.js", + "exportName": "INVALID_ROUTES", + "owner": "fixture", + "requiredFields": [ + "routeId", + "path", + "paramsSchema", + "searchSchema", + "loadingSurface", + "errorSurface", + "chunkId" + ], + "uniqueFields": ["routeId", "path", "chunkId"], + "allowedValues": { + "paramsSchema": [null], + "searchSchema": [null], + "loadingSurface": ["app-shell"], + "errorSurface": ["route-boundary"], + "chunkId": ["route-home"] + }, + "references": [ + { + "field": "routeId", + "registryId": "RUNTIME", + "targetField": "routeId" + } + ] + }, + { + "registryId": "RUNTIME", + "path": "tests/fixtures/registry/routes/invalid-routes.js", + "exportName": "INVALID_RUNTIME", + "owner": "fixture", + "requiredFields": ["routeId", "moduleId", "paramsCodec", "searchCodec"], + "allowedValues": { + "moduleId": ["home-page"], + "paramsCodec": ["none"], + "searchCodec": ["none"] + }, + "references": [ + { + "field": "routeId", + "registryId": "ROUTES", + "targetField": "routeId" + } + ] + } + ], + "compatibilityImpact": { + "allowed": ["none", "additive", "behavior-change", "breaking"], + "current": "breaking" + } +} diff --git a/tests/fixtures/registry/routes/invalid-routes.ts b/tests/fixtures/registry/routes/invalid-routes.ts new file mode 100644 index 00000000..83741227 --- /dev/null +++ b/tests/fixtures/registry/routes/invalid-routes.ts @@ -0,0 +1,29 @@ +export const INVALID_ROUTES = { + FIRST: { + routeId: "DUPLICATE", + path: "/duplicate", + paramsSchema: "UnknownParams", + searchSchema: "UnknownSearch", + loadingSurface: "unknown-loading", + errorSurface: "unknown-error", + chunkId: "unknown-chunk", + }, + SECOND: { + routeId: "DUPLICATE", + path: "/duplicate", + paramsSchema: null, + searchSchema: null, + loadingSurface: "app-shell", + errorSurface: "route-boundary", + chunkId: "route-home", + }, +}; + +export const INVALID_RUNTIME = { + ORPHAN: { + routeId: "ORPHAN", + moduleId: "unknown-module", + paramsCodec: "none", + searchCodec: "none", + }, +}; diff --git a/tests/fixtures/typecheck/invalid-route-runtime.ts b/tests/fixtures/typecheck/invalid-route-runtime.ts new file mode 100644 index 00000000..86df3811 --- /dev/null +++ b/tests/fixtures/typecheck/invalid-route-runtime.ts @@ -0,0 +1,14 @@ +import { ROUTE_RUNTIME_CONTRACT } from "../../../src/contracts/route-runtime-contract.js"; + +type RouteId = keyof typeof ROUTE_RUNTIME_CONTRACT; + +export const missingRuntime = { + APP_HOME: true, +} satisfies Record; + +export const orphanRuntime = { + ...Object.fromEntries( + Object.keys(ROUTE_RUNTIME_CONTRACT).map((routeId) => [routeId, true]), + ), + ORPHAN_ROUTE: true, +} satisfies Record; diff --git a/tests/helpers/create-test-application.js b/tests/helpers/create-test-application.js index 6a07a147..c54f83b4 100644 --- a/tests/helpers/create-test-application.js +++ b/tests/helpers/create-test-application.js @@ -6,7 +6,8 @@ import { createApplication } from "../../src/application/create-application.js"; * session?: import("../../src/application/ports/auth-session-port.js").AuthSessionPort, * preferences?: import("../../src/application/ports/storage-port.js").StoragePort, * diagnostics?: import("../../src/application/ports/telemetry-port.js").TelemetryPort, - * releaseInfo?: import("../../src/application/ports/release-info-port.js").ReleaseInfoPort + * releaseInfo?: import("../../src/application/ports/release-info-port.js").ReleaseInfoPort, + * navigation?: { reload(): void } * }} [overrides] */ export function createTestApplication(overrides = {}) { @@ -29,7 +30,23 @@ export function createTestApplication(overrides = {}) { configSchemaVersion: "1", apiContractVersion: "1", assetManifestHash: "test-hash", + routeChunks: { + "route-home": "assets/home.js", + "route-sample-resources": "assets/sample.js", + }, + }), + refresh: async () => ({ + buildId: "test-build", + releaseId: "test-release", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "test-hash", + routeChunks: { + "route-home": "assets/home.js", + "route-sample-resources": "assets/sample.js", + }, }), }, + navigation: overrides.navigation ?? { reload: () => {} }, }); } diff --git a/tests/runtime-schema/release-manifest.test.js b/tests/runtime-schema/release-manifest.test.js index 900cdbd1..03e59875 100644 --- a/tests/runtime-schema/release-manifest.test.js +++ b/tests/runtime-schema/release-manifest.test.js @@ -25,6 +25,7 @@ const manifest = { assetManifestHash: "hash-a", releaseId: "release-a", builtAt: "2026-07-25T00:00:00Z", + routeChunks: { "route-home": "assets/home.js" }, }; describe("release manifest boot boundary", () => { @@ -46,6 +47,62 @@ describe("release manifest boot boundary", () => { new Response(JSON.stringify({ ...manifest, buildId: "build-b" })), }, ), + ).rejects.toMatchObject({ + kind: "BUILD_MISMATCH", + code: "MANIFEST_BUILD_MISMATCH", + }); + }); + + it.each([ + [ + { configSchemaVersion: "2" }, + {}, + "CONFIG_MISMATCH", + "MANIFEST_CONFIG_SCHEMA_MISMATCH", + ], + [ + { apiContractVersion: "2" }, + {}, + "API_CONTRACT_MISMATCH", + "MANIFEST_API_CONTRACT_MISMATCH", + ], + [ + { releaseId: "release-b" }, + {}, + "RELEASE_MISMATCH", + "MANIFEST_RELEASE_MISMATCH", + ], + [ + {}, + { expectedAssetManifestHash: "different" }, + "ASSET_MISMATCH", + "MANIFEST_ASSET_MISMATCH", + ], + ])( + "classifies tuple mismatch %# without a generic deploy error", + async (manifestOverride, options, kind, code) => { + await expect( + loadReleaseManifest( + /** @type {Parameters[0]} */ (runtime), + { + fetcher: async () => + Response.json({ ...manifest, ...manifestOverride }), + ...options, + }, + ), + ).rejects.toMatchObject({ kind, code }); + }, + ); + + it("rejects a manifest without a complete route chunk map", async () => { + const malformed = Object.fromEntries( + Object.entries(manifest).filter(([key]) => key !== "routeChunks"), + ); + await expect( + loadReleaseManifest( + /** @type {Parameters[0]} */ (runtime), + { fetcher: async () => Response.json(malformed) }, + ), ).rejects.toBeInstanceOf(ReleaseManifestError); }); }); diff --git a/tests/unit/application-boundary.test.ts b/tests/unit/application-boundary.test.ts index bfaf94d6..30e5628a 100644 --- a/tests/unit/application-boundary.test.ts +++ b/tests/unit/application-boundary.test.ts @@ -15,6 +15,7 @@ describe("application input/output boundary", () => { "preferences", "diagnostics", "runtime", + "recovery", ]); expect(application).not.toHaveProperty("storage"); expect(application).not.toHaveProperty("telemetry"); @@ -51,8 +52,18 @@ describe("application input/output boundary", () => { configSchemaVersion: "1", apiContractVersion: "1", assetManifestHash: "hash-a", + routeChunks: { "route-home": "assets/home.js" }, + }), + refresh: async () => ({ + buildId: "build-a", + releaseId: "release-a", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "hash-a", + routeChunks: { "route-home": "assets/home.js" }, }), }, + navigation: { reload: () => {} }, } satisfies ApplicationOutputPorts; const application = createApplication(ports); diff --git a/tests/unit/chunk-recovery-runtime.test.ts b/tests/unit/chunk-recovery-runtime.test.ts new file mode 100644 index 00000000..dda1a6d8 --- /dev/null +++ b/tests/unit/chunk-recovery-runtime.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it, vi } from "vitest"; + +import { createApplication } from "../../src/application/create-application.js"; +import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.js"; +import type { StoragePort } from "../../src/application/ports/storage-port.js"; + +type ReleaseFixture = { + buildId: string; + releaseId: string; + configSchemaVersion: string; + apiContractVersion: string; + assetManifestHash: string; + routeChunks: Record; +}; + +function release(buildId: string, releaseId: string): ReleaseFixture { + return { + buildId, + releaseId, + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: `${buildId}-assets`, + routeChunks: { "route-home": `assets/${buildId}-home.js` }, + }; +} + +function memoryStorage(): StoragePort { + let value: unknown; + return { + read: () => ({ ok: true, value }), + write: (_name, next) => { + value = next; + return { ok: true }; + }, + remove: () => ({ ok: true }), + }; +} + +function applicationWith(options: { + storage?: StoragePort; + refresh?: () => Promise>; + reload?: () => void; +}) { + const current = release("build-a", "release-a"); + return createApplication({ + session: createAnonymousSessionAdapter(), + preferences: options.storage ?? memoryStorage(), + diagnostics: { emit: () => {} }, + releaseInfo: { + getCurrent: async () => current, + refresh: + options.refresh ?? + (async () => release("build-b", "release-b")), + }, + navigation: { reload: options.reload ?? (() => {}) }, + }); +} + +describe("production chunk recovery application input", () => { + it("reloads exactly once for one active build/release pair", async () => { + const reload = vi.fn(); + const application = applicationWith({ reload }); + const input = { + chunkId: "route-home", + failureKind: "CHUNK_LOAD_FAILURE" as const, + }; + + await expect(application.recovery.recoverChunk(input)).resolves.toEqual({ + action: "reload-once", + releasePair: "build-a/release-a->build-b/release-b", + }); + await expect(application.recovery.recoverChunk(input)).resolves.toEqual({ + action: "support", + reason: "reload-already-attempted", + }); + expect(reload).toHaveBeenCalledOnce(); + }); + + it.each([ + [ + { + refresh: async () => { + throw new Error("offline"); + }, + }, + "manifest-unavailable", + ], + [ + { + refresh: async () => ({ + ...release("build-b", "release-b"), + routeChunks: {}, + }), + }, + "active-chunk-unknown", + ], + [ + { + storage: { + read: () => ({ + ok: false as const, + error: { + kind: "STORAGE_UNAVAILABLE", + code: "STORAGE_UNAVAILABLE", + retryable: false, + operationId: "STORAGE", + attemptCount: 1, + userMessageKey: "error.storage_unavailable", + action: "none" as const, + }, + }), + write: () => ({ ok: true as const }), + remove: () => ({ ok: true as const }), + }, + }, + "guard-read-failed", + ], + ])("fails closed for recovery dependency case %#", async (options, reason) => { + const reload = vi.fn(); + const application = applicationWith({ ...options, reload }); + await expect( + application.recovery.recoverChunk({ + chunkId: "route-home", + failureKind: "CHUNK_LOAD_FAILURE", + }), + ).resolves.toEqual({ action: "support", reason }); + expect(reload).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/chunk-recovery.test.js b/tests/unit/chunk-recovery.test.js index 66b6c0b6..703a81dc 100644 --- a/tests/unit/chunk-recovery.test.js +++ b/tests/unit/chunk-recovery.test.js @@ -22,12 +22,14 @@ describe("controlled chunk recovery", () => { failureKind: "CHUNK_LOAD_FAILURE", manifestLoaded: true, currentBuildId: "build-a", + currentReleaseId: "release-a", + activeBuildId: "build-b", activeReleaseId: "release-b", storage, }; expect(decideChunkRecovery(input)).toEqual({ action: "reload-once", - releasePair: "build-a->release-b", + releasePair: "build-a/release-a->build-b/release-b", }); expect(decideChunkRecovery(input)).toEqual({ action: "support", @@ -38,12 +40,17 @@ describe("controlled chunk recovery", () => { it.each([ [{ failureKind: "SERVER_FAILURE" }, "not-recoverable"], [{ manifestLoaded: false }, "manifest-unavailable"], - [{ activeReleaseId: "build-a" }, "same-release"], + [ + { activeBuildId: "build-a", activeReleaseId: "release-a" }, + "same-release", + ], ])("stops when a recovery invariant fails: %#", (override, reason) => { const result = decideChunkRecovery({ failureKind: "DEPLOY_MISMATCH", manifestLoaded: true, currentBuildId: "build-a", + currentReleaseId: "release-a", + activeBuildId: "build-b", activeReleaseId: "release-b", storage: memoryStorage(), ...override, diff --git a/tests/unit/error-classification.test.js b/tests/unit/error-classification.test.js index 600ba64e..2a44a8b4 100644 --- a/tests/unit/error-classification.test.js +++ b/tests/unit/error-classification.test.js @@ -9,7 +9,7 @@ import { describe("frontend failure classification", () => { it("defines all 26 stable error kinds with the seven contract fields", () => { - expect(Object.keys(ERROR_REGISTRY)).toHaveLength(26); + expect(Object.keys(ERROR_REGISTRY)).toHaveLength(31); for (const definition of Object.values(ERROR_REGISTRY)) { expect(definition).toEqual( expect.objectContaining({ diff --git a/tests/unit/navigation-policy.test.js b/tests/unit/navigation-policy.test.js index 4ea27a3f..d2354814 100644 --- a/tests/unit/navigation-policy.test.js +++ b/tests/unit/navigation-policy.test.js @@ -72,7 +72,7 @@ describe("route registry", () => { "loadingSurface": "none", "navigationLabel": null, "navigationOrder": null, - "paramsSchema": null, + "paramsSchema": "NotFoundSplat", "path": "*", "routeId": "NOT_FOUND", "searchSchema": null, @@ -121,9 +121,12 @@ describe("route registry", () => { }); it("allows at most one automatic redirect per source-target pair", () => { - const guard = createRedirectLoopGuard(); + const guard = createRedirectLoopGuard(2); expect(guard.allow("/private", "/signin")).toBe(true); expect(guard.allow("/private", "/signin")).toBe(false); expect(guard.allow("/signin", "/signin")).toBe(false); + expect(guard.allow("/signin", "/continue")).toBe(true); + expect(guard.allow("/continue", "/final")).toBe(false); + expect(guard.hopCount).toBe(2); }); }); diff --git a/tests/unit/registry-governance.test.js b/tests/unit/registry-governance.test.js index fa9a5539..5f7a8d33 100644 --- a/tests/unit/registry-governance.test.js +++ b/tests/unit/registry-governance.test.js @@ -2,7 +2,7 @@ import { readFile } from "node:fs/promises"; import { describe, expect, it } from "vitest"; describe("registry governance manifest", () => { - it("declares exactly eight single-owner registries and impact labels", async () => { + it("declares exactly nine single-owner registries and impact labels", async () => { const governance = JSON.parse( await readFile("config/contracts/registry-governance.json", "utf8"), ); @@ -10,9 +10,9 @@ describe("registry governance manifest", () => { /** @type {Array<{registryId: string, owner: string}>} */ ( governance.registries ); - expect(governance.registries).toHaveLength(8); + expect(governance.registries).toHaveLength(9); expect(new Set(registries.map((entry) => entry.registryId)).size).toBe( - 8, + 9, ); expect(registries.every((entry) => entry.owner)).toBe(true); expect(governance.compatibilityImpact.allowed).toEqual([ diff --git a/tests/unit/route-runtime.test.ts b/tests/unit/route-runtime.test.ts new file mode 100644 index 00000000..b1285c55 --- /dev/null +++ b/tests/unit/route-runtime.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from "vitest"; + +import { ROUTE_RUNTIME_CONTRACT } from "../../src/contracts/route-runtime-contract.js"; +import { ROUTE_REGISTRY } from "../../src/contracts/routes.js"; +import { + buildRouteUrl, + parseRouteInput, +} from "../../src/presentation/routes/route-codecs.js"; +import { ROUTE_RUNTIME } from "../../src/presentation/routes/route-runtime.js"; + +describe("typed route contract and runtime", () => { + it("keeps contract, runtime contribution, and executable module complete", () => { + expect(Object.keys(ROUTE_RUNTIME_CONTRACT).sort()).toEqual( + Object.keys(ROUTE_REGISTRY).sort(), + ); + expect(Object.keys(ROUTE_RUNTIME).sort()).toEqual( + Object.keys(ROUTE_REGISTRY).sort(), + ); + }); + + it("round-trips canonical search through the registered codec", () => { + const url = buildRouteUrl("SAMPLE_RESOURCE_LIST", { + search: { + tags: ["open", "new"], + cursor: "a/b", + limit: 5, + }, + }); + expect(url).toBe( + "/sample/resources?cursor=a%2Fb&limit=5&tags=open&tags=new", + ); + const parsedUrl = new URL(url, "https://app.test"); + expect( + parseRouteInput( + "SAMPLE_RESOURCE_LIST", + {}, + parsedUrl.searchParams, + ), + ).toEqual({ + success: true, + data: { + routeId: "SAMPLE_RESOURCE_LIST", + params: {}, + search: { + cursor: "a/b", + limit: 5, + tags: ["open", "new"], + }, + }, + }); + }); + + it("rejects unknown search and accepts the not-found splat owner", () => { + expect( + parseRouteInput( + "SAMPLE_RESOURCE_LIST", + {}, + new URLSearchParams("unknown=value"), + ), + ).toEqual({ success: false, code: "ROUTE_SEARCH_INVALID" }); + expect( + parseRouteInput( + "NOT_FOUND", + { "*": "missing/path" }, + new URLSearchParams(), + ), + ).toMatchObject({ success: true }); + }); +}); diff --git a/tests/unit/runtime-adapters.test.js b/tests/unit/runtime-adapters.test.js index 3e4f39aa..d57e3a1c 100644 --- a/tests/unit/runtime-adapters.test.js +++ b/tests/unit/runtime-adapters.test.js @@ -13,6 +13,7 @@ const runtime = { AUTH_MODE: "demo", REQUEST_TIMEOUT_MS: 4321, MAX_RETRY_ATTEMPTS: 0, + RELEASE_MANIFEST_URL: "/release-manifest.json", }, }; const release = /** @type {const} */ ({ @@ -25,6 +26,7 @@ const release = /** @type {const} */ ({ assetManifestHash: "hash-a", releaseId: "release-a", builtAt: "2026-07-25T00:00:00Z", + routeChunks: { "route-home": "assets/home.js" }, }); describe("runtime adapter composition", () => { @@ -59,6 +61,34 @@ describe("runtime adapter composition", () => { expect(adapters.outputPorts.session.getState()).toBe("integration-failed"); }); + it("refetches the active release manifest with no-store semantics", async () => { + const activeRelease = { + ...release, + buildId: "build-b", + releaseId: "release-b", + routeChunks: { "route-home": "assets/home-b.js" }, + }; + const fetcher = vi.fn(async () => Response.json(activeRelease)); + const adapters = await createRuntimeAdapters({ + runtime: + /** @type {Parameters[0]["runtime"]} */ ( + runtime + ), + release, + fetcher, + host: {}, + }); + + await expect(adapters.outputPorts.releaseInfo.refresh()).resolves.toMatchObject({ + buildId: "build-b", + releaseId: "release-b", + }); + expect(fetcher).toHaveBeenCalledWith("/release-manifest.json", { + cache: "no-store", + headers: { Accept: "application/json" }, + }); + }); + it("injects runtime timeout and max-attempt policy into HTTP execution", async () => { const scheduled = /** @type {Array<{callback: () => void, milliseconds: number}>} */ ([]); From c11be43f20140955339cdd1256a9d32cbc4f9602 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sun, 26 Jul 2026 14:56:34 +0900 Subject: [PATCH 051/178] feat: add removable reference feature vertical slice --- .dependency-cruiser.cjs | 34 ++- ...RCE_LIST.md => REFERENCE_RESOURCE_LIST.md} | 2 +- config/ci/gates.json | 14 +- config/contracts/registry-governance.json | 18 +- docs/accessibility/manual-checklist.md | 2 +- .../frontend-platform-capability-review.md | 35 +-- .../frontend-ports-adapters-and-boundaries.md | 23 +- docs/architecture/overview.md | 5 +- .../routing-pages-and-patterns.md | 4 +- docs/architecture/starter-experience.md | 24 +- docs/styling/design-tokens.md | 5 +- .../frontend-platform-testing-strategy.md | 8 + eslint.config.js | 56 +++++ package.json | 3 +- public/release-manifest.json | 2 +- scripts/generate-build-manifest.mjs | 6 +- scripts/lib/manual-a11y-evidence.mjs | 13 +- scripts/test-performance.mjs | 7 +- scripts/test-sample-removal.mjs | 230 +++++++++++++---- scripts/verify-release.mjs | 6 +- src/adapters/http/client.js | 6 +- src/adapters/http/resource-mapper.js | 27 +- src/adapters/http/schema-registry.js | 28 +-- src/application/create-application.ts | 14 ++ src/application/ports/in/application-api.ts | 4 + src/application/ports/out/index.ts | 6 - src/application/ports/resource-ports.js | 28 --- .../view-models/resource-view-model.js | 16 -- src/bootstrap/composition-root.js | 8 +- src/bootstrap/runtime-adapters.js | 16 +- src/contracts/api-operations.js | 36 +-- src/contracts/query-keys.js | 24 +- src/contracts/route-runtime-contract.js | 10 +- src/contracts/routes.js | 40 +-- src/domain/models/resource.js | 19 -- src/features/installed-feature-adapters.ts | 15 ++ src/features/installed-feature-contracts.js | 48 ++++ src/features/installed-feature-runtimes.tsx | 16 ++ src/features/reference-feature/README.md | 39 +++ .../create-reference-feature-input.ts | 43 ++++ .../adapters/reference-http-gateway.ts | 56 +++++ .../application/reference-feature-api.ts | 58 +++++ .../contracts/reference-feature-contract.js | 75 ++++++ .../contracts/reference-mapper.ts | 54 ++++ .../contracts/reference-schemas.ts | 67 +++++ .../domain/reference-resource.ts | 14 ++ .../reference-feature-runtime.tsx | 14 ++ .../presentation/reference-resource-page.tsx | 60 +++++ .../presentation/use-reference-feature.ts | 62 +++++ src/presentation/layouts/app-shell.jsx | 5 +- src/presentation/pages/home-page.jsx | 2 +- src/presentation/pages/not-found-page.jsx | 2 +- .../pages/sample-contract-page.jsx | 23 -- src/presentation/routes/app-router.tsx | 6 +- src/presentation/routes/navigation-policy.js | 2 +- .../routes/platform-route-codecs.ts | 6 + src/presentation/routes/route-codecs.ts | 52 ++-- src/presentation/routes/route-runtime.tsx | 15 +- .../design-token-showcase.jsx | 15 -- src/sample/contract-fixture/sample-facade.js | 53 ---- .../contract-fixture/sample-resource-page.jsx | 61 ----- tests/component/design-tokens.test.jsx | 11 +- tests/component/router.test.jsx | 85 +------ tests/component/runtime-application.test.jsx | 1 - tests/component/sample-resource-page.test.jsx | 70 ------ tests/e2e/accessibility.spec.js | 12 +- tests/e2e/app-shell.spec.js | 9 +- .../reference-contract.test.ts | 94 +++++++ .../reference-feature/reference-page.test.tsx | 234 ++++++++++++++++++ .../reference-production-vertical.test.tsx | 129 ++++++++++ .../typecheck/invalid-route-runtime.ts | 2 +- tests/helpers/create-test-application.js | 80 +++--- tests/helpers/http-contract-fixture.ts | 108 ++++++++ tests/integration/auth-recovery.test.js | 20 +- tests/integration/http-client.test.js | 34 +-- .../http-execution-contract.test.js | 62 +++-- .../integration/sample-vertical-slice.test.js | 53 ---- tests/runtime-schema/http-schema.test.js | 55 ++-- tests/unit/application-boundary.test.ts | 5 + tests/unit/boundary-mapper.test.js | 47 +--- tests/unit/error-classification.test.js | 2 +- tests/unit/manual-a11y-evidence.test.js | 2 +- tests/unit/navigation-policy.test.js | 123 ++------- tests/unit/query-cache.test.js | 23 +- tests/unit/route-runtime.test.ts | 56 +---- tests/unit/runtime-adapters.test.js | 34 +-- tests/unit/telemetry.test.js | 2 +- 87 files changed, 1881 insertions(+), 1114 deletions(-) rename artifacts/tests/a11y-manual/{SAMPLE_RESOURCE_LIST.md => REFERENCE_RESOURCE_LIST.md} (92%) delete mode 100644 src/application/ports/resource-ports.js delete mode 100644 src/application/view-models/resource-view-model.js delete mode 100644 src/domain/models/resource.js create mode 100644 src/features/installed-feature-adapters.ts create mode 100644 src/features/installed-feature-contracts.js create mode 100644 src/features/installed-feature-runtimes.tsx create mode 100644 src/features/reference-feature/README.md create mode 100644 src/features/reference-feature/adapters/create-reference-feature-input.ts create mode 100644 src/features/reference-feature/adapters/reference-http-gateway.ts create mode 100644 src/features/reference-feature/application/reference-feature-api.ts create mode 100644 src/features/reference-feature/contracts/reference-feature-contract.js create mode 100644 src/features/reference-feature/contracts/reference-mapper.ts create mode 100644 src/features/reference-feature/contracts/reference-schemas.ts create mode 100644 src/features/reference-feature/domain/reference-resource.ts create mode 100644 src/features/reference-feature/presentation/reference-feature-runtime.tsx create mode 100644 src/features/reference-feature/presentation/reference-resource-page.tsx create mode 100644 src/features/reference-feature/presentation/use-reference-feature.ts delete mode 100644 src/presentation/pages/sample-contract-page.jsx create mode 100644 src/presentation/routes/platform-route-codecs.ts delete mode 100644 src/sample/contract-fixture/design-token-showcase.jsx delete mode 100644 src/sample/contract-fixture/sample-facade.js delete mode 100644 src/sample/contract-fixture/sample-resource-page.jsx delete mode 100644 tests/component/sample-resource-page.test.jsx create mode 100644 tests/features/reference-feature/reference-contract.test.ts create mode 100644 tests/features/reference-feature/reference-page.test.tsx create mode 100644 tests/features/reference-feature/reference-production-vertical.test.tsx create mode 100644 tests/helpers/http-contract-fixture.ts delete mode 100644 tests/integration/sample-vertical-slice.test.js diff --git a/.dependency-cruiser.cjs b/.dependency-cruiser.cjs index b1062d37..9fd4fdba 100644 --- a/.dependency-cruiser.cjs +++ b/.dependency-cruiser.cjs @@ -29,10 +29,42 @@ module.exports = { from: { path: "^src/adapters" }, to: { path: "^src/(presentation|bootstrap)" }, }, + { + name: "feature-domain-is-framework-neutral", + severity: "error", + from: { path: "^src/features/[^/]+/domain" }, + to: { + path: "^(src/(application|presentation|adapters|bootstrap)|src/features/[^/]+/(application|adapters|presentation)|react|react-dom|@tanstack)", + }, + }, + { + name: "feature-application-does-not-know-runtime", + severity: "error", + from: { path: "^src/features/[^/]+/application" }, + to: { + path: "^(src/(presentation|adapters|bootstrap)|src/features/[^/]+/(adapters|presentation)|react|react-dom|@tanstack)", + }, + }, + { + name: "feature-presentation-does-not-know-outbound-adapters", + severity: "error", + from: { path: "^src/features/[^/]+/presentation" }, + to: { + path: "^(src/(adapters|bootstrap)|src/features/[^/]+/adapters|@tanstack)", + }, + }, + { + name: "feature-adapters-do-not-know-presentation", + severity: "error", + from: { path: "^src/features/[^/]+/adapters" }, + to: { + path: "^(src/(presentation|bootstrap)|src/features/[^/]+/presentation)", + }, + }, { name: "concrete-adapters-compose-only-in-bootstrap", severity: "error", - from: { path: "^src/(domain|application|presentation|contracts|sample)" }, + from: { path: "^src/(domain|application|presentation|contracts)" }, to: { path: "^src/adapters" }, }, { diff --git a/artifacts/tests/a11y-manual/SAMPLE_RESOURCE_LIST.md b/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_LIST.md similarity index 92% rename from artifacts/tests/a11y-manual/SAMPLE_RESOURCE_LIST.md rename to artifacts/tests/a11y-manual/REFERENCE_RESOURCE_LIST.md index 5e160e8e..dede1df3 100644 --- a/artifacts/tests/a11y-manual/SAMPLE_RESOURCE_LIST.md +++ b/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_LIST.md @@ -1,7 +1,7 @@ # SAMPLE_RESOURCE_LIST accessibility review Status: pending-manual-review -Route ID: SAMPLE_RESOURCE_LIST +Route ID: REFERENCE_RESOURCE_LIST Release ID: Reviewer: Reviewed at: diff --git a/config/ci/gates.json b/config/ci/gates.json index 79d66783..8104985f 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -109,9 +109,15 @@ }, "FE-GATE-007": { "name": "integration", - "steps": [{ "script": "test:integration", "expect": "pass" }], + "steps": [ + { "script": "test:integration", "expect": "pass" }, + { "script": "test:reference-feature", "expect": "pass" } + ], "logPath": "artifacts/quality/gates/FE-GATE-007.txt", - "evidence": ["artifacts/tests/integration.xml"], + "evidence": [ + "artifacts/tests/integration.xml", + "artifacts/tests/reference-feature.xml" + ], "retentionClass": "merge-cycle" }, "FE-GATE-008": { @@ -134,7 +140,7 @@ "artifacts/tests/a11y-manual/EXAMPLES_UI.md", "artifacts/tests/a11y-manual/EXAMPLES_STATES.md", "artifacts/tests/a11y-manual/EXAMPLES_AUTH.md", - "artifacts/tests/a11y-manual/SAMPLE_RESOURCE_LIST.md", + "artifacts/tests/a11y-manual/REFERENCE_RESOURCE_LIST.md", "artifacts/tests/a11y-manual/NOT_FOUND.md", "artifacts/tests/a11y-manual/report.json" ], @@ -256,7 +262,7 @@ "retentionClass": "release-coherence" }, "FE-GATE-020": { - "name": "sample-removal", + "name": "reference-feature-removal", "steps": [{ "script": "test:sample-removal", "expect": "pass" }], "logPath": "artifacts/quality/gates/FE-GATE-020.txt", "evidence": ["artifacts/tests/sample-removal.xml"], diff --git a/config/contracts/registry-governance.json b/config/contracts/registry-governance.json index 36afe186..ed7db138 100644 --- a/config/contracts/registry-governance.json +++ b/config/contracts/registry-governance.json @@ -3,17 +3,17 @@ "registries": [ { "registryId": "FE-REG-ROUTE", - "path": "src/contracts/routes.js", + "path": "src/features/installed-feature-contracts.js", "exportName": "ROUTE_REGISTRY", "owner": "feature-routing-navigation-guard-contract", "uniqueFields": ["routeId", "path", "chunkId"], "allowedValues": { "paramsSchema": [null, "NotFoundSplat"], - "searchSchema": [null, "SampleResourceListQuery"], + "searchSchema": [null, "ReferenceResourceListQuery"], "loadingSurface": [ "app-shell", "example-page", - "sample-resource-list", + "reference-resource-list", "none" ], "errorSurface": [ @@ -26,7 +26,7 @@ "route-examples-ui", "route-examples-states", "route-examples-auth", - "route-sample-resources", + "route-reference-resources", "route-not-found" ] }, @@ -50,7 +50,7 @@ }, { "registryId": "FE-REG-ROUTE-RUNTIME", - "path": "src/contracts/route-runtime-contract.js", + "path": "src/features/installed-feature-contracts.js", "exportName": "ROUTE_RUNTIME_CONTRACT", "owner": "feature-frontend-routing-release-recovery-runtime", "requiredFields": [ @@ -66,11 +66,11 @@ "ui-gallery-page", "state-gallery-page", "auth-example-page", - "sample-contract-page", + "reference-resource-page", "not-found-page" ], "paramsCodec": ["none", "NotFoundSplat"], - "searchCodec": ["none", "SampleResourceListQuery"] + "searchCodec": ["none", "ReferenceResourceListQuery"] }, "references": [ { @@ -82,7 +82,7 @@ }, { "registryId": "FE-REG-API", - "path": "src/contracts/api-operations.js", + "path": "src/features/installed-feature-contracts.js", "exportName": "API_OPERATIONS", "owner": "feature-api-client-response-envelope-contract", "requiredFields": [ @@ -139,7 +139,7 @@ }, { "registryId": "FE-REG-QUERY", - "path": "src/contracts/query-keys.js", + "path": "src/features/installed-feature-contracts.js", "exportName": "QUERY_REGISTRY", "owner": "feature-server-state-caching-contract", "requiredFields": [ diff --git a/docs/accessibility/manual-checklist.md b/docs/accessibility/manual-checklist.md index 3ebfe3a8..6bfac322 100644 --- a/docs/accessibility/manual-checklist.md +++ b/docs/accessibility/manual-checklist.md @@ -4,7 +4,7 @@ Automated axe checks do not establish WCAG conformance. A human reviewer must review all six route records in `artifacts/tests/a11y-manual/` against one release candidate and sign them. The required scope is derived from the route registry: `APP_HOME`, `EXAMPLES_UI`, `EXAMPLES_STATES`, `EXAMPLES_AUTH`, -`SAMPLE_RESOURCE_LIST`, and `NOT_FOUND`. Copy the template fields exactly; the +`REFERENCE_RESOURCE_LIST`, and `NOT_FOUND`. Copy the template fields exactly; the gate rejects blank identity/timestamp/signature fields, pending verdicts, mismatched release IDs, or missing routes. diff --git a/docs/architecture/frontend-platform-capability-review.md b/docs/architecture/frontend-platform-capability-review.md index baac965c..96cd248a 100644 --- a/docs/architecture/frontend-platform-capability-review.md +++ b/docs/architecture/frontend-platform-capability-review.md @@ -33,14 +33,13 @@ 특히 다음은 선행 해결이 필요하다. -RP-01~RP-04에서 TypeScript 도구 안전망, application runtime 주입, +RP-01~RP-05에서 TypeScript 도구 안전망, application runtime 주입, query/mutation inbound adapter, HTTP 실행 계약과 executable route/release -recovery 계약은 구현됐다. 현재 선행 해결 +recovery 계약, 제거 가능한 reference 수직 슬라이스는 구현됐다. 현재 선행 해결 대상은 다음과 같다. -1. 전체를 제거할 수 있는 실제 reference feature -2. 폼, 페이지 템플릿, 확장된 디자인 시스템과 컴포넌트 워크벤치 -3. 국제화, diagnostics, optional adapter recipe와 심화 품질 게이트 +1. 폼, 페이지 템플릿, 확장된 디자인 시스템과 컴포넌트 워크벤치 +2. 국제화, diagnostics, optional adapter recipe와 심화 품질 게이트 따라서 현재 상태를 “프론트 공통부가 모두 구현됐다”고 표현하면 범위가 과장된다. 더 정확한 표현은 다음과 같다. @@ -70,7 +69,7 @@ recovery 계약은 구현됐다. 현재 선행 해결 | 오류 모델 | 부분 준비 | error registry와 normalization 존재 | typed discriminated union과 계층별 mapper | | 검증 | 부분 준비 | runtime/API Zod parse 결과를 실제 request에 사용 | route/form/domain 경계를 추가 | | 인증 연동 | 준비됨/프로젝트 선택 | opaque auth owner와 demo seam 존재 | 인증 방식별 recipe; 기본 token 저장소는 추가하지 않음 | -| 서버 상태 | 부분 준비 | 제한된 query/mutation bridge와 lifecycle test | RP-05 reference route에서 실제 feature 연결 | +| 서버 상태 | 준비됨 | reference route의 query/mutation, cancellation, stale, optimistic/conflict/rollback | feature별 query contribution recipe 유지 | | 클라이언트 상태 | 부분 준비 | local state, theme context, session external store | 상태 소유권 표와 typed external-store 예제 | | 범용 global store | 프로젝트 선택 | 별도 라이브러리 없음 | 필요 조건에 따라 Zustand/Redux Toolkit/state machine 선택 | | 라우팅 | 준비됨 | Data Router, typed runtime map, codec, metadata consumer, bounded chunk recovery | reference feature route와 release E2E로 사용 범위 확장 | @@ -86,7 +85,7 @@ recovery 계약은 구현됐다. 현재 선행 해결 | 비동기 상태 불변식 | 준비됨 | 배타적 typed overlay, stale latch, 실제 retry/conflict action | reference 화면에서 전체 상태 전시 | | 단위·통합·E2E | 준비됨 | Vitest, RTL, MSW, Playwright 3엔진 | TS 테스트 검사, 실제 bootstrap 통합, 위험 시나리오 보강 | | UI 회귀 검증 | 미제공 | axe/reflow는 있으나 visual baseline 없음 | Storybook 또는 동급 workshop과 시각 회귀 | -| 샘플 제거 | 부분 준비 | fixture 제거 테스트 존재 | sample domain/registry/runtime 전체 제거 검증 | +| 샘플 제거 | 준비됨 | feature/catalog/test 제거 후 type/architecture/registry/test/home/build 8단계 검증 | 새 contribution도 같은 제거 gate에 포함 | | registry·compatibility 집행 | 부분 준비 | registry와 gate는 있으나 실제 before/after 및 orphan 검사가 제한적 | type/reference/orphan/diff/migration을 자동 검증 | | 공급망 검사 | 부분 준비 | lockfile·문서·gate는 있으나 실제 transitive 취약점/license/SBOM 깊이가 부족 | pinned scanner와 policy exception/증적 연결 | | realtime·offline·file 등 | 프로젝트 선택 | 현재 없음 | port/adapter recipe와 선택 기준 제공 | @@ -159,8 +158,8 @@ timeout, retry, decoder, mapper 책임을 분리해야 한다. application에는 #### RP-04에서 route registry를 실행 계약으로 전환 -`src/contracts/routes.js`와 직렬화 가능한 -`src/contracts/route-runtime-contract.js`를 기준으로 +platform route 계약과 `src/features/installed-feature-contracts.js`의 직렬화 +가능한 contribution을 기준으로 `src/presentation/routes/app-router.tsx`가 Data Router route object와 navigation을 생성한다. `route-runtime.tsx`는 lazy component의 실행 map만 소유하며 contract/runtime 누락과 orphan은 TypeScript negative fixture와 registry @@ -179,16 +178,18 @@ gate가 모두 거절한다. 연결하고, no-store manifest 재조회와 build/release 쌍별 1회 reload를 production application input까지 연결한다. -#### reference feature가 완전히 제거되지 않는다 +#### RP-05에서 제거 가능한 reference feature 구현 -현재 sample removal gate는 `src/sample/contract-fixture`만 삭제한다. sample API -operation, schema, mapper, domain model, query key는 다른 production 경로에 남는다. -반면 화면에 노출된 `/sample/resources`는 실제 query 수직 흐름을 실행하지 않는다. +`src/features/reference-feature`가 domain, application input, outbound gateway, +DTO/schema, mapper, route/API/query contract, query/mutation controller와 page를 +한 소유 경계에 둔다. production composition은 generic feature input catalog를 +통해 이 input을 주입하며 UI는 HTTP나 output port를 직접 보지 않는다. -reference feature는 domain, application input/output, schemas, operation, -mapper, query controller, pages, tests를 한 소유 경계 아래 모아야 한다. 해당 모듈과 -registry contribution을 제거한 뒤 typecheck, architecture, test, build가 모두 -통과해야 “제거 가능”으로 판정한다. +`test:sample-removal`은 임시 복제본에서 feature source/tests를 삭제하고 installed +contract/runtime/adapter catalog를 빈 목록으로 재생성한다. 그 뒤 typecheck, +architecture, registry, unit/integration, home smoke, build와 fixture ID 잔여 +0개를 검사한다. 설치 모드에서는 MSW를 사용한 bootstrap → router → application +→ HTTP → schema → mapper → query cache → page 수직 테스트가 실행된다. #### 비동기·복구 상태의 불변식이 닫혀 있지 않다 diff --git a/docs/architecture/frontend-ports-adapters-and-boundaries.md b/docs/architecture/frontend-ports-adapters-and-boundaries.md index fa86802c..39ee0463 100644 --- a/docs/architecture/frontend-ports-adapters-and-boundaries.md +++ b/docs/architecture/frontend-ports-adapters-and-boundaries.md @@ -116,7 +116,7 @@ bootstrap은 page별 orchestration이나 업무 규칙을 소유하지 않는다 | `src/adapters` | HTTP, auth, storage, cache, telemetry 구현 | outbound adapter | | `src/bootstrap` | runtime config와 구현 조립 | 유일한 composition root | | `src/contracts` | 여러 계층의 registry가 혼재 | 소유 계층으로 분산 | -| `src/sample` | 제거 가능한 예제 일부 | 완전한 removable reference feature | +| `src/features/reference-feature` | 완전한 제거 가능 수직 예제 | installed contribution과 8단계 제거 gate 유지 | 현재 구조가 잘 제공하는 기반은 다음과 같다. @@ -154,15 +154,14 @@ RP-03 구현으로 HTTP와 server-state 경계도 다음처럼 연결됐다. - HTTP가 자동 network retry를 소유하고 query/mutation adapter의 vendor retry는 비활성화한다. -RP-04에서 첫 번째 실행 불일치는 닫혔다. route registry와 runtime map은 +RP-04에서 route 실행 불일치는 닫혔다. route registry와 runtime map은 Data Router tree, codec, surface, title, navigation, chunk/release recovery의 단일 조립 입력이며 registry/type/build 검증이 누락과 orphan을 거절한다. -후속 브랜치에서 닫아야 할 실행 불일치는 다음과 같다. - -1. 제거 테스트는 `src/sample/contract-fixture`만 제거하며, sample API - operation, Zod schema, mapper, domain model과 query key는 다른 경로에 - 남는다. +RP-05에서 두 번째 불일치도 닫혔다. feature별 domain/application/adapter/ +contract/presentation은 `src/features/reference-feature`가 소유하고, generic +installed catalog만 bootstrap과 router에 노출된다. 제거 gate는 feature와 test를 +삭제한 복제본에서 전체 P0 경로를 다시 실행한다. 이 문서의 목표 구조는 기존 기반을 폐기하는 것이 아니라 이러한 불일치를 제거하는 것이다. @@ -1222,11 +1221,11 @@ contract와 실패 분기를 우선한다. ### 26.5 Reference feature -- [ ] route부터 API mapper와 화면까지 완전한 수직 경로가 실행된다. -- [ ] list/create 등 최소 query와 mutation 예제가 있다. -- [ ] loading/empty/error/refresh/conflict 상태가 있다. -- [ ] reference feature 전체 삭제 후 typecheck/test/build가 통과한다. -- [ ] built asset에 reference operation, schema, mapper가 남지 않는다. +- [x] route부터 API mapper와 화면까지 완전한 수직 경로가 실행된다. +- [x] list/create 등 최소 query와 mutation 예제가 있다. +- [x] loading/empty/error/refresh/conflict 상태가 있다. +- [x] reference feature 전체 삭제 후 typecheck/architecture/registry/test/home/build가 통과한다. +- [x] 제거 모드 built asset에 reference operation, schema, mapper가 남지 않는다. ### 26.6 품질 diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index dc7ffe7d..b824bdb9 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -44,12 +44,13 @@ flowchart LR The current executable route tree is mounted only after runtime configuration and release-manifest coherence pass. It receives the composed query client, credential-opaque session port, storage port, telemetry port, and immutable -build ID. Visible starter pages do not depend on the removable sample fixture. +build ID. Generic starter pages do not depend on the removable reference +feature. This describes the current starter composition, not the completed target. The capability review found that raw outbound capabilities still reach the React tree, the composed application facade is not yet its entry point, and several -route, HTTP, recovery, telemetry, and sample-removal contracts are only +route, HTTP, recovery, telemetry, and reference-feature removal contracts are only partially connected. Use the following documents for the evidence and migration plan: diff --git a/docs/architecture/routing-pages-and-patterns.md b/docs/architecture/routing-pages-and-patterns.md index 4d4e71b6..df0cf4bd 100644 --- a/docs/architecture/routing-pages-and-patterns.md +++ b/docs/architecture/routing-pages-and-patterns.md @@ -23,8 +23,8 @@ RP-04 이후 현재 구현에는 다음 장점이 있다. - route heading focus와 비동기/render error boundary가 있다. - redirect loop와 chunk recovery가 bounded production call graph에 연결돼 있다. -`src/contracts/routes.js`, `src/contracts/route-runtime-contract.js`, -`src/presentation/routes/route-runtime.tsx`의 완전성은 TypeScript와 registry +platform route 계약, `src/features/installed-feature-contracts.js`, +`src/features/installed-feature-runtimes.tsx`의 완전성은 TypeScript와 registry negative fixture가 함께 검사한다. params/search codec, loading/error surface, access, title, navigation, chunk ID는 `src/presentation/routes/app-router.tsx`에서 모두 소비된다. built Vite diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index d5e37ed8..313022da 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -11,7 +11,8 @@ primitives, and state surfaces remain reusable. validated config + coherent release manifest -> concrete adapters -> QueryClientProvider - -> BrowserRouter + -> ApplicationProvider + -> RouterProvider -> ThemeProvider -> SessionProvider -> AppShell @@ -31,7 +32,7 @@ remain stable in the shell. | `EXAMPLES_UI` | `/examples/ui` | public | interactive primitives and tokens | | `EXAMPLES_STATES` | `/examples/states` | public | async and access state matrix | | `EXAMPLES_AUTH` | `/examples/auth` | public | session integration controls | -| `SAMPLE_RESOURCE_LIST` | `/sample/resources` | integration-defined | protected integration seam | +| `REFERENCE_RESOURCE_LIST` | `/examples/reference-resources` | integration-defined | removable vertical slice | | `NOT_FOUND` | `*` | public | safe navigation recovery | Navigation labels and order come from `ROUTE_REGISTRY`; the sidebar does not @@ -54,24 +55,25 @@ An external owner implements `readState`, `subscribe`, `beginSignIn`, ## Extending the starter -The steps below describe the current extension path. The platform review found -that several route metadata fields and the composed application facade are not -yet connected end to end. New platform work should follow +The steps below describe the current extension path. New platform work should follow [routing, page templates, and reusable patterns](./routing-pages-and-patterns.md) and the [TypeScript, state, and data-flow target](./typescript-state-and-data-flow.md) rather than adding another independent route or data-loading convention. -1. Register the route path, access hint, title, chunk, loading surface, error - surface, and optional navigation metadata in `src/contracts/routes.js`. -2. Add a lazy page in `src/presentation/` and render it through `RouteSurface`. -3. Use application ports or use cases; do not import concrete adapters. +1. Add a serializable contribution under the feature ownership boundary and + install it through `src/features/installed-feature-contracts.js`. +2. Add the lazy component and route codecs through + `src/features/installed-feature-runtimes.tsx`. +3. Compose feature application inputs and outbound gateways only through + `src/features/installed-feature-adapters.ts`. 4. Use the semantic tokens, UI primitives, and state surfaces before adding a project-specific variant. 5. Add component behavior, all-engine E2E, automated axe, and signed manual route evidence. -6. Run `test:sample-removal` to prove the visible starter still builds without - `src/sample/contract-fixture`. +6. Run `test:sample-removal` to prove the generic starter typechecks, passes + architecture/registry/tests/home smoke, and builds without the complete + reference feature. Theme preference is the public `COLOR_SCHEME` storage contract. Authentication tokens and other secrets remain forbidden storage keys. diff --git a/docs/styling/design-tokens.md b/docs/styling/design-tokens.md index baf91eb2..b2940c30 100644 --- a/docs/styling/design-tokens.md +++ b/docs/styling/design-tokens.md @@ -37,8 +37,9 @@ Arbitrary-value policy: - user-controlled or runtime-composed class strings are forbidden - class variants must be selected from a closed static map -The removable sample may demonstrate tokens, but production starter modules do -not import from `src/sample/contract-fixture`. +The removable reference feature may demonstrate tokens, but generic production +starter modules do not import its domain, application, adapter, or presentation +implementation. This file documents the currently implemented token and primitive baseline. The [design-system platform contract](./design-system-platform.md) defines the diff --git a/docs/testing/frontend-platform-testing-strategy.md b/docs/testing/frontend-platform-testing-strategy.md index ddf862e9..3f5d5fed 100644 --- a/docs/testing/frontend-platform-testing-strategy.md +++ b/docs/testing/frontend-platform-testing-strategy.md @@ -446,6 +446,14 @@ tests/support/query/ helper는 production default를 복사하지 않는다. production factory를 호출하고 필요한 시간·retry만 test override로 주입한다. +RP-05의 executable reference matrix는 +`tests/features/reference-feature`에 모여 있다. 설치 모드에서는 URL codec과 +query key/HTTP search의 동일성, DTO 차단, loading/success/empty/terminal, +refreshing/stale, pending/duplicate/optimistic/conflict/rollback과 MSW production +composition을 검증한다. 제거 모드는 feature source/tests와 installed +contract/runtime/adapter contribution을 제거한 복제본에서 P0 gate와 built asset +잔여 0개를 다시 검증한다. + ## 8. Form 테스트 Form test는 field primitive, form controller, application command mapping을 diff --git a/eslint.config.js b/eslint.config.js index ac300846..c2a92ef0 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -196,6 +196,62 @@ export default [ "no-restricted-imports": restrictedImports(layerPatterns.adapters), }, }, + { + files: [`src/features/*/domain/**/*.${sourceExtensions}`], + rules: { + "no-restricted-imports": restrictedImports(layerPatterns.domain), + "no-restricted-globals": [ + "error", + "window", + "document", + "localStorage", + "fetch", + ], + }, + }, + { + files: [`src/features/*/application/**/*.${sourceExtensions}`], + rules: { + "no-restricted-imports": restrictedImports(layerPatterns.application), + "no-restricted-globals": [ + "error", + "window", + "document", + "localStorage", + "fetch", + ], + }, + }, + { + files: [`src/features/*/presentation/**/*.${sourceExtensions}`], + rules: { + "no-restricted-imports": restrictedImports([ + "**/features/*/adapters/**", + "**/adapters/http/**", + "**/adapters/storage/**", + "**/adapters/auth/**", + "**/bootstrap/**", + "**/application/ports/out/**", + "@tanstack/**", + ]), + "no-restricted-globals": [ + "error", + "fetch", + "localStorage", + "sessionStorage", + ], + }, + }, + { + files: [`src/features/*/adapters/**/*.${sourceExtensions}`], + rules: { + "no-restricted-imports": restrictedImports([ + "**/presentation/**", + "**/bootstrap/**", + "@tanstack/**", + ]), + }, + }, { files: [`tests/**/*.${sourceExtensions}`], languageOptions: { diff --git a/package.json b/package.json index 0191f54d..936e69a3 100644 --- a/package.json +++ b/package.json @@ -34,7 +34,8 @@ "test:a11y": "playwright test --grep @a11y && node scripts/write-a11y-report.mjs", "review:a11y-manual": "node scripts/verify-a11y-manual.mjs", "test:sample-removal": "node scripts/test-sample-removal.mjs", - "test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:component && corepack pnpm test:integration", + "test:reference-feature": "vitest run tests/features/reference-feature --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/reference-feature.xml --passWithNoTests", + "test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:component && corepack pnpm test:integration && corepack pnpm test:reference-feature", "verify:lockfile": "corepack pnpm install --frozen-lockfile", "generate:supply-chain": "node scripts/generate-supply-chain.mjs", "scan:security": "node scripts/security-scan.mjs", diff --git a/public/release-manifest.json b/public/release-manifest.json index 051a15f7..ce70cd60 100644 --- a/public/release-manifest.json +++ b/public/release-manifest.json @@ -13,7 +13,7 @@ "route-examples-ui": "src/presentation/examples/ui-gallery-page.jsx", "route-examples-states": "src/presentation/examples/state-gallery-page.jsx", "route-examples-auth": "src/presentation/examples/auth-example-page.jsx", - "route-sample-resources": "src/presentation/pages/sample-contract-page.jsx", + "route-reference-resources": "src/features/reference-feature/presentation/reference-resource-page.tsx", "route-not-found": "src/presentation/pages/not-found-page.jsx" } } diff --git a/scripts/generate-build-manifest.mjs b/scripts/generate-build-manifest.mjs index b6a5ff8f..f89337f8 100644 --- a/scripts/generate-build-manifest.mjs +++ b/scripts/generate-build-manifest.mjs @@ -3,8 +3,10 @@ import { mkdir, readFile, writeFile } from "node:fs/promises"; import process from "node:process"; import { z } from "zod"; -import { ROUTE_REGISTRY } from "../src/contracts/routes.js"; -import { ROUTE_RUNTIME_CONTRACT } from "../src/contracts/route-runtime-contract.js"; +import { + ROUTE_REGISTRY, + ROUTE_RUNTIME_CONTRACT, +} from "../src/features/installed-feature-contracts.js"; import { runtimeConfigSchema } from "../src/bootstrap/runtime-config-schema.js"; const packageJson = JSON.parse(await readFile("package.json", "utf8")); diff --git a/scripts/lib/manual-a11y-evidence.mjs b/scripts/lib/manual-a11y-evidence.mjs index 2fbeac78..d67cd4d4 100644 --- a/scripts/lib/manual-a11y-evidence.mjs +++ b/scripts/lib/manual-a11y-evidence.mjs @@ -1,11 +1,8 @@ -export const MANUAL_A11Y_ROUTE_IDS = Object.freeze([ - "APP_HOME", - "EXAMPLES_UI", - "EXAMPLES_STATES", - "EXAMPLES_AUTH", - "SAMPLE_RESOURCE_LIST", - "NOT_FOUND", -]); +import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.js"; + +export const MANUAL_A11Y_ROUTE_IDS = Object.freeze( + Object.values(ROUTE_REGISTRY).map((route) => route.routeId), +); const REVIEW_FIELDS = Object.freeze([ "M1 Keyboard", diff --git a/scripts/test-performance.mjs b/scripts/test-performance.mjs index 598ec0a7..b3684669 100644 --- a/scripts/test-performance.mjs +++ b/scripts/test-performance.mjs @@ -6,7 +6,7 @@ import process from "node:process"; import { chromium } from "@playwright/test"; import { evaluateLabBudget } from "../src/application/policies/performance-budgets.js"; -import { ROUTE_REGISTRY } from "../src/contracts/routes.js"; +import { ROUTE_REGISTRY } from "../src/features/installed-feature-contracts.js"; const server = spawn( "corepack", @@ -67,8 +67,9 @@ try { }).observe({ type: "layout-shift", buffered: true }); }); await page.goto(baseUrl, { waitUntil: "networkidle" }); - const targetLabel = - ROUTE_REGISTRY.SAMPLE_RESOURCE_LIST.navigationLabel; + const targetLabel = Object.values(ROUTE_REGISTRY).find( + (definition) => definition.access === "integration-defined", + )?.navigationLabel; if (!targetLabel) { throw new Error("Performance route must be present in navigation."); } diff --git a/scripts/test-sample-removal.mjs b/scripts/test-sample-removal.mjs index ce42f54e..0cf76776 100644 --- a/scripts/test-sample-removal.mjs +++ b/scripts/test-sample-removal.mjs @@ -1,78 +1,218 @@ -import { cp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises"; import { spawnSync } from "node:child_process"; +import { + cp, + mkdir, + readFile, + readdir, + rm, + symlink, + writeFile, +} from "node:fs/promises"; import path from "node:path"; -const fixtureRoot = path.resolve(".tmp/sample-removal"); -const sampleRoot = path.resolve("src/sample/contract-fixture"); -const sourceRoot = path.resolve("src"); +const fixtureRoot = path.resolve(".tmp/reference-feature-removal"); const pnpmCli = /** @type {string} */ (process.env.npm_execpath); +const featureSource = "src/features/reference-feature"; +const featureTests = "tests/features/reference-feature"; +const copyTargets = [ + "src", + "tests", + "scripts", + "config", + "public", + "index.html", + "package.json", + "tsconfig.base.json", + "tsconfig.json", + "tsconfig.app.json", + "tsconfig.node.json", + "tsconfig.test.json", + "vite.config.js", + "vitest.config.js", + "playwright.config.js", + "eslint.config.js", + ".dependency-cruiser.cjs", +]; + +const emptyContracts = `import { PLATFORM_ROUTE_RUNTIME_CONTRACT } from "../contracts/route-runtime-contract.js"; +import { PLATFORM_ROUTE_REGISTRY } from "../contracts/routes.js"; + +export const INSTALLED_FEATURE_CONTRACTS = + /** @type {readonly unknown[]} */ (Object.freeze([])); +export const ROUTE_REGISTRY = PLATFORM_ROUTE_REGISTRY; +export const ROUTE_RUNTIME_CONTRACT = PLATFORM_ROUTE_RUNTIME_CONTRACT; +export const API_OPERATIONS = Object.freeze({}); +export const QUERY_REGISTRY = Object.freeze({}); +export const NAVIGATION_ROUTES = Object.freeze( + Object.values(ROUTE_REGISTRY) + .filter((definition) => definition.navigationOrder !== null) + .sort( + (left, right) => + /** @type {number} */ (left.navigationOrder) - + /** @type {number} */ (right.navigationOrder), + ), +); +/** @param {string} routeId */ +export function getRoute(routeId) { + const registry = + /** @type {Readonly>} */ ( + ROUTE_REGISTRY + ); + const selected = registry[routeId]; + if (!selected) throw new Error(\`Unregistered route: \${routeId}\`); + return selected; +} +/** @param {string} routeId */ +export function routePath(routeId) { + return getRoute(routeId).path; +} +`; + +const emptyRuntimes = `import { PLATFORM_ROUTE_CODECS } from "../presentation/routes/platform-route-codecs.js"; +import { PLATFORM_ROUTE_RUNTIME } from "../presentation/routes/route-runtime.js"; + +export const ROUTE_CODECS = PLATFORM_ROUTE_CODECS; +export const ROUTE_RUNTIME = PLATFORM_ROUTE_RUNTIME; +`; + +const emptyAdapters = `type FeatureContext = Readonly<{ + createHttpClient(contract: Readonly>): unknown; +}>; +export function createInstalledFeatureInputs(_context: FeatureContext) { + void _context; + return Object.freeze({}); +} +`; /** @param {string} directory @returns {Promise} */ -async function sourceFiles(directory) { +async function filesBelow(directory) { const entries = await readdir(directory, { withFileTypes: true }); - const nested = /** @type {string[][]} */ (await Promise.all( + const groups = await Promise.all( entries.map((entry) => { const target = path.join(directory, entry.name); - return entry.isDirectory() ? sourceFiles(target) : [target]; + return entry.isDirectory() ? filesBelow(target) : [target]; }), - )); - return nested.flat(); + ); + return groups.flat(); +} + +/** @param {string} script @param {string[]} [extra] */ +function runPnpm(script, extra = []) { + const result = spawnSync(process.execPath, [pnpmCli, script, ...extra], { + cwd: fixtureRoot, + stdio: "inherit", + }); + return result.status === 0; } await rm(fixtureRoot, { recursive: true, force: true }); await mkdir(fixtureRoot, { recursive: true }); +for (const target of copyTargets) { + await cp(target, path.join(fixtureRoot, target), { recursive: true }); +} +await symlink(path.resolve("node_modules"), path.join(fixtureRoot, "node_modules"), "dir"); -const incomingImports = []; -for (const sourceFile of await sourceFiles(sourceRoot)) { - if (sourceFile.startsWith(sampleRoot)) continue; - const content = await readFile(sourceFile, "utf8"); - if (/from\s+["'][^"']*sample\/contract-fixture/.test(content)) { - incomingImports.push(path.relative(".", sourceFile)); +await rm(path.join(fixtureRoot, featureSource), { + recursive: true, + force: true, +}); +await rm(path.join(fixtureRoot, featureTests), { + recursive: true, + force: true, +}); +await writeFile( + path.join(fixtureRoot, "src/features/installed-feature-contracts.js"), + emptyContracts, +); +await writeFile( + path.join(fixtureRoot, "src/features/installed-feature-runtimes.tsx"), + emptyRuntimes, +); +await writeFile( + path.join(fixtureRoot, "src/features/installed-feature-adapters.ts"), + emptyAdapters, +); + +/** @type {string[]} */ +const residue = []; +for (const root of ["src", "tests"]) { + for (const file of await filesBelow(path.join(fixtureRoot, root))) { + const relative = path.relative(fixtureRoot, file); + const content = await readFile(file, "utf8"); + if ( + /REFERENCE_RESOURCE|reference-feature|reference-resource/i.test( + `${relative}\n${content}`, + ) + ) { + residue.push(relative); + } } } -let buildStatus = 1; -if (incomingImports.length === 0) { - await cp("src", path.join(fixtureRoot, "src"), { - recursive: true, - filter: (source) => !source.startsWith(sampleRoot), - }); - await cp("public", path.join(fixtureRoot, "public"), { recursive: true }); - await cp("index.html", path.join(fixtureRoot, "index.html")); - await cp("vite.config.js", path.join(fixtureRoot, "vite.config.js")); - - const result = spawnSync( - process.execPath, - [ - pnpmCli, - "exec", - "vite", - "build", - fixtureRoot, - "--outDir", - path.join(fixtureRoot, "dist"), - ], - { stdio: "inherit" }, - ); - buildStatus = result.status ?? 1; +const checks = [ + ["typecheck", runPnpm("check:types")], + ["architecture", runPnpm("check:architecture")], + ["registry", runPnpm("check:registries")], + ["unit-integration", runPnpm("test:all")], + [ + "home-smoke", + runPnpm("exec", [ + "vitest", + "run", + "tests/component/router.test.jsx", + "--reporter=default", + ]), + ], + ["build", runPnpm("build")], +]; +/** @type {string[]} */ +const builtResidue = []; +for (const file of await filesBelow(path.join(fixtureRoot, "dist"))) { + if (!/\.(?:js|css|html|json)$/.test(file)) continue; + const content = await readFile(file, "utf8"); + if ( + /REFERENCE_RESOURCE|reference-feature|reference-resource/i.test(content) + ) { + builtResidue.push(path.relative(fixtureRoot, file)); + } } +const routeCatalog = await import( + `${new URL( + "../src/features/installed-feature-contracts.js", + `file://${fixtureRoot}/scripts/`, + ).href}?removed=${Date.now()}` +); +const routeIds = Object.keys(routeCatalog.ROUTE_REGISTRY); +const routeAbsent = routeIds.every((routeId) => !routeId.startsWith("REFERENCE_")); +checks.push(["route-absent", routeAbsent]); +checks.push(["fixture-id-residue", residue.length === 0]); +checks.push(["built-fixture-id-residue", builtResidue.length === 0]); +const passed = checks.every(([, result]) => result); await mkdir("artifacts/tests", { recursive: true }); -const passed = incomingImports.length === 0 && buildStatus === 0; await writeFile( "artifacts/tests/sample-removal.xml", `\n` + - `` + - `` + - `${passed ? "" : ""}` + + `` + + checks + .map( + ([name, result]) => + `${result ? "" : `${[...residue, ...builtResidue].join(", ")}`}`, + ) + .join("") + `\n`, ); await rm(fixtureRoot, { recursive: true, force: true }); if (!passed) { + const failures = checks + .filter(([, result]) => !result) + .map(([name]) => name); process.stderr.write( - `Sample removal failed. Incoming imports: ${incomingImports.join(", ")}\n`, + `Reference feature removal failed: ${failures.join(", ")}; residue: ${[...residue, ...builtResidue].join(", ")}\n`, ); process.exit(1); } -process.stdout.write("Sample removal smoke: PASS\n"); +process.stdout.write( + `Reference feature removal: PASS (${checks.length} checks, no fixture IDs)\n`, +); diff --git a/scripts/verify-release.mjs b/scripts/verify-release.mjs index ca5e4fe8..672ee1e4 100644 --- a/scripts/verify-release.mjs +++ b/scripts/verify-release.mjs @@ -6,8 +6,10 @@ import { compareReleaseToRuntime, RELEASE_TOKEN_REGISTRY, } from "../src/contracts/release-tokens.js"; -import { ROUTE_RUNTIME_CONTRACT } from "../src/contracts/route-runtime-contract.js"; -import { ROUTE_REGISTRY } from "../src/contracts/routes.js"; +import { + ROUTE_REGISTRY, + ROUTE_RUNTIME_CONTRACT, +} from "../src/features/installed-feature-contracts.js"; const fixturesDocument = /** @type {{ diff --git a/src/adapters/http/client.js b/src/adapters/http/client.js index 46abc594..a590c3e8 100644 --- a/src/adapters/http/client.js +++ b/src/adapters/http/client.js @@ -46,6 +46,8 @@ const noAuthSession = * random?: () => number, * validatePayload?: (schemaId: string, value: unknown) => * { success: true, data: unknown } | { success: false }, + * validateRequest?: (schemaId: string, value: unknown) => + * { success: true, data: unknown } | { success: false }, * mapPayload?: (operationId: string, payload: unknown) => unknown, * idempotencyKeyFactory?: () => string, * timeoutMs?: number, @@ -61,6 +63,8 @@ export function createHttpClient(dependencies) { const random = dependencies.random ?? Math.random; const validatePayload = dependencies.validatePayload ?? validateOperationPayload; + const validateRequest = + dependencies.validateRequest ?? validateOperationRequest; const mapPayload = dependencies.mapPayload ?? mapOperationPayload; const idempotencyKeyFactory = dependencies.idempotencyKeyFactory ?? (() => crypto.randomUUID()); @@ -193,7 +197,7 @@ export function createHttpClient(dependencies) { ? input.body : {}; if (operation.requestSource !== "none") { - const requestValidation = validateOperationRequest( + const requestValidation = validateRequest( operation.requestSchema, requestValue, ); diff --git a/src/adapters/http/resource-mapper.js b/src/adapters/http/resource-mapper.js index 2a8e6368..4486b05c 100644 --- a/src/adapters/http/resource-mapper.js +++ b/src/adapters/http/resource-mapper.js @@ -1,30 +1,5 @@ -import { createResource } from "../../domain/models/resource.js"; - -/** @param {unknown} value */ -export function mapResourceDto(value) { - if (!value || typeof value !== "object") { - throw new TypeError("Validated resource DTO is required"); - } - const dto = /** @type {Record} */ (value); - if (typeof dto.id !== "string" || typeof dto.name !== "string") { - throw new TypeError("Validated resource DTO invariants were breached"); - } - - return createResource({ - id: dto.id, - displayName: dto.name, - createdAt: typeof dto.createdAt === "string" ? dto.createdAt : null, - }); -} - /** @param {string} operationId @param {unknown} payload */ export function mapOperationPayload(operationId, payload) { - if (operationId === "LIST_SAMPLE_RESOURCES") { - if (!Array.isArray(payload)) throw new TypeError("Expected a resource list"); - return payload.map(mapResourceDto); - } - if (operationId === "CREATE_SAMPLE_RESOURCE") { - return mapResourceDto(payload); - } + void payload; throw new TypeError(`No boundary mapper registered for ${operationId}`); } diff --git a/src/adapters/http/schema-registry.js b/src/adapters/http/schema-registry.js index 4ec4af3a..13064b9c 100644 --- a/src/adapters/http/schema-registry.js +++ b/src/adapters/http/schema-registry.js @@ -37,35 +37,11 @@ export const responseEnvelopeSchema = z.discriminatedUnion("success", [ failureEnvelopeSchema, ]); -const sampleResourceSchema = z - .object({ - id: z.string().min(1), - name: z.string().min(1), - createdAt: z.string().optional(), - }) - .passthrough(); - const payloadSchemas = - /** @type {Readonly>} */ (Object.freeze({ - SampleResourceListPayload: z.array(sampleResourceSchema), - SampleResourcePayload: sampleResourceSchema, -})); + /** @type {Readonly>} */ (Object.freeze({})); const requestSchemas = - /** @type {Readonly>} */ (Object.freeze({ - SampleResourceListQuery: z - .object({ - cursor: z.string().optional(), - limit: z.int().min(1).max(100).default(20), - tags: z.array(z.string().trim().min(1)).optional(), - }) - .strict(), - CreateSampleResourceCommand: z - .object({ - name: z.string().trim().min(1).max(120), - }) - .strict(), -})); + /** @type {Readonly>} */ (Object.freeze({})); /** @param {unknown} value */ export function validateEnvelope(value) { diff --git a/src/application/create-application.ts b/src/application/create-application.ts index 2b92f9d0..ee760699 100644 --- a/src/application/create-application.ts +++ b/src/application/create-application.ts @@ -15,6 +15,7 @@ export type { ApplicationApi, ApplicationOutputPorts }; */ export function createApplication( outputPorts: ApplicationOutputPorts, + featureInputs: Readonly> = {}, ): ApplicationApi { const session = Object.freeze({ getSnapshot: () => outputPorts.session.getState(), @@ -107,6 +108,18 @@ export function createApplication( } }, }); + const installedFeatureInputs = Object.freeze({ ...featureInputs }); + const features = Object.freeze({ + has(featureId: string) { + return Object.hasOwn(installedFeatureInputs, featureId); + }, + get(featureId: string) { + if (!Object.hasOwn(installedFeatureInputs, featureId)) { + throw new Error(`Application feature is not installed: ${featureId}`); + } + return installedFeatureInputs[featureId]; + }, + }); return Object.freeze({ session, @@ -114,5 +127,6 @@ export function createApplication( diagnostics, runtime, recovery, + features, }); } diff --git a/src/application/ports/in/application-api.ts b/src/application/ports/in/application-api.ts index 5a79e4c0..68b62f7b 100644 --- a/src/application/ports/in/application-api.ts +++ b/src/application/ports/in/application-api.ts @@ -47,4 +47,8 @@ export type ApplicationApi = Readonly<{ | Readonly<{ action: "support"; reason: string }> >; }>; + features: Readonly<{ + has(featureId: string): boolean; + get(featureId: string): unknown; + }>; }>; diff --git a/src/application/ports/out/index.ts b/src/application/ports/out/index.ts index 9b364cdc..b16cb7e0 100644 --- a/src/application/ports/out/index.ts +++ b/src/application/ports/out/index.ts @@ -7,11 +7,5 @@ export type { export type { ClockPort } from "../clock-port.js"; export type { QueryCachePort } from "../query-cache-port.js"; export type { ReleaseInfoPort } from "../release-info-port.js"; -export type { - RequestContext, - ResourceCommandPort, - ResourceQueryPort, - Result, -} from "../resource-ports.js"; export type { StoragePort } from "../storage-port.js"; export type { TelemetryPort } from "../telemetry-port.js"; diff --git a/src/application/ports/resource-ports.js b/src/application/ports/resource-ports.js deleted file mode 100644 index 1290758c..00000000 --- a/src/application/ports/resource-ports.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @template Query - * @template Model - * @typedef {{ execute(query: Query, context?: RequestContext): Promise> }} ResourceQueryPort - */ - -/** - * @template Command - * @template Model - * @typedef {{ execute(command: Command, context?: RequestContext): Promise> }} ResourceCommandPort - */ - -/** - * @typedef {{ - * operationId: string, - * routeId: string, - * signal?: AbortSignal, - * idempotencyKey?: string - * }} RequestContext - */ - -/** - * @template Value - * @typedef {{ ok: true, value: Value, meta?: Record } | - * { ok: false, error: import("../../contracts/errors.js").ApiFailure }} Result - */ - -export {}; diff --git a/src/application/view-models/resource-view-model.js b/src/application/view-models/resource-view-model.js deleted file mode 100644 index 963f25d3..00000000 --- a/src/application/view-models/resource-view-model.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * @param {import("../../domain/models/resource.js").Resource} resource - * @param {(value: Date) => string} [formatDate] - */ -export function toResourceViewModel( - resource, - formatDate = (value) => new Intl.DateTimeFormat("ko-KR").format(value), -) { - return Object.freeze({ - resourceId: resource.id, - title: resource.displayName, - createdAtLabel: resource.createdAt - ? formatDate(new Date(resource.createdAt)) - : null, - }); -} diff --git a/src/bootstrap/composition-root.js b/src/bootstrap/composition-root.js index c6c58a24..db54934c 100644 --- a/src/bootstrap/composition-root.js +++ b/src/bootstrap/composition-root.js @@ -16,7 +16,8 @@ import { createApplication } from "../application/create-application.js"; * release: Release * }): Promise<{ * outputPorts: OutputPorts, - * infrastructure: Infrastructure + * infrastructure: Infrastructure, + * featureInputs?: Readonly> * }> * }} factories * @returns {Promise} host @@ -54,7 +55,7 @@ function storageOrUndefined(value) { * scheduler?: Parameters[0]["scheduler"] * }} context */ -export function createRuntimeHttpClient(context) { +export function createRuntimeHttpClient(context, contract = {}) { return createHttpClient({ baseUrl: context.runtime.config.API_BASE_URL, timeoutMs: context.runtime.config.REQUEST_TIMEOUT_MS, @@ -63,6 +64,7 @@ export function createRuntimeHttpClient(context) { fetcher: context.fetcher, clock: context.clock, scheduler: context.scheduler, + ...contract, }); } @@ -116,6 +118,17 @@ export async function createRuntimeAdapters(context) { location.reload(); }, }); + const featureInputs = createInstalledFeatureInputs({ + createHttpClient: (contract) => + createRuntimeHttpClient( + { + runtime: context.runtime, + authSession, + fetcher: context.fetcher, + }, + contract, + ), + }); return Object.freeze({ outputPorts: Object.freeze({ @@ -128,5 +141,6 @@ export async function createRuntimeAdapters(context) { infrastructure: Object.freeze({ queryClient, }), + featureInputs, }); } diff --git a/src/contracts/api-operations.js b/src/contracts/api-operations.js index a4eec5b9..e4196f15 100644 --- a/src/contracts/api-operations.js +++ b/src/contracts/api-operations.js @@ -14,41 +14,11 @@ * }} ApiOperation */ -/** @param {ApiOperation} definition */ -const operation = (definition) => Object.freeze(definition); - -export const API_OPERATIONS = Object.freeze({ - LIST_SAMPLE_RESOURCES: operation({ - method: "GET", - path: "/api/sample/resources", - operationId: "LIST_SAMPLE_RESOURCES", - auth: "external-session", - timeoutMs: null, - idempotency: "safe", - retry: "runtime", - requestSource: "search", - requestSchema: "SampleResourceListQuery", - responseSchema: "SampleResourceListPayload", - owner: "feature-sample-feature-slice-contract-fixture", - }), - CREATE_SAMPLE_RESOURCE: operation({ - method: "POST", - path: "/api/sample/resources", - operationId: "CREATE_SAMPLE_RESOURCE", - auth: "external-session", - timeoutMs: null, - idempotency: "keyed", - retry: "runtime", - requestSource: "body", - requestSchema: "CreateSampleResourceCommand", - responseSchema: "SampleResourcePayload", - owner: "feature-sample-feature-slice-contract-fixture", - }), -}); +export const API_OPERATIONS = Object.freeze({}); /** @param {string} operationId */ -export function getApiOperation(operationId) { - const registry = /** @type {Record} */ (API_OPERATIONS); +export function getApiOperation(operationId, operations = API_OPERATIONS) { + const registry = /** @type {Record} */ (operations); const selected = registry[operationId]; if (!selected) { throw new Error(`Unregistered API operation: ${operationId}`); diff --git a/src/contracts/query-keys.js b/src/contracts/query-keys.js index 050ac61b..24f4be75 100644 --- a/src/contracts/query-keys.js +++ b/src/contracts/query-keys.js @@ -1,26 +1,4 @@ -const RESOURCE_NAMESPACE = Object.freeze(["resource", 1]); - -export const queryKeys = Object.freeze({ - resource: Object.freeze({ - all: () => RESOURCE_NAMESPACE, - list: (filters = {}) => - Object.freeze([...RESOURCE_NAMESPACE, "list", canonicalize(filters)]), - /** @param {string} resourceId */ - detail: (resourceId) => - Object.freeze([...RESOURCE_NAMESPACE, "detail", String(resourceId)]), - }), -}); - -export const QUERY_REGISTRY = Object.freeze({ - RESOURCE: Object.freeze({ - namespace: RESOURCE_NAMESPACE, - serialization: "canonical-object-order", - identity: "no-pii-token-or-raw-url", - invalidation: "resource namespace after successful mutation", - version: 1, - persistence: "disabled", - }), -}); +export const QUERY_REGISTRY = Object.freeze({}); /** @param {unknown} value @returns {unknown} */ export function canonicalize(value) { diff --git a/src/contracts/route-runtime-contract.js b/src/contracts/route-runtime-contract.js index 19e149f6..6f796060 100644 --- a/src/contracts/route-runtime-contract.js +++ b/src/contracts/route-runtime-contract.js @@ -1,11 +1,11 @@ /** - * @typedef {"none" | "NotFoundSplat" | "SampleResourceListQuery"} RouteCodecId + * @typedef {"none" | "NotFoundSplat"} RouteCodecId */ /** @param {Readonly<{routeId: string, moduleId: string, paramsCodec: RouteCodecId, searchCodec: RouteCodecId}>} value */ const runtime = (value) => Object.freeze(value); -export const ROUTE_RUNTIME_CONTRACT = Object.freeze({ +export const PLATFORM_ROUTE_RUNTIME_CONTRACT = Object.freeze({ APP_HOME: runtime({ routeId: "APP_HOME", moduleId: "home-page", @@ -30,12 +30,6 @@ export const ROUTE_RUNTIME_CONTRACT = Object.freeze({ paramsCodec: "none", searchCodec: "none", }), - SAMPLE_RESOURCE_LIST: runtime({ - routeId: "SAMPLE_RESOURCE_LIST", - moduleId: "sample-contract-page", - paramsCodec: "none", - searchCodec: "SampleResourceListQuery", - }), NOT_FOUND: runtime({ routeId: "NOT_FOUND", moduleId: "not-found-page", diff --git a/src/contracts/routes.js b/src/contracts/routes.js index 050bb06f..8dba85ed 100644 --- a/src/contracts/routes.js +++ b/src/contracts/routes.js @@ -17,7 +17,7 @@ /** @param {RouteDefinition} definition */ const route = (definition) => Object.freeze(definition); -export const ROUTE_REGISTRY = Object.freeze({ +export const PLATFORM_ROUTE_REGISTRY = Object.freeze({ APP_HOME: route({ routeId: "APP_HOME", path: "/", @@ -70,19 +70,6 @@ export const ROUTE_REGISTRY = Object.freeze({ navigationLabel: "인증 연동", navigationOrder: 40, }), - SAMPLE_RESOURCE_LIST: route({ - routeId: "SAMPLE_RESOURCE_LIST", - path: "/sample/resources", - paramsSchema: null, - searchSchema: "SampleResourceListQuery", - access: "integration-defined", - loadingSurface: "sample-resource-list", - errorSurface: "feature-boundary", - chunkId: "route-sample-resources", - title: "보호된 연동 지점", - navigationLabel: "보호된 연동 지점", - navigationOrder: 50, - }), NOT_FOUND: route({ routeId: "NOT_FOUND", path: "*", @@ -97,28 +84,3 @@ export const ROUTE_REGISTRY = Object.freeze({ navigationOrder: null, }), }); - -export const NAVIGATION_ROUTES = Object.freeze( - Object.values(ROUTE_REGISTRY) - .filter((definition) => definition.navigationOrder !== null) - .sort( - (left, right) => - /** @type {number} */ (left.navigationOrder) - - /** @type {number} */ (right.navigationOrder), - ), -); - -/** @param {string} routeId */ -export function getRoute(routeId) { - const registry = /** @type {Record>} */ ( - ROUTE_REGISTRY - ); - const selected = registry[routeId]; - if (!selected) throw new Error(`Unregistered route: ${routeId}`); - return selected; -} - -/** @param {string} routeId */ -export function routePath(routeId) { - return getRoute(routeId).path; -} diff --git a/src/domain/models/resource.js b/src/domain/models/resource.js deleted file mode 100644 index 7a41ed28..00000000 --- a/src/domain/models/resource.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * @typedef {{ - * id: string, - * displayName: string, - * createdAt: string | null - * }} Resource - */ - -/** @param {Resource} values @returns {Readonly} */ -export function createResource(values) { - if (!values.id || !values.displayName) { - throw new TypeError("Resource invariants require id and displayName"); - } - return Object.freeze({ - id: values.id, - displayName: values.displayName, - createdAt: values.createdAt, - }); -} diff --git a/src/features/installed-feature-adapters.ts b/src/features/installed-feature-adapters.ts new file mode 100644 index 00000000..99de178f --- /dev/null +++ b/src/features/installed-feature-adapters.ts @@ -0,0 +1,15 @@ +import { createReferenceFeatureInstalledInput } from "./reference-feature/adapters/create-reference-feature-input.js"; + +export function createInstalledFeatureInputs( + context: Parameters[0], +): Readonly> { + const installed = [createReferenceFeatureInstalledInput(context)]; + return Object.freeze( + Object.fromEntries( + installed.map((contribution) => [ + contribution.featureId, + contribution.input, + ]), + ), + ); +} diff --git a/src/features/installed-feature-contracts.js b/src/features/installed-feature-contracts.js new file mode 100644 index 00000000..d21258a4 --- /dev/null +++ b/src/features/installed-feature-contracts.js @@ -0,0 +1,48 @@ +import { PLATFORM_ROUTE_RUNTIME_CONTRACT } from "../contracts/route-runtime-contract.js"; +import { PLATFORM_ROUTE_REGISTRY } from "../contracts/routes.js"; +import { REFERENCE_FEATURE_CONTRACT } from "./reference-feature/contracts/reference-feature-contract.js"; + +export const INSTALLED_FEATURE_CONTRACTS = Object.freeze([ + REFERENCE_FEATURE_CONTRACT, +]); + +export const ROUTE_REGISTRY = Object.freeze({ + ...PLATFORM_ROUTE_REGISTRY, + ...REFERENCE_FEATURE_CONTRACT.routes, +}); +export const ROUTE_RUNTIME_CONTRACT = Object.freeze({ + ...PLATFORM_ROUTE_RUNTIME_CONTRACT, + ...REFERENCE_FEATURE_CONTRACT.routeRuntimeContracts, +}); +export const API_OPERATIONS = Object.freeze({ + ...REFERENCE_FEATURE_CONTRACT.apiOperations, +}); +export const QUERY_REGISTRY = Object.freeze({ + ...REFERENCE_FEATURE_CONTRACT.queryRegistry, +}); + +export const NAVIGATION_ROUTES = Object.freeze( + Object.values(ROUTE_REGISTRY) + .filter((definition) => definition.navigationOrder !== null) + .sort( + (left, right) => + /** @type {number} */ (left.navigationOrder) - + /** @type {number} */ (right.navigationOrder), + ), +); + +/** @param {string} routeId */ +export function getRoute(routeId) { + const registry = + /** @type {Readonly>} */ ( + ROUTE_REGISTRY + ); + const selected = registry[routeId]; + if (!selected) throw new Error(`Unregistered route: ${routeId}`); + return selected; +} + +/** @param {string} routeId */ +export function routePath(routeId) { + return getRoute(routeId).path; +} diff --git a/src/features/installed-feature-runtimes.tsx b/src/features/installed-feature-runtimes.tsx new file mode 100644 index 00000000..c545c3b9 --- /dev/null +++ b/src/features/installed-feature-runtimes.tsx @@ -0,0 +1,16 @@ +import { PLATFORM_ROUTE_CODECS } from "../presentation/routes/platform-route-codecs.js"; +import { PLATFORM_ROUTE_RUNTIME } from "../presentation/routes/route-runtime.js"; +import { + REFERENCE_FEATURE_ROUTE_CODECS, + REFERENCE_FEATURE_ROUTE_RUNTIME, +} from "./reference-feature/presentation/reference-feature-runtime.js"; + +export const ROUTE_CODECS = Object.freeze({ + ...PLATFORM_ROUTE_CODECS, + ...REFERENCE_FEATURE_ROUTE_CODECS, +}); + +export const ROUTE_RUNTIME = Object.freeze({ + ...PLATFORM_ROUTE_RUNTIME, + ...REFERENCE_FEATURE_ROUTE_RUNTIME, +}); diff --git a/src/features/reference-feature/README.md b/src/features/reference-feature/README.md new file mode 100644 index 00000000..ef1d454d --- /dev/null +++ b/src/features/reference-feature/README.md @@ -0,0 +1,39 @@ +# Reference feature ownership and removal + +이 모듈은 제품 도메인이 아니라 새 기능의 수직 경계를 검증하는 제거 가능한 +reference implementation이다. + +## 소유 경계 + +- `domain`: 외부 DTO와 React를 모르는 불변 model +- `application`: UI가 호출하는 list/create input과 gateway 계약 +- `adapters`: HTTP executor를 gateway로 투영하는 outbound adapter +- `contracts`: route/API/query contribution, Zod DTO와 request schema, mapper +- `presentation`: route input을 query/mutation controller로 연결하는 inbound + adapter와 page + +generic application은 `features.get(featureId)` catalog만 제공한다. feature hook이 +자신의 input shape를 확인하며 page는 HTTP client, storage, auth owner, output +port나 TanStack API를 직접 import하지 않는다. + +## 설치 지점 + +- 직렬화 계약: `src/features/installed-feature-contracts.js` +- component/codec: `src/features/installed-feature-runtimes.tsx` +- bootstrap input 조립: `src/features/installed-feature-adapters.ts` + +새 기능도 이 세 지점에 contribution을 합성하되 feature ID를 generic application, +router나 HTTP client에 하드코딩하지 않는다. + +## 검증과 제거 + +```sh +corepack pnpm test:reference-feature +corepack pnpm test:sample-removal +``` + +첫 명령은 URL filter와 query key/HTTP request의 동일성, schema/mapper, 모든 +query/mutation 상태와 production composition을 검증한다. 두 번째 명령은 임시 +복제본에서 이 source/test 디렉터리를 제거하고 installed catalog를 빈 목록으로 +재생성한 뒤 typecheck, architecture, registry, unit/integration, home smoke, +production build와 fixture ID 잔여 0개를 검사한다. diff --git a/src/features/reference-feature/adapters/create-reference-feature-input.ts b/src/features/reference-feature/adapters/create-reference-feature-input.ts new file mode 100644 index 00000000..36a96985 --- /dev/null +++ b/src/features/reference-feature/adapters/create-reference-feature-input.ts @@ -0,0 +1,43 @@ +import { createReferenceFeatureInput } from "../application/reference-feature-api.js"; +import { + REFERENCE_FEATURE_CONTRACT, + REFERENCE_FEATURE_ID, +} from "../contracts/reference-feature-contract.js"; +import { mapReferenceOperation } from "../contracts/reference-mapper.js"; +import { + validateReferencePayload, + validateReferenceRequest, +} from "../contracts/reference-schemas.js"; +import { createReferenceHttpGateway } from "./reference-http-gateway.js"; + +type HttpContract = Readonly<{ + getOperation(operationId: string): unknown; + validatePayload: typeof validateReferencePayload; + validateRequest: typeof validateReferenceRequest; + mapPayload: typeof mapReferenceOperation; +}>; + +type HttpExecutor = Parameters[0]; + +export function createReferenceFeatureInstalledInput(context: Readonly<{ + createHttpClient(contract: HttpContract): HttpExecutor; +}>) { + const operations = + REFERENCE_FEATURE_CONTRACT.apiOperations as Readonly>; + const http = context.createHttpClient({ + getOperation(operationId) { + const operation = operations[operationId]; + if (!operation) { + throw new Error(`Unknown reference operation: ${operationId}`); + } + return operation; + }, + validatePayload: validateReferencePayload, + validateRequest: validateReferenceRequest, + mapPayload: mapReferenceOperation, + }); + return Object.freeze({ + featureId: REFERENCE_FEATURE_ID, + input: createReferenceFeatureInput(createReferenceHttpGateway(http)), + }); +} diff --git a/src/features/reference-feature/adapters/reference-http-gateway.ts b/src/features/reference-feature/adapters/reference-http-gateway.ts new file mode 100644 index 00000000..5497a4d1 --- /dev/null +++ b/src/features/reference-feature/adapters/reference-http-gateway.ts @@ -0,0 +1,56 @@ +import type { ApiFailure } from "../../../contracts/errors.js"; +import type { + ReferenceGateway, + ReferenceListFilters, +} from "../application/reference-feature-api.js"; +import type { ReferenceResource } from "../domain/reference-resource.js"; + +type HttpResult = + | Readonly<{ ok: true; value: unknown }> + | Readonly<{ ok: false; error: ApiFailure }>; + +type HttpExecutor = Readonly<{ + execute( + request: Readonly<{ + operationId: string; + routeId: string; + searchParams?: unknown; + body?: unknown; + signal?: AbortSignal; + }>, + ): Promise; +}>; + +export function createReferenceHttpGateway( + http: HttpExecutor, +): ReferenceGateway { + return Object.freeze({ + async list( + filters: ReferenceListFilters, + context?: Readonly<{ signal?: AbortSignal }>, + ) { + const result = await http.execute({ + operationId: "LIST_REFERENCE_RESOURCES", + routeId: "REFERENCE_RESOURCE_LIST", + searchParams: filters, + signal: context?.signal, + }); + return result.ok + ? { + ok: true as const, + value: result.value as readonly ReferenceResource[], + } + : result; + }, + async create(command: Readonly<{ name: string }>) { + const result = await http.execute({ + operationId: "CREATE_REFERENCE_RESOURCE", + routeId: "REFERENCE_RESOURCE_LIST", + body: command, + }); + return result.ok + ? { ok: true as const, value: result.value as ReferenceResource } + : result; + }, + }); +} diff --git a/src/features/reference-feature/application/reference-feature-api.ts b/src/features/reference-feature/application/reference-feature-api.ts new file mode 100644 index 00000000..c8d0e403 --- /dev/null +++ b/src/features/reference-feature/application/reference-feature-api.ts @@ -0,0 +1,58 @@ +import type { ApiFailure } from "../../../contracts/errors.js"; +import { + toReferenceView, + type ReferenceResourceView, +} from "../contracts/reference-mapper.js"; +import type { ReferenceResource } from "../domain/reference-resource.js"; + +export type ReferenceListFilters = Readonly<{ + cursor?: string; + limit: number; + tags?: readonly string[]; +}>; + +export type ReferenceResult = + | Readonly<{ ok: true; value: Value }> + | Readonly<{ ok: false; error: ApiFailure }>; + +export type ReferenceFeatureInput = Readonly<{ + listResources( + filters: ReferenceListFilters, + context?: Readonly<{ signal?: AbortSignal }>, + ): Promise>; + createResource( + command: Readonly<{ name: string }>, + ): Promise>; +}>; + +export type ReferenceGateway = Readonly<{ + list( + filters: ReferenceListFilters, + context?: Readonly<{ signal?: AbortSignal }>, + ): Promise>; + create( + command: Readonly<{ name: string }>, + ): Promise>; +}>; + +export function createReferenceFeatureInput( + gateway: ReferenceGateway, +): ReferenceFeatureInput { + return Object.freeze({ + async listResources(filters, context) { + const result = await gateway.list(filters, context); + return result.ok + ? { + ok: true as const, + value: result.value.map((resource) => toReferenceView(resource)), + } + : result; + }, + async createResource(command) { + const result = await gateway.create(command); + return result.ok + ? { ok: true as const, value: toReferenceView(result.value) } + : result; + }, + }); +} diff --git a/src/features/reference-feature/contracts/reference-feature-contract.js b/src/features/reference-feature/contracts/reference-feature-contract.js new file mode 100644 index 00000000..b34fe033 --- /dev/null +++ b/src/features/reference-feature/contracts/reference-feature-contract.js @@ -0,0 +1,75 @@ +import { canonicalize } from "../../../contracts/query-keys.js"; + +export const REFERENCE_FEATURE_ID = "reference-feature"; +const REFERENCE_NAMESPACE = Object.freeze(["reference-resource", 1]); + +export const referenceQueryKeys = Object.freeze({ + all: () => REFERENCE_NAMESPACE, + list: (filters = {}) => + Object.freeze([...REFERENCE_NAMESPACE, "list", canonicalize(filters)]), +}); + +export const REFERENCE_FEATURE_CONTRACT = Object.freeze({ + featureId: REFERENCE_FEATURE_ID, + routes: Object.freeze({ + REFERENCE_RESOURCE_LIST: Object.freeze({ + routeId: "REFERENCE_RESOURCE_LIST", + path: "/examples/reference-resources", + paramsSchema: null, + searchSchema: "ReferenceResourceListQuery", + access: "integration-defined", + loadingSurface: "reference-resource-list", + errorSurface: "feature-boundary", + chunkId: "route-reference-resources", + title: "Reference feature", + navigationLabel: "Reference feature", + navigationOrder: 50, + }), + }), + routeRuntimeContracts: Object.freeze({ + REFERENCE_RESOURCE_LIST: Object.freeze({ + routeId: "REFERENCE_RESOURCE_LIST", + moduleId: "reference-resource-page", + paramsCodec: "none", + searchCodec: "ReferenceResourceListQuery", + }), + }), + apiOperations: Object.freeze({ + LIST_REFERENCE_RESOURCES: Object.freeze({ + method: "GET", + path: "/api/reference-resources", + operationId: "LIST_REFERENCE_RESOURCES", + auth: "external-session", + timeoutMs: null, + idempotency: "safe", + retry: "runtime", + requestSource: "search", + requestSchema: "ReferenceResourceListQuery", + responseSchema: "ReferenceResourceListPayload", + owner: "feature-frontend-reference-feature-vertical-slice", + }), + CREATE_REFERENCE_RESOURCE: Object.freeze({ + method: "POST", + path: "/api/reference-resources", + operationId: "CREATE_REFERENCE_RESOURCE", + auth: "external-session", + timeoutMs: null, + idempotency: "keyed", + retry: "runtime", + requestSource: "body", + requestSchema: "CreateReferenceResourceCommand", + responseSchema: "ReferenceResourcePayload", + owner: "feature-frontend-reference-feature-vertical-slice", + }), + }), + queryRegistry: Object.freeze({ + REFERENCE_RESOURCE: Object.freeze({ + namespace: REFERENCE_NAMESPACE, + serialization: "canonical-object-order", + identity: "no-pii-token-or-raw-url", + invalidation: "reference resource namespace after successful mutation", + version: 1, + persistence: "disabled", + }), + }), +}); diff --git a/src/features/reference-feature/contracts/reference-mapper.ts b/src/features/reference-feature/contracts/reference-mapper.ts new file mode 100644 index 00000000..634732b5 --- /dev/null +++ b/src/features/reference-feature/contracts/reference-mapper.ts @@ -0,0 +1,54 @@ +import { + createReferenceResource, + type ReferenceResource, +} from "../domain/reference-resource.js"; + +export type ReferenceResourceView = Readonly<{ + resourceId: string; + title: string; + createdAtLabel: string | null; + optimistic?: boolean; +}>; + +function mapReferenceDto(value: unknown): ReferenceResource { + if (!value || typeof value !== "object") { + throw new TypeError("Validated reference DTO is required"); + } + const dto = value as Record; + if (typeof dto.id !== "string" || typeof dto.name !== "string") { + throw new TypeError("Validated reference DTO invariants were breached"); + } + return createReferenceResource({ + id: dto.id, + displayName: dto.name, + createdAt: typeof dto.createdAt === "string" ? dto.createdAt : null, + }); +} + +export function mapReferenceOperation( + operationId: string, + payload: unknown, +): ReferenceResource | readonly ReferenceResource[] { + if (operationId === "LIST_REFERENCE_RESOURCES") { + if (!Array.isArray(payload)) throw new TypeError("Expected a reference list"); + return payload.map(mapReferenceDto); + } + if (operationId === "CREATE_REFERENCE_RESOURCE") { + return mapReferenceDto(payload); + } + throw new TypeError(`No reference mapper registered for ${operationId}`); +} + +export function toReferenceView( + resource: ReferenceResource, + formatDate: (value: Date) => string = (value) => + new Intl.DateTimeFormat("ko-KR").format(value), +): ReferenceResourceView { + return Object.freeze({ + resourceId: resource.id, + title: resource.displayName, + createdAtLabel: resource.createdAt + ? formatDate(new Date(resource.createdAt)) + : null, + }); +} diff --git a/src/features/reference-feature/contracts/reference-schemas.ts b/src/features/reference-feature/contracts/reference-schemas.ts new file mode 100644 index 00000000..08d80669 --- /dev/null +++ b/src/features/reference-feature/contracts/reference-schemas.ts @@ -0,0 +1,67 @@ +import { z } from "zod"; + +export const referenceResourceListQuerySchema = z + .object({ + cursor: z.string().min(1).optional(), + limit: z.coerce.number().int().min(1).max(100).default(20), + tags: z + .preprocess( + (value) => + value === undefined + ? undefined + : Array.isArray(value) + ? value + : [value], + z.array(z.string().trim().min(1)), + ) + .optional(), + }) + .strict(); + +const referenceResourceDtoSchema = z + .object({ + id: z.string().min(1), + name: z.string().min(1), + createdAt: z.string().datetime().optional(), + }) + .strict(); + +const payloadSchemas = { + ReferenceResourceListPayload: z.array(referenceResourceDtoSchema), + ReferenceResourcePayload: referenceResourceDtoSchema, +} satisfies Record; + +const requestSchemas = { + ReferenceResourceListQuery: referenceResourceListQuerySchema, + CreateReferenceResourceCommand: z + .object({ + name: z.string().trim().min(1).max(120), + }) + .strict(), +} satisfies Record; + +function project(result: z.ZodSafeParseResult) { + return result.success + ? ({ success: true as const, data: structuredClone(result.data) }) + : ({ + success: false as const, + issues: result.error.issues.map((issue) => ({ + path: issue.path.join("."), + code: issue.code, + })), + }); +} + +export function validateReferencePayload(schemaId: string, value: unknown) { + const schema = payloadSchemas[schemaId as keyof typeof payloadSchemas]; + return schema + ? project(schema.safeParse(value)) + : { success: false as const, issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }] }; +} + +export function validateReferenceRequest(schemaId: string, value: unknown) { + const schema = requestSchemas[schemaId as keyof typeof requestSchemas]; + return schema + ? project(schema.safeParse(value)) + : { success: false as const, issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }] }; +} diff --git a/src/features/reference-feature/domain/reference-resource.ts b/src/features/reference-feature/domain/reference-resource.ts new file mode 100644 index 00000000..4aba209b --- /dev/null +++ b/src/features/reference-feature/domain/reference-resource.ts @@ -0,0 +1,14 @@ +export type ReferenceResource = Readonly<{ + id: string; + displayName: string; + createdAt: string | null; +}>; + +export function createReferenceResource( + values: ReferenceResource, +): ReferenceResource { + if (!values.id || !values.displayName) { + throw new TypeError("Reference resource invariants require id and displayName"); + } + return Object.freeze({ ...values }); +} diff --git a/src/features/reference-feature/presentation/reference-feature-runtime.tsx b/src/features/reference-feature/presentation/reference-feature-runtime.tsx new file mode 100644 index 00000000..cd16f99b --- /dev/null +++ b/src/features/reference-feature/presentation/reference-feature-runtime.tsx @@ -0,0 +1,14 @@ +import { lazy } from "react"; + +import { referenceResourceListQuerySchema } from "../contracts/reference-schemas.js"; + +export const REFERENCE_FEATURE_ROUTE_CODECS = { + ReferenceResourceListQuery: referenceResourceListQuerySchema, +} as const; + +export const REFERENCE_FEATURE_ROUTE_RUNTIME = { + REFERENCE_RESOURCE_LIST: Object.freeze({ + moduleId: "reference-resource-page", + Component: lazy(() => import("./reference-resource-page.js")), + }), +} as const; diff --git a/src/features/reference-feature/presentation/reference-resource-page.tsx b/src/features/reference-feature/presentation/reference-resource-page.tsx new file mode 100644 index 00000000..c65a4f73 --- /dev/null +++ b/src/features/reference-feature/presentation/reference-resource-page.tsx @@ -0,0 +1,60 @@ +import { useState, type FormEvent } from "react"; + +import { AsyncSurface } from "../../../presentation/components/async-surface.jsx"; +import { Button } from "../../../presentation/components/ui/button.jsx"; +import { PageHeader } from "../../../presentation/components/page-header.jsx"; +import { useReferenceFeature } from "./use-reference-feature.js"; + +export default function ReferenceResourcePage() { + const { filters, query, mutation } = useReferenceFeature(); + const [name, setName] = useState(""); + + async function submit(event: FormEvent) { + event.preventDefault(); + const result = await mutation.submit({ name }); + if (result.ok) setName(""); + } + + return ( +
+ +

+ limit {filters.limit} + {filters.tags?.length ? ` · tags ${filters.tags.join(", ")}` : ""} +

+ +
    + {(query.data ?? []).map((resource) => ( +
  • + {resource.title} +
  • + ))} +
+
+ +
void submit(event)}> + + setName(event.currentTarget.value)} + required + /> + +
+
+
+ ); +} diff --git a/src/features/reference-feature/presentation/use-reference-feature.ts b/src/features/reference-feature/presentation/use-reference-feature.ts new file mode 100644 index 00000000..8a4def4b --- /dev/null +++ b/src/features/reference-feature/presentation/use-reference-feature.ts @@ -0,0 +1,62 @@ +import { useApplication } from "../../../presentation/providers/application-provider.js"; +import { + useApplicationMutation, + useApplicationQuery, +} from "../../../presentation/adapters/query/application-query.js"; +import { useRouteInput } from "../../../presentation/routes/app-router.js"; +import type { ReferenceResourceView } from "../contracts/reference-mapper.js"; +import { + REFERENCE_FEATURE_ID, + referenceQueryKeys, +} from "../contracts/reference-feature-contract.js"; +import type { + ReferenceFeatureInput, + ReferenceListFilters, +} from "../application/reference-feature-api.js"; + +function useReferenceFeatureInput(): ReferenceFeatureInput { + const candidate = useApplication().features.get(REFERENCE_FEATURE_ID); + if ( + !candidate || + typeof candidate !== "object" || + typeof (candidate as ReferenceFeatureInput).listResources !== "function" || + typeof (candidate as ReferenceFeatureInput).createResource !== "function" + ) { + throw new Error("Reference feature application input is invalid"); + } + return candidate as ReferenceFeatureInput; +} + +export function useReferenceFeature() { + const input = useReferenceFeatureInput(); + const routeInput = useRouteInput(); + const filters = routeInput.search as ReferenceListFilters; + const queryKey = referenceQueryKeys.list(filters); + const query = useApplicationQuery({ + queryKey, + execute: ({ signal }) => input.listResources(filters, { signal }), + }); + const mutation = useApplicationMutation({ + execute: input.createResource, + invalidate: [referenceQueryKeys.all()], + currentData: true, + optimistic: { + queryKey, + update(previous, command: Readonly<{ name: string }>) { + const current = Array.isArray(previous) + ? (previous as readonly ReferenceResourceView[]) + : []; + return [ + ...current, + { + resourceId: `optimistic:${command.name}`, + title: command.name, + createdAtLabel: null, + optimistic: true, + }, + ]; + }, + }, + }); + return Object.freeze({ filters, query, mutation }); +} diff --git a/src/presentation/layouts/app-shell.jsx b/src/presentation/layouts/app-shell.jsx index 6147dd72..04ed26d4 100644 --- a/src/presentation/layouts/app-shell.jsx +++ b/src/presentation/layouts/app-shell.jsx @@ -1,7 +1,10 @@ import { useEffect, useState } from "react"; import { NavLink, Outlet, useLocation } from "react-router-dom"; -import { NAVIGATION_ROUTES, routePath } from "../../contracts/routes.js"; +import { + NAVIGATION_ROUTES, + routePath, +} from "../../features/installed-feature-contracts.js"; import { useSession } from "../providers/session-provider.jsx"; import { useTheme } from "../providers/theme-provider.jsx"; diff --git a/src/presentation/pages/home-page.jsx b/src/presentation/pages/home-page.jsx index d13fefb2..a35bb5af 100644 --- a/src/presentation/pages/home-page.jsx +++ b/src/presentation/pages/home-page.jsx @@ -1,7 +1,7 @@ import { useEffect, useState } from "react"; import { Link } from "react-router-dom"; -import { routePath } from "../../contracts/routes.js"; +import { routePath } from "../../features/installed-feature-contracts.js"; import { PageHeader } from "../components/page-header.jsx"; import { useApplication } from "../providers/application-provider.js"; diff --git a/src/presentation/pages/not-found-page.jsx b/src/presentation/pages/not-found-page.jsx index a1463b70..187b584a 100644 --- a/src/presentation/pages/not-found-page.jsx +++ b/src/presentation/pages/not-found-page.jsx @@ -1,6 +1,6 @@ import { Link } from "react-router-dom"; -import { routePath } from "../../contracts/routes.js"; +import { routePath } from "../../features/installed-feature-contracts.js"; import { PageHeader } from "../components/page-header.jsx"; export default function NotFoundPage() { diff --git a/src/presentation/pages/sample-contract-page.jsx b/src/presentation/pages/sample-contract-page.jsx deleted file mode 100644 index a8f8aab8..00000000 --- a/src/presentation/pages/sample-contract-page.jsx +++ /dev/null @@ -1,23 +0,0 @@ -import { PageHeader } from "../components/page-header.jsx"; -import { useSession } from "../providers/session-provider.jsx"; - -export default function SampleContractPage() { - const { sessionState } = useSession(); - - return ( -
- -
-

라우트 접근 허용

-

- 현재 세션 상태는 {sessionState}입니다. 서버의 - 권한 검증은 이 클라이언트 라우트 정책과 별도로 유지해야 합니다. -

-
-
- ); -} diff --git a/src/presentation/routes/app-router.tsx b/src/presentation/routes/app-router.tsx index a528c81d..74b93581 100644 --- a/src/presentation/routes/app-router.tsx +++ b/src/presentation/routes/app-router.tsx @@ -21,8 +21,8 @@ import { import { getRoute, ROUTE_REGISTRY, - type RouteDefinition, -} from "../../contracts/routes.js"; +} from "../../features/installed-feature-contracts.js"; +import type { RouteDefinition } from "../../contracts/routes.js"; import { FeatureBoundary, RouteBoundary, @@ -43,7 +43,7 @@ import { type ParsedRouteInput, type RouteId, } from "./route-codecs.js"; -import { ROUTE_RUNTIME } from "./route-runtime.js"; +import { ROUTE_RUNTIME } from "../../features/installed-feature-runtimes.js"; const RouteInputContext = createContext(null); diff --git a/src/presentation/routes/navigation-policy.js b/src/presentation/routes/navigation-policy.js index 51707937..d08e2223 100644 --- a/src/presentation/routes/navigation-policy.js +++ b/src/presentation/routes/navigation-policy.js @@ -1,4 +1,4 @@ -import { getRoute } from "../../contracts/routes.js"; +import { getRoute } from "../../features/installed-feature-contracts.js"; /** * @param {string} routeId diff --git a/src/presentation/routes/platform-route-codecs.ts b/src/presentation/routes/platform-route-codecs.ts new file mode 100644 index 00000000..830f2e6f --- /dev/null +++ b/src/presentation/routes/platform-route-codecs.ts @@ -0,0 +1,6 @@ +import { z } from "zod"; + +export const PLATFORM_ROUTE_CODECS = { + none: z.object({}).strict(), + NotFoundSplat: z.object({ "*": z.string().optional() }).strict(), +} as const; diff --git a/src/presentation/routes/route-codecs.ts b/src/presentation/routes/route-codecs.ts index 93761651..6391cf04 100644 --- a/src/presentation/routes/route-codecs.ts +++ b/src/presentation/routes/route-codecs.ts @@ -1,36 +1,8 @@ -import { z } from "zod"; - -import { getRoute } from "../../contracts/routes.js"; -import { ROUTE_RUNTIME_CONTRACT } from "../../contracts/route-runtime-contract.js"; +import { getRoute, ROUTE_RUNTIME_CONTRACT } from "../../features/installed-feature-contracts.js"; +import { ROUTE_CODECS } from "../../features/installed-feature-runtimes.js"; export type RouteId = keyof typeof ROUTE_RUNTIME_CONTRACT; -const emptyCodec = z.object({}).strict(); -const notFoundSplatCodec = z.object({ "*": z.string().optional() }).strict(); -const sampleResourceListQuery = z - .object({ - cursor: z.string().min(1).optional(), - limit: z.coerce.number().int().min(1).max(100).default(20), - tags: z - .preprocess( - (value) => - value === undefined - ? undefined - : Array.isArray(value) - ? value - : [value], - z.array(z.string().trim().min(1)), - ) - .optional(), - }) - .strict(); - -const codecs = { - none: emptyCodec, - NotFoundSplat: notFoundSplatCodec, - SampleResourceListQuery: sampleResourceListQuery, -} as const; - export type ParsedRouteInput = Readonly<{ routeId: RouteId; params: Readonly>; @@ -44,17 +16,23 @@ export type RouteInputResult = code: "ROUTE_PARAMS_INVALID" | "ROUTE_SEARCH_INVALID"; }>; +function codecById(codecId: string) { + const codec = ROUTE_CODECS[codecId as keyof typeof ROUTE_CODECS]; + if (!codec) throw new TypeError(`Unregistered route codec: ${codecId}`); + return codec; +} + export function parseRouteInput( routeId: RouteId, rawParams: Readonly>, rawSearch: URLSearchParams, ): RouteInputResult { const runtime = ROUTE_RUNTIME_CONTRACT[routeId]; - const params = codecs[runtime.paramsCodec].safeParse(rawParams); + const params = codecById(runtime.paramsCodec).safeParse(rawParams); if (!params.success) { return { success: false, code: "ROUTE_PARAMS_INVALID" }; } - const search = codecs[runtime.searchCodec].safeParse( + const search = codecById(runtime.searchCodec).safeParse( searchRecord(rawSearch), ); if (!search.success) { @@ -84,14 +62,18 @@ export function buildRouteUrl( throw new TypeError("The not-found route cannot build a canonical URL"); } const runtime = ROUTE_RUNTIME_CONTRACT[routeId]; - const params = codecs[runtime.paramsCodec].parse(input.params ?? {}); - const search = codecs[runtime.searchCodec].parse(input.search ?? {}); + const params = codecById(runtime.paramsCodec).parse(input.params ?? {}); + const search = codecById(runtime.searchCodec).parse(input.search ?? {}); const parsedParams: Record = { ...params }; const parsedSearch: Record = { ...search }; let path = definition.path; path = path.replace( /:([A-Za-z][A-Za-z0-9_]*)|\{([A-Za-z][A-Za-z0-9_]*)\}/g, - (_token, colonName: string | undefined, braceName: string | undefined) => { + ( + _token: string, + colonName: string | undefined, + braceName: string | undefined, + ) => { const name = colonName ?? braceName ?? ""; const value = parsedParams[name]; if (typeof value !== "string" && typeof value !== "number") { diff --git a/src/presentation/routes/route-runtime.tsx b/src/presentation/routes/route-runtime.tsx index 79551253..fc688694 100644 --- a/src/presentation/routes/route-runtime.tsx +++ b/src/presentation/routes/route-runtime.tsx @@ -4,8 +4,7 @@ import { type LazyExoticComponent, } from "react"; -import { ROUTE_RUNTIME_CONTRACT } from "../../contracts/route-runtime-contract.js"; -import type { RouteId } from "./route-codecs.js"; +import { PLATFORM_ROUTE_RUNTIME_CONTRACT } from "../../contracts/route-runtime-contract.js"; type RouteModule = Readonly<{ default: ComponentType }>; type RouteRuntime = Readonly<{ @@ -14,16 +13,16 @@ type RouteRuntime = Readonly<{ }>; function runtime( - routeId: RouteId, + routeId: keyof typeof PLATFORM_ROUTE_RUNTIME_CONTRACT, load: () => Promise, ): RouteRuntime { return Object.freeze({ - moduleId: ROUTE_RUNTIME_CONTRACT[routeId].moduleId, + moduleId: PLATFORM_ROUTE_RUNTIME_CONTRACT[routeId].moduleId, Component: lazy(load), }); } -export const ROUTE_RUNTIME = { +export const PLATFORM_ROUTE_RUNTIME = { APP_HOME: runtime("APP_HOME", () => import("../pages/home-page.jsx")), EXAMPLES_UI: runtime( "EXAMPLES_UI", @@ -37,12 +36,8 @@ export const ROUTE_RUNTIME = { "EXAMPLES_AUTH", () => import("../examples/auth-example-page.jsx"), ), - SAMPLE_RESOURCE_LIST: runtime( - "SAMPLE_RESOURCE_LIST", - () => import("../pages/sample-contract-page.jsx"), - ), NOT_FOUND: runtime( "NOT_FOUND", () => import("../pages/not-found-page.jsx"), ), -} satisfies Record; +} satisfies Record; diff --git a/src/sample/contract-fixture/design-token-showcase.jsx b/src/sample/contract-fixture/design-token-showcase.jsx deleted file mode 100644 index 0629453f..00000000 --- a/src/sample/contract-fixture/design-token-showcase.jsx +++ /dev/null @@ -1,15 +0,0 @@ -export function DesignTokenShowcase() { - return ( -
-

- Design token fixture -

-

- Semantic tokens style loading, empty, and terminal surfaces. -

- -
- ); -} diff --git a/src/sample/contract-fixture/sample-facade.js b/src/sample/contract-fixture/sample-facade.js deleted file mode 100644 index 62f45389..00000000 --- a/src/sample/contract-fixture/sample-facade.js +++ /dev/null @@ -1,53 +0,0 @@ -import { toResourceViewModel } from "../../application/view-models/resource-view-model.js"; -import { queryKeys } from "../../contracts/query-keys.js"; - -/** - * @param {{ - * http: { execute(operationId: string, input?: Record): Promise< - * {ok: true, value: unknown} | {ok: false, error: import("../../contracts/errors.js").ApiFailure} - * > }, - * cache: import("../../application/ports/query-cache-port.js").QueryCachePort - * }} ports - */ -export function createSampleFacade(ports) { - return Object.freeze({ - async listResources(filters = {}) { - const key = queryKeys.resource.list(filters); - const result = await ports.http.execute("LIST_SAMPLE_RESOURCES", { - routeId: "SAMPLE_RESOURCE_LIST", - }); - if (!result.ok) return result; - - const models = - /** @type {Array} */ ( - result.value - ); - const cached = ports.cache.write(key, models); - if (!cached.ok) return cached; - return { - ok: /** @type {true} */ (true), - value: models.map((model) => toResourceViewModel(model)), - }; - }, - - /** @param {{ name: string }} command */ - async createResource(command) { - const result = await ports.http.execute("CREATE_SAMPLE_RESOURCE", { - body: command, - routeId: "SAMPLE_RESOURCE_LIST", - }); - if (!result.ok) return result; - - const invalidated = await ports.cache.invalidate(queryKeys.resource.all()); - if (!invalidated.ok) return invalidated; - return { - ok: /** @type {true} */ (true), - value: toResourceViewModel( - /** @type {import("../../domain/models/resource.js").Resource} */ ( - result.value - ), - ), - }; - }, - }); -} diff --git a/src/sample/contract-fixture/sample-resource-page.jsx b/src/sample/contract-fixture/sample-resource-page.jsx deleted file mode 100644 index 6ace8ca7..00000000 --- a/src/sample/contract-fixture/sample-resource-page.jsx +++ /dev/null @@ -1,61 +0,0 @@ -import { useEffect, useState } from "react"; - -import { deriveAsyncState } from "../../application/view-models/async-state.js"; -import { AsyncSurface } from "../../presentation/components/async-surface.jsx"; - -/** - * @typedef {{ - * loading: boolean, - * resources?: Array<{resourceId: string, title: string, createdAtLabel: string | null}>, - * failure?: import("../../contracts/errors.js").ApiFailure - * }} SamplePageState - */ - -/** - * @param {{ - * facade: ReturnType - * }} props - */ -export function SampleResourcePage({ facade }) { - const [result, setResult] = useState( - /** @type {SamplePageState} */ ({ - loading: true, - resources: undefined, - failure: undefined, - }), - ); - - useEffect(() => { - let active = true; - void facade.listResources().then((outcome) => { - if (!active) return; - setResult( - outcome.ok - ? { loading: false, resources: outcome.value, failure: undefined } - : { loading: false, resources: undefined, failure: outcome.error }, - ); - }); - return () => { - active = false; - }; - }, [facade]); - - const state = deriveAsyncState({ - isInitialLoading: result.loading, - data: result.resources, - failure: result.failure, - }); - - return ( -
-

샘플 리소스

- -
    - {(result.resources ?? []).map((resource) => ( -
  • {resource.title}
  • - ))} -
-
-
- ); -} diff --git a/tests/component/design-tokens.test.jsx b/tests/component/design-tokens.test.jsx index 44e8db80..59425904 100644 --- a/tests/component/design-tokens.test.jsx +++ b/tests/component/design-tokens.test.jsx @@ -3,12 +3,17 @@ import { render, screen } from "@testing-library/react"; import { describe, expect, it } from "vitest"; -import { DesignTokenShowcase } from "../../src/sample/contract-fixture/design-token-showcase.jsx"; +import { Button } from "../../src/presentation/components/ui/button.jsx"; +import { Card } from "../../src/presentation/components/ui/card.jsx"; describe("design-token fixture", () => { it("uses static semantic primitive classes", () => { - render(); - expect(screen.getByRole("region")).toHaveClass("ui-panel"); + render( + + + , + ); + expect(screen.getByRole("article")).toHaveClass("ui-card"); expect(screen.getByRole("button")).toHaveClass("ui-button"); }); }); diff --git a/tests/component/router.test.jsx b/tests/component/router.test.jsx index 29d1b802..c89c296e 100644 --- a/tests/component/router.test.jsx +++ b/tests/component/router.test.jsx @@ -2,34 +2,29 @@ import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import { describe, expect, it, vi } from "vitest"; +import { describe, expect, it } from "vitest"; -import { - createAnonymousSessionAdapter, - createDemoSessionAdapter, -} from "../../src/adapters/auth/external-session-adapter.js"; +import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.js"; import { ApplicationProvider } from "../../src/presentation/providers/application-provider.js"; import { AppRouter } from "../../src/presentation/routes/app-router.jsx"; import { createTestApplication } from "../helpers/create-test-application.js"; -/** - * @param {import("../../src/application/ports/auth-session-port.js").AuthSessionPort} session - * @param {Parameters[0]} [overrides] - */ -function renderRouter(session, overrides = {}) { +function renderRouter() { return render( , ); } -describe("application router", () => { - it("renders the app shell and not-found route without an API request", async () => { +describe("generic application router", () => { + it("renders the app shell and not-found route without a feature input", async () => { window.history.pushState({}, "", "/missing"); - renderRouter(createAnonymousSessionAdapter()); + renderRouter(); expect( await screen.findByRole("heading", { @@ -40,10 +35,10 @@ describe("application router", () => { expect(screen.getByRole("main")).toBeVisible(); }); - it("navigates between registry-backed example routes", async () => { + it("navigates between registry-backed platform routes", async () => { const user = userEvent.setup(); window.history.pushState({}, "", "/"); - renderRouter(createAnonymousSessionAdapter()); + renderRouter(); await user.click( await screen.findByRole("link", { name: "UI 구성요소" }), @@ -58,62 +53,4 @@ describe("application router", () => { screen.getByRole("heading", { name: "UI 구성요소", level: 1 }), ).toHaveFocus(); }); - - it("reacts to demo sign-in and opens the protected integration route", async () => { - const user = userEvent.setup(); - const authSession = createDemoSessionAdapter(); - window.history.pushState({}, "", "/sample/resources"); - renderRouter(authSession); - - expect( - await screen.findByRole("heading", { name: "세션이 필요합니다." }), - ).toBeVisible(); - await user.click(screen.getByRole("button", { name: "로그인 시작" })); - - expect( - await screen.findByRole("heading", { name: "보호된 연동 지점" }), - ).toBeVisible(); - expect(screen.getByText("인증됨")).toBeVisible(); - }); - - it("fails closed when the auth integration does not change state", async () => { - const user = userEvent.setup(); - window.history.pushState({}, "", "/sample/resources"); - renderRouter(createAnonymousSessionAdapter()); - - await user.click( - await screen.findByRole("button", { name: "로그인 시작" }), - ); - - expect( - screen.getByRole("heading", { name: "세션이 필요합니다." }), - ).toBeVisible(); - }); - - it("rejects invalid route search before any application query runs", async () => { - const getCurrent = vi.fn(async () => ({ - buildId: "test-build", - releaseId: "test-release", - configSchemaVersion: "1", - apiContractVersion: "1", - assetManifestHash: "test-hash", - routeChunks: { "route-sample-resources": "assets/sample.js" }, - })); - window.history.pushState({}, "", "/sample/resources?limit=invalid"); - renderRouter(createDemoSessionAdapter("authenticated"), { - releaseInfo: { getCurrent, refresh: getCurrent }, - }); - - expect( - await screen.findByRole("heading", { - name: "올바르지 않은 주소입니다.", - }), - ).toBeVisible(); - expect(screen.getAllByRole("heading", { level: 1 })).toHaveLength(1); - expect(screen.getByText("안전한 탐색 링크를 사용해 주세요.")).toHaveAttribute( - "data-route-error", - "ROUTE_SEARCH_INVALID", - ); - expect(getCurrent).not.toHaveBeenCalled(); - }); }); diff --git a/tests/component/runtime-application.test.jsx b/tests/component/runtime-application.test.jsx index b3bdb44b..3e5a49f8 100644 --- a/tests/component/runtime-application.test.jsx +++ b/tests/component/runtime-application.test.jsx @@ -35,7 +35,6 @@ const releaseManifest = { "route-examples-ui": "assets/ui.js", "route-examples-states": "assets/states.js", "route-examples-auth": "assets/auth.js", - "route-sample-resources": "assets/sample.js", "route-not-found": "assets/not-found.js", }, }; diff --git a/tests/component/sample-resource-page.test.jsx b/tests/component/sample-resource-page.test.jsx deleted file mode 100644 index 63dc5533..00000000 --- a/tests/component/sample-resource-page.test.jsx +++ /dev/null @@ -1,70 +0,0 @@ -// @vitest-environment jsdom - -import { render, screen } from "@testing-library/react"; -import { describe, expect, it } from "vitest"; - -import { SampleResourcePage } from "../../src/sample/contract-fixture/sample-resource-page.jsx"; - -describe("removable sample feature page", () => { - it("renders the API-to-view-model result through AsyncSurface", async () => { - /** @type {Parameters[0]["facade"]} */ - const facade = { - listResources: async () => ({ - ok: /** @type {const} */ (true), - value: [ - { - resourceId: "resource-1", - title: "Example", - createdAtLabel: null, - }, - ], - }), - createResource: async () => ({ - ok: /** @type {const} */ (true), - value: { - resourceId: "resource-created", - title: "Created", - createdAtLabel: null, - }, - }), - }; - render(); - - expect(screen.getByLabelText("불러오는 중")).toBeVisible(); - expect(await screen.findByText("Example")).toBeVisible(); - }); - - it("renders normalized terminal errors without raw DTO fields", async () => { - /** @type {Parameters[0]["facade"]} */ - const facade = { - listResources: async () => ({ - ok: /** @type {const} */ (false), - error: { - kind: "SERVER_FAILURE", - code: "SERVER_FAILURE", - retryable: true, - operationId: "LIST_SAMPLE_RESOURCES", - attemptCount: 1, - userMessageKey: "error.server_failure", - action: "retry", - }, - }), - createResource: async () => ({ - ok: /** @type {const} */ (true), - value: { - resourceId: "resource-created", - title: "Created", - createdAtLabel: null, - }, - }), - }; - render(); - - const alert = await screen.findByRole("alert"); - expect(alert).toHaveTextContent("요청을 완료하지 못했습니다."); - expect(alert).toHaveAttribute( - "data-message-key", - "error.server_failure", - ); - }); -}); diff --git a/tests/e2e/accessibility.spec.js b/tests/e2e/accessibility.spec.js index 76a4bdba..8fb53894 100644 --- a/tests/e2e/accessibility.spec.js +++ b/tests/e2e/accessibility.spec.js @@ -1,14 +1,10 @@ import AxeBuilder from "@axe-core/playwright"; import { expect, test } from "@playwright/test"; +import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.js"; -for (const route of [ - "/", - "/examples/ui", - "/examples/states", - "/examples/auth", - "/sample/resources", - "/not-found", -]) { +for (const route of Object.values(ROUTE_REGISTRY).map((definition) => + definition.path === "*" ? "/not-found" : definition.path, +)) { test(`@a11y ${route} has no critical or serious axe violations`, async ({ page, }) => { diff --git a/tests/e2e/app-shell.spec.js b/tests/e2e/app-shell.spec.js index f2bc6be9..d4d7e077 100644 --- a/tests/e2e/app-shell.spec.js +++ b/tests/e2e/app-shell.spec.js @@ -1,4 +1,5 @@ import { expect, test } from "@playwright/test"; +import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.js"; test("boots the public app shell", async ({ page }) => { await page.goto("/"); @@ -27,7 +28,11 @@ test("navigates to a registry-backed example without a page reload", async ({ test("opens the protected integration route through the local demo seam", async ({ page, }) => { - await page.goto("/sample/resources"); + const protectedRoute = Object.values(ROUTE_REGISTRY).find( + (definition) => definition.access === "integration-defined", + ); + if (!protectedRoute) throw new Error("An integration route is required"); + await page.goto(protectedRoute.path); await expect( page.getByRole("heading", { name: "세션이 필요합니다." }), ).toBeVisible(); @@ -35,7 +40,7 @@ test("opens the protected integration route through the local demo seam", async await page.getByRole("button", { name: "로그인 시작" }).click(); await expect( - page.getByRole("heading", { name: "보호된 연동 지점" }), + page.getByRole("heading", { name: protectedRoute.title }), ).toBeVisible(); await expect(page.getByText("인증됨")).toBeVisible(); }); diff --git a/tests/features/reference-feature/reference-contract.test.ts b/tests/features/reference-feature/reference-contract.test.ts new file mode 100644 index 00000000..c1d95769 --- /dev/null +++ b/tests/features/reference-feature/reference-contract.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from "vitest"; + +import { + buildRouteUrl, + parseRouteInput, +} from "../../../src/presentation/routes/route-codecs.js"; +import { + mapReferenceOperation, + toReferenceView, +} from "../../../src/features/reference-feature/contracts/reference-mapper.js"; +import { + validateReferencePayload, + validateReferenceRequest, +} from "../../../src/features/reference-feature/contracts/reference-schemas.js"; +import { + REFERENCE_FEATURE_CONTRACT, + referenceQueryKeys, +} from "../../../src/features/reference-feature/contracts/reference-feature-contract.js"; + +describe("reference feature boundary contracts", () => { + it("round-trips one canonical filter through URL and query identity", () => { + const filters = { + tags: ["open", "new"], + cursor: "a/b", + limit: 5, + }; + const url = buildRouteUrl("REFERENCE_RESOURCE_LIST", { search: filters }); + expect(url).toBe( + "/examples/reference-resources?cursor=a%2Fb&limit=5&tags=open&tags=new", + ); + const parsed = parseRouteInput( + "REFERENCE_RESOURCE_LIST", + {}, + new URL(url, "https://app.test").searchParams, + ); + expect(parsed).toMatchObject({ + success: true, + data: { search: filters }, + }); + expect(referenceQueryKeys.list(filters).at(-1)).toEqual(filters); + }); + + it("rejects unknown search and malformed DTO before mapping", () => { + expect( + parseRouteInput( + "REFERENCE_RESOURCE_LIST", + {}, + new URLSearchParams("unknown=value"), + ), + ).toEqual({ success: false, code: "ROUTE_SEARCH_INVALID" }); + expect( + validateReferencePayload("ReferenceResourceListPayload", [ + { id: "unsafe", name: 42 }, + ]), + ).toMatchObject({ success: false }); + expect(() => + mapReferenceOperation("LIST_REFERENCE_RESOURCES", [ + { id: "unsafe", name: 42 }, + ]), + ).toThrow(); + }); + + it("normalizes request input and maps only owned domain fields", () => { + expect( + validateReferenceRequest("CreateReferenceResourceCommand", { + name: " Example ", + }), + ).toMatchObject({ success: true, data: { name: "Example" } }); + const model = mapReferenceOperation("CREATE_REFERENCE_RESOURCE", { + id: "reference-1", + name: "Example", + createdAt: "2026-07-26T00:00:00.000Z", + }); + if (!("id" in model)) throw new Error("expected one model"); + expect(toReferenceView(model, () => "formatted")).toEqual({ + resourceId: "reference-1", + title: "Example", + createdAtLabel: "formatted", + }); + }); + + it("owns route, operation and query contributions in one removable contract", () => { + expect(Object.keys(REFERENCE_FEATURE_CONTRACT.routes)).toEqual([ + "REFERENCE_RESOURCE_LIST", + ]); + expect(Object.keys(REFERENCE_FEATURE_CONTRACT.apiOperations)).toEqual([ + "LIST_REFERENCE_RESOURCES", + "CREATE_REFERENCE_RESOURCE", + ]); + expect(Object.keys(REFERENCE_FEATURE_CONTRACT.queryRegistry)).toEqual([ + "REFERENCE_RESOURCE", + ]); + }); +}); diff --git a/tests/features/reference-feature/reference-page.test.tsx b/tests/features/reference-feature/reference-page.test.tsx new file mode 100644 index 00000000..20293cdf --- /dev/null +++ b/tests/features/reference-feature/reference-page.test.tsx @@ -0,0 +1,234 @@ +// @vitest-environment jsdom + +import { + QueryClient, + QueryClientProvider, +} from "@tanstack/react-query"; +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, expect, it, vi } from "vitest"; + +import { createDemoSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.js"; +import type { + ReferenceFeatureInput, + ReferenceResult, +} from "../../../src/features/reference-feature/application/reference-feature-api.js"; +import { REFERENCE_FEATURE_ID } from "../../../src/features/reference-feature/contracts/reference-feature-contract.js"; +import type { ReferenceResourceView } from "../../../src/features/reference-feature/contracts/reference-mapper.js"; +import { createFailure } from "../../../src/contracts/errors.js"; +import { ApplicationProvider } from "../../../src/presentation/providers/application-provider.js"; +import { AppRouter } from "../../../src/presentation/routes/app-router.js"; +import { createTestApplication } from "../../helpers/create-test-application.js"; + +function renderReference( + input: ReferenceFeatureInput, + url = "/examples/reference-resources?limit=5", +) { + window.history.pushState({}, "", url); + const client = new QueryClient({ + defaultOptions: { + queries: { retry: false, gcTime: Infinity }, + mutations: { retry: false }, + }, + }); + return render( + + + + + , + ); +} + +function inputWith( + overrides: Partial = {}, +): ReferenceFeatureInput { + return { + listResources: async () => ({ ok: true, value: [] }), + createResource: async ({ name }) => ({ + ok: true, + value: { + resourceId: "created", + title: name, + createdAtLabel: null, + }, + }), + ...overrides, + }; +} + +describe("reference feature page states", () => { + it("renders loading, success and empty states through the installed route", async () => { + let resolveList: + | ((result: ReferenceResult) => void) + | undefined; + const pending = new Promise< + ReferenceResult + >((resolve) => { + resolveList = resolve; + }); + const loaded = renderReference( + inputWith({ listResources: async () => pending }), + ); + expect(await screen.findByLabelText("불러오는 중")).toBeVisible(); + resolveList?.({ + ok: true, + value: [ + { + resourceId: "reference-1", + title: "Loaded", + createdAtLabel: null, + }, + ], + }); + expect(await screen.findByText("Loaded")).toBeVisible(); + loaded.unmount(); + + renderReference(inputWith(), "/examples/reference-resources?limit=10"); + expect( + await screen.findByRole("heading", { + name: "표시할 항목이 없습니다.", + }), + ).toBeVisible(); + }); + + it("rejects invalid URL input before the feature application input", async () => { + const listResources = vi.fn(); + renderReference( + inputWith({ listResources }), + "/examples/reference-resources?limit=invalid", + ); + expect( + await screen.findByRole("heading", { + name: "올바르지 않은 주소입니다.", + }), + ).toBeVisible(); + expect(listResources).not.toHaveBeenCalled(); + }); + + it("renders backend forbidden even when the client access hint allowed entry", async () => { + renderReference( + inputWith({ + listResources: async () => ({ + ok: false, + error: createFailure( + "FORBIDDEN", + "LIST_REFERENCE_RESOURCES", + 0, + ), + }), + }), + ); + expect(await screen.findByRole("alert")).toHaveTextContent( + "이 작업을 수행할 권한이 없습니다.", + ); + }); + + it("deduplicates optimistic create and rolls back a conflict", async () => { + const user = userEvent.setup(); + let finish: + | ((result: ReferenceResult) => void) + | undefined; + const createResource = vi.fn( + () => + new Promise>((resolve) => { + finish = resolve; + }), + ); + renderReference( + inputWith({ + listResources: async () => ({ + ok: true, + value: [ + { + resourceId: "existing", + title: "Existing", + createdAtLabel: null, + }, + ], + }), + createResource, + }), + ); + await screen.findByText("Existing"); + await user.type(screen.getByLabelText("새 항목 이름"), "Conflicting"); + const submit = screen.getByRole("button", { name: "추가" }); + await user.dblClick(submit); + + await waitFor(() => expect(createResource).toHaveBeenCalledOnce()); + expect(await screen.findByText("Conflicting")).toHaveAttribute( + "data-optimistic", + "true", + ); + expect(screen.getByText("mutation-pending")).toBeVisible(); + + finish?.({ + ok: false, + error: createFailure( + "CONFLICT", + "CREATE_REFERENCE_RESOURCE", + 0, + ), + }); + expect( + await screen.findByRole("button", { name: "충돌 해결" }), + ).toBeVisible(); + expect(screen.queryByText("Conflicting")).not.toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: "충돌 해결" })); + await waitFor(() => + expect(screen.queryByText("mutation-conflict")).not.toBeInTheDocument(), + ); + }); + + it("keeps stale data visible during refresh failure and recovers on retry", async () => { + const user = userEvent.setup(); + const listResources = vi + .fn() + .mockResolvedValueOnce({ + ok: true, + value: [ + { + resourceId: "existing", + title: "Existing", + createdAtLabel: null, + }, + ], + }) + .mockResolvedValueOnce({ + ok: false, + error: createFailure( + "SERVER_FAILURE", + "LIST_REFERENCE_RESOURCES", + 0, + ), + }) + .mockResolvedValue({ + ok: true, + value: [ + { + resourceId: "recovered", + title: "Recovered", + createdAtLabel: null, + }, + ], + }); + renderReference(inputWith({ listResources })); + await screen.findByText("Existing"); + await user.type(screen.getByLabelText("새 항목 이름"), "Created"); + await user.click(screen.getByRole("button", { name: "추가" })); + + expect(await screen.findByText("stale-degraded")).toBeVisible(); + expect(screen.getByText("Existing")).toBeVisible(); + await user.click(screen.getByRole("button", { name: "다시 시도" })); + expect(await screen.findByText("Recovered")).toBeVisible(); + await waitFor(() => + expect(screen.queryByText("stale-degraded")).not.toBeInTheDocument(), + ); + expect(listResources).toHaveBeenCalledTimes(3); + }); +}); diff --git a/tests/features/reference-feature/reference-production-vertical.test.tsx b/tests/features/reference-feature/reference-production-vertical.test.tsx new file mode 100644 index 00000000..4d0608f6 --- /dev/null +++ b/tests/features/reference-feature/reference-production-vertical.test.tsx @@ -0,0 +1,129 @@ +// @vitest-environment jsdom + +import { HttpResponse, http } from "msw"; +import { setupServer } from "msw/node"; +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + vi, +} from "vitest"; + +import { createRuntimeComposition } from "../../../src/bootstrap/create-runtime-composition.js"; +import { RuntimeApplication } from "../../../src/bootstrap/runtime-application.jsx"; + +const runtimeConfig = { + APP_ENV: "local", + API_BASE_URL: "https://api.test", + REQUEST_TIMEOUT_MS: 10_000, + MAX_RETRY_ATTEMPTS: 0, + TELEMETRY_ENABLED: false, + AUTH_MODE: "demo", + CONFIG_SCHEMA_VERSION: "1", + API_CONTRACT_VERSION: "1", + RELEASE_MANIFEST_URL: "/release-manifest.json", + BUILD_ID: "local-build", + RELEASE_ID: "local-release", +}; +const releaseManifest = { + schemaVersion: 1, + appVersion: "0.1.0", + buildId: "local-build", + commitSha: "local", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "test-hash", + releaseId: "local-release", + builtAt: "2026-07-26T00:00:00.000Z", + routeChunks: { + "route-home": "assets/home.js", + "route-examples-ui": "assets/ui.js", + "route-examples-states": "assets/states.js", + "route-examples-auth": "assets/auth.js", + "route-reference-resources": "assets/reference.js", + "route-not-found": "assets/not-found.js", + }, +}; + +const listRequests = vi.fn(); +const createRequests = vi.fn(); +const resources = [{ id: "reference-1", name: "Existing" }]; +const server = setupServer( + http.get("http://app.test/config.json", () => + HttpResponse.json(runtimeConfig), + ), + http.get("http://app.test/release-manifest.json", () => + HttpResponse.json(releaseManifest), + ), + http.get("https://api.test/api/reference-resources", ({ request }) => { + listRequests(new URL(request.url).search); + return HttpResponse.json({ + success: true, + data: resources, + meta: { requestId: "request-list", traceId: "trace-list" }, + }); + }), + http.post("https://api.test/api/reference-resources", async ({ request }) => { + const body = (await request.json()) as { name: string }; + createRequests(body); + const created = { id: "reference-created", name: body.name }; + resources.push(created); + return HttpResponse.json({ + success: true, + data: created, + meta: { requestId: "request-create", traceId: "trace-create" }, + }); + }), +); + +beforeAll(() => server.listen({ onUnhandledRequest: "error" })); +afterEach(() => { + listRequests.mockClear(); + createRequests.mockClear(); + resources.splice(1); +}); +afterAll(() => server.close()); + +const absoluteFetch: typeof fetch = (input, init) => { + if (input instanceof Request) return fetch(input, init); + const url = new URL( + input instanceof URL ? input.href : input, + "http://app.test", + ); + return fetch(url, init); +}; + +describe("reference feature production vertical path", () => { + it("traverses bootstrap, router, application, HTTP schema/mapper and query cache", async () => { + const user = userEvent.setup(); + const composition = await createRuntimeComposition({ + fetcher: absoluteFetch, + host: {}, + }); + window.history.pushState( + {}, + "", + "/examples/reference-resources?tags=open&tags=new&limit=5", + ); + render(); + + await user.click( + await screen.findByRole("button", { name: "로그인 시작" }), + ); + expect(await screen.findByText("Existing")).toBeVisible(); + expect(listRequests).toHaveBeenCalledWith( + "?limit=5&tags=open&tags=new", + ); + + await user.type(screen.getByLabelText("새 항목 이름"), " Created "); + await user.click(screen.getByRole("button", { name: "추가" })); + expect(await screen.findByText("Created")).toBeVisible(); + expect(createRequests).toHaveBeenCalledWith({ name: "Created" }); + expect(listRequests.mock.calls.length).toBeGreaterThanOrEqual(2); + }); +}); diff --git a/tests/fixtures/typecheck/invalid-route-runtime.ts b/tests/fixtures/typecheck/invalid-route-runtime.ts index 86df3811..143e3586 100644 --- a/tests/fixtures/typecheck/invalid-route-runtime.ts +++ b/tests/fixtures/typecheck/invalid-route-runtime.ts @@ -1,4 +1,4 @@ -import { ROUTE_RUNTIME_CONTRACT } from "../../../src/contracts/route-runtime-contract.js"; +import { ROUTE_RUNTIME_CONTRACT } from "../../../src/features/installed-feature-contracts.js"; type RouteId = keyof typeof ROUTE_RUNTIME_CONTRACT; diff --git a/tests/helpers/create-test-application.js b/tests/helpers/create-test-application.js index c54f83b4..f254c028 100644 --- a/tests/helpers/create-test-application.js +++ b/tests/helpers/create-test-application.js @@ -7,46 +7,48 @@ import { createApplication } from "../../src/application/create-application.js"; * preferences?: import("../../src/application/ports/storage-port.js").StoragePort, * diagnostics?: import("../../src/application/ports/telemetry-port.js").TelemetryPort, * releaseInfo?: import("../../src/application/ports/release-info-port.js").ReleaseInfoPort, - * navigation?: { reload(): void } + * navigation?: { reload(): void }, + * featureInputs?: Readonly> * }} [overrides] */ export function createTestApplication(overrides = {}) { - return createApplication({ - session: overrides.session ?? createAnonymousSessionAdapter(), - preferences: - overrides.preferences ?? - { - read: () => ({ ok: /** @type {const} */ (true), value: "system" }), - write: () => ({ ok: /** @type {const} */ (true) }), - remove: () => ({ ok: /** @type {const} */ (true) }), - }, - diagnostics: overrides.diagnostics ?? { emit: () => {} }, - releaseInfo: - overrides.releaseInfo ?? - { - getCurrent: async () => ({ - buildId: "test-build", - releaseId: "test-release", - configSchemaVersion: "1", - apiContractVersion: "1", - assetManifestHash: "test-hash", - routeChunks: { - "route-home": "assets/home.js", - "route-sample-resources": "assets/sample.js", - }, - }), - refresh: async () => ({ - buildId: "test-build", - releaseId: "test-release", - configSchemaVersion: "1", - apiContractVersion: "1", - assetManifestHash: "test-hash", - routeChunks: { - "route-home": "assets/home.js", - "route-sample-resources": "assets/sample.js", - }, - }), - }, - navigation: overrides.navigation ?? { reload: () => {} }, - }); + return createApplication( + { + session: overrides.session ?? createAnonymousSessionAdapter(), + preferences: + overrides.preferences ?? + { + read: () => ({ ok: /** @type {const} */ (true), value: "system" }), + write: () => ({ ok: /** @type {const} */ (true) }), + remove: () => ({ ok: /** @type {const} */ (true) }), + }, + diagnostics: overrides.diagnostics ?? { emit: () => {} }, + releaseInfo: + overrides.releaseInfo ?? + { + getCurrent: async () => ({ + buildId: "test-build", + releaseId: "test-release", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "test-hash", + routeChunks: { + "route-home": "assets/home.js", + }, + }), + refresh: async () => ({ + buildId: "test-build", + releaseId: "test-release", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "test-hash", + routeChunks: { + "route-home": "assets/home.js", + }, + }), + }, + navigation: overrides.navigation ?? { reload: () => {} }, + }, + overrides.featureInputs, + ); } diff --git a/tests/helpers/http-contract-fixture.ts b/tests/helpers/http-contract-fixture.ts new file mode 100644 index 00000000..732ac3ec --- /dev/null +++ b/tests/helpers/http-contract-fixture.ts @@ -0,0 +1,108 @@ +import { z } from "zod"; + +import type { createHttpClient } from "../../src/adapters/http/client.js"; +import { canonicalize } from "../../src/contracts/query-keys.js"; + +const entitySchema = z + .object({ + id: z.string().min(1), + name: z.string().min(1), + }) + .passthrough(); +const payloadSchemas = { + EntityListPayload: z.array(entitySchema), + EntityPayload: entitySchema, +}; +const requestSchemas = { + EntityListQuery: z + .object({ + cursor: z.string().optional(), + limit: z.coerce.number().int().min(1).max(100).default(20), + tags: z.array(z.string().trim().min(1)).optional(), + }) + .strict(), + CreateEntityCommand: z + .object({ name: z.string().trim().min(1).max(120) }) + .strict(), +}; + +export const TEST_OPERATIONS = Object.freeze({ + LIST_ENTITIES: Object.freeze({ + method: "GET", + path: "/api/entities", + operationId: "LIST_ENTITIES", + auth: "external-session", + timeoutMs: null, + idempotency: "safe", + retry: "runtime", + requestSource: "search", + requestSchema: "EntityListQuery", + responseSchema: "EntityListPayload", + owner: "test-fixture", + }), + CREATE_ENTITY: Object.freeze({ + method: "POST", + path: "/api/entities", + operationId: "CREATE_ENTITY", + auth: "external-session", + timeoutMs: null, + idempotency: "keyed", + retry: "runtime", + requestSource: "body", + requestSchema: "CreateEntityCommand", + responseSchema: "EntityPayload", + owner: "test-fixture", + }), +}); + +export const entityQueryKeys = Object.freeze({ + list: (filters: Readonly> = {}) => + Object.freeze(["entity", 1, canonicalize(filters)]), +}); + +type Validation = + | Readonly<{ success: true; data: unknown }> + | Readonly<{ success: false }>; + +function project(schema: z.ZodType | undefined, value: unknown): Validation { + const result = schema?.safeParse(value); + if (!result?.success) return { success: false }; + return { success: true, data: structuredClone(result.data) }; +} + +type HttpDependencies = Parameters[0]; + +export const TEST_HTTP_CONTRACT = Object.freeze({ + getOperation(operationId: string) { + const operation = + TEST_OPERATIONS[operationId as keyof typeof TEST_OPERATIONS]; + if (!operation) throw new Error(`Unknown test operation: ${operationId}`); + return operation; + }, + validatePayload(schemaId: string, value: unknown) { + return project( + payloadSchemas[schemaId as keyof typeof payloadSchemas], + value, + ); + }, + validateRequest(schemaId: string, value: unknown) { + return project( + requestSchemas[schemaId as keyof typeof requestSchemas], + value, + ); + }, + mapPayload(operationId: string, payload: unknown) { + const mapOne = (value: unknown) => { + const entity = value as { id: string; name: string }; + return { id: entity.id, displayName: entity.name }; + }; + if (operationId === "LIST_ENTITIES") { + return (payload as readonly unknown[]).map(mapOne); + } + if (operationId === "CREATE_ENTITY") return mapOne(payload); + throw new Error(`Unknown test mapper: ${operationId}`); + }, +}) satisfies Pick< + HttpDependencies, + "getOperation" | "validatePayload" | "validateRequest" | "mapPayload" +>; diff --git a/tests/integration/auth-recovery.test.js b/tests/integration/auth-recovery.test.js index 72955b01..cae4d1dc 100644 --- a/tests/integration/auth-recovery.test.js +++ b/tests/integration/auth-recovery.test.js @@ -4,11 +4,12 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest import { createExternalAuthSessionAdapter } from "../../src/adapters/auth/external-session-adapter.js"; import { createHttpClient } from "../../src/adapters/http/client.js"; +import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.js"; /** @type {number[]} */ let responseStatuses = []; const server = setupServer( - http.get("https://api.test/api/sample/resources", () => { + http.get("https://api.test/api/entities", () => { const status = responseStatuses.shift() ?? 200; if (status === 401) { return HttpResponse.json( @@ -37,6 +38,11 @@ afterAll(() => server.close()); const clock = { now: () => 0, sleep: async () => {} }; +/** @param {Parameters[0]} options */ +function testClient(options) { + return createHttpClient({ ...TEST_HTTP_CONTRACT, ...options }); +} + /** * @param {Partial[0]>} overrides * @returns {Parameters[0]} @@ -63,13 +69,13 @@ describe("bounded 401 session recovery", () => { recoverSession, notifyUnauthenticated: vi.fn(), })); - const client = createHttpClient({ + const client = testClient({ baseUrl: "https://api.test", authSession, clock, }); - await expect(client.execute("LIST_SAMPLE_RESOURCES")).resolves.toMatchObject({ + await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({ ok: true, }); expect(recoverSession).toHaveBeenCalledTimes(1); @@ -83,13 +89,13 @@ describe("bounded 401 session recovery", () => { recoverSession: async () => "restored", notifyUnauthenticated, })); - const client = createHttpClient({ + const client = testClient({ baseUrl: "https://api.test", authSession, clock, }); - await expect(client.execute("LIST_SAMPLE_RESOURCES")).resolves.toMatchObject({ + await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({ ok: false, error: { kind: "AUTH_REQUIRED" }, }); @@ -104,13 +110,13 @@ describe("bounded 401 session recovery", () => { recoverSession: async () => "restored", notifyUnauthenticated: vi.fn(), })); - const client = createHttpClient({ + const client = testClient({ baseUrl: "https://api.test", authSession: attachFailure, clock, }); - await expect(client.execute("LIST_SAMPLE_RESOURCES")).resolves.toMatchObject({ + await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({ ok: false, error: { kind: "AUTH_INTEGRATION_FAILURE" }, }); diff --git a/tests/integration/http-client.test.js b/tests/integration/http-client.test.js index 6ca66402..c0208eed 100644 --- a/tests/integration/http-client.test.js +++ b/tests/integration/http-client.test.js @@ -3,10 +3,11 @@ import { setupServer } from "msw/node"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { createHttpClient } from "../../src/adapters/http/client.js"; +import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.js"; let attempts = 0; const server = setupServer( - http.get("https://api.test/api/sample/resources", () => { + http.get("https://api.test/api/entities", () => { attempts += 1; if (attempts < 3) { return HttpResponse.json( @@ -34,16 +35,21 @@ const clock = { sleep: async () => {}, }; +/** @param {Parameters[0]} options */ +function testClient(options) { + return createHttpClient({ ...TEST_HTTP_CONTRACT, ...options }); +} + describe("shared HTTP client", () => { it("retries a safe request at most twice and returns validated data", async () => { - const client = createHttpClient({ + const client = testClient({ baseUrl: "https://api.test", clock, random: () => 0, }); await expect( - client.execute("LIST_SAMPLE_RESOURCES", { routeId: "SAMPLE_RESOURCE_LIST" }), + client.execute("LIST_ENTITIES", { routeId: "TEST_ROUTE" }), ).resolves.toMatchObject({ ok: true, value: [{ id: "resource-1", displayName: "Example" }], @@ -55,12 +61,12 @@ describe("shared HTTP client", () => { it("rejects a non-JSON response without exposing its body", async () => { server.use( http.get( - "https://api.test/api/sample/resources", + "https://api.test/api/entities", () => new HttpResponse("raw body", { status: 502 }), ), ); - const client = createHttpClient({ baseUrl: "https://api.test", clock }); - const result = await client.execute("LIST_SAMPLE_RESOURCES"); + const client = testClient({ baseUrl: "https://api.test", clock }); + const result = await client.execute("LIST_ENTITIES"); expect(result).toMatchObject({ ok: false, @@ -72,21 +78,21 @@ describe("shared HTTP client", () => { it("classifies malformed JSON and invalid payloads at the boundary", async () => { server.use( http.get( - "https://api.test/api/sample/resources", + "https://api.test/api/entities", () => new HttpResponse("{", { headers: { "Content-Type": "application/json" }, }), ), ); - const client = createHttpClient({ baseUrl: "https://api.test", clock }); - await expect(client.execute("LIST_SAMPLE_RESOURCES")).resolves.toMatchObject({ + const client = testClient({ baseUrl: "https://api.test", clock }); + await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({ ok: false, error: { kind: "MALFORMED_JSON" }, }); server.use( - http.get("https://api.test/api/sample/resources", () => + http.get("https://api.test/api/entities", () => HttpResponse.json({ success: true, data: [{ id: "resource-1", name: 42 }], @@ -94,7 +100,7 @@ describe("shared HTTP client", () => { }), ), ); - await expect(client.execute("LIST_SAMPLE_RESOURCES")).resolves.toMatchObject({ + await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({ ok: false, error: { kind: "SCHEMA_MISMATCH" }, }); @@ -102,7 +108,7 @@ describe("shared HTTP client", () => { it("guards mapper exceptions as UNKNOWN_FAILURE", async () => { server.use( - http.get("https://api.test/api/sample/resources", () => + http.get("https://api.test/api/entities", () => HttpResponse.json({ success: true, data: [{ id: "resource-1", name: "Example" }], @@ -110,7 +116,7 @@ describe("shared HTTP client", () => { }), ), ); - const client = createHttpClient({ + const client = testClient({ baseUrl: "https://api.test", clock, mapPayload: () => { @@ -118,7 +124,7 @@ describe("shared HTTP client", () => { }, }); - const result = await client.execute("LIST_SAMPLE_RESOURCES"); + const result = await client.execute("LIST_ENTITIES"); expect(result).toMatchObject({ ok: false, error: { kind: "UNKNOWN_FAILURE" }, diff --git a/tests/integration/http-execution-contract.test.js b/tests/integration/http-execution-contract.test.js index e8e766d1..07896a6f 100644 --- a/tests/integration/http-execution-contract.test.js +++ b/tests/integration/http-execution-contract.test.js @@ -1,7 +1,10 @@ import { describe, expect, it, vi } from "vitest"; import { createHttpClient } from "../../src/adapters/http/client.js"; -import { queryKeys } from "../../src/contracts/query-keys.js"; +import { + entityQueryKeys, + TEST_HTTP_CONTRACT, +} from "../helpers/http-contract-fixture.js"; /** @param {unknown} data */ function successResponse(data) { @@ -40,6 +43,11 @@ function recordingScheduler() { }; } +/** @param {Parameters[0]} options */ +function testClient(options) { + return createHttpClient({ ...TEST_HTTP_CONTRACT, ...options }); +} + describe("HTTP operation execution contract", () => { it("sends parsed search/body values and aligns canonical query identity", async () => { const requests = /** @type {Request[]} */ ([]); @@ -51,7 +59,7 @@ describe("HTTP operation execution contract", () => { } return successResponse([]); }); - const client = createHttpClient({ + const client = testClient({ baseUrl: "https://api.test", fetcher, clock: immediateClock(), @@ -60,21 +68,21 @@ describe("HTTP operation execution contract", () => { const filters = { tags: ["open", "new"], cursor: "a/b", limit: 5 }; await client.execute({ - operationId: "LIST_SAMPLE_RESOURCES", - routeId: "SAMPLE_RESOURCE_LIST", + operationId: "LIST_ENTITIES", + routeId: "TEST_ROUTE", searchParams: filters, }); await client.execute({ - operationId: "CREATE_SAMPLE_RESOURCE", - routeId: "SAMPLE_RESOURCE_LIST", + operationId: "CREATE_ENTITY", + routeId: "TEST_ROUTE", body: { name: " Trimmed " }, idempotencyKey: "logical-command", }); expect(requests[0].url).toBe( - "https://api.test/api/sample/resources?cursor=a%2Fb&limit=5&tags=open&tags=new", + "https://api.test/api/entities?cursor=a%2Fb&limit=5&tags=open&tags=new", ); - expect(queryKeys.resource.list(filters).at(-1)).toEqual(filters); + expect(entityQueryKeys.list(filters).at(-1)).toEqual(filters); await expect(requests[1].json()).resolves.toEqual({ name: "Trimmed" }); expect(requests[1].headers.get("Idempotency-Key")).toBe("logical-command"); expect(scheduler.setTimeout).toHaveBeenCalledTimes(2); @@ -84,7 +92,7 @@ describe("HTTP operation execution contract", () => { it("performs no fetch or timer work for invalid request input", async () => { const fetcher = vi.fn(); const scheduler = recordingScheduler(); - const client = createHttpClient({ + const client = testClient({ baseUrl: "https://api.test", fetcher, scheduler, @@ -92,8 +100,8 @@ describe("HTTP operation execution contract", () => { await expect( client.execute({ - operationId: "CREATE_SAMPLE_RESOURCE", - routeId: "SAMPLE_RESOURCE_LIST", + operationId: "CREATE_ENTITY", + routeId: "TEST_ROUTE", body: { name: " " }, }), ).resolves.toMatchObject({ @@ -114,7 +122,7 @@ describe("HTTP operation execution contract", () => { async (maxRetryAttempts, totalAttempts) => { const fetcher = vi.fn(async () => failureResponse(503)); const scheduler = recordingScheduler(); - const client = createHttpClient({ + const client = testClient({ baseUrl: "https://api.test", fetcher, clock: immediateClock(), @@ -124,8 +132,8 @@ describe("HTTP operation execution contract", () => { await expect( client.execute({ - operationId: "LIST_SAMPLE_RESOURCES", - routeId: "SAMPLE_RESOURCE_LIST", + operationId: "LIST_ENTITIES", + routeId: "TEST_ROUTE", }), ).resolves.toMatchObject({ ok: false, @@ -149,15 +157,15 @@ describe("HTTP operation execution contract", () => { ); }), ); - const client = createHttpClient({ + const client = testClient({ baseUrl: "https://api.test", fetcher, scheduler, maxRetryAttempts: 0, }); const timeoutResult = client.execute({ - operationId: "LIST_SAMPLE_RESOURCES", - routeId: "SAMPLE_RESOURCE_LIST", + operationId: "LIST_ENTITIES", + routeId: "TEST_ROUTE", }); await vi.waitFor(() => expect(scheduler.callbacks).toHaveLength(1)); scheduler.callbacks[0](); @@ -170,8 +178,8 @@ describe("HTTP operation execution contract", () => { const add = vi.spyOn(caller.signal, "addEventListener"); const remove = vi.spyOn(caller.signal, "removeEventListener"); const abortResult = client.execute({ - operationId: "LIST_SAMPLE_RESOURCES", - routeId: "SAMPLE_RESOURCE_LIST", + operationId: "LIST_ENTITIES", + routeId: "TEST_ROUTE", signal: caller.signal, }); await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2)); @@ -196,11 +204,11 @@ describe("HTTP operation execution contract", () => { retry: "never", requestSource: "none", requestSchema: "unused", - responseSchema: "SampleResourcePayload", + responseSchema: "EntityPayload", owner: "test", }); const unsafeFetch = vi.fn(async () => failureResponse(503)); - const unsafeClient = createHttpClient({ + const unsafeClient = testClient({ baseUrl: "https://api.test", fetcher: unsafeFetch, clock: immediateClock(), @@ -213,14 +221,14 @@ describe("HTTP operation execution contract", () => { expect(unsafeFetch).toHaveBeenCalledOnce(); const statusFetch = vi.fn(async () => failureResponse(500)); - const statusClient = createHttpClient({ + const statusClient = testClient({ baseUrl: "https://api.test", fetcher: statusFetch, clock: immediateClock(), }); await statusClient.execute({ - operationId: "LIST_SAMPLE_RESOURCES", - routeId: "SAMPLE_RESOURCE_LIST", + operationId: "LIST_ENTITIES", + routeId: "TEST_ROUTE", }); expect(statusFetch).toHaveBeenCalledOnce(); @@ -228,15 +236,15 @@ describe("HTTP operation execution contract", () => { successResponse([{ id: "one", name: 42 }]), ); const schemaScheduler = recordingScheduler(); - const schemaClient = createHttpClient({ + const schemaClient = testClient({ baseUrl: "https://api.test", fetcher: schemaFetch, clock: immediateClock(), scheduler: schemaScheduler, }); await schemaClient.execute({ - operationId: "LIST_SAMPLE_RESOURCES", - routeId: "SAMPLE_RESOURCE_LIST", + operationId: "LIST_ENTITIES", + routeId: "TEST_ROUTE", }); expect(schemaFetch).toHaveBeenCalledOnce(); expect(schemaScheduler.clearTimeout).toHaveBeenCalledOnce(); diff --git a/tests/integration/sample-vertical-slice.test.js b/tests/integration/sample-vertical-slice.test.js deleted file mode 100644 index 414ac28a..00000000 --- a/tests/integration/sample-vertical-slice.test.js +++ /dev/null @@ -1,53 +0,0 @@ -import { HttpResponse, http } from "msw"; -import { setupServer } from "msw/node"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; - -import { createHttpClient } from "../../src/adapters/http/client.js"; -import { - createQueryCacheAdapter, - createQueryClient, -} from "../../src/adapters/query-cache/tanstack-query-cache.js"; -import { queryKeys } from "../../src/contracts/query-keys.js"; -import { createSampleFacade } from "../../src/sample/contract-fixture/sample-facade.js"; - -const server = setupServer( - http.get("https://api.test/api/sample/resources", () => - HttpResponse.json({ - success: true, - data: [{ id: "resource-1", name: "Example" }], - meta: { requestId: "request-1", traceId: "trace-1" }, - }), - ), -); - -beforeAll(() => server.listen({ onUnhandledRequest: "error" })); -afterAll(() => server.close()); - -describe("sample vertical contract fixture", () => { - it("traverses API, schema, mapper, application facade, and cache", async () => { - const queryClient = createQueryClient(); - const cache = createQueryCacheAdapter(queryClient); - const facade = createSampleFacade({ - http: createHttpClient({ - baseUrl: "https://api.test", - clock: { now: () => 0, sleep: async () => {} }, - }), - cache, - }); - - await expect(facade.listResources()).resolves.toEqual({ - ok: true, - value: [ - { - resourceId: "resource-1", - title: "Example", - createdAtLabel: null, - }, - ], - }); - expect(cache.read(queryKeys.resource.list({}))).toMatchObject({ - ok: true, - value: [{ id: "resource-1", displayName: "Example" }], - }); - }); -}); diff --git a/tests/runtime-schema/http-schema.test.js b/tests/runtime-schema/http-schema.test.js index 9fd8d6eb..42b1cb02 100644 --- a/tests/runtime-schema/http-schema.test.js +++ b/tests/runtime-schema/http-schema.test.js @@ -6,49 +6,34 @@ import { validateOperationRequest, } from "../../src/adapters/http/schema-registry.js"; -describe("HTTP runtime schema boundary", () => { +describe("HTTP platform schema boundary", () => { it("rejects an invalid top-level envelope", () => { expect(validateEnvelope({ success: true }).success).toBe(false); }); - it("rejects an invalid operation payload with safe issue metadata", () => { - const result = validateOperationPayload("SampleResourceListPayload", [ - { id: "resource-1", name: 42 }, - ]); - - expect(result).toMatchObject({ - success: false, - issues: [{ path: "0.name" }], - }); - expect(JSON.stringify(result)).not.toContain("resource-1"); - }); - - it("returns a deep-cloned additive-tolerant payload", () => { - const source = [{ id: "resource-1", name: "Example", additive: "accepted" }]; - const result = validateOperationPayload("SampleResourceListPayload", source); - - expect(result).toMatchObject({ + it("accepts and clones a generic valid response envelope", () => { + const source = { success: true, - data: [{ id: "resource-1", additive: "accepted" }], - }); - if (!result.success) throw new Error("expected valid sample payload"); + data: [], + meta: { requestId: "request-1", traceId: "trace-1" }, + }; + const result = validateEnvelope(source); + expect(result).toMatchObject({ success: true, data: source }); + if (!result.success) throw new Error("expected valid envelope"); expect(result.data).not.toBe(source); }); - it("validates outbound commands before transport", () => { - expect( - validateOperationRequest("CreateSampleResourceCommand", { name: "" }).success, - ).toBe(false); - expect( - validateOperationRequest("CreateSampleResourceCommand", { name: "Example" }) - .success, - ).toBe(true); - }); - - it("fails closed for an unregistered schema", () => { - expect(validateOperationPayload("UnknownPayload", {})).toMatchObject({ - success: false, - issues: [{ code: "SCHEMA_NOT_REGISTERED" }], + it("fails closed without leaking input when a feature schema is absent", () => { + const result = validateOperationPayload("UnknownPayload", { + secret: "not-projected", }); + expect(result).toMatchObject({ + success: false, + issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }], + }); + expect(JSON.stringify(result)).not.toContain("not-projected"); + expect( + validateOperationRequest("UnknownCommand", { name: "Example" }).success, + ).toBe(false); }); }); diff --git a/tests/unit/application-boundary.test.ts b/tests/unit/application-boundary.test.ts index 30e5628a..8cd4ffd6 100644 --- a/tests/unit/application-boundary.test.ts +++ b/tests/unit/application-boundary.test.ts @@ -16,10 +16,15 @@ describe("application input/output boundary", () => { "diagnostics", "runtime", "recovery", + "features", ]); expect(application).not.toHaveProperty("storage"); expect(application).not.toHaveProperty("telemetry"); expect(application).not.toHaveProperty("releaseInfo"); + expect(application.features.has("not-installed")).toBe(false); + expect(() => application.features.get("not-installed")).toThrow( + "Application feature is not installed", + ); await expect(application.runtime.getReleaseSummary()).resolves.toEqual({ buildId: "test-build", releaseId: "test-release", diff --git a/tests/unit/boundary-mapper.test.js b/tests/unit/boundary-mapper.test.js index 838b1c04..82296971 100644 --- a/tests/unit/boundary-mapper.test.js +++ b/tests/unit/boundary-mapper.test.js @@ -1,52 +1,11 @@ import { describe, expect, it } from "vitest"; -import { - mapOperationPayload, - mapResourceDto, -} from "../../src/adapters/http/resource-mapper.js"; -import { toResourceViewModel } from "../../src/application/view-models/resource-view-model.js"; +import { mapOperationPayload } from "../../src/adapters/http/resource-mapper.js"; -describe("DTO to model to view-model mapping", () => { - it("contains raw DTO names at the HTTP boundary", () => { - const model = mapResourceDto({ - id: "resource-1", - name: "Example", - createdAt: "2026-07-25T00:00:00.000Z", - backendOnly: "not propagated", - }); - - expect(model).toEqual({ - id: "resource-1", - displayName: "Example", - createdAt: "2026-07-25T00:00:00.000Z", - }); - expect(model).not.toHaveProperty("name"); - expect(model).not.toHaveProperty("backendOnly"); - }); - - it("maps operation payloads and rejects missing mappers", () => { - expect( - mapOperationPayload("LIST_SAMPLE_RESOURCES", [ - { id: "resource-1", name: "Example" }, - ]), - ).toEqual([ - { id: "resource-1", displayName: "Example", createdAt: null }, - ]); +describe("platform DTO mapper boundary", () => { + it("fails closed when no feature mapper was injected", () => { expect(() => mapOperationPayload("UNKNOWN", {})).toThrow( "No boundary mapper registered", ); }); - - it("projects an application-owned render-ready shape", () => { - const model = mapResourceDto({ - id: "resource-1", - name: "Example", - createdAt: null, - }); - expect(toResourceViewModel(model)).toEqual({ - resourceId: "resource-1", - title: "Example", - createdAtLabel: null, - }); - }); }); diff --git a/tests/unit/error-classification.test.js b/tests/unit/error-classification.test.js index 2a44a8b4..4c9c29dc 100644 --- a/tests/unit/error-classification.test.js +++ b/tests/unit/error-classification.test.js @@ -49,7 +49,7 @@ describe("frontend failure classification", () => { }; const result = createFailure( "SERVER_FAILURE", - "LIST_SAMPLE_RESOURCES", + "LIST_ENTITIES", 0, untrustedDetails, ); diff --git a/tests/unit/manual-a11y-evidence.test.js b/tests/unit/manual-a11y-evidence.test.js index 80dabff7..4d87d45c 100644 --- a/tests/unit/manual-a11y-evidence.test.js +++ b/tests/unit/manual-a11y-evidence.test.js @@ -4,7 +4,7 @@ import { MANUAL_A11Y_ROUTE_IDS, validateManualA11yEvidence, } from "../../scripts/lib/manual-a11y-evidence.mjs"; -import { ROUTE_REGISTRY } from "../../src/contracts/routes.js"; +import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.js"; const reviewed = `Status: reviewed Route ID: APP_HOME diff --git a/tests/unit/navigation-policy.test.js b/tests/unit/navigation-policy.test.js index d2354814..a6690c2d 100644 --- a/tests/unit/navigation-policy.test.js +++ b/tests/unit/navigation-policy.test.js @@ -1,126 +1,35 @@ import { describe, expect, it } from "vitest"; +import { + NAVIGATION_ROUTES, + ROUTE_REGISTRY, +} from "../../src/features/installed-feature-contracts.js"; import { createRedirectLoopGuard, decideRouteAccess, } from "../../src/presentation/routes/navigation-policy.js"; -import { - NAVIGATION_ROUTES, - ROUTE_REGISTRY, -} from "../../src/contracts/routes.js"; - -describe("route registry", () => { - it("matches the stable registry snapshot", () => { - expect(ROUTE_REGISTRY).toMatchInlineSnapshot(` - { - "APP_HOME": { - "access": "public", - "chunkId": "route-home", - "errorSurface": "route-boundary", - "loadingSurface": "app-shell", - "navigationLabel": "시작", - "navigationOrder": 10, - "paramsSchema": null, - "path": "/", - "routeId": "APP_HOME", - "searchSchema": null, - "title": "시작", - }, - "EXAMPLES_AUTH": { - "access": "public", - "chunkId": "route-examples-auth", - "errorSurface": "route-boundary", - "loadingSurface": "example-page", - "navigationLabel": "인증 연동", - "navigationOrder": 40, - "paramsSchema": null, - "path": "/examples/auth", - "routeId": "EXAMPLES_AUTH", - "searchSchema": null, - "title": "인증 연동", - }, - "EXAMPLES_STATES": { - "access": "public", - "chunkId": "route-examples-states", - "errorSurface": "route-boundary", - "loadingSurface": "example-page", - "navigationLabel": "화면 상태", - "navigationOrder": 30, - "paramsSchema": null, - "path": "/examples/states", - "routeId": "EXAMPLES_STATES", - "searchSchema": null, - "title": "화면 상태", - }, - "EXAMPLES_UI": { - "access": "public", - "chunkId": "route-examples-ui", - "errorSurface": "route-boundary", - "loadingSurface": "example-page", - "navigationLabel": "UI 구성요소", - "navigationOrder": 20, - "paramsSchema": null, - "path": "/examples/ui", - "routeId": "EXAMPLES_UI", - "searchSchema": null, - "title": "UI 구성요소", - }, - "NOT_FOUND": { - "access": "public", - "chunkId": "route-not-found", - "errorSurface": "not-found", - "loadingSurface": "none", - "navigationLabel": null, - "navigationOrder": null, - "paramsSchema": "NotFoundSplat", - "path": "*", - "routeId": "NOT_FOUND", - "searchSchema": null, - "title": "페이지를 찾을 수 없음", - }, - "SAMPLE_RESOURCE_LIST": { - "access": "integration-defined", - "chunkId": "route-sample-resources", - "errorSurface": "feature-boundary", - "loadingSurface": "sample-resource-list", - "navigationLabel": "보호된 연동 지점", - "navigationOrder": 50, - "paramsSchema": null, - "path": "/sample/resources", - "routeId": "SAMPLE_RESOURCE_LIST", - "searchSchema": "SampleResourceListQuery", - "title": "보호된 연동 지점", - }, - } - `); - }); +describe("installed route registry", () => { it("derives visible navigation in explicit order", () => { - expect(NAVIGATION_ROUTES.map(({ routeId }) => routeId)).toEqual([ - "APP_HOME", - "EXAMPLES_UI", - "EXAMPLES_STATES", - "EXAMPLES_AUTH", - "SAMPLE_RESOURCE_LIST", - ]); + const expected = Object.values(ROUTE_REGISTRY) + .filter((route) => route.navigationOrder !== null) + .sort( + (left, right) => + /** @type {number} */ (left.navigationOrder) - + /** @type {number} */ (right.navigationOrder), + ) + .map((route) => route.routeId); + expect(NAVIGATION_ROUTES.map(({ routeId }) => routeId)).toEqual(expected); }); - it("treats client access as a UX hint, not authorization", () => { + it("allows public routes without consulting a product permission", () => { expect(decideRouteAccess("APP_HOME", "unauthenticated")).toEqual({ allowed: true, action: "none", }); - expect(decideRouteAccess("SAMPLE_RESOURCE_LIST", "unauthenticated")).toEqual({ - allowed: false, - action: "show-sign-in", - }); - expect(decideRouteAccess("SAMPLE_RESOURCE_LIST", "authenticated")).toEqual({ - allowed: true, - action: "none", - }); }); - it("allows at most one automatic redirect per source-target pair", () => { + it("bounds automatic redirects by pair and maximum hops", () => { const guard = createRedirectLoopGuard(2); expect(guard.allow("/private", "/signin")).toBe(true); expect(guard.allow("/private", "/signin")).toBe(false); diff --git a/tests/unit/query-cache.test.js b/tests/unit/query-cache.test.js index f92732ac..c5bac1fd 100644 --- a/tests/unit/query-cache.test.js +++ b/tests/unit/query-cache.test.js @@ -5,18 +5,27 @@ import { createQueryCacheAdapter, createQueryClient, } from "../../src/adapters/query-cache/tanstack-query-cache.js"; -import { queryKeys } from "../../src/contracts/query-keys.js"; +import { canonicalize } from "../../src/contracts/query-keys.js"; + +const queryKeys = Object.freeze({ + all: () => Object.freeze(["entity", 1]), + list: (filters = {}) => + Object.freeze(["entity", 1, "list", canonicalize(filters)]), + /** @param {string} entityId */ + detail: (entityId) => + Object.freeze(["entity", 1, "detail", String(entityId)]), +}); describe("query key registry", () => { it("canonicalizes filter order into the same stable key", () => { - expect(queryKeys.resource.list({ page: 1, status: "open" })).toEqual( - queryKeys.resource.list({ status: "open", page: 1 }), + expect(queryKeys.list({ page: 1, status: "open" })).toEqual( + queryKeys.list({ status: "open", page: 1 }), ); }); it("contains no raw URL or token material", () => { - expect(JSON.stringify(queryKeys.resource.detail("resource-1"))).toBe( - '["resource",1,"detail","resource-1"]', + expect(JSON.stringify(queryKeys.detail("entity-1"))).toBe( + '["entity",1,"detail","entity-1"]', ); }); }); @@ -25,7 +34,7 @@ describe("TanStack QueryCachePort adapter", () => { it("reads, writes, and invalidates only the declared namespace", async () => { const client = createQueryClient(); const adapter = createQueryCacheAdapter(client); - const listKey = queryKeys.resource.list({ page: 1 }); + const listKey = queryKeys.list({ page: 1 }); const otherKey = ["other", 1]; expect(adapter.write(listKey, [{ id: "resource-1" }])).toEqual({ ok: true }); @@ -35,7 +44,7 @@ describe("TanStack QueryCachePort adapter", () => { value: [{ id: "resource-1" }], }); - await adapter.invalidate(queryKeys.resource.all()); + await adapter.invalidate(queryKeys.all()); expect(client.getQueryState(listKey)?.isInvalidated).toBe(true); expect(client.getQueryState(otherKey)?.isInvalidated).toBe(false); }); diff --git a/tests/unit/route-runtime.test.ts b/tests/unit/route-runtime.test.ts index b1285c55..62a36975 100644 --- a/tests/unit/route-runtime.test.ts +++ b/tests/unit/route-runtime.test.ts @@ -1,15 +1,14 @@ import { describe, expect, it } from "vitest"; -import { ROUTE_RUNTIME_CONTRACT } from "../../src/contracts/route-runtime-contract.js"; -import { ROUTE_REGISTRY } from "../../src/contracts/routes.js"; import { - buildRouteUrl, - parseRouteInput, -} from "../../src/presentation/routes/route-codecs.js"; -import { ROUTE_RUNTIME } from "../../src/presentation/routes/route-runtime.js"; + ROUTE_REGISTRY, + ROUTE_RUNTIME_CONTRACT, +} from "../../src/features/installed-feature-contracts.js"; +import { ROUTE_RUNTIME } from "../../src/features/installed-feature-runtimes.js"; +import { parseRouteInput } from "../../src/presentation/routes/route-codecs.js"; -describe("typed route contract and runtime", () => { - it("keeps contract, runtime contribution, and executable module complete", () => { +describe("typed installed route catalog", () => { + it("keeps contract and executable runtime contributions complete", () => { expect(Object.keys(ROUTE_RUNTIME_CONTRACT).sort()).toEqual( Object.keys(ROUTE_REGISTRY).sort(), ); @@ -18,46 +17,7 @@ describe("typed route contract and runtime", () => { ); }); - it("round-trips canonical search through the registered codec", () => { - const url = buildRouteUrl("SAMPLE_RESOURCE_LIST", { - search: { - tags: ["open", "new"], - cursor: "a/b", - limit: 5, - }, - }); - expect(url).toBe( - "/sample/resources?cursor=a%2Fb&limit=5&tags=open&tags=new", - ); - const parsedUrl = new URL(url, "https://app.test"); - expect( - parseRouteInput( - "SAMPLE_RESOURCE_LIST", - {}, - parsedUrl.searchParams, - ), - ).toEqual({ - success: true, - data: { - routeId: "SAMPLE_RESOURCE_LIST", - params: {}, - search: { - cursor: "a/b", - limit: 5, - tags: ["open", "new"], - }, - }, - }); - }); - - it("rejects unknown search and accepts the not-found splat owner", () => { - expect( - parseRouteInput( - "SAMPLE_RESOURCE_LIST", - {}, - new URLSearchParams("unknown=value"), - ), - ).toEqual({ success: false, code: "ROUTE_SEARCH_INVALID" }); + it("accepts the platform not-found splat owner", () => { expect( parseRouteInput( "NOT_FOUND", diff --git a/tests/unit/runtime-adapters.test.js b/tests/unit/runtime-adapters.test.js index d57e3a1c..40181d18 100644 --- a/tests/unit/runtime-adapters.test.js +++ b/tests/unit/runtime-adapters.test.js @@ -4,6 +4,7 @@ import { createRuntimeAdapters, createRuntimeHttpClient, } from "../../src/bootstrap/runtime-adapters.js"; +import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.js"; const runtime = { config: { @@ -118,23 +119,26 @@ describe("runtime adapter composition", () => { release, host: {}, })).outputPorts.session; - const client = createRuntimeHttpClient({ - runtime: - /** @type {Parameters[0]["runtime"]} */ ( - runtime - ), - authSession: - /** @type {import("../../src/application/ports/auth-session-port.js").AuthSessionPort} */ ( - authSession - ), - fetcher, - clock: { now: () => 0, sleep: async () => {} }, - scheduler, - }); + const client = createRuntimeHttpClient( + { + runtime: + /** @type {Parameters[0]["runtime"]} */ ( + runtime + ), + authSession: + /** @type {import("../../src/application/ports/auth-session-port.js").AuthSessionPort} */ ( + authSession + ), + fetcher, + clock: { now: () => 0, sleep: async () => {} }, + scheduler, + }, + TEST_HTTP_CONTRACT, + ); await client.execute({ - operationId: "LIST_SAMPLE_RESOURCES", - routeId: "SAMPLE_RESOURCE_LIST", + operationId: "LIST_ENTITIES", + routeId: "TEST_ROUTE", }); expect(fetcher).toHaveBeenCalledOnce(); diff --git a/tests/unit/telemetry.test.js b/tests/unit/telemetry.test.js index 67ccb0a9..c5c8106d 100644 --- a/tests/unit/telemetry.test.js +++ b/tests/unit/telemetry.test.js @@ -13,7 +13,7 @@ const validAttributes = { error_kind: "SERVER_FAILURE", http_status_group: "5xx", attempt_count_bucket: "3", - route_id: "SAMPLE_RESOURCE_LIST", + route_id: "TEST_ROUTE", }; describe("telemetry registry and redaction", () => { From b327d7370b1577680aba6ac360c0fbec58411751 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sun, 26 Jul 2026 15:22:52 +0900 Subject: [PATCH 052/178] feat: add form and page platform --- .dependency-cruiser.cjs | 8 + .../a11y-manual/REFERENCE_RESOURCE_DETAIL.md | 18 ++ .../a11y-manual/REFERENCE_RESOURCE_FORM.md | 18 ++ .../a11y-manual/REFERENCE_RESOURCE_LIST.md | 2 +- .../a11y-manual/REFERENCE_RESOURCE_STATUS.md | 18 ++ config/ci/gates.json | 3 +- config/contracts/registry-governance.json | 13 +- .../decisions/VD-04-native-form-facade.md | 55 ++++ .../frontend-platform-capability-review.md | 10 +- ...rontend-platform-implementation-roadmap.md | 16 ++ .../frontend-ports-adapters-and-boundaries.md | 12 +- .../routing-pages-and-patterns.md | 18 +- .../typescript-state-and-data-flow.md | 20 +- docs/styling/design-system-platform.md | 12 +- .../frontend-platform-testing-strategy.md | 10 + eslint.config.js | 12 + package.json | 1 + public/release-manifest.json | 3 + scripts/check-registries.mjs | 5 + scripts/test-sample-removal.mjs | 19 +- src/adapters/http/client.js | 9 + src/contracts/errors.js | 58 +++++ src/features/reference-feature/README.md | 10 +- .../adapters/reference-http-gateway.ts | 17 +- .../application/reference-feature-api.ts | 18 +- .../contracts/reference-feature-contract.js | 73 ++++++ .../contracts/reference-mapper.ts | 5 +- .../contracts/reference-schemas.ts | 7 + .../reference-feature-runtime.tsx | 18 +- .../reference-resource-detail-page.tsx | 47 ++++ .../reference-resource-form-page.tsx | 131 ++++++++++ .../presentation/reference-resource-form.ts | 29 +++ .../presentation/reference-resource-page.tsx | 79 +++--- .../reference-resource-status-page.tsx | 25 ++ .../presentation/use-reference-feature.ts | 23 +- src/presentation/forms/form-components.tsx | 90 +++++++ src/presentation/forms/form-contracts.ts | 69 +++++ src/presentation/forms/index.ts | 4 + src/presentation/forms/use-app-form.ts | 244 +++++++++++++++++ .../forms/use-dirty-navigation-guard.tsx | 54 ++++ src/presentation/styles/theme.css | 153 +++++++++++ src/presentation/templates/index.ts | 1 + src/presentation/templates/page-templates.tsx | 246 ++++++++++++++++++ tests/component/form-foundation.test.tsx | 199 ++++++++++++++ tests/component/page-templates.test.tsx | 92 +++++++ tests/e2e/accessibility.spec.js | 7 +- tests/e2e/reference-form.spec.js | 50 ++++ .../reference-contract.test.ts | 4 + .../reference-feature/reference-page.test.tsx | 57 ++-- .../reference-production-vertical.test.tsx | 13 +- .../template-imports-application.tsx | 5 + .../typecheck/invalid-page-action.tsx | 6 + tests/integration/http-client.test.js | 39 +++ vitest.config.js | 3 +- 54 files changed, 2036 insertions(+), 122 deletions(-) create mode 100644 artifacts/tests/a11y-manual/REFERENCE_RESOURCE_DETAIL.md create mode 100644 artifacts/tests/a11y-manual/REFERENCE_RESOURCE_FORM.md create mode 100644 artifacts/tests/a11y-manual/REFERENCE_RESOURCE_STATUS.md create mode 100644 docs/architecture/decisions/VD-04-native-form-facade.md create mode 100644 src/features/reference-feature/presentation/reference-resource-detail-page.tsx create mode 100644 src/features/reference-feature/presentation/reference-resource-form-page.tsx create mode 100644 src/features/reference-feature/presentation/reference-resource-form.ts create mode 100644 src/features/reference-feature/presentation/reference-resource-status-page.tsx create mode 100644 src/presentation/forms/form-components.tsx create mode 100644 src/presentation/forms/form-contracts.ts create mode 100644 src/presentation/forms/index.ts create mode 100644 src/presentation/forms/use-app-form.ts create mode 100644 src/presentation/forms/use-dirty-navigation-guard.tsx create mode 100644 src/presentation/templates/index.ts create mode 100644 src/presentation/templates/page-templates.tsx create mode 100644 tests/component/form-foundation.test.tsx create mode 100644 tests/component/page-templates.test.tsx create mode 100644 tests/e2e/reference-form.spec.js create mode 100644 tests/fixtures/architecture/forbidden/template-imports-application.tsx create mode 100644 tests/fixtures/typecheck/invalid-page-action.tsx diff --git a/.dependency-cruiser.cjs b/.dependency-cruiser.cjs index 9fd4fdba..6cd78b50 100644 --- a/.dependency-cruiser.cjs +++ b/.dependency-cruiser.cjs @@ -23,6 +23,14 @@ module.exports = { from: { path: "^src/presentation/(?!adapters/query)" }, to: { path: "^(src/(adapters|bootstrap)|@tanstack)" }, }, + { + name: "page-templates-own-layout-only", + severity: "error", + from: { path: "^src/presentation/templates" }, + to: { + path: "^(src/(application|adapters|bootstrap)|src/presentation/adapters|@tanstack)", + }, + }, { name: "adapters-do-not-know-presentation", severity: "error", diff --git a/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_DETAIL.md b/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_DETAIL.md new file mode 100644 index 00000000..81ebaae7 --- /dev/null +++ b/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_DETAIL.md @@ -0,0 +1,18 @@ +# REFERENCE_RESOURCE_DETAIL accessibility review + +Status: pending-manual-review +Route ID: REFERENCE_RESOURCE_DETAIL +Release ID: +Reviewer: +Reviewed at: +Signature: +Attestation: pending +M1 Keyboard: pending +M2 Visible focus: pending +M3 Route focus: pending +M4 Modal focus: not-applicable (no modal on this route) +M5 Error association: not-applicable (no form error on this route) +M6 Color signal: pending +M7 Reduced motion: pending +Screen reader: pending +Notes: Human review pending. diff --git a/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_FORM.md b/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_FORM.md new file mode 100644 index 00000000..e78d1859 --- /dev/null +++ b/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_FORM.md @@ -0,0 +1,18 @@ +# REFERENCE_RESOURCE_FORM accessibility review + +Status: pending-manual-review +Route ID: REFERENCE_RESOURCE_FORM +Release ID: +Reviewer: +Reviewed at: +Signature: +Attestation: pending +M1 Keyboard: pending +M2 Visible focus: pending +M3 Route focus: pending +M4 Modal focus: pending +M5 Error association: pending +M6 Color signal: pending +M7 Reduced motion: pending +Screen reader: pending +Notes: Human review pending. diff --git a/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_LIST.md b/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_LIST.md index dede1df3..74e9ae65 100644 --- a/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_LIST.md +++ b/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_LIST.md @@ -1,4 +1,4 @@ -# SAMPLE_RESOURCE_LIST accessibility review +# REFERENCE_RESOURCE_LIST accessibility review Status: pending-manual-review Route ID: REFERENCE_RESOURCE_LIST diff --git a/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_STATUS.md b/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_STATUS.md new file mode 100644 index 00000000..93e37c45 --- /dev/null +++ b/artifacts/tests/a11y-manual/REFERENCE_RESOURCE_STATUS.md @@ -0,0 +1,18 @@ +# REFERENCE_RESOURCE_STATUS accessibility review + +Status: pending-manual-review +Route ID: REFERENCE_RESOURCE_STATUS +Release ID: +Reviewer: +Reviewed at: +Signature: +Attestation: pending +M1 Keyboard: pending +M2 Visible focus: pending +M3 Route focus: pending +M4 Modal focus: not-applicable (no modal on this route) +M5 Error association: not-applicable (no form error on this route) +M6 Color signal: pending +M7 Reduced motion: pending +Screen reader: pending +Notes: Human review pending. diff --git a/config/ci/gates.json b/config/ci/gates.json index 8104985f..9a13e719 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -80,7 +80,8 @@ { "script": "check:types:fixture:application-output", "expect": "fail" }, { "script": "check:types:fixture:application-input", "expect": "fail" }, { "script": "check:types:fixture:async-overlay", "expect": "fail" }, - { "script": "check:types:fixture:route-runtime", "expect": "fail" } + { "script": "check:types:fixture:route-runtime", "expect": "fail" }, + { "script": "check:types:fixture:page-action", "expect": "fail" } ], "logPath": "artifacts/quality/check-types.txt", "evidence": ["artifacts/quality/check-types.txt"], diff --git a/config/contracts/registry-governance.json b/config/contracts/registry-governance.json index ed7db138..22990e2a 100644 --- a/config/contracts/registry-governance.json +++ b/config/contracts/registry-governance.json @@ -8,12 +8,15 @@ "owner": "feature-routing-navigation-guard-contract", "uniqueFields": ["routeId", "path", "chunkId"], "allowedValues": { - "paramsSchema": [null, "NotFoundSplat"], + "paramsSchema": [null, "NotFoundSplat", "ReferenceResourceParams"], "searchSchema": [null, "ReferenceResourceListQuery"], "loadingSurface": [ "app-shell", "example-page", "reference-resource-list", + "reference-resource-detail", + "reference-resource-form", + "reference-resource-status", "none" ], "errorSurface": [ @@ -27,6 +30,9 @@ "route-examples-states", "route-examples-auth", "route-reference-resources", + "route-reference-resource-detail", + "route-reference-resource-form", + "route-reference-resource-status", "route-not-found" ] }, @@ -67,9 +73,12 @@ "state-gallery-page", "auth-example-page", "reference-resource-page", + "reference-resource-detail-page", + "reference-resource-form-page", + "reference-resource-status-page", "not-found-page" ], - "paramsCodec": ["none", "NotFoundSplat"], + "paramsCodec": ["none", "NotFoundSplat", "ReferenceResourceParams"], "searchCodec": ["none", "ReferenceResourceListQuery"] }, "references": [ diff --git a/docs/architecture/decisions/VD-04-native-form-facade.md b/docs/architecture/decisions/VD-04-native-form-facade.md new file mode 100644 index 00000000..374fd20b --- /dev/null +++ b/docs/architecture/decisions/VD-04-native-form-facade.md @@ -0,0 +1,55 @@ +# VD-04: Native form controller와 local facade + +- 상태: Accepted +- 결정일: 2026-07-26 +- 적용 브랜치: `feature-frontend-form-page-platform` + +## 배경 + +플랫폼에는 Zod가 이미 설치돼 있지만 form state, field error, dirty navigation과 +page template 계약은 없었다. React Hook Form과 resolver를 바로 추가하면 +dependency와 lockfile이 바뀌고, 현재 reference form에 필요하지 않은 복합 비동기 +field orchestration까지 플랫폼 기본값으로 고정하게 된다. + +## 결정 + +1. RP-06은 React native form event와 controlled value를 사용하는 local + `useAppForm` facade를 기본 엔진으로 채택한다. +2. Zod presentation schema, application command mapper와 domain invariant는 서로 + 다른 소유물로 유지한다. +3. page와 feature는 `useAppForm`, `Form`, `FormField`, `ErrorSummary`, + `mapValidationFailureToFields`, `useDirtyNavigationGuard`만 사용한다. +4. 422 details는 승인된 `path`와 `code`만 HTTP 경계에서 투영한다. backend + message와 알 수 없는 field는 field에 전달하지 않고 안전한 form-level + error로 이동한다. +5. 409 conflict는 validation으로 바꾸지 않으며 입력과 dirty 상태를 보존한다. +6. pending submit은 동일 controller에서 한 번만 실행하고 success/reset 이후 + dirty 상태를 해제한다. +7. `StandardPage`, `CollectionPage`, `DetailPage`, `FormPage`, `StatusPage`는 + layout과 state slot만 소유하며 application/query/HTTP를 import하지 않는다. + +## React Hook Form 도입 조건 + +다음 중 하나가 실제 제품 요구로 확인되면 local facade 내부 adapter로 +React Hook Form과 Zod resolver를 평가한다. + +- 동적 field array와 중첩 object를 함께 다루는 복합 form +- field 단위 비동기 validation 취소와 의존 validation +- 수백 개 field의 render isolation이 측정 가능한 병목인 경우 +- uncontrolled input 또는 vendor extension이 필요한 경우 + +도입하더라도 이 문서의 public API와 component/application tests를 유지해야 +한다. vendor package를 feature/page에서 직접 import하는 것은 허용하지 않는다. + +## 검증과 rollback + +- client validation, transform/default, 422 allowlist, conflict, duplicate submit, + reset, dirty guard와 focus를 component test로 검증한다. +- template 최소/전체 slot과 async/status variation을 component test로 검증한다. +- architecture gate가 template의 application/HTTP/query vendor import를 + 거절한다. +- secret-like input이 URL, storage, diagnostics에 복제되지 않는지 검증한다. + +rollback 시 reference page는 이전 직접 form/layout으로 돌아갈 수 있다. +application input과 outbound gateway 계약은 유지되며, form facade와 template +commit은 독립적으로 되돌릴 수 있다. diff --git a/docs/architecture/frontend-platform-capability-review.md b/docs/architecture/frontend-platform-capability-review.md index 96cd248a..e6e3ac1d 100644 --- a/docs/architecture/frontend-platform-capability-review.md +++ b/docs/architecture/frontend-platform-capability-review.md @@ -67,18 +67,18 @@ recovery 계약, 제거 가능한 reference 수직 슬라이스는 구현됐다. | HTTP client | 준비됨 | path/search/body projection, runtime timeout/retry, abort/cleanup test | feature gateway 뒤에서 사용 | | retry | 준비됨 | HTTP 단일 소유, runtime max attempts, Query retry off | RP-09에서 telemetry 연결 | | 오류 모델 | 부분 준비 | error registry와 normalization 존재 | typed discriminated union과 계층별 mapper | -| 검증 | 부분 준비 | runtime/API Zod parse 결과를 실제 request에 사용 | route/form/domain 경계를 추가 | +| 검증 | 준비됨 | runtime/API/route/form Zod parse 결과를 실행 경계에서 사용하고 domain invariant와 분리 | feature별 schema 소유권 유지 | | 인증 연동 | 준비됨/프로젝트 선택 | opaque auth owner와 demo seam 존재 | 인증 방식별 recipe; 기본 token 저장소는 추가하지 않음 | | 서버 상태 | 준비됨 | reference route의 query/mutation, cancellation, stale, optimistic/conflict/rollback | feature별 query contribution recipe 유지 | | 클라이언트 상태 | 부분 준비 | local state, theme context, session external store | 상태 소유권 표와 typed external-store 예제 | | 범용 global store | 프로젝트 선택 | 별도 라이브러리 없음 | 필요 조건에 따라 Zustand/Redux Toolkit/state machine 선택 | | 라우팅 | 준비됨 | Data Router, typed runtime map, codec, metadata consumer, bounded chunk recovery | reference feature route와 release E2E로 사용 범위 확장 | | 앱 셸·반응형 | 부분 준비 | header/sidebar/content/theme 구현 | 접근 가능한 mobile drawer와 focus 복원 | -| 페이지 템플릿 | 미제공 | 각 페이지가 직접 레이아웃 조립 | list/detail/form/status 등 슬롯 기반 템플릿 | +| 페이지 템플릿 | 준비됨 | Standard/Collection/Detail/Form/Status slot 계약과 reference 소비 화면 | RP-07 public design-system entry로 이동 | | 디자인 토큰 | 부분 준비 | semantic color/theme 토큰 존재 | typography, spacing, motion, layer 등 3단계 토큰 | | 공통 UI | 부분 준비 | Button, TextField, Card, Alert, Badge, Dialog | form/navigation/overlay/data/layout primitives 확장 | | 아이콘 | 미제공 | 문자 기호를 직접 사용 | Lucide를 로컬 icon facade 뒤에서 사용 | -| 폼 | 미제공 | 수동 문자열 검증 예제만 존재 | schema 기반 form facade와 422/dirty/pending 정책 | +| 폼 | 준비됨 | Zod 기반 local facade, error summary/focus, 422 allowlist, dirty/pending/conflict 정책 | 복합 form 요구가 생기면 VD-04 조건으로 vendor adapter 평가 | | 국제화 | 미제공 | 한국어 문자열·locale이 하드코딩 | typed message/formatter/locale/RTL 경계 | | logging/diagnostics | 미제공 | telemetry port는 있으나 logger 없음 | redaction이 적용된 diagnostics/logging 경계 | | telemetry | 부분 준비 | registry, queue, redaction 존재 | HTTP·boot·cache·storage·route 사건에 실제 연결 | @@ -236,8 +236,8 @@ known vulnerability, license policy, SBOM/provenance를 pinned tool로 검사해 ### 5.2 P1: 공통 플랫폼 기본 제공 항목 -- schema 기반 form facade와 field/error/pending/dirty/422 정책 -- standard, collection, detail, form, status page template +- RP-06에서 완료한 schema 기반 form facade와 field/error/pending/dirty/422 정책 유지 +- RP-06에서 완료한 standard, collection, detail, form, status page template의 public entry 정리 - 접근 가능한 drawer, menu, popover, select 같은 interaction primitive - token → primitive → pattern → template로 이어지는 디자인 시스템 - Lucide를 감싼 local icon registry와 `IconButton` diff --git a/docs/architecture/frontend-platform-implementation-roadmap.md b/docs/architecture/frontend-platform-implementation-roadmap.md index 5423921a..27d5abdb 100644 --- a/docs/architecture/frontend-platform-implementation-roadmap.md +++ b/docs/architecture/frontend-platform-implementation-roadmap.md @@ -508,6 +508,22 @@ RP-06은 기존 reference controls/layout으로 돌아가도 controller/applicat 경계가 유지돼야 한다. vendor adapter, form contract와 template commit을 구분해 부분 revert가 가능하게 한다. +**구현 증거 (2026-07-26)** + +- VD-04에서 dependency 추가 없는 native controller + Zod local facade를 + 채택했고 vendor 도입 조건을 문서화했다. +- `src/presentation/forms`가 field registration, parse/error map, + dirty/touched/reset/pending/result, 422 allowlist, first-error focus, + duplicate submit과 dirty navigation을 제공한다. +- `src/presentation/templates`가 다섯 page 유형의 slot/landmark/responsive + 계약을 제공하며 architecture negative fixture가 application/vendor import를 + 거절한다. +- reference list/detail/create/status route가 네 구체 template를 사용하고 + production composition test가 list → form → command → HTTP → invalidation → + list 경로를 실행한다. +- component/integration/E2E test가 validation, transform, 422, conflict, + secret 비노출, navigation focus와 320px reflow를 검증한다. + ### 07. `feature-frontend-design-system-platform` **목표** diff --git a/docs/architecture/frontend-ports-adapters-and-boundaries.md b/docs/architecture/frontend-ports-adapters-and-boundaries.md index 39ee0463..c4b857a9 100644 --- a/docs/architecture/frontend-ports-adapters-and-boundaries.md +++ b/docs/architecture/frontend-ports-adapters-and-boundaries.md @@ -163,6 +163,14 @@ contract/presentation은 `src/features/reference-feature`가 소유하고, gener installed catalog만 bootstrap과 router에 노출된다. 제거 gate는 feature와 test를 삭제한 복제본에서 전체 P0 경로를 다시 실행한다. +RP-06에서 inbound form/page 경계도 실행됐다. `src/presentation/forms`는 Zod +presentation schema, controlled field state, error focus, 422 allowlist, +pending/deduplication과 dirty navigation을 local facade로 감싼다. +`src/presentation/templates`는 slot과 landmark만 소유하고 application, HTTP, +query vendor import는 architecture gate가 거절한다. reference feature의 +list/detail/create/status route가 각각 Collection/Detail/Form/Status template의 +실제 consumer다. + 이 문서의 목표 구조는 기존 기반을 폐기하는 것이 아니라 이러한 불일치를 제거하는 것이다. @@ -1249,8 +1257,8 @@ contract와 실패 분기를 우선한다. ### P1: 기본 플랫폼 완성도 -1. error/result/validation/form kernel -2. 배타적인 async 상태와 page template +1. 완료: error/result/validation/form kernel +2. 완료: 배타적인 async 상태와 page template 3. Logger와 telemetry 실제 wiring 4. design-system public API, icon wrapper와 headless interaction 5. locale/message/formatter와 pseudo-locale/RTL 경계 diff --git a/docs/architecture/routing-pages-and-patterns.md b/docs/architecture/routing-pages-and-patterns.md index df0cf4bd..114eb0b8 100644 --- a/docs/architecture/routing-pages-and-patterns.md +++ b/docs/architecture/routing-pages-and-patterns.md @@ -12,9 +12,9 @@ - page controller와 application input use case의 연결 - 프론트엔드에서 반복 사용하는 설계 패턴 -## 2. 현재 상태와 문제 +## 2. 현재 상태와 구현 기준 -RP-04 이후 현재 구현에는 다음 장점이 있다. +RP-04 이후 route runtime과 RP-06 page/form platform에는 다음 장점이 있다. - route registry가 path와 access policy를 소유한다. - contract에서 Data Router route object와 navigation을 생성한다. @@ -22,6 +22,12 @@ RP-04 이후 현재 구현에는 다음 장점이 있다. - 앱 셸과 보호 route, not-found surface가 있다. - route heading focus와 비동기/render error boundary가 있다. - redirect loop와 chunk recovery가 bounded production call graph에 연결돼 있다. +- `src/presentation/templates`가 standard/collection/detail/form/status slot, + landmark와 responsive layout을 제공한다. +- `src/presentation/forms`가 첫 오류 focus, error summary, 422 mapping, + duplicate submit과 dirty route blocker를 소유한다. +- reference feature의 list/detail/create/status route가 네 template variation을 + production composition에서 실행한다. platform route 계약, `src/features/installed-feature-contracts.js`, `src/features/installed-feature-runtimes.tsx`의 완전성은 TypeScript와 registry @@ -31,9 +37,11 @@ access, title, navigation, chunk ID는 manifest의 dynamic entry는 release manifest route chunk map과 검증되며, `ChunkRecoveryBoundary`는 일반 render error와 chunk rejection을 분리한다. -페이지도 공통 `PageHeader` 외에는 각자 section과 class를 직접 조립한다. 목록, -상세, 편집, 오류 페이지의 반복되는 접근성·반응형·상태 표면을 기능 팀이 다시 -구현해야 한다. +template는 데이터를 가져오지 않는다. reference page controller가 route input과 +application input을 query/form facade에 연결하고, template에는 render할 slot과 +안전한 callback만 전달한다. 이 분리는 +`page-templates-own-layout-only` dependency rule과 forbidden import fixture가 +검증한다. ## 3. React Router mode 결정 diff --git a/docs/architecture/typescript-state-and-data-flow.md b/docs/architecture/typescript-state-and-data-flow.md index 8696445d..894662ab 100644 --- a/docs/architecture/typescript-state-and-data-flow.md +++ b/docs/architecture/typescript-state-and-data-flow.md @@ -487,8 +487,12 @@ raw response body, stack, token, URL query, PII를 사용자 copy나 일반 log ## 8. 폼 표준 -form vendor는 React Hook Form 또는 TanStack Form 등을 평가하되 local facade 뒤에 -둔다. vendor 선택과 무관하게 다음 API를 제공한다. +VD-04에 따라 현재 기본 엔진은 React native form event와 controlled value이며 +Zod를 local facade 뒤에서 사용한다. 동적 field array, 비동기 field validation, +대규모 render isolation 요구가 실제로 생기면 public API를 유지한 채 React Hook +Form 또는 TanStack Form adapter를 평가한다. + +현재 public API는 다음과 같다. - `Form` - `FormField` @@ -500,6 +504,18 @@ form vendor는 React Hook Form 또는 TanStack Form 등을 평가하되 local fa - `mapValidationFailureToFields` - `useDirtyNavigationGuard` +구현 위치: + +- controller와 mapping: `src/presentation/forms` +- layout-only template: `src/presentation/templates` +- feature form schema/command mapper: + `src/features/reference-feature/presentation/reference-resource-form.ts` +- 실제 create page: + `src/features/reference-feature/presentation/reference-resource-form-page.tsx` + +`ApiFailure.validationIssues`는 HTTP 경계가 투영한 `path`와 `code`만 담는다. +backend message와 알 수 없는 path는 field copy로 사용하지 않는다. + 필수 동작: 1. label, description, error를 stable ID와 `aria-describedby`로 연결 diff --git a/docs/styling/design-system-platform.md b/docs/styling/design-system-platform.md index 3326ce9e..6a03aab4 100644 --- a/docs/styling/design-system-platform.md +++ b/docs/styling/design-system-platform.md @@ -34,6 +34,10 @@ - 초기 로딩, 빈 화면, terminal error, background 상태 - `src/presentation/components/state-surfaces.jsx` - 인증 필요, 권한 없음, 찾을 수 없음 +- `src/presentation/forms` + - local form facade, field/error summary, dirty navigation dialog +- `src/presentation/templates` + - Standard, Collection, Detail, Form, Status page template - `/examples/ui`, `/examples/states` - 실행 가능한 primitive와 상태 예제 - component/E2E/axe 테스트 @@ -47,8 +51,8 @@ 1. 토큰이 색상 중심이며 typography, elevation, motion, z-layer, control size, breakpoint가 계약으로 닫혀 있지 않다. -2. 공통 입력은 `TextField` 하나뿐이어서 일반적인 폼을 공통 규칙으로 만들 수 - 없다. +2. RP-06 form/page foundation은 준비됐지만 TextArea, Select, Checkbox, + RadioGroup 같은 form primitive 확장은 RP-07에 남아 있다. 3. 앱 셸과 예제 화면에서 공용 primitive 대신 raw `button`, `select`, 링크 class를 다시 작성하는 곳이 있다. 4. `☰`, `×` 같은 문자 glyph를 직접 사용하며 아이콘 공급자 경계가 없다. @@ -56,8 +60,8 @@ 6. runtime gallery는 있지만 격리된 story, interaction story, 시각 회귀 기준선이 없다. 7. 사용자 문구가 한국어 literal로 고정되어 locale과 RTL 계약이 없다. -8. `StandardPage`, `CollectionPage`, `DetailPage`, `FormPage` 같은 공통 페이지 - 템플릿이 없다. +8. page template은 준비됐지만 RP-07 design-system public entry와 token/pattern + 계층으로 정리해야 한다. 9. 모바일 sidebar는 표시 전환은 되지만 modal drawer 수준의 focus 이동, focus 복원, 배경 비활성화 계약은 없다. diff --git a/docs/testing/frontend-platform-testing-strategy.md b/docs/testing/frontend-platform-testing-strategy.md index 3f5d5fed..cc0cfad1 100644 --- a/docs/testing/frontend-platform-testing-strategy.md +++ b/docs/testing/frontend-platform-testing-strategy.md @@ -454,6 +454,16 @@ composition을 검증한다. 제거 모드는 feature source/tests와 installed contract/runtime/adapter contribution을 제거한 복제본에서 P0 gate와 built asset 잔여 0개를 다시 검증한다. +RP-06 form/page matrix는 `tests/component/form-foundation.test.tsx`, +`tests/component/page-templates.test.tsx`, +`tests/features/reference-feature/reference-page.test.tsx`와 +`tests/e2e/reference-form.spec.js`에 있다. client validation에서 command 0회와 +첫 오류 focus, Zod transform/default, pending 중 중복 제출, 승인된 422 +field/unknown field mapping, conflict 입력 보존, reset/dirty, navigation +confirmation/focus restore, URL/storage 비노출과 320px reflow를 검증한다. +HTTP integration test는 backend copy를 버리고 422 `path`/`code`만 전달하는지 +별도로 검사한다. + ## 8. Form 테스트 Form test는 field primitive, form controller, application command mapping을 diff --git a/eslint.config.js b/eslint.config.js index c2a92ef0..66979373 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -190,6 +190,17 @@ export default [ ]), }, }, + { + files: [`src/presentation/templates/**/*.${sourceExtensions}`], + rules: { + "no-restricted-imports": restrictedImports([ + "**/application/**", + "**/adapters/**", + "**/bootstrap/**", + "@tanstack/**", + ]), + }, + }, { files: [`src/adapters/**/*.${sourceExtensions}`], rules: { @@ -272,6 +283,7 @@ export default [ "@tanstack/**", "react", "react-dom", + "**/application/**", ]), "no-restricted-globals": [ "error", diff --git a/package.json b/package.json index 936e69a3..64f9bf5d 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "check:types:fixture:application-input": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-application-input.ts", "check:types:fixture:async-overlay": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-async-overlay.ts", "check:types:fixture:route-runtime": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-route-runtime.ts", + "check:types:fixture:page-action": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --jsx react-jsx tests/fixtures/typecheck/invalid-page-action.tsx", "test:runtime-schema": "vitest run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests", "test:unit": "vitest run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml", "test:component": "vitest run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml", diff --git a/public/release-manifest.json b/public/release-manifest.json index ce70cd60..553bde5c 100644 --- a/public/release-manifest.json +++ b/public/release-manifest.json @@ -14,6 +14,9 @@ "route-examples-states": "src/presentation/examples/state-gallery-page.jsx", "route-examples-auth": "src/presentation/examples/auth-example-page.jsx", "route-reference-resources": "src/features/reference-feature/presentation/reference-resource-page.tsx", + "route-reference-resource-detail": "src/features/reference-feature/presentation/reference-resource-detail-page.tsx", + "route-reference-resource-form": "src/features/reference-feature/presentation/reference-resource-form-page.tsx", + "route-reference-resource-status": "src/features/reference-feature/presentation/reference-resource-status-page.tsx", "route-not-found": "src/presentation/pages/not-found-page.jsx" } } diff --git a/scripts/check-registries.mjs b/scripts/check-registries.mjs index 60692dad..7586c6d4 100644 --- a/scripts/check-registries.mjs +++ b/scripts/check-registries.mjs @@ -173,6 +173,11 @@ const adHocPatterns = [ /** @param {string} directory */ async function scanDirectory(directory) { + try { + await access(directory); + } catch { + return; + } const entries = await import("node:fs/promises").then(({ readdir }) => readdir(directory, { withFileTypes: true }), ); diff --git a/scripts/test-sample-removal.mjs b/scripts/test-sample-removal.mjs index 0cf76776..ee3fe8b7 100644 --- a/scripts/test-sample-removal.mjs +++ b/scripts/test-sample-removal.mjs @@ -14,6 +14,11 @@ const fixtureRoot = path.resolve(".tmp/reference-feature-removal"); const pnpmCli = /** @type {string} */ (process.env.npm_execpath); const featureSource = "src/features/reference-feature"; const featureTests = "tests/features/reference-feature"; +const featureOwnedPaths = [ + featureSource, + featureTests, + "tests/e2e/reference-form.spec.js", +]; const copyTargets = [ "src", "tests", @@ -112,14 +117,12 @@ for (const target of copyTargets) { } await symlink(path.resolve("node_modules"), path.join(fixtureRoot, "node_modules"), "dir"); -await rm(path.join(fixtureRoot, featureSource), { - recursive: true, - force: true, -}); -await rm(path.join(fixtureRoot, featureTests), { - recursive: true, - force: true, -}); +for (const ownedPath of featureOwnedPaths) { + await rm(path.join(fixtureRoot, ownedPath), { + recursive: true, + force: true, + }); +} await writeFile( path.join(fixtureRoot, "src/features/installed-feature-contracts.js"), emptyContracts, diff --git a/src/adapters/http/client.js b/src/adapters/http/client.js index a590c3e8..d4561937 100644 --- a/src/adapters/http/client.js +++ b/src/adapters/http/client.js @@ -4,6 +4,7 @@ import { createFailure as failure, kindForStatus as statusKind, normalizeUnknownFailure, + safeValidationIssues, } from "../../contracts/errors.js"; import { mapOperationPayload } from "./resource-mapper.js"; import { retryDelay, shouldRetry } from "./retry-policy.js"; @@ -415,6 +416,10 @@ async function parseResponse( const kind = statusKind(response.status); const retryAfter = response.headers.get("retry-after"); + const backendError = + envelopeRecord.error && typeof envelopeRecord.error === "object" + ? /** @type {Record} */ (envelopeRecord.error) + : {}; return { ok: false, error: failure(kind, operation.operationId, attempt, { @@ -426,6 +431,10 @@ async function parseResponse( response.status === 429 && retryAfter ? parseRetryAfterHeader(retryAfter) : undefined, + validationIssues: + response.status === 422 + ? safeValidationIssues(backendError.details) + : undefined, }), }; } diff --git a/src/contracts/errors.js b/src/contracts/errors.js index 40d924ff..fb7429da 100644 --- a/src/contracts/errors.js +++ b/src/contracts/errors.js @@ -195,6 +195,7 @@ export const ERROR_REGISTRY = Object.freeze({ * requestId?: string, * traceId?: string, * retryAfterMs?: number, + * validationIssues?: readonly Readonly<{path: string, code: string}>[], * userMessageKey: string, * action: ErrorAction, * causeClass?: string @@ -211,6 +212,7 @@ export const ERROR_REGISTRY = Object.freeze({ * requestId?: string, * traceId?: string, * retryAfterMs?: number, + * validationIssues?: readonly Readonly<{path: string, code: string}>[], * causeClass?: string * }} [details] * @returns {ApiFailure} @@ -236,6 +238,24 @@ export function createFailure(kind, operationId, attempt, details = {}) { ...(typeof details.retryAfterMs === "number" ? { retryAfterMs: details.retryAfterMs } : {}), + ...(Array.isArray(details.validationIssues) + ? { + validationIssues: Object.freeze( + details.validationIssues + .filter( + (issue) => + issue && + typeof issue === "object" && + typeof issue.path === "string" && + typeof issue.code === "string", + ) + .slice(0, 50) + .map((issue) => + Object.freeze({ path: issue.path, code: issue.code }), + ), + ), + } + : {}), ...(typeof details.causeClass === "string" ? { causeClass: details.causeClass } : {}), @@ -244,6 +264,44 @@ export function createFailure(kind, operationId, attempt, details = {}) { }); } +/** + * Projects an untrusted 422 details payload into the only validation metadata + * allowed to cross the HTTP boundary. Backend copy and additional values are + * deliberately discarded. + * + * @param {unknown} value + * @returns {readonly Readonly<{path: string, code: string}>[]} + */ +export function safeValidationIssues(value) { + if (!value || typeof value !== "object") return Object.freeze([]); + const candidate = + /** @type {{issues?: unknown, fieldErrors?: unknown}} */ (value); + const issues = Array.isArray(candidate.issues) + ? candidate.issues + : Array.isArray(candidate.fieldErrors) + ? candidate.fieldErrors + : []; + return Object.freeze( + issues + .filter( + (issue) => + issue && + typeof issue === "object" && + typeof issue.path === "string" && + typeof issue.code === "string" && + issue.path.length <= 120 && + issue.code.length <= 80, + ) + .slice(0, 50) + .map((issue) => + Object.freeze({ + path: issue.path, + code: issue.code, + }), + ), + ); +} + /** @param {number} status */ export function kindForStatus(status) { if (status === 401) return "AUTH_REQUIRED"; diff --git a/src/features/reference-feature/README.md b/src/features/reference-feature/README.md index ef1d454d..80be3c8e 100644 --- a/src/features/reference-feature/README.md +++ b/src/features/reference-feature/README.md @@ -6,11 +6,11 @@ reference implementation이다. ## 소유 경계 - `domain`: 외부 DTO와 React를 모르는 불변 model -- `application`: UI가 호출하는 list/create input과 gateway 계약 +- `application`: UI가 호출하는 list/get/create input과 gateway 계약 - `adapters`: HTTP executor를 gateway로 투영하는 outbound adapter - `contracts`: route/API/query contribution, Zod DTO와 request schema, mapper -- `presentation`: route input을 query/mutation controller로 연결하는 inbound - adapter와 page +- `presentation`: route input을 query/form controller로 연결하는 inbound + adapter, 독립 form schema/command mapper와 list/detail/form/status page generic application은 `features.get(featureId)` catalog만 제공한다. feature hook이 자신의 input shape를 확인하며 page는 HTTP client, storage, auth owner, output @@ -33,7 +33,7 @@ corepack pnpm test:sample-removal ``` 첫 명령은 URL filter와 query key/HTTP request의 동일성, schema/mapper, 모든 -query/mutation 상태와 production composition을 검증한다. 두 번째 명령은 임시 +query/mutation/form 상태와 production composition을 검증한다. 두 번째 명령은 임시 복제본에서 이 source/test 디렉터리를 제거하고 installed catalog를 빈 목록으로 재생성한 뒤 typecheck, architecture, registry, unit/integration, home smoke, -production build와 fixture ID 잔여 0개를 검사한다. +production build와 source/built fixture ID 잔여 0개를 검사한다. diff --git a/src/features/reference-feature/adapters/reference-http-gateway.ts b/src/features/reference-feature/adapters/reference-http-gateway.ts index 5497a4d1..6063c94e 100644 --- a/src/features/reference-feature/adapters/reference-http-gateway.ts +++ b/src/features/reference-feature/adapters/reference-http-gateway.ts @@ -14,6 +14,7 @@ type HttpExecutor = Readonly<{ request: Readonly<{ operationId: string; routeId: string; + pathParams?: Record; searchParams?: unknown; body?: unknown; signal?: AbortSignal; @@ -42,7 +43,7 @@ export function createReferenceHttpGateway( } : result; }, - async create(command: Readonly<{ name: string }>) { + async create(command: Readonly<{ name: string; note?: string }>) { const result = await http.execute({ operationId: "CREATE_REFERENCE_RESOURCE", routeId: "REFERENCE_RESOURCE_LIST", @@ -52,5 +53,19 @@ export function createReferenceHttpGateway( ? { ok: true as const, value: result.value as ReferenceResource } : result; }, + async get( + resourceId: string, + context?: Readonly<{ signal?: AbortSignal }>, + ) { + const result = await http.execute({ + operationId: "GET_REFERENCE_RESOURCE", + routeId: "REFERENCE_RESOURCE_DETAIL", + pathParams: { resourceId }, + signal: context?.signal, + }); + return result.ok + ? { ok: true as const, value: result.value as ReferenceResource } + : result; + }, }); } diff --git a/src/features/reference-feature/application/reference-feature-api.ts b/src/features/reference-feature/application/reference-feature-api.ts index c8d0e403..0eade92d 100644 --- a/src/features/reference-feature/application/reference-feature-api.ts +++ b/src/features/reference-feature/application/reference-feature-api.ts @@ -21,7 +21,11 @@ export type ReferenceFeatureInput = Readonly<{ context?: Readonly<{ signal?: AbortSignal }>, ): Promise>; createResource( - command: Readonly<{ name: string }>, + command: Readonly<{ name: string; note?: string }>, + ): Promise>; + getResource( + resourceId: string, + context?: Readonly<{ signal?: AbortSignal }>, ): Promise>; }>; @@ -31,7 +35,11 @@ export type ReferenceGateway = Readonly<{ context?: Readonly<{ signal?: AbortSignal }>, ): Promise>; create( - command: Readonly<{ name: string }>, + command: Readonly<{ name: string; note?: string }>, + ): Promise>; + get( + resourceId: string, + context?: Readonly<{ signal?: AbortSignal }>, ): Promise>; }>; @@ -54,5 +62,11 @@ export function createReferenceFeatureInput( ? { ok: true as const, value: toReferenceView(result.value) } : result; }, + async getResource(resourceId, context) { + const result = await gateway.get(resourceId, context); + return result.ok + ? { ok: true as const, value: toReferenceView(result.value) } + : result; + }, }); } diff --git a/src/features/reference-feature/contracts/reference-feature-contract.js b/src/features/reference-feature/contracts/reference-feature-contract.js index b34fe033..86f4d07c 100644 --- a/src/features/reference-feature/contracts/reference-feature-contract.js +++ b/src/features/reference-feature/contracts/reference-feature-contract.js @@ -7,6 +7,9 @@ export const referenceQueryKeys = Object.freeze({ all: () => REFERENCE_NAMESPACE, list: (filters = {}) => Object.freeze([...REFERENCE_NAMESPACE, "list", canonicalize(filters)]), + /** @param {string} resourceId */ + detail: (resourceId) => + Object.freeze([...REFERENCE_NAMESPACE, "detail", String(resourceId)]), }); export const REFERENCE_FEATURE_CONTRACT = Object.freeze({ @@ -25,6 +28,45 @@ export const REFERENCE_FEATURE_CONTRACT = Object.freeze({ navigationLabel: "Reference feature", navigationOrder: 50, }), + REFERENCE_RESOURCE_DETAIL: Object.freeze({ + routeId: "REFERENCE_RESOURCE_DETAIL", + path: "/examples/reference-resources/:resourceId", + paramsSchema: "ReferenceResourceParams", + searchSchema: null, + access: "integration-defined", + loadingSurface: "reference-resource-detail", + errorSurface: "feature-boundary", + chunkId: "route-reference-resource-detail", + title: "Reference detail", + navigationLabel: null, + navigationOrder: null, + }), + REFERENCE_RESOURCE_FORM: Object.freeze({ + routeId: "REFERENCE_RESOURCE_FORM", + path: "/examples/reference-resources/new", + paramsSchema: null, + searchSchema: null, + access: "integration-defined", + loadingSurface: "reference-resource-form", + errorSurface: "feature-boundary", + chunkId: "route-reference-resource-form", + title: "Reference form", + navigationLabel: null, + navigationOrder: null, + }), + REFERENCE_RESOURCE_STATUS: Object.freeze({ + routeId: "REFERENCE_RESOURCE_STATUS", + path: "/examples/reference-resources/status", + paramsSchema: null, + searchSchema: null, + access: "integration-defined", + loadingSurface: "reference-resource-status", + errorSurface: "feature-boundary", + chunkId: "route-reference-resource-status", + title: "Reference status", + navigationLabel: null, + navigationOrder: null, + }), }), routeRuntimeContracts: Object.freeze({ REFERENCE_RESOURCE_LIST: Object.freeze({ @@ -33,6 +75,24 @@ export const REFERENCE_FEATURE_CONTRACT = Object.freeze({ paramsCodec: "none", searchCodec: "ReferenceResourceListQuery", }), + REFERENCE_RESOURCE_DETAIL: Object.freeze({ + routeId: "REFERENCE_RESOURCE_DETAIL", + moduleId: "reference-resource-detail-page", + paramsCodec: "ReferenceResourceParams", + searchCodec: "none", + }), + REFERENCE_RESOURCE_FORM: Object.freeze({ + routeId: "REFERENCE_RESOURCE_FORM", + moduleId: "reference-resource-form-page", + paramsCodec: "none", + searchCodec: "none", + }), + REFERENCE_RESOURCE_STATUS: Object.freeze({ + routeId: "REFERENCE_RESOURCE_STATUS", + moduleId: "reference-resource-status-page", + paramsCodec: "none", + searchCodec: "none", + }), }), apiOperations: Object.freeze({ LIST_REFERENCE_RESOURCES: Object.freeze({ @@ -61,6 +121,19 @@ export const REFERENCE_FEATURE_CONTRACT = Object.freeze({ responseSchema: "ReferenceResourcePayload", owner: "feature-frontend-reference-feature-vertical-slice", }), + GET_REFERENCE_RESOURCE: Object.freeze({ + method: "GET", + path: "/api/reference-resources/{resourceId}", + operationId: "GET_REFERENCE_RESOURCE", + auth: "external-session", + timeoutMs: null, + idempotency: "safe", + retry: "runtime", + requestSource: "none", + requestSchema: "NoRequest", + responseSchema: "ReferenceResourcePayload", + owner: "feature-frontend-form-page-platform", + }), }), queryRegistry: Object.freeze({ REFERENCE_RESOURCE: Object.freeze({ diff --git a/src/features/reference-feature/contracts/reference-mapper.ts b/src/features/reference-feature/contracts/reference-mapper.ts index 634732b5..06b39a6c 100644 --- a/src/features/reference-feature/contracts/reference-mapper.ts +++ b/src/features/reference-feature/contracts/reference-mapper.ts @@ -33,7 +33,10 @@ export function mapReferenceOperation( if (!Array.isArray(payload)) throw new TypeError("Expected a reference list"); return payload.map(mapReferenceDto); } - if (operationId === "CREATE_REFERENCE_RESOURCE") { + if ( + operationId === "CREATE_REFERENCE_RESOURCE" || + operationId === "GET_REFERENCE_RESOURCE" + ) { return mapReferenceDto(payload); } throw new TypeError(`No reference mapper registered for ${operationId}`); diff --git a/src/features/reference-feature/contracts/reference-schemas.ts b/src/features/reference-feature/contracts/reference-schemas.ts index 08d80669..0c6031b1 100644 --- a/src/features/reference-feature/contracts/reference-schemas.ts +++ b/src/features/reference-feature/contracts/reference-schemas.ts @@ -18,6 +18,12 @@ export const referenceResourceListQuerySchema = z }) .strict(); +export const referenceResourceParamsSchema = z + .object({ + resourceId: z.string().trim().min(1).max(120), + }) + .strict(); + const referenceResourceDtoSchema = z .object({ id: z.string().min(1), @@ -36,6 +42,7 @@ const requestSchemas = { CreateReferenceResourceCommand: z .object({ name: z.string().trim().min(1).max(120), + note: z.string().trim().max(500).optional(), }) .strict(), } satisfies Record; diff --git a/src/features/reference-feature/presentation/reference-feature-runtime.tsx b/src/features/reference-feature/presentation/reference-feature-runtime.tsx index cd16f99b..68da3880 100644 --- a/src/features/reference-feature/presentation/reference-feature-runtime.tsx +++ b/src/features/reference-feature/presentation/reference-feature-runtime.tsx @@ -1,9 +1,13 @@ import { lazy } from "react"; -import { referenceResourceListQuerySchema } from "../contracts/reference-schemas.js"; +import { + referenceResourceListQuerySchema, + referenceResourceParamsSchema, +} from "../contracts/reference-schemas.js"; export const REFERENCE_FEATURE_ROUTE_CODECS = { ReferenceResourceListQuery: referenceResourceListQuerySchema, + ReferenceResourceParams: referenceResourceParamsSchema, } as const; export const REFERENCE_FEATURE_ROUTE_RUNTIME = { @@ -11,4 +15,16 @@ export const REFERENCE_FEATURE_ROUTE_RUNTIME = { moduleId: "reference-resource-page", Component: lazy(() => import("./reference-resource-page.js")), }), + REFERENCE_RESOURCE_DETAIL: Object.freeze({ + moduleId: "reference-resource-detail-page", + Component: lazy(() => import("./reference-resource-detail-page.js")), + }), + REFERENCE_RESOURCE_FORM: Object.freeze({ + moduleId: "reference-resource-form-page", + Component: lazy(() => import("./reference-resource-form-page.js")), + }), + REFERENCE_RESOURCE_STATUS: Object.freeze({ + moduleId: "reference-resource-status-page", + Component: lazy(() => import("./reference-resource-status-page.js")), + }), } as const; diff --git a/src/features/reference-feature/presentation/reference-resource-detail-page.tsx b/src/features/reference-feature/presentation/reference-resource-detail-page.tsx new file mode 100644 index 00000000..cedaccaa --- /dev/null +++ b/src/features/reference-feature/presentation/reference-resource-detail-page.tsx @@ -0,0 +1,47 @@ +import { Link } from "react-router-dom"; + +import { AsyncSurface } from "../../../presentation/components/async-surface.jsx"; +import { DetailPage } from "../../../presentation/templates/index.js"; +import { useRouteInput } from "../../../presentation/routes/app-router.js"; +import { useReferenceDetail } from "./use-reference-feature.js"; + +export default function ReferenceResourceDetailPage() { + const route = useRouteInput(); + const resourceId = String(route.params.resourceId); + const { query } = useReferenceDetail(resourceId); + const resource = query.data; + + return ( + Reference resources + } + heading={{ + eyebrow: "DetailPage", + title: resource?.title ?? "Reference detail", + description: "route param과 detail query의 reset 경계를 확인합니다.", + }} + metadata={ + resource ? ( +
+
Resource ID
+
{resource.resourceId}
+
Created
+
{resource.createdAtLabel ?? "표시 정보 없음"}
+
+ ) : ( +

요약 정보를 준비하고 있습니다.

+ ) + } + feedback={ + + {resource ? ( +

이 영역에는 제품별 상세 section을 조립할 수 있습니다.

+ ) : null} +
+ } + aside={

상세 페이지의 관련 정보 slot입니다.

} + /> + ); +} diff --git a/src/features/reference-feature/presentation/reference-resource-form-page.tsx b/src/features/reference-feature/presentation/reference-resource-form-page.tsx new file mode 100644 index 00000000..8e907828 --- /dev/null +++ b/src/features/reference-feature/presentation/reference-resource-form-page.tsx @@ -0,0 +1,131 @@ +import { useCallback } from "react"; +import { useNavigate } from "react-router-dom"; + +import { Button } from "../../../presentation/components/ui/button.jsx"; +import { + DirtyNavigationDialog, + ErrorSummary, + Form, + FormActions, + FormField, + useAppForm, + useDirtyNavigationGuard, +} from "../../../presentation/forms/index.js"; +import { FormPage } from "../../../presentation/templates/index.js"; +import { + REFERENCE_FORM_DEFAULTS, + referenceResourceFormSchema, + toCreateReferenceCommand, + type ReferenceResourceFormValues, +} from "./reference-resource-form.js"; +import { useReferenceCreate } from "./use-reference-feature.js"; + +const FIELD_LABELS = Object.freeze({ + name: "새 항목 이름", + note: "설명", +}) satisfies Record; + +export default function ReferenceResourceFormPage() { + const navigate = useNavigate(); + const mutation = useReferenceCreate(); + const submit = useCallback( + (command: ReturnType) => + mutation.submit(command), + [mutation], + ); + const form = useAppForm({ + schema: referenceResourceFormSchema, + defaultValues: REFERENCE_FORM_DEFAULTS, + allowedServerFields: ["name", "note"], + mapToCommand: toCreateReferenceCommand, + submit, + }); + const guard = useDirtyNavigationGuard(form.dirty && !form.pending); + + return ( +
void form.submitForm(event)} + > + navigate("/examples/reference-resources")} + > + 목록으로 돌아가기 + + } + heading={{ + eyebrow: "FormPage", + title: "Reference resource 만들기", + description: + "presentation schema, command mapper, 422/conflict와 dirty navigation 정책을 실행합니다.", + }} + errorSummary={ + + } + fields={ + <> + + + + } + formActions={ + + + + + + } + feedback={ + form.result === "success" ? ( +

저장했습니다.

+ ) : form.result === "conflict" ? ( +

충돌을 해결한 뒤 다시 제출할 수 있습니다.

+ ) : null + } + aside={ +

+ form value는 URL, storage, telemetry에 저장되지 않고 submit 시에만 + application command로 변환됩니다. +

+ } + guard={} + /> + + ); +} diff --git a/src/features/reference-feature/presentation/reference-resource-form.ts b/src/features/reference-feature/presentation/reference-resource-form.ts new file mode 100644 index 00000000..059c596b --- /dev/null +++ b/src/features/reference-feature/presentation/reference-resource-form.ts @@ -0,0 +1,29 @@ +import { z } from "zod"; + +export const referenceResourceFormSchema = z + .object({ + name: z + .string() + .trim() + .min(2, "이름은 두 글자 이상이어야 합니다.") + .max(120), + note: z.string().trim().max(500).default(""), + }) + .strict(); + +export type ReferenceResourceFormValues = z.infer< + typeof referenceResourceFormSchema +>; + +export const REFERENCE_FORM_DEFAULTS: ReferenceResourceFormValues = + Object.freeze({ + name: "", + note: "", + }); + +export function toCreateReferenceCommand(values: ReferenceResourceFormValues) { + return Object.freeze({ + name: values.name, + ...(values.note ? { note: values.note } : {}), + }); +} diff --git a/src/features/reference-feature/presentation/reference-resource-page.tsx b/src/features/reference-feature/presentation/reference-resource-page.tsx index c65a4f73..f396df6f 100644 --- a/src/features/reference-feature/presentation/reference-resource-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-page.tsx @@ -1,60 +1,53 @@ -import { useState, type FormEvent } from "react"; +import { Link, useNavigate } from "react-router-dom"; import { AsyncSurface } from "../../../presentation/components/async-surface.jsx"; import { Button } from "../../../presentation/components/ui/button.jsx"; -import { PageHeader } from "../../../presentation/components/page-header.jsx"; +import { CollectionPage } from "../../../presentation/templates/index.js"; import { useReferenceFeature } from "./use-reference-feature.js"; export default function ReferenceResourcePage() { - const { filters, query, mutation } = useReferenceFeature(); - const [name, setName] = useState(""); - - async function submit(event: FormEvent) { - event.preventDefault(); - const result = await mutation.submit({ name }); - if (result.ok) setName(""); - } + const navigate = useNavigate(); + const { filters, query } = useReferenceFeature(); return ( -
- -

- limit {filters.limit} - {filters.tags?.length ? ` · tags ${filters.tags.join(", ")}` : ""} -

+ navigate("/examples/reference-resources/new"), + }, + ]} + activeFilters={ +

+ limit {filters.limit} + {filters.tags?.length ? ` · tags ${filters.tags.join(", ")}` : ""} +

+ } + toolbar={} + resultCount={ + query.data ? `총 ${query.data.length}개 항목` : "결과 확인 중" + } + >
    {(query.data ?? []).map((resource) => ( -
  • - {resource.title} +
  • + + {resource.title} +
  • ))}
- -
void submit(event)}> - - setName(event.currentTarget.value)} - required - /> - -
-
-
+ ); } diff --git a/src/features/reference-feature/presentation/reference-resource-status-page.tsx b/src/features/reference-feature/presentation/reference-resource-status-page.tsx new file mode 100644 index 00000000..4f748d6e --- /dev/null +++ b/src/features/reference-feature/presentation/reference-resource-status-page.tsx @@ -0,0 +1,25 @@ +import { useNavigate } from "react-router-dom"; + +import { StatusPage } from "../../../presentation/templates/index.js"; + +export default function ReferenceResourceStatusPage() { + const navigate = useNavigate(); + + return ( + navigate("/examples/reference-resources"), + }} + supportReference="REFERENCE-STATUS-DEMO" + /> + ); +} diff --git a/src/features/reference-feature/presentation/use-reference-feature.ts b/src/features/reference-feature/presentation/use-reference-feature.ts index 8a4def4b..f051ae6f 100644 --- a/src/features/reference-feature/presentation/use-reference-feature.ts +++ b/src/features/reference-feature/presentation/use-reference-feature.ts @@ -14,19 +14,38 @@ import type { ReferenceListFilters, } from "../application/reference-feature-api.js"; -function useReferenceFeatureInput(): ReferenceFeatureInput { +export function useReferenceFeatureInput(): ReferenceFeatureInput { const candidate = useApplication().features.get(REFERENCE_FEATURE_ID); if ( !candidate || typeof candidate !== "object" || typeof (candidate as ReferenceFeatureInput).listResources !== "function" || - typeof (candidate as ReferenceFeatureInput).createResource !== "function" + typeof (candidate as ReferenceFeatureInput).createResource !== "function" || + typeof (candidate as ReferenceFeatureInput).getResource !== "function" ) { throw new Error("Reference feature application input is invalid"); } return candidate as ReferenceFeatureInput; } +export function useReferenceDetail(resourceId: string) { + const input = useReferenceFeatureInput(); + const query = useApplicationQuery({ + queryKey: referenceQueryKeys.detail(resourceId), + execute: ({ signal }) => input.getResource(resourceId, { signal }), + }); + return Object.freeze({ query }); +} + +export function useReferenceCreate() { + const input = useReferenceFeatureInput(); + return useApplicationMutation({ + execute: input.createResource, + invalidate: [referenceQueryKeys.all()], + currentData: true, + }); +} + export function useReferenceFeature() { const input = useReferenceFeatureInput(); const routeInput = useRouteInput(); diff --git a/src/presentation/forms/form-components.tsx b/src/presentation/forms/form-components.tsx new file mode 100644 index 00000000..0bbfa7cf --- /dev/null +++ b/src/presentation/forms/form-components.tsx @@ -0,0 +1,90 @@ +import { useId, type FormHTMLAttributes, type ReactNode } from "react"; + +import { TextField } from "../components/ui/text-field.jsx"; +import type { + FieldErrors, + FieldName, + FormValues, +} from "./form-contracts.js"; + +export function Form( + props: FormHTMLAttributes & Readonly<{ pending?: boolean }>, +) { + const { pending = false, children, ...formProps } = props; + return ( +
+ {children} +
+ ); +} + +export function FormField( + props: React.ComponentProps, +) { + return ; +} + +export function ErrorSummary(props: Readonly<{ + fieldErrors: FieldErrors; + formErrors?: readonly string[]; + fieldLabels: Readonly, string>>; + fieldId(name: FieldName): string; + onFocusField?(name: FieldName): void; +}>) { + const { + fieldErrors, + formErrors = [], + fieldLabels, + fieldId, + onFocusField, + } = props; + const headingId = useId(); + const entries = Object.entries(fieldErrors) as [ + FieldName, + string, + ][]; + if (entries.length === 0 && formErrors.length === 0) return null; + return ( +
+

입력 내용을 확인해 주세요.

+ {entries.length > 0 ? ( + + ) : null} + {formErrors.map((message) => ( +

{message}

+ ))} +
+ ); +} + +export function FormActions(props: Readonly<{ + children: ReactNode; + sticky?: boolean; +}>) { + return ( +
+ {props.children} +
+ ); +} diff --git a/src/presentation/forms/form-contracts.ts b/src/presentation/forms/form-contracts.ts new file mode 100644 index 00000000..c1f409ee --- /dev/null +++ b/src/presentation/forms/form-contracts.ts @@ -0,0 +1,69 @@ +import type { ApiFailure } from "../../contracts/errors.js"; + +export type FormValues = Readonly>; +export type FieldName = Extract; +export type FieldErrors = Readonly< + Partial, string>> +>; + +export type FormResult = + | Readonly<{ ok: true; value: Value }> + | Readonly<{ ok: false; error: ApiFailure }>; + +export type FormResultState = + | "idle" + | "success" + | "validation-error" + | "conflict" + | "unavailable"; + +export type MappedValidationFailure = Readonly<{ + fieldErrors: FieldErrors; + formErrors: readonly string[]; +}>; + +const VALIDATION_COPY = Object.freeze({ + REQUIRED: "필수 입력값입니다.", + too_small: "입력값이 너무 짧습니다.", + too_big: "입력값이 너무 깁니다.", + invalid_type: "입력 형식을 확인해 주세요.", + invalid_format: "입력 형식을 확인해 주세요.", + invalid_value: "허용된 값을 선택해 주세요.", +}); + +export function validationMessage(code: string): string { + return ( + VALIDATION_COPY[code as keyof typeof VALIDATION_COPY] ?? + "입력값을 확인해 주세요." + ); +} + +export function mapValidationFailureToFields( + failure: ApiFailure, + allowedFields: readonly FieldName[], +): MappedValidationFailure { + if (failure.kind !== "VALIDATION_REJECTED") { + return Object.freeze({ fieldErrors: Object.freeze({}), formErrors: [] }); + } + const allowed = new Set(allowedFields); + const fieldErrors: Partial, string>> = {}; + const formErrors: string[] = []; + const issues = failure.validationIssues ?? []; + + if (issues.length === 0) { + formErrors.push("입력값을 다시 확인해 주세요."); + } + for (const issue of issues) { + const field = issue.path.split(".").at(0) ?? ""; + if (allowed.has(field)) { + const name = field as FieldName; + fieldErrors[name] ??= validationMessage(issue.code); + } else { + formErrors.push("서버가 확인하지 못한 입력 항목이 있습니다."); + } + } + return Object.freeze({ + fieldErrors: Object.freeze(fieldErrors), + formErrors: Object.freeze([...new Set(formErrors)]), + }); +} diff --git a/src/presentation/forms/index.ts b/src/presentation/forms/index.ts new file mode 100644 index 00000000..7ea1e7f4 --- /dev/null +++ b/src/presentation/forms/index.ts @@ -0,0 +1,4 @@ +export * from "./form-components.js"; +export * from "./form-contracts.js"; +export * from "./use-app-form.js"; +export * from "./use-dirty-navigation-guard.js"; diff --git a/src/presentation/forms/use-app-form.ts b/src/presentation/forms/use-app-form.ts new file mode 100644 index 00000000..f17b4e9a --- /dev/null +++ b/src/presentation/forms/use-app-form.ts @@ -0,0 +1,244 @@ +import { + useCallback, + useId, + useMemo, + useRef, + useState, + type ChangeEvent, + type FormEvent, +} from "react"; +import type { ZodType, ZodIssue } from "zod"; + +import { + mapValidationFailureToFields, + validationMessage, + type FieldErrors, + type FieldName, + type FormResult, + type FormResultState, + type FormValues, +} from "./form-contracts.js"; + +type AppFormOptions< + Values extends FormValues, + Command, + Output, +> = Readonly<{ + schema: ZodType; + defaultValues: Values; + allowedServerFields: readonly FieldName[]; + mapToCommand(values: Values): Command; + submit(command: Command): Promise>; + resetOnSuccess?: boolean; +}>; + +export function useAppForm< + Values extends FormValues, + Command, + Output, +>(options: AppFormOptions) { + const { + schema, + defaultValues, + allowedServerFields, + mapToCommand, + submit, + resetOnSuccess = true, + } = options; + const generatedId = useId().replaceAll(":", ""); + const formId = `app-form-${generatedId}`; + const [values, setValues] = useState(defaultValues); + const [initialValues, setInitialValues] = useState(defaultValues); + const [touched, setTouched] = useState>>( + () => new Set(), + ); + const [fieldErrors, setFieldErrors] = useState>( + () => ({} as FieldErrors), + ); + const [formErrors, setFormErrors] = useState([]); + const [pending, setPending] = useState(false); + const [result, setResult] = useState("idle"); + const pendingRef = useRef> | null>(null); + + const dirty = useMemo( + () => JSON.stringify(values) !== JSON.stringify(initialValues), + [initialValues, values], + ); + + const fieldId = useCallback( + (name: FieldName) => `${formId}-${name}`, + [formId], + ); + + const focusField = useCallback( + (name: FieldName) => { + const field = document.getElementById(fieldId(name)); + if (field instanceof HTMLElement) field.focus(); + }, + [fieldId], + ); + + const focusFirstError = useCallback( + (errors: FieldErrors) => { + const first = allowedServerFields.find((name) => Boolean(errors[name])); + if (first) focusField(first); + }, + [allowedServerFields, focusField], + ); + + const setValue = useCallback( + (name: FieldName, value: Values[FieldName]) => { + setValues((current) => ({ ...current, [name]: value }) as Values); + setFieldErrors((current) => { + if (!current[name]) return current; + const next = { ...current }; + delete next[name]; + return next; + }); + setFormErrors([]); + setResult("idle"); + }, + [], + ); + + const field = useCallback( + (name: FieldName) => ({ + id: fieldId(name), + name, + value: String(values[name] ?? ""), + onChange(event: ChangeEvent) { + setValue(name, event.currentTarget.value as Values[FieldName]); + }, + onBlur() { + setTouched((current) => new Set(current).add(name)); + }, + error: fieldErrors[name], + "aria-invalid": fieldErrors[name] ? ("true" as const) : undefined, + }), + [fieldErrors, fieldId, setValue, values], + ); + + const reset = useCallback( + (nextValues: Values = defaultValues) => { + setValues(nextValues); + setInitialValues(nextValues); + setTouched(new Set()); + setFieldErrors({} as FieldErrors); + setFormErrors([]); + setResult("idle"); + }, + [defaultValues], + ); + + const submitForm = useCallback( + async (event?: FormEvent): Promise | null> => { + event?.preventDefault(); + if (pendingRef.current) return pendingRef.current; + setFieldErrors({} as FieldErrors); + setFormErrors([]); + + const parsed = await schema.safeParseAsync(values); + if (!parsed.success) { + const errors = issuesToFieldErrors( + parsed.error.issues, + allowedServerFields, + ); + setFieldErrors(errors); + setFormErrors( + parsed.error.issues.some( + (issue) => !allowedServerFields.includes(issue.path[0] as FieldName), + ) + ? ["입력 구성을 다시 확인해 주세요."] + : [], + ); + setTouched(new Set(allowedServerFields)); + setResult("validation-error"); + focusFirstError(errors); + return null; + } + + const command = mapToCommand(parsed.data); + setPending(true); + const execution = submit(command); + pendingRef.current = execution; + try { + const outcome = await execution; + if (outcome.ok) { + setResult("success"); + if (resetOnSuccess) { + setValues(defaultValues); + setInitialValues(defaultValues); + setTouched(new Set()); + } else { + setInitialValues(parsed.data); + } + return outcome; + } + if (outcome.error.kind === "VALIDATION_REJECTED") { + const mapped = mapValidationFailureToFields( + outcome.error, + allowedServerFields, + ); + setFieldErrors(mapped.fieldErrors); + setFormErrors(mapped.formErrors); + setResult("validation-error"); + focusFirstError(mapped.fieldErrors); + } else if (outcome.error.kind === "CONFLICT") { + setFormErrors([ + "다른 변경과 충돌했습니다. 입력은 유지되었으니 최신 상태를 확인해 주세요.", + ]); + setResult("conflict"); + } else { + setFormErrors(["저장하지 못했습니다. 잠시 후 다시 시도해 주세요."]); + setResult("unavailable"); + } + return outcome; + } finally { + pendingRef.current = null; + setPending(false); + } + }, + [ + allowedServerFields, + defaultValues, + focusFirstError, + mapToCommand, + resetOnSuccess, + schema, + submit, + values, + ], + ); + + return Object.freeze({ + formId, + values, + dirty, + touched, + fieldErrors, + formErrors, + pending, + result, + field, + fieldId, + focusField, + setValue, + submitForm, + reset, + }); +} + +function issuesToFieldErrors( + issues: readonly ZodIssue[], + allowedFields: readonly FieldName[], +): FieldErrors { + const allowed = new Set(allowedFields); + const errors: Partial, string>> = {}; + for (const issue of issues) { + const field = issue.path[0]; + if (!allowed.has(field)) continue; + const name = field as FieldName; + errors[name] ??= validationMessage(issue.code); + } + return Object.freeze(errors); +} diff --git a/src/presentation/forms/use-dirty-navigation-guard.tsx b/src/presentation/forms/use-dirty-navigation-guard.tsx new file mode 100644 index 00000000..f0fb63f7 --- /dev/null +++ b/src/presentation/forms/use-dirty-navigation-guard.tsx @@ -0,0 +1,54 @@ +import { useCallback } from "react"; +import { useBeforeUnload, useBlocker } from "react-router-dom"; + +import { Button } from "../components/ui/button.jsx"; +import { Dialog } from "../components/ui/dialog.jsx"; + +export function useDirtyNavigationGuard(when: boolean) { + const blocker = useBlocker(when); + + useBeforeUnload( + useCallback( + (event) => { + if (!when) return; + event.preventDefault(); + event.returnValue = ""; + }, + [when], + ), + { capture: true }, + ); + + return Object.freeze({ + blocked: blocker.state === "blocked", + stay() { + blocker.reset?.(); + }, + leave() { + blocker.proceed?.(); + }, + }); +} + +export function DirtyNavigationDialog(props: Readonly<{ + guard: ReturnType; +}>) { + return ( + + + + + } + /> + ); +} diff --git a/src/presentation/styles/theme.css b/src/presentation/styles/theme.css index 7653fe8a..e2448630 100644 --- a/src/presentation/styles/theme.css +++ b/src/presentation/styles/theme.css @@ -590,6 +590,141 @@ line-height: 1.7; } + .page-template { + display: grid; + gap: 1.25rem; + min-width: 0; + } + + .page-template__breadcrumb { + padding-block-start: 1rem; + color: var(--color-content-muted); + font-size: 0.9rem; + } + + .page-template__heading { + display: grid; + min-width: 0; + grid-template-columns: minmax(0, 1fr) auto; + align-items: end; + gap: 1rem; + } + + .page-template__heading .page-header { + grid-row: span 2; + min-width: 0; + } + + .page-template__status, + .page-template__actions, + .status-page__actions, + .form-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: flex-end; + gap: 0.75rem; + } + + .page-template__layout { + display: grid; + min-width: 0; + gap: 1.5rem; + } + + .page-template__layout[data-has-aside="true"] { + grid-template-columns: minmax(0, 1fr) minmax(14rem, 20rem); + } + + .page-template__content, + .page-template__aside, + .collection-page__results, + .detail-page__sections, + .form-page__fields { + min-width: 0; + } + + .page-template__aside, + .detail-page__metadata, + .collection-page__toolbar, + .form-error-summary { + border: 1px solid var(--color-border); + border-radius: var(--radius-surface); + padding: 1rem; + background: var(--color-panel); + } + + .collection-page__toolbar, + .collection-page__active-filters, + .collection-page__bulk-actions { + display: flex; + flex-wrap: wrap; + align-items: end; + gap: 0.75rem; + } + + .collection-page__result-count { + color: var(--color-content-muted); + } + + .collection-page__results, + .detail-page__sections, + .form-page__fields, + .form-page__error-summary { + display: grid; + gap: 1rem; + } + + .collection-page__pagination { + margin-block-start: 1.25rem; + } + + .detail-page__danger { + margin-block-start: 2rem; + border-top: 1px solid var(--color-danger-border); + padding-block-start: 1rem; + } + + .form-error-summary { + border-color: var(--color-danger-border); + background: var(--color-danger-surface); + } + + .form-error-summary h2 { + font-size: 1.1rem; + } + + .form-error-summary p, + .form-error-summary ul { + margin-block-end: 0; + } + + .form-actions { + padding-block-start: 1rem; + border-top: 1px solid var(--color-border); + } + + .form-actions--sticky { + position: sticky; + z-index: 10; + bottom: 0; + padding: 0.75rem; + background: color-mix(in oklch, var(--color-panel) 94%, transparent); + } + + .status-page { + max-width: 48rem; + padding-block: 2rem; + } + + .status-page__actions { + justify-content: flex-start; + } + + .status-page__support { + color: var(--color-content-muted); + } + .readiness-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); @@ -832,6 +967,24 @@ .component-grid--three { grid-template-columns: minmax(0, 1fr); } + + .page-template__heading, + .page-template__layout[data-has-aside="true"] { + grid-template-columns: minmax(0, 1fr); + } + + .page-template__heading .page-header { + grid-row: auto; + } + + .page-template__actions, + .page-template__status { + justify-content: flex-start; + } + + .form-actions--sticky { + margin-inline: calc(var(--spacing-page) * -1); + } } @media (prefers-reduced-motion: reduce) { diff --git a/src/presentation/templates/index.ts b/src/presentation/templates/index.ts new file mode 100644 index 00000000..3cb33e1a --- /dev/null +++ b/src/presentation/templates/index.ts @@ -0,0 +1 @@ +export * from "./page-templates.js"; diff --git a/src/presentation/templates/page-templates.tsx b/src/presentation/templates/page-templates.tsx new file mode 100644 index 00000000..1cba5aff --- /dev/null +++ b/src/presentation/templates/page-templates.tsx @@ -0,0 +1,246 @@ +import type { ReactNode } from "react"; + +import { PageHeader } from "../components/page-header.jsx"; +import { Button } from "../components/ui/button.jsx"; + +export type PageHeading = Readonly<{ + title: string; + description?: string; + eyebrow?: string; +}>; + +export type PageActionDefinition = + | Readonly<{ + kind: "button"; + label: string; + onAction(): void; + disabled?: boolean; + variant?: "primary" | "secondary" | "danger" | "ghost"; + }> + | Readonly<{ + kind: "link"; + label: string; + href: string; + variant?: "primary" | "secondary" | "danger" | "ghost"; + }>; + +export type PageTemplateSlots = Readonly<{ + heading: PageHeading; + breadcrumb?: ReactNode; + status?: ReactNode; + actions?: readonly PageActionDefinition[]; + notices?: ReactNode; + children?: ReactNode; + aside?: ReactNode; + feedback?: ReactNode; +}>; + +export function StandardPage(props: PageTemplateSlots) { + return ( +
+ {props.breadcrumb ? ( + + ) : null} +
+ + {props.status ? ( +
{props.status}
+ ) : null} + {props.actions?.length ? ( + + ) : null} +
+ {props.notices ? ( +
{props.notices}
+ ) : null} + {props.feedback ? ( +
{props.feedback}
+ ) : null} +
+
{props.children}
+ {props.aside ? ( + + ) : null} +
+
+ ); +} + +export function CollectionPage( + props: PageTemplateSlots & + Readonly<{ + toolbar?: ReactNode; + activeFilters?: ReactNode; + resultCount?: ReactNode; + bulkActions?: ReactNode; + pagination?: ReactNode; + }>, +) { + return ( + + {props.notices} + {props.toolbar ? ( +
+ {props.toolbar} +
+ ) : null} + {props.activeFilters ? ( +
+ {props.activeFilters} +
+ ) : null} + {props.resultCount ? ( +
+ {props.resultCount} +
+ ) : null} + {props.bulkActions ? ( +
+ {props.bulkActions} +
+ ) : null} + + } + > +
{props.children}
+ {props.pagination ? ( + + ) : null} +
+ ); +} + +export function DetailPage( + props: PageTemplateSlots & + Readonly<{ + metadata?: ReactNode; + destructiveAction?: ReactNode; + }>, +) { + return ( + + {props.metadata ? ( +
+ {props.metadata} +
+ ) : null} +
{props.children}
+ {props.destructiveAction ? ( +
+ {props.destructiveAction} +
+ ) : null} +
+ ); +} + +export function FormPage( + props: PageTemplateSlots & + Readonly<{ + errorSummary?: ReactNode; + fields?: ReactNode; + formActions?: ReactNode; + guard?: ReactNode; + }>, +) { + return ( + + {props.errorSummary ? ( +
{props.errorSummary}
+ ) : null} +
{props.fields ?? props.children}
+ {props.formActions ? ( +
{props.formActions}
+ ) : null} + {props.guard} +
+ ); +} + +export type StatusPageVariant = + | "unauthenticated" + | "forbidden" + | "not-found" + | "unavailable" + | "offline" + | "maintenance" + | "unexpected"; + +export function StatusPage( + props: Readonly<{ + variant: StatusPageVariant; + heading: PageHeading; + primaryAction?: PageActionDefinition; + secondaryAction?: PageActionDefinition; + supportReference?: string; + }>, +) { + return ( +
+ + {props.primaryAction || props.secondaryAction ? ( + + ) : null} + {props.supportReference ? ( +

+ 지원 참조: {props.supportReference} +

+ ) : null} +
+ ); +} + +function PageActionBar(props: Readonly<{ + actions: readonly PageActionDefinition[]; + className?: string; +}>) { + return ( +
+ {props.actions.map((action) => + action.kind === "link" ? ( + + {action.label} + + ) : ( + + ), + )} +
+ ); +} diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx new file mode 100644 index 00000000..349b80a0 --- /dev/null +++ b/tests/component/form-foundation.test.tsx @@ -0,0 +1,199 @@ +// @vitest-environment jsdom + +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { useState } from "react"; +import { createMemoryRouter, RouterProvider, useNavigate } from "react-router-dom"; +import { z } from "zod"; +import { describe, expect, it, vi } from "vitest"; + +import { createFailure } from "../../src/contracts/errors.js"; +import { Button } from "../../src/presentation/components/ui/button.jsx"; +import { + DirtyNavigationDialog, + ErrorSummary, + Form, + FormField, + useAppForm, + useDirtyNavigationGuard, +} from "../../src/presentation/forms/index.js"; + +type Values = Readonly>; + +const schema = z + .object({ + name: z.string().trim().min(2), + note: z.string().trim().default(""), + }) + .strict(); +const defaults: Values = { name: "", note: "" }; + +function FormHarness(props: Readonly<{ + submit(command: Readonly<{ name: string; note?: string }>): Promise< + | Readonly<{ ok: true; value: string }> + | Readonly<{ ok: false; error: ReturnType }> + >; +}>) { + const form = useAppForm({ + schema, + defaultValues: defaults, + allowedServerFields: ["name", "note"], + mapToCommand(values) { + return { + name: values.name, + ...(values.note ? { note: values.note } : {}), + }; + }, + submit: props.submit, + }); + return ( +
void form.submitForm(event)}> + + + + + + {String(form.dirty)} + {form.result} + + ); +} + +describe("local form facade", () => { + it("focuses the first invalid field and performs no command", async () => { + const user = userEvent.setup(); + const submit = vi.fn(); + render(); + + await user.click(screen.getByRole("button", { name: "Submit" })); + + expect(submit).not.toHaveBeenCalled(); + expect(screen.getByRole("textbox", { name: /Name/ })).toHaveFocus(); + expect(screen.getByRole("alert")).toHaveTextContent("Name"); + }); + + it("submits transformed data once and clears dirty state after success", async () => { + const user = userEvent.setup(); + let finish: ((value: { ok: true; value: string }) => void) | undefined; + const submit = vi.fn( + () => + new Promise<{ ok: true; value: string }>((resolve) => { + finish = resolve; + }), + ); + render(); + await user.type(screen.getByRole("textbox", { name: /Name/ }), " Ready "); + await user.type(screen.getByRole("textbox", { name: "Note" }), " Safe "); + + await user.dblClick(screen.getByRole("button", { name: "Submit" })); + await waitFor(() => expect(submit).toHaveBeenCalledOnce()); + expect(submit).toHaveBeenCalledWith({ name: "Ready", note: "Safe" }); + expect(screen.getByRole("button", { name: "Pending" })).toBeDisabled(); + finish?.({ ok: true, value: "saved" }); + + await waitFor(() => expect(screen.getByTestId("dirty")).toHaveTextContent("false")); + expect(screen.getByTestId("result")).toHaveTextContent("success"); + }); + + it("maps only approved 422 fields and never renders backend copy", async () => { + const user = userEvent.setup(); + const failure = createFailure( + "VALIDATION_REJECTED", + "CREATE_ENTITY", + 0, + { + validationIssues: [ + { path: "name", code: "REQUIRED" }, + { path: "serverOnly", code: "raw-secret-message" }, + ], + }, + ); + render( + ({ ok: false, error: failure })} />, + ); + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid"); + await user.click(screen.getByRole("button", { name: "Submit" })); + + expect(await screen.findByRole("alert")).toHaveTextContent("필수 입력값입니다."); + expect(screen.getByRole("alert")).toHaveTextContent( + "서버가 확인하지 못한 입력 항목", + ); + expect(document.body).not.toHaveTextContent("raw-secret-message"); + }); + + it("keeps conflict input out of URL and storage", async () => { + const user = userEvent.setup(); + localStorage.clear(); + window.history.replaceState({}, "", "/form-test"); + render( + ({ + ok: false, + error: createFailure("CONFLICT", "CREATE_ENTITY", 0), + })} + />, + ); + const secretLike = "token-like-do-not-copy"; + await user.type(screen.getByRole("textbox", { name: /Name/ }), secretLike); + await user.click(screen.getByRole("button", { name: "Submit" })); + + expect(await screen.findByText(/다른 변경과 충돌했습니다/)).toBeVisible(); + expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue(secretLike); + expect(window.location.href).not.toContain(secretLike); + expect(JSON.stringify(localStorage)).not.toContain(secretLike); + }); +}); + +describe("dirty navigation guard", () => { + it("blocks navigation, restores focus on stay and proceeds explicitly", async () => { + const user = userEvent.setup(); + + function GuardedPage() { + const navigate = useNavigate(); + const [dirty, setDirty] = useState(false); + const guard = useDirtyNavigationGuard(dirty); + return ( + <> + + setDirty(true)} + /> + + + + ); + } + + const router = createMemoryRouter( + [ + { path: "/", element: }, + { path: "/target", element:

Target

}, + ], + { initialEntries: ["/"] }, + ); + render(); + await user.type(screen.getByRole("textbox", { name: "Guard field" }), "x"); + const leave = screen.getByRole("button", { name: "Leave" }); + await user.click(leave); + expect( + screen.getByRole("dialog", { name: "저장하지 않은 변경이 있습니다." }), + ).toHaveAttribute("open"); + + await user.click(screen.getByRole("button", { name: "계속 작성" })); + await waitFor(() => expect(leave).toHaveFocus()); + await user.click(leave); + await user.click(screen.getByRole("button", { name: "변경 버리고 이동" })); + expect(await screen.findByRole("heading", { name: "Target" })).toBeVisible(); + }); +}); diff --git a/tests/component/page-templates.test.tsx b/tests/component/page-templates.test.tsx new file mode 100644 index 00000000..0d036c1d --- /dev/null +++ b/tests/component/page-templates.test.tsx @@ -0,0 +1,92 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +import { + CollectionPage, + DetailPage, + FormPage, + StandardPage, + StatusPage, +} from "../../src/presentation/templates/index.js"; + +describe("page template slot contracts", () => { + it("renders StandardPage minimum and full landmarks with one h1", () => { + const { rerender } = render( + Content, + ); + expect(screen.getByRole("heading", { level: 1, name: "Minimum" })).toBeVisible(); + + rerender( + Home} + status={Ready} + actions={[ + { kind: "button", label: "Action", onAction: () => {} }, + ]} + notices={

Notice

} + feedback={

Refreshing

} + aside={

Aside

} + > + Content +
, + ); + expect(screen.getAllByRole("heading", { level: 1 })).toHaveLength(1); + expect(screen.getByRole("navigation", { name: "현재 위치" })).toBeVisible(); + expect(screen.getByRole("complementary", { name: "관련 정보" })).toBeVisible(); + }); + + it("places collection, detail and form state in stable slots", () => { + const { rerender } = render( + Filter} + resultCount="12 results" + pagination={Next} + > + Results + , + ); + expect(screen.getByRole("region", { name: "검색과 필터" })).toBeVisible(); + expect(screen.getByRole("navigation", { name: "페이지 탐색" })).toBeVisible(); + + rerender( +
ID
1
} + destructiveAction={} + > + Sections +
, + ); + expect(screen.getByRole("region", { name: "요약 정보" })).toBeVisible(); + expect(screen.getByRole("region", { name: "위험 작업" })).toBeVisible(); + + rerender( + Invalid

} + fields={} + formActions={} + />, + ); + expect(screen.getByRole("alert")).toBeVisible(); + expect(screen.getByRole("textbox", { name: "Field" })).toBeVisible(); + }); + + it("renders safe status variants without raw failure values", () => { + render( + {} }} + supportReference="SAFE-123" + />, + ); + expect(screen.getByRole("heading", { level: 1, name: "Offline" })).toBeVisible(); + expect(screen.getByText("SAFE-123")).toBeVisible(); + expect(document.body).not.toHaveTextContent("stack"); + }); +}); diff --git a/tests/e2e/accessibility.spec.js b/tests/e2e/accessibility.spec.js index 8fb53894..ba2f662f 100644 --- a/tests/e2e/accessibility.spec.js +++ b/tests/e2e/accessibility.spec.js @@ -2,9 +2,10 @@ import AxeBuilder from "@axe-core/playwright"; import { expect, test } from "@playwright/test"; import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.js"; -for (const route of Object.values(ROUTE_REGISTRY).map((definition) => - definition.path === "*" ? "/not-found" : definition.path, -)) { +for (const route of Object.values(ROUTE_REGISTRY).map((definition) => { + if (definition.path === "*") return "/not-found"; + return definition.path.replace(":resourceId", "reference-1"); +})) { test(`@a11y ${route} has no critical or serious axe violations`, async ({ page, }) => { diff --git a/tests/e2e/reference-form.spec.js b/tests/e2e/reference-form.spec.js new file mode 100644 index 00000000..7b748dd4 --- /dev/null +++ b/tests/e2e/reference-form.spec.js @@ -0,0 +1,50 @@ +import { expect, test } from "@playwright/test"; + +/** @param {import("@playwright/test").Page} page */ +async function openReferenceForm(page) { + await page.goto("/examples/reference-resources/new"); + await page.getByRole("button", { name: "로그인 시작" }).click(); + await expect( + page.getByRole("heading", { name: "Reference resource 만들기" }), + ).toBeVisible(); +} + +test("validates a reference form and focuses the first invalid field", async ({ + page, +}) => { + await openReferenceForm(page); + await page.getByRole("button", { name: "저장" }).click(); + + const firstField = page.getByRole("textbox", { name: /새 항목 이름/ }); + await expect(firstField).toBeFocused(); + await expect(firstField).toHaveAttribute("aria-invalid", "true"); + await expect(page.getByRole("alert")).toContainText("입력 내용을 확인해 주세요."); +}); + +test("guards dirty cancellation and restores focus when writing continues", async ({ + page, +}) => { + await openReferenceForm(page); + await page + .getByRole("textbox", { name: /새 항목 이름/ }) + .fill("Unsaved reference"); + const cancel = page.getByRole("button", { name: "취소" }); + await cancel.click(); + + await expect( + page.getByRole("dialog", { name: "저장하지 않은 변경이 있습니다." }), + ).toBeVisible(); + await page.getByRole("button", { name: "계속 작성" }).click(); + await expect(cancel).toBeFocused(); + await expect(page).toHaveURL(/\/examples\/reference-resources\/new$/); +}); + +test("keeps the form template within a 320px viewport", async ({ page }) => { + await page.setViewportSize({ width: 320, height: 720 }); + await openReferenceForm(page); + const viewport = await page.evaluate(() => ({ + clientWidth: document.documentElement.clientWidth, + scrollWidth: document.documentElement.scrollWidth, + })); + expect(viewport.scrollWidth).toBeLessThanOrEqual(viewport.clientWidth); +}); diff --git a/tests/features/reference-feature/reference-contract.test.ts b/tests/features/reference-feature/reference-contract.test.ts index c1d95769..279112fd 100644 --- a/tests/features/reference-feature/reference-contract.test.ts +++ b/tests/features/reference-feature/reference-contract.test.ts @@ -82,10 +82,14 @@ describe("reference feature boundary contracts", () => { it("owns route, operation and query contributions in one removable contract", () => { expect(Object.keys(REFERENCE_FEATURE_CONTRACT.routes)).toEqual([ "REFERENCE_RESOURCE_LIST", + "REFERENCE_RESOURCE_DETAIL", + "REFERENCE_RESOURCE_FORM", + "REFERENCE_RESOURCE_STATUS", ]); expect(Object.keys(REFERENCE_FEATURE_CONTRACT.apiOperations)).toEqual([ "LIST_REFERENCE_RESOURCES", "CREATE_REFERENCE_RESOURCE", + "GET_REFERENCE_RESOURCE", ]); expect(Object.keys(REFERENCE_FEATURE_CONTRACT.queryRegistry)).toEqual([ "REFERENCE_RESOURCE", diff --git a/tests/features/reference-feature/reference-page.test.tsx b/tests/features/reference-feature/reference-page.test.tsx index 20293cdf..79643069 100644 --- a/tests/features/reference-feature/reference-page.test.tsx +++ b/tests/features/reference-feature/reference-page.test.tsx @@ -58,6 +58,14 @@ function inputWith( createdAtLabel: null, }, }), + getResource: async (resourceId) => ({ + ok: true, + value: { + resourceId, + title: "Detail", + createdAtLabel: null, + }, + }), ...overrides, }; } @@ -129,7 +137,7 @@ describe("reference feature page states", () => { ); }); - it("deduplicates optimistic create and rolls back a conflict", async () => { + it("deduplicates create, preserves input and surfaces a conflict", async () => { const user = userEvent.setup(); let finish: | ((result: ReferenceResult) => void) @@ -141,31 +149,22 @@ describe("reference feature page states", () => { }), ); renderReference( - inputWith({ - listResources: async () => ({ - ok: true, - value: [ - { - resourceId: "existing", - title: "Existing", - createdAtLabel: null, - }, - ], - }), - createResource, - }), + inputWith({ createResource }), + "/examples/reference-resources/new", ); - await screen.findByText("Existing"); - await user.type(screen.getByLabelText("새 항목 이름"), "Conflicting"); - const submit = screen.getByRole("button", { name: "추가" }); + await screen.findByRole("heading", { + name: "Reference resource 만들기", + }); + await user.type( + screen.getByRole("textbox", { name: /새 항목 이름/ }), + "Conflicting", + ); + await user.type(screen.getByLabelText("설명"), "Keep this input"); + const submit = screen.getByRole("button", { name: "저장" }); await user.dblClick(submit); await waitFor(() => expect(createResource).toHaveBeenCalledOnce()); - expect(await screen.findByText("Conflicting")).toHaveAttribute( - "data-optimistic", - "true", - ); - expect(screen.getByText("mutation-pending")).toBeVisible(); + expect(screen.getByRole("button", { name: "저장 중…" })).toBeDisabled(); finish?.({ ok: false, @@ -175,14 +174,11 @@ describe("reference feature page states", () => { 0, ), }); + expect(await screen.findByText(/다른 변경과 충돌했습니다/)).toBeVisible(); expect( - await screen.findByRole("button", { name: "충돌 해결" }), - ).toBeVisible(); - expect(screen.queryByText("Conflicting")).not.toBeInTheDocument(); - await user.click(screen.getByRole("button", { name: "충돌 해결" })); - await waitFor(() => - expect(screen.queryByText("mutation-conflict")).not.toBeInTheDocument(), - ); + screen.getByRole("textbox", { name: /새 항목 이름/ }), + ).toHaveValue("Conflicting"); + expect(screen.getByLabelText("설명")).toHaveValue("Keep this input"); }); it("keeps stale data visible during refresh failure and recovers on retry", async () => { @@ -219,8 +215,7 @@ describe("reference feature page states", () => { }); renderReference(inputWith({ listResources })); await screen.findByText("Existing"); - await user.type(screen.getByLabelText("새 항목 이름"), "Created"); - await user.click(screen.getByRole("button", { name: "추가" })); + await user.click(screen.getByRole("button", { name: "새로고침" })); expect(await screen.findByText("stale-degraded")).toBeVisible(); expect(screen.getByText("Existing")).toBeVisible(); diff --git a/tests/features/reference-feature/reference-production-vertical.test.tsx b/tests/features/reference-feature/reference-production-vertical.test.tsx index 4d0608f6..afab4d31 100644 --- a/tests/features/reference-feature/reference-production-vertical.test.tsx +++ b/tests/features/reference-feature/reference-production-vertical.test.tsx @@ -46,6 +46,9 @@ const releaseManifest = { "route-examples-states": "assets/states.js", "route-examples-auth": "assets/auth.js", "route-reference-resources": "assets/reference.js", + "route-reference-resource-detail": "assets/reference-detail.js", + "route-reference-resource-form": "assets/reference-form.js", + "route-reference-resource-status": "assets/reference-status.js", "route-not-found": "assets/not-found.js", }, }; @@ -120,8 +123,14 @@ describe("reference feature production vertical path", () => { "?limit=5&tags=open&tags=new", ); - await user.type(screen.getByLabelText("새 항목 이름"), " Created "); - await user.click(screen.getByRole("button", { name: "추가" })); + await user.click(screen.getByRole("button", { name: "새 항목 만들기" })); + await user.type( + await screen.findByRole("textbox", { name: /새 항목 이름/ }), + " Created ", + ); + await user.click(screen.getByRole("button", { name: "저장" })); + expect(await screen.findByText("저장했습니다.")).toBeVisible(); + await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" })); expect(await screen.findByText("Created")).toBeVisible(); expect(createRequests).toHaveBeenCalledWith({ name: "Created" }); expect(listRequests.mock.calls.length).toBeGreaterThanOrEqual(2); diff --git a/tests/fixtures/architecture/forbidden/template-imports-application.tsx b/tests/fixtures/architecture/forbidden/template-imports-application.tsx new file mode 100644 index 00000000..31d77020 --- /dev/null +++ b/tests/fixtures/architecture/forbidden/template-imports-application.tsx @@ -0,0 +1,5 @@ +import type { ApplicationApi } from "../../../../src/application/ports/in/application-api.js"; + +export function ForbiddenTemplate(_props: { application: ApplicationApi }) { + return
Template must not select an application use case.
; +} diff --git a/tests/fixtures/typecheck/invalid-page-action.tsx b/tests/fixtures/typecheck/invalid-page-action.tsx new file mode 100644 index 00000000..a8b192e2 --- /dev/null +++ b/tests/fixtures/typecheck/invalid-page-action.tsx @@ -0,0 +1,6 @@ +import type { PageActionDefinition } from "../../../src/presentation/templates/index.js"; + +export const activeButtonWithoutCallback = { + kind: "button", + label: "Unsafe active action", +} satisfies PageActionDefinition; diff --git a/tests/integration/http-client.test.js b/tests/integration/http-client.test.js index c0208eed..31a22986 100644 --- a/tests/integration/http-client.test.js +++ b/tests/integration/http-client.test.js @@ -106,6 +106,45 @@ describe("shared HTTP client", () => { }); }); + it("projects only approved 422 issue path and code metadata", async () => { + server.use( + http.post("https://api.test/api/entities", () => + HttpResponse.json( + { + success: false, + error: { + code: "INVALID_INPUT", + message: "raw backend secret", + details: { + issues: [ + { path: "name", code: "REQUIRED", message: "raw field copy" }, + { path: 42, code: "INVALID" }, + ], + }, + }, + meta: { requestId: "request-422", traceId: "trace-422" }, + }, + { status: 422 }, + ), + ), + ); + const client = testClient({ baseUrl: "https://api.test", clock }); + const result = await client.execute("CREATE_ENTITY", { + routeId: "TEST_FORM", + body: { name: "Valid" }, + }); + + expect(result).toMatchObject({ + ok: false, + error: { + kind: "VALIDATION_REJECTED", + validationIssues: [{ path: "name", code: "REQUIRED" }], + }, + }); + expect(JSON.stringify(result)).not.toContain("raw backend secret"); + expect(JSON.stringify(result)).not.toContain("raw field copy"); + }); + it("guards mapper exceptions as UNKNOWN_FAILURE", async () => { server.use( http.get("https://api.test/api/entities", () => diff --git a/vitest.config.js b/vitest.config.js index 4293e824..893094f2 100644 --- a/vitest.config.js +++ b/vitest.config.js @@ -1,4 +1,4 @@ -import { defineConfig } from "vitest/config"; +import { configDefaults, defineConfig } from "vitest/config"; export default defineConfig({ test: { @@ -8,6 +8,7 @@ export default defineConfig({ clearMocks: true, mockReset: true, testTimeout: 10_000, + exclude: [...configDefaults.exclude, ".tmp/**"], coverage: { reporter: ["text", "json-summary"], }, From 13f28ef8119d249b8f1d9f22b1c4e7d864acd7a6 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Sun, 26 Jul 2026 15:49:07 +0900 Subject: [PATCH 053/178] feat: add design system platform --- .dependency-cruiser.cjs | 10 + artifacts/tests/a11y-manual/EXAMPLES_UI.md | 2 +- config/ci/gates.json | 7 +- .../decisions/VD-05-icon-and-headless-ui.md | 57 ++ .../frontend-platform-capability-review.md | 10 +- ...rontend-platform-implementation-roadmap.md | 16 + .../frontend-ports-adapters-and-boundaries.md | 7 + docs/styling/design-system-platform.md | 22 +- .../frontend-platform-testing-strategy.md | 7 + package.json | 4 + pnpm-lock.yaml | 12 + scripts/check-design-system.mjs | 148 +++++ .../reference-resource-detail-page.tsx | 6 +- .../reference-resource-form-page.tsx | 6 +- .../presentation/reference-resource-page.tsx | 8 +- .../reference-resource-status-page.tsx | 2 +- src/presentation/components/ui/alert.jsx | 37 +- src/presentation/components/ui/badge.jsx | 10 +- src/presentation/components/ui/button.jsx | 25 +- src/presentation/components/ui/card.jsx | 29 +- src/presentation/components/ui/dialog.jsx | 89 +-- src/presentation/components/ui/text-field.jsx | 53 +- .../design-system/icons/semantic-icons.tsx | 47 ++ .../design-system/icons/vendors/lucide.tsx | 21 + src/presentation/design-system/index.ts | 146 +++++ .../patterns/common-patterns.tsx | 139 +++++ .../design-system/primitives/core.tsx | 446 +++++++++++++++ .../design-system/primitives/feedback.tsx | 55 ++ .../design-system/primitives/forms.tsx | 409 ++++++++++++++ .../design-system/primitives/navigation.tsx | 193 +++++++ .../design-system/primitives/overlays.tsx | 441 +++++++++++++++ .../design-system/tokens/component.css | 26 + .../design-system/tokens/primitive.css | 63 +++ .../design-system/tokens/semantic.css | 83 +++ .../design-system/tokens/token-contract.ts | 62 +++ .../examples/auth-example-page.jsx | 2 +- .../examples/state-gallery-page.jsx | 10 +- src/presentation/examples/ui-gallery-page.jsx | 150 ++++- src/presentation/layouts/app-shell.jsx | 118 ++-- src/presentation/pages/home-page.jsx | 2 +- src/presentation/pages/not-found-page.jsx | 2 +- src/presentation/routes/app-router.tsx | 2 +- src/presentation/styles/theme.css | 523 +++++++++++++++--- .../component/design-system-platform.test.tsx | 269 +++++++++ tests/e2e/accessibility.spec.js | 16 + tests/e2e/app-shell.spec.js | 5 + tests/e2e/design-system-interactions.spec.js | 29 + .../design-system/forbidden/deep-import.tsx | 3 + .../design-system/forbidden/direct-icon.tsx | 3 + .../design-system/forbidden/raw-palette.tsx | 3 + .../design-system/forbidden/tooltip-only.tsx | 1 + .../typecheck/invalid-icon-button.tsx | 3 + tests/unit/design-system-contract.test.ts | 48 ++ 53 files changed, 3477 insertions(+), 410 deletions(-) create mode 100644 docs/architecture/decisions/VD-05-icon-and-headless-ui.md create mode 100644 scripts/check-design-system.mjs create mode 100644 src/presentation/design-system/icons/semantic-icons.tsx create mode 100644 src/presentation/design-system/icons/vendors/lucide.tsx create mode 100644 src/presentation/design-system/index.ts create mode 100644 src/presentation/design-system/patterns/common-patterns.tsx create mode 100644 src/presentation/design-system/primitives/core.tsx create mode 100644 src/presentation/design-system/primitives/feedback.tsx create mode 100644 src/presentation/design-system/primitives/forms.tsx create mode 100644 src/presentation/design-system/primitives/navigation.tsx create mode 100644 src/presentation/design-system/primitives/overlays.tsx create mode 100644 src/presentation/design-system/tokens/component.css create mode 100644 src/presentation/design-system/tokens/primitive.css create mode 100644 src/presentation/design-system/tokens/semantic.css create mode 100644 src/presentation/design-system/tokens/token-contract.ts create mode 100644 tests/component/design-system-platform.test.tsx create mode 100644 tests/e2e/design-system-interactions.spec.js create mode 100644 tests/fixtures/design-system/forbidden/deep-import.tsx create mode 100644 tests/fixtures/design-system/forbidden/direct-icon.tsx create mode 100644 tests/fixtures/design-system/forbidden/raw-palette.tsx create mode 100644 tests/fixtures/design-system/forbidden/tooltip-only.tsx create mode 100644 tests/fixtures/typecheck/invalid-icon-button.tsx create mode 100644 tests/unit/design-system-contract.test.ts diff --git a/.dependency-cruiser.cjs b/.dependency-cruiser.cjs index 6cd78b50..d320e6d0 100644 --- a/.dependency-cruiser.cjs +++ b/.dependency-cruiser.cjs @@ -31,6 +31,16 @@ module.exports = { path: "^(src/(application|adapters|bootstrap)|src/presentation/adapters|@tanstack)", }, }, + { + name: "icon-vendor-is-facade-only", + severity: "error", + from: { + path: "^src", + pathNot: + "^src/presentation/design-system/icons/vendors/lucide\\.tsx$", + }, + to: { path: "^lucide-react$" }, + }, { name: "adapters-do-not-know-presentation", severity: "error", diff --git a/artifacts/tests/a11y-manual/EXAMPLES_UI.md b/artifacts/tests/a11y-manual/EXAMPLES_UI.md index b82c1cfe..6f89235c 100644 --- a/artifacts/tests/a11y-manual/EXAMPLES_UI.md +++ b/artifacts/tests/a11y-manual/EXAMPLES_UI.md @@ -15,4 +15,4 @@ M5 Error association: pending M6 Color signal: pending M7 Reduced motion: pending Screen reader: pending -Notes: Review the text-field error association and modal focus containment/restoration. +Notes: Review form primitives, Menu/Tabs keyboard behavior, Toast announcements, Tooltip supplemental copy, text-field error association and modal focus containment/restoration. diff --git a/config/ci/gates.json b/config/ci/gates.json index 9a13e719..cf78832c 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -81,7 +81,8 @@ { "script": "check:types:fixture:application-input", "expect": "fail" }, { "script": "check:types:fixture:async-overlay", "expect": "fail" }, { "script": "check:types:fixture:route-runtime", "expect": "fail" }, - { "script": "check:types:fixture:page-action", "expect": "fail" } + { "script": "check:types:fixture:page-action", "expect": "fail" }, + { "script": "check:types:fixture:icon-button", "expect": "fail" } ], "logPath": "artifacts/quality/check-types.txt", "evidence": ["artifacts/quality/check-types.txt"], @@ -151,6 +152,8 @@ "name": "architecture", "steps": [ { "script": "check:architecture", "expect": "pass" }, + { "script": "check:design-system", "expect": "pass" }, + { "script": "check:design-system:fixture", "expect": "fail" }, { "script": "check:registries", "expect": "pass" }, { "script": "check:registries:fixture", "expect": "fail" }, { "script": "check:routes:fixture", "expect": "fail" } @@ -158,6 +161,8 @@ "logPath": "artifacts/quality/gates/FE-GATE-010.txt", "evidence": [ "artifacts/quality/dependency-report.json", + "artifacts/quality/design-system.json", + "artifacts/quality/design-system-fixture.json", "artifacts/quality/registries.json", "artifacts/quality/registry-fixture.json", "artifacts/quality/route-registry-fixture.json" diff --git a/docs/architecture/decisions/VD-05-icon-and-headless-ui.md b/docs/architecture/decisions/VD-05-icon-and-headless-ui.md new file mode 100644 index 00000000..9bda349f --- /dev/null +++ b/docs/architecture/decisions/VD-05-icon-and-headless-ui.md @@ -0,0 +1,57 @@ +# VD-05: Semantic icon facade와 native-first interaction + +- 상태: Accepted +- 결정일: 2026-07-26 +- 적용 브랜치: `feature-frontend-design-system-platform` +- 재검토: native 계약으로 충족할 수 없는 widget 요구가 확인될 때 + +## 배경 + +앱 셸과 공통 UI는 문자 glyph, raw button/select와 페이지별 focus 처리를 +사용했다. 아이콘 공급자와 복합 interaction을 제품 코드에 직접 노출하면 번들, +접근성, vendor type과 교체 비용이 모든 feature로 전파된다. 반대로 실제 요구가 +없는 두 개의 headless vendor를 기본 설치하면 skeleton 소비자가 제거해야 할 +의존성과 중복 interaction 모델이 생긴다. + +## 결정 + +1. 아이콘 공급자는 lockfile 최소 게시 유예를 통과한 `lucide-react@1.25.0`으로 + 고정한다. +2. `lucide-react`의 static named import는 + `design-system/icons/vendors/lucide.tsx` 한 파일에서만 허용한다. +3. public API는 `MenuIcon`, `CloseIcon`, `WarningIcon` 같은 의미 이름만 + 노출한다. vendor component type, icon name, stroke API와 dynamic icon + registry는 노출하지 않는다. +4. 장식 아이콘은 accessibility tree에서 제외한다. 정보를 단독 전달하는 + 아이콘은 `label`, icon-only action은 필수 `accessibleName`을 사용한다. +5. 현재 복합 control은 native `dialog`, form control, `details`와 local + TypeScript state model로 구현한다. Menu는 roving focus/typeahead/Escape, + Tabs는 manual/automatic activation, Drawer는 modal/background + 비활성화/focus restore 계약을 가진다. +6. React Aria와 Radix는 기본 dependency로 추가하지 않는다. native platform이 + collision, nested overlay, virtualized collection 또는 복합 select 요구를 + 충족하지 못한다는 재현 가능한 요구가 생길 때 prototype과 ADR로 다시 + 평가한다. +7. Storybook과 pinned visual baseline은 VD-08/RP-10에서 도입한다. RP-07의 + runtime gallery와 browser interaction test는 해당 workshop을 대체한다고 + 주장하지 않는다. + +## 경계와 검증 + +- 제품 코드는 `presentation/design-system/index`만 import한다. +- design-system 검사기는 direct icon/headless import, deep import, raw palette, + undefined token과 tooltip-only required information fixture를 거절한다. +- type negative fixture는 accessible name 없는 `IconButton`을 거절한다. +- component test는 decorative icon, form control, Menu, Tabs, Drawer와 Toast를 + 검증한다. +- Chromium/Firefox E2E는 compact Drawer의 native modal 상태, Escape, focus + restore, gallery keyboard interaction과 axe를 검증한다. +- 로컬 WebKit 실행은 host `libevent-2.1.so.7` 부재로 환경 검증이 남아 있으며 + 공급자 선택이나 product behavior의 PASS로 숨기지 않는다. + +## Rollback + +기존 `presentation/components/ui/*` 경로는 canonical TypeScript primitive를 +재수출하므로 소비 코드를 즉시 되돌릴 수 있다. Lucide 제거 시 vendor facade와 +semantic icon 구현만 교체하고 제품 API는 유지한다. headless vendor를 나중에 +도입해도 public props와 interaction test를 유지한다. diff --git a/docs/architecture/frontend-platform-capability-review.md b/docs/architecture/frontend-platform-capability-review.md index e6e3ac1d..4b860562 100644 --- a/docs/architecture/frontend-platform-capability-review.md +++ b/docs/architecture/frontend-platform-capability-review.md @@ -73,11 +73,11 @@ recovery 계약, 제거 가능한 reference 수직 슬라이스는 구현됐다. | 클라이언트 상태 | 부분 준비 | local state, theme context, session external store | 상태 소유권 표와 typed external-store 예제 | | 범용 global store | 프로젝트 선택 | 별도 라이브러리 없음 | 필요 조건에 따라 Zustand/Redux Toolkit/state machine 선택 | | 라우팅 | 준비됨 | Data Router, typed runtime map, codec, metadata consumer, bounded chunk recovery | reference feature route와 release E2E로 사용 범위 확장 | -| 앱 셸·반응형 | 부분 준비 | header/sidebar/content/theme 구현 | 접근 가능한 mobile drawer와 focus 복원 | -| 페이지 템플릿 | 준비됨 | Standard/Collection/Detail/Form/Status slot 계약과 reference 소비 화면 | RP-07 public design-system entry로 이동 | -| 디자인 토큰 | 부분 준비 | semantic color/theme 토큰 존재 | typography, spacing, motion, layer 등 3단계 토큰 | -| 공통 UI | 부분 준비 | Button, TextField, Card, Alert, Badge, Dialog | form/navigation/overlay/data/layout primitives 확장 | -| 아이콘 | 미제공 | 문자 기호를 직접 사용 | Lucide를 로컬 icon facade 뒤에서 사용 | +| 앱 셸·반응형 | 준비됨 | native modal Drawer, compact/desktop layout, Escape/link dismiss와 focus restore | RP-08에서 RTL/direction 검증 | +| 페이지 템플릿 | 준비됨 | Standard/Collection/Detail/Form/Status와 public design-system entry | feature별 slot 조합 유지 | +| 디자인 토큰 | 준비됨 | primitive/semantic/component CSS, 48-token 자동 계약, dark/forced-colors/reduced-motion | 제품 brand token은 외부 프로젝트에서 확장 | +| 공통 UI | 준비됨 | action/form/feedback/overlay/navigation primitive와 pattern, compatibility export | Storybook/visual은 RP-10 | +| 아이콘 | 준비됨 | Lucide static vendor facade와 semantic icon/IconButton 접근성 계약 | 의미 icon 추가 시 bundle/접근성 기준 적용 | | 폼 | 준비됨 | Zod 기반 local facade, error summary/focus, 422 allowlist, dirty/pending/conflict 정책 | 복합 form 요구가 생기면 VD-04 조건으로 vendor adapter 평가 | | 국제화 | 미제공 | 한국어 문자열·locale이 하드코딩 | typed message/formatter/locale/RTL 경계 | | logging/diagnostics | 미제공 | telemetry port는 있으나 logger 없음 | redaction이 적용된 diagnostics/logging 경계 | diff --git a/docs/architecture/frontend-platform-implementation-roadmap.md b/docs/architecture/frontend-platform-implementation-roadmap.md index 27d5abdb..fdc7754d 100644 --- a/docs/architecture/frontend-platform-implementation-roadmap.md +++ b/docs/architecture/frontend-platform-implementation-roadmap.md @@ -588,6 +588,22 @@ RP-07은 compatibility export로 기존 primitive import를 복구할 수 있어 token rename은 alias/migration 기간을 두고, vendor adapter와 local API commit을 분리한다. +**구현 증거 (2026-07-26)** + +- VD-05에서 `lucide-react@1.25.0` static semantic facade와 native-first + interaction을 채택하고 headless vendor 재평가 조건을 닫았다. +- `src/presentation/design-system`이 48개 필수 token, public TypeScript barrel, + action/form/feedback/overlay/navigation primitive와 공통 pattern을 제공한다. +- 기존 `components/ui` 경로는 compatibility export로 유지하고 앱 셸, gallery와 + reference feature는 public entry를 소비한다. +- 모바일 navigation은 native modal Drawer로 전환되어 배경 비활성화, Escape, + route dismiss와 trigger focus restore를 제공한다. +- source/negative fixture gate가 undefined token, raw palette, direct vendor, + deep import, tooltip-only 정보와 accessible name 누락을 거절한다. +- component/browser test가 Menu typeahead, Tabs activation, Toast queue, + form controls, compact reflow와 open-dialog axe를 실행한다. 로컬 WebKit은 host + `libevent-2.1.so.7` 부재로 환경 검증 상태를 유지한다. + ### 08. `feature-frontend-i18n-message-formatting-contract` **목표** diff --git a/docs/architecture/frontend-ports-adapters-and-boundaries.md b/docs/architecture/frontend-ports-adapters-and-boundaries.md index c4b857a9..db329163 100644 --- a/docs/architecture/frontend-ports-adapters-and-boundaries.md +++ b/docs/architecture/frontend-ports-adapters-and-boundaries.md @@ -171,6 +171,13 @@ query vendor import는 architecture gate가 거절한다. reference feature의 list/detail/create/status route가 각각 Collection/Detail/Form/Status template의 실제 consumer다. +RP-07에서 React inbound adapter 안의 UI 공급자 경계도 닫혔다. +`src/presentation/design-system/index.ts`는 token → primitive → pattern → +template public API이며 feature와 shell은 이 entry만 소비한다. Lucide는 +`icons/vendors/lucide.tsx`에 격리된 inbound vendor facade이므로 application +port가 아니다. native Dialog/Drawer/Menu/Tabs의 focus·keyboard 상태도 +presentation이 소유하고 use case나 outbound adapter로 올리지 않는다. + 이 문서의 목표 구조는 기존 기반을 폐기하는 것이 아니라 이러한 불일치를 제거하는 것이다. diff --git a/docs/styling/design-system-platform.md b/docs/styling/design-system-platform.md index 6a03aab4..642bf3d8 100644 --- a/docs/styling/design-system-platform.md +++ b/docs/styling/design-system-platform.md @@ -47,23 +47,23 @@ - Chromium, Firefox, WebKit - 등록 라우트의 자동 접근성 검사 -이 기반은 유효하지만 아직 디자인 시스템 플랫폼 전체는 아니다. +RP-07 구현 이후 이 기반은 저장소 내부 디자인 시스템 플랫폼 계약을 충족한다. +아래 목록은 구현 전 공백과 현재 해결 상태를 함께 보존한다. -1. 토큰이 색상 중심이며 typography, elevation, motion, z-layer, control size, - breakpoint가 계약으로 닫혀 있지 않다. +1. typography, elevation, motion, z-layer, control size와 breakpoint는 + `design-system/tokens`의 3계층과 자동 gate로 닫혔다. 2. RP-06 form/page foundation은 준비됐지만 TextArea, Select, Checkbox, RadioGroup 같은 form primitive 확장은 RP-07에 남아 있다. -3. 앱 셸과 예제 화면에서 공용 primitive 대신 raw `button`, `select`, 링크 - class를 다시 작성하는 곳이 있다. -4. `☰`, `×` 같은 문자 glyph를 직접 사용하며 아이콘 공급자 경계가 없다. -5. `theme.css` 하나가 token, layout, primitive, pattern 스타일을 모두 소유한다. +3. 앱 셸, 예제와 reference feature는 public design-system barrel을 소비한다. +4. 문자 glyph는 semantic Lucide facade로 교체됐다. +5. token은 세 CSS 파일로 분리됐고 `theme.css`는 layout/component styling만 + 소유한다. 6. runtime gallery는 있지만 격리된 story, interaction story, 시각 회귀 기준선이 없다. 7. 사용자 문구가 한국어 literal로 고정되어 locale과 RTL 계약이 없다. -8. page template은 준비됐지만 RP-07 design-system public entry와 token/pattern - 계층으로 정리해야 한다. -9. 모바일 sidebar는 표시 전환은 되지만 modal drawer 수준의 focus 이동, focus - 복원, 배경 비활성화 계약은 없다. +8. page template, form과 pattern은 public barrel에서 제공된다. +9. 모바일 navigation은 native modal Drawer로 focus 이동, 배경 비활성화, + Escape/link dismiss와 trigger focus restore를 제공한다. 따라서 기존 구성요소는 폐기하지 않고 아래 목표 계층으로 이동·확장한다. diff --git a/docs/testing/frontend-platform-testing-strategy.md b/docs/testing/frontend-platform-testing-strategy.md index cc0cfad1..50721e42 100644 --- a/docs/testing/frontend-platform-testing-strategy.md +++ b/docs/testing/frontend-platform-testing-strategy.md @@ -562,6 +562,13 @@ client route guard는 UX이며 authorization이 아님을 test 이름과 문서 공용 컴포넌트는 한 번의 결함이 모든 페이지로 전파되므로 위험도가 높다. +RP-07의 실행 경로는 `check:design-system`, +`check:design-system:fixture`, `check:types:fixture:icon-button`, +`tests/component/design-system-platform.test.tsx`와 +`tests/e2e/design-system-interactions.spec.js`다. Story interaction/visual +baseline은 VD-08/RP-10에서 추가하며 현재 runtime gallery를 isolated workshop +완료 증거로 사용하지 않는다. + ### 10.1 Component behavior - native role/name/value diff --git a/package.json b/package.json index 64f9bf5d..f12f6772 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,8 @@ "preview": "vite preview", "lint": "eslint src scripts tests vite.config.js vitest.config.js playwright.config.js --max-warnings=0", "check:architecture": "node scripts/check-architecture.mjs", + "check:design-system": "node scripts/check-design-system.mjs", + "check:design-system:fixture": "node scripts/check-design-system.mjs --fixture", "check:types": "corepack pnpm check:types:app && corepack pnpm check:types:node && corepack pnpm check:types:test", "check:types:app": "tsc --project tsconfig.app.json", "check:types:node": "tsc --project tsconfig.node.json", @@ -27,6 +29,7 @@ "check:types:fixture:async-overlay": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-async-overlay.ts", "check:types:fixture:route-runtime": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-route-runtime.ts", "check:types:fixture:page-action": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --jsx react-jsx tests/fixtures/typecheck/invalid-page-action.tsx", + "check:types:fixture:icon-button": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --jsx react-jsx tests/fixtures/typecheck/invalid-icon-button.tsx", "test:runtime-schema": "vitest run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests", "test:unit": "vitest run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml", "test:component": "vitest run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml", @@ -58,6 +61,7 @@ }, "dependencies": { "@tanstack/react-query": "5.101.4", + "lucide-react": "1.25.0", "react": "19.2.8", "react-dom": "19.2.8", "react-router-dom": "7.18.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d70fc0ed..c23938dd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -11,6 +11,9 @@ importers: '@tanstack/react-query': specifier: 5.101.4 version: 5.101.4(react@19.2.8) + lucide-react: + specifier: 1.25.0 + version: 1.25.0(react@19.2.8) react: specifier: 19.2.8 version: 19.2.8 @@ -1536,6 +1539,11 @@ packages: lru-cache@5.1.1: resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} + lucide-react@1.25.0: + resolution: {integrity: sha512-/mdJTRbiwcLOQ1NZZK1amZF9rIZyvO18D6r9TngE6TG1NmqHgFuT4eE7Xrkm9UsXMbBJD1NlfwHVltCDWHrOTw==} + peerDependencies: + react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0 + lz-string@1.5.0: resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} hasBin: true @@ -3314,6 +3322,10 @@ snapshots: dependencies: yallist: 3.1.1 + lucide-react@1.25.0(react@19.2.8): + dependencies: + react: 19.2.8 + lz-string@1.5.0: {} magic-string@0.30.21: diff --git a/scripts/check-design-system.mjs b/scripts/check-design-system.mjs new file mode 100644 index 00000000..2e871418 --- /dev/null +++ b/scripts/check-design-system.mjs @@ -0,0 +1,148 @@ +import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import path from "node:path"; + +// @ts-expect-error Node 24 executes erasable TypeScript for this build-time gate. +import { REQUIRED_COMPONENT_TOKENS, REQUIRED_PRIMITIVE_TOKENS, REQUIRED_SEMANTIC_TOKENS } from "../src/presentation/design-system/tokens/token-contract.ts"; + +const fixtureMode = process.argv.includes("--fixture"); +const failures = []; +const tokenFiles = { + primitive: "src/presentation/design-system/tokens/primitive.css", + semantic: "src/presentation/design-system/tokens/semantic.css", + component: "src/presentation/design-system/tokens/component.css", +}; +/** @type {Array} */ +const tokenLayers = [ + ["primitive", tokenFiles.primitive, REQUIRED_PRIMITIVE_TOKENS], + ["semantic", tokenFiles.semantic, REQUIRED_SEMANTIC_TOKENS], + ["component", tokenFiles.component, REQUIRED_COMPONENT_TOKENS], +]; + +for (const [layer, file, tokens] of tokenLayers) { + const source = await readFile(file, "utf8"); + for (const token of tokens) { + if (!source.includes(`${token}:`)) { + failures.push(`${layer} token is missing: ${token}`); + } + } +} + +const cssSources = await Promise.all( + [...Object.values(tokenFiles), "src/presentation/styles/theme.css"].map( + async (file) => ({ file, source: await readFile(file, "utf8") }), + ), +); +const definitions = new Set( + cssSources.flatMap(({ source }) => + [...source.matchAll(/(--[a-z0-9-]+)\s*:/g)].map((match) => match[1]), + ), +); +for (const { file, source } of cssSources) { + for (const match of source.matchAll(/var\((--[a-z0-9-]+)/g)) { + if (!definitions.has(match[1])) { + failures.push(`${file} uses undefined token ${match[1]}`); + } + } +} + +const semanticSource = await readFile(tokenFiles.semantic, "utf8"); +const darkSource = + semanticSource.match(/:root\[data-theme="dark"\]\s*\{([\s\S]*?)\n\}/)?.[1] ?? + ""; +for (const token of [ + "--color-surface", + "--color-surface-muted", + "--color-surface-elevated", + "--color-content", + "--color-content-muted", + "--color-content-inverse", + "--color-border", + "--color-border-strong", + "--color-action", + "--color-action-hover", + "--color-action-pressed", + "--color-danger", + "--color-focus", + "--color-disabled-content", + "--color-disabled-surface", +]) { + if (!darkSource.includes(`${token}:`)) { + failures.push(`dark theme token is missing: ${token}`); + } +} +const componentSource = await readFile(tokenFiles.component, "utf8"); +if (!componentSource.includes("@media (forced-colors: active)")) { + failures.push("forced-colors token fallback is missing"); +} + +/** @param {string} directory @returns {Promise} */ +async function listSourceFiles(directory) { + const result = []; + for (const entry of await readdir(directory, { withFileTypes: true })) { + const target = path.join(directory, entry.name); + if (entry.isDirectory()) result.push(...(await listSourceFiles(target))); + else if (/\.(js|jsx|mjs|ts|tsx|mts)$/.test(entry.name)) result.push(target); + } + return result; +} + +const sources = fixtureMode + ? await listSourceFiles("tests/fixtures/design-system/forbidden") + : await listSourceFiles("src"); +for (const file of sources) { + const source = await readFile(file, "utf8"); + const vendorFacade = + file === "src/presentation/design-system/icons/vendors/lucide.tsx"; + if (!vendorFacade && /from\s+["']lucide-react["']/.test(source)) { + failures.push(`direct icon vendor import in ${file}`); + } + if ( + /from\s+["'](?:react-aria-components|@radix-ui\/[^"']+)["']/.test(source) + ) { + failures.push(`direct headless vendor import in ${file}`); + } + if ( + !file.includes("src/presentation/design-system/") && + /presentation\/design-system\/(?!index(?:\.js)?["'])/.test(source) + ) { + failures.push(`design-system deep import in ${file}`); + } + if ( + !file.includes("src/presentation/design-system/tokens/") && + /(?:#[0-9a-f]{3,8}\b|oklch\(|rgba?\()/i.test(source) + ) { + failures.push(`raw palette value in ${file}`); + } + if ( + file.includes("tests/fixtures/design-system/forbidden") && + source.includes("TOOLTIP_ONLY_REQUIRED_INFORMATION") + ) { + failures.push(`tooltip-only required information in ${file}`); + } +} + +const report = { + schemaVersion: 1, + mode: fixtureMode ? "negative-fixture" : "source", + checkedTokenCount: + REQUIRED_PRIMITIVE_TOKENS.length + + REQUIRED_SEMANTIC_TOKENS.length + + REQUIRED_COMPONENT_TOKENS.length, + failures, + passed: failures.length === 0, +}; +await mkdir("artifacts/quality", { recursive: true }); +await writeFile( + fixtureMode + ? "artifacts/quality/design-system-fixture.json" + : "artifacts/quality/design-system.json", + `${JSON.stringify(report, null, 2)}\n`, +); + +if (failures.length > 0) { + process.stderr.write(`Design system contract failed:\n${failures.join("\n")}\n`); + process.exit(1); +} +process.stdout.write( + `Design system contract: ${report.checkedTokenCount} tokens and vendor boundaries PASS\n`, +); diff --git a/src/features/reference-feature/presentation/reference-resource-detail-page.tsx b/src/features/reference-feature/presentation/reference-resource-detail-page.tsx index cedaccaa..9b62f3b5 100644 --- a/src/features/reference-feature/presentation/reference-resource-detail-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-detail-page.tsx @@ -1,7 +1,9 @@ import { Link } from "react-router-dom"; -import { AsyncSurface } from "../../../presentation/components/async-surface.jsx"; -import { DetailPage } from "../../../presentation/templates/index.js"; +import { + AsyncSurface, + DetailPage, +} from "../../../presentation/design-system/index.js"; import { useRouteInput } from "../../../presentation/routes/app-router.js"; import { useReferenceDetail } from "./use-reference-feature.js"; diff --git a/src/features/reference-feature/presentation/reference-resource-form-page.tsx b/src/features/reference-feature/presentation/reference-resource-form-page.tsx index 8e907828..53334a83 100644 --- a/src/features/reference-feature/presentation/reference-resource-form-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-form-page.tsx @@ -1,17 +1,17 @@ import { useCallback } from "react"; import { useNavigate } from "react-router-dom"; -import { Button } from "../../../presentation/components/ui/button.jsx"; import { + Button, DirtyNavigationDialog, ErrorSummary, Form, FormActions, + FormPage, FormField, useAppForm, useDirtyNavigationGuard, -} from "../../../presentation/forms/index.js"; -import { FormPage } from "../../../presentation/templates/index.js"; +} from "../../../presentation/design-system/index.js"; import { REFERENCE_FORM_DEFAULTS, referenceResourceFormSchema, diff --git a/src/features/reference-feature/presentation/reference-resource-page.tsx b/src/features/reference-feature/presentation/reference-resource-page.tsx index f396df6f..65ed6715 100644 --- a/src/features/reference-feature/presentation/reference-resource-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-page.tsx @@ -1,8 +1,10 @@ import { Link, useNavigate } from "react-router-dom"; -import { AsyncSurface } from "../../../presentation/components/async-surface.jsx"; -import { Button } from "../../../presentation/components/ui/button.jsx"; -import { CollectionPage } from "../../../presentation/templates/index.js"; +import { + AsyncSurface, + Button, + CollectionPage, +} from "../../../presentation/design-system/index.js"; import { useReferenceFeature } from "./use-reference-feature.js"; export default function ReferenceResourcePage() { diff --git a/src/features/reference-feature/presentation/reference-resource-status-page.tsx b/src/features/reference-feature/presentation/reference-resource-status-page.tsx index 4f748d6e..1a6a61f8 100644 --- a/src/features/reference-feature/presentation/reference-resource-status-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-status-page.tsx @@ -1,6 +1,6 @@ import { useNavigate } from "react-router-dom"; -import { StatusPage } from "../../../presentation/templates/index.js"; +import { StatusPage } from "../../../presentation/design-system/index.js"; export default function ReferenceResourceStatusPage() { const navigate = useNavigate(); diff --git a/src/presentation/components/ui/alert.jsx b/src/presentation/components/ui/alert.jsx index 26beed8b..cdeda8b8 100644 --- a/src/presentation/components/ui/alert.jsx +++ b/src/presentation/components/ui/alert.jsx @@ -1,36 +1 @@ -/** - * @param {{ - * title: string, - * children?: React.ReactNode, - * variant?: "info" | "success" | "warning" | "danger", - * onDismiss?: () => void - * }} props - */ -export function Alert({ - title, - children, - variant = "info", - onDismiss, -}) { - return ( -
-
- {title} - {children ?
{children}
: null} -
- {onDismiss ? ( - - ) : null} -
- ); -} +export { Alert } from "../../design-system/primitives/core.js"; diff --git a/src/presentation/components/ui/badge.jsx b/src/presentation/components/ui/badge.jsx index a4ae2ff7..2ad826ab 100644 --- a/src/presentation/components/ui/badge.jsx +++ b/src/presentation/components/ui/badge.jsx @@ -1,9 +1 @@ -/** - * @param {{ - * children: React.ReactNode, - * variant?: "neutral" | "info" | "success" | "warning" | "danger" - * }} props - */ -export function Badge({ children, variant = "neutral" }) { - return {children}; -} +export { Badge } from "../../design-system/primitives/core.js"; diff --git a/src/presentation/components/ui/button.jsx b/src/presentation/components/ui/button.jsx index 7c7e3121..6072cba1 100644 --- a/src/presentation/components/ui/button.jsx +++ b/src/presentation/components/ui/button.jsx @@ -1,24 +1 @@ -/** - * @param {React.ButtonHTMLAttributes & { - * variant?: "primary" | "secondary" | "danger" | "ghost", - * size?: "default" | "compact" - * }} props - */ -export function Button({ - variant = "primary", - size = "default", - className = "", - type = "button", - ...props -}) { - const classes = [ - "ui-button", - `ui-button--${variant}`, - size === "compact" ? "ui-button--compact" : "", - className, - ] - .filter(Boolean) - .join(" "); - - return - - {children ?
{children}
: null} - {actions ?
{actions}
: null} -
- - ); -} +export { Dialog } from "../../design-system/primitives/core.js"; diff --git a/src/presentation/components/ui/text-field.jsx b/src/presentation/components/ui/text-field.jsx index 4ffb5b66..b29b3ed8 100644 --- a/src/presentation/components/ui/text-field.jsx +++ b/src/presentation/components/ui/text-field.jsx @@ -1,52 +1 @@ -import { useId } from "react"; - -/** - * @param {Omit, "id"> & { - * id?: string, - * label: string, - * description?: string, - * error?: string - * }} props - */ -export function TextField({ - id, - label, - description, - error, - className = "", - required, - ...inputProps -}) { - const generatedId = useId(); - const inputId = id ?? `field-${generatedId}`; - const descriptionId = description ? `${inputId}-description` : undefined; - const errorId = error ? `${inputId}-error` : undefined; - const describedBy = [descriptionId, errorId].filter(Boolean).join(" "); - - return ( -
- - {description ? ( -

- {description} -

- ) : null} - - {error ? ( -

- {error} -

- ) : null} -
- ); -} +export { TextField } from "../../design-system/primitives/core.js"; diff --git a/src/presentation/design-system/icons/semantic-icons.tsx b/src/presentation/design-system/icons/semantic-icons.tsx new file mode 100644 index 00000000..158bbbc2 --- /dev/null +++ b/src/presentation/design-system/icons/semantic-icons.tsx @@ -0,0 +1,47 @@ +import type { ComponentType, SVGProps } from "react"; + +import { + CloseGlyph, + ErrorGlyph, + InfoGlyph, + MenuGlyph, + NextGlyph, + PreviousGlyph, + SearchGlyph, + SuccessGlyph, + WarningGlyph, +} from "./vendors/lucide.js"; + +export type SemanticIconProps = Readonly<{ + label?: string; + size?: "small" | "medium" | "large"; +}>; + +function createSemanticIcon( + Glyph: ComponentType>, +) { + return function SemanticIcon({ + label, + size = "medium", + }: SemanticIconProps) { + return ( + + ); + }; +} + +export const MenuIcon = createSemanticIcon(MenuGlyph); +export const CloseIcon = createSemanticIcon(CloseGlyph); +export const WarningIcon = createSemanticIcon(WarningGlyph); +export const SuccessIcon = createSemanticIcon(SuccessGlyph); +export const ErrorIcon = createSemanticIcon(ErrorGlyph); +export const InfoIcon = createSemanticIcon(InfoGlyph); +export const SearchIcon = createSemanticIcon(SearchGlyph); +export const PreviousIcon = createSemanticIcon(PreviousGlyph); +export const NextIcon = createSemanticIcon(NextGlyph); diff --git a/src/presentation/design-system/icons/vendors/lucide.tsx b/src/presentation/design-system/icons/vendors/lucide.tsx new file mode 100644 index 00000000..b098b94c --- /dev/null +++ b/src/presentation/design-system/icons/vendors/lucide.tsx @@ -0,0 +1,21 @@ +import { + AlertTriangle, + Check, + ChevronLeft, + ChevronRight, + CircleX, + Info, + Menu, + Search, + X, +} from "lucide-react"; + +export const MenuGlyph = Menu; +export const CloseGlyph = X; +export const WarningGlyph = AlertTriangle; +export const SuccessGlyph = Check; +export const ErrorGlyph = CircleX; +export const InfoGlyph = Info; +export const SearchGlyph = Search; +export const PreviousGlyph = ChevronLeft; +export const NextGlyph = ChevronRight; diff --git a/src/presentation/design-system/index.ts b/src/presentation/design-system/index.ts new file mode 100644 index 00000000..4508f35b --- /dev/null +++ b/src/presentation/design-system/index.ts @@ -0,0 +1,146 @@ +export { + Alert, + Badge, + Button, + Card, + Dialog, + Field, + FocusRing, + IconButton, + LinkButton, + Portal, + Spinner, + TextField, + VisuallyHidden, +} from "./primitives/core.js"; +export type { + AlertProps, + BadgeProps, + ButtonProps, + ButtonSize, + ButtonVariant, + CardProps, + DialogProps, + IconButtonProps, + LinkButtonProps, + SpinnerProps, + TextFieldProps, +} from "./primitives/core.js"; +export { + Checkbox, + RadioGroup, + SearchField, + Select, + Switch, + TextArea, +} from "./primitives/forms.js"; +export type { + CheckboxProps, + RadioGroupProps, + RadioOption, + SearchFieldProps, + SelectOption, + SelectProps, + SwitchProps, + TextAreaProps, +} from "./primitives/forms.js"; +export { + ProgressBar, + Separator, + Skeleton, +} from "./primitives/feedback.js"; +export type { + ProgressBarProps, + SkeletonProps, +} from "./primitives/feedback.js"; +export { + ConfirmationDialog, + Drawer, + Menu, + Popover, + ToastProvider, + Tooltip, + useToast, +} from "./primitives/overlays.js"; +export type { + DrawerProps, + MenuItemDefinition, + MenuProps, + PopoverProps, + TooltipProps, +} from "./primitives/overlays.js"; +export { + Breadcrumbs, + Pagination, + Tabs, +} from "./primitives/navigation.js"; +export type { + BreadcrumbItem, + TabDefinition, +} from "./primitives/navigation.js"; +export { + CloseIcon, + ErrorIcon, + InfoIcon, + MenuIcon, + NextIcon, + PreviousIcon, + SearchIcon, + SuccessIcon, + WarningIcon, +} from "./icons/semantic-icons.js"; +export type { + SemanticIconProps, +} from "./icons/semantic-icons.js"; +export { + DESIGN_TOKEN_CONTRACT, + REQUIRED_COMPONENT_TOKENS, + REQUIRED_PRIMITIVE_TOKENS, + REQUIRED_SEMANTIC_TOKENS, +} from "./tokens/token-contract.js"; +export { + AccessSurface, + DataTable, + DisclosureGroup, + PaginationBar, + SearchFilterToolbar, +} from "./patterns/common-patterns.js"; +export type { + AccessSurfaceProps, + DataTableColumn, + DisclosureDefinition, +} from "./patterns/common-patterns.js"; + +export { + AsyncSurface, + EmptySurface, + LoadingSurface, + TerminalErrorSurface, +} from "../components/async-surface.jsx"; +export { PageHeader } from "../components/page-header.jsx"; +export { + AuthRequiredSurface, + ForbiddenSurface, + NotFoundSurface, +} from "../components/state-surfaces.jsx"; +export { + DetailPage, + CollectionPage, + FormPage, + StandardPage, + StatusPage, +} from "../templates/index.js"; +export { + DirtyNavigationDialog, + ErrorSummary, + Form, + FormActions, + FormField, + useAppForm, + useDirtyNavigationGuard, +} from "../forms/index.js"; +export type { + PageActionDefinition, + PageHeading, +} from "../templates/page-templates.js"; +export type { FormResult } from "../forms/form-contracts.js"; diff --git a/src/presentation/design-system/patterns/common-patterns.tsx b/src/presentation/design-system/patterns/common-patterns.tsx new file mode 100644 index 00000000..3c15b45e --- /dev/null +++ b/src/presentation/design-system/patterns/common-patterns.tsx @@ -0,0 +1,139 @@ +import { useId } from "react"; + +import { + AuthRequiredSurface, + ForbiddenSurface, + NotFoundSurface, +} from "../../components/state-surfaces.jsx"; +import { Button } from "../primitives/core.js"; +import { Pagination } from "../primitives/navigation.js"; + +export type DataTableColumn = Readonly<{ + id: string; + header: string; + cell(row: Row): React.ReactNode; +}>; + +export function DataTable({ + caption, + columns, + rows, + rowKey, + empty, +}: Readonly<{ + caption: string; + columns: readonly DataTableColumn[]; + rows: readonly Row[]; + rowKey(row: Row): string; + empty: React.ReactNode; +}>) { + if (rows.length === 0) return <>{empty}; + return ( +
+ + + + + {columns.map((column) => ( + + ))} + + + + {rows.map((row) => ( + + {columns.map((column) => ( + + ))} + + ))} + +
{caption}
+ {column.header} +
{column.cell(row)}
+
+ ); +} + +export function SearchFilterToolbar({ + label, + search, + filters, + resetLabel, + onReset, + resultCount, +}: Readonly<{ + label: string; + search: React.ReactNode; + filters?: React.ReactNode; + resetLabel: string; + onReset(): void; + resultCount: React.ReactNode; +}>) { + return ( +
+
{search}
+ {filters ?
{filters}
: null} + + {resultCount} +
+ ); +} + +export function PaginationBar({ + range, + ...pagination +}: React.ComponentProps & Readonly<{ range: string }>) { + return ( +
+

{range}

+ +
+ ); +} + +export type DisclosureDefinition = Readonly<{ + id: string; + title: string; + content: React.ReactNode; +}>; + +export function DisclosureGroup({ + label, + items, +}: Readonly<{ + label: string; + items: readonly DisclosureDefinition[]; +}>) { + const groupId = useId(); + return ( +
+

+ {label} +

+ {items.map((item) => ( +
+ {item.title} +
{item.content}
+
+ ))} +
+ ); +} + +export type AccessSurfaceProps = + | Readonly<{ kind: "auth-required"; onAction(): void }> + | Readonly<{ kind: "forbidden"; onAction(): void }> + | Readonly<{ kind: "not-found"; onAction(): void }>; + +export function AccessSurface(props: AccessSurfaceProps) { + if (props.kind === "auth-required") { + return ; + } + if (props.kind === "forbidden") { + return ; + } + return ; +} diff --git a/src/presentation/design-system/primitives/core.tsx b/src/presentation/design-system/primitives/core.tsx new file mode 100644 index 00000000..3c0557cf --- /dev/null +++ b/src/presentation/design-system/primitives/core.tsx @@ -0,0 +1,446 @@ +import { + forwardRef, + useEffect, + useId, + useImperativeHandle, + useRef, +} from "react"; +import { createPortal } from "react-dom"; + +import { CloseIcon } from "../icons/semantic-icons.js"; + +export type ButtonVariant = "primary" | "secondary" | "danger" | "ghost"; +export type ButtonSize = "default" | "compact"; + +export type ButtonProps = React.ButtonHTMLAttributes & + Readonly<{ + variant?: ButtonVariant; + size?: ButtonSize; + pending?: boolean; + pendingLabel?: string; + }>; + +export const Button = forwardRef( + function Button( + { + variant = "primary", + size = "default", + pending = false, + pendingLabel, + className = "", + type = "button", + children, + disabled, + ...props + }, + ref, + ) { + const classes = [ + "ui-button", + `ui-button--${variant}`, + size === "compact" ? "ui-button--compact" : "", + pending ? "ui-button--pending" : "", + className, + ] + .filter(Boolean) + .join(" "); + + return ( + + ); + }, +); + +export type LinkButtonProps = React.AnchorHTMLAttributes & + Readonly<{ + href: string; + variant?: ButtonVariant; + size?: ButtonSize; + }>; + +export const LinkButton = forwardRef( + function LinkButton( + { + href, + variant = "primary", + size = "default", + className = "", + ...props + }, + ref, + ) { + return ( + + ); + }, +); + +export type IconButtonProps = Omit & + Readonly<{ + accessibleName: string; + children: React.ReactElement; + }>; + +export const IconButton = forwardRef( + function IconButton({ accessibleName, className = "", ...props }, ref) { + return ( +