Skip to content

Commit de2881a

Browse files
ThorFuchsclaude
andcommitted
Add JSONHTML visual difference page over a shared structural walker
renderDifference(from:to:) renders two exact values as one static, script-free combined tree with added/removed/changed markers, a linked change list, a CSS-only changes-only toggle and native downloads of the RFC 6902 patch, source and target. The comparison moves into a package walker in JSON so JSONPatch.difference and JSONHTML share it and JSONHTML keeps depending on JSON only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 3ad1225 commit de2881a

14 files changed

Lines changed: 776 additions & 96 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,15 @@
1919
applies to the source to give the target, but is not minimal and never uses
2020
`move`, `copy` or `test`. One cumulative patch ledger covers both inputs and
2121
the produced operations.
22+
- Add `JSONHTMLRenderer.renderDifference(from:to:)` and
23+
`renderDifferenceWithReport`, a static, script-free page that shows two exact
24+
values as one combined tree. Added, removed and changed values carry
25+
text markers as well as color; equal values stay visible but collapsed. A
26+
summary, a change list linked by JSON Pointer, a CSS-only "Show changes only"
27+
toggle and native downloads of the RFC 6902 patch, the source and the target
28+
complete the page. Its CSP authorizes the two stylesheets by hash and sets
29+
`script-src 'none'`. The comparison is a package walker in JSON shared with
30+
`JSONPatch.difference`, so JSONHTML still depends on JSON only.
2231

2332
## Unreleased — 1.9.1 hygiene
2433

‎Documentation/Qualification/TestDiscovery.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
"JSONStreamingTests": 36,
88
"JSONPatchTests": 22,
99
"JSONIntegrationTests": 45,
10-
"JSONHTMLTests": 97,
10+
"JSONHTMLTests": 103,
1111
"JSONBridgesTests": 10,
1212
"JSONCLITests": 88,
1313
"JSONNavigationTests": 57,
@@ -79,7 +79,7 @@
7979
"JSONStreamingTests": 36,
8080
"JSONPatchTests": 22,
8181
"JSONIntegrationTests": 45,
82-
"JSONHTMLTests": 81,
82+
"JSONHTMLTests": 87,
8383
"JSONBridgesTests": 10,
8484
"JSONCLITests": 88,
8585
"JSONNavigationTests": 57,
@@ -95,7 +95,7 @@
9595
"JSONStreamingTests": 36,
9696
"JSONPatchTests": 22,
9797
"JSONIntegrationTests": 45,
98-
"JSONHTMLTests": 81,
98+
"JSONHTMLTests": 87,
9999
"JSONBridgesTests": 10,
100100
"JSONNavigationTests": 57,
101101
"JSONSchemaExamplesTests": 98,

‎Scripts/ci.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -533,7 +533,7 @@ def check_result(command, code, log, events=None):
533533
if command[:3] == ['python3', '-B', 'Scripts/qualify_navigation.py']:
534534
passed = passed and 'NAVIGATION_COMPILER passed configurations=2 consumer_cases=18 negative_probes=8' in log.splitlines()
535535
if command[:3] == ['python3', '-B', 'Scripts/verify_html_assets.py']:
536-
passed = passed and 'JSONHTML_ASSETS passed count=2' in log.splitlines()
536+
passed = passed and 'JSONHTML_ASSETS passed count=3' in log.splitlines()
537537
if 'BrowserFixtures' in command:
538538
passed = passed and 'JSONHTML_BROWSER_FIXTURES passed count=15' in log.splitlines()
539539
if command[:3] == ['python3', '-B', 'Scripts/qualify_html_browser.py']:

