revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
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
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! Hot reload support for CSS stylesheets

use crate::constants::DEBOUNCE_FILE_SYSTEM;
use notify::{Event, EventKind, RecursiveMode, Watcher};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{channel, Receiver};
use std::time::{Duration, Instant};

/// Validate and sanitize a path to prevent path traversal attacks
///
/// On Unix-like systems, performs strict validation to prevent escaping the project directory.
/// On Windows, path traversal risks are different, so we use a more permissive validation.
///
/// Returns an error if the path:
/// - Contains excessive parent directory references (`../`)
/// - Attempts to escape the current directory
/// - Contains null bytes
fn validate_path(path: &Path) -> Result<(), PathValidationError> {
    let path_str = path.to_string_lossy();

    // Check for null bytes (potential for string truncation attacks)
    if path_str.contains('') {
        return Err(PathValidationError::NullByte);
    }

    // Helper function to robustly check if a path is within the current directory
    let is_within_current_dir = |canonical_path: &Path| -> Result<bool, PathValidationError> {
        let current_dir =
            std::env::current_dir().map_err(|_| PathValidationError::CurrentDirAccess)?;

        // Try to canonicalize current_dir for fair comparison
        let current_canonical = current_dir.canonicalize().unwrap_or(current_dir.clone());

        // On both Unix and Windows, use prefix comparison on canonicalized paths
        // This handles case-insensitivity and different path separators
        Ok(canonical_path
            .to_string_lossy()
            .to_lowercase()
            .starts_with(&current_canonical.to_string_lossy().to_lowercase()))
    };

    // Normalize the path and check if it escapes the current directory
    match path.canonicalize() {
        Ok(canonical) => {
            if !is_within_current_dir(&canonical)? {
                return Err(PathValidationError::EscapeAttempt {
                    path: path.to_path_buf(),
                    canonical,
                });
            }
            Ok(())
        }
        Err(_) => {
            // If path doesn't exist yet, check the parent directory
            if let Some(parent) = path.parent() {
                if parent.try_exists().unwrap_or(false) {
                    match parent.canonicalize() {
                        Ok(canonical_parent) => {
                            if !is_within_current_dir(&canonical_parent)? {
                                return Err(PathValidationError::ParentEscapeAttempt {
                                    path: path.to_path_buf(),
                                    parent_canonical: canonical_parent,
                                });
                            }
                        }
                        Err(_) => {
                            return Err(PathValidationError::InvalidPath {
                                path: path.to_path_buf(),
                            });
                        }
                    }
                }
            }
            // Path doesn't exist and parent doesn't exist - allow it (might be created later)
            Ok(())
        }
    }
}

/// Errors that can occur during path validation
#[derive(Debug, Clone, PartialEq)]
pub enum PathValidationError {
    /// Path contains null byte
    NullByte,
    /// Path attempts to escape the current directory
    EscapeAttempt { path: PathBuf, canonical: PathBuf },
    /// Parent directory attempts to escape the current directory
    ParentEscapeAttempt {
        path: PathBuf,
        parent_canonical: PathBuf,
    },
    /// Invalid path that cannot be canonicalized
    InvalidPath { path: PathBuf },
    /// Cannot access current directory
    CurrentDirAccess,
}

impl std::fmt::Display for PathValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NullByte => write!(f, "Path contains null byte"),
            Self::EscapeAttempt { path, canonical } => write!(
                f,
                "Path escapes current directory: {:?} -> {:?}",
                path, canonical
            ),
            Self::ParentEscapeAttempt {
                path,
                parent_canonical,
            } => write!(
                f,
                "Parent directory escapes current directory: {:?} -> {:?}",
                path, parent_canonical
            ),
            Self::InvalidPath { path } => {
                write!(f, "Invalid path that cannot be canonicalized: {:?}", path)
            }
            Self::CurrentDirAccess => write!(f, "Cannot access current directory"),
        }
    }
}

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

/// Hot reload event
#[derive(Debug, Clone)]
pub enum HotReloadEvent {
    /// A stylesheet was modified
    StylesheetChanged(PathBuf),
    /// A file was created
    FileCreated(PathBuf),
    /// A file was deleted
    FileDeleted(PathBuf),
    /// Watcher error
    Error(String),
}

