mcapi 0.2.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, Java Runtimes, and SLP)
Documentation
/// A prefix rewrite rule mapping an upstream origin/prefix to a mirror prefix.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RewriteRule {
    pub from: String,
    pub to: String,
}

impl RewriteRule {
    /// Creates a new URL prefix rewrite rule.
    pub fn new(from: impl Into<String>, to: impl Into<String>) -> Self {
        Self {
            from: from.into().trim_end_matches('/').to_string(),
            to: to.into().trim_end_matches('/').to_string(),
        }
    }

    /// Applies this rule if `url` starts with `self.from` on a segment boundary.
    pub fn apply(&self, url: &str) -> Option<String> {
        let rest = url.strip_prefix(&self.from)?;
        if rest.is_empty() || rest.starts_with('/') || rest.starts_with('?') {
            Some(format!("{}{}", self.to, rest))
        } else {
            None
        }
    }
}

/// Mirror routing strategy applied to outbound URLs.
///
/// Built-in route tables follow:
/// - BMCLAPI: <https://bmclapidoc.bangbang93.com/>
/// - MCIMirror: <https://docs.mcimirror.top/>
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum Mirror {
    /// Use official upstream endpoints directly.
    #[default]
    Official,
    /// Route Mojang, Piston, Fabric, Forge, NeoForge, and authlib-injector URLs through BMCLAPI.
    Bmclapi,
    /// Route Modrinth and CurseForge API and download CDN URLs through MCIMirror.
    Mcim,
    /// Combines BMCLAPI (Mojang/Loaders/ALI) and MCIM (Modrinth/CurseForge).
    China,
    /// Applies multiple mirrors in order (first matching rule wins).
    Combined(Vec<Mirror>),
    /// Applies custom prefix rewrite rules in order.
    Custom(Vec<RewriteRule>),
}

const BMCLAPI_RULES: &[(&str, &str)] = &[
    (
        "https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json",
        "https://bmclapi2.bangbang93.com/forge/promos",
    ),
    (
        "https://dl.liteloader.com/versions/versions.json",
        "https://bmclapi2.bangbang93.com/maven/com/mumfrey/liteloader/versions.json",
    ),
    (
        "https://meta.quiltmc.org",
        "https://bmclapi2.bangbang93.com/quilt-meta",
    ),
    (
        "https://maven.quiltmc.org/repository/release",
        "https://bmclapi2.bangbang93.com/maven",
    ),
    (
        "https://piston-meta.mojang.com",
        "https://bmclapi2.bangbang93.com",
    ),
    (
        "https://launchermeta.mojang.com",
        "https://bmclapi2.bangbang93.com",
    ),
    (
        "https://piston-data.mojang.com",
        "https://bmclapi2.bangbang93.com",
    ),
    (
        "https://launcher.mojang.com",
        "https://bmclapi2.bangbang93.com",
    ),
    (
        "https://resources.download.minecraft.net",
        "https://bmclapi2.bangbang93.com/assets",
    ),
    (
        "https://libraries.minecraft.net",
        "https://bmclapi2.bangbang93.com/maven",
    ),
    (
        "https://meta.fabricmc.net",
        "https://bmclapi2.bangbang93.com/fabric-meta",
    ),
    (
        "https://maven.fabricmc.net",
        "https://bmclapi2.bangbang93.com/maven",
    ),
    (
        "https://maven.minecraftforge.net",
        "https://bmclapi2.bangbang93.com/maven",
    ),
    (
        "https://files.minecraftforge.net/maven",
        "https://bmclapi2.bangbang93.com/maven",
    ),
    (
        "https://maven.neoforged.net/releases",
        "https://bmclapi2.bangbang93.com/maven",
    ),
    (
        "https://authlib-injector.yushi.moe",
        "https://bmclapi2.bangbang93.com/mirrors/authlib-injector",
    ),
];

const MCIM_RULES: &[(&str, &str)] = &[
    (
        "https://api.modrinth.com",
        "https://mod.mcimirror.top/modrinth",
    ),
    (
        "https://api.curseforge.com",
        "https://mod.mcimirror.top/curseforge",
    ),
    ("https://cdn.modrinth.com", "https://mod.mcimirror.top"),
    ("https://edge.forgecdn.net", "https://mod.mcimirror.top"),
    (
        "https://mediafilez.forgecdn.net",
        "https://mod.mcimirror.top",
    ),
];

impl Mirror {
    /// Rewrites `url` according to this mirror configuration, returning the original URL
    /// if no rule matches.
    pub fn rewrite_url(&self, url: &str) -> String {
        match self {
            Mirror::Official => url.to_string(),
            Mirror::Bmclapi => {
                apply_static_rules(BMCLAPI_RULES, url).unwrap_or_else(|| url.to_string())
            }
            Mirror::Mcim => apply_static_rules(MCIM_RULES, url).unwrap_or_else(|| url.to_string()),
            Mirror::China => apply_static_rules(BMCLAPI_RULES, url)
                .or_else(|| apply_static_rules(MCIM_RULES, url))
                .unwrap_or_else(|| url.to_string()),
            Mirror::Combined(mirrors) => {
                for mirror in mirrors {
                    let rewritten = mirror.rewrite_url(url);
                    if rewritten != url {
                        return rewritten;
                    }
                }
                url.to_string()
            }
            Mirror::Custom(rules) => {
                for rule in rules {
                    if let Some(rewritten) = rule.apply(url) {
                        return rewritten;
                    }
                }
                url.to_string()
            }
        }
    }

    /// Returns `true` if `self` rewrites `url` to a different target URL.
    pub fn is_rewritten(&self, url: &str) -> bool {
        self.rewrite_url(url) != url
    }

    /// Returns all distinct candidate URLs for `official_url` in priority order
    /// (matching mirror URLs first, followed by `official_url` as the final fallback).
    pub fn candidate_urls(&self, official_url: &str) -> Vec<String> {
        let mut out = Vec::new();
        self.collect_mirror_candidates(official_url, &mut out);
        push_unique(&mut out, official_url.to_string());
        out
    }

    fn collect_mirror_candidates(&self, official_url: &str, out: &mut Vec<String>) {
        match self {
            Mirror::Official => {}
            Mirror::Bmclapi => push_static_rule(BMCLAPI_RULES, official_url, out),
            Mirror::Mcim => push_static_rule(MCIM_RULES, official_url, out),
            Mirror::China => {
                push_static_rule(BMCLAPI_RULES, official_url, out);
                push_static_rule(MCIM_RULES, official_url, out);
            }
            Mirror::Combined(mirrors) => {
                for mirror in mirrors {
                    mirror.collect_mirror_candidates(official_url, out);
                }
            }
            Mirror::Custom(rules) => {
                for rule in rules {
                    if let Some(rewritten) = rule.apply(official_url)
                        && rewritten != official_url
                    {
                        push_unique(out, rewritten);
                    }
                }
            }
        }
    }
}

fn push_static_rule(rules: &[(&str, &str)], official_url: &str, out: &mut Vec<String>) {
    if let Some(rewritten) = apply_static_rules(rules, official_url)
        && rewritten != official_url
    {
        push_unique(out, rewritten);
    }
}

fn push_unique(out: &mut Vec<String>, url: String) {
    if !out.contains(&url) {
        out.push(url);
    }
}

fn apply_static_rules(rules: &[(&str, &str)], url: &str) -> Option<String> {
    for (from, to) in rules {
        if let Some(rest) = url.strip_prefix(from)
            && (rest.is_empty() || rest.starts_with('/') || rest.starts_with('?'))
        {
            return Some(format!("{to}{rest}"));
        }
    }
    None
}