grafbase-sdk 0.23.1

An SDK to implement extensions for the Grafbase Gateway
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
use fxhash::FxBuildHasher;
use serde::Deserialize;
use std::collections::HashMap;
use std::fmt;

use crate::{SdkError, cbor, wit};

#[derive(Clone)]
pub(crate) struct IndexedSchema {
    name: String,
    directives: Vec<wit::Directive>,
    type_definitions: HashMap<DefinitionId, wit::TypeDefinition, FxBuildHasher>,
    field_definitions: HashMap<DefinitionId, wit::FieldDefinition, FxBuildHasher>,
    root_types: wit::RootTypes,
}

impl From<(String, wit::Schema)> for IndexedSchema {
    fn from((name, schema): (String, wit::Schema)) -> Self {
        Self {
            name,
            directives: schema.directives,
            type_definitions: schema
                .type_definitions
                .into_iter()
                .map(|def| {
                    let id = match &def {
                        wit::TypeDefinition::Scalar(scalar) => DefinitionId(scalar.id),
                        wit::TypeDefinition::Object(object) => DefinitionId(object.id),
                        wit::TypeDefinition::Interface(interface) => DefinitionId(interface.id),
                        wit::TypeDefinition::Union(union) => DefinitionId(union.id),
                        wit::TypeDefinition::Enum(enum_def) => DefinitionId(enum_def.id),
                        wit::TypeDefinition::InputObject(input_object) => DefinitionId(input_object.id),
                    };
                    (id, def)
                })
                .collect(),
            field_definitions: schema
                .field_definitions
                .into_iter()
                .map(|def| {
                    let id = DefinitionId(def.id);
                    (id, def)
                })
                .collect(),
            root_types: schema.root_types,
        }
    }
}

/// GraphQL schema
pub struct SubgraphSchema(pub(crate) IndexedSchema);

impl fmt::Debug for SubgraphSchema {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SubgraphSchema")
            .field("name", &self.subgraph_name())
            .field(
                "type_definitions",
                &format!("<{} type definitions>", self.type_definitions().len()),
            )
            .field("directives", &self.directives().collect::<Vec<_>>())
            .finish_non_exhaustive()
    }
}

impl SubgraphSchema {
    /// Name of the subgraph this schema belongs to
    pub fn subgraph_name(&self) -> &str {
        &self.0.name
    }

    /// Iterator over the definitions in this schema
    pub fn type_definitions(&self) -> impl ExactSizeIterator<Item = TypeDefinition<'_>> {
        let schema = &self.0;
        self.0.type_definitions.values().map(move |def| (schema, def).into())
    }

    /// Iterator over all object and interface fields in the schema
    pub fn iter_fields(&self) -> impl Iterator<Item = FieldDefinition<'_>> {
        let schema = &self.0;
        self.0
            .field_definitions
            .values()
            .map(|definition| FieldDefinition { schema, definition })
    }

    /// Retrieves a specific field definition by its unique identifier.
    pub fn field_definition(&self, id: DefinitionId) -> Option<FieldDefinition<'_>> {
        let schema = &self.0;
        self.0.field_definitions.get(&id).map(move |def| FieldDefinition {
            schema,
            definition: def,
        })
    }

    /// Retrieves a specific type definition by its unique identifier.
    pub fn type_definition(&self, id: DefinitionId) -> Option<TypeDefinition<'_>> {
        let schema = &self.0;
        self.0.type_definitions.get(&id).map(move |def| (schema, def).into())
    }

    /// Iterator over the directives applied to this schema
    pub fn directives(&self) -> impl ExactSizeIterator<Item = Directive<'_>> {
        self.0.directives.iter().map(Into::into)
    }

    /// Query type id definition if any. Subgraph schema may only contain mutations or add fields
    /// to external objects.
    pub fn query(&self) -> Option<ObjectDefinition<'_>> {
        self.0.root_types.query_id.map(|id| {
            let Some(wit::TypeDefinition::Object(def)) = self.0.type_definitions.get(&DefinitionId(id)) else {
                unreachable!("Inconsitent schema");
            };
            (&self.0, def).into()
        })
    }

    /// Mutation type definition id if any
    pub fn mutation(&self) -> Option<ObjectDefinition<'_>> {
        self.0.root_types.mutation_id.map(|id| {
            let Some(wit::TypeDefinition::Object(def)) = self.0.type_definitions.get(&DefinitionId(id)) else {
                unreachable!("Inconsitent schema");
            };
            (&self.0, def).into()
        })
    }

    /// Subscription type definition id if any
    pub fn subscription(&self) -> Option<ObjectDefinition<'_>> {
        self.0.root_types.subscription_id.map(|id| {
            let Some(wit::TypeDefinition::Object(def)) = self.0.type_definitions.get(&DefinitionId(id)) else {
                unreachable!("Inconsitent schema");
            };
            (&self.0, def).into()
        })
    }
}

