### Build and Test jsdiff with Yarn Source: https://github.com/kpdecker/jsdiff/blob/master/CONTRIBUTING.md Standard commands to install dependencies and run tests for the jsdiff project using Yarn. Assumes Yarn is installed and configured. ```shell yarn yarn test ``` -------------------------------- ### Run jsdiff Tests in a Browser with Karma Source: https://github.com/kpdecker/jsdiff/blob/master/CONTRIBUTING.md Instructions to start Karma test runner for browser-based testing of jsdiff. Requires Karma to be installed. Tests are initiated by opening localhost:9876 in the desired browser. ```shell yarn karma start ``` -------------------------------- ### Install jsdiff using npm Source: https://github.com/kpdecker/jsdiff/blob/master/README.md This command installs the jsdiff library as a project dependency using npm. ```bash npm install diff --save ``` -------------------------------- ### Release jsdiff with Yarn Source: https://github.com/kpdecker/jsdiff/blob/master/CONTRIBUTING.md Commands to perform a full release of the jsdiff library. This includes cleaning previous builds, creating a new production build, and publishing the package. Assumes Yarn is installed. ```shell yarn clean yarn build yarn publish ``` -------------------------------- ### Apply Multi-File Patch in Node.js using jsdiff Source: https://github.com/kpdecker/jsdiff/blob/master/README.md This Node.js example shows how to apply a multi-file patch, similar to the Unix `patch < mydiff.patch` command. It uses the `applyPatches` function, which requires callback functions for loading files (`loadFile`) and handling patched content (`patched`). It also includes a `complete` callback for error handling. ```javascript const {applyPatches} = require('diff'); const patch = fs.readFileSync("mydiff.patch").toString(); applyPatches(patch, { loadFile: (patch, callback) => { let fileContents; try { fileContents = fs.readFileSync(patch.oldFileName).toString(); } catch (e) { callback(`No such file: ${patch.oldFileName}`); return; } callback(undefined, fileContents); }, patched: (patch, patchedContent, callback) => { if (patchedContent === false) { callback(`Failed to apply patch to ${patch.oldFileName}`) return; } fs.writeFileSync(patch.oldFileName, patchedContent); callback(); }, complete: (err) => { if (err) { console.log("Failed with error:", err); } } }); ``` -------------------------------- ### Timeout and MaxEditLength for Large Diffs in Node.js Source: https://context7.com/kpdecker/jsdiff/llms.txt Illustrates how to prevent excessive computation on large or significantly different texts by setting timeout and maxEditLength limits. It shows examples of handling diffs that time out or exceed the maximum edit length, including combining these with async callbacks. ```javascript const {diffLines} = require('diff'); const hugeFile1 = 'Line 1\n'.repeat(100000); const hugeFile2 = 'Different\n'.repeat(100000); // Set timeout to 5 seconds const result1 = diffLines(hugeFile1, hugeFile2, { timeout: 5000 // milliseconds }); if (result1 === undefined) { console.log('Diff timed out'); } // Set maximum edit distance const result2 = diffLines(hugeFile1, hugeFile2, { maxEditLength: 10000 // maximum number of edits to consider }); if (result2 === undefined) { console.log('Diff exceeded maximum edit length'); } // Combine with async for non-blocking operation diffLines(hugeFile1, hugeFile2, { timeout: 5000, maxEditLength: 10000, callback: (changes) => { if (changes === undefined) { console.log('Diff aborted due to timeout or max length'); } else { console.log('Diff completed:', changes.length, 'blocks'); } } }); ``` -------------------------------- ### Basic Character Diffing in Web Page using jsdiff Source: https://github.com/kpdecker/jsdiff/blob/master/README.md This example demonstrates how to use jsdiff to compare two strings and display the differences in a web page. It iterates through the diff array, coloring added characters green, removed characters red, and common characters grey. It requires the 'diff.js' script to be included. ```html



```

--------------------------------

### Generate Patch from Node.js using jsdiff

Source: https://github.com/kpdecker/jsdiff/blob/master/README.md

This Node.js example shows how to generate a diff patch between two files, similar to the Unix `diff -u` command. It utilizes the `createTwoFilesPatch` function from the 'diff' module and requires Node.js built-in 'fs' module for file operations. The output is saved to a '.patch' file.

```javascript
const {createTwoFilesPatch} = require('diff');
const file1Contents = fs.readFileSync("file1.txt").toString();
const file2Contents = fs.readFileSync("file2.txt").toString();
const patch = createTwoFilesPatch("file1.txt", "file2.txt", file1Contents, file2Contents);
fs.writeFileSync("mydiff.patch", patch);
```

--------------------------------

### Async Diff and Patch Operations with Callbacks in Node.js

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Demonstrates asynchronous diff and patch operations using callbacks to prevent blocking the event loop. It shows how to handle large files and process the results of diff and patch operations.

```javascript
const {diffLines, createPatch, applyPatch} = require('diff');

