1
//! Shared wire-parse + render surface for CLI and TUI consumers.
2

            
3
pub mod account_order;
4
pub mod schema;
5

            
6
use nomiscript::{Reader, Value, format_value_display, list_to_vec};
7
use thiserror::Error;
8

            
9
use rpc::{EnvelopeError, ErrorCode, ResponsePayload, parse_response, try_expr_to_value};
10

            
11
#[derive(Debug, Clone, PartialEq)]
12
pub 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)]
21
pub 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)]
29
pub 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`.
45
28534
pub fn parse_wire(wire: &str) -> Result<WireValue, RenderError> {
46
28534
    let response = parse_response(wire)?;
47
28470
    match response.payload {
48
        ResponsePayload::Error {
49
            code,
50
            message,
51
            detail,
52
3074
        } => Err(RenderError::Server(ErrorReply {
53
3074
            code: code.as_symbol().to_string(),
54
3074
            message,
55
3074
            detail,
56
3074
        })),
57
25396
        ResponsePayload::Value(v) => Ok(WireValue::Value(v)),
58
    }
59
28534
}
60

            
61
/// One rejected field of a `form-invalid` reply.
62
#[derive(Debug, Clone, PartialEq, Eq)]
63
pub 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)]
71
pub struct ErrorReply {
72
    pub code: String,
73
    pub message: String,
74
    pub detail: Option<Value>,
75
}
76

            
77
impl 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
626
    pub fn field_errors(&self) -> Vec<FieldError> {
82
626
        let Some(detail) = self
83
626
            .detail
84
626
            .as_ref()
85
509
            .filter(|_| self.code == ErrorCode::FORM_INVALID)
86
        else {
87
134
            return Vec::new();
88
        };
89
492
        list_to_vec(detail)
90
492
            .unwrap_or_default()
91
492
            .iter()
92
543
            .filter_map(|item| {
93
                Some(FieldError {
94
543
                    field: crate::eval::plist_field(item, ":field")?,
95
539
                    message: crate::eval::plist_field(item, ":message")?,
96
                })
97
543
            })
98
            .collect()
99
626
    }
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.
104
const 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.
108
12917
fn max_nesting_depth(s: &str) -> usize {
109
12917
    let (mut depth, mut max) = (0usize, 0usize);
110
12917
    let (mut in_string, mut escaped) = (false, false);
111
12917
    for ch in s.chars() {
112
5350170
        if in_string {
113
4471042
            match (escaped, ch) {
114
4
                (true, _) => escaped = false,
115
4
                (false, '\\') => escaped = true,
116
39656
                (false, '"') => in_string = false,
117
4431378
                _ => {}
118
            }
119
4471042
            continue;
120
879128
        }
121
879128
        match ch {
122
39656
            '"' => in_string = true,
123
            '(' => {
124
39513
                depth += 1;
125
39513
                max = max.max(depth);
126
            }
127
39510
            ')' => depth = depth.saturating_sub(1),
128
760449
            _ => {}
129
        }
130
    }
131
12917
    max
132
12917
}
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.
140
12917
pub 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
12917
    if max_nesting_depth(s) > MAX_REPARSE_DEPTH {
146
1
        return Err(RenderError::ListReparse(format!(
147
1
            "printed list nested beyond {MAX_REPARSE_DEPTH}"
148
1
        )));
149
12916
    }
150
12916
    let program = Reader::parse(s).map_err(|e| RenderError::ListReparse(e.to_string()))?;
151
12915
    let mut iter = program.exprs.into_iter();
152
12915
    let Some(expr) = iter.next() else {
153
        return Ok(Value::Nil);
154
    };
155
12915
    if iter.next().is_some() {
156
        return Err(RenderError::ListReparse(
157
            "printed list string contains multiple top-level expressions".into(),
158
        ));
159
12915
    }
160
12915
    try_expr_to_value(expr).map_err(|e| RenderError::ListReparse(e.to_string()))
161
12917
}
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
169
104
pub fn value_to_rows(value: &Value) -> Vec<Vec<String>> {
170
104
    match value {
171
13
        Value::Nil => vec![],
172
        Value::Pair(_) => {
173
88
            if let Some(row) = try_plist_values(value) {
174
24
                vec![row]
175
64
            } else if let Some(elements) = list_to_vec(value) {
176
64
                elements.iter().map(element_to_row).collect()
177
            } else {
178
                vec![vec![format_value_display(value)]]
179
            }
180
        }
181
3
        other => vec![vec![format_value_display(other)]],
182
    }
183
104
}
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.
191
6
pub fn rows_with_ids(value: &Value) -> Vec<ListRow> {
192
6
    match value {
193
        Value::Nil => vec![],
194
        Value::Pair(_) => {
195
5
            if let Some(cells) = try_plist_values(value) {
196
                vec![ListRow {
197
                    id: row_id(value),
198
                    cells,
199
                }]
200
5
            } else if let Some(elements) = list_to_vec(value) {
201
5
                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
1
        other => vec![ListRow {
210
1
            id: None,
211
1
            cells: vec![format_value_display(other)],
212
1
        }],
213
    }
214
6
}
215

            
216
7
fn element_to_list_row(element: &Value) -> ListRow {
217
7
    match element {
218
        Value::Pair(_) => {
219
            let cells =
220
7
                try_plist_values(element).unwrap_or_else(|| vec![format_value_display(element)]);
221
7
            ListRow {
222
7
                id: row_id(element),
223
7
                cells,
224
7
            }
225
        }
226
        other => ListRow {
227
            id: None,
228
            cells: vec![format_value_display(other)],
229
        },
230
    }
231
7
}
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.
238
147466
fn row_id(value: &Value) -> Option<String> {
239
147466
    crate::eval::plist_field(value, ":id")
240
147466
}
241

            
242
115
fn element_to_row(element: &Value) -> Vec<String> {
243
115
    match element {
244
        Value::Pair(_) => {
245
88
            if let Some(cells) = try_plist_values(element) {
246
61
                return cells;
247
27
            }
248
27
            vec![format_value_display(element)]
249
        }
250
27
        other => vec![format_value_display(other)],
251
    }
252
115
}
253

            
254
270
fn is_plist_key(v: &Value) -> bool {
255
270
    matches!(v, Value::Symbol(s) if s.starts_with(':'))
256
270
}
257

            
258
188
fn try_plist_values(value: &Value) -> Option<Vec<String>> {
259
188
    let items = list_to_vec(value)?;
260
188
    if items.len() < 2 || !items.len().is_multiple_of(2) {
261
51
        return None;
262
137
    }
263
137
    if !items.iter().step_by(2).all(is_plist_key) {
264
52
        return None;
265
85
    }
266
    Some(
267
85
        items
268
85
            .into_iter()
269
85
            .skip(1)
270
85
            .step_by(2)
271
218
            .map(|v| format_value_display(&v))
272
            .collect(),
273
    )
274
188
}
275

            
276
#[cfg(test)]
277
mod tests;