auto-translate-json-library 1.5.4 → 2.0.2

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 (108) hide show
  1. package/README.MD +1141 -148
  2. package/build/package.json +97 -21
  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 -63
  7. package/build/src/bin/cli.d.ts +1 -1
  8. package/build/src/bin/cli.js +196 -37
  9. package/build/src/config.d.ts +1 -0
  10. package/build/src/config.js +1 -2
  11. package/build/src/deepl.d.ts +1 -1
  12. package/build/src/deepl.js +18 -64
  13. package/build/src/files.d.ts +11 -2
  14. package/build/src/files.js +356 -69
  15. package/build/src/folderFiles.d.ts +6 -3
  16. package/build/src/folderFiles.js +33 -44
  17. package/build/src/format/arb-handler.d.ts +33 -0
  18. package/build/src/format/arb-handler.js +679 -0
  19. package/build/src/format/base-format-handler.d.ts +75 -0
  20. package/build/src/format/base-format-handler.js +166 -0
  21. package/build/src/format/csv-handler.d.ts +38 -0
  22. package/build/src/format/csv-handler.js +604 -0
  23. package/build/src/format/index.d.ts +17 -0
  24. package/build/src/format/index.js +48 -0
  25. package/build/src/format/json-handler.d.ts +17 -0
  26. package/build/src/format/json-handler.js +294 -0
  27. package/build/src/format/po-handler.d.ts +17 -0
  28. package/build/src/format/po-handler.js +338 -0
  29. package/build/src/format/po-utils.d.ts +86 -0
  30. package/build/src/format/po-utils.js +385 -0
  31. package/build/src/format/pot-handler.d.ts +22 -0
  32. package/build/src/format/pot-handler.js +331 -0
  33. package/build/src/format/properties-handler.d.ts +26 -0
  34. package/build/src/format/properties-handler.js +500 -0
  35. package/build/src/format/tsv-handler.d.ts +13 -0
  36. package/build/src/format/tsv-handler.js +67 -0
  37. package/build/src/format/xliff-handler.d.ts +24 -0
  38. package/build/src/format/xliff-handler.js +433 -0
  39. package/build/src/format/xmb-handler.d.ts +33 -0
  40. package/build/src/format/xmb-handler.js +484 -0
  41. package/build/src/format/xmb-xtb-utils.d.ts +43 -0
  42. package/build/src/format/xmb-xtb-utils.js +180 -0
  43. package/build/src/format/xml-handler.d.ts +28 -0
  44. package/build/src/format/xml-handler.js +561 -0
  45. package/build/src/format/xtb-handler.d.ts +33 -0
  46. package/build/src/format/xtb-handler.js +518 -0
  47. package/build/src/format/yaml-handler.d.ts +26 -0
  48. package/build/src/format/yaml-handler.js +522 -0
  49. package/build/src/format-detector.d.ts +7 -0
  50. package/build/src/format-detector.js +58 -0
  51. package/build/src/format-handler-factory.d.ts +9 -0
  52. package/build/src/format-handler-factory.js +18 -0
  53. package/build/src/format.interface.d.ts +56 -0
  54. package/build/src/format.interface.js +1 -0
  55. package/build/src/google.d.ts +1 -1
  56. package/build/src/google.js +32 -49
  57. package/build/src/index.d.ts +4 -3
  58. package/build/src/index.js +15 -17
  59. package/build/src/lib.d.ts +1 -1
  60. package/build/src/lib.js +188 -133
  61. package/build/src/openai.d.ts +2 -2
  62. package/build/src/openai.js +59 -50
  63. package/build/src/translate.interface.d.ts +1 -1
  64. package/build/src/translate.interface.js +1 -2
  65. package/build/src/util.js +4 -9
  66. package/build/src/validation/enhanced-validation-result.d.ts +96 -0
  67. package/build/src/validation/enhanced-validation-result.js +198 -0
  68. package/build/src/validation/error-messages.d.ts +88 -0
  69. package/build/src/validation/error-messages.js +436 -0
  70. package/build/src/validation/error-recovery.d.ts +78 -0
  71. package/build/src/validation/error-recovery.js +593 -0
  72. package/build/src/validation/example-usage.d.ts +31 -0
  73. package/build/src/validation/example-usage.js +148 -0
  74. package/build/src/validation/format-rules.d.ts +37 -0
  75. package/build/src/validation/format-rules.js +550 -0
  76. package/build/src/validation/format-validator.d.ts +70 -0
  77. package/build/src/validation/format-validator.js +279 -0
  78. package/build/src/validation/index.d.ts +13 -0
  79. package/build/src/validation/index.js +30 -0
  80. package/build/src/validation/validation-service.d.ts +56 -0
  81. package/build/src/validation/validation-service.js +262 -0
  82. package/build/tests/arb-handler.test.d.ts +1 -0
  83. package/build/tests/arb-handler.test.js +694 -0
  84. package/build/tests/cli-integration.test.d.ts +1 -0
  85. package/build/tests/cli-integration.test.js +352 -0
  86. package/build/tests/csv-handler.test.d.ts +1 -0
  87. package/build/tests/csv-handler.test.js +507 -0
  88. package/build/tests/error-handling.test.d.ts +1 -0
  89. package/build/tests/error-handling.test.js +456 -0
  90. package/build/tests/files-integration.test.d.ts +1 -0
  91. package/build/tests/files-integration.test.js +421 -0
  92. package/build/tests/json-handler.test.d.ts +1 -0
  93. package/build/tests/json-handler.test.js +526 -0
  94. package/build/tests/po-handler.test.d.ts +1 -0
  95. package/build/tests/po-handler.test.js +768 -0
  96. package/build/tests/properties-handler.test.d.ts +1 -0
  97. package/build/tests/properties-handler.test.js +316 -0
  98. package/build/tests/setup.d.ts +1 -0
  99. package/build/tests/setup.js +5 -0
  100. package/build/tests/xliff-handler.test.d.ts +1 -0
  101. package/build/tests/xliff-handler.test.js +459 -0
  102. package/build/tests/xmb-xtb-handler.test.d.ts +1 -0
  103. package/build/tests/xmb-xtb-handler.test.js +758 -0
  104. package/build/tests/xml-handler.test.d.ts +1 -0
  105. package/build/tests/xml-handler.test.js +570 -0
  106. package/build/tests/yaml-handler.test.d.ts +1 -0
  107. package/build/tests/yaml-handler.test.js +156 -0
  108. package/package.json +97 -21
