diff --git a/CHANGELOG.md b/CHANGELOG.md index 84238b8..dd015f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,15 @@ applies to the source to give the target, but is not minimal and never uses `move`, `copy` or `test`. One cumulative patch ledger covers both inputs and the produced operations. +- Add `JSONHTMLRenderer.renderDifference(from:to:)` and + `renderDifferenceWithReport`, a static, script-free page that shows two exact + values as one combined tree. Added, removed and changed values carry + text markers as well as color; equal values stay visible but collapsed. A + summary, a change list linked by JSON Pointer, a CSS-only "Show changes only" + toggle and native downloads of the RFC 6902 patch, the source and the target + complete the page. Its CSP authorizes the two stylesheets by hash and sets + `script-src 'none'`. The comparison is a package walker in JSON shared with + `JSONPatch.difference`, so JSONHTML still depends on JSON only. ## Unreleased — 1.9.1 hygiene diff --git a/Documentation/Qualification/TestDiscovery.json b/Documentation/Qualification/TestDiscovery.json index e7aa7e0..cc5bedf 100644 --- a/Documentation/Qualification/TestDiscovery.json +++ b/Documentation/Qualification/TestDiscovery.json @@ -7,7 +7,7 @@ "JSONStreamingTests": 36, "JSONPatchTests": 22, "JSONIntegrationTests": 45, - "JSONHTMLTests": 97, + "JSONHTMLTests": 103, "JSONBridgesTests": 10, "JSONCLITests": 88, "JSONNavigationTests": 57, @@ -79,7 +79,7 @@ "JSONStreamingTests": 36, "JSONPatchTests": 22, "JSONIntegrationTests": 45, - "JSONHTMLTests": 81, + "JSONHTMLTests": 87, "JSONBridgesTests": 10, "JSONCLITests": 88, "JSONNavigationTests": 57, @@ -95,7 +95,7 @@ "JSONStreamingTests": 36, "JSONPatchTests": 22, "JSONIntegrationTests": 45, - "JSONHTMLTests": 81, + "JSONHTMLTests": 87, "JSONBridgesTests": 10, "JSONNavigationTests": 57, "JSONSchemaExamplesTests": 98, diff --git a/Scripts/ci.py b/Scripts/ci.py index 029f9c9..f10f21c 100644 --- a/Scripts/ci.py +++ b/Scripts/ci.py @@ -533,7 +533,7 @@ def check_result(command, code, log, events=None): if command[:3] == ['python3', '-B', 'Scripts/qualify_navigation.py']: passed = passed and 'NAVIGATION_COMPILER passed configurations=2 consumer_cases=18 negative_probes=8' in log.splitlines() if command[:3] == ['python3', '-B', 'Scripts/verify_html_assets.py']: - passed = passed and 'JSONHTML_ASSETS passed count=2' in log.splitlines() + passed = passed and 'JSONHTML_ASSETS passed count=3' in log.splitlines() if 'BrowserFixtures' in command: passed = passed and 'JSONHTML_BROWSER_FIXTURES passed count=15' in log.splitlines() if command[:3] == ['python3', '-B', 'Scripts/qualify_html_browser.py']: diff --git a/Scripts/verify_html_assets.py b/Scripts/verify_html_assets.py index 8258e0b..3d04561 100644 --- a/Scripts/verify_html_assets.py +++ b/Scripts/verify_html_assets.py @@ -9,9 +9,14 @@ def expected(root): js = (root / 'Sources/JSONHTML/Assets/Interactive.js').read_text().rstrip('\n') def digest(t): return base64.b64encode(hashlib.sha256(t.encode()).digest()).decode() 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' +def expected_difference(root): + css = (root / 'Sources/JSONHTML/Assets/Difference.css').read_text().rstrip('\n') + digest = base64.b64encode(hashlib.sha256(css.encode()).digest()).decode() + 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' if __name__ == '__main__': - target = ROOT / 'Sources/JSONHTML/JSONHTMLInteractiveAssets.swift' - text = expected(ROOT) - if sys.argv[1:] == ['--write']: target.write_text(text) - if target.read_text() != text: raise SystemExit('Interactive asset mirror or CSP hash mismatch') - print('JSONHTML_ASSETS passed count=2') + mirrors = [(ROOT / 'Sources/JSONHTML/JSONHTMLInteractiveAssets.swift', expected(ROOT), 'Interactive'), + (ROOT / 'Sources/JSONHTML/JSONHTMLDifferenceAssets.swift', expected_difference(ROOT), 'Difference')] + for target, text, name in mirrors: + if sys.argv[1:] == ['--write']: target.write_text(text) + if target.read_text() != text: raise SystemExit(f'{name} asset mirror or CSP hash mismatch') + print('JSONHTML_ASSETS passed count=3') diff --git a/Sources/JSON/Value/JSONStructuralDifference.swift b/Sources/JSON/Value/JSONStructuralDifference.swift new file mode 100644 index 0000000..c78adba --- /dev/null +++ b/Sources/JSON/Value/JSONStructuralDifference.swift @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: Apache-2.0 +// Original bounded structural difference shared by JSONPatch and JSONHTML. + +/// One step of a merged walk over two values, in display order. +/// +/// A value event (`same`, `added`, `removed`, `replaced`, `beginObject`, +/// `beginArray`) follows a `member` or `element` event, except at the root. +package enum JSONDifferenceEvent: Sendable { + /// The value is equal on both sides (exact model equality). + case same(JSON) + /// The value exists only in the target. + case added(JSON) + /// The value exists only in the source. + case removed(JSON) + /// Different kinds or unequal scalars: the source value is replaced. + case replaced(source: JSON, target: JSON) + /// Both sides are unequal objects; member events follow until `endObject`. + case beginObject + case endObject + /// Both sides are unequal arrays; element events follow until `endArray`. + case beginArray + case endArray + /// The next value event belongs to this object member. + case member(JSONKey) + /// The next value event belongs to this element; the position is nil on the side that lacks it. + case element(source: Int?, target: Int?) + /// A run of equal array elements, kept as one event. + case sameElements(ArraySlice, sourceStart: Int, targetStart: Int) +} + +/// A neutral RFC 6902 operation produced from the shared difference. +package struct JSONDifferenceOperation: Sendable { + package enum Kind: Sendable { case add, remove, replace } + package let kind: Kind + package let path: [JSONKey] + package let value: JSON? +} + +/// Walks two admitted values and yields ``JSONDifferenceEvent``s on the caller's meter. +/// +/// Objects list source members in source order (compared or removed), then target-only +/// members in target order. Arrays keep the longest equal prefix and suffix, compare +/// the remaining elements by position, then list surplus source elements (removed) +/// and surplus target elements (added) in ascending order. +package struct JSONDifferenceWalker { + private enum Frame { + case compare(JSON, JSON) + case object(JSONObject, JSONObject, phase: Int, index: Int) + case array([JSON], [JSON], prefix: Int, suffix: Int, step: Int) + } + private var frames: [Frame] + private var queued: [JSONDifferenceEvent] = [] + private var started = false + + package init(source: JSON, target: JSON) { frames = [.compare(source, target)] } + + package mutating func next(meter: inout JSONWorkMeter) throws -> JSONDifferenceEvent? { + if !started { try meter.retain(JSONLogicalWeights.frame); started = true } + while true { + try meter.work() + if !queued.isEmpty { return queued.removeFirst() } + guard let frame = frames.popLast() else { return nil } + try meter.release(JSONLogicalWeights.frame) + switch frame { + case .compare(let a, let b): + if try JSONComparison.equals(a, b, meter: &meter) { return .same(b) } + switch (a, b) { + case (.object(let x), .object(let y)): + try push(.object(x, y, phase: 0, index: 0), meter: &meter); return .beginObject + case (.array(let x), .array(let y)): + let shared = min(x.count, y.count) + var prefix = 0 + while prefix < shared, try JSONComparison.equals(x[prefix], y[prefix], meter: &meter) { prefix += 1 } + var suffix = 0 + while suffix < shared - prefix, + try JSONComparison.equals(x[x.count - 1 - suffix], y[y.count - 1 - suffix], meter: &meter) { suffix += 1 } + try push(.array(x, y, prefix: prefix, suffix: suffix, step: 0), meter: &meter); return .beginArray + default: + return .replaced(source: a, target: b) + } + case .object(let a, let b, let phase, let index): + if phase == 0, index < a.count { + let member = a[index] + try push(.object(a, b, phase: 0, index: index + 1), meter: &meter) + if let counterpart = try b.lookup(member.key.string, meter: &meter) { + try push(.compare(member.value, counterpart), meter: &meter) + } else { + queued.append(.removed(member.value)) + } + return .member(member.key) + } + var position = phase == 0 ? 0 : index + while position < b.count { + try meter.work() + let member = b[position]; position += 1 + if try a.lookup(member.key.string, meter: &meter) == nil { + try push(.object(a, b, phase: 1, index: position), meter: &meter) + queued.append(.added(member.value)) + return .member(member.key) + } + } + return .endObject + case .array(let a, let b, let prefix, let suffix, let step): + let middleA = a.count - prefix - suffix, middleB = b.count - prefix - suffix + let paired = min(middleA, middleB) + // Steps: 0 prefix run, then pairs, removals, additions, suffix run, end. + var next = step + if next == 0 { + next = 1 + if prefix > 0 { + try push(.array(a, b, prefix: prefix, suffix: suffix, step: next), meter: &meter) + return .sameElements(b[0.. 0 { + try push(.array(a, b, prefix: prefix, suffix: suffix, step: next + 1), meter: &meter) + return .sameElements(b[(b.count - suffix)...], sourceStart: a.count - suffix, targetStart: b.count - suffix) + } + return .endArray + } + } + } + private mutating func push(_ frame: Frame, meter: inout JSONWorkMeter) throws { + try meter.retain(JSONLogicalWeights.frame); frames.append(frame) + } + + /// RFC 6902 operations for the same difference, in an order that applies cleanly: + /// within an array, paired changes first, then removals from the highest index + /// down, then additions in ascending order. + package static func operations(from source: JSON, to target: JSON, meter: inout JSONWorkMeter) throws -> [JSONDifferenceOperation] { + struct Level { var removals: [JSONDifferenceOperation] = []; var additions: [JSONDifferenceOperation] = [] } + var walker = JSONDifferenceWalker(source: source, target: target) + var operations: [JSONDifferenceOperation] = [] + var path: [JSONKey] = [], levels: [Level?] = [] + var pendingKey: JSONKey? = nil, pendingElement = false + func emit(_ operation: JSONDifferenceOperation, meter: inout JSONWorkMeter) throws { + try meter.require(.operations, UInt64(operations.count) + 1) + try meter.retain(JSONLogicalWeights.frame); operations.append(operation) + } + func childPath(meter: inout JSONWorkMeter) throws -> [JSONKey] { + guard let pendingKey else { return path } + try meter.require(.pointerTokens, UInt64(path.count) + 1) + for _ in path { try meter.work() } + try meter.retain(16) + return path + [pendingKey] + } + func deferred(_ operation: JSONDifferenceOperation, removal: Bool, meter: inout JSONWorkMeter) throws { + guard pendingElement, let last = levels.indices.last, levels[last] != nil else { return try emit(operation, meter: &meter) } + try meter.retain(JSONLogicalWeights.frame) + if removal { levels[last]!.removals.append(operation) } else { levels[last]!.additions.append(operation) } + } + while let event = try walker.next(meter: &meter) { + switch event { + case .member(let key): pendingKey = key; pendingElement = false + case .element(let s, let t): + pendingKey = try JSONKey(String(s ?? t ?? 0), meter: &meter); pendingElement = s == nil || t == nil + case .same, .sameElements: pendingKey = nil; pendingElement = false + case .replaced(_, let value): + try emit(.init(kind: .replace, path: childPath(meter: &meter), value: value), meter: &meter) + pendingKey = nil; pendingElement = false + case .removed: + try deferred(.init(kind: .remove, path: childPath(meter: &meter), value: nil), removal: true, meter: &meter) + pendingKey = nil; pendingElement = false + case .added(let value): + try deferred(.init(kind: .add, path: childPath(meter: &meter), value: value), removal: false, meter: &meter) + pendingKey = nil; pendingElement = false + case .beginObject, .beginArray: + path = try childPath(meter: &meter); pendingKey = nil; pendingElement = false + try meter.retain(JSONLogicalWeights.frame) + if case .beginArray = event { levels.append(Level()) } else { levels.append(nil) } + case .endObject, .endArray: + if let level = levels.removeLast() { + for operation in level.removals.reversed() { try emit(operation, meter: &meter) } + for operation in level.additions { try emit(operation, meter: &meter) } + } + try meter.release(JSONLogicalWeights.frame) + if !path.isEmpty { path.removeLast() } + } + } + return operations + } +} diff --git a/Sources/JSONCLIEngine/CLIBuildIdentity.swift b/Sources/JSONCLIEngine/CLIBuildIdentity.swift index 136f916..5e2905f 100644 --- a/Sources/JSONCLIEngine/CLIBuildIdentity.swift +++ b/Sources/JSONCLIEngine/CLIBuildIdentity.swift @@ -2,6 +2,6 @@ // Generated by Scripts/generate_cli_identity.py; excludes this file. // SHA-256 of the ordered Package.swift + Sources content manifest (DocC catalogs excluded), not a Git commit. package enum CLIBuildIdentity { - package static let revision = "sha256:ab828e1c70d46c10f7a6431f5e9ef22ac469b8609778e3e99b7a0f6af77891ff" + package static let revision = "sha256:dafab040289a71fed6924ffe8aa7a7273e6315c5701d1fd35fd5d1b812a52ccd" package static let kind = "source-sha256" } diff --git a/Sources/JSONHTML/Assets/Difference.css b/Sources/JSONHTML/Assets/Difference.css new file mode 100644 index 0000000..5b75c81 --- /dev/null +++ b/Sources/JSONHTML/Assets/Difference.css @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: Apache-2.0; Swift-JSON difference asset v1 */ +.diff{--add:#1a7f37;--add-bg:#dafbe1;--del:#b42318;--del-bg:#ffebe9;--chg:#9a6700;--chg-bg:#fff4d6} +.diff.dark{--add:#5fd88a;--add-bg:#12361f;--del:#ff8f87;--del-bg:#45191a;--chg:#f2c45b;--chg-bg:#3a2d0d} +@media(prefers-color-scheme:dark){.diff.automatic{--add:#5fd88a;--add-bg:#12361f;--del:#ff8f87;--del-bg:#45191a;--chg:#f2c45b;--chg-bg:#3a2d0d}} +.diff .diff-summary{display:flex;gap:.75rem;flex-wrap:wrap}.diff .diff-count{font-weight:600;padding:.1rem .5rem;border-radius:.4rem} +.diff .diff-count.diff-added{color:var(--add);background:var(--add-bg)}.diff .diff-count.diff-removed{color:var(--del);background:var(--del-bg)}.diff .diff-count.diff-changed{color:var(--chg);background:var(--chg-bg)} +.diff .diff-downloads a{margin-right:1rem}.diff .diff-list{list-style:none;padding:0;margin:.4rem 0 0;display:grid;gap:.35rem} +.diff .diff-row{border-left:4px solid transparent;padding-left:.6rem}.diff .diff-row.diff-added{border-left-color:var(--add)}.diff .diff-row.diff-removed{border-left-color:var(--del)}.diff .diff-row.diff-changed{border-left-color:var(--chg)} +.diff ins{text-decoration:none;background:var(--add-bg);border-radius:.25rem}.diff del{text-decoration:line-through;background:var(--del-bg);border-radius:.25rem} +.diff .diff-value{margin:0;display:inline;white-space:pre-wrap;overflow-wrap:anywhere;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.diff pre.diff-value{display:block;padding:.3rem .45rem} +.diff .diff-mark{display:inline-block;width:1.2em;font-weight:700}.diff .diff-added>.diff-mark,.diff .diff-added>dd>.diff-mark{color:var(--add)}.diff .diff-removed>.diff-mark,.diff .diff-removed>dd>.diff-mark{color:var(--del)}.diff .diff-changed>.diff-mark,.diff .diff-changed>dd>.diff-mark{color:var(--chg)} +.diff .diff-arrow{padding:0 .3rem}.diff .diff-unchanged>summary{color:var(--muted);cursor:pointer}.diff .diff-changes li a{text-decoration:none}.diff .diff-changes li.diff-added a{color:var(--add)}.diff .diff-changes li.diff-removed a{color:var(--del)}.diff .diff-changes li.diff-changed a{color:var(--chg)} +.diff:has(#jd-only:checked) .diff-same{display:none}.diff .diff-row:target{outline:2px solid currentColor;outline-offset:2px} +@media(forced-colors:active){.diff ins,.diff del,.diff .diff-count{background:Canvas;color:CanvasText;border:1px solid CanvasText}.diff .diff-row{border-left-color:CanvasText}} +@media print{.diff .diff-filter,.diff .diff-downloads{display:none}.diff ins,.diff del{background:none}.diff ins{text-decoration:underline}} \ No newline at end of file diff --git a/Sources/JSONHTML/Documentation.docc/DifferenceRendering.md b/Sources/JSONHTML/Documentation.docc/DifferenceRendering.md new file mode 100644 index 0000000..2bd9c36 --- /dev/null +++ b/Sources/JSONHTML/Documentation.docc/DifferenceRendering.md @@ -0,0 +1,49 @@ +# Visual differences + +Render the structural difference between two exact values as one static page. + +## Overview + +``JSONHTMLRenderer/renderDifference(from:to:)`` shows `source` and `target` as one +combined tree. Members and elements that exist only in the target are marked +added, those only in the source are marked removed, and unequal scalars or values +of different kinds are shown as a change from the old value to the new one. +Unequal objects and arrays open into their members and elements. Equal values, +compared with the exact model's equality, stay visible but collapsed: `1.0` and +`1` are equal, and a different member order is not a change. + +The page uses the same comparison as `JSONPatch.difference(from:to:options:)` in +JSONPatch. Arrays keep their longest equal prefix and suffix and compare the +remaining elements by position. Elements are never matched as moves. + +Each marker carries visually hidden text ("Added: ", "Removed: ", "Changed from +… to "), so the difference does not depend on color. A summary counts the +changes, and a numbered list links every change by its JSON Pointer, in tree +order. A CSS-only "Show changes only" toggle hides unchanged rows. + +The page offers three native downloads: the RFC 6902 patch +(`application/json-patch+json`), the source and the target. The patch applies to +the source and yields a value equal to the target. Source and target keep their +exact original number lexemes. + +```swift +let page = try JSONHTMLRenderer(options: .init(title: "Release config")) + .renderDifference(from: before, to: after) +``` + +## Security and limits + +The difference page never contains script, whatever the presentation option. +Its Content Security Policy sets `script-src 'none'` and authorizes the shared +stylesheet and the difference stylesheet by their SHA-256 hashes. All input +text is escaped. + +One cumulative budget covers admission of both values, the comparison, the +patch and both downloads, and the final document. The configured +``JSONHTMLLimits`` apply, including document bytes and outline entries (one per +listed change). Cancellation is checked inside the walk. + +## Topics + +- ``JSONHTMLRenderer/renderDifference(from:to:)`` +- ``JSONHTMLRenderer/renderDifferenceWithReport(from:to:)`` diff --git a/Sources/JSONHTML/Documentation.docc/JSONHTML.md b/Sources/JSONHTML/Documentation.docc/JSONHTML.md index 2ac4ea3..f5ae0e5 100644 --- a/Sources/JSONHTML/Documentation.docc/JSONHTML.md +++ b/Sources/JSONHTML/Documentation.docc/JSONHTML.md @@ -15,6 +15,10 @@ downloads and complete printing use native prepared bytes. See . + Native JSON transfer and immutable prepared JSON/text/Markdown/static HTML, opt-in styled RTF and explicit main-actor PDF preparation are available since 1.3.0. PDF consumes prepared static HTML; typed caller annotations attach to exact @@ -34,6 +38,7 @@ browser heap, browser instruction quotas, process RSS or printing behavior. - - - +- - - - diff --git a/Sources/JSONHTML/JSONHTMLDifference.swift b/Sources/JSONHTML/JSONHTMLDifference.swift new file mode 100644 index 0000000..2eee2dd --- /dev/null +++ b/Sources/JSONHTML/JSONHTMLDifference.swift @@ -0,0 +1,343 @@ +// SPDX-License-Identifier: Apache-2.0 +// Original static, script-free rendering of a structural difference as one combined tree. +import Foundation +import JSON + +extension JSONHTMLRenderer { + /// Renders the difference between two values as one combined, script-free HTML tree. + /// + /// The page uses the same exact equality and structure as + /// `JSONPatch.difference(from:to:options:)`: equal decimals, decoded scalar keys + /// and order-independent objects are unchanged; objects compare by exact key; + /// arrays keep their equal prefix and suffix and compare the rest by position. + /// + /// Added values are marked `+` in ``, removed values `−` in `` at their + /// source position, and changed values show the source value followed by the + /// target value. Markers carry visually hidden text, so the view never relies on + /// color alone. Unchanged values and element runs are collapsed behind native + /// disclosures, and a CSS-only control hides them. A list of changes links to each + /// change by its JSON Pointer. The exact RFC 6902 patch, and both documents, can be + /// downloaded without JavaScript. + /// + /// The view is always static: ``JSONHTMLRenderingOptions/presentation``, + /// ``JSONHTMLRenderingOptions/layout`` and the preview settings are not used. + /// Title, theme, indentation and limits apply. Both values, the comparison and + /// the whole document share one cumulative core budget and the HTML capacities. + /// + /// - Returns: Owned UTF-8 HTML. + /// - Throws: HTML or core resource/configuration failure, or cancellation. + /// - Parameters: + /// - source: The earlier value. + /// - target: The later value. + public func renderDifference(from source: JSON, to target: JSON) throws -> Data { + try renderDifferenceWithReport(from: source, to: target).result + } + + /// Renders the difference with cumulative successful accounting, including the final Data copy. + /// + /// See ``renderDifference(from:to:)`` for the view. + /// + /// - Returns: Complete HTML bytes and rendering statistics. + /// - Throws: HTML or core resource/configuration failure, or cancellation. + /// - Parameters: + /// - source: The earlier value. + /// - target: The later value. + public func renderDifferenceWithReport(from source: JSON, to target: JSON) throws -> JSONHTMLRenderReport { + var meter = try JSONWorkMeter(limits: options.limits.core, domain: .writing) + let retainedAtEntry = meter.used(.retainedBytes) + let document: JSONHTMLDocumentBuffer + do { document = try renderDifferenceBody(source, target, meter: &meter) } + catch { + meter.recordFailure(error) + try meter.release(meter.used(.retainedBytes) - retainedAtEntry) + throw error + } + for _ in document.bytes { try meter.work(); try meter.retain(1) } + let result = Data(document.bytes) + try meter.release(UInt64(document.bytes.count)); try meter.checkpoint() + return .init(result: result, statistics: document.statistics(meter.statistics())) + } + + private enum DifferenceKind { case added, removed, changed } + private struct DifferenceChange { let kind: DifferenceKind; let path: [JSONLocationComponent] } + private enum DifferenceLabel { case key(JSONKey), element(source: Int?, target: Int?) } + + private func renderDifferenceBody(_ source: JSON, _ target: JSON, meter: inout JSONWorkMeter) throws -> JSONHTMLDocumentBuffer { + try meter.checkpoint() + try options.limits.validate() + guard (0...8).contains(options.indentation), (1...8).contains(options.tabWidth) else { throw JSONHTMLFailure.invalidConfiguration } + try JSONAdmission.text(options.title, meter: &meter) + for byte in options.title.utf8 { + try meter.work() + guard byte >= 32 && byte != 127 else { throw JSONHTMLFailure.invalidConfiguration } + } + try JSONAdmission.value(source, meter: &meter) + try meter.resetValueBounds(); try JSONAdmission.value(target, meter: &meter) + let writing = JSONWritingOptions(limits: options.limits.core, indentation: options.indentation, + numberStyle: .preserved, indentationUnit: options.indentationUnit) + + // Pass 1: the ordered list of changes, with their locations. + var changes: [DifferenceChange] = [] + do { + var walker = JSONDifferenceWalker(source: source, target: target) + var path: [JSONLocationComponent] = [], pending: JSONLocationComponent? = nil + func record(_ kind: DifferenceKind, meter: inout JSONWorkMeter) throws { + var location = path + if let pending { location.append(pending) } + for _ in location { try meter.work() } + try meter.retain(JSONLogicalWeights.frame + 16 * UInt64(location.count)) + changes.append(.init(kind: kind, path: location)) + } + while let event = try walker.next(meter: &meter) { + switch event { + case .member(let key): pending = .key(key) + case .element(let s, let t): pending = .index(t ?? s ?? 0) + case .same, .sameElements: pending = nil + case .added: try record(.added, meter: &meter); pending = nil + case .removed: try record(.removed, meter: &meter); pending = nil + case .replaced: try record(.changed, meter: &meter); pending = nil + case .beginObject, .beginArray: + if let pending { try meter.retain(16); path.append(pending) } + pending = nil + case .endObject, .endArray: if !path.isEmpty { path.removeLast() } + } + } + } + let added = changes.filter { $0.kind == .added }.count + let removed = changes.filter { $0.kind == .removed }.count + let changed = changes.count - added - removed + + var output = JSONHTMLDocumentBuffer(limits: options.limits) + try output.addDOM(40, meter: &meter) + try output.append("", meter: &meter) + try output.escaped(options.title, meter: &meter) + try output.append("

