Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 | 1x 1x 1x 1x 8x 51x 51x 51x 51x 51x 51x 1649x 1585x 1585x 64x 64x 125x 125x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 4x 4x 125x 125x 125x 125x 125x 64x 60x 51x 49x 51x 62x 62x 62x 1741x 1741x 60x 60x 60x 60x 1681x 60x 60x 1621x 1521x 62x 62x 62x 29x 62x 62x 62x 62x 23x 1x 22x 22x 22x 22x 22x 22x 33x 33x 33x 127x 127x 4x 3x 3x 3x 127x 35x 29x 29x 27x 22x 30x 30x 22x 1x 4x 4x 1x 35x 35x 1x 1x | /**
* @module Swedish Leakage Detector
* @description Detects untranslated Swedish text in non-Swedish articles.
*
* Scans HTML content for Swedish-specific tokens that should have been
* translated. Reports leaked terms with their positions and a leakage score.
*
* Typically used as an advisory CI check: the script exits non-zero if any
* non-SV article contains ≥ threshold untranslated Swedish tokens, but CI
* workflows may choose to run it with `continue-on-error`.
*
* Usage:
* npx tsx scripts/detect-swedish-leakage.ts --dir news/ --threshold 5
*/
import { join, resolve } from 'path';
import { fileURLToPath } from 'url';
import type { Language } from './types/language.js';
// ---------------------------------------------------------------------------
// Swedish-only vocabulary – high-confidence tokens that are exclusively Swedish
// and should never appear in correctly translated content.
// ---------------------------------------------------------------------------
/**
* Common Swedish function words that are almost never valid in other languages.
* Each word is a lower-case Swedish term.
*/
export const SWEDISH_STOP_WORDS: ReadonlySet<string> = new Set([
'och', 'att', 'det', 'som', 'är', 'för', 'med', 'har', 'den',
'inte', 'ska', 'kan', 'till', 'ett', 'var', 'blir', 'också',
'efter', 'vid', 'eller', 'från', 'dessa', 'samt', 'enligt',
'genom', 'inom', 'redan', 'dels', 'bland', 'dock', 'även',
'mellan', 'under', 'utan', 'sedan', 'bör', 'hos', 'mot',
]);
/**
* Swedish parliamentary terms that should always be translated.
* These are domain-specific Swedish words that should never appear in e.g. English articles.
* Includes common inflected forms (definite, plural, genitive) to catch actual leaked tokens.
*/
export const SWEDISH_PARLIAMENTARY_TERMS: ReadonlySet<string> = new Set([
// Betänkande (committee report) – base + common inflections
'betänkande', 'betänkanden', 'betänkandet', 'betänkandena',
// Proposition (government bill)
'proposition', 'propositionen', 'propositioner', 'propositionerna',
// Utskott (committee)
'utskott', 'utskottet', 'utskotten', 'utskottets', 'utskottens',
// Riksdag (parliament)
'riksdag', 'riksdagen', 'riksdagens',
// Regering (government)
'regering', 'regeringen', 'regeringens',
// Motion (member's bill)
'motion', 'motionen', 'motioner', 'motionerna', 'motionens',
// Interpellation (formal question)
'interpellation', 'interpellationen', 'interpellationer', 'interpellationerna',
// Anförande (speech)
'anförande', 'anförandet', 'anföranden', 'anförandena',
// Votering / omröstning (vote)
'votering', 'voteringen', 'voteringar', 'voteringarna',
'omröstning', 'omröstningen', 'omröstningar', 'omröstningarna',
// Bordläggning (tabling)
'bordläggning', 'bordläggningen',
// Remiss / yttrande (referral / opinion)
'remiss', 'remissen', 'remisser', 'remisserna',
'yttrande', 'yttrandet', 'yttranden', 'yttrandena',
// Statsråd / ledamot / riksdagsledamot (minister / member of parliament)
'statsråd', 'statsrådet', 'statsråden',
'ledamot', 'ledamoten', 'ledamöter', 'ledamöterna',
'riksdagsledamot', 'riksdagsledamoten', 'riksdagsledamöter', 'riksdagsledamöterna',
// Budget terms
'utgiftsområde', 'utgiftsområdet', 'utgiftsområden',
'budgetpropositionen', 'vårpropositionen',
// Committee names (already definite form)
'finansutskottet', 'justitieutskottet', 'försvarsutskottet',
'socialutskottet', 'utbildningsutskottet', 'utrikesutskottet',
'skatteutskottet', 'trafikutskottet', 'kulturutskottet',
// Other procedure terms
'tillkännagivande', 'tillkännagivanden', 'tillkännagivandet',
'lagförslag', 'lagförslaget', 'lagförslagen',
'lagstiftning', 'lagstiftningen',
'sammanträde', 'sammanträdet', 'sammanträden',
'anmälan', 'anmälningar', 'anmälningarna',
'granskning', 'granskningen', 'granskningar',
'beredning', 'beredningen', 'beredningar',
'anslag', 'anslaget', 'anslagen',
'utgiftstak', 'utgiftstaket',
'statsbudgeten',
// Swedish government ministries (departement) – should always be translated
'finansdepartementet',
'utrikesdepartementet',
'justitiedepartementet',
'försvarsdepartementet',
'utbildningsdepartementet',
'socialdepartementet',
'kulturdepartementet',
'miljödepartementet',
'infrastrukturdepartementet',
'arbetsmarknadsdepartementet',
'näringsdepartementet',
]);
/** Result for a single detected leaked term. */
export interface LeakedTerm {
/** The Swedish token detected. */
readonly term: string;
/** 1-based line number where the term was first found. */
readonly line: number;
/** Number of occurrences of this term in the article. */
readonly count: number;
}
/** Aggregated leakage report for a single article. */
export interface LeakageReport {
/** Array of leaked Swedish terms found (deduplicated, with per-term counts). */
readonly leakedTerms: ReadonlyArray<LeakedTerm>;
/** Total number of Swedish token occurrences detected across all leaked terms. */
readonly score: number;
}
// ---------------------------------------------------------------------------
// HTML stripping helper
// ---------------------------------------------------------------------------
/**
* Options for stripHtml processing.
*
* skipBlockStripping: Set to true when script/style blocks have already been
* removed by a prior pass (e.g. line-preserving preprocessing in detectSwedishLeakage)
* to avoid redundant block stripping work.
*/
interface StripHtmlOptions {
readonly skipBlockStripping?: boolean;
}
/** Valid boundary after an HTML tag name. */
function isTagNameBoundary(ch: string | undefined): boolean {
return ch === undefined || ch === '>' || ch === '/' || /\s/.test(ch);
}
/**
* Strip specific HTML tag blocks using a single-pass index-based scan
* (avoids regex tag filters and repeated toLowerCase).
*
* For preserveNewlines=true, removed content is replaced with spaces while keeping '\n'
* positions intact so line numbering remains stable.
*/
function stripTagBlocks(html: string, tagNames: ReadonlyArray<string>, preserveNewlines: boolean): string {
const lower = html.toLowerCase();
const length = html.length;
const resultParts: string[] = [];
let copyFrom = 0;
let i = 0;
while (i < length) {
if (lower[i] !== '<') {
i++;
continue;
}
let matchedBlock = false;
for (const tagName of tagNames) {
const openPrefix = `<${tagName}`;
if (!lower.startsWith(openPrefix, i)) continue;
const openNameBoundaryIndex = i + 1 + tagName.length;
Iif (!isTagNameBoundary(lower[openNameBoundaryIndex])) continue;
const openEnd = lower.indexOf('>', openNameBoundaryIndex);
Iif (openEnd === -1) continue;
const closePrefix = `</${tagName}`;
const closeStart = lower.indexOf(closePrefix, openEnd + 1);
Iif (closeStart === -1) continue;
const closeNameBoundaryIndex = closeStart + 2 + tagName.length;
Iif (!isTagNameBoundary(lower[closeNameBoundaryIndex])) continue;
const closeEnd = lower.indexOf('>', closeNameBoundaryIndex);
Iif (closeEnd === -1) continue;
// Push text before this block
if (i > copyFrom) {
resultParts.push(html.slice(copyFrom, i));
}
// Push replacement for the matched block
const block = html.slice(i, closeEnd + 1);
const replacement = preserveNewlines
? block.replace(/[^\n]/g, ' ')
: ' ';
resultParts.push(replacement);
i = closeEnd + 1;
copyFrom = i;
matchedBlock = true;
break;
}
if (!matchedBlock) {
i++;
}
}
// Push remaining text after the last matched block
if (copyFrom < length) {
resultParts.push(html.slice(copyFrom));
}
return resultParts.join('');
}
/** Remove all remaining HTML tags using an index-based state machine. */
function stripAllTags(html: string): string {
const chunks: string[] = [];
let inTag = false;
for (let i = 0; i < html.length; i++) {
const ch = html[i];
if (ch === '<') {
Eif (!inTag) {
chunks.push(' ');
}
inTag = true;
continue;
}
if (ch === '>' && inTag) {
inTag = false;
continue;
}
if (!inTag) {
chunks.push(ch);
}
}
return chunks.join('');
}
/**
* Strip HTML tags and decode common entities to get plain text.
* This is used only for analysis/detection purposes, NOT for sanitisation.
* @param html - Raw HTML string
* @returns Plain text content
*/
export function stripHtml(html: string, options: StripHtmlOptions = {}): string {
let text = html;
if (!options.skipBlockStripping) {
// Remove script/style blocks first to avoid matching inner tag-like content.
text = stripTagBlocks(text, ['script', 'style'], false);
}
// Remove remaining tags
text = stripAllTags(text);
// Decode common entities.
// First, decode doubly-encoded entity references (&#xE4; → ä) so that
// the subsequent hex/numeric patterns can match them in a single pass.
text = text.replace(/&(#\w+;)/g, '&$1');
text = text
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/�*39;|&#[xX]0*27;/g, "'")
.replace(/ /g, ' ')
// Swedish characters (HTML named and numeric entities, case-insensitive hex)
.replace(/ä|ä|&#[xX]0*[eE]4;/g, 'ä')
.replace(/Ä|Ä|&#[xX]0*[cC]4;/g, 'Ä')
.replace(/ö|ö|&#[xX]0*[fF]6;/g, 'ö')
.replace(/Ö|Ö|&#[xX]0*[dD]6;/g, 'Ö')
.replace(/å|å|&#[xX]0*[eE]5;/g, 'å')
.replace(/Å|Å|&#[xX]0*[cC]5;/g, 'Å')
// Common quote and dash entities (case-insensitive hex, optional leading zeros)
.replace(/–|–|&#[xX]0*2013;/g, '-')
.replace(/—|—|&#[xX]0*2014;/g, '-')
.replace(/“|”|“|”|&#[xX]0*201[Cc];|&#[xX]0*201[Dd];/g, '"')
.replace(/‘|’|‘|’|&#[xX]0*2018;|&#[xX]0*2019;|'/g, "'")
.replace(/&/g, '&');
// Normalise whitespace
return text.replace(/\s+/g, ' ').trim();
}
// ---------------------------------------------------------------------------
// Core detection logic
// ---------------------------------------------------------------------------
/**
* Detect Swedish leakage in HTML content intended for a non-Swedish audience.
*
* @param html - Full article HTML
* @param targetLang - The article's target language (e.g. 'en', 'de')
* @returns LeakageReport with leaked terms and score
*/
export function detectSwedishLeakage(html: string, targetLang: Language): LeakageReport {
// Swedish articles are expected to contain Swedish text.
if (targetLang === 'sv') {
return { leakedTerms: [], score: 0 };
}
// Strip script/style blocks on the full HTML first so multi-line blocks are
// removed correctly. Preserve newline count so reported line numbers remain accurate.
const cleaned = stripTagBlocks(html, ['script', 'style'], true);
const lines = cleaned.split('\n');
const leaked: LeakedTerm[] = [];
/** First-seen line for each term. */
const firstLine = new Map<string, number>();
/** Per-term occurrence count. */
const counts = new Map<string, number>();
for (let i = 0; i < lines.length; i++) {
const plainLine = stripHtml(lines[i], { skipBlockStripping: true });
const words = plainLine.split(/[-\s,.:;!?()[\]{}'"]+/).filter(Boolean);
for (const word of words) {
const lower = word.toLowerCase();
// Check against Swedish stop words (require ≥2 chars to avoid false positives)
if (lower.length >= 2 && SWEDISH_STOP_WORDS.has(lower)) {
if (!isSharedWord(lower, targetLang)) {
counts.set(lower, (counts.get(lower) ?? 0) + 1);
Eif (!firstLine.has(lower)) {
firstLine.set(lower, i + 1);
}
}
}
// Check against Swedish parliamentary terms, also applying shared-word filter
// to avoid false positives in Scandinavian languages (e.g. "proposition" shared across languages)
if (SWEDISH_PARLIAMENTARY_TERMS.has(lower)) {
if (!isSharedParliamentaryTerm(lower, targetLang)) {
counts.set(lower, (counts.get(lower) ?? 0) + 1);
if (!firstLine.has(lower)) {
firstLine.set(lower, i + 1);
}
}
}
}
}
// Build deduplicated results with counts
for (const [term, line] of firstLine) {
leaked.push({ term, line, count: counts.get(term) ?? 1 });
}
// Score: total number of Swedish token occurrences detected across all leaked terms
const totalOccurrences = Array.from(counts.values()).reduce((sum, value) => sum + value, 0);
return { leakedTerms: leaked, score: totalOccurrences };
}
// ---------------------------------------------------------------------------
// Shared word filter – some Swedish words are valid in other languages
// ---------------------------------------------------------------------------
/** Words shared between Swedish and specific other languages. */
const SHARED_WORDS: Partial<Record<Language, ReadonlySet<string>>> = {
// Danish shares some common words with Swedish but not 'och', 'att', 'från' etc.
da: new Set(['det', 'den', 'var', 'kan', 'efter', 'eller', 'under', 'mot', 'med', 'som', 'har']),
// Norwegian shares some common words with Swedish
no: new Set(['det', 'den', 'var', 'kan', 'eller', 'under', 'mot', 'med', 'som', 'har']),
// German: do not treat "det" or "var" as shared, to avoid hiding Swedish leakage
de: new Set([]),
// Dutch: currently no Swedish stop words are treated as shared
nl: new Set([]),
fr: new Set([]),
es: new Set([]),
fi: new Set([]),
en: new Set([]),
ar: new Set([]),
he: new Set([]),
ja: new Set([]),
ko: new Set([]),
zh: new Set([]),
};
/**
* Check if a Swedish word is also a valid word in the target language,
* to avoid false positives (e.g. "det" in Danish).
*/
function isSharedWord(word: string, targetLang: Language): boolean {
const shared = SHARED_WORDS[targetLang];
return shared ? shared.has(word) : false;
}
/**
* Parliamentary terms that are valid/identical in specific Scandinavian target
* languages and should not be flagged as Swedish leakage for those languages.
* Includes inflected forms to match the expanded SWEDISH_PARLIAMENTARY_TERMS set.
*/
const SHARED_PARLIAMENTARY_TERMS: Partial<Record<Language, ReadonlySet<string>>> = {
// Norwegian uses many of the same parliamentary terms as Swedish
no: new Set([
'proposition', 'propositionen', 'propositioner', 'propositionerna',
'interpellation', 'interpellationen', 'interpellationer', 'interpellationerna',
'regeringen', 'regeringens',
'statsråd', 'statsrådet', 'statsråden',
// Only keep ministry names whose spelling is truly identical in Swedish and Norwegian.
// Swedish-only spellings (försvarsdepartementet, miljödepartementet,
// arbetsmarknadsdepartementet, näringsdepartementet) are NOT shared —
// Norwegian uses distinct forms, so Swedish spellings should be flagged.
'finansdepartementet',
'kulturdepartementet',
'infrastrukturdepartementet',
]),
// Danish shares some parliamentary vocabulary
da: new Set([
'proposition', 'propositionen', 'propositioner', 'propositionerna',
'interpellation', 'interpellationen', 'interpellationer', 'interpellationerna',
'regeringen', 'regeringens',
]),
};
/**
* Check if a Swedish parliamentary term is also valid in the target language.
*/
function isSharedParliamentaryTerm(term: string, targetLang: Language): boolean {
const shared = SHARED_PARLIAMENTARY_TERMS[targetLang];
return shared ? shared.has(term) : false;
}
// ---------------------------------------------------------------------------
// CLI entry point
// ---------------------------------------------------------------------------
async function main(): Promise<void> {
const args = process.argv.slice(2);
let dir = 'news/';
let threshold = 5;
for (let i = 0; i < args.length; i++) {
if (args[i] === '--dir' && args[i + 1]) {
dir = args[i + 1];
i++;
}
if (args[i] === '--threshold' && args[i + 1]) {
const rawThreshold = args[i + 1];
// Validate: must be a positive integer (optional leading zeros allowed, e.g. "03")
if (!/^0*[1-9]\d*$/.test(rawThreshold)) {
console.error(`Invalid --threshold value "${rawThreshold}". Threshold must be a positive integer.`);
process.exit(1);
}
const parsed = Number(rawThreshold);
if (!Number.isInteger(parsed) || parsed <= 0) {
console.error(`Invalid --threshold value "${rawThreshold}". Threshold must be a positive integer.`);
process.exit(1);
}
threshold = parsed;
i++;
}
}
const { readdirSync, readFileSync } = await import('fs');
const files = readdirSync(dir).filter((f: string) => f.endsWith('.html'));
const langCodes: ReadonlyArray<Language> = [
'en', 'da', 'no', 'fi', 'de', 'fr', 'es', 'nl', 'ar', 'he', 'ja', 'ko', 'zh',
];
let totalFailures = 0;
for (const langCode of langCodes) {
const langFiles = files.filter((f: string) => f.endsWith(`-${langCode}.html`));
for (const file of langFiles) {
const html = readFileSync(join(dir, file), 'utf-8');
const report = detectSwedishLeakage(html, langCode);
if (report.score >= threshold) {
console.error(`❌ ${file}: ${report.score} Swedish tokens detected (threshold: ${threshold})`);
for (const t of report.leakedTerms.slice(0, 5)) {
console.error(` Line ${t.line}: "${t.term}" (×${t.count})`);
}
totalFailures++;
}
}
}
if (totalFailures > 0) {
console.error(`\n${totalFailures} file(s) exceeded the Swedish leakage threshold.`);
process.exit(1);
} else {
console.log('✅ All non-Swedish articles passed Swedish leakage check.');
}
}
// Run CLI when invoked directly
const isMainModule =
typeof process !== 'undefined' &&
typeof process.argv?.[1] === 'string' &&
resolve(fileURLToPath(import.meta.url)) === resolve(process.argv[1]);
Iif (isMainModule) {
main().catch((err) => {
console.error(err);
process.exit(1);
});
}
|