feat(smartdiff): Migrate package to ESM, replace fast-diff with and add rich diff APIs + formatters

This commit is contained in:
2025-12-14 12:33:23 +00:00
parent 742a8c734d
commit 46dbef319b
11 changed files with 8306 additions and 6299 deletions

437
readme.md
View File

@@ -1,81 +1,446 @@
# @push.rocks/smartdiff
a diffing lib for text
A powerful, cross-platform text diffing library for TypeScript/JavaScript with built-in visualization for CLI and browser. 🔍
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## Install
To install @push.rocks/smartdiff, you need to have Node.js and npm installed. Once you have those set up, you can install the library by running the following command in your project directory:
```sh
npm install @push.rocks/smartdiff --save
npm install @push.rocks/smartdiff
# or
pnpm add @push.rocks/smartdiff
```
## Features ✨
- 🔤 **Character-level diffs** — See exactly which characters changed
- 📝 **Word-level diffs** — Perfect for document comparisons
- 📄 **Line-level diffs** — Ideal for code and file comparisons
- 🖥️ **CLI output** — ANSI-colored terminal output
- 🌐 **HTML output** — Styled spans for browser rendering
- 📦 **Compact storage format** — Efficient diff serialization for storage/sync
- 🔧 **Git-style unified diffs** — Standard patch format
- 💅 **Built-in CSS** — Ready-to-use styles for HTML output
## Usage
@push.rocks/smartdiff is a simple yet powerful library designed for creating and applying text diffs. It leverages the fast-diff library for efficient diffing operations. This usage guide will take you through the process of creating diffs between two pieces of text and applying those diffs to text using TypeScript with ESM syntax.
### Quick Start
### Creating a Text Diff
```typescript
import {
createDiff,
applyPatch,
formatLineDiffForConsole,
formatWordDiffAsHtml,
} from '@push.rocks/smartdiff';
The primary functionality of @push.rocks/smartdiff is to create a diff between two versions of text, which can then be used to update texts or synchronize changes. Heres how you can create a diff:
// Create and apply compact diffs
const patch = createDiff('hello world', 'hello beautiful world');
const result = applyPatch('hello world', patch);
// result: 'hello beautiful world'
// Visualize changes in terminal
console.log(formatLineDiffForConsole(oldCode, newCode));
// Generate HTML for browser display
const html = formatWordDiffAsHtml(oldText, newText);
```
---
## 📦 Compact Diff Storage
For storing diffs efficiently (version control, sync, undo/redo):
### `createDiff(original, revision)`
Creates a compact JSON-encoded diff optimized for storage.
```typescript
import { createDiff } from '@push.rocks/smartdiff';
const originalText = 'Hello World';
const revisedText = 'Hello smart World';
const diffString = createDiff(originalText, revisedText);
console.log(diffString);
// Output would be a JSON string representing the diff
const diff = createDiff('Hello World', 'Hello smart World');
console.log(diff);
// Output: [[0,6],[1,"smart "],[0,5]]
```
This example demonstrates how to generate a diff. The `createDiff` function takes two arguments: the original text and the revised text. It returns a JSON string representing the changes required to go from the original text to the revised text.
**Format:**
- `[0, n]` — Keep `n` characters from original
- `[1, "text"]` — Insert `"text"`
- `[-1, n]` — Delete `n` characters
### Applying a Text Diff
### `applyPatch(original, diffString)`
Once you have a diff, you might want to apply it to the original text to reconstruct the revised version (or vice versa). Heres how you can apply a diff with smartdiff:
Reconstructs the revised text from original + diff.
```typescript
import { applyPatch } from '@push.rocks/smartdiff';
import { createDiff, applyPatch } from '@push.rocks/smartdiff';
const originalText = 'Hello World';
const diffString = '[[-6,"smart "],[0," World"]]'; // An example diff string
const original = 'hi there';
const revised = 'hi Polly, there is a Sandwich.';
const updatedText = applyPatch(originalText, diffString);
console.log(updatedText);
// Expected output: 'Hello smart World'
const patch = createDiff(original, revised);
const reconstructed = applyPatch(original, patch);
// reconstructed === revised ✓
```
The `applyPatch` function takes the original text and a diff string as inputs and outputs the updated text after applying the diff.
---
### Handling Complex Diffs
## 🔤 Character-Level Diff
@push.rocks/smartdiff is capable of handling more complex diffs, including multi-line changes, deletions, and insertions. When working with complex texts, the process remains the same: generate a diff using `createDiff` and apply it with `applyPatch`. This ensures that you can track and synchronize changes efficiently, no matter how extensive they are.
For precise character-by-character comparison:
### Best Practices for Managing Diffs
### `getCharDiff(original, revision)`
- **Version Control**: Always keep track of your base and revised texts in some form of version control. This can help in diagnosing issues or conflicts in diffs.
- **Testing**: Ensure that you thoroughly test diffs, especially in applications where correctness is critical (e.g., legal documents or codebases).
- **Performance Considerations**: While `smartdiff` is optimized for performance, generating and applying diffs across extremely large documents may require additional considerations, such as chunking texts.
Returns an array of diff segments.
In conclusion, @push.rocks/smartdiff offers a streamlined interface for working with text diffs in TypeScript applications. Whether you are developing a collaborative editing tool, implementing version control for texts, or simply need to track changes in documents, `smartdiff` provides the necessary tools to get the job done with minimal overhead.
```typescript
import { getCharDiff } from '@push.rocks/smartdiff';
For any questions or contributions, please refer to the project's GitHub repository or contact the maintainers. Happy coding!
const segments = getCharDiff('hello', 'hallo');
// [
// { type: 'equal', value: 'h' },
// { type: 'delete', value: 'e' },
// { type: 'insert', value: 'a' },
// { type: 'equal', value: 'llo' }
// ]
```
### `formatCharDiffForConsole(original, revision)`
Returns ANSI-colored string for terminal output.
```typescript
import { formatCharDiffForConsole } from '@push.rocks/smartdiff';
console.log(formatCharDiffForConsole('hello world', 'hello beautiful world'));
// Displays: hello [green background]beautiful [/green]world
```
### `formatCharDiffAsHtml(original, revision)`
Returns HTML with styled spans.
```typescript
import { formatCharDiffAsHtml } from '@push.rocks/smartdiff';
const html = formatCharDiffAsHtml('hello', 'hallo');
// <span class="smartdiff-equal">h</span>
// <span class="smartdiff-delete">e</span>
// <span class="smartdiff-insert">a</span>
// <span class="smartdiff-equal">llo</span>
```
---
## 📝 Word-Level Diff
For document and prose comparison:
### `getWordDiff(original, revision)`
```typescript
import { getWordDiff } from '@push.rocks/smartdiff';
const segments = getWordDiff('The quick brown fox', 'The slow brown dog');
// [
// { type: 'equal', value: 'The ' },
// { type: 'delete', value: 'quick' },
// { type: 'insert', value: 'slow' },
// { type: 'equal', value: ' brown ' },
// { type: 'delete', value: 'fox' },
// { type: 'insert', value: 'dog' }
// ]
```
### `formatWordDiffForConsole(original, revision)`
```typescript
import { formatWordDiffForConsole } from '@push.rocks/smartdiff';
console.log(formatWordDiffForConsole('Hello World', 'Hello Beautiful World'));
// Displays: Hello [green]Beautiful [/green]World
```
### `formatWordDiffAsHtml(original, revision)`
```typescript
import { formatWordDiffAsHtml } from '@push.rocks/smartdiff';
const html = formatWordDiffAsHtml('one two three', 'one TWO three');
// <span class="smartdiff-equal">one </span>
// <span class="smartdiff-delete">two</span>
// <span class="smartdiff-insert">TWO</span>
// <span class="smartdiff-equal"> three</span>
```
---
## 📄 Line-Level Diff
For code and file comparison:
### `getLineDiff(original, revision)`
```typescript
import { getLineDiff } from '@push.rocks/smartdiff';
const lineDiff = getLineDiff('line1\nline2\nline3', 'line1\nmodified\nline3');
// [
// { lineNumber: 1, type: 'equal', value: 'line1' },
// { lineNumber: 2, type: 'delete', value: 'line2' },
// { lineNumber: -1, type: 'insert', value: 'modified' },
// { lineNumber: 3, type: 'equal', value: 'line3' }
// ]
```
### `formatLineDiffForConsole(original, revision)`
Produces unified diff-style output with colors:
```typescript
import { formatLineDiffForConsole } from '@push.rocks/smartdiff';
const oldCode = `function hello() {
console.log("hi");
}`;
const newCode = `function hello() {
console.log("hello world");
}`;
console.log(formatLineDiffForConsole(oldCode, newCode));
```
Output:
```diff
function hello() {
- console.log("hi");
+ console.log("hello world");
}
```
### `formatLineDiffAsHtml(original, revision)`
```typescript
import { formatLineDiffAsHtml } from '@push.rocks/smartdiff';
const html = formatLineDiffAsHtml('a\nb\nc', 'a\nB\nc');
// <div class="smartdiff-lines">
// <div class="smartdiff-line smartdiff-equal"><span class="smartdiff-prefix"> </span>a</div>
// <div class="smartdiff-line smartdiff-delete"><span class="smartdiff-prefix">-</span>b</div>
// <div class="smartdiff-line smartdiff-insert"><span class="smartdiff-prefix">+</span>B</div>
// <div class="smartdiff-line smartdiff-equal"><span class="smartdiff-prefix"> </span>c</div>
// </div>
```
---
## 🔧 Unified Diff (Git-style)
### `createUnifiedDiff(original, revision, options?)`
Creates a standard unified diff patch.
```typescript
import { createUnifiedDiff } from '@push.rocks/smartdiff';
const patch = createUnifiedDiff(oldContent, newContent, {
originalFileName: 'file.txt',
revisedFileName: 'file.txt',
context: 3, // lines of context
});
console.log(patch);
```
Output:
```diff
--- file.txt
+++ file.txt
@@ -1,5 +1,5 @@
line1
-line2
+modified
line3
```
### `formatUnifiedDiffForConsole(original, revision, options?)`
Same as above, but with ANSI colors for terminal display.
---
## 💅 CSS Styles for HTML Output
### `getDefaultDiffCss()`
Returns ready-to-use CSS for styling HTML diff output.
```typescript
import { getDefaultDiffCss } from '@push.rocks/smartdiff';
const css = getDefaultDiffCss();
// Inject into your page:
// <style>${css}</style>
```
**Included styles:**
- `.smartdiff-delete` — Red background, strikethrough
- `.smartdiff-insert` — Green background
- `.smartdiff-equal` — Unchanged text
- `.smartdiff-lines` — Container for line diffs
- `.smartdiff-line` — Individual line styling
- `.smartdiff-prefix` — The +/- prefix styling
---
## 🎯 Real-World Use Cases
### Collaborative Editing
Track document versions without storing full copies:
```typescript
import { createDiff, applyPatch } from '@push.rocks/smartdiff';
const versions = ['Initial draft'];
const patches: string[] = [];
function saveVersion(newText: string) {
const lastVersion = versions[versions.length - 1];
patches.push(createDiff(lastVersion, newText));
versions.push(newText);
}
function getVersion(index: number): string {
let text = versions[0];
for (let i = 0; i < index; i++) {
text = applyPatch(text, patches[i]);
}
return text;
}
```
### Network Synchronization
Send compact diffs instead of full content:
```typescript
import { createDiff, applyPatch } from '@push.rocks/smartdiff';
// Client
function sendUpdate(localText: string, serverText: string) {
const diff = createDiff(serverText, localText);
socket.emit('update', diff); // Much smaller than full text!
}
// Server
socket.on('update', (diff: string) => {
document = applyPatch(document, diff);
});
```
### Undo/Redo System
```typescript
import { createDiff, applyPatch } from '@push.rocks/smartdiff';
interface HistoryEntry {
forward: string;
backward: string;
}
const history: HistoryEntry[] = [];
let currentText = 'Start';
function edit(newText: string) {
history.push({
forward: createDiff(currentText, newText),
backward: createDiff(newText, currentText),
});
currentText = newText;
}
function undo() {
const entry = history.pop();
if (entry) {
currentText = applyPatch(currentText, entry.backward);
}
}
```
### Code Review UI
```typescript
import { formatLineDiffAsHtml, getDefaultDiffCss } from '@push.rocks/smartdiff';
function renderCodeReview(oldCode: string, newCode: string) {
return `
<style>${getDefaultDiffCss()}</style>
${formatLineDiffAsHtml(oldCode, newCode)}
`;
}
```
---
## 📖 TypeScript Types
```typescript
interface IDiffSegment {
type: 'equal' | 'insert' | 'delete';
value: string;
}
interface ILineDiff {
lineNumber: number;
type: 'equal' | 'insert' | 'delete';
value: string;
}
```
---
## API Reference
| Function | Description |
|----------|-------------|
| `createDiff(original, revision)` | Create compact diff for storage |
| `applyPatch(original, diffString)` | Reconstruct text from diff |
| `getCharDiff(original, revision)` | Character-level diff segments |
| `getWordDiff(original, revision)` | Word-level diff segments |
| `getLineDiff(original, revision)` | Line-level diff segments |
| `formatCharDiffForConsole(...)` | ANSI-colored char diff |
| `formatWordDiffForConsole(...)` | ANSI-colored word diff |
| `formatLineDiffForConsole(...)` | ANSI-colored line diff |
| `formatCharDiffAsHtml(...)` | HTML char diff |
| `formatWordDiffAsHtml(...)` | HTML word diff |
| `formatLineDiffAsHtml(...)` | HTML line diff |
| `createUnifiedDiff(...)` | Git-style unified diff |
| `formatUnifiedDiffForConsole(...)` | Colored unified diff |
| `getDefaultDiffCss()` | CSS styles for HTML output |
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.