@verbaly/compiler 0.32.0 → 0.34.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 +56 -5
- package/dist/claude-CrAkiSVP.js +53 -0
- package/dist/claude-CrAkiSVP.js.map +1 -0
- package/dist/cli.js +65 -36
- package/dist/cli.js.map +1 -1
- package/dist/config-D8gkaunO.js +68 -0
- package/dist/config-D8gkaunO.js.map +1 -0
- package/dist/index.d.ts +97 -275
- package/dist/index.js +355 -1718
- package/dist/index.js.map +1 -1
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -20,7 +20,7 @@ Extraction covers `.js`/`.ts`/`.jsx`/`.tsx` **and `.svelte`, `.vue` and `.astro`
|
|
|
20
20
|
## 🧰 CLI
|
|
21
21
|
|
|
22
22
|
```bash
|
|
23
|
-
npx verbaly init # scaffold config + locale catalogs (detects your
|
|
23
|
+
npx verbaly init # scaffold config + locale catalogs (detects your framework)
|
|
24
24
|
npx verbaly doctor # diagnose the setup (config, catalogs, wiring, types, translations)
|
|
25
25
|
npx verbaly wrap # onboarding codemod: report plain JSX text, --write wraps it in t``
|
|
26
26
|
npx verbaly extract # sync catalogs + types
|
|
@@ -69,12 +69,17 @@ Hand-edited catalogs get the same treatment as imported files: the gate does not
|
|
|
69
69
|
|
|
70
70
|
**Machine output is a draft until a human says yes.** Everything `translate` writes is recorded in `locales/.verbaly-drafts.json` (commit it, never edit it by hand). `verbaly review` lists the drafts, `--approve` accepts them, and importing a translator's file clears the flag because a human already reviewed it. `verbaly check --drafts` turns "nothing unreviewed ships" into a CI rule; plain `check` leaves it alone, since a draft has a value and is therefore not missing.
|
|
71
71
|
|
|
72
|
-
Plug your own provider in `verbaly.config.ts
|
|
72
|
+
Plug your own provider in `verbaly.config.ts`. In TypeScript, `TranslateProvider` types it for you:
|
|
73
73
|
|
|
74
74
|
```ts
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
75
|
+
import type { TranslateProvider } from '@verbaly/compiler';
|
|
76
|
+
|
|
77
|
+
const provider: TranslateProvider = async ({ sourceLocale, targetLocale, messages, origins }) => {
|
|
78
|
+
// origins maps a key to the source files it appears in, so you can translate with context
|
|
79
|
+
return { ...translated };
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
export default { sourceLocale: 'en', locales: ['en', 'es'], translate: { provider } };
|
|
78
83
|
```
|
|
79
84
|
|
|
80
85
|
## 🌍 Human translators & TMS
|
|
@@ -124,6 +129,52 @@ Per-element `data-verbaly-links='{"repo":"https://…"}'` merges over the config
|
|
|
124
129
|
|
|
125
130
|
> ⚠️ Early development (`0.x`): API not stable yet.
|
|
126
131
|
|
|
132
|
+
## 🧩 Programmatic API
|
|
133
|
+
|
|
134
|
+
Almost nobody needs this: the CLI and the framework plugins cover the whole cycle. It exists for the one case they do not, building your own integration for a bundler or a tool we do not ship.
|
|
135
|
+
|
|
136
|
+
The package exports two layers, and **nothing else is public**. Anything you can see in the source but not in this list is internal and can change in any release.
|
|
137
|
+
|
|
138
|
+
**Your project's own types**, for a typed config file or a custom provider:
|
|
139
|
+
|
|
140
|
+
`VerbalyConfig` · `ResolvedConfig` · `RenderConfig` · `TranslateConfig` · `TranslateProvider` · `TranslateRequest` · `TranslateResult` · `TranslateOptions`
|
|
141
|
+
|
|
142
|
+
**Building an integration.** This is exactly what `@verbaly/vite`, `@verbaly/unplugin`, `@verbaly/next`, `@verbaly/astro`, `@verbaly/nuxt` and `@verbaly/mcp` consume, so a third one has everything they have:
|
|
143
|
+
|
|
144
|
+
| Area | Exports |
|
|
145
|
+
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
146
|
+
| Config & catalogs | `loadConfig` `resolveConfig` `loadCatalogs` `writeCatalog` · types `Catalog` `Catalogs` |
|
|
147
|
+
| Extraction | `extractProject` `collectOrigins` `syncCatalogs` `pruneCatalogs` `MessageRegistry` `stableKey` · type `SyncResult` |
|
|
148
|
+
| Codegen | `generateDts` `writeDts` `generateRuntimeModule` `generateLocaleModule` · type `RuntimeModuleOptions` |
|
|
149
|
+
| Bundler plumbing | `transformSource` `transformCode` `runBuildGate` `createSourceFilter` `isTransformTarget` `resolveVirtualId` `loadVirtualModule` `RESOLVED_VIRTUAL_ID` `LOCALE_MODULE_PREFIX` `SOURCE_FILE_RE` · types `PluginOptions` `TransformResult` |
|
|
150
|
+
| The gate | `check` `formatCheckResult` `formatCheckWarnings` · types `CheckResult` `MissingEntry` `UnknownEntry` `BrokenEntry` `IssueSeverity` |
|
|
151
|
+
| Coverage | `status` `formatStatusResult` · types `StatusResult` `LocaleStatus` |
|
|
152
|
+
| Draft review | `loadDrafts` `saveDrafts` `markDrafts` `effectiveDrafts` · type `Drafts` |
|
|
153
|
+
| Translation | `translateCatalogs` `resolveProvider` |
|
|
154
|
+
| Static rendering | `renderSite` · types `RenderSiteOptions` `RenderSiteResult` |
|
|
155
|
+
|
|
156
|
+
A minimal plugin is `loadConfig` + `loadCatalogs` once, then `transformSource` per file and `runBuildGate` at the end:
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
import {
|
|
160
|
+
MessageRegistry,
|
|
161
|
+
loadCatalogs,
|
|
162
|
+
loadConfig,
|
|
163
|
+
runBuildGate,
|
|
164
|
+
transformSource,
|
|
165
|
+
} from '@verbaly/compiler';
|
|
166
|
+
|
|
167
|
+
const cfg = await loadConfig(process.cwd());
|
|
168
|
+
const catalogs = loadCatalogs(cfg);
|
|
169
|
+
const registry = new MessageRegistry();
|
|
170
|
+
|
|
171
|
+
// per file: rewrites t`…` to a keyed call and hands you the messages it found
|
|
172
|
+
const { messages, result } = transformSource(code, id, registry);
|
|
173
|
+
|
|
174
|
+
// at the end of the build: throws with the reason and the remedy
|
|
175
|
+
runBuildGate(cfg, registry);
|
|
176
|
+
```
|
|
177
|
+
|
|
127
178
|
## License
|
|
128
179
|
|
|
129
180
|
[MIT](https://github.com/AronSoto/verbaly/blob/develop/LICENSE) © Aron Soto
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { t as isModuleNotFound } from "./config-D8gkaunO.js";
|
|
2
|
+
//#region src/providers/claude.ts
|
|
3
|
+
const DEFAULT_MODEL = "claude-sonnet-5";
|
|
4
|
+
const SYSTEM = `You translate UI strings for the Verbaly i18n library.
|
|
5
|
+
Rules:
|
|
6
|
+
- Translate only the human-readable text, naturally for the target locale.
|
|
7
|
+
- Preserve verbatim: placeholders like {name}, format specs like {price:currency/EUR}, variant blocks like {count | one: ... | other: # ...} (translate only the text inside each variant, keep keys and # as-is), ICU syntax, named tags like <em>...</em> and escapes {{ }} || ##.
|
|
8
|
+
- Keys are opaque identifiers: return exactly the same keys, never translate or rename them.`;
|
|
9
|
+
function claudeProvider(options = {}) {
|
|
10
|
+
return async (request) => {
|
|
11
|
+
const text = (await new (await (loadSdk()))(options.apiKey ? { apiKey: options.apiKey } : {}).messages.create({
|
|
12
|
+
model: options.model ?? DEFAULT_MODEL,
|
|
13
|
+
max_tokens: options.maxTokens ?? 16e3,
|
|
14
|
+
thinking: { type: "disabled" },
|
|
15
|
+
system: SYSTEM,
|
|
16
|
+
messages: [{
|
|
17
|
+
role: "user",
|
|
18
|
+
content: buildPrompt(request)
|
|
19
|
+
}],
|
|
20
|
+
output_config: { format: batchFormat(request) }
|
|
21
|
+
})).content.find((block) => block.type === "text")?.text ?? "{}";
|
|
22
|
+
return JSON.parse(text);
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function buildPrompt(request) {
|
|
26
|
+
const origins = request.origins;
|
|
27
|
+
const context = origins && Object.keys(origins).length ? `\n\nWhere each string appears (context for tone and length, do not translate these paths):\n` + Object.entries(origins).map(([key, files]) => ` ${key}: ${files.join(", ")}`).join("\n") : "";
|
|
28
|
+
return `Translate each value from "${request.sourceLocale}" to "${request.targetLocale}". Return a JSON object with the same keys and translated values.\n\n` + JSON.stringify(request.messages, null, 2) + context;
|
|
29
|
+
}
|
|
30
|
+
function batchFormat(request) {
|
|
31
|
+
const keys = Object.keys(request.messages);
|
|
32
|
+
return {
|
|
33
|
+
type: "json_schema",
|
|
34
|
+
schema: {
|
|
35
|
+
type: "object",
|
|
36
|
+
properties: Object.fromEntries(keys.map((key) => [key, { type: "string" }])),
|
|
37
|
+
required: keys,
|
|
38
|
+
additionalProperties: false
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
async function loadSdk(load = () => import("@anthropic-ai/sdk")) {
|
|
43
|
+
try {
|
|
44
|
+
return (await load()).default;
|
|
45
|
+
} catch (error) {
|
|
46
|
+
if (isModuleNotFound(error, "@anthropic-ai/sdk")) throw new Error("[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", { cause: error });
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
export { claudeProvider };
|
|
52
|
+
|
|
53
|
+
//# sourceMappingURL=claude-CrAkiSVP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claude-CrAkiSVP.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 claudeProvider(options: ClaudeProviderOptions = {}): TranslateProvider {\n return async (request: TranslateRequest) => {\n const Anthropic = await loadSdk();\n const client = new Anthropic(options.apiKey ? { apiKey: options.apiKey } : {});\n const response = await client.messages.create({\n model: options.model ?? DEFAULT_MODEL,\n max_tokens: options.maxTokens ?? 16000,\n thinking: { type: 'disabled' },\n system: SYSTEM,\n messages: [{ role: 'user', content: buildPrompt(request) }],\n output_config: { format: batchFormat(request) },\n });\n const text = response.content.find((block) => block.type === 'text')?.text ?? '{}';\n return JSON.parse(text) as Record<string, string>;\n };\n}\n\nexport function buildPrompt(request: TranslateRequest): string {\n const origins = request.origins;\n const context =\n origins && Object.keys(origins).length\n ? `\\n\\nWhere each string appears (context for tone and length, do not translate these paths):\\n` +\n Object.entries(origins)\n .map(([key, files]) => ` ${key}: ${files.join(', ')}`)\n .join('\\n')\n : '';\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 context\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,eAAe,UAAiC,CAAC,GAAsB;CACrF,OAAO,OAAO,YAA8B;EAW1C,MAAM,QAAO,MARU,KADJ,OADK,QAAQ,IACH,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC,CAChD,CAAC,CAAC,SAAS,OAAO;GAC5C,OAAO,QAAQ,SAAS;GACxB,YAAY,QAAQ,aAAa;GACjC,UAAU,EAAE,MAAM,WAAW;GAC7B,QAAQ;GACR,UAAU,CAAC;IAAE,MAAM;IAAQ,SAAS,YAAY,OAAO;GAAE,CAAC;GAC1D,eAAe,EAAE,QAAQ,YAAY,OAAO,EAAE;EAChD,CAAC,EAAA,CACqB,QAAQ,MAAM,UAAU,MAAM,SAAS,MAAM,CAAC,EAAE,QAAQ;EAC9E,OAAO,KAAK,MAAM,IAAI;CACxB;AACF;AAEA,SAAgB,YAAY,SAAmC;CAC7D,MAAM,UAAU,QAAQ;CACxB,MAAM,UACJ,WAAW,OAAO,KAAK,OAAO,CAAC,CAAC,SAC5B,iGACA,OAAO,QAAQ,OAAO,CAAC,CACpB,KAAK,CAAC,KAAK,WAAW,KAAK,IAAI,IAAI,MAAM,KAAK,IAAI,GAAG,CAAC,CACtD,KAAK,IAAI,IACZ;CACN,OACE,8BAA8B,QAAQ,aAAa,QAAQ,QAAQ,aAAa,yEAEhF,KAAK,UAAU,QAAQ,UAAU,MAAM,CAAC,IACxC;AAEJ;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
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
3
3
|
import { parseArgs } from "node:util";
|
|
4
4
|
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
|
|
5
|
-
import { RICH_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseTags, safeAttribute } from "verbaly";
|
|
5
|
+
import { RICH_TAGS, VOID_TAGS, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseTags, safeAttribute } from "verbaly";
|
|
6
6
|
import { pathToFileURL } from "node:url";
|
|
7
7
|
import { glob } from "tinyglobby";
|
|
8
8
|
import { parse as parse$1 } from "@babel/parser";
|
|
@@ -698,6 +698,14 @@ var MessageRegistry = class {
|
|
|
698
698
|
strayImports() {
|
|
699
699
|
return [...this.files.values()].flatMap((analysis) => analysis.strayImports);
|
|
700
700
|
}
|
|
701
|
+
parseErrors() {
|
|
702
|
+
const out = [];
|
|
703
|
+
for (const [file, analysis] of this.files) if (analysis.parseError) out.push({
|
|
704
|
+
file,
|
|
705
|
+
message: analysis.parseError
|
|
706
|
+
});
|
|
707
|
+
return out;
|
|
708
|
+
}
|
|
701
709
|
origins() {
|
|
702
710
|
const out = this.usedKeys();
|
|
703
711
|
for (const analysis of this.files.values()) for (const msg of analysis.tagged) {
|
|
@@ -715,6 +723,9 @@ function stableKey(message) {
|
|
|
715
723
|
}
|
|
716
724
|
//#endregion
|
|
717
725
|
//#region src/analyze.ts
|
|
726
|
+
function parseErrorMessage(error) {
|
|
727
|
+
return error instanceof Error ? error.message : String(error);
|
|
728
|
+
}
|
|
718
729
|
const SKIP_KEYS = /* @__PURE__ */ new Set([
|
|
719
730
|
"loc",
|
|
720
731
|
"leadingComments",
|
|
@@ -723,12 +734,13 @@ const SKIP_KEYS = /* @__PURE__ */ new Set([
|
|
|
723
734
|
"extra"
|
|
724
735
|
]);
|
|
725
736
|
const DEFAULT_T_NAMES = ["t"];
|
|
737
|
+
const JSX_FILE_RE = /\.(?:[cm]?jsx?|tsx)$/;
|
|
726
738
|
function analyze(code, file, options = {}) {
|
|
727
739
|
const names = new Set(options.tNames ?? DEFAULT_T_NAMES);
|
|
728
740
|
const ast = parse$1(code, {
|
|
729
741
|
sourceType: "module",
|
|
730
742
|
errorRecovery: true,
|
|
731
|
-
plugins:
|
|
743
|
+
plugins: JSX_FILE_RE.test(file) ? ["typescript", "jsx"] : ["typescript"]
|
|
732
744
|
});
|
|
733
745
|
const tagged = [];
|
|
734
746
|
const usedKeys = [];
|
|
@@ -995,7 +1007,17 @@ function isNode(value) {
|
|
|
995
1007
|
//#region src/sfc.ts
|
|
996
1008
|
const SFC_FILE_RE = /\.(?:svelte|vue|astro)$/;
|
|
997
1009
|
function analyzeFile(code, file) {
|
|
998
|
-
|
|
1010
|
+
if (SFC_FILE_RE.test(file)) return analyzeSfc(code, file);
|
|
1011
|
+
try {
|
|
1012
|
+
return analyze(code, file);
|
|
1013
|
+
} catch (error) {
|
|
1014
|
+
return {
|
|
1015
|
+
tagged: [],
|
|
1016
|
+
usedKeys: [],
|
|
1017
|
+
strayImports: [],
|
|
1018
|
+
parseError: parseErrorMessage(error)
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
999
1021
|
}
|
|
1000
1022
|
const SCRIPT_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi;
|
|
1001
1023
|
const STYLE_RE = /<style\b[^>]*>[\s\S]*?<\/style\s*>/gi;
|
|
@@ -1011,12 +1033,17 @@ function analyzeSfc(code, file) {
|
|
|
1011
1033
|
const tagged = [];
|
|
1012
1034
|
const usedKeys = [];
|
|
1013
1035
|
const strayImports = [];
|
|
1036
|
+
let parseError;
|
|
1037
|
+
const block = (segment, offset) => {
|
|
1038
|
+
parseError ??= segment.error;
|
|
1039
|
+
merge(segment.analysis, offset, false);
|
|
1040
|
+
};
|
|
1014
1041
|
const frontmatter = file.endsWith(".astro") ? FRONTMATTER_RE.exec(code) : null;
|
|
1015
|
-
if (frontmatter?.[2])
|
|
1042
|
+
if (frontmatter?.[2]) block(analyzeSegment(frontmatter[2], file, options), frontmatter[1].length);
|
|
1016
1043
|
for (const match of code.matchAll(SCRIPT_RE)) {
|
|
1017
1044
|
const content = match[2];
|
|
1018
1045
|
if (!content) continue;
|
|
1019
|
-
|
|
1046
|
+
block(analyzeSegment(content, file, options), match.index + match[1].length);
|
|
1020
1047
|
}
|
|
1021
1048
|
const markup = blank(blank(blank(frontmatter ? " ".repeat(frontmatter[0].length) + code.slice(frontmatter[0].length) : code, SCRIPT_RE), STYLE_RE), COMMENT_RE);
|
|
1022
1049
|
const candidates = svelte ? CANDIDATE_SVELTE : CANDIDATE_VUE;
|
|
@@ -1030,13 +1057,14 @@ function analyzeSfc(code, file) {
|
|
|
1030
1057
|
if (range >= ranges.length || start < ranges[range][0]) continue;
|
|
1031
1058
|
const end = expressionExtent(markup, start);
|
|
1032
1059
|
if (end === void 0) continue;
|
|
1033
|
-
merge(analyzeSegment(code.slice(start, end), file, options), start, true);
|
|
1060
|
+
merge(analyzeSegment(code.slice(start, end), file, options).analysis, start, true);
|
|
1034
1061
|
consumedTo = end;
|
|
1035
1062
|
}
|
|
1036
1063
|
return {
|
|
1037
1064
|
tagged,
|
|
1038
1065
|
usedKeys,
|
|
1039
|
-
strayImports
|
|
1066
|
+
strayImports,
|
|
1067
|
+
...parseError && { parseError }
|
|
1040
1068
|
};
|
|
1041
1069
|
function merge(analysis, offset, markupSegment) {
|
|
1042
1070
|
if (!analysis) return;
|
|
@@ -1059,9 +1087,9 @@ function analyzeSfc(code, file) {
|
|
|
1059
1087
|
}
|
|
1060
1088
|
function analyzeSegment(code, file, options) {
|
|
1061
1089
|
try {
|
|
1062
|
-
return analyze(code, file, options);
|
|
1063
|
-
} catch {
|
|
1064
|
-
return;
|
|
1090
|
+
return { analysis: analyze(code, file, options) };
|
|
1091
|
+
} catch (error) {
|
|
1092
|
+
return { error: parseErrorMessage(error) };
|
|
1065
1093
|
}
|
|
1066
1094
|
}
|
|
1067
1095
|
function blank(source, re) {
|
|
@@ -1370,6 +1398,12 @@ async function doctor(cfg) {
|
|
|
1370
1398
|
}
|
|
1371
1399
|
const registry = await extractProject(cfg);
|
|
1372
1400
|
if (scanning) {
|
|
1401
|
+
const unreadable = registry.parseErrors();
|
|
1402
|
+
if (unreadable.length > 0) {
|
|
1403
|
+
const first = unreadable[0];
|
|
1404
|
+
const one = unreadable.length === 1;
|
|
1405
|
+
warn("sources", `${unreadable.length} ${one ? "file" : "files"} could not be parsed, so ${one ? "its" : "their"} messages are not extracted (${rel(first.file)}: ${first.message})`, "fix the syntax error, or exclude the file in your config if it is not source");
|
|
1406
|
+
}
|
|
1373
1407
|
const stray = registry.strayImports();
|
|
1374
1408
|
if (stray.length > 0) {
|
|
1375
1409
|
const files = [...new Set(stray.map((entry) => rel(entry.file)))];
|
|
@@ -2098,22 +2132,7 @@ function csvRows(content) {
|
|
|
2098
2132
|
//#region src/render.ts
|
|
2099
2133
|
const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
|
|
2100
2134
|
const HREFLANG_CLOSE = "<!--/verbaly:hreflang-->";
|
|
2101
|
-
const
|
|
2102
|
-
"area",
|
|
2103
|
-
"base",
|
|
2104
|
-
"br",
|
|
2105
|
-
"col",
|
|
2106
|
-
"embed",
|
|
2107
|
-
"hr",
|
|
2108
|
-
"img",
|
|
2109
|
-
"input",
|
|
2110
|
-
"link",
|
|
2111
|
-
"meta",
|
|
2112
|
-
"param",
|
|
2113
|
-
"source",
|
|
2114
|
-
"track",
|
|
2115
|
-
"wbr"
|
|
2116
|
-
]);
|
|
2135
|
+
const VOID = new Set(VOID_TAGS);
|
|
2117
2136
|
const START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g;
|
|
2118
2137
|
const ATTR = /([^\s=/"'<>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
|
|
2119
2138
|
function renderHtml(html, options) {
|
|
@@ -2160,7 +2179,7 @@ function renderHtml(html, options) {
|
|
|
2160
2179
|
const args = parseArgs$1(attrs.get(argsAttr));
|
|
2161
2180
|
if (key) {
|
|
2162
2181
|
if (!v.has(key)) missing.add(key);
|
|
2163
|
-
else if (!
|
|
2182
|
+
else if (!VOID.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
|
|
2164
2183
|
const close = findClose(html, tagName, openEnd, inSkip);
|
|
2165
2184
|
if (close) {
|
|
2166
2185
|
const text = t(key, args);
|
|
@@ -2352,7 +2371,7 @@ function richToHtml(nodes, allowed, links) {
|
|
|
2352
2371
|
if (target) attrs += ` target="${escapeAttr(target)}"`;
|
|
2353
2372
|
if (rel) attrs += ` rel="${escapeAttr(rel)}"`;
|
|
2354
2373
|
out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;
|
|
2355
|
-
} else if (allowed.has(node.name)) out += `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
|
|
2374
|
+
} else if (allowed.has(node.name)) out += VOID.has(node.name) ? `<${node.name}>` : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;
|
|
2356
2375
|
else out += richToHtml(node.children, allowed, links);
|
|
2357
2376
|
return out;
|
|
2358
2377
|
}
|
|
@@ -2705,7 +2724,7 @@ Options:
|
|
|
2705
2724
|
--out <path> export directory (export, default: verbaly-export)
|
|
2706
2725
|
--missing export only untranslated entries (export)
|
|
2707
2726
|
--overwrite replace existing translations on import (import)
|
|
2708
|
-
--locale <id> pseudo-locale id (pseudo) /
|
|
2727
|
+
--locale <id> pseudo-locale id (pseudo) / one locale only (review, import)
|
|
2709
2728
|
--site <path> built site directory (render, default: dist)
|
|
2710
2729
|
--attribute <name> base data attribute (render, default: data-verbaly)
|
|
2711
2730
|
--base-url <url> site origin, enables hreflang alternates (render)
|
|
@@ -2781,7 +2800,7 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
2781
2800
|
warn: "⚠",
|
|
2782
2801
|
error: "✗"
|
|
2783
2802
|
};
|
|
2784
|
-
console.log(`[verbaly] doctor: ${result.entries.length}
|
|
2803
|
+
console.log(`[verbaly] doctor: ${plural(result.entries.length, "check")}`);
|
|
2785
2804
|
for (const entry of result.entries) {
|
|
2786
2805
|
const line = ` ${icon[entry.level]} ${entry.check}: ${entry.message}`;
|
|
2787
2806
|
if (entry.level === "error") console.error(line);
|
|
@@ -2816,8 +2835,9 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
2816
2835
|
if (cfg.dts !== false) writeDts(cfg, catalogs[cfg.sourceLocale] ?? {}, cfg.dts);
|
|
2817
2836
|
}
|
|
2818
2837
|
const total = registry.messages().size;
|
|
2819
|
-
console.log(`[verbaly] ${total}
|
|
2838
|
+
console.log(`[verbaly] ${plural(total, "message")} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`);
|
|
2820
2839
|
for (const [locale, keys] of Object.entries(added)) console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);
|
|
2840
|
+
reportParseErrors(cfg, registry);
|
|
2821
2841
|
reportEscapedSyntax(cfg, registry);
|
|
2822
2842
|
}
|
|
2823
2843
|
await runExtract();
|
|
@@ -2830,12 +2850,12 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
2830
2850
|
if (command === "wrap") {
|
|
2831
2851
|
const result = await wrapProject(cfg, { write: values.write });
|
|
2832
2852
|
if (result.wrapped.length === 0 && result.skipped.length === 0) {
|
|
2833
|
-
console.log(`[verbaly] nothing to wrap (${result.files}
|
|
2853
|
+
console.log(`[verbaly] nothing to wrap (${plural(result.files, "file")} scanned) ✓`);
|
|
2834
2854
|
return;
|
|
2835
2855
|
}
|
|
2836
2856
|
const verb = values.write ? "wrapped" : "would wrap";
|
|
2837
2857
|
const note = values.write ? "" : " (report only, use --write to apply)";
|
|
2838
|
-
console.log(`[verbaly] ${verb} ${result.wrapped.length}
|
|
2858
|
+
console.log(`[verbaly] ${verb} ${plural(result.wrapped.length, "text")} in ${plural(result.changed.length, "file")}${note}`);
|
|
2839
2859
|
for (const entry of result.wrapped) {
|
|
2840
2860
|
const attr = entry.kind === "attribute" ? `${entry.attribute} → ` : "";
|
|
2841
2861
|
console.log(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
|
|
@@ -3014,8 +3034,8 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3014
3034
|
sitemap: values.sitemap,
|
|
3015
3035
|
clean: values.clean
|
|
3016
3036
|
});
|
|
3017
|
-
console.log(`[verbaly] ${result.files}
|
|
3018
|
-
for (const [locale, keys] of Object.entries(result.missing)) console.warn(` ${locale}: ${keys.length}
|
|
3037
|
+
console.log(`[verbaly] ${plural(result.files, "page")} × ${plural(result.locales.length, "locale")} (${result.locales.join(", ")})`);
|
|
3038
|
+
for (const [locale, keys] of Object.entries(result.missing)) console.warn(` ${locale}: ${plural(keys.length, "key")} not pre-filled: ${keys.join(", ")}`);
|
|
3019
3039
|
return;
|
|
3020
3040
|
}
|
|
3021
3041
|
if (command === "pseudo") {
|
|
@@ -3023,7 +3043,7 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
3023
3043
|
const locale = values.locale ?? "en-XA";
|
|
3024
3044
|
const keys = pseudoCatalogs(cfg, catalogs, locale);
|
|
3025
3045
|
writeCatalog(cfg, locale, catalogs[locale] ?? {});
|
|
3026
|
-
console.log(`[verbaly] ${keys.length}
|
|
3046
|
+
console.log(`[verbaly] ${plural(keys.length, "message")} pseudo-localized → ${locale}`);
|
|
3027
3047
|
return;
|
|
3028
3048
|
}
|
|
3029
3049
|
console.error(`[verbaly] unknown command "${command}"\n${HELP}`);
|
|
@@ -3033,6 +3053,15 @@ function formatCliError(error) {
|
|
|
3033
3053
|
const message = error instanceof Error ? error.message : String(error);
|
|
3034
3054
|
return message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`;
|
|
3035
3055
|
}
|
|
3056
|
+
function plural(count, noun) {
|
|
3057
|
+
return `${count} ${noun}${count === 1 ? "" : "s"}`;
|
|
3058
|
+
}
|
|
3059
|
+
function reportParseErrors(cfg, registry) {
|
|
3060
|
+
for (const { file, message } of registry.parseErrors()) {
|
|
3061
|
+
const rel = relative(cfg.root, file).replaceAll("\\", "/");
|
|
3062
|
+
console.warn(` ${rel}: could not be parsed (${message}), its messages were not extracted`);
|
|
3063
|
+
}
|
|
3064
|
+
}
|
|
3036
3065
|
function reportEscapedSyntax(cfg, registry) {
|
|
3037
3066
|
for (const msg of registry.messages().values()) {
|
|
3038
3067
|
const slice = escapedSyntax(msg.message);
|