@verbaly/compiler 0.65.0 → 0.67.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 CHANGED
@@ -26,11 +26,12 @@ npx verbaly wrap # onboarding codemod: report plain JSX text, --write
26
26
  npx verbaly migrate # port catalogs from another i18n library (--write applies, --plurals merges)
27
27
  npx verbaly extract # sync catalogs + types
28
28
  npx verbaly extract --watch # keep extracting as you code (dev loop)
29
- npx verbaly extract --prune # drop orphaned keys
30
- npx verbaly status # coverage per locale, plus unreviewed and broken counts
29
+ npx verbaly extract --prune # drop orphaned keys (waits while any source file does not parse)
30
+ npx verbaly extract --dry-run # say what extract would add and prune, write nothing
31
+ npx verbaly status # coverage per locale, plus unreviewed, broken and outdated counts
31
32
  npx verbaly check # exit 1 if anything is missing or broken (CI)
32
33
  npx verbaly translate # fill missing translations via Claude (or your provider), as drafts
33
- npx verbaly review # list machine drafts, --approve accepts them
34
+ npx verbaly review # list drafts and outdated translations, --approve accepts them
34
35
  npx verbaly-studio # the same catalogs on localhost (@verbaly/studio, separate package)
35
36
  npx verbaly export # translator files (XLIFF 2.0, CSV, gettext PO) or mobile resources (Android, iOS)
36
37
  npx verbaly import <files> # fill catalogs back from translated XLIFF/CSV/PO files
@@ -59,17 +60,57 @@ Two more are reported as **warnings** and keep the exit code at 0, because the t
59
60
 
60
61
  A third warning is a key that **only a translation has**. It never fails the build either, and the report says which case it is: your code reads it, so the source language shows the raw key there, or nothing reads it and it is dead weight in that language's download (`extract --prune` drops it).
61
62
 
63
+ Three more warnings name things that used to happen in silence, each with the file and line to go to:
64
+
65
+ - **One key, two texts.** Two `` t.id('k')`…` `` with different texts both render the first one. The report lists every place.
66
+ - **The catalog and the code disagree.** A text written in your code is the code's: the build ships it, and the source catalog only mirrors it (see [where a text lives](#-where-a-text-lives)).
67
+ - **An outdated translation.** The source text changed after the translation was written, and nobody has looked at the translation since.
68
+
69
+ The bundler plugins run the same gate on `build`, and when `check` has warnings the build prints one line saying how many, then passes: `npx verbaly check` reads them out.
70
+
62
71
  ```bash
63
72
  npx verbaly check # text report
64
73
  npx verbaly check --reporter github # ::error and ::warning annotations on the PR, at the source line
65
74
  npx verbaly check --drafts # also fail while machine translations await review
75
+ npx verbaly check --outdated # also fail while a translation is older than its source text
66
76
  ```
67
77
 
68
78
  Hand-edited catalogs get the same treatment as imported files: the gate does not care where a translation came from.
69
79
 
80
+ ## 🧭 Where a text lives
81
+
82
+ A message keeps its text in exactly one place, and that place is where you edit it:
83
+
84
+ | You write | The text lives in | You change it in |
85
+ | ----------------------------------------- | ---------------------------------- | ----------------------- |
86
+ | `` t`Save changes` `` | the code (the key is a hash of it) | the code |
87
+ | `` t.id('settings.save')`Save changes` `` | the code, under a key you chose | the code |
88
+ | `t('settings.save')` | the source catalog | `locales/<source>.json` |
89
+
90
+ **The code wins over the catalog for the texts it writes.** `extract`, the dev servers and the build all use the text in the code, so a hand edit of one in the source catalog is replaced, and Verbaly tells you and points at the line where the text lives.
91
+
92
+ **Keys first** is the third row: the text lives only in the catalog, and a literal `t('settings.save')` counts as a use, so `--prune` keeps it. When a key comes from data instead of a literal, declare the keys with `defineKeys`, so the compiler sees them and TypeScript checks them where you write them:
93
+
94
+ ```ts
95
+ import { defineKeys } from 'virtual:verbaly';
96
+
97
+ const titles = defineKeys({ verbaly: 'project.verbaly.title', blog: 'project.blog.title' });
98
+ t(titles[slug]);
99
+ ```
100
+
101
+ `defineKeys` is detected by name, like `t`. It comes from `virtual:verbaly`, the module generated for your project, which is the one the framework provider already loads.
102
+
103
+ **A translation knows which source text it was written for.** For readable keys, the second and third rows, Verbaly keeps a short fingerprint of the source text and of the translation in `.verbaly-state.json`, next to your catalogs. When the source text changes and the translation does not, the translation is **outdated**: `status`, `check` and `doctor` say so, `review` lists it, and `review --approve` keeps it if it still holds. Editing the translation clears it on its own. Hash keys never need this, because a new text is a new key.
104
+
105
+ Three details that catch people out:
106
+
107
+ - **Name it `t`.** The compiler reads calls named `t`. `const tr = useT()` works at runtime, but `` tr`…` `` is never extracted, so that text stays in the source language. `extract` and `doctor` name every such call.
108
+ - **A number param is formatted for the language.** `{year}` with `2026` renders `2,026` in English, the same as ICU. Pass `String(year)` when the value is a label, not a quantity.
109
+ - **Literal braces are doubled in a catalog.** `{{` shows `{`. `extract` does it for you from code; a catalog written by hand has to do it itself.
110
+
70
111
  ## 🤖 Machine translation
