Skip to content

Commit 13f7247

Browse files
Chrisclaude
andcommitted
feat: text-diff-patch — Myers line diff, unified-diff hunks, fuzzy apply with reject reporting, word-level highlighting
Co-Authored-By: Claude <noreply@anthropic.com>
0 parents  commit 13f7247

12 files changed

Lines changed: 617 additions & 0 deletions

File tree

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
node_modules/
2+
dist/

‎LICENSE‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2026 Ruzylo-cloud
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

‎README.md‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# text-diff-patch
2+
3+
Zero-dependency line-based diff and patch for TypeScript/JavaScript: Myers
4+
O(ND) diff producing unified-diff-style hunks, fuzzy patch application with
5+
reject reporting, and a word-level intra-line diff highlighter.
6+
7+
## Why
8+
9+
Most diff libraries either only diff or only apply, and few report *why* a
10+
hunk failed to apply against a shifted file. This package does both
11+
directions with zero runtime dependencies, strict TypeScript, and an
12+
explicit `fuzz` tolerance for applying patches against slightly-moved text —
13+
the case agents hit constantly when re-applying an edit to a file that
14+
changed underneath them.
15+
16+
## Install
17+
18+
```bash
19+
npm install text-diff-patch
20+
```
21+
22+
## Quickstart
23+
24+
```ts
25+
import { createPatch, applyPatch, highlightWordDiff } from "text-diff-patch";
26+
27+
const patch = createPatch(oldText, newText, { oldFile: "a", newFile: "b" });
28+
console.log(patch); // unified-diff-style string
29+
30+
const { result, applied, rejects } = applyPatch(oldText, patch, { fuzz: 3 });
31+
// applied: number of hunks applied; rejects: hunks that couldn't be placed
32+
33+
highlightWordDiff("hello world", "hello there");
34+
// "hello {-world-}{+there+}"
35+
```
36+
37+
## API
38+
39+
### `myersDiff(a: string[], b: string[]): DiffOp[]`
40+
Raw Myers O(ND) line-array diff. `DiffOp = { type: "equal"|"delete"|"insert", value: string }`.
41+
42+
### `toLines(text: string): string[]`
43+
Splits text into lines (`""` → `[]`).
44+
45+
### `buildHunks(ops: DiffOp[], context = 3): Hunk[]`
46+
Groups a `DiffOp[]` into unified-diff hunks with `context` lines of
47+
surrounding unchanged text; adjacent changes within `2 * context` lines
48+
merge into one hunk.
49+
50+
### `createPatch(oldText: string, newText: string, options?: CreatePatchOptions): string`
51+
Full unified-diff text. `CreatePatchOptions = { context?: number; oldFile?: string; newFile?: string }`.
52+
53+
### `parsePatch(patchText: string): Hunk[]`
54+
Parses a unified-diff string back into `Hunk[]` (`{ oldStart, oldLines, newStart, newLines, lines }`).
55+
56+
### `applyPatch(text: string, patch: string | Hunk[], options?: ApplyOptions): ApplyResult`
57+
Applies hunks to `text`. `ApplyOptions = { fuzz?: number }` — with `fuzz > 0`,
58+
a hunk whose exact recorded line is off is retried at nearby offsets
59+
(±1..±fuzz) before being rejected.
60+
`ApplyResult = { result: string; applied: number; rejects: RejectedHunk[] }`,
61+
`RejectedHunk = { hunk: Hunk; reason: string }`.
62+
63+
### `tokenizeWords(line: string): string[]`
64+
Splits a line into word/whitespace tokens, exactly reconstructible via `join("")`.
65+
66+
### `diffWords(a: string, b: string): DiffOp[]`
67+
Word-level Myers diff over tokenized lines.
68+
69+
### `highlightWordDiff(a: string, b: string, options?: HighlightOptions): string`
70+
Renders a word-diff as one string with insertions/deletions wrapped in
71+
markers. `HighlightOptions = { insertOpen?, insertClose?, deleteOpen?, deleteClose? }`
72+
(defaults: `{+...+}` / `{-...-}`).
73+
74+
## Limits
75+
76+
- Line-based only — `myersDiff`/`createPatch` operate on `\n`-split lines,
77+
not characters (use `diffWords` for intra-line detail).
78+
- `applyPatch`'s fuzz search is a bounded ±N-line offset retry per hunk, not
79+
a general approximate-matching algorithm — very large shifts or heavily
80+
edited context will still reject.
81+
- No binary-file support; input is always treated as text.
82+
- `parsePatch` expects hunk bodies to use exactly one leading `' '`/`'+'`/`'-'`
83+
per line (standard unified-diff shape) — it does not tolerate tab-indented
84+
or CRLF-mixed patches.
85+
86+
---
87+
Part of the [ferrow-toolkit](https://github.com/Ruzylo-cloud/ferrow-toolkit) collection · Sponsored by [Ferrow](https://ferrow.ai)

‎examples/demo.js‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
const { createPatch, applyPatch, highlightWordDiff } = require("../dist/index.js");
2+
3+
const oldText = [
4+
"function greet(name) {",
5+
" console.log('Hello, ' + name);",
6+
"}",
7+
"",
8+
"greet('world');",
9+
].join("\n");
10+
11+
const newText = [
12+
"function greet(name) {",
13+
" console.log(`Hello, ${name}!`);",
14+
"}",
15+
"",
16+
"greet('world');",
17+
"greet('agent');",
18+
].join("\n");
19+
20+
const patch = createPatch(oldText, newText, { oldFile: "greet.js (old)", newFile: "greet.js (new)" });
21+
console.log("=== unified diff ===");
22+
console.log(patch);
23+
24+
// Apply cleanly.
25+
const clean = applyPatch(oldText, patch);
26+
console.log("clean apply -> applied:", clean.applied, "rejects:", clean.rejects.length);
27+
console.log("matches newText:", clean.result === newText);
28+
29+
// Apply to a shifted base: same content but with two extra leading lines,
30+
// so every hunk's recorded line number is off by 2. fuzz=3 should still find it.
31+
const shiftedBase = "// header comment\n// another header\n" + oldText;
32+
const shifted = applyPatch(shiftedBase, patch, { fuzz: 3 });
33+
console.log("\nshifted-base apply (fuzz=3) -> applied:", shifted.applied, "rejects:", shifted.rejects.length);
34+
35+
// Apply to unrelated content -> clean reject.
36+
const unrelatedBase = "totally\nunrelated\ncontent\nhere\n";
37+
const rejected = applyPatch(unrelatedBase, patch, { fuzz: 2 });
38+
console.log("\nunrelated-base apply (fuzz=2) -> applied:", rejected.applied, "rejects:", rejected.rejects.length);
39+
if (rejected.rejects.length > 0) {
40+
console.log("reject reason:", rejected.rejects[0].reason);
41+
}
42+
43+
console.log("\nword-level highlight:");
44+
console.log(highlightWordDiff(" console.log('Hello, ' + name);", " console.log(`Hello, ${name}!`);"));

‎llms.txt‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# text-diff-patch
2+
3+
> Zero-dependency Myers line diff producing unified-diff hunks, with fuzzy patch application, reject reporting, and word-level highlighting.
4+
5+
text-diff-patch computes an O(ND) Myers diff between two texts, formats it as
6+
unified-diff hunks, and can apply those hunks back to a (possibly slightly
7+
shifted) base text — reporting exactly which hunks couldn't be placed rather
8+
than throwing. It also exposes a word-level diff for intra-line highlighting.
9+
Built for agents that generate, store, and re-apply edits against files that
10+
may have drifted since the diff was made.
11+
12+
## API
13+
14+
- `myersDiff(a: string[], b: string[]): DiffOp[]` — `DiffOp = { type: "equal"|"delete"|"insert", value: string }`.
15+
- `toLines(text: string): string[]`
16+
- `buildHunks(ops: DiffOp[], context?: number): Hunk[]` — `Hunk = { oldStart, oldLines, newStart, newLines, lines: string[] }`.
17+
- `createPatch(oldText: string, newText: string, options?: { context?: number; oldFile?: string; newFile?: string }): string`
18+
- `parsePatch(patchText: string): Hunk[]`
19+
- `applyPatch(text: string, patch: string | Hunk[], options?: { fuzz?: number }): { result: string; applied: number; rejects: RejectedHunk[] }` — `RejectedHunk = { hunk: Hunk; reason: string }`.
20+
- `tokenizeWords(line: string): string[]`
21+
- `diffWords(a: string, b: string): DiffOp[]`
22+
- `highlightWordDiff(a: string, b: string, options?: { insertOpen?; insertClose?; deleteOpen?; deleteClose? }): string`
23+
24+
## Install
25+
26+
```bash
27+
npm install text-diff-patch
28+
```
29+
30+
Part of the Ferrow open-source toolkit: https://github.com/Ruzylo-cloud/ferrow-toolkit — sponsored by https://ferrow.ai

‎package.json‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
{
2+
"name": "text-diff-patch",
3+
"version": "1.0.0",
4+
"description": "Zero-dependency line-based Myers diff (O(ND)) producing unified-diff hunks, with fuzzy patch application, reject reporting, and word-level intra-line diff highlighting.",
5+
"main": "dist/index.js",
6+
"types": "dist/index.d.ts",
7+
"files": [
8+
"dist",
9+
"llms.txt"
10+
],
11+
"scripts": {
12+
"build": "tsc -p tsconfig.json",
13+
"prepublishOnly": "npm run build"
14+
},
15+
"keywords": [
16+
"diff",
17+
"patch",
18+
"myers-diff",
19+
"unified-diff",
20+
"text-diff",
21+
"word-diff",
22+
"apply-patch",
23+
"agent-tools"
24+
],
25+
"author": "Ruzylo-cloud",
26+
"license": "MIT",
27+
"engines": {
28+
"node": ">=18"
29+
},
30+
"devDependencies": {
31+
"typescript": "^5.0.0"
32+
}
33+
}

‎src/apply.ts‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import { Hunk, parsePatch } from "./hunks";
2+
import { toLines } from "./myers";
3+
4+
export interface RejectedHunk {
5+
hunk: Hunk;
6+
reason: string;
7+
}
8+
9+
export interface ApplyOptions {
10+
/** Search this many lines above/below the hunk's recorded position for a context match. Default 0. */
11+
fuzz?: number;
12+
}
13+
14+
export interface ApplyResult {
15+
result: string;
16+
applied: number;
17+
rejects: RejectedHunk[];
18+
}
19+
20+
function arraysEqual(a: string[], b: string[]): boolean {
21+
if (a.length !== b.length) return false;
22+
for (let i = 0; i < a.length; i++) {
23+
if (a[i] !== b[i]) return false;
24+
}
25+
return true;
26+
}
27+
28+
function oldSideLines(hunk: Hunk): string[] {
29+
return hunk.lines
30+
.filter((l) => l[0] === " " || l[0] === "-")
31+
.map((l) => l.slice(1));
32+
}
33+
34+
function newSideLines(hunk: Hunk): string[] {
35+
return hunk.lines
36+
.filter((l) => l[0] === " " || l[0] === "+")
37+
.map((l) => l.slice(1));
38+
}
39+
40+
/**
41+
* Applies a unified-diff patch (string or already-parsed hunks) to `text`.
42+
* With `fuzz > 0`, a hunk whose exact recorded position doesn't match the
43+
* target is retried at nearby offsets (±1..±fuzz lines) before being
44+
* rejected. Hunks that can't be placed within the fuzz window are reported
45+
* in `rejects` rather than throwing.
46+
*/
47+
export function applyPatch(
48+
text: string,
49+
patch: string | Hunk[],
50+
options: ApplyOptions = {}
51+
): ApplyResult {
52+
const fuzz = options.fuzz ?? 0;
53+
const hunks = typeof patch === "string" ? parsePatch(patch) : patch;
54+
55+
let lines = toLines(text);
56+
let offset = 0;
57+
const rejects: RejectedHunk[] = [];
58+
let applied = 0;
59+
60+
for (const hunk of hunks) {
61+
const oldSide = oldSideLines(hunk);
62+
const newSide = newSideLines(hunk);
63+
const base = hunk.oldStart - 1 + offset;
64+
65+
let pos = -1;
66+
if (base >= 0 && base + oldSide.length <= lines.length && arraysEqual(lines.slice(base, base + oldSide.length), oldSide)) {
67+
pos = base;
68+
} else {
69+
for (let d = 1; d <= fuzz && pos === -1; d++) {
70+
for (const cand of [base - d, base + d]) {
71+
if (cand < 0 || cand + oldSide.length > lines.length) continue;
72+
if (arraysEqual(lines.slice(cand, cand + oldSide.length), oldSide)) {
73+
pos = cand;
74+
break;
75+
}
76+
}
77+
}
78+
}
79+
80+
if (pos === -1) {
81+
rejects.push({
82+
hunk,
83+
reason: `context mismatch: expected near line ${hunk.oldStart}${
84+
fuzz > 0 ? ` (searched ±${fuzz})` : ""
85+
}`,
86+
});
87+
continue;
88+
}
89+
90+
lines = lines.slice(0, pos).concat(newSide, lines.slice(pos + oldSide.length));
91+
offset += newSide.length - oldSide.length;
92+
applied++;
93+
}
94+
95+
return { result: lines.join("\n"), applied, rejects };
96+
}

0 commit comments

Comments
 (0)