use serde::{Deserialize, Serialize};
pub const MAX_ARTIFACT_SEND_BYTES: usize = 2 * 1024 * 1024;
pub const TYPE_MARKDOWN: &str = "text/markdown";
pub const TYPE_HTML: &str = "text/html";
pub const TYPE_CHART: &str = "application/vnd.byob.chart+json";
pub const TYPE_PNG: &str = "image/png";
pub const TYPE_JPEG: &str = "image/jpeg";
pub const TYPE_TEXT: &str = "text/plain";
pub const MAX_CONTENT_TYPE_CHARS: usize = 100;
pub fn valid_content_type(t: &str) -> bool {
let ok = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'+' | b'-' | b'_'));
t.len() <= MAX_CONTENT_TYPE_CHARS && t.split_once('/').is_some_and(|(a, b)| ok(a) && ok(b))
}
pub fn mime(content_type: &str) -> String {
if !valid_content_type(content_type) {
"application/octet-stream".to_owned()
} else if content_type.starts_with("text/") {
format!("{content_type}; charset=utf-8")
} else if content_type.ends_with("+json") {
"application/json".to_owned()
} else {
content_type.to_owned()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArtifactKind {
Markdown,
Html,
Chart,
Image,
#[serde(other)]
Text,
}
impl ArtifactKind {
pub fn content_type(self, filename: &str) -> &'static str {
match self {
Self::Markdown => TYPE_MARKDOWN,
Self::Html => TYPE_HTML,
Self::Chart => TYPE_CHART,
Self::Image if filename.to_ascii_lowercase().ends_with(".png") => TYPE_PNG,
Self::Image => TYPE_JPEG,
Self::Text => TYPE_TEXT,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArtifactVersion {
pub n: u32,
pub path: String,
pub created_at: i64,
#[serde(default)]
pub note: String,
#[serde(default)]
pub size: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Artifact {
pub id: String,
pub kind: ArtifactKind,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub content_type: String,
pub title: String,
pub filename: String,
pub versions: Vec<ArtifactVersion>,
}
impl Artifact {
pub fn content_type(&self) -> &str {
if valid_content_type(&self.content_type) { &self.content_type } else { self.kind.content_type(&self.filename) }
}
pub fn latest(&self) -> Option<&ArtifactVersion> {
self.versions.iter().max_by_key(|v| v.n)
}
pub fn version(&self, n: u32) -> Option<&ArtifactVersion> {
self.versions.iter().find(|v| v.n == n)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArtifactRef {
pub id: String,
pub version: u32,
}
pub fn valid_id(id: &str) -> bool {
(1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') && !id.starts_with('-')
}
pub const THEME_VARS: [&str; 26] = [
"--byob-bg",
"--byob-surface",
"--byob-fg",
"--byob-muted",
"--byob-accent",
"--byob-on-accent",
"--byob-border",
"--byob-danger",
"--byob-success",
"--byob-warning",
"--byob-link",
"--byob-strong",
"--byob-faint",
"--byob-panel",
"--byob-field",
"--byob-code-bg",
"--byob-code-fg",
"--byob-radius",
"--byob-chart-a",
"--byob-chart-b",
"--byob-chart-c",
"--byob-chart-d",
"--byob-chart-e",
"--byob-chart-f",
"--byob-chart-g",
"--byob-chart-h",
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn content_types_and_their_fallbacks() {
let a = |kind, content_type: &str, filename: &str| Artifact {
id: "a".into(),
kind,
content_type: content_type.into(),
title: "A".into(),
filename: filename.into(),
versions: vec![],
};
assert_eq!(a(ArtifactKind::Text, "application/vnd.acme.sheet+json", "x.sheet").content_type(), "application/vnd.acme.sheet+json");
assert_eq!(a(ArtifactKind::Image, "", "p.PNG").content_type(), TYPE_PNG);
assert_eq!(a(ArtifactKind::Image, "", "p.jpg").content_type(), TYPE_JPEG);
assert_eq!(a(ArtifactKind::Chart, "", "s.chart.json").content_type(), TYPE_CHART);
assert_eq!(a(ArtifactKind::Html, "Text/HTML; x=<y>", "a.html").content_type(), TYPE_HTML);
assert!(valid_content_type("text/x-python") && !valid_content_type("text") && !valid_content_type("/x"));
assert!(!valid_content_type(&format!("a/{}", "b".repeat(100))));
assert_eq!(mime(TYPE_MARKDOWN), "text/markdown; charset=utf-8");
assert_eq!(mime(TYPE_CHART), "application/json");
assert_eq!(mime(TYPE_PNG), "image/png");
assert_eq!(mime("bad"), "application/octet-stream");
let json = serde_json::to_string(&a(ArtifactKind::Text, "", "n")).unwrap();
assert!(!json.contains("content_type"));
let back: Artifact = serde_json::from_str(&json).unwrap();
assert_eq!(back.content_type(), TYPE_TEXT);
}
#[test]
fn ids() {
assert!(valid_id("loan-calculator-3f2a"));
for bad in ["", "-x", "A", "a/b", "..", "a b", &"x".repeat(65)] {
assert!(!valid_id(bad), "{bad}");
}
}
#[test]
fn latest_and_lookup() {
let v = |n| ArtifactVersion { n, path: format!("v{n}"), created_at: 0, note: String::new(), size: 1 };
let a = Artifact {
id: "a".into(),
kind: ArtifactKind::Html,
content_type: TYPE_HTML.into(),
title: "A".into(),
filename: "a.html".into(),
versions: vec![v(1), v(3), v(2)],
};
assert_eq!(a.latest().map(|v| v.n), Some(3));
assert_eq!(a.version(2).map(|v| v.path.as_str()), Some("v2"));
assert!(a.version(9).is_none());
}
}