Lines
86.15 %
Functions
82.35 %
Branches
100 %
//! Shared wire-parse + render surface for CLI and TUI consumers.
pub mod account_order;
pub mod schema;
use nomiscript::{Reader, Value, format_value_display, list_to_vec};
use thiserror::Error;
use rpc::{EnvelopeError, ErrorCode, ResponsePayload, parse_response, try_expr_to_value};
#[derive(Debug, Clone, PartialEq)]
pub enum WireValue {
Value(Value),
}
/// A structured row from a list reply, carrying an optional entity id alongside display cells.
///
/// The `cells` are identical to what [`value_to_rows`] produces — display is unchanged.
/// The `id` is the `:id` plist field extracted separately for navigation (e.g. open/edit).
pub struct ListRow {
/// Entity id from the `:id` plist field, or `None` when absent.
pub id: Option<String>,
/// Display cells, byte-identical to the `value_to_rows` output for this element.
pub cells: Vec<String>,
#[derive(Debug, Error)]
pub enum RenderError {
#[error("envelope parse failed: {0}")]
Envelope(#[from] EnvelopeError),
#[error("wire error from server: [{}] {}", .0.code, .0.message)]
Server(ErrorReply),
#[error("re-parse of printed list failed: {0}")]
ListReparse(String),
/// Parse a wire reply into a [`WireValue`].
/// The `:value` payload is returned as-is: a `pair:*` or `entity:*` result
/// arrives as a structured list, a string stays `Value::String(s)`. Callers
/// of a string native that prints a list must call [`reparse_list`] on it.
/// Returns `Err(RenderError::Server)` when the frame contains `:error`.
pub fn parse_wire(wire: &str) -> Result<WireValue, RenderError> {
let response = parse_response(wire)?;
match response.payload {
ResponsePayload::Error {
code,
message,
detail,
} => Err(RenderError::Server(ErrorReply {
code: code.as_symbol().to_string(),
})),
ResponsePayload::Value(v) => Ok(WireValue::Value(v)),
/// One rejected field of a `form-invalid` reply.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldError {
/// Field address: `key`, `rows.i` or `rows.i.key`.
pub field: String,
pub message: String,
/// The `:error` of a wire reply, the one parsed form every client reads.
pub struct ErrorReply {
pub code: String,
pub detail: Option<Value>,
impl ErrorReply {
/// The rejected fields of a `form-invalid` reply; empty for any other
/// reply and for entries lacking a field or a message.
#[must_use]
pub fn field_errors(&self) -> Vec<FieldError> {
let Some(detail) = self
.detail
.as_ref()
.filter(|_| self.code == ErrorCode::FORM_INVALID)
else {
return Vec::new();
};
list_to_vec(detail)
.unwrap_or_default()
.iter()
.filter_map(|item| {
Some(FieldError {
field: crate::eval::plist_field(item, ":field")?,
message: crate::eval::plist_field(item, ":message")?,
})
.collect()
/// Paren-nesting depth above which [`reparse_list`] refuses to parse, to keep
/// the reader's per-paren recursion within the native stack.
const MAX_REPARSE_DEPTH: usize = 64;
/// Largest paren-nesting depth in `s`, ignoring parens inside string literals
/// (so a `"USD)"` cell does not inflate the count). Cheap single pass.
fn max_nesting_depth(s: &str) -> usize {
let (mut depth, mut max) = (0usize, 0usize);
let (mut in_string, mut escaped) = (false, false);
for ch in s.chars() {
if in_string {
match (escaped, ch) {
(true, _) => escaped = false,
(false, '\\') => escaped = true,
(false, '"') => in_string = false,
_ => {}
continue;
match ch {
'"' => in_string = true,
'(' => {
depth += 1;
max = max.max(depth);
')' => depth = depth.saturating_sub(1),
max
/// Re-parse a printed-list string (as returned by `string` natives that print
/// a plist, e.g. `form-options` or `get-transaction-detail`) into a
/// structured [`Value`].
/// Scalar string values (UUIDs, names) must NOT be passed here, as they may
/// accidentally parse as atoms or produce incorrect values.
pub fn reparse_list(s: &str) -> Result<Value, RenderError> {
// Bound nesting BEFORE handing the string to the reader: `Reader::parse`
// itself recurses per paren and overflows the native stack on deeply
// nested input. Real entity/balance plists are shallow (depth 1-2), so a
// generous cap rejects malformed/hostile wire data without parsing it.
if max_nesting_depth(s) > MAX_REPARSE_DEPTH {
return Err(RenderError::ListReparse(format!(
"printed list nested beyond {MAX_REPARSE_DEPTH}"
)));
let program = Reader::parse(s).map_err(|e| RenderError::ListReparse(e.to_string()))?;
let mut iter = program.exprs.into_iter();
let Some(expr) = iter.next() else {
return Ok(Value::Nil);
if iter.next().is_some() {
return Err(RenderError::ListReparse(
"printed list string contains multiple top-level expressions".into(),
));
try_expr_to_value(expr).map_err(|e| RenderError::ListReparse(e.to_string()))
/// Walk a [`Value`] into columnar rows for display.
/// - `Nil` → no rows
/// - A top-level plist (`(:k v :k v …)`) → ONE row of its field values
/// - Other proper list → one row per element; plist elements yield field cells
/// - Scalar → single 1-cell row
pub fn value_to_rows(value: &Value) -> Vec<Vec<String>> {
match value {
Value::Nil => vec![],
Value::Pair(_) => {
if let Some(row) = try_plist_values(value) {
vec![row]
} else if let Some(elements) = list_to_vec(value) {
elements.iter().map(element_to_row).collect()
} else {
vec![vec![format_value_display(value)]]
other => vec![vec![format_value_display(other)]],
/// Walk a [`Value`] into [`ListRow`]s, pairing display cells with the `:id` plist field.
/// The `cells` of every row are byte-identical to what [`value_to_rows`] produces;
/// the `id` is extracted separately by `row_id`. Real list rows are typed records
/// with a leading tag (`(:account :id … :name …)`), so the id is found by position,
/// not by assuming `:id` sits at an even key slot.
pub fn rows_with_ids(value: &Value) -> Vec<ListRow> {
if let Some(cells) = try_plist_values(value) {
vec![ListRow {
id: row_id(value),
cells,
}]
elements.iter().map(element_to_list_row).collect()
id: None,
cells: vec![format_value_display(value)],
other => vec![ListRow {
cells: vec![format_value_display(other)],
}],
fn element_to_list_row(element: &Value) -> ListRow {
match element {
let cells =
try_plist_values(element).unwrap_or_else(|| vec![format_value_display(element)]);
ListRow {
id: row_id(element),
other => ListRow {
},
/// Extract a row's `:id`, reusing the single-source plist scan.
/// [`crate::eval::plist_field`] finds `:id` by position over the top-level items,
/// so a leading type tag (`:account`) does not displace it and a nested split's
/// `:id` is never reached.
fn row_id(value: &Value) -> Option<String> {
crate::eval::plist_field(value, ":id")
fn element_to_row(element: &Value) -> Vec<String> {
if let Some(cells) = try_plist_values(element) {
return cells;
vec![format_value_display(element)]
other => vec![format_value_display(other)],
fn is_plist_key(v: &Value) -> bool {
matches!(v, Value::Symbol(s) if s.starts_with(':'))
fn try_plist_values(value: &Value) -> Option<Vec<String>> {
let items = list_to_vec(value)?;
if items.len() < 2 || !items.len().is_multiple_of(2) {
return None;
if !items.iter().step_by(2).all(is_plist_key) {
Some(
items
.into_iter()
.skip(1)
.step_by(2)
.map(|v| format_value_display(&v))
.collect(),
)
#[cfg(test)]
mod tests;