refactor(voice): isolate gemini live provider core

This commit is contained in:
manjunath committed 2026-10-19 21:40:40 +05:30
commit 10916227cb
655 files changed
+45946 -26483

No files matched your search

+280
View File
@@ -0,0 +1,280 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
checkCatalog,
extractMessages,
findUnmarked,
readCatalog,
shippedLocales,
unmarkedMarkup,
unmarkedScript,
} from '../../scripts/i18n.mjs';
import { LOCALES } from './locale.js';
const messages = extractMessages();
test('every catalog file is a shipped locale and every non-English locale has a catalog', () => {
assert.deepEqual(
shippedLocales().sort(),
LOCALES.filter((locale) => locale !== 'en').sort(),
);
});
for (const locale of shippedLocales()) {
test(`${locale} catalog matches the code (npm run i18n)`, () => {
const { missing, stale, errors } = checkCatalog(
locale,
readCatalog(locale),
messages,
);
assert.deepEqual(
{ missing, stale, errors },
{ missing: [], stale: [], errors: [] },
);
});
}
test('every UI string is marked for translation or kept on purpose (npm run i18n)', () => {
assert.deepEqual(
findUnmarked().map(({ where, text }) => `${where} ${text}`),
[],
);
});
test('checkCatalog reports missing, stale, placeholder and plural problems', () => {
const fixture = new Map([
['Saved {name}', { plural: false }],
['{count} keys', { plural: true, one: '{count} key' }],
['Untranslated', { plural: false }],
]);
const result = checkCatalog(
'ru',
{
'Saved {name}': 'Сохранено {nmae}',
'{count} keys': {
one: '{count} ключ',
few: '{count} ключа',
many: '{count} ключей',
},
Removed: 'Удалено',
},
fixture,
);
assert.deepEqual(result.missing, ['Untranslated']);
assert.deepEqual(result.stale, ['Removed']);
assert.equal(result.errors.length, 2);
});
test('checkCatalog reports a translation left in English unless it is allowed', () => {
const fixture = new Map([
['Bloom', { plural: false }],
['HDG', { plural: false }],
['voice|READY', { plural: false }],
['{state} · {source}', { plural: false }],
]);
const catalog = {
Bloom: 'Bloom',
HDG: 'HDG',
'voice|READY': 'READY',
'{state} · {source}': '{state} · {source}',
};
const errors = (allowed) =>
checkCatalog('es', catalog, fixture, new Set(allowed)).errors;
assert.deepEqual(
errors([]).map((error) => error.split(' is still English')[0]),
['"Bloom"', '"HDG"', '"voice|READY"'],
);
assert.deepEqual(errors(['Bloom', 'HDG', 'voice|READY']), []);
});
test('unmarkedMarkup finds text and attributes without data-i18n*', () => {
const texts = (html) => unmarkedMarkup('f.html', html).map((f) => f.text);
assert.deepEqual(texts('<span>Close</span>'), ['Close']);
assert.deepEqual(texts('<span data-i18n>Close</span>'), []);
assert.deepEqual(texts('<button title="Pin it">x</button>'), [
'title="Pin it"',
]);
assert.deepEqual(
texts('<button title="Pin it" data-i18n-title>x</button>'),
[],
);
assert.deepEqual(
texts('<select translate="no"><option>0.9 dB</option></select>'),
[],
);
assert.deepEqual(texts('<b data-i18n-runtime><i>OFF</i></b>'), []);
assert.deepEqual(
texts('<span class="material-symbols-outlined">public</span>'),
[],
);
assert.deepEqual(texts('<!-- Note --><span>— 42 —</span>'), []);
});
test('unmarkedScript finds literals that reach the page without t/tn/msg', () => {
const texts = (js) => unmarkedScript('f.js', js).map((f) => f.text);
assert.deepEqual(texts("el.textContent = 'Saved';"), ['Saved']);
assert.deepEqual(texts("el.textContent = t('Saved');"), []);
assert.deepEqual(texts("el.textContent = on ? 'On air' : 'Off air';"), [
'On air',
'Off air',
]);
assert.deepEqual(texts("el.setAttribute('aria-label', `Open ${name}`);"), [
'Open',
]);
assert.deepEqual(
texts("const row = { label: msg('Wind'), id: 'wind' };"),
[],
);
assert.deepEqual(texts("const row = { label: 'Wind' };"), ['Wind']);
assert.deepEqual(texts("el.textContent = labelFor('flights');"), []);
assert.deepEqual(texts("el.className = 'is-active';"), []);
assert.deepEqual(texts("el.title = mode === 'Auto mode' ? a : b;"), []);
assert.deepEqual(texts("// el.textContent = 'Old copy';"), []);
assert.deepEqual(
texts("// i18n-ignore: product name\nel.textContent = 'OpenSky';"),
[],
);
});
test('unmarkedScript sees toasts behind optional calls and private helpers', () => {
const texts = (js) => unmarkedScript('f.js', js).map((f) => f.text);
assert.deepEqual(texts("showToast?.('North up');"), ['North up']);
assert.deepEqual(texts("this._showToast('Search failed');"), [
'Search failed',
]);
assert.deepEqual(texts("this.showToast('Link copied');"), ['Link copied']);
assert.deepEqual(texts("this.actions.showToast?.('Tilted view');"), [
'Tilted view',
]);
assert.deepEqual(texts("showToast?.(t('North up'));"), []);
assert.deepEqual(texts("this._showToast(t('Search failed'));"), []);
});
test('unmarkedScript sees status text assigned to layer errors and labels', () => {
const texts = (js) => unmarkedScript('f.js', js).map((f) => f.text);
assert.deepEqual(texts("layerState._error = 'live feed unavailable';"), [
'live feed unavailable',
]);
assert.deepEqual(
texts("this._error = err?.message || 'TeleGeography load failed';"),
['TeleGeography load failed'],
);
assert.deepEqual(texts("_error = 'Route request failed';"), [
'Route request failed',
]);
assert.deepEqual(texts("error ??= 'Feed closed';"), ['Feed closed']);
assert.deepEqual(texts('stats.error = `${name} fetch error`;'), [
'fetch error',
]);
assert.deepEqual(texts("loadingLabel = 'loading coverage...';"), [
'loading coverage...',
]);
assert.deepEqual(texts("state._loadingLabel = 'Loading cables';"), [
'Loading cables',
]);
assert.deepEqual(texts("stats.statusMessage = 'Add a key in Settings';"), [
'Add a key in Settings',
]);
assert.deepEqual(texts("this.status = 'Scene not saved';"), [
'Scene not saved',
]);
assert.deepEqual(
texts("layerState._error = msg('live feed unavailable');"),
[],
);
assert.deepEqual(texts("stats.error = t('GBFS fetch error');"), []);
// Machine values, comparisons and local scratch variables are not UI text.
assert.deepEqual(texts("status = 'missing-key';"), []);
assert.deepEqual(texts("if (error === 'Feed closed') stop();"), []);
assert.deepEqual(texts("const error = log() || 'Unknown shader error';"), []);
assert.deepEqual(texts('stats.error = new Error(`HTTP ${code}`);'), []);
});
test('unmarkedScript sees human-readable status, loadingLabel and statusMessage fields', () => {
const texts = (js) => unmarkedScript('f.js', js).map((f) => f.text);
assert.deepEqual(
texts("return { status: 'Scene not saved — storage unavailable' };"),
['Scene not saved — storage unavailable'],
);
assert.deepEqual(
texts("return { status: ok ? 'Ready' : 'Source unavailable' };"),
['Ready', 'Source unavailable'],
);
assert.deepEqual(texts("return { loadingLabel: 'Loading feeds' };"), [
'Loading feeds',
]);
assert.deepEqual(texts("return { statusMessage: 'connect a receiver' };"), [
'connect a receiver',
]);
assert.deepEqual(texts("return { status: 'streaming', code: 'ok' };"), []);
assert.deepEqual(texts("return { status: 'auth-failed' };"), []);
assert.deepEqual(texts("return { status: msg('Source unavailable') };"), []);
});
// The Layers panel shows `stats.error || stats.lastError`, so a
// lastError is status text like error.
test('unmarkedScript sees status text assigned to lastError', () => {
const texts = (js) => unmarkedScript('f.js', js).map((f) => f.text);
assert.deepEqual(
texts(
"state.coverage.lastError = error?.message || 'Coverage tile failed';",
),
['Coverage tile failed'],
);
assert.deepEqual(texts("layerState._lastError = 'CelesTrak unreachable';"), [
'CelesTrak unreachable',
]);
assert.deepEqual(
texts(
"state.coverage.lastError = error?.message || msg('Coverage tile failed');",
),
[],
);
assert.deepEqual(texts('this._lastError = message;'), []);
});
test('unmarkedScript skips default values and ternary branches, not later assignments', () => {
const texts = (js) => unmarkedScript('f.js', js).map((f) => f.text);
// A default value in a parameter list or destructuring is a local's.
assert.deepEqual(texts("function f(error = 'Feed went away') {}"), []);
assert.deepEqual(texts("const f = (status = 'Not ready', x) => x;"), []);
assert.deepEqual(
texts("function f(\n status = 'Not ready',\n x,\n) {}"),
[],
);
assert.deepEqual(texts("const { status = 'Ready now' } = options;"), []);
assert.deepEqual(
texts("const {\n error = 'No data yet',\n} = options;"),
[],
);
assert.deepEqual(
texts("for (const [id, status = 'Waiting'] of rows) {}"),
[],
);
// A name right after `?` is a ternary branch, not a `status:` property.
assert.deepEqual(texts("const s = ok ? status : 'Source unavailable';"), []);
assert.deepEqual(texts("const s = ok\n ? title\n : 'Untitled view';"), []);
// …while the property itself still is.
assert.deepEqual(texts("return { title: x ? title : 'Untitled view' };"), [
'Untitled view',
]);
// A later assignment is checked even when the name is a declared local:
// a layer keeps its status in `let error` (wind, AIS watchdog) and builds
// `loadingLabel` in a `let` before returning it (FIRMS).
assert.deepEqual(
texts(
"function f() {\n let error = null;\n if (x) error = 'Feed closed';\n}",
),
['Feed closed'],
);
assert.deepEqual(
texts(
"let loadingLabel = '';\nif (x) {\n loadingLabel = 'KEY REQUIRED';\n}",
),
['KEY REQUIRED'],
);
assert.deepEqual(texts("let a = 1,\n error = 'Feed closed';"), [
'Feed closed',
]);
});
+62
View File
@@ -0,0 +1,62 @@
// An empty or blank translation must not count as done.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
checkCatalog,
extractMessages,
readCatalog,
} from '../../scripts/i18n.mjs';
import { getCatalog, setLocale, t, tn, translateKnown } from './index.js';
const messages = extractMessages();
const EMPTY = 'DISCONNECT';
const BLANK = 'CONTACT LOST · LAST KNOWN READOUT · NOT AN ALL-CLEAR';
for (const locale of ['es', 'ru']) {
test(`${locale}: checkCatalog rejects an empty or blank translation`, () => {
const catalog = { ...readCatalog(locale), [EMPTY]: '', [BLANK]: ' ' };
const { errors } = checkCatalog(locale, catalog, messages);
assert.ok(
errors.some((e) => e.includes(`"${EMPTY}"`)),
'empty string passes the check',
);
assert.ok(
errors.some((e) => e.includes(`"${BLANK}"`)),
'blank string passes the check',
);
});
}
test('t() and translateKnown() fall back to English for an empty entry', () => {
const es = getCatalog('es');
const saved = es[EMPTY];
es[EMPTY] = '';
setLocale('es');
try {
assert.equal(t(EMPTY), EMPTY);
assert.equal(translateKnown(EMPTY), EMPTY);
} finally {
es[EMPTY] = saved;
setLocale('en');
}
});
test('tn() skips an empty plural form', () => {
const es = getCatalog('es');
const KEY = '{count} INPUTS UNKNOWN';
const saved = es[KEY];
setLocale('es');
try {
es[KEY] = { ...saved, one: ' ' };
assert.equal(
tn(1, '{count} INPUT UNKNOWN', KEY),
saved.other.replace('{count}', '1'),
);
es[KEY] = { one: '', many: '', other: '' };
assert.equal(tn(1, '{count} INPUT UNKNOWN', KEY), '1 INPUT UNKNOWN');
assert.equal(tn(3, '{count} INPUT UNKNOWN', KEY), '3 INPUTS UNKNOWN');
} finally {
es[KEY] = saved;
setLocale('en');
}
});
+252
View File
@@ -0,0 +1,252 @@
import { test, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import {
applyDocumentTranslations,
formatDate,
formatNumber,
msg,
persistLocaleAndReload,
setLocale,
t,
tn,
} from './index.js';
import {
LOCALE_STORAGE_KEY,
applyDocumentLanguage,
normalizeLocale,
resolveLocale,
writeStoredLocale,
} from './locale.js';
afterEach(() => setLocale('en'));
function memoryStorage(initial = {}) {
const data = new Map(Object.entries(initial));
return {
getItem: (key) => (data.has(key) ? data.get(key) : null),
setItem: (key, value) => data.set(key, String(value)),
data,
};
}
test('normalizeLocale folds regional variants and rejects unshipped tags', () => {
assert.equal(normalizeLocale('ru-RU'), 'ru');
assert.equal(normalizeLocale(' RU '), 'ru');
assert.equal(normalizeLocale('en_GB'), 'en');
assert.equal(normalizeLocale('xx'), null);
assert.equal(normalizeLocale(undefined), null);
});
test('resolveLocale: ?lang= wins, then the stored choice, then browser languages, then English', () => {
const storage = memoryStorage({ [LOCALE_STORAGE_KEY]: 'ru' });
assert.equal(
resolveLocale({
location: { search: '?lang=en' },
storage,
languages: ['ru'],
}),
'en',
);
assert.equal(
resolveLocale({ location: { search: '' }, storage, languages: ['en'] }),
'ru',
);
assert.equal(
resolveLocale({
location: { search: '?lang=xx' },
storage: memoryStorage(),
languages: ['de-DE', 'ru-RU'],
}),
'ru',
);
assert.equal(
resolveLocale({
location: { search: '' },
storage: memoryStorage(),
languages: ['de'],
}),
'en',
);
});
test('a throwing storage never escapes', () => {
const storage = {
getItem() {
throw new Error('blocked');
},
setItem() {
throw new Error('blocked');
},
};
assert.equal(
resolveLocale({ location: { search: '' }, storage, languages: [] }),
'en',
);
assert.equal(writeStoredLocale('ru', storage), false);
});
test('applyDocumentLanguage sets lang and dir', () => {
const doc = { documentElement: {} };
applyDocumentLanguage(doc, 'ru-RU');
assert.deepEqual(doc.documentElement, { lang: 'ru', dir: 'ltr' });
});
test('t() returns English text in English and translates in Russian', () => {
assert.equal(t('POWERED UP'), 'POWERED UP');
setLocale('ru');
assert.notEqual(t('POWERED UP'), 'POWERED UP');
});
test('t() interpolates named values and keeps unknown names literal', () => {
assert.equal(
t('Save failed: {detail}', { detail: 'disk full' }),
'Save failed: disk full',
);
assert.equal(
t('Hello {who} {missing}', { who: 'pilot' }),
'Hello pilot {missing}',
);
});
test('t() falls back to English for text without a translation', () => {
setLocale('ru');
assert.equal(t('No such message {n}', { n: 1 }), 'No such message 1');
});
test('tn() picks English and Russian plural forms', () => {
const label = (count) =>
tn(
count,
'POWER UP · {count} KEY WAITING',
'POWER UP · {count} KEYS WAITING',
);
assert.equal(label(1), 'POWER UP · 1 KEY WAITING');
assert.equal(label(3), 'POWER UP · 3 KEYS WAITING');
setLocale('ru');
assert.match(label(1), / 1 КЛЮЧ(?![А-ЯЁ])/);
assert.match(label(3), / 3 КЛЮЧА(?![А-ЯЁ])/);
assert.match(label(5), / 5 КЛЮЧЕЙ(?![А-ЯЁ])/);
assert.match(label(21), / 21 КЛЮЧ(?![А-ЯЁ])/);
});
test('t() context separates identical English with different meanings', () => {
assert.equal(t('CLEAR', { context: 'action' }), 'CLEAR');
setLocale('ru');
assert.notEqual(t('CLEAR', { context: 'action' }), t('CLEAR'));
});
test('msg() returns its text unchanged', () => {
assert.equal(msg('Live Flights'), 'Live Flights');
});
test('Intl formatters follow the active locale', () => {
const date = new Date(Date.UTC(2026, 0, 15));
const options = {
year: 'numeric',
month: 'long',
day: 'numeric',
timeZone: 'UTC',
};
assert.equal(formatDate(date, options), 'January 15, 2026');
assert.equal(formatNumber(1234.5), '1,234.5');
setLocale('ru');
assert.equal(formatDate(date, options), '15 января 2026 г.');
assert.equal(formatNumber(1234.5), '1 234,5');
});
function fakeElement({ text = '', attributes = {} } = {}) {
const attrs = new Map(Object.entries(attributes));
return {
textContent: text,
getAttribute: (name) => (attrs.has(name) ? attrs.get(name) : null),
setAttribute: (name, value) => attrs.set(name, value),
attrs,
};
}
test('applyDocumentTranslations translates opted-in text and attributes in place', () => {
const label = fakeElement({ text: '\n POWERED\n UP ' });
const pin = fakeElement({ attributes: { title: 'POWERED UP' } });
const unknown = fakeElement({ text: 'No such message' });
const doc = {
querySelectorAll(selector) {
if (selector === '[data-i18n]') return [label, unknown];
if (selector === '[data-i18n-title]') return [pin];
return [];
},
};
assert.equal(
applyDocumentTranslations(doc),
0,
'English leaves markup alone',
);
setLocale('ru');
assert.equal(applyDocumentTranslations(doc), 2);
assert.equal(label.textContent, t('POWERED UP'));
assert.equal(pin.attrs.get('title'), t('POWERED UP'));
assert.equal(unknown.textContent, 'No such message');
});
test('persistLocaleAndReload keeps the choice in ?lang when storage is blocked', () => {
const calls = [];
const location = {
href: 'https://gev.local/?x=1#scene=a',
assign: (url) => calls.push(['assign', url]),
reload: () => calls.push(['reload']),
};
const history = {
replaceState: (_s, _t, url) => calls.push(['replace', url]),
};
const storage = {
setItem() {
throw new Error('blocked');
},
};
assert.equal(
persistLocaleAndReload('ru', { location, history, storage }),
true,
);
assert.deepEqual(calls, [
['replace', 'https://gev.local/?x=1&lang=ru#scene=a'],
['reload'],
]);
});
test('persistLocaleAndReload stores the choice, keeps the hash, strips ?lang', () => {
const storage = memoryStorage();
const calls = [];
const location = {
href: 'https://gev.local/?lang=en&x=1#scene=a',
assign: (url) => calls.push(['assign', url]),
reload: () => calls.push(['reload']),
};
const history = {
replaceState: (_s, _t, url) => calls.push(['replace', url]),
};
assert.equal(
persistLocaleAndReload('ru', { location, history, storage }),
true,
);
assert.equal(storage.data.get(LOCALE_STORAGE_KEY), 'ru');
assert.deepEqual(calls, [
['replace', 'https://gev.local/?x=1#scene=a'],
['reload'],
]);
});
test('tn() shows a caller-formatted count and still picks the form by number', () => {
const label = (n) =>
tn(n, '{count} map object', '{count} map objects', {
count: formatNumber(n),
});
assert.equal(label(12345), '12,345 map objects');
assert.equal(tn(12345, '{count} file', '{count} files'), '12345 files');
setLocale('ru');
try {
assert.equal(label(12345), '12 345 объектов на карте');
assert.equal(label(1), '1 объект на карте');
} finally {
setLocale('en');
}
});
+330
View File
@@ -0,0 +1,330 @@
// God's Eye View i18n: the English source text is the message key.
//
// t('Save keys') → 'Сохранить ключи'
// t('Cleared {name}', { name }) → named interpolation
// tn(count, '{count} camera', '{count} cameras') → plural by Intl.PluralRules
// t('CLEAR', { context: 'action' }) → same English, own entry
// msg('Live Flights') → marks a string kept in data
// for a later t(); returns it as is
//
// English needs no catalog. Every other locale is one flat JSON file,
// locales/<code>.json, keyed by the English text (for tn, by the English
// plural form). A missing or empty entry falls back to English.
// `npm run i18n` keeps the catalogs in step with the code. Guide: docs/I18N.md.
import {
DEFAULT_LOCALE,
normalizeLocale,
writeStoredLocale,
} from './locale.js';
import es from './locales/es.json' with { type: 'json' };
import ru from './locales/ru.json' with { type: 'json' };
const CATALOGS = Object.freeze({ es, ru });
let currentLocale = DEFAULT_LOCALE;
/** The catalog for a locale; null for English and unknown codes. */
export function getCatalog(locale) {
return CATALOGS[normalizeLocale(locale)] ?? null;
}
/** Active locale. */
export function getLocale() {
return currentLocale;
}
/**
* Switch the active locale. Pure state change: call applyDocumentLanguage /
* applyDocumentTranslations to reflect it in the DOM.
* @returns {string} The locale actually applied (normalized).
*/
export function setLocale(locale) {
const normalized = normalizeLocale(locale) || DEFAULT_LOCALE;
if (normalized !== currentLocale) {
currentLocale = normalized;
formatterCache.clear();
}
return currentLocale;
}
/** Development-only warning; silent under node:test and in production. */
function warnMissing(text) {
if (import.meta.env?.DEV !== true) return;
console.warn(
`[i18n] no ${currentLocale} translation for ${JSON.stringify(text)}`,
);
}
const PLACEHOLDER_PATTERN = /\{([A-Za-z0-9_]+)\}/g;
/** Named {placeholder} interpolation. Unknown names stay literal so a gap
* stays visible instead of silently vanishing. */
function interpolate(pattern, values) {
if (!values) return pattern;
return pattern.replace(PLACEHOLDER_PATTERN, (literal, name) =>
Object.hasOwn(values, name) ? String(values[name]) : literal,
);
}
/** A catalog string with something to show; an empty one counts as missing. */
const filled = (value) => typeof value === 'string' && value.trim() !== '';
function lookup(text) {
const catalog = CATALOGS[currentLocale];
if (!catalog) return undefined;
const entry = Object.hasOwn(catalog, text) ? catalog[text] : undefined;
if (filled(entry) || (entry && typeof entry === 'object')) return entry;
warnMissing(text);
return undefined;
}
/**
* Translate English source text into the active locale.
* @param {string} text English text, e.g. 'Hold Space to talk'
* @param {object} [values] Named interpolation values. `context` tells
* apart identical English with different meanings: t('CLEAR', { context:
* 'action' }) is the catalog entry "action|CLEAR"; English is unchanged.
* @returns {string}
*/
export function t(text, values) {
const entry = lookup(values?.context ? `${values.context}|${text}` : text);
return interpolate(typeof entry === 'string' ? entry : text, values);
}
/**
* Translate a count-dependent message. The catalog entry for `other` holds
* one form per Intl.PluralRules category of the locale ({ one, few, many, other }
* for Russian). `{count}` is always available to the pattern: the raw number,
* unless `values.count` gives its display text, e.g. `formatNumber(n)`.
* @param {number} count
* @param {string} one English singular, e.g. '{count} camera'
* @param {string} other English plural, e.g. '{count} cameras'
* @param {object} [values] Extra interpolation values; a `count` here is
* shown in place of the number (the plural form still follows `count`)
* @returns {string}
*/
export function tn(count, one, other, values) {
const entry = lookup(other);
const category = pluralRules(currentLocale).select(count);
let pattern;
const forms = entry && typeof entry === 'object' ? entry : null;
if (forms && (filled(forms[category]) || filled(forms.other))) {
pattern = filled(forms[category]) ? forms[category] : forms.other;
} else {
pattern = pluralRules(DEFAULT_LOCALE).select(count) === 'one' ? one : other;
}
return interpolate(pattern, { count, ...values });
}
/**
* Translate text that may be ours or may come from a provider: a catalog
* entry is used when there is one, anything else shows as given, without a
* missing-translation warning.
*/
export function translateKnown(text) {
const catalog = CATALOGS[currentLocale];
if (!catalog || typeof text !== 'string') return text;
const entry = Object.hasOwn(catalog, text) ? catalog[text] : undefined;
return filled(entry) ? entry : text;
}
/** Mark English text that is stored in data and translated later by t(). */
export function msg(text) {
return text;
}
const pluralRulesCache = new Map();
function pluralRules(locale) {
let rules = pluralRulesCache.get(locale);
if (!rules) {
rules = new Intl.PluralRules(locale);
pluralRulesCache.set(locale, rules);
}
return rules;
}
/*
* Intl formatters are memoized per (kind, locale, options): the constructors
* are expensive and panels format on refresh paths. The cache is cleared
* whenever the active locale changes.
*/
const formatterCache = new Map();
function cachedFormatter(kind, Constructor, options) {
const cacheKey = `${kind}|${currentLocale}|${options ? JSON.stringify(options) : ''}`;
let formatter = formatterCache.get(cacheKey);
if (!formatter) {
formatter = new Constructor(currentLocale, options);
formatterCache.set(cacheKey, formatter);
}
return formatter;
}
/** Locale-aware number formatting (Intl.NumberFormat). */
export function formatNumber(value, options) {
return cachedFormatter('number', Intl.NumberFormat, options).format(value);
}
/** Locale-aware date/time formatting (Intl.DateTimeFormat). */
export function formatDate(value, options) {
return cachedFormatter('date', Intl.DateTimeFormat, options).format(value);
}
const UTC_DAY_MONTH = Object.freeze({
day: '2-digit',
month: '2-digit',
timeZone: 'UTC',
});
/**
* The UTC day and month of a time, for "MM-DD HH:MM UTC" readouts: "10-13" in
* English, "13.10" in Russian, "13/10" in Spanish, never read as a
* range. Takes an ISO string (its date part is used as written) or a time.
* @param {string|number|Date} value
* @returns {string} '' when the value is not a time.
*/
export function formatUtcDayMonth(value) {
const written =
typeof value === 'string' ? /^(\d{4})-(\d{2})-(\d{2})/.exec(value) : null;
const time = written
? Date.UTC(Number(written[1]), Number(written[2]) - 1, Number(written[3]))
: new Date(value).getTime();
if (!Number.isFinite(time)) return '';
if (currentLocale === 'en') return new Date(time).toISOString().slice(5, 10);
return cachedFormatter('date', Intl.DateTimeFormat, UTC_DAY_MONTH).format(
time,
);
}
/**
* Locale-aware relative time (Intl.RelativeTimeFormat), e.g.
* formatRelativeTime(-5, 'minute') → '5 minutes ago' / '5 минут назад'.
*/
export function formatRelativeTime(value, unit = 'second', options) {
return cachedFormatter('relative', Intl.RelativeTimeFormat, {
numeric: 'auto',
...options,
}).format(value, unit);
}
/** Collapse markup whitespace so a message reads the same in HTML and JS. */
export function normalizeMarkupText(text) {
return String(text ?? '')
.replace(/\s+/g, ' ')
.trim();
}
/**
* Markup opt-in: the element's own English text or attribute is the source.
* <span data-i18n>Normal</span>
* <button title="Pin" data-i18n-title>…</button>
* Also data-i18n-aria-label and data-i18n-placeholder.
*/
const DOCUMENT_TRANSLATION_TARGETS = Object.freeze([
['data-i18n', null],
['data-i18n-title', 'title'],
['data-i18n-aria-label', 'aria-label'],
['data-i18n-placeholder', 'placeholder'],
]);
/**
* Translate every opted-in element in `doc`. Runs once at boot; switching
* locale reloads the page.
* @param {Document|Element} doc
* @returns {number} Count of element/attribute writes performed.
*/
export function applyDocumentTranslations(doc) {
if (typeof doc?.querySelectorAll !== 'function') return 0;
if (!CATALOGS[currentLocale]) return 0;
let applied = 0;
for (const [marker, attribute] of DOCUMENT_TRANSLATION_TARGETS) {
for (const element of doc.querySelectorAll(`[${marker}]`)) {
const source = attribute
? element.getAttribute(attribute)
: normalizeMarkupText(element.textContent);
if (!source) continue;
const text = t(source);
if (text === source) continue;
if (attribute) element.setAttribute(attribute, text);
else element.textContent = text;
applied += 1;
}
}
return applied;
}
const unsavedWorkChecks = new Set();
/**
* Name work that switching language would lose: the switch reloads the page,
* and the language switch asks first while any check reports something.
* @param {() => string|null|undefined} check Returns a msg() label (e.g.
* msg('unsaved CCTV calibration')) while there is such work, else nothing.
* @returns {() => void} Removes the check.
*/
export function registerUnsavedWork(check) {
if (typeof check !== 'function') return () => {};
unsavedWorkChecks.add(check);
return () => unsavedWorkChecks.delete(check);
}
/**
* What a reload would lose right now, translated, without repeats.
* @returns {string[]}
*/
export function describeUnsavedWork() {
const labels = new Set();
for (const check of unsavedWorkChecks) {
try {
const label = check();
if (typeof label === 'string' && label) labels.add(t(label));
} catch {
// A failing check must not block the switch.
}
}
return [...labels];
}
/**
* Persist a locale choice, then reload preserving window.location.hash exactly
* and stripping ?lang from the search string, so the stored choice applies.
* Where storage is blocked, ?lang carries the choice instead (share links
* drop it: ShareLinkManager.copyLink).
* @returns {boolean} true when a reload was triggered.
*/
export function persistLocaleAndReload(
locale,
{
location = globalThis.location,
history = globalThis.history,
storage,
} = {},
) {
const normalized = normalizeLocale(locale) || DEFAULT_LOCALE;
const stored = writeStoredLocale(normalized, storage);
if (!location || typeof location.assign !== 'function') return false;
let target = location.href;
try {
// Without storage the choice only survives in the URL, so keep it there.
const url = new URL(location.href);
if (stored) url.searchParams.delete('lang');
else url.searchParams.set('lang', normalized);
target = url.href;
} catch {
// Keep the current href.
}
// location.assign() to the identical URL does not navigate, so strip ?lang
// in place and force a real reload instead.
try {
history?.replaceState?.(null, '', target);
} catch {
// replaceState is best-effort; the reload below still applies.
}
if (typeof location.reload === 'function') {
location.reload();
} else {
location.assign(target);
}
return true;
}
+60
View File
@@ -0,0 +1,60 @@
// KartaView texts are English data (msg() in providers/kartaview/) shown
// through translateKnown, so each needs an entry in every catalog.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { setLocale, translateKnown } from './index.js';
const MESSAGES = [
// kartaview/policy.js
'KartaView is rate-limiting requests — they resume on their own',
'KartaView’s photos here are archived and cannot be shown',
'KartaView did not filter this area in time — move the map to ask again',
'None of KartaView’s photos here pass the imagery filter',
// kartaview/source.js
'KartaView did not answer in time — try again',
'KartaView could not be reached — check the network',
'KartaView sent an answer that could not be read',
'KartaView is rate-limiting requests',
'KartaView is rate-limiting requests — try again in a moment',
'KartaView sent too much data',
'KartaView has no such photo',
// kartaview/viewer.js, index.js
'The KartaView photo could not be loaded',
'KartaView has no position for this photo',
];
for (const locale of ['es', 'ru']) {
test(`KartaView provider messages are translated in ${locale}`, () => {
setLocale(locale);
try {
const untranslated = MESSAGES.filter((m) => translateKnown(m) === m);
assert.deepEqual(untranslated, []);
} finally {
setLocale('en');
}
});
}
// kartaview/source.js refusals with a number in them: English data, shown
// through placeholder entries by the Street Level panel and the layer panel.
test('KartaView HTTP and refusal codes keep their number in every language', async () => {
const { translateStreetLevelError } =
await import('../ui/streetLevelPresentation.js');
const http = 'KartaView answered HTTP 503';
const refused = 'KartaView refused the request (code 610)';
assert.equal(translateStreetLevelError(http), http);
assert.equal(translateStreetLevelError(refused), refused);
for (const locale of ['es', 'ru']) {
setLocale(locale);
try {
const shownHttp = translateStreetLevelError(http);
const shownRefused = translateStreetLevelError(refused);
assert.notEqual(shownHttp, http);
assert.match(shownHttp, /503/);
assert.notEqual(shownRefused, refused);
assert.match(shownRefused, /610/);
} finally {
setLocale('en');
}
}
});
+65
View File
@@ -0,0 +1,65 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { setLocale, translateKnown } from './index.js';
// Layers keep these status texts as English data, and the panels show them
// through translateKnown, so each needs an entry in every catalog.
const SITES = [
['../layers/streetLevel/index.js', 'loading coverage...'],
['../layers/firms/ingestion.js', 'live feed unavailable'],
['../layers/bikeshare/controls.js', 'GBFS fetch error'],
[
'../layers/streetLevel/viewerHost.js',
'Open the Street Level panel to view imagery',
],
['../layers/streetLevel/viewerHost.js', 'Image could not be opened'],
['../layers/satellites/ingestion.js', 'CelesTrak unreachable'],
[
'../layers/streetLevel/providers/mapillary/policy.js',
'Coverage requests are being rate-limited — they resume on their own',
],
['../layers/alpr/index.js', 'Camera source temporarily unavailable'],
['../layers/perimeters/index.js', 'Perimeter source unavailable'],
['../layers/recentImagery/index.js', 'Imagery catalog unavailable'],
['../layers/installations/ingestion.js', 'Installation context unavailable'],
['../layers/earthquakes/index.js', 'Earthquake source unavailable'],
['../layers/submarineCables/ingestion.js', 'TeleGeography load failed'],
['../layers/vessels/ingestion.js', 'AIS live load failed'],
['../layers/vessels/lifecycle.js', 'AIS live load failed'],
['../layers/wind/index.js', 'Wind unavailable'],
['../layers/wind/source.js', 'Wind request timed out'],
['../layers/wind/source.js', 'Malformed wind manifest'],
['../layers/wind/source.js', 'Malformed wind grid'],
['../layers/wind/fields.js', 'Temperature field unavailable'],
['../layers/wind/fields.js', 'Mean sea level pressure field unavailable'],
];
// A fallback that reaches the panel must be marked, or `npm run i18n` cannot
// see it and the catalog entry would be pruned as unused.
for (const [file, text] of SITES) {
test(`"${text}" in ${file} is marked`, () => {
const source = readFileSync(new URL(file, import.meta.url), 'utf8');
assert.ok(
new RegExp(
String.raw`\b(?:msg|t)\(\s*'${text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}'`,
).test(source),
`${text} is not marked in ${file}`,
);
});
}
for (const locale of ['es', 'ru']) {
for (const [file, text] of SITES) {
test(`${locale}: "${text}" from ${file} is translated`, () => {
const source = readFileSync(new URL(file, import.meta.url), 'utf8');
assert.ok(source.includes(`'${text}'`), `literal not found in ${file}`);
setLocale(locale);
try {
assert.notEqual(translateKnown(text), text);
} finally {
setLocale('en');
}
});
}
}
+88
View File
@@ -0,0 +1,88 @@
// Which locale the page runs in: ?lang= → stored choice → browser languages →
// English. Only shipped locales are ever selected.
/** Durable preference key. Matches the repo convention gev:<name>:v1. */
export const LOCALE_STORAGE_KEY = 'gev:locale:v1';
/** Source language and fallback. */
export const DEFAULT_LOCALE = 'en';
/** Shipped locales; order does not matter. Adding one: docs/TRANSLATORS.md. */
export const LOCALES = Object.freeze(['en', 'es', 'ru']);
/** Each locale named in its own language, for the selector. */
export const LOCALE_NAMES = Object.freeze({
en: 'English',
es: 'Español',
ru: 'Русский',
});
/** Right-to-left locales. */
const RTL_LOCALES = Object.freeze([]);
/**
* Map any language tag to a shipped locale: 'ru-RU' and 'RU' → 'ru'.
* @returns {string|null}
*/
export function normalizeLocale(candidate) {
if (typeof candidate !== 'string') return null;
const primary = candidate.trim().toLowerCase().split(/[-_]/)[0];
return LOCALES.includes(primary) ? primary : null;
}
function queryLocale(location) {
try {
return normalizeLocale(new URLSearchParams(location?.search).get('lang'));
} catch {
return null;
}
}
function readStoredLocale(storage) {
try {
const store = storage !== undefined ? storage : globalThis.localStorage;
return normalizeLocale(store?.getItem?.(LOCALE_STORAGE_KEY));
} catch {
return null;
}
}
/** Store the choice; false when storage is unavailable. */
export function writeStoredLocale(locale, storage) {
const normalized = normalizeLocale(locale) || DEFAULT_LOCALE;
try {
const store = storage !== undefined ? storage : globalThis.localStorage;
if (typeof store?.setItem !== 'function') return false;
store.setItem(LOCALE_STORAGE_KEY, normalized);
return true;
} catch {
return false;
}
}
/** Resolve the boot locale. Every input is injectable for tests. */
export function resolveLocale({
location = globalThis.location,
storage,
languages = globalThis.navigator?.languages,
} = {}) {
const fromQuery = queryLocale(location);
if (fromQuery) return fromQuery;
const stored = readStoredLocale(storage);
if (stored) return stored;
for (const candidate of Array.isArray(languages) ? languages : []) {
const normalized = normalizeLocale(candidate);
if (normalized) return normalized;
}
return DEFAULT_LOCALE;
}
/** Set <html lang> and <html dir>. */
export function applyDocumentLanguage(doc, locale = DEFAULT_LOCALE) {
const root = doc?.documentElement;
if (!root) return false;
const normalized = normalizeLocale(locale) || DEFAULT_LOCALE;
root.lang = normalized;
root.dir = RTL_LOCALES.includes(normalized) ? 'rtl' : 'ltr';
return true;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
// msg() for modules the server, tools or other portable code also import:
// marks English that stays in data for `npm run i18n`, without loading the
// catalogs (src/i18n/index.js). The UI shows it later through t().
// Browser-only modules import msg from src/i18n/index.js instead.
/** Mark English text that is stored in data and translated later by t(). */
export const msg = (text) => text;
+89
View File
@@ -0,0 +1,89 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
checkCatalog,
extractMessages,
missingTemplate,
} from '../../scripts/i18n.mjs';
// A plural entry with forms left in English is reported like a string entry.
const fixture = new Map([
['{count} cameras', { plural: true, one: '{count} camera' }],
['Save keys', { plural: false }],
]);
test('string entry left in English is reported (control)', () => {
const { errors } = checkCatalog(
'de',
{
'Save keys': 'Save keys',
'{count} cameras': { one: 'x {count}', other: 'y {count}' },
},
fixture,
new Set(),
);
assert.equal(errors.length, 1);
assert.match(errors[0], /is still English/);
});
for (const [locale, entry] of [
['de', { one: '{count} camera', other: '{count} cameras' }],
['ja', { other: '{count} cameras' }],
['zh-CN', { other: '{count} cameras' }],
[
'es',
{
one: '{count} camera',
many: '{count} cámaras',
other: '{count} cameras',
},
],
[
'ru',
{
one: '{count} camera',
few: '{count} камеры',
many: '{count} камер',
other: '{count} cameras',
},
],
]) {
test(`${locale}: plural entry with English forms is reported`, () => {
const { errors } = checkCatalog(
locale,
{ 'Save keys': 'Schlüssel', '{count} cameras': entry },
fixture,
new Set(),
);
assert.ok(
errors.some((e) => /is still English/.test(e)),
`expected an "is still English" error, got ${JSON.stringify(errors)}`,
);
});
}
// The `--missing` template, pasted without edits, must fail entry by entry,
// and its plural entries carry every form the language needs.
const messages = extractMessages();
for (const locale of ['de', 'ja', 'es', 'ru']) {
test(`${locale}: an untouched --missing template fails the check entry by entry`, () => {
const template = missingTemplate(locale, {}, messages);
assert.equal(Object.keys(template).length, messages.size);
const categories = new Intl.PluralRules(locale).resolvedOptions()
.pluralCategories;
for (const [text, info] of messages)
if (info.plural)
assert.deepEqual(Object.keys(template[text]), categories, text);
const { missing, errors } = checkCatalog(
locale,
template,
messages,
new Set(),
);
assert.deepEqual(missing, []);
const accepted = [...messages.keys()].filter(
(text) => !errors.some((error) => error.startsWith(`"${text}" `)),
);
assert.deepEqual(accepted, []);
});
}
+137
View File
@@ -0,0 +1,137 @@
{
"es": [
"1090 MHz",
"978 MHz UAT",
"AIS: --",
"AIS: {name}",
"ANIME",
"ASIA",
"AUTO",
"Ambient",
"Anime",
"Austin",
"BRG {value}°",
"BRG —",
"Blues",
"CAL {value}",
"CAL · {badge}",
"CCTV",
"CRS {value}°",
"CRT",
"Country",
"DEST ---°",
"DEST {bearing}",
"Dance",
"ENE",
"ERROR",
"ESE",
"Error: {message}",
"FLIR",
"FLT",
"FM MHZ",
"FOV",
"FOV {value}°",
"FT",
"Folk",
"Funk",
"GEO",
"GOOGLE STREET VIEW",
"Global",
"Global · 60°S–60°N",
"Google Street View",
"HDG",
"HDG {value}°",
"Hip-Hop",
"House",
"Indie",
"Ironbow",
"Jazz",
"LOCAL",
"Landsat 8/9",
"MIC",
"MIL",
"MINI",
"MM",
"MONITOR",
"MSG/S",
"Metal",
"NAV",
"NE",
"NNE",
"NOIR",
"NORMAL",
"NVG",
"Noir",
"Normal",
"POS: {time}Z",
"Plan",
"Pop",
"Punk",
"R&B",
"RADIO",
"RANGE",
"REC",
"Radio",
"Reggae",
"Rock",
"SAR",
"SE",
"SECTOR {lat} {lon}",
"SIG",
"SQUAWK {code} · {status}",
"SRC {value}",
"SSE",
"STD",
"San Francisco",
"Sector",
"Sonar",
"Soul",
"Techno",
"Trance",
"USB {rate} msg/s",
"VISUAL",
"VS",
"WHOT/BHOT",
"WX",
"audio {state}",
"dB",
"fire confidence|nominal",
"ft",
"hPa",
"installation class|BASE",
"km",
"km/h",
"min",
"mini",
"mph",
"nominal",
"panel",
"view band|GLOBAL",
"voice|ERROR",
"{rate} msg/s",
"{speed} kn",
"{type} SPD: {speed} HDG: {heading}",
"{value} KM",
"{value} KM/H",
"{value} KM/S",
"ΔE",
"ΔN",
"▲ {frp} MW"
],
"ru": [
"AIS: --",
"AIS: {name}",
"CCTV",
"CRT",
"FLIR",
"GEO",
"Ironbow",
"Landsat 8/9",
"NAV",
"NVG",
"R&B",
"REC",
"VS",
"WHOT/BHOT"
]
}
+51
View File
@@ -0,0 +1,51 @@
// scripts/i18n.mjs must skip index entries gone from the working tree
// (plain `mv`/`rm` without `git mv`/`git rm`).
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import {
mkdtempSync,
mkdirSync,
writeFileSync,
copyFileSync,
renameSync,
rmSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
function sandbox() {
const root = mkdtempSync(path.join(tmpdir(), 'k23-'));
mkdirSync(path.join(root, 'scripts'));
mkdirSync(path.join(root, 'src/i18n/locales'), { recursive: true });
copyFileSync(
path.join(HERE, '../../scripts/i18n.mjs'),
path.join(root, 'scripts/i18n.mjs'),
);
writeFileSync(path.join(root, 'src/a.js'), "export const x = t('Hello');\n");
writeFileSync(path.join(root, 'index.html'), '<p data-i18n>Hello</p>\n');
const git = (...args) =>
execFileSync('git', args, { cwd: root, encoding: 'utf8' });
git('init', '-q');
git('add', '-A');
git('-c', 'user.email=k@23', '-c', 'user.name=k23', 'commit', '-qm', 'init');
return root;
}
test('extractMessages survives a module renamed with plain mv', async () => {
const root = sandbox();
try {
renameSync(path.join(root, 'src/a.js'), path.join(root, 'src/b.js'));
const mod = await import(
pathToFileURL(path.join(root, 'scripts/i18n.mjs')).href
);
const messages = mod.extractMessages();
assert.ok(messages.has('Hello'));
assert.doesNotThrow(() => mod.findUnmarked());
} finally {
rmSync(root, { recursive: true, force: true });
}
});