@jsondelta/merge 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jsondelta
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.
package/README.md ADDED
@@ -0,0 +1,150 @@
1
+ <p align="center">
2
+ <img src="logo.svg" width="128" height="128" alt="@jsondelta/merge">
3
+ </p>
4
+
5
+ <h1 align="center">@jsondelta/merge</h1>
6
+
7
+ <p align="center">
8
+ Zig-powered three-way JSON merge with conflict detection. Merge concurrent edits, detect collisions, keep the base value for conflicts.
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://github.com/jsondelta/merge/actions/workflows/test.yml"><img src="https://github.com/jsondelta/merge/actions/workflows/test.yml/badge.svg" alt="test"></a>
13
+ <a href="https://www.npmjs.com/package/@jsondelta/merge"><img src="https://img.shields.io/npm/v/@jsondelta/merge" alt="npm"></a>
14
+ </p>
15
+
16
+ ## Install
17
+
18
+ ```
19
+ npm install @jsondelta/merge
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ```js
25
+ import { merge } from '@jsondelta/merge'
26
+
27
+ const base = { title: 'Draft', body: 'Hello', status: 'open' }
28
+ const left = { title: 'Draft', body: 'Hello world', status: 'open' }
29
+ const right = { title: 'Final', body: 'Hello', status: 'review' }
30
+
31
+ const { doc, conflicts } = merge(base, left, right)
32
+ // doc: { title: 'Final', body: 'Hello world', status: 'review' }
33
+ // conflicts: []
34
+ ```
35
+
36
+ The default import selects the fastest available backend: WebAssembly or pure JS fallback. You can also import a specific backend directly:
37
+
38
+ ```js
39
+ import { merge } from '@jsondelta/merge/fallback'
40
+ import { merge } from '@jsondelta/merge/wasm'
41
+ ```
42
+
43
+ ## Real-world examples
44
+
45
+ ### Merging concurrent edits in a collaborative editor
46
+
47
+ ```js
48
+ import { merge } from '@jsondelta/merge'
49
+
50
+ const base = {
51
+ title: 'Q1 Report',
52
+ sections: [
53
+ { heading: 'Revenue', body: 'Revenue grew 12% YoY.' },
54
+ { heading: 'Costs', body: 'Operating costs remained flat.' }
55
+ ],
56
+ metadata: { author: 'alice', version: 1 }
57
+ }
58
+
59
+ // alice updates the revenue figure and bumps the version
60
+ const alice = {
61
+ title: 'Q1 Report',
62
+ sections: [
63
+ { heading: 'Revenue', body: 'Revenue grew 15% YoY, beating estimates.' },
64
+ { heading: 'Costs', body: 'Operating costs remained flat.' }
65
+ ],
66
+ metadata: { author: 'alice', version: 2 }
67
+ }
68
+
69
+ // bob updates the title and costs section
70
+ const bob = {
71
+ title: 'Q1 Financial Report',
72
+ sections: [
73
+ { heading: 'Revenue', body: 'Revenue grew 12% YoY.' },
74
+ { heading: 'Costs', body: 'Operating costs decreased 3%.' }
75
+ ],
76
+ metadata: { author: 'alice', version: 1 }
77
+ }
78
+
79
+ const { doc, conflicts } = merge(base, alice, bob)
80
+ // doc.title === 'Q1 Financial Report'
81
+ // doc.sections[0].body === 'Revenue grew 15% YoY, beating estimates.'
82
+ // doc.sections[1].body === 'Operating costs decreased 3%.'
83
+ // doc.metadata.version === 2
84
+ // conflicts === []
85
+ ```
86
+
87
+ ### Merging configuration with conflict detection
88
+
89
+ ```js
90
+ import { merge } from '@jsondelta/merge'
91
+
92
+ const base = { database: { host: 'localhost', port: 5432 }, logging: { level: 'info' } }
93
+ const staging = { database: { host: 'staging.db', port: 5432 }, logging: { level: 'debug' } }
94
+ const production = { database: { host: 'prod.db', port: 5432 }, logging: { level: 'warn' } }
95
+
96
+ const { doc, conflicts } = merge(base, staging, production)
97
+ // doc.database.host stays 'localhost' (conflict - both changed it differently)
98
+ // doc.logging.level stays 'info' (conflict)
99
+ // conflicts.length === 2
100
+ ```
101
+
102
+ ## API
103
+
104
+ ### `merge(base, left, right)`
105
+
106
+ Three-way merge of JSON-compatible values.
107
+
108
+ - `base` - the common ancestor
109
+ - `left` - the left (or "ours") revision
110
+ - `right` - the right (or "theirs") revision
111
+ - Returns `{ doc, conflicts }`
112
+
113
+ **`doc`** contains all non-conflicting changes applied to the base. Conflicting paths retain the base value - neither side wins automatically.
114
+
115
+ **`conflicts`** is an array of conflict objects, each with `left` and `right` properties containing the conflicting operations from each side. Operations follow the `@jsondelta/diff` delta format:
116
+
117
+ ```js
118
+ {
119
+ left: { op: 'replace', path: ['level'], old: 'info', new: 'debug' },
120
+ right: { op: 'replace', path: ['level'], old: 'info', new: 'warn' }
121
+ }
122
+ ```
123
+
124
+ When both sides make the same change to the same path, it is not a conflict - the change is applied once.
125
+
126
+ ## Conflict detection
127
+
128
+ Two operations conflict when their paths overlap (one is a prefix of the other, or they are equal) and the operations differ.
129
+
130
+ | Left | Right | Result |
131
+ |------|-------|--------|
132
+ | Changes `a.b` | Changes `a.c` | Both applied (no overlap) |
133
+ | Changes `a.b` to X | Changes `a.b` to X | Applied once (identical) |
134
+ | Changes `a.b` to X | Changes `a.b` to Y | Conflict |
135
+ | Replaces `a` entirely | Changes `a.b` | Conflict (ancestor/descendant) |
136
+ | Removes `a.b` | Changes `a.b` | Conflict |
137
+
138
+ ## How it works
139
+
140
+ The merge engine is written in Zig and compiled to WebAssembly. It diffs the base against both revisions, partitions the resulting operations into clean (non-overlapping) and conflicting sets, and applies the clean operations to produce the merged document.
141
+
142
+ The pure JS fallback uses `@jsondelta/diff` and `@jsondelta/patch` under the hood.
143
+
144
+ **Architecture:**
145
+ 1. **WebAssembly** - Self-contained Zig engine with embedded diff and patch logic. Near-native speed, no JS dependencies at runtime
146
+ 2. **Pure JS fallback** - Uses `@jsondelta/diff` and `@jsondelta/patch`. Always works
147
+
148
+ ## License
149
+
150
+ MIT
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@jsondelta/merge",
3
+ "version": "1.0.0",
4
+ "description": "Zig-powered three-way JSON merge with conflict detection",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "types": "./types/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./types/index.d.ts",
11
+ "default": "./src/index.js"
12
+ },
13
+ "./fallback": {
14
+ "types": "./types/fallback.d.ts",
15
+ "default": "./src/fallback.js"
16
+ },
17
+ "./wasm": {
18
+ "types": "./types/wasm.d.ts",
19
+ "default": "./src/wasm.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "src",
24
+ "wasm",
25
+ "types"
26
+ ],
27
+ "scripts": {
28
+ "test": "node --test test/*.test.js",
29
+ "prepublishOnly": "npx tsc --declaration --allowJs --emitDeclarationOnly --skipLibCheck --target es2020 --module nodenext --moduleResolution nodenext --strict false --esModuleInterop true --outDir ./types src/index.js src/fallback.js src/wasm.js"
30
+ },
31
+ "keywords": [
32
+ "json",
33
+ "merge",
34
+ "three-way",
35
+ "conflict",
36
+ "zig",
37
+ "wasm",
38
+ "performance"
39
+ ],
40
+ "license": "MIT",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "https://github.com/jsondelta/merge.git"
44
+ },
45
+ "dependencies": {
46
+ "@jsondelta/diff": "^1.0.0",
47
+ "@jsondelta/patch": "^1.0.0"
48
+ },
49
+ "devDependencies": {
50
+ "typescript": "^5.9.3"
51
+ }
52
+ }
@@ -0,0 +1,113 @@
1
+ import { diff } from '@jsondelta/diff/fallback'
2
+ import { patch } from '@jsondelta/patch/fallback'
3
+
4
+ /**
5
+ * Three-way merge of JSON-compatible values.
6
+ * @param {*} base - Common ancestor
7
+ * @param {*} left - Left revision
8
+ * @param {*} right - Right revision
9
+ * @returns {{ doc: *, conflicts: Array<{ left: Object, right: Object }> }}
10
+ */
11
+ function merge(base, left, right) {
12
+ const leftDelta = diff(base, left)
13
+ const rightDelta = diff(base, right)
14
+
15
+ if (leftDelta.length === 0 && rightDelta.length === 0) {
16
+ return { doc: structuredClone(base), conflicts: [] }
17
+ }
18
+ if (leftDelta.length === 0) {
19
+ return { doc: structuredClone(right), conflicts: [] }
20
+ }
21
+ if (rightDelta.length === 0) {
22
+ return { doc: structuredClone(left), conflicts: [] }
23
+ }
24
+
25
+ const conflicts = []
26
+ const cleanLeft = []
27
+ const rightConsumed = new Set()
28
+
29
+ for (const lOp of leftDelta) {
30
+ let hasConflict = false
31
+
32
+ for (let ri = 0; ri < rightDelta.length; ri++) {
33
+ const rOp = rightDelta[ri]
34
+ if (!pathsOverlap(lOp.path, rOp.path)) continue
35
+
36
+ rightConsumed.add(ri)
37
+
38
+ if (opsEqual(lOp, rOp)) {
39
+ if (!hasConflict) cleanLeft.push(lOp)
40
+ hasConflict = 'equal'
41
+ } else {
42
+ hasConflict = true
43
+ conflicts.push({ left: lOp, right: rOp })
44
+ }
45
+ }
46
+
47
+ if (!hasConflict) {
48
+ cleanLeft.push(lOp)
49
+ }
50
+ }
51
+
52
+ const cleanRight = []
53
+ for (let ri = 0; ri < rightDelta.length; ri++) {
54
+ if (!rightConsumed.has(ri)) cleanRight.push(rightDelta[ri])
55
+ }
56
+
57
+ const cleanOps = [...cleanLeft, ...cleanRight]
58
+ const doc = cleanOps.length > 0 ? patch(base, cleanOps) : structuredClone(base)
59
+
60
+ return { doc, conflicts }
61
+ }
62
+
63
+ function pathsOverlap(a, b) {
64
+ const min = Math.min(a.length, b.length)
65
+ for (let i = 0; i < min; i++) {
66
+ if (a[i] !== b[i]) return false
67
+ }
68
+ return true
69
+ }
70
+
71
+ function opsEqual(a, b) {
72
+ if (a.op !== b.op) return false
73
+ if (!pathsEqual(a.path, b.path)) return false
74
+ if (a.op === 'replace') return deepEqual(a.old, b.old) && deepEqual(a.new, b.new)
75
+ return deepEqual(a.value, b.value)
76
+ }
77
+
78
+ function pathsEqual(a, b) {
79
+ if (a.length !== b.length) return false
80
+ for (let i = 0; i < a.length; i++) {
81
+ if (a[i] !== b[i]) return false
82
+ }
83
+ return true
84
+ }
85
+
86
+ function deepEqual(a, b) {
87
+ if (a === b) return true
88
+ if (a === null || b === null) return a === b
89
+ if (typeof a !== typeof b) return false
90
+ if (typeof a !== 'object') return false
91
+
92
+ const aArr = Array.isArray(a)
93
+ const bArr = Array.isArray(b)
94
+ if (aArr !== bArr) return false
95
+
96
+ if (aArr) {
97
+ if (a.length !== b.length) return false
98
+ for (let i = 0; i < a.length; i++) {
99
+ if (!deepEqual(a[i], b[i])) return false
100
+ }
101
+ return true
102
+ }
103
+
104
+ const aKeys = Object.keys(a)
105
+ const bKeys = Object.keys(b)
106
+ if (aKeys.length !== bKeys.length) return false
107
+ for (const key of aKeys) {
108
+ if (!(key in b) || !deepEqual(a[key], b[key])) return false
109
+ }
110
+ return true
111
+ }
112
+
113
+ export { merge }
package/src/index.js ADDED
@@ -0,0 +1,14 @@
1
+ import { merge as fallbackMerge } from './fallback.js'
2
+
3
+ let merge = fallbackMerge
4
+ let backend = 'fallback'
5
+
6
+ try {
7
+ const wasm = await import('./wasm.js')
8
+ merge = wasm.merge
9
+ backend = 'wasm'
10
+ } catch {
11
+ // using fallback
12
+ }
13
+
14
+ export { merge, backend }
package/src/wasm.js ADDED
@@ -0,0 +1,50 @@
1
+ import { readFileSync } from 'fs'
2
+ import { fileURLToPath } from 'url'
3
+ import { dirname, join } from 'path'
4
+
5
+ const __dirname = dirname(fileURLToPath(import.meta.url))
6
+ const wasmPath = join(__dirname, '..', 'wasm', 'merge.wasm')
7
+ const wasmBuffer = readFileSync(wasmPath)
8
+ const wasmModule = new WebAssembly.Module(wasmBuffer)
9
+ const wasmInstance = new WebAssembly.Instance(wasmModule)
10
+ const wasm = wasmInstance.exports
11
+
12
+ const encoder = new TextEncoder()
13
+ const decoder = new TextDecoder()
14
+
15
+ function callWasm(fn, ...jsonArgs) {
16
+ const buffers = jsonArgs.map(arg => encoder.encode(JSON.stringify(arg)))
17
+ const ptrs = buffers.map(buf => {
18
+ const ptr = wasm.alloc(buf.length)
19
+ if (!ptr) throw new Error('wasm allocation failed')
20
+ new Uint8Array(wasm.memory.buffer).set(buf, ptr)
21
+ return { ptr, len: buf.length }
22
+ })
23
+
24
+ const args = ptrs.flatMap(p => [p.ptr, p.len])
25
+ const resultLen = fn(...args)
26
+
27
+ for (const p of ptrs) wasm.dealloc(p.ptr, p.len)
28
+
29
+ if (resultLen < 0) throw new Error('wasm merge failed')
30
+
31
+ const resultPtr = wasm.getResultPtr()
32
+ const resultBytes = new Uint8Array(wasm.memory.buffer.slice(resultPtr, resultPtr + resultLen))
33
+ const result = JSON.parse(decoder.decode(resultBytes))
34
+
35
+ wasm.freeResult()
36
+ return result
37
+ }
38
+
39
+ /**
40
+ * Three-way merge of JSON-compatible values using the Zig WASM engine.
41
+ * @param {*} base - Common ancestor
42
+ * @param {*} left - Left revision
43
+ * @param {*} right - Right revision
44
+ * @returns {{ doc: *, conflicts: Array<{ left: Object, right: Object }> }}
45
+ */
46
+ function merge(base, left, right) {
47
+ return callWasm(wasm.merge, base, left, right)
48
+ }
49
+
50
+ export { merge }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Three-way merge of JSON-compatible values.
3
+ * @param {*} base - Common ancestor
4
+ * @param {*} left - Left revision
5
+ * @param {*} right - Right revision
6
+ * @returns {{ doc: *, conflicts: Array<{ left: Object, right: Object }> }}
7
+ */
8
+ export function merge(base: any, left: any, right: any): {
9
+ doc: any;
10
+ conflicts: Array<{
11
+ left: any;
12
+ right: any;
13
+ }>;
14
+ };
@@ -0,0 +1,3 @@
1
+ export let merge: typeof fallbackMerge;
2
+ export let backend: string;
3
+ import { merge as fallbackMerge } from './fallback.js';
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Three-way merge of JSON-compatible values using the Zig WASM engine.
3
+ * @param {*} base - Common ancestor
4
+ * @param {*} left - Left revision
5
+ * @param {*} right - Right revision
6
+ * @returns {{ doc: *, conflicts: Array<{ left: Object, right: Object }> }}
7
+ */
8
+ export function merge(base: any, left: any, right: any): {
9
+ doc: any;
10
+ conflicts: Array<{
11
+ left: any;
12
+ right: any;
13
+ }>;
14
+ };
Binary file