/// Hot reload watcher configuration
pub struct HotReloadConfig {
    /// Debounce duration to avoid rapid duplicate events
    pub debounce: Duration,
    /// Watch recursively
    pub recursive: bool,
}

impl Default for HotReloadConfig {
    fn default() -> Self {
        Self {
            debounce: DEBOUNCE_FILE_SYSTEM,
            recursive: true,
        }
    }
}

/// Hot reload watcher
pub struct HotReload {
    _watcher: notify::RecommendedWatcher,
    receiver: Receiver<HotReloadEvent>,
    watched_paths: Vec<PathBuf>,
    /// Per-path debounce tracking: maps (event_type_variant, path) -> last_event_time
    /// This prevents different files from debouncing each other
    last_events: HashMap<String, Instant>,
    debounce: Duration,
}

impl HotReload {
    /// Create a new hot reload watcher
    ///
    /// # Errors
    ///
    /// Returns `notify::Error` if the file system watcher cannot be created.
    /// This can happen if:
    /// - The operating system doesn't support file watching
    /// - The watcher limit has been reached
    /// - Insufficient permissions
    pub fn new() -> Result<Self, notify::Error> {
        Self::with_config(HotReloadConfig::default())
    }

    /// Create with custom configuration
    ///
    /// # Errors
    ///
    /// Returns `notify::Error` if the file system watcher cannot be created
    /// with the specified configuration.
    pub fn with_config(config: HotReloadConfig) -> Result<Self, notify::Error> {
        let (tx, rx) = channel();
        let sender = tx.clone();

        let watcher =
            notify::recommended_watcher(
                move |result: Result<Event, notify::Error>| match result {
                    Ok(event) => {
                        let reload_event = match event.kind {
                            EventKind::Modify(_) => event
                                .paths
                                .first()
                                .map(|p| HotReloadEvent::StylesheetChanged(p.clone())),
                            EventKind::Create(_) => event
                                .paths
                                .first()
                                .map(|p| HotReloadEvent::FileCreated(p.clone())),
                            EventKind::Remove(_) => event
                                .paths
                                .first()
                                .map(|p| HotReloadEvent::FileDeleted(p.clone())),
                            _ => None,
                        };

                        if let Some(e) = reload_event {
                            let _ = sender.send(e);
                        }
                    }
                    Err(e) => {
                        let _ = sender.send(HotReloadEvent::Error(e.to_string()));
                    }
                },
            )?;

        Ok(Self {
            _watcher: watcher,
            receiver: rx,
            watched_paths: Vec::new(),
            last_events: HashMap::new(),
            debounce: config.debounce,
        })
    }

    /// Watch a file or directory for changes
    ///
    /// Directories are watched recursively. Files are watched non-recursively.
    ///
    /// # Security
    ///
    /// This function validates paths to prevent path traversal attacks.
    /// Paths attempting to escape the current directory will be rejected.
    ///
    /// # Errors
    ///
    /// Returns `notify::Error` if:
    /// - The path doesn't exist
    /// - Insufficient permissions to watch the path
    /// - The watcher limit has been reached
    ///
    /// Returns `PathValidationError` if:
    /// - The path contains null bytes
    /// - The path attempts to escape the current directory (e.g., `../../../etc/passwd`)
    pub fn watch(&mut self, path: impl AsRef<Path>) -> Result<(), notify::Error> {
        let path = path.as_ref().to_path_buf();

        // Validate path to prevent traversal attacks
        validate_path(&path).map_err(|e| {
            notify::Error::new(notify::ErrorKind::Io(std::io::Error::new(
                std::io::ErrorKind::PermissionDenied,
                format!("Path validation failed: {}", e),
            )))
        })?;

        let mode = if path.is_dir() {
            RecursiveMode::Recursive
        } else {
            RecursiveMode::NonRecursive
        };

        self._watcher.watch(&path, mode)?;
        self.watched_paths.push(path);
        Ok(())
    }

