@verbaly/compiler 0.69.0 → 0.69.1
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 +3 -2
- package/dist/cli.js +16 -5
- package/dist/cli.js.map +1 -1
- package/dist/index.js +16 -5
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["parse","walk","parse","parse"],"sources":["../src/eol.ts","../src/catalog.ts","../src/bundle.ts","../src/registry.ts","../src/key.ts","../src/analyze.ts","../src/sfc.ts","../src/extract.ts","../src/validate.ts","../src/params.ts","../src/tsconfig.ts","../src/warn.ts","../src/codegen.ts","../src/findings.ts","../src/state.ts","../src/project.ts","../src/tag.ts","../src/init.ts","../src/check.ts","../src/transform.ts","../src/plugin.ts","../src/scope.ts","../src/drafts.ts","../src/status.ts","../src/doctor.ts","../src/translate.ts","../src/render.ts","../src/watch.ts","../src/wrap.ts","../src/run.ts"],"sourcesContent":["// a file checked out with CRLF stays CRLF: rewriting every line is a diff nobody made\nexport function withLineEndings(text: string, existing: string | undefined): string {\n const first = existing?.indexOf('\\n') ?? -1;\n return first > 0 && existing![first - 1] === '\\r' ? text.replace(/\\r?\\n/g, '\\r\\n') : text;\n}\n","import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { flatten, type MessageTree } from 'verbaly';\nimport type { ResolvedConfig } from './config';\nimport { withLineEndings } from './eol';\n\nexport type Catalog = Record<string, string>;\nexport type Catalogs = Record<string, Catalog>;\n\n// no prototype: a key is data, so toString or __proto__ must never answer from Object\nexport function emptyCatalog(): Catalog {\n return Object.create(null) as Catalog;\n}\n\n// a catalog handed in by a caller may be a plain object, and its prototype is not a message\nexport function own(catalog: Catalog, key: string): string | undefined {\n return Object.hasOwn(catalog, key) ? catalog[key] : undefined;\n}\n\nexport function catalogPath(cfg: ResolvedConfig, locale: string): string {\n return join(cfg.dir, `${locale}.json`);\n}\n\n// the flat view is the shape t() sees, so every command reads a catalog the way the runtime does\nexport function readCatalog(cfg: ResolvedConfig, locale: string): Catalog {\n const tree = readTree(cfg, locale);\n const bad = badLeaf(tree);\n // the runtime skips this leaf with a warn; a build tool that skipped it would write the skip back\n if (bad) {\n throw new Error(\n `[verbaly] ${catalogPath(cfg, locale)} has a non-string value at \"${bad}\", ` +\n 'catalog values are text (groups of text are fine): fix the value',\n );\n }\n return flatten(tree);\n}\n\n// dotted path of the first value that is neither text nor a group of text (an array is a bad leaf)\nexport function badLeaf(tree: MessageTree, prefix = ''): string | undefined {\n for (const [key, value] of Object.entries(tree)) {\n const path = prefix ? `${prefix}.${key}` : key;\n if (typeof value === 'string') continue;\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return path;\n const bad = badLeaf(value, path);\n if (bad) return bad;\n }\n return undefined;\n}\n\n// corrupt catalog throws: read as empty, the next extract would wipe the translations\nfunction readTree(cfg: ResolvedConfig, locale: string): MessageTree {\n let content: string;\n try {\n content = readFileSync(catalogPath(cfg, locale), 'utf8');\n } catch {\n return {};\n }\n const parsed = parseTree(content);\n if (parsed === undefined) {\n throw new Error(\n `[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`,\n );\n }\n // an array or a bare string reads as no messages, and the next extract would write over it\n if (!isTree(parsed)) {\n throw new Error(\n `[verbaly] ${catalogPath(cfg, locale)} is not a JSON object of messages, fix or delete the file`,\n );\n }\n return parsed;\n}\n\n// the flat view of a catalog that is not on disk: an old revision read out of git is text\nexport function parseCatalog(content: string): Catalog | undefined {\n const tree = parseTree(content);\n return tree === undefined ? undefined : flatten(tree as MessageTree);\n}\n\n// a byte order mark is legal in the file and illegal to JSON.parse: drop it by code, never by regex\nexport function parseTree(content: string): unknown {\n const body = content.charCodeAt(0) === 0xfeff ? content.slice(1) : content;\n try {\n return JSON.parse(body) as unknown;\n } catch {\n return undefined;\n }\n}\n\nexport function isTree(value: unknown): value is MessageTree {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function loadCatalogs(cfg: ResolvedConfig): Catalogs {\n const catalogs: Catalogs = {};\n for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);\n return catalogs;\n}\n\n// the nesting is the author's: a file written as groups is handed back as groups\nfunction isNested(tree: MessageTree): boolean {\n return Object.values(tree).some((value) => typeof value === 'object' && value !== null);\n}\n\n// null prototype: a group named __proto__ is data here, and on a plain object it writes to Object\nfunction group(): MessageTree {\n return Object.create(null) as MessageTree;\n}\n\n// dotted key back to its group; a path already taken by text stays flat so nothing is overwritten\nfunction nest(catalog: Catalog): MessageTree {\n const tree = group();\n // sorted, so \"hero\" always lands before \"hero.title\" and a message is never replaced by its group\n for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => (a < b ? -1 : 1))) {\n const parts = key.split('.');\n const leaf = parts[parts.length - 1]!;\n let node: MessageTree | undefined = parts.length > 1 ? tree : undefined;\n for (let i = 0; node && i < parts.length - 1; i++) {\n const next = (node[parts[i]!] ??= group());\n node = typeof next === 'object' && next !== null ? (next as MessageTree) : undefined;\n }\n if (node && typeof node[leaf] !== 'object') node[leaf] = message;\n else tree[key] = message;\n }\n return tree;\n}\n\nfunction sortTree(tree: MessageTree): MessageTree {\n const sorted = group();\n for (const key of Object.keys(tree).sort()) {\n const value = tree[key];\n if (typeof value === 'string') sorted[key] = value;\n else if (value !== undefined) sorted[key] = sortTree(value as MessageTree);\n }\n return sorted;\n}\n\nfunction isSorted(keys: string[]): boolean {\n for (let i = 1; i < keys.length; i++) if (keys[i - 1]! > keys[i]!) return false;\n return true;\n}\n\n// a level a person ordered keeps that order; one that was already sorted keeps being sorted\nfunction orderLike(tree: MessageTree, previous: MessageTree): MessageTree {\n const had = Object.keys(previous);\n if (isSorted(had)) return sortTree(tree);\n\n const out = group();\n const take = (key: string): void => {\n const value = tree[key];\n if (typeof value === 'string') {\n out[key] = value;\n return;\n }\n if (value === undefined) return;\n const before = previous[key];\n out[key] =\n typeof before === 'object' && before !== null\n ? orderLike(value, before)\n : sortTree(value);\n };\n\n for (const key of had) if (Object.hasOwn(tree, key)) take(key);\n // a key the file did not have is an addition, and it reads as one at the end of its group\n for (const key of Object.keys(tree).sort()) if (!Object.hasOwn(previous, key)) take(key);\n return out;\n}\n\nexport function serializeCatalog(\n catalog: Catalog,\n nested = false,\n previous?: MessageTree,\n): string {\n const tree: MessageTree = nested ? nest(catalog) : catalog;\n return JSON.stringify(previous ? orderLike(tree, previous) : sortTree(tree), null, 2) + '\\n';\n}\n\nexport function writeCatalog(cfg: ResolvedConfig, locale: string, catalog: Catalog): string {\n const path = catalogPath(cfg, locale);\n let existing: string | undefined;\n try {\n existing = readFileSync(path, 'utf8');\n } catch {\n mkdirSync(cfg.dir, { recursive: true });\n }\n // parsed once: the shape and the key order are two questions about the same previous file\n const parsed = existing === undefined ? undefined : parseTree(existing);\n const previous = isTree(parsed) ? parsed : undefined;\n const serialized = withLineEndings(\n serializeCatalog(catalog, wantsNesting(cfg, locale, existing, previous), previous),\n existing,\n );\n // identical writes are skipped: a rewrite retriggers whatever watches the catalog\n if (existing === serialized) return serialized;\n writeFileSync(path, serialized);\n return serialized;\n}\n\n// the file's own shape, and for a locale that does not exist yet, the source catalog's\nfunction wantsNesting(\n cfg: ResolvedConfig,\n locale: string,\n existing: string | undefined,\n previous: MessageTree | undefined,\n): boolean {\n if (existing !== undefined) return previous !== undefined && isNested(previous);\n if (locale === cfg.sourceLocale) return false;\n return isNested(readTree(cfg, cfg.sourceLocale));\n}\n\n// the same test the runtime uses, asked of the catalogs so the parser ships only where it is read\nconst ICU_ARG = /\\{\\s*[a-zA-Z0-9_]+\\s*,\\s*(?:plural|selectordinal|select|number|date|time)\\b/;\n\nexport function needsIcu(catalogs: Catalogs): boolean {\n for (const catalog of Object.values(catalogs)) {\n for (const message of Object.values(flatten(catalog as MessageTree))) {\n if (ICU_ARG.test(message)) return true;\n }\n }\n return false;\n}\n\n// relative time is the one format heavy enough to be worth shipping only where it is written\nconst RELATIVE_ARG = /\\{[^{}]*:\\s*relative\\b/;\n\nexport function needsRelative(catalogs: Catalogs): boolean {\n for (const catalog of Object.values(catalogs)) {\n for (const message of Object.values(flatten(catalog as MessageTree))) {\n if (RELATIVE_ARG.test(message)) return true;\n }\n }\n return false;\n}\n","import { emptyCatalog, type Catalogs } from './catalog';\nimport type { ResolvedConfig } from './config';\nimport type { MessageRegistry } from './registry';\nimport { counted } from './text';\n\n// segment prefix, never substring: excluding \"nav\" must not take \"navbar_x\" with it\nfunction isExcluded(key: string, prefixes: string[]): boolean {\n return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));\n}\n\n// what the browser gets; render and the gate keep reading the full catalogs from disk\nexport function clientCatalogs(cfg: ResolvedConfig, catalogs: Catalogs): Catalogs {\n const prefixes = cfg.bundle.exclude ?? [];\n if (prefixes.length === 0) return catalogs;\n const out: Catalogs = {};\n for (const [locale, catalog] of Object.entries(catalogs)) {\n const kept = emptyCatalog();\n for (const [key, message] of Object.entries(catalog)) {\n if (!isExcluded(key, prefixes)) kept[key] = message;\n }\n out[locale] = kept;\n }\n return out;\n}\n\nexport interface BundleIssue {\n prefix: string;\n problem: string;\n fix: string;\n}\n\n// never a gate failure: an excluded namespace builds, it just may not be there when code asks\nexport function auditBundle(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: MessageRegistry,\n): BundleIssue[] {\n const prefixes = cfg.bundle.exclude ?? [];\n if (prefixes.length === 0) return [];\n const source = Object.keys(catalogs[cfg.sourceLocale] ?? {});\n const used = registry.usedKeys();\n\n const issues: BundleIssue[] = [];\n for (const prefix of prefixes) {\n if (!source.some((key) => isExcluded(key, [prefix]))) {\n issues.push({\n prefix,\n problem: `matches no key in ${cfg.sourceLocale}.json, so it excludes nothing`,\n fix: 'check the spelling against your catalog, or drop it from bundle.exclude',\n });\n continue;\n }\n const files = new Set<string>();\n for (const [key, where] of used) {\n if (isExcluded(key, [prefix])) for (const file of where) files.add(file);\n }\n if (files.size > 0) {\n issues.push({\n prefix,\n problem: `is read by t() in ${counted(files.size, 'file')}, where it resolves to the key itself`,\n fix: 'pre-render those pages with render, load the group with addMessages, or stop excluding it',\n });\n }\n }\n return issues;\n}\n\n// one wording for the build gate and for doctor, so the two can never say different things\nexport function formatBundleIssue(issue: BundleIssue): string {\n return `bundle.exclude \"${issue.prefix}\" ${issue.problem}`;\n}\n","import type { Analysis, MissedCall, StrayImport, TaggedMessage } from './analyze';\n\n// one key, several texts: the earliest one wins everywhere, so the others render its words\nexport interface Collision {\n key: string;\n kept: TaggedMessage;\n dropped: TaggedMessage[];\n}\n\nexport class MessageRegistry {\n private files = new Map<string, Analysis>();\n\n update(file: string, analysis: Analysis): void {\n this.files.set(file, analysis);\n }\n\n remove(file: string): void {\n this.files.delete(file);\n }\n\n // the earliest site wins, by file then position, so no scan or load order ever picks the text\n messages(): Map<string, TaggedMessage> {\n const out = new Map<string, TaggedMessage>();\n for (const analysis of this.inOrder()) {\n for (const msg of analysis.tagged) {\n const held = out.get(msg.key);\n if (!held || earlier(msg, held)) out.set(msg.key, msg);\n }\n }\n return out;\n }\n\n // every place whose text differs from the one that wins, so fixing one never hides the next\n collisions(): Collision[] {\n const winners = this.messages();\n const dropped = new Map<string, TaggedMessage[]>();\n for (const analysis of this.inOrder()) {\n for (const msg of analysis.tagged) {\n if (msg.message === winners.get(msg.key)!.message) continue;\n dropped.set(msg.key, [...(dropped.get(msg.key) ?? []), msg]);\n }\n }\n return [...dropped].map(([key, others]) => ({\n key,\n kept: winners.get(key)!,\n dropped: others.sort((a, b) => (earlier(a, b) ? -1 : 1)),\n }));\n }\n\n // strict leaves out the loose spellings, which the gate does not fail on yet\n usedKeys(strict = false): Map<string, string[]> {\n const out = new Map<string, string[]>();\n for (const analysis of this.inOrder()) {\n for (const used of analysis.usedKeys) {\n if (strict && used.loose) continue;\n const files = out.get(used.key) ?? [];\n if (!files.includes(used.file)) files.push(used.file);\n out.set(used.key, files);\n }\n }\n return out;\n }\n\n strayImports(): StrayImport[] {\n return this.inOrder().flatMap((analysis) => analysis.strayImports);\n }\n\n // a t under another name: its texts are neither extracted nor rewritten, so they never translate\n missed(): MissedCall[] {\n return this.inOrder().flatMap((analysis) => analysis.missed);\n }\n\n // files the parser could not read: they contributed no messages and nothing else can tell\n parseErrors(): { file: string; message: string }[] {\n const out: { file: string; message: string }[] = [];\n for (const file of [...this.files.keys()].sort()) {\n const { parseError } = this.files.get(file)!;\n if (parseError) out.push({ file, message: parseError });\n }\n return out;\n }\n\n // key → every source file that writes or uses it (translator context)\n origins(): Map<string, string[]> {\n const out = this.usedKeys();\n for (const analysis of this.inOrder()) {\n for (const msg of analysis.tagged) {\n const files = out.get(msg.key) ?? [];\n if (!files.includes(msg.file)) files.push(msg.file);\n out.set(msg.key, files);\n }\n }\n return out;\n }\n\n // by path: a dev server registers files in load order, and every report must read the same\n private inOrder(): Analysis[] {\n return [...this.files.keys()].sort().map((file) => this.files.get(file)!);\n }\n}\n\nfunction earlier(a: TaggedMessage, b: TaggedMessage): boolean {\n return a.file === b.file ? a.start < b.start : a.file < b.file;\n}\n","import { createHash } from 'node:crypto';\n\nexport function stableKey(message: string): string {\n return createHash('sha256').update(message).digest('base64url').slice(0, 8);\n}\n","import { parse } from '@babel/parser';\nimport { stableKey } from './key';\n\nexport interface TaggedParam {\n name: string;\n start: number;\n end: number;\n}\n\nexport interface TransComponent {\n name: string;\n source: string;\n}\n\nexport interface TaggedMessage {\n key: string;\n message: string;\n params: TaggedParam[];\n start: number;\n end: number;\n line: number;\n tagStart: number;\n tagEnd: number;\n file: string;\n jsx?: { name: string; components: TransComponent[] };\n singleQuote?: boolean;\n}\n\nexport interface UsedKey {\n key: string;\n file: string;\n loose?: true;\n}\n\n// a named import the verbaly packages do not export: t comes from an instance, never from a package\nexport interface StrayImport {\n name: string;\n source: string;\n file: string;\n}\n\n// a tagged template on t under another name: never extracted, never rewritten, never translated\nexport interface MissedCall {\n name: string;\n file: string;\n start: number;\n line: number;\n}\n\nexport interface Analysis {\n tagged: TaggedMessage[];\n usedKeys: UsedKey[];\n strayImports: StrayImport[];\n missed: MissedCall[];\n parseError?: string;\n}\n\n// babel's message carries the position but never the path: every caller adds the file itself\nexport function parseErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n// exported for wrap.ts (module-internal reuse, not part of the package surface)\nexport interface AstNode {\n type: string;\n start: number;\n end: number;\n [key: string]: unknown;\n}\n\nconst SKIP_KEYS = new Set(['loc', 'leadingComments', 'trailingComments', 'innerComments', 'extra']);\n\nexport interface AnalyzeOptions {\n tNames?: readonly string[];\n renamed?: readonly string[];\n}\n\nconst DEFAULT_T_NAMES: readonly string[] = ['t'];\nconst JSX_FILE_RE = /\\.(?:[cm]?jsx?|tsx)$/;\n\n// a key module declares what a call site would otherwise pass as a literal the scanner can read\nconst DEFINE_KEYS = 'defineKeys';\n\nexport function analyze(code: string, file: string, options: AnalyzeOptions = {}): Analysis {\n return analyzeScript(code, file, options).analysis;\n}\n\n// a tagged template or a call on a name other than t, judged once every binding is known\ntype Candidate = { kind: 'tag'; node: AstNode } | { kind: 'call'; name: string; key: string };\n\n// the analysis plus the names t was renamed to, which an SFC hands on to its markup\nexport function analyzeScript(\n code: string,\n file: string,\n options: AnalyzeOptions = {},\n): { analysis: Analysis; renamed: string[] } {\n const names = new Set(options.tNames ?? DEFAULT_T_NAMES);\n const ast = parse(code, {\n sourceType: 'module',\n errorRecovery: true,\n plugins: JSX_FILE_RE.test(file) ? ['typescript', 'jsx'] : ['typescript'],\n });\n\n const tagged: TaggedMessage[] = [];\n const usedKeys: UsedKey[] = [];\n const strayImports: StrayImport[] = [];\n const bindings = new Bindings(names);\n const candidates: Candidate[] = [];\n\n walk(ast.program as unknown as AstNode, (node) => {\n if (node.type === 'ImportDeclaration') {\n collectStrayImports(node, file, strayImports);\n bindings.addImport(node);\n } else if (node.type === 'VariableDeclarator') {\n bindings.addDeclarator(node);\n } else if (node.type === 'TaggedTemplateExpression') {\n const tag = node.tag as AstNode;\n const explicit = explicitId(tag, names);\n if (!explicit && !isTReference(tag, names)) {\n candidates.push({ kind: 'tag', node });\n return;\n }\n const quasi = node.quasi as AstNode;\n const message = buildMessage(code, quasi, names);\n if (!message) return;\n tagged.push({\n key: explicit ? explicit.key : stableKey(message.text),\n message: message.text,\n params: message.params,\n start: node.start,\n end: node.end,\n line: lineOf(node),\n tagStart: explicit ? explicit.refStart : tag.start,\n tagEnd: explicit ? explicit.refEnd : tag.end,\n file,\n });\n } else if (node.type === 'CallExpression') {\n const callee = node.callee as AstNode;\n const args = node.arguments as AstNode[];\n if (callee.type === 'Identifier' && callee.name === DEFINE_KEYS) {\n collectDeclaredKeys(args[0], file, usedKeys);\n return;\n }\n if (!isTReference(callee, names)) {\n const key = callee.type === 'Identifier' ? staticString(args[0]) : undefined;\n if (key !== undefined) candidates.push({ kind: 'call', name: callee.name as string, key });\n return;\n }\n const key = staticString(args[0]);\n if (key !== undefined) usedKeys.push(usedKey(key, file, args[0]));\n } else if (node.type === 'JSXElement') {\n handleTrans(code, node, file, tagged, usedKeys, names);\n }\n });\n\n const renamed = bindings.renamed(options.renamed);\n const missed: MissedCall[] = [];\n for (const candidate of candidates) {\n // a key read under another name is in use: loose, so prune keeps it and no gate fails\n if (candidate.kind === 'call') {\n if (renamed.has(candidate.name)) usedKeys.push({ key: candidate.key, file, loose: true });\n continue;\n }\n const { node } = candidate;\n const name = renamedTag(node.tag as AstNode, renamed);\n if (!name) continue;\n missed.push({ name, file, start: node.start, line: lineOf(node) });\n // never extracted, yet its translation has to outlive prune until the binding is named t\n const key = missedKey(code, node, names);\n if (key !== undefined) usedKeys.push({ key, file, loose: true });\n }\n\n return { analysis: { tagged, usedKeys, strayImports, missed }, renamed: [...renamed] };\n}\n\nfunction lineOf(node: AstNode): number {\n return (node.loc as { start: { line: number } } | undefined)?.start.line ?? 1;\n}\n\n// a module whose exports hand out verbaly's t: the core, every adapter and virtual:verbaly\nconst VERBALY_SOURCE = /^(?:verbaly|virtual:verbaly|@verbaly\\/[\\w-]+(?:\\/[\\w-]+)*)$/;\n\n// how each factory hands out t: useT() returns it, getT() resolves to it\nconst T_FACTORIES = new Map([\n ['useT', 'call'],\n ['getT', 'await'],\n]);\n\n// instance factories whose result carries t, for const { t: x } = useVerbaly() with no import\nconst INSTANCE_FACTORIES = new Set(['useVerbaly', 'getVerbaly']);\n\n// what hands out a t in this file, judged by where each name was imported from\nclass Bindings {\n private imports = new Map<string, { source: string; imported: string }>();\n private direct = new Set<string>();\n private declared: { name: string; init: AstNode }[] = [];\n private destructured: { name: string; init: AstNode }[] = [];\n\n constructor(private names: ReadonlySet<string>) {}\n\n addImport(node: AstNode): void {\n const source = (node.source as { value?: unknown }).value;\n if (typeof source !== 'string') return;\n for (const spec of node.specifiers as AstNode[]) {\n const local = identifierName(spec.local as AstNode);\n if (!local) continue;\n const imported =\n spec.type === 'ImportSpecifier' ? importedName(spec.imported as AstNode) : spec.type;\n this.imports.set(local, { source, imported });\n if (source === 'virtual:verbaly' && imported === 't') this.direct.add(local);\n }\n }\n\n addDeclarator(node: AstNode): void {\n const id = node.id as AstNode;\n const init = node.init as AstNode | null;\n if (!init) return;\n if (id.type === 'Identifier') {\n this.declared.push({ name: id.name as string, init });\n return;\n }\n if (id.type !== 'ObjectPattern') return;\n for (const property of id.properties as AstNode[]) {\n if (property.type !== 'ObjectProperty' || property.computed) continue;\n if (identifierName(property.key as AstNode) !== 't') continue;\n const value = property.value as AstNode;\n // { t: x = fallback } binds x all the same\n const target = value.type === 'AssignmentPattern' ? (value.left as AstNode) : value;\n const name = identifierName(target);\n if (name) this.destructured.push({ name, init });\n }\n }\n\n renamed(seed: readonly string[] = []): Set<string> {\n const out = new Set(seed);\n const add = (name: string): void => {\n if (this.names.has(name)) return;\n out.add(name);\n // a svelte store is read as $name, the way t itself is read as $t\n if (this.names.has('$t')) out.add(`$${name}`);\n };\n for (const name of this.direct) add(name);\n for (const { name, init } of this.declared) if (this.handsOutT(init)) add(name);\n for (const { name, init } of this.destructured) if (this.carriesT(init)) add(name);\n return out;\n }\n\n // useT() or await getT(), imported from verbaly or not imported at all (a Nuxt auto-import)\n private handsOutT(init: AstNode): boolean {\n const awaited = init.type === 'AwaitExpression';\n const call = awaited ? (init.argument as AstNode) : init;\n if (call.type !== 'CallExpression') return false;\n const origin = this.origin(identifierName(call.callee as AstNode));\n if (origin.verbaly === false) return false;\n const how = T_FACTORIES.get(origin.imported);\n return how !== undefined && (how === 'await') === awaited;\n }\n\n // { t: x } reads from something verbaly handed out, or from an auto-imported instance factory\n private carriesT(init: AstNode): boolean {\n const inner = init.type === 'AwaitExpression' ? (init.argument as AstNode) : init;\n const read = inner.type === 'CallExpression' ? (inner.callee as AstNode) : inner;\n const name = identifierName(read);\n if (!name) return false;\n const origin = this.origin(name);\n return origin.verbaly ?? INSTANCE_FACTORIES.has(name);\n }\n\n private origin(local: string): { verbaly: boolean | undefined; imported: string } {\n const found = this.imports.get(local);\n if (!found) return { verbaly: undefined, imported: local };\n return { verbaly: VERBALY_SOURCE.test(found.source), imported: found.imported };\n }\n}\n\nfunction importedName(node: AstNode): string {\n return node.type === 'StringLiteral' ? (node.value as string) : identifierName(node);\n}\n\nfunction identifierName(node: AstNode | null | undefined): string {\n return node?.type === 'Identifier' ? (node.name as string) : '';\n}\n\n// x`…` or x.id('…')`…` where x is a renamed t\nfunction renamedTag(tag: AstNode, renamed: ReadonlySet<string>): string | undefined {\n if (renamed.size === 0) return undefined;\n const name = identifierName(tag);\n if (renamed.has(name)) return name;\n if (tag.type !== 'CallExpression') return undefined;\n const callee = tag.callee as AstNode;\n if (callee.type !== 'MemberExpression' || callee.computed) return undefined;\n if (identifierName(callee.property as AstNode) !== 'id') return undefined;\n const object = identifierName(callee.object as AstNode);\n return renamed.has(object) ? object : undefined;\n}\n\n// the key a tagged template on a renamed t would have had: its quoted id, or its text's hash\nfunction missedKey(code: string, node: AstNode, names: ReadonlySet<string>): string | undefined {\n const tag = node.tag as AstNode;\n if (tag.type === 'CallExpression') {\n const args = tag.arguments as AstNode[];\n const first = args[0];\n return args.length === 1 && first?.type === 'StringLiteral'\n ? (first.value as string)\n : undefined;\n }\n const message = buildMessage(code, node.quasi as AstNode, names);\n return message ? stableKey(message.text) : undefined;\n}\n\n// every string leaf is a key: the call is the author saying so, and '' still means untranslated\nfunction collectDeclaredKeys(node: AstNode | undefined, file: string, out: UsedKey[]): void {\n if (node?.type !== 'ObjectExpression') return;\n for (const property of node.properties as AstNode[]) {\n if (property.type !== 'ObjectProperty') continue;\n const value = property.value as AstNode;\n const key = staticString(value);\n if (key !== undefined) {\n if (key !== '') out.push(usedKey(key, file, value));\n } else if (value.type === 'ObjectExpression') {\n collectDeclaredKeys(value, file, out);\n }\n }\n}\n\nfunction usedKey(key: string, file: string, node: AstNode | null | undefined): UsedKey {\n return node?.type === 'StringLiteral' ? { key, file } : { key, file, loose: true };\n}\n\n// a key is a literal however it is spelled: '…', `…` with no ${}, or {'…'} in a JSX attribute\nfunction staticString(node: AstNode | null | undefined): string | undefined {\n if (!node) return undefined;\n if (node.type === 'StringLiteral') return node.value as string;\n if (node.type === 'TemplateLiteral' && (node.expressions as AstNode[]).length === 0) {\n return cookedValue((node.quasis as AstNode[])[0]);\n }\n if (node.type === 'JSXExpressionContainer') return staticString(node.expression as AstNode);\n return undefined;\n}\n\nconst VERBALY_PACKAGE = /^(?:verbaly|@verbaly\\/[\\w-]+)$/;\n\n// the most plausible onboarding error: only the bundler used to complain, and never about verbaly\nfunction collectStrayImports(node: AstNode, file: string, out: StrayImport[]): void {\n const source = node.source as { value?: unknown };\n if (typeof source.value !== 'string' || !VERBALY_PACKAGE.test(source.value)) return;\n for (const spec of node.specifiers as AstNode[]) {\n if (spec.type !== 'ImportSpecifier') continue;\n const imported = spec.imported as AstNode;\n if (imported.type !== 'Identifier') continue;\n const name = imported.name as string;\n // both come from virtual:verbaly, which is the project's module and never a package export\n if (name === 't' || name === DEFINE_KEYS) out.push({ name, source: source.value, file });\n }\n}\n\nfunction handleTrans(\n code: string,\n node: AstNode,\n file: string,\n tagged: TaggedMessage[],\n usedKeys: UsedKey[],\n names: ReadonlySet<string>,\n): void {\n const opening = node.openingElement as AstNode;\n const nameNode = opening.name as AstNode;\n if (nameNode.type !== 'JSXIdentifier' || nameNode.name !== 'Trans') return;\n\n const attrs = opening.attributes as AstNode[];\n const idAttr = attrs.find((a) => a.type === 'JSXAttribute' && (a.name as AstNode).name === 'id');\n const children = node.children as AstNode[] | undefined;\n const push = (key: string, built: BuiltTrans) =>\n tagged.push({\n key,\n message: built.text,\n params: built.params,\n start: node.start,\n end: node.end,\n line: lineOf(node),\n tagStart: nameNode.start,\n tagEnd: nameNode.end,\n file,\n jsx: { name: nameNode.name as string, components: built.components },\n });\n\n if (idAttr) {\n const value = idAttr.value as AstNode | null;\n const id = staticString(value);\n if (id === undefined) return;\n // quoted id + children → extract under the explicit key; a backtick id never extracted before\n if (value?.type === 'StringLiteral' && attrs.length === 1 && children?.length) {\n const built = buildTransMessage(code, children, names);\n if (built?.text.trim()) {\n push(id, built);\n return;\n }\n }\n usedKeys.push(usedKey(id, file, value));\n return; // runtime-first, untouched\n }\n if (attrs.length > 0) return; // hand-written props → don't guess\n\n if (!children?.length) return;\n\n const built = buildTransMessage(code, children, names);\n if (!built || !built.text.trim()) return;\n\n push(stableKey(built.text), built);\n}\n\n// t.id('key')`…` → explicit readable key\nfunction explicitId(\n tag: AstNode,\n names: ReadonlySet<string>,\n): { key: string; refStart: number; refEnd: number } | undefined {\n if (tag.type !== 'CallExpression') return undefined;\n const callee = tag.callee as AstNode;\n if (callee.type !== 'MemberExpression' || callee.computed) return undefined;\n const prop = callee.property as AstNode;\n if (prop.type !== 'Identifier' || prop.name !== 'id') return undefined;\n const obj = callee.object as AstNode;\n if (!isTReference(obj, names)) return undefined;\n const args = tag.arguments as AstNode[];\n const first = args[0];\n // quoted only: extracting a backtick id now would be a new reason for a build to fail\n if (args.length !== 1 || first?.type !== 'StringLiteral') return undefined;\n return { key: first.value as string, refStart: obj.start, refEnd: obj.end };\n}\n\ninterface BuiltTrans {\n text: string;\n params: TaggedParam[];\n components: TransComponent[];\n}\n\nfunction buildTransMessage(\n code: string,\n children: AstNode[],\n names: ReadonlySet<string>,\n): BuiltTrans | undefined {\n const params: TaggedParam[] = [];\n const components: TransComponent[] = [];\n const takenParams = new Map<string, string>();\n const takenTags = new Map<string, string>();\n\n function walkChildren(nodes: AstNode[]): string | undefined {\n let text = '';\n for (const child of nodes) {\n if (child.type === 'JSXText') {\n text += escapeText(cleanJsxText(child.value as string));\n } else if (child.type === 'JSXExpressionContainer') {\n const expr = child.expression as AstNode;\n if (expr.type === 'JSXEmptyExpression') continue;\n if (expr.type === 'StringLiteral') {\n text += escapeText(expr.value as string);\n continue;\n }\n if (containsTaggedT(expr, names)) return undefined; // overlap hazard\n const source = code.slice(expr.start, expr.end);\n const name = uniqueName(deriveName(expr, params.length), source, takenParams);\n params.push({ name, start: expr.start, end: expr.end });\n text += `{${name}}`;\n } else if (child.type === 'JSXElement') {\n const opening = child.openingElement as AstNode;\n const nameNode = opening.name as AstNode;\n if (nameNode.type !== 'JSXIdentifier' || nameNode.name === 'Trans') return undefined;\n const source = selfClosedSource(code, opening);\n const tag = uniqueName((nameNode.name as string).toLowerCase(), source, takenTags);\n if (!components.some((c) => c.name === tag)) components.push({ name: tag, source });\n if (!child.closingElement) {\n text += `<${tag}/>`;\n } else {\n const inner = walkChildren(child.children as AstNode[]);\n if (inner === undefined) return undefined;\n text += `<${tag}>${inner}</${tag}>`;\n }\n } else {\n return undefined; // fragments / spread children → bail\n }\n }\n return text;\n }\n\n const text = walkChildren(children);\n if (text === undefined) return undefined;\n return { text, params, components };\n}\n\n// JSX text semantics: newline-indent boundaries removed, interior joins = one space\nexport function cleanJsxText(raw: string): string {\n const lines = raw.split(/\\r\\n|[\\r\\n]/);\n let out = '';\n for (let i = 0; i < lines.length; i++) {\n let line = lines[i]!.replace(/\\t/g, ' ');\n if (i !== 0) line = line.replace(/^ +/, '');\n if (i !== lines.length - 1) line = line.replace(/ +$/, '');\n if (!line) continue;\n if (out && i !== 0) out += ' ';\n out += line;\n }\n return out;\n}\n\nfunction selfClosedSource(code: string, opening: AstNode): string {\n const src = code.slice(opening.start, opening.end);\n return src.endsWith('/>') ? src : `${src.slice(0, -1).trimEnd()} />`;\n}\n\n// true if the subtree holds a t`…` / t.id('…')`…` that analyze would extract itself\nfunction containsTaggedT(node: AstNode, names: ReadonlySet<string>): boolean {\n let found = false;\n walk(node, (n) => {\n if (n.type !== 'TaggedTemplateExpression') return;\n const tag = n.tag as AstNode;\n if (isTReference(tag, names) || explicitId(tag, names)) found = true;\n });\n return found;\n}\n\nexport function isTReference(node: AstNode, names: ReadonlySet<string>): boolean {\n if (node.type === 'Identifier') return names.has(node.name as string);\n if (node.type === 'MemberExpression' && !node.computed) {\n const prop = node.property as AstNode;\n return prop.type === 'Identifier' && names.has(prop.name as string);\n }\n return false;\n}\n\ninterface BuiltMessage {\n text: string;\n params: TaggedParam[];\n}\n\nfunction buildMessage(\n code: string,\n quasi: AstNode,\n names: ReadonlySet<string>,\n): BuiltMessage | undefined {\n const quasis = quasi.quasis as AstNode[];\n const expressions = quasi.expressions as AstNode[];\n const params: TaggedParam[] = [];\n const taken = new Map<string, string>();\n\n let text = escapeText(cookedValue(quasis[0]));\n\n for (let i = 0; i < expressions.length; i++) {\n const expr = expressions[i];\n if (!expr) return undefined;\n // a nested t`…` would be extracted on its own: overlapping rewrites; bail the outer\n if (containsTaggedT(expr, names)) return undefined;\n const source = code.slice(expr.start, expr.end);\n const name = uniqueName(deriveName(expr, i), source, taken);\n params.push({ name, start: expr.start, end: expr.end });\n text += `{${name}}` + escapeText(cookedValue(quasis[i + 1]));\n }\n return { text, params };\n}\n\nfunction cookedValue(element: AstNode | undefined): string {\n if (!element) return '';\n const value = element.value as { cooked?: string; raw: string };\n return value.cooked ?? value.raw;\n}\n\n// literal braces → escaped\nfunction escapeText(text: string): string {\n return text.replace(/[{}]/g, (m) => m + m);\n}\n\nfunction deriveName(expr: AstNode, index: number): string {\n if (expr.type === 'Identifier') return expr.name as string;\n if (expr.type === 'MemberExpression' && !expr.computed) {\n const prop = expr.property as AstNode;\n if (prop.type === 'Identifier') return prop.name as string;\n }\n return `_${index}`;\n}\n\nfunction uniqueName(base: string, source: string, taken: Map<string, string>): string {\n let name = base;\n let n = 2;\n while (taken.has(name) && taken.get(name) !== source) {\n name = `${base}${n}`;\n n += 1;\n }\n taken.set(name, source);\n return name;\n}\n\nexport function walk(node: AstNode, visit: (node: AstNode) => void): void {\n visit(node);\n for (const key in node) {\n if (SKIP_KEYS.has(key)) continue;\n const value = node[key];\n if (Array.isArray(value)) {\n for (const item of value) {\n if (isNode(item)) walk(item, visit);\n }\n } else if (isNode(value)) {\n walk(value, visit);\n }\n }\n}\n\nfunction isNode(value: unknown): value is AstNode {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { type?: unknown }).type === 'string'\n );\n}\n","import {\n analyze,\n analyzeScript,\n parseErrorMessage,\n type Analysis,\n type AnalyzeOptions,\n type MissedCall,\n type StrayImport,\n type TaggedParam,\n type UsedKey,\n} from './analyze';\n\nexport const SFC_FILE_RE = /\\.(?:svelte|vue|astro)$/;\n\n// single dispatch point: SFCs get the block/markup analyzer, everything else plain analyze\nexport function analyzeFile(code: string, file: string): Analysis {\n if (SFC_FILE_RE.test(file)) return analyzeSfc(code, file);\n try {\n return analyze(code, file);\n } catch (error) {\n // one file the parser cannot read must never take down a whole extract, check or doctor\n const message = parseErrorMessage(error);\n return { tagged: [], usedKeys: [], strayImports: [], missed: [], parseError: message };\n }\n}\n\nconst SCRIPT_RE = /(<script\\b[^>]*>)([\\s\\S]*?)(<\\/script\\s*>)/gi;\nconst STYLE_RE = /<style\\b[^>]*>[\\s\\S]*?<\\/style\\s*>/gi;\nconst COMMENT_RE = /<!--[\\s\\S]*?-->/g;\n// astro component script: --- fences at the top of the file\nconst FRONTMATTER_RE = /^(\\uFEFF?\\s*---\\r?\\n)([\\s\\S]*?)\\r?\\n---(?=\\r?\\n|$)/;\n\nconst MUSTACHE_RE = /\\{\\{[\\s\\S]*?\\}\\}/g;\nconst DIRECTIVE_RE = /\\s(?:v-[\\w-]+(?::[^\\s=>/]+)?|[:@][^\\s=>/]+)\\s*=\\s*(\"[^\"]*\"|'[^']*')/g;\n\nexport function analyzeSfc(code: string, file: string): Analysis {\n // svelte components consume t as a store: $t`…` is the idiomatic form\n const svelte = file.endsWith('.svelte');\n const tNames = svelte ? ['t', '$t'] : ['t'];\n\n const tagged: Analysis['tagged'] = [];\n const usedKeys: UsedKey[] = [];\n const strayImports: StrayImport[] = [];\n const missed: MissedCall[] = [];\n const renamed = new Set<string>();\n const lineAt = lineCounter(code);\n let parseError: string | undefined;\n\n // a script block is structural: if it does not parse, the file is reported, unlike a markup slice\n const block = (content: string, offset: number): void => {\n const segment = analyzeSegment(content, file, { tNames });\n parseError ??= segment.error;\n for (const name of segment.renamed) renamed.add(name);\n merge(segment.analysis, offset, false);\n };\n\n const frontmatter = file.endsWith('.astro') ? FRONTMATTER_RE.exec(code) : null;\n if (frontmatter?.[2]) block(frontmatter[2], frontmatter[1]!.length);\n\n for (const match of code.matchAll(SCRIPT_RE)) {\n const content = match[2]!;\n if (content) block(content, match.index + match[1]!.length);\n }\n\n // markup = everything left once frontmatter, scripts, styles and comments are blanked out\n const body = frontmatter\n ? ' '.repeat(frontmatter[0].length) + code.slice(frontmatter[0].length)\n : code;\n const markup = blank(blank(blank(body, SCRIPT_RE), STYLE_RE), COMMENT_RE);\n // the markup reads the script's bindings, so a t renamed there is followed here too\n const markupOptions: AnalyzeOptions = { tNames, renamed: [...renamed] };\n // display-only text never yields candidates: only expression context counts\n const ranges = file.endsWith('.vue') ? vueExpressionRanges(markup) : braceRanges(markup);\n let range = 0;\n let consumedTo = 0;\n for (const match of markup.matchAll(candidatePattern(svelte, renamed))) {\n const start = match.index;\n if (start < consumedTo) continue;\n while (range < ranges.length && ranges[range]![1] <= start) range += 1;\n if (range >= ranges.length || start < ranges[range]![0]) continue;\n const end = expressionExtent(markup, start, match[0].length);\n if (end === undefined) continue;\n merge(analyzeSegment(code.slice(start, end), file, markupOptions).analysis, start, true);\n consumedTo = end;\n }\n\n return { tagged, usedKeys, strayImports, missed, ...(parseError && { parseError }) };\n\n function merge(analysis: Analysis | undefined, offset: number, markupSegment: boolean): void {\n if (!analysis) return;\n const lines = lineAt(offset) - 1;\n for (const msg of analysis.tagged) {\n tagged.push({\n ...msg,\n start: msg.start + offset,\n end: msg.end + offset,\n line: msg.line + lines,\n tagStart: msg.tagStart + offset,\n tagEnd: msg.tagEnd + offset,\n params: msg.params.map((p): TaggedParam => ({\n ...p,\n start: p.start + offset,\n end: p.end + offset,\n })),\n ...(markupSegment && { singleQuote: true }),\n });\n }\n for (const call of analysis.missed) {\n missed.push({ ...call, start: call.start + offset, line: call.line + lines });\n }\n usedKeys.push(...analysis.usedKeys);\n strayImports.push(...analysis.strayImports);\n }\n}\n\n// no whitespace after the name: prose like \"won't ('x')\" must never become a used key\nfunction candidatePattern(svelte: boolean, renamed: ReadonlySet<string>): RegExp {\n const bare = new Set(['t', ...[...renamed].map((name) => name.replace(/^\\$/, ''))]);\n const names = [...bare].map((name) => name.replace(/[$]/g, '\\\\$')).join('|');\n return new RegExp(`(?<![\\\\w$])${svelte ? '\\\\$?' : ''}(?:${names})(?=[\\`(]|\\\\.id\\\\()`, 'g');\n}\n\n// 1-based line of an offset, from one pass over the file however many segments ask\nfunction lineCounter(code: string): (offset: number) => number {\n const breaks: number[] = [];\n for (let i = code.indexOf('\\n'); i !== -1; i = code.indexOf('\\n', i + 1)) breaks.push(i);\n return (offset) => {\n let low = 0;\n let high = breaks.length;\n while (low < high) {\n const mid = (low + high) >> 1;\n if (breaks[mid]! < offset) low = mid + 1;\n else high = mid;\n }\n return low + 1;\n };\n}\n\ninterface SegmentResult {\n analysis?: Analysis;\n renamed: string[];\n error?: string;\n}\n\nfunction analyzeSegment(code: string, file: string, options: AnalyzeOptions): SegmentResult {\n try {\n return analyzeScript(code, file, options);\n } catch (error) {\n // never fail the whole file over one segment\n return { renamed: [], error: parseErrorMessage(error) };\n }\n}\n\nfunction blank(source: string, re: RegExp): string {\n return source.replace(re, (m) => ' '.repeat(m.length));\n}\n\n// [start, end) content spans of balanced {…} regions (astro expressions, svelte mustaches)\nfunction braceRanges(markup: string): Array<[number, number]> {\n const ranges: Array<[number, number]> = [];\n let i = 0;\n while (i < markup.length) {\n if (markup[i] === '{') {\n const end = balancedEnd(markup, i);\n if (end !== undefined) {\n ranges.push([i + 1, end - 1]);\n i = end;\n continue;\n }\n }\n i += 1;\n }\n return ranges;\n}\n\n// vue expression context: {{ mustaches }} plus quoted values of :/@/v- directive attributes\nfunction vueExpressionRanges(markup: string): Array<[number, number]> {\n const ranges: Array<[number, number]> = [];\n for (const match of markup.matchAll(MUSTACHE_RE)) {\n ranges.push([match.index + 2, match.index + match[0].length - 2]);\n }\n for (const match of markup.matchAll(DIRECTIVE_RE)) {\n const valueStart = match.index + match[0].length - match[1]!.length + 1;\n ranges.push([valueStart, valueStart + match[1]!.length - 2]);\n }\n return ranges.sort((a, b) => a[0] - b[0]);\n}\n\n// end (exclusive) of the expression starting at a candidate: t`…` | t(...) | t.id('…')`…`\nfunction expressionExtent(code: string, start: number, nameLength: number): number | undefined {\n const i = start + nameLength;\n if (code.startsWith('.id(', i)) {\n const close = balancedEnd(code, i + 3);\n if (close === undefined || code[close] !== '`') return undefined;\n return balancedEnd(code, close);\n }\n if (code[i] === '`' || code[i] === '(') return balancedEnd(code, i);\n return undefined;\n}\n\n// scans a template literal or paren group to its close, tracking nested ${…}, strings and groups\nfunction balancedEnd(code: string, open: number): number | undefined {\n const stack: string[] = [];\n let i = open;\n while (i < code.length) {\n const ch = code[i]!;\n if (stack[stack.length - 1] === '`') {\n if (ch === '\\\\') i += 1;\n else if (ch === '`') stack.pop();\n else if (ch === '$' && code[i + 1] === '{') {\n stack.push('{');\n i += 1;\n }\n } else if (ch === \"'\" || ch === '\"') {\n i = stringEnd(code, i);\n } else if (ch === '`' || ch === '(' || ch === '{') {\n stack.push(ch);\n } else if (ch === ')' || ch === '}') {\n if (stack[stack.length - 1] !== (ch === ')' ? '(' : '{')) return undefined;\n stack.pop();\n }\n i += 1;\n if (stack.length === 0) return i;\n }\n return undefined;\n}\n\nfunction stringEnd(code: string, start: number): number {\n const quote = code[start];\n let i = start + 1;\n while (i < code.length) {\n if (code[i] === '\\\\') i += 2;\n else if (code[i] === quote) return i;\n else i += 1;\n }\n return code.length;\n}\n","import { readFileSync } from 'node:fs';\nimport { relative } from 'node:path';\nimport { glob } from 'tinyglobby';\nimport { flatten } from 'verbaly';\nimport { emptyCatalog, own, type Catalogs } from './catalog';\nimport type { ResolvedConfig } from './config';\nimport { MessageRegistry } from './registry';\nimport { analyzeFile } from './sfc';\n\nexport async function extractProject(cfg: ResolvedConfig): Promise<MessageRegistry> {\n const files = await glob(cfg.include, {\n cwd: cfg.root,\n ignore: cfg.exclude,\n absolute: true,\n });\n const registry = new MessageRegistry();\n // tinyglobby crawls sibling folders in parallel, so its order changes from one run to the next\n for (const file of files.sort()) {\n registry.update(file, analyzeFile(readFileSync(file, 'utf8'), file));\n }\n return registry;\n}\n\n// root-relative with forward slashes so a translator reads the same path on any OS, one scan\nexport async function collectOrigins(\n cfg: ResolvedConfig,\n reuse?: MessageRegistry,\n): Promise<Record<string, string[]>> {\n const registry = reuse ?? (await extractProject(cfg));\n const origins: Record<string, string[]> = Object.create(null);\n for (const [key, files] of registry.origins()) {\n origins[key] = files.map((file) => relative(cfg.root, file).replaceAll('\\\\', '/'));\n }\n return origins;\n}\n\n// a source text the code wrote over, and what the catalog said before\nexport interface ReplacedText {\n key: string;\n before: string;\n}\n\nexport interface SyncResult {\n // keys new to each catalog; a source text the code rewrote is in replaced, not here\n added: Record<string, string[]>;\n replaced: ReplacedText[];\n}\n\n// fills source texts + '' placeholders; a text written in the code always wins over the catalog\nexport function syncCatalogs(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: MessageRegistry,\n): SyncResult {\n const added: Record<string, string[]> = {};\n const replaced: ReplacedText[] = [];\n const source = (catalogs[cfg.sourceLocale] ??= emptyCatalog());\n\n for (const [key, msg] of registry.messages()) {\n const before = own(source, key);\n if (before === msg.message) continue;\n source[key] = msg.message;\n if (before) replaced.push({ key, before });\n else (added[cfg.sourceLocale] ??= []).push(key);\n }\n\n const needed = Object.keys(source);\n for (const locale of cfg.locales) {\n if (locale === cfg.sourceLocale) continue;\n const catalog = (catalogs[locale] ??= emptyCatalog());\n for (const key of needed) {\n if (own(catalog, key) === undefined) {\n catalog[key] = '';\n (added[locale] ??= []).push(key);\n }\n }\n }\n return { added, replaced };\n}\n\n// the catalogs as a build ships them: the code's text wherever the code owns one, read-only\nexport function shippedCatalogs(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: MessageRegistry,\n // false: only keys the source catalog has, for the commands that run after extract\n options: { newKeys?: boolean } = {},\n): Catalogs {\n const source = Object.assign(emptyCatalog(), flatten(catalogs[cfg.sourceLocale] ?? {}));\n for (const [key, msg] of registry.messages()) {\n if (options.newKeys !== false || own(source, key) !== undefined) source[key] = msg.message;\n }\n return { ...catalogs, [cfg.sourceLocale]: source };\n}\n\n// drops keys no longer referenced\nexport function pruneCatalogs(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: MessageRegistry,\n): Record<string, string[]> {\n const removed: Record<string, string[]> = {};\n // a file the parser could not read still uses its keys, so pruning now deletes live translations\n if (registry.parseErrors().length > 0) return removed;\n const keep = new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);\n for (const locale of cfg.locales) {\n const catalog = catalogs[locale];\n if (!catalog) continue;\n for (const key of Object.keys(catalog)) {\n if (!keep.has(key)) {\n delete catalog[key];\n (removed[locale] ??= []).push(key);\n }\n }\n }\n return removed;\n}\n","import { parse, parseIcu, type MessageNode } from 'verbaly';\n\n// the gate reads every catalog on disk, so it always has the parser the runtime only opts into\nconst read = (message: string): MessageNode[] => parse(message, parseIcu);\n\nexport const PLURAL_CATEGORIES = new Set(['zero', 'one', 'two', 'few', 'many']);\nexport type IssueSeverity = 'error' | 'warning';\n\nexport interface StructureIssue {\n severity: IssueSeverity;\n message: string;\n}\n\ninterface VariantShape {\n selectors: string[];\n plural: boolean;\n ordinal: boolean;\n}\n\nconst EXACT = /^=\\d+$/;\n\n// param name → its plural/select block, when it has one; first block per name wins\nfunction shapes(message: string): Map<string, VariantShape> {\n const out = new Map<string, VariantShape>();\n walk(read(message), out);\n return out;\n}\n\nfunction walk(nodes: MessageNode[], out: Map<string, VariantShape>): void {\n for (const node of nodes) {\n if (node.kind !== 'param' || !node.variants) continue;\n const selectors = node.variants.map(([key]) => key);\n if (!out.has(node.name)) {\n out.set(node.name, {\n selectors,\n plural: selectors.some((key) => PLURAL_CATEGORIES.has(key)),\n ordinal: node.ordinal === true,\n });\n }\n for (const [, body] of node.variants) walk(body, out);\n }\n}\n\nfunction paramNames(message: string): string[] {\n const names = new Set<string>();\n collect(read(message), names);\n return [...names].sort();\n}\n\nfunction collect(nodes: MessageNode[], out: Set<string>): void {\n for (const node of nodes) {\n if (node.kind !== 'param') continue;\n out.add(node.name);\n if (node.variants) for (const [, body] of node.variants) collect(body, out);\n }\n}\n\nconst TAG = /<(\\/?)([a-zA-Z][\\w-]*)(\\/?)>/g;\n\n// markup is only what the message closes (</x>) or self-closes (<x/>): a lone <Enter> is prose\nfunction markupNames(message: string): Set<string> {\n const out = new Set<string>();\n for (const match of message.matchAll(TAG)) {\n if (match[1] || match[3]) out.add(match[2]!);\n }\n return out;\n}\n\nfunction tagTokens(message: string, markup: Set<string>): string[] {\n const out: string[] = [];\n for (const match of message.matchAll(TAG)) {\n if (markup.has(match[2]!)) out.push(`${match[1]}${match[2]}${match[3]}`);\n }\n return out.sort();\n}\n\n// items in a that are missing from b, counting duplicates\nfunction surplus(a: string[], b: string[]): string[] {\n const rest = [...b];\n const out: string[] = [];\n for (const item of a) {\n const at = rest.indexOf(item);\n if (at < 0) out.push(item);\n else rest.splice(at, 1);\n }\n return out;\n}\n\nfunction list(items: string[]): string {\n return items.length > 1\n ? `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`\n : items[0]!;\n}\n\n// a tagged template escapes its own braces, so a block written inside one ships as literal text\nconst ESCAPED_SYNTAX = /(?<!\\{)\\{\\{\\s*[\\w.]+\\s*[|:][^{}]*\\}\\}/;\n\n// the escaped slice of an extracted message, when the author meant a plural or format block\nexport function escapedSyntax(message: string): string | undefined {\n return ESCAPED_SYNTAX.exec(message)?.[0];\n}\n\n// one message on its own: defects that need no source to be visible\nexport function validateMessage(message: string, locale?: string): StructureIssue[] {\n const issues: StructureIssue[] = [];\n for (const [name, shape] of shapes(message)) {\n if (!shape.plural) continue; // a select block without 'other' is the author's design\n if (!shape.selectors.includes('other')) {\n issues.push({\n severity: 'error',\n message: `the plural block for {${name}} has no \"other\" case, so any count it does not list renders empty`,\n });\n continue;\n }\n if (!locale) continue;\n const missing = reachableCategories(locale, shape.ordinal).filter(\n (category) => category !== 'other' && !shape.selectors.includes(category),\n );\n if (missing.length > 0) {\n issues.push({\n severity: 'warning',\n message: `${locale} also needs the ${list(missing)} plural ${missing.length > 1 ? 'forms' : 'form'} for {${name}}`,\n });\n }\n }\n return issues;\n}\n\n// a translation against the source it must mirror\nexport function validatePair(source: string, translated: string): StructureIssue[] {\n const issues: StructureIssue[] = [];\n\n const lostParams = surplus(paramNames(source), paramNames(translated));\n const newParams = surplus(paramNames(translated), paramNames(source));\n if (lostParams.length > 0) {\n issues.push({\n severity: 'error',\n message: `${list(lostParams.map((name) => `{${name}}`))} ${lostParams.length > 1 ? 'are' : 'is'} missing, so ${lostParams.length > 1 ? 'their values never reach' : 'its value never reaches'} the text`,\n });\n }\n if (newParams.length > 0) {\n issues.push({\n severity: 'error',\n message: `${list(newParams.map((name) => `{${name}}`))} ${newParams.length > 1 ? 'are' : 'is'} not in the source message, so ${newParams.length > 1 ? 'they render' : 'it renders'} as literal text`,\n });\n }\n\n // one vocabulary for both sides: a tag the translation invents is still caught\n const markup = new Set([...markupNames(source), ...markupNames(translated)]);\n const lostTags = tagReport(surplus(tagTokens(source, markup), tagTokens(translated, markup)));\n const newTags = tagReport(surplus(tagTokens(translated, markup), tagTokens(source, markup)));\n if (lostTags.length > 0) {\n issues.push({\n severity: 'error',\n message: `${list(lostTags)} ${lostTags.length > 1 ? 'are' : 'is'} missing from the translation`,\n });\n }\n if (newTags.length > 0) {\n issues.push({\n severity: 'error',\n message: `${list(newTags)} ${newTags.length > 1 ? 'are' : 'is'} not in the source message`,\n });\n }\n\n const target = shapes(translated);\n for (const [name, shape] of shapes(source)) {\n const other = target.get(name);\n if (!other) {\n issues.push({\n severity: 'error',\n message: `the ${shape.plural ? 'plural' : 'select'} block for {${name}} was flattened into plain text`,\n });\n continue;\n }\n // 'other' is the catch-all: losing it renders empty (the plural case is validateMessage's)\n if (shape.selectors.includes('other') && !other.selectors.includes('other') && !other.plural) {\n issues.push({\n severity: 'error',\n message: `the \"other\" case for {${name}} is missing, so unlisted values render empty`,\n });\n }\n const lostExact = shape.selectors\n .filter((key) => EXACT.test(key))\n .filter((key) => !other.selectors.includes(key));\n if (lostExact.length > 0) {\n issues.push({\n severity: 'warning',\n message: `the ${list(lostExact)} ${lostExact.length > 1 ? 'cases' : 'case'} for {${name}} ${lostExact.length > 1 ? 'are' : 'is'} missing, so ${lostExact.length > 1 ? 'those counts' : 'that count'} falls back to \"other\"`,\n });\n }\n }\n\n return issues;\n}\n\n// one entry per tag name: a translator restores the pair, not a lone closing tag\nfunction tagReport(tokens: string[]): string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n for (const token of tokens) {\n const name = token.replaceAll('/', '');\n if (seen.has(name)) continue;\n seen.add(name);\n out.push(token.endsWith('/') ? `<${name}/>` : `<${name}>`);\n }\n return out;\n}\n\nconst COUNT_PROBE = 200; // the range a UI counter realistically reaches\nconst reachable = new Map<string, string[]>();\n\nfunction reachableCategories(locale: string, ordinal: boolean): string[] {\n const type = ordinal ? 'ordinal' : 'cardinal';\n // the escape, never the raw character: a literal NUL makes git treat the file as binary\n const cacheKey = `${locale}\\u0000${type}`;\n const hit = reachable.get(cacheKey);\n if (hit) return hit;\n\n let out: string[];\n try {\n // pt_BR formats as pt-BR at runtime, so its plurals are pt-BR's here too\n const rules = new Intl.PluralRules(locale.replace(/_/g, '-'), { type });\n const seen = new Set<string>();\n for (let n = 0; n <= COUNT_PROBE; n++) seen.add(rules.select(n));\n out = [...seen];\n } catch {\n out = []; // unknown tag: nothing is ever reported missing\n }\n reachable.set(cacheKey, out);\n return out;\n}\n","import { parse, parseIcu, type MessageNode } from 'verbaly';\nimport { PLURAL_CATEGORIES } from './validate';\n\nexport type ParamType = 'number' | 'string' | 'date' | 'unknown';\n\nconst NUMBER_FORMATS = new Set(['number', 'integer', 'percent', 'currency']);\nconst DATE_FORMATS = new Set(['date', 'time']);\n\nexport function collectParams(message: string): Map<string, Set<ParamType>> {\n const out = new Map<string, Set<ParamType>>();\n // with no parser an ICU message is one text node, so its params would be typed as none at all\n visit(parse(message, parseIcu), out);\n return out;\n}\n\nfunction visit(nodes: MessageNode[], out: Map<string, Set<ParamType>>): void {\n for (const node of nodes) {\n if (node.kind !== 'param') continue;\n const types = out.get(node.name) ?? new Set<ParamType>();\n out.set(node.name, types);\n\n if (node.variants) {\n for (const [key, body] of node.variants) {\n if (PLURAL_CATEGORIES.has(key) || /^=\\d+$/.test(key)) types.add('number');\n else if (key !== 'other') types.add('string');\n visit(body, out);\n }\n if (types.size === 0) types.add('string');\n } else if (node.format && NUMBER_FORMATS.has(node.format)) {\n types.add('number');\n } else if (node.format && DATE_FORMATS.has(node.format)) {\n types.add('date');\n } else {\n types.add('unknown');\n }\n }\n}\n\nexport function renderParamType(types: Set<ParamType>): string {\n if (types.has('unknown') || types.size === 0) return 'unknown';\n const members = new Set<string>();\n if (types.has('number')) members.add('number');\n if (types.has('string')) members.add('string');\n if (types.has('date')) for (const m of ['Date', 'number', 'string']) members.add(m);\n return [...members].join(' | ');\n}\n","import { readFileSync, writeFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { applyEdits, modify, parse, type FormattingOptions, type ParseError } from 'jsonc-parser';\nimport picomatch from 'picomatch';\n\nexport type IncludeState = 'present' | 'added' | 'missing' | 'no-tsconfig' | 'unreadable';\n\ninterface TsconfigShape {\n include?: unknown;\n files?: unknown;\n}\n\n// tsconfig.json as TypeScript reads it: comments and trailing commas are legal there\nfunction readTsconfig(root: string): { path: string; text: string; json: TsconfigShape } | string {\n const path = join(root, 'tsconfig.json');\n let text: string;\n try {\n text = readFileSync(path, 'utf8');\n } catch {\n return 'no-tsconfig';\n }\n const errors: ParseError[] = [];\n const json = parse(text, errors, { allowTrailingComma: true }) as unknown;\n if (errors.length > 0 || typeof json !== 'object' || json === null || Array.isArray(json)) {\n return 'unreadable';\n }\n return { path, text, json: json as TsconfigShape };\n}\n\n// as TypeScript matches an entry: a glob skips dot folders, and a bare folder means all inside it\nfunction covered(list: unknown, entry: string): boolean {\n if (!Array.isArray(list)) return false;\n return list.some((item) => {\n if (typeof item !== 'string') return false;\n const pattern = item.replace(/^\\.\\//, '').replace(/\\/+$/, '');\n return picomatch(pattern)(entry) || picomatch(`${pattern}/**/*`)(entry);\n });\n}\n\n// the indentation the file already uses, so the new line looks like the ones around it\nfunction formatting(text: string): FormattingOptions {\n const indent = /\\n([ \\t]+)\\S/.exec(text)?.[1] ?? ' ';\n return {\n insertSpaces: !indent.startsWith('\\t'),\n tabSize: indent.startsWith('\\t') ? 1 : indent.length,\n eol: text.includes('\\r\\n') ? '\\r\\n' : '\\n',\n };\n}\n\n// whether TypeScript reads the generated file: never true for a file outside the project\nexport function typesIncluded(root: string, file: string): IncludeState {\n const read = readTsconfig(root);\n if (typeof read === 'string') return read as IncludeState;\n const entry = relative(root, file).replaceAll('\\\\', '/');\n const { include, files } = read.json;\n if (covered(include, entry) || covered(files, entry)) return 'present';\n return 'missing';\n}\n\n// TypeScript never walks into a dot folder by itself: .verbaly/ needs a line, like .next/types\nexport function includeTypes(root: string, file: string): IncludeState {\n const read = readTsconfig(root);\n if (typeof read === 'string') return read as IncludeState;\n const entry = relative(root, file).replaceAll('\\\\', '/');\n const { include, files } = read.json;\n if (covered(include, entry) || covered(files, entry)) return 'present';\n\n const options = { formattingOptions: formatting(read.text) };\n // a files list with no include means include defaults to nothing, so the entry goes there\n const edits = Array.isArray(include)\n ? modify(read.text, ['include', -1], entry, { ...options, isArrayInsertion: true })\n : Array.isArray(files) && include === undefined\n ? modify(read.text, ['files', -1], entry, { ...options, isArrayInsertion: true })\n : modify(read.text, ['include'], ['**/*', entry], options);\n writeFileSync(read.path, applyEdits(read.text, edits));\n return 'added';\n}\n","const warned = new Set<string>();\n\n// one warn-once for the whole compiler: dedupe by static content, never by a value being edited\nexport function warnOnce(message: string, dedupeKey = message): void {\n if (warned.has(dedupeKey)) return;\n warned.add(dedupeKey);\n console.warn(`[verbaly] ${message}`);\n}\n\n// bundler paths only: the CLI reports its own run, so a file is never announced twice\nexport function warnParseError(file: string, message: string): void {\n warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);\n}\n","import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\nimport type { Catalog } from './catalog';\nimport type { ResolvedConfig } from './config';\nimport { withLineEndings } from './eol';\nimport { collectParams, renderParamType } from './params';\nimport { byCodeUnit } from './text';\nimport { includeTypes } from './tsconfig';\nimport { warnOnce } from './warn';\n\nexport const VIRTUAL_ID = 'virtual:verbaly';\n\n// the header every generated d.ts opens with: a file without it was written by a person\nexport const DTS_HEADER = '// generated by verbaly: do not edit';\n\nexport interface RuntimeModuleOptions {\n localeImport?: (locale: string) => string;\n extraExports?: string;\n icu?: boolean;\n relative?: boolean;\n inlineCatalog?: boolean;\n}\n\n// only under inlineCatalog: read the blob `verbaly render` left, and take the next page's own\nconst SLICE_HELPERS = `function readSlice(root, path) {\n const locale = readPath({ supported: locales, path });\n if (!locale || locale === sourceLocale) return undefined;\n const messages = inlineMessages(root);\n return messages ? { locale, messages } : undefined;\n}\n\nexport function adoptPage(options) {\n const slice = readSlice(options?.root, options?.path);\n if (slice) v.addMessages(slice.locale, slice.messages, { partial: true });\n return slice ? slice.locale : undefined;\n}\n\n`;\n\nexport function generateRuntimeModule(\n cfg: ResolvedConfig,\n options: RuntimeModuleOptions = {},\n): string {\n const importPath = options.localeImport ?? ((locale: string) => `${VIRTUAL_ID}/locale/${locale}`);\n const others = cfg.locales.filter((locale) => locale !== cfg.sourceLocale);\n const src = JSON.stringify(cfg.sourceLocale);\n const loaders = others\n .map((locale) => ` ${JSON.stringify(locale)}: () => import('${importPath(locale)}'),`)\n .join('\\n');\n\n // named in the import list only when a catalog uses them, so otherwise they tree-shake out\n const icu = options.icu ? ',\\n parseIcu' : '';\n const rel = options.relative ? ',\\n relativeFormatter' : '';\n const slice = options.inlineCatalog ? ',\\n inlineMessages' : '';\n const slices = options.inlineCatalog ? SLICE_HELPERS : '';\n\n return `import {\n createVerbaly,\n localeFromPath as readPath,\n localePath as writePath,\n switchLocale as runSwitch${icu}${rel}${slice},\n} from 'verbaly';\nimport source from '${importPath(cfg.sourceLocale)}';\n\nexport const sourceLocale = ${src};\nexport const locales = ${JSON.stringify(cfg.locales)};\nexport const routing = ${JSON.stringify(cfg.routing)};\n\n// bound to this project: the locale set, the source and the routing mode are never passed in\nexport function localePath(locale, options) {\n return writePath(locale, { ...options, supported: locales, sourceLocale, routing });\n}\n\nexport function localeFromPath(options) {\n return readPath({ ...options, supported: locales });\n}\n\n// identity: it exists so the compiler can see keys that live in a module instead of at a call site\nexport function defineKeys(keys) {\n return keys;\n}\n\n// the whole switch a language control needs, in either mode: catalog or navigation, then persistence\nexport function switchLocale(locale, options) {\n return runSwitch(v, locale, { supported: locales, sourceLocale, routing, ...options });\n}\n\nconst localeLoaders = {\n${loaders}\n};\n\n// raw catalog access: SSR integrations serialize it across the client boundary\nexport async function loadMessages(locale) {\n if (locale === ${src}) return source;\n // own entries only: a locale named constructor must be a miss, not the Object function\n const loader = Object.prototype.hasOwnProperty.call(localeLoaders, locale)\n ? localeLoaders[locale]\n : undefined;\n return loader ? (await loader()).default : {};\n}\n\n${slices}// per-request/per-instance factory (SSR): the singleton below is browser/SPA-only\nexport function createInstance(options) {${\n options.inlineCatalog ? '\\n const page = readSlice();' : ''\n }\n return createVerbaly({\n locale: ${options.inlineCatalog ? `page ? page.locale : ${src}` : src},\n fallback: ${src},\n messages: ${\n options.inlineCatalog\n ? `page ? { [${src}]: source, [page.locale]: page.messages } : { [${src}]: source }`\n : `{ [${src}]: source }`\n },\n loaders: localeLoaders,${options.inlineCatalog ? '\\n partial: page ? [page.locale] : undefined,' : ''}${options.icu ? '\\n icu: parseIcu,' : ''}\n ...options,${\n options.relative\n ? '\\n // merged, not spread over: passing your own formatters must not drop this one' +\n '\\n formatters: { relative: relativeFormatter, ...options?.formatters },'\n : ''\n }\n });\n}\n\n// the no-FOUC contract in one call: fresh instance + catalog awaited before render\nexport async function createRequestInstance(locale) {\n const instance = createInstance({ locale });\n await instance.loadLocale(locale);\n return instance;\n}\n\nconst v = createInstance();\n\nexport const verbaly = v;\nexport const t = v.t;\n\nexport function getLocale() {\n return v.locale;\n}\n\nexport function subscribe(listener) {\n return v.subscribe(listener);\n}\n\nexport async function setLocale(locale) {\n await v.loadLocale(locale);\n v.setLocale(locale);\n}\n${options.extraExports ?? ''}`;\n}\n\nexport function generateLocaleModule(catalog: Catalog): string {\n // \"__proto__\": in an object literal sets the prototype; computed, it stays a key like any other\n const json = JSON.stringify(catalog).replace(/([{,])\"__proto__\":/, '$1[\"__proto__\"]:');\n return `export default ${json};\\n`;\n}\n\nexport interface DtsOptions {\n inlineCatalog?: boolean;\n locales?: string[];\n}\n\nexport function generateDts(catalog: Catalog, options: DtsOptions = {}): string {\n const lines: string[] = [];\n const locales = options.locales?.length\n ? [...options.locales]\n .sort(byCodeUnit)\n .map((locale) => JSON.stringify(locale))\n .join(' | ')\n : 'string';\n for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => byCodeUnit(a, b))) {\n const params = collectParams(message);\n if (params.size === 0) {\n lines.push(` ${JSON.stringify(key)}: never;`);\n } else {\n const fields = [...params.entries()]\n .map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`)\n .join('; ');\n lines.push(` ${JSON.stringify(key)}: { ${fields} };`);\n }\n }\n\n return `${DTS_HEADER}\ndeclare module 'virtual:verbaly' {\n export interface VerbalyMessages {\n${lines.join('\\n')}\n }\n export type VerbalyKey = keyof VerbalyMessages & string;\n export type VerbalyLocale = ${locales};\n\n export type VerbalyKeyTree = VerbalyKey | { readonly [name: string]: VerbalyKeyTree };\n export function defineKeys<const T extends VerbalyKeyTree>(keys: T): T;\n\n export const verbaly: import('verbaly').Verbaly;\n\n export const sourceLocale: VerbalyLocale;\n export const locales: string[];\n export const routing: import('verbaly').Routing;\n export function localePath(\n locale: string,\n options?: { path?: string; base?: string },\n ): string;\n export function localeFromPath(options?: {\n path?: string;\n base?: string;\n }): string | undefined;\n export function loadMessages(locale: string): Promise<Record<string, string>>;${\n options.inlineCatalog\n ? '\\n export function adoptPage(options?: {' +\n '\\n root?: ParentNode;' +\n '\\n path?: string;' +\n '\\n }): string | undefined;'\n : ''\n }\n export function createInstance(\n options?: import('verbaly').VerbalyOptions,\n ): import('verbaly').Verbaly;\n export function createRequestInstance(locale: string): Promise<import('verbaly').Verbaly>;\n\n export function t<K extends VerbalyKey | TemplateStringsArray>(\n first: K,\n ...rest: K extends VerbalyKey\n ? [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]\n : unknown[]\n ): string;\n export namespace t {\n export function id(\n key: string,\n ): (strings: TemplateStringsArray, ...values: unknown[]) => string;\n }\n\n export function setLocale(locale: string): Promise<void>;\n export function switchLocale(\n locale: string,\n options?: Omit<\n import('verbaly').SwitchLocaleOptions,\n 'routing' | 'supported' | 'sourceLocale'\n >,\n ): Promise<void>;\n export function getLocale(): string;\n export function subscribe(listener: () => void): () => void;\n\n // nested, so it augments verbaly: at the top of a script it would replace the real module\n module 'verbaly' {\n interface Register {\n t: typeof t;\n locale: VerbalyLocale;\n }\n }\n}\n\ndeclare module 'virtual:verbaly/locale/*' {\n const messages: Record<string, string>;\n export default messages;\n}\n`;\n}\n\n// the d.ts a project gets: what the config says about it is passed the same way everywhere\nexport function projectDtsOptions(cfg: ResolvedConfig): DtsOptions {\n return { inlineCatalog: cfg.render.inlineCatalog === true, locales: cfg.locales };\n}\n\nexport interface DtsWrite {\n file: string;\n changed: boolean;\n}\n\n// unchanged writes are skipped: a rewritten d.ts churns the consumer's TS server\nexport function writeDts(\n cfg: ResolvedConfig,\n catalog: Catalog,\n file?: string | false,\n): DtsWrite | undefined {\n // the config decides unless a caller names a file: dts false means no file anywhere\n const target = file === undefined ? cfg.dts : file;\n if (target === false) return undefined;\n let existing: string | undefined;\n try {\n existing = readFileSync(target, 'utf8');\n } catch {\n // new file\n }\n const content = withLineEndings(generateDts(catalog, projectDtsOptions(cfg)), existing);\n const changed = existing !== content;\n if (changed) {\n mkdirSync(dirname(target), { recursive: true });\n writeFileSync(target, content);\n }\n removeRootDts(cfg, target);\n // .verbaly/ is a dot folder, and TypeScript only reads one that tsconfig names\n if (resolve(target).startsWith(resolve(cfg.root, '.verbaly') + sep)) {\n // generated and never committed: the .gitignore withVerbaly writes next to its modules\n const ignore = join(cfg.root, '.verbaly', '.gitignore');\n if (!existsSync(ignore)) writeFileSync(ignore, '*\\n');\n const state = includeTypes(cfg.root, target);\n const entry = relative(cfg.root, target).replaceAll('\\\\', '/');\n if (state === 'added') {\n warnOnce(`added \"${entry}\" to the include of tsconfig.json, so TypeScript reads the types`);\n } else if (state === 'unreadable') {\n warnOnce(`tsconfig.json could not be read, so add \"${entry}\" to its include yourself`);\n }\n }\n return { file: target, changed };\n}\n\n// the types moved out of the root: the old file would declare the same module a second time\nfunction removeRootDts(cfg: ResolvedConfig, target: string): void {\n const old = join(cfg.root, 'verbaly.d.ts');\n if (resolve(target) === resolve(old)) return;\n let head: string;\n try {\n head = readFileSync(old, 'utf8').slice(0, DTS_HEADER.length);\n } catch {\n return;\n }\n // a verbaly.d.ts someone wrote by hand is theirs\n if (head !== DTS_HEADER) return;\n rmSync(old);\n const moved = relative(cfg.root, target).replaceAll('\\\\', '/');\n warnOnce(\n `the types live in ${moved} now, so the verbaly.d.ts Verbaly wrote at the root was removed`,\n );\n}\n","import { relative } from 'node:path';\nimport type { TaggedMessage } from './analyze';\nimport type { ResolvedConfig } from './config';\nimport type { ReplacedText } from './extract';\nimport type { MessageRegistry } from './registry';\nimport type { OutdatedEntry } from './state';\nimport { counted, truncate } from './text';\nimport { escapedSyntax } from './validate';\n\n// where a text is written in the code: an absolute file, like every path check reports\nexport interface SourceSite {\n file: string;\n line?: number;\n message: string;\n}\n\nexport interface CollisionEntry {\n key: string;\n sites: SourceSite[];\n}\n\n// a source text the code wrote over; edited when the run knows a person changed the catalog\nexport interface ReplacedEntry {\n locale: string;\n key: string;\n before: string;\n site: SourceSite;\n edited?: boolean;\n}\n\nexport interface RenamedEntry {\n name: string;\n file: string;\n line?: number;\n}\n\nexport interface PositionalEntry {\n params: string[];\n site: SourceSite;\n}\n\nexport interface EscapedEntry {\n slice: string;\n site: SourceSite;\n}\n\nexport interface UnparsedEntry {\n file: string;\n message: string;\n}\n\n// what a scan finds that never fails a gate; every surface words it through formatFinding\nexport type Finding =\n | ({ kind: 'replaced' } & ReplacedEntry)\n | ({ kind: 'collision' } & CollisionEntry)\n | ({ kind: 'renamed' } & RenamedEntry)\n | ({ kind: 'positional' } & PositionalEntry)\n | ({ kind: 'escaped' } & EscapedEntry)\n | ({ kind: 'unparsed' } & UnparsedEntry)\n | ({ kind: 'outdated' } & OutdatedEntry);\n\nexport function siteOf(msg: TaggedMessage): SourceSite {\n return { file: msg.file, line: msg.line, message: msg.message };\n}\n\nexport function collisionEntries(registry: MessageRegistry): CollisionEntry[] {\n return registry.collisions().map(({ key, kept, dropped }) => ({\n key,\n sites: [kept, ...dropped].map(siteOf),\n }));\n}\n\n// one pass, a fixed order: the same project always reads as the same report\nexport function scanFindings(\n cfg: ResolvedConfig,\n registry: MessageRegistry,\n replaced: ReplacedText[] = [],\n): Finding[] {\n const messages = registry.messages();\n const out: Finding[] = [];\n for (const { key, before } of replaced) {\n const msg = messages.get(key);\n if (msg)\n out.push({ kind: 'replaced', locale: cfg.sourceLocale, key, before, site: siteOf(msg) });\n }\n for (const entry of collisionEntries(registry)) out.push({ kind: 'collision', ...entry });\n for (const { name, file, line } of registry.missed()) {\n out.push({ kind: 'renamed', name, file, line });\n }\n for (const msg of messages.values()) {\n // a translator who reads {_0} cannot know what goes there\n const params = msg.params.map((param) => param.name).filter((name) => /^_\\d+$/.test(name));\n if (params.length > 0) out.push({ kind: 'positional', params, site: siteOf(msg) });\n const slice = escapedSyntax(msg.message);\n if (slice) out.push({ kind: 'escaped', slice, site: siteOf(msg) });\n }\n for (const { file, message } of registry.parseErrors()) {\n out.push({ kind: 'unparsed', file, message });\n }\n return out;\n}\n\n// file:line, so the editor and the terminal can jump to where the text is written\nexport function sourcePlace(at: { file: string; line?: number }, root?: string): string {\n const file = root ? relative(root, at.file).replaceAll('\\\\', '/') : at.file;\n return at.line ? `${file}:${at.line}` : file;\n}\n\nfunction quoted(at: SourceSite, root?: string): string {\n return `\"${truncate(at.message, 40)}\" (${sourcePlace(at, root)})`;\n}\n\n// the one wording of a collision, shared by extract, check, doctor and both dev servers\nexport function formatCollision({ key, sites }: CollisionEntry, root?: string): string {\n const [kept, ...others] = sites as [SourceSite, ...SourceSite[]];\n const texts = new Set(sites.map((at) => at.message)).size;\n return (\n `${key}: one key with ${counted(texts, 'text')}, and every place shows ${quoted(kept, root)}, ` +\n `never ${others.map((at) => quoted(at, root)).join(' or ')}: give each text its own key`\n );\n}\n\n// the one wording of every finding; each surface adds its own prefix or indent\nexport function formatFinding(finding: Finding, root?: string): string {\n switch (finding.kind) {\n case 'collision':\n return formatCollision(finding, root);\n case 'replaced': {\n const place = sourcePlace(finding.site, root);\n return finding.edited\n ? `${finding.locale}.json: your edit of \"${finding.key}\" was replaced, its text lives in ${place}: change it there`\n : `${finding.locale}: ${finding.key} follows the code (${place}): \"${truncate(finding.site.message, 40)}\", was \"${truncate(finding.before, 40)}\"`;\n }\n case 'renamed':\n return `${sourcePlace(finding, root)}: ${finding.name}\\`…\\` is never extracted, so it stays in the source language: name it t`;\n case 'positional': {\n const names = finding.params.map((name) => `{${name}}`).join(', ');\n 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`;\n }\n case 'escaped':\n return `${sourcePlace(finding.site, root)}: ${finding.slice} renders as literal text, a tagged template has no params (use t(key, params) for a plural or format block, or pass a \\${…} value)`;\n case 'unparsed':\n return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;\n case 'outdated':\n return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \\`npx verbaly review --approve\\``;\n }\n}\n\n// keyed on what a finding is about, never on its text: a dev server re-runs per keystroke\nfunction findingId(finding: Finding): string {\n switch (finding.kind) {\n case 'collision':\n case 'replaced':\n return `${finding.kind}:${finding.key}`;\n case 'outdated':\n return `outdated:${finding.locale}:${finding.key}`;\n case 'renamed':\n return `renamed:${finding.file}:${finding.name}`;\n case 'positional':\n return `positional:${finding.site.file}:${finding.params.join(',')}`;\n case 'escaped':\n return `escaped:${finding.site.file}:${finding.slice}`;\n case 'unparsed':\n return `unparsed:${finding.file}`;\n }\n}\n\nexport interface DevReporter {\n // prints what is new in this channel since its last report, and forgets what went away\n report(channel: string, findings: Finding[]): void;\n}\n\n// once per finding, and again only after it went away and came back; a few at a time\nexport function createDevReporter(\n root: string,\n print: (line: string) => void = (line) => console.warn(`[verbaly] ${line}`),\n cap = 5,\n): DevReporter {\n const shown = new Map<string, Set<string>>();\n return {\n report(channel, findings) {\n const before = shown.get(channel) ?? new Set<string>();\n const now = new Set<string>();\n const fresh: Finding[] = [];\n for (const finding of findings) {\n const id = findingId(finding);\n if (now.has(id)) continue;\n now.add(id);\n if (!before.has(id)) fresh.push(finding);\n }\n shown.set(channel, now);\n for (const finding of fresh.slice(0, cap)) print(formatFinding(finding, root));\n if (fresh.length > cap)\n print(`and ${fresh.length - cap} more: \\`npx verbaly doctor\\` names them`);\n },\n };\n}\n","import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { flatten, type MessageTree } from 'verbaly';\nimport { catalogPath, emptyCatalog, own, type Catalog, type Catalogs } from './catalog';\nimport { targetLocales, type ResolvedConfig } from './config';\nimport { withLineEndings } from './eol';\nimport { stableKey } from './key';\nimport { byCodeUnit } from './text';\n\nexport const STATE_FILE = '.verbaly-state.json';\n// before 0.67.0 the sidecar held only the drafts, and a teammate on 0.66.0 still writes it\nconst LEGACY_DRAFTS_FILE = '.verbaly-drafts.json';\n\nexport type Drafts = Record<string, string[]>;\n\n// locale -> key -> \"<source>.<translation>\" fingerprints from when that translation was written\nexport type Fingerprints = Record<string, Record<string, string>>;\n\nexport interface State {\n drafts: Drafts;\n fingerprints: Fingerprints;\n}\n\nexport interface OutdatedEntry {\n locale: string;\n key: string;\n}\n\n// what a read-only path gets: the state, or nothing plus the reason it could not be read\nexport interface StateRead {\n state: State;\n problem?: string;\n}\n\n// a translation just written, and the source text it was written for when that is not today's\nexport interface WrittenTranslation {\n key: string;\n text: string;\n source?: string;\n}\n\nexport interface TranslationWrite {\n locale: string;\n entries: WrittenTranslation[];\n draft?: boolean;\n}\n\nfunction statePath(cfg: ResolvedConfig, file = STATE_FILE): string {\n return join(cfg.dir, file);\n}\n\nexport function loadState(cfg: ResolvedConfig): State {\n const current = readJson(statePath(cfg));\n if (current !== undefined && !isObject(current)) throw corrupt(statePath(cfg));\n const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));\n if (legacy !== undefined && !isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));\n const state: State = isObject(current)\n ? { drafts: readDrafts(current.drafts), fingerprints: readFingerprints(current.fingerprints) }\n : { drafts: {}, fingerprints: {} };\n // drafts the old file still lists join the new ones, and the next save removes that file\n if (legacy !== undefined) {\n for (const [locale, keys] of Object.entries(readDrafts(legacy))) {\n markDrafts(state.drafts, locale, keys);\n }\n }\n return state;\n}\n\n// read-only paths go on without the state: it only feeds warnings, never a gate they run\nexport function readState(cfg: ResolvedConfig): StateRead {\n try {\n return { state: loadState(cfg) };\n } catch (error) {\n const problem = (error as Error).message.replace(/^\\[verbaly\\] /, '');\n return { state: { drafts: {}, fingerprints: {} }, problem };\n }\n}\n\n// content-compared like a catalog, and gone when there is nothing left to remember\nexport function saveState(cfg: ResolvedConfig, state: State): void {\n const fresh = serializeState(state);\n const path = statePath(cfg);\n const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);\n if (fresh === undefined) {\n rmSync(path, { force: true });\n rmSync(legacy, { force: true });\n return;\n }\n let existing: string | undefined;\n try {\n existing = readFileSync(path, 'utf8');\n } catch {\n mkdirSync(cfg.dir, { recursive: true });\n }\n const serialized = withLineEndings(fresh, existing);\n if (existing !== serialized) writeFileSync(path, serialized);\n if (existsSync(legacy)) rmSync(legacy);\n}\n\n// the state follows the catalogs it is shown; a locale whose catalog was not read stays as it was\nexport function updateState(cfg: ResolvedConfig, catalogs: Catalogs): State {\n const next = refreshState(cfg, catalogs, loadState(cfg));\n saveState(cfg, next);\n return next;\n}\n\nfunction refreshState(cfg: ResolvedConfig, catalogs: Catalogs, previous: State): State {\n const flat = flatCatalogs(catalogs);\n const source = flat[cfg.sourceLocale] ?? {};\n // a narrowed --locales run, or a catalog missing mid-checkout, must never erase what it held\n const shown = new Set(\n targetLocales(cfg).filter(\n (locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale)),\n ),\n );\n const drafts: Drafts = {};\n for (const [locale, keys] of Object.entries(previous.drafts)) {\n if (!shown.has(locale)) {\n drafts[locale] = keys;\n continue;\n }\n // a draft counts only while its translation is present: a pruned key is missing, not a draft\n const live = keys.filter((key) => own(flat[locale]!, key));\n if (live.length) drafts[locale] = live;\n }\n const fingerprints: Fingerprints = {};\n for (const [locale, stamps] of Object.entries(previous.fingerprints)) {\n if (!shown.has(locale)) fingerprints[locale] = stamps;\n }\n for (const locale of shown) {\n const stamps = refreshStamps(source, flat[locale]!, previous.fingerprints[locale] ?? {});\n if (Object.keys(stamps).length) fingerprints[locale] = stamps;\n }\n return { drafts, fingerprints };\n}\n\n// a stamp lives as long as its translation: kept while the translation is unchanged\nfunction refreshStamps(\n source: Catalog,\n catalog: Catalog,\n before: Record<string, string>,\n): Record<string, string> {\n const after: Record<string, string> = emptyCatalog();\n for (const key of new Set([...Object.keys(before), ...Object.keys(source)])) {\n const translated = own(catalog, key);\n if (!translated) continue;\n const was = own(before, key);\n if (was !== undefined && translationOf(was) === fingerprint(translated)) {\n after[key] = was;\n continue;\n }\n const text = own(source, key);\n // a new or edited translation was written for the source as it reads now\n if (text && tracked(key, text)) after[key] = stamp(text, translated);\n // edited while its source is empty: the old stamp waits until there is a source again\n else if (was !== undefined) after[key] = was;\n }\n return after;\n}\n\n// a translation written now was written for a known source: stamped and flagged in one save\nexport function recordTranslations(\n cfg: ResolvedConfig,\n source: Catalog,\n writes: TranslationWrite[],\n): State {\n const state = loadState(cfg);\n for (const { locale, entries, draft } of writes) {\n if (entries.length === 0) continue;\n const stamps = (state.fingerprints[locale] ??= emptyCatalog());\n for (const entry of entries) {\n const from = entry.source || own(source, entry.key);\n if (from && entry.text && tracked(entry.key, from)) {\n stamps[entry.key] = stamp(from, entry.text);\n }\n }\n const keys = entries.map((entry) => entry.key);\n if (draft === true) markDrafts(state.drafts, locale, keys);\n else if (draft === false) clearDrafts(state.drafts, locale, keys);\n }\n saveState(cfg, state);\n return state;\n}\n\n// a draft counts only while its translation is present: a pruned key is missing, not a draft\nexport function effectiveDrafts(drafts: Drafts, catalogs: Catalogs): Drafts {\n const out: Drafts = {};\n for (const [locale, keys] of Object.entries(drafts)) {\n const catalog = catalogs[locale] ?? {};\n const live = keys.filter((key) => own(catalog, key));\n if (live.length) out[locale] = live;\n }\n return out;\n}\n\nexport function markDrafts(drafts: Drafts, locale: string, keys: string[]): void {\n if (!keys.length) return;\n drafts[locale] = [...new Set([...(drafts[locale] ?? []), ...keys])];\n}\n\n// clears specific keys, or the whole locale when keys is omitted (approve everything)\nexport function clearDrafts(drafts: Drafts, locale: string, keys?: string[]): void {\n if (!drafts[locale]) return;\n if (!keys) {\n delete drafts[locale];\n return;\n }\n const drop = new Set(keys);\n drafts[locale] = drafts[locale].filter((key) => !drop.has(key));\n if (!drafts[locale].length) delete drafts[locale];\n}\n\nexport function fingerprint(text: string): string {\n return stableKey(text);\n}\n\n// a hash key is its own text: a new text is a new key, so its translation can never be stale\nfunction tracked(key: string, text: string): boolean {\n return stableKey(text) !== key;\n}\n\nfunction stamp(source: string, translated: string): string {\n return `${fingerprint(source)}.${fingerprint(translated)}`;\n}\n\nexport function outdatedTranslations(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n fingerprints: Fingerprints,\n): OutdatedEntry[] {\n const source = catalogs[cfg.sourceLocale] ?? {};\n const out: OutdatedEntry[] = [];\n for (const locale of targetLocales(cfg)) {\n const catalog = catalogs[locale] ?? {};\n for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {\n const text = own(source, key);\n const translated = own(catalog, key);\n if (!text || !translated) continue;\n // edited since it was stamped: whoever touched it last wrote it against this source\n if (translationOf(was) !== fingerprint(translated)) continue;\n if (sourceOf(was) !== fingerprint(text)) out.push({ locale, key });\n }\n }\n // code unit order, the one the catalogs use: localeCompare differs from machine to machine\n return out.sort((a, b) => byCodeUnit(a.locale, b.locale) || byCodeUnit(a.key, b.key));\n}\n\n// a person read it against the new source and kept it: stamp it as written for that source\nexport function acceptOutdated(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n fingerprints: Fingerprints,\n entries: OutdatedEntry[],\n): void {\n const source = catalogs[cfg.sourceLocale] ?? {};\n for (const { locale, key } of entries) {\n const text = own(source, key);\n const translated = own(catalogs[locale] ?? {}, key);\n if (!text || !translated) continue;\n (fingerprints[locale] ??= emptyCatalog())[key] = stamp(text, translated);\n }\n}\n\nfunction sourceOf(stamped: string): string {\n return stamped.slice(0, stamped.indexOf('.'));\n}\n\nfunction translationOf(stamped: string): string {\n return stamped.slice(stamped.indexOf('.') + 1);\n}\n\n// a caller may hand nested groups, and every key here is the dotted one t() reads\nfunction flatCatalogs(catalogs: Catalogs): Catalogs {\n const out: Catalogs = {};\n for (const [locale, catalog] of Object.entries(catalogs)) {\n out[locale] = flatten(catalog as unknown as MessageTree);\n }\n return out;\n}\n\nfunction serializeState(state: State): string | undefined {\n const drafts: Drafts = {};\n for (const locale of Object.keys(state.drafts).sort()) {\n const keys = [...new Set(state.drafts[locale])].sort();\n if (keys.length) drafts[locale] = keys;\n }\n const fingerprints: Fingerprints = {};\n for (const locale of Object.keys(state.fingerprints).sort()) {\n const entries = state.fingerprints[locale] ?? {};\n const keys = Object.keys(entries).sort();\n if (!keys.length) continue;\n fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]!]));\n }\n const out: Partial<State> = {};\n if (Object.keys(drafts).length) out.drafts = drafts;\n if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;\n if (!out.drafts && !out.fingerprints) return undefined;\n return JSON.stringify(out, null, 2) + '\\n';\n}\n\n// a corrupt sidecar throws: read as empty, the next save would erase every draft it held\nfunction readJson(path: string): unknown {\n let content: string;\n try {\n content = readFileSync(path, 'utf8');\n } catch {\n return undefined;\n }\n try {\n return JSON.parse(content.charCodeAt(0) === 0xfeff ? content.slice(1) : content) as unknown;\n } catch (error) {\n throw corrupt(path, error);\n }\n}\n\n// deleting it is the one fix that is not safe: every draft it listed would read as reviewed\nfunction corrupt(path: string, cause?: unknown): Error {\n return new Error(\n `[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`,\n { cause },\n );\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction readDrafts(value: unknown): Drafts {\n const out: Drafts = {};\n if (!isObject(value)) return out;\n for (const [locale, keys] of Object.entries(value)) {\n if (Array.isArray(keys)) out[locale] = keys.filter((key): key is string => typeof key === 'string');\n }\n return out;\n}\n\nfunction readFingerprints(value: unknown): Fingerprints {\n const out: Fingerprints = {};\n if (!isObject(value)) return out;\n for (const [locale, entries] of Object.entries(value)) {\n if (!isObject(entries)) continue;\n const kept: Record<string, string> = emptyCatalog();\n for (const [key, stamped] of Object.entries(entries)) {\n if (typeof stamped === 'string' && stamped.includes('.')) kept[key] = stamped;\n }\n out[locale] = kept;\n }\n return out;\n}\n","import { readFileSync } from 'node:fs';\nimport { loadCatalogs, own, writeCatalog, type Catalogs } from './catalog';\nimport { writeDts } from './codegen';\nimport type { ResolvedConfig } from './config';\nimport { extractProject, pruneCatalogs, syncCatalogs, type ReplacedText } from './extract';\nimport { scanFindings, type Finding } from './findings';\nimport type { MessageRegistry } from './registry';\nimport { analyzeFile } from './sfc';\nimport { updateState, type State } from './state';\n\n// The one way the code reaches the catalogs: scan, prune, sync, write, keep the state in step\nexport interface SyncProjectOptions {\n prune?: boolean;\n dryRun?: boolean;\n registry?: MessageRegistry;\n catalogs?: Catalogs;\n confirm?: boolean;\n write?: 'all' | 'changed';\n}\n\nexport interface SyncProjectResult {\n registry: MessageRegistry;\n catalogs: Catalogs;\n added: Record<string, string[]>;\n replaced: ReplacedText[];\n pruned: Record<string, string[]>;\n pruneBlocked: boolean;\n findings: Finding[];\n written: Record<string, string>;\n state?: State;\n stateProblem?: string;\n}\n\n// the one way the code reaches the catalogs: scan, prune, sync, write, keep the state in step\nexport async function syncProject(\n cfg: ResolvedConfig,\n options: SyncProjectOptions = {},\n): Promise<SyncProjectResult> {\n const registry = options.registry ?? (await extractProject(cfg));\n const catalogs = options.catalogs ?? loadCatalogs(cfg);\n if (options.confirm) confirmFromDisk(cfg, catalogs, registry);\n const pruneBlocked = options.prune === true && registry.parseErrors().length > 0;\n const pruned = options.prune ? pruneCatalogs(cfg, catalogs, registry) : {};\n const { added, replaced } = syncCatalogs(cfg, catalogs, registry);\n const result: SyncProjectResult = {\n registry,\n catalogs,\n added,\n replaced,\n pruned,\n pruneBlocked,\n findings: scanFindings(cfg, registry, replaced),\n written: {},\n };\n if (options.dryRun) return result;\n\n const changed = new Set([...Object.keys(added), ...Object.keys(pruned)]);\n if (replaced.length > 0) changed.add(cfg.sourceLocale);\n for (const locale of cfg.locales) {\n if (options.write === 'changed' && !changed.has(locale)) continue;\n result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});\n }\n writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});\n try {\n // a pruned key takes its draft along, and an edited source text marks its translations\n result.state = updateState(cfg, catalogs);\n } catch (error) {\n result.stateProblem = (error as Error).message.replace(/^\\[verbaly\\] /, '');\n }\n return result;\n}\n\n// a file can change on disk unseen by a registry built over time: a checkout, another terminal\nfunction confirmFromDisk(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry): void {\n const source = catalogs[cfg.sourceLocale] ?? {};\n const stale = new Set<string>();\n for (const [key, msg] of registry.messages()) {\n if (own(source, key) !== msg.message) stale.add(msg.file);\n }\n for (const file of stale) {\n let code: string;\n try {\n code = readFileSync(file, 'utf8');\n } catch {\n registry.remove(file);\n continue;\n }\n registry.update(file, analyzeFile(code, file));\n }\n}\n","// Intl is the one reader that decides whether a string is a locale tag, so it answers here too\nexport function isLocaleTag(tag: string): boolean {\n try {\n Intl.getCanonicalLocales(tag);\n return true;\n } catch {\n return false;\n }\n}\n\n// pt_BR is how gettext, Java and many backends write pt-BR: the one misspelling with a sure fix\nexport function suggestTag(tag: string): string | undefined {\n const near = tag.replace(/_/g, '-');\n return near !== tag && isLocaleTag(near) ? near : undefined;\n}\n\n// the project's own spelling of a tag written another way: pt_BR and PT-br both mean pt-BR\nexport function projectLocale(tag: string, locales: string[]): string | undefined {\n if (locales.includes(tag)) return tag;\n const plain = (value: string): string => value.replace(/_/g, '-').toLowerCase();\n return locales.find((locale) => plain(locale) === plain(tag));\n}\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { findConfigFile, loadConfigFile } from './config';\nimport { detectHost, installCommand, type Host } from './host';\nimport { isLocaleTag, suggestTag } from './tag';\n\nexport type { Host };\n\nexport interface InitOptions {\n root?: string;\n dir?: string;\n sourceLocale?: string;\n locales?: string[];\n}\n\nexport interface InitResult {\n created: string[];\n skipped: string[];\n host: Host | undefined;\n configFile: string;\n next: string[];\n renamed: { from: string; to: string }[];\n refused: string[];\n}\n\n// a package manager links a bin for a direct dependency only, and ours is usually transitive\nexport function cliReachable(root: string): boolean {\n const bin = join(root, 'node_modules', '.bin');\n return existsSync(join(bin, 'verbaly')) || existsSync(join(bin, 'verbaly.CMD'));\n}\n\nexport const CLI_INSTALL_FIX =\n 'add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves';\n\nfunction configSource(options: InitOptions, typescript: boolean): string {\n const fields = [` sourceLocale: '${options.sourceLocale ?? 'en'}',`];\n if (options.locales?.length) {\n fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(', ')}],`);\n }\n if (options.dir) fields.push(` dir: '${options.dir}',`);\n const body = `export default {\\n${fields.join('\\n')}\\n}`;\n if (typescript) {\n return `import type { VerbalyConfig } from '@verbaly/compiler';\\n\\n${body} satisfies VerbalyConfig;\\n`;\n }\n return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\\n${body};\\n`;\n}\n\nexport async function init(input: InitOptions = {}): Promise<InitResult> {\n const root = input.root ?? process.cwd();\n const created: string[] = [];\n const skipped: string[] = [];\n const renamed: InitResult['renamed'] = [];\n const refused: string[] = [];\n\n // only what was typed is corrected: a locale in a config file is the author's, doctor says so\n const typed = input.locales?.flatMap((locale) => {\n if (isLocaleTag(locale)) return [locale];\n const near = suggestTag(locale);\n if (near) renamed.push({ from: locale, to: near });\n else refused.push(locale);\n return near ? [near] : [];\n });\n // pt_BR,pt-BR is one locale once written right, and the config must not list it twice\n const locales = typed && [...new Set(typed)];\n let sourceLocale = input.sourceLocale;\n if (sourceLocale !== undefined && !isLocaleTag(sourceLocale)) {\n const near = suggestTag(sourceLocale);\n if (!near) {\n throw new Error(\n `[verbaly] \"${sourceLocale}\" is not a locale tag: pass --source with one like en or pt-BR`,\n );\n }\n renamed.push({ from: sourceLocale, to: near });\n sourceLocale = near;\n }\n const options: InitOptions = { ...input, locales, sourceLocale };\n\n const existing = findConfigFile(root);\n const typescript = existsSync(join(root, 'tsconfig.json'));\n const configFile = existing ?? (typescript ? 'verbaly.config.ts' : 'verbaly.config.mjs');\n if (existing) {\n skipped.push(existing);\n } else {\n writeFileSync(join(root, configFile), configSource(options, typescript));\n created.push(configFile);\n }\n\n // a config already answers where the catalogs go: guessing again scaffolds a second set\n const fromFile = existing ? await loadConfigFile(root) : {};\n const scaffold: InitOptions = {\n dir: options.dir ?? fromFile.dir,\n sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,\n locales: options.locales ?? fromFile.locales,\n };\n\n const dir = join(root, scaffold.dir ?? 'locales');\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n for (const locale of new Set([scaffold.sourceLocale ?? 'en', ...(scaffold.locales ?? [])])) {\n const file = join(dir, `${locale}.json`);\n const label = relative(root, file).replaceAll('\\\\', '/');\n if (existsSync(file)) {\n skipped.push(label);\n } else {\n writeFileSync(file, '{}\\n');\n created.push(label);\n }\n }\n\n const host = detectHost(root);\n // the line its README teaches, in the project's own package manager\n const next = host\n ? [installCommand(root, host.install), host.wire]\n : ['run \"verbaly extract\" after writing your first t`…` message'];\n\n return { created, skipped, host: host?.name, configFile, next, renamed, refused };\n}\n","import { relative } from 'node:path';\nimport { flatten, type MessageTree } from 'verbaly';\nimport { catalogPath, type Catalog, type Catalogs } from './catalog';\nimport type { ResolvedConfig } from './config';\nimport { shippedCatalogs } from './extract';\nimport {\n collisionEntries,\n formatFinding,\n siteOf,\n sourcePlace,\n type CollisionEntry,\n type SourceSite,\n} from './findings';\nimport { CLI_INSTALL_FIX } from './init';\nimport type { MessageRegistry } from './registry';\nimport { outdatedTranslations, type Fingerprints, type OutdatedEntry } from './state';\nimport { counted, truncate } from './text';\nimport { validateMessage, validatePair, type IssueSeverity, type StructureIssue } from './validate';\n\nexport interface MissingEntry {\n locale: string;\n key: string;\n source?: string;\n}\n\nexport interface UnknownEntry {\n key: string;\n files: string[];\n}\n\nexport interface BrokenEntry {\n locale: string;\n key: string;\n severity: IssueSeverity;\n issue: string;\n}\n\nexport interface ExtraEntry {\n locale: string;\n key: string;\n files: string[];\n}\n\nexport interface DivergentEntry {\n key: string;\n catalog: string;\n code: SourceSite;\n}\n\nexport type { CollisionEntry, SourceSite } from './findings';\nexport type { OutdatedEntry } from './state';\n\nexport interface CheckResult {\n ok: boolean;\n missing: MissingEntry[];\n unknown: UnknownEntry[];\n broken: BrokenEntry[];\n extra: ExtraEntry[];\n collisions: CollisionEntry[];\n divergent: DivergentEntry[];\n outdated: OutdatedEntry[];\n}\n\nexport function gatePasses(result: Pick<CheckResult, 'missing' | 'unknown' | 'broken'>): boolean {\n return (\n result.missing.length === 0 &&\n result.unknown.length === 0 &&\n !result.broken.some((entry) => entry.severity === 'error')\n );\n}\n\n// every warning list, counted once: the build line and doctor say the same number\nexport function warningCount(result: CheckResult): number {\n return (\n result.broken.filter((entry) => entry.severity === 'warning').length +\n result.extra.length +\n result.collisions.length +\n result.divergent.length +\n result.outdated.length\n );\n}\n\nexport function check(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: MessageRegistry,\n fingerprints: Fingerprints = {},\n): CheckResult {\n const extracted = registry.messages();\n\n // one flat view per locale: the shape t() sees, so nested catalogs compare leaf by leaf\n const flat: Record<string, Catalog> = {};\n for (const locale of cfg.locales) {\n flat[locale] = flatten((catalogs[locale] ?? {}) as MessageTree);\n }\n const source = flat[cfg.sourceLocale] ?? {};\n // the code's text is the one that ships, so every translation is read against it\n const shipped = shippedCatalogs(cfg, flat, registry);\n const sourceText = shipped[cfg.sourceLocale]!;\n\n const used = registry.usedKeys();\n const unknown: UnknownEntry[] = [];\n // strict: a key only spelled in backticks never failed the gate, and it does not start to here\n for (const [key, files] of registry.usedKeys(true)) {\n const known =\n extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== undefined);\n if (!known) unknown.push({ key, files });\n }\n\n const needed = new Set<string>([...extracted.keys(), ...Object.keys(source)]);\n\n const missing: MissingEntry[] = [];\n for (const key of extracted.keys()) {\n if (!source[key]) {\n missing.push({ locale: cfg.sourceLocale, key, source: extracted.get(key)?.message });\n }\n }\n for (const locale of cfg.locales) {\n if (locale === cfg.sourceLocale) continue;\n for (const key of needed) {\n if (!flat[locale]?.[key]) {\n missing.push({ locale, key, source: source[key] ?? extracted.get(key)?.message });\n }\n }\n }\n\n // presence is not correctness: a translation can be there and still render wrong\n const broken: BrokenEntry[] = [];\n const add = (locale: string, key: string, issues: StructureIssue[]): void => {\n for (const issue of issues) {\n broken.push({ locale, key, severity: issue.severity, issue: issue.message });\n }\n };\n\n const divergent: DivergentEntry[] = [];\n for (const [key, entry] of extracted) {\n const written = source[key];\n if (written && written !== entry.message) {\n divergent.push({ key, catalog: written, code: siteOf(entry) });\n }\n }\n for (const [key, text] of Object.entries(sourceText)) {\n add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));\n }\n for (const locale of cfg.locales) {\n if (locale === cfg.sourceLocale) continue;\n for (const [key, translated] of Object.entries(flat[locale] ?? {})) {\n if (!translated) continue; // '' is untranslated, already reported as missing\n add(locale, key, validateMessage(translated, locale));\n const text = sourceText[key];\n if (text) add(locale, key, validatePair(text, translated));\n }\n }\n\n // dead weight in that language's download, or, when the code reads it, the raw key in the source\n const extra: ExtraEntry[] = [];\n for (const locale of cfg.locales) {\n if (locale === cfg.sourceLocale) continue;\n for (const key of Object.keys(flat[locale] ?? {})) {\n if (source[key] !== undefined || extracted.has(key)) continue;\n extra.push({ locale, key, files: used.get(key) ?? [] });\n }\n }\n\n return {\n ok: gatePasses({ missing, unknown, broken }),\n missing,\n unknown,\n broken,\n extra,\n collisions: collisionEntries(registry),\n divergent,\n outdated: outdatedTranslations(cfg, shipped, fingerprints),\n };\n}\n\n// root makes the paths readable: an absolute path is noise in the one message people are stuck on\nexport function formatCheckResult(result: CheckResult, root?: string): string {\n const show = (file: string) => (root ? relative(root, file).replaceAll('\\\\', '/') : file);\n const lines: string[] = [];\n if (result.missing.length > 0) {\n lines.push('missing translations:');\n for (const entry of result.missing) {\n const hint = entry.source ? `: \"${truncate(entry.source, 40)}\"` : '';\n lines.push(` [${entry.locale}] ${entry.key}${hint}`);\n }\n }\n if (result.unknown.length > 0) {\n lines.push('unknown keys (not in any catalog):');\n for (const entry of result.unknown) {\n lines.push(` ${entry.key} (used in ${entry.files.map(show).join(', ')})`);\n }\n }\n const errors = result.broken.filter((entry) => entry.severity === 'error');\n if (errors.length > 0) {\n lines.push('broken translations:');\n for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);\n }\n return lines.join('\\n');\n}\n\n// what to do about each kind of failure: extract only fixes one of the three\nexport function checkNextSteps(result: CheckResult, cliReachable = true): string {\n const steps: string[] = [];\n if (result.missing.length > 0) {\n steps.push(\n 'missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)',\n );\n }\n if (result.unknown.length > 0) {\n steps.push(\n 'unknown keys: the key used in the code is in no catalog, fix the key or run `npx verbaly extract`',\n );\n }\n if (result.broken.some((entry) => entry.severity === 'error')) {\n steps.push(\n 'broken: a translation has to keep the params, tags and plural cases of its source message',\n );\n }\n // the gate prints from inside a build, where the command it just named may not exist at all\n if (steps.length > 0 && !cliReachable) {\n steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);\n }\n return steps.join('\\n');\n}\n\nexport interface CheckReportOptions {\n // check --outdated fails on them, so they are printed with the failures, not as warnings\n outdatedFails?: boolean;\n}\n\n// warnings never fail the gate, so they print on their own\nexport function formatCheckWarnings(\n result: CheckResult,\n root?: string,\n options: CheckReportOptions = {},\n): string {\n const lines = result.broken\n .filter((entry) => entry.severity === 'warning')\n .map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);\n for (const entry of result.extra) {\n lines.push(\n entry.files.length > 0\n ? ` [${entry.locale}] ${entry.key}: only this translation has it, so the source language shows the key itself`\n : ` [${entry.locale}] ${entry.key}: only this translation has it, and no code reads it`,\n );\n }\n for (const entry of result.collisions) {\n lines.push(` ${formatFinding({ kind: 'collision', ...entry }, root)}`);\n }\n for (const { key, catalog, code } of result.divergent) {\n lines.push(\n ` ${key}: the source catalog says \"${truncate(catalog, 40)}\" and the code says ` +\n `\"${truncate(code.message, 40)}\" (${sourcePlace(code, root)}): ` +\n 'the code wins, so edit the text there (extract writes it into the catalog)',\n );\n }\n if (!options.outdatedFails) {\n for (const entry of result.outdated) {\n lines.push(` ${formatFinding({ kind: 'outdated', ...entry }, root)}`);\n }\n }\n return lines.join('\\n');\n}\n\n// GitHub workflow commands: every failure becomes a clickable ::error annotation on the PR\nexport function githubCheckAnnotations(\n result: CheckResult,\n registry: MessageRegistry,\n cfg: ResolvedConfig,\n options: CheckReportOptions = {},\n): string[] {\n const messages = registry.messages();\n const rel = (file: string): string =>\n escapeProperty(relative(cfg.root, file).replaceAll('\\\\', '/'));\n const at = (file: string, line: number | undefined): string =>\n `file=${rel(file)}${line ? `,line=${line}` : ''}`;\n\n const lines: string[] = [];\n\n // one annotation per key, locales grouped: N locales must not bury the PR in N copies\n const byKey = new Map<string, MissingEntry & { locales: string[] }>();\n for (const entry of result.missing) {\n const grouped = byKey.get(entry.key);\n if (grouped) grouped.locales.push(entry.locale);\n else byKey.set(entry.key, { ...entry, locales: [entry.locale] });\n }\n\n for (const entry of byKey.values()) {\n const origin = messages.get(entry.key);\n const hint = entry.source ? `: \"${truncate(entry.source, 60)}\"` : '';\n const text = escapeData(`missing [${entry.locales.join(', ')}] ${entry.key}${hint}`);\n if (origin) {\n lines.push(`::error ${at(origin.file, origin.line)}::${text}`);\n } else {\n lines.push(`::error::${text}`);\n }\n }\n\n for (const entry of result.unknown) {\n const text = escapeData(`unknown key \"${entry.key}\" (not in any catalog)`);\n const file = entry.files[0];\n lines.push(file ? `::error file=${rel(file)}::${text}` : `::error::${text}`);\n }\n\n // a broken translation points at the source line that wrote the message\n for (const entry of result.broken) {\n const origin = messages.get(entry.key);\n const text = escapeData(`[${entry.locale}] ${entry.key}: ${entry.issue}`);\n const command = entry.severity === 'error' ? 'error' : 'warning';\n if (!origin) {\n lines.push(`::${command}::${text}`);\n continue;\n }\n lines.push(`::${command} ${at(origin.file, origin.line)}::${text}`);\n }\n\n for (const entry of result.extra) {\n const text = escapeData(`[${entry.locale}] ${entry.key}: only this translation has it`);\n const file = entry.files[0];\n lines.push(file ? `::warning file=${rel(file)}::${text}` : `::warning::${text}`);\n }\n\n // one per place a colliding text is written, so the PR shows every one of them\n for (const { key, sites } of result.collisions) {\n const texts = new Set(sites.map((place) => place.message)).size;\n const text = escapeData(\n `\"${key}\" has ${counted(texts, 'text')}, and every place shows the first one`,\n );\n for (const place of sites) lines.push(`::warning ${at(place.file, place.line)}::${text}`);\n }\n for (const { key, code } of result.divergent) {\n const text = escapeData(`\"${key}\": the source catalog has another text, the code's one ships`);\n lines.push(`::warning ${at(code.file, code.line)}::${text}`);\n }\n // the translation lives in its catalog, and under --outdated it is what fails the job\n const outdated = options.outdatedFails ? 'error' : 'warning';\n for (const { locale, key } of result.outdated) {\n const text = escapeData(`[${locale}] ${key}: translated from an older source text`);\n lines.push(`::${outdated} file=${rel(catalogPath(cfg, locale))}::${text}`);\n }\n return lines;\n}\n\nfunction escapeData(text: string): string {\n return text.replaceAll('%', '%25').replaceAll('\\r', '%0D').replaceAll('\\n', '%0A');\n}\n\nfunction escapeProperty(text: string): string {\n return escapeData(text).replaceAll(':', '%3A').replaceAll(',', '%2C');\n}\n","import MagicString from 'magic-string';\nimport type { Analysis } from './analyze';\nimport { analyzeFile } from './sfc';\nimport { warnParseError } from './warn';\n\nexport interface TransformResult {\n code: string;\n map: ReturnType<MagicString['generateMap']>;\n}\n\nfunction quote(text: string, single: boolean | undefined): string {\n if (!single) return JSON.stringify(text);\n return `'${text.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n}\n\nexport function transformCode(\n code: string,\n file: string,\n analysis?: Analysis,\n): TransformResult | null {\n const own = analysis ?? analyzeFile(code, file);\n if (!analysis && own.parseError) warnParseError(file, own.parseError);\n const { tagged } = own;\n if (tagged.length === 0) return null;\n\n const s = new MagicString(code);\n for (const msg of tagged) {\n const seen = new Set<string>();\n const entries = msg.params.filter((p) => !seen.has(p.name) && seen.add(p.name));\n const pairs = entries\n .map((p) => `${quote(p.name, msg.singleQuote)}: ${code.slice(p.start, p.end)}`)\n .join(', ');\n\n if (msg.jsx) {\n const values = entries.length ? ` values={{ ${pairs} }}` : '';\n const components = msg.jsx.components.length\n ? ` components={{ ${msg.jsx.components\n .map((c) => `${JSON.stringify(c.name)}: ${c.source}`)\n .join(', ')} }}`\n : '';\n s.overwrite(\n msg.start,\n msg.end,\n `<${msg.jsx.name} id=${JSON.stringify(msg.key)}${values}${components} />`,\n );\n continue;\n }\n\n const tagSource = code.slice(msg.tagStart, msg.tagEnd);\n const args = entries.length ? `, { ${pairs} }` : '';\n s.overwrite(msg.start, msg.end, `${tagSource}(${quote(msg.key, msg.singleQuote)}${args})`);\n }\n return { code: s.toString(), map: s.generateMap({ hires: true }) };\n}\n","import { relative } from 'node:path';\nimport picomatch from 'picomatch';\nimport { auditBundle, clientCatalogs, formatBundleIssue } from './bundle';\nimport {\n emptyCatalog,\n loadCatalogs,\n needsIcu,\n needsRelative,\n type Catalog,\n type Catalogs,\n} from './catalog';\nimport { check, checkNextSteps, formatCheckResult, gatePasses, warningCount } from './check';\nimport { VIRTUAL_ID, generateLocaleModule, generateRuntimeModule } from './codegen';\nimport type { ResolvedConfig, VerbalyConfig } from './config';\nimport { cliReachable } from './init';\nimport type { MessageRegistry } from './registry';\nimport { analyzeFile } from './sfc';\nimport { readState, type Fingerprints } from './state';\nimport { counted } from './text';\nimport { transformCode, type TransformResult } from './transform';\nimport { warnOnce, warnParseError } from './warn';\n\nexport interface PluginOptions extends VerbalyConfig {\n failOnMissing?: boolean;\n}\n\nexport const RESOLVED_VIRTUAL_ID = '\\0' + VIRTUAL_ID;\nexport const LOCALE_MODULE_PREFIX = `${RESOLVED_VIRTUAL_ID}/locale/`;\nexport const SOURCE_FILE_RE = /\\.(?:[cm]?[jt]sx?|svelte|vue|astro)$/;\n\nexport function resolveVirtualId(id: string): string | undefined {\n if (id === VIRTUAL_ID || id.startsWith(`${VIRTUAL_ID}/`)) return '\\0' + id;\n return undefined;\n}\n\nexport function loadVirtualModule(\n id: string,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n): string | undefined {\n // filtered before the detectors run: a group that leaves the bundle takes its parsers with it\n const client = clientCatalogs(cfg, catalogs);\n if (id === RESOLVED_VIRTUAL_ID) {\n return generateRuntimeModule(cfg, {\n icu: cfg.icu ?? needsIcu(client),\n relative: cfg.relative ?? needsRelative(client),\n inlineCatalog: cfg.render.inlineCatalog === true,\n });\n }\n if (id.startsWith(LOCALE_MODULE_PREFIX)) {\n return generateLocaleModule(client[id.slice(LOCALE_MODULE_PREFIX.length)] ?? {});\n }\n return undefined;\n}\n\nexport function isTransformTarget(id: string): boolean {\n return SOURCE_FILE_RE.test(id) && !id.includes('node_modules') && !id.startsWith('\\0');\n}\n\nexport function createSourceFilter(cfg: ResolvedConfig): (id: string) => boolean {\n if (cfg.include.length === 0) return () => false;\n const matches = picomatch(cfg.include, { ignore: cfg.exclude });\n return (id) => {\n const rel = relative(cfg.root, id).replaceAll('\\\\', '/');\n return !rel.startsWith('..') && matches(rel);\n };\n}\n\n// analyze + register + rewrite: the per-file transform every bundler plugin runs\nexport function transformSource(\n code: string,\n id: string,\n registry: MessageRegistry,\n): { messages: Catalog; result: TransformResult | null } {\n const analysis = analyzeFile(code, id);\n registry.update(id, analysis);\n if (analysis.parseError) warnParseError(id, analysis.parseError);\n // key → text for live extraction; first wins, mirroring the registry's collision rule\n const messages = emptyCatalog();\n for (const msg of analysis.tagged) messages[msg.key] ??= msg.message;\n return { messages, result: transformCode(code, id, analysis) ?? null };\n}\n\n// the one build-blocking error message, kept in one place (undefined = gate on)\nexport function runBuildGate(\n cfg: ResolvedConfig,\n registry: MessageRegistry,\n failOnMissing?: boolean,\n): void {\n const catalogs = loadCatalogs(cfg);\n // warns, never blocks: an excluded group that a page needs is a mistake the build cannot prove\n for (const issue of auditBundle(cfg, catalogs, registry)) {\n warnOnce(`${formatBundleIssue(issue)}\\n fix: ${issue.fix}`, `bundle:${issue.prefix}`);\n }\n const found = check(cfg, catalogs, registry, buildFingerprints(cfg));\n // a warning never stops a build, so the build says they exist in one line and check reads them\n const warnings = warningCount(found);\n if (warnings > 0) {\n warnOnce(\n `check has ${counted(warnings, 'warning')}, and the build still passes: run \\`npx verbaly check\\` to read them`,\n 'gate:warnings',\n );\n }\n // false = build with untranslated strings, never with broken ones: those render wrong\n const result = failOnMissing === false ? { ...found, missing: [] } : found;\n if (gatePasses(result)) return;\n throw new Error(\n `[verbaly] build blocked\\n${formatCheckResult(result, cfg.root)}\\n${checkNextSteps(result, cliReachable(cfg.root))}`,\n );\n}\n\n// the state only feeds a warning, so a sidecar nobody can parse must not be what stops a build\nfunction buildFingerprints(cfg: ResolvedConfig): Fingerprints {\n const { state, problem } = readState(cfg);\n if (problem) warnOnce(`${problem}, so outdated translations are not reported`, 'gate:state');\n return state.fingerprints;\n}\n","import { readFileSync } from 'node:fs';\nimport { relative } from 'node:path';\nimport picomatch from 'picomatch';\nimport { glob } from 'tinyglobby';\nimport { SOURCE_EXTENSIONS, type ResolvedConfig } from './config';\nimport { analyzeFile } from './sfc';\nimport { warnOnce } from './warn';\n\n// a hint before Babel is asked: t`, t.id('…')` or a Svelte $t`\nconst TAGGED_HINT = /(?<![\\w$.])\\$?t(?:\\.id\\s*\\([^)]*\\))?\\s*`/;\n\n// folders that hold builds or vendored code, never the app's own source\nconst NOT_SOURCE = [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/out/**',\n '**/coverage/**',\n];\n\nfunction relativeId(cfg: ResolvedConfig, id: string): string {\n return relative(cfg.root, id).replaceAll('\\\\', '/');\n}\n\n// the include pattern that would cover a file: its top folder with the extensions extract reads\nfunction suggestedPattern(rel: string): string {\n const slash = rel.indexOf('/');\n return slash < 0 ? rel : `${rel.slice(0, slash)}/**/*.${SOURCE_EXTENSIONS}`;\n}\n\nexport interface OutsideFile {\n file: string;\n pattern: string;\n}\n\n// a file the build reads and extract never will: its t`…` shows the source text in every language\nexport function createOutsideCheck(\n cfg: ResolvedConfig,\n): (code: string, id: string) => OutsideFile | undefined {\n // include: [] turns scanning off on purpose, so nothing is outside of it\n if (cfg.include.length === 0) return () => undefined;\n const included = picomatch(cfg.include);\n const excluded = picomatch(cfg.exclude);\n return (code, id) => {\n const rel = relativeId(cfg, id);\n if (rel.startsWith('..') || included(rel) || excluded(rel)) return undefined;\n if (!TAGGED_HINT.test(code)) return undefined;\n // the hint matches prose too: only a real tagged template on t counts\n if (analyzeFile(code, id).tagged.length === 0) return undefined;\n return { file: id, pattern: suggestedPattern(rel) };\n };\n}\n\n// one wording for the loader, both plugins and doctor\nexport function formatOutside(cfg: ResolvedConfig, found: OutsideFile): string {\n return (\n `${relativeId(cfg, found.file)} uses t\\`…\\` outside the include of your verbaly config, so its ` +\n `texts are never extracted and show in ${cfg.sourceLocale} in every language: add ` +\n `\"${found.pattern}\" to include (or the file to exclude, if it is not app code)`\n );\n}\n\n// once when a build or a dev server starts: a loader result can come from a cache, a scan cannot\nexport async function reportOutsideInclude(cfg: ResolvedConfig): Promise<void> {\n for (const found of await filesOutsideInclude(cfg)) {\n warnOnce(formatOutside(cfg, found), `outside:${found.file}`);\n }\n}\n\n// the whole project, for doctor: every source file outside include that writes a t`…`\nexport async function filesOutsideInclude(cfg: ResolvedConfig): Promise<OutsideFile[]> {\n if (cfg.include.length === 0) return [];\n const check = createOutsideCheck(cfg);\n const files = await glob([`**/*.${SOURCE_EXTENSIONS}`], {\n cwd: cfg.root,\n ignore: [...NOT_SOURCE, ...cfg.exclude],\n absolute: true,\n });\n const found: OutsideFile[] = [];\n for (const file of files.sort()) {\n let code: string;\n try {\n code = readFileSync(file, 'utf8');\n } catch {\n continue;\n }\n const outside = check(code, file);\n if (outside) found.push(outside);\n }\n return found;\n}\n","import type { ResolvedConfig } from './config';\nimport { loadState, saveState, type Drafts } from './state';\n\nexport { clearDrafts, effectiveDrafts, markDrafts, STATE_FILE } from './state';\nexport type { Drafts } from './state';\n\nexport function loadDrafts(cfg: ResolvedConfig): Drafts {\n return loadState(cfg).drafts;\n}\n\n// the drafts share their file with the fingerprints, so a save keeps whatever else it holds\nexport function saveDrafts(cfg: ResolvedConfig, drafts: Drafts): void {\n const state = loadState(cfg);\n saveState(cfg, { ...state, drafts });\n}\n","import type { Catalog, Catalogs } from './catalog';\nimport type { ResolvedConfig } from './config';\nimport { effectiveDrafts, type Drafts } from './drafts';\nimport { shippedCatalogs } from './extract';\nimport { outdatedTranslations, type Fingerprints } from './state';\nimport { flatten, type MessageTree } from 'verbaly';\nimport type { MessageRegistry } from './registry';\nimport { counted } from './text';\nimport { validateMessage, validatePair } from './validate';\n\nexport interface LocaleStatus {\n locale: string;\n translated: number;\n total: number;\n drafts: number;\n broken: number;\n outdated: number;\n}\n\nexport interface StatusResult {\n messages: number;\n source: string;\n locales: LocaleStatus[];\n}\n\n// coverage overview for humans; check stays the CI gate\nexport function status(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: MessageRegistry,\n drafts: Drafts = {},\n fingerprints: Fingerprints = {},\n): StatusResult {\n const extracted = registry.messages();\n\n // one flat view per locale, like check: the shape t() sees, counted leaf by leaf\n const flat: Record<string, Catalog> = {};\n for (const locale of cfg.locales) {\n flat[locale] = flatten((catalogs[locale] ?? {}) as MessageTree);\n }\n const source = flat[cfg.sourceLocale] ?? {};\n const needed = new Set<string>([...extracted.keys(), ...Object.keys(source)]);\n const live = effectiveDrafts(drafts, flat);\n // the text that ships, as check reads it, so status and check never disagree\n const shipped = shippedCatalogs(cfg, flat, registry);\n const sourceText = shipped[cfg.sourceLocale]!;\n const outdated = outdatedTranslations(cfg, shipped, fingerprints);\n\n const locales: LocaleStatus[] = [];\n for (const locale of cfg.locales) {\n if (locale === cfg.sourceLocale) continue;\n const catalog = flat[locale] ?? {};\n let translated = 0;\n for (const key of needed) {\n if (catalog[key]) translated += 1;\n }\n let broken = 0;\n for (const [key, text] of Object.entries(catalog)) {\n if (!text) continue;\n const from = sourceText[key];\n const issues = [...validateMessage(text, locale), ...(from ? validatePair(from, text) : [])];\n if (issues.some((issue) => issue.severity === 'error')) broken += 1;\n }\n locales.push({\n locale,\n translated,\n total: needed.size,\n drafts: live[locale]?.length ?? 0,\n broken,\n outdated: outdated.filter((entry) => entry.locale === locale).length,\n });\n }\n return { messages: needed.size, source: cfg.sourceLocale, locales };\n}\n\nexport function formatStatusResult(result: StatusResult): string {\n const lines = [`[verbaly] ${counted(result.messages, 'message')} · source: ${result.source}`];\n if (result.locales.length === 0) {\n lines.push(' no target locales (add locales to your config)');\n return lines.join('\\n');\n }\n for (const { locale, translated, total, drafts, broken, outdated } of result.locales) {\n const pct = total === 0 ? 100 : Math.floor((translated / total) * 100);\n const mark = translated === total && broken === 0 && outdated === 0 ? ' ✓' : '';\n const notes = [\n drafts > 0 ? `${drafts} unreviewed` : '',\n broken > 0 ? `${broken} broken` : '',\n outdated > 0 ? `${outdated} outdated` : '',\n ].filter(Boolean);\n const note = notes.length > 0 ? `, ${notes.join(', ')}` : '';\n lines.push(` ${locale}: ${translated}/${total} translated (${pct}%${note})${mark}`);\n }\n return lines.join('\\n');\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { flatten } from 'verbaly';\nimport { auditBundle, formatBundleIssue } from './bundle';\nimport { badLeaf, isTree, parseTree, type Catalogs } from './catalog';\nimport { check } from './check';\nimport { DTS_HEADER, generateDts, projectDtsOptions } from './codegen';\nimport { findConfigFile, type ResolvedConfig } from './config';\nimport { extractProject } from './extract';\nimport { sourcePlace } from './findings';\nimport { detectHost, installCommand, readDependencies, WIRING_PACKAGES } from './host';\nimport { CLI_INSTALL_FIX, cliReachable } from './init';\nimport { filesOutsideInclude } from './scope';\nimport { typesIncluded } from './tsconfig';\nimport { counted } from './text';\nimport { isLocaleTag, suggestTag } from './tag';\nimport { effectiveDrafts, readState, STATE_FILE } from './state';\nimport { escapedSyntax } from './validate';\n\nexport interface DoctorEntry {\n level: 'ok' | 'warn' | 'error';\n check: string;\n message: string;\n fix?: string;\n}\n\nexport interface DoctorResult {\n ok: boolean; // no error-level entries (warns allowed)\n entries: DoctorEntry[];\n}\n\nconst PREVIEW = 5; // keys shown before \"…\"\n\n// a mode nobody wrote down was inferred, and doctor says which of the two it is reading\nfunction readRoutingChoice(root: string, configFile: string): boolean {\n try {\n return /\\brouting[\"']?\\s*[:=]/.test(readFileSync(join(root, configFile), 'utf8'));\n } catch {\n return false;\n }\n}\n\nconst ROUTING_SAYS: Record<ResolvedConfig['routing'], string> = {\n 'prefix-except-source': 'the source locale has no prefix, every other locale does',\n 'prefix-all': 'every locale has a prefix, the source included',\n 'no-prefix': 'the language is not in the url, one address serves every locale',\n};\n\nconst ICON = { ok: '✓', warn: '⚠', error: '✗' } as const;\n\n// one definition of a doctor line: the cli routes it by level, the mcp tool joins the block\nexport function formatDoctorEntry(entry: DoctorEntry): string {\n const head = ` ${ICON[entry.level]} ${entry.check}: ${entry.message}`;\n return entry.fix\n ? `${head}\n fix: ${entry.fix}`\n : head;\n}\n\nexport async function doctor(cfg: ResolvedConfig): Promise<DoctorResult> {\n const entries: DoctorEntry[] = [];\n const ok = (name: string, message: string) => entries.push({ level: 'ok', check: name, message });\n const warn = (name: string, message: string, fix: string) =>\n entries.push({ level: 'warn', check: name, message, fix });\n const error = (name: string, message: string, fix: string) =>\n entries.push({ level: 'error', check: name, message, fix });\n const rel = (path: string) => relative(cfg.root, path).replaceAll('\\\\', '/');\n\n const configFile = findConfigFile(cfg.root);\n if (configFile) ok('config', `${configFile} found`);\n else warn('config', 'no config file, running on defaults', 'run `npx verbaly init`');\n\n // the build works without it: what breaks is every command we tell people to run\n if (cliReachable(cfg.root)) ok('cli', 'the verbaly command is available in this project');\n else warn('cli', 'the verbaly command is not linked in node_modules/.bin', CLI_INSTALL_FIX);\n\n const catalogs: Catalogs = {};\n let catalogsHealthy = true;\n if (!existsSync(cfg.dir)) {\n catalogsHealthy = false;\n error(\n 'catalogs',\n `catalogs directory ${rel(cfg.dir)}/ does not exist`,\n 'run `npx verbaly init` to scaffold it',\n );\n } else {\n for (const locale of cfg.locales) {\n const file = join(cfg.dir, `${locale}.json`);\n if (!existsSync(file)) {\n catalogsHealthy = false;\n error(\n `locale ${locale}`,\n `${rel(file)} is missing`,\n 'run `npx verbaly extract` to create it',\n );\n continue;\n }\n // the same reader the gate uses, so a BOM the build accepts is never an error here\n const parsed = parseTree(readFileSync(file, 'utf8'));\n if (parsed === undefined) {\n catalogsHealthy = false;\n error(\n `locale ${locale}`,\n `${rel(file)} is not valid JSON`,\n 'repair the file (or delete it and run `npx verbaly extract`)',\n );\n continue;\n }\n if (!isTree(parsed)) {\n catalogsHealthy = false;\n error(\n `locale ${locale}`,\n `${rel(file)} is not a JSON object of messages`,\n 'a catalog is an object of texts (groups of text are fine): fix the file',\n );\n continue;\n }\n // nested groups are a real shape: only a leaf that is not text is broken\n const bad = badLeaf(parsed);\n if (bad) {\n catalogsHealthy = false;\n error(\n `locale ${locale}`,\n `${rel(file)} has a non-string value at \"${bad}\"`,\n 'catalog values are text (groups of text are fine); fix the value',\n );\n } else {\n catalogs[locale] = flatten(parsed);\n }\n }\n if (catalogsHealthy) {\n const how = cfg.localesDeclared ? '' : ', no locales set, so the catalog files decide';\n ok(\n 'catalogs',\n `${counted(cfg.locales.length, 'locale')} (${cfg.locales.join(', ')}) in ${rel(cfg.dir)}/${how}`,\n );\n }\n }\n\n // it builds and the runtime falls back with a warn, so this is a warn too, rename in hand\n for (const locale of cfg.locales) {\n if (isLocaleTag(locale)) continue;\n const near = suggestTag(locale);\n const file = rel(join(cfg.dir, `${locale}.json`));\n warn(\n 'locales',\n `\"${locale}\" is not a locale tag, so numbers, dates and plurals in it format in a fallback`,\n near\n ? `rename it to ${near}: the file ${file} and your config`\n : `name it with a language tag like es or pt-BR, in ${file} and in your config`,\n );\n }\n\n const source = catalogs[cfg.sourceLocale];\n if (source && Object.keys(source).length === 0) {\n warn(\n 'source',\n `source catalog ${cfg.sourceLocale}.json is empty`,\n 'write your first t`…` message and run `npx verbaly extract`',\n );\n }\n\n const mirrors = cfg.render.site !== undefined || Object.keys(cfg.render).length > 0;\n if (cfg.routing === 'no-prefix' && mirrors) {\n warn(\n 'routing',\n 'routing is \"no-prefix\" but a render section is configured, and render writes one url tree per locale',\n 'drop the render section, or set routing to \"prefix-except-source\" so the helpers agree with the urls',\n );\n } else if (cfg.routing === 'prefix-all' && mirrors) {\n // render leaves the source tree at the root, so a helper that prefixes it points at no page\n warn(\n 'routing',\n `routing is \"prefix-all\" but render keeps ${cfg.sourceLocale} at the root, so its links point at a /${cfg.sourceLocale}/ tree nobody wrote`,\n 'set routing to \"prefix-except-source\", the url tree render writes',\n );\n } else {\n const named = configFile ? readRoutingChoice(cfg.root, configFile) : false;\n const how = named ? '' : ' (from your setup, no routing set)';\n ok('routing', `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);\n }\n\n const deps = readDependencies(cfg.root);\n const host = detectHost(cfg.root);\n const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);\n if (!host) {\n ok('plugin', 'no framework or bundler detected, the CLI flow (extract/check) applies');\n } else if (installed) {\n ok('plugin', `${installed} installed for ${host.name}`);\n } else {\n warn(\n 'plugin',\n `${host.name} detected but ${host.pkg} is not installed`,\n `${installCommand(cfg.root, host.install)}, then ${host.wire}`,\n );\n }\n\n // with include: [] no code is read, so orphans and types cannot be claimed here\n const scanning = cfg.include.length > 0;\n if (!scanning) {\n ok('sources', 'source scanning is off (include: []), the catalogs are the source of truth');\n }\n\n if (source && scanning && cfg.dts !== false) {\n const dtsPath = cfg.dts;\n const shown = rel(dtsPath);\n // a framework slot is linked from the framework's own types, which only its command writes\n const regenerate =\n host?.name === 'astro'\n ? 'run `npx astro sync`, which writes the types and links them'\n : host?.name === 'nuxt'\n ? 'run `npx nuxi prepare`, which writes the types and links them'\n : 'run `npx verbaly typegen`';\n const expected = generateDts(source, projectDtsOptions(cfg));\n if (!existsSync(dtsPath)) {\n warn('types', `${shown} has not been generated`, regenerate);\n } else if (readFileSync(dtsPath, 'utf8').replace(/\\r\\n/g, '\\n') !== expected) {\n warn('types', `${shown} is stale`, 'run `npx verbaly typegen`');\n } else {\n ok('types', `${shown} is up to date`);\n }\n // .verbaly/ is a dot folder: TypeScript reads it only if tsconfig names the file\n if (dtsPath.startsWith(join(cfg.root, '.verbaly'))) {\n const state = typesIncluded(cfg.root, dtsPath);\n if (state === 'missing' || state === 'unreadable') {\n warn(\n 'types',\n state === 'missing'\n ? `tsconfig.json does not include ${shown}, so TypeScript never reads the types`\n : `tsconfig.json could not be read, so it may not include ${shown}`,\n `run \\`npx verbaly typegen\\`, which adds the line, or add \"${shown}\" to include`,\n );\n }\n }\n // the root file and the one in its new place declare the same module twice\n const old = join(cfg.root, 'verbaly.d.ts');\n if (dtsPath !== old && existsSync(old) && readFileSync(old, 'utf8').startsWith(DTS_HEADER)) {\n warn(\n 'types',\n `the verbaly.d.ts Verbaly wrote at the root is still there next to ${shown}, and they declare the same module twice`,\n 'run `npx verbaly typegen`, which removes it',\n );\n }\n }\n\n const registry = await extractProject(cfg);\n if (scanning) {\n // a warn, not an error: decorators or a dialect babel does not read still build in the project\n const unreadable = registry.parseErrors();\n if (unreadable.length > 0) {\n const first = unreadable[0]!;\n warn(\n 'sources',\n `could not parse ${counted(unreadable.length, 'file')}, so the messages inside are not extracted (${rel(first.file)}: ${first.message})`,\n 'fix the syntax error, or exclude the file in your config if it is not source',\n );\n }\n // a file the build reads and extract never will: its texts show the source language everywhere\n const outside = await filesOutsideInclude(cfg);\n if (outside.length > 0) {\n const files = outside.map((entry) => rel(entry.file));\n const patterns = [...new Set(outside.map((entry) => `\"${entry.pattern}\"`))];\n warn(\n 'sources',\n `t\\`…\\` is written in ${counted(outside.length, 'file')} outside include, and those texts are never extracted or translated (${preview(files)})`,\n `add ${patterns.join(' and ')} to include in your verbaly config, or the files to exclude if they are not app code`,\n );\n }\n const stray = registry.strayImports();\n if (stray.length > 0) {\n const files = [...new Set(stray.map((entry) => rel(entry.file)))];\n error(\n 'imports',\n `t is imported from a verbaly package, which never exports it, in ${counted(files.length, 'file')} (${preview(files)})`,\n 't comes from your instance (React: const t = useT()) or from virtual:verbaly',\n );\n }\n // a t under another name reads fine at runtime, and its texts stay in the source language\n const missed = registry.missed();\n if (missed.length > 0) {\n const first = missed[0]!;\n warn(\n 'sources',\n `a t under another name keeps ${counted(missed.length, 'text')} out of extraction (${sourcePlace(first, cfg.root)}: ${first.name}\\`…\\`)`,\n 'name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog',\n );\n }\n // a translator who sees {_0} cannot know what goes there\n const positional = [...registry.messages().values()].filter((msg) =>\n msg.params.some((param) => /^_\\d+$/.test(param.name)),\n );\n if (positional.length > 0) {\n const first = positional[0]!;\n warn(\n 'messages',\n `a translator gets a nameless value like {_0} in ${counted(positional.length, 'message')} (${sourcePlace(first, cfg.root)}: \"${first.message}\")`,\n 'put the value in a named variable first (const date = formatDate(d)), so the message says {date}',\n );\n }\n const escaped = [...registry.messages().values()]\n .map((msg) => ({ file: rel(msg.file), slice: escapedSyntax(msg.message) }))\n .filter((entry) => entry.slice !== undefined);\n if (escaped.length > 0) {\n warn(\n 'messages',\n `a block ships as literal text in ${counted(escaped.length, 'extracted message')} (${escaped[0]!.file}: ${escaped[0]!.slice})`,\n 'a tagged template takes its values from ${…}: use t(key, params) for a plural or format block',\n );\n }\n }\n if (source && scanning) {\n const extracted = registry.messages();\n const used = registry.usedKeys();\n const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));\n // a file that did not parse may be the one reading them, and prune waits until it does\n const unread = registry.parseErrors().length > 0;\n if (orphans.length > 0) {\n warn(\n 'orphans',\n `${counted(orphans.length, 'catalog key')} no longer referenced in code (${preview(orphans)})`,\n unread\n ? 'fix the files that do not parse first, they may use these, and `npx verbaly extract --prune` leaves every key alone until then'\n : 'run `npx verbaly extract --prune` to drop them',\n );\n } else {\n ok('orphans', 'no orphan keys');\n }\n }\n\n const excluded = cfg.bundle.exclude ?? [];\n if (excluded.length > 0 && catalogsHealthy) {\n const issues = auditBundle(cfg, catalogs, registry);\n for (const issue of issues) warn('bundle', formatBundleIssue(issue), issue.fix);\n if (issues.length === 0) {\n ok(\n 'bundle',\n `${counted(excluded.length, 'group')} kept out of the client (${preview(excluded)})`,\n );\n }\n }\n\n // the sidecar only feeds warnings, so a broken one is reported here and never stops a build\n const { state, problem } = readState(cfg);\n if (problem) {\n warn(\n 'state',\n problem,\n `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`,\n );\n }\n if (catalogsHealthy) {\n const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {\n const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);\n return keys.filter((key) => !live.has(key)).map((key) => `${locale}: ${key}`);\n });\n if (stale.length > 0) {\n warn(\n 'drafts',\n `${STATE_FILE} lists ${counted(stale.length, 'draft')} whose translation is gone (${preview(stale)})`,\n 'run `npx verbaly extract`, which drops them',\n );\n }\n }\n\n if (catalogsHealthy) {\n const result = check(cfg, catalogs, registry, state.fingerprints);\n if (result.unknown.length > 0) {\n error(\n 'keys',\n `${counted(result.unknown.length, 'unknown key')} used in code (${preview(result.unknown.map((u) => u.key))})`,\n 'fix the key or add it to the catalogs (`npx verbaly check` for details)',\n );\n }\n if (result.missing.length > 0) {\n const locales = [...new Set(result.missing.map((m) => m.locale))];\n warn(\n 'translations',\n `${counted(result.missing.length, 'missing translation')} (${locales.join(', ')})`,\n 'run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)',\n );\n }\n // the gate fails on these, so doctor cannot keep calling the setup healthy\n const broken = result.broken.filter((entry) => entry.severity === 'error');\n if (broken.length > 0) {\n const locales = [...new Set(broken.map((b) => b.locale))];\n error(\n 'translations',\n `${counted(broken.length, 'broken translation')} (${locales.join(', ')}): present but not rendering what the source renders`,\n 'run `npx verbaly check` to read what each one lost',\n );\n }\n if (result.extra.length > 0) {\n const shown = result.extra.map((entry) => `${entry.locale}: ${entry.key}`);\n warn(\n 'extras',\n `a translation has ${counted(result.extra.length, 'key')} the source catalog does not (${preview(shown)})`,\n scanning\n ? 'add them to the source catalog if your code uses them, or run `npx verbaly extract --prune` to drop the rest'\n : 'add them to the source catalog if your code uses them, or delete them from the translations',\n );\n }\n const warnings = result.broken.filter((entry) => entry.severity === 'warning');\n if (warnings.length > 0) {\n warn(\n 'translations',\n `${counted(warnings.length, 'structural warning')} (plural forms a language asks for)`,\n 'run `npx verbaly check` to read them, they never fail the build',\n );\n }\n if (result.collisions.length > 0) {\n const first = result.collisions[0]!;\n warn(\n 'keys',\n `${counted(result.collisions.length, 'key')} written with more than one text, and every place shows the first (${first.key}: ${first.sites.map((at) => sourcePlace(at, cfg.root)).join(', ')})`,\n 'give each text its own key (`npx verbaly check` lists every place)',\n );\n }\n if (result.divergent.length > 0) {\n const first = result.divergent[0]!;\n warn(\n 'source texts',\n `the code and ${cfg.sourceLocale}.json disagree on ${counted(result.divergent.length, 'text')}, and the code's text ships (${first.key}, ${sourcePlace(first.code, cfg.root)})`,\n 'edit those texts in the code; `npx verbaly extract` writes them into the catalog',\n );\n }\n if (result.outdated.length > 0) {\n const shown = result.outdated.map((entry) => `${entry.locale}: ${entry.key}`);\n warn(\n 'outdated',\n `${counted(result.outdated.length, 'translation')} written for an older source text (${preview(shown)})`,\n 'update them, or keep them with `npx verbaly review --approve`',\n );\n }\n if (result.ok) ok('translations', 'all translations complete');\n }\n\n return { ok: entries.every((entry) => entry.level !== 'error'), entries };\n}\n\nfunction preview(keys: string[]): string {\n const head = keys.slice(0, PREVIEW).join(', ');\n return keys.length > PREVIEW ? `${head}, …` : head;\n}\n","import {\n emptyCatalog,\n own,\n readCatalog,\n writeCatalog,\n type Catalog,\n type Catalogs,\n} from './catalog';\nimport { targetLocales, type ResolvedConfig } from './config';\nimport { shippedCatalogs } from './extract';\nimport type { MessageRegistry } from './registry';\nimport { loadState, recordTranslations } from './state';\nimport { byCodeUnit, counted } from './text';\nimport { validateMessage, validatePair } from './validate';\n\nexport interface TranslateRequest {\n sourceLocale: string;\n targetLocale: string;\n messages: Record<string, string>;\n origins?: Record<string, string[]>;\n instructions?: string;\n glossary?: Record<string, string>;\n}\n\nexport type TranslateProvider = (request: TranslateRequest) => Promise<Record<string, string>>;\n\nexport interface TranslateProgress {\n locale: string;\n batch: number;\n batches: number;\n keys: number;\n error?: string;\n}\n\nexport interface TranslateOptions {\n locales?: string[];\n batchSize?: number;\n concurrency?: number;\n retries?: number;\n retryDelay?: number;\n dryRun?: boolean;\n origins?: Record<string, string[]>;\n onProgress?: (progress: TranslateProgress) => void;\n}\n\n// carries its reason, which the per-locale records cannot: a batch fails as a batch\nexport interface TranslateFailure {\n locale: string;\n keys: string[];\n error: string;\n}\n\nexport interface TranslateResult {\n translated: Record<string, string[]>;\n invalid: Record<string, string[]>;\n pending: Record<string, string[]>;\n failed: TranslateFailure[];\n}\n\ninterface Batch {\n locale: string;\n index: number;\n batches: number;\n keys: string[];\n}\n\nconst RETRY_STATUS = new Set([408, 409, 425, 429, 500, 502, 503, 504, 529]);\n\n// a provider is an extension point: retry what looks transient, never a request the api refused\nfunction retryable(error: unknown): boolean {\n const status = (error as { status?: number; statusCode?: number } | null)?.status;\n const code = (error as { statusCode?: number } | null)?.statusCode;\n const value = typeof status === 'number' ? status : code;\n return typeof value === 'number' ? RETRY_STATUS.has(value) : true;\n}\n\nfunction reason(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nconst wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n// a batch that never gets an answer is a failed batch, never a thrown run: everything else lands\nasync function attempt(\n run: () => Promise<Record<string, string>>,\n retries: number,\n delay: number,\n): Promise<Record<string, string>> {\n for (let round = 0; ; round++) {\n try {\n return await run();\n } catch (error) {\n if (round >= retries || !retryable(error)) throw error;\n await wait(delay * 2 ** round);\n }\n }\n}\n\n// bounded pool: independent batches, so the only reason to serialize them is the provider's limit\nasync function pooled<T>(jobs: T[], limit: number, run: (job: T) => Promise<void>): Promise<void> {\n let next = 0;\n const workers = Array.from({ length: Math.min(limit, jobs.length) }, async () => {\n while (next < jobs.length) {\n await run(jobs[next++]!);\n }\n });\n await Promise.all(workers);\n}\n\n// fills '' entries via the provider; invalid translations stay '' (check keeps failing)\nexport async function translateCatalogs(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n provider: TranslateProvider,\n options: TranslateOptions = {},\n): Promise<TranslateResult> {\n const batchSize = options.batchSize ?? 20;\n const concurrency = Math.max(1, options.concurrency ?? 4);\n const retries = Math.max(0, options.retries ?? 2);\n const retryDelay = options.retryDelay ?? 500;\n const targets = targetLocales(cfg, options.locales);\n const source = catalogs[cfg.sourceLocale] ?? {};\n const result: TranslateResult = { translated: {}, invalid: {}, pending: {}, failed: [] };\n\n const jobs: Batch[] = [];\n for (const locale of targets) {\n const catalog = (catalogs[locale] ??= emptyCatalog());\n const missing = Object.keys(source).filter((key) => source[key] && !own(catalog, key));\n if (missing.length === 0) continue;\n\n if (options.dryRun) {\n result.pending[locale] = missing;\n continue;\n }\n\n const batches = Math.ceil(missing.length / batchSize);\n for (let i = 0; i < missing.length; i += batchSize) {\n const index = Math.floor(i / batchSize) + 1;\n jobs.push({ locale, index, batches, keys: missing.slice(i, i + batchSize) });\n }\n }\n\n await pooled(jobs, concurrency, async (job) => {\n const { locale, keys } = job;\n const catalog = catalogs[locale]!;\n const messages = Object.fromEntries(keys.map((key) => [key, source[key]!]));\n const origins = options.origins\n ? Object.fromEntries(\n keys\n .filter((key) => Object.hasOwn(options.origins!, key))\n .map((key) => [key, options.origins![key]!]),\n )\n : undefined;\n\n let out: Record<string, string>;\n try {\n out = await attempt(\n () =>\n provider({\n sourceLocale: cfg.sourceLocale,\n targetLocale: locale,\n messages,\n origins,\n instructions: cfg.translate.instructions,\n glossary: glossaryFor(cfg, locale, messages),\n }),\n retries,\n retryDelay,\n );\n } catch (error) {\n const message = reason(error);\n result.failed.push({ locale, keys, error: message });\n options.onProgress?.({ ...progressOf(job), error: message });\n return;\n }\n\n for (const key of keys) {\n const text = out[key];\n if (typeof text === 'string' && text.trim() && structureMatches(source[key]!, text)) {\n catalog[key] = text;\n (result.translated[locale] ??= []).push(key);\n } else {\n (result.invalid[locale] ??= []).push(key);\n }\n }\n options.onProgress?.(progressOf(job));\n });\n\n // batches land out of order once they run in parallel, and a report has to read the same twice\n for (const locale of Object.keys(result.translated)) result.translated[locale]!.sort();\n for (const locale of Object.keys(result.invalid)) result.invalid[locale]!.sort();\n result.failed.sort((a, b) => byCodeUnit(a.locale, b.locale) || compare(a.keys, b.keys));\n return result;\n}\n\nfunction compare(a: string[], b: string[]): number {\n return byCodeUnit(a[0] ?? '', b[0] ?? '');\n}\n\n// a run takes minutes, so it writes onto the file as it is now: text a person added meanwhile stays\nexport function mergeTranslations(\n cfg: ResolvedConfig,\n locale: string,\n translated: Catalog,\n keys: string[],\n): string[] {\n const source = readCatalog(cfg, cfg.sourceLocale);\n const current = readCatalog(cfg, locale);\n const written: string[] = [];\n for (const key of keys) {\n const text = translated[key];\n // pruned meanwhile, or filled meanwhile: either way the file already says what it should\n if (!source[key] || current[key] || !text) continue;\n current[key] = text;\n written.push(key);\n }\n if (written.length > 0) writeCatalog(cfg, locale, current);\n return written;\n}\n\nexport interface DraftEntry {\n key: string;\n text: string;\n}\n\nexport interface WriteDraftsResult {\n written: string[];\n kept: string[];\n invalid: string[];\n unknown: string[];\n}\n\n// A batch of drafts is a batch of translations, so it can be written and marked as unreviewed\nexport interface WriteDraftsOptions {\n overwrite?: boolean;\n registry?: MessageRegistry;\n}\n\n// an agent's own translation lands like a provider's: checked, written and marked unreviewed\nexport function writeDrafts(\n cfg: ResolvedConfig,\n locale: string,\n entries: DraftEntry[],\n options: WriteDraftsOptions = {},\n): WriteDraftsResult {\n const targets = targetLocales(cfg);\n if (!targets.includes(locale)) {\n throw new Error(\n `[verbaly] \"${locale}\" is not a language this project translates into (${targets.join(', ') || 'none yet'})`,\n );\n }\n // the draft flag is what keeps it from passing as reviewed: an unreadable state writes nothing\n loadState(cfg);\n const catalogs: Catalogs = { [cfg.sourceLocale]: readCatalog(cfg, cfg.sourceLocale) };\n const source = options.registry\n ? shippedCatalogs(cfg, catalogs, options.registry, { newKeys: false })[cfg.sourceLocale]!\n : catalogs[cfg.sourceLocale]!;\n const current = readCatalog(cfg, locale);\n const result: WriteDraftsResult = { written: [], kept: [], invalid: [], unknown: [] };\n for (const { key, text } of entries) {\n const from = own(source, key);\n if (!from) result.unknown.push(key);\n else if (!text.trim() || !structureMatches(from, text)) result.invalid.push(key);\n else if (own(current, key) && !options.overwrite) result.kept.push(key);\n else {\n current[key] = text;\n result.written.push(key);\n }\n }\n if (result.written.length > 0) {\n writeCatalog(cfg, locale, current);\n const written = result.written.map((key) => ({ key, text: current[key]! }));\n recordTranslations(cfg, source, [{ locale, entries: written, draft: true }]);\n }\n return result;\n}\n\n// the same reason repeats across batches: say it once and name every key it cost\nexport function formatTranslateFailures(failed: TranslateFailure[]): string[] {\n const grouped: TranslateFailure[] = [];\n for (const entry of failed) {\n const same = grouped.find((it) => it.locale === entry.locale && it.error === entry.error);\n if (same) same.keys = [...same.keys, ...entry.keys];\n else grouped.push({ ...entry, keys: [...entry.keys] });\n }\n return grouped.map(\n ({ locale, error, keys }) =>\n ` ${locale}: ${counted(keys.length, 'message')} not translated (${error}): ${keys.join(', ')}`,\n );\n}\n\n// config provider wins; claude loads lazily so only translate pays for its optional SDK\nexport async function resolveProvider(\n cfg: ResolvedConfig,\n model?: string,\n): Promise<TranslateProvider> {\n const configured = cfg.translate.provider;\n if (typeof configured === 'function') return configured;\n const { claudeProvider } = await import('./providers/claude');\n return claudeProvider({ model: model ?? cfg.translate.model });\n}\n\n// no locale on purpose: a locale-specific plural gap must never drop a translator's file\nexport function structureMatches(source: string, translated: string): boolean {\n try {\n const issues = [...validateMessage(translated), ...validatePair(source, translated)];\n return !issues.some((issue) => issue.severity === 'error');\n } catch {\n return false; // unparseable input rejects the translation, it never crashes the caller\n }\n}\n\nfunction progressOf(job: Batch): TranslateProgress {\n return { locale: job.locale, batch: job.index, batches: job.batches, keys: job.keys.length };\n}\n\n// only the terms this batch actually contains: a glossary of hundreds must not become the prompt\nfunction glossaryFor(\n cfg: ResolvedConfig,\n locale: string,\n messages: Record<string, string>,\n): Record<string, string> | undefined {\n const entries = cfg.translate.glossary;\n if (!entries) return undefined;\n const text = Object.values(messages).join('\\n').toLowerCase();\n const out: Record<string, string> = {};\n for (const [term, rendering] of Object.entries(entries)) {\n if (!text.includes(term.toLowerCase())) continue;\n const value = typeof rendering === 'string' ? rendering : rendering[locale];\n if (value) out[term] = value;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n","import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport MagicString from 'magic-string';\nimport picomatch from 'picomatch';\nimport { glob } from 'tinyglobby';\nimport {\n alternateLinks,\n createVerbaly,\n localeDirection,\n LOCALE_STORAGE_KEY,\n normalizeLink,\n parseTags,\n RICH_TAGS,\n CATALOG_SCRIPT,\n safeAttribute,\n VOID_TAGS,\n type MessageTree,\n type Params,\n type RichLink,\n type TagNode,\n type Verbaly,\n} from 'verbaly';\nimport type { Catalogs } from './catalog';\nimport { loadCatalogs } from './catalog';\nimport { extractProject, shippedCatalogs } from './extract';\nimport type { RedirectConfig, ResolvedConfig } from './config';\nimport { counted } from './text';\nimport { warnOnce } from './warn';\n\nexport interface Alternate {\n hreflang: string;\n href: string;\n}\n\n// links that point at a page this mirror also holds get its prefix, so the visitor stays inside\nexport interface MirrorLinks {\n prefix: string;\n base?: string;\n pages: ReadonlySet<string>;\n}\n\n// the pre-paint script: the locale set it chooses from, and where a saved choice lives\nexport interface RedirectScript {\n locales: string[];\n sourceLocale: string;\n base?: string;\n storageKey?: string | false;\n}\n\ninterface RenderHtmlBase {\n locale: string;\n sourceLocale?: string;\n attribute?: string;\n richTags?: string[];\n richLinks?: Record<string, RichLink>;\n setLang?: boolean;\n alternates?: Alternate[];\n mirror?: MirrorLinks;\n redirect?: RedirectScript;\n inlineCatalog?: boolean;\n}\n\n// one of the two, never both: an instance already carries the catalogs it was built from\nexport type RenderHtmlOptions = RenderHtmlBase &\n (\n | { catalogs: Catalogs | Record<string, MessageTree>; instance?: never }\n | { catalogs?: never; instance: Verbaly }\n );\n\n// nested trees welcome: the runtime flattens them (verbaly-web's shape)\nexport function localeInstance(\n catalogs: Catalogs | Record<string, MessageTree>,\n locale: string,\n sourceLocale: string,\n): Verbaly {\n return createVerbaly({ locale, fallback: sourceLocale, messages: catalogs });\n}\n\nexport interface RenderHtmlResult {\n html: string;\n missing: string[];\n // every key this page resolved: the exact set a visitor needs, and nothing else\n used: string[];\n}\n\nconst HREFLANG_OPEN = '<!--verbaly:hreflang-->';\nconst HREFLANG_CLOSE = '<!--/verbaly:hreflang-->';\nconst CATALOG_OPEN = '<!--verbaly:catalog-->';\nconst CATALOG_CLOSE = '<!--/verbaly:catalog-->';\nconst REDIRECT_OPEN = '<!--verbaly:redirect-->';\nconst REDIRECT_CLOSE = '<!--/verbaly:redirect-->';\n\nconst VOID = new Set(VOID_TAGS);\n\nconst START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:\"[^\"]*\"|'[^']*'|[^\"'>])*)>/g;\nconst ATTR = /([^\\s=/\"'<>]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+)))?/g;\n\n// pre-fills data-verbaly elements for one locale; the runtime stays functional\nexport function renderHtml(html: string, options: RenderHtmlOptions): RenderHtmlResult {\n const attr = options.attribute ?? 'data-verbaly';\n const argsAttr = `${attr}-args`;\n const attrsAttr = `${attr}-attr`;\n const richAttr = `${attr}-rich`;\n const linksAttr = `${attr}-links`;\n const richTags = new Set(options.richTags ?? RICH_TAGS);\n const globalLinks = options.richLinks;\n const sourceLocale = options.sourceLocale ?? 'en';\n\n const v = options.instance ?? localeInstance(options.catalogs, options.locale, sourceLocale);\n const t = v.t as unknown as (key: string, params?: Params) => string;\n\n const ms = new MagicString(html);\n const missing = new Set<string>();\n const used = new Set<string>();\n const skip = protectedRanges(html);\n const inSkip = (index: number): boolean => skip.some(([from, to]) => index >= from && index < to);\n\n // a message can carry markup of its own, and MagicString refuses to edit inside what it replaced\n const filled: Array<[number, number]> = [];\n const inFilled = (index: number): boolean =>\n filled.some(([from, to]) => index >= from && index < to);\n\n // per-locale canonical/og:url: a cross-locale canonical would void the hreflang set\n const selfUrl = options.alternates?.find((a) => a.hreflang === options.locale)?.href;\n const sourceUrl = options.alternates?.find((a) => a.hreflang === 'x-default')?.href;\n const rewriteUrl = selfUrl !== undefined && selfUrl !== sourceUrl;\n\n START_TAG.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = START_TAG.exec(html)) !== null) {\n if (inSkip(m.index) || inFilled(m.index)) continue;\n const [full, rawName, attrChunk] = m as unknown as [string, string, string];\n const tagName = rawName.toLowerCase();\n const openEnd = m.index + full.length;\n\n const chunkStart = m.index + 1 + rawName.length;\n\n if (tagName === 'html' && options.setLang !== false) {\n // lang and dir together: what persistLocale/switchLocale set at runtime\n setAttribute(ms, html, chunkStart, openEnd, attrChunk, 'lang', options.locale);\n setAttribute(\n ms,\n html,\n chunkStart,\n openEnd,\n attrChunk,\n 'dir',\n localeDirection(options.locale),\n );\n continue;\n }\n\n const attrs = parseAttrs(attrChunk);\n\n if (\n rewriteUrl &&\n tagName === 'link' &&\n attrs.get('rel')?.toLowerCase() === 'canonical' &&\n decodeEntities(attrs.get('href') ?? '') === sourceUrl\n ) {\n setAttribute(ms, html, chunkStart, openEnd, attrChunk, 'href', selfUrl!);\n }\n if (\n rewriteUrl &&\n tagName === 'meta' &&\n attrs.get('property') === 'og:url' &&\n decodeEntities(attrs.get('content') ?? '') === sourceUrl\n ) {\n setAttribute(ms, html, chunkStart, openEnd, attrChunk, 'content', selfUrl!);\n }\n\n const mirror = options.mirror;\n if (mirror) {\n if (tagName === 'a' || tagName === 'area') {\n const inside = mirroredHref(attrs.get('href'), mirror);\n if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, 'href', inside);\n } else if (tagName === 'form' || tagName === 'button' || tagName === 'input') {\n // submitting navigates: a form landing on a page we mirrored belongs in the mirror too\n const name = tagName === 'form' ? 'action' : 'formaction';\n const inside = mirroredHref(attrs.get(name), mirror);\n if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, inside);\n } else if (tagName === 'meta' && attrs.get('http-equiv')?.toLowerCase() === 'refresh') {\n // a redirect page ships inside the mirror too, and its target must not leave it\n const content = attrs.get('content') ?? '';\n const url = /^([^;]*;\\s*url\\s*=\\s*)(.*)$/i.exec(decodeEntities(content));\n const inside = url && mirroredHref(url[2], mirror);\n if (inside) {\n setAttribute(ms, html, chunkStart, openEnd, attrChunk, 'content', `${url![1]}${inside}`);\n }\n }\n }\n\n const key = attrs.get(attr);\n const attrMapRaw = attrs.get(attrsAttr);\n if (key === undefined && attrMapRaw === undefined) continue;\n\n const args = parseArgs(attrs.get(argsAttr), argsAttr);\n\n if (key) {\n if (!v.has(key)) {\n missing.add(key);\n } else if (!VOID.has(tagName) && !attrChunk.trimEnd().endsWith('/')) {\n used.add(key);\n const close = findClose(html, tagName, openEnd, inSkip);\n if (close) {\n const text = t(key, args);\n const own = parseArgs(attrs.get(linksAttr), linksAttr) as Record<string, RichLink> | undefined;\n const merged = own ? (globalLinks ? { ...globalLinks, ...own } : own) : globalLinks;\n // a link inside a message is a link: without the prefix it leaves the mirror\n const links = mirror ? mirroredLinks(merged, mirror) : merged;\n const nodes = attrs.has(richAttr) ? parseTags(text) : [];\n // the page carries its own links: the runtime rebuilds from here, never from the config\n if (mirror && links) {\n const carried = usedLinks(nodes, links);\n if (carried && JSON.stringify(carried) !== JSON.stringify(own)) {\n setAttribute(\n ms,\n html,\n chunkStart,\n openEnd,\n attrChunk,\n linksAttr,\n JSON.stringify(carried),\n );\n }\n }\n const content = attrs.has(richAttr)\n ? richToHtml(nodes, richTags, links)\n : escapeHtml(text);\n if (html.slice(openEnd, close.contentEnd) !== content) {\n if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);\n else ms.overwrite(openEnd, close.contentEnd, content);\n }\n filled.push([openEnd, close.contentEnd]);\n }\n }\n }\n\n if (attrMapRaw !== undefined) {\n const map = parseArgs(attrMapRaw, attrsAttr);\n if (map) {\n for (const [name, attrKey] of Object.entries(map)) {\n if (typeof attrKey !== 'string') continue;\n if (!v.has(attrKey)) {\n missing.add(attrKey);\n continue;\n }\n used.add(attrKey);\n const value = safeAttribute(name, t(attrKey, args));\n if (value !== undefined)\n setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value);\n }\n }\n }\n }\n\n if (options.alternates?.length) injectAlternates(ms, html, options.alternates);\n if (options.redirect) injectRedirect(ms, html, options.redirect);\n // the source catalog always ships eagerly, so its own tree gains nothing from a slice\n if (options.inlineCatalog && options.locale !== sourceLocale) {\n const slice = pageSlice(v, options.locale, used);\n if (Object.keys(slice).length > 0) injectCatalog(ms, html, slice);\n }\n\n return { html: ms.toString(), missing: [...missing], used: [...used] };\n}\n\n// every key the page used, '' where the locale falls back: a short slice is not an empty message\nfunction pageSlice(v: Verbaly, locale: string, used: Set<string>): Record<string, string> {\n const slice: Record<string, string> = Object.create(null);\n for (const key of used) {\n const found = v.inspect(key);\n slice[key] = found?.from === locale ? found.source : '';\n }\n return slice;\n}\n\n// the public path of a built page, the shape both the page set and an author's href reduce to\nexport function publicPath(rel: string): string {\n const path = `/${rel.replace(/(^|\\/)index\\.html$/, '$1')}`;\n return path.length > 1 ? path.replace(/\\/+$/, '') : path;\n}\n\n// own entries only: a tag named constructor in a message must not find the one on Object\nfunction linkFor(links: Record<string, RichLink> | undefined, name: string): RichLink | undefined {\n return links && Object.hasOwn(links, name) ? links[name] : undefined;\n}\n\n// only the names this message actually renders: a global map has entries other messages use\nfunction usedLinks(\n nodes: TagNode[],\n links: Record<string, RichLink>,\n): Record<string, RichLink> | undefined {\n const out: Record<string, RichLink> = {};\n const walk = (list: TagNode[]): void => {\n for (const node of list) {\n if (typeof node === 'string') continue;\n const link = linkFor(links, node.name);\n if (link !== undefined) out[node.name] = link;\n walk(node.children);\n }\n };\n walk(nodes);\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n// same rule as an author's href, applied to the links a message renders through its map\nfunction mirroredLinks(\n links: Record<string, RichLink> | undefined,\n mirror: MirrorLinks,\n): Record<string, RichLink> | undefined {\n if (!links) return links;\n const out: Record<string, RichLink> = {};\n for (const [name, link] of Object.entries(links)) {\n const href = typeof link === 'string' ? link : link.href;\n const inside = mirroredHref(href, mirror);\n if (inside === undefined) out[name] = link;\n else out[name] = typeof link === 'string' ? inside : { ...link, href: inside };\n }\n return out;\n}\n\n// only a root-relative link to a page the mirror contains: assets, externals and anchors stay\nfunction mirroredHref(raw: string | undefined, mirror: MirrorLinks): string | undefined {\n if (raw === undefined) return undefined;\n const href = decodeEntities(raw);\n if (!href.startsWith('/') || href.startsWith('//')) return undefined;\n const base = mirror.base ?? '';\n // hrefs carry the base the site is served under, the page set never does: compare like with like\n const inside = base ? stripBase(href, base) : href;\n if (base && inside === href) return undefined;\n const cut = inside.search(/[?#]/);\n const path = cut < 0 ? inside : inside.slice(0, cut);\n if (!mirror.pages.has(publicPath(path.replace(/^\\//, '')))) return undefined;\n return `${base}${mirror.prefix}${inside}`;\n}\n\n// the boundary check is what keeps base /app from swallowing /application\nfunction stripBase(path: string, base: string): string {\n if (!path.startsWith(base)) return path;\n const rest = path.slice(base.length);\n if (rest === '') return '/';\n return rest.startsWith('/') ? rest : path;\n}\n\n// 'app', '/app' and '/app/' all read as '/app'; nothing means the site sits at the root\nfunction normalizeBase(base: string | undefined): string {\n const trimmed = base?.replace(/^\\/+/, '').replace(/\\/+$/, '');\n return trimmed ? `/${trimmed}` : '';\n}\n\n// the narrowing of matchPathSegment, inlined: render == runtime has to hold here too\nconst REDIRECT_BODY =\n '(function(){var T=/^[a-z]{2,3}(-[a-z]{4})?(-([a-z]{2}|[0-9]{3}))?$/i;' +\n 'function M(t,g){t=String(t||\"\");if(S.indexOf(t)>=0)return t;if(g&&!T.test(t))return;' +\n 'while(t){var i=t.lastIndexOf(\"-\");if(i<0)return;t=t.slice(0,i);if(S.indexOf(t)>=0)return t}}' +\n 'var p=location.pathname;' +\n 'if(B){if(p.indexOf(B)!==0)return;p=p.slice(B.length)||\"/\";if(p.charAt(0)!==\"/\")return}' +\n 'if(M(p.split(\"/\")[1],1))return;' +\n 'var w;if(K)try{w=M(localStorage.getItem(K))}catch(e){}' +\n 'if(!w){var l=navigator.languages||[navigator.language];for(var i=0;i<l.length&&!w;i++)w=M(l[i])}' +\n 'if(!w||w===D)return;location.replace(B+\"/\"+w+p+location.search+location.hash)})()';\n\n// </script> can never appear in a locale code, but a catalog is untrusted and this costs nothing\nfunction jsLiteral(value: unknown): string {\n return JSON.stringify(value ?? null).replace(/</g, '\\\\u003c');\n}\n\n// pre-paint, in the source tree only: the mirror page a visitor lands on is already the answer\nfunction redirectScript(options: RedirectScript): string {\n const vars = [\n `S=${jsLiteral(options.locales)}`,\n `D=${jsLiteral(options.sourceLocale)}`,\n `B=${jsLiteral(normalizeBase(options.base))}`,\n `K=${options.storageKey === false ? 'null' : jsLiteral(options.storageKey ?? LOCALE_STORAGE_KEY)}`,\n ].join(',');\n return `<script>var ${vars};${REDIRECT_BODY};</script>`;\n}\n\n// goes first in <head> so it runs before a stylesheet can paint, idempotent via markers\nfunction injectRedirect(ms: MagicString, html: string, options: RedirectScript): void {\n const block = `${REDIRECT_OPEN}${redirectScript(options)}${REDIRECT_CLOSE}`;\n const from = html.indexOf(REDIRECT_OPEN);\n if (from !== -1) {\n const to = html.indexOf(REDIRECT_CLOSE, from);\n if (to !== -1) {\n const end = to + REDIRECT_CLOSE.length;\n if (html.slice(from, end) !== block) ms.overwrite(from, end, block);\n return;\n }\n }\n const head = /<head\\b(?:\"[^\"]*\"|'[^']*'|[^\"'>])*>/i.exec(html);\n if (head) ms.appendRight(head.index + head[0].length, block);\n}\n\n// injects <link rel=\"alternate\" hreflang> into <head>, idempotent via markers\nfunction injectAlternates(ms: MagicString, html: string, alternates: Alternate[]): void {\n const links = alternates\n .map(\n (a) =>\n `<link rel=\"alternate\" hreflang=\"${escapeAttr(a.hreflang)}\" href=\"${escapeAttr(a.href)}\">`,\n )\n .join('');\n const block = `${HREFLANG_OPEN}${links}${HREFLANG_CLOSE}`;\n const from = html.indexOf(HREFLANG_OPEN);\n if (from !== -1) {\n const to = html.indexOf(HREFLANG_CLOSE, from);\n if (to !== -1) {\n const end = to + HREFLANG_CLOSE.length;\n if (html.slice(from, end) !== block) ms.overwrite(from, end, block);\n return;\n }\n }\n const head = /<\\/head\\s*>/i.exec(html);\n if (head) ms.appendLeft(head.index, block);\n}\n\n// inlines the slice this page needs, so a mirrored page fetches no catalog at all\nfunction injectCatalog(ms: MagicString, html: string, messages: Record<string, string>): void {\n // <!-- opens a state where the closing </script> no longer closes, and JSON has no escape for it\n const json = JSON.stringify(messages).replace(/<\\//g, '<\\\\/').replace(/<!--/g, '\\\\u003c!--');\n const tag = `<script ${CATALOG_SCRIPT} type=\"application/json\">${json}</script>`;\n const block = `${CATALOG_OPEN}${tag}${CATALOG_CLOSE}`;\n const from = html.indexOf(CATALOG_OPEN);\n if (from !== -1) {\n const to = html.indexOf(CATALOG_CLOSE, from);\n if (to !== -1) {\n const end = to + CATALOG_CLOSE.length;\n if (html.slice(from, end) !== block) ms.overwrite(from, end, block);\n return;\n }\n }\n const head = /<\\/head\\s*>/i.exec(html);\n if (head) ms.appendLeft(head.index, block);\n}\n\nexport interface RenderSiteOptions {\n site?: string;\n locales?: string[];\n attribute?: string;\n richTags?: string[];\n richLinks?: Record<string, RichLink>;\n base?: string;\n baseUrl?: string;\n hreflang?: boolean;\n exclude?: string[];\n sitemap?: boolean | string;\n redirect?: boolean | RedirectConfig;\n clean?: boolean;\n}\n\nexport interface RenderSiteResult {\n files: number;\n locales: string[];\n missing: Record<string, string[]>;\n untranslatedHead: string[];\n}\n\nconst TITLE_TAG = /<title\\b([^>]*)>/i;\nconst REFRESH_META = /<meta\\b[^>]*http-equiv\\s*=\\s*[\"']?refresh/i;\n\nconst NOINDEX_META = /<meta\\b[^>]*name\\s*=\\s*[\"']?robots[\"']?[^>]*content\\s*=\\s*[\"'][^\"']*noindex/i;\n\n// the mirror still publishes these, they are simply never search results\nfunction isIndexable(html: string): boolean {\n return !REFRESH_META.test(html) && !NOINDEX_META.test(html);\n}\n\n// a <title> with no key ships the source language everywhere, and it is most of a search result\nfunction headIsBound(html: string, attr: string): boolean {\n // a page that only redirects is never a search result, so its title is nobody's to translate\n if (REFRESH_META.test(html)) return true;\n const title = TITLE_TAG.exec(html);\n return title ? title[1]!.includes(attr) : true;\n}\n\n// mirrors the built site per locale: dist/index.html → dist/<locale>/index.html\nexport async function renderSite(\n cfg: ResolvedConfig,\n options: RenderSiteOptions = {},\n): Promise<RenderSiteResult> {\n const site = join(cfg.root, options.site ?? cfg.render.site ?? 'dist');\n const locales = options.locales ?? cfg.locales;\n const attribute = options.attribute ?? cfg.render.attribute;\n const base = normalizeBase(options.base ?? cfg.render.base);\n const baseUrl = (options.baseUrl ?? cfg.render.baseUrl)?.replace(/\\/+$/, '');\n const wantHreflang = (options.hreflang ?? cfg.render.hreflang ?? true) && baseUrl !== undefined;\n // the escape hatch for a page that is indexable and still not ours to list\n const patterns = options.exclude ?? cfg.render.exclude ?? [];\n const excluded = patterns.length > 0 ? picomatch(patterns) : () => false;\n const sitemap = options.sitemap ?? cfg.render.sitemap ?? false;\n const wantSitemap = sitemap !== false && baseUrl !== undefined;\n const clean = options.clean ?? cfg.render.clean ?? false;\n const wanted = options.redirect ?? cfg.render.redirect ?? false;\n const redirect = wanted === false ? undefined : wanted === true ? {} : wanted;\n const script: RedirectScript | undefined = redirect && {\n locales,\n sourceLocale: cfg.sourceLocale,\n base,\n storageKey: redirect.storageKey,\n };\n // the text the build ships, or the pre-filled page and the runtime that repaints it disagree\n const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), await extractProject(cfg));\n // one runtime per locale for the whole run: rebuilding it per page reflattened every catalog\n const instances = new Map(\n locales.map((locale) => [locale, localeInstance(catalogs, locale, cfg.sourceLocale)]),\n );\n\n if (clean) {\n for (const locale of locales) {\n if (locale !== cfg.sourceLocale) rmSync(join(site, locale), { recursive: true, force: true });\n }\n }\n\n const files = await glob('**/*.html', {\n cwd: site,\n absolute: true,\n ignore: locales.map((locale) => `${locale}/**`),\n });\n\n // every page the mirror will hold, so a link into one of them can keep the visitor inside\n const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\\\/g, '/'))));\n\n const missing: Record<string, string[]> = {};\n const untranslatedHead: string[] = [];\n const urls: Array<{ rel: string; alternates: Alternate[] }> = [];\n for (const file of files) {\n const html = readFileSync(file, 'utf8');\n const rel = relative(site, file).replace(/\\\\/g, '/');\n // one locale is not a mirror, so there is no second title for this one to disagree with\n if (locales.length > 1 && !headIsBound(html, attribute ?? 'data-verbaly')) {\n untranslatedHead.push(rel);\n }\n const alternates = wantHreflang ? pageAlternates(baseUrl!, rel, locales, cfg.sourceLocale) : [];\n if (wantHreflang && isIndexable(html) && !excluded(rel)) urls.push({ rel, alternates });\n // only the source tree carries it: the mirror page a visitor reaches is already the answer\n const routed = script && (redirect!.on === 'all' || rel === 'index.html');\n for (const locale of locales) {\n const result = renderHtml(html, {\n locale,\n instance: instances.get(locale)!,\n sourceLocale: cfg.sourceLocale,\n attribute,\n richTags: options.richTags,\n richLinks: options.richLinks ?? cfg.render.links,\n alternates,\n mirror: locale === cfg.sourceLocale ? undefined : { prefix: `/${locale}`, base, pages },\n redirect: routed && locale === cfg.sourceLocale ? script : undefined,\n inlineCatalog: cfg.render.inlineCatalog === true,\n });\n for (const key of result.missing) {\n const list = (missing[locale] ??= []);\n if (!list.includes(key)) list.push(key);\n }\n const out = locale === cfg.sourceLocale ? file : join(site, locale, rel);\n mkdirSync(dirname(out), { recursive: true });\n writeFileSync(out, result.html);\n }\n }\n\n if (wantSitemap && urls.length) {\n const name = typeof sitemap === 'string' ? sitemap : 'sitemap-i18n.xml';\n writeFileSync(join(site, name), buildSitemap(urls));\n }\n\n return { files: files.length, locales: [...locales], missing, untranslatedHead };\n}\n\n// the cli and @verbaly/astro both run the mirror, so what it warns about is written once\nexport function formatRenderWarnings(result: RenderSiteResult, sourceLocale: string): string[] {\n const lines: string[] = [];\n for (const [locale, keys] of Object.entries(result.missing)) {\n lines.push(` ${locale}: ${counted(keys.length, 'key')} not pre-filled: ${keys.join(', ')}`);\n }\n if (result.untranslatedHead.length > 0) {\n lines.push(\n ` ${counted(result.untranslatedHead.length, 'page')} of ${result.files} ship the same <title> in every locale (${result.untranslatedHead[0]}), so search results read in ${sourceLocale}`,\n ` fix: bind the head too, <title data-verbaly=\"key\"> and a meta through data-verbaly-attr`,\n );\n }\n return lines;\n}\n\n// request path of a built page path (index.html → directory URL)\nfunction pagePath(rel: string): string {\n const path = rel.replace(/(^|\\/)index\\.html$/, '$1');\n return path ? `/${path}` : '/';\n}\n\n// reciprocal hreflang set for one page, from core: an SSR head has to write the same one\nfunction pageAlternates(\n baseUrl: string,\n rel: string,\n locales: string[],\n sourceLocale: string,\n): Alternate[] {\n return alternateLinks({\n supported: locales,\n sourceLocale,\n path: pagePath(rel),\n routing: 'prefix-except-source',\n baseUrl,\n });\n}\n\nfunction buildSitemap(urls: Array<{ rel: string; alternates: Alternate[] }>): string {\n const body = urls\n .flatMap(({ alternates }) => {\n const alts = alternates\n .map(\n (a) =>\n `<xhtml:link rel=\"alternate\" hreflang=\"${a.hreflang}\" href=\"${escapeAttr(a.href)}\"/>`,\n )\n .join('');\n return alternates\n .filter((a) => a.hreflang !== 'x-default')\n .map((self) => `<url><loc>${escapeAttr(self.href)}</loc>${alts}</url>`);\n })\n .join('');\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">${body}</urlset>\\n`;\n}\n\nfunction parseAttrs(chunk: string): Map<string, string> {\n const attrs = new Map<string, string>();\n ATTR.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = ATTR.exec(chunk)) !== null) {\n attrs.set(m[1]!.toLowerCase(), m[2] ?? m[3] ?? m[4] ?? '');\n }\n return attrs;\n}\n\n// three attributes share this parser, so the report names the one that is actually malformed\nfunction parseArgs(raw: string | undefined, attribute: string): Params | undefined {\n if (!raw) return undefined;\n try {\n return JSON.parse(decodeEntities(raw)) as Params;\n } catch {\n // a page is mirrored once per locale, so a raw warn says the same thing once per tree\n warnOnce(`invalid JSON in ${attribute}: ${raw}`, `${attribute}:${raw}`);\n return undefined;\n }\n}\n\n// comments and script/style bodies are opaque to the scanner\nfunction protectedRanges(html: string): Array<[number, number]> {\n const ranges: Array<[number, number]> = [];\n const re = /<!--[\\s\\S]*?-->|<script\\b[\\s\\S]*?<\\/script\\s*>|<style\\b[\\s\\S]*?<\\/style\\s*>/gi;\n let m: RegExpExecArray | null;\n while ((m = re.exec(html)) !== null) {\n // keep script/style open tags scannable; protect only their bodies\n const openEnd = m[0].startsWith('<!--') ? m.index : html.indexOf('>', m.index) + 1;\n ranges.push([openEnd, m.index + m[0].length]);\n }\n return ranges;\n}\n\nfunction findClose(\n html: string,\n tagName: string,\n from: number,\n inSkip: (index: number) => boolean,\n): { contentEnd: number } | null {\n const re = new RegExp(\n `<${tagName}(?=[\\\\s/>])(?:\"[^\"]*\"|'[^']*'|[^\"'>])*>|</${tagName}\\\\s*>`,\n 'gi',\n );\n re.lastIndex = from;\n let depth = 1;\n let m: RegExpExecArray | null;\n while ((m = re.exec(html)) !== null) {\n if (inSkip(m.index)) continue;\n if (m[0][1] === '/') {\n depth -= 1;\n if (depth === 0) return { contentEnd: m.index };\n } else if (!m[0].endsWith('/>')) {\n depth += 1;\n }\n }\n return null;\n}\n\nfunction setAttribute(\n ms: MagicString,\n html: string,\n chunkStart: number,\n openEnd: number,\n attrChunk: string,\n name: string,\n value: string,\n): void {\n const escaped = escapeAttr(value);\n const existing = new RegExp(`(\\\\s${name}\\\\s*=\\\\s*)(\"[^\"]*\"|'[^']*'|[^\\\\s>]+)`, 'i').exec(\n attrChunk,\n );\n if (existing) {\n const valueStart = chunkStart + existing.index + existing[1]!.length;\n const valueEnd = valueStart + existing[2]!.length;\n if (html.slice(valueStart, valueEnd) !== `\"${escaped}\"`) {\n ms.overwrite(valueStart, valueEnd, `\"${escaped}\"`);\n }\n return;\n }\n const selfClosing = html.slice(openEnd - 2, openEnd) === '/>';\n const insertAt = openEnd - (selfClosing ? 2 : 1);\n ms.appendLeft(insertAt, ` ${name}=\"${escaped}\"`);\n}\n\nfunction richToHtml(\n nodes: TagNode[],\n allowed: Set<string>,\n links?: Record<string, RichLink>,\n): string {\n let out = '';\n for (const node of nodes) {\n const link = typeof node === 'string' ? undefined : linkFor(links, node.name);\n if (typeof node === 'string') {\n out += escapeHtml(node);\n } else if (link !== undefined) {\n const { href, target, rel } = normalizeLink(link);\n let attrs = href !== undefined ? ` href=\"${escapeAttr(href)}\"` : '';\n if (target) attrs += ` target=\"${escapeAttr(target)}\"`;\n if (rel) attrs += ` rel=\"${escapeAttr(rel)}\"`;\n out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;\n } else if (allowed.has(node.name)) {\n out += VOID.has(node.name)\n ? `<${node.name}>`\n : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;\n } else {\n out += richToHtml(node.children, allowed, links); // unknown tag → unwrap\n }\n }\n return out;\n}\n\nfunction escapeHtml(text: string): string {\n return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n}\n\nfunction escapeAttr(text: string): string {\n return escapeHtml(text).replace(/\"/g, '"');\n}\n\nfunction decodeEntities(text: string): string {\n return text\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/&/g, '&');\n}\n","import { lstatSync, readdirSync, watch, type FSWatcher } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type { ResolvedConfig } from './config';\nimport { SOURCE_FILE_RE } from './plugin';\n\n// only these watch a tree natively: elsewhere Node walks it in sync and watches every entry\nconst NATIVE_TREE = process.platform === 'darwin' || process.platform === 'win32';\n\nexport interface TreeOptions {\n keep?: string;\n native?: boolean;\n persistent?: boolean;\n}\n\n// every change under root, named from root; node_modules alone can use up the inotify limit\nexport function watchTree(\n root: string,\n options: TreeOptions,\n onFile: (file: string) => void,\n): () => void {\n // by top-level name, '' being the root itself\n const watchers = new Map<string, FSWatcher>();\n const close = (name: string): void => {\n watchers.get(name)?.close();\n watchers.delete(name);\n };\n const open = (\n name: string,\n recursive: boolean,\n listener: (event: string, file: string | null) => void,\n ): void => {\n const watcher = watch(\n join(root, name),\n { recursive, persistent: options.persistent ?? true },\n listener,\n );\n // an error nobody listens to ends the process, and a quiet stop would end the watching\n watcher.on('error', (error) => {\n close(name);\n console.warn(`[verbaly] stopped watching ${name || 'the project'}:`, error);\n });\n watchers.set(name, watcher);\n };\n\n if (options.native ?? NATIVE_TREE) {\n open('', true, (_event, file) => {\n if (file) onFile(file);\n });\n } else {\n // the top level by hand, so a directory that holds no code is never walked at all\n const sync = (name: string): void => {\n // the root hears of a directory only when it is made, removed or moved: reopen, never reuse\n close(name);\n if (name !== options.keep && (name === 'node_modules' || name.startsWith('.'))) return;\n try {\n // lstat: a linked directory is not walked, the same as at startup and as native watching\n if (!lstatSync(join(root, name)).isDirectory()) return;\n open(name, true, (_event, file) => {\n if (file) onFile(`${name}/${file}`);\n });\n } catch (error) {\n // a throw in a watch callback ends the process: say a watch limit, not a vanished dir\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n console.warn(`[verbaly] could not watch ${name}:`, error);\n }\n }\n };\n open('', false, (event, file) => {\n if (!file) return;\n // a change is the same directory touched, and reopening it would walk the whole tree again\n if (event === 'rename') sync(file);\n onFile(file);\n });\n for (const entry of readdirSync(root, { withFileTypes: true })) {\n if (entry.isDirectory()) sync(entry.name);\n }\n }\n return () => {\n for (const name of [...watchers.keys()]) close(name);\n };\n}\n\nexport interface WatchProjectOptions {\n debounce?: number;\n}\n\n// source files only: extract's own catalog/dts writes must never retrigger a run\nexport function watchProject(\n cfg: ResolvedConfig,\n run: () => Promise<void>,\n options: WatchProjectOptions = {},\n): () => void {\n const catalogDir = relative(cfg.root, cfg.dir).replaceAll('\\\\', '/');\n let timer: ReturnType<typeof setTimeout> | undefined;\n let running = false;\n let queued = false;\n\n async function refresh(): Promise<void> {\n if (running) {\n queued = true;\n return;\n }\n running = true;\n try {\n await run();\n } catch (error) {\n console.warn('[verbaly] watch run failed:', error);\n } finally {\n running = false;\n if (queued) {\n queued = false;\n schedule();\n }\n }\n }\n\n function schedule(): void {\n clearTimeout(timer);\n timer = setTimeout(() => void refresh(), options.debounce ?? 150);\n }\n\n const close = watchTree(cfg.root, {}, (filename) => {\n if (!filename) return;\n const file = filename.replaceAll('\\\\', '/');\n if (file.includes('node_modules/') || file.endsWith('.d.ts')) return;\n if (catalogDir && file.startsWith(`${catalogDir}/`)) return;\n if (SOURCE_FILE_RE.test(file)) schedule();\n });\n\n return (): void => {\n clearTimeout(timer);\n close();\n };\n}\n","import { readFileSync, writeFileSync } from 'node:fs';\nimport { relative } from 'node:path';\nimport { parse } from '@babel/parser';\nimport MagicString from 'magic-string';\nimport { glob } from 'tinyglobby';\nimport { cleanJsxText, isTReference, walk, type AstNode } from './analyze';\nimport type { ResolvedConfig } from './config';\n\nexport interface WrapEntry {\n file: string;\n line: number;\n text: string;\n kind: 'text' | 'attribute';\n attribute?: string;\n}\n\nexport interface WrapSkip {\n file: string;\n line: number;\n text: string;\n reason: string;\n}\n\n// a file wrap could rewrite but will not, because the rewrite would not compile\nexport interface WrapBlocked {\n file: string;\n texts: number;\n client: boolean;\n}\n\nexport interface WrapResult {\n files: number;\n changed: string[];\n wrapped: WrapEntry[];\n skipped: WrapSkip[];\n blocked: WrapBlocked[];\n}\n\nexport interface WrapOptions {\n write?: boolean;\n}\n\n// user-visible string attributes worth translating; everything else stays code\nconst WRAP_ATTRS = new Set(['title', 'alt', 'placeholder', 'aria-label']);\n\n// their content is code or preformatted output, never interface copy\nconst CODE_TAGS = new Set(['code', 'pre', 'kbd', 'samp', 'var']);\n\nconst T_NAMES: ReadonlySet<string> = new Set(['t']);\nconst LETTER = /\\p{L}/u;\nconst WHITESPACE = /\\s/;\n\n// onboarding codemod: errs on skipping, never on inventing (ambiguous goes to the report)\nexport async function wrapProject(\n cfg: ResolvedConfig,\n options: WrapOptions = {},\n): Promise<WrapResult> {\n const files = (\n await glob(cfg.include, { cwd: cfg.root, ignore: cfg.exclude, absolute: true })\n ).filter((file) => /\\.[jt]sx$/.test(file));\n\n const result: WrapResult = {\n files: files.length,\n changed: [],\n wrapped: [],\n skipped: [],\n blocked: [],\n };\n\n for (const file of files) {\n const code = readFileSync(file, 'utf8');\n const label = relative(cfg.root, file).replaceAll('\\\\', '/');\n const out = wrapCode(code, label);\n result.wrapped.push(...out.wrapped);\n result.skipped.push(...out.skipped);\n if (out.code === undefined) continue;\n result.changed.push(label);\n // writing a t call into a file with no t is how wrap left 32 files uncompilable\n if (!out.hasT) {\n result.blocked.push({ file: label, texts: out.wrapped.length, client: out.client });\n continue;\n }\n if (options.write) writeFileSync(file, out.code);\n }\n return result;\n}\n\nexport interface WrapCodeResult {\n code?: string;\n wrapped: WrapEntry[];\n skipped: WrapSkip[];\n hasT: boolean;\n client: boolean;\n}\n\nexport function wrapCode(code: string, file: string): WrapCodeResult {\n const wrapped: WrapEntry[] = [];\n const skipped: WrapSkip[] = [];\n\n let ast: AstNode;\n try {\n ast = parse(code, {\n sourceType: 'module',\n errorRecovery: true,\n plugins: ['typescript', 'jsx'],\n }).program as unknown as AstNode;\n } catch {\n return { wrapped, skipped, hasT: false, client: false }; // unparseable file: leave it alone\n }\n\n const hasT = declaresT(ast);\n const client = hasDirective(ast, 'use client');\n const s = new MagicString(code);\n const visited = new Set<AstNode>();\n let changed = false;\n\n walk(ast, (node) => {\n if (node.type !== 'JSXElement' && node.type !== 'JSXFragment') return;\n if (visited.has(node)) return;\n processElement(node);\n });\n\n return changed\n ? { code: s.toString(), wrapped, skipped, hasT, client }\n : { wrapped, skipped, hasT, client };\n\n function processElement(node: AstNode): void {\n visited.add(node);\n\n if (node.type === 'JSXElement') {\n const opening = node.openingElement as AstNode;\n const name = opening.name as AstNode;\n // <Trans> children and data-verbaly subtrees are already message-managed\n if (name.type === 'JSXIdentifier' && name.name === 'Trans') return markSubtree(node);\n if (hasVerbalyAttr(opening)) return markSubtree(node);\n if (name.type === 'JSXIdentifier' && CODE_TAGS.has(name.name as string)) {\n return markSubtree(node);\n }\n wrapAttributes(opening);\n }\n\n const children = (node.children as AstNode[] | undefined) ?? [];\n const hasElementChild = children.some(\n (c) => c.type === 'JSXElement' || c.type === 'JSXFragment',\n );\n const hasText = children.some(\n (c) =>\n (c.type === 'JSXText' && LETTER.test(c.value as string)) ||\n (c.type === 'JSXExpressionContainer' &&\n (c.expression as AstNode).type === 'StringLiteral' &&\n LETTER.test((c.expression as AstNode).value as string)),\n );\n\n if (hasElementChild && hasText) {\n // splitting the sentence into fragments would ship broken translations\n skip(node, snippet(children), 'mixed text and markup: wrap by hand or use <Trans>');\n return markSubtree(node);\n }\n if (hasText) {\n wrapSegment(node, children);\n return markSubtree(node);\n }\n for (const child of children) {\n if (child.type === 'JSXElement' || child.type === 'JSXFragment') processElement(child);\n }\n }\n\n function wrapSegment(parent: AstNode, children: AstNode[]): void {\n const meaningful = children.filter(\n (c) =>\n (c.type === 'JSXText' && (c.value as string).trim() !== '') ||\n (c.type === 'JSXExpressionContainer' &&\n (c.expression as AstNode).type !== 'JSXEmptyExpression'),\n );\n if (meaningful.length === 0) return;\n\n const first = meaningful[0]!;\n const last = meaningful[meaningful.length - 1]!;\n\n // a message opening with an interpolation is a fragment: the translator never sees the sentence\n if (first.type === 'JSXExpressionContainer' && meaningful.length > 1) {\n skip(parent, snippet(children), 'starts with an interpolation: wrap the sentence by hand');\n return;\n }\n\n let template = '';\n let report = '';\n for (let i = children.indexOf(first); i <= children.indexOf(last); i++) {\n const child = children[i]!;\n if (child.type === 'JSXText') {\n let value = cleanJsxText(child.value as string);\n if (child === first) value = value.trimStart();\n if (child === last) value = value.trimEnd();\n template += escapeTemplate(value);\n report += value;\n } else if (child.type === 'JSXExpressionContainer') {\n const expr = child.expression as AstNode;\n if (expr.type === 'JSXEmptyExpression') continue;\n if (usesT(expr)) {\n skip(parent, snippet(children), 'already uses t: finish it by hand');\n return;\n }\n if (containsJsx(expr)) {\n skip(\n parent,\n snippet(children),\n 'an expression renders markup: wrap by hand or use <Trans>',\n );\n markSubtree(child);\n return;\n }\n if (expr.type === 'StringLiteral') {\n template += escapeTemplate(expr.value as string);\n report += expr.value as string;\n } else {\n const source = code.slice(expr.start, expr.end);\n template += '${' + source + '}';\n report += '${' + source + '}';\n }\n } else {\n return; // spread children and friends: bail quietly\n }\n }\n if (!LETTER.test(report)) return;\n if (isIdentifierLike(report)) return;\n\n const start =\n first.type === 'JSXText' ? first.start + leadingWs(first.value as string) : first.start;\n const end = last.type === 'JSXText' ? last.end - trailingWs(last.value as string) : last.end;\n\n s.overwrite(start, end, '{t`' + template + '`}');\n changed = true;\n wrapped.push({ file, line: line(first), text: report, kind: 'text' });\n }\n\n function wrapAttributes(opening: AstNode): void {\n for (const attr of opening.attributes as AstNode[]) {\n if (attr.type !== 'JSXAttribute') continue;\n const name = attr.name as AstNode;\n if (name.type !== 'JSXIdentifier' || !WRAP_ATTRS.has(name.name as string)) continue;\n const value = attr.value as AstNode | null;\n if (value?.type !== 'StringLiteral') continue;\n const raw = value.value as string;\n if (!LETTER.test(raw) || isIdentifierLike(raw)) continue;\n s.overwrite(value.start, value.end, '{t`' + escapeTemplate(raw) + '`}');\n changed = true;\n wrapped.push({\n file,\n line: line(value),\n text: raw,\n kind: 'attribute',\n attribute: name.name as string,\n });\n }\n }\n\n function skip(node: AstNode, text: string, reason: string): void {\n skipped.push({ file, line: line(node), text, reason });\n }\n\n function snippet(children: AstNode[]): string {\n const start = children[0]?.start ?? 0;\n const end = children[children.length - 1]?.end ?? start;\n const text = code.slice(start, end).replace(/\\s+/g, ' ').trim();\n return text.length > 60 ? text.slice(0, 59) + '…' : text;\n }\n\n function markSubtree(node: AstNode): void {\n walk(node, (n) => {\n if (n.type === 'JSXElement' || n.type === 'JSXFragment') visited.add(n);\n });\n }\n}\n\n// one lowercase token with no space is a slug, a handle or a value, not a sentence someone wrote\nfunction isIdentifierLike(text: string): boolean {\n const trimmed = text.trim();\n if (WHITESPACE.test(trimmed)) return false;\n const first = [...trimmed].find((char) => LETTER.test(char));\n return first !== undefined && first !== first.toUpperCase();\n}\n\n// a directive is the only way a file states which side it renders on\nfunction hasDirective(program: AstNode, value: string): boolean {\n const directives = (program.directives as AstNode[] | undefined) ?? [];\n return directives.some((d) => ((d.value as AstNode | undefined)?.value as string) === value);\n}\n\n// a t call written where nothing binds t does not compile, so wrap has to know before it writes\nfunction declaresT(program: AstNode): boolean {\n let found = false;\n walk(program, (node) => {\n if (found) return;\n if (node.type === 'ImportDeclaration') {\n for (const spec of node.specifiers as AstNode[]) {\n if (isTName((spec.local as AstNode | undefined)?.name)) found = true;\n }\n return;\n }\n if (node.type === 'VariableDeclarator' && bindsT(node.id as AstNode)) found = true;\n if (node.type === 'FunctionDeclaration' && isTName((node.id as AstNode | undefined)?.name)) {\n found = true;\n }\n const params = node.params as AstNode[] | undefined;\n if (params?.some((param) => bindsT(param))) found = true;\n });\n return found;\n}\n\nfunction bindsT(pattern: AstNode | undefined): boolean {\n if (!pattern) return false;\n if (pattern.type === 'Identifier') return isTName(pattern.name);\n if (pattern.type === 'AssignmentPattern') return bindsT(pattern.left as AstNode);\n if (pattern.type === 'ObjectPattern') {\n return (pattern.properties as AstNode[]).some((prop) =>\n prop.type === 'RestElement'\n ? bindsT(prop.argument as AstNode)\n : bindsT(prop.value as AstNode),\n );\n }\n if (pattern.type === 'ArrayPattern') {\n return (pattern.elements as (AstNode | null)[]).some((el) => bindsT(el ?? undefined));\n }\n return false;\n}\n\nfunction isTName(name: unknown): boolean {\n return typeof name === 'string' && T_NAMES.has(name);\n}\n\nfunction hasVerbalyAttr(opening: AstNode): boolean {\n return (opening.attributes as AstNode[]).some((attr) => {\n if (attr.type !== 'JSXAttribute') return false;\n const name = attr.name as AstNode;\n return name.type === 'JSXIdentifier' && (name.name as string).startsWith('data-verbaly');\n });\n}\n\n// a t`…` / t(...) / t.id anywhere in the expression means a human already started here\nfunction usesT(node: AstNode): boolean {\n let found = false;\n walk(node, (n) => {\n if (n.type === 'TaggedTemplateExpression' && isTReference(n.tag as AstNode, T_NAMES)) {\n found = true;\n }\n if (n.type === 'CallExpression' && isTReference(n.callee as AstNode, T_NAMES)) found = true;\n });\n return found;\n}\n\nfunction containsJsx(node: AstNode): boolean {\n let found = false;\n walk(node, (n) => {\n if (n.type === 'JSXElement' || n.type === 'JSXFragment') found = true;\n });\n return found;\n}\n\n// literal text run → template-literal-safe\nfunction escapeTemplate(text: string): string {\n return text.replace(/[\\\\`]/g, '\\\\$&').replace(/\\$\\{/g, '\\\\${');\n}\n\nfunction leadingWs(text: string): number {\n return text.length - text.trimStart().length;\n}\n\nfunction trailingWs(text: string): number {\n return text.length - text.trimEnd().length;\n}\n\nfunction line(node: AstNode): number {\n const loc = node.loc as { start?: { line?: number } } | undefined;\n return loc?.start?.line ?? 1;\n}\n","import { relative } from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { loadCatalogs, writeCatalog } from './catalog';\nimport {\n check,\n checkNextSteps,\n formatCheckResult,\n formatCheckWarnings,\n githubCheckAnnotations,\n} from './check';\nimport { writeDts } from './codegen';\nimport { loadConfig, type ResolvedConfig } from './config';\nimport { doctor, formatDoctorEntry } from './doctor';\nimport { exportCatalogs, importCatalogs, isMobileFormat, type ExportFormat } from './exchange';\nimport { collectOrigins, extractProject, shippedCatalogs } from './extract';\nimport { createDevReporter, formatFinding } from './findings';\nimport { init } from './init';\nimport { migrateCatalogs } from './migrate';\nimport { syncProject } from './project';\nimport { PSEUDO_LOCALE, pseudoCatalogs } from './pseudo';\nimport { formatRenderWarnings, renderSite } from './render';\nimport {\n acceptOutdated,\n clearDrafts,\n effectiveDrafts,\n loadState,\n outdatedTranslations,\n readState,\n recordTranslations,\n saveState,\n type State,\n type TranslationWrite,\n} from './state';\nimport { formatStatusResult, status } from './status';\nimport { counted, truncate } from './text';\nimport {\n formatTranslateFailures,\n mergeTranslations,\n resolveProvider,\n translateCatalogs,\n type TranslateProgress,\n} from './translate';\nimport { watchProject } from './watch';\nimport { wrapProject } from './wrap';\n\nconst HELP = `verbaly · i18n compiler\n\nUsage:\n verbaly init scaffold config + locale catalogs (detects your framework)\n verbaly doctor diagnose the setup (config, catalogs, plugin, types, keys)\n verbaly wrap find hardcoded JSX text and wrap it in t\\`…\\` (report; --write applies)\n verbaly migrate port catalogs from another i18n library (report; --write applies)\n verbaly extract scan sources, update catalogs and types\n verbaly typegen write the TypeScript types only (CI: run it before tsc)\n verbaly status translation coverage per locale, at a glance\n verbaly check verify translations are complete (CI)\n verbaly translate fill missing translations via a provider (default: claude)\n verbaly review [keys…] list translations awaiting review: machine drafts and outdated ones (--approve accepts them)\n verbaly export write translator files (XLIFF 2.0, CSV, gettext PO) or mobile resources (Android, iOS)\n verbaly import <files…> fill catalogs back from translated XLIFF/CSV/PO files\n verbaly pseudo generate a pseudo-locale catalog for i18n QA (default: en-XA)\n verbaly render pre-fill data-verbaly HTML per locale (SSG, kills the FOUC)\n\nOptions:\n --root <path> project root (default: cwd)\n --dir <path> catalogs directory (default: locales)\n --source <locale> source locale (default: en)\n --locales <csv> run on these locales only, the source always included (init: the ones to create)\n --prune drop keys no longer referenced (extract)\n --watch keep extracting as source files change (extract)\n --write apply the rewrites instead of only reporting (wrap, migrate)\n --plurals also merge _one/_other into one message with variants (migrate)\n --json machine-readable output (status)\n --drafts also fail on unreviewed machine translations (check)\n --outdated also fail on translations written for an older source text (check)\n --approve accept what review lists, drafts and outdated, or only the keys given (review)\n --reporter <name> failure format: text (default) or github annotations (check)\n --model <id> model override for the claude provider (translate)\n --dry-run list what would happen, write nothing (translate, import, extract)\n --format <f> export format: xliff (default), csv, po, android-xml or ios-strings (export)\n --out <path> export directory (export, default: verbaly-export)\n --missing export only untranslated entries (export)\n --overwrite replace existing translations on import (import)\n --draft mark what the files bring as drafts a person still has to review (import)\n --locale <id> pseudo-locale id (pseudo) / one locale only (review, import)\n --site <path> built site directory (render, default: dist)\n --attribute <name> base data attribute (render, default: data-verbaly)\n --base <path> subpath the site is served under, e.g. /app (render)\n --base-url <url> site origin, enables hreflang alternates (render)\n --sitemap emit sitemap-i18n.xml with per-locale alternates (render)\n --redirect send a visitor on the root to their mirror, pre-paint (render)\n --clean remove existing locale dirs before mirroring (render)\n\nConfig file: verbaly.config.{js,mjs,ts,mts,json} at root (flags win).\nThe claude provider needs @anthropic-ai/sdk installed and ANTHROPIC_API_KEY set.\n`;\n\nexport async function runCli(args: string[] = process.argv.slice(2)): Promise<void> {\n const { positionals, values } = parseArgs({\n args,\n allowPositionals: true,\n options: {\n root: { type: 'string' },\n dir: { type: 'string' },\n source: { type: 'string' },\n locales: { type: 'string' },\n prune: { type: 'boolean' },\n watch: { type: 'boolean' },\n write: { type: 'boolean' },\n json: { type: 'boolean' },\n drafts: { type: 'boolean' },\n outdated: { type: 'boolean' },\n draft: { type: 'boolean' },\n approve: { type: 'boolean' },\n reporter: { type: 'string' },\n model: { type: 'string' },\n locale: { type: 'string' },\n site: { type: 'string' },\n attribute: { type: 'string' },\n base: { type: 'string' },\n 'base-url': { type: 'string' },\n redirect: { type: 'boolean' },\n sitemap: { type: 'boolean' },\n clean: { type: 'boolean' },\n 'dry-run': { type: 'boolean' },\n plurals: { type: 'boolean' },\n format: { type: 'string' },\n out: { type: 'string' },\n missing: { type: 'boolean' },\n overwrite: { type: 'boolean' },\n help: { type: 'boolean', short: 'h' },\n },\n });\n\n const command = positionals[0];\n // asking for help is not a usage error, even with no command: only bare `verbaly` is\n if (values.help || !command) {\n console.log(HELP);\n process.exitCode = values.help ? 0 : 1;\n return;\n }\n\n if (rejectStrayFlags(command, values)) return;\n\n if (command === 'init') {\n const result = await init({\n root: values.root,\n dir: values.dir,\n sourceLocale: values.source,\n locales: csv(values.locales),\n });\n if (result.created.length) console.log(`[verbaly] created: ${result.created.join(', ')}`);\n if (result.skipped.length) console.log(` kept (already there): ${result.skipped.join(', ')}`);\n for (const { from, to } of result.renamed) {\n console.log(` wrote ${to} for ${from}, since a locale tag takes a hyphen`);\n }\n for (const locale of result.refused) {\n console.warn(` left out \"${locale}\": it is not a locale tag, use one like es or pt-BR`);\n }\n if (result.host) console.log(` detected: ${result.host}`);\n console.log(\n [' next steps:', ...result.next.map((step, i) => ` ${i + 1}. ${step}`)].join('\\n'),\n );\n return;\n }\n\n const cfg = await loadConfig(values.root ?? process.cwd(), {\n dir: values.dir,\n sourceLocale: values.source,\n locales: csv(values.locales),\n });\n\n if (command === 'doctor') {\n const result = await doctor(cfg);\n console.log(`[verbaly] doctor: ${counted(result.entries.length, 'check')}`);\n for (const entry of result.entries) {\n const line = formatDoctorEntry(entry);\n if (entry.level === 'error') console.error(line);\n else if (entry.level === 'warn') console.warn(line);\n else console.log(line);\n }\n if (result.ok) {\n console.log('[verbaly] setup looks healthy ✓');\n } else {\n console.error('[verbaly] doctor found problems');\n process.exitCode = 1;\n }\n return;\n }\n\n if (command === 'extract') {\n const dryRun = values['dry-run'];\n if (values.watch && (dryRun || values.prune)) {\n console.error(\n '[verbaly] --watch runs alone: prune is a deliberate one-shot action and dry-run writes nothing',\n );\n process.exitCode = 1;\n return;\n }\n\n // a watch run says each warning once, and again only after it went away and came back\n const reporter = values.watch\n ? createDevReporter(cfg.root, (line) => console.warn(` ${line}`))\n : undefined;\n\n async function runExtract(): Promise<void> {\n const result = await syncProject(cfg, { prune: values.prune, dryRun });\n if (result.pruneBlocked) {\n const unread = result.registry.parseErrors().length;\n console.warn(\n ` prune skipped: an unparsed file may read any key (${counted(unread, 'file')} below), so it waits until every file parses`,\n );\n }\n for (const [locale, keys] of Object.entries(result.pruned)) {\n console.log(\n dryRun\n ? ` ${locale}: would prune ${keys.length}: ${keys.join(', ')}`\n : ` ${locale}: -${keys.length} pruned`,\n );\n }\n const total = result.registry.messages().size;\n console.log(\n `[verbaly] ${counted(total, 'message')} · locales: ${cfg.locales.join(', ')}${dryRun ? ' (dry run, nothing written)' : ''}`,\n );\n for (const [locale, keys] of Object.entries(result.added)) {\n console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);\n }\n // news either way: an edit made in the code, or one the code undid in the catalog\n const warnings = result.findings.filter((finding) => {\n if (finding.kind !== 'replaced') return true;\n console.log(` ${formatFinding(finding, cfg.root)}`);\n return false;\n });\n if (reporter) reporter.report('extract', warnings);\n else for (const finding of warnings) console.warn(` ${formatFinding(finding, cfg.root)}`);\n if (result.stateProblem) {\n console.warn(\n ` ${result.stateProblem}, so drafts and outdated translations were not updated`,\n );\n }\n }\n\n await runExtract();\n if (values.watch) {\n watchProject(cfg, runExtract);\n console.log('[verbaly] watching for source changes (ctrl+c to stop)');\n }\n return;\n }\n\n if (command === 'typegen') {\n const registry = await extractProject(cfg);\n // the types describe the text that ships, the code's text wherever the code owns one\n const source = shippedCatalogs(cfg, loadCatalogs(cfg), registry)[cfg.sourceLocale] ?? {};\n const written = writeDts(cfg, source);\n if (!written) {\n console.log('[verbaly] no types written: dts is false in your verbaly config');\n return;\n }\n const where = relative(cfg.root, written.file).replaceAll('\\\\', '/');\n const how = written.changed ? 'written to' : 'up to date in';\n console.log(\n `[verbaly] types ${how} ${where} (${counted(Object.keys(source).length, 'message')})`,\n );\n return;\n }\n\n if (command === 'migrate') {\n const result = migrateCatalogs(cfg, { write: values.write, plurals: values.plurals });\n const from = result.detected.length ? result.detected.join(', ') : 'no known i18n library';\n const changes = result.braces.length + result.plurals.length;\n if (changes === 0 && result.skipped.length === 0) {\n console.log(`[verbaly] catalogs need nothing (${from}) ✓`);\n return;\n }\n const verb = values.write ? 'ported' : 'would port';\n const note = values.write ? '' : ' (report only, use --write to apply)';\n console.log(`[verbaly] ${verb} ${counted(changes, 'message')} from ${from}${note}`);\n for (const entry of result.braces) {\n console.log(` ${entry.locale} ${entry.key} ${entry.before} → ${entry.after}`);\n }\n for (const entry of result.plurals) {\n console.log(` ${entry.locale} ${entry.key} ${entry.from.join(' + ')} → ${entry.after}`);\n }\n if (!values.plurals && changes > 0) {\n console.log(' --plurals also merges _one/_other into one message with variants');\n }\n if (result.skipped.length > 0) {\n console.log(' needs a human:');\n for (const entry of result.skipped) {\n console.log(` ${entry.locale} ${entry.key} ${entry.reason}`);\n }\n }\n if (values.write) console.log(' next: run verbaly check');\n return;\n }\n\n if (command === 'wrap') {\n const result = await wrapProject(cfg, { write: values.write });\n if (result.wrapped.length === 0 && result.skipped.length === 0) {\n console.log(`[verbaly] nothing to wrap (${counted(result.files, 'file')} scanned) ✓`);\n return;\n }\n const blocked = new Set(result.blocked.map((entry) => entry.file));\n const done = result.changed.filter((file) => !blocked.has(file));\n const texts = result.wrapped.filter((entry) => !blocked.has(entry.file));\n const verb = values.write ? 'wrapped' : 'would wrap';\n const note = values.write ? '' : ' (report only, use --write to apply)';\n const counts = values.write\n ? `${counted(texts.length, 'text')} in ${counted(done.length, 'file')}`\n : `${counted(result.wrapped.length, 'text')} in ${counted(result.changed.length, 'file')}`;\n console.log(`[verbaly] ${verb} ${counts}${note}`);\n for (const entry of values.write ? texts : result.wrapped) {\n const attr = entry.kind === 'attribute' ? `${entry.attribute} → ` : '';\n console.log(` ${entry.file}:${entry.line} ${attr}\"${entry.text}\"`);\n }\n if (result.skipped.length > 0) {\n console.log(' needs a human:');\n for (const entry of result.skipped) {\n console.log(` ${entry.file}:${entry.line} \"${entry.text}\" (${entry.reason})`);\n }\n }\n if (result.blocked.length > 0) {\n console.log(` nothing written in ${counted(result.blocked.length, 'file')} with no t in scope:`);\n for (const entry of result.blocked) {\n const how = entry.client\n ? '\"use client\", so const t = useT()'\n : 'no \"use client\": check which side renders it before you pick the binding';\n console.log(` ${entry.file} ${counted(entry.texts, 'text')}, ${how}`);\n }\n console.log(' next: add t there, run verbaly wrap --write again, then verbaly extract');\n } else if (values.write && done.length > 0) {\n console.log(' next: run verbaly extract');\n }\n return;\n }\n\n if (command === 'status') {\n const registry = await extractProject(cfg);\n const { state, problem } = readState(cfg);\n if (problem) {\n console.warn(`[verbaly] ${problem}, so drafts and outdated translations are not counted`);\n }\n const result = status(cfg, loadCatalogs(cfg), registry, state.drafts, state.fingerprints);\n console.log(values.json ? JSON.stringify(result) : formatStatusResult(result));\n return;\n }\n\n if (command === 'check') {\n const reporter = values.reporter ?? 'text';\n if (reporter !== 'text' && reporter !== 'github') {\n console.error(`[verbaly] unknown reporter \"${values.reporter}\", use text or github`);\n process.exitCode = 1;\n return;\n }\n const registry = await extractProject(cfg);\n const catalogs = loadCatalogs(cfg);\n const state = checkState(cfg, values.drafts === true || values.outdated === true);\n const result = check(cfg, catalogs, registry, state.fingerprints);\n // opt-in: unreviewed machine translations and outdated ones block the merge too\n const unreviewed = values.drafts ? effectiveDrafts(state.drafts, catalogs) : {};\n const outdated = values.outdated ? result.outdated : [];\n const gated = { outdatedFails: values.outdated === true };\n // the annotations carry both severities, so they print whether the gate passes or not\n if (reporter === 'github') {\n for (const line of githubCheckAnnotations(result, registry, cfg, gated)) {\n console.error(line);\n }\n } else {\n const warnings = formatCheckWarnings(result, cfg.root, gated);\n if (warnings) console.warn(`[verbaly] warnings (the gate still passes)\\n${warnings}`);\n }\n\n const awaiting = [\n ...Object.entries(unreviewed).map(\n ([locale, keys]) => ` [${locale}] ${keys.length} unreviewed: ${keys.join(', ')}`,\n ),\n ...byLocale(outdated).map(\n ([locale, keys]) => ` [${locale}] ${keys.length} outdated: ${keys.join(', ')}`,\n ),\n ];\n if (result.ok && awaiting.length === 0) {\n console.log('[verbaly] all translations complete ✓');\n return;\n }\n if (!result.ok) {\n const brokenCount = result.broken.filter((entry) => entry.severity === 'error').length;\n const report =\n reporter === 'github'\n ? `[verbaly] check failed: ${result.missing.length} missing, ${result.unknown.length} unknown, ${brokenCount} broken`\n : `[verbaly] check failed\\n${formatCheckResult(result, cfg.root)}`;\n console.error(`${report}\\n${checkNextSteps(result)}`);\n }\n // printed whether or not the gate failed too: a flag that fails the run names what it found\n if (awaiting.length > 0) {\n for (const line of awaiting) console.error(line);\n console.error(\n '[verbaly] check failed: translations awaiting review (run verbaly review, then --approve what holds)',\n );\n }\n process.exitCode = 1;\n return;\n }\n\n if (command === 'translate') {\n // a machine translation that lost its draft flag passes as reviewed: read the state first\n if (!values['dry-run']) loadState(cfg);\n const registry = await extractProject(cfg);\n // the provider reads the text that ships, which is the text its answer has to match\n const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });\n const provider = await resolveProvider(cfg, values.model);\n const result = await translateCatalogs(cfg, catalogs, provider, {\n locales: csv(values.locales),\n batchSize: cfg.translate.batchSize,\n concurrency: cfg.translate.concurrency,\n retries: cfg.translate.retries,\n dryRun: values['dry-run'],\n // dry-run never calls the provider, so it sends no origins either\n origins: values['dry-run'] ? undefined : await collectOrigins(cfg, registry),\n onProgress: values['dry-run'] ? undefined : reportProgress,\n });\n\n if (values['dry-run']) {\n const entries = Object.entries(result.pending);\n if (entries.length === 0) {\n console.log('[verbaly] nothing to translate ✓');\n return;\n }\n for (const [locale, keys] of entries) {\n console.log(` ${locale}: ${keys.length} missing: ${keys.join(', ')}`);\n }\n return;\n }\n\n // machine output is a draft until a human reviews it, stamped with the text it was made for\n const source = catalogs[cfg.sourceLocale] ?? {};\n const writes: TranslationWrite[] = [];\n for (const [locale, keys] of Object.entries(result.translated)) {\n const catalog = catalogs[locale] ?? {};\n const written = mergeTranslations(cfg, locale, catalog, keys);\n writes.push({\n locale,\n draft: true,\n entries: written.map((key) => ({ key, text: catalog[key]! })),\n });\n console.log(` ${locale}: +${written.length} translated (draft)`);\n const kept = keys.length - written.length;\n if (kept > 0) {\n console.log(` ${locale}: ${counted(kept, 'message')} kept as written while this ran`);\n }\n }\n if (writes.length > 0) recordTranslations(cfg, source, writes);\n for (const [locale, keys] of Object.entries(result.invalid)) {\n console.warn(\n ` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(', ')}`,\n );\n }\n for (const line of formatTranslateFailures(result.failed)) console.error(line);\n if (result.failed.length > 0) process.exitCode = 1;\n if (\n Object.keys(result.translated).length === 0 &&\n Object.keys(result.invalid).length === 0 &&\n result.failed.length === 0\n ) {\n console.log('[verbaly] nothing to translate ✓');\n }\n return;\n }\n\n if (command === 'review') {\n const registry = await extractProject(cfg);\n const catalogs = loadCatalogs(cfg);\n // outdated against the text that ships, the one status and check count it against\n const shipped = shippedCatalogs(cfg, catalogs, registry);\n const state = loadState(cfg);\n const only = new Set(positionals.slice(1));\n const wanted = ({ locale, key }: { locale: string; key: string }): boolean =>\n (!values.locale || locale === values.locale) && (only.size === 0 || only.has(key));\n const drafts = Object.entries(effectiveDrafts(state.drafts, catalogs))\n .flatMap(([locale, keys]) => keys.map((key) => ({ locale, key })))\n .filter(wanted);\n const outdated = outdatedTranslations(cfg, shipped, state.fingerprints).filter(wanted);\n\n if (drafts.length === 0 && outdated.length === 0) {\n console.log('[verbaly] nothing awaiting review ✓');\n return;\n }\n\n if (values.approve) {\n for (const [locale, keys] of byLocale(drafts)) {\n clearDrafts(state.drafts, locale, keys);\n console.log(` ${locale}: ${keys.length} approved`);\n }\n // a person read the old translation against the new source and kept it\n acceptOutdated(cfg, shipped, state.fingerprints, outdated);\n for (const [locale, keys] of byLocale(outdated)) {\n console.log(` ${locale}: ${keys.length} kept for the new source text`);\n }\n saveState(cfg, state);\n // a draft can be outdated as well, and it is still one translation reviewed\n const reviewed = new Set(\n [...drafts, ...outdated].map(({ locale, key }) => `${locale}:${key}`),\n );\n console.log(`[verbaly] ${counted(reviewed.size, 'translation')} marked reviewed ✓`);\n return;\n }\n\n // a key alone cannot be judged: each line shows the text that ships and its translation\n const source = shipped[cfg.sourceLocale] ?? {};\n const show = (locale: string, keys: string[]): void => {\n console.log(` ${locale}:`);\n for (const key of keys) {\n const translated = catalogs[locale]?.[key] ?? '';\n console.log(\n ` ${key}: \"${truncate(source[key] ?? '', 60)}\" → \"${truncate(translated, 60)}\"`,\n );\n }\n };\n if (drafts.length > 0) {\n console.log(\n `[verbaly] ${counted(drafts.length, 'machine translation')} awaiting review (--approve to accept)`,\n );\n for (const [locale, keys] of byLocale(drafts)) show(locale, keys);\n }\n if (outdated.length > 0) {\n console.log(\n `[verbaly] ${counted(outdated.length, 'translation')} written for an older source text (update them, or --approve keeps them)`,\n );\n for (const [locale, keys] of byLocale(outdated)) show(locale, keys);\n }\n return;\n }\n\n if (command === 'export') {\n const format = (values.format ?? 'xliff') as ExportFormat;\n if (!['xliff', 'csv', 'po', 'android-xml', 'ios-strings'].includes(format)) {\n console.error(\n `[verbaly] unknown format \"${values.format}\", use xliff, csv, po, android-xml or ios-strings`,\n );\n process.exitCode = 1;\n return;\n }\n if (values.missing && isMobileFormat(format)) {\n console.error(\n `[verbaly] --missing is for translator formats (xliff, csv): ${format} already skips untranslated keys so the app falls back to the source locale`,\n );\n process.exitCode = 1;\n return;\n }\n const registry = await extractProject(cfg);\n // a translator gets the text that ships, never a catalog the code has since moved past\n const shipped = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });\n const result = exportCatalogs(cfg, shipped, {\n locales: csv(values.locales),\n format,\n out: values.out,\n missing: values.missing,\n // mobile formats are delivery-only: no translator reads where a text lives\n origins: isMobileFormat(format) ? undefined : await collectOrigins(cfg, registry),\n });\n if (result.files.length === 0) {\n console.log('[verbaly] no target locales to export (add locales to your config)');\n return;\n }\n const note = isMobileFormat(result.format) ? 'untranslated skipped' : 'untranslated';\n console.log(\n `[verbaly] exported ${counted(result.files.length, 'locale')} (${result.format}) → ${result.dir}`,\n );\n for (const file of result.files) {\n console.log(\n ` ${file.locale}: ${counted(file.total, 'message')} (${file.untranslated} ${note}) → ${file.path}`,\n );\n }\n return;\n }\n\n if (command === 'import') {\n const files = positionals.slice(1);\n if (files.length === 0) {\n console.error(\n '[verbaly] import needs at least one file: verbaly import verbaly-export/es.xlf',\n );\n process.exitCode = 1;\n return;\n }\n // the draft flags are written after the catalogs: an unreadable state writes neither\n if (!values['dry-run']) loadState(cfg);\n const registry = await extractProject(cfg);\n // checked against the text that ships, like check reads every translation\n const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });\n const result = importCatalogs(cfg, catalogs, files, {\n locale: values.locale,\n overwrite: values.overwrite,\n dryRun: values['dry-run'],\n });\n for (const { file, from, to } of result.mapped) {\n console.log(` ${file}: \"${from}\" read as ${to}`);\n }\n // a warning and exit 1, like a batch translate could not land: the file is skipped, not guessed\n for (const { file, locale, reason } of result.unmatched) {\n if (reason === 'undeclared') {\n console.warn(\n ` ${file}: \"${locale}\" is not one of this project's locales (${cfg.locales.join(', ')}), so nothing was imported from it`,\n );\n console.warn(\n ` fix: add ${locale} to locales in your verbaly config, or pass --locale with one of them`,\n );\n } else {\n console.warn(` ${file}: \"${locale}\" is not a locale tag, so nothing was imported from it`);\n console.warn(' fix: pass --locale with the tag it stands for, like pt-BR');\n }\n process.exitCode = 1;\n }\n // a person's file clears the draft flag unless --draft, stamped with the source it carried\n const writes: TranslationWrite[] = [];\n for (const [locale, keys] of Object.entries(result.imported)) {\n if (!values['dry-run']) {\n const catalog = catalogs[locale] ?? {};\n writeCatalog(cfg, locale, catalog);\n const seen = result.sources[locale] ?? {};\n const entries = keys.map((key) => ({ key, text: catalog[key]!, source: seen[key] }));\n writes.push({ locale, entries, draft: values.draft === true });\n }\n const verb = values['dry-run'] ? 'would import' : 'imported';\n console.log(` ${locale}: +${keys.length} ${verb}${values.draft ? ' (draft)' : ''}`);\n }\n if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);\n for (const [locale, keys] of Object.entries(result.skipped)) {\n console.log(\n ` ${locale}: ${keys.length} already translated, kept (use --overwrite to replace)`,\n );\n }\n for (const [locale, keys] of Object.entries(result.rejected)) {\n console.warn(\n ` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(', ')}`,\n );\n }\n for (const [locale, keys] of Object.entries(result.unknown)) {\n console.warn(\n ` ${locale}: ${counted(keys.length, 'unknown key')} ignored (not in the source catalog): ${keys.join(', ')}`,\n );\n }\n if (Object.keys(result.imported).length === 0 && result.unmatched.length === 0) {\n console.log('[verbaly] nothing to import ✓');\n }\n return;\n }\n\n if (command === 'render') {\n const result = await renderSite(cfg, {\n site: values.site,\n locales: csv(values.locales),\n attribute: values.attribute,\n base: values.base,\n baseUrl: values['base-url'],\n sitemap: values.sitemap,\n redirect: values.redirect,\n clean: values.clean,\n });\n console.log(\n `[verbaly] ${counted(result.files, 'page')} × ${counted(result.locales.length, 'locale')} (${result.locales.join(', ')})`,\n );\n for (const line of formatRenderWarnings(result, cfg.sourceLocale)) console.warn(line);\n return;\n }\n\n if (command === 'pseudo') {\n // the text that ships is the one QA has to see stretched, never a catalog the code moved past\n const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), await extractProject(cfg), {\n newKeys: false,\n });\n const locale = values.locale ?? PSEUDO_LOCALE;\n const keys = pseudoCatalogs(cfg, catalogs, locale);\n writeCatalog(cfg, locale, catalogs[locale] ?? {});\n console.log(`[verbaly] ${counted(keys.length, 'message')} pseudo-localized → ${locale}`);\n return;\n }\n\n console.error(`[verbaly] unknown command \"${command}\"\\n${HELP}`);\n process.exitCode = 1;\n}\n\n// \"es, pt\" is how a person types a list: a space must not become part of a locale\nfunction csv(value: string | undefined): string[] | undefined {\n return value\n ?.split(',')\n .map((item) => item.trim())\n .filter(Boolean);\n}\n\n// a translate run is minutes of network: say what landed as it lands, never only at the end\nfunction reportProgress(progress: TranslateProgress): void {\n const head = ` ${progress.locale} ${progress.batch}/${progress.batches}`;\n if (progress.error) console.warn(`${head}: failed (${progress.error}), continuing`);\n else console.log(`${head}: ${counted(progress.keys, 'message')}`);\n}\n\n// every compiler error already opens with [verbaly]: prefix only what does not\nexport function formatCliError(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n return message.startsWith('[verbaly]') ? message : `[verbaly] ${message}`;\n}\n\n// check reads the state for its warnings, and it only has to be readable when a flag gates on it\nfunction checkState(cfg: ResolvedConfig, gating: boolean): State {\n if (gating) return loadState(cfg);\n const { state, problem } = readState(cfg);\n if (problem) console.warn(`[verbaly] ${problem}, so outdated translations are not reported`);\n return state;\n}\n\nfunction byLocale(entries: { locale: string; key: string }[]): [string, string[]][] {\n const out = new Map<string, string[]>();\n for (const { locale, key } of entries) {\n const keys = out.get(locale);\n if (keys) keys.push(key);\n else out.set(locale, [key]);\n }\n return [...out];\n}\n\n// flags shared by every command (config overrides)\nconst COMMON_FLAGS = new Set(['root', 'dir', 'source', 'locales', 'help']);\nexport const COMMAND_FLAGS: Record<string, string[]> = {\n init: [],\n doctor: [],\n extract: ['prune', 'dry-run', 'watch'],\n typegen: [],\n wrap: ['write'],\n migrate: ['write', 'plurals'],\n status: ['json'],\n check: ['reporter', 'drafts', 'outdated'],\n translate: ['model', 'dry-run'],\n review: ['approve', 'locale'],\n export: ['format', 'out', 'missing'],\n import: ['locale', 'overwrite', 'dry-run', 'draft'],\n pseudo: ['locale'],\n render: ['site', 'attribute', 'base', 'base-url', 'sitemap', 'redirect', 'clean'],\n};\n\n// a flag another command owns must fail loudly, never be silently ignored\nfunction rejectStrayFlags(command: string, values: Record<string, unknown>): boolean {\n const own = COMMAND_FLAGS[command];\n if (!own) return false; // unknown command: reported later with the help text\n const allowed = new Set([...COMMON_FLAGS, ...own]);\n const stray = Object.keys(values).filter((k) => values[k] !== undefined && !allowed.has(k));\n if (stray.length === 0) return false;\n for (const flag of stray) {\n const hint = flag === 'locale' ? ' (did you mean --locales?)' : '';\n console.error(`[verbaly] --${flag} is not a \"${command}\" flag${hint}`);\n }\n process.exitCode = 1;\n return true;\n}\n"],"mappings":";;;;;;;;;;;AACA,SAAgB,gBAAgB,MAAc,UAAsC;CAClF,MAAM,QAAQ,UAAU,QAAQ,IAAI,KAAK;CACzC,OAAO,QAAQ,KAAK,SAAU,QAAQ,OAAO,OAAO,KAAK,QAAQ,UAAU,MAAM,IAAI;AACvF;;;ACMA,SAAgB,eAAwB;CACtC,OAAO,OAAO,OAAO,IAAI;AAC3B;AAGA,SAAgB,IAAI,SAAkB,KAAiC;CACrE,OAAO,OAAO,OAAO,SAAS,GAAG,IAAI,QAAQ,OAAO,KAAA;AACtD;AAEA,SAAgB,YAAY,KAAqB,QAAwB;CACvE,OAAO,KAAK,IAAI,KAAK,GAAG,OAAO,MAAM;AACvC;AAGA,SAAgB,YAAY,KAAqB,QAAyB;CACxE,MAAM,OAAO,SAAS,KAAK,MAAM;CACjC,MAAM,MAAM,QAAQ,IAAI;CAExB,IAAI,KACF,MAAM,IAAI,MACR,aAAa,YAAY,KAAK,MAAM,EAAE,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,eAAe,QAAQ;CACnE,CAAC;CACD,OAAO;AACT;AAGA,SAAS,eAAe,MAAsB;CAC5C,OAAO,KAAK,QAAQ,UAAU,MAAM,CAAC,CAAC,QAAQ,SAAS,MAAM;AAC/D;AAEA,SAAS,UAAU,MAAsB;CACvC,OAAO,KAAK,SAAS,KAAK,UAAU,CAAC,CAAC;AACxC;AAEA,SAAS,WAAW,MAAsB;CACxC,OAAO,KAAK,SAAS,KAAK,QAAQ,CAAC,CAAC;AACtC;AAEA,SAAS,KAAK,MAAuB;CAEnC,OADY,KAAK,KACL,OAAO,QAAQ;AAC7B;;;ACoUA,SAAgB,eAAe,OAAwB;CACrD,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CACrE,OAAO,QAAQ,WAAW,WAAW,IAAI,UAAU,aAAa;AAClE"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["parse","walk","parse","parse"],"sources":["../src/eol.ts","../src/catalog.ts","../src/bundle.ts","../src/registry.ts","../src/key.ts","../src/analyze.ts","../src/sfc.ts","../src/extract.ts","../src/validate.ts","../src/params.ts","../src/tsconfig.ts","../src/warn.ts","../src/codegen.ts","../src/findings.ts","../src/state.ts","../src/project.ts","../src/tag.ts","../src/init.ts","../src/check.ts","../src/transform.ts","../src/plugin.ts","../src/scope.ts","../src/drafts.ts","../src/status.ts","../src/doctor.ts","../src/translate.ts","../src/render.ts","../src/watch.ts","../src/wrap.ts","../src/run.ts"],"sourcesContent":["// a file checked out with CRLF stays CRLF: rewriting every line is a diff nobody made\nexport function withLineEndings(text: string, existing: string | undefined): string {\n const first = existing?.indexOf('\\n') ?? -1;\n return first > 0 && existing![first - 1] === '\\r' ? text.replace(/\\r?\\n/g, '\\r\\n') : text;\n}\n","import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { flatten, type MessageTree } from 'verbaly';\nimport type { ResolvedConfig } from './config';\nimport { withLineEndings } from './eol';\n\nexport type Catalog = Record<string, string>;\nexport type Catalogs = Record<string, Catalog>;\n\n// no prototype: a key is data, so toString or __proto__ must never answer from Object\nexport function emptyCatalog(): Catalog {\n return Object.create(null) as Catalog;\n}\n\n// a catalog handed in by a caller may be a plain object, and its prototype is not a message\nexport function own(catalog: Catalog, key: string): string | undefined {\n return Object.hasOwn(catalog, key) ? catalog[key] : undefined;\n}\n\nexport function catalogPath(cfg: ResolvedConfig, locale: string): string {\n return join(cfg.dir, `${locale}.json`);\n}\n\n// the flat view is the shape t() sees, so every command reads a catalog the way the runtime does\nexport function readCatalog(cfg: ResolvedConfig, locale: string): Catalog {\n const tree = readTree(cfg, locale);\n const bad = badLeaf(tree);\n // the runtime skips this leaf with a warn; a build tool that skipped it would write the skip back\n if (bad) {\n throw new Error(\n `[verbaly] ${catalogPath(cfg, locale)} has a non-string value at \"${bad}\", ` +\n 'catalog values are text (groups of text are fine): fix the value',\n );\n }\n return flatten(tree);\n}\n\n// dotted path of the first value that is neither text nor a group of text (an array is a bad leaf)\nexport function badLeaf(tree: MessageTree, prefix = ''): string | undefined {\n for (const [key, value] of Object.entries(tree)) {\n const path = prefix ? `${prefix}.${key}` : key;\n if (typeof value === 'string') continue;\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return path;\n const bad = badLeaf(value, path);\n if (bad) return bad;\n }\n return undefined;\n}\n\n// corrupt catalog throws: read as empty, the next extract would wipe the translations\nfunction readTree(cfg: ResolvedConfig, locale: string): MessageTree {\n let content: string;\n try {\n content = readFileSync(catalogPath(cfg, locale), 'utf8');\n } catch {\n return {};\n }\n const parsed = parseTree(content);\n if (parsed === undefined) {\n throw new Error(\n `[verbaly] ${catalogPath(cfg, locale)} is not valid JSON, fix or delete the file`,\n );\n }\n // an array or a bare string reads as no messages, and the next extract would write over it\n if (!isTree(parsed)) {\n throw new Error(\n `[verbaly] ${catalogPath(cfg, locale)} is not a JSON object of messages, fix or delete the file`,\n );\n }\n return parsed;\n}\n\n// the flat view of a catalog that is not on disk: an old revision read out of git is text\nexport function parseCatalog(content: string): Catalog | undefined {\n const tree = parseTree(content);\n return tree === undefined ? undefined : flatten(tree as MessageTree);\n}\n\n// a byte order mark is legal in the file and illegal to JSON.parse: drop it by code, never by regex\nexport function parseTree(content: string): unknown {\n const body = content.charCodeAt(0) === 0xfeff ? content.slice(1) : content;\n try {\n return JSON.parse(body) as unknown;\n } catch {\n return undefined;\n }\n}\n\nexport function isTree(value: unknown): value is MessageTree {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function loadCatalogs(cfg: ResolvedConfig): Catalogs {\n const catalogs: Catalogs = {};\n for (const locale of cfg.locales) catalogs[locale] = readCatalog(cfg, locale);\n return catalogs;\n}\n\n// the nesting is the author's: a file written as groups is handed back as groups\nfunction isNested(tree: MessageTree): boolean {\n return Object.values(tree).some((value) => typeof value === 'object' && value !== null);\n}\n\n// null prototype: a group named __proto__ is data here, and on a plain object it writes to Object\nfunction group(): MessageTree {\n return Object.create(null) as MessageTree;\n}\n\n// dotted key back to its group; a path already taken by text stays flat so nothing is overwritten\nfunction nest(catalog: Catalog): MessageTree {\n const tree = group();\n // sorted, so \"hero\" always lands before \"hero.title\" and a message is never replaced by its group\n for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => (a < b ? -1 : 1))) {\n const parts = key.split('.');\n const leaf = parts[parts.length - 1]!;\n let node: MessageTree | undefined = parts.length > 1 ? tree : undefined;\n for (let i = 0; node && i < parts.length - 1; i++) {\n const next = (node[parts[i]!] ??= group());\n node = typeof next === 'object' && next !== null ? (next as MessageTree) : undefined;\n }\n if (node && typeof node[leaf] !== 'object') node[leaf] = message;\n else tree[key] = message;\n }\n return tree;\n}\n\nfunction sortTree(tree: MessageTree): MessageTree {\n const sorted = group();\n for (const key of Object.keys(tree).sort()) {\n const value = tree[key];\n if (typeof value === 'string') sorted[key] = value;\n else if (value !== undefined) sorted[key] = sortTree(value as MessageTree);\n }\n return sorted;\n}\n\nfunction isSorted(keys: string[]): boolean {\n for (let i = 1; i < keys.length; i++) if (keys[i - 1]! > keys[i]!) return false;\n return true;\n}\n\n// a level a person ordered keeps that order; one that was already sorted keeps being sorted\nfunction orderLike(tree: MessageTree, previous: MessageTree): MessageTree {\n const had = Object.keys(previous);\n if (isSorted(had)) return sortTree(tree);\n\n const out = group();\n const take = (key: string): void => {\n const value = tree[key];\n if (typeof value === 'string') {\n out[key] = value;\n return;\n }\n if (value === undefined) return;\n const before = previous[key];\n out[key] =\n typeof before === 'object' && before !== null\n ? orderLike(value, before)\n : sortTree(value);\n };\n\n for (const key of had) if (Object.hasOwn(tree, key)) take(key);\n // a key the file did not have is an addition, and it reads as one at the end of its group\n for (const key of Object.keys(tree).sort()) if (!Object.hasOwn(previous, key)) take(key);\n return out;\n}\n\nexport function serializeCatalog(\n catalog: Catalog,\n nested = false,\n previous?: MessageTree,\n): string {\n const tree: MessageTree = nested ? nest(catalog) : catalog;\n return JSON.stringify(previous ? orderLike(tree, previous) : sortTree(tree), null, 2) + '\\n';\n}\n\nexport function writeCatalog(cfg: ResolvedConfig, locale: string, catalog: Catalog): string {\n const path = catalogPath(cfg, locale);\n let existing: string | undefined;\n try {\n existing = readFileSync(path, 'utf8');\n } catch {\n mkdirSync(cfg.dir, { recursive: true });\n }\n // parsed once: the shape and the key order are two questions about the same previous file\n const parsed = existing === undefined ? undefined : parseTree(existing);\n const previous = isTree(parsed) ? parsed : undefined;\n const serialized = withLineEndings(\n serializeCatalog(catalog, wantsNesting(cfg, locale, existing, previous), previous),\n existing,\n );\n // identical writes are skipped: a rewrite retriggers whatever watches the catalog\n if (existing === serialized) return serialized;\n writeFileSync(path, serialized);\n return serialized;\n}\n\n// the file's own shape, and for a locale that does not exist yet, the source catalog's\nfunction wantsNesting(\n cfg: ResolvedConfig,\n locale: string,\n existing: string | undefined,\n previous: MessageTree | undefined,\n): boolean {\n if (existing !== undefined) return previous !== undefined && isNested(previous);\n if (locale === cfg.sourceLocale) return false;\n return isNested(readTree(cfg, cfg.sourceLocale));\n}\n\n// the same test the runtime uses, asked of the catalogs so the parser ships only where it is read\nconst ICU_ARG = /\\{\\s*[a-zA-Z0-9_]+\\s*,\\s*(?:plural|selectordinal|select|number|date|time)\\b/;\n\nexport function needsIcu(catalogs: Catalogs): boolean {\n for (const catalog of Object.values(catalogs)) {\n for (const message of Object.values(flatten(catalog as MessageTree))) {\n if (ICU_ARG.test(message)) return true;\n }\n }\n return false;\n}\n\n// relative time is the one format heavy enough to be worth shipping only where it is written\nconst RELATIVE_ARG = /\\{[^{}]*:\\s*relative\\b/;\n\nexport function needsRelative(catalogs: Catalogs): boolean {\n for (const catalog of Object.values(catalogs)) {\n for (const message of Object.values(flatten(catalog as MessageTree))) {\n if (RELATIVE_ARG.test(message)) return true;\n }\n }\n return false;\n}\n","import { emptyCatalog, type Catalogs } from './catalog';\nimport type { ResolvedConfig } from './config';\nimport type { MessageRegistry } from './registry';\nimport { counted } from './text';\n\n// segment prefix, never substring: excluding \"nav\" must not take \"navbar_x\" with it\nfunction isExcluded(key: string, prefixes: string[]): boolean {\n return prefixes.some((prefix) => key === prefix || key.startsWith(`${prefix}.`));\n}\n\n// what the browser gets; render and the gate keep reading the full catalogs from disk\nexport function clientCatalogs(cfg: ResolvedConfig, catalogs: Catalogs): Catalogs {\n const prefixes = cfg.bundle.exclude ?? [];\n if (prefixes.length === 0) return catalogs;\n const out: Catalogs = {};\n for (const [locale, catalog] of Object.entries(catalogs)) {\n const kept = emptyCatalog();\n for (const [key, message] of Object.entries(catalog)) {\n if (!isExcluded(key, prefixes)) kept[key] = message;\n }\n out[locale] = kept;\n }\n return out;\n}\n\nexport interface BundleIssue {\n prefix: string;\n problem: string;\n fix: string;\n}\n\n// never a gate failure: an excluded namespace builds, it just may not be there when code asks\nexport function auditBundle(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: MessageRegistry,\n): BundleIssue[] {\n const prefixes = cfg.bundle.exclude ?? [];\n if (prefixes.length === 0) return [];\n const source = Object.keys(catalogs[cfg.sourceLocale] ?? {});\n const used = registry.usedKeys();\n\n const issues: BundleIssue[] = [];\n for (const prefix of prefixes) {\n if (!source.some((key) => isExcluded(key, [prefix]))) {\n issues.push({\n prefix,\n problem: `matches no key in ${cfg.sourceLocale}.json, so it excludes nothing`,\n fix: 'check the spelling against your catalog, or drop it from bundle.exclude',\n });\n continue;\n }\n const files = new Set<string>();\n for (const [key, where] of used) {\n if (isExcluded(key, [prefix])) for (const file of where) files.add(file);\n }\n if (files.size > 0) {\n issues.push({\n prefix,\n problem: `is read by t() in ${counted(files.size, 'file')}, where it resolves to the key itself`,\n fix: 'pre-render those pages with render, load the group with addMessages, or stop excluding it',\n });\n }\n }\n return issues;\n}\n\n// one wording for the build gate and for doctor, so the two can never say different things\nexport function formatBundleIssue(issue: BundleIssue): string {\n return `bundle.exclude \"${issue.prefix}\" ${issue.problem}`;\n}\n","import type { Analysis, MissedCall, StrayImport, TaggedMessage } from './analyze';\n\n// one key, several texts: the earliest one wins everywhere, so the others render its words\nexport interface Collision {\n key: string;\n kept: TaggedMessage;\n dropped: TaggedMessage[];\n}\n\nexport class MessageRegistry {\n private files = new Map<string, Analysis>();\n\n update(file: string, analysis: Analysis): void {\n this.files.set(file, analysis);\n }\n\n remove(file: string): void {\n this.files.delete(file);\n }\n\n // the earliest site wins, by file then position, so no scan or load order ever picks the text\n messages(): Map<string, TaggedMessage> {\n const out = new Map<string, TaggedMessage>();\n for (const analysis of this.inOrder()) {\n for (const msg of analysis.tagged) {\n const held = out.get(msg.key);\n if (!held || earlier(msg, held)) out.set(msg.key, msg);\n }\n }\n return out;\n }\n\n // every place whose text differs from the one that wins, so fixing one never hides the next\n collisions(): Collision[] {\n const winners = this.messages();\n const dropped = new Map<string, TaggedMessage[]>();\n for (const analysis of this.inOrder()) {\n for (const msg of analysis.tagged) {\n if (msg.message === winners.get(msg.key)!.message) continue;\n dropped.set(msg.key, [...(dropped.get(msg.key) ?? []), msg]);\n }\n }\n return [...dropped].map(([key, others]) => ({\n key,\n kept: winners.get(key)!,\n dropped: others.sort((a, b) => (earlier(a, b) ? -1 : 1)),\n }));\n }\n\n // strict leaves out the loose spellings, which the gate does not fail on yet\n usedKeys(strict = false): Map<string, string[]> {\n const out = new Map<string, string[]>();\n for (const analysis of this.inOrder()) {\n for (const used of analysis.usedKeys) {\n if (strict && used.loose) continue;\n const files = out.get(used.key) ?? [];\n if (!files.includes(used.file)) files.push(used.file);\n out.set(used.key, files);\n }\n }\n return out;\n }\n\n strayImports(): StrayImport[] {\n return this.inOrder().flatMap((analysis) => analysis.strayImports);\n }\n\n // a t under another name: its texts are neither extracted nor rewritten, so they never translate\n missed(): MissedCall[] {\n return this.inOrder().flatMap((analysis) => analysis.missed);\n }\n\n // files the parser could not read: they contributed no messages and nothing else can tell\n parseErrors(): { file: string; message: string }[] {\n const out: { file: string; message: string }[] = [];\n for (const file of [...this.files.keys()].sort()) {\n const { parseError } = this.files.get(file)!;\n if (parseError) out.push({ file, message: parseError });\n }\n return out;\n }\n\n // key → every source file that writes or uses it (translator context)\n origins(): Map<string, string[]> {\n const out = this.usedKeys();\n for (const analysis of this.inOrder()) {\n for (const msg of analysis.tagged) {\n const files = out.get(msg.key) ?? [];\n if (!files.includes(msg.file)) files.push(msg.file);\n out.set(msg.key, files);\n }\n }\n return out;\n }\n\n // by path: a dev server registers files in load order, and every report must read the same\n private inOrder(): Analysis[] {\n return [...this.files.keys()].sort().map((file) => this.files.get(file)!);\n }\n}\n\nfunction earlier(a: TaggedMessage, b: TaggedMessage): boolean {\n return a.file === b.file ? a.start < b.start : a.file < b.file;\n}\n","import { createHash } from 'node:crypto';\n\nexport function stableKey(message: string): string {\n return createHash('sha256').update(message).digest('base64url').slice(0, 8);\n}\n","import { parse } from '@babel/parser';\nimport { stableKey } from './key';\n\nexport interface TaggedParam {\n name: string;\n start: number;\n end: number;\n}\n\nexport interface TransComponent {\n name: string;\n source: string;\n}\n\nexport interface TaggedMessage {\n key: string;\n message: string;\n params: TaggedParam[];\n start: number;\n end: number;\n line: number;\n tagStart: number;\n tagEnd: number;\n file: string;\n jsx?: { name: string; components: TransComponent[] };\n singleQuote?: boolean;\n}\n\nexport interface UsedKey {\n key: string;\n file: string;\n loose?: true;\n}\n\n// a named import the verbaly packages do not export: t comes from an instance, never from a package\nexport interface StrayImport {\n name: string;\n source: string;\n file: string;\n}\n\n// a tagged template on t under another name: never extracted, never rewritten, never translated\nexport interface MissedCall {\n name: string;\n file: string;\n start: number;\n line: number;\n}\n\nexport interface Analysis {\n tagged: TaggedMessage[];\n usedKeys: UsedKey[];\n strayImports: StrayImport[];\n missed: MissedCall[];\n parseError?: string;\n}\n\n// babel's message carries the position but never the path: every caller adds the file itself\nexport function parseErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n// exported for wrap.ts (module-internal reuse, not part of the package surface)\nexport interface AstNode {\n type: string;\n start: number;\n end: number;\n [key: string]: unknown;\n}\n\nconst SKIP_KEYS = new Set(['loc', 'leadingComments', 'trailingComments', 'innerComments', 'extra']);\n\nexport interface AnalyzeOptions {\n tNames?: readonly string[];\n renamed?: readonly string[];\n}\n\nconst DEFAULT_T_NAMES: readonly string[] = ['t'];\nconst JSX_FILE_RE = /\\.(?:[cm]?jsx?|tsx)$/;\n\n// a key module declares what a call site would otherwise pass as a literal the scanner can read\nconst DEFINE_KEYS = 'defineKeys';\n\nexport function analyze(code: string, file: string, options: AnalyzeOptions = {}): Analysis {\n return analyzeScript(code, file, options).analysis;\n}\n\n// a tagged template or a call on a name other than t, judged once every binding is known\ntype Candidate = { kind: 'tag'; node: AstNode } | { kind: 'call'; name: string; key: string };\n\n// the analysis plus the names t was renamed to, which an SFC hands on to its markup\nexport function analyzeScript(\n code: string,\n file: string,\n options: AnalyzeOptions = {},\n): { analysis: Analysis; renamed: string[] } {\n const names = new Set(options.tNames ?? DEFAULT_T_NAMES);\n const ast = parse(code, {\n sourceType: 'module',\n errorRecovery: true,\n plugins: JSX_FILE_RE.test(file) ? ['typescript', 'jsx'] : ['typescript'],\n });\n\n const tagged: TaggedMessage[] = [];\n const usedKeys: UsedKey[] = [];\n const strayImports: StrayImport[] = [];\n const bindings = new Bindings(names);\n const candidates: Candidate[] = [];\n\n walk(ast.program as unknown as AstNode, (node) => {\n if (node.type === 'ImportDeclaration') {\n collectStrayImports(node, file, strayImports);\n bindings.addImport(node);\n } else if (node.type === 'VariableDeclarator') {\n bindings.addDeclarator(node);\n } else if (node.type === 'TaggedTemplateExpression') {\n const tag = node.tag as AstNode;\n const explicit = explicitId(tag, names);\n if (!explicit && !isTReference(tag, names)) {\n candidates.push({ kind: 'tag', node });\n return;\n }\n const quasi = node.quasi as AstNode;\n const message = buildMessage(code, quasi, names);\n if (!message) return;\n tagged.push({\n key: explicit ? explicit.key : stableKey(message.text),\n message: message.text,\n params: message.params,\n start: node.start,\n end: node.end,\n line: lineOf(node),\n tagStart: explicit ? explicit.refStart : tag.start,\n tagEnd: explicit ? explicit.refEnd : tag.end,\n file,\n });\n } else if (node.type === 'CallExpression') {\n const callee = node.callee as AstNode;\n const args = node.arguments as AstNode[];\n if (callee.type === 'Identifier' && callee.name === DEFINE_KEYS) {\n collectDeclaredKeys(args[0], file, usedKeys);\n return;\n }\n if (!isTReference(callee, names)) {\n const key = callee.type === 'Identifier' ? staticString(args[0]) : undefined;\n if (key !== undefined) candidates.push({ kind: 'call', name: callee.name as string, key });\n return;\n }\n const key = staticString(args[0]);\n if (key !== undefined) usedKeys.push(usedKey(key, file, args[0]));\n } else if (node.type === 'JSXElement') {\n handleTrans(code, node, file, tagged, usedKeys, names);\n }\n });\n\n const renamed = bindings.renamed(options.renamed);\n const missed: MissedCall[] = [];\n for (const candidate of candidates) {\n // a key read under another name is in use: loose, so prune keeps it and no gate fails\n if (candidate.kind === 'call') {\n if (renamed.has(candidate.name)) usedKeys.push({ key: candidate.key, file, loose: true });\n continue;\n }\n const { node } = candidate;\n const name = renamedTag(node.tag as AstNode, renamed);\n if (!name) continue;\n missed.push({ name, file, start: node.start, line: lineOf(node) });\n // never extracted, yet its translation has to outlive prune until the binding is named t\n const key = missedKey(code, node, names);\n if (key !== undefined) usedKeys.push({ key, file, loose: true });\n }\n\n return { analysis: { tagged, usedKeys, strayImports, missed }, renamed: [...renamed] };\n}\n\nfunction lineOf(node: AstNode): number {\n return (node.loc as { start: { line: number } } | undefined)?.start.line ?? 1;\n}\n\n// a module whose exports hand out verbaly's t: the core, every adapter and virtual:verbaly\nconst VERBALY_SOURCE = /^(?:verbaly|virtual:verbaly|@verbaly\\/[\\w-]+(?:\\/[\\w-]+)*)$/;\n\n// how each factory hands out t: useT() returns it, getT() resolves to it\nconst T_FACTORIES = new Map([\n ['useT', 'call'],\n ['getT', 'await'],\n]);\n\n// instance factories whose result carries t, for const { t: x } = useVerbaly() with no import\nconst INSTANCE_FACTORIES = new Set(['useVerbaly', 'getVerbaly']);\n\n// what hands out a t in this file, judged by where each name was imported from\nclass Bindings {\n private imports = new Map<string, { source: string; imported: string }>();\n private direct = new Set<string>();\n private declared: { name: string; init: AstNode }[] = [];\n private destructured: { name: string; init: AstNode }[] = [];\n\n constructor(private names: ReadonlySet<string>) {}\n\n addImport(node: AstNode): void {\n const source = (node.source as { value?: unknown }).value;\n if (typeof source !== 'string') return;\n for (const spec of node.specifiers as AstNode[]) {\n const local = identifierName(spec.local as AstNode);\n if (!local) continue;\n const imported =\n spec.type === 'ImportSpecifier' ? importedName(spec.imported as AstNode) : spec.type;\n this.imports.set(local, { source, imported });\n if (source === 'virtual:verbaly' && imported === 't') this.direct.add(local);\n }\n }\n\n addDeclarator(node: AstNode): void {\n const id = node.id as AstNode;\n const init = node.init as AstNode | null;\n if (!init) return;\n if (id.type === 'Identifier') {\n this.declared.push({ name: id.name as string, init });\n return;\n }\n if (id.type !== 'ObjectPattern') return;\n for (const property of id.properties as AstNode[]) {\n if (property.type !== 'ObjectProperty' || property.computed) continue;\n if (identifierName(property.key as AstNode) !== 't') continue;\n const value = property.value as AstNode;\n // { t: x = fallback } binds x all the same\n const target = value.type === 'AssignmentPattern' ? (value.left as AstNode) : value;\n const name = identifierName(target);\n if (name) this.destructured.push({ name, init });\n }\n }\n\n renamed(seed: readonly string[] = []): Set<string> {\n const out = new Set(seed);\n const add = (name: string): void => {\n if (this.names.has(name)) return;\n out.add(name);\n // a svelte store is read as $name, the way t itself is read as $t\n if (this.names.has('$t')) out.add(`$${name}`);\n };\n for (const name of this.direct) add(name);\n for (const { name, init } of this.declared) if (this.handsOutT(init)) add(name);\n for (const { name, init } of this.destructured) if (this.carriesT(init)) add(name);\n return out;\n }\n\n // useT() or await getT(), imported from verbaly or not imported at all (a Nuxt auto-import)\n private handsOutT(init: AstNode): boolean {\n const awaited = init.type === 'AwaitExpression';\n const call = awaited ? (init.argument as AstNode) : init;\n if (call.type !== 'CallExpression') return false;\n const origin = this.origin(identifierName(call.callee as AstNode));\n if (origin.verbaly === false) return false;\n const how = T_FACTORIES.get(origin.imported);\n return how !== undefined && (how === 'await') === awaited;\n }\n\n // { t: x } reads from something verbaly handed out, or from an auto-imported instance factory\n private carriesT(init: AstNode): boolean {\n const inner = init.type === 'AwaitExpression' ? (init.argument as AstNode) : init;\n const read = inner.type === 'CallExpression' ? (inner.callee as AstNode) : inner;\n const name = identifierName(read);\n if (!name) return false;\n const origin = this.origin(name);\n return origin.verbaly ?? INSTANCE_FACTORIES.has(name);\n }\n\n private origin(local: string): { verbaly: boolean | undefined; imported: string } {\n const found = this.imports.get(local);\n if (!found) return { verbaly: undefined, imported: local };\n return { verbaly: VERBALY_SOURCE.test(found.source), imported: found.imported };\n }\n}\n\nfunction importedName(node: AstNode): string {\n return node.type === 'StringLiteral' ? (node.value as string) : identifierName(node);\n}\n\nfunction identifierName(node: AstNode | null | undefined): string {\n return node?.type === 'Identifier' ? (node.name as string) : '';\n}\n\n// x`…` or x.id('…')`…` where x is a renamed t\nfunction renamedTag(tag: AstNode, renamed: ReadonlySet<string>): string | undefined {\n if (renamed.size === 0) return undefined;\n const name = identifierName(tag);\n if (renamed.has(name)) return name;\n if (tag.type !== 'CallExpression') return undefined;\n const callee = tag.callee as AstNode;\n if (callee.type !== 'MemberExpression' || callee.computed) return undefined;\n if (identifierName(callee.property as AstNode) !== 'id') return undefined;\n const object = identifierName(callee.object as AstNode);\n return renamed.has(object) ? object : undefined;\n}\n\n// the key a tagged template on a renamed t would have had: its quoted id, or its text's hash\nfunction missedKey(code: string, node: AstNode, names: ReadonlySet<string>): string | undefined {\n const tag = node.tag as AstNode;\n if (tag.type === 'CallExpression') {\n const args = tag.arguments as AstNode[];\n const first = args[0];\n return args.length === 1 && first?.type === 'StringLiteral'\n ? (first.value as string)\n : undefined;\n }\n const message = buildMessage(code, node.quasi as AstNode, names);\n return message ? stableKey(message.text) : undefined;\n}\n\n// every string leaf is a key: the call is the author saying so, and '' still means untranslated\nfunction collectDeclaredKeys(node: AstNode | undefined, file: string, out: UsedKey[]): void {\n if (node?.type !== 'ObjectExpression') return;\n for (const property of node.properties as AstNode[]) {\n if (property.type !== 'ObjectProperty') continue;\n const value = property.value as AstNode;\n const key = staticString(value);\n if (key !== undefined) {\n if (key !== '') out.push(usedKey(key, file, value));\n } else if (value.type === 'ObjectExpression') {\n collectDeclaredKeys(value, file, out);\n }\n }\n}\n\nfunction usedKey(key: string, file: string, node: AstNode | null | undefined): UsedKey {\n return node?.type === 'StringLiteral' ? { key, file } : { key, file, loose: true };\n}\n\n// a key is a literal however it is spelled: '…', `…` with no ${}, or {'…'} in a JSX attribute\nfunction staticString(node: AstNode | null | undefined): string | undefined {\n if (!node) return undefined;\n if (node.type === 'StringLiteral') return node.value as string;\n if (node.type === 'TemplateLiteral' && (node.expressions as AstNode[]).length === 0) {\n return cookedValue((node.quasis as AstNode[])[0]);\n }\n if (node.type === 'JSXExpressionContainer') return staticString(node.expression as AstNode);\n return undefined;\n}\n\nconst VERBALY_PACKAGE = /^(?:verbaly|@verbaly\\/[\\w-]+)$/;\n\n// the most plausible onboarding error: only the bundler used to complain, and never about verbaly\nfunction collectStrayImports(node: AstNode, file: string, out: StrayImport[]): void {\n const source = node.source as { value?: unknown };\n if (typeof source.value !== 'string' || !VERBALY_PACKAGE.test(source.value)) return;\n for (const spec of node.specifiers as AstNode[]) {\n if (spec.type !== 'ImportSpecifier') continue;\n const imported = spec.imported as AstNode;\n if (imported.type !== 'Identifier') continue;\n const name = imported.name as string;\n // both come from virtual:verbaly, which is the project's module and never a package export\n if (name === 't' || name === DEFINE_KEYS) out.push({ name, source: source.value, file });\n }\n}\n\nfunction handleTrans(\n code: string,\n node: AstNode,\n file: string,\n tagged: TaggedMessage[],\n usedKeys: UsedKey[],\n names: ReadonlySet<string>,\n): void {\n const opening = node.openingElement as AstNode;\n const nameNode = opening.name as AstNode;\n if (nameNode.type !== 'JSXIdentifier' || nameNode.name !== 'Trans') return;\n\n const attrs = opening.attributes as AstNode[];\n const idAttr = attrs.find((a) => a.type === 'JSXAttribute' && (a.name as AstNode).name === 'id');\n const children = node.children as AstNode[] | undefined;\n const push = (key: string, built: BuiltTrans) =>\n tagged.push({\n key,\n message: built.text,\n params: built.params,\n start: node.start,\n end: node.end,\n line: lineOf(node),\n tagStart: nameNode.start,\n tagEnd: nameNode.end,\n file,\n jsx: { name: nameNode.name as string, components: built.components },\n });\n\n if (idAttr) {\n const value = idAttr.value as AstNode | null;\n const id = staticString(value);\n if (id === undefined) return;\n // quoted id + children → extract under the explicit key; a backtick id never extracted before\n if (value?.type === 'StringLiteral' && attrs.length === 1 && children?.length) {\n const built = buildTransMessage(code, children, names);\n if (built?.text.trim()) {\n push(id, built);\n return;\n }\n }\n usedKeys.push(usedKey(id, file, value));\n return; // runtime-first, untouched\n }\n if (attrs.length > 0) return; // hand-written props → don't guess\n\n if (!children?.length) return;\n\n const built = buildTransMessage(code, children, names);\n if (!built || !built.text.trim()) return;\n\n push(stableKey(built.text), built);\n}\n\n// t.id('key')`…` → explicit readable key\nfunction explicitId(\n tag: AstNode,\n names: ReadonlySet<string>,\n): { key: string; refStart: number; refEnd: number } | undefined {\n if (tag.type !== 'CallExpression') return undefined;\n const callee = tag.callee as AstNode;\n if (callee.type !== 'MemberExpression' || callee.computed) return undefined;\n const prop = callee.property as AstNode;\n if (prop.type !== 'Identifier' || prop.name !== 'id') return undefined;\n const obj = callee.object as AstNode;\n if (!isTReference(obj, names)) return undefined;\n const args = tag.arguments as AstNode[];\n const first = args[0];\n // quoted only: extracting a backtick id now would be a new reason for a build to fail\n if (args.length !== 1 || first?.type !== 'StringLiteral') return undefined;\n return { key: first.value as string, refStart: obj.start, refEnd: obj.end };\n}\n\ninterface BuiltTrans {\n text: string;\n params: TaggedParam[];\n components: TransComponent[];\n}\n\nfunction buildTransMessage(\n code: string,\n children: AstNode[],\n names: ReadonlySet<string>,\n): BuiltTrans | undefined {\n const params: TaggedParam[] = [];\n const components: TransComponent[] = [];\n const takenParams = new Map<string, string>();\n const takenTags = new Map<string, string>();\n\n function walkChildren(nodes: AstNode[]): string | undefined {\n let text = '';\n for (const child of nodes) {\n if (child.type === 'JSXText') {\n text += escapeText(cleanJsxText(child.value as string));\n } else if (child.type === 'JSXExpressionContainer') {\n const expr = child.expression as AstNode;\n if (expr.type === 'JSXEmptyExpression') continue;\n if (expr.type === 'StringLiteral') {\n text += escapeText(expr.value as string);\n continue;\n }\n if (containsTaggedT(expr, names)) return undefined; // overlap hazard\n const source = code.slice(expr.start, expr.end);\n const name = uniqueName(deriveName(expr, params.length), source, takenParams);\n params.push({ name, start: expr.start, end: expr.end });\n text += `{${name}}`;\n } else if (child.type === 'JSXElement') {\n const opening = child.openingElement as AstNode;\n const nameNode = opening.name as AstNode;\n if (nameNode.type !== 'JSXIdentifier' || nameNode.name === 'Trans') return undefined;\n const source = selfClosedSource(code, opening);\n const tag = uniqueName((nameNode.name as string).toLowerCase(), source, takenTags);\n if (!components.some((c) => c.name === tag)) components.push({ name: tag, source });\n if (!child.closingElement) {\n text += `<${tag}/>`;\n } else {\n const inner = walkChildren(child.children as AstNode[]);\n if (inner === undefined) return undefined;\n text += `<${tag}>${inner}</${tag}>`;\n }\n } else {\n return undefined; // fragments / spread children → bail\n }\n }\n return text;\n }\n\n const text = walkChildren(children);\n if (text === undefined) return undefined;\n return { text, params, components };\n}\n\n// JSX text semantics: newline-indent boundaries removed, interior joins = one space\nexport function cleanJsxText(raw: string): string {\n const lines = raw.split(/\\r\\n|[\\r\\n]/);\n let out = '';\n for (let i = 0; i < lines.length; i++) {\n let line = lines[i]!.replace(/\\t/g, ' ');\n if (i !== 0) line = line.replace(/^ +/, '');\n if (i !== lines.length - 1) line = line.replace(/ +$/, '');\n if (!line) continue;\n if (out && i !== 0) out += ' ';\n out += line;\n }\n return out;\n}\n\nfunction selfClosedSource(code: string, opening: AstNode): string {\n const src = code.slice(opening.start, opening.end);\n return src.endsWith('/>') ? src : `${src.slice(0, -1).trimEnd()} />`;\n}\n\n// true if the subtree holds a t`…` / t.id('…')`…` that analyze would extract itself\nfunction containsTaggedT(node: AstNode, names: ReadonlySet<string>): boolean {\n let found = false;\n walk(node, (n) => {\n if (n.type !== 'TaggedTemplateExpression') return;\n const tag = n.tag as AstNode;\n if (isTReference(tag, names) || explicitId(tag, names)) found = true;\n });\n return found;\n}\n\nexport function isTReference(node: AstNode, names: ReadonlySet<string>): boolean {\n if (node.type === 'Identifier') return names.has(node.name as string);\n if (node.type === 'MemberExpression' && !node.computed) {\n const prop = node.property as AstNode;\n return prop.type === 'Identifier' && names.has(prop.name as string);\n }\n return false;\n}\n\ninterface BuiltMessage {\n text: string;\n params: TaggedParam[];\n}\n\nfunction buildMessage(\n code: string,\n quasi: AstNode,\n names: ReadonlySet<string>,\n): BuiltMessage | undefined {\n const quasis = quasi.quasis as AstNode[];\n const expressions = quasi.expressions as AstNode[];\n const params: TaggedParam[] = [];\n const taken = new Map<string, string>();\n\n let text = escapeText(cookedValue(quasis[0]));\n\n for (let i = 0; i < expressions.length; i++) {\n const expr = expressions[i];\n if (!expr) return undefined;\n // a nested t`…` would be extracted on its own: overlapping rewrites; bail the outer\n if (containsTaggedT(expr, names)) return undefined;\n const source = code.slice(expr.start, expr.end);\n const name = uniqueName(deriveName(expr, i), source, taken);\n params.push({ name, start: expr.start, end: expr.end });\n text += `{${name}}` + escapeText(cookedValue(quasis[i + 1]));\n }\n return { text, params };\n}\n\nfunction cookedValue(element: AstNode | undefined): string {\n if (!element) return '';\n const value = element.value as { cooked?: string; raw: string };\n return value.cooked ?? value.raw;\n}\n\n// literal braces → escaped\nfunction escapeText(text: string): string {\n return text.replace(/[{}]/g, (m) => m + m);\n}\n\nfunction deriveName(expr: AstNode, index: number): string {\n if (expr.type === 'Identifier') return expr.name as string;\n if (expr.type === 'MemberExpression' && !expr.computed) {\n const prop = expr.property as AstNode;\n if (prop.type === 'Identifier') return prop.name as string;\n }\n return `_${index}`;\n}\n\nfunction uniqueName(base: string, source: string, taken: Map<string, string>): string {\n let name = base;\n let n = 2;\n while (taken.has(name) && taken.get(name) !== source) {\n name = `${base}${n}`;\n n += 1;\n }\n taken.set(name, source);\n return name;\n}\n\nexport function walk(node: AstNode, visit: (node: AstNode) => void): void {\n visit(node);\n for (const key in node) {\n if (SKIP_KEYS.has(key)) continue;\n const value = node[key];\n if (Array.isArray(value)) {\n for (const item of value) {\n if (isNode(item)) walk(item, visit);\n }\n } else if (isNode(value)) {\n walk(value, visit);\n }\n }\n}\n\nfunction isNode(value: unknown): value is AstNode {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { type?: unknown }).type === 'string'\n );\n}\n","import {\n analyze,\n analyzeScript,\n parseErrorMessage,\n type Analysis,\n type AnalyzeOptions,\n type MissedCall,\n type StrayImport,\n type TaggedParam,\n type UsedKey,\n} from './analyze';\n\nexport const SFC_FILE_RE = /\\.(?:svelte|vue|astro)$/;\n\n// single dispatch point: SFCs get the block/markup analyzer, everything else plain analyze\nexport function analyzeFile(code: string, file: string): Analysis {\n if (SFC_FILE_RE.test(file)) return analyzeSfc(code, file);\n try {\n return analyze(code, file);\n } catch (error) {\n // one file the parser cannot read must never take down a whole extract, check or doctor\n const message = parseErrorMessage(error);\n return { tagged: [], usedKeys: [], strayImports: [], missed: [], parseError: message };\n }\n}\n\nconst SCRIPT_RE = /(<script\\b[^>]*>)([\\s\\S]*?)(<\\/script\\s*>)/gi;\nconst STYLE_RE = /<style\\b[^>]*>[\\s\\S]*?<\\/style\\s*>/gi;\nconst COMMENT_RE = /<!--[\\s\\S]*?-->/g;\n// astro component script: --- fences at the top of the file\nconst FRONTMATTER_RE = /^(\\uFEFF?\\s*---\\r?\\n)([\\s\\S]*?)\\r?\\n---(?=\\r?\\n|$)/;\n\nconst MUSTACHE_RE = /\\{\\{[\\s\\S]*?\\}\\}/g;\nconst DIRECTIVE_RE = /\\s(?:v-[\\w-]+(?::[^\\s=>/]+)?|[:@][^\\s=>/]+)\\s*=\\s*(\"[^\"]*\"|'[^']*')/g;\n\nexport function analyzeSfc(code: string, file: string): Analysis {\n // svelte components consume t as a store: $t`…` is the idiomatic form\n const svelte = file.endsWith('.svelte');\n const tNames = svelte ? ['t', '$t'] : ['t'];\n\n const tagged: Analysis['tagged'] = [];\n const usedKeys: UsedKey[] = [];\n const strayImports: StrayImport[] = [];\n const missed: MissedCall[] = [];\n const renamed = new Set<string>();\n const lineAt = lineCounter(code);\n let parseError: string | undefined;\n\n // a script block is structural: if it does not parse, the file is reported, unlike a markup slice\n const block = (content: string, offset: number): void => {\n const segment = analyzeSegment(content, file, { tNames });\n parseError ??= segment.error;\n for (const name of segment.renamed) renamed.add(name);\n merge(segment.analysis, offset, false);\n };\n\n const frontmatter = file.endsWith('.astro') ? FRONTMATTER_RE.exec(code) : null;\n if (frontmatter?.[2]) block(frontmatter[2], frontmatter[1]!.length);\n\n for (const match of code.matchAll(SCRIPT_RE)) {\n const content = match[2]!;\n if (content) block(content, match.index + match[1]!.length);\n }\n\n // markup = everything left once frontmatter, scripts, styles and comments are blanked out\n const body = frontmatter\n ? ' '.repeat(frontmatter[0].length) + code.slice(frontmatter[0].length)\n : code;\n const markup = blank(blank(blank(body, SCRIPT_RE), STYLE_RE), COMMENT_RE);\n // the markup reads the script's bindings, so a t renamed there is followed here too\n const markupOptions: AnalyzeOptions = { tNames, renamed: [...renamed] };\n // display-only text never yields candidates: only expression context counts\n const ranges = file.endsWith('.vue') ? vueExpressionRanges(markup) : braceRanges(markup);\n let range = 0;\n let consumedTo = 0;\n for (const match of markup.matchAll(candidatePattern(svelte, renamed))) {\n const start = match.index;\n if (start < consumedTo) continue;\n while (range < ranges.length && ranges[range]![1] <= start) range += 1;\n if (range >= ranges.length || start < ranges[range]![0]) continue;\n const end = expressionExtent(markup, start, match[0].length);\n if (end === undefined) continue;\n merge(analyzeSegment(code.slice(start, end), file, markupOptions).analysis, start, true);\n consumedTo = end;\n }\n\n return { tagged, usedKeys, strayImports, missed, ...(parseError && { parseError }) };\n\n function merge(analysis: Analysis | undefined, offset: number, markupSegment: boolean): void {\n if (!analysis) return;\n const lines = lineAt(offset) - 1;\n for (const msg of analysis.tagged) {\n tagged.push({\n ...msg,\n start: msg.start + offset,\n end: msg.end + offset,\n line: msg.line + lines,\n tagStart: msg.tagStart + offset,\n tagEnd: msg.tagEnd + offset,\n params: msg.params.map((p): TaggedParam => ({\n ...p,\n start: p.start + offset,\n end: p.end + offset,\n })),\n ...(markupSegment && { singleQuote: true }),\n });\n }\n for (const call of analysis.missed) {\n missed.push({ ...call, start: call.start + offset, line: call.line + lines });\n }\n usedKeys.push(...analysis.usedKeys);\n strayImports.push(...analysis.strayImports);\n }\n}\n\n// no whitespace after the name: prose like \"won't ('x')\" must never become a used key\nfunction candidatePattern(svelte: boolean, renamed: ReadonlySet<string>): RegExp {\n const bare = new Set(['t', ...[...renamed].map((name) => name.replace(/^\\$/, ''))]);\n const names = [...bare].map((name) => name.replace(/[$]/g, '\\\\$')).join('|');\n return new RegExp(`(?<![\\\\w$])${svelte ? '\\\\$?' : ''}(?:${names})(?=[\\`(]|\\\\.id\\\\()`, 'g');\n}\n\n// 1-based line of an offset, from one pass over the file however many segments ask\nfunction lineCounter(code: string): (offset: number) => number {\n const breaks: number[] = [];\n for (let i = code.indexOf('\\n'); i !== -1; i = code.indexOf('\\n', i + 1)) breaks.push(i);\n return (offset) => {\n let low = 0;\n let high = breaks.length;\n while (low < high) {\n const mid = (low + high) >> 1;\n if (breaks[mid]! < offset) low = mid + 1;\n else high = mid;\n }\n return low + 1;\n };\n}\n\ninterface SegmentResult {\n analysis?: Analysis;\n renamed: string[];\n error?: string;\n}\n\nfunction analyzeSegment(code: string, file: string, options: AnalyzeOptions): SegmentResult {\n try {\n return analyzeScript(code, file, options);\n } catch (error) {\n // never fail the whole file over one segment\n return { renamed: [], error: parseErrorMessage(error) };\n }\n}\n\nfunction blank(source: string, re: RegExp): string {\n return source.replace(re, (m) => ' '.repeat(m.length));\n}\n\n// [start, end) content spans of balanced {…} regions (astro expressions, svelte mustaches)\nfunction braceRanges(markup: string): Array<[number, number]> {\n const ranges: Array<[number, number]> = [];\n let i = 0;\n while (i < markup.length) {\n if (markup[i] === '{') {\n const end = balancedEnd(markup, i);\n if (end !== undefined) {\n ranges.push([i + 1, end - 1]);\n i = end;\n continue;\n }\n }\n i += 1;\n }\n return ranges;\n}\n\n// vue expression context: {{ mustaches }} plus quoted values of :/@/v- directive attributes\nfunction vueExpressionRanges(markup: string): Array<[number, number]> {\n const ranges: Array<[number, number]> = [];\n for (const match of markup.matchAll(MUSTACHE_RE)) {\n ranges.push([match.index + 2, match.index + match[0].length - 2]);\n }\n for (const match of markup.matchAll(DIRECTIVE_RE)) {\n const valueStart = match.index + match[0].length - match[1]!.length + 1;\n ranges.push([valueStart, valueStart + match[1]!.length - 2]);\n }\n return ranges.sort((a, b) => a[0] - b[0]);\n}\n\n// end (exclusive) of the expression starting at a candidate: t`…` | t(...) | t.id('…')`…`\nfunction expressionExtent(code: string, start: number, nameLength: number): number | undefined {\n const i = start + nameLength;\n if (code.startsWith('.id(', i)) {\n const close = balancedEnd(code, i + 3);\n if (close === undefined || code[close] !== '`') return undefined;\n return balancedEnd(code, close);\n }\n if (code[i] === '`' || code[i] === '(') return balancedEnd(code, i);\n return undefined;\n}\n\n// scans a template literal or paren group to its close, tracking nested ${…}, strings and groups\nfunction balancedEnd(code: string, open: number): number | undefined {\n const stack: string[] = [];\n let i = open;\n while (i < code.length) {\n const ch = code[i]!;\n if (stack[stack.length - 1] === '`') {\n if (ch === '\\\\') i += 1;\n else if (ch === '`') stack.pop();\n else if (ch === '$' && code[i + 1] === '{') {\n stack.push('{');\n i += 1;\n }\n } else if (ch === \"'\" || ch === '\"') {\n i = stringEnd(code, i);\n } else if (ch === '`' || ch === '(' || ch === '{') {\n stack.push(ch);\n } else if (ch === ')' || ch === '}') {\n if (stack[stack.length - 1] !== (ch === ')' ? '(' : '{')) return undefined;\n stack.pop();\n }\n i += 1;\n if (stack.length === 0) return i;\n }\n return undefined;\n}\n\nfunction stringEnd(code: string, start: number): number {\n const quote = code[start];\n let i = start + 1;\n while (i < code.length) {\n if (code[i] === '\\\\') i += 2;\n else if (code[i] === quote) return i;\n else i += 1;\n }\n return code.length;\n}\n","import { readFileSync } from 'node:fs';\nimport { relative } from 'node:path';\nimport { glob } from 'tinyglobby';\nimport { flatten } from 'verbaly';\nimport { emptyCatalog, own, type Catalogs } from './catalog';\nimport type { ResolvedConfig } from './config';\nimport { MessageRegistry } from './registry';\nimport { analyzeFile } from './sfc';\n\nexport async function extractProject(cfg: ResolvedConfig): Promise<MessageRegistry> {\n const files = await glob(cfg.include, {\n cwd: cfg.root,\n ignore: cfg.exclude,\n absolute: true,\n });\n const registry = new MessageRegistry();\n // tinyglobby crawls sibling folders in parallel, so its order changes from one run to the next\n for (const file of files.sort()) {\n registry.update(file, analyzeFile(readFileSync(file, 'utf8'), file));\n }\n return registry;\n}\n\n// root-relative with forward slashes so a translator reads the same path on any OS, one scan\nexport async function collectOrigins(\n cfg: ResolvedConfig,\n reuse?: MessageRegistry,\n): Promise<Record<string, string[]>> {\n const registry = reuse ?? (await extractProject(cfg));\n const origins: Record<string, string[]> = Object.create(null);\n for (const [key, files] of registry.origins()) {\n origins[key] = files.map((file) => relative(cfg.root, file).replaceAll('\\\\', '/'));\n }\n return origins;\n}\n\n// a source text the code wrote over, and what the catalog said before\nexport interface ReplacedText {\n key: string;\n before: string;\n}\n\nexport interface SyncResult {\n // keys new to each catalog; a source text the code rewrote is in replaced, not here\n added: Record<string, string[]>;\n replaced: ReplacedText[];\n}\n\n// fills source texts + '' placeholders; a text written in the code always wins over the catalog\nexport function syncCatalogs(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: MessageRegistry,\n): SyncResult {\n const added: Record<string, string[]> = {};\n const replaced: ReplacedText[] = [];\n const source = (catalogs[cfg.sourceLocale] ??= emptyCatalog());\n\n for (const [key, msg] of registry.messages()) {\n const before = own(source, key);\n if (before === msg.message) continue;\n source[key] = msg.message;\n if (before) replaced.push({ key, before });\n else (added[cfg.sourceLocale] ??= []).push(key);\n }\n\n const needed = Object.keys(source);\n for (const locale of cfg.locales) {\n if (locale === cfg.sourceLocale) continue;\n const catalog = (catalogs[locale] ??= emptyCatalog());\n for (const key of needed) {\n if (own(catalog, key) === undefined) {\n catalog[key] = '';\n (added[locale] ??= []).push(key);\n }\n }\n }\n return { added, replaced };\n}\n\n// the catalogs as a build ships them: the code's text wherever the code owns one, read-only\nexport function shippedCatalogs(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: MessageRegistry,\n // false: only keys the source catalog has, for the commands that run after extract\n options: { newKeys?: boolean } = {},\n): Catalogs {\n const source = Object.assign(emptyCatalog(), flatten(catalogs[cfg.sourceLocale] ?? {}));\n for (const [key, msg] of registry.messages()) {\n if (options.newKeys !== false || own(source, key) !== undefined) source[key] = msg.message;\n }\n return { ...catalogs, [cfg.sourceLocale]: source };\n}\n\n// drops keys no longer referenced\nexport function pruneCatalogs(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: MessageRegistry,\n): Record<string, string[]> {\n const removed: Record<string, string[]> = {};\n // a file the parser could not read still uses its keys, so pruning now deletes live translations\n if (registry.parseErrors().length > 0) return removed;\n const keep = new Set([...registry.messages().keys(), ...registry.usedKeys().keys()]);\n for (const locale of cfg.locales) {\n const catalog = catalogs[locale];\n if (!catalog) continue;\n for (const key of Object.keys(catalog)) {\n if (!keep.has(key)) {\n delete catalog[key];\n (removed[locale] ??= []).push(key);\n }\n }\n }\n return removed;\n}\n","import { parse, parseIcu, type MessageNode } from 'verbaly';\n\n// the gate reads every catalog on disk, so it always has the parser the runtime only opts into\nconst read = (message: string): MessageNode[] => parse(message, parseIcu);\n\nexport const PLURAL_CATEGORIES = new Set(['zero', 'one', 'two', 'few', 'many']);\nexport type IssueSeverity = 'error' | 'warning';\n\nexport interface StructureIssue {\n severity: IssueSeverity;\n message: string;\n}\n\ninterface VariantShape {\n selectors: string[];\n plural: boolean;\n ordinal: boolean;\n}\n\nconst EXACT = /^=\\d+$/;\n\n// param name → its plural/select block, when it has one; first block per name wins\nfunction shapes(message: string): Map<string, VariantShape> {\n const out = new Map<string, VariantShape>();\n walk(read(message), out);\n return out;\n}\n\nfunction walk(nodes: MessageNode[], out: Map<string, VariantShape>): void {\n for (const node of nodes) {\n if (node.kind !== 'param' || !node.variants) continue;\n const selectors = node.variants.map(([key]) => key);\n if (!out.has(node.name)) {\n out.set(node.name, {\n selectors,\n plural: selectors.some((key) => PLURAL_CATEGORIES.has(key)),\n ordinal: node.ordinal === true,\n });\n }\n for (const [, body] of node.variants) walk(body, out);\n }\n}\n\nfunction paramNames(message: string): string[] {\n const names = new Set<string>();\n collect(read(message), names);\n return [...names].sort();\n}\n\nfunction collect(nodes: MessageNode[], out: Set<string>): void {\n for (const node of nodes) {\n if (node.kind !== 'param') continue;\n out.add(node.name);\n if (node.variants) for (const [, body] of node.variants) collect(body, out);\n }\n}\n\nconst TAG = /<(\\/?)([a-zA-Z][\\w-]*)(\\/?)>/g;\n\n// markup is only what the message closes (</x>) or self-closes (<x/>): a lone <Enter> is prose\nfunction markupNames(message: string): Set<string> {\n const out = new Set<string>();\n for (const match of message.matchAll(TAG)) {\n if (match[1] || match[3]) out.add(match[2]!);\n }\n return out;\n}\n\nfunction tagTokens(message: string, markup: Set<string>): string[] {\n const out: string[] = [];\n for (const match of message.matchAll(TAG)) {\n if (markup.has(match[2]!)) out.push(`${match[1]}${match[2]}${match[3]}`);\n }\n return out.sort();\n}\n\n// items in a that are missing from b, counting duplicates\nfunction surplus(a: string[], b: string[]): string[] {\n const rest = [...b];\n const out: string[] = [];\n for (const item of a) {\n const at = rest.indexOf(item);\n if (at < 0) out.push(item);\n else rest.splice(at, 1);\n }\n return out;\n}\n\nfunction list(items: string[]): string {\n return items.length > 1\n ? `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`\n : items[0]!;\n}\n\n// a tagged template escapes its own braces, so a block written inside one ships as literal text\nconst ESCAPED_SYNTAX = /(?<!\\{)\\{\\{\\s*[\\w.]+\\s*[|:][^{}]*\\}\\}/;\n\n// the escaped slice of an extracted message, when the author meant a plural or format block\nexport function escapedSyntax(message: string): string | undefined {\n return ESCAPED_SYNTAX.exec(message)?.[0];\n}\n\n// one message on its own: defects that need no source to be visible\nexport function validateMessage(message: string, locale?: string): StructureIssue[] {\n const issues: StructureIssue[] = [];\n for (const [name, shape] of shapes(message)) {\n if (!shape.plural) continue; // a select block without 'other' is the author's design\n if (!shape.selectors.includes('other')) {\n issues.push({\n severity: 'error',\n message: `the plural block for {${name}} has no \"other\" case, so any count it does not list renders empty`,\n });\n continue;\n }\n if (!locale) continue;\n const missing = reachableCategories(locale, shape.ordinal).filter(\n (category) => category !== 'other' && !shape.selectors.includes(category),\n );\n if (missing.length > 0) {\n issues.push({\n severity: 'warning',\n message: `${locale} also needs the ${list(missing)} plural ${missing.length > 1 ? 'forms' : 'form'} for {${name}}`,\n });\n }\n }\n return issues;\n}\n\n// a translation against the source it must mirror\nexport function validatePair(source: string, translated: string): StructureIssue[] {\n const issues: StructureIssue[] = [];\n\n const lostParams = surplus(paramNames(source), paramNames(translated));\n const newParams = surplus(paramNames(translated), paramNames(source));\n if (lostParams.length > 0) {\n issues.push({\n severity: 'error',\n message: `${list(lostParams.map((name) => `{${name}}`))} ${lostParams.length > 1 ? 'are' : 'is'} missing, so ${lostParams.length > 1 ? 'their values never reach' : 'its value never reaches'} the text`,\n });\n }\n if (newParams.length > 0) {\n issues.push({\n severity: 'error',\n message: `${list(newParams.map((name) => `{${name}}`))} ${newParams.length > 1 ? 'are' : 'is'} not in the source message, so ${newParams.length > 1 ? 'they render' : 'it renders'} as literal text`,\n });\n }\n\n // one vocabulary for both sides: a tag the translation invents is still caught\n const markup = new Set([...markupNames(source), ...markupNames(translated)]);\n const lostTags = tagReport(surplus(tagTokens(source, markup), tagTokens(translated, markup)));\n const newTags = tagReport(surplus(tagTokens(translated, markup), tagTokens(source, markup)));\n if (lostTags.length > 0) {\n issues.push({\n severity: 'error',\n message: `${list(lostTags)} ${lostTags.length > 1 ? 'are' : 'is'} missing from the translation`,\n });\n }\n if (newTags.length > 0) {\n issues.push({\n severity: 'error',\n message: `${list(newTags)} ${newTags.length > 1 ? 'are' : 'is'} not in the source message`,\n });\n }\n\n const target = shapes(translated);\n for (const [name, shape] of shapes(source)) {\n const other = target.get(name);\n if (!other) {\n issues.push({\n severity: 'error',\n message: `the ${shape.plural ? 'plural' : 'select'} block for {${name}} was flattened into plain text`,\n });\n continue;\n }\n // 'other' is the catch-all: losing it renders empty (the plural case is validateMessage's)\n if (shape.selectors.includes('other') && !other.selectors.includes('other') && !other.plural) {\n issues.push({\n severity: 'error',\n message: `the \"other\" case for {${name}} is missing, so unlisted values render empty`,\n });\n }\n const lostExact = shape.selectors\n .filter((key) => EXACT.test(key))\n .filter((key) => !other.selectors.includes(key));\n if (lostExact.length > 0) {\n issues.push({\n severity: 'warning',\n message: `the ${list(lostExact)} ${lostExact.length > 1 ? 'cases' : 'case'} for {${name}} ${lostExact.length > 1 ? 'are' : 'is'} missing, so ${lostExact.length > 1 ? 'those counts' : 'that count'} falls back to \"other\"`,\n });\n }\n }\n\n return issues;\n}\n\n// one entry per tag name: a translator restores the pair, not a lone closing tag\nfunction tagReport(tokens: string[]): string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n for (const token of tokens) {\n const name = token.replaceAll('/', '');\n if (seen.has(name)) continue;\n seen.add(name);\n out.push(token.endsWith('/') ? `<${name}/>` : `<${name}>`);\n }\n return out;\n}\n\nconst COUNT_PROBE = 200; // the range a UI counter realistically reaches\nconst reachable = new Map<string, string[]>();\n\nfunction reachableCategories(locale: string, ordinal: boolean): string[] {\n const type = ordinal ? 'ordinal' : 'cardinal';\n // the escape, never the raw character: a literal NUL makes git treat the file as binary\n const cacheKey = `${locale}\\u0000${type}`;\n const hit = reachable.get(cacheKey);\n if (hit) return hit;\n\n let out: string[];\n try {\n // pt_BR formats as pt-BR at runtime, so its plurals are pt-BR's here too\n const rules = new Intl.PluralRules(locale.replace(/_/g, '-'), { type });\n const seen = new Set<string>();\n for (let n = 0; n <= COUNT_PROBE; n++) seen.add(rules.select(n));\n out = [...seen];\n } catch {\n out = []; // unknown tag: nothing is ever reported missing\n }\n reachable.set(cacheKey, out);\n return out;\n}\n","import { parse, parseIcu, type MessageNode } from 'verbaly';\nimport { PLURAL_CATEGORIES } from './validate';\n\nexport type ParamType = 'number' | 'string' | 'date' | 'unknown';\n\nconst NUMBER_FORMATS = new Set(['number', 'integer', 'percent', 'currency']);\nconst DATE_FORMATS = new Set(['date', 'time']);\n\nexport function collectParams(message: string): Map<string, Set<ParamType>> {\n const out = new Map<string, Set<ParamType>>();\n // with no parser an ICU message is one text node, so its params would be typed as none at all\n visit(parse(message, parseIcu), out);\n return out;\n}\n\nfunction visit(nodes: MessageNode[], out: Map<string, Set<ParamType>>): void {\n for (const node of nodes) {\n if (node.kind !== 'param') continue;\n const types = out.get(node.name) ?? new Set<ParamType>();\n out.set(node.name, types);\n\n if (node.variants) {\n for (const [key, body] of node.variants) {\n if (PLURAL_CATEGORIES.has(key) || /^=\\d+$/.test(key)) types.add('number');\n else if (key !== 'other') types.add('string');\n visit(body, out);\n }\n if (types.size === 0) types.add('string');\n } else if (node.format && NUMBER_FORMATS.has(node.format)) {\n types.add('number');\n } else if (node.format && DATE_FORMATS.has(node.format)) {\n types.add('date');\n } else {\n types.add('unknown');\n }\n }\n}\n\nexport function renderParamType(types: Set<ParamType>): string {\n if (types.has('unknown') || types.size === 0) return 'unknown';\n const members = new Set<string>();\n if (types.has('number')) members.add('number');\n if (types.has('string')) members.add('string');\n if (types.has('date')) for (const m of ['Date', 'number', 'string']) members.add(m);\n return [...members].join(' | ');\n}\n","import { readFileSync, writeFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { applyEdits, modify, parse, type FormattingOptions, type ParseError } from 'jsonc-parser';\nimport picomatch from 'picomatch';\n\nexport type IncludeState = 'present' | 'added' | 'missing' | 'no-tsconfig' | 'unreadable';\n\ninterface TsconfigShape {\n include?: unknown;\n files?: unknown;\n}\n\n// tsconfig.json as TypeScript reads it: comments and trailing commas are legal there\nfunction readTsconfig(root: string): { path: string; text: string; json: TsconfigShape } | string {\n const path = join(root, 'tsconfig.json');\n let text: string;\n try {\n text = readFileSync(path, 'utf8');\n } catch {\n return 'no-tsconfig';\n }\n const errors: ParseError[] = [];\n const json = parse(text, errors, { allowTrailingComma: true }) as unknown;\n if (errors.length > 0 || typeof json !== 'object' || json === null || Array.isArray(json)) {\n return 'unreadable';\n }\n return { path, text, json: json as TsconfigShape };\n}\n\n// as TypeScript matches an entry: a glob skips dot folders, and a bare folder means all inside it\nfunction covered(list: unknown, entry: string): boolean {\n if (!Array.isArray(list)) return false;\n return list.some((item) => {\n if (typeof item !== 'string') return false;\n const pattern = item.replace(/^\\.\\//, '').replace(/\\/+$/, '');\n return picomatch(pattern)(entry) || picomatch(`${pattern}/**/*`)(entry);\n });\n}\n\n// the indentation the file already uses, so the new line looks like the ones around it\nfunction formatting(text: string): FormattingOptions {\n const indent = /\\n([ \\t]+)\\S/.exec(text)?.[1] ?? ' ';\n return {\n insertSpaces: !indent.startsWith('\\t'),\n tabSize: indent.startsWith('\\t') ? 1 : indent.length,\n eol: text.includes('\\r\\n') ? '\\r\\n' : '\\n',\n };\n}\n\n// whether TypeScript reads the generated file: never true for a file outside the project\nexport function typesIncluded(root: string, file: string): IncludeState {\n const read = readTsconfig(root);\n if (typeof read === 'string') return read as IncludeState;\n const entry = relative(root, file).replaceAll('\\\\', '/');\n const { include, files } = read.json;\n if (covered(include, entry) || covered(files, entry)) return 'present';\n return 'missing';\n}\n\n// TypeScript never walks into a dot folder by itself: .verbaly/ needs a line, like .next/types\nexport function includeTypes(root: string, file: string): IncludeState {\n const read = readTsconfig(root);\n if (typeof read === 'string') return read as IncludeState;\n const entry = relative(root, file).replaceAll('\\\\', '/');\n const { include, files } = read.json;\n if (covered(include, entry) || covered(files, entry)) return 'present';\n\n const options = { formattingOptions: formatting(read.text) };\n // a files list with no include means include defaults to nothing, so the entry goes there\n const edits = Array.isArray(include)\n ? modify(read.text, ['include', -1], entry, { ...options, isArrayInsertion: true })\n : Array.isArray(files) && include === undefined\n ? modify(read.text, ['files', -1], entry, { ...options, isArrayInsertion: true })\n : modify(read.text, ['include'], ['**/*', entry], options);\n writeFileSync(read.path, applyEdits(read.text, edits));\n return 'added';\n}\n","const warned = new Set<string>();\n\n// one warn-once for the whole compiler: dedupe by static content, never by a value being edited\nexport function warnOnce(message: string, dedupeKey = message): void {\n if (warned.has(dedupeKey)) return;\n warned.add(dedupeKey);\n console.warn(`[verbaly] ${message}`);\n}\n\n// bundler paths only: the CLI reports its own run, so a file is never announced twice\nexport function warnParseError(file: string, message: string): void {\n warnOnce(`${file}: could not be parsed (${message}), its messages were not extracted`);\n}\n","import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\nimport type { Catalog } from './catalog';\nimport type { ResolvedConfig } from './config';\nimport { withLineEndings } from './eol';\nimport { collectParams, renderParamType } from './params';\nimport { byCodeUnit } from './text';\nimport { includeTypes } from './tsconfig';\nimport { warnOnce } from './warn';\n\nexport const VIRTUAL_ID = 'virtual:verbaly';\n\n// the header every generated d.ts opens with: a file without it was written by a person\nexport const DTS_HEADER = '// generated by verbaly: do not edit';\n\nexport interface RuntimeModuleOptions {\n localeImport?: (locale: string) => string;\n extraExports?: string;\n icu?: boolean;\n relative?: boolean;\n inlineCatalog?: boolean;\n}\n\n// only under inlineCatalog: read the blob `verbaly render` left, and take the next page's own\nconst SLICE_HELPERS = `function readSlice(root, path) {\n const locale = readPath({ supported: locales, path });\n if (!locale || locale === sourceLocale) return undefined;\n const messages = inlineMessages(root);\n return messages ? { locale, messages } : undefined;\n}\n\nexport function adoptPage(options) {\n const slice = readSlice(options?.root, options?.path);\n if (slice) v.addMessages(slice.locale, slice.messages, { partial: true });\n return slice ? slice.locale : undefined;\n}\n\n`;\n\nexport function generateRuntimeModule(\n cfg: ResolvedConfig,\n options: RuntimeModuleOptions = {},\n): string {\n const importPath = options.localeImport ?? ((locale: string) => `${VIRTUAL_ID}/locale/${locale}`);\n const others = cfg.locales.filter((locale) => locale !== cfg.sourceLocale);\n const src = JSON.stringify(cfg.sourceLocale);\n const loaders = others\n .map((locale) => ` ${JSON.stringify(locale)}: () => import('${importPath(locale)}'),`)\n .join('\\n');\n\n // named in the import list only when a catalog uses them, so otherwise they tree-shake out\n const icu = options.icu ? ',\\n parseIcu' : '';\n const rel = options.relative ? ',\\n relativeFormatter' : '';\n const slice = options.inlineCatalog ? ',\\n inlineMessages' : '';\n const slices = options.inlineCatalog ? SLICE_HELPERS : '';\n\n return `import {\n createVerbaly,\n localeFromPath as readPath,\n localePath as writePath,\n switchLocale as runSwitch${icu}${rel}${slice},\n} from 'verbaly';\nimport source from '${importPath(cfg.sourceLocale)}';\n\nexport const sourceLocale = ${src};\nexport const locales = ${JSON.stringify(cfg.locales)};\nexport const routing = ${JSON.stringify(cfg.routing)};\n\n// bound to this project: the locale set, the source and the routing mode are never passed in\nexport function localePath(locale, options) {\n return writePath(locale, { ...options, supported: locales, sourceLocale, routing });\n}\n\nexport function localeFromPath(options) {\n return readPath({ ...options, supported: locales });\n}\n\n// identity: it exists so the compiler can see keys that live in a module instead of at a call site\nexport function defineKeys(keys) {\n return keys;\n}\n\n// the whole switch a language control needs, in either mode: catalog or navigation, then persistence\nexport function switchLocale(locale, options) {\n return runSwitch(v, locale, { supported: locales, sourceLocale, routing, ...options });\n}\n\nconst localeLoaders = {\n${loaders}\n};\n\n// raw catalog access: SSR integrations serialize it across the client boundary\nexport async function loadMessages(locale) {\n if (locale === ${src}) return source;\n // own entries only: a locale named constructor must be a miss, not the Object function\n const loader = Object.prototype.hasOwnProperty.call(localeLoaders, locale)\n ? localeLoaders[locale]\n : undefined;\n return loader ? (await loader()).default : {};\n}\n\n${slices}// per-request/per-instance factory (SSR): the singleton below is browser/SPA-only\nexport function createInstance(options) {${\n options.inlineCatalog ? '\\n const page = readSlice();' : ''\n }\n return createVerbaly({\n locale: ${options.inlineCatalog ? `page ? page.locale : ${src}` : src},\n fallback: ${src},\n messages: ${\n options.inlineCatalog\n ? `page ? { [${src}]: source, [page.locale]: page.messages } : { [${src}]: source }`\n : `{ [${src}]: source }`\n },\n loaders: localeLoaders,${options.inlineCatalog ? '\\n partial: page ? [page.locale] : undefined,' : ''}${options.icu ? '\\n icu: parseIcu,' : ''}\n ...options,${\n options.relative\n ? '\\n // merged, not spread over: passing your own formatters must not drop this one' +\n '\\n formatters: { relative: relativeFormatter, ...options?.formatters },'\n : ''\n }\n });\n}\n\n// the no-FOUC contract in one call: fresh instance + catalog awaited before render\nexport async function createRequestInstance(locale) {\n const instance = createInstance({ locale });\n await instance.loadLocale(locale);\n return instance;\n}\n\nconst v = createInstance();\n\nexport const verbaly = v;\nexport const t = v.t;\n\nexport function getLocale() {\n return v.locale;\n}\n\nexport function subscribe(listener) {\n return v.subscribe(listener);\n}\n\nexport async function setLocale(locale) {\n await v.loadLocale(locale);\n v.setLocale(locale);\n}\n${options.extraExports ?? ''}`;\n}\n\nexport function generateLocaleModule(catalog: Catalog): string {\n // \"__proto__\": in an object literal sets the prototype; computed, it stays a key like any other\n const json = JSON.stringify(catalog).replace(/([{,])\"__proto__\":/, '$1[\"__proto__\"]:');\n return `export default ${json};\\n`;\n}\n\nexport interface DtsOptions {\n inlineCatalog?: boolean;\n locales?: string[];\n}\n\nexport function generateDts(catalog: Catalog, options: DtsOptions = {}): string {\n const lines: string[] = [];\n const locales = options.locales?.length\n ? [...options.locales]\n .sort(byCodeUnit)\n .map((locale) => JSON.stringify(locale))\n .join(' | ')\n : 'string';\n for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => byCodeUnit(a, b))) {\n const params = collectParams(message);\n if (params.size === 0) {\n lines.push(` ${JSON.stringify(key)}: never;`);\n } else {\n const fields = [...params.entries()]\n .map(([name, types]) => `${JSON.stringify(name)}: ${renderParamType(types)}`)\n .join('; ');\n lines.push(` ${JSON.stringify(key)}: { ${fields} };`);\n }\n }\n\n return `${DTS_HEADER}\ndeclare module 'virtual:verbaly' {\n export interface VerbalyMessages {\n${lines.join('\\n')}\n }\n export type VerbalyKey = keyof VerbalyMessages & string;\n export type VerbalyLocale = ${locales};\n\n export type VerbalyKeyTree = VerbalyKey | { readonly [name: string]: VerbalyKeyTree };\n export function defineKeys<const T extends VerbalyKeyTree>(keys: T): T;\n\n export const verbaly: import('verbaly').Verbaly;\n\n export const sourceLocale: VerbalyLocale;\n export const locales: string[];\n export const routing: import('verbaly').Routing;\n export function localePath(\n locale: string,\n options?: { path?: string; base?: string },\n ): string;\n export function localeFromPath(options?: {\n path?: string;\n base?: string;\n }): string | undefined;\n export function loadMessages(locale: string): Promise<Record<string, string>>;${\n options.inlineCatalog\n ? '\\n export function adoptPage(options?: {' +\n '\\n root?: ParentNode;' +\n '\\n path?: string;' +\n '\\n }): string | undefined;'\n : ''\n }\n export function createInstance(\n options?: import('verbaly').VerbalyOptions,\n ): import('verbaly').Verbaly;\n export function createRequestInstance(locale: string): Promise<import('verbaly').Verbaly>;\n\n // a key written as a literal must exist; string, or a template with a part from data, is data\n export function t<K extends VerbalyKey | TemplateStringsArray | (string & {})>(\n first: K extends TemplateStringsArray\n ? K\n : {} extends Record<K & string, 1>\n ? K\n : K extends VerbalyKey ? K : VerbalyKey,\n ...rest: [K] extends [never]\n ? [params?: import('verbaly').Params]\n : K extends TemplateStringsArray\n ? unknown[]\n : {} extends Record<K & string, 1>\n ? [params?: import('verbaly').Params]\n : K extends VerbalyKey\n ? [VerbalyMessages[K]] extends [never] ? [] : [VerbalyMessages[K]]\n : unknown[]\n ): string;\n export namespace t {\n export function id(\n key: string,\n ): (strings: TemplateStringsArray, ...values: unknown[]) => string;\n }\n\n export function setLocale(locale: string): Promise<void>;\n export function switchLocale(\n locale: string,\n options?: Omit<\n import('verbaly').SwitchLocaleOptions,\n 'routing' | 'supported' | 'sourceLocale'\n >,\n ): Promise<void>;\n export function getLocale(): string;\n export function subscribe(listener: () => void): () => void;\n\n // nested, so it augments verbaly: at the top of a script it would replace the real module\n module 'verbaly' {\n interface Register {\n t: typeof t;\n locale: VerbalyLocale;\n }\n }\n}\n\ndeclare module 'virtual:verbaly/locale/*' {\n const messages: Record<string, string>;\n export default messages;\n}\n`;\n}\n\n// the d.ts a project gets: what the config says about it is passed the same way everywhere\nexport function projectDtsOptions(cfg: ResolvedConfig): DtsOptions {\n return { inlineCatalog: cfg.render.inlineCatalog === true, locales: cfg.locales };\n}\n\nexport interface DtsWrite {\n file: string;\n changed: boolean;\n}\n\n// unchanged writes are skipped: a rewritten d.ts churns the consumer's TS server\nexport function writeDts(\n cfg: ResolvedConfig,\n catalog: Catalog,\n file?: string | false,\n): DtsWrite | undefined {\n // the config decides unless a caller names a file: dts false means no file anywhere\n const target = file === undefined ? cfg.dts : file;\n if (target === false) return undefined;\n let existing: string | undefined;\n try {\n existing = readFileSync(target, 'utf8');\n } catch {\n // new file\n }\n const content = withLineEndings(generateDts(catalog, projectDtsOptions(cfg)), existing);\n const changed = existing !== content;\n if (changed) {\n mkdirSync(dirname(target), { recursive: true });\n writeFileSync(target, content);\n }\n removeRootDts(cfg, target);\n // .verbaly/ is a dot folder, and TypeScript only reads one that tsconfig names\n if (resolve(target).startsWith(resolve(cfg.root, '.verbaly') + sep)) {\n // generated and never committed: the .gitignore withVerbaly writes next to its modules\n const ignore = join(cfg.root, '.verbaly', '.gitignore');\n if (!existsSync(ignore)) writeFileSync(ignore, '*\\n');\n const state = includeTypes(cfg.root, target);\n const entry = relative(cfg.root, target).replaceAll('\\\\', '/');\n if (state === 'added') {\n warnOnce(`added \"${entry}\" to the include of tsconfig.json, so TypeScript reads the types`);\n } else if (state === 'unreadable') {\n warnOnce(`tsconfig.json could not be read, so add \"${entry}\" to its include yourself`);\n }\n }\n return { file: target, changed };\n}\n\n// the types moved out of the root: the old file would declare the same module a second time\nfunction removeRootDts(cfg: ResolvedConfig, target: string): void {\n const old = join(cfg.root, 'verbaly.d.ts');\n if (resolve(target) === resolve(old)) return;\n let head: string;\n try {\n head = readFileSync(old, 'utf8').slice(0, DTS_HEADER.length);\n } catch {\n return;\n }\n // a verbaly.d.ts someone wrote by hand is theirs\n if (head !== DTS_HEADER) return;\n rmSync(old);\n const moved = relative(cfg.root, target).replaceAll('\\\\', '/');\n warnOnce(\n `the types live in ${moved} now, so the verbaly.d.ts Verbaly wrote at the root was removed`,\n );\n}\n","import { relative } from 'node:path';\nimport type { TaggedMessage } from './analyze';\nimport type { ResolvedConfig } from './config';\nimport type { ReplacedText } from './extract';\nimport type { MessageRegistry } from './registry';\nimport type { OutdatedEntry } from './state';\nimport { counted, truncate } from './text';\nimport { escapedSyntax } from './validate';\n\n// where a text is written in the code: an absolute file, like every path check reports\nexport interface SourceSite {\n file: string;\n line?: number;\n message: string;\n}\n\nexport interface CollisionEntry {\n key: string;\n sites: SourceSite[];\n}\n\n// a source text the code wrote over; edited when the run knows a person changed the catalog\nexport interface ReplacedEntry {\n locale: string;\n key: string;\n before: string;\n site: SourceSite;\n edited?: boolean;\n}\n\nexport interface RenamedEntry {\n name: string;\n file: string;\n line?: number;\n}\n\nexport interface PositionalEntry {\n params: string[];\n site: SourceSite;\n}\n\nexport interface EscapedEntry {\n slice: string;\n site: SourceSite;\n}\n\nexport interface UnparsedEntry {\n file: string;\n message: string;\n}\n\n// what a scan finds that never fails a gate; every surface words it through formatFinding\nexport type Finding =\n | ({ kind: 'replaced' } & ReplacedEntry)\n | ({ kind: 'collision' } & CollisionEntry)\n | ({ kind: 'renamed' } & RenamedEntry)\n | ({ kind: 'positional' } & PositionalEntry)\n | ({ kind: 'escaped' } & EscapedEntry)\n | ({ kind: 'unparsed' } & UnparsedEntry)\n | ({ kind: 'outdated' } & OutdatedEntry);\n\nexport function siteOf(msg: TaggedMessage): SourceSite {\n return { file: msg.file, line: msg.line, message: msg.message };\n}\n\nexport function collisionEntries(registry: MessageRegistry): CollisionEntry[] {\n return registry.collisions().map(({ key, kept, dropped }) => ({\n key,\n sites: [kept, ...dropped].map(siteOf),\n }));\n}\n\n// one pass, a fixed order: the same project always reads as the same report\nexport function scanFindings(\n cfg: ResolvedConfig,\n registry: MessageRegistry,\n replaced: ReplacedText[] = [],\n): Finding[] {\n const messages = registry.messages();\n const out: Finding[] = [];\n for (const { key, before } of replaced) {\n const msg = messages.get(key);\n if (msg)\n out.push({ kind: 'replaced', locale: cfg.sourceLocale, key, before, site: siteOf(msg) });\n }\n for (const entry of collisionEntries(registry)) out.push({ kind: 'collision', ...entry });\n for (const { name, file, line } of registry.missed()) {\n out.push({ kind: 'renamed', name, file, line });\n }\n for (const msg of messages.values()) {\n // a translator who reads {_0} cannot know what goes there\n const params = msg.params.map((param) => param.name).filter((name) => /^_\\d+$/.test(name));\n if (params.length > 0) out.push({ kind: 'positional', params, site: siteOf(msg) });\n const slice = escapedSyntax(msg.message);\n if (slice) out.push({ kind: 'escaped', slice, site: siteOf(msg) });\n }\n for (const { file, message } of registry.parseErrors()) {\n out.push({ kind: 'unparsed', file, message });\n }\n return out;\n}\n\n// file:line, so the editor and the terminal can jump to where the text is written\nexport function sourcePlace(at: { file: string; line?: number }, root?: string): string {\n const file = root ? relative(root, at.file).replaceAll('\\\\', '/') : at.file;\n return at.line ? `${file}:${at.line}` : file;\n}\n\nfunction quoted(at: SourceSite, root?: string): string {\n return `\"${truncate(at.message, 40)}\" (${sourcePlace(at, root)})`;\n}\n\n// the one wording of a collision, shared by extract, check, doctor and both dev servers\nexport function formatCollision({ key, sites }: CollisionEntry, root?: string): string {\n const [kept, ...others] = sites as [SourceSite, ...SourceSite[]];\n const texts = new Set(sites.map((at) => at.message)).size;\n return (\n `${key}: one key with ${counted(texts, 'text')}, and every place shows ${quoted(kept, root)}, ` +\n `never ${others.map((at) => quoted(at, root)).join(' or ')}: give each text its own key`\n );\n}\n\n// the one wording of every finding; each surface adds its own prefix or indent\nexport function formatFinding(finding: Finding, root?: string): string {\n switch (finding.kind) {\n case 'collision':\n return formatCollision(finding, root);\n case 'replaced': {\n const place = sourcePlace(finding.site, root);\n return finding.edited\n ? `${finding.locale}.json: your edit of \"${finding.key}\" was replaced, its text lives in ${place}: change it there`\n : `${finding.locale}: ${finding.key} follows the code (${place}): \"${truncate(finding.site.message, 40)}\", was \"${truncate(finding.before, 40)}\"`;\n }\n case 'renamed':\n return `${sourcePlace(finding, root)}: ${finding.name}\\`…\\` is never extracted, so it stays in the source language: name it t`;\n case 'positional': {\n const names = finding.params.map((name) => `{${name}}`).join(', ');\n 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`;\n }\n case 'escaped':\n return `${sourcePlace(finding.site, root)}: ${finding.slice} renders as literal text, a tagged template has no params (use t(key, params) for a plural or format block, or pass a \\${…} value)`;\n case 'unparsed':\n return `${sourcePlace(finding, root)}: could not be parsed (${finding.message}), its messages were not extracted`;\n case 'outdated':\n return `[${finding.locale}] ${finding.key}: translated from an older source text, update it or keep it with \\`npx verbaly review --approve\\``;\n }\n}\n\n// keyed on what a finding is about, never on its text: a dev server re-runs per keystroke\nfunction findingId(finding: Finding): string {\n switch (finding.kind) {\n case 'collision':\n case 'replaced':\n return `${finding.kind}:${finding.key}`;\n case 'outdated':\n return `outdated:${finding.locale}:${finding.key}`;\n case 'renamed':\n return `renamed:${finding.file}:${finding.name}`;\n case 'positional':\n return `positional:${finding.site.file}:${finding.params.join(',')}`;\n case 'escaped':\n return `escaped:${finding.site.file}:${finding.slice}`;\n case 'unparsed':\n return `unparsed:${finding.file}`;\n }\n}\n\nexport interface DevReporter {\n // prints what is new in this channel since its last report, and forgets what went away\n report(channel: string, findings: Finding[]): void;\n}\n\n// once per finding, and again only after it went away and came back; a few at a time\nexport function createDevReporter(\n root: string,\n print: (line: string) => void = (line) => console.warn(`[verbaly] ${line}`),\n cap = 5,\n): DevReporter {\n const shown = new Map<string, Set<string>>();\n return {\n report(channel, findings) {\n const before = shown.get(channel) ?? new Set<string>();\n const now = new Set<string>();\n const fresh: Finding[] = [];\n for (const finding of findings) {\n const id = findingId(finding);\n if (now.has(id)) continue;\n now.add(id);\n if (!before.has(id)) fresh.push(finding);\n }\n shown.set(channel, now);\n for (const finding of fresh.slice(0, cap)) print(formatFinding(finding, root));\n if (fresh.length > cap)\n print(`and ${fresh.length - cap} more: \\`npx verbaly doctor\\` names them`);\n },\n };\n}\n","import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { flatten, type MessageTree } from 'verbaly';\nimport { catalogPath, emptyCatalog, own, type Catalog, type Catalogs } from './catalog';\nimport { targetLocales, type ResolvedConfig } from './config';\nimport { withLineEndings } from './eol';\nimport { stableKey } from './key';\nimport { byCodeUnit } from './text';\n\nexport const STATE_FILE = '.verbaly-state.json';\n// before 0.67.0 the sidecar held only the drafts, and a teammate on 0.66.0 still writes it\nconst LEGACY_DRAFTS_FILE = '.verbaly-drafts.json';\n\nexport type Drafts = Record<string, string[]>;\n\n// locale -> key -> \"<source>.<translation>\" fingerprints from when that translation was written\nexport type Fingerprints = Record<string, Record<string, string>>;\n\nexport interface State {\n drafts: Drafts;\n fingerprints: Fingerprints;\n}\n\nexport interface OutdatedEntry {\n locale: string;\n key: string;\n}\n\n// what a read-only path gets: the state, or nothing plus the reason it could not be read\nexport interface StateRead {\n state: State;\n problem?: string;\n}\n\n// a translation just written, and the source text it was written for when that is not today's\nexport interface WrittenTranslation {\n key: string;\n text: string;\n source?: string;\n}\n\nexport interface TranslationWrite {\n locale: string;\n entries: WrittenTranslation[];\n draft?: boolean;\n}\n\nfunction statePath(cfg: ResolvedConfig, file = STATE_FILE): string {\n return join(cfg.dir, file);\n}\n\nexport function loadState(cfg: ResolvedConfig): State {\n const current = readJson(statePath(cfg));\n if (current !== undefined && !isObject(current)) throw corrupt(statePath(cfg));\n const legacy = readJson(statePath(cfg, LEGACY_DRAFTS_FILE));\n if (legacy !== undefined && !isObject(legacy)) throw corrupt(statePath(cfg, LEGACY_DRAFTS_FILE));\n const state: State = isObject(current)\n ? { drafts: readDrafts(current.drafts), fingerprints: readFingerprints(current.fingerprints) }\n : { drafts: {}, fingerprints: {} };\n // drafts the old file still lists join the new ones, and the next save removes that file\n if (legacy !== undefined) {\n for (const [locale, keys] of Object.entries(readDrafts(legacy))) {\n markDrafts(state.drafts, locale, keys);\n }\n }\n return state;\n}\n\n// read-only paths go on without the state: it only feeds warnings, never a gate they run\nexport function readState(cfg: ResolvedConfig): StateRead {\n try {\n return { state: loadState(cfg) };\n } catch (error) {\n const problem = (error as Error).message.replace(/^\\[verbaly\\] /, '');\n return { state: { drafts: {}, fingerprints: {} }, problem };\n }\n}\n\n// content-compared like a catalog, and gone when there is nothing left to remember\nexport function saveState(cfg: ResolvedConfig, state: State): void {\n const fresh = serializeState(state);\n const path = statePath(cfg);\n const legacy = statePath(cfg, LEGACY_DRAFTS_FILE);\n if (fresh === undefined) {\n rmSync(path, { force: true });\n rmSync(legacy, { force: true });\n return;\n }\n let existing: string | undefined;\n try {\n existing = readFileSync(path, 'utf8');\n } catch {\n mkdirSync(cfg.dir, { recursive: true });\n }\n const serialized = withLineEndings(fresh, existing);\n if (existing !== serialized) writeFileSync(path, serialized);\n if (existsSync(legacy)) rmSync(legacy);\n}\n\n// the state follows the catalogs it is shown; a locale whose catalog was not read stays as it was\nexport function updateState(cfg: ResolvedConfig, catalogs: Catalogs): State {\n const next = refreshState(cfg, catalogs, loadState(cfg));\n saveState(cfg, next);\n return next;\n}\n\nfunction refreshState(cfg: ResolvedConfig, catalogs: Catalogs, previous: State): State {\n const flat = flatCatalogs(catalogs);\n const source = flat[cfg.sourceLocale] ?? {};\n // a narrowed --locales run, or a catalog missing mid-checkout, must never erase what it held\n const shown = new Set(\n targetLocales(cfg).filter(\n (locale) => Object.hasOwn(flat, locale) && existsSync(catalogPath(cfg, locale)),\n ),\n );\n const drafts: Drafts = {};\n for (const [locale, keys] of Object.entries(previous.drafts)) {\n if (!shown.has(locale)) {\n drafts[locale] = keys;\n continue;\n }\n // a draft counts only while its translation is present: a pruned key is missing, not a draft\n const live = keys.filter((key) => own(flat[locale]!, key));\n if (live.length) drafts[locale] = live;\n }\n const fingerprints: Fingerprints = {};\n for (const [locale, stamps] of Object.entries(previous.fingerprints)) {\n if (!shown.has(locale)) fingerprints[locale] = stamps;\n }\n for (const locale of shown) {\n const stamps = refreshStamps(source, flat[locale]!, previous.fingerprints[locale] ?? {});\n if (Object.keys(stamps).length) fingerprints[locale] = stamps;\n }\n return { drafts, fingerprints };\n}\n\n// a stamp lives as long as its translation: kept while the translation is unchanged\nfunction refreshStamps(\n source: Catalog,\n catalog: Catalog,\n before: Record<string, string>,\n): Record<string, string> {\n const after: Record<string, string> = emptyCatalog();\n for (const key of new Set([...Object.keys(before), ...Object.keys(source)])) {\n const translated = own(catalog, key);\n if (!translated) continue;\n const was = own(before, key);\n if (was !== undefined && translationOf(was) === fingerprint(translated)) {\n after[key] = was;\n continue;\n }\n const text = own(source, key);\n // a new or edited translation was written for the source as it reads now\n if (text && tracked(key, text)) after[key] = stamp(text, translated);\n // edited while its source is empty: the old stamp waits until there is a source again\n else if (was !== undefined) after[key] = was;\n }\n return after;\n}\n\n// a translation written now was written for a known source: stamped and flagged in one save\nexport function recordTranslations(\n cfg: ResolvedConfig,\n source: Catalog,\n writes: TranslationWrite[],\n): State {\n const state = loadState(cfg);\n for (const { locale, entries, draft } of writes) {\n if (entries.length === 0) continue;\n const stamps = (state.fingerprints[locale] ??= emptyCatalog());\n for (const entry of entries) {\n const from = entry.source || own(source, entry.key);\n if (from && entry.text && tracked(entry.key, from)) {\n stamps[entry.key] = stamp(from, entry.text);\n }\n }\n const keys = entries.map((entry) => entry.key);\n if (draft === true) markDrafts(state.drafts, locale, keys);\n else if (draft === false) clearDrafts(state.drafts, locale, keys);\n }\n saveState(cfg, state);\n return state;\n}\n\n// a draft counts only while its translation is present: a pruned key is missing, not a draft\nexport function effectiveDrafts(drafts: Drafts, catalogs: Catalogs): Drafts {\n const out: Drafts = {};\n for (const [locale, keys] of Object.entries(drafts)) {\n const catalog = catalogs[locale] ?? {};\n const live = keys.filter((key) => own(catalog, key));\n if (live.length) out[locale] = live;\n }\n return out;\n}\n\nexport function markDrafts(drafts: Drafts, locale: string, keys: string[]): void {\n if (!keys.length) return;\n drafts[locale] = [...new Set([...(drafts[locale] ?? []), ...keys])];\n}\n\n// clears specific keys, or the whole locale when keys is omitted (approve everything)\nexport function clearDrafts(drafts: Drafts, locale: string, keys?: string[]): void {\n if (!drafts[locale]) return;\n if (!keys) {\n delete drafts[locale];\n return;\n }\n const drop = new Set(keys);\n drafts[locale] = drafts[locale].filter((key) => !drop.has(key));\n if (!drafts[locale].length) delete drafts[locale];\n}\n\nexport function fingerprint(text: string): string {\n return stableKey(text);\n}\n\n// a hash key is its own text: a new text is a new key, so its translation can never be stale\nfunction tracked(key: string, text: string): boolean {\n return stableKey(text) !== key;\n}\n\nfunction stamp(source: string, translated: string): string {\n return `${fingerprint(source)}.${fingerprint(translated)}`;\n}\n\nexport function outdatedTranslations(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n fingerprints: Fingerprints,\n): OutdatedEntry[] {\n const source = catalogs[cfg.sourceLocale] ?? {};\n const out: OutdatedEntry[] = [];\n for (const locale of targetLocales(cfg)) {\n const catalog = catalogs[locale] ?? {};\n for (const [key, was] of Object.entries(fingerprints[locale] ?? {})) {\n const text = own(source, key);\n const translated = own(catalog, key);\n if (!text || !translated) continue;\n // edited since it was stamped: whoever touched it last wrote it against this source\n if (translationOf(was) !== fingerprint(translated)) continue;\n if (sourceOf(was) !== fingerprint(text)) out.push({ locale, key });\n }\n }\n // code unit order, the one the catalogs use: localeCompare differs from machine to machine\n return out.sort((a, b) => byCodeUnit(a.locale, b.locale) || byCodeUnit(a.key, b.key));\n}\n\n// a person read it against the new source and kept it: stamp it as written for that source\nexport function acceptOutdated(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n fingerprints: Fingerprints,\n entries: OutdatedEntry[],\n): void {\n const source = catalogs[cfg.sourceLocale] ?? {};\n for (const { locale, key } of entries) {\n const text = own(source, key);\n const translated = own(catalogs[locale] ?? {}, key);\n if (!text || !translated) continue;\n (fingerprints[locale] ??= emptyCatalog())[key] = stamp(text, translated);\n }\n}\n\nfunction sourceOf(stamped: string): string {\n return stamped.slice(0, stamped.indexOf('.'));\n}\n\nfunction translationOf(stamped: string): string {\n return stamped.slice(stamped.indexOf('.') + 1);\n}\n\n// a caller may hand nested groups, and every key here is the dotted one t() reads\nfunction flatCatalogs(catalogs: Catalogs): Catalogs {\n const out: Catalogs = {};\n for (const [locale, catalog] of Object.entries(catalogs)) {\n out[locale] = flatten(catalog as unknown as MessageTree);\n }\n return out;\n}\n\nfunction serializeState(state: State): string | undefined {\n const drafts: Drafts = {};\n for (const locale of Object.keys(state.drafts).sort()) {\n const keys = [...new Set(state.drafts[locale])].sort();\n if (keys.length) drafts[locale] = keys;\n }\n const fingerprints: Fingerprints = {};\n for (const locale of Object.keys(state.fingerprints).sort()) {\n const entries = state.fingerprints[locale] ?? {};\n const keys = Object.keys(entries).sort();\n if (!keys.length) continue;\n fingerprints[locale] = Object.fromEntries(keys.map((key) => [key, entries[key]!]));\n }\n const out: Partial<State> = {};\n if (Object.keys(drafts).length) out.drafts = drafts;\n if (Object.keys(fingerprints).length) out.fingerprints = fingerprints;\n if (!out.drafts && !out.fingerprints) return undefined;\n return JSON.stringify(out, null, 2) + '\\n';\n}\n\n// a corrupt sidecar throws: read as empty, the next save would erase every draft it held\nfunction readJson(path: string): unknown {\n let content: string;\n try {\n content = readFileSync(path, 'utf8');\n } catch {\n return undefined;\n }\n try {\n return JSON.parse(content.charCodeAt(0) === 0xfeff ? content.slice(1) : content) as unknown;\n } catch (error) {\n throw corrupt(path, error);\n }\n}\n\n// deleting it is the one fix that is not safe: every draft it listed would read as reviewed\nfunction corrupt(path: string, cause?: unknown): Error {\n return new Error(\n `[verbaly] ${path} is not valid JSON: restore it from git or fix it (deleting it approves every draft)`,\n { cause },\n );\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction readDrafts(value: unknown): Drafts {\n const out: Drafts = {};\n if (!isObject(value)) return out;\n for (const [locale, keys] of Object.entries(value)) {\n if (Array.isArray(keys)) out[locale] = keys.filter((key): key is string => typeof key === 'string');\n }\n return out;\n}\n\nfunction readFingerprints(value: unknown): Fingerprints {\n const out: Fingerprints = {};\n if (!isObject(value)) return out;\n for (const [locale, entries] of Object.entries(value)) {\n if (!isObject(entries)) continue;\n const kept: Record<string, string> = emptyCatalog();\n for (const [key, stamped] of Object.entries(entries)) {\n if (typeof stamped === 'string' && stamped.includes('.')) kept[key] = stamped;\n }\n out[locale] = kept;\n }\n return out;\n}\n","import { readFileSync } from 'node:fs';\nimport { loadCatalogs, own, writeCatalog, type Catalogs } from './catalog';\nimport { writeDts } from './codegen';\nimport type { ResolvedConfig } from './config';\nimport { extractProject, pruneCatalogs, syncCatalogs, type ReplacedText } from './extract';\nimport { scanFindings, type Finding } from './findings';\nimport type { MessageRegistry } from './registry';\nimport { analyzeFile } from './sfc';\nimport { updateState, type State } from './state';\n\n// The one way the code reaches the catalogs: scan, prune, sync, write, keep the state in step\nexport interface SyncProjectOptions {\n prune?: boolean;\n dryRun?: boolean;\n registry?: MessageRegistry;\n catalogs?: Catalogs;\n confirm?: boolean;\n write?: 'all' | 'changed';\n}\n\nexport interface SyncProjectResult {\n registry: MessageRegistry;\n catalogs: Catalogs;\n added: Record<string, string[]>;\n replaced: ReplacedText[];\n pruned: Record<string, string[]>;\n pruneBlocked: boolean;\n findings: Finding[];\n written: Record<string, string>;\n state?: State;\n stateProblem?: string;\n}\n\n// the one way the code reaches the catalogs: scan, prune, sync, write, keep the state in step\nexport async function syncProject(\n cfg: ResolvedConfig,\n options: SyncProjectOptions = {},\n): Promise<SyncProjectResult> {\n const registry = options.registry ?? (await extractProject(cfg));\n const catalogs = options.catalogs ?? loadCatalogs(cfg);\n if (options.confirm) confirmFromDisk(cfg, catalogs, registry);\n const pruneBlocked = options.prune === true && registry.parseErrors().length > 0;\n const pruned = options.prune ? pruneCatalogs(cfg, catalogs, registry) : {};\n const { added, replaced } = syncCatalogs(cfg, catalogs, registry);\n const result: SyncProjectResult = {\n registry,\n catalogs,\n added,\n replaced,\n pruned,\n pruneBlocked,\n findings: scanFindings(cfg, registry, replaced),\n written: {},\n };\n if (options.dryRun) return result;\n\n const changed = new Set([...Object.keys(added), ...Object.keys(pruned)]);\n if (replaced.length > 0) changed.add(cfg.sourceLocale);\n for (const locale of cfg.locales) {\n if (options.write === 'changed' && !changed.has(locale)) continue;\n result.written[locale] = writeCatalog(cfg, locale, catalogs[locale] ?? {});\n }\n writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});\n try {\n // a pruned key takes its draft along, and an edited source text marks its translations\n result.state = updateState(cfg, catalogs);\n } catch (error) {\n result.stateProblem = (error as Error).message.replace(/^\\[verbaly\\] /, '');\n }\n return result;\n}\n\n// a file can change on disk unseen by a registry built over time: a checkout, another terminal\nfunction confirmFromDisk(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry): void {\n const source = catalogs[cfg.sourceLocale] ?? {};\n const stale = new Set<string>();\n for (const [key, msg] of registry.messages()) {\n if (own(source, key) !== msg.message) stale.add(msg.file);\n }\n for (const file of stale) {\n let code: string;\n try {\n code = readFileSync(file, 'utf8');\n } catch {\n registry.remove(file);\n continue;\n }\n registry.update(file, analyzeFile(code, file));\n }\n}\n","// Intl is the one reader that decides whether a string is a locale tag, so it answers here too\nexport function isLocaleTag(tag: string): boolean {\n try {\n Intl.getCanonicalLocales(tag);\n return true;\n } catch {\n return false;\n }\n}\n\n// pt_BR is how gettext, Java and many backends write pt-BR: the one misspelling with a sure fix\nexport function suggestTag(tag: string): string | undefined {\n const near = tag.replace(/_/g, '-');\n return near !== tag && isLocaleTag(near) ? near : undefined;\n}\n\n// the project's own spelling of a tag written another way: pt_BR and PT-br both mean pt-BR\nexport function projectLocale(tag: string, locales: string[]): string | undefined {\n if (locales.includes(tag)) return tag;\n const plain = (value: string): string => value.replace(/_/g, '-').toLowerCase();\n return locales.find((locale) => plain(locale) === plain(tag));\n}\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { findConfigFile, loadConfigFile } from './config';\nimport { detectHost, installCommand, type Host } from './host';\nimport { isLocaleTag, suggestTag } from './tag';\n\nexport type { Host };\n\nexport interface InitOptions {\n root?: string;\n dir?: string;\n sourceLocale?: string;\n locales?: string[];\n}\n\nexport interface InitResult {\n created: string[];\n skipped: string[];\n host: Host | undefined;\n configFile: string;\n next: string[];\n renamed: { from: string; to: string }[];\n refused: string[];\n}\n\n// a package manager links a bin for a direct dependency only, and ours is usually transitive\nexport function cliReachable(root: string): boolean {\n const bin = join(root, 'node_modules', '.bin');\n return existsSync(join(bin, 'verbaly')) || existsSync(join(bin, 'verbaly.CMD'));\n}\n\nexport const CLI_INSTALL_FIX =\n 'add `@verbaly/compiler` to your dev dependencies, then `npx verbaly` resolves';\n\nfunction configSource(options: InitOptions, typescript: boolean): string {\n const fields = [` sourceLocale: '${options.sourceLocale ?? 'en'}',`];\n if (options.locales?.length) {\n fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(', ')}],`);\n }\n if (options.dir) fields.push(` dir: '${options.dir}',`);\n const body = `export default {\\n${fields.join('\\n')}\\n}`;\n if (typescript) {\n return `import type { VerbalyConfig } from '@verbaly/compiler';\\n\\n${body} satisfies VerbalyConfig;\\n`;\n }\n return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\\n${body};\\n`;\n}\n\nexport async function init(input: InitOptions = {}): Promise<InitResult> {\n const root = input.root ?? process.cwd();\n const created: string[] = [];\n const skipped: string[] = [];\n const renamed: InitResult['renamed'] = [];\n const refused: string[] = [];\n\n // only what was typed is corrected: a locale in a config file is the author's, doctor says so\n const typed = input.locales?.flatMap((locale) => {\n if (isLocaleTag(locale)) return [locale];\n const near = suggestTag(locale);\n if (near) renamed.push({ from: locale, to: near });\n else refused.push(locale);\n return near ? [near] : [];\n });\n // pt_BR,pt-BR is one locale once written right, and the config must not list it twice\n const locales = typed && [...new Set(typed)];\n let sourceLocale = input.sourceLocale;\n if (sourceLocale !== undefined && !isLocaleTag(sourceLocale)) {\n const near = suggestTag(sourceLocale);\n if (!near) {\n throw new Error(\n `[verbaly] \"${sourceLocale}\" is not a locale tag: pass --source with one like en or pt-BR`,\n );\n }\n renamed.push({ from: sourceLocale, to: near });\n sourceLocale = near;\n }\n const options: InitOptions = { ...input, locales, sourceLocale };\n\n const existing = findConfigFile(root);\n const typescript = existsSync(join(root, 'tsconfig.json'));\n const configFile = existing ?? (typescript ? 'verbaly.config.ts' : 'verbaly.config.mjs');\n if (existing) {\n skipped.push(existing);\n } else {\n writeFileSync(join(root, configFile), configSource(options, typescript));\n created.push(configFile);\n }\n\n // a config already answers where the catalogs go: guessing again scaffolds a second set\n const fromFile = existing ? await loadConfigFile(root) : {};\n const scaffold: InitOptions = {\n dir: options.dir ?? fromFile.dir,\n sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,\n locales: options.locales ?? fromFile.locales,\n };\n\n const dir = join(root, scaffold.dir ?? 'locales');\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n for (const locale of new Set([scaffold.sourceLocale ?? 'en', ...(scaffold.locales ?? [])])) {\n const file = join(dir, `${locale}.json`);\n const label = relative(root, file).replaceAll('\\\\', '/');\n if (existsSync(file)) {\n skipped.push(label);\n } else {\n writeFileSync(file, '{}\\n');\n created.push(label);\n }\n }\n\n const host = detectHost(root);\n // the line its README teaches, in the project's own package manager\n const next = host\n ? [installCommand(root, host.install), host.wire]\n : ['run \"verbaly extract\" after writing your first t`…` message'];\n\n return { created, skipped, host: host?.name, configFile, next, renamed, refused };\n}\n","import { relative } from 'node:path';\nimport { flatten, type MessageTree } from 'verbaly';\nimport { catalogPath, type Catalog, type Catalogs } from './catalog';\nimport type { ResolvedConfig } from './config';\nimport { shippedCatalogs } from './extract';\nimport {\n collisionEntries,\n formatFinding,\n siteOf,\n sourcePlace,\n type CollisionEntry,\n type SourceSite,\n} from './findings';\nimport { CLI_INSTALL_FIX } from './init';\nimport type { MessageRegistry } from './registry';\nimport { outdatedTranslations, type Fingerprints, type OutdatedEntry } from './state';\nimport { counted, truncate } from './text';\nimport { validateMessage, validatePair, type IssueSeverity, type StructureIssue } from './validate';\n\nexport interface MissingEntry {\n locale: string;\n key: string;\n source?: string;\n}\n\nexport interface UnknownEntry {\n key: string;\n files: string[];\n}\n\nexport interface BrokenEntry {\n locale: string;\n key: string;\n severity: IssueSeverity;\n issue: string;\n}\n\nexport interface ExtraEntry {\n locale: string;\n key: string;\n files: string[];\n}\n\nexport interface DivergentEntry {\n key: string;\n catalog: string;\n code: SourceSite;\n}\n\nexport type { CollisionEntry, SourceSite } from './findings';\nexport type { OutdatedEntry } from './state';\n\nexport interface CheckResult {\n ok: boolean;\n missing: MissingEntry[];\n unknown: UnknownEntry[];\n broken: BrokenEntry[];\n extra: ExtraEntry[];\n collisions: CollisionEntry[];\n divergent: DivergentEntry[];\n outdated: OutdatedEntry[];\n}\n\nexport function gatePasses(result: Pick<CheckResult, 'missing' | 'unknown' | 'broken'>): boolean {\n return (\n result.missing.length === 0 &&\n result.unknown.length === 0 &&\n !result.broken.some((entry) => entry.severity === 'error')\n );\n}\n\n// every warning list, counted once: the build line and doctor say the same number\nexport function warningCount(result: CheckResult): number {\n return (\n result.broken.filter((entry) => entry.severity === 'warning').length +\n result.extra.length +\n result.collisions.length +\n result.divergent.length +\n result.outdated.length\n );\n}\n\nexport function check(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: MessageRegistry,\n fingerprints: Fingerprints = {},\n): CheckResult {\n const extracted = registry.messages();\n\n // one flat view per locale: the shape t() sees, so nested catalogs compare leaf by leaf\n const flat: Record<string, Catalog> = {};\n for (const locale of cfg.locales) {\n flat[locale] = flatten((catalogs[locale] ?? {}) as MessageTree);\n }\n const source = flat[cfg.sourceLocale] ?? {};\n // the code's text is the one that ships, so every translation is read against it\n const shipped = shippedCatalogs(cfg, flat, registry);\n const sourceText = shipped[cfg.sourceLocale]!;\n\n const used = registry.usedKeys();\n const unknown: UnknownEntry[] = [];\n // strict: a key only spelled in backticks never failed the gate, and it does not start to here\n for (const [key, files] of registry.usedKeys(true)) {\n const known =\n extracted.has(key) || cfg.locales.some((locale) => flat[locale]?.[key] !== undefined);\n if (!known) unknown.push({ key, files });\n }\n\n const needed = new Set<string>([...extracted.keys(), ...Object.keys(source)]);\n\n const missing: MissingEntry[] = [];\n for (const key of extracted.keys()) {\n if (!source[key]) {\n missing.push({ locale: cfg.sourceLocale, key, source: extracted.get(key)?.message });\n }\n }\n for (const locale of cfg.locales) {\n if (locale === cfg.sourceLocale) continue;\n for (const key of needed) {\n if (!flat[locale]?.[key]) {\n missing.push({ locale, key, source: source[key] ?? extracted.get(key)?.message });\n }\n }\n }\n\n // presence is not correctness: a translation can be there and still render wrong\n const broken: BrokenEntry[] = [];\n const add = (locale: string, key: string, issues: StructureIssue[]): void => {\n for (const issue of issues) {\n broken.push({ locale, key, severity: issue.severity, issue: issue.message });\n }\n };\n\n const divergent: DivergentEntry[] = [];\n for (const [key, entry] of extracted) {\n const written = source[key];\n if (written && written !== entry.message) {\n divergent.push({ key, catalog: written, code: siteOf(entry) });\n }\n }\n for (const [key, text] of Object.entries(sourceText)) {\n add(cfg.sourceLocale, key, validateMessage(text, cfg.sourceLocale));\n }\n for (const locale of cfg.locales) {\n if (locale === cfg.sourceLocale) continue;\n for (const [key, translated] of Object.entries(flat[locale] ?? {})) {\n if (!translated) continue; // '' is untranslated, already reported as missing\n add(locale, key, validateMessage(translated, locale));\n const text = sourceText[key];\n if (text) add(locale, key, validatePair(text, translated));\n }\n }\n\n // dead weight in that language's download, or, when the code reads it, the raw key in the source\n const extra: ExtraEntry[] = [];\n for (const locale of cfg.locales) {\n if (locale === cfg.sourceLocale) continue;\n for (const key of Object.keys(flat[locale] ?? {})) {\n if (source[key] !== undefined || extracted.has(key)) continue;\n extra.push({ locale, key, files: used.get(key) ?? [] });\n }\n }\n\n return {\n ok: gatePasses({ missing, unknown, broken }),\n missing,\n unknown,\n broken,\n extra,\n collisions: collisionEntries(registry),\n divergent,\n outdated: outdatedTranslations(cfg, shipped, fingerprints),\n };\n}\n\n// root makes the paths readable: an absolute path is noise in the one message people are stuck on\nexport function formatCheckResult(result: CheckResult, root?: string): string {\n const show = (file: string) => (root ? relative(root, file).replaceAll('\\\\', '/') : file);\n const lines: string[] = [];\n if (result.missing.length > 0) {\n lines.push('missing translations:');\n for (const entry of result.missing) {\n const hint = entry.source ? `: \"${truncate(entry.source, 40)}\"` : '';\n lines.push(` [${entry.locale}] ${entry.key}${hint}`);\n }\n }\n if (result.unknown.length > 0) {\n lines.push('unknown keys (not in any catalog):');\n for (const entry of result.unknown) {\n lines.push(` ${entry.key} (used in ${entry.files.map(show).join(', ')})`);\n }\n }\n const errors = result.broken.filter((entry) => entry.severity === 'error');\n if (errors.length > 0) {\n lines.push('broken translations:');\n for (const entry of errors) lines.push(` [${entry.locale}] ${entry.key}: ${entry.issue}`);\n }\n return lines.join('\\n');\n}\n\n// what to do about each kind of failure: extract only fixes one of the three\nexport function checkNextSteps(result: CheckResult, cliReachable = true): string {\n const steps: string[] = [];\n if (result.missing.length > 0) {\n steps.push(\n 'missing: run `npx verbaly extract` to scaffold the keys, then fill them (or run `npx verbaly translate`)',\n );\n }\n if (result.unknown.length > 0) {\n steps.push(\n 'unknown keys: the key used in the code is in no catalog, fix the key or run `npx verbaly extract`',\n );\n }\n if (result.broken.some((entry) => entry.severity === 'error')) {\n steps.push(\n 'broken: a translation has to keep the params, tags and plural cases of its source message',\n );\n }\n // the gate prints from inside a build, where the command it just named may not exist at all\n if (steps.length > 0 && !cliReachable) {\n steps.push(`the verbaly command is not linked in this project: ${CLI_INSTALL_FIX}`);\n }\n return steps.join('\\n');\n}\n\nexport interface CheckReportOptions {\n // check --outdated fails on them, so they are printed with the failures, not as warnings\n outdatedFails?: boolean;\n}\n\n// warnings never fail the gate, so they print on their own\nexport function formatCheckWarnings(\n result: CheckResult,\n root?: string,\n options: CheckReportOptions = {},\n): string {\n const lines = result.broken\n .filter((entry) => entry.severity === 'warning')\n .map((entry) => ` [${entry.locale}] ${entry.key}: ${entry.issue}`);\n for (const entry of result.extra) {\n lines.push(\n entry.files.length > 0\n ? ` [${entry.locale}] ${entry.key}: only this translation has it, so the source language shows the key itself`\n : ` [${entry.locale}] ${entry.key}: only this translation has it, and no code reads it`,\n );\n }\n for (const entry of result.collisions) {\n lines.push(` ${formatFinding({ kind: 'collision', ...entry }, root)}`);\n }\n for (const { key, catalog, code } of result.divergent) {\n lines.push(\n ` ${key}: the source catalog says \"${truncate(catalog, 40)}\" and the code says ` +\n `\"${truncate(code.message, 40)}\" (${sourcePlace(code, root)}): ` +\n 'the code wins, so edit the text there (extract writes it into the catalog)',\n );\n }\n if (!options.outdatedFails) {\n for (const entry of result.outdated) {\n lines.push(` ${formatFinding({ kind: 'outdated', ...entry }, root)}`);\n }\n }\n return lines.join('\\n');\n}\n\n// GitHub workflow commands: every failure becomes a clickable ::error annotation on the PR\nexport function githubCheckAnnotations(\n result: CheckResult,\n registry: MessageRegistry,\n cfg: ResolvedConfig,\n options: CheckReportOptions = {},\n): string[] {\n const messages = registry.messages();\n const rel = (file: string): string =>\n escapeProperty(relative(cfg.root, file).replaceAll('\\\\', '/'));\n const at = (file: string, line: number | undefined): string =>\n `file=${rel(file)}${line ? `,line=${line}` : ''}`;\n\n const lines: string[] = [];\n\n // one annotation per key, locales grouped: N locales must not bury the PR in N copies\n const byKey = new Map<string, MissingEntry & { locales: string[] }>();\n for (const entry of result.missing) {\n const grouped = byKey.get(entry.key);\n if (grouped) grouped.locales.push(entry.locale);\n else byKey.set(entry.key, { ...entry, locales: [entry.locale] });\n }\n\n for (const entry of byKey.values()) {\n const origin = messages.get(entry.key);\n const hint = entry.source ? `: \"${truncate(entry.source, 60)}\"` : '';\n const text = escapeData(`missing [${entry.locales.join(', ')}] ${entry.key}${hint}`);\n if (origin) {\n lines.push(`::error ${at(origin.file, origin.line)}::${text}`);\n } else {\n lines.push(`::error::${text}`);\n }\n }\n\n for (const entry of result.unknown) {\n const text = escapeData(`unknown key \"${entry.key}\" (not in any catalog)`);\n const file = entry.files[0];\n lines.push(file ? `::error file=${rel(file)}::${text}` : `::error::${text}`);\n }\n\n // a broken translation points at the source line that wrote the message\n for (const entry of result.broken) {\n const origin = messages.get(entry.key);\n const text = escapeData(`[${entry.locale}] ${entry.key}: ${entry.issue}`);\n const command = entry.severity === 'error' ? 'error' : 'warning';\n if (!origin) {\n lines.push(`::${command}::${text}`);\n continue;\n }\n lines.push(`::${command} ${at(origin.file, origin.line)}::${text}`);\n }\n\n for (const entry of result.extra) {\n const text = escapeData(`[${entry.locale}] ${entry.key}: only this translation has it`);\n const file = entry.files[0];\n lines.push(file ? `::warning file=${rel(file)}::${text}` : `::warning::${text}`);\n }\n\n // one per place a colliding text is written, so the PR shows every one of them\n for (const { key, sites } of result.collisions) {\n const texts = new Set(sites.map((place) => place.message)).size;\n const text = escapeData(\n `\"${key}\" has ${counted(texts, 'text')}, and every place shows the first one`,\n );\n for (const place of sites) lines.push(`::warning ${at(place.file, place.line)}::${text}`);\n }\n for (const { key, code } of result.divergent) {\n const text = escapeData(`\"${key}\": the source catalog has another text, the code's one ships`);\n lines.push(`::warning ${at(code.file, code.line)}::${text}`);\n }\n // the translation lives in its catalog, and under --outdated it is what fails the job\n const outdated = options.outdatedFails ? 'error' : 'warning';\n for (const { locale, key } of result.outdated) {\n const text = escapeData(`[${locale}] ${key}: translated from an older source text`);\n lines.push(`::${outdated} file=${rel(catalogPath(cfg, locale))}::${text}`);\n }\n return lines;\n}\n\nfunction escapeData(text: string): string {\n return text.replaceAll('%', '%25').replaceAll('\\r', '%0D').replaceAll('\\n', '%0A');\n}\n\nfunction escapeProperty(text: string): string {\n return escapeData(text).replaceAll(':', '%3A').replaceAll(',', '%2C');\n}\n","import MagicString from 'magic-string';\nimport type { Analysis } from './analyze';\nimport { analyzeFile } from './sfc';\nimport { warnParseError } from './warn';\n\nexport interface TransformResult {\n code: string;\n map: ReturnType<MagicString['generateMap']>;\n}\n\nfunction quote(text: string, single: boolean | undefined): string {\n if (!single) return JSON.stringify(text);\n return `'${text.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n}\n\nexport function transformCode(\n code: string,\n file: string,\n analysis?: Analysis,\n): TransformResult | null {\n const own = analysis ?? analyzeFile(code, file);\n if (!analysis && own.parseError) warnParseError(file, own.parseError);\n const { tagged } = own;\n if (tagged.length === 0) return null;\n\n const s = new MagicString(code);\n for (const msg of tagged) {\n const seen = new Set<string>();\n const entries = msg.params.filter((p) => !seen.has(p.name) && seen.add(p.name));\n const pairs = entries\n .map((p) => `${quote(p.name, msg.singleQuote)}: ${code.slice(p.start, p.end)}`)\n .join(', ');\n\n if (msg.jsx) {\n const values = entries.length ? ` values={{ ${pairs} }}` : '';\n const components = msg.jsx.components.length\n ? ` components={{ ${msg.jsx.components\n .map((c) => `${JSON.stringify(c.name)}: ${c.source}`)\n .join(', ')} }}`\n : '';\n s.overwrite(\n msg.start,\n msg.end,\n `<${msg.jsx.name} id=${JSON.stringify(msg.key)}${values}${components} />`,\n );\n continue;\n }\n\n const tagSource = code.slice(msg.tagStart, msg.tagEnd);\n const args = entries.length ? `, { ${pairs} }` : '';\n s.overwrite(msg.start, msg.end, `${tagSource}(${quote(msg.key, msg.singleQuote)}${args})`);\n }\n return { code: s.toString(), map: s.generateMap({ hires: true }) };\n}\n","import { relative } from 'node:path';\nimport picomatch from 'picomatch';\nimport { auditBundle, clientCatalogs, formatBundleIssue } from './bundle';\nimport {\n emptyCatalog,\n loadCatalogs,\n needsIcu,\n needsRelative,\n type Catalog,\n type Catalogs,\n} from './catalog';\nimport { check, checkNextSteps, formatCheckResult, gatePasses, warningCount } from './check';\nimport { VIRTUAL_ID, generateLocaleModule, generateRuntimeModule } from './codegen';\nimport type { ResolvedConfig, VerbalyConfig } from './config';\nimport { cliReachable } from './init';\nimport type { MessageRegistry } from './registry';\nimport { analyzeFile } from './sfc';\nimport { readState, type Fingerprints } from './state';\nimport { counted } from './text';\nimport { transformCode, type TransformResult } from './transform';\nimport { warnOnce, warnParseError } from './warn';\n\nexport interface PluginOptions extends VerbalyConfig {\n failOnMissing?: boolean;\n}\n\nexport const RESOLVED_VIRTUAL_ID = '\\0' + VIRTUAL_ID;\nexport const LOCALE_MODULE_PREFIX = `${RESOLVED_VIRTUAL_ID}/locale/`;\nexport const SOURCE_FILE_RE = /\\.(?:[cm]?[jt]sx?|svelte|vue|astro)$/;\n\nexport function resolveVirtualId(id: string): string | undefined {\n if (id === VIRTUAL_ID || id.startsWith(`${VIRTUAL_ID}/`)) return '\\0' + id;\n return undefined;\n}\n\nexport function loadVirtualModule(\n id: string,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n): string | undefined {\n // filtered before the detectors run: a group that leaves the bundle takes its parsers with it\n const client = clientCatalogs(cfg, catalogs);\n if (id === RESOLVED_VIRTUAL_ID) {\n return generateRuntimeModule(cfg, {\n icu: cfg.icu ?? needsIcu(client),\n relative: cfg.relative ?? needsRelative(client),\n inlineCatalog: cfg.render.inlineCatalog === true,\n });\n }\n if (id.startsWith(LOCALE_MODULE_PREFIX)) {\n return generateLocaleModule(client[id.slice(LOCALE_MODULE_PREFIX.length)] ?? {});\n }\n return undefined;\n}\n\nexport function isTransformTarget(id: string): boolean {\n return SOURCE_FILE_RE.test(id) && !id.includes('node_modules') && !id.startsWith('\\0');\n}\n\nexport function createSourceFilter(cfg: ResolvedConfig): (id: string) => boolean {\n if (cfg.include.length === 0) return () => false;\n const matches = picomatch(cfg.include, { ignore: cfg.exclude });\n return (id) => {\n const rel = relative(cfg.root, id).replaceAll('\\\\', '/');\n return !rel.startsWith('..') && matches(rel);\n };\n}\n\n// analyze + register + rewrite: the per-file transform every bundler plugin runs\nexport function transformSource(\n code: string,\n id: string,\n registry: MessageRegistry,\n): { messages: Catalog; result: TransformResult | null } {\n const analysis = analyzeFile(code, id);\n registry.update(id, analysis);\n if (analysis.parseError) warnParseError(id, analysis.parseError);\n // key → text for live extraction; first wins, mirroring the registry's collision rule\n const messages = emptyCatalog();\n for (const msg of analysis.tagged) messages[msg.key] ??= msg.message;\n return { messages, result: transformCode(code, id, analysis) ?? null };\n}\n\n// the one build-blocking error message, kept in one place (undefined = gate on)\nexport function runBuildGate(\n cfg: ResolvedConfig,\n registry: MessageRegistry,\n failOnMissing?: boolean,\n): void {\n const catalogs = loadCatalogs(cfg);\n // warns, never blocks: an excluded group that a page needs is a mistake the build cannot prove\n for (const issue of auditBundle(cfg, catalogs, registry)) {\n warnOnce(`${formatBundleIssue(issue)}\\n fix: ${issue.fix}`, `bundle:${issue.prefix}`);\n }\n const found = check(cfg, catalogs, registry, buildFingerprints(cfg));\n // a warning never stops a build, so the build says they exist in one line and check reads them\n const warnings = warningCount(found);\n if (warnings > 0) {\n warnOnce(\n `check has ${counted(warnings, 'warning')}, and the build still passes: run \\`npx verbaly check\\` to read them`,\n 'gate:warnings',\n );\n }\n // false = build with untranslated strings, never with broken ones: those render wrong\n const result = failOnMissing === false ? { ...found, missing: [] } : found;\n if (gatePasses(result)) return;\n throw new Error(\n `[verbaly] build blocked\\n${formatCheckResult(result, cfg.root)}\\n${checkNextSteps(result, cliReachable(cfg.root))}`,\n );\n}\n\n// the state only feeds a warning, so a sidecar nobody can parse must not be what stops a build\nfunction buildFingerprints(cfg: ResolvedConfig): Fingerprints {\n const { state, problem } = readState(cfg);\n if (problem) warnOnce(`${problem}, so outdated translations are not reported`, 'gate:state');\n return state.fingerprints;\n}\n","import { readFileSync } from 'node:fs';\nimport { relative } from 'node:path';\nimport picomatch from 'picomatch';\nimport { glob } from 'tinyglobby';\nimport { SOURCE_EXTENSIONS, type ResolvedConfig } from './config';\nimport { analyzeFile } from './sfc';\nimport { warnOnce } from './warn';\n\n// a hint before Babel is asked: t`, t.id('…')` or a Svelte $t`\nconst TAGGED_HINT = /(?<![\\w$.])\\$?t(?:\\.id\\s*\\([^)]*\\))?\\s*`/;\n\n// folders that hold builds or vendored code, never the app's own source\nconst NOT_SOURCE = [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/out/**',\n '**/coverage/**',\n];\n\nfunction relativeId(cfg: ResolvedConfig, id: string): string {\n return relative(cfg.root, id).replaceAll('\\\\', '/');\n}\n\n// the include pattern that would cover a file: its top folder with the extensions extract reads\nfunction suggestedPattern(rel: string): string {\n const slash = rel.indexOf('/');\n return slash < 0 ? rel : `${rel.slice(0, slash)}/**/*.${SOURCE_EXTENSIONS}`;\n}\n\nexport interface OutsideFile {\n file: string;\n pattern: string;\n}\n\n// a file the build reads and extract never will: its t`…` shows the source text in every language\nexport function createOutsideCheck(\n cfg: ResolvedConfig,\n): (code: string, id: string) => OutsideFile | undefined {\n // include: [] turns scanning off on purpose, so nothing is outside of it\n if (cfg.include.length === 0) return () => undefined;\n const included = picomatch(cfg.include);\n const excluded = picomatch(cfg.exclude);\n return (code, id) => {\n const rel = relativeId(cfg, id);\n if (rel.startsWith('..') || included(rel) || excluded(rel)) return undefined;\n if (!TAGGED_HINT.test(code)) return undefined;\n // the hint matches prose too: only a real tagged template on t counts\n if (analyzeFile(code, id).tagged.length === 0) return undefined;\n return { file: id, pattern: suggestedPattern(rel) };\n };\n}\n\n// one wording for the loader, both plugins and doctor\nexport function formatOutside(cfg: ResolvedConfig, found: OutsideFile): string {\n return (\n `${relativeId(cfg, found.file)} uses t\\`…\\` outside the include of your verbaly config, so its ` +\n `texts are never extracted and show in ${cfg.sourceLocale} in every language: add ` +\n `\"${found.pattern}\" to include (or the file to exclude, if it is not app code)`\n );\n}\n\n// once when a build or a dev server starts: a loader result can come from a cache, a scan cannot\nexport async function reportOutsideInclude(cfg: ResolvedConfig): Promise<void> {\n for (const found of await filesOutsideInclude(cfg)) {\n warnOnce(formatOutside(cfg, found), `outside:${found.file}`);\n }\n}\n\n// the whole project, for doctor: every source file outside include that writes a t`…`\nexport async function filesOutsideInclude(cfg: ResolvedConfig): Promise<OutsideFile[]> {\n if (cfg.include.length === 0) return [];\n const check = createOutsideCheck(cfg);\n const files = await glob([`**/*.${SOURCE_EXTENSIONS}`], {\n cwd: cfg.root,\n ignore: [...NOT_SOURCE, ...cfg.exclude],\n absolute: true,\n });\n const found: OutsideFile[] = [];\n for (const file of files.sort()) {\n let code: string;\n try {\n code = readFileSync(file, 'utf8');\n } catch {\n continue;\n }\n const outside = check(code, file);\n if (outside) found.push(outside);\n }\n return found;\n}\n","import type { ResolvedConfig } from './config';\nimport { loadState, saveState, type Drafts } from './state';\n\nexport { clearDrafts, effectiveDrafts, markDrafts, STATE_FILE } from './state';\nexport type { Drafts } from './state';\n\nexport function loadDrafts(cfg: ResolvedConfig): Drafts {\n return loadState(cfg).drafts;\n}\n\n// the drafts share their file with the fingerprints, so a save keeps whatever else it holds\nexport function saveDrafts(cfg: ResolvedConfig, drafts: Drafts): void {\n const state = loadState(cfg);\n saveState(cfg, { ...state, drafts });\n}\n","import type { Catalog, Catalogs } from './catalog';\nimport type { ResolvedConfig } from './config';\nimport { effectiveDrafts, type Drafts } from './drafts';\nimport { shippedCatalogs } from './extract';\nimport { outdatedTranslations, type Fingerprints } from './state';\nimport { flatten, type MessageTree } from 'verbaly';\nimport type { MessageRegistry } from './registry';\nimport { counted } from './text';\nimport { validateMessage, validatePair } from './validate';\n\nexport interface LocaleStatus {\n locale: string;\n translated: number;\n total: number;\n drafts: number;\n broken: number;\n outdated: number;\n}\n\nexport interface StatusResult {\n messages: number;\n source: string;\n locales: LocaleStatus[];\n}\n\n// coverage overview for humans; check stays the CI gate\nexport function status(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: MessageRegistry,\n drafts: Drafts = {},\n fingerprints: Fingerprints = {},\n): StatusResult {\n const extracted = registry.messages();\n\n // one flat view per locale, like check: the shape t() sees, counted leaf by leaf\n const flat: Record<string, Catalog> = {};\n for (const locale of cfg.locales) {\n flat[locale] = flatten((catalogs[locale] ?? {}) as MessageTree);\n }\n const source = flat[cfg.sourceLocale] ?? {};\n const needed = new Set<string>([...extracted.keys(), ...Object.keys(source)]);\n const live = effectiveDrafts(drafts, flat);\n // the text that ships, as check reads it, so status and check never disagree\n const shipped = shippedCatalogs(cfg, flat, registry);\n const sourceText = shipped[cfg.sourceLocale]!;\n const outdated = outdatedTranslations(cfg, shipped, fingerprints);\n\n const locales: LocaleStatus[] = [];\n for (const locale of cfg.locales) {\n if (locale === cfg.sourceLocale) continue;\n const catalog = flat[locale] ?? {};\n let translated = 0;\n for (const key of needed) {\n if (catalog[key]) translated += 1;\n }\n let broken = 0;\n for (const [key, text] of Object.entries(catalog)) {\n if (!text) continue;\n const from = sourceText[key];\n const issues = [...validateMessage(text, locale), ...(from ? validatePair(from, text) : [])];\n if (issues.some((issue) => issue.severity === 'error')) broken += 1;\n }\n locales.push({\n locale,\n translated,\n total: needed.size,\n drafts: live[locale]?.length ?? 0,\n broken,\n outdated: outdated.filter((entry) => entry.locale === locale).length,\n });\n }\n return { messages: needed.size, source: cfg.sourceLocale, locales };\n}\n\nexport function formatStatusResult(result: StatusResult): string {\n const lines = [`[verbaly] ${counted(result.messages, 'message')} · source: ${result.source}`];\n if (result.locales.length === 0) {\n lines.push(' no target locales (add locales to your config)');\n return lines.join('\\n');\n }\n for (const { locale, translated, total, drafts, broken, outdated } of result.locales) {\n const pct = total === 0 ? 100 : Math.floor((translated / total) * 100);\n const mark = translated === total && broken === 0 && outdated === 0 ? ' ✓' : '';\n const notes = [\n drafts > 0 ? `${drafts} unreviewed` : '',\n broken > 0 ? `${broken} broken` : '',\n outdated > 0 ? `${outdated} outdated` : '',\n ].filter(Boolean);\n const note = notes.length > 0 ? `, ${notes.join(', ')}` : '';\n lines.push(` ${locale}: ${translated}/${total} translated (${pct}%${note})${mark}`);\n }\n return lines.join('\\n');\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { flatten } from 'verbaly';\nimport { auditBundle, formatBundleIssue } from './bundle';\nimport { badLeaf, isTree, parseTree, type Catalogs } from './catalog';\nimport { check } from './check';\nimport { DTS_HEADER, generateDts, projectDtsOptions } from './codegen';\nimport { findConfigFile, type ResolvedConfig } from './config';\nimport { extractProject } from './extract';\nimport { sourcePlace } from './findings';\nimport { detectHost, installCommand, readDependencies, WIRING_PACKAGES } from './host';\nimport { CLI_INSTALL_FIX, cliReachable } from './init';\nimport { filesOutsideInclude } from './scope';\nimport { typesIncluded } from './tsconfig';\nimport { counted } from './text';\nimport { isLocaleTag, suggestTag } from './tag';\nimport { effectiveDrafts, readState, STATE_FILE } from './state';\nimport { escapedSyntax } from './validate';\n\nexport interface DoctorEntry {\n level: 'ok' | 'warn' | 'error';\n check: string;\n message: string;\n fix?: string;\n}\n\nexport interface DoctorResult {\n ok: boolean; // no error-level entries (warns allowed)\n entries: DoctorEntry[];\n}\n\nconst PREVIEW = 5; // keys shown before \"…\"\n\n// a mode nobody wrote down was inferred, and doctor says which of the two it is reading\nfunction readRoutingChoice(root: string, configFile: string): boolean {\n try {\n return /\\brouting[\"']?\\s*[:=]/.test(readFileSync(join(root, configFile), 'utf8'));\n } catch {\n return false;\n }\n}\n\nconst ROUTING_SAYS: Record<ResolvedConfig['routing'], string> = {\n 'prefix-except-source': 'the source locale has no prefix, every other locale does',\n 'prefix-all': 'every locale has a prefix, the source included',\n 'no-prefix': 'the language is not in the url, one address serves every locale',\n};\n\nconst ICON = { ok: '✓', warn: '⚠', error: '✗' } as const;\n\n// one definition of a doctor line: the cli routes it by level, the mcp tool joins the block\nexport function formatDoctorEntry(entry: DoctorEntry): string {\n const head = ` ${ICON[entry.level]} ${entry.check}: ${entry.message}`;\n return entry.fix\n ? `${head}\n fix: ${entry.fix}`\n : head;\n}\n\nexport async function doctor(cfg: ResolvedConfig): Promise<DoctorResult> {\n const entries: DoctorEntry[] = [];\n const ok = (name: string, message: string) => entries.push({ level: 'ok', check: name, message });\n const warn = (name: string, message: string, fix: string) =>\n entries.push({ level: 'warn', check: name, message, fix });\n const error = (name: string, message: string, fix: string) =>\n entries.push({ level: 'error', check: name, message, fix });\n const rel = (path: string) => relative(cfg.root, path).replaceAll('\\\\', '/');\n\n const configFile = findConfigFile(cfg.root);\n if (configFile) ok('config', `${configFile} found`);\n else warn('config', 'no config file, running on defaults', 'run `npx verbaly init`');\n\n // the build works without it: what breaks is every command we tell people to run\n if (cliReachable(cfg.root)) ok('cli', 'the verbaly command is available in this project');\n else warn('cli', 'the verbaly command is not linked in node_modules/.bin', CLI_INSTALL_FIX);\n\n const catalogs: Catalogs = {};\n let catalogsHealthy = true;\n if (!existsSync(cfg.dir)) {\n catalogsHealthy = false;\n error(\n 'catalogs',\n `catalogs directory ${rel(cfg.dir)}/ does not exist`,\n 'run `npx verbaly init` to scaffold it',\n );\n } else {\n for (const locale of cfg.locales) {\n const file = join(cfg.dir, `${locale}.json`);\n if (!existsSync(file)) {\n catalogsHealthy = false;\n error(\n `locale ${locale}`,\n `${rel(file)} is missing`,\n 'run `npx verbaly extract` to create it',\n );\n continue;\n }\n // the same reader the gate uses, so a BOM the build accepts is never an error here\n const parsed = parseTree(readFileSync(file, 'utf8'));\n if (parsed === undefined) {\n catalogsHealthy = false;\n error(\n `locale ${locale}`,\n `${rel(file)} is not valid JSON`,\n 'repair the file (or delete it and run `npx verbaly extract`)',\n );\n continue;\n }\n if (!isTree(parsed)) {\n catalogsHealthy = false;\n error(\n `locale ${locale}`,\n `${rel(file)} is not a JSON object of messages`,\n 'a catalog is an object of texts (groups of text are fine): fix the file',\n );\n continue;\n }\n // nested groups are a real shape: only a leaf that is not text is broken\n const bad = badLeaf(parsed);\n if (bad) {\n catalogsHealthy = false;\n error(\n `locale ${locale}`,\n `${rel(file)} has a non-string value at \"${bad}\"`,\n 'catalog values are text (groups of text are fine); fix the value',\n );\n } else {\n catalogs[locale] = flatten(parsed);\n }\n }\n if (catalogsHealthy) {\n const how = cfg.localesDeclared ? '' : ', no locales set, so the catalog files decide';\n ok(\n 'catalogs',\n `${counted(cfg.locales.length, 'locale')} (${cfg.locales.join(', ')}) in ${rel(cfg.dir)}/${how}`,\n );\n }\n }\n\n // it builds and the runtime falls back with a warn, so this is a warn too, rename in hand\n for (const locale of cfg.locales) {\n if (isLocaleTag(locale)) continue;\n const near = suggestTag(locale);\n const file = rel(join(cfg.dir, `${locale}.json`));\n warn(\n 'locales',\n `\"${locale}\" is not a locale tag, so numbers, dates and plurals in it format in a fallback`,\n near\n ? `rename it to ${near}: the file ${file} and your config`\n : `name it with a language tag like es or pt-BR, in ${file} and in your config`,\n );\n }\n\n const source = catalogs[cfg.sourceLocale];\n if (source && Object.keys(source).length === 0) {\n warn(\n 'source',\n `source catalog ${cfg.sourceLocale}.json is empty`,\n 'write your first t`…` message and run `npx verbaly extract`',\n );\n }\n\n const mirrors = cfg.render.site !== undefined || Object.keys(cfg.render).length > 0;\n if (cfg.routing === 'no-prefix' && mirrors) {\n warn(\n 'routing',\n 'routing is \"no-prefix\" but a render section is configured, and render writes one url tree per locale',\n 'drop the render section, or set routing to \"prefix-except-source\" so the helpers agree with the urls',\n );\n } else if (cfg.routing === 'prefix-all' && mirrors) {\n // render leaves the source tree at the root, so a helper that prefixes it points at no page\n warn(\n 'routing',\n `routing is \"prefix-all\" but render keeps ${cfg.sourceLocale} at the root, so its links point at a /${cfg.sourceLocale}/ tree nobody wrote`,\n 'set routing to \"prefix-except-source\", the url tree render writes',\n );\n } else {\n const named = configFile ? readRoutingChoice(cfg.root, configFile) : false;\n const how = named ? '' : ' (from your setup, no routing set)';\n ok('routing', `${cfg.routing}${how}: ${ROUTING_SAYS[cfg.routing]}`);\n }\n\n const deps = readDependencies(cfg.root);\n const host = detectHost(cfg.root);\n const installed = WIRING_PACKAGES.find((pkg) => deps[pkg]);\n if (!host) {\n ok('plugin', 'no framework or bundler detected, the CLI flow (extract/check) applies');\n } else if (installed) {\n ok('plugin', `${installed} installed for ${host.name}`);\n } else {\n warn(\n 'plugin',\n `${host.name} detected but ${host.pkg} is not installed`,\n `${installCommand(cfg.root, host.install)}, then ${host.wire}`,\n );\n }\n\n // with include: [] no code is read, so orphans and types cannot be claimed here\n const scanning = cfg.include.length > 0;\n if (!scanning) {\n ok('sources', 'source scanning is off (include: []), the catalogs are the source of truth');\n }\n\n if (source && scanning && cfg.dts !== false) {\n const dtsPath = cfg.dts;\n const shown = rel(dtsPath);\n // a framework slot is linked from the framework's own types, which only its command writes\n const regenerate =\n host?.name === 'astro'\n ? 'run `npx astro sync`, which writes the types and links them'\n : host?.name === 'nuxt'\n ? 'run `npx nuxi prepare`, which writes the types and links them'\n : 'run `npx verbaly typegen`';\n const expected = generateDts(source, projectDtsOptions(cfg));\n if (!existsSync(dtsPath)) {\n warn('types', `${shown} has not been generated`, regenerate);\n } else if (readFileSync(dtsPath, 'utf8').replace(/\\r\\n/g, '\\n') !== expected) {\n warn('types', `${shown} is stale`, 'run `npx verbaly typegen`');\n } else {\n ok('types', `${shown} is up to date`);\n }\n // .verbaly/ is a dot folder: TypeScript reads it only if tsconfig names the file\n if (dtsPath.startsWith(join(cfg.root, '.verbaly'))) {\n const state = typesIncluded(cfg.root, dtsPath);\n if (state === 'missing' || state === 'unreadable') {\n warn(\n 'types',\n state === 'missing'\n ? `tsconfig.json does not include ${shown}, so TypeScript never reads the types`\n : `tsconfig.json could not be read, so it may not include ${shown}`,\n `run \\`npx verbaly typegen\\`, which adds the line, or add \"${shown}\" to include`,\n );\n }\n }\n // the root file and the one in its new place declare the same module twice\n const old = join(cfg.root, 'verbaly.d.ts');\n if (dtsPath !== old && existsSync(old) && readFileSync(old, 'utf8').startsWith(DTS_HEADER)) {\n warn(\n 'types',\n `the verbaly.d.ts Verbaly wrote at the root is still there next to ${shown}, and they declare the same module twice`,\n 'run `npx verbaly typegen`, which removes it',\n );\n }\n }\n\n const registry = await extractProject(cfg);\n if (scanning) {\n // a warn, not an error: decorators or a dialect babel does not read still build in the project\n const unreadable = registry.parseErrors();\n if (unreadable.length > 0) {\n const first = unreadable[0]!;\n warn(\n 'sources',\n `could not parse ${counted(unreadable.length, 'file')}, so the messages inside are not extracted (${rel(first.file)}: ${first.message})`,\n 'fix the syntax error, or exclude the file in your config if it is not source',\n );\n }\n // a file the build reads and extract never will: its texts show the source language everywhere\n const outside = await filesOutsideInclude(cfg);\n if (outside.length > 0) {\n const files = outside.map((entry) => rel(entry.file));\n const patterns = [...new Set(outside.map((entry) => `\"${entry.pattern}\"`))];\n warn(\n 'sources',\n `t\\`…\\` is written in ${counted(outside.length, 'file')} outside include, and those texts are never extracted or translated (${preview(files)})`,\n `add ${patterns.join(' and ')} to include in your verbaly config, or the files to exclude if they are not app code`,\n );\n }\n const stray = registry.strayImports();\n if (stray.length > 0) {\n const files = [...new Set(stray.map((entry) => rel(entry.file)))];\n error(\n 'imports',\n `t is imported from a verbaly package, which never exports it, in ${counted(files.length, 'file')} (${preview(files)})`,\n 't comes from your instance (React: const t = useT()) or from virtual:verbaly',\n );\n }\n // a t under another name reads fine at runtime, and its texts stay in the source language\n const missed = registry.missed();\n if (missed.length > 0) {\n const first = missed[0]!;\n warn(\n 'sources',\n `a t under another name keeps ${counted(missed.length, 'text')} out of extraction (${sourcePlace(first, cfg.root)}: ${first.name}\\`…\\`)`,\n 'name it t (const t = useT()), the only name verbaly reads, or use t(key) with the key in the catalog',\n );\n }\n // a translator who sees {_0} cannot know what goes there\n const positional = [...registry.messages().values()].filter((msg) =>\n msg.params.some((param) => /^_\\d+$/.test(param.name)),\n );\n if (positional.length > 0) {\n const first = positional[0]!;\n warn(\n 'messages',\n `a translator gets a nameless value like {_0} in ${counted(positional.length, 'message')} (${sourcePlace(first, cfg.root)}: \"${first.message}\")`,\n 'put the value in a named variable first (const date = formatDate(d)), so the message says {date}',\n );\n }\n const escaped = [...registry.messages().values()]\n .map((msg) => ({ file: rel(msg.file), slice: escapedSyntax(msg.message) }))\n .filter((entry) => entry.slice !== undefined);\n if (escaped.length > 0) {\n warn(\n 'messages',\n `a block ships as literal text in ${counted(escaped.length, 'extracted message')} (${escaped[0]!.file}: ${escaped[0]!.slice})`,\n 'a tagged template takes its values from ${…}: use t(key, params) for a plural or format block',\n );\n }\n }\n if (source && scanning) {\n const extracted = registry.messages();\n const used = registry.usedKeys();\n const orphans = Object.keys(source).filter((key) => !extracted.has(key) && !used.has(key));\n // a file that did not parse may be the one reading them, and prune waits until it does\n const unread = registry.parseErrors().length > 0;\n if (orphans.length > 0) {\n warn(\n 'orphans',\n `${counted(orphans.length, 'catalog key')} no longer referenced in code (${preview(orphans)})`,\n unread\n ? 'fix the files that do not parse first, they may use these, and `npx verbaly extract --prune` leaves every key alone until then'\n : 'run `npx verbaly extract --prune` to drop them',\n );\n } else {\n ok('orphans', 'no orphan keys');\n }\n }\n\n const excluded = cfg.bundle.exclude ?? [];\n if (excluded.length > 0 && catalogsHealthy) {\n const issues = auditBundle(cfg, catalogs, registry);\n for (const issue of issues) warn('bundle', formatBundleIssue(issue), issue.fix);\n if (issues.length === 0) {\n ok(\n 'bundle',\n `${counted(excluded.length, 'group')} kept out of the client (${preview(excluded)})`,\n );\n }\n }\n\n // the sidecar only feeds warnings, so a broken one is reported here and never stops a build\n const { state, problem } = readState(cfg);\n if (problem) {\n warn(\n 'state',\n problem,\n `restore ${STATE_FILE} from git: deleting it would mark every machine draft as reviewed`,\n );\n }\n if (catalogsHealthy) {\n const stale = Object.entries(state.drafts).flatMap(([locale, keys]) => {\n const live = new Set(effectiveDrafts({ [locale]: keys }, catalogs)[locale] ?? []);\n return keys.filter((key) => !live.has(key)).map((key) => `${locale}: ${key}`);\n });\n if (stale.length > 0) {\n warn(\n 'drafts',\n `${STATE_FILE} lists ${counted(stale.length, 'draft')} whose translation is gone (${preview(stale)})`,\n 'run `npx verbaly extract`, which drops them',\n );\n }\n }\n\n if (catalogsHealthy) {\n const result = check(cfg, catalogs, registry, state.fingerprints);\n if (result.unknown.length > 0) {\n error(\n 'keys',\n `${counted(result.unknown.length, 'unknown key')} used in code (${preview(result.unknown.map((u) => u.key))})`,\n 'fix the key or add it to the catalogs (`npx verbaly check` for details)',\n );\n }\n if (result.missing.length > 0) {\n const locales = [...new Set(result.missing.map((m) => m.locale))];\n warn(\n 'translations',\n `${counted(result.missing.length, 'missing translation')} (${locales.join(', ')})`,\n 'run `npx verbaly translate` or fill the catalogs (`npx verbaly check` for details)',\n );\n }\n // the gate fails on these, so doctor cannot keep calling the setup healthy\n const broken = result.broken.filter((entry) => entry.severity === 'error');\n if (broken.length > 0) {\n const locales = [...new Set(broken.map((b) => b.locale))];\n error(\n 'translations',\n `${counted(broken.length, 'broken translation')} (${locales.join(', ')}): present but not rendering what the source renders`,\n 'run `npx verbaly check` to read what each one lost',\n );\n }\n if (result.extra.length > 0) {\n const shown = result.extra.map((entry) => `${entry.locale}: ${entry.key}`);\n warn(\n 'extras',\n `a translation has ${counted(result.extra.length, 'key')} the source catalog does not (${preview(shown)})`,\n scanning\n ? 'add them to the source catalog if your code uses them, or run `npx verbaly extract --prune` to drop the rest'\n : 'add them to the source catalog if your code uses them, or delete them from the translations',\n );\n }\n const warnings = result.broken.filter((entry) => entry.severity === 'warning');\n if (warnings.length > 0) {\n warn(\n 'translations',\n `${counted(warnings.length, 'structural warning')} (plural forms a language asks for)`,\n 'run `npx verbaly check` to read them, they never fail the build',\n );\n }\n if (result.collisions.length > 0) {\n const first = result.collisions[0]!;\n warn(\n 'keys',\n `${counted(result.collisions.length, 'key')} written with more than one text, and every place shows the first (${first.key}: ${first.sites.map((at) => sourcePlace(at, cfg.root)).join(', ')})`,\n 'give each text its own key (`npx verbaly check` lists every place)',\n );\n }\n if (result.divergent.length > 0) {\n const first = result.divergent[0]!;\n warn(\n 'source texts',\n `the code and ${cfg.sourceLocale}.json disagree on ${counted(result.divergent.length, 'text')}, and the code's text ships (${first.key}, ${sourcePlace(first.code, cfg.root)})`,\n 'edit those texts in the code; `npx verbaly extract` writes them into the catalog',\n );\n }\n if (result.outdated.length > 0) {\n const shown = result.outdated.map((entry) => `${entry.locale}: ${entry.key}`);\n warn(\n 'outdated',\n `${counted(result.outdated.length, 'translation')} written for an older source text (${preview(shown)})`,\n 'update them, or keep them with `npx verbaly review --approve`',\n );\n }\n if (result.ok) ok('translations', 'all translations complete');\n }\n\n return { ok: entries.every((entry) => entry.level !== 'error'), entries };\n}\n\nfunction preview(keys: string[]): string {\n const head = keys.slice(0, PREVIEW).join(', ');\n return keys.length > PREVIEW ? `${head}, …` : head;\n}\n","import {\n emptyCatalog,\n own,\n readCatalog,\n writeCatalog,\n type Catalog,\n type Catalogs,\n} from './catalog';\nimport { targetLocales, type ResolvedConfig } from './config';\nimport { shippedCatalogs } from './extract';\nimport type { MessageRegistry } from './registry';\nimport { loadState, recordTranslations } from './state';\nimport { byCodeUnit, counted } from './text';\nimport { validateMessage, validatePair } from './validate';\n\nexport interface TranslateRequest {\n sourceLocale: string;\n targetLocale: string;\n messages: Record<string, string>;\n origins?: Record<string, string[]>;\n instructions?: string;\n glossary?: Record<string, string>;\n}\n\nexport type TranslateProvider = (request: TranslateRequest) => Promise<Record<string, string>>;\n\nexport interface TranslateProgress {\n locale: string;\n batch: number;\n batches: number;\n keys: number;\n error?: string;\n}\n\nexport interface TranslateOptions {\n locales?: string[];\n batchSize?: number;\n concurrency?: number;\n retries?: number;\n retryDelay?: number;\n dryRun?: boolean;\n origins?: Record<string, string[]>;\n onProgress?: (progress: TranslateProgress) => void;\n}\n\n// carries its reason, which the per-locale records cannot: a batch fails as a batch\nexport interface TranslateFailure {\n locale: string;\n keys: string[];\n error: string;\n}\n\nexport interface TranslateResult {\n translated: Record<string, string[]>;\n invalid: Record<string, string[]>;\n pending: Record<string, string[]>;\n failed: TranslateFailure[];\n}\n\ninterface Batch {\n locale: string;\n index: number;\n batches: number;\n keys: string[];\n}\n\nconst RETRY_STATUS = new Set([408, 409, 425, 429, 500, 502, 503, 504, 529]);\n\n// a provider is an extension point: retry what looks transient, never a request the api refused\nfunction retryable(error: unknown): boolean {\n const status = (error as { status?: number; statusCode?: number } | null)?.status;\n const code = (error as { statusCode?: number } | null)?.statusCode;\n const value = typeof status === 'number' ? status : code;\n return typeof value === 'number' ? RETRY_STATUS.has(value) : true;\n}\n\nfunction reason(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nconst wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n// a batch that never gets an answer is a failed batch, never a thrown run: everything else lands\nasync function attempt(\n run: () => Promise<Record<string, string>>,\n retries: number,\n delay: number,\n): Promise<Record<string, string>> {\n for (let round = 0; ; round++) {\n try {\n return await run();\n } catch (error) {\n if (round >= retries || !retryable(error)) throw error;\n await wait(delay * 2 ** round);\n }\n }\n}\n\n// bounded pool: independent batches, so the only reason to serialize them is the provider's limit\nasync function pooled<T>(jobs: T[], limit: number, run: (job: T) => Promise<void>): Promise<void> {\n let next = 0;\n const workers = Array.from({ length: Math.min(limit, jobs.length) }, async () => {\n while (next < jobs.length) {\n await run(jobs[next++]!);\n }\n });\n await Promise.all(workers);\n}\n\n// fills '' entries via the provider; invalid translations stay '' (check keeps failing)\nexport async function translateCatalogs(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n provider: TranslateProvider,\n options: TranslateOptions = {},\n): Promise<TranslateResult> {\n const batchSize = options.batchSize ?? 20;\n const concurrency = Math.max(1, options.concurrency ?? 4);\n const retries = Math.max(0, options.retries ?? 2);\n const retryDelay = options.retryDelay ?? 500;\n const targets = targetLocales(cfg, options.locales);\n const source = catalogs[cfg.sourceLocale] ?? {};\n const result: TranslateResult = { translated: {}, invalid: {}, pending: {}, failed: [] };\n\n const jobs: Batch[] = [];\n for (const locale of targets) {\n const catalog = (catalogs[locale] ??= emptyCatalog());\n const missing = Object.keys(source).filter((key) => source[key] && !own(catalog, key));\n if (missing.length === 0) continue;\n\n if (options.dryRun) {\n result.pending[locale] = missing;\n continue;\n }\n\n const batches = Math.ceil(missing.length / batchSize);\n for (let i = 0; i < missing.length; i += batchSize) {\n const index = Math.floor(i / batchSize) + 1;\n jobs.push({ locale, index, batches, keys: missing.slice(i, i + batchSize) });\n }\n }\n\n await pooled(jobs, concurrency, async (job) => {\n const { locale, keys } = job;\n const catalog = catalogs[locale]!;\n const messages = Object.fromEntries(keys.map((key) => [key, source[key]!]));\n const origins = options.origins\n ? Object.fromEntries(\n keys\n .filter((key) => Object.hasOwn(options.origins!, key))\n .map((key) => [key, options.origins![key]!]),\n )\n : undefined;\n\n let out: Record<string, string>;\n try {\n out = await attempt(\n () =>\n provider({\n sourceLocale: cfg.sourceLocale,\n targetLocale: locale,\n messages,\n origins,\n instructions: cfg.translate.instructions,\n glossary: glossaryFor(cfg, locale, messages),\n }),\n retries,\n retryDelay,\n );\n } catch (error) {\n const message = reason(error);\n result.failed.push({ locale, keys, error: message });\n options.onProgress?.({ ...progressOf(job), error: message });\n return;\n }\n\n for (const key of keys) {\n const text = out[key];\n if (typeof text === 'string' && text.trim() && structureMatches(source[key]!, text)) {\n catalog[key] = text;\n (result.translated[locale] ??= []).push(key);\n } else {\n (result.invalid[locale] ??= []).push(key);\n }\n }\n options.onProgress?.(progressOf(job));\n });\n\n // batches land out of order once they run in parallel, and a report has to read the same twice\n for (const locale of Object.keys(result.translated)) result.translated[locale]!.sort();\n for (const locale of Object.keys(result.invalid)) result.invalid[locale]!.sort();\n result.failed.sort((a, b) => byCodeUnit(a.locale, b.locale) || compare(a.keys, b.keys));\n return result;\n}\n\nfunction compare(a: string[], b: string[]): number {\n return byCodeUnit(a[0] ?? '', b[0] ?? '');\n}\n\n// a run takes minutes, so it writes onto the file as it is now: text a person added meanwhile stays\nexport function mergeTranslations(\n cfg: ResolvedConfig,\n locale: string,\n translated: Catalog,\n keys: string[],\n): string[] {\n const source = readCatalog(cfg, cfg.sourceLocale);\n const current = readCatalog(cfg, locale);\n const written: string[] = [];\n for (const key of keys) {\n const text = translated[key];\n // pruned meanwhile, or filled meanwhile: either way the file already says what it should\n if (!source[key] || current[key] || !text) continue;\n current[key] = text;\n written.push(key);\n }\n if (written.length > 0) writeCatalog(cfg, locale, current);\n return written;\n}\n\nexport interface DraftEntry {\n key: string;\n text: string;\n}\n\nexport interface WriteDraftsResult {\n written: string[];\n kept: string[];\n invalid: string[];\n unknown: string[];\n}\n\n// A batch of drafts is a batch of translations, so it can be written and marked as unreviewed\nexport interface WriteDraftsOptions {\n overwrite?: boolean;\n registry?: MessageRegistry;\n}\n\n// an agent's own translation lands like a provider's: checked, written and marked unreviewed\nexport function writeDrafts(\n cfg: ResolvedConfig,\n locale: string,\n entries: DraftEntry[],\n options: WriteDraftsOptions = {},\n): WriteDraftsResult {\n const targets = targetLocales(cfg);\n if (!targets.includes(locale)) {\n throw new Error(\n `[verbaly] \"${locale}\" is not a language this project translates into (${targets.join(', ') || 'none yet'})`,\n );\n }\n // the draft flag is what keeps it from passing as reviewed: an unreadable state writes nothing\n loadState(cfg);\n const catalogs: Catalogs = { [cfg.sourceLocale]: readCatalog(cfg, cfg.sourceLocale) };\n const source = options.registry\n ? shippedCatalogs(cfg, catalogs, options.registry, { newKeys: false })[cfg.sourceLocale]!\n : catalogs[cfg.sourceLocale]!;\n const current = readCatalog(cfg, locale);\n const result: WriteDraftsResult = { written: [], kept: [], invalid: [], unknown: [] };\n for (const { key, text } of entries) {\n const from = own(source, key);\n if (!from) result.unknown.push(key);\n else if (!text.trim() || !structureMatches(from, text)) result.invalid.push(key);\n else if (own(current, key) && !options.overwrite) result.kept.push(key);\n else {\n current[key] = text;\n result.written.push(key);\n }\n }\n if (result.written.length > 0) {\n writeCatalog(cfg, locale, current);\n const written = result.written.map((key) => ({ key, text: current[key]! }));\n recordTranslations(cfg, source, [{ locale, entries: written, draft: true }]);\n }\n return result;\n}\n\n// the same reason repeats across batches: say it once and name every key it cost\nexport function formatTranslateFailures(failed: TranslateFailure[]): string[] {\n const grouped: TranslateFailure[] = [];\n for (const entry of failed) {\n const same = grouped.find((it) => it.locale === entry.locale && it.error === entry.error);\n if (same) same.keys = [...same.keys, ...entry.keys];\n else grouped.push({ ...entry, keys: [...entry.keys] });\n }\n return grouped.map(\n ({ locale, error, keys }) =>\n ` ${locale}: ${counted(keys.length, 'message')} not translated (${error}): ${keys.join(', ')}`,\n );\n}\n\n// config provider wins; claude loads lazily so only translate pays for its optional SDK\nexport async function resolveProvider(\n cfg: ResolvedConfig,\n model?: string,\n): Promise<TranslateProvider> {\n const configured = cfg.translate.provider;\n if (typeof configured === 'function') return configured;\n const { claudeProvider } = await import('./providers/claude');\n return claudeProvider({ model: model ?? cfg.translate.model });\n}\n\n// no locale on purpose: a locale-specific plural gap must never drop a translator's file\nexport function structureMatches(source: string, translated: string): boolean {\n try {\n const issues = [...validateMessage(translated), ...validatePair(source, translated)];\n return !issues.some((issue) => issue.severity === 'error');\n } catch {\n return false; // unparseable input rejects the translation, it never crashes the caller\n }\n}\n\nfunction progressOf(job: Batch): TranslateProgress {\n return { locale: job.locale, batch: job.index, batches: job.batches, keys: job.keys.length };\n}\n\n// only the terms this batch actually contains: a glossary of hundreds must not become the prompt\nfunction glossaryFor(\n cfg: ResolvedConfig,\n locale: string,\n messages: Record<string, string>,\n): Record<string, string> | undefined {\n const entries = cfg.translate.glossary;\n if (!entries) return undefined;\n const text = Object.values(messages).join('\\n').toLowerCase();\n const out: Record<string, string> = {};\n for (const [term, rendering] of Object.entries(entries)) {\n if (!text.includes(term.toLowerCase())) continue;\n const value = typeof rendering === 'string' ? rendering : rendering[locale];\n if (value) out[term] = value;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n","import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport MagicString from 'magic-string';\nimport picomatch from 'picomatch';\nimport { glob } from 'tinyglobby';\nimport {\n alternateLinks,\n createVerbaly,\n localeDirection,\n LOCALE_STORAGE_KEY,\n normalizeLink,\n parseTags,\n RICH_TAGS,\n CATALOG_SCRIPT,\n safeAttribute,\n VOID_TAGS,\n type MessageTree,\n type Params,\n type RichLink,\n type TagNode,\n type Verbaly,\n} from 'verbaly';\nimport type { Catalogs } from './catalog';\nimport { loadCatalogs } from './catalog';\nimport { extractProject, shippedCatalogs } from './extract';\nimport type { RedirectConfig, ResolvedConfig } from './config';\nimport { counted } from './text';\nimport { warnOnce } from './warn';\n\nexport interface Alternate {\n hreflang: string;\n href: string;\n}\n\n// links that point at a page this mirror also holds get its prefix, so the visitor stays inside\nexport interface MirrorLinks {\n prefix: string;\n base?: string;\n pages: ReadonlySet<string>;\n}\n\n// the pre-paint script: the locale set it chooses from, and where a saved choice lives\nexport interface RedirectScript {\n locales: string[];\n sourceLocale: string;\n base?: string;\n storageKey?: string | false;\n}\n\ninterface RenderHtmlBase {\n locale: string;\n sourceLocale?: string;\n attribute?: string;\n richTags?: string[];\n richLinks?: Record<string, RichLink>;\n setLang?: boolean;\n alternates?: Alternate[];\n mirror?: MirrorLinks;\n redirect?: RedirectScript;\n inlineCatalog?: boolean;\n}\n\n// one of the two, never both: an instance already carries the catalogs it was built from\nexport type RenderHtmlOptions = RenderHtmlBase &\n (\n | { catalogs: Catalogs | Record<string, MessageTree>; instance?: never }\n | { catalogs?: never; instance: Verbaly }\n );\n\n// nested trees welcome: the runtime flattens them (verbaly-web's shape)\nexport function localeInstance(\n catalogs: Catalogs | Record<string, MessageTree>,\n locale: string,\n sourceLocale: string,\n): Verbaly {\n return createVerbaly({ locale, fallback: sourceLocale, messages: catalogs });\n}\n\nexport interface RenderHtmlResult {\n html: string;\n missing: string[];\n // every key this page resolved: the exact set a visitor needs, and nothing else\n used: string[];\n}\n\nconst HREFLANG_OPEN = '<!--verbaly:hreflang-->';\nconst HREFLANG_CLOSE = '<!--/verbaly:hreflang-->';\nconst CATALOG_OPEN = '<!--verbaly:catalog-->';\nconst CATALOG_CLOSE = '<!--/verbaly:catalog-->';\nconst REDIRECT_OPEN = '<!--verbaly:redirect-->';\nconst REDIRECT_CLOSE = '<!--/verbaly:redirect-->';\n\nconst VOID = new Set(VOID_TAGS);\n\nconst START_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)((?:\"[^\"]*\"|'[^']*'|[^\"'>])*)>/g;\nconst ATTR = /([^\\s=/\"'<>]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+)))?/g;\n\n// pre-fills data-verbaly elements for one locale; the runtime stays functional\nexport function renderHtml(html: string, options: RenderHtmlOptions): RenderHtmlResult {\n const attr = options.attribute ?? 'data-verbaly';\n const argsAttr = `${attr}-args`;\n const attrsAttr = `${attr}-attr`;\n const richAttr = `${attr}-rich`;\n const linksAttr = `${attr}-links`;\n const richTags = new Set(options.richTags ?? RICH_TAGS);\n const globalLinks = options.richLinks;\n const sourceLocale = options.sourceLocale ?? 'en';\n\n const v = options.instance ?? localeInstance(options.catalogs, options.locale, sourceLocale);\n const t = v.t as unknown as (key: string, params?: Params) => string;\n\n const ms = new MagicString(html);\n const missing = new Set<string>();\n const used = new Set<string>();\n const skip = protectedRanges(html);\n const inSkip = (index: number): boolean => skip.some(([from, to]) => index >= from && index < to);\n\n // a message can carry markup of its own, and MagicString refuses to edit inside what it replaced\n const filled: Array<[number, number]> = [];\n const inFilled = (index: number): boolean =>\n filled.some(([from, to]) => index >= from && index < to);\n\n // per-locale canonical/og:url: a cross-locale canonical would void the hreflang set\n const selfUrl = options.alternates?.find((a) => a.hreflang === options.locale)?.href;\n const sourceUrl = options.alternates?.find((a) => a.hreflang === 'x-default')?.href;\n const rewriteUrl = selfUrl !== undefined && selfUrl !== sourceUrl;\n\n START_TAG.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = START_TAG.exec(html)) !== null) {\n if (inSkip(m.index) || inFilled(m.index)) continue;\n const [full, rawName, attrChunk] = m as unknown as [string, string, string];\n const tagName = rawName.toLowerCase();\n const openEnd = m.index + full.length;\n\n const chunkStart = m.index + 1 + rawName.length;\n\n if (tagName === 'html' && options.setLang !== false) {\n // lang and dir together: what persistLocale/switchLocale set at runtime\n setAttribute(ms, html, chunkStart, openEnd, attrChunk, 'lang', options.locale);\n setAttribute(\n ms,\n html,\n chunkStart,\n openEnd,\n attrChunk,\n 'dir',\n localeDirection(options.locale),\n );\n continue;\n }\n\n const attrs = parseAttrs(attrChunk);\n\n if (\n rewriteUrl &&\n tagName === 'link' &&\n attrs.get('rel')?.toLowerCase() === 'canonical' &&\n decodeEntities(attrs.get('href') ?? '') === sourceUrl\n ) {\n setAttribute(ms, html, chunkStart, openEnd, attrChunk, 'href', selfUrl!);\n }\n if (\n rewriteUrl &&\n tagName === 'meta' &&\n attrs.get('property') === 'og:url' &&\n decodeEntities(attrs.get('content') ?? '') === sourceUrl\n ) {\n setAttribute(ms, html, chunkStart, openEnd, attrChunk, 'content', selfUrl!);\n }\n\n const mirror = options.mirror;\n if (mirror) {\n if (tagName === 'a' || tagName === 'area') {\n const inside = mirroredHref(attrs.get('href'), mirror);\n if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, 'href', inside);\n } else if (tagName === 'form' || tagName === 'button' || tagName === 'input') {\n // submitting navigates: a form landing on a page we mirrored belongs in the mirror too\n const name = tagName === 'form' ? 'action' : 'formaction';\n const inside = mirroredHref(attrs.get(name), mirror);\n if (inside) setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, inside);\n } else if (tagName === 'meta' && attrs.get('http-equiv')?.toLowerCase() === 'refresh') {\n // a redirect page ships inside the mirror too, and its target must not leave it\n const content = attrs.get('content') ?? '';\n const url = /^([^;]*;\\s*url\\s*=\\s*)(.*)$/i.exec(decodeEntities(content));\n const inside = url && mirroredHref(url[2], mirror);\n if (inside) {\n setAttribute(ms, html, chunkStart, openEnd, attrChunk, 'content', `${url![1]}${inside}`);\n }\n }\n }\n\n const key = attrs.get(attr);\n const attrMapRaw = attrs.get(attrsAttr);\n if (key === undefined && attrMapRaw === undefined) continue;\n\n const args = parseArgs(attrs.get(argsAttr), argsAttr);\n\n if (key) {\n if (!v.has(key)) {\n missing.add(key);\n } else if (!VOID.has(tagName) && !attrChunk.trimEnd().endsWith('/')) {\n used.add(key);\n const close = findClose(html, tagName, openEnd, inSkip);\n if (close) {\n const text = t(key, args);\n const own = parseArgs(attrs.get(linksAttr), linksAttr) as Record<string, RichLink> | undefined;\n const merged = own ? (globalLinks ? { ...globalLinks, ...own } : own) : globalLinks;\n // a link inside a message is a link: without the prefix it leaves the mirror\n const links = mirror ? mirroredLinks(merged, mirror) : merged;\n const nodes = attrs.has(richAttr) ? parseTags(text) : [];\n // the page carries its own links: the runtime rebuilds from here, never from the config\n if (mirror && links) {\n const carried = usedLinks(nodes, links);\n if (carried && JSON.stringify(carried) !== JSON.stringify(own)) {\n setAttribute(\n ms,\n html,\n chunkStart,\n openEnd,\n attrChunk,\n linksAttr,\n JSON.stringify(carried),\n );\n }\n }\n const content = attrs.has(richAttr)\n ? richToHtml(nodes, richTags, links)\n : escapeHtml(text);\n if (html.slice(openEnd, close.contentEnd) !== content) {\n if (openEnd === close.contentEnd) ms.appendLeft(openEnd, content);\n else ms.overwrite(openEnd, close.contentEnd, content);\n }\n filled.push([openEnd, close.contentEnd]);\n }\n }\n }\n\n if (attrMapRaw !== undefined) {\n const map = parseArgs(attrMapRaw, attrsAttr);\n if (map) {\n for (const [name, attrKey] of Object.entries(map)) {\n if (typeof attrKey !== 'string') continue;\n if (!v.has(attrKey)) {\n missing.add(attrKey);\n continue;\n }\n used.add(attrKey);\n const value = safeAttribute(name, t(attrKey, args));\n if (value !== undefined)\n setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value);\n }\n }\n }\n }\n\n if (options.alternates?.length) injectAlternates(ms, html, options.alternates);\n if (options.redirect) injectRedirect(ms, html, options.redirect);\n // the source catalog always ships eagerly, so its own tree gains nothing from a slice\n if (options.inlineCatalog && options.locale !== sourceLocale) {\n const slice = pageSlice(v, options.locale, used);\n if (Object.keys(slice).length > 0) injectCatalog(ms, html, slice);\n }\n\n return { html: ms.toString(), missing: [...missing], used: [...used] };\n}\n\n// every key the page used, '' where the locale falls back: a short slice is not an empty message\nfunction pageSlice(v: Verbaly, locale: string, used: Set<string>): Record<string, string> {\n const slice: Record<string, string> = Object.create(null);\n for (const key of used) {\n const found = v.inspect(key);\n slice[key] = found?.from === locale ? found.source : '';\n }\n return slice;\n}\n\n// the public path of a built page, the shape both the page set and an author's href reduce to\nexport function publicPath(rel: string): string {\n const path = `/${rel.replace(/(^|\\/)index\\.html$/, '$1')}`;\n return path.length > 1 ? path.replace(/\\/+$/, '') : path;\n}\n\n// own entries only: a tag named constructor in a message must not find the one on Object\nfunction linkFor(links: Record<string, RichLink> | undefined, name: string): RichLink | undefined {\n return links && Object.hasOwn(links, name) ? links[name] : undefined;\n}\n\n// only the names this message actually renders: a global map has entries other messages use\nfunction usedLinks(\n nodes: TagNode[],\n links: Record<string, RichLink>,\n): Record<string, RichLink> | undefined {\n const out: Record<string, RichLink> = {};\n const walk = (list: TagNode[]): void => {\n for (const node of list) {\n if (typeof node === 'string') continue;\n const link = linkFor(links, node.name);\n if (link !== undefined) out[node.name] = link;\n walk(node.children);\n }\n };\n walk(nodes);\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n// same rule as an author's href, applied to the links a message renders through its map\nfunction mirroredLinks(\n links: Record<string, RichLink> | undefined,\n mirror: MirrorLinks,\n): Record<string, RichLink> | undefined {\n if (!links) return links;\n const out: Record<string, RichLink> = {};\n for (const [name, link] of Object.entries(links)) {\n const href = typeof link === 'string' ? link : link.href;\n const inside = mirroredHref(href, mirror);\n if (inside === undefined) out[name] = link;\n else out[name] = typeof link === 'string' ? inside : { ...link, href: inside };\n }\n return out;\n}\n\n// only a root-relative link to a page the mirror contains: assets, externals and anchors stay\nfunction mirroredHref(raw: string | undefined, mirror: MirrorLinks): string | undefined {\n if (raw === undefined) return undefined;\n const href = decodeEntities(raw);\n if (!href.startsWith('/') || href.startsWith('//')) return undefined;\n const base = mirror.base ?? '';\n // hrefs carry the base the site is served under, the page set never does: compare like with like\n const inside = base ? stripBase(href, base) : href;\n if (base && inside === href) return undefined;\n const cut = inside.search(/[?#]/);\n const path = cut < 0 ? inside : inside.slice(0, cut);\n if (!mirror.pages.has(publicPath(path.replace(/^\\//, '')))) return undefined;\n return `${base}${mirror.prefix}${inside}`;\n}\n\n// the boundary check is what keeps base /app from swallowing /application\nfunction stripBase(path: string, base: string): string {\n if (!path.startsWith(base)) return path;\n const rest = path.slice(base.length);\n if (rest === '') return '/';\n return rest.startsWith('/') ? rest : path;\n}\n\n// 'app', '/app' and '/app/' all read as '/app'; nothing means the site sits at the root\nfunction normalizeBase(base: string | undefined): string {\n const trimmed = base?.replace(/^\\/+/, '').replace(/\\/+$/, '');\n return trimmed ? `/${trimmed}` : '';\n}\n\n// the narrowing of matchPathSegment, inlined: render == runtime has to hold here too\nconst REDIRECT_BODY =\n '(function(){var T=/^[a-z]{2,3}(-[a-z]{4})?(-([a-z]{2}|[0-9]{3}))?$/i;' +\n 'function M(t,g){t=String(t||\"\");if(S.indexOf(t)>=0)return t;if(g&&!T.test(t))return;' +\n 'while(t){var i=t.lastIndexOf(\"-\");if(i<0)return;t=t.slice(0,i);if(S.indexOf(t)>=0)return t}}' +\n 'var p=location.pathname;' +\n 'if(B){if(p.indexOf(B)!==0)return;p=p.slice(B.length)||\"/\";if(p.charAt(0)!==\"/\")return}' +\n 'if(M(p.split(\"/\")[1],1))return;' +\n 'var w;if(K)try{w=M(localStorage.getItem(K))}catch(e){}' +\n 'if(!w){var l=navigator.languages||[navigator.language];for(var i=0;i<l.length&&!w;i++)w=M(l[i])}' +\n 'if(!w||w===D)return;location.replace(B+\"/\"+w+p+location.search+location.hash)})()';\n\n// </script> can never appear in a locale code, but a catalog is untrusted and this costs nothing\nfunction jsLiteral(value: unknown): string {\n return JSON.stringify(value ?? null).replace(/</g, '\\\\u003c');\n}\n\n// pre-paint, in the source tree only: the mirror page a visitor lands on is already the answer\nfunction redirectScript(options: RedirectScript): string {\n const vars = [\n `S=${jsLiteral(options.locales)}`,\n `D=${jsLiteral(options.sourceLocale)}`,\n `B=${jsLiteral(normalizeBase(options.base))}`,\n `K=${options.storageKey === false ? 'null' : jsLiteral(options.storageKey ?? LOCALE_STORAGE_KEY)}`,\n ].join(',');\n return `<script>var ${vars};${REDIRECT_BODY};</script>`;\n}\n\n// goes first in <head> so it runs before a stylesheet can paint, idempotent via markers\nfunction injectRedirect(ms: MagicString, html: string, options: RedirectScript): void {\n const block = `${REDIRECT_OPEN}${redirectScript(options)}${REDIRECT_CLOSE}`;\n const from = html.indexOf(REDIRECT_OPEN);\n if (from !== -1) {\n const to = html.indexOf(REDIRECT_CLOSE, from);\n if (to !== -1) {\n const end = to + REDIRECT_CLOSE.length;\n if (html.slice(from, end) !== block) ms.overwrite(from, end, block);\n return;\n }\n }\n const head = /<head\\b(?:\"[^\"]*\"|'[^']*'|[^\"'>])*>/i.exec(html);\n if (head) ms.appendRight(head.index + head[0].length, block);\n}\n\n// injects <link rel=\"alternate\" hreflang> into <head>, idempotent via markers\nfunction injectAlternates(ms: MagicString, html: string, alternates: Alternate[]): void {\n const links = alternates\n .map(\n (a) =>\n `<link rel=\"alternate\" hreflang=\"${escapeAttr(a.hreflang)}\" href=\"${escapeAttr(a.href)}\">`,\n )\n .join('');\n const block = `${HREFLANG_OPEN}${links}${HREFLANG_CLOSE}`;\n const from = html.indexOf(HREFLANG_OPEN);\n if (from !== -1) {\n const to = html.indexOf(HREFLANG_CLOSE, from);\n if (to !== -1) {\n const end = to + HREFLANG_CLOSE.length;\n if (html.slice(from, end) !== block) ms.overwrite(from, end, block);\n return;\n }\n }\n const head = /<\\/head\\s*>/i.exec(html);\n if (head) ms.appendLeft(head.index, block);\n}\n\n// inlines the slice this page needs, so a mirrored page fetches no catalog at all\nfunction injectCatalog(ms: MagicString, html: string, messages: Record<string, string>): void {\n // <!-- opens a state where the closing </script> no longer closes, and JSON has no escape for it\n const json = JSON.stringify(messages).replace(/<\\//g, '<\\\\/').replace(/<!--/g, '\\\\u003c!--');\n const tag = `<script ${CATALOG_SCRIPT} type=\"application/json\">${json}</script>`;\n const block = `${CATALOG_OPEN}${tag}${CATALOG_CLOSE}`;\n const from = html.indexOf(CATALOG_OPEN);\n if (from !== -1) {\n const to = html.indexOf(CATALOG_CLOSE, from);\n if (to !== -1) {\n const end = to + CATALOG_CLOSE.length;\n if (html.slice(from, end) !== block) ms.overwrite(from, end, block);\n return;\n }\n }\n const head = /<\\/head\\s*>/i.exec(html);\n if (head) ms.appendLeft(head.index, block);\n}\n\nexport interface RenderSiteOptions {\n site?: string;\n locales?: string[];\n attribute?: string;\n richTags?: string[];\n richLinks?: Record<string, RichLink>;\n base?: string;\n baseUrl?: string;\n hreflang?: boolean;\n exclude?: string[];\n sitemap?: boolean | string;\n redirect?: boolean | RedirectConfig;\n clean?: boolean;\n}\n\nexport interface RenderSiteResult {\n files: number;\n locales: string[];\n missing: Record<string, string[]>;\n untranslatedHead: string[];\n}\n\nconst TITLE_TAG = /<title\\b([^>]*)>/i;\nconst REFRESH_META = /<meta\\b[^>]*http-equiv\\s*=\\s*[\"']?refresh/i;\n\nconst NOINDEX_META = /<meta\\b[^>]*name\\s*=\\s*[\"']?robots[\"']?[^>]*content\\s*=\\s*[\"'][^\"']*noindex/i;\n\n// the mirror still publishes these, they are simply never search results\nfunction isIndexable(html: string): boolean {\n return !REFRESH_META.test(html) && !NOINDEX_META.test(html);\n}\n\n// a <title> with no key ships the source language everywhere, and it is most of a search result\nfunction headIsBound(html: string, attr: string): boolean {\n // a page that only redirects is never a search result, so its title is nobody's to translate\n if (REFRESH_META.test(html)) return true;\n const title = TITLE_TAG.exec(html);\n return title ? title[1]!.includes(attr) : true;\n}\n\n// mirrors the built site per locale: dist/index.html → dist/<locale>/index.html\nexport async function renderSite(\n cfg: ResolvedConfig,\n options: RenderSiteOptions = {},\n): Promise<RenderSiteResult> {\n const site = join(cfg.root, options.site ?? cfg.render.site ?? 'dist');\n const locales = options.locales ?? cfg.locales;\n const attribute = options.attribute ?? cfg.render.attribute;\n const base = normalizeBase(options.base ?? cfg.render.base);\n const baseUrl = (options.baseUrl ?? cfg.render.baseUrl)?.replace(/\\/+$/, '');\n const wantHreflang = (options.hreflang ?? cfg.render.hreflang ?? true) && baseUrl !== undefined;\n // the escape hatch for a page that is indexable and still not ours to list\n const patterns = options.exclude ?? cfg.render.exclude ?? [];\n const excluded = patterns.length > 0 ? picomatch(patterns) : () => false;\n const sitemap = options.sitemap ?? cfg.render.sitemap ?? false;\n const wantSitemap = sitemap !== false && baseUrl !== undefined;\n const clean = options.clean ?? cfg.render.clean ?? false;\n const wanted = options.redirect ?? cfg.render.redirect ?? false;\n const redirect = wanted === false ? undefined : wanted === true ? {} : wanted;\n const script: RedirectScript | undefined = redirect && {\n locales,\n sourceLocale: cfg.sourceLocale,\n base,\n storageKey: redirect.storageKey,\n };\n // the text the build ships, or the pre-filled page and the runtime that repaints it disagree\n const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), await extractProject(cfg));\n // one runtime per locale for the whole run: rebuilding it per page reflattened every catalog\n const instances = new Map(\n locales.map((locale) => [locale, localeInstance(catalogs, locale, cfg.sourceLocale)]),\n );\n\n if (clean) {\n for (const locale of locales) {\n if (locale !== cfg.sourceLocale) rmSync(join(site, locale), { recursive: true, force: true });\n }\n }\n\n const files = await glob('**/*.html', {\n cwd: site,\n absolute: true,\n ignore: locales.map((locale) => `${locale}/**`),\n });\n\n // every page the mirror will hold, so a link into one of them can keep the visitor inside\n const pages = new Set(files.map((file) => publicPath(relative(site, file).replace(/\\\\/g, '/'))));\n\n const missing: Record<string, string[]> = {};\n const untranslatedHead: string[] = [];\n const urls: Array<{ rel: string; alternates: Alternate[] }> = [];\n for (const file of files) {\n const html = readFileSync(file, 'utf8');\n const rel = relative(site, file).replace(/\\\\/g, '/');\n // one locale is not a mirror, so there is no second title for this one to disagree with\n if (locales.length > 1 && !headIsBound(html, attribute ?? 'data-verbaly')) {\n untranslatedHead.push(rel);\n }\n const alternates = wantHreflang ? pageAlternates(baseUrl!, rel, locales, cfg.sourceLocale) : [];\n if (wantHreflang && isIndexable(html) && !excluded(rel)) urls.push({ rel, alternates });\n // only the source tree carries it: the mirror page a visitor reaches is already the answer\n const routed = script && (redirect!.on === 'all' || rel === 'index.html');\n for (const locale of locales) {\n const result = renderHtml(html, {\n locale,\n instance: instances.get(locale)!,\n sourceLocale: cfg.sourceLocale,\n attribute,\n richTags: options.richTags,\n richLinks: options.richLinks ?? cfg.render.links,\n alternates,\n mirror: locale === cfg.sourceLocale ? undefined : { prefix: `/${locale}`, base, pages },\n redirect: routed && locale === cfg.sourceLocale ? script : undefined,\n inlineCatalog: cfg.render.inlineCatalog === true,\n });\n for (const key of result.missing) {\n const list = (missing[locale] ??= []);\n if (!list.includes(key)) list.push(key);\n }\n const out = locale === cfg.sourceLocale ? file : join(site, locale, rel);\n mkdirSync(dirname(out), { recursive: true });\n writeFileSync(out, result.html);\n }\n }\n\n if (wantSitemap && urls.length) {\n const name = typeof sitemap === 'string' ? sitemap : 'sitemap-i18n.xml';\n writeFileSync(join(site, name), buildSitemap(urls));\n }\n\n return { files: files.length, locales: [...locales], missing, untranslatedHead };\n}\n\n// the cli and @verbaly/astro both run the mirror, so what it warns about is written once\nexport function formatRenderWarnings(result: RenderSiteResult, sourceLocale: string): string[] {\n const lines: string[] = [];\n for (const [locale, keys] of Object.entries(result.missing)) {\n lines.push(` ${locale}: ${counted(keys.length, 'key')} not pre-filled: ${keys.join(', ')}`);\n }\n if (result.untranslatedHead.length > 0) {\n lines.push(\n ` ${counted(result.untranslatedHead.length, 'page')} of ${result.files} ship the same <title> in every locale (${result.untranslatedHead[0]}), so search results read in ${sourceLocale}`,\n ` fix: bind the head too, <title data-verbaly=\"key\"> and a meta through data-verbaly-attr`,\n );\n }\n return lines;\n}\n\n// request path of a built page path (index.html → directory URL)\nfunction pagePath(rel: string): string {\n const path = rel.replace(/(^|\\/)index\\.html$/, '$1');\n return path ? `/${path}` : '/';\n}\n\n// reciprocal hreflang set for one page, from core: an SSR head has to write the same one\nfunction pageAlternates(\n baseUrl: string,\n rel: string,\n locales: string[],\n sourceLocale: string,\n): Alternate[] {\n return alternateLinks({\n supported: locales,\n sourceLocale,\n path: pagePath(rel),\n routing: 'prefix-except-source',\n baseUrl,\n });\n}\n\nfunction buildSitemap(urls: Array<{ rel: string; alternates: Alternate[] }>): string {\n const body = urls\n .flatMap(({ alternates }) => {\n const alts = alternates\n .map(\n (a) =>\n `<xhtml:link rel=\"alternate\" hreflang=\"${a.hreflang}\" href=\"${escapeAttr(a.href)}\"/>`,\n )\n .join('');\n return alternates\n .filter((a) => a.hreflang !== 'x-default')\n .map((self) => `<url><loc>${escapeAttr(self.href)}</loc>${alts}</url>`);\n })\n .join('');\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">${body}</urlset>\\n`;\n}\n\nfunction parseAttrs(chunk: string): Map<string, string> {\n const attrs = new Map<string, string>();\n ATTR.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = ATTR.exec(chunk)) !== null) {\n attrs.set(m[1]!.toLowerCase(), m[2] ?? m[3] ?? m[4] ?? '');\n }\n return attrs;\n}\n\n// three attributes share this parser, so the report names the one that is actually malformed\nfunction parseArgs(raw: string | undefined, attribute: string): Params | undefined {\n if (!raw) return undefined;\n try {\n return JSON.parse(decodeEntities(raw)) as Params;\n } catch {\n // a page is mirrored once per locale, so a raw warn says the same thing once per tree\n warnOnce(`invalid JSON in ${attribute}: ${raw}`, `${attribute}:${raw}`);\n return undefined;\n }\n}\n\n// comments and script/style bodies are opaque to the scanner\nfunction protectedRanges(html: string): Array<[number, number]> {\n const ranges: Array<[number, number]> = [];\n const re = /<!--[\\s\\S]*?-->|<script\\b[\\s\\S]*?<\\/script\\s*>|<style\\b[\\s\\S]*?<\\/style\\s*>/gi;\n let m: RegExpExecArray | null;\n while ((m = re.exec(html)) !== null) {\n // keep script/style open tags scannable; protect only their bodies\n const openEnd = m[0].startsWith('<!--') ? m.index : html.indexOf('>', m.index) + 1;\n ranges.push([openEnd, m.index + m[0].length]);\n }\n return ranges;\n}\n\nfunction findClose(\n html: string,\n tagName: string,\n from: number,\n inSkip: (index: number) => boolean,\n): { contentEnd: number } | null {\n const re = new RegExp(\n `<${tagName}(?=[\\\\s/>])(?:\"[^\"]*\"|'[^']*'|[^\"'>])*>|</${tagName}\\\\s*>`,\n 'gi',\n );\n re.lastIndex = from;\n let depth = 1;\n let m: RegExpExecArray | null;\n while ((m = re.exec(html)) !== null) {\n if (inSkip(m.index)) continue;\n if (m[0][1] === '/') {\n depth -= 1;\n if (depth === 0) return { contentEnd: m.index };\n } else if (!m[0].endsWith('/>')) {\n depth += 1;\n }\n }\n return null;\n}\n\nfunction setAttribute(\n ms: MagicString,\n html: string,\n chunkStart: number,\n openEnd: number,\n attrChunk: string,\n name: string,\n value: string,\n): void {\n const escaped = escapeAttr(value);\n const existing = new RegExp(`(\\\\s${name}\\\\s*=\\\\s*)(\"[^\"]*\"|'[^']*'|[^\\\\s>]+)`, 'i').exec(\n attrChunk,\n );\n if (existing) {\n const valueStart = chunkStart + existing.index + existing[1]!.length;\n const valueEnd = valueStart + existing[2]!.length;\n if (html.slice(valueStart, valueEnd) !== `\"${escaped}\"`) {\n ms.overwrite(valueStart, valueEnd, `\"${escaped}\"`);\n }\n return;\n }\n const selfClosing = html.slice(openEnd - 2, openEnd) === '/>';\n const insertAt = openEnd - (selfClosing ? 2 : 1);\n ms.appendLeft(insertAt, ` ${name}=\"${escaped}\"`);\n}\n\nfunction richToHtml(\n nodes: TagNode[],\n allowed: Set<string>,\n links?: Record<string, RichLink>,\n): string {\n let out = '';\n for (const node of nodes) {\n const link = typeof node === 'string' ? undefined : linkFor(links, node.name);\n if (typeof node === 'string') {\n out += escapeHtml(node);\n } else if (link !== undefined) {\n const { href, target, rel } = normalizeLink(link);\n let attrs = href !== undefined ? ` href=\"${escapeAttr(href)}\"` : '';\n if (target) attrs += ` target=\"${escapeAttr(target)}\"`;\n if (rel) attrs += ` rel=\"${escapeAttr(rel)}\"`;\n out += `<a${attrs}>${richToHtml(node.children, allowed, links)}</a>`;\n } else if (allowed.has(node.name)) {\n out += VOID.has(node.name)\n ? `<${node.name}>`\n : `<${node.name}>${richToHtml(node.children, allowed, links)}</${node.name}>`;\n } else {\n out += richToHtml(node.children, allowed, links); // unknown tag → unwrap\n }\n }\n return out;\n}\n\nfunction escapeHtml(text: string): string {\n return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n}\n\nfunction escapeAttr(text: string): string {\n return escapeHtml(text).replace(/\"/g, '"');\n}\n\nfunction decodeEntities(text: string): string {\n return text\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/&/g, '&');\n}\n","import { lstatSync, readdirSync, watch, type FSWatcher } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type { ResolvedConfig } from './config';\nimport { SOURCE_FILE_RE } from './plugin';\n\n// only these watch a tree natively: elsewhere Node walks it in sync and watches every entry\nconst NATIVE_TREE = process.platform === 'darwin' || process.platform === 'win32';\n\nexport interface TreeOptions {\n keep?: string;\n native?: boolean;\n persistent?: boolean;\n}\n\n// every change under root, named from root; node_modules alone can use up the inotify limit\nexport function watchTree(\n root: string,\n options: TreeOptions,\n onFile: (file: string) => void,\n): () => void {\n // by top-level name, '' being the root itself\n const watchers = new Map<string, FSWatcher>();\n const close = (name: string): void => {\n watchers.get(name)?.close();\n watchers.delete(name);\n };\n const open = (\n name: string,\n recursive: boolean,\n listener: (event: string, file: string | null) => void,\n ): void => {\n const watcher = watch(\n join(root, name),\n { recursive, persistent: options.persistent ?? true },\n listener,\n );\n // an error nobody listens to ends the process, and a quiet stop would end the watching\n watcher.on('error', (error) => {\n close(name);\n console.warn(`[verbaly] stopped watching ${name || 'the project'}:`, error);\n });\n watchers.set(name, watcher);\n };\n\n if (options.native ?? NATIVE_TREE) {\n open('', true, (_event, file) => {\n if (file) onFile(file);\n });\n } else {\n // the top level by hand, so a directory that holds no code is never walked at all\n const sync = (name: string): void => {\n // the root hears of a directory only when it is made, removed or moved: reopen, never reuse\n close(name);\n if (name !== options.keep && (name === 'node_modules' || name.startsWith('.'))) return;\n try {\n // lstat: a linked directory is not walked, the same as at startup and as native watching\n if (!lstatSync(join(root, name)).isDirectory()) return;\n open(name, true, (_event, file) => {\n if (file) onFile(`${name}/${file}`);\n });\n } catch (error) {\n // a throw in a watch callback ends the process: say a watch limit, not a vanished dir\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n console.warn(`[verbaly] could not watch ${name}:`, error);\n }\n }\n };\n open('', false, (event, file) => {\n if (!file) return;\n // a change is the same directory touched, and reopening it would walk the whole tree again\n if (event === 'rename') sync(file);\n onFile(file);\n });\n for (const entry of readdirSync(root, { withFileTypes: true })) {\n if (entry.isDirectory()) sync(entry.name);\n }\n }\n return () => {\n for (const name of [...watchers.keys()]) close(name);\n };\n}\n\nexport interface WatchProjectOptions {\n debounce?: number;\n}\n\n// source files only: extract's own catalog/dts writes must never retrigger a run\nexport function watchProject(\n cfg: ResolvedConfig,\n run: () => Promise<void>,\n options: WatchProjectOptions = {},\n): () => void {\n const catalogDir = relative(cfg.root, cfg.dir).replaceAll('\\\\', '/');\n let timer: ReturnType<typeof setTimeout> | undefined;\n let running = false;\n let queued = false;\n\n async function refresh(): Promise<void> {\n if (running) {\n queued = true;\n return;\n }\n running = true;\n try {\n await run();\n } catch (error) {\n console.warn('[verbaly] watch run failed:', error);\n } finally {\n running = false;\n if (queued) {\n queued = false;\n schedule();\n }\n }\n }\n\n function schedule(): void {\n clearTimeout(timer);\n timer = setTimeout(() => void refresh(), options.debounce ?? 150);\n }\n\n const close = watchTree(cfg.root, {}, (filename) => {\n if (!filename) return;\n const file = filename.replaceAll('\\\\', '/');\n if (file.includes('node_modules/') || file.endsWith('.d.ts')) return;\n if (catalogDir && file.startsWith(`${catalogDir}/`)) return;\n if (SOURCE_FILE_RE.test(file)) schedule();\n });\n\n return (): void => {\n clearTimeout(timer);\n close();\n };\n}\n","import { readFileSync, writeFileSync } from 'node:fs';\nimport { relative } from 'node:path';\nimport { parse } from '@babel/parser';\nimport MagicString from 'magic-string';\nimport { glob } from 'tinyglobby';\nimport { cleanJsxText, isTReference, walk, type AstNode } from './analyze';\nimport type { ResolvedConfig } from './config';\n\nexport interface WrapEntry {\n file: string;\n line: number;\n text: string;\n kind: 'text' | 'attribute';\n attribute?: string;\n}\n\nexport interface WrapSkip {\n file: string;\n line: number;\n text: string;\n reason: string;\n}\n\n// a file wrap could rewrite but will not, because the rewrite would not compile\nexport interface WrapBlocked {\n file: string;\n texts: number;\n client: boolean;\n}\n\nexport interface WrapResult {\n files: number;\n changed: string[];\n wrapped: WrapEntry[];\n skipped: WrapSkip[];\n blocked: WrapBlocked[];\n}\n\nexport interface WrapOptions {\n write?: boolean;\n}\n\n// user-visible string attributes worth translating; everything else stays code\nconst WRAP_ATTRS = new Set(['title', 'alt', 'placeholder', 'aria-label']);\n\n// their content is code or preformatted output, never interface copy\nconst CODE_TAGS = new Set(['code', 'pre', 'kbd', 'samp', 'var']);\n\nconst T_NAMES: ReadonlySet<string> = new Set(['t']);\nconst LETTER = /\\p{L}/u;\nconst WHITESPACE = /\\s/;\n\n// onboarding codemod: errs on skipping, never on inventing (ambiguous goes to the report)\nexport async function wrapProject(\n cfg: ResolvedConfig,\n options: WrapOptions = {},\n): Promise<WrapResult> {\n const files = (\n await glob(cfg.include, { cwd: cfg.root, ignore: cfg.exclude, absolute: true })\n ).filter((file) => /\\.[jt]sx$/.test(file));\n\n const result: WrapResult = {\n files: files.length,\n changed: [],\n wrapped: [],\n skipped: [],\n blocked: [],\n };\n\n for (const file of files) {\n const code = readFileSync(file, 'utf8');\n const label = relative(cfg.root, file).replaceAll('\\\\', '/');\n const out = wrapCode(code, label);\n result.wrapped.push(...out.wrapped);\n result.skipped.push(...out.skipped);\n if (out.code === undefined) continue;\n result.changed.push(label);\n // writing a t call into a file with no t is how wrap left 32 files uncompilable\n if (!out.hasT) {\n result.blocked.push({ file: label, texts: out.wrapped.length, client: out.client });\n continue;\n }\n if (options.write) writeFileSync(file, out.code);\n }\n return result;\n}\n\nexport interface WrapCodeResult {\n code?: string;\n wrapped: WrapEntry[];\n skipped: WrapSkip[];\n hasT: boolean;\n client: boolean;\n}\n\nexport function wrapCode(code: string, file: string): WrapCodeResult {\n const wrapped: WrapEntry[] = [];\n const skipped: WrapSkip[] = [];\n\n let ast: AstNode;\n try {\n ast = parse(code, {\n sourceType: 'module',\n errorRecovery: true,\n plugins: ['typescript', 'jsx'],\n }).program as unknown as AstNode;\n } catch {\n return { wrapped, skipped, hasT: false, client: false }; // unparseable file: leave it alone\n }\n\n const hasT = declaresT(ast);\n const client = hasDirective(ast, 'use client');\n const s = new MagicString(code);\n const visited = new Set<AstNode>();\n let changed = false;\n\n walk(ast, (node) => {\n if (node.type !== 'JSXElement' && node.type !== 'JSXFragment') return;\n if (visited.has(node)) return;\n processElement(node);\n });\n\n return changed\n ? { code: s.toString(), wrapped, skipped, hasT, client }\n : { wrapped, skipped, hasT, client };\n\n function processElement(node: AstNode): void {\n visited.add(node);\n\n if (node.type === 'JSXElement') {\n const opening = node.openingElement as AstNode;\n const name = opening.name as AstNode;\n // <Trans> children and data-verbaly subtrees are already message-managed\n if (name.type === 'JSXIdentifier' && name.name === 'Trans') return markSubtree(node);\n if (hasVerbalyAttr(opening)) return markSubtree(node);\n if (name.type === 'JSXIdentifier' && CODE_TAGS.has(name.name as string)) {\n return markSubtree(node);\n }\n wrapAttributes(opening);\n }\n\n const children = (node.children as AstNode[] | undefined) ?? [];\n const hasElementChild = children.some(\n (c) => c.type === 'JSXElement' || c.type === 'JSXFragment',\n );\n const hasText = children.some(\n (c) =>\n (c.type === 'JSXText' && LETTER.test(c.value as string)) ||\n (c.type === 'JSXExpressionContainer' &&\n (c.expression as AstNode).type === 'StringLiteral' &&\n LETTER.test((c.expression as AstNode).value as string)),\n );\n\n if (hasElementChild && hasText) {\n // splitting the sentence into fragments would ship broken translations\n skip(node, snippet(children), 'mixed text and markup: wrap by hand or use <Trans>');\n return markSubtree(node);\n }\n if (hasText) {\n wrapSegment(node, children);\n return markSubtree(node);\n }\n for (const child of children) {\n if (child.type === 'JSXElement' || child.type === 'JSXFragment') processElement(child);\n }\n }\n\n function wrapSegment(parent: AstNode, children: AstNode[]): void {\n const meaningful = children.filter(\n (c) =>\n (c.type === 'JSXText' && (c.value as string).trim() !== '') ||\n (c.type === 'JSXExpressionContainer' &&\n (c.expression as AstNode).type !== 'JSXEmptyExpression'),\n );\n if (meaningful.length === 0) return;\n\n const first = meaningful[0]!;\n const last = meaningful[meaningful.length - 1]!;\n\n // a message opening with an interpolation is a fragment: the translator never sees the sentence\n if (first.type === 'JSXExpressionContainer' && meaningful.length > 1) {\n skip(parent, snippet(children), 'starts with an interpolation: wrap the sentence by hand');\n return;\n }\n\n let template = '';\n let report = '';\n for (let i = children.indexOf(first); i <= children.indexOf(last); i++) {\n const child = children[i]!;\n if (child.type === 'JSXText') {\n let value = cleanJsxText(child.value as string);\n if (child === first) value = value.trimStart();\n if (child === last) value = value.trimEnd();\n template += escapeTemplate(value);\n report += value;\n } else if (child.type === 'JSXExpressionContainer') {\n const expr = child.expression as AstNode;\n if (expr.type === 'JSXEmptyExpression') continue;\n if (usesT(expr)) {\n skip(parent, snippet(children), 'already uses t: finish it by hand');\n return;\n }\n if (containsJsx(expr)) {\n skip(\n parent,\n snippet(children),\n 'an expression renders markup: wrap by hand or use <Trans>',\n );\n markSubtree(child);\n return;\n }\n if (expr.type === 'StringLiteral') {\n template += escapeTemplate(expr.value as string);\n report += expr.value as string;\n } else {\n const source = code.slice(expr.start, expr.end);\n template += '${' + source + '}';\n report += '${' + source + '}';\n }\n } else {\n return; // spread children and friends: bail quietly\n }\n }\n if (!LETTER.test(report)) return;\n if (isIdentifierLike(report)) return;\n\n const start =\n first.type === 'JSXText' ? first.start + leadingWs(first.value as string) : first.start;\n const end = last.type === 'JSXText' ? last.end - trailingWs(last.value as string) : last.end;\n\n s.overwrite(start, end, '{t`' + template + '`}');\n changed = true;\n wrapped.push({ file, line: line(first), text: report, kind: 'text' });\n }\n\n function wrapAttributes(opening: AstNode): void {\n for (const attr of opening.attributes as AstNode[]) {\n if (attr.type !== 'JSXAttribute') continue;\n const name = attr.name as AstNode;\n if (name.type !== 'JSXIdentifier' || !WRAP_ATTRS.has(name.name as string)) continue;\n const value = attr.value as AstNode | null;\n if (value?.type !== 'StringLiteral') continue;\n const raw = value.value as string;\n if (!LETTER.test(raw) || isIdentifierLike(raw)) continue;\n s.overwrite(value.start, value.end, '{t`' + escapeTemplate(raw) + '`}');\n changed = true;\n wrapped.push({\n file,\n line: line(value),\n text: raw,\n kind: 'attribute',\n attribute: name.name as string,\n });\n }\n }\n\n function skip(node: AstNode, text: string, reason: string): void {\n skipped.push({ file, line: line(node), text, reason });\n }\n\n function snippet(children: AstNode[]): string {\n const start = children[0]?.start ?? 0;\n const end = children[children.length - 1]?.end ?? start;\n const text = code.slice(start, end).replace(/\\s+/g, ' ').trim();\n return text.length > 60 ? text.slice(0, 59) + '…' : text;\n }\n\n function markSubtree(node: AstNode): void {\n walk(node, (n) => {\n if (n.type === 'JSXElement' || n.type === 'JSXFragment') visited.add(n);\n });\n }\n}\n\n// one lowercase token with no space is a slug, a handle or a value, not a sentence someone wrote\nfunction isIdentifierLike(text: string): boolean {\n const trimmed = text.trim();\n if (WHITESPACE.test(trimmed)) return false;\n const first = [...trimmed].find((char) => LETTER.test(char));\n return first !== undefined && first !== first.toUpperCase();\n}\n\n// a directive is the only way a file states which side it renders on\nfunction hasDirective(program: AstNode, value: string): boolean {\n const directives = (program.directives as AstNode[] | undefined) ?? [];\n return directives.some((d) => ((d.value as AstNode | undefined)?.value as string) === value);\n}\n\n// a t call written where nothing binds t does not compile, so wrap has to know before it writes\nfunction declaresT(program: AstNode): boolean {\n let found = false;\n walk(program, (node) => {\n if (found) return;\n if (node.type === 'ImportDeclaration') {\n for (const spec of node.specifiers as AstNode[]) {\n if (isTName((spec.local as AstNode | undefined)?.name)) found = true;\n }\n return;\n }\n if (node.type === 'VariableDeclarator' && bindsT(node.id as AstNode)) found = true;\n if (node.type === 'FunctionDeclaration' && isTName((node.id as AstNode | undefined)?.name)) {\n found = true;\n }\n const params = node.params as AstNode[] | undefined;\n if (params?.some((param) => bindsT(param))) found = true;\n });\n return found;\n}\n\nfunction bindsT(pattern: AstNode | undefined): boolean {\n if (!pattern) return false;\n if (pattern.type === 'Identifier') return isTName(pattern.name);\n if (pattern.type === 'AssignmentPattern') return bindsT(pattern.left as AstNode);\n if (pattern.type === 'ObjectPattern') {\n return (pattern.properties as AstNode[]).some((prop) =>\n prop.type === 'RestElement'\n ? bindsT(prop.argument as AstNode)\n : bindsT(prop.value as AstNode),\n );\n }\n if (pattern.type === 'ArrayPattern') {\n return (pattern.elements as (AstNode | null)[]).some((el) => bindsT(el ?? undefined));\n }\n return false;\n}\n\nfunction isTName(name: unknown): boolean {\n return typeof name === 'string' && T_NAMES.has(name);\n}\n\nfunction hasVerbalyAttr(opening: AstNode): boolean {\n return (opening.attributes as AstNode[]).some((attr) => {\n if (attr.type !== 'JSXAttribute') return false;\n const name = attr.name as AstNode;\n return name.type === 'JSXIdentifier' && (name.name as string).startsWith('data-verbaly');\n });\n}\n\n// a t`…` / t(...) / t.id anywhere in the expression means a human already started here\nfunction usesT(node: AstNode): boolean {\n let found = false;\n walk(node, (n) => {\n if (n.type === 'TaggedTemplateExpression' && isTReference(n.tag as AstNode, T_NAMES)) {\n found = true;\n }\n if (n.type === 'CallExpression' && isTReference(n.callee as AstNode, T_NAMES)) found = true;\n });\n return found;\n}\n\nfunction containsJsx(node: AstNode): boolean {\n let found = false;\n walk(node, (n) => {\n if (n.type === 'JSXElement' || n.type === 'JSXFragment') found = true;\n });\n return found;\n}\n\n// literal text run → template-literal-safe\nfunction escapeTemplate(text: string): string {\n return text.replace(/[\\\\`]/g, '\\\\$&').replace(/\\$\\{/g, '\\\\${');\n}\n\nfunction leadingWs(text: string): number {\n return text.length - text.trimStart().length;\n}\n\nfunction trailingWs(text: string): number {\n return text.length - text.trimEnd().length;\n}\n\nfunction line(node: AstNode): number {\n const loc = node.loc as { start?: { line?: number } } | undefined;\n return loc?.start?.line ?? 1;\n}\n","import { relative } from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { loadCatalogs, writeCatalog } from './catalog';\nimport {\n check,\n checkNextSteps,\n formatCheckResult,\n formatCheckWarnings,\n githubCheckAnnotations,\n} from './check';\nimport { writeDts } from './codegen';\nimport { loadConfig, type ResolvedConfig } from './config';\nimport { doctor, formatDoctorEntry } from './doctor';\nimport { exportCatalogs, importCatalogs, isMobileFormat, type ExportFormat } from './exchange';\nimport { collectOrigins, extractProject, shippedCatalogs } from './extract';\nimport { createDevReporter, formatFinding } from './findings';\nimport { init } from './init';\nimport { migrateCatalogs } from './migrate';\nimport { syncProject } from './project';\nimport { PSEUDO_LOCALE, pseudoCatalogs } from './pseudo';\nimport { formatRenderWarnings, renderSite } from './render';\nimport {\n acceptOutdated,\n clearDrafts,\n effectiveDrafts,\n loadState,\n outdatedTranslations,\n readState,\n recordTranslations,\n saveState,\n type State,\n type TranslationWrite,\n} from './state';\nimport { formatStatusResult, status } from './status';\nimport { counted, truncate } from './text';\nimport {\n formatTranslateFailures,\n mergeTranslations,\n resolveProvider,\n translateCatalogs,\n type TranslateProgress,\n} from './translate';\nimport { watchProject } from './watch';\nimport { wrapProject } from './wrap';\n\nconst HELP = `verbaly · i18n compiler\n\nUsage:\n verbaly init scaffold config + locale catalogs (detects your framework)\n verbaly doctor diagnose the setup (config, catalogs, plugin, types, keys)\n verbaly wrap find hardcoded JSX text and wrap it in t\\`…\\` (report; --write applies)\n verbaly migrate port catalogs from another i18n library (report; --write applies)\n verbaly extract scan sources, update catalogs and types\n verbaly typegen write the TypeScript types only (CI: run it before tsc)\n verbaly status translation coverage per locale, at a glance\n verbaly check verify translations are complete (CI)\n verbaly translate fill missing translations via a provider (default: claude)\n verbaly review [keys…] list translations awaiting review: machine drafts and outdated ones (--approve accepts them)\n verbaly export write translator files (XLIFF 2.0, CSV, gettext PO) or mobile resources (Android, iOS)\n verbaly import <files…> fill catalogs back from translated XLIFF/CSV/PO files\n verbaly pseudo generate a pseudo-locale catalog for i18n QA (default: en-XA)\n verbaly render pre-fill data-verbaly HTML per locale (SSG, kills the FOUC)\n\nOptions:\n --root <path> project root (default: cwd)\n --dir <path> catalogs directory (default: locales)\n --source <locale> source locale (default: en)\n --locales <csv> run on these locales only, the source always included (init: the ones to create)\n --prune drop keys no longer referenced (extract)\n --watch keep extracting as source files change (extract)\n --write apply the rewrites instead of only reporting (wrap, migrate)\n --plurals also merge _one/_other into one message with variants (migrate)\n --json machine-readable output (status)\n --drafts also fail on unreviewed machine translations (check)\n --outdated also fail on translations written for an older source text (check)\n --approve accept what review lists, drafts and outdated, or only the keys given (review)\n --reporter <name> failure format: text (default) or github annotations (check)\n --model <id> model override for the claude provider (translate)\n --dry-run list what would happen, write nothing (translate, import, extract)\n --format <f> export format: xliff (default), csv, po, android-xml or ios-strings (export)\n --out <path> export directory (export, default: verbaly-export)\n --missing export only untranslated entries (export)\n --overwrite replace existing translations on import (import)\n --draft mark what the files bring as drafts a person still has to review (import)\n --locale <id> pseudo-locale id (pseudo) / one locale only (review, import)\n --site <path> built site directory (render, default: dist)\n --attribute <name> base data attribute (render, default: data-verbaly)\n --base <path> subpath the site is served under, e.g. /app (render)\n --base-url <url> site origin, enables hreflang alternates (render)\n --sitemap emit sitemap-i18n.xml with per-locale alternates (render)\n --redirect send a visitor on the root to their mirror, pre-paint (render)\n --clean remove existing locale dirs before mirroring (render)\n\nConfig file: verbaly.config.{js,mjs,ts,mts,json} at root (flags win).\nThe claude provider needs @anthropic-ai/sdk installed and ANTHROPIC_API_KEY set.\n`;\n\nexport async function runCli(args: string[] = process.argv.slice(2)): Promise<void> {\n const { positionals, values } = parseArgs({\n args,\n allowPositionals: true,\n options: {\n root: { type: 'string' },\n dir: { type: 'string' },\n source: { type: 'string' },\n locales: { type: 'string' },\n prune: { type: 'boolean' },\n watch: { type: 'boolean' },\n write: { type: 'boolean' },\n json: { type: 'boolean' },\n drafts: { type: 'boolean' },\n outdated: { type: 'boolean' },\n draft: { type: 'boolean' },\n approve: { type: 'boolean' },\n reporter: { type: 'string' },\n model: { type: 'string' },\n locale: { type: 'string' },\n site: { type: 'string' },\n attribute: { type: 'string' },\n base: { type: 'string' },\n 'base-url': { type: 'string' },\n redirect: { type: 'boolean' },\n sitemap: { type: 'boolean' },\n clean: { type: 'boolean' },\n 'dry-run': { type: 'boolean' },\n plurals: { type: 'boolean' },\n format: { type: 'string' },\n out: { type: 'string' },\n missing: { type: 'boolean' },\n overwrite: { type: 'boolean' },\n help: { type: 'boolean', short: 'h' },\n },\n });\n\n const command = positionals[0];\n // asking for help is not a usage error, even with no command: only bare `verbaly` is\n if (values.help || !command) {\n console.log(HELP);\n process.exitCode = values.help ? 0 : 1;\n return;\n }\n\n if (rejectStrayFlags(command, values)) return;\n\n if (command === 'init') {\n const result = await init({\n root: values.root,\n dir: values.dir,\n sourceLocale: values.source,\n locales: csv(values.locales),\n });\n if (result.created.length) console.log(`[verbaly] created: ${result.created.join(', ')}`);\n if (result.skipped.length) console.log(` kept (already there): ${result.skipped.join(', ')}`);\n for (const { from, to } of result.renamed) {\n console.log(` wrote ${to} for ${from}, since a locale tag takes a hyphen`);\n }\n for (const locale of result.refused) {\n console.warn(` left out \"${locale}\": it is not a locale tag, use one like es or pt-BR`);\n }\n if (result.host) console.log(` detected: ${result.host}`);\n console.log(\n [' next steps:', ...result.next.map((step, i) => ` ${i + 1}. ${step}`)].join('\\n'),\n );\n return;\n }\n\n const cfg = await loadConfig(values.root ?? process.cwd(), {\n dir: values.dir,\n sourceLocale: values.source,\n locales: csv(values.locales),\n });\n\n if (command === 'doctor') {\n const result = await doctor(cfg);\n console.log(`[verbaly] doctor: ${counted(result.entries.length, 'check')}`);\n for (const entry of result.entries) {\n const line = formatDoctorEntry(entry);\n if (entry.level === 'error') console.error(line);\n else if (entry.level === 'warn') console.warn(line);\n else console.log(line);\n }\n if (result.ok) {\n console.log('[verbaly] setup looks healthy ✓');\n } else {\n console.error('[verbaly] doctor found problems');\n process.exitCode = 1;\n }\n return;\n }\n\n if (command === 'extract') {\n const dryRun = values['dry-run'];\n if (values.watch && (dryRun || values.prune)) {\n console.error(\n '[verbaly] --watch runs alone: prune is a deliberate one-shot action and dry-run writes nothing',\n );\n process.exitCode = 1;\n return;\n }\n\n // a watch run says each warning once, and again only after it went away and came back\n const reporter = values.watch\n ? createDevReporter(cfg.root, (line) => console.warn(` ${line}`))\n : undefined;\n\n async function runExtract(): Promise<void> {\n const result = await syncProject(cfg, { prune: values.prune, dryRun });\n if (result.pruneBlocked) {\n const unread = result.registry.parseErrors().length;\n console.warn(\n ` prune skipped: an unparsed file may read any key (${counted(unread, 'file')} below), so it waits until every file parses`,\n );\n }\n for (const [locale, keys] of Object.entries(result.pruned)) {\n console.log(\n dryRun\n ? ` ${locale}: would prune ${keys.length}: ${keys.join(', ')}`\n : ` ${locale}: -${keys.length} pruned`,\n );\n }\n const total = result.registry.messages().size;\n console.log(\n `[verbaly] ${counted(total, 'message')} · locales: ${cfg.locales.join(', ')}${dryRun ? ' (dry run, nothing written)' : ''}`,\n );\n for (const [locale, keys] of Object.entries(result.added)) {\n console.log(` ${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length}`}`);\n }\n // news either way: an edit made in the code, or one the code undid in the catalog\n const warnings = result.findings.filter((finding) => {\n if (finding.kind !== 'replaced') return true;\n console.log(` ${formatFinding(finding, cfg.root)}`);\n return false;\n });\n if (reporter) reporter.report('extract', warnings);\n else for (const finding of warnings) console.warn(` ${formatFinding(finding, cfg.root)}`);\n if (result.stateProblem) {\n console.warn(\n ` ${result.stateProblem}, so drafts and outdated translations were not updated`,\n );\n }\n }\n\n await runExtract();\n if (values.watch) {\n watchProject(cfg, runExtract);\n console.log('[verbaly] watching for source changes (ctrl+c to stop)');\n }\n return;\n }\n\n if (command === 'typegen') {\n const registry = await extractProject(cfg);\n // the types describe the text that ships, the code's text wherever the code owns one\n const source = shippedCatalogs(cfg, loadCatalogs(cfg), registry)[cfg.sourceLocale] ?? {};\n const written = writeDts(cfg, source);\n if (!written) {\n console.log('[verbaly] no types written: dts is false in your verbaly config');\n return;\n }\n const where = relative(cfg.root, written.file).replaceAll('\\\\', '/');\n const how = written.changed ? 'written to' : 'up to date in';\n console.log(\n `[verbaly] types ${how} ${where} (${counted(Object.keys(source).length, 'message')})`,\n );\n return;\n }\n\n if (command === 'migrate') {\n const result = migrateCatalogs(cfg, { write: values.write, plurals: values.plurals });\n const from = result.detected.length ? result.detected.join(', ') : 'no known i18n library';\n const changes = result.braces.length + result.plurals.length;\n if (changes === 0 && result.skipped.length === 0) {\n console.log(`[verbaly] catalogs need nothing (${from}) ✓`);\n return;\n }\n const verb = values.write ? 'ported' : 'would port';\n const note = values.write ? '' : ' (report only, use --write to apply)';\n console.log(`[verbaly] ${verb} ${counted(changes, 'message')} from ${from}${note}`);\n for (const entry of result.braces) {\n console.log(` ${entry.locale} ${entry.key} ${entry.before} → ${entry.after}`);\n }\n for (const entry of result.plurals) {\n console.log(` ${entry.locale} ${entry.key} ${entry.from.join(' + ')} → ${entry.after}`);\n }\n if (!values.plurals && changes > 0) {\n console.log(' --plurals also merges _one/_other into one message with variants');\n }\n if (result.skipped.length > 0) {\n console.log(' needs a human:');\n for (const entry of result.skipped) {\n console.log(` ${entry.locale} ${entry.key} ${entry.reason}`);\n }\n }\n if (values.write) console.log(' next: run verbaly check');\n return;\n }\n\n if (command === 'wrap') {\n const result = await wrapProject(cfg, { write: values.write });\n if (result.wrapped.length === 0 && result.skipped.length === 0) {\n console.log(`[verbaly] nothing to wrap (${counted(result.files, 'file')} scanned) ✓`);\n return;\n }\n const blocked = new Set(result.blocked.map((entry) => entry.file));\n const done = result.changed.filter((file) => !blocked.has(file));\n const texts = result.wrapped.filter((entry) => !blocked.has(entry.file));\n const verb = values.write ? 'wrapped' : 'would wrap';\n const note = values.write ? '' : ' (report only, use --write to apply)';\n const counts = values.write\n ? `${counted(texts.length, 'text')} in ${counted(done.length, 'file')}`\n : `${counted(result.wrapped.length, 'text')} in ${counted(result.changed.length, 'file')}`;\n console.log(`[verbaly] ${verb} ${counts}${note}`);\n for (const entry of values.write ? texts : result.wrapped) {\n const attr = entry.kind === 'attribute' ? `${entry.attribute} → ` : '';\n console.log(` ${entry.file}:${entry.line} ${attr}\"${entry.text}\"`);\n }\n if (result.skipped.length > 0) {\n console.log(' needs a human:');\n for (const entry of result.skipped) {\n console.log(` ${entry.file}:${entry.line} \"${entry.text}\" (${entry.reason})`);\n }\n }\n if (result.blocked.length > 0) {\n console.log(` nothing written in ${counted(result.blocked.length, 'file')} with no t in scope:`);\n for (const entry of result.blocked) {\n const how = entry.client\n ? '\"use client\", so const t = useT()'\n : 'no \"use client\": check which side renders it before you pick the binding';\n console.log(` ${entry.file} ${counted(entry.texts, 'text')}, ${how}`);\n }\n console.log(' next: add t there, run verbaly wrap --write again, then verbaly extract');\n } else if (values.write && done.length > 0) {\n console.log(' next: run verbaly extract');\n }\n return;\n }\n\n if (command === 'status') {\n const registry = await extractProject(cfg);\n const { state, problem } = readState(cfg);\n if (problem) {\n console.warn(`[verbaly] ${problem}, so drafts and outdated translations are not counted`);\n }\n const result = status(cfg, loadCatalogs(cfg), registry, state.drafts, state.fingerprints);\n console.log(values.json ? JSON.stringify(result) : formatStatusResult(result));\n return;\n }\n\n if (command === 'check') {\n const reporter = values.reporter ?? 'text';\n if (reporter !== 'text' && reporter !== 'github') {\n console.error(`[verbaly] unknown reporter \"${values.reporter}\", use text or github`);\n process.exitCode = 1;\n return;\n }\n const registry = await extractProject(cfg);\n const catalogs = loadCatalogs(cfg);\n const state = checkState(cfg, values.drafts === true || values.outdated === true);\n const result = check(cfg, catalogs, registry, state.fingerprints);\n // opt-in: unreviewed machine translations and outdated ones block the merge too\n const unreviewed = values.drafts ? effectiveDrafts(state.drafts, catalogs) : {};\n const outdated = values.outdated ? result.outdated : [];\n const gated = { outdatedFails: values.outdated === true };\n // the annotations carry both severities, so they print whether the gate passes or not\n if (reporter === 'github') {\n for (const line of githubCheckAnnotations(result, registry, cfg, gated)) {\n console.error(line);\n }\n } else {\n const warnings = formatCheckWarnings(result, cfg.root, gated);\n if (warnings) console.warn(`[verbaly] warnings (the gate still passes)\\n${warnings}`);\n }\n\n const awaiting = [\n ...Object.entries(unreviewed).map(\n ([locale, keys]) => ` [${locale}] ${keys.length} unreviewed: ${keys.join(', ')}`,\n ),\n ...byLocale(outdated).map(\n ([locale, keys]) => ` [${locale}] ${keys.length} outdated: ${keys.join(', ')}`,\n ),\n ];\n if (result.ok && awaiting.length === 0) {\n console.log('[verbaly] all translations complete ✓');\n return;\n }\n if (!result.ok) {\n const brokenCount = result.broken.filter((entry) => entry.severity === 'error').length;\n const report =\n reporter === 'github'\n ? `[verbaly] check failed: ${result.missing.length} missing, ${result.unknown.length} unknown, ${brokenCount} broken`\n : `[verbaly] check failed\\n${formatCheckResult(result, cfg.root)}`;\n console.error(`${report}\\n${checkNextSteps(result)}`);\n }\n // printed whether or not the gate failed too: a flag that fails the run names what it found\n if (awaiting.length > 0) {\n for (const line of awaiting) console.error(line);\n console.error(\n '[verbaly] check failed: translations awaiting review (run verbaly review, then --approve what holds)',\n );\n }\n process.exitCode = 1;\n return;\n }\n\n if (command === 'translate') {\n // a machine translation that lost its draft flag passes as reviewed: read the state first\n if (!values['dry-run']) loadState(cfg);\n const registry = await extractProject(cfg);\n // the provider reads the text that ships, which is the text its answer has to match\n const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });\n const provider = await resolveProvider(cfg, values.model);\n const result = await translateCatalogs(cfg, catalogs, provider, {\n locales: csv(values.locales),\n batchSize: cfg.translate.batchSize,\n concurrency: cfg.translate.concurrency,\n retries: cfg.translate.retries,\n dryRun: values['dry-run'],\n // dry-run never calls the provider, so it sends no origins either\n origins: values['dry-run'] ? undefined : await collectOrigins(cfg, registry),\n onProgress: values['dry-run'] ? undefined : reportProgress,\n });\n\n if (values['dry-run']) {\n const entries = Object.entries(result.pending);\n if (entries.length === 0) {\n console.log('[verbaly] nothing to translate ✓');\n return;\n }\n for (const [locale, keys] of entries) {\n console.log(` ${locale}: ${keys.length} missing: ${keys.join(', ')}`);\n }\n return;\n }\n\n // machine output is a draft until a human reviews it, stamped with the text it was made for\n const source = catalogs[cfg.sourceLocale] ?? {};\n const writes: TranslationWrite[] = [];\n for (const [locale, keys] of Object.entries(result.translated)) {\n const catalog = catalogs[locale] ?? {};\n const written = mergeTranslations(cfg, locale, catalog, keys);\n writes.push({\n locale,\n draft: true,\n entries: written.map((key) => ({ key, text: catalog[key]! })),\n });\n console.log(` ${locale}: +${written.length} translated (draft)`);\n const kept = keys.length - written.length;\n if (kept > 0) {\n console.log(` ${locale}: ${counted(kept, 'message')} kept as written while this ran`);\n }\n }\n if (writes.length > 0) recordTranslations(cfg, source, writes);\n for (const [locale, keys] of Object.entries(result.invalid)) {\n console.warn(\n ` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(', ')}`,\n );\n }\n for (const line of formatTranslateFailures(result.failed)) console.error(line);\n if (result.failed.length > 0) process.exitCode = 1;\n if (\n Object.keys(result.translated).length === 0 &&\n Object.keys(result.invalid).length === 0 &&\n result.failed.length === 0\n ) {\n console.log('[verbaly] nothing to translate ✓');\n }\n return;\n }\n\n if (command === 'review') {\n const registry = await extractProject(cfg);\n const catalogs = loadCatalogs(cfg);\n // outdated against the text that ships, the one status and check count it against\n const shipped = shippedCatalogs(cfg, catalogs, registry);\n const state = loadState(cfg);\n const only = new Set(positionals.slice(1));\n const wanted = ({ locale, key }: { locale: string; key: string }): boolean =>\n (!values.locale || locale === values.locale) && (only.size === 0 || only.has(key));\n const drafts = Object.entries(effectiveDrafts(state.drafts, catalogs))\n .flatMap(([locale, keys]) => keys.map((key) => ({ locale, key })))\n .filter(wanted);\n const outdated = outdatedTranslations(cfg, shipped, state.fingerprints).filter(wanted);\n\n if (drafts.length === 0 && outdated.length === 0) {\n console.log('[verbaly] nothing awaiting review ✓');\n return;\n }\n\n if (values.approve) {\n for (const [locale, keys] of byLocale(drafts)) {\n clearDrafts(state.drafts, locale, keys);\n console.log(` ${locale}: ${keys.length} approved`);\n }\n // a person read the old translation against the new source and kept it\n acceptOutdated(cfg, shipped, state.fingerprints, outdated);\n for (const [locale, keys] of byLocale(outdated)) {\n console.log(` ${locale}: ${keys.length} kept for the new source text`);\n }\n saveState(cfg, state);\n // a draft can be outdated as well, and it is still one translation reviewed\n const reviewed = new Set(\n [...drafts, ...outdated].map(({ locale, key }) => `${locale}:${key}`),\n );\n console.log(`[verbaly] ${counted(reviewed.size, 'translation')} marked reviewed ✓`);\n return;\n }\n\n // a key alone cannot be judged: each line shows the text that ships and its translation\n const source = shipped[cfg.sourceLocale] ?? {};\n const show = (locale: string, keys: string[]): void => {\n console.log(` ${locale}:`);\n for (const key of keys) {\n const translated = catalogs[locale]?.[key] ?? '';\n console.log(\n ` ${key}: \"${truncate(source[key] ?? '', 60)}\" → \"${truncate(translated, 60)}\"`,\n );\n }\n };\n if (drafts.length > 0) {\n console.log(\n `[verbaly] ${counted(drafts.length, 'machine translation')} awaiting review (--approve to accept)`,\n );\n for (const [locale, keys] of byLocale(drafts)) show(locale, keys);\n }\n if (outdated.length > 0) {\n console.log(\n `[verbaly] ${counted(outdated.length, 'translation')} written for an older source text (update them, or --approve keeps them)`,\n );\n for (const [locale, keys] of byLocale(outdated)) show(locale, keys);\n }\n return;\n }\n\n if (command === 'export') {\n const format = (values.format ?? 'xliff') as ExportFormat;\n if (!['xliff', 'csv', 'po', 'android-xml', 'ios-strings'].includes(format)) {\n console.error(\n `[verbaly] unknown format \"${values.format}\", use xliff, csv, po, android-xml or ios-strings`,\n );\n process.exitCode = 1;\n return;\n }\n if (values.missing && isMobileFormat(format)) {\n console.error(\n `[verbaly] --missing is for translator formats (xliff, csv): ${format} already skips untranslated keys so the app falls back to the source locale`,\n );\n process.exitCode = 1;\n return;\n }\n const registry = await extractProject(cfg);\n // a translator gets the text that ships, never a catalog the code has since moved past\n const shipped = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });\n const result = exportCatalogs(cfg, shipped, {\n locales: csv(values.locales),\n format,\n out: values.out,\n missing: values.missing,\n // mobile formats are delivery-only: no translator reads where a text lives\n origins: isMobileFormat(format) ? undefined : await collectOrigins(cfg, registry),\n });\n if (result.files.length === 0) {\n console.log('[verbaly] no target locales to export (add locales to your config)');\n return;\n }\n const note = isMobileFormat(result.format) ? 'untranslated skipped' : 'untranslated';\n console.log(\n `[verbaly] exported ${counted(result.files.length, 'locale')} (${result.format}) → ${result.dir}`,\n );\n for (const file of result.files) {\n console.log(\n ` ${file.locale}: ${counted(file.total, 'message')} (${file.untranslated} ${note}) → ${file.path}`,\n );\n }\n return;\n }\n\n if (command === 'import') {\n const files = positionals.slice(1);\n if (files.length === 0) {\n console.error(\n '[verbaly] import needs at least one file: verbaly import verbaly-export/es.xlf',\n );\n process.exitCode = 1;\n return;\n }\n // the draft flags are written after the catalogs: an unreadable state writes neither\n if (!values['dry-run']) loadState(cfg);\n const registry = await extractProject(cfg);\n // checked against the text that ships, like check reads every translation\n const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });\n const result = importCatalogs(cfg, catalogs, files, {\n locale: values.locale,\n overwrite: values.overwrite,\n dryRun: values['dry-run'],\n });\n for (const { file, from, to } of result.mapped) {\n console.log(` ${file}: \"${from}\" read as ${to}`);\n }\n // a warning and exit 1, like a batch translate could not land: the file is skipped, not guessed\n for (const { file, locale, reason } of result.unmatched) {\n if (reason === 'undeclared') {\n console.warn(\n ` ${file}: \"${locale}\" is not one of this project's locales (${cfg.locales.join(', ')}), so nothing was imported from it`,\n );\n console.warn(\n ` fix: add ${locale} to locales in your verbaly config, or pass --locale with one of them`,\n );\n } else {\n console.warn(` ${file}: \"${locale}\" is not a locale tag, so nothing was imported from it`);\n console.warn(' fix: pass --locale with the tag it stands for, like pt-BR');\n }\n process.exitCode = 1;\n }\n // a person's file clears the draft flag unless --draft, stamped with the source it carried\n const writes: TranslationWrite[] = [];\n for (const [locale, keys] of Object.entries(result.imported)) {\n if (!values['dry-run']) {\n const catalog = catalogs[locale] ?? {};\n writeCatalog(cfg, locale, catalog);\n const seen = result.sources[locale] ?? {};\n const entries = keys.map((key) => ({ key, text: catalog[key]!, source: seen[key] }));\n writes.push({ locale, entries, draft: values.draft === true });\n }\n const verb = values['dry-run'] ? 'would import' : 'imported';\n console.log(` ${locale}: +${keys.length} ${verb}${values.draft ? ' (draft)' : ''}`);\n }\n if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);\n for (const [locale, keys] of Object.entries(result.skipped)) {\n console.log(\n ` ${locale}: ${keys.length} already translated, kept (use --overwrite to replace)`,\n );\n }\n for (const [locale, keys] of Object.entries(result.rejected)) {\n console.warn(\n ` ${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(', ')}`,\n );\n }\n for (const [locale, keys] of Object.entries(result.unknown)) {\n console.warn(\n ` ${locale}: ${counted(keys.length, 'unknown key')} ignored (not in the source catalog): ${keys.join(', ')}`,\n );\n }\n if (Object.keys(result.imported).length === 0 && result.unmatched.length === 0) {\n console.log('[verbaly] nothing to import ✓');\n }\n return;\n }\n\n if (command === 'render') {\n const result = await renderSite(cfg, {\n site: values.site,\n locales: csv(values.locales),\n attribute: values.attribute,\n base: values.base,\n baseUrl: values['base-url'],\n sitemap: values.sitemap,\n redirect: values.redirect,\n clean: values.clean,\n });\n console.log(\n `[verbaly] ${counted(result.files, 'page')} × ${counted(result.locales.length, 'locale')} (${result.locales.join(', ')})`,\n );\n for (const line of formatRenderWarnings(result, cfg.sourceLocale)) console.warn(line);\n return;\n }\n\n if (command === 'pseudo') {\n // the text that ships is the one QA has to see stretched, never a catalog the code moved past\n const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), await extractProject(cfg), {\n newKeys: false,\n });\n const locale = values.locale ?? PSEUDO_LOCALE;\n const keys = pseudoCatalogs(cfg, catalogs, locale);\n writeCatalog(cfg, locale, catalogs[locale] ?? {});\n console.log(`[verbaly] ${counted(keys.length, 'message')} pseudo-localized → ${locale}`);\n return;\n }\n\n console.error(`[verbaly] unknown command \"${command}\"\\n${HELP}`);\n process.exitCode = 1;\n}\n\n// \"es, pt\" is how a person types a list: a space must not become part of a locale\nfunction csv(value: string | undefined): string[] | undefined {\n return value\n ?.split(',')\n .map((item) => item.trim())\n .filter(Boolean);\n}\n\n// a translate run is minutes of network: say what landed as it lands, never only at the end\nfunction reportProgress(progress: TranslateProgress): void {\n const head = ` ${progress.locale} ${progress.batch}/${progress.batches}`;\n if (progress.error) console.warn(`${head}: failed (${progress.error}), continuing`);\n else console.log(`${head}: ${counted(progress.keys, 'message')}`);\n}\n\n// every compiler error already opens with [verbaly]: prefix only what does not\nexport function formatCliError(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n return message.startsWith('[verbaly]') ? message : `[verbaly] ${message}`;\n}\n\n// check reads the state for its warnings, and it only has to be readable when a flag gates on it\nfunction checkState(cfg: ResolvedConfig, gating: boolean): State {\n if (gating) return loadState(cfg);\n const { state, problem } = readState(cfg);\n if (problem) console.warn(`[verbaly] ${problem}, so outdated translations are not reported`);\n return state;\n}\n\nfunction byLocale(entries: { locale: string; key: string }[]): [string, string[]][] {\n const out = new Map<string, string[]>();\n for (const { locale, key } of entries) {\n const keys = out.get(locale);\n if (keys) keys.push(key);\n else out.set(locale, [key]);\n }\n return [...out];\n}\n\n// flags shared by every command (config overrides)\nconst COMMON_FLAGS = new Set(['root', 'dir', 'source', 'locales', 'help']);\nexport const COMMAND_FLAGS: Record<string, string[]> = {\n init: [],\n doctor: [],\n extract: ['prune', 'dry-run', 'watch'],\n typegen: [],\n wrap: ['write'],\n migrate: ['write', 'plurals'],\n status: ['json'],\n check: ['reporter', 'drafts', 'outdated'],\n translate: ['model', 'dry-run'],\n review: ['approve', 'locale'],\n export: ['format', 'out', 'missing'],\n import: ['locale', 'overwrite', 'dry-run', 'draft'],\n pseudo: ['locale'],\n render: ['site', 'attribute', 'base', 'base-url', 'sitemap', 'redirect', 'clean'],\n};\n\n// a flag another command owns must fail loudly, never be silently ignored\nfunction rejectStrayFlags(command: string, values: Record<string, unknown>): boolean {\n const own = COMMAND_FLAGS[command];\n if (!own) return false; // unknown command: reported later with the help text\n const allowed = new Set([...COMMON_FLAGS, ...own]);\n const stray = Object.keys(values).filter((k) => values[k] !== undefined && !allowed.has(k));\n if (stray.length === 0) return false;\n for (const flag of stray) {\n const hint = flag === 'locale' ? ' (did you mean --locales?)' : '';\n console.error(`[verbaly] --${flag} is not a \"${command}\" flag${hint}`);\n }\n process.exitCode = 1;\n return true;\n}\n"],"mappings":";;;;;;;;;;;AACA,SAAgB,gBAAgB,MAAc,UAAsC;CAClF,MAAM,QAAQ,UAAU,QAAQ,IAAI,KAAK;CACzC,OAAO,QAAQ,KAA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