1use serde::{Deserialize, Serialize};
21use serde_json::{Map, Value};
22
23use crate::tree::{Event, Node, Patch};
24
25pub const CAP_VIEW_SITES: &str = "view_sites";
28
29pub const MAX_VIEWS: usize = 16;
31pub const MAX_VIEW_ID_CHARS: usize = 48;
33pub const MAX_VIEW_KEY_CHARS: usize = 128;
35pub const MAX_EVENT_BYTES: usize = 256 * 1024;
37pub const MAX_TITLE_CHARS: usize = 80;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum Site {
44 Pane,
46 Settings,
48 Status,
50 Card,
52 Artifact,
56 #[serde(other)]
58 Other,
59}
60
61impl Site {
62 pub const ALL: [Site; 5] = [Site::Pane, Site::Settings, Site::Status, Site::Card, Site::Artifact];
63
64 pub fn label(self) -> &'static str {
65 match self {
66 Self::Pane => "pane",
67 Self::Settings => "settings",
68 Self::Status => "status",
69 Self::Card => "card",
70 Self::Artifact => "artifact",
71 Self::Other => "other",
72 }
73 }
74
75 pub fn parse(s: &str) -> Option<Self> {
76 Self::ALL.into_iter().find(|x| x.label() == s)
77 }
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82pub struct ViewDecl {
83 pub id: String,
85 pub site: Site,
86 #[serde(default)]
87 pub title: String,
88 #[serde(default, skip_serializing_if = "String::is_empty")]
90 pub icon: String,
91 #[serde(default, skip_serializing_if = "String::is_empty")]
94 pub html: String,
95}
96
97#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
99pub struct ViewRef {
100 pub plugin: String,
101 pub view: String,
103 #[serde(default, skip_serializing_if = "String::is_empty")]
105 pub key: String,
106}
107
108impl ViewRef {
109 pub fn new(plugin: impl Into<String>, view: impl Into<String>, key: impl Into<String>) -> Self {
110 Self { plugin: plugin.into(), view: view.into(), key: key.into() }
111 }
112
113 pub fn check(&self) -> Result<(), String> {
115 if !byob_types::config::plugin_id_ok(&self.plugin) {
116 return Err(format!("{:?} isn't a plugin id", self.plugin.chars().take(60).collect::<String>()));
117 }
118 if !view_id_ok(&self.view) {
119 return Err(format!("{:?} isn't a view id", self.view.chars().take(60).collect::<String>()));
120 }
121 if self.key.chars().count() > MAX_VIEW_KEY_CHARS {
122 return Err(format!("a view key can be at most {MAX_VIEW_KEY_CHARS} characters"));
123 }
124 Ok(())
125 }
126}
127
128pub fn artifact_key(id: &str, version: u32) -> String {
130 format!("{id}@{version}")
131}
132
133pub fn parse_artifact_key(key: &str) -> Option<(&str, u32)> {
135 let (id, v) = key.rsplit_once('@')?;
136 let v: u32 = v.parse().ok()?;
137 (crate::artifact::valid_id(id) && v > 0).then_some((id, v))
138}
139
140pub fn view_id_ok(id: &str) -> bool {
142 (1..=MAX_VIEW_ID_CHARS).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-'))
143}
144
145#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
152pub struct LiveView {
153 pub view: ViewRef,
154 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub tree: Option<Node>,
156 #[serde(default, skip_serializing_if = "Vec::is_empty")]
157 pub patch: Vec<Patch>,
158 #[serde(default, skip_serializing_if = "Map::is_empty")]
159 pub values: Map<String, Value>,
160 #[serde(default, skip_serializing_if = "Option::is_none")]
161 pub error: Option<String>,
162 #[serde(default, skip_serializing_if = "Vec::is_empty")]
163 pub faults: Vec<String>,
164 #[serde(default, skip_serializing_if = "is_false")]
165 pub reset: bool,
166}
167
168fn is_false(b: &bool) -> bool {
169 !*b
170}
171
172pub(crate) fn check_sizes(msg: &crate::ClientMsg) -> Result<(), String> {
174 use crate::ClientMsg;
175 match msg {
176 ClientMsg::OpenView { view } | ClientMsg::CloseView { view } => view.check(),
177 ClientMsg::ViewEvent { view, event } => {
178 view.check()?;
179 check_event(event)
180 }
181 _ => Ok(()),
182 }
183}
184
185fn check_event(e: &Event) -> Result<(), String> {
186 if e.action.chars().count() > crate::tree::MAX_TEXT_CHARS {
187 return Err("the event's action is too long".into());
188 }
189 if e.values.len() > crate::tree::MAX_VALUES {
190 return Err(format!("an event carries at most {} values", crate::tree::MAX_VALUES));
191 }
192 let size = serde_json::to_string(e).map_or(usize::MAX, |s| s.len());
193 if size > MAX_EVENT_BYTES {
194 return Err(format!("event too large ({size} bytes, at most {MAX_EVENT_BYTES})"));
195 }
196 Ok(())
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202 use crate::tree::{Kind, Target};
203 use crate::{ClientMsg, ServerMsg};
204
205 #[test]
206 fn view_messages_round_trip_and_are_checked() {
207 let r = ViewRef::new("todo", "list", "");
208 let event = Event { action: "add".into(), values: serde_json::json!({"new": "milk"}).as_object().cloned().unwrap_or_default(), edit: None, grid: None };
209 for m in [ClientMsg::OpenView { view: r.clone() }, ClientMsg::CloseView { view: r.clone() }, ClientMsg::ViewEvent { view: r.clone(), event }] {
210 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m, "{}", m.to_json());
211 assert!(m.check_sizes().is_ok());
212 }
213 assert_eq!(ClientMsg::OpenView { view: r.clone() }.to_json(), r#"{"type":"open_view","view":{"plugin":"todo","view":"list"}}"#);
214 for bad in [ViewRef::new("Todo", "list", ""), ViewRef::new("todo", "a b", ""), ViewRef::new("todo", "list", "k".repeat(MAX_VIEW_KEY_CHARS + 1))] {
215 assert!(ClientMsg::OpenView { view: bad }.check_sizes().is_err());
216 }
217 let big =
218 Event { action: "x".into(), values: [("t".to_owned(), Value::String("x".repeat(MAX_EVENT_BYTES)))].into_iter().collect(), edit: None, grid: None };
219 assert!(ClientMsg::ViewEvent { view: r.clone(), event: big }.check_sizes().is_err());
220
221 let tree = Node::new(Kind::Text { text: "3 left".into(), style: Default::default(), tone: Default::default() });
222 let msgs = [
223 ServerMsg::LiveView(LiveView { view: r.clone(), tree: Some(tree), faults: vec!["/x: y".into()], ..Default::default() }),
224 ServerMsg::LiveView(LiveView {
225 view: r.clone(),
226 patch: vec![Patch::Remove { at: Target::key("a") }],
227 values: serde_json::json!({"new": ""}).as_object().cloned().unwrap_or_default(),
228 ..Default::default()
229 }),
230 ServerMsg::LiveView(LiveView { view: r.clone(), error: Some("no backend".into()), ..Default::default() }),
231 ServerMsg::LiveView(LiveView { view: r, reset: true, ..Default::default() }),
232 ];
233 for m in msgs {
234 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m, "{}", m.to_json());
235 }
236 }
237
238 #[test]
239 fn sites_and_ids() {
240 for s in Site::ALL {
241 assert_eq!(Site::parse(s.label()), Some(s));
242 }
243 assert_eq!(serde_json::from_str::<Site>(r#""sidebar""#).unwrap(), Site::Other);
244 assert!(view_id_ok("todo_list-2") && !view_id_ok("") && !view_id_ok("Todo") && !view_id_ok(&"x".repeat(49)));
245 let d: ViewDecl = serde_json::from_str(r#"{"id":"list","site":"pane"}"#).unwrap();
247 assert_eq!((d.title.as_str(), d.icon.as_str()), ("", ""));
248 }
249
250 #[test]
253 fn minor_3_is_compatible_with_minor_2() {
254 let card = crate::PluginCard {
255 plugin: "p".into(),
256 scope: crate::PluginScope::Chat,
257 action: crate::PluginAction::Made,
258 tools: vec![],
259 added: vec![],
260 removed: vec![],
261 test: None,
262 problems: vec![],
263 missing_settings: vec![],
264 };
265 let v = crate::View::of(&card);
266 assert!(!serde_json::to_string(&v).unwrap().contains("owner"));
267 let old: crate::View = serde_json::from_str(r#"{"kind":"byob.tree","v":1,"data":{"type":"text","text":"x"},"fallback":"x"}"#).unwrap();
268 assert_eq!(old.owner, None);
269 let mut owned = old.clone();
270 owned.owner = Some(ViewRef::new("todo", "item", "3"));
271 let back: crate::View = serde_json::from_str(&serde_json::to_string(&owned).unwrap()).unwrap();
272 assert_eq!(back, owned);
273 let lv = ServerMsg::LiveView(LiveView { view: ViewRef::new("todo", "list", ""), reset: true, ..Default::default() }).to_json();
275 assert!(lv.starts_with(r#"{"type":"live_view""#), "{lv}");
276 }
277}