@oxog/i18n-cli 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -242
- package/dist/cli.js +521 -325
- package/package.json +17 -7
package/dist/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { promises } from 'fs';
|
|
3
|
-
import
|
|
2
|
+
import { readFileSync, promises } from 'fs';
|
|
3
|
+
import path3, { join, relative, sep } from 'path';
|
|
4
4
|
import { readdir, stat } from 'fs/promises';
|
|
5
5
|
import { createInterface } from 'readline';
|
|
6
6
|
|
|
@@ -33,182 +33,86 @@ var colors = {
|
|
|
33
33
|
primary: colorize(36),
|
|
34
34
|
secondary: colorize(90)
|
|
35
35
|
};
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
this.programVersion = version;
|
|
54
|
-
return this;
|
|
55
|
-
}
|
|
56
|
-
option(flags, description, defaultValue) {
|
|
57
|
-
this.globalOptions.push({ flags, description, defaultValue });
|
|
58
|
-
return this;
|
|
59
|
-
}
|
|
60
|
-
command(name) {
|
|
61
|
-
const command = {
|
|
62
|
-
name,
|
|
63
|
-
description: "",
|
|
64
|
-
options: []
|
|
65
|
-
};
|
|
66
|
-
this.commands.set(name, command);
|
|
67
|
-
return new CommandBuilder(command);
|
|
68
|
-
}
|
|
69
|
-
async parse(argv = process.argv) {
|
|
70
|
-
const args = argv.slice(2);
|
|
71
|
-
if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
|
|
72
|
-
this.showHelp();
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
75
|
-
if (args.includes("--version") || args.includes("-V")) {
|
|
76
|
-
console.log(this.programVersion);
|
|
77
|
-
return;
|
|
78
|
-
}
|
|
79
|
-
const commandName = args[0];
|
|
80
|
-
const command = this.commands.get(commandName);
|
|
81
|
-
if (!command) {
|
|
82
|
-
console.error(colors.red(`Unknown command: ${commandName}`));
|
|
83
|
-
this.showHelp();
|
|
84
|
-
process.exit(1);
|
|
85
|
-
}
|
|
86
|
-
const options = this.parseOptions(args.slice(1), [...this.globalOptions, ...command.options]);
|
|
87
|
-
if (command.action) {
|
|
88
|
-
try {
|
|
89
|
-
await command.action(options);
|
|
90
|
-
} catch (error) {
|
|
91
|
-
console.error(colors.red("Error:"), error instanceof Error ? error.message : String(error));
|
|
92
|
-
process.exit(1);
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
parseOptions(args, optionDefinitions) {
|
|
97
|
-
const options = {};
|
|
98
|
-
const optionMap = /* @__PURE__ */ new Map();
|
|
99
|
-
for (const option of optionDefinitions) {
|
|
100
|
-
const [shortFlag, longFlag] = this.parseFlags(option.flags);
|
|
101
|
-
if (shortFlag) optionMap.set(shortFlag, option);
|
|
102
|
-
if (longFlag) optionMap.set(longFlag, option);
|
|
103
|
-
if (option.defaultValue !== void 0) {
|
|
104
|
-
const key = this.getOptionKey(option.flags);
|
|
105
|
-
options[key] = option.defaultValue;
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
for (let i = 0; i < args.length; i++) {
|
|
109
|
-
const arg = args[i];
|
|
110
|
-
if (arg.startsWith("-")) {
|
|
111
|
-
const option = optionMap.get(arg);
|
|
112
|
-
if (!option) {
|
|
113
|
-
console.error(colors.red(`Unknown option: ${arg}`));
|
|
114
|
-
process.exit(1);
|
|
115
|
-
}
|
|
116
|
-
const key = this.getOptionKey(option.flags);
|
|
117
|
-
if (this.isBooleanOption(option)) {
|
|
118
|
-
options[key] = true;
|
|
119
|
-
} else {
|
|
120
|
-
i++;
|
|
121
|
-
if (i >= args.length) {
|
|
122
|
-
console.error(colors.red(`Option ${arg} requires a value`));
|
|
123
|
-
process.exit(1);
|
|
36
|
+
async function glob(pattern, cwd = process.cwd()) {
|
|
37
|
+
const results = [];
|
|
38
|
+
const regex = globToRegex(pattern);
|
|
39
|
+
async function walk(dir) {
|
|
40
|
+
try {
|
|
41
|
+
const entries = await readdir(dir);
|
|
42
|
+
for (const entry of entries) {
|
|
43
|
+
const fullPath = join(dir, entry);
|
|
44
|
+
const stats2 = await stat(fullPath);
|
|
45
|
+
if (stats2.isDirectory()) {
|
|
46
|
+
if (shouldDescend(pattern, relative(cwd, fullPath))) {
|
|
47
|
+
await walk(fullPath);
|
|
48
|
+
}
|
|
49
|
+
} else if (stats2.isFile()) {
|
|
50
|
+
const relativePath = relative(cwd, fullPath).replace(/\\/g, "/");
|
|
51
|
+
if (regex.test(relativePath)) {
|
|
52
|
+
results.push(fullPath);
|
|
124
53
|
}
|
|
125
|
-
options[key] = args[i];
|
|
126
54
|
}
|
|
127
55
|
}
|
|
56
|
+
} catch (error) {
|
|
128
57
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
58
|
+
}
|
|
59
|
+
await walk(cwd);
|
|
60
|
+
return results.sort();
|
|
61
|
+
}
|
|
62
|
+
function globToRegex(pattern) {
|
|
63
|
+
const normalized = pattern.replace(/\\/g, "/").replace(/^(?:\.\/)+/, "");
|
|
64
|
+
let source = "";
|
|
65
|
+
for (let i = 0; i < normalized.length; i++) {
|
|
66
|
+
const char = normalized[i];
|
|
67
|
+
if (char === "*") {
|
|
68
|
+
if (normalized[i + 1] === "*") {
|
|
69
|
+
if (normalized[i + 2] === "/") {
|
|
70
|
+
source += "(?:.*/)?";
|
|
71
|
+
i += 2;
|
|
72
|
+
} else {
|
|
73
|
+
source += ".*";
|
|
74
|
+
i += 1;
|
|
135
75
|
}
|
|
76
|
+
} else {
|
|
77
|
+
source += "[^/]*";
|
|
136
78
|
}
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
longFlag = trimmed;
|
|
148
|
-
} else if (trimmed.startsWith("-")) {
|
|
149
|
-
shortFlag = trimmed;
|
|
79
|
+
} else if (char === "?") {
|
|
80
|
+
source += "[^/]";
|
|
81
|
+
} else if (char === "{") {
|
|
82
|
+
const end = normalized.indexOf("}", i);
|
|
83
|
+
if (end === -1) {
|
|
84
|
+
source += "\\{";
|
|
85
|
+
} else {
|
|
86
|
+
const options = normalized.slice(i + 1, end).split(",").map((option) => option.replace(/[.+^$()|[\]\\]/g, "\\$&"));
|
|
87
|
+
source += `(?:${options.join("|")})`;
|
|
88
|
+
i = end;
|
|
150
89
|
}
|
|
90
|
+
} else {
|
|
91
|
+
source += char.replace(/[.+^$()|[\]\\{}]/g, "\\$&");
|
|
151
92
|
}
|
|
152
|
-
return [shortFlag, longFlag];
|
|
153
|
-
}
|
|
154
|
-
getOptionKey(flags) {
|
|
155
|
-
const [, longFlag] = this.parseFlags(flags);
|
|
156
|
-
if (longFlag) {
|
|
157
|
-
return longFlag.replace(/^--/, "").replace(/\s*[<\[].*$/, "").replace(/-/g, "_");
|
|
158
|
-
}
|
|
159
|
-
const [shortFlag] = this.parseFlags(flags);
|
|
160
|
-
return shortFlag.replace(/^-/, "").replace(/\s*[<\[].*$/, "");
|
|
161
93
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
if (
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
console.log(` ${name.padEnd(15)} ${command.description}`);
|
|
178
|
-
}
|
|
179
|
-
console.log();
|
|
180
|
-
}
|
|
181
|
-
if (this.globalOptions.length > 0) {
|
|
182
|
-
console.log(colors.bold("Options:"));
|
|
183
|
-
for (const option of this.globalOptions) {
|
|
184
|
-
console.log(` ${option.flags.padEnd(20)} ${option.description}`);
|
|
185
|
-
}
|
|
186
|
-
console.log();
|
|
94
|
+
return new RegExp(`^${source}$`);
|
|
95
|
+
}
|
|
96
|
+
function shouldDescend(rawPattern, currentPath) {
|
|
97
|
+
const pattern = rawPattern.replace(/\\/g, "/").replace(/^(?:\.\/)+/, "");
|
|
98
|
+
if (/(^|[\\/])node_modules$/.test(currentPath) && !pattern.includes("node_modules")) return false;
|
|
99
|
+
if (pattern.includes("**")) return true;
|
|
100
|
+
const patternParts = pattern.split("/");
|
|
101
|
+
const currentParts = currentPath.split(sep);
|
|
102
|
+
if (currentParts.length >= patternParts.length) return false;
|
|
103
|
+
for (let i = 0; i < currentParts.length; i++) {
|
|
104
|
+
const patternPart = patternParts[i];
|
|
105
|
+
const currentPart = currentParts[i];
|
|
106
|
+
if (patternPart === "**") return true;
|
|
107
|
+
if (patternPart !== currentPart && !isGlobMatch(patternPart, currentPart)) {
|
|
108
|
+
return false;
|
|
187
109
|
}
|
|
188
|
-
console.log(colors.bold("Global Options:"));
|
|
189
|
-
console.log(" -h, --help Show help");
|
|
190
|
-
console.log(" -V, --version Show version");
|
|
191
110
|
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
description(desc) {
|
|
198
|
-
this.command.description = desc;
|
|
199
|
-
return this;
|
|
200
|
-
}
|
|
201
|
-
option(flags, description, defaultValue) {
|
|
202
|
-
this.command.options.push({ flags, description, defaultValue });
|
|
203
|
-
return this;
|
|
204
|
-
}
|
|
205
|
-
action(fn) {
|
|
206
|
-
this.command.action = fn;
|
|
207
|
-
return this;
|
|
208
|
-
}
|
|
209
|
-
};
|
|
210
|
-
function createCommander() {
|
|
211
|
-
return new Commander();
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
function isGlobMatch(pattern, text) {
|
|
114
|
+
const regex = globToRegex(pattern);
|
|
115
|
+
return regex.test(text);
|
|
212
116
|
}
|
|
213
117
|
|
|
214
118
|
// src/utils/spinner.ts
|
|
@@ -284,77 +188,32 @@ var Spinner = class {
|
|
|
284
188
|
function createSpinner(text = "") {
|
|
285
189
|
return new Spinner(text);
|
|
286
190
|
}
|
|
287
|
-
async function glob(pattern, cwd = process.cwd()) {
|
|
288
|
-
const results = [];
|
|
289
|
-
const regex = globToRegex(pattern);
|
|
290
|
-
async function walk(dir) {
|
|
291
|
-
try {
|
|
292
|
-
const entries = await readdir(dir);
|
|
293
|
-
for (const entry of entries) {
|
|
294
|
-
const fullPath = join(dir, entry);
|
|
295
|
-
const stats2 = await stat(fullPath);
|
|
296
|
-
if (stats2.isDirectory()) {
|
|
297
|
-
if (shouldDescend(pattern, relative(cwd, fullPath))) {
|
|
298
|
-
await walk(fullPath);
|
|
299
|
-
}
|
|
300
|
-
} else if (stats2.isFile()) {
|
|
301
|
-
const relativePath = relative(cwd, fullPath).replace(/\\/g, "/");
|
|
302
|
-
if (regex.test(relativePath)) {
|
|
303
|
-
results.push(fullPath);
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
} catch (error) {
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
await walk(cwd);
|
|
311
|
-
return results.sort();
|
|
312
|
-
}
|
|
313
|
-
function globToRegex(pattern) {
|
|
314
|
-
pattern = pattern.replace(/\\/g, "/");
|
|
315
|
-
let regex = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "___DOUBLESTAR___").replace(/\*/g, "___STAR___").replace(/___DOUBLESTAR___/g, ".*").replace(/\?/g, "___QUESTION___");
|
|
316
|
-
regex = regex.replace(/\\\{([^}]+)\\\}/g, (_, group) => {
|
|
317
|
-
const options = group.split(",").join("|");
|
|
318
|
-
return `(${options})`;
|
|
319
|
-
});
|
|
320
|
-
regex = regex.replace(/\//g, "[\\/\\\\]");
|
|
321
|
-
regex = regex.replace(/___STAR___/g, "[^\\/\\\\]*").replace(/___QUESTION___/g, "[^\\/\\\\]");
|
|
322
|
-
return new RegExp(`^${regex}$`);
|
|
323
|
-
}
|
|
324
|
-
function shouldDescend(pattern, currentPath) {
|
|
325
|
-
if (pattern.includes("**")) return true;
|
|
326
|
-
const patternParts = pattern.split("/");
|
|
327
|
-
const currentParts = currentPath.split(sep);
|
|
328
|
-
if (currentParts.length >= patternParts.length) return false;
|
|
329
|
-
for (let i = 0; i < currentParts.length; i++) {
|
|
330
|
-
const patternPart = patternParts[i];
|
|
331
|
-
const currentPart = currentParts[i];
|
|
332
|
-
if (patternPart === "**") return true;
|
|
333
|
-
if (patternPart !== currentPart && !isGlobMatch(patternPart, currentPart)) {
|
|
334
|
-
return false;
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
return true;
|
|
338
|
-
}
|
|
339
|
-
function isGlobMatch(pattern, text) {
|
|
340
|
-
const regex = globToRegex(pattern);
|
|
341
|
-
return regex.test(text);
|
|
342
|
-
}
|
|
343
191
|
|
|
344
192
|
// src/commands/compile.ts
|
|
345
193
|
async function compile(options) {
|
|
346
194
|
const spinner = createSpinner("Compiling translations").start();
|
|
347
195
|
try {
|
|
348
|
-
const pattern =
|
|
196
|
+
const pattern = path3.join(options.input, "*.json");
|
|
349
197
|
const files = await glob(pattern);
|
|
350
198
|
await promises.mkdir(options.output, { recursive: true });
|
|
351
199
|
let compiledCount = 0;
|
|
352
200
|
for (const file of files) {
|
|
353
|
-
const locale =
|
|
201
|
+
const locale = path3.basename(file, ".json");
|
|
354
202
|
const content = await promises.readFile(file, "utf-8");
|
|
355
|
-
|
|
203
|
+
let translations;
|
|
204
|
+
try {
|
|
205
|
+
translations = JSON.parse(content);
|
|
206
|
+
} catch (parseError) {
|
|
207
|
+
spinner.fail(`Failed to parse ${file}`);
|
|
208
|
+
console.error(
|
|
209
|
+
colors.red(
|
|
210
|
+
` JSON parse error: ${parseError instanceof Error ? parseError.message : String(parseError)}`
|
|
211
|
+
)
|
|
212
|
+
);
|
|
213
|
+
process.exit(1);
|
|
214
|
+
}
|
|
356
215
|
const optimized = optimizeTranslations(translations);
|
|
357
|
-
const outputFile =
|
|
216
|
+
const outputFile = path3.join(options.output, `${locale}.${options.format}`);
|
|
358
217
|
switch (options.format) {
|
|
359
218
|
case "json":
|
|
360
219
|
await promises.writeFile(outputFile, JSON.stringify(optimized));
|
|
@@ -375,7 +234,7 @@ async function compile(options) {
|
|
|
375
234
|
compiledCount++;
|
|
376
235
|
}
|
|
377
236
|
const indexContent = generateIndex(files, options.format);
|
|
378
|
-
const indexFile =
|
|
237
|
+
const indexFile = path3.join(
|
|
379
238
|
options.output,
|
|
380
239
|
`index.${options.format === "mjs" ? "mjs" : "js"}`
|
|
381
240
|
);
|
|
@@ -383,7 +242,7 @@ async function compile(options) {
|
|
|
383
242
|
spinner.succeed(`Compiled ${compiledCount} locale files`);
|
|
384
243
|
const originalSize = await calculateDirSize(options.input);
|
|
385
244
|
const compiledSize = await calculateDirSize(options.output);
|
|
386
|
-
const reduction = ((originalSize - compiledSize) / originalSize * 100).toFixed(1);
|
|
245
|
+
const reduction = originalSize > 0 ? ((originalSize - compiledSize) / originalSize * 100).toFixed(1) : "0.0";
|
|
387
246
|
console.log("\n" + colors.green("\u2728 Compilation complete!"));
|
|
388
247
|
console.log(colors.gray(`Files compiled: ${compiledCount}`));
|
|
389
248
|
console.log(colors.gray(`Size reduction: ${reduction}%`));
|
|
@@ -411,24 +270,29 @@ function optimizeTranslations(obj) {
|
|
|
411
270
|
return result;
|
|
412
271
|
}
|
|
413
272
|
function generateIndex(files, format) {
|
|
414
|
-
const locales = files.map((f) =>
|
|
273
|
+
const locales = files.map((f) => path3.basename(f, ".json"));
|
|
274
|
+
const extension = format === "json" ? "json" : format;
|
|
415
275
|
if (format === "mjs") {
|
|
416
|
-
|
|
276
|
+
const imports = locales.map((locale, index) => `import locale${index} from './${locale}.mjs';`);
|
|
277
|
+
const entries2 = locales.map((locale, index) => ` ${JSON.stringify(locale)}: locale${index},`);
|
|
278
|
+
return `${imports.join("\n")}
|
|
417
279
|
|
|
418
280
|
export default {
|
|
419
|
-
|
|
281
|
+
${entries2.join("\n")}
|
|
420
282
|
};
|
|
421
283
|
`;
|
|
422
284
|
}
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
285
|
+
const accessor = format === "json" ? "" : ".default";
|
|
286
|
+
const entries = locales.map(
|
|
287
|
+
(locale) => ` ${JSON.stringify(locale)}: require(${JSON.stringify(`./${locale}.${extension}`)})${accessor},`
|
|
288
|
+
);
|
|
289
|
+
return `module.exports = {
|
|
290
|
+
${entries.join("\n")}
|
|
427
291
|
};
|
|
428
292
|
`;
|
|
429
293
|
}
|
|
430
294
|
async function calculateDirSize(dir) {
|
|
431
|
-
const files = await glob(
|
|
295
|
+
const files = await glob(path3.join(dir, "**/*"));
|
|
432
296
|
let totalSize = 0;
|
|
433
297
|
for (const file of files) {
|
|
434
298
|
try {
|
|
@@ -441,51 +305,98 @@ async function calculateDirSize(dir) {
|
|
|
441
305
|
}
|
|
442
306
|
return totalSize;
|
|
443
307
|
}
|
|
308
|
+
var KEY_PATTERNS = [
|
|
309
|
+
/(?:^|[^\w$])t\s*\(\s*(['"`])([^'"`$\n]+)\1/g,
|
|
310
|
+
/<(?:T|Trans)\s+id\s*=\s*(['"`])([^'"`$\n]+)\1/g
|
|
311
|
+
];
|
|
312
|
+
var UNSAFE_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
313
|
+
function extractKeysFromSource(content) {
|
|
314
|
+
const keys = /* @__PURE__ */ new Set();
|
|
315
|
+
for (const pattern of KEY_PATTERNS) {
|
|
316
|
+
pattern.lastIndex = 0;
|
|
317
|
+
let match;
|
|
318
|
+
while ((match = pattern.exec(content)) !== null) {
|
|
319
|
+
keys.add(match[2]);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return [...keys];
|
|
323
|
+
}
|
|
324
|
+
function isPlainObject(value) {
|
|
325
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
326
|
+
}
|
|
327
|
+
function buildTranslations(keys, existing, prune = false) {
|
|
328
|
+
const translations = prune || !isPlainObject(existing) ? {} : structuredClone(existing);
|
|
329
|
+
const skipped = [];
|
|
330
|
+
for (const key of [...keys].sort()) {
|
|
331
|
+
const parts = key.split(".");
|
|
332
|
+
if (parts.some((part) => part === "" || UNSAFE_SEGMENTS.has(part))) {
|
|
333
|
+
skipped.push(key);
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
let current = translations;
|
|
337
|
+
let conflict = false;
|
|
338
|
+
for (const part of parts.slice(0, -1)) {
|
|
339
|
+
if (!Object.prototype.hasOwnProperty.call(current, part)) {
|
|
340
|
+
current[part] = {};
|
|
341
|
+
}
|
|
342
|
+
const next = current[part];
|
|
343
|
+
if (!isPlainObject(next)) {
|
|
344
|
+
conflict = true;
|
|
345
|
+
break;
|
|
346
|
+
}
|
|
347
|
+
current = next;
|
|
348
|
+
}
|
|
349
|
+
if (conflict) {
|
|
350
|
+
skipped.push(key);
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
const finalKey = parts[parts.length - 1];
|
|
354
|
+
const present = Object.prototype.hasOwnProperty.call(current, finalKey) ? current[finalKey] : void 0;
|
|
355
|
+
if (typeof present === "string" || isPlainObject(present)) {
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
const previous = getNestedValue(existing, key);
|
|
359
|
+
current[finalKey] = typeof previous === "string" ? previous : isPlainObject(previous) ? structuredClone(previous) : `[${key}]`;
|
|
360
|
+
}
|
|
361
|
+
return { translations, skipped };
|
|
362
|
+
}
|
|
444
363
|
async function extract(options) {
|
|
445
364
|
const spinner = createSpinner("Extracting translation keys").start();
|
|
446
365
|
try {
|
|
447
366
|
const files = await glob(options.pattern);
|
|
448
367
|
const keys = /* @__PURE__ */ new Set();
|
|
449
|
-
const patterns = [
|
|
450
|
-
/\.t\(['"`]([^'"`]+)['"`]/g,
|
|
451
|
-
/t\(['"`]([^'"`]+)['"`]/g,
|
|
452
|
-
/<T\s+id=['"`]([^'"`]+)['"`]/g,
|
|
453
|
-
/<Trans\s+id=['"`]([^'"`]+)['"`]/g
|
|
454
|
-
];
|
|
455
368
|
for (const file of files) {
|
|
456
369
|
const content = await promises.readFile(file, "utf-8");
|
|
457
|
-
for (const
|
|
458
|
-
|
|
459
|
-
while ((match = pattern.exec(content)) !== null) {
|
|
460
|
-
keys.add(match[1]);
|
|
461
|
-
}
|
|
370
|
+
for (const key of extractKeysFromSource(content)) {
|
|
371
|
+
keys.add(key);
|
|
462
372
|
}
|
|
463
373
|
}
|
|
464
|
-
spinner.
|
|
374
|
+
spinner.set(`Found ${keys.size} translation keys`);
|
|
465
375
|
await promises.mkdir(options.output, { recursive: true });
|
|
466
376
|
const locales = options.locales.split(",").map((l) => l.trim());
|
|
467
377
|
for (const locale of locales) {
|
|
468
|
-
const filePath =
|
|
378
|
+
const filePath = path3.join(options.output, `${locale}.json`);
|
|
469
379
|
let existingTranslations = {};
|
|
470
380
|
try {
|
|
471
381
|
const content = await promises.readFile(filePath, "utf-8");
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
}
|
|
483
|
-
current = current[parts[i]];
|
|
382
|
+
try {
|
|
383
|
+
existingTranslations = JSON.parse(content);
|
|
384
|
+
} catch (parseError) {
|
|
385
|
+
spinner.fail(`Failed to parse existing file: ${filePath}`);
|
|
386
|
+
console.error(
|
|
387
|
+
colors.red(
|
|
388
|
+
` JSON parse error: ${parseError instanceof Error ? parseError.message : String(parseError)}`
|
|
389
|
+
)
|
|
390
|
+
);
|
|
391
|
+
process.exit(1);
|
|
484
392
|
}
|
|
485
|
-
|
|
486
|
-
current[finalKey] = getNestedValue(existingTranslations, key) || `[${key}]`;
|
|
393
|
+
} catch (readError) {
|
|
487
394
|
}
|
|
488
|
-
|
|
395
|
+
const { translations, skipped } = buildTranslations(keys, existingTranslations, options.prune);
|
|
396
|
+
for (const key of skipped) {
|
|
397
|
+
console.warn(colors.yellow(` Skipped key "${key}": it conflicts with another key or uses a reserved name`));
|
|
398
|
+
}
|
|
399
|
+
await promises.writeFile(filePath, JSON.stringify(translations, null, 2) + "\n");
|
|
489
400
|
}
|
|
490
401
|
spinner.succeed(`Extracted ${keys.size} keys to ${locales.length} locale files`);
|
|
491
402
|
console.log("\n" + colors.green("\u2728 Extraction complete!"));
|
|
@@ -502,7 +413,7 @@ function getNestedValue(obj, path7) {
|
|
|
502
413
|
const parts = path7.split(".");
|
|
503
414
|
let current = obj;
|
|
504
415
|
for (const part of parts) {
|
|
505
|
-
if (current && typeof current === "object" && part
|
|
416
|
+
if (current && typeof current === "object" && Object.prototype.hasOwnProperty.call(current, part)) {
|
|
506
417
|
current = current[part];
|
|
507
418
|
} else {
|
|
508
419
|
return void 0;
|
|
@@ -552,9 +463,26 @@ var Prompts = class {
|
|
|
552
463
|
});
|
|
553
464
|
});
|
|
554
465
|
}
|
|
466
|
+
// BUG-039 FIX: Check setRawMode availability and fallback to text input in non-TTY environments
|
|
555
467
|
async select(options) {
|
|
556
468
|
const choices = options.choices || [];
|
|
557
469
|
const initial = typeof options.initial === "number" ? options.initial : 0;
|
|
470
|
+
if (!process.stdin.isTTY || typeof process.stdin.setRawMode !== "function") {
|
|
471
|
+
console.log(`${colors.cyan("?")} ${options.message}`);
|
|
472
|
+
choices.forEach((choice, index) => {
|
|
473
|
+
console.log(` ${index + 1}. ${choice.title}${choice.description ? colors.gray(` - ${choice.description}`) : ""}`);
|
|
474
|
+
});
|
|
475
|
+
return new Promise((resolve) => {
|
|
476
|
+
this.readline.question(`${colors.gray(`Enter number (1-${choices.length}, default: ${initial + 1})`)}: `, (answer) => {
|
|
477
|
+
const num = parseInt(answer.trim(), 10);
|
|
478
|
+
if (answer.trim() === "" || isNaN(num) || num < 1 || num > choices.length) {
|
|
479
|
+
resolve(choices[initial].value);
|
|
480
|
+
} else {
|
|
481
|
+
resolve(choices[num - 1].value);
|
|
482
|
+
}
|
|
483
|
+
});
|
|
484
|
+
});
|
|
485
|
+
}
|
|
558
486
|
console.log(`${colors.cyan("?")} ${options.message}`);
|
|
559
487
|
choices.forEach((choice, index) => {
|
|
560
488
|
const marker = index === initial ? colors.cyan("\u276F") : " ";
|
|
@@ -564,7 +492,7 @@ var Prompts = class {
|
|
|
564
492
|
});
|
|
565
493
|
return new Promise((resolve) => {
|
|
566
494
|
let selectedIndex = initial;
|
|
567
|
-
const onKeypress = (
|
|
495
|
+
const onKeypress = (_str, key) => {
|
|
568
496
|
if (key.name === "up" && selectedIndex > 0) {
|
|
569
497
|
selectedIndex--;
|
|
570
498
|
this.redrawChoices(options.message, choices, selectedIndex);
|
|
@@ -663,22 +591,23 @@ async function init(options) {
|
|
|
663
591
|
"common.save": "Save"
|
|
664
592
|
};
|
|
665
593
|
await promises.writeFile(
|
|
666
|
-
|
|
594
|
+
path3.join(config.localesPath, `${config.defaultLocale}.json`),
|
|
667
595
|
JSON.stringify(defaultMessages, null, 2)
|
|
668
596
|
);
|
|
669
597
|
for (const locale of config.additionalLocales) {
|
|
670
598
|
await promises.writeFile(
|
|
671
|
-
|
|
599
|
+
path3.join(config.localesPath, `${locale}.json`),
|
|
672
600
|
JSON.stringify(defaultMessages, null, 2)
|
|
673
601
|
);
|
|
674
602
|
}
|
|
675
603
|
const configContent = config.typescript ? generateTypeScriptConfig(config) : generateJavaScriptConfig(config);
|
|
676
604
|
const configFileName = config.typescript ? "i18n.config.ts" : "i18n.config.js";
|
|
677
|
-
await promises.
|
|
605
|
+
await promises.mkdir("./src", { recursive: true });
|
|
606
|
+
await promises.writeFile(path3.join("./src", configFileName), configContent);
|
|
678
607
|
if (config.typescript) {
|
|
679
|
-
await promises.mkdir(
|
|
680
|
-
const typesContent = generateTypes();
|
|
681
|
-
await promises.writeFile(
|
|
608
|
+
await promises.mkdir(path3.join("./src/types"), { recursive: true });
|
|
609
|
+
const typesContent = generateTypes(config);
|
|
610
|
+
await promises.writeFile(path3.join("./src/types", "i18n.d.ts"), typesContent);
|
|
682
611
|
}
|
|
683
612
|
spinner.succeed("Setup complete!");
|
|
684
613
|
console.log("\n" + colors.green("\u2728 Next steps:"));
|
|
@@ -695,64 +624,69 @@ async function init(options) {
|
|
|
695
624
|
console.error(error);
|
|
696
625
|
process.exit(1);
|
|
697
626
|
}
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
627
|
+
}
|
|
628
|
+
function importPath(fromDir, target) {
|
|
629
|
+
const relative2 = path3.relative(fromDir, target).split(path3.sep).join("/");
|
|
630
|
+
return relative2.startsWith(".") ? relative2 : `./${relative2}`;
|
|
631
|
+
}
|
|
632
|
+
function localeImports(config, configDir) {
|
|
633
|
+
const locales = [config.defaultLocale, ...config.additionalLocales.filter((locale) => locale !== config.defaultLocale)];
|
|
634
|
+
const imports = locales.map((locale, index) => `import locale${index} from '${importPath(configDir, path3.join(config.localesPath, `${locale}.json`))}';`).join("\n");
|
|
635
|
+
const entries = locales.map((locale, index) => ` ${JSON.stringify(locale)}: locale${index},`).join("\n");
|
|
636
|
+
return { imports, entries };
|
|
637
|
+
}
|
|
638
|
+
function generateTypeScriptConfig(config, configDir = "./src") {
|
|
639
|
+
const framework = config.framework;
|
|
640
|
+
const imports = [`import { createI18n } from '@oxog/i18n';`];
|
|
641
|
+
if (framework && framework !== "vanilla") {
|
|
642
|
+
imports.push(`// import { I18nProvider } from '@oxog/i18n-${framework}';`);
|
|
643
|
+
}
|
|
644
|
+
const locales = localeImports(config, configDir);
|
|
645
|
+
return `${imports.join("\n")}
|
|
705
646
|
import type { Messages } from './types/i18n';
|
|
706
|
-
|
|
707
|
-
${config2.additionalLocales.map((locale) => `import ${locale} from '${config2.localesPath}/${locale}.json';`).join("\n")}
|
|
647
|
+
${locales.imports}
|
|
708
648
|
|
|
709
649
|
export const i18n = createI18n<Messages>({
|
|
710
|
-
locale:
|
|
711
|
-
fallbackLocale:
|
|
650
|
+
locale: ${JSON.stringify(config.defaultLocale)},
|
|
651
|
+
fallbackLocale: ${JSON.stringify(config.defaultLocale)},
|
|
712
652
|
messages: {
|
|
713
|
-
|
|
714
|
-
${config2.additionalLocales.join(",\n ")}
|
|
653
|
+
${locales.entries}
|
|
715
654
|
},
|
|
716
655
|
warnOnMissingTranslations: process.env.NODE_ENV !== 'production',
|
|
717
656
|
});
|
|
718
657
|
`;
|
|
658
|
+
}
|
|
659
|
+
function generateJavaScriptConfig(config, configDir = "./src") {
|
|
660
|
+
const framework = config.framework;
|
|
661
|
+
const imports = [`import { createI18n } from '@oxog/i18n';`];
|
|
662
|
+
if (framework && framework !== "vanilla") {
|
|
663
|
+
imports.push(`// import { I18nProvider } from '@oxog/i18n-${framework}';`);
|
|
719
664
|
}
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
if (framework2 !== "vanilla") {
|
|
724
|
-
imports.push(`// import { I18nProvider } from '@oxog/i18n-${framework2}';`);
|
|
725
|
-
}
|
|
726
|
-
return `${imports.join("\n")}
|
|
727
|
-
import en from '${config2.localesPath}/en.json';
|
|
728
|
-
${config2.additionalLocales.map((locale) => `import ${locale} from '${config2.localesPath}/${locale}.json';`).join("\n")}
|
|
665
|
+
const locales = localeImports(config, configDir);
|
|
666
|
+
return `${imports.join("\n")}
|
|
667
|
+
${locales.imports}
|
|
729
668
|
|
|
730
669
|
export const i18n = createI18n({
|
|
731
|
-
locale:
|
|
732
|
-
fallbackLocale:
|
|
670
|
+
locale: ${JSON.stringify(config.defaultLocale)},
|
|
671
|
+
fallbackLocale: ${JSON.stringify(config.defaultLocale)},
|
|
733
672
|
messages: {
|
|
734
|
-
|
|
735
|
-
${config2.additionalLocales.join(",\n ")}
|
|
673
|
+
${locales.entries}
|
|
736
674
|
},
|
|
737
675
|
warnOnMissingTranslations: process.env.NODE_ENV !== 'production',
|
|
738
676
|
});
|
|
739
677
|
`;
|
|
740
|
-
}
|
|
741
|
-
function generateTypes() {
|
|
742
|
-
return `import type enMessages from '../locales/en.json';
|
|
743
|
-
|
|
744
|
-
export type Messages = typeof enMessages;
|
|
745
|
-
|
|
746
|
-
declare module '@oxog/i18n' {
|
|
747
|
-
interface CustomMessages extends Messages {}
|
|
748
678
|
}
|
|
679
|
+
function generateTypes(config, typesDir = "./src/types") {
|
|
680
|
+
const source = importPath(typesDir, path3.join(config.localesPath, `${config.defaultLocale}.json`));
|
|
681
|
+
return `import type sourceMessages from '${source}';
|
|
682
|
+
|
|
683
|
+
export type Messages = typeof sourceMessages;
|
|
749
684
|
`;
|
|
750
|
-
}
|
|
751
685
|
}
|
|
752
686
|
async function stats(options) {
|
|
753
687
|
const spinner = createSpinner("Calculating statistics").start();
|
|
754
688
|
try {
|
|
755
|
-
const pattern =
|
|
689
|
+
const pattern = path3.join(options.path, "*.json");
|
|
756
690
|
const files = await glob(pattern);
|
|
757
691
|
if (files.length === 0) {
|
|
758
692
|
throw new Error("No translation files found");
|
|
@@ -760,9 +694,20 @@ async function stats(options) {
|
|
|
760
694
|
const localeStats = [];
|
|
761
695
|
let maxKeys = 0;
|
|
762
696
|
for (const file of files) {
|
|
763
|
-
const locale =
|
|
697
|
+
const locale = path3.basename(file, ".json");
|
|
764
698
|
const content = await promises.readFile(file, "utf-8");
|
|
765
|
-
|
|
699
|
+
let translations;
|
|
700
|
+
try {
|
|
701
|
+
translations = JSON.parse(content);
|
|
702
|
+
} catch (parseError) {
|
|
703
|
+
spinner.fail(`Failed to parse ${file}`);
|
|
704
|
+
console.error(
|
|
705
|
+
colors.red(
|
|
706
|
+
` JSON parse error: ${parseError instanceof Error ? parseError.message : String(parseError)}`
|
|
707
|
+
)
|
|
708
|
+
);
|
|
709
|
+
process.exit(1);
|
|
710
|
+
}
|
|
766
711
|
const stats2 = calculateStats(translations);
|
|
767
712
|
maxKeys = Math.max(maxKeys, stats2.keys);
|
|
768
713
|
localeStats.push({
|
|
@@ -830,26 +775,47 @@ function displayTable(stats2) {
|
|
|
830
775
|
async function sync(options) {
|
|
831
776
|
const spinner = createSpinner("Loading translations").start();
|
|
832
777
|
try {
|
|
833
|
-
const sourceFile =
|
|
778
|
+
const sourceFile = path3.join(options.path, `${options.source}.json`);
|
|
834
779
|
const sourceContent = await promises.readFile(sourceFile, "utf-8");
|
|
835
|
-
|
|
780
|
+
let sourceTranslations;
|
|
781
|
+
try {
|
|
782
|
+
sourceTranslations = JSON.parse(sourceContent);
|
|
783
|
+
} catch (parseError) {
|
|
784
|
+
spinner.fail(`Failed to parse source file: ${sourceFile}`);
|
|
785
|
+
console.error(
|
|
786
|
+
colors.red(
|
|
787
|
+
` JSON parse error: ${parseError instanceof Error ? parseError.message : String(parseError)}`
|
|
788
|
+
)
|
|
789
|
+
);
|
|
790
|
+
process.exit(1);
|
|
791
|
+
}
|
|
836
792
|
let targetLocales = [];
|
|
837
793
|
if (options.target) {
|
|
838
794
|
targetLocales = options.target.split(",").map((l) => l.trim());
|
|
839
795
|
} else {
|
|
840
796
|
const files = await promises.readdir(options.path);
|
|
841
797
|
const localeFiles = files.filter((f) => f.endsWith(".json") && f !== `${options.source}.json`);
|
|
842
|
-
targetLocales = localeFiles.map((f) =>
|
|
798
|
+
targetLocales = localeFiles.map((f) => path3.basename(f, ".json"));
|
|
843
799
|
}
|
|
844
|
-
spinner.
|
|
800
|
+
spinner.set(`Syncing to ${targetLocales.length} locales`);
|
|
845
801
|
const syncResults = {};
|
|
846
802
|
for (const locale of targetLocales) {
|
|
847
|
-
const targetFile =
|
|
803
|
+
const targetFile = path3.join(options.path, `${locale}.json`);
|
|
848
804
|
let targetTranslations = {};
|
|
849
805
|
try {
|
|
850
806
|
const content = await promises.readFile(targetFile, "utf-8");
|
|
851
|
-
|
|
852
|
-
|
|
807
|
+
try {
|
|
808
|
+
targetTranslations = JSON.parse(content);
|
|
809
|
+
} catch (parseError) {
|
|
810
|
+
spinner.fail(`Failed to parse target file: ${targetFile}`);
|
|
811
|
+
console.error(
|
|
812
|
+
colors.red(
|
|
813
|
+
` JSON parse error: ${parseError instanceof Error ? parseError.message : String(parseError)}`
|
|
814
|
+
)
|
|
815
|
+
);
|
|
816
|
+
process.exit(1);
|
|
817
|
+
}
|
|
818
|
+
} catch (readError) {
|
|
853
819
|
}
|
|
854
820
|
const result = syncTranslations(sourceTranslations, targetTranslations);
|
|
855
821
|
syncResults[locale] = result.stats;
|
|
@@ -894,7 +860,7 @@ function syncTranslations(source, target) {
|
|
|
894
860
|
}
|
|
895
861
|
const result = { ...tgt };
|
|
896
862
|
for (const [key, value] of Object.entries(src)) {
|
|
897
|
-
if (!(key
|
|
863
|
+
if (!Object.prototype.hasOwnProperty.call(result, key)) {
|
|
898
864
|
result[key] = value;
|
|
899
865
|
if (typeof value === "string") {
|
|
900
866
|
stats2.added++;
|
|
@@ -917,18 +883,40 @@ async function validate(options) {
|
|
|
917
883
|
try {
|
|
918
884
|
const files = await glob(options.pattern);
|
|
919
885
|
const results = {};
|
|
920
|
-
const sourceFile = files.find((f) =>
|
|
886
|
+
const sourceFile = files.find((f) => path3.basename(f, ".json") === options.source);
|
|
921
887
|
if (!sourceFile) {
|
|
922
888
|
throw new Error(`Source locale file not found: ${options.source}`);
|
|
923
889
|
}
|
|
924
890
|
const sourceContent = await promises.readFile(sourceFile, "utf-8");
|
|
925
|
-
|
|
891
|
+
let sourceTranslations;
|
|
892
|
+
try {
|
|
893
|
+
sourceTranslations = JSON.parse(sourceContent);
|
|
894
|
+
} catch (parseError) {
|
|
895
|
+
spinner.fail(`Failed to parse source file: ${sourceFile}`);
|
|
896
|
+
console.error(
|
|
897
|
+
colors.red(
|
|
898
|
+
` JSON parse error: ${parseError instanceof Error ? parseError.message : String(parseError)}`
|
|
899
|
+
)
|
|
900
|
+
);
|
|
901
|
+
process.exit(1);
|
|
902
|
+
}
|
|
926
903
|
const sourceKeys = extractKeys(sourceTranslations);
|
|
927
904
|
for (const file of files) {
|
|
928
905
|
if (file === sourceFile) continue;
|
|
929
|
-
const locale =
|
|
906
|
+
const locale = path3.basename(file, ".json");
|
|
930
907
|
const content = await promises.readFile(file, "utf-8");
|
|
931
|
-
|
|
908
|
+
let translations;
|
|
909
|
+
try {
|
|
910
|
+
translations = JSON.parse(content);
|
|
911
|
+
} catch (parseError) {
|
|
912
|
+
spinner.fail(`Failed to parse ${file}`);
|
|
913
|
+
console.error(
|
|
914
|
+
colors.red(
|
|
915
|
+
` JSON parse error: ${parseError instanceof Error ? parseError.message : String(parseError)}`
|
|
916
|
+
)
|
|
917
|
+
);
|
|
918
|
+
process.exit(1);
|
|
919
|
+
}
|
|
932
920
|
const keys = extractKeys(translations);
|
|
933
921
|
const missing = sourceKeys.filter((key) => !keys.includes(key));
|
|
934
922
|
const extra = keys.filter((key) => !sourceKeys.includes(key));
|
|
@@ -941,6 +929,7 @@ async function validate(options) {
|
|
|
941
929
|
console.log(colors.green("\u2713 All translations are in sync!"));
|
|
942
930
|
} else {
|
|
943
931
|
console.log(colors.red("\n\u2717 Translation issues found:\n"));
|
|
932
|
+
process.exitCode = 1;
|
|
944
933
|
for (const [locale, issues] of Object.entries(results)) {
|
|
945
934
|
console.log(colors.yellow(`${locale}:`));
|
|
946
935
|
if (issues.missing.length > 0) {
|
|
@@ -977,6 +966,213 @@ function extractKeys(obj, prefix = "") {
|
|
|
977
966
|
return keys;
|
|
978
967
|
}
|
|
979
968
|
|
|
969
|
+
// src/utils/commander.ts
|
|
970
|
+
var Commander = class {
|
|
971
|
+
commands = /* @__PURE__ */ new Map();
|
|
972
|
+
globalOptions = [];
|
|
973
|
+
programName = "cli";
|
|
974
|
+
programDescription = "";
|
|
975
|
+
programVersion = "1.0.0";
|
|
976
|
+
name(name) {
|
|
977
|
+
this.programName = name;
|
|
978
|
+
return this;
|
|
979
|
+
}
|
|
980
|
+
description(desc) {
|
|
981
|
+
this.programDescription = desc;
|
|
982
|
+
return this;
|
|
983
|
+
}
|
|
984
|
+
version(version) {
|
|
985
|
+
this.programVersion = version;
|
|
986
|
+
return this;
|
|
987
|
+
}
|
|
988
|
+
option(flags, description, defaultValue) {
|
|
989
|
+
this.globalOptions.push({ flags, description, defaultValue });
|
|
990
|
+
return this;
|
|
991
|
+
}
|
|
992
|
+
command(name) {
|
|
993
|
+
const command = {
|
|
994
|
+
name,
|
|
995
|
+
description: "",
|
|
996
|
+
options: []
|
|
997
|
+
};
|
|
998
|
+
this.commands.set(name, command);
|
|
999
|
+
return new CommandBuilder(command);
|
|
1000
|
+
}
|
|
1001
|
+
async parse(argv = process.argv) {
|
|
1002
|
+
const args = argv.slice(2);
|
|
1003
|
+
const wantsHelp = args.includes("--help") || args.includes("-h");
|
|
1004
|
+
const commandName = args[0];
|
|
1005
|
+
const command = commandName === void 0 ? void 0 : this.commands.get(commandName);
|
|
1006
|
+
if (command && wantsHelp) {
|
|
1007
|
+
this.showCommandHelp(command);
|
|
1008
|
+
return;
|
|
1009
|
+
}
|
|
1010
|
+
if (args.length === 0 || wantsHelp) {
|
|
1011
|
+
this.showHelp();
|
|
1012
|
+
return;
|
|
1013
|
+
}
|
|
1014
|
+
if (args.includes("--version") || args.includes("-V")) {
|
|
1015
|
+
console.log(this.programVersion);
|
|
1016
|
+
return;
|
|
1017
|
+
}
|
|
1018
|
+
if (!command) {
|
|
1019
|
+
console.error(colors.red(`Unknown command: ${commandName}`));
|
|
1020
|
+
this.showHelp();
|
|
1021
|
+
process.exit(1);
|
|
1022
|
+
}
|
|
1023
|
+
const options = this.parseOptions(args.slice(1), [...this.globalOptions, ...command.options]);
|
|
1024
|
+
if (command.action) {
|
|
1025
|
+
try {
|
|
1026
|
+
await command.action(options);
|
|
1027
|
+
} catch (error) {
|
|
1028
|
+
console.error(colors.red("Error:"), error instanceof Error ? error.message : String(error));
|
|
1029
|
+
process.exit(1);
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
parseOptions(args, optionDefinitions) {
|
|
1034
|
+
const options = {};
|
|
1035
|
+
const optionMap = /* @__PURE__ */ new Map();
|
|
1036
|
+
for (const option of optionDefinitions) {
|
|
1037
|
+
const [shortFlag, longFlag] = this.parseFlags(option.flags);
|
|
1038
|
+
if (shortFlag) optionMap.set(shortFlag, option);
|
|
1039
|
+
if (longFlag) optionMap.set(longFlag, option);
|
|
1040
|
+
if (option.defaultValue !== void 0) {
|
|
1041
|
+
const key = this.getOptionKey(option.flags);
|
|
1042
|
+
options[key] = option.defaultValue;
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
for (let i = 0; i < args.length; i++) {
|
|
1046
|
+
const arg = args[i];
|
|
1047
|
+
if (arg.startsWith("-")) {
|
|
1048
|
+
const option = optionMap.get(arg);
|
|
1049
|
+
if (!option) {
|
|
1050
|
+
console.error(colors.red(`Unknown option: ${arg}`));
|
|
1051
|
+
process.exit(1);
|
|
1052
|
+
}
|
|
1053
|
+
const key = this.getOptionKey(option.flags);
|
|
1054
|
+
if (this.isBooleanOption(option)) {
|
|
1055
|
+
options[key] = true;
|
|
1056
|
+
} else {
|
|
1057
|
+
i++;
|
|
1058
|
+
if (i >= args.length) {
|
|
1059
|
+
console.error(colors.red(`Option ${arg} requires a value`));
|
|
1060
|
+
process.exit(1);
|
|
1061
|
+
}
|
|
1062
|
+
options[key] = args[i];
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
for (const option of optionDefinitions) {
|
|
1067
|
+
if (option.required) {
|
|
1068
|
+
const key = this.getOptionKey(option.flags);
|
|
1069
|
+
if (options[key] === void 0) {
|
|
1070
|
+
console.error(colors.red(`Required option missing: ${option.flags}`));
|
|
1071
|
+
process.exit(1);
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
return options;
|
|
1076
|
+
}
|
|
1077
|
+
// BUG-037 FIX: Strip value placeholders from flags before storing in map
|
|
1078
|
+
parseFlags(flags) {
|
|
1079
|
+
const parts = flags.split(/,\s*/);
|
|
1080
|
+
let shortFlag;
|
|
1081
|
+
let longFlag;
|
|
1082
|
+
for (const part of parts) {
|
|
1083
|
+
const trimmed = part.trim().replace(/\s*[<[].*$/, "");
|
|
1084
|
+
if (trimmed.startsWith("--")) {
|
|
1085
|
+
longFlag = trimmed;
|
|
1086
|
+
} else if (trimmed.startsWith("-")) {
|
|
1087
|
+
shortFlag = trimmed;
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
return [shortFlag, longFlag];
|
|
1091
|
+
}
|
|
1092
|
+
getOptionKey(flags) {
|
|
1093
|
+
const [, longFlag] = this.parseFlags(flags);
|
|
1094
|
+
if (longFlag) {
|
|
1095
|
+
return longFlag.replace(/^--/, "").replace(/\s*[<[].*$/, "").replace(/-/g, "_");
|
|
1096
|
+
}
|
|
1097
|
+
const [shortFlag] = this.parseFlags(flags);
|
|
1098
|
+
return shortFlag.replace(/^-/, "").replace(/\s*[<[].*$/, "");
|
|
1099
|
+
}
|
|
1100
|
+
isBooleanOption(option) {
|
|
1101
|
+
return !option.flags.includes("<") && !option.flags.includes("[");
|
|
1102
|
+
}
|
|
1103
|
+
showCommandHelp(command) {
|
|
1104
|
+
console.log(colors.bold(`${this.programName} ${command.name}`));
|
|
1105
|
+
if (command.description) {
|
|
1106
|
+
console.log(command.description);
|
|
1107
|
+
}
|
|
1108
|
+
console.log();
|
|
1109
|
+
console.log(colors.bold("Usage:"));
|
|
1110
|
+
console.log(` ${this.programName} ${command.name} [options]`);
|
|
1111
|
+
console.log();
|
|
1112
|
+
console.log(colors.bold("Options:"));
|
|
1113
|
+
for (const option of command.options) {
|
|
1114
|
+
const defaultText = option.defaultValue !== void 0 ? ` (default: ${JSON.stringify(option.defaultValue)})` : "";
|
|
1115
|
+
console.log(` ${option.flags.padEnd(30)} ${option.description}${defaultText}`);
|
|
1116
|
+
}
|
|
1117
|
+
console.log(` ${"-h, --help".padEnd(30)} Show help`);
|
|
1118
|
+
}
|
|
1119
|
+
showHelp() {
|
|
1120
|
+
console.log(colors.bold(this.programName));
|
|
1121
|
+
if (this.programDescription) {
|
|
1122
|
+
console.log(this.programDescription);
|
|
1123
|
+
}
|
|
1124
|
+
console.log();
|
|
1125
|
+
console.log(colors.bold("Usage:"));
|
|
1126
|
+
console.log(` ${this.programName} [command] [options]`);
|
|
1127
|
+
console.log();
|
|
1128
|
+
if (this.commands.size > 0) {
|
|
1129
|
+
console.log(colors.bold("Commands:"));
|
|
1130
|
+
for (const [name, command] of this.commands) {
|
|
1131
|
+
console.log(` ${name.padEnd(15)} ${command.description}`);
|
|
1132
|
+
}
|
|
1133
|
+
console.log();
|
|
1134
|
+
}
|
|
1135
|
+
if (this.globalOptions.length > 0) {
|
|
1136
|
+
console.log(colors.bold("Options:"));
|
|
1137
|
+
for (const option of this.globalOptions) {
|
|
1138
|
+
console.log(` ${option.flags.padEnd(20)} ${option.description}`);
|
|
1139
|
+
}
|
|
1140
|
+
console.log();
|
|
1141
|
+
}
|
|
1142
|
+
console.log(colors.bold("Global Options:"));
|
|
1143
|
+
console.log(" -h, --help Show help");
|
|
1144
|
+
console.log(" -V, --version Show version");
|
|
1145
|
+
}
|
|
1146
|
+
};
|
|
1147
|
+
var CommandBuilder = class {
|
|
1148
|
+
constructor(command) {
|
|
1149
|
+
this.command = command;
|
|
1150
|
+
}
|
|
1151
|
+
description(desc) {
|
|
1152
|
+
this.command.description = desc;
|
|
1153
|
+
return this;
|
|
1154
|
+
}
|
|
1155
|
+
option(flags, description, defaultValue) {
|
|
1156
|
+
this.command.options.push({ flags, description, defaultValue });
|
|
1157
|
+
return this;
|
|
1158
|
+
}
|
|
1159
|
+
action(fn) {
|
|
1160
|
+
this.command.action = fn;
|
|
1161
|
+
return this;
|
|
1162
|
+
}
|
|
1163
|
+
};
|
|
1164
|
+
function createCommander() {
|
|
1165
|
+
return new Commander();
|
|
1166
|
+
}
|
|
1167
|
+
function readVersion() {
|
|
1168
|
+
try {
|
|
1169
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf-8"));
|
|
1170
|
+
return pkg.version ?? "unknown";
|
|
1171
|
+
} catch {
|
|
1172
|
+
return "unknown";
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
|
|
980
1176
|
// src/cli.ts
|
|
981
1177
|
process.on("uncaughtException", (error) => {
|
|
982
1178
|
console.error("[CLI] Uncaught exception:", error.message);
|
|
@@ -993,9 +1189,9 @@ process.on("unhandledRejection", (reason, promise) => {
|
|
|
993
1189
|
process.exit(1);
|
|
994
1190
|
});
|
|
995
1191
|
try {
|
|
996
|
-
const program = createCommander().name("oxog-i18n").description("CLI tool for @oxog/i18n").version(
|
|
1192
|
+
const program = createCommander().name("oxog-i18n").description("CLI tool for @oxog/i18n").version(readVersion());
|
|
997
1193
|
program.command("init").description("Initialize i18n in your project").option("-f, --framework <framework>", "Framework to use (react, vue, svelte)").option("-t, --typescript", "Use TypeScript").action(init);
|
|
998
|
-
program.command("extract").description("Extract translation keys from source code").option("-p, --pattern <pattern>", "Glob pattern for files", "src/**/*.{ts,tsx,js,jsx}").option("-o, --output <path>", "Output directory for translations", "./src/locales").option("-l, --locales <locales>", "Comma-separated list of locales", "en").action(extract);
|
|
1194
|
+
program.command("extract").description("Extract translation keys from source code").option("-p, --pattern <pattern>", "Glob pattern for files", "src/**/*.{ts,tsx,js,jsx}").option("-o, --output <path>", "Output directory for translations", "./src/locales").option("-l, --locales <locales>", "Comma-separated list of locales", "en").option("--prune", "Remove keys that are no longer used in the source code").action(extract);
|
|
999
1195
|
program.command("validate").description("Validate translations for missing keys").option("-p, --pattern <pattern>", "Glob pattern for translation files", "./src/locales/**/*.json").option("-s, --source <locale>", "Source locale to compare against", "en").action(validate);
|
|
1000
1196
|
program.command("compile").description("Pre-compile translations for production").option("-i, --input <path>", "Input directory", "./src/locales").option("-o, --output <path>", "Output directory", "./dist/locales").option("-f, --format <format>", "Output format (json, js, mjs)", "json").action(compile);
|
|
1001
1197
|
program.command("sync").description("Sync translations across locales").option("-s, --source <locale>", "Source locale", "en").option("-t, --target <locales>", "Target locales (comma-separated)").option("-p, --path <path>", "Translation files path", "./src/locales").action(sync);
|