71
112
 
72
- `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.
113
+ `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-5` (balanced quality/cost); override with `translate.model` in config or `--model <id>`. Each model is asked for the least thinking it accepts, so any current Claude model works there, and on the models that support it a batch the model declines is answered by Anthropic's recommended fallback model instead of coming back untranslated. Placeholders, variants and tags are validated after translation: anything not preserved verbatim stays `""` so `check` keeps failing.
73
114
 
74
115
  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.
75
116
 
@@ -88,7 +129,7 @@ export default {
88
129
 
89
130
  Only the terms a batch actually contains are sent, so a glossary of hundreds never becomes the prompt.
90
131
 
91
- **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.
132
+ **Machine output is a draft until a human says yes.** Everything `translate` writes is recorded in `locales/.verbaly-state.json`, the file that also holds the fingerprints above: commit it, and 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. `import --draft` keeps them as drafts instead, for a file nobody has read yet. An agent that translates on its own saves its work through the MCP tool `verbaly_write_drafts`, which checks it like a provider's and marks it as a draft. `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. `extract` keeps the file in step with the catalogs, so a pruned key takes its draft with it, and the file disappears when there is nothing left in it.
92
133
 
93
134
  Plug your own provider in `verbaly.config.ts`. In TypeScript, `TranslateProvider` types it for you:
94
135
 
@@ -140,7 +181,7 @@ Under a prefix mode that goes to `/es/…`, which is already rendered in Spanish
140
181
  await switchLocale('es', { navigate: (path) => router.push(path) });
141
182
  ```
142
183
 
143
- `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.
184
+ `npx verbaly doctor` names the mode you are in, and says so when the mode and a `render` section disagree: `render` keeps the source language at the root and writes every other language under its own prefix, which is `prefix-except-source`.
144
185
 
145
186
  ## 🧪 What the runtime carries, and what it does not
146
187
 
@@ -261,10 +302,10 @@ The package exports two layers, and **nothing else is public**. Anything you can
261
302
  | Extraction | `extractProject` `collectOrigins` `syncCatalogs` `pruneCatalogs` `MessageRegistry` `stableKey` `watchTree` · types `SyncResult` `TreeOptions` |
262
303
  | Codegen | `generateDts` `writeDts` `generateRuntimeModule` `generateLocaleModule` · types `DtsOptions` `RuntimeModuleOptions` |
263
304
  | Bundler plumbing | `transformSource` `transformCode` `runBuildGate` `createSourceFilter` `isTransformTarget` `resolveVirtualId` `loadVirtualModule` `RESOLVED_VIRTUAL_ID` `LOCALE_MODULE_PREFIX` `SOURCE_FILE_RE` · types `PluginOptions` `TransformResult` |
264
- | The gate | `check` `validateMessage` `validatePair` `formatCheckResult` `formatCheckWarnings` · types `CheckResult` `MissingEntry` `UnknownEntry` `BrokenEntry` `ExtraEntry` `StructureIssue` `IssueSeverity` |
305
+ | The gate | `check` `validateMessage` `validatePair` `formatCheckResult` `formatCheckWarnings` `collisionEntries` `formatCollision` · types `CheckResult` `MissingEntry` `UnknownEntry` `BrokenEntry` `ExtraEntry` `CollisionEntry` `DivergentEntry` `OutdatedEntry` `SourceSite` `StructureIssue` `IssueSeverity` |
265
306
  | Coverage | `status` `formatStatusResult` `counted` · types `StatusResult` `LocaleStatus` |
