Skip to main content

tilo_render_protocol/patch/
validate.rs

1//! The check every batch an app sends passes before the UI host touches a widget.
2//!
3//! The UI host builds every window of a workspace from what each app sends. A batch that makes it
4//! build a widget wrongly, or work without bound, takes the workspace's windows down with it. So
5//! every message is checked, once, in the host's own copy:
6//!
7//! - **Valid by type.** A described component's node (`ui.ListRow`) names a component of the
8//!   toolkit's catalogue; each of its props is one the description declares (or a sizing
9//!   argument every node takes, or the companion of a prop it declares, such as `value:as`
10//!   saying which kind of text `value` holds), holding a value of the declared type; each event
11//!   and binding is one it declares. A primitive of the language (`stack`, `list`) is one the
12//!   host builds.
13//! - **Bounded.** Strings, keys, paths, props, depth and the rows of one message are limited,
14//!   and each window's trees together hold at most [`PatchLimits::nodes`] nodes (the host
15//!   counts them as it applies patches: one window's budget is its own).
16//! - **Only its own trees.** A connection is one window of one app; its patches name nodes by
17//!   key paths in the trees it sent, and a path that names no node is refused when applied.
18
19use tilo_actions::ActionAddress;
20use tilo_ui_graph::component::{Catalogue, Description, Type, companion};
21
22use super::{
23    Binding, Event, MAX_CALL_PICTURE_BYTES, MAX_CALL_PICTURES, Node, Patch, ResourceRef, RowChange,
24    ToApp, ToUi, Value, Words,
25};
26
27/// Why a batch was refused: what was wrong, and where.
28#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
29#[error("{what}{at}")]
30pub struct Refused {
31    pub what: &'static str,
32    /// Where, from the outermost part in, such as `` in `stack` s in prop `gap` ``.
33    pub at: String,
34}
35
36impl Refused {
37    #[must_use]
38    pub fn invalid(what: &'static str) -> Self {
39        Self {
40            what,
41            at: String::new(),
42        }
43    }
44
45    /// The same refusal, found in `part`.
46    #[must_use]
47    pub fn within(mut self, part: impl std::fmt::Display) -> Self {
48        self.at = format!(" in {part}{}", self.at);
49        self
50    }
51}
52
53/// What one window may make its UI host hold and do.
54#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
55pub struct PatchLimits {
56    /// Nodes of one window's trees together, rendered rows included.
57    pub nodes: u32,
58    /// How deep a tree nests.
59    pub depth: u32,
60    /// Bytes of one string: a prop's text, a bound value, a splice — as much
61    /// as one text an action carries ([`tilo_actions::MAX_TEXT_BYTES`]), so a
62    /// text an edit keeps is always a text a window can show.
63    pub string_bytes: u32,
64    /// Bytes of one key or name.
65    pub key_bytes: u32,
66    /// Keys in one path.
67    pub path: u32,
68    /// Props of one node.
69    pub props: u32,
70    /// Rows or keys in one message.
71    pub rows: u32,
72    /// Messages in one batch.
73    pub messages: u32,
74}
75
76/// One text's bytes as a window counts one string: the same number
77/// ([`tilo_actions::MAX_TEXT_BYTES`]), so a text an edit keeps is never one the
78/// window refuses to show.
79#[expect(
80    clippy::cast_possible_truncation,
81    reason = "one text's bytes, 8 MiB, fit a window's count of a string"
82)]
83const STRING_BYTES: u32 = tilo_actions::MAX_TEXT_BYTES as u32;
84
85impl Default for PatchLimits {
86    fn default() -> Self {
87        Self {
88            nodes: 200_000,
89            depth: 128,
90            string_bytes: STRING_BYTES,
91            key_bytes: 4096,
92            path: 128,
93            props: 128,
94            rows: 8192,
95            messages: 65_536,
96        }
97    }
98}
99
100/// The sizing and placement arguments every node takes (`fill`, `min: 12.rem`, `at`), as the
101/// language's `prims::NODE_ARGS` names them.
102pub const NODE_ARGS: &[&str] = &[
103    "fill", "min", "max", "height", "aspect", "span", "lines", "truncate", "at", "lead", "x", "y",
104];
105
106/// Every primitive of the language a view may send: the layouts, controls and blocks the host
107/// builds itself, and `part`, a component's named part. A primitive's props are the language's
108/// arguments, which the host reads by name, each as the type it takes, ignoring what it does
109/// not read; so what is checked of them is that the primitive is one the host builds and that
110/// every value is bounded.
111pub const PRIMITIVES: &[&str] = &[
112    "stack",
113    "column",
114    "fragment",
115    "primary",
116    "secondary",
117    "item",
118    "row",
119    "grid",
120    "split",
121    "page",
122    "layers",
123    "scroll",
124    "spacer",
125    "divider",
126    "progress",
127    "form",
128    "field",
129    "toggle",
130    "choice",
131    "list",
132    "checkbox",
133    "date",
134    "image",
135    "embed",
136    "invocation",
137    "error",
138    "text",
139    PART,
140];
141
142/// The kind of a node holding the content of a component's named part.
143pub const PART: &str = "part";
144
145/// The prefix of a described component's kind: `ui.ListRow`.
146pub const COMPONENT_PREFIX: &str = "ui.";
147
148/// Whether `kind` is a primitive the host builds.
149#[must_use]
150pub fn primitive(kind: &str) -> bool {
151    PRIMITIVES.contains(&kind)
152}
153
154/// Checks batches against a toolkit's catalogue and a window's limits.
155pub struct Validator<'a> {
156    catalogue: &'a Catalogue,
157    limits: PatchLimits,
158}
159
160impl<'a> Validator<'a> {
161    #[must_use]
162    pub fn new(catalogue: &'a Catalogue, limits: PatchLimits) -> Self {
163        Self { catalogue, limits }
164    }
165
166    #[must_use]
167    pub fn limits(&self) -> &PatchLimits {
168        &self.limits
169    }
170
171    /// Check one batch an app sent its window.
172    ///
173    /// # Errors
174    /// The first thing in it that is not valid.
175    pub fn to_ui(&self, batch: &[ToUi]) -> Result<(), Refused> {
176        if batch.len() > self.limits.messages as usize {
177            return Err(Refused::invalid(concat!(
178                "over the limit of ",
179                "messages in a batch"
180            )));
181        }
182        for message in batch {
183            self.message(message)?;
184        }
185        Ok(())
186    }
187
188    /// A resource the window names: its id and its type.
189    fn target(&self, target: &ResourceRef) -> Result<(), Refused> {
190        self.key(&target.id)?;
191        self.key(&target.ty)
192    }
193
194    /// `bytes` a message carries whole, within the limit of a string's; `refused` says it is not.
195    fn carried(&self, bytes: usize, refused: &'static str) -> Result<(), Refused> {
196        if bytes > self.limits.string_bytes as usize {
197            return Err(Refused::invalid(refused));
198        }
199        Ok(())
200    }
201
202    #[allow(
203        clippy::too_many_lines,
204        reason = "one arm per message a window takes, read side by side as the protocol lists them"
205    )]
206    fn message(&self, message: &ToUi) -> Result<(), Refused> {
207        match message {
208            ToUi::Loading
209            | ToUi::Close
210            | ToUi::Front { shows: None, .. }
211            | ToUi::Ask(None)
212            | ToUi::Form(None)
213            | ToUi::Activate
214            | ToUi::Kept(_)
215            | ToUi::History(_)
216            | ToUi::Took { .. }
217            | ToUi::CloseWindow => Ok(()),
218            ToUi::Focus { key } => match key {
219                Some(key) => self.key(key),
220                None => Ok(()),
221            },
222            ToUi::Actions(catalogue) => {
223                self.carried(catalogue.len(), "over the limit of bytes in a catalogue")
224            }
225            ToUi::Heard(bytes) | ToUi::Outputs(bytes) => {
226                self.carried(bytes.len(), "over the limit of bytes in a message")
227            }
228            ToUi::CallPictures { shown, pictures } => {
229                if shown.len() > MAX_CALL_PICTURES || pictures.len() > MAX_CALL_PICTURES {
230                    return Err(Refused::invalid("over the limit of pictures in a message"));
231                }
232                for shown in shown {
233                    self.key(&shown.person)?;
234                }
235                for picture in pictures {
236                    self.key(&picture.person)?;
237                    self.key(&picture.stream)?;
238                    if picture.object.is_empty() || picture.object.len() > MAX_CALL_PICTURE_BYTES {
239                        return Err(Refused::invalid("a call picture is not one picture"));
240                    }
241                }
242                Ok(())
243            }
244            ToUi::Desktop { action, argument } => {
245                self.key(action)?;
246                self.carried(argument.len(), "over the limit of bytes in a message")
247            }
248            ToUi::Page { request, .. } => {
249                if request.len() > super::MAX_PAGE_BYTES {
250                    return Err(Refused::invalid(
251                        "over the limit of bytes in a page request",
252                    ));
253                }
254                Ok(())
255            }
256            ToUi::Front {
257                shows: Some((_, target)),
258                ..
259            } => self.target(target),
260            ToUi::Open { target, tree, .. } => {
261                self.key(&target.id)?;
262                self.key(&target.ty)?;
263                self.node(tree, 0)
264            }
265            ToUi::Patch { patches, .. } => {
266                if patches.len() > self.limits.messages as usize {
267                    return Err(Refused::invalid(concat!(
268                        "over the limit of ",
269                        "patches in a message"
270                    )));
271                }
272                patches.iter().try_for_each(|patch| self.patch(patch))
273            }
274            ToUi::Bound { key, value, .. } => {
275                self.key(key)?;
276                self.value(value, 0)
277            }
278            ToUi::Rows {
279                list, keys, rows, ..
280            } => {
281                self.key(list)?;
282                if keys.len() > self.limits.rows as usize || rows.len() > self.limits.rows as usize
283                {
284                    return Err(Refused::invalid(concat!(
285                        "over the limit of ",
286                        "rows in a message"
287                    )));
288                }
289                keys.iter().try_for_each(|key| self.key(key))?;
290                rows.iter().try_for_each(|row| self.node(row, 1))
291            }
292            ToUi::Spaces { keys, .. } => {
293                if keys.len() > self.limits.rows as usize {
294                    return Err(Refused::invalid(concat!(
295                        "over the limit of ",
296                        "views in a message"
297                    )));
298                }
299                keys.iter().try_for_each(|key| self.key(key))
300            }
301            ToUi::RowsChanged { list, changes, .. } => {
302                self.key(list)?;
303                if changes.len() > self.limits.rows as usize {
304                    return Err(Refused::invalid(concat!(
305                        "over the limit of ",
306                        "rows in a message"
307                    )));
308                }
309                changes.iter().try_for_each(|change| match change {
310                    RowChange::Inserted { key, .. } => self.key(key),
311                    RowChange::Changed { row } => self.node(row, 1),
312                    RowChange::Removed { .. } | RowChange::Moved { .. } | RowChange::Reset => {
313                        Ok(())
314                    }
315                })
316            }
317            ToUi::Notice { words, .. } => self.words(words),
318            ToUi::ShowRun { run } => self.key(run),
319            ToUi::Speak(language) => self.key(language),
320            ToUi::Ask(Some(ask)) => {
321                self.string(&ask.action)?;
322                self.string(&ask.invoker)
323            }
324            ToUi::Form(Some(form)) => {
325                self.string(&form.title)?;
326                self.string(&form.submit)?;
327                if let Some(error) = &form.error {
328                    self.string(error)?;
329                }
330                if let Some((_, key)) = &form.from {
331                    self.key(key)?;
332                }
333                if form.fields.len() > self.limits.messages as usize {
334                    return Err(Refused::invalid(concat!(
335                        "over the limit of ",
336                        "fields in a form"
337                    )));
338                }
339                form.fields.iter().try_for_each(|(key, text)| {
340                    self.key(key)?;
341                    self.string(text)
342                })?;
343                self.node(&form.tree, 1)
344            }
345        }
346    }
347
348    fn patch(&self, patch: &Patch) -> Result<(), Refused> {
349        match patch {
350            Patch::SetRoot(node) => self.node(node, 0),
351            Patch::Insert { parent, node, .. } => {
352                self.path(parent)?;
353                self.node(node, parent.len().saturating_add(1))
354            }
355            Patch::Remove { parent, key } | Patch::Move { parent, key, .. } => {
356                self.path(parent)?;
357                self.key(key)
358            }
359            // A prop, binding or event set on its own is checked against its node's kind when
360            // applied ([`Self::node`] of the node it changed).
361            Patch::SetProp { path, name, value } => {
362                self.path(path)?;
363                self.key(name)?;
364                value
365                    .as_ref()
366                    .map_or(Ok(()), |value| self.value(value, path.len()))
367            }
368            Patch::SetBinding { path, binding } => {
369                self.path(path)?;
370                binding
371                    .as_ref()
372                    .map_or(Ok(()), |binding| self.binding(binding))
373            }
374            Patch::SetEvent {
375                path,
376                event,
377                action,
378            } => {
379                self.path(path)?;
380                self.key(event)?;
381                action.as_ref().map_or(Ok(()), |event| self.event(event))
382            }
383            Patch::SetAnchor { path, anchor } => {
384                self.path(path)?;
385                anchor.as_ref().map_or(Ok(()), |anchor| self.key(anchor))
386            }
387            Patch::SpliceProp {
388                path, name, insert, ..
389            } => {
390                self.path(path)?;
391                self.key(name)?;
392                if insert.len() > self.limits.rows as usize {
393                    return Err(Refused::invalid(concat!(
394                        "over the limit of ",
395                        "items of a list value"
396                    )));
397                }
398                insert
399                    .iter()
400                    .try_for_each(|item| self.value(item, path.len().saturating_add(1)))
401            }
402        }
403    }
404
405    /// Check `node`, at `depth`, and everything under it: its kind, and each prop, binding,
406    /// event and child against it.
407    ///
408    /// # Errors
409    /// The first part of it that is not valid.
410    pub fn node(&self, node: &Node, depth: usize) -> Result<(), Refused> {
411        if depth > self.limits.depth as usize {
412            return Err(Refused::invalid(concat!(
413                "over the limit of ",
414                "tree depth"
415            )));
416        }
417        self.key(&node.key)?;
418        if node.props.len() > self.limits.props as usize {
419            return Err(Refused::invalid(concat!(
420                "over the limit of ",
421                "props of a node"
422            )));
423        }
424        if let Some(anchor) = &node.anchor {
425            self.key(anchor)?;
426        }
427        self.shape(node, depth)
428            .map_err(|refused| refused.within(format_args!("`{}` {}", node.kind, node.key)))?;
429        node.children
430            .iter()
431            .try_for_each(|child| self.node(child, depth.saturating_add(1)))
432    }
433
434    /// Check the node's own parts, not its children, against its kind.
435    pub fn shape(&self, node: &Node, depth: usize) -> Result<(), Refused> {
436        if let Some(name) = node.kind.strip_prefix(COMPONENT_PREFIX) {
437            let description = self
438                .catalogue
439                .get(name)
440                .ok_or_else(|| Refused::invalid("a component the toolkit does not describe"))?;
441            return self.component(node, description, depth);
442        }
443        if !primitive(&node.kind) {
444            return Err(Refused::invalid("a kind of node the host does not build"));
445        }
446        for (name, value) in &node.props {
447            self.key(name)?;
448            self.value(value, depth)
449                .map_err(|refused| refused.within(format_args!("prop `{name}`")))?;
450        }
451        for (name, event) in &node.events {
452            self.key(name)?;
453            self.event(event)?;
454        }
455        node.binding
456            .as_ref()
457            .map_or(Ok(()), |binding| self.binding(binding))
458    }
459
460    fn component(
461        &self,
462        node: &Node,
463        description: &Description,
464        depth: usize,
465    ) -> Result<(), Refused> {
466        for (name, value) in &node.props {
467            self.prop(name, value, description, depth)
468                .map_err(|refused| refused.within(format_args!("prop `{name}`")))?;
469        }
470        self.parts(node, description)
471    }
472
473    fn prop(
474        &self,
475        name: &str,
476        value: &Value,
477        description: &Description,
478        depth: usize,
479    ) -> Result<(), Refused> {
480        self.value(value, depth)?;
481        {
482            let declared = description
483                .prop(name)
484                .map(|prop| &prop.ty)
485                .or_else(|| description.state(name).map(|state| &state.ty))
486                // A value the view gives a control rather than binds to it (a device's
487                // volume): the control shows it, and its `change` event says what the person
488                // did with it.
489                .or_else(|| {
490                    description
491                        .event("change")
492                        .and_then(|_| description.binding(name))
493                        .map(|binding| &binding.ty)
494                });
495            match declared {
496                Some(ty) => {
497                    if !fits(value, ty) {
498                        return Err(Refused::invalid(
499                            "a prop holding a value of another type than its component declares",
500                        ));
501                    }
502                }
503                None if node_arg(name) => {}
504                // Which binding a node binds, of a component with several.
505                None if name == "bind" => {
506                    let Value::Text(bound) = value else {
507                        return Err(Refused::invalid("a binding named by other than text"));
508                    };
509                    if description.binding(bound).is_none() {
510                        return Err(Refused::invalid("a binding its component does not declare"));
511                    }
512                }
513                // A companion of a prop the component declares: `value:as` says which kind of
514                // text `value` holds, and `meta:time` the time of day the day `meta` is due at.
515                None if companion(name).is_some_and(|(prop, _)| {
516                    description.prop(prop).is_some() || description.state(prop).is_some()
517                }) => {}
518                None => {
519                    return Err(Refused::invalid("a prop its component does not declare"));
520                }
521            }
522        }
523        Ok(())
524    }
525
526    fn parts(&self, node: &Node, description: &Description) -> Result<(), Refused> {
527        for (name, event) in &node.events {
528            if description.event(name).is_none()
529                && description.binding(name).is_none()
530                && !offers(description, name)
531            {
532                return Err(Refused::invalid("an event its component does not declare")
533                    .within(format_args!("event `{name}`")));
534            }
535            self.event(event)?;
536        }
537        if let Some(binding) = &node.binding {
538            if description.bindings.is_empty() {
539                return Err(Refused::invalid("a binding on a component that takes none"));
540            }
541            self.binding(binding)?;
542        }
543        Ok(())
544    }
545
546    fn binding(&self, binding: &Binding) -> Result<(), Refused> {
547        self.string(&binding.name)?;
548        if let Some((target, field)) = &binding.field {
549            self.key(target)?;
550            self.key(field)?;
551        }
552        Ok(())
553    }
554
555    fn event(&self, event: &Event) -> Result<(), Refused> {
556        if let Some((target, field)) = &event.toggles {
557            self.key(target)?;
558            self.key(field)?;
559        }
560        if let Some(invoked) = &event.invokes {
561            self.key(&invoked.resource)?;
562            self.key(&invoked.action)?;
563        }
564        Ok(())
565    }
566
567    fn value(&self, value: &Value, depth: usize) -> Result<(), Refused> {
568        if depth > self.limits.depth as usize {
569            return Err(Refused::invalid(concat!(
570                "over the limit of ",
571                "value depth"
572            )));
573        }
574        match value {
575            Value::Unit | Value::Int(_) | Value::Bool(_) => Ok(()),
576            Value::Float(number) if number.is_finite() => Ok(()),
577            Value::Float(_) => Err(Refused::invalid("a number that is not finite")),
578            Value::Text(text) | Value::Error(text) => self.string(text),
579            Value::Enum(case) => self.key(case),
580            Value::Case { case, fields } => {
581                self.key(case)?;
582                for (name, held) in fields {
583                    self.key(name)?;
584                    self.value(held, depth.saturating_add(1))?;
585                }
586                Ok(())
587            }
588            Value::List(items) => {
589                if items.len() > self.limits.rows as usize {
590                    return Err(Refused::invalid(concat!(
591                        "over the limit of ",
592                        "items of a list value"
593                    )));
594                }
595                items
596                    .iter()
597                    .try_for_each(|item| self.value(item, depth.saturating_add(1)))
598            }
599            Value::Opt(held) => held
600                .as_deref()
601                .map_or(Ok(()), |held| self.value(held, depth.saturating_add(1))),
602            Value::Ref(resource) => {
603                self.key(&resource.id)?;
604                self.key(&resource.ty)
605            }
606            Value::Actor(who) => {
607                self.key(who.id.id())?;
608                self.string(&who.name)
609            }
610            Value::Map(entries) => {
611                if entries.len() > self.limits.rows as usize {
612                    return Err(Refused::invalid(concat!(
613                        "over the limit of ",
614                        "entries of a map value"
615                    )));
616                }
617                entries.iter().try_for_each(|(key, value)| {
618                    self.value(key, depth.saturating_add(1))?;
619                    self.value(value, depth.saturating_add(1))
620                })
621            }
622            Value::Action(offered) => {
623                self.string(&offered.label)?;
624                self.key(&offered.event)?;
625                offered.icon.as_ref().map_or(Ok(()), |icon| self.key(icon))
626            }
627            Value::Picture(picture) => self.string(&picture.src),
628            Value::File(file) => {
629                self.string(&file.name)?;
630                self.key(&file.media)?;
631                self.string(&file.url)
632            }
633            Value::Link { reference, title } => {
634                self.string(reference)?;
635                self.string(title)
636            }
637            Value::Rich(rich) => {
638                if rich.blocks.len() > self.limits.rows as usize
639                    || rich.embeds.len() > self.limits.rows as usize
640                {
641                    return Err(Refused::invalid(concat!(
642                        "over the limit of ",
643                        "paragraphs of rich text"
644                    )));
645                }
646                rich.strings().try_for_each(|text| self.string(text))
647            }
648        }
649    }
650
651    fn words(&self, words: &Words) -> Result<(), Refused> {
652        match words {
653            Words::Plain(text) => self.string(text),
654            Words::Phrase { id, args } => {
655                self.key(id)?;
656                if args.len() > self.limits.props as usize {
657                    return Err(Refused::invalid(concat!(
658                        "over the limit of ",
659                        "arguments of a phrase"
660                    )));
661                }
662                args.iter().try_for_each(|(name, value)| {
663                    self.key(name)?;
664                    self.string(value)
665                })
666            }
667        }
668    }
669
670    fn path(&self, path: &[String]) -> Result<(), Refused> {
671        if path.len() > self.limits.path as usize {
672            return Err(Refused::invalid(concat!(
673                "over the limit of ",
674                "path length"
675            )));
676        }
677        path.iter().try_for_each(|key| self.key(key))
678    }
679
680    fn key(&self, key: &str) -> Result<(), Refused> {
681        if key.len() > self.limits.key_bytes as usize {
682            return Err(Refused::invalid(concat!(
683                "over the limit of ",
684                "key length"
685            )));
686        }
687        Ok(())
688    }
689
690    fn resource(&self, resource: &ResourceRef) -> Result<(), Refused> {
691        self.key(&resource.id)?;
692        self.key(&resource.ty)
693    }
694
695    fn string(&self, text: &str) -> Result<(), Refused> {
696        if text.len() > self.limits.string_bytes as usize {
697            return Err(Refused::invalid(concat!(
698                "over the limit of ",
699                "string length"
700            )));
701        }
702        Ok(())
703    }
704
705    /// Check one batch the host sent an app: in an app host, what the window says it did is
706    /// as hostile as what an app sends its window.
707    ///
708    /// # Errors
709    /// The first thing in it that is not valid.
710    pub fn to_app(&self, batch: &[ToApp]) -> Result<(), Refused> {
711        if batch.len() > self.limits.messages as usize {
712            return Err(Refused::invalid(concat!(
713                "over the limit of ",
714                "messages in a batch"
715            )));
716        }
717        for message in batch {
718            self.to_app_message(message)?;
719        }
720        Ok(())
721    }
722
723    /// Check one message the host sent an app: the keys it names, then the value it carries.
724    fn to_app_message(&self, message: &ToApp) -> Result<(), Refused> {
725        self.to_app_targets(message)?;
726        self.to_app_payload(message)
727    }
728
729    /// The keys and resources `message` names.
730    fn to_app_targets(&self, message: &ToApp) -> Result<(), Refused> {
731        match message {
732            ToApp::Fire { key, event, .. } => {
733                self.key(key)?;
734                self.key(event)?;
735            }
736            ToApp::Toggle { target, key, .. }
737            | ToApp::Splice { target, key, .. }
738            | ToApp::Edit { target, key, .. }
739            | ToApp::EditRich { target, key, .. } => {
740                self.resource(target)?;
741                self.key(key)?;
742            }
743            ToApp::Resolve { key, .. } => self.key(key)?,
744            ToApp::Rows {
745                list, open, menu, ..
746            } => {
747                for key in std::iter::once(list).chain(open).chain(menu) {
748                    self.key(key)?;
749                }
750            }
751            ToApp::Focus { at } => {
752                if let Some((_, key)) = at {
753                    self.key(key)?;
754                }
755            }
756            ToApp::FormEdit { field, .. } => self.key(field)?,
757            ToApp::Open { .. }
758            | ToApp::OpenReference { .. }
759            | ToApp::Space { .. }
760            | ToApp::Invoke { .. }
761            | ToApp::Serving { .. }
762            | ToApp::PageAnswer { .. }
763            | ToApp::PagePrompt { .. }
764            | ToApp::Desktop { .. }
765            | ToApp::Back
766            | ToApp::Answer(_)
767            | ToApp::Undo
768            | ToApp::Redo
769            | ToApp::Composing(_)
770            | ToApp::Held(_)
771            | ToApp::SaveAgain
772            | ToApp::History { .. }
773            | ToApp::FormSubmit { .. }
774            | ToApp::FormCancel { .. } => {}
775        }
776        Ok(())
777    }
778
779    /// The value `message` carries, and how large it comes to.
780    fn to_app_payload(&self, message: &ToApp) -> Result<(), Refused> {
781        match message {
782            ToApp::Fire {
783                value: Some(value), ..
784            } => self.value(value, 0),
785            ToApp::Splice { insert, .. } => self.string(insert),
786            ToApp::Edit { text, .. } | ToApp::FormEdit { text, .. } => self.string(text),
787            ToApp::EditRich { rich, .. } => self.value(&Value::Rich(rich.clone()), 0),
788            ToApp::Open { resource } => self.resource(resource),
789            ToApp::OpenReference { reference } => self.string(reference),
790            ToApp::Rows { start, end, .. } => {
791                if end < start || end.saturating_sub(*start) > self.limits.rows {
792                    return Err(Refused::invalid(concat!(
793                        "over the limit of ",
794                        "rows in a message"
795                    )));
796                }
797                Ok(())
798            }
799            ToApp::Space {
800                width, height, rem, ..
801            } => {
802                if !(width.is_finite()
803                    && height.is_finite()
804                    && *width >= 0.0
805                    && *height >= 0.0
806                    && rem.is_finite()
807                    && *rem > 0.0)
808                {
809                    return Err(Refused::invalid("a space is no size"));
810                }
811                Ok(())
812            }
813            ToApp::Invoke { address, argument } => self.invoke(address, argument.as_deref()),
814            ToApp::Serving { call, invoker } => self.serving(call, invoker.as_deref()),
815            ToApp::PageAnswer { answer, .. } => {
816                if answer.len() > super::MAX_PAGE_BYTES {
817                    return Err(Refused::invalid("over the limit of bytes in a page answer"));
818                }
819                Ok(())
820            }
821            ToApp::Desktop { layout } => {
822                if layout.len() > super::MAX_PAGE_BYTES {
823                    return Err(Refused::invalid("over the limit of bytes in a layout"));
824                }
825                Ok(())
826            }
827            ToApp::PagePrompt { prompt } => {
828                if prompt.len() > self.limits.string_bytes as usize {
829                    return Err(Refused::invalid(
830                        "over the limit of bytes in a page's prompt",
831                    ));
832                }
833                Ok(())
834            }
835            _ => Ok(()),
836        }
837    }
838
839    /// Check an action the host asks an app to run.
840    fn invoke(&self, address: &ActionAddress, argument: Option<&str>) -> Result<(), Refused> {
841        self.key(&address.resource)?;
842        self.key(&address.action)?;
843        argument.map_or(Ok(()), |argument| self.string(argument))
844    }
845
846    /// Check a signed call the host serves for its invoker.
847    fn serving(&self, call: &[u8], invoker: Option<&str>) -> Result<(), Refused> {
848        if call.len() > self.limits.string_bytes as usize {
849            return Err(Refused::invalid(
850                "a signed call is over the limit of a string",
851            ));
852        }
853        invoker.map_or(Ok(()), |invoker| self.string(invoker))
854    }
855}
856
857/// The event an action offered in the prop `prop` fires: `actions.2` for the third of
858/// `actions`. Its node gives it what the action runs, as it gives its declared events.
859#[must_use]
860pub fn offered_event(prop: &str, index: usize) -> String {
861    format!("{prop}.{index}")
862}
863
864/// Whether `event` is one an action offered in a prop of the component fires
865/// ([`offered_event`]): the host binds such an event to the action it runs.
866#[must_use]
867pub fn offers(description: &Description, event: &str) -> bool {
868    fn holds_actions(ty: &Type) -> bool {
869        match ty {
870            Type::Action => true,
871            Type::Option(inner) | Type::List(inner) | Type::Set(inner) => holds_actions(inner),
872            Type::Map { value, .. } => holds_actions(value),
873            _ => false,
874        }
875    }
876    event
877        .rsplit_once('.')
878        .filter(|(_, index)| !index.is_empty() && index.bytes().all(|b| b.is_ascii_digit()))
879        .and_then(|(prop, _)| description.prop(prop))
880        .is_some_and(|prop| holds_actions(&prop.ty))
881}
882
883/// Whether `name` is a sizing or placement argument every node takes, with its unit
884/// (`min.rem`).
885fn node_arg(name: &str) -> bool {
886    let base = name
887        .strip_suffix(".rem")
888        .or_else(|| name.strip_suffix(".dp"))
889        .unwrap_or(name);
890    NODE_ARGS.contains(&base)
891}
892
893/// Whether `value` is one of the type `ty`, as the host reads it into a widget: text shows any
894/// value as text, a whole number is a number, an `Option` holds nothing or a value.
895#[must_use]
896pub fn fits(value: &Value, ty: &Type) -> bool {
897    match (ty, value) {
898        (Type::Option(_), Value::Opt(None) | Value::Unit)
899        | (Type::Int, Value::Int(_))
900        | (Type::Float, Value::Float(_) | Value::Int(_))
901        | (Type::Bool, Value::Bool(_) | Value::Int(_))
902        | (Type::Actor, Value::Actor(_))
903        | (Type::Resource, Value::Ref(_))
904        | (Type::Icon | Type::Time, Value::Text(_))
905        | (Type::Picture, Value::Picture(_))
906        | (Type::File, Value::File(_))
907        | (Type::Link, Value::Link { .. })
908        | (Type::RichText, Value::Rich(_))
909        | (Type::Action, Value::Action(_))
910        // The case's fields are read against the catalogue's set where the node is built.
911        | (Type::Cases { .. }, Value::Case { .. }) => true,
912        (Type::Option(inner), Value::Opt(Some(held))) => fits(held, inner),
913        (Type::Option(inner), other) => fits(other, inner),
914        (_, Value::Opt(Some(held))) => fits(held, ty),
915        (
916            Type::Text,
917            Value::List(_)
918            | Value::Ref(_)
919            | Value::Rich(_)
920            | Value::Map(_)
921            | Value::Action(_)
922            | Value::Picture(_)
923            | Value::File(_)
924            | Value::Link { .. },
925        ) => false,
926        (Type::Text, _) => true,
927        (Type::Choice { cases, .. }, Value::Text(case) | Value::Enum(case)) => cases.contains(case),
928        (Type::List(inner) | Type::Set(inner), Value::List(items)) => {
929            items.iter().all(|item| fits(item, inner))
930        }
931        (Type::Map { key, value }, Value::Map(entries)) => {
932            entries.iter().all(|(k, v)| fits(k, key) && fits(v, value))
933        }
934        _ => false,
935    }
936}
937
938#[cfg(test)]
939mod tests {
940    use super::super::Level;
941    use super::*;
942
943    fn validator() -> Validator<'static> {
944        Validator::new(
945            tilo_ui_graph::component::catalogue(),
946            PatchLimits::default(),
947        )
948    }
949
950    fn component(name: &str, key: &str, props: &[(&str, Value)]) -> Node {
951        let mut node = Node::empty(&format!("{COMPONENT_PREFIX}{name}"), key);
952        for (prop, value) in props {
953            node.props.insert((*prop).to_owned(), value.clone());
954        }
955        node
956    }
957
958    fn open(tree: Node) -> Vec<ToUi> {
959        vec![ToUi::Open {
960            level: Level::Root,
961            target: ResourceRef {
962                id: "doc".to_owned(),
963                ty: "notes.Notebook".to_owned(),
964            },
965            tree,
966            front: None,
967
968            capture_protected: false,
969        }]
970    }
971
972    /// A text an edit keeps is one the window can carry: the bytes of one string here are the
973    /// bytes of one text an action carries, so a paste at the limit is shown and a longer one is
974    /// refused where it is made.
975    #[test]
976    fn a_text_an_edit_keeps_is_one_a_window_carries() {
977        assert_eq!(
978            PatchLimits::default().string_bytes as usize,
979            tilo_actions::MAX_TEXT_BYTES
980        );
981    }
982
983    #[test]
984    fn a_tree_of_described_components_and_primitives_passes() {
985        let mut stack = Node::empty("stack", "s");
986        stack.props.insert("gap".to_owned(), Value::text("section"));
987        stack.props.insert("min.rem".to_owned(), Value::Float(12.0));
988        let mut button = component("Button", "b", &[("label", Value::text("Send"))]);
989        button.events.insert("press".to_owned(), Event::default());
990        stack.children = vec![
991            component(
992                "Text",
993                "t",
994                &[
995                    ("value", Value::text("2026-10-24")),
996                    ("value:as", Value::text("date")),
997                    ("role", Value::text("title")),
998                ],
999            ),
1000            button,
1001        ];
1002        assert_eq!(validator().to_ui(&open(stack)), Ok(()));
1003    }
1004
1005    /// A row's quiet fact is a day the person reads (`Today`, `Overdue`), and the time of day it
1006    /// is due at reads with it (`Today 9:00 AM`): the day is the prop the row declares, and the
1007    /// time its companion.
1008    #[test]
1009    fn a_day_reads_with_the_time_of_day_it_is_due_at() {
1010        let row = component(
1011            "ListRow",
1012            "t",
1013            &[
1014                ("title", Value::text("Call the landlord")),
1015                ("meta", Value::text("2026-11-03")),
1016                ("meta:as", Value::text("date")),
1017                ("meta:time", Value::text("2026-11-03T17:00:00Z")),
1018            ],
1019        );
1020        assert_eq!(validator().to_ui(&open(row)), Ok(()));
1021        let mistyped = component(
1022            "ListRow",
1023            "t",
1024            &[("title", Value::text("x")), ("meta:tmie", Value::text("x"))],
1025        );
1026        assert!(
1027            validator().to_ui(&open(mistyped)).is_err(),
1028            "a companion is a name the component declares a prop for, spelled as the host reads it"
1029        );
1030    }
1031
1032    #[test]
1033    fn what_a_component_does_not_declare_is_refused() {
1034        let unknown = component("Nothing", "x", &[]);
1035        assert!(validator().to_ui(&open(unknown)).is_err());
1036        let prop = component("Text", "t", &[("color", Value::text("red"))]);
1037        assert!(validator().to_ui(&open(prop)).is_err());
1038        let typed = component("Text", "t", &[("role", Value::text("shouting"))]);
1039        assert!(
1040            validator().to_ui(&open(typed)).is_err(),
1041            "a case not declared"
1042        );
1043        let mut event = component("Text", "t", &[("value", Value::text("x"))]);
1044        event.events.insert("press".to_owned(), Event::default());
1045        assert!(validator().to_ui(&open(event)).is_err());
1046        assert!(
1047            validator()
1048                .to_ui(&open(Node::empty("script", "s")))
1049                .is_err()
1050        );
1051    }
1052
1053    /// A slider over a value the view does not hold (a device's volume) is given that value,
1054    /// and says through `change` what the person did with it.
1055    #[test]
1056    fn a_value_given_to_a_control_with_a_change_event_passes() {
1057        let mut slider = component("Slider", "s", &[("value", Value::Float(0.4))]);
1058        slider.events.insert("change".to_owned(), Event::default());
1059        assert_eq!(validator().to_ui(&open(slider)), Ok(()));
1060        let wrong = component("Slider", "s", &[("value", Value::text("loud"))]);
1061        assert!(validator().to_ui(&open(wrong)).is_err());
1062    }
1063
1064    #[test]
1065    fn work_is_bounded() {
1066        let limits = PatchLimits {
1067            depth: 3,
1068            key_bytes: 16,
1069            ..PatchLimits::default()
1070        };
1071        let checked = Validator::new(tilo_ui_graph::component::catalogue(), limits);
1072        let mut deep = Node::empty("stack", "0");
1073        for level in 1..6 {
1074            deep = Node {
1075                children: vec![deep],
1076                ..Node::empty("stack", &level.to_string())
1077            };
1078        }
1079        assert_eq!(
1080            checked.to_ui(&open(deep)).map_err(|refused| refused.what),
1081            Err("over the limit of tree depth")
1082        );
1083        assert_eq!(
1084            checked
1085                .to_ui(&open(Node::empty(
1086                    "stack",
1087                    "a key far longer than sixteen bytes"
1088                )))
1089                .map_err(|refused| refused.what),
1090            Err("over the limit of key length")
1091        );
1092        assert!(
1093            validator()
1094                .to_ui(&open(component(
1095                    "Text",
1096                    "t",
1097                    &[("value", Value::Float(f64::NAN))]
1098                )))
1099                .is_err()
1100        );
1101    }
1102}