webshot 0.3.0

A command-line tool for automated website screenshots and web scraping
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
use crate::error::{Result, WebshotError};
use crate::screenshot::ScrollMode;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// Validate that a navigation target is a syntactically valid HTTP(S) URL.
///
/// This is a scheme allowlist, not a full network safety check. CLI callers
/// intentionally validate before browser startup while browser APIs validate
/// again at the navigation boundary for defense in depth.
pub fn validate_navigation_url(url: &str, context: impl AsRef<str>) -> Result<()> {
    let parsed_url = url::Url::parse(url).map_err(|error| {
        WebshotError::config(format!("Invalid URL in {}: {}", context.as_ref(), error))
    })?;

    match parsed_url.scheme() {
        "http" | "https" => Ok(()),
        scheme => Err(WebshotError::config(format!(
            "Unsupported URL scheme in {}: {}. Supported schemes: http, https",
            context.as_ref(),
            scheme
        ))),
    }
}

/// Batch processing configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Config {
    /// List of screenshots to take
    pub screenshots: Vec<ScreenshotConfig>,
    /// Global settings that apply to all screenshots
    #[serde(default)]
    pub defaults: DefaultConfig,
}

/// Individual screenshot configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ScreenshotConfig {
    /// Target URL
    pub url: String,
    /// Output file path
    pub output: PathBuf,
    /// Viewport width
    #[serde(default = "default_width")]
    pub width: u32,
    /// Viewport height
    #[serde(default = "default_height")]
    pub height: u32,
    /// CSS selector for element screenshot
    pub selector: Option<String>,
    /// JavaScript to execute before screenshot
    pub javascript: Option<String>,
    /// Element to wait for before taking screenshot
    pub wait_for: Option<String>,
    /// Timeout in seconds
    #[serde(default = "default_timeout")]
    pub timeout: u64,
    /// Enable retina/high-DPI mode
    #[serde(default)]
    pub retina: bool,
    /// JPEG quality (1-100)
    pub quality: Option<u8>,
    /// Wait time before taking screenshot
    #[serde(default)]
    pub wait: u64,
    /// Custom user agent
    pub user_agent: Option<String>,
    /// Output format override
    pub format: Option<String>,
    /// Custom headers
    #[serde(default)]
    pub headers: std::collections::HashMap<String, String>,
    /// Cookies to set
    #[serde(default)]
    pub cookies: Vec<CookieConfig>,
    /// Authentication credentials
    pub auth: Option<AuthConfig>,
    /// Comparison configuration for visual regression testing
    pub comparison: Option<ComparisonConfig>,
    /// Scrolling screenshot mode
    #[serde(default)]
    pub scroll_mode: ScrollMode,
    /// Maximum height for full page screenshots (safety limit)
    pub max_height: Option<u32>,
    /// Scroll delay between captures (milliseconds)
    #[serde(default = "default_scroll_delay")]
    pub scroll_delay: u64,
}

/// Cookie configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CookieConfig {
    pub name: String,
    pub value: String,
    pub domain: Option<String>,
    pub path: Option<String>,
    pub secure: Option<bool>,
    pub http_only: Option<bool>,
}

/// Comparison configuration for visual regression testing
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ComparisonConfig {
    /// Base image path for comparison
    pub baseline_path: Option<String>,
    /// Comparison algorithm to use
    #[serde(default = "default_algorithm")]
    pub algorithm: String,
    /// Threshold for considering images similar (0.0-1.0)
    #[serde(default = "default_threshold")]
    pub threshold: f64,
    /// Generate difference image
    #[serde(default)]
    pub generate_diff: bool,
    /// Path for difference image output
    pub diff_output_path: Option<String>,
    /// Ignore anti-aliasing differences
    #[serde(default)]
    pub ignore_antialiasing: bool,
    /// Color for highlighting differences (RGB format: "255,0,0")
    #[serde(default = "default_diff_color")]
    pub diff_color: String,
}

/// Authentication configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthConfig {
    pub username: String,
    pub password: String,
}

/// Default configuration applied to all screenshots
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DefaultConfig {
    /// Default viewport width
    #[serde(default = "default_width")]
    pub width: u32,
    /// Default viewport height
    #[serde(default = "default_height")]
    pub height: u32,
    /// Default timeout
    #[serde(default = "default_timeout")]
    pub timeout: u64,
    /// Default user agent
    pub user_agent: Option<String>,
    /// Default output directory
    pub output_dir: Option<PathBuf>,
    /// Default wait time
    #[serde(default)]
    pub wait: u64,
    /// Default retina mode
    #[serde(default)]
    pub retina: bool,
    /// Default JPEG quality
    pub quality: Option<u8>,
    /// Global headers
    #[serde(default)]
    pub headers: std::collections::HashMap<String, String>,
    /// Global cookies
    #[serde(default)]
    pub cookies: Vec<CookieConfig>,
    /// Default scrolling screenshot mode
    #[serde(default)]
    pub scroll_mode: ScrollMode,
    /// Default maximum height for full page screenshots
    pub max_height: Option<u32>,
    /// Default scroll delay between captures (milliseconds)
    #[serde(default = "default_scroll_delay")]
    pub scroll_delay: u64,
}

