microsoft-webui-cli 0.0.29

CLI tool for building WebUI applications
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
461
462
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

use std::sync::OnceLock;

use webui::{Diagnostic, ParserError, Severity, WebUIError};

/// CLI output format, selected with the global `--format` flag.
///
/// `Human` is the default colorized terminal rendering. `Json` emits a single
/// machine-readable object per error on **stdout** (and suppresses decorative
/// human output) so editors, CI, and AI assistants can consume diagnostics
/// without scraping ANSI text.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum OutputFormat {
    /// Colorized, human-readable terminal output (default).
    #[default]
    Human,
    /// Machine-readable JSON diagnostics on stdout.
    Json,
}

static FORMAT: OnceLock<OutputFormat> = OnceLock::new();

/// Set the process-wide CLI output format. Call once at startup, before any
/// output is produced; later calls are ignored.
pub fn set_format(format: OutputFormat) {
    let _ = FORMAT.set(format);
}

/// The configured output format (defaults to [`OutputFormat::Human`]).
#[must_use]
pub fn format() -> OutputFormat {
    FORMAT.get().copied().unwrap_or_default()
}

#[must_use]
fn is_json() -> bool {
    matches!(format(), OutputFormat::Json)
}

pub fn header(title: &str) {
    if is_json() {
        return;
    }
    eprintln!(
        "\n  {} {}\n",
        console::style("⚡").cyan().bold(),
        console::style(title).cyan().bold()
    );
}

pub fn field(label: &str, value: &dyn std::fmt::Display) {
    if is_json() {
        return;
    }
    eprintln!(
        "  {} {}",
        console::style(format!("▸ {label:<10}")).dim(),
        console::style(value).bold()
    );
}

pub fn success(message: &str) {
    if is_json() {
        return;
    }
    eprintln!("  {} {message}", console::style("✔").green());
}

pub fn finish(message: &str) {
    if is_json() {
        return;
    }
    eprintln!("\n  {} {message}\n", console::style("✨").green());
}

/// Find a build-time template [`Diagnostic`] within an error's source chain.
fn template_diagnostic(err: &anyhow::Error) -> Option<&Diagnostic> {
    err.chain()
        .find_map(|cause| match cause.downcast_ref::<WebUIError>() {
            Some(WebUIError::Parse {
                source: ParserError::Template(diag),
                ..
            }) => Some(&**diag),
            // Source-transform diagnostics surface during registration.
            Some(WebUIError::ComponentRegistration {
                source: ParserError::Template(diag),
                ..
            }) => Some(&**diag),
            Some(WebUIError::ComponentAssets(diag) | WebUIError::Projection(diag)) => Some(&**diag),
            _ => None,
        })
}

/// Serialize an error as a single machine-readable JSON object.
///
/// A structured template [`Diagnostic`] contributes its `code`, `severity`,
/// owning `file`, `line`/`column`, `snippet`, and `help`; any error also
/// carries the flattened source `chain`. Fields that don't apply are `null`.
///
/// Built via the `serde_json::Map` API rather than the `json!` macro, whose
/// expansion trips the workspace `disallowed_methods` lint (it `unwrap`s on
/// internally-constructed values).
#[must_use]
fn error_json(err: &anyhow::Error) -> serde_json::Value {
    use serde_json::Value;

    let chain: Vec<Value> = err.chain().map(|c| Value::from(c.to_string())).collect();
    let str_or_null = |value: Option<&str>| value.map_or(Value::Null, Value::from);

    let mut map = serde_json::Map::new();
    match template_diagnostic(err) {
        Some(diag) => {
            let (line, column) = match diag.position_line_column() {
                Some((line, column)) => (Value::from(line), Value::from(column)),
                None => (Value::Null, Value::Null),
            };
            map.insert("severity".into(), Value::from(diag.severity().label()));
            map.insert("code".into(), str_or_null(diag.error_code()));
            map.insert("message".into(), Value::from(diag.title()));
            map.insert("file".into(), str_or_null(diag.component_name()));
            map.insert("line".into(), line);
            map.insert("column".into(), column);
            map.insert("snippet".into(), str_or_null(diag.snippet_text()));
            map.insert("help".into(), str_or_null(diag.help_text()));
        }
        None => {
            // Keep the same key set as the structured branch so `--format json`
            // has one stable shape; fields that don't apply are null.
            map.insert("severity".into(), Value::from("error"));
            map.insert("code".into(), Value::Null);
            map.insert("message".into(), Value::from(err.to_string()));
            map.insert("file".into(), Value::Null);
            map.insert("line".into(), Value::Null);
            map.insert("column".into(), Value::Null);
            map.insert("snippet".into(), Value::Null);
            map.insert("help".into(), Value::Null);
        }
    }
    map.insert("chain".into(), Value::Array(chain));
    Value::Object(map)
}