/// Identifier for a GraphQL definition within a schema
///
/// Provides a unique reference to different types of schema definitions such as
/// scalars, objects, interfaces, and other type definitions.
///
/// There is no particular guarantee on the nature of the u32, it could be a `u32::MAX`. It's only
/// ensured to be unique. It's recommended to use the `fxhash::FxHasher32` with a hashmap for best
/// performance.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
pub struct DefinitionId(pub(crate) u32);

impl From<DefinitionId> for u32 {
    fn from(id: DefinitionId) -> u32 {
        id.0
    }
}

/// Enum representing the different types of GraphQL definitions
#[derive(Clone, Copy)]
pub enum TypeDefinition<'a> {
    /// A scalar type definition (e.g., String, Int, custom scalars)
    Scalar(ScalarDefinition<'a>),
    /// An object type definition
    Object(ObjectDefinition<'a>),
    /// An interface type definition
    Interface(InterfaceDefinition<'a>),
    /// A union type definition
    Union(UnionDefinition<'a>),
    /// An enum type definition
    Enum(EnumDefinition<'a>),
    /// An input object type definition
    InputObject(InputObjectDefinition<'a>),
}

impl fmt::Debug for TypeDefinition<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TypeDefinition::Scalar(def) => f.debug_tuple("Scalar").field(def).finish(),
            TypeDefinition::Object(def) => f.debug_tuple("Object").field(def).finish(),
            TypeDefinition::Interface(def) => f.debug_tuple("Interface").field(def).finish(),
            TypeDefinition::Union(def) => f.debug_tuple("Union").field(def).finish(),
            TypeDefinition::Enum(def) => f.debug_tuple("Enum").field(def).finish(),
            TypeDefinition::InputObject(def) => f.debug_tuple("InputObject").field(def).finish(),
        }
    }
}

impl std::fmt::Display for TypeDefinition<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl<'a> TypeDefinition<'a> {
    /// Unique identifier for this type definition
    pub fn id(&self) -> DefinitionId {
        match self {
            TypeDefinition::Scalar(def) => def.id(),
            TypeDefinition::Object(def) => def.id(),
            TypeDefinition::Interface(def) => def.id(),
            TypeDefinition::Union(def) => def.id(),
            TypeDefinition::Enum(def) => def.id(),
            TypeDefinition::InputObject(def) => def.id(),
        }
    }

    /// Name of the type definition
    pub fn name(&self) -> &'a str {
        match self {
            TypeDefinition::Scalar(def) => def.name(),
            TypeDefinition::Object(def) => def.name(),
            TypeDefinition::Interface(def) => def.name(),
            TypeDefinition::Union(def) => def.name(),
            TypeDefinition::Enum(def) => def.name(),
            TypeDefinition::InputObject(def) => def.name(),
        }
    }
}

impl<'a> From<(&'a IndexedSchema, &'a wit::TypeDefinition)> for TypeDefinition<'a> {
    fn from((schema, definition): (&'a IndexedSchema, &'a wit::TypeDefinition)) -> Self {
        match definition {
            wit::TypeDefinition::Scalar(scalar) => TypeDefinition::Scalar((schema, scalar).into()),
            wit::TypeDefinition::Object(object) => TypeDefinition::Object((schema, object).into()),
            wit::TypeDefinition::Interface(interface) => TypeDefinition::Interface((schema, interface).into()),
            wit::TypeDefinition::Union(union) => TypeDefinition::Union((schema, union).into()),
            wit::TypeDefinition::Enum(enum_def) => TypeDefinition::Enum((schema, enum_def).into()),
            wit::TypeDefinition::InputObject(input_object) => {
                TypeDefinition::InputObject((schema, input_object).into())
            }
        }
    }
}

/// GraphQL scalar type definition
#[derive(Clone, Copy)]
pub struct ScalarDefinition<'a> {
    pub(crate) definition: &'a wit::ScalarDefinition,
}

