1use serde::{Deserialize, Serialize};
20
21pub const MAX_ARTIFACT_SEND_BYTES: usize = 2 * 1024 * 1024;
24
25pub const TYPE_MARKDOWN: &str = "text/markdown";
27pub const TYPE_HTML: &str = "text/html";
28pub const TYPE_CHART: &str = "application/vnd.byob.chart+json";
29pub const TYPE_PNG: &str = "image/png";
30pub const TYPE_JPEG: &str = "image/jpeg";
31pub const TYPE_TEXT: &str = "text/plain";
33
34pub const MAX_CONTENT_TYPE_CHARS: usize = 100;
36
37pub fn valid_content_type(t: &str) -> bool {
40 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'_'));
41 t.len() <= MAX_CONTENT_TYPE_CHARS && t.split_once('/').is_some_and(|(a, b)| ok(a) && ok(b))
42}
43
44pub fn mime(content_type: &str) -> String {
47 if !valid_content_type(content_type) {
48 "application/octet-stream".to_owned()
49 } else if content_type.starts_with("text/") {
50 format!("{content_type}; charset=utf-8")
51 } else if content_type.ends_with("+json") {
52 "application/json".to_owned()
53 } else {
54 content_type.to_owned()
55 }
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
60#[serde(rename_all = "snake_case")]
61pub enum ArtifactKind {
62 Markdown,
64 Html,
66 Chart,
68 Image,
70 #[serde(other)]
73 Text,
74}
75
76impl ArtifactKind {
77 pub fn content_type(self, filename: &str) -> &'static str {
79 match self {
80 Self::Markdown => TYPE_MARKDOWN,
81 Self::Html => TYPE_HTML,
82 Self::Chart => TYPE_CHART,
83 Self::Image if filename.to_ascii_lowercase().ends_with(".png") => TYPE_PNG,
84 Self::Image => TYPE_JPEG,
85 Self::Text => TYPE_TEXT,
86 }
87 }
88}
89
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92pub struct ArtifactVersion {
93 pub n: u32,
95 pub path: String,
97 pub created_at: i64,
99 #[serde(default)]
101 pub note: String,
102 #[serde(default)]
103 pub size: u64,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct Artifact {
108 pub id: String,
110 pub kind: ArtifactKind,
112 #[serde(default, skip_serializing_if = "String::is_empty")]
115 pub content_type: String,
116 pub title: String,
117 pub filename: String,
119 pub versions: Vec<ArtifactVersion>,
121}
122
123impl Artifact {
124 pub fn content_type(&self) -> &str {
127 if valid_content_type(&self.content_type) { &self.content_type } else { self.kind.content_type(&self.filename) }
128 }
129
130 pub fn latest(&self) -> Option<&ArtifactVersion> {
131 self.versions.iter().max_by_key(|v| v.n)
132 }
133
134 pub fn version(&self, n: u32) -> Option<&ArtifactVersion> {
135 self.versions.iter().find(|v| v.n == n)
136 }
137}
138
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141pub struct ArtifactRef {
142 pub id: String,
143 pub version: u32,
144}
145
146pub fn valid_id(id: &str) -> bool {
148 (1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') && !id.starts_with('-')
149}
150
151pub const THEME_VARS: [&str; 26] = [
155 "--byob-bg",
156 "--byob-surface",
157 "--byob-fg",
158 "--byob-muted",
159 "--byob-accent",
160 "--byob-on-accent",
161 "--byob-border",
162 "--byob-danger",
163 "--byob-success",
164 "--byob-warning",
165 "--byob-link",
166 "--byob-strong",
167 "--byob-faint",
168 "--byob-panel",
169 "--byob-field",
170 "--byob-code-bg",
171 "--byob-code-fg",
172 "--byob-radius",
173 "--byob-chart-a",
174 "--byob-chart-b",
175 "--byob-chart-c",
176 "--byob-chart-d",
177 "--byob-chart-e",
178 "--byob-chart-f",
179 "--byob-chart-g",
180 "--byob-chart-h",
181];
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 #[test]
188 fn content_types_and_their_fallbacks() {
189 let a = |kind, content_type: &str, filename: &str| Artifact {
190 id: "a".into(),
191 kind,
192 content_type: content_type.into(),
193 title: "A".into(),
194 filename: filename.into(),
195 versions: vec![],
196 };
197 assert_eq!(a(ArtifactKind::Text, "application/vnd.acme.sheet+json", "x.sheet").content_type(), "application/vnd.acme.sheet+json");
199 assert_eq!(a(ArtifactKind::Image, "", "p.PNG").content_type(), TYPE_PNG);
201 assert_eq!(a(ArtifactKind::Image, "", "p.jpg").content_type(), TYPE_JPEG);
202 assert_eq!(a(ArtifactKind::Chart, "", "s.chart.json").content_type(), TYPE_CHART);
203 assert_eq!(a(ArtifactKind::Html, "Text/HTML; x=<y>", "a.html").content_type(), TYPE_HTML);
205 assert!(valid_content_type("text/x-python") && !valid_content_type("text") && !valid_content_type("/x"));
206 assert!(!valid_content_type(&format!("a/{}", "b".repeat(100))));
207 assert_eq!(mime(TYPE_MARKDOWN), "text/markdown; charset=utf-8");
208 assert_eq!(mime(TYPE_CHART), "application/json");
209 assert_eq!(mime(TYPE_PNG), "image/png");
210 assert_eq!(mime("bad"), "application/octet-stream");
211 let json = serde_json::to_string(&a(ArtifactKind::Text, "", "n")).unwrap();
213 assert!(!json.contains("content_type"));
214 let back: Artifact = serde_json::from_str(&json).unwrap();
215 assert_eq!(back.content_type(), TYPE_TEXT);
216 }
217
218 #[test]
219 fn ids() {
220 assert!(valid_id("loan-calculator-3f2a"));
221 for bad in ["", "-x", "A", "a/b", "..", "a b", &"x".repeat(65)] {
222 assert!(!valid_id(bad), "{bad}");
223 }
224 }
225
226 #[test]
227 fn latest_and_lookup() {
228 let v = |n| ArtifactVersion { n, path: format!("v{n}"), created_at: 0, note: String::new(), size: 1 };
229 let a = Artifact {
230 id: "a".into(),
231 kind: ArtifactKind::Html,
232 content_type: TYPE_HTML.into(),
233 title: "A".into(),
234 filename: "a.html".into(),
235 versions: vec![v(1), v(3), v(2)],
236 };
237 assert_eq!(a.latest().map(|v| v.n), Some(3));
238 assert_eq!(a.version(2).map(|v| v.path.as_str()), Some("v2"));
239 assert!(a.version(9).is_none());
240 }
241}