mcapi 0.3.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation
//! Modrinth Labrinth v2 REST API client (public search/version/hash lookups
//! and authenticated reads, plus optional creator/team/user write APIs gated
//! behind `modrinth-write`).
//!
//! Reference spec: <https://docs.modrinth.com/api/>.

mod misc;
/// Data models for Modrinth search, projects, versions, tags, teams, users, and write requests.
pub mod models;
mod projects;
mod tags;
mod teams;
mod users;
mod version_files;
mod versions;

#[cfg(feature = "modrinth-write")]
use reqwest::header::CONTENT_TYPE;
use reqwest::header::{AUTHORIZATION, HeaderValue};
#[cfg(feature = "modrinth-write")]
use reqwest::multipart::{Form, Part};
use serde::Serialize;
use serde::de::DeserializeOwned;

#[cfg(feature = "modrinth-write")]
use self::models::UploadFile;
use crate::error::{Error, Result};
use crate::http::HttpClient;
use crate::util::{define_authed, encode_path_segment, trim_trailing_slash};

/// Default Modrinth Labrinth API base URL.
pub const DEFAULT_BASE_URL: &str = "https://api.modrinth.com";

/// Validates a Modrinth ID or slug (`^[\w!@$()`.+,"\-']{3,64}$`).
#[must_use]
pub fn is_valid_id_or_slug(value: &str) -> bool {
    let len = value.len();
    if !(3..=64).contains(&len) {
        return false;
    }
    value.bytes().all(|b| {
        b.is_ascii_alphanumeric()
            || matches!(
                b,
                b'_' | b'-' | b'!' | b'@' | b'$' | b'(' | b')' | b'.' | b'+' | b',' | b'"' | b'\''
            )
    })
}

/// Validates a 40-character hexadecimal SHA-1 hash string.
#[must_use]
pub fn is_valid_sha1(hash: &str) -> bool {
    hash.len() == 40 && hash.bytes().all(|b| b.is_ascii_hexdigit())
}

/// Validates a 128-character hexadecimal SHA-512 hash string.
#[must_use]
pub fn is_valid_sha512(hash: &str) -> bool {
    hash.len() == 128 && hash.bytes().all(|b| b.is_ascii_hexdigit())
}

pub(crate) fn check_id_or_slug(value: &str) -> Result<()> {
    if is_valid_id_or_slug(value) {
        Ok(())
    } else {
        Err(Error::InvalidInput(format!(
            "invalid Modrinth project/version/user ID or slug: {value}"
        )))
    }
}

pub(crate) fn encode_id_or_slug(value: &str) -> Result<String> {
    check_id_or_slug(value)?;
    encode_path_segment(value)
}

/// Async client for the Modrinth Labrinth v2 REST API.
///
/// Authenticated operations via [`ModrinthClient::authed`] always bypass [`crate::Mirror`]
/// rewriting and send requests directly to `base_url` so tokens are never exposed to
/// third-party mirrors.
#[derive(Clone, Debug)]
pub struct ModrinthClient {
    base_url: String,
    http: HttpClient,
}

impl ModrinthClient {
    /// Creates a new [`ModrinthClient`] using the default [`HttpClient`] configuration.
    pub fn new() -> Result<Self> {
        Ok(Self::from_http(HttpClient::new()?))
    }

    /// Creates a new [`ModrinthClient`] with an explicit `User-Agent`
    /// (Modrinth recommends `org/app/version (contact)`).
    pub fn new_with_user_agent(user_agent: impl Into<String>) -> Result<Self> {
        Ok(Self::from_http(
            HttpClient::builder().user_agent(user_agent).build()?,
        ))
    }

    /// Creates a new [`ModrinthClient`] sharing an existing [`HttpClient`].
    #[must_use]
    pub fn from_http(http: HttpClient) -> Self {
        Self {
            base_url: DEFAULT_BASE_URL.to_string(),
            http,
        }
    }

    /// Overrides the base URL (e.g., staging `https://staging-api.modrinth.com` or mock server).
    #[must_use]
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = trim_trailing_slash(base_url);
        self
    }

    /// Returns an authenticated view bound to a Modrinth Personal Access Token or OAuth token.
    #[must_use]
    pub fn authed<'a>(&'a self, token: &'a str) -> Authed<'a> {
        Authed::new(self, token)
    }

    /// Returns the configured Modrinth API base URL.
    #[must_use]
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Returns a reference to the underlying shared [`HttpClient`].
    #[must_use]
    pub fn http(&self) -> &HttpClient {
        &self.http
    }

    pub(crate) fn v2(&self, path: &str) -> String {
        format!("{}/v2{}", self.base_url, path)
    }

    pub(crate) async fn get_json<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        let url = self.v2(path);
        self.http.get_json(&url).await
    }

    pub(crate) async fn get_json_query<Q: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        query: &Q,
    ) -> Result<T> {
        let url = self.v2(path);
        self.http.get_json_query(&url, query).await
    }

    pub(crate) async fn post_json<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        let url = self.v2(path);
        self.http.post_json(&url, body).await
    }

    pub(crate) async fn get_by_ids<T: DeserializeOwned>(
        &self,
        path: &str,
        ids: &[impl AsRef<str>],
    ) -> Result<Vec<T>> {
        let id_refs: Vec<&str> = ids.iter().map(AsRef::as_ref).collect();
        for id in &id_refs {
            check_id_or_slug(id)?;
        }
        let ids_json = serde_json::to_string(&id_refs)?;
        self.get_json_query(path, &[("ids", ids_json)]).await
    }
}

