mcapi 0.2.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, Java Runtimes, and SLP)
Documentation
use std::collections::HashMap;

use crate::mirror::Mirror;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use url::Url;

/// Version release channel in Mojang's version manifest.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ReleaseType {
    Release,
    Snapshot,
    OldBeta,
    OldAlpha,
    #[serde(other)]
    Unknown,
}

/// Latest release/snapshot IDs at the top of `version_manifest_v2.json`.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct VersionManifestLatest {
    pub release: String,
    pub snapshot: String,
}

/// Single version entry inside `version_manifest_v2.json`.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct VersionManifestEntry {
    pub id: String,
    #[serde(rename = "type")]
    pub release_type: ReleaseType,
    pub url: Url,
    pub time: DateTime<Utc>,
    pub release_time: DateTime<Utc>,
    pub sha1: String,
    pub compliance_level: u32,
}

/// Complete `version_manifest_v2.json` payload from `piston-meta.mojang.com`.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct VersionManifestV2 {
    pub latest: VersionManifestLatest,
    pub versions: Vec<VersionManifestEntry>,
}

/// Detailed Minecraft client/server version metadata JSON (`<version>.json`).
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GameVersionMetadata {
    pub id: String,
    #[serde(rename = "type")]
    pub release_type: ReleaseType,
    pub main_class: String,
    #[serde(default)]
    pub arguments: Option<Arguments>,
    #[serde(default)]
    pub minecraft_arguments: Option<String>,
    pub asset_index: AssetIndexReference,
    pub assets: String,
    #[serde(default)]
    pub compliance_level: Option<u32>,
    pub downloads: VersionDownloads,
    #[serde(default)]
    pub java_version: Option<JavaVersionSpec>,
    #[serde(default)]
    pub libraries: Vec<Library>,
    #[serde(default)]
    pub logging: Option<LoggingSpec>,
    #[serde(default)]
    pub minimum_launcher_version: Option<u32>,
    #[serde(default)]
    pub inherits_from: Option<String>,
    #[serde(default)]
    pub jar: Option<String>,
    pub release_time: DateTime<Utc>,
    pub time: DateTime<Utc>,
}

/// Modern `arguments` block (`game` and `jvm` argument items).
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct Arguments {
    #[serde(default)]
    pub game: Vec<ArgumentItem>,
    #[serde(default)]
    pub jvm: Vec<ArgumentItem>,
}

/// Individual argument entry — either a literal string or a conditional rule block.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ArgumentItem {
    Simple(String),
    Conditional {
        rules: Vec<Rule>,
        value: ArgumentValue,
    },
}

/// Single or multi-string value inside a conditional [`ArgumentItem`].
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ArgumentValue {
    Single(String),
    Multiple(Vec<String>),
}

/// Reference to a version's asset index JSON file.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AssetIndexReference {
    pub id: String,
    pub sha1: String,
    pub size: u64,
    pub total_size: u64,
    pub url: Url,
}

/// Primary jar/mappings downloads for a Minecraft version.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct VersionDownloads {
    #[serde(default)]
    pub client: Option<DownloadArtifact>,
    #[serde(default)]
    pub client_mappings: Option<DownloadArtifact>,
    #[serde(default)]
    pub server: Option<DownloadArtifact>,
    #[serde(default)]
    pub server_mappings: Option<DownloadArtifact>,
}

/// Single downloadable file with SHA-1 and byte length.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct DownloadArtifact {
    #[serde(default)]
    pub path: Option<String>,
    pub sha1: String,
    pub size: u64,
    pub url: Url,
}

/// Recommended Java major version component for launching a Minecraft version.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct JavaVersionSpec {
    pub component: String,
    pub major_version: u32,
}

/// Maven library dependency entry inside [`GameVersionMetadata`].
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Library {
    pub name: String,
    #[serde(default)]
    pub downloads: Option<LibraryDownloads>,
    #[serde(default)]
    pub natives: Option<HashMap<String, String>>,
    #[serde(default)]
    pub extract: Option<serde_json::Value>,
    #[serde(default)]
    pub rules: Option<Vec<Rule>>,
    #[serde(default)]
    pub url: Option<Url>,
}

/// Artifact and native classifier downloads for a [`Library`].
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct LibraryDownloads {
    #[serde(default)]
    pub artifact: Option<DownloadArtifact>,
    #[serde(default)]
    pub classifiers: Option<LibraryClassifiers>,
}

/// Map of classifier key (e.g. `"natives-windows"`) to [`DownloadArtifact`].
pub type LibraryClassifiers = HashMap<String, DownloadArtifact>;

/// Action taken when a [`Rule`] matches.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum RuleAction {
    Allow,
    Disallow,
}

/// OS matching predicates inside a [`Rule`].
#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
pub struct OsRule {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub version: Option<String>,
    #[serde(default)]
    pub arch: Option<String>,
}

/// Conditional rule attached to libraries and launch arguments.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Rule {
    pub action: RuleAction,
    #[serde(default)]
    pub os: Option<OsRule>,
    #[serde(default)]
    pub features: Option<HashMap<String, bool>>,
}

/// Client log4j configuration spec.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct LoggingSpec {
    #[serde(default)]
    pub client: Option<LoggingClientSpec>,
}

/// Client logging config descriptor inside [`LoggingSpec`].
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct LoggingClientSpec {
    pub argument: String,
    pub file: LoggingFileArtifact,
    #[serde(rename = "type")]
    pub logging_type: String,
}

/// Downloadable log4j XML artifact inside [`LoggingClientSpec`].
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct LoggingFileArtifact {
    pub id: String,
    pub sha1: String,
    pub size: u64,
    pub url: Url,
}

/// Asset index mapping virtual resource paths to hashed objects.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct AssetIndex {
    pub objects: HashMap<String, AssetObject>,
    #[serde(default, rename = "virtual")]
    pub is_virtual: bool,
    #[serde(default)]
    pub map_to_resources: bool,
}

/// Single asset object hash & size inside [`AssetIndex`].
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct AssetObject {
    pub hash: String,
    pub size: u64,
}

impl AssetObject {
    /// Returns `<hash[0..2]>/<hash>` relative object storage path when `hash` is valid hex.
    pub fn relative_path(&self) -> Option<String> {
        if self.hash.len() < 2 || !self.hash.bytes().all(|b| b.is_ascii_hexdigit()) {
            return None;
        }
        let prefix = self.hash.get(..2)?;
        Some(format!("{prefix}/{}", self.hash))
    }

    /// Returns the download URL for this asset object, routed through `mirror`.
    pub fn download_url(&self, mirror: &Mirror) -> Option<Url> {
        let rel = self.relative_path()?;
        let official = format!("https://resources.download.minecraft.net/{rel}");
        Url::parse(&mirror.rewrite_url(&official)).ok()
    }
}