oag-core 0.20.6

OpenAPI 3.2 parser, IR, and transforms for oag
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
use oag_core::ir::{IrParameterLocation, IrReturnType, IrSchema, IrType};
use oag_core::parse;
use oag_core::transform;

const SSE_CHAT: &str = include_str!("fixtures/sse-chat.yaml");
const PETSTORE: &str = include_str!("fixtures/petstore-3.2.yaml");
const MIXED: &str = include_str!("fixtures/mixed-endpoints.yaml");
const ANTHROPIC: &str = include_str!("fixtures/anthropic-messages.yaml");
const PETSTORE_POLY: &str = include_str!("fixtures/petstore-polymorphic.yaml");
const INTEGER_DISC: &str = include_str!("fixtures/integer-discriminator.yaml");
const LITERAL_DEFAULT: &str = include_str!("fixtures/literal-default.yaml");

#[test]
fn transform_sse_chat() {
    let spec = parse::from_yaml(SSE_CHAT).unwrap();
    let ir = transform::transform(&spec).unwrap();

    assert_eq!(ir.info.title, "AI Chat API");
    assert!(!ir.schemas.is_empty());
    assert!(!ir.operations.is_empty());

    // Check that we have SSE operations
    let stream_op = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "createChatCompletionStream")
        .expect("should have createChatCompletionStream");

    match &stream_op.return_type {
        IrReturnType::Sse(sse) => {
            assert!(sse.event_type_name.is_some(), "should have event type name");
            assert_eq!(sse.variants.len(), 2, "should have 2 SSE event variants");
            assert!(
                !sse.also_has_json,
                "stream-only endpoint should not have JSON"
            );
        }
        _ => panic!("expected SSE return type"),
    }

    // Check dual endpoint
    let dual_op = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "createChatCompletion")
        .expect("should have createChatCompletion");

    match &dual_op.return_type {
        IrReturnType::Sse(sse) => {
            assert!(sse.also_has_json, "dual endpoint should have JSON");
            assert!(sse.json_response.is_some());
        }
        _ => panic!("expected SSE return type for dual endpoint"),
    }
}

#[test]
fn transform_petstore() {
    let spec = parse::from_yaml(PETSTORE).unwrap();
    let ir = transform::transform(&spec).unwrap();

    assert_eq!(ir.info.title, "Petstore");

    // Check schema types
    let pet = ir.schemas.iter().find(|s| s.name().pascal_case == "Pet");
    assert!(pet.is_some(), "should have Pet schema");
    match pet.unwrap() {
        IrSchema::Object(obj) => {
            assert!(obj.fields.len() >= 3);
        }
        _ => panic!("Pet should be an object schema"),
    }

    let status = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "PetStatus");
    assert!(status.is_some(), "should have PetStatus schema");
    match status.unwrap() {
        IrSchema::Enum(e) => {
            assert_eq!(e.variants.len(), 3);
        }
        _ => panic!("PetStatus should be an enum"),
    }

    // Check operations
    assert!(!ir.operations.is_empty());
    let list_op = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "listPets")
        .expect("should have listPets");
    assert_eq!(list_op.parameters.len(), 2); // limit, status

    let delete_op = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "deletePet")
        .expect("should have deletePet");
    match &delete_op.return_type {
        IrReturnType::Void => {}
        _ => panic!("deletePet should return void"),
    }
}

#[test]
fn transform_mixed() {
    let spec = parse::from_yaml(MIXED).unwrap();
    let ir = transform::transform(&spec).unwrap();

    // Check SSE endpoint without itemSchema (fallback to schema)
    let stream_op = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "streamEvents")
        .expect("should have streamEvents");

    match &stream_op.return_type {
        IrReturnType::Sse(sse) => {
            assert!(!sse.also_has_json);
            // Event type should be resolved from schema
            assert!(
                sse.event_type_name.is_none(),
                "no itemSchema oneOf, so no event type name"
            );
        }
        _ => panic!("expected SSE return type"),
    }

    // Check style/explode propagation on listItems parameters
    let list_items = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "listItems")
        .expect("should have listItems");

    let tags_param = list_items
        .parameters
        .iter()
        .find(|p| p.original_name == "tags")
        .unwrap();
    assert_eq!(tags_param.style, Some("form".to_string()));
    assert_eq!(tags_param.explode, Some(false));

    let filter_param = list_items
        .parameters
        .iter()
        .find(|p| p.original_name == "filter")
        .unwrap();
    assert_eq!(filter_param.style, Some("deepObject".to_string()));
    assert_eq!(filter_param.explode, Some(true));

    // Params without explicit style/explode should be None
    let page_param = list_items
        .parameters
        .iter()
        .find(|p| p.original_name == "page")
        .unwrap();
    assert_eq!(page_param.style, None);
    assert_eq!(page_param.explode, None);
}