", meter: &meter) + try output.escaped(options.title, meter: &meter) + try output.append("

", meter: &meter) + if changes.isEmpty { + try output.append("No differences: both values are equal.", meter: &meter) + } else { + try output.append("", meter: &meter) + try output.decimal(UInt64(added), meter: &meter) + try output.append(" added ", meter: &meter) + try output.decimal(UInt64(removed), meter: &meter) + try output.append(" removed ", meter: &meter) + try output.decimal(UInt64(changed), meter: &meter) + try output.append(" changed", meter: &meter) + } + try output.append("

", meter: &meter) + + // Downloads: the exact patch and both documents, as native writer bytes. + let patch = try patchBytes(source, target, meter: &meter) + output.setCopyBytes(UInt64(patch.count)) + try output.addDOM(12, meter: &meter) + try output.append("

Download RFC 6902 patch", meter: &meter) + try meter.release(UInt64(patch.count)) + for (name, value) in [("source", source), ("target", target)] { + let bytes = try nativeBytes(value, options: writing, meter: &meter) + try output.append(" Download " + name + " JSON", meter: &meter) + try meter.release(UInt64(bytes.count)) + } + try output.append("

", meter: &meter) + if !changes.isEmpty { + try output.append("

", meter: &meter) + } + + try output.append("
", meter: &meter) + try differenceTree(source, target, writing: writing, output: &output, meter: &meter) + try output.append("
", meter: &meter) + if !changes.isEmpty { + try output.append("", meter: &meter) + } + try output.append("
\n", meter: &meter) + try meter.checkpoint() + return output + } + + private static func differenceClass(_ kind: DifferenceKind) -> String { + switch kind { case .added: "diff-added"; case .removed: "diff-removed"; case .changed: "diff-changed" } + } + private static func differenceWord(_ kind: DifferenceKind) -> String { + switch kind { case .added: "Added"; case .removed: "Removed"; case .changed: "Changed" } + } + + /// The RFC 6902 operations as compact native JSON bytes. + private func patchBytes(_ source: JSON, _ target: JSON, meter: inout JSONWorkMeter) throws -> [UInt8] { + let operations = try JSONDifferenceWalker.operations(from: source, to: target, meter: &meter) + var values: [JSON] = [] + for operation in operations { + try meter.work() + let pointer = try JSONPointer.decodedTokens(operation.path, meter: &meter).encodedString(meter: &meter) + let name = switch operation.kind { case .add: "add"; case .remove: "remove"; case .replace: "replace" } + var members = [JSONMember("op", value: .string(name)), JSONMember("path", value: .string(pointer))] + if let value = operation.value { members.append(JSONMember("value", value: value)) } + try meter.retain(JSONLogicalWeights.frame) + values.append(.object(try JSONObject.checked(members: members, meter: &meter))) + } + return try nativeBytes(.array(values), options: .init(limits: options.limits.core, numberStyle: .preserved), meter: &meter) + } + + /// Pass 2: the combined tree, with one anchor per change in the same order as pass 1. + private func differenceTree(_ source: JSON, _ target: JSON, writing: JSONWritingOptions, + output: inout JSONHTMLDocumentBuffer, meter: inout JSONWorkMeter) throws { + var walker = JSONDifferenceWalker(source: source, target: target) + var closers: [String] = [] + var inArray: [Bool] = [] + var pending: DifferenceLabel? = nil + var ordinal: UInt64 = 0 + func open(_ classes: String, change: Bool, output: inout JSONHTMLDocumentBuffer, meter: inout JSONWorkMeter) throws { + try output.addNode(meter: &meter) + try output.addDOM(8, meter: &meter) + let element = inArray.last == true + try output.append(element ? "
  • ", meter: &meter) + switch pending { + case .key(let key): + try output.append("
    ", meter: &meter) + try label(.key(key), output: &output, meter: &meter, searchable: false) + try output.append("
    ", meter: &meter) + case .element(let s, let t): + try output.append("", meter: &meter) + if let t { try output.append("#", meter: &meter); try output.decimal(UInt64(t), meter: &meter) } + else if let s { try output.append("was #", meter: &meter); try output.decimal(UInt64(s), meter: &meter) } + try output.append(" ", meter: &meter) + case nil: + try output.append("Root ", meter: &meter) + } + } + func close(output: inout JSONHTMLDocumentBuffer, meter: inout JSONWorkMeter) throws { + if case .key = pending { try output.append("
    ", meter: &meter) } + try output.append(inArray.last == true ? "
  • " : "", meter: &meter) + pending = nil + } + func mark(_ symbol: String, _ text: String, output: inout JSONHTMLDocumentBuffer, meter: inout JSONWorkMeter) throws { + try output.append("" + symbol + "" + text + "", meter: &meter) + } + func value(_ value: JSON, output: inout JSONHTMLDocumentBuffer, meter: inout JSONWorkMeter) throws { + let container: Bool + switch value { case .object, .array: container = true; default: container = false } + try output.addDOM(4, meter: &meter) + try output.append(container ? "
    " : "", meter: &meter)
    +            try highlighted(value, options: container ? writing : .init(limits: writing.limits, numberStyle: .preserved), output: &output, meter: &meter)
    +            try output.append(container ? "
    " : "", meter: &meter) + } + func summary(_ value: JSON) -> String { + switch value { + case .object(let o): "Unchanged object, \(o.count) member\(o.count == 1 ? "" : "s")" + case .array(let a): "Unchanged array, \(a.count) element\(a.count == 1 ? "" : "s")" + default: "Unchanged" + } + } + while let event = try walker.next(meter: &meter) { + switch event { + case .member(let key): pending = .key(key) + case .element(let s, let t): pending = .element(source: s, target: t) + case .same(let v): + try open("diff-same", change: false, output: &output, meter: &meter) + switch v { + case .object, .array: + try output.addDOM(3, meter: &meter) + try output.append("
    " + summary(v) + "", meter: &meter) + try value(v, output: &output, meter: &meter) + try output.append("
    ", meter: &meter) + default: try value(v, output: &output, meter: &meter) + } + try close(output: &output, meter: &meter) + case .sameElements(let run, let s, let t): + try output.addNode(meter: &meter); try output.addDOM(6, meter: &meter) + try output.append("
  • ", meter: &meter) + try output.append(run.count == 1 ? "Element #" : "Elements #", meter: &meter) + try output.decimal(UInt64(t), meter: &meter) + if run.count > 1 { try output.append("–#", meter: &meter); try output.decimal(UInt64(t + run.count - 1), meter: &meter) } + try output.append(" unchanged", meter: &meter) + if s != t { try output.append(" (was #", meter: &meter); try output.decimal(UInt64(s), meter: &meter); try output.append(")", meter: &meter) } + try output.append("
      ", meter: &meter) + for element in run { + try meter.work(); try output.addDOM(2, meter: &meter) + try output.append("
    1. ", meter: &meter); try value(element, output: &output, meter: &meter); try output.append("
    2. ", meter: &meter) + } + try output.append("
  • ", meter: &meter) + pending = nil + case .added(let v): + try open("diff-added", change: true, output: &output, meter: &meter) + try mark("+", "Added: ", output: &output, meter: &meter) + try output.append("", meter: &meter); try value(v, output: &output, meter: &meter); try output.append("", meter: &meter) + try close(output: &output, meter: &meter) + case .removed(let v): + try open("diff-removed", change: true, output: &output, meter: &meter) + try mark("−", "Removed: ", output: &output, meter: &meter) + try output.append("", meter: &meter); try value(v, output: &output, meter: &meter); try output.append("", meter: &meter) + try close(output: &output, meter: &meter) + case .replaced(let a, let b): + try open("diff-changed", change: true, output: &output, meter: &meter) + try mark("~", "Changed from ", output: &output, meter: &meter) + try output.append("", meter: &meter); try value(a, output: &output, meter: &meter) + try output.append(" → to ", meter: &meter) + try value(b, output: &output, meter: &meter); try output.append("", meter: &meter) + try close(output: &output, meter: &meter) + case .beginObject, .beginArray: + let array: Bool + if case .beginArray = event { array = true } else { array = false } + try open("diff-nested", change: false, output: &output, meter: &meter) + try output.addDOM(4, meter: &meter) + try output.append(array ? "
    Array with changes
      " + : "
      Object with changes
      ", meter: &meter) + var closing = array ? "
    " : "" + if case .key = pending { closing += "" } + closing += inArray.last == true ? "" : "" + try meter.retain(JSONLogicalWeights.frame + UInt64(closing.utf8.count)) + closers.append(closing); inArray.append(array); pending = nil + case .endObject, .endArray: + inArray.removeLast() + let closing = closers.removeLast() + try output.append(closing, meter: &meter) + try meter.release(JSONLogicalWeights.frame + UInt64(closing.utf8.count)) + } + } + } +} diff --git a/Sources/JSONHTML/JSONHTMLDifferenceAssets.swift b/Sources/JSONHTML/JSONHTMLDifferenceAssets.swift new file mode 100644 index 0000000..651d9db --- /dev/null +++ b/Sources/JSONHTML/JSONHTMLDifferenceAssets.swift @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: Apache-2.0 +// Fixed difference CSS from Assets/Difference.css; CSP hashes exactly these UTF-8 bytes. +package enum JSONHTMLDifferenceAssets { + package static let css = #""" +/* SPDX-License-Identifier: Apache-2.0; Swift-JSON difference asset v1 */ +.diff{--add:#1a7f37;--add-bg:#dafbe1;--del:#b42318;--del-bg:#ffebe9;--chg:#9a6700;--chg-bg:#fff4d6} +.diff.dark{--add:#5fd88a;--add-bg:#12361f;--del:#ff8f87;--del-bg:#45191a;--chg:#f2c45b;--chg-bg:#3a2d0d} +@media(prefers-color-scheme:dark){.diff.automatic{--add:#5fd88a;--add-bg:#12361f;--del:#ff8f87;--del-bg:#45191a;--chg:#f2c45b;--chg-bg:#3a2d0d}} +.diff .diff-summary{display:flex;gap:.75rem;flex-wrap:wrap}.diff .diff-count{font-weight:600;padding:.1rem .5rem;border-radius:.4rem} +.diff .diff-count.diff-added{color:var(--add);background:var(--add-bg)}.diff .diff-count.diff-removed{color:var(--del);background:var(--del-bg)}.diff .diff-count.diff-changed{color:var(--chg);background:var(--chg-bg)} +.diff .diff-downloads a{margin-right:1rem}.diff .diff-list{list-style:none;padding:0;margin:.4rem 0 0;display:grid;gap:.35rem} +.diff .diff-row{border-left:4px solid transparent;padding-left:.6rem}.diff .diff-row.diff-added{border-left-color:var(--add)}.diff .diff-row.diff-removed{border-left-color:var(--del)}.diff .diff-row.diff-changed{border-left-color:var(--chg)} +.diff ins{text-decoration:none;background:var(--add-bg);border-radius:.25rem}.diff del{text-decoration:line-through;background:var(--del-bg);border-radius:.25rem} +.diff .diff-value{margin:0;display:inline;white-space:pre-wrap;overflow-wrap:anywhere;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.diff pre.diff-value{display:block;padding:.3rem .45rem} +.diff .diff-mark{display:inline-block;width:1.2em;font-weight:700}.diff .diff-added>.diff-mark,.diff .diff-added>dd>.diff-mark{color:var(--add)}.diff .diff-removed>.diff-mark,.diff .diff-removed>dd>.diff-mark{color:var(--del)}.diff .diff-changed>.diff-mark,.diff .diff-changed>dd>.diff-mark{color:var(--chg)} +.diff .diff-arrow{padding:0 .3rem}.diff .diff-unchanged>summary{color:var(--muted);cursor:pointer}.diff .diff-changes li a{text-decoration:none}.diff .diff-changes li.diff-added a{color:var(--add)}.diff .diff-changes li.diff-removed a{color:var(--del)}.diff .diff-changes li.diff-changed a{color:var(--chg)} +.diff:has(#jd-only:checked) .diff-same{display:none}.diff .diff-row:target{outline:2px solid currentColor;outline-offset:2px} +@media(forced-colors:active){.diff ins,.diff del,.diff .diff-count{background:Canvas;color:CanvasText;border:1px solid CanvasText}.diff .diff-row{border-left-color:CanvasText}} +@media print{.diff .diff-filter,.diff .diff-downloads{display:none}.diff ins,.diff del{background:none}.diff ins{text-decoration:underline}} +"""# + package static let cssHash = "Yxkb5kFSD0GtznECmpxmXaIKNx+nS67jT/X9lvKJV2I=" +} diff --git a/Sources/JSONPatch/JSONPatchDifference.swift b/Sources/JSONPatch/JSONPatchDifference.swift index 680bf85..83b714a 100644 --- a/Sources/JSONPatch/JSONPatchDifference.swift +++ b/Sources/JSONPatch/JSONPatchDifference.swift @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -// Original implementation of a bounded structural difference producing RFC 6902 operations. +// RFC 6902 facade over the shared bounded structural difference in JSON. import JSON extension JSONPatch { @@ -12,10 +12,10 @@ extension JSONPatch { /// - Equal values, using the exact model's equality (decimal value, decoded /// scalars, order-independent objects), produce no operation. `1.0` and `1` /// are equal, so neither is replaced by the other. - /// - Object members are compared by exact key. Members only in `source` are - /// removed, members only in `target` are added in `target` order, and shared - /// members are compared recursively. A changed member order alone produces no - /// operation, because object equality ignores order. + /// - Object members are compared by exact key, in source order: members only in + /// `source` are removed and shared members are compared recursively. Members + /// only in `target` are then added in `target` order. A changed member order + /// alone produces no operation, because object equality ignores order. /// - Arrays keep their longest equal prefix and suffix. The remaining elements /// are compared pairwise by position; surplus `source` elements are removed /// from the highest index down, and surplus `target` elements are added in order. @@ -24,7 +24,8 @@ extension JSONPatch { /// - Values of different kinds, and unequal scalars, are replaced. A root /// change replaces the root through the empty Pointer. /// - /// The result contains no `test`, `move` or `copy` operations. + /// The result contains no `test`, `move` or `copy` operations. JSONHTML's + /// difference view uses the same comparison. /// /// - Returns: A patch whose application to `source` yields a value equal to `target`. /// - Throws: Resource failure for oversized inputs, operation counts or Pointer @@ -57,85 +58,14 @@ extension JSONPatch { package static func difference(from source: JSON, to target: JSON, meter: inout JSONWorkMeter) throws -> JSONPatch { try JSONAdmission.value(source, meter: &meter) try meter.resetValueBounds(); try JSONAdmission.value(target, meter: &meter) - enum Step { - /// Compare two values found at the same path. - case compare(path: [JSONKey], source: JSON, target: JSON) - /// Emit an operation after the steps pushed before it have run. - case emit(JSONPatchOperation) - } var operations: [JSONPatchOperation] = [] - var stack: [Step] = [] - func push(_ step: Step, meter: inout JSONWorkMeter) throws { - try meter.work(); try meter.retain(JSONLogicalWeights.frame); stack.append(step) - } - func pointer(_ path: [JSONKey], meter: inout JSONWorkMeter) throws -> JSONPointer { - try JSONPointer.decodedTokens(path, meter: &meter) - } - func extended(_ path: [JSONKey], _ key: JSONKey, meter: inout JSONWorkMeter) throws -> [JSONKey] { - try meter.require(.pointerTokens, UInt64(path.count) + 1) - for _ in path { try meter.work() } - try meter.retain(16); return path + [key] - } - func index(_ value: Int, meter: inout JSONWorkMeter) throws -> JSONKey { - try JSONKey(String(value), meter: &meter) - } - try push(.compare(path: [], source: source, target: target), meter: &meter) - while let step = stack.popLast() { - try meter.release(JSONLogicalWeights.frame); try meter.work() - switch step { - case .emit(let operation): - try meter.require(.operations, UInt64(operations.count) + 1) - try meter.retain(JSONLogicalWeights.frame); operations.append(operation) - case .compare(let path, .object(let a), .object(let b)): - // Steps are pushed in reverse so they run in source/target order. - var pending: [Step] = [] - for member in a { - try meter.work() - if try b.lookup(member.key.string, meter: &meter) == nil { - pending.append(.emit(.remove(path: try pointer(extended(path, member.key, meter: &meter), meter: &meter)))) - } - } - for member in b { - try meter.work() - let childPath = try extended(path, member.key, meter: &meter) - if let existing = try a.lookup(member.key.string, meter: &meter) { - pending.append(.compare(path: childPath, source: existing, target: member.value)) - } else { - pending.append(.emit(.add(path: try pointer(childPath, meter: &meter), value: member.value))) - } - } - for item in pending.reversed() { try push(item, meter: &meter) } - case .compare(let path, .array(let a), .array(let b)): - let shared = min(a.count, b.count) - var prefix = 0 - while prefix < shared, try JSONComparison.equals(a[prefix], b[prefix], meter: &meter) { prefix += 1 } - var suffix = 0 - while suffix < shared - prefix, - try JSONComparison.equals(a[a.count - 1 - suffix], b[b.count - 1 - suffix], meter: &meter) { suffix += 1 } - let middleA = a.count - prefix - suffix, middleB = b.count - prefix - suffix - let paired = min(middleA, middleB) - var pending: [Step] = [] - for offset in 0.. JSON { try JSONParser().parse(text) } +private func page(_ source: String, _ target: String, options: JSONHTMLRenderingOptions = .init()) throws -> String { + String(decoding: try JSONHTMLRenderer(options: options).renderDifference(from: parse(source), to: parse(target)), as: UTF8.self) +} +/// Decodes the base64 payload of the first data link whose download name matches. +private func download(_ html: String, named name: String) throws -> String { + let marker = "download=\"\(name)\" href=\"data:" + let start = try #require(html.range(of: marker)).upperBound + let comma = try #require(html[start...].range(of: "base64,")).upperBound + let end = try #require(html[comma...].firstIndex(of: "\"")) + return String(decoding: try #require(Data(base64Encoded: String(html[comma..") && html.contains("2 removed") && html.contains("1 changed")) + #expect(html.contains("diff-row diff-added") && html.contains("diff-row diff-removed") && html.contains("diff-row diff-changed")) + // Markers carry text, not only color. + #expect(html.contains("Added: ")) + #expect(html.contains("Removed: ")) + #expect(html.contains("Changed from ")) + // Equal decimals are unchanged; the unchanged member stays visible but collapsible. + #expect(html.contains("diff-row diff-same")) + // The change list links each change by its Pointer, in tree order. + for (index, pointer) in ["/drop", "/change/n", "/list/1", "/new"].enumerated() { + #expect(html.contains("")) + #expect(html.contains("\(pointer)")) + #expect(html.contains("id=\"jd-c-\(index)\"")) + } + #expect(!html.contains("id=\"jd-c-4\"")) +} + +@Test func differencePageDownloadsTheExactPatchAndBothDocuments() throws { + let html = try page(#"{"a":[0,1,2,3,4],"b":1.50}"#, #"{"a":[0,4],"b":1.50,"c/d":null}"#) + #expect(try download(html, named: "patch.json") == + #"[{"op":"remove","path":"/a/3"},{"op":"remove","path":"/a/2"},{"op":"remove","path":"/a/1"},{"op":"add","path":"/c~1d","value":null}]"#) + // Native exact bytes: the preserved lexeme survives. + #expect(try download(html, named: "source.json").contains("1.50")) + #expect(try download(html, named: "target.json").contains("\"c/d\"")) + #expect(html.contains("Elements #0 unchanged") || html.contains("Element #0 unchanged")) +} + +@Test func differencePageIsStaticEscapedAndHashAuthorized() throws { + let html = try page(#"{"