Files
clean-architecture-frontend…/scripts/check-i18n.ts
T
DongHyeonka ade1fc4a71 fix(i18n): 제품이 화면 언어를 자기 파일에서 선언한다
문제: 지원 locale 목록, 언어 대체, 글 방향, 문구 표, 셸의 언어
선택지가 템플릿 파일 다섯 곳에 손으로 적혀 있다. 한 언어 제품은 가짜
en-US 문구를 만들거나 템플릿 파일을 고쳐야 하고, 운영 셸 메뉴에
Pseudo·RTL 시험 locale이 보인다(0929/08-01).

고른 방법(1101 결정 (가), 템플릿이 확장 지점을 연다):
- 제품 소유 src/contracts/product-contracts.ts에 PRODUCT_LOCALES
  (기본 ko-KR, en-US)와 DEV_LOCALES(기본 en-XA, ar-EG)를 둔다.
- message-contract가 둘에서 SUPPORTED_LOCALES, 언어 대체(같은 언어의
  첫 선언 locale, 없으면 첫 제품 locale), 글 방향(RTL 언어 집합),
  DEFAULT_LOCALE을 만든다. 시험 locale은 en-US 문구를, en-US가 없으면 첫
  제품 locale 문구를 보인다.
- catalog.ts는 선언한 제품 locale마다 문구 표 하나를 둔다. en-US 표는
  en-US를 선언했을 때만 모든 키를 요구한다.
- 셸 언어 선택지는 선언에서 나오고, locale이 하나면 선택을 그리지 않는다.
  템플릿 문구에 없는 locale은 Intl.DisplayNames의 자기 이름으로 적는다.
버린 대안: 운영 환경(APP_ENV)에서 시험 locale을 자동으로 숨기기 —
presentation이 실행 환경을 읽는 포트가 없고, e2e가 production 빌드로
시험 locale을 고른다. 제품이 DEV_LOCALES를 비우는 쪽이 명시적이다.

위험·한계: ko-KR은 다른 표를 대조하는 원본이라 남겨야 한다. 템플릿에
없는 언어를 선언하면 그 문구 표가 catalog.ts에 있어야 한다(타입 오류로
알린다). 시험 locale을 빼는 것은 제품이 DEV_LOCALES를 비울 때다.

검증: desktop 결과는 PR 본문.

Refs: 0929/08-01
2026-11-13 21:16:40 +09:00

183 lines
6.9 KiB
TypeScript

