All files / src/generators/news-indexes backfill.ts

53.28% Statements 73/137
34.11% Branches 29/85
71.42% Functions 15/21
57.14% Lines 68/119

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 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540                                                                5x     5x                                                 5x                                                                                                                                                                                                                                                                                                                                   9x 9x 3x   6x 6x 9x 9x 9x 9x 9x 24x   9x 9x 9x                     6x 6x                       6x 6x 6x 6x 6x 5x                   12x                               9x 5x                                                                                                                                       10x 10x                         10x                                             5x 5x 5x                           5x 1x         4x           5x             5x           5x 5x                       10x   140x   10x     10x                     7x                     1x       1x                             9x 9x 11x   9x                   11x 11x 10x 10x 10x   10x 10x 10x     10x 7x   3x     3x 1x     8x 8x 8x    
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Generators/NewsIndexes/Backfill
 * @description Legacy article HTML SEO repair helpers, factored out of
 * `news-indexes.ts` (Refactor 8/8). All public names (`applyArticleSeoBackfill`,
 * `backfillLegacyArticleSeo`, `healJsonLdDescriptionCorruption`,
 * `backfillArticleHreflang`, `buildLegacyBackfillDescription`) keep their
 * original exported signatures so the regression test suites in
 * `test/unit/news-indexes-*.test.js` keep importing from the barrel.
 */
 
import path from 'path';
import fs from 'fs';
import { NEWS_DIR, BASE_URL } from '../../constants/config.js';
import {
  ALL_LANGUAGES,
  ARTICLE_TYPE_LABELS,
  getLocalizedString,
} from '../../constants/languages.js';
import {
  formatSlug,
  parseArticleFilename,
  extractArticleMeta,
  escapeHTML,
  atomicWrite,
} from '../../utils/file-utils.js';
import { detectCategory } from '../../utils/article-category.js';
import { buildSeoKeywords, resolveArticleMetadata } from '../../aggregator/article-metadata.js';
import type { ArticleCategoryLabels, LanguageCode } from '../../types/index.js';
 
const MIN_ARTICLE_DESCRIPTION_LENGTH = 120;
 
/** Language labels used only in forced legacy backfill prefixes. */
const LEGACY_LANGUAGE_LABELS: Record<LanguageCode, string> = {
  en: 'English',
  sv: 'Svenska',
  da: 'Dansk',
  no: 'Norsk',
  fi: 'Suomi',
  de: 'Deutsch',
  fr: 'Français',
  es: 'Español',
  nl: 'Nederlands',
  ar: 'العربية',
  he: 'עברית',
  ja: '日本語',
  ko: '한국어',
  zh: '中文',
};
 
/**
 * Regex pattern that flags internal artefact identifiers
 * (`<slug>-run<N>-<unix-ts>`). Used by
 * {@link descriptionHasLeakyToken} to force backfill of legacy articles
 * whose `<meta description>` was authored before the resolver started
 * stripping run-ids and "analysis run" jargon. Mirrors
 * `FORBIDDEN_PATTERNS` in `scripts/validate-manifest-seo.js`.
 */
const LEAKY_RUNID_RE = /\b[a-z][a-z-]*-run-?\d+-\d{8,}\b/iu;
 
/**
 * Backfill SEO metadata for legacy article HTML files that pre-date the
 * current article generator. This keeps historic pages from carrying short
 * or duplicate descriptions while the canonical generator handles new runs.
 *
 * @param filenames - News article filenames to inspect
 * @returns Number of HTML files updated
 */
export function backfillLegacyArticleSeo(filenames: readonly string[]): number {
  const descriptions = new Map<string, number>();
  for (const filename of filenames) {
    const meta = extractArticleMeta(path.join(NEWS_DIR, filename));
    if (!meta.description) continue;
    descriptions.set(meta.description, (descriptions.get(meta.description) ?? 0) + 1);
  }
 
  let updated = 0;
  for (const filename of filenames) {
    if (backfillOneLegacyArticleSeo(filename, descriptions)) updated++;
  }
  return updated;
}
 
