// @generated by jacquard-lexicon. DO NOT EDIT.
//
// Lexicon: zone.stratos.sync.subscribeRecords
//
// 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::cid::CidLink;
use jacquard_common::types::string::{Did, Tid, Datetime, UriValue};
use jacquard_common::types::value::Data;
use jacquard_derive::{IntoStatic, 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::zone_stratos::sync::subscribe_records;
/// A commit event containing record operations.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Commit<S: BosStr = DefaultStr> {
    ///The DID of the account.
    pub did: Did<S>,
    ///List of record operations in this commit.
    pub ops: Vec<subscribe_records::RecordOp<S>>,
    ///The repo revision.
    pub rev: Tid,
    ///The sequence number of this event.
    pub seq: i64,
    ///Timestamp of when the event was sequenced.
    pub time: Datetime,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// An enrollment event indicating a user has enrolled or unenrolled from the service.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Enrollment<S: BosStr = DefaultStr> {
    ///The enrollment action.
    pub action: EnrollmentAction<S>,
    ///The boundaries assigned to the user.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub boundaries: Option<Vec<S>>,
    ///The DID of the user.
    pub did: Did<S>,
    ///The Stratos service endpoint URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service: Option<UriValue<S>>,
    ///Timestamp of the enrollment event.
    pub time: Datetime,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// The enrollment action.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum EnrollmentAction<S: BosStr = DefaultStr> {
    Enroll,
    Unenroll,
    Other(S),
}

impl<S: BosStr> EnrollmentAction<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Enroll => "enroll",
            Self::Unenroll => "unenroll",
            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() {
            "enroll" => Self::Enroll,
            "unenroll" => Self::Unenroll,
            _ => Self::Other(s),
        }
    }
}

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

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

impl<S: BosStr> Serialize for EnrollmentAction<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 EnrollmentAction<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 EnrollmentAction<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for EnrollmentAction<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = EnrollmentAction<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            EnrollmentAction::Enroll => EnrollmentAction::Enroll,
            EnrollmentAction::Unenroll => EnrollmentAction::Unenroll,
            EnrollmentAction::Other(v) => EnrollmentAction::Other(v.into_static()),
        }
    }
}

/// An informational message about the subscription state.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct Info<S: BosStr = DefaultStr> {
    ///Additional details about the info message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<S>,
    ///The type of info message.
    pub name: InfoName<S>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// The type of info message.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum InfoName<S: BosStr = DefaultStr> {
    OutdatedCursor,
    Other(S),
}

impl<S: BosStr> InfoName<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::OutdatedCursor => "OutdatedCursor",
            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() {
            "OutdatedCursor" => Self::OutdatedCursor,
            _ => Self::Other(s),
        }
    }
}

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

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

impl<S: BosStr> Serialize for InfoName<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 InfoName<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 InfoName<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for InfoName<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = InfoName<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            InfoName::OutdatedCursor => InfoName::OutdatedCursor,
            InfoName::Other(v) => InfoName::Other(v.into_static()),
        }
    }
}


#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct SubscribeRecords<S: BosStr = DefaultStr> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub did: Option<Did<S>>,
    /// (max length: 253)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub domain: Option<S>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sync_token: Option<S>,
}


#[open_union]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
#[serde(tag = "$type", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub enum SubscribeRecordsMessage<S: BosStr = DefaultStr> {
    #[serde(rename = "#commit")]
    Commit(Box<subscribe_records::Commit<S>>),
    #[serde(rename = "#enrollment")]
    Enrollment(Box<subscribe_records::Enrollment<S>>),
    #[serde(rename = "#info")]
    Info(Box<subscribe_records::Info<S>>),
}

impl<S: BosStr> SubscribeRecordsMessage<S> {
    /// Decode a framed DAG-CBOR message (header + body).
    pub fn decode_framed<'de>(
        bytes: &'de [u8],
    ) -> Result<SubscribeRecordsMessage<S>, jacquard_common::error::DecodeError>
    where
        S: serde::Deserialize<'de>,
    {
        let (header, body) = jacquard_common::xrpc::subscription::parse_event_header(
            bytes,
        )?;
        match header.t.as_str() {
            "#commit" => {
                let variant = jacquard_common::deps::codegen::serde_ipld_dagcbor::from_slice(
                    body,
                )?;
                Ok(Self::Commit(Box::new(variant)))
            }
            "#enrollment" => {
                let variant = jacquard_common::deps::codegen::serde_ipld_dagcbor::from_slice(
                    body,
                )?;
                Ok(Self::Enrollment(Box::new(variant)))
            }
            "#info" => {
                let variant = jacquard_common::deps::codegen::serde_ipld_dagcbor::from_slice(
                    body,
                )?;
                Ok(Self::Info(Box::new(variant)))
            }
            unknown => {
                Err(
                    jacquard_common::error::DecodeError::UnknownEventType(unknown.into()),
                )
            }
        }
    }
}


