@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,1031 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import { Listr } from 'listr2';
|
|
3
|
+
import { LanguageProcessor } from '../processors/languageProcessor.js';
|
|
4
|
+
import { LogCollector } from '../logging/index.js';
|
|
5
|
+
import { printTranslationRunSummary, buildResultParts, buildLanguageResultLine } from '../utils/reportingUtils.js';
|
|
6
|
+
import { defaultChalk } from '../utils/colorUtils.js';
|
|
7
|
+
import { formatNumber } from '../utils/costCalculations.js';
|
|
8
|
+
import { ProviderFactory } from '../providers/ProviderFactory.js';
|
|
9
|
+
import { ReporterFactory } from '../reporters/ReporterFactory.js';
|
|
10
|
+
import { getFileNamingLocale } from '../utils/languageMapping.js';
|
|
11
|
+
import { formatCount } from '../utils/pluralization.js';
|
|
12
|
+
import { getTotalValidationIssues, formatValidationBreakdown } from '../utils/validationStats.js';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Main orchestrator class that coordinates the translation workflow.
|
|
16
|
+
* Manages AI provider initialization, language processing tasks,
|
|
17
|
+
* parallel execution, and result aggregation.
|
|
18
|
+
*
|
|
19
|
+
* @since 1.0.0
|
|
20
|
+
*/
|
|
21
|
+
export class TranslationOrchestrator {
|
|
22
|
+
/**
|
|
23
|
+
* Creates a new TranslationOrchestrator instance.
|
|
24
|
+
*
|
|
25
|
+
* @since 1.0.0
|
|
26
|
+
*
|
|
27
|
+
* @param {Object} config - Configuration object containing all translation settings.
|
|
28
|
+
* @param {Object} mainLogger - Main logger instance for orchestrator messages.
|
|
29
|
+
*/
|
|
30
|
+
constructor(config, mainLogger) {
|
|
31
|
+
this.config = config;
|
|
32
|
+
this.mainLogger = mainLogger;
|
|
33
|
+
this.logCollector = new LogCollector();
|
|
34
|
+
this.provider = null;
|
|
35
|
+
this.startTime = Date.now();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Initializes the orchestrator by setting up the AI provider.
|
|
40
|
+
* Must be called before processing languages.
|
|
41
|
+
*
|
|
42
|
+
* @since 1.0.0
|
|
43
|
+
*
|
|
44
|
+
* @return {Promise<void>} Resolves when initialization is complete.
|
|
45
|
+
*/
|
|
46
|
+
async initialize() {
|
|
47
|
+
this.mainLogger.info(`Initializing translation orchestrator…`);
|
|
48
|
+
|
|
49
|
+
await this._initializeProvider();
|
|
50
|
+
|
|
51
|
+
this.mainLogger.info('Orchestrator initialized successfully');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Processes all target languages in parallel using Listr task runner.
|
|
56
|
+
* Coordinates language processing, handles errors, and generates summary reports.
|
|
57
|
+
* When maxStringsTotal is set, processes languages sequentially to enforce global limit.
|
|
58
|
+
*
|
|
59
|
+
* @since 1.0.0
|
|
60
|
+
*
|
|
61
|
+
* @return {Promise<number>} Exit code (0 for success, 1 for failure).
|
|
62
|
+
*/
|
|
63
|
+
async processAllLanguages() {
|
|
64
|
+
this.mainLogger.info(`Starting translation process for ${formatCount(this.config.targetLanguages.length, 'language')}: ${this.config.targetLanguages.join(', ')}`);
|
|
65
|
+
this.mainLogger.info(`Max concurrent jobs: ${this.config.concurrentJobs}`);
|
|
66
|
+
this.mainLogger.info(`Output directory: ${path.resolve(this.config.outputDir)}`);
|
|
67
|
+
|
|
68
|
+
if (this.config.poFilePrefix) {
|
|
69
|
+
this.mainLogger.info(`Using .po file prefix: "${this.config.poFilePrefix}"`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (this.config.poHeaderTemplatePath) {
|
|
73
|
+
this.mainLogger.info(`Using PO header template: ${this.config.poHeaderTemplatePath}`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (this.config.maxStringsTotal) {
|
|
77
|
+
this.mainLogger.info(`String limit: ${formatNumber(this.config.maxStringsTotal)} total across all languages (processing sequentially)`);
|
|
78
|
+
|
|
79
|
+
return await this._processLanguagesSequentially();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (this.config.maxCost) {
|
|
83
|
+
this.mainLogger.info(`Cost limit: $${this.config.maxCost.toFixed(4)} total across all languages (processing sequentially)`);
|
|
84
|
+
|
|
85
|
+
return await this._processLanguagesWithCostLimit();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const tasks = this._createLanguageTasks();
|
|
89
|
+
const listr = this._createListr(tasks);
|
|
90
|
+
const allLanguageStats = [];
|
|
91
|
+
let exitCode = 1;
|
|
92
|
+
|
|
93
|
+
try {
|
|
94
|
+
this.mainLogger.info('Starting language processing tasks…');
|
|
95
|
+
|
|
96
|
+
const context = await listr.run();
|
|
97
|
+
|
|
98
|
+
if (context && context.results) {
|
|
99
|
+
allLanguageStats.push(...context.results);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (!(this.config.outputFormat === 'json' && !this.config.outputFile)) {
|
|
103
|
+
this.mainLogger.success('All language processing tasks finished.');
|
|
104
|
+
}
|
|
105
|
+
} catch (error) {
|
|
106
|
+
this.mainLogger.error('An unexpected error occurred during task execution:', error.message);
|
|
107
|
+
|
|
108
|
+
if (error.context && error.context.results) {
|
|
109
|
+
allLanguageStats.push(...error.context.results.filter((r) => !allLanguageStats.find((ar) => ar.language === r.language)));
|
|
110
|
+
}
|
|
111
|
+
} finally {
|
|
112
|
+
await this._printResults(allLanguageStats);
|
|
113
|
+
|
|
114
|
+
exitCode = this._determineExitCode(allLanguageStats);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return exitCode;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Initializes the AI provider using the ProviderFactory.
|
|
122
|
+
* Validates configuration and creates the appropriate provider instance.
|
|
123
|
+
*
|
|
124
|
+
* @private
|
|
125
|
+
*
|
|
126
|
+
* @since 1.0.0
|
|
127
|
+
*
|
|
128
|
+
* @throws {Error} If provider creation or validation fails.
|
|
129
|
+
*/
|
|
130
|
+
async _initializeProvider() {
|
|
131
|
+
try {
|
|
132
|
+
this.provider = await ProviderFactory.createAndValidateProvider(this.config, this.mainLogger);
|
|
133
|
+
|
|
134
|
+
if (this.config.dryRun) {
|
|
135
|
+
this.mainLogger.info('Dry run mode: provider initialized for cost estimation');
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
this.mainLogger.info(`${this.config.provider} provider initialized`);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
throw new Error(`Failed to initialize provider: ${error.message}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Processes languages sequentially when a global string limit is set.
|
|
147
|
+
* Uses Listr with concurrency=1 to maintain the same UI/UX as concurrent processing.
|
|
148
|
+
*
|
|
149
|
+
* @private
|
|
150
|
+
*
|
|
151
|
+
* @since 1.0.0
|
|
152
|
+
*
|
|
153
|
+
* @return {Promise<number>} Exit code (0 for success, 1 for failure).
|
|
154
|
+
*/
|
|
155
|
+
async _processLanguagesSequentially() {
|
|
156
|
+
const allLanguageStats = [];
|
|
157
|
+
const skippedLanguages = [];
|
|
158
|
+
const globalLimit = this.config.maxStringsTotal;
|
|
159
|
+
let totalStringsProcessed = 0;
|
|
160
|
+
|
|
161
|
+
this.mainLogger.info('Starting sequential processing…');
|
|
162
|
+
|
|
163
|
+
const sequentialTasks = this._createSequentialTasks(globalLimit);
|
|
164
|
+
const listr = this._createSequentialListr(sequentialTasks);
|
|
165
|
+
let exitCode = 1;
|
|
166
|
+
|
|
167
|
+
try {
|
|
168
|
+
const context = await listr.run();
|
|
169
|
+
|
|
170
|
+
if (context && context.results) {
|
|
171
|
+
allLanguageStats.push(...context.results);
|
|
172
|
+
|
|
173
|
+
totalStringsProcessed = context.totalStringsProcessed || 0;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (context && context.skippedLanguages) {
|
|
177
|
+
skippedLanguages.push(...context.skippedLanguages);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
this._logStringLimitedCompletion(totalStringsProcessed, globalLimit, skippedLanguages);
|
|
181
|
+
} catch (error) {
|
|
182
|
+
this.mainLogger.error('An unexpected error occurred during sequential task execution:', error.message);
|
|
183
|
+
|
|
184
|
+
if (error.context && error.context.results) {
|
|
185
|
+
allLanguageStats.push(...error.context.results.filter((r) => !allLanguageStats.find((ar) => ar.language === r.language)));
|
|
186
|
+
}
|
|
187
|
+
} finally {
|
|
188
|
+
await this._printResults(allLanguageStats);
|
|
189
|
+
|
|
190
|
+
exitCode = this._determineExitCode(allLanguageStats);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return exitCode;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Creates sequential task definitions for global string limit processing.
|
|
198
|
+
*
|
|
199
|
+
* @private
|
|
200
|
+
*
|
|
201
|
+
* @since 1.0.0
|
|
202
|
+
*
|
|
203
|
+
* @param {number} globalLimit - Global string limit.
|
|
204
|
+
*
|
|
205
|
+
* @return {Array} Array of sequential task objects.
|
|
206
|
+
*/
|
|
207
|
+
_createSequentialTasks(globalLimit) {
|
|
208
|
+
const sequentialTasks = [];
|
|
209
|
+
|
|
210
|
+
for (let i = 0; i < this.config.targetLanguages.length; i++) {
|
|
211
|
+
const language = this.config.targetLanguages[i];
|
|
212
|
+
|
|
213
|
+
sequentialTasks.push({
|
|
214
|
+
title: `Queued translation for ${language}`,
|
|
215
|
+
task: async (ctx, task) => {
|
|
216
|
+
const currentTotalProcessed = ctx.totalStringsProcessed || 0;
|
|
217
|
+
const remainingStrings = globalLimit - currentTotalProcessed;
|
|
218
|
+
|
|
219
|
+
if (remainingStrings <= 0) {
|
|
220
|
+
this._handleSkippedLanguage(ctx, language, globalLimit, task);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
await this._processSequentialLanguage(language, i, remainingStrings, ctx, task);
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
return sequentialTasks;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Handles a language that needs to be skipped due to global limit.
|
|
234
|
+
*
|
|
235
|
+
* @private
|
|
236
|
+
*
|
|
237
|
+
* @since 1.0.0
|
|
238
|
+
*
|
|
239
|
+
* @param {Object} ctx - Task context.
|
|
240
|
+
* @param {string} language - Language code.
|
|
241
|
+
* @param {number} globalLimit - Global string limit.
|
|
242
|
+
* @param {Object} task - Task object.
|
|
243
|
+
*/
|
|
244
|
+
_handleSkippedLanguage(ctx, language, globalLimit, task) {
|
|
245
|
+
ctx.skippedLanguages = ctx.skippedLanguages || [];
|
|
246
|
+
|
|
247
|
+
if (!ctx.skippedLanguages.includes(language)) {
|
|
248
|
+
ctx.skippedLanguages.push(language);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
task.title = `Skipped ${language}: Global limit of ${formatNumber(globalLimit)} strings reached`;
|
|
252
|
+
task.skip(`Skipped ${language} - Global limit reached (${formatNumber(globalLimit)} strings)`);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Processes a single language in sequential mode with global string limit tracking.
|
|
257
|
+
*
|
|
258
|
+
* @private
|
|
259
|
+
*
|
|
260
|
+
* @since 1.0.0
|
|
261
|
+
*
|
|
262
|
+
* @param {string} language - Language code to process.
|
|
263
|
+
* @param {number} index - Language index in the processing order.
|
|
264
|
+
* @param {number} remainingStrings - Number of strings remaining in global limit.
|
|
265
|
+
* @param {Object} ctx - Task context for sharing state.
|
|
266
|
+
* @param {Object} task - Task object for updating progress.
|
|
267
|
+
*
|
|
268
|
+
* @return {Promise<Object>} Language processing statistics.
|
|
269
|
+
*/
|
|
270
|
+
async _processSequentialLanguage(language, index, remainingStrings, ctx, task) {
|
|
271
|
+
const startTime = Date.now();
|
|
272
|
+
|
|
273
|
+
try {
|
|
274
|
+
const languageLogger = this.logCollector.addLanguageLogger(language);
|
|
275
|
+
|
|
276
|
+
// Override maxStrings for this language to respect global limit.
|
|
277
|
+
const languageConfig = {
|
|
278
|
+
...this.config,
|
|
279
|
+
maxStrings: Math.min(this.config.maxStrings || Infinity, remainingStrings),
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
// If there's also a cost limit, calculate remaining budget and pass it.
|
|
283
|
+
if (this.config.maxCost) {
|
|
284
|
+
const totalCostSoFar = (ctx.results || []).reduce((sum, stat) => sum + (stat.costData?.totalCost || 0), 0);
|
|
285
|
+
const remainingBudget = this.config.maxCost - totalCostSoFar;
|
|
286
|
+
|
|
287
|
+
// Use a smarter threshold for small budgets.
|
|
288
|
+
// For budgets < $0.001, use a smaller absolute threshold
|
|
289
|
+
// For larger budgets, use the original threshold.
|
|
290
|
+
const costThreshold = this.config.maxCost < 0.001 ? 0.00002 : 0.0001;
|
|
291
|
+
|
|
292
|
+
if (remainingBudget <= costThreshold) {
|
|
293
|
+
// Cost limit reached, create stats entry for this language
|
|
294
|
+
const costLimitedStats = {
|
|
295
|
+
language,
|
|
296
|
+
totalStringsInPot: 0,
|
|
297
|
+
mergedFromExisting: 0,
|
|
298
|
+
translatedInRun: 0,
|
|
299
|
+
failedInRun: 0,
|
|
300
|
+
skippedDueToBudget: 0,
|
|
301
|
+
skippedDueToLimits: 0,
|
|
302
|
+
alreadyTranslated: 0,
|
|
303
|
+
method: 'cost_limited',
|
|
304
|
+
outputFile: this._getOutputFilePath(language),
|
|
305
|
+
costData: { totalCost: 0, totalTokens: 0 },
|
|
306
|
+
error: null,
|
|
307
|
+
executionTimeMs: 0,
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
ctx.results = ctx.results || [];
|
|
311
|
+
ctx.results.push(costLimitedStats);
|
|
312
|
+
|
|
313
|
+
ctx.skippedLanguages = ctx.skippedLanguages || [];
|
|
314
|
+
if (!ctx.skippedLanguages.includes(language)) {
|
|
315
|
+
ctx.skippedLanguages.push(language);
|
|
316
|
+
}
|
|
317
|
+
task.title = `Skipped ${language}: Cost limit of $${this.config.maxCost.toFixed(4)} reached`;
|
|
318
|
+
task.skip(`Skipped ${language} - Cost limit reached ($${this.config.maxCost.toFixed(4)})`);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
languageConfig.maxCostRemaining = remainingBudget;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const processor = new LanguageProcessor(languageConfig, this.provider, languageLogger);
|
|
326
|
+
|
|
327
|
+
const stats = await processor.processLanguage(language, (progressText) => {
|
|
328
|
+
task.title = progressText;
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
const endTime = Date.now();
|
|
332
|
+
const executionTimeMs = endTime - startTime;
|
|
333
|
+
|
|
334
|
+
// Add execution time to stats.
|
|
335
|
+
stats.executionTimeMs = executionTimeMs;
|
|
336
|
+
|
|
337
|
+
ctx.results = ctx.results || [];
|
|
338
|
+
ctx.results.push(stats);
|
|
339
|
+
|
|
340
|
+
// Update global tracking.
|
|
341
|
+
const stringsProcessed = stats.translatedInRun || 0;
|
|
342
|
+
|
|
343
|
+
ctx.totalStringsProcessed = (ctx.totalStringsProcessed || 0) + stringsProcessed;
|
|
344
|
+
|
|
345
|
+
this._updateSequentialTaskTitle(task, language, stats);
|
|
346
|
+
this._logValidationWarnings(language, stats);
|
|
347
|
+
|
|
348
|
+
return stats;
|
|
349
|
+
} catch (error) {
|
|
350
|
+
const endTime = Date.now();
|
|
351
|
+
const executionTimeMs = endTime - startTime;
|
|
352
|
+
|
|
353
|
+
this._handleSequentialTaskError(ctx, language, error, task, executionTimeMs);
|
|
354
|
+
throw error;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Updates the task title for a completed sequential language task.
|
|
360
|
+
*
|
|
361
|
+
* @private
|
|
362
|
+
*
|
|
363
|
+
* @since 1.0.0
|
|
364
|
+
*
|
|
365
|
+
* @param {Object} task - Task object.
|
|
366
|
+
* @param {string} language - Language code.
|
|
367
|
+
* @param {Object} stats - Language processing statistics.
|
|
368
|
+
*/
|
|
369
|
+
_updateSequentialTaskTitle(task, language, stats) {
|
|
370
|
+
// Use the shared buildLanguageResultLine function for consistent formatting.
|
|
371
|
+
const line = buildLanguageResultLine(stats, {
|
|
372
|
+
includeLanguageCode: true,
|
|
373
|
+
styled: false,
|
|
374
|
+
prefix: 'Finished',
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
task.title = line;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Handles errors during sequential language processing.
|
|
382
|
+
*
|
|
383
|
+
* @private
|
|
384
|
+
*
|
|
385
|
+
* @since 1.0.0
|
|
386
|
+
*
|
|
387
|
+
* @param {Object} ctx - Task context.
|
|
388
|
+
* @param {string} language - Language code.
|
|
389
|
+
* @param {Error} error - Error that occurred.
|
|
390
|
+
* @param {Object} task - Task object.
|
|
391
|
+
* @param {number} executionTimeMs - Execution time in milliseconds.
|
|
392
|
+
*/
|
|
393
|
+
_handleSequentialTaskError(ctx, language, error, task, executionTimeMs = 0) {
|
|
394
|
+
task.title = `Error processing ${language}: ${error.message.substring(0, 100)}…`;
|
|
395
|
+
|
|
396
|
+
ctx.results = ctx.results || [];
|
|
397
|
+
ctx.results.push({
|
|
398
|
+
language,
|
|
399
|
+
error: error.message,
|
|
400
|
+
logs: this.logCollector.getLogsFor(language),
|
|
401
|
+
outputFile: path.join(this.config.outputDir, `${this.config.poFilePrefix}${getFileNamingLocale(language, this.config.localeFormat)}.po`),
|
|
402
|
+
translatedInRun: 0,
|
|
403
|
+
failedInRun: 0,
|
|
404
|
+
executionTimeMs,
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Creates a Listr instance for sequential processing.
|
|
410
|
+
*
|
|
411
|
+
* @private
|
|
412
|
+
*
|
|
413
|
+
* @since 1.0.0
|
|
414
|
+
*
|
|
415
|
+
* @param {Array} sequentialTasks - Array of sequential task definitions.
|
|
416
|
+
*
|
|
417
|
+
* @return {Listr} Configured Listr instance.
|
|
418
|
+
*/
|
|
419
|
+
_createSequentialListr(sequentialTasks) {
|
|
420
|
+
return new Listr(sequentialTasks, {
|
|
421
|
+
concurrent: 1,
|
|
422
|
+
exitOnError: false,
|
|
423
|
+
renderer: this._getListrRenderer(),
|
|
424
|
+
rendererOptions: {
|
|
425
|
+
showTimer: this.config.verboseLevel >= 1,
|
|
426
|
+
collapseErrors: false,
|
|
427
|
+
formatOutput: 'wrap',
|
|
428
|
+
},
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Logs completion message for sequential processing.
|
|
434
|
+
*
|
|
435
|
+
* @private
|
|
436
|
+
*
|
|
437
|
+
* @since 1.0.0
|
|
438
|
+
*
|
|
439
|
+
* @param {number} totalStringsProcessed - Total strings processed.
|
|
440
|
+
* @param {number} globalLimit - Global string limit.
|
|
441
|
+
* @param {Array} skippedLanguages - Array of skipped language codes.
|
|
442
|
+
*/
|
|
443
|
+
_logStringLimitedCompletion(totalStringsProcessed, globalLimit, skippedLanguages) {
|
|
444
|
+
// Don't log completion message when outputting JSON to stdout to keep output clean.
|
|
445
|
+
if (this.config.outputFormat === 'json' && !this.config.outputFile) {
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
let completionMessage = `Sequential processing completed. Total strings processed: ${formatNumber(totalStringsProcessed)}/${formatNumber(globalLimit)}`;
|
|
450
|
+
|
|
451
|
+
if (skippedLanguages.length > 0) {
|
|
452
|
+
completionMessage += `. Skipped ${formatCount(skippedLanguages.length, 'language')} due to global limit: ${skippedLanguages.join(', ')}`;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
this.mainLogger.success(completionMessage);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* Processes languages sequentially when a cost limit is set.
|
|
460
|
+
* Tracks total cost across all languages and stops when limit is reached.
|
|
461
|
+
*
|
|
462
|
+
* @private
|
|
463
|
+
*
|
|
464
|
+
* @since 1.0.0
|
|
465
|
+
*
|
|
466
|
+
* @return {Promise<number>} Exit code (0 for success, 1 for failure).
|
|
467
|
+
*/
|
|
468
|
+
async _processLanguagesWithCostLimit() {
|
|
469
|
+
const allLanguageStats = [];
|
|
470
|
+
let totalCostAccumulated = 0;
|
|
471
|
+
|
|
472
|
+
this.mainLogger.info('Starting sequential processing…');
|
|
473
|
+
|
|
474
|
+
for (let i = 0; i < this.config.targetLanguages.length; i++) {
|
|
475
|
+
const language = this.config.targetLanguages[i];
|
|
476
|
+
const remainingBudget = this.config.maxCost - totalCostAccumulated;
|
|
477
|
+
|
|
478
|
+
// Use a smarter threshold for small budgets.
|
|
479
|
+
// For budgets < $0.001, use a smaller absolute threshold
|
|
480
|
+
// For larger budgets, use the original threshold.
|
|
481
|
+
const costThreshold = this.config.maxCost < 0.001 ? 0.00002 : 0.0001;
|
|
482
|
+
|
|
483
|
+
if (remainingBudget <= costThreshold) {
|
|
484
|
+
// Create stats entries for skipped languages due to cost limit.
|
|
485
|
+
for (let j = i; j < this.config.targetLanguages.length; j++) {
|
|
486
|
+
const skippedLanguage = this.config.targetLanguages[j];
|
|
487
|
+
const skippedStats = {
|
|
488
|
+
language: skippedLanguage,
|
|
489
|
+
totalStringsInPot: 0,
|
|
490
|
+
mergedFromExisting: 0,
|
|
491
|
+
translatedInRun: 0,
|
|
492
|
+
failedInRun: 0,
|
|
493
|
+
skippedDueToBudget: 0,
|
|
494
|
+
skippedDueToLimits: 0,
|
|
495
|
+
alreadyTranslated: 0,
|
|
496
|
+
method: 'cost_limited',
|
|
497
|
+
outputFile: this._getOutputFilePath(skippedLanguage),
|
|
498
|
+
costData: { totalCost: 0, totalTokens: 0 },
|
|
499
|
+
error: null,
|
|
500
|
+
executionTimeMs: 0,
|
|
501
|
+
};
|
|
502
|
+
allLanguageStats.push(skippedStats);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
this._handleCostLimitReached(i);
|
|
506
|
+
break;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
this.mainLogger.info(`Processing ${language} (${i + 1}/${this.config.targetLanguages.length}) - $${remainingBudget.toFixed(4)} remaining in budget`);
|
|
510
|
+
|
|
511
|
+
try {
|
|
512
|
+
const stats = await this._processCostLimitedLanguage(language, remainingBudget);
|
|
513
|
+
|
|
514
|
+
allLanguageStats.push(stats);
|
|
515
|
+
|
|
516
|
+
const languageCost = stats.costData?.totalCost || 0;
|
|
517
|
+
|
|
518
|
+
totalCostAccumulated += languageCost;
|
|
519
|
+
|
|
520
|
+
this._logCostLimitedLanguageResult(language, stats, languageCost, totalCostAccumulated);
|
|
521
|
+
|
|
522
|
+
if (this._shouldStopDueToCostLimit(totalCostAccumulated, i)) {
|
|
523
|
+
// Create stats entries for remaining skipped languages.
|
|
524
|
+
for (let j = i + 1; j < this.config.targetLanguages.length; j++) {
|
|
525
|
+
const skippedLanguage = this.config.targetLanguages[j];
|
|
526
|
+
const skippedStats = {
|
|
527
|
+
language: skippedLanguage,
|
|
528
|
+
totalStringsInPot: 0,
|
|
529
|
+
mergedFromExisting: 0,
|
|
530
|
+
translatedInRun: 0,
|
|
531
|
+
failedInRun: 0,
|
|
532
|
+
skippedDueToBudget: 0,
|
|
533
|
+
skippedDueToLimits: 0,
|
|
534
|
+
alreadyTranslated: 0,
|
|
535
|
+
method: 'cost_limited',
|
|
536
|
+
outputFile: this._getOutputFilePath(skippedLanguage),
|
|
537
|
+
costData: { totalCost: 0, totalTokens: 0 },
|
|
538
|
+
error: null,
|
|
539
|
+
executionTimeMs: 0,
|
|
540
|
+
};
|
|
541
|
+
allLanguageStats.push(skippedStats);
|
|
542
|
+
}
|
|
543
|
+
break;
|
|
544
|
+
}
|
|
545
|
+
} catch (error) {
|
|
546
|
+
this._handleCostLimitedLanguageError(language, error, allLanguageStats);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
this._logCostLimitedCompletion(totalCostAccumulated);
|
|
551
|
+
|
|
552
|
+
await this._printResults(allLanguageStats);
|
|
553
|
+
|
|
554
|
+
return this._determineExitCode(allLanguageStats);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Handles when the cost limit is reached.
|
|
559
|
+
*
|
|
560
|
+
* @private
|
|
561
|
+
*
|
|
562
|
+
* @since 1.0.0
|
|
563
|
+
*
|
|
564
|
+
* @param {number} currentIndex - Current language index.
|
|
565
|
+
*/
|
|
566
|
+
_handleCostLimitReached(currentIndex) {
|
|
567
|
+
this.mainLogger.info(`Cost limit of $${this.config.maxCost.toFixed(4)} reached. Skipping remaining languages: ${this.config.targetLanguages.slice(currentIndex).join(', ')}`);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* Processes a single language with cost limit tracking.
|
|
572
|
+
*
|
|
573
|
+
* @private
|
|
574
|
+
*
|
|
575
|
+
* @since 1.0.0
|
|
576
|
+
*
|
|
577
|
+
* @param {string} language - Language code to process.
|
|
578
|
+
* @param {number} remainingBudget - Remaining cost budget.
|
|
579
|
+
*
|
|
580
|
+
* @return {Promise<Object>} Language processing statistics.
|
|
581
|
+
*/
|
|
582
|
+
async _processCostLimitedLanguage(language, remainingBudget) {
|
|
583
|
+
const startTime = Date.now();
|
|
584
|
+
|
|
585
|
+
try {
|
|
586
|
+
const languageLogger = this.logCollector.addLanguageLogger(language);
|
|
587
|
+
|
|
588
|
+
// Create a copy of the config with the remaining budget set for this language.
|
|
589
|
+
const configWithBudget = { ...this.config, maxCostRemaining: remainingBudget };
|
|
590
|
+
const processor = new LanguageProcessor(configWithBudget, this.provider, languageLogger);
|
|
591
|
+
|
|
592
|
+
const stats = await processor.processLanguage(language, (progressText) => {
|
|
593
|
+
this.mainLogger.info(progressText);
|
|
594
|
+
});
|
|
595
|
+
|
|
596
|
+
const endTime = Date.now();
|
|
597
|
+
const executionTimeMs = endTime - startTime;
|
|
598
|
+
|
|
599
|
+
// Add execution time to stats.
|
|
600
|
+
stats.executionTimeMs = executionTimeMs;
|
|
601
|
+
|
|
602
|
+
return stats;
|
|
603
|
+
} catch (error) {
|
|
604
|
+
const endTime = Date.now();
|
|
605
|
+
const executionTimeMs = endTime - startTime;
|
|
606
|
+
|
|
607
|
+
// Create error stats with execution time.
|
|
608
|
+
return {
|
|
609
|
+
language,
|
|
610
|
+
error: error.message,
|
|
611
|
+
logs: this.logCollector.getLogsFor(language),
|
|
612
|
+
outputFile: path.join(this.config.outputDir, `${this.config.poFilePrefix}${getFileNamingLocale(language, this.config.localeFormat)}.po`),
|
|
613
|
+
translatedInRun: 0,
|
|
614
|
+
failedInRun: 0,
|
|
615
|
+
executionTimeMs,
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/**
|
|
621
|
+
* Logs the result of processing a cost-limited language.
|
|
622
|
+
*
|
|
623
|
+
* @private
|
|
624
|
+
*
|
|
625
|
+
* @since 1.0.0
|
|
626
|
+
*
|
|
627
|
+
* @param {string} language - Language code.
|
|
628
|
+
* @param {Object} stats - Language processing statistics.
|
|
629
|
+
* @param {number} languageCost - Cost for this language.
|
|
630
|
+
* @param {number} totalCostAccumulated - Total accumulated cost.
|
|
631
|
+
*/
|
|
632
|
+
_logCostLimitedLanguageResult(language, stats, languageCost, totalCostAccumulated) {
|
|
633
|
+
const costDisplay = this.config.dryRun ? 'Cost (estimated)' : 'Cost';
|
|
634
|
+
const resultParts = buildResultParts(stats);
|
|
635
|
+
|
|
636
|
+
this.mainLogger.info(`✔ Finished ${language}: ${resultParts.join(', ')}. ${costDisplay}: $${languageCost.toFixed(4)}. Total ${this.config.dryRun ? 'estimated ' : ''}cost: $${totalCostAccumulated.toFixed(4)}/$${this.config.maxCost.toFixed(4)}`);
|
|
637
|
+
|
|
638
|
+
this._logValidationWarnings(language, stats);
|
|
639
|
+
|
|
640
|
+
if (stats.skippedDueToBudget > 0 && languageCost === 0) {
|
|
641
|
+
const remainingBudget = this.config.maxCost - totalCostAccumulated;
|
|
642
|
+
|
|
643
|
+
this.mainLogger.info(`💰 ${language}: ${formatNumber(stats.skippedDueToBudget)} strings skipped due to budget limit (remaining: $${remainingBudget.toFixed(4)})`);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* Determines if processing should stop due to cost limit.
|
|
649
|
+
*
|
|
650
|
+
* @private
|
|
651
|
+
*
|
|
652
|
+
* @since 1.0.0
|
|
653
|
+
*
|
|
654
|
+
* @param {number} totalCostAccumulated - Total accumulated cost.
|
|
655
|
+
* @param {number} currentIndex - Current language index.
|
|
656
|
+
*
|
|
657
|
+
* @return {boolean} True if processing should stop.
|
|
658
|
+
*/
|
|
659
|
+
_shouldStopDueToCostLimit(totalCostAccumulated, currentIndex) {
|
|
660
|
+
if (totalCostAccumulated < this.config.maxCost * 0.95) {
|
|
661
|
+
return false;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const limitType = this.config.dryRun ? 'estimated cost limit' : 'cost limit';
|
|
665
|
+
const roundedTotalCost = parseFloat(totalCostAccumulated.toFixed(4));
|
|
666
|
+
const roundedMaxCost = parseFloat(this.config.maxCost.toFixed(4));
|
|
667
|
+
const percentage = ((roundedTotalCost / roundedMaxCost) * 100).toFixed(1);
|
|
668
|
+
|
|
669
|
+
this.mainLogger.info(`Approaching ${limitType} (${percentage}% used). ${this.config.dryRun ? 'Would stop' : 'Stopping'} to avoid budget overrun.`);
|
|
670
|
+
|
|
671
|
+
if (currentIndex + 1 < this.config.targetLanguages.length) {
|
|
672
|
+
const skipMessage = this.config.dryRun ? 'Would skip' : 'Skipping';
|
|
673
|
+
|
|
674
|
+
this.mainLogger.info(`${skipMessage} remaining languages: ${this.config.targetLanguages.slice(currentIndex + 1).join(', ')}`);
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
return true;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* Handles errors during cost-limited language processing.
|
|
682
|
+
*
|
|
683
|
+
* @private
|
|
684
|
+
*
|
|
685
|
+
* @since 1.0.0
|
|
686
|
+
*
|
|
687
|
+
* @param {string} language - Language code.
|
|
688
|
+
* @param {Error} error - Error that occurred.
|
|
689
|
+
* @param {Array} allLanguageStats - Array to add error stats to.
|
|
690
|
+
*/
|
|
691
|
+
_handleCostLimitedLanguageError(language, error, allLanguageStats) {
|
|
692
|
+
this.mainLogger.error(`Error processing ${language}: ${error.message}`);
|
|
693
|
+
|
|
694
|
+
allLanguageStats.push({
|
|
695
|
+
language,
|
|
696
|
+
error: error.message,
|
|
697
|
+
logs: this.logCollector.getLogsFor(language),
|
|
698
|
+
outputFile: path.join(this.config.outputDir, `${this.config.poFilePrefix}${getFileNamingLocale(language, this.config.localeFormat)}.po`),
|
|
699
|
+
translatedInRun: 0,
|
|
700
|
+
failedInRun: 0,
|
|
701
|
+
costData: { totalCost: 0, totalTokens: 0 },
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* Logs completion message for cost-limited processing.
|
|
707
|
+
*
|
|
708
|
+
* @private
|
|
709
|
+
*
|
|
710
|
+
* @since 1.0.0
|
|
711
|
+
*
|
|
712
|
+
* @param {number} totalCostAccumulated - Total accumulated cost.
|
|
713
|
+
*/
|
|
714
|
+
_logCostLimitedCompletion(totalCostAccumulated) {
|
|
715
|
+
// Don't log completion message when outputting JSON to stdout to keep output clean.
|
|
716
|
+
if (this.config.outputFormat === 'json' && !this.config.outputFile) {
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
const roundedTotalCost = parseFloat(totalCostAccumulated.toFixed(4));
|
|
721
|
+
const roundedMaxCost = parseFloat(this.config.maxCost.toFixed(4));
|
|
722
|
+
const percentage = ((roundedTotalCost / roundedMaxCost) * 100).toFixed(1);
|
|
723
|
+
|
|
724
|
+
this.mainLogger.success(`Cost-limited processing completed. Total ${this.config.dryRun ? 'estimated ' : ''}cost: $${roundedTotalCost.toFixed(4)}/$${roundedMaxCost.toFixed(4)} (${percentage}% of budget ${this.config.dryRun ? 'would be ' : ''}used)`);
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* Creates task definitions for processing each target language.
|
|
729
|
+
* Each task handles language processing, error handling, and result collection.
|
|
730
|
+
*
|
|
731
|
+
* @private
|
|
732
|
+
*
|
|
733
|
+
* @since 1.0.0
|
|
734
|
+
*
|
|
735
|
+
* @return {Array} Array of task definitions for Listr.
|
|
736
|
+
*/
|
|
737
|
+
_createLanguageTasks() {
|
|
738
|
+
return this.config.targetLanguages.map((language) => ({
|
|
739
|
+
title: `Queued translation for ${language}`,
|
|
740
|
+
task: async (ctx, task) => {
|
|
741
|
+
const startTime = Date.now();
|
|
742
|
+
|
|
743
|
+
this.mainLogger.info(`Processing ${language}…`);
|
|
744
|
+
|
|
745
|
+
try {
|
|
746
|
+
const languageLogger = this.logCollector.addLanguageLogger(language);
|
|
747
|
+
const processor = new LanguageProcessor(this.config, this.provider, languageLogger);
|
|
748
|
+
|
|
749
|
+
const stats = await processor.processLanguage(language, (progressText) => {
|
|
750
|
+
task.title = progressText;
|
|
751
|
+
});
|
|
752
|
+
|
|
753
|
+
const endTime = Date.now();
|
|
754
|
+
const executionTimeMs = endTime - startTime;
|
|
755
|
+
|
|
756
|
+
// Add execution time to stats.
|
|
757
|
+
stats.executionTimeMs = executionTimeMs;
|
|
758
|
+
|
|
759
|
+
ctx.results = ctx.results || [];
|
|
760
|
+
ctx.results.push(stats);
|
|
761
|
+
|
|
762
|
+
this._updateTaskTitle(task, language, stats);
|
|
763
|
+
this._logValidationWarnings(language, stats);
|
|
764
|
+
} catch (error) {
|
|
765
|
+
const endTime = Date.now();
|
|
766
|
+
const executionTimeMs = endTime - startTime;
|
|
767
|
+
|
|
768
|
+
this._handleTaskError(ctx, language, error, task, executionTimeMs);
|
|
769
|
+
throw error;
|
|
770
|
+
}
|
|
771
|
+
},
|
|
772
|
+
}));
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/**
|
|
776
|
+
* Updates the task title for a completed language task.
|
|
777
|
+
*
|
|
778
|
+
* @private
|
|
779
|
+
*
|
|
780
|
+
* @since 1.0.0
|
|
781
|
+
*
|
|
782
|
+
* @param {Object} task - Task object.
|
|
783
|
+
* @param {string} language - Language code.
|
|
784
|
+
* @param {Object} stats - Language processing statistics.
|
|
785
|
+
*/
|
|
786
|
+
_updateTaskTitle(task, language, stats) {
|
|
787
|
+
// Use the shared buildLanguageResultLine function for consistent formatting.
|
|
788
|
+
const line = buildLanguageResultLine(stats, {
|
|
789
|
+
includeLanguageCode: true,
|
|
790
|
+
styled: false,
|
|
791
|
+
prefix: 'Finished',
|
|
792
|
+
});
|
|
793
|
+
|
|
794
|
+
task.title = line;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/**
|
|
798
|
+
* Logs validation warnings to the main logger if any validation issues were detected.
|
|
799
|
+
*
|
|
800
|
+
* @private
|
|
801
|
+
*
|
|
802
|
+
* @since 1.1.0
|
|
803
|
+
*
|
|
804
|
+
* @param {string} language - Language code.
|
|
805
|
+
* @param {Object} stats - Language processing statistics.
|
|
806
|
+
*/
|
|
807
|
+
_logValidationWarnings(language, stats) {
|
|
808
|
+
// Check if validation stats exist and verbosity level is at least 1.
|
|
809
|
+
if (!stats.validationStats || (this.config.verboseLevel || 1) < 1) {
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
const totalValidationIssues = getTotalValidationIssues(stats.validationStats);
|
|
814
|
+
|
|
815
|
+
if (totalValidationIssues > 0) {
|
|
816
|
+
const breakdown = formatValidationBreakdown(stats.validationStats);
|
|
817
|
+
this.mainLogger.warn(`⚠️ ${language}: ${breakdown}. Run with -v 2 for details.`);
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/**
|
|
822
|
+
* Handles errors during language task processing.
|
|
823
|
+
*
|
|
824
|
+
* @private
|
|
825
|
+
*
|
|
826
|
+
* @since 1.0.0
|
|
827
|
+
*
|
|
828
|
+
* @param {Object} ctx - Task context.
|
|
829
|
+
* @param {string} language - Language code.
|
|
830
|
+
* @param {Error} error - Error that occurred.
|
|
831
|
+
* @param {Object} task - Task object.
|
|
832
|
+
* @param {number} executionTimeMs - Execution time in milliseconds.
|
|
833
|
+
*/
|
|
834
|
+
_handleTaskError(ctx, language, error, task, executionTimeMs = 0) {
|
|
835
|
+
task.title = `Error processing ${language}: ${error.message.substring(0, 100)}…`;
|
|
836
|
+
|
|
837
|
+
ctx.results = ctx.results || [];
|
|
838
|
+
ctx.results.push({
|
|
839
|
+
language,
|
|
840
|
+
error: error.message,
|
|
841
|
+
logs: this.logCollector.getLogsFor(language),
|
|
842
|
+
outputFile: path.join(this.config.outputDir, `${this.config.poFilePrefix}${getFileNamingLocale(language, this.config.localeFormat)}.po`),
|
|
843
|
+
translatedInRun: 0,
|
|
844
|
+
failedInRun: 0,
|
|
845
|
+
executionTimeMs,
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/**
|
|
850
|
+
* Creates and configures a Listr instance for running language tasks.
|
|
851
|
+
* Sets up parallelism, error handling, and rendering options.
|
|
852
|
+
*
|
|
853
|
+
* @private
|
|
854
|
+
*
|
|
855
|
+
* @since 1.0.0
|
|
856
|
+
*
|
|
857
|
+
* @param {Array} tasks - Array of task definitions.
|
|
858
|
+
*
|
|
859
|
+
* @return {Listr} Configured Listr instance.
|
|
860
|
+
*/
|
|
861
|
+
_createListr(tasks) {
|
|
862
|
+
return new Listr(tasks, {
|
|
863
|
+
concurrent: this.config.concurrentJobs,
|
|
864
|
+
exitOnError: false, // Continue other languages if one fails.
|
|
865
|
+
renderer: this._getListrRenderer(),
|
|
866
|
+
rendererOptions: {
|
|
867
|
+
showTimer: this.config.verboseLevel >= 1,
|
|
868
|
+
collapseErrors: false,
|
|
869
|
+
formatOutput: 'wrap',
|
|
870
|
+
},
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
/**
|
|
875
|
+
* Determines the appropriate Listr renderer based on verbosity level and TTY availability.
|
|
876
|
+
*
|
|
877
|
+
* @private
|
|
878
|
+
*
|
|
879
|
+
* @since 1.0.0
|
|
880
|
+
*
|
|
881
|
+
* @return {string} Renderer name ('verbose', 'simple', or 'silent').
|
|
882
|
+
*/
|
|
883
|
+
_getListrRenderer() {
|
|
884
|
+
if (this.config.outputFormat === 'json' && !this.config.outputFile) {
|
|
885
|
+
return 'silent';
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
if (this.config.verboseLevel === 0) {
|
|
889
|
+
return 'silent';
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
if (this.config.verboseLevel >= 2) {
|
|
893
|
+
return 'verbose';
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
return !process.stdout.isTTY ? 'verbose' : 'default';
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/**
|
|
900
|
+
* Reports translation results using the configured output format.
|
|
901
|
+
* Uses the Reporter pattern to handle different output formats (console, JSON, etc.).
|
|
902
|
+
*
|
|
903
|
+
* @private
|
|
904
|
+
*
|
|
905
|
+
* @since 1.0.0
|
|
906
|
+
*
|
|
907
|
+
* @param {Array} allLanguageStats - Array of language processing results.
|
|
908
|
+
*
|
|
909
|
+
* @return {Promise<void>} Resolves when all reports are printed.
|
|
910
|
+
*/
|
|
911
|
+
async _printResults(allLanguageStats) {
|
|
912
|
+
try {
|
|
913
|
+
const reporter = ReporterFactory.createAndValidateReporter(this.config, this.mainLogger);
|
|
914
|
+
const endTime = Date.now();
|
|
915
|
+
|
|
916
|
+
await reporter.report(allLanguageStats, this.startTime, endTime, this.logCollector);
|
|
917
|
+
} catch (error) {
|
|
918
|
+
this.mainLogger.error(`Failed to generate report: ${error.message}`);
|
|
919
|
+
|
|
920
|
+
if (allLanguageStats.length === 0) {
|
|
921
|
+
this.mainLogger.warn('No language tasks were processed or no statistics were collected.');
|
|
922
|
+
return;
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
this.mainLogger.warn('Using fallback console output due to reporter error.');
|
|
926
|
+
|
|
927
|
+
const endTime = Date.now();
|
|
928
|
+
|
|
929
|
+
printTranslationRunSummary(allLanguageStats, this.mainLogger, defaultChalk, this.startTime, endTime);
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
/**
|
|
934
|
+
* Determines the appropriate exit code based on processing results.
|
|
935
|
+
* Returns 0 if all languages processed successfully, 1 if any had errors.
|
|
936
|
+
*
|
|
937
|
+
* @private
|
|
938
|
+
*
|
|
939
|
+
* @since 1.0.0
|
|
940
|
+
*
|
|
941
|
+
* @param {Array} allLanguageStats - Array of language processing statistics.
|
|
942
|
+
*
|
|
943
|
+
* @return {number} Exit code (0 for success, 1 for failure).
|
|
944
|
+
*/
|
|
945
|
+
_determineExitCode(allLanguageStats) {
|
|
946
|
+
if (allLanguageStats.length === 0) {
|
|
947
|
+
if (!(this.config.outputFormat === 'json' && !this.config.outputFile)) {
|
|
948
|
+
this.mainLogger.error('Script finished, but no languages were attempted or an early critical error occurred.');
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
return 1;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
const criticalErrors = allLanguageStats.filter((stat) => stat.error);
|
|
955
|
+
|
|
956
|
+
if (criticalErrors.length > 0) {
|
|
957
|
+
if (!(this.config.outputFormat === 'json' && !this.config.outputFile)) {
|
|
958
|
+
this.mainLogger.error(`${formatCount(criticalErrors.length, 'language')} failed to process due to critical errors.`);
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
return 1;
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
const languagesWithFailures = allLanguageStats.filter((stat) => !stat.error && stat.failedInRun > 0 && stat.translatedInRun === 0);
|
|
965
|
+
|
|
966
|
+
if (languagesWithFailures.length > 0) {
|
|
967
|
+
if (!(this.config.outputFormat === 'json' && !this.config.outputFile)) {
|
|
968
|
+
this.mainLogger.warn(`${formatCount(languagesWithFailures.length, 'language')} completed processing but had no successful translations.`);
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
return 1;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
const totalTranslated = allLanguageStats.reduce((sum, stat) => sum + (stat.translatedInRun || 0), 0);
|
|
975
|
+
const totalFailed = allLanguageStats.reduce((sum, stat) => sum + (stat.failedInRun || 0), 0);
|
|
976
|
+
|
|
977
|
+
// Check if all languages were cost-limited (no translations due to budget constraints.)
|
|
978
|
+
const costLimitedLanguages = allLanguageStats.filter((stat) => stat.method === 'cost_limited' || (stat.translatedInRun === 0 && stat.failedInRun === 0 && !stat.error));
|
|
979
|
+
const allLanguagesCostLimited = costLimitedLanguages.length === allLanguageStats.length;
|
|
980
|
+
|
|
981
|
+
if (totalTranslated === 0 && totalFailed > 0) {
|
|
982
|
+
if (!(this.config.outputFormat === 'json' && !this.config.outputFile)) {
|
|
983
|
+
this.mainLogger.warn('Processing completed but no strings were successfully translated.');
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
return 1;
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
// A partially translated run leaves untranslated strings in the .po file. Reporting
|
|
990
|
+
// that as success hides the gap from anyone running this unattended.
|
|
991
|
+
if (totalFailed > 0) {
|
|
992
|
+
if (!(this.config.outputFormat === 'json' && !this.config.outputFile)) {
|
|
993
|
+
this.mainLogger.warn(`Processing completed with ${formatCount(totalFailed, 'string')} left untranslated.`);
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
return 1;
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
// If all languages were cost-limited, consider it successful completion.
|
|
1000
|
+
if (totalTranslated === 0 && totalFailed === 0 && allLanguagesCostLimited) {
|
|
1001
|
+
if (!(this.config.outputFormat === 'json' && !this.config.outputFile)) {
|
|
1002
|
+
this.mainLogger.success('All specified languages processed successfully (cost limits enforced).');
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
return 0;
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
if (!(this.config.outputFormat === 'json' && !this.config.outputFile)) {
|
|
1009
|
+
this.mainLogger.success('All specified languages processed successfully.');
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
return 0;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
/**
|
|
1016
|
+
* Generates the output file path for a given language.
|
|
1017
|
+
*
|
|
1018
|
+
* @private
|
|
1019
|
+
*
|
|
1020
|
+
* @since 1.0.0
|
|
1021
|
+
*
|
|
1022
|
+
* @param {string} language - Language code.
|
|
1023
|
+
*
|
|
1024
|
+
* @return {string} Output file path.
|
|
1025
|
+
*/
|
|
1026
|
+
_getOutputFilePath(language) {
|
|
1027
|
+
const fileLocale = getFileNamingLocale(language, this.config.localeFormat);
|
|
1028
|
+
|
|
1029
|
+
return path.join(this.config.outputDir, `${this.config.poFilePrefix}${fileLocale}.po`);
|
|
1030
|
+
}
|
|
1031
|
+
}
|