@verbaly/compiler 0.71.0 → 0.72.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 +19 -19
- package/dist/{claude-CusgBHrv.js → claude-Baoc6pYL.js} +2 -2
- package/dist/{claude-CusgBHrv.js.map → claude-Baoc6pYL.js.map} +1 -1
- package/dist/cli.js +108 -34
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.js +110 -29
- package/dist/index.js.map +1 -1
- package/dist/{text-dwjJ8ZDb.js → text-BMBWE8tL.js} +8 -9
- package/dist/{text-dwjJ8ZDb.js.map → text-BMBWE8tL.js.map} +1 -1
- package/package.json +6 -10
package/README.md
CHANGED
|
@@ -40,7 +40,7 @@ npx verbaly pseudo # generate a pseudo-locale catalog for i18n QA (en-XA
|
|
|
40
40
|
npx verbaly render # pre-fill data-verbaly HTML per locale (SSG, kills the FOUC)
|
|
41
41
|
```
|
|
42
42
|
|
|
43
|
-
Reads `verbaly.config.{js,mjs,ts,mts,json}` (
|
|
43
|
+
Reads `verbaly.config.{js,mjs,ts,mts,json}` (a TypeScript config is read as written, including imports without an extension, and needs nothing installed for it). Generates `locales/<locale>.json` (portable JSON, flat or nested, whichever the file already is) and the TypeScript types of your messages, [where your framework looks for them](#-typed-keys-and-where-the-types-live).
|
|
44
44
|
|
|
45
45
|
## 🚦 The gate: `check` in CI, a report in every build
|
|
46
46
|
|
|
@@ -158,7 +158,7 @@ In CI, write the types before you check them, since a fresh clone has none: `npx
|
|
|
158
158
|
|
|
159
159
|
## 🚚 Coming from i18next
|
|
160
160
|
|
|
161
|
-
`npx verbaly init` keeps the catalogs a project already has: it points the config at `src/locales`, or wherever they are, instead of starting a second set, and its next steps name `migrate` when your dependencies have i18next. `npx verbaly migrate` reports what it would change in those catalogs, and `--write` applies it: `{{name}}` becomes `{name}`, and a brace i18next showed as text is doubled, so it stays text. A format, an unescape or a nesting is left to you, each with its reason.
|
|
161
|
+
`npx verbaly init` keeps the catalogs a project already has: it points the config at `src/locales`, or wherever they are, instead of starting a second set, and its next steps name `migrate` when your dependencies have i18next. `npx verbaly migrate` reports what it would change in those catalogs, and `--write` applies it: `{{name}}` becomes `{name}`, and a brace i18next showed as text is doubled, so it stays text. A format, an unescape or a nesting is left to you, each with its reason. `verbaly.lock` remembers which languages were converted, so a later run, like `--plurals` to merge `_one` and `_other` into one message, never reads them as i18next again.
|
|
162
162
|
|
|
163
163
|
While i18next still serves some screens, give it `interpolation: { prefix: '{', suffix: '}' }` and both libraries read the converted files.
|
|
164
164
|
|
|
@@ -183,7 +183,7 @@ export default {
|
|
|
183
183
|
|
|
184
184
|
Only the terms a batch actually contains are sent, so a glossary of hundreds never becomes the prompt.
|
|
185
185
|
|
|
186
|
-
**Machine output is a draft until a human says yes.** Everything `translate` writes is recorded in `verbaly.lock`, the file that also holds the fingerprints above. Like a package manager's lockfile, Verbaly writes it and you commit it, and nobody edits it by hand; the first command that writes it says so. A `.verbaly-state.json` an older version left next to the catalogs moves into it on its own. `verbaly review` lists the drafts with the source text and the translation side by side, `--approve` accepts them (`verbaly review home.title --approve` accepts only the keys you name), and importing a translator's file clears the flag because a human already reviewed it. `import --draft` keeps them as drafts instead, for a file nobody has read yet. An agent that translates on its own saves its work through the MCP tool `verbaly_write_drafts`, which checks it like a provider's and marks it as a draft. `verbaly check --drafts` turns "nothing unreviewed ships" into a CI rule; plain `check` leaves it alone, since a draft has a value and is therefore not missing. `extract` keeps the file in step with the catalogs, so a pruned key takes its draft with it, and the file disappears when there is nothing left in it. It only ever touches the languages it read: `extract --locales es` leaves every other language's drafts and fingerprints as they were.
|
|
186
|
+
**Machine output is a draft until a human says yes.** Everything `translate` writes is recorded in `verbaly.lock`, the file that also holds the fingerprints above. Like a package manager's lockfile, Verbaly writes it and you commit it, and nobody edits it by hand; the first command that writes it says so. A `.verbaly-state.json` an older version left next to the catalogs moves into it on its own. `verbaly review` lists the drafts with the source text and the translation side by side, `--approve` accepts them (`verbaly review home.title --approve` accepts only the keys you name), and importing a translator's file clears the flag because a human already reviewed it. `import --draft` keeps them as drafts instead, for a file nobody has read yet. An agent that translates on its own saves its work through the MCP tool `verbaly_write_drafts`, which checks it like a provider's and marks it as a draft. `verbaly check --drafts` turns "nothing unreviewed ships" into a CI rule; plain `check` leaves it alone, since a draft has a value and is therefore not missing. `extract` keeps the file in step with the catalogs, so a pruned key takes its draft with it, and the file disappears when there is nothing left in it. It only ever touches the languages it read: `extract --locales es` leaves every other language's drafts and fingerprints as they were. A merge that touched it on both sides leaves git conflict markers in it, and Verbaly reads both sides: a stamp two branches wrote for one key keeps the one whose translation the catalog holds, every draft either side listed stays a draft, and the next command that writes the file writes it whole and says so, so you commit it with the merge. If the file cannot be read at all, the commands that only read it warn and go on, and the ones that would write drafts stop before writing anything: fix it by hand, because deleting it would mark every draft as reviewed.
|
|
187
187
|
|
|
188
188
|
Plug your own provider in `verbaly.config.ts`. In TypeScript, `TranslateProvider` types it for you:
|
|
189
189
|
|
|
@@ -349,21 +349,21 @@ The package exports two layers, and **nothing else is public**. Anything you can
|
|
|
349
349
|
|
|
350
350
|
**Building an integration.** This is exactly what `@verbaly/vite`, `@verbaly/unplugin`, `@verbaly/next`, `@verbaly/astro`, `@verbaly/nuxt`, `@verbaly/mcp` and `@verbaly/studio` consume, so a third one has everything they have:
|
|
351
351
|
|
|
352
|
-
| Area | Exports
|
|
353
|
-
| ----------------- |
|
|
354
|
-
| Setup | `init` · types `Host` `InitOptions` `InitResult`
|
|
355
|
-
| Config & catalogs | `loadConfig` `resolveConfig` `targetLocales` `loadCatalogs` `readCatalog` `parseCatalog` `writeCatalog` `clientCatalogs` `needsIcu` `needsRelative` · types `Catalog` `Catalogs`
|
|
356
|
-
| Extraction | `syncProject` `extractProject` `collectOrigins` `syncCatalogs` `shippedCatalogs` `pruneCatalogs` `MessageRegistry` `stableKey` `watchTree` · types `SyncProjectResult` `SyncResult` `TreeOptions`
|
|
357
|
-
| Codegen | `generateDts` `writeDts` `generateRuntimeModule` `generateLocaleModule` · types `DtsOptions` `RuntimeModuleOptions`
|
|
358
|
-
| Bundler plumbing | `transformSource` `transformCode` `runBuildGate` `createSourceFilter` `reportOutsideInclude` `isTransformTarget` `resolveVirtualId` `loadVirtualModule` `RESOLVED_VIRTUAL_ID` `LOCALE_MODULE_PREFIX` `SOURCE_FILE_RE` · types `PluginOptions` `TransformResult`
|
|
352
|
+
| Area | Exports |
|
|
353
|
+
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
354
|
+
| Setup | `init` · types `Host` `InitOptions` `InitResult` |
|
|
355
|
+
| Config & catalogs | `loadConfig` `resolveConfig` `targetLocales` `loadCatalogs` `readCatalog` `parseCatalog` `writeCatalog` `clientCatalogs` `needsIcu` `needsRelative` · types `Catalog` `Catalogs` |
|
|
356
|
+
| Extraction | `syncProject` `extractProject` `collectOrigins` `syncCatalogs` `shippedCatalogs` `pruneCatalogs` `MessageRegistry` `stableKey` `watchTree` · types `SyncProjectResult` `SyncResult` `TreeOptions` |
|
|
357
|
+
| Codegen | `generateDts` `writeDts` `generateRuntimeModule` `generateLocaleModule` · types `DtsOptions` `RuntimeModuleOptions` |
|
|
358
|
+
| Bundler plumbing | `transformSource` `transformCode` `runBuildGate` `createSourceFilter` `reportOutsideInclude` `isTransformTarget` `resolveVirtualId` `loadVirtualModule` `RESOLVED_VIRTUAL_ID` `LOCALE_MODULE_PREFIX` `SOURCE_FILE_RE` · types `PluginOptions` `TransformResult` |
|
|
359
359
|
| The gate | `check` `validateMessage` `validatePair` `formatCheckResult` `formatCheckWarnings` `collisionEntries` `formatCollision` `formatFinding` `createDevReporter` · types `Finding` `DevReporter` `CheckResult` `MissingEntry` `UnknownEntry` `BrokenEntry` `ExtraEntry` `CollisionEntry` `DivergentEntry` `OutdatedEntry` `SourceSite` `StructureIssue` `IssueSeverity` |
|
|
360
|
-
| Coverage | `status` `formatStatusResult` `counted` · types `StatusResult` `LocaleStatus`
|
|
361
|
-
| Review state | `loadDrafts` `saveDrafts` `markDrafts` `clearDrafts` `effectiveDrafts` `loadState` `readState` `updateState` `recordTranslations` `outdatedTranslations` `STATE_FILE` · types `Drafts` `State` `Fingerprints` `TranslationWrite`
|
|
362
|
-
| Translation | `translateCatalogs` `mergeTranslations` `writeDrafts` `resolveProvider` `formatTranslateFailures` · types `DraftEntry` `WriteDraftsResult`
|
|
363
|
-
| Diagnosis | `doctor` `formatDoctorEntry` `formatDoctorHealth` · types `DoctorResult` `DoctorEntry`
|
|
364
|
-
| Onboarding | `wrapProject` · types `WrapResult` `WrapEntry` `WrapSkip` `WrapBlocked` `WrapOptions`
|
|
365
|
-
| Static rendering | `renderSite` `formatRenderWarnings` · types `RenderSiteOptions` `RenderSiteResult`
|
|
366
|
-
| Error output | `formatCliError`
|
|
360
|
+
| Coverage | `status` `formatStatusResult` `counted` · types `StatusResult` `LocaleStatus` |
|
|
361
|
+
| Review state | `loadDrafts` `saveDrafts` `markDrafts` `clearDrafts` `effectiveDrafts` `loadState` `readState` `updateState` `recordTranslations` `outdatedTranslations` `STATE_FILE` · types `Drafts` `State` `Fingerprints` `TranslationWrite` |
|
|
362
|
+
| Translation | `translateCatalogs` `mergeTranslations` `writeDrafts` `resolveProvider` `formatTranslateFailures` · types `DraftEntry` `WriteDraftsResult` |
|
|
363
|
+
| Diagnosis | `doctor` `formatDoctorEntry` `formatDoctorHealth` · types `DoctorResult` `DoctorEntry` |
|
|
364
|
+
| Onboarding | `wrapProject` · types `WrapResult` `WrapEntry` `WrapSkip` `WrapBlocked` `WrapOptions` |
|
|
365
|
+
| Static rendering | `renderSite` `formatRenderWarnings` · types `RenderSiteOptions` `RenderSiteResult` |
|
|
366
|
+
| Error output | `formatCliError` |
|
|
367
367
|
|
|
368
368
|
A minimal plugin is `loadConfig` + `loadCatalogs` once, then `transformSource` per file and `runBuildGate` at the end:
|
|
369
369
|
|
|
@@ -383,11 +383,11 @@ const registry = new MessageRegistry();
|
|
|
383
383
|
// per file: rewrites t`…` to a keyed call and hands you the messages it found
|
|
384
384
|
const { messages, result } = transformSource(code, id, registry);
|
|
385
385
|
|
|
386
|
-
// at the end of the build:
|
|
386
|
+
// at the end of the build: lists what is missing or broken, and throws only with failOnMissing
|
|
387
387
|
runBuildGate(cfg, registry);
|
|
388
388
|
```
|
|
389
389
|
|
|
390
|
-
Call `reportOutsideInclude(cfg)` once when your build starts: it names every file outside `include` that writes a `` t`…` ``, which no build translates. It reads the project itself, so a cached transform never hides one. `writeDts(cfg, catalog)` writes the types where the config resolves them and returns the file and whether it changed.
|
|
390
|
+
A build that scans first, as the Vite plugin does to sync the catalogs, keeps that scan with `extractProject(cfg, { keepSource: true })` and passes it as the fourth argument of `transformSource`: a file it read unchanged is not parsed a second time. Call `reportOutsideInclude(cfg)` once when your build starts: it names every file outside `include` that writes a `` t`…` ``, which no build translates. It reads the project itself, so a cached transform never hides one. `writeDts(cfg, catalog)` writes the types where the config resolves them and returns the file and whether it changed.
|
|
391
391
|
|
|
392
392
|
A dev server that writes the catalogs goes through `syncProject`, the same path `extract`, the MCP server and Studio take: it scans (or takes the registry you hold), syncs, writes the catalogs and the types, and keeps `verbaly.lock` in step, in that order; its `findings` say once when that file first appears. Pass `confirm: true` when your registry is built file by file, so a file that changed on disk unseen is read again before its text is written back. `createDevReporter` then says each of its findings once, says it again if it goes away and comes back, and keeps a long list to a few lines.
|
|
393
393
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as counted, o as isModuleNotFound } from "./text-
|
|
1
|
+
import { n as counted, o as isModuleNotFound } from "./text-BMBWE8tL.js";
|
|
2
2
|
//#region src/providers/claude.ts
|
|
3
3
|
const DEFAULT_MODEL = "claude-sonnet-5-5";
|
|
4
4
|
const FALLBACK_MODELS = /* @__PURE__ */ new Set([
|
|
@@ -91,4 +91,4 @@ async function loadSdk(load = () => import("@anthropic-ai/sdk")) {
|
|
|
91
91
|
//#endregion
|
|
92
92
|
export { claudeProvider };
|
|
93
93
|
|
|
94
|
-
//# sourceMappingURL=claude-
|
|
94
|
+
//# sourceMappingURL=claude-Baoc6pYL.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude-
|
|
1
|
+
{"version":3,"file":"claude-Baoc6pYL.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
|
@@ -899,14 +899,25 @@ function stringEnd(code, start) {
|
|
|
899
899
|
}
|
|
900
900
|
//#endregion
|
|
901
901
|
//#region src/extract.ts
|
|
902
|
-
|
|
902
|
+
const kept = /* @__PURE__ */ new WeakMap();
|
|
903
|
+
async function extractProject(cfg, options = {}) {
|
|
903
904
|
const files = await glob(cfg.include, {
|
|
904
905
|
cwd: cfg.root,
|
|
905
906
|
ignore: cfg.exclude,
|
|
906
907
|
absolute: true
|
|
907
908
|
});
|
|
908
909
|
const registry = new MessageRegistry();
|
|
909
|
-
|
|
910
|
+
const read = options.keepSource ? /* @__PURE__ */ new Map() : null;
|
|
911
|
+
for (const file of files.sort()) {
|
|
912
|
+
const code = readFileSync(file, "utf8");
|
|
913
|
+
const analysis = analyzeFile(code, file);
|
|
914
|
+
registry.update(file, analysis);
|
|
915
|
+
read?.set(file.replaceAll("\\", "/"), {
|
|
916
|
+
code,
|
|
917
|
+
analysis
|
|
918
|
+
});
|
|
919
|
+
}
|
|
920
|
+
if (read) kept.set(registry, read);
|
|
910
921
|
return registry;
|
|
911
922
|
}
|
|
912
923
|
async function collectOrigins(cfg, reuse) {
|
|
@@ -1016,15 +1027,20 @@ function collect(nodes, out) {
|
|
|
1016
1027
|
if (node.variants) for (const [, body] of node.variants) collect(body, out);
|
|
1017
1028
|
}
|
|
1018
1029
|
}
|
|
1019
|
-
const TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
|
|
1030
|
+
const TAG = /<(\/?)([a-zA-Z][\w-]*)\s*(\/?)>/g;
|
|
1031
|
+
const BREAK$1 = /^(?:br|wbr)$/;
|
|
1020
1032
|
function markupNames(message) {
|
|
1021
1033
|
const out = /* @__PURE__ */ new Set();
|
|
1022
|
-
for (const match of message.matchAll(TAG)) if (match[1] || match[3]) out.add(match[2]);
|
|
1034
|
+
for (const match of message.matchAll(TAG)) if (match[1] || match[3] || BREAK$1.test(match[2])) out.add(match[2]);
|
|
1023
1035
|
return out;
|
|
1024
1036
|
}
|
|
1025
1037
|
function tagTokens(message, markup) {
|
|
1026
1038
|
const out = [];
|
|
1027
|
-
for (const
|
|
1039
|
+
for (const [, closing, name, selfClose] of message.matchAll(TAG)) {
|
|
1040
|
+
if (!markup.has(name)) continue;
|
|
1041
|
+
if (!BREAK$1.test(name)) out.push(`${closing}${name}${selfClose}`);
|
|
1042
|
+
else if (!closing) out.push(`${name}/`);
|
|
1043
|
+
}
|
|
1028
1044
|
return out.sort();
|
|
1029
1045
|
}
|
|
1030
1046
|
function surplus(a, b) {
|
|
@@ -1227,6 +1243,7 @@ function formatFinding(finding, root) {
|
|
|
1227
1243
|
case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
|
|
1228
1244
|
case "lock": {
|
|
1229
1245
|
const lock = sourcePlace(finding, root);
|
|
1246
|
+
if (finding.merged) return `${lock} had a merge conflict and now holds both sides, drafts and stamps included: add it to the commit that resolves the merge`;
|
|
1230
1247
|
return finding.from ? `${sourcePlace({ file: finding.from }, root)} moved to ${lock}, next to your config: commit both changes` : `${lock} now keeps the source text each translation was made for and which ones are drafts: commit it with your catalogs`;
|
|
1231
1248
|
}
|
|
1232
1249
|
}
|
|
@@ -1240,7 +1257,7 @@ function findingId(finding) {
|
|
|
1240
1257
|
case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
|
|
1241
1258
|
case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
|
|
1242
1259
|
case "unparsed": return `unparsed:${finding.file}`;
|
|
1243
|
-
case "lock": return `lock:${finding.file}`;
|
|
1260
|
+
case "lock": return `lock:${finding.merged ? "merged:" : ""}${finding.file}`;
|
|
1244
1261
|
}
|
|
1245
1262
|
}
|
|
1246
1263
|
function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
|
|
@@ -1581,14 +1598,13 @@ function readJsonConfig(path) {
|
|
|
1581
1598
|
}
|
|
1582
1599
|
}
|
|
1583
1600
|
async function loadTsConfig(path) {
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
}
|
|
1601
|
+
const { createJiti } = await import("jiti");
|
|
1602
|
+
const mod = await createJiti(import.meta.url, {
|
|
1603
|
+
fsCache: false,
|
|
1604
|
+
moduleCache: false,
|
|
1605
|
+
interopDefault: false
|
|
1606
|
+
}).import(path);
|
|
1607
|
+
return mod.__esModule ? mod.default ?? {} : mod;
|
|
1592
1608
|
}
|
|
1593
1609
|
function isModuleNotFound(error, name) {
|
|
1594
1610
|
return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
|
|
@@ -1613,6 +1629,7 @@ const LOCK_VERSION = 1;
|
|
|
1613
1629
|
const README = "Written by Verbaly: the source text each translation was made for, which ones are drafts, and which languages migrate converted. Commit it with your catalogs and never edit it: deleting it marks every draft as reviewed.";
|
|
1614
1630
|
const LEGACY_STATE_FILE = ".verbaly-state.json";
|
|
1615
1631
|
const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
|
|
1632
|
+
const resolved = /* @__PURE__ */ new Set();
|
|
1616
1633
|
function statePath(cfg) {
|
|
1617
1634
|
return join(cfg.root, STATE_FILE);
|
|
1618
1635
|
}
|
|
@@ -1620,31 +1637,51 @@ function legacyPaths(cfg) {
|
|
|
1620
1637
|
return [join(cfg.dir, LEGACY_STATE_FILE), join(cfg.dir, LEGACY_DRAFTS_FILE)];
|
|
1621
1638
|
}
|
|
1622
1639
|
function loadState(cfg) {
|
|
1623
|
-
const lock =
|
|
1624
|
-
|
|
1625
|
-
const [legacyState, legacyDrafts] = legacyPaths(cfg).map(
|
|
1640
|
+
const lock = readSides(statePath(cfg)) ?? [];
|
|
1641
|
+
for (const side of lock) checkVersion(statePath(cfg), side.version);
|
|
1642
|
+
const [legacyState = [], legacyDrafts = []] = legacyPaths(cfg).map((path) => readSides(path) ?? []);
|
|
1626
1643
|
const state = {
|
|
1627
1644
|
drafts: {},
|
|
1628
1645
|
fingerprints: {}
|
|
1629
1646
|
};
|
|
1630
|
-
|
|
1631
|
-
|
|
1647
|
+
const kept = lock.length > 1 ? keptStamp(cfg) : void 0;
|
|
1648
|
+
[...lock, ...legacyState].forEach((source, index) => {
|
|
1632
1649
|
for (const [locale, keys] of Object.entries(readDrafts(source.drafts))) markDrafts(state.drafts, locale, keys);
|
|
1633
1650
|
for (const [locale, stamps] of Object.entries(readFingerprints(source.fingerprints))) {
|
|
1634
1651
|
const into = state.fingerprints[locale] ??= emptyCatalog();
|
|
1635
|
-
for (const [key, stamped] of Object.entries(stamps))
|
|
1652
|
+
for (const [key, stamped] of Object.entries(stamps)) {
|
|
1653
|
+
const held = own(into, key);
|
|
1654
|
+
if (held === void 0) into[key] = stamped;
|
|
1655
|
+
else if (index < lock.length && held !== stamped && kept?.(locale, key, stamped)) into[key] = stamped;
|
|
1656
|
+
}
|
|
1636
1657
|
}
|
|
1637
1658
|
const migrated = readMigrated(source.migrated);
|
|
1638
1659
|
if (migrated) state.migrated = [.../* @__PURE__ */ new Set([...state.migrated ?? [], ...migrated])];
|
|
1639
|
-
}
|
|
1640
|
-
|
|
1660
|
+
});
|
|
1661
|
+
for (const side of legacyDrafts) for (const [locale, keys] of Object.entries(readDrafts(side))) markDrafts(state.drafts, locale, keys);
|
|
1641
1662
|
return state;
|
|
1642
1663
|
}
|
|
1664
|
+
function keptStamp(cfg) {
|
|
1665
|
+
const read = /* @__PURE__ */ new Map();
|
|
1666
|
+
return (locale, key, stamped) => {
|
|
1667
|
+
if (!read.has(locale)) try {
|
|
1668
|
+
read.set(locale, readCatalog(cfg, locale));
|
|
1669
|
+
} catch {
|
|
1670
|
+
read.set(locale, void 0);
|
|
1671
|
+
}
|
|
1672
|
+
const translated = own(read.get(locale) ?? {}, key);
|
|
1673
|
+
return translated !== void 0 && translationOf(stamped) === fingerprint(translated);
|
|
1674
|
+
};
|
|
1675
|
+
}
|
|
1643
1676
|
function stateFile(cfg) {
|
|
1644
1677
|
return [statePath(cfg), ...legacyPaths(cfg)].find((path) => existsSync(path));
|
|
1645
1678
|
}
|
|
1646
1679
|
function lockNews(cfg, before) {
|
|
1647
1680
|
const lock = statePath(cfg);
|
|
1681
|
+
if (resolved.delete(lock)) return {
|
|
1682
|
+
file: lock,
|
|
1683
|
+
merged: true
|
|
1684
|
+
};
|
|
1648
1685
|
if (before === lock || !existsSync(lock)) return void 0;
|
|
1649
1686
|
return before ? {
|
|
1650
1687
|
file: lock,
|
|
@@ -1655,15 +1692,20 @@ function checkVersion(path, version) {
|
|
|
1655
1692
|
if (typeof version === "number" && version > LOCK_VERSION) throw new Error(`[verbaly] ${path} was written by a newer Verbaly (format ${version}): update @verbaly/compiler to read it`);
|
|
1656
1693
|
}
|
|
1657
1694
|
function readState(cfg) {
|
|
1695
|
+
const marked = (readText(statePath(cfg))?.split(/\r?\n/) ?? []).some((line) => CONFLICT.start.test(line)) ? { conflict: true } : {};
|
|
1658
1696
|
try {
|
|
1659
|
-
return {
|
|
1697
|
+
return {
|
|
1698
|
+
state: loadState(cfg),
|
|
1699
|
+
...marked
|
|
1700
|
+
};
|
|
1660
1701
|
} catch (error) {
|
|
1661
1702
|
return {
|
|
1662
1703
|
state: {
|
|
1663
1704
|
drafts: {},
|
|
1664
1705
|
fingerprints: {}
|
|
1665
1706
|
},
|
|
1666
|
-
problem: error.message.replace(/^\[verbaly\] /, "")
|
|
1707
|
+
problem: error.message.replace(/^\[verbaly\] /, ""),
|
|
1708
|
+
...marked
|
|
1667
1709
|
};
|
|
1668
1710
|
}
|
|
1669
1711
|
}
|
|
@@ -1678,7 +1720,10 @@ function saveState(cfg, state) {
|
|
|
1678
1720
|
const existing = readText(path);
|
|
1679
1721
|
if (existing === void 0) mkdirSync(cfg.root, { recursive: true });
|
|
1680
1722
|
const serialized = withLineEndings(fresh, existing ?? legacy.map(readText).find((text) => text !== void 0));
|
|
1681
|
-
if (existing !== serialized)
|
|
1723
|
+
if (existing !== serialized) {
|
|
1724
|
+
if (existing !== void 0 && conflictSides(existing)) resolved.add(path);
|
|
1725
|
+
writeFileSync(path, serialized);
|
|
1726
|
+
}
|
|
1682
1727
|
for (const file of legacy) rmSync(file, { force: true });
|
|
1683
1728
|
}
|
|
1684
1729
|
function readText(path) {
|
|
@@ -1844,20 +1889,47 @@ function serializeState(state) {
|
|
|
1844
1889
|
if (migrated.length) out.migrated = migrated;
|
|
1845
1890
|
return JSON.stringify(out, null, 2) + "\n";
|
|
1846
1891
|
}
|
|
1847
|
-
function
|
|
1892
|
+
function readSides(path) {
|
|
1848
1893
|
const content = readText(path);
|
|
1849
1894
|
if (content === void 0) return void 0;
|
|
1895
|
+
const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
|
|
1896
|
+
const sides = conflictSides(body);
|
|
1897
|
+
return (sides ?? [body]).map((text) => parseObject(path, text, sides !== void 0));
|
|
1898
|
+
}
|
|
1899
|
+
function parseObject(path, text, conflicted) {
|
|
1850
1900
|
let value;
|
|
1851
1901
|
try {
|
|
1852
|
-
value = JSON.parse(
|
|
1902
|
+
value = JSON.parse(text);
|
|
1853
1903
|
} catch (error) {
|
|
1854
|
-
throw corrupt(path, error);
|
|
1904
|
+
throw corrupt(path, conflicted, error);
|
|
1855
1905
|
}
|
|
1856
|
-
if (!isObject(value)) throw corrupt(path);
|
|
1906
|
+
if (!isObject(value)) throw corrupt(path, conflicted);
|
|
1857
1907
|
return value;
|
|
1858
1908
|
}
|
|
1859
|
-
|
|
1860
|
-
|
|
1909
|
+
const CONFLICT = {
|
|
1910
|
+
start: /^<{7}(?: |$)/,
|
|
1911
|
+
base: /^\|{7}(?: |$)/,
|
|
1912
|
+
split: /^={7}$/,
|
|
1913
|
+
end: /^>{7}(?: |$)/
|
|
1914
|
+
};
|
|
1915
|
+
function conflictSides(text) {
|
|
1916
|
+
const lines = text.split(/\r?\n/);
|
|
1917
|
+
if (!lines.some((line) => CONFLICT.start.test(line))) return void 0;
|
|
1918
|
+
const ours = [];
|
|
1919
|
+
const theirs = [];
|
|
1920
|
+
let at = "both";
|
|
1921
|
+
for (const line of lines) if (at === "both" && CONFLICT.start.test(line)) at = "ours";
|
|
1922
|
+
else if (at === "ours" && CONFLICT.base.test(line)) at = "base";
|
|
1923
|
+
else if ((at === "ours" || at === "base") && CONFLICT.split.test(line)) at = "theirs";
|
|
1924
|
+
else if (at === "theirs" && CONFLICT.end.test(line)) at = "both";
|
|
1925
|
+
else if (at !== "base") {
|
|
1926
|
+
if (at !== "theirs") ours.push(line);
|
|
1927
|
+
if (at !== "ours") theirs.push(line);
|
|
1928
|
+
}
|
|
1929
|
+
return at === "both" ? [ours.join("\n"), theirs.join("\n")] : void 0;
|
|
1930
|
+
}
|
|
1931
|
+
function corrupt(path, conflicted, cause) {
|
|
1932
|
+
return new Error(conflicted ? `[verbaly] ${path} has a merge conflict Verbaly cannot read: resolve it by hand and keep the entries of both sides (dropping a side, or the file, approves its drafts)` : `[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`, { cause });
|
|
1861
1933
|
}
|
|
1862
1934
|
function isObject(value) {
|
|
1863
1935
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -2948,8 +3020,9 @@ async function doctor(cfg) {
|
|
|
2948
3020
|
for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
|
|
2949
3021
|
if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
|
|
2950
3022
|
}
|
|
2951
|
-
const { state, problem } = readState(cfg);
|
|
2952
|
-
if (problem) warn("state", problem, `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`);
|
|
3023
|
+
const { state, problem, conflict } = readState(cfg);
|
|
3024
|
+
if (problem) warn("state", problem, conflict ? "resolve it by hand, keeping the entries of both sides: taking one side approves the drafts of the other" : `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`);
|
|
3025
|
+
else if (conflict) warn("state", `${STATE_FILE} has a merge conflict, and both sides were read`, "run `npx verbaly extract`, which writes both sides into it, then commit it");
|
|
2953
3026
|
if (catalogsHealthy) {
|
|
2954
3027
|
const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {
|
|
2955
3028
|
const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);
|
|
@@ -3001,6 +3074,7 @@ function preview(keys) {
|
|
|
3001
3074
|
//#endregion
|
|
3002
3075
|
//#region src/inline.ts
|
|
3003
3076
|
const OPEN_TAG = /^<([a-zA-Z][a-zA-Z0-9-]*)\s*(\/?)>/;
|
|
3077
|
+
const BREAK = /^(?:br|wbr)$/;
|
|
3004
3078
|
function messageToInline(text) {
|
|
3005
3079
|
return renderParts(parseParts(text, 0).parts, /* @__PURE__ */ new Map());
|
|
3006
3080
|
}
|
|
@@ -3106,7 +3180,7 @@ function parseParts(text, pos, closeTag) {
|
|
|
3106
3180
|
const open = OPEN_TAG.exec(text.slice(i));
|
|
3107
3181
|
if (open) {
|
|
3108
3182
|
const [openSrc, name, selfClose] = open;
|
|
3109
|
-
if (selfClose) {
|
|
3183
|
+
if (selfClose || BREAK.test(name)) {
|
|
3110
3184
|
flush();
|
|
3111
3185
|
parts.push({
|
|
3112
3186
|
kind: "ph",
|