Skip to main content

fallow_core/
lib.rs

1pub mod analyze;
2pub mod cache;
3pub mod churn;
4pub mod cross_reference;
5pub mod discover;
6pub mod duplicates;
7pub mod errors;
8pub mod extract;
9pub mod plugins;
10pub mod progress;
11pub mod results;
12pub mod scripts;
13pub mod suppress;
14pub mod trace;
15
16// Re-export from fallow-graph for backwards compatibility
17pub use fallow_graph::graph;
18pub use fallow_graph::project;
19pub use fallow_graph::resolve;
20
21use std::path::Path;
22use std::time::Instant;
23
24use errors::FallowError;
25use fallow_config::{PackageJson, ResolvedConfig, discover_workspaces};
26use rayon::prelude::*;
27use results::AnalysisResults;
28use trace::PipelineTimings;
29
30/// Result of the full analysis pipeline, including optional performance timings.
31pub struct AnalysisOutput {
32    pub results: AnalysisResults,
33    pub timings: Option<PipelineTimings>,
34    pub graph: Option<graph::ModuleGraph>,
35}
36
37/// Update cache: write freshly parsed modules and refresh stale mtime/size entries.
38fn update_cache(
39    store: &mut cache::CacheStore,
40    modules: &[extract::ModuleInfo],
41    files: &[discover::DiscoveredFile],
42) {
43    for module in modules {
44        if let Some(file) = files.get(module.file_id.0 as usize) {
45            let (mt, sz) = file_mtime_and_size(&file.path);
46            // If content hash matches, just refresh mtime/size if stale (e.g. `touch`ed file)
47            if let Some(cached) = store.get_by_path_only(&file.path)
48                && cached.content_hash == module.content_hash
49            {
50                if cached.mtime_secs != mt || cached.file_size != sz {
51                    store.insert(&file.path, cache::module_to_cached(module, mt, sz));
52                }
53                continue;
54            }
55            store.insert(&file.path, cache::module_to_cached(module, mt, sz));
56        }
57    }
58    store.retain_paths(files);
59}
60
61/// Extract mtime (seconds since epoch) and file size from a path.
62fn file_mtime_and_size(path: &std::path::Path) -> (u64, u64) {
63    std::fs::metadata(path)
64        .map(|m| {
65            let mt = m
66                .modified()
67                .ok()
68                .and_then(|t| t.duration_since(std::time::SystemTime::UNIX_EPOCH).ok())
69                .map_or(0, |d| d.as_secs());
70            (mt, m.len())
71        })
72        .unwrap_or((0, 0))
73}
74
75/// Run the full analysis pipeline.
76///
77/// # Errors
78///
79/// Returns an error if file discovery, parsing, or analysis fails.
80pub fn analyze(config: &ResolvedConfig) -> Result<AnalysisResults, FallowError> {
81    let output = analyze_full(config, false, false)?;
82    Ok(output.results)
83}
84
85/// Run the full analysis pipeline with export usage collection (for LSP Code Lens).
86///
87/// # Errors
88///
89/// Returns an error if file discovery, parsing, or analysis fails.
90pub fn analyze_with_usages(config: &ResolvedConfig) -> Result<AnalysisResults, FallowError> {
91    let output = analyze_full(config, false, true)?;
92    Ok(output.results)
93}
94
95/// Run the full analysis pipeline with optional performance timings and graph retention.
96///
97/// # Errors
98///
99/// Returns an error if file discovery, parsing, or analysis fails.
100pub fn analyze_with_trace(config: &ResolvedConfig) -> Result<AnalysisOutput, FallowError> {
101    analyze_full(config, true, false)
102}
103
104/// Run the analysis pipeline using pre-parsed modules, skipping the parsing stage.
105///
106/// This avoids re-parsing files when the caller already has a `ParseResult` (e.g., from
107/// `fallow_core::extract::parse_all_files`). Discovery, plugins, scripts, entry points,
108/// import resolution, graph construction, and dead code detection still run normally.
109/// The graph is always retained (needed for file scores).
110///
111/// # Errors
112///
113/// Returns an error if discovery, graph construction, or analysis fails.
114pub fn analyze_with_parse_result(
115    config: &ResolvedConfig,
116    modules: &[extract::ModuleInfo],
117) -> Result<AnalysisOutput, FallowError> {
118    let _span = tracing::info_span!("fallow_analyze_with_parse_result").entered();
119    let pipeline_start = Instant::now();
120
121    let show_progress = !config.quiet
122        && std::io::IsTerminal::is_terminal(&std::io::stderr())
123        && matches!(
124            config.output,
125            fallow_config::OutputFormat::Human
126                | fallow_config::OutputFormat::Compact
127                | fallow_config::OutputFormat::Markdown
128        );
129    let progress = progress::AnalysisProgress::new(show_progress);
130
131    if !config.root.join("node_modules").is_dir() {
132        tracing::warn!(
133            "node_modules directory not found. Run `npm install` / `pnpm install` first for accurate results."
134        );
135    }
136
137    // Discover workspaces
138    let t = Instant::now();
139    let workspaces_vec = discover_workspaces(&config.root);
140    let workspaces_ms = t.elapsed().as_secs_f64() * 1000.0;
141    if !workspaces_vec.is_empty() {
142        tracing::info!(count = workspaces_vec.len(), "workspaces discovered");
143    }
144
145    // Stage 1: Discover files (cheap — needed for file registry and resolution)
146    let t = Instant::now();
147    let pb = progress.stage_spinner("Discovering files...");
148    let discovered_files = discover::discover_files(config);
149    let discover_ms = t.elapsed().as_secs_f64() * 1000.0;
150    pb.finish_and_clear();
151
152    let project = project::ProjectState::new(discovered_files, workspaces_vec);
153    let files = project.files();
154    let workspaces = project.workspaces();
155
156    // Stage 1.5: Run plugin system
157    let t = Instant::now();
158    let pb = progress.stage_spinner("Detecting plugins...");
159    let mut plugin_result = run_plugins(config, files, workspaces);
160    let plugins_ms = t.elapsed().as_secs_f64() * 1000.0;
161    pb.finish_and_clear();
162
163    // Stage 1.6: Analyze package.json scripts
164    let t = Instant::now();
165    analyze_all_scripts(config, workspaces, &mut plugin_result);
166    let scripts_ms = t.elapsed().as_secs_f64() * 1000.0;
167
168    // Stage 2: SKIPPED — using pre-parsed modules from caller
169
170    // Stage 3: Discover entry points
171    let t = Instant::now();
172    let entry_points = discover_all_entry_points(config, files, workspaces, &plugin_result);
173    let entry_points_ms = t.elapsed().as_secs_f64() * 1000.0;
174
175    // Stage 4: Resolve imports to file IDs
176    let t = Instant::now();
177    let pb = progress.stage_spinner("Resolving imports...");
178    let resolved = resolve::resolve_all_imports(
179        modules,
180        files,
181        workspaces,
182        &plugin_result.active_plugins,
183        &plugin_result.path_aliases,
184        &config.root,
185    );
186    let resolve_ms = t.elapsed().as_secs_f64() * 1000.0;
187    pb.finish_and_clear();
188
189    // Stage 5: Build module graph
190    let t = Instant::now();
191    let pb = progress.stage_spinner("Building module graph...");
192    let graph = graph::ModuleGraph::build(&resolved, &entry_points, files);
193    let graph_ms = t.elapsed().as_secs_f64() * 1000.0;
194    pb.finish_and_clear();
195
196    // Stage 6: Analyze for dead code
197    let t = Instant::now();
198    let pb = progress.stage_spinner("Analyzing...");
199    let result = analyze::find_dead_code_full(
200        &graph,
201        config,
202        &resolved,
203        Some(&plugin_result),
204        workspaces,
205        modules,
206        false,
207    );
208    let analyze_ms = t.elapsed().as_secs_f64() * 1000.0;
209    pb.finish_and_clear();
210    progress.finish();
211
212    let total_ms = pipeline_start.elapsed().as_secs_f64() * 1000.0;
213
214    tracing::debug!(
215        "\n┌─ Pipeline Profile (reuse) ─────────────────────\n\
216         │  discover files:   {:>8.1}ms  ({} files)\n\
217         │  workspaces:       {:>8.1}ms\n\
218         │  plugins:          {:>8.1}ms\n\
219         │  script analysis:  {:>8.1}ms\n\
220         │  parse/extract:    SKIPPED (reused {} modules)\n\
221         │  entry points:     {:>8.1}ms  ({} entries)\n\
222         │  resolve imports:  {:>8.1}ms\n\
223         │  build graph:      {:>8.1}ms\n\
224         │  analyze:          {:>8.1}ms\n\
225         │  ────────────────────────────────────────────\n\
226         │  TOTAL:            {:>8.1}ms\n\
227         └─────────────────────────────────────────────────",
228        discover_ms,
229        files.len(),
230        workspaces_ms,
231        plugins_ms,
232        scripts_ms,
233        modules.len(),
234        entry_points_ms,
235        entry_points.len(),
236        resolve_ms,
237        graph_ms,
238        analyze_ms,
239        total_ms,
240    );
241
242    let timings = Some(PipelineTimings {
243        discover_files_ms: discover_ms,
244        file_count: files.len(),
245        workspaces_ms,
246        workspace_count: workspaces.len(),
247        plugins_ms,
248        script_analysis_ms: scripts_ms,
249        parse_extract_ms: 0.0, // Skipped — modules were reused
250        module_count: modules.len(),
251        cache_hits: 0,
252        cache_misses: 0,
253        cache_update_ms: 0.0,
254        entry_points_ms,
255        entry_point_count: entry_points.len(),
256        resolve_imports_ms: resolve_ms,
257        build_graph_ms: graph_ms,
258        analyze_ms,
259        total_ms,
260    });
261
262    Ok(AnalysisOutput {
263        results: result,
264        timings,
265        graph: Some(graph),
266    })
267}
268
269#[expect(clippy::unnecessary_wraps)] // Result kept for future error handling
270fn analyze_full(
271    config: &ResolvedConfig,
272    retain: bool,
273    collect_usages: bool,
274) -> Result<AnalysisOutput, FallowError> {
275    let _span = tracing::info_span!("fallow_analyze").entered();
276    let pipeline_start = Instant::now();
277
278    // Progress bars: enabled when not quiet, stderr is a terminal, and output is human-readable.
279    // Structured formats (JSON, SARIF) suppress spinners even on TTY — users piping structured
280    // output don't expect progress noise on stderr.
281    let show_progress = !config.quiet
282        && std::io::IsTerminal::is_terminal(&std::io::stderr())
283        && matches!(
284            config.output,
285            fallow_config::OutputFormat::Human
286                | fallow_config::OutputFormat::Compact
287                | fallow_config::OutputFormat::Markdown
288        );
289    let progress = progress::AnalysisProgress::new(show_progress);
290
291    // Warn if node_modules is missing — resolution will be severely degraded
292    if !config.root.join("node_modules").is_dir() {
293        tracing::warn!(
294            "node_modules directory not found. Run `npm install` / `pnpm install` first for accurate results."
295        );
296    }
297
298    // Discover workspaces if in a monorepo
299    let t = Instant::now();
300    let workspaces_vec = discover_workspaces(&config.root);
301    let workspaces_ms = t.elapsed().as_secs_f64() * 1000.0;
302    if !workspaces_vec.is_empty() {
303        tracing::info!(count = workspaces_vec.len(), "workspaces discovered");
304    }
305
306    // Stage 1: Discover all source files
307    let t = Instant::now();
308    let pb = progress.stage_spinner("Discovering files...");
309    let discovered_files = discover::discover_files(config);
310    let discover_ms = t.elapsed().as_secs_f64() * 1000.0;
311    pb.finish_and_clear();
312
313    // Build ProjectState: owns the file registry with stable FileIds and workspace metadata.
314    // This is the foundation for cross-workspace resolution and future incremental analysis.
315    let project = project::ProjectState::new(discovered_files, workspaces_vec);
316    let files = project.files();
317    let workspaces = project.workspaces();
318
319    // Stage 1.5: Run plugin system — parse config files, discover dynamic entries
320    let t = Instant::now();
321    let pb = progress.stage_spinner("Detecting plugins...");
322    let mut plugin_result = run_plugins(config, files, workspaces);
323    let plugins_ms = t.elapsed().as_secs_f64() * 1000.0;
324    pb.finish_and_clear();
325
326    // Stage 1.6: Analyze package.json scripts for binary usage and config file refs
327    let t = Instant::now();
328    analyze_all_scripts(config, workspaces, &mut plugin_result);
329    let scripts_ms = t.elapsed().as_secs_f64() * 1000.0;
330
331    // Stage 2: Parse all files in parallel and extract imports/exports
332    let t = Instant::now();
333    let pb = progress.stage_spinner(&format!("Parsing {} files...", files.len()));
334    let mut cache_store = if config.no_cache {
335        None
336    } else {
337        cache::CacheStore::load(&config.cache_dir)
338    };
339
340    let parse_result = extract::parse_all_files(files, cache_store.as_ref());
341    let modules = parse_result.modules;
342    let cache_hits = parse_result.cache_hits;
343    let cache_misses = parse_result.cache_misses;
344    let parse_ms = t.elapsed().as_secs_f64() * 1000.0;
345    pb.finish_and_clear();
346
347    // Update cache with freshly parsed modules and refresh stale mtime/size entries.
348    let t = Instant::now();
349    if !config.no_cache {
350        let store = cache_store.get_or_insert_with(cache::CacheStore::new);
351        update_cache(store, &modules, files);
352        if let Err(e) = store.save(&config.cache_dir) {
353            tracing::warn!("Failed to save cache: {e}");
354        }
355    }
356    let cache_ms = t.elapsed().as_secs_f64() * 1000.0;
357
358    // Stage 3: Discover entry points (static patterns + plugin-discovered patterns)
359    let t = Instant::now();
360    let entry_points = discover_all_entry_points(config, files, workspaces, &plugin_result);
361    let entry_points_ms = t.elapsed().as_secs_f64() * 1000.0;
362
363    // Stage 4: Resolve imports to file IDs
364    let t = Instant::now();
365    let pb = progress.stage_spinner("Resolving imports...");
366    let resolved = resolve::resolve_all_imports(
367        &modules,
368        files,
369        workspaces,
370        &plugin_result.active_plugins,
371        &plugin_result.path_aliases,
372        &config.root,
373    );
374    let resolve_ms = t.elapsed().as_secs_f64() * 1000.0;
375    pb.finish_and_clear();
376
377    // Stage 5: Build module graph
378    let t = Instant::now();
379    let pb = progress.stage_spinner("Building module graph...");
380    let graph = graph::ModuleGraph::build(&resolved, &entry_points, files);
381    let graph_ms = t.elapsed().as_secs_f64() * 1000.0;
382    pb.finish_and_clear();
383
384    // Stage 6: Analyze for dead code (with plugin context and workspace info)
385    let t = Instant::now();
386    let pb = progress.stage_spinner("Analyzing...");
387    let result = analyze::find_dead_code_full(
388        &graph,
389        config,
390        &resolved,
391        Some(&plugin_result),
392        workspaces,
393        &modules,
394        collect_usages,
395    );
396    let analyze_ms = t.elapsed().as_secs_f64() * 1000.0;
397    pb.finish_and_clear();
398    progress.finish();
399
400    let total_ms = pipeline_start.elapsed().as_secs_f64() * 1000.0;
401
402    let cache_summary = if cache_hits > 0 {
403        format!(" ({cache_hits} cached, {cache_misses} parsed)")
404    } else {
405        String::new()
406    };
407
408    tracing::debug!(
409        "\n┌─ Pipeline Profile ─────────────────────────────\n\
410         │  discover files:   {:>8.1}ms  ({} files)\n\
411         │  workspaces:       {:>8.1}ms\n\
412         │  plugins:          {:>8.1}ms\n\
413         │  script analysis:  {:>8.1}ms\n\
414         │  parse/extract:    {:>8.1}ms  ({} modules{})\n\
415         │  cache update:     {:>8.1}ms\n\
416         │  entry points:     {:>8.1}ms  ({} entries)\n\
417         │  resolve imports:  {:>8.1}ms\n\
418         │  build graph:      {:>8.1}ms\n\
419         │  analyze:          {:>8.1}ms\n\
420         │  ────────────────────────────────────────────\n\
421         │  TOTAL:            {:>8.1}ms\n\
422         └─────────────────────────────────────────────────",
423        discover_ms,
424        files.len(),
425        workspaces_ms,
426        plugins_ms,
427        scripts_ms,
428        parse_ms,
429        modules.len(),
430        cache_summary,
431        cache_ms,
432        entry_points_ms,
433        entry_points.len(),
434        resolve_ms,
435        graph_ms,
436        analyze_ms,
437        total_ms,
438    );
439
440    let timings = if retain {
441        Some(PipelineTimings {
442            discover_files_ms: discover_ms,
443            file_count: files.len(),
444            workspaces_ms,
445            workspace_count: workspaces.len(),
446            plugins_ms,
447            script_analysis_ms: scripts_ms,
448            parse_extract_ms: parse_ms,
449            module_count: modules.len(),
450            cache_hits,
451            cache_misses,
452            cache_update_ms: cache_ms,
453            entry_points_ms,
454            entry_point_count: entry_points.len(),
455            resolve_imports_ms: resolve_ms,
456            build_graph_ms: graph_ms,
457            analyze_ms,
458            total_ms,
459        })
460    } else {
461        None
462    };
463
464    Ok(AnalysisOutput {
465        results: result,
466        timings,
467        graph: if retain { Some(graph) } else { None },
468    })
469}
470
471/// Analyze package.json scripts from root and all workspace packages.
472///
473/// Populates the plugin result with script-used packages and config file
474/// entry patterns. Also scans CI config files for binary invocations.
475fn analyze_all_scripts(
476    config: &ResolvedConfig,
477    workspaces: &[fallow_config::WorkspaceInfo],
478    plugin_result: &mut plugins::AggregatedPluginResult,
479) {
480    let pkg_path = config.root.join("package.json");
481    if let Ok(pkg) = PackageJson::load(&pkg_path)
482        && let Some(ref pkg_scripts) = pkg.scripts
483    {
484        let scripts_to_analyze = if config.production {
485            scripts::filter_production_scripts(pkg_scripts)
486        } else {
487            pkg_scripts.clone()
488        };
489        let script_analysis = scripts::analyze_scripts(&scripts_to_analyze, &config.root);
490        plugin_result.script_used_packages = script_analysis.used_packages;
491
492        for config_file in &script_analysis.config_files {
493            plugin_result
494                .entry_patterns
495                .push((config_file.clone(), "scripts".to_string()));
496        }
497    }
498    for ws in workspaces {
499        let ws_pkg_path = ws.root.join("package.json");
500        if let Ok(ws_pkg) = PackageJson::load(&ws_pkg_path)
501            && let Some(ref ws_scripts) = ws_pkg.scripts
502        {
503            let scripts_to_analyze = if config.production {
504                scripts::filter_production_scripts(ws_scripts)
505            } else {
506                ws_scripts.clone()
507            };
508            let ws_analysis = scripts::analyze_scripts(&scripts_to_analyze, &ws.root);
509            plugin_result
510                .script_used_packages
511                .extend(ws_analysis.used_packages);
512
513            let ws_prefix = ws
514                .root
515                .strip_prefix(&config.root)
516                .unwrap_or(&ws.root)
517                .to_string_lossy();
518            for config_file in &ws_analysis.config_files {
519                plugin_result
520                    .entry_patterns
521                    .push((format!("{ws_prefix}/{config_file}"), "scripts".to_string()));
522            }
523        }
524    }
525
526    // Scan CI config files for binary invocations
527    let ci_packages = scripts::ci::analyze_ci_files(&config.root);
528    plugin_result.script_used_packages.extend(ci_packages);
529}
530
531/// Discover all entry points from static patterns, workspaces, plugins, and infrastructure.
532fn discover_all_entry_points(
533    config: &ResolvedConfig,
534    files: &[discover::DiscoveredFile],
535    workspaces: &[fallow_config::WorkspaceInfo],
536    plugin_result: &plugins::AggregatedPluginResult,
537) -> Vec<discover::EntryPoint> {
538    let mut entry_points = discover::discover_entry_points(config, files);
539    let ws_entries: Vec<_> = workspaces
540        .par_iter()
541        .flat_map(|ws| discover::discover_workspace_entry_points(&ws.root, config, files))
542        .collect();
543    entry_points.extend(ws_entries);
544    let plugin_entries = discover::discover_plugin_entry_points(plugin_result, config, files);
545    entry_points.extend(plugin_entries);
546    let infra_entries = discover::discover_infrastructure_entry_points(&config.root);
547    entry_points.extend(infra_entries);
548    entry_points
549}
550
551/// Run plugins for root project and all workspace packages.
552fn run_plugins(
553    config: &ResolvedConfig,
554    files: &[discover::DiscoveredFile],
555    workspaces: &[fallow_config::WorkspaceInfo],
556) -> plugins::AggregatedPluginResult {
557    let registry = plugins::PluginRegistry::new(config.external_plugins.clone());
558    let file_paths: Vec<std::path::PathBuf> = files.iter().map(|f| f.path.clone()).collect();
559
560    // Run plugins for root project (full run with external plugins, inline config, etc.)
561    let pkg_path = config.root.join("package.json");
562    let mut result = PackageJson::load(&pkg_path).map_or_else(
563        |_| plugins::AggregatedPluginResult::default(),
564        |pkg| registry.run(&pkg, &config.root, &file_paths),
565    );
566
567    if workspaces.is_empty() {
568        return result;
569    }
570
571    // Pre-compile config matchers and relative files once for all workspace runs.
572    // This avoids re-compiling glob patterns and re-computing relative paths per workspace
573    // (previously O(workspaces × plugins × files) glob compilations).
574    let precompiled_matchers = registry.precompile_config_matchers();
575    let relative_files: Vec<(&std::path::PathBuf, String)> = file_paths
576        .iter()
577        .map(|f| {
578            let rel = f
579                .strip_prefix(&config.root)
580                .unwrap_or(f)
581                .to_string_lossy()
582                .into_owned();
583            (f, rel)
584        })
585        .collect();
586
587    // Run plugins for each workspace package in parallel, then merge results.
588    let ws_results: Vec<_> = workspaces
589        .par_iter()
590        .filter_map(|ws| {
591            let ws_pkg_path = ws.root.join("package.json");
592            let ws_pkg = PackageJson::load(&ws_pkg_path).ok()?;
593            let ws_result = registry.run_workspace_fast(
594                &ws_pkg,
595                &ws.root,
596                &config.root,
597                &precompiled_matchers,
598                &relative_files,
599            );
600            if ws_result.active_plugins.is_empty() {
601                return None;
602            }
603            let ws_prefix = ws
604                .root
605                .strip_prefix(&config.root)
606                .unwrap_or(&ws.root)
607                .to_string_lossy()
608                .into_owned();
609            Some((ws_result, ws_prefix))
610        })
611        .collect();
612
613    // Merge workspace results sequentially (deterministic order via par_iter index stability)
614    // Track seen names for O(1) dedup instead of O(n) Vec::contains
615    let mut seen_plugins: rustc_hash::FxHashSet<String> =
616        result.active_plugins.iter().cloned().collect();
617    let mut seen_prefixes: rustc_hash::FxHashSet<String> =
618        result.virtual_module_prefixes.iter().cloned().collect();
619    for (ws_result, ws_prefix) in ws_results {
620        // Prefix helper: workspace-relative patterns need the workspace prefix
621        // to be matchable from the monorepo root. But patterns that are already
622        // project-root-relative (e.g., from angular.json which uses absolute paths
623        // like "apps/client/src/styles.css") should not be double-prefixed.
624        let prefix_if_needed = |pat: &str| -> String {
625            if pat.starts_with(ws_prefix.as_str()) || pat.starts_with('/') {
626                pat.to_string()
627            } else {
628                format!("{ws_prefix}/{pat}")
629            }
630        };
631
632        for (pat, pname) in &ws_result.entry_patterns {
633            result
634                .entry_patterns
635                .push((prefix_if_needed(pat), pname.clone()));
636        }
637        for (pat, pname) in &ws_result.always_used {
638            result
639                .always_used
640                .push((prefix_if_needed(pat), pname.clone()));
641        }
642        for (pat, pname) in &ws_result.discovered_always_used {
643            result
644                .discovered_always_used
645                .push((prefix_if_needed(pat), pname.clone()));
646        }
647        for (file_pat, exports) in &ws_result.used_exports {
648            result
649                .used_exports
650                .push((prefix_if_needed(file_pat), exports.clone()));
651        }
652        // Merge active plugin names (deduplicated via HashSet)
653        for plugin_name in ws_result.active_plugins {
654            if !seen_plugins.contains(&plugin_name) {
655                seen_plugins.insert(plugin_name.clone());
656                result.active_plugins.push(plugin_name);
657            }
658        }
659        // These don't need prefixing (absolute paths / package names)
660        result
661            .referenced_dependencies
662            .extend(ws_result.referenced_dependencies);
663        result.setup_files.extend(ws_result.setup_files);
664        result
665            .tooling_dependencies
666            .extend(ws_result.tooling_dependencies);
667        // Virtual module prefixes (e.g., Docusaurus @theme/, @site/) are
668        // package-name prefixes, not file paths — no workspace prefix needed.
669        for prefix in ws_result.virtual_module_prefixes {
670            if !seen_prefixes.contains(&prefix) {
671                seen_prefixes.insert(prefix.clone());
672                result.virtual_module_prefixes.push(prefix);
673            }
674        }
675    }
676
677    result
678}
679
680/// Run analysis on a project directory (with export usages for LSP Code Lens).
681///
682/// # Errors
683///
684/// Returns an error if config loading, file discovery, parsing, or analysis fails.
685pub fn analyze_project(root: &Path) -> Result<AnalysisResults, FallowError> {
686    let config = default_config(root);
687    analyze_with_usages(&config)
688}
689
690/// Create a default config for a project root.
691pub(crate) fn default_config(root: &Path) -> ResolvedConfig {
692    let user_config = fallow_config::FallowConfig::find_and_load(root)
693        .ok()
694        .flatten();
695    match user_config {
696        Some((config, _path)) => config.resolve(
697            root.to_path_buf(),
698            fallow_config::OutputFormat::Human,
699            num_cpus(),
700            false,
701            true, // quiet: LSP/programmatic callers don't need progress bars
702        ),
703        None => fallow_config::FallowConfig::default().resolve(
704            root.to_path_buf(),
705            fallow_config::OutputFormat::Human,
706            num_cpus(),
707            false,
708            true,
709        ),
710    }
711}
712
713fn num_cpus() -> usize {
714    std::thread::available_parallelism()
715        .map(std::num::NonZeroUsize::get)
716        .unwrap_or(4)
717}