@juicesharp/rpiv-i18n 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 juicesharp
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,317 @@
1
+ # @juicesharp/rpiv-i18n
2
+
3
+ i18n/localization SDK for Pi extensions. Pick a UI language interactively or via flag; localize your own Pi extension with a few lines of code.
4
+
5
+ ## Features
6
+
7
+ - **One shared locale dial** for every Pi extension that adopts the SDK — `/languages` switches them all at once.
8
+ - **`/languages` slash command** with an interactive picker; persists the choice to `~/.config/rpiv-i18n/locale.json` (chmod `0600`) and reports a clear error if disk persistence fails.
9
+ - **`--locale <code>` CLI flag** for one-shot or scripted launches.
10
+ - **Auto-detects** `process.env.LANG` / `LC_ALL` so most Unix users get a localized UI without configuration.
11
+ - **Tiny SDK surface for authors** — `registerStrings(namespace, byLocale)`, `scope(namespace)`, `tr(namespace, key, fallback)`. Render-time lookups, English fallback per missing key, no module-init baking.
12
+ - **Ships picker entries for** German, English, Spanish, French, Portuguese (European), Portuguese (Brazilian), Russian, and Ukrainian — alphabetical by locale code (consumers contribute their own translation maps; the SDK ships infrastructure, not strings).
13
+ - **Live propagation** — locale changes via `/languages` apply to the next render with no restart, even when the SDK is loaded as multiple module instances.
14
+ - **Always-safe fallback** — if the SDK isn't installed at all, every `tr(...)` call returns the consumer's literal English fallback. Extensions stay usable.
15
+ - **Zero-import escape hatch** — `globalThis[Symbol.for("rpiv-i18n")]` exposes a frozen `{ locale, namespaces }` snapshot for tools that prefer not to depend on this package.
16
+
17
+ ## For users
18
+
19
+ Install the extension (auto-wired by `/rpiv-setup`), then choose a language:
20
+
21
+ ```
22
+ /languages
23
+ ```
24
+
25
+ Or pass a flag at startup:
26
+
27
+ ```bash
28
+ pi --locale uk
29
+ ```
30
+
31
+ Or edit the config file directly:
32
+
33
+ ```bash
34
+ echo '{"locale":"uk"}' > ~/.config/rpiv-i18n/locale.json
35
+ ```
36
+
37
+ Locale detection priority: `--locale` flag → `~/.config/rpiv-i18n/locale.json` → `process.env.LANG` / `LC_ALL` → English default.
38
+
39
+ Other Pi extensions that integrate the SDK pick up your choice automatically.
40
+
41
+ ## For Pi extension authors
42
+
43
+ The SDK gives every Pi extension a single shared locale dial. Register your translations once, then look them up at render time.
44
+
45
+ ### Register strings at extension load
46
+
47
+ ```ts
48
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
49
+ import { registerStrings, scope } from "@juicesharp/rpiv-i18n";
50
+
51
+ const NAMESPACE = "@my-org/cool-tool";
52
+
53
+ registerStrings(NAMESPACE, {
54
+ en: {
55
+ "welcome": "Welcome!",
56
+ "submit": "Submit",
57
+ },
58
+ uk: {
59
+ "welcome": "Ласкаво просимо!",
60
+ "submit": "Надіслати",
61
+ },
62
+ });
63
+
64
+ const t = scope(NAMESPACE);
65
+
66
+ export default function (pi: ExtensionAPI) {
67
+ pi.registerCommand("hello", {
68
+ handler: async (_args, ctx) => {
69
+ ctx.ui.notify(t("welcome", "Welcome!"));
70
+ },
71
+ });
72
+ }
73
+ ```
74
+
75
+ ### API
76
+
77
+ | Function | Purpose |
78
+ |---|---|
79
+ | `registerStrings(namespace, byLocale)` | Register a package's translation maps. The namespace SHOULD be your npm package name. Re-calling replaces the prior registration. |
80
+ | `scope(namespace)` | Returns a pre-bound `(key, fallback) => string` closure. |
81
+ | `tr(namespace, key, fallback)` | One-shot lookup. Returns `fallback` when the namespace or key isn't registered. |
82
+ | `getActiveLocale()` | Current locale code, or `undefined` for the English default. |
83
+ | `applyLocale(code)` | Set the active locale; rebuilds the active strings across all registered namespaces. |
84
+
85
+ ### Behavior contract
86
+
87
+ - **English fallback per key.** If a key exists in `en` but not in the active locale's map, the English entry is returned. Missing-only-in-current-locale strings stay readable.
88
+ - **Always-safe fallback.** If neither this SDK nor your namespace is loaded, every `tr(...)` call returns its `fallback` literal — your extension keeps working.
89
+ - **Live locale changes.** When the user runs `/languages`, the next `tr(...)` call returns the new locale's string. No restart required.
90
+ - **Render-time only.** Call `tr(...)` at render time — never bake the result into a top-level `const X = tr(...)`. Module-init evaluation freezes the string before the user has a chance to set their locale.
91
+
92
+ ## Localizing your extension — step by step
93
+
94
+ The inline example above is fine for a one-key smoke test. For a real Pi extension, use the file-based pattern that scales to dozens of strings and ten contributors. Same shape proven in production.
95
+
96
+ ### 1. Author a `locales/en.json` next to your source
97
+
98
+ ```json
99
+ {
100
+ "_meta.notes": "English baseline. Any new key MUST land here first; other locales fall back to it.",
101
+
102
+ "welcome.title": "Welcome",
103
+ "submit.button": "Submit",
104
+ "hint.cancel": "Esc to cancel"
105
+ }
106
+ ```
107
+
108
+ Conventions: flat dotted lowercase keys, `snake_case` only for multi-word leaves (`hint.cancel` ✓, `hint.cancelKey` ✗). `_meta.*` keys are ignored at lookup time — use them for provenance / WIP notes.
109
+
110
+ ### 2. Add a one-file bridge inside your package
111
+
112
+ `state/i18n-bridge.ts` (or wherever your package keeps cross-cutting helpers):
113
+
114
+ ```ts
115
+ import { scope } from "@juicesharp/rpiv-i18n";
116
+
117
+ export const I18N_NAMESPACE = "@my-org/cool-tool";
118
+
119
+ export const t = scope(I18N_NAMESPACE);
120
+ ```
121
+
122
+ Every render-time call site imports `t` from this one file. If you ever switch namespaces, change the SDK, or add a `displayLabel(kind)` convenience for sentinel-row enums, you touch one place.
123
+
124
+ ### 3. Register strings at extension load
125
+
126
+ ```ts
127
+ import { readFileSync } from "node:fs";
128
+ import { fileURLToPath } from "node:url";
129
+ import { registerStrings, type TranslationMap } from "@juicesharp/rpiv-i18n";
130
+ import { I18N_NAMESPACE } from "./state/i18n-bridge.js";
131
+
132
+ function loadLocale(code: string): TranslationMap {
133
+ // A missing/malformed locale file MUST NOT crash module init — the bridge's
134
+ // literal English fallbacks will keep every render readable.
135
+ try {
136
+ return JSON.parse(
137
+ readFileSync(fileURLToPath(new URL(`./locales/${code}.json`, import.meta.url)), "utf-8"),
138
+ ) as TranslationMap;
139
+ } catch (err) {
140
+ console.warn(`@my-org/cool-tool: failed to load locales/${code}.json (${(err as Error).message})`);
141
+ return {};
142
+ }
143
+ }
144
+
145
+ registerStrings(I18N_NAMESPACE, {
146
+ en: loadLocale("en"),
147
+ // Add more as files arrive. Order doesn't matter; keys missing from a non-en
148
+ // map fall back to en automatically.
149
+ });
150
+
151
+ export default function (pi /* : ExtensionAPI */) {
152
+ // your tool/command/hook registrations here…
153
+ }
154
+ ```
155
+
156
+ `registerStrings` runs at module top-level, before Pi calls your default export. That timing is intentional — by the time the first `tr(...)` fires, every locale map is in the registry.
157
+
158
+ ### 4. Use `t(key, fallback)` at the render call site
159
+
160
+ ```ts
161
+ import { t } from "../state/i18n-bridge.js";
162
+
163
+ // ✓ Render-time — re-evaluated each render; live `/languages` switches apply
164
+ function renderHeader(theme) {
165
+ return new Text(theme.bold(t("welcome.title", "Welcome")));
166
+ }
167
+
168
+ // ✗ Module-init — captured ONCE, freezes English on first load
169
+ const HEADING = t("welcome.title", "Welcome");
170
+ ```
171
+
172
+ The fallback string is the canonical English literal — same one you put in `en.json`. Keep it inline at the call site so the file reads end-to-end without locale lookups, and so your extension stays usable when the SDK isn't installed at all.
173
+
174
+ ### 5. Ship the locale files in `package.json`
175
+
176
+ ```json
177
+ {
178
+ "files": [
179
+ "index.ts",
180
+ "state/i18n-bridge.ts",
181
+ "locales/",
182
+ "…"
183
+ ]
184
+ }
185
+ ```
186
+
187
+ The `files[]` manifest is the #1 publish-time miss in this monorepo's history. Ship it in the same commit as the locale JSONs.
188
+
189
+ ### What stays English (do NOT route through `t(...)`)
190
+
191
+ - Tool descriptions, TypeBox `description` fields, prompt guidelines / snippets — these go to the LLM. Localizing them risks the model emitting localized option labels that bypass your `RESERVED_LABEL_SET` validation.
192
+ - Validation errors that flow back through `tool result` envelopes — same reason.
193
+ - Anything checked by exact-string matching (reserved labels, dispatcher discriminants) — keep both sides in canonical English.
194
+
195
+ The recommended pattern is to keep a top-level `const X = "literal"` for the canonical English (so reserved-label checks and tests stay stable), then route the **render call site** through `t("key", X)`. The SDK never sees `X`; the LLM never sees `t(...)`.
196
+
197
+ ### Optional: per-namespace `displayLabel` helper
198
+
199
+ If your extension has a small enum-typed set of "kind" rows (sentinels, statuses, modes), a one-line helper keeps render code tight:
200
+
201
+ ```ts
202
+ // state/i18n-bridge.ts
203
+ import { ROW_INTENT_META, type SentinelKind } from "./row-intent.js";
204
+
205
+ export function displayLabel(kind: SentinelKind): string {
206
+ return t(`sentinel.${kind}`, ROW_INTENT_META[kind].label);
207
+ }
208
+ ```
209
+
210
+ Render code becomes `displayLabel("next")` instead of `t("sentinel.next", "Next")` — same lookup, but the canonical English fallback is sourced from the same metadata table the rest of your code uses. One source of truth per kind.
211
+
212
+ ### Optional: a non-English locale file
213
+
214
+ Add `locales/uk.json` mirroring the en key set:
215
+
216
+ ```json
217
+ {
218
+ "_meta.notes": "Auto-translated draft. Native review welcome.",
219
+
220
+ "welcome.title": "Ласкаво просимо",
221
+ "submit.button": "Надіслати",
222
+ "hint.cancel": "Esc — скасувати"
223
+ }
224
+ ```
225
+
226
+ Wire it into `registerStrings({ en: …, uk: loadLocale("uk") })`. To make the locale show up in the `/languages` picker, add `{ code: "uk", label: "Українська" }` to `SUPPORTED_LOCALES` in this package's `i18n.ts` (open a PR, or file an issue if your extension lives outside this repo).
227
+
228
+ Done. `/languages` now switches your extension's UI alongside every other extension that adopts the SDK.
229
+
230
+ ## Contributing translations
231
+
232
+ Want to add or improve a translation for a Pi extension that uses this SDK? Open a PR — the contract is small and uniform across packages.
233
+
234
+ ### What to translate (and what NOT to)
235
+
236
+ **Translate**: every key listed in the package's `locales/en.json`. These are TUI-facing strings — labels, hints, prompts, headings — read by humans on screen.
237
+
238
+ **Do NOT translate**:
239
+ - Tool descriptions, TypeBox `description` fields, prompt guidelines, prompt snippets — they go to the LLM and stay English so the model parses them deterministically across sessions and providers.
240
+ - Validation errors that flow through `tool result` envelopes (e.g. `"Error: UI not available …"`) — same reason.
241
+ - `RESERVED_LABELS` and any keys checked by reserved-label validation — translating these lets a localized equivalent slip past the duplicate-detection guard.
242
+
243
+ If a key isn't in the package's `locales/en.json`, it's intentionally English-only. Don't invent new keys; open an issue first if you think a string should be made localizable.
244
+
245
+ ### File location and naming
246
+
247
+ - One JSON file per locale, named `<code>.json` (e.g. `es.json`, `fr.json`, `pt-BR.json`), inside the consumer package's `locales/` directory.
248
+ - Locale codes follow BCP-47-ish convention: language only (`es`, `fr`, `de`) or `language-Region` for variants (`pt-BR`, `zh-CN`). Keep hyphenated, not underscored.
249
+ - Mirror the exact key set from `en.json`. Missing keys fall back to English silently — that's fine, but the `_meta.notes` field below should mention the gap.
250
+
251
+ ### Key naming convention
252
+
253
+ Flat dotted lowercase: `sentinel.next`, `submit.cancel`, `preview.no_preview`. Use `snake_case` only for multi-word leaves (`preview.no_preview`, never `preview.noPreview` or `preview.no-preview`). Mixing conventions inside one file is a rejection criterion.
254
+
255
+ ### File shape
256
+
257
+ ```json
258
+ {
259
+ "_meta.notes": "Optional contributor note — auto-translated, native review welcome, key gaps, etc.",
260
+
261
+ "<dotted.key.from.en.json>": "Localized string"
262
+ }
263
+ ```
264
+
265
+ `_meta.*` keys are ignored by `tr(...)` lookups (no consumer requests them). Use them for provenance, change notes, or "WIP — N keys missing".
266
+
267
+ ### Universal CLI conventions (do NOT translate)
268
+
269
+ - Symbols: `↑/↓`, `⚠`, `✓` — render the same in every locale.
270
+ - Keyboard names: `Enter`, `Esc`, `Tab`, `Space` — these are the labels printed on physical keyboards worldwide. Some locales (e.g. French) write `Entrée` / `Échap`; that's acceptable when paired with the convention you're targeting (KDE/GNOME do this), but be consistent across the file.
271
+ - Single-key shortcut letters (`n` to add notes): keep the letter unchanged — it maps to a literal keystroke handler, not to a label.
272
+
273
+ ### Registering the locale
274
+
275
+ After dropping the JSON file, the consumer package's `index.ts` (or wherever it calls `registerStrings`) needs the new entry:
276
+
277
+ ```ts
278
+ registerStrings(I18N_NAMESPACE, {
279
+ en: loadLocale("en"),
280
+ es: loadLocale("es"),
281
+ fr: loadLocale("fr"),
282
+ "pt-BR": loadLocale("pt-BR"),
283
+ });
284
+ ```
285
+
286
+ Add the locale to the `/languages` picker by appending an entry to `SUPPORTED_LOCALES` in `packages/rpiv-i18n/i18n.ts`:
287
+
288
+ ```ts
289
+ { code: "fr", label: "Français" },
290
+ ```
291
+
292
+ The `label` is the locale's endonym (the language's name in itself), not its English name.
293
+
294
+ ### Submitting a PR
295
+
296
+ Include:
297
+ 1. The new `locales/<code>.json` file.
298
+ 2. The `registerStrings(...)` update in the consumer's entry point.
299
+ 3. The `SUPPORTED_LOCALES` entry in `rpiv-i18n/i18n.ts`.
300
+ 4. Run `npm run check && npm test` from the monorepo root — both must pass.
301
+
302
+ A native-speaker reviewer will land it. Auto-translated drafts are accepted (mark them in `_meta.notes`); English fallbacks make any gap or error invisible to users until a fix arrives.
303
+
304
+ ## globalThis introspection (escape hatch)
305
+
306
+ For tools that prefer not to import this package, the active state is also published at `globalThis[Symbol.for("rpiv-i18n")]`:
307
+
308
+ ```ts
309
+ const I18N = Symbol.for("rpiv-i18n");
310
+ const state = (globalThis as any)[I18N] as
311
+ | { locale: string | undefined; namespaces: Record<string, Record<string, string>> }
312
+ | undefined;
313
+
314
+ const value = state?.namespaces["@my-org/cool-tool"]?.["welcome"] ?? "Welcome!";
315
+ ```
316
+
317
+ This is read-only; registration MUST go through `registerStrings(...)`.
package/i18n-ui.ts ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * i18n-ui — bordered select-panel for the /languages command.
3
+ *
4
+ * Mirrors advisor-ui.ts:showAdvisorPicker — bordered container with title,
5
+ * prose, SelectList, nav hint. Single public function (showLanguagePicker);
6
+ * private buildSelectPanel owns the layout + theme wiring.
7
+ */
8
+
9
+ import { DynamicBorder, type ExtensionContext, type Theme } from "@mariozechner/pi-coding-agent";
10
+ import { Container, type SelectItem, SelectList, Spacer, Text } from "@mariozechner/pi-tui";
11
+
12
+ const MAX_VISIBLE_ROWS = 10;
13
+ const NAV_HINT = "↑↓ navigate • enter select • esc cancel";
14
+
15
+ const HEADER_TITLE = "UI Language";
16
+ const HEADER_PROSE =
17
+ "Choose the locale used for rpiv-* TUI strings (sentinel rows, hints, " +
18
+ "submit labels, preview text). LLM-facing copy stays English. Selection " +
19
+ "persists at ~/.config/rpiv-i18n/locale.json.";
20
+
21
+ function selectListTheme(theme: Theme) {
22
+ return {
23
+ selectedPrefix: (t: string) => theme.bg("selectedBg", theme.fg("accent", t)),
24
+ selectedText: (t: string) => theme.bg("selectedBg", theme.bold(t)),
25
+ description: (t: string) => theme.fg("muted", t),
26
+ scrollInfo: (t: string) => theme.fg("dim", t),
27
+ noMatch: (t: string) => theme.fg("warning", t),
28
+ };
29
+ }
30
+
31
+ function buildSelectPanel(theme: Theme, title: string, proseLines: string[], selectList: SelectList): Container {
32
+ const container = new Container();
33
+ const border = () => new DynamicBorder((s: string) => theme.fg("accent", s));
34
+
35
+ container.addChild(border());
36
+ container.addChild(new Spacer(1));
37
+ container.addChild(new Text(theme.fg("accent", theme.bold(title)), 1, 0));
38
+ container.addChild(new Spacer(1));
39
+ for (const line of proseLines) {
40
+ container.addChild(new Text(line, 1, 0));
41
+ container.addChild(new Spacer(1));
42
+ }
43
+ container.addChild(selectList);
44
+ container.addChild(new Spacer(1));
45
+ container.addChild(new Text(theme.fg("dim", NAV_HINT), 1, 0));
46
+ container.addChild(new Spacer(1));
47
+ container.addChild(border());
48
+ return container;
49
+ }
50
+
51
+ export async function showLanguagePicker(ctx: ExtensionContext, items: SelectItem[]): Promise<string | null> {
52
+ return ctx.ui.custom<string | null>((tui, theme, _kb, done) => {
53
+ const selectList = new SelectList(items, Math.min(items.length, MAX_VISIBLE_ROWS), selectListTheme(theme));
54
+ selectList.onSelect = (item) => done(item.value);
55
+ selectList.onCancel = () => done(null);
56
+
57
+ const container = buildSelectPanel(theme, HEADER_TITLE, [HEADER_PROSE], selectList);
58
+
59
+ return {
60
+ render: (w) => container.render(w),
61
+ invalidate: () => container.invalidate(),
62
+ handleInput: (data) => {
63
+ selectList.handleInput(data);
64
+ tui.requestRender();
65
+ },
66
+ };
67
+ });
68
+ }
package/i18n.ts ADDED
@@ -0,0 +1,258 @@
1
+ /**
2
+ * i18n/localization SDK for Pi extensions.
3
+ *
4
+ * Public surface for consumers (rpiv-* family or third-party Pi extensions):
5
+ * - `registerStrings(namespace, byLocale)` — register a package's translation maps
6
+ * - `tr(namespace, key, fallback)` / `scope(namespace)` — render-time lookup
7
+ * - `getActiveLocale()` — current locale code (undefined = English default)
8
+ * - `applyLocale(code)` — change locale; rebuilds active strings across all namespaces
9
+ *
10
+ * Locale detection priority (resolved in index.ts):
11
+ * 1. --locale CLI flag
12
+ * 2. ~/.config/rpiv-i18n/locale.json
13
+ * 3. process.env.LANG / LC_ALL (Unix convention)
14
+ * 4. English default (locale === undefined)
15
+ *
16
+ * A flattened, read-only snapshot is also published at
17
+ * `globalThis[Symbol.for("rpiv-i18n")]` as `{ locale, namespaces }` for
18
+ * introspection and zero-import escape hatches.
19
+ *
20
+ * Config persists at ~/.config/rpiv-i18n/locale.json (chmod 0o600, best-effort writes).
21
+ */
22
+
23
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
24
+ import { homedir } from "node:os";
25
+ import { dirname, join } from "node:path";
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // Types
29
+ // ---------------------------------------------------------------------------
30
+
31
+ export type TranslationMap = Readonly<Record<string, string>>;
32
+ export type LocaleStrings = Readonly<Record<string, TranslationMap>>;
33
+
34
+ export interface I18nState {
35
+ readonly locale: string | undefined;
36
+ readonly namespaces: Readonly<Record<string, TranslationMap>>;
37
+ }
38
+
39
+ export interface LocaleConfig {
40
+ locale?: string;
41
+ }
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // Constants
45
+ // ---------------------------------------------------------------------------
46
+
47
+ export const I18N_STATE_KEY = Symbol.for("rpiv-i18n");
48
+ const I18N_RUNTIME_KEY = Symbol.for("rpiv-i18n.runtime");
49
+
50
+ const CONFIG_DIR = join(homedir(), ".config", "rpiv-i18n");
51
+ const LOCALE_CONFIG_PATH = join(CONFIG_DIR, "locale.json");
52
+ const CONFIG_FILE_MODE = 0o600;
53
+ const DEFAULT_FALLBACK_LOCALE = "en";
54
+
55
+ // Supported locales — alphabetical by code (so the /languages picker stays
56
+ // in deterministic order regardless of how entries are appended). Labels
57
+ // are endonyms (the language's name in itself), not English names.
58
+ // Third-party extensions opt in to additional locales by calling
59
+ // registerStrings with the matching code keys; this list drives only the
60
+ // /languages picker UI.
61
+ export const SUPPORTED_LOCALES: readonly { code: string; label: string }[] = [
62
+ { code: "de", label: "Deutsch" },
63
+ { code: DEFAULT_FALLBACK_LOCALE, label: "English" },
64
+ { code: "es", label: "Español" },
65
+ { code: "fr", label: "Français" },
66
+ { code: "pt", label: "Português" },
67
+ { code: "pt-BR", label: "Português (Brasil)" },
68
+ { code: "ru", label: "Русский" },
69
+ { code: "uk", label: "Українська" },
70
+ ];
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // Translation registry — Map<namespace, Map<locale, strings>>.
74
+ //
75
+ // All SDK state is anchored on globalThis under `Symbol.for("rpiv-i18n.runtime")`
76
+ // so live locale changes via `/languages` propagate even when this module is
77
+ // loaded as multiple instances (e.g. once via Pi's extension entry, once via
78
+ // a consumer's `node_modules/@juicesharp/rpiv-i18n` import — Pi's TS loader
79
+ // caches them under different paths and each `import { tr }` would otherwise
80
+ // see its own private copy of `activeStrings`).
81
+ //
82
+ // The public read-only snapshot under `Symbol.for("rpiv-i18n")` is kept as a
83
+ // frozen plain-data view for zero-import consumers.
84
+ // ---------------------------------------------------------------------------
85
+
86
+ interface I18nRuntime {
87
+ registry: Map<string, Map<string, TranslationMap>>;
88
+ activeLocale: string | undefined;
89
+ activeStrings: Map<string, TranslationMap>;
90
+ }
91
+
92
+ function getRuntime(): I18nRuntime {
93
+ const g = globalThis as unknown as { [k: symbol]: I18nRuntime | undefined };
94
+ let rt = g[I18N_RUNTIME_KEY];
95
+ if (!rt) {
96
+ rt = { registry: new Map(), activeLocale: undefined, activeStrings: new Map() };
97
+ g[I18N_RUNTIME_KEY] = rt;
98
+ }
99
+ return rt;
100
+ }
101
+
102
+ function pickStringsForLocale(byLocale: Map<string, TranslationMap>, locale: string | undefined): TranslationMap {
103
+ if (locale && locale !== DEFAULT_FALLBACK_LOCALE) {
104
+ const overlay = byLocale.get(locale);
105
+ const base = byLocale.get(DEFAULT_FALLBACK_LOCALE) ?? {};
106
+ if (overlay) return Object.freeze({ ...base, ...overlay });
107
+ return base;
108
+ }
109
+ return byLocale.get(DEFAULT_FALLBACK_LOCALE) ?? {};
110
+ }
111
+
112
+ function rebuildActive(): void {
113
+ const rt = getRuntime();
114
+ rt.activeStrings.clear();
115
+ for (const [namespace, byLocale] of rt.registry) {
116
+ rt.activeStrings.set(namespace, pickStringsForLocale(byLocale, rt.activeLocale));
117
+ }
118
+ writeRegistry();
119
+ }
120
+
121
+ function snapshotForGlobal(): Readonly<Record<string, TranslationMap>> {
122
+ const snapshot: Record<string, TranslationMap> = {};
123
+ for (const [namespace, strings] of getRuntime().activeStrings) {
124
+ snapshot[namespace] = strings;
125
+ }
126
+ return Object.freeze(snapshot);
127
+ }
128
+
129
+ function writeRegistry(): void {
130
+ const state: I18nState = Object.freeze({
131
+ locale: getRuntime().activeLocale,
132
+ namespaces: snapshotForGlobal(),
133
+ });
134
+ (globalThis as unknown as { [k: symbol]: I18nState })[I18N_STATE_KEY] = state;
135
+ }
136
+
137
+ // ---------------------------------------------------------------------------
138
+ // Public registration + lookup API
139
+ // ---------------------------------------------------------------------------
140
+
141
+ /**
142
+ * Register translation strings for a Pi extension. Consumers call this once
143
+ * at extension load (typically inside their default-exported wiring function).
144
+ * The namespace SHOULD be the npm package name to avoid collisions.
145
+ *
146
+ * Re-calling with the same namespace replaces the prior registration.
147
+ */
148
+ export function registerStrings(namespace: string, byLocale: LocaleStrings): void {
149
+ const map = new Map<string, TranslationMap>();
150
+ for (const [code, strings] of Object.entries(byLocale)) {
151
+ map.set(code, Object.freeze({ ...strings }));
152
+ }
153
+ getRuntime().registry.set(namespace, map);
154
+ rebuildActive();
155
+ }
156
+
157
+ /** Render-time translation lookup. Returns `fallback` when no entry exists. */
158
+ export function tr(namespace: string, key: string, fallback: string): string {
159
+ const strings = getRuntime().activeStrings.get(namespace);
160
+ if (!strings) return fallback;
161
+ const value = strings[key];
162
+ return typeof value === "string" && value.length > 0 ? value : fallback;
163
+ }
164
+
165
+ /** Bind a namespace once; returns a `(key, fallback) => string` closure. */
166
+ export function scope(namespace: string): (key: string, fallback: string) => string {
167
+ return (key, fallback) => tr(namespace, key, fallback);
168
+ }
169
+
170
+ // ---------------------------------------------------------------------------
171
+ // Locale state
172
+ // ---------------------------------------------------------------------------
173
+
174
+ export function applyLocale(locale: string | undefined): void {
175
+ getRuntime().activeLocale = locale;
176
+ rebuildActive();
177
+ }
178
+
179
+ export function getActiveLocale(): string | undefined {
180
+ return getRuntime().activeLocale;
181
+ }
182
+
183
+ // ---------------------------------------------------------------------------
184
+ // Config persistence — mirrors advisor.ts:99-123
185
+ // ---------------------------------------------------------------------------
186
+
187
+ export function loadLocaleConfig(): LocaleConfig {
188
+ if (!existsSync(LOCALE_CONFIG_PATH)) return {};
189
+ try {
190
+ return JSON.parse(readFileSync(LOCALE_CONFIG_PATH, "utf-8")) as LocaleConfig;
191
+ } catch (err) {
192
+ console.warn(
193
+ `rpiv-i18n: invalid locale config at ${LOCALE_CONFIG_PATH}, using default (${(err as Error).message})`,
194
+ );
195
+ return {};
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Persist the locale preference. Returns `true` on success, `false` if the
201
+ * write failed (disk full, permissions, etc.) — caller MUST react. The chmod
202
+ * step is best-effort and never affects the return value.
203
+ */
204
+ export function saveLocaleConfig(locale: string | undefined): boolean {
205
+ const config: LocaleConfig = {};
206
+ if (locale) config.locale = locale;
207
+ try {
208
+ mkdirSync(dirname(LOCALE_CONFIG_PATH), { recursive: true });
209
+ writeFileSync(LOCALE_CONFIG_PATH, `${JSON.stringify(config, null, 2)}\n`, "utf-8");
210
+ } catch {
211
+ return false;
212
+ }
213
+ try {
214
+ chmodSync(LOCALE_CONFIG_PATH, CONFIG_FILE_MODE);
215
+ } catch {
216
+ // chmod is non-critical — file persists with default mode
217
+ }
218
+ return true;
219
+ }
220
+
221
+ // ---------------------------------------------------------------------------
222
+ // Locale detection (no flag — flag is read in index.ts which has pi access)
223
+ // ---------------------------------------------------------------------------
224
+
225
+ function parseLangEnv(value: string | undefined): string | undefined {
226
+ if (!value) return undefined;
227
+ const lang = value.split("_")[0]?.split(".")[0];
228
+ if (!lang || lang === "C" || lang === "POSIX") return undefined;
229
+ return lang;
230
+ }
231
+
232
+ export function detectLocaleFromConfigAndEnv(): string | undefined {
233
+ const config = loadLocaleConfig();
234
+ if (config.locale) return config.locale;
235
+ return parseLangEnv(process.env.LANG) ?? parseLangEnv(process.env.LC_ALL);
236
+ }
237
+
238
+ // ---------------------------------------------------------------------------
239
+ // Module init — globalThis registry exists from first import. Subsequent
240
+ // loads of this module (e.g. via different node_modules resolution paths)
241
+ // share the same runtime via the globalThis singleton, so re-running this
242
+ // init on the second load is a no-op data-wise (the locale value is the
243
+ // same, registrations are preserved).
244
+ // ---------------------------------------------------------------------------
245
+
246
+ applyLocale(detectLocaleFromConfigAndEnv());
247
+
248
+ // ---------------------------------------------------------------------------
249
+ // Test reset — wired into test/setup.ts beforeEach
250
+ // ---------------------------------------------------------------------------
251
+
252
+ export function __resetState(): void {
253
+ const rt = getRuntime();
254
+ rt.registry.clear();
255
+ rt.activeStrings.clear();
256
+ rt.activeLocale = undefined;
257
+ writeRegistry();
258
+ }
package/index.ts ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * @juicesharp/rpiv-i18n — Pi extension entry point.
3
+ *
4
+ * Wires:
5
+ * - --locale CLI flag (pi.registerFlag)
6
+ * - /languages slash command (interactive picker)
7
+ * - session_start hook (applies flag → config → LANG → English priority chain)
8
+ *
9
+ * Exposes i18n state via globalThis[Symbol.for("rpiv-i18n")] as plain data.
10
+ */
11
+
12
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
13
+ import type { SelectItem } from "@mariozechner/pi-tui";
14
+ import {
15
+ applyLocale,
16
+ detectLocaleFromConfigAndEnv,
17
+ getActiveLocale,
18
+ SUPPORTED_LOCALES,
19
+ saveLocaleConfig,
20
+ } from "./i18n.js";
21
+ import { showLanguagePicker } from "./i18n-ui.js";
22
+
23
+ const FLAG_NAME = "locale";
24
+ const COMMAND_NAME = "languages";
25
+ const NO_LOCALE_VALUE = "__system__";
26
+ const CHECKMARK = " ✓";
27
+ const MSG_REQUIRES_INTERACTIVE = "/languages requires interactive mode";
28
+ const MSG_PERSIST_FAILED = "Failed to save locale preference — selection not persisted";
29
+ const msgLocaleSet = (code: string | undefined) => (code ? `Language: ${code}` : "Language: system default");
30
+
31
+ export default function (pi: ExtensionAPI): void {
32
+ pi.registerFlag(FLAG_NAME, {
33
+ type: "string",
34
+ description: "UI locale code (e.g. en, uk, es, de)",
35
+ });
36
+
37
+ pi.on("session_start", async () => {
38
+ const flagValue = pi.getFlag(FLAG_NAME);
39
+ const fromFlag = typeof flagValue === "string" && flagValue.length > 0 ? flagValue : undefined;
40
+ applyLocale(fromFlag ?? detectLocaleFromConfigAndEnv());
41
+ });
42
+
43
+ pi.registerCommand(COMMAND_NAME, {
44
+ description: "Select UI language for rpiv-* TUI strings",
45
+ handler: async (_args, ctx) => {
46
+ if (!ctx.hasUI) {
47
+ ctx.ui.notify(MSG_REQUIRES_INTERACTIVE, "error");
48
+ return;
49
+ }
50
+ const current = getActiveLocale();
51
+ const items: SelectItem[] = SUPPORTED_LOCALES.map((l) => ({
52
+ value: l.code,
53
+ label: `${l.label} (${l.code})${current === l.code ? CHECKMARK : ""}`,
54
+ }));
55
+ items.push({
56
+ value: NO_LOCALE_VALUE,
57
+ label: current === undefined ? `System default${CHECKMARK}` : "System default",
58
+ });
59
+
60
+ const choice = await showLanguagePicker(ctx, items);
61
+ if (!choice) return;
62
+
63
+ const next = choice === NO_LOCALE_VALUE ? undefined : choice;
64
+ if (!saveLocaleConfig(next)) {
65
+ // Don't apply in-memory either — keeps the UI honest. A successful
66
+ // applyLocale + failed disk write would silently revert at restart.
67
+ ctx.ui.notify(MSG_PERSIST_FAILED, "error");
68
+ return;
69
+ }
70
+ applyLocale(next);
71
+ ctx.ui.notify(msgLocaleSet(next), "info");
72
+ },
73
+ });
74
+ }
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@juicesharp/rpiv-i18n",
3
+ "version": "1.1.0",
4
+ "description": "Pi extension: i18n/localization foundation — locale detection, /languages command, --locale flag, cross-package locale registry",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi-extension",
8
+ "rpiv",
9
+ "i18n",
10
+ "localization"
11
+ ],
12
+ "type": "module",
13
+ "license": "MIT",
14
+ "author": "juicesharp",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/juicesharp/rpiv-mono.git",
18
+ "directory": "packages/rpiv-i18n"
19
+ },
20
+ "homepage": "https://github.com/juicesharp/rpiv-mono/tree/main/packages/rpiv-i18n#readme",
21
+ "bugs": {
22
+ "url": "https://github.com/juicesharp/rpiv-mono/issues"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "scripts": {
28
+ "test": "vitest run"
29
+ },
30
+ "files": [
31
+ "index.ts",
32
+ "i18n.ts",
33
+ "i18n-ui.ts",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "exports": {
38
+ ".": "./i18n.ts"
39
+ },
40
+ "pi": {
41
+ "extensions": [
42
+ "./index.ts"
43
+ ]
44
+ },
45
+ "peerDependencies": {
46
+ "@mariozechner/pi-coding-agent": "*",
47
+ "@mariozechner/pi-tui": "*"
48
+ }
49
+ }