facet-json-schema 0.46.1

Generate JSON Schema from facet type metadata
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
//! Generate JSON Schema from facet type metadata.
//!
//! This crate uses facet's reflection capabilities to generate JSON Schema definitions
//! from any type that implements `Facet`.
//!
//! # Example
//!
//! ```
//! use facet::Facet;
//! use facet_json_schema::to_schema;
//!
//! #[derive(Facet)]
//! struct User {
//!     name: String,
//!     age: u32,
//!     email: Option<String>,
//! }
//!
//! let schema = to_schema::<User>();
//! println!("{}", schema);
//! ```

extern crate alloc;

use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;

use facet::Facet;
use facet_core::{Def, Field, Shape, StructKind, Type, UserType};

/// A JSON Schema definition.
///
/// This is a simplified representation that covers the most common cases.
/// It can be serialized to JSON using facet-json.
#[derive(Debug, Clone, Facet)]
#[facet(skip_all_unless_truthy)]
pub struct JsonSchema {
    /// The JSON Schema dialect
    #[facet(rename = "$schema")]
    pub schema: Option<String>,

    /// Reference to another schema definition
    #[facet(rename = "$ref")]
    pub ref_: Option<String>,

    /// Schema definitions for reuse
    #[facet(rename = "$defs")]
    pub defs: Option<BTreeMap<String, JsonSchema>>,

    /// The type (or list of types) of the schema
    #[facet(rename = "type")]
    pub type_: Option<SchemaTypes>,

    /// For objects: the properties
    pub properties: Option<BTreeMap<String, JsonSchema>>,

    /// For objects: required property names
    pub required: Option<Vec<String>>,

    /// For objects: additional properties schema or false
    #[facet(rename = "additionalProperties")]
    pub additional_properties: Option<AdditionalProperties>,

    /// For arrays: the items schema
    pub items: Option<Box<JsonSchema>>,

    /// For strings: enumerated values
    #[facet(rename = "enum")]
    pub enum_: Option<Vec<String>>,

    /// For numbers: minimum value
    pub minimum: Option<i64>,

    /// For numbers: maximum value
    pub maximum: Option<i64>,

    /// For oneOf/anyOf/allOf
    #[facet(rename = "oneOf")]
    pub one_of: Option<Vec<JsonSchema>>,

    #[facet(rename = "anyOf")]
    pub any_of: Option<Vec<JsonSchema>>,

    #[facet(rename = "allOf")]
    pub all_of: Option<Vec<JsonSchema>>,

    /// Description from doc comments
    pub description: Option<String>,

    /// Title (type name)
    pub title: Option<String>,

    /// Constant value
    #[facet(rename = "const")]
    pub const_: Option<String>,
}

/// JSON Schema type
#[derive(Debug, Clone, Facet)]
#[facet(rename_all = "lowercase")]
#[repr(u8)]
pub enum SchemaType {
    String,
    Number,
    Integer,
    Boolean,
    Array,
    Object,
    Null,
}

/// JSON Schema `type` supports either a string or an array of strings.
#[derive(Debug, Clone, Facet)]
#[facet(untagged)]
#[repr(u8)]
pub enum SchemaTypes {
    Single(SchemaType),
    Multiple(Vec<SchemaType>),
}

impl From<SchemaType> for SchemaTypes {
    fn from(value: SchemaType) -> Self {
        Self::Single(value)
    }
}

/// Additional properties can be a boolean or a schema
#[derive(Debug, Clone, Facet)]
#[facet(untagged)]
#[repr(u8)]
pub enum AdditionalProperties {
    Bool(bool),
    Schema(Box<JsonSchema>),
}

impl Default for JsonSchema {
    fn default() -> Self {
        Self::new()
    }
}

