vimanam 1.6.0

OpenAPI/Swagger to Markdown documentation generator with grouping, filtering, and detail levels for docs and LLM context
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
//! JSON output for `vimanam diff` (#98): a machine-readable rendering of a
//! [`SpecDiff`] with a stable, content-derived ID per change.
//!
//! The output types here are **serializable and deserializable** and kept separate from the
//! domain types in [`crate::diff`]: the JSON contract must not drift when the
//! internals are refactored, so `Change`/`ChangeKind`/`ValueChange` stay
//! serde-free. Field declaration order on the structs sets the pretty-printed
//! key order and is deterministic.
//!
//! # Change identity
//!
//! Every record carries `id = "vc1_" + hex(SHA-256(canonical_bytes))` where
//! `canonical_bytes` is the canonical JSON (object keys sorted recursively in
//! byte order, compact separators) of `{ "v": 1, "endpoint": …, "kind": …,
//! "details": … }` — exactly the values emitted in the record, so the hash
//! input and the output can't disagree. Severity, display strings, timestamps,
//! file paths and `file_sha256` are deliberately left out: a future change to
//! the severity rule table must not change any ID. The `vc1_` prefix and the
//! `"v": 1` field both version the construction; any future change to it bumps
//! both. A change behind a shared `$ref` yields one record per affected
//! endpoint, each with its own ID, because the endpoint is part of the hash
//! input.

use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::fmt::Write as _;

use crate::diff::{
    Change, ChangeKind, Deltas, Location, Severity, SpecDiff, ValueChange, ValueChangeKind, locate,
    severity,
};
use crate::utils::decode_json_pointer_token;

// ── output types ────────────────────────────────────────────────────────────

/// The complete JSON document printed by `vimanam diff --format json`.
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonDiff {
    /// JSON contract version; currently `1`.
    pub schema_version: u8,
    /// Generator name and package version.
    pub generator: JsonGenerator,
    /// API identity and raw input hash for the old spec.
    pub old: JsonSide,
    /// API identity and raw input hash for the new spec.
    pub new: JsonSide,
    /// Endpoint and severity counts.
    pub summary: JsonSummary,
    /// Changes in deterministic spec order.
    pub changes: Vec<JsonChange>,
    /// Present only under `--report`; the key is omitted (never `null`)
    /// otherwise.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deltas: Option<JsonDeltas>,
}

/// Identity of the binary/library that produced the document.
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonGenerator {
    /// The declared name.
    pub name: String,
    /// Declared version.
    pub version: String,
}

/// API identity and raw-file hash for one side of the comparison.
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonSide {
    /// Declared title.
    pub title: String,
    /// Declared version.
    pub version: String,
    /// SHA-256 of the original input file bytes exactly as read from disk,
    /// before any parsing. Reformatting a spec changes this hash but not the
    /// change IDs.
    pub file_sha256: String,
}

/// Counts matching the human-readable diff summary.
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonSummary {
    /// Number of operations added.
    pub endpoints_added: usize,
    /// Number of operations removed.
    pub endpoints_removed: usize,
    /// Number of distinct surviving operations with changes.
    pub endpoints_changed: usize,
    /// Number of breaking changes.
    pub breaking: usize,
    /// Number of additive or relaxing changes.
    pub non_breaking: usize,
    /// Number of changes requiring usage-specific review.
    pub review: usize,
}

/// One endpoint-attributed contract change with a stable ID.
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonChange {
    /// Stable content-derived change identifier, prefixed with `vc1_`.
    pub id: String,
    /// The HTTP operation to which this change is attributed.
    pub endpoint: JsonEndpoint,
    /// The concrete difference or operation applied at this location.
    pub kind: JsonChangeKind,
    /// Impact on existing clients.
    pub severity: JsonSeverity,
    /// Insertion-ordered contract detail fields for this change kind.
    pub details: JsonDetails,
}

/// Exact HTTP method/path identity used by the diff.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonEndpoint {
    /// Uppercase HTTP method.
    pub method: String,
    /// Exact path template from the spec, without a Swagger 2 `basePath`.
    pub path: String,
}

/// Stable snake_case change kind in JSON contract version 1.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum JsonChangeKind {
    /// An operation exists only in the new spec.
    EndpointAdded,
    /// An operation from the old spec was removed.
    EndpointRemoved,
    /// A parameter was added to a surviving operation.
    ParameterAdded,
    /// A parameter was removed from a surviving operation.
    ParameterRemoved,
    /// A parameter changed between optional and required.
    ParameterRequiredChanged,
    /// An unambiguous parameter moved to a different location.
    ParameterLocationChanged,
    /// A parameter schema has a field-level change.
    ParameterSchemaChanged,
    /// A response status was added.
    ResponseAdded,
    /// A response status was removed.
    ResponseRemoved,
    /// An operationId changed, appeared, or disappeared.
    OperationIdChanged,
    /// An operation changed its deprecation flag.
    DeprecatedChanged,
    /// A request-body schema has a field-level change.
    RequestSchemaChanged,
    /// A response schema has a field-level change.
    ResponseSchemaChanged,
}

