panproto-protocols 0.74.1

Built-in protocol definitions for panproto
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
//! `OpenAPI`/Swagger protocol definition.
//!
//! `OpenAPI` uses a constrained multigraph schema theory
//! (`colimit(ThGraph, ThConstraint, ThMulti)`) and a W-type
//! instance theory (`ThWType`).
//!
//! Vertex kinds: path, operation, parameter, request-body, response,
//! schema-object, header, string, integer, number, boolean, array, object.
//!
//! Edge kinds: prop, items, variant, ref.

use std::collections::{HashMap, HashSet};

use panproto_gat::Theory;
use panproto_schema::{EdgeRule, Protocol, Schema, SchemaBuilder};

use crate::emit::{children_by_edge, constraint_value, find_roots};
use crate::error::ProtocolError;
use crate::theories;

/// Returns the `OpenAPI` protocol definition.
#[must_use]
pub fn protocol() -> Protocol {
    Protocol {
        name: "openapi".into(),
        schema_theory: "ThOpenAPISchema".into(),
        instance_theory: "ThOpenAPIInstance".into(),
        edge_rules: edge_rules(),
        obj_kinds: vec![
            "path".into(),
            "operation".into(),
            "parameter".into(),
            "request-body".into(),
            "response".into(),
            "schema-object".into(),
            "header".into(),
            "string".into(),
            "integer".into(),
            "number".into(),
            "boolean".into(),
            "array".into(),
            "object".into(),
        ],
        constraint_sorts: vec![
            "required".into(),
            "format".into(),
            "enum".into(),
            "default".into(),
            "minimum".into(),
            "maximum".into(),
            "pattern".into(),
            "minLength".into(),
            "maxLength".into(),
            "minItems".into(),
            "maxItems".into(),
            "deprecated".into(),
        ],
        has_order: true,
        has_coproducts: true,
        has_recursion: true,
        nominal_identity: true,
        ..Protocol::default()
    }
}

/// Register the component GATs for `OpenAPI` with a theory registry.
pub fn register_theories<S: ::std::hash::BuildHasher>(registry: &mut HashMap<String, Theory, S>) {
    theories::register_constrained_multigraph_wtype(
        registry,
        "ThOpenAPISchema",
        "ThOpenAPIInstance",
    );
}

/// Parse an `OpenAPI` JSON document into a [`Schema`].
///
/// Walks paths, operations, parameters, request bodies, responses,
/// and schemas to produce a flat vertex/edge graph.
///
/// Equivalent to [`parse_openapi_bundle`] over a single document, so
/// the two cannot drift apart.
///
/// # Errors
///
/// Returns [`ProtocolError`] if parsing or schema construction fails.
pub fn parse_openapi(json: &serde_json::Value) -> Result<Schema, ProtocolError> {
    parse_openapi_bundle(std::slice::from_ref(json))
}

/// The vertex-id prefix for a document, and the identity other
/// documents address it by.
///
/// `OpenAPI` 3.1 aligns with JSON Schema 2020-12, so a document may
/// carry `$id`; that is what a cross-document `$ref` names. A document
/// without one is unaddressable from outside, and is prefixed by its
/// position so its ids do not collide with a sibling's. A lone document
/// keeps the unprefixed ids a single-document parse has always
/// produced.
fn document_identity(
    json: &serde_json::Value,
    index: usize,
    count: usize,
) -> (Option<String>, Option<&str>) {
    let declared = json.get("$id").and_then(serde_json::Value::as_str);
    let prefix = match declared {
        _ if count == 1 => None,
        Some(id) => Some(id.to_owned()),
        None => Some(format!("doc{index}")),
    };
    (prefix, declared)
}

/// Qualify a document-local id with the document's prefix, if it has
/// one.
fn qualify(prefix: Option<&str>, local: &str) -> String {
    prefix.map_or_else(|| local.to_owned(), |p| format!("{p}::{local}"))
}

