webspec-index 0.7.0

Query WHATWG/W3C/TC39 web specifications from the command line
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
use std::process::ExitCode;

use clap::{Parser, Subcommand, ValueEnum};
use moz_cli_version_check::VersionChecker;

use webspec_index::{format, model};

#[derive(Parser, Debug)]
#[command(
    name = "webspec-index",
    version,
    about = "Query WHATWG/W3C/TC39/IETF web specifications",
    long_about = "A command-line tool for querying web specification sections, algorithms, \
        and cross-references.\n\n\
        Indexes specs from WHATWG (HTML, DOM, URL, Fetch, …), W3C (CSS, Geometry, …), \
        TC39 (ECMAScript), and IETF (RFCs and Internet Drafts). Specs are fetched and \
        cached locally on first use.\n\n\
        IETF specs are resolved dynamically — use the RFC number or draft name:\n  \
        webspec-index query RFC9110#section-5\n  \
        webspec-index query draft-touch-sne#section-1\n  \
        webspec-index query draft-touch-sne-02#section-1   (pinned version)\n\n\
        Examples:\n  \
        webspec-index query HTML#navigate\n  \
        webspec-index search \"tree order\" --spec DOM\n  \
        webspec-index anchors \"*-tree\" --spec DOM\n  \
        webspec-index refs HTML#navigate --direction incoming\n  \
        webspec-index list DOM\n  \
        webspec-index exists HTML#navigate"
)]
struct Cli {
    #[arg(
        long,
        global = true,
        default_value = "json",
        help = "Output format",
        long_help = "Output format.\n  json     — JSON (default, best for programmatic use)\n  markdown — Human-readable markdown"
    )]
    format: OutputFormat,

    #[command(subcommand)]
    command: Command,
}

#[derive(ValueEnum, Clone, Debug)]
enum OutputFormat {
    Json,
    Markdown,
}

#[derive(ValueEnum, Clone, Debug)]
enum GraphOutputFormat {
    Json,
    Markdown,
    Mermaid,
    Dot,
}

#[derive(ValueEnum, Clone, Debug)]
enum AnalyzeFormat {
    Json,
    Searchfox,
}