/// Impact classification used by the JSON contract.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum JsonSeverity {
    /// Existing API clients can break.
    Breaking,
    /// An additive or relaxing change.
    NonBreaking,
    /// Impact depends on client usage and needs review.
    Review,
}

/// The `details` object of a change record: an insertion-ordered map whose key
/// order follows the contract table (deterministic under serde_json's
/// `preserve_order`). Newtype so the record serialises it as a bare object.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonDetails(
    /// Contract detail fields in deterministic insertion order.
    pub serde_json::Map<String, Value>,
);

/// Field-level schema difference embedded in the details of a schema change.
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonSchemaChange {
    /// RFC 6901 pointer exactly as the differ emits it. It addresses the
    /// *resolved, canonicalised* schema (`$ref`s inlined, annotation keywords
    /// stripped), not necessarily a location in the input file.
    pub pointer: String,
    /// What the pointer addresses, per the schema grammar (`locate`).
    pub target: JsonTarget,
    /// The decoded last pointer segment when the target is a named member;
    /// `null` otherwise.
    pub member: Option<String>,
    /// Whether the schema value was added, removed, or changed.
    pub operation: JsonOperation,
    /// Old schema value, distinguishing absence from JSON null.
    pub before: JsonPresence,
    /// New schema value, distinguishing absence from JSON null.
    pub after: JsonPresence,
}

/// Schema-grammar classification of a canonical JSON pointer.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum JsonTarget {
    /// The schema type keyword.
    Type,
    /// A named member of a required set.
    RequiredMember,
    /// A member of an enum set.
    EnumMember,
    /// A named property schema.
    Property,
    /// The additionalProperties keyword.
    AdditionalProperties,
    /// The nullable keyword.
    Nullable,
    /// Another schema keyword or value.
    Other,
}

/// The operation applied at a schema pointer.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum JsonOperation {
    /// A value exists only in the new schema.
    Added,
    /// A value exists only in the old schema.
    Removed,
    /// A value differs between the old and new schemas.
    Changed,
}

/// Either `{ "present": false }` or `{ "present": true, "value": <json> }`.
/// A present `value` may legitimately be JSON `null` (`default: null`,
/// `enum: [null]`) — that is distinct from absence.
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonPresence {
    /// Whether the value exists at this location.
    pub present: bool,
    /// The present JSON value, including `Some(Value::Null)`; `None` means absent.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default, deserialize_with = "deserialize_present_value")]
    pub value: Option<Value>,
}

/// Optional hygiene and full-detail token estimates for both specs.
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonDeltas {
    /// Whole-document hygiene counts in report order.
    pub hygiene: Vec<JsonHygieneRow>,
    /// Whole-document token estimates.
    pub tokens: JsonTokenEstimate,
}

/// One hygiene check and its old/new counts.
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonHygieneRow {
    /// Hygiene check label.
    pub check: String,
    /// The value or count in the old spec.
    pub old: usize,
    /// The value or count in the new spec.
    pub new: usize,
}

/// Old/new token estimates and their render/estimation profile.
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonTokenEstimate {
    /// The value or count in the old spec.
    pub old: usize,
    /// The value or count in the new spec.
    pub new: usize,
    /// Token-estimation heuristic, currently `chars/4`.
    pub estimate: String,
    /// Render profile used for estimates, currently `full+schemas`.
    pub detail: String,
}

// `Option<Value>` normally deserializes both a missing key and null as None.
// The contract distinguishes those cases: an explicit null is a present value.
fn deserialize_present_value<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<Value>, D::Error> {
    Value::deserialize(deserializer).map(Some)
}

// ── construction ────────────────────────────────────────────────────────────

