holger-traits 3.3.2

holger's shared vocabulary: ArtifactId, RepositoryBackendTrait, ZnippyPlugin discriminants, and ArtifactFormat — including `ArtifactFormat::home()`, the format→crate map that answers which crate serves PyPI when grepping cannot.
Documentation
//! **npm**: a tarball at `<package>/-/<name>-<version>.tgz`, named by its `package.json`;
//! npm's rules for names, versions and dist-tags.

use std::cmp::Ordering;

use super::{mismatch, ClientAt, ClientSetup, Format, Located, Named, Purl};
use crate::index_row::IndexRow;
use crate::ArtifactId;

/// npm's limit on a package name.
pub const MAX_NAME: usize = 214;

/// npm's rule for a NEW package name: lowercase, URL-safe, at most 214 characters, an optional
/// `@scope/`, never starting with `.` or `_`.
pub fn valid_package_name(name: &str) -> bool {
    fn part(p: &str) -> bool {
        !p.is_empty()
            && !p.starts_with(['.', '_'])
            && p.chars().all(|c| {
                c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '-' | '.' | '_' | '~')
            })
    }
    if name.is_empty() || name.len() > MAX_NAME {
        return false;
    }
    match name.strip_prefix('@') {
        Some(rest) => {
            matches!(rest.split_once('/'), Some((scope, pkg)) if part(scope) && part(pkg))
        }
        None => part(name),
    }
}

/// The name without its scope (what the tarball's file name carries).
pub fn unscoped(name: &str) -> &str {
    name.rsplit('/').next().unwrap_or(name)
}

/// A semantic version (`1.2.3`, `1.2.3-beta.1`, `1.2.3+build`), as npm requires one.
pub fn valid_version(v: &str) -> bool {
    parse_version(v).is_some()
}

type Parsed<'a> = ([u64; 3], Vec<&'a str>);

