Skip to main content

cli_core/
render.rs

1//! Shared wire-parse + render surface for CLI and TUI consumers.
2
3pub mod account_order;
4pub mod schema;
5
6use nomiscript::{Reader, Value, format_value_display, list_to_vec};
7use thiserror::Error;
8
9use rpc::{EnvelopeError, ErrorCode, ResponsePayload, parse_response, try_expr_to_value};
10
11#[derive(Debug, Clone, PartialEq)]
12pub enum WireValue {
13    Value(Value),
14}
15
16/// A structured row from a list reply, carrying an optional entity id alongside display cells.
17///
18/// The `cells` are identical to what [`value_to_rows`] produces — display is unchanged.
19/// The `id` is the `:id` plist field extracted separately for navigation (e.g. open/edit).
20#[derive(Debug, Clone, PartialEq)]
21pub struct ListRow {
22    /// Entity id from the `:id` plist field, or `None` when absent.
23    pub id: Option<String>,
24    /// Display cells, byte-identical to the `value_to_rows` output for this element.
25    pub cells: Vec<String>,
26}
27
28#[derive(Debug, Error)]
29pub enum RenderError {
30    #[error("envelope parse failed: {0}")]
31    Envelope(#[from] EnvelopeError),
32    #[error("wire error from server: [{}] {}", .0.code, .0.message)]
33    Server(ErrorReply),
34    #[error("re-parse of printed list failed: {0}")]
35    ListReparse(String),
36}
37
38/// Parse a wire reply into a [`WireValue`].
39///
40/// The `:value` payload is returned as-is: a `pair:*` or `entity:*` result
41/// arrives as a structured list, a string stays `Value::String(s)`. Callers
42/// of a string native that prints a list must call [`reparse_list`] on it.
43///
44/// Returns `Err(RenderError::Server)` when the frame contains `:error`.
45pub fn parse_wire(wire: &str) -> Result<WireValue, RenderError> {
46    let response = parse_response(wire)?;
47    match response.payload {
48        ResponsePayload::Error {
49            code,
50            message,
51            detail,
52        } => Err(RenderError::Server(ErrorReply {
53            code: code.as_symbol().to_string(),
54            message,
55            detail,
56        })),
57        ResponsePayload::Value(v) => Ok(WireValue::Value(v)),
58    }
59}
60
61/// One rejected field of a `form-invalid` reply.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct FieldError {
64    /// Field address: `key`, `rows.i` or `rows.i.key`.
65    pub field: String,
66    pub message: String,
67}
68
69/// The `:error` of a wire reply, the one parsed form every client reads.
70#[derive(Debug, Clone, PartialEq)]
71pub struct ErrorReply {
72    pub code: String,
73    pub message: String,
74    pub detail: Option<Value>,
75}
76
77impl ErrorReply {
78    /// The rejected fields of a `form-invalid` reply; empty for any other
79    /// reply and for entries lacking a field or a message.
80    #[must_use]
81    pub fn field_errors(&self) -> Vec<FieldError> {
82        let Some(detail) = self
83            .detail
84            .as_ref()
85            .filter(|_| self.code == ErrorCode::FORM_INVALID)
86        else {
87            return Vec::new();
88        };
89        list_to_vec(detail)
90            .unwrap_or_default()
91            .iter()
92            .filter_map(|item| {
93                Some(FieldError {
94                    field: crate::eval::plist_field(item, ":field")?,
95                    message: crate::eval::plist_field(item, ":message")?,
96                })
97            })
98            .collect()
99    }
100}
101
102/// Paren-nesting depth above which [`reparse_list`] refuses to parse, to keep
103/// the reader's per-paren recursion within the native stack.
104const MAX_REPARSE_DEPTH: usize = 64;
105
106/// Largest paren-nesting depth in `s`, ignoring parens inside string literals
107/// (so a `"USD)"` cell does not inflate the count). Cheap single pass.
108fn max_nesting_depth(s: &str) -> usize {
109    let (mut depth, mut max) = (0usize, 0usize);
110    let (mut in_string, mut escaped) = (false, false);
111    for ch in s.chars() {
112        if in_string {
113            match (escaped, ch) {
114                (true, _) => escaped = false,
115                (false, '\\') => escaped = true,
116                (false, '"') => in_string = false,
117                _ => {}
118            }
119            continue;
120        }
121        match ch {
122            '"' => in_string = true,
123            '(' => {
124                depth += 1;
125                max = max.max(depth);
126            }
127            ')' => depth = depth.saturating_sub(1),
128            _ => {}
129        }
130    }
131    max
132}
133
134/// Re-parse a printed-list string (as returned by `string` natives that print
135/// a plist, e.g. `form-options` or `get-transaction-detail`) into a
136/// structured [`Value`].
137///
138/// Scalar string values (UUIDs, names) must NOT be passed here, as they may
139/// accidentally parse as atoms or produce incorrect values.
140pub fn reparse_list(s: &str) -> Result<Value, RenderError> {
141    // Bound nesting BEFORE handing the string to the reader: `Reader::parse`
142    // itself recurses per paren and overflows the native stack on deeply
143    // nested input. Real entity/balance plists are shallow (depth 1-2), so a
144    // generous cap rejects malformed/hostile wire data without parsing it.
145    if max_nesting_depth(s) > MAX_REPARSE_DEPTH {
146        return Err(RenderError::ListReparse(format!(
147            "printed list nested beyond {MAX_REPARSE_DEPTH}"
148        )));
149    }
150    let program = Reader::parse(s).map_err(|e| RenderError::ListReparse(e.to_string()))?;
151    let mut iter = program.exprs.into_iter();
152    let Some(expr) = iter.next() else {
153        return Ok(Value::Nil);
154    };
155    if iter.next().is_some() {
156        return Err(RenderError::ListReparse(
157            "printed list string contains multiple top-level expressions".into(),
158        ));
159    }
160    try_expr_to_value(expr).map_err(|e| RenderError::ListReparse(e.to_string()))
161}
162
163/// Walk a [`Value`] into columnar rows for display.
164///
165/// - `Nil` → no rows
166/// - A top-level plist (`(:k v :k v …)`) → ONE row of its field values
167/// - Other proper list → one row per element; plist elements yield field cells
168/// - Scalar → single 1-cell row
169pub fn value_to_rows(value: &Value) -> Vec<Vec<String>> {
170    match value {
171        Value::Nil => vec![],
172        Value::Pair(_) => {
173            if let Some(row) = try_plist_values(value) {
174                vec![row]
175            } else if let Some(elements) = list_to_vec(value) {
176                elements.iter().map(element_to_row).collect()
177            } else {
178                vec![vec![format_value_display(value)]]
179            }
180        }
181        other => vec![vec![format_value_display(other)]],
182    }
183}
184
185/// Walk a [`Value`] into [`ListRow`]s, pairing display cells with the `:id` plist field.
186///
187/// The `cells` of every row are byte-identical to what [`value_to_rows`] produces;
188/// the `id` is extracted separately by `row_id`. Real list rows are typed records
189/// with a leading tag (`(:account :id … :name …)`), so the id is found by position,
190/// not by assuming `:id` sits at an even key slot.
191pub fn rows_with_ids(value: &Value) -> Vec<ListRow> {
192    match value {
193        Value::Nil => vec![],
194        Value::Pair(_) => {
195            if let Some(cells) = try_plist_values(value) {
196                vec![ListRow {
197                    id: row_id(value),
198                    cells,
199                }]
200            } else if let Some(elements) = list_to_vec(value) {
201                elements.iter().map(element_to_list_row).collect()
202            } else {
203                vec![ListRow {
204                    id: None,
205                    cells: vec![format_value_display(value)],
206                }]
207            }
208        }
209        other => vec![ListRow {
210            id: None,
211            cells: vec![format_value_display(other)],
212        }],
213    }
214}
215
216fn element_to_list_row(element: &Value) -> ListRow {
217    match element {
218        Value::Pair(_) => {
219            let cells =
220                try_plist_values(element).unwrap_or_else(|| vec![format_value_display(element)]);
221            ListRow {
222                id: row_id(element),
223                cells,
224            }
225        }
226        other => ListRow {
227            id: None,
228            cells: vec![format_value_display(other)],
229        },
230    }
231}
232
233/// Extract a row's `:id`, reusing the single-source plist scan.
234///
235/// [`crate::eval::plist_field`] finds `:id` by position over the top-level items,
236/// so a leading type tag (`:account`) does not displace it and a nested split's
237/// `:id` is never reached.
238fn row_id(value: &Value) -> Option<String> {
239    crate::eval::plist_field(value, ":id")
240}
241
242fn element_to_row(element: &Value) -> Vec<String> {
243    match element {
244        Value::Pair(_) => {
245            if let Some(cells) = try_plist_values(element) {
246                return cells;
247            }
248            vec![format_value_display(element)]
249        }
250        other => vec![format_value_display(other)],
251    }
252}
253
254fn is_plist_key(v: &Value) -> bool {
255    matches!(v, Value::Symbol(s) if s.starts_with(':'))
256}
257
258fn try_plist_values(value: &Value) -> Option<Vec<String>> {
259    let items = list_to_vec(value)?;
260    if items.len() < 2 || !items.len().is_multiple_of(2) {
261        return None;
262    }
263    if !items.iter().step_by(2).all(is_plist_key) {
264        return None;
265    }
266    Some(
267        items
268            .into_iter()
269            .skip(1)
270            .step_by(2)
271            .map(|v| format_value_display(&v))
272            .collect(),
273    )
274}
275
276#[cfg(test)]
277mod tests;