All files / packages/design-system/scripts/validation/lib html-report.js

60% Statements 63/105
62.22% Branches 28/45
86.66% Functions 13/15
58.41% Lines 59/101

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                                                                                                                                                                                                                                                                                                          2x     2x 2x 2x 3x 3x 6x 3x 6x         2x                               5x     5x 1x 4x 1x 3x     3x     5x 2x               3x                             2x     2x 1x             2x 1x     2x         2x 2x 2x     3x       2x                 5x 5x   2x   2x                                         2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   3x 2x 1x 1x   1x 1x 1x 1x 1x 1x       1x     2x    
/**
 * HTML report generation for validation framework
 * Core: diff2html report generation
 */
import fs from 'fs-extra';
import path from 'node:path';
import { execSync } from 'node:child_process';
import {
  escapeHtml,
  render,
  renderTemplate,
  loadTemplate,
  loadStyles,
} from './template-renderer.js';
 
// Re-export escapeHtml for backward compatibility
export { escapeHtml };
 
/**
 * Generate the diff header HTML for injection into diff2html output
 * @param {string} reportName - Name of the report
 * @param {string} relativePath - Relative path of the file
 * @returns {string} Header HTML
 */
function generateDiffHeader(reportName, relativePath) {
  const template = loadTemplate('diff-header.html');
  const styles = loadStyles();
 
  // Include inline styles for the header since it's injected into diff2html output
  const inlineStyles = `
    <style>
      .diff-header {
        background: #1e1e1e;
        color: #d4d4d4;
        padding: 16px 24px;
        border-bottom: 1px solid #3e3e42;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      }
      .diff-header__title { font-size: 18px; font-weight: 600; margin-bottom: 8px; }
      .diff-header__comparison { font-size: 14px; color: #858585; }
      .diff-header__baseline { color: #f48771; }
      .diff-header__current { color: #89d185; }
      .diff-header__path { font-size: 13px; color: #6a9955; margin-top: 8px; font-family: 'Monaco', 'Menlo', monospace; }
      .diff-header__back { margin-top: 12px; }
      .diff-header__back a { color: #4ec9b0; text-decoration: none; }
      .diff-header__back a:hover { text-decoration: underline; }
    </style>`;
 
  const headerHtml = render(template, {
    reportName: escapeHtml(reportName),
    relativePath: escapeHtml(relativePath),
  });
 
  return inlineStyles + headerHtml;
}
 
/**
 * Generate HTML diff for a file using diff2html-cli
 * @param {Object} result - Comparison result
 * @param {string} outputPath - Path to write HTML file
 * @param {string} reportDir - Report directory for temp files
 * @param {string} reportName - Name of the report for header
 * @returns {boolean} True if successful
 */
export function generateHtmlDiff(result, outputPath, reportDir, reportName = 'Comparison') {
  const { relativePath, status, baselineContent, currentContent } = result;
 
  try {
    if (status === 'added' || status === 'removed') {
      // For added/removed files, create a simple diff
      const emptyFile = path.join(reportDir, '.empty');
      fs.writeFileSync(emptyFile, '', 'utf8');
 
      if (status === 'added') {
        const currentFile = path.join(reportDir, '.current');
        fs.writeFileSync(currentFile, currentContent, 'utf8');
        execSync(
          `diff -u "${emptyFile}" "${currentFile}" | npx --yes diff2html-cli -i stdin -s side -F "${outputPath}"`,
          { cwd: reportDir, stdio: 'pipe' },
        );
        fs.removeSync(currentFile);
      } else {
        const baselineFile = path.join(reportDir, '.baseline');
        fs.writeFileSync(baselineFile, baselineContent, 'utf8');
        execSync(
          `diff -u "${baselineFile}" "${emptyFile}" | npx --yes diff2html-cli -i stdin -s side -F "${outputPath}"`,
          { cwd: reportDir, stdio: 'pipe' },
        );
        fs.removeSync(baselineFile);
      }
 
      fs.removeSync(emptyFile);
    } else {
      // For different files, create temp files and diff
      const baselineFile = path.join(reportDir, '.baseline');
      const currentFile = path.join(reportDir, '.current');
 
      fs.writeFileSync(baselineFile, baselineContent, 'utf8');
      fs.writeFileSync(currentFile, currentContent, 'utf8');
 
      try {
        execSync(
          `diff -u "${baselineFile}" "${currentFile}" | npx --yes diff2html-cli -i stdin -s side -F "${outputPath}"`,
          { cwd: reportDir, stdio: 'pipe' },
        );
      } catch (e) {
        // diff returns exit code 1 when files differ, which is expected
        if (!fs.existsSync(outputPath)) {
          throw e;
        }
      }
 
      fs.removeSync(baselineFile);
      fs.removeSync(currentFile);
    }
 
    // Post-process: Replace diff2html default header with custom header
    if (fs.existsSync(outputPath)) {
      let html = fs.readFileSync(outputPath, 'utf8');
 
      // Replace the title
      html = html.replace(
        /<title>.*?<\/title>/,
        `<title>${escapeHtml(relativePath)} - ${escapeHtml(reportName)}</title>`,
      );
 
      // Generate and insert custom header after <body> tag
      const customHeader = generateDiffHeader(reportName, relativePath);
      html = html.replace(/<body[^>]*>/, `$&${customHeader}`);
 
      fs.writeFileSync(outputPath, html, 'utf8');
    }
 
    return true;
  } catch (error) {
    // Fall back to custom HTML if diff2html-cli fails
    console.warn(`Warning: diff2html-cli failed for ${relativePath}, using fallback`);
    const fallbackHtml = generateFallbackHtml(result);
    fs.writeFileSync(outputPath, fallbackHtml, 'utf8');
    return true;
  }
}
 
