// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: at.inlay.component
//
// 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::collection::{Collection, RecordError};
use jacquard_common::types::string::{Did, AtUri, Nsid, 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::at_inlay::ViaValtown;
use crate::at_inlay::component;
/// Component rendered by calling a remote XRPC endpoint

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct BodyExternal<S: BosStr = DefaultStr> {
    ///DID of the service hosting this component
    pub did: Did<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Component rendered by the host from a serialized element tree

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct BodyTemplate<S: BosStr = DefaultStr> {
    ///Serialized element tree with bindings
    pub node: Data<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// Component record - declares an implementation of a type

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(
    rename_all = "camelCase",
    rename = "at.inlay.component",
    tag = "$type",
    bound(deserialize = "S: Deserialize<'de> + BosStr")
)]
pub struct Component<S: BosStr = DefaultStr> {
    ///How this component is rendered. Omit for primitives rendered by the host.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<ComponentBody<S>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<Datetime>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<S>,
    ///Ordered list of pack URIs (import stack). First pack that exports an NSID wins.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub imports: Option<Vec<AtUri<S>>>,
    ///NSID this component implements (also the XRPC procedure)
    pub r#type: Nsid<S>,
    ///Last update timestamp. Set by the publish flow to bust cached responses.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<Datetime>,
    ///Platform-managed deployment metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub via: Option<ViaValtown<S>>,
    ///What data this component views and which prop receives it
    #[serde(skip_serializing_if = "Option::is_none")]
    pub view: Option<component::View<S>>,
    #[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 ComponentBody<S: BosStr = DefaultStr> {
    #[serde(rename = "at.inlay.component#bodyExternal")]
    BodyExternal(Box<component::BodyExternal<S>>),
    #[serde(rename = "at.inlay.component#bodyTemplate")]
    BodyTemplate(Box<component::BodyTemplate<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 ComponentGetRecordOutput<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<Cid<S>>,
    pub uri: AtUri<S>,
    pub value: Component<S>,
}

/// Declares what data this component views and which prop receives it.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct View<S: BosStr = DefaultStr> {
    ///Data types this view accepts.
    pub accepts: Vec<ViewAcceptsItem<S>>,
    ///Which component prop receives the view data.
    pub prop: S,
    #[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 ViewAcceptsItem<S: BosStr = DefaultStr> {
    #[serde(rename = "at.inlay.component#viewRecord")]
    ViewRecord(Box<component::ViewRecord<S>>),
    #[serde(rename = "at.inlay.component#viewPrimitive")]
    ViewPrimitive(Box<component::ViewPrimitive<S>>),
}

/// View accepts a primitive value type.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct ViewPrimitive<S: BosStr = DefaultStr> {
    ///String format constraint. Only applies when type is 'string'.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<ViewPrimitiveFormat<S>>,
    ///Lexicon primitive type.
    pub r#type: ViewPrimitiveType<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// String format constraint. Only applies when type is 'string'.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ViewPrimitiveFormat<S: BosStr = DefaultStr> {
    AtUri,
    Did,
    Datetime,
    Uri,
    Handle,
    AtIdentifier,
    Nsid,
    Cid,
    Language,
    RecordKey,
    Tid,
    Other(S),
}

impl<S: BosStr> ViewPrimitiveFormat<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::AtUri => "at-uri",
            Self::Did => "did",
            Self::Datetime => "datetime",
            Self::Uri => "uri",
            Self::Handle => "handle",
            Self::AtIdentifier => "at-identifier",
            Self::Nsid => "nsid",
            Self::Cid => "cid",
            Self::Language => "language",
            Self::RecordKey => "record-key",
            Self::Tid => "tid",
            Self::Other(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "at-uri" => Self::AtUri,
            "did" => Self::Did,
            "datetime" => Self::Datetime,
            "uri" => Self::Uri,
            "handle" => Self::Handle,
            "at-identifier" => Self::AtIdentifier,
            "nsid" => Self::Nsid,
            "cid" => Self::Cid,
            "language" => Self::Language,
            "record-key" => Self::RecordKey,
            "tid" => Self::Tid,
            _ => Self::Other(s),
        }
    }
}

