cc-translate 1.3.0 → 1.3.3

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/index.js CHANGED
@@ -7,16 +7,30 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
+ var __rest = (this && this.__rest) || function (s, e) {
11
+ var t = {};
12
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
+ t[p] = s[p];
14
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
+ t[p[i]] = s[p[i]];
18
+ }
19
+ return t;
20
+ };
10
21
  import path from "path";
11
22
  import fs from "fs";
12
23
  import colors from "ansi-colors";
13
24
  import { OpenAI } from "openai";
14
25
  import cliProgress from "cli-progress";
15
26
  import { getRandomNumber, notExistsToCreateFile, readFileOfDirSync, readJsonFileSync, runWithConcurrencyLimit, sleep, } from "./lib/utils.js";
16
- import { getCacheFileSync, registerLanguageCacheFile, translateJSONDiffToJson, } from "./lib/cache/index.js";
27
+ import { getCacheFileSync, getRejectedReferences, getMissingReferenceIds, readReferenceCache, referenceDigest, registerLanguageCacheFile, translateJSONDiffToJson, writeReferenceCache, writeMissingReferenceIds, } from "./lib/cache/index.js";
17
28
  import { logErrorToFile } from "./lib/log/index.js";
18
29
  import { SUPPORT_LANGUAGE_MAP } from "./lib/support.js";
30
+ import { isProtectedText, protectTerms, readProtectedTerms, readTranslationMetadata, } from "./lib/translation-metadata.js";
19
31
  import { TranslationReferencePlugin } from "./lib/translation-reference.js";
32
+ import { englishSourceLiterals, hasUnexpectedTranslationLanguage, isNonEnglishSource, readTranslationResponse, } from "./lib/translation-response.js";
33
+ import { splitTranslationText } from "./lib/translation-format.js";
20
34
  export { generateCache, deleteBatchCache } from "./lib/cache/index.js";
21
35
  export { TranslationReferencePlugin };