#[derive(
    Serialize,
    Deserialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
    thiserror::Error,
    miette::Diagnostic
)]

#[serde(tag = "error", content = "message")]
pub enum SubscribeRecordsError {
    /// Cursor is in the future.
    #[serde(rename = "FutureCursor")]
    FutureCursor(Option<SmolStr>),
    /// Authentication is required.
    #[serde(rename = "AuthRequired")]
    AuthRequired(Option<SmolStr>),
    /// Catch-all for unknown error codes.
    #[serde(untagged)]
    Other { error: SmolStr, message: Option<SmolStr> },
}

impl core::fmt::Display for SubscribeRecordsError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::FutureCursor(msg) => {
                write!(f, "FutureCursor")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::AuthRequired(msg) => {
                write!(f, "AuthRequired")?;
                if let Some(msg) = msg {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
            Self::Other { error, message } => {
                write!(f, "{}", error)?;
                if let Some(msg) = message {
                    write!(f, ": {}", msg)?;
                }
                Ok(())
            }
        }
    }
}

/// A single record operation within a commit.

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
#[serde(rename_all = "camelCase", bound(deserialize = "S: Deserialize<'de> + BosStr"))]
pub struct RecordOp<S: BosStr = DefaultStr> {
    ///The type of operation.
    pub action: RecordOpAction<S>,
    ///The CID of the record. Present for create and update operations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cid: Option<CidLink<S>>,
    ///The record path (collection/rkey).
    pub path: S,
    ///The record content. Present for create and update operations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub record: Option<Data<S>>,
    #[serde(flatten, default, skip_serializing_if = "Option::is_none")]
    pub extra_data: Option<BTreeMap<SmolStr, Data<S>>>,
}

/// The type of operation.

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum RecordOpAction<S: BosStr = DefaultStr> {
    Create,
    Update,
    Delete,
    Other(S),
}

impl<S: BosStr> RecordOpAction<S> {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Create => "create",
            Self::Update => "update",
            Self::Delete => "delete",
            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() {
            "create" => Self::Create,
            "update" => Self::Update,
            "delete" => Self::Delete,
            _ => Self::Other(s),
        }
    }
}

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

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

impl<S: BosStr> Serialize for RecordOpAction<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 RecordOpAction<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 RecordOpAction<S> {
    fn default() -> Self {
        Self::Other(Default::default())
    }
}

impl<S: BosStr> jacquard_common::IntoStatic for RecordOpAction<S>
where
    S: BosStr + jacquard_common::IntoStatic,
    S::Output: BosStr,
{
    type Output = RecordOpAction<S::Output>;
    fn into_static(self) -> Self::Output {
        match self {
            RecordOpAction::Create => RecordOpAction::Create,
            RecordOpAction::Update => RecordOpAction::Update,
            RecordOpAction::Delete => RecordOpAction::Delete,
            RecordOpAction::Other(v) => RecordOpAction::Other(v.into_static()),
        }
    }
}

impl<S: BosStr> LexiconSchema for Commit<S> {
    fn nsid() -> &'static str {
        "zone.stratos.sync.subscribeRecords"
    }
    fn def_name() -> &'static str {
        "commit"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_zone_stratos_sync_subscribeRecords()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for Enrollment<S> {
    fn nsid() -> &'static str {
        "zone.stratos.sync.subscribeRecords"
    }
    fn def_name() -> &'static str {
        "enrollment"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_zone_stratos_sync_subscribeRecords()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.action;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 32usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("action"),
                    max: 32usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

