diff --git a/docs/architecture/decisions/VD-06-intl-typed-message-catalog.md b/docs/architecture/decisions/VD-06-intl-typed-message-catalog.md index c9e02cf4..66b0a112 100644 --- a/docs/architecture/decisions/VD-06-intl-typed-message-catalog.md +++ b/docs/architecture/decisions/VD-06-intl-typed-message-catalog.md @@ -68,13 +68,21 @@ route/form/failure 의미 값 ## 검증 -- `check:i18n`은 catalog key와 placeholder parity, 화면 코드의 한국어 literal, - backend message JSX 렌더링과 raw HTML 사용을 검사한다. 검사 범위는 공통 UI - 디렉터리, `src/presentation/pages`, 모든 `src/features/*/presentation`이다. - 컴포넌트 갤러리 `src/presentation/examples`는 일부러 뺐다 - (`scripts/check-i18n.ts`의 `commonDirectories`, `featurePresentationDirectories`). -- `check:i18n:fixture`는 같은 탐색 규칙을 `tests/fixtures/i18n/forbidden` 트리에 - 돌린다. fixture 파일 하나라도 거절되지 않으면 종료 코드 2로 실패한다. +- `check:i18n`은 catalog key와 placeholder parity, backend message JSX 렌더링을 + 검사한다. 검사 범위는 공통 UI 디렉터리, `src/presentation/pages`, 모든 + `src/features/*/presentation`이다. 컴포넌트 갤러리 `src/presentation/examples`는 + 일부러 뺐다(`scripts/check-i18n.ts`의 `commonDirectories`, + `featurePresentationDirectories`). +- 화면 문구가 catalog에서 오는지는 ESLint `no-restricted-syntax`가 본다 + (`eslint.config.ts`의 `screenTextSelectors`, 0929/08-02). 대상은 글자가 든 + `JSXText`와 표시·접근성 속성(`aria-label`, `title`, `placeholder`, `alt`, + `label` 등)의 문자열 literal이다. 주석은 AST에 없어 걸리지 않는다. 범위는 위와 + 같고 stories는 뺐다. 제품은 이 선택자를 자기 설정으로 덮어쓸 수 있다. + raw HTML은 FE-OC-019 ESLint 규칙이 거절한다. +- `check:i18n:fixture`는 같은 탐색 규칙과 위 ESLint 규칙을 + `tests/fixtures/i18n/forbidden` 트리에 돌린다. fixture 파일 하나라도 거절되지 + 않으면 종료 코드 2로 실패한다. `tests/fixtures/i18n/allowed` 트리(한국어 주석, + 구두점, catalog 문구)가 거절돼도 종료 코드 2로 실패한다. - `tests/unit/i18n-contract.test.ts`는 `ERROR_REGISTRY`의 모든 `userMessageKey`가 ko-KR·en-US catalog에 있는지 확인한다. - type negative fixture는 unknown key와 잘못된 parameter shape를 거절한다. diff --git a/eslint.config.ts b/eslint.config.ts index 7f7beeab..2e55d3c6 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -451,6 +451,49 @@ const hookRules = { "react-hooks/exhaustive-deps": "error", }; +// 0929/08-02. Screen code takes its words from the message catalog. Comments +// are not in the AST, so only rendered text and accessible names are checked: +// JSX text and the display/accessibility attributes below that hold a letter +// in any script. Punctuation and numbers pass. Text built in an expression (a +// template literal, a ternary, an object prop such as `heading.title`) is not +// seen; review catches those. A product replaces these selectors in its own +// config, for example to allow a brand name or to drop the rule for a +// one-locale product. The component gallery (src/presentation/examples) and +// stories are workshop code and stay out; tests are outside these folders. +const screenTextDirectories = [ + "src/presentation/boundaries", + "src/presentation/components", + "src/presentation/design-system", + "src/presentation/forms", + "src/presentation/layouts", + "src/presentation/pages", + "src/presentation/routes", + "src/presentation/templates", + "src/features/*/presentation", +]; +const screenTextAttributes = + "/^(?:aria-label|aria-description|aria-roledescription|aria-valuetext|aria-placeholder|title|placeholder|alt|label)$/"; +const screenTextMessage = + "Screen words come from the message catalog: use message(key) (0929/08-02)."; +const screenTextSelectors = [ + { + selector: "JSXText[value=/\\p{L}/u]", + message: screenTextMessage, + }, + { + selector: `JSXElement > JSXExpressionContainer > Literal[value=/\\p{L}/u]`, + message: screenTextMessage, + }, + { + selector: `JSXAttribute[name.name=${screenTextAttributes}] > Literal[value=/\\p{L}/u]`, + message: screenTextMessage, + }, + { + selector: `JSXAttribute[name.name=${screenTextAttributes}] > JSXExpressionContainer > Literal[value=/\\p{L}/u]`, + message: screenTextMessage, + }, +]; + export default [ { ignores: [ @@ -860,6 +903,22 @@ export default [ ], }, }, + { + // The same folders inside an i18n fixture tree, so check:i18n:fixture + // runs this rule on its fixtures. This entry replaces the general + // no-restricted-syntax list, so it carries the FE-OC-019 selectors too. + files: screenTextDirectories.flatMap((directory) => [ + `${directory}/**/*.tsx`, + `tests/fixtures/i18n/*/${directory}/**/*.tsx`, + ]), + ignores: ["**/*.stories.tsx"], + rules: { + "no-restricted-syntax": [ + ...commonSecurityRules["no-restricted-syntax"], + ...screenTextSelectors, + ], + }, + }, { files: [`tests/**/*.${sourceExtensions}`], languageOptions: { diff --git a/scripts/check-i18n.ts b/scripts/check-i18n.ts index e1a58c88..438b2680 100644 --- a/scripts/check-i18n.ts +++ b/scripts/check-i18n.ts @@ -9,7 +9,6 @@ import { EN_MESSAGES, KO_MESSAGES, MESSAGE_CATALOGS } from "../src/presentation/ const fixtureMode = process.argv.includes("--fixture"); const failures: string[] = []; const sourceExtensions = /\.(?:ts|tsx|mts|cts)$/; -const koreanLiteral = /[가-힣]/; const rawFailureRender = /(? { + const found: string[] = []; + for (const file of files) { + if (rawFailureRender.test(await readFile(file, "utf8"))) { + found.push(`raw backend/error message rendered in ${file}`); + } } + return found; } +/** ESLint errors in a fixture tree, one entry per error, ending in the file. */ +async function lintErrors(root: string): Promise { + const { ESLint } = await import("eslint"); + const results = await new ESLint({ ignore: false }).lintFiles([root]); + return results.flatMap((result) => + result.messages + .filter((message) => message.severity === 2) + .map( + (message) => + `${message.ruleId ?? "eslint"} ${message.line}:${message.column} ${message.message} in ${path.relative(process.cwd(), result.filePath)}`, + ), + ); +} + +failures.push(...(await rawFailureRenders(sources))); +if (fixtureMode) failures.push(...(await lintErrors(forbiddenFixtureRoot))); +const allowedFixtureFailures = fixtureMode + ? [ + ...(await rawFailureRenders(await listSourceFiles(allowedFixtureRoot))), + ...(await lintErrors(allowedFixtureRoot)), + ] + : []; + const report = i18nReportArtifactSchema.parse({ schemaVersion: 1, mode: fixtureMode ? "negative-fixture" : "source", @@ -135,6 +163,13 @@ if (fixtureMode && (fixtureFiles.length === 0 || unrejectedFixtures.length > 0)) ); process.exit(2); } +// A comment, punctuation or catalog words must not be rejected (0929/08-02). +if (allowedFixtureFailures.length > 0) { + process.stderr.write( + `I18n allowed fixture was rejected:\n${allowedFixtureFailures.join("\n")}\n`, + ); + process.exit(2); +} if (failures.length > 0) { process.stderr.write(`I18n contract failed:\n${failures.join("\n")}\n`); diff --git a/src/features/reference-feature/contracts/reference-message-catalog.ts b/src/features/reference-feature/contracts/reference-message-catalog.ts index e080dcb1..d96be057 100644 --- a/src/features/reference-feature/contracts/reference-message-catalog.ts +++ b/src/features/reference-feature/contracts/reference-message-catalog.ts @@ -14,7 +14,12 @@ export const REFERENCE_MESSAGE_CATALOGS = Object.freeze({ "reference.list.create": "새 항목 만들기", "reference.list.refresh": "새로고침", "reference.list.resultCount": "총 {count}개 항목", + "reference.list.title": "참조 기능", + "reference.list.filterLimit": "최대 {limit}개", + "reference.list.filterTags": "태그 {tags}", + "reference.list.resources": "참조 리소스 목록", "reference.form.back": "목록으로 돌아가기", + "reference.form.eyebrow": "폼 페이지", "reference.form.title": "Reference resource 만들기", "reference.form.description": "presentation schema, command mapper, 422/conflict와 dirty navigation 정책을 실행합니다.", @@ -33,12 +38,17 @@ export const REFERENCE_MESSAGE_CATALOGS = Object.freeze({ "reference.form.conflict": "충돌을 해결한 뒤 다시 제출할 수 있습니다.", "reference.form.privacy": "form value는 URL, storage, telemetry에 저장되지 않고 submit 시에만 application command로 변환됩니다.", + "reference.detail.eyebrow": "상세 페이지", + "reference.detail.titlePending": "참조 상세", + "reference.detail.resourceId": "리소스 ID", + "reference.detail.createdAt": "생성 시각", "reference.detail.description": "route param과 detail query의 reset 경계를 확인합니다.", "reference.detail.summaryPending": "요약 정보를 준비하고 있습니다.", "reference.detail.sectionSlot": "이 영역에는 제품별 상세 section을 조립할 수 있습니다.", "reference.detail.aside": "상세 페이지의 관련 정보 slot입니다.", + "reference.status.eyebrow": "상태 페이지 · 점검", "reference.status.title": "잠시 사용할 수 없습니다.", "reference.status.description": "도메인 데이터나 raw 오류를 노출하지 않는 중립적인 상태 페이지 예시입니다.", @@ -59,7 +69,12 @@ export const REFERENCE_MESSAGE_CATALOGS = Object.freeze({ "reference.list.create": "Create item", "reference.list.refresh": "Refresh", "reference.list.resultCount": "Total items: {count}", + "reference.list.title": "Reference feature", + "reference.list.filterLimit": "limit {limit}", + "reference.list.filterTags": "tags {tags}", + "reference.list.resources": "Reference resources", "reference.form.back": "Back to the list", + "reference.form.eyebrow": "FormPage", "reference.form.title": "Create a reference resource", "reference.form.description": "Runs the presentation schema, command mapper, 422/conflict and dirty navigation policies.", @@ -78,12 +93,17 @@ export const REFERENCE_MESSAGE_CATALOGS = Object.freeze({ "reference.form.conflict": "Resolve the conflict, then submit again.", "reference.form.privacy": "Form values are never written to the URL, storage or telemetry; they become an application command only on submit.", + "reference.detail.eyebrow": "DetailPage", + "reference.detail.titlePending": "Reference detail", + "reference.detail.resourceId": "Resource ID", + "reference.detail.createdAt": "Created", "reference.detail.description": "Checks the reset boundary between the route parameter and the detail query.", "reference.detail.summaryPending": "Preparing the summary.", "reference.detail.sectionSlot": "Product-specific detail sections can be assembled here.", "reference.detail.aside": "Related information slot of the detail page.", + "reference.status.eyebrow": "StatusPage · maintenance", "reference.status.title": "Temporarily unavailable.", "reference.status.description": "An example of a neutral status page that exposes no domain data or raw errors.", 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 447a091a..29d6e9b3 100644 --- a/src/features/reference-feature/presentation/reference-resource-detail-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-detail-page.tsx @@ -21,19 +21,21 @@ export default function ReferenceResourceDetailPage() { Reference resources + + {message("reference.list.resources")} + } heading={{ - eyebrow: "DetailPage", - title: resource?.title ?? "Reference detail", + eyebrow: message("reference.detail.eyebrow"), + title: resource?.title ?? message("reference.detail.titlePending"), description: message("reference.detail.description"), }} metadata={ resource ? (
-
Resource ID
+
{message("reference.detail.resourceId")}
{resource.resourceId}
-
Created
+
{message("reference.detail.createdAt")}
{resource.createdAt ? date(new Date(resource.createdAt)) 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 342dc106..13d796d4 100644 --- a/src/features/reference-feature/presentation/reference-resource-form-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-form-page.tsx @@ -77,7 +77,7 @@ export default function ReferenceResourceFormPage() { } heading={{ - eyebrow: "FormPage", + eyebrow: message("reference.form.eyebrow"), title: message("reference.form.title"), description: message("reference.form.description"), }} diff --git a/src/features/reference-feature/presentation/reference-resource-page.tsx b/src/features/reference-feature/presentation/reference-resource-page.tsx index 997345c6..b143930e 100644 --- a/src/features/reference-feature/presentation/reference-resource-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-page.tsx @@ -19,7 +19,7 @@ export default function ReferenceResourcePage() { - limit {filters.limit} - {filters.tags?.length ? ` · tags ${filters.tags.join(", ")}` : ""} + {message("reference.list.filterLimit", { limit: filters.limit })} + {filters.tags?.length + ? ` · ${message("reference.list.filterTags", { + tags: filters.tags.join(", "), + })}` + : ""}

} toolbar={ @@ -55,7 +59,7 @@ export default function ReferenceResourcePage() { onAction={failureAction} onRetry={query.retry} > -
    +
      {(query.data ?? []).map((resource) => (
    • { await page.route(LIST_API, (route) => route.fulfill({ json: payload })); - await signInAt(page, LIST_PATH, "Reference feature"); + await signInAt(page, LIST_PATH, "참조 기능"); await expect(page.getByRole("main")).toContainText(visible); await expectNoBlockingViolations(page); }); diff --git a/tests/features/reference-feature/reference-page.test.tsx b/tests/features/reference-feature/reference-page.test.tsx index c833f7c3..5a5bb77f 100644 --- a/tests/features/reference-feature/reference-page.test.tsx +++ b/tests/features/reference-feature/reference-page.test.tsx @@ -31,6 +31,7 @@ import { createServerStateScopeRuntime } from "../../../src/adapters/query-cache import { ApplicationProvider } from "../../../src/presentation/providers/application-provider.tsx"; import { PreferenceProviders } from "../../../src/presentation/providers/preference-providers.tsx"; import { AppRouter } from "../../../src/presentation/routes/app-router.tsx"; +import { KO_MESSAGES } from "../../../src/presentation/i18n/catalog.ts"; import { createTestApplication } from "../../helpers/create-test-application.ts"; function renderReference( @@ -121,7 +122,53 @@ function inputWith( }; } +/** + * 0929/08-02. The main area's text and accessible names with every ko-KR + * catalog value and every given data value cut out. The lint rule sees JSX + * text and attributes only; this also sees words passed through props. + */ +function mainTextOutsideCatalog(data: readonly string[]): string { + const main = screen.getByRole("main"); + const names = [...main.querySelectorAll("[aria-label],[title],[placeholder],[alt]")] + .flatMap((element) => + ["aria-label", "title", "placeholder", "alt"].map( + (name) => element.getAttribute(name) ?? "", + ), + ); + return [...data, ...Object.values(KO_MESSAGES)] + .sort((left, right) => right.length - left.length) + .reduce( + (text, known) => text.split(known).join(" "), + [main.textContent ?? "", ...names].join(" "), + ); +} + describe("reference feature page states", () => { + it("shows no Latin words outside the catalog on the ko-KR screens", async () => { + const resource = { + resourceId: "reference-1", + title: "Loaded", + createdAt: null, + }; + const input = inputWith({ + listResources: async () => ({ ok: true, value: [resource] }), + }); + for (const [url, ready] of [ + ["/examples/reference-resources?limit=5&tags=open", "Loaded"], + ["/examples/reference-resources/items/reference-1", "Detail"], + ["/examples/reference-resources/new", "저장"], + ["/examples/reference-resources/status", "목록으로 이동"], + ] as const) { + const view = renderReference(input, url); + await screen.findAllByText(ready); + expect( + mainTextOutsideCatalog(["reference-1", "Loaded", "Detail", "open"]), + url, + ).not.toMatch(/[A-Za-z]/); + view.unmount(); + } + }); + it("mounts list and detail keys under the installed governed namespace", async () => { expect(REFERENCE_RESOURCE_QUERY_NAMESPACE).toEqual({ namespaceId: "reference-resource", diff --git a/tests/fixtures/i18n/allowed/src/presentation/components/korean-comment.tsx b/tests/fixtures/i18n/allowed/src/presentation/components/korean-comment.tsx new file mode 100644 index 00000000..eb6f7ca7 --- /dev/null +++ b/tests/fixtures/i18n/allowed/src/presentation/components/korean-comment.tsx @@ -0,0 +1,10 @@ +// 한국어 주석은 화면 문구가 아니다. 문구는 catalog에서 온다. +export function CatalogAction({ + message, +}: Readonly<{ message: (key: "action.retry") => string }>) { + return ( + + ); +} diff --git a/tests/fixtures/i18n/forbidden/src/features/sample-feature/presentation/english-accessible-name.tsx b/tests/fixtures/i18n/forbidden/src/features/sample-feature/presentation/english-accessible-name.tsx new file mode 100644 index 00000000..af5781a1 --- /dev/null +++ b/tests/fixtures/i18n/forbidden/src/features/sample-feature/presentation/english-accessible-name.tsx @@ -0,0 +1,3 @@ +export function EnglishAccessibleName() { + return
        ; +} diff --git a/tests/fixtures/i18n/forbidden/src/presentation/components/english-jsx-text.tsx b/tests/fixtures/i18n/forbidden/src/presentation/components/english-jsx-text.tsx new file mode 100644 index 00000000..e02b07e5 --- /dev/null +++ b/tests/fixtures/i18n/forbidden/src/presentation/components/english-jsx-text.tsx @@ -0,0 +1,3 @@ +export function EnglishHeading() { + return

        Reference feature

        ; +}