All files / src/generators/sitemap xml.ts

92.68% Statements 76/82
78.94% Branches 30/38
100% Functions 19/19
93.58% Lines 73/78

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                                                                                      3x                             14x 14x 2x   12x 12x 28x 28x 7x 21x 12x     12x                                     28x 28x                           28x                             784x                   784x                       105x 105x 105x 105x                   105x                     28x 28x 392x   28x 392x                               784x                     28x 28x 392x   28x 392x                               28x 28x 392x   28x 392x                                     28x 28x 23x 23x 23x 23x 23x 6x 6x   23x     28x 23x 23x 23x 23x 23x   23x 23x       23x                                     28x 12x 12x 12x 12x       12x                               12x 12x 6x   6x 3x   3x                   1239x       17874x       1239x                 3x  
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Generators/Sitemap/Xml
 * @description Generates the `sitemap.xml` document with hreflang
 * alternates per Google guidelines. Wraps the index pages, sitemap HTML
 * pages, political-intelligence pages, RSS feed, news articles, and
 * documentation files with appropriate `<changefreq>` / `<priority>`
 * defaults and `xhtml:link rel="alternate"` blocks for multilingual
 * variants.
 *
 * Lifted out of the monolithic `sitemap.ts` so the XML emission can be
 * unit-tested in isolation, so the bounded context "sitemap XML" is
 * pure (no HTML chrome dependencies), and so future XML output formats
 * (news-sitemap, video-sitemap) can reuse the same URL builders.
 *
 * Output is byte-identical to the legacy in-line implementation that
 * lived in `sitemap.ts`, verified by the byte-equality regression test.
 */
 
import fs from 'fs';
import path from 'path';
import { BASE_URL, NEWS_DIR, PROJECT_ROOT } from '../../constants/config.js';
import { ALL_LANGUAGES } from '../../constants/languages.js';
import { getModifiedDate, parseArticleFilename } from '../../utils/file-utils.js';
import type { SitemapUrl } from '../../types/index.js';
import { getPoliticalIntelligenceFilename } from '../political-intelligence.js';
import { escapeXML } from './xml-utils.js';
import { getSitemapFilename, getIndexFilename } from './html.js';
 
/**
 * Extended sitemap URL with optional `xhtml:link` alternate-language
 * entries. Used to emit Google-compliant hreflang blocks inside each
 * `<url>` element so multilingual variants of the same logical page are
 * cross-linked.
 */
export interface SitemapUrlWithAlternates extends SitemapUrl {
  /** Map of hreflang code → absolute URL of the alternate language variant. */
  alternates?: Record<string, string>;
}
 
/** Absolute docs directory under project root */
const DOCS_DIR: string = path.join(PROJECT_ROOT, 'docs');
 
/**
 * Recursively collect all `.html` files under a directory, returning
 * paths relative to the project root with POSIX separators.
 *
 * Returns an empty array silently when `dir` does not exist — callers
 * (notably the sitemap generator) need not pre-check, and a missing
 * docs directory is a normal "no docs published yet" state.
 *
 * @param dir - Directory to scan
 * @param rootDir - Project root for computing relative paths
 * @returns Sorted array of relative paths (e.g. `docs/api/index.html`)
 */
export function collectDocsHtmlFiles(dir: string, rootDir: string = PROJECT_ROOT): string[] {
  const results: string[] = [];
  if (!fs.existsSync(dir)) {
    return results;
  }
  const entries = fs.readdirSync(dir, { withFileTypes: true });
  for (const entry of entries) {
    const fullPath = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      results.push(...collectDocsHtmlFiles(fullPath, rootDir));
    } else if (entry.isFile() && entry.name.endsWith('.html')) {
      results.push(path.relative(rootDir, fullPath).replace(/\\/g, '/'));
    }
  }
  return results.sort();
}
 
/**
 * Generate sitemap XML including index pages, news articles, sitemap
 * HTML pages, political-intelligence pages, RSS feed, and documentation
 * files from the `docs/` folder.
 *
 * Multilingual pages (the 14 index pages, the 14 sitemap HTML pages,
 * the 14 political-intelligence pages, and any article whose base stem
 * exists in multiple languages) are enriched with `xhtml:link
 * rel="alternate" hreflang="…"` entries so Google and other search
 * engines can discover the full set of language variants.
 *
 * @param articles - List of article filenames (sourced from the `news/` directory)
 * @param docsFiles - Relative paths to docs HTML files (e.g. `docs/api/index.html`)
 * @returns Complete sitemap XML string
 */
