@verbaly/compiler 0.37.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 +24 -4
- 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 +271 -86
- 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 +68 -1
- package/dist/index.js +648 -53
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
- 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
|
|
|
@@ -148,9 +166,11 @@ The package exports two layers, and **nothing else is public**. Anything you can
|
|
|
148
166
|
| Codegen | `generateDts` `writeDts` `generateRuntimeModule` `generateLocaleModule` · type `RuntimeModuleOptions` |
|
|
149
167
|
| Bundler plumbing | `transformSource` `transformCode` `runBuildGate` `createSourceFilter` `isTransformTarget` `resolveVirtualId` `loadVirtualModule` `RESOLVED_VIRTUAL_ID` `LOCALE_MODULE_PREFIX` `SOURCE_FILE_RE` · types `PluginOptions` `TransformResult` |
|
|
150
168
|
| The gate | `check` `formatCheckResult` `formatCheckWarnings` · types `CheckResult` `MissingEntry` `UnknownEntry` `BrokenEntry` `IssueSeverity` |
|
|
151
|
-
| Coverage | `status` `formatStatusResult` · types `StatusResult` `LocaleStatus`
|
|
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,QA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Q,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` / `np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