impl fmt::Debug for ScalarDefinition<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ScalarDefinition")
            .field("id", &self.id())
            .field("name", &self.name())
            .field("specified_by_url", &self.specified_by_url())
            .field("directives", &self.directives().collect::<Vec<_>>())
            .finish()
    }
}

impl std::fmt::Display for ScalarDefinition<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl<'a> From<(&'a IndexedSchema, &'a wit::ScalarDefinition)> for ScalarDefinition<'a> {
    fn from((_, definition): (&'a IndexedSchema, &'a wit::ScalarDefinition)) -> Self {
        Self { definition }
    }
}

impl<'a> ScalarDefinition<'a> {
    /// Unique identifier for this scalar definition
    pub fn id(&self) -> DefinitionId {
        DefinitionId(self.definition.id)
    }

    /// Name of the scalar type
    pub fn name(&self) -> &'a str {
        self.definition.name.as_str()
    }

    /// URL that specifies the behavior of this scalar, if any
    ///
    /// The specified by URL is used with custom scalars to point to
    /// a specification for how the scalar should be validated and parsed.
    pub fn specified_by_url(&self) -> Option<&'a str> {
        self.definition.specified_by_url.as_deref()
    }

    /// Iterator over the directives applied to this scalar
    pub fn directives(&self) -> impl ExactSizeIterator<Item = Directive<'a>> + 'a {
        self.definition.directives.iter().map(Into::into)
    }
}

/// GraphQL object type definition
#[derive(Clone, Copy)]
pub struct ObjectDefinition<'a> {
    pub(crate) schema: &'a IndexedSchema,
    pub(crate) definition: &'a wit::ObjectDefinition,
}

impl fmt::Debug for ObjectDefinition<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ObjectDefinition")
            .field("id", &self.id())
            .field("name", &self.name())
            .field("fields", &self.fields().collect::<Vec<_>>())
            .field(
                "interfaces",
                &self.interfaces().map(|inf| inf.name()).collect::<Vec<_>>(),
            )
            .field("directives", &self.directives().collect::<Vec<_>>())
            .finish()
    }
}

impl std::fmt::Display for ObjectDefinition<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl<'a> From<(&'a IndexedSchema, &'a wit::ObjectDefinition)> for ObjectDefinition<'a> {
    fn from((schema, definition): (&'a IndexedSchema, &'a wit::ObjectDefinition)) -> Self {
        Self { schema, definition }
    }
}

impl<'a> ObjectDefinition<'a> {
    /// Unique identifier for this object definition
    pub fn id(&self) -> DefinitionId {
        DefinitionId(self.definition.id)
    }

    /// Name of the object type
    pub fn name(&self) -> &'a str {
        self.definition.name.as_str()
    }

    /// Iterator over the fields defined in this object
    pub fn fields(&self) -> impl ExactSizeIterator<Item = FieldDefinition<'a>> + 'a {
        let schema = self.schema;
        self.definition.field_ids.iter().map(move |id| FieldDefinition {
            schema,
            definition: &schema.field_definitions[&DefinitionId(*id)],
        })
    }

    /// Iterator over the interfaces implemented by this object
    pub fn interfaces(&self) -> impl ExactSizeIterator<Item = InterfaceDefinition<'a>> + 'a {
        let schema = self.schema;
        self.definition.interface_ids.iter().map(move |&id| {
            let Some(wit::TypeDefinition::Interface(def)) = &schema.type_definitions.get(&DefinitionId(id)) else {
                unreachable!("Inconsitent schema");
            };
            (schema, def).into()
        })
    }

    /// Iterator over the directives applied to this object
    pub fn directives(&self) -> impl ExactSizeIterator<Item = Directive<'a>> + 'a {
        self.definition.directives.iter().map(Into::into)
    }
}

/// Represents a GraphQL interface type definition
///
/// Interface types define a set of fields that multiple object types can implement.
/// Interfaces can also implement other interfaces.
#[derive(Clone, Copy)]
pub struct InterfaceDefinition<'a> {
    pub(crate) schema: &'a IndexedSchema,
    pub(crate) definition: &'a wit::InterfaceDefinition,
}