#[derive(Subcommand, Debug)]
enum Command {
    /// Query a specific section in a specification
    ///
    /// Returns complete section information including content, navigation
    /// (parent/prev/next/children), and cross-references.
    #[command(long_about = "Query a specific section in a specification.\n\n\
        Returns complete section information including content, navigation\n\
        (parent/prev/next/children), and cross-references.\n\n\
        The argument can be SPEC#anchor or a full spec URL:\n  \
        webspec-index query HTML#navigate\n  \
        webspec-index query \"https://html.spec.whatwg.org/#navigate\"")]
    Query {
        /// Section identifier: SPEC#anchor or full URL
        spec_anchor: String,
    },

    /// Full-text search across specifications
    #[command(long_about = "Full-text search across indexed specifications.\n\n\
        Uses SQLite FTS5 for fast text search. Results include snippets\n\
        showing matching context.\n\n\
        Examples:\n  \
        webspec-index search \"tree order\"\n  \
        webspec-index search \"navigate\" --spec HTML --limit 5")]
    Search {
        /// Search query string
        query: String,

        #[arg(long, short, help = "Limit search to a specific spec (e.g. HTML, DOM)")]
        spec: Option<String>,

        #[arg(long, short, default_value = "20", help = "Maximum number of results")]
        limit: u32,
    },

    /// Check if a section exists (exit code 0 = found, 1 = not found)
    Exists {
        /// Section identifier: SPEC#anchor or full URL
        spec_anchor: String,
    },

    /// Find anchors matching a glob pattern
    #[command(long_about = "Find anchors matching a glob pattern.\n\n\
        Uses * as wildcard. Searches across all indexed specs unless\n\
        --spec is given.\n\n\
        Examples:\n  \
        webspec-index anchors \"*-tree\" --spec DOM\n  \
        webspec-index anchors \"concept-*\"")]
    Anchors {
        /// Glob pattern (e.g. "*-tree", "concept-*")
        pattern: String,

        #[arg(long, short, help = "Limit to a specific spec")]
        spec: Option<String>,

        #[arg(long, short, default_value = "50", help = "Maximum number of results")]
        limit: u32,
    },

    /// List all headings in a specification
    List {
        /// Spec name (e.g. HTML, DOM, CSS-GRID)
        spec: String,
    },

    /// Get cross-references for a section
    #[command(long_about = "Get cross-references for a section.\n\n\
        Shows which other spec sections reference this one (incoming)\n\
        and which sections this one references (outgoing).\n\n\
        Target can be SPEC#anchor (exact), full URL, or shorthand such as\n\
        Interface.member (heuristic match against indexed sections).\n\n\
        Examples:\n  \
        webspec-index refs HTML#navigate\n  \
        webspec-index refs HTML#navigate --direction incoming\n  \
        webspec-index refs Window.navigation --limit 5")]
    Refs {
        /// Target: SPEC#anchor, full URL, or shorthand (e.g. Window.navigation)
        target: String,

        #[arg(
            long,
            short,
            default_value = "both",
            help = "Reference direction: incoming, outgoing, or both"
        )]
        direction: String,

        #[arg(long, short, default_value = "10", help = "Maximum number of matches")]
        limit: u32,
    },

    /// Build a cross-reference graph rooted at a section
    #[command(
        long_about = "Build a cross-reference graph rooted at SPEC#anchor.\n\n\
        Traverses indexed references up to --max-depth and returns a graph.\n\
        Output formats: json, markdown, mermaid, dot.\n\n\
        Examples:\n  \
        webspec-index graph HTML#navigate --direction outgoing --max-depth 2\n  \
        webspec-index graph HTML#navigate --graph-format mermaid"
    )]
    Graph {
        /// Root section identifier: SPEC#anchor or full URL
        spec_anchor: String,

        #[arg(
            long,
            short,
            default_value = "outgoing",
            help = "Traversal direction: incoming, outgoing, or both"
        )]
        direction: String,

        #[arg(long, default_value = "2", help = "Maximum traversal depth")]
        max_depth: usize,

        #[arg(long, default_value = "150", help = "Maximum number of graph nodes")]
        max_nodes: usize,

        #[arg(
            long = "include",
            help = "Include node id patterns (wildcard by default, or re:<regex>)",
            action = clap::ArgAction::Append
        )]
        include: Vec<String>,

        #[arg(
            long = "exclude",
            help = "Exclude node id patterns (wildcard by default, or re:<regex>)",
            action = clap::ArgAction::Append
        )]
        exclude: Vec<String>,

        #[arg(long, help = "Keep only nodes/edges within the root spec")]
        same_spec_only: bool,

        #[arg(
            long,
            default_value = "json",
            help = "Graph output format: json, markdown, mermaid, dot"
        )]
        graph_format: GraphOutputFormat,
    },

    /// Query dedicated WebIDL definitions
    #[command(long_about = "Query structured WebIDL definitions.\n\n\
        Supports exact anchors and canonical names:\n  \
        webspec-index idl HTML#dom-window-navigation\n  \
        webspec-index idl Window.navigation\n  \
        webspec-index idl Window.open()\n\n\
        Use --spec to narrow to one specification.")]
    Idl {
        /// Query string: SPEC#anchor, full URL, or canonical IDL name
        query: String,

        #[arg(long, short, help = "Limit lookup to a specific spec (e.g. HTML, DOM)")]
        spec: Option<String>,

        #[arg(long, short, default_value = "20", help = "Maximum number of matches")]
        limit: u32,
    },

    /// Update specifications to latest versions
    #[command(long_about = "Update indexed specifications to latest versions.\n\n\
        Without --spec, updates all currently indexed specs. Uses a 24h\n\
        freshness window unless --force is given.\n\n\
        Examples:\n  \
        webspec-index update\n  \
        webspec-index update --spec HTML\n  \
        webspec-index update --force")]
    Update {
        #[arg(long, short, help = "Update only this spec")]
        spec: Option<String>,

        #[arg(long, short, help = "Force update even if recently checked")]
        force: bool,
    },

    /// Clear the local database (remove all indexed data)
    ClearDb {
        #[arg(long, short, help = "Skip confirmation prompt")]
        yes: bool,
    },

    /// Analyze source files for spec references and step comment validation
    #[command(
        long_about = "Analyze source files for spec URL references and step comments.\n\n\
        Scans files for spec URLs (e.g. https://html.spec.whatwg.org/#navigate),\n\
        validates step comments against spec algorithms using fuzzy matching,\n\
        and reports coverage metrics.\n\n\
        Uses indentation-based scoping to correctly associate step comments\n\
        with their enclosing spec algorithm.\n\n\
        Examples:\n  \
        webspec-index analyze src/dom/base/Element.cpp\n  \
        webspec-index analyze src/ --recursive\n  \
        webspec-index analyze src/foo.cpp --threshold 0.9"
    )]
    Analyze {
        /// File or directory to analyze
        path: std::path::PathBuf,

        #[arg(long, short, help = "Recursively analyze directories")]
        recursive: bool,

        #[arg(
            long,
            short,
            default_value = "0.85",
            help = "Fuzzy match threshold (0.0-1.0)"
        )]
        threshold: f64,

        #[arg(
            long,
            default_value = "json",
            help = "Output format: json (human-readable) or searchfox (analysis records)"
        )]
        output_format: AnalyzeFormat,

        #[arg(
            long,
            help = "Write searchfox records to per-file analysis files in this directory \
                    (appending to existing files). Mirrors source tree structure. \
                    Requires --output-format=searchfox"
        )]
        output_dir: Option<std::path::PathBuf>,

        #[arg(
            long,
            help = "Strip this prefix from file paths when computing output paths \
                    (used with --output-dir to map source paths to analysis paths)"
        )]
        strip_prefix: Option<std::path::PathBuf>,
    },

    /// List indexed/discovered spec names and base URLs
    Specs,

    /// Start the Language Server Protocol server (stdio)
    Lsp,

    /// Update the local W3C spec list from csswg-drafts and w3c/groups
    ///
    /// Clones (or updates) csswg-drafts and w3c/groups, then regenerates
    /// data/w3c_specs.json. After running this command, rebuild to apply changes.
    #[command(long_about = "Update the local W3C spec list.\n\n\
        Clones (or updates) the csswg-drafts and w3c/groups repositories,\n\
        then regenerates data/w3c_specs.json with all discovered specs.\n\
        Rebuild after running this to apply the new spec list.\n\n\
        Examples:\n  \
        webspec-index update-spec-list\n  \
        webspec-index update-spec-list --csswg-dir /path/to/csswg-drafts")]
    UpdateSpecList {
        #[arg(
            long,
            default_value = "csswg-drafts",
            help = "Path to csswg-drafts clone"
        )]
        csswg_dir: std::path::PathBuf,

        #[arg(long, default_value = "groups", help = "Path to w3c/groups clone")]
        groups_dir: std::path::PathBuf,

        #[arg(
            long,
            default_value = "data/w3c_specs.json",
            help = "Output path for the spec list"
        )]
        output: std::path::PathBuf,
    },
}