    /// Unwatch a previously watched path
    ///
    /// # Errors
    ///
    /// Returns `notify::Error` if the path was not being watched.
    pub fn unwatch(&mut self, path: impl AsRef<Path>) -> Result<(), notify::Error> {
        let path = path.as_ref();
        self._watcher.unwatch(path)?;
        self.watched_paths.retain(|p| p != path);
        Ok(())
    }

    /// Get watched paths
    pub fn watched_paths(&self) -> &[PathBuf] {
        &self.watched_paths
    }

    /// Poll for events (non-blocking)
    pub fn poll(&mut self) -> Option<HotReloadEvent> {
        match self.receiver.try_recv() {
            Ok(event) => {
                // Apply per-path debouncing
                let now = Instant::now();
                // Create a unique key based on event type and path
                let event_key = match &event {
                    HotReloadEvent::StylesheetChanged(p) => format!("changed:{}", p.display()),
                    HotReloadEvent::FileCreated(p) => format!("created:{}", p.display()),
                    HotReloadEvent::FileDeleted(p) => format!("deleted:{}", p.display()),
                    HotReloadEvent::Error(_) => format!("error:{}", now.elapsed().as_millis()),
                };

                if let Some(&last) = self.last_events.get(&event_key) {
                    if now.duration_since(last) < self.debounce {
                        return None; // Debounced
                    }
                }
                self.last_events.insert(event_key, now);
                Some(event)
            }
            Err(_) => None,
        }
    }

    /// Wait for next event (blocking)
    pub fn wait(&mut self) -> Option<HotReloadEvent> {
        match self.receiver.recv() {
            Ok(event) => {
                let now = Instant::now();
                // Create a unique key based on event type and path
                let event_key = match &event {
                    HotReloadEvent::StylesheetChanged(p) => format!("changed:{}", p.display()),
                    HotReloadEvent::FileCreated(p) => format!("created:{}", p.display()),
                    HotReloadEvent::FileDeleted(p) => format!("deleted:{}", p.display()),
                    HotReloadEvent::Error(_) => format!("error:{}", now.elapsed().as_millis()),
                };
                self.last_events.insert(event_key, now);
                Some(event)
            }
            Err(_) => None,
        }
    }

    /// Wait for next event with timeout
    pub fn wait_timeout(&mut self, timeout: Duration) -> Option<HotReloadEvent> {
        match self.receiver.recv_timeout(timeout) {
            Ok(event) => {
                let now = Instant::now();
                // Create a unique key based on event type and path
                let event_key = match &event {
                    HotReloadEvent::StylesheetChanged(p) => format!("changed:{}", p.display()),
                    HotReloadEvent::FileCreated(p) => format!("created:{}", p.display()),
                    HotReloadEvent::FileDeleted(p) => format!("deleted:{}", p.display()),
                    HotReloadEvent::Error(_) => format!("error:{}", now.elapsed().as_millis()),
                };
                self.last_events.insert(event_key, now);
                Some(event)
            }
            Err(_) => None,
        }
    }

    /// Check if any CSS files changed
    pub fn css_changed(&mut self) -> Option<PathBuf> {
        while let Some(event) = self.poll() {
            if let HotReloadEvent::StylesheetChanged(path) = event {
                // Case-insensitive extension check (handles .CSS, .Css, etc.)
                if path
                    .extension()
                    .and_then(|e| e.to_str())
                    .map(|e| e.eq_ignore_ascii_case("css"))
                    .unwrap_or(false)
                {
                    return Some(path);
                }
            }
        }
        None
    }
}

/// Builder for hot reload
pub struct HotReloadBuilder {
    config: HotReloadConfig,
    paths: Vec<PathBuf>,
}

impl HotReloadBuilder {
    /// Create a new builder
    pub fn new() -> Self {
        Self {
            config: HotReloadConfig::default(),
            paths: Vec::new(),
        }
    }

    /// Set debounce duration
    pub fn debounce(mut self, duration: Duration) -> Self {
        self.config.debounce = duration;
        self
    }

    /// Add a path to watch
    pub fn watch(mut self, path: impl AsRef<Path>) -> Self {
        self.paths.push(path.as_ref().to_path_buf());
        self
    }