#[test]
fn transform_202_with_body_is_mapped() {
    let spec = parse::from_yaml(MIXED).unwrap();
    let ir = transform::transform(&spec).unwrap();

    // A 202 Accepted response that declares a body must be mapped to that body
    // type, not collapsed to void (OpenAPI 3.2 allows bodies on any 2xx code).
    let enqueue = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "enqueueJob")
        .expect("should have enqueueJob");

    match &enqueue.return_type {
        IrReturnType::Standard(resp) => {
            assert!(
                matches!(&resp.response_type, IrType::Ref(name) if name == "Job"),
                "enqueueJob (202) should return the Job body, got {:?}",
                resp.response_type
            );
            assert_eq!(
                resp.status_code, 202,
                "the 202 status code must be retained so server stubs stay compliant"
            );
        }
        other => panic!("enqueueJob should map its 202 body, got {other:?}"),
    }

    // A 204 with no content must still be void (regression guard).
    let delete = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "deleteItem")
        .expect("should have deleteItem");
    assert!(
        matches!(delete.return_type, IrReturnType::Void),
        "deleteItem (204, no body) should remain void"
    );
}

/// Build the return type for a single-operation spec from its responses block.
fn return_type_for(responses_yaml: &str) -> IrReturnType {
    let spec = format!(
        r#"
openapi: "3.2.0"
info:
  title: T
  version: "1.0"
paths:
  /thing:
    get:
      operationId: getThing
      responses:
{responses_yaml}
components:
  schemas:
    Thing:
      type: object
      properties:
        id:
          type: string
"#
    );
    let parsed = parse::from_yaml(&spec).unwrap();
    let ir = transform::transform(&parsed).unwrap();
    ir.operations
        .into_iter()
        .find(|op| op.name.camel_case == "getThing")
        .expect("should have getThing")
        .return_type
}

#[test]
fn transform_200_body_is_retained() {
    // The primary success case: a 200 with a body is mapped, never void.
    let rt = return_type_for(
        r##"        "200":
          description: ok
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Thing""##,
    );
    assert!(
        matches!(&rt, IrReturnType::Standard(r) if matches!(&r.response_type, IrType::Ref(n) if n == "Thing")),
        "200 with a body should return the body type, got {rt:?}"
    );
}

#[test]
fn transform_body_bearing_2xx_wins_over_empty_200() {
    // An empty 200 alongside a 202 that declares a body must not collapse the
    // operation to void — the 202 body wins.
    let rt = return_type_for(
        r##"        "200":
          description: accepted, no content
        "202":
          description: queued
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Thing""##,
    );
    assert!(
        matches!(&rt, IrReturnType::Standard(r) if matches!(&r.response_type, IrType::Ref(n) if n == "Thing")),
        "a bodyless 200 must not hide a 202 body, got {rt:?}"
    );
}

#[test]
fn transform_all_bodyless_2xx_is_void() {
    // When no success response carries a body, the operation is void.
    let rt = return_type_for(
        r##"        "200":
          description: ok
        "204":
          description: no content"##,
    );
    assert!(
        matches!(rt, IrReturnType::Void),
        "bodyless success responses should be void, got {rt:?}"
    );
}

#[test]
fn transform_modules_grouping() {
    let spec = parse::from_yaml(SSE_CHAT).unwrap();
    let ir = transform::transform(&spec).unwrap();

    assert!(
        ir.modules.len() >= 2,
        "should have at least chat and models modules"
    );

    let chat_module = ir
        .modules
        .iter()
        .find(|m| m.name.original == "chat")
        .expect("should have chat module");
    assert!(!chat_module.operations.is_empty());

    let models_module = ir
        .modules
        .iter()
        .find(|m| m.name.original == "models")
        .expect("should have models module");
    assert!(!models_module.operations.is_empty());
}