export function generateSitemap(articles: string[], docsFiles: string[] = []): string {
  const today = new Date().toISOString().slice(0, 10);
  const urls: SitemapUrlWithAlternates[] = [
    ...buildIndexUrls(today),
    ...buildSitemapHtmlUrls(today),
    ...buildPoliticalIntelligenceUrls(today),
    {
      loc: `${BASE_URL}/rss.xml`,
      lastmod: today,
      changefreq: 'daily',
      priority: '0.5',
    },
    ...buildArticleUrls(articles),
    ...buildDocsUrls(docsFiles, today),
  ];
 
  return `<?xml version="1.0" encoding="UTF-8"?>
<!-- SPDX-FileCopyrightText: 2024-2026 Hack23 AB -->
<!-- SPDX-License-Identifier: Apache-2.0 -->
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
${urls.map(renderSitemapUrl).join('\n')}
</urlset>`;
}
 
/**
 * Build the absolute URL for a language-specific index page.
 *
 * @param lang - Language code
 * @returns Absolute URL
 */
function indexUrlFor(lang: string): string {
  return `${BASE_URL}/${getIndexFilename(lang)}`;
}
 
/**
 * Build the absolute URL for a language-specific sitemap HTML page.
 *
 * @param lang - Language code
 * @returns Absolute URL
 */
function sitemapUrlFor(lang: string): string {
  return `${BASE_URL}/${getSitemapFilename(lang)}`;
}
 
/**
 * Build hreflang alternates for a set of language→URL entries, adding
 * `x-default` pointing at the English variant (or, when English is
 * absent, the alphabetically-first available language).
 *
 * @param byLang - Mapping of language code to absolute URL
 * @returns Alternates map including `x-default`
 */
function withXDefault(byLang: Record<string, string>): Record<string, string> {
  const result = { ...byLang };
  const enFallback = result['en'];
  if (enFallback) {
    result['x-default'] = enFallback;
  } else E{
    const firstLang = Object.keys(result).sort()[0];
    if (firstLang) {
      const fallback = result[firstLang];
      if (fallback) {
        result['x-default'] = fallback;
      }
    }
  }
  return result;
}
 
/**
 * Build the 14 `<url>` entries for language index pages, each with a
 * shared hreflang-alternates block covering every supported language.
 *
 * @param today - ISO date string for `<lastmod>`
 * @returns Sitemap URL entries
 */
function buildIndexUrls(today: string): SitemapUrlWithAlternates[] {
  const alternates: Record<string, string> = {};
  for (const lang of ALL_LANGUAGES) {
    alternates[lang] = indexUrlFor(lang);
  }
  const full = withXDefault(alternates);
  return ALL_LANGUAGES.map((lang) => ({
    loc: indexUrlFor(lang),
    lastmod: today,
    changefreq: 'daily',
    priority: '1.0',
    alternates: full,
  }));
}
 
/**
 * Build the absolute URL for a language-specific political-intelligence HTML page.
 *
 * @param lang - Language code
 * @returns Absolute URL
 */
function politicalIntelligenceUrlFor(lang: string): string {
  return `${BASE_URL}/${getPoliticalIntelligenceFilename(lang)}`;
}
 
/**
 * Build the 14 `<url>` entries for political-intelligence HTML pages
 * with hreflang alternates covering every supported language.
 *
 * @param today - ISO date string for `<lastmod>`
 * @returns Sitemap URL entries
 */
function buildPoliticalIntelligenceUrls(today: string): SitemapUrlWithAlternates[] {
  const alternates: Record<string, string> = {};
  for (const lang of ALL_LANGUAGES) {
    alternates[lang] = politicalIntelligenceUrlFor(lang);
  }
  const full = withXDefault(alternates);
  return ALL_LANGUAGES.map((lang) => ({
    loc: politicalIntelligenceUrlFor(lang),
    lastmod: today,
    changefreq: 'weekly',
    priority: '0.6',
    alternates: full,
  }));
}
 
/**
 * Build the 14 `<url>` entries for sitemap HTML pages with hreflang alternates.
 *
 * @param today - ISO date string for `<lastmod>`
 * @returns Sitemap URL entries
 */