pub fn error(err: &anyhow::Error) {
    if is_json() {
        // One machine-readable object on stdout; tools parse this instead of
        // scraping the colorized stderr rendering.
        println!("{}", error_json(err));
        return;
    }

    // Build-time template-authoring mistakes carry a structured diagnostic;
    // render it in a friendly, colorized format instead of the generic chain.
    if let Some(diag) = template_diagnostic(err) {
        diagnostic(diag);
        return;
    }

    eprintln!(
        "\n  {} {}",
        console::style("✘").red().bold(),
        console::style(err).red().bold()
    );
    for cause in err.chain().skip(1) {
        eprintln!("  {} {cause}", console::style("caused by:").dim());
    }
}

/// Render a build error for the dev-server rebuild loop into a
/// `(display, message)` pair.
///
/// - `display` is per-line colorized for the terminal [`RebuildReporter`].
/// - `message` is plain, color-free text for the browser overlay /
///   live-reload console (ANSI must never reach a browser).
///
/// A template authoring mistake renders as its self-contained [`Diagnostic`]
/// (`title` + `--> file:line:col` + snippet + `help:`), so it isn't buried
/// under redundant `Build failed: Failed to parse …:` context. Any other error
/// flattens the anyhow chain for both renderings.
///
/// [`RebuildReporter`]: webui_dev_server::RebuildReporter
#[must_use]
pub fn build_error_renderings(err: &anyhow::Error) -> (String, String) {
    match template_diagnostic(err) {
        Some(diag) => (styled_diagnostic_body(diag), diag.body()),
        None => {
            let flat = format!("{err:#}");
            (flat.clone(), flat)
        }
    }
}

/// Build the per-line-colorized body of `diag` for the dev-server reporter.
///
/// Mirrors [`diagnostic`], but returns a string because the reporter prepends
/// its own `✘ build error:` / `⚠ build warning:` marker. Each line opens and
/// closes its own SGR span so the output survives being re-prefixed line-by-line
/// (e.g. `[server]` under `xtask dev`); a single span across newlines would
/// bleed. The title is colored by severity (red for errors, yellow for
/// warnings); the location/snippet/help styling is shared.
pub(crate) fn styled_diagnostic_body(diag: &Diagnostic) -> String {
    use std::fmt::Write as _;
    let mut out = String::with_capacity(128);
    let styled_title = match diag.severity() {
        Severity::Warning => console::style(diag.title()).yellow().bold(),
        Severity::Error => console::style(diag.title()).red().bold(),
    };
    let _ = write!(out, "{styled_title}");
    if let Some(code) = diag.error_code() {
        let _ = write!(out, " {}", console::style(format!("[{code}]")).dim());
    }
    if let Some(location) = diag.location() {
        let _ = write!(out, "\n  {}", console::style(location).dim());
    }
    if let Some(snippet) = diag.snippet_text() {
        let _ = write!(out, "\n    {}", console::style(snippet).yellow());
    }
    if let Some(help) = diag.help_text() {
        let _ = write!(out, "\n  {} {help}", console::style("help:").cyan().bold());
    }
    out
}

