auto-translate-json-library 1.5.5 → 2.0.5

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.
Files changed (85) hide show
  1. package/README.MD +1379 -149
  2. package/build/package.json +113 -25
  3. package/build/src/aws.d.ts +1 -1
  4. package/build/src/aws.js +27 -38
  5. package/build/src/azure.d.ts +1 -1
  6. package/build/src/azure.js +50 -64
  7. package/build/src/bin/cli.js +224 -36
  8. package/build/src/config.d.ts +13 -1
  9. package/build/src/config.js +1 -2
  10. package/build/src/deepl.d.ts +1 -1
  11. package/build/src/deepl.js +18 -64
  12. package/build/src/files.d.ts +11 -2
  13. package/build/src/files.js +356 -69
  14. package/build/src/folderFiles.d.ts +6 -3
  15. package/build/src/folderFiles.js +33 -44
  16. package/build/src/format/arb-handler.d.ts +33 -0
  17. package/build/src/format/arb-handler.js +679 -0
  18. package/build/src/format/base-format-handler.d.ts +75 -0
  19. package/build/src/format/base-format-handler.js +166 -0
  20. package/build/src/format/csv-handler.d.ts +38 -0
  21. package/build/src/format/csv-handler.js +604 -0
  22. package/build/src/format/index.d.ts +17 -0
  23. package/build/src/format/index.js +48 -0
  24. package/build/src/format/json-handler.d.ts +17 -0
  25. package/build/src/format/json-handler.js +294 -0
  26. package/build/src/format/po-handler.d.ts +17 -0
  27. package/build/src/format/po-handler.js +338 -0
  28. package/build/src/format/po-utils.d.ts +86 -0
  29. package/build/src/format/po-utils.js +385 -0
  30. package/build/src/format/pot-handler.d.ts +22 -0
  31. package/build/src/format/pot-handler.js +331 -0
  32. package/build/src/format/properties-handler.d.ts +26 -0
  33. package/build/src/format/properties-handler.js +500 -0
  34. package/build/src/format/tsv-handler.d.ts +13 -0
  35. package/build/src/format/tsv-handler.js +67 -0
  36. package/build/src/format/xliff-handler.d.ts +24 -0
  37. package/build/src/format/xliff-handler.js +433 -0
  38. package/build/src/format/xmb-handler.d.ts +33 -0
  39. package/build/src/format/xmb-handler.js +484 -0
  40. package/build/src/format/xmb-xtb-utils.d.ts +43 -0
  41. package/build/src/format/xmb-xtb-utils.js +180 -0
  42. package/build/src/format/xml-handler.d.ts +28 -0
  43. package/build/src/format/xml-handler.js +561 -0
  44. package/build/src/format/xtb-handler.d.ts +33 -0
  45. package/build/src/format/xtb-handler.js +518 -0
  46. package/build/src/format/yaml-handler.d.ts +26 -0
  47. package/build/src/format/yaml-handler.js +522 -0
  48. package/build/src/format-detector.d.ts +7 -0
  49. package/build/src/format-detector.js +58 -0
  50. package/build/src/format-handler-factory.d.ts +9 -0
  51. package/build/src/format-handler-factory.js +18 -0
  52. package/build/src/format.interface.d.ts +56 -0
  53. package/build/src/format.interface.js +1 -0
  54. package/build/src/google.d.ts +1 -1
  55. package/build/src/google.js +32 -49
  56. package/build/src/huggingface-local.d.ts +11 -0
  57. package/build/src/huggingface-local.js +71 -0
  58. package/build/src/huggingface.d.ts +12 -0
  59. package/build/src/huggingface.js +76 -0
  60. package/build/src/index.d.ts +4 -3
  61. package/build/src/index.js +32 -17
  62. package/build/src/lib.d.ts +1 -1
  63. package/build/src/lib.js +196 -133
  64. package/build/src/openai.d.ts +2 -2
  65. package/build/src/openai.js +60 -50
  66. package/build/src/translate.interface.d.ts +1 -1
  67. package/build/src/translate.interface.js +1 -2
  68. package/build/src/util.js +4 -9
  69. package/build/src/validation/enhanced-validation-result.d.ts +96 -0
  70. package/build/src/validation/enhanced-validation-result.js +198 -0
  71. package/build/src/validation/error-messages.d.ts +88 -0
  72. package/build/src/validation/error-messages.js +436 -0
  73. package/build/src/validation/error-recovery.d.ts +78 -0
  74. package/build/src/validation/error-recovery.js +593 -0
  75. package/build/src/validation/example-usage.d.ts +31 -0
  76. package/build/src/validation/example-usage.js +148 -0
  77. package/build/src/validation/format-rules.d.ts +37 -0
  78. package/build/src/validation/format-rules.js +550 -0
  79. package/build/src/validation/format-validator.d.ts +70 -0
  80. package/build/src/validation/format-validator.js +279 -0
  81. package/build/src/validation/index.d.ts +13 -0
  82. package/build/src/validation/index.js +30 -0
  83. package/build/src/validation/validation-service.d.ts +56 -0
  84. package/build/src/validation/validation-service.js +262 -0
  85. package/package.json +113 -25
