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,768 @@
1
+ import * as fs from "node:fs";
2
+ import { fileURLToPath } from 'url';
3
+ import { dirname } from 'path';
4
+ const __filename = fileURLToPath(import.meta.url);
5
+ const __dirname = dirname(__filename);
6
+ import * as path from "node:path";
7
+ import { POHandler } from "../src/format/po-handler.js";
8
+ import { POTHandler } from "../src/format/pot-handler.js";
9
+ import { getPluralRule, formatPluralFormsHeader, validatePluralForms, parseContext, createContextKey, parsePluralIndex, createPluralKey, validatePluralExpression, evaluatePluralExpression, normalizeLanguageCode, getSupportedLanguages, hasComplexPlurals, generateSamplePlurals } from "../src/format/po-utils.js";
10
+ describe("PO Handler", () => {
11
+ let handler;
12
+ beforeEach(() => {
13
+ handler = new POHandler();
14
+ });
15
+ describe("canHandle", () => {
16
+ it("should handle .po files", () => {
17
+ expect(handler.canHandle("test.po")).toBe(true);
18
+ expect(handler.canHandle("test.pot")).toBe(false);
19
+ expect(handler.canHandle("test.json")).toBe(false);
20
+ });
21
+ it("should handle PO content", () => {
22
+ const poContent = `
23
+ msgid ""
24
+ msgstr ""
25
+ "Content-Type: text/plain; charset=UTF-8\\n"
26
+
27
+ msgid "Hello"
28
+ msgstr "Hola"
29
+ `;
30
+ expect(handler.canHandle("test.po", poContent)).toBe(true);
31
+ });
32
+ });
33
+ describe("parse", () => {
34
+ it("should parse simple PO file", () => {
35
+ const poContent = `
36
+ msgid ""
37
+ msgstr ""
38
+ "Content-Type: text/plain; charset=UTF-8\\n"
39
+ "Language: es\\n"
40
+
41
+ msgid "Hello"
42
+ msgstr "Hola"
43
+
44
+ msgid "World"
45
+ msgstr "Mundo"
46
+ `;
47
+ const result = handler.parse(poContent);
48
+ expect(result.Hello).toBe("Hola");
49
+ expect(result.World).toBe("Mundo");
50
+ expect(result._metadata?.format).toBe("po");
51
+ expect(result._metadata?.targetLanguage).toBe("es");
52
+ });
53
+ it("should parse PO file with context", () => {
54
+ const poContent = `
55
+ msgid ""
56
+ msgstr ""
57
+ "Content-Type: text/plain; charset=UTF-8\\n"
58
+
59
+ msgctxt "greeting"
60
+ msgid "Hello"
61
+ msgstr "Hola"
62
+
63
+ msgctxt "farewell"
64
+ msgid "Hello"
65
+ msgstr "Adiós"
66
+ `;
67
+ const result = handler.parse(poContent);
68
+ expect(result["greeting|Hello"]).toBe("Hola");
69
+ expect(result["farewell|Hello"]).toBe("Adiós");
70
+ });
71
+ it("should parse PO file with plural forms", () => {
72
+ const poContent = `
73
+ msgid ""
74
+ msgstr ""
75
+ "Content-Type: text/plain; charset=UTF-8\\n"
76
+ "Plural-Forms: nplurals=2; plural=(n != 1);\\n"
77
+
78
+ msgid "One item"
79
+ msgid_plural "%d items"
80
+ msgstr[0] "Un elemento"
81
+ msgstr[1] "%d elementos"
82
+ `;
83
+ const result = handler.parse(poContent);
84
+ expect(result["One item"]).toBe("Un elemento");
85
+ expect(result["One item[1]"]).toBe("%d elementos");
86
+ });
87
+ });
88
+ describe("serialize", () => {
89
+ it("should serialize simple translations", () => {
90
+ const data = {
91
+ Hello: "Hola",
92
+ World: "Mundo",
93
+ _metadata: {
94
+ format: "po",
95
+ targetLanguage: "es",
96
+ encoding: "utf-8"
97
+ }
98
+ };
99
+ const result = handler.serialize(data);
100
+ expect(result).toContain('msgid "Hello"');
101
+ expect(result).toContain('msgstr "Hola"');
102
+ expect(result).toContain('msgid "World"');
103
+ expect(result).toContain('msgstr "Mundo"');
104
+ expect(result).toContain("Language: es");
105
+ });
106
+ it("should serialize translations with context", () => {
107
+ const data = {
108
+ "greeting|Hello": "Hola",
109
+ "farewell|Hello": "Adiós",
110
+ _metadata: {
111
+ format: "po",
112
+ targetLanguage: "es"
113
+ }
114
+ };
115
+ const result = handler.serialize(data);
116
+ expect(result).toContain('msgctxt "greeting"');
117
+ expect(result).toContain('msgctxt "farewell"');
118
+ });
119
+ it("should serialize plural forms", () => {
120
+ const data = {
121
+ "One item": "Un elemento",
122
+ "One item[1]": "%d elementos",
123
+ _metadata: {
124
+ format: "po",
125
+ targetLanguage: "es"
126
+ }
127
+ };
128
+ const result = handler.serialize(data);
129
+ expect(result).toContain('msgid_plural');
130
+ expect(result).toContain('msgstr[0] "Un elemento"');
131
+ expect(result).toContain('msgstr[1] "%d elementos"');
132
+ });
133
+ });
134
+ describe("validateStructure", () => {
135
+ it("should validate correct PO structure", () => {
136
+ const data = {
137
+ Hello: "Hola",
138
+ World: "Mundo",
139
+ _metadata: { format: "po" }
140
+ };
141
+ const result = handler.validateStructure(data);
142
+ expect(result.isValid).toBe(true);
143
+ expect(result.errors).toHaveLength(0);
144
+ });
145
+ it("should detect invalid translation values", () => {
146
+ const data = {
147
+ Hello: 123, // Invalid: should be string
148
+ World: "Mundo",
149
+ _metadata: { format: "po" }
150
+ };
151
+ const result = handler.validateStructure(data);
152
+ expect(result.isValid).toBe(false);
153
+ expect(result.errors).toHaveLength(1);
154
+ expect(result.errors[0].code).toBe("INVALID_TRANSLATION_VALUE");
155
+ });
156
+ it("should warn about empty PO files", () => {
157
+ const data = {
158
+ _metadata: { format: "po" }
159
+ };
160
+ const result = handler.validateStructure(data);
161
+ expect(result.isValid).toBe(true);
162
+ expect(result.warnings).toHaveLength(1);
163
+ expect(result.warnings[0].code).toBe("EMPTY_PO");
164
+ });
165
+ it("should validate plural forms for specific languages", () => {
166
+ const data = {
167
+ "One item": "Un elemento",
168
+ "One item[1]": "%d elementos",
169
+ "One item[2]": "Extra form", // Extra for Spanish
170
+ _metadata: {
171
+ format: "po",
172
+ targetLanguage: "es"
173
+ }
174
+ };
175
+ const result = handler.validateStructure(data);
176
+ expect(result.isValid).toBe(true);
177
+ expect(result.warnings.some(w => w.code === "EXTRA_PLURAL_FORM")).toBe(true);
178
+ });
179
+ });
180
+ describe("real file parsing", () => {
181
+ it("should parse real PO file with all features", () => {
182
+ const poPath = path.join(__dirname, "test-data", "sample.po");
183
+ const poContent = fs.readFileSync(poPath, "utf-8");
184
+ const result = handler.parse(poContent);
185
+ // Check basic translations
186
+ expect(result["Hello, World!"]).toBe("¡Hola, Mundo!");
187
+ expect(result["Welcome to our application"]).toBe("Bienvenido a nuestra aplicación");
188
+ // Check context translations
189
+ expect(result["greeting|Hello"]).toBe("Hola");
190
+ expect(result["farewell|Hello"]).toBe("Adiós");
191
+ // Check plural forms
192
+ expect(result["You have %d item"]).toBe("Tienes %d elemento");
193
+ expect(result["You have %d item[1]"]).toBe("Tienes %d elementos");
194
+ // Check metadata
195
+ expect(result._metadata?.format).toBe("po");
196
+ expect(result._metadata?.targetLanguage).toBe("es");
197
+ expect(result._metadata?.encoding).toBe("utf-8");
198
+ });
199
+ it("should serialize and parse round-trip correctly", () => {
200
+ const originalData = {
201
+ "Hello, World!": "¡Hola, Mundo!",
202
+ "greeting|Hello": "Hola",
203
+ "farewell|Hello": "Adiós",
204
+ "You have %d item": "Tienes %d elemento",
205
+ "You have %d item[1]": "Tienes %d elementos",
206
+ _metadata: {
207
+ format: "po",
208
+ targetLanguage: "es",
209
+ encoding: "utf-8"
210
+ }
211
+ };
212
+ const serialized = handler.serialize(originalData);
213
+ const parsed = handler.parse(serialized);
214
+ // Check that all translations are preserved
215
+ expect(parsed["Hello, World!"]).toBe("¡Hola, Mundo!");
216
+ expect(parsed["greeting|Hello"]).toBe("Hola");
217
+ expect(parsed["farewell|Hello"]).toBe("Adiós");
218
+ expect(parsed["You have %d item"]).toBe("Tienes %d elemento");
219
+ expect(parsed["You have %d item[1]"]).toBe("Tienes %d elementos");
220
+ });
221
+ it("should handle malformed PO files gracefully", () => {
222
+ const malformedPO = `
223
+ msgid "Hello"
224
+ msgstr "Hola"
225
+ # Missing closing quote
226
+ msgid "Broken
227
+ msgstr "Roto"
228
+ `;
229
+ expect(() => handler.parse(malformedPO)).toThrow("Failed to parse PO file");
230
+ });
231
+ it("should handle empty PO files", () => {
232
+ const emptyPO = `
233
+ msgid ""
234
+ msgstr ""
235
+ "Content-Type: text/plain; charset=UTF-8\\n"
236
+ `;
237
+ const result = handler.parse(emptyPO);
238
+ expect(Object.keys(result).filter(k => k !== "_metadata")).toHaveLength(0);
239
+ expect(result._metadata?.format).toBe("po");
240
+ });
241
+ it("should preserve comments and metadata in serialization", () => {
242
+ const poWithComments = `
243
+ msgid ""
244
+ msgstr ""
245
+ "Content-Type: text/plain; charset=UTF-8\\n"
246
+ "Language: es\\n"
247
+
248
+ # Translator comment
249
+ #. Extracted comment
250
+ #: reference.c:123
251
+ #, fuzzy
252
+ msgid "Hello"
253
+ msgstr "Hola"
254
+ `;
255
+ const parsed = handler.parse(poWithComments);
256
+ const serialized = handler.serialize(parsed);
257
+ // The serialized version should maintain the translation
258
+ expect(serialized).toContain('msgid "Hello"');
259
+ expect(serialized).toContain('msgstr "Hola"');
260
+ });
261
+ });
262
+ });
263
+ describe("POT Handler", () => {
264
+ let handler;
265
+ beforeEach(() => {
266
+ handler = new POTHandler();
267
+ });
268
+ describe("canHandle", () => {
269
+ it("should handle .pot files", () => {
270
+ expect(handler.canHandle("test.pot")).toBe(true);
271
+ expect(handler.canHandle("test.po")).toBe(false);
272
+ expect(handler.canHandle("test.json")).toBe(false);
273
+ });
274
+ it("should handle POT content", () => {
275
+ const potContent = `
276
+ # POT-Creation-Date: 2024-01-01 12:00+0000
277
+ msgid ""
278
+ msgstr ""
279
+
280
+ msgid "Hello"
281
+ msgstr ""
282
+ `;
283
+ expect(handler.canHandle("test.pot", potContent)).toBe(true);
284
+ });
285
+ });
286
+ describe("generatePOFromTemplate", () => {
287
+ it("should generate PO file from POT template", () => {
288
+ const potContent = `
289
+ msgid ""
290
+ msgstr ""
291
+ "Content-Type: text/plain; charset=UTF-8\\n"
292
+
293
+ msgid "Hello"
294
+ msgstr ""
295
+
296
+ msgid "World"
297
+ msgstr ""
298
+ `;
299
+ const translations = {
300
+ Hello: "Hola",
301
+ World: "Mundo"
302
+ };
303
+ const result = handler.generatePOFromTemplate(potContent, "es", translations);
304
+ expect(result).toContain('msgid "Hello"');
305
+ expect(result).toContain('msgstr "Hola"');
306
+ expect(result).toContain('msgid "World"');
307
+ expect(result).toContain('msgstr "Mundo"');
308
+ expect(result).toContain("Language: es");
309
+ });
310
+ it("should generate PO from real POT template file", () => {
311
+ const potPath = path.join(__dirname, "test-data", "sample.pot");
312
+ const potContent = fs.readFileSync(potPath, "utf-8");
313
+ const translations = {
314
+ "Hello, World!": "¡Hola, Mundo!",
315
+ "Welcome to our application": "Bienvenido a nuestra aplicación",
316
+ "greeting|Hello": "Hola",
317
+ "farewell|Hello": "Adiós",
318
+ "You have %d item": "Tienes %d elemento",
319
+ "You have %d item[1]": "Tienes %d elementos",
320
+ "File saved successfully": "Archivo guardado exitosamente",
321
+ "An error occurred": "Ocurrió un error"
322
+ };
323
+ const result = handler.generatePOFromTemplate(potContent, "es", translations);
324
+ // Check that translations are applied
325
+ expect(result).toContain('msgstr "¡Hola, Mundo!"');
326
+ expect(result).toContain('msgstr "Bienvenido a nuestra aplicación"');
327
+ expect(result).toContain('msgstr "Hola"');
328
+ expect(result).toContain('msgstr "Adiós"');
329
+ expect(result).toContain('msgstr[0] "Tienes %d elemento"');
330
+ expect(result).toContain('msgstr[1] "Tienes %d elementos"');
331
+ // Check that headers are updated for Spanish
332
+ expect(result).toContain("Language: es");
333
+ expect(result).toContain("nplurals=2; plural=(n != 1);");
334
+ });
335
+ it("should handle POT template without translations", () => {
336
+ const potPath = path.join(__dirname, "test-data", "sample.pot");
337
+ const potContent = fs.readFileSync(potPath, "utf-8");
338
+ const result = handler.generatePOFromTemplate(potContent, "fr");
339
+ // Check that headers are updated for French
340
+ expect(result).toContain("Language: fr");
341
+ expect(result).toContain("nplurals=2; plural=(n > 1);");
342
+ // Check that msgstr entries are empty
343
+ expect(result).toContain('msgstr ""');
344
+ });
345
+ });
346
+ describe("validateStructure", () => {
347
+ it("should validate POT template structure", () => {
348
+ const data = {
349
+ Hello: "",
350
+ World: "",
351
+ _metadata: { format: "pot", isTemplate: true }
352
+ };
353
+ const result = handler.validateStructure(data);
354
+ expect(result.isValid).toBe(true);
355
+ expect(result.errors).toHaveLength(0);
356
+ });
357
+ it("should warn about non-empty template values", () => {
358
+ const data = {
359
+ Hello: "Translated", // Should be empty in template
360
+ World: "",
361
+ _metadata: { format: "pot", isTemplate: true }
362
+ };
363
+ const result = handler.validateStructure(data);
364
+ expect(result.isValid).toBe(true);
365
+ expect(result.warnings.some(w => w.code === "NON_EMPTY_TEMPLATE_VALUE")).toBe(true);
366
+ });
367
+ it("should validate POT headers", () => {
368
+ const data = {
369
+ Hello: "",
370
+ _metadata: {
371
+ format: "pot",
372
+ potHeaders: {
373
+ "Project-Id-Version": "PACKAGE VERSION", // Template placeholder
374
+ "Content-Type": "text/plain; charset=UTF-8"
375
+ }
376
+ }
377
+ };
378
+ const result = handler.validateStructure(data);
379
+ expect(result.isValid).toBe(true);
380
+ expect(result.warnings.some(w => w.code === "TEMPLATE_PLACEHOLDER")).toBe(true);
381
+ });
382
+ });
383
+ describe("real file parsing", () => {
384
+ it("should parse real POT template file", () => {
385
+ const potPath = path.join(__dirname, "test-data", "sample.pot");
386
+ const potContent = fs.readFileSync(potPath, "utf-8");
387
+ const result = handler.parse(potContent);
388
+ // Check that all template strings are empty
389
+ expect(result["Hello, World!"]).toBe("");
390
+ expect(result["Welcome to our application"]).toBe("");
391
+ expect(result["greeting|Hello"]).toBe("");
392
+ expect(result["farewell|Hello"]).toBe("");
393
+ expect(result["You have %d item"]).toBe("");
394
+ expect(result["You have %d item[1]"]).toBe("");
395
+ // Check metadata
396
+ expect(result._metadata?.format).toBe("pot");
397
+ expect(result._metadata?.isTemplate).toBe(true);
398
+ expect(result._metadata?.encoding).toBe("utf-8");
399
+ });
400
+ });
401
+ });
402
+ describe("PO Utils", () => {
403
+ describe("getPluralRule", () => {
404
+ it("should return correct plural rules for different languages", () => {
405
+ const enRule = getPluralRule("en");
406
+ expect(enRule.nplurals).toBe(2);
407
+ expect(enRule.plural).toBe("(n != 1)");
408
+ const ruRule = getPluralRule("ru");
409
+ expect(ruRule.nplurals).toBe(3);
410
+ const zhRule = getPluralRule("zh");
411
+ expect(zhRule.nplurals).toBe(1);
412
+ });
413
+ it("should handle language codes with regions", () => {
414
+ const rule = getPluralRule("en-US");
415
+ expect(rule.nplurals).toBe(2);
416
+ expect(rule.plural).toBe("(n != 1)");
417
+ });
418
+ it("should default to English for unknown languages", () => {
419
+ const rule = getPluralRule("unknown");
420
+ expect(rule.nplurals).toBe(2);
421
+ expect(rule.plural).toBe("(n != 1)");
422
+ });
423
+ });
424
+ describe("formatPluralFormsHeader", () => {
425
+ it("should format plural forms header correctly", () => {
426
+ const header = formatPluralFormsHeader("en");
427
+ expect(header).toBe("nplurals=2; plural=(n != 1);");
428
+ const ruHeader = formatPluralFormsHeader("ru");
429
+ expect(ruHeader).toContain("nplurals=3");
430
+ });
431
+ });
432
+ describe("parseContext", () => {
433
+ it("should parse context from keys", () => {
434
+ const result1 = parseContext("greeting|Hello");
435
+ expect(result1.context).toBe("greeting");
436
+ expect(result1.msgid).toBe("Hello");
437
+ const result2 = parseContext("Hello");
438
+ expect(result2.context).toBe("");
439
+ expect(result2.msgid).toBe("Hello");
440
+ });
441
+ });
442
+ describe("createContextKey", () => {
443
+ it("should create context keys correctly", () => {
444
+ expect(createContextKey("greeting", "Hello")).toBe("greeting|Hello");
445
+ expect(createContextKey("", "Hello")).toBe("Hello");
446
+ });
447
+ });
448
+ describe("parsePluralIndex", () => {
449
+ it("should parse plural indices from keys", () => {
450
+ const result1 = parsePluralIndex("Hello[1]");
451
+ expect(result1.baseKey).toBe("Hello");
452
+ expect(result1.pluralIndex).toBe(1);
453
+ const result2 = parsePluralIndex("Hello");
454
+ expect(result2.baseKey).toBe("Hello");
455
+ expect(result2.pluralIndex).toBeUndefined();
456
+ });
457
+ });
458
+ describe("createPluralKey", () => {
459
+ it("should create plural keys correctly", () => {
460
+ expect(createPluralKey("Hello", 1)).toBe("Hello[1]");
461
+ expect(createPluralKey("greeting|Hello", 2)).toBe("greeting|Hello[2]");
462
+ });
463
+ });
464
+ describe("validatePluralForms", () => {
465
+ it("should validate plural forms for different languages", () => {
466
+ const translations = {
467
+ "One item": "Un elemento",
468
+ "One item[1]": "%d elementos"
469
+ };
470
+ const result = validatePluralForms(translations, "es");
471
+ expect(result.isValid).toBe(true);
472
+ expect(result.missing).toHaveLength(0);
473
+ expect(result.extra).toHaveLength(0);
474
+ });
475
+ it("should detect missing plural forms", () => {
476
+ const translations = {
477
+ "One item": "Un elemento",
478
+ "One item[1]": "" // This indicates a plural form exists but is empty
479
+ // Missing would be if we had no [1] at all
480
+ };
481
+ // For this test, let's create a scenario where we have a plural form but missing others
482
+ const translationsWithMissing = {
483
+ "One item": "Un elemento"
484
+ // Missing plural form [1] entirely
485
+ };
486
+ const result = validatePluralForms(translationsWithMissing, "es");
487
+ expect(result.isValid).toBe(true); // Spanish only needs singular, no plural forms required unless explicitly defined
488
+ // Test with actual missing plural forms
489
+ const translationsWithPlural = {
490
+ "One item": "Un elemento",
491
+ "One item[2]": "Extra form" // Has [2] but missing [1] - this should be invalid
492
+ };
493
+ const result2 = validatePluralForms(translationsWithPlural, "es");
494
+ expect(result2.isValid).toBe(false);
495
+ expect(result2.missing).toContain("One item[1]");
496
+ });
497
+ it("should detect extra plural forms", () => {
498
+ const translations = {
499
+ "One item": "Un elemento",
500
+ "One item[1]": "%d elementos",
501
+ "One item[2]": "Extra form" // Extra for Spanish
502
+ };
503
+ const result = validatePluralForms(translations, "es");
504
+ expect(result.isValid).toBe(false);
505
+ expect(result.extra).toContain("One item[2]");
506
+ });
507
+ });
508
+ describe("validatePluralExpression", () => {
509
+ it("should validate correct plural expressions", () => {
510
+ expect(validatePluralExpression("(n != 1)", 2)).toBe(true);
511
+ expect(validatePluralExpression("(n > 1)", 2)).toBe(true);
512
+ expect(validatePluralExpression("(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)", 3)).toBe(true);
513
+ });
514
+ it("should reject invalid plural expressions", () => {
515
+ expect(validatePluralExpression("invalid_expression", 2)).toBe(false);
516
+ expect(validatePluralExpression("(x != 1)", 2)).toBe(false); // Invalid variable
517
+ expect(validatePluralExpression("alert('hack')", 2)).toBe(false); // Security risk
518
+ });
519
+ });
520
+ describe("evaluatePluralExpression", () => {
521
+ it("should evaluate plural expressions correctly", () => {
522
+ // (n != 1) returns 1 when n is not 1, 0 when n is 1
523
+ expect(evaluatePluralExpression("(n != 1)", 0)).toBe(1); // 0 != 1 is true -> 1
524
+ expect(evaluatePluralExpression("(n != 1)", 1)).toBe(0); // 1 != 1 is false -> 0
525
+ expect(evaluatePluralExpression("(n != 1)", 2)).toBe(1); // 2 != 1 is true -> 1
526
+ // (n > 1) returns 1 when n > 1, 0 otherwise
527
+ expect(evaluatePluralExpression("(n > 1)", 0)).toBe(0); // 0 > 1 is false -> 0
528
+ expect(evaluatePluralExpression("(n > 1)", 1)).toBe(0); // 1 > 1 is false -> 0
529
+ expect(evaluatePluralExpression("(n > 1)", 2)).toBe(1); // 2 > 1 is true -> 1
530
+ });
531
+ it("should handle invalid expressions gracefully", () => {
532
+ expect(evaluatePluralExpression("invalid", 5)).toBe(0);
533
+ expect(evaluatePluralExpression("", 5)).toBe(0);
534
+ });
535
+ });
536
+ describe("normalizeLanguageCode", () => {
537
+ it("should normalize language codes", () => {
538
+ expect(normalizeLanguageCode("en-US")).toBe("en");
539
+ expect(normalizeLanguageCode("es-ES")).toBe("es");
540
+ expect(normalizeLanguageCode("zh-CN")).toBe("zh");
541
+ expect(normalizeLanguageCode("fr")).toBe("fr");
542
+ });
543
+ });
544
+ describe("getSupportedLanguages", () => {
545
+ it("should return list of supported languages", () => {
546
+ const languages = getSupportedLanguages();
547
+ expect(languages).toContain("en");
548
+ expect(languages).toContain("es");
549
+ expect(languages).toContain("fr");
550
+ expect(languages).toContain("ru");
551
+ expect(languages).toContain("zh");
552
+ expect(languages.length).toBeGreaterThan(20);
553
+ });
554
+ });
555
+ describe("hasComplexPlurals", () => {
556
+ it("should identify languages with complex plurals", () => {
557
+ expect(hasComplexPlurals("en")).toBe(false); // 2 forms
558
+ expect(hasComplexPlurals("es")).toBe(false); // 2 forms
559
+ expect(hasComplexPlurals("ru")).toBe(true); // 3 forms
560
+ expect(hasComplexPlurals("ar")).toBe(true); // 6 forms
561
+ expect(hasComplexPlurals("zh")).toBe(false); // 1 form
562
+ });
563
+ });
564
+ describe("generateSamplePlurals", () => {
565
+ it("should generate sample plural forms", () => {
566
+ const samples = generateSamplePlurals("en", "item", "items");
567
+ expect(samples).toHaveLength(2);
568
+ expect(samples[0]).toBe("item");
569
+ expect(samples[1]).toBe("items");
570
+ const ruSamples = generateSamplePlurals("ru", "элемент", "элементы");
571
+ expect(ruSamples).toHaveLength(3);
572
+ expect(ruSamples[0]).toBe("элемент");
573
+ expect(ruSamples[1]).toBe("элементы");
574
+ });
575
+ it("should handle languages without plural forms", () => {
576
+ const samples = generateSamplePlurals("zh", "项目");
577
+ expect(samples).toHaveLength(1);
578
+ expect(samples[0]).toBe("项目");
579
+ });
580
+ });
581
+ describe("comprehensive plural form validation", () => {
582
+ it("should validate complex Russian plural forms", () => {
583
+ const translations = {
584
+ "файл": "файл",
585
+ "файл[1]": "файла",
586
+ "файл[2]": "файлов"
587
+ };
588
+ const result = validatePluralForms(translations, "ru");
589
+ expect(result.isValid).toBe(true);
590
+ expect(result.missing).toHaveLength(0);
591
+ expect(result.extra).toHaveLength(0);
592
+ });
593
+ it("should validate Arabic plural forms", () => {
594
+ const translations = {
595
+ "كتاب": "كتاب",
596
+ "كتاب[1]": "كتاب",
597
+ "كتاب[2]": "كتابان",
598
+ "كتاب[3]": "كتب",
599
+ "كتاب[4]": "كتاب",
600
+ "كتاب[5]": "كتاب"
601
+ };
602
+ const result = validatePluralForms(translations, "ar");
603
+ expect(result.isValid).toBe(true);
604
+ expect(result.missing).toHaveLength(0);
605
+ expect(result.extra).toHaveLength(0);
606
+ });
607
+ it("should handle languages with no plural forms", () => {
608
+ const translations = {
609
+ "项目": "项目"
610
+ };
611
+ const result = validatePluralForms(translations, "zh");
612
+ expect(result.isValid).toBe(true);
613
+ expect(result.missing).toHaveLength(0);
614
+ expect(result.extra).toHaveLength(0);
615
+ });
616
+ });
617
+ });
618
+ describe("PO/POT Integration Tests", () => {
619
+ let poHandler;
620
+ let potHandler;
621
+ beforeEach(() => {
622
+ poHandler = new POHandler();
623
+ potHandler = new POTHandler();
624
+ });
625
+ describe("POT to PO workflow", () => {
626
+ it("should create PO from POT template and translate back", () => {
627
+ const potPath = path.join(__dirname, "test-data", "sample.pot");
628
+ const potContent = fs.readFileSync(potPath, "utf-8");
629
+ // Parse POT template
630
+ const potData = potHandler.parse(potContent);
631
+ // Verify template has empty translations
632
+ expect(potData["Hello, World!"]).toBe("");
633
+ expect(potData["greeting|Hello"]).toBe("");
634
+ // Generate PO with translations
635
+ const translations = {
636
+ "Hello, World!": "¡Hola, Mundo!",
637
+ "Welcome to our application": "Bienvenido a nuestra aplicación",
638
+ "greeting|Hello": "Hola",
639
+ "farewell|Hello": "Adiós"
640
+ };
641
+ const poContent = potHandler.generatePOFromTemplate(potContent, "es", translations);
642
+ // Parse the generated PO
643
+ const poData = poHandler.parse(poContent);
644
+ // Verify translations are applied
645
+ expect(poData["Hello, World!"]).toBe("¡Hola, Mundo!");
646
+ expect(poData["Welcome to our application"]).toBe("Bienvenido a nuestra aplicación");
647
+ expect(poData["greeting|Hello"]).toBe("Hola");
648
+ expect(poData["farewell|Hello"]).toBe("Adiós");
649
+ expect(poData._metadata?.targetLanguage).toBe("es");
650
+ });
651
+ it("should handle plural forms in POT to PO conversion", () => {
652
+ const potWithPlurals = `
653
+ msgid ""
654
+ msgstr ""
655
+ "Content-Type: text/plain; charset=UTF-8\\n"
656
+
657
+ msgid "One file"
658
+ msgid_plural "%d files"
659
+ msgstr[0] ""
660
+ msgstr[1] ""
661
+ `;
662
+ const translations = {
663
+ "One file": "Un archivo",
664
+ "One file[1]": "%d archivos"
665
+ };
666
+ const poContent = potHandler.generatePOFromTemplate(potWithPlurals, "es", translations);
667
+ const poData = poHandler.parse(poContent);
668
+ expect(poData["One file"]).toBe("Un archivo");
669
+ expect(poData["One file[1]"]).toBe("%d archivos");
670
+ });
671
+ it("should maintain context in POT to PO conversion", () => {
672
+ const potWithContext = `
673
+ msgid ""
674
+ msgstr ""
675
+ "Content-Type: text/plain; charset=UTF-8\\n"
676
+
677
+ msgctxt "menu"
678
+ msgid "File"
679
+ msgstr ""
680
+
681
+ msgctxt "document"
682
+ msgid "File"
683
+ msgstr ""
684
+ `;
685
+ const translations = {
686
+ "menu|File": "Archivo",
687
+ "document|File": "Documento"
688
+ };
689
+ const poContent = potHandler.generatePOFromTemplate(potWithContext, "es", translations);
690
+ const poData = poHandler.parse(poContent);
691
+ expect(poData["menu|File"]).toBe("Archivo");
692
+ expect(poData["document|File"]).toBe("Documento");
693
+ });
694
+ });
695
+ describe("format detection", () => {
696
+ it("should correctly identify PO vs POT files", () => {
697
+ expect(poHandler.canHandle("test.po")).toBe(true);
698
+ expect(poHandler.canHandle("test.pot")).toBe(false);
699
+ expect(potHandler.canHandle("test.pot")).toBe(true);
700
+ expect(potHandler.canHandle("test.po")).toBe(false);
701
+ });
702
+ it("should identify PO content by signature", () => {
703
+ const poContent = `
704
+ msgid "Hello"
705
+ msgstr "Hola"
706
+ `;
707
+ const potContent = `
708
+ # POT-Creation-Date: 2024-01-01 12:00+0000
709
+ msgid "Hello"
710
+ msgstr ""
711
+ `;
712
+ expect(poHandler.canHandle("test.po", poContent)).toBe(true);
713
+ expect(potHandler.canHandle("test.pot", potContent)).toBe(true);
714
+ });
715
+ });
716
+ describe("error handling", () => {
717
+ it("should handle invalid POT template generation", () => {
718
+ const invalidPOT = "not a valid pot file";
719
+ expect(() => {
720
+ potHandler.generatePOFromTemplate(invalidPOT, "es");
721
+ }).toThrow("Failed to generate PO from POT template");
722
+ });
723
+ it("should handle serialization errors gracefully", () => {
724
+ const invalidData = {
725
+ Hello: "Hola",
726
+ _metadata: {
727
+ originalStructure: {
728
+ // Create a circular reference that will cause JSON.parse to fail
729
+ get circular() { return this; }
730
+ }
731
+ }
732
+ };
733
+ expect(() => {
734
+ poHandler.serialize(invalidData);
735
+ }).toThrow("Failed to serialize PO file");
736
+ });
737
+ });
738
+ describe("encoding handling", () => {
739
+ it("should handle different encodings", () => {
740
+ const data = {
741
+ "Café": "Café",
742
+ "Niño": "Niño",
743
+ "Año": "Año",
744
+ _metadata: {
745
+ format: "po",
746
+ encoding: "utf-8",
747
+ targetLanguage: "es"
748
+ }
749
+ };
750
+ const serialized = poHandler.serialize(data);
751
+ const parsed = poHandler.parse(serialized);
752
+ expect(parsed["Café"]).toBe("Café");
753
+ expect(parsed["Niño"]).toBe("Niño");
754
+ expect(parsed["Año"]).toBe("Año");
755
+ });
756
+ it("should preserve encoding in metadata", () => {
757
+ const data = {
758
+ Hello: "Hola",
759
+ _metadata: {
760
+ format: "po",
761
+ encoding: "iso-8859-1"
762
+ }
763
+ };
764
+ const serialized = poHandler.serialize(data, { encoding: "iso-8859-1" });
765
+ expect(serialized).toContain("charset=iso-8859-1");
766
+ });
767
+ });
768
+ });