function buildSitemapHtmlUrls(today: string): SitemapUrlWithAlternates[] {
  const alternates: Record<string, string> = {};
  for (const lang of ALL_LANGUAGES) {
    alternates[lang] = sitemapUrlFor(lang);
  }
  const full = withXDefault(alternates);
  return ALL_LANGUAGES.map((lang) => ({
    loc: sitemapUrlFor(lang),
    lastmod: today,
    changefreq: 'daily',
    priority: '0.5',
    alternates: full,
  }));
}
 
/**
 * Build `<url>` entries for every news article. Multi-language clusters
 * (articles that share the same `YYYY-MM-DD-slug` stem) receive
 * hreflang alternates so search engines can discover every variant.
 *
 * @param articles - Article filenames from the `news/` directory
 * @returns Sitemap URL entries
 */
function buildArticleUrls(articles: string[]): SitemapUrlWithAlternates[] {
  // Group language variants by stem
  const byStem = new Map<string, Record<string, string>>();
  for (const article of articles) {
    const parsed = parseArticleFilename(article);
    Iif (!parsed) continue;
    const stem = `${parsed.date}-${parsed.slug}`;
    let bucket = byStem.get(stem);
    if (!bucket) {
      bucket = {};
      byStem.set(stem, bucket);
    }
    bucket[parsed.lang] = `${BASE_URL}/news/${article}`;
  }
 
  return articles.map((article) => {
    const filepath = path.join(NEWS_DIR, article);
    const lastmod = getModifiedDate(filepath);
    const parsed = parseArticleFilename(article);
    const stem = parsed ? `${parsed.date}-${parsed.slug}` : null;
    const bucket = stem ? byStem.get(stem) : undefined;
    // Only emit alternates when the stem has multiple language variants
    const hasMultipleLocales = bucket && Object.keys(bucket).length > 1;
    const alternates = hasMultipleLocales
      ? withXDefault(bucket as Record<string, string>)
      : undefined;
 
    return {
      loc: `${BASE_URL}/news/${article}`,
      lastmod,
      changefreq: 'monthly' as const,
      priority: '0.8',
      ...(alternates ? { alternates } : {}),
    };
  });
}
 
/**
 * Build `<url>` entries for documentation HTML files (no hreflang
 * alternates — docs are single-locale).
 *
 * @param docsFiles - Docs file paths relative to the project root
 * @param today - Fallback ISO date string when `fs.stat` fails
 * @returns Sitemap URL entries
 */
function buildDocsUrls(docsFiles: string[], today: string): SitemapUrlWithAlternates[] {
  return docsFiles.map((relPath) => {
    const fullPath = path.join(PROJECT_ROOT, relPath);
    let lastmod = today;
    try {
      lastmod = getModifiedDate(fullPath);
    } catch {
      // Use today if file stat fails
    }
    return {
      loc: `${BASE_URL}/${canonicalDocsPath(relPath)}`,
      lastmod,
      changefreq: 'weekly',
      priority: '0.3',
    };
  });
}
 
/**
 * Convert documentation file paths to their preferred public canonical URL path.
 *
 * @param relPath - Docs file path relative to the project root
 * @returns URL path with canonical directory forms for docs index pages
 */
function canonicalDocsPath(relPath: string): string {
  const normalized = relPath.replace(/\\/g, '/');
  if (normalized === 'docs/index.html') {
    return 'docs/';
  }
  if (normalized === 'docs/api/index.html') {
    return 'docs/api/';
  }
  return normalized;
}
 
/**
 * Render a single `<url>` block, including any `xhtml:link` alternates.
 *
 * @param url - Sitemap URL entry with optional hreflang alternates
 * @returns XML fragment for the `<url>` block
 */
function renderSitemapUrl(url: SitemapUrlWithAlternates): string {
  const altLinks = url.alternates
    ? Object.entries(url.alternates)
        .map(
          ([hreflang, href]) =>
            `    <xhtml:link rel="alternate" hreflang="${escapeXML(hreflang)}" href="${escapeXML(href)}"/>`
        )
        .join('\n')
    : '';
  return `  <url>
    <loc>${escapeXML(url.loc)}</loc>
    <lastmod>${escapeXML(url.lastmod)}</lastmod>
    <changefreq>${escapeXML(url.changefreq)}</changefreq>
    <priority>${escapeXML(url.priority)}</priority>${altLinks ? `\n${altLinks}` : ''}
  </url>`;
}
 
/** Absolute path of the docs/ directory used by the sitemap CLI. */
export const SITEMAP_DOCS_DIR: string = DOCS_DIR;