node-app-build 5.20.3

Mini app developer CLI: scaffold, validate, package node-app-* Debian packages
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use std::collections::{HashMap, VecDeque};
use std::time::Instant;

use ratatui::layout::Rect;

use super::LogEntry;

const MAX_LOG_LINES: usize = 2000;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LogSource {
    Daemon,
    UiServer,
    Build,
    App,
    System,
}

impl LogSource {
    pub fn all() -> &'static [LogSource] {
        &[
            LogSource::System,
            LogSource::Daemon,
            LogSource::UiServer,
            LogSource::Build,
            LogSource::App,
        ]
    }

    pub fn tab_label(self) -> &'static str {
        match self {
            LogSource::System => "1:system",
            LogSource::Daemon => "2:daemon",
            LogSource::UiServer => "3:ui",
            LogSource::Build => "4:build",
            LogSource::App => "5:app",
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum ServiceStatus {
    Pending,
    Building,
    Starting,
    Ready,
    Watching,
    Changed,
    Loaded { reloads: usize },
    Failed(String),
    Disabled,
}

impl ServiceStatus {
    pub fn indicator(&self) -> &'static str {
        match self {
            ServiceStatus::Ready | ServiceStatus::Loaded { .. } | ServiceStatus::Watching => "",
            ServiceStatus::Building | ServiceStatus::Starting | ServiceStatus::Changed => "",
            ServiceStatus::Failed(_) => "",
            ServiceStatus::Pending => "",
            ServiceStatus::Disabled => "",
        }
    }

    pub fn color(&self) -> ratatui::style::Color {
        use ratatui::style::Color;
        match self {
            ServiceStatus::Ready | ServiceStatus::Loaded { .. } | ServiceStatus::Watching => {
                Color::Green
            }
            ServiceStatus::Building | ServiceStatus::Starting | ServiceStatus::Changed => {
                Color::Yellow
            }
            ServiceStatus::Failed(_) => Color::Red,
            ServiceStatus::Pending | ServiceStatus::Disabled => Color::DarkGray,
        }
    }

    pub fn summary(&self) -> String {
        match self {
            ServiceStatus::Pending => "pending".into(),
            ServiceStatus::Building => "building…".into(),
            ServiceStatus::Starting => "starting…".into(),
            ServiceStatus::Ready => "ready".into(),
            ServiceStatus::Watching => "watching".into(),
            ServiceStatus::Changed => "changed!".into(),
            ServiceStatus::Loaded { reloads } => format!("loaded (×{reloads})"),
            ServiceStatus::Failed(msg) => {
                format!("FAILED: {}", msg.chars().take(18).collect::<String>())
            }
            ServiceStatus::Disabled => "disabled".into(),
        }
    }
}

pub struct ServiceState {
    pub label: &'static str,
    pub status: ServiceStatus,
    pub detail: String,
}

/// Timing metadata tracked per service from status-transition events.
/// Computed once per status change; live elapsed is derived at render time.
pub struct Timings {
    // Build
    pub build_started_at: Option<Instant>,
    pub last_build_ms: Option<u64>,
    pub build_count: usize,
    // Daemon uptime
    pub daemon_started_at: Option<Instant>,
    // App reload
    pub last_reload_ms: Option<u64>,
}

