cc-translate 1.2.2 → 1.3.2

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 CHANGED
@@ -2,6 +2,61 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [Unreleased]
6
+
7
+ ### Added
8
+
9
+ - Source JSON files can define optional `_meta.context` for file-wide
10
+ business context and `_meta.noTranslate` for words or phrases that should
11
+ be preserved inside translated sentences.
12
+ - The agent accepts global `noTranslate` terms. File-level matches take
13
+ precedence when they overlap with global matches.
14
+ - Tracked reference changes retranslate only the affected keys in each target
15
+ language, even when the source text stays the same.
16
+
17
+ ## [1.3.2] - 2026-11-26
18
+
19
+ ### Fixed
20
+
21
+ - Retry responses that contain translation preambles or response labels
22
+ while allowing inline JSON examples in the translated text.
23
+ - Use NodeNext-compatible relative imports in published TypeScript declarations.
24
+
25
+ ## [1.3.1] - 2026-11-25
26
+
27
+ ### Added
28
+
29
+ - `translate()` now accepts an ordered array of reference plugins alongside
30
+ the existing single-plugin call. Available references are passed to each
31
+ translation request in array order.
32
+
33
+ ## [1.3.0] - 2026-11-25
34
+
35
+ ### Added
36
+
37
+ - Added the optional `TranslationReferencePlugin` for using a reviewed locale
38
+ as context for pending translations. It matches by filename and JSON key,
39
+ with translation eligibility determined by the existing cache.
40
+ - Added a reference coverage preview before translation. Missing files or
41
+ entries require terminal confirmation to continue with source-only
42
+ translation for those entries. Invalid reference directories and malformed
43
+ matching files stop the run.
44
+ - Added an opt-in conflict check shared across target languages
45
+ (`checkConflicts: true`). By default, translation uses the source and
46
+ matched reference directly. When enabled, conflicts and checks that fail
47
+ after retries are logged separately once per filename and key. Skipped entries
48
+ keep their existing translations and cache state. The reference locale is
49
+ read-only.
50
+
51
+ ### Changed
52
+
53
+ - Improved terminal translation progress and added a final task summary.
54
+
55
+ ### Fixed
56
+
57
+ - Added progress updates and per-request timeouts during reference conflict
58
+ checks. Entries that still time out after retries are logged and skipped.
59
+
5
60
  ## [1.0.0] - 2026-03-04
6
61
 
7
62
  ### Changed
package/README.md CHANGED
@@ -6,6 +6,7 @@ An AI-powered i18n translation tool for JSON language files.
6
6
 
7
7
  - Translate from one source language to multiple target languages.
8
8
  - Cache-based incremental translation (only changed keys are translated).
9
+ - Use a reviewed locale as optional context for ambiguous UI copy.
9
10
  - Concurrency queue with retry support for unstable API calls.
10
11
  - Real-time progress bars and final success/failure summary.
11
12
  - Cleaner logs for skipped files (`No content to translate` is aggregated).
