@verbaly/compiler 0.38.0 → 0.40.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 +64 -4
- package/dist/{claude-h9WA0ppg.js → claude-ByRATJ03.js} +26 -7
- package/dist/claude-ByRATJ03.js.map +1 -0
- package/dist/{claude-CrAkiSVP.js → claude-DGo229kG.js} +27 -8
- package/dist/claude-DGo229kG.js.map +1 -0
- package/dist/cli.js +190 -35
- package/dist/cli.js.map +1 -1
- package/dist/{config-D8gkaunO.js → config-B6MP3zwt.js} +13 -2
- package/dist/config-B6MP3zwt.js.map +1 -0
- package/dist/index.d.ts +70 -2
- package/dist/index.js +592 -20
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
- 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,14 +91,45 @@ 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
|
|
|
82
100
|
export default { sourceLocale: 'en', locales: ['en', 'es'], translate: { provider } };
|
|
83
101
|
```
|
|
84
102
|
|
|
103
|
+
## 🔗 Where the language lives in the URL
|
|
104
|
+
|
|
105
|
+
One setting, because every other URL answer follows from it:
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
export default {
|
|
109
|
+
sourceLocale: 'en',
|
|
110
|
+
locales: ['en', 'es', 'pt'],
|
|
111
|
+
routing: 'prefix-except-source', // the default: /docs and /es/docs
|
|
112
|
+
};
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
| `routing` | The address | Switching language is |
|
|
116
|
+
| ---------------------- | ------------------------- | ----------------------------- |
|
|
117
|
+
| `prefix-except-source` | `/docs` and `/es/docs` | a navigation |
|
|
118
|
+
| `prefix-all` | `/en/docs` and `/es/docs` | a navigation |
|
|
119
|
+
| `no-prefix` | `/docs` in every language | the text changing where it is |
|
|
120
|
+
|
|
121
|
+
Pick by surface, not by taste: [Google recommends a different URL per language](https://developers.google.com/search/docs/specialty/international/managing-multi-regional-sites) rather than cookies or browser settings, so anything people reach through search wants the language in the address. An app behind a login loses nothing with `no-prefix`.
|
|
122
|
+
|
|
123
|
+
`virtual:verbaly` exports `routing` plus `localePath` and `localeFromPath` **already bound** to your locales, source and mode, so a locale switcher has nothing left to pass wrong:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
import { localePath, routing } from 'virtual:verbaly';
|
|
127
|
+
|
|
128
|
+
location.assign(localePath('es')); // /es/docs, or the same url under no-prefix
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
`npx verbaly doctor` names the mode you are in, and says so when `no-prefix` sits next to a `render` section that writes one URL tree per locale.
|
|
132
|
+
|
|
85
133
|
## 🌍 Human translators & TMS
|
|
86
134
|
|
|
87
135
|
Catalogs are **flat JSON**: most TMS platforms (Crowdin, Lokalise, Phrase, …) ingest them natively; point the platform at `locales/` and you're done. For everything else there's a built-in round-trip:
|
|
@@ -119,6 +167,16 @@ render: { links: { docs: { href: '/docs', target: '_blank', rel: 'noopener' } }
|
|
|
119
167
|
|
|
120
168
|
Per-element `data-verbaly-links='{"repo":"https://…"}'` merges over the config map.
|
|
121
169
|
|
|
170
|
+
**The head is half of what a search result shows.** A mirrored page whose `<title>` and `<meta name="description">` are not bound ships the source language to every locale, which is most of the reason to give a locale its own URL in the first place. Bind them like anything else, and `render` fills them:
|
|
171
|
+
|
|
172
|
+
```html
|
|
173
|
+
<title data-verbaly="page.title">URL strategy</title>
|
|
174
|
+
<meta name="description" content="…" data-verbaly-attr='{"content":"page.desc"}' />
|
|
175
|
+
<meta property="og:title" content="…" data-verbaly-attr='{"content":"page.title"}' />
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
`verbaly render` counts the pages whose title never varies and says so, once, with the fix. It is a warning and never fails a build: a site can have a name that does not translate.
|
|
179
|
+
|
|
122
180
|
**Multi-locale SEO**: set `render.baseUrl` (or `--base-url`) and every page gets reciprocal `<link rel="alternate" hreflang>` (plus `x-default`) for the whole locale set; `--sitemap` writes a locale-aware `sitemap-i18n.xml`. `--clean` drops stale `dist/<locale>/` pages before mirroring. Injection is idempotent.
|
|
123
181
|
|
|
124
182
|
## 🔍 Pseudo-localization
|
|
@@ -137,7 +195,7 @@ The package exports two layers, and **nothing else is public**. Anything you can
|
|
|
137
195
|
|
|
138
196
|
**Your project's own types**, for a typed config file or a custom provider:
|
|
139
197
|
|
|
140
|
-
`VerbalyConfig` · `ResolvedConfig` · `RenderConfig` · `RedirectConfig` · `TranslateConfig` · `TranslateProvider` · `TranslateRequest` · `TranslateResult` · `TranslateOptions`
|
|
198
|
+
`VerbalyConfig` · `ResolvedConfig` · `RenderConfig` · `RedirectConfig` · `TranslateConfig` · `GlossaryEntry` · `TranslateProvider` · `TranslateRequest` · `TranslateResult` · `TranslateOptions` · `TranslateProgress` · `TranslateFailure`
|
|
141
199
|
|
|
142
200
|
**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
201
|
|
|
@@ -150,8 +208,10 @@ The package exports two layers, and **nothing else is public**. Anything you can
|
|
|
150
208
|
| The gate | `check` `formatCheckResult` `formatCheckWarnings` · types `CheckResult` `MissingEntry` `UnknownEntry` `BrokenEntry` `IssueSeverity` |
|
|
151
209
|
| Coverage | `status` `formatStatusResult` `counted` · types `StatusResult` `LocaleStatus` |
|
|
152
210
|
| Draft review | `loadDrafts` `saveDrafts` `markDrafts` `effectiveDrafts` · type `Drafts` |
|
|
153
|
-
| Translation | `translateCatalogs` `resolveProvider`
|
|
154
|
-
|
|
|
211
|
+
| Translation | `translateCatalogs` `resolveProvider` `formatTranslateFailures` |
|
|
212
|
+
| Diagnosis | `doctor` `formatDoctorEntry` · types `DoctorResult` `DoctorEntry` |
|
|
213
|
+
| Onboarding | `wrapProject` · types `WrapResult` `WrapEntry` `WrapSkip` `WrapOptions` |
|
|
214
|
+
| Static rendering | `renderSite` `formatRenderWarnings` · types `RenderSiteOptions` `RenderSiteResult` |
|
|
155
215
|
|
|
156
216
|
A minimal plugin is `loadConfig` + `loadCatalogs` once, then `transformSource` per file and `runBuildGate` at the end:
|
|
157
217
|
|
|
@@ -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,MAA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AAO,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"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as isModuleNotFound } from "./config-B6MP3zwt.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-DGo229kG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claude-DGo229kG.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,4DAA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