impl JsonSchema {
    /// Create an empty schema
    pub const fn new() -> Self {
        Self {
            schema: None,
            ref_: None,
            defs: None,
            type_: None,
            properties: None,
            required: None,
            additional_properties: None,
            items: None,
            enum_: None,
            minimum: None,
            maximum: None,
            one_of: None,
            any_of: None,
            all_of: None,
            description: None,
            title: None,
            const_: None,
        }
    }

    /// Create a schema with a $schema dialect
    pub fn with_dialect(dialect: &str) -> Self {
        Self {
            schema: Some(dialect.into()),
            ..Self::new()
        }
    }

    /// Create a reference to another schema
    pub fn reference(ref_path: &str) -> Self {
        Self {
            ref_: Some(ref_path.into()),
            ..Self::new()
        }
    }
}

/// Generate a JSON Schema from a facet type.
///
/// This returns a `JsonSchema` struct that can be serialized to JSON.
pub fn schema_for<T: Facet<'static>>() -> JsonSchema {
    let mut ctx = SchemaContext::new();
    let schema = ctx.schema_for_shape(T::SHAPE);

    // If we collected any definitions, add them to the root
    if ctx.defs.is_empty() {
        schema
    } else {
        JsonSchema {
            schema: Some("https://json-schema.org/draft/2020-12/schema".into()),
            defs: Some(ctx.defs),
            ..schema
        }
    }
}

/// Generate a JSON Schema string from a facet type.
pub fn to_schema<T: Facet<'static>>() -> String {
    let schema = schema_for::<T>();
    facet_json::to_string_pretty(&schema).expect("JSON Schema serialization should not fail")
}

/// Context for schema generation, tracking definitions to avoid cycles.
struct SchemaContext {
    /// Collected schema definitions
    defs: BTreeMap<String, JsonSchema>,
    /// Types currently being processed (for cycle detection)
    in_progress: Vec<&'static str>,
}

impl SchemaContext {
    const fn new() -> Self {
        Self {
            defs: BTreeMap::new(),
            in_progress: Vec::new(),
        }
    }

    fn schema_for_shape(&mut self, shape: &'static Shape) -> JsonSchema {
        // Check for cycles - if we're already processing this type, emit a $ref
        let type_name = shape.type_identifier;
        if self.in_progress.contains(&type_name) {
            return JsonSchema::reference(&format!("#/$defs/{}", type_name));
        }

        // Build description from doc comments
        let description = if shape.doc.is_empty() {
            None
        } else {
            Some(shape.doc.join("\n").trim().to_string())
        };

        // Handle the type based on its definition
        // NOTE: We check Def BEFORE shape.inner because types like Vec<T> set
        // .inner() for type parameter propagation but should still be treated
        // as List, not as transparent wrappers.
        match &shape.def {
            Def::Scalar => self.schema_for_scalar(shape, description),
            Def::Option(opt) => {
                // Option<T> becomes anyOf: [schema(T), {type: "null"}]
                let inner_schema = self.schema_for_shape(opt.t);
                JsonSchema {
                    any_of: Some(vec![
                        inner_schema,
                        JsonSchema {
                            type_: Some(SchemaType::Null.into()),
                            ..JsonSchema::new()
                        },
                    ]),
                    description,
                    ..JsonSchema::new()
                }
            }
            Def::List(list) => JsonSchema {
                type_: Some(SchemaType::Array.into()),
                items: Some(Box::new(self.schema_for_shape(list.t))),
                description,
                ..JsonSchema::new()
            },
            Def::Array(arr) => JsonSchema {
                type_: Some(SchemaType::Array.into()),
                items: Some(Box::new(self.schema_for_shape(arr.t))),
                description,
                ..JsonSchema::new()
            },
            Def::Set(set) => JsonSchema {
                type_: Some(SchemaType::Array.into()),
                items: Some(Box::new(self.schema_for_shape(set.t))),
                description,
                ..JsonSchema::new()
            },
            Def::Map(map) => {
                // Maps become objects with additionalProperties
                JsonSchema {
                    type_: Some(SchemaType::Object.into()),
                    additional_properties: Some(AdditionalProperties::Schema(Box::new(
                        self.schema_for_shape(map.v),
                    ))),
                    description,
                    ..JsonSchema::new()
                }
            }
            Def::Undefined => {
                // Check if it's a struct or enum via Type
                match &shape.ty {
                    Type::User(UserType::Struct(st)) => {
                        self.schema_for_struct(shape, st.fields, st.kind, description)
                    }
                    Type::User(UserType::Enum(en)) => self.schema_for_enum(shape, en, description),
                    _ => {
                        // For other undefined types, check if it's a transparent wrapper
                        if let Some(inner) = shape.inner {
                            self.schema_for_shape(inner)
                        } else {
                            JsonSchema {
                                description,
                                ..JsonSchema::new()
                            }
                        }
                    }
                }
            }
            _ => {
                // For other defs, check if it's a transparent wrapper
                if let Some(inner) = shape.inner {
                    self.schema_for_shape(inner)
                } else {
                    JsonSchema {
                        description,
                        ..JsonSchema::new()
                    }
                }
            }
        }
    }