/**
 * Generate fallback HTML diff when diff2html-cli fails
 * @param {Object} result - Comparison result
 * @returns {string} HTML content
 */
export function generateFallbackHtml(result) {
  const { relativePath, status, diff, linesAdded, linesRemoved } = result;
 
  // Build diff content HTML
  let diffContent = '';
  Eif (diff) {
    diff.forEach((part) => {
      const lines = part.value.split('\n');
      lines.forEach((line, idx) => {
        if (idx === lines.length - 1 && line === '') return;
        const className = part.added ? 'added' : part.removed ? 'removed' : 'context';
        diffContent += `<div class="line ${className}">${escapeHtml(line)}</div>`;
      });
    });
  }
 
  return renderTemplate('fallback.html', {
    relativePath: relativePath,
    statusUppercase: status.toUpperCase(),
    diffContent: diffContent,
    linesAdded: linesAdded,
    linesRemoved: linesRemoved,
  });
}
 
/**
 * Generate file item HTML for the index page
 * @param {Object} file - File object
 * @param {boolean} isLink - Whether to render as a link
 * @returns {string} HTML content
 */
function generateFileItem(file, isLink) {
  const safeFileName = file.relativePath.replace(/[^a-zA-Z0-9]/g, '_') + '.html';
 
  let statsText;
  if (file.status === 'different') {
    statsText = `-${file.linesRemoved} / +${file.linesAdded}`;
  } else if (file.status === 'added') {
    statsText = `+${file.linesAdded} lines`;
  } else if (Ifile.status === 'removed') {
    statsText = `-${file.linesRemoved} lines`;
  } else {
    statsText = 'No changes';
  }
 
  if (isLink) {
    return `
        <a href="${escapeHtml(safeFileName)}" class="file-item">
          <span class="file-status ${file.status}">${file.status.toUpperCase()}</span>
          <span class="file-name">${escapeHtml(file.relativePath)}</span>
          <span class="file-stats">${statsText}</span>
        </a>`;
  }
 
  return `
        <div class="file-item identical-item">
          <span class="file-status identical">IDENTICAL</span>
          <span class="file-name">${escapeHtml(file.relativePath)}</span>
          <span class="file-stats">${statsText}</span>
        </div>`;
}
 
/**
 * Generate the files list HTML for the index page
 * @param {Object[]} filesWithDiffs - Files that have differences
 * @param {Object[]} identicalFiles - Files that are identical
 * @returns {string} HTML content
 */
function generateFilesList(filesWithDiffs, identicalFiles) {
  let filesList = '';
 
  // Show success banner if all files match
  if (filesWithDiffs.length === 0) {
    filesList += `
    <div class="success-message">
      āœ… All files match baseline!
    </div>`;
  }
 
  // Show files with differences (with links to diff pages)
  if (filesWithDiffs.length > 0) {
    filesList += `
    <div class="files-list">
      <h2>Files with Differences</h2>
      ${filesWithDiffs.map((file) => generateFileItem(file, true)).join('')}
    </div>`;
  }
 
  // Show identical files (no links, just display)
  Eif (identicalFiles.length > 0) {
    const checkmark = filesWithDiffs.length === 0 ? ' āœ“' : '';
    filesList += `
    <div class="files-list">
      <h2>Identical Files${checkmark}</h2>
      ${identicalFiles.map((file) => generateFileItem(file, false)).join('')}
    </div>`;
  }
 
  return filesList;
}
 
/**
 * Generate index HTML page for comparison report
 * @param {Object} report - Full comparison report
 * @returns {string} HTML content
 */
export function generateIndexHtml(report) {
  const filesWithDiffs = report.files.filter((f) => f.status !== 'identical');
  const identicalFiles = report.files.filter((f) => f.status === 'identical');
 
  const filesList = generateFilesList(filesWithDiffs, identicalFiles);
 
  return renderTemplate('index.html', {
    reportName: report.name,
    timestamp: new Date(report.timestamp).toLocaleString(),
    sha: report.sha || 'unknown',
    baselinePath: report.baselinePath,
    sourcePath: report.sourcePath,
    summaryTotal: report.summary.total,
    summaryIdentical: report.summary.identical,
    summaryDifferent: report.summary.different,
    summaryAdded: report.summary.added,
    summaryRemoved: report.summary.removed,
    filesList: filesList,
  });
}
 
/**
 * Generate text report
 * @param {Object} report - Full comparison report
 * @returns {string} Text report content
 */
export function generateTextReport(report) {
  let text = `${report.name} - Comparison Report\n`;
  text += '='.repeat(50) + '\n\n';
  text += `Timestamp: ${report.timestamp}\n`;
  text += `Commit: ${report.sha || 'unknown'}\n`;
  text += `Baseline: ${report.baselinePath}\n`;
  text += `Source: ${report.sourcePath}\n\n`;
  text += 'Summary:\n';
  text += `  Total files: ${report.summary.total}\n`;
  text += `  Identical: ${report.summary.identical}\n`;
  text += `  Different: ${report.summary.different}\n`;
  text += `  Added: ${report.summary.added}\n`;
  text += `  Removed: ${report.summary.removed}\n\n`;
 
  const filesWithDiffs = report.files.filter((f) => f.status !== 'identical');
  if (filesWithDiffs.length > 0) {
    text += 'Files with differences:\n';
    text += '-'.repeat(50) + '\n';
 
    filesWithDiffs.forEach((file) => {
      text += `\n${file.relativePath}:\n`;
      text += `  Status: ${file.status}\n`;
      Eif (file.status === 'different') {
        text += `  Lines added: ${file.linesAdded}\n`;
        text += `  Lines removed: ${file.linesRemoved}\n`;
      }
    });
  } else {
    text += '\nāœ“ All files match baseline!\n';
  }
 
  return text;
}