1#![cfg_attr(not(test), deny(clippy::disallowed_methods))]
13#![cfg_attr(
14 test,
15 allow(
16 clippy::unwrap_used,
17 clippy::expect_used,
18 reason = "tests use unwrap and expect to keep fixture setup concise"
19 )
20)]
21
22pub mod analyze;
23pub mod cache;
24pub mod discover;
25pub(crate) mod errors;
26mod external_style_usage;
27pub mod extract;
28pub mod git_env;
29mod package_assets;
30pub mod plugins;
31pub(crate) mod progress;
32mod resolution_inputs;
33pub mod results;
34pub(crate) mod scripts;
35#[doc(hidden)]
38pub use scripts::parse_script;
39pub mod suppress;
40
41pub use fallow_graph::cache as graph_cache;
42pub use fallow_graph::graph;
43pub use fallow_graph::project;
44pub use fallow_graph::resolve;
45
46use std::path::{Path, PathBuf};
47use std::time::Instant;
48
49use errors::FallowError;
50use fallow_config::{
51 EntryPointRole, PackageJson, ResolvedConfig, find_undeclared_workspaces_with_ignores,
52};
53use fallow_types::cache_rejection::CacheRejection;
54use fallow_types::trace::{EntryPointSpans, PipelineCounters, PipelineTimings};
55use rayon::prelude::*;
56use results::AnalysisResults;
57use rustc_hash::FxHashSet;
58
59const UNDECLARED_WORKSPACE_WARNING_PREVIEW: usize = 5;
60type LoadedWorkspacePackage = (fallow_config::WorkspaceInfo, PackageJson);
61
62fn record_graph_package_usage(
63 graph: &mut graph::ModuleGraph,
64 package_name: &str,
65 file_id: discover::FileId,
66 is_type_only: bool,
67) {
68 graph
69 .package_usage
70 .entry(package_name.to_owned())
71 .or_default()
72 .push(file_id);
73 if is_type_only {
74 graph
75 .type_only_package_usage
76 .entry(package_name.to_owned())
77 .or_default()
78 .push(file_id);
79 }
80}
81
82fn workspace_package_name<'a>(
83 source: &str,
84 workspace_names: &FxHashSet<&'a str>,
85) -> Option<&'a str> {
86 if !resolve::is_bare_specifier(source) {
87 return None;
88 }
89 let package_name = resolve::extract_package_name(source);
90 workspace_names.get(package_name.as_str()).copied()
91}
92
93fn credit_workspace_package_usage(
94 graph: &mut graph::ModuleGraph,
95 resolved: &[resolve::ResolvedModule],
96 workspaces: &[fallow_config::WorkspaceInfo],
97) {
98 if workspaces.is_empty() {
99 return;
100 }
101
102 let workspace_names: FxHashSet<&str> = workspaces.iter().map(|ws| ws.name.as_str()).collect();
103 for module in resolved {
104 for import in module.all_resolved_imports() {
105 if matches!(
106 import.target,
107 resolve::ResolveResult::InternalModule(_)
108 | resolve::ResolveResult::CommonJsInternalModule(_)
109 ) && let Some(package_name) =
110 workspace_package_name(&import.info.source, &workspace_names)
111 {
112 record_graph_package_usage(
113 graph,
114 package_name,
115 module.file_id,
116 import.info.is_type_only,
117 );
118 }
119 }
120
121 for re_export in &module.re_exports {
122 if matches!(re_export.target, resolve::ResolveResult::InternalModule(_))
123 && let Some(package_name) =
124 workspace_package_name(&re_export.info.source, &workspace_names)
125 {
126 record_graph_package_usage(
127 graph,
128 package_name,
129 module.file_id,
130 re_export.info.is_type_only,
131 );
132 }
133 }
134 }
135}
136
137fn credit_package_path_references(graph: &mut graph::ModuleGraph, modules: &[extract::ModuleInfo]) {
138 for module in modules {
139 for package_name in &module.package_path_references {
140 record_graph_package_usage(graph, package_name, module.file_id, false);
141 }
142 for package_name in &module.type_package_references {
146 record_graph_package_usage(graph, package_name, module.file_id, true);
147 }
148 }
149}
150
151fn credit_bin_path_references(
157 graph: &mut graph::ModuleGraph,
158 modules: &[extract::ModuleInfo],
159 binaries: &scripts::DependencyBinaries,
160) {
161 for module in modules {
162 for binary in &module.bin_path_references {
163 if let Some(package_name) = binaries.package_for(binary) {
164 record_graph_package_usage(graph, &package_name, module.file_id, false);
165 }
166 }
167 }
168}
169
170#[doc(hidden)]
172pub struct AnalysisOutput {
173 pub results: AnalysisResults,
174 pub timings: Option<PipelineTimings>,
175 pub graph: Option<graph::ModuleGraph>,
176 pub modules: Option<Vec<extract::ModuleInfo>>,
180 pub files: Option<Vec<discover::DiscoveredFile>>,
182 pub script_used_packages: rustc_hash::FxHashSet<String>,
187 pub trace_provenance: fallow_types::trace::TraceProvenance,
190 pub file_hashes: rustc_hash::FxHashMap<std::path::PathBuf, u64>,
199}
200
201#[derive(Debug, Clone, Copy)]
204#[doc(hidden)]
205pub struct AnalysisParseMetrics {
206 parse_ms: f64,
207 cache_ms: f64,
208 cache_hits: usize,
209 cache_misses: usize,
210 parse_cpu_ms: f64,
211 cache_rejection: Option<CacheRejection>,
212}
213
214fn update_cache(
231 store: &mut cache::CacheStore,
232 modules: &[extract::ModuleInfo],
233 files: &[discover::DiscoveredFile],
234 need_complexity: bool,
235 read_started_ns: u64,
236) -> bool {
237 let mut dirty = false;
238 for module in modules {
239 if let Some(file) = files.get(module.file_id.0 as usize) {
240 let fingerprint = file_fingerprint(&file.path).for_content_read_at(read_started_ns);
241 if let Some(cached) = store.get_by_path_only(&file.path)
242 && cached.content_hash == module.content_hash
243 {
244 let stale_metadata = cached.source_fingerprint() != fingerprint;
245 let adds_complexity = need_complexity && !cached.complexity_extracted;
246 if stale_metadata && !adds_complexity {
247 store.refresh_fingerprint(&file.path, fingerprint);
248 dirty = true;
249 } else if adds_complexity {
250 let preserved_complexity = (!need_complexity && cached.complexity_extracted)
251 .then(|| cached.complexity.clone());
252 let mut refreshed =
253 cache::module_to_cached(module, fingerprint, need_complexity);
254 if let Some(complexity) = preserved_complexity {
255 refreshed.complexity = complexity;
256 refreshed.complexity_extracted = true;
257 }
258 store.insert(&file.path, refreshed);
259 dirty = true;
260 }
261 continue;
262 }
263 store.insert(
264 &file.path,
265 cache::module_to_cached(module, fingerprint, need_complexity),
266 );
267 dirty = true;
268 }
269 }
270 let removed_stale_paths = store.retain_paths(files);
271 dirty || removed_stale_paths
272}
273
274#[must_use]
282fn resolve_cache_max_size_bytes(config: &ResolvedConfig) -> usize {
283 config
284 .cache_max_size_mb
285 .map_or(cache::DEFAULT_CACHE_MAX_SIZE, |mb| {
286 (mb as usize).saturating_mul(1024 * 1024)
287 })
288}
289
290fn file_fingerprint(path: &std::path::Path) -> fallow_types::source_fingerprint::SourceFingerprint {
292 std::fs::metadata(path).map_or(
293 fallow_types::source_fingerprint::SourceFingerprint::new(0, 0),
294 |metadata| fallow_types::source_fingerprint::SourceFingerprint::from_metadata(&metadata),
295 )
296}
297
298fn format_undeclared_workspace_warning(
299 root: &Path,
300 undeclared: &[fallow_config::WorkspaceDiagnostic],
301) -> Option<String> {
302 if undeclared.is_empty() {
303 return None;
304 }
305
306 let preview = undeclared
307 .iter()
308 .take(UNDECLARED_WORKSPACE_WARNING_PREVIEW)
309 .map(|diag| {
310 diag.path
311 .strip_prefix(root)
312 .unwrap_or(&diag.path)
313 .display()
314 .to_string()
315 .replace('\\', "/")
316 })
317 .collect::<Vec<_>>();
318 let remaining = undeclared
319 .len()
320 .saturating_sub(UNDECLARED_WORKSPACE_WARNING_PREVIEW);
321 let tail = if remaining > 0 {
322 format!(" (and {remaining} more)")
323 } else {
324 String::new()
325 };
326 let noun = if undeclared.len() == 1 {
327 "directory with package.json is"
328 } else {
329 "directories with package.json are"
330 };
331 let guidance = if undeclared.len() == 1 {
332 "Add that path to package.json workspaces or pnpm-workspace.yaml if it should be analyzed as a workspace."
333 } else {
334 "Add those paths to package.json workspaces or pnpm-workspace.yaml if they should be analyzed as workspaces."
335 };
336
337 Some(format!(
338 "{} {} not declared as {}: {}{}. {}",
339 undeclared.len(),
340 noun,
341 if undeclared.len() == 1 {
342 "a workspace"
343 } else {
344 "workspaces"
345 },
346 preview.join(", "),
347 tail,
348 guidance
349 ))
350}
351
352fn warn_undeclared_workspaces(
353 root: &Path,
354 workspaces_vec: &[fallow_config::WorkspaceInfo],
355 ignore_patterns: &fallow_config::IgnorePatternSet,
356 quiet: bool,
357) {
358 let undeclared = find_undeclared_workspaces_with_ignores(root, workspaces_vec, ignore_patterns);
359 if undeclared.is_empty() {
360 return;
361 }
362
363 let existing = fallow_config::workspace_diagnostics_for(root);
364 let already_flagged: rustc_hash::FxHashSet<PathBuf> = existing
365 .iter()
366 .map(|d| dunce::canonicalize(&d.path).unwrap_or_else(|_| d.path.clone()))
367 .collect();
368 let undeclared: Vec<_> = undeclared
369 .into_iter()
370 .filter(|diag| {
371 let canonical = dunce::canonicalize(&diag.path).unwrap_or_else(|_| diag.path.clone());
372 !already_flagged.contains(&canonical)
373 })
374 .collect();
375 if undeclared.is_empty() {
376 return;
377 }
378
379 fallow_config::append_workspace_diagnostics(root, undeclared.clone());
380
381 if !quiet && let Some(message) = format_undeclared_workspace_warning(root, &undeclared) {
382 tracing::warn!("{message}");
383 }
384}
385
386#[doc(hidden)]
392#[deprecated(
393 since = "2.76.0",
394 note = "fallow_core is internal; use fallow_api::run_dead_code for typed output; serialize with fallow_api::serialize_dead_code_programmatic_json for JSON output. See docs/fallow-core-migration.md."
395)]
396pub fn analyze(config: &ResolvedConfig) -> Result<AnalysisResults, FallowError> {
397 let output = analyze_full(config, false, false, false, false)?;
398 Ok(output.results)
399}
400
401#[doc(hidden)]
407#[deprecated(
408 since = "2.76.0",
409 note = "fallow_core is internal; use fallow_api::run_dead_code for public typed output. NOTE: export-usage collection is not exposed in the programmatic surface today. See docs/fallow-core-migration.md."
410)]
411pub fn analyze_with_usages(config: &ResolvedConfig) -> Result<AnalysisResults, FallowError> {
412 let output = analyze_full(config, false, true, false, false)?;
413 Ok(output.results)
414}
415
416#[doc(hidden)]
422#[deprecated(
423 since = "2.76.0",
424 note = "fallow_core is internal; use fallow_api::run_dead_code for public typed output. NOTE: trace timings are not exposed in the programmatic surface today; use `fallow dead-code --performance` for CLI-side timings. See docs/fallow-core-migration.md."
425)]
426pub fn analyze_with_trace(config: &ResolvedConfig) -> Result<AnalysisOutput, FallowError> {
427 analyze_full(config, true, false, false, false)
428}
429
430#[doc(hidden)]
440#[deprecated(
441 since = "2.76.0",
442 note = "fallow_core is internal; use fallow_api::run_dead_code for public typed output. NOTE: combined-mode module retention is not exposed in the programmatic surface today. See docs/fallow-core-migration.md."
443)]
444pub fn analyze_retaining_modules(
445 config: &ResolvedConfig,
446 need_complexity: bool,
447 retain_graph: bool,
448) -> Result<AnalysisOutput, FallowError> {
449 analyze_full(config, retain_graph, false, need_complexity, true)
450}
451
452fn new_analysis_progress(config: &ResolvedConfig) -> progress::AnalysisProgress {
453 let show_progress = !config.quiet
454 && std::io::IsTerminal::is_terminal(&std::io::stderr())
455 && matches!(
456 config.output,
457 fallow_config::OutputFormat::Human
458 | fallow_config::OutputFormat::Compact
459 | fallow_config::OutputFormat::Markdown
460 );
461 progress::AnalysisProgress::new(show_progress)
462}
463
464fn discover_analysis_workspaces(
465 config: &ResolvedConfig,
466) -> Result<(Vec<fallow_config::WorkspaceInfo>, f64), FallowError> {
467 let t = Instant::now();
468 let (workspaces, diagnostics) =
469 fallow_config::discover_workspaces_with_diagnostics_and_patterns(
470 &config.root,
471 &config.ignore_patterns,
472 &config.workspace_patterns,
473 )
474 .map_err(|error| FallowError::config(error.to_string()))?;
475 fallow_config::stash_workspace_diagnostics(&config.root, diagnostics);
476 let workspaces_ms = t.elapsed().as_secs_f64() * 1000.0;
477 if !workspaces.is_empty() {
478 tracing::info!(count = workspaces.len(), "workspaces discovered");
479 }
480
481 warn_undeclared_workspaces(
482 &config.root,
483 &workspaces,
484 &config.ignore_patterns,
485 config.quiet,
486 );
487
488 Ok((workspaces, workspaces_ms))
489}
490
491struct AnalysisSetup {
495 progress: progress::AnalysisProgress,
496 project: project::ProjectState,
497 root_pkg: Option<PackageJson>,
498 config_candidates: Vec<std::path::PathBuf>,
503 discover_ms: f64,
504 workspaces_ms: f64,
505}
506
507#[derive(Debug, Clone)]
513#[doc(hidden)]
514pub struct AnalysisDiscovery {
515 files: Vec<discover::DiscoveredFile>,
516 workspaces: Vec<fallow_config::WorkspaceInfo>,
517 root_pkg: Option<PackageJson>,
518 config_candidates: Vec<std::path::PathBuf>,
519 discover_ms: f64,
520 workspaces_ms: f64,
521}
522
523impl AnalysisDiscovery {
524 #[must_use]
526 pub fn from_parts(
527 files: Vec<discover::DiscoveredFile>,
528 workspaces: Vec<fallow_config::WorkspaceInfo>,
529 root_pkg: Option<PackageJson>,
530 config_candidates: Vec<std::path::PathBuf>,
531 discover_ms: f64,
532 workspaces_ms: f64,
533 ) -> Self {
534 Self {
535 files,
536 workspaces,
537 root_pkg,
538 config_candidates,
539 discover_ms,
540 workspaces_ms,
541 }
542 }
543
544 #[must_use]
546 fn files(&self) -> &[discover::DiscoveredFile] {
547 &self.files
548 }
549
550 #[must_use]
552 pub fn workspaces(&self) -> &[fallow_config::WorkspaceInfo] {
553 &self.workspaces
554 }
555
556 #[must_use]
558 pub fn into_files(self) -> Vec<discover::DiscoveredFile> {
559 self.files
560 }
561}
562
563pub(crate) struct AnalysisSession<'a> {
568 config: &'a ResolvedConfig,
569 pipeline_start: Instant,
570 progress: progress::AnalysisProgress,
571 project: project::ProjectState,
572 root_pkg: Option<PackageJson>,
573 config_candidates: Vec<std::path::PathBuf>,
574 discover_ms: f64,
575 workspaces_ms: f64,
576}
577
578impl<'a> AnalysisSession<'a> {
579 fn new(config: &'a ResolvedConfig) -> Result<Self, FallowError> {
580 let pipeline_start = Instant::now();
581 let AnalysisSetup {
582 progress,
583 project,
584 root_pkg,
585 config_candidates,
586 discover_ms,
587 workspaces_ms,
588 } = run_analysis_setup(config)?;
589
590 Ok(Self {
591 config,
592 pipeline_start,
593 progress,
594 project,
595 root_pkg,
596 config_candidates,
597 discover_ms,
598 workspaces_ms,
599 })
600 }
601
602 fn files(&self) -> &[discover::DiscoveredFile] {
603 self.project.files()
604 }
605
606 fn workspaces(&self) -> &[fallow_config::WorkspaceInfo] {
607 self.project.workspaces()
608 }
609
610 fn load_workspace_packages(&self) -> Vec<LoadedWorkspacePackage> {
611 load_workspace_packages(self.workspaces())
612 }
613
614 fn run_plugins_and_scripts(
615 &self,
616 workspace_pkgs: &[LoadedWorkspacePackage],
617 ) -> Result<(plugins::AggregatedPluginResult, f64, f64), FallowError> {
618 run_plugins_and_scripts(&PluginScriptInput {
619 config: self.config,
620 progress: &self.progress,
621 files: self.files(),
622 workspaces: self.workspaces(),
623 root_pkg: self.root_pkg.as_ref(),
624 workspace_pkgs,
625 config_candidates: &self.config_candidates,
626 })
627 }
628
629 fn prelude_timings(&self, plugins_ms: f64, scripts_ms: f64) -> PreludeTimings {
630 PreludeTimings {
631 discover_ms: self.discover_ms,
632 workspaces_ms: self.workspaces_ms,
633 plugins_ms,
634 scripts_ms,
635 }
636 }
637
638 fn parse_modules(&self, need_complexity: bool) -> AnalysisParseOutput {
639 let t = Instant::now();
640 self.progress
641 .set_stage(&format!("parsing {} files...", self.files().len()));
642 parse_analysis_modules(self.config, self.files(), need_complexity, t)
643 }
644
645 fn run_owned_core(
646 &self,
647 workspace_pkgs: &[LoadedWorkspacePackage],
648 plugin_result: &plugins::AggregatedPluginResult,
649 mut modules: Vec<extract::ModuleInfo>,
650 collect_usages: bool,
651 ) -> OwnedAnalysisCore {
652 let shared = AnalysisCoreSharedInput {
653 config: self.config,
654 progress: &self.progress,
655 files: self.files(),
656 workspaces: self.workspaces(),
657 root_pkg: self.root_pkg.as_ref(),
658 workspace_pkgs,
659 plugin_result,
660 };
661
662 let entry_points = discover_analysis_entry_points(&shared);
663 let mut graph_cache_rejection = None;
664 let (resolved, graph) =
665 match try_load_analysis_graph_cache(&shared, &entry_points, &modules) {
666 Ok(hit) => (
667 TimedResolvedModules {
668 project: hit.project,
669 elapsed_ms: 0.0,
670 },
671 TimedGraph {
672 graph: hit.graph,
673 elapsed_ms: hit.elapsed_ms,
674 },
675 ),
676 Err(rejection) => {
677 graph_cache_rejection = rejection;
678 let resolved = resolve_analysis_imports_timed(&shared, &modules);
679 let graph = build_analysis_graph_timed(
680 &shared,
681 &resolved.project,
682 &entry_points,
683 &modules,
684 );
685 (resolved, graph)
686 }
687 };
688 release_resolution_payloads(&mut modules);
689 let analysis = analyze_dead_code_timed(
690 &shared,
691 &graph.graph,
692 &resolved.project.modules,
693 &modules,
694 collect_usages,
695 entry_points.summary,
696 );
697
698 OwnedAnalysisCore {
699 result: analysis.result,
700 graph: graph.graph,
701 modules,
702 entry_point_count: entry_points.count,
703 entry_points_ms: entry_points.elapsed_ms,
704 entry_point_spans: entry_points.spans,
705 resolve_ms: resolved.elapsed_ms,
706 graph_ms: graph.elapsed_ms,
707 analyze_ms: analysis.elapsed_ms,
708 graph_cache_rejection,
709 resolve_work: resolved.project.work,
710 }
711 }
712
713 fn run_full(
714 self,
715 retain: bool,
716 collect_usages: bool,
717 need_complexity: bool,
718 retain_modules: bool,
719 ) -> Result<AnalysisOutput, FallowError> {
720 let workspace_pkgs = self.load_workspace_packages();
721 let (plugin_result, plugins_ms, scripts_ms) =
722 self.run_plugins_and_scripts(&workspace_pkgs)?;
723
724 let AnalysisParseOutput { modules, metrics } = self.parse_modules(need_complexity);
725 let core = self.run_owned_core(&workspace_pkgs, &plugin_result, modules, collect_usages);
726 self.progress.finish();
727
728 let profile = full_analysis_pipeline_profile(
729 &self.prelude_timings(plugins_ms, scripts_ms),
730 self.pipeline_start,
731 self.files(),
732 self.workspaces(),
733 &core,
734 &metrics,
735 );
736 trace_pipeline_profile(&profile);
737
738 let trace_provenance = plugins::build_trace_provenance(
739 &self.config.root,
740 self.files(),
741 self.workspaces(),
742 &core.modules,
743 &plugin_result,
744 plugins::ExportCredits::for_run(retain, self.config),
745 );
746 let mut output = assemble_full_output(
747 core,
748 plugin_result,
749 &profile,
750 self.files(),
751 retain,
752 retain_modules,
753 );
754 output.trace_provenance = trace_provenance;
755 Ok(output)
756 }
757}
758
759fn run_analysis_setup(config: &ResolvedConfig) -> Result<AnalysisSetup, FallowError> {
762 let progress = new_analysis_progress(config);
763
764 let (workspaces_vec, workspaces_ms) = discover_analysis_workspaces(config)?;
765 let root_pkg = fallow_config::load_dir_package_json(&config.root);
766 let discovery_hidden_dir_scopes =
767 discover::collect_hidden_dir_scopes(config, root_pkg.as_ref(), &workspaces_vec);
768
769 let t = Instant::now();
770 progress.set_stage("discovering files...");
771 let (discovered_files, config_candidates) =
772 discover::discover_files_and_config_candidates(config, &discovery_hidden_dir_scopes);
773 let discover_ms = t.elapsed().as_secs_f64() * 1000.0;
774
775 let project = project::ProjectState::new(discovered_files, workspaces_vec);
776
777 Ok(AnalysisSetup {
778 progress,
779 project,
780 root_pkg,
781 config_candidates,
782 discover_ms,
783 workspaces_ms,
784 })
785}
786
787struct PluginScriptInput<'a> {
789 config: &'a ResolvedConfig,
790 progress: &'a progress::AnalysisProgress,
791 files: &'a [discover::DiscoveredFile],
792 workspaces: &'a [fallow_config::WorkspaceInfo],
793 root_pkg: Option<&'a PackageJson>,
794 workspace_pkgs: &'a [LoadedWorkspacePackage],
795 config_candidates: &'a [std::path::PathBuf],
796}
797
798fn run_plugins_and_scripts(
801 input: &PluginScriptInput<'_>,
802) -> Result<(plugins::AggregatedPluginResult, f64, f64), FallowError> {
803 let t = Instant::now();
804 input.progress.set_stage("detecting plugins...");
805 let mut plugin_result = run_plugins(
806 input.config,
807 input.files,
808 input.workspaces,
809 input.root_pkg,
810 input.workspace_pkgs,
811 input.config_candidates,
812 )?;
813 let plugins_ms = t.elapsed().as_secs_f64() * 1000.0;
814
815 let t = Instant::now();
816 analyze_all_scripts(
817 input.config,
818 input.workspaces,
819 input.root_pkg,
820 input.workspace_pkgs,
821 &mut plugin_result,
822 );
823 let scripts_ms = t.elapsed().as_secs_f64() * 1000.0;
824
825 Ok((plugin_result, plugins_ms, scripts_ms))
826}
827
828#[derive(Debug, Clone, Copy)]
830#[doc(hidden)]
831pub struct DeadCodePreludeTimings {
832 pub discover_ms: f64,
833 pub workspaces_ms: f64,
834 pub plugins_ms: f64,
835 pub scripts_ms: f64,
836}
837
838#[doc(hidden)]
843pub struct DeadCodeBackendPrelude<'a> {
844 config: &'a ResolvedConfig,
845 pipeline_start: Instant,
846 progress: progress::AnalysisProgress,
847 discovery: AnalysisDiscovery,
848 workspace_pkgs: Vec<LoadedWorkspacePackage>,
849 plugin_result: plugins::AggregatedPluginResult,
850 plugins_ms: f64,
851 scripts_ms: f64,
852}
853
854impl DeadCodeBackendPrelude<'_> {
855 #[must_use]
856 pub fn timings(&self) -> DeadCodePreludeTimings {
857 DeadCodePreludeTimings {
858 discover_ms: self.discovery.discover_ms,
859 workspaces_ms: self.discovery.workspaces_ms,
860 plugins_ms: self.plugins_ms,
861 scripts_ms: self.scripts_ms,
862 }
863 }
864
865 #[must_use]
866 pub fn elapsed_ms(&self) -> f64 {
867 self.pipeline_start.elapsed().as_secs_f64() * 1000.0
868 }
869
870 #[must_use]
871 pub fn script_used_packages(&self) -> FxHashSet<String> {
872 self.plugin_result.script_used_packages.clone()
873 }
874
875 #[must_use]
878 pub fn trace_provenance(
879 &self,
880 modules: &[extract::ModuleInfo],
881 retain_graph: bool,
882 ) -> fallow_types::trace::TraceProvenance {
883 plugins::build_trace_provenance(
884 &self.config.root,
885 self.discovery.files(),
886 self.discovery.workspaces(),
887 modules,
888 &self.plugin_result,
889 plugins::ExportCredits::for_run(retain_graph, self.config),
890 )
891 }
892
893 #[must_use]
896 pub const fn plugin_result(&self) -> &plugins::AggregatedPluginResult {
897 &self.plugin_result
898 }
899
900 pub fn finish(&self) {
901 self.progress.finish();
902 }
903}
904
905#[doc(hidden)]
907pub struct DeadCodeEntryPoints {
908 inner: TimedEntryPoints,
909}
910
911impl DeadCodeEntryPoints {
912 #[must_use]
913 pub fn count(&self) -> usize {
914 self.inner.count
915 }
916
917 #[must_use]
918 pub fn elapsed_ms(&self) -> f64 {
919 self.inner.elapsed_ms
920 }
921
922 #[must_use]
924 pub fn spans(&self) -> EntryPointSpans {
925 self.inner.spans
926 }
927
928 #[must_use]
930 pub fn all(&self) -> &[discover::EntryPoint] {
931 &self.inner.entry_points.all
932 }
933}
934
935#[doc(hidden)]
937pub struct DeadCodeResolvedModules {
938 pub project: resolve::ResolvedProject,
939 pub elapsed_ms: f64,
940}
941
942#[doc(hidden)]
944pub struct DeadCodeGraphRun {
945 pub graph: graph::ModuleGraph,
946 pub elapsed_ms: f64,
947}
948
949#[doc(hidden)]
951pub struct DeadCodeDetectorRun {
952 pub results: AnalysisResults,
953 pub elapsed_ms: f64,
954}
955
956pub fn prepare_dead_code_backend_prelude(
962 config: &ResolvedConfig,
963 discovery: AnalysisDiscovery,
964) -> Result<DeadCodeBackendPrelude<'_>, FallowError> {
965 let progress = new_analysis_progress(config);
966 let pipeline_start = Instant::now();
967 let workspace_pkgs = load_workspace_packages(&discovery.workspaces);
968 let (plugin_result, plugins_ms, scripts_ms) = run_plugins_and_scripts(&PluginScriptInput {
969 config,
970 progress: &progress,
971 files: discovery.files(),
972 workspaces: &discovery.workspaces,
973 root_pkg: discovery.root_pkg.as_ref(),
974 workspace_pkgs: &workspace_pkgs,
975 config_candidates: &discovery.config_candidates,
976 })?;
977
978 Ok(DeadCodeBackendPrelude {
979 config,
980 pipeline_start,
981 progress,
982 discovery,
983 workspace_pkgs,
984 plugin_result,
985 plugins_ms,
986 scripts_ms,
987 })
988}
989
990#[must_use]
992pub fn discover_dead_code_entry_points(
993 prelude: &DeadCodeBackendPrelude<'_>,
994) -> DeadCodeEntryPoints {
995 let shared = prelude.shared_input();
996 DeadCodeEntryPoints {
997 inner: discover_analysis_entry_points(&shared),
998 }
999}
1000
1001pub fn try_load_dead_code_graph_cache(
1011 prelude: &DeadCodeBackendPrelude<'_>,
1012 entry_points: &DeadCodeEntryPoints,
1013 modules: &[extract::ModuleInfo],
1014) -> Result<(DeadCodeResolvedModules, DeadCodeGraphRun), Option<CacheRejection>> {
1015 let shared = prelude.shared_input();
1016 try_load_analysis_graph_cache(&shared, &entry_points.inner, modules).map(|hit| {
1017 (
1018 DeadCodeResolvedModules {
1019 project: hit.project,
1020 elapsed_ms: 0.0,
1021 },
1022 DeadCodeGraphRun {
1023 graph: hit.graph,
1024 elapsed_ms: hit.elapsed_ms,
1025 },
1026 )
1027 })
1028}
1029
1030#[must_use]
1032pub fn resolve_dead_code_imports(
1033 prelude: &DeadCodeBackendPrelude<'_>,
1034 modules: &[extract::ModuleInfo],
1035) -> DeadCodeResolvedModules {
1036 let shared = prelude.shared_input();
1037 let resolved = resolve_analysis_imports_timed(&shared, modules);
1038 DeadCodeResolvedModules {
1039 project: resolved.project,
1040 elapsed_ms: resolved.elapsed_ms,
1041 }
1042}
1043
1044#[must_use]
1046pub fn build_dead_code_graph(
1047 prelude: &DeadCodeBackendPrelude<'_>,
1048 project: &resolve::ResolvedProject,
1049 entry_points: &DeadCodeEntryPoints,
1050 modules: &[extract::ModuleInfo],
1051) -> DeadCodeGraphRun {
1052 let shared = prelude.shared_input();
1053 let graph = build_analysis_graph_timed(&shared, project, &entry_points.inner, modules);
1054 DeadCodeGraphRun {
1055 graph: graph.graph,
1056 elapsed_ms: graph.elapsed_ms,
1057 }
1058}
1059
1060#[must_use]
1062pub fn run_dead_code_detectors(
1063 prelude: &DeadCodeBackendPrelude<'_>,
1064 graph: &graph::ModuleGraph,
1065 resolved: &[resolve::ResolvedModule],
1066 modules: &[extract::ModuleInfo],
1067 collect_usages: bool,
1068 entry_points: &DeadCodeEntryPoints,
1069) -> DeadCodeDetectorRun {
1070 let shared = prelude.shared_input();
1071 let analysis = analyze_dead_code_timed(
1072 &shared,
1073 graph,
1074 resolved,
1075 modules,
1076 collect_usages,
1077 entry_points.inner.summary.clone(),
1078 );
1079 DeadCodeDetectorRun {
1080 results: analysis.result,
1081 elapsed_ms: analysis.elapsed_ms,
1082 }
1083}
1084
1085impl<'a> DeadCodeBackendPrelude<'a> {
1086 fn shared_input(&'a self) -> AnalysisCoreSharedInput<'a> {
1087 AnalysisCoreSharedInput {
1088 config: self.config,
1089 progress: &self.progress,
1090 files: self.discovery.files(),
1091 workspaces: &self.discovery.workspaces,
1092 root_pkg: self.discovery.root_pkg.as_ref(),
1093 workspace_pkgs: &self.workspace_pkgs,
1094 plugin_result: &self.plugin_result,
1095 }
1096 }
1097}
1098
1099struct PreludeMetrics {
1102 discover_ms: f64,
1103 workspaces_ms: f64,
1104 plugins_ms: f64,
1105 scripts_ms: f64,
1106 total_ms: f64,
1107 file_count: usize,
1108 workspace_count: usize,
1109 module_count: usize,
1110}
1111
1112#[expect(
1114 clippy::struct_field_names,
1115 reason = "timings are all milliseconds; the _ms suffix is the unit"
1116)]
1117struct PreludeTimings {
1118 discover_ms: f64,
1119 workspaces_ms: f64,
1120 plugins_ms: f64,
1121 scripts_ms: f64,
1122}
1123
1124fn prelude_metrics(
1127 timings: &PreludeTimings,
1128 pipeline_start: Instant,
1129 files: &[discover::DiscoveredFile],
1130 workspaces: &[fallow_config::WorkspaceInfo],
1131 module_count: usize,
1132) -> PreludeMetrics {
1133 PreludeMetrics {
1134 discover_ms: timings.discover_ms,
1135 workspaces_ms: timings.workspaces_ms,
1136 plugins_ms: timings.plugins_ms,
1137 scripts_ms: timings.scripts_ms,
1138 total_ms: pipeline_start.elapsed().as_secs_f64() * 1000.0,
1139 file_count: files.len(),
1140 workspace_count: workspaces.len(),
1141 module_count,
1142 }
1143}
1144
1145struct AnalysisCoreSharedInput<'a> {
1146 config: &'a ResolvedConfig,
1147 progress: &'a progress::AnalysisProgress,
1148 files: &'a [discover::DiscoveredFile],
1149 workspaces: &'a [fallow_config::WorkspaceInfo],
1150 root_pkg: Option<&'a PackageJson>,
1151 workspace_pkgs: &'a [LoadedWorkspacePackage],
1152 plugin_result: &'a plugins::AggregatedPluginResult,
1153}
1154
1155struct TimedEntryPoints {
1156 entry_points: discover::CategorizedEntryPoints,
1157 summary: results::EntryPointSummary,
1158 count: usize,
1159 elapsed_ms: f64,
1160 spans: EntryPointSpans,
1161}
1162
1163struct TimedResolvedModules {
1164 project: resolve::ResolvedProject,
1165 elapsed_ms: f64,
1166}
1167
1168struct TimedGraph {
1169 graph: graph::ModuleGraph,
1170 elapsed_ms: f64,
1171}
1172
1173struct GraphCacheHit {
1174 graph: graph::ModuleGraph,
1175 project: resolve::ResolvedProject,
1176 elapsed_ms: f64,
1177}
1178
1179#[derive(Clone, Copy)]
1180struct DiscoverAllEntryPointsInput<'a> {
1181 config: &'a ResolvedConfig,
1182 files: &'a [discover::DiscoveredFile],
1183 workspaces: &'a [fallow_config::WorkspaceInfo],
1184 root_pkg: Option<&'a PackageJson>,
1185 workspace_pkgs: &'a [LoadedWorkspacePackage],
1186 plugin_result: &'a plugins::AggregatedPluginResult,
1187}
1188
1189struct TimedAnalysis {
1190 result: AnalysisResults,
1191 elapsed_ms: f64,
1192}
1193
1194fn discover_analysis_entry_points(input: &AnalysisCoreSharedInput<'_>) -> TimedEntryPoints {
1195 let t = Instant::now();
1196 let (entry_points, spans) = discover_all_entry_points(DiscoverAllEntryPointsInput {
1197 config: input.config,
1198 files: input.files,
1199 workspaces: input.workspaces,
1200 root_pkg: input.root_pkg,
1201 workspace_pkgs: input.workspace_pkgs,
1202 plugin_result: input.plugin_result,
1203 });
1204 let elapsed_ms = t.elapsed().as_secs_f64() * 1000.0;
1205 let summary = discover::summarize_entry_points(&entry_points.all);
1206 let count = entry_points.all.len();
1207
1208 TimedEntryPoints {
1209 entry_points,
1210 summary,
1211 count,
1212 elapsed_ms,
1213 spans,
1214 }
1215}
1216
1217fn try_load_analysis_graph_cache(
1227 input: &AnalysisCoreSharedInput<'_>,
1228 entry_points: &TimedEntryPoints,
1229 modules: &[extract::ModuleInfo],
1230) -> Result<GraphCacheHit, Option<CacheRejection>> {
1231 if input.config.no_cache {
1232 return Err(None);
1233 }
1234
1235 let t = Instant::now();
1236 input.progress.set_stage("loading module graph cache...");
1237 let unseeded_declaration_files = orphan_module_declaration_files(input, modules);
1238 let current = build_graph_cache_manifest(&GraphCacheManifestInput {
1239 config: input.config,
1240 plugin_result: input.plugin_result,
1241 entry_points: &entry_points.entry_points,
1242 files: input.files,
1243 workspaces: input.workspaces,
1244 modules,
1245 unseeded_declaration_files: &unseeded_declaration_files,
1246 });
1247 let store = graph_cache::GraphCacheStore::load(&input.config.cache_dir).map_err(Some)?;
1248 if store.manifest.matches_inputs(¤t) {
1249 let project = restore_cached_resolved_project(input, modules, &store.resolved_project)?;
1250 tracing::debug!("Graph cache hit: skipping import resolution and graph build");
1251 let mut graph = store.graph;
1252 credit_bin_path_references(
1253 &mut graph,
1254 modules,
1255 &input.plugin_result.dependency_binaries,
1256 );
1257
1258 return Ok(GraphCacheHit {
1259 graph,
1260 project,
1261 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1262 });
1263 }
1264
1265 if let Some(rejection) = store.manifest.classify_resolution_mismatch(¤t) {
1266 if rejection.discarded_existing_work() {
1270 tracing::warn!(
1271 target: fallow_types::ANALYSIS_DIAGNOSTIC_LOG_TARGET,
1272 "Graph cache decoded but not reused: {}",
1273 rejection.describe()
1274 );
1275 } else {
1276 tracing::debug!(
1277 "Graph cache decoded but not reused: {}",
1278 rejection.describe()
1279 );
1280 }
1281 return Err(Some(rejection));
1282 }
1283
1284 let project = restore_cached_resolved_project(input, modules, &store.resolved_project)?;
1285 tracing::debug!("Graph resolver cache hit: skipping import resolution and rebuilding graph");
1286 let graph = build_analysis_graph_timed(input, &project, entry_points, modules);
1287
1288 Ok(GraphCacheHit {
1289 graph: graph.graph,
1290 project,
1291 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1292 })
1293}
1294
1295fn restore_cached_resolved_project(
1301 input: &AnalysisCoreSharedInput<'_>,
1302 modules: &[extract::ModuleInfo],
1303 resolved_project: &graph_cache::CachedResolvedProject,
1304) -> Result<resolve::ResolvedProject, Option<CacheRejection>> {
1305 graph_cache::restore_resolved_project(
1306 &input.config.root,
1307 modules,
1308 input.files,
1309 resolved_project,
1310 )
1311 .inspect(|project| {
1312 record_unreadable_auto_import_reads(
1313 project,
1314 input.files,
1315 input.plugin_result,
1316 input.config,
1317 );
1318 })
1319 .ok_or_else(|| {
1320 tracing::debug!(
1324 "Graph cache decoded but its resolver payload no longer maps to the discovered files"
1325 );
1326 Some(CacheRejection::FileSetChanged)
1327 })
1328}
1329
1330fn resolve_analysis_imports_timed(
1331 input: &AnalysisCoreSharedInput<'_>,
1332 modules: &[extract::ModuleInfo],
1333) -> TimedResolvedModules {
1334 let t = Instant::now();
1335 input.progress.set_stage("resolving imports...");
1336 let project = resolve_analysis_imports(
1337 modules,
1338 input.files,
1339 input.workspaces,
1340 input.plugin_result,
1341 input.config,
1342 );
1343 TimedResolvedModules {
1344 project,
1345 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1346 }
1347}
1348
1349fn build_analysis_graph_timed(
1350 input: &AnalysisCoreSharedInput<'_>,
1351 project: &resolve::ResolvedProject,
1352 entry_points: &TimedEntryPoints,
1353 modules: &[extract::ModuleInfo],
1354) -> TimedGraph {
1355 let t = Instant::now();
1356 input.progress.set_stage("building module graph...");
1357 let unseeded_declaration_files = orphan_module_declaration_files(input, modules);
1358 let mut graph = build_analysis_graph(&BuildAnalysisGraphInput {
1359 config: input.config,
1360 plugin_result: input.plugin_result,
1361 project,
1362 entry_points: &entry_points.entry_points,
1363 files: input.files,
1364 modules,
1365 workspaces: input.workspaces,
1366 unseeded_declaration_files: &unseeded_declaration_files,
1367 });
1368 credit_bin_path_references(
1369 &mut graph,
1370 modules,
1371 &input.plugin_result.dependency_binaries,
1372 );
1373 TimedGraph {
1374 graph,
1375 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1376 }
1377}
1378
1379fn orphan_module_declaration_files(
1382 input: &AnalysisCoreSharedInput<'_>,
1383 modules: &[extract::ModuleInfo],
1384) -> FxHashSet<discover::FileId> {
1385 discover::find_orphan_module_declaration_files(&input.config.root, input.files, modules)
1386}
1387
1388fn release_resolution_payloads(modules: &mut [extract::ModuleInfo]) {
1389 for module in modules {
1390 module.release_resolution_payload();
1391 }
1392}
1393
1394fn analyze_dead_code_timed(
1395 input: &AnalysisCoreSharedInput<'_>,
1396 graph: &graph::ModuleGraph,
1397 resolved: &[resolve::ResolvedModule],
1398 modules: &[extract::ModuleInfo],
1399 collect_usages: bool,
1400 entry_point_summary: results::EntryPointSummary,
1401) -> TimedAnalysis {
1402 let t = Instant::now();
1403 input.progress.set_stage("analyzing...");
1404 let mut result = analyze::find_dead_code_full(
1405 graph,
1406 input.config,
1407 resolved,
1408 Some(input.plugin_result),
1409 input.workspaces,
1410 modules,
1411 collect_usages,
1412 );
1413 result.entry_point_summary = Some(entry_point_summary);
1414 TimedAnalysis {
1415 result,
1416 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1417 }
1418}
1419
1420fn analyze_full(
1421 config: &ResolvedConfig,
1422 retain: bool,
1423 collect_usages: bool,
1424 need_complexity: bool,
1425 retain_modules: bool,
1426) -> Result<AnalysisOutput, FallowError> {
1427 let _span = tracing::info_span!("fallow_analyze").entered();
1428 AnalysisSession::new(config)?.run_full(retain, collect_usages, need_complexity, retain_modules)
1429}
1430
1431fn full_analysis_pipeline_profile(
1432 timings: &PreludeTimings,
1433 pipeline_start: Instant,
1434 files: &[discover::DiscoveredFile],
1435 workspaces: &[fallow_config::WorkspaceInfo],
1436 core: &OwnedAnalysisCore,
1437 metrics: &ParseMetrics,
1438) -> PipelineProfile {
1439 let prelude = prelude_metrics(
1440 timings,
1441 pipeline_start,
1442 files,
1443 workspaces,
1444 core.modules.len(),
1445 );
1446 full_pipeline_profile(&prelude, core, metrics)
1447}
1448
1449fn assemble_full_output(
1452 core: OwnedAnalysisCore,
1453 plugin_result: plugins::AggregatedPluginResult,
1454 profile: &PipelineProfile,
1455 files: &[discover::DiscoveredFile],
1456 retain: bool,
1457 retain_modules: bool,
1458) -> AnalysisOutput {
1459 let file_hashes = collect_file_hashes(&core.modules, files);
1460 AnalysisOutput {
1461 results: core.result,
1462 timings: retained_pipeline_timings(retain, profile),
1463 graph: if retain { Some(core.graph) } else { None },
1464 modules: if retain_modules {
1465 Some(core.modules)
1466 } else {
1467 None
1468 },
1469 files: if retain_modules {
1470 Some(files.to_vec())
1471 } else {
1472 None
1473 },
1474 script_used_packages: plugin_result.script_used_packages,
1475 trace_provenance: fallow_types::trace::TraceProvenance::default(),
1476 file_hashes,
1477 }
1478}
1479
1480struct OwnedAnalysisCore {
1483 result: AnalysisResults,
1484 graph: graph::ModuleGraph,
1485 modules: Vec<extract::ModuleInfo>,
1486 entry_point_count: usize,
1487 entry_points_ms: f64,
1488 entry_point_spans: EntryPointSpans,
1489 resolve_ms: f64,
1490 graph_ms: f64,
1491 analyze_ms: f64,
1492 graph_cache_rejection: Option<CacheRejection>,
1493 resolve_work: resolve::ResolveWork,
1494}
1495
1496fn full_pipeline_profile(
1498 prelude: &PreludeMetrics,
1499 core: &OwnedAnalysisCore,
1500 parse: &ParseMetrics,
1501) -> PipelineProfile {
1502 PipelineProfile {
1503 discover_ms: prelude.discover_ms,
1504 workspaces_ms: prelude.workspaces_ms,
1505 plugins_ms: prelude.plugins_ms,
1506 scripts_ms: prelude.scripts_ms,
1507 parse_ms: parse.parse_ms,
1508 cache_ms: parse.cache_ms,
1509 entry_points_ms: core.entry_points_ms,
1510 entry_point_spans: core.entry_point_spans,
1511 resolve_ms: core.resolve_ms,
1512 graph_ms: core.graph_ms,
1513 analyze_ms: core.analyze_ms,
1514 total_ms: prelude.total_ms,
1515 file_count: prelude.file_count,
1516 workspace_count: prelude.workspace_count,
1517 module_count: prelude.module_count,
1518 entry_point_count: core.entry_point_count,
1519 cache_hits: parse.cache_hits,
1520 cache_misses: parse.cache_misses,
1521 parse_cpu_ms: parse.parse_cpu_ms,
1522 parse_cache_load_ms: parse.parse_cache_load_ms,
1523 cache_rejection: parse.cache_rejection,
1524 graph_cache_rejection: core.graph_cache_rejection,
1525 counters: PipelineCounters {
1526 files_read: parse.files_read,
1527 source_bytes_read: parse.source_bytes_read,
1528 parse_cache_bytes_read: parse.parse_cache_bytes_read,
1529 css_masked_bytes: parse.css_masked_bytes,
1530 resolve_specifier_calls: core.resolve_work.specifier_calls,
1531 unique_specifiers: core.resolve_work.unique_specifiers,
1532 oxc_resolve_calls: core.resolve_work.oxc_resolve_calls,
1533 canonicalize_calls: core.resolve_work.canonicalize_calls,
1534 },
1535 }
1536}
1537
1538#[derive(Clone, Copy)]
1539struct PipelineProfile {
1540 discover_ms: f64,
1541 workspaces_ms: f64,
1542 plugins_ms: f64,
1543 scripts_ms: f64,
1544 parse_ms: f64,
1545 cache_ms: f64,
1546 entry_points_ms: f64,
1547 entry_point_spans: EntryPointSpans,
1548 resolve_ms: f64,
1549 graph_ms: f64,
1550 analyze_ms: f64,
1551 total_ms: f64,
1552 file_count: usize,
1553 workspace_count: usize,
1554 module_count: usize,
1555 entry_point_count: usize,
1556 cache_hits: usize,
1557 cache_misses: usize,
1558 parse_cpu_ms: f64,
1559 parse_cache_load_ms: f64,
1560 cache_rejection: Option<CacheRejection>,
1561 graph_cache_rejection: Option<CacheRejection>,
1562 counters: PipelineCounters,
1563}
1564
1565struct AnalysisParseOutput {
1566 modules: Vec<extract::ModuleInfo>,
1567 metrics: ParseMetrics,
1568}
1569
1570struct ParseMetrics {
1572 parse_ms: f64,
1573 cache_ms: f64,
1574 cache_hits: usize,
1575 cache_misses: usize,
1576 parse_cpu_ms: f64,
1577 cache_rejection: Option<CacheRejection>,
1579 files_read: u64,
1580 source_bytes_read: u64,
1581 parse_cache_bytes_read: u64,
1582 css_masked_bytes: u64,
1583 parse_cache_load_ms: f64,
1584}
1585
1586impl From<AnalysisParseMetrics> for ParseMetrics {
1587 fn from(metrics: AnalysisParseMetrics) -> Self {
1588 Self {
1589 parse_ms: metrics.parse_ms,
1590 cache_ms: metrics.cache_ms,
1591 cache_hits: metrics.cache_hits,
1592 cache_misses: metrics.cache_misses,
1593 parse_cpu_ms: metrics.parse_cpu_ms,
1594 cache_rejection: metrics.cache_rejection,
1595 files_read: 0,
1596 source_bytes_read: 0,
1597 parse_cache_bytes_read: 0,
1598 css_masked_bytes: 0,
1599 parse_cache_load_ms: 0.0,
1600 }
1601 }
1602}
1603
1604fn parse_analysis_modules(
1605 config: &ResolvedConfig,
1606 files: &[discover::DiscoveredFile],
1607 need_complexity: bool,
1608 start: Instant,
1609) -> AnalysisParseOutput {
1610 let cache_max_size_bytes = resolve_cache_max_size_bytes(config);
1611 let mut cache_rejection = None;
1612 let mut parse_cache_bytes_read = 0;
1613 let mut parse_cache_load_ms = 0.0;
1614 let mut cache_store = if config.no_cache {
1615 None
1616 } else {
1617 let load_start = Instant::now();
1618 let (loaded, bytes_read) = cache::CacheStore::load_counting_bytes(
1619 &config.cache_dir,
1620 &config.root,
1621 config.cache_config_hash,
1622 cache_max_size_bytes,
1623 );
1624 parse_cache_bytes_read = bytes_read;
1625 parse_cache_load_ms = load_start.elapsed().as_secs_f64() * 1000.0;
1626 match loaded {
1627 Ok(store) => Some(store),
1628 Err(rejection) => {
1629 cache_rejection = Some(rejection);
1630 None
1631 }
1632 }
1633 };
1634
1635 let read_started_ns = fallow_types::source_fingerprint::now_ns();
1636 let parse_result = extract::parse_all_files_cancellable(
1637 files,
1638 cache_store.as_ref(),
1639 need_complexity,
1640 None,
1641 &config.flags.patterns(),
1642 );
1643 let _ = fallow_config::record_source_read_failures(&config.root, &parse_result.read_failures);
1644 let _ =
1645 fallow_config::record_source_parse_degradations(config, &parse_result.parse_degradations);
1646 let modules = parse_result.modules;
1647 let parse_ms = start.elapsed().as_secs_f64() * 1000.0;
1648 let cache_ms = update_parse_cache_if_enabled(
1649 config,
1650 &mut cache_store,
1651 &modules,
1652 files,
1653 need_complexity,
1654 read_started_ns,
1655 );
1656
1657 AnalysisParseOutput {
1658 modules,
1659 metrics: ParseMetrics {
1660 parse_ms,
1661 cache_ms,
1662 cache_hits: parse_result.cache_hits,
1663 cache_misses: parse_result.cache_misses,
1664 parse_cpu_ms: parse_result.parse_cpu_ms,
1665 cache_rejection,
1666 files_read: parse_result.files_read,
1667 source_bytes_read: parse_result.source_bytes_read,
1668 parse_cache_bytes_read,
1669 css_masked_bytes: parse_result.css_masked_bytes,
1670 parse_cache_load_ms,
1671 },
1672 }
1673}
1674
1675fn retained_pipeline_timings(retain: bool, profile: &PipelineProfile) -> Option<PipelineTimings> {
1676 retain.then_some(PipelineTimings {
1677 discover_files_ms: profile.discover_ms,
1678 file_count: profile.file_count,
1679 workspaces_ms: profile.workspaces_ms,
1680 workspace_count: profile.workspace_count,
1681 plugins_ms: profile.plugins_ms,
1682 script_analysis_ms: profile.scripts_ms,
1683 parse_extract_ms: profile.parse_ms,
1684 parse_cpu_ms: profile.parse_cpu_ms,
1685 parse_cache_load_ms: profile.parse_cache_load_ms,
1686 module_count: profile.module_count,
1687 cache_hits: profile.cache_hits,
1688 cache_misses: profile.cache_misses,
1689 cache_rejection: profile.cache_rejection,
1690 graph_cache_rejection: profile.graph_cache_rejection,
1691 cache_update_ms: profile.cache_ms,
1692 entry_points_ms: profile.entry_points_ms,
1693 entry_point_spans: profile.entry_point_spans,
1694 entry_point_count: profile.entry_point_count,
1695 resolve_imports_ms: profile.resolve_ms,
1696 build_graph_ms: profile.graph_ms,
1697 analyze_ms: profile.analyze_ms,
1698 duplication_ms: None,
1699 total_ms: profile.total_ms,
1700 counters: profile.counters,
1701 })
1702}
1703
1704fn update_parse_cache_if_enabled(
1705 config: &ResolvedConfig,
1706 cache_store: &mut Option<cache::CacheStore>,
1707 modules: &[extract::ModuleInfo],
1708 files: &[discover::DiscoveredFile],
1709 need_complexity: bool,
1710 read_started_ns: u64,
1711) -> f64 {
1712 let t = Instant::now();
1713 if !config.no_cache {
1714 let cache_max_size_bytes = resolve_cache_max_size_bytes(config);
1715 let store = cache_store.get_or_insert_with(|| cache::CacheStore::new(&config.root));
1716 if update_cache(store, modules, files, need_complexity, read_started_ns)
1717 && let Err(error) = store.save(
1718 &config.cache_dir,
1719 config.cache_config_hash,
1720 cache_max_size_bytes,
1721 )
1722 {
1723 tracing::warn!("Failed to save cache: {error}");
1724 }
1725 }
1726 t.elapsed().as_secs_f64() * 1000.0
1727}
1728
1729fn resolve_analysis_imports(
1730 modules: &[extract::ModuleInfo],
1731 files: &[discover::DiscoveredFile],
1732 workspaces: &[fallow_config::WorkspaceInfo],
1733 plugin_result: &plugins::AggregatedPluginResult,
1734 config: &ResolvedConfig,
1735) -> resolve::ResolvedProject {
1736 let mut project = resolve::resolve_all_imports(&resolve::ResolveAllImportsInput {
1737 modules,
1738 files,
1739 workspaces,
1740 active_plugins: &plugin_result.active_plugins,
1741 path_aliases: &plugin_result.path_aliases,
1742 auto_imports: &plugin_result.auto_imports,
1743 jsx_import_sources: &plugin_result.jsx_import_sources,
1744 scss_include_paths: &plugin_result.scss_include_paths,
1745 static_dir_mappings: &plugin_result.static_dir_mappings,
1746 framework_static_dir_mappings: &plugin_result.framework_static_dir_mappings,
1747 root: &config.root,
1748 extra_conditions: &config.resolve.conditions,
1749 });
1750 external_style_usage::augment_external_style_package_usage(
1751 &mut project.modules,
1752 config,
1753 workspaces,
1754 plugin_result,
1755 );
1756 record_unreadable_auto_import_reads(&project, files, plugin_result, config);
1757 project
1758}
1759
1760fn record_unreadable_auto_import_reads(
1772 project: &resolve::ResolvedProject,
1773 files: &[discover::DiscoveredFile],
1774 plugin_result: &plugins::AggregatedPluginResult,
1775 config: &ResolvedConfig,
1776) {
1777 if !config.auto_imports
1778 || plugin_result.auto_imports.is_empty()
1779 || !plugin_result
1780 .active_plugins
1781 .iter()
1782 .any(|name| name == "nuxt")
1783 {
1784 return;
1785 }
1786 let diagnostics: Vec<fallow_config::WorkspaceDiagnostic> =
1787 resolve::unreadable_auto_import_reads(&project.modules)
1788 .into_iter()
1789 .filter_map(|read| {
1790 let file = files.get(read.file_id.0 as usize)?;
1791 let diagnostic = plugins::PluginConfigDiagnostic::not_modeled(
1792 &file.path,
1793 "nuxt",
1794 read.module,
1795 AUTO_IMPORT_KEY_NOT_MODELED,
1796 );
1797 Some(diagnostic.into_workspace_diagnostic(&config.root))
1798 })
1799 .collect();
1800 fallow_config::append_workspace_diagnostics(&config.root, diagnostics);
1801}
1802
1803struct BuildAnalysisGraphInput<'a> {
1804 config: &'a ResolvedConfig,
1805 plugin_result: &'a plugins::AggregatedPluginResult,
1806 project: &'a resolve::ResolvedProject,
1807 entry_points: &'a discover::CategorizedEntryPoints,
1808 files: &'a [discover::DiscoveredFile],
1809 modules: &'a [extract::ModuleInfo],
1810 workspaces: &'a [fallow_config::WorkspaceInfo],
1811 unseeded_declaration_files: &'a FxHashSet<discover::FileId>,
1812}
1813
1814fn build_analysis_graph(input: &BuildAnalysisGraphInput<'_>) -> graph::ModuleGraph {
1822 let caching_enabled = !input.config.no_cache;
1823 let current_manifest = caching_enabled.then(|| {
1824 build_graph_cache_manifest(&GraphCacheManifestInput {
1825 config: input.config,
1826 plugin_result: input.plugin_result,
1827 entry_points: input.entry_points,
1828 files: input.files,
1829 workspaces: input.workspaces,
1830 modules: input.modules,
1831 unseeded_declaration_files: input.unseeded_declaration_files,
1832 })
1833 });
1834
1835 let mut graph = graph::ModuleGraph::build_with_declaration_seeding(
1836 &input.project.modules,
1837 &input.project.replaced_module_targets,
1838 &graph::ReachabilityRoots {
1839 all: &input.entry_points.all,
1840 runtime: &input.entry_points.runtime,
1841 test: &input.entry_points.test,
1842 },
1843 input.files,
1844 input.unseeded_declaration_files,
1845 );
1846 credit_package_path_references(&mut graph, input.modules);
1847 credit_workspace_package_usage(&mut graph, &input.project.modules, input.workspaces);
1848
1849 if let Some(manifest) = current_manifest {
1850 let Some(resolved_project) =
1851 graph_cache::cache_resolved_project(&input.config.root, input.files, input.project)
1852 else {
1853 return graph;
1854 };
1855 let store = graph_cache::GraphCacheStore {
1856 version: graph_cache::GRAPH_CACHE_VERSION,
1857 manifest,
1858 graph,
1859 resolved_project,
1860 };
1861 store.save(&input.config.cache_dir);
1862 return store.graph;
1867 }
1868
1869 graph
1870}
1871
1872struct GraphCacheManifestInput<'a> {
1874 config: &'a ResolvedConfig,
1875 plugin_result: &'a plugins::AggregatedPluginResult,
1876 entry_points: &'a discover::CategorizedEntryPoints,
1877 files: &'a [discover::DiscoveredFile],
1878 workspaces: &'a [fallow_config::WorkspaceInfo],
1879 modules: &'a [extract::ModuleInfo],
1880 unseeded_declaration_files: &'a FxHashSet<discover::FileId>,
1881}
1882
1883fn build_graph_cache_manifest(
1886 input: &GraphCacheManifestInput<'_>,
1887) -> graph_cache::GraphCacheManifest {
1888 let GraphCacheManifestInput {
1889 config,
1890 plugin_result,
1891 entry_points,
1892 files,
1893 workspaces,
1894 modules,
1895 unseeded_declaration_files,
1896 } = *input;
1897 let mode = graph_cache::GraphCacheMode::new(
1898 resolver_options_hash(config, workspaces, files),
1899 entry_points_hash(
1900 entry_points,
1901 files,
1902 unseeded_declaration_files,
1903 &config.root,
1904 ),
1905 plugin_config_hash(plugin_result, &config.root),
1906 );
1907 let mut content_hashes = vec![0u64; files.len()];
1912 for module in modules {
1913 if let Some(slot) = content_hashes.get_mut(module.file_id.0 as usize) {
1914 *slot = module.content_hash;
1915 }
1916 }
1917 graph_cache::GraphCacheManifest::from_discovered_files(&config.root, files, mode, |file| {
1918 content_hashes
1919 .get(file.id.0 as usize)
1920 .copied()
1921 .unwrap_or_default()
1922 })
1923}
1924
1925fn resolver_options_hash(
1950 config: &ResolvedConfig,
1951 workspaces: &[fallow_config::WorkspaceInfo],
1952 files: &[discover::DiscoveredFile],
1953) -> u64 {
1954 use std::hash::{Hash, Hasher};
1955 let mut hasher = rustc_hash::FxHasher::default();
1956 config.cache_config_hash.hash(&mut hasher);
1957 config.resolve.conditions.hash(&mut hasher);
1958 resolution_inputs::resolution_inputs_hash(&config.root, workspaces, files).hash(&mut hasher);
1959 hasher.finish()
1960}
1961
1962fn root_relative_key(root: &std::path::Path, path: &std::path::Path) -> String {
1966 path.strip_prefix(root)
1967 .unwrap_or(path)
1968 .to_string_lossy()
1969 .replace('\\', "/")
1970}
1971
1972fn entry_points_hash(
1977 entry_points: &discover::CategorizedEntryPoints,
1978 files: &[discover::DiscoveredFile],
1979 unseeded_declaration_files: &FxHashSet<discover::FileId>,
1980 root: &std::path::Path,
1981) -> u64 {
1982 use std::hash::{Hash, Hasher};
1983 let mut hasher = rustc_hash::FxHasher::default();
1984 for role in [&entry_points.all, &entry_points.runtime, &entry_points.test] {
1985 let mut keys: Vec<String> = role
1986 .iter()
1987 .map(|ep| root_relative_key(root, &ep.path))
1988 .collect();
1989 keys.sort_unstable();
1990 keys.len().hash(&mut hasher);
1991 for key in keys {
1992 key.hash(&mut hasher);
1993 }
1994 }
1995 let mut unseeded: Vec<String> = files
1996 .iter()
1997 .filter(|file| unseeded_declaration_files.contains(&file.id))
1998 .map(|file| root_relative_key(root, &file.path))
1999 .collect();
2000 unseeded.sort_unstable();
2001 unseeded.len().hash(&mut hasher);
2002 for key in unseeded {
2003 key.hash(&mut hasher);
2004 }
2005 hasher.finish()
2006}
2007
2008fn plugin_config_hash(
2011 plugin_result: &plugins::AggregatedPluginResult,
2012 root: &std::path::Path,
2013) -> u64 {
2014 use std::hash::{Hash, Hasher};
2015 let mut hasher = rustc_hash::FxHasher::default();
2016
2017 hash_active_plugins(plugin_result, &mut hasher);
2018 hash_path_aliases(plugin_result, root, &mut hasher);
2019
2020 let mut auto_imports: Vec<AutoImportHashKey<'_>> = plugin_result
2021 .auto_imports
2022 .iter()
2023 .map(|rule| {
2024 let mut scope: Vec<String> = rule
2025 .scope
2026 .iter()
2027 .map(|scope_root| root_relative_key(root, scope_root))
2028 .collect();
2029 scope.sort_unstable();
2030 (
2031 rule.name.as_str(),
2032 root_relative_key(root, &rule.source),
2033 auto_import_kind_rank(rule.kind),
2034 scope,
2035 )
2036 })
2037 .collect();
2038 auto_imports.sort_unstable();
2039 auto_imports.len().hash(&mut hasher);
2040 for key in &auto_imports {
2041 key.hash(&mut hasher);
2042 }
2043
2044 fn sorted(patterns: &[String]) -> Vec<&str> {
2045 let mut patterns: Vec<&str> = patterns.iter().map(String::as_str).collect();
2046 patterns.sort_unstable();
2047 patterns
2048 }
2049 let mut jsx_import_sources: Vec<(&str, String, Vec<&str>, Vec<&str>)> = plugin_result
2050 .jsx_import_sources
2051 .iter()
2052 .map(|rule| {
2053 (
2054 rule.source.as_str(),
2055 root_relative_key(root, &rule.config_dir),
2056 sorted(&rule.include),
2057 sorted(&rule.exclude),
2058 )
2059 })
2060 .collect();
2061 jsx_import_sources.sort_unstable();
2062 jsx_import_sources.dedup();
2063 jsx_import_sources.len().hash(&mut hasher);
2064 for key in &jsx_import_sources {
2065 key.hash(&mut hasher);
2066 }
2067
2068 let mut scss_include_paths: Vec<String> = plugin_result
2069 .scss_include_paths
2070 .iter()
2071 .map(|path| root_relative_key(root, path))
2072 .collect();
2073 scss_include_paths.sort_unstable();
2074 scss_include_paths.len().hash(&mut hasher);
2075 for path in scss_include_paths {
2076 path.hash(&mut hasher);
2077 }
2078
2079 hash_static_dir_mappings(&plugin_result.static_dir_mappings, root, &mut hasher);
2080 hash_static_dir_mappings(
2081 &plugin_result.framework_static_dir_mappings,
2082 root,
2083 &mut hasher,
2084 );
2085
2086 hasher.finish()
2087}
2088
2089fn hash_static_dir_mappings(
2091 mappings: &[(std::path::PathBuf, String)],
2092 root: &std::path::Path,
2093 hasher: &mut rustc_hash::FxHasher,
2094) {
2095 use std::hash::Hash;
2096 let mut keys: Vec<(String, &str)> = mappings
2097 .iter()
2098 .map(|(from_dir, mount)| (root_relative_key(root, from_dir), mount.as_str()))
2099 .collect();
2100 keys.sort_unstable();
2101 keys.len().hash(hasher);
2102 for (from_dir, mount) in keys {
2103 from_dir.hash(hasher);
2104 mount.hash(hasher);
2105 }
2106}
2107
2108fn hash_active_plugins(
2109 plugin_result: &plugins::AggregatedPluginResult,
2110 hasher: &mut rustc_hash::FxHasher,
2111) {
2112 use std::hash::Hash;
2113 let mut active: Vec<&str> = plugin_result
2114 .active_plugins
2115 .iter()
2116 .map(String::as_str)
2117 .collect();
2118 active.sort_unstable();
2119 active.len().hash(hasher);
2120 for name in active {
2121 name.hash(hasher);
2122 }
2123}
2124
2125fn hash_path_aliases(
2129 plugin_result: &plugins::AggregatedPluginResult,
2130 root: &std::path::Path,
2131 hasher: &mut rustc_hash::FxHasher,
2132) {
2133 use std::hash::Hash;
2134 let mut aliases: Vec<(&str, String)> = plugin_result
2135 .path_aliases
2136 .iter()
2137 .map(|(prefix, replacement)| {
2138 (
2139 prefix.as_str(),
2140 root_relative_key(root, std::path::Path::new(replacement)),
2141 )
2142 })
2143 .collect();
2144 aliases.sort_unstable();
2145 aliases.len().hash(hasher);
2146 for (prefix, replacement) in aliases {
2147 prefix.hash(hasher);
2148 replacement.hash(hasher);
2149 }
2150}
2151
2152type AutoImportHashKey<'a> = (&'a str, String, u8, Vec<String>);
2155
2156fn auto_import_kind_rank(kind: fallow_config::AutoImportKind) -> u8 {
2157 match kind {
2158 fallow_config::AutoImportKind::Named => 0,
2159 fallow_config::AutoImportKind::Default => 1,
2160 fallow_config::AutoImportKind::DefaultComponent => 2,
2161 }
2162}
2163
2164fn collect_file_hashes(
2165 modules: &[extract::ModuleInfo],
2166 files: &[discover::DiscoveredFile],
2167) -> rustc_hash::FxHashMap<std::path::PathBuf, u64> {
2168 modules
2169 .iter()
2170 .filter_map(|module| {
2171 files
2172 .get(module.file_id.0 as usize)
2173 .map(|file| (file.path.clone(), module.content_hash))
2174 })
2175 .collect()
2176}
2177
2178fn trace_pipeline_profile(profile: &PipelineProfile) {
2179 let PipelineProfile {
2180 discover_ms,
2181 workspaces_ms,
2182 plugins_ms,
2183 scripts_ms,
2184 parse_ms,
2185 cache_ms,
2186 entry_points_ms,
2187 resolve_ms,
2188 graph_ms,
2189 analyze_ms,
2190 total_ms,
2191 file_count,
2192 module_count,
2193 entry_point_count,
2194 cache_hits,
2195 cache_misses,
2196 cache_rejection,
2197 ..
2198 } = *profile;
2199 let cache_summary = cache_rejection.map_or_else(
2200 || format!(" ({cache_hits} cached, {cache_misses} parsed)"),
2201 |rejection| {
2202 format!(
2203 " ({cache_hits} cached, {cache_misses} parsed, cache refused: {})",
2204 rejection.describe()
2205 )
2206 },
2207 );
2208
2209 tracing::debug!(
2210 "\n┌─ Pipeline Profile ─────────────────────────────\n\
2211 │ discover files: {:>8.1}ms ({} files)\n\
2212 │ workspaces: {:>8.1}ms\n\
2213 │ plugin detection: {:>8.1}ms\n\
2214 │ script analysis: {:>8.1}ms\n\
2215 │ parse/extract: {:>8.1}ms ({} modules{})\n\
2216 │ cache update: {:>8.1}ms\n\
2217 │ entry points: {:>8.1}ms ({} entries)\n\
2218 │ resolve imports: {:>8.1}ms\n\
2219 │ build graph: {:>8.1}ms\n\
2220 │ analyze: {:>8.1}ms\n\
2221 │ ────────────────────────────────────────────\n\
2222 │ TOTAL: {:>8.1}ms\n\
2223 └─────────────────────────────────────────────────",
2224 discover_ms,
2225 file_count,
2226 workspaces_ms,
2227 plugins_ms,
2228 scripts_ms,
2229 parse_ms,
2230 module_count,
2231 cache_summary,
2232 cache_ms,
2233 entry_points_ms,
2234 entry_point_count,
2235 resolve_ms,
2236 graph_ms,
2237 analyze_ms,
2238 total_ms,
2239 );
2240}
2241
2242fn load_workspace_packages(
2243 workspaces: &[fallow_config::WorkspaceInfo],
2244) -> Vec<LoadedWorkspacePackage> {
2245 workspaces
2246 .iter()
2247 .filter_map(|ws| {
2248 fallow_config::load_dir_package_json(&ws.root).map(|pkg| (ws.clone(), pkg))
2249 })
2250 .collect()
2251}
2252
2253fn analyze_all_scripts(
2258 config: &ResolvedConfig,
2259 workspaces: &[fallow_config::WorkspaceInfo],
2260 root_pkg: Option<&PackageJson>,
2261 workspace_pkgs: &[LoadedWorkspacePackage],
2262 plugin_result: &mut plugins::AggregatedPluginResult,
2263) {
2264 let manifests: Vec<&PackageJson> = root_pkg
2265 .into_iter()
2266 .chain(workspace_pkgs.iter().map(|(_, ws_pkg)| ws_pkg))
2267 .collect();
2268 let all_dep_names = scripts::all_dependency_names(&manifests);
2269 let all_dep_set: FxHashSet<String> = all_dep_names.iter().cloned().collect();
2270 let workspace_packages =
2271 discover::collect_workspace_packages(&config.root, root_pkg, workspace_pkgs);
2272 let all_scripts = collect_all_scripts(root_pkg, workspace_pkgs, &workspace_packages);
2273 let nm_roots = collect_node_modules_roots(config, workspaces);
2274 let ws_manifests = workspace_pkgs.iter().map(|(_, pkg)| pkg);
2275 let bin_map = scripts::project_bin_map(&nm_roots, &all_dep_names, ws_manifests, &all_dep_set);
2276 let registry = plugins::PluginRegistry::new(config.external_plugins.clone());
2277 let deps = ScriptDependencyContext {
2278 bin_map: &bin_map,
2279 all_dep_set: &all_dep_set,
2280 workspace_packages: &workspace_packages,
2281 registry: ®istry,
2282 };
2283
2284 analyze_root_scripts(config, root_pkg, &deps, plugin_result);
2285 analyze_workspace_scripts(config, workspace_pkgs, &deps, plugin_result);
2286 analyze_ci_scripts(config, &bin_map, &all_dep_set, &all_scripts, plugin_result);
2287 analyze_hook_scripts(
2288 config,
2289 workspaces,
2290 &scripts::hooks::HookContext {
2291 bin_map: &bin_map,
2292 declared_packages: &all_dep_set,
2293 scripts: &all_scripts,
2294 ignored: scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
2295 },
2296 plugin_result,
2297 );
2298 scripts::credit_npm_aliases(&mut plugin_result.script_used_packages, &manifests);
2299 plugin_result.dependency_binaries =
2300 scripts::DependencyBinaries::new(config.root.clone(), bin_map, all_dep_set);
2301 plugin_result.dev_dependency_names = manifests
2302 .iter()
2303 .flat_map(|pkg| pkg.dev_dependency_names())
2304 .collect();
2305
2306 plugin_result
2307 .entry_point_roles
2308 .entry("scripts".to_string())
2309 .or_insert(EntryPointRole::Support);
2310 plugin_result
2311 .entry_point_roles
2312 .entry(SCRIPT_TEST_ENTRY_SOURCE.to_string())
2313 .or_insert(EntryPointRole::Test);
2314}
2315
2316struct ScriptDependencyContext<'a> {
2319 bin_map: &'a rustc_hash::FxHashMap<String, String>,
2320 all_dep_set: &'a FxHashSet<String>,
2321 workspace_packages: &'a std::sync::Arc<scripts::WorkspacePackages>,
2322 registry: &'a plugins::PluginRegistry,
2323}
2324
2325fn workspace_dir(root: &std::path::Path, ws: &fallow_config::WorkspaceInfo) -> String {
2328 ws.root
2329 .strip_prefix(root)
2330 .unwrap_or(&ws.root)
2331 .to_string_lossy()
2332 .replace('\\', "/")
2333}
2334
2335fn collect_all_scripts(
2337 root_pkg: Option<&PackageJson>,
2338 workspace_pkgs: &[LoadedWorkspacePackage],
2339 workspace_packages: &std::sync::Arc<scripts::WorkspacePackages>,
2340) -> scripts::ScriptCatalog {
2341 let mut catalog = scripts::ScriptCatalog::default();
2342 if let Some(pkg) = root_pkg
2343 && let Some(ref pkg_scripts) = pkg.scripts
2344 {
2345 catalog.merge_scripts(pkg_scripts);
2346 }
2347 for (_, ws_pkg) in workspace_pkgs {
2348 if let Some(ref ws_scripts) = ws_pkg.scripts {
2349 catalog.merge_workspace_scripts(ws_scripts);
2350 }
2351 }
2352 catalog.with_workspaces(std::sync::Arc::clone(workspace_packages), "")
2353}
2354
2355fn collect_node_modules_roots<'a>(
2357 config: &'a ResolvedConfig,
2358 workspaces: &'a [fallow_config::WorkspaceInfo],
2359) -> Vec<&'a std::path::Path> {
2360 let mut nm_roots: Vec<&std::path::Path> = Vec::new();
2361 if config.root.join("node_modules").is_dir() {
2362 nm_roots.push(&config.root);
2363 }
2364 for ws in workspaces {
2365 if ws.root.join("node_modules").is_dir() {
2366 nm_roots.push(&ws.root);
2367 }
2368 }
2369 nm_roots
2370}
2371
2372fn analyze_root_scripts(
2374 config: &ResolvedConfig,
2375 root_pkg: Option<&PackageJson>,
2376 deps: &ScriptDependencyContext<'_>,
2377 plugin_result: &mut plugins::AggregatedPluginResult,
2378) {
2379 let pkg_scripts = root_pkg
2380 .and_then(|pkg| pkg.scripts.clone())
2381 .unwrap_or_default();
2382 let mut scripts_to_analyze = if config.production {
2383 scripts::filter_production_scripts(&pkg_scripts)
2384 } else {
2385 pkg_scripts.clone()
2386 };
2387 scripts_to_analyze.extend(scripts::config_task_scripts(
2388 &config.root,
2389 "",
2390 config.production,
2391 ));
2392 if scripts_to_analyze.is_empty() {
2393 return;
2394 }
2395 let pkg_scripts = &pkg_scripts;
2396 let catalog =
2397 scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze)
2398 .with_workspaces(std::sync::Arc::clone(deps.workspace_packages), "");
2399 let script_analysis = scripts::analyze_scripts_with_dependency_context(
2400 &scripts_to_analyze,
2401 &config.root,
2402 deps.bin_map,
2403 deps.all_dep_set,
2404 &catalog,
2405 scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
2406 );
2407 plugin_result.script_used_packages = script_analysis.used_packages;
2408 plugin_result.merge_into(deps.registry.resolve_script_config_files(
2409 &script_analysis.binary_config_files,
2410 &config.root,
2411 &config.root,
2412 "",
2413 ));
2414
2415 for config_file in &script_analysis.config_files {
2416 if let Some(path) = scripts::normalize_script_entry_pattern("", config_file) {
2417 plugin_result
2418 .discovered_always_used
2419 .push((path, "scripts".to_string()));
2420 }
2421 }
2422 push_script_entry_patterns(
2423 &mut plugin_result.entry_patterns,
2424 "",
2425 &script_analysis.entry_files,
2426 &script_analysis.test_entry_files,
2427 );
2428}
2429
2430type WsScriptOut = (
2432 Vec<String>,
2433 Vec<(String, String)>,
2434 Vec<(plugins::PathRule, String)>,
2435 plugins::AggregatedPluginResult,
2436);
2437
2438fn analyze_workspace_scripts(
2439 config: &ResolvedConfig,
2440 workspace_pkgs: &[LoadedWorkspacePackage],
2441 deps: &ScriptDependencyContext<'_>,
2442 plugin_result: &mut plugins::AggregatedPluginResult,
2443) {
2444 let ws_results: Vec<WsScriptOut> = workspace_pkgs
2445 .par_iter()
2446 .map(|(ws, ws_pkg)| analyze_one_workspace_scripts(config, ws, ws_pkg, deps))
2447 .collect();
2448 for (used_packages, discovered_always_used, entry_patterns, config_result) in ws_results {
2449 plugin_result.script_used_packages.extend(used_packages);
2450 plugin_result.merge_into(config_result);
2451 plugin_result
2452 .discovered_always_used
2453 .extend(discovered_always_used);
2454 plugin_result.entry_patterns.extend(entry_patterns);
2455 }
2456}
2457
2458fn analyze_one_workspace_scripts(
2462 config: &ResolvedConfig,
2463 ws: &fallow_config::WorkspaceInfo,
2464 ws_pkg: &PackageJson,
2465 deps: &ScriptDependencyContext<'_>,
2466) -> WsScriptOut {
2467 let mut used_packages = Vec::new();
2468 let mut discovered_always_used: Vec<(String, String)> = Vec::new();
2469 let mut entry_patterns: Vec<(plugins::PathRule, String)> = Vec::new();
2470 let ws_prefix = workspace_dir(&config.root, ws);
2471 let ws_scripts = ws_pkg.scripts.clone().unwrap_or_default();
2472 let mut scripts_to_analyze = if config.production {
2473 scripts::filter_production_scripts(&ws_scripts)
2474 } else {
2475 ws_scripts.clone()
2476 };
2477 scripts_to_analyze.extend(scripts::config_task_scripts(
2478 &ws.root,
2479 &ws_prefix,
2480 config.production,
2481 ));
2482 if scripts_to_analyze.is_empty() {
2483 return (
2484 used_packages,
2485 discovered_always_used,
2486 entry_patterns,
2487 plugins::AggregatedPluginResult::default(),
2488 );
2489 }
2490 let catalog =
2491 scripts::ScriptCatalog::from_scripts_with_bodies(&ws_scripts, &scripts_to_analyze)
2492 .with_workspaces(std::sync::Arc::clone(deps.workspace_packages), &ws_prefix);
2493 let ws_analysis = scripts::analyze_scripts_with_dependency_context(
2494 &scripts_to_analyze,
2495 &ws.root,
2496 deps.bin_map,
2497 deps.all_dep_set,
2498 &catalog,
2499 scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
2500 );
2501 used_packages.extend(ws_analysis.used_packages);
2502 let config_result = deps.registry.resolve_script_config_files(
2503 &ws_analysis.binary_config_files,
2504 &ws.root,
2505 &config.root,
2506 &ws_prefix,
2507 );
2508
2509 for config_file in &ws_analysis.config_files {
2510 if let Some(path) = scripts::normalize_script_entry_pattern(&ws_prefix, config_file) {
2511 discovered_always_used.push((path, "scripts".to_string()));
2512 }
2513 }
2514 push_script_entry_patterns(
2515 &mut entry_patterns,
2516 &ws_prefix,
2517 &ws_analysis.entry_files,
2518 &ws_analysis.test_entry_files,
2519 );
2520 (
2521 used_packages,
2522 discovered_always_used,
2523 entry_patterns,
2524 config_result,
2525 )
2526}
2527
2528fn analyze_ci_scripts(
2530 config: &ResolvedConfig,
2531 bin_map: &rustc_hash::FxHashMap<String, String>,
2532 all_dep_set: &FxHashSet<String>,
2533 all_scripts: &scripts::ScriptCatalog,
2534 plugin_result: &mut plugins::AggregatedPluginResult,
2535) {
2536 let ci_analysis = scripts::ci::analyze_ci_files(
2537 &config.root,
2538 bin_map,
2539 all_dep_set,
2540 all_scripts,
2541 scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
2542 );
2543 plugin_result
2544 .script_used_packages
2545 .extend(ci_analysis.used_packages);
2546 push_script_entry_patterns(
2547 &mut plugin_result.entry_patterns,
2548 "",
2549 &ci_analysis.entry_files,
2550 &ci_analysis.test_entry_files,
2551 );
2552}
2553
2554const SCRIPT_TEST_ENTRY_SOURCE: &str = "script-tests";
2558
2559fn push_script_entry_patterns(
2564 entry_patterns: &mut Vec<(plugins::PathRule, String)>,
2565 prefix: &str,
2566 entry_files: &[String],
2567 test_entry_files: &[String],
2568) {
2569 let sources = entry_files.iter().map(|entry| (entry, "scripts")).chain(
2570 test_entry_files
2571 .iter()
2572 .map(|entry| (entry, SCRIPT_TEST_ENTRY_SOURCE)),
2573 );
2574 for (entry, source) in sources {
2575 if let Some(pat) = scripts::normalize_script_entry_pattern(prefix, entry) {
2576 entry_patterns.push((plugins::PathRule::new(pat), source.to_string()));
2577 }
2578 }
2579}
2580
2581fn analyze_hook_scripts(
2587 config: &ResolvedConfig,
2588 workspaces: &[fallow_config::WorkspaceInfo],
2589 context: &scripts::hooks::HookContext<'_>,
2590 plugin_result: &mut plugins::AggregatedPluginResult,
2591) {
2592 if config.production {
2593 return;
2594 }
2595 let roots = std::iter::once(config.root.as_path()).chain(
2596 workspaces
2597 .iter()
2598 .map(|ws| ws.root.as_path())
2599 .filter(|root| *root != config.root.as_path()),
2600 );
2601 for root in roots {
2602 plugin_result
2603 .script_used_packages
2604 .extend(scripts::hooks::analyze_hook_files(root, context));
2605 }
2606}
2607
2608fn discover_all_entry_points(
2610 input: DiscoverAllEntryPointsInput<'_>,
2611) -> (discover::CategorizedEntryPoints, EntryPointSpans) {
2612 let mut spans = EntryPointSpans::default();
2613 let mut mark = Instant::now();
2614 let mut entry_points = discover::CategorizedEntryPoints::default();
2615 let workspace_packages = discover::collect_workspace_packages(
2618 &input.config.root,
2619 input.root_pkg,
2620 input.workspace_pkgs,
2621 );
2622 let runtime_seeds = discover::workspace_runtime_script_seeds(&workspace_packages);
2623 let discovered = discover::DiscoveredPaths::new(input.files);
2624 let is_discovered = |path: &std::path::Path| discovered.contains(path);
2625 let script_workspaces = discover::ScriptWorkspaces {
2626 packages: &workspace_packages,
2627 project_root: &input.config.root,
2628 runtime_seeds: &runtime_seeds,
2629 discovered: Some(&is_discovered),
2630 };
2631 let root_discovery = discover::discover_root_entry_points(
2632 input.config,
2633 input.files,
2634 input.root_pkg,
2635 input.workspaces.is_empty(),
2636 script_workspaces,
2637 );
2638 spans.root_ms = split_ms(&mut mark);
2639
2640 let workspace_pkg_by_root: rustc_hash::FxHashMap<std::path::PathBuf, &PackageJson> = input
2641 .workspace_pkgs
2642 .iter()
2643 .map(|(ws, pkg)| (ws.root.clone(), pkg))
2644 .collect();
2645 let workspace_discovery: Vec<discover::EntryPointDiscovery> = input
2646 .workspaces
2647 .par_iter()
2648 .map(|ws| {
2649 let pkg = workspace_pkg_by_root.get(&ws.root).copied();
2650 discover::discover_workspace_package_entry_points(
2651 &ws.root,
2652 input.files,
2653 pkg,
2654 scripts::IgnoredCommandEntries::new(&input.config.ignore_command_entries),
2655 script_workspaces,
2656 )
2657 })
2658 .collect();
2659 let mut skipped_entries = rustc_hash::FxHashMap::default();
2660 let other_sources = root_discovery.non_manual_runtime_paths;
2661 entry_points.extend_runtime(root_discovery.entries);
2662 entry_points.extend_support(root_discovery.support_entries);
2663 for (path, count) in root_discovery.skipped_entries {
2664 *skipped_entries.entry(path).or_insert(0) += count;
2665 }
2666 let mut ws_entries = Vec::new();
2667 let mut ws_support_entries = Vec::new();
2668 for workspace in workspace_discovery {
2669 ws_entries.extend(workspace.entries);
2670 ws_support_entries.extend(workspace.support_entries);
2671 for (path, count) in workspace.skipped_entries {
2672 *skipped_entries.entry(path).or_insert(0) += count;
2673 }
2674 }
2675 discover::warn_skipped_entry_summary(&skipped_entries);
2676 entry_points.extend_runtime(ws_entries);
2677 entry_points.extend_support(ws_support_entries);
2678 spans.workspaces_ms = split_ms(&mut mark);
2679
2680 let plugin_entries = discover::discover_plugin_entry_point_sets_timed(
2681 input.plugin_result,
2682 input.config,
2683 input.files,
2684 );
2685 spans.plugin_glob_build_ms = plugin_entries.build_ms;
2686 spans.plugin_glob_match_ms = plugin_entries.match_ms;
2687 entry_points.extend(plugin_entries.entries);
2688 spans.plugins_ms = split_ms(&mut mark);
2689
2690 let all_scripts =
2693 collect_all_scripts(input.root_pkg, input.workspace_pkgs, &workspace_packages);
2694 let infra_entries = discover::discover_infrastructure_entry_points(
2695 &input.config.root,
2696 discover::CommandRefContext {
2697 ignored: scripts::IgnoredCommandEntries::new(&input.config.ignore_command_entries),
2698 scripts: &all_scripts,
2699 },
2700 );
2701 entry_points.extend_runtime(infra_entries);
2702 spans.infrastructure_ms = split_ms(&mut mark);
2703
2704 if !input.config.dynamically_loaded.is_empty() {
2705 let dynamic_entries =
2706 discover::discover_dynamically_loaded_entry_points(input.config, input.files);
2707 entry_points.extend_runtime(dynamic_entries);
2708 }
2709 spans.dynamic_ms = split_ms(&mut mark);
2710 discover::record_entry_pattern_effect(input.config, input.files, &entry_points, other_sources);
2711
2712 let deduped = entry_points.dedup();
2713 spans.dedup_ms = split_ms(&mut mark);
2714 (deduped, spans)
2715}
2716
2717fn split_ms(mark: &mut Instant) -> f64 {
2722 let now = Instant::now();
2723 let elapsed = now.duration_since(*mark).as_secs_f64() * 1000.0;
2724 *mark = now;
2725 elapsed
2726}
2727
2728fn append_package_file_asset_patterns(
2729 result: &mut plugins::AggregatedPluginResult,
2730 prefix: &str,
2731 pkg: &PackageJson,
2732) {
2733 let prefix = prefix.trim_matches('/');
2734 for pattern in package_assets::scaffold_template_asset_patterns(pkg) {
2735 let pattern = if prefix.is_empty() {
2736 pattern
2737 } else {
2738 format!("{prefix}/{pattern}")
2739 };
2740 result
2741 .discovered_always_used
2742 .push((pattern, package_assets::PACKAGE_FILES_SOURCE.to_string()));
2743 }
2744}
2745
2746fn append_workspace_package_file_asset_patterns(
2747 result: &mut plugins::AggregatedPluginResult,
2748 config: &ResolvedConfig,
2749 workspace_pkgs: &[LoadedWorkspacePackage],
2750) {
2751 for (ws, ws_pkg) in workspace_pkgs {
2752 let ws_prefix = ws
2753 .root
2754 .strip_prefix(&config.root)
2755 .unwrap_or(&ws.root)
2756 .to_string_lossy()
2757 .replace('\\', "/");
2758 append_package_file_asset_patterns(result, &ws_prefix, ws_pkg);
2759 }
2760}
2761
2762fn run_plugins(
2764 config: &ResolvedConfig,
2765 files: &[discover::DiscoveredFile],
2766 workspaces: &[fallow_config::WorkspaceInfo],
2767 root_pkg: Option<&PackageJson>,
2768 workspace_pkgs: &[LoadedWorkspacePackage],
2769 config_candidates: &[std::path::PathBuf],
2770) -> Result<plugins::AggregatedPluginResult, FallowError> {
2771 let registry = plugins::PluginRegistry::new(config.external_plugins.clone());
2772 let file_paths: Vec<std::path::PathBuf> = files.iter().map(|f| f.path.clone()).collect();
2773
2774 let candidate_index = (!config.production).then(|| {
2779 plugins::registry::ConfigCandidateIndex::build(
2780 file_paths
2781 .iter()
2782 .map(std::path::PathBuf::as_path)
2783 .chain(config_candidates.iter().map(std::path::PathBuf::as_path)),
2784 )
2785 });
2786
2787 let mut result = run_root_plugins(
2788 ®istry,
2789 config,
2790 root_pkg,
2791 &file_paths,
2792 candidate_index.as_ref(),
2793 )?;
2794
2795 if workspaces.is_empty() {
2796 share_auto_imports_across_layers(&mut result, config, workspaces);
2797 gate_auto_import_entry_patterns(&mut result, config, workspaces);
2798 record_plugin_config_diagnostics(&result, &config.root);
2799 return Ok(result);
2800 }
2801
2802 append_workspace_package_file_asset_patterns(&mut result, config, workspace_pkgs);
2803
2804 let ws_results = run_workspace_plugins(
2805 ®istry,
2806 config,
2807 workspace_pkgs,
2808 &file_paths,
2809 &result.active_plugins,
2810 candidate_index.as_ref(),
2811 );
2812 merge_workspace_plugin_results(&mut result, ws_results)?;
2813
2814 share_auto_imports_across_layers(&mut result, config, workspaces);
2815 gate_auto_import_entry_patterns(&mut result, config, workspaces);
2816 record_plugin_config_diagnostics(&result, &config.root);
2817
2818 Ok(result)
2819}
2820
2821fn record_plugin_config_diagnostics(result: &plugins::AggregatedPluginResult, root: &Path) {
2833 let diagnostics = result
2834 .config_diagnostics
2835 .iter()
2836 .cloned()
2837 .map(|diagnostic| diagnostic.into_workspace_diagnostic(root))
2838 .collect();
2839 let _ = fallow_config::record_plugin_config_diagnostics(root, diagnostics);
2840}
2841
2842type WorkspacePluginResult = Result<
2843 (plugins::AggregatedPluginResult, String),
2844 Vec<plugins::registry::PluginRegexValidationError>,
2845>;
2846
2847fn run_root_plugins(
2849 registry: &plugins::PluginRegistry,
2850 config: &ResolvedConfig,
2851 root_pkg: Option<&PackageJson>,
2852 file_paths: &[std::path::PathBuf],
2853 candidate_index: Option<&plugins::registry::ConfigCandidateIndex>,
2854) -> Result<plugins::AggregatedPluginResult, FallowError> {
2855 let root_config_search_roots = collect_config_search_roots(&config.root, file_paths);
2856 let root_config_search_root_refs: Vec<&Path> = root_config_search_roots
2857 .iter()
2858 .map(std::path::PathBuf::as_path)
2859 .collect();
2860
2861 let mut result = if let Some(pkg) = root_pkg {
2862 registry
2863 .try_run_with_search_roots(
2864 pkg,
2865 &config.root,
2866 file_paths,
2867 &root_config_search_root_refs,
2868 config.production,
2869 candidate_index,
2870 )
2871 .map_err(|errors| {
2872 FallowError::config(plugins::registry::format_plugin_regex_errors(&errors))
2873 })?
2874 } else {
2875 plugins::AggregatedPluginResult::default()
2876 };
2877 if let Some(pkg) = root_pkg {
2878 append_package_file_asset_patterns(&mut result, "", pkg);
2879 }
2880 Ok(result)
2881}
2882
2883fn run_workspace_plugins(
2886 registry: &plugins::PluginRegistry,
2887 config: &ResolvedConfig,
2888 workspace_pkgs: &[LoadedWorkspacePackage],
2889 file_paths: &[std::path::PathBuf],
2890 root_active_plugins: &[String],
2891 candidate_index: Option<&plugins::registry::ConfigCandidateIndex>,
2892) -> Vec<WorkspacePluginResult> {
2893 let root_active_plugins: rustc_hash::FxHashSet<&str> =
2894 root_active_plugins.iter().map(String::as_str).collect();
2895
2896 let precompiled_matchers = registry.precompile_config_matchers();
2897 let workspace_relative_files = bucket_files_by_workspace(workspace_pkgs, file_paths);
2898
2899 workspace_pkgs
2900 .par_iter()
2901 .zip(workspace_relative_files.par_iter())
2902 .filter_map(|((ws, ws_pkg), relative_files)| {
2903 let ws_result =
2904 match registry.try_run_workspace_fast(&plugins::registry::WorkspacePluginRunInput {
2905 pkg: ws_pkg,
2906 root: &ws.root,
2907 project_root: &config.root,
2908 precompiled_config_matchers: &precompiled_matchers,
2909 relative_files,
2910 skip_config_plugins: &root_active_plugins,
2911 production_mode: config.production,
2912 candidate_index,
2913 }) {
2914 Ok(result) => result,
2915 Err(errors) => return Some(Err(errors)),
2916 };
2917 if ws_result.active_plugins.is_empty() {
2918 return None;
2919 }
2920 Some(Ok((ws_result, workspace_prefix(&config.root, &ws.root))))
2921 })
2922 .collect::<Vec<_>>()
2923}
2924
2925fn merge_workspace_plugin_results(
2928 result: &mut plugins::AggregatedPluginResult,
2929 ws_results: Vec<WorkspacePluginResult>,
2930) -> Result<(), FallowError> {
2931 let mut regex_errors = Vec::new();
2932 for ws_result in ws_results {
2933 match ws_result {
2934 Ok((mut ws_result, ws_prefix)) => {
2935 ws_result.apply_workspace_prefix(&ws_prefix);
2936 ws_result.config_patterns.clear();
2937 ws_result.script_used_packages.clear();
2938 result.merge_into(ws_result);
2939 }
2940 Err(mut errors) => regex_errors.append(&mut errors),
2941 }
2942 }
2943 if !regex_errors.is_empty() {
2944 return Err(FallowError::config(
2945 plugins::registry::format_plugin_regex_errors(®ex_errors),
2946 ));
2947 }
2948 Ok(())
2949}
2950
2951fn workspace_prefix(root: &Path, workspace_root: &Path) -> String {
2955 workspace_root
2956 .strip_prefix(root)
2957 .unwrap_or(workspace_root)
2958 .to_string_lossy()
2959 .into_owned()
2960}
2961
2962fn share_auto_imports_across_layers(
2978 result: &mut plugins::AggregatedPluginResult,
2979 config: &ResolvedConfig,
2980 workspaces: &[fallow_config::WorkspaceInfo],
2981) {
2982 if result.auto_imports.is_empty() || !result.active_plugins.iter().any(|name| name == "nuxt") {
2983 return;
2984 }
2985 let links = layer_links(config, workspaces);
2986 if links.is_empty() {
2987 return;
2988 }
2989 let mut related: rustc_hash::FxHashMap<PathBuf, Vec<PathBuf>> =
2990 rustc_hash::FxHashMap::default();
2991 for rule in &mut result.auto_imports {
2992 let declared = rule.scope.clone();
2993 for root in &declared {
2994 let roots = related.entry(root.clone()).or_insert_with(|| {
2995 let mut roots = reachable_roots(root, &links, |(app, layer)| (app, layer));
2996 roots.extend(reachable_roots(root, &links, |(app, layer)| (layer, app)));
2997 roots
2998 });
2999 for extra in roots.iter() {
3000 if !rule.scope.contains(extra) {
3001 rule.scope.push(extra.clone());
3002 }
3003 }
3004 }
3005 }
3006}
3007
3008fn reachable_roots<'a>(
3012 start: &Path,
3013 links: &'a [(PathBuf, PathBuf)],
3014 direction: impl Fn(&'a (PathBuf, PathBuf)) -> (&'a PathBuf, &'a PathBuf),
3015) -> Vec<PathBuf> {
3016 let mut found: Vec<PathBuf> = Vec::new();
3017 let mut pending: Vec<&Path> = vec![start];
3018 while let Some(current) = pending.pop() {
3019 for link in links {
3020 let (from, to) = direction(link);
3021 if from.as_path() == current && to.as_path() != start && !found.contains(to) {
3022 found.push(to.clone());
3023 pending.push(to.as_path());
3024 }
3025 }
3026 }
3027 found
3028}
3029
3030fn layer_links(
3034 config: &ResolvedConfig,
3035 workspaces: &[fallow_config::WorkspaceInfo],
3036) -> Vec<(PathBuf, PathBuf)> {
3037 let roots_by_name: rustc_hash::FxHashMap<&str, &Path> = workspaces
3038 .iter()
3039 .map(|ws| (ws.name.as_str(), ws.root.as_path()))
3040 .collect();
3041 let app_roots =
3042 std::iter::once(config.root.as_path()).chain(workspaces.iter().map(|ws| ws.root.as_path()));
3043 let mut links: Vec<(PathBuf, PathBuf)> = Vec::new();
3044 for app in app_roots {
3045 let package_layers = plugins::nuxt::package_layer_names(app)
3046 .into_iter()
3047 .filter_map(|name| {
3048 roots_by_name
3049 .get(name.as_str())
3050 .map(|root| root.to_path_buf())
3051 });
3052 for layer in plugins::nuxt::outside_layer_roots(app)
3053 .into_iter()
3054 .chain(package_layers)
3055 {
3056 let link = (app.to_path_buf(), layer);
3057 if link.0 != link.1 && !links.contains(&link) {
3058 links.push(link);
3059 }
3060 }
3061 }
3062 links
3063}
3064
3065fn gate_auto_import_entry_patterns(
3084 result: &mut plugins::AggregatedPluginResult,
3085 config: &ResolvedConfig,
3086 workspaces: &[fallow_config::WorkspaceInfo],
3087) {
3088 if !config.auto_imports {
3089 return;
3090 }
3091 if !result.active_plugins.iter().any(|name| name == "nuxt") {
3092 return;
3093 }
3094 let root_settings = plugins::nuxt::auto_import_settings(&config.root);
3095 let workspace_settings: Vec<_> = workspaces
3096 .iter()
3097 .map(|ws| {
3098 (
3099 workspace_prefix(&config.root, &ws.root),
3100 plugins::nuxt::auto_import_settings(&ws.root),
3101 )
3102 })
3103 .collect();
3104 let mut retained: Vec<plugins::PluginConfigDiagnostic> = Vec::new();
3105 result.entry_patterns.retain(|(rule, plugin)| {
3106 if plugin != "nuxt" {
3107 return true;
3108 }
3109 let setting =
3110 settings_for_entry_pattern(&root_settings, &workspace_settings, &rule.pattern);
3111 if plugins::nuxt::is_component_entry_pattern(&rule.pattern) {
3112 if !setting.components.is_custom() {
3113 return false;
3114 }
3115 record_retained_auto_import_surface(
3116 &mut retained,
3117 &setting.components_origin,
3118 "components",
3119 );
3120 return true;
3121 }
3122 if plugins::nuxt::is_script_auto_import_entry_pattern(&rule.pattern) {
3123 if !setting.scripts.is_custom() {
3124 return false;
3125 }
3126 record_retained_auto_import_surface(&mut retained, &setting.scripts_origin, "imports");
3127 return true;
3128 }
3129 true
3130 });
3131 result.config_diagnostics.extend(retained);
3132}
3133
3134const AUTO_IMPORT_PROPERTY_UNREADABLE: &str = "config-property-unreadable";
3139const AUTO_IMPORT_KEY_NOT_MODELED: &str = "key-effect-not-modeled";
3140
3141fn record_retained_auto_import_surface(
3144 retained: &mut Vec<plugins::PluginConfigDiagnostic>,
3145 origin: &plugins::nuxt::SurfaceOrigin,
3146 key: &str,
3147) {
3148 let Some(config_path) = origin.config_path.as_deref() else {
3149 return;
3150 };
3151 let reason = if origin.unreadable_property {
3152 AUTO_IMPORT_PROPERTY_UNREADABLE
3153 } else {
3154 AUTO_IMPORT_KEY_NOT_MODELED
3155 };
3156 let diagnostic = plugins::PluginConfigDiagnostic::not_modeled(config_path, "nuxt", key, reason);
3157 if !retained.contains(&diagnostic) {
3158 retained.push(diagnostic);
3159 }
3160}
3161
3162fn settings_for_entry_pattern<'a>(
3167 root: &'a plugins::nuxt::AutoImportSettings,
3168 workspaces: &'a [(String, plugins::nuxt::AutoImportSettings)],
3169 pattern: &str,
3170) -> &'a plugins::nuxt::AutoImportSettings {
3171 workspaces
3172 .iter()
3173 .filter(|(prefix, _)| {
3174 !prefix.is_empty()
3175 && pattern
3176 .strip_prefix(prefix.as_str())
3177 .is_some_and(|rest| rest.starts_with('/'))
3178 })
3179 .max_by_key(|(prefix, _)| prefix.len())
3180 .map_or(root, |(_, setting)| setting)
3181}
3182
3183fn bucket_files_by_workspace(
3184 workspace_pkgs: &[LoadedWorkspacePackage],
3185 file_paths: &[std::path::PathBuf],
3186) -> Vec<Vec<(std::path::PathBuf, String)>> {
3187 let workspace_roots: Vec<_> = workspace_pkgs
3188 .iter()
3189 .map(|(workspace, _)| workspace.root.as_path())
3190 .collect();
3191 bucket_files_by_workspace_roots(&workspace_roots, file_paths)
3192}
3193
3194fn bucket_files_by_workspace_roots(
3195 workspace_roots: &[&Path],
3196 file_paths: &[std::path::PathBuf],
3197) -> Vec<Vec<(std::path::PathBuf, String)>> {
3198 use rayon::prelude::*;
3199
3200 let mut workspace_by_root: rustc_hash::FxHashMap<&Path, usize> =
3204 rustc_hash::FxHashMap::default();
3205 for (idx, root) in workspace_roots.iter().enumerate() {
3206 workspace_by_root.entry(root).or_insert(idx);
3207 }
3208
3209 let assignments: Vec<Option<(usize, std::path::PathBuf, String)>> = file_paths
3210 .par_iter()
3211 .map(|file_path| {
3212 let idx = file_path
3213 .ancestors()
3214 .filter_map(|ancestor| workspace_by_root.get(ancestor).copied())
3215 .min()?;
3216 let relative = file_path.strip_prefix(workspace_roots[idx]).ok()?;
3217 Some((
3218 idx,
3219 file_path.clone(),
3220 relative.to_string_lossy().into_owned(),
3221 ))
3222 })
3223 .collect();
3224
3225 let mut buckets = vec![Vec::new(); workspace_roots.len()];
3226 for (idx, file_path, relative) in assignments.into_iter().flatten() {
3227 buckets[idx].push((file_path, relative));
3228 }
3229
3230 buckets
3231}
3232
3233#[doc(hidden)]
3235pub fn benchmark_bucket_files_by_workspace(
3236 workspace_roots: &[std::path::PathBuf],
3237 file_paths: &[std::path::PathBuf],
3238) -> Vec<Vec<(std::path::PathBuf, String)>> {
3239 let workspace_roots: Vec<_> = workspace_roots
3240 .iter()
3241 .map(std::path::PathBuf::as_path)
3242 .collect();
3243 bucket_files_by_workspace_roots(&workspace_roots, file_paths)
3244}
3245
3246fn collect_config_search_roots(
3247 root: &Path,
3248 file_paths: &[std::path::PathBuf],
3249) -> Vec<std::path::PathBuf> {
3250 let mut roots: rustc_hash::FxHashSet<std::path::PathBuf> = rustc_hash::FxHashSet::default();
3251 roots.insert(root.to_path_buf());
3252
3253 for file_path in file_paths {
3254 let mut current = file_path.parent();
3255 while let Some(dir) = current {
3256 if !dir.starts_with(root) {
3257 break;
3258 }
3259 roots.insert(dir.to_path_buf());
3260 if dir == root {
3261 break;
3262 }
3263 current = dir.parent();
3264 }
3265 }
3266
3267 let mut roots_vec: Vec<_> = roots.into_iter().collect();
3268 roots_vec.sort();
3269 roots_vec
3270}
3271
3272fn config_for_project(
3280 root: &Path,
3281 config_path: Option<&Path>,
3282) -> Result<(ResolvedConfig, Option<std::path::PathBuf>), FallowError> {
3283 let user_config = if let Some(path) = config_path {
3284 Some((
3285 fallow_config::FallowConfig::load(path)
3286 .map_err(|e| FallowError::config(format!("{e:#}")))?,
3287 path.to_path_buf(),
3288 ))
3289 } else {
3290 fallow_config::FallowConfig::find_and_load(root).map_err(FallowError::config)?
3291 };
3292
3293 let config = match user_config {
3294 Some((config, path)) => resolve_user_config(config, path, root)?,
3295 None => (
3296 fallow_config::FallowConfig::default().resolve(
3297 root.to_path_buf(),
3298 fallow_config::OutputFormat::Human,
3299 num_cpus(),
3300 false,
3301 true,
3302 None,
3303 ),
3304 None,
3305 ),
3306 };
3307
3308 Ok(config)
3309}
3310
3311fn resolve_user_config(
3314 mut config: fallow_config::FallowConfig,
3315 path: std::path::PathBuf,
3316 root: &Path,
3317) -> Result<(ResolvedConfig, Option<std::path::PathBuf>), FallowError> {
3318 let dead_code_production = config
3319 .production
3320 .for_analysis(fallow_config::ProductionAnalysis::DeadCode);
3321 config.production = dead_code_production.into();
3322 config
3323 .validate_resolved_boundaries(root)
3324 .map_err(|errors| {
3325 let joined = errors
3326 .iter()
3327 .map(ToString::to_string)
3328 .collect::<Vec<_>>()
3329 .join("\n - ");
3330 FallowError::config(format!("invalid boundary configuration:\n - {joined}"))
3331 })?;
3332 let packs = fallow_config::load_rule_packs(root, &config.rule_packs).map_err(|errors| {
3333 let joined = errors
3334 .iter()
3335 .map(ToString::to_string)
3336 .collect::<Vec<_>>()
3337 .join("\n - ");
3338 FallowError::config(format!("invalid rule pack:\n - {joined}"))
3339 })?;
3340 let zone_errors = fallow_config::validate_rule_pack_zones(
3341 root,
3342 &config.boundaries,
3343 &config.rule_packs,
3344 &packs,
3345 );
3346 if !zone_errors.is_empty() {
3347 let joined = zone_errors
3348 .iter()
3349 .map(ToString::to_string)
3350 .collect::<Vec<_>>()
3351 .join("\n - ");
3352 return Err(FallowError::config(format!(
3353 "invalid rule pack:\n - {joined}"
3354 )));
3355 }
3356 Ok((
3357 config.resolve(
3358 root.to_path_buf(),
3359 fallow_config::OutputFormat::Human,
3360 num_cpus(),
3361 false,
3362 true, None, ),
3365 Some(path),
3366 ))
3367}
3368
3369#[cfg_attr(
3380 not(test),
3381 allow(
3382 dead_code,
3383 reason = "config resolution fallback is exercised by session tests"
3384 )
3385)]
3386pub(crate) fn default_config(root: &Path) -> ResolvedConfig {
3387 config_for_project(root, None).map_or_else(
3388 |_| {
3389 fallow_config::FallowConfig::default().resolve(
3390 root.to_path_buf(),
3391 fallow_config::OutputFormat::Human,
3392 num_cpus(),
3393 false,
3394 true,
3395 None,
3396 )
3397 },
3398 |(config, _)| config,
3399 )
3400}
3401
3402fn num_cpus() -> usize {
3403 std::thread::available_parallelism().map_or(4, std::num::NonZeroUsize::get)
3404}
3405
3406#[cfg(test)]
3407mod tests {
3408 use super::{
3409 AnalysisSession, bucket_files_by_workspace, bucket_files_by_workspace_roots,
3410 collect_config_search_roots, credit_workspace_package_usage, default_config,
3411 format_undeclared_workspace_warning, gate_auto_import_entry_patterns,
3412 parse_analysis_modules, plugin_config_hash, resolver_options_hash,
3413 settings_for_entry_pattern, warn_undeclared_workspaces, workspace_prefix,
3414 };
3415 use std::path::{Path, PathBuf};
3416 use std::time::Instant;
3417
3418 use fallow_config::{
3419 AutoImportKind, AutoImportRule, WorkspaceDiagnostic, WorkspaceDiagnosticKind,
3420 };
3421 use fallow_types::discover::{DiscoveredFile, FileId};
3422 use fallow_types::extract::{ImportInfo, ImportedName};
3423
3424 fn plugin_result() -> crate::plugins::AggregatedPluginResult {
3425 let mut result = crate::plugins::AggregatedPluginResult::default();
3426 result.active_plugins.push("nuxt".to_string());
3427 result
3428 .path_aliases
3429 .push(("@/".to_string(), "src/".to_string()));
3430 result
3431 }
3432
3433 fn auto_import_settings(
3434 components: crate::plugins::nuxt::AutoImportSetting,
3435 ) -> crate::plugins::nuxt::AutoImportSettings {
3436 crate::plugins::nuxt::AutoImportSettings {
3437 components,
3438 scripts: crate::plugins::nuxt::AutoImportSetting::Default,
3439 components_origin: crate::plugins::nuxt::SurfaceOrigin {
3440 config_path: Some(std::path::PathBuf::from("nuxt.config.ts")),
3441 unreadable_property: false,
3442 },
3443 scripts_origin: crate::plugins::nuxt::SurfaceOrigin::default(),
3444 }
3445 }
3446
3447 #[test]
3448 fn entry_pattern_settings_prefer_the_longest_workspace_prefix() {
3449 let root = auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Default);
3450 let workspaces = vec![
3451 (
3452 "packages/web".to_string(),
3453 auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Custom),
3454 ),
3455 (
3456 "packages/web-admin".to_string(),
3457 auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Disabled),
3458 ),
3459 ];
3460
3461 let admin = settings_for_entry_pattern(
3462 &root,
3463 &workspaces,
3464 "packages/web-admin/components/**/*.{vue,ts,tsx,js,jsx}",
3465 );
3466 assert_eq!(
3467 admin.components,
3468 crate::plugins::nuxt::AutoImportSetting::Disabled,
3469 "a sibling whose name starts with another workspace name is its own"
3470 );
3471
3472 let web = settings_for_entry_pattern(
3473 &root,
3474 &workspaces,
3475 "packages/web/components/**/*.{vue,ts,tsx,js,jsx}",
3476 );
3477 assert_eq!(
3478 web.components,
3479 crate::plugins::nuxt::AutoImportSetting::Custom
3480 );
3481 }
3482
3483 #[test]
3484 fn entry_pattern_without_a_workspace_prefix_belongs_to_the_project_root() {
3485 let root = auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Custom);
3486 let workspaces = vec![(
3487 "packages/web".to_string(),
3488 auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Default),
3489 )];
3490
3491 let setting = settings_for_entry_pattern(
3492 &root,
3493 &workspaces,
3494 "app/components/**/*.{vue,ts,tsx,js,jsx}",
3495 );
3496 assert_eq!(
3497 setting.components,
3498 crate::plugins::nuxt::AutoImportSetting::Custom
3499 );
3500 }
3501
3502 fn nuxt_gate_fixture(
3505 config_source: &str,
3506 ) -> (tempfile::TempDir, crate::plugins::AggregatedPluginResult) {
3507 let dir = tempfile::tempdir().expect("temp project");
3508 std::fs::write(dir.path().join("nuxt.config.ts"), config_source).expect("nuxt config");
3509 let mut result = crate::plugins::AggregatedPluginResult::default();
3510 result.active_plugins.push("nuxt".to_string());
3511 for pattern in [
3512 "app/components/**/*.{vue,ts,tsx,js,jsx}",
3513 "app/composables/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}",
3514 ] {
3515 result.entry_patterns.push((
3516 crate::plugins::PathRule::new(pattern.to_string()),
3517 "nuxt".to_string(),
3518 ));
3519 }
3520 (dir, result)
3521 }
3522
3523 fn gate(root: &Path, result: &mut crate::plugins::AggregatedPluginResult) {
3524 let config = fallow_config::FallowConfig {
3525 auto_imports: true,
3526 ..fallow_config::FallowConfig::default()
3527 };
3528 let resolved = config.resolve(
3529 root.to_path_buf(),
3530 fallow_config::OutputFormat::Json,
3531 1,
3532 false,
3533 true,
3534 None,
3535 );
3536 assert!(resolved.auto_imports, "the gate only runs when opted in");
3537 gate_auto_import_entry_patterns(result, &resolved, &[]);
3538 }
3539
3540 #[test]
3544 fn a_retained_auto_import_surface_records_one_advisory_per_surface() {
3545 let (project, mut result) =
3546 nuxt_gate_fixture("export default { components: { dirs: ['~/ui'] } };\n");
3547 gate(project.path(), &mut result);
3548
3549 let recorded: Vec<(&str, &str, &str)> = result
3550 .config_diagnostics
3551 .iter()
3552 .map(|diagnostic| {
3553 (
3554 diagnostic.plugin.as_str(),
3555 diagnostic.key.as_str(),
3556 diagnostic.reason.as_str(),
3557 )
3558 })
3559 .collect();
3560 assert_eq!(
3561 recorded,
3562 vec![("nuxt", "components", "key-effect-not-modeled")],
3563 "only the surface that kept its patterns is reported: {:?}",
3564 result.config_diagnostics
3565 );
3566 assert_eq!(
3567 result.config_diagnostics[0].config_path,
3568 project.path().join("nuxt.config.ts")
3569 );
3570 assert_eq!(
3571 result.entry_patterns.len(),
3572 1,
3573 "the modeled surface still loses its patterns: {:?}",
3574 result.entry_patterns
3575 );
3576 }
3577
3578 #[test]
3582 fn an_unreadable_top_level_property_reports_both_surfaces_with_its_own_reason() {
3583 let (project, mut result) =
3584 nuxt_gate_fixture("export default { ...baseConfig, modules: [] };\n");
3585 gate(project.path(), &mut result);
3586
3587 let recorded: Vec<(&str, &str)> = result
3588 .config_diagnostics
3589 .iter()
3590 .map(|diagnostic| (diagnostic.key.as_str(), diagnostic.reason.as_str()))
3591 .collect();
3592 assert_eq!(
3593 recorded,
3594 vec![
3595 ("components", "config-property-unreadable"),
3596 ("imports", "config-property-unreadable"),
3597 ],
3598 "{:?}",
3599 result.config_diagnostics
3600 );
3601 assert_eq!(
3602 result.entry_patterns.len(),
3603 2,
3604 "a spread keeps every gated pattern"
3605 );
3606 }
3607
3608 #[test]
3611 fn a_modeled_nuxt_config_records_no_advisory() {
3612 let (project, mut result) = nuxt_gate_fixture("export default { modules: [] };\n");
3613 gate(project.path(), &mut result);
3614 assert!(
3615 result.config_diagnostics.is_empty(),
3616 "{:?}",
3617 result.config_diagnostics
3618 );
3619 assert!(
3620 result.entry_patterns.is_empty(),
3621 "both modeled surfaces lose their patterns: {:?}",
3622 result.entry_patterns
3623 );
3624 }
3625
3626 #[test]
3627 fn a_workspace_outside_the_project_keeps_its_own_prefix() {
3628 let project_root = Path::new("/repo");
3629 let outside = Path::new("/elsewhere/app");
3630 let prefix = workspace_prefix(project_root, outside);
3631 assert_eq!(prefix, "/elsewhere/app");
3632
3633 let root = auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Default);
3634 let workspaces = vec![(
3635 prefix,
3636 auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Custom),
3637 )];
3638 let setting = settings_for_entry_pattern(
3639 &root,
3640 &workspaces,
3641 "/elsewhere/app/components/**/*.{vue,ts,tsx,js,jsx}",
3642 );
3643 assert_eq!(
3644 setting.components,
3645 crate::plugins::nuxt::AutoImportSetting::Custom,
3646 "an out-of-tree workspace is classified on its own config"
3647 );
3648 }
3649
3650 #[test]
3651 fn commonjs_internal_import_credits_workspace_package_usage() {
3652 let workspace = fallow_config::WorkspaceInfo {
3653 root: PathBuf::from("/repo/packages/shared"),
3654 name: "@repo/shared".to_string(),
3655 is_internal_dependency: true,
3656 };
3657 let resolved = vec![crate::resolve::ResolvedModule {
3658 file_id: FileId(0),
3659 resolved_imports: vec![crate::resolve::ResolvedImport {
3660 info: ImportInfo {
3661 source: "@repo/shared".to_string(),
3662 imported_name: ImportedName::Namespace,
3663 local_name: "shared".to_string(),
3664 is_type_only: false,
3665 is_type_only_star: false,
3666 from_style: false,
3667 span: oxc_span::Span::new(0, 20),
3668 source_span: oxc_span::Span::new(8, 20),
3669 },
3670 target: crate::resolve::ResolveResult::CommonJsInternalModule(FileId(1)),
3671 }],
3672 ..crate::resolve::ResolvedModule::default()
3673 }];
3674 let mut graph = crate::graph::ModuleGraph::build(&[], &[], &[]);
3675
3676 credit_workspace_package_usage(&mut graph, &resolved, &[workspace]);
3677
3678 assert_eq!(
3679 graph.package_usage.get("@repo/shared"),
3680 Some(&vec![FileId(0)])
3681 );
3682 }
3683
3684 #[test]
3687 fn graph_cache_resolver_hash_is_independent_of_the_project_root() {
3688 let dir_a = tempfile::tempdir().expect("create temp dir a");
3689 let dir_b = tempfile::tempdir().expect("create temp dir b");
3690 let config_a = session_config(dir_a.path());
3691 let config_b = session_config(dir_b.path());
3692
3693 assert_eq!(
3694 resolver_options_hash(&config_a, &[], &[]),
3695 resolver_options_hash(&config_b, &[], &[]),
3696 "root identity is handled separately from resolver options"
3697 );
3698 }
3699
3700 #[test]
3703 fn graph_cache_manifest_still_rejects_a_different_file_set() {
3704 let dir_a = tempfile::tempdir().expect("create temp dir a");
3705 let mode = crate::graph_cache::GraphCacheMode::new(1, 2, 3);
3706 let files_a = [crate::discover::DiscoveredFile {
3707 id: crate::discover::FileId(0),
3708 path: dir_a.path().join("src/a.ts"),
3709 size_bytes: 1,
3710 }];
3711 let files_b = [crate::discover::DiscoveredFile {
3712 id: crate::discover::FileId(0),
3713 path: dir_a.path().join("src/b.ts"),
3714 size_bytes: 1,
3715 }];
3716
3717 let manifest_a = crate::graph_cache::GraphCacheManifest::from_discovered_files(
3718 dir_a.path(),
3719 &files_a,
3720 mode,
3721 |_| 7,
3722 );
3723 let manifest_b = crate::graph_cache::GraphCacheManifest::from_discovered_files(
3724 dir_a.path(),
3725 &files_b,
3726 mode,
3727 |_| 7,
3728 );
3729
3730 assert_eq!(
3731 manifest_a.classify_resolution_mismatch(&manifest_b),
3732 Some(fallow_types::cache_rejection::CacheRejection::FileSetChanged)
3733 );
3734 }
3735
3736 #[test]
3737 fn graph_cache_resolver_hash_includes_resolve_conditions() {
3738 let dir = tempfile::tempdir().expect("create temp dir");
3739 let config_a = session_config(dir.path());
3740 let mut config_b = session_config(dir.path());
3741 config_b.resolve.conditions.push("react-server".to_string());
3742
3743 assert_ne!(
3744 resolver_options_hash(&config_a, &[], &[]),
3745 resolver_options_hash(&config_b, &[], &[]),
3746 "resolve condition changes must invalidate the graph cache"
3747 );
3748 }
3749
3750 #[test]
3751 fn graph_cache_plugin_hash_includes_auto_imports() {
3752 let mut without_auto_import = plugin_result();
3753 let mut with_auto_import = plugin_result();
3754 with_auto_import.auto_imports.push(AutoImportRule::new(
3755 "useCounter".to_string(),
3756 PathBuf::from("/project/composables/useCounter.ts"),
3757 AutoImportKind::Named,
3758 ));
3759
3760 assert_ne!(
3761 plugin_config_hash(&without_auto_import, std::path::Path::new("")),
3762 plugin_config_hash(&with_auto_import, std::path::Path::new("")),
3763 "auto-import edge changes must invalidate the graph cache"
3764 );
3765
3766 without_auto_import.auto_imports.push(AutoImportRule::new(
3767 "useCounter".to_string(),
3768 PathBuf::from("/project/composables/useCounter.ts"),
3769 AutoImportKind::Default,
3770 ));
3771 assert_ne!(
3772 plugin_config_hash(&without_auto_import, std::path::Path::new("")),
3773 plugin_config_hash(&with_auto_import, std::path::Path::new("")),
3774 "auto-import kind changes must invalidate the graph cache"
3775 );
3776
3777 let mut scoped = with_auto_import.auto_imports.clone();
3778 scoped[0].scope = vec![PathBuf::from("/project/packages/a")];
3779 let mut with_scoped_auto_import = plugin_result();
3780 with_scoped_auto_import.auto_imports = scoped;
3781 assert_ne!(
3782 plugin_config_hash(&with_scoped_auto_import, std::path::Path::new("")),
3783 plugin_config_hash(&with_auto_import, std::path::Path::new("")),
3784 "auto-import scope changes must invalidate the graph cache"
3785 );
3786 }
3787
3788 #[test]
3789 fn graph_cache_plugin_hash_includes_framework_static_dir_mappings() {
3790 let base = plugin_result();
3791 let mut with_mount = plugin_result();
3792 with_mount
3793 .framework_static_dir_mappings
3794 .push((PathBuf::from("/project/public"), "/".to_string()));
3795 let mut tool_mount = plugin_result();
3796 tool_mount
3797 .static_dir_mappings
3798 .push((PathBuf::from("/project/public"), "/".to_string()));
3799 let root = std::path::Path::new("/project");
3800 assert_ne!(
3801 plugin_config_hash(&base, root),
3802 plugin_config_hash(&with_mount, root),
3803 "framework static mounts feed the resolver and must key the graph cache"
3804 );
3805 assert_ne!(
3806 plugin_config_hash(&tool_mount, root),
3807 plugin_config_hash(&with_mount, root),
3808 "a framework mount and a tool mount resolve differently"
3809 );
3810 }
3811
3812 #[test]
3813 fn graph_cache_plugin_hash_includes_jsx_import_sources() {
3814 let rule = fallow_config::JsxImportSourceRule {
3815 source: "./src/jsx".to_string(),
3816 config_dir: PathBuf::from("/project"),
3817 include: vec!["src/**/*.test.tsx".to_string()],
3818 exclude: vec![],
3819 };
3820 let base = plugin_result();
3821 let mut with_rule = plugin_result();
3822 with_rule.jsx_import_sources.push(rule.clone());
3823 assert_ne!(
3824 plugin_config_hash(&base, std::path::Path::new("")),
3825 plugin_config_hash(&with_rule, std::path::Path::new("")),
3826 "JSX import source changes must invalidate the graph cache"
3827 );
3828
3829 let mut other_source = plugin_result();
3830 other_source
3831 .jsx_import_sources
3832 .push(fallow_config::JsxImportSourceRule {
3833 source: "./src/jsx/dom".to_string(),
3834 ..rule.clone()
3835 });
3836 assert_ne!(
3837 plugin_config_hash(&with_rule, std::path::Path::new("")),
3838 plugin_config_hash(&other_source, std::path::Path::new("")),
3839 "a changed JSX import source must invalidate the graph cache"
3840 );
3841
3842 let mut with_exclude = plugin_result();
3843 with_exclude
3844 .jsx_import_sources
3845 .push(fallow_config::JsxImportSourceRule {
3846 exclude: vec!["src/skip/**".to_string()],
3847 ..rule
3848 });
3849 assert_ne!(
3850 plugin_config_hash(&with_rule, std::path::Path::new("")),
3851 plugin_config_hash(&with_exclude, std::path::Path::new("")),
3852 "a changed JSX exclude must invalidate the graph cache"
3853 );
3854 }
3855
3856 #[test]
3857 fn graph_cache_plugin_hash_includes_style_and_static_mappings() {
3858 let base = plugin_result();
3859 let mut with_scss = base.clone();
3860 with_scss
3861 .scss_include_paths
3862 .push(PathBuf::from("/project/styles"));
3863 assert_ne!(
3864 plugin_config_hash(&base, std::path::Path::new("")),
3865 plugin_config_hash(&with_scss, std::path::Path::new("")),
3866 "SCSS include path changes must invalidate the graph cache"
3867 );
3868
3869 let mut with_static_dir = base.clone();
3870 with_static_dir
3871 .static_dir_mappings
3872 .push((PathBuf::from("/project/public"), "/".to_string()));
3873 assert_ne!(
3874 plugin_config_hash(&base, std::path::Path::new("")),
3875 plugin_config_hash(&with_static_dir, std::path::Path::new("")),
3876 "static directory mapping changes must invalidate the graph cache"
3877 );
3878 }
3879
3880 fn diag(root: &Path, relative: &str) -> WorkspaceDiagnostic {
3881 WorkspaceDiagnostic::new(
3882 root,
3883 root.join(relative),
3884 WorkspaceDiagnosticKind::UndeclaredWorkspace,
3885 )
3886 }
3887
3888 fn session_config(root: &Path) -> fallow_config::ResolvedConfig {
3889 let mut config = default_config(root);
3890 config.no_cache = true;
3891 config.quiet = true;
3892 config
3893 }
3894
3895 fn write_session_fixture(root: &Path) {
3896 let src = root.join("src");
3897 std::fs::create_dir_all(&src).expect("create src");
3898 std::fs::write(
3899 root.join("package.json"),
3900 r#"{"name":"session-fixture","type":"module"}"#,
3901 )
3902 .expect("write package json");
3903 std::fs::write(
3904 src.join("index.ts"),
3905 "import { used } from './used';\nconsole.log(used);\n",
3906 )
3907 .expect("write index");
3908 std::fs::write(src.join("used.ts"), "export const used = 1;\n").expect("write used");
3909 }
3910
3911 #[test]
3912 fn analysis_session_discovers_project_files() {
3913 let dir = tempfile::tempdir().expect("create temp dir");
3914 write_session_fixture(dir.path());
3915 let config = session_config(dir.path());
3916
3917 let session = AnalysisSession::new(&config).expect("session setup should succeed");
3918
3919 assert!(
3920 session
3921 .files()
3922 .iter()
3923 .any(|file| file.path.ends_with("src/index.ts")),
3924 "session should own discovered project files"
3925 );
3926 assert_eq!(session.workspaces().len(), 0);
3927 }
3928
3929 #[test]
3930 fn direct_core_parse_surfaces_source_read_failure_diagnostic() {
3931 let project = tempfile::tempdir().expect("create project");
3932 let root = project.path();
3933 let paths = ["a.ts", "b.ts", "c.ts"].map(|name| root.join(name));
3934 for (index, path) in paths.iter().enumerate() {
3935 std::fs::write(path, format!("export const value{index} = {index};\n"))
3936 .expect("write source");
3937 }
3938 let files: Vec<DiscoveredFile> = paths
3939 .iter()
3940 .enumerate()
3941 .map(|(index, path)| DiscoveredFile {
3942 id: FileId(u32::try_from(index).expect("test index fits u32")),
3943 path: path.clone(),
3944 size_bytes: std::fs::metadata(path).expect("source metadata").len(),
3945 })
3946 .collect();
3947 std::fs::remove_file(&paths[1]).expect("remove source after discovery");
3948 let config = session_config(root);
3949
3950 let parsed = parse_analysis_modules(&config, &files, false, Instant::now());
3951
3952 assert_eq!(
3953 parsed
3954 .modules
3955 .iter()
3956 .map(|module| module.file_id)
3957 .collect::<Vec<_>>(),
3958 vec![FileId(0), FileId(2)]
3959 );
3960 let diagnostics = fallow_config::workspace_diagnostics_for(root);
3961 let diagnostic = diagnostics
3962 .iter()
3963 .find(|diagnostic| diagnostic.kind.id() == "source-read-failure")
3964 .expect("source read failure diagnostic");
3965 assert_eq!(diagnostic.path, paths[1]);
3966 assert!(matches!(
3967 diagnostic.kind,
3968 WorkspaceDiagnosticKind::SourceReadFailure { .. }
3969 ));
3970 }
3971
3972 #[test]
3973 fn analysis_session_parses_owned_modules() {
3974 let dir = tempfile::tempdir().expect("create temp dir");
3975 write_session_fixture(dir.path());
3976 let config = session_config(dir.path());
3977
3978 let session = AnalysisSession::new(&config).expect("session setup should succeed");
3979 let parsed = session.parse_modules(false);
3980
3981 assert!(
3982 parsed
3983 .modules
3984 .iter()
3985 .any(|module| session.files()[module.file_id.0 as usize]
3986 .path
3987 .ends_with("src/index.ts")),
3988 "session parsing should return modules keyed to session files"
3989 );
3990 }
3991
3992 #[test]
3993 fn undeclared_workspace_warning_is_singular_for_one_path() {
3994 let root = Path::new("/repo");
3995 let warning = format_undeclared_workspace_warning(root, &[diag(root, "packages/api")])
3996 .expect("warning should be rendered");
3997
3998 assert_eq!(
3999 warning,
4000 "1 directory with package.json is not declared as a workspace: packages/api. Add that path to package.json workspaces or pnpm-workspace.yaml if it should be analyzed as a workspace."
4001 );
4002 }
4003
4004 #[test]
4005 fn undeclared_workspace_warning_summarizes_many_paths() {
4006 let root = PathBuf::from("/repo");
4007 let diagnostics = [
4008 "examples/a",
4009 "examples/b",
4010 "examples/c",
4011 "examples/d",
4012 "examples/e",
4013 "examples/f",
4014 ]
4015 .into_iter()
4016 .map(|path| diag(&root, path))
4017 .collect::<Vec<_>>();
4018
4019 let warning = format_undeclared_workspace_warning(&root, &diagnostics)
4020 .expect("warning should be rendered");
4021
4022 assert_eq!(
4023 warning,
4024 "6 directories with package.json are not declared as workspaces: examples/a, examples/b, examples/c, examples/d, examples/e (and 1 more). Add those paths to package.json workspaces or pnpm-workspace.yaml if they should be analyzed as workspaces."
4025 );
4026 }
4027
4028 #[test]
4029 fn collect_config_search_roots_includes_file_ancestors_once() {
4030 let root = PathBuf::from("/repo");
4031 let search_roots = collect_config_search_roots(
4032 &root,
4033 &[
4034 root.join("apps/query/src/main.ts"),
4035 root.join("packages/shared/lib/index.ts"),
4036 ],
4037 );
4038
4039 assert_eq!(
4040 search_roots,
4041 vec![
4042 root.clone(),
4043 root.join("apps"),
4044 root.join("apps/query"),
4045 root.join("apps/query/src"),
4046 root.join("packages"),
4047 root.join("packages/shared"),
4048 root.join("packages/shared/lib"),
4049 ]
4050 );
4051 }
4052
4053 #[test]
4054 fn bucket_files_by_workspace_uses_workspace_relative_paths() {
4055 let root = PathBuf::from("/repo");
4056 let ui = fallow_config::WorkspaceInfo {
4057 root: root.join("apps/ui"),
4058 name: "ui".to_string(),
4059 is_internal_dependency: false,
4060 };
4061 let api = fallow_config::WorkspaceInfo {
4062 root: root.join("apps/api"),
4063 name: "api".to_string(),
4064 is_internal_dependency: false,
4065 };
4066 let workspace_pkgs = vec![
4067 (
4068 ui,
4069 fallow_config::PackageJson {
4070 name: Some("ui".to_string()),
4071 ..Default::default()
4072 },
4073 ),
4074 (
4075 api,
4076 fallow_config::PackageJson {
4077 name: Some("api".to_string()),
4078 ..Default::default()
4079 },
4080 ),
4081 ];
4082 let files = vec![
4083 root.join("apps/ui/vite.config.ts"),
4084 root.join("apps/ui/src/main.ts"),
4085 root.join("apps/api/src/server.ts"),
4086 root.join("tools/build.ts"),
4087 ];
4088
4089 let buckets = bucket_files_by_workspace(&workspace_pkgs, &files);
4090
4091 assert_eq!(
4092 buckets[0],
4093 vec![
4094 (
4095 root.join("apps/ui/vite.config.ts"),
4096 "vite.config.ts".to_string()
4097 ),
4098 (root.join("apps/ui/src/main.ts"), "src/main.ts".to_string()),
4099 ]
4100 );
4101 assert_eq!(
4102 buckets[1],
4103 vec![(
4104 root.join("apps/api/src/server.ts"),
4105 "src/server.ts".to_string()
4106 )]
4107 );
4108 }
4109
4110 #[test]
4111 fn workspace_bucketing_preserves_first_declared_match_and_file_order() {
4112 let root = PathBuf::from("/repo");
4113 let parent = root.join("apps");
4114 let child = parent.join("web");
4115 let nested_first = child.join("src/first.ts");
4116 let nested_second = child.join("src/second.ts");
4117 let unmatched = root.join("tools/build.ts");
4118 let files = vec![nested_first.clone(), unmatched, nested_second.clone()];
4119
4120 let normalize = |bucket: &[(PathBuf, String)]| -> Vec<(PathBuf, String)> {
4125 bucket
4126 .iter()
4127 .map(|(path, rel)| (path.clone(), rel.replace('\\', "/")))
4128 .collect()
4129 };
4130
4131 let parent_first = bucket_files_by_workspace_roots(&[&parent, &child, &child], &files);
4132 assert_eq!(
4133 normalize(&parent_first[0]),
4134 vec![
4135 (nested_first.clone(), "web/src/first.ts".to_string()),
4136 (nested_second.clone(), "web/src/second.ts".to_string()),
4137 ]
4138 );
4139 assert!(parent_first[1].is_empty());
4140 assert!(parent_first[2].is_empty());
4141
4142 let child_first = bucket_files_by_workspace_roots(&[&child, &parent], &files);
4143 assert_eq!(
4144 normalize(&child_first[0]),
4145 vec![
4146 (nested_first, "src/first.ts".to_string()),
4147 (nested_second, "src/second.ts".to_string()),
4148 ]
4149 );
4150 assert!(child_first[1].is_empty());
4151 }
4152
4153 #[test]
4154 fn warn_undeclared_workspaces_suppresses_paths_already_flagged_as_malformed() {
4155 let dir = tempfile::tempdir().expect("create temp dir");
4156 let pkg_good = dir.path().join("packages").join("good");
4157 let pkg_bad = dir.path().join("packages").join("bad");
4158 std::fs::create_dir_all(&pkg_good).unwrap();
4159 std::fs::create_dir_all(&pkg_bad).unwrap();
4160 std::fs::write(
4161 dir.path().join("package.json"),
4162 r#"{"workspaces": ["packages/*"]}"#,
4163 )
4164 .unwrap();
4165 std::fs::write(pkg_good.join("package.json"), r#"{"name": "good"}"#).unwrap();
4166 std::fs::write(pkg_bad.join("package.json"), r"{,").unwrap();
4167
4168 let (workspaces, diagnostics) = fallow_config::discover_workspaces_with_diagnostics(
4169 dir.path(),
4170 &fallow_config::IgnorePatternSet::empty(),
4171 )
4172 .expect("root package.json is valid");
4173 assert_eq!(workspaces.len(), 1, "only the valid workspace discovers");
4174 fallow_config::stash_workspace_diagnostics(dir.path(), diagnostics);
4175
4176 warn_undeclared_workspaces(
4177 dir.path(),
4178 &workspaces,
4179 &fallow_config::IgnorePatternSet::empty(),
4180 false,
4181 );
4182
4183 let diagnostics = fallow_config::workspace_diagnostics_for(dir.path());
4184 let mut malformed = 0;
4185 let mut undeclared_for_bad = 0;
4186 for diag in &diagnostics {
4187 if matches!(
4188 diag.kind,
4189 WorkspaceDiagnosticKind::MalformedPackageJson { .. }
4190 ) && diag.path.ends_with("bad")
4191 {
4192 malformed += 1;
4193 }
4194 if matches!(diag.kind, WorkspaceDiagnosticKind::UndeclaredWorkspace)
4195 && diag.path.ends_with("bad")
4196 {
4197 undeclared_for_bad += 1;
4198 }
4199 }
4200 assert_eq!(
4201 malformed, 1,
4202 "expected one MalformedPackageJson for packages/bad: {diagnostics:?}"
4203 );
4204 assert_eq!(
4205 undeclared_for_bad, 0,
4206 "warn_undeclared_workspaces must NOT re-flag a path that already \
4207 carries MalformedPackageJson; got duplicates: {diagnostics:?}"
4208 );
4209 }
4210
4211 #[test]
4216 fn a_rewrite_after_the_parse_read_misses_the_next_run() {
4217 use fallow_types::discover::{DiscoveredFile, FileId};
4218
4219 let project = tempfile::tempdir().expect("create project");
4220 let path = project.path().join("api.ts");
4221 let before = "export const alpha = 1;\n";
4222 let after = "export const bravo = 1;\n";
4223 assert_eq!(before.len(), after.len());
4224 std::fs::write(&path, before).expect("write source");
4225 let discovered = [DiscoveredFile {
4226 id: FileId(0),
4227 path: path.clone(),
4228 size_bytes: u64::try_from(before.len()).expect("source length fits u64"),
4229 }];
4230
4231 let read_started_ns = fallow_types::source_fingerprint::now_ns();
4232 let first = super::extract::parse_all_files(&discovered, None, false);
4233 std::fs::write(&path, after).expect("rewrite source with equal-length content");
4234 let mut store = super::cache::CacheStore::new(project.path());
4235 super::update_cache(
4236 &mut store,
4237 &first.modules,
4238 &discovered,
4239 false,
4240 read_started_ns,
4241 );
4242
4243 let second = super::extract::parse_all_files(&discovered, Some(&store), false);
4244 let exports: Vec<String> = second
4245 .modules
4246 .first()
4247 .expect("second parse produces module")
4248 .exports
4249 .iter()
4250 .map(|export| export.name.to_string())
4251 .collect();
4252 assert_eq!(exports, vec!["bravo".to_string()]);
4253 }
4254}