const largeFile1 = 'A'.repeat(1000000) + '\nB\nC';
const largeFile2 = 'A'.repeat(1000000) + '\nD\nE';

// Async diff
diffLines(largeFile1, largeFile2, {
  callback: (changes) => {
    console.log(`Diff complete: ${changes.length} change blocks`);

    changes.forEach((change) => {
      if (change.added || change.removed) {
        console.log(`${change.added ? '+' : '-'} ${change.count} lines`);
      }
    });
  }
});

// Async patch creation
createPatch('large.txt', largeFile1, largeFile2, undefined, undefined, {
  callback: (patch) => {
    console.log('Patch created:', patch.length, 'characters');
    // Process patch...
  }
});

console.log('Diff operations started, continuing with other work...');

```

--------------------------------

### applyPatches - Apply multiple patches with callbacks

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Applies multiple patches asynchronously with callbacks for loading files and handling results. Useful for batch patch operations in build tools or version control systems.

```APIDOC
## applyPatches

### Description
Applies multiple patches asynchronously with callbacks for loading files and handling results. Useful for batch patch operations in build tools or version control systems.

### Method
*Not specified, assumed to be a function call*

### Endpoint
*Not applicable (JavaScript function)*

### Parameters
#### Arguments
- **multiFilePatch** (string) - Required - A string containing multiple patch definitions in unified diff format.
- **options** (object) - Required - An object containing callback functions for patch processing:
  - **loadFile** (function) - Callback to load the content of a file for patching. Receives `(patch, callback)`.
  - **patched** (function) - Callback invoked after a patch is applied. Receives `(patch, patchedContent, callback)`.
  - **complete** (function) - Callback invoked when all patches have been processed. Receives `(err)`.

### Request Example
```javascript
const {applyPatches} = require('diff');
const fs = require('fs');

const multiFilePatch = `--- file1.txt\n+++ file1.txt\n@@ -1,1 +1,1 @@\n-old content 1\n+new content 1\n--- file2.txt\n+++ file2.txt\n@@ -1,1 +1,1 @@\n-old content 2\n+new content 2`;

applyPatches(multiFilePatch, {
  loadFile: (patch, callback) => {
    const filename = patch.oldFileName;
    try {
      const content = fs.readFileSync(filename, 'utf8');
      callback(undefined, content);
    } catch (err) {
      callback(`Failed to read ${filename}: ${err.message}`);
    }
  },

  patched: (patch, patchedContent, callback) => {
    if (patchedContent === false) {
      callback(`Failed to apply patch to ${patch.oldFileName}`);
      return;
    }

    try {
      fs.writeFileSync(patch.oldFileName, patchedContent);
      console.log(`Successfully patched ${patch.oldFileName}`);
      callback();
    } catch (err) {
      callback(`Failed to write ${patch.oldFileName}: ${err.message}`);
    }
  },

  complete: (err) => {
    if (err) {
      console.error('Patch operation failed:', err);
    } else {
      console.log('All patches applied successfully');
    }
  }
});
```

### Response
*This function operates via callbacks and does not return a direct response. Errors and results are handled by the provided callback functions.*
```

--------------------------------

### Basic Character Difference in Node.js

Source: https://github.com/kpdecker/jsdiff/blob/master/README.md

Demonstrates a basic usage of `diffChars` in Node.js to find differences between two strings. It highlights how to iterate through the diff results and display added or removed characters with color coding. Requires the 'colors' package for output formatting.

```javascript
require('colors');
const {diffChars} = require('diff');

const one = 'beep boop';
const other = 'beep boob blah';

const diff = diffChars(one, other);

diff.forEach((part) => {
  // green for additions, red for deletions
  let text = part.added ? part.value.bgGreen :
             part.removed ? part.value.bgRed :
                            part.value;
  process.stderr.write(text);
});

console.log();

```

--------------------------------

### Import jsdiff utilities (CommonJS)

Source: https://github.com/kpdecker/jsdiff/blob/master/README.md

Shows how to import specific functions like diffChars and createPatch from the jsdiff library in a CommonJS environment.

```javascript
const {diffChars, createPatch} = require('diff');
```

--------------------------------

### convertChangesToDMP - Export to diff-match-patch format

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Converts change objects to the format used by Google's diff-match-patch library, enabling interoperability between different diff implementations.

```APIDOC
## convertChangesToDMP

