-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathi18n.gen.cjs
More file actions
77 lines (61 loc) · 1.86 KB
/
i18n.gen.cjs
File metadata and controls
77 lines (61 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const fs = require("fs");
const path = require("path");
const INPUT_DIR = path.resolve(__dirname, "src", "langs"); // folder with JSON files
const OUTPUT_FILE = path.resolve(__dirname, "src", "utils", "i18n.ts");
/**
* Recursively find all JSON files in a directory
*/
function getJsonFiles(dir) {
const entries = fs.readdirSync(dir, {withFileTypes: true});
let files = [];
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
files = files.concat(getJsonFiles(fullPath));
} else if (entry.isFile() && entry.name.endsWith(".json")) {
files.push(fullPath);
}
}
return files;
}
/**
* Recursively build i18n structure
*/
function buildI18nObject(obj, group, currentPath = []) {
const result = {};
for (const [key, value] of Object.entries(obj)) {
if (key.startsWith("$")) continue;
if (typeof value === "string") {
result[key] = [group, [...currentPath, key]];
} else if (typeof value === "object" && value !== null) {
result[key] = buildI18nObject(value, group, [...currentPath, key]);
}
}
return result;
}
/**
* Main
*/
const i18n = {};
const jsonFiles = getJsonFiles(INPUT_DIR);
for (const file of jsonFiles) {
const content = JSON.parse(fs.readFileSync(file, "utf8"));
const group = content.$group;
if (!group) {
console.warn(`Skipping ${file} (missing $group)`);
continue;
}
if (!i18n[group]) {
i18n[group] = {};
}
Object.assign(
i18n[group],
buildI18nObject(content, group)
);
}
/**
* Write TypeScript file
*/
const tsOutput = `const I18n = ${JSON.stringify(i18n)} as const;\nexport default I18n;\n`;
fs.writeFileSync(OUTPUT_FILE, tsOutput, "utf8");
console.log(`✅ I18n file generated at: ${OUTPUT_FILE}`);