cc-translate 1.3.2 → 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
@@ -24,12 +24,13 @@ import colors from "ansi-colors";
24
24
  import { OpenAI } from "openai";
25
25
  import cliProgress from "cli-progress";
26
26
  import { getRandomNumber, notExistsToCreateFile, readFileOfDirSync, readJsonFileSync, runWithConcurrencyLimit, sleep, } from "./lib/utils.js";
27
- import { getCacheFileSync, readReferenceCache, registerLanguageCacheFile, translateJSONDiffToJson, writeReferenceCache, } from "./lib/cache/index.js";
27
+ import { getCacheFileSync, getRejectedReferences, getMissingReferenceIds, readReferenceCache, referenceDigest, registerLanguageCacheFile, translateJSONDiffToJson, writeReferenceCache, writeMissingReferenceIds, } from "./lib/cache/index.js";
28
28
  import { logErrorToFile } from "./lib/log/index.js";
29
29
  import { SUPPORT_LANGUAGE_MAP } from "./lib/support.js";
30
30
  import { isProtectedText, protectTerms, readProtectedTerms, readTranslationMetadata, } from "./lib/translation-metadata.js";
31
31
  import { TranslationReferencePlugin } from "./lib/translation-reference.js";
32
- import { readTranslationResponse } from "./lib/translation-response.js";
32
+ import { englishSourceLiterals, hasUnexpectedTranslationLanguage, isNonEnglishSource, readTranslationResponse, } from "./lib/translation-response.js";
33
+ import { splitTranslationText } from "./lib/translation-format.js";
33
34
  export { generateCache, deleteBatchCache } from "./lib/cache/index.js";
34
35
  export { TranslationReferencePlugin };
