Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@
# Generated runtime English subset: compared byte-for-byte by
# verify:localization-runtime-catalog, so a CRLF checkout would fail the gate.
/src/renderer/src/i18n/en-runtime-required.json linguist-generated=true text eol=lf
# Generated from zh.json; compare-zh-hant-catalog reads it as text and compares
# byte-for-byte, so a CRLF checkout would fail the gate on a clean tree.
/src/renderer/src/i18n/locales/zh-Hant.json linguist-generated=true text eol=lf
# Generated method->params catalog: compared byte-for-byte by
# verify:rpc-params-catalog, so a CRLF checkout would fail the gate.
/src/shared/rpc-contract/rpc-params-catalog.generated.ts linguist-generated=true text eol=lf
Expand Down
81 changes: 81 additions & 0 deletions config/scripts/generate-zh-hant-catalog.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Generates src/renderer/src/i18n/locales/zh-Hant.json from zh.json.
//
// Usage: node config/scripts/generate-zh-hant-catalog.mjs [--check]
//
// Why derived from Simplified rather than translated from English: the Simplified
// catalog carries reviewed terminology and Orca glossary decisions that a fresh
// English→Traditional translation would have to rediscover, and a script
// conversion cannot regress a term that catalog already settled. Deriving the
// key set from zh.json also inherits its sparseness — a key zh.json leaves to
// the English runtime fallback stays absent here for the same reason.
// `--check` regenerates in memory and fails if the committed file differs.
import fs from 'node:fs/promises'
import path from 'node:path'
import process from 'node:process'
import { pathToFileURL } from 'node:url'

import {
collectStringLeaves,
convertCatalogLeaves,
convertValueToTraditional
} from './zh-hant-catalog.mjs'
import { ZHT_KEY_OVERRIDES } from './locale-zht-key-overrides.mjs'

export const LOCALES_DIR = path.join('src', 'renderer', 'src', 'i18n', 'locales')
export const ZHT_CATALOG_FILE = 'zh-Hant.json'

/** Traditional value for one leaf; a pinned key wins over the conversion. */
export function convertLeaf(zhValue, key) {
return ZHT_KEY_OVERRIDES[key] ?? convertValueToTraditional(zhValue)
}

export function buildZhHantCatalog({ zhCatalog }) {
return convertCatalogLeaves(zhCatalog, convertLeaf)
}

export function serializeCatalog(catalog) {
return `${JSON.stringify(catalog, null, 2)}\n`
}

export async function main(root = process.cwd(), argv = process.argv.slice(2)) {
const zhCatalogPath = path.join(root, LOCALES_DIR, 'zh.json')
let zhCatalog
try {
zhCatalog = JSON.parse(await fs.readFile(zhCatalogPath, 'utf8'))
} catch {
// Why: zh-Hant is derived from zh.json, so a tree without one (the
// combined verifier's synthetic fixtures) has nothing to derive or check.
console.log(`${ZHT_CATALOG_FILE} is derived from zh.json, which is absent here.`)
return 0
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

const catalog = buildZhHantCatalog({ zhCatalog })
const catalogPath = path.join(root, LOCALES_DIR, ZHT_CATALOG_FILE)
const expected = serializeCatalog(catalog)

if (argv.includes('--check')) {
let actual
try {
actual = await fs.readFile(catalogPath, 'utf8')
} catch {
console.error(`${ZHT_CATALOG_FILE} is missing. Run \`pnpm run sync:zh-hant-catalog\`.`)
return 1
}
if (actual !== expected) {
console.error(
`${ZHT_CATALOG_FILE} is out of date with zh.json. Run \`pnpm run sync:zh-hant-catalog\`.`
)
return 1
}
console.log(`${ZHT_CATALOG_FILE} matches zh.json.`)
return 0
}

await fs.writeFile(catalogPath, expected, 'utf8')
console.log(`Wrote ${catalogPath} (${collectStringLeaves(catalog).length} entries).`)
return 0
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
process.exit(await main())
}
124 changes: 124 additions & 0 deletions config/scripts/generate-zh-hant-catalog.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import fs from 'node:fs'
import path from 'node:path'
import { describe, expect, it } from 'vitest'

import {
LOCALES_DIR,
ZHT_CATALOG_FILE,
buildZhHantCatalog,
serializeCatalog
} from './generate-zh-hant-catalog.mjs'
import { collectStringLeaves, isSimplifiedOnly } from './zh-hant-catalog.mjs'
import { ZHT_KEY_OVERRIDES } from './locale-zht-key-overrides.mjs'

const readCatalog = (locale) =>
JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, `${locale}.json`), 'utf8'))