#[test]
fn transform_request_body() {
    let spec = parse::from_yaml(SSE_CHAT).unwrap();
    let ir = transform::transform(&spec).unwrap();

    let create_op = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "createChatCompletion")
        .expect("should have createChatCompletion");

    let body = create_op
        .request_body
        .as_ref()
        .expect("should have request body");
    assert!(body.required);
    assert_eq!(body.content_type, "application/json");
}

#[test]
fn transform_void_response() {
    let spec = parse::from_yaml(SSE_CHAT).unwrap();
    let ir = transform::transform(&spec).unwrap();

    let feedback_op = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "submitFeedback")
        .expect("should have submitFeedback");

    match &feedback_op.return_type {
        IrReturnType::Void => {}
        _ => panic!("submitFeedback should return void"),
    }
}

#[test]
fn transform_anthropic_messages() {
    let spec = parse::from_yaml(ANTHROPIC).unwrap();
    let ir = transform::transform(&spec).unwrap();

    assert_eq!(ir.info.title, "Anthropic Messages API");

    // --- ContentBlock: discriminated union with 4 Ref variants ---
    let content_block = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "ContentBlock")
        .expect("should have ContentBlock schema");
    match content_block {
        IrSchema::Union(u) => {
            assert_eq!(u.variants.len(), 4, "ContentBlock should have 4 variants");
            assert!(
                matches!(&u.variants[0], IrType::Ref(name) if name == "TextBlock"),
                "first variant should be Ref(TextBlock)"
            );
            assert!(
                matches!(&u.variants[1], IrType::Ref(name) if name == "ImageBlock"),
                "second variant should be Ref(ImageBlock)"
            );
            let disc = u.discriminator.as_ref().expect("should have discriminator");
            assert_eq!(disc.property_name, "type");
            assert_eq!(disc.mapping.len(), 4);
            assert_eq!(
                disc.mapping.iter().find(|(k, _)| k == "text").unwrap().1,
                "TextBlock"
            );
            assert_eq!(
                disc.mapping.iter().find(|(k, _)| k == "image").unwrap().1,
                "ImageBlock"
            );
        }
        _ => panic!("ContentBlock should be a Union"),
    }

    // --- StreamDelta: discriminated union with 2 Ref variants ---
    let stream_delta = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "StreamDelta")
        .expect("should have StreamDelta schema");
    match stream_delta {
        IrSchema::Union(u) => {
            assert_eq!(u.variants.len(), 2, "StreamDelta should have 2 variants");
            assert!(
                matches!(&u.variants[0], IrType::Ref(name) if name == "TextDelta"),
                "first variant should be Ref(TextDelta)"
            );
            assert!(
                matches!(&u.variants[1], IrType::Ref(name) if name == "InputJsonDelta"),
                "second variant should be Ref(InputJsonDelta)"
            );
            let disc = u.discriminator.as_ref().expect("should have discriminator");
            assert_eq!(disc.property_name, "type");
        }
        _ => panic!("StreamDelta should be a Union"),
    }

    // --- ToolResultContent: anyOf union with Ref variants, NO discriminator ---
    let tool_result_content = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "ToolResultContent")
        .expect("should have ToolResultContent schema");
    match tool_result_content {
        IrSchema::Union(u) => {
            assert_eq!(
                u.variants.len(),
                2,
                "ToolResultContent should have 2 variants"
            );
            assert!(
                matches!(&u.variants[0], IrType::Ref(name) if name == "TextBlock"),
                "first variant should be Ref(TextBlock)"
            );
            assert!(
                matches!(&u.variants[1], IrType::Ref(name) if name == "ImageBlock"),
                "second variant should be Ref(ImageBlock)"
            );
            assert!(
                u.discriminator.is_none(),
                "anyOf should have no discriminator"
            );
        }
        _ => panic!("ToolResultContent should be a Union"),
    }

    // --- MessageStartEvent: allOf merged into Object ---
    let msg_start = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "MessageStartEvent")
        .expect("should have MessageStartEvent schema");
    match msg_start {
        IrSchema::Object(obj) => {
            assert!(
                obj.fields.iter().any(|f| f.original_name == "type"),
                "should have type field"
            );
            let message_field = obj
                .fields
                .iter()
                .find(|f| f.original_name == "message")
                .expect("should have message field");
            assert!(
                matches!(&message_field.field_type, IrType::Ref(name) if name == "MessageResponse"),
                "message field should reference MessageResponse"
            );
        }
        _ => panic!("MessageStartEvent should be an Object (merged allOf)"),
    }

    // --- TextBlock.type is StringLiteral("text") ---
    let text_block = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "TextBlock")
        .expect("should have TextBlock schema");
    match text_block {
        IrSchema::Object(obj) => {
            let type_field = obj
                .fields
                .iter()
                .find(|f| f.original_name == "type")
                .expect("TextBlock should have type field");
            assert_eq!(
                type_field.field_type,
                IrType::StringLiteral("text".to_string()),
                "TextBlock.type should be StringLiteral(\"text\")"
            );
        }
        _ => panic!("TextBlock should be an Object"),
    }

    // --- MessageResponse.id has read_only: true ---
    let msg_resp = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "MessageResponse")
        .expect("should have MessageResponse schema");
    match msg_resp {
        IrSchema::Object(obj) => {
            let id_field = obj
                .fields
                .iter()
                .find(|f| f.original_name == "id")
                .expect("MessageResponse should have id field");
            assert!(id_field.read_only, "MessageResponse.id should be readOnly");
        }
        _ => panic!("MessageResponse should be an Object"),
    }

    // --- createMessage has anthropic-version header parameter ---
    let create_msg = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "createMessage")
        .expect("should have createMessage operation");
    let header_param = create_msg
        .parameters
        .iter()
        .find(|p| p.original_name == "anthropic-version")
        .expect("should have anthropic-version parameter");
    assert_eq!(header_param.location, IrParameterLocation::Header);

    // --- createMessage SSE return has 8 variants, also_has_json: true ---
    match &create_msg.return_type {
        IrReturnType::Sse(sse) => {
            assert_eq!(sse.variants.len(), 8, "should have 8 SSE event variants");
            assert!(sse.also_has_json, "dual endpoint should have JSON");
            assert!(sse.json_response.is_some());
        }
        _ => panic!("createMessage should have SSE return type"),
    }

    // --- cancelBatch returns Void ---
    let cancel_batch = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "cancelBatch")
        .expect("should have cancelBatch operation");
    match &cancel_batch.return_type {
        IrReturnType::Void => {}
        _ => panic!("cancelBatch should return Void"),
    }

    // --- StopReason is Enum with 4 variants ---
    let stop_reason = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "StopReason")
        .expect("should have StopReason schema");
    match stop_reason {
        IrSchema::Enum(e) => {
            assert_eq!(e.variants.len(), 4, "StopReason should have 4 variants");
        }
        _ => panic!("StopReason should be an Enum"),
    }

    // --- At least 3 modules ---
    assert!(
        ir.modules.len() >= 3,
        "should have at least 3 modules (messages, models, and tokens or batches), got {}",
        ir.modules.len()
    );
}