‎Scripts/verify_html_assets.py‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,14 @@ def expected(root):
99
js = (root / 'Sources/JSONHTML/Assets/Interactive.js').read_text().rstrip('\n')
1010
def digest(t): return base64.b64encode(hashlib.sha256(t.encode()).digest()).decode()
1111
return '// SPDX-License-Identifier: Apache-2.0\n// Generated from Assets; verify with Scripts/verify_html_assets.py.\npackage enum JSONHTMLInteractiveAssets {\n package static let base64Alphabet: [UInt8] = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".utf8)\n package static let css = #"""\n' + css + '\n"""#\n package static let script = #"""\n' + js + '\n"""#\n package static let styleHash = "' + digest(base + '\n' + css) + '"\n package static let scriptHash = "' + digest(js) + '"\n}\n'
12+
def expected_difference(root):
13+
css = (root / 'Sources/JSONHTML/Assets/Difference.css').read_text().rstrip('\n')
14+
digest = base64.b64encode(hashlib.sha256(css.encode()).digest()).decode()
15+
return '// SPDX-License-Identifier: Apache-2.0\n// Fixed difference CSS from Assets/Difference.css; CSP hashes exactly these UTF-8 bytes.\npackage enum JSONHTMLDifferenceAssets {\n package static let css = #"""\n' + css + '\n"""#\n package static let cssHash = "' + digest + '"\n}\n'
1216
if __name__ == '__main__':
13-
target = ROOT / 'Sources/JSONHTML/JSONHTMLInteractiveAssets.swift'
14-
text = expected(ROOT)
15-
if sys.argv[1:] == ['--write']: target.write_text(text)
16-
if target.read_text() != text: raise SystemExit('Interactive asset mirror or CSP hash mismatch')
17-
print('JSONHTML_ASSETS passed count=2')
17+
mirrors = [(ROOT / 'Sources/JSONHTML/JSONHTMLInteractiveAssets.swift', expected(ROOT), 'Interactive'),
18+
(ROOT / 'Sources/JSONHTML/JSONHTMLDifferenceAssets.swift', expected_difference(ROOT), 'Difference')]
19+
for target, text, name in mirrors:
20+
if sys.argv[1:] == ['--write']: target.write_text(text)
21+
if target.read_text() != text: raise SystemExit(f'{name} asset mirror or CSP hash mismatch')
22+
print('JSONHTML_ASSETS passed count=3')
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
// Original bounded structural difference shared by JSONPatch and JSONHTML.
3+
4+
/// One step of a merged walk over two values, in display order.
5+
///
6+
/// A value event (`same`, `added`, `removed`, `replaced`, `beginObject`,
7+
/// `beginArray`) follows a `member` or `element` event, except at the root.
8+
package enum JSONDifferenceEvent: Sendable {
9+
/// The value is equal on both sides (exact model equality).
10+
case same(JSON)
11+
/// The value exists only in the target.
12+
case added(JSON)
13+
/// The value exists only in the source.
14+
case removed(JSON)
15+
/// Different kinds or unequal scalars: the source value is replaced.
16+
case replaced(source: JSON, target: JSON)
17+
/// Both sides are unequal objects; member events follow until `endObject`.
18+
case beginObject
19+
case endObject
20+
/// Both sides are unequal arrays; element events follow until `endArray`.
21+
case beginArray
22+
case endArray
23+
/// The next value event belongs to this object member.
24+
case member(JSONKey)
25+
/// The next value event belongs to this element; the position is nil on the side that lacks it.
26+
case element(source: Int?, target: Int?)
27+
/// A run of equal array elements, kept as one event.
28+
case sameElements(ArraySlice<JSON>, sourceStart: Int, targetStart: Int)
29+
}
30+
31+
/// A neutral RFC 6902 operation produced from the shared difference.
32+
package struct JSONDifferenceOperation: Sendable {
33+
package enum Kind: Sendable { case add, remove, replace }
34+
package let kind: Kind
35+
package let path: [JSONKey]
36+
package let value: JSON?
37+
}
38+
39+
/// Walks two admitted values and yields ``JSONDifferenceEvent``s on the caller's meter.
40+
///
41+
/// Objects list source members in source order (compared or removed), then target-only
42+
/// members in target order. Arrays keep the longest equal prefix and suffix, compare
43+
/// the remaining elements by position, then list surplus source elements (removed)
44+
/// and surplus target elements (added) in ascending order.
45+
package struct JSONDifferenceWalker {
46+
private enum Frame {
47+
case compare(JSON, JSON)
48+
case object(JSONObject, JSONObject, phase: Int, index: Int)
49+
case array([JSON], [JSON], prefix: Int, suffix: Int, step: Int)
50+
}
51+
private var frames: [Frame]
52+
private var queued: [JSONDifferenceEvent] = []
53+
private var started = false
54+
55+
package init(source: JSON, target: JSON) { frames = [.compare(source, target)] }
56+
57+
package mutating func next(meter: inout JSONWorkMeter) throws -> JSONDifferenceEvent? {
58+
if !started { try meter.retain(JSONLogicalWeights.frame); started = true }
59+
while true {
60+
try meter.work()
61+
if !queued.isEmpty { return queued.removeFirst() }
62+
guard let frame = frames.popLast() else { return nil }
63+
try meter.release(JSONLogicalWeights.frame)
64+
switch frame {
65+
case .compare(let a, let b):
66+
if try JSONComparison.equals(a, b, meter: &meter) { return .same(b) }
67+
switch (a, b) {
68+
case (.object(let x), .object(let y)):
69+
try push(.object(x, y, phase: 0, index: 0), meter: &meter); return .beginObject
70+
case (.array(let x), .array(let y)):
71+
let shared = min(x.count, y.count)
72+
var prefix = 0
73+
while prefix < shared, try JSONComparison.equals(x[prefix], y[prefix], meter: &meter) { prefix += 1 }
74+
var suffix = 0
75+
while suffix < shared - prefix,
76+
try JSONComparison.equals(x[x.count - 1 - suffix], y[y.count - 1 - suffix], meter: &meter) { suffix += 1 }
77+
try push(.array(x, y, prefix: prefix, suffix: suffix, step: 0), meter: &meter); return .beginArray
78+
default:
79+
return .replaced(source: a, target: b)
80+
}
81+
case .object(let a, let b, let phase, let index):
82+
if phase == 0, index < a.count {
83+
let member = a[index]
84+
try push(.object(a, b, phase: 0, index: index + 1), meter: &meter)
85+
if let counterpart = try b.lookup(member.key.string, meter: &meter) {
86+
try push(.compare(member.value, counterpart), meter: &meter)
87+
} else {
88+
queued.append(.removed(member.value))
89+
}
90+
return .member(member.key)
91+
}
92+
var position = phase == 0 ? 0 : index
93+
while position < b.count {
94+
try meter.work()
95+
let member = b[position]; position += 1
96+
if try a.lookup(member.key.string, meter: &meter) == nil {
97+
try push(.object(a, b, phase: 1, index: position), meter: &meter)
98+
queued.append(.added(member.value))
99+
return .member(member.key)
100+
}
101+
}
102+
return .endObject
103+
case .array(let a, let b, let prefix, let suffix, let step):
104+
let middleA = a.count - prefix - suffix, middleB = b.count - prefix - suffix
105+
let paired = min(middleA, middleB)
106+
// Steps: 0 prefix run, then pairs, removals, additions, suffix run, end.
107+
var next = step
108+
if next == 0 {
109+
next = 1
110+
if prefix > 0 {
111+
try push(.array(a, b, prefix: prefix, suffix: suffix, step: next), meter: &meter)
112+
return .sameElements(b[0..<prefix], sourceStart: 0, targetStart: 0)
113+
}
114+
}
115+
let pairedEnd = 1 + paired, removedEnd = pairedEnd + middleA - paired, addedEnd = removedEnd + middleB - paired
116+
if next < pairedEnd {
117+
let position = prefix + next - 1
118+
try push(.array(a, b, prefix: prefix, suffix: suffix, step: next + 1), meter: &meter)
119+
try push(.compare(a[position], b[position]), meter: &meter)
120+
return .element(source: position, target: position)
121+
}
122+
if next < removedEnd {
123+
let position = prefix + paired + (next - pairedEnd)
124+
try push(.array(a, b, prefix: prefix, suffix: suffix, step: next + 1), meter: &meter)
125+
queued.append(.removed(a[position]))
126+
return .element(source: position, target: nil)
127+
}
128+
if next < addedEnd {
129+
let position = prefix + paired + (next - removedEnd)
130+
try push(.array(a, b, prefix: prefix, suffix: suffix, step: next + 1), meter: &meter)
131+
queued.append(.added(b[position]))
132+
return .element(source: nil, target: position)
133+
}
134+
if next == addedEnd, suffix > 0 {
135+
try push(.array(a, b, prefix: prefix, suffix: suffix, step: next + 1), meter: &meter)
136+
return .sameElements(b[(b.count - suffix)...], sourceStart: a.count - suffix, targetStart: b.count - suffix)
137+
}
138+
return .endArray
139+
}
140+
}
141+
}
142+
private mutating func push(_ frame: Frame, meter: inout JSONWorkMeter) throws {
143+
try meter.retain(JSONLogicalWeights.frame); frames.append(frame)
144+
}
145+
146+
/// RFC 6902 operations for the same difference, in an order that applies cleanly:
147+
/// within an array, paired changes first, then removals from the highest index
148+
/// down, then additions in ascending order.
149+
package static func operations(from source: JSON, to target: JSON, meter: inout JSONWorkMeter) throws -> [JSONDifferenceOperation] {
150+
struct Level { var removals: [JSONDifferenceOperation] = []; var additions: [JSONDifferenceOperation] = [] }
151+
var walker = JSONDifferenceWalker(source: source, target: target)
152+
var operations: [JSONDifferenceOperation] = []
153+
var path: [JSONKey] = [], levels: [Level?] = []
154+
var pendingKey: JSONKey? = nil, pendingElement = false
155+
func emit(_ operation: JSONDifferenceOperation, meter: inout JSONWorkMeter) throws {
156+
try meter.require(.operations, UInt64(operations.count) + 1)
157+
try meter.retain(JSONLogicalWeights.frame); operations.append(operation)
158+
}
159+
func childPath(meter: inout JSONWorkMeter) throws -> [JSONKey] {
160+
guard let pendingKey else { return path }
161+
try meter.require(.pointerTokens, UInt64(path.count) + 1)
162+
for _ in path { try meter.work() }
163+
try meter.retain(16)
164+
return path + [pendingKey]
165+
}
166+
func deferred(_ operation: JSONDifferenceOperation, removal: Bool, meter: inout JSONWorkMeter) throws {
167+
guard pendingElement, let last = levels.indices.last, levels[last] != nil else { return try emit(operation, meter: &meter) }
168+
try meter.retain(JSONLogicalWeights.frame)
169+
if removal { levels[last]!.removals.append(operation) } else { levels[last]!.additions.append(operation) }
170+
}
171+
while let event = try walker.next(meter: &meter) {
172+
switch event {
173+
case .member(let key): pendingKey = key; pendingElement = false
174+
case .element(let s, let t):
175+
pendingKey = try JSONKey(String(s ?? t ?? 0), meter: &meter); pendingElement = s == nil || t == nil
176+
case .same, .sameElements: pendingKey = nil; pendingElement = false
177+
case .replaced(_, let value):
178+
try emit(.init(kind: .replace, path: childPath(meter: &meter), value: value), meter: &meter)
179+
pendingKey = nil; pendingElement = false
180+
case .removed:
181+
try deferred(.init(kind: .remove, path: childPath(meter: &meter), value: nil), removal: true, meter: &meter)
182+
pendingKey = nil; pendingElement = false
183+
case .added(let value):
184+
try deferred(.init(kind: .add, path: childPath(meter: &meter), value: value), removal: false, meter: &meter)
185+
pendingKey = nil; pendingElement = false
186+
case .beginObject, .beginArray:
187+
path = try childPath(meter: &meter); pendingKey = nil; pendingElement = false
188+
try meter.retain(JSONLogicalWeights.frame)
189+
if case .beginArray = event { levels.append(Level()) } else { levels.append(nil) }
190+
case .endObject, .endArray:
191+
if let level = levels.removeLast() {
192+
for operation in level.removals.reversed() { try emit(operation, meter: &meter) }
193+
for operation in level.additions { try emit(operation, meter: &meter) }
194+
}
195+
try meter.release(JSONLogicalWeights.frame)
196+
if !path.isEmpty { path.removeLast() }
197+
}
198+
}
199+
return operations
200+
}
201+
}

‎Sources/JSONCLIEngine/CLIBuildIdentity.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@
22
// Generated by Scripts/generate_cli_identity.py; excludes this file.
33
// SHA-256 of the ordered Package.swift + Sources content manifest (DocC catalogs excluded), not a Git commit.
44
package enum CLIBuildIdentity {
5-
package static let revision = "sha256:ab828e1c70d46c10f7a6431f5e9ef22ac469b8609778e3e99b7a0f6af77891ff"
5+
package static let revision = "sha256:dafab040289a71fed6924ffe8aa7a7273e6315c5701d1fd35fd5d1b812a52ccd"
66
package static let kind = "source-sha256"
77
}

‎Sources/JSONHTML/Assets/Difference.css‎

Lines changed: 15 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)