### Description
Converts change objects to the format used by Google's diff-match-patch library, enabling interoperability between different diff implementations.

### Method
*Not specified, assumed to be a function call*

### Endpoint
*Not applicable (JavaScript function)*

### Parameters
#### Arguments
- **changes** (array) - Required - An array of change objects, typically generated by a diff function (e.g., `diffChars`). Each change object should have `added` (boolean or null), `removed` (boolean or null), and `value` (string) properties.

### Request Example
```javascript
const {diffChars, convertChangesToDMP} = require('diff');

const changes = diffChars('Hello', 'Hallo');
const dmpFormat = convertChangesToDMP(changes);

console.log(dmpFormat);
```

### Response
#### Success Response (200)
- **dmpFormat** (array) - An array representing the diff in a format compatible with the diff-match-patch library. Each element is a tuple `[operation, text]`:
  - **operation** (number) - -1 for deletion, 0 for equality, 1 for insertion.
  - **text** (string) - The text content for the operation.

#### Response Example
```json
[[0, "H"], [-1, "e"], [1, "a"], [0, "llo"]]
```
```

--------------------------------

### Import jsdiff utilities (ESM)

Source: https://github.com/kpdecker/jsdiff/blob/master/README.md

Demonstrates how to import specific functions like diffChars and createPatch from the jsdiff library in an ECMAScript Module (ESM) environment.

```javascript
import {diffChars, createPatch} from 'diff';
```

--------------------------------

### Apply Multiple Patches Asynchronously with Callbacks (JavaScript)

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Applies multiple patches defined in a unified diff string asynchronously. It uses callbacks to load original file content and to handle the results of patching each file. This is useful for batch patch operations in build tools or version control systems. It requires the 'diff' and 'fs' modules.

```javascript
const {applyPatches} = require('diff');
const fs = require('fs');

const multiFilePatch = `--- file1.txt
+++ file1.txt
@@ -1,1 +1,1 @@
-old content 1
+new content 1
--- file2.txt
+++ file2.txt
@@ -1,1 +1,1 @@
-old content 2
+new content 2`;

applyPatches(multiFilePatch, {
  loadFile: (patch, callback) => {
    const filename = patch.oldFileName;
    try {
      const content = fs.readFileSync(filename, 'utf8');
      callback(undefined, content);
    } catch (err) {
      callback(`Failed to read ${filename}: ${err.message}`);
    }
  },

  patched: (patch, patchedContent, callback) => {
    if (patchedContent === false) {
      callback(`Failed to apply patch to ${patch.oldFileName}`);
      return;
    }

    try {
      fs.writeFileSync(patch.oldFileName, patchedContent);
      console.log(`Successfully patched ${patch.oldFileName}`);
      callback();
    } catch (err) {
      callback(`Failed to write ${patch.oldFileName}: ${err.message}`);
    }
  },

  complete: (err) => {
    if (err) {
      console.error('Patch operation failed:', err);
    } else {
      console.log('All patches applied successfully');
    }
  }
});
```

--------------------------------

### Apply Patch to a Specified File in Node.js using jsdiff

Source: https://github.com/kpdecker/jsdiff/blob/master/README.md

This Node.js code snippet demonstrates how to apply a diff patch to a specific file, mimicking the Unix `patch` command. It uses the `applyPatch` function from the 'diff' module and requires the 'fs' module for reading and writing files. The patched content is then written back to the original file.

```javascript
const {applyPatch} = require('diff');
const file1Contents = fs.readFileSync("file1.txt").toString();
const patch = fs.readFileSync("mydiff.patch").toString();
const patchedFile = applyPatch(file1Contents, patch);
fs.writeFileSync("file1.txt", patchedFile);
```

--------------------------------

### structuredPatch - Generate structured patch object

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Returns a structured patch object with detailed hunk information instead of a formatted string. Useful for programmatic patch manipulation and custom patch formatting.

```APIDOC
## structuredPatch

### Description
Returns a structured patch object with detailed hunk information instead of a formatted string. Useful for programmatic patch manipulation and custom patch formatting.

### Method
*Not specified, assumed to be a function call*

### Endpoint
*Not applicable (JavaScript function)*

### Parameters
#### Arguments
- **oldFileName** (string) - Required - The original file name.
- **newFileName** (string) - Required - The new file name.
- **oldCode** (string) - Required - The content of the old file.
- **newCode** (string) - Required - The content of the new file.
- **oldHeader** (string) - Required - The header string for the old file.
- **newHeader** (string) - Required - The header string for the new file.
- **options** (object) - Optional - Configuration options for generating the patch:
  - **context** (number) - Optional - The number of context lines to include in each hunk. Defaults to 2.
  - **hash** (string) - Optional - A hash value for the patch.

