@lookworld4/json-delta-sync
v1.0.0
Published
Compare two JSON trees and produce a minimal delta patch for WebSockets and real-time dashboards — send only what changed.
Maintainers
Readme
@lookworld4/json-delta-sync
Compare two JSON trees and produce a small delta you can send over WebSockets or SSE instead of the full payload. Applying the delta to the client’s last-known state reconstructs the latest snapshot.
Install
npm install @lookworld4/json-delta-syncUsage
import { createDelta, applyDelta, utf8JsonByteLength } from '@lookworld4/json-delta-sync';
const prev = { matchId: 'm1', score: { home: 1, away: 0 }, clock: '12:00' };
const next = { matchId: 'm1', score: { home: 2, away: 0 }, clock: '12:01' };
const delta = createDelta(prev, next);
if (delta === null) {
// no changes
} else {
const bytes = utf8JsonByteLength(delta);
// send `delta` over the wire — typically much smaller than JSON.stringify(next)
const reconstructed = applyDelta(prev, delta);
}Delta format (defaults)
$r: replace an entire subtree (used when types differ, arrays change length, or a large fraction of array cells change).$u: list of object keys removed from the previous value.$i: sparse map of array index → patch for that element (when only a few indices change).
You can rename these with metaKeys if they clash with your domain (see types).
Constraints
- Values should be JSON-safe (plain objects, arrays, strings, numbers, booleans,
null). Circular references are not supported. - Avoid using the same strings as your configured meta keys (
$r/$u/$iby default) as literal object keys in persisted state if those objects are diffed in place; customizemetaKeysif needed.
License
MIT
