servo-fetch-cli 0.12.2

A browser engine in a binary — fetch, render, and extract web content as Markdown, JSON, or screenshots. Powered by Servo.
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
//! CLI argument parsing.

use std::path::PathBuf;

use clap::builder::NonEmptyStringValueParser;
use clap::{ArgAction, Args, Parser, Subcommand, ValueEnum, value_parser};

#[derive(Parser, Debug)]
#[command(
    name = "servo-fetch",
    version,
    about = "A browser engine in a binary — fetch, render, and extract web content."
)]
pub(crate) struct Cli {
    #[command(subcommand)]
    pub command: Option<Command>,

    #[command(flatten)]
    pub fetch: FetchArgs,

    /// Increase log verbosity (`-v` info, `-vv` debug, `-vvv` trace)
    #[arg(short = 'v', long, action = ArgAction::Count, global = true, conflicts_with = "quiet")]
    pub verbose: u8,

    /// Suppress all logs except errors
    #[arg(short = 'q', long, global = true)]
    pub quiet: bool,

    /// Allow requests to loopback/private addresses (for testing with local servers).
    #[arg(long = "allow-private-addresses", hide = true, global = true)]
    pub allow_private_addresses: bool,
}

#[derive(Args, Debug)]
pub(crate) struct FetchArgs {
    /// URLs to fetch (one or more)
    #[arg(num_args = 1..)]
    pub urls: Vec<String>,

    /// Output format
    #[arg(long, value_enum, value_name = "FORMAT", default_value_t = Format::Markdown,
          conflicts_with_all = ["js"])]
    pub format: Format,

    /// Capture the full scrollable page instead of just the viewport (requires `--format png`).
    #[arg(long)]
    pub full_page: bool,

    /// Execute JavaScript and print the result (single URL only)
    #[arg(long, value_name = "EXPR")]
    pub js: Option<String>,

    /// Timeout in seconds for page load
    #[arg(short = 't', long, default_value_t = 30, value_parser = value_parser!(u64).range(1..), value_name = "SECS")]
    pub timeout: u64,

    /// Extra wait in ms after the `load` event, for SPAs that keep hydrating.
    #[arg(long, default_value_t = 0, value_parser = value_parser!(u64).range(0..=10_000), value_name = "MS")]
    pub settle: u64,

    /// CSS selector to extract a specific section
    #[arg(long, value_name = "CSS", value_parser = NonEmptyStringValueParser::new())]
    pub selector: Option<String>,

    /// Override the User-Agent string
    #[arg(long, value_name = "UA")]
    pub user_agent: Option<String>,

    /// Load cookies from a Netscape-format cookies.txt file.
    #[arg(long, value_name = "FILE")]
    pub cookies: Option<PathBuf>,

    /// Path to a CSS-selector schema file for structured JSON extraction
    #[arg(long, value_name = "FILE", conflicts_with_all = ["js", "selector", "format"])]
    pub schema: Option<PathBuf>,

    /// Save the rendered output to a single file. Use `-` for stdout, `./-` for a literal `-` file.
    #[arg(short = 'o', long, value_name = "FILE", conflicts_with_all = ["output_dir"])]
    pub output: Option<PathBuf>,

    /// Write each URL's output to a file in this directory (auto-created).
    #[arg(long, value_name = "DIR")]
    pub output_dir: Option<PathBuf>,

    /// Visibility-aware filtering policy.
    #[arg(long, value_name = "POLICY", value_enum, default_value_t = VisibilityArg::Moderate)]
    pub visibility: VisibilityArg,
}

/// Visibility filtering policy.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub(crate) enum VisibilityArg {
    /// Strip CSS-, ARIA-, and geometry-hidden content (default).
    Moderate,
    /// Moderate plus screen-reader-only content.
    Strict,
    /// No flag-based stripping. ARIA/HTML semantic hides still apply.
    Off,
}

impl VisibilityArg {
    pub(crate) fn to_policy(self) -> servo_fetch::VisibilityPolicy {
        match self {
            Self::Moderate => servo_fetch::VisibilityPolicy::moderate(),
            Self::Strict => servo_fetch::VisibilityPolicy::strict(),
            Self::Off => servo_fetch::VisibilityPolicy::off(),
        }
    }
}

/// Output format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub(crate) enum Format {
    /// Readability-extracted Markdown
    Markdown,
    /// Readability-extracted JSON
    Json,
    /// Raw rendered HTML (post-JS execution)
    Html,
    /// Plain text (`document.body.innerText`)
    Text,
    /// PNG screenshot of the rendered page (single URL only)
    Png,
}

/// Crawl output format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub(crate) enum CrawlFormat {
    /// Readability-extracted Markdown
    Markdown,
    /// NDJSON
    Json,
}

