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 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 | 15x 1x 1x 14x 20x 72x 72x 3x 69x 69x 69x 2x 2x 4x 2x 6x 6x 6x 6x 6x 2x 4x 4x 4x 2x 9x 14x 36x 36x 2x 3x 3x 16x 3x 3x 3x 3x 2x 2x 2x 2x 1x 1x 3x 3x 3x 3x 4x 3x 3x 3x 3x 3x 3x 1x 1x 1x 2x 2x 4x 1x 1x 10x 9x 9x 9x 9x 8x 8x 4x 4x 2x 2x 4x 8x 8x 8x 3x 1x 1x 3x 3x 3x 4x 4x 3x 3x 2x 4x 4x 4x 4x 3x 3x 2x 1x 8x 8x 7x 7x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 3x 3x 2x 1x 8x 5x 5x 33x 28x 28x 28x 28x 28x 28x 3x 3x 3x 27x 24x 24x 14x 27x 27x 16x 28x 19579x 14x 14x 14x 14x 7x 6x 6x 36x 6x 6x 36x 36x 11x 11x 13x 12x 12x 6x 6x 6x 14x 2x 2x 2x 2x | // SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
/**
* @module Utils/FileUtils
* @description Shared file system utilities for news article operations
*/
import { randomUUID } from 'crypto';
import fs from 'fs';
import path from 'path';
import { NEWS_DIR, ARTICLE_FILENAME_PATTERN } from '../constants/config.js';
import { ALL_LANGUAGES } from '../constants/language-core.js';
import type { AnalysisFileEntry, LanguageCode, ParsedArticle } from '../types/index.js';
/**
* Get all news article HTML files from the news directory
*
* @param newsDir - News directory path (defaults to NEWS_DIR)
* @returns List of article filenames
*/
export function getNewsArticles(newsDir: string = NEWS_DIR): string[] {
if (!fs.existsSync(newsDir)) {
console.log('📁 News directory does not exist yet');
return [];
}
const files = fs.readdirSync(newsDir);
return files.filter((f) => f.endsWith('.html') && !f.startsWith('index-'));
}
/**
* Parse article filename to extract metadata
*
* @param filename - Article filename (e.g., "2025-01-15-week-ahead-en.html")
* @returns Parsed metadata or null if filename doesn't match pattern
*/
export function parseArticleFilename(filename: string): ParsedArticle | null {
const match = filename.match(ARTICLE_FILENAME_PATTERN);
if (!match) {
return null;
}
const langCandidate = match[3] as string;
Iif (!ALL_LANGUAGES.includes(langCandidate as LanguageCode)) {
return null;
}
return {
date: match[1] as string,
slug: match[2] as string,
lang: langCandidate as LanguageCode,
filename,
};
}
/**
* Group articles by language code
*
* @param articles - List of article filenames
* @param languages - Supported language codes
* @returns Articles grouped by language, sorted newest first
*/
export function groupArticlesByLanguage(
articles: string[],
languages: readonly string[]
): Record<string, ParsedArticle[]> {
const grouped: Record<string, ParsedArticle[]> = {};
for (const lang of languages) {
grouped[lang] = [];
}
for (const article of articles) {
const parsed = parseArticleFilename(article);
Eif (parsed) {
const bucket = grouped[parsed.lang];
Eif (bucket) {
bucket.push(parsed);
}
}
}
// Sort by date (newest first)
for (const lang in grouped) {
const bucket = grouped[lang];
Eif (bucket) {
bucket.sort((a, b) => b.date.localeCompare(a.date));
}
}
return grouped;
}
/**
* Format slug for display (hyphen-separated to Title Case)
*
* @param slug - Hyphen-separated slug string
* @returns Formatted title string
*/
export function formatSlug(slug: string): string {
return slug
.split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
/**
* Get file modification time as YYYY-MM-DD string
*
* @param filepath - Path to file
* @returns Last modified date in YYYY-MM-DD format
*/
export function getModifiedDate(filepath: string): string {
const stats = fs.statSync(filepath);
return stats.mtime.toISOString().slice(0, 10);
}
/**
* Format date for article slug
*
* @param date - Date to format (defaults to now)
* @returns Formatted date string (YYYY-MM-DD)
*/
export function formatDateForSlug(date: Date = new Date()): string {
return date.toISOString().slice(0, 10);
}
/**
* Calculate read time estimate from content
*
* @param content - Article content text
* @param wordsPerMinute - Reading speed (default 250)
* @returns Estimated read time in minutes
*/
export function calculateReadTime(content: string, wordsPerMinute: number = 250): number {
const words = content.split(/\s+/).length;
return Math.ceil(words / wordsPerMinute);
}
/**
* Ensure a directory exists, creating it recursively if needed
*
* @param dirPath - Directory path to ensure
*/
export function ensureDirectoryExists(dirPath: string): void {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
}
/**
* Attempt to atomically claim a directory by creating it non-recursively.
*
* @param dirPath - Directory path to claim
* @returns `true` when the directory was created by this call, otherwise `false`
*/
function claimDir(dirPath: string): boolean {
// Ensure parent exists (recursive: true never throws EEXIST)
fs.mkdirSync(path.dirname(dirPath), { recursive: true });
try {
// Non-recursive create: EEXIST means another run already claimed it
fs.mkdirSync(dirPath, { recursive: false });
return true;
} catch (err: unknown) {
if ((err as NodeJS.ErrnoException).code === 'EEXIST') {
return false;
}
throw err;
}
}
/**
* Resolve a unique directory path by appending a numeric suffix (-2, -3, …)
* when the preferred directory has already been claimed by a completed run.
*
* The base directory is treated as occupied when it contains `manifest.json`
* (written at the end of a successful analysis run). A directory without
* `manifest.json` is considered available — this allows the `skipCompleted`
* feature to resume an incomplete run in the same directory.
*
* Suffixed candidates (-2, -3, …) are claimed atomically via non-recursive
* `mkdirSync`, preventing TOCTOU races when concurrent workflow runs
* attempt to claim the same candidate.
*
* @param baseDir - The preferred directory path (e.g. `analysis/daily/2026-04-02/breaking`)
* @returns The original `baseDir` when no completed run exists there, or a
* suffixed variant (e.g. `analysis/daily/2026-04-02/breaking-2`) otherwise.
*/
export function resolveUniqueAnalysisDir(baseDir: string): string {
// If the directory doesn't exist yet or has no manifest from a prior
// completed run, use it as-is. This supports the skipCompleted feature
// which resumes an incomplete run in the same directory.
if (!fs.existsSync(path.join(baseDir, 'manifest.json'))) {
return baseDir;
}
// Directory already has a completed run — find the next available suffix.
// Use atomic mkdirSync to prevent TOCTOU races when parallel workflow
// runs attempt to claim the same suffixed candidate concurrently.
let suffix = 2;
const MAX_SUFFIX = 100;
while (suffix <= MAX_SUFFIX) {
const candidate = `${baseDir}-${suffix}`;
if (claimDir(candidate)) {
return candidate;
}
suffix++;
}
// Fallback: use UUID-suffixed directory to guarantee uniqueness
const candidate = `${baseDir}-${randomUUID().slice(0, 8)}`;
fs.mkdirSync(candidate, { recursive: true });
return candidate;
}
// ─── Manifest history (shared same-day folder support) ──────────────────────
/**
* Single entry in `manifest.json.history[]` recording one run that wrote
* artifacts into a shared same-day analysis folder.
*
* When the analysis workflow re-runs against the same
* `analysis/daily/${DATE}/${TYPE}/` directory, it appends a new entry
* instead of triggering the `-2` suffix in {@link resolveUniqueAnalysisDir}.
* The article workflow reads this history to decide whether to consume or
* skip the folder.
*/
export interface AnalysisManifestHistoryEntry {
/** Stable identifier for this attempt (e.g. `breaking-run60-1729876543`) */
readonly runId: string;
/** ISO-8601 UTC timestamp when the run started */
readonly startedAt: string;
/** ISO-8601 UTC timestamp when the run finished (or last wrote) */
readonly finishedAt: string;
/** Short git SHA of the commit the run was produced against (optional) */
readonly commit?: string;
/** Stage-C result: GREEN | GREEN_WITH_WARNINGS | ANALYSIS_ONLY | PENDING */
readonly gateResult: 'GREEN' | 'GREEN_WITH_WARNINGS' | 'ANALYSIS_ONLY' | 'PENDING';
/** Relative-path list of analysis files written or refreshed during the run */
readonly filesWritten: readonly string[];
}
/**
* Merge a new run entry into the `history[]` array of the manifest file at
* `manifestPath`, creating the file if it doesn't exist.
*
* The merge is additive: existing history entries are preserved, and the new
* entry is appended. When `manifestPath` already has a manifest with
* top-level fields (runId, date, articleType, etc.), those fields are left
* untouched — only `history[]` is appended to and the top-level
* `updatedAt` timestamp is refreshed.
*
* This supports the stable same-day analysis folder layout
* (`analysis/daily/${DATE}/${TYPE}/`) where repeated analysis runs
* overwrite/upgrade artifacts but each attempt adds a history entry.
*
* @param manifestPath - Absolute path to the run's manifest.json.
* @param entry - History entry describing this run.
*/
export function mergeManifestHistory(
manifestPath: string,
entry: AnalysisManifestHistoryEntry
): void {
ensureDirectoryExists(path.dirname(manifestPath));
let manifest: Record<string, unknown> = {};
if (fs.existsSync(manifestPath)) {
try {
const raw = fs.readFileSync(manifestPath, 'utf-8');
const parsed: unknown = JSON.parse(raw);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
manifest = parsed as Record<string, unknown>;
}
} catch {
// Corrupt manifest — start fresh but keep a diagnostic field.
manifest = { corruptManifestRecoveredAt: new Date().toISOString() };
}
}
const existingHistory = Array.isArray(manifest['history'])
? (manifest['history'] as AnalysisManifestHistoryEntry[])
: [];
manifest['history'] = [...existingHistory, entry];
manifest['updatedAt'] = entry.finishedAt;
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf-8');
}
/**
* Read the `gateResult` from the most recent entry in the manifest's
* `history[]` array.
*
* Used by the article workflow to decide whether to consume a committed
* analysis folder: `GREEN` proceeds to Stage D, everything else exits noop.
*
* @param manifestPath - Absolute path to the run's manifest.json.
* @returns The latest `gateResult`, or `'PENDING'` when the manifest is
* missing, unreadable, or contains no history entries.
*/
export function readLatestGateResult(
manifestPath: string
): AnalysisManifestHistoryEntry['gateResult'] {
if (!fs.existsSync(manifestPath)) return 'PENDING';
try {
const raw = fs.readFileSync(manifestPath, 'utf-8');
const parsed: unknown = JSON.parse(raw);
Iif (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return 'PENDING';
const history = (parsed as Record<string, unknown>)['history'];
if (!Array.isArray(history) || history.length === 0) {
// Back-compat: a manifest without a history[] might carry gateResult
// directly at the top level during the transition.
const direct = (parsed as Record<string, unknown>)['gateResult'];
Eif (
direct === 'GREEN' ||
direct === 'GREEN_WITH_WARNINGS' ||
direct === 'ANALYSIS_ONLY' ||
direct === 'PENDING'
) {
return direct;
}
return 'PENDING';
}
const last = history[history.length - 1] as AnalysisManifestHistoryEntry | undefined;
const gate = last?.gateResult;
if (
gate === 'GREEN' ||
gate === 'GREEN_WITH_WARNINGS' ||
gate === 'ANALYSIS_ONLY' ||
gate === 'PENDING'
) {
return gate;
}
return 'PENDING';
} catch {
return 'PENDING';
}
}
/**
* Find the most-recent **resolved** (non-`PENDING`) `gateResult` in a
* manifest's `history[]` array by searching backward from the end.
*
* Used by the `--analysis-only` wrap-up path to carry forward the Stage-C
* result already written by the AI agent, so the discovery history entry
* produced by `runAnalysisStage` preserves `GREEN` / `ANALYSIS_ONLY` instead
* of clobbering it with the default `PENDING`.
*
* @param manifestPath - Absolute path to the run's manifest.json.
* @returns The latest non-PENDING `gateResult`, or `'PENDING'` when none
* exists or the manifest is missing / unreadable.
*/
export function readLatestResolvedGateResult(
manifestPath: string
): AnalysisManifestHistoryEntry['gateResult'] {
if (!fs.existsSync(manifestPath)) return 'PENDING';
try {
const raw = fs.readFileSync(manifestPath, 'utf-8');
const parsed: unknown = JSON.parse(raw);
Iif (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return 'PENDING';
const history = (parsed as Record<string, unknown>)['history'];
if (!Array.isArray(history) || history.length === 0) {
// Back-compat: older manifests may carry a resolved gateResult directly
// at the top level without a history[] array. Only honour non-PENDING
// values — a stale PENDING at the top level must not be treated as
// resolved, because that defeats the carry-forward purpose of this helper.
const direct = (parsed as Record<string, unknown>)['gateResult'];
if (direct === 'GREEN' || direct === 'GREEN_WITH_WARNINGS' || direct === 'ANALYSIS_ONLY') {
return direct;
}
return 'PENDING';
}
// Search from the end to find the most recent non-PENDING result.
for (let i = history.length - 1; i >= 0; i--) {
const entry = history[i] as AnalysisManifestHistoryEntry | undefined;
const gate = entry?.gateResult;
if (gate === 'GREEN' || gate === 'GREEN_WITH_WARNINGS' || gate === 'ANALYSIS_ONLY') {
return gate;
}
}
return 'PENDING';
} catch {
return 'PENDING';
}
}
/**
* Resolve a unique filename by appending a numeric suffix (-2, -3, …) before
* the file extension when the file already exists.
*
* This prevents repeated workflow runs from overwriting previously committed
* news articles.
*
* @param filepath - The preferred file path (e.g. `news/2026-04-02-breaking-en.html`)
* @returns The original path when the file doesn't exist, or a suffixed
* variant (e.g. `news/2026-04-02-breaking-en-2.html`) otherwise.
*/
export function resolveUniqueFilePath(filepath: string): string {
if (!fs.existsSync(filepath)) {
return filepath;
}
const dir = path.dirname(filepath);
const ext = path.extname(filepath);
const base = path.basename(filepath, ext);
let suffix = 2;
const MAX_SUFFIX = 100;
while (suffix <= MAX_SUFFIX) {
const candidate = path.join(dir, `${base}-${suffix}${ext}`);
if (!fs.existsSync(candidate)) {
return candidate;
}
suffix++;
}
return path.join(dir, `${base}-${randomUUID().slice(0, 8)}${ext}`);
}
/**
* Write content to a file with UTF-8 encoding
*
* @param filepath - Output file path
* @param content - File content
*/
export function writeFileContent(filepath: string, content: string): void {
const dir = path.dirname(filepath);
ensureDirectoryExists(dir);
fs.writeFileSync(filepath, content, 'utf-8');
}
/**
* Remove a file, ignoring ENOENT (file already deleted by another writer).
*
* @param filepath - Path to the file to remove
*/
function unlinkIfExists(filepath: string): void {
try {
fs.unlinkSync(filepath);
} catch (err: unknown) {
const code = err instanceof Error ? (err as NodeJS.ErrnoException).code : '';
Iif (code !== 'ENOENT') {
throw err;
}
}
}
/**
* Attempt to rename `src` to `dest` with a bounded retry loop.
*
* On each attempt the existing destination is removed first, then
* `renameSync` is retried. `EEXIST`/`EPERM` failures from concurrent
* writers are tolerated for up to `maxRetries` attempts.
*
* @param src - Source (temp) file path
* @param dest - Final destination path
* @param maxRetries - Maximum number of unlink-then-rename attempts
*/
function renameWithRetry(src: string, dest: string, maxRetries: number): void {
for (let attempt = 0; attempt < maxRetries; attempt++) {
unlinkIfExists(dest);
try {
fs.renameSync(src, dest);
return;
} catch (retryErr: unknown) {
const retryCode = retryErr instanceof Error ? (retryErr as NodeJS.ErrnoException).code : '';
if ((retryCode === 'EEXIST' || retryCode === 'EPERM') && attempt < maxRetries - 1) {
continue;
}
throw retryErr;
}
}
}
/**
* Best-effort removal of a temporary file. Ignores ENOENT (the file was
* already renamed or never created) but logs a warning for other errors
* (e.g. EBUSY, EACCES) so operators can detect leaked temp files.
*
* @param tempPath - Path to the temp file to remove
*/
function cleanupTempFile(tempPath: string): void {
try {
fs.unlinkSync(tempPath);
} catch (unlinkErr: unknown) {
const errno =
unlinkErr && typeof unlinkErr === 'object' ? (unlinkErr as NodeJS.ErrnoException) : undefined;
if (errno?.code !== 'ENOENT') {
const message =
errno && typeof errno.message === 'string' ? errno.message : String(unlinkErr);
const code = errno?.code ?? 'UNKNOWN';
console.warn(
`atomicWrite: failed to remove temporary file "${tempPath}" (code: ${code}): ${message}`
);
}
}
}
/**
* Write content to a file atomically.
*
* Writes to a uniquely-named temporary file in the same directory first, then
* renames it to the final path. The temp filename includes the PID and a random
* UUID so that concurrent callers targeting the same destination never collide
* on the intermediate file. If the rename fails the temp file is cleaned up in
* a `finally` block. On platforms where `renameSync` does not overwrite an
* existing destination (e.g. Windows), the error is caught and the target is
* removed before retrying the rename.
*
* @param filepath - Final output file path
* @param content - File content to write
*/
export function atomicWrite(filepath: string, content: string): void {
const dir = path.dirname(filepath);
ensureDirectoryExists(dir);
const uniqueSuffix = `${process.pid}-${randomUUID()}`;
const tempPath = `${filepath}.${uniqueSuffix}.tmp`;
try {
fs.writeFileSync(tempPath, content, 'utf-8');
try {
fs.renameSync(tempPath, filepath);
} catch (err: unknown) {
const code = err instanceof Error ? (err as NodeJS.ErrnoException).code : '';
if (code === 'EEXIST' || code === 'EPERM') {
renameWithRetry(tempPath, filepath, 3);
} else {
throw err;
}
}
} finally {
cleanupTempFile(tempPath);
}
}
/**
* Check whether a news article file already exists on disk.
*
* This is used by generation pipelines to skip work when a prior workflow run
* (or the same run) has already produced the article, avoiding unnecessary
* regeneration and potential merge conflicts.
*
* @param slug - Article slug including date prefix (e.g. `"2025-01-15-week-ahead"`)
* @param lang - Language code (e.g. `"en"`)
* @param newsDir - Absolute path to the news output directory (defaults to NEWS_DIR)
* @returns `true` when the article file exists
*/
export function checkArticleExists(
slug: string,
lang: string,
newsDir: string = NEWS_DIR
): boolean {
const filename = `${slug}-${lang}.html`;
return fs.existsSync(path.join(newsDir, filename));
}
/**
* Decode the 5 HTML entities produced by escapeHTML() back to plain text.
* Used when extracting text from our own generated HTML to obtain unescaped values.
*
* IMPORTANT: `&` MUST be decoded last. Decoding it first would convert
* `&lt;` to `<` before the `<` → `<` replacement runs, causing
* double-decoding. The correct order is: decode all specific entities first,
* then decode `&` as the final step.
*
* @param str - HTML string with entities
* @returns Plain text with entities decoded
*/
function decodeHtmlEntities(str: string): string {
return str
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&');
}
/**
* Extract title and description from a generated article HTML file.
* Reads the predictable template structure produced by the aggregator
* article generator. Falls back to empty strings when the file cannot
* be read. HTML entities from the template are decoded to produce
* plain text.
*
* Title resolution order:
* 1. `<head><title>` value with the trailing ` — EU Parliament Monitor`
* (or legacy ` | EU Parliament Monitor`) site-suffix stripped.
* This is where the editorial-highlights resolver + SEO backport
* script write their output, so using it as the primary source
* surfaces the strongest headline on index cards and sitemaps.
* 2. First body `<h1>` — fallback for files whose `<title>` was never
* refreshed.
*
* NOTE: The meta description regex relies on the template's use of
* escapeHTML(), which converts `"` to `"`. Because descriptions are
* always stored with double-quote delimiters and inner quotes are
* HTML-encoded, the `[^"]+` pattern safely captures the full value.
*
* @param filepath - Path to the article HTML file
* @returns Object with title (from head-title, else first body h1) and
* description (from meta description)
*/
export function extractArticleMeta(filepath: string): { title: string; description: string } {
let title = '';
let description = '';
try {
const content = fs.readFileSync(filepath, 'utf-8');
// Prefer the <head><title> value (with the " — EU Parliament Monitor"
// or " | EU Parliament Monitor" site-suffix stripped) — that is where
// the SEO-facing editorial headline resolver writes its output. Fall
// back to the first body <h1> for older files where <title> was
// never refreshed.
const headTitleMatch = content.match(/<title[^>]*>([^<]+)<\/title>/u);
if (headTitleMatch?.[1]) {
const rawTitle = decodeHtmlEntities(headTitleMatch[1].trim());
const stripped = rawTitle
.replace(/\s*—\s*EU Parliament Monitor\s*$/u, '')
.replace(/\s*\|\s*EU Parliament Monitor\s*$/u, '')
.trim();
Eif (stripped.length > 0) title = stripped;
}
if (!title) {
// Matches h1 with any attributes but only plain-text content (no
// nested tags). The template always writes plain escaped text in
// h1, so this is correct.
const titleMatch = content.match(/<h1[^>]*>([^<]+)<\/h1>/u);
if (titleMatch?.[1]) {
title = decodeHtmlEntities(titleMatch[1].trim());
}
}
const descMatch = content.match(/<meta name="description" content="([^"]+)"/u);
if (descMatch?.[1]) {
description = decodeHtmlEntities(descMatch[1]);
}
} catch {
// File not readable – return empty strings
}
return { title, description };
}
/**
* Escape special HTML characters to prevent XSS
*
* @param str - Raw string to escape
* @returns HTML-safe string
*/
export function escapeHTML(str: string): string {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
/**
* Validate that a URL uses a safe scheme (http or https)
*
* @param url - URL string to validate
* @returns true if URL has a safe scheme
*/
export function isSafeURL(url: string): boolean {
try {
const parsed = new URL(url);
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
} catch {
return false;
}
}
/** Result of article HTML validation */
export interface ArticleValidationResult {
/** Whether the article passes all structural checks */
valid: boolean;
/** List of missing elements */
errors: readonly string[];
}
/** Required structural elements that every article must contain */
const REQUIRED_ARTICLE_ELEMENTS: ReadonlyArray<{
selector: string | readonly string[];
label: string;
}> = [
{
selector: ['class="site-header__langs"', 'class="language-switcher"'],
label: 'language switcher nav',
},
{ selector: 'class="article-top-nav"', label: 'article-top-nav (back button)' },
{ selector: 'class="site-header"', label: 'site-header' },
{ selector: 'class="skip-link"', label: 'skip-link' },
{ selector: 'class="reading-progress"', label: 'reading-progress bar' },
{ selector: '<main id="main"', label: 'main content wrapper' },
{ selector: 'class="site-footer"', label: 'site-footer' },
] as const;
/**
* Validate that generated article HTML includes all required structural elements.
*
* This is the primary validation gate — articles must be generated correctly
* by the template. The fix-articles script is only a fallback for legacy articles.
*
* @param html - Complete HTML string of the article
* @returns Validation result with errors list (empty if valid)
*/
export function validateArticleHTML(html: string): ArticleValidationResult {
const errors: string[] = [];
for (const element of REQUIRED_ARTICLE_ELEMENTS) {
const sel = element.selector;
const found = Array.isArray(sel)
? sel.some((s) => html.includes(s))
: html.includes(sel as string);
if (!found) {
errors.push(`Missing required element: ${element.label}`);
}
}
return { valid: errors.length === 0, errors };
}
/**
* Well-known analysis subdirectories scanned for transparency links.
* Matches the subdirectory structure created by agentic workflows.
*/
const DISCOVERY_SUBDIRS = [
'classification',
'threat-assessment',
'risk-scoring',
'existing',
'documents',
'intelligence',
] as const;
/**
* Maps canonical analysis filenames (without `.md`) to their canonical
* analysis method IDs used by `METHOD_LABEL_MAP` in `article-template.ts`.
*
* Per `analysis/README.md`, some canonical filenames differ from the method
* identifier (e.g. the `stakeholder-analysis` method produces
* `stakeholder-impact.md`). This mapping ensures localized labels render
* correctly in the analysis transparency section.
*/
const FILENAME_TO_METHOD: Readonly<Record<string, string>> = {
'stakeholder-impact': 'stakeholder-analysis',
'coalition-dynamics': 'coalition-analysis',
'document-analysis-index': 'document-analysis',
};
/**
* Resolve the canonical analysis method ID for a given filename (without `.md`).
*
* Uses the {@link FILENAME_TO_METHOD} mapping for known mismatches; falls back
* to the filename itself when no mapping exists.
*
* @param baseName - Filename without extension (e.g. `stakeholder-impact`)
* @returns Canonical method ID (e.g. `stakeholder-analysis`)
*/
function resolveCanonicalMethod(baseName: string): string {
return FILENAME_TO_METHOD[baseName] ?? baseName;
}
/**
* Discover analysis file entries by scanning the analysis directory on disk.
*
* Scans known subdirectories plus root-level `.md` files to produce a
* complete list of {@link AnalysisFileEntry} objects suitable for the
* article template's dynamic analysis transparency section.
*
* This provides a robust fallback when the manifest.json doesn't contain
* a standard `methods[]` array (e.g. manifests written by agentic workflows
* use a different structure).
*
* @param analysisDirPath - Absolute path to the analysis directory on disk
* @returns Array of discovered analysis file entries, or empty array when directory doesn't exist
*/
export function discoverAnalysisFileEntries(analysisDirPath: string): AnalysisFileEntry[] {
if (!fs.existsSync(analysisDirPath)) return [];
const entries: AnalysisFileEntry[] = [];
// Scan known subdirectories
for (const subdir of DISCOVERY_SUBDIRS) {
scanSubdirectory(path.join(analysisDirPath, subdir), subdir, entries);
}
// Scan root-level .md files (e.g. synthesis-summary.md, weekly-intelligence-brief.md)
scanRootMarkdownFiles(analysisDirPath, entries);
return entries;
}
/**
* Scan a single subdirectory for .md files and add them to the entries list.
*
* @param subdirPath - Absolute path to the subdirectory
* @param subdir - Subdirectory name for the output file path prefix
* @param entries - Mutable array to push discovered entries into
*/
function scanSubdirectory(subdirPath: string, subdir: string, entries: AnalysisFileEntry[]): void {
try {
if (!fs.existsSync(subdirPath) || !fs.statSync(subdirPath).isDirectory()) return;
const files = fs.readdirSync(subdirPath);
for (const file of files) {
if (!file.endsWith('.md')) continue;
const baseName = file.replace(/\.md$/u, '');
entries.push({
method: resolveCanonicalMethod(baseName),
outputFile: `${subdir}/${file}`,
});
}
} catch {
// Skip unreadable directories
}
}
/**
* Scan root-level .md files in the analysis directory.
*
* @param dirPath - Analysis directory path
* @param entries - Mutable array to push discovered entries into
*/
function scanRootMarkdownFiles(dirPath: string, entries: AnalysisFileEntry[]): void {
try {
const rootFiles = fs.readdirSync(dirPath);
for (const file of rootFiles) {
if (!file.endsWith('.md')) continue;
const filePath = path.join(dirPath, file);
Iif (!fs.statSync(filePath).isFile()) continue;
const baseName = file.replace(/\.md$/u, '');
entries.push({
method: resolveCanonicalMethod(baseName),
outputFile: file,
});
}
} catch {
// Skip if unreadable
}
}
|