### Request Example
```javascript
const {structuredPatch} = require('diff');

const oldCode = `class User {\n  constructor(name) {\n    this.name = name;\n  }\n}`;

const newCode = `class User {\n  constructor(name, email) {\n    this.name = name;\n    this.email = email;\n  }\n}`;

const patch = structuredPatch(
  'User.js',
  'User.js',
  oldCode,
  newCode,
  'Before',
  'After',
  {context: 2}
);

console.log(patch);
```

### Response
#### Success Response (200)
- **patch** (object) - A structured object representing the patch.
  - **oldFileName** (string) - The original file name.
  - **newFileName** (string) - The new file name.
  - **oldHeader** (string) - The header string for the old file.
  - **newHeader** (string) - The header string for the new file.
  - **hunks** (array) - An array of hunk objects:
    - **oldStart** (number) - The starting line number in the old file.
    - **oldLines** (number) - The number of lines in the old file for this hunk.
    - **newStart** (number) - The starting line number in the new file.
    - **newLines** (number) - The number of lines in the new file for this hunk.
    - **lines** (array) - An array of strings representing the lines in the hunk, prefixed with '-', '+', or ' '.

#### Response Example
```json
{
  "oldFileName": "User.js",
  "newFileName": "User.js",
  "oldHeader": "Before",
  "newHeader": "After",
  "hunks": [{
    "oldStart": 1,
    "oldLines": 5,
    "newStart": 1,
    "newLines": 6,
    "lines": [
      " class User {",
      "-  constructor(name) {",
      "+  constructor(name, email) {",
      "     this.name = name;",
      "+    this.email = email;",
      "   }",
      " }"
    ]
  }]
}
```
```

--------------------------------

### Character Diffing and Display with jsdiff (JavaScript)

Source: https://github.com/kpdecker/jsdiff/blob/master/examples/web_example.html

This snippet demonstrates how to use Diff.diffChars to find character differences between two strings. It then iterates over the differences, applying specific colors (green for additions, red for deletions, grey for common parts) to spans created for each part's value, and appends these spans to a document fragment for efficient DOM manipulation. Requires a DOM environment with an element having the ID 'display'.

```javascript
var one = 'beep boop', other = 'beep boob blah', color = '', span = null;
var diff = Diff.diffChars(one, other),
    display = document.getElementById('display'),
    fragment = document.createDocumentFragment();

diff.forEach(function(part){
  // green for additions, red for deletions
  // grey for common parts
  color = part.added ? 'green' : part.removed ? 'red' : 'grey';
  span = document.createElement('span');
  span.style.color = color;
  span.appendChild(document.createTextNode(part.value));
  fragment.appendChild(span);
});

display.appendChild(fragment);
```

--------------------------------

### Generate Structured Patch Data

Source: https://github.com/kpdecker/jsdiff/blob/master/README.md

Similar to `createTwoFilesPatch`, this function computes a diff and returns a structured object representing the patch, suitable for further programmatic processing. It includes detailed information about hunks and lines. Parameters are the same as `createTwoFilesPatch`.

```javascript
structuredPatch(oldFileName, newFileName, oldStr, newStr[, oldHeader[, newHeader[, options]]])
```

--------------------------------

### Word-level Diffing with jsdiff

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Compares two strings word by word, ideal for natural language text. Whitespace is ignored during diff computation but preserved in the output. Can leverage Intl.Segmenter for advanced word detection.

```javascript
const {diffWords} = require('diff');

const original = 'The quick brown fox jumps over the lazy dog';
const modified = 'The fast brown fox leaps over the sleepy dog';

const wordDiff = diffWords(original, modified);

wordDiff.forEach((part) => {
  const prefix = part.added ? '+' : part.removed ? '-' : ' ';
  console.log(`${prefix} ${part.value}`);
});

// Output:
//   The
// - quick
// + fast
//   brown fox
// - jumps
// + leaps
//   over the
// - lazy
// + sleepy
//   dog

// Using Intl.Segmenter for better word detection
const segmenter = new Intl.Segmenter('en', {granularity: 'word'});
const advancedDiff = diffWords('Hello world', 'Hello earth', {
  intlSegmenter: segmenter
});
console.log(advancedDiff);
```

--------------------------------

### parsePatch - Parse unified diff string

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Parses a unified diff patch string into structured patch objects. Converts patch text into a programmatic format for analysis or manipulation.

```APIDOC
## parsePatch