@@ -1,52 +1,162 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+ import minimist from "minimist";
5
+ import c from "picocolors";
6
+ import packageJson from "../../package.json" with { type: "json" };
7
+ const { version } = packageJson;
8
+ import { config as dotenvConfig } from "dotenv";
9
+ dotenvConfig();
10
+ const formatDetails = {
11
+ json: { extensions: [".json"], description: "JSON translation files" },
12
+ arb: {
13
+ extensions: [".arb"],
14
+ description: "Flutter Application Resource Bundle",
15
+ },
16
+ xml: { extensions: [".xml"], description: "Generic XML translation files" },
17
+ "android-xml": {
18
+ extensions: [".xml"],
19
+ description: "Android strings.xml format",
20
+ },
21
+ "ios-xml": {
22
+ extensions: [".xml"],
23
+ description: "iOS localization XML format",
24
+ },
25
+ "generic-xml": { extensions: [".xml"], description: "Generic XML format" },
26
+ xliff: {
27
+ extensions: [".xlf", ".xliff"],
28
+ description: "XLIFF 1.2 and 2.x translation files",
29
+ },
30
+ xmb: {
31
+ extensions: [".xmb"],
32
+ description: "XML Message Bundle source files",
33
+ },
34
+ xtb: { extensions: [".xtb"], description: "XML Translation Bundle files" },
35
+ po: { extensions: [".po"], description: "GNU gettext PO files" },
36
+ pot: {
37
+ extensions: [".pot"],
38
+ description: "GNU gettext POT template files",
39
+ },
40
+ yaml: {
41
+ extensions: [".yaml", ".yml"],
42
+ description: "YAML translation files",
43
+ },
44
+ properties: {
45
+ extensions: [".properties"],
46
+ description: "Java Properties files",
47
+ },
48
+ csv: { extensions: [".csv"], description: "Comma-separated values files" },
49
+ tsv: { extensions: [".tsv"], description: "Tab-separated values files" },
5
50
  };
6
- var _a, _b, _c, _d, _e, _f, _g, _h;
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- const node_path_1 = __importDefault(require("node:path"));
9
- const minimist_1 = __importDefault(require("minimist"));
10
- const picocolors_1 = __importDefault(require("picocolors"));
11
- const package_json_1 = require("../../package.json");
12
- const lib_1 = require("../lib");
13
- require("dotenv").config();
51
+ const supportedFormats = Object.keys(formatDetails);
14
52
  // Define a function to display the help message
