1use std::collections::BTreeSet;
11use std::path::{Component, Path, PathBuf};
12
13use serde::{Deserialize, Serialize};
14
15pub const HOST_API_VERSION: &str = "0.15";
22
23#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
25#[non_exhaustive]
26pub struct ApiRange {
32 pub min: String,
34 pub max: String,
36}
37
38impl Default for ApiRange {
39 fn default() -> Self {
40 Self::line(HOST_API_VERSION)
41 }
42}
43
44impl ApiRange {
45 pub fn new(min: impl Into<String>, max: impl Into<String>) -> Self {
47 Self {
48 min: min.into(),
49 max: max.into(),
50 }
51 }
52
53 pub fn line(version: &str) -> Self {
55 let mut parts = version.split('.');
56 let major = parts.next().unwrap_or("0");
57 let minor = parts.next().unwrap_or("0").parse::<u64>().unwrap_or(0);
58 Self {
59 min: format!("{major}.{minor}"),
60 max: format!("{major}.{}", minor + 1),
61 }
62 }
63
64 pub fn allows(&self, version: &str) -> bool {
67 [version, &self.min, &self.max].iter().all(|text| well_formed(text))
69 && compare(version, &self.min) >= 0
70 && compare(version, &self.max) < 0
71 }
72}
73
74fn well_formed(version: &str) -> bool {
76 let mut parts = version.split('.');
77 parts.clone().count() >= 2 && parts.all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
78}
79
80fn compare(left: &str, right: &str) -> i32 {
81 let mut left = left.split('.').map(|part| part.parse::<u64>().unwrap_or(0));
82 let mut right = right.split('.').map(|part| part.parse::<u64>().unwrap_or(0));
83 for _ in 0..2 {
84 let a = left.next().unwrap_or(0);
85 let b = right.next().unwrap_or(0);
86 if a != b {
87 return if a < b { -1 } else { 1 };
88 }
89 }
90 0
91}
92
93fn entry_is_safe(entry: &str) -> bool {
98 if entry.is_empty() || entry.contains('\\') || entry.contains(':') {
99 return false;
100 }
101 Path::new(entry)
102 .components()
103 .all(|component| matches!(component, Component::Normal(_)))
104}
105
106#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
108#[serde(tag = "kind", rename_all = "snake_case")]
109#[non_exhaustive]
110pub enum Capability {
116 Commands,
118 Panels,
120 Viewers,
122 Themes,
124 Keybindings,
126 Settings,
128 ChartLayers,
130 FilesystemRead {
132 prefix: String,
134 },
135 Data,
137 Selection,
139}
140
141impl Capability {
142 pub fn parse(text: &str) -> Result<Self, ManifestError> {
147 let value = match text {
148 "commands" => Self::Commands,
149 "panels" => Self::Panels,
150 "viewers" => Self::Viewers,
151 "themes" => Self::Themes,
152 "keybindings" => Self::Keybindings,
153 "settings" => Self::Settings,
154 "chart-layers" => Self::ChartLayers,
155 "data" => Self::Data,
156 "selection" => Self::Selection,
157 other => {
158 if let Some(prefix) = other.strip_prefix("filesystem:read:") {
159 if prefix.is_empty() {
162 return Err(ManifestError::Capability(other.to_owned()));
163 }
164 Self::FilesystemRead {
165 prefix: prefix.to_owned(),
166 }
167 } else {
168 return Err(ManifestError::Capability(other.to_owned()));
169 }
170 }
171 };
172 Ok(value)
173 }
174}
175
176#[derive(Clone, Debug, Default, Serialize, Deserialize)]
178#[non_exhaustive]
179pub struct ExtensionManifest {
185 pub id: String,
187 pub version: String,
189 pub name: String,
191 pub api: ApiRange,
193 pub entry: String,
195 pub checksum: Option<String>,
197 pub signature: Option<String>,
200 #[serde(default)]
202 pub capabilities: BTreeSet<String>,
203 pub author: Option<String>,
205 pub description: Option<String>,
207}
208
209impl ExtensionManifest {
210 #[cfg(feature = "threads")]
215 pub fn load(directory: impl Into<PathBuf>) -> Result<(Self, PathBuf), ManifestError> {
216 let directory = directory.into();
217 let path = directory.join("extension.json");
218 let text = std::fs::read_to_string(&path).map_err(|error| ManifestError::Io(error.to_string()))?;
219 let manifest: Self = serde_json::from_str(&text).map_err(|error| ManifestError::Json(error.to_string()))?;
220 manifest.validate()?;
221 Ok((manifest, directory))
222 }
223
224 pub fn validate(&self) -> Result<(), ManifestError> {
229 if self.id.is_empty()
231 || self.id.len() > 128
232 || self.id.starts_with('.')
233 || !self
234 .id
235 .bytes()
236 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_'))
237 {
238 return Err(ManifestError::Id(self.id.clone()));
239 }
240 if self.version.split('.').count() < 2 || self.version.split('.').any(|part| part.parse::<u64>().is_err()) {
241 return Err(ManifestError::Version(self.version.clone()));
242 }
243 if !entry_is_safe(&self.entry) {
244 return Err(ManifestError::Entry(self.entry.clone()));
245 }
246 if !self.api.allows(crate::extensions::HOST_API_VERSION) {
247 return Err(ManifestError::Api {
248 min: self.api.min.clone(),
249 max: self.api.max.clone(),
250 });
251 }
252 for capability in &self.capabilities {
253 Capability::parse(capability)?;
254 }
255 Ok(())
256 }
257
258 pub fn parsed_capabilities(&self) -> Result<BTreeSet<Capability>, ManifestError> {
263 self.capabilities.iter().map(|text| Capability::parse(text)).collect()
264 }
265
266 pub fn module_path(&self, directory: &std::path::Path) -> PathBuf {
268 directory.join(&self.entry)
269 }
270}
271
272#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
274#[non_exhaustive]
275pub enum ManifestError {
281 #[error("{0}")]
283 Io(String),
284 #[error("{0}")]
286 Json(String),
287 #[error("invalid extension id `{0}`")]
289 Id(String),
290 #[error("invalid extension version `{0}`")]
292 Version(String),
293 #[error("invalid entry `{0}`")]
295 Entry(String),
296 #[error("host API {host} is outside {min}..{max}", host = crate::extensions::HOST_API_VERSION)]
298 Api {
299 min: String,
301 max: String,
303 },
304 #[error("unknown capability `{0}`")]
306 Capability(String),
307}