    /// Build the hot reload watcher
    ///
    /// # Errors
    ///
    /// Returns `notify::Error` if:
    /// - The watcher cannot be created
    /// - Any of the configured paths cannot be watched
    pub fn build(self) -> Result<HotReload, notify::Error> {
        let mut hr = HotReload::with_config(self.config)?;
        for path in self.paths {
            hr.watch(&path)?;
        }
        Ok(hr)
    }
}

impl Default for HotReloadBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Helper function to create a hot reload watcher
pub fn hot_reload() -> HotReloadBuilder {
    HotReloadBuilder::new()
}
// KEEP HERE - Private implementation tests (accesses private fields)

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

    #[test]
    fn test_hot_reload_new() {
        let hr = HotReload::new();
        assert!(hr.is_ok());
    }

    #[test]
    fn test_hot_reload_with_config() {
        let config = HotReloadConfig {
            debounce: Duration::from_millis(50),
            recursive: false,
        };
        let hr = HotReload::with_config(config);
        assert!(hr.is_ok());
        let hr = hr.unwrap();
        assert_eq!(hr.debounce, Duration::from_millis(50));
    }

    #[test]
    fn test_hot_reload_config_default() {
        let config = HotReloadConfig::default();
        assert_eq!(config.debounce, Duration::from_millis(100));
        assert!(config.recursive);
    }

    #[test]
    fn test_hot_reload_builder_new() {
        let builder = HotReloadBuilder::new();
        assert!(builder.paths.is_empty());
        assert_eq!(builder.config.debounce, Duration::from_millis(100));
    }

    #[test]
    fn test_hot_reload_builder_default() {
        let builder = HotReloadBuilder::default();
        assert!(builder.paths.is_empty());
        assert_eq!(builder.config.debounce, Duration::from_millis(100));
    }

    #[test]
    fn test_hot_reload_builder_debounce() {
        let builder = HotReloadBuilder::new().debounce(Duration::from_millis(200));
        assert_eq!(builder.config.debounce, Duration::from_millis(200));
    }

    #[test]
    fn test_hot_reload_builder_watch() {
        let builder = HotReloadBuilder::new().watch("src").watch("tests");
        assert_eq!(builder.paths.len(), 2);
    }

    #[test]
    fn test_hot_reload_builder_build() {
        let hr = HotReloadBuilder::new()
            .debounce(Duration::from_millis(75))
            .watch(".")
            .build();
        assert!(hr.is_ok());
        let hr = hr.unwrap();
        assert_eq!(hr.debounce, Duration::from_millis(75));
        assert_eq!(hr.watched_paths().len(), 1);
    }

    #[test]
    fn test_hot_reload_watch_current_dir() {
        let mut hr = HotReload::new().unwrap();
        // Watch current directory (always exists)
        let result = hr.watch(".");
        assert!(result.is_ok());
        assert_eq!(hr.watched_paths().len(), 1);
    }

    #[test]
    fn test_hot_reload_watch_multiple_paths() {
        let mut hr = HotReload::new().unwrap();
        let _ = hr.watch(".");
        let _ = hr.watch("src");
        // Both should be tracked
        assert_eq!(hr.watched_paths().len(), 2);
    }

    #[test]
    fn test_hot_reload_unwatch() {
        let mut hr = HotReload::new().unwrap();
        let _ = hr.watch(".");
        assert_eq!(hr.watched_paths().len(), 1);
        let result = hr.unwatch(".");
        assert!(result.is_ok());
        assert!(hr.watched_paths().is_empty());
    }

    #[test]
    fn test_hot_reload_poll_empty() {
        let mut hr = HotReload::new().unwrap();
        assert!(hr.poll().is_none());
    }

    #[test]
    fn test_hot_reload_wait_timeout_empty() {
        let mut hr = HotReload::new().unwrap();
        let event = hr.wait_timeout(Duration::from_millis(1));
        assert!(event.is_none());
    }

    #[test]
    fn test_hot_reload_css_changed_empty() {
        let mut hr = HotReload::new().unwrap();
        let changed = hr.css_changed();
        assert!(changed.is_none());
    }

    #[test]
    fn test_hot_reload_helper() {
        let builder = hot_reload().debounce(Duration::from_millis(50));
        assert_eq!(builder.config.debounce, Duration::from_millis(50));
    }

    #[test]
    fn test_hot_reload_event_stylesheet_changed() {
        let event = HotReloadEvent::StylesheetChanged(PathBuf::from("test.css"));
        let debug = format!("{:?}", event);
        assert!(debug.contains("StylesheetChanged"));
        assert!(debug.contains("test.css"));
    }

    #[test]
    fn test_hot_reload_event_file_created() {
        let event = HotReloadEvent::FileCreated(PathBuf::from("new.css"));
        let debug = format!("{:?}", event);
        assert!(debug.contains("FileCreated"));
        assert!(debug.contains("new.css"));
    }

    #[test]
    fn test_hot_reload_event_file_deleted() {
        let event = HotReloadEvent::FileDeleted(PathBuf::from("deleted.css"));
        let debug = format!("{:?}", event);
        assert!(debug.contains("FileDeleted"));
        assert!(debug.contains("deleted.css"));
    }

    #[test]
    fn test_hot_reload_event_error() {
        let event = HotReloadEvent::Error("test error".to_string());
        let debug = format!("{:?}", event);
        assert!(debug.contains("Error"));
        assert!(debug.contains("test error"));
    }

    #[test]
    fn test_hot_reload_event_clone() {
        let event = HotReloadEvent::StylesheetChanged(PathBuf::from("style.css"));
        let cloned = event.clone();
        match cloned {
            HotReloadEvent::StylesheetChanged(path) => {
                assert_eq!(path, PathBuf::from("style.css"));
            }
            _ => panic!("Expected StylesheetChanged"),
        }
    }

    #[test]
    fn test_hot_reload_watched_paths_empty() {
        let hr = HotReload::new().unwrap();
        assert!(hr.watched_paths().is_empty());
    }

    #[test]
    fn test_hot_reload_builder_chaining() {
        let builder = HotReloadBuilder::new()
            .debounce(Duration::from_millis(150))
            .watch("src")
            .watch("tests")
            .watch("examples");

        assert_eq!(builder.config.debounce, Duration::from_millis(150));
        assert_eq!(builder.paths.len(), 3);
    }

    // Security tests for path validation
    #[test]
    fn test_hot_reload_watch_null_byte_rejected() {
        let mut hr = HotReload::new().unwrap();
        // Path with null byte should be rejected
        let result = hr.watch("test\x00file");
        assert!(result.is_err());
    }

    #[test]
    fn test_hot_reload_watch_path_traversal_rejected() {
        let mut hr = HotReload::new().unwrap();
        // Attempt to escape current directory should be rejected
        let result = hr.watch("../../../etc/passwd");
        assert!(result.is_err());
    }

    #[test]
    fn test_hot_reload_watch_absolute_path_outside_rejected() {
        let mut hr = HotReload::new().unwrap();
        // Absolute path outside project should be rejected
        let result = hr.watch("/etc/passwd");
        assert!(result.is_err());
    }

    #[test]
    fn test_hot_reload_watch_relative_path_accepted() {
        let mut hr = HotReload::new().unwrap();
        // Valid relative path within project should be accepted
        let result = hr.watch("src");
        // Only check if src exists, otherwise we expect an error from the watcher
        if std::path::Path::new("src").exists() {
            assert!(result.is_ok());
        }
    }

    #[test]
    fn test_hot_reload_watch_current_dir_accepted() {
        let mut hr = HotReload::new().unwrap();
        // Current directory should always be accepted
        let result = hr.watch(".");
        assert!(result.is_ok());
    }

    #[test]
    fn test_path_validation_error_display() {
        let err = PathValidationError::NullByte;
        assert!(err.to_string().contains("null byte"));

        let err = PathValidationError::EscapeAttempt {
            path: PathBuf::from("../../../etc/passwd"),
            canonical: PathBuf::from("/etc/passwd"),
        };
        assert!(err.to_string().contains("escapes"));
    }
}