@@ -0,0 +1,522 @@
1
+ import * as path from "node:path";
2
+ import * as yaml from "js-yaml";
3
+ export class YamlHandler {
4
+ canHandle(filePath, content) {
5
+ const extension = path.extname(filePath).toLowerCase();
6
+ if (extension !== ".yaml" && extension !== ".yml") {
7
+ return false;
8
+ }
9
+ // If content is provided, check for valid YAML
10
+ if (content) {
11
+ try {
12
+ yaml.load(content);
13
+ return true;
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ return true;
20
+ }
21
+ parse(content) {
22
+ try {
23
+ const parsed = yaml.load(content, {
24
+ schema: yaml.DEFAULT_SCHEMA,
25
+ json: false, // Allow YAML-specific features
26
+ });
27
+ if (parsed === null || parsed === undefined) {
28
+ throw new Error("YAML file is empty or contains only null/undefined");
29
+ }
30
+ if (typeof parsed !== "object" || Array.isArray(parsed)) {
31
+ throw new Error("YAML root must be an object, not an array or primitive value");
32
+ }
33
+ // Flatten nested structures for translation while preserving metadata
34
+ const flattened = this.flattenObject(parsed);
35
+ // Add metadata
36
+ const result = {
37
+ ...flattened,
38
+ _metadata: {
39
+ format: "yaml",
40
+ originalStructure: parsed,
41
+ preserveComments: true, // YAML supports comments
42
+ preserveAttributes: false,
43
+ },
44
+ };
45
+ return result;
46
+ }
47
+ catch (error) {
48
+ throw new Error(`Failed to parse YAML: ${error instanceof Error ? error.message : String(error)}`);
49
+ }
50
+ }
51
+ serialize(data, options) {
52
+ try {
53
+ // Remove metadata for serialization
54
+ const { _metadata, ...cleanData } = data;
55
+ let result;
56
+ if (_metadata?.originalStructure) {
57
+ // Reconstruct original nested structure with translated values
58
+ result = this.reconstructNestedStructure(_metadata.originalStructure, cleanData);
59
+ }
60
+ else {
61
+ // Use flat structure or attempt to reconstruct from dot notation
62
+ result = this.reconstructFromFlatStructure(cleanData);
63
+ }
64
+ // Apply formatting options
65
+ const yamlOptions = {
66
+ indent: this.getIndentation(options),
67
+ lineWidth: -1, // Disable line wrapping
68
+ noRefs: true, // Disable references
69
+ sortKeys: false, // Preserve key order
70
+ schema: yaml.DEFAULT_SCHEMA,
71
+ };
72
+ // Preserve formatting if requested
73
+ if (options?.preserveFormatting !== false) {
74
+ yamlOptions.flowLevel = -1; // Use block style by default
75
+ }
76
+ return yaml.dump(result, yamlOptions);
77
+ }
78
+ catch (error) {
79
+ throw new Error(`Failed to serialize YAML: ${error instanceof Error ? error.message : String(error)}`);
80
+ }
81
+ }
82
+ getFileExtension() {
83
+ return ".yaml";
84
+ }
85
+ validateStructure(data) {
86
+ const errors = [];
87
+ const warnings = [];
88
+ // Basic YAML structure validation
89
+ if (!data || typeof data !== "object") {
90
+ errors.push({
91
+ code: "INVALID_STRUCTURE",
92
+ message: "YAML data must be an object",
93
+ });
94
+ return { isValid: false, errors, warnings };
95
+ }
96
+ if (Array.isArray(data)) {
97
+ errors.push({
98
+ code: "INVALID_ROOT_TYPE",
99
+ message: "YAML root cannot be an array for translation files",
100
+ });
101
+ return { isValid: false, errors, warnings };
102
+ }
103
+ // Check for circular references
104
+ try {
105
+ JSON.stringify(data);
106
+ }
107
+ catch (error) {
108
+ if (error instanceof TypeError && error.message.includes("circular")) {
109
+ errors.push({
110
+ code: "CIRCULAR_REFERENCE",
111
+ message: "YAML contains circular references",
112
+ });
113
+ }
114
+ }
115
+ // Validate YAML-specific data types and structure integrity
116
+ this.validateYamlDataTypes(data, "", errors, warnings);
117
+ // Validate hierarchical structure integrity
118
+ this.validateHierarchicalStructure(data, "", errors, warnings);
119
+ // Validate that all values are translatable (strings or nested objects with strings)
120
+ this.validateTranslatableContent(data, "", errors, warnings);
121
+ // Check for empty object
122
+ if (Object.keys(data).length === 0) {
123
+ warnings.push({
124
+ code: "EMPTY_YAML",
125
+ message: "YAML file appears to be empty",
126
+ });
127
+ }
128
+ return {
129
+ isValid: errors.length === 0,
130
+ errors,
131
+ warnings,
132
+ };
133
+ }
134
+ validateYamlDataTypes(obj, path, errors, warnings) {
135
+ for (const [key, value] of Object.entries(obj)) {
136
+ const currentPath = path ? `${path}.${key}` : key;
137
+ // Check for YAML-specific data types
138
+ if (value instanceof Date) {
139
+ warnings.push({
140
+ code: "DATE_VALUE",
141
+ message: `Date value at ${currentPath} will be preserved but not translated`,
142
+ });
143
+ }
144
+ else if (typeof value === "object" &&
145
+ value !== null &&
146
+ !Array.isArray(value)) {
147
+ // Recursively validate nested objects
148
+ this.validateYamlDataTypes(value, currentPath, errors, warnings);
149
+ }
150
+ else if (Array.isArray(value)) {
151
+ // Validate array contents
152
+ this.validateArrayDataTypes(value, currentPath, errors, warnings);
153
+ }
154
+ }
155
+ }
156
+ validateArrayDataTypes(arr, path, errors, warnings) {
157
+ arr.forEach((item, index) => {
158
+ const arrayPath = `${path}[${index}]`;
159
+ if (item instanceof Date) {
160
+ warnings.push({
161
+ code: "DATE_VALUE_IN_ARRAY",
162
+ message: `Date value at ${arrayPath} will be preserved but not translated`,
163
+ });
164
+ }
165
+ else if (typeof item === "object" &&
166
+ item !== null &&
167
+ !Array.isArray(item)) {
168
+ this.validateYamlDataTypes(item, arrayPath, errors, warnings);
169
+ }
170
+ else if (Array.isArray(item)) {
171
+ this.validateArrayDataTypes(item, arrayPath, errors, warnings);
172
+ }
173
+ });
174
+ }
175
+ validateHierarchicalStructure(obj, path, errors, warnings) {
176
+ const keys = Object.keys(obj);
177
+ // Check for deeply nested structures (more than 10 levels)
178
+ const depth = path.split(".").length;
179
+ if (depth > 10) {
180
+ warnings.push({
181
+ code: "DEEP_NESTING",
182
+ message: `Very deep nesting detected at ${path} (${depth} levels). Consider flattening the structure.`,
183
+ });
184
+ }
185
+ // Check for mixed array and object structures at the same level
186
+ let hasArrays = false;
187
+ let hasObjects = false;
188
+ for (const [key, value] of Object.entries(obj)) {
189
+ if (Array.isArray(value)) {
190
+ hasArrays = true;
191
+ }
192
+ else if (typeof value === "object" && value !== null) {
193
+ hasObjects = true;
194
+ }
195
+ // Recursively check nested structures
196
+ if (typeof value === "object" &&
197
+ value !== null &&
198
+ !Array.isArray(value)) {
199
+ this.validateHierarchicalStructure(value, path ? `${path}.${key}` : key, errors, warnings);
200
+ }
201
+ }
202
+ if (hasArrays && hasObjects && path) {
203
+ warnings.push({
204
+ code: "MIXED_STRUCTURE",
205
+ message: `Mixed array and object structure at ${path}. This is valid but may complicate translation.`,
206
+ });
207
+ }
208
+ }
209
+ flattenObject(obj, prefix = "", result = {}) {
210
+ for (const [key, value] of Object.entries(obj)) {
211
+ const newKey = prefix ? `${prefix}.${key}` : key;
212
+ if (typeof value === "string") {
213
+ result[newKey] = value;
214
+ }
215
+ else if (this.isNonStringPreservableValue(value)) {
216
+ // Preserve non-string values as-is (numbers, booleans, dates, null, etc.)
217
+ result[newKey] = value;
218
+ }
219
+ else if (typeof value === "object" &&
220
+ value !== null &&
221
+ !Array.isArray(value)) {
222
+ // Recursively flatten nested objects
223
+ this.flattenObject(value, newKey, result);
224
+ }
225
+ else if (Array.isArray(value)) {
226
+ // Handle arrays - support both simple arrays and complex nested arrays
227
+ this.flattenArray(value, newKey, result);
228
+ }
229
+ else {
230
+ // Other values are preserved as-is
231
+ result[newKey] = value;
232
+ }
233
+ }
234
+ return result;
235
+ }
236
+ flattenArray(arr, prefix, result) {
237
+ arr.forEach((item, index) => {
238
+ const arrayKey = `${prefix}[${index}]`;
239
+ if (typeof item === "string") {
240
+ result[arrayKey] = item;
241
+ }
242
+ else if (this.isNonStringPreservableValue(item)) {
243
+ // Preserve non-string values as-is
244
+ result[arrayKey] = item;
245
+ }
246
+ else if (typeof item === "object" &&
247
+ item !== null &&
248
+ !Array.isArray(item)) {
249
+ // Handle objects within arrays
250
+ this.flattenObject(item, arrayKey, result);
251
+ }
252
+ else if (Array.isArray(item)) {
253
+ // Handle nested arrays
254
+ this.flattenArray(item, arrayKey, result);
255
+ }
256
+ else {
257
+ // Other values are preserved as-is
258
+ result[arrayKey] = item;
259
+ }
260
+ });
261
+ }
262
+ reconstructNestedStructure(original, translations) {
263
+ // Deep clone the original structure
264
+ const result = this.deepClone(original);
265
+ // Update with translated values
266
+ this.updateNestedValues(result, translations);
267
+ return result;
268
+ }
269
+ updateNestedValues(obj, translations, path = "") {
270
+ for (const [key, value] of Object.entries(obj)) {
271
+ const currentPath = path ? `${path}.${key}` : key;
272
+ if (typeof value === "string") {
273
+ // Check if we have a translation for this path
274
+ if (translations[currentPath] !== undefined) {
275
+ obj[key] = translations[currentPath];
276
+ }
277
+ }
278
+ else if (this.isNonStringPreservableValue(value)) {
279
+ // Check if we have a replacement for non-string values (preserve original if no translation)
280
+ if (translations[currentPath] !== undefined) {
281
+ obj[key] = translations[currentPath];
282
+ }
283
+ // Otherwise, keep the original non-string value
284
+ }
285
+ else if (typeof value === "object" &&
286
+ value !== null &&
287
+ !Array.isArray(value)) {
288
+ // Recursively update nested objects
289
+ this.updateNestedValues(value, translations, currentPath);
290
+ }
291
+ else if (Array.isArray(value)) {
292
+ // Handle arrays
293
+ this.updateArrayValues(value, translations, currentPath);
294
+ }
295
+ }
296
+ }
297
+ updateArrayValues(arr, translations, path) {
298
+ arr.forEach((item, index) => {
299
+ const arrayPath = `${path}[${index}]`;
300
+ if (typeof item === "string" && translations[arrayPath] !== undefined) {
301
+ arr[index] = translations[arrayPath];
302
+ }
303
+ else if (this.isNonStringPreservableValue(item)) {
304
+ // Check if we have a replacement for non-string values
305
+ if (translations[arrayPath] !== undefined) {
306
+ arr[index] = translations[arrayPath];
307
+ }
308
+ // Otherwise, keep the original non-string value
309
+ }
310
+ else if (typeof item === "object" &&
311
+ item !== null &&
312
+ !Array.isArray(item)) {
313
+ this.updateNestedValues(item, translations, arrayPath);
314
+ }
315
+ else if (Array.isArray(item)) {
316
+ this.updateArrayValues(item, translations, arrayPath);
317
+ }
318
+ });
319
+ }
320
+ reconstructFromFlatStructure(flatData) {
321
+ const result = {};
322
+ for (const [key, value] of Object.entries(flatData)) {
323
+ this.setNestedValue(result, key, value);
324
+ }
325
+ return result;
326
+ }
327
+ setNestedValue(obj, path, value) {
328
+ const keys = this.parsePath(path);
329
+ let current = obj;
330
+ for (let i = 0; i < keys.length - 1; i++) {
331
+ const key = keys[i];
332
+ if (key.isArray) {
333
+ if (!Array.isArray(current[key.name])) {
334
+ current[key.name] = [];
335
+ }
336
+ // Ensure array has enough elements
337
+ while (current[key.name].length <= key.index) {
338
+ // For non-string preservable values, use appropriate default
339
+ const defaultValue = this.isNonStringPreservableValue(value)
340
+ ? null
341
+ : {};
342
+ current[key.name].push(defaultValue);
343
+ }
344
+ current = current[key.name][key.index];
345
+ }
346
+ else {
347
+ if (!(key.name in current)) {
348
+ current[key.name] = {};
349
+ }
350
+ current = current[key.name];
351
+ }
352
+ }
353
+ const lastKey = keys[keys.length - 1];
354
+ if (lastKey.isArray) {
355
+ if (!Array.isArray(current[lastKey.name])) {
356
+ current[lastKey.name] = [];
357
+ }
358
+ // Ensure array has enough elements
359
+ while (current[lastKey.name].length <= lastKey.index) {
360
+ current[lastKey.name].push(null);
361
+ }
362
+ current[lastKey.name][lastKey.index] = value;
363
+ }
364
+ else {
365
+ current[lastKey.name] = value;
366
+ }
367
+ }
368
+ parsePath(path) {
369
+ const parts = path.split(".");
370
+ const result = [];
371
+ for (const part of parts) {
372
+ const arrayMatch = part.match(/^(.+)\[(\d+)\]$/);
373
+ if (arrayMatch) {
374
+ result.push({
375
+ name: arrayMatch[1],
376
+ isArray: true,
377
+ index: parseInt(arrayMatch[2], 10),
378
+ });
379
+ }
380
+ else {
381
+ result.push({
382
+ name: part,
383
+ isArray: false,
384
+ });
385
+ }
386
+ }
387
+ return result;
388
+ }
389
+ validateTranslatableContent(obj, path, errors, warnings, visited = new Set()) {
390
+ // Check for circular references
391
+ if (visited.has(obj)) {
392
+ return; // Already processed this object
393
+ }
394
+ if (typeof obj === "object" && obj !== null) {
395
+ visited.add(obj);
396
+ }
397
+ for (const [key, value] of Object.entries(obj)) {
398
+ const currentPath = path ? `${path}.${key}` : key;
399
+ if (typeof value === "string") {
400
+ // String values are translatable - this is good
401
+ continue;
402
+ }
403
+ else if (this.isNonStringPreservableValue(value)) {
404
+ // Non-string values that should be preserved
405
+ const valueType = this.getValueTypeDescription(value);
406
+ warnings.push({
407
+ code: "NON_TRANSLATABLE_VALUE_PRESERVED",
408
+ message: `${valueType} value at ${currentPath} will be preserved unchanged`,
409
+ });
410
+ }
411
+ else if (typeof value === "object" &&
412
+ value !== null &&
413
+ !Array.isArray(value)) {
414
+ // Nested objects - recursively validate
415
+ this.validateTranslatableContent(value, currentPath, errors, warnings, visited);
416
+ }
417
+ else if (Array.isArray(value)) {
418
+ // Arrays - check each element
419
+ this.validateArrayTranslatableContent(value, currentPath, errors, warnings, visited);
420
+ }
421
+ else {
422
+ // Other non-string, non-object values
423
+ const valueType = this.getValueTypeDescription(value);
424
+ warnings.push({
425
+ code: "NON_TRANSLATABLE_VALUE",
426
+ message: `${valueType} value at ${currentPath} is not translatable`,
427
+ });
428
+ }
429
+ }
430
+ if (typeof obj === "object" && obj !== null) {
431
+ visited.delete(obj);
432
+ }
433
+ }
434
+ validateArrayTranslatableContent(arr, path, errors, warnings, visited) {
435
+ arr.forEach((item, index) => {
436
+ const arrayPath = `${path}[${index}]`;
437
+ if (typeof item === "string") {
438
+ // String in array is translatable
439
+ return;
440
+ }
441
+ else if (this.isNonStringPreservableValue(item)) {
442
+ // Non-string values that should be preserved
443
+ const valueType = this.getValueTypeDescription(item);
444
+ warnings.push({
445
+ code: "NON_TRANSLATABLE_ARRAY_ITEM_PRESERVED",
446
+ message: `${valueType} value at ${arrayPath} will be preserved unchanged`,
447
+ });
448
+ }
449
+ else if (typeof item === "object" &&
450
+ item !== null &&
451
+ !Array.isArray(item)) {
452
+ this.validateTranslatableContent(item, arrayPath, errors, warnings, visited);
453
+ }
454
+ else if (Array.isArray(item)) {
455
+ this.validateArrayTranslatableContent(item, arrayPath, errors, warnings, visited);
456
+ }
457
+ else {
458
+ // Other non-string, non-object values in arrays
459
+ const valueType = this.getValueTypeDescription(item);
460
+ warnings.push({
461
+ code: "NON_TRANSLATABLE_ARRAY_ITEM",
462
+ message: `${valueType} value at ${arrayPath} is not translatable`,
463
+ });
464
+ }
465
+ });
466
+ }
467
+ isNonStringPreservableValue(value) {
468
+ // Define which non-string values should be preserved
469
+ return (typeof value === "number" ||
470
+ typeof value === "boolean" ||
471
+ value === null ||
472
+ value === undefined ||
473
+ value instanceof Date ||
474
+ // YAML-specific types that should be preserved
475
+ (typeof value === "object" &&
476
+ value !== null &&
477
+ value.constructor &&
478
+ ["RegExp", "Buffer"].includes(value.constructor.name)));
479
+ }
480
+ getValueTypeDescription(value) {
481
+ if (value === null)
482
+ return "null";
483
+ if (value === undefined)
484
+ return "undefined";
485
+ if (value instanceof Date)
486
+ return "Date";
487
+ if (typeof value === "number")
488
+ return "number";
489
+ if (typeof value === "boolean")
490
+ return "boolean";
491
+ if (Array.isArray(value))
492
+ return "array";
493
+ if (typeof value === "object" && value.constructor) {
494
+ return value.constructor.name;
495
+ }
496
+ return typeof value;
497
+ }
498
+ getIndentation(options) {
499
+ if (options?.indentation !== undefined) {
500
+ if (typeof options.indentation === "number") {
501
+ return options.indentation;
502
+ }
503
+ if (typeof options.indentation === "string") {
504
+ return options.indentation.length;
505
+ }
506
+ }
507
+ return 2; // Default indentation
508
+ }
509
+ deepClone(obj) {
510
+ if (obj === null || typeof obj !== "object") {
511
+ return obj;
512
+ }
513
+ if (Array.isArray(obj)) {
514
+ return obj.map((item) => this.deepClone(item));
515
+ }
516
+ const cloned = {};
517
+ for (const [key, value] of Object.entries(obj)) {
518
+ cloned[key] = this.deepClone(value);
519
+ }
520
+ return cloned;
521
+ }
522
+ }
@@ -0,0 +1,7 @@
1
+ export declare class FormatDetector {
2
+ private static extensionMap;
3
+ private static contentSignatures;
4
+ static detectFormat(filePath: string, content?: string): string;
5
+ static getSupportedExtensions(): string[];
6
+ static getSupportedFormats(): string[];
7
+ }
@@ -0,0 +1,58 @@
1
+ import * as path from "node:path";
2
+ export class FormatDetector {
3
+ static extensionMap = new Map([
4
+ [".json", "json"],
5
+ [".xml", "xml"],
6
+ [".xlf", "xliff"],
7
+ [".xliff", "xliff"],
8
+ [".po", "po"],
9
+ [".pot", "pot"],
10
+ [".yaml", "yaml"],
11
+ [".yml", "yaml"],
12
+ [".properties", "properties"],
13
+ [".csv", "csv"],
14
+ [".tsv", "tsv"],
15
+ [".arb", "arb"],
16
+ [".xmb", "xmb"],
17
+ [".xtb", "xtb"],
18
+ ]);
19
+ static contentSignatures = new Map([
20
+ [/^\s*<\?xml[\s\S]*<resources>/, "android-xml"],
21
+ [/^\s*<\?xml[\s\S]*<plist/, "ios-xml"],
22
+ [/^\s*<\?xml[\s\S]*<xliff/, "xliff"],
23
+ [/^\s*<\?xml[\s\S]*<messagebundle/, "xmb"],
24
+ [/^\s*<\?xml[\s\S]*<translationbundle/, "xtb"],
25
+ [/^\s*{[\s\S]*"@@locale"/, "arb"],
26
+ [/^\s*msgid\s+"/m, "po"],
27
+ [/^\s*#.*POT-Creation-Date/m, "pot"],
28
+ [/^\s*[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m, "properties"],
29
+ ]);
30
+ static detectFormat(filePath, content) {
31
+ const extension = path.extname(filePath).toLowerCase();
32
+ // First try extension-based detection
33
+ const formatFromExtension = this.extensionMap.get(extension);
34
+ // For YAML files, prioritize extension-based detection to avoid confusion with properties
35
+ if (formatFromExtension === 'yaml') {
36
+ return formatFromExtension;
37
+ }
38
+ if (formatFromExtension && !content) {
39
+ return formatFromExtension;
40
+ }
41
+ // If content is provided, use content signature detection
42
+ if (content) {
43
+ for (const [pattern, format] of this.contentSignatures) {
44
+ if (pattern.test(content)) {
45
+ return format;
46
+ }
47
+ }
48
+ }
49
+ // Fallback to extension-based detection
50
+ return formatFromExtension || "unknown";
51
+ }
52
+ static getSupportedExtensions() {
53
+ return Array.from(this.extensionMap.keys());
54
+ }
55
+ static getSupportedFormats() {
56
+ return Array.from(new Set(this.extensionMap.values()));
57
+ }
58
+ }
@@ -0,0 +1,9 @@
1
+ import type { IFormatHandler } from "./format.interface.js";
2
+ export declare class FormatHandlerFactory {
3
+ private static handlers;
4
+ static registerHandler(format: string, handler: IFormatHandler): void;
5
+ static getHandler(format: string): IFormatHandler | undefined;
6
+ static getSupportedFormats(): string[];
7
+ static hasHandler(format: string): boolean;
8
+ static getAllHandlers(): Map<string, IFormatHandler>;
9
+ }
@@ -0,0 +1,18 @@
1
+ export class FormatHandlerFactory {
2
+ static handlers = new Map();
3
+ static registerHandler(format, handler) {
4
+ this.handlers.set(format, handler);
5
+ }
6
+ static getHandler(format) {
7
+ return this.handlers.get(format);
8
+ }
9
+ static getSupportedFormats() {
10
+ return Array.from(this.handlers.keys());
11
+ }
12
+ static hasHandler(format) {
13
+ return this.handlers.has(format);
14
+ }
15
+ static getAllHandlers() {
16
+ return new Map(this.handlers);
17
+ }
18
+ }
@@ -0,0 +1,56 @@
1
+ import type { TranslationFile } from "./translate.interface.js";
2
+ export interface FormatOptions {
3
+ preserveFormatting?: boolean;
4
+ encoding?: string;
5
+ indentation?: string | number;
6
+ xmlDeclaration?: boolean;
7
+ namespace?: string;
8
+ customSettings?: Record<string, any>;
9
+ }
10
+ export interface ValidationError {
11
+ code: string;
12
+ message: string;
13
+ line?: number;
14
+ column?: number;
15
+ }
16
+ export interface ValidationWarning {
17
+ code: string;
18
+ message: string;
19
+ line?: number;
20
+ column?: number;
21
+ }
22
+ export interface ValidationResult {
23
+ isValid: boolean;
24
+ errors: ValidationError[];
25
+ warnings: ValidationWarning[];
26
+ }
27
+ export interface IFormatHandler {
28
+ canHandle(filePath: string, content?: string): boolean;
29
+ parse(content: string): TranslationFile;
30
+ serialize(data: TranslationFile, options?: FormatOptions): string;
31
+ getFileExtension(): string;
32
+ validateStructure(data: TranslationFile): ValidationResult;
33
+ /**
34
+ * Enhanced validation using the centralized validation system
35
+ * This method should be preferred over validateStructure for comprehensive validation
36
+ */
37
+ validateWithRules?(data: TranslationFile, filePath?: string, originalContent?: string): ValidationResult;
38
+ }
39
+ export interface EnhancedTranslationFile extends TranslationFile {
40
+ _metadata?: {
41
+ format: string;
42
+ version?: string;
43
+ sourceLanguage?: string;
44
+ targetLanguage?: string;
45
+ encoding?: string;
46
+ originalStructure?: any;
47
+ preserveComments?: boolean;
48
+ preserveAttributes?: boolean;
49
+ arbMetadata?: Record<string, string | undefined>;
50
+ resourceMetadata?: Record<string, any>;
51
+ icuAnalysis?: Record<string, any>;
52
+ xliffVersion?: string;
53
+ xliffMetadata?: any;
54
+ [key: string]: any;
55
+ };
56
+ }
@@ -0,0 +1 @@
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 GoogleTranslate implements ITranslate {
3
3
  private googleTranslate;
4
4
  private supportedLanguages;