266
- | Draft review | `loadDrafts` `saveDrafts` `markDrafts` `clearDrafts` `effectiveDrafts` `DRAFTS_FILE` · type `Drafts` |
267
- | Translation | `translateCatalogs` `mergeTranslations` `resolveProvider` `formatTranslateFailures` |
307
+ | Review state | `loadDrafts` `saveDrafts` `markDrafts` `clearDrafts` `effectiveDrafts` `loadState` `updateState` `outdatedTranslations` `STATE_FILE` · types `Drafts` `State` `Fingerprints` |
308
+ | Translation | `translateCatalogs` `mergeTranslations` `writeDrafts` `resolveProvider` `formatTranslateFailures` · types `DraftEntry` `WriteDraftsResult` |
268
309
  | Diagnosis | `doctor` `formatDoctorEntry` · types `DoctorResult` `DoctorEntry` |
269
310
  | Onboarding | `wrapProject` · types `WrapResult` `WrapEntry` `WrapSkip` `WrapBlocked` `WrapOptions` |
270
311
  | Static rendering | `renderSite` `formatRenderWarnings` · types `RenderSiteOptions` `RenderSiteResult` |
@@ -1,6 +1,17 @@
1
- import { n as isModuleNotFound } from "./config-DYlbHrPc.js";
1
+ import { n as isModuleNotFound, t as counted } from "./cli.js";
2
2
  //#region src/providers/claude.ts
