1use ratatui::{
2 buffer::{Buffer, CellDiffOption},
3 layout::Rect,
4 style::{Color, Modifier},
5 widgets::Widget,
6};
7use std::sync::OnceLock;
8use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
9
10static BIN_NAME: OnceLock<&'static str> = OnceLock::new();
22
23pub fn set_bin_name(name: &'static str) {
27 let _ = BIN_NAME.set(name);
28}
29
30pub fn bin_name() -> &'static str {
34 BIN_NAME.get().copied().unwrap_or("vta")
35}
36
37static FULL_DISPLAY: AtomicBool = AtomicBool::new(false);
46
47pub fn set_full_display(enabled: bool) {
50 FULL_DISPLAY.store(enabled, Ordering::Relaxed);
51}
52
53pub fn is_full_display() -> bool {
56 FULL_DISPLAY.load(Ordering::Relaxed)
57}
58
59pub fn print_full_entry(pairs: &[(&str, &str)]) {
66 let widest = pairs.iter().map(|(l, _)| l.len()).max().unwrap_or(0);
67 for (label, value) in pairs {
68 let pad = " ".repeat(widest.saturating_sub(label.len()));
69 println!(" {label}:{pad} {DIM}{value}{RESET}");
70 }
71 println!();
72}
73
74pub fn print_full_entry_owned(pairs: &[(&str, String)]) {
79 let borrowed: Vec<(&str, &str)> = pairs.iter().map(|(l, v)| (*l, v.as_str())).collect();
80 print_full_entry(&borrowed);
81}
82
83pub fn print_full_list_title(title: &str, count: usize) {
86 println!();
87 println!("{BOLD}{title} ({count}){RESET}");
88 println!();
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum OutputFormat {
102 Human,
103 Json,
104}
105
106static OUTPUT_FORMAT: AtomicU8 = AtomicU8::new(0); pub fn set_output_format(format: OutputFormat) {
111 OUTPUT_FORMAT.store(
112 match format {
113 OutputFormat::Human => 0,
114 OutputFormat::Json => 1,
115 },
116 Ordering::Relaxed,
117 );
118}
119
120pub fn output_format() -> OutputFormat {
122 if OUTPUT_FORMAT.load(Ordering::Relaxed) == 1 {
123 OutputFormat::Json
124 } else {
125 OutputFormat::Human
126 }
127}
128
129#[must_use]
133pub fn is_json_output() -> bool {
134 output_format() == OutputFormat::Json
135}
136
137pub fn print_json<T: serde::Serialize>(value: &T) -> Result<(), serde_json::Error> {
142 let text = serde_json::to_string_pretty(value)?;
143 println!("{text}");
144 Ok(())
145}
146
147pub const BOLD: &str = "\x1b[1m";
150pub const DIM: &str = "\x1b[2m";
151pub const GREEN: &str = "\x1b[32m";
152pub const RED: &str = "\x1b[31m";
153pub const CYAN: &str = "\x1b[36m";
154pub const YELLOW: &str = "\x1b[33m";
155pub const RESET: &str = "\x1b[0m";
156
157pub fn print_cli_error(err: &(dyn std::error::Error + 'static)) {
171 use vta_sdk::error::VtaError;
172 if let Some(vta_err) = err.downcast_ref::<VtaError>() {
173 match vta_err {
174 VtaError::Auth(msg) => {
175 eprintln!("{RED}\u{2717}{RESET} Authentication failed: {msg}");
176 eprintln!(
177 " {DIM}Token may be expired. Try `pnm setup` to re-authenticate, or check \
178 that the VTA's `/auth` endpoint is reachable.{RESET}"
179 );
180 }
181 VtaError::Forbidden(msg) => {
182 eprintln!("{RED}\u{2717}{RESET} Forbidden: {msg}");
183 eprintln!(
184 " {DIM}Your role or context access doesn't permit this operation. \
185 Inspect with `pnm acl get <your-did>`.{RESET}"
186 );
187 }
188 VtaError::NotFound(msg) => {
189 eprintln!("{RED}\u{2717}{RESET} Not found: {msg}");
190 }
191 VtaError::Conflict(msg) => {
192 eprintln!(
198 "{RED}\u{2717}{RESET} Conflict: {}",
199 extract_human_message(msg)
200 );
201 }
202 VtaError::Gone(msg) => {
203 let bin = bin_name();
204 eprintln!("{RED}\u{2717}{RESET} Resource is gone: {msg}");
205 eprintln!(
206 " {DIM}This usually means the bootstrap carve-out has already been used. \
207 For a second admin, run `{bin} bootstrap provision-request` from the new \
208 operator's host and have an existing admin run \
209 `{bin} bootstrap provision-integration` against this VTA.{RESET}"
210 );
211 }
212 VtaError::Validation(msg) => {
213 eprintln!("{RED}\u{2717}{RESET} Invalid request: {msg}");
214 }
215 VtaError::Network(e) => {
216 eprintln!("{RED}\u{2717}{RESET} Network error: {e}");
217 eprintln!(" {DIM}Is the VTA reachable? Check its URL with `pnm vta info`.{RESET}");
218 }
219 VtaError::Server { status, body } => {
220 eprintln!("{RED}\u{2717}{RESET} Server error (HTTP {status}): {body}");
221 eprintln!(
222 " {DIM}This is a VTA-side failure. Check server logs or contact the operator.{RESET}"
223 );
224 }
225 VtaError::UnsupportedTransport(msg) => {
226 eprintln!("{RED}\u{2717}{RESET} Unsupported transport: {msg}");
227 eprintln!(
228 " {DIM}This operation requires a specific transport (REST or DIDComm). \
229 Check which mode your CLI is in and whether the endpoint supports it.{RESET}"
230 );
231 }
232 VtaError::DidcommTransport(msg) => {
233 eprintln!("{RED}\u{2717}{RESET} DIDComm transport error: {msg}");
234 eprintln!(
235 " {DIM}Mediator or peer unreachable. Retry after checking mediator \
236 connectivity.{RESET}"
237 );
238 }
239 VtaError::DidcommRemote { code, comment } => {
240 eprintln!("{RED}\u{2717}{RESET} Remote error ({code}): {comment}");
241 }
242 VtaError::Protocol(msg) => {
243 eprintln!("{RED}\u{2717}{RESET} Protocol error: {msg}");
244 }
245 VtaError::LastServiceRefused => {
247 let bin = bin_name();
248 eprintln!(
249 "{RED}\u{2717}{RESET} Refused: would leave the VTA with no advertised services."
250 );
251 eprintln!(
252 " {DIM}At least one transport (REST or DIDComm) must remain advertised. \
253 Enable the other transport first via `{bin} services <kind> enable …`, \
254 then retry.{RESET}"
255 );
256 }
257 VtaError::ServiceNotPresent => {
258 let bin = bin_name();
259 eprintln!("{RED}\u{2717}{RESET} Service is not present.");
260 eprintln!(
261 " {DIM}The service kind isn't currently enabled. Use `{bin} services \
262 <kind> enable …` to bring it online before updating, disabling, or rolling \
263 it back.{RESET}"
264 );
265 }
266 VtaError::ServiceAlreadyEnabled => {
267 let bin = bin_name();
268 eprintln!("{RED}\u{2717}{RESET} Service is already enabled.");
269 eprintln!(
270 " {DIM}Use `{bin} services <kind> update …` to change its configuration, \
271 or `{bin} services <kind> disable` to remove it.{RESET}"
272 );
273 }
274 VtaError::MediatorHandshakeFailed { reason } => {
275 eprintln!("{RED}\u{2717}{RESET} Mediator handshake failed: {reason}");
276 eprintln!(
277 " {DIM}Confirm the mediator DID is correct and the mediator is reachable. \
278 The reason above is the specific cause from the handshake protocol.{RESET}"
279 );
280 }
281 VtaError::DrainTtlOutOfBounds {
282 min,
283 max,
284 requested,
285 } => {
286 eprintln!(
287 "{RED}\u{2717}{RESET} Drain TTL {requested}s is outside the allowed range \
288 [{min}s, {max}s]."
289 );
290 eprintln!(
291 " {DIM}Pick a value within those bounds. The minimum applies when the \
292 command is delivered over DIDComm transport (so the listener stays up long \
293 enough for the response).{RESET}"
294 );
295 }
296 VtaError::NoPriorMutation => {
297 let bin = bin_name();
298 eprintln!("{RED}\u{2717}{RESET} No prior mutation to roll back.");
299 eprintln!(
300 " {DIM}Use `{bin} services <kind> {{enable,update,disable}} …` directly \
301 instead of rollback.{RESET}"
302 );
303 }
304 other => eprintln!("{RED}\u{2717}{RESET} Error: {other}"),
305 }
306 return;
307 }
308 eprintln!("{RED}\u{2717}{RESET} Error: {err}");
309 let mut source = err.source();
310 while let Some(s) = source {
311 eprintln!(" {DIM}caused by: {s}{RESET}");
312 source = s.source();
313 }
314}
315
316fn extract_human_message(body: &str) -> String {
324 serde_json::from_str::<serde_json::Value>(body)
325 .ok()
326 .and_then(|v| {
327 v.get("message")
328 .or_else(|| v.get("error"))
329 .and_then(|m| m.as_str())
330 .map(str::to_string)
331 })
332 .unwrap_or_else(|| body.to_string())
333}
334
335pub fn print_widget(widget: impl Widget, height: u16) {
338 let width = ratatui::crossterm::terminal::size().map_or(120, |(w, _)| w);
339 let area = Rect::new(0, 0, width, height);
340 let mut buf = Buffer::empty(area);
341 widget.render(area, &mut buf);
342
343 let mut out = String::new();
344 for y in 0..height {
345 let mut cur_fg = Color::Reset;
346 let mut cur_bg = Color::Reset;
347 let mut cur_mod = Modifier::empty();
348
349 for x in 0..width {
350 let cell = &buf[(x, y)];
351 if cell.diff_option == CellDiffOption::Skip {
352 continue;
353 }
354
355 if cell.fg != cur_fg || cell.bg != cur_bg || cell.modifier != cur_mod {
356 out.push_str("\x1b[0m");
357 push_ansi_fg(&mut out, cell.fg);
358 push_ansi_bg(&mut out, cell.bg);
359 push_ansi_mod(&mut out, cell.modifier);
360 cur_fg = cell.fg;
361 cur_bg = cell.bg;
362 cur_mod = cell.modifier;
363 }
364
365 out.push_str(cell.symbol());
366 }
367 out.push_str("\x1b[0m\n");
368 }
369
370 print!("{out}");
371}
372
373pub fn push_ansi_fg(out: &mut String, color: Color) {
374 use std::fmt::Write as _;
375 match color {
376 Color::Reset => {}
377 Color::Black => out.push_str("\x1b[30m"),
378 Color::Red => out.push_str("\x1b[31m"),
379 Color::Green => out.push_str("\x1b[32m"),
380 Color::Yellow => out.push_str("\x1b[33m"),
381 Color::Blue => out.push_str("\x1b[34m"),
382 Color::Magenta => out.push_str("\x1b[35m"),
383 Color::Cyan => out.push_str("\x1b[36m"),
384 Color::Gray => out.push_str("\x1b[37m"),
385 Color::DarkGray => out.push_str("\x1b[90m"),
386 Color::LightRed => out.push_str("\x1b[91m"),
387 Color::LightGreen => out.push_str("\x1b[92m"),
388 Color::LightYellow => out.push_str("\x1b[93m"),
389 Color::LightBlue => out.push_str("\x1b[94m"),
390 Color::LightMagenta => out.push_str("\x1b[95m"),
391 Color::LightCyan => out.push_str("\x1b[96m"),
392 Color::White => out.push_str("\x1b[97m"),
393 Color::Rgb(r, g, b) => {
394 let _ = write!(out, "\x1b[38;2;{r};{g};{b}m");
395 }
396 Color::Indexed(i) => {
397 let _ = write!(out, "\x1b[38;5;{i}m");
398 }
399 }
400}
401
402pub fn push_ansi_bg(out: &mut String, color: Color) {
403 use std::fmt::Write as _;
404 match color {
405 Color::Reset => {}
406 Color::Black => out.push_str("\x1b[40m"),
407 Color::Red => out.push_str("\x1b[41m"),
408 Color::Green => out.push_str("\x1b[42m"),
409 Color::Yellow => out.push_str("\x1b[43m"),
410 Color::Blue => out.push_str("\x1b[44m"),
411 Color::Magenta => out.push_str("\x1b[45m"),
412 Color::Cyan => out.push_str("\x1b[46m"),
413 Color::Gray => out.push_str("\x1b[47m"),
414 Color::DarkGray => out.push_str("\x1b[100m"),
415 Color::LightRed => out.push_str("\x1b[101m"),
416 Color::LightGreen => out.push_str("\x1b[102m"),
417 Color::LightYellow => out.push_str("\x1b[103m"),
418 Color::LightBlue => out.push_str("\x1b[104m"),
419 Color::LightMagenta => out.push_str("\x1b[105m"),
420 Color::LightCyan => out.push_str("\x1b[106m"),
421 Color::White => out.push_str("\x1b[107m"),
422 Color::Rgb(r, g, b) => {
423 let _ = write!(out, "\x1b[48;2;{r};{g};{b}m");
424 }
425 Color::Indexed(i) => {
426 let _ = write!(out, "\x1b[48;5;{i}m");
427 }
428 }
429}
430
431pub fn push_ansi_mod(out: &mut String, modifier: Modifier) {
432 if modifier.contains(Modifier::BOLD) {
433 out.push_str("\x1b[1m");
434 }
435 if modifier.contains(Modifier::DIM) {
436 out.push_str("\x1b[2m");
437 }
438 if modifier.contains(Modifier::ITALIC) {
439 out.push_str("\x1b[3m");
440 }
441 if modifier.contains(Modifier::UNDERLINED) {
442 out.push_str("\x1b[4m");
443 }
444 if modifier.contains(Modifier::REVERSED) {
445 out.push_str("\x1b[7m");
446 }
447 if modifier.contains(Modifier::CROSSED_OUT) {
448 out.push_str("\x1b[9m");
449 }
450}
451
452pub fn print_section(title: &str) {
453 let pad = 46usize.saturating_sub(title.len());
454 println!(
455 "\n{DIM}──{RESET} {BOLD}{title}{RESET} {DIM}{}{RESET}",
456 "─".repeat(pad)
457 );
458}
459
460#[cfg(test)]
461mod tests {
462 use super::extract_human_message;
463
464 #[test]
465 fn prefers_message_field() {
466 let body = r#"{"error":"didcomm_already_enabled","message":"DIDComm is already enabled.","mediator_did":"did:peer:2.med"}"#;
467 assert_eq!(extract_human_message(body), "DIDComm is already enabled.");
468 }
469
470 #[test]
471 fn falls_back_to_error_field_when_no_message() {
472 let body = r#"{"error":"duplicate_key"}"#;
473 assert_eq!(extract_human_message(body), "duplicate_key");
474 }
475
476 #[test]
477 fn falls_back_to_raw_text_for_non_json() {
478 let body = "plain conflict text";
479 assert_eq!(extract_human_message(body), "plain conflict text");
480 }
481
482 #[test]
483 fn falls_back_to_raw_text_when_fields_missing() {
484 let body = r#"{"detail":"something"}"#;
486 assert_eq!(extract_human_message(body), body);
487 }
488}