### Description
Parses a unified diff patch string into structured patch objects. Converts patch text into a programmatic format for analysis or manipulation.

### Method
*Not specified, assumed to be a function call*

### Endpoint
*Not applicable (JavaScript function)*

### Parameters
#### Arguments
- **patchString** (string) - Required - The unified diff patch string to parse.

### Request Example
```javascript
const {parsePatch} = require('diff');

const patchString = `Index: example.js\n===================================================================
--- example.js\t2024-01-01 10:00:00\n+++ example.js\t2024-01-01 11:00:00\n@@ -1,4 +1,5 @@\n const x = 1;\n-const y = 2;\n+const y = 3;\n+const z = 4;\n const sum = x + y;\n console.log(sum);`;

const patches = parsePatch(patchString);

patches.forEach((patch) => {
  console.log(`File: ${patch.oldFileName} -> ${patch.newFileName}`);
  console.log(`Hunks: ${patch.hunks.length}`);

  patch.hunks.forEach((hunk, index) => {
    console.log(`\nHunk ${index + 1}:`);
    console.log(`  Old: lines ${hunk.oldStart}-${hunk.oldStart + hunk.oldLines - 1}`);
    console.log(`  New: lines ${hunk.newStart}-${hunk.newStart + hunk.newLines - 1}`);
    console.log('  Changes:');
    hunk.lines.forEach((line) => {
      console.log(`    ${line}`);
    });
  });
});
```

### Response
#### Success Response (200)
- **patches** (array) - An array of structured patch objects. Each object has the following properties:
  - **oldFileName** (string) - The original file name.
  - **newFileName** (string) - The new file name.
  - **oldHeader** (string) - The header string for the old file.
  - **newHeader** (string) - The header string for the new file.
  - **hunks** (array) - An array of hunk objects (same structure as returned by `structuredPatch`).

#### Response Example
```json
[
  {
    "oldFileName": "example.js",
    "newFileName": "example.js",
    "oldHeader": "2024-01-01 10:00:00",
    "newHeader": "2024-01-01 11:00:00",
    "hunks": [
      {
        "oldStart": 1,
        "oldLines": 4,
        "newStart": 1,
        "newLines": 5,
        "lines": [
          " const x = 1;",
          "-const y = 2;",
          "+const y = 3;",
          "+const z = 4;",
          " const sum = x + y;",
          " console.log(sum);"
        ]
      }
    ]
  }
]
```
```

--------------------------------

### Create Unified Diff Patch

Source: https://github.com/kpdecker/jsdiff/blob/master/README.md

Generates a unified diff patch from two strings. It first computes a line-based diff using `diffLines` and then formats it into the unified diff standard. Supports specifying filenames, headers, and context options, including ignoring whitespace and stripping trailing carriage returns.

```javascript
createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr[, oldHeader[, newHeader[, options]]])
```

```javascript
createPatch(fileName, oldStr, newStr[, oldHeader[, newHeader[, options]]])
```

--------------------------------

### Create Patch for Different Files with jsdiff

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Generates a unified diff patch comparing two distinct files by providing their names and content. This is useful for scenarios involving file renames or comparisons between files with different identifiers.

```javascript
const {createTwoFilesPatch} = require('diff');

const file1Content = 'Original content\nLine 2\nLine 3';
const file2Content = 'Modified content\nLine 2\nLine 3';

const patch = createTwoFilesPatch(
  'old-file.txt',          // old filename
  'new-file.txt',          // new filename
  file1Content,            // old content
  file2Content,            // new content
  'Version 1.0',           // old header
  'Version 2.0',
  {
    context: 2,            // number of context lines
    ignoreWhitespace: false,
    stripTrailingCr: true
  }
);

console.log(patch);
// ===================================================================
// --- old-file.txt	Version 1.0
// +++ new-file.txt	Version 2.0
// @@ -1,3 +1,3 @@
// -Original content
// +Modified content
//  Line 2
//  Line 3
```

--------------------------------

### convertChangesToXML - Export diff as XML

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Converts an array of change objects to XML format for integration with XML-based tools or for structured data storage.

```APIDOC
## convertChangesToXML

### Description
Converts an array of change objects to XML format for integration with XML-based tools or for structured data storage.

### Method
*Not specified, assumed to be a function call*

### Endpoint
*Not applicable (JavaScript function)*

### Parameters
#### Arguments
- **changes** (array) - Required - An array of change objects, typically generated by a diff function (e.g., `diffWords`). Each change object should have `added` (boolean) and `value` (string) properties.