15
53
  function displayHelp() {
16
- console.log(`🔨 Auto translate json cli v${package_json_1.version}`);
54
+ console.log(`🔨 Auto translate json/xml cli v${version}`);
17
55
  console.log("Usage: atj [options] <inputPath>");
18
56
  console.log("");
19
57
  console.log("Options:");
20
58
  console.log(" --help, -h Display this help message");
59
+ console.log(" --list-formats List all supported file formats");
21
60
  console.log(" --mode, -m <mode> Specify the translation mode:file or folder");
22
61
  console.log(" --engine, -e <engine> Specify the translation engine:aws,azure,google,deepLPro,deepLFree or openai");
23
62
  console.log(" --sourceLocale, -s <locale> Specify the source locale");
63
+ console.log(" --format, -f <format> Manually specify the file format (overrides auto-detection)");
64
+ console.log(" Note: inputPath can be a translation file in any supported format, or a folder structure");
24
65
  console.log(" --keepTranslations, --no-keepTranslations Keep or retranslate existing translations");
25
66
  console.log(" --keepExtraTranslations, --no-keepExtraTranslations Keep or remove extra translations");
26
67
  console.log("");
68
+ console.log("Supported formats:");
69
+ const formatGroups = {
70
+ "JSON-based": ["json", "arb"],
71
+ "XML-based": [
72
+ "xml",
73
+ "android-xml",
74
+ "ios-xml",
75
+ "generic-xml",
76
+ "xliff",
77
+ "xmb",
78
+ "xtb",
79
+ ],
80
+ "Text-based": ["po", "pot", "yaml", "properties"],
81
+ Tabular: ["csv", "tsv"],
82
+ };
83
+ for (const [group, groupFormats] of Object.entries(formatGroups)) {
84
+ const availableFormats = groupFormats.filter((f) => supportedFormats.includes(f));
85
+ if (availableFormats.length > 0) {
86
+ console.log(` ${group}: ${availableFormats.join(", ")}`);
87
+ }
88
+ }
89
+ console.log("");
90
+ console.log("Format examples:");
91
+ console.log(" JSON: translations.json, app.arb (Flutter)");
92
+ console.log(" XML: strings.xml (Android), messages.xlf (XLIFF), template.xmb (Google)");
93
+ console.log(" Text: messages.po (gettext), config.yaml, app.properties (Java)");
94
+ console.log(" Tabular: translations.csv, data.tsv");
95
+ console.log("");
96
+ console.log("Usage examples:");
97
+ console.log(" atj translations.json # Auto-detect JSON format");
98
+ console.log(" atj --format xliff messages.xlf # Force XLIFF format");
99
+ console.log(" atj --mode folder locales/ # Process entire folder");
100
+ console.log(" atj --engine google --format po msgs.po # Use Google Translate with PO files");
101
+ console.log("");
27
102
  console.log("Default values");
28
103
  console.log(" --mode, -m <mode> file");
29
104
  console.log(" --engine, -e <engine> aws");
30
105
  console.log(" --sourceLocale, -s <locale> en");
106
+ console.log(" --format, -f <format> auto-detect");
31
107
  console.log(" --keepTranslations, --no-keepTranslations --keepTranslations");
32
108
  console.log(" --keepExtraTranslations, --no-keepExtraTranslations --no-keepExtraTranslations");
33
109
  }
110
+ // Define a function to list supported formats
111
+ function listFormats() {
112
+ console.log(`🔨 Auto translate json/xml cli v${version}`);
113
+ console.log("");
114
+ console.log("Supported file formats:");
115
+ console.log("");
116
+ for (const format of [...supportedFormats].sort()) {
117
+ const details = formatDetails[format];
118
+ if (details) {
119
+ console.log(` ${format.padEnd(15)} ${details.extensions.join(", ").padEnd(20)} ${details.description}`);
120
+ }
121
+ }
122
+ console.log("");
123
+ console.log("Usage examples:");
124
+ console.log(" atj --format json translations.json");
125
+ console.log(" atj --format xliff messages.xlf");
126
+ console.log(" atj --format po locales/messages.po");
127
+ console.log(" atj --format yaml config/translations.yaml");
128
+ console.log(" atj --format arb --engine google lib/l10n/app_en.arb");
129
+ console.log(" atj --format android-xml --sourceLocale en res/values/strings.xml");
130
+ console.log("");
131
+ console.log("Best practices:");
132
+ console.log(" • Format is usually auto-detected from file extension");
133
+ console.log(" • Use --format to override auto-detection when needed");
134
+ console.log(" • For XML files, specify the exact variant (android-xml, ios-xml, xliff)");
135
+ console.log(" • Use --keepTranslations to preserve existing translations");
136
+ console.log(" • Test with a single file before processing entire folders");
137
+ }
34
138
  const arguments_ = process.argv.slice(2);
