Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
chore(skills): add working-with-translations
Elian Doran87592b75f916
diff --git a/.claude/skills/working-with-translations/SKILL.md b/.claude/skills/working-with-translations/SKILL.mdnew file mode 100644index 0000000000..3c0a845f93--- /dev/null+++ b/.claude/skills/working-with-translations/SKILL.md@@ -0,0 +1,143 @@+---+name: working-with-translations+description: Use when adding, finding, changing, reading or auditing a UI string in Trilium — "is there already a key for X?", "add a translation key", "what does <key> say?", "what does this button say in German?", "has this string been translated yet?", "which catalogue does this go in?", "any unused or misspelled keys?". Covers the three English catalogues (client / entry / server) and the routing rule that decides which one a key belongs to, and includes i18n.mjs to look a key up across all 39 locales, so neither the 226 KB catalogue nor a locale file ever has to be read or hand-edited. Writes English only. For deliberately filling in a lagging locale (Romanian is behind, bring a locale to 100%), use the translating-locales skill instead.+---++# Working with Trilium's English UI strings++Trilium's UI is localized with **i18next**. English is the source of truth and the only catalogue you edit by hand — the other ~38 locales belong to Weblate. This skill is the everyday case: you are building or changing a feature and need to add a string, find one that already exists, or check that nothing dangles.++Every mechanical step is [i18n.mjs](i18n.mjs).++```bash+S=.claude/skills/working-with-translations/i18n.mjs+node $S find "Cancel" # English text → catalogue + dotted key+node $S find totp_enroll --key # search key paths instead of values+node $S show about.channel # dump one section+node $S show delete_note.delete_note --locales # what the string says in every language+node $S add client dialog.my_thing "My text" # insert, preserving key order + formatting+node $S callers about.channel.nightly # where a key is referenced+node $S missing # keys used in code but absent from the catalogue+node $S unused # catalogue keys nothing references+```++**Never read a whole catalogue to answer a question.** `apps/client/src/translations/en/translation.json` is 226 KB / 4032 lines / 3384 keys across 304 top-level sections — reading it costs more than any question it answers. `find` and `show` exist so nothing has to.++**Never hand-edit the JSON either.** `add` writes through the file's own indent (2), EOL (LF) and trailing newline, and appends into the correct parent object. A round-trip is byte-identical, so a one-string change is a 3-line diff. A hand-edit gets the nesting or the trailing comma wrong; a naive `JSON.parse → stringify` at the wrong indent rewrites all 4032 lines.++## Reading a string in other languages++`show <key> --locales` prints the value in every locale that has it, then the locales that don't+and the ones whose value is byte-identical to English:++```+--- client: delete_note.delete_note+ en "Delete note"+ de "Notiz löschen"+ ro "Șterge notița"+ …+ 22/39 locales translated+ missing: az, bg, ca, el, en-GB, fa, fi, hr, hu, md, mr, nb-NO, nl, sl, sv, ur, vi+```++Use it to answer "what does this button say in German?", "has this been translated yet?", or+"why does the Romanian UI show that?". Identical-to-English is usually legitimate — a proper noun+(`hidden-subtree.llm-title` is "AI / LLM" nearly everywhere) or a word the language shares+(Italian `login.password` is "Password"). It works for all three catalogues.++**This tool never writes a non-English file.** `add` takes a *catalogue* (`client` / `entry` / `server`),+not a locale, so `add ro …` is rejected outright — there is no path by which it can touch a+Weblate-owned file. Editing a locale is the translating-locales skill's `merge`, and even then only+for a deliberate maintainer pass.++Changing an **English** string does not update the ~38 existing translations, which then read as+translations of text that no longer exists — `show --locales` makes that visible. Weblate flags them+for review on its next pull; you don't hand-edit them.++## Which catalogue does a key go in?++| Catalogue | File | Read by |+|---|---|---|+| `client` | `apps/client/src/translations/en/translation.json` | the browser UI — everything after login |+| `entry` | `apps/client/src/translations/en/entry.json` | **only** the setup wizard, login and password-reset pages |+| `server` | `apps/server/src/assets/translations/en/server.json` | `apps/server`, the Electron main process, `packages/trilium-core`, and the standalone worker |++Getting this wrong is the most common mistake, and `add` warns when a key's section lives in a different catalogue than the one you named.++- **`entry` exists for weight.** The three pre-login pages call `initLocale(locale, "entry")` and read ~12 KB instead of the app's 226 KB — which matters because the wizard reloads the catalogue every time the user picks a language. Put a `login.*` / `set_password.*` / `setup.*` key in `client` and the pre-login pages simply will not find it.+- **The app loads both** `client` and `entry` with `fallbackNS: "entry"`, so a call site writes `t("login.password")` without caring which file holds it. Only the *new* key has to go in the right place.+- **`server.json` is misnamed** — it is the catalogue for every runtime outside the browser UI. A `t()` call added to `trilium-core` resolves in server, desktop **and** standalone with no extra work (`apps/standalone/vite.config.mts` copies `apps/server/src/assets/**` and the worker loads it with `ns: "server"`). Don't assume a core string needs a fallback to work in the browser build.++Client code imports `t` from `../services/i18n`; server, desktop and core import it from `i18next` directly.++## Adding a string++```bash+node $S find "Save changes" # 1. does it already exist?+node $S add client dialog.my_thing "Save changes"+```++`add` prints two advisories worth reading:++- **Duplicate text** — every existing key carrying that exact English string. Reuse one if it means the same thing; each new key costs ~38 locales a translation. But *do* add a separate key when the same English word differs by context — a language that inflects will need both.+- **Catalogue routing** — when the key's section doesn't exist in the catalogue you named but does in another.++`add` refuses to overwrite an existing key (`--force` to override) and refuses to nest under one that is already a string.++Then use it: `t("dialog.my_thing")`. Only `en/` changes — Weblate carries the string to the other locales, and you should **not** hand-edit the other ~38 locale files.++### Pluralization++i18next pluralizes only when the translation has `_one` / `_other` keys **and** the call site passes `{ count }`. Add both forms and call `t("key", { count })`:++```bash+node $S add client space_usage.my_notes_one "{{count}} note"+node $S add client space_usage.my_notes_other "{{count}} notes"+```++There is no base key — `find --key space_usage.my_notes` shows only the suffixed pair, and that is correct. Converting an *existing* single-form English key to a plural pair removes the base key, so every other locale falls back to English until Weblate migrates them; call that out in the PR.++### Interpolation++`{{var}}` normally, `{{- var}}` to skip HTML-escaping when the value contains quotes. When a string embeds **components** whose order varies by language (links, note references), use `<Trans>` from `react-i18next` rather than `t()`, so translators can reorder them.++## Auditing++`missing` is the one that catches real bugs — a `t("…")` whose key is in no catalogue renders the raw key to the user:++```bash+node $S missing # currently 1 known hit, see below+node $S unused # advisory only+```++`unused` is **advisory, not a delete list**. It already suppresses three legitimate patterns (plural bases, dynamic prefixes, keys travelling as bare strings), but ~27 call sites build a key from a variable with no visible prefix, and keys can also be referenced from a test fixture or a docs note. Run `callers <key>` and confirm before deleting anything.++## What the scanner does and doesn't see++`missing` / `unused` / `callers` scan `apps/client/src` (against `client` + `entry`) and `apps/server/src`, `apps/desktop/src`, `packages/trilium-core/src` (against `server`). Within those:++| Pattern | Handled |+|---|---|+| `t("some.key")`, `<Trans i18nKey="some.key">` | resolved exactly |+| `t("pdf.annotations", { count })` → `_one` / `_other` | plural bases bridged in both directions |+| ``t(`about.channel.${channel}`)`` | static prefix keeps every key under it live |+| `"security-dialog.lan-access"` passed to a helper that calls `t()` | counted as a soft reference |+| `t(labelKey)` — a bare variable | **invisible**; reported as a caveat count |++**`packages/ckeditor5` is deliberately not scanned.** Its plugins pass the English text itself to CKEditor's `t()`, so the argument is a message, not a key — scanning it would produce nothing but noise. That mechanism has its own rules (a `text-editor.ck` entry keyed by the slug of the English text) and `apps/client/src/services/i18n.spec.ts` already enforces it in **both** directions, so a missing entry and a stale one both fail. See the CKEditor section of `CLAUDE.md`; don't reimplement that check here.++## Validation++```bash+pnpm --filter client test src/services/i18n.spec.ts+```++That is the repo's only translation test: valid JSON, no duplicate keys, plus the CKEditor message-catalogue check. There is **no** locale-parity test and **no** typed i18next, so a missing key fails at runtime as a raw key on screen, not at build time — which is exactly why `missing` is worth running before you finish.++## Known outstanding issue++`packages/trilium-core/src/services/hidden_subtree_launcherbar.ts:136` calls `t("hidden-subtree.llm-chat-title")`, which does not exist in `server.json` (the nearby keys are `llm-title`, `llm-chat-history-title`, `sidebar-chat-title`). Low impact — that launcher entry is `enforceDeleted: true`, so the note is removed rather than displayed. Fix it or delete the dead entry if you are in that file anyway.++## Related++- **translating-locales** — filling in a lagging non-English locale: measuring coverage, exporting work lists, placeholder validation, plural categories per locale, and how Weblate sync works. Use that skill, not this one, when the task is "bring `<locale>` to 100%".diff --git a/.claude/skills/working-with-translations/i18n.mjs b/.claude/skills/working-with-translations/i18n.mjsnew file mode 100644index 0000000000..1b59171e06--- /dev/null+++ b/.claude/skills/working-with-translations/i18n.mjs@@ -0,0 +1,416 @@+#!/usr/bin/env node+/**+ * UI-string workbench for Trilium's i18next catalogs. Reads all 39 locales, writes English only.+ *+ * node .claude/skills/working-with-translations/i18n.mjs <command> [args]+ *+ * find <text> [--key] [--all] locate a string by its English text (or by key path)+ * show <section> [--locales] dump one section; --locales shows every language's value+ * add <catalog> <key> <text> add an English string, preserving key order + formatting+ * callers <key> where a key is referenced in code+ * missing keys used in code but absent from every catalog (typos)+ * unused catalog keys no call site references+ *+ * catalog: client | entry | server+ * add opts: --force (overwrite an existing key instead of refusing)+ *+ * The client catalog is 226 KB / 3400 keys, so reading it to answer a question costs more+ * than the question is worth. `find` and `show` exist so nothing ever has to. `add` exists+ * because hand-editing needs the right file, the right nesting and no reformatting.+ *+ * This tool only ever writes `en/` — the other ~38 locales belong to Weblate. To fill a+ * lagging locale, use the translating-locales skill instead.+ */+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++const SKILL_DIR = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.resolve(SKILL_DIR, "../../..");++/**+ * `scan` is the set of source trees whose `t()` calls resolve against this catalog.+ * `apps/client/src` resolves against client *and* entry, because the app loads both+ * namespaces with `fallbackNS: "entry"` — a call site writes `t("login.password")`+ * without caring which file holds it.+ *+ * `packages/ckeditor5` is deliberately absent: its plugins pass the English text itself+ * to CKEditor's `t()`, so its arguments are messages, not keys. `apps/client/src/services/i18n.spec.ts`+ * already enforces that mechanism in both directions.+ */+const CATALOGS = {+ client: {+ file: "apps/client/src/translations/en/translation.json",+ dir: "apps/client/src/translations",+ localeFile: (l) => `apps/client/src/translations/${l}/translation.json`,+ scan: ["apps/client/src"]+ },+ entry: {+ file: "apps/client/src/translations/en/entry.json",+ dir: "apps/client/src/translations",+ localeFile: (l) => `apps/client/src/translations/${l}/entry.json`,+ scan: ["apps/client/src"]+ },+ server: {+ file: "apps/server/src/assets/translations/en/server.json",+ dir: "apps/server/src/assets/translations",+ localeFile: (l) => `apps/server/src/assets/translations/${l}/server.json`,+ scan: ["apps/server/src", "apps/desktop/src", "packages/trilium-core/src"]+ }+};++const SOURCE_EXTENSIONS = new Set([".ts", ".tsx"]);+const SKIP_DIRECTORIES = new Set(["node_modules", "dist", "build", ".vite", "coverage"]);++/**+ * i18next resolves `t("pdf.annotations", { count })` to `pdf.annotations_one` / `_other`, so a+ * pluralized string has no base key at all. Both `missing` and `unused` have to bridge that gap+ * or every plural group in the catalog reads as broken in both directions.+ */+const PLURAL_SUFFIX = /_(zero|one|two|few|many|other)$/;++const [, , cmd, ...rest] = process.argv;+const flags = {};+const args = [];+for (const arg of rest) {+ if (arg.startsWith("--")) flags[arg.slice(2)] = true;+ else args.push(arg);+}++const COMMANDS = { find, show, add, callers, missing, unused };+const run = COMMANDS[cmd];+if (!run) {+ console.log(fs.readFileSync(fileURLToPath(import.meta.url), "utf8").split("*/")[0].split("/**")[1].replace(/^ \* ?/gm, ""));+ process.exit(cmd ? 1 : 0);+}+run(...args);++// ---------------------------------------------------------------- commands++function find(text) {+ if (!text) fail("usage: find <text> [--key] [--all]");+ const needle = text.toLowerCase();+ const limit = flags.all ? Infinity : 40;+ const hits = [];+ for (const [name, entries] of Object.entries(readCatalogs())) {+ for (const [key, value] of Object.entries(entries)) {+ const haystack = flags.key ? key : String(value);+ if (haystack.toLowerCase().includes(needle)) hits.push({ name, key, value });+ }+ }+ for (const hit of hits.slice(0, limit)) {+ console.log(`${hit.name.padEnd(6)} ${hit.key}\n ${JSON.stringify(hit.value)}`);+ }+ if (hits.length > limit) console.log(`\n… +${hits.length - limit} more (pass --all)`);+ console.log(`\n${hits.length} match(es) for ${JSON.stringify(text)} in ${flags.key ? "key paths" : "English values"}`);+ if (!flags.key && !hits.length) console.log("Nothing matched a value — retry with --key to search key paths.");+}++function show(section) {+ if (!section) fail("usage: show <section> [--locales]");+ let total = 0;+ for (const [name, entries] of Object.entries(readCatalogs())) {+ const under = Object.entries(entries).filter(([key]) => key === section || key.startsWith(`${section}.`));+ if (!under.length) continue;+ if (flags.locales) {+ for (const [key] of under) showAcrossLocales(name, key);+ } else {+ console.log(`--- ${name}: ${CATALOGS[name].file}`);+ for (const [key, value] of under) console.log(` ${key} = ${JSON.stringify(value)}`);+ }+ total += under.length;+ }+ if (!total) {+ const sections = new Set();+ for (const entries of Object.values(readCatalogs())) {+ for (const key of Object.keys(entries)) sections.add(key.split(".")[0]);+ }+ const near = [...sections].filter((s) => s.includes(section) || section.includes(s)).slice(0, 10);+ console.log(`no keys under "${section}"${near.length ? `\ndid you mean: ${near.join(", ")}` : ""}`);+ return;+ }+ console.log(`\n${total} string(s) under "${section}"`);+}++/** One key in every locale that has it, plus the list of locales that don't — "is this translated yet?". */+function showAcrossLocales(catalog, key) {+ const entry = CATALOGS[catalog];+ const english = flatten(JSON.parse(fs.readFileSync(path.join(ROOT, entry.file), "utf8")))[key];+ console.log(`--- ${catalog}: ${key}`);+ console.log(` ${"en".padEnd(7)} ${JSON.stringify(english)}`);++ const locales = listLocales(catalog);+ const absent = [];+ const untranslated = [];+ for (const locale of locales) {+ const file = path.join(ROOT, entry.localeFile(locale));+ if (!fs.existsSync(file)) { absent.push(locale); continue; }+ const value = flatten(JSON.parse(fs.readFileSync(file, "utf8")))[key];+ if (value === undefined) { absent.push(locale); continue; }+ console.log(` ${locale.padEnd(7)} ${JSON.stringify(value)}`);+ if (value === english) untranslated.push(locale);+ }+ const done = locales.length - absent.length;+ console.log(` ${done}/${locales.length} locales translated`);+ if (absent.length) console.log(` missing: ${absent.join(", ")}`);+ // Byte-identical to English: either a proper noun, or Weblate carrying the source string through.+ if (untranslated.length) console.log(` identical to English: ${untranslated.join(", ")}`);+ console.log();+}++function listLocales(catalog) {+ const dir = path.join(ROOT, CATALOGS[catalog].dir);+ return fs.readdirSync(dir, { withFileTypes: true })+ .filter((e) => e.isDirectory() && e.name !== "en")+ .map((e) => e.name)+ .sort();+}++function add(catalog, key, text) {+ if (!catalog || !key || text === undefined) fail('usage: add <client|entry|server> <dotted.key> "English text"');+ const entry = CATALOGS[catalog];+ if (!entry) fail(`unknown catalog "${catalog}" — use client, entry or server`);++ const catalogs = readCatalogs();+ const existing = catalogs[catalog][key];+ if (existing !== undefined && !flags.force) {+ fail(`${catalog}.${key} already exists: ${JSON.stringify(existing)}\nPass --force to overwrite it.`);+ }++ // A key can only nest under an object. `a.b.c` is impossible when `a.b` is already a string.+ for (const ancestor of ancestorsOf(key)) {+ if (typeof catalogs[catalog][ancestor] === "string") {+ fail(`cannot nest under "${ancestor}" — it is already a string in ${catalog}: ${JSON.stringify(catalogs[catalog][ancestor])}`);+ }+ }++ warnAboutCatalogChoice(catalog, key, catalogs);+ warnAboutDuplicateText(text, key, catalogs);++ const file = path.join(ROOT, entry.file);+ const raw = fs.readFileSync(file, "utf8");+ const parsed = JSON.parse(raw);+ setDeep(parsed, key, text);+ fs.writeFileSync(file, serializeLike(raw, parsed), "utf8");++ console.log(`${existing === undefined ? "added" : "updated"} ${key} in ${entry.file}`);+ console.log(` ${JSON.stringify(text)}`);+ console.log(`\nCall it with t(${JSON.stringify(key)}). Only en/ is edited — Weblate carries it to the other locales.`);+}++function callers(key) {+ if (!key) fail("usage: callers <key>");+ const trees = [...new Set(Object.values(CATALOGS).flatMap((c) => c.scan))];+ const usage = scanSources(trees);+ const literal = usage.literals.filter((u) => u.key === key);+ for (const u of literal) console.log(`${u.file}:${u.line} t("${u.key}")`);++ const seen = new Set(literal.map((u) => `${u.file}:${u.line}`));+ const bare = usage.quoted.filter((u) => u.key === key && !seen.has(`${u.file}:${u.line}`));+ for (const u of bare) console.log(`${u.file}:${u.line} "${u.key}" <- key travelling as data, not a direct t() call`);++ const prefixes = usage.prefixes.filter((p) => key.startsWith(p.prefix));+ for (const p of prefixes) console.log(`${p.file}:${p.line} t(\`${p.prefix}\${…}\`) <- could resolve to this key`);++ const parts = [`${literal.length} literal reference(s)`];+ if (bare.length) parts.push(`${bare.length} bare-string reference(s)`);+ if (prefixes.length) parts.push(`${prefixes.length} dynamic prefix(es) that could produce it`);+ console.log(`\n${parts.join(", ")}`);+ if (!literal.length && !bare.length && !prefixes.length) {+ console.log(`Nothing references "${key}". ${usage.opaque.length} opaque t(variable) call site(s) exist repo-wide, so confirm before deleting.`);+ }+}++function missing() {+ let total = 0;+ for (const { trees, names, keys, label } of scanGroups()) {+ const usage = scanSources(trees);+ const absent = usage.literals.filter((u) => !resolvesInKeyspace(u.key, keys));+ if (absent.length) {+ console.log(`--- ${label} (resolves against ${names.join(" + ")})`);+ for (const u of absent) console.log(` ${u.file}:${u.line} t("${u.key}")`);+ }+ total += absent.length;+ }+ console.log(`\n${total} key(s) used in code but absent from their catalog.`);+ if (total) console.log('Each is either a typo or a string never added — `find --key <fragment>` to check for a near-miss.');+}++function unused() {+ let total = 0;+ let opaqueTotal = 0;+ for (const { trees, keys, catalogOf, label } of scanGroups()) {+ const usage = scanSources(trees);+ const referenced = new Set([...usage.literals, ...usage.quoted].map((u) => u.key));+ const orphans = [...keys]+ // `pdf.annotations_one` is live when the code calls t("pdf.annotations", { count }).+ .filter((key) => !referenced.has(key) && !referenced.has(key.replace(PLURAL_SUFFIX, "")))+ .filter((key) => !usage.prefixes.some((p) => key.startsWith(p.prefix)));+ if (orphans.length) {+ console.log(`--- ${label}`);+ for (const key of orphans) console.log(` ${catalogOf.get(key)} ${key}`);+ }+ total += orphans.length;+ opaqueTotal += usage.opaque.length;+ }+ console.log(`\n${total} key(s) with no t() call, no bare-string mention and no matching dynamic prefix.`);+ console.log(`Not proof they are dead: ${opaqueTotal} t(variable) call site(s) build their key at runtime with`);+ console.log("no visible prefix. Run `callers <key>` and confirm before deleting anything.");+}++// ---------------------------------------------------------------- source scanning++/** The keyspace a `t()` call resolves against depends on which tree it lives in, not which catalog you have open. */+function scanGroups() {+ const catalogs = readCatalogs();+ const byTree = new Map();+ for (const [name, entry] of Object.entries(CATALOGS)) {+ for (const tree of entry.scan) byTree.set(tree, [...(byTree.get(tree) ?? []), name]);+ }+ // Trees sharing an identical catalog set form one group, so client+entry are checked together.+ const groups = new Map();+ for (const [tree, names] of byTree) {+ const id = names.slice().sort().join("+");+ groups.set(id, { names, trees: [...(groups.get(id)?.trees ?? []), tree] });+ }+ return [...groups.values()].map(({ names, trees }) => {+ const keys = new Set();+ const catalogOf = new Map();+ for (const name of names) {+ for (const key of Object.keys(catalogs[name])) {+ keys.add(key);+ catalogOf.set(key, name);+ }+ }+ return { trees, names, keys, catalogOf, label: trees.join(", ") };+ });+}++/** True when `key` names a string, or names a plural group whose suffixed forms exist. */+function resolvesInKeyspace(key, keys) {+ if (keys.has(key)) return true;+ for (const category of ["zero", "one", "two", "few", "many", "other"]) {+ if (keys.has(`${key}_${category}`)) return true;+ }+ return false;+}++function scanSources(trees) {+ const literals = [];+ const prefixes = [];+ const opaque = [];+ const quoted = [];+ for (const tree of trees) {+ for (const file of walk(path.join(ROOT, tree))) {+ const relative = path.relative(ROOT, file);+ const lines = fs.readFileSync(file, "utf8").split("\n");+ lines.forEach((text, index) => {+ const line = index + 1;+ // t("some.key") / t('some.key') — the everyday form.+ for (const m of text.matchAll(/\bt\(\s*["']([a-zA-Z0-9_.-]+)["']/g)) literals.push({ key: m[1], file: relative, line });+ // <Trans i18nKey="some.key"> — same keyspace, different syntax.+ for (const m of text.matchAll(/\bi18nKey=["']([a-zA-Z0-9_.-]+)["']/g)) literals.push({ key: m[1], file: relative, line });+ // t(`about.channel.${channel}`) — the static prefix still tells us which keys are live.+ for (const m of text.matchAll(/\bt\(\s*`([a-zA-Z0-9_.-]*)\$\{/g)) prefixes.push({ prefix: m[1], file: relative, line });+ // t(labelKey) — no prefix at all, so it can vouch for nothing. Counted, not resolved.+ for (const m of text.matchAll(/\bt\(\s*[a-zA-Z_$][\w$.]*\s*[,)]/g)) opaque.push({ file: relative, line, text: m[0] });+ // Any bare "some.key" literal. Keys routinely travel as data — stored in a config+ // table, passed to a helper that calls t() itself (registerToggleHandler), or held+ // in a `labelKey` field. Intersected with the catalog by the caller, so a string+ // that merely looks key-shaped vouches for nothing.+ for (const m of text.matchAll(/["'`]([a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)+)["'`]/g)) quoted.push({ key: m[1], file: relative, line });+ });+ }+ }+ return { literals, prefixes, opaque, quoted };+}++function* walk(dir) {+ if (!fs.existsSync(dir)) return;+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ if (entry.isDirectory()) {+ if (!SKIP_DIRECTORIES.has(entry.name)) yield* walk(path.join(dir, entry.name));+ } else if (SOURCE_EXTENSIONS.has(path.extname(entry.name))) {+ yield path.join(dir, entry.name);+ }+ }+}++// ---------------------------------------------------------------- helpers++function readCatalogs() {+ const out = {};+ for (const [name, entry] of Object.entries(CATALOGS)) {+ out[name] = flatten(JSON.parse(fs.readFileSync(path.join(ROOT, entry.file), "utf8")));+ }+ return out;+}++/** `setup.wizard.title` -> ["setup", "setup.wizard"] */+function ancestorsOf(key) {+ const parts = key.split(".");+ return parts.slice(0, -1).map((_, i) => parts.slice(0, i + 1).join("."));+}++/** The entry catalog holds exactly three sections; putting one of them in `client` breaks the pre-login pages. */+function warnAboutCatalogChoice(catalog, key, catalogs) {+ const section = key.split(".")[0];+ const homes = Object.keys(CATALOGS).filter((name) =>+ name !== catalog && Object.keys(catalogs[name]).some((k) => k.split(".")[0] === section)+ );+ const here = Object.keys(catalogs[catalog]).some((k) => k.split(".")[0] === section);+ if (!here && homes.length) {+ console.log(`note: section "${section}" does not exist in ${catalog} but does in ${homes.join(", ")}.`);+ console.log(` The setup wizard, login and password-reset pages load only "entry"; everything else loads "client".`);+ console.log(` Server, Electron main and trilium-core read "server".\n`);+ }+}++function warnAboutDuplicateText(text, key, catalogs) {+ const normalized = text.trim().toLowerCase();+ const twins = [];+ for (const [name, entries] of Object.entries(catalogs)) {+ for (const [k, v] of Object.entries(entries)) {+ if (k !== key && typeof v === "string" && v.trim().toLowerCase() === normalized) twins.push(`${name} ${k}`);+ }+ }+ if (twins.length) {+ console.log(`note: ${twins.length} existing key(s) already carry this exact English text:`);+ for (const t of twins.slice(0, 8)) console.log(` ${t}`);+ if (twins.length > 8) console.log(` … +${twins.length - 8} more`);+ console.log(` Reuse one if it means the same thing — every new key costs ~38 locales a translation.\n`);+ }+}++/** Writes `value` with the indent, EOL and trailing newline the original file already uses. */+function serializeLike(raw, value) {+ const eol = raw.includes("\r\n") ? "\r\n" : "\n";+ const indent = raw.match(/^[^\n]*\n(\s+)"/)?.[1].replace("\r", "").length ?? 2;+ let out = JSON.stringify(value, null, indent);+ if (eol === "\r\n") out = out.replace(/\n/g, "\r\n");+ return out + (/\r?\n$/.test(raw) ? eol : "");+}++function flatten(o, p = "", out = {}) {+ for (const k of Object.keys(o)) {+ const key = p ? `${p}.${k}` : k;+ if (o[k] && typeof o[k] === "object" && !Array.isArray(o[k])) flatten(o[k], key, out);+ else out[key] = o[k];+ }+ return out;+}++function setDeep(obj, dotted, val) {+ const ks = dotted.split(".");+ let o = obj;+ for (const k of ks.slice(0, -1)) {+ if (typeof o[k] !== "object" || o[k] === null) o[k] = {};+ o = o[k];+ }+ o[ks[ks.length - 1]] = val;+}++function fail(message) {+ console.error(message);+ process.exit(1);+}