impl Timings {
    fn new() -> Self {
        Self {
            build_started_at: None,
            last_build_ms: None,
            build_count: 0,
            daemon_started_at: None,
            last_reload_ms: None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShutdownPhase {
    Running,
    /// `q` / Ctrl+C pressed — waiting for host_impl.shutdown() to complete.
    ShuttingDown,
    /// Orchestrator finished shutdown — TUI may now exit.
    Done,
}

/// Saved layout rects from the last rendered frame, used for mouse hit-testing.
#[derive(Clone, Copy, Default)]
pub struct TuiLayout {
    pub service_list: Rect,
    pub tab_bar: Rect,
    pub log_scroll: Rect,
    /// x-position of each tab's left edge, parallel to LogSource::all().
    pub tab_edges: [u16; 5],
}

/// A drag selection over absolute log-line indices in the VecDeque.
#[derive(Clone, Copy, Debug)]
pub struct Selection {
    /// Absolute log-line index (in the VecDeque) where drag started.
    pub anchor: usize,
    /// Current drag endpoint.
    pub head: usize,
}

impl Selection {
    pub fn range(self) -> (usize, usize) {
        (self.anchor.min(self.head), self.anchor.max(self.head))
    }
    pub fn contains(self, idx: usize) -> bool {
        let (s, e) = self.range();
        idx >= s && idx <= e
    }
}

pub struct AppState {
    pub app_name: String,
    pub app_version: String,
    pub mode: String,
    services: Vec<(LogSource, ServiceState)>,
    logs: HashMap<LogSource, VecDeque<String>>,
    pub active_pane: LogSource,
    pub auto_scroll: bool,
    pub scroll_pos: usize,
    // Search / filter
    pub search_query: String,
    pub search_input_active: bool,
    // Set by the render function so page_up/page_down know the viewport height.
    pub last_render_height: usize,
    pub shutdown_phase: ShutdownPhase,
    pub timings: Timings,
    // Mouse support
    pub layout: TuiLayout,
    /// Absolute log-line index of the first visible row (set by render each frame).
    pub log_scroll_start: usize,
    pub selection: Option<Selection>,
    /// Set when text is copied; shown in footer for 2 s.
    pub copy_flash: Option<std::time::Instant>,
}

impl AppState {
    pub fn new(app_name: String, app_version: String, mode: String) -> Self {
        let services = vec![
            (
                LogSource::Daemon,
                ServiceState {
                    label: "daemon",
                    status: ServiceStatus::Pending,
                    detail: String::new(),
                },
            ),
            (
                LogSource::UiServer,
                ServiceState {
                    label: "ui-server",
                    status: ServiceStatus::Pending,
                    detail: String::new(),
                },
            ),
            (
                LogSource::Build,
                ServiceState {
                    label: "build",
                    status: ServiceStatus::Pending,
                    detail: String::new(),
                },
            ),
            (
                LogSource::App,
                ServiceState {
                    label: "app",
                    status: ServiceStatus::Pending,
                    detail: String::new(),
                },
            ),
            (
                LogSource::System,
                ServiceState {
                    label: "system",
                    status: ServiceStatus::Ready,
                    detail: String::new(),
                },
            ),
        ];
        Self {
            app_name,
            app_version,
            mode,
            services,
            logs: HashMap::new(),
            active_pane: LogSource::System,
            auto_scroll: true,
            scroll_pos: 0,
            search_query: String::new(),
            search_input_active: false,
            last_render_height: 24,
            shutdown_phase: ShutdownPhase::Running,
            timings: Timings::new(),
            layout: TuiLayout::default(),
            log_scroll_start: 0,
            selection: None,
            copy_flash: None,
        }
    }

    pub fn push_log(&mut self, entry: LogEntry) {
        let buf = self.logs.entry(entry.source).or_default();
        // Strip ANSI escape sequences and bare \r before storing — cargo and
        // daemon processes emit colour codes and progress-bar carriage returns
        // that ratatui renders as literal characters, corrupting the display.
        let line = strip_ansi(&entry.line);
        if line.is_empty() {
            return;
        }
        buf.push_back(line);
        if buf.len() > MAX_LOG_LINES {
            buf.pop_front();
            if !self.auto_scroll && entry.source == self.active_pane {
                self.scroll_pos = self.scroll_pos.saturating_sub(1);
            }
        }
        if self.auto_scroll && entry.source == self.active_pane && self.search_query.is_empty() {
            self.scroll_pos = buf.len();
        }
    }

    pub fn update_service(
        &mut self,
        source: LogSource,
        status: ServiceStatus,
        detail: Option<String>,
    ) {
        // Record timing from status transitions before updating the service.
        match (&source, &status) {
            (LogSource::Build, ServiceStatus::Building) => {
                self.timings.build_started_at = Some(Instant::now());
            }
            (LogSource::Build, ServiceStatus::Ready) => {
                if let Some(started) = self.timings.build_started_at.take() {
                    self.timings.last_build_ms = Some(started.elapsed().as_millis() as u64);
                    self.timings.build_count += 1;
                }
            }
            (LogSource::Build, ServiceStatus::Failed(_)) => {
                if let Some(started) = self.timings.build_started_at.take() {
                    self.timings.last_build_ms = Some(started.elapsed().as_millis() as u64);
                    // Count failed builds too so the developer can see retry patterns.
                    self.timings.build_count += 1;
                }
            }
            (LogSource::Daemon, ServiceStatus::Starting) => {
                self.timings.daemon_started_at = Some(Instant::now());
            }
            (LogSource::App, ServiceStatus::Loaded { .. }) => {
                // cycle() sends detail = "last reload: Xms"; extract the ms value.
                if let Some(d) = &detail {
                    if let Some(rest) = d.strip_prefix("last reload: ") {
                        if let Some(ms_str) = rest.strip_suffix("ms") {
                            if let Ok(ms) = ms_str.parse::<u64>() {
                                self.timings.last_reload_ms = Some(ms);
                            }
                        }
                    }
                }
            }
            _ => {}
        }

        if let Some((_, svc)) = self.services.iter_mut().find(|(s, _)| *s == source) {
            svc.status = status;
            if let Some(d) = detail {
                svc.detail = d;
            }
        }
    }

    pub fn services(&self) -> &[(LogSource, ServiceState)] {
        &self.services
    }

    pub fn log_lines(&self, source: LogSource) -> &VecDeque<String> {
        static EMPTY: std::sync::OnceLock<VecDeque<String>> = std::sync::OnceLock::new();
        self.logs
            .get(&source)
            .unwrap_or_else(|| EMPTY.get_or_init(VecDeque::new))
    }

    /// Returns the first visible line index for a given pane height and total
    /// (which may be the filtered total when a query is active).
    pub fn visible_start_for(&self, total: usize, height: usize) -> usize {
        if self.auto_scroll {
            total.saturating_sub(height)
        } else {
            self.scroll_pos.min(total.saturating_sub(height))
        }
    }

    pub fn cycle_pane(&mut self, delta: i32) {
        let sources = LogSource::all();
        let pos = sources
            .iter()
            .position(|s| *s == self.active_pane)
            .unwrap_or(0);
        let next = ((pos as i32 + delta).rem_euclid(sources.len() as i32)) as usize;
        self.active_pane = sources[next];
        self.auto_scroll = true;
        self.clear_search();
    }

    pub fn scroll_up(&mut self) {
        if self.auto_scroll {
            let total = self.log_lines(self.active_pane).len();
            self.scroll_pos = total;
            self.auto_scroll = false;
        }
        self.scroll_pos = self.scroll_pos.saturating_sub(1);
    }

    pub fn scroll_down(&mut self) {
        if !self.auto_scroll {
            let total = self.log_lines(self.active_pane).len();
            self.scroll_pos = (self.scroll_pos + 1).min(total);
        }
    }

    pub fn page_up(&mut self) {
        let step = (self.last_render_height / 2).max(1);
        if self.auto_scroll {
            let total = self.log_lines(self.active_pane).len();
            self.scroll_pos = total;
            self.auto_scroll = false;
        }
        self.scroll_pos = self.scroll_pos.saturating_sub(step);
    }

    pub fn page_down(&mut self) {
        if !self.auto_scroll {
            let step = (self.last_render_height / 2).max(1);
            let total = self.log_lines(self.active_pane).len();
            self.scroll_pos = (self.scroll_pos + step).min(total);
        }
    }

    pub fn scroll_top(&mut self) {
        self.auto_scroll = false;
        self.scroll_pos = 0;
    }

    pub fn scroll_bottom(&mut self) {
        self.auto_scroll = true;
    }

    pub fn clear_active_pane(&mut self) {
        self.logs.remove(&self.active_pane);
        self.scroll_pos = 0;
        self.auto_scroll = true;
        self.clear_search();
    }

    // ── Search / filter ───────────────────────────────────────────────────────

    /// Open the search input box.
    pub fn enter_search(&mut self) {
        self.search_input_active = true;
    }

    /// Close the input box but leave the filter active.
    pub fn exit_search_input(&mut self) {
        self.search_input_active = false;
    }

    /// Clear the query and close the input box.
    pub fn clear_search(&mut self) {
        self.search_query.clear();
        self.search_input_active = false;
        self.auto_scroll = true;
    }

    /// Append a character to the search query.
    pub fn search_push(&mut self, c: char) {
        self.search_query.push(c);
        self.scroll_pos = 0;
        self.auto_scroll = false;
    }

    /// Remove the last character from the query.
    pub fn search_backspace(&mut self) {
        self.search_query.pop();
        self.scroll_pos = 0;
        if self.search_query.is_empty() {
            self.auto_scroll = true;
        }
    }

    /// Returns `true` if `line` matches the current query (fuzzy, case-insensitive).
    /// Always returns `true` when the query is empty.
    pub fn matches(&self, line: &str) -> bool {
        fuzzy_match(line, &self.search_query)
    }

    /// For a line that matches the query, returns the byte indices of every
    /// matched character (for highlight rendering). Returns `None` if no match.
    pub fn match_positions(&self, line: &str) -> Option<Vec<usize>> {
        if self.search_query.is_empty() {
            return None;
        }
        fuzzy_positions(line, &self.search_query)
    }

    /// Collect the currently selected log lines as a newline-separated string.
    pub fn get_selected_text(&self) -> String {
        let sel = match self.selection {
            Some(s) => s,
            None => return String::new(),
        };
        let (start, end) = sel.range();
        self.log_lines(self.active_pane)
            .iter()
            .enumerate()
            .skip(start)
            .take_while(|(i, _)| *i <= end)
            .map(|(_, l)| l.as_str())
            .collect::<Vec<_>>()
            .join("\n")
    }
}

// ── ANSI stripping ────────────────────────────────────────────────────────────

/// Remove ANSI/VT escape sequences and bare `\r` from a log line.
///
/// Handles:
/// - CSI sequences: `ESC [ <params> <final-byte>`  (colours, cursor movement)
/// - OSC sequences: `ESC ] … ST`                   (title sets, hyperlinks)
/// - Bare `\r`                                      (cargo progress-bar rewind)
fn strip_ansi(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut it = s.chars().peekable();
    while let Some(c) = it.next() {
        match c {
            '\x1b' => match it.peek() {
                // CSI: ESC [ <param bytes 0x30-0x3f> <intermediate 0x20-0x2f> <final 0x40-0x7e>
                Some('[') => {
                    it.next();
                    for ch in it.by_ref() {
                        if ch.is_ascii() && (0x40..=0x7e).contains(&(ch as u8)) {
                            break;
                        }
                    }
                }
                // OSC: ESC ] … BEL  or  … ESC \
                Some(']') => {
                    it.next();
                    loop {
                        match it.next() {
                            None | Some('\x07') => break,
                            Some('\x1b') => {
                                if it.peek() == Some(&'\\') {
                                    it.next();
                                }
                                break;
                            }
                            _ => {}
                        }
                    }
                }
                // Any other ESC — skip the ESC byte itself; let next char through.
                _ => {}
            },
            // Carriage return — cargo uses \r to rewrite progress lines.
            // We treat it as a line-reset: discard everything written so far on
            // this "visual line" (i.e. clear `out`) so only the final state shows.
            '\r' => out.clear(),
            _ => out.push(c),
        }
    }
    out
}

// ── Fuzzy matching ─────────────────────────────────────────────────────────────

/// True if every character in `query` appears in `line` in order (case-insensitive).
pub fn fuzzy_match(line: &str, query: &str) -> bool {
    if query.is_empty() {
        return true;
    }
    let mut line_chars = line.chars().flat_map(char::to_lowercase);
    query
        .chars()
        .flat_map(char::to_lowercase)
        .all(|q| line_chars.any(|c| c == q))
}

/// Returns the *char* indices (into `line`) of matched query characters.
/// Returns `None` if the line doesn't match.
pub fn fuzzy_positions(line: &str, query: &str) -> Option<Vec<usize>> {
    if query.is_empty() {
        return Some(vec![]);
    }
    let line_chars: Vec<char> = line.chars().collect();
    let query_lower: Vec<char> = query.chars().flat_map(char::to_lowercase).collect();

    let mut positions = Vec::with_capacity(query_lower.len());
    let mut li = 0usize;

    for qc in &query_lower {
        let found = line_chars[li..].iter().enumerate().find(|(_, lc)| {
            lc.to_lowercase().next() == Some(*qc)
        });
        match found {
            Some((offset, _)) => {
                positions.push(li + offset);
                li += offset + 1;
            }
            None => return None,
        }
    }
    Some(positions)
}