/**
 * Heal JSON-LD `description` field corruption left behind by a prior
 * version of {@link applyArticleSeoBackfill}. The old regex
 * `"description":"[^"]*"` terminated at the first JSON-escaped quote
 * (`\"`), so every rebuild prepended a new value in front of the
 * previous description's tail — producing an unparseable JSON-LD
 * block whose `description` value was followed by a run of repeated
 * fragments before `,"datePublished"`.
 *
 * This pass is idempotent: when the JSON-LD is already well-formed,
 * the regex `[^,]*` matches the empty string and the file is left
 * unchanged. It runs unconditionally because the original backfill
 * path skips files whose `<meta name="description">` is already
 * clean, even when their JSON-LD is corrupted.
 *
 * @param filenames - News article filenames to inspect
 * @returns Number of HTML files updated
 */
export function healJsonLdDescriptionCorruption(filenames: readonly string[]): number {
  let updated = 0;
  for (const filename of filenames) {
    const filepath = path.join(NEWS_DIR, filename);
    const html = readArticleHtml(filepath);
    if (!html) continue;
    const next = html.replace(/("description":"(?:\\.|[^"\\])*")[^,]*(,"datePublished")/u, '$1$2');
    if (next === html) continue;
    atomicWrite(filepath, next);
    updated++;
  }
  return updated;
}
 
/**
 * Backfill one article file when its metadata is missing, short or duplicate.
 *
 * @param filename - News article filename
 * @param descriptions - Description frequency map for duplicate detection
 * @returns True when the file was updated
 */
function backfillOneLegacyArticleSeo(
  filename: string,
  descriptions: ReadonlyMap<string, number>
): boolean {
  const filepath = path.join(NEWS_DIR, filename);
  const parsed = parseArticleFilename(filename);
  if (!parsed) return false;
  const meta = extractArticleMeta(filepath);
  const html = readArticleHtml(filepath);
  if (!html) return false;
  const hasKeywords = /<meta name="keywords" content="[^"]+"/u.test(html);
  const needsDescription = shouldBackfillDescription(meta.description, descriptions);
  if (hasKeywords && !needsDescription) return false;
 
  // Suppress leaky tokens (run-ids, "analysis run" jargon) from both
  // the Markdown body we feed the resolver AND the `manifest.description`
  // override, so the resolver derives `<meta description>` from a clean
  // editorial signal rather than echoing the legacy junk back unchanged.
  const titleHasLeaks = descriptionHasLeakyToken(meta.title);
  const descHasLeaks = descriptionHasLeakyToken(meta.description);
  const safeTitle = titleHasLeaks ? formatSlug(parsed.slug) : meta.title;
  const safeDescription = descHasLeaks ? '' : meta.description;
 
  const articleType = String(detectCategory(parsed.slug));
  const resolved = resolveArticleMetadata({
    articleType,
    date: parsed.date,
    markdown: `# ${safeTitle || formatSlug(parsed.slug)}\n\n${safeDescription}`,
    manifest: buildBackfillManifest(parsed.slug, safeTitle, safeDescription, needsDescription),
  });
  const entry = Object.getOwnPropertyDescriptor(resolved, parsed.lang)?.value as
    | { readonly title: string; readonly description: string; readonly keywords: readonly string[] }
    | undefined;
  const fallbackKeywords = buildSeoKeywords(
    parsed.lang,
    articleType,
    parsed.date,
    parsed.slug,
    safeTitle,
    safeDescription
  );
  // Never echo a leaky description into the rewrite, even as a last-resort
  // fallback. If the resolver produced nothing clean, fall back to a
  // page-specific stub built from the slug.
  const resolverDescription = entry?.description ?? '';
  const baseDescription =
    resolverDescription && !descriptionHasLeakyToken(resolverDescription)
      ? resolverDescription
      : safeDescription || formatSlug(parsed.slug);
  const description = needsDescription
    ? buildLegacyBackfillDescription(parsed.date, parsed.slug, parsed.lang, baseDescription, {
        forceContextPrefix: true,
      })
    : meta.description;
  const keywords = entry?.keywords ?? fallbackKeywords;
  const nextHtml = applyArticleSeoBackfill(html, description, keywords);
  if (nextHtml === html) return false;
  atomicWrite(filepath, nextHtml);
  return true;
}
 