impl Default for DefaultConfig {
    fn default() -> Self {
        Self {
            width: default_width(),
            height: default_height(),
            timeout: default_timeout(),
            user_agent: None,
            output_dir: None,
            wait: 0,
            retina: false,
            quality: None,
            headers: std::collections::HashMap::new(),
            cookies: Vec::new(),
            scroll_mode: ScrollMode::default(),
            max_height: Some(30000),
            scroll_delay: default_scroll_delay(),
        }
    }
}

impl Config {
    /// Load configuration from a YAML file
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let content = std::fs::read_to_string(&path)?;
        let mut config: Config = serde_yaml::from_str(&content)?;

        // Apply defaults to screenshots that don't have values set
        for screenshot in &mut config.screenshots {
            if screenshot.width == default_width() && config.defaults.width != default_width() {
                screenshot.width = config.defaults.width;
            }
            if screenshot.height == default_height() && config.defaults.height != default_height() {
                screenshot.height = config.defaults.height;
            }
            if screenshot.timeout == default_timeout()
                && config.defaults.timeout != default_timeout()
            {
                screenshot.timeout = config.defaults.timeout;
            }
            if screenshot.user_agent.is_none() && config.defaults.user_agent.is_some() {
                screenshot.user_agent = config.defaults.user_agent.clone();
            }
            if screenshot.quality.is_none() && config.defaults.quality.is_some() {
                screenshot.quality = config.defaults.quality;
            }

            // Merge headers
            for (key, value) in &config.defaults.headers {
                screenshot
                    .headers
                    .entry(key.clone())
                    .or_insert_with(|| value.clone());
            }

            // Merge cookies
            if screenshot.cookies.is_empty() && !config.defaults.cookies.is_empty() {
                screenshot.cookies = config.defaults.cookies.clone();
            }

            // Merge scrolling options
            if screenshot.scroll_mode == ScrollMode::default()
                && config.defaults.scroll_mode != ScrollMode::default()
            {
                screenshot.scroll_mode = config.defaults.scroll_mode;
            }
            if screenshot.max_height.is_none() && config.defaults.max_height.is_some() {
                screenshot.max_height = config.defaults.max_height;
            }
            if screenshot.scroll_delay == default_scroll_delay()
                && config.defaults.scroll_delay != default_scroll_delay()
            {
                screenshot.scroll_delay = config.defaults.scroll_delay;
            }

            // Resolve output path relative to output_dir if set
            if let Some(output_dir) = &config.defaults.output_dir {
                if screenshot.output.is_relative() {
                    screenshot.output = output_dir.join(&screenshot.output);
                }
            }
        }

        config.validate()?;

        Ok(config)
    }

    /// Save configuration to a YAML file
    pub fn to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let content = serde_yaml::to_string(self)?;
        std::fs::write(path, content)?;
        Ok(())
    }

    /// Validate the configuration
    pub fn validate(&self) -> Result<()> {
        if self.screenshots.is_empty() {
            return Err(WebshotError::config(
                "No screenshots defined in configuration",
            ));
        }

        for (i, screenshot) in self.screenshots.iter().enumerate() {
            validate_navigation_url(&screenshot.url, format!("screenshot {}", i))?;

            // Validate viewport dimensions
            if screenshot.width == 0 || screenshot.height == 0 {
                return Err(WebshotError::InvalidViewport {
                    width: screenshot.width,
                    height: screenshot.height,
                });
            }

            // Validate JPEG quality
            if let Some(quality) = screenshot.quality {
                if !(1..=100).contains(&quality) {
                    return Err(WebshotError::config(format!(
                        "JPEG quality must be between 1-100, got: {}",
                        quality
                    )));
                }
            }

            // Validate timeout
            if screenshot.timeout == 0 {
                return Err(WebshotError::config(format!(
                    "Timeout must be greater than 0, got: {}",
                    screenshot.timeout
                )));
            }

            // FullElement scrolling requires a selector to target
            if screenshot.scroll_mode == ScrollMode::FullElement && screenshot.selector.is_none() {
                return Err(WebshotError::config(format!(
                    "screenshot {}: FullElement scroll mode requires a selector",
                    i
                )));
            }

            let extension = screenshot
                .output
                .extension()
                .and_then(|ext| ext.to_str())
                .map(|ext| ext.to_lowercase());

            match extension.as_deref() {
                Some("png") | Some("jpg") | Some("jpeg") | Some("webp") | Some("pdf") => {}
                Some(ext) => {
                    return Err(WebshotError::UnsupportedFormat {
                        format: ext.to_string(),
                    });
                }
                None => {
                    return Err(WebshotError::config(format!(
                        "Output file must have a supported extension: {}. Supported extensions: png, jpg, jpeg, webp, pdf",
                        screenshot.output.display()
                    )));
                }
            }
        }

        Ok(())
    }
}