/// Available subcommands.
#[derive(Subcommand, Debug)]
pub(crate) enum Command {
    /// Start MCP server (stdio transport by default, or HTTP with --port)
    Mcp(McpArgs),
    /// Start HTTP API server for fetch/screenshot/crawl/map operations.
    Serve(ServeArgs),
    /// Crawl a website by following links (BFS). Respects robots.txt.
    Crawl(CrawlArgs),
    /// Discover URLs on a site via sitemaps (no rendering).
    Map(MapArgs),
    /// Probe the local /health endpoint. Exits 0 on 2xx, 1 otherwise.
    Healthcheck(HealthcheckArgs),
}

impl Command {
    pub(crate) fn needs_servo_init(&self) -> bool {
        !matches!(self, Self::Healthcheck(_))
    }
}

#[derive(Args, Debug)]
pub(crate) struct McpArgs {
    /// Port for Streamable HTTP transport. Omit for stdio.
    #[arg(long, value_name = "PORT")]
    pub port: Option<u16>,
}

#[derive(Args, Debug)]
pub(crate) struct ServeArgs {
    /// Host to bind on.
    #[arg(long, value_name = "HOST", default_value = "127.0.0.1")]
    pub host: String,

    /// Port to listen on.
    #[arg(long, value_name = "PORT", default_value_t = 3000)]
    pub port: u16,
}

#[derive(Args, Debug)]
pub(crate) struct CrawlArgs {
    /// Starting URL to crawl
    pub url: String,

    /// Maximum number of pages to crawl
    #[arg(long, default_value_t = 50, value_name = "N")]
    pub limit: usize,

    /// Maximum link depth from the seed URL
    #[arg(long, default_value_t = 3, value_name = "N")]
    pub max_depth: usize,

    /// URL path glob patterns to include (e.g. "/docs/**")
    #[arg(long, value_name = "GLOB")]
    pub include: Vec<String>,

    /// URL path glob patterns to exclude (e.g. "/docs/archive/**")
    #[arg(long, value_name = "GLOB")]
    pub exclude: Vec<String>,

    /// Output format
    #[arg(long, value_enum, value_name = "FORMAT", default_value_t = CrawlFormat::Markdown)]
    pub format: CrawlFormat,

    /// CSS selector to extract a specific section per page
    #[arg(long, value_name = "CSS", value_parser = NonEmptyStringValueParser::new())]
    pub selector: Option<String>,

    /// Timeout in seconds per page
    #[arg(short = 't', long, default_value_t = 30, value_parser = value_parser!(u64).range(1..), value_name = "SECS")]
    pub timeout: u64,

    /// Extra wait in ms after load event per page
    #[arg(long, default_value_t = 0, value_parser = value_parser!(u64).range(0..=10_000), value_name = "MS")]
    pub settle: u64,

    /// Maximum parallel page fetches. Yields in completion order when greater than 1.
    #[arg(long, default_value_t = 1, value_parser = value_parser!(u64).range(1..=64), value_name = "N")]
    pub concurrency: u64,

    /// Minimum dispatch interval in ms (0 to disable).
    #[arg(long, default_value_t = 500, value_parser = value_parser!(u64).range(0..=60_000), value_name = "MS")]
    pub delay_ms: u64,

    /// Override the User-Agent string
    #[arg(long, value_name = "UA")]
    pub user_agent: Option<String>,

    /// Load cookies from a Netscape-format cookies.txt file.
    #[arg(long, value_name = "FILE")]
    pub cookies: Option<PathBuf>,

    /// Write each crawled page's output to a file in this directory.
    #[arg(long, value_name = "DIR")]
    pub output_dir: Option<PathBuf>,
}

#[derive(Args, Debug)]
pub(crate) struct MapArgs {
    /// Starting URL to discover links from
    pub url: String,

    /// Maximum number of URLs to discover
    #[arg(long, default_value_t = 5000, value_name = "N")]
    pub limit: usize,

    /// URL path glob patterns to include (e.g. "/docs/**")
    #[arg(long, value_name = "GLOB")]
    pub include: Vec<String>,

    /// URL path glob patterns to exclude (e.g. "/docs/archive/**")
    #[arg(long, value_name = "GLOB")]
    pub exclude: Vec<String>,

    /// Output as JSON array with metadata
    #[arg(long)]
    pub json: bool,

    /// Skip HTML link fallback if no sitemap is found
    #[arg(long)]
    pub no_fallback: bool,

    /// Override the User-Agent string
    #[arg(long, value_name = "UA")]
    pub user_agent: Option<String>,

    /// Timeout in seconds per HTTP request
    #[arg(short = 't', long, default_value_t = 30, value_parser = value_parser!(u64).range(1..), value_name = "SECS")]
    pub timeout: u64,
}

#[derive(Args, Debug)]
pub(crate) struct HealthcheckArgs {
    /// Port to probe.
    #[arg(long, value_name = "PORT", default_value_t = 3000)]
    pub port: u16,
}

#[cfg(test)]
mod tests {
    use clap::error::ErrorKind;

    use super::*;
    use crate::commands::fetch::validate_args;

    fn parse(args: &[&str]) -> Result<Cli, clap::Error> {
        Cli::try_parse_from(std::iter::once("servo-fetch").chain(args.iter().copied()))
    }

