enforce i18n key order (#3430)

This commit is contained in:
Kevin B. authored and GitHub committed 2026-11-23 13:11:15 -06:00
1 parent 7f5fb7535a
commit d2ccbc0628
8 files changed
+46 -26

No files matched your search

+1 -1
View File
@@ -133,7 +133,7 @@ When changing a key in `en.json`:
```shell
make generate-translation-types # regenerate messages.generated.ts
make sync-translations # also translates new keys in the other locales (but needs DEEPL_API_KEY)
make sync-translations # translates new keys in the other locales (needs DEEPL_API_KEY)
make check-translations # run the i18n checks
```
+1 -1
View File
@@ -21,7 +21,7 @@
"i18n:types": "node scripts/i18n/index.ts types",
"i18n:sync": "node scripts/i18n/index.ts sync",
"i18n:cleanup": "node scripts/i18n/index.ts sync --cleanup",
"i18n:enforce-order": "node scripts/i18n/index.ts sync --enforce-order",
"i18n:reorder": "node scripts/i18n/index.ts sync --reorder",
"icons:sync": "node ./scripts/build-icon-subset.js",
"icons:check": "node ./scripts/build-icon-subset.js --check",
"test": "vitest run "
@@ -47,8 +47,8 @@ describe("sync with a different shape in a locale", () => {
for (const file of fs.readdirSync(dir)) fs.rmSync(path.join(dir, file));
});
const run = (options: { enforceOrder?: boolean; cleanup?: boolean } = {}) =>
syncTranslations({ enforceOrder: false, cleanup: false, ...options });
const run = (options: { reorder?: boolean; cleanup?: boolean } = {}) =>
syncTranslations({ reorder: false, cleanup: false, ...options });
describe("an object where en.json has a string", () => {
beforeEach(() => {
@@ -66,8 +66,8 @@ describe("sync with a different shape in a locale", () => {
expect(read("de.json")).toEqual({ general: {} });
});
it("removes the obsolete subtree when enforcing the order", async () => {
expect(await run({ enforceOrder: true })).toBe(0);
it("removes the obsolete subtree when reordering", async () => {
expect(await run({ reorder: true })).toBe(0);
expect(read("de.json")).toEqual({ general: {} });
});
});
+9 -7
View File
@@ -1,15 +1,15 @@
/**
* npm run i18n:types regenerate messages.generated.ts
* npm run i18n:sync regenerate the types, translate new keys (DEEPL_API_KEY)
* npm run i18n:enforce-order regenerate the types, reorder locales like en.json
* npm run i18n:sync regenerate the types, reorder, translate new keys (DEEPL_API_KEY)
* npm run i18n:reorder regenerate the types, reorder locales like en.json
* npm run i18n:cleanup regenerate the types, remove obsolete keys
* npm run i18n:check locale list, translations, types, dynamic keys, unused keys and raw text
* npm run i18n:check locale list, translations, key order, types, dynamic keys, unused keys and raw text
* npm run i18n:check:strict checks for raw `$t` and 'vue-i18n' imports, including JS files
*/
import { checkLocaleRegistry, checkRawText, checkUnusedKeys } from "./check.ts";
import { report } from "./shared.ts";
import { checkTranslations, syncTranslations } from "./sync.ts";
import { checkOrder, checkTranslations, syncTranslations } from "./sync.ts";
import { checkTypes, writeTypes } from "./types.ts";
const [command, ...flags] = process.argv.slice(2);
@@ -19,19 +19,21 @@ try {
if (command === "types") {
process.exitCode = writeTypes();
} else if (command === "sync") {
process.exitCode = writeTypes() || (await syncTranslations({ enforceOrder: has("--enforce-order"), cleanup: has("--cleanup") }));
process.exitCode = writeTypes() || (await syncTranslations({ reorder: has("--reorder"), cleanup: has("--cleanup") }));
} else if (command === "check") {
const translations = checkTranslations();
const problems = [...checkLocaleRegistry(), ...translations, ...checkTypes(has("--strict")), ...checkUnusedKeys(), ...checkRawText()];
const order = checkOrder();
const problems = [...checkLocaleRegistry(), ...translations, ...order, ...checkTypes(has("--strict")), ...checkUnusedKeys(), ...checkRawText()];
if (problems.length) {
report(problems);
if (translations.length) console.error("Run: npm run i18n:sync (or i18n:cleanup)");
if (order.length) console.error("Run: npm run i18n:reorder");
process.exitCode = 1;
} else {
console.log("✅ i18n checks passed");
}
} else {
console.error("Usage: node scripts/i18n/index.ts <types | sync [--enforce-order | --cleanup] | check [--strict]>");
console.error("Usage: node scripts/i18n/index.ts <types | sync [--reorder | --cleanup] | check [--strict]>");
process.exitCode = 1;
}
} catch (error) {
+28 -10
View File
@@ -48,6 +48,24 @@ export function checkTranslations(): string[] {
return problems;
}
export function checkOrder(): string[] {
const master = Object.keys(readLocale("en.json"));
const problems: string[] = [];
for (const file of translationFiles()) {
let keys: string[];
try {
keys = Object.keys(readLocale(file));
} catch {
continue; // checkTranslations reports it
}
const actual = keys.filter((key) => master.includes(key));
const expected = master.filter((key) => keys.includes(key));
const index = expected.findIndex((key, i) => key !== actual[i]);
if (index !== -1) problems.push(`${file}: keys are not in the order of en.json"`);
}
return problems;
}
async function translateText(text: string, targetLanguage: string, keyPath: string): Promise<string | null> {
if (!text.trim()) {
console.warn(`Skipping translation for empty text: "${text}"`);
@@ -101,7 +119,7 @@ async function processKeys(
target: Tree,
lang: string,
parents: string[],
enforceOrder: boolean,
reorder: boolean,
cleanup: boolean,
): Promise<boolean | "UNSUPPORTED"> {
let changed = false;
@@ -123,7 +141,7 @@ async function processKeys(
}
const child = target[key];
if (isTree(child)) {
const result = await processKeys(masterValue, child, lang, [...parents, key], enforceOrder, cleanup);
const result = await processKeys(masterValue, child, lang, [...parents, key], reorder, cleanup);
if (result === "UNSUPPORTED") {
console.log(`Skipping translation for "${lang}" due to unsupported structure.`);
return result;
@@ -134,7 +152,7 @@ async function processKeys(
if (typeof masterValue === "string") {
const existing = target[key];
if (!Object.hasOwn(target, key) || existing === "" || existing === null) {
if (enforceOrder) {
if (reorder) {
console.log(`Skipping new key "${keyPath}" for ${lang}.json`);
} else {
const translated = await translateText(masterValue, lang, keyPath);
@@ -162,21 +180,21 @@ async function processKeys(
return changed;
}
export async function syncTranslations({ enforceOrder, cleanup }: { enforceOrder: boolean; cleanup: boolean }): Promise<number> {
const reorder = enforceOrder && !cleanup;
export async function syncTranslations({ reorder, cleanup }: { reorder: boolean; cleanup: boolean }): Promise<number> {
const orderKeys = !cleanup;
if (!enforceOrder && !cleanup) {
if (!reorder && !cleanup) {
const apiKey = process.env.DEEPL_API_KEY;
if (!apiKey) {
console.error("❌ Missing DEEPL_API_KEY in environment.");
return 1;
}
translator = new DeepLClient(apiKey);
console.warn("--- Using DeepL API for translation ---");
console.warn("--- Using DeepL API for translation, keys will be reordered afterwards ---");
} else if (cleanup) {
console.warn("--- Only obsolete keys will be removed - No translations, or reordering will happen ---");
} else {
console.warn("--- Enforcing order of all files to match master language (no translations will be performed) ---");
console.warn("--- Reordering the keys of all files to match master language (no translations will be performed) ---");
}
const master = readJson(path.join(localesDir, "en.json")) as Tree;
@@ -205,7 +223,7 @@ export async function syncTranslations({ enforceOrder, cleanup }: { enforceOrder
}
let orderChanged = false;
if (reorder) {
if (orderKeys) {
target = reorderObject(target, master) as Tree;
orderChanged = JSON.stringify(original) !== JSON.stringify(target);
if (orderChanged) console.log(`- Reordered keys in ${lang}.json`);
@@ -224,7 +242,7 @@ export async function syncTranslations({ enforceOrder, cleanup }: { enforceOrder
}
if (cleanup) console.log("\n✅ Cleanup complete (obsolete keys removed).");
else if (reorder) console.log("\n✅ Enforce order complete.");
else if (reorder) console.log("\n✅ Reorder complete.");
else console.log("\n✅ Translation synchronization complete (via DeepL).");
return 0;
}
+1 -1
View File
@@ -104,7 +104,7 @@
"replace": "Remplacer{suffix}",
"save": "Enregistrer{suffix}",
"select": "Sélectionner{suffix}",
"share": "Partager{suffix}",
"share": "Partage{suffix}",
"update": "Mettre à jour{suffix}",
"upload": "Importer{suffix}",
"openFile": "Ouvrir un fichier{suffix}",
+1 -1
View File
@@ -887,7 +887,7 @@
"maxConcurrentUploadHelp": "Максимальное количество одновременных загрузок. Более высокие значения обычно работают лучше, но это зависит от многих факторов.",
"uploadChunkSizeMb": "Размер загружаемого фрагмента в МБ",
"uploadChunkSizeMbHelp": "Обычно от 5 до 50 МБ, меньший размер лучше для нестабильных или ограниченных соединений. При установке значения 0 отключается функция \"кусковой загрузки\".",
"downloadChunkSizeMb": "Размер загружаемого фрагмента в МБ",
"downloadChunkSizeMb": "Размер скачиваемого фрагмента в МБ",
"downloadChunkSizeMbHelp": "Размер куска для кусковых загрузок. Файлы, превышающие этот размер, будут загружаться кусками, чтобы предотвратить проблемы с таймаутом (например, ошибки Cloudflare 524). Установка значения 0 отключает загрузку кусками.",
"uploadStallTimeoutSeconds": "Тайм-аут зависшей загрузки в секундах",
"uploadStallTimeoutSecondsHelp": "Сколько секунд загрузка может идти без прогресса, прежде чем будет приостановлена. Увеличьте значение при медленном или нестабильном соединении, а также если файлы читаются с медленных дисков. Значения меньше 1 означают значение по умолчанию — 10 секунд.",
+1 -1
View File
@@ -129,7 +129,7 @@ generate-translation-types:
cd frontend && npm run i18n:types
reorder-translations:
cd frontend && npm run i18n:enforce-order
cd frontend && npm run i18n:reorder
cleanup-translations:
cd frontend && npm run i18n:cleanup