/**
 * Prefix legacy descriptions with date and **localized** category label
 * so duplicate strings become page-specific before the 180-character
 * snippet cap. Two-tier strategy:
 *
 * 1. **Substantive resolver output** (≥{@link MIN_ARTICLE_DESCRIPTION_LENGTH}
 *    chars) is returned **unchanged** — no prefix is prepended. The
 *    description is already unique per page because it contains
 *    article-specific editorial content (named bills, vote outcomes,
 *    coalition dynamics). Adding a bureaucratic prefix in that case
 *    only steals SERP characters from real content.
 * 2. **Short / placeholder** descriptions get a localized prefix
 *    `${date} — ${ARTICLE_TYPE_LABELS[lang][category]} —` so the
 *    duplicate-deduper still works on legacy articles whose
 *    `<meta description>` is `formatSlug(slug)`-only or a generic stub.
 *    The category noun is **translated** via {@link ARTICLE_TYPE_LABELS}
 *    so Arabic / Hebrew / Swedish cards no longer carry the English
 *    "EN Committee Reports" wart that the prior single-language
 *    `formatSlug(slug)` form produced.
 *
 * @param date - Article date (ISO YYYY-MM-DD)
 * @param slug - Article slug (used to derive the category)
 * @param lang - Article language (ISO 639-1 lower-case code)
 * @param description - Candidate description (resolver output preferred)
 * @param options - Backfill options
 * @param options.forceContextPrefix - Force date/language/category prefix
 *   even when the description is already substantive
 * @returns Page-specific description, prefix-free when description is
 *   already substantive
 */
export function buildLegacyBackfillDescription(
  date: string,
  slug: string,
  lang: string,
  description: string,
  options: { readonly forceContextPrefix?: boolean } = {}
): string {
  const trimmedDescription = description.trim();
  if (trimmedDescription.length >= MIN_ARTICLE_DESCRIPTION_LENGTH && !options.forceContextPrefix) {
    return capDescriptionLength(trimmedDescription);
  }
  const category = detectCategory(slug);
  const langCode = (lang || 'en').toLowerCase() as LanguageCode;
  const categoryLabels = getLocalizedString(ARTICLE_TYPE_LABELS, langCode) as ArticleCategoryLabels;
  const label = categoryLabels[category] ?? formatSlug(slug);
  const qualifier = buildLegacySlugQualifier(slug, label);
  const languageLabel = legacyLanguageLabel(langCode);
  const prefix = [date, languageLabel, label, qualifier]
    .filter((part) => part.length > 0)
    .join(' — ');
  const body = trimmedDescription || label;
  const contextual = `${prefix} — ${body}`.replace(/\s+/g, ' ').trim();
  return capDescriptionLength(contextual);
}
 
/**
 * Resolve the human language label used to make otherwise-identical
 * cross-locale legacy descriptions unique.
 *
 * @param lang - Language code
 * @returns Local language name, or the raw code if unknown
 */
function legacyLanguageLabel(lang: LanguageCode): string {
  const descriptor = Object.getOwnPropertyDescriptor(LEGACY_LANGUAGE_LABELS, lang);
  return typeof descriptor?.value === 'string' ? descriptor.value : lang;
}
 
/**
 * Build an optional slug-derived qualifier for legacy pages that share the
 * same date and article category (for example same-day `*-run2` variants).
 *
 * @param slug - Article slug without date/language suffix
 * @param localizedLabel - Localized category label already present in prefix
 * @returns Human-readable qualifier, or empty when it would duplicate label
 */
function buildLegacySlugQualifier(slug: string, localizedLabel: string): string {
  const formatted = formatSlug(slug).trim();
  Iif (!formatted) return '';
  const normalizedFormatted = normalizeLegacyQualifier(formatted);
  const normalizedLabel = normalizeLegacyQualifier(localizedLabel);
  if (!normalizedFormatted || normalizedFormatted === normalizedLabel) return '';
  return formatted;
}
 
/**
 * Normalize a prefix component for duplicate detection.
 *
 * @param value - Candidate text
 * @returns Lower-case alphanumeric text
 */
function normalizeLegacyQualifier(value: string): string {
  return value
    .toLowerCase()
    .replace(/[^\p{L}\p{N}]+/gu, ' ')
    .trim();
}
 
/**
 * Clamp a description to the 180-character SERP-friendly cap with a
 * trailing ellipsis when truncated. Extracted from
 * {@link buildLegacyBackfillDescription} so both the prefix-free and
 * prefixed branches share identical clamping behaviour.
 *
 * @param text - Candidate description
 * @returns Description ≤180 chars, ending with `…` on truncation
 */
