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 #[serde(default, skip_serializing_if = "String::is_empty")]
107 pub turn: String,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111pub struct Artifact {
112 pub id: String,
114 pub kind: ArtifactKind,
116 #[serde(default, skip_serializing_if = "String::is_empty")]
119 pub content_type: String,
120 pub title: String,
121 pub filename: String,
123 pub versions: Vec<ArtifactVersion>,
125 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
128 pub network: bool,
129}
130
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
134pub struct LibraryItem {
135 pub chat: String,
136 pub chat_title: String,
137 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub workspace: Option<String>,
140 pub artifact: Artifact,
141 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
143 pub chat_gone: bool,
144 #[serde(default, skip_serializing_if = "Option::is_none")]
146 pub live: Option<String>,
147}
148
149impl Artifact {
150 pub fn content_type(&self) -> &str {
153 if valid_content_type(&self.content_type) { &self.content_type } else { self.kind.content_type(&self.filename) }
154 }
155
156 pub fn latest(&self) -> Option<&ArtifactVersion> {
157 self.versions.iter().max_by_key(|v| v.n)
158 }
159
160 pub fn version(&self, n: u32) -> Option<&ArtifactVersion> {
161 self.versions.iter().find(|v| v.n == n)
162 }
163}
164
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167pub struct ArtifactRef {
168 pub id: String,
169 pub version: u32,
170}
171
172pub fn valid_id(id: &str) -> bool {
174 (1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') && !id.starts_with('-')
175}
176
177pub const THEME_VARS: [&str; 26] = [
181 "--byob-bg",
182 "--byob-surface",
183 "--byob-fg",
184 "--byob-muted",
185 "--byob-accent",
186 "--byob-on-accent",
187 "--byob-border",
188 "--byob-danger",
189 "--byob-success",
190 "--byob-warning",
191 "--byob-link",
192 "--byob-strong",
193 "--byob-faint",
194 "--byob-panel",
195 "--byob-field",
196 "--byob-code-bg",
197 "--byob-code-fg",
198 "--byob-radius",
199 "--byob-chart-a",
200 "--byob-chart-b",
201 "--byob-chart-c",
202 "--byob-chart-d",
203 "--byob-chart-e",
204 "--byob-chart-f",
205 "--byob-chart-g",
206 "--byob-chart-h",
207];
208
209#[cfg(test)]
210mod tests {
211 use super::*;
212
213 #[test]
214 fn content_types_and_their_fallbacks() {
215 let a = |kind, content_type: &str, filename: &str| Artifact {
216 id: "a".into(),
217 kind,
218 content_type: content_type.into(),
219 title: "A".into(),
220 filename: filename.into(),
221 versions: vec![],
222 network: false,
223 };
224 assert_eq!(a(ArtifactKind::Text, "application/vnd.acme.sheet+json", "x.sheet").content_type(), "application/vnd.acme.sheet+json");
226 assert_eq!(a(ArtifactKind::Image, "", "p.PNG").content_type(), TYPE_PNG);
228 assert_eq!(a(ArtifactKind::Image, "", "p.jpg").content_type(), TYPE_JPEG);
229 assert_eq!(a(ArtifactKind::Chart, "", "s.chart.json").content_type(), TYPE_CHART);
230 assert_eq!(a(ArtifactKind::Html, "Text/HTML; x=<y>", "a.html").content_type(), TYPE_HTML);
232 assert!(valid_content_type("text/x-python") && !valid_content_type("text") && !valid_content_type("/x"));
233 assert!(!valid_content_type(&format!("a/{}", "b".repeat(100))));
234 assert_eq!(mime(TYPE_MARKDOWN), "text/markdown; charset=utf-8");
235 assert_eq!(mime(TYPE_CHART), "application/json");
236 assert_eq!(mime(TYPE_PNG), "image/png");
237 assert_eq!(mime("bad"), "application/octet-stream");
238 let json = serde_json::to_string(&a(ArtifactKind::Text, "", "n")).unwrap();
240 assert!(!json.contains("content_type"));
241 let back: Artifact = serde_json::from_str(&json).unwrap();
242 assert_eq!(back.content_type(), TYPE_TEXT);
243 }
244
245 #[test]
246 fn ids() {
247 assert!(valid_id("loan-calculator-3f2a"));
248 for bad in ["", "-x", "A", "a/b", "..", "a b", &"x".repeat(65)] {
249 assert!(!valid_id(bad), "{bad}");
250 }
251 }
252
253 #[test]
254 fn latest_and_lookup() {
255 let v = |n| ArtifactVersion { n, path: format!("v{n}"), created_at: 0, note: String::new(), size: 1, turn: String::new() };
256 let a = Artifact {
257 id: "a".into(),
258 kind: ArtifactKind::Html,
259 content_type: TYPE_HTML.into(),
260 title: "A".into(),
261 filename: "a.html".into(),
262 versions: vec![v(1), v(3), v(2)],
263 network: false,
264 };
265 assert_eq!(a.latest().map(|v| v.n), Some(3));
266 assert_eq!(a.version(2).map(|v| v.path.as_str()), Some("v2"));
267 assert!(a.version(9).is_none());
268 }
269}