quilldown 1.5.0

Convert GitHub-Flavored Markdown into high-fidelity Word .docx documents.
Documentation
// <auto-generated by typra-emitter>
// Code generated by Typra emitter; DO NOT EDIT.

#![allow(
    unused_imports,
    dead_code,
    non_camel_case_types,
    unused_variables,
    unexpected_cfgs,
    clippy::all
)]

use super::context::{LoadContext, SaveContext};

use super::content_type_declaration::ContentTypeDeclaration;

use super::document_metadata::DocumentMetadata;

use super::package_part::PackagePart;

use super::package_relationship_set::PackageRelationshipSet;

#[derive(Debug, Clone, Default, PartialEq)]
pub struct OfficePackageManifest {
    pub kind: String,
    pub parts: Vec<PackagePart>,
    pub relationships: Vec<PackageRelationshipSet>,
    pub content_types: Vec<ContentTypeDeclaration>,
    pub core_properties: Option<DocumentMetadata>,
}

impl OfficePackageManifest {
    /// Create a new OfficePackageManifest with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Load OfficePackageManifest from a JSON string.
    pub fn from_json(json: &str, ctx: &LoadContext) -> Result<Self, serde_json::Error> {
        let value: serde_json::Value = serde_json::from_str(json)?;
        Self::validate_input_at(&value, "")
            .map_err(|message| <serde_json::Error as serde::de::Error>::custom(message))?;
        Ok(Self::load_from_value(&value, ctx))
    }

    /// Load OfficePackageManifest from a YAML string.
    pub fn from_yaml(yaml: &str, ctx: &LoadContext) -> Result<Self, serde_yaml::Error> {
        let value: serde_json::Value = serde_yaml::from_str(yaml)?;
        Self::validate_input_at(&value, "")
            .map_err(|message| <serde_yaml::Error as serde::de::Error>::custom(message))?;
        Ok(Self::load_from_value(&value, ctx))
    }

    /// Load OfficePackageManifest from an already-parsed JSON value, returning an error
    /// instead of panicking on invalid input. Fallible companion to
    /// `load_from_value` with the same validation policy as `from_json`.
    pub fn try_load_from_value(
        value: &serde_json::Value,
        ctx: &LoadContext,
    ) -> Result<Self, serde_json::Error> {
        Self::validate_input_at(value, "")
            .map_err(|message| <serde_json::Error as serde::de::Error>::custom(message))?;
        Ok(Self::load_from_value(value, ctx))
    }

    /// Load OfficePackageManifest from a `serde_json::Value`.
    ///
    /// Calls `ctx.process_input` before field extraction.
    pub fn load_from_value(value: &serde_json::Value, ctx: &LoadContext) -> Self {
        let value = ctx.process_input(value.clone());
        if let Err(message) = Self::validate_input_at(&value, "") {
            panic!("{}", message);
        }
        Self {
            kind: value
                .get("kind")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string(),
            parts: value
                .get("parts")
                .map(|v| Self::load_parts(v, ctx))
                .unwrap_or_default(),
            relationships: value
                .get("relationships")
                .map(|v| Self::load_relationships(v, ctx))
                .unwrap_or_default(),
            content_types: value
                .get("contentTypes")
                .map(|v| Self::load_content_types(v, ctx))
                .unwrap_or_default(),
            core_properties: value
                .get("coreProperties")
                .filter(|v| v.is_object() || v.is_array() || v.is_string())
                .map(|v| DocumentMetadata::load_from_value(v, ctx)),
        }
    }

    pub(crate) fn validate_input_at(value: &serde_json::Value, path: &str) -> Result<(), String> {
        if let Some(entries) = value
            .get("parts")
            .and_then(|candidate| candidate.as_array())
        {
            let collection_path = if path.is_empty() {
                "parts".to_string()
            } else {
                format!("{}.parts", path)
            };
            for (index, entry) in entries.iter().enumerate() {
                let entry_path = format!("{}[{}]", collection_path, index);
                PackagePart::validate_input_at(entry, &entry_path)?;
            }
        }
        if let Some(entries) = value
            .get("relationships")
            .and_then(|candidate| candidate.as_array())
        {
            let collection_path = if path.is_empty() {
                "relationships".to_string()
            } else {
                format!("{}.relationships", path)
            };
            for (index, entry) in entries.iter().enumerate() {
                let entry_path = format!("{}[{}]", collection_path, index);
                PackageRelationshipSet::validate_input_at(entry, &entry_path)?;
            }
        }
        if let Some(entries) = value
            .get("contentTypes")
            .and_then(|candidate| candidate.as_array())
        {
            let collection_path = if path.is_empty() {
                "contentTypes".to_string()
            } else {
                format!("{}.contentTypes", path)
            };
            for (index, entry) in entries.iter().enumerate() {
                let entry_path = format!("{}[{}]", collection_path, index);
                ContentTypeDeclaration::validate_input_at(entry, &entry_path)?;
            }
        }
        let child_path = if path.is_empty() {
            "coreProperties".to_string()
        } else {
            format!("{}.coreProperties", path)
        };
        if let Some(child) = value.get("coreProperties") {
            DocumentMetadata::validate_input_at(child, &child_path)?;
        }
        Ok(())
    }

