mcapi 0.3.1

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation
//! Shared path encoding, serde helpers, and internal boilerplate macros.

#[cfg(any(feature = "curseforge", feature = "mojang"))]
use serde::{Deserialize, Deserializer};
#[cfg(any(feature = "curseforge", feature = "modrinth"))]
use serde::{Serialize, Serializer};
#[cfg(any(
    feature = "curseforge",
    feature = "mojang",
    feature = "yggdrasil",
    feature = "blessing"
))]
use url::Url;

#[cfg(any(
    feature = "mojang",
    feature = "modrinth",
    feature = "curseforge",
    feature = "yggdrasil",
    feature = "blessing",
    feature = "loaders",
    feature = "bmclapi",
    feature = "java"
))]
use crate::{Error, Result};

/// Percent-encodes a single URL path segment according to RFC 3986 §3.3.
///
/// Rejects empty strings, dot segments (`.` / `..`), slashes (`/` / `\`), and NUL bytes
/// so callers cannot inject extra path segments or query/fragment delimiters.
#[cfg(any(
    feature = "mojang",
    feature = "modrinth",
    feature = "curseforge",
    feature = "blessing",
    feature = "loaders",
    feature = "bmclapi",
    feature = "java"
))]
pub(crate) fn encode_path_segment(segment: &str) -> Result<String> {
    if segment.is_empty()
        || segment == "."
        || segment == ".."
        || segment.contains(['/', '\\', '\0'])
    {
        return Err(Error::InvalidInput(format!(
            "invalid URL path segment: {segment:?}"
        )));
    }

    let mut out = String::with_capacity(segment.len());
    for byte in segment.bytes() {
        let is_unreserved =
            byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~');
        if is_unreserved {
            out.push(byte as char);
        } else {
            out.push('%');
            out.push(hex_upper(byte >> 4));
            out.push(hex_upper(byte & 0x0F));
        }
    }
    Ok(out)
}

#[cfg(any(
    feature = "mojang",
    feature = "modrinth",
    feature = "curseforge",
    feature = "blessing",
    feature = "loaders",
    feature = "bmclapi",
    feature = "java"
))]
#[inline]
fn hex_upper(nibble: u8) -> char {
    match nibble {
        0..=9 => (b'0' + nibble) as char,
        10..=15 => (b'A' + (nibble - 10)) as char,
        _ => unreachable!(),
    }
}

/// Strips any trailing `'/'` characters from `url` in place without extra allocation.
#[cfg(any(
    feature = "mojang",
    feature = "modrinth",
    feature = "curseforge",
    feature = "yggdrasil-authlib",
    feature = "blessing",
    feature = "loaders",
    feature = "bmclapi",
    feature = "java"
))]
pub(crate) fn trim_trailing_slash(url: impl Into<String>) -> String {
    let mut s = url.into();
    while s.ends_with('/') {
        s.pop();
    }
    s
}

/// Validates that `raw` parses as an `http://` or `https://` URL with a host.
#[cfg(any(feature = "yggdrasil", feature = "blessing"))]
pub(crate) fn validate_http_url(raw: &str) -> Result<Url> {
    let parsed = Url::parse(raw.trim())?;
    if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
        return Err(Error::InvalidInput(format!(
            "URL must use http:// or https:// with a host: {raw:?}"
        )));
    }
    Ok(parsed)
}

/// Deserializes an optional [`Url`], treating `null` and empty/whitespace-only strings
/// as `None`. Non-empty malformed URL strings fail deserialization.
#[cfg(any(feature = "curseforge", feature = "mojang"))]
pub(crate) fn deserialize_optional_url<'de, D>(
    deserializer: D,
) -> std::result::Result<Option<Url>, D::Error>
where
    D: Deserializer<'de>,
{
    let raw = Option::<String>::deserialize(deserializer)?;
    match raw {
        None => Ok(None),
        Some(s) => {
            let trimmed = s.trim();
            if trimmed.is_empty() {
                Ok(None)
            } else {
                Url::parse(trimmed)
                    .map(Some)
                    .map_err(serde::de::Error::custom)
            }
        }
    }
}