impl<S: BosStr> LexiconSchema for Info<S> {
    fn nsid() -> &'static str {
        "zone.stratos.sync.subscribeRecords"
    }
    fn def_name() -> &'static str {
        "info"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_zone_stratos_sync_subscribeRecords()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        if let Some(ref value) = self.message {
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 1024usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("message"),
                    max: 1024usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.name;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 128usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("name"),
                    max: 128usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

///Stream response type for
///zone.stratos.sync.subscribeRecords
pub struct SubscribeRecordsStream;
impl jacquard_common::xrpc::SubscriptionResp for SubscribeRecordsStream {
    const NSID: &'static str = "zone.stratos.sync.subscribeRecords";
    const ENCODING: jacquard_common::xrpc::MessageEncoding = jacquard_common::xrpc::MessageEncoding::Json;
    type Message<S: BosStr> = SubscribeRecordsMessage<S>;
    type Error = SubscribeRecordsError;
}

impl<S: BosStr> jacquard_common::xrpc::XrpcSubscription for SubscribeRecords<S> {
    const NSID: &'static str = "zone.stratos.sync.subscribeRecords";
    const ENCODING: jacquard_common::xrpc::MessageEncoding = jacquard_common::xrpc::MessageEncoding::Json;
    type Stream = SubscribeRecordsStream;
}

pub struct SubscribeRecordsEndpoint;
impl jacquard_common::xrpc::SubscriptionEndpoint for SubscribeRecordsEndpoint {
    const PATH: &'static str = "/xrpc/zone.stratos.sync.subscribeRecords";
    const ENCODING: jacquard_common::xrpc::MessageEncoding = jacquard_common::xrpc::MessageEncoding::Json;
    type Params<S: BosStr> = SubscribeRecords<S>;
    type Stream = SubscribeRecordsStream;
}

impl<S: BosStr> LexiconSchema for RecordOp<S> {
    fn nsid() -> &'static str {
        "zone.stratos.sync.subscribeRecords"
    }
    fn def_name() -> &'static str {
        "recordOp"
    }
    fn lexicon_doc() -> LexiconDoc<'static> {
        lexicon_doc_zone_stratos_sync_subscribeRecords()
    }
    fn validate(&self) -> Result<(), ConstraintError> {
        {
            let value = &self.action;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 32usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("action"),
                    max: 32usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        {
            let value = &self.path;
            #[allow(unused_comparisons)]
            if <str>::len(value.as_ref()) > 512usize {
                return Err(ConstraintError::MaxLength {
                    path: ValidationPath::from_field("path"),
                    max: 512usize,
                    actual: <str>::len(value.as_ref()),
                });
            }
        }
        Ok(())
    }
}

pub mod commit_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;
        type Ops;
        type Rev;
        type Seq;
        type Time;
    }
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {
        type Did = Unset;
        type Ops = Unset;
        type Rev = Unset;
        type Seq = Unset;
        type Time = 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>;
        type Ops = St::Ops;
        type Rev = St::Rev;
        type Seq = St::Seq;
        type Time = St::Time;
    }
    ///State transition - sets the `ops` field to Set
    pub struct SetOps<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetOps<St> {}
    impl<St: State> State for SetOps<St> {
        type Did = St::Did;
        type Ops = Set<members::ops>;
        type Rev = St::Rev;
        type Seq = St::Seq;
        type Time = St::Time;
    }
    ///State transition - sets the `rev` field to Set
    pub struct SetRev<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetRev<St> {}
    impl<St: State> State for SetRev<St> {
        type Did = St::Did;
        type Ops = St::Ops;
        type Rev = Set<members::rev>;
        type Seq = St::Seq;
        type Time = St::Time;
    }
    ///State transition - sets the `seq` field to Set
    pub struct SetSeq<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetSeq<St> {}
    impl<St: State> State for SetSeq<St> {
        type Did = St::Did;
        type Ops = St::Ops;
        type Rev = St::Rev;
        type Seq = Set<members::seq>;
        type Time = St::Time;
    }
    ///State transition - sets the `time` field to Set
    pub struct SetTime<St: State = Empty>(PhantomData<fn() -> St>);
    impl<St: State> sealed::Sealed for SetTime<St> {}
    impl<St: State> State for SetTime<St> {
        type Did = St::Did;
        type Ops = St::Ops;
        type Rev = St::Rev;
        type Seq = St::Seq;
        type Time = Set<members::time>;
    }
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {
        ///Marker type for the `did` field
        pub struct did(());
        ///Marker type for the `ops` field
        pub struct ops(());
        ///Marker type for the `rev` field
        pub struct rev(());
        ///Marker type for the `seq` field
        pub struct seq(());
        ///Marker type for the `time` field
        pub struct time(());
    }
}

