Skip to main content

byob_protocol/tree/
decode.rs

1//! Tolerant decoding of untrusted trees, patches and replies: limits applied, unknown nodes
2//! shown as their fallback, everything fixed reported as a [`Fault`].
3
4use std::fmt::Write as _;
5
6use serde_json::{Map, Value};
7
8use std::collections::BTreeMap;
9
10use super::{
11    Fault, GridBlock, GridCell, GridRange, Kind, MAX_CELL_CHARS, MAX_DEPTH, MAX_FAULTS, MAX_GRID_BLOCKS, MAX_GRID_CELLS, MAX_GRID_COLS, MAX_GRID_ROWS,
12    MAX_KEY_CHARS, MAX_NODES, MAX_OPTIONS, MAX_PATCHES, MAX_SHAPES, MAX_TABLE_COLUMNS, MAX_TABLE_ROWS, MAX_TEXT_CHARS, MAX_VALUES, Node, Patch, Reply, Shape,
13    TableColumn, Target, TextStyle, Tone, pointer_segment,
14};
15
16/// Decode an untrusted tree. Never fails: what can't be shown is left out (or shown as its
17/// `fallback`) and listed in the faults. A root that isn't a node is an empty column.
18pub fn decode(v: Value) -> (Node, Vec<Fault>) {
19    let mut d = Decoder::default();
20    let node = d.node(v, &mut String::new(), 1).unwrap_or_else(|| Node::new(Kind::Column { children: Vec::new() }));
21    (node, d.finish())
22}
23
24/// [`decode`] from JSON text (text that isn't JSON is an empty column and one fault).
25pub fn decode_str(s: &str) -> (Node, Vec<Fault>) {
26    match serde_json::from_str::<Value>(s) {
27        Ok(v) => decode(v),
28        Err(e) => (Node::new(Kind::Column { children: Vec::new() }), vec![Fault::new("", format!("not JSON: {e}"))]),
29    }
30}
31
32pub(crate) fn reply(v: Value) -> (Reply, Vec<Fault>) {
33    let mut d = Decoder::default();
34    let Value::Object(mut o) = v else {
35        return (Reply::default(), vec![Fault::new("", "a reply must be a JSON object")]);
36    };
37    let mut path = String::new();
38    let view = match o.remove("view") {
39        None | Some(Value::Null) => None,
40        Some(v) => {
41            path.push_str("/view");
42            let node = d.node(v, &mut path, 1);
43            if node.is_none() {
44                d.fault("/view", "the view didn't decode, so the old one stays");
45            }
46            node
47        }
48    };
49    let mut patch = Vec::new();
50    match o.remove("patch") {
51        None | Some(Value::Null) => {}
52        Some(Value::Array(list)) => {
53            if list.len() > MAX_PATCHES {
54                d.fault("/patch", format!("at most {MAX_PATCHES} patches; the rest are left out"));
55            }
56            for (i, p) in list.into_iter().take(MAX_PATCHES).enumerate() {
57                path.clear();
58                let _ = write!(path, "/patch/{i}");
59                patch.extend(d.patch(p, &mut path));
60            }
61        }
62        Some(_) => d.fault("/patch", "patch must be a list of patches"),
63    }
64    let values = d.values(o.remove("values"), "/values");
65    (Reply { view, patch, values }, d.finish())
66}
67
68/// Decoding state: the faults so far and the node budget.
69#[derive(Default)]
70pub(crate) struct Decoder {
71    faults: Vec<Fault>,
72    /// Faults past [`MAX_FAULTS`].
73    dropped: usize,
74    /// Nodes decoded (or in the tree being patched); at [`MAX_NODES`] the rest are dropped.
75    pub(crate) nodes: usize,
76    told_too_many: bool,
77}
78
79impl Decoder {
80    pub(crate) fn fault(&mut self, path: &str, message: impl Into<String>) {
81        if self.faults.len() < MAX_FAULTS {
82            self.faults.push(Fault::new(path, message));
83        } else {
84            self.dropped += 1;
85        }
86    }
87
88    pub(crate) fn finish(mut self) -> Vec<Fault> {
89        if self.dropped > 0 {
90            self.faults.push(Fault::new("", format!("… and {} more problems", self.dropped)));
91        }
92        self.faults
93    }
94
95    /// Decode one node at `depth` (the root is 1); `None`: nothing to show.
96    pub(crate) fn node(&mut self, v: Value, path: &mut String, depth: usize) -> Option<Node> {
97        let Value::Object(mut o) = v else {
98            self.fault(path, "a node must be an object like {\"type\": \"text\", \"text\": \"hi\"}");
99            return None;
100        };
101        if depth > MAX_DEPTH {
102            self.fault(path, format!("nested too deep (at most {MAX_DEPTH} levels); left out"));
103            return None;
104        }
105        if self.nodes >= MAX_NODES {
106            if !self.told_too_many {
107                self.told_too_many = true;
108                self.fault(path, format!("too many nodes (at most {MAX_NODES}); the rest are left out"));
109            }
110            return None;
111        }
112        self.nodes += 1;
113        let key = match o.remove("key") {
114            None | Some(Value::Null) => None,
115            Some(k) => self.key(k, path),
116        };
117        let fallback = match o.remove("fallback") {
118            Some(Value::String(s)) => Some(s),
119            _ => None,
120        };
121        let ty = match o.get("type") {
122            Some(Value::String(s)) => s.clone(),
123            _ => {
124                self.fault(path, "a node needs a \"type\" (column, row, card, text, button, …)");
125                return self.fallback(key, fallback);
126            }
127        };
128        let kind = match ty.as_str() {
129            "column" | "row" | "card" => {
130                let children = self.children(o.remove("children"), path, depth);
131                match ty.as_str() {
132                    "column" => Kind::Column { children },
133                    "row" => Kind::Row { children },
134                    _ => {
135                        let title = match o.remove("title") {
136                            None | Some(Value::Null) => String::new(),
137                            Some(Value::String(s)) => s,
138                            Some(other @ (Value::Number(_) | Value::Bool(_))) => other.to_string(),
139                            Some(_) => {
140                                self.fault(&format!("{path}/title"), "title must be text");
141                                String::new()
142                            }
143                        };
144                        Kind::Card { title, children }
145                    }
146                }
147            }
148            "chart" => match o.remove("spec") {
149                Some(spec) => match byob_types::chart::validate(&spec) {
150                    Ok(spec) => Kind::Chart { spec },
151                    Err(e) => {
152                        self.fault(&format!("{path}/spec"), e);
153                        return self.fallback(key, fallback);
154                    }
155                },
156                None => {
157                    self.fault(path, "a chart needs a \"spec\" (version, type, title, x, series, data)");
158                    return self.fallback(key, fallback);
159                }
160            },
161            "table" => {
162                let rows = o.remove("rows");
163                o.insert("rows".into(), Value::Array(Vec::new()));
164                match self.leaf(&ty, o, path) {
165                    Some(Kind::Table { name, mut columns, height, select, .. }) => {
166                        if columns.len() > MAX_TABLE_COLUMNS {
167                            self.fault(&format!("{path}/columns"), format!("at most {MAX_TABLE_COLUMNS} columns; the rest are left out"));
168                            columns.truncate(MAX_TABLE_COLUMNS);
169                        }
170                        let rows = self.rows(rows, &columns, path);
171                        Kind::Table { name, columns, rows, height, select }
172                    }
173                    _ => return self.fallback(key, fallback),
174                }
175            }
176            "canvas" => {
177                let shapes = o.remove("shapes");
178                o.insert("shapes".into(), Value::Array(Vec::new()));
179                match self.leaf(&ty, o, path) {
180                    Some(Kind::Canvas { width, height, action, .. }) => Kind::Canvas { width, height, shapes: self.shapes(shapes, path), action },
181                    _ => return self.fallback(key, fallback),
182                }
183            }
184            "grid" => self.grid(o, path),
185            "text" | "markdown" | "chip" | "button" | "input" | "toggle" | "select" | "progress" | "separator" | "image" => match self.leaf(&ty, o, path) {
186                Some(kind) => kind,
187                None => return self.fallback(key, fallback),
188            },
189            other => {
190                let what = if fallback.is_some() { "showing its fallback" } else { "left out (give it a \"fallback\" text for older clients)" };
191                self.fault(path, format!("unknown node type {:?}; {what}", cut_str(other, MAX_KEY_CHARS)));
192                return self.fallback(key, fallback);
193            }
194        };
195        let mut node = Node { key, kind };
196        self.sanitize(&mut node.kind, path);
197        Some(node)
198    }
199
200    /// A leaf's fields through serde (children, rows and shapes already taken out).
201    fn leaf(&mut self, ty: &str, o: Map<String, Value>, path: &str) -> Option<Kind> {
202        match serde_json::from_value::<Kind>(Value::Object(o)) {
203            Ok(kind) => Some(kind),
204            Err(e) => {
205                self.fault(path, format!("{ty}: {e}"));
206                None
207            }
208        }
209    }
210
211    fn fallback(&mut self, key: Option<String>, fallback: Option<String>) -> Option<Node> {
212        let mut text = fallback?;
213        cut(&mut text);
214        Some(Node { key, kind: Kind::Text { text, style: TextStyle::Body, tone: Tone::Dim } })
215    }
216
217    pub(crate) fn key(&mut self, k: Value, path: &str) -> Option<String> {
218        let k = match k {
219            Value::String(s) => s,
220            Value::Number(n) => n.to_string(),
221            _ => {
222                self.fault(&format!("{path}/key"), "a key must be text");
223                return None;
224            }
225        };
226        if k.chars().count() > MAX_KEY_CHARS {
227            self.fault(&format!("{path}/key"), format!("a key can be at most {MAX_KEY_CHARS} characters"));
228            return None;
229        }
230        Some(k)
231    }
232
233    pub(crate) fn children(&mut self, v: Option<Value>, path: &mut String, depth: usize) -> Vec<Node> {
234        let list = match v {
235            None | Some(Value::Null) => return Vec::new(),
236            Some(Value::Array(list)) => list,
237            Some(_) => {
238                self.fault(&format!("{path}/children"), "children must be a list of nodes");
239                return Vec::new();
240            }
241        };
242        let at = path.len();
243        let mut out = Vec::with_capacity(list.len().min(MAX_NODES));
244        for (i, c) in list.into_iter().enumerate() {
245            let _ = write!(path, "/children/{i}");
246            out.extend(self.node(c, path, depth + 1));
247            path.truncate(at);
248        }
249        out
250    }
251
252    /// Table rows: lists of cells in column order, or objects by column key.
253    pub(crate) fn rows(&mut self, v: Option<Value>, columns: &[TableColumn], path: &str) -> Vec<Vec<Value>> {
254        let mut list = match v {
255            None | Some(Value::Null) => return Vec::new(),
256            Some(Value::Array(list)) => list,
257            Some(_) => {
258                self.fault(&format!("{path}/rows"), "rows must be a list of rows (each a list of cells)");
259                return Vec::new();
260            }
261        };
262        if list.len() > MAX_TABLE_ROWS {
263            self.fault(&format!("{path}/rows"), format!("at most {MAX_TABLE_ROWS} rows; the rest are left out"));
264            list.truncate(MAX_TABLE_ROWS);
265        }
266        list.into_iter().enumerate().map(|(i, r)| self.row(r, columns, path, i)).collect()
267    }
268
269    pub(crate) fn row(&mut self, r: Value, columns: &[TableColumn], path: &str, i: usize) -> Vec<Value> {
270        match r {
271            Value::Array(mut cells) => {
272                cells.truncate(MAX_TABLE_COLUMNS);
273                cells.into_iter().map(cell).collect()
274            }
275            Value::Object(mut by_key) => columns.iter().map(|c| by_key.remove(&c.key).map(cell).unwrap_or(Value::Null)).collect(),
276            _ => {
277                self.fault(&format!("{path}/rows/{i}"), "a row must be a list of cells");
278                Vec::new()
279            }
280        }
281    }
282
283    pub(crate) fn shapes(&mut self, v: Option<Value>, path: &str) -> Vec<Shape> {
284        let mut list = match v {
285            None | Some(Value::Null) => return Vec::new(),
286            Some(Value::Array(list)) => list,
287            Some(_) => {
288                self.fault(&format!("{path}/shapes"), "shapes must be a list");
289                return Vec::new();
290            }
291        };
292        if list.len() > MAX_SHAPES {
293            self.fault(&format!("{path}/shapes"), format!("at most {MAX_SHAPES} shapes; the rest are left out"));
294            list.truncate(MAX_SHAPES);
295        }
296        list.into_iter().enumerate().filter_map(|(i, s)| self.shape(s, &format!("{path}/shapes/{i}"))).collect()
297    }
298
299    pub(crate) fn shape(&mut self, s: Value, path: &str) -> Option<Shape> {
300        match serde_json::from_value::<Shape>(s) {
301            Ok(mut s) => {
302                sanitize_shape(&mut s);
303                Some(s)
304            }
305            Err(e) => {
306                self.fault(path, format!("shape (rect, circle, line or text): {e}"));
307                None
308            }
309        }
310    }
311
312    pub(crate) fn values(&mut self, v: Option<Value>, path: &str) -> Map<String, Value> {
313        match v {
314            None | Some(Value::Null) => Map::new(),
315            Some(Value::Object(mut m)) => {
316                if m.len() > MAX_VALUES {
317                    self.fault(path, format!("at most {MAX_VALUES} values"));
318                    m = m.into_iter().take(MAX_VALUES).collect();
319                }
320                m
321            }
322            Some(_) => {
323                self.fault(path, "values must be an object of field name → value");
324                Map::new()
325            }
326        }
327    }
328
329    /// A whole number field up to `max` (over it: `max`, with a fault); `None` if absent or
330    /// not a number (with a fault).
331    fn uint(&mut self, v: Option<Value>, path: &str, max: u32) -> Option<u32> {
332        let v = match v {
333            None | Some(Value::Null) => return None,
334            Some(v) => v,
335        };
336        let n = match v.as_u64() {
337            Some(n) => n,
338            None => match v.as_f64() {
339                Some(f) if f.is_finite() && f >= 0.0 => f.floor() as u64,
340                _ => {
341                    self.fault(path, "must be a whole number from 0");
342                    return None;
343                }
344            },
345        };
346        if n > u64::from(max) {
347            self.fault(path, format!("at most {max}"));
348            return Some(max);
349        }
350        u32::try_from(n).ok()
351    }
352
353    fn number(&mut self, v: Option<Value>, path: &str, lo: f32, hi: f32) -> Option<f32> {
354        match v {
355            None | Some(Value::Null) => None,
356            Some(v) => match v.as_f64().map(|f| f as f32).filter(|f| f.is_finite()) {
357                Some(f) => Some(f.clamp(lo, hi)),
358                None => {
359                    self.fault(path, "must be a number");
360                    None
361                }
362            },
363        }
364    }
365
366    fn flag(&mut self, v: Option<Value>, path: &str, default: bool) -> bool {
367        match v {
368            None | Some(Value::Null) => default,
369            Some(Value::Bool(b)) => b,
370            Some(_) => {
371                self.fault(path, "must be true or false");
372                default
373            }
374        }
375    }
376
377    /// A grid, field by field: what's wrong is fixed or left out, the grid always decodes.
378    pub(crate) fn grid(&mut self, mut o: Map<String, Value>, path: &str) -> Kind {
379        let name = match o.remove("name") {
380            None | Some(Value::Null) => String::new(),
381            Some(Value::String(s)) => s,
382            Some(Value::Number(n)) => n.to_string(),
383            Some(_) => {
384                self.fault(&format!("{path}/name"), "name must be text");
385                String::new()
386            }
387        };
388        let given_rows = self.uint(o.remove("rows"), &format!("{path}/rows"), MAX_GRID_ROWS);
389        let given_cols = self.uint(o.remove("cols"), &format!("{path}/cols"), MAX_GRID_COLS);
390        let blocks = self.blocks(o.remove("blocks"), given_rows.unwrap_or(MAX_GRID_ROWS), given_cols.unwrap_or(MAX_GRID_COLS), path);
391        if given_rows.is_none() || given_cols.is_none() {
392            self.fault(path, "a grid needs \"rows\" and \"cols\" (its size); taken from its blocks");
393        }
394        let rows = given_rows.unwrap_or_else(|| blocks.iter().map(|b| b.row.saturating_add(b.height())).max().unwrap_or(0)).clamp(1, MAX_GRID_ROWS);
395        let cols = given_cols.unwrap_or_else(|| blocks.iter().map(|b| b.col.saturating_add(b.width())).max().unwrap_or(0)).clamp(1, MAX_GRID_COLS);
396        let mut frozen = |d: &mut Self, field: &str, max: u32| {
397            let n = d.uint(o.remove(field), &format!("{path}/{field}"), MAX_GRID_ROWS).unwrap_or(0);
398            if n >= max && n > 0 {
399                d.fault(&format!("{path}/{field}"), "more than the grid has; one less than its size is frozen");
400            }
401            n.min(max.saturating_sub(1))
402        };
403        let frozen_rows = frozen(self, "frozen_rows", rows);
404        let frozen_cols = frozen(self, "frozen_cols", cols);
405        let mut widths = BTreeMap::new();
406        match o.remove("widths") {
407            None | Some(Value::Null) => {}
408            Some(Value::Object(m)) => {
409                for (k, v) in m {
410                    let at = format!("{path}/widths/{}", pointer_segment(&cut_str(&k, MAX_KEY_CHARS)));
411                    let Some(c) = k.trim().parse::<u32>().ok().filter(|c| *c < cols) else {
412                        self.fault(&at, format!("a width's key is a column index from 0 to {}", cols - 1));
413                        continue;
414                    };
415                    if let Some(w) = self.number(Some(v), &at, 16.0, 2000.0) {
416                        widths.insert(c, w);
417                    }
418                }
419            }
420            Some(_) => self.fault(&format!("{path}/widths"), "widths must be an object of column index → points, like {\"0\": 140}"),
421        }
422        let default_width = self.number(o.remove("default_width"), &format!("{path}/default_width"), 16.0, 2000.0);
423        let editable = self.flag(o.remove("editable"), &format!("{path}/editable"), false);
424        let headers = self.flag(o.remove("headers"), &format!("{path}/headers"), true);
425        let height = self.number(o.remove("height"), &format!("{path}/height"), 60.0, 4000.0);
426        let selection = match o.remove("selection") {
427            None | Some(Value::Null) => None,
428            Some(Value::Object(mut s)) => {
429                let sp = format!("{path}/selection");
430                let row = self.uint(s.remove("row"), &format!("{sp}/row"), rows - 1);
431                let col = self.uint(s.remove("col"), &format!("{sp}/col"), cols - 1);
432                match (row, col) {
433                    (Some(row), Some(col)) => {
434                        let to_row = self.uint(s.remove("to_row"), &format!("{sp}/to_row"), rows - 1).unwrap_or(row);
435                        let to_col = self.uint(s.remove("to_col"), &format!("{sp}/to_col"), cols - 1).unwrap_or(col);
436                        Some(GridRange { row, col, to_row, to_col })
437                    }
438                    _ => {
439                        self.fault(&sp, "a selection needs a \"row\" and a \"col\"");
440                        None
441                    }
442                }
443            }
444            Some(_) => {
445                self.fault(&format!("{path}/selection"), "selection must be an object like {\"row\": 0, \"col\": 0}");
446                None
447            }
448        };
449        Kind::Grid { name, rows, cols, blocks, frozen_rows, frozen_cols, widths, default_width, editable, headers, height, selection }
450    }
451
452    /// A grid's blocks, cut to a `rows` × `cols` sheet and the cell limits.
453    pub(crate) fn blocks(&mut self, v: Option<Value>, rows: u32, cols: u32, path: &str) -> Vec<GridBlock> {
454        let mut list = match v {
455            None | Some(Value::Null) => return Vec::new(),
456            Some(Value::Array(list)) => list,
457            Some(_) => {
458                self.fault(&format!("{path}/blocks"), "blocks must be a list of {\"row\", \"col\", \"cells\"}");
459                return Vec::new();
460            }
461        };
462        if list.len() > MAX_GRID_BLOCKS {
463            self.fault(&format!("{path}/blocks"), format!("at most {MAX_GRID_BLOCKS} blocks; the rest are left out"));
464            list.truncate(MAX_GRID_BLOCKS);
465        }
466        let mut cx = CellBudget::with(MAX_GRID_CELLS);
467        let mut out = Vec::with_capacity(list.len());
468        for (i, b) in list.into_iter().enumerate() {
469            let bp = format!("{path}/blocks/{i}");
470            if let Some(b) = self.block(b, rows, cols, &bp, &mut cx) {
471                out.push(b);
472            }
473        }
474        cx.report(self, &format!("{path}/blocks"));
475        out
476    }
477
478    /// One block; `None` if it can't be placed.
479    pub(crate) fn block(&mut self, b: Value, rows: u32, cols: u32, bp: &str, cx: &mut CellBudget) -> Option<GridBlock> {
480        let Value::Object(mut bo) = b else {
481            self.fault(bp, "a block must be an object like {\"row\": 0, \"col\": 0, \"cells\": [[...]]}");
482            return None;
483        };
484        let at = |d: &mut Self, v: Option<Value>, field: &str| -> Option<u32> {
485            match v {
486                None | Some(Value::Null) => Some(0),
487                v => d.uint(v, &format!("{bp}/{field}"), u32::MAX),
488            }
489        };
490        let row = at(self, bo.remove("row"), "row")?;
491        let col = at(self, bo.remove("col"), "col")?;
492        if row >= rows || col >= cols {
493            self.fault(bp, format!("the block starts outside the grid ({rows} rows × {cols} columns); left out"));
494            return None;
495        }
496        let list = match bo.remove("cells") {
497            None | Some(Value::Null) => Vec::new(),
498            Some(Value::Array(l)) => l,
499            Some(_) => {
500                self.fault(&format!("{bp}/cells"), "cells must be a list of rows (each a list of cells)");
501                return None;
502            }
503        };
504        let (max_h, max_w) = (usize::try_from(rows - row).unwrap_or(usize::MAX), usize::try_from(cols - col).unwrap_or(usize::MAX));
505        if list.len() > max_h {
506            self.fault(&format!("{bp}/cells"), "rows past the grid's last row are left out");
507        }
508        let mut cells = Vec::with_capacity(list.len().min(max_h));
509        let mut wide = false;
510        for (r, rv) in list.into_iter().take(max_h).enumerate() {
511            if cx.left == 0 {
512                cx.over = true;
513                break;
514            }
515            let Value::Array(mut cs) = rv else {
516                self.fault(&format!("{bp}/cells/{r}"), "a row of cells must be a list");
517                cells.push(Vec::new());
518                continue;
519            };
520            if cs.len() > max_w {
521                wide = true;
522                cs.truncate(max_w);
523            }
524            if cs.len() > cx.left {
525                cx.over = true;
526                cs.truncate(cx.left);
527            }
528            cx.left -= cs.len();
529            let row: Vec<GridCell> = cs
530                .into_iter()
531                .enumerate()
532                .map(|(c, v)| match GridCell::decode(v) {
533                    Ok((cell, long)) => {
534                        cx.long |= long;
535                        cell
536                    }
537                    Err(msg) => {
538                        if cx.bad == 0 {
539                            cx.first_bad = Some((format!("{bp}/cells/{r}/{c}"), msg));
540                        }
541                        cx.bad += 1;
542                        GridCell::default()
543                    }
544                })
545                .collect();
546            cells.push(row);
547        }
548        if wide {
549            self.fault(&format!("{bp}/cells"), "cells past the grid's last column are left out");
550        }
551        Some(GridBlock { row, col, cells })
552    }
553
554    /// One patch; `None` (with a fault) if it can't be read.
555    pub(crate) fn patch(&mut self, v: Value, path: &mut String) -> Option<Patch> {
556        const OPS: &str = "put, replace, set, append, remove or rows";
557        let Value::Object(o) = v else {
558            self.fault(path, format!("a patch must be an object with one operation ({OPS})"));
559            return None;
560        };
561        if o.len() != 1 {
562            self.fault(path, format!("a patch has exactly one operation ({OPS})"));
563            return None;
564        }
565        let (op, body) = o.into_iter().next()?;
566        let _ = write!(path, "/{}", pointer_segment(&cut_str(&op, MAX_KEY_CHARS)));
567        let Value::Object(mut b) = body else {
568            self.fault(path, "the operation's value must be an object");
569            return None;
570        };
571        if op == "put" {
572            let Some(p) = text_field(self, &mut b, "path", path) else {
573                self.fault(path, "put needs a \"path\" (a JSON pointer like /children/0/text)");
574                return None;
575            };
576            let Some(value) = b.remove("value") else {
577                self.fault(path, "put needs a \"value\"");
578                return None;
579            };
580            return Some(Patch::Put { path: p, value });
581        }
582        let at = Target { key: text_field(self, &mut b, "key", path), path: text_field(self, &mut b, "path", path) };
583        if at.key.is_none() && at.path.is_none() {
584            self.fault(path, "a patch needs the \"key\" of the node it changes (or its \"path\")");
585            return None;
586        }
587        match op.as_str() {
588            "replace" => {
589                let at_len = path.len();
590                path.push_str("/node");
591                let node = b.remove("node").and_then(|n| self.node(n, path, 1));
592                path.truncate(at_len);
593                match node {
594                    Some(node) => Some(Patch::Replace { at, node }),
595                    None => {
596                        self.fault(path, "replace needs a \"node\"");
597                        None
598                    }
599                }
600            }
601            "set" => match b.remove("fields") {
602                Some(Value::Object(fields)) => Some(Patch::Set { at, fields }),
603                _ => {
604                    self.fault(path, "set needs \"fields\", an object like {\"text\": \"3 left\"}");
605                    None
606                }
607            },
608            "append" => {
609                let nodes = match b.remove("nodes").or_else(|| b.remove("node").map(|n| Value::Array(vec![n]))) {
610                    Some(Value::Array(list)) => {
611                        let at_len = path.len();
612                        let mut out = Vec::new();
613                        for (i, n) in list.into_iter().enumerate() {
614                            let _ = write!(path, "/nodes/{i}");
615                            out.extend(self.node(n, path, 1));
616                            path.truncate(at_len);
617                        }
618                        out
619                    }
620                    _ => {
621                        self.fault(path, "append needs \"nodes\", a list of nodes");
622                        return None;
623                    }
624                };
625                Some(Patch::Append { at, nodes })
626            }
627            "remove" => Some(Patch::Remove { at }),
628            "rows" => {
629                let start = match b.remove("start") {
630                    None | Some(Value::Null) => 0,
631                    Some(v) => match v.as_u64().and_then(|n| usize::try_from(n).ok()) {
632                        Some(n) => n,
633                        None => {
634                            self.fault(&format!("{path}/start"), "start must be a row index");
635                            return None;
636                        }
637                    },
638                };
639                let len = match b.remove("len") {
640                    None | Some(Value::Null) => None,
641                    Some(v) => match v.as_u64().and_then(|n| usize::try_from(n).ok()) {
642                        Some(n) => Some(n),
643                        None => {
644                            self.fault(&format!("{path}/len"), "len must be a row count");
645                            return None;
646                        }
647                    },
648                };
649                let rows = self.rows(b.remove("rows"), &[], path);
650                Some(Patch::Rows { at, start, rows, len })
651            }
652            _ => {
653                self.fault(path, format!("unknown patch operation (use {OPS})"));
654                None
655            }
656        }
657    }
658
659    /// Cut long strings and lists, make numbers finite.
660    fn sanitize(&mut self, k: &mut Kind, path: &str) {
661        let mut long = false;
662        let mut c = |s: &mut String| long |= cut(s);
663        match k {
664            Kind::Column { .. } | Kind::Row { .. } | Kind::Separator {} | Kind::Chart { .. } => {}
665            // Checked as it was decoded.
666            Kind::Grid { name, .. } => c(name),
667            Kind::Card { title, .. } => c(title),
668            Kind::Text { text, .. } | Kind::Markdown { text } | Kind::Chip { text, .. } => c(text),
669            Kind::Button { label, action, .. } => {
670                c(label);
671                c(action);
672            }
673            Kind::Input { name, value, placeholder, submit } => {
674                c(name);
675                c(value);
676                c(placeholder);
677                submit.iter_mut().for_each(c);
678            }
679            Kind::Toggle { name, label, action, .. } => {
680                c(name);
681                c(label);
682                action.iter_mut().for_each(c);
683            }
684            Kind::Select { name, options, value, action } => {
685                if options.len() > MAX_OPTIONS {
686                    self.fault(&format!("{path}/options"), format!("at most {MAX_OPTIONS} options; the rest are left out"));
687                    options.truncate(MAX_OPTIONS);
688                }
689                c(name);
690                c(value);
691                options.iter_mut().for_each(&mut c);
692                action.iter_mut().for_each(c);
693            }
694            Kind::Progress { value, label } => {
695                *value = if value.is_finite() { value.clamp(0.0, 1.0) } else { 0.0 };
696                c(label);
697            }
698            Kind::Table { name, columns, height, select, .. } => {
699                c(name);
700                for col in columns.iter_mut() {
701                    c(&mut col.key);
702                    c(&mut col.label);
703                    col.width = col.width.filter(|w| w.is_finite()).map(|w| w.clamp(20.0, 2000.0));
704                }
705                *height = height.filter(|h| h.is_finite()).map(|h| h.clamp(40.0, 4000.0));
706                select.iter_mut().for_each(c);
707            }
708            Kind::Image { media, artifact, alt, width, height } => {
709                media.iter_mut().for_each(&mut c);
710                artifact.iter_mut().for_each(&mut c);
711                c(alt);
712                for side in [width, height] {
713                    *side = side.filter(|s| s.is_finite()).map(|s| s.clamp(1.0, 4000.0));
714                }
715            }
716            Kind::Canvas { width, height, action, .. } => {
717                for side in [width, height] {
718                    *side = if side.is_finite() { side.clamp(1.0, 4000.0) } else { 100.0 };
719                }
720                action.iter_mut().for_each(c);
721            }
722        }
723        if long {
724            self.fault(path, format!("text longer than {MAX_TEXT_CHARS} characters was cut"));
725        }
726    }
727}
728
729/// What's left of a grid's cell limit, and what was wrong with its cells (reported once).
730#[derive(Default)]
731pub(crate) struct CellBudget {
732    pub(crate) left: usize,
733    over: bool,
734    long: bool,
735    bad: usize,
736    first_bad: Option<(String, &'static str)>,
737}
738
739impl CellBudget {
740    pub(crate) fn with(left: usize) -> Self {
741        Self { left, ..Self::default() }
742    }
743
744    pub(crate) fn report(self, d: &mut Decoder, path: &str) {
745        if let Some((path, msg)) = self.first_bad {
746            let more = if self.bad > 1 { format!(" ({} cells like it are empty)", self.bad) } else { "; it is empty".to_owned() };
747            d.fault(&path, format!("{msg}{more}"));
748        }
749        if self.long {
750            d.fault(path, format!("grid cell text longer than {MAX_CELL_CHARS} characters was cut"));
751        }
752        if self.over {
753            d.fault(path, format!("a grid has at most {MAX_GRID_CELLS} cells in its blocks; the rest are left out"));
754        }
755    }
756}
757
758/// A text field of a patch (numbers are taken as text).
759fn text_field(d: &mut Decoder, b: &mut Map<String, Value>, field: &str, path: &str) -> Option<String> {
760    match b.remove(field) {
761        None | Some(Value::Null) => None,
762        Some(Value::String(s)) => Some(s),
763        Some(Value::Number(n)) => Some(n.to_string()),
764        Some(_) => {
765            d.fault(&format!("{path}/{field}"), format!("{field} must be text"));
766            None
767        }
768    }
769}
770
771/// A table cell: a scalar (lists and objects become their JSON text), long text cut.
772pub(crate) fn cell(v: Value) -> Value {
773    match v {
774        Value::String(mut s) => {
775            cut(&mut s);
776            Value::String(s)
777        }
778        v @ (Value::Null | Value::Bool(_) | Value::Number(_)) => v,
779        other => {
780            let mut s = other.to_string();
781            cut(&mut s);
782            Value::String(s)
783        }
784    }
785}
786
787fn sanitize_shape(s: &mut Shape) {
788    let fin = |v: &mut f32| {
789        if !v.is_finite() {
790            *v = 0.0;
791        }
792        *v = v.clamp(-100_000.0, 100_000.0);
793    };
794    match s {
795        Shape::Rect { x, y, w, h, radius, .. } => [x, y, w, h, radius].into_iter().for_each(fin),
796        Shape::Circle { x, y, r, .. } => [x, y, r].into_iter().for_each(fin),
797        Shape::Line { points, width, .. } => {
798            points.truncate(MAX_SHAPES);
799            points.iter_mut().flatten().for_each(fin);
800            fin(width);
801            *width = width.clamp(0.0, 100.0);
802        }
803        Shape::Text { x, y, text, size, .. } => {
804            [x, y].into_iter().for_each(fin);
805            cut(text);
806            *size = if size.is_finite() { size.clamp(6.0, 96.0) } else { 14.0 };
807        }
808    }
809}
810
811/// Cut `s` to [`MAX_TEXT_CHARS`]; whether it was longer.
812fn cut(s: &mut String) -> bool {
813    // A byte length under the limit can't be over it in characters.
814    if s.len() <= MAX_TEXT_CHARS {
815        return false;
816    }
817    match s.char_indices().nth(MAX_TEXT_CHARS) {
818        Some((at, _)) => {
819            s.truncate(at);
820            true
821        }
822        None => false,
823    }
824}
825
826fn cut_str(s: &str, max: usize) -> String {
827    s.chars().take(max).collect()
828}