/// Builds the JSON document for a [`SpecDiff`]. `old_sha`/`new_sha` are the
/// lowercase-hex SHA-256 of the original input file bytes; `deltas` is passed
/// only under `--report`.
pub fn to_json(diff: &SpecDiff, deltas: Option<&Deltas>, old_sha: &str, new_sha: &str) -> JsonDiff {
    JsonDiff {
        schema_version: 1,
        generator: JsonGenerator {
            name: "vimanam".to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
        },
        old: JsonSide {
            title: diff.old_title.clone(),
            version: diff.old_version.clone(),
            file_sha256: old_sha.to_string(),
        },
        new: JsonSide {
            title: diff.new_title.clone(),
            version: diff.new_version.clone(),
            file_sha256: new_sha.to_string(),
        },
        summary: JsonSummary {
            endpoints_added: diff.endpoints_added(),
            endpoints_removed: diff.endpoints_removed(),
            endpoints_changed: diff.endpoints_changed(),
            breaking: diff.count(Severity::Breaking),
            non_breaking: diff.count(Severity::NonBreaking),
            review: diff.count(Severity::Review),
        },
        changes: diff.changes.iter().map(json_change).collect(),
        deltas: deltas.map(|deltas| JsonDeltas {
            hygiene: deltas
                .hygiene
                .iter()
                .map(|(check, old, new)| JsonHygieneRow {
                    check: (*check).to_string(),
                    old: *old,
                    new: *new,
                })
                .collect(),
            tokens: JsonTokenEstimate {
                old: deltas.tokens_old,
                new: deltas.tokens_new,
                estimate: "chars/4".to_string(),
                detail: "full+schemas".to_string(),
            },
        }),
    }
}

/// The stable ID of a change record: `vc1_` + hex(SHA-256(canonical_json({
/// v, endpoint, kind, details }))). Derived from the serialised record
/// itself, so the hash input can never disagree with the emitted document.
pub fn change_id(change: &JsonChange) -> String {
    #[derive(Serialize)]
    struct IdInput<'a> {
        v: u8,
        endpoint: &'a JsonEndpoint,
        kind: &'a JsonChangeKind,
        details: &'a JsonDetails,
    }

    let input = IdInput {
        v: 1,
        endpoint: &change.endpoint,
        kind: &change.kind,
        details: &change.details,
    };
    let value = serde_json::to_value(&input).expect("ID input always serialises");
    format!("vc1_{}", sha256_hex(canonical_json(&value).as_bytes()))
}

fn json_change(change: &Change) -> JsonChange {
    let (kind, details) = json_kind_and_details(&change.kind);
    let mut record = JsonChange {
        id: String::new(),
        endpoint: JsonEndpoint {
            method: change.endpoint.method.clone(),
            path: change.endpoint.path.clone(),
        },
        kind,
        severity: severity(change).into(),
        details,
    };
    record.id = change_id(&record);
    record
}

