Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,13 @@ jobs:
working-directory: frontend
run: pnpm check

# Data-level catalogue tests cannot see the 1,500-odd call sites that use the keys,
# or how the strings are rendered. This checks both: every literal $t/tr/trp key
# exists in en.json, and no catalogue value is rendered with {@html}.
- name: i18n catalogue guard (call sites, no {@html})
working-directory: frontend
run: pnpm check:i18n

- name: Build frontend (required by the Go embed)
working-directory: frontend
run: pnpm build
Expand Down
1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"scripts": {
"dev": "vite dev",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:i18n": "node scripts/check-i18n.mjs",
"build": "vite build",
"preview": "vite preview",
"test:visual": "vitest run"
Expand Down
108 changes: 108 additions & 0 deletions frontend/scripts/check-i18n.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
#!/usr/bin/env node
// Source-level guards for the admin catalogue.
//
// The catalogue tests (src/lib/i18n/i18n.test.ts) prove things about the data: keys line
// up, placeholders match, no baked plurals. They cannot see the 1,270-odd call sites that
// use that data, and they cannot see how it is rendered. That gap is what this checks:
//
// 1. Every literal key passed to $t/tr/trp/trp2 exists in en.json. A typo currently
// renders the dotted key on screen and every test stays green.
// 2. No catalogue string is rendered with {@html}. Catalogue text is plain text by
// contract (see catalog.ts); community locale PRs are a real input, so HTML in a
// catalogue is an injection surface, not a styling convenience.
//
// Runs from the frontend directory: `pnpm check:i18n`, and in CI.
//
// Dynamic keys (template literals, ternaries) are skipped rather than guessed at. They
// are listed at the end so a reviewer can see what is not covered.

import { readFileSync, readdirSync, statSync } from 'node:fs';
import { join, relative, extname } from 'node:path';
import { fileURLToPath } from 'node:url';

const frontendDir = fileURLToPath(new URL('..', import.meta.url));
const srcDir = join(frontendDir, 'src');
const cataloguePath = join(srcDir, 'lib/i18n/en.json');

// The catalogue's own module and tests define the helpers; they are not call sites.
const SKIP_DIRS = [join(srcDir, 'lib/i18n')];

function flatten(value, prefix = '', leaves = new Map(), groups = new Set()) {
if (value && typeof value === 'object' && !Array.isArray(value)) {
// An object is a real key too: trp/trp2 append `.one`/`.other` themselves, so a
// plural call passes the group path, not a leaf.
if (prefix) groups.add(prefix);
for (const [k, v] of Object.entries(value)) flatten(v, prefix ? `${prefix}.${k}` : k, leaves, groups);
} else {
leaves.set(prefix, value);
}
return { leaves, groups };
}

function* walk(dir) {
for (const entry of readdirSync(dir)) {
const full = join(dir, entry);
if (SKIP_DIRS.some((skip) => full === skip || full.startsWith(skip + '/'))) continue;
const st = statSync(full);
if (st.isDirectory()) yield* walk(full);
else if (['.svelte', '.ts'].includes(extname(full))) yield full;
}
}

const { leaves: keys, groups } = flatten(JSON.parse(readFileSync(cataloguePath, 'utf8')));

// `$t('key')`, `tr('key')`, `trp('key', n)`, `trp2('key', a, b)`. The key must be the
// first argument and a plain quoted string; anything else is dynamic and is counted, not
// checked.
const CALL = /(?:\$t\(|\b(?:tr|trp|trp2)\()\s*(['"])((?:(?!\1).)+)\1/g;
const ANY_CALL = /(?:\$t\(|\b(?:tr|trp|trp2)\()/g;
const RENDERED_AS_HTML = /\{@html[^}]*?(?:\$t\(|\b(?:tr|trp|trp2)\()/;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the scan is per line, a {@html whose expression wraps — {@html on one line, $t('…')} on the next — escapes this check entirely; I confirmed it with a probe file. The regex already crosses newlines via [^}]*?, so it is only the source.split('\n') above that hides it: matching against the whole source and deriving the line from the match index closes the gap.

Technical details
# `{@html}` guard misses wrapped expressions

## Affected sites
- `frontend/scripts/check-i18n.mjs:69-70` — `RENDERED_AS_HTML.test(line)` only ever sees one line of source.
- `frontend/scripts/check-i18n.mjs:59` — `RENDERED_AS_HTML` itself is fine for multi-line input; `[^}]*?` already spans newlines.

## Required outcome
- A `{@html` whose catalogue call sits on a following line is reported by `pnpm check:i18n`, anchored at the line of the `{@html`.
- Existing single-line detection and the `missing` / `dynamic` reporting stay unchanged.

## Suggested approach (optional)
- Leave the per-line loop as is, then run `RENDERED_AS_HTML` with the `/g` flag over the whole `source` and compute the line as `source.slice(0, match.index).split('\n').length`. Keep `[^}]*?` as the bound so code after the closing `}` cannot match.

## Verification
- Probe used: a `.svelte` file containing `<p>{@html\n  $t('layout.reportDialog.description')}</p>`; the current script exits 0 on it.


const missing = [];
const asHtml = [];
let checked = 0;
let dynamic = 0;

for (const file of walk(srcDir)) {
const rel = relative(frontendDir, file);
const source = readFileSync(file, 'utf8');
source.split('\n').forEach((line, i) => {
if (RENDERED_AS_HTML.test(line)) asHtml.push(`${rel}:${i + 1}: ${line.trim()}`);
const literalKeys = new Set();
for (const m of line.matchAll(CALL)) {
checked++;
literalKeys.add(m[2]);
if (!keys.has(m[2]) && !groups.has(m[2])) missing.push(`${rel}:${i + 1}: ${m[2]}`);
}
// Calls on this line with no literal key are dynamic.
const total = [...line.matchAll(ANY_CALL)].length;
dynamic += Math.max(0, total - literalKeys.size);
});
}

let failed = false;

if (missing.length > 0) {
failed = true;
console.error(`\n${missing.length} call site(s) use a key that is not in en.json:\n`);
for (const m of missing) console.error(` ${m}`);
console.error('\nA missing key renders as the dotted key on screen. Check the spelling, or add it to en.json first.\n');
}

if (asHtml.length > 0) {
failed = true;
console.error(`\n${asHtml.length} call site(s) render catalogue text with {@html}:\n`);
for (const h of asHtml) console.error(` ${h}`);
console.error(
'\nCatalogue values are plain text and community locale PRs are a real input, so this is an injection surface.\n' +
'Render the markup in the component and use a key per fragment, or use LinkedText for operator links.\n'
);
}

console.log(
`i18n guard: ${checked} literal call site(s) checked against ${keys.size} keys ` +
`(+${groups.size} plural groups), ` +
`${dynamic} dynamic call site(s) skipped (template/ternary keys).`
);

if (failed) process.exit(1);
3 changes: 1 addition & 2 deletions frontend/src/lib/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,7 @@
"title": "Report an issue",
"description": "Please search the existing issues first — it may already be reported or being worked on. The tracker is for reproducible bugs in Calnode; for setup help or \"how do I…\" questions, please use Discussions instead.",
"searchIssues": "Search existing issues",
"reportBug": "Report a bug",
"descriptionHtml": "Please <strong>search the existing issues first</strong> — it may already be reported or being worked on. The tracker is for <strong>reproducible bugs</strong> in Calnode; for setup help or “how do I…” questions, please use Discussions instead."
"reportBug": "Report a bug"
},
"headTitleSuffix": "Calnode"
},
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/lib/i18n/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,7 @@
"title": "Signaler un problème",
"description": "Veuillez d'abord rechercher parmi les tickets existants — le problème a peut-être déjà été signalé ou est en cours de traitement. Le suivi est réservé aux bugs reproductibles dans Calnode ; pour une aide à la configuration ou les questions du type « comment faire pour… », utilisez plutôt Discussions.",
"searchIssues": "Rechercher parmi les tickets existants",
"reportBug": "Signaler un bug",
"descriptionHtml": "Veuillez d'abord <strong>rechercher parmi les tickets existants</strong> — le problème a peut-être déjà été signalé ou est en cours de traitement. Le suivi est réservé aux <strong>bugs reproductibles</strong> dans Calnode ; pour une aide à la configuration ou les questions du type « comment faire pour… », utilisez plutôt Discussions."
"reportBug": "Signaler un bug"
},
"headTitleSuffix": "Calnode"
},
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/routes/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@
<Dialog.Header>
<Dialog.Title>{$t('layout.reportDialog.title')}</Dialog.Title>
<Dialog.Description>
{@html $t('layout.reportDialog.descriptionHtml')}
{$t('layout.reportDialog.description')}
</Dialog.Description>
</Dialog.Header>
<Dialog.Footer class="gap-2 sm:justify-between">
Expand Down
Loading