#[test]
fn transform_petstore_polymorphic() {
    let spec = parse::from_yaml(PETSTORE_POLY).unwrap();
    let ir = transform::transform(&spec).unwrap();

    assert_eq!(ir.info.title, "Petstore (Polymorphic)");

    // --- Pet: discriminated union with 2 Ref variants ---
    let pet = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "Pet")
        .expect("should have Pet schema");
    match pet {
        IrSchema::Union(u) => {
            assert_eq!(u.variants.len(), 2, "Pet should have 2 variants");
            assert!(
                matches!(&u.variants[0], IrType::Ref(name) if name == "Cat"),
                "first variant should be Ref(Cat)"
            );
            assert!(
                matches!(&u.variants[1], IrType::Ref(name) if name == "Dog"),
                "second variant should be Ref(Dog)"
            );
            let disc = u.discriminator.as_ref().expect("should have discriminator");
            assert_eq!(disc.property_name, "petType");
            assert_eq!(disc.mapping.len(), 2);
            assert_eq!(
                disc.mapping.iter().find(|(k, _)| k == "cat").unwrap().1,
                "Cat"
            );
            assert_eq!(
                disc.mapping.iter().find(|(k, _)| k == "dog").unwrap().1,
                "Dog"
            );
        }
        _ => panic!("Pet should be a Union"),
    }

    // --- Cat: object with const petType ---
    let cat = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "Cat")
        .expect("should have Cat schema");
    match cat {
        IrSchema::Object(obj) => {
            let pet_type_field = obj
                .fields
                .iter()
                .find(|f| f.original_name == "petType")
                .expect("Cat should have petType field");
            assert_eq!(
                pet_type_field.field_type,
                IrType::StringLiteral("cat".to_string()),
                "Cat.petType should be StringLiteral(\"cat\")"
            );
            assert!(
                obj.fields.iter().any(|f| f.original_name == "huntingSkill"),
                "Cat should have huntingSkill field"
            );
        }
        _ => panic!("Cat should be an Object"),
    }

    // --- Dog: object with const petType ---
    let dog = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "Dog")
        .expect("should have Dog schema");
    match dog {
        IrSchema::Object(obj) => {
            let pet_type_field = obj
                .fields
                .iter()
                .find(|f| f.original_name == "petType")
                .expect("Dog should have petType field");
            assert_eq!(
                pet_type_field.field_type,
                IrType::StringLiteral("dog".to_string()),
                "Dog.petType should be StringLiteral(\"dog\")"
            );
        }
        _ => panic!("Dog should be an Object"),
    }

    // --- ExtendedErrorModel: allOf with $ref produces Alias(Intersection) ---
    let ext_err = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "ExtendedErrorModel")
        .expect("should have ExtendedErrorModel schema");
    match ext_err {
        IrSchema::Alias(alias) => match &alias.target {
            IrType::Intersection(parts) => {
                assert_eq!(parts.len(), 2, "should have 2 intersection parts");
                assert!(
                    matches!(&parts[0], IrType::Ref(name) if name == "ErrorModel"),
                    "first part should be Ref(ErrorModel)"
                );
                match &parts[1] {
                    IrType::Object(fields) => {
                        assert!(
                            fields.iter().any(|(name, _, _)| name == "rootCause"),
                            "should have rootCause field from extension"
                        );
                    }
                    _ => panic!("second part should be Object"),
                }
            }
            _ => panic!("ExtendedErrorModel target should be Intersection"),
        },
        _ => panic!("ExtendedErrorModel should be an Alias (allOf with $ref)"),
    }

    // --- Operations ---
    assert!(!ir.operations.is_empty());
    let list_op = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "listPets")
        .expect("should have listPets");
    assert_eq!(list_op.parameters.len(), 1); // limit

    let create_op = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "createPet")
        .expect("should have createPet");
    assert!(create_op.request_body.is_some());

    let get_op = ir
        .operations
        .iter()
        .find(|op| op.name.camel_case == "getPet")
        .expect("should have getPet");
    assert_eq!(get_op.parameters.len(), 1); // petId
}

