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 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 | 1x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 12x 12x 21x 12x 21x 6x 6x 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, renderTemplate } from './template-renderer.js';
// Re-export escapeHtml for backward compatibility
export { escapeHtml };
/**
* Compute the side-by-side hunks filename that pairs with a primary
* full-file HTML at `outputPath`. Centralized so the link rendering and the
* file emission stay in lockstep.
*
* @param {string} outputPath - Path to the primary `<safeName>.html`
* @returns {string} Path to `<safeName>.hunks.html`
*/
function hunksPathFor(outputPath) {
return outputPath.replace(/\.html$/, '.hunks.html');
}
/**
* Render the in-page view-toggle navigation injected into both the full-file
* and hunks HTMLs. Mirrors the link target so users can flip between
* "Full file (in-situ)" and "Hunks (side-by-side)" without going back to the
* index. The link to the *current* view is rendered as a non-link span.
*
* @param {Object} opts
* @param {string} opts.safeFileName - Base safe filename (no extension)
* @param {'full'|'hunks'} opts.activeView - Which view this header is being rendered into
* @param {boolean} opts.hunksAvailable - Whether the hunks HTML was emitted
* @returns {string} HTML for the toggle
*/
function generateViewToggle({ safeFileName, activeView, hunksAvailable }) {
const fullHref = `${safeFileName}.html`;
const hunksHref = `${safeFileName}.hunks.html`;
const fullCell =
activeView === 'full'
? `<span class="view-toggle__option view-toggle__option--active">Full file (in-situ)</span>`
: `<a class="view-toggle__option" href="${escapeHtml(fullHref)}">Full file (in-situ)</a>`;
const hunksCell = !hunksAvailable
? `<span class="view-toggle__option view-toggle__option--disabled" title="Side-by-side hunks view unavailable for this file">Hunks (side-by-side)</span>`
: activeView === 'hunks'
? `<span class="view-toggle__option view-toggle__option--active">Hunks (side-by-side)</span>`
: `<a class="view-toggle__option" href="${escapeHtml(hunksHref)}">Hunks (side-by-side)</a>`;
return `<div class="view-toggle">View as: ${fullCell}${hunksCell}</div>`;
}
/**
* Render the page header used at the top of both the full-file page
* (`full-file.html` template) and the hunks page (this same markup injected
* into diff2html-cli's standalone output by `writeHunksHtml`).
*
* The full-file page reaches its styles through `report.css` (linked via
* the template's `{{{styles}}}` slot). The hunks page can't — diff2html-cli
* emits a self-contained HTML that has no reference to our stylesheet — so
* when this helper is invoked for injection we additionally emit a `<style>`
* block carrying the rules from `report.css` for `.header`, `.header h1`,
* `.header .meta`, and `.view-toggle*`. Keep these inline rules in lockstep
* with `report.css` (any change to one must be mirrored to the other).
*
* @param {Object} opts
* @param {string} opts.relativePath - Path shown in the H1
* @param {string} opts.statusUppercase - Uppercased status string
* @param {Object} opts.viewToggleOpts - Args for `generateViewToggle`
* @param {boolean} [opts.includeInlineStyles=false] - When true, prepend a
* `<style>` block carrying the header + view-toggle rules. Used by the
* hunks-page injection path; the full-file template doesn't need it.
* @returns {string} Header HTML (optionally preceded by inline `<style>`)
*/
function generateInjectableHeader({
relativePath,
statusUppercase,
viewToggleOpts,
includeInlineStyles = false,
}) {
const headerMarkup = `<div class="header">
<h1>${escapeHtml(relativePath)}</h1>
<div class="meta">
<span>Status: ${escapeHtml(statusUppercase)}</span>
<span style="margin-left: 16px;"><a href="index.html">← Back to index</a></span>
</div>
${generateViewToggle(viewToggleOpts)}
</div>`;
Iif (!includeInlineStyles) {
return headerMarkup;
}
// Mirrors the matching ruleset in `scripts/validation/styles/report.css`.
// Keep both copies in sync.
const inlineStyles = `<style>
.hunks-body {
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
font-size: 13px;
}
.header {
background: #252526;
border-bottom: 1px solid #3e3e42;
padding: 12px 20px;
position: sticky;
top: 0;
z-index: 100;
}
.header h1 {
font-size: 14px;
font-weight: 600;
color: #cccccc;
margin: 0;
}
.header .meta {
font-size: 11px;
color: #858585;
margin-top: 4px;
margin-bottom: 0;
}
.header .meta a { color: #4ec9b0; text-decoration: none; }
.header .meta a:hover { text-decoration: underline; }
.view-toggle { margin-top: 8px; font-size: 12px; color: #858585; }
.view-toggle__option {
display: inline-block;
margin-left: 8px;
padding: 3px 8px;
border: 1px solid #3e3e42;
border-radius: 4px;
color: #4ec9b0;
text-decoration: none;
}
.view-toggle__option:hover { background: #2a2a2a; text-decoration: none; }
.view-toggle__option--active {
background: #094771;
border-color: #094771;
color: #ffffff;
cursor: default;
}
.view-toggle__option--disabled { color: #6a6a6a; cursor: not-allowed; }
</style>`;
return inlineStyles + headerMarkup;
}
/**
* Generate HTML diff(s) for a single file. Always emits the in-situ full-file
* HTML at `outputPath` (primary view). Additionally emits a side-by-side
* hunks HTML at `<outputPath>.hunks.html` (secondary view), produced by
* `diff2html-cli`.
*
* The two views are complementary, not redundant:
* - **Full file (in-situ)** renders every line of the current file with
* `+`/`-`/context markers inline. Best for verifying that *unchanged*
* regions are actually unchanged and for orienting around large files.
* Pure JS, no external binary, works offline.
* - **Hunks (side-by-side)** is `diff2html-cli`'s side-by-side renderer,
* showing only changed regions plus a few context lines. Best for
* focusing on the actual changes when files are large.
*
* `diff2html-cli` is declared as a devDependency of
* `@salesforce-ux/design-system` so `npx diff2html-cli` resolves the
* locally-installed binary via `node_modules/.bin/`. We deliberately do NOT
* pass `--yes`: that flag tells npx to fetch the package on demand if it's
* missing, which both (a) hits the network on every invocation, and
* (b) silently degrades the secondary view whenever the registry is
* unreachable (sandboxed shells, offline, transient proxy 403s). Without
* `--yes`, a missing install fails fast and we emit only the primary view
* with a disabled "Hunks" link.
*
* @param {Object} result - Comparison result
* @param {string} outputPath - Path for the primary `<safeName>.html`
* @param {string} reportDir - Report directory for temp files
* @param {string} reportName - Name of the report for header
* @returns {boolean} True if at least the primary HTML was written
*/
export function generateHtmlDiff(result, outputPath, reportDir, reportName = 'Comparison') {
const { relativePath } = result;
const safeFileName = path.basename(outputPath, '.html');
const hunksPath = hunksPathFor(outputPath);
// Write the secondary hunks view first so the primary view's toggle can
// accurately reflect whether the hunks HTML actually exists on disk. If
// the hunks emission fails we drop the link from both pages.
const hunksAvailable = writeHunksHtml({
result,
hunksPath,
reportDir,
reportName,
safeFileName,
});
// Primary view: always emit. Pure JS, no external binary.
const fullHtml = generateFullFileHtml(result, {
reportName,
safeFileName,
hunksAvailable,
});
fs.writeFileSync(outputPath, fullHtml, 'utf8');
return true;
}
/**
* Render and write the side-by-side hunks HTML via `diff2html-cli`.
*
* Returns `true` on success, `false` if the binary failed/was unavailable
* (in which case the primary view's toggle will render the Hunks link as
* disabled).
*
* @returns {boolean}
*/
function writeHunksHtml({ result, hunksPath, reportDir, reportName, safeFileName }) {
const { relativePath, status, baselineContent, currentContent } = result;
// Hard ceiling on every `npx diff2html-cli` spawn so a hung binary (most
// commonly: cold CI runners that resolve the bin slowly, sandboxed shells
// where npx tries — and stalls — on a network probe) fails fast and we
// gracefully fall back to "full-file only" instead of timing out the
// surrounding test/validation run.
const execOpts = { cwd: reportDir, stdio: 'pipe', timeout: 20_000 };
try {
Iif (status === 'added' || status === 'removed') {
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 diff2html-cli -i stdin -s side -F "${hunksPath}"`,
execOpts,
);
fs.removeSync(currentFile);
} else {
const baselineFile = path.join(reportDir, '.baseline');
fs.writeFileSync(baselineFile, baselineContent, 'utf8');
execSync(
`diff -u "${baselineFile}" "${emptyFile}" | npx diff2html-cli -i stdin -s side -F "${hunksPath}"`,
execOpts,
);
fs.removeSync(baselineFile);
}
fs.removeSync(emptyFile);
} else {
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 diff2html-cli -i stdin -s side -F "${hunksPath}"`,
execOpts,
);
} catch (e) {
// `diff` returns exit 1 when files differ — that's normal. Only
// re-throw if diff2html-cli truly failed to produce a file.
if (!fs.existsSync(hunksPath)) {
throw e;
}
}
fs.removeSync(baselineFile);
fs.removeSync(currentFile);
}
Iif (!fs.existsSync(hunksPath)) {
return false;
}
// Post-process the diff2html-cli output:
// 1. Set a meaningful `<title>`.
// 2. Strip the default `style="text-align:center; font-family: …"`
// attribute that ships on diff2html-cli's `<body>`. The center
// alignment is fine for diff2html's own demo page but clashes with
// our left-aligned `.header` chrome (and looks visually inconsistent
// with the full-file view).
// 3. Strip diff2html-cli's "Diff to HTML by rtfpessoa" branding `<h1>`
// that sits between `<body>` and the `<div id="diff">` wrapper.
// 4. Inject the same `.header` markup the full-file page uses so both
// views present an identical chrome. The hunks page can't reach
// `report.css` (diff2html-cli emits a self-contained HTML with no
// link to our stylesheet), so this branch passes
// `includeInlineStyles: true` to embed the matching ruleset.
let html = fs.readFileSync(hunksPath, 'utf8');
html = html.replace(
/<title>.*?<\/title>/,
`<title>${escapeHtml(relativePath)} - ${escapeHtml(reportName)}</title>`,
);
// Drop the inline `style="…"` from `<body>` (centers content + sets
// diff2html's preferred sans-serif) and tag the body with our
// `.hunks-body` class so the inline styles below can target it (and
// pair symmetrically with the full-file page's `.full-file-body`).
// Leave any other body attributes that diff2html-cli might add intact.
html = html.replace(
/<body([^>]*)\sstyle="[^"]*"([^>]*)>/,
'<body$1$2 class="hunks-body">',
);
// Remove the "Diff to HTML by rtfpessoa" attribution `<h1>` (visible)
// and the corresponding `<!-- Diff to HTML (template.html) Author:
// rtfpessoa -->` comment in `<head>` (not rendered, but tidies the
// source so the report is unambiguously ours).
html = html.replace(
/\s*<h1>Diff to HTML by\s*<a[^>]*>rtfpessoa<\/a>\s*<\/h1>\s*/,
'\n',
);
html = html.replace(/\s*<!--\s*Diff to HTML[\s\S]*?-->\s*/, '\n');
const customHeader = generateInjectableHeader({
relativePath,
statusUppercase: status.toUpperCase(),
viewToggleOpts: {
safeFileName,
activeView: 'hunks',
hunksAvailable: true,
},
includeInlineStyles: true,
});
html = html.replace(/<body[^>]*>/, `$&${customHeader}`);
fs.writeFileSync(hunksPath, html, 'utf8');
return true;
} catch (error) {
console.warn(
`Warning: diff2html-cli unavailable for ${relativePath}; emitting full-file view only.`,
);
if (fs.existsSync(hunksPath)) {
fs.removeSync(hunksPath);
}
return false;
}
}
/**
* Render the in-situ full-file HTML diff (primary view).
*
* Iterates over `result.diff` (output of the `diff` npm package) and emits
* every line of the current file with a `+`/`-`/context marker. Self-contained
* — no external binary, works offline.
*
* @param {Object} result - Comparison result
* @param {Object} [opts] - Rendering options
* @param {string} [opts.reportName] - Name of the report (for the page header link)
* @param {string} [opts.safeFileName] - Base safe filename for the view toggle
* @param {boolean} [opts.hunksAvailable] - Whether the hunks HTML was emitted
* @returns {string} HTML content
*/
export function generateFullFileHtml(result, opts = {}) {
const { relativePath, status, diff, linesAdded, linesRemoved } = result;
const {
safeFileName = path.basename(relativePath).replace(/[^a-zA-Z0-9]/g, '_'),
hunksAvailable = false,
} = opts;
// Markup is intentionally minimal: just `<div class="line {status}">text</div>`
// per line. The two-column line-number gutter (`old | new`) is rendered by
// pure CSS counters in `report.css` — `.content` resets `oldNo`/`newNo`,
// each `.line.{added,removed,context}` increments the appropriate
// counter(s), and `::before`/`::after` print them. This keeps the per-file
// payload lean (no extra spans per line) while still producing the same
// GitHub/git-diff-style gutter at render time.
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>`;
});
});
}
const viewToggle = generateViewToggle({
safeFileName,
activeView: 'full',
hunksAvailable,
});
return renderTemplate('full-file.html', {
relativePath: relativePath,
statusUppercase: status.toUpperCase(),
diffContent: diffContent,
linesAdded: linesAdded,
linesRemoved: linesRemoved,
viewToggle,
});
}
/**
* 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 Iif (file.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;
}
|