    #[track_caller]
    fn error_kind(args: &[&str]) -> ErrorKind {
        parse(args).unwrap_err().kind()
    }

    #[track_caller]
    fn assert_validation_err(args: &[&str], expected: &str) {
        let err = validate_args(&parse(args).unwrap().fetch).unwrap_err().to_string();
        assert!(err.contains(expected), "expected {expected:?}, got: {err}");
    }

    #[test]
    fn format_from_str() {
        use ValueEnum;
        assert!(Format::from_str("markdown", true).is_ok());
        assert!(Format::from_str("json", true).is_ok());
        assert!(Format::from_str("html", true).is_ok());
        assert!(Format::from_str("text", true).is_ok());
        assert!(Format::from_str("png", true).is_ok());
        assert!(Format::from_str("xml", true).is_err());
    }

    #[test]
    fn crawl_format_from_str() {
        use ValueEnum;
        assert!(CrawlFormat::from_str("markdown", true).is_ok());
        assert!(CrawlFormat::from_str("json", true).is_ok());
        assert!(CrawlFormat::from_str("html", true).is_err());
    }

    #[test]
    fn settle_rejects_out_of_range() {
        assert_eq!(
            error_kind(&["--settle", "10001", "https://example.com"]),
            ErrorKind::ValueValidation,
        );
    }

    #[test]
    fn invalid_format_rejected() {
        assert_eq!(
            error_kind(&["--format", "xml", "https://example.com"]),
            ErrorKind::InvalidValue,
        );
    }

    #[test]
    fn full_page_requires_format_png() {
        assert_validation_err(
            &["--full-page", "https://example.com"],
            "--full-page requires --format png",
        );
    }

    #[test]
    fn full_page_with_format_png_is_allowed() {
        let cli = parse(&["--full-page", "--format", "png", "-o", "out.png", "https://example.com"]).unwrap();
        validate_args(&cli.fetch).unwrap();
    }

    #[test]
    fn schema_conflicts_with_selector() {
        assert_eq!(
            error_kind(&["--schema", "s.json", "--selector", "div", "https://example.com"]),
            ErrorKind::ArgumentConflict,
        );
    }

    #[test]
    fn schema_conflicts_with_format() {
        assert_eq!(
            error_kind(&["--schema", "s.json", "--format", "json", "https://example.com"]),
            ErrorKind::ArgumentConflict,
        );
    }

    #[test]
    fn format_png_conflicts_with_js() {
        assert_eq!(
            error_kind(&["--format", "png", "--js", "document.title", "https://example.com"]),
            ErrorKind::ArgumentConflict,
        );
    }

    #[test]
    fn format_png_conflicts_with_selector() {
        assert_validation_err(
            &["--format", "png", "--selector", "article", "https://example.com"],
            "--selector cannot be used with --format png",
        );
    }

    #[test]
    fn format_png_conflicts_with_schema() {
        assert_eq!(
            error_kind(&["--format", "png", "--schema", "s.json", "https://example.com"]),
            ErrorKind::ArgumentConflict,
        );
    }

    #[test]
    fn format_png_with_multi_urls_errors() {
        assert_validation_err(
            &["--format", "png", "https://example.com", "https://example.org"],
            "--format png only supports a single URL",
        );
    }

    #[test]
    fn format_png_conflicts_with_output_dir() {
        assert_validation_err(
            &["--format", "png", "--output-dir", "out", "https://example.com"],
            "--format png cannot be used with --output-dir",
        );
    }

    #[test]
    fn format_png_with_output_file_is_allowed() {
        let cli = parse(&["--format", "png", "-o", "out.png", "https://example.com"]).unwrap();
        validate_args(&cli.fetch).unwrap();
    }

    #[test]
    fn format_png_with_dash_output_is_allowed() {
        let cli = parse(&["--format", "png", "-o", "-", "https://example.com"]).unwrap();
        validate_args(&cli.fetch).unwrap();
    }

    #[test]
    fn output_conflicts_with_output_dir() {
        assert_eq!(
            error_kind(&["-o", "out.md", "--output-dir", "out", "https://example.com"]),
            ErrorKind::ArgumentConflict,
        );
    }

    #[test]
    fn output_with_js_is_allowed() {
        parse(&["-o", "out.txt", "--js", "document.title", "https://example.com"]).unwrap();
    }

    #[test]
    fn format_html_with_selector_errors() {
        assert_validation_err(
            &["--format", "html", "--selector", "article", "https://example.com"],
            "--selector cannot be used with --format html or text",
        );
    }

    #[test]
    fn format_html_with_multi_urls_errors() {
        assert_validation_err(
            &["--format", "html", "https://example.com", "https://example.org"],
            "cannot be used with multiple URLs",
        );
    }

    #[test]
    fn output_with_multi_urls_errors() {
        assert_validation_err(
            &["-o", "out.md", "https://example.com", "https://example.org"],
            "only valid with a single URL",
        );
    }
}