Files
gabrielvidalandClaude Opus 5.5 961b5929f5 feat(plugins): a plugin's own strings — the i18n contract, and the i18n.read bridge for auto-translate
A plugin's translations now live in that plugin: "i18n": "i18n" in plugin.json
→ i18n/en.json (the English source list, generated by the plugins repo's
scripts/plugin_i18n.py) + i18n/<lang>.json (English → translation).

- plugins/plugin_i18n.py: validation (the folder, en.json an array, each
  <lang>.json an object; every file's language added to `languages`),
  per-language coverage (missing / stale / placeholder mismatches), the bundle.
- GET /api/plugins/i18n/{lang}: every active plugin's dictionary in one ETag'd
  body (a guest: their installs + the managed plugins granted to them).
- Frames: init.i18n + init.locale, aiAgentPlugin.t / tn (English fallback).
- Manifest labels (nav, drawers, header, Files/Projects/Dashboards, settings
  subtitle + fields) through pluginT: plugin dictionary → core t() → English.
- Handlers get AIA_LANGS (the hub's languages); they read their own file.
- /api/plugins/{id}/info|settings carry `i18n` coverage; the plugin page shows
  "Its strings in <language>" rows.
- plugins/hubi18n.py: the owner-only i18n.read bridge (operator approval) —
  translations' and plugins' coverage, files only — for the auto-translate plugin.
- docs/plugins.md ("A plugin's own strings"), CLAUDE.md, i18n README; openapi +
  generated types, authz golden, ui key list regenerated.

Changelog
- Added: plugins can ship their own translations (i18n/<lang>.json), shown per language on their page.
- Added: the i18n.read bridge the auto-translate plugin uses to keep translations complete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:58:08 +01:00

182 lines
6.9 KiB
Python

"""A plugin's own strings in other languages (since 2026-11-28, the
auto-translate plugin): the ``i18n`` manifest field.
A plugin that declares ``"i18n": "i18n"`` keeps, in that folder:
* ``en.json`` — the **English source list**: a JSON array of every string the
plugin passes through its translation helpers (``aiAgentPlugin.t()`` /
``tn()`` in its frames, its handlers' ``t(lang, …)``) plus the manifest's
labels (name, description, pages, settings). Written by the plugins repo's
``scripts/plugin_i18n.py keys`` from the sources, never by hand.
* ``<lang>.json`` — one per language: English text → translation (the same
shape as a translation plugin's dictionaries, ``typed_manifest.load_dictionary``).
What the hub does with them:
* the manifest's ``languages`` is completed with every ``<lang>.json``
present (``manifest.validate_manifest`` → :func:`file_languages`);
* ``GET /api/plugins/i18n/{lang}`` hands the PWA every active plugin's
dictionary in one body (:func:`bundle`): its frames get theirs as
``init.i18n`` (+ ``aiAgentPlugin.t``), and the app translates the plugin's
manifest labels through it before its own ``t()``;
* a handler reads ``$AIA_PLUGIN_DIR/<i18n>/<lang>.json`` itself — its lang is
``AIA_USER_CONTEXT.lang``, the installed ones are ``AIA_LANGS``;
* :func:`coverage` is the per-language missing / stale / placeholder count
shown on the plugin's page and read by the ``i18n.read`` bridge.
Anything missing falls back to the English. A plugin without ``i18n`` keeps
working as it did (its frames still get ``init.lang`` and pick their own
strings).
"""
from __future__ import annotations
import hashlib
import json
import pathlib
import re
import threading
from typing import Any
_LANG_FILE_RE = re.compile(r"^([a-z]{2,3})\.json$")
_VAR_RE = re.compile(r"\{(\w+)\}")
SOURCE = "en.json"
_MAX_KEYS = 5000
_MAX_BYTES = 2 * 1024 * 1024
_lock = threading.Lock()
# path → ((mtime_ns, size), parsed) — dictionaries are read once per change
_cache: dict[str, tuple[tuple[int, int], Any]] = {}
def i18n_dir(rec_or_root: Any, manifest: dict[str, Any] | None = None) -> pathlib.Path | None:
"""The plugin's i18n folder, None when it doesn't declare one."""
if isinstance(rec_or_root, dict):
manifest = rec_or_root.get("manifest") or {}
root = pathlib.Path(rec_or_root.get("dir") or "")
else:
root = pathlib.Path(rec_or_root)
rel = (manifest or {}).get("i18n")
if not rel or not isinstance(rel, str):
return None
root = root.resolve()
d = (root / rel).resolve()
try:
d.relative_to(root)
except ValueError:
return None
return d if d.is_dir() else None
def _read(path: pathlib.Path) -> Any:
try:
st = path.stat()
except OSError:
return None
key = (st.st_mtime_ns, st.st_size)
with _lock:
hit = _cache.get(str(path))
if hit and hit[0] == key:
return hit[1]
if st.st_size > _MAX_BYTES:
data = None
else:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
data = None
with _lock:
_cache[str(path)] = (key, data)
return data
def file_languages(d: pathlib.Path | None) -> list[str]:
"""The languages a plugin has a dictionary file for (never ``en``)."""
if d is None:
return []
out = []
for p in sorted(d.iterdir()):
m = _LANG_FILE_RE.match(p.name)
if m and m.group(1) != "en" and p.is_file():
out.append(m.group(1))
return out
def source_keys(d: pathlib.Path | None) -> list[str]:
"""The English source list (``en.json``), [] when absent or broken."""
if d is None:
return []
data = _read(d / SOURCE)
if not isinstance(data, list):
return []
return [k for k in data[:_MAX_KEYS] if isinstance(k, str) and k]
def dictionary(d: pathlib.Path | None, lang: str | None) -> dict[str, str]:
"""``<lang>.json`` — English → translation; {} for English or none."""
if d is None or not lang or lang == "en" or not re.fullmatch(r"[a-z]{2,3}", lang):
return {}
data = _read(d / f"{lang}.json")
if not isinstance(data, dict):
return {}
return {k: v for k, v in data.items() if isinstance(k, str) and isinstance(v, str) and k}
def validate(root: pathlib.Path, raw: Any, errors: list[str]) -> tuple[str | None, list[str]]:
"""``i18n`` as declared: (the folder, the languages its files speak)."""
if raw is None:
return None, []
if not isinstance(raw, str) or not raw.strip() or raw.startswith("/") or ".." in raw.split("/"):
errors.append("i18n must be a relative folder in the plugin (\"i18n\")")
return None, []
d = i18n_dir(root, {"i18n": raw})
if d is None:
errors.append(f"i18n: folder '{raw}' not found")
return None, []
src = d / SOURCE
data = _read(src)
if not src.is_file() or not isinstance(data, list) or not all(isinstance(k, str) for k in data):
errors.append(f"i18n: {raw}/{SOURCE} must be a JSON array of the English strings")
for lang in file_languages(d):
if not isinstance(_read(d / f"{lang}.json"), dict):
errors.append(f"i18n: {raw}/{lang}.json must be a JSON object (English → translation)")
return raw, file_languages(d)
def _vars(s: str) -> list[str]:
return sorted(_VAR_RE.findall(re.sub(r"^[^|{]*\|", "", s)))
def coverage(rec: dict[str, Any]) -> dict[str, Any] | None:
"""Per language: how many of the plugin's English strings it has, which
are missing (the first 50), the stale entries (their English is gone),
the ones whose ``{placeholders}`` differ. None without ``i18n``."""
d = i18n_dir(rec)
if d is None:
return None
keys = source_keys(d)
wanted = set(keys)
langs: dict[str, Any] = {}
for lang in file_languages(d):
dct = dictionary(d, lang)
missing = [k for k in keys if k not in dct]
langs[lang] = {
"total": len(keys), "translated": len(keys) - len(missing),
"missing": len(missing), "missingSample": missing[:50],
"stale": len([k for k in dct if k not in wanted]),
"staleSample": [k for k in dct if k not in wanted][:50],
"placeholderMismatch": [k for k, v in dct.items() if k in wanted and _vars(k) != _vars(v)][:50],
}
return {"dir": (rec.get("manifest") or {}).get("i18n"), "source": len(keys), "langs": langs}
def bundle(recs: list[dict[str, Any]], lang: str) -> dict[str, Any]:
"""``{lang, plugins: {pid: dict}, etag}`` for these active plugins."""
plugins: dict[str, dict[str, str]] = {}
for rec in recs:
dct = dictionary(i18n_dir(rec), lang)
if dct:
plugins[rec["id"]] = dct
body = json.dumps(plugins, ensure_ascii=False, sort_keys=True).encode()
return {"lang": lang, "plugins": plugins, "etag": hashlib.sha256(body).hexdigest()[:20]}