@verbaly/compiler 0.38.0 → 0.39.0
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/README.md +23 -3
- package/dist/{claude-CrAkiSVP.js → claude-0MJOMelz.js} +27 -8
- package/dist/claude-0MJOMelz.js.map +1 -0
- package/dist/{claude-h9WA0ppg.js → claude-ByRATJ03.js} +26 -7
- package/dist/claude-ByRATJ03.js.map +1 -0
- package/dist/cli.js +154 -33
- package/dist/cli.js.map +1 -1
- package/dist/{config-D8gkaunO.js → config-pSOnS9OZ.js} +12 -2
- package/dist/config-pSOnS9OZ.js.map +1 -0
- package/dist/index.d.ts +65 -1
- package/dist/index.js +547 -18
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/dist/claude-CrAkiSVP.js.map +0 -1
- package/dist/claude-h9WA0ppg.js.map +0 -1
- package/dist/config-D8gkaunO.js.map +0 -1
package/README.md
CHANGED
|
@@ -67,6 +67,23 @@ Hand-edited catalogs get the same treatment as imported files: the gate does not
|
|
|
67
67
|
|
|
68
68
|
`verbaly translate` fills the `""` holes `check` reports. The default provider uses Claude via the official SDK; install it as a dev dependency (translation is a build-time step, not an app runtime dependency): `pnpm add -D @anthropic-ai/sdk` (or `npm i -D`), plus `ANTHROPIC_API_KEY`. Default model is `claude-sonnet-5` (balanced quality/cost); override with `translate.model` in config or `--model <id>`. Placeholders, variants and tags are validated after translation: anything not preserved verbatim stays `""` so `check` keeps failing.
|
|
69
69
|
|
|
70
|
+
Long runs survive the network. Batches go out in parallel (`translate.concurrency`, default 4), a transient failure is retried (`translate.retries`, default 2), and a batch that still does not answer is reported with its keys while every batch that did answer is written: re-running asks only for what is left.
|
|
71
|
+
|
|
72
|
+
Two config options steer the wording. `translate.instructions` is free text appended to the system prompt (tone, address form, product voice), and `translate.glossary` states how a term has to come out, for all locales or per locale, so a brand name never comes back translated:
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
export default {
|
|
76
|
+
sourceLocale: 'en',
|
|
77
|
+
locales: ['en', 'es', 'pt'],
|
|
78
|
+
translate: {
|
|
79
|
+
instructions: 'Address the reader informally. Keep UI labels short.',
|
|
80
|
+
glossary: { Verbaly: 'Verbaly', checkout: { es: 'pago', pt: 'pagamento' } },
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Only the terms a batch actually contains are sent, so a glossary of hundreds never becomes the prompt.
|
|
86
|
+
|
|
70
87
|
**Machine output is a draft until a human says yes.** Everything `translate` writes is recorded in `locales/.verbaly-drafts.json` (commit it, never edit it by hand). `verbaly review` lists the drafts, `--approve` accepts them, and importing a translator's file clears the flag because a human already reviewed it. `verbaly check --drafts` turns "nothing unreviewed ships" into a CI rule; plain `check` leaves it alone, since a draft has a value and is therefore not missing.
|
|
71
88
|
|
|
72
89
|
Plug your own provider in `verbaly.config.ts`. In TypeScript, `TranslateProvider` types it for you:
|
|
@@ -74,8 +91,9 @@ Plug your own provider in `verbaly.config.ts`. In TypeScript, `TranslateProvider
|
|
|
74
91
|
```ts
|
|
75
92
|
import type { TranslateProvider } from '@verbaly/compiler';
|
|
76
93
|
|
|
77
|
-
const provider: TranslateProvider = async ({
|
|
94
|
+
const provider: TranslateProvider = async ({ targetLocale, messages, origins, glossary }) => {
|
|
78
95
|
// origins maps a key to the source files it appears in, so you can translate with context
|
|
96
|
+
// glossary and instructions ride along too: a custom provider gets the same steering
|
|
79
97
|
return { ...translated };
|
|
80
98
|
};
|
|
81
99
|
|
|
@@ -137,7 +155,7 @@ The package exports two layers, and **nothing else is public**. Anything you can
|
|
|
137
155
|
|
|
138
156
|
**Your project's own types**, for a typed config file or a custom provider:
|
|
139
157
|
|
|
140
|
-
`VerbalyConfig` · `ResolvedConfig` · `RenderConfig` · `RedirectConfig` · `TranslateConfig` · `TranslateProvider` · `TranslateRequest` · `TranslateResult` · `TranslateOptions`
|
|
158
|
+
`VerbalyConfig` · `ResolvedConfig` · `RenderConfig` · `RedirectConfig` · `TranslateConfig` · `GlossaryEntry` · `TranslateProvider` · `TranslateRequest` · `TranslateResult` · `TranslateOptions` · `TranslateProgress` · `TranslateFailure`
|
|
141
159
|
|
|
142
160
|
**Building an integration.** This is exactly what `@verbaly/vite`, `@verbaly/unplugin`, `@verbaly/next`, `@verbaly/astro`, `@verbaly/nuxt` and `@verbaly/mcp` consume, so a third one has everything they have:
|
|
143
161
|
|
|
@@ -150,7 +168,9 @@ The package exports two layers, and **nothing else is public**. Anything you can
|
|
|
150
168
|
| The gate | `check` `formatCheckResult` `formatCheckWarnings` · types `CheckResult` `MissingEntry` `UnknownEntry` `BrokenEntry` `IssueSeverity` |
|
|
151
169
|
| Coverage | `status` `formatStatusResult` `counted` · types `StatusResult` `LocaleStatus` |
|
|
152
170
|
| Draft review | `loadDrafts` `saveDrafts` `markDrafts` `effectiveDrafts` · type `Drafts` |
|
|
153
|
-
| Translation | `translateCatalogs` `resolveProvider`
|
|
171
|
+
| Translation | `translateCatalogs` `resolveProvider` `formatTranslateFailures` |
|
|
172
|
+
| Diagnosis | `doctor` `formatDoctorEntry` · types `DoctorResult` `DoctorEntry` |
|
|
173
|
+
| Onboarding | `wrapProject` · types `WrapResult` `WrapEntry` `WrapSkip` `WrapOptions` |
|
|
154
174
|
| Static rendering | `renderSite` · types `RenderSiteOptions` `RenderSiteResult` |
|
|
155
175
|
|
|
156
176
|
A minimal plugin is `loadConfig` + `loadCatalogs` once, then `transformSource` per file and `runBuildGate` at the end:
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as isModuleNotFound } from "./config-pSOnS9OZ.js";
|
|
2
2
|
//#region src/providers/claude.ts
|
|
3
3
|
const DEFAULT_MODEL = "claude-sonnet-5";
|
|
4
4
|
const SYSTEM = `You translate UI strings for the Verbaly i18n library.
|
|
@@ -6,26 +6,45 @@ Rules:
|
|
|
6
6
|
- Translate only the human-readable text, naturally for the target locale.
|
|
7
7
|
- Preserve verbatim: placeholders like {name}, format specs like {price:currency/EUR}, variant blocks like {count | one: ... | other: # ...} (translate only the text inside each variant, keep keys and # as-is), ICU syntax, named tags like <em>...</em> and escapes {{ }} || ##.
|
|
8
8
|
- Keys are opaque identifiers: return exactly the same keys, never translate or rename them.`;
|
|
9
|
+
function systemPrompt(instructions) {
|
|
10
|
+
return instructions ? `${SYSTEM}\n\nProject instructions:\n${instructions}` : SYSTEM;
|
|
11
|
+
}
|
|
9
12
|
function claudeProvider(options = {}) {
|
|
13
|
+
let client;
|
|
10
14
|
return async (request) => {
|
|
11
|
-
|
|
15
|
+
client ??= loadSdk().then((Anthropic) => new Anthropic(options.apiKey ? { apiKey: options.apiKey } : {}));
|
|
16
|
+
const response = await (await client).messages.create({
|
|
12
17
|
model: options.model ?? DEFAULT_MODEL,
|
|
13
18
|
max_tokens: options.maxTokens ?? 16e3,
|
|
14
19
|
thinking: { type: "disabled" },
|
|
15
|
-
system:
|
|
20
|
+
system: systemPrompt(request.instructions),
|
|
16
21
|
messages: [{
|
|
17
22
|
role: "user",
|
|
18
23
|
content: buildPrompt(request)
|
|
19
24
|
}],
|
|
20
25
|
output_config: { format: batchFormat(request) }
|
|
21
|
-
})
|
|
22
|
-
|
|
26
|
+
});
|
|
27
|
+
if (response.stop_reason === "max_tokens") throw new Error(`[verbaly] the model ran out of output room on a batch of ${Object.keys(request.messages).length} messages: lower translate.batchSize (or raise maxTokens on the provider)`);
|
|
28
|
+
const text = response.content.find((block) => block.type === "text")?.text ?? "{}";
|
|
29
|
+
try {
|
|
30
|
+
return JSON.parse(text);
|
|
31
|
+
} catch (error) {
|
|
32
|
+
throw new Error("[verbaly] the model did not answer with the JSON object it was asked for", { cause: error });
|
|
33
|
+
}
|
|
23
34
|
};
|
|
24
35
|
}
|
|
25
36
|
function buildPrompt(request) {
|
|
37
|
+
return `Translate each value from "${request.sourceLocale}" to "${request.targetLocale}". Return a JSON object with the same keys and translated values.\n\n` + JSON.stringify(request.messages, null, 2) + glossarySection(request) + originsSection(request);
|
|
38
|
+
}
|
|
39
|
+
function glossarySection(request) {
|
|
40
|
+
const glossary = request.glossary;
|
|
41
|
+
if (!glossary || Object.keys(glossary).length === 0) return "";
|
|
42
|
+
return `\n\nGlossary, these renderings are required wherever the term appears:\n${Object.entries(glossary).map(([term, rendering]) => ` ${term} -> ${rendering}`).join("\n")}`;
|
|
43
|
+
}
|
|
44
|
+
function originsSection(request) {
|
|
26
45
|
const origins = request.origins;
|
|
27
|
-
|
|
28
|
-
return
|
|
46
|
+
if (!origins || Object.keys(origins).length === 0) return "";
|
|
47
|
+
return `\n\nWhere each string appears (context for tone and length, do not translate these paths):\n${Object.entries(origins).map(([key, files]) => ` ${key}: ${files.join(", ")}`).join("\n")}`;
|
|
29
48
|
}
|
|
30
49
|
function batchFormat(request) {
|
|
31
50
|
const keys = Object.keys(request.messages);
|
|
@@ -50,4 +69,4 @@ async function loadSdk(load = () => import("@anthropic-ai/sdk")) {
|
|
|
50
69
|
//#endregion
|
|
51
70
|
export { claudeProvider };
|
|
52
71
|
|
|
53
|
-
//# sourceMappingURL=claude-
|
|
72
|
+
//# sourceMappingURL=claude-0MJOMelz.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claude-0MJOMelz.js","names":[],"sources":["../src/providers/claude.ts"],"sourcesContent":["import { isModuleNotFound } from '../config';\nimport type { TranslateProvider, TranslateRequest } from '../translate';\n\nexport interface ClaudeProviderOptions {\n model?: string;\n apiKey?: string;\n maxTokens?: number;\n}\n\n// balanced default for translation\nconst DEFAULT_MODEL = 'claude-sonnet-5';\n\nconst SYSTEM = `You translate UI strings for the Verbaly i18n library.\nRules:\n- Translate only the human-readable text, naturally for the target locale.\n- Preserve verbatim: placeholders like {name}, format specs like {price:currency/EUR}, variant blocks like {count | one: ... | other: # ...} (translate only the text inside each variant, keep keys and # as-is), ICU syntax, named tags like <em>...</em> and escapes {{ }} || ##.\n- Keys are opaque identifiers: return exactly the same keys, never translate or rename them.`;\n\nexport function systemPrompt(instructions?: string): string {\n return instructions ? `${SYSTEM}\\n\\nProject instructions:\\n${instructions}` : SYSTEM;\n}\n\nexport function claudeProvider(options: ClaudeProviderOptions = {}): TranslateProvider {\n // one client per provider: a batch is a request, not a reason to rebuild the transport\n let client: Promise<InstanceType<typeof import('@anthropic-ai/sdk').default>> | undefined;\n\n return async (request: TranslateRequest) => {\n client ??= loadSdk().then(\n (Anthropic) => new Anthropic(options.apiKey ? { apiKey: options.apiKey } : {}),\n );\n const response = await (\n await client\n ).messages.create({\n model: options.model ?? DEFAULT_MODEL,\n max_tokens: options.maxTokens ?? 16000,\n thinking: { type: 'disabled' },\n system: systemPrompt(request.instructions),\n messages: [{ role: 'user', content: buildPrompt(request) }],\n output_config: { format: batchFormat(request) },\n });\n if (response.stop_reason === 'max_tokens') {\n throw new Error(\n `[verbaly] the model ran out of output room on a batch of ${Object.keys(request.messages).length} messages: lower translate.batchSize (or raise maxTokens on the provider)`,\n );\n }\n const text = response.content.find((block) => block.type === 'text')?.text ?? '{}';\n try {\n return JSON.parse(text) as Record<string, string>;\n } catch (error) {\n throw new Error('[verbaly] the model did not answer with the JSON object it was asked for', {\n cause: error,\n });\n }\n };\n}\n\nexport function buildPrompt(request: TranslateRequest): string {\n return (\n `Translate each value from \"${request.sourceLocale}\" to \"${request.targetLocale}\". ` +\n `Return a JSON object with the same keys and translated values.\\n\\n` +\n JSON.stringify(request.messages, null, 2) +\n glossarySection(request) +\n originsSection(request)\n );\n}\n\n// the glossary is a requirement, not a hint: it exists because a brand name came back translated\nfunction glossarySection(request: TranslateRequest): string {\n const glossary = request.glossary;\n if (!glossary || Object.keys(glossary).length === 0) return '';\n const lines = Object.entries(glossary).map(([term, rendering]) => ` ${term} -> ${rendering}`);\n return `\\n\\nGlossary, these renderings are required wherever the term appears:\\n${lines.join('\\n')}`;\n}\n\nfunction originsSection(request: TranslateRequest): string {\n const origins = request.origins;\n if (!origins || Object.keys(origins).length === 0) return '';\n const lines = Object.entries(origins).map(([key, files]) => ` ${key}: ${files.join(', ')}`);\n return `\\n\\nWhere each string appears (context for tone and length, do not translate these paths):\\n${lines.join('\\n')}`;\n}\n\nexport function batchFormat(request: TranslateRequest) {\n const keys = Object.keys(request.messages);\n return {\n type: 'json_schema' as const,\n schema: {\n type: 'object',\n properties: Object.fromEntries(keys.map((key) => [key, { type: 'string' }])),\n required: keys,\n additionalProperties: false,\n },\n };\n}\n\ntype SdkModule = { default: typeof import('@anthropic-ai/sdk').default };\n\n// injectable for tests\nexport async function loadSdk(\n load: () => Promise<SdkModule> = () => import('@anthropic-ai/sdk'),\n): Promise<SdkModule['default']> {\n try {\n const mod = await load();\n return mod.default;\n } catch (error) {\n if (isModuleNotFound(error, '@anthropic-ai/sdk')) {\n throw new Error(\n '[verbaly] the claude translate provider needs @anthropic-ai/sdk: install it as a dev dependency (e.g. `pnpm add -D @anthropic-ai/sdk` / `npm i -D @anthropic-ai/sdk`) and set ANTHROPIC_API_KEY',\n { cause: error },\n );\n }\n throw error;\n }\n}\n"],"mappings":";;AAUA,MAAM,gBAAgB;AAEtB,MAAM,SAAS;;;;;AAMf,SAAgB,aAAa,cAA+B;CAC1D,OAAO,eAAe,GAAG,OAAO,6BAA6B,iBAAiB;AAChF;AAEA,SAAgB,eAAe,UAAiC,CAAC,GAAsB;CAErF,IAAI;CAEJ,OAAO,OAAO,YAA8B;EAC1C,WAAW,QAAQ,CAAC,CAAC,MAClB,cAAc,IAAI,UAAU,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC,CAAC,CAC/E;EACA,MAAM,WAAW,OACf,MAAM,OAAA,CACN,SAAS,OAAO;GAChB,OAAO,QAAQ,SAAS;GACxB,YAAY,QAAQ,aAAa;GACjC,UAAU,EAAE,MAAM,WAAW;GAC7B,QAAQ,aAAa,QAAQ,YAAY;GACzC,UAAU,CAAC;IAAE,MAAM;IAAQ,SAAS,YAAY,OAAO;GAAE,CAAC;GAC1D,eAAe,EAAE,QAAQ,YAAY,OAAO,EAAE;EAChD,CAAC;EACD,IAAI,SAAS,gBAAgB,cAC3B,MAAM,IAAI,MACR,4DAA4D,OAAO,KAAK,QAAQ,QAAQ,CAAC,CAAC,OAAO,0EACnG;EAEF,MAAM,OAAO,SAAS,QAAQ,MAAM,UAAU,MAAM,SAAS,MAAM,CAAC,EAAE,QAAQ;EAC9E,IAAI;GACF,OAAO,KAAK,MAAM,IAAI;EACxB,SAAS,OAAO;GACd,MAAM,IAAI,MAAM,4EAA4E,EAC1F,OAAO,MACT,CAAC;EACH;CACF;AACF;AAEA,SAAgB,YAAY,SAAmC;CAC7D,OACE,8BAA8B,QAAQ,aAAa,QAAQ,QAAQ,aAAa,yEAEhF,KAAK,UAAU,QAAQ,UAAU,MAAM,CAAC,IACxC,gBAAgB,OAAO,IACvB,eAAe,OAAO;AAE1B;AAGA,SAAS,gBAAgB,SAAmC;CAC1D,MAAM,WAAW,QAAQ;CACzB,IAAI,CAAC,YAAY,OAAO,KAAK,QAAQ,CAAC,CAAC,WAAW,GAAG,OAAO;CAE5D,OAAO,2EADO,OAAO,QAAQ,QAAQ,CAAC,CAAC,KAAK,CAAC,MAAM,eAAe,KAAK,KAAK,MAAM,WACI,CAAC,CAAC,KAAK,IAAI;AACnG;AAEA,SAAS,eAAe,SAAmC;CACzD,MAAM,UAAU,QAAQ;CACxB,IAAI,CAAC,WAAW,OAAO,KAAK,OAAO,CAAC,CAAC,WAAW,GAAG,OAAO;CAE1D,OAAO,+FADO,OAAO,QAAQ,OAAO,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,KAAK,IAAI,IAAI,MAAM,KAAK,IAAI,GACkB,CAAC,CAAC,KAAK,IAAI;AACvH;AAEA,SAAgB,YAAY,SAA2B;CACrD,MAAM,OAAO,OAAO,KAAK,QAAQ,QAAQ;CACzC,OAAO;EACL,MAAM;EACN,QAAQ;GACN,MAAM;GACN,YAAY,OAAO,YAAY,KAAK,KAAK,QAAQ,CAAC,KAAK,EAAE,MAAM,SAAS,CAAC,CAAC,CAAC;GAC3E,UAAU;GACV,sBAAsB;EACxB;CACF;AACF;AAKA,eAAsB,QACpB,aAAuC,OAAO,sBACf;CAC/B,IAAI;EAEF,QAAO,MADW,KAAK,EAAA,CACZ;CACb,SAAS,OAAO;EACd,IAAI,iBAAiB,OAAO,mBAAmB,GAC7C,MAAM,IAAI,MACR,mMACA,EAAE,OAAO,MAAM,CACjB;EAEF,MAAM;CACR;AACF"}
|
|
@@ -6,26 +6,45 @@ Rules:
|
|
|
6
6
|
- Translate only the human-readable text, naturally for the target locale.
|
|
7
7
|
- Preserve verbatim: placeholders like {name}, format specs like {price:currency/EUR}, variant blocks like {count | one: ... | other: # ...} (translate only the text inside each variant, keep keys and # as-is), ICU syntax, named tags like <em>...</em> and escapes {{ }} || ##.
|
|
8
8
|
- Keys are opaque identifiers: return exactly the same keys, never translate or rename them.`;
|
|
9
|
+
function systemPrompt(instructions) {
|
|
10
|
+
return instructions ? `${SYSTEM}\n\nProject instructions:\n${instructions}` : SYSTEM;
|
|
11
|
+
}
|
|
9
12
|
function claudeProvider(options = {}) {
|
|
13
|
+
let client;
|
|
10
14
|
return async (request) => {
|
|
11
|
-
|
|
15
|
+
client ??= loadSdk().then((Anthropic) => new Anthropic(options.apiKey ? { apiKey: options.apiKey } : {}));
|
|
16
|
+
const response = await (await client).messages.create({
|
|
12
17
|
model: options.model ?? DEFAULT_MODEL,
|
|
13
18
|
max_tokens: options.maxTokens ?? 16e3,
|
|
14
19
|
thinking: { type: "disabled" },
|
|
15
|
-
system:
|
|
20
|
+
system: systemPrompt(request.instructions),
|
|
16
21
|
messages: [{
|
|
17
22
|
role: "user",
|
|
18
23
|
content: buildPrompt(request)
|
|
19
24
|
}],
|
|
20
25
|
output_config: { format: batchFormat(request) }
|
|
21
|
-
})
|
|
22
|
-
|
|
26
|
+
});
|
|
27
|
+
if (response.stop_reason === "max_tokens") throw new Error(`[verbaly] the model ran out of output room on a batch of ${Object.keys(request.messages).length} messages: lower translate.batchSize (or raise maxTokens on the provider)`);
|
|
28
|
+
const text = response.content.find((block) => block.type === "text")?.text ?? "{}";
|
|
29
|
+
try {
|
|
30
|
+
return JSON.parse(text);
|
|
31
|
+
} catch (error) {
|
|
32
|
+
throw new Error("[verbaly] the model did not answer with the JSON object it was asked for", { cause: error });
|
|
33
|
+
}
|
|
23
34
|
};
|
|
24
35
|
}
|
|
25
36
|
function buildPrompt(request) {
|
|
37
|
+
return `Translate each value from "${request.sourceLocale}" to "${request.targetLocale}". Return a JSON object with the same keys and translated values.\n\n` + JSON.stringify(request.messages, null, 2) + glossarySection(request) + originsSection(request);
|
|
38
|
+
}
|
|
39
|
+
function glossarySection(request) {
|
|
40
|
+
const glossary = request.glossary;
|
|
41
|
+
if (!glossary || Object.keys(glossary).length === 0) return "";
|
|
42
|
+
return `\n\nGlossary, these renderings are required wherever the term appears:\n${Object.entries(glossary).map(([term, rendering]) => ` ${term} -> ${rendering}`).join("\n")}`;
|
|
43
|
+
}
|
|
44
|
+
function originsSection(request) {
|
|
26
45
|
const origins = request.origins;
|
|
27
|
-
|
|
28
|
-
return
|
|
46
|
+
if (!origins || Object.keys(origins).length === 0) return "";
|
|
47
|
+
return `\n\nWhere each string appears (context for tone and length, do not translate these paths):\n${Object.entries(origins).map(([key, files]) => ` ${key}: ${files.join(", ")}`).join("\n")}`;
|
|
29
48
|
}
|
|
30
49
|
function batchFormat(request) {
|
|
31
50
|
const keys = Object.keys(request.messages);
|
|
@@ -50,4 +69,4 @@ async function loadSdk(load = () => import("@anthropic-ai/sdk")) {
|
|
|
50
69
|
//#endregion
|
|
51
70
|
export { claudeProvider };
|
|
52
71
|
|
|
53
|
-
//# sourceMappingURL=claude-
|
|
72
|
+
//# sourceMappingURL=claude-ByRATJ03.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claude-ByRATJ03.js","names":[],"sources":["../src/providers/claude.ts"],"sourcesContent":["import { isModuleNotFound } from '../config';\nimport type { TranslateProvider, TranslateRequest } from '../translate';\n\nexport interface ClaudeProviderOptions {\n model?: string;\n apiKey?: string;\n maxTokens?: number;\n}\n\n// balanced default for translation\nconst DEFAULT_MODEL = 'claude-sonnet-5';\n\nconst SYSTEM = `You translate UI strings for the Verbaly i18n library.\nRules:\n- Translate only the human-readable text, naturally for the target locale.\n- Preserve verbatim: placeholders like {name}, format specs like {price:currency/EUR}, variant blocks like {count | one: ... | other: # ...} (translate only the text inside each variant, keep keys and # as-is), ICU syntax, named tags like <em>...</em> and escapes {{ }} || ##.\n- Keys are opaque identifiers: return exactly the same keys, never translate or rename them.`;\n\nexport function systemPrompt(instructions?: string): string {\n return instructions ? `${SYSTEM}\\n\\nProject instructions:\\n${instructions}` : SYSTEM;\n}\n\nexport function claudeProvider(options: ClaudeProviderOptions = {}): TranslateProvider {\n // one client per provider: a batch is a request, not a reason to rebuild the transport\n let client: Promise<InstanceType<typeof import('@anthropic-ai/sdk').default>> | undefined;\n\n return async (request: TranslateRequest) => {\n client ??= loadSdk().then(\n (Anthropic) => new Anthropic(options.apiKey ? { apiKey: options.apiKey } : {}),\n );\n const response = await (\n await client\n ).messages.create({\n model: options.model ?? DEFAULT_MODEL,\n max_tokens: options.maxTokens ?? 16000,\n thinking: { type: 'disabled' },\n system: systemPrompt(request.instructions),\n messages: [{ role: 'user', content: buildPrompt(request) }],\n output_config: { format: batchFormat(request) },\n });\n if (response.stop_reason === 'max_tokens') {\n throw new Error(\n `[verbaly] the model ran out of output room on a batch of ${Object.keys(request.messages).length} messages: lower translate.batchSize (or raise maxTokens on the provider)`,\n );\n }\n const text = response.content.find((block) => block.type === 'text')?.text ?? '{}';\n try {\n return JSON.parse(text) as Record<string, string>;\n } catch (error) {\n throw new Error('[verbaly] the model did not answer with the JSON object it was asked for', {\n cause: error,\n });\n }\n };\n}\n\nexport function buildPrompt(request: TranslateRequest): string {\n return (\n `Translate each value from \"${request.sourceLocale}\" to \"${request.targetLocale}\". ` +\n `Return a JSON object with the same keys and translated values.\\n\\n` +\n JSON.stringify(request.messages, null, 2) +\n glossarySection(request) +\n originsSection(request)\n );\n}\n\n// the glossary is a requirement, not a hint: it exists because a brand name came back translated\nfunction glossarySection(request: TranslateRequest): string {\n const glossary = request.glossary;\n if (!glossary || Object.keys(glossary).length === 0) return '';\n const lines = Object.entries(glossary).map(([term, rendering]) => ` ${term} -> ${rendering}`);\n return `\\n\\nGlossary, these renderings are required wherever the term appears:\\n${lines.join('\\n')}`;\n}\n\nfunction originsSection(request: TranslateRequest): string {\n const origins = request.origins;\n if (!origins || Object.keys(origins).length === 0) return '';\n const lines = Object.entries(origins).map(([key, files]) => ` ${key}: ${files.join(', ')}`);\n return `\\n\\nWhere each string appears (context for tone and length, do not translate these paths):\\n${lines.join('\\n')}`;\n}\n\nexport function batchFormat(request: TranslateRequest) {\n const keys = Object.keys(request.messages);\n return {\n type: 'json_schema' as const,\n schema: {\n type: 'object',\n properties: Object.fromEntries(keys.map((key) => [key, { type: 'string' }])),\n required: keys,\n additionalProperties: false,\n },\n };\n}\n\ntype SdkModule = { default: typeof import('@anthropic-ai/sdk').default };\n\n// injectable for tests\nexport async function loadSdk(\n load: () => Promise<SdkModule> = () => import('@anthropic-ai/sdk'),\n): Promise<SdkModule['default']> {\n try {\n const mod = await load();\n return mod.default;\n } catch (error) {\n if (isModuleNotFound(error, '@anthropic-ai/sdk')) {\n throw new Error(\n '[verbaly] the claude translate provider needs @anthropic-ai/sdk: install it as a dev dependency (e.g. `pnpm add -D @anthropic-ai/sdk` / `npm i -D @anthropic-ai/sdk`) and set ANTHROPIC_API_KEY',\n { cause: error },\n );\n }\n throw error;\n }\n}\n"],"mappings":";;AAUA,MAAM,gBAAgB;AAEtB,MAAM,SAAS;;;;;AAMf,SAAgB,aAAa,cAA+B;CAC1D,OAAO,eAAe,GAAG,OAAO,6BAA6B,iBAAiB;AAChF;AAEA,SAAgB,eAAe,UAAiC,CAAC,GAAsB;CAErF,IAAI;CAEJ,OAAO,OAAO,YAA8B;EAC1C,WAAW,QAAQ,CAAC,CAAC,MAClB,cAAc,IAAI,UAAU,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC,CAAC,CAC/E;EACA,MAAM,WAAW,OACf,MAAM,OAAA,CACN,SAAS,OAAO;GAChB,OAAO,QAAQ,SAAS;GACxB,YAAY,QAAQ,aAAa;GACjC,UAAU,EAAE,MAAM,WAAW;GAC7B,QAAQ,aAAa,QAAQ,YAAY;GACzC,UAAU,CAAC;IAAE,MAAM;IAAQ,SAAS,YAAY,OAAO;GAAE,CAAC;GAC1D,eAAe,EAAE,QAAQ,YAAY,OAAO,EAAE;EAChD,CAAC;EACD,IAAI,SAAS,gBAAgB,cAC3B,MAAM,IAAI,MACR,4DAA4D,OAAO,KAAK,QAAQ,QAAQ,CAAC,CAAC,OAAO,0EACnG;EAEF,MAAM,OAAO,SAAS,QAAQ,MAAM,UAAU,MAAM,SAAS,MAAM,CAAC,EAAE,QAAQ;EAC9E,IAAI;GACF,OAAO,KAAK,MAAM,IAAI;EACxB,SAAS,OAAO;GACd,MAAM,IAAI,MAAM,4EAA4E,EAC1F,OAAO,MACT,CAAC;EACH;CACF;AACF;AAEA,SAAgB,YAAY,SAAmC;CAC7D,OACE,8BAA8B,QAAQ,aAAa,QAAQ,QAAQ,aAAa,yEAEhF,KAAK,UAAU,QAAQ,UAAU,MAAM,CAAC,IACxC,gBAAgB,OAAO,IACvB,eAAe,OAAO;AAE1B;AAGA,SAAS,gBAAgB,SAAmC;CAC1D,MAAM,WAAW,QAAQ;CACzB,IAAI,CAAC,YAAY,OAAO,KAAK,QAAQ,CAAC,CAAC,WAAW,GAAG,OAAO;CAE5D,OAAO,2EADO,OAAO,QAAQ,QAAQ,CAAC,CAAC,KAAK,CAAC,MAAM,eAAe,KAAK,KAAK,MAAM,WACI,CAAC,CAAC,KAAK,IAAI;AACnG;AAEA,SAAS,eAAe,SAAmC;CACzD,MAAM,UAAU,QAAQ;CACxB,IAAI,CAAC,WAAW,OAAO,KAAK,OAAO,CAAC,CAAC,WAAW,GAAG,OAAO;CAE1D,OAAO,+FADO,OAAO,QAAQ,OAAO,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,KAAK,IAAI,IAAI,MAAM,KAAK,IAAI,GACkB,CAAC,CAAC,KAAK,IAAI;AACvH;AAEA,SAAgB,YAAY,SAA2B;CACrD,MAAM,OAAO,OAAO,KAAK,QAAQ,QAAQ;CACzC,OAAO;EACL,MAAM;EACN,QAAQ;GACN,MAAM;GACN,YAAY,OAAO,YAAY,KAAK,KAAK,QAAQ,CAAC,KAAK,EAAE,MAAM,SAAS,CAAC,CAAC,CAAC;GAC3E,UAAU;GACV,sBAAsB;EACxB;CACF;AACF;AAKA,eAAsB,QACpB,aAAuC,OAAO,sBACf;CAC/B,IAAI;EAEF,QAAO,MADW,KAAK,EAAA,CACZ;CACb,SAAS,OAAO;EACd,IAAI,iBAAiB,OAAO,mBAAmB,GAC7C,MAAM,IAAI,MACR,mMACA,EAAE,OAAO,MAAM,CACjB;EAEF,MAAM;CACR;AACF"}
|
package/dist/cli.js
CHANGED
|
@@ -1396,6 +1396,16 @@ function counted(count, noun, many = `${noun}s`) {
|
|
|
1396
1396
|
//#endregion
|
|
1397
1397
|
//#region src/doctor.ts
|
|
1398
1398
|
const PREVIEW = 5;
|
|
1399
|
+
const ICON = {
|
|
1400
|
+
ok: "✓",
|
|
1401
|
+
warn: "⚠",
|
|
1402
|
+
error: "✗"
|
|
1403
|
+
};
|
|
1404
|
+
function formatDoctorEntry(entry) {
|
|
1405
|
+
const head = ` ${ICON[entry.level]} ${entry.check}: ${entry.message}`;
|
|
1406
|
+
return entry.fix ? `${head}
|
|
1407
|
+
fix: ${entry.fix}` : head;
|
|
1408
|
+
}
|
|
1399
1409
|
async function doctor(cfg) {
|
|
1400
1410
|
const entries = [];
|
|
1401
1411
|
const ok = (name, message) => entries.push({
|
|
@@ -1467,41 +1477,40 @@ async function doctor(cfg) {
|
|
|
1467
1477
|
const unreadable = registry.parseErrors();
|
|
1468
1478
|
if (unreadable.length > 0) {
|
|
1469
1479
|
const first = unreadable[0];
|
|
1470
|
-
|
|
1471
|
-
warn("sources", `${unreadable.length} ${one ? "file" : "files"} could not be parsed, so ${one ? "its" : "their"} messages are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
|
|
1480
|
+
warn("sources", `could not parse ${counted(unreadable.length, "file")}, so the messages inside are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
|
|
1472
1481
|
}
|
|
1473
1482
|
const stray = registry.strayImports();
|
|
1474
1483
|
if (stray.length > 0) {
|
|
1475
1484
|
const files = [...new Set(stray.map((entry) => rel(entry.file)))];
|
|
1476
|
-
error("imports",
|
|
1485
|
+
error("imports", `t is imported from a verbaly package, which never exports it, in ${counted(files.length, "file")} (${preview(files)})`, "t comes from your instance (React: const t = useT()) or from virtual:verbaly");
|
|
1477
1486
|
}
|
|
1478
1487
|
const escaped = [...registry.messages().values()].map((msg) => ({
|
|
1479
1488
|
file: rel(msg.file),
|
|
1480
1489
|
slice: escapedSyntax(msg.message)
|
|
1481
1490
|
})).filter((entry) => entry.slice !== void 0);
|
|
1482
|
-
if (escaped.length > 0) warn("messages",
|
|
1491
|
+
if (escaped.length > 0) warn("messages", `a block ships as literal text in ${counted(escaped.length, "extracted message")} (${escaped[0].file}: ${escaped[0].slice})`, "a tagged template takes its values from ${…}: use t(key, params) for a plural or format block");
|
|
1483
1492
|
}
|
|
1484
1493
|
if (source && scanning) {
|
|
1485
1494
|
const extracted = registry.messages();
|
|
1486
1495
|
const used = registry.usedKeys();
|
|
1487
1496
|
const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
|
|
1488
|
-
if (orphans.length > 0) warn("orphans", `${orphans.length
|
|
1497
|
+
if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, "run `npx verbaly extract --prune` to drop them");
|
|
1489
1498
|
else ok("orphans", "no orphan keys");
|
|
1490
1499
|
}
|
|
1491
1500
|
if (catalogsHealthy) {
|
|
1492
1501
|
const result = check(cfg, catalogs, registry);
|
|
1493
|
-
if (result.unknown.length > 0) error("keys", `${result.unknown.length
|
|
1502
|
+
if (result.unknown.length > 0) error("keys", `${counted(result.unknown.length, "unknown key")} used in code (${preview(result.unknown.map((u) => u.key))})`, "fix the key or add it to the catalogs (`npx verbaly check` for details)");
|
|
1494
1503
|
if (result.missing.length > 0) {
|
|
1495
1504
|
const locales = [...new Set(result.missing.map((m) => m.locale))];
|
|
1496
|
-
warn("translations", `${result.missing.length
|
|
1505
|
+
warn("translations", `${counted(result.missing.length, "missing translation")} (${locales.join(", ")})`, "run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)");
|
|
1497
1506
|
}
|
|
1498
1507
|
const broken = result.broken.filter((entry) => entry.severity === "error");
|
|
1499
1508
|
if (broken.length > 0) {
|
|
1500
1509
|
const locales = [...new Set(broken.map((b) => b.locale))];
|
|
1501
|
-
error("translations", `${broken.length
|
|
1510
|
+
error("translations", `${counted(broken.length, "broken translation")} (${locales.join(", ")}): present but not rendering what the source renders`, "run `npx verbaly check` to read what each one lost");
|
|
1502
1511
|
}
|
|
1503
1512
|
const warnings = result.broken.filter((entry) => entry.severity === "warning");
|
|
1504
|
-
if (warnings.length > 0) warn("translations", `${warnings.length
|
|
1513
|
+
if (warnings.length > 0) warn("translations", `${counted(warnings.length, "structural warning")} (plural forms a language asks for)`, "run `npx verbaly check` to read them, they never fail the build");
|
|
1505
1514
|
if (result.ok) ok("translations", "all translations complete");
|
|
1506
1515
|
}
|
|
1507
1516
|
return {
|
|
@@ -1921,15 +1930,56 @@ function poUnquote(text) {
|
|
|
1921
1930
|
}
|
|
1922
1931
|
//#endregion
|
|
1923
1932
|
//#region src/translate.ts
|
|
1933
|
+
const RETRY_STATUS = /* @__PURE__ */ new Set([
|
|
1934
|
+
408,
|
|
1935
|
+
409,
|
|
1936
|
+
425,
|
|
1937
|
+
429,
|
|
1938
|
+
500,
|
|
1939
|
+
502,
|
|
1940
|
+
503,
|
|
1941
|
+
504,
|
|
1942
|
+
529
|
|
1943
|
+
]);
|
|
1944
|
+
function retryable(error) {
|
|
1945
|
+
const status = error?.status;
|
|
1946
|
+
const code = error?.statusCode;
|
|
1947
|
+
const value = typeof status === "number" ? status : code;
|
|
1948
|
+
return typeof value === "number" ? RETRY_STATUS.has(value) : true;
|
|
1949
|
+
}
|
|
1950
|
+
function reason(error) {
|
|
1951
|
+
return error instanceof Error ? error.message : String(error);
|
|
1952
|
+
}
|
|
1953
|
+
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1954
|
+
async function attempt(run, retries, delay) {
|
|
1955
|
+
for (let round = 0;; round++) try {
|
|
1956
|
+
return await run();
|
|
1957
|
+
} catch (error) {
|
|
1958
|
+
if (round >= retries || !retryable(error)) throw error;
|
|
1959
|
+
await wait(delay * 2 ** round);
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
async function pooled(jobs, limit, run) {
|
|
1963
|
+
let next = 0;
|
|
1964
|
+
const workers = Array.from({ length: Math.min(limit, jobs.length) }, async () => {
|
|
1965
|
+
while (next < jobs.length) await run(jobs[next++]);
|
|
1966
|
+
});
|
|
1967
|
+
await Promise.all(workers);
|
|
1968
|
+
}
|
|
1924
1969
|
async function translateCatalogs(cfg, catalogs, provider, options = {}) {
|
|
1925
1970
|
const batchSize = options.batchSize ?? 20;
|
|
1971
|
+
const concurrency = Math.max(1, options.concurrency ?? 4);
|
|
1972
|
+
const retries = Math.max(0, options.retries ?? 2);
|
|
1973
|
+
const retryDelay = options.retryDelay ?? 500;
|
|
1926
1974
|
const targets = targetLocales(cfg, options.locales);
|
|
1927
1975
|
const source = catalogs[cfg.sourceLocale] ?? {};
|
|
1928
1976
|
const result = {
|
|
1929
1977
|
translated: {},
|
|
1930
1978
|
invalid: {},
|
|
1931
|
-
pending: {}
|
|
1979
|
+
pending: {},
|
|
1980
|
+
failed: []
|
|
1932
1981
|
};
|
|
1982
|
+
const jobs = [];
|
|
1933
1983
|
for (const locale of targets) {
|
|
1934
1984
|
const catalog = catalogs[locale] ??= {};
|
|
1935
1985
|
const missing = Object.keys(source).filter((key) => source[key] && !catalog[key]);
|
|
@@ -1938,31 +1988,78 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
|
|
|
1938
1988
|
result.pending[locale] = missing;
|
|
1939
1989
|
continue;
|
|
1940
1990
|
}
|
|
1991
|
+
const batches = Math.ceil(missing.length / batchSize);
|
|
1941
1992
|
for (let i = 0; i < missing.length; i += batchSize) {
|
|
1942
|
-
const
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1993
|
+
const index = Math.floor(i / batchSize) + 1;
|
|
1994
|
+
jobs.push({
|
|
1995
|
+
locale,
|
|
1996
|
+
index,
|
|
1997
|
+
batches,
|
|
1998
|
+
keys: missing.slice(i, i + batchSize)
|
|
1999
|
+
});
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
await pooled(jobs, concurrency, async (job) => {
|
|
2003
|
+
const { locale, keys } = job;
|
|
2004
|
+
const catalog = catalogs[locale];
|
|
2005
|
+
const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
|
|
2006
|
+
const origins = options.origins ? Object.fromEntries(keys.filter((key) => options.origins[key]).map((key) => [key, options.origins[key]])) : void 0;
|
|
2007
|
+
let out;
|
|
2008
|
+
try {
|
|
2009
|
+
out = await attempt(() => provider({
|
|
1946
2010
|
sourceLocale: cfg.sourceLocale,
|
|
1947
2011
|
targetLocale: locale,
|
|
1948
2012
|
messages,
|
|
1949
|
-
origins
|
|
2013
|
+
origins,
|
|
2014
|
+
instructions: cfg.translate.instructions,
|
|
2015
|
+
glossary: glossaryFor(cfg, locale, messages)
|
|
2016
|
+
}), retries, retryDelay);
|
|
2017
|
+
} catch (error) {
|
|
2018
|
+
const message = reason(error);
|
|
2019
|
+
result.failed.push({
|
|
2020
|
+
locale,
|
|
2021
|
+
keys,
|
|
2022
|
+
error: message
|
|
1950
2023
|
});
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
} else (result.invalid[locale] ??= []).push(key);
|
|
1957
|
-
}
|
|
2024
|
+
options.onProgress?.({
|
|
2025
|
+
...progressOf(job),
|
|
2026
|
+
error: message
|
|
2027
|
+
});
|
|
2028
|
+
return;
|
|
1958
2029
|
}
|
|
1959
|
-
|
|
2030
|
+
for (const key of keys) {
|
|
2031
|
+
const text = out[key];
|
|
2032
|
+
if (typeof text === "string" && text.trim() && structureMatches(source[key], text)) {
|
|
2033
|
+
catalog[key] = text;
|
|
2034
|
+
(result.translated[locale] ??= []).push(key);
|
|
2035
|
+
} else (result.invalid[locale] ??= []).push(key);
|
|
2036
|
+
}
|
|
2037
|
+
options.onProgress?.(progressOf(job));
|
|
2038
|
+
});
|
|
2039
|
+
for (const locale of Object.keys(result.translated)) result.translated[locale].sort();
|
|
2040
|
+
for (const locale of Object.keys(result.invalid)) result.invalid[locale].sort();
|
|
2041
|
+
result.failed.sort((a, b) => a.locale.localeCompare(b.locale) || compare(a.keys, b.keys));
|
|
1960
2042
|
return result;
|
|
1961
2043
|
}
|
|
2044
|
+
function compare(a, b) {
|
|
2045
|
+
return (a[0] ?? "").localeCompare(b[0] ?? "");
|
|
2046
|
+
}
|
|
2047
|
+
function formatTranslateFailures(failed) {
|
|
2048
|
+
const grouped = [];
|
|
2049
|
+
for (const entry of failed) {
|
|
2050
|
+
const same = grouped.find((it) => it.locale === entry.locale && it.error === entry.error);
|
|
2051
|
+
if (same) same.keys = [...same.keys, ...entry.keys];
|
|
2052
|
+
else grouped.push({
|
|
2053
|
+
...entry,
|
|
2054
|
+
keys: [...entry.keys]
|
|
2055
|
+
});
|
|
2056
|
+
}
|
|
2057
|
+
return grouped.map(({ locale, error, keys }) => ` ${locale}: ${counted(keys.length, "message")} not translated (${error}): ${keys.join(", ")}`);
|
|
2058
|
+
}
|
|
1962
2059
|
async function resolveProvider(cfg, model) {
|
|
1963
2060
|
const configured = cfg.translate.provider;
|
|
1964
2061
|
if (typeof configured === "function") return configured;
|
|
1965
|
-
const { claudeProvider } = await import("./claude-
|
|
2062
|
+
const { claudeProvider } = await import("./claude-ByRATJ03.js");
|
|
1966
2063
|
return claudeProvider({ model: model ?? cfg.translate.model });
|
|
1967
2064
|
}
|
|
1968
2065
|
function structureMatches(source, translated) {
|
|
@@ -1972,6 +2069,26 @@ function structureMatches(source, translated) {
|
|
|
1972
2069
|
return false;
|
|
1973
2070
|
}
|
|
1974
2071
|
}
|
|
2072
|
+
function progressOf(job) {
|
|
2073
|
+
return {
|
|
2074
|
+
locale: job.locale,
|
|
2075
|
+
batch: job.index,
|
|
2076
|
+
batches: job.batches,
|
|
2077
|
+
keys: job.keys.length
|
|
2078
|
+
};
|
|
2079
|
+
}
|
|
2080
|
+
function glossaryFor(cfg, locale, messages) {
|
|
2081
|
+
const entries = cfg.translate.glossary;
|
|
2082
|
+
if (!entries) return void 0;
|
|
2083
|
+
const text = Object.values(messages).join("\n").toLowerCase();
|
|
2084
|
+
const out = {};
|
|
2085
|
+
for (const [term, rendering] of Object.entries(entries)) {
|
|
2086
|
+
if (!text.includes(term.toLowerCase())) continue;
|
|
2087
|
+
const value = typeof rendering === "string" ? rendering : rendering[locale];
|
|
2088
|
+
if (value) out[term] = value;
|
|
2089
|
+
}
|
|
2090
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
2091
|
+
}
|
|
1975
2092
|
//#endregion
|
|
1976
2093
|
//#region src/exchange.ts
|
|
1977
2094
|
function isMobileFormat(format) {
|
|
@@ -2953,18 +3070,12 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
2953
3070
|
});
|
|
2954
3071
|
if (command === "doctor") {
|
|
2955
3072
|
const result = await doctor(cfg);
|
|
2956
|
-
const icon = {
|
|
2957
|
-
ok: "✓",
|
|
2958
|
-
warn: "⚠",
|
|
2959
|
-
error: "✗"
|
|
2960
|
-
};
|
|
2961
3073
|
console.log(`[verbaly] doctor: ${counted(result.entries.length, "check")}`);
|
|
2962
3074
|
for (const entry of result.entries) {
|
|
2963
|
-
const line =
|
|
3075
|
+
const line = formatDoctorEntry(entry);
|
|
2964
3076
|
if (entry.level === "error") console.error(line);
|
|
2965
3077
|
else if (entry.level === "warn") console.warn(line);
|
|
2966
3078
|
else console.log(line);
|
|
2967
|
-
if (entry.fix) console.log(` fix: ${entry.fix}`);
|
|
2968
3079
|
}
|
|
2969
3080
|
if (result.ok) console.log("[verbaly] setup looks healthy ✓");
|
|
2970
3081
|
else {
|
|
@@ -3069,8 +3180,11 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3069
3180
|
const result = await translateCatalogs(cfg, catalogs, await resolveProvider(cfg, values.model), {
|
|
3070
3181
|
locales: values.locales?.split(","),
|
|
3071
3182
|
batchSize: cfg.translate.batchSize,
|
|
3183
|
+
concurrency: cfg.translate.concurrency,
|
|
3184
|
+
retries: cfg.translate.retries,
|
|
3072
3185
|
dryRun: values["dry-run"],
|
|
3073
|
-
origins: values["dry-run"] ? void 0 : await collectOrigins(cfg)
|
|
3186
|
+
origins: values["dry-run"] ? void 0 : await collectOrigins(cfg),
|
|
3187
|
+
onProgress: values["dry-run"] ? void 0 : reportProgress
|
|
3074
3188
|
});
|
|
3075
3189
|
if (values["dry-run"]) {
|
|
3076
3190
|
const entries = Object.entries(result.pending);
|
|
@@ -3089,7 +3203,9 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3089
3203
|
}
|
|
3090
3204
|
if (Object.keys(result.translated).length > 0) saveDrafts(cfg, drafts);
|
|
3091
3205
|
for (const [locale, keys] of Object.entries(result.invalid)) console.warn(` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
|
|
3092
|
-
|
|
3206
|
+
for (const line of formatTranslateFailures(result.failed)) console.error(line);
|
|
3207
|
+
if (result.failed.length > 0) process.exitCode = 1;
|
|
3208
|
+
if (Object.keys(result.translated).length === 0 && Object.keys(result.invalid).length === 0 && result.failed.length === 0) console.log("[verbaly] nothing to translate ✓");
|
|
3093
3209
|
return;
|
|
3094
3210
|
}
|
|
3095
3211
|
if (command === "review") {
|
|
@@ -3209,6 +3325,11 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3209
3325
|
console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
|
|
3210
3326
|
process.exitCode = 1;
|
|
3211
3327
|
}
|
|
3328
|
+
function reportProgress(progress) {
|
|
3329
|
+
const head = ` ${progress.locale} ${progress.batch}/${progress.batches}`;
|
|
3330
|
+
if (progress.error) console.warn(`${head}: failed (${progress.error}), continuing`);
|
|
3331
|
+
else console.log(`${head}: ${counted(progress.keys, "message")}`);
|
|
3332
|
+
}
|
|
3212
3333
|
function formatCliError(error) {
|
|
3213
3334
|
const message = error instanceof Error ? error.message : String(error);
|
|
3214
3335
|
return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
|