impl<S: BosStr> core::fmt::Display for ViewPrimitiveFormat<S> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<S: BosStr> AsRef<str> for ViewPrimitiveFormat<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<S: BosStr> Serialize for ViewPrimitiveFormat<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for ViewPrimitiveFormat<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for ViewPrimitiveFormat<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for ViewPrimitiveFormat<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = ViewPrimitiveFormat<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            ViewPrimitiveFormat::AtUri => ViewPrimitiveFormat::AtUri,
            ViewPrimitiveFormat::Did => ViewPrimitiveFormat::Did,
            ViewPrimitiveFormat::Datetime => ViewPrimitiveFormat::Datetime,
            ViewPrimitiveFormat::Uri => ViewPrimitiveFormat::Uri,
            ViewPrimitiveFormat::Handle => ViewPrimitiveFormat::Handle,
            ViewPrimitiveFormat::AtIdentifier => ViewPrimitiveFormat::AtIdentifier,
            ViewPrimitiveFormat::Nsid => ViewPrimitiveFormat::Nsid,
            ViewPrimitiveFormat::Cid => ViewPrimitiveFormat::Cid,
            ViewPrimitiveFormat::Language => ViewPrimitiveFormat::Language,
            ViewPrimitiveFormat::RecordKey => ViewPrimitiveFormat::RecordKey,
            ViewPrimitiveFormat::Tid => ViewPrimitiveFormat::Tid,
            ViewPrimitiveFormat::Other(v) => ViewPrimitiveFormat::Other(v.into_static()),
        }
    }
}

/// Lexicon primitive type.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ViewPrimitiveType<S: BosStr = DefaultStr> {
    String,
    Integer,
    Boolean,
    Blob,
    CidLink,
    Bytes,
    Other(S),
}

impl<S: BosStr> ViewPrimitiveType<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::String => "string",
            Self::Integer => "integer",
            Self::Boolean => "boolean",
            Self::Blob => "blob",
            Self::CidLink => "cid-link",
            Self::Bytes => "bytes",
            Self::Other(s) => s.as_ref(),
        }
    }
    /// Construct from a string-like value, matching known values.
    pub fn from_value(s: S) -> Self {
        match s.as_ref() {
            "string" => Self::String,
            "integer" => Self::Integer,
            "boolean" => Self::Boolean,
            "blob" => Self::Blob,
            "cid-link" => Self::CidLink,
            "bytes" => Self::Bytes,
            _ => Self::Other(s),
        }
    }
}

impl<S: BosStr> core::fmt::Display for ViewPrimitiveType<S> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl<S: BosStr> AsRef<str> for ViewPrimitiveType<S> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<S: BosStr> Serialize for ViewPrimitiveType<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de, S: Deserialize<'de> + BosStr> Deserialize<'de> for ViewPrimitiveType<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = S::deserialize(deserializer)?;
        Ok(Self::from_value(s))
    }
}

impl<S: BosStr + Default> Default for ViewPrimitiveType<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for ViewPrimitiveType<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = ViewPrimitiveType<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            ViewPrimitiveType::String => ViewPrimitiveType::String,
            ViewPrimitiveType::Integer => ViewPrimitiveType::Integer,
            ViewPrimitiveType::Boolean => ViewPrimitiveType::Boolean,
            ViewPrimitiveType::Blob => ViewPrimitiveType::Blob,
            ViewPrimitiveType::CidLink => ViewPrimitiveType::CidLink,
            ViewPrimitiveType::Bytes => ViewPrimitiveType::Bytes,
            ViewPrimitiveType::Other(v) => ViewPrimitiveType::Other(v.into_static()),
        }
    }
}