/// Parse a bundle of `OpenAPI` documents into one [`Schema`], resolving
/// `$ref`s across the whole bundle.
///
/// Splitting a specification across files is the standard way a large
/// API is organized, and a `$ref` into a sibling document is routine.
/// Every document's `components/schemas` are mapped to their vertex ids
/// before any document's paths are walked, so such a ref lands on the
/// referenced schema's real, typed vertex rather than on the opaque
/// placeholder the parser leaves for an unresolvable one.
///
/// A cross-document `$ref` is spelled against the target document's
/// `$id` (`https://example.com/common.json#/components/schemas/Address`).
/// A relative-path `$ref` (`./common.yaml#/components/schemas/Address`)
/// is not resolved: a bundle is an unordered array of documents with no
/// filenames, so there is nothing for a path to be relative to. Give
/// the documents `$id`s to have their cross-references resolve.
///
/// Passing a single document is equivalent to [`parse_openapi`], down
/// to the unprefixed vertex ids.
///
/// # Errors
///
/// Returns [`ProtocolError::Parse`] if two documents declare the same
/// `$id`, or a construction error from the schema builder.
pub fn parse_openapi_bundle(docs: &[serde_json::Value]) -> Result<Schema, ProtocolError> {
    let proto = protocol();
    let mut builder = SchemaBuilder::new(&proto);
    let mut counter: usize = 0;

    // Pass 1, over the whole bundle: map every reference spelling to the
    // vertex id it names, before walking anything. A component's vertex
    // id follows from its document and its name, so this needs no walk,
    // and doing it first is what lets a ref reach a sibling document.
    let mut defs_map: HashMap<String, String> = HashMap::new();
    let mut identities: Vec<(Option<String>, Option<&str>)> = Vec::with_capacity(docs.len());
    let mut seen_ids: HashSet<&str> = HashSet::with_capacity(docs.len());

    for (i, json) in docs.iter().enumerate() {
        let (prefix, declared) = document_identity(json, i, docs.len());
        if let Some(id) = declared {
            if !seen_ids.insert(id) {
                return Err(ProtocolError::Parse(format!(
                    "duplicate $id in bundle: {id}"
                )));
            }
        }
        if let Some(schemas) = json
            .pointer("/components/schemas")
            .and_then(serde_json::Value::as_object)
        {
            for name in schemas.keys() {
                let schema_id = qualify(prefix.as_deref(), &format!("components/schemas/{name}"));
                if let Some(id) = declared {
                    defs_map.insert(format!("{id}#/components/schemas/{name}"), schema_id);
                }
            }
        }
        identities.push((prefix, declared));
    }

    // Pass 2: walk each document. Its own `#/...` refs resolve to its
    // own components; every in-bundle cross-document target is already
    // in `defs_map`.
    for (json, (prefix, _)) in docs.iter().zip(&identities) {
        let prefix = prefix.as_deref();
        let mut local = defs_map.clone();

        if let Some(schemas) = json
            .pointer("/components/schemas")
            .and_then(serde_json::Value::as_object)
        {
            for name in schemas.keys() {
                local.insert(
                    format!("#/components/schemas/{name}"),
                    qualify(prefix, &format!("components/schemas/{name}")),
                );
            }
            for (name, schema_val) in schemas {
                let schema_id = qualify(prefix, &format!("components/schemas/{name}"));
                builder = walk_schema(builder, schema_val, &schema_id, &mut counter)?;
            }
        }

        // Walk paths. Each path item is an entry basepoint: it is a root
        // sort for instances of this API.
        if let Some(paths) = json.get("paths").and_then(serde_json::Value::as_object) {
            for (path_str, path_item) in paths {
                let path_id = qualify(prefix, &format!("path:{path_str}"));
                builder = builder.vertex(&path_id, "path", None)?;
                builder = builder.entry(&path_id);
                builder = parse_path_item(builder, path_item, &path_id, &mut counter, &local)?;
            }
        }
    }

    let schema = builder.build()?;
    Ok(schema)
}

/// Parse a single path item, walking HTTP methods.
fn parse_path_item(
    mut builder: SchemaBuilder,
    path_item: &serde_json::Value,
    path_id: &str,
    counter: &mut usize,
    defs_map: &HashMap<String, String>,
) -> Result<SchemaBuilder, ProtocolError> {
    for method in &[
        "get", "post", "put", "delete", "patch", "options", "head", "trace",
    ] {
        if let Some(op) = path_item.get(*method) {
            let op_id = format!("{path_id}:{method}");
            builder = builder.vertex(&op_id, "operation", None)?;
            builder = builder.edge(path_id, &op_id, "prop", Some(method))?;

            if op.get("deprecated").and_then(serde_json::Value::as_bool) == Some(true) {
                builder = builder.constraint(&op_id, "deprecated", "true");
            }

            builder = parse_operation(builder, op, &op_id, counter, defs_map)?;
        }
    }
    Ok(builder)
}