3
- const DEFAULT_MODEL = "claude-sonnet-5";
3
+ const DEFAULT_MODEL = "claude-sonnet-5-5";
4
+ const FALLBACK_MODELS = /* @__PURE__ */ new Set([
5
+ "claude-sonnet-5-5",
6
+ "claude-opus-5-5",
7
+ "claude-opus-5",
8
+ "claude-fable-5-1"
9
+ ]);
10
+ const FALLBACK_BETA = "server-side-fallback-2026-07-01";
11
+ function thinkingFor(model) {
12
+ if (model === "claude-sonnet-5-5") return { type: "between_tools" };
13
+ if (model === "claude-sonnet-5" || model === "claude-opus-5") return { type: "disabled" };
14
+ }
4
15
  const SYSTEM = `You translate UI strings for the Verbaly i18n library.
5
16
  Rules:
6
17
  - Translate only the human-readable text, naturally for the target locale.
@@ -13,10 +24,16 @@ function claudeProvider(options = {}) {
13
24
  let client;
14
25
  return async (request) => {
15
26
  client ??= loadSdk().then((Anthropic) => new Anthropic(options.apiKey ? { apiKey: options.apiKey } : {}));
16
- const response = await (await client).messages.create({
17
- model: options.model ?? DEFAULT_MODEL,
27
+ const model = options.model ?? DEFAULT_MODEL;
28
+ const thinking = thinkingFor(model);
29
+ const response = await (await client).beta.messages.create({
30
+ model,
18
31
  max_tokens: options.maxTokens ?? 16e3,
19
- thinking: { type: "disabled" },
32
+ ...thinking && { thinking },
33
+ ...FALLBACK_MODELS.has(model) && {
34
+ betas: [FALLBACK_BETA],
35
+ fallbacks: "default"
36
+ },
20
37
  system: systemPrompt(request.instructions),
21
38
  messages: [{
22
39
  role: "user",
@@ -24,8 +41,12 @@ function claudeProvider(options = {}) {
24
41
  }],
25
42
  output_config: { format: batchFormat(request) }
26
43
  });
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
- if (response.stop_reason === "refusal") throw Object.assign(/* @__PURE__ */ new Error(`[verbaly] the model declined a batch of ${Object.keys(request.messages).length} messages, so they stay untranslated: translate them by hand or with another provider`), { status: 400 });
44
+ const batch = counted(Object.keys(request.messages).length, "message");
45
+ if (response.stop_reason === "max_tokens") throw new Error(`[verbaly] the model ran out of output room on a batch of ${batch}: lower translate.batchSize (or raise maxTokens on the provider)`);
46
+ if (response.stop_reason === "refusal") {
47
+ const category = response.stop_details?.category;
48
+ throw Object.assign(/* @__PURE__ */ new Error(`[verbaly] the model declined a batch of ${batch}${category ? ` (${category})` : ""}, so they stay untranslated: translate them by hand or with another provider`), { status: 400 });
49
+ }
29
50
  const text = response.content.find((block) => block.type === "text")?.text ?? "{}";
30
51
  try {
31
52
  return JSON.parse(text);
@@ -70,4 +91,4 @@ async function loadSdk(load = () => import("@anthropic-ai/sdk")) {
70
91
  //#endregion
71
92
  export { claudeProvider };
72
93
 
73
- //# sourceMappingURL=claude--aMMLA-N.js.map
94
+ //# sourceMappingURL=claude-BmD8W9uW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude-BmD8W9uW.js","names":[],"sources":["../src/providers/claude.ts"],"sourcesContent":["import { isModuleNotFound } from '../config';\nimport { counted } from '../text';\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: the current Sonnet, at the price of the one before it\nconst DEFAULT_MODEL = 'claude-sonnet-5-5';\n\n// the models that take fallbacks \"default\": a batch one declines is answered by another model\nconst FALLBACK_MODELS = new Set([\n 'claude-sonnet-5-5',\n 'claude-opus-5-5',\n 'claude-opus-5',\n 'claude-fable-5-1',\n]);\nconst FALLBACK_BETA = 'server-side-fallback-2026-07-01';\n\n// the least thinking each model takes: disabled is a 400 on the newest, and the oldest never think\nexport function thinkingFor(model: string): { type: 'between_tools' | 'disabled' } | undefined {\n if (model === 'claude-sonnet-5-5') return { type: 'between_tools' };\n if (model === 'claude-sonnet-5' || model === 'claude-opus-5') return { type: 'disabled' };\n return undefined;\n}\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 model = options.model ?? DEFAULT_MODEL;\n const thinking = thinkingFor(model);\n const response = await (\n await client\n ).beta.messages.create({\n model,\n max_tokens: options.maxTokens ?? 16000,\n ...(thinking && { thinking }),\n ...(FALLBACK_MODELS.has(model) && { betas: [FALLBACK_BETA], fallbacks: 'default' as const }),\n system: systemPrompt(request.instructions),\n messages: [{ role: 'user', content: buildPrompt(request) }],\n output_config: { format: batchFormat(request) },\n });\n const batch = counted(Object.keys(request.messages).length, 'message');\n if (response.stop_reason === 'max_tokens') {\n throw new Error(\n `[verbaly] the model ran out of output room on a batch of ${batch}: lower translate.batchSize (or raise maxTokens on the provider)`,\n );\n }\n // a decline is about the content, so asking again gets the same answer: a 400 is never retried\n if (response.stop_reason === 'refusal') {\n const category = response.stop_details?.category;\n throw Object.assign(\n new Error(\n `[verbaly] the model declined a batch of ${batch}${category ? ` (${category})` : ''}, so they stay untranslated: translate them by hand or with another provider`,\n ),\n { status: 400 },\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":";;AAWA,MAAM,gBAAgB;AAGtB,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,gBAAgB;AAGtB,SAAgB,YAAY,OAAmE;CAC7F,IAAI,UAAU,qBAAqB,OAAO,EAAE,MAAM,gBAAgB;CAClE,IAAI,UAAU,qBAAqB,UAAU,iBAAiB,OAAO,EAAE,MAAM,WAAW;AAE1F;AAEA,MAAM,SAAS;;;;;AAMf,SAAgB,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t as counted } from "./text-M4XbWU6N.js";
2
2
  //#region src/providers/claude.ts
3
- const DEFAULT_MODEL = "claude-sonnet-5";
3
+ const DEFAULT_MODEL = "claude-sonnet-5-5";
4
+ const FALLBACK_MODELS = /* @__PURE__ */ new Set([
5
+ "claude-sonnet-5-5",
6
+ "claude-opus-5-5",
7
+ "claude-opus-5",
8
+ "claude-fable-5-1"
9
+ ]);
10
+ const FALLBACK_BETA = "server-side-fallback-2026-07-01";
11
+ function thinkingFor(model) {
12
+ if (model === "claude-sonnet-5-5") return { type: "between_tools" };
13
+ if (model === "claude-sonnet-5" || model === "claude-opus-5") return { type: "disabled" };
14
+ }
4
15
  const SYSTEM = `You translate UI strings for the Verbaly i18n library.
5
16
  Rules:
6
17
  - Translate only the human-readable text, naturally for the target locale.