/// View accepts individual records of a collection. Omit collection for a generic record view. When rkey is present, the component accepts bare DIDs (expanded to full AT URIs) and appears on identity pages.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct ViewRecord<S: BosStr = DefaultStr> {
    ///The collection this component views. Omit for any-collection.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub collection: Option<Nsid<S>>,
    ///The record key, baked from the collection's lexicon at authoring time. Presence enables DID expansion and identity page routing.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rkey: Option<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

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

impl<S: BosStr> LexiconSchema for BodyExternal<S> {
    fn nsid() -> &'static str {
        "at.inlay.component"
    }
    fn def_name() -> &'static str {
        "bodyExternal"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_inlay_component()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for BodyTemplate<S> {
    fn nsid() -> &'static str {
        "at.inlay.component"
    }
    fn def_name() -> &'static str {
        "bodyTemplate"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_inlay_component()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

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

#[derive(Debug, Serialize, Deserialize)]
pub struct ComponentRecord;
impl XrpcResp for ComponentRecord {
    const NSID: &'static str = "at.inlay.component";
    const ENCODING: &'static str = "application/json";
    type Output<S: BosStr> = ComponentGetRecordOutput<S>;
    type Err = RecordError;
}

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

impl<S: BosStr> Collection for Component<S> {
    const NSID: &'static str = "at.inlay.component";
    type Record = ComponentRecord;
}

impl Collection for ComponentRecord {
    const NSID: &'static str = "at.inlay.component";
    type Record = ComponentRecord;
}

