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 { .. } => Ok(()),
217            ToUi::Focus { key } => match key {
218                Some(key) => self.key(key),
219                None => Ok(()),
220            },
221            ToUi::Actions(catalogue) => {
222                self.carried(catalogue.len(), "over the limit of bytes in a catalogue")
223            }
224            ToUi::Heard(bytes) | ToUi::Outputs(bytes) => {
225                self.carried(bytes.len(), "over the limit of bytes in a message")
226            }
227            ToUi::CallPictures { shown, pictures } => {
228                if shown.len() > MAX_CALL_PICTURES || pictures.len() > MAX_CALL_PICTURES {
229                    return Err(Refused::invalid("over the limit of pictures in a message"));
230                }
231                for shown in shown {
232                    self.key(&shown.person)?;
233                }
234                for picture in pictures {
235                    self.key(&picture.person)?;
236                    self.key(&picture.stream)?;
237                    if picture.object.is_empty() || picture.object.len() > MAX_CALL_PICTURE_BYTES {
238                        return Err(Refused::invalid("a call picture is not one picture"));
239                    }
240                }
241                Ok(())
242            }
243            ToUi::Page { request, .. } => {
244                if request.len() > super::MAX_PAGE_BYTES {
245                    return Err(Refused::invalid(
246                        "over the limit of bytes in a page request",
247                    ));
248                }
249                Ok(())
250            }
251            ToUi::Front {
252                shows: Some((_, target)),
253                ..
254            } => self.target(target),
255            ToUi::Open { target, tree, .. } => {
256                self.key(&target.id)?;
257                self.key(&target.ty)?;
258                self.node(tree, 0)
259            }
260            ToUi::Patch { patches, .. } => {
261                if patches.len() > self.limits.messages as usize {
262                    return Err(Refused::invalid(concat!(
263                        "over the limit of ",
264                        "patches in a message"
265                    )));
266                }
267                patches.iter().try_for_each(|patch| self.patch(patch))
268            }
269            ToUi::Bound { key, value, .. } => {
270                self.key(key)?;
271                self.value(value, 0)
272            }
273            ToUi::Rows {
274                list, keys, rows, ..
275            } => {
276                self.key(list)?;
277                if keys.len() > self.limits.rows as usize || rows.len() > self.limits.rows as usize
278                {
279                    return Err(Refused::invalid(concat!(
280                        "over the limit of ",
281                        "rows in a message"
282                    )));
283                }
284                keys.iter().try_for_each(|key| self.key(key))?;
285                rows.iter().try_for_each(|row| self.node(row, 1))
286            }
287            ToUi::Spaces { keys, .. } => {
288                if keys.len() > self.limits.rows as usize {
289                    return Err(Refused::invalid(concat!(
290                        "over the limit of ",
291                        "views in a message"
292                    )));
293                }
294                keys.iter().try_for_each(|key| self.key(key))
295            }
296            ToUi::RowsChanged { list, changes, .. } => {
297                self.key(list)?;
298                if changes.len() > self.limits.rows as usize {
299                    return Err(Refused::invalid(concat!(
300                        "over the limit of ",
301                        "rows in a message"
302                    )));
303                }
304                changes.iter().try_for_each(|change| match change {
305                    RowChange::Inserted { key, .. } => self.key(key),
306                    RowChange::Changed { row } => self.node(row, 1),
307                    RowChange::Removed { .. } | RowChange::Moved { .. } | RowChange::Reset => {
308                        Ok(())
309                    }
310                })
311            }
312            ToUi::Notice { words, .. } => self.words(words),
313            ToUi::ShowRun { run } => self.key(run),
314            ToUi::Speak(language) => self.key(language),
315            ToUi::Ask(Some(ask)) => {
316                self.string(&ask.action)?;
317                self.string(&ask.invoker)
318            }
319            ToUi::Form(Some(form)) => {
320                self.string(&form.title)?;
321                self.string(&form.submit)?;
322                if let Some(error) = &form.error {
323                    self.string(error)?;
324                }
325                if let Some((_, key)) = &form.from {
326                    self.key(key)?;
327                }
328                if form.fields.len() > self.limits.messages as usize {
329                    return Err(Refused::invalid(concat!(
330                        "over the limit of ",
331                        "fields in a form"
332                    )));
333                }
334                form.fields.iter().try_for_each(|(key, text)| {
335                    self.key(key)?;
336                    self.string(text)
337                })?;
338                self.node(&form.tree, 1)
339            }
340        }
341    }
342
343    fn patch(&self, patch: &Patch) -> Result<(), Refused> {
344        match patch {
345            Patch::SetRoot(node) => self.node(node, 0),
346            Patch::Insert { parent, node, .. } => {
347                self.path(parent)?;
348                self.node(node, parent.len().saturating_add(1))
349            }
350            Patch::Remove { parent, key } | Patch::Move { parent, key, .. } => {
351                self.path(parent)?;
352                self.key(key)
353            }
354            // A prop, binding or event set on its own is checked against its node's kind when
355            // applied ([`Self::node`] of the node it changed).
356            Patch::SetProp { path, name, value } => {
357                self.path(path)?;
358                self.key(name)?;
359                value
360                    .as_ref()
361                    .map_or(Ok(()), |value| self.value(value, path.len()))
362            }
363            Patch::SetBinding { path, binding } => {
364                self.path(path)?;
365                binding
366                    .as_ref()
367                    .map_or(Ok(()), |binding| self.binding(binding))
368            }
369            Patch::SetEvent {
370                path,
371                event,
372                action,
373            } => {
374                self.path(path)?;
375                self.key(event)?;
376                action.as_ref().map_or(Ok(()), |event| self.event(event))
377            }
378            Patch::SetAnchor { path, anchor } => {
379                self.path(path)?;
380                anchor.as_ref().map_or(Ok(()), |anchor| self.key(anchor))
381            }
382            Patch::SpliceProp {
383                path, name, insert, ..
384            } => {
385                self.path(path)?;
386                self.key(name)?;
387                if insert.len() > self.limits.rows as usize {
388                    return Err(Refused::invalid(concat!(
389                        "over the limit of ",
390                        "items of a list value"
391                    )));
392                }
393                insert
394                    .iter()
395                    .try_for_each(|item| self.value(item, path.len().saturating_add(1)))
396            }
397        }
398    }
399
400    /// Check `node`, at `depth`, and everything under it: its kind, and each prop, binding,
401    /// event and child against it.
402    ///
403    /// # Errors
404    /// The first part of it that is not valid.
405    pub fn node(&self, node: &Node, depth: usize) -> Result<(), Refused> {
406        if depth > self.limits.depth as usize {
407            return Err(Refused::invalid(concat!(
408                "over the limit of ",
409                "tree depth"
410            )));
411        }
412        self.key(&node.key)?;
413        if node.props.len() > self.limits.props as usize {
414            return Err(Refused::invalid(concat!(
415                "over the limit of ",
416                "props of a node"
417            )));
418        }
419        if let Some(anchor) = &node.anchor {
420            self.key(anchor)?;
421        }
422        self.shape(node, depth)
423            .map_err(|refused| refused.within(format_args!("`{}` {}", node.kind, node.key)))?;
424        node.children
425            .iter()
426            .try_for_each(|child| self.node(child, depth.saturating_add(1)))
427    }
428
429    /// Check the node's own parts, not its children, against its kind.
430    pub fn shape(&self, node: &Node, depth: usize) -> Result<(), Refused> {
431        if let Some(name) = node.kind.strip_prefix(COMPONENT_PREFIX) {
432            let description = self
433                .catalogue
434                .get(name)
435                .ok_or_else(|| Refused::invalid("a component the toolkit does not describe"))?;
436            return self.component(node, description, depth);
437        }
438        if !primitive(&node.kind) {
439            return Err(Refused::invalid("a kind of node the host does not build"));
440        }
441        for (name, value) in &node.props {
442            self.key(name)?;
443            self.value(value, depth)
444                .map_err(|refused| refused.within(format_args!("prop `{name}`")))?;
445        }
446        for (name, event) in &node.events {
447            self.key(name)?;
448            self.event(event)?;
449        }
450        node.binding
451            .as_ref()
452            .map_or(Ok(()), |binding| self.binding(binding))
453    }
454
455    fn component(
456        &self,
457        node: &Node,
458        description: &Description,
459        depth: usize,
460    ) -> Result<(), Refused> {
461        for (name, value) in &node.props {
462            self.prop(name, value, description, depth)
463                .map_err(|refused| refused.within(format_args!("prop `{name}`")))?;
464        }
465        self.parts(node, description)
466    }
467
468    fn prop(
469        &self,
470        name: &str,
471        value: &Value,
472        description: &Description,
473        depth: usize,
474    ) -> Result<(), Refused> {
475        self.value(value, depth)?;
476        {
477            let declared = description
478                .prop(name)
479                .map(|prop| &prop.ty)
480                .or_else(|| description.state(name).map(|state| &state.ty))
481                // A value the view gives a control rather than binds to it (a device's
482                // volume): the control shows it, and its `change` event says what the person
483                // did with it.
484                .or_else(|| {
485                    description
486                        .event("change")
487                        .and_then(|_| description.binding(name))
488                        .map(|binding| &binding.ty)
489                });
490            match declared {
491                Some(ty) => {
492                    if !fits(value, ty) {
493                        return Err(Refused::invalid(
494                            "a prop holding a value of another type than its component declares",
495                        ));
496                    }
497                }
498                None if node_arg(name) => {}
499                // Which binding a node binds, of a component with several.
500                None if name == "bind" => {
501                    let Value::Text(bound) = value else {
502                        return Err(Refused::invalid("a binding named by other than text"));
503                    };
504                    if description.binding(bound).is_none() {
505                        return Err(Refused::invalid("a binding its component does not declare"));
506                    }
507                }
508                // A companion of a prop the component declares: `value:as` says which kind of
509                // text `value` holds, and `meta:time` the time of day the day `meta` is due at.
510                None if companion(name).is_some_and(|(prop, _)| {
511                    description.prop(prop).is_some() || description.state(prop).is_some()
512                }) => {}
513                None => {
514                    return Err(Refused::invalid("a prop its component does not declare"));
515                }
516            }
517        }
518        Ok(())
519    }
520
521    fn parts(&self, node: &Node, description: &Description) -> Result<(), Refused> {
522        for (name, event) in &node.events {
523            if description.event(name).is_none()
524                && description.binding(name).is_none()
525                && !offers(description, name)
526            {
527                return Err(Refused::invalid("an event its component does not declare")
528                    .within(format_args!("event `{name}`")));
529            }
530            self.event(event)?;
531        }
532        if let Some(binding) = &node.binding {
533            if description.bindings.is_empty() {
534                return Err(Refused::invalid("a binding on a component that takes none"));
535            }
536            self.binding(binding)?;
537        }
538        Ok(())
539    }
540
541    fn binding(&self, binding: &Binding) -> Result<(), Refused> {
542        self.string(&binding.name)?;
543        if let Some((target, field)) = &binding.field {
544            self.key(target)?;
545            self.key(field)?;
546        }
547        Ok(())
548    }
549
550    fn event(&self, event: &Event) -> Result<(), Refused> {
551        if let Some((target, field)) = &event.toggles {
552            self.key(target)?;
553            self.key(field)?;
554        }
555        if let Some(invoked) = &event.invokes {
556            self.key(&invoked.resource)?;
557            self.key(&invoked.action)?;
558        }
559        Ok(())
560    }
561
562    fn value(&self, value: &Value, depth: usize) -> Result<(), Refused> {
563        if depth > self.limits.depth as usize {
564            return Err(Refused::invalid(concat!(
565                "over the limit of ",
566                "value depth"
567            )));
568        }
569        match value {
570            Value::Unit | Value::Int(_) | Value::Bool(_) => Ok(()),
571            Value::Float(number) if number.is_finite() => Ok(()),
572            Value::Float(_) => Err(Refused::invalid("a number that is not finite")),
573            Value::Text(text) | Value::Error(text) => self.string(text),
574            Value::Enum(case) => self.key(case),
575            Value::Case { case, fields } => {
576                self.key(case)?;
577                for (name, held) in fields {
578                    self.key(name)?;
579                    self.value(held, depth.saturating_add(1))?;
580                }
581                Ok(())
582            }
583            Value::List(items) => {
584                if items.len() > self.limits.rows as usize {
585                    return Err(Refused::invalid(concat!(
586                        "over the limit of ",
587                        "items of a list value"
588                    )));
589                }
590                items
591                    .iter()
592                    .try_for_each(|item| self.value(item, depth.saturating_add(1)))
593            }
594            Value::Opt(held) => held
595                .as_deref()
596                .map_or(Ok(()), |held| self.value(held, depth.saturating_add(1))),
597            Value::Ref(resource) => {
598                self.key(&resource.id)?;
599                self.key(&resource.ty)
600            }
601            Value::Actor(who) => {
602                self.key(who.id.id())?;
603                self.string(&who.name)
604            }
605            Value::Map(entries) => {
606                if entries.len() > self.limits.rows as usize {
607                    return Err(Refused::invalid(concat!(
608                        "over the limit of ",
609                        "entries of a map value"
610                    )));
611                }
612                entries.iter().try_for_each(|(key, value)| {
613                    self.value(key, depth.saturating_add(1))?;
614                    self.value(value, depth.saturating_add(1))
615                })
616            }
617            Value::Action(offered) => {
618                self.string(&offered.label)?;
619                self.key(&offered.event)?;
620                offered.icon.as_ref().map_or(Ok(()), |icon| self.key(icon))
621            }
622            Value::Picture(picture) => self.string(&picture.src),
623            Value::File(file) => {
624                self.string(&file.name)?;
625                self.key(&file.media)?;
626                self.string(&file.url)
627            }
628            Value::Link { reference, title } => {
629                self.string(reference)?;
630                self.string(title)
631            }
632            Value::Rich(rich) => {
633                if rich.blocks.len() > self.limits.rows as usize
634                    || rich.embeds.len() > self.limits.rows as usize
635                {
636                    return Err(Refused::invalid(concat!(
637                        "over the limit of ",
638                        "paragraphs of rich text"
639                    )));
640                }
641                rich.strings().try_for_each(|text| self.string(text))
642            }
643        }
644    }
645
646    fn words(&self, words: &Words) -> Result<(), Refused> {
647        match words {
648            Words::Plain(text) => self.string(text),
649            Words::Phrase { id, args } => {
650                self.key(id)?;
651                if args.len() > self.limits.props as usize {
652                    return Err(Refused::invalid(concat!(
653                        "over the limit of ",
654                        "arguments of a phrase"
655                    )));
656                }
657                args.iter().try_for_each(|(name, value)| {
658                    self.key(name)?;
659                    self.string(value)
660                })
661            }
662        }
663    }
664
665    fn path(&self, path: &[String]) -> Result<(), Refused> {
666        if path.len() > self.limits.path as usize {
667            return Err(Refused::invalid(concat!(
668                "over the limit of ",
669                "path length"
670            )));
671        }
672        path.iter().try_for_each(|key| self.key(key))
673    }
674
675    fn key(&self, key: &str) -> Result<(), Refused> {
676        if key.len() > self.limits.key_bytes as usize {
677            return Err(Refused::invalid(concat!(
678                "over the limit of ",
679                "key length"
680            )));
681        }
682        Ok(())
683    }
684
685    fn resource(&self, resource: &ResourceRef) -> Result<(), Refused> {
686        self.key(&resource.id)?;
687        self.key(&resource.ty)
688    }
689
690    fn string(&self, text: &str) -> Result<(), Refused> {
691        if text.len() > self.limits.string_bytes as usize {
692            return Err(Refused::invalid(concat!(
693                "over the limit of ",
694                "string length"
695            )));
696        }
697        Ok(())
698    }
699
700    /// Check one batch the host sent an app: in an app host, what the window says it did is
701    /// as hostile as what an app sends its window.
702    ///
703    /// # Errors
704    /// The first thing in it that is not valid.
705    pub fn to_app(&self, batch: &[ToApp]) -> Result<(), Refused> {
706        if batch.len() > self.limits.messages as usize {
707            return Err(Refused::invalid(concat!(
708                "over the limit of ",
709                "messages in a batch"
710            )));
711        }
712        for message in batch {
713            self.to_app_message(message)?;
714        }
715        Ok(())
716    }
717
718    /// Check one message the host sent an app: the keys it names, then the value it carries.
719    fn to_app_message(&self, message: &ToApp) -> Result<(), Refused> {
720        self.to_app_targets(message)?;
721        self.to_app_payload(message)
722    }
723
724    /// The keys and resources `message` names.
725    fn to_app_targets(&self, message: &ToApp) -> Result<(), Refused> {
726        match message {
727            ToApp::Fire { key, event, .. } => {
728                self.key(key)?;
729                self.key(event)?;
730            }
731            ToApp::Toggle { target, key, .. }
732            | ToApp::Splice { target, key, .. }
733            | ToApp::Edit { target, key, .. }
734            | ToApp::EditRich { target, key, .. } => {
735                self.resource(target)?;
736                self.key(key)?;
737            }
738            ToApp::Resolve { key, .. } => self.key(key)?,
739            ToApp::Rows {
740                list, open, menu, ..
741            } => {
742                for key in std::iter::once(list).chain(open).chain(menu) {
743                    self.key(key)?;
744                }
745            }
746            ToApp::Focus { at } => {
747                if let Some((_, key)) = at {
748                    self.key(key)?;
749                }
750            }
751            ToApp::FormEdit { field, .. } => self.key(field)?,
752            ToApp::Open { .. }
753            | ToApp::OpenReference { .. }
754            | ToApp::Space { .. }
755            | ToApp::Invoke { .. }
756            | ToApp::Serving { .. }
757            | ToApp::PageAnswer { .. }
758            | ToApp::PagePrompt { .. }
759            | ToApp::Back
760            | ToApp::Answer(_)
761            | ToApp::Undo
762            | ToApp::Redo
763            | ToApp::Composing(_)
764            | ToApp::Held(_)
765            | ToApp::SaveAgain
766            | ToApp::History { .. }
767            | ToApp::FormSubmit { .. }
768            | ToApp::FormCancel { .. } => {}
769        }
770        Ok(())
771    }
772
773    /// The value `message` carries, and how large it comes to.
774    fn to_app_payload(&self, message: &ToApp) -> Result<(), Refused> {
775        match message {
776            ToApp::Fire {
777                value: Some(value), ..
778            } => self.value(value, 0),
779            ToApp::Splice { insert, .. } => self.string(insert),
780            ToApp::Edit { text, .. } | ToApp::FormEdit { text, .. } => self.string(text),
781            ToApp::EditRich { rich, .. } => self.value(&Value::Rich(rich.clone()), 0),
782            ToApp::Open { resource } => self.resource(resource),
783            ToApp::OpenReference { reference } => self.string(reference),
784            ToApp::Rows { start, end, .. } => {
785                if end < start || end.saturating_sub(*start) > self.limits.rows {
786                    return Err(Refused::invalid(concat!(
787                        "over the limit of ",
788                        "rows in a message"
789                    )));
790                }
791                Ok(())
792            }
793            ToApp::Space {
794                width, height, rem, ..
795            } => {
796                if !(width.is_finite()
797                    && height.is_finite()
798                    && *width >= 0.0
799                    && *height >= 0.0
800                    && rem.is_finite()
801                    && *rem > 0.0)
802                {
803                    return Err(Refused::invalid("a space is no size"));
804                }
805                Ok(())
806            }
807            ToApp::Invoke { address, argument } => self.invoke(address, argument.as_deref()),
808            ToApp::Serving { call, invoker } => self.serving(call, invoker.as_deref()),
809            ToApp::PageAnswer { answer, .. } => {
810                if answer.len() > super::MAX_PAGE_BYTES {
811                    return Err(Refused::invalid("over the limit of bytes in a page answer"));
812                }
813                Ok(())
814            }
815            ToApp::PagePrompt { prompt } => {
816                if prompt.len() > self.limits.string_bytes as usize {
817                    return Err(Refused::invalid(
818                        "over the limit of bytes in a page's prompt",
819                    ));
820                }
821                Ok(())
822            }
823            _ => Ok(()),
824        }
825    }
826
827    /// Check an action the host asks an app to run.
828    fn invoke(&self, address: &ActionAddress, argument: Option<&str>) -> Result<(), Refused> {
829        self.key(&address.resource)?;
830        self.key(&address.action)?;
831        argument.map_or(Ok(()), |argument| self.string(argument))
832    }
833
834    /// Check a signed call the host serves for its invoker.
835    fn serving(&self, call: &[u8], invoker: Option<&str>) -> Result<(), Refused> {
836        if call.len() > self.limits.string_bytes as usize {
837            return Err(Refused::invalid(
838                "a signed call is over the limit of a string",
839            ));
840        }
841        invoker.map_or(Ok(()), |invoker| self.string(invoker))
842    }
843}
844
845/// The event an action offered in the prop `prop` fires: `actions.2` for the third of
846/// `actions`. Its node gives it what the action runs, as it gives its declared events.
847#[must_use]
848pub fn offered_event(prop: &str, index: usize) -> String {
849    format!("{prop}.{index}")
850}
851
852/// Whether `event` is one an action offered in a prop of the component fires
853/// ([`offered_event`]): the host binds such an event to the action it runs.
854#[must_use]
855pub fn offers(description: &Description, event: &str) -> bool {
856    fn holds_actions(ty: &Type) -> bool {
857        match ty {
858            Type::Action => true,
859            Type::Option(inner) | Type::List(inner) | Type::Set(inner) => holds_actions(inner),
860            Type::Map { value, .. } => holds_actions(value),
861            _ => false,
862        }
863    }
864    event
865        .rsplit_once('.')
866        .filter(|(_, index)| !index.is_empty() && index.bytes().all(|b| b.is_ascii_digit()))
867        .and_then(|(prop, _)| description.prop(prop))
868        .is_some_and(|prop| holds_actions(&prop.ty))
869}
870
871/// Whether `name` is a sizing or placement argument every node takes, with its unit
872/// (`min.rem`).
873fn node_arg(name: &str) -> bool {
874    let base = name
875        .strip_suffix(".rem")
876        .or_else(|| name.strip_suffix(".dp"))
877        .unwrap_or(name);
878    NODE_ARGS.contains(&base)
879}
880
881/// Whether `value` is one of the type `ty`, as the host reads it into a widget: text shows any
882/// value as text, a whole number is a number, an `Option` holds nothing or a value.
883#[must_use]
884pub fn fits(value: &Value, ty: &Type) -> bool {
885    match (ty, value) {
886        (Type::Option(_), Value::Opt(None) | Value::Unit)
887        | (Type::Int, Value::Int(_))
888        | (Type::Float, Value::Float(_) | Value::Int(_))
889        | (Type::Bool, Value::Bool(_) | Value::Int(_))
890        | (Type::Actor, Value::Actor(_))
891        | (Type::Resource, Value::Ref(_))
892        | (Type::Icon | Type::Time, Value::Text(_))
893        | (Type::Picture, Value::Picture(_))
894        | (Type::File, Value::File(_))
895        | (Type::Link, Value::Link { .. })
896        | (Type::RichText, Value::Rich(_))
897        | (Type::Action, Value::Action(_))
898        // The case's fields are read against the catalogue's set where the node is built.
899        | (Type::Cases { .. }, Value::Case { .. }) => true,
900        (Type::Option(inner), Value::Opt(Some(held))) => fits(held, inner),
901        (Type::Option(inner), other) => fits(other, inner),
902        (_, Value::Opt(Some(held))) => fits(held, ty),
903        (
904            Type::Text,
905            Value::List(_)
906            | Value::Ref(_)
907            | Value::Rich(_)
908            | Value::Map(_)
909            | Value::Action(_)
910            | Value::Picture(_)
911            | Value::File(_)
912            | Value::Link { .. },
913        ) => false,
914        (Type::Text, _) => true,
915        (Type::Choice { cases, .. }, Value::Text(case) | Value::Enum(case)) => cases.contains(case),
916        (Type::List(inner) | Type::Set(inner), Value::List(items)) => {
917            items.iter().all(|item| fits(item, inner))
918        }
919        (Type::Map { key, value }, Value::Map(entries)) => {
920            entries.iter().all(|(k, v)| fits(k, key) && fits(v, value))
921        }
922        _ => false,
923    }
924}
925
926#[cfg(test)]
927mod tests {
928    use super::super::Level;
929    use super::*;
930
931    fn validator() -> Validator<'static> {
932        Validator::new(
933            tilo_ui_graph::component::catalogue(),
934            PatchLimits::default(),
935        )
936    }
937
938    fn component(name: &str, key: &str, props: &[(&str, Value)]) -> Node {
939        let mut node = Node::empty(&format!("{COMPONENT_PREFIX}{name}"), key);
940        for (prop, value) in props {
941            node.props.insert((*prop).to_owned(), value.clone());
942        }
943        node
944    }
945
946    fn open(tree: Node) -> Vec<ToUi> {
947        vec![ToUi::Open {
948            level: Level::Root,
949            target: ResourceRef {
950                id: "doc".to_owned(),
951                ty: "notes.Notebook".to_owned(),
952            },
953            tree,
954            front: None,
955
956            capture_protected: false,
957        }]
958    }
959
960    /// A text an edit keeps is one the window can carry: the bytes of one string here are the
961    /// bytes of one text an action carries, so a paste at the limit is shown and a longer one is
962    /// refused where it is made.
963    #[test]
964    fn a_text_an_edit_keeps_is_one_a_window_carries() {
965        assert_eq!(
966            PatchLimits::default().string_bytes as usize,
967            tilo_actions::MAX_TEXT_BYTES
968        );
969    }
970
971    #[test]
972    fn a_tree_of_described_components_and_primitives_passes() {
973        let mut stack = Node::empty("stack", "s");
974        stack.props.insert("gap".to_owned(), Value::text("section"));
975        stack.props.insert("min.rem".to_owned(), Value::Float(12.0));
976        let mut button = component("Button", "b", &[("label", Value::text("Send"))]);
977        button.events.insert("press".to_owned(), Event::default());
978        stack.children = vec![
979            component(
980                "Text",
981                "t",
982                &[
983                    ("value", Value::text("2026-10-24")),
984                    ("value:as", Value::text("date")),
985                    ("role", Value::text("title")),
986                ],
987            ),
988            button,
989        ];
990        assert_eq!(validator().to_ui(&open(stack)), Ok(()));
991    }
992
993    /// A row's quiet fact is a day the person reads (`Today`, `Overdue`), and the time of day it
994    /// is due at reads with it (`Today 9:00 AM`): the day is the prop the row declares, and the
995    /// time its companion.
996    #[test]
997    fn a_day_reads_with_the_time_of_day_it_is_due_at() {
998        let row = component(
999            "ListRow",
1000            "t",
1001            &[
1002                ("title", Value::text("Call the landlord")),
1003                ("meta", Value::text("2026-11-03")),
1004                ("meta:as", Value::text("date")),
1005                ("meta:time", Value::text("2026-11-03T17:00:00Z")),
1006            ],
1007        );
1008        assert_eq!(validator().to_ui(&open(row)), Ok(()));
1009        let mistyped = component(
1010            "ListRow",
1011            "t",
1012            &[("title", Value::text("x")), ("meta:tmie", Value::text("x"))],
1013        );
1014        assert!(
1015            validator().to_ui(&open(mistyped)).is_err(),
1016            "a companion is a name the component declares a prop for, spelled as the host reads it"
1017        );
1018    }
1019
1020    #[test]
1021    fn what_a_component_does_not_declare_is_refused() {
1022        let unknown = component("Nothing", "x", &[]);
1023        assert!(validator().to_ui(&open(unknown)).is_err());
1024        let prop = component("Text", "t", &[("color", Value::text("red"))]);
1025        assert!(validator().to_ui(&open(prop)).is_err());
1026        let typed = component("Text", "t", &[("role", Value::text("shouting"))]);
1027        assert!(
1028            validator().to_ui(&open(typed)).is_err(),
1029            "a case not declared"
1030        );
1031        let mut event = component("Text", "t", &[("value", Value::text("x"))]);
1032        event.events.insert("press".to_owned(), Event::default());
1033        assert!(validator().to_ui(&open(event)).is_err());
1034        assert!(
1035            validator()
1036                .to_ui(&open(Node::empty("script", "s")))
1037                .is_err()
1038        );
1039    }
1040
1041    /// A slider over a value the view does not hold (a device's volume) is given that value,
1042    /// and says through `change` what the person did with it.
1043    #[test]
1044    fn a_value_given_to_a_control_with_a_change_event_passes() {
1045        let mut slider = component("Slider", "s", &[("value", Value::Float(0.4))]);
1046        slider.events.insert("change".to_owned(), Event::default());
1047        assert_eq!(validator().to_ui(&open(slider)), Ok(()));
1048        let wrong = component("Slider", "s", &[("value", Value::text("loud"))]);
1049        assert!(validator().to_ui(&open(wrong)).is_err());
1050    }
1051
1052    #[test]
1053    fn work_is_bounded() {
1054        let limits = PatchLimits {
1055            depth: 3,
1056            key_bytes: 16,
1057            ..PatchLimits::default()
1058        };
1059        let checked = Validator::new(tilo_ui_graph::component::catalogue(), limits);
1060        let mut deep = Node::empty("stack", "0");
1061        for level in 1..6 {
1062            deep = Node {
1063                children: vec![deep],
1064                ..Node::empty("stack", &level.to_string())
1065            };
1066        }
1067        assert_eq!(
1068            checked.to_ui(&open(deep)).map_err(|refused| refused.what),
1069            Err("over the limit of tree depth")
1070        );
1071        assert_eq!(
1072            checked
1073                .to_ui(&open(Node::empty(
1074                    "stack",
1075                    "a key far longer than sixteen bytes"
1076                )))
1077                .map_err(|refused| refused.what),
1078            Err("over the limit of key length")
1079        );
1080        assert!(
1081            validator()
1082                .to_ui(&open(component(
1083                    "Text",
1084                    "t",
1085                    &[("value", Value::Float(f64::NAN))]
1086                )))
1087                .is_err()
1088        );
1089    }
1090}