function capDescriptionLength(text: string): string {
  if (text.length <= 180) return text;
  return `${text.slice(0, 177).replace(/[.,;:—\s-]+$/u, '')}…`;
}
 
/**
 * Detect whether a legacy article description contains the run-id or
 * "analysis run" jargon that was prevalent in pre-aggregator brief
 * authorship. These tokens are deemed unfit for `<meta description>`
 * regardless of length and force a backfill rewrite.
 *
 * @param description - Current description value
 * @returns True when the description contains a forbidden internal token
 */
function descriptionHasLeakyToken(description: string): boolean {
  if (!description) return false;
  const lower = description.toLowerCase();
  if (lower.includes('analysis run')) return true;
  return LEAKY_RUNID_RE.test(description);
}
 
/**
 * Determine whether a meta description needs backfilling.
 *
 * @param description - Current description
 * @param descriptions - Description frequency map
 * @returns True when the description is missing, short, duplicated, or
 *   contains internal run-id tokens that must not appear in SEO surfaces
 */
function shouldBackfillDescription(
  description: string,
  descriptions: ReadonlyMap<string, number>
): boolean {
  return (
    !description ||
    description.length < MIN_ARTICLE_DESCRIPTION_LENGTH ||
    (descriptions.get(description) ?? 0) > 1 ||
    descriptionHasLeakyToken(description)
  );
}
 
/**
 * Build the manifest projection for legacy SEO backfill.
 *
 * @param runId - Stable slug/run id
 * @param title - Current article title
 * @param description - Current article description
 * @param includeDescription - Whether to use the current description as a manifest override
 * @returns Manifest projection accepted by `resolveArticleMetadata`
 */
function buildBackfillManifest(
  runId: string,
  title: string,
  description: string,
  includeDescription: boolean
): { readonly runId: string; readonly title: string; readonly description?: string } {
  return {
    runId,
    title,
    ...(includeDescription ? { description } : {}),
  };
}
 
/**
 * Read an article HTML file, returning an empty string when unavailable.
 *
 * @param filepath - Absolute HTML file path
 * @returns File content or empty string
 */
function readArticleHtml(filepath: string): string {
  try {
    return path.isAbsolute(filepath) ? requireFsRead(filepath) : '';
  } catch {
    return '';
  }
}
 
/**
 * Isolated file read helper to keep try/catch bodies small.
 *
 * @param filepath - Absolute file path
 * @returns File text
 */
function requireFsRead(filepath: string): string {
  return fs.readFileSync(filepath, 'utf8');
}
 
/**
 * Apply SEO meta tag replacements to a complete article HTML document.
 *
 * Exported for the regression test in
 * `test/unit/news-indexes-jsonld-description-regex.test.js`, which
 * locks in the JSON-LD description regex against the duplicate-tail
 * bug (the legacy `"description":"[^"]*"` pattern terminated at the
 * first JSON-escaped quote `\"` and left the previous description's
 * tail in place, accumulating duplicates on every prebuild run).
 *
 * @param html - Existing article HTML
 * @param description - Backfilled meta description
 * @param keywords - Backfilled keyword list
 * @returns Updated HTML
 */
export function applyArticleSeoBackfill(
  html: string,
  description: string,
  keywords: readonly string[]
): string {
  const safeDescription = escapeHTML(description);
  const safeKeywords = escapeHTML(keywords.join(', '));
  let next = html
    .replace(
      /<meta name="description" content="[^"]*">/u,
      `<meta name="description" content="${safeDescription}">`
    )
    .replace(
      /<meta property="og:description" content="[^"]*">/u,
      `<meta property="og:description" content="${safeDescription}">`
    )
    .replace(
      /<meta name="twitter:description" content="[^"]*">/u,
      `<meta name="twitter:description" content="${safeDescription}">`
    );
 
  if (/<meta name="keywords" content="[^"]*">/u.test(next)) {
    next = next.replace(
      /<meta name="keywords" content="[^"]*">/u,
      `<meta name="keywords" content="${safeKeywords}">`
    );
  } else {
    next = next.replace(
      /(<meta name="description" content="[^"]*">\n)/u,
      `$1  <meta name="keywords" content="${safeKeywords}">\n`
    );
  }
 
  const jsonDescription = JSON.stringify(description).slice(1, -1).replace(/</g, '\\u003c');
  // Match a JSON string value safely: every `"` inside the description
  // is JSON-escaped as `\"`, so the inner pattern must accept either an
  // escape sequence (`\\.`) or a non-quote/non-backslash character —
  // otherwise the match terminates at the first `\"` and leaves the
  // tail of the previous description in place, which on subsequent
  // prebuild runs appears to "duplicate" the description fragment.
  next = next.replace(/"description":"(?:\\.|[^"\\])*"/u, `"description":"${jsonDescription}"`);
  // Heal any previously-corrupted JSON-LD where the old buggy regex
  // left an orphan tail between the description's closing quote and
  // the next known field (`,"datePublished"`). The pattern is
  // idempotent: when there is no orphan, `[^,]*` matches the empty
  // string and the file is unchanged.
  next = next.replace(/("description":"(?:\\.|[^"\\])*")[^,]*(,"datePublished")/u, '$1$2');
  return next;
}
 