import { mkdir, readFile, readdir } from "node:fs/promises";
import { i18nReportArtifactSchema } from "./contracts/release-artifacts.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
import path from "node:path";
import { EN_MESSAGES, KO_MESSAGES, MESSAGE_CATALOGS } from "../src/presentation/i18n/catalog.ts";
import { SUPPORTED_LOCALES } from "../src/presentation/i18n/message-contract.ts";
const fixtureMode = process.argv.includes("--fixture");
const failures: string[] = [];
const sourceExtensions = /\.(?:ts|tsx|mts|cts)$/;
const rawFailureRender =
/(?<!\$)\{\s*(?:failure|error|response|backend)(?:\?\.|\.)[\w?.]*message\s*\}/;
async function listSourceFiles(directory: string): Promise<string[]> {
const result: string[] = [];
for (const entry of await readdir(directory, { withFileTypes: true })) {
const target = path.join(directory, entry.name);
if (entry.isDirectory()) result.push(...(await listSourceFiles(target)));
else if (sourceExtensions.test(entry.name)) result.push(target);
}
return result;
}
function placeholders(template: string): string[] {
return [...template.matchAll(/\{([a-zA-Z][a-zA-Z0-9]*)\}/g)]
.map((match) => match[1])
.sort();
}
if (!fixtureMode) {
const canonicalKeys = Object.keys(KO_MESSAGES).sort();
for (const [locale, catalog] of Object.entries(MESSAGE_CATALOGS)) {
const readableCatalog = catalog as Readonly<Record<string, string>>;
const canonicalCatalog = KO_MESSAGES as Readonly<Record<string, string>>;
const keys = Object.keys(catalog).sort();
if (JSON.stringify(keys) !== JSON.stringify(canonicalKeys)) {
failures.push(`${locale} catalog keys do not match ko-KR`);
}
for (const key of canonicalKeys) {
if (
JSON.stringify(placeholders(readableCatalog[key] ?? "")) !==
JSON.stringify(placeholders(canonicalCatalog[key] ?? ""))
) {
failures.push(`${locale}:${key} interpolation parameters do not match`);
}
}
}
// 0929/08-01. Only a product that ships en-US needs every key in it.
if (Object.hasOwn(MESSAGE_CATALOGS, "en-US") && Object.keys(EN_MESSAGES).length !== canonicalKeys.length) {
failures.push("en-US catalog key count does not match ko-KR");
}
}
// 0929/08-02. Whether screen code takes its words from the catalog is an
// ESLint rule now (eslint.config.ts, screenTextSelectors): this script looked
// for Hangul anywhere in a file, so it rejected Korean comments and let English
// copy through. Raw HTML is the FE-OC-019 ESLint rule. What stays here is
// catalog parity and rendering a backend message, which a selector cannot tell
// from an ordinary `.message` read. Fixture mode runs the ESLint rule on the
// fixture trees too, so this one gate shows the whole i18n contract rejecting
// every forbidden file and passing the allowed one.
// `src/presentation/examples` (the platform overview) and the stories are
// workshop code and stay out of the ESLint rule's scope on purpose.
const forbiddenFixtureRoot = "tests/fixtures/i18n/forbidden";
const allowedFixtureRoot = "tests/fixtures/i18n/allowed";
const sourceRoot = fixtureMode ? forbiddenFixtureRoot : ".";
const commonDirectories = [
"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",
];
async function featurePresentationDirectories(root: string): Promise<string[]> {
const features = path.join(root, "src/features");
const entries = await readdir(features, { withFileTypes: true }).catch(
() => [],
);
return entries
.filter((entry) => entry.isDirectory())
.map((entry) => path.join("src/features", entry.name, "presentation"));
}
async function existingSourceFiles(directory: string): Promise<string[]> {
return listSourceFiles(directory).catch((error: NodeJS.ErrnoException) => {
if (error.code === "ENOENT") return [];
throw error;
});
}
const sourceDirectories = [
...commonDirectories,
...(await featurePresentationDirectories(sourceRoot)),
].map((directory) => path.join(sourceRoot, directory));
const sources = (
await Promise.all(sourceDirectories.map(existingSourceFiles))
).flat();
async function rawFailureRenders(files: readonly string[]): Promise<string[]> {
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<string[]> {
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",
localeCount: SUPPORTED_LOCALES.length,
messageKeyCount: Object.keys(KO_MESSAGES).length,
checkedFiles: sources.length,
failures,
passed: failures.length === 0,
});
await mkdir("artifacts/quality", { recursive: true });
await writeValidatedJsonArtifact({
path: fixtureMode
? "artifacts/quality/i18n-fixture.json"
: "artifacts/quality/i18n.json",
schema: i18nReportArtifactSchema,
value: report,
});
// Every fixture file must be rejected on its own; one rejected file must not
// hide a directory the discovery above stopped reaching.
const fixtureFiles = fixtureMode ? await listSourceFiles(sourceRoot) : [];
const unrejectedFixtures = fixtureFiles.filter(
(file) => !failures.some((failure) => failure.endsWith(file)),
);
if (fixtureMode && (fixtureFiles.length === 0 || unrejectedFixtures.length > 0)) {
process.stderr.write(
`I18n fixture was not rejected:\n${unrejectedFixtures.join("\n") || "(no fixture files found)"}\n`,
);
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`);
process.exit(1);
}
process.stdout.write(
`I18n contract: ${report.messageKeyCount} keys across ${report.localeCount} locales PASS\n`,
);