Skip to main content

day_script_protocol/
ids.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3//! Compiled declaration catalogs and family-level dayscript evidence.
4use serde::{Deserialize, Serialize};
5use std::collections::BTreeSet;
6
7#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
8pub struct IdDeclaration {
9    pub family: String,
10    pub keyed: bool,
11    pub package: String,
12    pub version: String,
13    pub locations: Vec<String>,
14}
15#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
16pub struct IdCatalog {
17    pub schema_version: u32,
18    pub declarations: Vec<IdDeclaration>,
19}
20impl IdCatalog {
21    /// Check the catalog's schema version and that each family is declared once.
22    ///
23    /// # Errors
24    ///
25    /// Returns an error when the schema version is not 1 or two declarations share a family.
26    pub fn validate(&self) -> Result<(), String> {
27        if self.schema_version != 1 {
28            return Err("unsupported element registry version".into());
29        }
30        let mut names = BTreeSet::new();
31        for d in &self.declarations {
32            if !names.insert(&d.family) {
33                return Err(format!("duplicate registry family {}", d.family));
34            }
35        }
36        Ok(())
37    }
38    /// Find the declaration that the element ID `id` belongs to.
39    ///
40    /// # Errors
41    ///
42    /// Returns an error when the ID's family is not declared, the ID is keyed where the declaration
43    /// is static (or the reverse), or its key is not canonical percent-encoded UTF-8.
44    pub fn resolve(&self, id: &str) -> Result<&IdDeclaration, String> {
45        let mut split = None;
46        let mut chars = id.char_indices().peekable();
47        while let Some((i, c)) = chars.next() {
48            if c == ':' {
49                if chars.peek().is_some_and(|(_, c)| *c == ':') {
50                    chars.next();
51                } else {
52                    split = Some(i);
53                    break;
54                }
55            }
56        }
57        let family = split.map_or(id, |i| &id[..i]);
58        let d = self
59            .declarations
60            .iter()
61            .find(|d| d.family == family)
62            .ok_or_else(|| format!("undeclared element ID {family:?}"))?;
63        if d.keyed != split.is_some() {
64            return Err(format!("element ID {id:?} has wrong static/keyed shape"));
65        }
66        if let Some(i) = split {
67            validate_key(&id[i + 1..])?;
68        }
69        Ok(d)
70    }
71}
72fn unreserved(b: u8) -> bool {
73    b.is_ascii_alphanumeric() || b"-._~".contains(&b)
74}
75fn validate_key(key: &str) -> Result<(), String> {
76    let b = key.as_bytes();
77    let mut out = Vec::new();
78    let mut i = 0;
79    while i < b.len() {
80        if unreserved(b[i]) {
81            out.push(b[i]);
82            i += 1;
83            continue;
84        }
85        if b[i] != b'%' || i + 2 >= b.len() {
86            return Err("noncanonical element key; use percent-encoded UTF-8".into());
87        }
88        let digit = |x: u8| match x {
89            b'0'..=b'9' => Some(x - b'0'),
90            b'A'..=b'F' => Some(x - b'A' + 10),
91            _ => None,
92        };
93        let (Some(hi), Some(lo)) = (digit(b[i + 1]), digit(b[i + 2])) else {
94            return Err("element key escapes require uppercase hexadecimal".into());
95        };
96        let byte = (hi << 4) | lo;
97        if unreserved(byte) {
98            return Err("unnecessary element key escape".into());
99        }
100        out.push(byte);
101        i += 3;
102    }
103    String::from_utf8(out).map_err(|_| "element key is not UTF-8".to_owned())?;
104    Ok(())
105}
106#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
107#[serde(rename_all = "snake_case")]
108pub enum EvidenceClass {
109    Interaction,
110    Assertion,
111    Observed,
112    Negative,
113}
114#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
115pub struct IdEvidence {
116    pub family: String,
117    pub class: EvidenceClass,
118}
119
120impl crate::Step {
121    /// Element references only: model row keys, routes, strings and screenshot names are
122    /// intentionally excluded. Secondary geometry references are validated, not credited.
123    ///
124    /// # Panics
125    ///
126    /// Panics if the step does not serialize as JSON, which no [`Step`](crate::Step) can cause.
127    #[must_use]
128    pub fn element_references(&self) -> Vec<String> {
129        let value = serde_json::to_value(self).expect("serializable step");
130        let mut ids = Vec::new();
131        for field in ["id", "relative_to", "item_id"] {
132            if let Some(id) = value.get(field).and_then(|v| v.as_str()) {
133                ids.push(id.to_owned());
134            }
135        }
136        if let Self::Toolbar { item, .. } = self {
137            ids.push(item.clone());
138        }
139        ids
140    }
141    #[must_use]
142    pub fn evidence_class(&self) -> Option<EvidenceClass> {
143        use EvidenceClass::{Assertion, Interaction, Negative, Observed};
144        match self {
145            Self::WaitFor { .. } => Some(Observed),
146            Self::AssertMissing { .. } | Self::AssertHidden { .. } => Some(Negative),
147            Self::AssertVisible { .. }
148            | Self::AssertText { .. }
149            | Self::AssertValue { .. }
150            | Self::AssertFrame { .. }
151            | Self::AssertNative { .. }
152            | Self::AssertFocused { .. } => Some(Assertion),
153            Self::WebEval { text, contains, .. } => {
154                if text.is_some() || contains.is_some() {
155                    Some(Assertion)
156                } else {
157                    Some(Observed)
158                }
159            }
160            Self::Tap { .. }
161            | Self::Key { .. }
162            | Self::ScrollTo { .. }
163            | Self::Drag { .. }
164            | Self::Hover { .. }
165            | Self::Pan { .. }
166            | Self::Pinch { .. }
167            | Self::Rotate { .. }
168            | Self::Submit { .. }
169            | Self::Input { .. }
170            | Self::SetValue { .. }
171            | Self::Toggle { .. }
172            | Self::Select { .. }
173            | Self::Focus { .. }
174            | Self::Reorder { .. }
175            | Self::Expand { .. }
176            | Self::TreeMove { .. }
177            | Self::DeleteRow { .. }
178            | Self::SwipeRow { .. }
179            | Self::Menu { .. }
180            | Self::Toolbar { .. }
181            | Self::ContextMenu { .. } => Some(Interaction),
182            _ => None,
183        }
184    }
185}
186#[cfg(test)]
187mod tests {
188    use super::*;
189    #[test]
190    fn namespace_and_canonical_keys() {
191        let c = IdCatalog {
192            schema_version: 1,
193            declarations: vec![IdDeclaration {
194                family: "account::row".into(),
195                keyed: true,
196                package: "fixture".into(),
197                version: "0".into(),
198                locations: vec![],
199            }],
200        };
201        for s in ["account::row:42", "account::row:", "account::row:%3Ab"] {
202            assert!(c.resolve(s).is_ok(), "{s}");
203        }
204        for s in [
205            "account::row",
206            "account::row:%3ab",
207            "account::row:%41",
208            "account::row:%FF",
209            "unknown:1",
210        ] {
211            assert!(c.resolve(s).is_err(), "{s}");
212        }
213    }
214}