Files
Oliver_Herb 9053327486 Inline Comment 0.2.0 - initial public release
Thunderbird/Betterbird add-on (Manifest V3): typing inside a quote splits
the quote and inserts your own text with a marker such as [OH]:.

- English and German user interface
- Licensed under the Mozilla Public License 2.0
- English documentation, JSDoc lint gate, 87 tests (node:test + jsdom)
2026-11-24 12:07:09 +01:00

520 lines
18 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
* Copyright 2026 Oliver Herb
* SPDX-License-Identifier: MPL-2.0
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
"use strict";
/*
* Tests for the translations in src/_locales and the localization helper
* src/lib/i18n.js, including the options page rendered in jsdom.
*
* The static checks compare the messages.json files with each other and
* with the keys used in options.html, the scripts and manifest.json. The
* options page tests load options.html into jsdom, provide a fake
* WebExtension API (i18n, storage, identities) and run the page scripts, so
* the rendered texts can be checked for each locale.
*/
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const { JSDOM } = require("jsdom");
const { createDocument, text } = require("./helpers/dom.js");
const { localizeDocument } = require("../src/lib/i18n.js");
const manifest = require("../src/manifest.json");
const SRC = path.join(__dirname, "..", "src");
const LOCALES_DIR = path.join(SRC, "_locales");
const LOCALES = fs.readdirSync(LOCALES_DIR).sort();
const MESSAGES = Object.fromEntries(
LOCALES.map((locale) => [
locale,
JSON.parse(
fs.readFileSync(path.join(LOCALES_DIR, locale, "messages.json"), "utf8"),
),
]),
);
const DEFAULT_MESSAGES = MESSAGES[manifest.default_locale];
const KEYS = Object.keys(DEFAULT_MESSAGES).sort();
const OPTIONS_PAGE = manifest.options_ui.page;
const OPTIONS_HTML = fs.readFileSync(path.join(SRC, OPTIONS_PAGE), "utf8");
/**
* Lists all .js files below dir, recursively.
* @param {string} [dir] Absolute directory path. Defaults to SRC.
* @returns {string[]} Absolute paths of the .js files found.
*/
function sourceFiles(dir = SRC) {
const files = [];
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...sourceFiles(full));
} else if (entry.name.endsWith(".js")) {
files.push(full);
}
}
return files;
}
/**
* Extracts the message keys an HTML page uses via data-i18n,
* data-i18n-aria-label, data-i18n-title and similar attributes.
* @param {string} html Page markup.
* @returns {string[]} The keys, in document order (duplicates kept).
*/
function htmlKeys(html) {
return [...html.matchAll(/\sdata-i18n(?:-[a-z-]+)?="([^"]*)"/g)].map(
(match) => match[1],
);
}
/**
* Collects the literal keys passed to getMessage("...") or msg("...") in the
* scripts below src/.
* @returns {{ key: string, file: string }[]} Each key with the file it is
* used in, relative to src/.
*/
function scriptKeys() {
const keys = [];
for (const file of sourceFiles()) {
const source = fs.readFileSync(file, "utf8");
for (const match of source.matchAll(
/\b(?:getMessage|msg)\(\s*(["'`])([^"'`]+)\1/g,
)) {
keys.push({ key: match[2], file: path.relative(SRC, file) });
}
}
return keys;
}
/**
* Collects the keys referenced as __MSG_key__ in manifest.json.
* @returns {string[]} The keys, in the order they appear.
*/
function manifestKeys() {
return [
...JSON.stringify(manifest).matchAll(/__MSG_([A-Za-z0-9_@]+)__/g),
].map((match) => match[1]);
}
/**
* Minimal stand-in for browser.i18n.getMessage: resolves named placeholders
* ($NAME$, case-insensitive) and positional substitutions ($1 ... $9).
* @param {object} messages Parsed messages.json of one locale.
* @returns {(key: string, substitutions?: unknown) => string} A getMessage
* function; it returns "" for unknown keys, like the real API.
*/
function makeGetMessage(messages) {
return (key, substitutions) => {
const entry = messages[key];
if (!entry) {
return "";
}
const values =
substitutions === undefined ? [] : [].concat(substitutions).map(String);
const placeholders = entry.placeholders || {};
return entry.message
.replace(/\$([A-Za-z0-9_@]+)\$/g, (match, name) => {
const placeholder = placeholders[name.toLowerCase()];
return placeholder ? placeholder.content : match;
})
.replace(/\$([1-9])/g, (match, index) => values[index - 1] ?? "");
};
}
/**
* Waits one macrotask so pending promises (e.g. storage and identity
* requests of the options page) can settle.
* @returns {Promise<void>} Resolves on the next turn of the event loop.
*/
function tick() {
return new Promise((resolve) => setTimeout(resolve, 0));
}
/**
* Creates manually driven timers: callbacks are only recorded and never run
* by themselves, so a test can decide which timer fires and when.
* @returns {{pending: Map<number, () => void>, setTimeout: (callback: () => void) => number, clearTimeout: (id: number) => void}}
* The pending callbacks by timer ID and the two timer functions.
*/
function createFakeTimers() {
let nextId = 1;
const pending = new Map();
return {
pending,
/**
* Records a callback instead of scheduling it.
* @param {() => void} callback Function the page wants to run later.
* @returns {number} Timer ID for clearTimeout.
*/
setTimeout(callback) {
const id = nextId++;
pending.set(id, callback);
return id;
},
/**
* Forgets a recorded callback, like clearTimeout cancels a timer.
* @param {number} id Timer ID returned by setTimeout.
*/
clearTimeout(id) {
pending.delete(id);
},
};
}
/**
* Loads the options page in jsdom with a fake WebExtension API and runs its
* scripts in the order of the <script> tags.
* @param {string} locale Locale to render, e.g. "en" or "de".
* @param {object} [options] Fake API data.
* @param {object[]} [options.identities] Result of
* browser.identities.list(). Defaults to an empty list.
* @param {object} [options.stored] Value stored under the "settings" key.
* @param {object} [options.timers] Fake timers from createFakeTimers();
* when given, they replace the page's setTimeout and clearTimeout.
* @returns {Promise<{ window: Window, doc: Document }>} The jsdom window
* (close it after the test) and its document.
*/
async function openOptions(locale, { identities = [], stored, timers } = {}) {
const dom = new JSDOM(OPTIONS_HTML, { runScripts: "outside-only" });
const { window } = dom;
if (timers) {
window.setTimeout = timers.setTimeout;
window.clearTimeout = timers.clearTimeout;
}
window.browser = {
i18n: {
getMessage: makeGetMessage(MESSAGES[locale]),
/**
* Fake i18n.getUILanguage.
* @returns {string} The locale under test.
*/
getUILanguage: () => locale,
},
storage: {
local: {
/**
* Fake storage.local.get: ignores the requested keys and always
* returns the stored settings.
* @returns {Promise<{ settings: object | undefined }>} The value
* under the "settings" key.
*/
get: async () => ({ settings: stored }),
/**
* Fake storage.local.set: accepts and discards every write.
* @returns {Promise<void>} Resolves immediately.
*/
set: async () => {},
},
},
identities: {
/**
* Fake identities.list.
* @returns {Promise<object[]>} The identities passed to openOptions.
*/
list: async () => identities,
},
};
const dir = path.dirname(OPTIONS_PAGE);
for (const [, src] of OPTIONS_HTML.matchAll(/<script src="([^"]+)"/g)) {
window.eval(fs.readFileSync(path.join(SRC, dir, src), "utf8"));
}
await tick();
await tick();
return { window, doc: window.document };
}
test("locales en and de exist and have the same keys", () => {
assert.ok(LOCALES.includes("en"), "en missing");
assert.ok(LOCALES.includes("de"), "de missing");
assert.ok(KEYS.length > 0);
for (const locale of LOCALES) {
assert.deepEqual(Object.keys(MESSAGES[locale]).sort(), KEYS, locale);
}
});
test("every message has a text and an English description", () => {
for (const locale of LOCALES) {
for (const [key, entry] of Object.entries(MESSAGES[locale])) {
const where = `${locale}/${key}`;
assert.match(key, /^[A-Za-z0-9_@]+$/, where);
assert.equal(typeof entry.message, "string", where);
assert.notEqual(entry.message.trim(), "", where);
assert.equal(typeof entry.description, "string", where);
assert.notEqual(entry.description.trim(), "", where);
// Descriptions are notes for translators and stay English everywhere.
assert.equal(entry.description, DEFAULT_MESSAGES[key].description, where);
}
}
});
test("placeholders are defined and the same in every locale", () => {
for (const locale of LOCALES) {
for (const [key, entry] of Object.entries(MESSAGES[locale])) {
const where = `${locale}/${key}`;
const defined = Object.keys(entry.placeholders || {}).sort();
const expected = Object.keys(
DEFAULT_MESSAGES[key].placeholders || {},
).sort();
assert.deepEqual(defined, expected, where);
for (const [, name] of entry.message.matchAll(/\$([A-Za-z0-9_@]+)\$/g)) {
assert.ok(defined.includes(name.toLowerCase()), `${where}: $${name}$`);
}
}
}
});
test("every data-i18n key in the options page exists", () => {
const keys = htmlKeys(OPTIONS_HTML);
assert.ok(keys.length > 20, "options page is not marked for translation");
for (const key of keys) {
assert.ok(KEYS.includes(key), `unknown key in options.html: ${key}`);
}
});
test("elements with data-i18n contain only text", () => {
const doc = new JSDOM(OPTIONS_HTML).window.document;
for (const element of doc.querySelectorAll("[data-i18n]")) {
assert.equal(
element.children.length,
0,
`<${element.localName} data-i18n="${element.dataset.i18n}"> has child elements`,
);
}
});
test("options page loads i18n.js before options.js", () => {
const scripts = [...OPTIONS_HTML.matchAll(/<script src="([^"]+)"/g)].map(
(match) => match[1],
);
const i18n = scripts.indexOf("../lib/i18n.js");
assert.ok(i18n >= 0, "i18n.js not loaded");
assert.ok(i18n < scripts.indexOf("options.js"));
});
test("every getMessage()/msg() key in the scripts exists", () => {
const used = scriptKeys();
assert.ok(used.length > 0, "no message keys found in src");
for (const { key, file } of used) {
assert.ok(KEYS.includes(key), `unknown key in ${file}: ${key}`);
}
});
test("every __MSG_key__ in manifest.json exists", () => {
const keys = manifestKeys();
assert.ok(keys.includes("extensionName"));
for (const key of keys) {
assert.ok(KEYS.includes(key), `unknown key in manifest.json: ${key}`);
}
});
test("every message is used somewhere", () => {
const used = new Set([
...htmlKeys(OPTIONS_HTML),
...scriptKeys().map((entry) => entry.key),
...manifestKeys(),
]);
for (const key of KEYS) {
assert.ok(used.has(key), `unused message: ${key}`);
}
});
test("localizeDocument replaces text and attributes, keeps fallbacks", () => {
const { doc } = createDocument(`
<h1 id="a" data-i18n="a">Fallback A</h1>
<p id="missing" data-i18n="missing">Keep me</p>
<div id="b" aria-label="old" data-i18n-aria-label="b"></div>
<button id="c" title="old" data-i18n-title="c">Button</button>
<span id="d" title="keep" data-i18n-title="missing">D</span>`);
const messages = { a: "Text A", b: "Label B", c: "Title C" };
const count = localizeDocument(doc, (key) => messages[key] || "");
assert.equal(count, 3);
assert.equal(doc.getElementById("a").textContent, "Text A");
assert.equal(doc.getElementById("missing").textContent, "Keep me");
assert.equal(doc.getElementById("b").getAttribute("aria-label"), "Label B");
assert.equal(doc.getElementById("c").getAttribute("title"), "Title C");
assert.equal(doc.getElementById("c").textContent, "Button");
assert.equal(doc.getElementById("d").getAttribute("title"), "keep");
});
test("localizeDocument tolerates missing or odd getMessage results", () => {
const { doc } = createDocument(`<p id="p" data-i18n="x">Fallback</p>`);
assert.equal(
localizeDocument(doc, () => undefined),
0,
);
assert.equal(
localizeDocument(doc, () => null),
0,
);
assert.equal(localizeDocument(doc, null), 0);
assert.equal(doc.getElementById("p").textContent, "Fallback");
});
for (const locale of ["de", "en"]) {
test(`options page is fully translated (${locale})`, async () => {
const getMessage = makeGetMessage(MESSAGES[locale]);
const { window, doc } = await openOptions(locale);
try {
assert.equal(doc.documentElement.lang, locale);
assert.equal(doc.title, getMessage("optionsTitle"));
for (const element of doc.querySelectorAll("[data-i18n]")) {
assert.equal(element.textContent, getMessage(element.dataset.i18n));
}
assert.equal(
doc.getElementById("chips").getAttribute("aria-label"),
getMessage("placeholderChipsLabel"),
);
assert.equal(
doc.getElementById("profile").options[0].text,
getMessage("profileAllIdentities"),
);
assert.equal(
doc.getElementById("profileHint").textContent,
getMessage("profileHintGlobal"),
);
} finally {
window.close();
}
});
}
test("options page: German profile list, hint and preview", async () => {
const { window, doc } = await openOptions("de", {
identities: [
{ id: "id1", name: "Anna Beispiel", email: "anna@example.com" },
{ id: "id2", name: "", email: "b@example.com" },
],
stored: { global: {}, identities: { id1: { template: "[A]:" } } },
});
try {
const select = doc.getElementById("profile");
assert.deepEqual(
[...select.options].map((option) => option.text),
[
"Alle Identitäten (Standard)",
"Anna Beispiel <anna@example.com> – eigene Einstellungen",
"b@example.com",
],
);
const preview = text(doc.getElementById("preview"));
assert.match(preview, /Können Sie mir die Unterlagen bis Freitag/);
assert.match(preview, /\[AB\]: Ja, kommen morgen\./);
assert.match(preview, /Und bitte die Rechnung beilegen\./);
select.value = "id2";
select.dispatchEvent(new window.Event("change", { bubbles: true }));
assert.equal(
doc.getElementById("profileHint").textContent,
"Diese Identität nutzt die Einstellungen für alle Identitäten. Haken setzen, um sie anzupassen.",
);
const reset = doc.getElementById("reset");
assert.equal(reset.textContent, "Auf Standard zurücksetzen");
select.value = "";
select.dispatchEvent(new window.Event("change", { bubbles: true }));
reset.click();
assert.equal(reset.textContent, "Wirklich zurücksetzen?");
} finally {
window.close();
}
});
test("options page: English preview without identities", async () => {
const { window, doc } = await openOptions("en");
try {
const preview = text(doc.getElementById("preview"));
assert.match(preview, /Could you send me the documents by Friday\?/);
assert.match(preview, /\[JD\]: Yes, they will arrive tomorrow\./);
assert.match(preview, /And please attach the invoice\./);
assert.equal(doc.getElementById("reset").textContent, "Reset to defaults");
} finally {
window.close();
}
});
test("options page: an old reset timer does not end a new confirm step", async () => {
const timers = createFakeTimers();
const { window, doc } = await openOptions("en", {
stored: { global: {}, identities: {} },
timers,
});
try {
const reset = doc.getElementById("reset");
const normalLabel = reset.textContent;
const confirmLabel = MESSAGES.en.resetConfirm.message;
const before = new Set(timers.pending.keys());
reset.click(); // arm
const armTimers = [...timers.pending.keys()].filter(
(id) => !before.has(id),
);
assert.equal(armTimers.length, 1);
assert.equal(reset.textContent, confirmLabel);
reset.click(); // confirm: reset happens, the arm timer is cancelled
assert.equal(reset.textContent, normalLabel);
reset.click(); // arm again
assert.equal(reset.textContent, confirmLabel);
// The first timer must not be able to end the new confirm step.
for (const id of armTimers) {
const callback = timers.pending.get(id);
if (callback) {
callback();
}
}
assert.equal(reset.textContent, confirmLabel);
} finally {
window.close();
}
});
test("options page: preview is built from DOM nodes, HTML stays text", async () => {
const template = '<img src="x" onerror="alert(1)">{initials}:';
const { window, doc } = await openOptions("en", {
stored: { global: { template }, identities: {} },
});
try {
const preview = doc.getElementById("preview");
assert.deepEqual(
[...preview.children].map((element) => element.localName),
["blockquote", "div", "blockquote"],
);
for (const quote of preview.querySelectorAll("blockquote")) {
assert.equal(quote.getAttribute("type"), "cite");
}
const comment = preview.children[1];
assert.equal(comment.getAttribute("data-inline-comment"), "preview");
assert.equal(preview.querySelector("img"), null);
assert.equal(
comment.querySelector("[data-inline-comment-marker]").textContent,
'<img src="x" onerror="alert(1)">JD:',
);
assert.equal(
text(comment),
'<img src="x" onerror="alert(1)">JD: Yes, they will arrive tomorrow.',
);
// Editing the template re-renders the preview instead of appending to it.
const input = doc.getElementById("template");
input.value = "{name} <b>says</b>:";
input.dispatchEvent(new window.Event("input", { bubbles: true }));
assert.equal(preview.children.length, 3);
assert.equal(preview.querySelector("b"), null);
assert.equal(
text(preview.children[1]),
"Jane Doe <b>says</b>: Yes, they will arrive tomorrow.",
);
} finally {
window.close();
}
});