@verbaly/compiler 0.71.0 → 0.73.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 +21 -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 +182 -40
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.js +185 -36
- 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 +7 -11
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
|
|
|
@@ -122,6 +122,8 @@ t(titles[slug]);
|
|
|
122
122
|
|
|
123
123
|
**A translation knows which source text it was written for.** For readable keys, the second and third rows, Verbaly keeps a short fingerprint of the source text and of the translation in `verbaly.lock`, next to your config. It is taken the moment the translation is written, by `translate`, `import`, Studio or an agent, so a source that changes right after is still caught; `import` takes it from the source text the translator's file carries, so a file made for an older text reads as outdated at once. When the source text changes and the translation does not, the translation is **outdated**: `status`, `check` and `doctor` say so, `review` lists it with both texts, and `review --approve` keeps it if it still holds. Editing the translation clears it on its own. Hash keys never need this, because a new text is a new key.
|
|
124
124
|
|
|
125
|
+
**Plurals, selects and formats go in the template, with the value in `${…}`.** `` t`You have {${count} | one: # message | other: # messages}` `` and `` t`Total: {${total}:currency/EUR}` `` extract as the same blocks a catalog holds, and the call becomes `t('<key>', { count })`. Inside a block the catalog syntax holds: `#` is the number, and `||`, `##` and `{{` are escapes. A block written around a bare name (`{count | …}`), one that never closes, and ICU written in the template stay text, and `extract` shows how to write each.
|
|
126
|
+
|
|
125
127
|
Four details that catch people out:
|
|
126
128
|
|
|
127
129
|
- **Keep the files that write `t` inside `include`.** The default reads `src/` and `app/`. A file outside them, like `components/` in a Next app without `src/`, is never extracted, so its text shows in the source language in every language. `@verbaly/next`, the Vite plugin and unplugin say so once when they start, with the pattern to add, and `doctor` lists every such file.
|
|
@@ -158,7 +160,7 @@ In CI, write the types before you check them, since a fresh clone has none: `npx
|
|
|
158
160
|
|
|
159
161
|
## 🚚 Coming from i18next
|
|
160
162
|
|
|
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.
|
|
163
|
+
`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
164
|
|
|
163
165
|
While i18next still serves some screens, give it `interpolation: { prefix: '{', suffix: '}' }` and both libraries read the converted files.
|
|
164
166
|
|
|
@@ -183,7 +185,7 @@ export default {
|
|
|
183
185
|
|
|
184
186
|
Only the terms a batch actually contains are sent, so a glossary of hundreds never becomes the prompt.
|
|
185
187
|
|
|
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.
|
|
188
|
+
**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
189
|
|
|
188
190
|
Plug your own provider in `verbaly.config.ts`. In TypeScript, `TranslateProvider` types it for you:
|
|
189
191
|
|
|
@@ -349,21 +351,21 @@ The package exports two layers, and **nothing else is public**. Anything you can
|
|
|
349
351
|
|
|
350
352
|
**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
353
|
|
|
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`
|
|
354
|
+
| Area | Exports |
|
|
355
|
+
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
356
|
+
| Setup | `init` · types `Host` `InitOptions` `InitResult` |
|
|
357
|
+
| Config & catalogs | `loadConfig` `resolveConfig` `targetLocales` `loadCatalogs` `readCatalog` `parseCatalog` `writeCatalog` `clientCatalogs` `needsIcu` `needsRelative` · types `Catalog` `Catalogs` |
|
|
358
|
+
| Extraction | `syncProject` `extractProject` `collectOrigins` `syncCatalogs` `shippedCatalogs` `pruneCatalogs` `MessageRegistry` `stableKey` `watchTree` · types `SyncProjectResult` `SyncResult` `TreeOptions` |
|
|
359
|
+
| Codegen | `generateDts` `writeDts` `generateRuntimeModule` `generateLocaleModule` · types `DtsOptions` `RuntimeModuleOptions` |
|
|
360
|
+
| Bundler plumbing | `transformSource` `transformCode` `runBuildGate` `createSourceFilter` `reportOutsideInclude` `isTransformTarget` `resolveVirtualId` `loadVirtualModule` `RESOLVED_VIRTUAL_ID` `LOCALE_MODULE_PREFIX` `SOURCE_FILE_RE` · types `PluginOptions` `TransformResult` |
|
|
359
361
|
| 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`
|
|
362
|
+
| Coverage | `status` `formatStatusResult` `counted` · types `StatusResult` `LocaleStatus` |
|
|
363
|
+
| Review state | `loadDrafts` `saveDrafts` `markDrafts` `clearDrafts` `effectiveDrafts` `loadState` `readState` `updateState` `recordTranslations` `outdatedTranslations` `STATE_FILE` · types `Drafts` `State` `Fingerprints` `TranslationWrite` |
|
|
364
|
+
| Translation | `translateCatalogs` `mergeTranslations` `writeDrafts` `resolveProvider` `formatTranslateFailures` · types `DraftEntry` `WriteDraftsResult` |
|
|
365
|
+
| Diagnosis | `doctor` `formatDoctorEntry` `formatDoctorHealth` · types `DoctorResult` `DoctorEntry` |
|
|
366
|
+
| Onboarding | `wrapProject` · types `WrapResult` `WrapEntry` `WrapSkip` `WrapBlocked` `WrapOptions` |
|
|
367
|
+
| Static rendering | `renderSite` `formatRenderWarnings` · types `RenderSiteOptions` `RenderSiteResult` |
|
|
368
|
+
| Error output | `formatCliError` |
|
|
367
369
|
|
|
368
370
|
A minimal plugin is `loadConfig` + `loadCatalogs` once, then `transformSource` per file and `runBuildGate` at the end:
|
|
369
371
|
|
|
@@ -383,11 +385,11 @@ const registry = new MessageRegistry();
|
|
|
383
385
|
// per file: rewrites t`…` to a keyed call and hands you the messages it found
|
|
384
386
|
const { messages, result } = transformSource(code, id, registry);
|
|
385
387
|
|
|
386
|
-
// at the end of the build:
|
|
388
|
+
// at the end of the build: lists what is missing or broken, and throws only with failOnMissing
|
|
387
389
|
runBuildGate(cfg, registry);
|
|
388
390
|
```
|
|
389
391
|
|
|
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.
|
|
392
|
+
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
393
|
|
|
392
394
|
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
395
|
|
|
@@ -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
|
@@ -643,13 +643,19 @@ function isTReference(node, names) {
|
|
|
643
643
|
}
|
|
644
644
|
return false;
|
|
645
645
|
}
|
|
646
|
+
const BLOCK_TAIL = /^(?:\s*\|\s*[^\s|{}:]+\s*:|:[A-Za-z_][\w-]*)/;
|
|
646
647
|
function buildMessage(code, quasi, names) {
|
|
647
648
|
const quasis = quasi.quasis;
|
|
648
649
|
const expressions = quasi.expressions;
|
|
650
|
+
const texts = quasis.map(cookedValue);
|
|
649
651
|
const params = [];
|
|
650
652
|
const taken = /* @__PURE__ */ new Map();
|
|
651
|
-
|
|
652
|
-
for (let i = 0; i <
|
|
653
|
+
const tokens = [];
|
|
654
|
+
for (let i = 0; i < texts.length; i++) {
|
|
655
|
+
const chunk = texts[i];
|
|
656
|
+
const head = i < expressions.length && chunk.endsWith("{") && BLOCK_TAIL.test(texts[i + 1]);
|
|
657
|
+
for (const char of head ? chunk.slice(0, -1) : chunk) tokens.push(char);
|
|
658
|
+
if (i === expressions.length) break;
|
|
653
659
|
const expr = expressions[i];
|
|
654
660
|
if (!expr) return void 0;
|
|
655
661
|
if (containsTaggedT(expr, names)) return void 0;
|
|
@@ -660,13 +666,50 @@ function buildMessage(code, quasi, names) {
|
|
|
660
666
|
start: expr.start,
|
|
661
667
|
end: expr.end
|
|
662
668
|
});
|
|
663
|
-
|
|
669
|
+
tokens.push({
|
|
670
|
+
name,
|
|
671
|
+
head
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
let text = "";
|
|
675
|
+
for (let k = 0; k < tokens.length; k++) {
|
|
676
|
+
const token = tokens[k];
|
|
677
|
+
if (typeof token === "string") text += token === "{" || token === "}" ? token + token : token;
|
|
678
|
+
else if (!token.head) text += `{${token.name}}`;
|
|
679
|
+
else {
|
|
680
|
+
const end = blockEnd(tokens, k, false) ?? blockEnd(tokens, k, true);
|
|
681
|
+
if (end === void 0) return {
|
|
682
|
+
text: texts.map((chunk, i) => escapeText(chunk) + (params[i] ? `{${params[i].name}}` : "")).join(""),
|
|
683
|
+
params
|
|
684
|
+
};
|
|
685
|
+
for (let m = k; m <= end; m++) text += tokenText(tokens[m]);
|
|
686
|
+
k = end;
|
|
687
|
+
}
|
|
664
688
|
}
|
|
665
689
|
return {
|
|
666
690
|
text,
|
|
667
691
|
params
|
|
668
692
|
};
|
|
669
693
|
}
|
|
694
|
+
function tokenText(token) {
|
|
695
|
+
if (typeof token === "string") return token;
|
|
696
|
+
return token.head ? `{${token.name}` : `{${token.name}}`;
|
|
697
|
+
}
|
|
698
|
+
function blockEnd(tokens, start, pairs) {
|
|
699
|
+
let depth = 0;
|
|
700
|
+
for (let k = start; k < tokens.length; k++) {
|
|
701
|
+
const token = tokens[k];
|
|
702
|
+
if (typeof token !== "string") {
|
|
703
|
+
if (token.head) depth += 1;
|
|
704
|
+
} else if (token === "{" || token === "}") {
|
|
705
|
+
if (tokens[k + 1] === token && (token === "{" || !(pairs && depth > 1))) k += 1;
|
|
706
|
+
else {
|
|
707
|
+
depth += token === "{" ? 1 : -1;
|
|
708
|
+
if (depth === 0) return k;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|
|
670
713
|
function cookedValue(element) {
|
|
671
714
|
if (!element) return "";
|
|
672
715
|
const value = element.value;
|
|
@@ -899,14 +942,25 @@ function stringEnd(code, start) {
|
|
|
899
942
|
}
|
|
900
943
|
//#endregion
|
|
901
944
|
//#region src/extract.ts
|
|
902
|
-
|
|
945
|
+
const kept = /* @__PURE__ */ new WeakMap();
|
|
946
|
+
async function extractProject(cfg, options = {}) {
|
|
903
947
|
const files = await glob(cfg.include, {
|
|
904
948
|
cwd: cfg.root,
|
|
905
949
|
ignore: cfg.exclude,
|
|
906
950
|
absolute: true
|
|
907
951
|
});
|
|
908
952
|
const registry = new MessageRegistry();
|
|
909
|
-
|
|
953
|
+
const read = options.keepSource ? /* @__PURE__ */ new Map() : null;
|
|
954
|
+
for (const file of files.sort()) {
|
|
955
|
+
const code = readFileSync(file, "utf8");
|
|
956
|
+
const analysis = analyzeFile(code, file);
|
|
957
|
+
registry.update(file, analysis);
|
|
958
|
+
read?.set(file.replaceAll("\\", "/"), {
|
|
959
|
+
code,
|
|
960
|
+
analysis
|
|
961
|
+
});
|
|
962
|
+
}
|
|
963
|
+
if (read) kept.set(registry, read);
|
|
910
964
|
return registry;
|
|
911
965
|
}
|
|
912
966
|
async function collectOrigins(cfg, reuse) {
|
|
@@ -1016,15 +1070,20 @@ function collect(nodes, out) {
|
|
|
1016
1070
|
if (node.variants) for (const [, body] of node.variants) collect(body, out);
|
|
1017
1071
|
}
|
|
1018
1072
|
}
|
|
1019
|
-
const TAG = /<(\/?)([a-zA-Z][\w-]*)(\/?)>/g;
|
|
1073
|
+
const TAG = /<(\/?)([a-zA-Z][\w-]*)\s*(\/?)>/g;
|
|
1074
|
+
const BREAK$1 = /^(?:br|wbr)$/;
|
|
1020
1075
|
function markupNames(message) {
|
|
1021
1076
|
const out = /* @__PURE__ */ new Set();
|
|
1022
|
-
for (const match of message.matchAll(TAG)) if (match[1] || match[3]) out.add(match[2]);
|
|
1077
|
+
for (const match of message.matchAll(TAG)) if (match[1] || match[3] || BREAK$1.test(match[2])) out.add(match[2]);
|
|
1023
1078
|
return out;
|
|
1024
1079
|
}
|
|
1025
1080
|
function tagTokens(message, markup) {
|
|
1026
1081
|
const out = [];
|
|
1027
|
-
for (const
|
|
1082
|
+
for (const [, closing, name, selfClose] of message.matchAll(TAG)) {
|
|
1083
|
+
if (!markup.has(name)) continue;
|
|
1084
|
+
if (!BREAK$1.test(name)) out.push(`${closing}${name}${selfClose}`);
|
|
1085
|
+
else if (!closing) out.push(`${name}/`);
|
|
1086
|
+
}
|
|
1028
1087
|
return out.sort();
|
|
1029
1088
|
}
|
|
1030
1089
|
function surplus(a, b) {
|
|
@@ -1040,10 +1099,35 @@ function surplus(a, b) {
|
|
|
1040
1099
|
function list(items) {
|
|
1041
1100
|
return items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}` : items[0];
|
|
1042
1101
|
}
|
|
1043
|
-
const ESCAPED_SYNTAX = /(?<!\{)\{\{\s*[\w.]
|
|
1102
|
+
const ESCAPED_SYNTAX = /(?<!\{)\{\{\s*([\w.]+)(\s*[|:][^{}]*)\}\}/;
|
|
1103
|
+
const ESCAPED_ICU = /(?<!\{)\{\{\s*([\w.]+)\s*,\s*(plural|selectordinal|select|number|date|time)\b/;
|
|
1104
|
+
const ICU_SLICE = /^\{\{([\w.]+), (\w+), …\}\}$/;
|
|
1105
|
+
const ESCAPED_OPEN = /(?<!\{)\{\{\{([\w.]+)\}(\s*\|\s*[^\s|{}:]+\s*:|:[A-Za-z_][\w-]*)/;
|
|
1044
1106
|
function escapedSyntax(message) {
|
|
1107
|
+
const icu = ESCAPED_ICU.exec(message);
|
|
1108
|
+
if (icu) return `{{${icu[1]}, ${icu[2]}, …}}`;
|
|
1109
|
+
const open = ESCAPED_OPEN.exec(message);
|
|
1110
|
+
if (open) return `{\${${open[1]}}${open[2]}…`;
|
|
1045
1111
|
return ESCAPED_SYNTAX.exec(message)?.[0];
|
|
1046
1112
|
}
|
|
1113
|
+
function shownSlice(slice) {
|
|
1114
|
+
return slice.startsWith("{{") ? slice.slice(1, -1) : slice;
|
|
1115
|
+
}
|
|
1116
|
+
function inlineBlock(slice) {
|
|
1117
|
+
if (slice.startsWith("{${")) return "the same block with its closing }";
|
|
1118
|
+
const icu = ICU_SLICE.exec(slice);
|
|
1119
|
+
if (icu) {
|
|
1120
|
+
const [, name = "", type = ""] = icu;
|
|
1121
|
+
if (type === "plural") return `{\${${name}} | one: … | other: …}`;
|
|
1122
|
+
if (type === "select") return `{\${${name}} | …: … | other: …}`;
|
|
1123
|
+
if (type === "selectordinal") return "t(key, params), with the ICU message in the catalog";
|
|
1124
|
+
return `{\${${name}}:${type}}`;
|
|
1125
|
+
}
|
|
1126
|
+
const match = ESCAPED_SYNTAX.exec(slice);
|
|
1127
|
+
if (!match) return slice;
|
|
1128
|
+
const [, name = "", tail = ""] = match;
|
|
1129
|
+
return `{\${${name}}${tail.trimStart().startsWith(":") ? `:${tail.trimStart().slice(1).trimStart()}` : tail}}`;
|
|
1130
|
+
}
|
|
1047
1131
|
function validateMessage(message, locale) {
|
|
1048
1132
|
const issues = [];
|
|
1049
1133
|
for (const [name, shape] of shapes(message)) {
|
|
@@ -1222,11 +1306,12 @@ function formatFinding(finding, root) {
|
|
|
1222
1306
|
const names = finding.params.map((name) => `{${name}}`).join(", ");
|
|
1223
1307
|
return `${sourcePlace(finding.site, root)}: ${names} in "${truncate(finding.site.message, 60)}" reaches the translator without a name, put the value in a named variable first`;
|
|
1224
1308
|
}
|
|
1225
|
-
case "escaped": return `${sourcePlace(finding.site, root)}: ${finding.slice} renders as literal text
|
|
1309
|
+
case "escaped": return `${sourcePlace(finding.site, root)}: ${shownSlice(finding.slice)} renders as literal text: write ${inlineBlock(finding.slice)}`;
|
|
1226
1310
|
case "unparsed": return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;
|
|
1227
1311
|
case "outdated": return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \`npx verbaly review --approve\``;
|
|
1228
1312
|
case "lock": {
|
|
1229
1313
|
const lock = sourcePlace(finding, root);
|
|
1314
|
+
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
1315
|
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
1316
|
}
|
|
1232
1317
|
}
|
|
@@ -1240,7 +1325,7 @@ function findingId(finding) {
|
|
|
1240
1325
|
case "positional": return `positional:${finding.site.file}:${finding.params.join(",")}`;
|
|
1241
1326
|
case "escaped": return `escaped:${finding.site.file}:${finding.slice}`;
|
|
1242
1327
|
case "unparsed": return `unparsed:${finding.file}`;
|
|
1243
|
-
case "lock": return `lock:${finding.file}`;
|
|
1328
|
+
case "lock": return `lock:${finding.merged ? "merged:" : ""}${finding.file}`;
|
|
1244
1329
|
}
|
|
1245
1330
|
}
|
|
1246
1331
|
function createDevReporter(root, print = (line) => console.warn(`[verbaly] ${line}`), cap = 5) {
|
|
@@ -1581,14 +1666,13 @@ function readJsonConfig(path) {
|
|
|
1581
1666
|
}
|
|
1582
1667
|
}
|
|
1583
1668
|
async function loadTsConfig(path) {
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
}
|
|
1669
|
+
const { createJiti } = await import("jiti");
|
|
1670
|
+
const mod = await createJiti(import.meta.url, {
|
|
1671
|
+
fsCache: false,
|
|
1672
|
+
moduleCache: false,
|
|
1673
|
+
interopDefault: false
|
|
1674
|
+
}).import(path);
|
|
1675
|
+
return mod.__esModule ? mod.default ?? {} : mod;
|
|
1592
1676
|
}
|
|
1593
1677
|
function isModuleNotFound(error, name) {
|
|
1594
1678
|
return error instanceof Error && error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes(name);
|
|
@@ -1613,6 +1697,7 @@ const LOCK_VERSION = 1;
|
|
|
1613
1697
|
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
1698
|
const LEGACY_STATE_FILE = ".verbaly-state.json";
|
|
1615
1699
|
const LEGACY_DRAFTS_FILE = ".verbaly-drafts.json";
|
|
1700
|
+
const resolved = /* @__PURE__ */ new Set();
|
|
1616
1701
|
function statePath(cfg) {
|
|
1617
1702
|
return join(cfg.root, STATE_FILE);
|
|
1618
1703
|
}
|
|
@@ -1620,31 +1705,51 @@ function legacyPaths(cfg) {
|
|
|
1620
1705
|
return [join(cfg.dir, LEGACY_STATE_FILE), join(cfg.dir, LEGACY_DRAFTS_FILE)];
|
|
1621
1706
|
}
|
|
1622
1707
|
function loadState(cfg) {
|
|
1623
|
-
const lock =
|
|
1624
|
-
|
|
1625
|
-
const [legacyState, legacyDrafts] = legacyPaths(cfg).map(
|
|
1708
|
+
const lock = readSides(statePath(cfg)) ?? [];
|
|
1709
|
+
for (const side of lock) checkVersion(statePath(cfg), side.version);
|
|
1710
|
+
const [legacyState = [], legacyDrafts = []] = legacyPaths(cfg).map((path) => readSides(path) ?? []);
|
|
1626
1711
|
const state = {
|
|
1627
1712
|
drafts: {},
|
|
1628
1713
|
fingerprints: {}
|
|
1629
1714
|
};
|
|
1630
|
-
|
|
1631
|
-
|
|
1715
|
+
const kept = lock.length > 1 ? keptStamp(cfg) : void 0;
|
|
1716
|
+
[...lock, ...legacyState].forEach((source, index) => {
|
|
1632
1717
|
for (const [locale, keys] of Object.entries(readDrafts(source.drafts))) markDrafts(state.drafts, locale, keys);
|
|
1633
1718
|
for (const [locale, stamps] of Object.entries(readFingerprints(source.fingerprints))) {
|
|
1634
1719
|
const into = state.fingerprints[locale] ??= emptyCatalog();
|
|
1635
|
-
for (const [key, stamped] of Object.entries(stamps))
|
|
1720
|
+
for (const [key, stamped] of Object.entries(stamps)) {
|
|
1721
|
+
const held = own(into, key);
|
|
1722
|
+
if (held === void 0) into[key] = stamped;
|
|
1723
|
+
else if (index < lock.length && held !== stamped && kept?.(locale, key, stamped)) into[key] = stamped;
|
|
1724
|
+
}
|
|
1636
1725
|
}
|
|
1637
1726
|
const migrated = readMigrated(source.migrated);
|
|
1638
1727
|
if (migrated) state.migrated = [.../* @__PURE__ */ new Set([...state.migrated ?? [], ...migrated])];
|
|
1639
|
-
}
|
|
1640
|
-
|
|
1728
|
+
});
|
|
1729
|
+
for (const side of legacyDrafts) for (const [locale, keys] of Object.entries(readDrafts(side))) markDrafts(state.drafts, locale, keys);
|
|
1641
1730
|
return state;
|
|
1642
1731
|
}
|
|
1732
|
+
function keptStamp(cfg) {
|
|
1733
|
+
const read = /* @__PURE__ */ new Map();
|
|
1734
|
+
return (locale, key, stamped) => {
|
|
1735
|
+
if (!read.has(locale)) try {
|
|
1736
|
+
read.set(locale, readCatalog(cfg, locale));
|
|
1737
|
+
} catch {
|
|
1738
|
+
read.set(locale, void 0);
|
|
1739
|
+
}
|
|
1740
|
+
const translated = own(read.get(locale) ?? {}, key);
|
|
1741
|
+
return translated !== void 0 && translationOf(stamped) === fingerprint(translated);
|
|
1742
|
+
};
|
|
1743
|
+
}
|
|
1643
1744
|
function stateFile(cfg) {
|
|
1644
1745
|
return [statePath(cfg), ...legacyPaths(cfg)].find((path) => existsSync(path));
|
|
1645
1746
|
}
|
|
1646
1747
|
function lockNews(cfg, before) {
|
|
1647
1748
|
const lock = statePath(cfg);
|
|
1749
|
+
if (resolved.delete(lock)) return {
|
|
1750
|
+
file: lock,
|
|
1751
|
+
merged: true
|
|
1752
|
+
};
|
|
1648
1753
|
if (before === lock || !existsSync(lock)) return void 0;
|
|
1649
1754
|
return before ? {
|
|
1650
1755
|
file: lock,
|
|
@@ -1655,15 +1760,20 @@ function checkVersion(path, version) {
|
|
|
1655
1760
|
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
1761
|
}
|
|
1657
1762
|
function readState(cfg) {
|
|
1763
|
+
const marked = (readText(statePath(cfg))?.split(/\r?\n/) ?? []).some((line) => CONFLICT.start.test(line)) ? { conflict: true } : {};
|
|
1658
1764
|
try {
|
|
1659
|
-
return {
|
|
1765
|
+
return {
|
|
1766
|
+
state: loadState(cfg),
|
|
1767
|
+
...marked
|
|
1768
|
+
};
|
|
1660
1769
|
} catch (error) {
|
|
1661
1770
|
return {
|
|
1662
1771
|
state: {
|
|
1663
1772
|
drafts: {},
|
|
1664
1773
|
fingerprints: {}
|
|
1665
1774
|
},
|
|
1666
|
-
problem: error.message.replace(/^\[verbaly\] /, "")
|
|
1775
|
+
problem: error.message.replace(/^\[verbaly\] /, ""),
|
|
1776
|
+
...marked
|
|
1667
1777
|
};
|
|
1668
1778
|
}
|
|
1669
1779
|
}
|
|
@@ -1678,7 +1788,10 @@ function saveState(cfg, state) {
|
|
|
1678
1788
|
const existing = readText(path);
|
|
1679
1789
|
if (existing === void 0) mkdirSync(cfg.root, { recursive: true });
|
|
1680
1790
|
const serialized = withLineEndings(fresh, existing ?? legacy.map(readText).find((text) => text !== void 0));
|
|
1681
|
-
if (existing !== serialized)
|
|
1791
|
+
if (existing !== serialized) {
|
|
1792
|
+
if (existing !== void 0 && conflictSides(existing)) resolved.add(path);
|
|
1793
|
+
writeFileSync(path, serialized);
|
|
1794
|
+
}
|
|
1682
1795
|
for (const file of legacy) rmSync(file, { force: true });
|
|
1683
1796
|
}
|
|
1684
1797
|
function readText(path) {
|
|
@@ -1844,20 +1957,47 @@ function serializeState(state) {
|
|
|
1844
1957
|
if (migrated.length) out.migrated = migrated;
|
|
1845
1958
|
return JSON.stringify(out, null, 2) + "\n";
|
|
1846
1959
|
}
|
|
1847
|
-
function
|
|
1960
|
+
function readSides(path) {
|
|
1848
1961
|
const content = readText(path);
|
|
1849
1962
|
if (content === void 0) return void 0;
|
|
1963
|
+
const body = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
|
|
1964
|
+
const sides = conflictSides(body);
|
|
1965
|
+
return (sides ?? [body]).map((text) => parseObject(path, text, sides !== void 0));
|
|
1966
|
+
}
|
|
1967
|
+
function parseObject(path, text, conflicted) {
|
|
1850
1968
|
let value;
|
|
1851
1969
|
try {
|
|
1852
|
-
value = JSON.parse(
|
|
1970
|
+
value = JSON.parse(text);
|
|
1853
1971
|
} catch (error) {
|
|
1854
|
-
throw corrupt(path, error);
|
|
1972
|
+
throw corrupt(path, conflicted, error);
|
|
1855
1973
|
}
|
|
1856
|
-
if (!isObject(value)) throw corrupt(path);
|
|
1974
|
+
if (!isObject(value)) throw corrupt(path, conflicted);
|
|
1857
1975
|
return value;
|
|
1858
1976
|
}
|
|
1859
|
-
|
|
1860
|
-
|
|
1977
|
+
const CONFLICT = {
|
|
1978
|
+
start: /^<{7}(?: |$)/,
|
|
1979
|
+
base: /^\|{7}(?: |$)/,
|
|
1980
|
+
split: /^={7}$/,
|
|
1981
|
+
end: /^>{7}(?: |$)/
|
|
1982
|
+
};
|
|
1983
|
+
function conflictSides(text) {
|
|
1984
|
+
const lines = text.split(/\r?\n/);
|
|
1985
|
+
if (!lines.some((line) => CONFLICT.start.test(line))) return void 0;
|
|
1986
|
+
const ours = [];
|
|
1987
|
+
const theirs = [];
|
|
1988
|
+
let at = "both";
|
|
1989
|
+
for (const line of lines) if (at === "both" && CONFLICT.start.test(line)) at = "ours";
|
|
1990
|
+
else if (at === "ours" && CONFLICT.base.test(line)) at = "base";
|
|
1991
|
+
else if ((at === "ours" || at === "base") && CONFLICT.split.test(line)) at = "theirs";
|
|
1992
|
+
else if (at === "theirs" && CONFLICT.end.test(line)) at = "both";
|
|
1993
|
+
else if (at !== "base") {
|
|
1994
|
+
if (at !== "theirs") ours.push(line);
|
|
1995
|
+
if (at !== "ours") theirs.push(line);
|
|
1996
|
+
}
|
|
1997
|
+
return at === "both" ? [ours.join("\n"), theirs.join("\n")] : void 0;
|
|
1998
|
+
}
|
|
1999
|
+
function corrupt(path, conflicted, cause) {
|
|
2000
|
+
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
2001
|
}
|
|
1862
2002
|
function isObject(value) {
|
|
1863
2003
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -2932,7 +3072,7 @@ async function doctor(cfg) {
|
|
|
2932
3072
|
file: rel(msg.file),
|
|
2933
3073
|
slice: escapedSyntax(msg.message)
|
|
2934
3074
|
})).filter((entry) => entry.slice !== void 0);
|
|
2935
|
-
if (escaped.length > 0) warn("messages", `a block ships as literal text in ${counted(escaped.length, "extracted message")} (${escaped[0].file}: ${escaped[0].slice})`,
|
|
3075
|
+
if (escaped.length > 0) warn("messages", `a block ships as literal text in ${counted(escaped.length, "extracted message")} (${escaped[0].file}: ${shownSlice(escaped[0].slice)})`, `in a tagged template, write ${inlineBlock(escaped[0].slice)}`);
|
|
2936
3076
|
}
|
|
2937
3077
|
if (source && scanning) {
|
|
2938
3078
|
const extracted = registry.messages();
|
|
@@ -2948,8 +3088,9 @@ async function doctor(cfg) {
|
|
|
2948
3088
|
for (const issue of issues) warn("bundle", formatBundleIssue(issue), issue.fix);
|
|
2949
3089
|
if (issues.length === 0) ok("bundle", `${counted(excluded.length, "group")} kept out of the client (${preview(excluded)})`);
|
|
2950
3090
|
}
|
|
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`);
|
|
3091
|
+
const { state, problem, conflict } = readState(cfg);
|
|
3092
|
+
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`);
|
|
3093
|
+
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
3094
|
if (catalogsHealthy) {
|
|
2954
3095
|
const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {
|
|
2955
3096
|
const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);
|
|
@@ -3001,6 +3142,7 @@ function preview(keys) {
|
|
|
3001
3142
|
//#endregion
|
|
3002
3143
|
//#region src/inline.ts
|
|
3003
3144
|
const OPEN_TAG = /^<([a-zA-Z][a-zA-Z0-9-]*)\s*(\/?)>/;
|
|
3145
|
+
const BREAK = /^(?:br|wbr)$/;
|
|
3004
3146
|
function messageToInline(text) {
|
|
3005
3147
|
return renderParts(parseParts(text, 0).parts, /* @__PURE__ */ new Map());
|
|
3006
3148
|
}
|
|
@@ -3106,7 +3248,7 @@ function parseParts(text, pos, closeTag) {
|
|
|
3106
3248
|
const open = OPEN_TAG.exec(text.slice(i));
|
|
3107
3249
|
if (open) {
|
|
3108
3250
|
const [openSrc, name, selfClose] = open;
|
|
3109
|
-
if (selfClose) {
|
|
3251
|
+
if (selfClose || BREAK.test(name)) {
|
|
3110
3252
|
flush();
|
|
3111
3253
|
parts.push({
|
|
3112
3254
|
kind: "ph",
|