wyvern-schema 0.4.0

Wyvern JSON types, validation, and error messages
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Typed command surface for the current phase.

use crate::chrome::{ChromeStatus, ChromeTitle};
use crate::report::ReportCommand;
use crate::wizard::WizardCommand;

/// Standard button preset for dialog types (REQ Phase B).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ButtonsPreset {
    /// Single OK button.
    Ok,
    /// OK + Cancel.
    OkCancel,
    /// Yes + No.
    YesNo,
    /// Yes + No + Cancel.
    YesNoCancel,
    /// Retry + Cancel.
    RetryCancel,
    /// Caller-supplied labels via `custom_buttons`.
    Custom,
}

impl ButtonsPreset {
    /// Parse a wire preset name (`ok`, `ok_cancel`, …).
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "ok" => Some(Self::Ok),
            "ok_cancel" => Some(Self::OkCancel),
            "yes_no" => Some(Self::YesNo),
            "yes_no_cancel" => Some(Self::YesNoCancel),
            "retry_cancel" => Some(Self::RetryCancel),
            "custom" => Some(Self::Custom),
            _ => None,
        }
    }

    /// All valid wire names (for error messages / suggestions).
    pub fn all_names() -> &'static [&'static str] {
        &[
            "ok",
            "ok_cancel",
            "yes_no",
            "yes_no_cancel",
            "retry_cancel",
            "custom",
        ]
    }

    /// Display labels shown in the HTML button bar (ipc-dialog-contract).
    pub fn display_labels(self, custom_buttons: Option<&[String]>) -> Vec<String> {
        match self {
            Self::Ok => vec!["OK".into()],
            Self::OkCancel => vec!["OK".into(), "Cancel".into()],
            Self::YesNo => vec!["Yes".into(), "No".into()],
            Self::YesNoCancel => vec!["Yes".into(), "No".into(), "Cancel".into()],
            Self::RetryCancel => vec!["Retry".into(), "Cancel".into()],
            Self::Custom => custom_buttons.unwrap_or(&[]).to_vec(),
        }
    }

    /// Stdout / IPC wire labels corresponding 1:1 with [`Self::display_labels`].
    pub fn wire_labels(self, custom_buttons: Option<&[String]>) -> Vec<String> {
        match self {
            Self::Ok => vec!["ok".into()],
            Self::OkCancel => vec!["ok".into(), "cancel".into()],
            Self::YesNo => vec!["yes".into(), "no".into()],
            Self::YesNoCancel => vec!["yes".into(), "no".into(), "cancel".into()],
            Self::RetryCancel => vec!["retry".into(), "cancel".into()],
            Self::Custom => custom_buttons.unwrap_or(&[]).to_vec(),
        }
    }

    /// Number of buttons for the active preset (or custom list).
    pub fn button_count(self, custom_buttons: Option<&[String]>) -> usize {
        self.wire_labels(custom_buttons).len()
    }
}

/// Semantic severity for a message dialog (REQ-0012).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageLevel {
    /// Informational notice.
    Info,
    /// Caution / non-fatal problem.
    Warning,
    /// Error condition.
    Error,
    /// Prompt requiring a decision.
    Question,
}

impl MessageLevel {
    /// Parse a wire level name (`info`, `warning`, …).
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "info" => Some(Self::Info),
            "warning" => Some(Self::Warning),
            "error" => Some(Self::Error),
            "question" => Some(Self::Question),
            _ => None,
        }
    }

    /// All valid wire names (for error messages / suggestions).
    pub fn all_names() -> &'static [&'static str] {
        &["info", "warning", "error", "question"]
    }

    /// Wire / asset name for this level.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Info => "info",
            Self::Warning => "warning",
            Self::Error => "error",
            Self::Question => "question",
        }
    }
}

/// Input dialog mode (REQ-0014).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputMode {
    /// Free-text field (default when `mode` is omitted).
    Text,
    /// Native file picker via `rfd` on the HTTP host (`POST /api/picker/file`).
    File,
    /// Native folder picker via `rfd` on the HTTP host (`POST /api/picker/folder`).
    Folder,
}

impl InputMode {
    /// Parse a wire mode name (`text`, `file`, `folder`).
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "text" => Some(Self::Text),
            "file" => Some(Self::File),
            "folder" => Some(Self::Folder),
            _ => None,
        }
    }

    /// All valid wire names (for error messages / suggestions).
    pub fn all_names() -> &'static [&'static str] {
        &["text", "file", "folder"]
    }

    /// Wire name for this mode.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Text => "text",
            Self::File => "file",
            Self::Folder => "folder",
        }
    }
}

