All files / scripts/sitemap-xml/render sitemap.ts

91.6% Statements 131/143
78.57% Branches 55/70
97.14% Functions 34/35
93.7% Lines 119/127

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                                                            2x 2x   2x 2x   2x       1649x             17x   17x       17x 238x     238x       17x 17x   238x 221x 221x 221x 221x   221x     17x 17x 17x           17x 238x 238x 221x 221x 238x     17x 238x     238x       17x 17x   238x 221x 221x 221x 221x 221x 221x       17x                       17x 153x 153x 153x 153x 2142x         2142x     153x     2142x 1989x 1989x 1989x 1989x 1989x           17x 238x     238x       17x 17x   238x 221x 221x     221x     17x 238x     238x     17x 17x 17x     17x 238x 221x 221x 221x 221x     17x 697x   17x   238x 17x 224x 224x         17x 224x     17x   238x 224x             17x 16x     238x 221x 221x 208x 208x 221x     17x 17x   17x 8891x 228599x 207315x 205598x     103207x         8891x         8891x 103207x 103207x       17x 17x                   17x 17x 17x   17x 58752x 58752x 58752x       17x       17x    
/**
 * @module Infrastructure/SitemapXml/Render/Sitemap
 * @category Intelligence Operations / Supporting Infrastructure
 * @name Top-level sitemap.xml builder
 *
 * @description
 * Orchestrates the full `<urlset>` XML: index pages (with hreflang
 * alternates), language landing pages, dashboards, news articles, RSS,
 * TypeDoc API pages, and the `docs/` tree. Pure with respect to its
 * inputs (the scanners read the filesystem; this function only composes
 * their output).
 *
 * Round-6 split: extracted from `scripts/generate-sitemap.ts`.
 *
 * @author Hack23 AB (Infrastructure Team)
 * @license Apache-2.0
 */
 
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
 
import type { Language } from '../../types/language.js';
 
import { getFileModTime } from '../git-timestamps.js';
import { getNewsArticles } from '../scanners/news.js';
import { getApiDocs } from '../scanners/api.js';
import { getDocFiles } from '../scanners/docs.js';
import { generateUrlEntry, type HreflangAlternate } from './url-entry.js';
 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
 
const ROOT_DIR = path.join(__dirname, '..', '..', '..');
const NEWS_DIR = path.join(ROOT_DIR, 'news');
 
const LANGUAGES: readonly Language[] = ['en', 'sv', 'da', 'no', 'fi', 'de', 'fr', 'es', 'nl', 'ar', 'he', 'ja', 'ko', 'zh'];
 
/** True when `relPath` (relative to the site root) exists on disk. */
function existsAtRoot(relPath: string): boolean {
  return fs.existsSync(path.join(ROOT_DIR, relPath));
}
 
/**
 * Generate sitemap XML.
 */
