roas 0.17.0

Rust OpenAPI Specification — parser, validator, and loader for OpenAPI v2.0 / v3.0.x / v3.1.x / v3.2.x
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
//! `Spec::collapse` for OAS 2.0 — lift every inline `Schema`,
//! `Parameter`, and `Response` into the top-level `definitions`,
//! `parameters`, and `responses` bags.
//!
//! All of the heavy lifting (dedup, naming, the generic `lift_ref_or`
//! routine, the `LiftableBag` trait, the `Bag<T>` storage) lives in
//! [`crate::common::collapse`]. This module just provides the v2
//! pieces:
//!
//! * The concrete [`Collapser`] struct (one `Bag<T>` field per
//!   component type plus the loader handle).
//! * A [`LiftableBag`] impl per component type, with the per-type
//!   [`tree-walk`](LiftableBag::walk) that calls
//!   [`lift_ref_or`](crate::common::collapse::lift_ref_or) on every
//!   nested component slot.
//! * A small [`collapse_spec`] entrypoint that owns the Collapser,
//!   runs phase 1 (seed bags) + phase 2a (recurse into pre-existing
//!   bag entries) + phase 2b (walk paths), then writes each bag back.
//!
//! The v2 bags differ from v3 components in two ways:
//!
//! * They live at the *root* of the spec (`spec.definitions`,
//!   `spec.parameters`, `spec.responses`) rather than nested under
//!   `components`.
//! * They hold *bare* values (`BTreeMap<String, T>`) rather than
//!   `BTreeMap<String, RefOr<T>>` — a bag entry can't itself be a
//!   `$ref`. [`Bag<T>`] still stores entries as `RefOr<T>`
//!   internally, so this module wraps in/out of `RefOr::new_item`
//!   at the bag boundary.
//!
//! Inline `RefOr<Header>` / `RefOr<Items>` slots are walked in
//! place but never lifted — v2 has no top-level `headers` or
//! `items` bag.

use std::collections::BTreeMap;

use crate::common::bool_or::BoolOr;
use crate::common::collapse::{Bag, HasLoader, LiftableBag, NameContext, lift_ref_or};
use crate::common::reference::RefOr;
use crate::loader::Loader;
use crate::v2::parameter::Parameter;
use crate::v2::path_item::{PathItem, Paths};
use crate::v2::response::{Response, Responses};
use crate::v2::schema::{ObjectSchema, Schema};
use crate::v2::spec::Spec;

pub use crate::common::collapse::CollapseError;

// ── Collapser: per-bag state + loader handle ────────────────────────────

pub(crate) struct Collapser<'a> {
    schemas: Bag<Schema>,
    parameters: Bag<Parameter>,
    responses: Bag<Response>,
    loader: Option<&'a mut Loader>,
}

impl HasLoader for Collapser<'_> {
    fn loader_mut(&mut self) -> Option<&mut Loader> {
        self.loader.as_deref_mut()
    }
}

// ── LiftableBag impls per component type ────────────────────────────────

impl<'a> LiftableBag<Collapser<'a>> for Schema {
    const PREFIX: &'static str = "#/definitions/";

    fn bag<'b>(c: &'b mut Collapser<'a>) -> &'b mut Bag<Self> {
        &mut c.schemas
    }

    fn walk(
        item: &mut Self,
        ctx: &NameContext,
        c: &mut Collapser<'a>,
    ) -> Result<(), CollapseError> {
        recurse_schema(item, ctx, c)
    }

    fn name_hint(item: &Self) -> Option<String> {
        schema_title(item).map(str::to_owned)
    }
}

impl<'a> LiftableBag<Collapser<'a>> for Parameter {
    const PREFIX: &'static str = "#/parameters/";

    fn bag<'b>(c: &'b mut Collapser<'a>) -> &'b mut Bag<Self> {
        &mut c.parameters
    }

    fn walk(
        item: &mut Self,
        ctx: &NameContext,
        c: &mut Collapser<'a>,
    ) -> Result<(), CollapseError> {
        walk_parameter(item, ctx, c)
    }

    fn name_hint(item: &Self) -> Option<String> {
        let hint = parameter_name_hint(item);
        if hint.is_empty() { None } else { Some(hint) }
    }
}

impl<'a> LiftableBag<Collapser<'a>> for Response {
    const PREFIX: &'static str = "#/responses/";

    fn bag<'b>(c: &'b mut Collapser<'a>) -> &'b mut Bag<Self> {
        &mut c.responses
    }