/// Parse an operation's parameters, request body, and responses.
fn parse_operation(
    mut builder: SchemaBuilder,
    op: &serde_json::Value,
    op_id: &str,
    counter: &mut usize,
    defs_map: &HashMap<String, String>,
) -> Result<SchemaBuilder, ProtocolError> {
    // Parameters.
    if let Some(params) = op.get("parameters").and_then(serde_json::Value::as_array) {
        for (i, param) in params.iter().enumerate() {
            let param_name = param
                .get("name")
                .and_then(serde_json::Value::as_str)
                .unwrap_or("unknown");
            let param_id = format!("{op_id}:param{i}");
            builder = builder.vertex(&param_id, "parameter", None)?;
            builder = builder.edge(op_id, &param_id, "prop", Some(param_name))?;

            if param.get("required").and_then(serde_json::Value::as_bool) == Some(true) {
                builder = builder.constraint(&param_id, "required", "true");
            }

            if let Some(schema_val) = param.get("schema") {
                let s_id = format!("{param_id}:schema");
                builder = walk_schema_or_ref(builder, schema_val, &s_id, counter, defs_map)?;
                builder = builder.edge(&param_id, &s_id, "prop", Some("schema"))?;
            }
        }
    }

    // Request body.
    if let Some(req_body) = op.get("requestBody") {
        let rb_id = format!("{op_id}:requestBody");
        builder = builder.vertex(&rb_id, "request-body", None)?;
        builder = builder.edge(op_id, &rb_id, "prop", Some("requestBody"))?;

        if let Some(content) = req_body
            .get("content")
            .and_then(serde_json::Value::as_object)
        {
            for (media_type, media_obj) in content {
                if let Some(schema_val) = media_obj.get("schema") {
                    let s_id = format!("{rb_id}:{media_type}");
                    builder = walk_schema_or_ref(builder, schema_val, &s_id, counter, defs_map)?;
                    builder = builder.edge(&rb_id, &s_id, "prop", Some(media_type))?;
                }
            }
        }
    }

    // Responses.
    if let Some(responses) = op.get("responses").and_then(serde_json::Value::as_object) {
        for (status, resp) in responses {
            let resp_id = format!("{op_id}:resp{status}");
            builder = builder.vertex(&resp_id, "response", None)?;
            builder = builder.edge(op_id, &resp_id, "prop", Some(status))?;

            if let Some(content) = resp.get("content").and_then(serde_json::Value::as_object) {
                for (media_type, media_obj) in content {
                    if let Some(schema_val) = media_obj.get("schema") {
                        let s_id = format!("{resp_id}:{media_type}");
                        builder =
                            walk_schema_or_ref(builder, schema_val, &s_id, counter, defs_map)?;
                        builder = builder.edge(&resp_id, &s_id, "prop", Some(media_type))?;
                    }
                }
            }

            if let Some(headers) = resp.get("headers").and_then(serde_json::Value::as_object) {
                for (hdr_name, _hdr_obj) in headers {
                    let hdr_id = format!("{resp_id}:hdr:{hdr_name}");
                    builder = builder.vertex(&hdr_id, "header", None)?;
                    builder = builder.edge(&resp_id, &hdr_id, "prop", Some(hdr_name))?;
                }
            }
        }
    }

    Ok(builder)
}

/// Walk a schema value, resolving `$ref` if present.
fn walk_schema_or_ref(
    builder: SchemaBuilder,
    schema: &serde_json::Value,
    current_id: &str,
    counter: &mut usize,
    defs_map: &HashMap<String, String>,
) -> Result<SchemaBuilder, ProtocolError> {
    if let Some(ref_str) = schema.get("$ref").and_then(serde_json::Value::as_str) {
        let mut b = builder.vertex(current_id, "schema-object", None)?;
        if let Some(def_id) = defs_map.get(ref_str) {
            b = b.edge(current_id, def_id, "ref", Some(ref_str))?;
        }
        Ok(b)
    } else {
        walk_schema(builder, schema, current_id, counter)
    }
}