22
36
  const DEFAULT_CHAT_COMPLETION_CREATE_PARAMS = {
@@ -40,7 +54,10 @@ export class I18nTranslateAgent {
40
54
  * 翻译入口文件的所有支持的语言文件夹和其中的文件
41
55
  */
42
56
  this.translate = (referencePlugin) => __awaiter(this, void 0, void 0, function* () {
43
- var _a;
57
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
58
+ if (Array.isArray(referencePlugin)) {
59
+ throw new Error("translate() accepts one reference plugin. Pass it directly, without an array.");
60
+ }
44
61
  if (!referencePlugin)
45
62
  fs.writeFileSync("error.log", "", "utf8");
46
63
  console.log("🚀 Start translation");
@@ -52,48 +69,221 @@ export class I18nTranslateAgent {
52
69
  const translateFolders = yield readFileOfDirSync(translateFolderPath);
53
70
  console.log("🚀 ~ files to translate:", translateFolders, translateFolderPath);
54
71
  const tasks = [];
55
- const skippedNoContent = [];
56
72
  const emptyFiles = [];
73
+ const invalidSources = [];
57
74
  const targetLanguages = this.supportLanguages.filter(({ code }) => code !== this.SOURCE_LANGUAGE && code !== (referencePlugin === null || referencePlugin === void 0 ? void 0 : referencePlugin.language));
75
+ const sourceFiles = new Map();
76
+ for (const fileName of translateFolders) {
77
+ const _u = (_a = (yield readJsonFileSync(path.join(translateFolderPath, fileName)))) !== null && _a !== void 0 ? _a : {}, { _meta } = _u, entries = __rest(_u, ["_meta"]);
78
+ const metadata = readTranslationMetadata(_meta);
79
+ const invalidKeys = new Set();
80
+ for (const [key, source] of Object.entries(entries)) {
81
+ const english = typeof source === "string" && this.SOURCE_LANGUAGE === "en"
82
+ ? (_c = (_b = protectTerms(source, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, this.noTranslate)) === null || _b === void 0 ? void 0 : _b.text) !== null && _c !== void 0 ? _c : source
83
+ : undefined;
84
+ if (typeof source !== "string" ||
85
+ (english !== undefined && isNonEnglishSource(english))) {
86
+ invalidKeys.add(key);
87
+ delete entries[key];
88
+ invalidSources.push({
89
+ fileName, key, language: this.SOURCE_LANGUAGE,
90
+ error: new Error(typeof source === "string"
91
+ ? "English source contains non-English text"
92
+ : "Source entry must be a string"),
93
+ });
94
+ }
95
+ }
96
+ const protectedEntries = Object.entries(entries).filter(([, source]) => isProtectedText(source, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, this.noTranslate));
97
+ sourceFiles.set(fileName, { entries, metadata, protectedEntries, invalidKeys });
98
+ }
99
+ if (!referencePlugin) {
100
+ for (const issue of invalidSources)
101
+ yield logErrorToFile(issue);
102
+ }
103
+ const writableDirectories = targetLanguages.flatMap(({ code }) => [
104
+ path.join(this.outputPath, code),
105
+ path.join(this.CACHE_ROOT_PATH, code),
106
+ path.join(this.CACHE_ROOT_PATH, code, ".references"),
107
+ ]);
108
+ // 用本次匹配和发送给模型的参考译文建立快照,避免两次读取之间发生变化。
109
+ const referenceSnapshots = new Map();
110
+ const referenceFiles = referencePlugin === null || referencePlugin === void 0 ? void 0 : referencePlugin.readFiles(sourceFiles.keys(), writableDirectories);
111
+ const referenceIdentity = referencePlugin && JSON.stringify([referencePlugin.language, referencePlugin.directory]);
112
+ if (referenceFiles && referenceIdentity) {
113
+ for (const [fileName, { entries, metadata }] of sourceFiles) {
114
+ const snapshots = new Map();
115
+ for (const [key, source] of Object.entries(entries)) {
116
+ if (isProtectedText(source, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, this.noTranslate))
117
+ continue;
118
+ const reference = (_d = referenceFiles.get(fileName)) === null || _d === void 0 ? void 0 : _d.get(key);
119
+ // 没有匹配到参考译文的词条不建立参考快照。
120
+ if (reference !== undefined)
121
+ snapshots.set(key, { [referenceIdentity]: reference });
122
+ }
123
+ referenceSnapshots.set(fileName, snapshots);
124
+ }
125
+ }
126
+ const baselines = [];
58
127
  for (const item of targetLanguages) {
59
- for (const fileName of translateFolders) {
60
- const translateJson = yield this.getTranslateContent(item.code, fileName, referencePlugin ? emptyFiles : undefined);
61
- if (!translateJson) {
62
- skippedNoContent.push(`${item.code}:${fileName}`);
128
+ for (const [fileName, { entries, metadata, protectedEntries, invalidKeys }] of sourceFiles) {
129
+ if (invalidKeys.size && Object.keys(entries).length === 0)
63
130
  continue;
131
+ const sourceCachePath = path.join(this.CACHE_ROOT_PATH, item.code, fileName);
132
+ const sourceCache = yield getCacheFileSync(sourceCachePath);
133
+ const translateJson = (_e = (yield this.getTranslateContent(item.code, fileName, referencePlugin ? emptyFiles : undefined, entries, sourceCache))) !== null && _e !== void 0 ? _e : {};
134
+ const current = referenceSnapshots.get(fileName);
135
+ const target = (current === null || current === void 0 ? void 0 : current.size) || protectedEntries.length
136
+ ? (_f = (yield readJsonFileSync(path.join(this.outputPath, item.code, fileName)))) !== null && _f !== void 0 ? _f : {}
137
+ : {};
138
+ // 整条文案是保护词时,纠正旧缓存命中的错误译文,直接复制源文案。
139
+ for (const [key, source] of protectedEntries) {
140
+ if (target[key] !== source)
141
+ translateJson[key] = source;
142
+ }
143
+ let referenceCache;
144
+ const referenceCachePath = path.join(this.CACHE_ROOT_PATH, item.code, ".references", fileName);
145
+ const rejectedReferences = getRejectedReferences(sourceCache);
146
+ if (referencePlugin && ((current === null || current === void 0 ? void 0 : current.size) || fs.existsSync(referenceCachePath))) {
147
+ const previouslyMissing = new Map();
148
+ const observed = readReferenceCache(referenceCachePath, previouslyMissing);
149
+ const missingReferenceIds = getMissingReferenceIds(sourceCache);
150
+ const migratedMissing = {};
151
+ for (const [key, ids] of previouslyMissing) {
152
+ if (typeof sourceCache[key] === "string" && Object.prototype.hasOwnProperty.call(entries, key)) {
153
+ // 保留旧缓存中缺失参考的身份,切换插件后仍能识别新补齐的参考。
154
+ migratedMissing[key] = [...new Set([...((_g = missingReferenceIds[key]) !== null && _g !== void 0 ? _g : []), ...ids])];
155
+ missingReferenceIds[key] = migratedMissing[key];
156
+ }
157
+ }
158
+ const changed = new Map();
159
+ referenceCache = {
160
+ filePath: referenceCachePath, rejectedReferences, observed,
161
+ current: current !== null && current !== void 0 ? current : new Map(), changed,
162
+ };
163
+ const knownReferences = new Set(Array.from(observed.values()).flatMap((snapshot) => Object.keys(snapshot)));
164
+ const pending = new Map();
165
+ for (const [key, snapshot] of referenceCache.current) {
166
+ const previous = (_h = observed.get(key)) !== null && _h !== void 0 ? _h : {};
167
+ const values = Object.entries(snapshot);
168
+ const rejectedDigest = rejectedReferences[key];
169
+ const referenceChanged = rejectedDigest && rejectedDigest !== referenceDigest(snapshot);
170
+ const targetValue = target[key];
171
+ const hasTarget = typeof targetValue === "string" && Boolean(targetValue.trim());
172
+ const pendingSource = Object.prototype.hasOwnProperty.call(translateJson, key);
173
+ // 同一参考已回退且译文仍有效时,等参考或源文案变化后再处理。
174
+ if (rejectedDigest && !referenceChanged && hasTarget && !pendingSource)
175
+ continue;
176
+ // 按插件顺序选出首个变更的参考,只记录本次实际使用的参考。
177
+ const changedEntry = (_j = values.find(([id, value]) => {
178
+ var _a;
179
+ return (previous[id] !== undefined || knownReferences.has(id) ||
180
+ ((_a = missingReferenceIds[key]) === null || _a === void 0 ? void 0 : _a.includes(id))) && previous[id] !== value;
181
+ })) !== null && _j !== void 0 ? _j : (referenceChanged ? values[0] : undefined);
182
+ if (changedEntry) {
183
+ const [identity, value] = changedEntry;
184
+ changed.set(key, { identity, value });
185
+ translateJson[key] = entries[key];
186
+ continue;
187
+ }
188
+ if (!hasTarget) {
189
+ translateJson[key] = entries[key];
190
+ continue;
191
+ }
192
+ // 普通缓存未命中时保留翻译任务,不从现有译文重建普通缓存。
193
+ if (pendingSource)
194
+ continue;
195
+ // 旧缓存只记录源文案。首次遇到未记录的参考时建立比对基准,不回填旧译文。
196
+ const untracked = values.filter(([id]) => previous[id] === undefined);
197
+ if (untracked.length) {
198
+ pending.set(key, Object.fromEntries(untracked));
199
+ }
200
+ }
201
+ if (pending.size || previouslyMissing.size) {
202
+ baselines.push({
203
+ fileName, cache: referenceCache, pending, hadLegacyNulls: previouslyMissing.size > 0,
204
+ sourceCachePath, migratedMissing,
205
+ });
206
+ }
64
207
  }
65
- tasks.push({ language: item.code, fileName, translateJson });
208
+ tasks.push({
209
+ language: item.code, fileName, translateJson, metadata,
210
+ referenceCache, blockedKeys: invalidKeys,
211
+ });
66
212
  }
67
213
  }
68
214
  if (referencePlugin) {
69
- const writableDirectories = targetLanguages.flatMap(({ code }) => [
70
- path.join(this.outputPath, code),
71
- path.join(this.CACHE_ROOT_PATH, code),
72
- ]);
73
- const matches = yield referencePlugin.prepare(tasks, writableDirectories);
74
- if (!matches)
215
+ const matches = yield referencePlugin.prepare(tasks, writableDirectories, this.noTranslate, referenceFiles);
216
+ if (!matches) {
217
+ for (const issue of invalidSources)
218
+ yield logErrorToFile(issue);
75
219
  return;
220
+ }
76
221
  fs.writeFileSync("error.log", "", "utf8");
77
- const blockedByFile = referencePlugin.checkConflicts
78
- ? yield this.reviewReferences(matches, referencePlugin.language)
79
- : undefined;
222
+ for (const issue of invalidSources)
223
+ yield logErrorToFile(issue);
224
+ const blockedByFile = new Map();
225
+ const conflictsByFile = new Map();
226
+ if (referencePlugin.checkConflicts) {
227
+ // 首次建立参考基准的词条也参与检查,防止已缓存的目标语言写入冲突参考。
228
+ for (const { fileName, pending } of baselines) {
229
+ const fileMatches = (_k = matches.get(fileName)) !== null && _k !== void 0 ? _k : new Map();
230
+ const source = (_l = sourceFiles.get(fileName)) === null || _l === void 0 ? void 0 : _l.entries;
231
+ if (!source)
232
+ continue;
233
+ for (const [key, snapshot] of pending) {
234
+ const reference = referenceIdentity && snapshot[referenceIdentity];
235
+ if (reference !== undefined) {
236
+ fileMatches.set(key, { source: source[key], translation: reference });
237
+ }
238
+ }
239
+ if (fileMatches.size)
240
+ matches.set(fileName, fileMatches);
241
+ }
242
+ yield this.reviewReferences(matches, referencePlugin.language, blockedByFile, conflictsByFile);
243
+ }
244
+ for (const { fileName, cache, pending, hadLegacyNulls, sourceCachePath, migratedMissing } of baselines) {
245
+ if (Object.keys(migratedMissing).length) {
246
+ yield writeMissingReferenceIds(sourceCachePath, migratedMissing);
247
+ }
248
+ let changed = hadLegacyNulls;
249
+ for (const [key, snapshot] of pending) {
250
+ if (((_m = blockedByFile.get(fileName)) === null || _m === void 0 ? void 0 : _m.has(key)) || ((_o = conflictsByFile.get(fileName)) === null || _o === void 0 ? void 0 : _o.has(key))) {
251
+ continue;
252
+ }
253
+ cache.observed.set(key, Object.assign(Object.assign({}, cache.observed.get(key)), snapshot));
254
+ changed = true;
255
+ }
256
+ if (changed)
257
+ writeReferenceCache(cache);
258
+ }
80
259
  for (const task of tasks) {
81
260
  const fileMatches = matches.get(task.fileName);
82
- if (fileMatches) {
83
- task.reference = {
84
- language: referencePlugin.language,
85
- matches: fileMatches,
86
- };
261
+ if (fileMatches)
262
+ task.reference = { language: referencePlugin.language, matches: fileMatches };
263
+ task.conflictingKeys = conflictsByFile.get(task.fileName);
264
+ // 确认冲突后,所有目标语言使用源文案,普通缓存命中的旧译文也要修正。
265
+ for (const key of (_p = task.conflictingKeys) !== null && _p !== void 0 ? _p : []) {
266
+ const snapshot = (_q = task.referenceCache) === null || _q === void 0 ? void 0 : _q.current.get(key);
267
+ if (snapshot && ((_r = task.referenceCache) === null || _r === void 0 ? void 0 : _r.rejectedReferences[key]) === referenceDigest(snapshot) &&
268
+ !Object.prototype.hasOwnProperty.call(task.translateJson, key))
269
+ continue;
270
+ const source = (_s = fileMatches === null || fileMatches === void 0 ? void 0 : fileMatches.get(key)) === null || _s === void 0 ? void 0 : _s.source;
271
+ if (source !== undefined)
272
+ task.translateJson[key] = source;
87
273
  }
88
- task.blockedKeys = blockedByFile === null || blockedByFile === void 0 ? void 0 : blockedByFile.get(task.fileName);
89
- for (const key of (_a = task.blockedKeys) !== null && _a !== void 0 ? _a : []) {
90
- delete task.translateJson[key];
274
+ const blocked = blockedByFile.get(task.fileName);
275
+ if (blocked === null || blocked === void 0 ? void 0 : blocked.size) {
276
+ task.blockedKeys = new Set([...((_t = task.blockedKeys) !== null && _t !== void 0 ? _t : []), ...blocked]);
277
+ for (const key of blocked)
278
+ delete task.translateJson[key];
91
279
  }
92
280
  }
93
- for (const emptyFile of emptyFiles) {
281
+ for (const emptyFile of emptyFiles)
94
282
  yield this.outputLanguageFile(emptyFile);
95
- }
96
283
  }
284
+ const skippedNoContent = tasks
285
+ .filter(({ translateJson }) => Object.keys(translateJson).length === 0)
286
+ .map(({ language, fileName }) => `${language}:${fileName}`);
97
287
  if (skippedNoContent.length > 0) {
98
288
  const summary = skippedNoContent.length <= 5
99
289
  ? skippedNoContent.join(", ")
@@ -157,14 +347,16 @@ export class I18nTranslateAgent {
157
347
  * @returns
158
348
  */
159
349
  this.singleTranslate = (params) => __awaiter(this, void 0, void 0, function* () {
350
+ var _a;
160
351
  const {
161
352
  /** 待翻译的语言 */
162
353
  language,
163
354
  /** 待翻译的文件名 */
164
- fileName, translateJson, multiBar, progressBar: taskProgressBar, callback, reference, blockedKeys, } = params;
355
+ fileName, translateJson, multiBar, progressBar: taskProgressBar, callback, reference, blockedKeys, conflictingKeys, metadata, referenceCache, } = params;
165
356
  try {
166
357
  // 生成chat循环代码
167
358
  const promiseList = Object.entries(translateJson).map(([key, value], index) => () => {
359
+ var _a;
168
360
  const match = reference === null || reference === void 0 ? void 0 : reference.matches.get(key);
169
361
  return this.translateChat({
170
362
  key,
@@ -175,6 +367,9 @@ export class I18nTranslateAgent {
175
367
  reference: reference && match
176
368
  ? { language: reference.language, value: match.translation }
177
369
  : undefined,
370
+ metadata,
371
+ changedReference: (_a = referenceCache === null || referenceCache === void 0 ? void 0 : referenceCache.changed.get(key)) === null || _a === void 0 ? void 0 : _a.value,
372
+ sourceOnly: conflictingKeys === null || conflictingKeys === void 0 ? void 0 : conflictingKeys.has(key),
178
373
  });
179
374
  });
180
375
  const progressBar = taskProgressBar !== null && taskProgressBar !== void 0 ? taskProgressBar : multiBar === null || multiBar === void 0 ? void 0 : multiBar.create(promiseList.length, 0, {
@@ -182,12 +377,34 @@ export class I18nTranslateAgent {
182
377
  });
183
378
  for (const fn of promiseList) {
184
379
  const result = yield fn();
380
+ const snapshot = result.usedSourceFallback
381
+ ? undefined
382
+ : referenceCache === null || referenceCache === void 0 ? void 0 : referenceCache.current.get(result.key);
383
+ // 回退后在普通缓存中记录待比较的摘要,参考缓存仍只保存采用的参考。
384
+ const rejectedReferences = referenceCache && !snapshot &&
385
+ (result.usedSourceFallback || referenceCache.observed.has(result.key) ||
386
+ referenceCache.rejectedReferences[result.key])
387
+ ? { [result.key]: referenceDigest((_a = referenceCache.current.get(result.key)) !== null && _a !== void 0 ? _a : {}) }
388
+ : undefined;
185
389
  yield this.outputLanguageFile({
186
390
  jsonMap: { [result.key]: result.value },
187
391
  folderName: language,
188
392
  fileName,
189
393
  blockedKeys,
394
+ rejectedReferences,
395
+ usedReferenceId: snapshot ? Object.keys(snapshot)[0] : undefined,
190
396
  });
397
+ // 译文写入后同步参考快照。未采用参考时删除旧记录。
398
+ if (referenceCache && snapshot) {
399
+ const previous = referenceCache.observed.get(result.key);
400
+ const changed = referenceCache.changed.get(result.key);
401
+ const used = changed ? { [changed.identity]: changed.value } : snapshot;
402
+ referenceCache.observed.set(result.key, Object.assign(Object.assign({}, previous), used));
403
+ writeReferenceCache(referenceCache);
404
+ }
405
+ else if (referenceCache === null || referenceCache === void 0 ? void 0 : referenceCache.observed.delete(result.key)) {
406
+ writeReferenceCache(referenceCache);
407
+ }
191
408
  delete translateJson[result.key];
192
409
  progressBar === null || progressBar === void 0 ? void 0 : progressBar.increment();
193
410
  }
@@ -212,11 +429,9 @@ export class I18nTranslateAgent {
212
429
  * @returns
213
430
  */
214
431
  this.translateChat = (params) => __awaiter(this, void 0, void 0, function* () {
215
- var _a, _b, _c, _d;
216
- const { key, value, language, index, fileName, reference } = params;
432
+ var _a, _b, _c, _d, _e, _f, _g;
433
+ const { key, value, language, index, fileName, reference, metadata, changedReference, sourceOnly, } = params;
217
434
  try {
218
- if (!this.client)
219
- throw new Error("Connection failed");
220
435
  const targetLanguage = this.searchLanguage(language);
221
436
  const originLanguage = this.searchLanguage(this.SOURCE_LANGUAGE);
222
437
  if (!targetLanguage) {
@@ -225,43 +440,103 @@ export class I18nTranslateAgent {
225
440
  if (!originLanguage) {
226
441
  throw new Error(`Unsupported language:${this.SOURCE_LANGUAGE}`);
227
442
  }
443
+ if (isProtectedText(value, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, this.noTranslate)) {
444
+ return { key, value, index };
445
+ }
446
+ if (!this.client)
447
+ throw new Error("Connection failed");
448
+ const configuredProtection = protectTerms(value, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, this.noTranslate);
449
+ if (this.SOURCE_LANGUAGE === "en" && isNonEnglishSource((_a = configuredProtection === null || configuredProtection === void 0 ? void 0 : configuredProtection.text) !== null && _a !== void 0 ? _a : value)) {
450
+ throw new Error("English source contains non-English text");
451
+ }
452
+ const protectedText = this.SOURCE_LANGUAGE === "en"
453
+ ? protectTerms(value, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, this.noTranslate, englishSourceLiterals)
454
+ : configuredProtection;
455
+ const source = (_b = protectedText === null || protectedText === void 0 ? void 0 : protectedText.text) !== null && _b !== void 0 ? _b : value;
456
+ const primaryReference = sourceOnly ? undefined : reference;
457
+ let input = primaryReference ? JSON.stringify({
458
+ source,
459
+ referenceLanguage: (_d = (_c = SUPPORT_LANGUAGE_MAP[primaryReference.language]) === null || _c === void 0 ? void 0 : _c.name) !== null && _d !== void 0 ? _d : primaryReference.language,
460
+ reference: primaryReference.value,
461
+ }) : source;
462
+ const isReferenceRetranslation = changedReference !== undefined && primaryReference;
463
+ const sourcePlaceholders = splitTranslationText(source)
464
+ .filter(({ placeholder }) => placeholder)
465
+ .map(({ text }) => text);
466
+ const instructions = isReferenceRetranslation
467
+ ? [
468
+ `Translate the reference field into ${targetLanguage.name}.`,
469
+ "Translate only the meaning expressed by the reference. If sourcePlaceholders are provided, preserve each occurrence in the corresponding position.",
470
+ ]
471
+ : primaryReference
472
+ ? [
473
+ `Translate the meaning of the reference into ${targetLanguage.name}.`,
474
+ "The primary reference is authoritative for meaning. Use file-level business context only as secondary guidance when it agrees with the reference. " +
475
+ "Use the source to preserve placeholders and formatting. If the source, business context, or general guidance suggests a different meaning, follow the primary reference.",
476
+ ]
477
+ : [`Please translate ${originLanguage.name} to ${targetLanguage.name}`];
478
+ if (!isReferenceRetranslation && (metadata === null || metadata === void 0 ? void 0 : metadata.context)) {
479
+ instructions.push(`Business context for this file: ${metadata.context}`);
480
+ }
481
+ if (isReferenceRetranslation) {
482
+ // 参考变更时只发送新参考及源文案的格式要求,避免旧语境把模型拉回原来的词义。
483
+ input = JSON.stringify(Object.assign({ referenceLanguage: (_f = (_e = SUPPORT_LANGUAGE_MAP[primaryReference.language]) === null || _e === void 0 ? void 0 : _e.name) !== null && _f !== void 0 ? _f : primaryReference.language, reference: changedReference }, (sourcePlaceholders.length ? { sourcePlaceholders } : {})));
484
+ }
485
+ const primaryReferenceLanguage = primaryReference === null || primaryReference === void 0 ? void 0 : primaryReference.language;
486
+ // 简繁互译时保留首选中文参考的措辞,避免根据通用业务背景改成别的术语。
487
+ if ((language === "zh-TW" && primaryReferenceLanguage === "zh-CN") ||
488
+ (language === "zh-CN" && primaryReferenceLanguage === "zh-TW")) {
489
+ instructions.push("Preserve the wording of the Chinese reference. Convert it to the requested Chinese script and locale without paraphrasing or substituting synonyms.");
490
+ }
491
+ if (protectedText) {
492
+ instructions.push("Copy each {__CC_PROTECTED_...} placeholder exactly once. Translate the surrounding text normally.");
493
+ }
494
+ if (sourcePlaceholders.length && !isReferenceRetranslation) {
495
+ instructions.push("Keep source placeholders and rich-text tags exactly as written.");
496
+ }
228
497
  yield sleep(getRandomNumber(200, 300));
229
- const chatCompletion = yield this.client.chat.completions.create(Object.assign(Object.assign({ model: (_a = this.chatCompletionCreateParams.model) !== null && _a !== void 0 ? _a : "gpt-4o" }, this.chatCompletionCreateParams), { stream: false, messages: [
230
- ...this.fineTune.map((val) => ({
498
+ const chatCompletion = yield this.client.chat.completions.create(Object.assign(Object.assign({ model: (_g = this.chatCompletionCreateParams.model) !== null && _g !== void 0 ? _g : "gpt-4o" }, this.chatCompletionCreateParams), { stream: false, messages: [
499
+ ...(isReferenceRetranslation ? [] : this.fineTune).map((val) => ({
231
500
  role: "system",
232
501
  content: val,
233
502
  })),
234
503
  {
235
504
  role: "system",
236
- content: `Please translate ${originLanguage.name} to ${targetLanguage.name}` +
237
- (reference
238
- ? ". Use the reference translation to clarify the meaning of the source text."
239
- : ""),
505
+ content: instructions.join("\n"),
240
506
  },
241
507
  {
242
508
  role: "system",
243
- content: `After translation is complete, directly output the corresponding meaning without any irrelevant content`,
509
+ content: "Return only the translated text in the requested language. " +
510
+ "Do not add the source text, response labels, JSON or Markdown wrappers, or explanations. " +
511
+ "Preserve JSON examples that are part of the source text.",
244
512
  },
245
513
  {
246
514
  role: "user",
247
- content: reference
248
- ? JSON.stringify({
249
- source: value,
250
- referenceLanguage: (_c = (_b = SUPPORT_LANGUAGE_MAP[reference.language]) === null || _b === void 0 ? void 0 : _b.name) !== null && _c !== void 0 ? _c : reference.language,
251
- reference: reference.value,
252
- })
253
- : value,
515
+ content: input,
254
516
  },
255
517
  ] }));
256
- const translation = (_d = chatCompletion === null || chatCompletion === void 0 ? void 0 : chatCompletion.choices[0]) === null || _d === void 0 ? void 0 : _d.message.content;
257
- if (reference && !(translation === null || translation === void 0 ? void 0 : translation.trim())) {
258
- throw new Error("No translation returned for referenced entry");
518
+ const choice = chatCompletion === null || chatCompletion === void 0 ? void 0 : chatCompletion.choices[0];
519
+ if ((choice === null || choice === void 0 ? void 0 : choice.message.refusal) || ((choice === null || choice === void 0 ? void 0 : choice.finish_reason) && choice.finish_reason !== "stop")) {
520
+ throw new Error("The model did not complete the translation");
259
521
  }
260
- return {
261
- key,
262
- value: translation !== null && translation !== void 0 ? translation : value,
263
- index,
264
- };
522
+ const translation = readTranslationResponse(choice === null || choice === void 0 ? void 0 : choice.message.content, source);
523
+ if (hasUnexpectedTranslationLanguage(translation, { language: this.SOURCE_LANGUAGE, value }, language, reference ? [reference] : [])) {
524
+ if (!primaryReference) {
525
+ throw new Error("Translation is not in the source or target language");
526
+ }
527
+ console.warn(`Unexpected translation language, translating from source: ${language}/${fileName} (${key})`);
528
+ // 保留参考供本地检查,但回退请求只发送源文案和正常的业务语境。
529
+ return this.translateChat(Object.assign(Object.assign({}, params), { sourceOnly: true }));
530
+ }
531
+ if (sourcePlaceholders.length) {
532
+ const actualPlaceholders = splitTranslationText(translation)
533
+ .filter(({ placeholder }) => placeholder)
534
+ .map(({ text }) => text);
535
+ if (sourcePlaceholders.sort().join("\n") !== actualPlaceholders.sort().join("\n")) {
536
+ throw new Error("Translation did not preserve the source placeholders");
537
+ }
538
+ }
539
+ return Object.assign({ key, value: protectedText ? protectedText.restore(translation) : translation, index }, (sourceOnly ? { usedSourceFallback: true } : {}));
265
540
  }
266
541
  catch (error) {
267
542
  logErrorToFile({ error: error, key, fileName, language });
@@ -279,7 +554,8 @@ export class I18nTranslateAgent {
279
554
  * @param fileName
280
555
  * @returns
281
556
  */
282
- this.getTranslateContent = (language, fileName, deferredEmptyFiles) => __awaiter(this, void 0, void 0, function* () {
557
+ this.getTranslateContent = (language, fileName, deferredEmptyFiles, sourceEntries, sourceCache) => __awaiter(this, void 0, void 0, function* () {
558
+ var _a;
283
559
  const translateFilePath = path.join(this.ENTRY_ROOT_PATH, this.SOURCE_LANGUAGE, fileName);
284
560
  /** 缓存文件路径 */
285
561
  const cacheFilePath = path.join(this.CACHE_ROOT_PATH, language, fileName);
@@ -287,8 +563,8 @@ export class I18nTranslateAgent {
287
563
  console.dir(`File not found: ${translateFilePath}`);
288
564
  return;
289
565
  }
290
- const translateFileObject = yield readJsonFileSync(translateFilePath);
291
- const cacheObject = yield getCacheFileSync(cacheFilePath);
566
+ const _b = (_a = sourceEntries !== null && sourceEntries !== void 0 ? sourceEntries : (yield readJsonFileSync(translateFilePath))) !== null && _a !== void 0 ? _a : {}, { _meta } = _b, translateFileObject = __rest(_b, ["_meta"]);
567
+ const cacheObject = sourceCache !== null && sourceCache !== void 0 ? sourceCache : yield getCacheFileSync(cacheFilePath);
292
568
  const diffObject = translateJSONDiffToJson(cacheObject, translateFileObject);
293
569
  if (Object.values(diffObject).length === 0) {
294
570
  if (Object.keys(translateFileObject).length === 0) {
@@ -311,7 +587,7 @@ export class I18nTranslateAgent {
311
587
  * @param {Object} jsonMap
312
588
  */
313
589
  this.outputLanguageFile = (params) => __awaiter(this, void 0, void 0, function* () {
314
- const { folderName, fileName, jsonMap, blockedKeys } = params;
590
+ const { folderName, fileName, jsonMap, blockedKeys, rejectedReferences, usedReferenceId } = params;
315
591
  const outputFilePath = path.join(this.outputPath, folderName, fileName);
316
592
  //创建输出文件夹
317
593
  notExistsToCreateFile(this.outputPath);
@@ -332,11 +608,14 @@ export class I18nTranslateAgent {
332
608
  delete oldJsonMap[key];
333
609
  }
334
610
  const newJsonMap = Object.assign(oldJsonMap, jsonMap);
611
+ delete newJsonMap._meta;
335
612
  yield fs.writeFileSync(path.resolve(outputFilePath), JSON.stringify(newJsonMap, null, 2), "utf8");
336
613
  // 注册缓存
337
614
  yield registerLanguageCacheFile({
338
615
  sourceFilePath: path.join(this.ENTRY_ROOT_PATH, this.SOURCE_LANGUAGE, fileName),
339
616
  jsonMap,
617
+ rejectedReferences,
618
+ usedReferenceId,
340
619
  fileName,
341
620
  language: folderName,
342
621
  folderName: this.CACHE_ROOT_PATH,
@@ -357,6 +636,7 @@ export class I18nTranslateAgent {
357
636
  this.OUTPUT_ROOT_PATH = params.outputRootPath;
358
637
  /** 微调模型 */
359
638
  this.fineTune = (_d = params.fineTune) !== null && _d !== void 0 ? _d : [];
639
+ this.noTranslate = readProtectedTerms(params.noTranslate);
360
640
  /** 需要翻译的语言列表 */
361
641
  this.languages = (_e = params.languages) !== null && _e !== void 0 ? _e : [];
362
642
  /** 翻译任务并发数(队列长度),完成一个即取下一个 */
@@ -383,75 +663,92 @@ export class I18nTranslateAgent {
383
663
  searchLanguage(code) {
384
664
  return this.supportLanguages.find((item) => item.code === code);
385
665
  }
386
- reviewReferences(matches, language) {
666
+ reviewReferences(matches, language, blocked, conflicts) {
387
667
  return __awaiter(this, void 0, void 0, function* () {
388
668
  var _a, _b, _c, _d, _e;
389
- const blocked = new Map();
669
+ let skipped = 0;
670
+ let fallbackCount = 0;
390
671
  const sourceLanguage = (_b = (_a = SUPPORT_LANGUAGE_MAP[this.SOURCE_LANGUAGE]) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : this.SOURCE_LANGUAGE;
391
672
  const referenceLanguage = (_d = (_c = SUPPORT_LANGUAGE_MAP[language]) === null || _c === void 0 ? void 0 : _c.name) !== null && _d !== void 0 ? _d : language;
392
673
  const timeout = (_e = this.openaiClientConfig.timeout) !== null && _e !== void 0 ? _e : 30000;
393
- const checks = Array.from(matches).flatMap(([fileName, entries]) => Array.from(entries, ([key, { source, translation }]) => () => __awaiter(this, void 0, void 0, function* () {
394
- var _a, _b, _c;
395
- let issue;
396
- for (let attempt = 0;; attempt++) {
397
- const deadline = new AbortController();
398
- const timer = setTimeout(() => deadline.abort(), timeout);
399
- try {
400
- if (!this.client)
401
- throw new Error("Connection failed");
402
- const response = yield this.client.chat.completions.create({
403
- model: (_a = this.chatCompletionCreateParams.model) !== null && _a !== void 0 ? _a : "gpt-4o",
404
- messages: [
405
- {
406
- role: "system",
407
- content: "Compare the source UI text and its reference translation. " +
408
- "Reply CONFLICT only when they clearly express incompatible product meanings. " +
409
- "A reference that clarifies an ambiguous source or adds compatible detail is not a conflict. " +
410
- "Reply COMPATIBLE in all other cases. Output exactly one label.",
411
- },
412
- {
413
- role: "user",
414
- content: JSON.stringify({
415
- sourceLanguage,
416
- source,
417
- referenceLanguage,
418
- reference: translation,
419
- }),
420
- },
421
- ],
422
- }, { signal: deadline.signal, timeout, maxRetries: 0 });
423
- const verdict = (_c = (_b = response.choices[0]) === null || _b === void 0 ? void 0 : _b.message.content) === null || _c === void 0 ? void 0 : _c.trim();
424
- if (verdict === "COMPATIBLE")
425
- return;
426
- if (verdict !== "CONFLICT")
427
- throw new Error("Invalid reference verdict");
428
- issue = new Error("Reference conflict");
429
- break;
430
- }
431
- catch (error) {
432
- if (attempt >= this.maxTaskRetries) {
433
- const reason = deadline.signal.aborted
434
- ? `request timed out after ${timeout} ms`
435
- : error;
436
- issue = new Error(`Reference judgment failed: ${reason}`);
674
+ const checks = Array.from(matches).flatMap(([fileName, entries]) => {
675
+ const blockedKeys = blocked.get(fileName);
676
+ const conflictingKeys = conflicts.get(fileName);
677
+ const pending = Array.from(entries).filter(([key]) => !(blockedKeys === null || blockedKeys === void 0 ? void 0 : blockedKeys.has(key)) && !(conflictingKeys === null || conflictingKeys === void 0 ? void 0 : conflictingKeys.has(key)));
678
+ return pending.map(([key, { source, translation }]) => () => __awaiter(this, void 0, void 0, function* () {
679
+ var _a, _b;
680
+ let issue;
681
+ let conflict = false;
682
+ for (let attempt = 0;; attempt++) {
683
+ const deadline = new AbortController();
684
+ const timer = setTimeout(() => deadline.abort(), timeout);
685
+ try {
686
+ if (!this.client)
687
+ throw new Error("Connection failed");
688
+ const response = yield this.client.chat.completions.create({
689
+ model: (_a = this.chatCompletionCreateParams.model) !== null && _a !== void 0 ? _a : "gpt-4o",
690
+ messages: [
691
+ {
692
+ role: "system",
693
+ content: "Compare the source UI text and its reference translation. " +
694
+ "Reply CONFLICT only when they clearly express incompatible product meanings. " +
695
+ "A reference that clarifies an ambiguous source or adds compatible detail is not a conflict. " +
696
+ "Reply COMPATIBLE in all other cases. Output exactly one label.",
697
+ },
698
+ {
699
+ role: "user",
700
+ content: JSON.stringify({
701
+ sourceLanguage,
702
+ source,
703
+ referenceLanguage,
704
+ reference: translation,
705
+ }),
706
+ },
707
+ ],
708
+ }, { signal: deadline.signal, timeout, maxRetries: 0 });
709
+ const choice = response.choices[0];
710
+ if ((choice === null || choice === void 0 ? void 0 : choice.message.refusal) || ((choice === null || choice === void 0 ? void 0 : choice.finish_reason) && choice.finish_reason !== "stop")) {
711
+ throw new Error("Incomplete reference verdict");
712
+ }
713
+ const verdict = (_b = choice === null || choice === void 0 ? void 0 : choice.message.content) === null || _b === void 0 ? void 0 : _b.trim();
714
+ if (verdict === "COMPATIBLE")
715
+ return;
716
+ if (verdict !== "CONFLICT")
717
+ throw new Error("Invalid reference verdict");
718
+ conflict = true;
719
+ issue = new Error("Reference conflict");
437
720
  break;
438
721
  }
722
+ catch (error) {
723
+ if (attempt >= this.maxTaskRetries) {
724
+ const reason = deadline.signal.aborted
725
+ ? `request timed out after ${timeout} ms`
726
+ : error;
727
+ issue = new Error(`Reference judgment failed: ${reason}`);
728
+ break;
729
+ }
730
+ }
731
+ finally {
732
+ clearTimeout(timer);
733
+ }
734
+ yield sleep(this.taskRetryBaseDelayMs * (attempt + 1));
439
735
  }
440
- finally {
441
- clearTimeout(timer);
736
+ const outcome = conflict ? conflicts : blocked;
737
+ let keys = outcome.get(fileName);
738
+ if (!keys) {
739
+ keys = new Set();
740
+ outcome.set(fileName, keys);
442
741
  }
443
- yield sleep(this.taskRetryBaseDelayMs * (attempt + 1));
444
- }
445
- let keys = blocked.get(fileName);
446
- if (!keys) {
447
- keys = new Set();
448
- blocked.set(fileName, keys);
449
- }
450
- keys.add(key);
451
- yield logErrorToFile({ error: issue, fileName, key, language });
452
- })));
742
+ keys.add(key);
743
+ if (conflict)
744
+ fallbackCount++;
745
+ else
746
+ skipped++;
747
+ yield logErrorToFile({ error: issue, fileName, key, language });
748
+ }));
749
+ });
453
750
  if (checks.length === 0)
454
- return blocked;
751
+ return;
455
752
  let completed = 0;
456
753
  const reportProgress = () => {
457
754
  console.log(`Reference checks: ${completed}/${checks.length} completed`);
@@ -472,11 +769,12 @@ export class I18nTranslateAgent {
472
769
  clearInterval(progressTimer);
473
770
  }
474
771
  reportProgress();
475
- const skipped = Array.from(blocked.values()).reduce((count, keys) => count + keys.size, 0);
772
+ if (fallbackCount) {
773
+ console.warn(`Translating ${fallbackCount} conflicting reference entries from source. See error.log for details.`);
774
+ }
476
775
  if (skipped) {
477
776
  console.warn(`Skipped ${skipped} reference entries. See error.log for details.`);
478
777
  }
479
- return blocked;
480
778
  });
481
779
  }
482
780
  }