offline-registry 0.4.0

Registry of Offline Protocol packages, skills, workflows, and templates
Documentation
//! Package resolution: expand a requested package set (or a workflow +
//! platform) into the full ordered install list with versions, peer
//! dependencies, platform-compatibility checks, and license call-outs.

use std::collections::{BTreeMap, BTreeSet, VecDeque};

use serde::Serialize;

use crate::store::Registry;
use crate::RegistryError;

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResolvedPackage {
    pub name: String,
    pub version: String,
    pub registry: String,
    pub license: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub license_note: Option<String>,
    /// Why this package is in the set: `requested` or `required by <pkg>`.
    pub reason: String,
    pub status: String,
    /// The package's own install instruction, when its registry has no
    /// default command (a Swift package, a release download).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub install: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Resolution {
    pub platform: String,
    pub packages: Vec<ResolvedPackage>,
    /// Peer dependencies the host app must provide (name -> version range).
    pub peer_dependencies: BTreeMap<String, String>,
    /// Ready-to-run install commands.
    pub install_commands: Vec<String>,
    /// Non-fatal compatibility or licensing notices.
    pub warnings: Vec<String>,
}

impl Registry {
    /// Resolve an explicit package list for a platform.
    pub fn resolve_packages(
        &self,
        requested: &[String],
        platform: &str,
    ) -> Result<Resolution, RegistryError> {
        let mut order: Vec<String> = Vec::new();
        let mut seen: BTreeSet<String> = BTreeSet::new();
        let mut reasons: BTreeMap<String, String> = BTreeMap::new();
        let mut queue: VecDeque<String> = VecDeque::new();

        for name in requested {
            let pkg = self
                .package(name)
                .ok_or_else(|| RegistryError::NotFound(format!("package `{name}`")))?;
            reasons.insert(pkg.name.clone(), "requested".to_string());
            queue.push_back(pkg.name.clone());
        }

        while let Some(name) = queue.pop_front() {
            if !seen.insert(name.clone()) {
                continue;
            }
            order.push(name.clone());
            let pkg = self.package(&name).expect("validated in registry load");
            for req in &pkg.requires {
                reasons
                    .entry(req.clone())
                    .or_insert_with(|| format!("required by {name}"));
                queue.push_back(req.clone());
            }
        }

        let mut warnings = Vec::new();
        let mut peer_dependencies = BTreeMap::new();
        let mut packages = Vec::new();
        for name in &order {
            let pkg = self.package(name).expect("seen packages exist");
            if !pkg.platforms.iter().any(|p| p == platform) {
                return Err(RegistryError::Incompatible(format!(
                    "package `{}` supports platforms [{}], not `{platform}`",
                    pkg.name,
                    pkg.platforms.join(", ")
                )));
            }
            if pkg.status != "stable" {
                warnings.push(format!(
                    "`{}` is {} — pin carefully and expect API changes",
                    pkg.name, pkg.status
                ));
            }
            if let Some(note) = &pkg.license_note {
                warnings.push(format!("`{}` ({}): {}", pkg.name, pkg.license, note));
            }
            for (peer, range) in &pkg.peer_dependencies {
                peer_dependencies.insert(peer.clone(), range.clone());
            }
            packages.push(ResolvedPackage {
                name: pkg.name.clone(),
                version: pkg.version.clone(),
                registry: pkg.registry.clone(),
                license: pkg.license.clone(),
                license_note: pkg.license_note.clone(),
                reason: reasons
                    .get(name)
                    .cloned()
                    .unwrap_or_else(|| "requested".to_string()),
                status: pkg.status.clone(),
                install: pkg.install.clone(),
            });
        }

        let install_commands = build_install_commands(&packages);
        Ok(Resolution {
            platform: platform.to_string(),
            packages,
            peer_dependencies,
            install_commands,
            warnings,
        })
    }

    /// Resolve everything a workflow needs on a given platform.
    pub fn resolve_workflow(
        &self,
        workflow_name: &str,
        platform: &str,
    ) -> Result<Resolution, RegistryError> {
        let wf = self
            .workflow(workflow_name)
            .ok_or_else(|| RegistryError::NotFound(format!("workflow `{workflow_name}`")))?;
        let pkgs = wf.packages.get(platform).ok_or_else(|| {
            RegistryError::Incompatible(format!(
                "workflow `{workflow_name}` supports platforms [{}], not `{platform}`",
                wf.packages.keys().cloned().collect::<Vec<_>>().join(", ")
            ))
        })?;
        self.resolve_packages(pkgs, platform)
    }
}

fn build_install_commands(packages: &[ResolvedPackage]) -> Vec<String> {
    let by_default = |registry: &str| -> Vec<String> {
        packages
            .iter()
            .filter(|p| p.registry == registry && p.install.is_none())
            .map(|p| match registry {
                "pypi" => format!("{}=={}", p.name, p.version),
                _ => format!("{}@{}", p.name, p.version),
            })
            .collect()
    };
    let mut cmds = Vec::new();
    for (registry, command) in [
        ("npm", "npm install"),
        ("crates", "cargo add"),
        ("pypi", "pip install"),
    ] {
        let names = by_default(registry);
        if !names.is_empty() {
            cmds.push(format!("{command} {}", names.join(" ")));
        }
    }
    // A package with its own instruction (a Swift package, a release
    // download, a crate that needs features) is installed as it says.
    cmds.extend(packages.iter().filter_map(|p| p.install.clone()));
    cmds
}