Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(i18n): generate en.json from source; check locale files for coherence

Juan Denis600a4e945648
diff --git a/frontend/package.json b/frontend/package.json
index 0759f807..ea37d07f 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -7,11 +7,13 @@
"dev": "vite",
"build": "vite build",
"test": "node --test",
- "lint": "eslint . && node scripts/check-settings-index.mjs && node scripts/check-theme-tokens.mjs && node scripts/check-frontend-boundaries.mjs && node scripts/check-style-ownership.mjs && node scripts/check-status-one-door.mjs && node scripts/check-status-scss.mjs && node scripts/check-i18n-literals.mjs && node scripts/check-intl-door.mjs && node ../scripts/check-html-sinks.mjs",
+ "lint": "eslint . && node scripts/check-settings-index.mjs && node scripts/check-theme-tokens.mjs && node scripts/check-frontend-boundaries.mjs && node scripts/check-style-ownership.mjs && node scripts/check-status-one-door.mjs && node scripts/check-status-scss.mjs && node scripts/check-i18n-literals.mjs && node scripts/check-intl-door.mjs && node scripts/extract-i18n.mjs --check && node scripts/check-i18n.mjs && node ../scripts/check-html-sinks.mjs",
"lint:settings-index": "node scripts/check-settings-index.mjs",
"lint:status": "node scripts/check-status-one-door.mjs",
"lint:i18n": "node scripts/check-i18n-literals.mjs",
"lint:intl": "node scripts/check-intl-door.mjs",
+ "lint:locales": "node scripts/check-i18n.mjs",
+ "i18n:extract": "node scripts/extract-i18n.mjs",
"lint:html-sinks": "node ../scripts/check-html-sinks.mjs",
"lint:frontend-boundaries": "node scripts/check-frontend-boundaries.mjs",
"capture:skeletons": "node scripts/capture-skeletons.mjs",
diff --git a/frontend/scripts/check-i18n.mjs b/frontend/scripts/check-i18n.mjs
new file mode 100644
index 00000000..27aa379f
--- /dev/null
+++ b/frontend/scripts/check-i18n.mjs
@@ -0,0 +1,120 @@
+#!/usr/bin/env node
+// Plan 79 D2 — locale-file integrity.
+//
+// Four assertions, each guarding a failure that is invisible until a user in
+// that language hits it:
+//
+// 1. No orphan keys. A key in es.json that no longer exists in en.json is
+// dead weight at best, and at worst hides that the English moved on.
+// 2. No missing interpolation placeholders. A translation that drops
+// `{{count}}` renders a sentence with a hole in it; one that keeps a
+// placeholder English no longer passes renders literal braces to a user.
+// 3. Same shape. A leaf in one file and a namespace in another means one of
+// the two renders "[object Object]".
+// 4. The manifest and the shipped files agree. A language advertised in the
+// selector with no bundle silently falls back to English, and the user
+// cannot tell the difference between "not translated" and "broken".
+//
+// Coverage (how much of the app is keyed at all) is the separate
+// check-i18n-literals ratchet; this script is about the files being coherent.
+//
+// Usage (from frontend/):
+// node scripts/check-i18n.mjs
+
+import { readFileSync, readdirSync } from 'node:fs';
+import { basename, dirname, extname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const root = resolve(here, '..');
+const localesDir = resolve(root, 'src', 'i18n', 'locales');
+const manifestFile = resolve(root, 'src', 'i18n', 'languages.json');
+
+const DEFAULT_LOCALE = 'en';
+const PLACEHOLDER = /\{\{\s*(\w+)[^}]*\}\}/g;
+
+function readJson(path) {
+ return JSON.parse(readFileSync(path, 'utf8'));
+}
+
+/** Flatten a nested locale tree into dotted key -> string. */
+function flatten(node, prefix = '', out = new Map()) {
+ for (const [key, value] of Object.entries(node)) {
+ const path = prefix ? `${prefix}.${key}` : key;
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
+ flatten(value, path, out);
+ } else {
+ out.set(path, value);
+ }
+ }
+ return out;
+}
+
+function placeholders(value) {
+ return new Set([...String(value).matchAll(PLACEHOLDER)].map((match) => match[1]));
+}
+
+const problems = [];
+
+const manifest = readJson(manifestFile);
+const declared = manifest.languages.map((language) => language.code);
+
+const shipped = readdirSync(localesDir)
+ .filter((name) => extname(name) === '.json')
+ .map((name) => basename(name, '.json'));
+
+// 4. manifest <-> files
+for (const code of declared) {
+ if (!shipped.includes(code)) {
+ problems.push(`languages.json advertises '${code}' but src/i18n/locales/${code}.json is missing`);
+ }
+}
+for (const code of shipped) {
+ if (!declared.includes(code)) {
+ problems.push(`src/i18n/locales/${code}.json ships but languages.json does not advertise '${code}'`);
+ }
+}
+
+const base = flatten(readJson(join(localesDir, `${DEFAULT_LOCALE}.json`)));
+
+for (const code of shipped.filter((name) => name !== DEFAULT_LOCALE)) {
+ const translated = flatten(readJson(join(localesDir, `${code}.json`)));
+
+ for (const [key, value] of translated) {
+ // 1. orphans
+ if (!base.has(key)) {
+ problems.push(`${code}.json: '${key}' does not exist in ${DEFAULT_LOCALE}.json`);
+ continue;
+ }
+ // 3. shape
+ if (typeof value !== 'string') {
+ problems.push(`${code}.json: '${key}' is ${typeof value}, expected a string`);
+ continue;
+ }
+ // 2. placeholders
+ const expected = placeholders(base.get(key));
+ const actual = placeholders(value);
+ for (const name of expected) {
+ if (!actual.has(name)) {
+ problems.push(`${code}.json: '${key}' drops the {{${name}}} placeholder`);
+ }
+ }
+ for (const name of actual) {
+ if (!expected.has(name)) {
+ problems.push(`${code}.json: '${key}' introduces an unknown {{${name}}} placeholder`);
+ }
+ }
+ }
+}
+
+if (problems.length) {
+ console.error('\ni18n locale check failed:\n');
+ for (const problem of problems) console.error(` ${problem}`);
+ console.error('');
+ process.exit(1);
+}
+
+const translatedCount = shipped.filter((name) => name !== DEFAULT_LOCALE).length;
+console.log(
+ `✓ i18n locales: ${base.size} keys, ${translatedCount} translated locale(s), no orphans or placeholder drift.`,
+);
diff --git a/frontend/scripts/extract-i18n.mjs b/frontend/scripts/extract-i18n.mjs
new file mode 100644
index 00000000..106cc2d3
--- /dev/null
+++ b/frontend/scripts/extract-i18n.mjs
@@ -0,0 +1,206 @@
+#!/usr/bin/env node
+// Plan 79 D1 — generate src/i18n/locales/en.json from the source tree.
+//
+// The inline English default IS the source of truth:
+//
+// t('apps.empty.title', 'No applications yet')
+//
+// en.json is generated from those defaults and must never be hand-edited. Two
+// properties follow from that, and they are what make a migration of this size
+// survivable:
+//
+// * A key that has not been extracted yet still renders correct English, so
+// a half-migrated page is never broken and never shows a raw key path to a
+// user.
+// * Renaming the English copy is a one-place edit in the component; the
+// translations for other locales stay keyed and are visibly stale rather
+// than silently wrong.
+//
+// Usage (from frontend/):
+// node scripts/extract-i18n.mjs # write en.json
+// node scripts/extract-i18n.mjs --check # fail if en.json is out of date
+
+import { readFileSync, readdirSync, writeFileSync } from 'node:fs';
+import { dirname, extname, join, relative, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { parse } from 'espree';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const root = resolve(here, '..');
+const srcDir = resolve(root, 'src');
+const outFile = resolve(srcDir, 'i18n', 'locales', 'en.json');
+
+const SKIP_DIRS = new Set(['node_modules', '__mocks__']);
+const SKIP_FILE = /\.(test|spec|stories)\.[jt]sx?$/;
+
+function walk(dir) {
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) return SKIP_DIRS.has(entry.name) ? [] : walk(path);
+ if (!['.js', '.jsx'].includes(extname(entry.name))) return [];
+ if (SKIP_FILE.test(entry.name)) return [];
+ return [path];
+ });
+}
+
+// Bare `t(...)` only -- the `const { t } = useTranslation()` idiom.
+//
+// Deliberately NOT `<anything>.t(...)`: `i18next.t(key, ...)` inside the
+// format door re-dispatches a key it was handed, so its argument is a variable
+// by construction. Flagging that would make the door unextractable while the
+// literal keys at its own call sites are right there to collect.
+function isTranslationCall(node) {
+ return node.type === 'CallExpression'
+ && node.callee.type === 'Identifier'
+ && node.callee.name === 't';
+}
+
+/** The English default declared at a call site, or null. */
+function defaultValueOf(node) {
+ const [, second, third] = node.arguments;
+ if (second?.type === 'Literal' && typeof second.value === 'string') return second.value;
+ for (const candidate of [second, third]) {
+ if (candidate?.type !== 'ObjectExpression') continue;
+ for (const property of candidate.properties) {
+ if (property.type !== 'Property' || property.computed) continue;
+ const key = property.key.name || property.key.value;
+ if (key === 'defaultValue' && property.value.type === 'Literal') {
+ return String(property.value.value);
+ }
+ }
+ }
+ return null;
+}
+
+function visit(node, onCall) {
+ if (!node || typeof node !== 'object') return;
+ if (Array.isArray(node)) {
+ for (const child of node) visit(child, onCall);
+ return;
+ }
+ if (!node.type) return;
+ if (isTranslationCall(node)) onCall(node);
+ for (const key of Object.keys(node)) {
+ if (key === 'type' || key === 'loc' || key === 'range') continue;
+ visit(node[key], onCall);
+ }
+}
+
+export function collect() {
+ const entries = new Map(); // key -> { value, sites: [] }
+ const problems = [];
+
+ for (const path of walk(srcDir)) {
+ const rel = relative(root, path).replaceAll('\\', '/');
+ let ast;
+ try {
+ ast = parse(readFileSync(path, 'utf8'), {
+ ecmaVersion: 'latest',
+ sourceType: 'module',
+ ecmaFeatures: { jsx: true },
+ loc: true,
+ });
+ } catch (error) {
+ problems.push(`${rel}: parse failed — ${error.message}`);
+ continue;
+ }
+
+ visit(ast, (node) => {
+ const first = node.arguments[0];
+ const site = `${rel}:${node.loc.start.line}`;
+
+ if (first?.type !== 'Literal' || typeof first.value !== 'string') {
+ // A computed key cannot be extracted, so its English can only
+ // live in en.json by hand -- which the generated file forbids.
+ problems.push(`${site}: t() called with a non-literal key`);
+ return;
+ }
+ const key = first.value;
+ const value = defaultValueOf(node);
+ if (value === null) {
+ problems.push(`${site}: t('${key}') has no inline English default`);
+ return;
+ }
+
+ const existing = entries.get(key);
+ if (existing && existing.value !== value) {
+ problems.push(
+ `${site}: key '${key}' redefines the English default\n`
+ + ` here: ${JSON.stringify(value)}\n`
+ + ` there: ${JSON.stringify(existing.value)} (${existing.sites[0]})`,
+ );
+ return;
+ }
+ if (existing) {
+ existing.sites.push(site);
+ return;
+ }
+ entries.set(key, { value, sites: [site] });
+ });
+ }
+
+ return { entries, problems };
+}
+
+/** Dotted keys into the nested shape the locale files use. */
+export function nest(entries) {
+ const tree = {};
+ const problems = [];
+
+ for (const key of [...entries.keys()].sort()) {
+ const parts = key.split('.');
+ let node = tree;
+ let ok = true;
+ for (const part of parts.slice(0, -1)) {
+ if (typeof node[part] === 'string') {
+ problems.push(`key '${key}' nests under '${part}', which is already a string`);
+ ok = false;
+ break;
+ }
+ node[part] = node[part] || {};
+ node = node[part];
+ }
+ if (!ok) continue;
+ const leaf = parts[parts.length - 1];
+ if (node[leaf] && typeof node[leaf] === 'object') {
+ problems.push(`key '${key}' is both a string and a namespace`);
+ continue;
+ }
+ node[leaf] = entries.get(key).value;
+ }
+
+ return { tree, problems };
+}
+
+const { entries, problems: collectProblems } = collect();
+const { tree, problems: nestProblems } = nest(entries);
+const problems = [...collectProblems, ...nestProblems];
+
+if (problems.length) {
+ console.error('\ni18n extraction failed:\n');
+ for (const problem of problems) console.error(` ${problem}`);
+ console.error('\n Every t() needs a literal key and an inline English default:');
+ console.error(" t('apps.empty.title', 'No applications yet')\n");
+ process.exit(1);
+}
+
+const serialized = `${JSON.stringify(tree, null, 4)}\n`;
+
+if (process.argv.includes('--check')) {
+ let current = '';
+ try {
+ current = readFileSync(outFile, 'utf8');
+ } catch {
+ current = '';
+ }
+ if (current !== serialized) {
+ console.error('\nen.json is out of date — it is generated, not written.\n');
+ console.error(' node scripts/extract-i18n.mjs\n');
+ process.exit(1);
+ }
+ console.log(`✓ en.json is current (${entries.size} keys).`);
+ process.exit(0);
+}
+
+writeFileSync(outFile, serialized);
+console.log(`✓ wrote ${relative(root, outFile).replaceAll('\\', '/')} — ${entries.size} keys.`);
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 0967ef42..f6ce6a93 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -1 +1,17 @@
-{}
+{
+ "common": {
+ "duration": {
+ "hours": "{{count}}h",
+ "hoursMinutes": "{{hours}}h {{minutes}}m",
+ "minutes": "{{count}}m",
+ "minutesSeconds": "{{minutes}}m {{seconds}}s",
+ "seconds": "{{count}}s"
+ },
+ "time": {
+ "daysShort": "{{count}}d",
+ "hoursShort": "{{count}}h",
+ "justNow": "just now",
+ "minutesShort": "{{count}}m"
+ }
+ }
+}
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
new file mode 100644
index 00000000..f7a16b70
--- /dev/null
+++ b/frontend/src/i18n/locales/es.json
@@ -0,0 +1,17 @@
+{
+ "common": {
+ "duration": {
+ "hours": "{{count}} h",
+ "hoursMinutes": "{{hours}} h {{minutes}} min",
+ "minutes": "{{count}} min",
+ "minutesSeconds": "{{minutes}} min {{seconds}} s",
+ "seconds": "{{count}} s"
+ },
+ "time": {
+ "daysShort": "{{count}} d",
+ "hoursShort": "{{count}} h",
+ "justNow": "ahora mismo",
+ "minutesShort": "{{count}} min"
+ }
+ }
+}
diff --git a/frontend/src/utils/intl.js b/frontend/src/utils/intl.js
index 8f27f9e3..02cb14c1 100644
--- a/frontend/src/utils/intl.js
+++ b/frontend/src/utils/intl.js
@@ -52,8 +52,12 @@ function cached(kind, options, build) {
/**
* Translate with an inline English default, tolerating an uninitialised
* i18next (node tooling, tests, a crash before the provider mounts).
+ *
+ * Named `t` so the extractor sees the literal keys at the call sites below; a
+ * differently-named wrapper would make this file's copy invisible to en.json
+ * generation, which is how copy quietly stops being translatable.
*/
-function translate(key, fallback, values) {
+function t(key, fallback, values) {
if (i18next.isInitialized) {
return i18next.t(key, { defaultValue: fallback, ...values });
}
@@ -154,16 +158,16 @@ export function formatRelativeShort(value, { fallback = '' } = {}) {
if (!date) return fallback;
const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
- if (seconds < 45) return translate('common.time.justNow', 'just now');
+ if (seconds < 45) return t('common.time.justNow', 'just now');
const minutes = Math.floor(seconds / 60);
- if (minutes < 60) return translate('common.time.minutesShort', '{{count}}m', { count: minutes });
+ if (minutes < 60) return t('common.time.minutesShort', '{{count}}m', { count: minutes });
const hours = Math.floor(minutes / 60);
- if (hours < 24) return translate('common.time.hoursShort', '{{count}}h', { count: hours });
+ if (hours < 24) return t('common.time.hoursShort', '{{count}}h', { count: hours });
const days = Math.floor(hours / 24);
- if (days < 7) return translate('common.time.daysShort', '{{count}}d', { count: days });
+ if (days < 7) return t('common.time.daysShort', '{{count}}d', { count: days });
return formatDate(date, { style: 'short' });
}
@@ -174,22 +178,22 @@ export function formatDuration(seconds, { fallback = '-' } = {}) {
if (total === null || total < 0) return fallback;
if (total < 60) {
- return translate('common.duration.seconds', '{{count}}s', { count: Math.round(total) });
+ return t('common.duration.seconds', '{{count}}s', { count: Math.round(total) });
}
const minutes = Math.floor(total / 60);
if (minutes < 60) {
const rest = Math.round(total % 60);
return rest
- ? translate('common.duration.minutesSeconds', '{{minutes}}m {{seconds}}s',
+ ? t('common.duration.minutesSeconds', '{{minutes}}m {{seconds}}s',
{ minutes, seconds: rest })
- : translate('common.duration.minutes', '{{count}}m', { count: minutes });
+ : t('common.duration.minutes', '{{count}}m', { count: minutes });
}
const hours = Math.floor(minutes / 60);
const restMinutes = minutes % 60;
return restMinutes
- ? translate('common.duration.hoursMinutes', '{{hours}}h {{minutes}}m',
+ ? t('common.duration.hoursMinutes', '{{hours}}h {{minutes}}m',
{ hours, minutes: restMinutes })
- : translate('common.duration.hours', '{{count}}h', { count: hours });
+ : t('common.duration.hours', '{{count}}h', { count: hours });
}
// -------------------------------------------------------------- numbers ---