@publishpress/potomatic 0.0.0-stage → 1.4.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.
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Utility functions for proper singular/plural forms in output messages.
3
+ *
4
+ * @since 1.0.0
5
+ */
6
+
7
+ /**
8
+ * Returns the correct singular or plural form of a word based on count.
9
+ *
10
+ * @since 1.0.0
11
+ *
12
+ * @param {number} count - The count to determine singular/plural.
13
+ * @param {string} singular - The singular form of the word.
14
+ * @param {string} plural - The plural form of the word (optional, defaults to singular + 's').
15
+ *
16
+ * @return {string} The correct form of the word.
17
+ */
18
+ export function pluralize(count, singular, plural = null) {
19
+ if (plural === null) {
20
+ plural = singular + 's';
21
+ }
22
+
23
+ return count === 1 ? singular : plural;
24
+ }
25
+
26
+ /**
27
+ * Returns a formatted string with count and properly pluralized word.
28
+ *
29
+ * @since 1.0.0
30
+ *
31
+ * @param {number} count - The count to display and use for pluralization.
32
+ * @param {string} singular - The singular form of the word.
33
+ * @param {string} plural - The plural form of the word (optional, defaults to singular + 's').
34
+ *
35
+ * @return {string} Formatted string like "1 item" or "5 items".
36
+ */
37
+ export function formatCount(count, singular, plural = null) {
38
+ return `${count} ${pluralize(count, singular, plural)}`;
39
+ }
@@ -0,0 +1,599 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import gettextParser from 'gettext-parser';
4
+ import { getPoHeaderLocale } from './languageMapping.js';
5
+
6
+ /**
7
+ * Mapping of language codes to their plural forms rules.
8
+ * Rules are primarily sourced from GlotPress (locales.php) for WordPress compatibility.
9
+ * Supports both specific locales (e.g., fr_FR) and base languages (e.g., fr).
10
+ *
11
+ * @since 1.0.0
12
+ */
13
+ const pluralFormsMap = {
14
+ af: 'nplurals=2; plural=(n != 1);', // Afrikaans.
15
+ ar: 'nplurals=6; plural=(n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5);', // Arabic.
16
+ az: 'nplurals=2; plural=(n != 1);', // Azerbaijani.
17
+ bg_BG: 'nplurals=2; plural=(n != 1);', // Bulgarian.
18
+ bn_BD: 'nplurals=2; plural=(n != 1);', // Bengali (Bangladesh.).
19
+ ca: 'nplurals=2; plural=(n != 1);', // Catalan.
20
+ cs_CZ: 'nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;', // Czech.
21
+ cy: 'nplurals=4; plural=(n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3;', // Welsh.
22
+ da_DK: 'nplurals=2; plural=(n != 1);', // Danish.
23
+ de_DE: 'nplurals=2; plural=(n != 1);', // German (Germany.).
24
+ de_CH: 'nplurals=2; plural=(n != 1);', // German (Switzerland.).
25
+ el: 'nplurals=2; plural=(n != 1);', // Greek.
26
+ en_AU: 'nplurals=2; plural=(n != 1);', // English (Australia.).
27
+ en_CA: 'nplurals=2; plural=(n != 1);', // English (Canada.).
28
+ en_GB: 'nplurals=2; plural=(n != 1);', // English (UK.).
29
+ en_US: 'nplurals=2; plural=(n != 1);', // English (US.).
30
+ en_ZA: 'nplurals=2; plural=(n != 1);', // English (South Africa.).
31
+ eo: 'nplurals=2; plural=(n != 1);', // Esperanto.
32
+ es_AR: 'nplurals=2; plural=(n != 1);', // Spanish (Argentina.).
33
+ es_CL: 'nplurals=2; plural=(n != 1);', // Spanish (Chile.).
34
+ es_CO: 'nplurals=2; plural=(n != 1);', // Spanish (Colombia.).
35
+ es_ES: 'nplurals=2; plural=(n != 1);', // Spanish (Spain.).
36
+ es_MX: 'nplurals=2; plural=(n != 1);', // Spanish (Mexico.).
37
+ es_PE: 'nplurals=2; plural=(n != 1);', // Spanish (Peru.).
38
+ es_VE: 'nplurals=2; plural=(n != 1);', // Spanish (Venezuela.).
39
+ et: 'nplurals=2; plural=(n != 1);', // Estonian.
40
+ eu: 'nplurals=2; plural=(n != 1);', // Basque.
41
+ fa_IR: 'nplurals=1; plural=0;', // Persian (Iran) - GlotPress uses nplurals=2, plural=(n > 1) for 'fa', but many sources show.1. Sticking to common practice for fa_IR.
42
+ fi: 'nplurals=2; plural=(n != 1);', // Finnish.
43
+ fo: 'nplurals=2; plural=(n != 1);', // Faroese.
44
+ fr_BE: 'nplurals=2; plural=(n > 1);', // French (Belgium.).
45
+ fr_CA: 'nplurals=2; plural=(n > 1);', // French (Canada.).
46
+ fr_FR: 'nplurals=2; plural=(n > 1);', // French (France.).
47
+ fy: 'nplurals=2; plural=(n != 1);', // Frisian.
48
+ ga: 'nplurals=5; plural=n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4;', // Irish.
49
+ gd: 'nplurals=4; plural=(n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3;', // Scottish Gaelic.
50
+ gl_ES: 'nplurals=2; plural=(n != 1);', // Galician.
51
+ he_IL: 'nplurals=2; plural=(n != 1);', // Hebrew. GlotPress has 4; (n==1 ? 0 : n==2 ? 1 : (n<0 || n>10) && n%10==0 ? 2 : 3); for general 'he' - using simpler common one for IL.
52
+ hi_IN: 'nplurals=2; plural=(n != 1);', // Hindi.
53
+ hr: 'nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);', // Croatian.
54
+ hu_HU: 'nplurals=2; plural=(n != 1);', // Hungarian.
55
+ hy: 'nplurals=2; plural=(n != 1);', // Armenian.
56
+ id_ID: 'nplurals=1; plural=0;', // Indonesian.
57
+ is_IS: 'nplurals=2; plural=(n%10!=1 || n%100==11);', // Icelandic.
58
+ it_IT: 'nplurals=2; plural=(n != 1);', // Italian.
59
+ ja: 'nplurals=1; plural=0;', // Japanese.
60
+ ka_GE: 'nplurals=1; plural=0;', // Georgian.
61
+ ko_KR: 'nplurals=1; plural=0;', // Korean.
62
+ ku: 'nplurals=2; plural=(n != 1);', // Kurdish.
63
+ lt_LT: 'nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);', // Lithuanian.
64
+ lv_LV: 'nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n!=0 ? 1 : 2);', // Latvian.
65
+ mk_MK: 'nplurals=2; plural=n==1 || n%10==1 ? 0 : 1;', // Macedonian.
66
+ mn: 'nplurals=2; plural=(n != 1);', // Mongolian.
67
+ ms_MY: 'nplurals=1; plural=0;', // Malay.
68
+ nb_NO: 'nplurals=2; plural=(n != 1);', // Norwegian Bokmål.
69
+ ne_NP: 'nplurals=2; plural=(n != 1);', // Nepali.
70
+ nl_NL: 'nplurals=2; plural=(n != 1);', // Dutch (Netherlands.).
71
+ nl_BE: 'nplurals=2; plural=(n != 1);', // Dutch (Belgium.).
72
+ nn_NO: 'nplurals=2; plural=(n != 1);', // Norwegian Nynorsk.
73
+ pl_PL: 'nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);', // Polish.
74
+ pt_BR: 'nplurals=2; plural=(n > 1);', // Portuguese (Brazil) - GlotPress uses (n!=1) for pt_BR, but (n>1) is common for Brazil.
75
+ pt_PT: 'nplurals=2; plural=(n != 1);', // Portuguese (Portugal.).
76
+ ro_RO: 'nplurals=3; plural=(n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);', // Romanian.
77
+ ru_RU: 'nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);', // Russian.
78
+ sk_SK: 'nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;', // Slovak.
79
+ sl_SI: 'nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3);', // Slovenian.
80
+ sq_AL: 'nplurals=2; plural=(n != 1);', // Albanian.
81
+ sr_RS: 'nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);', // Serbian.
82
+ sv_SE: 'nplurals=2; plural=(n != 1);', // Swedish.
83
+ th: 'nplurals=1; plural=0;', // Thai.
84
+ tr_TR: 'nplurals=2; plural=(n > 1);', // Turkish - GlotPress has (n != 1) for tr. (n > 1) is also common.
85
+ uk: 'nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);', // Ukrainian.
86
+ vi: 'nplurals=1; plural=0;', // Vietnamese.
87
+ zh_CN: 'nplurals=1; plural=0;', // Chinese (China.).
88
+ zh_HK: 'nplurals=1; plural=0;', // Chinese (Hong Kong.).
89
+ zh_TW: 'nplurals=1; plural=0;', // Chinese (Taiwan.).
90
+
91
+ // Fallbacks for base languages. These are lower precedence than specific regional codes.
92
+ en: 'nplurals=2; plural=(n != 1);',
93
+ de: 'nplurals=2; plural=(n != 1);',
94
+ es: 'nplurals=2; plural=(n != 1);',
95
+ fr: 'nplurals=2; plural=(n > 1);',
96
+ it: 'nplurals=2; plural=(n != 1);',
97
+ pt: 'nplurals=2; plural=(n != 1);', // Defaulting to Portugal's (n != 1) for generic 'pt.'.
98
+ nl: 'nplurals=2; plural=(n != 1);',
99
+ ru: 'nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);',
100
+ pl: 'nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);',
101
+ cs: 'nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;',
102
+ zh: 'nplurals=1; plural=0;', // Already specific, but good as a base.
103
+ ko: 'nplurals=1; plural=0;', // Already specific, but good as a base.
104
+ tr: 'nplurals=2; plural=(n > 1);', // Fallback for Turkish.
105
+ };
106
+
107
+ /**
108
+ * Default plural forms rule used as fallback when language-specific rule is not found.
109
+ * Uses the common English plural rule: singular for 1, plural for everything else.
110
+ *
111
+ * @since 1.0.0
112
+ */
113
+ const DEFAULT_PLURAL_FORMS = 'nplurals=2; plural=(n != 1);'; // English language default.
114
+
115
+ /**
116
+ * Parses a POT or PO file using gettext-parser and returns the parsed data structure.
117
+ *
118
+ * @since 1.0.0
119
+ *
120
+ * @param {string} filePath - Path to the .pot or .po file to parse.
121
+ * @param {Object} logger - Logger instance for outputting messages.
122
+ *
123
+ * @return {Object} Parsed POT/PO data structure containing translations, headers, etc.
124
+ *
125
+ * @throws {Error} When file cannot be read or parsed.
126
+ */
127
+ export async function parsePotFile(filePath, logger) {
128
+ try {
129
+ const potFileContent = fs.readFileSync(filePath, 'utf8');
130
+ const parsedPot = gettextParser.po.parse(potFileContent);
131
+
132
+ logger.success(`Successfully parsed .po/.pot file: ${filePath}`);
133
+
134
+ return parsedPot;
135
+ } catch (error) {
136
+ logger.error(`Error reading or parsing .po/.pot file at ${filePath}:`, error);
137
+
138
+ throw error;
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Gets the appropriate plural forms rule for a given language code.
144
+ * Tries specific locale first (e.g., fr_FR), then base language (e.g., fr).
145
+ *
146
+ * @since 1.0.0
147
+ *
148
+ * @param {string} languageCode - Language code like 'fr_FR', 'en_US', or 'ja'.
149
+ * @param {Object} logger - Logger instance for outputting messages.
150
+ *
151
+ * @return {string} Plural forms rule string (e.g., 'nplurals=2; plural=(n != 1);').
152
+ */
153
+ export function getPluralForms(languageCode, logger) {
154
+ if (!languageCode) {
155
+ logger.warn('No language code provided for getPluralForms, using default.');
156
+
157
+ return DEFAULT_PLURAL_FORMS;
158
+ }
159
+
160
+ // Try specific locale first (.e.g., fr_FR).
161
+ if (pluralFormsMap[languageCode]) {
162
+ logger.debug(`Found specific plural form for ${languageCode}: ${pluralFormsMap[languageCode]}`);
163
+
164
+ return pluralFormsMap[languageCode];
165
+ }
166
+
167
+ // Try base language (.e.g., fr) if specific not found.
168
+ const baseLanguage = languageCode.split('_')[0];
169
+
170
+ if (pluralFormsMap[baseLanguage]) {
171
+ logger.debug(`Found base language plural form for ${languageCode} (using ${baseLanguage}): ${pluralFormsMap[baseLanguage]}`);
172
+
173
+ return pluralFormsMap[baseLanguage];
174
+ }
175
+
176
+ logger.warn(`No plural form found for language code ${languageCode} or base language ${baseLanguage}. Using default: ${DEFAULT_PLURAL_FORMS}`);
177
+
178
+ return DEFAULT_PLURAL_FORMS;
179
+ }
180
+
181
+ /**
182
+ * Compiles parsed PO data into a .po file with proper headers and formatting.
183
+ * Merges default headers with custom template and sets dynamic values.
184
+ *
185
+ * @since 1.0.0
186
+ *
187
+ * @param {Object} parsedPot - Parsed POT/PO data structure.
188
+ * @param {string} targetLang - Target language code (e.g., 'fr_FR', 'en_US').
189
+ * @param {string} outputFilePath - Path where the compiled .po file will be saved.
190
+ * @param {Object} logger - Logger instance for outputting messages.
191
+ *
192
+ * @param {string|null} poHeaderTemplatePath - Optional path to JSON header template file.
193
+ *
194
+ * @return {boolean} True if compilation and saving succeeded, false otherwise.
195
+ */
196
+ export async function compilePoFile(parsedPot, targetLang, outputFilePath, logger, poHeaderTemplatePath = null) {
197
+ if (!parsedPot) {
198
+ logger.error('Cannot compile .po file: parsed PO data is missing.');
199
+
200
+ return false;
201
+ }
202
+
203
+ if (!targetLang) {
204
+ logger.error('Cannot compile .po file: target language is missing.');
205
+
206
+ return false;
207
+ }
208
+
209
+ if (!outputFilePath) {
210
+ logger.error('Cannot compile .po file: output file path is missing.');
211
+
212
+ return false;
213
+ }
214
+
215
+ const compiledPoData = { ...parsedPot };
216
+
217
+ compiledPoData.headers = { ...(compiledPoData.headers || {}) };
218
+
219
+ // Load and merge custom headers template.
220
+ let customHeaders = {};
221
+
222
+ if (poHeaderTemplatePath) {
223
+ try {
224
+ const templateContent = fs.readFileSync(poHeaderTemplatePath, 'utf8');
225
+
226
+ customHeaders = JSON.parse(templateContent);
227
+
228
+ logger.debug(`Successfully loaded custom PO header template from: ${poHeaderTemplatePath}`);
229
+ } catch (err) {
230
+ logger.warn(`Could not read or parse PO header template at ${poHeaderTemplatePath}. Using defaults. Error: ${err.message}`);
231
+ }
232
+ }
233
+
234
+ const baseHeaders = { ...(parsedPot.headers || {}), ...customHeaders };
235
+
236
+ // Set/update dynamic headers.
237
+ const poRevisionDate = new Date().toISOString().slice(0, 16).replace('T', ' ') + '+0000';
238
+ const pluralForms = getPluralForms(targetLang, logger);
239
+
240
+ // Replace placeholders in all baseHeaders values.
241
+ for (const key in baseHeaders) {
242
+ if (typeof baseHeaders[key] !== 'string') {
243
+ continue;
244
+ }
245
+
246
+ baseHeaders[key] = baseHeaders[key].replace(/{{LANGUAGE}}/g, targetLang);
247
+ }
248
+
249
+ // These are the final authoritative values for these specific headers.
250
+ // Note: Plural-Forms is set if not already present OR if it contains placeholder values.
251
+ const finalDynamicHeaders = {
252
+ Language: getPoHeaderLocale(targetLang),
253
+ 'PO-Revision-Date': poRevisionDate,
254
+ };
255
+
256
+ // Set Plural-Forms if it's not already present OR if it contains placeholder values.
257
+ const existingPluralForms = baseHeaders['Plural-Forms'];
258
+ const hasPlaceholderPluralForms = !existingPluralForms || existingPluralForms.includes('INTEGER') || existingPluralForms.includes('EXPRESSION');
259
+
260
+ if (hasPlaceholderPluralForms) {
261
+ finalDynamicHeaders['Plural-Forms'] = pluralForms;
262
+ }
263
+
264
+ compiledPoData.headers = { ...baseHeaders, ...finalDynamicHeaders }; // Dynamic headers take final precedence.
265
+
266
+ // Ensure charset is correctly set if not present or different.
267
+ if (!compiledPoData.charset || compiledPoData.charset.toLowerCase() !== 'utf-8') {
268
+ compiledPoData.charset = 'utf-8'; // Standardize to UTF-.8.
269
+ logger.debug('Charset standardized to utf-8 in compiled PO data.');
270
+ }
271
+
272
+ try {
273
+ const outputContent = gettextParser.po.compile(compiledPoData);
274
+ const outputDir = path.dirname(outputFilePath);
275
+
276
+ if (!fs.existsSync(outputDir)) {
277
+ fs.mkdirSync(outputDir, { recursive: true });
278
+ }
279
+
280
+ fs.writeFileSync(outputFilePath, outputContent);
281
+
282
+ logger.success(`Successfully compiled and saved .po file to: ${outputFilePath}`);
283
+
284
+ return true;
285
+ } catch (error) {
286
+ logger.error(`Error compiling or writing .po file to ${outputFilePath}:`, error);
287
+
288
+ return false;
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Counts the number of untranslated strings in a parsed PO data structure.
294
+ * A string is considered untranslated if it has no `msgstr` or all `msgstr` entries are empty.
295
+ *
296
+ * @since 1.0.0
297
+ *
298
+ * @param {Object} poData - Parsed PO data structure containing translations.
299
+ *
300
+ * @return {number} Count of untranslated strings.
301
+ */
302
+ export function countUntranslatedStrings(poData) {
303
+ if (!poData?.translations) {
304
+ return 0;
305
+ }
306
+
307
+ let count = 0;
308
+
309
+ for (const context of Object.values(poData.translations)) {
310
+ if (!context || typeof context !== 'object') {
311
+ continue;
312
+ }
313
+
314
+ for (const [msgid, entry] of Object.entries(context)) {
315
+ if (msgid === '') {
316
+ continue; // Skip header.
317
+ }
318
+
319
+ const msgstr = entry?.msgstr;
320
+
321
+ // Check if it needs translation (empty or dry run placeholder.).
322
+ let needsTranslation = !msgstr || msgstr.every((str) => !str);
323
+
324
+ // Also consider dry run placeholders as needing translation.
325
+ if (!needsTranslation && msgstr) {
326
+ needsTranslation = msgstr.every((str) => {
327
+ if (!str || str.trim() === '') {
328
+ return true; // Empty strings need translation.
329
+ }
330
+
331
+ // Dry run placeholders also need translation.
332
+ return str.startsWith('[DRY RUN]');
333
+ });
334
+ }
335
+
336
+ if (needsTranslation) {
337
+ count++;
338
+ }
339
+ }
340
+ }
341
+
342
+ return count;
343
+ }
344
+
345
+ /**
346
+ * Counts the number of real translations in a parsed PO data structure.
347
+ * Excludes dry run placeholders and empty translations.
348
+ *
349
+ * @since 1.0.0
350
+ *
351
+ * @param {Object} poData - Parsed PO data structure containing translations.
352
+ *
353
+ * @return {number} Count of real translations.
354
+ */
355
+ export function countRealTranslations(poData) {
356
+ if (!poData?.translations) {
357
+ return 0;
358
+ }
359
+
360
+ let count = 0;
361
+
362
+ for (const context of Object.values(poData.translations)) {
363
+ if (!context || typeof context !== 'object') {
364
+ continue;
365
+ }
366
+
367
+ for (const [msgid, entry] of Object.entries(context)) {
368
+ if (msgid === '') {
369
+ continue; // Skip header.
370
+ }
371
+
372
+ const msgstr = entry?.msgstr;
373
+
374
+ // Check if it has valid translation content.
375
+ if (!msgstr || msgstr.length === 0) {
376
+ continue;
377
+ }
378
+
379
+ // Check if all msgstr entries are empty or dry run placeholders.
380
+ const hasRealTranslation = msgstr.some((str) => {
381
+ if (!str || str.trim() === '') {
382
+ return false;
383
+ }
384
+
385
+ // Check if it's a dry run placeholder.
386
+ if (str.startsWith('[DRY RUN]')) {
387
+ return false;
388
+ }
389
+
390
+ return true;
391
+ });
392
+
393
+ if (hasRealTranslation) {
394
+ count++;
395
+ }
396
+ }
397
+ }
398
+
399
+ return count;
400
+ }
401
+
402
+ /**
403
+ * Merges existing PO data into a fresh clone of POT data.
404
+ * Preserves valid translations from existing PO file while maintaining POT structure.
405
+ *
406
+ * @since 1.0.0
407
+ *
408
+ * @param {Object} basePotData - Base POT data structure to merge into.
409
+ * @param {Object} existingPoData - Existing PO data containing translations to preserve.
410
+ * @param {Object} localLogger - Logger instance for outputting debug messages.
411
+ * @param {string|null} targetLanguage - Target language code for proper plural forms handling.
412
+ *
413
+ * @return {Object} Object containing outputPoData (merged result) and mergedStringsCount.
414
+ */
415
+ export function mergePoData(basePotData, existingPoData, localLogger, targetLanguage = null) {
416
+ const outputPoData = JSON.parse(JSON.stringify(basePotData)); // Deep clone base. .pot data.
417
+ let mergedStringsCount = 0;
418
+
419
+ // Get target language plural count for proper plural forms handling.
420
+ let targetPluralCount = 2; // Default fallback.
421
+
422
+ if (targetLanguage) {
423
+ const fallbackLogger = localLogger && typeof localLogger.debug === 'function' && typeof localLogger.warn === 'function' ? localLogger : { debug: () => {}, warn: () => {} };
424
+ const pluralFormsString = getPluralForms(targetLanguage, fallbackLogger);
425
+
426
+ targetPluralCount = extractPluralCount(pluralFormsString);
427
+ }
428
+
429
+ // 1. Merge Headers.
430
+ const dynamicHeaderKeys = ['Language', 'PO-Revision-Date', 'Last-Translator', 'MIME-Version', 'Content-Transfer-Encoding'];
431
+
432
+ if (existingPoData.headers) {
433
+ outputPoData.headers = outputPoData.headers || {};
434
+
435
+ for (const key in existingPoData.headers) {
436
+ // If the header is one of the dynamic ones, and the base POT data already has a version of it (.e.g., POT-Creation-Date),
437
+ // we might prefer the base one or let compilePoFile handle it.
438
+ // For non-dynamic headers, or dynamic ones not in base, take from existing.
439
+ // The main goal is to preserve user-defined headers from the existing. .po file.
440
+ // compilePoFile will have the final say on essential dynamic headers like Language, Plural-Forms.
441
+ if (dynamicHeaderKeys.includes(key)) {
442
+ // If it's a dynamic header, only preserve it if it's not already in the base POT data.
443
+ if (!basePotData.headers || !basePotData.headers[key]) {
444
+ outputPoData.headers[key] = existingPoData.headers[key];
445
+ }
446
+ // Otherwise, let compilePoFile handle the final value.
447
+ } else {
448
+ // Not a dynamic key, so preserve from existing. .po file.
449
+ outputPoData.headers[key] = existingPoData.headers[key];
450
+ }
451
+ }
452
+ }
453
+
454
+ // 2. Merge translations.
455
+ for (const context of Object.keys(outputPoData.translations)) {
456
+ if (!outputPoData.translations[context]) {
457
+ continue;
458
+ }
459
+
460
+ for (const msgid of Object.keys(outputPoData.translations[context])) {
461
+ if (msgid === '') {
462
+ continue; // Skip POT header entry.
463
+ }
464
+
465
+ const potEntry = outputPoData.translations[context][msgid];
466
+ const existingEntry = existingPoData.translations && existingPoData.translations[context] && existingPoData.translations[context][msgid];
467
+
468
+ // Skip if no existing entry or no valid translation.
469
+ if (!existingEntry || !existingEntry.msgstr || existingEntry.msgstr.length === 0 || !existingEntry.msgstr[0]) {
470
+ continue;
471
+ }
472
+
473
+ // Handle plural forms correctly.
474
+ if (potEntry.msgid_plural) {
475
+ // This is a plural entry - ensure we maintain the correct number of forms.
476
+ const existingMsgstr = existingEntry.msgstr;
477
+ const newMsgstr = new Array(targetPluralCount).fill('');
478
+
479
+ // Copy existing translations up to the target plural count.
480
+ for (let i = 0; i < Math.min(existingMsgstr.length, targetPluralCount); i++) {
481
+ if (existingMsgstr[i] && existingMsgstr[i].trim() !== '') {
482
+ newMsgstr[i] = existingMsgstr[i];
483
+ }
484
+ }
485
+
486
+ // Only merge if we have at least one valid translation.
487
+ const hasValidTranslation = newMsgstr.some((str) => str && str.trim() !== '');
488
+
489
+ if (hasValidTranslation) {
490
+ potEntry.msgstr = newMsgstr;
491
+ mergedStringsCount++;
492
+
493
+ if (localLogger && typeof localLogger.debug === 'function') {
494
+ localLogger.debug(`Merged plural entry "${msgid}" with ${targetPluralCount} forms (${existingMsgstr.length} existing forms)`);
495
+ }
496
+ }
497
+ } else {
498
+ // Regular (non-plural) entry.
499
+ potEntry.msgstr = existingEntry.msgstr;
500
+ mergedStringsCount++;
501
+ }
502
+
503
+ if (existingEntry.comments && existingEntry.comments.flag === 'fuzzy') {
504
+ potEntry.comments = { ...(potEntry.comments || {}), flag: 'fuzzy' };
505
+ } else if (potEntry.comments && potEntry.comments.flag === 'fuzzy') {
506
+ delete potEntry.comments.flag;
507
+
508
+ if (Object.keys(potEntry.comments).length === 0) {
509
+ delete potEntry.comments;
510
+ }
511
+ }
512
+ }
513
+ }
514
+
515
+ if (localLogger && typeof localLogger.debug === 'function') {
516
+ // Check if logger and debug method exist.
517
+ localLogger.debug(`mergePoData: Merged ${mergedStringsCount} strings. Header merge strategy applied.`);
518
+ }
519
+
520
+ return { outputPoData, mergedStringsCount };
521
+ }
522
+
523
+ /**
524
+ * Extracts the number of plural forms from a plural forms string.
525
+ *
526
+ * @since 1.0.0
527
+ *
528
+ * @param {string} pluralFormsString - Plural forms string (e.g., 'nplurals=6; plural=(n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5);').
529
+ *
530
+ * @return {number} Number of plural forms (defaults to 2 if parsing fails).
531
+ */
532
+ export function extractPluralCount(pluralFormsString) {
533
+ if (!pluralFormsString) {
534
+ return 2;
535
+ }
536
+
537
+ const match = pluralFormsString.match(/nplurals\s*=\s*(\d+)/);
538
+
539
+ return match ? parseInt(match[1], 10) : 2;
540
+ }
541
+
542
+ /**
543
+ * Initializes plural entries in PO data with the correct number of msgstr entries for the target language.
544
+ * This ensures that plural forms have the right number of empty slots for translation.
545
+ *
546
+ * @since 1.0.0
547
+ *
548
+ * @param {Object} poData - Parsed PO data structure.
549
+ * @param {string} targetLanguage - Target language code (e.g., 'ar', 'pl_PL').
550
+ * @param {Object} logger - Logger instance for outputting messages.
551
+ *
552
+ * @return {Object} Updated PO data with correctly initialized plural forms.
553
+ */
554
+ export function initializePluralForms(poData, targetLanguage, logger) {
555
+ const pluralFormsString = getPluralForms(targetLanguage, logger);
556
+ const pluralCount = extractPluralCount(pluralFormsString);
557
+
558
+ logger.debug(`Initializing plural forms for ${targetLanguage}: ${pluralCount} forms`);
559
+
560
+ // Deep clone to avoid modifying the original.
561
+ const updatedPoData = JSON.parse(JSON.stringify(poData));
562
+
563
+ // Update headers with correct plural forms.
564
+ if (!updatedPoData.headers) {
565
+ updatedPoData.headers = {};
566
+ }
567
+
568
+ updatedPoData.headers['Plural-Forms'] = pluralFormsString;
569
+
570
+ // Initialize plural entries with correct number of msgstr entries.
571
+ for (const contextKey in updatedPoData.translations) {
572
+ const context = updatedPoData.translations[contextKey];
573
+
574
+ for (const msgid in context) {
575
+ const entry = context[msgid];
576
+
577
+ // Skip header entry.
578
+ if (msgid === '') {
579
+ continue;
580
+ }
581
+
582
+ // Check if this is a plural entry.
583
+ if (entry.msgid_plural) {
584
+ // Initialize with the correct number of empty strings.
585
+ entry.msgstr = new Array(pluralCount).fill('');
586
+ logger.debug(`Initialized plural entry "${msgid}" with ${pluralCount} forms`);
587
+ }
588
+ }
589
+ }
590
+
591
+ return updatedPoData;
592
+ }
593
+
594
+ /**
595
+ * Export constants for external use in other modules.
596
+ *
597
+ * @since 1.0.0
598
+ */
599
+ export { pluralFormsMap, DEFAULT_PLURAL_FORMS };