Skip to main content

ask/
spec.rs

1//! Spec parsing for `ask.json` library entries — Rust port of
2//! `packages/cli/src/spec.ts`.
3//!
4//! The spec string is the user-facing identifier; the library *name* is the slug
5//! used for `.ask/docs/<name>@<ver>/` and `.claude/skills/<name>-docs/`. Slug
6//! derivation:
7//!
8//!   - `npm:next`              → `next`
9//!   - `npm:@mastra/client-js` → `mastra-client-js` (scoped flatten)
10//!   - `github:vercel/next.js` → `next.js`
11
12/// A parsed `ask.json` spec string. Discriminated the same way as the TS
13/// `ParsedSpec` union.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum ParsedSpec {
16    Npm {
17        pkg: String,
18        name: String,
19    },
20    Github {
21        owner: String,
22        repo: String,
23        name: String,
24    },
25    Unknown {
26        ecosystem: String,
27        payload: String,
28        name: String,
29    },
30}
31
32impl ParsedSpec {
33    /// The library slug, regardless of variant.
34    pub fn name(&self) -> &str {
35        match self {
36            ParsedSpec::Npm { name, .. }
37            | ParsedSpec::Github { name, .. }
38            | ParsedSpec::Unknown { name, .. } => name,
39        }
40    }
41}
42
43/// Parse a spec string into its ecosystem-tagged form.
44///
45/// Mirrors `parseSpec` in `spec.ts`: the ecosystem is everything before the
46/// first `:`; a spec with no `:` is `unknown` with an empty ecosystem.
47pub fn parse_spec(spec: &str) -> ParsedSpec {
48    let Some(colon_idx) = spec.find(':') else {
49        return ParsedSpec::Unknown {
50            ecosystem: String::new(),
51            payload: spec.to_string(),
52            name: spec.to_string(),
53        };
54    };
55    let ecosystem = &spec[..colon_idx];
56    let payload = &spec[colon_idx + 1..];
57
58    if ecosystem == "npm" {
59        return ParsedSpec::Npm {
60            pkg: payload.to_string(),
61            name: slugify_npm_name(payload),
62        };
63    }
64
65    if ecosystem == "github" {
66        // The github repo is everything after the FIRST slash (repo names never
67        // contain a slash, but owners don't either — split on the first).
68        match payload.split_once('/') {
69            Some((owner, repo)) => {
70                return ParsedSpec::Github {
71                    owner: owner.to_string(),
72                    repo: repo.to_string(),
73                    name: repo.to_string(),
74                };
75            }
76            None => {
77                return ParsedSpec::Unknown {
78                    ecosystem: ecosystem.to_string(),
79                    payload: payload.to_string(),
80                    name: payload.to_string(),
81                };
82            }
83        }
84    }
85
86    ParsedSpec::Unknown {
87        ecosystem: ecosystem.to_string(),
88        payload: payload.to_string(),
89        name: payload.to_string(),
90    }
91}
92
93/// The library slug for a spec (`parse_spec(spec).name()`).
94pub fn library_name_from_spec(spec: &str) -> String {
95    parse_spec(spec).name().to_string()
96}
97
98/// Split an inline `@version` suffix off a spec — port of
99/// `splitExplicitVersion` in `commands/ensure-checkout.ts`.
100///
101/// The `@` is treated as a version separator only when it is neither the first
102/// character (a bare scoped name `@vercel/ai`) nor immediately after the
103/// ecosystem-prefix colon (`npm:@vercel/ai`). Returns the spec body and the
104/// optional version, borrowing from the input.
105pub fn split_explicit_version(input: &str) -> (&str, Option<&str>) {
106    match input.rfind('@') {
107        None => (input, None),
108        // `@` at index 0, or right after a `:` → scope marker, not a version.
109        Some(0) => (input, None),
110        Some(idx) if input.as_bytes()[idx - 1] == b':' => (input, None),
111        Some(idx) => (&input[..idx], Some(&input[idx + 1..])),
112    }
113}
114
115/// `@mastra/client-js` → `mastra-client-js`. Scoped npm names are not valid as
116/// `.ask/docs/<dir>` or Claude Code skill dir names, so we flatten them the same
117/// way the registry server does. Non-scoped names pass through unchanged.
118pub fn slugify_npm_name(pkg_name: &str) -> String {
119    if is_scoped_pkg(pkg_name) {
120        // Drop the leading `@`, then turn the single `/` into `-`.
121        pkg_name[1..].replacen('/', "-", 1)
122    } else {
123        pkg_name.to_string()
124    }
125}
126
127/// Equivalent of the TS `SCOPED_PKG_RE = /^@[^/]+\/[^/]+$/`: a leading `@`, a
128/// non-empty scope with no slash, a single `/`, and a non-empty name with no
129/// slash.
130fn is_scoped_pkg(s: &str) -> bool {
131    let Some(rest) = s.strip_prefix('@') else {
132        return false;
133    };
134    match rest.split_once('/') {
135        // `split_once` splits on the first `/`, so `scope` is slash-free by
136        // construction; the name must also be non-empty and slash-free.
137        Some((scope, name)) => !scope.is_empty() && !name.is_empty() && !name.contains('/'),
138        None => false,
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    #[test]
147    fn npm_unscoped() {
148        assert_eq!(
149            parse_spec("npm:next"),
150            ParsedSpec::Npm {
151                pkg: "next".into(),
152                name: "next".into()
153            }
154        );
155    }
156
157    #[test]
158    fn npm_scoped_is_flattened() {
159        assert_eq!(
160            parse_spec("npm:@mastra/client-js"),
161            ParsedSpec::Npm {
162                pkg: "@mastra/client-js".into(),
163                name: "mastra-client-js".into(),
164            }
165        );
166    }
167
168    #[test]
169    fn github_repo_keeps_dots() {
170        assert_eq!(
171            parse_spec("github:vercel/next.js"),
172            ParsedSpec::Github {
173                owner: "vercel".into(),
174                repo: "next.js".into(),
175                name: "next.js".into(),
176            }
177        );
178    }
179
180    #[test]
181    fn github_without_slash_is_unknown() {
182        assert_eq!(
183            parse_spec("github:justarepo"),
184            ParsedSpec::Unknown {
185                ecosystem: "github".into(),
186                payload: "justarepo".into(),
187                name: "justarepo".into(),
188            }
189        );
190    }
191
192    #[test]
193    fn no_colon_is_unknown_empty_ecosystem() {
194        assert_eq!(
195            parse_spec("next"),
196            ParsedSpec::Unknown {
197                ecosystem: String::new(),
198                payload: "next".into(),
199                name: "next".into(),
200            }
201        );
202    }
203
204    #[test]
205    fn unknown_ecosystem_passthrough() {
206        assert_eq!(
207            parse_spec("pypi:fastapi"),
208            ParsedSpec::Unknown {
209                ecosystem: "pypi".into(),
210                payload: "fastapi".into(),
211                name: "fastapi".into(),
212            }
213        );
214    }
215
216    #[test]
217    fn github_owner_repo_with_subpath_splits_on_first_slash() {
218        // Only the first slash separates owner/repo; the rest stays in repo.
219        assert_eq!(
220            parse_spec("github:owner/repo/extra"),
221            ParsedSpec::Github {
222                owner: "owner".into(),
223                repo: "repo/extra".into(),
224                name: "repo/extra".into(),
225            }
226        );
227    }
228
229    #[test]
230    fn library_name_helper_matches_variant_name() {
231        assert_eq!(
232            library_name_from_spec("npm:@mastra/client-js"),
233            "mastra-client-js"
234        );
235        assert_eq!(library_name_from_spec("github:vercel/next.js"), "next.js");
236        assert_eq!(library_name_from_spec("react"), "react");
237    }
238
239    #[test]
240    fn split_explicit_version_cases() {
241        assert_eq!(
242            split_explicit_version("npm:next@14"),
243            ("npm:next", Some("14"))
244        );
245        assert_eq!(
246            split_explicit_version("github:vercel/next.js@v14.2.3"),
247            ("github:vercel/next.js", Some("v14.2.3"))
248        );
249        // Bare scoped name: leading `@` is a scope marker.
250        assert_eq!(split_explicit_version("@vercel/ai"), ("@vercel/ai", None));
251        // `@` right after the ecosystem colon is a scope marker.
252        assert_eq!(
253            split_explicit_version("npm:@vercel/ai"),
254            ("npm:@vercel/ai", None)
255        );
256        // Scoped name WITH a version → split on the last `@`.
257        assert_eq!(
258            split_explicit_version("npm:@vercel/ai@5.0.0"),
259            ("npm:@vercel/ai", Some("5.0.0"))
260        );
261        assert_eq!(split_explicit_version("next"), ("next", None));
262    }
263
264    #[test]
265    fn slugify_edge_cases() {
266        assert_eq!(slugify_npm_name("next"), "next");
267        assert_eq!(slugify_npm_name("@scope/pkg"), "scope-pkg");
268        // Not a valid scoped name (no `/`) — passes through unchanged.
269        assert_eq!(slugify_npm_name("@notscoped"), "@notscoped");
270        // Deep path is not the scoped shape (`^@[^/]+/[^/]+$`) — unchanged.
271        assert_eq!(slugify_npm_name("@a/b/c"), "@a/b/c");
272    }
273}