impl<S: BosStr> LexiconSchema for Component<S> {
    fn nsid() -> &'static str {
        "at.inlay.component"
    }
    fn def_name() -> &'static str {
        "main"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_inlay_component()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.description {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 10000usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("description"),
                    max: 10000usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        if let Some(ref value) = self.description {
            {
                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
                if count > 1000usize {
                    return Err(ConstraintError::MaxGraphemes {
                        path: ValidationPath::from_field("description"),
                        max: 1000usize,
                        actual: count,
                    });
                }
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for View<S> {
    fn nsid() -> &'static str {
        "at.inlay.component"
    }
    fn def_name() -> &'static str {
        "view"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_inlay_component()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.accepts;
            #[allow(unused_comparisons)]
            if value.len() < 1usize {
                return Err(ConstraintError::MinLength {
                    path: ValidationPath::from_field("accepts"),
                    min: 1usize,
                    actual: value.len(),
                });
            }
        }
        {
            let value = &self.prop;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 256usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("prop"),
                    max: 256usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for ViewPrimitive<S> {
    fn nsid() -> &'static str {
        "at.inlay.component"
    }
    fn def_name() -> &'static str {
        "viewPrimitive"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_inlay_component()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.format {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 64usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("format"),
                    max: 64usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.r#type;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 128usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("type"),
                    max: 128usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for ViewRecord<S> {
    fn nsid() -> &'static str {
        "at.inlay.component"
    }
    fn def_name() -> &'static str {
        "viewRecord"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_at_inlay_component()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.rkey {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 512usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("rkey"),
                    max: 512usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod body_external_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 Did;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Did = Unset;
    }
    ///State transition - sets the `did` field to Set
    pub struct SetDid<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetDid<St> {}
    impl<St: State> State for SetDid<St> {
        type Did = Set<members::did>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `did` field
        pub struct did(());
    }
}

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

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

impl<S: BosStr> BodyExternal<S> {
    /// Create a new builder for this type
    pub fn builder() -> BodyExternalBuilder<body_external_state::Empty, S> {
        BodyExternalBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> BodyExternalBuilder<St, S>
where
    St: body_external_state::State,
    St::Did: body_external_state::IsUnset,
{
    /// Set the `did` field (required)
    pub fn did(
        mut self,
        value: impl Into<Did<S>>,
    ) -> BodyExternalBuilder<body_external_state::SetDid<St>, S> {
        self._fields.0 = Option::Some(value.into());
        BodyExternalBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> BodyExternalBuilder<St, S>
where
    St: body_external_state::State,
    St::Did: body_external_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> BodyExternal<S> {
        BodyExternal {
            did: self._fields.0.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>>,
    ) -> BodyExternal<S> {
        BodyExternal {
            did: self._fields.0.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_at_inlay_component() -> 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("at.inlay.component"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("bodyExternal"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Component rendered by calling a remote XRPC endpoint",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("did")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("did"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "DID of the service hosting this component",
                                    ),
                                ),
                                format: Some(LexStringFormat::Did),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("bodyTemplate"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Component rendered by the host from a serialized element tree",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("node")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("node"),
                            LexObjectProperty::Unknown(LexUnknown {
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::Record(LexRecord {
                    description: Some(
                        CowStr::new_static(
                            "Component record - declares an implementation of a type",
                        ),
                    ),
                    key: Some(CowStr::new_static("tid")),
                    record: LexRecordRecord::Object(LexObject {
                        required: Some(vec![SmolStr::new_static("type")]),
                        properties: {
                            #[allow(unused_mut)]
                            let mut map = BTreeMap::new();
                            map.insert(
                                SmolStr::new_static("body"),
                                LexObjectProperty::Union(LexRefUnion {
                                    description: Some(
                                        CowStr::new_static(
                                            "How this component is rendered. Omit for primitives rendered by the host.",
                                        ),
                                    ),
                                    refs: vec![
                                        CowStr::new_static("#bodyExternal"),
                                        CowStr::new_static("#bodyTemplate")
                                    ],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("createdAt"),
                                LexObjectProperty::String(LexString {
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("description"),
                                LexObjectProperty::String(LexString {
                                    max_length: Some(10000usize),
                                    max_graphemes: Some(1000usize),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("imports"),
                                LexObjectProperty::Array(LexArray {
                                    description: Some(
                                        CowStr::new_static(
                                            "Ordered list of pack URIs (import stack). First pack that exports an NSID wins.",
                                        ),
                                    ),
                                    items: LexArrayItem::String(LexString {
                                        format: Some(LexStringFormat::AtUri),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("type"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "NSID this component implements (also the XRPC procedure)",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Nsid),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("updatedAt"),
                                LexObjectProperty::String(LexString {
                                    description: Some(
                                        CowStr::new_static(
                                            "Last update timestamp. Set by the publish flow to bust cached responses.",
                                        ),
                                    ),
                                    format: Some(LexStringFormat::Datetime),
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("via"),
                                LexObjectProperty::Union(LexRefUnion {
                                    description: Some(
                                        CowStr::new_static("Platform-managed deployment metadata"),
                                    ),
                                    refs: vec![CowStr::new_static("at.inlay.defs#viaValtown")],
                                    ..Default::default()
                                }),
                            );
                            map.insert(
                                SmolStr::new_static("view"),
                                LexObjectProperty::Ref(LexRef {
                                    r#ref: CowStr::new_static("#view"),
                                    ..Default::default()
                                }),
                            );
                            map
                        },
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("view"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "Declares what data this component views and which prop receives it.",
                        ),
                    ),
                    required: Some(
                        vec![SmolStr::new_static("prop"), SmolStr::new_static("accepts")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("accepts"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static("Data types this view accepts."),
                                ),
                                items: LexArrayItem::Union(LexRefUnion {
                                    refs: vec![
                                        CowStr::new_static("#viewRecord"),
                                        CowStr::new_static("#viewPrimitive")
                                    ],
                                    ..Default::default()
                                }),
                                min_length: Some(1usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("prop"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Which component prop receives the view data.",
                                    ),
                                ),
                                max_length: Some(256usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("viewPrimitive"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("View accepts a primitive value type."),
                    ),
                    required: Some(vec![SmolStr::new_static("type")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("format"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "String format constraint. Only applies when type is 'string'.",
                                    ),
                                ),
                                max_length: Some(64usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("type"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Lexicon primitive type."),
                                ),
                                max_length: Some(128usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("viewRecord"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "View accepts individual records of a collection. Omit collection for a generic record view. When rkey is present, the component accepts bare DIDs (expanded to full AT URIs) and appears on identity pages.",
                        ),
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("collection"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "The collection this component views. Omit for any-collection.",
                                    ),
                                ),
                                format: Some(LexStringFormat::Nsid),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("rkey"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "The record key, baked from the collection's lexicon at authoring time. Presence enables DID expansion and identity page routing.",
                                    ),
                                ),
                                max_length: Some(512usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

pub mod body_template_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 Node;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Node = Unset;
    }
    ///State transition - sets the `node` field to Set
    pub struct SetNode<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetNode<St> {}
    impl<St: State> State for SetNode<St> {
        type Node = Set<members::node>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `node` field
        pub struct node(());
    }
}

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

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

impl<S: BosStr> BodyTemplate<S> {
    /// Create a new builder for this type
    pub fn builder() -> BodyTemplateBuilder<body_template_state::Empty, S> {
        BodyTemplateBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> BodyTemplateBuilder<St, S>
where
    St: body_template_state::State,
    St::Node: body_template_state::IsUnset,
{
    /// Set the `node` field (required)
    pub fn node(
        mut self,
        value: impl Into<Data<S>>,
    ) -> BodyTemplateBuilder<body_template_state::SetNode<St>, S> {
        self._fields.0 = Option::Some(value.into());
        BodyTemplateBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> BodyTemplateBuilder<St, S>
where
    St: body_template_state::State,
    St::Node: body_template_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> BodyTemplate<S> {
        BodyTemplate {
            node: self._fields.0.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>>,
    ) -> BodyTemplate<S> {
        BodyTemplate {
            node: self._fields.0.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

pub mod component_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 Type;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Type = Unset;
    }
    ///State transition - sets the `type` field to Set
    pub struct SetType<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetType<St> {}
    impl<St: State> State for SetType<St> {
        type Type = Set<members::r#type>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `type` field
        pub struct r#type(());
    }
}

/// Builder for constructing an instance of this type.
pub struct ComponentBuilder<St: component_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<ComponentBody<S>>,
        Option<Datetime>,
        Option<S>,
        Option<Vec<AtUri<S>>>,
        Option<Nsid<S>>,
        Option<Datetime>,
        Option<ViaValtown<S>>,
        Option<component::View<S>>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Component<S> {
    /// Create a new builder for this type
    pub fn builder() -> ComponentBuilder<component_state::Empty, S> {
        ComponentBuilder::builder()
    }
}

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

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

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

impl<St: component_state::State, S: BosStr> ComponentBuilder<St, S> {
    /// Set the `createdAt` field (optional)
    pub fn created_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `createdAt` field to an Option value (optional)
    pub fn maybe_created_at(mut self, value: Option<Datetime>) -> Self {
        self._fields.1 = value;
        self
    }
}

impl<St: component_state::State, S: BosStr> ComponentBuilder<St, S> {
    /// Set the `description` field (optional)
    pub fn description(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.2 = value.into();
        self
    }
    /// Set the `description` field to an Option value (optional)
    pub fn maybe_description(mut self, value: Option<S>) -> Self {
        self._fields.2 = value;
        self
    }
}

impl<St: component_state::State, S: BosStr> ComponentBuilder<St, S> {
    /// Set the `imports` field (optional)
    pub fn imports(mut self, value: impl Into<Option<Vec<AtUri<S>>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `imports` field to an Option value (optional)
    pub fn maybe_imports(mut self, value: Option<Vec<AtUri<S>>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St, S: BosStr> ComponentBuilder<St, S>
where
    St: component_state::State,
    St::Type: component_state::IsUnset,
{
    /// Set the `type` field (required)
    pub fn r#type(
        mut self,
        value: impl Into<Nsid<S>>,
    ) -> ComponentBuilder<component_state::SetType<St>, S> {
        self._fields.4 = Option::Some(value.into());
        ComponentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: component_state::State, S: BosStr> ComponentBuilder<St, S> {
    /// Set the `updatedAt` field (optional)
    pub fn updated_at(mut self, value: impl Into<Option<Datetime>>) -> Self {
        self._fields.5 = 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.5 = value;
        self
    }
}

impl<St: component_state::State, S: BosStr> ComponentBuilder<St, S> {
    /// Set the `via` field (optional)
    pub fn via(mut self, value: impl Into<Option<ViaValtown<S>>>) -> Self {
        self._fields.6 = value.into();
        self
    }
    /// Set the `via` field to an Option value (optional)
    pub fn maybe_via(mut self, value: Option<ViaValtown<S>>) -> Self {
        self._fields.6 = value;
        self
    }
}

impl<St: component_state::State, S: BosStr> ComponentBuilder<St, S> {
    /// Set the `view` field (optional)
    pub fn view(mut self, value: impl Into<Option<component::View<S>>>) -> Self {
        self._fields.7 = value.into();
        self
    }
    /// Set the `view` field to an Option value (optional)
    pub fn maybe_view(mut self, value: Option<component::View<S>>) -> Self {
        self._fields.7 = value;
        self
    }
}

impl<St, S: BosStr> ComponentBuilder<St, S>
where
    St: component_state::State,
    St::Type: component_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Component<S> {
        Component {
            body: self._fields.0,
            created_at: self._fields.1,
            description: self._fields.2,
            imports: self._fields.3,
            r#type: self._fields.4.unwrap(),
            updated_at: self._fields.5,
            via: self._fields.6,
            view: self._fields.7,
            extra_data: Default::default(),
        }
    }
    /// Build the final struct with custom extra_data.
    pub fn build_with_data(
        self,
        extra_data: BTreeMap<SmolStr, Data<S>>,
    ) -> Component<S> {
        Component {
            body: self._fields.0,
            created_at: self._fields.1,
            description: self._fields.2,
            imports: self._fields.3,
            r#type: self._fields.4.unwrap(),
            updated_at: self._fields.5,
            via: self._fields.6,
            view: self._fields.7,
            extra_data: Some(extra_data),
        }
    }
}

pub mod view_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 Accepts;
        type Prop;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Accepts = Unset;
        type Prop = Unset;
    }
    ///State transition - sets the `accepts` field to Set
    pub struct SetAccepts<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetAccepts<St> {}
    impl<St: State> State for SetAccepts<St> {
        type Accepts = Set<members::accepts>;
        type Prop = St::Prop;
    }
    ///State transition - sets the `prop` field to Set
    pub struct SetProp<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetProp<St> {}
    impl<St: State> State for SetProp<St> {
        type Accepts = St::Accepts;
        type Prop = Set<members::prop>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `accepts` field
        pub struct accepts(());
        ///Marker type for the `prop` field
        pub struct prop(());
    }
}

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

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

impl<S: BosStr> View<S> {
    /// Create a new builder for this type
    pub fn builder() -> ViewBuilder<view_state::Empty, S> {
        ViewBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> ViewBuilder<St, S>
where
    St: view_state::State,
    St::Accepts: view_state::IsUnset,
{
    /// Set the `accepts` field (required)
    pub fn accepts(
        mut self,
        value: impl Into<Vec<ViewAcceptsItem<S>>>,
    ) -> ViewBuilder<view_state::SetAccepts<St>, S> {
        self._fields.0 = Option::Some(value.into());
        ViewBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ViewBuilder<St, S>
where
    St: view_state::State,
    St::Prop: view_state::IsUnset,
{
    /// Set the `prop` field (required)
    pub fn prop(
        mut self,
        value: impl Into<S>,
    ) -> ViewBuilder<view_state::SetProp<St>, S> {
        self._fields.1 = Option::Some(value.into());
        ViewBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> ViewBuilder<St, S>
where
    St: view_state::State,
    St::Accepts: view_state::IsSet,
    St::Prop: view_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> View<S> {
        View {
            accepts: self._fields.0.unwrap(),
            prop: 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>>) -> View<S> {
        View {
            accepts: self._fields.0.unwrap(),
            prop: self._fields.1.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}