/// Recursively walk a JSON Schema object within an `OpenAPI` spec.
fn walk_schema(
    mut builder: SchemaBuilder,
    schema: &serde_json::Value,
    current_id: &str,
    counter: &mut usize,
) -> Result<SchemaBuilder, ProtocolError> {
    let type_str = schema
        .get("type")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("object");

    let kind = match type_str {
        "string" => "string",
        "integer" => "integer",
        "number" => "number",
        "boolean" => "boolean",
        "array" => "array",
        _ => "object",
    };

    builder = builder.vertex(current_id, kind, None)?;

    // Add constraints.
    for field in &[
        "format",
        "minimum",
        "maximum",
        "pattern",
        "minLength",
        "maxLength",
        "minItems",
        "maxItems",
    ] {
        if let Some(val) = schema.get(field) {
            let val_str = match val {
                serde_json::Value::String(s) => s.clone(),
                serde_json::Value::Number(n) => n.to_string(),
                _ => val.to_string(),
            };
            builder = builder.constraint(current_id, field, &val_str);
        }
    }

    if let Some(enum_val) = schema.get("enum").and_then(serde_json::Value::as_array) {
        let vals: Vec<String> = enum_val
            .iter()
            .map(|v| v.as_str().map_or_else(|| v.to_string(), String::from))
            .collect();
        builder = builder.constraint(current_id, "enum", &vals.join(","));
    }

    if let Some(default_val) = schema.get("default") {
        let val_str = match default_val {
            serde_json::Value::String(s) => s.clone(),
            _ => default_val.to_string(),
        };
        builder = builder.constraint(current_id, "default", &val_str);
    }

    // Properties.
    if let Some(properties) = schema
        .get("properties")
        .and_then(serde_json::Value::as_object)
    {
        let required_fields: Vec<&str> = schema
            .get("required")
            .and_then(serde_json::Value::as_array)
            .map(|arr| arr.iter().filter_map(serde_json::Value::as_str).collect())
            .unwrap_or_default();

        for (prop_name, prop_schema) in properties {
            let prop_id = format!("{current_id}.{prop_name}");
            builder = walk_schema(builder, prop_schema, &prop_id, counter)?;
            builder = builder.edge(current_id, &prop_id, "prop", Some(prop_name))?;
            if required_fields.contains(&prop_name.as_str()) {
                builder = builder.constraint(&prop_id, "required", "true");
            }
        }
    }

    // Items.
    if let Some(items) = schema.get("items") {
        let items_id = format!("{current_id}:items");
        builder = walk_schema(builder, items, &items_id, counter)?;
        builder = builder.edge(current_id, &items_id, "items", None)?;
    }

    // oneOf / anyOf / allOf.
    for combiner in &["oneOf", "anyOf", "allOf"] {
        if let Some(arr) = schema.get(*combiner).and_then(serde_json::Value::as_array) {
            for (i, sub_schema) in arr.iter().enumerate() {
                *counter += 1;
                let sub_id = format!("{current_id}:{combiner}{i}_{counter}");
                builder = walk_schema(builder, sub_schema, &sub_id, counter)?;
                builder = builder.edge(current_id, &sub_id, "variant", Some(combiner))?;
            }
        }
    }

    Ok(builder)
}