    fn schema_for_scalar(
        &mut self,
        shape: &'static Shape,
        description: Option<String>,
    ) -> JsonSchema {
        let type_name = shape.type_identifier;

        // Map common Rust types to JSON Schema types
        let (type_, minimum, maximum) = match type_name {
            // Strings
            "String" | "str" | "&str" | "Cow" => (Some(SchemaType::String.into()), None, None),

            // Booleans
            "bool" => (Some(SchemaType::Boolean.into()), None, None),

            // Unsigned integers
            "u8" | "u16" | "u32" | "u64" | "u128" | "usize" => {
                (Some(SchemaType::Integer.into()), Some(0), None)
            }

            // Signed integers
            "i8" => (Some(SchemaType::Integer.into()), Some(i8::MIN as i64), None),
            "i16" => (
                Some(SchemaType::Integer.into()),
                Some(i16::MIN as i64),
                None,
            ),
            "i32" => (
                Some(SchemaType::Integer.into()),
                Some(i32::MIN as i64),
                None,
            ),
            "i64" => (Some(SchemaType::Integer.into()), Some(i64::MIN), None),
            "i128" => (Some(SchemaType::Integer.into()), Some(i64::MIN), None),
            "isize" => (Some(SchemaType::Integer.into()), Some(i64::MIN), None),

            // Floats
            "f32" | "f64" => (Some(SchemaType::Number.into()), None, None),

            // Char as string
            "char" => (Some(SchemaType::String.into()), None, None),

            // Unknown scalar - no type constraint
            _ => (None, None, None),
        };

        JsonSchema {
            type_,
            minimum,
            maximum,
            description,
            ..JsonSchema::new()
        }
    }

