feat(i18n): @xenia/i18n translations, language resolution and venue-time formatting
Platform-v2 step 2.4 (APPS_PLATFORM D-11, D-12, §7.2, §8): - i18next 26.7.2 + react-i18next 17.1.13 (exact); en/el locale files (common, dev); createI18n, I18nProvider, useLanguage, setUserLanguage (screen first, then PATCH /api/auth/me through an app-provided save) - resolveLanguage: user -> device -> venue -> en - useFormat(): dates/times always in the venue zone from bootstrap (24 h, DST-safe, business dates never shifted), relative times, money and numbers per language; parseNumber accepts a comma or a dot - scripts/check-i18n.mjs guard: keys missing in en, placeholder mismatches, dates formatted without the venue zone in new code (fails); missing el (warns) - @xenia/ui components read their texts from UiLabelsProvider; useUiLabels() supplies the translated set - dev-only /i18n-sample in the manager; ui.mjs e2e checks it with the browser in New York; unit tests in run-all; lockfile keeps both apps' versions - new pack rule CS-17 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
// Translation and time-zone guard (plan step 2.4, APPS_PLATFORM §7.2, §8).
|
||||
//
|
||||
// node packages/i18n/scripts/check-i18n.mjs (from client-services/; also run by npm test -w @xenia/i18n)
|
||||
//
|
||||
// ERRORS (exit 1):
|
||||
// - a key used in code (t('…'), i18nKey="…") that isn't in the English files
|
||||
// - a key whose {{placeholders}} differ between en and el
|
||||
// - in new code (packages/*, terminal/): toLocaleString/-DateString/-TimeString or
|
||||
// new Intl.DateTimeFormat( without a timeZone — dates must be shown in venue time (useFormat)
|
||||
// WARNINGS (exit 0): English keys missing in Greek, Greek keys that English doesn't have.
|
||||
//
|
||||
// Only files that import react-i18next or @xenia/i18n are scanned for keys, so v1 code with
|
||||
// its own `t` variables doesn't confuse it. A file's default namespace is the first
|
||||
// useTranslation('ns') in it ("common" otherwise); "ns:key" overrides. Plural keys
|
||||
// (key_one/key_other) count as the base key. Dynamic keys (t(`x.${y}`)) are skipped.
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const PKG = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const CS = path.resolve(PKG, '..', '..')
|
||||
const LOCALES = path.join(PKG, 'locales')
|
||||
const SOURCE = 'en'
|
||||
const quiet = process.argv.includes('--quiet')
|
||||
|
||||
const errors = []
|
||||
const warnings = []
|
||||
const rel = p => path.relative(CS, p).split(path.sep).join('/')
|
||||
|
||||
// ── Locale files ─────────────────────────────────────────────────────────────
|
||||
function flatten(obj, prefix = '', out = {}) {
|
||||
for (const [k, v] of Object.entries(obj)) {
|
||||
const key = prefix ? `${prefix}.${k}` : k
|
||||
if (v && typeof v === 'object') flatten(v, key, out)
|
||||
else out[key] = String(v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
const langs = readdirSync(LOCALES).filter(d => statSync(path.join(LOCALES, d)).isDirectory())
|
||||
const keys = {} // keys[lang]["ns:key"] = text
|
||||
for (const lang of langs) {
|
||||
keys[lang] = {}
|
||||
for (const file of readdirSync(path.join(LOCALES, lang)).filter(f => f.endsWith('.json'))) {
|
||||
const ns = file.slice(0, -5)
|
||||
let data
|
||||
try { data = JSON.parse(readFileSync(path.join(LOCALES, lang, file), 'utf8')) } catch (e) {
|
||||
errors.push(`${lang}/${file}: invalid JSON (${e.message})`); continue
|
||||
}
|
||||
for (const [k, v] of Object.entries(flatten(data))) keys[lang][`${ns}:${k}`] = v
|
||||
}
|
||||
}
|
||||
const placeholders = text => [...text.matchAll(/\{\{\s*([\w.]+)[^}]*\}\}/g)].map(m => m[1]).sort().join(',')
|
||||
for (const lang of langs.filter(l => l !== SOURCE)) {
|
||||
for (const [k, v] of Object.entries(keys[SOURCE])) {
|
||||
if (!(k in keys[lang])) warnings.push(`${lang}: missing ${k}`)
|
||||
else if (placeholders(v) !== placeholders(keys[lang][k])) {
|
||||
errors.push(`${lang}: ${k} has placeholders {${placeholders(keys[lang][k])}}, English has {${placeholders(v)}}`)
|
||||
}
|
||||
}
|
||||
for (const k of Object.keys(keys[lang])) if (!(k in keys[SOURCE])) warnings.push(`${lang}: ${k} isn't in English (remove it or add it to en)`)
|
||||
}
|
||||
const known = new Set(Object.keys(keys[SOURCE]).map(k => k.replace(/_(zero|one|two|few|many|other)$/, '')))
|
||||
const exists = k => known.has(k) || (k in keys[SOURCE])
|
||||
|
||||
// ── Source files ─────────────────────────────────────────────────────────────
|
||||
function walk(dir, out = []) {
|
||||
if (!existsSync(dir)) return out
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (name === 'node_modules' || name === 'dist' || name.startsWith('dist-') || name === 'android') continue
|
||||
const p = path.join(dir, name)
|
||||
if (statSync(p).isDirectory()) walk(p, out)
|
||||
else if (/\.(jsx?|mjs|tsx?)$/.test(name)) out.push(p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
const packages = readdirSync(path.join(CS, 'packages')).map(d => path.join(CS, 'packages', d))
|
||||
// New code: every package (minus tests/scripts) and the terminal app. The v1 apps join as they're converted (phases 4, 6).
|
||||
const newCode = [...packages.flatMap(p => ['src', 'gallery', 'sample'].map(d => path.join(p, d))), path.join(CS, 'terminal', 'src')]
|
||||
const keyScan = [...newCode, path.join(CS, 'manager_dashboard', 'src'), path.join(CS, 'waiter_pwa', 'src')]
|
||||
|
||||
// The one place allowed to build Intl.DateTimeFormat directly (it always passes timeZone)
|
||||
const TIME_ALLOW = new Set(['packages/i18n/src/format.js'])
|
||||
const used = new Set()
|
||||
|
||||
for (const file of [...new Set(keyScan.flatMap(d => walk(d)))]) {
|
||||
const text = readFileSync(file, 'utf8')
|
||||
const r = rel(file)
|
||||
const isNew = newCode.some(d => file.startsWith(d + path.sep))
|
||||
|
||||
if (isNew && !TIME_ALLOW.has(r)) {
|
||||
text.split('\n').forEach((line, i) => {
|
||||
if (/^\s*(\/\/|\*)/.test(line)) return
|
||||
if (/\.toLocale(Date|Time)?String\(/.test(line) && !/timeZone/.test(line)) {
|
||||
errors.push(`${r}:${i + 1}: toLocale…String() without timeZone; use useFormat() (venue time, §7.2)`)
|
||||
}
|
||||
if (/new Intl\.DateTimeFormat\(/.test(line) && !/timeZone/.test(line)) {
|
||||
errors.push(`${r}:${i + 1}: Intl.DateTimeFormat without timeZone; use useFormat() (venue time, §7.2)`)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (!/from ['"](react-i18next|@xenia\/i18n)['"]/.test(text)) continue
|
||||
const defaultNs = text.match(/useTranslation\(\s*['"]([\w-]+)['"]/)?.[1] || 'common'
|
||||
const found = [
|
||||
...[...text.matchAll(/\bt\(\s*(['"])([^'"`$\n]+)\1/g)].map(m => [m[2], m.index]),
|
||||
...[...text.matchAll(/i18nKey=(['"])([^'"]+)\1/g)].map(m => [m[2], m.index]),
|
||||
]
|
||||
for (const [raw, index] of found) {
|
||||
const key = raw.includes(':') ? raw : `${defaultNs}:${raw}`
|
||||
used.add(key)
|
||||
// fallbackNS: a plain key also resolves from common
|
||||
const ok = exists(key) || (!raw.includes(':') && exists(`common:${raw}`))
|
||||
if (!ok) {
|
||||
const line = text.slice(0, index).split('\n').length
|
||||
errors.push(`${r}:${line}: key "${key}" is not in locales/${SOURCE}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Report ───────────────────────────────────────────────────────────────────
|
||||
if (!quiet) for (const w of warnings) console.log(`warning ${w}`)
|
||||
for (const e of errors) console.log(`ERROR ${e}`)
|
||||
const total = Object.keys(keys[SOURCE]).length
|
||||
console.log(`i18n: ${langs.join('/')} · ${total} English keys · ${used.size} used in code · ${errors.length} error(s), ${warnings.length} warning(s)`)
|
||||
process.exit(errors.length ? 1 : 0)
|
||||
Reference in New Issue
Block a user