/// Emit a [`Schema`] as an `OpenAPI` JSON document.
///
/// # Errors
///
/// Returns [`ProtocolError`] if emission fails.
pub fn emit_openapi(schema: &Schema) -> Result<serde_json::Value, ProtocolError> {
    let mut paths = serde_json::Map::new();
    let mut component_schemas = serde_json::Map::new();

    let roots = find_roots(schema, &["prop", "items", "variant", "ref"]);

    for root in &roots {
        if root.kind == "path" {
            let path_name = root.id.strip_prefix("path:").unwrap_or(&root.id);
            let mut path_obj = serde_json::Map::new();

            for (edge, op_vertex) in children_by_edge(schema, &root.id, "prop") {
                if op_vertex.kind == "operation" {
                    let method = edge.name.as_deref().unwrap_or("get");
                    let op_obj = emit_operation(schema, &op_vertex.id);
                    path_obj.insert(method.to_string(), op_obj);
                }
            }

            paths.insert(path_name.to_string(), serde_json::Value::Object(path_obj));
        } else {
            let schema_obj = emit_schema_value(schema, &root.id);
            let name = root
                .id
                .strip_prefix("components/schemas/")
                .unwrap_or(&root.id);
            component_schemas.insert(name.to_string(), schema_obj);
        }
    }

    let mut result = serde_json::Map::new();
    result.insert("openapi".into(), serde_json::Value::String("3.0.0".into()));
    result.insert(
        "info".into(),
        serde_json::json!({"title": "Generated", "version": "1.0.0"}),
    );
    result.insert("paths".into(), serde_json::Value::Object(paths));

    if !component_schemas.is_empty() {
        let mut components = serde_json::Map::new();
        components.insert(
            "schemas".into(),
            serde_json::Value::Object(component_schemas),
        );
        result.insert("components".into(), serde_json::Value::Object(components));
    }

    Ok(serde_json::Value::Object(result))
}

/// Emit an operation vertex as a JSON object.
fn emit_operation(schema: &Schema, op_id: &str) -> serde_json::Value {
    let mut obj = serde_json::Map::new();

    if constraint_value(schema, op_id, "deprecated") == Some("true") {
        obj.insert("deprecated".into(), serde_json::Value::Bool(true));
    }

    let children = children_by_edge(schema, op_id, "prop");

    // Parameters.
    let params: Vec<serde_json::Value> = children
        .iter()
        .filter(|(_, v)| v.kind == "parameter")
        .map(|(edge, v)| {
            let mut p = serde_json::Map::new();
            p.insert(
                "name".into(),
                serde_json::Value::String(edge.name.as_deref().unwrap_or("unknown").to_string()),
            );
            p.insert("in".into(), serde_json::Value::String("query".into()));
            if constraint_value(schema, &v.id, "required") == Some("true") {
                p.insert("required".into(), serde_json::Value::Bool(true));
            }
            serde_json::Value::Object(p)
        })
        .collect();
    if !params.is_empty() {
        obj.insert("parameters".into(), serde_json::Value::Array(params));
    }

    // Responses.
    let responses: Vec<_> = children
        .iter()
        .filter(|(_, v)| v.kind == "response")
        .collect();
    if !responses.is_empty() {
        let mut resp_obj = serde_json::Map::new();
        for (edge, _v) in &responses {
            let status = edge.name.as_deref().unwrap_or("200");
            let mut r = serde_json::Map::new();
            r.insert(
                "description".into(),
                serde_json::Value::String(String::new()),
            );
            resp_obj.insert(status.to_string(), serde_json::Value::Object(r));
        }
        obj.insert("responses".into(), serde_json::Value::Object(resp_obj));
    }

    serde_json::Value::Object(obj)
}

/// Emit a schema vertex as a JSON Schema value.
fn emit_schema_value(schema: &Schema, vertex_id: &str) -> serde_json::Value {
    let Some(vertex) = schema.vertices.get(vertex_id) else {
        return serde_json::Value::Object(serde_json::Map::new());
    };

    let mut obj = serde_json::Map::new();

    let type_str = match vertex.kind.as_str() {
        "string" => Some("string"),
        "integer" => Some("integer"),
        "number" => Some("number"),
        "boolean" => Some("boolean"),
        "array" => Some("array"),
        "object" | "schema-object" => Some("object"),
        _ => None,
    };

    if let Some(t) = type_str {
        obj.insert("type".into(), serde_json::Value::String(t.into()));
    }

    for field in &[
        "format",
        "minimum",
        "maximum",
        "pattern",
        "minLength",
        "maxLength",
        "minItems",
        "maxItems",
    ] {
        if let Some(val) = constraint_value(schema, vertex_id, field) {
            if let Ok(n) = val.parse::<f64>() {
                obj.insert((*field).into(), serde_json::json!(n));
            } else {
                obj.insert((*field).into(), serde_json::Value::String(val.to_string()));
            }
        }
    }

    // Properties.
    let props = children_by_edge(schema, vertex_id, "prop");
    if !props.is_empty() {
        let mut properties = serde_json::Map::new();
        let mut required_list = Vec::new();
        for (edge, _child) in &props {
            let name = edge.name.as_deref().unwrap_or("");
            let child_schema = emit_schema_value(schema, &edge.tgt);
            properties.insert(name.to_string(), child_schema);
            if constraint_value(schema, &edge.tgt, "required") == Some("true") {
                required_list.push(serde_json::Value::String(name.to_string()));
            }
        }
        obj.insert("properties".into(), serde_json::Value::Object(properties));
        if !required_list.is_empty() {
            obj.insert("required".into(), serde_json::Value::Array(required_list));
        }
    }

    // Items.
    let items = children_by_edge(schema, vertex_id, "items");
    if let Some((edge, _)) = items.first() {
        let items_schema = emit_schema_value(schema, &edge.tgt);
        obj.insert("items".into(), items_schema);
    }

    serde_json::Value::Object(obj)
}