/// Serializes an `Option<T>` as a compact JSON string when `Some` (for query parameters
/// such as Modrinth `loaders`/`game_versions` or CurseForge `categoryIds`/`modLoaderTypes`).
#[cfg(any(feature = "curseforge", feature = "modrinth"))]
pub(crate) fn serialize_option_json<T: Serialize, S: Serializer>(
    value: &Option<T>,
    serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
    match value {
        Some(v) => {
            let encoded = serde_json::to_string(v).map_err(serde::ser::Error::custom)?;
            serializer.serialize_str(&encoded)
        }
        None => serializer.serialize_none(),
    }
}

/// Declares a module-local zero-cost `Authed<'a>` view struct for `$client`.
#[cfg(any(
    feature = "mojang",
    feature = "modrinth",
    feature = "yggdrasil",
    feature = "blessing"
))]
macro_rules! define_authed {
    ($client:ty) => {
        /// Borrowed authenticated view over a client bound to a credential token.
        #[derive(Clone, Copy)]
        pub struct Authed<'a> {
            pub(crate) client: &'a $client,
            pub(crate) token: &'a str,
        }

        impl<'a> std::fmt::Debug for Authed<'a> {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_struct("Authed")
                    .field("client", &self.client)
                    .field("token", &"[REDACTED]")
                    .finish()
            }
        }

        impl<'a> Authed<'a> {
            /// Creates an authenticated view bound to `client` and a credential `token`.
            #[must_use]
            pub const fn new(client: &'a $client, token: &'a str) -> Self {
                Self { client, token }
            }

            /// Returns a reference to the underlying client.
            #[must_use]
            pub const fn client(&self) -> &'a $client {
                self.client
            }

            /// Returns the credential token bound to this view.
            #[must_use]
            pub const fn token(&self) -> &'a str {
                self.token
            }
        }
    };
}

#[cfg(any(
    feature = "mojang",
    feature = "modrinth",
    feature = "yggdrasil",
    feature = "blessing"
))]
pub(crate) use define_authed;

/// Implements `std::fmt::Debug` for a struct while replacing sensitive fields with `"[REDACTED]"`.
#[cfg(any(
    feature = "curseforge",
    feature = "mojang",
    feature = "yggdrasil",
    feature = "blessing"
))]
macro_rules! impl_redacted_debug {
    (
        $ty:ident {
            $($field:ident),* $(,)?;
            redacted: $($secret:ident),* $(,)?
            $(; optional_redacted: $($opt_secret:ident),* $(,)?)?
        }
    ) => {
        impl std::fmt::Debug for $ty {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                let mut ds = f.debug_struct(stringify!($ty));
                $(ds.field(stringify!($field), &self.$field);)*
                $(ds.field(stringify!($secret), &"[REDACTED]");)*
                $($(
                    ds.field(
                        stringify!($opt_secret),
                        &self.$opt_secret.as_ref().map(|_| "[REDACTED]"),
                    );
                )*)?
                ds.finish()
            }
        }
    };
}

#[cfg(any(
    feature = "curseforge",
    feature = "mojang",
    feature = "yggdrasil",
    feature = "blessing"
))]
pub(crate) use impl_redacted_debug;

#[cfg(all(
    test,
    any(
        feature = "mojang",
        feature = "modrinth",
        feature = "curseforge",
        feature = "blessing",
        feature = "loaders",
        feature = "bmclapi",
        feature = "java"
    )
))]
mod tests {
    use super::encode_path_segment;

    #[test]
    fn encode_path_segment_validates_and_percent_encodes() {
        assert_eq!(
            encode_path_segment("1.0.0+fabric").unwrap(),
            "1.0.0%2Bfabric"
        );
        assert_eq!(
            encode_path_segment("史蒂夫").unwrap(),
            "%E5%8F%B2%E8%92%82%E5%A4%AB"
        );
        assert!(encode_path_segment("../etc").is_err());
        assert!(encode_path_segment("..").is_err());
        assert!(encode_path_segment("").is_err());
    }
}