### Request Example
```javascript
const {diffWords, convertChangesToXML} = require('diff');

const oldText = 'The quick brown fox';
const newText = 'The fast brown wolf';

const changes = diffWords(oldText, newText);
const xml = convertChangesToXML(changes);

console.log(xml);
```

### Response
#### Success Response (200)
- **xml** (string) - An XML string representing the changes. Added text is wrapped in `` tags, and deleted text is wrapped in `` tags.

#### Response Example
```html
The 
quick 
fast 
brown 
fox
wolf
```
```

--------------------------------

### Diff Words with Space using jdiff

Source: https://github.com/kpdecker/jsdiff/blob/master/README.md

Compares two strings by treating words, punctuation, newlines, and runs of non-newline whitespace as tokens. This provides a more granular diff than `diffWords` by including whitespace as distinct tokens. Returns a list of change objects.

```javascript
import { diffWordsWithSpace } from 'diff';

const oldStr = "This is a test.";
const newStr = "This  is a  test.";

const diff = diffWordsWithSpace(oldStr, newStr);
console.log(diff);
```

--------------------------------

### Generate Structured Patch Object (JavaScript)

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Generates a structured patch object from two versions of a file, providing detailed hunk information rather than a formatted string. This is useful for programmatic patch manipulation and custom patch formatting. It takes file names, old and new code content, headers, and optional formatting options.

```javascript
const {structuredPatch} = require('diff');

const oldCode = `class User {
  constructor(name) {
    this.name = name;
  }
}`;

const newCode = `class User {
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }
}`;

const patch = structuredPatch(
  'User.js',
  'User.js',
  oldCode,
  newCode,
  'Before',
  'After',
  {context: 2}
);

console.log(patch);
// {
//   oldFileName: 'User.js',
//   newFileName: 'User.js',
//   oldHeader: 'Before',
//   newHeader: 'After',
//   hunks: [{
//     oldStart: 1,
//     oldLines: 5,
//     newStart: 1,
//     newLines: 6,
//     lines: [
//       ' class User {',
//       '-  constructor(name) {',
//       '+  constructor(name, email) {',
//       '     this.name = name;',
//       '+    this.email = email;',
//       '   }',
//       ' }'
//     ]
//   }]
// }

// Process hunks programmatically
patch.hunks.forEach((hunk) => {
  console.log(`Hunk at line ${hunk.oldStart}:`);
  console.log(`  ${hunk.oldLines} old lines, ${hunk.newLines} new lines`);
});
```

--------------------------------

### Diff Lines using jdiff

Source: https://github.com/kpdecker/jsdiff/blob/master/README.md

Compares two strings by treating each line as a token. Offers options to ignore leading/trailing whitespace, handle trailing CR characters, and treat newlines as separate tokens for more granular diffs. Returns a list of change objects.

```javascript
import { diffLines } from 'diff';

const oldStr = "Line 1\nLine 2\nLine 3";
const newStr = "Line 1\n  Line 2\nLine 4";

// Default diff
let diff = diffLines(oldStr, newStr);
console.log('Default diff:', diff);

// Ignore whitespace
diff = diffLines(oldStr, newStr, { ignoreWhitespace: true });
console.log('Ignore whitespace diff:', diff);

// Treat newlines as tokens
diff = diffLines(oldStr, newStr, { newlineIsToken: true });
console.log('Newline as token diff:', diff);

// Strip trailing CR
const winStr = "Line 1\r\nLine 2\r";
const unixStr = "Line 1\nLine 2";
diff = diffLines(winStr, unixStr, { stripTrailingCr: true });
console.log('Strip trailing CR diff:', diff);
```

--------------------------------

### Line-level Diffing with jsdiff

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Compares two strings line by line, treating each line as a token. Commonly used for file comparison and version control. Supports options to ignore whitespace, treat newlines as tokens, and handle different line endings.

```javascript
const {diffLines} = require('diff');

const oldFile = `Line 1
Line 2
Line 3
Line 4`;

const newFile = `Line 1
Line 2 modified
Line 3
Line 5`;

const lineDiff = diffLines(oldFile, newFile);

lineDiff.forEach((change) => {
  if (change.added) {
    console.log(`+ ${change.value.trim()}`);
  } else if (change.removed) {
    console.log(`- ${change.value.trim()}`);
  } else {
    console.log(`  ${change.value.trim()}`);
  }
});