fn is_llm_environment() -> bool {
    let has = |k| std::env::var(k).is_ok_and(|v| !v.is_empty());
    has("CLAUDECODE") || has("CODEX_SANDBOX") || has("GEMINI_CLI") || has("OPENCODE")
}

fn print_llm_help() {
    print!(
        r#"webspec-index: Query WHATWG/W3C/TC39 web specifications
query <SPEC#anchor|URL> [--format json|markdown]
search <Q> [-s SPEC] [-l N(20)] [--format json|markdown]
exists <SPEC#anchor|URL> exit:0=found,1=not
anchors <GLOB> [-s SPEC] [-l N(50)]
list <SPEC>
refs <SPEC#anchor|TARGET> [-d incoming|outgoing|both(default)] [-l N(10)]
update [-s SPEC] [-f force]
clear-db [-y skip confirm]
specs — list indexed/discovered spec names+URLs
lsp — start LSP server on stdio
graph <SPEC#anchor|URL> [-d incoming|outgoing|both(default outgoing)] [--max-depth N(2)] [--max-nodes N(150)] [--include PATTERN --exclude PATTERN --same-spec-only] [--graph-format json|markdown|mermaid|dot]
idl <Q|SPEC#anchor|URL> [-s SPEC] [-l N(20)] [--format json|markdown]
SPEC#anchor examples: HTML#navigate, DOM#concept-tree, CSS-GRID#grid-container
Full URL also works: https://html.spec.whatwg.org/#navigate
Ex: query HTML#navigate|search "tree order" -s DOM|anchors "*-tree" -s DOM
Ex: refs HTML#navigate -d incoming|refs Window.navigation|graph HTML#navigate --graph-format mermaid
Ex: idl Window.navigation|idl Window.open()|idl HTML#dom-window-navigation
"#
    );
}