    /// Serialize OfficePackageManifest to a `serde_json::Value`.
    ///
    /// Calls `ctx.process_dict` after serialization.
    pub fn to_value(&self, ctx: &SaveContext) -> serde_json::Value {
        let mut result = serde_json::Map::new();
        // Write base fields
        result.insert(
            "kind".to_string(),
            serde_json::Value::String(self.kind.clone()),
        );
        result.insert("parts".to_string(), Self::save_parts(&self.parts, ctx));
        result.insert(
            "relationships".to_string(),
            Self::save_relationships(&self.relationships, ctx),
        );
        result.insert(
            "contentTypes".to_string(),
            Self::save_content_types(&self.content_types, ctx),
        );
        if let Some(val) = self.core_properties.as_ref() {
            let nested = val.to_value(ctx);
            if !nested.is_null() {
                result.insert("coreProperties".to_string(), nested);
            }
        }
        ctx.process_dict(serde_json::Value::Object(result))
    }

    /// Serialize OfficePackageManifest to a JSON string.
    pub fn to_json(&self, ctx: &SaveContext) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(&self.to_value(ctx))
    }

    /// Serialize OfficePackageManifest to a YAML string.
    pub fn to_yaml(&self, ctx: &SaveContext) -> Result<String, serde_yaml::Error> {
        serde_yaml::to_string(&self.to_value(ctx))
    }

    /// Load a collection of PackagePart from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_parts(data: &serde_json::Value, ctx: &LoadContext) -> Vec<PackagePart> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| PackagePart::load_from_value(v, ctx))
                .collect(),

            _ => Vec::new(),
        }
    }

    /// Save a collection of PackagePart to a JSON value.
    fn save_parts(items: &[PackagePart], ctx: &SaveContext) -> serde_json::Value {
        serde_json::Value::Array(
            items
                .iter()
                .map(|item| item.to_value(ctx))
                .collect::<Vec<_>>(),
        )
    }

    /// Load a collection of PackageRelationshipSet from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_relationships(
        data: &serde_json::Value,
        ctx: &LoadContext,
    ) -> Vec<PackageRelationshipSet> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| PackageRelationshipSet::load_from_value(v, ctx))
                .collect(),

            _ => Vec::new(),
        }
    }

    /// Save a collection of PackageRelationshipSet to a JSON value.
    fn save_relationships(
        items: &[PackageRelationshipSet],
        ctx: &SaveContext,
    ) -> serde_json::Value {
        serde_json::Value::Array(
            items
                .iter()
                .map(|item| item.to_value(ctx))
                .collect::<Vec<_>>(),
        )
    }

    /// Load a collection of ContentTypeDeclaration from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_content_types(
        data: &serde_json::Value,
        ctx: &LoadContext,
    ) -> Vec<ContentTypeDeclaration> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| ContentTypeDeclaration::load_from_value(v, ctx))
                .collect(),

            _ => Vec::new(),
        }
    }

    /// Save a collection of ContentTypeDeclaration to a JSON value.
    fn save_content_types(
        items: &[ContentTypeDeclaration],
        ctx: &SaveContext,
    ) -> serde_json::Value {
        serde_json::Value::Array(
            items
                .iter()
                .map(|item| item.to_value(ctx))
                .collect::<Vec<_>>(),
        )
    }
}

// Serde for `OfficePackageManifest` delegates to the canonical to_value/load_from_value
// logic so its serde wire form always equals the canonical to_value/load_from_value form. Uses a default (no-op) context — no ${env:}/${file:}
// resolution here — leaving the context-aware LoadContext/SaveContext API intact.
#[cfg(feature = "serde")]
impl serde::Serialize for OfficePackageManifest {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serde::Serialize::serialize(&self.to_value(&SaveContext::default()), serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for OfficePackageManifest {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
        Self::validate_input_at(&value, "").map_err(serde::de::Error::custom)?;
        Ok(Self::load_from_value(&value, &LoadContext::default()))
    }
}