#[test]
fn integer_const_produces_integer_literal() {
    let spec = parse::from_yaml(INTEGER_DISC).unwrap();
    let ir = transform::transform(&spec).unwrap();

    // Circle.shapeType has const: 0 — should be IntegerLiteral(0)
    let circle = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "Circle")
        .expect("should have Circle schema");
    match circle {
        IrSchema::Object(obj) => {
            let shape_type = obj
                .fields
                .iter()
                .find(|f| f.original_name == "shapeType")
                .expect("Circle should have shapeType field");
            assert_eq!(
                shape_type.field_type,
                IrType::IntegerLiteral(0),
                "Circle.shapeType should be IntegerLiteral(0)"
            );
        }
        _ => panic!("Circle should be an Object"),
    }

    // Square.shapeType has const: 1 — should be IntegerLiteral(1)
    let square = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "Square")
        .expect("should have Square schema");
    match square {
        IrSchema::Object(obj) => {
            let shape_type = obj
                .fields
                .iter()
                .find(|f| f.original_name == "shapeType")
                .expect("Square should have shapeType field");
            assert_eq!(
                shape_type.field_type,
                IrType::IntegerLiteral(1),
                "Square.shapeType should be IntegerLiteral(1)"
            );
        }
        _ => panic!("Square should be an Object"),
    }
}

