use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LibraryEntryObject {
pub spec: String,
#[serde(rename = "docsPaths")]
pub docs_paths: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum LibraryEntry {
Spec(String),
WithDocs(LibraryEntryObject),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AskJson {
pub libraries: Vec<LibraryEntry>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum StoreMode {
#[default]
Copy,
Link,
Ref,
}
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum AskJsonError {
#[error("spec must start with an ecosystem prefix (e.g. \"npm:next\", \"github:owner/repo@v1.2.3\"): {0:?}")]
InvalidSpec(String),
#[error(
"docsPaths override must be non-empty (use a bare spec string for no override): {0:?}"
)]
EmptyDocsPaths(String),
#[error("docsPaths entries must be non-empty strings: {0:?}")]
EmptyDocsPathItem(String),
}
impl AskJson {
pub fn parse(json: &str) -> anyhow::Result<Self> {
let parsed: AskJson = serde_json::from_str(json)?;
parsed.validate()?;
Ok(parsed)
}
pub fn validate(&self) -> Result<(), AskJsonError> {
for entry in &self.libraries {
let spec = entry.spec();
if !is_valid_spec_string(spec) {
return Err(AskJsonError::InvalidSpec(spec.to_string()));
}
if let LibraryEntry::WithDocs(obj) = entry {
if obj.docs_paths.is_empty() {
return Err(AskJsonError::EmptyDocsPaths(spec.to_string()));
}
if obj.docs_paths.iter().any(|p| p.is_empty()) {
return Err(AskJsonError::EmptyDocsPathItem(spec.to_string()));
}
}
}
Ok(())
}
}
impl LibraryEntry {
pub fn spec(&self) -> &str {
match self {
LibraryEntry::Spec(s) => s,
LibraryEntry::WithDocs(o) => &o.spec,
}
}
pub fn docs_paths(&self) -> Option<&[String]> {
match self {
LibraryEntry::Spec(_) => None,
LibraryEntry::WithDocs(o) => Some(&o.docs_paths),
}
}
}
pub fn entry_from_spec(spec: impl Into<String>, docs_paths: &[String]) -> LibraryEntry {
let spec = spec.into();
if docs_paths.is_empty() {
LibraryEntry::Spec(spec)
} else {
LibraryEntry::WithDocs(LibraryEntryObject {
spec,
docs_paths: docs_paths.to_vec(),
})
}
}
fn is_valid_spec_string(spec: &str) -> bool {
let Some((prefix, payload)) = spec.split_once(':') else {
return false;
};
if payload.is_empty() {
return false;
}
if payload.contains(['\n', '\r', '\u{2028}', '\u{2029}']) {
return false;
}
let mut chars = prefix.chars();
match chars.next() {
Some(c) if c.is_ascii_lowercase() => {}
_ => return false,
}
chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '+' || c == '-')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_mixed_string_and_object_entries() {
let json = r#"{
"libraries": [
"npm:next",
{ "spec": "npm:zod", "docsPaths": ["docs/API.md"] },
"github:vercel/ai@v5.0.0"
]
}"#;
let ask = AskJson::parse(json).unwrap();
assert_eq!(ask.libraries.len(), 3);
assert_eq!(ask.libraries[0], LibraryEntry::Spec("npm:next".into()));
assert_eq!(ask.libraries[1].spec(), "npm:zod");
assert_eq!(
ask.libraries[1].docs_paths(),
Some(&["docs/API.md".to_string()][..])
);
assert_eq!(ask.libraries[2].docs_paths(), None);
}
#[test]
fn string_entry_roundtrips_as_plain_string() {
let entry = LibraryEntry::Spec("npm:next".into());
assert_eq!(serde_json::to_string(&entry).unwrap(), "\"npm:next\"");
}
#[test]
fn object_entry_uses_camelcase_docs_paths() {
let entry = entry_from_spec("npm:zod", &["docs/API.md".to_string()]);
assert_eq!(
serde_json::to_string(&entry).unwrap(),
r#"{"spec":"npm:zod","docsPaths":["docs/API.md"]}"#
);
}
#[test]
fn entry_from_spec_collapses_empty_docs_paths_to_string() {
assert_eq!(
entry_from_spec("npm:next", &[]),
LibraryEntry::Spec("npm:next".into())
);
assert!(matches!(
entry_from_spec("npm:next", &["d".to_string()]),
LibraryEntry::WithDocs(_)
));
}
#[test]
fn rejects_spec_without_ecosystem_prefix() {
let err = AskJson::parse(r#"{"libraries":["next"]}"#).unwrap_err();
assert!(err.to_string().contains("ecosystem prefix"));
}
#[test]
fn rejects_spec_with_embedded_line_terminator() {
let err = AskJson::parse(r#"{"libraries":["npm:next\nmalicious"]}"#).unwrap_err();
assert!(err.to_string().contains("ecosystem prefix"));
}
#[test]
fn rejects_object_with_empty_docs_paths() {
let err =
AskJson::parse(r#"{"libraries":[{"spec":"npm:zod","docsPaths":[]}]}"#).unwrap_err();
assert!(err.to_string().contains("non-empty"));
}
#[test]
fn rejects_unknown_top_level_field() {
assert!(AskJson::parse(r#"{"libraries":[],"extra":1}"#).is_err());
}
#[test]
fn rejects_unknown_object_entry_field() {
assert!(AskJson::parse(
r#"{"libraries":[{"spec":"npm:zod","docsPaths":["d"],"ref":"v1"}]}"#
)
.is_err());
}
#[test]
fn spec_string_shape_matches_regex() {
assert!(is_valid_spec_string("npm:next"));
assert!(is_valid_spec_string("github:owner/repo@v1.2.3"));
assert!(is_valid_spec_string("llms-txt:x"));
assert!(!is_valid_spec_string("Next:x")); assert!(!is_valid_spec_string("npm:")); assert!(!is_valid_spec_string("noprefix"));
assert!(!is_valid_spec_string(":x")); }
#[test]
fn store_mode_serializes_lowercase() {
assert_eq!(serde_json::to_string(&StoreMode::Ref).unwrap(), "\"ref\"");
assert_eq!(
serde_json::from_str::<StoreMode>("\"link\"").unwrap(),
StoreMode::Link
);
}
}