1use serde::{Deserialize, Serialize};
12
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(deny_unknown_fields)]
20pub struct LibraryEntryObject {
21 pub spec: String,
22 #[serde(rename = "docsPaths")]
23 pub docs_paths: Vec<String>,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(untagged)]
31pub enum LibraryEntry {
32 Spec(String),
33 WithDocs(LibraryEntryObject),
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(deny_unknown_fields)]
40pub struct AskJson {
41 pub libraries: Vec<LibraryEntry>,
42}
43
44#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
46#[serde(rename_all = "lowercase")]
47pub enum StoreMode {
48 #[default]
49 Copy,
50 Link,
51 Ref,
52}
53
54#[derive(Debug, thiserror::Error, PartialEq, Eq)]
57pub enum AskJsonError {
58 #[error("spec must start with an ecosystem prefix (e.g. \"npm:next\", \"github:owner/repo@v1.2.3\"): {0:?}")]
59 InvalidSpec(String),
60 #[error(
61 "docsPaths override must be non-empty (use a bare spec string for no override): {0:?}"
62 )]
63 EmptyDocsPaths(String),
64 #[error("docsPaths entries must be non-empty strings: {0:?}")]
65 EmptyDocsPathItem(String),
66}
67
68impl AskJson {
69 pub fn parse(json: &str) -> anyhow::Result<Self> {
75 let parsed: AskJson = serde_json::from_str(json)?;
76 parsed.validate()?;
77 Ok(parsed)
78 }
79
80 pub fn validate(&self) -> Result<(), AskJsonError> {
82 for entry in &self.libraries {
83 let spec = entry.spec();
84 if !is_valid_spec_string(spec) {
85 return Err(AskJsonError::InvalidSpec(spec.to_string()));
86 }
87 if let LibraryEntry::WithDocs(obj) = entry {
88 if obj.docs_paths.is_empty() {
89 return Err(AskJsonError::EmptyDocsPaths(spec.to_string()));
90 }
91 if obj.docs_paths.iter().any(|p| p.is_empty()) {
92 return Err(AskJsonError::EmptyDocsPathItem(spec.to_string()));
93 }
94 }
95 }
96 Ok(())
97 }
98}
99
100impl LibraryEntry {
101 pub fn spec(&self) -> &str {
103 match self {
104 LibraryEntry::Spec(s) => s,
105 LibraryEntry::WithDocs(o) => &o.spec,
106 }
107 }
108
109 pub fn docs_paths(&self) -> Option<&[String]> {
112 match self {
113 LibraryEntry::Spec(_) => None,
114 LibraryEntry::WithDocs(o) => Some(&o.docs_paths),
115 }
116 }
117}
118
119pub fn entry_from_spec(spec: impl Into<String>, docs_paths: &[String]) -> LibraryEntry {
123 let spec = spec.into();
124 if docs_paths.is_empty() {
125 LibraryEntry::Spec(spec)
126 } else {
127 LibraryEntry::WithDocs(LibraryEntryObject {
128 spec,
129 docs_paths: docs_paths.to_vec(),
130 })
131 }
132}
133
134fn is_valid_spec_string(spec: &str) -> bool {
137 let Some((prefix, payload)) = spec.split_once(':') else {
138 return false;
139 };
140 if payload.is_empty() {
141 return false;
142 }
143 if payload.contains(['\n', '\r', '\u{2028}', '\u{2029}']) {
149 return false;
150 }
151 let mut chars = prefix.chars();
152 match chars.next() {
153 Some(c) if c.is_ascii_lowercase() => {}
154 _ => return false,
155 }
156 chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '+' || c == '-')
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162
163 #[test]
164 fn parses_mixed_string_and_object_entries() {
165 let json = r#"{
166 "libraries": [
167 "npm:next",
168 { "spec": "npm:zod", "docsPaths": ["docs/API.md"] },
169 "github:vercel/ai@v5.0.0"
170 ]
171 }"#;
172 let ask = AskJson::parse(json).unwrap();
173 assert_eq!(ask.libraries.len(), 3);
174 assert_eq!(ask.libraries[0], LibraryEntry::Spec("npm:next".into()));
175 assert_eq!(ask.libraries[1].spec(), "npm:zod");
176 assert_eq!(
177 ask.libraries[1].docs_paths(),
178 Some(&["docs/API.md".to_string()][..])
179 );
180 assert_eq!(ask.libraries[2].docs_paths(), None);
181 }
182
183 #[test]
184 fn string_entry_roundtrips_as_plain_string() {
185 let entry = LibraryEntry::Spec("npm:next".into());
188 assert_eq!(serde_json::to_string(&entry).unwrap(), "\"npm:next\"");
189 }
190
191 #[test]
192 fn object_entry_uses_camelcase_docs_paths() {
193 let entry = entry_from_spec("npm:zod", &["docs/API.md".to_string()]);
194 assert_eq!(
195 serde_json::to_string(&entry).unwrap(),
196 r#"{"spec":"npm:zod","docsPaths":["docs/API.md"]}"#
197 );
198 }
199
200 #[test]
201 fn entry_from_spec_collapses_empty_docs_paths_to_string() {
202 assert_eq!(
203 entry_from_spec("npm:next", &[]),
204 LibraryEntry::Spec("npm:next".into())
205 );
206 assert!(matches!(
207 entry_from_spec("npm:next", &["d".to_string()]),
208 LibraryEntry::WithDocs(_)
209 ));
210 }
211
212 #[test]
213 fn rejects_spec_without_ecosystem_prefix() {
214 let err = AskJson::parse(r#"{"libraries":["next"]}"#).unwrap_err();
215 assert!(err.to_string().contains("ecosystem prefix"));
216 }
217
218 #[test]
219 fn rejects_spec_with_embedded_line_terminator() {
220 let err = AskJson::parse(r#"{"libraries":["npm:next\nmalicious"]}"#).unwrap_err();
223 assert!(err.to_string().contains("ecosystem prefix"));
224 }
225
226 #[test]
227 fn rejects_object_with_empty_docs_paths() {
228 let err =
230 AskJson::parse(r#"{"libraries":[{"spec":"npm:zod","docsPaths":[]}]}"#).unwrap_err();
231 assert!(err.to_string().contains("non-empty"));
232 }
233
234 #[test]
235 fn rejects_unknown_top_level_field() {
236 assert!(AskJson::parse(r#"{"libraries":[],"extra":1}"#).is_err());
237 }
238
239 #[test]
240 fn rejects_unknown_object_entry_field() {
241 assert!(AskJson::parse(
242 r#"{"libraries":[{"spec":"npm:zod","docsPaths":["d"],"ref":"v1"}]}"#
243 )
244 .is_err());
245 }
246
247 #[test]
248 fn spec_string_shape_matches_regex() {
249 assert!(is_valid_spec_string("npm:next"));
250 assert!(is_valid_spec_string("github:owner/repo@v1.2.3"));
251 assert!(is_valid_spec_string("llms-txt:x"));
252 assert!(!is_valid_spec_string("Next:x")); assert!(!is_valid_spec_string("npm:")); assert!(!is_valid_spec_string("noprefix"));
255 assert!(!is_valid_spec_string(":x")); }
257
258 #[test]
259 fn store_mode_serializes_lowercase() {
260 assert_eq!(serde_json::to_string(&StoreMode::Ref).unwrap(), "\"ref\"");
261 assert_eq!(
262 serde_json::from_str::<StoreMode>("\"link\"").unwrap(),
263 StoreMode::Link
264 );
265 }
266}