fn default_width() -> u32 {
    1280
}

fn default_height() -> u32 {
    800
}

fn default_timeout() -> u64 {
    30
}

fn default_algorithm() -> String {
    "pixel-diff".to_string()
}

fn default_threshold() -> f64 {
    0.1
}

fn default_diff_color() -> String {
    "255,0,0".to_string()
}

fn default_scroll_delay() -> u64 {
    100
}

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

    fn valid_screenshot_config() -> ScreenshotConfig {
        ScreenshotConfig {
            url: "https://example.com".to_string(),
            output: PathBuf::from("test.png"),
            width: 1920,
            height: 1080,
            selector: None,
            javascript: None,
            wait_for: None,
            timeout: 30,
            retina: false,
            quality: None,
            wait: 0,
            user_agent: None,
            format: None,
            headers: std::collections::HashMap::new(),
            cookies: Vec::new(),
            auth: None,
            comparison: None,
            scroll_mode: ScrollMode::default(),
            max_height: None,
            scroll_delay: default_scroll_delay(),
        }
    }

    #[test]
    fn test_config_serialization() {
        let config = Config {
            screenshots: vec![ScreenshotConfig {
                url: "https://example.com".to_string(),
                output: PathBuf::from("test.png"),
                width: 1920,
                height: 1080,
                selector: Some(".header".to_string()),
                ..valid_screenshot_config()
            }],
            defaults: DefaultConfig::default(),
        };

        let yaml = serde_yaml::to_string(&config).unwrap();
        let deserialized: Config = serde_yaml::from_str(&yaml).unwrap();

        assert_eq!(config.screenshots.len(), deserialized.screenshots.len());
        assert_eq!(config.screenshots[0].url, deserialized.screenshots[0].url);
    }

    #[test]
    fn test_config_validation() {
        let mut config = Config {
            screenshots: vec![valid_screenshot_config()],
            defaults: DefaultConfig::default(),
        };

        assert!(config.validate().is_ok());

        // Test invalid URL
        config.screenshots[0].url = "not-a-url".to_string();
        assert!(config.validate().is_err());

        // Test invalid dimensions
        config.screenshots[0].url = "https://example.com".to_string();
        config.screenshots[0].width = 0;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_config_validation_rejects_non_web_url_schemes() {
        for url in [
            "file:///etc/passwd",
            "data:text/html,<h1>Test</h1>",
            "javascript:alert(1)",
            "chrome://settings",
            "ftp://example.com/file.png",
        ] {
            let mut screenshot = valid_screenshot_config();
            screenshot.url = url.to_string();

            let config = Config {
                screenshots: vec![screenshot],
                defaults: DefaultConfig::default(),
            };

            let error = config.validate().unwrap_err();

            assert!(error.to_string().contains("Unsupported URL scheme"));
        }
    }

    #[test]
    fn test_config_validation_accepts_case_insensitive_web_url_schemes() {
        let mut screenshot = valid_screenshot_config();
        screenshot.url = "HTTPS://example.com".to_string();

        let config = Config {
            screenshots: vec![screenshot],
            defaults: DefaultConfig::default(),
        };

        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_validation_accepts_webp_output() {
        let mut screenshot = valid_screenshot_config();
        screenshot.output = PathBuf::from("test.webp");

        let config = Config {
            screenshots: vec![screenshot],
            defaults: DefaultConfig::default(),
        };

        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_validation_rejects_unsupported_output_even_with_format_override() {
        let mut screenshot = valid_screenshot_config();
        screenshot.output = PathBuf::from("test.gif");
        screenshot.format = Some("png".to_string());

        let config = Config {
            screenshots: vec![screenshot],
            defaults: DefaultConfig::default(),
        };

        assert!(config.validate().is_err());
    }

    #[test]
    fn test_from_file_rejects_invalid_config_before_processing() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.yaml");
        std::fs::write(
            &config_path,
            r#"
screenshots:
  - url: "not-a-url"
    output: "test.png"
"#,
        )
        .unwrap();

        let error = Config::from_file(&config_path).unwrap_err();

        assert!(error.to_string().contains("Invalid URL in screenshot 0"));
    }

    #[test]
    fn test_from_file_applies_output_dir_before_validation() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.yaml");
        std::fs::write(
            &config_path,
            r#"
defaults:
  output_dir: "screenshots"
screenshots:
  - url: "https://example.com"
    output: "test.png"
"#,
        )
        .unwrap();

        let config = Config::from_file(&config_path).unwrap();

        assert_eq!(
            config.screenshots[0].output,
            PathBuf::from("screenshots").join("test.png")
        );
    }
}