#[test]
fn literal_default_keeps_literals_present_and_preserves_default() {
    let spec = parse::from_yaml(LITERAL_DEFAULT).unwrap();
    let ir = transform::transform(&spec).unwrap();

    let message = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "Message")
        .expect("should have Message schema");
    let IrSchema::Object(obj) = message else {
        panic!("Message should be an Object");
    };
    let field = |name: &str| {
        obj.fields
            .iter()
            .find(|f| f.original_name == name)
            .unwrap_or_else(|| panic!("Message should have {name} field"))
    };

    // --- Single-value enum with a default, NOT in `required` ---
    // The literal type is preserved AND the default is captured, but required-ness
    // is unchanged (still derived from the `required` list).
    let type_field = field("type");
    assert_eq!(
        type_field.field_type,
        IrType::StringLiteral("message".to_string())
    );
    assert!(!type_field.required, "type is not in `required`");
    assert_eq!(
        type_field.default_repr,
        Some(IrType::StringLiteral("message".to_string())),
        "literal default value should be preserved on the field"
    );

    // --- Integer single-value enum with a default ---
    let version = field("version");
    assert_eq!(version.field_type, IrType::IntegerLiteral(1));
    assert_eq!(version.default_repr, Some(IrType::IntegerLiteral(1)));

    // --- Aliased literal (camelCase original) ---
    let object_type = field("objectType");
    assert_eq!(
        object_type.field_type,
        IrType::StringLiteral("list".to_string())
    );
    assert_eq!(
        object_type.default_repr,
        Some(IrType::StringLiteral("list".to_string()))
    );

    // --- Required field, no default ---
    let content = field("content");
    assert!(content.required, "content is the only required field");
    assert_eq!(content.field_type, IrType::String);
    assert_eq!(content.default_repr, None);

    // --- Non-literal scalar defaults: NOT literals, stay optional ---
    let max_tokens = field("maxTokens");
    assert_eq!(max_tokens.field_type, IrType::Integer);
    assert!(!max_tokens.required);

    let temperature = field("temperature");
    assert_eq!(temperature.field_type, IrType::Number);
    assert!(!temperature.required);
    assert_eq!(
        temperature.default_repr, None,
        "a float default is not a string/integer literal"
    );

    // --- Multi-value enum with a default: becomes a Union, not a literal ---
    let role = field("role");
    assert!(
        matches!(role.field_type, IrType::Union(_)),
        "multi-value enum should be a Union, not a single literal"
    );
    assert!(!role.required);

    // --- const literal that IS in `required` stays required ---
    let text_block = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "TextBlock")
        .expect("should have TextBlock schema");
    let IrSchema::Object(tb) = text_block else {
        panic!("TextBlock should be an Object");
    };
    let tb_type = tb
        .fields
        .iter()
        .find(|f| f.original_name == "type")
        .expect("TextBlock should have type field");
    assert_eq!(
        tb_type.field_type,
        IrType::StringLiteral("text".to_string())
    );
    assert!(tb_type.required, "TextBlock.type is in `required`");
    assert_eq!(
        tb_type.default_repr,
        Some(IrType::StringLiteral("text".to_string()))
    );
}

#[test]
fn integer_discriminator_mapping_keys_preserved() {
    let spec = parse::from_yaml(INTEGER_DISC).unwrap();
    let ir = transform::transform(&spec).unwrap();

    let shape = ir
        .schemas
        .iter()
        .find(|s| s.name().pascal_case == "Shape")
        .expect("should have Shape schema");
    match shape {
        IrSchema::Union(u) => {
            let disc = u.discriminator.as_ref().expect("should have discriminator");
            assert_eq!(disc.property_name, "shapeType");
            assert_eq!(disc.mapping.len(), 2);
            assert_eq!(
                disc.mapping.iter().find(|(k, _)| k == "0").unwrap().1,
                "Circle"
            );
            assert_eq!(
                disc.mapping.iter().find(|(k, _)| k == "1").unwrap().1,
                "Square"
            );
        }
        _ => panic!("Shape should be a Union"),
    }
}