35
139
  if (arguments_.length === 0) {
36
140
  displayHelp();
37
141
  process.exit(0);
38
142
  }
39
- const flags = (0, minimist_1.default)(arguments_, {
143
+ const flags = minimist(arguments_, {
40
144
  alias: {
41
145
  mode: ["m"],
42
146
  engine: ["e"],
43
147
  keepTranslations: ["kt"],
44
148
  keepExtraTranslations: ["ket"],
45
149
  sourceLocale: ["s"],
150
+ format: ["f"],
46
151
  help: ["h"],
47
152
  },
48
- string: ["mode", "engine", "sourceLocale"],
49
- boolean: ["keepTranslations", "keepExtraTranslations", "help"],
153
+ string: ["mode", "engine", "sourceLocale", "format"],
154
+ boolean: [
155
+ "keepTranslations",
156
+ "keepExtraTranslations",
157
+ "help",
158
+ "list-formats",
159
+ ],
50
160
  default: {
51
161
  engine: "aws",
52
162
  sourceLocale: "en",
@@ -55,20 +165,63 @@ const flags = (0, minimist_1.default)(arguments_, {
55
165
  mode: "file",
56
166
  },
57
167
  });
58
- console.log(picocolors_1.default.green(`🔨 Auto translate json cli v${package_json_1.version}`));
168
+ console.log(c.green(`🔨 Auto translate json cli v${version}`));
59
169
  if (flags.help) {
60
170
  displayHelp();
61
171
  process.exit(0);
62
172
  }
173
+ if (flags["list-formats"]) {
174
+ listFormats();
175
+ process.exit(0);
176
+ }
63
177
  const inputPath = flags._[0];
64
- const { mode, engine, sourceLocale, keepTranslations, keepExtraTranslations } = flags;
178
+ const { mode, engine, sourceLocale, keepTranslations, keepExtraTranslations, format, } = flags;
179
+ // Validate input path
180
+ if (!inputPath) {
181
+ console.error(c.red("❌ Input path is required"));
182
+ console.error(c.yellow("💡 Usage: atj [options] <inputPath>"));
183
+ process.exit(1);
184
+ }
185
+ // Validate format if specified
186
+ if (format && !supportedFormats.includes(format)) {
187
+ console.error(c.red(`❌ Unsupported format: ${format}`));
188
+ console.error(c.yellow("💡 Use --list-formats to see all supported formats"));
189
+ process.exit(1);
190
+ }
191
+ // Validate mode
192
+ if (mode && !["file", "folder"].includes(mode)) {
193
+ console.error(c.red(`❌ Invalid mode: ${mode}`));
194
+ console.error(c.yellow("💡 Mode must be either 'file' or 'folder'"));
195
+ process.exit(1);
196
+ }
197
+ // Validate engine
198
+ const validEngines = [
199
+ "aws",
200
+ "azure",
201
+ "google",
202
+ "deepLPro",
203
+ "deepLFree",
204
+ "openai",
205
+ "huggingface",
206
+ "huggingface-local",
207
+ ];
208
+ if (engine && !validEngines.includes(engine)) {
209
+ console.error(c.red(`❌ Invalid engine: ${engine}`));
210
+ console.error(c.yellow(`💡 Supported engines: ${validEngines.join(", ")}`));
211
+ process.exit(1);
212
+ }
213
+ // Check if input path exists
214
+ if (!existsSync(inputPath)) {
215
+ console.error(c.red(`❌ Input path does not exist: ${inputPath}`));
216
+ process.exit(1);
217
+ }
65
218
  const config = {};
66
219
  // set translate engine config
67
220
  switch (engine) {
68
221
  case "google": {
69
222
  const googleApiKey = process.env.ATJ_GOOGLE_API_KEY;
70
223
  if (!googleApiKey) {
71
- console.error(picocolors_1.default.red("❌ Google api key not found in environment variable ATJ_GOOGLE_API_KEY"));
224
+ console.error(c.red("❌ Google api key not found in environment variable ATJ_GOOGLE_API_KEY"));
72
225
  process.exit(1);
73
226
  }
74
227
  config.translationKeyInfo = {
@@ -82,7 +235,7 @@ switch (engine) {
82
235
  const awsSecretAccessKey = process.env.ATJ_AWS_SECRET_ACCESS_KEY;
83
236
  const awsRegion = process.env.ATJ_AWS_REGION;
84
237
  if (!awsAccessKeyId || !awsSecretAccessKey || !awsRegion) {
85
- console.error(picocolors_1.default.red("❌ AWS credentials not found in environment variables ATJ_AWS_ACCESS_KEY_ID, ATJ_AWS_SECRET_ACCESS_KEY, ATJ_AWS_REGION"));
238
+ console.error(c.red("❌ AWS credentials not found in environment variables ATJ_AWS_ACCESS_KEY_ID, ATJ_AWS_SECRET_ACCESS_KEY, ATJ_AWS_REGION"));
86
239
  process.exit(1);
87
240
  }
88
241
  config.translationKeyInfo = {
@@ -97,7 +250,7 @@ switch (engine) {
97
250
  const azureSecretKey = process.env.ATJ_AZURE_SECRET_KEY;
98
251
  const azureRegion = process.env.ATJ_AZURE_REGION;
99
252
  if (!azureSecretKey || !azureRegion) {
100
- console.error(picocolors_1.default.red("❌ Azure credentials not found in environment variables ATJ_AZURE_SECRET_KEY, ATJ_AZURE_REGION"));
253
+ console.error(c.red("❌ Azure credentials not found in environment variables ATJ_AZURE_SECRET_KEY, ATJ_AZURE_REGION"));
101
254
  process.exit(1);
102
255
  }
103
256
  config.translationKeyInfo = {
@@ -110,27 +263,27 @@ switch (engine) {
110
263
  case "openai": {
111
264
  const openaiApiKey = process.env.ATJ_OPEN_AI_SECRET_KEY;
112
265
  if (!openaiApiKey) {
113
- console.error(picocolors_1.default.red("❌ Openai api key not found in environment variable ATJ_OPEN_AI_SECRET_KEY"));
266
+ console.error(c.red("❌ Openai api key not found in environment variable ATJ_OPEN_AI_SECRET_KEY"));
114
267
  process.exit(1);
115
268
  }
116
269
  config.translationKeyInfo = {
117
270
  kind: "openai",
118
271
  apiKey: openaiApiKey,
119
- baseUrl: (_a = process.env.ATJ_OPEN_AI_BASE_URL) !== null && _a !== void 0 ? _a : "https://api.openai.com/v1",
120
- model: (_b = process.env.ATJ_OPEN_AI_MODEL) !== null && _b !== void 0 ? _b : "gpt-3.5-turbo",
121
- maxTokens: Number((_c = process.env.ATJ_OPEN_AI_MAX_TOKENS) !== null && _c !== void 0 ? _c : "256"),
122
- temperature: Number((_d = process.env.ATJ_OPEN_AI_TEMPERATURE) !== null && _d !== void 0 ? _d : "0.7"),
123
- topP: Number((_e = process.env.ATJ_OPEN_AI_TOP_P) !== null && _e !== void 0 ? _e : "0.9"),
124
- n: Number((_f = process.env.ATJ_OPEN_AI_N) !== null && _f !== void 0 ? _f : "1"),
125
- frequencyPenalty: Number((_g = process.env.ATJ_OPEN_AI_FREQUENCY_PENALTY) !== null && _g !== void 0 ? _g : "0"),
126
- presencePenalty: Number((_h = process.env.ATJ_OPEN_AI_PRESENCE_PENALTY) !== null && _h !== void 0 ? _h : "0"),
272
+ baseUrl: process.env.ATJ_OPEN_AI_BASE_URL ?? "https://api.openai.com/v1",
273
+ model: process.env.ATJ_OPEN_AI_MODEL ?? "gpt-3.5-turbo",
274
+ maxTokens: Number(process.env.ATJ_OPEN_AI_MAX_TOKENS ?? "256"),
275
+ temperature: Number(process.env.ATJ_OPEN_AI_TEMPERATURE ?? "0.7"),
276
+ topP: Number(process.env.ATJ_OPEN_AI_TOP_P ?? "0.9"),
277
+ n: Number(process.env.ATJ_OPEN_AI_N ?? "1"),
278
+ frequencyPenalty: Number(process.env.ATJ_OPEN_AI_FREQUENCY_PENALTY ?? "0"),
279
+ presencePenalty: Number(process.env.ATJ_OPEN_AI_PRESENCE_PENALTY ?? "0"),
127
280
  };
128
281
  break;
129
282
  }
130
283
  case "deepLPro": {
131
284
  const deepLProSecretKey = process.env.ATJ_DEEPL_PRO_SECRET_KEY;
132
285
  if (!deepLProSecretKey) {
133
- console.log(picocolors_1.default.red("❌ DeepL pro api key not found in environment variable ATJ_DEEPL_PRO_SECRET_KEY"));
286
+ console.log(c.red("❌ DeepL pro api key not found in environment variable ATJ_DEEPL_PRO_SECRET_KEY"));
134
287
  process.exit(1);
135
288
  }
136
289
  config.translationKeyInfo = {
@@ -142,7 +295,7 @@ switch (engine) {
142
295
  case "deepLFree": {
143
296
  const deepLFreeSecretKey = process.env.ATJ_DEEPL_FREE_SECRET_KEY;
144
297
  if (!deepLFreeSecretKey) {
145
- console.error(picocolors_1.default.red("❌ DeepL free api key not found in environment variable ATJ_DEEPL_FREE_SECRET_KEY"));
298
+ console.error(c.red("❌ DeepL free api key not found in environment variable ATJ_DEEPL_FREE_SECRET_KEY"));
146
299
  process.exit(1);
147
300
  }
148
301
  config.translationKeyInfo = {
@@ -151,8 +304,34 @@ switch (engine) {
151
304
  };
152
305
  break;
153
306
  }
307
+ case "huggingface": {
308
+ const huggingFaceApiKey = process.env.ATJ_HUGGING_FACE_API_KEY;
309
+ if (!huggingFaceApiKey) {
310
+ console.error(c.red("❌ Hugging Face API key not found in environment variable ATJ_HUGGING_FACE_API_KEY"));
311
+ process.exit(1);
312
+ }
313
+ config.translationKeyInfo = {
314
+ kind: "huggingface",
315
+ apiKey: huggingFaceApiKey,
316
+ model: process.env.ATJ_HUGGING_FACE_MODEL ?? "Helsinki-NLP/opus-mt-en-fr",
317
+ provider: process.env.ATJ_HUGGING_FACE_PROVIDER,
318
+ };
319
+ break;
320
+ }
321
+ case "huggingface-local": {
322
+ const huggingFaceLocalModel = process.env.ATJ_HUGGING_FACE_LOCAL_MODEL;
323
+ if (!huggingFaceLocalModel) {
324
+ console.error(c.red("❌ Hugging Face local model not found in environment variable ATJ_HUGGING_FACE_LOCAL_MODEL"));
325
+ process.exit(1);
326
+ }
327
+ config.translationKeyInfo = {
328
+ kind: "huggingface-local",
329
+ model: huggingFaceLocalModel,
330
+ };
331
+ break;
332
+ }
154
333
  default:
155
- console.error(picocolors_1.default.red(`❌ Engine ${engine} not supported`));
334
+ console.error(c.red(`❌ Engine ${engine} not supported`));
156
335
  process.exit(1);
157
336
  }
158
337
  if (process.env.ATJ_START_DELIMITER) {
@@ -165,9 +344,18 @@ config.sourceLocale = sourceLocale;
165
344
  config.keepTranslations = keepTranslations ? "keep" : "retranslate";
166
345
  config.keepExtraTranslations = keepExtraTranslations ? "keep" : "remove";
167
346
  config.mode = mode;
168
- const sourcePath = node_path_1.default.join(process.cwd(), inputPath);
169
- console.log(picocolors_1.default.green(`🌐 Translating ${sourcePath}`));
170
- (0, lib_1.translate)(sourcePath, config).catch((error) => {
171
- console.error(picocolors_1.default.red("❌ Translate error:\n"), error);
347
+ if (format) {
348
+ config.format = format;
349
+ }
350
+ async function main() {
351
+ // Load the translation runtime only when an actual translation command is executed.
352
+ await import("../format/index.js");
353
+ const { translate } = await import("../lib.js");
354
+ const sourcePath = path.join(process.cwd(), inputPath);
355
+ console.log(c.green(`🌐 Translating ${sourcePath}`));
356
+ await translate(sourcePath, config);
357
+ }
358
+ main().catch((error) => {
359
+ console.error(c.red("❌ Translate error:\n"), error);
172
360
  process.exit(1);
173
361
  });
@@ -1,5 +1,6 @@
1
+ import type { InferenceProviderOrPolicy } from "@huggingface/inference";
1
2
  export type Configuration = {
2
- translationKeyInfo: GoogleTranslationKey | AwsTranslationKey | AzureTranslationKey | DeepLProTranslationKey | DeepLFreeTranslationKey | OpenAITranslationKey;
3
+ translationKeyInfo: GoogleTranslationKey | AwsTranslationKey | AzureTranslationKey | DeepLProTranslationKey | DeepLFreeTranslationKey | OpenAITranslationKey | HuggingFaceTranslationKey | HuggingFaceLocalTranslationKey;
3
4
  startDelimiter: string;
4
5
  endDelimiter: string;
5
6
  mode: "file" | "folder";
@@ -7,6 +8,7 @@ export type Configuration = {
7
8
  keepTranslations: "keep" | "retranslate";
8
9
  keepExtraTranslations: "keep" | "remove";
9
10
  ignorePrefix: string;
11
+ format?: string;
10
12
  };
11
13
  type GoogleTranslationKey = {
12
14
  kind: "google";
@@ -43,4 +45,14 @@ type OpenAITranslationKey = {
43
45
  frequencyPenalty: number;
44
46
  presencePenalty: number;
45
47
  };
48
+ type HuggingFaceTranslationKey = {
49
+ kind: "huggingface";
50
+ apiKey: string;
51
+ model: string;
52
+ provider?: InferenceProviderOrPolicy;
53
+ };
54
+ type HuggingFaceLocalTranslationKey = {
55
+ kind: "huggingface-local";
56
+ model: string;
57
+ };
46
58
  export {};
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
@@ -1,4 +1,4 @@
1
- import type { ITranslate } from "./translate.interface";
1
+ import type { ITranslate } from "./translate.interface.js";
2
2
  export declare class DeepLTranslate implements ITranslate {
3
3
  private subscriptionKey;
4
4
  private type;
@@ -1,50 +1,5 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
- return new (P || (P = Promise))(function (resolve, reject) {
38
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
- step((generator = generator.apply(thisArg, _arguments || [])).next());
42
- });
43
- };
44
- Object.defineProperty(exports, "__esModule", { value: true });
45
- exports.DeepLTranslate = void 0;
46
- const deepl = __importStar(require("deepl-node"));
47
- const util_1 = require("./util");
1
+ import * as deepl from "deepl-node";
2
+ import { Util } from "./util.js";
48
3
  const supportedLanguages = [
49
4
  "AR",
50
5
  "BG",
@@ -82,11 +37,13 @@ const supportedLanguages = [
82
37
  "UK",
83
38
  "ZH",
84
39
  ];
85
- class DeepLTranslate {
40
+ export class DeepLTranslate {
41
+ subscriptionKey;
42
+ type;
43
+ endpoint = "https://api.deepl.com";
86
44
  constructor(subscriptionKey, type) {
87
45
  this.subscriptionKey = subscriptionKey;
88
46
  this.type = type;
89
- this.endpoint = "https://api.deepl.com";
90
47
  if (this.type === "free") {
91
48
  this.endpoint = "https://api-free.deepl.com";
92
49
  }
@@ -94,22 +51,19 @@ class DeepLTranslate {
94
51
  isValidLocale(targetLocale) {
95
52
  return supportedLanguages.includes(targetLocale.toUpperCase());
96
53
  }
97
- translateText(text, sourceLocale, targetLocale) {
98
- return __awaiter(this, void 0, void 0, function* () {
99
- let args;
100
- ({ args, text } = util_1.Util.replaceContextVariables(text));
101
- let result = "";
102
- const translator = new deepl.Translator(this.subscriptionKey, {
103
- serverUrl: this.endpoint,
104
- minTimeout: 10000,
105
- maxRetries: 5,
106
- });
107
- const translation = yield translator.translateText(text, sourceLocale, targetLocale);
108
- result = translation.text;
109
- result = util_1.Util.replaceArgumentsWithNumbers(args, result);
110
- return result;
54
+ async translateText(text, sourceLocale, targetLocale) {
55
+ let args;
56
+ ({ args, text } = Util.replaceContextVariables(text));
57
+ let result = "";
58
+ const translator = new deepl.Translator(this.subscriptionKey, {
59
+ serverUrl: this.endpoint,
60
+ minTimeout: 10000,
61
+ maxRetries: 5,
111
62
  });
63
+ const translation = await translator.translateText(text, sourceLocale, targetLocale);
64
+ result = translation.text;
65
+ result = Util.replaceArgumentsWithNumbers(args, result);
66
+ return result;
112
67
  }
113
68
  }
114
- exports.DeepLTranslate = DeepLTranslate;
115
69
  // https://www.deepl.com/docs-api/translating-text/example/
@@ -1,9 +1,12 @@
1
- import type { TranslationFile } from "./translate.interface";
1
+ import type { TranslationFile } from "./translate.interface.js";
2
+ import "./format/index.js";
2
3
  export interface IFiles {
3
4
  sourceLocale: string;
4
5
  targetLocales: Array<string>;
5
6
  loadJsonFromLocale(locale: string): Promise<TranslationFile>;
6
7
  saveJsonToLocale(locale: string, file: TranslationFile): void;
8
+ getDetectedFormat?(): string | undefined;
9
+ getFormatOverride?(): string | undefined;
7
10
  }
8
11
  export declare const readFileAsync: (filename: string) => Promise<string>;
9
12
  export declare const loadJsonFromLocale: (fileName: string) => Promise<TranslationFile>;
@@ -12,9 +15,15 @@ export declare class Files implements IFiles {
12
15
  folderPath: string;
13
16
  sourceLocale: string;
14
17
  targetLocales: Array<string>;
15
- constructor(filePath: string);
18
+ private fileExt;
19
+ private formatOverride?;
20
+ private detectedFormat?;
21
+ constructor(filePath: string, formatOverride?: string);
16
22
  private getLocaleFromFilename;
23
+ private detectFileFormat;
17
24
  private getTargetLocales;
25
+ getDetectedFormat(): string | undefined;
26
+ getFormatOverride(): string | undefined;
18
27
  loadJsonFromLocale(locale: string): Promise<TranslationFile>;
19
28
  saveJsonToLocale(locale: string, file: TranslationFile): void;
20
29
  }