#[tokio::main]
async fn main() -> ExitCode {
    // Handle SIGPIPE gracefully (prevents broken pipe panics when piped through head/less)
    #[cfg(unix)]
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }

    let version_checker = VersionChecker::new("webspec-index", env!("CARGO_PKG_VERSION"));
    version_checker.check_async();

    // Intercept --version for sync version warning
    if std::env::args().any(|arg| arg == "--version" || arg == "-V") {
        println!("webspec-index {}", env!("CARGO_PKG_VERSION"));
        version_checker.print_warning_sync();
        return ExitCode::SUCCESS;
    }

    // LLM-friendly condensed help
    if is_llm_environment() && std::env::args().any(|arg| arg == "--help" || arg == "-h") {
        print_llm_help();
        version_checker.print_warning();
        return ExitCode::SUCCESS;
    }

    let cli = Cli::parse();

    let result = run(cli).await;

    version_checker.print_warning();

    match result {
        Ok(code) => code,
        Err(e) => {
            eprintln!("Error: {e:#}");
            ExitCode::FAILURE
        }
    }
}

async fn run(cli: Cli) -> anyhow::Result<ExitCode> {
    match cli.command {
        Command::Query { spec_anchor } => {
            let result = webspec_index::query_section(&spec_anchor).await?;
            print_output(&cli.format, &result, format::query);
            Ok(ExitCode::SUCCESS)
        }

        Command::Search { query, spec, limit } => {
            let result = webspec_index::search_sections(&query, spec.as_deref(), limit)?;
            print_output(&cli.format, &result, format::search);
            Ok(ExitCode::SUCCESS)
        }

        Command::Exists { spec_anchor } => {
            let result = webspec_index::check_exists(&spec_anchor).await?;
            let found = result.exists;
            print_output(&cli.format, &result, format::exists);
            Ok(if found {
                ExitCode::SUCCESS
            } else {
                ExitCode::from(1)
            })
        }

        Command::Anchors {
            pattern,
            spec,
            limit,
        } => {
            let result = webspec_index::find_anchors(&pattern, spec.as_deref(), limit)?;
            print_output(&cli.format, &result, format::anchors);
            Ok(ExitCode::SUCCESS)
        }

        Command::List { spec } => {
            let result = webspec_index::list_headings(&spec).await?;
            match cli.format {
                OutputFormat::Json => {
                    println!("{}", serde_json::to_string_pretty(&result)?);
                }
                OutputFormat::Markdown => {
                    print!("{}", format::list(&result));
                }
            }
            Ok(ExitCode::SUCCESS)
        }

        Command::Refs {
            target,
            direction,
            limit,
        } => {
            let result = webspec_index::find_references(&target, &direction, limit).await?;
            print_output(&cli.format, &result, format::refs);
            Ok(ExitCode::SUCCESS)
        }

        Command::Graph {
            spec_anchor,
            direction,
            max_depth,
            max_nodes,
            include,
            exclude,
            same_spec_only,
            graph_format,
        } => {
            let result = webspec_index::graph_section(
                &spec_anchor,
                &direction,
                max_depth,
                max_nodes,
                &include,
                &exclude,
                same_spec_only,
            )
            .await?;
            match graph_format {
                GraphOutputFormat::Json => {
                    println!("{}", serde_json::to_string_pretty(&result)?);
                }
                GraphOutputFormat::Markdown => {
                    print!("{}", format::graph(&result));
                }
                GraphOutputFormat::Mermaid => {
                    print!("{}", format::graph_mermaid(&result));
                }
                GraphOutputFormat::Dot => {
                    print!("{}", format::graph_dot(&result));
                }
            }
            Ok(ExitCode::SUCCESS)
        }

        Command::Idl { query, spec, limit } => {
            let result = webspec_index::query_idl(&query, spec.as_deref(), limit).await?;
            print_output(&cli.format, &result, format::idl);
            Ok(ExitCode::SUCCESS)
        }

        Command::Update { spec, force } => {
            let results = webspec_index::update_specs(spec.as_deref(), force).await?;
            let output: Vec<model::UpdateEntry> = results
                .into_iter()
                .map(|(name, snapshot_id)| model::UpdateEntry {
                    spec: name,
                    updated: snapshot_id.is_some(),
                })
                .collect();
            println!("{}", serde_json::to_string_pretty(&output)?);
            Ok(ExitCode::SUCCESS)
        }

        Command::ClearDb { yes } => {
            if !yes {
                eprint!("This will delete all indexed data. Continue? [y/N] ");
                let mut input = String::new();
                std::io::stdin().read_line(&mut input)?;
                if !input.trim().eq_ignore_ascii_case("y") {
                    eprintln!("Aborted.");
                    return Ok(ExitCode::SUCCESS);
                }
            }
            let path = webspec_index::clear_database()?;
            eprintln!("Deleted {path}");
            Ok(ExitCode::SUCCESS)
        }

        Command::Analyze {
            path,
            recursive,
            threshold,
            output_format,
            output_dir,
            strip_prefix,
        } => {
            run_analyze(
                &path,
                recursive,
                threshold,
                &output_format,
                output_dir.as_deref(),
                strip_prefix.as_deref(),
            )
            .await?;
            Ok(ExitCode::SUCCESS)
        }

        Command::Specs => {
            let urls = webspec_index::spec_urls();
            println!("{}", serde_json::to_string_pretty(&urls)?);
            Ok(ExitCode::SUCCESS)
        }

        Command::Lsp => {
            webspec_index::lsp::serve_stdio().await;
            Ok(ExitCode::SUCCESS)
        }

        Command::UpdateSpecList {
            csswg_dir,
            groups_dir,
            output,
        } => {
            let (csswg_count, standalone_count, entries) =
                webspec_index::spec_list::update(&csswg_dir, &groups_dir, &output)?;
            let conn = webspec_index::db::open_or_create_db()?;
            for e in &entries {
                webspec_index::db::write::seed_spec(&conn, &e.name, &e.base_url, &e.provider)?;
            }
            eprintln!(
                "wrote {} specs to {} ({} CSSWG + {} standalone); seeded DB",
                csswg_count + standalone_count,
                output.display(),
                csswg_count,
                standalone_count
            );
            Ok(ExitCode::SUCCESS)
        }
    }
}

