All files / generators/pipeline generate-stage.ts

97.67% Statements 42/43
83.33% Branches 15/18
100% Functions 3/3
100% Lines 42/42

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                                                                                                  3x 3x       3x       3x       3x       3x 3x       3x       3x       3x           7x                                         7x 7x 7x                                                   7x 7x   7x 7x 7x 7x   7x   4x 4x 6x   6x 6x   6x                         6x 4x 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 } from '../../utils/file-utils.js';
import type { ArticleStrategy, ArticleData } from '../strategies/article-strategy.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, ArticleStrategy<ArticleData>>;
 
/**
 * Build the default strategy registry containing all built-in strategies.
 *
 * Each concrete strategy implements `ArticleStrategy<ConcreteData>` where
 * `ConcreteData` extends `ArticleData`.  TypeScript's invariant generic
 * parameter means the concrete type is not directly assignable to the base
 * `ArticleStrategy<ArticleData>` without a boundary cast; the
 * `as unknown as ArticleStrategy<ArticleData>` casts below are therefore
 * intentional and safe — the registry delegates back to each strategy's own
 * typed `fetchData`/`buildContent`/`getMetadata` methods at call-site.
 *
 * @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 as unknown as ArticleStrategy<ArticleData>
  );
  registry.set(
    ArticleCategory.BREAKING_NEWS,
    breakingNewsStrategy as unknown as ArticleStrategy<ArticleData>
  );
  registry.set(
    ArticleCategory.COMMITTEE_REPORTS,
    committeeReportsStrategy as unknown as ArticleStrategy<ArticleData>
  );
  registry.set(
    ArticleCategory.PROPOSITIONS,
    propositionsStrategy as unknown as ArticleStrategy<ArticleData>
  );
  registry.set(ArticleCategory.MOTIONS, motionsStrategy as unknown as ArticleStrategy<ArticleData>);
  registry.set(
    ArticleCategory.MONTH_AHEAD,
    monthAheadStrategy as unknown as ArticleStrategy<ArticleData>
  );
  registry.set(
    ArticleCategory.WEEK_IN_REVIEW,
    weeklyReviewStrategy as unknown as ArticleStrategy<ArticleData>
  );
  registry.set(
    ArticleCategory.MONTH_IN_REVIEW,
    monthlyReviewStrategy as unknown as ArticleStrategy<ArticleData>
  );
  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];
}
 
// ─── 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: ArticleStrategy<ArticleData>,
  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);
 
    let writtenCount = 0;
    for (const lang of languages) {
      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] : [],
      });
 
      if (writeSingleArticle(html, slug, lang, outputOptions, stats)) {
        writtenCount++;
        console.log(`  ✅ ${lang.toUpperCase()} version generated`);
      }
    }
 
    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 };
  }
}