    fn schema_for_struct(
        &mut self,
        shape: &'static Shape,
        fields: &'static [Field],
        kind: StructKind,
        description: Option<String>,
    ) -> JsonSchema {
        match kind {
            StructKind::Unit => {
                // Unit struct serializes as null or empty object
                JsonSchema {
                    type_: Some(SchemaType::Null.into()),
                    description,
                    ..JsonSchema::new()
                }
            }
            StructKind::TupleStruct if fields.len() == 1 => {
                // Newtype - serialize as the inner type
                self.schema_for_shape(fields[0].shape.get())
            }
            StructKind::TupleStruct | StructKind::Tuple => {
                // Tuple struct as array - collect items for prefixItems
                let _items: Vec<JsonSchema> = fields
                    .iter()
                    .map(|f| self.schema_for_shape(f.shape.get()))
                    .collect();

                // TODO: Use prefixItems for proper tuple schema (JSON Schema 2020-12)
                JsonSchema {
                    type_: Some(SchemaType::Array.into()),
                    description,
                    ..JsonSchema::new()
                }
            }
            StructKind::Struct => {
                // Mark as in progress for cycle detection
                self.in_progress.push(shape.type_identifier);

                let mut properties = BTreeMap::new();
                let mut required = Vec::new();

                for field in fields {
                    // Skip fields marked with skip
                    if field.flags.contains(facet_core::FieldFlags::SKIP) {
                        continue;
                    }

                    let field_name = field.effective_name();
                    let mut field_schema = self.schema_for_shape(field.shape.get());

                    // Use field-level doc comments instead of type-level
                    let field_description = if field.doc.is_empty() {
                        None
                    } else {
                        Some(field.doc.join("\n").trim().to_string())
                    };
                    field_schema.description = field_description;

                    // Check if field is required (not Option and no default)
                    let is_option = matches!(field.shape.get().def, Def::Option(_));
                    let has_default = field.default.is_some();

                    if !is_option && !has_default {
                        required.push(field_name.to_string());
                    }

                    properties.insert(field_name.to_string(), field_schema);
                }

                self.in_progress.pop();

                JsonSchema {
                    type_: Some(SchemaType::Object.into()),
                    properties: Some(properties),
                    required: if required.is_empty() {
                        None
                    } else {
                        Some(required)
                    },
                    additional_properties: Some(AdditionalProperties::Bool(false)),
                    description,
                    title: Some(shape.type_identifier.to_string()),
                    ..JsonSchema::new()
                }
            }
        }
    }

