@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.
- package/CHANGELOG.md +127 -0
- package/LICENSE.md +20 -0
- package/README.md +470 -2
- package/config/openai-pricing.json +112 -0
- package/config/po-header.json +10 -0
- package/config/prompt.md +23 -0
- package/package.json +84 -5
- package/potomatic +103 -0
- package/src/config/index.js +497 -0
- package/src/logging/index.js +362 -0
- package/src/orchestrator/index.js +1031 -0
- package/src/processors/batchProcessor.js +171 -0
- package/src/processors/languageProcessor.js +1464 -0
- package/src/providers/ProviderFactory.js +124 -0
- package/src/providers/base/Provider.js +198 -0
- package/src/providers/openai/OpenAIProvider.js +805 -0
- package/src/providers/openai/modelCapabilities.js +256 -0
- package/src/reporters/ConsoleReporter.js +256 -0
- package/src/reporters/JsonReporter.js +254 -0
- package/src/reporters/ReporterFactory.js +218 -0
- package/src/reporters/base/BaseReporter.js +124 -0
- package/src/utils/colorUtils.js +93 -0
- package/src/utils/costCalculations.js +245 -0
- package/src/utils/costTracker.js +277 -0
- package/src/utils/dictionaryUtils.js +211 -0
- package/src/utils/languageMapping.js +1113 -0
- package/src/utils/pluralization.js +39 -0
- package/src/utils/poFileUtils.js +599 -0
- package/src/utils/promptLoader.js +115 -0
- package/src/utils/reportingUtils.js +417 -0
- package/src/utils/validationStats.js +110 -0
- package/src/utils/xmlTranslation.js +532 -0
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* XML-based translation utilities.
|
|
3
|
+
* Provides simple and reliable XML format for AI translation requests.
|
|
4
|
+
*
|
|
5
|
+
* @since 1.0.0
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { getLanguageName } from './languageMapping.js';
|
|
9
|
+
import { createEmptyValidationStats } from './validationStats.js';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Builds XML prompt for translation batch with optional dictionary examples.
|
|
13
|
+
*
|
|
14
|
+
* @since 1.0.0
|
|
15
|
+
*
|
|
16
|
+
* @param {Array} batch - Array of translation entries.
|
|
17
|
+
* @param {string} targetLang - Target language code.
|
|
18
|
+
* @param {number} pluralCount - Number of plural forms for target language.
|
|
19
|
+
* @param {Array} dictionaryMatches - Optional dictionary examples to include.
|
|
20
|
+
*
|
|
21
|
+
* @return {Object} Object containing xmlPrompt, dictionaryCount, and metadata.
|
|
22
|
+
*/
|
|
23
|
+
export function buildXmlPrompt(batch, targetLang, pluralCount, dictionaryMatches = []) {
|
|
24
|
+
const languageName = getLanguageName(targetLang);
|
|
25
|
+
let prompt = `Translate to ${languageName}:\n\n`;
|
|
26
|
+
let startIndex = 1;
|
|
27
|
+
|
|
28
|
+
// Add dictionary examples first, if any.
|
|
29
|
+
if (dictionaryMatches.length > 0) {
|
|
30
|
+
prompt += '<!-- Dictionary Examples for Consistency -->\n';
|
|
31
|
+
dictionaryMatches.forEach((match, index) => {
|
|
32
|
+
const dictIndex = index + 1;
|
|
33
|
+
const ph = extractPlaceholders(match.source);
|
|
34
|
+
const phAttr = ph ? `placeholders="${escapeXmlAttribute(ph)}"` : 'placeholders="none"';
|
|
35
|
+
|
|
36
|
+
prompt += `<source i="${dictIndex}" ${phAttr}>${escapeXmlAttribute(match.source)}</source>\n`;
|
|
37
|
+
});
|
|
38
|
+
prompt += '<!-- End Dictionary Examples -->\n\n';
|
|
39
|
+
startIndex = dictionaryMatches.length + 1;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const hasPlurals = batch.some((entry) => entry.msgid_plural);
|
|
43
|
+
|
|
44
|
+
const xmlTags = batch
|
|
45
|
+
.map((entry, index) => {
|
|
46
|
+
const actualIndex = startIndex + index;
|
|
47
|
+
const attrs = [`i="${actualIndex}"`];
|
|
48
|
+
|
|
49
|
+
if (entry.extractedComments) {
|
|
50
|
+
attrs.push(`c="${escapeXmlAttribute(entry.extractedComments)}"`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Include expected placeholders so the LLM can verify its output.
|
|
54
|
+
const ph = extractPlaceholders(entry.msgid);
|
|
55
|
+
|
|
56
|
+
if (ph) {
|
|
57
|
+
attrs.push(`placeholders="${escapeXmlAttribute(ph)}"`);
|
|
58
|
+
} else {
|
|
59
|
+
attrs.push('placeholders="none"');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// For plural forms, use separate <singular> and <plural> tags.
|
|
63
|
+
if (entry.msgid_plural) {
|
|
64
|
+
return `<source ${attrs.join(' ')}>
|
|
65
|
+
<singular>${escapeXmlAttribute(entry.msgid)}</singular>
|
|
66
|
+
<plural>${escapeXmlAttribute(entry.msgid_plural)}</plural>
|
|
67
|
+
</source>`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// For singular forms, use simple format.
|
|
71
|
+
return `<source ${attrs.join(' ')}>${escapeXmlAttribute(entry.msgid)}</source>`;
|
|
72
|
+
})
|
|
73
|
+
.join('\n');
|
|
74
|
+
|
|
75
|
+
prompt += xmlTags + '\n\nRespond:\n';
|
|
76
|
+
|
|
77
|
+
if (hasPlurals) {
|
|
78
|
+
const formTags = Array.from({ length: pluralCount }, (_, i) => `<f${i}>translation for form ${i}</f${i}>`).join('');
|
|
79
|
+
|
|
80
|
+
prompt += `For entries with <singular> and <plural> tags, provide ${pluralCount} plural forms:\n`;
|
|
81
|
+
prompt += `Format: <t i="N">${formTags}</t>\n\n`;
|
|
82
|
+
prompt += `For all other entries (no <singular>/<plural>), provide a single translation:\n`;
|
|
83
|
+
prompt += `Format: <t i="N">translation</t>\n`;
|
|
84
|
+
} else {
|
|
85
|
+
prompt += `Format: <t i="N">translation</t>\n`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
xmlPrompt: prompt,
|
|
90
|
+
dictionaryCount: dictionaryMatches.length,
|
|
91
|
+
metadata: {
|
|
92
|
+
hasDictionary: dictionaryMatches.length > 0,
|
|
93
|
+
dictionaryEntries: dictionaryMatches.length,
|
|
94
|
+
batchStartIndex: startIndex,
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Creates dictionary response content for AI context.
|
|
101
|
+
* Builds the expected AI response for dictionary examples.
|
|
102
|
+
*
|
|
103
|
+
* @since 1.0.0
|
|
104
|
+
*
|
|
105
|
+
* @param {Array} dictionaryMatches - Dictionary examples.
|
|
106
|
+
*
|
|
107
|
+
* @return {string} Dictionary response XML content.
|
|
108
|
+
*/
|
|
109
|
+
export function buildDictionaryResponse(dictionaryMatches) {
|
|
110
|
+
return dictionaryMatches.map((match, index) => `<t i="${index + 1}">${escapeXmlAttribute(match.target)}</t>`).join('\n');
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Validates plural form translations.
|
|
115
|
+
* Ensures correct form count and warns about incomplete translations.
|
|
116
|
+
*
|
|
117
|
+
* @since 1.1.0
|
|
118
|
+
*
|
|
119
|
+
* @param {Array<string>} forms - Array of translated forms.
|
|
120
|
+
* @param {string} originalMsgid - Original msgid for logging context.
|
|
121
|
+
* @param {number} expectedCount - Expected number of plural forms.
|
|
122
|
+
* @param {number} itemId - Item ID for logging.
|
|
123
|
+
* @param {Object} logger - Logger instance.
|
|
124
|
+
* @param {number} verbosityLevel - Logger verbosity level (0-3). Warnings shown at level 2+.
|
|
125
|
+
*
|
|
126
|
+
* @return {Object} Object with correctedForms array and hasIssues boolean.
|
|
127
|
+
*/
|
|
128
|
+
function validatePluralForms(forms, originalMsgid, expectedCount, itemId, logger, verbosityLevel = 1) {
|
|
129
|
+
let correctedForms = [...forms];
|
|
130
|
+
let hasIssues = false;
|
|
131
|
+
const issues = [];
|
|
132
|
+
|
|
133
|
+
// Find first non-empty form to use as fallback.
|
|
134
|
+
const fallbackForm = correctedForms.find((f) => f && f.trim() !== '') || '';
|
|
135
|
+
|
|
136
|
+
// Ensure we have exactly the right number of forms.
|
|
137
|
+
if (correctedForms.length < expectedCount) {
|
|
138
|
+
hasIssues = true;
|
|
139
|
+
|
|
140
|
+
issues.push(`insufficient forms (expected ${expectedCount}, got ${correctedForms.length})`);
|
|
141
|
+
|
|
142
|
+
if (verbosityLevel >= 2) {
|
|
143
|
+
logger.warn(`Insufficient plural forms at index ${itemId} for "${originalMsgid.substring(0, 50)}...": ` + `Expected ${expectedCount}, got ${correctedForms.length}. Padding with first form as fallback.`);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
while (correctedForms.length < expectedCount) {
|
|
147
|
+
correctedForms.push(fallbackForm);
|
|
148
|
+
}
|
|
149
|
+
} else if (correctedForms.length > expectedCount) {
|
|
150
|
+
hasIssues = true;
|
|
151
|
+
|
|
152
|
+
issues.push(`excess forms (expected ${expectedCount}, got ${correctedForms.length})`);
|
|
153
|
+
|
|
154
|
+
if (verbosityLevel >= 2) {
|
|
155
|
+
logger.warn(`Too many plural forms at index ${itemId} for "${originalMsgid.substring(0, 50)}...": ` + `Expected ${expectedCount}, got ${correctedForms.length}. Truncating.`);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
correctedForms = correctedForms.slice(0, expectedCount);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Warn about empty forms (except when all are empty - likely not translated yet).
|
|
162
|
+
const nonEmptyCount = correctedForms.filter((f) => f && f.trim() !== '').length;
|
|
163
|
+
|
|
164
|
+
if (nonEmptyCount > 0 && nonEmptyCount < expectedCount) {
|
|
165
|
+
hasIssues = true;
|
|
166
|
+
|
|
167
|
+
const emptyIndices = correctedForms.map((f, i) => (f && f.trim() !== '' ? null : i)).filter((i) => i !== null);
|
|
168
|
+
|
|
169
|
+
issues.push(`incomplete forms (empty at indices [${emptyIndices.join(', ')}])`);
|
|
170
|
+
|
|
171
|
+
if (verbosityLevel >= 2) {
|
|
172
|
+
logger.warn(`Incomplete plural forms at index ${itemId} for "${originalMsgid.substring(0, 50)}...": ` + `Forms at indices [${emptyIndices.join(', ')}] are empty. Filling with first form as fallback.`);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Fill empty forms with the first non-empty form as fallback.
|
|
176
|
+
correctedForms = correctedForms.map((f) => (f && f.trim() !== '' ? f : fallbackForm));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (hasIssues && verbosityLevel >= 3) {
|
|
180
|
+
logger.debug(`Plural issues at index ${itemId}: ${issues.join(', ')}`);
|
|
181
|
+
logger.debug(`Corrected forms:`, correctedForms);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return { correctedForms, hasIssues };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Parses XML response and extracts translations, accounting for dictionary indices.
|
|
189
|
+
*
|
|
190
|
+
* @since 1.0.0
|
|
191
|
+
*
|
|
192
|
+
* @param {string} xmlResponse - XML response from AI provider.
|
|
193
|
+
* @param {Array} batch - Original batch for fallback.
|
|
194
|
+
* @param {number} pluralCount - Expected number of plural forms.
|
|
195
|
+
* @param {Object} logger - Logger instance.
|
|
196
|
+
* @param {number} dictionaryCount - Number of dictionary entries to skip.
|
|
197
|
+
* @param {number} verbosityLevel - Logger verbosity level (0-3). Warnings shown at level 2+.
|
|
198
|
+
*
|
|
199
|
+
* @return {Object} Object with translations array and validationStats.
|
|
200
|
+
*/
|
|
201
|
+
export function parseXmlResponse(xmlResponse, batch, pluralCount, logger, dictionaryCount = 0, verbosityLevel = 1) {
|
|
202
|
+
const result = batch.map((entry) => ({
|
|
203
|
+
msgid: entry.msgid,
|
|
204
|
+
msgstr: Array(entry.msgid_plural ? pluralCount : 1).fill(''),
|
|
205
|
+
}));
|
|
206
|
+
|
|
207
|
+
const validationStats = createEmptyValidationStats();
|
|
208
|
+
|
|
209
|
+
if (!xmlResponse || xmlResponse.trim() === '') {
|
|
210
|
+
if (verbosityLevel >= 2) {
|
|
211
|
+
logger.warn('Empty XML response received');
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return { translations: result, validationStats };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
try {
|
|
218
|
+
const translationBlocks = xmlResponse.match(/<t[^>]*>[\s\S]*?<\/t>/g);
|
|
219
|
+
|
|
220
|
+
if (!translationBlocks) {
|
|
221
|
+
if (verbosityLevel >= 2) {
|
|
222
|
+
logger.warn('No translation blocks found in XML response');
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
return { translations: result, validationStats };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
translationBlocks.forEach((block) => {
|
|
229
|
+
const indexMatch = block.match(/i="(\d+)"/);
|
|
230
|
+
|
|
231
|
+
if (!indexMatch) {
|
|
232
|
+
logger.warn('No index found in translation block');
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const responseIndex = parseInt(indexMatch[1], 10);
|
|
237
|
+
|
|
238
|
+
// Skip dictionary indices - only process translation indices.
|
|
239
|
+
if (responseIndex <= dictionaryCount) {
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Convert to 0-based batch index.
|
|
244
|
+
const batchIndex = responseIndex - dictionaryCount - 1;
|
|
245
|
+
|
|
246
|
+
if (batchIndex < 0 || batchIndex >= batch.length) {
|
|
247
|
+
logger.warn(`Invalid batch index ${batchIndex} (response index ${responseIndex}) in translation block`);
|
|
248
|
+
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// Tolerate stray characters inside the tag (models occasionally emit `<f0">`);
|
|
253
|
+
// a strict match drops the whole entry to the singular branch and blanks every form.
|
|
254
|
+
const hasFormTags = /<f0(?=[\s">])[^>]*>/.test(block);
|
|
255
|
+
const isSingularEntry = !batch[batchIndex].msgid_plural;
|
|
256
|
+
|
|
257
|
+
if (hasFormTags && !isSingularEntry) {
|
|
258
|
+
const forms = [];
|
|
259
|
+
|
|
260
|
+
for (let i = 0; i < pluralCount; i++) {
|
|
261
|
+
const formRegex = new RegExp(`<f${i}(?=[\\s">])[^>]*>(.*?)</f${i}(?=[\\s">])[^>]*>`, 's');
|
|
262
|
+
const formMatch = block.match(formRegex);
|
|
263
|
+
|
|
264
|
+
if (formMatch) {
|
|
265
|
+
const source = i === 0 ? batch[batchIndex].msgid : batch[batchIndex].msgid_plural || batch[batchIndex].msgid;
|
|
266
|
+
const translation = normalizeNbsp(decodeXmlEntities(formMatch[1]), source);
|
|
267
|
+
|
|
268
|
+
forms[i] = translation;
|
|
269
|
+
} else {
|
|
270
|
+
if (verbosityLevel >= 2) {
|
|
271
|
+
logger.warn(`Missing f${i} form in translation block for index ${responseIndex}`);
|
|
272
|
+
}
|
|
273
|
+
forms[i] = '';
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// Validate and auto-correct plural forms.
|
|
278
|
+
const { correctedForms, hasIssues } = validatePluralForms(forms, batch[batchIndex].msgid, pluralCount, responseIndex, logger, verbosityLevel);
|
|
279
|
+
|
|
280
|
+
if (hasIssues) {
|
|
281
|
+
validationStats.stringsWithPluralIssues++;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
result[batchIndex].msgstr = correctedForms;
|
|
285
|
+
} else if (hasFormTags && isSingularEntry) {
|
|
286
|
+
// AI incorrectly returned plural forms for a singular entry.
|
|
287
|
+
// Extract only form 0 and discard the rest.
|
|
288
|
+
const formRegex = /<f0(?=[\s">])[^>]*>(.*?)<\/f0(?=[\s">])[^>]*>/s;
|
|
289
|
+
const formMatch = block.match(formRegex);
|
|
290
|
+
|
|
291
|
+
if (formMatch) {
|
|
292
|
+
const translation = normalizeNbsp(decodeXmlEntities(formMatch[1]), batch[batchIndex].msgid);
|
|
293
|
+
|
|
294
|
+
result[batchIndex].msgstr = [translation];
|
|
295
|
+
}
|
|
296
|
+
} else {
|
|
297
|
+
const contentMatch = block.match(/<t[^>]*>(.*?)<\/t>/s);
|
|
298
|
+
|
|
299
|
+
if (contentMatch) {
|
|
300
|
+
const translation = normalizeNbsp(decodeXmlEntities(contentMatch[1]), batch[batchIndex].msgid);
|
|
301
|
+
|
|
302
|
+
// If this entry expects plural forms, validate the result
|
|
303
|
+
if (batch[batchIndex].msgid_plural) {
|
|
304
|
+
if (verbosityLevel >= 2) {
|
|
305
|
+
logger.warn(`Missing plural forms at index ${responseIndex} for "${batch[batchIndex].msgid.substring(0, 50)}...": ` + `Expected ${pluralCount} forms but received singular translation. Using single translation for form 0 only.`);
|
|
306
|
+
}
|
|
307
|
+
const { correctedForms, hasIssues } = validatePluralForms([translation], batch[batchIndex].msgid, pluralCount, responseIndex, logger, verbosityLevel);
|
|
308
|
+
|
|
309
|
+
if (hasIssues) {
|
|
310
|
+
validationStats.stringsWithPluralIssues++;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
result[batchIndex].msgstr = correctedForms;
|
|
314
|
+
} else {
|
|
315
|
+
result[batchIndex].msgstr = [translation];
|
|
316
|
+
}
|
|
317
|
+
} else {
|
|
318
|
+
if (verbosityLevel >= 2) {
|
|
319
|
+
logger.warn(`Could not extract translation from block for index ${responseIndex}`);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
// Post-process: reject translations where placeholders don't match the source.
|
|
326
|
+
for (let idx = 0; idx < result.length; idx++) {
|
|
327
|
+
const entry = batch[idx];
|
|
328
|
+
const singularPh = extractPlaceholders(entry.msgid);
|
|
329
|
+
const pluralPh = entry.msgid_plural ? extractPlaceholders(entry.msgid_plural) : singularPh;
|
|
330
|
+
|
|
331
|
+
for (let fi = 0; fi < result[idx].msgstr.length; fi++) {
|
|
332
|
+
const translation = result[idx].msgstr[fi];
|
|
333
|
+
|
|
334
|
+
if (!translation) {
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// Form 0 validates against singular, forms 1+ against plural.
|
|
339
|
+
// For plural strings, form 0 (singular) may legitimately drop %d/%d
|
|
340
|
+
// when the language uses a word like "one" instead of the number.
|
|
341
|
+
const expectedPh = fi === 0 ? singularPh : pluralPh;
|
|
342
|
+
const transPlaceholders = extractPlaceholders(translation);
|
|
343
|
+
|
|
344
|
+
let isValid = expectedPh === transPlaceholders;
|
|
345
|
+
|
|
346
|
+
if (!isValid && entry.msgid_plural && pluralCount > 1) {
|
|
347
|
+
// Plural forms that represent specific small counts may
|
|
348
|
+
// legitimately drop %d and use words instead:
|
|
349
|
+
// - Form 0 (zero/singular): "no items" or "one item"
|
|
350
|
+
// - Form 1 (one/singular in 6-form languages): "مراجعة واحدة"
|
|
351
|
+
// - Form 2 (two/dual in 6-form languages): "مراجعتان"
|
|
352
|
+
// Not allowed when pluralCount === 1 (Japanese, Chinese, Korean)
|
|
353
|
+
// because form 0 is the ONLY form and must retain all placeholders.
|
|
354
|
+
const isSmallCountForm = fi === 0 || (pluralCount === 6 && fi <= 2);
|
|
355
|
+
|
|
356
|
+
if (isSmallCountForm) {
|
|
357
|
+
// Allow dropping only numeric placeholders (%d, %f, %u and
|
|
358
|
+
// positional variants). String placeholders (%s, %1$s) must
|
|
359
|
+
// always be retained — they carry non-count data.
|
|
360
|
+
// NOTE: pluralCount === 6 only matches Arabic in our current
|
|
361
|
+
// locale map. If a non-Arabic 6-form language is added, revisit.
|
|
362
|
+
// Uses frequency maps (not Sets) to preserve duplicate placeholder counts.
|
|
363
|
+
const expectedArr = (expectedPh || '').split(',').filter(Boolean);
|
|
364
|
+
const transArr = (transPlaceholders || '').split(',').filter(Boolean);
|
|
365
|
+
|
|
366
|
+
const buildFreqMap = (arr) => {
|
|
367
|
+
const freq = {};
|
|
368
|
+
|
|
369
|
+
for (const p of arr) {
|
|
370
|
+
freq[p] = (freq[p] || 0) + 1;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
return freq;
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
const expectedFreq = buildFreqMap(expectedArr);
|
|
377
|
+
const transFreq = buildFreqMap(transArr);
|
|
378
|
+
|
|
379
|
+
// Find dropped placeholders (count-aware).
|
|
380
|
+
// A numeric placeholder can only be dropped entirely (all
|
|
381
|
+
// instances), not partially. "%d of %d" → dropping one %d
|
|
382
|
+
// but keeping the other breaks sprintf.
|
|
383
|
+
let allDropsValid = true;
|
|
384
|
+
let hasExtra = false;
|
|
385
|
+
|
|
386
|
+
for (const [ph, count] of Object.entries(expectedFreq)) {
|
|
387
|
+
const transCount = transFreq[ph] || 0;
|
|
388
|
+
|
|
389
|
+
if (transCount < count) {
|
|
390
|
+
const isNumeric = /^%(?:\d+\$)?[-+0 '#]*(?:\*|\d+)?(?:\.(?:\*|\d+))?[dfueEfFgGuxX]$/.test(ph);
|
|
391
|
+
|
|
392
|
+
if (!isNumeric || transCount !== 0) {
|
|
393
|
+
// Non-numeric dropped, or numeric partially dropped.
|
|
394
|
+
allDropsValid = false;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
for (const [ph, count] of Object.entries(transFreq)) {
|
|
400
|
+
if (count > (expectedFreq[ph] || 0)) {
|
|
401
|
+
hasExtra = true;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
isValid = allDropsValid && !hasExtra;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
if (!isValid) {
|
|
410
|
+
if (verbosityLevel >= 1) {
|
|
411
|
+
logger.warn(`Placeholder mismatch for "${entry.msgid.substring(0, 50)}..." [form ${fi}] — ` + `expected [${expectedPh}], got [${transPlaceholders}]. Blanking translation.`);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
result[idx].msgstr[fi] = '';
|
|
415
|
+
validationStats.stringsWithPluralIssues++;
|
|
416
|
+
validationStats.blankedStrings.push({
|
|
417
|
+
msgid: entry.msgid.substring(0, 100),
|
|
418
|
+
form: fi,
|
|
419
|
+
expected: expectedPh || 'none',
|
|
420
|
+
got: transPlaceholders || 'none',
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
return { translations: result, validationStats };
|
|
427
|
+
} catch (error) {
|
|
428
|
+
if (verbosityLevel >= 2) {
|
|
429
|
+
logger.warn(`Failed to parse XML response: ${error.message}`);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
return { translations: result, validationStats };
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* Extracts sorted printf-style placeholders from a string.
|
|
438
|
+
*
|
|
439
|
+
* @since 1.2.0
|
|
440
|
+
*
|
|
441
|
+
* @param {string} text - Text to extract from.
|
|
442
|
+
*
|
|
443
|
+
* @return {string} Comma-separated sorted placeholders.
|
|
444
|
+
*/
|
|
445
|
+
function extractPlaceholders(text) {
|
|
446
|
+
if (!text) {
|
|
447
|
+
return '';
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// Full PHP sprintf format: %[position$][flags][width][.precision]type
|
|
451
|
+
// First replace %% with a sentinel to avoid false matches, then extract.
|
|
452
|
+
const cleaned = text.replace(/%%/g, '\x00\x00');
|
|
453
|
+
|
|
454
|
+
return (cleaned.match(/%(?:\d+\$)?[-+0 '#]*(?:\*|\d+)?(?:\.(?:\*|\d+))?[bcdeEfFgGosuxX]/g) || []).sort().join(',');
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Decodes XML entities.
|
|
459
|
+
*
|
|
460
|
+
* @since 1.0.0
|
|
461
|
+
*
|
|
462
|
+
* @param {string} text - Text to decode.
|
|
463
|
+
*
|
|
464
|
+
* @return {string} Decoded text.
|
|
465
|
+
*/
|
|
466
|
+
function decodeXmlEntities(text) {
|
|
467
|
+
if (!text) {
|
|
468
|
+
return '';
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
return text
|
|
472
|
+
.replace(/</g, '<')
|
|
473
|
+
.replace(/>/g, '>')
|
|
474
|
+
.replace(/"/g, '"')
|
|
475
|
+
.replace(/'/g, "'")
|
|
476
|
+
.replace(/&/g, '&');
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* Normalizes non-breaking spaces (U+00A0) in a translation to match the
|
|
481
|
+
* source string's whitespace. LLMs sometimes produce nbsp where the source
|
|
482
|
+
* has regular spaces, which triggers GlotPress "missing spaces" warnings.
|
|
483
|
+
*
|
|
484
|
+
* Only normalizes leading/trailing whitespace — interior nbsp is preserved
|
|
485
|
+
* as it may be intentional (e.g., French punctuation spacing).
|
|
486
|
+
*
|
|
487
|
+
* @since 1.2.0
|
|
488
|
+
*
|
|
489
|
+
* @param {string} translation - Translated text.
|
|
490
|
+
* @param {string} source - Source text to match whitespace against.
|
|
491
|
+
*
|
|
492
|
+
* @return {string} Translation with leading/trailing nbsp normalized.
|
|
493
|
+
*/
|
|
494
|
+
function normalizeNbsp(translation, source) {
|
|
495
|
+
if (!translation || !translation.includes('\u00A0')) {
|
|
496
|
+
return translation;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
let result = translation;
|
|
500
|
+
|
|
501
|
+
const origLeading = source.match(/^(\s*)/)[1];
|
|
502
|
+
const origTrailing = source.match(/(\s*)$/)[1];
|
|
503
|
+
const transLeading = result.match(/^(\s*)/)[1];
|
|
504
|
+
const transTrailing = result.match(/(\s*)$/)[1];
|
|
505
|
+
|
|
506
|
+
if (origLeading && transLeading.includes('\u00A0')) {
|
|
507
|
+
result = transLeading.replace(/\u00A0/g, ' ') + result.slice(transLeading.length);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
if (origTrailing && transTrailing.includes('\u00A0')) {
|
|
511
|
+
result = result.slice(0, -transTrailing.length) + transTrailing.replace(/\u00A0/g, ' ');
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
return result;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* Escapes XML attribute values.
|
|
519
|
+
*
|
|
520
|
+
* @since 1.0.0
|
|
521
|
+
*
|
|
522
|
+
* @param {string} text - Text to escape.
|
|
523
|
+
*
|
|
524
|
+
* @return {string} Escaped text.
|
|
525
|
+
*/
|
|
526
|
+
function escapeXmlAttribute(text) {
|
|
527
|
+
if (!text) {
|
|
528
|
+
return '';
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
return text.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
|
|
532
|
+
}
|