/// Builder for constructing an instance of this type.
pub struct CommitBuilder<St: commit_state::State, S: BosStr = DefaultStr> {
    _state: PhantomData<fn() -> St>,
    _fields: (
        Option<Did<S>>,
        Option<Vec<subscribe_records::RecordOp<S>>>,
        Option<Tid>,
        Option<i64>,
        Option<Datetime>,
    ),
    _type: PhantomData<fn() -> S>,
}

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

impl<S: BosStr> Commit<S> {
    /// Create a new builder for this type
    pub fn builder() -> CommitBuilder<commit_state::Empty, S> {
        CommitBuilder::builder()
    }
}

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

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

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

impl<St, S: BosStr> CommitBuilder<St, S>
where
    St: commit_state::State,
    St::Ops: commit_state::IsUnset,
{
    /// Set the `ops` field (required)
    pub fn ops(
        mut self,
        value: impl Into<Vec<subscribe_records::RecordOp<S>>>,
    ) -> CommitBuilder<commit_state::SetOps<St>, S> {
        self._fields.1 = Option::Some(value.into());
        CommitBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CommitBuilder<St, S>
where
    St: commit_state::State,
    St::Rev: commit_state::IsUnset,
{
    /// Set the `rev` field (required)
    pub fn rev(
        mut self,
        value: impl Into<Tid>,
    ) -> CommitBuilder<commit_state::SetRev<St>, S> {
        self._fields.2 = Option::Some(value.into());
        CommitBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CommitBuilder<St, S>
where
    St: commit_state::State,
    St::Seq: commit_state::IsUnset,
{
    /// Set the `seq` field (required)
    pub fn seq(
        mut self,
        value: impl Into<i64>,
    ) -> CommitBuilder<commit_state::SetSeq<St>, S> {
        self._fields.3 = Option::Some(value.into());
        CommitBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CommitBuilder<St, S>
where
    St: commit_state::State,
    St::Time: commit_state::IsUnset,
{
    /// Set the `time` field (required)
    pub fn time(
        mut self,
        value: impl Into<Datetime>,
    ) -> CommitBuilder<commit_state::SetTime<St>, S> {
        self._fields.4 = Option::Some(value.into());
        CommitBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> CommitBuilder<St, S>
where
    St: commit_state::State,
    St::Did: commit_state::IsSet,
    St::Ops: commit_state::IsSet,
    St::Rev: commit_state::IsSet,
    St::Seq: commit_state::IsSet,
    St::Time: commit_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Commit<S> {
        Commit {
            did: self._fields.0.unwrap(),
            ops: self._fields.1.unwrap(),
            rev: self._fields.2.unwrap(),
            seq: self._fields.3.unwrap(),
            time: self._fields.4.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>>) -> Commit<S> {
        Commit {
            did: self._fields.0.unwrap(),
            ops: self._fields.1.unwrap(),
            rev: self._fields.2.unwrap(),
            seq: self._fields.3.unwrap(),
            time: self._fields.4.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

fn lexicon_doc_zone_stratos_sync_subscribeRecords() -> 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("zone.stratos.sync.subscribeRecords"),
        defs: {
            let mut map = BTreeMap::new();
            map.insert(
                SmolStr::new_static("commit"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "A commit event containing record operations.",
                        ),
                    ),
                    required: Some(
                        vec![
                            SmolStr::new_static("seq"), SmolStr::new_static("did"),
                            SmolStr::new_static("time"), SmolStr::new_static("rev"),
                            SmolStr::new_static("ops")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("did"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The DID of the account."),
                                ),
                                format: Some(LexStringFormat::Did),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("ops"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static(
                                        "List of record operations in this commit.",
                                    ),
                                ),
                                items: LexArrayItem::Ref(LexRef {
                                    r#ref: CowStr::new_static("#recordOp"),
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("rev"),
                            LexObjectProperty::String(LexString {
                                description: Some(CowStr::new_static("The repo revision.")),
                                format: Some(LexStringFormat::Tid),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("seq"),
                            LexObjectProperty::Integer(LexInteger {
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("time"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Timestamp of when the event was sequenced.",
                                    ),
                                ),
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("enrollment"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "An enrollment event indicating a user has enrolled or unenrolled from the service.",
                        ),
                    ),
                    required: Some(
                        vec![
                            SmolStr::new_static("did"), SmolStr::new_static("action"),
                            SmolStr::new_static("time")
                        ],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("action"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The enrollment action."),
                                ),
                                max_length: Some(32usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("boundaries"),
                            LexObjectProperty::Array(LexArray {
                                description: Some(
                                    CowStr::new_static("The boundaries assigned to the user."),
                                ),
                                items: LexArrayItem::String(LexString {
                                    ..Default::default()
                                }),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("did"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The DID of the user."),
                                ),
                                format: Some(LexStringFormat::Did),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("service"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The Stratos service endpoint URL."),
                                ),
                                format: Some(LexStringFormat::Uri),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("time"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("Timestamp of the enrollment event."),
                                ),
                                format: Some(LexStringFormat::Datetime),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("info"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static(
                            "An informational message about the subscription state.",
                        ),
                    ),
                    required: Some(vec![SmolStr::new_static("name")]),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("message"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static(
                                        "Additional details about the info message.",
                                    ),
                                ),
                                max_length: Some(1024usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("name"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The type of info message."),
                                ),
                                max_length: Some(128usize),
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("main"),
                LexUserType::XrpcSubscription(LexXrpcSubscription {
                    parameters: Some(
                        LexXrpcSubscriptionParameter::Params(LexXrpcParameters {
                            properties: {
                                #[allow(unused_mut)]
                                let mut map = BTreeMap::new();
                                map.insert(
                                    SmolStr::new_static("cursor"),
                                    LexXrpcParametersProperty::Integer(LexInteger {
                                        ..Default::default()
                                    }),
                                );
                                map.insert(
                                    SmolStr::new_static("did"),
                                    LexXrpcParametersProperty::String(LexString {
                                        description: Some(
                                            CowStr::new_static(
                                                "The DID of the account to subscribe to. If omitted, subscribes to service-level enrollment events.",
                                            ),
                                        ),
                                        format: Some(LexStringFormat::Did),
                                        ..Default::default()
                                    }),
                                );
                                map.insert(
                                    SmolStr::new_static("domain"),
                                    LexXrpcParametersProperty::String(LexString {
                                        description: Some(
                                            CowStr::new_static(
                                                "Optional domain filter. Only events for records with this domain in their boundary will be emitted.",
                                            ),
                                        ),
                                        max_length: Some(253usize),
                                        ..Default::default()
                                    }),
                                );
                                map.insert(
                                    SmolStr::new_static("syncToken"),
                                    LexXrpcParametersProperty::String(LexString {
                                        description: Some(
                                            CowStr::new_static(
                                                "Signed service JWT for AppView authentication. Must include iss, aud, exp, and lxm claims. Required for service callers; owner callers may use the Authorization header instead.",
                                            ),
                                        ),
                                        ..Default::default()
                                    }),
                                );
                                map
                            },
                            ..Default::default()
                        }),
                    ),
                    ..Default::default()
                }),
            );
            map.insert(
                SmolStr::new_static("recordOp"),
                LexUserType::Object(LexObject {
                    description: Some(
                        CowStr::new_static("A single record operation within a commit."),
                    ),
                    required: Some(
                        vec![SmolStr::new_static("action"), SmolStr::new_static("path")],
                    ),
                    properties: {
                        #[allow(unused_mut)]
                        let mut map = BTreeMap::new();
                        map.insert(
                            SmolStr::new_static("action"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The type of operation."),
                                ),
                                max_length: Some(32usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("cid"),
                            LexObjectProperty::CidLink(LexCidLink {
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("path"),
                            LexObjectProperty::String(LexString {
                                description: Some(
                                    CowStr::new_static("The record path (collection/rkey)."),
                                ),
                                max_length: Some(512usize),
                                ..Default::default()
                            }),
                        );
                        map.insert(
                            SmolStr::new_static("record"),
                            LexObjectProperty::Unknown(LexUnknown {
                                ..Default::default()
                            }),
                        );
                        map
                    },
                    ..Default::default()
                }),
            );
            map
        },
        ..Default::default()
    }
}

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

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

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

impl<S: BosStr> Enrollment<S> {
    /// Create a new builder for this type
    pub fn builder() -> EnrollmentBuilder<enrollment_state::Empty, S> {
        EnrollmentBuilder::builder()
    }
}

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

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

impl<St, S: BosStr> EnrollmentBuilder<St, S>
where
    St: enrollment_state::State,
    St::Action: enrollment_state::IsUnset,
{
    /// Set the `action` field (required)
    pub fn action(
        mut self,
        value: impl Into<EnrollmentAction<S>>,
    ) -> EnrollmentBuilder<enrollment_state::SetAction<St>, S> {
        self._fields.0 = Option::Some(value.into());
        EnrollmentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St: enrollment_state::State, S: BosStr> EnrollmentBuilder<St, S> {
    /// Set the `boundaries` field (optional)
    pub fn boundaries(mut self, value: impl Into<Option<Vec<S>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `boundaries` field to an Option value (optional)
    pub fn maybe_boundaries(mut self, value: Option<Vec<S>>) -> Self {
        self._fields.1 = value;
        self
    }
}

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

impl<St: enrollment_state::State, S: BosStr> EnrollmentBuilder<St, S> {
    /// Set the `service` field (optional)
    pub fn service(mut self, value: impl Into<Option<UriValue<S>>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `service` field to an Option value (optional)
    pub fn maybe_service(mut self, value: Option<UriValue<S>>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St, S: BosStr> EnrollmentBuilder<St, S>
where
    St: enrollment_state::State,
    St::Time: enrollment_state::IsUnset,
{
    /// Set the `time` field (required)
    pub fn time(
        mut self,
        value: impl Into<Datetime>,
    ) -> EnrollmentBuilder<enrollment_state::SetTime<St>, S> {
        self._fields.4 = Option::Some(value.into());
        EnrollmentBuilder {
            _state: PhantomData,
            _fields: self._fields,
            _type: PhantomData,
        }
    }
}

impl<St, S: BosStr> EnrollmentBuilder<St, S>
where
    St: enrollment_state::State,
    St::Action: enrollment_state::IsSet,
    St::Did: enrollment_state::IsSet,
    St::Time: enrollment_state::IsSet,
{
    /// Build the final struct.
    pub fn build(self) -> Enrollment<S> {
        Enrollment {
            action: self._fields.0.unwrap(),
            boundaries: self._fields.1,
            did: self._fields.2.unwrap(),
            service: self._fields.3,
            time: self._fields.4.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>>,
    ) -> Enrollment<S> {
        Enrollment {
            action: self._fields.0.unwrap(),
            boundaries: self._fields.1,
            did: self._fields.2.unwrap(),
            service: self._fields.3,
            time: self._fields.4.unwrap(),
            extra_data: Some(extra_data),
        }
    }
}

pub mod subscribe_records_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 {}
    /// Empty state - all required fields are unset
    pub struct Empty(());
    impl sealed::Sealed for Empty {}
    impl State for Empty {}
    /// Marker types for field names
    #[allow(non_camel_case_types)]
    pub mod members {}
}

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

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

impl<S: BosStr> SubscribeRecords<S> {
    /// Create a new builder for this type
    pub fn builder() -> SubscribeRecordsBuilder<subscribe_records_state::Empty, S> {
        SubscribeRecordsBuilder::builder()
    }
}

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

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

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

impl<St: subscribe_records_state::State, S: BosStr> SubscribeRecordsBuilder<St, S> {
    /// Set the `did` field (optional)
    pub fn did(mut self, value: impl Into<Option<Did<S>>>) -> Self {
        self._fields.1 = value.into();
        self
    }
    /// Set the `did` field to an Option value (optional)
    pub fn maybe_did(mut self, value: Option<Did<S>>) -> Self {
        self._fields.1 = value;
        self
    }
}

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

impl<St: subscribe_records_state::State, S: BosStr> SubscribeRecordsBuilder<St, S> {
    /// Set the `syncToken` field (optional)
    pub fn sync_token(mut self, value: impl Into<Option<S>>) -> Self {
        self._fields.3 = value.into();
        self
    }
    /// Set the `syncToken` field to an Option value (optional)
    pub fn maybe_sync_token(mut self, value: Option<S>) -> Self {
        self._fields.3 = value;
        self
    }
}

impl<St, S: BosStr> SubscribeRecordsBuilder<St, S>
where
    St: subscribe_records_state::State,
{
    /// Build the final struct.
    pub fn build(self) -> SubscribeRecords<S> {
        SubscribeRecords {
            cursor: self._fields.0,
            did: self._fields.1,
            domain: self._fields.2,
            sync_token: self._fields.3,
        }
    }
}