@@ -13,10 +24,16 @@ function claudeProvider(options = {}) {
13
24
  let client;
14
25
  return async (request) => {
15
26
  client ??= loadSdk().then((Anthropic) => new Anthropic(options.apiKey ? { apiKey: options.apiKey } : {}));
16
- const response = await (await client).messages.create({
17
- model: options.model ?? DEFAULT_MODEL,
27
+ const model = options.model ?? DEFAULT_MODEL;
28
+ const thinking = thinkingFor(model);
29
+ const response = await (await client).beta.messages.create({
30
+ model,
18
31
  max_tokens: options.maxTokens ?? 16e3,
19
- thinking: { type: "disabled" },
32
+ ...thinking && { thinking },
33
+ ...FALLBACK_MODELS.has(model) && {
34
+ betas: [FALLBACK_BETA],
35
+ fallbacks: "default"
36
+ },
20
37
  system: systemPrompt(request.instructions),
21
38
  messages: [{
22
39
  role: "user",
@@ -24,8 +41,12 @@ function claudeProvider(options = {}) {
24
41
  }],
25
42
  output_config: { format: batchFormat(request) }
26
43
  });
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
- if (response.stop_reason === "refusal") throw Object.assign(/* @__PURE__ */ new Error(`[verbaly] the model declined a batch of ${Object.keys(request.messages).length} messages, so they stay untranslated: translate them by hand or with another provider`), { status: 400 });
44
+ const batch = counted(Object.keys(request.messages).length, "message");
45
+ if (response.stop_reason === "max_tokens") throw new Error(`[verbaly] the model ran out of output room on a batch of ${batch}: lower translate.batchSize (or raise maxTokens on the provider)`);
46
+ if (response.stop_reason === "refusal") {
47
+ const category = response.stop_details?.category;
48
+ throw Object.assign(/* @__PURE__ */ new Error(`[verbaly] the model declined a batch of ${batch}${category ? ` (${category})` : ""}, so they stay untranslated: translate them by hand or with another provider`), { status: 400 });
49
+ }
29
50
  const text = response.content.find((block) => block.type === "text")?.text ?? "{}";
30
51
  try {
31
52
  return JSON.parse(text);
@@ -70,4 +91,4 @@ async function loadSdk(load = () => import("@anthropic-ai/sdk")) {
70
91
  //#endregion
71
92
  export { claudeProvider };
72
93
 
73
- //# sourceMappingURL=claude-arq_js_3.js.map
94
+ //# sourceMappingURL=claude-D-j-ZiYH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude-D-j-ZiYH.js","names":[],"sources":["../src/providers/claude.ts"],"sourcesContent":["import { isModuleNotFound } from '../config';\nimport { counted } from '../text';\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: the current Sonnet, at the price of the one before it\nconst DEFAULT_MODEL = 'claude-sonnet-5-5';\n\n// the models that take fallbacks \"default\": a batch one declines is answered by another model\nconst FALLBACK_MODELS = new Set([\n 'claude-sonnet-5-5',\n 'claude-opus-5-5',\n 'claude-opus-5',\n 'claude-fable-5-1',\n]);\nconst FALLBACK_BETA = 'server-side-fallback-2026-07-01';\n\n// the least thinking each model takes: disabled is a 400 on the newest, and the oldest never think\nexport function thinkingFor(model: string): { type: 'between_tools' | 'disabled' } | undefined {\n if (model === 'claude-sonnet-5-5') return { type: 'between_tools' };\n if (model === 'claude-sonnet-5' || model === 'claude-opus-5') return { type: 'disabled' };\n return undefined;\n}\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 model = options.model ?? DEFAULT_MODEL;\n const thinking = thinkingFor(model);\n const response = await (\n await client\n ).beta.messages.create({\n model,\n max_tokens: options.maxTokens ?? 16000,\n ...(thinking && { thinking }),\n ...(FALLBACK_MODELS.has(model) && { betas: [FALLBACK_BETA], fallbacks: 'default' as const }),\n system: systemPrompt(request.instructions),\n messages: [{ role: 'user', content: buildPrompt(request) }],\n output_config: { format: batchFormat(request) },\n });\n const batch = counted(Object.keys(request.messages).length, 'message');\n if (response.stop_reason === 'max_tokens') {\n throw new Error(\n `[verbaly] the model ran out of output room on a batch of ${batch}: lower translate.batchSize (or raise maxTokens on the provider)`,\n );\n }\n // a decline is about the content, so asking again gets the same answer: a 400 is never retried\n if (response.stop_reason === 'refusal') {\n const category = response.stop_details?.category;\n throw Object.assign(\n new Error(\n `[verbaly] the model declined a batch of ${batch}${category ? ` (${category})` : ''}, so they stay untranslated: translate them by hand or with another provider`,\n ),\n { status: 400 },\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":";;AAWA,MAAM,gBAAgB;AAGtB,MAAM,kCAAkB,IAA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