/// Optional viewer window size in CSS pixels (embedded shell or browser window hint).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct WindowSizeHint {
    /// Width in CSS pixels.
    pub width: Option<u32>,
    /// Height in CSS pixels.
    pub height: Option<u32>,
}

impl WindowSizeHint {
    /// True when either dimension is set.
    pub fn is_some(&self) -> bool {
        self.width.is_some() || self.height.is_some()
    }
}

/// Executable command after successful validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Command {
    /// Foundation chrome frame: required `title`, optional `status`.
    Chrome {
        title: ChromeTitle,
        status: Option<ChromeStatus>,
        width: Option<u32>,
        height: Option<u32>,
    },
    /// Modal message dialog (Phase B sprint b.1 / b.2).
    Message {
        title: ChromeTitle,
        message: String,
        status: Option<ChromeStatus>,
        buttons: ButtonsPreset,
        custom_buttons: Option<Vec<String>>,
        default_button: Option<u32>,
        level: Option<MessageLevel>,
        icon: Option<crate::MediaRef>,
        image: Option<crate::MediaRef>,
        markdown: bool,
        width: Option<u32>,
        height: Option<u32>,
    },
    /// Modal input dialog — text / file / folder (REQ-0013 / REQ-0015).
    Input {
        title: ChromeTitle,
        message: String,
        status: Option<ChromeStatus>,
        icon: Option<crate::MediaRef>,
        markdown: bool,
        multiline: bool,
        placeholder: Option<String>,
        default: Option<String>,
        /// Mask the text field (`type=password`); text mode only (c.11).
        password: bool,
        mode: InputMode,
        /// Extension patterns (`*.json`, …); file mode only (REQ-0015 / REQ-0059).
        filter: Option<Vec<String>>,
        /// Multi-file selection; file mode only (REQ-0015 / REQ-0059).
        multiple: bool,
        /// Initial picker directory; file or folder mode only (REQ-0059).
        start_path: Option<String>,
        buttons: ButtonsPreset,
        width: Option<u32>,
        height: Option<u32>,
    },
    /// Markdown viewer — exactly one of `file` or `content` (REQ-0016 / REQ-0058).
    Markdown {
        /// Window title; omitted → filename (file) or `"Markdown"` (inline).
        title: Option<ChromeTitle>,
        /// Path to a `.md` file (mutually exclusive with `content`).
        file: Option<String>,
        /// Inline markdown source (mutually exclusive with `file`).
        content: Option<String>,
        status: Option<ChromeStatus>,
        /// Defaults to [`ButtonsPreset::Ok`] when omitted.
        buttons: ButtonsPreset,
        width: Option<u32>,
        height: Option<u32>,
    },
    /// Question cards dialog (REQ-0061 / REQ-0062).
    Question {
        /// Typed cards used for rendering and host-side answer checks.
        questions: Vec<QuestionCard>,
        /// Verbatim `questions` array entries for stdout echo (REQ-0067).
        questions_raw: Vec<serde_json::Value>,
        width: Option<u32>,
        height: Option<u32>,
    },
    /// Multi-page wizard (Phase D / REQ-0017 / REQ-0026).
    Wizard(WizardCommand),
    /// Static XHTML/HTML report (Phase H / REQ-0140 / ADR-0025).
    Report(ReportCommand),
}

impl Command {
    /// Optional viewer window width from command JSON (`width`).
    pub fn window_width(&self) -> Option<u32> {
        match self {
            Self::Chrome { width, .. }
            | Self::Message { width, .. }
            | Self::Input { width, .. }
            | Self::Markdown { width, .. }
            | Self::Question { width, .. } => *width,
            Self::Wizard(cmd) => cmd.width,
            Self::Report(cmd) => cmd.width,
        }
    }

    /// Optional viewer window height from command JSON (`height`).
    pub fn window_height(&self) -> Option<u32> {
        match self {
            Self::Chrome { height, .. }
            | Self::Message { height, .. }
            | Self::Input { height, .. }
            | Self::Markdown { height, .. }
            | Self::Question { height, .. } => *height,
            Self::Wizard(cmd) => cmd.height,
            Self::Report(cmd) => cmd.height,
        }
    }

