use serde_json::Value;
use super::http::{Http, host_of, unreachable};
use super::{Catalog, CatalogEntry, EntryKind, Publisher};
use crate::error::CoreError;
pub const MIN_QUERY: usize = 2;
pub(crate) const PING_QUERY: &str = "skills";
const MAX_TEXT: usize = 200;
pub(crate) const WEBSITE_PROBLEM: &str = "this skill comes from a website, not a GitHub \
repository; Surjection installs skills.sh entries from GitHub repositories only";
fn clean(text: &str) -> Option<String> {
let text: String = text
.chars()
.filter(|c| !c.is_control())
.take(MAX_TEXT)
.collect();
let text = text.trim();
(!text.is_empty()).then(|| text.to_owned())
}
fn valid_part(part: &str) -> bool {
!part.is_empty()
&& part != "."
&& part != ".."
&& part
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}
pub(crate) fn github_source(id: &str) -> Option<(&str, &str, &str)> {
let mut parts = id.split('/');
let (owner, repo, skill) = (parts.next()?, parts.next()?, parts.next()?);
(parts.next().is_none()
&& [owner, repo, skill].iter().all(|p| valid_part(p))
&& !owner.contains('.'))
.then_some((owner, repo, skill))
}
pub(crate) fn page_url(catalog: &Catalog, id: &str) -> String {
format!("{}/{id}", catalog.url.trim_end_matches('/'))
}
pub(crate) fn entry_for(
catalog: &Catalog,
id: &str,
name: Option<String>,
source: Option<String>,
installs: Option<u64>,
) -> Option<CatalogEntry> {
if id.len() > MAX_TEXT || id.split('/').count() < 2 || !id.split('/').all(valid_part) {
return None;
}
let github = github_source(id);
let source = source
.or_else(|| id.rsplit_once('/').map(|(source, _)| source.to_owned()))
.unwrap_or_default();
let skill = id.rsplit('/').next().unwrap_or(id).to_owned();
Some(CatalogEntry {
catalog: catalog.id.clone(),
id: id.to_owned(),
kind: EntryKind::Skill,
name: name.unwrap_or_else(|| skill.clone()),
description: None,
version: None,
updated_at: None,
deprecated: false,
status_message: None,
publisher: Some(Publisher {
name: source,
checked: None,
}),
official: false,
warning: None,
repository: github.map(|(owner, repo, _)| format!("https://github.com/{owner}/{repo}")),
website: Some(page_url(catalog, id)),
license: None,
transports: Vec::new(),
packages: Vec::new(),
remotes: Vec::new(),
required_secrets: Vec::new(),
pinned: false,
git_ref: None,
commit: None,
path: None,
skills: vec![skill],
servers: Vec::new(),
not_imported: Vec::new(),
source: None,
install_mcp: false,
install_skill: github.is_some(),
problem: github.is_none().then(|| WEBSITE_PROBLEM.to_owned()),
server_json: None,
mcp_servers: None,
installs,
})
}
fn parse_item(catalog: &Catalog, item: &Value) -> Option<CatalogEntry> {
let text = |key: &str| item.get(key).and_then(Value::as_str);
let id = text("id")?;
let source = text("source")?;
let name = clean(text("name")?)?;
if source.len() > MAX_TEXT
|| !source.split('/').all(valid_part)
|| !id.starts_with(&format!("{source}/"))
{
return None;
}
let installs = item.get("installs").and_then(Value::as_u64);
entry_for(catalog, id, Some(name), Some(source.to_owned()), installs)
}
pub(crate) fn search(
http: &dyn Http,
catalog: &Catalog,
query: &str,
) -> Result<Vec<CatalogEntry>, CoreError> {
let base = catalog.url.trim_end_matches('/');
let mut url = url::Url::parse(&format!("{base}/api/search"))
.map_err(|_| unreachable(&catalog.url, "its address is not valid"))?;
url.query_pairs_mut().append_pair("q", query.trim());
let url = String::from(url);
let response = http.get(&url)?;
let site = |url: &str| host_of(url).trim_start_matches("www.").to_owned();
if let Some(answered) = &response.url
&& site(answered) != site(&url)
{
return Err(unreachable(&url, "it redirected to another site"));
}
match response.status {
200..=299 => {}
429 | 403 => {
return Err(unreachable(
&url,
"it is limiting requests from this network; try again later",
));
}
status => return Err(unreachable(&url, format!("it answered HTTP {status}"))),
}
let unexpected = || {
CoreError::new(
crate::error::ErrorCode::CatalogUnreachable,
"skills.sh answered in an unexpected format",
)
};
let json: Value = serde_json::from_slice(&response.body).map_err(|_| unexpected())?;
let items = json
.get("skills")
.and_then(Value::as_array)
.ok_or_else(unexpected)?;
let mut entries: Vec<CatalogEntry> = Vec::new();
for entry in items.iter().filter_map(|item| parse_item(catalog, item)) {
if !entries.iter().any(|known| known.id == entry.id) {
entries.push(entry);
}
}
Ok(entries)
}