auto-translate-json-library 1.5.5 → 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 +96 -22
  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.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 +96 -22
@@ -0,0 +1,294 @@
1
+ import * as path from "node:path";
2
+ export class JsonHandler {
3
+ canHandle(filePath, content) {
4
+ const extension = path.extname(filePath).toLowerCase();
5
+ if (extension !== ".json") {
6
+ return false;
7
+ }
8
+ // If content is provided, check for valid JSON
9
+ if (content) {
10
+ try {
11
+ JSON.parse(content);
12
+ return true;
13
+ }
14
+ catch {
15
+ return false;
16
+ }
17
+ }
18
+ return true;
19
+ }
20
+ parse(content) {
21
+ try {
22
+ const parsed = JSON.parse(content);
23
+ // Flatten nested structures for translation while preserving metadata
24
+ const flattened = this.flattenObject(parsed);
25
+ // Add metadata
26
+ const result = {
27
+ ...flattened,
28
+ _metadata: {
29
+ format: "json",
30
+ originalStructure: parsed,
31
+ preserveComments: false, // JSON doesn't support comments natively
32
+ preserveAttributes: false,
33
+ },
34
+ };
35
+ return result;
36
+ }
37
+ catch (error) {
38
+ throw new Error(`Failed to parse JSON: ${error instanceof Error ? error.message : String(error)}`);
39
+ }
40
+ }
41
+ serialize(data, options) {
42
+ try {
43
+ // Remove metadata for serialization
44
+ const { _metadata, ...cleanData } = data;
45
+ let result;
46
+ if (_metadata?.originalStructure) {
47
+ // Reconstruct original nested structure with translated values
48
+ result = this.reconstructNestedStructure(_metadata.originalStructure, cleanData);
49
+ }
50
+ else {
51
+ // Use flat structure or attempt to reconstruct from dot notation
52
+ result = this.reconstructFromFlatStructure(cleanData);
53
+ }
54
+ // Apply formatting options
55
+ const indentation = this.getIndentation(options);
56
+ return JSON.stringify(result, null, indentation);
57
+ }
58
+ catch (error) {
59
+ throw new Error(`Failed to serialize JSON: ${error instanceof Error ? error.message : String(error)}`);
60
+ }
61
+ }
62
+ getFileExtension() {
63
+ return ".json";
64
+ }
65
+ validateStructure(data) {
66
+ const errors = [];
67
+ const warnings = [];
68
+ // Basic JSON structure validation
69
+ if (!data || typeof data !== "object") {
70
+ errors.push({
71
+ code: "INVALID_STRUCTURE",
72
+ message: "JSON data must be an object",
73
+ });
74
+ return { isValid: false, errors, warnings };
75
+ }
76
+ // Check for circular references
77
+ try {
78
+ JSON.stringify(data);
79
+ }
80
+ catch (error) {
81
+ if (error instanceof TypeError && error.message.includes("circular")) {
82
+ errors.push({
83
+ code: "CIRCULAR_REFERENCE",
84
+ message: "JSON contains circular references",
85
+ });
86
+ }
87
+ }
88
+ // Validate that all values are translatable (strings or nested objects with strings)
89
+ this.validateTranslatableContent(data, "", errors, warnings);
90
+ // Check for empty object
91
+ if (Object.keys(data).length === 0) {
92
+ warnings.push({
93
+ code: "EMPTY_JSON",
94
+ message: "JSON file appears to be empty",
95
+ });
96
+ }
97
+ return {
98
+ isValid: errors.length === 0,
99
+ errors,
100
+ warnings,
101
+ };
102
+ }
103
+ flattenObject(obj, prefix = "", result = {}) {
104
+ for (const [key, value] of Object.entries(obj)) {
105
+ const newKey = prefix ? `${prefix}.${key}` : key;
106
+ if (typeof value === "string") {
107
+ result[newKey] = value;
108
+ }
109
+ else if (typeof value === "object" &&
110
+ value !== null &&
111
+ !Array.isArray(value)) {
112
+ // Recursively flatten nested objects
113
+ this.flattenObject(value, newKey, result);
114
+ }
115
+ else if (Array.isArray(value)) {
116
+ // Handle arrays - flatten each element with index
117
+ value.forEach((item, index) => {
118
+ const arrayKey = `${newKey}[${index}]`;
119
+ if (typeof item === "string") {
120
+ result[arrayKey] = item;
121
+ }
122
+ else if (typeof item === "object" && item !== null) {
123
+ this.flattenObject(item, arrayKey, result);
124
+ }
125
+ else {
126
+ // Non-string, non-object values in arrays are preserved as-is
127
+ result[arrayKey] = item;
128
+ }
129
+ });
130
+ }
131
+ else {
132
+ // Non-string, non-object values (numbers, booleans, null) are preserved
133
+ result[newKey] = value;
134
+ }
135
+ }
136
+ return result;
137
+ }
138
+ reconstructNestedStructure(original, translations) {
139
+ // Deep clone the original structure
140
+ const result = JSON.parse(JSON.stringify(original));
141
+ // Update with translated values
142
+ this.updateNestedValues(result, translations);
143
+ return result;
144
+ }
145
+ updateNestedValues(obj, translations, path = "") {
146
+ for (const [key, value] of Object.entries(obj)) {
147
+ const currentPath = path ? `${path}.${key}` : key;
148
+ if (typeof value === "string") {
149
+ // Check if we have a translation for this path
150
+ if (translations[currentPath] !== undefined) {
151
+ obj[key] = translations[currentPath];
152
+ }
153
+ }
154
+ else if (typeof value === "object" &&
155
+ value !== null &&
156
+ !Array.isArray(value)) {
157
+ // Recursively update nested objects
158
+ this.updateNestedValues(value, translations, currentPath);
159
+ }
160
+ else if (Array.isArray(value)) {
161
+ // Handle arrays
162
+ value.forEach((item, index) => {
163
+ const arrayPath = `${currentPath}[${index}]`;
164
+ if (typeof item === "string" &&
165
+ translations[arrayPath] !== undefined) {
166
+ value[index] = translations[arrayPath];
167
+ }
168
+ else if (typeof item === "object" && item !== null) {
169
+ this.updateNestedValues(item, translations, arrayPath);
170
+ }
171
+ });
172
+ }
173
+ }
174
+ }
175
+ reconstructFromFlatStructure(flatData) {
176
+ const result = {};
177
+ for (const [key, value] of Object.entries(flatData)) {
178
+ this.setNestedValue(result, key, value);
179
+ }
180
+ return result;
181
+ }
182
+ setNestedValue(obj, path, value) {
183
+ const keys = this.parsePath(path);
184
+ let current = obj;
185
+ for (let i = 0; i < keys.length - 1; i++) {
186
+ const key = keys[i];
187
+ if (key.isArray) {
188
+ if (!Array.isArray(current[key.name])) {
189
+ current[key.name] = [];
190
+ }
191
+ // Ensure array has enough elements
192
+ while (current[key.name].length <= key.index) {
193
+ current[key.name].push({});
194
+ }
195
+ current = current[key.name][key.index];
196
+ }
197
+ else {
198
+ if (!(key.name in current)) {
199
+ current[key.name] = {};
200
+ }
201
+ current = current[key.name];
202
+ }
203
+ }
204
+ const lastKey = keys[keys.length - 1];
205
+ if (lastKey.isArray) {
206
+ if (!Array.isArray(current[lastKey.name])) {
207
+ current[lastKey.name] = [];
208
+ }
209
+ current[lastKey.name][lastKey.index] = value;
210
+ }
211
+ else {
212
+ current[lastKey.name] = value;
213
+ }
214
+ }
215
+ parsePath(path) {
216
+ const parts = path.split(".");
217
+ const result = [];
218
+ for (const part of parts) {
219
+ const arrayMatch = part.match(/^(.+)\[(\d+)\]$/);
220
+ if (arrayMatch) {
221
+ result.push({
222
+ name: arrayMatch[1],
223
+ isArray: true,
224
+ index: parseInt(arrayMatch[2], 10),
225
+ });
226
+ }
227
+ else {
228
+ result.push({
229
+ name: part,
230
+ isArray: false,
231
+ });
232
+ }
233
+ }
234
+ return result;
235
+ }
236
+ validateTranslatableContent(obj, path, errors, warnings, visited = new Set()) {
237
+ // Check for circular references
238
+ if (visited.has(obj)) {
239
+ return; // Already processed this object
240
+ }
241
+ if (typeof obj === "object" && obj !== null) {
242
+ visited.add(obj);
243
+ }
244
+ for (const [key, value] of Object.entries(obj)) {
245
+ const currentPath = path ? `${path}.${key}` : key;
246
+ if (typeof value === "string") {
247
+ // String values are translatable - this is good
248
+ continue;
249
+ }
250
+ else if (typeof value === "object" &&
251
+ value !== null &&
252
+ !Array.isArray(value)) {
253
+ // Nested objects - recursively validate
254
+ this.validateTranslatableContent(value, currentPath, errors, warnings, visited);
255
+ }
256
+ else if (Array.isArray(value)) {
257
+ // Arrays - check each element
258
+ value.forEach((item, index) => {
259
+ const arrayPath = `${currentPath}[${index}]`;
260
+ if (typeof item === "string") {
261
+ // String in array is translatable
262
+ return;
263
+ }
264
+ else if (typeof item === "object" && item !== null) {
265
+ this.validateTranslatableContent(item, arrayPath, errors, warnings, visited);
266
+ }
267
+ else {
268
+ // Non-string, non-object values in arrays
269
+ warnings.push({
270
+ code: "NON_TRANSLATABLE_ARRAY_ITEM",
271
+ message: `Array item at ${arrayPath} is not translatable (${typeof item})`,
272
+ });
273
+ }
274
+ });
275
+ }
276
+ else {
277
+ // Non-string, non-object values (numbers, booleans, null)
278
+ warnings.push({
279
+ code: "NON_TRANSLATABLE_VALUE",
280
+ message: `Value at ${currentPath} is not translatable (${typeof value})`,
281
+ });
282
+ }
283
+ }
284
+ if (typeof obj === "object" && obj !== null) {
285
+ visited.delete(obj);
286
+ }
287
+ }
288
+ getIndentation(options) {
289
+ if (options?.indentation !== undefined) {
290
+ return options.indentation;
291
+ }
292
+ return 2; // Default indentation
293
+ }
294
+ }
@@ -0,0 +1,17 @@
1
+ import type { EnhancedTranslationFile, FormatOptions, IFormatHandler, ValidationResult } from "../format.interface.js";
2
+ import type { TranslationFile } from "../translate.interface.js";
3
+ export declare class POHandler implements IFormatHandler {
4
+ canHandle(filePath: string, content?: string): boolean;
5
+ parse(content: string): EnhancedTranslationFile;
6
+ serialize(data: EnhancedTranslationFile, options?: FormatOptions): string;
7
+ getFileExtension(): string;
8
+ validateStructure(data: TranslationFile): ValidationResult;
9
+ private extractTranslatableStrings;
10
+ private updateTranslations;
11
+ private createPOStructure;
12
+ private parseTranslationKey;
13
+ private extractLanguageFromHeaders;
14
+ private getDefaultHeaders;
15
+ private formatHeaders;
16
+ private validatePluralForms;
17
+ }
@@ -0,0 +1,338 @@
1
+ import * as path from "node:path";
2
+ import * as gettextParser from "gettext-parser";
3
+ import { createContextKey, createPluralKey, formatPluralFormsHeader, parseContext, parsePluralIndex, validateContext, validatePluralExpression, validatePluralForms, } from "./po-utils.js";
4
+ export class POHandler {
5
+ canHandle(filePath, content) {
6
+ const extension = path.extname(filePath).toLowerCase();
7
+ if (extension !== ".po") {
8
+ return false;
9
+ }
10
+ // If content is provided, check for PO format signatures
11
+ if (content) {
12
+ return /^\s*msgid\s+"/m.test(content) || /^\s*#.*msgid/m.test(content);
13
+ }
14
+ return true;
15
+ }
16
+ parse(content) {
17
+ try {
18
+ const parsed = gettextParser.po.parse(content);
19
+ // Extract translatable strings from PO structure
20
+ const flattened = this.extractTranslatableStrings(parsed);
21
+ // Add metadata
22
+ const result = {
23
+ ...flattened,
24
+ _metadata: {
25
+ format: "po",
26
+ encoding: parsed.charset || "utf-8",
27
+ originalStructure: parsed,
28
+ preserveComments: true,
29
+ preserveAttributes: true,
30
+ poHeaders: parsed.headers,
31
+ sourceLanguage: this.extractLanguageFromHeaders(parsed.headers, "source"),
32
+ targetLanguage: this.extractLanguageFromHeaders(parsed.headers, "target"),
33
+ },
34
+ };
35
+ return result;
36
+ }
37
+ catch (error) {
38
+ throw new Error(`Failed to parse PO file: ${error instanceof Error ? error.message : String(error)}`);
39
+ }
40
+ }
41
+ serialize(data, options) {
42
+ try {
43
+ const { _metadata, ...translations } = data;
44
+ let poData;
45
+ if (_metadata?.originalStructure) {
46
+ // Use original structure and update with translations
47
+ poData = JSON.parse(JSON.stringify(_metadata.originalStructure));
48
+ this.updateTranslations(poData, translations);
49
+ }
50
+ else {
51
+ // Create new PO structure from translations
52
+ poData = this.createPOStructure(translations, _metadata);
53
+ }
54
+ // Apply encoding from options or metadata
55
+ const encoding = options?.encoding || _metadata?.encoding || "utf-8";
56
+ poData.charset = encoding;
57
+ // Update Content-Type header with the correct encoding
58
+ if (encoding !== "utf-8") {
59
+ poData.headers["Content-Type"] = `text/plain; charset=${encoding}`;
60
+ }
61
+ return gettextParser.po.compile(poData, { foldLength: 76 }).toString();
62
+ }
63
+ catch (error) {
64
+ throw new Error(`Failed to serialize PO file: ${error instanceof Error ? error.message : String(error)}`);
65
+ }
66
+ }
67
+ getFileExtension() {
68
+ return ".po";
69
+ }
70
+ validateStructure(data) {
71
+ const errors = [];
72
+ const warnings = [];
73
+ // Basic structure validation
74
+ if (!data || typeof data !== "object") {
75
+ errors.push({
76
+ code: "INVALID_STRUCTURE",
77
+ message: "PO data must be an object",
78
+ });
79
+ return { isValid: false, errors, warnings };
80
+ }
81
+ // Check for empty translations
82
+ const translationKeys = Object.keys(data).filter((key) => key !== "_metadata");
83
+ if (translationKeys.length === 0) {
84
+ warnings.push({
85
+ code: "EMPTY_PO",
86
+ message: "PO file appears to have no translatable strings",
87
+ });
88
+ }
89
+ // Validate translation values
90
+ for (const [key, value] of Object.entries(data)) {
91
+ if (key === "_metadata")
92
+ continue;
93
+ if (typeof value !== "string") {
94
+ errors.push({
95
+ code: "INVALID_TRANSLATION_VALUE",
96
+ message: `Translation value for "${key}" must be a string, got ${typeof value}`,
97
+ });
98
+ }
99
+ }
100
+ // Check for potential plural form issues
101
+ this.validatePluralForms(data, warnings);
102
+ return {
103
+ isValid: errors.length === 0,
104
+ errors,
105
+ warnings,
106
+ };
107
+ }
108
+ extractTranslatableStrings(poData) {
109
+ const result = {};
110
+ for (const [context, translations] of Object.entries(poData.translations)) {
111
+ for (const [msgid, entry] of Object.entries(translations)) {
112
+ // Skip empty msgid (header entry)
113
+ if (!msgid)
114
+ continue;
115
+ // Create unique key for context + msgid using utility function
116
+ const key = createContextKey(context, msgid);
117
+ // Handle plural forms
118
+ if (entry.msgid_plural) {
119
+ // For plural forms, use the first msgstr as the translation (singular)
120
+ result[key] = entry.msgstr[0] || "";
121
+ // Add plural form entries
122
+ for (let i = 1; i < entry.msgstr.length; i++) {
123
+ const pluralKey = createPluralKey(key, i);
124
+ result[pluralKey] = entry.msgstr[i] || "";
125
+ }
126
+ }
127
+ else {
128
+ // Regular singular form
129
+ result[key] = entry.msgstr[0] || "";
130
+ }
131
+ }
132
+ }
133
+ return result;
134
+ }
135
+ updateTranslations(poData, translations) {
136
+ for (const [context, contextTranslations] of Object.entries(poData.translations)) {
137
+ for (const [msgid, entry] of Object.entries(contextTranslations)) {
138
+ // Skip empty msgid (header entry)
139
+ if (!msgid)
140
+ continue;
141
+ const key = createContextKey(context, msgid);
142
+ // Update regular translation
143
+ if (translations[key] !== undefined) {
144
+ entry.msgstr[0] = translations[key];
145
+ }
146
+ // Update plural forms if they exist
147
+ if (entry.msgid_plural) {
148
+ for (let i = 1; i < entry.msgstr.length; i++) {
149
+ const pluralKey = createPluralKey(key, i);
150
+ if (translations[pluralKey] !== undefined) {
151
+ entry.msgstr[i] = translations[pluralKey];
152
+ }
153
+ }
154
+ }
155
+ }
156
+ }
157
+ }
158
+ createPOStructure(translations, metadata) {
159
+ const targetLanguage = metadata?.targetLanguage;
160
+ const encoding = metadata?.encoding || "utf-8";
161
+ const headers = metadata?.poHeaders || this.getDefaultHeaders(targetLanguage);
162
+ // Update Content-Type header with the correct encoding
163
+ if (encoding !== "utf-8") {
164
+ headers["Content-Type"] = `text/plain; charset=${encoding}`;
165
+ }
166
+ const poData = {
167
+ charset: encoding,
168
+ headers,
169
+ translations: {
170
+ "": {}, // Default context
171
+ },
172
+ };
173
+ // Add header entry
174
+ poData.translations[""][""] = {
175
+ msgid: "",
176
+ msgstr: [this.formatHeaders(poData.headers)],
177
+ };
178
+ // Process translations
179
+ for (const [key, value] of Object.entries(translations)) {
180
+ const { context, msgid, pluralIndex } = this.parseTranslationKey(key);
181
+ // Validate context
182
+ if (context && !validateContext(context)) {
183
+ throw new Error(`Invalid context in key "${key}": context cannot contain separator character`);
184
+ }
185
+ // Ensure context exists
186
+ if (!poData.translations[context]) {
187
+ poData.translations[context] = {};
188
+ }
189
+ // Ensure entry exists
190
+ if (!poData.translations[context][msgid]) {
191
+ poData.translations[context][msgid] = {
192
+ msgid,
193
+ msgstr: [""],
194
+ };
195
+ }
196
+ const entry = poData.translations[context][msgid];
197
+ // Handle plural forms
198
+ if (pluralIndex !== undefined) {
199
+ // Ensure msgstr array is large enough
200
+ while (entry.msgstr.length <= pluralIndex) {
201
+ entry.msgstr.push("");
202
+ }
203
+ entry.msgstr[pluralIndex] = value;
204
+ // Set msgid_plural if this is a plural form
205
+ if (pluralIndex > 0 && !entry.msgid_plural) {
206
+ entry.msgid_plural = msgid; // This should be set properly based on the original
207
+ }
208
+ }
209
+ else {
210
+ entry.msgstr[0] = value;
211
+ }
212
+ // Set context if it exists
213
+ if (context) {
214
+ entry.msgctxt = context;
215
+ }
216
+ }
217
+ return poData;
218
+ }
219
+ parseTranslationKey(key) {
220
+ // Parse plural form index first
221
+ const { baseKey, pluralIndex } = parsePluralIndex(key);
222
+ // Parse context from base key
223
+ const { context, msgid } = parseContext(baseKey);
224
+ return {
225
+ context,
226
+ msgid,
227
+ pluralIndex,
228
+ };
229
+ }
230
+ extractLanguageFromHeaders(headers, type) {
231
+ const languageHeader = headers["Language"];
232
+ const localeHeader = headers["Language-Team"];
233
+ if (languageHeader) {
234
+ return languageHeader;
235
+ }
236
+ if (localeHeader) {
237
+ // Extract language code from Language-Team header
238
+ const match = localeHeader.match(/\(([^)]+)\)/);
239
+ return match ? match[1] : undefined;
240
+ }
241
+ return undefined;
242
+ }
243
+ getDefaultHeaders(language) {
244
+ const now = new Date();
245
+ const pluralForms = language
246
+ ? formatPluralFormsHeader(language)
247
+ : "nplurals=2; plural=(n != 1);";
248
+ return {
249
+ "Project-Id-Version": "PACKAGE VERSION",
250
+ "Report-Msgid-Bugs-To": "",
251
+ "POT-Creation-Date": now
252
+ .toISOString()
253
+ .replace(/T/, " ")
254
+ .replace(/\..+/, " +0000"),
255
+ "PO-Revision-Date": now
256
+ .toISOString()
257
+ .replace(/T/, " ")
258
+ .replace(/\..+/, " +0000"),
259
+ "Last-Translator": "auto-translate-json-library",
260
+ "Language-Team": language
261
+ ? `${language.toUpperCase()} <${language}@li.org>`
262
+ : "LANGUAGE <LL@li.org>",
263
+ Language: language || "",
264
+ "MIME-Version": "1.0",
265
+ "Content-Type": "text/plain; charset=UTF-8",
266
+ "Content-Transfer-Encoding": "8bit",
267
+ "Plural-Forms": pluralForms,
268
+ };
269
+ }
270
+ formatHeaders(headers) {
271
+ return Object.entries(headers)
272
+ .map(([key, value]) => `${key}: ${value}\\n`)
273
+ .join("");
274
+ }
275
+ validatePluralForms(data, warnings) {
276
+ const metadata = data._metadata;
277
+ const targetLanguage = metadata?.targetLanguage;
278
+ if (targetLanguage) {
279
+ // Use comprehensive plural form validation
280
+ const validationResult = validatePluralForms(data, targetLanguage);
281
+ if (!validationResult.isValid) {
282
+ for (const missing of validationResult.missing) {
283
+ warnings.push({
284
+ code: "MISSING_PLURAL_FORM",
285
+ message: `Missing plural form: ${missing}`,
286
+ });
287
+ }
288
+ for (const extra of validationResult.extra) {
289
+ warnings.push({
290
+ code: "EXTRA_PLURAL_FORM",
291
+ message: `Extra plural form for language ${targetLanguage}: ${extra}`,
292
+ });
293
+ }
294
+ }
295
+ }
296
+ else {
297
+ // Fallback to basic validation
298
+ const pluralKeys = new Set();
299
+ const singularKeys = new Set();
300
+ for (const key of Object.keys(data)) {
301
+ if (key === "_metadata")
302
+ continue;
303
+ const { baseKey, pluralIndex } = parsePluralIndex(key);
304
+ if (pluralIndex !== undefined) {
305
+ pluralKeys.add(baseKey);
306
+ }
307
+ else {
308
+ singularKeys.add(key);
309
+ }
310
+ }
311
+ // Check for incomplete plural forms
312
+ for (const pluralBase of pluralKeys) {
313
+ if (!singularKeys.has(pluralBase)) {
314
+ warnings.push({
315
+ code: "INCOMPLETE_PLURAL_FORM",
316
+ message: `Plural form found for "${pluralBase}" but no singular form exists`,
317
+ });
318
+ }
319
+ }
320
+ }
321
+ // Validate plural forms header if present
322
+ if (metadata?.poHeaders?.["Plural-Forms"]) {
323
+ const pluralFormsHeader = metadata.poHeaders["Plural-Forms"];
324
+ const npluralsMatch = pluralFormsHeader.match(/nplurals=(\d+)/);
325
+ const pluralMatch = pluralFormsHeader.match(/plural=([^;]+)/);
326
+ if (npluralsMatch && pluralMatch) {
327
+ const nplurals = parseInt(npluralsMatch[1], 10);
328
+ const pluralExpr = pluralMatch[1];
329
+ if (!validatePluralExpression(pluralExpr, nplurals)) {
330
+ warnings.push({
331
+ code: "INVALID_PLURAL_EXPRESSION",
332
+ message: `Invalid plural expression: ${pluralExpr}`,
333
+ });
334
+ }
335
+ }
336
+ }
337
+ }
338
+ }