define_authed!(ModrinthClient);

impl<'a> Authed<'a> {
    pub(crate) fn auth_header(&self) -> Result<HeaderValue> {
        let mut val = HeaderValue::from_str(self.token)?;
        val.set_sensitive(true);
        Ok(val)
    }

    async fn send_authed_inner<F>(
        &self,
        path: &str,
        idempotent: bool,
        mut build: F,
    ) -> Result<reqwest::Response>
    where
        F: FnMut(&reqwest::Client, &str) -> reqwest::RequestBuilder,
    {
        let url = self.client.v2(path);
        let auth = self.auth_header()?;
        let req_fn = |client: &reqwest::Client, target: &str| {
            build(client, target).header(AUTHORIZATION, auth.clone())
        };
        if idempotent {
            self.client.http.send_direct_idempotent(&url, req_fn).await
        } else {
            self.client.http.send_direct(&url, req_fn).await
        }
    }

    #[cfg(feature = "modrinth-write")]
    pub(crate) async fn send_authed<F>(&self, path: &str, build: F) -> Result<reqwest::Response>
    where
        F: FnMut(&reqwest::Client, &str) -> reqwest::RequestBuilder,
    {
        self.send_authed_inner(path, false, build).await
    }

    pub(crate) async fn get_authed_json<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        let resp = self.send_authed_inner(path, true, |c, t| c.get(t)).await?;
        Ok(resp.json().await?)
    }
}

#[cfg(feature = "modrinth-write")]
impl<'a> Authed<'a> {
    pub(crate) async fn post_authed_empty<B: Serialize + ?Sized>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<()> {
        self.send_authed(path, |c, t| c.post(t).json(body)).await?;
        Ok(())
    }

    pub(crate) async fn post_authed_no_body(&self, path: &str) -> Result<()> {
        self.send_authed(path, |c, t| c.post(t)).await?;
        Ok(())
    }

    pub(crate) async fn patch_authed_json<B: Serialize + ?Sized>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<()> {
        self.send_authed(path, |c, t| c.patch(t).json(body)).await?;
        Ok(())
    }

    pub(crate) async fn patch_authed_query<Q: Serialize + ?Sized, B: Serialize + ?Sized>(
        &self,
        path: &str,
        query: &Q,
        body: &B,
    ) -> Result<()> {
        self.send_authed(path, |c, t| c.patch(t).query(query).json(body))
            .await?;
        Ok(())
    }

    pub(crate) async fn delete_authed(&self, path: &str) -> Result<()> {
        self.send_authed(path, |c, t| c.delete(t)).await?;
        Ok(())
    }

    pub(crate) async fn upload_icon(
        &self,
        path: &str,
        ext: &str,
        bytes: Vec<u8>,
        content_type: &str,
    ) -> Result<()> {
        let url = self.client.v2(path);
        let auth = self.auth_header()?;
        self.client
            .http
            .send_direct_oneshot(&url, move |client, target| {
                client
                    .patch(target)
                    .header(AUTHORIZATION, auth)
                    .header(CONTENT_TYPE, content_type)
                    .query(&[("ext", ext)])
                    .body(bytes)
            })
            .await?;
        Ok(())
    }

    pub(crate) async fn send_multipart(
        &self,
        path: &str,
        data_json: String,
        files: Vec<(String, UploadFile)>,
    ) -> Result<reqwest::Response> {
        let url = self.client.v2(path);
        let auth = self.auth_header()?;
        let parts = files
            .into_iter()
            .map(|(part_name, file)| {
                let part = Part::bytes(file.bytes)
                    .file_name(file.file_name)
                    .mime_str(&file.mime_type)?;
                Ok((part_name, part))
            })
            .collect::<Result<Vec<_>>>()?;

        self.client
            .http
            .send_direct_oneshot(&url, move |client, target| {
                let mut form = Form::new().text("data", data_json);
                for (part_name, part) in parts {
                    form = form.part(part_name, part);
                }
                client
                    .post(target)
                    .header(AUTHORIZATION, auth)
                    .multipart(form)
            })
            .await
    }
}