/// DB-backed spec resolver for the analyze command.
///
/// Uses `DashMap` for thread-safe caching (safe for future parallelization).
struct DbResolver {
    cache: dashmap::DashMap<String, Option<String>>,
}

impl DbResolver {
    fn new() -> Self {
        DbResolver {
            cache: dashmap::DashMap::new(),
        }
    }

    /// Return all successfully resolved sections as a map of
    /// "SPEC_<spec>_<anchor>" -> content (the same symbol names used
    /// in searchfox analysis records).
    fn resolved_sections(&self) -> std::collections::HashMap<String, String> {
        self.cache
            .iter()
            .filter_map(|entry| {
                let content = entry.value().as_ref()?;
                let (spec, anchor) = entry.key().split_once('#')?;
                let sym = format!("SPEC_{spec}_{anchor}");
                Some((sym, content.clone()))
            })
            .collect()
    }
}

impl webspec_index::analyze::file::SpecResolver for DbResolver {
    fn resolve(&self, spec: &str, anchor: &str) -> Option<String> {
        let key = format!("{spec}#{anchor}");
        if let Some(cached) = self.cache.get(&key) {
            return cached.clone();
        }
        let result = tokio::task::block_in_place(|| {
            tokio::runtime::Handle::current()
                .block_on(webspec_index::query_section(&key))
                .ok()
        });
        let content = result.and_then(|r| r.content).filter(|c| !c.is_empty());
        self.cache.insert(key, content.clone());
        content
    }
}

/// Source file extensions to scan when analyzing directories.
const SOURCE_EXTENSIONS: &[&str] = &[
    "cpp", "cc", "cxx", "c", "h", "hpp", "hxx", "rs", "js", "mjs", "jsm", "py", "java",
];

fn is_source_file(path: &std::path::Path) -> bool {
    path.extension()
        .and_then(|e| e.to_str())
        .is_some_and(|ext| SOURCE_EXTENSIONS.contains(&ext))
}