    /// Combined optional window size hint.
    pub fn window_size_hint(&self) -> WindowSizeHint {
        WindowSizeHint {
            width: self.window_width(),
            height: self.window_height(),
        }
    }
}

/// One selectable option inside a [`QuestionCard`] (AskUserQuestion wire names).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QuestionOption {
    /// Display / answer label.
    pub label: String,
    /// Secondary text under the label.
    pub description: String,
    /// Optional HTML/markdown preview fragment (rendered sanitized in b.8).
    pub preview: Option<String>,
}

/// Why [`QuestionPrompt::try_new`] rejected a value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuestionPromptError {
    /// Prompt was empty.
    Empty,
}

impl std::fmt::Display for QuestionPromptError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Empty => f.write_str("question prompt must be a non-empty string"),
        }
    }
}

impl std::error::Error for QuestionPromptError {}

/// Validated question-card prompt (non-empty; also the stdout `answers` key).
///
/// Construct via [`Self::try_new`] at the [`crate::validate`] boundary so
/// [`QuestionCard::question`] cannot carry an unchecked `String`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct QuestionPrompt(String);

impl QuestionPrompt {
    /// Wrap an already-validated prompt.
    ///
    /// Prefer [`Self::try_new`] at trust boundaries.
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// Construct a non-empty prompt.
    ///
    /// # Errors
    ///
    /// Returns [`QuestionPromptError::Empty`] when `value` is empty.
    pub fn try_new(value: impl Into<String>) -> Result<Self, QuestionPromptError> {
        let value = value.into();
        if value.is_empty() {
            return Err(QuestionPromptError::Empty);
        }
        Ok(Self(value))
    }

    /// Borrow as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume and return the inner string.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl std::ops::Deref for QuestionPrompt {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl AsRef<str> for QuestionPrompt {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl std::fmt::Display for QuestionPrompt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl From<String> for QuestionPrompt {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl From<&str> for QuestionPrompt {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

impl PartialEq<str> for QuestionPrompt {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

impl PartialEq<&str> for QuestionPrompt {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

/// One question card in a `type: "question"` command (REQ-0062).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QuestionCard {
    /// Prompt text; also the key in the stdout `answers` map.
    pub question: QuestionPrompt,
    /// Short card header (max 12 characters).
    pub header: String,
    /// Selectable options (2–4 entries).
    pub options: Vec<QuestionOption>,
    /// When true, checkboxes and comma-joined labels; otherwise radio.
    pub multi_select: bool,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn preset_label_mapping_table() {
        assert_eq!(ButtonsPreset::Ok.display_labels(None), ["OK"]);
        assert_eq!(ButtonsPreset::Ok.wire_labels(None), ["ok"]);

        assert_eq!(
            ButtonsPreset::OkCancel.display_labels(None),
            ["OK", "Cancel"]
        );
        assert_eq!(ButtonsPreset::OkCancel.wire_labels(None), ["ok", "cancel"]);

        assert_eq!(ButtonsPreset::YesNo.display_labels(None), ["Yes", "No"]);
        assert_eq!(ButtonsPreset::YesNo.wire_labels(None), ["yes", "no"]);

        assert_eq!(
            ButtonsPreset::YesNoCancel.display_labels(None),
            ["Yes", "No", "Cancel"]
        );
        assert_eq!(
            ButtonsPreset::YesNoCancel.wire_labels(None),
            ["yes", "no", "cancel"]
        );

        assert_eq!(
            ButtonsPreset::RetryCancel.display_labels(None),
            ["Retry", "Cancel"]
        );
        assert_eq!(
            ButtonsPreset::RetryCancel.wire_labels(None),
            ["retry", "cancel"]
        );
    }

    #[test]
    fn custom_labels_are_verbatim() {
        let custom = vec!["Save".into(), "Discard".into()];
        assert_eq!(ButtonsPreset::Custom.display_labels(Some(&custom)), custom);
        assert_eq!(ButtonsPreset::Custom.wire_labels(Some(&custom)), custom);
    }

    #[test]
    fn question_prompt_try_new_rejects_empty() {
        assert_eq!(QuestionPrompt::try_new(""), Err(QuestionPromptError::Empty));
        assert_eq!(QuestionPrompt::try_new("Q?").unwrap().as_str(), "Q?");
    }
}