    fn schema_for_enum(
        &mut self,
        shape: &'static Shape,
        enum_type: &facet_core::EnumType,
        description: Option<String>,
    ) -> JsonSchema {
        // Check if all variants are unit variants (simple string enum)
        let all_unit = enum_type
            .variants
            .iter()
            .all(|v| matches!(v.data.kind, StructKind::Unit));

        if all_unit {
            // Simple string enum
            let values: Vec<String> = enum_type
                .variants
                .iter()
                .map(|v| v.effective_name().to_string())
                .collect();

            JsonSchema {
                type_: Some(SchemaType::String.into()),
                enum_: Some(values),
                description,
                title: Some(shape.type_identifier.to_string()),
                ..JsonSchema::new()
            }
        } else {
            // Complex enum - use oneOf with discriminator
            // This handles internally tagged, externally tagged, adjacently tagged, and untagged
            let variants: Vec<JsonSchema> = enum_type
                .variants
                .iter()
                .map(|v| {
                    let variant_name = v.effective_name().to_string();
                    match v.data.kind {
                        StructKind::Unit => {
                            // Unit variant: { "type": "VariantName" } or just "VariantName"
                            JsonSchema {
                                const_: Some(variant_name),
                                ..JsonSchema::new()
                            }
                        }
                        StructKind::TupleStruct if v.data.fields.len() == 1 => {
                            // Newtype variant: { "VariantName": <inner> }
                            let mut props = BTreeMap::new();
                            props.insert(
                                variant_name.clone(),
                                self.schema_for_shape(v.data.fields[0].shape.get()),
                            );
                            JsonSchema {
                                type_: Some(SchemaType::Object.into()),
                                properties: Some(props),
                                required: Some(vec![variant_name]),
                                additional_properties: Some(AdditionalProperties::Bool(false)),
                                ..JsonSchema::new()
                            }
                        }
                        _ => {
                            // Struct variant: { "VariantName": { ...fields } }
                            let inner =
                                self.schema_for_struct(shape, v.data.fields, v.data.kind, None);
                            let mut props = BTreeMap::new();
                            props.insert(variant_name.clone(), inner);
                            JsonSchema {
                                type_: Some(SchemaType::Object.into()),
                                properties: Some(props),
                                required: Some(vec![variant_name]),
                                additional_properties: Some(AdditionalProperties::Bool(false)),
                                ..JsonSchema::new()
                            }
                        }
                    }
                })
                .collect();

            JsonSchema {
                one_of: Some(variants),
                description,
                title: Some(shape.type_identifier.to_string()),
                ..JsonSchema::new()
            }
        }
    }
}

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

    #[test]
    fn test_simple_struct() {
        #[derive(Facet)]
        struct User {
            name: String,
            age: u32,
        }

        let schema = to_schema::<User>();
        insta::assert_snapshot!(schema);
    }

    #[test]
    fn test_optional_field() {
        #[derive(Facet)]
        struct Config {
            required: String,
            optional: Option<String>,
        }

        let schema = to_schema::<Config>();
        insta::assert_snapshot!(schema);
    }

    #[test]
    fn test_simple_enum() {
        #[derive(Facet)]
        #[repr(u8)]
        enum Status {
            Active,
            Inactive,
            Pending,
        }

        let schema = to_schema::<Status>();
        insta::assert_snapshot!(schema);
    }

    #[test]
    fn test_vec() {
        #[derive(Facet)]
        struct Data {
            items: Vec<String>,
        }

        let schema = to_schema::<Data>();
        insta::assert_snapshot!(schema);
    }

    #[test]
    fn test_enum_rename_all_snake_case() {
        #[derive(Facet)]
        #[facet(rename_all = "snake_case")]
        #[repr(u8)]
        enum ValidationErrorCode {
            CircularDependency,
            InvalidNaming,
            UnknownRequirement,
        }

        let schema = to_schema::<ValidationErrorCode>();
        insta::assert_snapshot!(schema);
    }

    #[test]
    fn test_struct_rename_all_camel_case() {
        #[derive(Facet)]
        #[facet(rename_all = "camelCase")]
        struct ApiResponse {
            user_name: String,
            created_at: String,
            is_active: bool,
        }

        let schema = to_schema::<ApiResponse>();
        insta::assert_snapshot!(schema);
    }

    #[test]
    fn test_field_doc_comments_override_type_description() {
        #[derive(Facet)]
        /// Shared type-level docs that should not leak into undocumented fields.
        struct DocumentedInner {
            value: String,
        }

        #[derive(Facet)]
        struct Container {
            /// Field-level docs win for this property.
            documented: DocumentedInner,
            undocumented: DocumentedInner,
        }

        let schema = schema_for::<Container>();
        let properties = schema
            .properties
            .expect("container should have object properties");

        let documented = properties
            .get("documented")
            .expect("documented field schema should exist");
        assert_eq!(
            documented.description.as_deref(),
            Some("Field-level docs win for this property.")
        );

        let undocumented = properties
            .get("undocumented")
            .expect("undocumented field schema should exist");
        assert_eq!(undocumented.description, None);
    }

    #[test]
    fn test_enum_with_data_rename_all() {
        #[allow(dead_code)]
        #[derive(Facet)]
        #[facet(rename_all = "snake_case")]
        #[repr(C)]
        enum Message {
            TextMessage { content: String },
            ImageUpload { url: String, width: u32 },
        }

        let schema = to_schema::<Message>();
        insta::assert_snapshot!(schema);
    }

    #[test]
    fn test_deserialize_schema_type_as_string() {
        let schema: JsonSchema =
            facet_json::from_str_borrowed(r#"{"type":"integer"}"#).expect("valid schema JSON");

        match schema.type_ {
            Some(SchemaTypes::Single(SchemaType::Integer)) => {}
            other => panic!("expected single integer type, got {other:?}"),
        }
    }

    #[test]
    fn test_deserialize_schema_type_as_array() {
        let schema: JsonSchema =
            facet_json::from_str_borrowed(r#"{"type":["integer"]}"#).expect("valid schema JSON");

        match schema.type_ {
            Some(SchemaTypes::Multiple(types)) => {
                assert!(matches!(types.as_slice(), [SchemaType::Integer]));
            }
            other => panic!("expected integer type array, got {other:?}"),
        }
    }
}