@allons-y/actions-file-diff 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -25678,7 +25678,7 @@ function getOctokit(token, options, ...additionalPlugins) {
25678
25678
 
25679
25679
  // src/changes.js
25680
25680
  import { execFile } from "node:child_process";
25681
- import { closeSync, openSync, readSync } from "node:fs";
25681
+ import { closeSync, mkdtempSync, openSync, readFileSync as readFileSync3, readSync, rmSync, writeFileSync } from "node:fs";
25682
25682
  import { devNull, tmpdir } from "node:os";
25683
25683
  import { join as join6 } from "node:path";
25684
25684
  import { promisify } from "node:util";
@@ -25885,7 +25885,7 @@ import * as os6 from "os";
25885
25885
  import * as path9 from "path";
25886
25886
  import assert3 from "assert";
25887
25887
 
25888
- // node_modules/brace-expansion/node_modules/balanced-match/dist/esm/index.js
25888
+ // node_modules/balanced-match/dist/esm/index.js
25889
25889
  var balanced = (a, b, str) => {
25890
25890
  const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
25891
25891
  const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
@@ -28399,11 +28399,11 @@ function buildFileRow({ readableFilename, files, hasBase, isMainFile = false })
28399
28399
  const gzipSize = removed ? " - " : siblingCell(gzippedName(readableFilename));
28400
28400
  return [isMainFile ? `**${readableFilename}**` : readableFilename, size, minSize, gzipSize, ...hasBase ? [delta] : []];
28401
28401
  }
28402
- function buildSections(packages, { hasBase, rootPath = ".", buildDir = DEFAULT_BUILD_DIR, mainFile = DEFAULT_MAIN_FILE, readPackageJson = true, core } = {}) {
28402
+ function buildSections(packages, { hasBase, changed, rootPath = ".", buildDir = DEFAULT_BUILD_DIR, mainFile = DEFAULT_MAIN_FILE, readPackageJson = true, core } = {}) {
28403
28403
  const sections = [];
28404
28404
  packages.forEach(({ name, packageDir, files }) => {
28405
28405
  if (files.size === 0) return;
28406
- const hasChange = [...files.values()].some(({ headByteSize, baseByteSize }) => headByteSize !== baseByteSize);
28406
+ const hasChange = [...files.values()].some(({ path: path11, headByteSize, baseByteSize }) => changed ? changed.has(path11) : headByteSize !== baseByteSize);
28407
28407
  if (hasBase && !hasChange) return;
28408
28408
  sections.push({
28409
28409
  name,
@@ -28429,14 +28429,15 @@ function fitRows(rows, budget) {
28429
28429
  }
28430
28430
  return { kept, used };
28431
28431
  }
28432
- function buildReport({ headMap = /* @__PURE__ */ new Map(), baseMap = /* @__PURE__ */ new Map(), hasBase = baseMap.size > 0, rootPath = ".", buildDir = DEFAULT_BUILD_DIR, mainFile = DEFAULT_MAIN_FILE, readPackageJson = true, extensions = [], maxLength = Infinity, core } = {}) {
28432
+ function buildReport({ headMap = /* @__PURE__ */ new Map(), baseMap = /* @__PURE__ */ new Map(), hasBase = baseMap.size > 0, changed, rootPath = ".", buildDir = DEFAULT_BUILD_DIR, mainFile = DEFAULT_MAIN_FILE, readPackageJson = true, extensions = [], maxLength = Infinity, core } = {}) {
28433
28433
  const allowed = normalizeExtensions(extensions);
28434
28434
  const head = filterByExtensions(headMap, allowed);
28435
28435
  const base = hasBase ? filterByExtensions(baseMap, allowed) : /* @__PURE__ */ new Map();
28436
28436
  const headTotal = totalSize(head);
28437
28437
  const baseTotal = hasBase ? totalSize(base) : 0;
28438
- const hasChanged = hasBase && headTotal !== baseTotal;
28439
- const sections = buildSections(groupByPackage(head, base, { buildDir }), { hasBase, rootPath, buildDir, mainFile, readPackageJson, core });
28438
+ const sizeChanged = hasBase && headTotal !== baseTotal;
28439
+ const sections = buildSections(groupByPackage(head, base, { buildDir }), { hasBase, changed, rootPath, buildDir, mainFile, readPackageJson, core });
28440
+ const hasChanged = hasBase && (changed ? sections.length > 0 : sizeChanged);
28440
28441
  const summary2 = ["### Summary", `**Total size**: ${bytesToSize(headTotal)}<sup>*</sup>`];
28441
28442
  const markdown = [];
28442
28443
  const omitted = { files: 0, packages: 0 };
@@ -28480,11 +28481,11 @@ function buildReport({ headMap = /* @__PURE__ */ new Map(), baseMap = /* @__PURE
28480
28481
  if (omitted.packages > 0) markdown.push("", `<em>\u2026 ${omitted.packages} more ${omitted.packages === 1 ? "package" : "packages"} not shown.</em>`);
28481
28482
  if (!hasBase) {
28482
28483
  summary2.push("No base branch to compare against.", "");
28483
- } else if (hasChanged) {
28484
+ } else if (sizeChanged) {
28484
28485
  const percent = printPercentChange(headTotal, baseTotal);
28485
- summary2.push(`**Total change (\u0394)**: ${printChange(headTotal, baseTotal)}${percent ? ` (${percent})` : ""}`, "", `<small><em>Table reports on changes to a package's main file.${sections.length > 1 ? ` Other changes can be found in the collapsed <a href="#details">Details</a> section below.` : ""}</em></small>`, "");
28486
+ summary2.push(`**Total change (\u0394)**: ${printChange(headTotal, baseTotal)}${percent ? ` (${percent})` : ""}`, "", `<small><em>Table reports on changes to a package's main file.${sections.length > 1 ? ' Other changes can be found in the collapsed <a href="#details">Details</a> section below.' : ""}</em></small>`, "");
28486
28487
  } else {
28487
- summary2.push("\u2705 **No change in file sizes**", "");
28488
+ summary2.push(hasChanged ? "\u2705 **No change in total size**" : "\u2705 **No change in file sizes**", "");
28488
28489
  }
28489
28490
  if (sections.length > 1) {
28490
28491
  markdown.unshift('<a name="details"></a>', "<details>", "<summary><b>File change details</b></summary>", "");
@@ -28519,6 +28520,10 @@ var DIFF_CONCURRENCY = 4;
28519
28520
  var SNIFF_BYTES = 8e3;
28520
28521
  var COMPARE_CHUNK = 64 * 1024;
28521
28522
  var MAX_OUTPUT = 32 * 1024 * 1024;
28523
+ var IGNORED = "[ignored]";
28524
+ function ignoreMatches(text, patterns) {
28525
+ return patterns.reduce((out, pattern) => out.replace(pattern, IGNORED), text);
28526
+ }
28522
28527
  function isBinary(buffer) {
28523
28528
  return buffer.subarray(0, SNIFF_BYTES).includes(0);
28524
28529
  }
@@ -28532,13 +28537,32 @@ function isBinaryFile(path11) {
28532
28537
  closeSync(fd);
28533
28538
  }
28534
28539
  }
28540
+ var COMPRESSED = /\.(gz|br|zst)$/i;
28541
+ var isCompressed = (file) => COMPRESSED.test(file);
28542
+ var stripCompression = (file) => file.replace(COMPRESSED, "");
28543
+ function contentDiffers({ headRoot, baseRoot, file, headByteSize, baseByteSize, ignorePatterns = [], maxDiffSize = DEFAULT_MAX_DIFF_SIZE }) {
28544
+ if (headByteSize == null || baseByteSize == null || !baseRoot) return headByteSize !== baseByteSize;
28545
+ const headPath = join6(headRoot, file);
28546
+ const basePath = join6(baseRoot, file);
28547
+ try {
28548
+ if (ignorePatterns.length === 0 || Math.max(headByteSize, baseByteSize) > maxDiffSize) return headByteSize !== baseByteSize || !sameContent(headPath, basePath);
28549
+ const headContent = readFileSync3(headPath);
28550
+ const baseContent = readFileSync3(basePath);
28551
+ if (headByteSize === baseByteSize && headContent.equals(baseContent)) return false;
28552
+ if (isBinary(headContent) || isBinary(baseContent)) return true;
28553
+ return ignoreMatches(headContent.toString("utf8"), ignorePatterns) !== ignoreMatches(baseContent.toString("utf8"), ignorePatterns);
28554
+ } catch {
28555
+ return true;
28556
+ }
28557
+ }
28558
+ var compareBuffers = [Buffer.allocUnsafe(COMPARE_CHUNK), Buffer.allocUnsafe(COMPARE_CHUNK)];
28535
28559
  function sameContent(a, b) {
28536
28560
  const fa = openSync(a, "r");
28537
28561
  let fb;
28538
28562
  try {
28539
28563
  fb = openSync(b, "r");
28540
- const bufA = Buffer.alloc(COMPARE_CHUNK);
28541
- const bufB = Buffer.alloc(COMPARE_CHUNK);
28564
+ const bufA = compareBuffers[0];
28565
+ const bufB = compareBuffers[1];
28542
28566
  for (let position = 0; ; position += COMPARE_CHUNK) {
28543
28567
  const readA = readSync(fa, bufA, 0, COMPARE_CHUNK, position);
28544
28568
  const readB = readSync(fb, bufB, 0, COMPARE_CHUNK, position);
@@ -28599,25 +28623,47 @@ async function gitDiff({ basePath, headPath, git = "git", timeout = DIFF_TIMEOUT
28599
28623
  throw Object.assign(new Error(reason), { reason, cause: error2 });
28600
28624
  }
28601
28625
  }
28602
- async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), headRoot, baseRoot, extensions = [], maxDiffSize = DEFAULT_MAX_DIFF_SIZE, maxDiffLines = DEFAULT_MAX_DIFF_LINES, git = "git", diffTimeout = DIFF_TIMEOUT, diffTimeBudget = DIFF_TIME_BUDGET, core }) {
28626
+ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), headRoot, baseRoot, renames = /* @__PURE__ */ new Map(), ignorePatterns = [], extensions = [], maxDiffSize = DEFAULT_MAX_DIFF_SIZE, maxDiffLines = DEFAULT_MAX_DIFF_LINES, git = "git", diffTimeout = DIFF_TIMEOUT, diffTimeBudget = DIFF_TIME_BUDGET, diffs = true, core }) {
28603
28627
  const allowed = normalizeExtensions(extensions);
28604
28628
  const head = filterByExtensions(headMap, allowed);
28605
28629
  const base = filterByExtensions(baseMap, allowed);
28606
28630
  const text = [];
28607
28631
  const images = [];
28608
28632
  const stats = { added: 0, removed: 0, modified: 0, additions: 0, deletions: 0 };
28633
+ const changed = /* @__PURE__ */ new Set();
28609
28634
  const pending = [];
28610
28635
  const unreadable = [];
28611
- const files = [.../* @__PURE__ */ new Set([...head.keys(), ...base.keys()])].filter(isReportedFile).sort();
28636
+ const all = [.../* @__PURE__ */ new Set([...head.keys(), ...base.keys()])].sort();
28637
+ const hasSource = (file) => isCompressed(file) && (head.has(stripCompression(file)) || base.has(stripCompression(file)));
28638
+ const files = all.filter((file) => isReportedFile(file) && !hasSource(file));
28639
+ const reported = new Set(files);
28640
+ const derived = all.filter((file) => !reported.has(file));
28612
28641
  files.forEach((file) => {
28613
28642
  const headByteSize = head.get(file);
28614
28643
  const baseByteSize = base.get(file);
28615
28644
  const status = changeStatus(headByteSize, baseByteSize);
28616
28645
  if (!status) return;
28617
28646
  const headPath = headByteSize != null ? join6(headRoot, file) : void 0;
28618
- const basePath = baseByteSize != null && baseRoot ? join6(baseRoot, file) : void 0;
28647
+ const from = renames.get(file);
28648
+ const basePath = baseByteSize != null && baseRoot ? join6(baseRoot, from ?? file) : void 0;
28619
28649
  let failure;
28620
- if (status === "modified" && headByteSize === baseByteSize) {
28650
+ let ignored;
28651
+ let binary;
28652
+ const textFile = !isImage(file) || baseExtension(file) === "svg";
28653
+ if (status === "modified" && ignorePatterns.length > 0 && textFile && Math.max(headByteSize, baseByteSize) <= maxDiffSize) {
28654
+ try {
28655
+ const headContent = readFileSync3(headPath);
28656
+ const baseContent = readFileSync3(basePath);
28657
+ if (headByteSize === baseByteSize && headContent.equals(baseContent)) return;
28658
+ binary = isBinary(headContent) || isBinary(baseContent);
28659
+ if (!binary) {
28660
+ ignored = { head: ignoreMatches(headContent.toString("utf8"), ignorePatterns), base: ignoreMatches(baseContent.toString("utf8"), ignorePatterns) };
28661
+ if (ignored.head === ignored.base) return;
28662
+ }
28663
+ } catch (error2) {
28664
+ failure = error2;
28665
+ }
28666
+ } else if (status === "modified" && headByteSize === baseByteSize) {
28621
28667
  try {
28622
28668
  if (sameContent(headPath, basePath)) return;
28623
28669
  } catch (error2) {
@@ -28625,15 +28671,18 @@ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), he
28625
28671
  }
28626
28672
  }
28627
28673
  stats[status]++;
28674
+ changed.add(file);
28675
+ if (!diffs) return;
28628
28676
  if (isImage(file)) {
28629
- images.push({ file, status, headByteSize, baseByteSize, headPath, basePath });
28677
+ images.push({ file, status, headByteSize, baseByteSize, headPath, basePath, ...from ? { from } : {} });
28630
28678
  if (baseExtension(file) !== "svg") return;
28631
28679
  }
28632
- const change = { file, status, additions: 0, deletions: 0, hunks: [] };
28680
+ const change = { file, status, additions: 0, deletions: 0, hunks: [], ...from ? { from } : {} };
28633
28681
  text.push(change);
28634
28682
  if (!failure) {
28635
28683
  try {
28636
- if (headPath && isBinaryFile(headPath) || basePath && isBinaryFile(basePath)) {
28684
+ binary ??= Boolean(headPath && isBinaryFile(headPath) || basePath && isBinaryFile(basePath));
28685
+ if (binary) {
28637
28686
  change.skipped = "binary file";
28638
28687
  return;
28639
28688
  }
@@ -28650,45 +28699,62 @@ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), he
28650
28699
  change.skipped = "file exceeds max-diff-size";
28651
28700
  return;
28652
28701
  }
28653
- pending.push({ change, headPath, basePath });
28702
+ pending.push({ change, headPath, basePath, ignored });
28703
+ });
28704
+ derived.filter((file) => !hasSource(file)).forEach((file) => {
28705
+ if (contentDiffers({ headRoot, baseRoot, file, headByteSize: head.get(file), baseByteSize: base.get(file), ignorePatterns, maxDiffSize })) changed.add(file);
28706
+ });
28707
+ derived.filter(hasSource).forEach((file) => {
28708
+ if (changed.has(stripCompression(file))) changed.add(file);
28654
28709
  });
28655
28710
  if (unreadable.length > 0) core?.warning?.(`Could not read ${unreadable.length} file${unreadable.length === 1 ? "" : "s"}; listed without a diff: ${unreadable.slice(0, 5).join(", ")}${unreadable.length > 5 ? ", \u2026" : ""}`);
28656
28711
  if (pending.length > 0 && !await hasGit(git)) {
28657
28712
  core?.warning?.("`git` was not found on the PATH, so line diffs are skipped. Install git (it is preinstalled on GitHub-hosted runners) to see them.");
28658
28713
  pending.forEach(({ change }) => change.skipped = "git is not available on PATH");
28659
- return { text, images, stats };
28714
+ return { text, images, stats, changed };
28660
28715
  }
28661
28716
  const started = Date.now();
28662
28717
  let retained = 0;
28663
- for (let i = 0; i < pending.length; i += DIFF_CONCURRENCY * 8) {
28664
- const batch = pending.slice(i, i + DIFF_CONCURRENCY * 8);
28665
- const results = await mapLimit(batch, DIFF_CONCURRENCY, async ({ headPath, basePath }) => {
28666
- if (Date.now() - started > diffTimeBudget) return { reason: "diff time budget exhausted" };
28667
- try {
28668
- return await gitDiff({ basePath, headPath, git, timeout: diffTimeout });
28669
- } catch (error2) {
28670
- return { reason: error2.reason ?? error2.message };
28671
- }
28672
- });
28673
- results.forEach((result, index) => {
28674
- const { change } = batch[index];
28675
- if (result.reason) {
28676
- change.skipped = result.reason;
28677
- return;
28678
- }
28679
- change.additions = result.additions;
28680
- change.deletions = result.deletions;
28681
- stats.additions += result.additions;
28682
- stats.deletions += result.deletions;
28683
- const lines = result.hunks.reduce((sum, hunk) => sum + hunk.lines.length + 1, 0);
28684
- if (retained + lines > maxDiffLines) change.omitted = `the report's diff budget (${maxDiffLines.toLocaleString("en-US")} lines) is used up`;
28685
- else {
28686
- retained += lines;
28687
- change.hunks = result.hunks;
28688
- }
28689
- });
28718
+ const scratch = pending.some(({ ignored }) => ignored) ? mkdtempSync(join6(tmpdir(), "file-diff-")) : void 0;
28719
+ try {
28720
+ for (let i = 0; i < pending.length; i += DIFF_CONCURRENCY * 8) {
28721
+ const batch = pending.slice(i, i + DIFF_CONCURRENCY * 8);
28722
+ const results = await mapLimit(batch, DIFF_CONCURRENCY, async ({ headPath, basePath, ignored }, index) => {
28723
+ if (Date.now() - started > diffTimeBudget) return { reason: "diff time budget exhausted" };
28724
+ try {
28725
+ if (!ignored) return await gitDiff({ basePath, headPath, git, timeout: diffTimeout });
28726
+ const copy = (side) => {
28727
+ const path11 = join6(scratch, `${i + index}.${side}`);
28728
+ writeFileSync(path11, ignored[side]);
28729
+ return path11;
28730
+ };
28731
+ return await gitDiff({ basePath: copy("base"), headPath: copy("head"), git, timeout: diffTimeout });
28732
+ } catch (error2) {
28733
+ return { reason: error2.reason ?? error2.message };
28734
+ }
28735
+ });
28736
+ results.forEach((result, index) => {
28737
+ const { change } = batch[index];
28738
+ if (result.reason) {
28739
+ change.skipped = result.reason;
28740
+ return;
28741
+ }
28742
+ change.additions = result.additions;
28743
+ change.deletions = result.deletions;
28744
+ stats.additions += result.additions;
28745
+ stats.deletions += result.deletions;
28746
+ const lines = result.hunks.reduce((sum, hunk) => sum + hunk.lines.length + 1, 0);
28747
+ if (retained + lines > maxDiffLines) change.omitted = `the report's diff budget (${maxDiffLines.toLocaleString("en-US")} lines) is used up`;
28748
+ else {
28749
+ retained += lines;
28750
+ change.hunks = result.hunks;
28751
+ }
28752
+ });
28753
+ }
28754
+ } finally {
28755
+ if (scratch) rmSync(scratch, { recursive: true, force: true });
28690
28756
  }
28691
- return { text, images, stats };
28757
+ return { text, images, stats, changed };
28692
28758
  }
28693
28759
 
28694
28760
  // src/comment.js
@@ -28784,6 +28850,119 @@ async function publishToBranch({ octokit, owner, repo, branch, dir, files, messa
28784
28850
  }
28785
28851
  }
28786
28852
 
28853
+ // src/renames.js
28854
+ import { readFileSync as readFileSync4 } from "node:fs";
28855
+ import { join as join7 } from "node:path";
28856
+ var DEFAULT_RENAME_THRESHOLD = 50;
28857
+ var MAX_RENAME_CANDIDATES = 200;
28858
+ var MAX_RENAME_SIZE = 1024 * 1024;
28859
+ var RENAME_TIME_BUDGET = 3e4;
28860
+ var PLACEHOLDER = "[hash]";
28861
+ var CHUNK = 64;
28862
+ var BOUNDARY = /(?<=[\n}])/;
28863
+ function compileNamePatterns(lines = [], input = "normalize-names") {
28864
+ return lines.map((line) => String(line ?? "").trim()).filter(Boolean).map((line) => {
28865
+ try {
28866
+ return new RegExp(line, "g");
28867
+ } catch (error2) {
28868
+ throw new Error(`Invalid ${input} pattern "${line}": ${error2.message}`, { cause: error2 });
28869
+ }
28870
+ });
28871
+ }
28872
+ function normalizeName(path11, patterns) {
28873
+ return patterns.reduce((name, pattern) => name.replace(pattern, PLACEHOLDER), path11);
28874
+ }
28875
+ function chunkCounts(content) {
28876
+ const counts = /* @__PURE__ */ new Map();
28877
+ content.toString("latin1").split(BOUNDARY).forEach((piece) => {
28878
+ for (let i = 0; i < piece.length; i += CHUNK) {
28879
+ const chunk = piece.slice(i, i + CHUNK);
28880
+ counts.set(chunk, (counts.get(chunk) ?? 0) + 1);
28881
+ }
28882
+ });
28883
+ return counts;
28884
+ }
28885
+ function chunkSimilarity(sizeA, countsA, sizeB, countsB) {
28886
+ const larger = Math.max(sizeA, sizeB);
28887
+ if (larger === 0) return 100;
28888
+ const [small, big] = countsA.size <= countsB.size ? [countsA, countsB] : [countsB, countsA];
28889
+ let shared = 0;
28890
+ small.forEach((count, chunk) => {
28891
+ shared += Math.min(count, big.get(chunk) ?? 0) * chunk.length;
28892
+ });
28893
+ return Math.floor(shared / larger * 100);
28894
+ }
28895
+ function groupBy(paths, key) {
28896
+ const groups = /* @__PURE__ */ new Map();
28897
+ paths.forEach((path11) => {
28898
+ const k = key(path11);
28899
+ groups.set(k, [...groups.get(k) ?? [], path11]);
28900
+ });
28901
+ return groups;
28902
+ }
28903
+ function matchRenames({ headMap, baseMap, headRoot, baseRoot, normalizeNames = [], threshold = DEFAULT_RENAME_THRESHOLD, maxCandidates = MAX_RENAME_CANDIDATES, maxSize = MAX_RENAME_SIZE, timeBudget = RENAME_TIME_BUDGET, now = Date.now }) {
28904
+ const renames = /* @__PURE__ */ new Map();
28905
+ const deadline = now() + timeBudget;
28906
+ let timedOut = false;
28907
+ const onlyHead = new Set([...headMap.keys()].filter((path11) => !baseMap.has(path11)));
28908
+ const onlyBase = new Set([...baseMap.keys()].filter((path11) => !headMap.has(path11)));
28909
+ const pair = (head, base) => {
28910
+ renames.set(head, base);
28911
+ onlyHead.delete(head);
28912
+ onlyBase.delete(base);
28913
+ };
28914
+ if (normalizeNames.length > 0) {
28915
+ const heads = groupBy([...onlyHead], (path11) => normalizeName(path11, normalizeNames));
28916
+ groupBy([...onlyBase], (path11) => normalizeName(path11, normalizeNames)).forEach((bases, name) => {
28917
+ const matches = heads.get(name);
28918
+ if (bases.length === 1 && matches?.length === 1 && name !== bases[0]) pair(matches[0], bases[0]);
28919
+ });
28920
+ }
28921
+ if (threshold > 0 && onlyHead.size > 0 && onlyBase.size > 0) {
28922
+ const heads = groupBy([...onlyHead], baseExtension);
28923
+ groupBy([...onlyBase], baseExtension).forEach((bases, ext2) => {
28924
+ const candidates = heads.get(ext2) ?? [];
28925
+ if (timedOut || candidates.length === 0 || bases.length > maxCandidates || candidates.length > maxCandidates) return;
28926
+ const read = (root, map) => (path11) => {
28927
+ if (map.get(path11) > maxSize) return void 0;
28928
+ try {
28929
+ return readFileSync4(join7(root, path11));
28930
+ } catch {
28931
+ return void 0;
28932
+ }
28933
+ };
28934
+ const baseContent = new Map(bases.map((path11) => [path11, read(baseRoot, baseMap)(path11)]));
28935
+ const headContent = new Map(candidates.map((path11) => [path11, read(headRoot, headMap)(path11)]));
28936
+ const counts = new Map([...baseContent.values(), ...headContent.values()].filter((content) => content && !isBinary(content)).map((content) => [content, chunkCounts(content)]));
28937
+ const scores = [];
28938
+ baseContent.forEach((b, base) => {
28939
+ if (!b || timedOut) return;
28940
+ if (now() > deadline) {
28941
+ timedOut = true;
28942
+ return;
28943
+ }
28944
+ headContent.forEach((h, head) => {
28945
+ if (!h) return;
28946
+ if (Math.min(b.length, h.length) * 100 < threshold * Math.max(b.length, h.length)) return;
28947
+ const score = counts.has(b) && counts.has(h) ? chunkSimilarity(b.length, counts.get(b), h.length, counts.get(h)) : b.equals(h) ? 100 : 0;
28948
+ if (score >= threshold) scores.push({ base, head, score });
28949
+ });
28950
+ });
28951
+ scores.sort((x, y) => y.score - x.score || x.base.localeCompare(y.base) || x.head.localeCompare(y.head));
28952
+ scores.forEach(({ base, head }) => {
28953
+ if (onlyBase.has(base) && onlyHead.has(head)) pair(head, base);
28954
+ });
28955
+ });
28956
+ }
28957
+ if (renames.size === 0) return { baseMap, renames, timedOut };
28958
+ const remapped = new Map(baseMap);
28959
+ renames.forEach((base, head) => {
28960
+ remapped.delete(base);
28961
+ remapped.set(head, baseMap.get(base));
28962
+ });
28963
+ return { baseMap: remapped, renames, timedOut };
28964
+ }
28965
+
28787
28966
  // src/inputs.js
28788
28967
  var VISUAL_DIFF_MODES = ["summary", "branch", "none"];
28789
28968
  var BRANCH_NAME = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;
@@ -28801,6 +28980,8 @@ function readInputs(core) {
28801
28980
  if (!VISUAL_DIFF_MODES.includes(visualDiff)) throw new Error(`Invalid visual-diff "${visualDiff}"; expected one of: ${VISUAL_DIFF_MODES.join(", ")}.`);
28802
28981
  const reportBranch = text("report-branch", DEFAULT_REPORT_BRANCH);
28803
28982
  if (!BRANCH_NAME.test(reportBranch) || reportBranch.includes("..") || reportBranch.endsWith(".lock") || reportBranch.endsWith(".")) throw new Error(`Invalid report-branch "${reportBranch}"; use letters, digits, ".", "_", "-" and "/" in a valid git branch name.`);
28983
+ const renameThreshold = count("rename-threshold", DEFAULT_RENAME_THRESHOLD);
28984
+ if (renameThreshold > 100) throw new Error(`Invalid rename-threshold "${renameThreshold}"; expected a percentage from 0 to 100.`);
28804
28985
  const pagesUrl = text("pages-url");
28805
28986
  if (pagesUrl) {
28806
28987
  let url;
@@ -28826,12 +29007,15 @@ function readInputs(core) {
28826
29007
  reportBranch,
28827
29008
  pagesUrl,
28828
29009
  maxDiffSize: count("max-diff-size", DEFAULT_MAX_DIFF_SIZE),
28829
- maxDiffLines: count("max-diff-lines", DEFAULT_MAX_DIFF_LINES)
29010
+ maxDiffLines: count("max-diff-lines", DEFAULT_MAX_DIFF_LINES),
29011
+ normalizeNames: compileNamePatterns(core.getMultilineInput("normalize-names", { trimWhitespace: true })),
29012
+ ignorePatterns: compileNamePatterns(core.getMultilineInput("ignore-patterns", { trimWhitespace: true }), "ignore-patterns"),
29013
+ renameThreshold
28830
29014
  };
28831
29015
  }
28832
29016
 
28833
29017
  // src/page.js
28834
- import { readFileSync as readFileSync3 } from "node:fs";
29018
+ import { readFileSync as readFileSync5 } from "node:fs";
28835
29019
 
28836
29020
  // node_modules/diff/libesm/diff/base.js
28837
29021
  var Diff = class {
@@ -29324,8 +29508,8 @@ function fenceFor(content) {
29324
29508
  const longest = Math.max(0, ...(String(content).match(/`+/g) ?? []).map((run2) => run2.length));
29325
29509
  return "`".repeat(Math.max(3, longest + 1));
29326
29510
  }
29327
- function unifiedDiff({ file, status, hunks }) {
29328
- const from = status === "added" ? "/dev/null" : `a/${file}`;
29511
+ function unifiedDiff({ file, status, hunks, from: renamedFrom }) {
29512
+ const from = status === "added" ? "/dev/null" : `a/${renamedFrom ?? file}`;
29329
29513
  const to = status === "removed" ? "/dev/null" : `b/${file}`;
29330
29514
  const body = hunks.flatMap(({ oldStart, oldLines, newStart, newLines, lines }) => [`@@ -${oldStart},${oldLines} +${newStart},${newLines} @@`, ...lines]);
29331
29515
  return [`--- ${from}`, `+++ ${to}`, ...body].join("\n");
@@ -29360,7 +29544,8 @@ function renderSummaryMarkdown({ rows, hasBase, changes, budget = SUMMARY_BUDGET
29360
29544
  const truncated = [];
29361
29545
  changes.text.forEach((change) => {
29362
29546
  const counts = change.skipped ? "" : ` (+${change.additions} / \u2212${change.deletions})`;
29363
- const heading = `#### \`${change.file}\` \u2014 ${STATUS_LABEL[change.status]}${counts}`;
29547
+ const renamed = change.from ? ` (renamed from \`${change.from}\`)` : "";
29548
+ const heading = `#### \`${change.file}\` \u2014 ${STATUS_LABEL[change.status]}${renamed}${counts}`;
29364
29549
  if (change.skipped) {
29365
29550
  out.push(heading, "", `_Line diff skipped: ${change.skipped}._`, "");
29366
29551
  return;
@@ -29382,7 +29567,7 @@ function renderSummaryMarkdown({ rows, hasBase, changes, budget = SUMMARY_BUDGET
29382
29567
  });
29383
29568
  if (truncated.length > 0) {
29384
29569
  const where = reportUrl2 ? ` See the [full report](${reportUrl2}).` : "";
29385
- out.push(`> [!NOTE]`, `> ${truncated.length} diff(s) omitted to stay under GitHub's summary size limit: ${truncated.map((f) => `\`${f}\``).join(", ")}.${where}`, "");
29570
+ out.push("> [!NOTE]", `> ${truncated.length} diff(s) omitted to stay under GitHub's summary size limit: ${truncated.map((f) => `\`${f}\``).join(", ")}.${where}`, "");
29386
29571
  }
29387
29572
  out.push("</details>", "");
29388
29573
  if (changes.images.length > 0) {
@@ -29620,6 +29805,11 @@ kbd {
29620
29805
  color: var(--mod);
29621
29806
  }
29622
29807
 
29808
+ .pill.renamed {
29809
+ background: var(--surface-2);
29810
+ color: var(--muted);
29811
+ }
29812
+
29623
29813
  .ratio {
29624
29814
  display: block;
29625
29815
  block-size: 6px;
@@ -30513,7 +30703,7 @@ input[type="range"]:focus-visible {
30513
30703
  `;
30514
30704
 
30515
30705
  // src/report-page.client.js
30516
- var report_page_client_default = '/* Browser script for the visual diff page (inlined by page.js). */\n(() => {\n const $ = (sel, root = document) => root.querySelector(sel);\n const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];\n const store = {\n get(key) {\n try {\n return localStorage.getItem(`file-diff:${key}`);\n } catch {\n return null;\n }\n },\n set(key, value) {\n try {\n localStorage.setItem(`file-diff:${key}`, value);\n } catch {\n // Storage blocked; the choice still applies to this view.\n }\n },\n };\n\n const code = $(".code-main");\n\n /** Index an arrow, Home or End key moves to in a horizontal list, or undefined for other keys. */\n function targetIndex(key, i, length, rtl) {\n const step = { ArrowRight: rtl ? -1 : 1, ArrowLeft: rtl ? 1 : -1 }[key];\n if (step) return (i + step + length) % length;\n if (key === "Home") return 0;\n if (key === "End") return length - 1;\n return undefined;\n }\n\n /* ---- Tabs: selection follows focus, roving tabindex ------------------ */\n const tablist = $(\'[role="tablist"]\');\n const tabs = $$(\'[role="tab"]\', tablist);\n const panelFor = (tab) => document.getElementById(tab.id.replace(/^tab-/, "panel-"));\n\n function selectTab(tab, { focus = false, push = true } = {}) {\n tabs.forEach((t) => {\n const on = t === tab;\n t.setAttribute("aria-selected", String(on));\n t.tabIndex = on ? 0 : -1;\n const panel = panelFor(t);\n if (on) panel.removeAttribute("hidden");\n else panel.setAttribute("hidden", "until-found");\n });\n if (focus) tab.focus();\n tab.scrollIntoView({ block: "nearest", inline: "nearest" });\n if (push) history.replaceState(null, "", `#${tab.id.slice(4)}`);\n }\n\n tablist.addEventListener("click", (e) => {\n const tab = e.target.closest(\'[role="tab"]\');\n if (tab) selectTab(tab);\n });\n tablist.addEventListener("keydown", (e) => {\n const i = tabs.indexOf(document.activeElement);\n const next = i < 0 ? undefined : targetIndex(e.key, i, tabs.length, getComputedStyle(tablist).direction === "rtl");\n if (next === undefined) return;\n e.preventDefault();\n selectTab(tabs[next], { focus: true });\n });\n // Find-in-page revealed a hidden panel: select its tab.\n $$(\'[role="tabpanel"]\').forEach((panel) =>\n panel.addEventListener("beforematch", () => {\n const tab = document.getElementById(panel.getAttribute("aria-labelledby"));\n if (tab) selectTab(tab, { push: false });\n }),\n );\n\n /** Shows the tab holding an element, then scrolls to it. */\n function reveal(el) {\n const panel = el.closest(\'[role="tabpanel"]\');\n const tab = panel && document.getElementById(panel.getAttribute("aria-labelledby"));\n if (tab && tab.getAttribute("aria-selected") !== "true") selectTab(tab, { push: false });\n const details = el.querySelector("details");\n if (details) {\n details.open = true;\n renderFile(el);\n }\n el.scrollIntoView({ block: "start" });\n }\n\n document.addEventListener("click", (e) => {\n const link = e.target.closest(\'a[href^="#f-"]\');\n if (!link) return;\n const target = document.getElementById(link.hash.slice(1));\n if (!target) return;\n e.preventDefault();\n reveal(target);\n history.replaceState(null, "", link.hash);\n });\n\n /* ---- Toolbars: one tab stop, arrow keys move (focusgroup fallback) --- */\n $$(\'[role="toolbar"]\').forEach((bar) => {\n if ("focusGroup" in HTMLElement.prototype) return bar.setAttribute("focusgroup", "toolbar wrap");\n const items = () => $$("button", bar);\n items().forEach((b, i) => (b.tabIndex = i ? -1 : 0));\n bar.addEventListener("focusin", ({ target }) => {\n if (items().includes(target)) items().forEach((b) => (b.tabIndex = b === target ? 0 : -1));\n });\n bar.addEventListener("keydown", (e) => {\n const list = items();\n const i = list.indexOf(document.activeElement);\n const next = i < 0 ? undefined : targetIndex(e.key, i, list.length, getComputedStyle(bar).direction === "rtl");\n if (next === undefined) return;\n e.preventDefault();\n list[next].focus();\n });\n });\n\n /** Presses one button in a segmented group. */\n function press(group, button) {\n $$("button", group).forEach((b) => b.setAttribute("aria-pressed", String(b === button)));\n }\n\n /* ---- Code: rows are built from JSON when a file opens ----------------- */\n const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", \'"\': "&quot;", "\'": "&#39;" };\n const esc = (text) => text.replace(/[&<>"\']/g, (c) => ESCAPES[c]);\n\n /** Escapes a line, wrapping the changed `[start, end, \u2026]` ranges in <mark>. */\n function markup(text, ranges) {\n if (!ranges) return esc(text);\n let out = "";\n let at = 0;\n for (let k = 0; k < ranges.length; k += 2) {\n out += `${esc(text.slice(at, ranges[k]))}<mark>${esc(text.slice(ranges[k], ranges[k + 1]))}</mark>`;\n at = ranges[k + 1];\n }\n return out + esc(text.slice(at));\n }\n\n /** Old and new line numbers for every line of a hunk (null where a side has none). */\n function numbers({ o, n, l }) {\n let oldNo = o;\n let newNo = n;\n return l.map((line) => (line[0] === "-" ? [oldNo++, null] : line[0] === "+" ? [null, newNo++] : line[0] === "\\\\" ? [null, null] : [oldNo++, newNo++]));\n }\n\n const metaRow = (line, cols) => `<tr class="meta"><td colspan="${cols}">${esc(line)}</td></tr>`;\n\n function unifiedRows(hunk) {\n const nos = numbers(hunk);\n const rows = [`<tr class="hunk"><td colspan="3">${esc(hunk.h)}</td></tr>`];\n hunk.l.forEach((line, i) => {\n const sign = line[0];\n if (sign === "\\\\") return rows.push(metaRow(line, 3));\n const kind = sign === "-" ? "del" : sign === "+" ? "add" : "ctx";\n rows.push(`<tr class="${kind}"><td class="ln">${nos[i][0] ?? ""}</td><td class="ln">${nos[i][1] ?? ""}</td><td class="code"><span class="sign">${sign}</span>${markup(line.slice(1), hunk.m[i])}</td></tr>`);\n });\n return rows;\n }\n\n const EMPTY_CELLS = \'<td class="ln empty"></td><td class="code empty"></td>\';\n\n /** Side-by-side rows. Edited line pairs share a row; other changes fill the gaps between them. */\n function splitRows(hunk) {\n const nos = numbers(hunk);\n const pairOf = new Map(hunk.p);\n const cells = (i, kind, no) => (i < 0 ? EMPTY_CELLS : `<td class="ln ${kind}">${no}</td><td class="code ${kind}">${markup(hunk.l[i].slice(1), hunk.m[i])}</td>`);\n const rows = [`<tr class="hunk"><td colspan="4">${esc(hunk.h)}</td></tr>`];\n\n for (let i = 0; i < hunk.l.length; ) {\n const sign = hunk.l[i][0];\n if (sign === "\\\\") {\n rows.push(metaRow(hunk.l[i++], 4));\n } else if (sign !== "-" && sign !== "+") {\n const text = markup(hunk.l[i].slice(1));\n rows.push(`<tr class="ctx"><td class="ln">${nos[i][0]}</td><td class="code">${text}</td><td class="ln">${nos[i][1]}</td><td class="code">${text}</td></tr>`);\n i++;\n } else {\n const dels = [];\n const adds = [];\n const notes = [];\n while (hunk.l[i]?.[0] === "-") dels.push(i++);\n while (hunk.l[i]?.[0] === "\\\\") notes.push(i++);\n while (hunk.l[i]?.[0] === "+") adds.push(i++);\n\n const pairs = [];\n let di = 0;\n let ai = 0;\n const fill = (dEnd, aEnd) => {\n for (let k = 0, n = Math.max(dEnd - di, aEnd - ai); k < n; k++) pairs.push([di + k < dEnd ? dels[di + k] : -1, ai + k < aEnd ? adds[ai + k] : -1]);\n di = dEnd;\n ai = aEnd;\n };\n dels.forEach((d, dPos) => {\n const aPos = adds.indexOf(pairOf.get(d));\n if (aPos < ai) return;\n fill(dPos, aPos);\n pairs.push([d, adds[aPos]]);\n di = dPos + 1;\n ai = aPos + 1;\n });\n fill(dels.length, adds.length);\n\n pairs.forEach(([d, a]) => rows.push(`<tr>${cells(d, "del", nos[d]?.[0])}${cells(a, "add", nos[a]?.[1])}</tr>`));\n notes.forEach((n) => rows.push(metaRow(hunk.l[n], 4)));\n }\n }\n return rows;\n }\n\n const parsed = new WeakMap();\n\n /** Builds a file\'s diff table for the current layout, once per layout. */\n function renderFile(section) {\n const scroll = section && $(".diff-scroll", section);\n if (!scroll || !code) return;\n const view = code.dataset.view;\n if (scroll.dataset.view === view) return;\n if (!parsed.has(scroll)) parsed.set(scroll, JSON.parse($(\'script[type="application/json"]\', scroll).textContent));\n const rows = parsed.get(scroll).flatMap((hunk) => (view === "split" ? splitRows(hunk) : unifiedRows(hunk)));\n const table = view === "split" ? `<table class="diff split"><colgroup><col class="ln-col"><col><col class="ln-col"><col></colgroup>${rows.join("")}</table>` : `<table class="diff unified">${rows.join("")}</table>`;\n $(".rendered", scroll)?.remove();\n scroll.insertAdjacentHTML("beforeend", `<div class="rendered">${table}</div>`);\n scroll.dataset.view = view;\n }\n\n if (code) {\n const sections = $$(".file", code);\n const renderOpen = () => sections.filter((section) => $("details", section).open).forEach(renderFile);\n const layout = $(\'[aria-label="Diff layout"]\', code);\n const collapse = $(\'[data-action="collapse"]\', code);\n const syncCollapse = () => (collapse.textContent = sections.every((section) => $("details", section).open) ? "Collapse all" : "Expand all");\n\n const setView = (view) => {\n code.dataset.view = view;\n press(layout, $(`button[data-view="${view}"]`, code));\n renderOpen();\n };\n\n layout.addEventListener("click", (e) => {\n const b = e.target.closest("button[data-view]");\n if (!b) return;\n setView(b.dataset.view);\n store.set("view", b.dataset.view);\n });\n collapse.addEventListener("click", () => {\n const open = collapse.textContent.startsWith("Expand");\n sections.forEach((section) => ($("details", section).open = open));\n syncCollapse();\n });\n // `toggle` doesn\'t bubble, so listen while it travels down.\n code.addEventListener(\n "toggle",\n (e) => {\n if (e.target.open) renderFile(e.target.closest(".file"));\n syncCollapse();\n },\n true,\n );\n\n setView(store.get("view") === "split" ? "split" : "unified");\n syncCollapse();\n }\n\n /* ---- Visual: modes, sliders, swipe drag, zoom, pager ----------------- */\n const viewer = $(".viewer");\n if (viewer) {\n const items = $$(".image-item", viewer);\n const listButtons = $$(".filelist button", viewer.parentElement);\n const modes = $(".modes", viewer);\n let index = 0;\n\n const current = () => items[index];\n\n const FIT_HEIGHT = 420;\n\n /** Sizes both versions by one scale so stacked modes stay aligned. Fit fills the stage. */\n function applyZoom() {\n const item = current();\n const imgs = $$("img", item);\n if (!imgs.every((img) => img.complete && img.naturalWidth)) {\n imgs.forEach((img) => img.addEventListener("load", applyZoom, { once: true }));\n return;\n }\n const zoom = viewer.dataset.zoom;\n let scale = Number(zoom);\n if (zoom === "fit") {\n const stage = $(".stage", item);\n const pad = parseFloat(getComputedStyle(stage).paddingLeft) * 2;\n const columns = viewer.dataset.mode === "side" && !item.hasAttribute("data-single") ? 2 : 1;\n const width = (stage.clientWidth - pad - (columns - 1) * 16) / columns;\n // The stage has no size while its tab is hidden; the ResizeObserver reruns this once it shows.\n if (width <= 0) return;\n const maxW = Math.max(...imgs.map((img) => img.naturalWidth));\n const maxH = Math.max(...imgs.map((img) => img.naturalHeight));\n scale = Math.min(width / maxW, FIT_HEIGHT / maxH);\n }\n imgs.forEach((img) => {\n img.style.inlineSize = `${Math.round(img.naturalWidth * scale)}px`;\n img.classList.toggle("upscaled", scale > 1);\n });\n }\n new ResizeObserver(() => viewer.dataset.zoom === "fit" && applyZoom()).observe(viewer);\n\n function syncModes() {\n const single = current().hasAttribute("data-single");\n $$("button", modes).forEach((b) => {\n if (b.dataset.mode === "side") return;\n if (single) b.setAttribute("aria-disabled", "true");\n else b.removeAttribute("aria-disabled");\n });\n }\n\n function show(i) {\n index = (i + items.length) % items.length;\n items.forEach((item, k) => (item.hidden = k !== index));\n listButtons.forEach((b, k) => (k === index ? b.setAttribute("aria-current", "true") : b.removeAttribute("aria-current")));\n $(".pager-count", viewer).textContent = `${index + 1} of ${items.length}`;\n syncModes();\n applyZoom();\n }\n\n // Natural dimensions under each image header.\n items.forEach((item) =>\n $$("img", item).forEach((img) => {\n const write = () => {\n const out = $(`[data-dims="${img.dataset.side}"]`, item);\n if (out) out.textContent = `${img.dataset.side} ${img.naturalWidth}\xD7${img.naturalHeight}`;\n };\n if (img.complete && img.naturalWidth) write();\n else img.addEventListener("load", write, { once: true });\n }),\n );\n\n $(".toolbar", viewer).addEventListener("click", (e) => {\n const b = e.target.closest("button");\n if (!b || b.getAttribute("aria-disabled") === "true") return;\n for (const key of ["mode", "bg", "zoom"]) {\n if (b.dataset[key] === undefined) continue;\n viewer.dataset[key] = b.dataset[key];\n press(b.parentElement, b);\n if (key !== "bg") applyZoom();\n if (key !== "zoom") store.set(key, b.dataset[key]);\n }\n });\n for (const key of ["mode", "bg"]) {\n const saved = store.get(key);\n const b = saved && $(`button[data-${key}="${saved}"]`, viewer);\n if (b) {\n viewer.dataset[key] = saved;\n press(b.parentElement, b);\n }\n }\n\n // Range inputs drive --opacity / --pos; keep the filled track in sync.\n $$(\'input[type="range"]\', viewer).forEach((input) => {\n const output = input.nextElementSibling;\n const sync = () => {\n const v = Number(input.value);\n input.style.setProperty("--control-value", v);\n input.style.setProperty("--attr-min", input.min || 0);\n input.style.setProperty("--attr-max", input.max || 100);\n viewer.style.setProperty(input.dataset.control === "opacity" ? "--opacity" : "--pos", input.dataset.control === "opacity" ? v / 100 : `${v}%`);\n output.textContent = `${v}%`;\n };\n input.addEventListener("input", sync);\n sync();\n });\n\n // Drag directly on the image in swipe mode.\n const swipeInput = $(\'input[data-control="pos"]\', viewer);\n items.forEach((item) => {\n const layers = $(".layers", item);\n const move = (e) => {\n const box = layers.getBoundingClientRect();\n swipeInput.value = String(Math.round(Math.min(100, Math.max(0, ((e.clientX - box.left) / box.width) * 100))));\n swipeInput.dispatchEvent(new Event("input"));\n };\n layers.addEventListener("pointerdown", (e) => {\n if (viewer.dataset.mode !== "swipe" || item.hasAttribute("data-single")) return;\n layers.setPointerCapture(e.pointerId);\n move(e);\n layers.addEventListener("pointermove", move);\n // Fires after pointerup and pointercancel alike, so the listener never outlives the drag.\n layers.addEventListener("lostpointercapture", () => layers.removeEventListener("pointermove", move), { once: true });\n });\n });\n\n listButtons.forEach((b, k) => b.addEventListener("click", () => show(k)));\n $$("[data-step]", viewer).forEach((b) => b.addEventListener("click", () => show(index + Number(b.dataset.step))));\n document.addEventListener("keydown", (e) => {\n if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;\n if ($("#panel-visual")?.hidden || e.target.closest("input, textarea, select, [contenteditable]")) return;\n if (e.key === "j" || e.key === "k") show(index + (e.key === "j" ? 1 : -1));\n });\n\n show(0);\n }\n\n /* ---- Open the tab or file named in the URL ---------------------------- */\n const initial = location.hash.slice(1);\n const initialTab = document.getElementById(`tab-${initial}`);\n if (initialTab) selectTab(initialTab, { push: false });\n else if (initial && document.getElementById(initial)) reveal(document.getElementById(initial));\n})();\n';
30706
+ var report_page_client_default = '/**\n * SPDX-License-Identifier: MPL-2.0\n * Copyright 2025 Allons-y Studio\n */\n\n/* Browser script for the visual diff page (inlined by page.js). */\n(() => {\n const $ = (sel, root = document) => root.querySelector(sel);\n const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];\n const store = {\n get(key) {\n try {\n return localStorage.getItem(`file-diff:${key}`);\n } catch {\n return null;\n }\n },\n set(key, value) {\n try {\n localStorage.setItem(`file-diff:${key}`, value);\n } catch {\n // Storage blocked; the choice still applies to this view.\n }\n },\n };\n\n const code = $(".code-main");\n\n /** Index an arrow, Home or End key moves to in a horizontal list, or undefined for other keys. */\n function targetIndex(key, i, length, rtl) {\n const step = { ArrowRight: rtl ? -1 : 1, ArrowLeft: rtl ? 1 : -1 }[key];\n if (step) return (i + step + length) % length;\n if (key === "Home") return 0;\n if (key === "End") return length - 1;\n return undefined;\n }\n\n /* ---- Tabs: selection follows focus, roving tabindex ------------------ */\n const tablist = $(\'[role="tablist"]\');\n const tabs = $$(\'[role="tab"]\', tablist);\n const panelFor = (tab) => document.getElementById(tab.id.replace(/^tab-/, "panel-"));\n\n function selectTab(tab, { focus = false, push = true } = {}) {\n tabs.forEach((t) => {\n const on = t === tab;\n t.setAttribute("aria-selected", String(on));\n t.tabIndex = on ? 0 : -1;\n const panel = panelFor(t);\n if (on) panel.removeAttribute("hidden");\n else panel.setAttribute("hidden", "until-found");\n });\n if (focus) tab.focus();\n tab.scrollIntoView({ block: "nearest", inline: "nearest" });\n if (push) history.replaceState(null, "", `#${tab.id.slice(4)}`);\n }\n\n tablist.addEventListener("click", (e) => {\n const tab = e.target.closest(\'[role="tab"]\');\n if (tab) selectTab(tab);\n });\n tablist.addEventListener("keydown", (e) => {\n const i = tabs.indexOf(document.activeElement);\n const next = i < 0 ? undefined : targetIndex(e.key, i, tabs.length, getComputedStyle(tablist).direction === "rtl");\n if (next === undefined) return;\n e.preventDefault();\n selectTab(tabs[next], { focus: true });\n });\n // Find-in-page revealed a hidden panel: select its tab.\n $$(\'[role="tabpanel"]\').forEach((panel) =>\n panel.addEventListener("beforematch", () => {\n const tab = document.getElementById(panel.getAttribute("aria-labelledby"));\n if (tab) selectTab(tab, { push: false });\n }),\n );\n\n /** Shows the tab holding an element, then scrolls to it. */\n function reveal(el) {\n const panel = el.closest(\'[role="tabpanel"]\');\n const tab = panel && document.getElementById(panel.getAttribute("aria-labelledby"));\n if (tab && tab.getAttribute("aria-selected") !== "true") selectTab(tab, { push: false });\n const details = el.querySelector("details");\n if (details) {\n details.open = true;\n renderFile(el);\n }\n el.scrollIntoView({ block: "start" });\n }\n\n document.addEventListener("click", (e) => {\n const link = e.target.closest(\'a[href^="#f-"]\');\n if (!link) return;\n const target = document.getElementById(link.hash.slice(1));\n if (!target) return;\n e.preventDefault();\n reveal(target);\n history.replaceState(null, "", link.hash);\n });\n\n /* ---- Toolbars: one tab stop, arrow keys move (focusgroup fallback) --- */\n $$(\'[role="toolbar"]\').forEach((bar) => {\n if ("focusGroup" in HTMLElement.prototype) return bar.setAttribute("focusgroup", "toolbar wrap");\n const items = () => $$("button", bar);\n items().forEach((b, i) => (b.tabIndex = i ? -1 : 0));\n bar.addEventListener("focusin", ({ target }) => {\n if (items().includes(target)) items().forEach((b) => (b.tabIndex = b === target ? 0 : -1));\n });\n bar.addEventListener("keydown", (e) => {\n const list = items();\n const i = list.indexOf(document.activeElement);\n const next = i < 0 ? undefined : targetIndex(e.key, i, list.length, getComputedStyle(bar).direction === "rtl");\n if (next === undefined) return;\n e.preventDefault();\n list[next].focus();\n });\n });\n\n /** Presses one button in a segmented group. */\n function press(group, button) {\n $$("button", group).forEach((b) => b.setAttribute("aria-pressed", String(b === button)));\n }\n\n /* ---- Code: rows are built from JSON when a file opens ----------------- */\n const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", \'"\': "&quot;", "\'": "&#39;" };\n const esc = (text) => text.replace(/[&<>"\']/g, (c) => ESCAPES[c]);\n\n /** Escapes a line, wrapping the changed `[start, end, \u2026]` ranges in <mark>. */\n function markup(text, ranges) {\n if (!ranges) return esc(text);\n let out = "";\n let at = 0;\n for (let k = 0; k < ranges.length; k += 2) {\n out += `${esc(text.slice(at, ranges[k]))}<mark>${esc(text.slice(ranges[k], ranges[k + 1]))}</mark>`;\n at = ranges[k + 1];\n }\n return out + esc(text.slice(at));\n }\n\n /** Old and new line numbers for every line of a hunk (null where a side has none). */\n function numbers({ o, n, l }) {\n let oldNo = o;\n let newNo = n;\n return l.map((line) => (line[0] === "-" ? [oldNo++, null] : line[0] === "+" ? [null, newNo++] : line[0] === "\\\\" ? [null, null] : [oldNo++, newNo++]));\n }\n\n const metaRow = (line, cols) => `<tr class="meta"><td colspan="${cols}">${esc(line)}</td></tr>`;\n\n function unifiedRows(hunk) {\n const nos = numbers(hunk);\n const rows = [`<tr class="hunk"><td colspan="3">${esc(hunk.h)}</td></tr>`];\n hunk.l.forEach((line, i) => {\n const sign = line[0];\n if (sign === "\\\\") return rows.push(metaRow(line, 3));\n const kind = sign === "-" ? "del" : sign === "+" ? "add" : "ctx";\n rows.push(`<tr class="${kind}"><td class="ln">${nos[i][0] ?? ""}</td><td class="ln">${nos[i][1] ?? ""}</td><td class="code"><span class="sign">${sign}</span>${markup(line.slice(1), hunk.m[i])}</td></tr>`);\n });\n return rows;\n }\n\n const EMPTY_CELLS = \'<td class="ln empty"></td><td class="code empty"></td>\';\n\n /** Side-by-side rows. Edited line pairs share a row; other changes fill the gaps between them. */\n function splitRows(hunk) {\n const nos = numbers(hunk);\n const pairOf = new Map(hunk.p);\n const cells = (i, kind, no) => (i < 0 ? EMPTY_CELLS : `<td class="ln ${kind}">${no}</td><td class="code ${kind}">${markup(hunk.l[i].slice(1), hunk.m[i])}</td>`);\n const rows = [`<tr class="hunk"><td colspan="4">${esc(hunk.h)}</td></tr>`];\n\n for (let i = 0; i < hunk.l.length; ) {\n const sign = hunk.l[i][0];\n if (sign === "\\\\") {\n rows.push(metaRow(hunk.l[i++], 4));\n } else if (sign !== "-" && sign !== "+") {\n const text = markup(hunk.l[i].slice(1));\n rows.push(`<tr class="ctx"><td class="ln">${nos[i][0]}</td><td class="code">${text}</td><td class="ln">${nos[i][1]}</td><td class="code">${text}</td></tr>`);\n i++;\n } else {\n const dels = [];\n const adds = [];\n const notes = [];\n while (hunk.l[i]?.[0] === "-") dels.push(i++);\n while (hunk.l[i]?.[0] === "\\\\") notes.push(i++);\n while (hunk.l[i]?.[0] === "+") adds.push(i++);\n\n const pairs = [];\n let di = 0;\n let ai = 0;\n const fill = (dEnd, aEnd) => {\n for (let k = 0, n = Math.max(dEnd - di, aEnd - ai); k < n; k++) pairs.push([di + k < dEnd ? dels[di + k] : -1, ai + k < aEnd ? adds[ai + k] : -1]);\n di = dEnd;\n ai = aEnd;\n };\n dels.forEach((d, dPos) => {\n const aPos = adds.indexOf(pairOf.get(d));\n if (aPos < ai) return;\n fill(dPos, aPos);\n pairs.push([d, adds[aPos]]);\n di = dPos + 1;\n ai = aPos + 1;\n });\n fill(dels.length, adds.length);\n\n pairs.forEach(([d, a]) => rows.push(`<tr>${cells(d, "del", nos[d]?.[0])}${cells(a, "add", nos[a]?.[1])}</tr>`));\n notes.forEach((n) => rows.push(metaRow(hunk.l[n], 4)));\n }\n }\n return rows;\n }\n\n const parsed = new WeakMap();\n\n /** Builds a file\'s diff table for the current layout, once per layout. */\n function renderFile(section) {\n const scroll = section && $(".diff-scroll", section);\n if (!scroll || !code) return;\n const view = code.dataset.view;\n if (scroll.dataset.view === view) return;\n if (!parsed.has(scroll)) parsed.set(scroll, JSON.parse($(\'script[type="application/json"]\', scroll).textContent));\n const rows = parsed.get(scroll).flatMap((hunk) => (view === "split" ? splitRows(hunk) : unifiedRows(hunk)));\n const table = view === "split" ? `<table class="diff split"><colgroup><col class="ln-col"><col><col class="ln-col"><col></colgroup>${rows.join("")}</table>` : `<table class="diff unified">${rows.join("")}</table>`;\n $(".rendered", scroll)?.remove();\n scroll.insertAdjacentHTML("beforeend", `<div class="rendered">${table}</div>`);\n scroll.dataset.view = view;\n }\n\n if (code) {\n const sections = $$(".file", code);\n const renderOpen = () => sections.filter((section) => $("details", section).open).forEach(renderFile);\n const layout = $(\'[aria-label="Diff layout"]\', code);\n const collapse = $(\'[data-action="collapse"]\', code);\n const syncCollapse = () => (collapse.textContent = sections.every((section) => $("details", section).open) ? "Collapse all" : "Expand all");\n\n const setView = (view) => {\n code.dataset.view = view;\n press(layout, $(`button[data-view="${view}"]`, code));\n renderOpen();\n };\n\n layout.addEventListener("click", (e) => {\n const b = e.target.closest("button[data-view]");\n if (!b) return;\n setView(b.dataset.view);\n store.set("view", b.dataset.view);\n });\n collapse.addEventListener("click", () => {\n const open = collapse.textContent.startsWith("Expand");\n sections.forEach((section) => ($("details", section).open = open));\n syncCollapse();\n });\n // `toggle` doesn\'t bubble, so listen while it travels down.\n code.addEventListener(\n "toggle",\n (e) => {\n if (e.target.open) renderFile(e.target.closest(".file"));\n syncCollapse();\n },\n true,\n );\n\n setView(store.get("view") === "split" ? "split" : "unified");\n syncCollapse();\n }\n\n /* ---- Visual: modes, sliders, swipe drag, zoom, pager ----------------- */\n const viewer = $(".viewer");\n if (viewer) {\n const items = $$(".image-item", viewer);\n const listButtons = $$(".filelist button", viewer.parentElement);\n const modes = $(".modes", viewer);\n let index = 0;\n\n const current = () => items[index];\n\n const FIT_HEIGHT = 420;\n\n /** Sizes both versions by one scale so stacked modes stay aligned. Fit fills the stage. */\n function applyZoom() {\n const item = current();\n const imgs = $$("img", item);\n if (!imgs.every((img) => img.complete && img.naturalWidth)) {\n imgs.forEach((img) => img.addEventListener("load", applyZoom, { once: true }));\n return;\n }\n const zoom = viewer.dataset.zoom;\n let scale = Number(zoom);\n if (zoom === "fit") {\n const stage = $(".stage", item);\n const pad = parseFloat(getComputedStyle(stage).paddingLeft) * 2;\n const columns = viewer.dataset.mode === "side" && !item.hasAttribute("data-single") ? 2 : 1;\n const width = (stage.clientWidth - pad - (columns - 1) * 16) / columns;\n // The stage has no size while its tab is hidden; the ResizeObserver reruns this once it shows.\n if (width <= 0) return;\n const maxW = Math.max(...imgs.map((img) => img.naturalWidth));\n const maxH = Math.max(...imgs.map((img) => img.naturalHeight));\n scale = Math.min(width / maxW, FIT_HEIGHT / maxH);\n }\n imgs.forEach((img) => {\n img.style.inlineSize = `${Math.round(img.naturalWidth * scale)}px`;\n img.classList.toggle("upscaled", scale > 1);\n });\n }\n new ResizeObserver(() => viewer.dataset.zoom === "fit" && applyZoom()).observe(viewer);\n\n function syncModes() {\n const single = current().hasAttribute("data-single");\n $$("button", modes).forEach((b) => {\n if (b.dataset.mode === "side") return;\n if (single) b.setAttribute("aria-disabled", "true");\n else b.removeAttribute("aria-disabled");\n });\n }\n\n function show(i) {\n index = (i + items.length) % items.length;\n items.forEach((item, k) => (item.hidden = k !== index));\n listButtons.forEach((b, k) => (k === index ? b.setAttribute("aria-current", "true") : b.removeAttribute("aria-current")));\n $(".pager-count", viewer).textContent = `${index + 1} of ${items.length}`;\n syncModes();\n applyZoom();\n }\n\n // Natural dimensions under each image header.\n items.forEach((item) =>\n $$("img", item).forEach((img) => {\n const write = () => {\n const out = $(`[data-dims="${img.dataset.side}"]`, item);\n if (out) out.textContent = `${img.dataset.side} ${img.naturalWidth}\xD7${img.naturalHeight}`;\n };\n if (img.complete && img.naturalWidth) write();\n else img.addEventListener("load", write, { once: true });\n }),\n );\n\n $(".toolbar", viewer).addEventListener("click", (e) => {\n const b = e.target.closest("button");\n if (!b || b.getAttribute("aria-disabled") === "true") return;\n for (const key of ["mode", "bg", "zoom"]) {\n if (b.dataset[key] === undefined) continue;\n viewer.dataset[key] = b.dataset[key];\n press(b.parentElement, b);\n if (key !== "bg") applyZoom();\n if (key !== "zoom") store.set(key, b.dataset[key]);\n }\n });\n for (const key of ["mode", "bg"]) {\n const saved = store.get(key);\n const b = saved && $(`button[data-${key}="${saved}"]`, viewer);\n if (b) {\n viewer.dataset[key] = saved;\n press(b.parentElement, b);\n }\n }\n\n // Range inputs drive --opacity / --pos; keep the filled track in sync.\n $$(\'input[type="range"]\', viewer).forEach((input) => {\n const output = input.nextElementSibling;\n const sync = () => {\n const v = Number(input.value);\n input.style.setProperty("--control-value", v);\n input.style.setProperty("--attr-min", input.min || 0);\n input.style.setProperty("--attr-max", input.max || 100);\n viewer.style.setProperty(input.dataset.control === "opacity" ? "--opacity" : "--pos", input.dataset.control === "opacity" ? v / 100 : `${v}%`);\n output.textContent = `${v}%`;\n };\n input.addEventListener("input", sync);\n sync();\n });\n\n // Drag directly on the image in swipe mode.\n const swipeInput = $(\'input[data-control="pos"]\', viewer);\n items.forEach((item) => {\n const layers = $(".layers", item);\n const move = (e) => {\n const box = layers.getBoundingClientRect();\n swipeInput.value = String(Math.round(Math.min(100, Math.max(0, ((e.clientX - box.left) / box.width) * 100))));\n swipeInput.dispatchEvent(new Event("input"));\n };\n layers.addEventListener("pointerdown", (e) => {\n if (viewer.dataset.mode !== "swipe" || item.hasAttribute("data-single")) return;\n layers.setPointerCapture(e.pointerId);\n move(e);\n layers.addEventListener("pointermove", move);\n // Fires after pointerup and pointercancel alike, so the listener never outlives the drag.\n layers.addEventListener("lostpointercapture", () => layers.removeEventListener("pointermove", move), { once: true });\n });\n });\n\n listButtons.forEach((b, k) => b.addEventListener("click", () => show(k)));\n $$("[data-step]", viewer).forEach((b) => b.addEventListener("click", () => show(index + Number(b.dataset.step))));\n document.addEventListener("keydown", (e) => {\n if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;\n if ($("#panel-visual")?.hidden || e.target.closest("input, textarea, select, [contenteditable]")) return;\n if (e.key === "j" || e.key === "k") show(index + (e.key === "j" ? 1 : -1));\n });\n\n show(0);\n }\n\n /* ---- Open the tab or file named in the URL ---------------------------- */\n const initial = location.hash.slice(1);\n const initialTab = document.getElementById(`tab-${initial}`);\n if (initialTab) selectTab(initialTab, { push: false });\n else if (initial && document.getElementById(initial)) reveal(document.getElementById(initial));\n})();\n';
30517
30707
 
30518
30708
  // src/page.js
30519
30709
  var INTRALINE_LIMIT = 1e3;
@@ -30686,6 +30876,7 @@ function renderFileList(items, label, buttons = false) {
30686
30876
  });
30687
30877
  return `<nav class="filelist" aria-label="${escapeHtml(label)}"><ul>${entries.join("")}</ul></nav>`;
30688
30878
  }
30879
+ var renamedPill = (from) => from ? `<span class="pill renamed" title="Renamed from ${escapeHtml(from)}">renamed</span>` : "";
30689
30880
  var OPEN_LINES = 800;
30690
30881
  function renderCode({ changes }, anchors) {
30691
30882
  if (changes.text.length === 0) return '<p class="empty-state">No text changes.</p>';
@@ -30704,7 +30895,8 @@ function renderCode({ changes }, anchors) {
30704
30895
  else if (c.omitted) body = `<p class="note">Diff left out because ${escapeHtml(c.omitted)}. Raise <code>max-diff-lines</code> to include it.</p>`;
30705
30896
  else if (c.hunks.length === 0) body = '<p class="note">No line changes.</p>';
30706
30897
  else body = `<div class="diff-scroll"><script type="application/json">${scriptJson(c.hunks.map(hunkData))}</script></div>`;
30707
- return `<section class="file" id="${anchors.get(c.file)}"><details${open2 ? " open" : ""}><summary><span class="chev">${ICON.chevron}</span><span class="pill ${c.status}">${c.status}</span><span class="path">${pathHtml(c.file)}</span><span class="meta">${counts(c)}</span></summary>${body}</details></section>`;
30898
+ if (c.from) body = `<p class="note">Renamed from <code>${escapeHtml(c.from)}</code>.</p>${body}`;
30899
+ return `<section class="file" id="${anchors.get(c.file)}"><details${open2 ? " open" : ""}><summary><span class="chev">${ICON.chevron}</span><span class="pill ${c.status}">${c.status}</span>${renamedPill(c.from)}<span class="path">${pathHtml(c.file)}</span><span class="meta">${counts(c)}</span></summary>${body}</details></section>`;
30708
30900
  }).join("");
30709
30901
  return `<div class="layout">${list}<div class="main code-main" data-view="unified">
30710
30902
  <div class="toolbar" role="toolbar" aria-label="Diff options">
@@ -30724,10 +30916,10 @@ function renderVisual({ changes, imageUrls = /* @__PURE__ */ new Map() }) {
30724
30916
  true
30725
30917
  );
30726
30918
  const figure = (side, url) => url ? `<figure class="layer ${side}"><img src="${escapeHtml(url)}" alt="${side === "base" ? "Base" : "Head"} version" decoding="async" data-side="${side}"><figcaption>${side === "base" ? "Base" : "Head"}</figcaption></figure>` : `<figure class="layer ${side} missing"><figcaption>${side === "base" ? "Base" : "Head"}: not available</figcaption></figure>`;
30727
- const viewers = items.map(({ id, file, status, urls, baseByteSize, headByteSize }, i) => {
30919
+ const viewers = items.map(({ id, file, status, from, urls, baseByteSize, headByteSize }, i) => {
30728
30920
  const single = !(urls.base && urls.head);
30729
30921
  return `<section class="image-item" id="${id}"${i ? " hidden" : ""}${single ? " data-single" : ""} aria-label="${escapeHtml(file)}">
30730
- <header class="image-head"><span class="pill ${status}">${status}</span><span class="path">${pathHtml(file)}</span><span class="meta">${escapeHtml(bytesToSize(baseByteSize))} \u2192 ${escapeHtml(bytesToSize(headByteSize))} ${deltaHtml(headByteSize, baseByteSize)}</span><span class="meta dims"><span data-dims="base"></span><span data-dims="head"></span></span></header>
30922
+ <header class="image-head"><span class="pill ${status}">${status}</span>${renamedPill(from)}<span class="path">${pathHtml(file)}</span><span class="meta">${escapeHtml(bytesToSize(baseByteSize))} \u2192 ${escapeHtml(bytesToSize(headByteSize))} ${deltaHtml(headByteSize, baseByteSize)}</span><span class="meta dims"><span data-dims="base"></span><span data-dims="head"></span></span></header>
30731
30923
  <div class="stage"><div class="layers">${figure("base", urls.base)}${figure("head", urls.head)}<span class="divider" aria-hidden="true"></span><span class="tag tag-base" aria-hidden="true">Base</span><span class="tag tag-head" aria-hidden="true">Head</span></div></div>
30732
30924
  ${single ? `<p class="note">${status === "added" ? "New image: there's no base version to compare." : status === "removed" ? "Removed image: there's no head version to compare." : "Only one version could be included."}</p>` : ""}
30733
30925
  </section>`;
@@ -30794,7 +30986,7 @@ function reportFiles(options) {
30794
30986
  ["base", image.basePath, image.baseByteSize]
30795
30987
  ].forEach(([side, path11, size]) => {
30796
30988
  if (!path11 || size > MAX_IMAGE_SIZE) return;
30797
- files.push({ path: `images/${side}/${image.file}`, content: readFileSync3(path11) });
30989
+ files.push({ path: `images/${side}/${image.file}`, content: readFileSync5(path11) });
30798
30990
  urls[side] = `images/${side}/${encodePath(image.file)}`;
30799
30991
  });
30800
30992
  imageUrls.set(image.file, urls);
@@ -30823,16 +31015,25 @@ async function run({ core, context: context3, getOctokit: getOctokit2, env = pro
30823
31015
  core.info(sha ? `Removed ${dir}/ from ${inputs.reportBranch}.` : `Nothing to remove for ${dir}/ on ${inputs.reportBranch}.`);
30824
31016
  return;
30825
31017
  }
30826
- const [headMap, baseMap] = await Promise.all([fetchFilesAndSizes(inputs.headPath, inputs.fileGlobPattern, { core, required: true }), fetchFilesAndSizes(inputs.basePath, inputs.fileGlobPattern, { core, required: false })]);
30827
- const hasBase = baseMap.size > 0;
30828
- const reportOptions = { headMap, baseMap, hasBase, rootPath: inputs.headPath, buildDir: inputs.buildDir, mainFile: inputs.mainFile, readPackageJson: inputs.readPackageJson, extensions: inputs.extensions, core };
31018
+ const [headMap, measuredBase] = await Promise.all([fetchFilesAndSizes(inputs.headPath, inputs.fileGlobPattern, { core, required: true }), fetchFilesAndSizes(inputs.basePath, inputs.fileGlobPattern, { core, required: false })]);
31019
+ const hasBase = measuredBase.size > 0;
31020
+ const { baseMap, renames, timedOut } = hasBase ? matchRenames({ headMap, baseMap: measuredBase, headRoot: inputs.headPath, baseRoot: inputs.basePath, normalizeNames: inputs.normalizeNames, threshold: inputs.renameThreshold }) : { baseMap: measuredBase, renames: /* @__PURE__ */ new Map(), timedOut: false };
31021
+ if (timedOut) core.warning("Stopped matching renamed files after 30 seconds; some may show as added and removed. Add normalize-names patterns or narrow file-glob-pattern.");
31022
+ if (renames.size > 0) core.info(`Matched ${renames.size} renamed file${renames.size === 1 ? "" : "s"} between base and head.`);
31023
+ const visual = inputs.visualDiff !== "none";
31024
+ const changes = await collectChanges({ headMap, baseMap, headRoot: inputs.headPath, baseRoot: inputs.basePath, renames, ignorePatterns: inputs.ignorePatterns, extensions: inputs.extensions, maxDiffSize: inputs.maxDiffSize, maxDiffLines: inputs.maxDiffLines, diffs: visual, core });
31025
+ const reportOptions = { headMap, baseMap, hasBase, changed: changes.changed, rootPath: inputs.headPath, buildDir: inputs.buildDir, mainFile: inputs.mainFile, readPackageJson: inputs.readPackageJson, extensions: inputs.extensions, core };
30829
31026
  const report = buildReport(reportOptions);
30830
- const reportWithin = (limit) => report.text.length <= limit ? report : buildReport({ ...reportOptions, maxLength: limit });
30831
- let changes;
31027
+ const shortened = /* @__PURE__ */ new Map();
31028
+ const reportWithin = (limit) => {
31029
+ if (report.text.length <= limit) return report;
31030
+ if (!shortened.has(limit)) shortened.set(limit, buildReport({ ...reportOptions, maxLength: limit }));
31031
+ return shortened.get(limit);
31032
+ };
30832
31033
  let link;
31034
+ let published = false;
30833
31035
  let summaryMarkdown = "";
30834
- if (inputs.visualDiff !== "none") {
30835
- changes = await collectChanges({ headMap, baseMap, headRoot: inputs.headPath, baseRoot: inputs.basePath, extensions: inputs.extensions, maxDiffSize: inputs.maxDiffSize, maxDiffLines: inputs.maxDiffLines, core });
31036
+ if (visual) {
30836
31037
  const rows = sizeRows(report.sections);
30837
31038
  const totals = { headTotal: report.headTotal, baseTotal: report.baseTotal };
30838
31039
  if (inputs.visualDiff === "branch") {
@@ -30842,6 +31043,7 @@ async function run({ core, context: context3, getOctokit: getOctokit2, env = pro
30842
31043
  const files = reportFiles({ title: inputs.commentHeader.replace(/^#+\s*/, "") || "File metrics", rows, hasBase, changes, totals, context: `${where} @ ${(pullRequest?.head?.sha ?? context3.sha ?? "").slice(0, 7)}` });
30843
31044
  await publishToBranch({ octokit: octokit(), owner, repo, branch: inputs.reportBranch, dir, files, message: `chore: file diff report for ${pullRequest ? `#${pullRequest.number}` : dir}` });
30844
31045
  link = await reportUrl({ octokit: octokit(), owner, repo, dir, pagesUrl: inputs.pagesUrl });
31046
+ published = true;
30845
31047
  core.info(`Published the visual diff to ${inputs.reportBranch}/${dir}/ (${link}).`);
30846
31048
  } catch (error2) {
30847
31049
  core.warning(`Unable to publish the visual diff to "${inputs.reportBranch}" (${error2.message}). Falling back to the job summary; the token needs contents: write.`);
@@ -30852,10 +31054,11 @@ async function run({ core, context: context3, getOctokit: getOctokit2, env = pro
30852
31054
  link ??= runUrl(env);
30853
31055
  }
30854
31056
  const marker = commentMarker(inputs.commentHeader);
30855
- const stats = changes ? renderStats({ stats: changes.stats, imageCount: changes.images.length }) : "";
31057
+ const stats = visual ? renderStats({ stats: changes.stats, imageCount: changes.images.length }) : "";
30856
31058
  const commentReport = reportWithin(COMMENT_LIMIT - COMMENT_RESERVE);
30857
31059
  const omittedNote = commentReport.omitted.files > 0 ? `<em>Some rows were left out to fit GitHub's comment limit.${link ? ` See the [full report](${link}).` : ""}</em>` : "";
30858
- const commentStats = [stats, link ? `\u{1F4CA} [View the visual diff](${link})` : ""].filter(Boolean).join("<br/>\n");
31060
+ const linkLine = !link || hasBase && !report.hasChanged ? "" : published ? `\u{1F4CA} [View the visual diff](${link})` : `\u{1F4DD} [Size and line diffs in the job summary](${link})`;
31061
+ const commentStats = [stats, linkLine].filter(Boolean).join("<br/>\n");
30859
31062
  const content = [marker, inputs.commentHeader, "", ...commentStats ? [commentStats, ""] : [], commentReport.text, ...omittedNote ? ["", omittedNote] : []].join("\n");
30860
31063
  if (inputs.comment) {
30861
31064
  if (!pullRequest) core.info("Not running on a pull request; skipping the comment.");