// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: network.slices.tools.document
//
// This file was automatically generated from Lexicon schemas.
// Any manual changes will be overwritten on the next regeneration.

#[allow(unused_imports)]
use alloc::collections::BTreeMap;

#[allow(unused_imports)]
use core::marker::PhantomData;
use jacquard_common::{CowStr, BosStr, DefaultStr, FromStaticStr};

#[allow(unused_imports)]
use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
use jacquard_common::deps::smol_str::SmolStr;
use jacquard_common::types::blob::BlobRef;
use jacquard_common::types::collection::{Collection, RecordError};
use jacquard_common::types::string::{AtUri, Cid, Datetime};
use jacquard_common::types::uri::{RecordUri, UriError};
use jacquard_common::types::value::Data;
use jacquard_common::xrpc::XrpcResp;
use jacquard_derive::{IntoStatic, lexicon, open_union};
use jacquard_lexicon::lexicon::LexiconDoc;
use jacquard_lexicon::schema::LexiconSchema;

#[allow(unused_imports)]
use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
use serde::{Serialize, Deserialize};
use crate::network_slices::tools::richtext::facet::Facet;
use crate::network_slices::tools::document;
/// A fenced code block

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct CodeBlock<S: BosStr = DefaultStr> {
    pub code: S,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lang: Option<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// A heading block (h1-h3) with optional inline formatting

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Heading<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub facets: Option<Vec<Facet<S>>>,
    pub level: i64,
    pub text: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// An embedded image with alt text

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct ImageEmbed<S: BosStr = DefaultStr> {
    ///Alt text for accessibility
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alt: Option<S>,
    pub image: BlobRef<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "network.slices.tools.document",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Document<S: BosStr = DefaultStr> {
    ///Document content as array of blocks
    pub blocks: Vec<DocumentBlocksItem<S>>,
    pub created_at: Datetime,
    ///URL-friendly identifier, unique per author
    pub slug: S,
    ///Document title
    pub title: S,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<Datetime>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub enum DocumentBlocksItem<S: BosStr = DefaultStr> {
    #[serde(rename = "network.slices.tools.document#paragraph")]
    Paragraph(Box<document::Paragraph<S>>),
    #[serde(rename = "network.slices.tools.document#heading")]
    Heading(Box<document::Heading<S>>),
    #[serde(rename = "network.slices.tools.document#codeBlock")]
    CodeBlock(Box<document::CodeBlock<S>>),
    #[serde(rename = "network.slices.tools.document#quote")]
    Quote(Box<document::Quote<S>>),
    #[serde(rename = "network.slices.tools.document#tangledEmbed")]
    TangledEmbed(Box<document::TangledEmbed<S>>),
    #[serde(rename = "network.slices.tools.document#imageEmbed")]
    ImageEmbed(Box<document::ImageEmbed<S>>),
}

/// Typed wrapper for GetRecord response with this collection's record type.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase")]
pub struct DocumentGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Document<S>,
}

/// A paragraph block with optional inline formatting

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Paragraph<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub facets: Option<Vec<Facet<S>>>,
    pub text: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// A blockquote with optional inline formatting

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Quote<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub facets: Option<Vec<Facet<S>>>,
    pub text: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// An embedded Tangled repo card

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct TangledEmbed<S: BosStr = DefaultStr> {
    ///The repo owner's handle
    pub handle: S,
    ///The repository name
    pub repo: S,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

impl<S: BosStr> Document<S> {
    pub fn uri(uri: S) -> Result<RecordUri<S, DocumentRecord>, UriError> {
        RecordUri::try_from_uri(AtUri::new(uri)?)
    }
}

impl<S: BosStr> LexiconSchema for CodeBlock<S> {
    fn nsid() -> &'static str {
        "network.slices.tools.document"
    }
    fn def_name() -> &'static str {
        "codeBlock"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_network_slices_tools_document()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.code;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 20000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("code"),
                    max: 20000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.lang {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 50usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("lang"),
                    max: 50usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for Heading<S> {
    fn nsid() -> &'static str {
        "network.slices.tools.document"
    }
    fn def_name() -> &'static str {
        "heading"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_network_slices_tools_document()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.level;
            if *value > 3i64 {
                return Err(ConstraintError::Maximum {
                    path: ValidationPath::from_field("level"),
                    max: 3i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.level;
            if *value < 1i64 {
                return Err(ConstraintError::Minimum {
                    path: ValidationPath::from_field("level"),
                    min: 1i64,
                    actual: *value,
                });
            }
        }
        {
            let value = &self.text;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 300usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("text"),
                    max: 300usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for ImageEmbed<S> {
    fn nsid() -> &'static str {
        "network.slices.tools.document"
    }
    fn def_name() -> &'static str {
        "imageEmbed"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_network_slices_tools_document()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.alt {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("alt"),
                    max: 1000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.image;
            {
                let size = value.blob().size;
                if size > 1000000usize {
                    return Err(ConstraintError::BlobTooLarge {
                        path: ValidationPath::from_field("image"),
                        max: 1000000usize,
                        actual: size,
                    });
                }
            }
        }
        {
            let value = &self.image;
            {
                let mime = value.blob().mime_type.as_str();
                let accepted: &[&str] = &["image/*"];
                let matched = accepted
                    .iter()
                    .any(|pattern| {
                        if *pattern == "*/*" {
                            true
                        } else if pattern.ends_with("/*") {
                            let prefix = &pattern[..pattern.len() - 2];
                            mime.starts_with(prefix)
                                && mime.as_bytes().get(prefix.len()) == Some(&b'/')
                        } else {
                            mime == *pattern
                        }
                    });
                if !matched {
                    return Err(ConstraintError::BlobMimeTypeNotAccepted {
                        path: ValidationPath::from_field("image"),
                        accepted: vec!["image/*".to_string()],
                        actual: mime.to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

/// Marker type for deserializing records from this collection.

#[derive(Debug, Serialize, Deserialize)]
pub struct DocumentRecord;
impl XrpcResp for DocumentRecord {
    const NSID: &'static str = "network.slices.tools.document";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = DocumentGetRecordOutput<S>;
    type Err = RecordError;
}

impl<S: BosStr> From<DocumentGetRecordOutput<S>> for Document<S> {
    fn from(output: DocumentGetRecordOutput<S>) -> Self {
        output.value
    }
}

impl<S: BosStr> Collection for Document<S> {
    const NSID: &'static str = "network.slices.tools.document";
    type Record = DocumentRecord;
}

impl Collection for DocumentRecord {
    const NSID: &'static str = "network.slices.tools.document";
    type Record = DocumentRecord;
}

impl<S: BosStr> LexiconSchema for Document<S> {
    fn nsid() -> &'static str {
        "network.slices.tools.document"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_network_slices_tools_document()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.slug;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 100usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("slug"),
                    max: 100usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.title;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 300usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("title"),
                    max: 300usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for Paragraph<S> {
    fn nsid() -> &'static str {
        "network.slices.tools.document"
    }
    fn def_name() -> &'static str {
        "paragraph"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_network_slices_tools_document()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.text;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 10000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("text"),
                    max: 10000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for Quote<S> {
    fn nsid() -> &'static str {
        "network.slices.tools.document"
    }
    fn def_name() -> &'static str {
        "quote"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_network_slices_tools_document()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.text;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 5000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("text"),
                    max: 5000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for TangledEmbed<S> {
    fn nsid() -> &'static str {
        "network.slices.tools.document"
    }
    fn def_name() -> &'static str {
        "tangledEmbed"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_network_slices_tools_document()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.handle;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 300usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("handle"),
                    max: 300usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.repo;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 300usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("repo"),
                    max: 300usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

fn lexicon_doc_network_slices_tools_document() -> LexiconDoc<'static> {
    #[allow(unused_imports)]
    use jacquard_common::{CowStr, deps::smol_str::SmolStr, types::blob::MimeType};
    use jacquard_lexicon::lexicon::*;
    use alloc::collections::BTreeMap;
    LexiconDoc {
        lexicon: Lexicon::Lexicon1,
        id: CowStr::new_static("network.slices.tools.document"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("codeBlock"),
                LexUserType::Object(LexObject {
                    description: Some(CowStr::new_static("A fenced code block")),
                    required: Some(vec![SmolStr::new_static("code")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("code"),
                            LexObjectProperty::String(LexString {
                                max_length: Some(20000usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("lang"),
                            LexObjectProperty::String(LexString {
                                max_length: Some(50usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("heading"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "A heading block (h1-h3) with optional inline formatting",
                        ),
                    ),
                    required: Some(
                        vec![SmolStr::new_static("level"), SmolStr::new_static("text")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("facets"),
                            LexObjectProperty::Array(LexArray {
                                items: LexArrayItem::Ref(LexRef {
                                    r#ref: CowStr::new_static(
                                        "network.slices.tools.richtext.facet",
                                    ),
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("level"),
                            LexObjectProperty::Integer(LexInteger {
                                minimum: Some(1i64),
                                maximum: Some(3i64),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("text"),
                            LexObjectProperty::String(LexString {
                                max_length: Some(300usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("imageEmbed"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("An embedded image with alt text"),
                    ),
                    required: Some(vec![SmolStr::new_static("image")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("alt"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Alt text for accessibility"),
                                ),
                                max_length: Some(1000usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("image"),
                            LexObjectProperty::Blob(LexBlob { ..Default::default() }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(
                            vec![
                                SmolStr::new_static("title"), SmolStr::new_static("slug"),
                                SmolStr::new_static("blocks"),
                                SmolStr::new_static("createdAt")
                            ],
                        ),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("blocks"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static("Document content as array of blocks"),
                                    ),
                                    items: LexArrayItem::Union(LexRefUnion {
                                        refs: vec![
                                            CowStr::new_static("#paragraph"),
                                            CowStr::new_static("#heading"),
                                            CowStr::new_static("#codeBlock"),
                                            CowStr::new_static("#quote"),
                                            CowStr::new_static("#tangledEmbed"),
                                            CowStr::new_static("#imageEmbed")
                                        ],
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("slug"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "URL-friendly identifier, unique per author",
                                        ),
                                    ),
                                    max_length: Some(100usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("title"),
                                LexObjectProperty::String(LexString {
                                    description: Some(CowStr::new_static("Document title")),
                                    max_length: Some(300usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("updatedAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("paragraph"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "A paragraph block with optional inline formatting",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("text")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("facets"),
                            LexObjectProperty::Array(LexArray {
                                items: LexArrayItem::Ref(LexRef {
                                    r#ref: CowStr::new_static(
                                        "network.slices.tools.richtext.facet",
                                    ),
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("text"),
                            LexObjectProperty::String(LexString {
                                max_length: Some(10000usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("quote"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "A blockquote with optional inline formatting",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("text")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("facets"),
                            LexObjectProperty::Array(LexArray {
                                items: LexArrayItem::Ref(LexRef {
                                    r#ref: CowStr::new_static(
                                        "network.slices.tools.richtext.facet",
                                    ),
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("text"),
                            LexObjectProperty::String(LexString {
                                max_length: Some(5000usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("tangledEmbed"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("An embedded Tangled repo card"),
                    ),
                    required: Some(
                        vec![SmolStr::new_static("handle"), SmolStr::new_static("repo")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("handle"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The repo owner's handle"),
                                ),
                                max_length: Some(300usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("repo"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The repository name"),
                                ),
                                max_length: Some(300usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod heading_state {

    pub use crate::builder_types::{Set, Unset, IsSet, IsUnset};
    #[allow(unused)]
    use ::core::marker::PhantomData;
    mod sealed {
        pub trait Sealed {}
    }
    /// State trait tracking which required fields have been set
    pub trait State: sealed::Sealed {
        type Level;
        type Text;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Level = Unset;
        type Text = Unset;
    }
    ///State transition - sets the `level` field to Set
    pub struct SetLevel<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetLevel<St> {}
    impl<St: State> State for SetLevel<St> {
        type Level = Set<members::level>;
        type Text = St::Text;
    }
    ///State transition - sets the `text` field to Set
    pub struct SetText<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetText<St> {}
    impl<St: State> State for SetText<St> {
        type Level = St::Level;
        type Text = Set<members::text>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `level` field
        pub struct level(());
        ///Marker type for the `text` field
        pub struct text(());
    }
}

/// Builder for constructing an instance of this type.
pub struct HeadingBuilder<St: heading_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<Vec<Facet<S>>>, Option<i64>, Option<S>),
    _type: PhantomData<fn() -> S>,
}

impl Heading<DefaultStr> {
    /// Create a new builder for this type, using the default string type (DefaultStr = SmolStr) if needed
    pub fn new() -> HeadingBuilder<heading_state::Empty, DefaultStr> {
        HeadingBuilder::new()
    }
}

impl<S: BosStr> Heading<S> {
    /// Create a new builder for this type
    pub fn builder() -> HeadingBuilder<heading_state::Empty, S> {
        HeadingBuilder::builder()
    }
}

impl HeadingBuilder<heading_state::Empty, DefaultStr> {
    /// Create a new builder with all fields unset, using the default string type, if needed
    pub fn new() -> Self {
        HeadingBuilder {
            _state: PhantomData,
            _fields: (None, None, None),
            _type: PhantomData,
        }
    }
}

impl<S: BosStr> HeadingBuilder<heading_state::Empty, S> {
    /// Create a new builder with all fields unset
    pub fn builder() -> Self {
        HeadingBuilder {
            _state: PhantomData,
            _fields: (None, None, None),
            _type: PhantomData,
        }
    }
}

impl<St: heading_state::State, S: BosStr> HeadingBuilder<St, S> {
    /// Set the `facets` field (optional)
    pub fn facets(mut self, value: impl Into<Option<Vec<Facet<S>>>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `facets` field to an Option value (optional)
    pub fn maybe_facets(mut self, value: Option<Vec<Facet<S>>>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St, S: BosStr> HeadingBuilder<St, S>
where
    St: heading_state::State,
    St::Level: heading_state::IsUnset,
{
    /// Set the `level` field (required)
    pub fn level(
        mut self,
        value: impl Into<i64>,
    ) -> HeadingBuilder<heading_state::SetLevel<St>, S> {
        self._fields.1 = Option::Some(value.into());
        HeadingBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> HeadingBuilder<St, S>
where
    St: heading_state::State,
    St::Text: heading_state::IsUnset,
{
    /// Set the `text` field (required)
    pub fn text(
        mut self,
        value: impl Into<S>,
    ) -> HeadingBuilder<heading_state::SetText<St>, S> {
        self._fields.2 = Option::Some(value.into());
        HeadingBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> HeadingBuilder<St, S>
where
    St: heading_state::State,
    St::Level: heading_state::IsSet,
    St::Text: heading_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Heading<S> {
        Heading {
            facets: self._fields.0,
            level: self._fields.1.unwrap(),
            text: self._fields.2.unwrap(),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Heading<S> {
        Heading {
            facets: self._fields.0,
            level: self._fields.1.unwrap(),
            text: self._fields.2.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

pub mod image_embed_state {

    pub use crate::builder_types::{Set, Unset, IsSet, IsUnset};
    #[allow(unused)]
    use ::core::marker::PhantomData;
    mod sealed {
        pub trait Sealed {}
    }
    /// State trait tracking which required fields have been set
    pub trait State: sealed::Sealed {
        type Image;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Image = Unset;
    }
    ///State transition - sets the `image` field to Set
    pub struct SetImage<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetImage<St> {}
    impl<St: State> State for SetImage<St> {
        type Image = Set<members::image>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `image` field
        pub struct image(());
    }
}

/// Builder for constructing an instance of this type.
pub struct ImageEmbedBuilder<St: image_embed_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (Option<S>, Option<BlobRef<S>>),
    _type: PhantomData<fn() -> S>,
}

impl ImageEmbed<DefaultStr> {
    /// Create a new builder for this type, using the default string type (DefaultStr = SmolStr) if needed
    pub fn new() -> ImageEmbedBuilder<image_embed_state::Empty, DefaultStr> {
        ImageEmbedBuilder::new()
    }
}

impl<S: BosStr> ImageEmbed<S> {
    /// Create a new builder for this type
    pub fn builder() -> ImageEmbedBuilder<image_embed_state::Empty, S> {
        ImageEmbedBuilder::builder()
    }
}

impl ImageEmbedBuilder<image_embed_state::Empty, DefaultStr> {
    /// Create a new builder with all fields unset, using the default string type, if needed
    pub fn new() -> Self {
        ImageEmbedBuilder {
            _state: PhantomData,
            _fields: (None, None),
            _type: PhantomData,
        }
    }
}

impl<S: BosStr> ImageEmbedBuilder<image_embed_state::Empty, S> {
    /// Create a new builder with all fields unset
    pub fn builder() -> Self {
        ImageEmbedBuilder {
            _state: PhantomData,
            _fields: (None, None),
            _type: PhantomData,
        }
    }
}

impl<St: image_embed_state::State, S: BosStr> ImageEmbedBuilder<St, S> {
    /// Set the `alt` field (optional)
    pub fn alt(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.0 = value.into();
        self
    }
    /// Set the `alt` field to an Option value (optional)
    pub fn maybe_alt(mut self, value: Option<S>) -> Self {
        self._fields.0 = value;
        self
    }
}

impl<St, S: BosStr> ImageEmbedBuilder<St, S>
where
    St: image_embed_state::State,
    St::Image: image_embed_state::IsUnset,
{
    /// Set the `image` field (required)
    pub fn image(
        mut self,
        value: impl Into<BlobRef<S>>,
    ) -> ImageEmbedBuilder<image_embed_state::SetImage<St>, S> {
        self._fields.1 = Option::Some(value.into());
        ImageEmbedBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ImageEmbedBuilder<St, S>
where
    St: image_embed_state::State,
    St::Image: image_embed_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> ImageEmbed<S> {
        ImageEmbed {
            alt: self._fields.0,
            image: self._fields.1.unwrap(),
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> ImageEmbed<S> {
        ImageEmbed {
            alt: self._fields.0,
            image: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

pub mod document_state {

    pub use crate::builder_types::{Set, Unset, IsSet, IsUnset};
    #[allow(unused)]
    use ::core::marker::PhantomData;
    mod sealed {
        pub trait Sealed {}
    }
    /// State trait tracking which required fields have been set
    pub trait State: sealed::Sealed {
        type Blocks;
        type CreatedAt;
        type Slug;
        type Title;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Blocks = Unset;
        type CreatedAt = Unset;
        type Slug = Unset;
        type Title = Unset;
    }
    ///State transition - sets the `blocks` field to Set
    pub struct SetBlocks<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetBlocks<St> {}
    impl<St: State> State for SetBlocks<St> {
        type Blocks = Set<members::blocks>;
        type CreatedAt = St::CreatedAt;
        type Slug = St::Slug;
        type Title = St::Title;
    }
    ///State transition - sets the `created_at` field to Set
    pub struct SetCreatedAt<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetCreatedAt<St> {}
    impl<St: State> State for SetCreatedAt<St> {
        type Blocks = St::Blocks;
        type CreatedAt = Set<members::created_at>;
        type Slug = St::Slug;
        type Title = St::Title;
    }
    ///State transition - sets the `slug` field to Set
    pub struct SetSlug<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSlug<St> {}
    impl<St: State> State for SetSlug<St> {
        type Blocks = St::Blocks;
        type CreatedAt = St::CreatedAt;
        type Slug = Set<members::slug>;
        type Title = St::Title;
    }
    ///State transition - sets the `title` field to Set
    pub struct SetTitle<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetTitle<St> {}
    impl<St: State> State for SetTitle<St> {
        type Blocks = St::Blocks;
        type CreatedAt = St::CreatedAt;
        type Slug = St::Slug;
        type Title = Set<members::title>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `blocks` field
        pub struct blocks(());
        ///Marker type for the `created_at` field
        pub struct created_at(());
        ///Marker type for the `slug` field
        pub struct slug(());
        ///Marker type for the `title` field
        pub struct title(());
    }
}

/// Builder for constructing an instance of this type.
pub struct DocumentBuilder<St: document_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Vec<DocumentBlocksItem<S>>>,
        Option<Datetime>,
        Option<S>,
        Option<S>,
        Option<Datetime>,
    ),
    _type: PhantomData<fn() -> S>,
}

impl Document<DefaultStr> {
    /// Create a new builder for this type, using the default string type (DefaultStr = SmolStr) if needed
    pub fn new() -> DocumentBuilder<document_state::Empty, DefaultStr> {
        DocumentBuilder::new()
    }
}

impl<S: BosStr> Document<S> {
    /// Create a new builder for this type
    pub fn builder() -> DocumentBuilder<document_state::Empty, S> {
        DocumentBuilder::builder()
    }
}

impl DocumentBuilder<document_state::Empty, DefaultStr> {
    /// Create a new builder with all fields unset, using the default string type, if needed
    pub fn new() -> Self {
        DocumentBuilder {
            _state: PhantomData,
            _fields: (None, None, None, None, None),
            _type: PhantomData,
        }
    }
}

impl<S: BosStr> DocumentBuilder<document_state::Empty, S> {
    /// Create a new builder with all fields unset
    pub fn builder() -> Self {
        DocumentBuilder {
            _state: PhantomData,
            _fields: (None, None, None, None, None),
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> DocumentBuilder<St, S>
where
    St: document_state::State,
    St::Blocks: document_state::IsUnset,
{
    /// Set the `blocks` field (required)
    pub fn blocks(
        mut self,
        value: impl Into<Vec<DocumentBlocksItem<S>>>,
    ) -> DocumentBuilder<document_state::SetBlocks<St>, S> {
        self._fields.0 = Option::Some(value.into());
        DocumentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> DocumentBuilder<St, S>
where
    St: document_state::State,
    St::CreatedAt: document_state::IsUnset,
{
    /// Set the `createdAt` field (required)
    pub fn created_at(
        mut self,
        value: impl Into<Datetime>,
    ) -> DocumentBuilder<document_state::SetCreatedAt<St>, S> {
        self._fields.1 = Option::Some(value.into());
        DocumentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> DocumentBuilder<St, S>
where
    St: document_state::State,
    St::Slug: document_state::IsUnset,
{
    /// Set the `slug` field (required)
    pub fn slug(
        mut self,
        value: impl Into<S>,
    ) -> DocumentBuilder<document_state::SetSlug<St>, S> {
        self._fields.2 = Option::Some(value.into());
        DocumentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> DocumentBuilder<St, S>
where
    St: document_state::State,
    St::Title: document_state::IsUnset,
{
    /// Set the `title` field (required)
    pub fn title(
        mut self,
        value: impl Into<S>,
    ) -> DocumentBuilder<document_state::SetTitle<St>, S> {
        self._fields.3 = Option::Some(value.into());
        DocumentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: document_state::State, S: BosStr> DocumentBuilder<St, S> {
    /// Set the `updatedAt` field (optional)
    pub fn updated_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.4 = value.into();
        self
    }
    /// Set the `updatedAt` field to an Option value (optional)
    pub fn maybe_updated_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.4 = value;
        self
    }
}

impl<St, S: BosStr> DocumentBuilder<St, S>
where
    St: document_state::State,
    St::Blocks: document_state::IsSet,
    St::CreatedAt: document_state::IsSet,
    St::Slug: document_state::IsSet,
    St::Title: document_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Document<S> {
        Document {
            blocks: self._fields.0.unwrap(),
            created_at: self._fields.1.unwrap(),
            slug: self._fields.2.unwrap(),
            title: self._fields.3.unwrap(),
            updated_at: self._fields.4,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(self, extra_data: BTreeMap<SmolStr, Data<S>>) -> Document<S> {
        Document {
            blocks: self._fields.0.unwrap(),
            created_at: self._fields.1.unwrap(),
            slug: self._fields.2.unwrap(),
            title: self._fields.3.unwrap(),
            updated_at: self._fields.4,
            extra_data: Some(extra_data),
        }
    }
}