- Build single-source-of-truth 7-domain locale catalog (`locales/{zh-CN,en-US}/*.json`, 1,100+ keys) and `cmd/i18ngen` generator emitting Go catalogs and eager/lazy-split TypeScript domain modules (`core`/`vm` eager; `wizard`/`settings`/`plugins` lazy)
- Add zero-dependency ICU MessageFormat subset (`{var}`, `{n, number}`, CLDR `plural`, `select`), 8-hop cycle-free regional fallback (`zh-HK/zh-MO -> zh-Hant -> zh-TW -> zh-CN`), `auto` OS display-language preference, and `en-XA` pseudo-localization across Go and TypeScript
- Introduce `CodedError` supportability with `[E_CODE]` badges, collapsible `[detail]` diagnostics, and automatic SMC OSK / SMBIOS serial / MAC / token redaction
- Add Host × Guest macOS dual-terminology annotation (`FormatGuestTerm`) across 6 official Apple guest UI locales and localize Win32 system tray, file pickers, and DPI-adaptive `installguide` overlays with CJK font fallback probing
- Upgrade L1–L4 plugin localization to dual-track v2: Track A full language packs (`files`, WOFF2 `fonts`, cross-plugin `pluginOverrides`), Track B plugin-scoped `l10n` bundles (`HasUIMessages` isolation), live `plugin/localeChanged` notifications, `< 2ms` static CLI pack loading, and `reims-go plugin locale init|check` translator toolchain with `zh-TW` and `ja-JP` reference packs
- Harden security, WCAG 2.1 AA token contrast, `< 768px` responsive drawer & form layouts, and RTL logical properties; add backend security/locale regression tests and frontend `node --test` static/runtime guard suite in CI
# Conflicts:
# frontend/src/i18n.ts
# internal/cli/cli.go
# internal/i18n/i18n.go
468 lines
15 KiB
Go
468 lines
15 KiB
Go
package plugin
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/Nwflower/reims-go/internal/i18n"
|
|
"github.com/Nwflower/reims-go/locales"
|
|
)
|
|
|
|
type localeDomainSpec struct {
|
|
Key string // key in LocaleContribution.Files
|
|
FileName string // filename under locales/<tag>/
|
|
IsUI bool
|
|
IsNative bool
|
|
}
|
|
|
|
var canonicalLocaleDomains = []localeDomainSpec{
|
|
{Key: "core", FileName: "core.json", IsUI: true, IsNative: true},
|
|
{Key: "vm", FileName: "vm.json", IsUI: true},
|
|
{Key: "wizard", FileName: "wizard.json", IsUI: true},
|
|
{Key: "settings", FileName: "settings.json", IsUI: true},
|
|
{Key: "plugins", FileName: "plugins.json", IsUI: true},
|
|
{Key: "native", FileName: "native.json", IsNative: true},
|
|
{Key: "macosGlossary", FileName: "macos-glossary.json", IsUI: true, IsNative: true},
|
|
}
|
|
|
|
// LocaleInitOptions configures scaffolding for `reims-go plugin locale init`.
|
|
type LocaleInitOptions struct {
|
|
Locale string
|
|
OutDir string
|
|
PluginID string
|
|
ForPlugin string
|
|
}
|
|
|
|
// DomainCoverage summarizes translation completeness for a single catalog domain.
|
|
type DomainCoverage struct {
|
|
Domain string `json:"domain"`
|
|
Translated int `json:"translated"`
|
|
Total int `json:"total"`
|
|
Percent float64 `json:"percent"`
|
|
}
|
|
|
|
// LocaleCheckReport summarizes static verification and coverage of a language pack.
|
|
type LocaleCheckReport struct {
|
|
PluginID string `json:"plugin_id"`
|
|
Locale string `json:"locale"`
|
|
Domains []DomainCoverage `json:"domains,omitempty"`
|
|
TotalTranslated int `json:"total_translated"`
|
|
TotalReference int `json:"total_reference"`
|
|
TotalPercent float64 `json:"total_percent"`
|
|
UnknownKeys []string `json:"unknown_keys,omitempty"`
|
|
Findings []DoctorFinding `json:"findings,omitempty"`
|
|
Errors int `json:"errors"`
|
|
Warnings int `json:"warnings"`
|
|
}
|
|
|
|
// InitLocalePack scaffolds a v2 L1 Language Pack directory (or cross-plugin
|
|
// override template when opts.ForPlugin is set) from Reims-Go's embedded catalogs.
|
|
func InitLocalePack(opts LocaleInitOptions) error {
|
|
canon, ok := i18n.ParseLocale(opts.Locale)
|
|
if !ok {
|
|
return fmt.Errorf("invalid BCP-47 locale tag %q (e.g. zh-TW, ja-JP, ko-KR, de-DE)", opts.Locale)
|
|
}
|
|
if strings.TrimSpace(opts.OutDir) == "" {
|
|
return errors.New("output directory (--out) is required")
|
|
}
|
|
if opts.ForPlugin != "" && !reReverseDomainID.MatchString(opts.ForPlugin) {
|
|
return fmt.Errorf("invalid target plugin id %q", opts.ForPlugin)
|
|
}
|
|
|
|
tagLower := strings.ToLower(string(canon))
|
|
pluginID := strings.TrimSpace(opts.PluginID)
|
|
if pluginID == "" {
|
|
if opts.ForPlugin != "" {
|
|
pluginID = fmt.Sprintf("community.lang.%s.%s", strings.ReplaceAll(opts.ForPlugin, ".", "-"), tagLower)
|
|
} else {
|
|
pluginID = "community.lang." + tagLower
|
|
}
|
|
}
|
|
if !reReverseDomainID.MatchString(pluginID) {
|
|
return fmt.Errorf("invalid plugin id %q", pluginID)
|
|
}
|
|
|
|
outDir := filepath.Clean(opts.OutDir)
|
|
if _, err := os.Stat(filepath.Join(outDir, "plugin.json")); err == nil {
|
|
return fmt.Errorf("refusing to overwrite existing plugin.json in %s", outDir)
|
|
}
|
|
if err := os.MkdirAll(outDir, 0o755); err != nil {
|
|
return err
|
|
}
|
|
|
|
fb := i18n.DefaultFallback(canon)
|
|
sourceLocale := "en-US"
|
|
if fb == i18n.ZhCN {
|
|
sourceLocale = "zh-CN"
|
|
}
|
|
|
|
lc := LocaleContribution{
|
|
Locale: string(canon),
|
|
Label: defaultNativeLocaleLabel(string(canon)),
|
|
Fallback: string(fb),
|
|
}
|
|
|
|
if opts.ForPlugin != "" {
|
|
ovDir := filepath.Join(outDir, "overrides")
|
|
if err := os.MkdirAll(ovDir, 0o755); err != nil {
|
|
return err
|
|
}
|
|
manRel := "overrides/" + opts.ForPlugin + ".manifest.json"
|
|
msgRel := "overrides/" + opts.ForPlugin + ".messages.json"
|
|
sampleMan := PluginManifestOverride{
|
|
Name: "",
|
|
Description: "",
|
|
Fields: map[string]string{
|
|
"setting.example.title": "Translated title",
|
|
},
|
|
}
|
|
if err := writeIndentedJSON(filepath.Join(outDir, filepath.FromSlash(manRel)), sampleMan); err != nil {
|
|
return err
|
|
}
|
|
sampleMsg := map[string]any{
|
|
"$comment": "Translate keys from target plugin " + opts.ForPlugin,
|
|
"example": map[string]any{
|
|
"message": "Translated message",
|
|
"$comment": "Replace with keys declared in target plugin locales/",
|
|
},
|
|
}
|
|
if err := writeIndentedJSON(filepath.Join(outDir, filepath.FromSlash(msgRel)), sampleMsg); err != nil {
|
|
return err
|
|
}
|
|
lc.PluginOverrides = map[string]PluginLocaleOverride{
|
|
opts.ForPlugin: {
|
|
ManifestFile: manRel,
|
|
MessagesFile: msgRel,
|
|
},
|
|
}
|
|
} else {
|
|
locDir := filepath.Join(outDir, "locales")
|
|
if err := os.MkdirAll(locDir, 0o755); err != nil {
|
|
return err
|
|
}
|
|
lc.Files = make(map[string]string, len(canonicalLocaleDomains))
|
|
for _, dom := range canonicalLocaleDomains {
|
|
raw, err := locales.FS.ReadFile(sourceLocale + "/" + dom.FileName)
|
|
if err != nil {
|
|
return fmt.Errorf("read embedded template %s/%s: %w", sourceLocale, dom.FileName, err)
|
|
}
|
|
rel := "locales/" + dom.FileName
|
|
if err := os.WriteFile(filepath.Join(outDir, filepath.FromSlash(rel)), raw, 0o644); err != nil {
|
|
return err
|
|
}
|
|
lc.Files[dom.Key] = rel
|
|
}
|
|
}
|
|
|
|
man := Manifest{
|
|
Schema: ManifestSchemaVersion,
|
|
ID: pluginID,
|
|
Version: "0.1.0",
|
|
Name: LocalizedText{
|
|
ZhCN: string(canon) + " 语言包",
|
|
EnUS: string(canon) + " Language Pack",
|
|
Extra: map[string]string{string(canon): lc.Label},
|
|
},
|
|
Description: LocalizedText{
|
|
ZhCN: fmt.Sprintf("为 Reims-Go 提供 %s 界面与命令行本地化支持", lc.Label),
|
|
EnUS: fmt.Sprintf("Provides %s UI and CLI localization for Reims-Go", lc.Label),
|
|
},
|
|
License: "Apache-2.0",
|
|
Engines: Engines{
|
|
PluginAPI: "^1.0.0",
|
|
},
|
|
Contributes: Contributes{
|
|
Locales: []LocaleContribution{lc},
|
|
},
|
|
}
|
|
return writeIndentedJSON(filepath.Join(outDir, "plugin.json"), man)
|
|
}
|
|
|
|
func defaultNativeLocaleLabel(tag string) string {
|
|
switch tag {
|
|
case "zh-CN":
|
|
return "简体中文"
|
|
case "zh-TW":
|
|
return "繁體中文(台灣)"
|
|
case "zh-HK":
|
|
return "繁體中文(香港)"
|
|
case "en-US":
|
|
return "English (US)"
|
|
case "ja-JP":
|
|
return "日本語"
|
|
case "ko-KR":
|
|
return "한국어"
|
|
case "de-DE":
|
|
return "Deutsch"
|
|
case "fr-FR":
|
|
return "Français"
|
|
case "es-ES":
|
|
return "Español"
|
|
case "ru-RU":
|
|
return "Русский"
|
|
default:
|
|
return tag
|
|
}
|
|
}
|
|
|
|
func writeIndentedJSON(dest string, v any) error {
|
|
var buf bytes.Buffer
|
|
enc := json.NewEncoder(&buf)
|
|
enc.SetEscapeHTML(false)
|
|
enc.SetIndent("", " ")
|
|
if err := enc.Encode(v); err != nil {
|
|
return err
|
|
}
|
|
return os.WriteFile(dest, buf.Bytes(), 0o644)
|
|
}
|
|
|
|
type refCatalogEntry struct {
|
|
Domain string
|
|
Vars []string
|
|
}
|
|
|
|
func loadEmbeddedReferenceCatalogs() (map[string]map[string]refCatalogEntry, map[string]refCatalogEntry, error) {
|
|
byDomain := make(map[string]map[string]refCatalogEntry, len(canonicalLocaleDomains))
|
|
all := make(map[string]refCatalogEntry, 1200)
|
|
for _, dom := range canonicalLocaleDomains {
|
|
raw, err := locales.FS.ReadFile("en-US/" + dom.FileName)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
msgs, err := parseLocaleMessagesJSON(raw)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
dmap := make(map[string]refCatalogEntry, len(msgs))
|
|
for k, tpl := range msgs {
|
|
_, vars, _ := i18n.ParseICU(tpl)
|
|
ent := refCatalogEntry{Domain: dom.Key, Vars: vars}
|
|
dmap[k] = ent
|
|
all[k] = ent
|
|
}
|
|
byDomain[dom.Key] = dmap
|
|
}
|
|
return byDomain, all, nil
|
|
}
|
|
|
|
// CheckLocalePack performs static ICU AST validation, placeholder parity checks,
|
|
// domain coverage calculation, stale-key detection, and regional terminology
|
|
// linting (such as Taiwan/HK Traditional Chinese glossary checks) on dir.
|
|
func CheckLocalePack(dir string) ([]LocaleCheckReport, []DoctorFinding, error) {
|
|
raw, err := os.ReadFile(filepath.Join(dir, "plugin.json"))
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("read plugin.json: %w", err)
|
|
}
|
|
var m Manifest
|
|
if err := json.Unmarshal(raw, &m); err != nil {
|
|
return nil, nil, fmt.Errorf("parse plugin.json: %w", err)
|
|
}
|
|
if err := ValidateManifest(m, "", false); err != nil {
|
|
return nil, []DoctorFinding{{Severity: "error", Check: "manifest", Message: err.Error()}}, nil
|
|
}
|
|
|
|
refByDomain, refAll, err := loadEmbeddedReferenceCatalogs()
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
var reports []LocaleCheckReport
|
|
var allFindings []DoctorFinding
|
|
|
|
for _, lc := range m.Contributes.Locales {
|
|
rep := LocaleCheckReport{
|
|
PluginID: m.ID,
|
|
Locale: lc.Locale,
|
|
}
|
|
addFinding := func(sev, check, msg string) {
|
|
f := DoctorFinding{Severity: sev, Check: check, Message: msg}
|
|
rep.Findings = append(rep.Findings, f)
|
|
allFindings = append(allFindings, f)
|
|
switch sev {
|
|
case "error":
|
|
rep.Errors++
|
|
case "warn":
|
|
rep.Warnings++
|
|
}
|
|
}
|
|
|
|
if err := ValidateLocaleContribution(lc, dir); err != nil {
|
|
addFinding("error", "locale", err.Error())
|
|
reports = append(reports, rep)
|
|
continue
|
|
}
|
|
|
|
canon, _ := i18n.ParseLocale(lc.Locale)
|
|
merged := make(map[string]string)
|
|
collectMap := func(src map[string]string, sourceLabel string) {
|
|
keys := make([]string, 0, len(src))
|
|
for k := range src {
|
|
keys = append(keys, k)
|
|
}
|
|
sort.Strings(keys)
|
|
for _, k := range keys {
|
|
v := src[k]
|
|
merged[k] = v
|
|
_, gotVars, pErr := i18n.ParseICU(v)
|
|
if pErr != nil {
|
|
addFinding("error", "icu-syntax", fmt.Sprintf("[%s] %s key %q: %v", canon, sourceLabel, k, pErr))
|
|
continue
|
|
}
|
|
if ref, exists := refAll[k]; exists {
|
|
if !reflect.DeepEqual(gotVars, ref.Vars) {
|
|
addFinding("error", "icu-params", fmt.Sprintf("[%s] %s key %q placeholder mismatch: got %v, expected %v", canon, sourceLabel, k, gotVars, ref.Vars))
|
|
}
|
|
}
|
|
for _, hint := range lintRegionalTerminology(canon, k, v) {
|
|
addFinding("warn", "l10n-regional", fmt.Sprintf("[%s] %s key %q: %s", canon, sourceLabel, k, hint))
|
|
}
|
|
}
|
|
}
|
|
|
|
if strings.TrimSpace(lc.File) != "" {
|
|
if loaded, err := loadLocaleJSONFile(dir, lc.File); err == nil {
|
|
collectMap(loaded, lc.File)
|
|
}
|
|
}
|
|
if strings.TrimSpace(lc.BackendFile) != "" {
|
|
if loaded, err := loadLocaleJSONFile(dir, lc.BackendFile); err == nil {
|
|
collectMap(loaded, lc.BackendFile)
|
|
}
|
|
}
|
|
for _, dom := range canonicalLocaleDomains {
|
|
rel := strings.TrimSpace(lc.Files[dom.Key])
|
|
if rel == "" && dom.Key == "macosGlossary" {
|
|
rel = strings.TrimSpace(lc.Files["macos-glossary"])
|
|
}
|
|
if rel != "" {
|
|
if loaded, err := loadLocaleJSONFile(dir, rel); err == nil {
|
|
collectMap(loaded, rel)
|
|
}
|
|
}
|
|
}
|
|
collectMap(lc.Messages, "messages")
|
|
collectMap(lc.Backend, "backend")
|
|
|
|
// Check cross-plugin override terminology as well.
|
|
for targetID, ov := range lc.PluginOverrides {
|
|
if strings.TrimSpace(ov.MessagesFile) != "" {
|
|
if loaded, err := loadLocaleJSONFile(dir, ov.MessagesFile); err == nil {
|
|
for k, v := range loaded {
|
|
for _, hint := range lintRegionalTerminology(canon, k, v) {
|
|
addFinding("warn", "l10n-regional", fmt.Sprintf("[%s] override %s key %q: %s", canon, targetID, k, hint))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
for k, v := range ov.Messages {
|
|
for _, hint := range lintRegionalTerminology(canon, k, v) {
|
|
addFinding("warn", "l10n-regional", fmt.Sprintf("[%s] override %s key %q: %s", canon, targetID, k, hint))
|
|
}
|
|
}
|
|
if ov.Manifest != nil {
|
|
for _, hint := range lintRegionalTerminology(canon, "manifest.name", ov.Manifest.Name) {
|
|
addFinding("warn", "l10n-regional", fmt.Sprintf("[%s] override %s manifest.name: %s", canon, targetID, hint))
|
|
}
|
|
for _, hint := range lintRegionalTerminology(canon, "manifest.description", ov.Manifest.Description) {
|
|
addFinding("warn", "l10n-regional", fmt.Sprintf("[%s] override %s manifest.description: %s", canon, targetID, hint))
|
|
}
|
|
}
|
|
}
|
|
|
|
// Compute domain-by-domain coverage when host keys are present or files are declared.
|
|
hasHostKeys := len(merged) > 0 || len(lc.Files) > 0 || lc.File != "" || lc.BackendFile != ""
|
|
if hasHostKeys {
|
|
for _, dom := range canonicalLocaleDomains {
|
|
dref := refByDomain[dom.Key]
|
|
total := len(dref)
|
|
translated := 0
|
|
for k := range dref {
|
|
if strings.TrimSpace(merged[k]) != "" {
|
|
translated++
|
|
}
|
|
}
|
|
pct := 0.0
|
|
if total > 0 {
|
|
pct = float64(translated) * 100.0 / float64(total)
|
|
}
|
|
rep.Domains = append(rep.Domains, DomainCoverage{
|
|
Domain: dom.Key,
|
|
Translated: translated,
|
|
Total: total,
|
|
Percent: pct,
|
|
})
|
|
rep.TotalTranslated += translated
|
|
rep.TotalReference += total
|
|
}
|
|
if rep.TotalReference > 0 {
|
|
rep.TotalPercent = float64(rep.TotalTranslated) * 100.0 / float64(rep.TotalReference)
|
|
}
|
|
|
|
for k := range merged {
|
|
if _, ok := refAll[k]; !ok {
|
|
rep.UnknownKeys = append(rep.UnknownKeys, k)
|
|
}
|
|
}
|
|
sort.Strings(rep.UnknownKeys)
|
|
if len(rep.UnknownKeys) > 0 {
|
|
sample := rep.UnknownKeys
|
|
if len(sample) > 5 {
|
|
sample = sample[:5]
|
|
}
|
|
addFinding("warn", "locale-stale", fmt.Sprintf("[%s] %d unknown/stale host key(s) (e.g. %s)", canon, len(rep.UnknownKeys), strings.Join(sample, ", ")))
|
|
}
|
|
addFinding("ok", "locale-coverage", fmt.Sprintf("[%s] coverage %d/%d (%.1f%%)", canon, rep.TotalTranslated, rep.TotalReference, rep.TotalPercent))
|
|
}
|
|
|
|
reports = append(reports, rep)
|
|
}
|
|
|
|
return reports, allFindings, nil
|
|
}
|
|
|
|
type regionalLintRule struct {
|
|
Bad string
|
|
Suggestion string
|
|
}
|
|
|
|
var zhHantLintRules = []regionalLintRule{
|
|
{Bad: "默认", Suggestion: "use Traditional regional term 「預設」 instead of 「默认」"},
|
|
{Bad: "默認", Suggestion: "use Traditional regional term 「預設」 instead of Mainland literal 「默認」"},
|
|
{Bad: "内存", Suggestion: "use Traditional regional term 「記憶體」 instead of 「内存」"},
|
|
{Bad: "內存", Suggestion: "use Traditional regional term 「記憶體」 instead of Mainland literal 「內存」"},
|
|
{Bad: "磁盘", Suggestion: "use Traditional regional term 「磁碟」 instead of 「磁盘」"},
|
|
{Bad: "磁盤", Suggestion: "use Traditional regional term 「磁碟」 instead of Mainland literal 「磁盤」"},
|
|
{Bad: "抹掉", Suggestion: "use Apple Traditional macOS term 「清除」 instead of 「抹掉」"},
|
|
{Bad: "宗卷", Suggestion: "use Apple Traditional macOS term 「卷宗」 instead of 「宗卷」"},
|
|
{Bad: "剪贴板", Suggestion: "use Traditional regional term 「剪貼簿」 instead of 「剪贴板」"},
|
|
{Bad: "剪貼板", Suggestion: "use Traditional regional term 「剪貼簿」 instead of Mainland literal 「剪貼板」"},
|
|
{Bad: "鼠标", Suggestion: "use Traditional regional term 「滑鼠」 instead of 「鼠标」"},
|
|
{Bad: "鼠標", Suggestion: "use Traditional regional term 「滑鼠」 instead of Mainland literal 「鼠標」"},
|
|
}
|
|
|
|
func lintRegionalTerminology(canon i18n.Locale, _ string, val string) []string {
|
|
if val == "" {
|
|
return nil
|
|
}
|
|
var hints []string
|
|
switch canon {
|
|
case "zh-TW", "zh-HK":
|
|
for _, rule := range zhHantLintRules {
|
|
if strings.Contains(val, rule.Bad) {
|
|
hints = append(hints, rule.Suggestion)
|
|
}
|
|
}
|
|
if strings.ContainsAny(val, "“”") {
|
|
hints = append(hints, "prefer CJK corner brackets 「…」 over curly quotes “…” in Traditional Chinese UI")
|
|
}
|
|
}
|
|
return hints
|
|
}
|