    fn walk(
        item: &mut Self,
        ctx: &NameContext,
        c: &mut Collapser<'a>,
    ) -> Result<(), CollapseError> {
        walk_response(item, ctx, c)
    }
}

// ── Walkers: per-type tree recursion ────────────────────────────────────

fn recurse_schema(
    schema: &mut Schema,
    ctx: &NameContext,
    c: &mut Collapser<'_>,
) -> Result<(), CollapseError> {
    match schema {
        Schema::AllOf(s) => {
            for (i, child) in s.all_of.iter_mut().enumerate() {
                lift_ref_or::<Schema, _>(child, ctx.push(&format!("allOf[{i}]")), c)?;
            }
        }
        Schema::Object(o) => recurse_object_schema(o.as_mut(), ctx, c)?,
        Schema::Array(a) => {
            if let Some(items) = a.items.as_mut() {
                lift_ref_or::<Schema, _>(items, ctx.push("items"), c)?;
            }
        }
        // Primitive variants (String, Integer, Number, Boolean, Null)
        // carry no nested schema slots.
        Schema::String(_)
        | Schema::Integer(_)
        | Schema::Number(_)
        | Schema::Boolean(_)
        | Schema::Null(_) => {}
    }
    Ok(())
}

fn recurse_object_schema(
    o: &mut ObjectSchema,
    ctx: &NameContext,
    c: &mut Collapser<'_>,
) -> Result<(), CollapseError> {
    if let Some(props) = o.properties.as_mut() {
        for (name, child) in props.iter_mut() {
            lift_ref_or::<Schema, _>(child, ctx.push(&format!("properties.{name}")), c)?;
        }
    }
    if let Some(BoolOr::Item(s)) = o.additional_properties.as_mut() {
        lift_ref_or::<Schema, _>(s, ctx.push("additionalProperties"), c)?;
    }
    // `all_of` holds `RefOr<ObjectSchema>` rather than `RefOr<Schema>` —
    // there's no `definitions` slot that matches `ObjectSchema` directly,
    // so we walk inline children in place rather than lifting them.
    if let Some(all_of) = o.all_of.as_mut() {
        for (i, child) in all_of.iter_mut().enumerate() {
            if let RefOr::Item(inner) = child {
                recurse_object_schema(inner, &ctx.push(&format!("allOf[{i}]")), c)?;
            }
        }
    }
    Ok(())
}

fn walk_parameter(
    param: &mut Parameter,
    ctx: &NameContext,
    c: &mut Collapser<'_>,
) -> Result<(), CollapseError> {
    // Only the Body variant carries a schema slot. The typed variants
    // (Header / Path / Query / FormData) encode their type inline and
    // have no nested ref slots.
    if let Parameter::Body(b) = param {
        let ctx = ctx.push(b.name.as_str());
        lift_ref_or::<Schema, _>(&mut b.schema, ctx.push("schema"), c)?;
    }
    Ok(())
}

fn walk_response(
    r: &mut Response,
    ctx: &NameContext,
    c: &mut Collapser<'_>,
) -> Result<(), CollapseError> {
    if let Some(s) = r.schema.as_mut() {
        lift_ref_or::<Schema, _>(s, ctx.push("schema"), c)?;
    }
    Ok(())
}

fn walk_responses(
    responses: &mut Responses,
    ctx: &NameContext,
    c: &mut Collapser<'_>,
) -> Result<(), CollapseError> {
    if let Some(default) = responses.default.as_mut() {
        lift_ref_or::<Response, _>(default, ctx.push("default"), c)?;
    }
    if let Some(map) = responses.responses.as_mut() {
        for (status, resp) in map.iter_mut() {
            lift_ref_or::<Response, _>(resp, ctx.push(status), c)?;
        }
    }
    Ok(())
}

fn walk_path_item(
    pi: &mut PathItem,
    ctx: NameContext,
    c: &mut Collapser<'_>,
) -> Result<(), CollapseError> {
    if let Some(params) = pi.parameters.as_mut() {
        for (i, p) in params.iter_mut().enumerate() {
            lift_ref_or::<Parameter, _>(p, ctx.push(&format!("parameters[{i}]")), c)?;
        }
    }
    if let Some(ops) = pi.operations.as_mut() {
        for (method, op) in ops.iter_mut() {
            walk_operation(op, ctx.push(method), c)?;
        }
    }
    Ok(())
}

