// Minimal runnable check for dsh-git-review's parsers and pure client logic // (node scripts/check-parse.mjs). Requires Node >= 23.6 (native TS type // stripping; verified on v24) — older LTS fail with 'Unknown file extension // ".ts"'. No build step, no test framework. NUL in fixtures is written // '\x00' (a '\0' before a digit would parse as an octal escape). import assert from 'node:assert/strict' import { countMatches, countOccurrences, EMPTY_TREE_ID, mergeDiffRows, mergeStatus, normalizeBaseRef, numstatIndex, OBJECT_ID_RE, parseBlamePorcelain, parseDecorations, parseLogLines, parseNameStatusZ, parseNumstatZ, parsePorcelainV1, parseStashLines, refRange, sniffPreviewMime, splitDiffSections, unquoteHeaderPath } from '../src/git-parse.ts' import { buildHunkPatch } from '../src/client/diff-parse.ts' import { countMatchRows, countUnifiedMatches, makeSearchEngine, makeWordHighlighter, parseUnifiedDiff, splitByMatch, unifyHunkRows } from '../src/client/diff-parse.ts' import { computeGraphLanes } from '../src/client/git-graph.ts' import { langOf, makeLineHighlighter, sliceTokens, splitLineByTokens, tokenizeLine } from '../src/client/highlight.ts' import { badgeFor, badgesFor, buildFileTree, filterFiles, flattenTree, isUnmerged, mergeAllFiles } from '../src/client/file-tree.ts' import { DEFAULT_PREFS, normalizePrefs, normalizeWorkspaceKey } from '../src/client/prefs.ts' import { migrationFields, prefsFromSection, sectionIsDefault } from '../src/client/review-settings.ts' import { needsScriptNotice, previewKindForPath } from '../src/client/preview-kind.ts' import { resolveImageSides } from '../src/client/image-sides.ts' import { collectMdAssets, defangRemoteImages, htmlFallbackForPreview, resolveMdAsset, rewriteMdAssets } from '../src/client/md-preview.ts' import { createViewedStore, parseViewed } from '../src/client/viewed.ts' import { createDraftBox, draftsKey, parseDrafts } from '../src/client/comment-drafts.ts' import { findBranchTip, isAncestorOrSelf, resolveRangeHash } from '../src/client/range-guard.ts' import { compareNatural } from '../src/natural-order.ts' // ── porcelain v1 -z ─────────────────────────────────────────────────────── // 1. Mixed everyday states: staged modify, unstaged modify, untracked. let entries = parsePorcelainV1('M src/a.ts\x00 M src/b.ts\x00?? docs/new.md\x00') assert.deepEqual(entries, [ { x: 'M', y: ' ', path: 'src/a.ts' }, { x: ' ', y: 'M', path: 'src/b.ts' }, { x: '?', y: '?', path: 'docs/new.md' }, ]) // 2. Rename records carry the original path as one extra NUL token, and the // walk must NOT mistake that token for the next record. entries = parsePorcelainV1('R new-name.ts\x00old-name.ts\x00M keep.ts\x00') assert.equal(entries.length, 2) assert.deepEqual(entries[0], { x: 'R', y: ' ', path: 'new-name.ts', origPath: 'old-name.ts' }) assert.deepEqual(entries[1], { x: 'M', y: ' ', path: 'keep.ts' }) // 3. CJK and spaces arrive verbatim (quotepath=false, NUL separation). entries = parsePorcelainV1('?? docs/中文 文档.md\x00') assert.equal(entries[0].path, 'docs/中文 文档.md') // 4. Empty output → no entries; the trailing NUL's empty token is not one. assert.deepEqual(parsePorcelainV1(''), []) assert.equal(parsePorcelainV1('A x\x00').length, 1) // ── numstat -z ──────────────────────────────────────────────────────────── // 5. Counts, binary dashes, and a path containing a tab (path = everything // after the SECOND tab of the record). let rows = parseNumstatZ('3\t1\ta.ts\x00-\t-\tpic web.webp\x0012\t0\tweird\tname.ts\x00') assert.deepEqual(rows, [ { added: 3, deleted: 1, path: 'a.ts' }, { added: null, deleted: null, path: 'pic web.webp' }, { added: 12, deleted: 0, path: 'weird\tname.ts' }, ]) // 6. Rename/copy records (-z, real git shape): `added\tdeleted\t` with an // EMPTY third field, then TWO NUL tokens — source, then destination. rows = parseNumstatZ('1\t0\t\x00old-name.ts\x00renamed.ts\x00') assert.deepEqual(rows, [{ added: 1, deleted: 0, path: 'renamed.ts', origPath: 'old-name.ts' }]) assert.deepEqual(parseNumstatZ(''), []) // ── status merge ────────────────────────────────────────────────────────── // 7. Merge: tracked counts come from numstat, untracked from the probe map, // binary flags follow dashes/absence, totals-free shape is client-ready. const index = numstatIndex(parseNumstatZ('10\t2\tm.ts\x00-\t-\tb.webp\x00')) const files = mergeStatus( parsePorcelainV1('M m.ts\x00A b.webp\x00?? u.md\x00 M none.ts\x00'), index, new Map([['u.md', { added: 7, binary: false }]]), ) assert.deepEqual(files.map(f => [f.path, f.added, f.deleted, f.binary, f.untracked]), [ ['m.ts', 10, 2, false, false], ['b.webp', 0, 0, true, false], ['u.md', 7, 0, false, true], // No numstat row + not untracked → mode-only style change, not binary. ['none.ts', 0, 0, false, false], ]) // ── unified diff ────────────────────────────────────────────────────────── // 8. Classic two-hunk diff: ctx/del/add rows, 1-based numbering per side // restarting at each hunk's @@ starts, section heading captured. let parsed = parseUnifiedDiff([ 'diff --git a/x.ts b/x.ts', 'index 111..222 100644', '--- a/x.ts', '+++ b/x.ts', '@@ -1,3 +1,3 @@ import a', ' old', '-gone', '+here', ' tail', '@@ -10,2 +10,4 @@ fn b', ' ctx', '+one', '+two', ' ctx', ].join('\n')) assert.equal(parsed.hunks.length, 2) assert.equal(parsed.oldPath, 'x.ts') assert.equal(parsed.newPath, 'x.ts') const [h1, h2] = parsed.hunks assert.equal(h1.section, 'import a') assert.deepEqual(h1.rows.map(r => r.kind), ['ctx', 'pair', 'ctx']) assert.equal(h1.rows[0].left.no, 1) assert.equal(h1.rows[0].right.no, 1) assert.equal(h1.rows[1].left.text, 'gone') assert.equal(h1.rows[1].right.text, 'here') assert.equal(h2.rows.map(r => r.kind).join(','), 'ctx,add,add,ctx') assert.equal(h2.rows[1].right.no, 11) assert.equal(h2.rows[1].left, null) assert.equal(h2.damaged, false, 'the declared counts match the body (no truncated-hunk flag)') // 9. Pure additions have no old side; counts count. parsed = parseUnifiedDiff([ '--- /dev/null', '+++ b/new.md', '@@ -0,0 +1,2 @@', '+first', '+second', ].join('\n')) assert.equal(parsed.newFile, true) assert.deepEqual(parsed.hunks[0].rows.map(r => r.kind), ['add', 'add']) assert.equal(parsed.hunks[0].rows[0].right.no, 1) // 10. Deletion: every row is left-only. parsed = parseUnifiedDiff([ '--- a/old.md', '+++ /dev/null', '@@ -1,2 +0,0 @@', '-first', '-second', ].join('\n')) assert.equal(parsed.deletedFile, true) assert.deepEqual(parsed.hunks[0].rows.map(r => r.kind), ['del', 'del']) // 11. Unbalanced run: 2 dels + 1 add → one pair plus one left-only leftover. parsed = parseUnifiedDiff([ '@@ -1,3 +1,2 @@', '-a1', '-a2', '+b1', ' c', ].join('\n')) assert.deepEqual(parsed.hunks[0].rows.map(r => r.kind), ['pair', 'del', 'ctx']) assert.equal(parsed.hunks[0].rows[1].left.text, 'a2') assert.equal(parsed.hunks[0].rows[1].right, null) // 12. "\ No newline" annotates the cell right before it (both sides). parsed = parseUnifiedDiff([ '@@ -1,2 +1,2 @@', '-old', '\\ No newline at end of file', '+new', '\\ No newline at end of file', ].join('\n')) assert.equal(parsed.hunks[0].rows[0].left.noNewline, true) assert.equal(parsed.hunks[0].rows[0].right.noNewline, true) // 13. Binary markers and rename headers; empty text parses to no hunks. parsed = parseUnifiedDiff([ 'diff --git a/p.webp b/p.webp', 'Binary files a/p.webp and b/p.webp differ', ].join('\n')) assert.equal(parsed.binary, true) parsed = parseUnifiedDiff([ 'diff --git a/ren.ts b/ren.ts', 'similarity index 99%', 'rename from old.ts', 'rename to ren.ts', ].join('\n')) assert.equal(parsed.rename, true) assert.deepEqual(parseUnifiedDiff(''), { hunks: [], binary: false, oldPath: null, newPath: null, newFile: false, deletedFile: false, rename: false }) // 13b. Parser edges: empty results are fresh copies, stray '@' lines end // the hunk, quoted headers strip, and no-newline markers never leak // across file boundaries. const emptyA = parseUnifiedDiff('') emptyA.hunks.push({ oldStart: 1, oldCount: 1, newStart: 1, newCount: 1, section: '', rows: [] }) assert.equal(parseUnifiedDiff('').hunks.length, 0, 'empty base is not shared-mutable') const strayAt = parseUnifiedDiff(['diff --git a/a b/a', '--- a/a', '+++ b/a', '@@ -1,1 +1,1 @@', '-old', '@stray', '+new'].join('\n')) assert.equal(strayAt.hunks.length, 1) assert.equal(strayAt.hunks[0].rows.length, 1, 'stray @ ends the hunk') const quoted = parseUnifiedDiff(['diff --git "a/we ird" "b/we ird"', '--- "a/we ird"', '+++ "b/we ird"', '@@ -1,1 +1,1 @@', '-o', '+n'].join('\n')) assert.equal(quoted.newPath, 'we ird') const leaky = parseUnifiedDiff(['diff --git a/a b/a', '--- a/a', '+++ b/a', '@@ -1,1 +1,1 @@', '-old', '+new', 'diff --git a/b b/b', '\\ No newline at end of file'].join('\n')) const leakyDel = leaky.hunks[0].rows.find(r => r.kind === 'del') assert.equal(leakyDel?.left?.noNewline, undefined, 'marker after boundary marks nothing') // 14. Untracked pseudo diff (host-synthesized shape) parses as a new file. parsed = parseUnifiedDiff([ 'diff --git a/u.md b/u.md', '--- /dev/null', '+++ b/u.md', '@@ -0,0 +1,1 @@', '+hello', ].join('\n')) assert.equal(parsed.newFile, true) assert.deepEqual(parsed.hunks[0].rows.map(r => r.kind), ['add']) // ── file tree / filter / badge ──────────────────────────────────────────── // 15. Tree aggregates by directory, dirs before files, counts recurse; // filter degrades to a flat case-insensitive list. const treeFiles = mergeStatus( parsePorcelainV1('M lib/a.ts\x00M lib/deep/b.ts\x00?? readme.md\x00'), new Map(), new Map(), ) const tree = buildFileTree(treeFiles) assert.deepEqual(tree.children.map(c => c.kind + ':' + c.name), ['dir:lib', 'file:readme.md']) const libDir = tree.children[0] assert.equal(libDir.kind === 'dir' ? libDir.fileCount : -1, 2) assert.equal(tree.fileCount, 3) assert.equal(filterFiles(treeFiles, 'DEEP').length, 1) assert.equal(filterFiles(treeFiles, ' ').length, 3) // 15b. flattenTree: render order with indent depth; a collapsed directory // keeps its own row and drops its children (the panel's row budget). assert.deepEqual(flattenTree(tree.children, new Set()).map(r => r.depth + ':' + r.entry.name), ['0:lib', '1:deep', '2:b.ts', '1:a.ts', '0:readme.md']) assert.deepEqual(flattenTree(tree.children, new Set(['lib'])).map(r => r.entry.name), ['lib', 'readme.md']) assert.deepEqual(flattenTree(tree.children, new Set(['lib/deep'])).map(r => r.depth + ':' + r.entry.name), ['0:lib', '1:deep', '1:a.ts', '0:readme.md']) // 16. Badge priority: untracked beats added, added beats deleted, renamed // and modified map to their own glyphs. assert.equal(badgeFor({ ...treeFiles[2], untracked: true }).key, 'untracked') assert.equal(badgeFor({ path: 'x', x: 'A', y: 'D', added: 1, deleted: 1, binary: false, untracked: false }).key, 'added') assert.equal(badgeFor({ path: 'x', x: 'D', y: ' ', added: 0, deleted: 2, binary: false, untracked: false }).glyph, '\u2212') assert.equal(badgeFor({ path: 'x', x: 'R', y: ' ', added: 0, deleted: 0, binary: false, untracked: false }).key, 'renamed') assert.equal(badgeFor({ path: 'x', x: ' ', y: 'M', added: 1, deleted: 1, binary: false, untracked: false }).glyph, '\u00b1') // 17. badgesFor: staged (X) and unstaged (Y) halves render as ordered badges; // untracked stays a single muted '?'; an inactive/inactive row renders // no badge rather than a fake "modified" one. const dual = badgesFor({ path: 'x', x: 'M', y: 'M', added: 1, deleted: 1, binary: false, untracked: false }) assert.deepEqual(dual.map(b => [b.glyph, b.staged]), [['\u00b1', true], ['\u00b1', false]]) const addDelete = badgesFor({ path: 'x', x: 'A', y: 'D', added: 1, deleted: 1, binary: false, untracked: false }) assert.deepEqual(addDelete.map(b => b.glyph), ['+', '\u2212']) assert.deepEqual(addDelete.map(b => b.staged), [true, false]) assert.deepEqual(badgesFor({ path: 'x', x: ' ', y: ' ', added: 0, deleted: 0, binary: false, untracked: false }).map(b => b.key), []) assert.deepEqual(badgesFor({ ...treeFiles[2] }).map(b => [b.key, b.staged]), [['untracked', undefined]]) // 17b. Unmerged states (both-sided DD included) collapse to one red conflict // badge; staged-add + worktree-delete (A/D) stays two normal badges. for (const pair of ['UU', 'AA', 'DD', 'AU', 'UA', 'DU', 'UD']) { assert.ok(isUnmerged(pair[0], pair[1]), pair + ' is unmerged') assert.deepEqual(badgesFor({ path: 'x', x: pair[0], y: pair[1], added: 0, deleted: 0, binary: false, untracked: false }).map(b => b.key), ['conflict']) } assert.ok(!isUnmerged('A', 'D') && !isUnmerged('M', ' ') && !isUnmerged(' ', ' ')) const subTree = buildFileTree([ { path: 'lib/z.ts', x: ' ', y: 'M', added: 1, deleted: 0, binary: false, untracked: false }, { path: 'lib/a.ts', x: ' ', y: 'M', added: 1, deleted: 0, binary: false, untracked: false }, ]) const subLib = subTree.children[0] assert.deepEqual(subLib.kind === 'dir' ? subLib.children.map(c => c.name) : [], ['a.ts', 'z.ts']) // 18. mergeAllFiles: changed rows pass through, other paths become unchanged // rows with no badge; input order is preserved. const merged = mergeAllFiles(['lib/a.ts', 'other/x.ts', 'readme.md'], treeFiles) assert.deepEqual(merged.map(f => [f.path, f.unchanged === true]), [ ['lib/a.ts', false], ['other/x.ts', true], ['readme.md', false], ]) assert.deepEqual(badgesFor(merged[1]), []) // treeFiles[2] is the untracked readme.md — its row (x='?') passes through. assert.equal(merged[2].x, '?') // 19. countOccurrences: case-insensitive, non-overlapping, empty needle = 0. assert.equal(countOccurrences('aBc AbC abc', 'abc'), 3) assert.equal(countOccurrences('abc', ''), 0) assert.equal(countOccurrences('', 'abc'), 0) // 20. splitDiffSections: path from +++ (b/ stripped), deletion falls back to // --- (a/ stripped), body starts at @@ (headers never match queries). const fullDiff = [ 'diff --git a/one.ts b/one.ts', 'index 111..222 100644', '--- a/one.ts', '+++ b/one.ts', '@@ -1 +1 @@', '-alpha', '+ALPHA beta', 'diff --git a/gone.md b/gone.md', '--- a/gone.md', '+++ /dev/null', '@@ -1 +0,0 @@', '-gamma', ].join('\n') const sections = splitDiffSections(fullDiff) assert.deepEqual(sections.map(s => s.path), ['one.ts', 'gone.md']) assert.equal(countOccurrences(sections[0].body, 'alpha'), 2) assert.equal(countOccurrences(sections[0].body, 'index'), 0) assert.equal(countOccurrences(sections[1].body, 'gamma'), 1) // 21. splitByMatch: odd indices are the matched substrings; no match = [text]. assert.deepEqual(splitByMatch('x Foo y FOO z', 'foo'), ['x ', 'Foo', ' y ', 'FOO', ' z']) assert.deepEqual(splitByMatch('nothing', 'foo'), ['nothing']) // 22. normalizeBaseRef: rejects option/range/metacharacter injection, keeps // plain names (dots, dashes, slashes, CJK). assert.equal(normalizeBaseRef('feature/foo-1.2'), 'feature/foo-1.2') assert.equal(normalizeBaseRef('中文分支'), '中文分支') assert.equal(normalizeBaseRef(' main '), 'main') assert.equal(normalizeBaseRef('-oProxyCommand=evil'), null) assert.equal(normalizeBaseRef('a..b'), null) assert.equal(normalizeBaseRef('a b'), null) assert.equal(normalizeBaseRef('a~1'), null) assert.equal(normalizeBaseRef('a^2'), null) assert.equal(normalizeBaseRef('a:b'), null) assert.equal(normalizeBaseRef('a{b'), null) assert.equal(normalizeBaseRef(42), null) assert.equal(normalizeBaseRef(''), null) // 23. parseNameStatusZ: plain records take one path token; R/C records take // source then destination (with the score kept from the letter token). let nsRows = parseNameStatusZ('M\x00a.ts\x00D\x00b.ts\x00') assert.deepEqual(nsRows, [ { letter: 'M', path: 'a.ts' }, { letter: 'D', path: 'b.ts' }, ]) nsRows = parseNameStatusZ('R100\x00old.ts\x00new.ts\x00') assert.deepEqual(nsRows, [{ letter: 'R', score: '100', path: 'new.ts', origPath: 'old.ts' }]) assert.deepEqual(parseNameStatusZ(''), []) // 24. refRange: three-dot for two commits (merge-base view); two-dot when // the base end is the empty tree (a tree id has no merge-base). assert.deepEqual(refRange('a'.repeat(40), 'b'.repeat(40)), ['a'.repeat(40) + '...' + 'b'.repeat(40)]) assert.deepEqual(refRange(EMPTY_TREE_ID, 'b'.repeat(40)), [EMPTY_TREE_ID, 'b'.repeat(40)]) // 25. mergeDiffRows: name-status letters become x with a blank y; counts come // from the numstat index (destination path); binary follows the dashes; // rows without a numstat entry are zero-count, not binary. const rangeRows = mergeDiffRows( parseNameStatusZ('A\x00added.ts\x00M\x00mod.ts\x00R100\x00old.ts\x00ren.ts\x00D\x00gone.bin\x00'), numstatIndex(parseNumstatZ('5\t0\tadded.ts\x001\t2\tmod.ts\x000\t0\t\x00old.ts\x00ren.ts\x00-\t-\tgone.bin\x00')), ) assert.deepEqual(rangeRows.map(r => [r.path, r.x, r.y, r.added, r.deleted, r.binary, r.untracked]), [ ['added.ts', 'A', ' ', 5, 0, false, false], ['mod.ts', 'M', ' ', 1, 2, false, false], ['ren.ts', 'R', ' ', 0, 0, false, false], ['gone.bin', 'D', ' ', 0, 0, true, false], ]) assert.deepEqual(mergeDiffRows([], new Map()), []) // 26. parseLogLines + parseDecorations: \x1e-record/\x1f-field wire format, // leading newlines trimmed, root commits have no parents, decorations // classify head/tag/other, malformed records are skipped. const H1 = 'a'.repeat(40) const H2 = 'b'.repeat(40) const H3 = 'c'.repeat(40) const logLines = parseLogLines([ '', H1 + '\x1f' + H2 + ' ' + H3 + '\x1fAlice\x1f1700000000\x1fHEAD -> main, origin/main, tag: v1.0\x1fsubject one\x1e', H2 + '\x1f\x1fBob\x1f1700000001\x1f\x1froot commit\x1e', H3 + '\x1f' + H1 + '\x1fCara\x1f1700000002\x1f\x1fsubject three\x1fbody line one\nbody line two\x1e', 'zz' + '\x1fshort\x1e', ].join('\x1e')) assert.equal(logLines.length, 3) assert.deepEqual(logLines[0], { hash: H1, parents: [H2, H3], authorName: 'Alice', timestamp: 1700000000, refs: [ { name: 'HEAD', kind: 'head' }, { name: 'main', kind: 'head' }, { name: 'origin/main', kind: 'other' }, { name: 'v1.0', kind: 'tag' }, ], subject: 'subject one', body: '', }) assert.deepEqual(logLines[1].parents, []) assert.equal(logLines[1].subject, 'root commit') assert.equal(logLines[1].body, '') assert.equal(logLines[2].subject, 'subject three') assert.equal(logLines[2].body, 'body line one\nbody line two') // 27. computeGraphLanes, straight history: one lane, in/out segments chain. const straight = computeGraphLanes([ { hash: H1, parents: [H2] }, { hash: H2, parents: [H3] }, { hash: H3, parents: [] }, ]) assert.equal(straight.length, 3) assert.ok(straight.every(row => row.lane === 0 && row.laneCount === 1 && row.pass.length === 0)) assert.deepEqual(straight[0].inEdges, []) assert.deepEqual(straight[0].outEdges, [{ from: 0, to: 0, color: 0 }]) assert.deepEqual(straight[1].inEdges, [{ from: 0, to: 0, color: 0 }]) assert.deepEqual(straight[2].outEdges, []) // 28. computeGraphLanes, branch: a second tip claims a new lane and folds // into the main line at the shared parent (the fold keeps its color); // the main line passes straight through the branch tip's row. const branched = computeGraphLanes([ { hash: H1, parents: [H3] }, { hash: H2, parents: [H3] }, { hash: H3, parents: [] }, ]) assert.deepEqual(branched.map(r => r.lane), [0, 1, 0]) assert.deepEqual(branched[1].inEdges, []) assert.deepEqual(branched[1].outEdges, [{ from: 1, to: 0, color: branched[1].color }]) assert.deepEqual(branched[1].pass, [{ lane: 0, color: 0 }]) assert.deepEqual(branched[2].inEdges, [{ from: 0, to: 0, color: 0 }]) assert.deepEqual(branched[2].pass, []) // 29. computeGraphLanes, merge: the merge commit branches out, the merged // line folds sideways into it at its row, and the untouched line passes // straight through the middle row. const mergeBase = computeGraphLanes([ { hash: H1, parents: [H2, H3] }, { hash: H2, parents: [H3] }, { hash: H3, parents: [] }, ]) assert.deepEqual(mergeBase[0].outEdges, [{ from: 0, to: 0, color: 0 }, { from: 0, to: 1, color: 1 }]) assert.deepEqual(mergeBase[1].inEdges, [{ from: 0, to: 0, color: 0 }]) assert.deepEqual(mergeBase[1].pass, [{ lane: 1, color: 1 }]) assert.deepEqual(mergeBase[2].inEdges, [{ from: 1, to: 1, color: 1 }]) // 29b. Dead trailing slots don't widen the canvas — but the row's OWN lane // always counts: H3 sits in lane 1, so the canvas stays 2 wide even // though every other lane is free (at width 1 its node is clipped away, // which the old "live only" count did). assert.equal(mergeBase[2].laneCount, 2) // 30. countMatches: literal case-insensitive default; the optional case and // regex toggles; an invalid regex counts 0 (never throws). assert.equal(countMatches('aBc AbC abc', 'abc'), 3) assert.equal(countMatches('aBc AbC abc', 'abc', { caseSensitive: true }), 1) assert.equal(countMatches('aBc AbC abc', 'a.c', { regex: true }), 3) assert.equal(countMatches('aBc AbC abc', 'a.c', { regex: true, caseSensitive: true }), 2) // aBc + abc (AbC has an uppercase A) assert.equal(countMatches('abc', '['), 0) assert.equal(countMatches('aaa', 'aa'), 1) // non-overlapping, like countOccurrences // 31. makeSearchEngine: parts/count/test under case/regex options; an invalid // regex produces an inactive engine. const engine = makeSearchEngine({ query: 'foo' }) assert.ok(engine.active) assert.equal(engine.count('Foo fOo foo'), 3) assert.deepEqual(engine.parts('x Foo y'), ['x ', 'Foo', ' y']) assert.ok(engine.test('xxFOO')) const csEngine = makeSearchEngine({ query: 'Foo', caseSensitive: true }) assert.equal(csEngine.count('Foo FOO'), 1) const rxEngine = makeSearchEngine({ query: 'f.o', regex: true }) assert.equal(rxEngine.count('Foo foo fuo'), 3) const badEngine = makeSearchEngine({ query: '[' , regex: true }) assert.equal(badEngine.active, false) assert.equal(badEngine.count('anything'), 0) const emptyEngine = makeSearchEngine({ query: ' ' }) assert.equal(emptyEngine.active, false) // 32. rowHasMatch/countMatchRows with an engine (side-by-side navigation). const parseDiff = parseUnifiedDiff([ 'diff --git a/a.txt b/a.txt', '--- a/a.txt', '+++ b/a.txt', '@@ -1,2 +1,2 @@', ' keep', '-old Foo', '+new bar', ].join('\n')) assert.equal(countMatchRows(parseDiff, makeSearchEngine({ query: 'foo' })), 1) // 33. unifyHunkRows: context stays one line; a replacement (pair) renders as // deletion line then addition line; one-sided rows pass through. const unified = unifyHunkRows(parseDiff.hunks[0].rows) assert.deepEqual(unified.map(line => line.kind), ['ctx', 'del', 'add']) assert.deepEqual(unified.map(line => line.no), [1, 2, 2]) // ctx=old1, del=old2, add=new2 assert.equal(unified[2].text, 'new bar') // 34. countUnifiedMatches: a replacement pair with a match on BOTH lines // counts twice (the unified navigation walks lines, not rows). const pairDiff = parseUnifiedDiff([ 'diff --git a/b.txt b/b.txt', '--- a/b.txt', '+++ b/b.txt', '@@ -1 +1 @@', '-alpha & beta', '+alpha & gamma', ].join('\n')) const pairEngine = makeSearchEngine({ query: 'alpha' }) assert.equal(countUnifiedMatches(pairDiff, pairEngine), 2) // 34b. Preferences normalization: junk store falls back to defaults, valid // values survive, unknown keys drop (a hand-edited localStorage must never // crash the tab). assert.deepEqual(normalizePrefs(null), DEFAULT_PREFS) assert.deepEqual(normalizePrefs('not json'), DEFAULT_PREFS) assert.deepEqual(normalizePrefs({ viewMode: 'unified', searchScope: 'path', graphCollapsed: true, searchCS: true, searchRegex: true, wsIgnore: true, junk: 1 }), { viewMode: 'unified', searchScope: 'path', graphCollapsed: true, searchCS: true, searchRegex: true, wsIgnore: true, syntaxHighlight: true }) assert.deepEqual(normalizePrefs({ viewMode: 'bogus', searchScope: 'nope' }), DEFAULT_PREFS) // 35. Settings-scope store helpers: section reads normalize, a default // section reads as default, and the legacy-store migration carries only // a user-written store (defaults or junk stay put; shapes clean up). assert.deepEqual(prefsFromSection({ viewMode: 'unified', junk: 1 }), { viewMode: 'unified', searchScope: 'diff', graphCollapsed: false, searchCS: false, searchRegex: false, wsIgnore: false, syntaxHighlight: true }) assert.equal(sectionIsDefault({ viewMode: 'split', searchScope: 'diff', graphCollapsed: false, searchCS: false, searchRegex: false, wsIgnore: false, syntaxHighlight: true }), true) assert.equal(sectionIsDefault({ viewMode: 'unified', searchScope: 'diff', graphCollapsed: false, searchCS: false, searchRegex: false, wsIgnore: false, syntaxHighlight: true }), false) assert.equal(migrationFields(null), null) assert.equal(migrationFields('not json'), null) assert.equal(migrationFields(JSON.stringify(DEFAULT_PREFS)), null) const legacy = JSON.stringify({ viewMode: 'unified', searchScope: 'content' }) assert.deepEqual(migrationFields(legacy), { viewMode: 'unified', searchScope: 'content', graphCollapsed: false, searchCS: false, searchRegex: false, wsIgnore: false, syntaxHighlight: true }) // 36. Word-level highlight: a replacement pair's changed spans come out of a // character-level LCS; non-pairs, rewrites (low similarity) and exhausted // budget all degrade to null (plain row rendering). const words = makeWordHighlighter() assert.equal(words.pair({ kind: 'ctx', left: { no: 1, text: 'a' }, right: { no: 1, text: 'a' } }), null) const wordPair = words.pair({ kind: 'pair', left: { no: 3, text: 'const x = foo(a, b);' }, right: { no: 3, text: 'const x = foo(a, c);' }, }) assert.ok(wordPair !== null) assert.deepEqual(wordPair.old, [[17, 18]]) assert.deepEqual(wordPair.new, [[17, 18]]) assert.equal(words.pair({ kind: 'pair', left: { no: 4, text: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }, right: { no: 4, text: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' }, }), null) const tiny = makeWordHighlighter(1) assert.equal(tiny.pair({ kind: 'pair', left: { no: 1, text: 'ab' }, right: { no: 1, text: 'ax' } }), null) // 37. Viewed store: toggling round-trips through a memory storage, junk // stored values degrade to empty, and the cap evicts the oldest. function memoryStorage(initial) { const map = new Map(Object.entries(initial ?? {})) return { getItem: key => map.get(key) ?? null, setItem: (key, value) => { map.set(key, value) }, removeItem: key => { map.delete(key) }, } } assert.deepEqual(parseViewed(null), []) assert.deepEqual(parseViewed('not json'), []) assert.deepEqual(parseViewed('{"a":1}'), []) assert.deepEqual(parseViewed(JSON.stringify(['a'.repeat(40), 2, '', 'b'.repeat(40), 'a'.repeat(40), 'not-hex', 'x'.repeat(200)])), ['a'.repeat(40), 'b'.repeat(40)]) const VA = 'a'.repeat(40) const VB = 'b'.repeat(40) const viewedStorage = memoryStorage() const viewed = createViewedStore('C:/repo', viewedStorage) assert.equal(viewed.toggle(VA), true) assert.equal(viewed.toggle(VB), true) assert.ok(viewed.has(VA)) assert.ok(viewed.has(VB)) assert.equal(viewed.toggle(VA), false) assert.ok(!viewed.has(VA)) assert.deepEqual(parseViewed(viewedStorage.getItem('dsh-git-review.viewed:' + encodeURIComponent('c:/repo'))), [VB]) const cappedStorage = memoryStorage() cappedStorage.setItem('dsh-git-review.viewed:' + encodeURIComponent('c:/repo'), JSON.stringify(Array.from({ length: 2000 }, (_, i) => i.toString(16).padStart(40, '0')))) const capped = createViewedStore('C:/repo', cappedStorage) const VC = 'c'.repeat(40) capped.toggle(VC) assert.ok(capped.has(VC)) assert.ok(!capped.has((1999).toString(16).padStart(40, '0'))) // 38. Comment draft box: per-workspace key, junk degrades to empty, and the assert.equal(draftsKey('C:/repo/'), 'dsh-git-review.drafts:' + encodeURIComponent('c:/repo')) assert.equal(normalizeWorkspaceKey('C:/repo'), 'c:/repo') assert.equal(normalizeWorkspaceKey('C:/repo/'), 'c:/repo') assert.equal(normalizeWorkspaceKey('C:' + String.fromCharCode(92) + 'repo' + String.fromCharCode(92)), 'c:/repo') assert.equal(normalizeWorkspaceKey('/home/u/repo/'), '/home/u/repo') assert.equal(normalizeWorkspaceKey('/Home/U/Repo'), '/Home/U/Repo') // add/remove/clear round-trips persist into the storage. assert.deepEqual(parseDrafts(null), []) assert.deepEqual(parseDrafts('nope'), []) assert.deepEqual(parseDrafts('[{"path":"a.ts","line":3,"text":"hi"},{"path":"","line":1,"text":"x"},{"bad":1}]'), [{ path: 'a.ts', line: 3, text: 'hi' }]) const draftStorage = memoryStorage() const box = createDraftBox('D:\\repo', draftStorage) box.add({ path: 'src/a.ts', line: 12, text: 'rename this' }) box.add({ path: 'src/b.ts', line: 4, text: 'check null' }) assert.deepEqual(box.list(), [ { path: 'src/a.ts', line: 12, text: 'rename this' }, { path: 'src/b.ts', line: 4, text: 'check null' }, ]) box.remove(0) assert.deepEqual(box.list(), [{ path: 'src/b.ts', line: 4, text: 'check null' }]) box.clear() assert.deepEqual(box.list(), []) // 38b. Draft validation: empty path/text and non-finite lines drop, negative // lines clamp to 1, oversized bodies trim, and the box caps at 200. assert.deepEqual(parseDrafts('[{"path":"a","line":-2,"text":""}]'), []) assert.deepEqual(parseDrafts('[{"path":"a","line":0,"text":"ok"}]'), [{ path: 'a', line: 1, text: 'ok' }]) const bigBox = createDraftBox('D:\\big', memoryStorage()) for (let i = 0; i < 205; i++) bigBox.add({ path: 'f' + i + '.ts', line: i + 1, text: 'c' }) assert.equal(bigBox.list().length, 200) assert.equal(bigBox.list()[0].path, 'f5.ts') bigBox.add({ path: '', line: 1, text: 'junk' }) assert.equal(bigBox.list().length, 200) // 39. Stash list parsing: stash@{n} selector extraction, / records, // malformed records skipped (same shape the log feed uses). const stashRaw = 'stash@{0}1730000000WIP on main: abc1234 fix bugstash@{1}1730000100custom message' const stashes = parseStashLines(stashRaw) assert.deepEqual(stashes, [ { index: 0, timestamp: 1730000000, subject: 'WIP on main: abc1234 fix bug' }, { index: 1, timestamp: 1730000100, subject: 'custom message' }, ]) assert.deepEqual(parseStashLines(''), []) assert.deepEqual(parseStashLines('no-selector123textstash@{x}123bad'), []) assert.deepEqual(parseStashLines('stash@{12}bad-timekeep'), [{ index: 12, timestamp: 0, subject: 'keep' }]) // 40. Syntax highlighting: language mapping, single-line tokenization // (strings with escapes, line comments, numbers, keywords), the budget // degrading to null, and span slicing for word-level overlays. assert.equal(langOf('src/app.tsx'), 'c') assert.equal(langOf('README.md'), null) const toks = tokenizeLine('const url = "http://x" // set', 'c') assert.deepEqual(toks.map(t => [t.kind, t.start, t.end]), [ ['kw', 0, 5], ['str', 12, 22], ['com', 23, 29], ]) const esc = tokenizeLine('a = "say \\"hi\\" now"', 'c') assert.ok(esc.some(t => t.kind === 'str' && t.start === 4)) const pyTok = tokenizeLine('# only a comment', 'py') assert.deepEqual(pyTok, [{ start: 0, end: 16, kind: 'com' }]) const hl = makeLineHighlighter('a.py', 6) assert.notEqual(hl.line('x = 1'), null) assert.deepEqual(hl.line(''), []) assert.equal(hl.line('y = 2'), null, 'budget exhausted -> plain') const sliced = sliceTokens([{ start: 0, end: 10, kind: 'kw' }], 2, 5) assert.deepEqual(sliced, [{ start: 0, end: 3, kind: 'kw' }]) assert.equal(sliceTokens(null, 0, 5), null) // 40b. Tokenizer edges: uppercase keywords, bare Dockerfile, CSS urls, // tight numbers, exact-budget lines. assert.deepEqual(tokenizeLine('SELECT * FROM tbl WHERE x', 'sql').map(t => t.kind), ['kw', 'kw', 'kw']) assert.equal(langOf('Dockerfile'), 'sh') assert.equal(langOf('Dockerfile.dev'), 'sh') assert.ok(tokenizeLine('background: url(https://e.com/a.png)', 'css').every(t => t.kind !== 'com'), 'css has no line comments') const numToks = tokenizeLine('x = 404abc + 0xFF + 1.5e3', 'c') assert.deepEqual(numToks.filter(t => t.kind === 'num').map(t => 'x = 404abc + 0xFF + 1.5e3'.slice(t.start, t.end)), ['404', '0xFF', '1.5e3']) const exactHl = makeLineHighlighter('a.ts', 5) assert.notEqual(exactHl.line('ab = '), null, 'exact-budget line still tokenizes') assert.equal(exactHl.line('more'), null, 'spent budget degrades') // 40c. Gap-preserving segments: tokens plus the plain text between them tile // the line exactly, so highlight rendering never drops identifiers or // whitespace (regression: renderers that mapped tokens alone lost text). const gapLine = 'const x = 1' const gapSegs = splitLineByTokens(gapLine, tokenizeLine(gapLine, 'c')) assert.equal(gapSegs.map(s => gapLine.slice(s.start, s.end)).join(''), gapLine) assert.ok(gapSegs.some(s => s.kind === null && gapLine.slice(s.start, s.end).includes('x ='))) assert.deepEqual(splitLineByTokens('', tokenizeLine('', 'c')), []) assert.deepEqual(splitLineByTokens('abc', []), [{ start: 0, end: 3, kind: null }]) assert.deepEqual(splitLineByTokens('abc', null), [{ start: 0, end: 3, kind: null }]) const clampSegs = splitLineByTokens('ab', [{ start: -5, end: 99, kind: 'kw' }]) assert.equal(clampSegs.map(s => 'ab'.slice(s.start, s.end)).join(''), 'ab') // 41. buildHunkPatch: cut one hunk with the file header from a raw unified // diff as a standalone `git apply` patch (per-hunk stage/unstage/revert). const RAW_DIFF = [ 'diff --git a/app.ts b/app.ts', 'index 1111111..2222222 100644', '--- a/app.ts', '+++ b/app.ts', '@@ -1,3 +1,3 @@ const a', '-old one', '+new one', ' context', ' still', '@@ -20,3 +20,4 @@ fn b', ' tail', '+added tail', ' end', '\\ No newline at end of file', ].join('\n') const hunk0 = buildHunkPatch(RAW_DIFF, 0) assert.equal(hunk0, [ 'diff --git a/app.ts b/app.ts', 'index 1111111..2222222 100644', '--- a/app.ts', '+++ b/app.ts', '@@ -1,3 +1,3 @@ const a', '-old one', '+new one', ' context', ' still', '', ].join('\n')) const hunk1 = buildHunkPatch(RAW_DIFF, 1) assert.ok(hunk1.startsWith('diff --git a/app.ts b/app.ts\nindex 1111111..2222222 100644\n--- a/app.ts\n+++ b/app.ts\n@@ -20,3 +20,4 @@ fn b\n')) assert.ok(hunk1.endsWith('+added tail\n end\n\\ No newline at end of file\n')) assert.equal(buildHunkPatch(RAW_DIFF, 2), null) assert.equal(buildHunkPatch(RAW_DIFF, -1), null) assert.equal(buildHunkPatch('', 0), null) assert.equal(buildHunkPatch('diff --git a/x b/x\nBinary files a/x and b/x differ\n', 0), null) // 42. parseBlamePorcelain: header/first-occurrence metadata/repeat-commit // cache/tab-content record ends; the trailing truncated record still // yields its row. const BLAME_RAW = [ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 3 1 3', 'author Alice', 'author-mail ', 'author-time 1700000000', 'author-tz +0800', 'committer Alice', 'committer-time 1700000000', 'summary add header', '\tpublic class X {', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 4 2', '\tint y;', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb 1 3', 'author Bob', 'author-time 1700001000', 'summary bob line', '\t// bob was here', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 5 4', '\t}', ].join('\n') const blameRows = parseBlamePorcelain(BLAME_RAW) assert.equal(blameRows.length, 4) assert.deepEqual(blameRows.map(row => row.hash.slice(0, 1)), ['a', 'a', 'b', 'a']) assert.deepEqual(blameRows.map(row => row.finalLine), [1, 2, 3, 4]) assert.deepEqual(blameRows.map(row => row.origLine), [3, 4, 1, 5]) assert.equal(blameRows[0].author, 'Alice') assert.equal(blameRows[1].author, 'Alice', 'repeat commit fills from cache') assert.equal(blameRows[2].author, 'Bob') assert.equal(blameRows[2].summary, 'bob line') assert.equal(blameRows[0].timestamp, 1700000000) const blameTrunc = parseBlamePorcelain('cccccccccccccccccccccccccccccccccccccccc 2 9') assert.equal(blameTrunc.length, 1) assert.equal(blameTrunc[0].author, '') // 43. Word highlight semantic cleanup (google/diff-match-patch // Diff_cleanupSemantic): a trivial equality — no longer than the edits on // BOTH sides of it — dissolves into the surrounding change instead of // shredding the row into single-letter spans (the "letter salad" // regression: unrelated lines matched char-by-char into 17/14 spans). const saladWords = makeWordHighlighter() const dissolved = saladWords.pair({ kind: 'pair', left: { no: 1, text: 'axbXc' }, right: { no: 1, text: 'aybYc' }, }) assert.ok(dissolved !== null) assert.deepEqual(dissolved.old, [[1, 4]], '1-char island between 1-char edits dissolves') assert.deepEqual(dissolved.new, [[1, 4]]) // A longer island survives single-char edits on both sides. const island = saladWords.pair({ kind: 'pair', left: { no: 2, text: 'pXabYq' }, right: { no: 2, text: 'pZabWq' }, }) assert.deepEqual(island.old, [[1, 2], [4, 5]]) assert.deepEqual(island.new, [[1, 2], [4, 5]]) // Leading/trailing equalities are never dissolved (interior rule only). const edges = saladWords.pair({ kind: 'pair', left: { no: 3, text: 'fooXbar' }, right: { no: 3, text: 'fooYbar' }, }) assert.deepEqual(edges.old, [[3, 4]]) assert.deepEqual(edges.new, [[3, 4]]) // The screenshot pair: two unrelated lines must render as a few big spans, // and no interior equality may survive that the rule would dissolve. const rewrite = saladWords.pair({ kind: 'pair', left: { no: 4, text: 'const attempt = (range: string): Promise => runGit(repoRoot,' }, right: { no: 4, text: '// J9-2: a single file is diff is bounded by DIFF_CAP after the fact' }, }) assert.ok(rewrite !== null) assert.ok(rewrite.old.length <= 5, 'rewrite renders as big spans, not salad (was 17): ' + rewrite.old.length) assert.ok(rewrite.new.length <= 5, 'rewrite renders as big spans, not salad (was 14): ' + rewrite.new.length) for (const [text, spans] of [ ['const attempt = (range: string): Promise => runGit(repoRoot,', rewrite.old], ['// J9-2: a single file is diff is bounded by DIFF_CAP after the fact', rewrite.new], ]) { for (let s = 1; s < spans.length; s++) { const gap = spans[s][0] - spans[s - 1][1] const left = spans[s - 1][1] - spans[s - 1][0] const right = spans[s][1] - spans[s][0] assert.ok(gap > left || gap > right, `trivial equality survives in ${JSON.stringify(text)}`) } } // 44. sniffPreviewMime: magic-byte preview detection (the file-bytes // endpoint trusts magic, never the extension). Strict prefix lengths — // a truncated signature is null, not a guess. const pngMagic = new Uint8Array([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00]) assert.equal(sniffPreviewMime(pngMagic), 'image/png') assert.equal(sniffPreviewMime(new Uint8Array([0x89, 0x50, 0x4E])), null, 'truncated png signature') assert.equal(sniffPreviewMime(new Uint8Array([0xFF, 0xD8, 0xFF, 0xE0, 0x00])), 'image/jpeg') assert.equal(sniffPreviewMime(new TextEncoder().encode('GIF89a\x01\x00')), 'image/gif') assert.equal(sniffPreviewMime(new TextEncoder().encode('GIF87a\x01\x00')), 'image/gif') assert.equal(sniffPreviewMime(new TextEncoder().encode('RIFF\x24\x00\x00\x00WEBPVP8 ')), 'image/webp') assert.equal(sniffPreviewMime(new TextEncoder().encode('BM\x36\x00\x00\x00')), 'image/bmp') assert.equal(sniffPreviewMime(new TextEncoder().encode('\x00\x00\x00\x20ftypavif\x00')), 'image/avif') assert.equal(sniffPreviewMime(new TextEncoder().encode('%PDF-1.7\n%âã')), 'application/pdf') assert.equal(sniffPreviewMime(new TextEncoder().encode('')), 'image/svg+xml') assert.equal(sniffPreviewMime(new TextEncoder().encode(' \n')), 'image/svg+xml') assert.equal(sniffPreviewMime(new TextEncoder().encode('')), null, 'NUL is never svg') assert.equal(sniffPreviewMime(new TextEncoder().encode('hello, world')), null) assert.equal(sniffPreviewMime(new Uint8Array(0)), null) assert.equal(sniffPreviewMime(new Uint8Array([0x00, 0x01, 0x02])), null) assert.equal(sniffPreviewMime(new Uint8Array([0x00, 0x00, 0x01, 0x00, 0x01])), 'image/x-icon') assert.equal(sniffPreviewMime(new Uint8Array([0x00, 0x00, 0x02])), null, 'truncated ico signature') // 45. previewKindForPath: extension gate for the in-tab preview (the server // mime wins on conflict; unknown extensions stay on the source view). assert.equal(previewKindForPath('README.md'), 'markdown') assert.equal(previewKindForPath('docs/Guide.MARKDOWN'), 'markdown') assert.equal(previewKindForPath('assets/logo.png'), 'image') assert.equal(previewKindForPath('shot.JPG'), 'image') assert.equal(previewKindForPath('fig.svg'), 'image') assert.equal(previewKindForPath('paper.pdf'), 'pdf') assert.equal(previewKindForPath('page.html'), 'html') assert.equal(previewKindForPath('docs/UPPER.HTM'), 'html') assert.equal(previewKindForPath('src/index.ts'), null) assert.equal(previewKindForPath('notes.mkd'), 'markdown') assert.equal(previewKindForPath('icon.ICO'), 'image') assert.equal(previewKindForPath('archive.zip'), null) assert.equal(previewKindForPath('Makefile'), null) // 46. file-type coverage: logo-less code still highlights (vue -> c, // sql -> its own family with -- comments), so the tree + source view // stay useful for the common types without brand logos. assert.equal(langOf('app.vue'), 'c') assert.equal(langOf('query.sql'), 'sql') assert.deepEqual(tokenizeLine('select * from t -- hi', 'sql')[0], { start: 0, end: 6, kind: 'kw' }) assert.equal(tokenizeLine('-- only a comment', 'sql')[0].kind, 'com') // 47. md-preview: safe-HTML fallback + relative-asset collect/rewrite/resolve. assert.equal( htmlFallbackForPreview('

