All files / utils file-utils.ts

97.36% Statements 37/38
94.11% Branches 16/17
100% Functions 14/14
97.22% Lines 35/36

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                                        7x 1x 1x     6x 10x                   16x   16x 3x     13x                                     2x   2x 4x     2x 6x 6x 6x         2x 5x     2x                   8x   11x                     1x   1x                     2x                     3x 3x                 10x 2x                     3x 3x 3x                   1958x                             108x 108x 108x          
// 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 fs from 'fs';
import path from 'path';
import { NEWS_DIR, ARTICLE_FILENAME_PATTERN } from '../constants/config.js';
import type { 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;
  }
 
  return {
    date: match[1] as string,
    slug: match[2] as string,
    lang: match[3] as string,
    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 && grouped[parsed.lang] !== undefined) {
      grouped[parsed.lang]!.push(parsed);
    }
  }
 
  // Sort by date (newest first)
  for (const lang in grouped) {
    grouped[lang]!.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);
  // split('T') on an ISO string always produces at least one element
  return stats.mtime.toISOString().split('T')[0]!;
}
 
/**
 * 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 {
  // split('T') on an ISO string always produces at least one element
  return date.toISOString().split('T')[0]!;
}
 
/**
 * 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 });
  }
}
 
/**
 * 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');
}
 
/**
 * 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, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}
 
/**
 * 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;
  }
}