fn parse_version(v: &str) -> Option<Parsed<'_>> {
    if v.is_empty() || v.len() > 256 {
        return None;
    }
    let core_pre = v
        .split_once('+')
        .map(|(a, b)| (a, Some(b)))
        .unwrap_or((v, None));
    if let Some(build) = core_pre.1 {
        if build.is_empty()
            || !build
                .split('.')
                .all(|i| !i.is_empty() && i.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'))
        {
            return None;
        }
    }
    let (core, pre) = match core_pre.0.split_once('-') {
        Some((c, p)) => (c, Some(p)),
        None => (core_pre.0, None),
    };
    let mut nums = [0u64; 3];
    let mut it = core.split('.');
    for n in &mut nums {
        let s = it.next()?;
        if s.is_empty()
            || !s.chars().all(|c| c.is_ascii_digit())
            || (s.len() > 1 && s.starts_with('0'))
        {
            return None;
        }
        *n = s.parse().ok()?;
    }
    if it.next().is_some() {
        return None;
    }
    let pre: Vec<&str> = match pre {
        None => Vec::new(),
        Some(p) => {
            let ids: Vec<&str> = p.split('.').collect();
            if ids
                .iter()
                .any(|i| i.is_empty() || !i.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'))
            {
                return None;
            }
            ids
        }
    };
    Some((nums, pre))
}

/// SemVer precedence (build metadata ignored). An unparseable version sorts first.
pub fn compare_versions(a: &str, b: &str) -> Ordering {
    match (parse_version(a), parse_version(b)) {
        (Some((ca, pa)), Some((cb, pb))) => {
            ca.cmp(&cb)
                .then_with(|| match (pa.is_empty(), pb.is_empty()) {
                    (true, true) => Ordering::Equal,
                    (true, false) => Ordering::Greater,
                    (false, true) => Ordering::Less,
                    (false, false) => {
                        for (x, y) in pa.iter().zip(pb.iter()) {
                            let o = match (x.parse::<u64>(), y.parse::<u64>()) {
                                (Ok(m), Ok(n)) => m.cmp(&n),
                                (Ok(_), Err(_)) => Ordering::Less,
                                (Err(_), Ok(_)) => Ordering::Greater,
                                (Err(_), Err(_)) => x.cmp(y),
                            };
                            if o != Ordering::Equal {
                                return o;
                            }
                        }
                        pa.len().cmp(&pb.len())
                    }
                })
        }
        (None, Some(_)) => Ordering::Less,
        (Some(_), None) => Ordering::Greater,
        (None, None) => a.cmp(b),
    }
}

/// A dist-tag name: not a version (npm reads `pkg@1.2.3` as a version), URL-safe, short.
pub fn valid_tag(tag: &str) -> bool {
    !tag.is_empty()
        && tag.len() <= 64
        && !valid_version(tag)
        && !tag.starts_with(|c: char| {
            c.is_ascii_digit() || c == 'v' && tag[1..].starts_with(|d: char| d.is_ascii_digit())
        })
        && tag
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_'))
}

/// The tarball's file name: `<name without scope>-<version>.tgz`.
pub fn tarball_file(package: &str, version: &str) -> String {
    format!("{}-{version}.tgz", unscoped(package))
}

/// **The intake coordinate of a version**: the tarball's registry path below the repository,
/// `<package>/-/<file>`, as a raw coordinate (no namespace, no version), the way the chain's raw
/// `incoming` and `production` name a file.
pub fn coordinate(package: &str, version: &str) -> ArtifactId {
    ArtifactId {
        namespace: None,
        name: format!("{package}/-/{}", tarball_file(package, version)),
        version: String::new(),
    }
}

/// The (package, version) an intake coordinate is the npm tarball of, if it is one.
pub fn coords_of(id: &ArtifactId) -> Option<(String, String)> {
    if id.namespace.as_deref().is_some_and(|n| !n.is_empty()) || !id.version.is_empty() {
        return None;
    }
    let (package, file) = id.name.split_once("/-/")?;
    if !valid_package_name(package) || file.contains('/') {
        return None;
    }
    let version = file
        .strip_suffix(".tgz")?
        .strip_prefix(unscoped(package))?
        .strip_prefix('-')?;
    valid_version(version).then(|| (package.to_string(), version.to_string()))
}

/// The npm descriptor.
pub struct Npm;

/// The one npm descriptor ([`super::FORMATS`]).
pub static NPM: Npm = Npm;

impl Format for Npm {
    fn name(&self) -> &'static str {
        "npm"
    }

    fn repository(&self) -> Option<crate::ArtifactFormat> {
        Some(crate::ArtifactFormat::Npm)
    }
    fn ecosystem(&self, _distro: Option<&'static str>) -> &'static str {
        "npm"
    }
    fn claims(&self, path: &str) -> bool {
        let file = path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase();
        let ends = |exts: &[&str]| exts.iter().any(|e| file.ends_with(e));
        ends(&[".tgz"])
    }
    fn reads_row(&self) -> bool {
        true
    }
    fn client_setup(&self, at: &ClientAt<'_>) -> Vec<ClientSetup> {
        let ClientAt {
            name,
            base,
            host,
            token,
            ..
        } = *at;
        vec![ClientSetup::new(
            "npm",
            ".npmrc",
            format!("registry={base}/{name}/\n//{host}/{name}/:_authToken={token}\n"),
        )]
    }
    fn identify(&self, at: &Located<'_>) -> Result<Named, String> {
        let said = match at.declared {
            Some((n, v)) => Some((n.to_string(), v.to_string())),
            None => coords_of(&ArtifactId {
                namespace: None,
                name: at.path.to_string(),
                version: String::new(),
            }),
        };
        let own = match at.row {
            Some(IndexRow::Npm { manifest, .. }) => match (
                manifest.get("name").and_then(|v| v.as_str()),
                manifest.get("version").and_then(|v| v.as_str()),
            ) {
                (Some(n), Some(v)) => Some((n.to_string(), v.to_string())),
                _ => None,
            },
            _ => None,
        };
        let (name, version) = match (said, own) {
            (Some(s), Some(o)) if s != o => {
                return Err(mismatch(
                    self.name(),
                    (&s.0, &s.1),
                    (&o.0, &o.1),
                    "package.json",
                ))
            }
            (Some(s), _) => s,
            (None, Some(o)) => o,
            (None, None) => {
                return Err(format!(
                    "{:?} is no npm tarball (`<package>/-/<name>-<version>.tgz`)",
                    at.path
                ))
            }
        };
        let (ns, bare) = match name.strip_prefix('@').and_then(|s| s.split_once('/')) {
            Some((scope, n)) => (Some(format!("@{scope}")), n.to_string()),
            None => (None, name.clone()),
        };
        Ok(Named {
            purl: Purl::new("npm", ns.as_deref(), &bare, &version),
            coords: Some((name, version)),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::format::test_at as at;

    #[test]
    fn a_tarball_is_named_by_its_registry_path_and_its_package_json() {
        let n = NPM
            .identify(&at("@scope/pkg/-/pkg-1.2.3.tgz", None))
            .unwrap();
        assert_eq!(n.purl.to_string(), "pkg:npm/%40scope/pkg@1.2.3");
        assert_eq!(n.coords, Some(("@scope/pkg".into(), "1.2.3".into())));
        let row = |name: &str| IndexRow::Npm {
            manifest: serde_json::json!({"name": name, "version": "1.2.3"}),
            integrity: "sha512-AA==".into(),
        };
        let own = row("@scope/pkg");
        assert!(NPM
            .identify(&at("@scope/pkg/-/pkg-1.2.3.tgz", Some(&own)))
            .is_ok());
        let evil = row("evil");
        let e = NPM
            .identify(&at("@scope/pkg/-/pkg-1.2.3.tgz", Some(&evil)))
            .unwrap_err();
        assert!(e.contains("in its package.json"), "{e}");
        assert!(NPM.identify(&at("pkg-1.2.3.tgz", None)).is_err());
    }

    #[test]
    fn names_versions_and_tags_follow_npm() {
        assert!(valid_package_name("@scope/a-b.c"));
        assert!(
            !valid_package_name("Upper") && !valid_package_name("_x") && !valid_package_name("@s")
        );
        assert!(!valid_package_name(&"a".repeat(MAX_NAME + 1)));
        assert!(
            valid_version("1.2.3-beta.1+build")
                && !valid_version("01.2.3")
                && !valid_version("1.2")
        );
        assert_eq!(compare_versions("1.2.3-beta", "1.2.3"), Ordering::Less);
        assert_eq!(compare_versions("1.2.3-2", "1.2.3-10"), Ordering::Less);
        assert_eq!(compare_versions("1.10.0", "1.9.0"), Ordering::Greater);
        assert!(valid_tag("next") && !valid_tag("1.2.3") && !valid_tag("v1"));
        assert_eq!(tarball_file("@s/p", "1.0.0"), "p-1.0.0.tgz");
        assert_eq!(coordinate("@s/p", "1.0.0").name, "@s/p/-/p-1.0.0.tgz");
        let id = coordinate("@s/p", "1.0.0");
        assert_eq!(coords_of(&id), Some(("@s/p".into(), "1.0.0".into())));
        assert_eq!(unscoped("@s/p"), "p");
    }
}