export function generateSitemap(): string {
  console.log('🔨 Generating sitemap...');
 
  let xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xhtml="http://www.w3.org/1999/xhtml">`;
 
  const indexAlternates: HreflangAlternate[] = [
    ...LANGUAGES.map((lang) => ({
      lang,
      href: lang === 'en' ? 'index.html' : `index_${lang}.html`,
    })).filter((alt) => existsAtRoot(alt.href)),
    { lang: 'x-default', href: 'index.html' },
  ];
 
  const indexMtime = getFileModTime(path.join(ROOT_DIR, 'index.html'));
  xml += generateUrlEntry('index.html', indexMtime, 'daily', '1.0', indexAlternates);
 
  LANGUAGES.filter((lang) => lang !== 'en').forEach((lang) => {
    const loc = `index_${lang}.html`;
    Iif (!existsAtRoot(loc)) return;
    const lastmod = getFileModTime(path.join(ROOT_DIR, loc));
    const priority = lang === 'sv' ? '0.9' : '0.7';
 
    xml += generateUrlEntry(loc, lastmod, 'daily', priority);
  });
 
  Eif (existsAtRoot('politician-dashboard.html')) {
    const politicianDashboardMtime = getFileModTime(path.join(ROOT_DIR, 'politician-dashboard.html'));
    xml += generateUrlEntry('politician-dashboard.html', politicianDashboardMtime, 'weekly', '0.8');
  }
 
  // English rss.xml plus every localized rss_<lang>.xml that was actually
  // emitted by generate-rss (languages with no articles are skipped there,
  // so the existence check keeps the sitemap free of dead feed URLs).
  for (const lang of LANGUAGES) {
    const loc = lang === 'en' ? 'rss.xml' : `rss_${lang}.xml`;
    if (!existsAtRoot(loc)) continue;
    const rssMtime = getFileModTime(path.join(ROOT_DIR, loc));
    const priority = lang === 'en' ? '0.5' : '0.4';
    xml += generateUrlEntry(loc, rssMtime, 'daily', priority);
  }
 
  const dashboardAlternates: HreflangAlternate[] = [
    ...LANGUAGES.map((lang) => ({
      lang,
      href: lang === 'en' ? 'dashboard/index.html' : `dashboard/index_${lang}.html`,
    })).filter((alt) => fs.existsSync(path.join(ROOT_DIR, alt.href))),
    { lang: 'x-default', href: 'dashboard/index.html' },
  ];
 
  const dashboardEnMtime = getFileModTime(path.join(ROOT_DIR, 'dashboard', 'index.html'));
  xml += generateUrlEntry('dashboard/index.html', dashboardEnMtime, 'weekly', '0.8', dashboardAlternates);
 
  LANGUAGES.filter((lang) => lang !== 'en').forEach((lang) => {
    const loc = `dashboard/index_${lang}.html`;
    const dashboardPath = path.join(ROOT_DIR, 'dashboard', `index_${lang}.html`);
    Eif (fs.existsSync(dashboardPath)) {
      const lastmod = getFileModTime(dashboardPath);
      const priority = lang === 'sv' ? '0.8' : '0.7';
      xml += generateUrlEntry(loc, lastmod, 'weekly', priority);
    }
  });
 
  const SPECIALISED_DASHBOARDS = [
    'election-cycle',
    'parties',
    'committees',
    'coalitions',
    'seasonal-patterns',
    'pre-election',
    'anomaly-detection',
    'ministers',
    'risk',
  ] as const;
 
  SPECIALISED_DASHBOARDS.forEach((slug) => {
    const enPath = path.join(ROOT_DIR, 'dashboards', `${slug}.html`);
    Iif (!fs.existsSync(enPath)) return;
    const enLastmod = getFileModTime(enPath);
    const alternates: HreflangAlternate[] = [
      ...LANGUAGES.map((lang) => ({
        lang,
        href: lang === 'en'
          ? `dashboards/${slug}.html`
          : `dashboards/${slug}_${lang}.html`,
      })).filter((alt) => fs.existsSync(path.join(ROOT_DIR, alt.href))),
      { lang: 'x-default', href: `dashboards/${slug}.html` },
    ];
    xml += generateUrlEntry(
      `dashboards/${slug}.html`, enLastmod, 'weekly', '0.75', alternates,
    );
    LANGUAGES.filter((lang) => lang !== 'en').forEach((lang) => {
      const langPath = path.join(ROOT_DIR, 'dashboards', `${slug}_${lang}.html`);
      Iif (!fs.existsSync(langPath)) return;
      const lastmod = getFileModTime(langPath);
      const priority = lang === 'sv' ? '0.7' : '0.6';
      xml += generateUrlEntry(
        `dashboards/${slug}_${lang}.html`, lastmod, 'weekly', priority,
      );
    });
  });
 
  const sitemapAlternates: HreflangAlternate[] = [
    ...LANGUAGES.map((lang) => ({
      lang,
      href: lang === 'en' ? 'sitemap.html' : `sitemap_${lang}.html`,
    })).filter((alt) => existsAtRoot(alt.href)),
    { lang: 'x-default', href: 'sitemap.html' },
  ];
 
  const sitemapEnMtime = getFileModTime(path.join(ROOT_DIR, 'sitemap.html'));
  xml += generateUrlEntry('sitemap.html', sitemapEnMtime, 'monthly', '0.6', sitemapAlternates);
 
  LANGUAGES.filter((lang) => lang !== 'en').forEach((lang) => {
    const file = `sitemap_${lang}.html`;
    Eif (!existsAtRoot(file)) return;
    const lastmod = getFileModTime(path.join(ROOT_DIR, file));
    const priority = lang === 'sv' ? '0.5' : '0.4';
    xml += generateUrlEntry(file, lastmod, 'monthly', priority);
  });
 
  const piAlternates = [
    ...LANGUAGES.map((lang) => ({
      lang: lang === 'no' ? 'nb' : lang,
      href: lang === 'en' ? 'political-intelligence.html' : `political-intelligence_${lang}.html`,
    })).filter((alt) => existsAtRoot(alt.href)),
    { lang: 'x-default', href: 'political-intelligence.html' },
  ];
  Eif (existsAtRoot('political-intelligence.html')) {
    const piEnMtime = getFileModTime(path.join(ROOT_DIR, 'political-intelligence.html'));
    xml += generateUrlEntry('political-intelligence.html', piEnMtime, 'daily', '0.85', piAlternates);
  }
 
  for (const lang of LANGUAGES) {
    if (lang === 'en') continue;
    const file = `political-intelligence_${lang}.html`;
    Iif (!existsAtRoot(file)) continue;
    const lastmod = getFileModTime(path.join(ROOT_DIR, file));
    xml += generateUrlEntry(file, lastmod, 'daily', '0.7');
  }
 
  const newsIndexFileFor = (lang: Language): string =>
    lang === 'en' ? 'index.html' : `index_${lang}.html`;
 
  const newsLangFiles = LANGUAGES
    .map(newsIndexFileFor)
    .filter((file) => fs.existsSync(path.join(NEWS_DIR, file)));
  const newsIndexMtimes = newsLangFiles.map((file) => {
    try {
      return new Date(getFileModTime(path.join(NEWS_DIR, file)));
    } catch (_e: unknown) {
      return new Date(0);
    }
  });
  const newsIndexMaxMtime = newsIndexMtimes.length > 0
    ? new Date(Math.max(...newsIndexMtimes.map((d) => d.getTime()))).toISOString()
    : new Date(0).toISOString();
 
  const newsIndexAlternates: HreflangAlternate[] = [
    ...LANGUAGES
      .filter((lang) => fs.existsSync(path.join(NEWS_DIR, newsIndexFileFor(lang))))
      .map((lang) => ({
        lang,
        href: lang === 'en' ? 'news/' : `news/index_${lang}.html`,
      })),
    { lang: 'x-default', href: 'news/' },
  ];
 
  if (fs.existsSync(path.join(NEWS_DIR, 'index.html'))) {
    xml += generateUrlEntry('news/', newsIndexMaxMtime, 'daily', '0.9', newsIndexAlternates);
  }
 
  LANGUAGES.filter((lang) => lang !== 'en').forEach((lang) => {
    const file = newsIndexFileFor(lang);
    if (!fs.existsSync(path.join(NEWS_DIR, file))) return;
    const lastmod = getFileModTime(path.join(NEWS_DIR, file));
    const priority = lang === 'sv' ? '0.9' : '0.7';
    xml += generateUrlEntry(`news/${file}`, lastmod, 'daily', priority);
  });
 
  const articles = getNewsArticles();
  console.log(`  Processing ${articles.length} article groups...`);
 
  articles.forEach((article) => {
    const sortedLanguages = [...article.languages].sort((a, b) => {
      if (a === 'en') return -1;
      if (b === 'en') return 1;
      return a.localeCompare(b);
    });
 
    const alternates: HreflangAlternate[] = sortedLanguages.map((altLang) => ({
      lang: altLang,
      href: `news/${article.baseSlug}-${altLang}.html`,
    }));
 
    alternates.push({
      lang: 'x-default',
      href: `news/${article.baseSlug}-${sortedLanguages[0]}.html`,
    });
 
    sortedLanguages.forEach((lang) => {
      const loc = `news/${article.baseSlug}-${lang}.html`;
      xml += generateUrlEntry(loc, article.lastmod, 'monthly', '0.8', alternates);
    });
  });
 
  const apiDocs = getApiDocs();
  Iif (apiDocs.length > 0) {
    console.log(`  Processing ${apiDocs.length} API documentation files...`);
 
    apiDocs.forEach((doc) => {
      const loc = `api/${doc.file}`;
      const priority = doc.file === 'index.html' ? '0.7' : '0.5';
      xml += generateUrlEntry(loc, doc.lastmod, 'weekly', priority);
    });
  }
 
  const docFiles = getDocFiles();
  Eif (docFiles.length > 0) {
    console.log(`  Processing ${docFiles.length} docs/ documentation files...`);
 
    docFiles.forEach((doc) => {
      const loc = `docs/${doc.file}`;
      const priority = doc.file === 'index.html' || doc.file.endsWith('/index.html') ? '0.4' : '0.3';
      xml += generateUrlEntry(loc, doc.lastmod, 'monthly', priority);
    });
  }
 
  xml += `
  
</urlset>`;
 
  return xml;
}