fn walk_operation(
    op: &mut crate::v2::operation::Operation,
    ctx: NameContext,
    c: &mut Collapser<'_>,
) -> Result<(), CollapseError> {
    // Prefer `operationId` for naming the operation's children — it's
    // the canonical, author-chosen identifier and keeps derived names
    // stable across spec edits.
    let ctx = match op.operation_id.as_deref() {
        Some(id) if !id.is_empty() => NameContext::new([id]),
        _ => ctx,
    };
    if let Some(params) = op.parameters.as_mut() {
        for (i, p) in params.iter_mut().enumerate() {
            lift_ref_or::<Parameter, _>(p, ctx.push(&format!("parameters[{i}]")), c)?;
        }
    }
    walk_responses(&mut op.responses, &ctx.push("responses"), c)?;
    Ok(())
}

fn walk_paths(
    paths: &mut Paths,
    ctx: NameContext,
    c: &mut Collapser<'_>,
) -> Result<(), CollapseError> {
    for (path_key, pi) in paths.paths.iter_mut() {
        walk_path_item(pi, ctx.push(path_key), c)?;
    }
    Ok(())
}

// ── Orchestration ──────────────────────────────────────────────────────

pub(crate) fn collapse_spec(
    spec: &mut Spec,
    loader: Option<&mut Loader>,
) -> Result<(), CollapseError> {
    // Phase 0: take each existing root bag out of the spec. v2's
    // bags hold bare values; wrap them as `RefOr::Item` for the
    // shared `Bag<T>` storage.
    let initial_schemas = take_bare_bag(&mut spec.definitions);
    let initial_parameters = take_bare_bag(&mut spec.parameters);
    let initial_responses = take_bare_bag(&mut spec.responses);

    let mut c = Collapser {
        schemas: Bag::default(),
        parameters: Bag::default(),
        responses: Bag::default(),
        loader,
    };

    // Phase 1: seed every bag from its existing entries so dedup
    // collapses newly-lifted equivalents onto the existing names.
    c.schemas.seed(initial_schemas)?;
    c.parameters.seed(initial_parameters)?;
    c.responses.seed(initial_responses)?;

    // Phase 2a: recurse into each pre-existing inline component,
    // lifting its nested children.
    recurse_existing::<Schema>(&mut c, &["definitions"])?;
    recurse_existing::<Parameter>(&mut c, &["parameters"])?;
    recurse_existing::<Response>(&mut c, &["responses"])?;

    // Phase 2b: walk paths. `spec.paths` is required (no `Option`
    // wrapper) in v2.
    walk_paths(&mut spec.paths, NameContext::new(["paths"]), &mut c)?;

    // Phase 3: write each lifted bag back into the spec, unwrapping
    // the `RefOr::Item` shell at the boundary.
    if !c.schemas.is_empty() {
        spec.definitions = Some(unwrap_bag(c.schemas.into_map()));
    }
    if !c.parameters.is_empty() {
        spec.parameters = Some(unwrap_bag(c.parameters.into_map()));
    }
    if !c.responses.is_empty() {
        spec.responses = Some(unwrap_bag(c.responses.into_map()));
    }

    Ok(())
}

fn take_bare_bag<T>(slot: &mut Option<BTreeMap<String, T>>) -> BTreeMap<String, RefOr<T>> {
    slot.take()
        .map(|m| {
            m.into_iter()
                .map(|(k, v)| (k, RefOr::new_item(v)))
                .collect()
        })
        .unwrap_or_default()
}

fn unwrap_bag<T>(m: BTreeMap<String, RefOr<T>>) -> BTreeMap<String, T> {
    m.into_iter()
        .map(|(k, v)| match v {
            RefOr::Item(item) => (k, item),
            // v2 bag entries can't themselves be `$ref` slots — the
            // shared `Bag<T>` only ever stores `Item` variants via
            // `seed`/`intern`. A `Ref` here is a hard invariant
            // violation in the shared collapse machinery; panic in
            // *every* build so a regression surfaces immediately
            // rather than as silently dropped definitions.
            RefOr::Ref(r) => unreachable!(
                "v2 bag entry `{k}` is a $ref (`{}`) but bare bags can't hold refs",
                r.reference,
            ),
        })
        .collect()
}

