@verbaly/compiler 0.40.0 → 0.42.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 +25 -5
- package/dist/{claude-DGo229kG.js → claude-CJsHMxsE.js} +2 -2
- package/dist/{claude-DGo229kG.js.map → claude-CJsHMxsE.js.map} +1 -1
- package/dist/cli.js +20 -2
- package/dist/cli.js.map +1 -1
- package/dist/{config-B6MP3zwt.js → config-BjWd3mkT.js} +3 -2
- package/dist/config-BjWd3mkT.js.map +1 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +39 -7
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- 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,16 +122,34 @@ 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.
|
|
132
140
|
|
|
141
|
+
## 🧪 ICU, and what it costs you
|
|
142
|
+
|
|
143
|
+
Verbaly's own syntax covers plurals, selects and formats, and [ICU message syntax](https://unicode-org.github.io/icu/userguide/format_parse/messages/) is the escape hatch for what it does not. **You pay for the escape hatch only if you open it.** The compiler reads your catalogs, and if any message uses ICU it wires the parser into the generated runtime; if none does, the parser is not in your bundle at all. Measured on a real app bundle: **544 bytes gzip**, which is 15% of the runtime.
|
|
144
|
+
|
|
145
|
+
Nothing to configure. The one case the catalogs cannot answer is a message that arrives after the build, from a CMS or a fetched catalog:
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
export default { locales: ['en', 'es'], icu: true }; // ship the parser anyway
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Without that, such a message renders **its own source text** and warns once naming the fix, rather than half-rendering into something that looks plausible.
|
|
152
|
+
|
|
133
153
|
## 🌍 Human translators & TMS
|
|
134
154
|
|
|
135
155
|
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:
|
|
@@ -201,7 +221,7 @@ The package exports two layers, and **nothing else is public**. Anything you can
|
|
|
201
221
|
|
|
202
222
|
| Area | Exports |
|
|
203
223
|
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
204
|
-
| Config & catalogs | `loadConfig` `resolveConfig` `loadCatalogs` `writeCatalog` · types `Catalog` `Catalogs`
|
|
224
|
+
| Config & catalogs | `loadConfig` `resolveConfig` `loadCatalogs` `writeCatalog` `needsIcu` · types `Catalog` `Catalogs` |
|
|
205
225
|
| Extraction | `extractProject` `collectOrigins` `syncCatalogs` `pruneCatalogs` `MessageRegistry` `stableKey` · type `SyncResult` |
|
|
206
226
|
| Codegen | `generateDts` `writeDts` `generateRuntimeModule` `generateLocaleModule` · type `RuntimeModuleOptions` |
|
|
207
227
|
| Bundler plumbing | `transformSource` `transformCode` `runBuildGate` `createSourceFilter` `isTransformTarget` `resolveVirtualId` `loadVirtualModule` `RESOLVED_VIRTUAL_ID` `LOCALE_MODULE_PREFIX` `SOURCE_FILE_RE` · types `PluginOptions` `TransformResult` |
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as isModuleNotFound } from "./config-
|
|
1
|
+
import { n as isModuleNotFound } from "./config-BjWd3mkT.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-CJsHMxsE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude-
|
|
1
|
+
{"version":3,"file":"claude-CJsHMxsE.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,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B,IAAI,CAAC,WAAW,OAAO,KAAK,OAAO,CAAC,CAAC,WAAW,GAAG,OAAO;CAE1D,OAAO,+FADO,OAAO,QAAQ,OAAO,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,KAAK,IAAI,IAAI,MAAM,KAAK,IAAI,GACkB,CAAC,CAAC,KAAK,IAAI;AACvH;AAEA,SAAgB,YAAY,SAA2B;CACrD,MAAM,OAAO,OAAO,KAAK,QAAQ,QAAQ;CACzC,OAAO;EACL,MAAM;EACN,QAAQ;GACN,MAAM;GACN,YAAY,OAAO,YAAY,KAAK,KAAK,QAAQ,CAAC,KAAK,EAAE,MAAM,SAAS,CAAC,CAAC,CAAC;GAC3E,UAAU;GACV,sBAAsB;EACxB;CACF;AACF;AAKA,eAAsB,QACpB,aAAuC,OAAO,sBACf;CAC/B,IAAI;EAEF,QAAO,MADW,KAAK,EAAA,CACZ;CACb,SAAS,OAAO;EACd,IAAI,iBAAiB,OAAO,mBAAmB,GAC7C,MAAM,IAAI,MACR,mMACA,EAAE,OAAO,MAAM,CACjB;EAEF,MAAM;CACR;AACF"}
|
package/dist/cli.js
CHANGED
|
@@ -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,8 @@ 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"),
|
|
680
|
+
icu: config.icu,
|
|
673
681
|
locales: [...locales],
|
|
674
682
|
include: config.include ?? ["{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}"],
|
|
675
683
|
exclude: config.exclude ?? ["**/node_modules/**", "**/dist/**"],
|
|
@@ -1406,6 +1414,13 @@ function counted(count, noun, many = `${noun}s`) {
|
|
|
1406
1414
|
//#endregion
|
|
1407
1415
|
//#region src/doctor.ts
|
|
1408
1416
|
const PREVIEW = 5;
|
|
1417
|
+
function readRoutingChoice(root, configFile) {
|
|
1418
|
+
try {
|
|
1419
|
+
return /\brouting["']?\s*[:=]/.test(readFileSync(join(root, configFile), "utf8"));
|
|
1420
|
+
} catch {
|
|
1421
|
+
return false;
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1409
1424
|
const ROUTING_SAYS = {
|
|
1410
1425
|
"prefix-except-source": "the source locale has no prefix, every other locale does",
|
|
1411
1426
|
"prefix-all": "every locale has a prefix, the source included",
|
|
@@ -1475,7 +1490,10 @@ async function doctor(cfg) {
|
|
|
1475
1490
|
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
1491
|
const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
|
|
1477
1492
|
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
|
|
1493
|
+
else {
|
|
1494
|
+
const how = (configFile ? readRoutingChoice(cfg.root, configFile) : false) ? "" : " (from your setup, no routing set)";
|
|
1495
|
+
ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
|
|
1496
|
+
}
|
|
1479
1497
|
const deps = readDependencies(cfg.root);
|
|
1480
1498
|
const host = detectHost(cfg.root);
|
|
1481
1499
|
const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);
|