@@ -44,6 +45,7 @@ const agent = new I18nTranslateAgent({
44
45
  "This is a crypto wallet product",
45
46
  "Keep blockchain terms consistent",
46
47
  ],
48
+ noTranslate: ["USDC", "Cozy Card"],
47
49
  chatCompletionCreateParams: {
48
50
  model: "gpt-4o",
49
51
  temperature: 0.2,
@@ -53,6 +55,116 @@ const agent = new I18nTranslateAgent({
53
55
  await agent.translate();
54
56
  ```
55
57
 
58
+ ## Optional Translation Reference
59
+
60
+ Use a reviewed locale as context for ambiguous UI copy. Initialize the plugin
61
+ with the reference language code and the directory containing its JSON files,
62
+ then pass it to the translation entry point.
63
+
64
+ ```ts
65
+ import { TranslationReferencePlugin } from "cc-translate";
66
+
67
+ const reference = new TranslationReferencePlugin({
68
+ language: "zh-CN",
69
+ directory: "./locales/zh-CN",
70
+ // checkConflicts: true, // Enable a separate conflict check.
71
+ });
72
+
73
+ await agent.translate(reference);
74
+ ```
75
+
76
+ Pass multiple plugins as an array, for example
77
+ `await agent.translate([chineseReference, frenchReference])`. Reference
78
+ matching, optional conflict checks, and reference texts in the translation
79
+ request follow the array order. Each target entry is translated once using
80
+ all the references available for that entry. An empty array runs without plugins.
81
+
82
+ The cache compares source text and tracked reference text for each target
83
+ language. Changing a reference value requeues the corresponding key even if
84
+ the source text is unchanged. A newly filled reference also requeues its key
85
+ if the key was previously tracked without a value. Clearing or deleting a
86
+ reference leaves existing translations intact.
87
+
88
+ On the first run with an old source-only cache, the current references become
89
+ the baseline for existing translations without a bulk retranslation. Reference
90
+ snapshots are saved under `<cache>/<target-language>/.references/`. Each target
91
+ updates its snapshot only after a successful translation, so failed entries
92
+ can be retried independently. The source and reference files are read-only
93
+ during translation.
94
+
95
+ Before any model calls, the plugin reports the reference language, directory,
96
+ file matches, and coverage of pending keys.
97
+
98
+ - When every pending entry has a non-empty reference, translation starts automatically.
99
+ - Missing files or entries in a reference directory trigger a terminal prompt.
100
+ If you confirm, translation uses the source and any references that matched
101
+ in other directories. Declining or running without an interactive terminal
102
+ ends the run before translation.
103
+ - A missing or unreadable reference directory, or an invalid matching JSON
104
+ file, stops the run with an error that identifies the path.
105
+
106
+ The reference locale is read-only and its language is excluded from the output
107
+ targets. By default, the translation request includes both the source text and
108
+ its matched reference. Set `checkConflicts: true` to run a separate check before
109
+ translation. Each matched reference then gets one check shared by all targets.
110
+ Clear conflicts and checks that still fail after retries receive distinct
111
+ entries in `error.log`, once per filename and key. The affected keys are skipped
112
+ across all targets and subsequent conflict checks, preserving existing
113
+ translations and leaving their cache entries unchanged for the next run.
114
+
115
+ ## File Context and Protected Terms
116
+
117
+ Add an optional `_meta` object at the top level of a **source-language** JSON
118
+ file, such as `locales/en/bots.json`.
119
+
120
+ ```json
121
+ {
122
+ "_meta": {
123
+ "context": "Trading bot settings for opening positions and configuring margin.",
124
+ "noTranslate": ["MAX", "Cozy Card"]
125
+ },
126
+ "keyword.long": "Long",
127
+ "trade.hint": "Tap MAX to use your full balance.",
128
+ "trade.max": "MAX"
129
+ }
130
+ ```
131
+
132
+ | Field | Accepted value | Behavior |
133
+ | --- | --- | --- |
134
+ | `context` | Non-blank string | Adds business context to every translation request for this file. It works alongside global `fineTune` and any matched reference translation. |
135
+ | `noTranslate` | Non-empty array of non-blank strings | Preserves the listed words or phrases in this file. Entries are terms such as `MAX` or `Cozy Card`, with case-sensitive, whole-term matching. |
136
+
137
+ Both fields are optional and validated independently. For example, a valid
138
+ `context` still applies if `noTranslate` is accidentally written as a string.
139
+ Missing or invalid metadata is ignored. The script reads metadata from the
140
+ source file and excludes `_meta` from generated translations and caches.
141
+
142
+ In the example, `trade.hint` can become `点击 MAX 使用全部余额。` in Chinese.
143
+ The surrounding sentence is translated while `MAX` is restored verbatim.
144
+ The word `maximum` can still be translated. A value that consists entirely of
145
+ a protected term, such as `trade.max`, is copied directly to the target locale.
146
+ If a model response drops or duplicates a protected placeholder, the script
147
+ uses the existing retry policy and leaves the entry pending if retries are
148
+ exhausted.
149
+
150
+ ### Global protected terms
151
+
152
+ Set `noTranslate: ["USDC", "Cozy Card"]` on `I18nTranslateAgent` to protect
153
+ these terms in every source JSON file. Keep application-wide names and symbols
154
+ in this configuration, and put file-specific terms in `_meta.noTranslate`.
155
+ Both lists use the same validation and matching rules. For a long list, keep it
156
+ in a separate project configuration file and import it into the entry script.
157
+
158
+ When matching a sentence, the script applies file rules first. Global rules
159
+ then protect any remaining matches. For example, if the global list contains
160
+ `["Cozy Card", "USDC"]` and a file lists `["Card"]`, that file protects
161
+ `Card` and `USDC`. Other files still protect the full phrase `Cozy Card`.
162
+
163
+ The cache still selects which entries are processed. Editing either list or
164
+ the context alone does not retranslate existing entries. To apply a change
165
+ to previously translated copy, clear the affected keys from the relevant
166
+ target-language caches.
167
+
56
168
  ## Directory Layout
57
169
 
58
170
  ```text
@@ -81,6 +193,7 @@ your-project/
81
193
  | `outputRootPath` | `string` | No | Output directory, defaults to `fileRootPath` |
82
194
  | `concurrency` | `number` | No | Queue length, default `8` |
83
195
  | `fineTune` | `string[]` | No | Extra translation context lines |
196
+ | `noTranslate` | `readonly string[]` | No | Terms preserved across source files. File-level matches take precedence where they overlap. |
84
197
  | `chatCompletionCreateParams` | `Partial<ChatCompletionCreateParams>` | No | Extra chat completion params |
85
198
 
86
199
  ### Utility Exports
@@ -103,4 +216,4 @@ See `CHANGELOG.md`.
103
216
 
104
217
  ## License
105
218
 
106
- ISC
219
+ ISC
package/index.d.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  import { ClientOptions, OpenAI } from "openai";
2
- import { II18nTranslateAgentParams, IJson, IOutputLanguageFile, ISingleTranslate, ITranslateChat, ITranslateChatResponse, SupportLanguageType } from "./types";
2
+ import { II18nTranslateAgentParams, IJson, IOutputLanguageFile, ISingleTranslate, ITranslateChat, ITranslateChatResponse, SupportLanguageType } from "./types/index.js";
3
+ import { TranslationReferencePlugin } from "./lib/translation-reference.js";
3
4
  import { ChatCompletionCreateParams } from "openai/resources";
4
5
  export { generateCache, deleteBatchCache } from "./lib/cache/index.js";
6
+ export { TranslationReferencePlugin };
7
+ export type { TranslationReferenceOptions } from "./lib/translation-reference.js";
5
8
  export declare class I18nTranslateAgent {
6
9
  /** 缓存文件根路径 */
7
10
  CACHE_ROOT_PATH: string;
@@ -18,6 +21,7 @@ export declare class I18nTranslateAgent {
18
21
  client: OpenAI | null;
19
22
  /** 微调模型 */
20
23
  fineTune: string[];
24
+ readonly noTranslate?: readonly string[];
21
25
  /** 翻译任务并发数(队列长度),完成一个即取下一个 */
22
26
  concurrency: number;
23
27
  /** openai 客户端配置 */
@@ -29,17 +33,18 @@ export declare class I18nTranslateAgent {
29
33
  taskRetryBaseDelayMs: number;
30
34
  constructor(params: II18nTranslateAgentParams);
31
35
  /** 支持翻译的语言列表 */
32
- get supportLanguages(): import("./types").ILanguage[];
36
+ get supportLanguages(): import("./types/index.js").ILanguage[];
33
37
  /** 输出文件根路径 */
34
38
  get outputPath(): string;
35
39
  /** 搜索语言 */
36
- searchLanguage(code: SupportLanguageType): import("./types").ILanguage | undefined;
40
+ searchLanguage(code: SupportLanguageType): import("./types/index.js").ILanguage | undefined;
37
41
  /** 创建openai客户端 */
38
42
  createOpenAIClient: () => void;
39
43
  /**
40
44
  * 翻译入口文件的所有支持的语言文件夹和其中的文件
41
45
  */
42
- translate: () => Promise<void>;
46
+ translate: (referencePlugins?: TranslationReferencePlugin | readonly TranslationReferencePlugin[]) => Promise<void>;
47
+ private reviewReferences;
43
48
  /**
44
49
  * 翻译单个文件
45
50
  * @param params
@@ -61,7 +66,7 @@ export declare class I18nTranslateAgent {
61
66
  * @param fileName
62
67
  * @returns
63
68
  */
64
- getTranslateContent: (language: SupportLanguageType, fileName: string) => Promise<IJson | undefined>;
69
+ getTranslateContent: (language: SupportLanguageType, fileName: string, deferredEmptyFiles?: IOutputLanguageFile[], sourceEntries?: IJson) => Promise<IJson | undefined>;
65
70
  /**
66
71
  * 输出语言文件
67
72
  * @param {Object} jsonMap