/// Render a structured build-time [`Diagnostic`] with rustc-style coloring.
///
/// Color is the entry point's responsibility: the parser produces the plain
/// structured data, and the CLI styles it here.
pub fn diagnostic(diag: &Diagnostic) {
    let code = diag
        .error_code()
        .map(|c| format!(" {}", console::style(format!("[{c}]")).dim()))
        .unwrap_or_default();
    eprintln!(
        "\n  {} {}{}",
        console::style("✘").red().bold(),
        console::style(format!("{}: {}", diag.severity().label(), diag.title()))
            .red()
            .bold(),
        code
    );
    if let Some(location) = diag.location() {
        eprintln!("  {}", console::style(location).dim());
    }
    if let Some(snippet) = diag.snippet_text() {
        eprintln!("    {}", console::style(snippet).yellow());
    }
    if let Some(help) = diag.help_text() {
        eprintln!("  {} {help}", console::style("help:").cyan().bold());
    }
}

pub fn hint(message: &str) {
    if is_json() {
        return;
    }
    eprintln!("\n  {} {message}", console::style("hint:").dim());
}

/// Print a non-fatal build advisory as a multi-line warning [`Diagnostic`]
/// (yellow `⚠ build warning:`), mirroring the error layout with its
/// `--> file:line:col`, source snippet, and `help:` suggestion. A leading
/// blank line frames it. Suppressed in JSON mode.
pub fn warning_diagnostic(diag: &Diagnostic) {
    if is_json() {
        return;
    }
    eprintln!(
        "\n  {} {} {}",
        console::style("⚠").yellow().bold(),
        console::style("build warning:").yellow().bold(),
        styled_diagnostic_body(diag),
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Mutex, MutexGuard};

    /// `console` color enablement is process-global, so tests that force it on
    /// must not run concurrently with each other or they observe each other's
    /// restore and see uncolored output.
    static COLOR_LOCK: Mutex<()> = Mutex::new(());

    fn force_colors() -> (MutexGuard<'static, ()>, bool) {
        let guard = COLOR_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let previous = console::colors_enabled();
        console::set_colors_enabled(true);
        (guard, previous)
    }

    fn template_error() -> anyhow::Error {
        let diag = Diagnostic::error("invalid <for> each expression")
            .code("invalid-for-each")
            .component("index.html")
            .position(67, 5)
            .snippet(r#"each="person inpeople""#)
            .help(r#"use the form each="item in collection", e.g. each="todo in todos""#);
        WebUIError::Parse {
            context: "Failed to parse index.html".to_owned(),
            source: ParserError::Template(Box::new(diag)),
        }
        .into()
    }

    fn registration_template_error() -> anyhow::Error {
        let diag = Diagnostic::error("invalid transformed component source")
            .code("invalid-component-source")
            .component("file-card")
            .position(3, 5)
            .snippet("<invalid-source>")
            .help("fix the component source accepted by the active plugin");
        WebUIError::ComponentRegistration {
            context: "Failed to register components from ./src".to_owned(),
            source: ParserError::Template(Box::new(diag)),
        }
        .into()
    }

    #[test]
    fn build_error_message_is_plain_for_browser() {
        // The browser receives `message` via live-reload and logs it with
        // `console.error`; ANSI escape codes would render as literal garbage
        // and break the single-line SSE frame. It must stay color-free even
        // when terminal color is forced on.
        let (_guard, prev) = force_colors();
        let (_display, message) = build_error_renderings(&template_error());
        console::set_colors_enabled(prev);

        assert!(
            !message.contains('\u{1b}'),
            "browser message must not contain ANSI escapes: {message:?}"
        );
        assert!(message.contains("invalid <for> each expression"));
        assert!(message.contains("--> index.html:67:5"));
        assert!(message.contains(r#"each="person inpeople""#));
        assert!(message.contains("help:"));
    }

    #[test]
    fn build_error_display_is_colorized_for_terminal() {
        let (_guard, prev) = force_colors();
        let (display, _message) = build_error_renderings(&template_error());
        console::set_colors_enabled(prev);

        // The terminal rendering carries color...
        assert!(
            display.contains('\u{1b}'),
            "terminal display should be colorized when color is enabled: {display:?}"
        );
        // ...applied per line: no SGR span may straddle a newline, or it would
        // bleed when each line is re-prefixed (e.g. `[server]`). Every line
        // that opens a color must reset before its end.
        for line in display.lines() {
            if line.contains('\u{1b}') {
                assert!(
                    line.contains("\u{1b}[0m"),
                    "colored line must reset within itself: {line:?}"
                );
            }
        }
        // Same content as the plain body, just styled.
        assert!(console::strip_ansi_codes(&display).contains("invalid <for> each expression"));
        assert!(console::strip_ansi_codes(&display).contains("--> index.html:67:5"));
    }

    #[test]
    fn build_error_falls_back_to_flat_chain_without_diagnostic() {
        let err: anyhow::Error = WebUIError::Serialization("bad state json".to_owned()).into();
        let (display, message) = build_error_renderings(&err);
        assert_eq!(display, message);
        assert!(message.contains("bad state json"));
        assert!(!message.contains('\u{1b}'));
    }

    #[test]
    fn error_json_for_diagnostic_has_structured_fields() {
        let value = error_json(&template_error());
        assert_eq!(value["severity"], "error");
        assert_eq!(value["code"], "invalid-for-each");
        assert_eq!(value["message"], "invalid <for> each expression");
        assert_eq!(value["file"], "index.html");
        assert_eq!(value["line"], 67);
        assert_eq!(value["column"], 5);
        assert_eq!(value["snippet"], "each=\"person inpeople\"");
        assert!(value["help"]
            .as_str()
            .is_some_and(|h| h.contains("item in collection")));
        // The flattened source chain is always present.
        assert!(value["chain"].is_array());
        // The serialized object never carries ANSI escapes.
        assert!(!value.to_string().contains('\u{1b}'));
    }

    #[test]
    fn error_json_extracts_registration_template_diagnostic() {
        // A component-registration authoring mistake must surface its full
        // structured diagnostic in `--format json` (code/file/line/column/
        // snippet/help), not a flattened string — the same shape as a parse
        // error — and never leak ANSI escapes.
        let prev = console::colors_enabled();
        console::set_colors_enabled(true);
        let value = error_json(&registration_template_error());
        console::set_colors_enabled(prev);

        assert_eq!(value["severity"], "error");
        assert_eq!(value["code"], "invalid-component-source");
        assert_eq!(value["file"], "file-card");
        assert_eq!(value["line"], 3);
        assert_eq!(value["column"], 5);
        assert_eq!(value["snippet"], "<invalid-source>");
        assert!(value["message"]
            .as_str()
            .is_some_and(|m| m.contains("invalid transformed component source")));
        assert!(value["help"]
            .as_str()
            .is_some_and(|h| h.contains("active plugin")));
        assert!(value["chain"].is_array());
        assert!(!value.to_string().contains('\u{1b}'));
    }

    #[test]
    fn build_error_rendering_for_registration_diagnostic_is_plain_and_located() {
        // The dev-server/browser rendering path also extracts the structured
        // diagnostic from a registration error, so the color-free browser
        // message keeps its rustc-style `--> file:line:col` location.
        let prev = console::colors_enabled();
        console::set_colors_enabled(true);
        let (_display, message) = build_error_renderings(&registration_template_error());
        console::set_colors_enabled(prev);

        assert!(
            !message.contains('\u{1b}'),
            "browser message must be ANSI-free: {message:?}"
        );
        assert!(message.contains("--> file-card:3:5"));
        assert!(message.contains("[invalid-component-source]"));
    }

    #[test]
    fn error_json_without_diagnostic_has_consistent_shape() {
        let err: anyhow::Error = WebUIError::Serialization("bad state json".to_owned()).into();
        let value = error_json(&err);
        assert_eq!(value["severity"], "error");
        assert!(value["code"].is_null());
        assert!(value["message"]
            .as_str()
            .is_some_and(|m| m.contains("bad state json")));
        assert!(value["chain"].is_array());
        // Non-applicable fields are present as null, not omitted, so tools see
        // one stable object shape regardless of error kind.
        for key in ["file", "line", "column", "snippet", "help"] {
            assert!(
                value.get(key).is_some_and(serde_json::Value::is_null),
                "expected `{key}` to be present and null"
            );
        }
    }
}