impl fmt::Debug for InterfaceDefinition<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InterfaceDefinition")
            .field("id", &self.id())
            .field("name", &self.name())
            .field("fields", &self.fields().collect::<Vec<_>>())
            .field(
                "interfaces",
                &self.interfaces().map(|inf| inf.name()).collect::<Vec<_>>(),
            )
            .field("directives", &self.directives().collect::<Vec<_>>())
            .finish()
    }
}

impl std::fmt::Display for InterfaceDefinition<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl<'a> From<(&'a IndexedSchema, &'a wit::InterfaceDefinition)> for InterfaceDefinition<'a> {
    fn from((schema, definition): (&'a IndexedSchema, &'a wit::InterfaceDefinition)) -> Self {
        Self { schema, definition }
    }
}

impl<'a> InterfaceDefinition<'a> {
    /// Unique identifier for this interface definition
    pub fn id(&self) -> DefinitionId {
        DefinitionId(self.definition.id)
    }

    /// Name of the interface type
    pub fn name(&self) -> &'a str {
        self.definition.name.as_str()
    }

    /// Iterator over the fields defined in this interface
    pub fn fields(&self) -> impl ExactSizeIterator<Item = FieldDefinition<'a>> + 'a {
        let schema = self.schema;
        self.definition.field_ids.iter().map(move |id| FieldDefinition {
            definition: &schema.field_definitions[&DefinitionId(*id)],
            schema,
        })
    }

    /// Iterator over the interfaces implemented by this interface
    pub fn interfaces(&self) -> impl ExactSizeIterator<Item = InterfaceDefinition<'a>> + 'a {
        let schema = self.schema;
        self.definition.interface_ids.iter().map(move |&id| {
            let Some(wit::TypeDefinition::Interface(def)) = &schema.type_definitions.get(&DefinitionId(id)) else {
                unreachable!("Inconsitent schema");
            };
            (schema, def).into()
        })
    }

    /// Iterator over the directives applied to this interface
    pub fn directives(&self) -> impl ExactSizeIterator<Item = Directive<'a>> + 'a {
        self.definition.directives.iter().map(Into::into)
    }
}

/// Represents a GraphQL entity definition, which can be either an object or an interface
/// It does not imply that this is a _federated_ entity with a `@key` directive.
#[derive(Clone, Copy)]
pub enum EntityDefinition<'a> {
    /// An object type definition
    Object(ObjectDefinition<'a>),
    /// An interface type definition
    Interface(InterfaceDefinition<'a>),
}

impl fmt::Debug for EntityDefinition<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EntityDefinition::Object(def) => f.debug_tuple("Object").field(def).finish(),
            EntityDefinition::Interface(def) => f.debug_tuple("Interface").field(def).finish(),
        }
    }
}

impl std::fmt::Display for EntityDefinition<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EntityDefinition::Object(def) => write!(f, "{}", def.name()),
            EntityDefinition::Interface(def) => write!(f, "{}", def.name()),
        }
    }
}

/// Represents a GraphQL union type definition
///
/// Union types define a type that could be one of several object types.
#[derive(Clone, Copy)]
pub struct UnionDefinition<'a> {
    pub(crate) schema: &'a IndexedSchema,
    pub(crate) definition: &'a wit::UnionDefinition,
}

impl fmt::Debug for UnionDefinition<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("UnionDefinition")
            .field("id", &self.id())
            .field("name", &self.name())
            .field(
                "member_types",
                &self.member_types().map(|obj| obj.name()).collect::<Vec<_>>(),
            )
            .field("directives", &self.directives().collect::<Vec<_>>())
            .finish()
    }
}

impl std::fmt::Display for UnionDefinition<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl<'a> From<(&'a IndexedSchema, &'a wit::UnionDefinition)> for UnionDefinition<'a> {
    fn from((schema, definition): (&'a IndexedSchema, &'a wit::UnionDefinition)) -> Self {
        Self { schema, definition }
    }
}

impl<'a> UnionDefinition<'a> {
    /// Unique identifier for this union definition
    pub fn id(&self) -> DefinitionId {
        DefinitionId(self.definition.id)
    }