/// Well-formedness rules for `OpenAPI` edges.
fn edge_rules() -> Vec<EdgeRule> {
    vec![
        EdgeRule {
            edge_kind: "prop".into(),
            src_kinds: vec![
                "path".into(),
                "operation".into(),
                "parameter".into(),
                "request-body".into(),
                "response".into(),
                "object".into(),
                "schema-object".into(),
            ],
            tgt_kinds: vec![],
        },
        EdgeRule {
            edge_kind: "items".into(),
            src_kinds: vec!["array".into()],
            tgt_kinds: vec![],
        },
        EdgeRule {
            edge_kind: "variant".into(),
            src_kinds: vec![],
            tgt_kinds: vec![],
        },
        EdgeRule {
            edge_kind: "ref".into(),
            src_kinds: vec![],
            tgt_kinds: vec![],
        },
    ]
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn protocol_def() {
        let p = protocol();
        assert_eq!(p.name, "openapi");
        assert_eq!(p.schema_theory, "ThOpenAPISchema");
        assert_eq!(p.instance_theory, "ThOpenAPIInstance");
    }

    #[test]
    fn register_theories_works() {
        let mut registry = HashMap::new();
        register_theories(&mut registry);
        assert!(registry.contains_key("ThOpenAPISchema"));
        assert!(registry.contains_key("ThOpenAPIInstance"));
    }

    #[test]
    fn parse_minimal() {
        let doc = serde_json::json!({
            "openapi": "3.0.0",
            "info": {"title": "Test", "version": "1.0.0"},
            "paths": {
                "/users": {
                    "get": {
                        "parameters": [
                            {"name": "limit", "in": "query", "schema": {"type": "integer"}}
                        ],
                        "responses": {
                            "200": {
                                "description": "OK",
                                "content": {
                                    "application/json": {
                                        "schema": {
                                            "type": "array",
                                            "items": {"type": "string"}
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
        let schema = parse_openapi(&doc).expect("should parse");
        assert!(schema.has_vertex("path:/users"));
        assert!(schema.has_vertex("path:/users:get"));
    }

    #[test]
    fn emit_minimal() {
        let doc = serde_json::json!({
            "openapi": "3.0.0",
            "info": {"title": "Test", "version": "1.0.0"},
            "paths": {
                "/pets": {
                    "get": {
                        "responses": {
                            "200": {"description": "OK"}
                        }
                    }
                }
            }
        });
        let schema = parse_openapi(&doc).expect("should parse");
        let emitted = emit_openapi(&schema).expect("should emit");
        assert!(emitted.get("paths").is_some());
    }

    #[test]
    fn roundtrip() {
        let doc = serde_json::json!({
            "openapi": "3.0.0",
            "info": {"title": "Test", "version": "1.0.0"},
            "paths": {
                "/items": {
                    "get": {
                        "responses": {
                            "200": {"description": "OK"}
                        }
                    }
                }
            }
        });
        let schema = parse_openapi(&doc).expect("parse");
        let emitted = emit_openapi(&schema).expect("emit");
        let schema2 = parse_openapi(&emitted).expect("re-parse");
        assert_eq!(schema.vertices.len(), schema2.vertices.len());
    }
}