/** * Tests of the message catalog: the `t` helper (lookup, interpolation, * missing keys), the one date format, and a scan of the frontend source that every literal key * passed to `t` exists in `en.json`. */ import { readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import en from "../../src/i18n/en.json"; import { formatDate, formatDateTime, hasMessage, t } from "../../src/i18n"; /** Root of the frontend source tree. */ const SRC = join(import.meta.dirname, "..", "..", "src"); /** * Lists the `.ts` and `.vue` files below a directory. * * @param dir - the directory. */ function sourceFiles(dir: string): string[] { return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { const path = join(dir, entry.name); if (entry.isDirectory()) { return sourceFiles(path); } return /\.(ts|vue)$/.test(entry.name) ? [path] : []; }); } /** * Every call of `t` with a literal first argument, and every literal * `labelKey` (UI commands, whose labels the palette looks up), by file. */ const usedKeys = sourceFiles(SRC).flatMap((file) => [...readFileSync(file, "utf8").matchAll(/(?:\bt\(|\blabelKey:)\s*(["'`])([^"'`]*)\1/g)].map((m) => ({ file, key: m[2] ?? "", })), ); /** Root of the repository. */ const REPO = join(SRC, "..", ".."); /** * Lists the Rust files below a directory, leaving out `tests` directories * and build output. * * @param dir - the directory. */ function rustFiles(dir: string): string[] { return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { const path = join(dir, entry.name); if (entry.isDirectory()) { return ["tests", "target", "node_modules"].includes(entry.name) ? [] : rustFiles(path); } return entry.name.endsWith(".rs") ? [path] : []; }); } /** * The shipped part of a Rust file: everything before its unit test module. * * @param file - the path. */ function shippedRust(file: string): string { return readFileSync(file, "utf8").replace(/\r\n/g, "\n").split("\n#[cfg(test)]\nmod tests")[0] ?? ""; } /** * Turns a settings enum value into its key segment (`lutra-dark` → * `lutraDark`). * * @param value - the value as the engine stores it. */ function camel(value: string): string { return value.replace(/-([a-z0-9])/g, (_, c: string) => c.toUpperCase()); } /** * Keys the source never passes to `t` literally because they arrive at * runtime, derived from the source so new ones need no list here: * * - any `notification.*` literal: the `messageKey` of `notification` * events (engine and desktop host) and of the toasts the frontend raises; * - Rust `*_key: "…"` fields: theme labels and the settings' `labelKey` * and `descriptionKey`; * - per settings definition, its section name (`settings.section.`) and * each enum value (`settings..value.`); a `Kind::Theme` * setting has every built-in theme id of `theme.rs` and `system` as * values (C9 T1). */ const RUNTIME_KEYS = (() => { const keys = new Set(); const themeIds = [ ...[...shippedRust(join(REPO, "crates", "engine", "src", "theme.rs")).matchAll(/\bid:\s*"([a-z0-9-]+)"/g)].map( (m) => m[1] ?? "", ), "system", ]; const add = (text: string, pattern: RegExp): void => { for (const m of text.matchAll(pattern)) { keys.add(m[1] ?? ""); } }; for (const file of sourceFiles(SRC)) { add(readFileSync(file, "utf8"), /["'`](notification\.[A-Za-z0-9.]+)["'`]/g); } for (const file of [...rustFiles(join(REPO, "crates")), ...rustFiles(join(REPO, "apps"))]) { const text = shippedRust(file); add(text, /"(notification\.[A-Za-z0-9.]+)"/g); add(text, /\b[a-z]+_key:\s*"([a-z][A-Za-z0-9.]*)"/g); for (const def of text.matchAll(/\bDef\s*\{([\s\S]*?)\n\s*\},?\n/g)) { const body = def[1] ?? ""; const key = /\bkey:\s*"([^"]+)"/.exec(body)?.[1]; const section = /\bsection:\s*"([^"]+)"/.exec(body)?.[1]; if (section !== undefined) { keys.add(`settings.section.${section}`); } const values = /Kind::Enum\(&\[([^\]]*)\]\)/.exec(body)?.[1] ?? ""; for (const value of values.matchAll(/"([^"]+)"/g)) { keys.add(`settings.${key ?? ""}.value.${camel(value[1] ?? "")}`); } if (/Kind::Theme\b/.test(body)) { for (const id of themeIds) { keys.add(`settings.${key ?? ""}.value.${camel(id)}`); } } } } keys.delete(""); return keys; })(); afterEach(() => { vi.restoreAllMocks(); }); describe("t", () => { it("returns the message of a key", () => { expect(t("common.cancel")).toBe("Cancel"); }); it("fills in placeholders", () => { expect(t("editor.tabs.close", { name: "index.php" })).toBe("Close index.php"); expect(t("app.statusBar.version", { name: "Lutra", version: "0.1.0" })).toBe("Lutra 0.1.0"); }); it("formats numbers", () => { expect(t("common.toolWindow.hide", { title: 3 })).toBe("Hide 3"); }); it("keeps a placeholder without a value", () => { expect(t("editor.tabs.close")).toBe("Close {name}"); expect(t("editor.tabs.close", { other: "x" })).toBe("Close {name}"); }); it("does not resolve placeholders from the prototype", () => { expect(t("editor.tabs.close", {})).toBe("Close {name}"); expect(t("common.error.unexpectedResult", { command: "{name}" })).toBe( "unexpected result of {name}", ); }); it("returns the key and warns on a missing key", () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); expect(t("no.such.key")).toBe("no.such.key"); expect(warn).toHaveBeenCalledWith(expect.stringContaining("no.such.key")); }); it("does not treat prototype names as keys", () => { vi.spyOn(console, "warn").mockImplementation(() => undefined); expect(hasMessage("toString")).toBe(false); expect(t("toString")).toBe("toString"); }); }); describe("en.json", () => { it("uses flat dotted keys of known areas with string values", () => { for (const [key, value] of Object.entries(en)) { expect(key).toMatch( /^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure|menu|terminal|problems|nav|vcs|deploy)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/, ); expect(typeof value).toBe("string"); expect(value.trim()).not.toBe(""); } }); it("is sorted by key", () => { const keys = Object.keys(en); expect(keys).toEqual([...keys].sort()); }); it("contains every key the source passes to t", () => { expect(usedKeys.length).toBeGreaterThan(0); const missing = usedKeys.filter(({ key }) => !hasMessage(key)); expect(missing).toEqual([]); }); it("finds the runtime keys of every source", () => { for (const key of [ "notification.vcs.committed", "notification.project.unsavedChanges", "settings.editor.fontSize.label", "settings.section.git", "settings.appearance.theme.value.lutraDark", "theme.lutraLight", ]) { expect(RUNTIME_KEYS.has(key), key).toBe(true); } }); it("has every runtime key", () => { expect([...RUNTIME_KEYS].filter((key) => !hasMessage(key))).toEqual([]); }); it("has no unused keys", () => { const used = new Set([...usedKeys.map(({ key }) => key), ...RUNTIME_KEYS]); expect(Object.keys(en).filter((key) => !used.has(key))).toEqual([]); }); }); describe("dates", () => { it("shows every date as YYYY-MM-DD and times as HH:mm in local time, whatever the system locale", () => { const local = new Date(2026, 10, 1, 9, 5, 30); expect(formatDate(local.getTime())).toBe("2026-11-01"); expect(formatDateTime(local.getTime())).toBe("2026-11-01 09:05"); expect(formatDateTime("2026-12-24T18:30:00")).toBe("2026-12-24 18:30"); expect(formatDate("2026-03-07T23:59:00")).toBe("2026-03-07"); expect(formatDateTime("not a date")).toBe("not a date"); expect(formatDate("")).toBe(""); }); });