/// Collect source files to analyze.
fn collect_files(
    path: &std::path::Path,
    recursive: bool,
) -> anyhow::Result<Vec<std::path::PathBuf>> {
    if path.is_file() {
        return Ok(vec![path.to_path_buf()]);
    }
    if !path.is_dir() {
        anyhow::bail!("{} is not a file or directory", path.display());
    }
    let mut files = Vec::new();
    let mut dirs = vec![path.to_path_buf()];
    while let Some(dir) = dirs.pop() {
        for entry in std::fs::read_dir(&dir)? {
            let entry = entry?;
            let ft = entry.file_type()?;
            if ft.is_file() && is_source_file(&entry.path()) {
                files.push(entry.path());
            } else if ft.is_dir() && recursive {
                dirs.push(entry.path());
            }
        }
    }
    files.sort();
    Ok(files)
}

/// Run the analyze subcommand.
async fn run_analyze(
    path: &std::path::Path,
    recursive: bool,
    threshold: f64,
    format: &AnalyzeFormat,
    output_dir: Option<&std::path::Path>,
    strip_prefix: Option<&std::path::Path>,
) -> anyhow::Result<()> {
    use webspec_index::analyze::file::{analyze_file, FileAnalysisView};
    use webspec_index::analyze::scanner::SpecUrl;
    use webspec_index::analyze::searchfox::to_searchfox_records;

    if output_dir.is_some() && !matches!(format, AnalyzeFormat::Searchfox) {
        anyhow::bail!("--output-dir requires --output-format=searchfox");
    }

    let files = collect_files(path, recursive)?;
    if files.is_empty() {
        eprintln!("No source files found in {}", path.display());
        return Ok(());
    }

    // Build spec URL list from the database.
    let spec_urls: Vec<SpecUrl> = webspec_index::spec_urls()
        .into_iter()
        .map(|e| SpecUrl {
            spec: e.spec,
            base_url: e.base_url,
        })
        .collect();

    let resolver = DbResolver::new();
    let mut files_with_refs = 0;

    for file_path in &files {
        let text = match std::fs::read_to_string(file_path) {
            Ok(t) => t,
            Err(e) => {
                eprintln!("warning: {}: {e}", file_path.display());
                continue;
            }
        };

        let result = analyze_file(&text, &spec_urls, &resolver, threshold);
        if result.scopes.is_empty() {
            continue;
        }

        let view = FileAnalysisView::from(&result);

        match format {
            AnalyzeFormat::Json => {
                let output = serde_json::json!({
                    "file": file_path.to_string_lossy(),
                    "scopes": view.scopes,
                });
                println!("{}", serde_json::to_string_pretty(&output)?);
            }
            AnalyzeFormat::Searchfox => {
                let records = to_searchfox_records(&view);
                if records.is_empty() {
                    continue;
                }
                if let Some(out_dir) = output_dir {
                    let relative = if let Some(prefix) = strip_prefix {
                        file_path.strip_prefix(prefix).unwrap_or(file_path)
                    } else {
                        file_path.as_path()
                    };
                    let analysis_path = out_dir.join(relative);
                    if let Some(parent) = analysis_path.parent() {
                        std::fs::create_dir_all(parent)?;
                    }
                    use std::io::Write;
                    let mut f = std::fs::OpenOptions::new()
                        .create(true)
                        .append(true)
                        .open(&analysis_path)?;
                    writeln!(f, "{records}")?;
                } else {
                    println!("{records}");
                }
            }
        }
        files_with_refs += 1;
    }

    if let Some(out_dir) = output_dir {
        let sections = resolver.resolved_sections();
        if !sections.is_empty() {
            let sections_path = out_dir.join("spec-sections.json");
            let json = serde_json::to_string(&sections)?;
            std::fs::write(&sections_path, json)?;
            eprintln!(
                "spec-analyze: wrote {} spec sections to {}",
                sections.len(),
                sections_path.display()
            );
        }
    }

    eprintln!("spec-analyze: {files_with_refs} files with spec references");
    Ok(())
}

/// Print output in the requested format
fn print_output<T: serde::Serialize>(
    fmt: &OutputFormat,
    value: &T,
    markdown_fn: impl FnOnce(&T) -> String,
) {
    match fmt {
        OutputFormat::Json => {
            println!(
                "{}",
                serde_json::to_string_pretty(value).expect("serialization failed")
            );
        }
        OutputFormat::Markdown => {
            print!("{}", markdown_fn(value));
        }
    }
}