/// Maps a [`ChangeKind`] to its contract `(kind, details)` pair. One arm per
/// variant, so adding a variant fails to compile here instead of silently
/// missing from the JSON contract.
fn json_kind_and_details(kind: &ChangeKind) -> (JsonChangeKind, JsonDetails) {
    use serde_json::json;

    /// Builds the insertion-ordered details map for a record.
    fn details(entries: Vec<(&'static str, Value)>) -> JsonDetails {
        JsonDetails(
            entries
                .into_iter()
                .map(|(key, value)| (key.to_string(), value))
                .collect(),
        )
    }

    match kind {
        ChangeKind::EndpointAdded => (JsonChangeKind::EndpointAdded, details(Vec::new())),
        ChangeKind::EndpointRemoved { was_deprecated } => (
            JsonChangeKind::EndpointRemoved,
            details(vec![("was_deprecated", json!(was_deprecated))]),
        ),
        ChangeKind::ParameterAdded {
            name,
            location,
            required,
        } => (
            JsonChangeKind::ParameterAdded,
            details(vec![
                ("name", json!(name)),
                ("location", json!(location)),
                ("required", json!(required)),
            ]),
        ),
        ChangeKind::ParameterRemoved { name, location } => (
            JsonChangeKind::ParameterRemoved,
            details(vec![("name", json!(name)), ("location", json!(location))]),
        ),
        ChangeKind::ParameterRequiredChanged {
            name,
            location,
            now_required,
        } => (
            JsonChangeKind::ParameterRequiredChanged,
            details(vec![
                ("name", json!(name)),
                ("location", json!(location)),
                ("now_required", json!(now_required)),
            ]),
        ),
        ChangeKind::ParameterLocationChanged {
            name,
            old_location,
            new_location,
        } => (
            JsonChangeKind::ParameterLocationChanged,
            details(vec![
                ("name", json!(name)),
                ("old_location", json!(old_location)),
                ("new_location", json!(new_location)),
            ]),
        ),
        ChangeKind::ParameterSchemaChanged {
            name,
            location,
            change,
        } => (
            JsonChangeKind::ParameterSchemaChanged,
            details(vec![
                ("name", json!(name)),
                ("location", json!(location)),
                ("schema_change", json!(json_schema_change(change))),
            ]),
        ),
        ChangeKind::ResponseAdded { status } => (
            JsonChangeKind::ResponseAdded,
            details(vec![("status", json!(status))]),
        ),
        ChangeKind::ResponseRemoved { status } => (
            JsonChangeKind::ResponseRemoved,
            details(vec![("status", json!(status))]),
        ),
        // The IR really has Option<String> here, so `null` is a legitimate
        // value in the contract.
        ChangeKind::OperationIdChanged { old, new } => (
            JsonChangeKind::OperationIdChanged,
            details(vec![("old", json!(old)), ("new", json!(new))]),
        ),
        ChangeKind::DeprecatedChanged { now } => (
            JsonChangeKind::DeprecatedChanged,
            details(vec![("now", json!(now))]),
        ),
        ChangeKind::RequestSchemaChanged { change } => (
            JsonChangeKind::RequestSchemaChanged,
            details(vec![("schema_change", json!(json_schema_change(change)))]),
        ),
        ChangeKind::ResponseSchemaChanged { status, change } => (
            JsonChangeKind::ResponseSchemaChanged,
            details(vec![
                ("status", json!(status)),
                ("schema_change", json!(json_schema_change(change))),
            ]),
        ),
    }
}

impl From<Severity> for JsonSeverity {
    fn from(severity: Severity) -> Self {
        match severity {
            Severity::Breaking => JsonSeverity::Breaking,
            Severity::NonBreaking => JsonSeverity::NonBreaking,
            Severity::Review => JsonSeverity::Review,
        }
    }
}

// ── schema_change ───────────────────────────────────────────────────────────

fn json_schema_change(change: &ValueChange) -> JsonSchemaChange {
    let at_root = change.pointer.is_empty();
    let (target, member) = target_and_member(&change.pointer);

    JsonSchemaChange {
        pointer: change.pointer.clone(),
        target,
        member,
        operation: match &change.kind {
            ValueChangeKind::Added(_) => JsonOperation::Added,
            ValueChangeKind::Removed(_) => JsonOperation::Removed,
            ValueChangeKind::Changed { old, new } => {
                // The differ encodes "no schema at all" as `Value::Null` at
                // the root pointer, so a root null side means the schema
                // appeared or vanished rather than changed to/from null.
                if at_root && old.is_null() {
                    JsonOperation::Added
                } else if at_root && new.is_null() {
                    JsonOperation::Removed
                } else {
                    JsonOperation::Changed
                }
            }
        },
        before: presence(old_side(&change.kind), at_root),
        after: presence(new_side(&change.kind), at_root),
    }
}

fn old_side(kind: &ValueChangeKind) -> Option<&Value> {
    match kind {
        ValueChangeKind::Added(_) => None,
        ValueChangeKind::Removed(old) | ValueChangeKind::Changed { old, .. } => Some(old),
    }
}

fn new_side(kind: &ValueChangeKind) -> Option<&Value> {
    match kind {
        ValueChangeKind::Added(new) | ValueChangeKind::Changed { new, .. } => Some(new),
        ValueChangeKind::Removed(_) => None,
    }
}

fn presence(side: Option<&Value>, at_root: bool) -> JsonPresence {
    match side {
        // A side the `ValueChangeKind` does not carry is absent.
        None => JsonPresence {
            present: false,
            value: None,
        },
        // At the root pointer `Value::Null` means "no schema at all"
        // (`optional_schema_value`/`parameter_schema_value`); everywhere else
        // it is a real `null` value.
        Some(value) if at_root && value.is_null() => JsonPresence {
            present: false,
            value: None,
        },
        Some(value) => JsonPresence {
            present: true,
            value: Some(value.clone()),
        },
    }
}

/// Classifies a pointer with the schema grammar ([`locate`]) — never by
/// guessing from the last segment, so a property named `type` is a `property`,
/// not the `type` keyword.
fn target_and_member(pointer: &str) -> (JsonTarget, Option<String>) {
    let member = || -> Option<String> {
        pointer
            .rsplit('/')
            .next()
            .filter(|segment| !segment.is_empty())
            .map(decode_json_pointer_token)
    };

    match locate(pointer) {
        Location::Type => (JsonTarget::Type, None),
        Location::RequiredElement => (JsonTarget::RequiredMember, member()),
        Location::EnumElement => (JsonTarget::EnumMember, member()),
        Location::Property => (JsonTarget::Property, member()),
        Location::AdditionalProperties => (JsonTarget::AdditionalProperties, None),
        Location::Nullable => (JsonTarget::Nullable, None),
        Location::Other => (JsonTarget::Other, None),
    }
}

// ── hashing helpers ─────────────────────────────────────────────────────────

/// Lowercase-hex SHA-256. Used for both `file_sha256` and change IDs.
pub fn sha256_hex(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    let mut hex = String::with_capacity(digest.len() * 2);
    for byte in digest {
        write!(hex, "{byte:02x}").expect("writing to a String cannot fail");
    }
    hex
}

/// Serialises `value` as canonical JSON: object keys sorted recursively in
/// byte order, compact separators, strings and numbers as `serde_json`
/// serialises them. The crate enables serde_json's `preserve_order`, so maps
/// keep insertion order unless sorted explicitly — which is what makes the
/// change-ID hash input reproducible. (Not to be confused with
/// `utils::canonicalize_schema_value`, which strips schema annotation
/// keywords; that is schema semantics, this is serialisation.)
pub fn canonical_json(value: &Value) -> String {
    fn canonical(value: &Value) -> Value {
        match value {
            Value::Object(map) => {
                let mut keys: Vec<&String> = map.keys().collect();
                keys.sort();
                keys.into_iter()
                    .map(|key| (key.clone(), canonical(&map[key])))
                    .collect::<serde_json::Map<String, Value>>()
                    .into()
            }
            Value::Array(items) => Value::Array(items.iter().map(canonical).collect()),
            other => other.clone(),
        }
    }

    canonical(value).to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::report::EndpointRef;
    use serde_json::json;

    /// Builds a JSON record for `kind` on a fixed endpoint.
    fn record(kind: ChangeKind) -> JsonChange {
        json_change(&Change {
            endpoint: EndpointRef {
                method: "GET".to_string(),
                path: "/widgets".to_string(),
            },
            kind,
        })
    }

    /// `(kind string, details value)` of a record.
    fn contract(record: &JsonChange) -> (String, Value) {
        (
            serde_json::to_value(&record.kind)
                .unwrap()
                .as_str()
                .unwrap()
                .to_string(),
            serde_json::to_value(&record.details).unwrap(),
        )
    }

    fn value_change(pointer: &str, kind: ValueChangeKind) -> ValueChange {
        ValueChange {
            pointer: pointer.to_string(),
            kind,
        }
    }

    // ── kind/details mapping: one test per ChangeKind variant ───────────────

    #[test]
    fn endpoint_added_maps_to_empty_details() {
        let (kind, details) = contract(&record(ChangeKind::EndpointAdded));
        assert_eq!(kind, "endpoint_added");
        assert_eq!(details, json!({}));
    }

    #[test]
    fn endpoint_removed_maps_was_deprecated() {
        let (kind, details) = contract(&record(ChangeKind::EndpointRemoved {
            was_deprecated: true,
        }));
        assert_eq!(kind, "endpoint_removed");
        assert_eq!(details, json!({ "was_deprecated": true }));
    }

    #[test]
    fn parameter_added_maps_name_location_required() {
        let (kind, details) = contract(&record(ChangeKind::ParameterAdded {
            name: "limit".into(),
            location: "query".into(),
            required: false,
        }));
        assert_eq!(kind, "parameter_added");
        assert_eq!(
            details,
            json!({ "name": "limit", "location": "query", "required": false })
        );
    }

    #[test]
    fn parameter_removed_maps_name_location() {
        let (kind, details) = contract(&record(ChangeKind::ParameterRemoved {
            name: "limit".into(),
            location: "query".into(),
        }));
        assert_eq!(kind, "parameter_removed");
        assert_eq!(details, json!({ "name": "limit", "location": "query" }));
    }

    #[test]
    fn parameter_required_changed_maps_now_required() {
        let (kind, details) = contract(&record(ChangeKind::ParameterRequiredChanged {
            name: "fields".into(),
            location: "query".into(),
            now_required: true,
        }));
        assert_eq!(kind, "parameter_required_changed");
        assert_eq!(
            details,
            json!({ "name": "fields", "location": "query", "now_required": true })
        );
    }

    #[test]
    fn parameter_location_changed_maps_locations() {
        let (kind, details) = contract(&record(ChangeKind::ParameterLocationChanged {
            name: "X-Trace".into(),
            old_location: "header".into(),
            new_location: "query".into(),
        }));
        assert_eq!(kind, "parameter_location_changed");
        assert_eq!(
            details,
            json!({ "name": "X-Trace", "old_location": "header", "new_location": "query" })
        );
    }

    #[test]
    fn parameter_schema_changed_maps_nested_schema_change() {
        let (kind, details) = contract(&record(ChangeKind::ParameterSchemaChanged {
            name: "limit".into(),
            location: "query".into(),
            change: value_change(
                "/type",
                ValueChangeKind::Changed {
                    old: json!("integer"),
                    new: json!("string"),
                },
            ),
        }));
        assert_eq!(kind, "parameter_schema_changed");
        assert_eq!(
            details,
            json!({
                "name": "limit",
                "location": "query",
                "schema_change": {
                    "pointer": "/type",
                    "target": "type",
                    "member": null,
                    "operation": "changed",
                    "before": { "present": true, "value": "integer" },
                    "after": { "present": true, "value": "string" }
                }
            })
        );
    }

    #[test]
    fn response_added_maps_status() {
        let (kind, details) = contract(&record(ChangeKind::ResponseAdded {
            status: "404".into(),
        }));
        assert_eq!(kind, "response_added");
        assert_eq!(details, json!({ "status": "404" }));
    }

    #[test]
    fn response_removed_maps_status() {
        let (kind, details) = contract(&record(ChangeKind::ResponseRemoved {
            status: "default".into(),
        }));
        assert_eq!(kind, "response_removed");
        assert_eq!(details, json!({ "status": "default" }));
    }

    #[test]
    fn operation_id_changed_maps_nullable_old_and_new() {
        let (kind, details) = contract(&record(ChangeKind::OperationIdChanged {
            old: Some("listWidgets".into()),
            new: None,
        }));
        assert_eq!(kind, "operation_id_changed");
        assert_eq!(details, json!({ "old": "listWidgets", "new": null }));
    }

    #[test]
    fn deprecated_changed_maps_now() {
        let (kind, details) = contract(&record(ChangeKind::DeprecatedChanged { now: true }));
        assert_eq!(kind, "deprecated_changed");
        assert_eq!(details, json!({ "now": true }));
    }

    #[test]
    fn request_schema_changed_maps_schema_change() {
        let (kind, details) = contract(&record(ChangeKind::RequestSchemaChanged {
            change: value_change(
                "/properties/weight/format",
                ValueChangeKind::Changed {
                    old: json!("float"),
                    new: json!("double"),
                },
            ),
        }));
        assert_eq!(kind, "request_schema_changed");
        assert_eq!(
            details,
            json!({
                "schema_change": {
                    "pointer": "/properties/weight/format",
                    "target": "other",
                    "member": null,
                    "operation": "changed",
                    "before": { "present": true, "value": "float" },
                    "after": { "present": true, "value": "double" }
                }
            })
        );
    }

    #[test]
    fn response_schema_changed_maps_status_and_schema_change() {
        let (kind, details) = contract(&record(ChangeKind::ResponseSchemaChanged {
            status: "200".into(),
            change: value_change(
                "/properties/pricing",
                ValueChangeKind::Added(json!({ "type": "number" })),
            ),
        }));
        assert_eq!(kind, "response_schema_changed");
        assert_eq!(
            details,
            json!({
                "status": "200",
                "schema_change": {
                    "pointer": "/properties/pricing",
                    "target": "property",
                    "member": "pricing",
                    "operation": "added",
                    "before": { "present": false },
                    "after": { "present": true, "value": { "type": "number" } }
                }
            })
        );
    }

    // ── presence encoding ───────────────────────────────────────────────────

    #[test]
    fn explicit_null_value_is_present_elsewhere_but_absent_at_root() {
        // `default: null` → `default: "x"`: the null before-value is real.
        let change = value_change(
            "/properties/token/default",
            ValueChangeKind::Changed {
                old: Value::Null,
                new: json!("none"),
            },
        );
        let rendered = json!(json_schema_change(&change));
        assert_eq!(
            rendered["before"],
            json!({ "present": true, "value": null })
        );
        assert_eq!(
            rendered["after"],
            json!({ "present": true, "value": "none" })
        );
        assert_eq!(rendered["operation"], json!("changed"));

        // At the root pointer the same Null means "no schema": absent.
        let appeared = value_change(
            "",
            ValueChangeKind::Changed {
                old: Value::Null,
                new: json!({ "type": "integer" }),
            },
        );
        let rendered = json!(json_schema_change(&appeared));
        assert_eq!(rendered["before"], json!({ "present": false }));
        assert_eq!(
            rendered["after"],
            json!({ "present": true, "value": { "type": "integer" } })
        );
        // …and the operation flips to `added`.
        assert_eq!(rendered["operation"], json!("added"));

        let vanished = value_change(
            "",
            ValueChangeKind::Changed {
                old: json!({ "type": "integer" }),
                new: Value::Null,
            },
        );
        let rendered = json!(json_schema_change(&vanished));
        assert_eq!(
            rendered["before"],
            json!({ "present": true, "value": { "type": "integer" } })
        );
        assert_eq!(rendered["after"], json!({ "present": false }));
        assert_eq!(rendered["operation"], json!("removed"));
    }

    #[test]
    fn added_and_removed_sides_encode_absence() {
        let added = value_change("/properties/pricing", ValueChangeKind::Added(json!(1)));
        let rendered = json!(json_schema_change(&added));
        assert_eq!(rendered["before"], json!({ "present": false }));
        assert_eq!(rendered["after"], json!({ "present": true, "value": 1 }));

        let removed = value_change("/properties/pricing", ValueChangeKind::Removed(json!(1)));
        let rendered = json!(json_schema_change(&removed));
        assert_eq!(rendered["before"], json!({ "present": true, "value": 1 }));
        assert_eq!(rendered["after"], json!({ "present": false }));
    }

    #[test]
    fn enum_member_gaining_null_keeps_operation() {
        // `enum: [null]` → `enum: [null, "custom"]`: the new member is an
        // addition; the *value* "custom" is a string, and the existing null
        // member is untouched (no record for it).
        let added = value_change("/enum/custom", ValueChangeKind::Added(json!("custom")));
        let rendered = json!(json_schema_change(&added));
        assert_eq!(rendered["target"], json!("enum_member"));
        assert_eq!(rendered["member"], json!("custom"));
        assert_eq!(rendered["operation"], json!("added"));
        assert_eq!(rendered["before"], json!({ "present": false }));

        // A *changed* null member value away from the root stays present.
        let changed = value_change(
            "/enum/0",
            ValueChangeKind::Changed {
                old: Value::Null,
                new: json!("none"),
            },
        );
        let rendered = json!(json_schema_change(&changed));
        assert_eq!(
            rendered["before"],
            json!({ "present": true, "value": null })
        );
    }

    // ── target/member classification ────────────────────────────────────────

    #[test]
    fn target_distinguishes_property_named_type_from_type_keyword() {
        // A property called "type" is a property …
        let change = value_change("/properties/type", ValueChangeKind::Added(json!({})));
        let rendered = json!(json_schema_change(&change));
        assert_eq!(rendered["target"], json!("property"));
        assert_eq!(rendered["member"], json!("type"));

        // … while the keyword is `type`.
        let change = value_change(
            "/type",
            ValueChangeKind::Changed {
                old: json!("string"),
                new: json!("integer"),
            },
        );
        let rendered = json!(json_schema_change(&change));
        assert_eq!(rendered["target"], json!("type"));
        assert_eq!(rendered["member"], Value::Null);
    }

    #[test]
    fn target_resolves_required_enum_and_other_keywords() {
        let change = value_change("/required/x", ValueChangeKind::Added(json!("x")));
        let rendered = json!(json_schema_change(&change));
        assert_eq!(rendered["target"], json!("required_member"));
        assert_eq!(rendered["member"], json!("x"));

        let change = value_change("/enum/z", ValueChangeKind::Added(json!("z")));
        let rendered = json!(json_schema_change(&change));
        assert_eq!(rendered["target"], json!("enum_member"));
        assert_eq!(rendered["member"], json!("z"));

        // A pointer token is decoded before it becomes `member`.
        let change = value_change("/properties/a~1b", ValueChangeKind::Added(json!({})));
        let rendered = json!(json_schema_change(&change));
        assert_eq!(rendered["target"], json!("property"));
        assert_eq!(rendered["member"], json!("a/b"));

        let change = value_change(
            "/additionalProperties",
            ValueChangeKind::Removed(json!(false)),
        );
        let rendered = json!(json_schema_change(&change));
        assert_eq!(rendered["target"], json!("additional_properties"));
        assert_eq!(rendered["member"], Value::Null);

        let change = value_change("/nullable", ValueChangeKind::Removed(json!(true)));
        let rendered = json!(json_schema_change(&change));
        assert_eq!(rendered["target"], json!("nullable"));

        let change = value_change(
            "/format",
            ValueChangeKind::Changed {
                old: json!("float"),
                new: json!("double"),
            },
        );
        let rendered = json!(json_schema_change(&change));
        assert_eq!(rendered["target"], json!("other"));
        assert_eq!(rendered["member"], Value::Null);
    }

    // ── canonical JSON and identity ─────────────────────────────────────────

    #[test]
    fn canonical_json_sorts_object_keys_recursively_but_keeps_array_order() {
        let value = json!({
            "b": 1,
            "a": { "d": [json!({ "z": 1, "y": 2 }), "x"], "c": 3 },
        });
        assert_eq!(
            canonical_json(&value),
            r#"{"a":{"c":3,"d":[{"y":2,"z":1},"x"]},"b":1}"#
        );
        // Scalars pass through serde_json's compact form.
        assert_eq!(canonical_json(&json!("x")), r#""x""#);
        assert_eq!(canonical_json(&Value::Null), "null");
        assert_eq!(canonical_json(&json!(true)), "true");
        assert_eq!(canonical_json(&json!(1.5)), "1.5");
    }

    #[test]
    fn change_id_is_sha256_of_canonical_identity() {
        // Pinned independently (sha256sum of the canonical bytes below).
        let change = record(ChangeKind::EndpointAdded);
        let canonical = r#"{"details":{},"endpoint":{"method":"GET","path":"/widgets"},"kind":"endpoint_added","v":1}"#;
        let expected = format!("vc1_{}", sha256_hex(canonical.as_bytes()));
        assert_eq!(change.id, expected);
    }

    #[test]
    fn change_id_ignores_severity() {
        // Severity is not part of the hash input: two records differing only
        // in severity must have the same ID, so a future change to the
        // severity rule table cannot rewrite history.
        let with_breaking = JsonChange {
            id: String::new(),
            endpoint: JsonEndpoint {
                method: "GET".to_string(),
                path: "/widgets".to_string(),
            },
            kind: JsonChangeKind::EndpointAdded,
            details: JsonDetails(serde_json::Map::new()),
            severity: JsonSeverity::Breaking,
        };
        let mut with_review = JsonChange {
            id: String::new(),
            endpoint: with_breaking.endpoint.clone(),
            kind: JsonChangeKind::EndpointAdded,
            details: JsonDetails(serde_json::Map::new()),
            severity: JsonSeverity::Review,
        };
        assert_eq!(change_id(&with_breaking), change_id(&with_review));

        // The endpoint, by contrast, IS hashed.
        with_review.endpoint.path = "/elsewhere".to_string();
        assert_ne!(change_id(&with_breaking), change_id(&with_review));

        // And the record constructor produces the same ID it would hash.
        let built = record(ChangeKind::EndpointAdded);
        assert_eq!(built.id, change_id(&built));
    }

    #[test]
    fn different_details_give_different_ids() {
        let a = record(ChangeKind::ResponseSchemaChanged {
            status: "200".into(),
            change: value_change(
                "/properties/price/type",
                ValueChangeKind::Changed {
                    old: json!("string"),
                    new: json!("integer"),
                },
            ),
        });
        let b = record(ChangeKind::ResponseSchemaChanged {
            status: "200".into(),
            change: value_change(
                "/properties/price/type",
                ValueChangeKind::Changed {
                    old: json!("string"),
                    new: json!("boolean"),
                },
            ),
        });
        assert_ne!(a.id, b.id);
    }

    #[test]
    fn sha256_hex_matches_known_vectors() {
        assert_eq!(
            sha256_hex(b""),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
        assert_eq!(
            sha256_hex(b"abc"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }

    #[test]
    fn to_json_summary_matches_specdiff_counts() {
        let diff = crate::diff::diff(
            &crate::parser::parse_openapi("tests/fixtures/diff_old_oas3.json").unwrap(),
            &crate::parser::parse_openapi("tests/fixtures/diff_new_oas3.json").unwrap(),
        );
        let document = to_json(
            &diff,
            None,
            "a".repeat(64).as_str(),
            "b".repeat(64).as_str(),
        );
        assert_eq!(document.schema_version, 1);
        assert_eq!(document.generator.version, env!("CARGO_PKG_VERSION"));
        assert_eq!(document.summary.endpoints_added, diff.endpoints_added());
        assert_eq!(document.summary.endpoints_removed, diff.endpoints_removed());
        assert_eq!(document.summary.endpoints_changed, diff.endpoints_changed());
        assert_eq!(document.summary.breaking, diff.count(Severity::Breaking));
        assert_eq!(
            document.summary.non_breaking,
            diff.count(Severity::NonBreaking)
        );
        assert_eq!(document.summary.review, diff.count(Severity::Review));
        assert_eq!(document.changes.len(), diff.changes.len());
        // Order follows SpecDiff::changes, and IDs are unique in the document.
        let mut ids: Vec<&str> = document.changes.iter().map(|c| c.id.as_str()).collect();
        let expected_order: Vec<String> = diff
            .changes
            .iter()
            .map(|change| json_change(change).id)
            .collect();
        let actual_order: Vec<String> = document.changes.iter().map(|c| c.id.clone()).collect();
        assert_eq!(actual_order, expected_order);
        ids.sort_unstable();
        ids.dedup();
        assert_eq!(ids.len(), document.changes.len(), "IDs must be unique");
        // deltas stays omitted without --report.
        assert!(document.deltas.is_none());
    }
}