// With options
const diffWithOptions = diffLines(oldFile, newFile, {
  ignoreWhitespace: true,     // Ignore leading/trailing whitespace
  newlineIsToken: true,       // Treat newlines as separate tokens
  stripTrailingCr: true       // Remove \r characters (Windows line endings)
});
```

--------------------------------

### Convert Text Changes to Diff-Match-Patch Format (JavaScript)

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Converts an array of change objects into the specific format used by Google's diff-match-patch library. This enables interoperability between the 'diff' library and diff-match-patch, allowing for complex diff operations using both tools. The output is an array of operations and text segments.

```javascript
const {diffChars, convertChangesToDMP} = require('diff');

const changes = diffChars('Hello', 'Hallo');
const dmpFormat = convertChangesToDMP(changes);

console.log(dmpFormat);
// [[0, 'H'], [-1, 'e'], [1, 'a'], [0, 'llo']]
// Format: [operation, text]
//   operation: -1 = delete, 0 = equal, 1 = insert

// Use with Google's diff-match-patch library
// const dmp = new diff_match_patch();
// dmp.patch_make(dmpFormat);
```

--------------------------------

### Convert Text Changes to XML Format (JavaScript)

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Converts an array of change objects, typically generated by diffing text, into an XML string. This is useful for integrating diff results with XML-based tools or for structured data storage. It requires the 'diff' module and relies on the output of functions like diffWords.

```javascript
const {diffWords, convertChangesToXML} = require('diff');

const oldText = 'The quick brown fox';
const newText = 'The fast brown wolf';

const changes = diffWords(oldText, newText);
const xml = convertChangesToXML(changes);

console.log(xml);
// The 
// quick 
// fast 
// brown 
// fox
// wolf
```

--------------------------------

### Character-level Diffing with jsdiff

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Compares two strings character by character, returning an array of change objects. Supports options for case-insensitive comparison. Useful for detailed text analysis.

```javascript
const {diffChars} = require('diff');

const oldText = 'Hello World';
const newText = 'Hello JavaScript';

const changes = diffChars(oldText, newText);

// Process the changes
changes.forEach((change) => {
  if (change.added) {
    console.log(`+ Added: "${change.value}"`);
  } else if (change.removed) {
    console.log(`- Removed: "${change.value}"`);
  } else {
    console.log(`  Unchanged: "${change.value}"`);
  }
});

// Output:
//   Unchanged: "Hello "
// - Removed: "World"
// + Added: "JavaScript"

// Case-insensitive comparison
const caseInsensitiveChanges = diffChars('Foo', 'FOOD', {ignoreCase: true});
console.log(caseInsensitiveChanges);
// [{value: 'FOO', count: 3}, {value: 'D', added: true, count: 1}]
```

--------------------------------

### Create Unified Diff Patch with jsdiff

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Generates a unified diff patch from two strings, suitable for Unix patch tools. It computes line-based differences and formats them with context lines and hunk headers.

```javascript
const {createPatch} = require('diff');
const fs = require('fs');

const oldContent = `function hello() {
  console.log('Hello');
}

function goodbye() {
  console.log('Goodbye');
}`;

const newContent = `function hello() {
  console.log('Hello World');
}

function farewell() {
  console.log('Farewell');
}`;

const patch = createPatch(
  'greeting.js',           // filename
  oldContent,              // old string
  newContent,              // new string
  'Original version',      // old header (optional)
  'Updated version',       // new header (optional)
  {context: 3}            // options: 3 lines of context
);

console.log(patch);
// Index: greeting.js
// ===================================================================
// --- greeting.js	Original version
// +++ greeting.js	Updated version
// @@ -1,7 +1,7 @@
//  function hello() {
// -  console.log('Hello');
// +  console.log('Hello World');
//  }
//
// -function goodbye() {
// -  console.log('Goodbye');
// +function farewell() {
// +  console.log('Farewell');
//  }

// Save to file
fs.writeFileSync('changes.patch', patch);
```

--------------------------------

### JSON Diffing with jsdiff

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Compares two JSON-serializable objects by performing a line-by-line comparison of their prettified JSON representations. Object properties are sorted alphabetically for order-independent diffing. Supports custom replacers for values like 'undefined'.

```javascript
const {diffJson} = require('diff');

const oldObject = {
  name: 'John',
  age: 30,
  city: 'New York',
  skills: ['JavaScript', 'Python']
};

const newObject = {
  name: 'John',
  age: 31,
  city: 'Boston',
  skills: ['JavaScript', 'Python', 'Go']
};

const jsonDiff = diffJson(oldObject, newObject);

jsonDiff.forEach((part) => {
  const prefix = part.added ? '+' : part.removed ? '-' : ' ';
  console.log(prefix + part.value);
});

// Custom replacer for undefined values
const objWithUndefined = {a: 1, b: undefined, c: 3};
const objReplaced = {a: 1, b: null, c: 4};