35
36
  const DEFAULT_CHAT_COMPLETION_CREATE_PARAMS = {
@@ -52,12 +53,12 @@ export class I18nTranslateAgent {
52
53
  /**
53
54
  * 翻译入口文件的所有支持的语言文件夹和其中的文件
54
55
  */
55
- this.translate = (referencePlugins) => __awaiter(this, void 0, void 0, function* () {
56
- var _a, _b, _c, _d;
57
- const plugins = referencePlugins && "prepare" in referencePlugins
58
- ? [referencePlugins]
59
- : referencePlugins !== null && referencePlugins !== void 0 ? referencePlugins : [];
60
- if (plugins.length === 0)
56
+ this.translate = (referencePlugin) => __awaiter(this, void 0, void 0, function* () {
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
+ }
61
+ if (!referencePlugin)
61
62
  fs.writeFileSync("error.log", "", "utf8");
62
63
  console.log("🚀 Start translation");
63
64
  console.log(`🚀 Using model: ${this.chatCompletionCreateParams.model} 🚀`);
@@ -68,120 +69,221 @@ export class I18nTranslateAgent {
68
69
  const translateFolders = yield readFileOfDirSync(translateFolderPath);
69
70
  console.log("🚀 ~ files to translate:", translateFolders, translateFolderPath);
70
71
  const tasks = [];
71
- const skippedNoContent = [];
72
72
  const emptyFiles = [];
73
- const referenceLanguages = new Set(plugins.map(({ language }) => language));
74
- const targetLanguages = this.supportLanguages.filter(({ code }) => code !== this.SOURCE_LANGUAGE && !referenceLanguages.has(code));
73
+ const invalidSources = [];
74
+ const targetLanguages = this.supportLanguages.filter(({ code }) => code !== this.SOURCE_LANGUAGE && code !== (referencePlugin === null || referencePlugin === void 0 ? void 0 : referencePlugin.language));
75
75
  const sourceFiles = new Map();
76
76
  for (const fileName of translateFolders) {
77
- const _e = (_a = (yield readJsonFileSync(path.join(translateFolderPath, fileName)))) !== null && _a !== void 0 ? _a : {}, { _meta } = _e, entries = __rest(_e, ["_meta"]);
78
- sourceFiles.set(fileName, { entries, metadata: readTranslationMetadata(_meta) });
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);
79
102
  }
80
103
  const writableDirectories = targetLanguages.flatMap(({ code }) => [
81
104
  path.join(this.outputPath, code),
82
105
  path.join(this.CACHE_ROOT_PATH, code),
83
106
  path.join(this.CACHE_ROOT_PATH, code, ".references"),
84
107
  ]);
85
- const loadedReferences = plugins.map((plugin) => ({
86
- plugin,
87
- identity: JSON.stringify([plugin.language, plugin.directory]),
88
- files: plugin.readFiles(sourceFiles.keys(), writableDirectories),
89
- }));
90
108
  // 用本次匹配和发送给模型的参考译文建立快照,避免两次读取之间发生变化。
91
109
  const referenceSnapshots = new Map();
92
- if (loadedReferences.length) {
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) {
93
113
  for (const [fileName, { entries, metadata }] of sourceFiles) {
94
114
  const snapshots = new Map();
95
115
  for (const [key, source] of Object.entries(entries)) {
96
116
  if (isProtectedText(source, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, this.noTranslate))
97
117
  continue;
98
- snapshots.set(key, Object.fromEntries(loadedReferences.map(({ identity, files }) => {
99
- var _a, _b;
100
- return [
101
- identity,
102
- (_b = (_a = files.get(fileName)) === null || _a === void 0 ? void 0 : _a.get(key)) !== null && _b !== void 0 ? _b : null,
103
- ];
104
- })));
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 });
105
122
  }
106
123
  referenceSnapshots.set(fileName, snapshots);
107
124
  }
108
125
  }
109
126
  const baselines = [];
110
127
  for (const item of targetLanguages) {
111
- for (const [fileName, { entries, metadata }] of sourceFiles) {
112
- const translateJson = (_b = (yield this.getTranslateContent(item.code, fileName, plugins.length ? emptyFiles : undefined, entries))) !== null && _b !== void 0 ? _b : {};
128
+ for (const [fileName, { entries, metadata, protectedEntries, invalidKeys }] of sourceFiles) {
129
+ if (invalidKeys.size && Object.keys(entries).length === 0)
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 : {};
113
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
+ }
114
143
  let referenceCache;
115
- if (current === null || current === void 0 ? void 0 : current.size) {
116
- const filePath = path.join(this.CACHE_ROOT_PATH, item.code, ".references", fileName);
117
- const observed = readReferenceCache(filePath);
118
- referenceCache = { filePath, observed, current };
119
- let addedBaseline = false;
120
- for (const [key, snapshot] of current) {
121
- if (Object.prototype.hasOwnProperty.call(translateJson, key))
122
- continue;
123
- const previous = (_c = observed.get(key)) !== null && _c !== void 0 ? _c : {};
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 : {};
124
167
  const values = Object.entries(snapshot);
125
- // 参考译文被清空或删除时,保留已有译文。
126
- if (values.some(([id, value]) => value !== null && previous[id] !== undefined && previous[id] !== value)) {
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) {
127
189
  translateJson[key] = entries[key];
128
190
  continue;
129
191
  }
192
+ // 普通缓存未命中时保留翻译任务,不从现有译文重建普通缓存。
193
+ if (pendingSource)
194
+ continue;
130
195
  // 旧缓存只记录源文案。首次遇到未记录的参考时建立比对基准,不回填旧译文。
131
196
  const untracked = values.filter(([id]) => previous[id] === undefined);
132
197
  if (untracked.length) {
133
- observed.set(key, Object.assign(Object.assign({}, previous), Object.fromEntries(untracked)));
134
- addedBaseline = true;
198
+ pending.set(key, Object.fromEntries(untracked));
135
199
  }
136
200
  }
137
- if (addedBaseline)
138
- baselines.push(referenceCache);
139
- }
140
- if (Object.keys(translateJson).length === 0) {
141
- skippedNoContent.push(`${item.code}:${fileName}`);
142
- continue;
201
+ if (pending.size || previouslyMissing.size) {
202
+ baselines.push({
203
+ fileName, cache: referenceCache, pending, hadLegacyNulls: previouslyMissing.size > 0,
204
+ sourceCachePath, migratedMissing,
205
+ });
206
+ }
143
207
  }
144
- tasks.push({ language: item.code, fileName, translateJson, metadata, referenceCache });
208
+ tasks.push({
209
+ language: item.code, fileName, translateJson, metadata,
210
+ referenceCache, blockedKeys: invalidKeys,
211
+ });
145
212
  }
146
213
  }
147
- if (plugins.length) {
148
- const prepared = [];
149
- for (const { plugin, files } of loadedReferences) {
150
- const matches = yield plugin.prepare(tasks, writableDirectories, this.noTranslate, files);
151
- if (!matches)
152
- return;
153
- prepared.push({ plugin, matches });
214
+ if (referencePlugin) {
215
+ const matches = yield referencePlugin.prepare(tasks, writableDirectories, this.noTranslate, referenceFiles);
216
+ if (!matches) {
217
+ for (const issue of invalidSources)
218
+ yield logErrorToFile(issue);
219
+ return;
154
220
  }
155
221
  fs.writeFileSync("error.log", "", "utf8");
156
- // 所有参考匹配预览通过后,才写入比对基准。
157
- for (const baseline of baselines)
158
- writeReferenceCache(baseline);
222
+ for (const issue of invalidSources)
223
+ yield logErrorToFile(issue);
159
224
  const blockedByFile = new Map();
160
- for (const { plugin, matches } of prepared) {
161
- if (plugin.checkConflicts) {
162
- yield this.reviewReferences(matches, plugin.language, blockedByFile);
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;
163
255
  }
256
+ if (changed)
257
+ writeReferenceCache(cache);
164
258
  }
165
259
  for (const task of tasks) {
166
- const fileReferences = prepared.flatMap(({ plugin, matches }) => {
167
- const fileMatches = matches.get(task.fileName);
168
- return fileMatches
169
- ? [{ language: plugin.language, matches: fileMatches }]
170
- : [];
171
- });
172
- if (fileReferences.length === 1)
173
- task.reference = fileReferences[0];
174
- else if (fileReferences.length > 1)
175
- task.references = fileReferences;
176
- task.blockedKeys = blockedByFile.get(task.fileName);
177
- for (const key of (_d = task.blockedKeys) !== null && _d !== void 0 ? _d : []) {
178
- delete task.translateJson[key];
260
+ const fileMatches = matches.get(task.fileName);
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;
273
+ }
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];
179
279
  }
180
280
  }
181
- for (const emptyFile of emptyFiles) {
281
+ for (const emptyFile of emptyFiles)
182
282
  yield this.outputLanguageFile(emptyFile);
183
- }
184
283
  }
284
+ const skippedNoContent = tasks
285
+ .filter(({ translateJson }) => Object.keys(translateJson).length === 0)
286
+ .map(({ language, fileName }) => `${language}:${fileName}`);
185
287
  if (skippedNoContent.length > 0) {
186
288
  const summary = skippedNoContent.length <= 5
187
289
  ? skippedNoContent.join(", ")
@@ -245,28 +347,29 @@ export class I18nTranslateAgent {
245
347
  * @returns
246
348
  */
247
349
  this.singleTranslate = (params) => __awaiter(this, void 0, void 0, function* () {
350
+ var _a;
248
351
  const {
249
352
  /** 待翻译的语言 */
250
353
  language,
251
354
  /** 待翻译的文件名 */
252
- fileName, translateJson, multiBar, progressBar: taskProgressBar, callback, reference, references, blockedKeys, metadata, referenceCache, } = params;
355
+ fileName, translateJson, multiBar, progressBar: taskProgressBar, callback, reference, blockedKeys, conflictingKeys, metadata, referenceCache, } = params;
253
356
  try {
254
- const fileReferences = references !== null && references !== void 0 ? references : (reference ? [reference] : []);
255
357
  // 生成chat循环代码
256
358
  const promiseList = Object.entries(translateJson).map(([key, value], index) => () => {
257
- const matched = fileReferences.flatMap(({ language, matches }) => {
258
- const match = matches.get(key);
259
- return match ? [{ language, value: match.translation }] : [];
260
- });
359
+ var _a;
360
+ const match = reference === null || reference === void 0 ? void 0 : reference.matches.get(key);
261
361
  return this.translateChat({
262
362
  key,
263
363
  value,
264
364
  language,
265
365
  index,
266
366
  fileName,
267
- reference: matched.length === 1 ? matched[0] : undefined,
268
- references: matched.length > 1 ? matched : undefined,
367
+ reference: reference && match
368
+ ? { language: reference.language, value: match.translation }
369
+ : undefined,
269
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),
270
373
  });
271
374
  });
272
375
  const progressBar = taskProgressBar !== null && taskProgressBar !== void 0 ? taskProgressBar : multiBar === null || multiBar === void 0 ? void 0 : multiBar.create(promiseList.length, 0, {
@@ -274,17 +377,32 @@ export class I18nTranslateAgent {
274
377
  });
275
378
  for (const fn of promiseList) {
276
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;
277
389
  yield this.outputLanguageFile({
278
390
  jsonMap: { [result.key]: result.value },
279
391
  folderName: language,
280
392
  fileName,
281
393
  blockedKeys,
394
+ rejectedReferences,
395
+ usedReferenceId: snapshot ? Object.keys(snapshot)[0] : undefined,
282
396
  });
283
- // 译文写入成功后才更新参考快照,失败或跳过的词条留待下次处理。
284
- const snapshot = referenceCache === null || referenceCache === void 0 ? void 0 : referenceCache.current.get(result.key);
397
+ // 译文写入后同步参考快照。未采用参考时删除旧记录。
285
398
  if (referenceCache && snapshot) {
286
399
  const previous = referenceCache.observed.get(result.key);
287
- referenceCache.observed.set(result.key, Object.assign(Object.assign({}, previous), snapshot));
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)) {
288
406
  writeReferenceCache(referenceCache);
289
407
  }
290
408
  delete translateJson[result.key];
@@ -311,8 +429,8 @@ export class I18nTranslateAgent {
311
429
  * @returns
312
430
  */
313
431
  this.translateChat = (params) => __awaiter(this, void 0, void 0, function* () {
314
- var _a, _b;
315
- const { key, value, language, index, fileName, reference, references, metadata } = params;
432
+ var _a, _b, _c, _d, _e, _f, _g;
433
+ const { key, value, language, index, fileName, reference, metadata, changedReference, sourceOnly, } = params;
316
434
  try {
317
435
  const targetLanguage = this.searchLanguage(language);
318
436
  const originLanguage = this.searchLanguage(this.SOURCE_LANGUAGE);
@@ -327,41 +445,58 @@ export class I18nTranslateAgent {
327
445
  }
328
446
  if (!this.client)
329
447
  throw new Error("Connection failed");
330
- const protectedText = protectTerms(value, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, this.noTranslate);
331
- const source = (_a = protectedText === null || protectedText === void 0 ? void 0 : protectedText.text) !== null && _a !== void 0 ? _a : value;
332
- const referenceEntries = (references !== null && references !== void 0 ? references : (reference ? [reference] : [])).map(({ language, value }) => {
333
- var _a, _b;
334
- return ({
335
- referenceLanguage: (_b = (_a = SUPPORT_LANGUAGE_MAP[language]) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : language,
336
- reference: value,
337
- });
338
- });
339
- let input = source;
340
- let referenceInstruction = "";
341
- if (referenceEntries.length > 0) {
342
- referenceInstruction =
343
- ". For ambiguous words, abbreviations, and short UI labels, use the reviewed reference to determine the intended product meaning before interpreting or rewriting the source. " +
344
- "Translate that meaning using the established terminology of the target language and domain.";
345
- if (referenceEntries.length === 1) {
346
- input = JSON.stringify(Object.assign({ source }, referenceEntries[0]));
347
- }
348
- else {
349
- input = JSON.stringify({ source, references: referenceEntries });
350
- referenceInstruction += " Consider the references in the given order.";
351
- }
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");
352
451
  }
353
- const instructions = [
354
- `Please translate ${originLanguage.name} to ${targetLanguage.name}${referenceInstruction}`,
355
- ];
356
- if (metadata === null || metadata === void 0 ? void 0 : metadata.context) {
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)) {
357
479
  instructions.push(`Business context for this file: ${metadata.context}`);
358
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
+ }
359
491
  if (protectedText) {
360
492
  instructions.push("Copy each {__CC_PROTECTED_...} placeholder exactly once. Translate the surrounding text normally.");
361
493
  }
494
+ if (sourcePlaceholders.length && !isReferenceRetranslation) {
495
+ instructions.push("Keep source placeholders and rich-text tags exactly as written.");
496
+ }
362
497
  yield sleep(getRandomNumber(200, 300));
363
- const chatCompletion = yield this.client.chat.completions.create(Object.assign(Object.assign({ model: (_b = this.chatCompletionCreateParams.model) !== null && _b !== void 0 ? _b : "gpt-4o" }, this.chatCompletionCreateParams), { stream: false, messages: [
364
- ...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) => ({
365
500
  role: "system",
366
501
  content: val,
367
502
  })),
@@ -385,11 +520,23 @@ export class I18nTranslateAgent {
385
520
  throw new Error("The model did not complete the translation");
386
521
  }
387
522
  const translation = readTranslationResponse(choice === null || choice === void 0 ? void 0 : choice.message.content, source);
388
- return {
389
- key,
390
- value: protectedText ? protectedText.restore(translation) : translation,
391
- index,
392
- };
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 } : {}));
393
540
  }
394
541
  catch (error) {
395
542
  logErrorToFile({ error: error, key, fileName, language });
@@ -407,7 +554,7 @@ export class I18nTranslateAgent {
407
554
  * @param fileName
408
555
  * @returns
409
556
  */
410
- this.getTranslateContent = (language, fileName, deferredEmptyFiles, sourceEntries) => __awaiter(this, void 0, void 0, function* () {
557
+ this.getTranslateContent = (language, fileName, deferredEmptyFiles, sourceEntries, sourceCache) => __awaiter(this, void 0, void 0, function* () {
411
558
  var _a;
412
559
  const translateFilePath = path.join(this.ENTRY_ROOT_PATH, this.SOURCE_LANGUAGE, fileName);
413
560
  /** 缓存文件路径 */
@@ -417,7 +564,7 @@ export class I18nTranslateAgent {
417
564
  return;
418
565
  }
419
566
  const _b = (_a = sourceEntries !== null && sourceEntries !== void 0 ? sourceEntries : (yield readJsonFileSync(translateFilePath))) !== null && _a !== void 0 ? _a : {}, { _meta } = _b, translateFileObject = __rest(_b, ["_meta"]);
420
- const cacheObject = yield getCacheFileSync(cacheFilePath);
567
+ const cacheObject = sourceCache !== null && sourceCache !== void 0 ? sourceCache : yield getCacheFileSync(cacheFilePath);
421
568
  const diffObject = translateJSONDiffToJson(cacheObject, translateFileObject);
422
569
  if (Object.values(diffObject).length === 0) {
423
570
  if (Object.keys(translateFileObject).length === 0) {
@@ -440,7 +587,7 @@ export class I18nTranslateAgent {
440
587
  * @param {Object} jsonMap
441
588
  */
442
589
  this.outputLanguageFile = (params) => __awaiter(this, void 0, void 0, function* () {
443
- const { folderName, fileName, jsonMap, blockedKeys } = params;
590
+ const { folderName, fileName, jsonMap, blockedKeys, rejectedReferences, usedReferenceId } = params;
444
591
  const outputFilePath = path.join(this.outputPath, folderName, fileName);
445
592
  //创建输出文件夹
446
593
  notExistsToCreateFile(this.outputPath);
@@ -467,6 +614,8 @@ export class I18nTranslateAgent {
467
614
  yield registerLanguageCacheFile({
468
615
  sourceFilePath: path.join(this.ENTRY_ROOT_PATH, this.SOURCE_LANGUAGE, fileName),
469
616
  jsonMap,
617
+ rejectedReferences,
618
+ usedReferenceId,
470
619
  fileName,
471
620
  language: folderName,
472
621
  folderName: this.CACHE_ROOT_PATH,
@@ -514,19 +663,22 @@ export class I18nTranslateAgent {
514
663
  searchLanguage(code) {
515
664
  return this.supportLanguages.find((item) => item.code === code);
516
665
  }
517
- reviewReferences(matches, language, blocked) {
666
+ reviewReferences(matches, language, blocked, conflicts) {
518
667
  return __awaiter(this, void 0, void 0, function* () {
519
668
  var _a, _b, _c, _d, _e;
520
669
  let skipped = 0;
670
+ let fallbackCount = 0;
521
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;
522
672
  const referenceLanguage = (_d = (_c = SUPPORT_LANGUAGE_MAP[language]) === null || _c === void 0 ? void 0 : _c.name) !== null && _d !== void 0 ? _d : language;
523
673
  const timeout = (_e = this.openaiClientConfig.timeout) !== null && _e !== void 0 ? _e : 30000;
524
674
  const checks = Array.from(matches).flatMap(([fileName, entries]) => {
525
675
  const blockedKeys = blocked.get(fileName);
526
- const pending = Array.from(entries).filter(([key]) => !(blockedKeys === null || blockedKeys === void 0 ? void 0 : blockedKeys.has(key)));
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)));
527
678
  return pending.map(([key, { source, translation }]) => () => __awaiter(this, void 0, void 0, function* () {
528
- var _a, _b, _c;
679
+ var _a, _b;
529
680
  let issue;
681
+ let conflict = false;
530
682
  for (let attempt = 0;; attempt++) {
531
683
  const deadline = new AbortController();
532
684
  const timer = setTimeout(() => deadline.abort(), timeout);
@@ -554,11 +706,16 @@ export class I18nTranslateAgent {
554
706
  },
555
707
  ],
556
708
  }, { signal: deadline.signal, timeout, maxRetries: 0 });
557
- const verdict = (_c = (_b = response.choices[0]) === null || _b === void 0 ? void 0 : _b.message.content) === null || _c === void 0 ? void 0 : _c.trim();
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();
558
714
  if (verdict === "COMPATIBLE")
559
715
  return;
560
716
  if (verdict !== "CONFLICT")
561
717
  throw new Error("Invalid reference verdict");
718
+ conflict = true;
562
719
  issue = new Error("Reference conflict");
563
720
  break;
564
721
  }
@@ -576,13 +733,17 @@ export class I18nTranslateAgent {
576
733
  }
577
734
  yield sleep(this.taskRetryBaseDelayMs * (attempt + 1));
578
735
  }
579
- let keys = blocked.get(fileName);
736
+ const outcome = conflict ? conflicts : blocked;
737
+ let keys = outcome.get(fileName);
580
738
  if (!keys) {
581
739
  keys = new Set();
582
- blocked.set(fileName, keys);
740
+ outcome.set(fileName, keys);
583
741
  }
584
742
  keys.add(key);
585
- skipped++;
743
+ if (conflict)
744
+ fallbackCount++;
745
+ else
746
+ skipped++;
586
747
  yield logErrorToFile({ error: issue, fileName, key, language });
587
748
  }));
588
749
  });
@@ -608,6 +769,9 @@ export class I18nTranslateAgent {
608
769
  clearInterval(progressTimer);
609
770
  }
610
771
  reportProgress();
772
+ if (fallbackCount) {
773
+ console.warn(`Translating ${fallbackCount} conflicting reference entries from source. See error.log for details.`);
774
+ }
611
775
  if (skipped) {
612
776
  console.warn(`Skipped ${skipped} reference entries. See error.log for details.`);
613
777
  }