demo

'), '\n\n![demo](a.svg)\n\n', ) assert.equal(htmlFallbackForPreview('English | 中文'), '[English](README.md) | 中文') assert.equal(htmlFallbackForPreview('# Title\n\nplain **md** stays'), '# Title\n\nplain **md** stays') assert.equal(htmlFallbackForPreview('no-src'), '') assert.equal(htmlFallbackForPreview(' demo'), '![demo](a.svg)') assert.equal(htmlFallbackForPreview(' EN | 中'), '[EN](R.md) | 中') assert.equal(htmlFallbackForPreview("demo"), '![demo](a.svg)') assert.equal(htmlFallbackForPreview("EN"), '[EN](R.md)') assert.deepEqual(collectMdAssets('![a](docs/x.svg)\n![b](https://e.com/y.png)\n![c][id]\n\n[id]: assets/z.png\n\n[unused]: q.png'), ['docs/x.svg', 'https://e.com/y.png', 'assets/z.png']) assert.equal( rewriteMdAssets('![a](docs/x.svg "t") and ![c][id]\n\n[id]: assets/z.png', new Map([['docs/x.svg', 'DATA:X'], ['assets/z.png', 'DATA:Z']])), '![a](DATA:X "t") and ![c][id]\n\n[id]: DATA:Z', ) assert.equal(rewriteMdAssets('![a](https://e.com/y.png)', new Map()), '![a](https://e.com/y.png)') assert.equal(resolveMdAsset('README.md', 'docs/demo.svg'), 'docs/demo.svg') assert.equal(resolveMdAsset('docs/sub/note.md', '../img.png'), 'docs/img.png') assert.equal(resolveMdAsset('docs/note.md', '/assets/a.png'), 'assets/a.png') assert.equal(resolveMdAsset('docs/note.md', 'a.png?v=2#x'), 'docs/a.png') assert.equal(resolveMdAsset('README.md', 'https://e.com/y.png'), null) assert.equal(resolveMdAsset('README.md', 'data:image/png;base64,xx'), null) assert.equal(resolveMdAsset('README.md', '#frag'), null) assert.equal(resolveMdAsset('docs/note.md', '../../escape.png'), null) assert.equal(resolveMdAsset('README.md', ''), null) // 48. Header quoting: quoted fields keep inner spaces (git never quotes // space-padded names), C-quoted escapes decode at the byte level. assert.equal(unquoteHeaderPath('a/ leadtrail\t'), 'a/ leadtrail') assert.equal(unquoteHeaderPath('"a/ leadtrail "'), 'a/ leadtrail ') assert.equal(unquoteHeaderPath('"a/we\\"ird"'), 'a/we"ird') assert.equal(unquoteHeaderPath('"a/x\\303\\251"'), 'a/x\u00e9') assert.equal(unquoteHeaderPath('/dev/null'), '/dev/null') const spacedDiff = parseUnifiedDiff('--- "a/ leadtrail "\n+++ "b/ leadtrail "\n@@ -1 +1 @@\n-x\n+y\n') assert.equal(spacedDiff.oldPath, ' leadtrail ') assert.equal(spacedDiff.newPath, ' leadtrail ') assert.equal(spacedDiff.hunks[0].damaged, false) // 49. Hunk validation: short bodies flag damaged; multi-file raws refuse. const shortDiff = parseUnifiedDiff('--- a/f\n+++ b/f\n@@ -1,3 +1,3 @@\n-a\n+b\n') assert.equal(shortDiff.hunks[0].damaged, true) const multiRaw = 'diff --git a/a b/a\n--- a/a\n+++ b/a\n@@ -1 +1 @@\n-x\n+y\n' + 'diff --git a/c b/c\n--- a/c\n+++ b/c\n@@ -1 +1 @@\n-x\n+y\n' assert.equal(buildHunkPatch(multiRaw, 1), null) // Stray context outside any hunk is ignored, never a crash. parseUnifiedDiff('--- a/f\n+++ b/f\n stray ctx\n') // 50. Client regex guard: nested quantifiers degrade to literal, fast. const evilEngine = makeSearchEngine({ query: '(a+)+$', caseSensitive: false, regex: true }) assert.equal(evilEngine.count('a'.repeat(50000)), 0) // 51. Single-line block comments color; line comments still win. assert.ok(tokenizeLine('const x = /* hi */ 1;', 'c').some(t => t.kind === 'com')) assert.deepEqual(tokenizeLine('// /* not a block */', 'c').map(t => t.kind), ['com']) // 52. Remote images defang to click-to-load links; local URLs pass through. assert.equal(defangRemoteImages('![a](https://e.com/y.png)'), '[a](https://e.com/y.png "external image")') assert.equal(defangRemoteImages('![a](docs/x.svg)'), '![a](docs/x.svg)') assert.equal(defangRemoteImages('![a][id]\n\n[id]: https://e.com/y.png'), '[a][id]\n\n[id]: https://e.com/y.png') // 52b. Collapsed reference `![alt][]`: its id IS the alt text, so the asset is // collected and a remote definition defangs like the named form. assert.deepEqual(collectMdAssets('![shot][]\n\n[shot]: docs/a.png'), ['docs/a.png']) assert.deepEqual(collectMdAssets('![a][b]\n\n[b]: docs/b.png'), ['docs/b.png']) assert.equal(defangRemoteImages('![shot][]\n\n[shot]: https://e.com/y.png'), '[shot][]\n\n[shot]: https://e.com/y.png') assert.equal(defangRemoteImages('![a][b]\n\n[b]: docs/x.svg'), '![a][b]\n\n[b]: docs/x.svg') assert.equal(htmlFallbackForPreview('x'), 'x') assert.equal(htmlFallbackForPreview('x'), '[x](https://e.com)') // 53. Range guard: ancestry walks, name resolution, branch tips. const HA = 'a'.repeat(40) const HB = 'b'.repeat(40) const HC = 'c'.repeat(40) const HX = 'd'.repeat(40) const chainCommits = [ { hash: HC, parents: [HB], refs: [] }, { hash: HB, parents: [HA], refs: [{ name: 'main' }] }, { hash: HA, parents: [], refs: [] }, ] const chainParents = new Map(chainCommits.map(c => [c.hash, c.parents])) assert.equal(isAncestorOrSelf(chainParents, HA, HC), true) assert.equal(isAncestorOrSelf(chainParents, HC, HA), false) assert.equal(isAncestorOrSelf(chainParents, HB, HB), true) assert.equal(isAncestorOrSelf(chainParents, HX, HC), false) assert.equal(isAncestorOrSelf(chainParents, HA, 'e'.repeat(40)), false) assert.equal(resolveRangeHash('main', chainCommits, null), HB) assert.equal(resolveRangeHash('HEAD', chainCommits, HC), HC) assert.equal(resolveRangeHash(HC, chainCommits, null), HC) assert.equal(resolveRangeHash('nope', chainCommits, null), null) assert.equal(resolveRangeHash(null, chainCommits, HC), null) assert.equal(findBranchTip(chainCommits, 'main'), HB) assert.equal(findBranchTip(chainCommits, null), null) assert.equal(findBranchTip(chainCommits, 'ghost'), null) // 54. Image-diff sides: each scope reads the right byte source — the base of // a staged edit is HEAD, the base of an unstaged edit is the index blob, // an added file has no base at all, and a rename reads the old path on // the base side. const worktreeInput = (extra) => ({ mode: 'worktree', scope: 'all', baseRef: null, targetRef: null, path: 'a.png', ...extra }) let sides = resolveImageSides(worktreeInput({ x: 'M', y: ' ' })) assert.deepEqual(sides, { before: { side: { kind: 'ref', ref: 'HEAD' }, path: 'a.png' }, after: { side: { kind: 'worktree' }, path: 'a.png' }, comparable: true, }) // Staged half: the index blob against HEAD. sides = resolveImageSides(worktreeInput({ scope: 'staged', x: 'M', y: ' ' })) assert.deepEqual(sides.before.side, { kind: 'ref', ref: 'HEAD' }) assert.deepEqual(sides.after.side, { kind: 'index' }) // Unstaged half: the worktree against the staged blob. sides = resolveImageSides(worktreeInput({ scope: 'unstaged', x: 'M', y: 'M' })) assert.deepEqual(sides.before.side, { kind: 'index' }) assert.deepEqual(sides.after.side, { kind: 'worktree' }) // A base override replaces HEAD on the before side only. assert.deepEqual(resolveImageSides(worktreeInput({ baseRef: 'dev', x: 'M', y: ' ' })).before.side, { kind: 'ref', ref: 'dev' }) // Untracked: neither HEAD nor the index carries it — the before side is empty. sides = resolveImageSides(worktreeInput({ x: '?', y: '?', untracked: true })) assert.deepEqual(sides.before.side, { kind: 'empty' }) assert.deepEqual(sides.after.side, { kind: 'worktree' }) assert.equal(sides.comparable, false) sides = resolveImageSides(worktreeInput({ scope: 'unstaged', x: '?', y: '?', untracked: true })) assert.deepEqual(sides.before.side, { kind: 'empty' }, 'an untracked file has no staged copy to compare against') // A staged addition: HEAD never had the file. sides = resolveImageSides(worktreeInput({ scope: 'staged', x: 'A', y: ' ' })) assert.deepEqual(sides.before.side, { kind: 'empty' }) assert.deepEqual(sides.after.side, { kind: 'index' }) // A worktree deletion leaves nothing on the after side. sides = resolveImageSides(worktreeInput({ x: 'M', y: 'D' })) assert.deepEqual(sides.before.side, { kind: 'ref', ref: 'HEAD' }) assert.deepEqual(sides.after.side, { kind: 'empty' }) assert.equal(sides.comparable, false) // A staged deletion has no index blob to read. assert.deepEqual(resolveImageSides(worktreeInput({ scope: 'staged', x: 'D', y: 'D' })).after.side, { kind: 'empty' }) // A rename reads the old path on the base side, the new one on the target. sides = resolveImageSides(worktreeInput({ x: 'R', y: ' ', path: 'new.png', origPath: 'old.png' })) assert.equal(sides.before.path, 'old.png') assert.equal(sides.after.path, 'new.png') // Refs mode: both ends are the picked refs. sides = resolveImageSides({ mode: 'refs', scope: 'all', baseRef: 'main', targetRef: 'dev', path: 'a.png' }) assert.deepEqual(sides.before.side, { kind: 'ref', ref: 'main' }) assert.deepEqual(sides.after.side, { kind: 'ref', ref: 'dev' }) assert.equal(sides.comparable, true) // An unset end compares against nothing (the picker's guard state). sides = resolveImageSides({ mode: 'refs', scope: 'all', baseRef: null, targetRef: 'dev', path: 'a.png' }) assert.deepEqual(sides.before.side, { kind: 'empty' }) assert.equal(sides.comparable, false) // Graph mode: parent0 against the commit; a root commit has no parent. sides = resolveImageSides({ mode: 'graph', scope: 'all', baseRef: HA, targetRef: HB, path: 'a.png' }) assert.deepEqual(sides.before.side, { kind: 'ref', ref: HA }) assert.deepEqual(sides.after.side, { kind: 'ref', ref: HB }) sides = resolveImageSides({ mode: 'graph', scope: 'all', baseRef: null, targetRef: HB, path: 'a.png' }) assert.deepEqual(sides.before.side, { kind: 'empty' }) assert.equal(sides.comparable, false) // 55. Image sides, rename x scope: only a REF keeps the pre-rename name, so // the unstaged half (index vs worktree) reads the current path on BOTH // ends — the index has no `old.png` to serve, and answering `missing` // there would hide a real comparison. sides = resolveImageSides({ mode: 'worktree', scope: 'all', baseRef: null, targetRef: null, x: 'R', y: ' ', path: 'new.png', origPath: 'old.png' }) assert.equal(sides.before.path, 'old.png') assert.equal(sides.after.path, 'new.png') sides = resolveImageSides({ mode: 'worktree', scope: 'staged', baseRef: null, targetRef: null, x: 'R', y: ' ', path: 'new.png', origPath: 'old.png' }) assert.equal(sides.before.path, 'old.png', 'the staged half still reads the old name from the base ref') assert.equal(sides.after.path, 'new.png') sides = resolveImageSides({ mode: 'worktree', scope: 'unstaged', baseRef: null, targetRef: null, x: 'R', y: 'M', path: 'new.png', origPath: 'old.png' }) assert.equal(sides.before.path, 'new.png', 'the index end follows the current path after a rename') assert.equal(sides.after.path, 'new.png') // 56. SVG prolog: exporters emit an XML declaration, a DOCTYPE and comments // before the root element — the sniff walks past all of them, while still // refusing a plain HTML document (the security posture is unchanged). const sniff = (text) => sniffPreviewMime(new TextEncoder().encode(text)) assert.equal(sniff(''), 'image/svg+xml') assert.equal(sniff('\n'), 'image/svg+xml') assert.equal(sniff('\n'), 'image/svg+xml') assert.equal(sniff('\n'), 'image/svg+xml') assert.equal(sniff('\n\n\n'), 'image/svg+xml') assert.equal(sniff('