const customDiff = diffJson(objWithUndefined, objReplaced, {
  undefinedReplacement: null
});
```

--------------------------------

### Diff Words using jdiff

Source: https://github.com/kpdecker/jsdiff/blob/master/README.md

Compares two strings by treating words and punctuation as tokens, while ignoring whitespace. Supports case-insensitivity and an optional Intl.Segmenter for advanced word tokenization, especially for non-English text. Returns a list of change objects.

```javascript
import { diffWords } from 'diff';

const oldStr = "Hello world! How are you?";
const newStr = "Hello there! How is it going?";

// Default behavior
let diff = diffWords(oldStr, newStr);
console.log('Default diff:', diff);

// With ignoreCase option
diff = diffWords(oldStr, newStr, { ignoreCase: true });
console.log('Ignore case diff:', diff);

// Using Intl.Segmenter (example with English)
if (typeof Intl.Segmenter !== 'undefined') {
  const segmenter = new Intl.Segmenter('en', { granularity: 'word' });
  diff = diffWords(oldStr, newStr, { intlSegmenter: segmenter });
  console.log('Intl.Segmenter diff:', diff);
} else {
  console.log('Intl.Segmenter not supported in this environment.');
}
```

--------------------------------

### Apply Unified Diff Patch

Source: https://github.com/kpdecker/jsdiff/blob/master/README.md

Attempts to apply a unified diff patch to a given source string. It intelligently applies hunks, trying various matching strategies and handling context mismatches with a `fuzzFactor`. Adjusts subsequent hunk application based on successful previous applications.

```javascript
applyPatch(source, patch[, options])
```

--------------------------------

### Diff CSS Tokens

Source: https://github.com/kpdecker/jsdiff/blob/master/README.md

Compares two blocks of text by tokenizing them as CSS. It returns a list of change objects detailing the differences. This function is useful for comparing CSS stylesheets.

```javascript
diffCss(oldStr, newStr[, options])
```

--------------------------------

### Parse Unified Diff String into Structured Objects (JavaScript)

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Parses a unified diff patch string into an array of structured patch objects. This function converts patch text into a programmatic format, making it suitable for analysis or manipulation. It takes the diff string as input and returns an array of patch objects, each containing file information and hunks.

```javascript
const {parsePatch} = require('diff');

const patchString = `Index: example.js
===================================================================
--- example.js	2024-01-01 10:00:00
+++ example.js	2024-01-01 11:00:00
@@ -1,4 +1,5 @@
 const x = 1;
-const y = 2;
+const y = 3;
+const z = 4;
 const sum = x + y;
 console.log(sum);``;

const patches = parsePatch(patchString);

patches.forEach((patch) => {
  console.log(`File: ${patch.oldFileName} -> ${patch.newFileName}`);
  console.log(`Hunks: ${patch.hunks.length}`);

  patch.hunks.forEach((hunk, index) => {
    console.log(`\nHunk ${index + 1}:`);
    console.log(`  Old: lines ${hunk.oldStart}-${hunk.oldStart + hunk.oldLines - 1}`);
    console.log(`  New: lines ${hunk.newStart}-${hunk.newStart + hunk.newLines - 1}`);
    console.log('  Changes:');
    hunk.lines.forEach((line) => {
      console.log(`    ${line}`);
    });
  });
});
```

--------------------------------

### Apply Unified Diff Patch with jsdiff

Source: https://context7.com/kpdecker/jsdiff/llms.txt

Applies a unified diff patch to source text. It supports features like fuzzy matching, automatic line ending conversion, and intelligent hunk positioning for robust patch application.

```javascript
const {applyPatch} = require('diff');

const sourceCode = `function calculate(a, b) {
  const sum = a + b;
  return sum;
}`;

const patchText = `--- calculator.js
+++ calculator.js
@@ -1,3 +1,4 @@
 function calculate(a, b) {
-  const sum = a + b;
+  const sum = a + b;
+  console.log('Sum:', sum);
   return sum;
 }`;

const patchedCode = applyPatch(sourceCode, patchText);

if (patchedCode === false) {
  console.error('Failed to apply patch');
} else {
  console.log('Patched successfully:');
  console.log(patchedCode);
}

// With fuzzy matching
const fuzzPatch = applyPatch(sourceCode, patchText, {
  fuzzFactor: 2,                    // Allow up to 2 line mismatches
  autoConvertLineEndings: true,     // Auto-convert CRLF/LF
  compareLine: (lineNum, line, op, patchContent) => {
    // Custom line comparison logic
    return line.trim() === patchContent.trim();
  }
});
```