@verbaly/compiler 0.40.0 → 0.41.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 +12 -4
- package/dist/{claude-DGo229kG.js → claude-DYAwaLJz.js} +2 -2
- package/dist/{claude-DGo229kG.js.map → claude-DYAwaLJz.js.map} +1 -1
- package/dist/cli.js +19 -2
- package/dist/cli.js.map +1 -1
- package/dist/{config-B6MP3zwt.js → config-dVhga3PS.js} +2 -2
- package/dist/config-dVhga3PS.js.map +1 -0
- package/dist/index.js +31 -4
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/dist/config-B6MP3zwt.js.map +0 -1
package/README.md
CHANGED
|
@@ -104,11 +104,13 @@ export default { sourceLocale: 'en', locales: ['en', 'es'], translate: { provide
|
|
|
104
104
|
|
|
105
105
|
One setting, because every other URL answer follows from it:
|
|
106
106
|
|
|
107
|
+
**You usually write nothing.** The mode follows your setup: a project with a `render` section builds one URL tree per language, so it is `prefix-except-source`; a project without one has a single address, so it is `no-prefix`. Say it out loud only to disagree:
|
|
108
|
+
|
|
107
109
|
```ts
|
|
108
110
|
export default {
|
|
109
111
|
sourceLocale: 'en',
|
|
110
112
|
locales: ['en', 'es', 'pt'],
|
|
111
|
-
routing: 'prefix-
|
|
113
|
+
routing: 'prefix-all', // /en/docs and /es/docs, when no language is the house language
|
|
112
114
|
};
|
|
113
115
|
```
|
|
114
116
|
|
|
@@ -120,12 +122,18 @@ export default {
|
|
|
120
122
|
|
|
121
123
|
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
124
|
|
|
123
|
-
`virtual:verbaly` exports `routing
|
|
125
|
+
`virtual:verbaly` exports `routing`, `localePath`, `localeFromPath` and **`switchLocale`, already bound** to your locales, source and mode. The switcher is one line and it is the same line in every mode:
|
|
124
126
|
|
|
125
127
|
```ts
|
|
126
|
-
import {
|
|
128
|
+
import { switchLocale } from 'virtual:verbaly';
|
|
129
|
+
|
|
130
|
+
await switchLocale('es');
|
|
131
|
+
```
|
|
127
132
|
|
|
128
|
-
|
|
133
|
+
Under a prefix mode that goes to `/es/…`, which is already rendered in Spanish, so there is no catalog to fetch and no flash. Under `no-prefix` it swaps the text where it stands and the address never changes. Either way it remembers the choice, in the cookie a server reads **and** in the storage the pre-paint redirect reads, and it sets `<html lang>` and `<html dir>`. Pass your framework's router so the app survives the switch:
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
await switchLocale('es', { navigate: (path) => router.push(path) });
|
|
129
137
|
```
|
|
130
138
|
|
|
131
139
|
`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.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as isModuleNotFound } from "./config-
|
|
1
|
+
import { n as isModuleNotFound } from "./config-dVhga3PS.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.
|
|
@@ -69,4 +69,4 @@ async function loadSdk(load = () => import("@anthropic-ai/sdk")) {
|
|
|
69
69
|
//#endregion
|
|
70
70
|
export { claudeProvider };
|
|
71
71
|
|
|
72
|
-
//# sourceMappingURL=claude-
|
|
72
|
+
//# sourceMappingURL=claude-DYAwaLJz.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude-
|
|
1
|
+
{"version":3,"file":"claude-DYAwaLJz.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,MAA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,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
|
@@ -517,6 +517,13 @@ ${lines.join("\n")}
|
|
|
517
517
|
}
|
|
518
518
|
|
|
519
519
|
export function setLocale(locale: string): Promise<void>;
|
|
520
|
+
export function switchLocale(
|
|
521
|
+
locale: string,
|
|
522
|
+
options?: Omit<
|
|
523
|
+
import('verbaly').SwitchLocaleOptions,
|
|
524
|
+
'routing' | 'supported' | 'sourceLocale'
|
|
525
|
+
>,
|
|
526
|
+
): Promise<void>;
|
|
520
527
|
export function getLocale(): string;
|
|
521
528
|
export function subscribe(listener: () => void): () => void;
|
|
522
529
|
}
|
|
@@ -669,7 +676,7 @@ function resolveConfig(config = {}) {
|
|
|
669
676
|
root,
|
|
670
677
|
dir,
|
|
671
678
|
sourceLocale,
|
|
672
|
-
routing: config.routing ?? "prefix-except-source",
|
|
679
|
+
routing: config.routing ?? (config.render ? "prefix-except-source" : "no-prefix"),
|
|
673
680
|
locales: [...locales],
|
|
674
681
|
include: config.include ?? ["{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}"],
|
|
675
682
|
exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
|
|
@@ -1406,6 +1413,13 @@ function counted(count, noun, many = `${noun}s`) {
|
|
|
1406
1413
|
//#endregion
|
|
1407
1414
|
//#region src/doctor.ts
|
|
1408
1415
|
const PREVIEW = 5;
|
|
1416
|
+
function readRoutingChoice(root, configFile) {
|
|
1417
|
+
try {
|
|
1418
|
+
return /\brouting["']?\s*[:=]/.test(readFileSync(join(root, configFile), "utf8"));
|
|
1419
|
+
} catch {
|
|
1420
|
+
return false;
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1409
1423
|
const ROUTING_SAYS = {
|
|
1410
1424
|
"prefix-except-source": "the source locale has no prefix, every other locale does",
|
|
1411
1425
|
"prefix-all": "every locale has a prefix, the source included",
|
|
@@ -1475,7 +1489,10 @@ async function doctor(cfg) {
|
|
|
1475
1489
|
if (source && Object.keys(source).length === 0) warn("source", `source catalog ${cfg.sourceLocale}.json is empty`, "write your first t`…` message and run `npx verbaly extract`");
|
|
1476
1490
|
const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
|
|
1477
1491
|
if (cfg.routing === "no-prefix" && mirrors) warn("routing", "routing is \"no-prefix\" but a render section is configured, and render writes one url tree per locale", "drop the render section, or set routing to \"prefix-except-source\" so the helpers agree with the urls");
|
|
1478
|
-
else
|
|
1492
|
+
else {
|
|
1493
|
+
const how = (configFile ? readRoutingChoice(cfg.root, configFile) : false) ? "" : " (from your setup, no routing set)";
|
|
1494
|
+
ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
|
|
1495
|
+
}
|
|
1479
1496
|
const deps = readDependencies(cfg.root);
|
|
1480
1497
|
const host = detectHost(cfg.root);
|
|
1481
1498
|
const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
|