/**
 * Build hreflang `<link rel="alternate">` tags for an article slug.
 * Produces one tag per supported language plus an `x-default` pointing at
 * the English variant, all using absolute URLs.
 *
 * @param articleSlug - Slug without language suffix (e.g. `2026-02-24-propositions`)
 * @returns Newline-joined `<link>` tags
 */
function buildArticleHreflang(articleSlug: string): string {
  const entries = ALL_LANGUAGES.map(
    (code) =>
      `  <link rel="alternate" hreflang="${code}" href="${BASE_URL}/news/${articleSlug}-${code}.html">`
  );
  entries.push(
    `  <link rel="alternate" hreflang="x-default" href="${BASE_URL}/news/${articleSlug}-en.html">`
  );
  return entries.join('\n');
}
 
/**
 * Inject hreflang links into an article that has none.
 *
 * @param html - Article HTML content
 * @param hreflangBlock - Pre-built hreflang link block
 * @returns Updated HTML, or original if no change needed
 */
function injectHreflangLinks(html: string, hreflangBlock: string): string {
  return html.replace(/(<\/head>)/u, `${hreflangBlock}\n$1`);
}
 
/**
 * Replace existing relative hreflang links with absolute URLs.
 *
 * @param html - Article HTML content
 * @param hreflangBlock - Pre-built hreflang link block with absolute URLs
 * @returns Updated HTML, or original if no change needed
 */
function fixRelativeHreflangLinks(html: string, hreflangBlock: string): string {
  const stripped = html.replace(
    /\s*<link\s+rel="alternate"\s+hreflang="[^"]*"\s+href="[^"]*">\n?/gu,
    ''
  );
  return stripped.replace(/(<\/head>)/u, `${hreflangBlock}\n$1`);
}
 
/**
 * Backfill hreflang alternate links for all article HTML files.
 *
 * Handles three cases:
 * 1. Articles with no hreflang links at all → inject the full block before `</head>`
 * 2. Articles with relative hreflang URLs → replace with absolute URLs
 * 3. Articles already correct → skip
 *
 * @param filenames - News article filenames
 * @returns Number of HTML files updated
 */
export function backfillArticleHreflang(filenames: readonly string[]): number {
  let updated = 0;
  for (const filename of filenames) {
    if (backfillOneArticleHreflang(filename)) updated++;
  }
  return updated;
}
 
/**
 * Backfill hreflang for a single article file.
 *
 * @param filename - News article filename
 * @returns True when the file was updated
 */
function backfillOneArticleHreflang(filename: string): boolean {
  const parsed = parseArticleFilename(filename);
  if (!parsed) return false;
  const filepath = path.join(NEWS_DIR, filename);
  const html = readArticleHtml(filepath);
  Iif (!html) return false;
 
  const articleSlug = `${parsed.date}-${parsed.slug}`;
  const hreflangBlock = buildArticleHreflang(articleSlug);
  const hasHreflang = /<link\s+rel="alternate"\s+hreflang="/u.test(html);
 
  let next: string;
  if (!hasHreflang) {
    next = injectHreflangLinks(html, hreflangBlock);
  } else {
    const hasRelative = /<link\s+rel="alternate"\s+hreflang="[^"]*"\s+href="(?!https?:\/\/)/u.test(
      html
    );
    if (!hasRelative) return false;
    next = fixRelativeHreflangLinks(html, hreflangBlock);
  }
 
  Iif (next === html) return false;
  atomicWrite(filepath, next);
  return true;
}