    /// Name of the union type
    pub fn name(&self) -> &'a str {
        self.definition.name.as_str()
    }

    /// Iterator over the member types that are part of this union
    pub fn member_types(&self) -> impl ExactSizeIterator<Item = ObjectDefinition<'a>> + 'a {
        let schema = self.schema;
        self.definition.member_types.iter().map(move |&id| {
            let Some(wit::TypeDefinition::Object(def)) = &schema.type_definitions.get(&DefinitionId(id)) else {
                unreachable!("Inconsitent schema");
            };
            (schema, def).into()
        })
    }

    /// Iterator over the directives applied to this union
    pub fn directives(&self) -> impl ExactSizeIterator<Item = Directive<'a>> + 'a {
        self.definition.directives.iter().map(Into::into)
    }
}

/// Represents a GraphQL enum type definition
///
/// Enum types restrict a field to a finite set of values.
#[derive(Clone, Copy)]
pub struct EnumDefinition<'a> {
    pub(crate) definition: &'a wit::EnumDefinition,
}

impl fmt::Debug for EnumDefinition<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EnumDefinition")
            .field("id", &self.id())
            .field("name", &self.name())
            .field("values", &self.values().collect::<Vec<_>>())
            .field("directives", &self.directives().collect::<Vec<_>>())
            .finish()
    }
}

impl std::fmt::Display for EnumDefinition<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl<'a> From<(&'a IndexedSchema, &'a wit::EnumDefinition)> for EnumDefinition<'a> {
    fn from((_, definition): (&'a IndexedSchema, &'a wit::EnumDefinition)) -> Self {
        Self { definition }
    }
}

impl<'a> EnumDefinition<'a> {
    /// Unique identifier for this enum definition
    pub fn id(&self) -> DefinitionId {
        DefinitionId(self.definition.id)
    }

    /// Name of the enum type
    pub fn name(&self) -> &'a str {
        self.definition.name.as_str()
    }

    /// Iterator over the possible values for this enum
    pub fn values(&self) -> impl ExactSizeIterator<Item = EnumValue<'a>> + 'a {
        self.definition.values.iter().map(Into::into)
    }

    /// Iterator over the directives applied to this enum
    pub fn directives(&self) -> impl ExactSizeIterator<Item = Directive<'a>> + 'a {
        self.definition.directives.iter().map(Into::into)
    }
}

/// Represents a GraphQL input object type definition
///
/// Input objects are complex objects provided as arguments to fields,
/// consisting of a set of input fields.
#[derive(Clone, Copy)]
pub struct InputObjectDefinition<'a> {
    pub(crate) schema: &'a IndexedSchema,
    pub(crate) definition: &'a wit::InputObjectDefinition,
}

impl fmt::Debug for InputObjectDefinition<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InputObjectDefinition")
            .field("id", &self.id())
            .field("name", &self.name())
            .field("input_fields", &self.input_fields().collect::<Vec<_>>())
            .field("directives", &self.directives().collect::<Vec<_>>())
            .finish()
    }
}

impl std::fmt::Display for InputObjectDefinition<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl<'a> From<(&'a IndexedSchema, &'a wit::InputObjectDefinition)> for InputObjectDefinition<'a> {
    fn from((schema, definition): (&'a IndexedSchema, &'a wit::InputObjectDefinition)) -> Self {
        Self { schema, definition }
    }
}

impl<'a> InputObjectDefinition<'a> {
    /// Unique identifier for this input object definition
    pub fn id(&self) -> DefinitionId {
        DefinitionId(self.definition.id)
    }

    /// Name of the input object type
    pub fn name(&self) -> &'a str {
        self.definition.name.as_str()
    }

    /// Iterator over the input fields defined in this input object
    pub fn input_fields(&self) -> impl ExactSizeIterator<Item = InputValueDefinition<'a>> + 'a {
        self.definition.input_fields.iter().map(|field| InputValueDefinition {
            definition: field,
            schema: self.schema,
        })
    }

    /// Iterator over the directives applied to this input object
    pub fn directives(&self) -> impl ExactSizeIterator<Item = Directive<'a>> + 'a {
        self.definition.directives.iter().map(Into::into)
    }
}

/// Represents a GraphQL field definition within an object or interface
///
/// Fields are the basic units of data in GraphQL. They define what data can be
/// fetched from a particular object or interface.
#[derive(Clone, Copy)]
pub struct FieldDefinition<'a> {
    pub(crate) schema: &'a IndexedSchema,
    pub(crate) definition: &'a wit::FieldDefinition,
}