const zhCatalog = readCatalog('zh')
const enCatalog = readCatalog('en')
const zhHantCatalog = readCatalog('zh-Hant')

describe('zh-Hant catalog generation', () => {
it('stays in sync with zh.json', () => {
// Why: zh-Hant is generated, so a Simplified edit that skips
// `sync:zh-hant-catalog` would otherwise ship a stale Traditional catalog,
// and the combined verifier would be the only thing to notice.
const expected = serializeCatalog(buildZhHantCatalog({ zhCatalog }))
const onDisk = fs.readFileSync(path.join(LOCALES_DIR, ZHT_CATALOG_FILE), 'utf8')
expect(onDisk).toBe(expected)
})

it('covers exactly the keys zh.json carries', () => {
// Why: deriving the key set from zh.json is what inherits its sparseness —
// a key zh.json leaves to the English runtime fallback must stay absent
// here for the same reason rather than being invented.
const zhKeys = collectStringLeaves(zhCatalog)
.map((leaf) => leaf.key)
.sort()
const zhHantKeys = collectStringLeaves(zhHantCatalog)
.map((leaf) => leaf.key)
.sort()
expect(zhHantKeys).toEqual(zhKeys)
})

it('preserves every interpolation placeholder', () => {
const placeholder = (value) => [...(value.match(/\{\{[^}]+\}\}/g) ?? [])].sort().join('|')
const byKey = new Map(collectStringLeaves(zhCatalog).map((leaf) => [leaf.key, leaf.value]))
const mismatches = collectStringLeaves(zhHantCatalog)
.filter((leaf) => placeholder(leaf.value) !== placeholder(byKey.get(leaf.key)))
.map((leaf) => leaf.key)
expect(mismatches).toEqual([])
})

it('leaves no Simplified-only character behind', () => {
// Why: a conversion that silently skips a word (OpenCC missed 云包) ships
// Simplified glyphs to a Traditional reader. The check uses the pure
// character map minus the glyphs both scripts share, and exempts the
// language-picker endonyms — those are deliberately Simplified
// (see locale-zht-key-overrides).
const pinned = new Set(Object.keys(ZHT_KEY_OVERRIDES))
const offenders = collectStringLeaves(zhHantCatalog)
.filter((leaf) => !pinned.has(leaf.key))
.flatMap((leaf) => {
const simplified = [...new Set([...leaf.value].filter(isSimplifiedOnly))]
return simplified.length > 0 ? [`${leaf.key}: ${simplified.join('')}`] : []
})
expect(offenders).toEqual([])
})

it('uses the Taiwan terms OpenCC gets wrong on its own', () => {
const zhHant = new Map(collectStringLeaves(zhHantCatalog).map((l) => [l.key, l.value]))
const zh = new Map(collectStringLeaves(zhCatalog).map((l) => [l.key, l.value]))

// Permission: OpenCC emits 許可權, Taiwan says 權限.
expect(zhHant.get('settings.chat.permissionsTitle')).toBe('新聊天的權限')
// Cursor: OpenCC's phrase dictionary overshoots 游標 to 遊標.
expect(zhHant.get('auto.components.settings.TerminalAppearanceSection.abcb4dd019')).toBe(
'終端游標'
)
// Process: the source said 進程 (an OS process), which Taiwan calls 行程 —
// not 程式 ("program"), which is where OpenCC's single pass lands.
const processKeys = [...zh.keys()].filter((key) => zh.get(key)?.includes('进程'))
expect(processKeys.length).toBeGreaterThan(0)
for (const key of processKeys) {
expect(zhHant.get(key), key).not.toContain('程序')
}
})

// Why not folded into the leftover-character test above: that test exempts
// glyphs both scripts legitimately share, and 云 is one of them (白雲 is
// correct Traditional). The exemption is what lets a regression of the
// 云包→雲包 fix pass unnoticed, so the words that motivated the rule are
// pinned here by value instead of by glyph.
it('converts word-forms the phrase dictionary skips', () => {
const zhHant = new Map(collectStringLeaves(zhHantCatalog).map((l) => [l.key, l.value]))
const zh = new Map(collectStringLeaves(zhCatalog).map((l) => [l.key, l.value]))

const cloudKeys = [...zh.keys()].filter((key) => zh.get(key)?.includes('云'))
expect(cloudKeys.length).toBeGreaterThan(0)
for (const key of cloudKeys) {
expect(zhHant.get(key), key).not.toContain('云')
}

// The same for the compounded 復制 that single-pass twp produced from 复制.
const copyKeys = [...zh.keys()].filter((key) => zh.get(key)?.includes('复制'))
expect(copyKeys.length).toBeGreaterThan(0)
for (const key of copyKeys) {
expect(zhHant.get(key), key).not.toContain('復制')
}
})

it('keeps language-picker endonyms untranslated', () => {
// Why: a reader switches to their own language from an interface they may
// not read, so each language name stays in that language's own script.
const language = zhHantCatalog.settings.appearance.language
expect(language.chinese).toBe('中文(简体)')
expect(language.chineseTraditional).toBe('中文(繁體)')
expect(language.korean).toBe('한국어')
expect(language.japanese).toBe('日本語')
})

it('keeps the English catalog pinned to the same picker labels', () => {
expect(enCatalog.settings.appearance.language.chineseTraditional).toBe('中文(繁體)')
})
})
5 changes: 5 additions & 0 deletions config/scripts/locale-translation-policy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -222,34 +222,39 @@ export const NEVER_TRANSLATE_VALUES = new Set([
export const NATIVE_PICKER_LABELS = {
zh: {
chinese: '中文(简体)',
chineseTraditional: '中文(繁體)',
korean: '한국어',
japanese: '日本語',
spanish: 'Español',
french: 'Français'
},
ko: {
chinese: '中文(简体)',
chineseTraditional: '中文(繁體)',
korean: '한국어',
japanese: '日本語',
spanish: 'Español',
french: 'Français'
},
ja: {
chinese: '中文(简体)',
chineseTraditional: '中文(繁體)',
korean: '한국어',
japanese: '日本語',
spanish: 'Español',
french: 'Français'
},
es: {
chinese: '中文(简体)',
chineseTraditional: '中文(繁體)',
korean: '한국어',
japanese: '日本語',
spanish: 'Español',
french: 'Français'
},
fr: {
chinese: '中文(简体)',
chineseTraditional: '中文(繁體)',
korean: '한국어',
japanese: '日本語',
spanish: 'Español',
Expand Down
23 changes: 23 additions & 0 deletions config/scripts/locale-zht-key-overrides.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Per-key Traditional overrides, by Orca message ID.
//
// Why a key map in addition to the phrase fixes: a value whose correct form
// cannot be expressed as a substring rule, because the same substring must stay
// untouched elsewhere, is pinned here.
import { NATIVE_PICKER_LABELS } from './locale-translation-policy.mjs'

/**
* The language picker lists every language in its OWN script, so a reader can
* find their language from an interface they cannot read. Converting them would
* rename Simplified Chinese "中文(簡體)" in a script its own users do not read —
* the one place a Simplified form must survive in this catalog.
*
* Derived from NATIVE_PICKER_LABELS rather than restated, so the catalog and the
* repair policy cannot drift into disagreeing about the same labels. Every locale
* in that table carries identical values (an endonym does not vary by UI locale).
*/
export const ZHT_KEY_OVERRIDES = Object.fromEntries(
Object.entries(NATIVE_PICKER_LABELS.zh).map(([labelKey, label]) => [
`settings.appearance.language.${labelKey}`,
label
])
)
72 changes: 72 additions & 0 deletions config/scripts/locale-zht-value-overrides.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Post-conversion corrections for OpenCC's `cn → twp` output.
//
// Why fixes at all: `twp`'s phrase dictionary is neither complete nor idempotent,
// so in some contexts it emits a mainland form the Taiwan UI never uses (it maps
// 复制→複製 alone but 进行复制→進行復制). Re-running OpenCC does not remove these —
// iterating to a fixed point makes two cases worse (游標→遊標, 程序→程式 for
// "process") — so each correction is an explicit, reviewable entry here.
//
// Every rule is evidence-backed. The reference corpus is the Traditional Chinese
// language pack Microsoft ships for VS Code, about 2 MB of reviewed Taiwan UI
// terminology. A rule belongs here only when that corpus shows the `twp` form
// essentially unused and the replacement well attested; a style preference does
// not qualify. Hit counts are recorded as "twp form N vs Taiwan form M".
export const ZHT_PHRASE_FIXES = [
// Permission: 許可權 0 vs 權限 84.
['許可權', '權限'],
// Account: 賬戶 0 vs 帳戶 111.
['賬戶', '帳戶'],
// Background: 後臺 0 ("back stage") vs 後台 1.
['後臺', '後台'],
// Save/store: 存儲 is not a Taiwan word; 儲存 642 (保存 5).
['存儲', '儲存'],
['保存', '儲存'],
// Send: 發送 0 vs 傳送 118.
['發送', '傳送'],
// Add: 添加 0 vs 新增 359.
['添加', '新增'],
// Font: 字體 2 vs 字型 164.
['字體', '字型'],
// Device: 設備 0 vs 裝置 36.
['設備', '裝置'],
// Run: 運行 4 vs 執行 1050.
['運行', '執行'],
// Info: 信息 0 vs 資訊 211; message: 消息 already 訊息.
['信息', '資訊'],
// Default: 默認 1 vs 預設 380.
['默認', '預設'],
// Open: 打開 2 vs 開啟 1158.
['打開', '開啟'],
// Interface: 接口 0 vs 介面 25.
['接口', '介面'],
// Network: 網絡 0 vs 網路 60.
['網絡', '網路'],
// Mouse/pointer: 鼠標 → 滑鼠 58, 指針 → 指標.
['鼠標', '滑鼠'],
['指針', '指標'],
// Video: 視頻 0 vs 影片 11.
['視頻', '影片'],
// Software: 軟件 → 軟體.
['軟件', '軟體'],
// Clipboard: 剪貼板 → 剪貼簿 33.
['剪貼板', '剪貼簿'],
// 云 survived the phrase pass in 云包/云虛擬機; the character map is
// unambiguous for it (云→雲, and 雲 itself contains no 云).
['云', '雲'],
// twp produced 復制 ("again"+"make") from 进行复制; the source meant 複製.
['復制', '複製']
]

/**
* Rules that need the Simplified source to disambiguate the output.
*
* Why: the Simplified catalog distinguishes 進程 ("process") from 程序
* ("program"), but `twp` maps the former to 程序 and the latter to 程式 — so the
* two collapse and the output alone cannot say which was meant. Taiwan calls an
* OS process 行程 (24 corpus hits), and `twp` never emits 程序 for a source that
* said 程序 (that becomes 程式), so any 程序 left in the output came from 進程.
* Reads `{ source, from, to }`: when the Simplified value contains `source`,
* replace `from` in the converted value with `to`. `source` is Simplified — it
* is matched against zh.json, not against the converted value.
*/
export const ZHT_SOURCE_CONDITIONAL_FIXES = [{ source: '进程', from: '程序', to: '行程' }]
6 changes: 5 additions & 1 deletion config/scripts/verify-localization-catalogs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@ import {
main as verifyCatalog
} from './verify-localization-catalog.mjs'
import { main as verifyRuntimeCatalog } from './generate-runtime-required-english-catalog.mjs'
import { main as verifyZhHantCatalog } from './generate-zh-hant-catalog.mjs'

export async function main(root = process.cwd()) {
// Share only this invocation's scan, never cached evidence from another checkout.
const references = await collectLocalizationReferences(root)
const results = await Promise.allSettled([
verifyCatalog(root, {}, references),
verifyRuntimeCatalog(root, [], references)
verifyRuntimeCatalog(root, [], references),
// Why: zh-Hant.json is generated from zh.json, so a Simplified edit that
// skips `sync:zh-hant-catalog` would ship a stale Traditional catalog.
verifyZhHantCatalog(root, ['--check'])
])
let exitCode = 0
for (const result of results) {
Expand Down
Loading