/// Generic phase-2a driver: snapshot inline names of `T`'s bag,
/// pull each out, walk via the trait's `walk`, put back with
/// refreshed canonical form.
fn recurse_existing<T>(c: &mut Collapser<'_>, ctx_root: &[&str]) -> Result<(), CollapseError>
where
    T: for<'b> LiftableBag<Collapser<'b>>,
{
    let names = T::bag(c).inline_names();
    for name in names {
        let Some(mut item) = T::bag(c).take_inline(&name) else {
            continue;
        };
        let mut parts: Vec<String> = ctx_root.iter().map(|s| (*s).to_owned()).collect();
        parts.push(name.clone());
        let ctx = NameContext::new(parts);
        T::walk(&mut item, &ctx, c)?;
        T::bag(c).put_inline(name, item)?;
    }
    Ok(())
}

// ── Version-specific helpers ────────────────────────────────────────────

/// `<name><In>` hint for a v2 `Parameter` — e.g. `limitQuery`,
/// `petBody`. Returns `""` when the parameter has no usable name,
/// signalling the intern path to fall back to context-derived
/// naming.
fn parameter_name_hint(param: &Parameter) -> String {
    use crate::v2::parameter::{InFormData, InHeader, InPath, InQuery};
    let (name, in_) = match param {
        Parameter::Body(p) => (p.name.as_str(), "Body"),
        Parameter::Header(p) => {
            let name = match p.as_ref() {
                InHeader::String(p) => p.name.as_str(),
                InHeader::Integer(p) => p.name.as_str(),
                InHeader::Number(p) => p.name.as_str(),
                InHeader::Boolean(p) => p.name.as_str(),
                InHeader::Array(p) => p.name.as_str(),
            };
            (name, "Header")
        }
        Parameter::Path(p) => {
            let name = match p.as_ref() {
                InPath::String(p) => p.name.as_str(),
                InPath::Integer(p) => p.name.as_str(),
                InPath::Number(p) => p.name.as_str(),
                InPath::Boolean(p) => p.name.as_str(),
                InPath::Array(p) => p.name.as_str(),
            };
            (name, "Path")
        }
        Parameter::Query(p) => {
            let name = match p.as_ref() {
                InQuery::String(p) => p.name.as_str(),
                InQuery::Integer(p) => p.name.as_str(),
                InQuery::Number(p) => p.name.as_str(),
                InQuery::Boolean(p) => p.name.as_str(),
                InQuery::Array(p) => p.name.as_str(),
            };
            (name, "Query")
        }
        Parameter::FormData(p) => {
            let name = match p.as_ref() {
                InFormData::String(p) => p.name.as_str(),
                InFormData::Integer(p) => p.name.as_str(),
                InFormData::Number(p) => p.name.as_str(),
                InFormData::Boolean(p) => p.name.as_str(),
                InFormData::Array(p) => p.name.as_str(),
                InFormData::File(p) => p.name.as_str(),
            };
            (name, "FormData")
        }
    };
    if name.is_empty() {
        String::new()
    } else {
        format!("{name}{in_}")
    }
}

fn schema_title(schema: &Schema) -> Option<&str> {
    match schema {
        Schema::AllOf(s) => s.title.as_deref(),
        Schema::Object(s) => s.title.as_deref(),
        Schema::Array(s) => s.title.as_deref(),
        Schema::String(s) => s.title.as_deref(),
        Schema::Integer(s) => s.title.as_deref(),
        Schema::Number(s) => s.title.as_deref(),
        Schema::Boolean(s) => s.title.as_deref(),
        Schema::Null(s) => s.title.as_deref(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(value: serde_json::Value) -> Spec {
        serde_json::from_value(value).expect("spec parses")
    }

    fn lifted_schema_names(spec: &Spec) -> Vec<String> {
        spec.definitions
            .as_ref()
            .map(|m| m.keys().cloned().collect())
            .unwrap_or_default()
    }

    fn lifted_parameter_names(spec: &Spec) -> Vec<String> {
        spec.parameters
            .as_ref()
            .map(|m| m.keys().cloned().collect())
            .unwrap_or_default()
    }

    fn lifted_response_names(spec: &Spec) -> Vec<String> {
        spec.responses
            .as_ref()
            .map(|m| m.keys().cloned().collect())
            .unwrap_or_default()
    }

    fn schema_at(spec: &Spec, name: &str) -> serde_json::Value {
        let item = spec
            .definitions
            .as_ref()
            .and_then(|m| m.get(name))
            .expect("schema present");
        serde_json::to_value(item).unwrap()
    }

    #[test]
    fn lift_inline_body_parameter_schema_into_definitions() {
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {
                "/pets": {
                    "post": {
                        "operationId": "createPet",
                        "parameters": [
                            {
                                "in": "body",
                                "name": "pet",
                                "schema": {"title": "Pet", "type": "object", "properties": {"id": {"type": "integer"}}}
                            }
                        ],
                        "responses": {"200": {"description": "ok"}}
                    }
                }
            }
        }));
        spec.collapse(None).expect("collapse ok");
        let names = lifted_schema_names(&spec);
        assert!(names.contains(&"Pet".to_owned()), "got {names:?}");
        let v = serde_json::to_value(&spec).unwrap();
        // The parameter is itself lifted (it's the inline first hit),
        // so dig through `parameters.<name>` to reach the schema ref.
        let p_ref = v["paths"]["/pets"]["post"]["parameters"][0]["$ref"]
            .as_str()
            .expect("parameter lifted");
        let p_name = p_ref.trim_start_matches("#/parameters/");
        assert_eq!(
            v["parameters"][p_name]["schema"]["$ref"],
            "#/definitions/Pet"
        );
    }

    #[test]
    fn lift_inline_response_schema_into_definitions() {
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {
                "/pets": {
                    "get": {
                        "operationId": "listPets",
                        "responses": {
                            "200": {
                                "description": "ok",
                                "schema": {"title": "Pet", "type": "object", "properties": {"id": {"type": "integer"}}}
                            }
                        }
                    }
                }
            }
        }));
        spec.collapse(None).expect("collapse ok");
        let v = serde_json::to_value(&spec).unwrap();
        let resp_ref = v["paths"]["/pets"]["get"]["responses"]["200"]["$ref"]
            .as_str()
            .expect("response lifted");
        let resp_name = resp_ref.trim_start_matches("#/responses/");
        assert_eq!(
            v["responses"][resp_name]["schema"]["$ref"],
            "#/definitions/Pet"
        );
        assert!(lifted_schema_names(&spec).contains(&"Pet".to_owned()));
    }

    #[test]
    fn parameter_name_hint_picks_up_typed_variants() {
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {
                "/pets/{id}": {
                    "get": {
                        "operationId": "getPet",
                        "parameters": [
                            {"name": "id", "in": "path", "required": true, "type": "integer"},
                            {"name": "tag", "in": "query", "type": "string"},
                            {"name": "x-trace", "in": "header", "type": "string"}
                        ],
                        "responses": {"200": {"description": "ok"}}
                    }
                }
            }
        }));
        spec.collapse(None).unwrap();
        let names = lifted_parameter_names(&spec);
        for expected in ["idPath", "tagQuery", "x-traceHeader"] {
            assert!(
                names.contains(&expected.to_owned()),
                "missing `{expected}`: {names:?}"
            );
        }
    }

    #[test]
    fn identical_inline_responses_dedupe_to_one_definition() {
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {
                "/a": {"get": {"operationId": "a", "responses": {"200": {"description": "ok"}}}},
                "/b": {"get": {"operationId": "b", "responses": {"200": {"description": "ok"}}}}
            }
        }));
        spec.collapse(None).unwrap();
        let v = serde_json::to_value(&spec).unwrap();
        // Both call sites point at the same lifted response.
        assert_eq!(
            v["paths"]["/a"]["get"]["responses"]["200"]["$ref"],
            v["paths"]["/b"]["get"]["responses"]["200"]["$ref"],
        );
        assert_eq!(lifted_response_names(&spec).len(), 1);
    }

    #[test]
    fn identical_named_inline_schemas_dedupe_to_one_definition() {
        // Two distinct paths whose bodies share the same titled
        // schema collapse onto one `definitions.<title>` entry.
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {
                "/a": {
                    "post": {
                        "operationId": "a",
                        "parameters": [
                            {"in": "body", "name": "body", "schema": {"title": "Body", "type": "string"}}
                        ],
                        "responses": {"200": {"description": "ok"}}
                    }
                },
                "/b": {
                    "post": {
                        "operationId": "b",
                        "parameters": [
                            {"in": "body", "name": "body", "schema": {"title": "Body", "type": "string"}}
                        ],
                        "responses": {"200": {"description": "ok"}}
                    }
                }
            }
        }));
        spec.collapse(None).unwrap();
        assert_eq!(lifted_schema_names(&spec), vec!["Body".to_owned()]);
    }

    #[test]
    fn existing_definitions_keep_names_and_recurse_children() {
        // A pre-existing `definitions.Pet` keeps its name; the nested
        // inline schema inside it lifts as a new definition.
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {},
            "definitions": {
                "Pet": {
                    "type": "object",
                    "properties": {
                        "extras": {"title": "Extras", "type": "object", "properties": {"v": {"type": "string"}}}
                    }
                }
            }
        }));
        spec.collapse(None).unwrap();
        let names = lifted_schema_names(&spec);
        assert!(names.contains(&"Pet".to_owned()), "got {names:?}");
        assert!(names.contains(&"Extras".to_owned()), "got {names:?}");
        let pet = schema_at(&spec, "Pet");
        assert_eq!(pet["properties"]["extras"]["$ref"], "#/definitions/Extras");
    }

    #[test]
    fn object_allof_children_stay_inline_but_inner_schemas_lift() {
        // OAS 2.0's `ObjectSchema.all_of` is `Vec<RefOr<ObjectSchema>>`
        // — there's no `definitions` slot that matches `ObjectSchema`
        // directly, so inline allOf children are walked in place. Their
        // nested `properties.<x>` slots (which hold `RefOr<Schema>`)
        // still lift normally.
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {},
            "definitions": {
                "Pet": {
                    "allOf": [
                        {"title": "PetBase", "type": "object", "properties": {"id": {"title": "Id", "type": "integer"}}}
                    ]
                }
            }
        }));
        spec.collapse(None).unwrap();
        let names = lifted_schema_names(&spec);
        assert!(names.contains(&"Id".to_owned()), "got {names:?}");
        // The PetBase ObjectSchema itself isn't lifted — it stays
        // inline under definitions.Pet.allOf[0].
        let v = serde_json::to_value(&spec).unwrap();
        assert!(
            v["definitions"]["Pet"]["allOf"][0]["title"] == "PetBase",
            "allOf child must stay inline: {:?}",
            v["definitions"]["Pet"]["allOf"][0]
        );
        assert_eq!(
            v["definitions"]["Pet"]["allOf"][0]["properties"]["id"]["$ref"],
            "#/definitions/Id"
        );
    }

    #[test]
    fn array_items_lift_into_definitions() {
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {},
            "definitions": {
                "Pets": {
                    "type": "array",
                    "items": {"title": "Pet", "type": "object", "properties": {"id": {"type": "integer"}}}
                }
            }
        }));
        spec.collapse(None).unwrap();
        assert!(lifted_schema_names(&spec).contains(&"Pet".to_owned()));
        let pets = schema_at(&spec, "Pets");
        assert_eq!(pets["items"]["$ref"], "#/definitions/Pet");
    }

    #[test]
    fn internal_ref_slots_are_untouched() {
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {
                "/a": {
                    "get": {
                        "operationId": "a",
                        "responses": {
                            "200": {"description": "ok", "schema": {"$ref": "#/definitions/Pet"}}
                        }
                    }
                }
            },
            "definitions": {
                "Pet": {"type": "object", "properties": {"id": {"type": "integer"}}}
            }
        }));
        spec.collapse(None).unwrap();
        let v = serde_json::to_value(&spec).unwrap();
        let resp_ref = v["paths"]["/a"]["get"]["responses"]["200"]["$ref"]
            .as_str()
            .expect("response lifted");
        let resp_name = resp_ref.trim_start_matches("#/responses/");
        assert_eq!(
            v["responses"][resp_name]["schema"]["$ref"],
            "#/definitions/Pet"
        );
    }

    #[test]
    fn external_ref_without_loader_is_left_alone() {
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {
                "/a": {
                    "get": {
                        "operationId": "a",
                        "parameters": [{"$ref": "shared.json#/PageParam"}],
                        "responses": {
                            "200": {"$ref": "shared.json#/Ok"}
                        }
                    }
                }
            }
        }));
        spec.collapse(None).unwrap();
        let v = serde_json::to_value(&spec).unwrap();
        assert_eq!(
            v["paths"]["/a"]["get"]["parameters"][0]["$ref"],
            "shared.json#/PageParam"
        );
        assert_eq!(
            v["paths"]["/a"]["get"]["responses"]["200"]["$ref"],
            "shared.json#/Ok"
        );
    }

    #[test]
    fn loader_resolves_external_schema_refs() {
        let mut loader = Loader::new();
        loader
            .preload_resource(
                "shared.json",
                serde_json::json!({
                    "Pet": {"title": "Pet", "type": "object", "properties": {"id": {"type": "integer"}}}
                }),
            )
            .unwrap();
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {
                "/pets": {
                    "post": {
                        "operationId": "createPet",
                        "parameters": [
                            {
                                "in": "body",
                                "name": "pet",
                                "schema": {"$ref": "shared.json#/Pet"}
                            }
                        ],
                        "responses": {"200": {"description": "ok"}}
                    }
                }
            }
        }));
        spec.collapse(Some(&mut loader)).unwrap();
        assert!(lifted_schema_names(&spec).contains(&"Pet".to_owned()));
    }

    #[test]
    fn round_trips_through_serde_after_collapse() {
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {
                "/pets": {
                    "get": {
                        "operationId": "listPets",
                        "responses": {
                            "200": {"description": "ok", "schema": {"title": "Pet", "type": "object", "properties": {"id": {"type": "integer"}}}}
                        }
                    }
                }
            }
        }));
        spec.collapse(None).unwrap();
        let s = serde_json::to_string(&spec).unwrap();
        let _: Spec = serde_json::from_str(&s).expect("re-parses");
    }

    // ── Recursion: top-level Schema::AllOf with typed (non-object)
    //    children, which is the only shape that escapes the ObjectSchema
    //    untagged-deserialisation path. Forces the AllOf branch of
    //    `recurse_schema` to actually run.

    #[test]
    fn top_level_schema_allof_recurses_through_children() {
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {},
            "definitions": {
                // Children with explicit non-object `type` values defeat
                // ObjectSchema's permissive default and force the parse
                // through `Schema::AllOf`.
                "Mixed": {
                    "allOf": [
                        {"title": "A", "type": "string"},
                        {"title": "B", "type": "integer"}
                    ]
                }
            }
        }));
        spec.collapse(None).unwrap();
        let names = lifted_schema_names(&spec);
        for s in ["A", "B"] {
            assert!(names.contains(&s.to_owned()), "missing `{s}`: {names:?}");
        }
        let v = serde_json::to_value(&spec).unwrap();
        assert_eq!(
            v["definitions"]["Mixed"]["allOf"][0]["$ref"],
            "#/definitions/A"
        );
        assert_eq!(
            v["definitions"]["Mixed"]["allOf"][1]["$ref"],
            "#/definitions/B"
        );
    }

    // ── Recursion: ObjectSchema.additionalProperties (Item branch). ──────

    #[test]
    fn object_additional_properties_with_inline_schema_is_lifted() {
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {},
            "definitions": {
                "Map": {
                    "type": "object",
                    "additionalProperties": {"title": "Val", "type": "string"}
                }
            }
        }));
        spec.collapse(None).unwrap();
        assert!(lifted_schema_names(&spec).contains(&"Val".to_owned()));
        let v = serde_json::to_value(&spec).unwrap();
        assert_eq!(
            v["definitions"]["Map"]["additionalProperties"]["$ref"],
            "#/definitions/Val"
        );
    }

    // ── Walker coverage: Responses.default lifting. ───────────────────────

    #[test]
    fn default_response_is_walked_and_lifted() {
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {
                "/x": {
                    "get": {
                        "operationId": "x",
                        "responses": {
                            "default": {
                                "description": "fallback",
                                "schema": {"title": "Err", "type": "object", "properties": {"msg": {"type": "string"}}}
                            }
                        }
                    }
                }
            }
        }));
        spec.collapse(None).unwrap();
        assert!(lifted_schema_names(&spec).contains(&"Err".to_owned()));
        let v = serde_json::to_value(&spec).unwrap();
        // The default response is itself lifted to `#/responses/<name>`.
        let resp_ref = v["paths"]["/x"]["get"]["responses"]["default"]["$ref"]
            .as_str()
            .expect("default response lifted");
        let resp_name = resp_ref.trim_start_matches("#/responses/");
        assert_eq!(
            v["responses"][resp_name]["schema"]["$ref"],
            "#/definitions/Err"
        );
    }

    // ── Walker coverage: PathItem-level parameters list. ──────────────────

    #[test]
    fn path_item_level_parameters_are_walked() {
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {
                "/x/{id}": {
                    // PathItem.parameters — distinct from operation-level
                    // ones; the walker must hit them too.
                    "parameters": [
                        {"name": "id", "in": "path", "required": true, "type": "string"}
                    ],
                    "get": {
                        "operationId": "x",
                        "responses": {"200": {"description": "ok"}}
                    }
                }
            }
        }));
        spec.collapse(None).unwrap();
        assert!(
            lifted_parameter_names(&spec).contains(&"idPath".to_owned()),
            "got {:?}",
            lifted_parameter_names(&spec),
        );
    }

    // ── Walker coverage: Operation.operationId fallback when missing. ─────

    #[test]
    fn operation_without_operation_id_uses_context_path() {
        // Without an `operationId`, the walker keeps the inherited
        // `paths.<path>.<method>` context for derived names instead of
        // jumping to an operation-id-rooted context.
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {
                "/x": {
                    "post": {
                        "parameters": [
                            {"in": "body", "name": "body", "schema": {"type": "object", "properties": {"v": {"type": "string"}}}}
                        ],
                        "responses": {"200": {"description": "ok"}}
                    }
                }
            }
        }));
        spec.collapse(None).unwrap();
        let names = lifted_parameter_names(&spec);
        assert!(names.contains(&"bodyBody".to_owned()), "got {names:?}",);
    }

    // ── parameter_name_hint coverage: every typed variant ── ──────────────

    #[test]
    fn parameter_name_hint_picks_up_every_typed_variant() {
        // Lifting one parameter per (`in`, `type`) pair walks each arm
        // of `parameter_name_hint`'s nested match. The names are picked
        // so the lifted entries are distinct — otherwise dedup would
        // hide branches that did execute.
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {
                "/x": {
                    "post": {
                        "operationId": "kitchenSink",
                        "parameters": [
                            // Header: integer, number, boolean, array.
                            {"name": "h_int", "in": "header", "type": "integer"},
                            {"name": "h_num", "in": "header", "type": "number"},
                            {"name": "h_bool", "in": "header", "type": "boolean"},
                            {"name": "h_arr", "in": "header", "type": "array", "items": {"type": "string"}},
                            // Path: every typed variant.
                            {"name": "p_str", "in": "path", "required": true, "type": "string"},
                            {"name": "p_int", "in": "path", "required": true, "type": "integer"},
                            {"name": "p_num", "in": "path", "required": true, "type": "number"},
                            {"name": "p_bool", "in": "path", "required": true, "type": "boolean"},
                            {"name": "p_arr", "in": "path", "required": true, "type": "array", "items": {"type": "string"}},
                            // Query: every typed variant.
                            {"name": "q_str", "in": "query", "type": "string"},
                            {"name": "q_int", "in": "query", "type": "integer"},
                            {"name": "q_num", "in": "query", "type": "number"},
                            {"name": "q_bool", "in": "query", "type": "boolean"},
                            {"name": "q_arr", "in": "query", "type": "array", "items": {"type": "string"}},
                            // FormData: every typed variant including File.
                            {"name": "f_str", "in": "formData", "type": "string"},
                            {"name": "f_int", "in": "formData", "type": "integer"},
                            {"name": "f_num", "in": "formData", "type": "number"},
                            {"name": "f_bool", "in": "formData", "type": "boolean"},
                            {"name": "f_arr", "in": "formData", "type": "array", "items": {"type": "string"}},
                            {"name": "f_file", "in": "formData", "type": "file"}
                        ],
                        "responses": {"200": {"description": "ok"}}
                    }
                }
            }
        }));
        spec.collapse(None).unwrap();
        let names = lifted_parameter_names(&spec);
        for expected in [
            "h_intHeader",
            "h_numHeader",
            "h_boolHeader",
            "h_arrHeader",
            "p_strPath",
            "p_intPath",
            "p_numPath",
            "p_boolPath",
            "p_arrPath",
            "q_strQuery",
            "q_intQuery",
            "q_numQuery",
            "q_boolQuery",
            "q_arrQuery",
            "f_strFormData",
            "f_intFormData",
            "f_numFormData",
            "f_boolFormData",
            "f_arrFormData",
            "f_fileFormData",
        ] {
            assert!(
                names.contains(&expected.to_owned()),
                "missing `{expected}`: {names:?}",
            );
        }
    }

    // ── schema_title helper: every titled Schema variant. ─────────────────

    #[test]
    fn schema_title_picks_up_every_titled_variant() {
        // Each variant's `title` lifts to a `definitions.<title>` entry,
        // exercising the matching arm of `schema_title`.
        let mut spec = parse(serde_json::json!({
            "swagger": "2.0",
            "info": {"title": "x", "version": "1"},
            "paths": {},
            "definitions": {
                // Container with one nested ref slot per variant. Putting
                // them under `properties` walks each through the lifter.
                "Holder": {
                    "type": "object",
                    "properties": {
                        "s": {"title": "TStr", "type": "string"},
                        "i": {"title": "TInt", "type": "integer"},
                        "n": {"title": "TNum", "type": "number"},
                        "b": {"title": "TBool", "type": "boolean"},
                        "a": {"title": "TArr", "type": "array", "items": {"type": "string"}},
                        "nul": {"title": "TNull", "type": "null"},
                        "allof": {"title": "TAllOf", "allOf": [{"type": "string"}]}
                    }
                }
            }
        }));
        spec.collapse(None).unwrap();
        let names = lifted_schema_names(&spec);
        for s in ["TStr", "TInt", "TNum", "TBool", "TArr", "TNull", "TAllOf"] {
            assert!(names.contains(&s.to_owned()), "missing `{s}`: {names:?}");
        }
    }
}