impl fmt::Debug for FieldDefinition<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FieldDefinition")
            .field("id", &self.id())
            .field("name", &self.name())
            .field("type", &self.ty())
            .field("arguments", &self.arguments().collect::<Vec<_>>())
            .field("directives", &self.directives().collect::<Vec<_>>())
            .finish()
    }
}

impl std::fmt::Display for FieldDefinition<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}", self.parent_entity(), self.name())
    }
}

impl<'a> FieldDefinition<'a> {
    /// Unique identifier for this field definition
    pub fn id(&self) -> DefinitionId {
        DefinitionId(self.definition.id)
    }

    /// Name of the field
    pub fn name(&self) -> &'a str {
        self.definition.name.as_str()
    }

    /// Parent entity that this field belongs to
    pub fn parent_entity(&self) -> EntityDefinition<'a> {
        let def = &self.schema.type_definitions[&DefinitionId(self.definition.parent_type_id)];
        match def {
            wit::TypeDefinition::Object(obj) => EntityDefinition::Object((self.schema, obj).into()),
            wit::TypeDefinition::Interface(inf) => EntityDefinition::Interface((self.schema, inf).into()),
            _ => unreachable!("Field definition parent type must be an object or interface"),
        }
    }

    /// Type of value this field returns
    pub fn ty(&self) -> Type<'a> {
        (self.schema, &self.definition.ty).into()
    }

    /// Iterator over the arguments that can be passed to this field
    pub fn arguments(&self) -> impl ExactSizeIterator<Item = InputValueDefinition<'a>> + 'a {
        self.definition.arguments.iter().map(|arg| InputValueDefinition {
            definition: arg,
            schema: self.schema,
        })
    }

    /// Iterator over the directives applied to this field
    pub fn directives(&self) -> impl ExactSizeIterator<Item = Directive<'a>> + 'a {
        self.definition.directives.iter().map(Into::into)
    }
}

/// Represents a GraphQL type with its wrapping information
///
/// This struct contains information about a type's definition and any non-null
/// or list wrapping that may be applied to it.
#[derive(Clone, Copy)]
pub struct Type<'a> {
    schema: &'a IndexedSchema,
    ty: &'a wit::Ty,
}

impl fmt::Debug for Type<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Type")
            .field("definition", &self.definition().name())
            .field("wrapping", &self.wrapping().collect::<Vec<_>>())
            .finish()
    }
}

impl<'a> From<(&'a IndexedSchema, &'a wit::Ty)> for Type<'a> {
    fn from((schema, ty): (&'a IndexedSchema, &'a wit::Ty)) -> Self {
        Self { schema, ty }
    }
}

impl<'a> Type<'a> {
    /// Whether this type is non-null
    pub fn is_non_null(&self) -> bool {
        self.wrapping().last() == Some(WrappingType::NonNull)
    }

    /// Whether this type is a list
    pub fn is_list(&self) -> bool {
        self.wrapping().any(|w| matches!(w, WrappingType::List))
    }

    /// Iterator over the type wrappers applied to this type
    /// From the innermost to the outermost
    pub fn wrapping(&self) -> impl ExactSizeIterator<Item = WrappingType> + 'a {
        self.ty.wrapping.iter().map(|&w| w.into())
    }

    /// Identifier for the base type definition
    pub fn definition(&self) -> TypeDefinition<'a> {
        let Some(def) = self.schema.type_definitions.get(&DefinitionId(self.ty.definition_id)) else {
            unreachable!("Inconsitent schema");
        };
        (self.schema, def).into()
    }
}

/// Represents the different ways a GraphQL type can be wrapped
///
/// Types in GraphQL can be wrapped to indicate they are non-null or
/// represent a list of values.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum WrappingType {
    /// Indicates that the wrapped type cannot be null
    NonNull,
    /// Indicates that the wrapped type is a list of elements
    List,
}

impl From<wit::WrappingType> for WrappingType {
    fn from(wrapping: wit::WrappingType) -> Self {
        match wrapping {
            wit::WrappingType::NonNull => WrappingType::NonNull,
            wit::WrappingType::List => WrappingType::List,
        }
    }
}

/// Represents an input value definition in a GraphQL schema
///
/// Input values are used for arguments on fields and input object fields.
#[derive(Clone, Copy)]
pub struct InputValueDefinition<'a> {
    pub(crate) schema: &'a IndexedSchema,
    pub(crate) definition: &'a wit::InputValueDefinition,
}

