/* * 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} 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 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