Refactor code structure for improved readability and maintainability

This commit is contained in:
shuaiplus
2026-04-29 03:23:04 +08:00
parent 29a846c562
commit 85147e1569
14 changed files with 2748 additions and 881 deletions
+32
View File
@@ -0,0 +1,32 @@
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const localeDir = path.join(__dirname, '..', 'webapp', 'src', 'lib', 'i18n', 'locales');
function readLocale(fileName, variableName) {
let code = fs.readFileSync(path.join(localeDir, fileName), 'utf8');
code = code
.replace(/const (\w+): Record<string, string> =/g, 'const $1 =')
.replace(/export default \w+;\s*$/m, '');
code += `\nresult = ${variableName};`;
const sandbox = { result: null };
vm.createContext(sandbox);
vm.runInContext(code, sandbox, { filename: fileName });
return sandbox.result;
}
function writeLocale(fileName, variableName, table, header) {
const body = JSON.stringify(table, null, 2);
fs.writeFileSync(
path.join(localeDir, fileName),
`${header}\nconst ${variableName}: Record<string, string> = ${body};\n\nexport default ${variableName};\n`,
'utf8'
);
}
module.exports = {
localeDir,
readLocale,
writeLocale,
};
+42
View File
@@ -0,0 +1,42 @@
const { readLocale } = require('./i18n-utils.cjs');
const localeFiles = [
['en', 'en.ts', 'en'],
['zh-CN', 'zh-CN.ts', 'zhCN'],
['zh-TW', 'zh-TW.ts', 'zhTW'],
['ru', 'ru.ts', 'ru'],
];
const locales = Object.fromEntries(
localeFiles.map(([locale, fileName, variableName]) => [locale, readLocale(fileName, variableName)])
);
const base = locales.en;
const baseKeys = Object.keys(base).sort();
const placeholderRe = /\{\w+\}/g;
const errors = [];
for (const [locale, table] of Object.entries(locales)) {
const keys = Object.keys(table).sort();
const missing = baseKeys.filter((key) => !(key in table));
const extra = keys.filter((key) => !baseKeys.includes(key));
if (missing.length || extra.length) {
errors.push({ locale, missing, extra });
}
for (const key of baseKeys) {
const basePlaceholders = Array.from(String(base[key]).matchAll(placeholderRe), (match) => match[0]).sort().join('|');
const localePlaceholders = Array.from(String(table[key]).matchAll(placeholderRe), (match) => match[0]).sort().join('|');
if (basePlaceholders !== localePlaceholders) {
errors.push({ locale, key, basePlaceholders, localePlaceholders });
}
}
}
console.log(JSON.stringify({
counts: Object.fromEntries(Object.entries(locales).map(([locale, table]) => [locale, Object.keys(table).length])),
errors,
}, null, 2));
if (errors.length) {
process.exit(1);
}