impl fmt::Debug for InputValueDefinition<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InputValueDefinition")
            .field("id", &self.id())
            .field("name", &self.name())
            .field("type", &self.ty())
            .field("directives", &self.directives().collect::<Vec<_>>())
            .finish()
    }
}

impl<'a> From<(&'a IndexedSchema, &'a wit::InputValueDefinition)> for InputValueDefinition<'a> {
    fn from((schema, definition): (&'a IndexedSchema, &'a wit::InputValueDefinition)) -> Self {
        Self { schema, definition }
    }
}

impl<'a> InputValueDefinition<'a> {
    /// Unique identifier for this input value definition
    pub fn id(&self) -> DefinitionId {
        DefinitionId(self.definition.id)
    }

    /// Name of the input value
    pub fn name(&self) -> &'a str {
        self.definition.name.as_str()
    }

    /// Type of this input value
    pub fn ty(&self) -> Type<'a> {
        (self.schema, &self.definition.ty).into()
    }

    /// Iterator over the directives applied to this input value
    pub fn directives(&self) -> impl ExactSizeIterator<Item = Directive<'a>> + 'a {
        self.definition.directives.iter().map(Into::into)
    }
}

/// Represents a single possible value in a GraphQL enum definition
#[derive(Clone, Copy)]
pub struct EnumValue<'a>(&'a wit::EnumValue);

impl fmt::Debug for EnumValue<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EnumValue")
            .field("name", &self.name())
            .field("directives", &self.directives().collect::<Vec<_>>())
            .finish()
    }
}

impl<'a> From<&'a wit::EnumValue> for EnumValue<'a> {
    fn from(enum_value: &'a wit::EnumValue) -> Self {
        Self(enum_value)
    }
}

impl<'a> EnumValue<'a> {
    /// Name of this enum value
    pub fn name(&self) -> &'a str {
        self.0.name.as_str()
    }

    /// Iterator over the directives applied to this enum value
    pub fn directives(&self) -> impl ExactSizeIterator<Item = Directive<'a>> + 'a {
        self.0.directives.iter().map(Into::into)
    }
}

/// Represents a GraphQL directive applied to a schema element
///
/// Directives provide a way to describe alternate runtime execution and type validation
/// behavior in a GraphQL document.
#[derive(Clone, Copy)]
pub struct Directive<'a>(pub(crate) DirectiveInner<'a>);

// TODO: write explicitly wit::Directive to use Cow instead of this enum.
#[derive(Clone, Copy)]
pub(crate) enum DirectiveInner<'a> {
    Wit(&'a wit::Directive),
    NameAndArgs { name: &'a str, arguments: &'a [u8] },
}

impl fmt::Debug for Directive<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Directive")
            .field("name", &self.name())
            .field("arguments", &"<binary arguments>")
            .finish()
    }
}

impl<'a> From<&'a wit::Directive> for Directive<'a> {
    fn from(directive: &'a wit::Directive) -> Self {
        Self(DirectiveInner::Wit(directive))
    }
}

impl<'a> Directive<'a> {
    /// Name of the directive
    pub fn name(&self) -> &'a str {
        match &self.0 {
            DirectiveInner::Wit(directive) => directive.name.as_str(),
            DirectiveInner::NameAndArgs { name, .. } => name,
        }
    }

    /// Deserializes the directive's arguments into the specified type.
    pub fn arguments<T>(&self) -> Result<T, SdkError>
    where
        T: Deserialize<'a>,
    {
        cbor::from_slice::<T>(self.arguments_bytes()).map_err(Into::into)
    }

    /// Deserialize the arguments of the directive using a `DeserializeSeed`.
    #[inline]
    pub fn arguments_seed<T>(&self, seed: T) -> Result<T::Value, SdkError>
    where
        T: serde::de::DeserializeSeed<'a>,
    {
        cbor::from_slice_with_seed(self.arguments_bytes(), seed).map_err(Into::into)
    }

    fn arguments_bytes(&self) -> &'a [u8] {
        match &self.0 {
            DirectiveInner::Wit(directive) => &directive.arguments,
            DirectiveInner::NameAndArgs { arguments, .. } => arguments,
        }
    }
}