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 | 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 7x 8x 8x 8x 6x 6x 6x 6x 6x 6x 6x 6x 6x 3x 6x 6x 6x 6x 4x 4x 2x 8x 8x 8x 8x 8x 8x 8x 5x 1x 1x 1x 4x 4x 6x 4x 4x 4x 2x 2x 4x 3x 3x 3x 3x 1x 3x 3x | // SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
/**
* @module Generators/Pipeline/GenerateStage
* @description Article content generation orchestration pipeline stage.
*
* Provides a {@link StrategyRegistry} that maps each {@link ArticleCategory}
* to its concrete {@link ArticleStrategy} implementation, and a single
* {@link generateArticleForStrategy} function that runs the full fetch →
* build → write cycle for one article type across all requested languages.
*/
import type { EuropeanParliamentMCPClient } from '../../mcp/ep-mcp-client.js';
import { ArticleCategory } from '../../types/index.js';
import type { LanguageCode, GenerationStats, GenerationResult } from '../../types/index.js';
import { generateArticleHTML } from '../../templates/article-template.js';
import {
calculateReadTime,
formatDateForSlug,
validateArticleHTML,
} from '../../utils/file-utils.js';
import type { ArticleStrategyBase, ArticleData } from '../strategies/article-strategy.js';
import { validateArticleContent } from '../../utils/content-validator.js';
import { scoreArticleQuality } from '../../utils/article-quality-scorer.js';
import { weekAheadStrategy } from '../strategies/week-ahead-strategy.js';
import { breakingNewsStrategy } from '../strategies/breaking-news-strategy.js';
import { committeeReportsStrategy } from '../strategies/committee-reports-strategy.js';
import { propositionsStrategy } from '../strategies/propositions-strategy.js';
import { motionsStrategy } from '../strategies/motions-strategy.js';
import { monthAheadStrategy } from '../strategies/month-ahead-strategy.js';
import { weeklyReviewStrategy } from '../strategies/weekly-review-strategy.js';
import { monthlyReviewStrategy } from '../strategies/monthly-review-strategy.js';
import type { OutputOptions } from './output-stage.js';
import { writeSingleArticle } from './output-stage.js';
// ─── Registry ────────────────────────────────────────────────────────────────
/** Map from {@link ArticleCategory} to its registered strategy */
export type StrategyRegistry = Map<ArticleCategory, ArticleStrategyBase>;
/**
* Build the default strategy registry containing all built-in strategies.
*
* Each concrete strategy implements `ArticleStrategy<ConcreteData>` which
* extends `ArticleStrategyBase`. Because TypeScript's method-parameter
* checking is bivariant, a strategy whose methods accept a narrower `TData`
* is structurally assignable to `ArticleStrategyBase` without any cast.
*
* @returns A populated registry ready for use by {@link generateArticleForStrategy}
*/
export function createStrategyRegistry(): StrategyRegistry {
const registry: StrategyRegistry = new Map();
registry.set(ArticleCategory.WEEK_AHEAD, weekAheadStrategy);
registry.set(ArticleCategory.BREAKING_NEWS, breakingNewsStrategy);
registry.set(ArticleCategory.COMMITTEE_REPORTS, committeeReportsStrategy);
registry.set(ArticleCategory.PROPOSITIONS, propositionsStrategy);
registry.set(ArticleCategory.MOTIONS, motionsStrategy);
registry.set(ArticleCategory.MONTH_AHEAD, monthAheadStrategy);
registry.set(ArticleCategory.WEEK_IN_REVIEW, weeklyReviewStrategy);
registry.set(ArticleCategory.MONTH_IN_REVIEW, monthlyReviewStrategy);
return registry;
}
// ─── Emoji map ────────────────────────────────────────────────────────────────
/** Display emoji for each article category */
const ARTICLE_EMOJIS: Partial<Record<ArticleCategory, string>> = {
[ArticleCategory.WEEK_AHEAD]: '📅',
[ArticleCategory.MONTH_AHEAD]: '📅',
[ArticleCategory.BREAKING_NEWS]: '🚨',
[ArticleCategory.COMMITTEE_REPORTS]: '🏛️',
[ArticleCategory.PROPOSITIONS]: '📜',
[ArticleCategory.MOTIONS]: '🗳️',
[ArticleCategory.WEEK_IN_REVIEW]: '📊',
[ArticleCategory.MONTH_IN_REVIEW]: '📊',
};
// ─── Date helper ──────────────────────────────────────────────────────────────
/**
* Extract the YYYY-MM-DD portion of a Date object's ISO string.
* Throws explicitly instead of relying on non-null assertion.
*
* @param date - Date to extract from
* @returns ISO date string (YYYY-MM-DD)
*/
function getIsoDatePart(date: Date): string {
const parts = date.toISOString().split('T');
Iif (!parts[0]) throw new Error('Failed to extract date part from ISO string');
return parts[0];
}
/**
* Generate, validate and write a single language version of an article.
*
* @param strategy - Article strategy providing content and metadata
* @param data - Fetched article data
* @param lang - Target language code
* @param dateStr - ISO date string
* @param slug - File slug (date-type)
* @param outputOptions - Output configuration
* @param stats - Mutable generation stats
* @param availableLanguages - Languages for which the article exists; used to restrict language switcher links
* @returns true if a file was written
*/
function generateSingleLanguageArticle(
strategy: ArticleStrategyBase,
data: ArticleData,
lang: LanguageCode,
dateStr: string,
slug: string,
outputOptions: OutputOptions,
stats: GenerationStats,
availableLanguages?: ReadonlyArray<LanguageCode>
): boolean {
console.log(` 🌐 Generating ${lang.toUpperCase()} version...`);
const content = strategy.buildContent(data, lang);
const metadata = strategy.getMetadata(data, lang);
const html = generateArticleHTML({
slug: strategy.type,
title: metadata.title,
subtitle: metadata.subtitle,
date: dateStr,
category: metadata.category,
readTime: calculateReadTime(content),
lang,
content,
keywords: [...metadata.keywords],
sources: metadata.sources ? [...metadata.sources] : [],
availableLanguages,
});
// Validate generated HTML has all required structural elements
const validation = validateArticleHTML(html);
Iif (!validation.valid) {
console.error(
` ❌ ${lang.toUpperCase()} article failed validation: ${validation.errors.join('; ')}`
);
stats.errors++;
return false;
}
// Validate content quality (word count, placeholders, required elements)
const contentValidation = validateArticleContent(html, lang, strategy.type);
Iif (!contentValidation.valid) {
console.error(
` ❌ ${lang.toUpperCase()} article failed content validation: ${contentValidation.errors.join('; ')}`
);
stats.errors++;
return false;
}
for (const warning of contentValidation.warnings) {
console.warn(` ⚠️ ${lang.toUpperCase()} content warning: ${warning}`);
}
// Quality scoring — informational only, never blocks generation
const qualityReport = scoreArticleQuality(html, slug, lang, strategy.type);
console.log(
` 📊 ${lang.toUpperCase()} quality: Grade ${qualityReport.grade} (${qualityReport.overallScore}/100)`
);
Iif (!qualityReport.passesQualityGate) {
console.warn(
` ⚠️ ${lang.toUpperCase()} article did not pass quality gate (score ${qualityReport.overallScore} < 40). Recommendations:`
);
for (const rec of qualityReport.recommendations.slice(0, 3)) {
console.warn(` 💡 ${rec}`);
}
}
if (writeSingleArticle(html, slug, lang, outputOptions, stats)) {
console.log(` ✅ ${lang.toUpperCase()} version generated`);
return true;
}
return false;
}
// ─── Generation orchestrator ──────────────────────────────────────────────────
/**
* Run the complete fetch → build → write cycle for one article type.
*
* Iterates over `languages`, calls the strategy for content and metadata,
* generates the full HTML wrapper and writes each file through the output
* stage. Catches all errors so the caller can continue with other types.
*
* @param strategy - Concrete strategy for the target article category
* @param client - Connected MCP client or null
* @param languages - Target language codes
* @param outputOptions - Dry-run, skip-existing and directory flags
* @param stats - Mutable stats object to increment counters on
* @returns Generation result with success flag, file count and slug
*/
export async function generateArticleForStrategy(
strategy: ArticleStrategyBase,
client: EuropeanParliamentMCPClient | null,
languages: ReadonlyArray<LanguageCode>,
outputOptions: OutputOptions,
stats: GenerationStats
): Promise<GenerationResult> {
const emoji = ARTICLE_EMOJIS[strategy.type] ?? '📄';
console.log(`${emoji} Generating ${strategy.type} article...`);
try {
const today = new Date();
const dateStr = getIsoDatePart(today);
const slug = `${formatDateForSlug(today)}-${strategy.type}`;
const data = await strategy.fetchData(client, dateStr);
// Check if the strategy wants to skip generation (e.g. all data is placeholder)
if (strategy.shouldSkip?.(data)) {
console.log(
` ⚠️ ${strategy.type} article skipped: all fetched data is placeholder (MCP unavailable or API gap). No files written.`
);
stats.skipped += languages.length;
return { success: true, files: 0, slug };
}
let writtenCount = 0;
for (const lang of languages) {
if (
generateSingleLanguageArticle(
strategy,
data,
lang,
dateStr,
slug,
outputOptions,
stats,
languages
)
) {
writtenCount++;
}
}
const totalLangs = languages.length;
if (writtenCount === 0) {
console.log(
` ✅ ${strategy.type} article generation completed: 0 files written (dry-run or all files skipped)`
);
} else {
console.log(
` ✅ ${strategy.type} article generated: ${writtenCount}/${totalLangs} language(s) written`
);
}
return { success: true, files: writtenCount, slug };
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
const stack = error instanceof Error ? error.stack : undefined;
console.error(`❌ Error generating ${strategy.type}:`, message);
if (stack && process.env['DEBUG'] === 'true') {
console.error(' Stack:', stack);
}
stats.errors++;
return { success: false, error: message };
}
}
|