@verbaly/compiler 0.65.0 → 0.66.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 +5 -3
- package/dist/{claude--aMMLA-N.js → claude-BmD8W9uW.js} +29 -8
- package/dist/claude-BmD8W9uW.js.map +1 -0
- package/dist/{claude-arq_js_3.js → claude-D-j-ZiYH.js} +29 -8
- package/dist/claude-D-j-ZiYH.js.map +1 -0
- package/dist/cli.js +91 -54
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +63 -45
- package/dist/index.js.map +1 -1
- package/dist/{config-DYlbHrPc.js → text-M4XbWU6N.js} +17 -3
- package/dist/text-M4XbWU6N.js.map +1 -0
- package/package.json +3 -3
- package/dist/claude--aMMLA-N.js.map +0 -1
- package/dist/claude-arq_js_3.js.map +0 -1
- package/dist/config-DYlbHrPc.js.map +0 -1
package/README.md
CHANGED
|
@@ -26,7 +26,7 @@ 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
|
|
29
|
+
npx verbaly extract --prune # drop orphaned keys (waits while any source file does not parse)
|
|
30
30
|
npx verbaly status # coverage per locale, plus unreviewed and broken counts
|
|
31
31
|
npx verbaly check # exit 1 if anything is missing or broken (CI)
|
|
32
32
|
npx verbaly translate # fill missing translations via Claude (or your provider), as drafts
|
|
@@ -59,6 +59,8 @@ Two more are reported as **warnings** and keep the exit code at 0, because the t
|
|
|
59
59
|
|
|
60
60
|
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
61
|
|
|
62
|
+
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.
|
|
63
|
+
|
|
62
64
|
```bash
|
|
63
65
|
npx verbaly check # text report
|
|
64
66
|
npx verbaly check --reporter github # ::error and ::warning annotations on the PR, at the source line
|
|
@@ -69,7 +71,7 @@ Hand-edited catalogs get the same treatment as imported files: the gate does not
|
|
|
69
71
|
|
|
70
72
|
## 🤖 Machine translation
|
|
71
73
|
|
|
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.
|
|
74
|
+
`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
75
|
|
|
74
76
|
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
77
|
|
|
@@ -140,7 +142,7 @@ Under a prefix mode that goes to `/es/…`, which is already rendered in Spanish
|
|
|
140
142
|
await switchLocale('es', { navigate: (path) => router.push(path) });
|
|
141
143
|
```
|
|
142
144
|
|
|
143
|
-
`npx verbaly doctor` names the mode you are in, and says so when
|
|
145
|
+
`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
146
|
|
|
145
147
|
## 🧪 What the runtime carries, and what it does not
|
|
146
148
|
|
|
@@ -1,6 +1,17 @@
|
|
|
1
|
-
import { n as isModuleNotFound } from "./
|
|
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
|
|
17
|
-
|
|
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
|
|
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
|
-
|
|
28
|
-
if (response.stop_reason === "
|
|
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
|
|
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":"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"}
|
|
@@ -1,6 +1,17 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { r as isModuleNotFound, 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
|
|
17
|
-
|
|
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
|
|
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
|
-
|
|
28
|
-
if (response.stop_reason === "
|
|
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-
|
|
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":"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"}
|
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
3
3
|
import { parseArgs } from "node:util";
|
|
4
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync,
|
|
4
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
|
|
5
5
|
import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseIcu, parseTags, safeAttribute } from "verbaly";
|
|
6
6
|
import { pathToFileURL } from "node:url";
|
|
7
7
|
import { glob } from "tinyglobby";
|
|
@@ -10,6 +10,12 @@ import { createHash } from "node:crypto";
|
|
|
10
10
|
import MagicString from "magic-string";
|
|
11
11
|
import picomatch from "picomatch";
|
|
12
12
|
//#region src/catalog.ts
|
|
13
|
+
function emptyCatalog() {
|
|
14
|
+
return Object.create(null);
|
|
15
|
+
}
|
|
16
|
+
function own(catalog, key) {
|
|
17
|
+
return Object.hasOwn(catalog, key) ? catalog[key] : void 0;
|
|
18
|
+
}
|
|
13
19
|
function catalogPath(cfg, locale) {
|
|
14
20
|
return join(cfg.dir, `${locale}.json`);
|
|
15
21
|
}
|
|
@@ -36,8 +42,9 @@ function readTree(cfg, locale) {
|
|
|
36
42
|
return {};
|
|
37
43
|
}
|
|
38
44
|
const parsed = parseTree(content);
|
|
39
|
-
if (parsed)
|
|
40
|
-
throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not
|
|
45
|
+
if (parsed === void 0) throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`);
|
|
46
|
+
if (!isTree(parsed)) throw new Error(`[verbaly] ${catalogPath(cfg, locale)} is not a JSON object of messages, fix or delete the file`);
|
|
47
|
+
return parsed;
|
|
41
48
|
}
|
|
42
49
|
function parseTree(content) {
|
|
43
50
|
const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
|
|
@@ -47,6 +54,9 @@ function parseTree(content) {
|
|
|
47
54
|
return;
|
|
48
55
|
}
|
|
49
56
|
}
|
|
57
|
+
function isTree(value) {
|
|
58
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
59
|
+
}
|
|
50
60
|
function loadCatalogs(cfg) {
|
|
51
61
|
const catalogs = {};
|
|
52
62
|
for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);
|
|
@@ -116,7 +126,8 @@ function writeCatalog(cfg, locale, catalog) {
|
|
|
116
126
|
} catch {
|
|
117
127
|
mkdirSync(cfg.dir, { recursive: true });
|
|
118
128
|
}
|
|
119
|
-
const
|
|
129
|
+
const parsed = existing === void 0 ? void 0 : parseTree(existing);
|
|
130
|
+
const previous = isTree(parsed) ? parsed : void 0;
|
|
120
131
|
const serialized = serializeCatalog(catalog, wantsNesting(cfg, locale, existing, previous), previous);
|
|
121
132
|
if (existing === serialized) return serialized;
|
|
122
133
|
writeFileSync(path, serialized);
|
|
@@ -241,7 +252,7 @@ function matchBrace$1(message, start) {
|
|
|
241
252
|
}
|
|
242
253
|
function pseudoCatalogs(cfg, catalogs, locale = PSEUDO_LOCALE) {
|
|
243
254
|
const source = catalogs[cfg.sourceLocale] ?? {};
|
|
244
|
-
const target =
|
|
255
|
+
const target = emptyCatalog();
|
|
245
256
|
for (const [key, msg] of Object.entries(source)) target[key] = msg ? pseudoLocalize(msg) : "";
|
|
246
257
|
catalogs[locale] = target;
|
|
247
258
|
return Object.keys(target).filter((key) => target[key]);
|
|
@@ -294,9 +305,18 @@ async function loadConfigFile(root) {
|
|
|
294
305
|
if (existsSync(path)) return loadTsConfig(path);
|
|
295
306
|
}
|
|
296
307
|
const jsonPath = join(root, "verbaly.config.json");
|
|
297
|
-
if (existsSync(jsonPath)) return
|
|
308
|
+
if (existsSync(jsonPath)) return readJsonConfig(jsonPath);
|
|
298
309
|
return {};
|
|
299
310
|
}
|
|
311
|
+
function readJsonConfig(path) {
|
|
312
|
+
const content = readFileSync(path, "utf8");
|
|
313
|
+
const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
|
|
314
|
+
try {
|
|
315
|
+
return JSON.parse(body);
|
|
316
|
+
} catch (error) {
|
|
317
|
+
throw new Error(`[verbaly] ${path} is not valid JSON: ${error.message}`, { cause: error });
|
|
318
|
+
}
|
|
319
|
+
}
|
|
300
320
|
async function loadTsConfig(path) {
|
|
301
321
|
try {
|
|
302
322
|
const { bundleRequire } = await import("bundle-require");
|
|
@@ -653,7 +673,7 @@ function reachableCategories(locale, ordinal) {
|
|
|
653
673
|
if (hit) return hit;
|
|
654
674
|
let out;
|
|
655
675
|
try {
|
|
656
|
-
const rules = new Intl.PluralRules(locale, { type });
|
|
676
|
+
const rules = new Intl.PluralRules(locale.replace(/_/g, "-"), { type });
|
|
657
677
|
const seen = /* @__PURE__ */ new Set();
|
|
658
678
|
for (let n = 0; n <= COUNT_PROBE; n++) seen.add(rules.select(n));
|
|
659
679
|
out = [...seen];
|
|
@@ -703,7 +723,7 @@ function check(cfg, catalogs, registry) {
|
|
|
703
723
|
issue: issue.message
|
|
704
724
|
});
|
|
705
725
|
};
|
|
706
|
-
const sourceText =
|
|
726
|
+
const sourceText = Object.assign(emptyCatalog(), source);
|
|
707
727
|
for (const [key, entry] of extracted) if (!sourceText[key]) sourceText[key] = entry.message;
|
|
708
728
|
for (const [key, text] of Object.entries(sourceText)) add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));
|
|
709
729
|
for (const locale of cfg.locales) {
|
|
@@ -959,7 +979,9 @@ declare module 'virtual:verbaly/locale/*' {
|
|
|
959
979
|
`;
|
|
960
980
|
}
|
|
961
981
|
function writeDts(cfg, catalog, file) {
|
|
962
|
-
file
|
|
982
|
+
const target = file === void 0 ? cfg.dts : file;
|
|
983
|
+
if (target === false) return;
|
|
984
|
+
file = target ?? join(cfg.root, "verbaly.d.ts");
|
|
963
985
|
const content = generateDts(catalog, { inlineCatalog: cfg.render.inlineCatalog === true });
|
|
964
986
|
try {
|
|
965
987
|
if (readFileSync(file, "utf8") === content) return;
|
|
@@ -1554,22 +1576,22 @@ async function extractProject(cfg) {
|
|
|
1554
1576
|
}
|
|
1555
1577
|
async function collectOrigins(cfg, reuse) {
|
|
1556
1578
|
const registry = reuse ?? await extractProject(cfg);
|
|
1557
|
-
const origins =
|
|
1579
|
+
const origins = Object.create(null);
|
|
1558
1580
|
for (const [key, files] of registry.origins()) origins[key] = files.map((file) => relative(cfg.root, file).replaceAll("\\", "/"));
|
|
1559
1581
|
return origins;
|
|
1560
1582
|
}
|
|
1561
1583
|
function syncCatalogs(cfg, catalogs, registry) {
|
|
1562
1584
|
const added = {};
|
|
1563
|
-
const source = catalogs[cfg.sourceLocale] ??=
|
|
1564
|
-
for (const [key, msg] of registry.messages()) if (source
|
|
1585
|
+
const source = catalogs[cfg.sourceLocale] ??= emptyCatalog();
|
|
1586
|
+
for (const [key, msg] of registry.messages()) if (own(source, key) !== msg.message) {
|
|
1565
1587
|
source[key] = msg.message;
|
|
1566
1588
|
(added[cfg.sourceLocale] ??= []).push(key);
|
|
1567
1589
|
}
|
|
1568
1590
|
const needed = Object.keys(source);
|
|
1569
1591
|
for (const locale of cfg.locales) {
|
|
1570
1592
|
if (locale === cfg.sourceLocale) continue;
|
|
1571
|
-
const catalog = catalogs[locale] ??=
|
|
1572
|
-
for (const key of needed) if (catalog
|
|
1593
|
+
const catalog = catalogs[locale] ??= emptyCatalog();
|
|
1594
|
+
for (const key of needed) if (own(catalog, key) === void 0) {
|
|
1573
1595
|
catalog[key] = "";
|
|
1574
1596
|
(added[locale] ??= []).push(key);
|
|
1575
1597
|
}
|
|
@@ -1577,8 +1599,9 @@ function syncCatalogs(cfg, catalogs, registry) {
|
|
|
1577
1599
|
return { added };
|
|
1578
1600
|
}
|
|
1579
1601
|
function pruneCatalogs(cfg, catalogs, registry) {
|
|
1580
|
-
const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
|
|
1581
1602
|
const removed = {};
|
|
1603
|
+
if (registry.parseErrors().length > 0) return removed;
|
|
1604
|
+
const keep = /* @__PURE__ */ new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);
|
|
1582
1605
|
for (const locale of cfg.locales) {
|
|
1583
1606
|
const catalog = catalogs[locale];
|
|
1584
1607
|
if (!catalog) continue;
|
|
@@ -1652,17 +1675,22 @@ async function doctor(cfg) {
|
|
|
1652
1675
|
error(`locale ${locale}`, `${rel(file)} is missing`, "run `npx verbaly extract` to create it");
|
|
1653
1676
|
continue;
|
|
1654
1677
|
}
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
const bad = badLeaf(parsed);
|
|
1658
|
-
if (bad) {
|
|
1659
|
-
catalogsHealthy = false;
|
|
1660
|
-
error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad}"`, "catalog values are text (groups of text are fine); fix the value");
|
|
1661
|
-
} else catalogs[locale] = flatten(parsed);
|
|
1662
|
-
} catch {
|
|
1678
|
+
const parsed = parseTree(readFileSync(file, "utf8"));
|
|
1679
|
+
if (parsed === void 0) {
|
|
1663
1680
|
catalogsHealthy = false;
|
|
1664
1681
|
error(`locale ${locale}`, `${rel(file)} is not valid JSON`, "repair the file (or delete it and run `npx verbaly extract`)");
|
|
1682
|
+
continue;
|
|
1683
|
+
}
|
|
1684
|
+
if (!isTree(parsed)) {
|
|
1685
|
+
catalogsHealthy = false;
|
|
1686
|
+
error(`locale ${locale}`, `${rel(file)} is not a JSON object of messages`, "a catalog is an object of texts (groups of text are fine): fix the file");
|
|
1687
|
+
continue;
|
|
1665
1688
|
}
|
|
1689
|
+
const bad = badLeaf(parsed);
|
|
1690
|
+
if (bad) {
|
|
1691
|
+
catalogsHealthy = false;
|
|
1692
|
+
error(`locale ${locale}`, `${rel(file)} has a non-string value at "${bad}"`, "catalog values are text (groups of text are fine); fix the value");
|
|
1693
|
+
} else catalogs[locale] = flatten(parsed);
|
|
1666
1694
|
}
|
|
1667
1695
|
if (catalogsHealthy) {
|
|
1668
1696
|
const how = cfg.localesDeclared ? "" : ", no locales set, so the catalog files decide";
|
|
@@ -1679,6 +1707,7 @@ async function doctor(cfg) {
|
|
|
1679
1707
|
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`");
|
|
1680
1708
|
const mirrors = cfg.render.site !== void 0 || Object.keys(cfg.render).length > 0;
|
|
1681
1709
|
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");
|
|
1710
|
+
else if (cfg.routing === "prefix-all" && mirrors) warn("routing", `routing is "prefix-all" but render keeps ${cfg.sourceLocale} at the root, so its links point at a /${cfg.sourceLocale}/ tree nobody wrote`, "set routing to \"prefix-except-source\", the url tree render writes");
|
|
1682
1711
|
else {
|
|
1683
1712
|
const how = (configFile ? readRoutingChoice(cfg.root, configFile) : false) ? "" : " (from your setup, no routing set)";
|
|
1684
1713
|
ok("routing", `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);
|
|
@@ -1719,7 +1748,8 @@ async function doctor(cfg) {
|
|
|
1719
1748
|
const extracted = registry.messages();
|
|
1720
1749
|
const used = registry.usedKeys();
|
|
1721
1750
|
const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));
|
|
1722
|
-
|
|
1751
|
+
const unread = registry.parseErrors().length > 0;
|
|
1752
|
+
if (orphans.length > 0) warn("orphans", `${counted(orphans.length, "catalog key")} no longer referenced in code (${preview(orphans)})`, unread ? "fix the files that do not parse first, they may use these, and `npx verbaly extract --prune` leaves every key alone until then" : "run `npx verbaly extract --prune` to drop them");
|
|
1723
1753
|
else ok("orphans", "no orphan keys");
|
|
1724
1754
|
}
|
|
1725
1755
|
const excluded = cfg.bundle.exclude ?? [];
|
|
@@ -1812,7 +1842,7 @@ function effectiveDrafts(drafts, catalogs) {
|
|
|
1812
1842
|
const out = {};
|
|
1813
1843
|
for (const [locale, keys] of Object.entries(drafts)) {
|
|
1814
1844
|
const catalog = catalogs[locale] ?? {};
|
|
1815
|
-
const live = keys.filter((key) => catalog
|
|
1845
|
+
const live = keys.filter((key) => own(catalog, key));
|
|
1816
1846
|
if (live.length) out[locale] = live;
|
|
1817
1847
|
}
|
|
1818
1848
|
return out;
|
|
@@ -2216,8 +2246,8 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
|
|
|
2216
2246
|
};
|
|
2217
2247
|
const jobs = [];
|
|
2218
2248
|
for (const locale of targets) {
|
|
2219
|
-
const catalog = catalogs[locale] ??=
|
|
2220
|
-
const missing = Object.keys(source).filter((key) => source[key] && !catalog
|
|
2249
|
+
const catalog = catalogs[locale] ??= emptyCatalog();
|
|
2250
|
+
const missing = Object.keys(source).filter((key) => source[key] && !own(catalog, key));
|
|
2221
2251
|
if (missing.length === 0) continue;
|
|
2222
2252
|
if (options.dryRun) {
|
|
2223
2253
|
result.pending[locale] = missing;
|
|
@@ -2238,7 +2268,7 @@ async function translateCatalogs(cfg, catalogs, provider, options = {}) {
|
|
|
2238
2268
|
const { locale, keys } = job;
|
|
2239
2269
|
const catalog = catalogs[locale];
|
|
2240
2270
|
const messages = Object.fromEntries(keys.map((key) => [key, source[key]]));
|
|
2241
|
-
const origins = options.origins ? Object.fromEntries(keys.filter((key) => options.origins
|
|
2271
|
+
const origins = options.origins ? Object.fromEntries(keys.filter((key) => Object.hasOwn(options.origins, key)).map((key) => [key, options.origins[key]])) : void 0;
|
|
2242
2272
|
let out;
|
|
2243
2273
|
try {
|
|
2244
2274
|
out = await attempt(() => provider({
|
|
@@ -2307,7 +2337,7 @@ function formatTranslateFailures(failed) {
|
|
|
2307
2337
|
async function resolveProvider(cfg, model) {
|
|
2308
2338
|
const configured = cfg.translate.provider;
|
|
2309
2339
|
if (typeof configured === "function") return configured;
|
|
2310
|
-
const { claudeProvider } = await import("./claude-
|
|
2340
|
+
const { claudeProvider } = await import("./claude-BmD8W9uW.js");
|
|
2311
2341
|
return claudeProvider({ model: model ?? cfg.translate.model });
|
|
2312
2342
|
}
|
|
2313
2343
|
function structureMatches(source, translated) {
|
|
@@ -2349,14 +2379,15 @@ function exportCatalogs(cfg, catalogs, options = {}) {
|
|
|
2349
2379
|
const targets = targetLocales(cfg, options.locales);
|
|
2350
2380
|
if (isMobileFormat(format)) return exportMobile(cfg, catalogs, format, dir, source, targets);
|
|
2351
2381
|
const files = [];
|
|
2382
|
+
const origins = options.origins;
|
|
2352
2383
|
mkdirSync(dir, { recursive: true });
|
|
2353
2384
|
for (const locale of targets) {
|
|
2354
|
-
const catalog = catalogs[locale] ??
|
|
2385
|
+
const catalog = catalogs[locale] ?? emptyCatalog();
|
|
2355
2386
|
const all = Object.keys(source).filter((key) => source[key]).sort().map((key) => ({
|
|
2356
2387
|
key,
|
|
2357
2388
|
source: source[key],
|
|
2358
|
-
target: catalog
|
|
2359
|
-
location:
|
|
2389
|
+
target: own(catalog, key) ?? "",
|
|
2390
|
+
location: origins && Object.hasOwn(origins, key) ? origins[key] : void 0
|
|
2360
2391
|
}));
|
|
2361
2392
|
const untranslated = all.filter((entry) => !entry.target);
|
|
2362
2393
|
const entries = options.missing ? untranslated : all;
|
|
@@ -2383,7 +2414,7 @@ function exportMobile(cfg, catalogs, format, dir, source, targets) {
|
|
|
2383
2414
|
const catalog = locale === cfg.sourceLocale ? source : catalogs[locale] ?? {};
|
|
2384
2415
|
const entries = keys.map((key) => ({
|
|
2385
2416
|
key,
|
|
2386
|
-
text: catalog
|
|
2417
|
+
text: own(catalog, key) ?? ""
|
|
2387
2418
|
})).filter((entry) => entry.text);
|
|
2388
2419
|
const relative = format === "android-xml" ? join(androidValuesDir(locale, cfg.sourceLocale), "strings.xml") : join(`${locale}.lproj`, "Localizable.strings");
|
|
2389
2420
|
const path = join(dir, relative);
|
|
@@ -2436,18 +2467,19 @@ function importCatalogs(cfg, catalogs, files, options = {}) {
|
|
|
2436
2467
|
from: detected,
|
|
2437
2468
|
to: locale
|
|
2438
2469
|
});
|
|
2439
|
-
const catalog = catalogs[locale] ??=
|
|
2470
|
+
const catalog = catalogs[locale] ??= emptyCatalog();
|
|
2440
2471
|
for (const [key, text] of Object.entries(parsed.entries)) {
|
|
2441
2472
|
if (!text.trim()) continue;
|
|
2442
|
-
|
|
2473
|
+
const from = own(source, key);
|
|
2474
|
+
if (!from) {
|
|
2443
2475
|
(result.unknown[locale] ??= []).push(key);
|
|
2444
2476
|
continue;
|
|
2445
2477
|
}
|
|
2446
|
-
if (catalog
|
|
2478
|
+
if (own(catalog, key) && !options.overwrite) {
|
|
2447
2479
|
(result.skipped[locale] ??= []).push(key);
|
|
2448
2480
|
continue;
|
|
2449
2481
|
}
|
|
2450
|
-
if (!structureMatches(
|
|
2482
|
+
if (!structureMatches(from, text)) {
|
|
2451
2483
|
(result.rejected[locale] ??= []).push(key);
|
|
2452
2484
|
continue;
|
|
2453
2485
|
}
|
|
@@ -2690,7 +2722,7 @@ function migrateCatalogs(cfg, options = {}) {
|
|
|
2690
2722
|
const written = [];
|
|
2691
2723
|
for (const locale of cfg.locales) {
|
|
2692
2724
|
const catalog = readCatalog(cfg, locale);
|
|
2693
|
-
const out =
|
|
2725
|
+
const out = Object.assign(emptyCatalog(), catalog);
|
|
2694
2726
|
for (const [key, value] of Object.entries(catalog)) {
|
|
2695
2727
|
if (typeof value !== "string") continue;
|
|
2696
2728
|
if (NESTED.test(value)) {
|
|
@@ -2871,7 +2903,7 @@ function renderHtml(html, options) {
|
|
|
2871
2903
|
};
|
|
2872
2904
|
}
|
|
2873
2905
|
function pageSlice(v, locale, used) {
|
|
2874
|
-
const slice =
|
|
2906
|
+
const slice = Object.create(null);
|
|
2875
2907
|
for (const key of used) {
|
|
2876
2908
|
const found = v.inspect(key);
|
|
2877
2909
|
slice[key] = found?.from === locale ? found.source : "";
|
|
@@ -3263,17 +3295,17 @@ function watchTree(root, options, onFile) {
|
|
|
3263
3295
|
close(name);
|
|
3264
3296
|
if (name !== options.keep && (name === "node_modules" || name.startsWith("."))) return;
|
|
3265
3297
|
try {
|
|
3266
|
-
if (!
|
|
3267
|
-
|
|
3268
|
-
|
|
3298
|
+
if (!lstatSync(join(root, name)).isDirectory()) return;
|
|
3299
|
+
open(name, true, (_event, file) => {
|
|
3300
|
+
if (file) onFile(`${name}/${file}`);
|
|
3301
|
+
});
|
|
3302
|
+
} catch (error) {
|
|
3303
|
+
if (error.code !== "ENOENT") console.warn(`[verbaly] could not watch ${name}:`, error);
|
|
3269
3304
|
}
|
|
3270
|
-
open(name, true, (_event, file) => {
|
|
3271
|
-
if (file) onFile(`${name}/${file}`);
|
|
3272
|
-
});
|
|
3273
3305
|
};
|
|
3274
|
-
open("", false, (
|
|
3306
|
+
open("", false, (event, file) => {
|
|
3275
3307
|
if (!file) return;
|
|
3276
|
-
sync(file);
|
|
3308
|
+
if (event === "rename") sync(file);
|
|
3277
3309
|
onFile(file);
|
|
3278
3310
|
});
|
|
3279
3311
|
for (const entry of readdirSync(root, { withFileTypes: true })) if (entry.isDirectory()) sync(entry.name);
|
|
@@ -3696,7 +3728,7 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3696
3728
|
root: values.root,
|
|
3697
3729
|
dir: values.dir,
|
|
3698
3730
|
sourceLocale: values.source,
|
|
3699
|
-
locales: values.locales
|
|
3731
|
+
locales: csv(values.locales)
|
|
3700
3732
|
});
|
|
3701
3733
|
if (result.created.length) console.log(`[verbaly] created: ${result.created.join(", ")}`);
|
|
3702
3734
|
if (result.skipped.length) console.log(` kept (already there): ${result.skipped.join(", ")}`);
|
|
@@ -3709,7 +3741,7 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3709
3741
|
const cfg = await loadConfig(values.root ?? process.cwd(), {
|
|
3710
3742
|
dir: values.dir,
|
|
3711
3743
|
sourceLocale: values.source,
|
|
3712
|
-
locales: values.locales
|
|
3744
|
+
locales: csv(values.locales)
|
|
3713
3745
|
});
|
|
3714
3746
|
if (command === "doctor") {
|
|
3715
3747
|
const result = await doctor(cfg);
|
|
@@ -3739,12 +3771,14 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3739
3771
|
const catalogs = loadCatalogs(cfg);
|
|
3740
3772
|
if (values.prune) {
|
|
3741
3773
|
const removed = pruneCatalogs(cfg, catalogs, registry);
|
|
3774
|
+
const unread = registry.parseErrors().length;
|
|
3775
|
+
if (unread > 0) console.warn(` prune skipped: an unparsed file may read any key (${counted(unread, "file")} below), so it waits until every file parses`);
|
|
3742
3776
|
for (const [locale, keys] of Object.entries(removed)) console.log(dryRun ? ` ${locale}: would prune ${keys.length}: ${keys.join(", ")}` : ` ${locale}: -${keys.length} pruned`);
|
|
3743
3777
|
}
|
|
3744
3778
|
const { added } = syncCatalogs(cfg, catalogs, registry);
|
|
3745
3779
|
if (!dryRun) {
|
|
3746
3780
|
for (const locale of cfg.locales) writeCatalog(cfg, locale, catalogs[locale] ?? {});
|
|
3747
|
-
|
|
3781
|
+
writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
|
|
3748
3782
|
}
|
|
3749
3783
|
const total = registry.messages().size;
|
|
3750
3784
|
console.log(`[verbaly] ${counted(total, "message")} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
|
|
@@ -3856,7 +3890,7 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3856
3890
|
if (command === "translate") {
|
|
3857
3891
|
const catalogs = loadCatalogs(cfg);
|
|
3858
3892
|
const result = await translateCatalogs(cfg, catalogs, await resolveProvider(cfg, values.model), {
|
|
3859
|
-
locales: values.locales
|
|
3893
|
+
locales: csv(values.locales),
|
|
3860
3894
|
batchSize: cfg.translate.batchSize,
|
|
3861
3895
|
concurrency: cfg.translate.concurrency,
|
|
3862
3896
|
retries: cfg.translate.retries,
|
|
@@ -3933,7 +3967,7 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3933
3967
|
return;
|
|
3934
3968
|
}
|
|
3935
3969
|
const result = exportCatalogs(cfg, loadCatalogs(cfg), {
|
|
3936
|
-
locales: values.locales
|
|
3970
|
+
locales: csv(values.locales),
|
|
3937
3971
|
format,
|
|
3938
3972
|
out: values.out,
|
|
3939
3973
|
missing: values.missing,
|
|
@@ -3993,7 +4027,7 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3993
4027
|
if (command === "render") {
|
|
3994
4028
|
const result = await renderSite(cfg, {
|
|
3995
4029
|
site: values.site,
|
|
3996
|
-
locales: values.locales
|
|
4030
|
+
locales: csv(values.locales),
|
|
3997
4031
|
attribute: values.attribute,
|
|
3998
4032
|
base: values.base,
|
|
3999
4033
|
baseUrl: values["base-url"],
|
|
@@ -4016,6 +4050,9 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
4016
4050
|
console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
|
|
4017
4051
|
process.exitCode = 1;
|
|
4018
4052
|
}
|
|
4053
|
+
function csv(value) {
|
|
4054
|
+
return value?.split(",").map((item) => item.trim()).filter(Boolean);
|
|
4055
|
+
}
|
|
4019
4056
|
function reportProgress(progress) {
|
|
4020
4057
|
const head = ` ${progress.locale} ${progress.batch}/${progress.batches}`;
|
|
4021
4058
|
if (progress.error) console.warn(`${head}: failed (${progress.error}), continuing`);
|
|
@@ -4099,6 +4136,6 @@ runCli().catch((error) => {
|
|
|
4099
4136
|
process.exitCode = 1;
|
|
4100
4137
|
});
|
|
4101
4138
|
//#endregion
|
|
4102
|
-
export { isModuleNotFound as t };
|
|
4139
|
+
export { isModuleNotFound as n, counted as t };
|
|
4103
4140
|
|
|
4104
4141
|
//# sourceMappingURL=cli.js.map
|