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;
28mod graph_build;
29mod graph_cache_key;
30mod package_assets;
31mod package_credits;
32pub mod plugins;
33mod production_scope;
34pub(crate) mod progress;
35mod resolution_inputs;
36pub mod results;
37mod script_entries;
38pub(crate) mod scripts;
39#[doc(hidden)]
42pub use scripts::parse_script;
43pub mod suppress;
44#[cfg(test)]
45mod test_config;
46
47pub use fallow_graph::cache as graph_cache;
48pub use fallow_graph::graph;
49pub use fallow_graph::project;
50pub use fallow_graph::resolve;
51
52use std::path::{Path, PathBuf};
53use std::time::Instant;
54
55use errors::FallowError;
56use fallow_config::{
57 EntryPointRole, PackageJson, ResolvedConfig, find_undeclared_workspaces_with_ignores,
58};
59use fallow_types::cache_rejection::CacheRejection;
60use fallow_types::trace::{EntryPointSpans, PipelineCounters, PipelineTimings};
61use package_credits::{
62 credit_bin_path_references, credit_package_path_references, credit_workspace_package_usage,
63};
64use rayon::prelude::*;
65use results::AnalysisResults;
66use rustc_hash::FxHashSet;
67
68const UNDECLARED_WORKSPACE_WARNING_PREVIEW: usize = 5;
69type LoadedWorkspacePackage = (fallow_config::WorkspaceInfo, PackageJson);
70
71#[doc(hidden)]
73pub struct AnalysisOutput {
74 pub results: AnalysisResults,
75 pub timings: Option<PipelineTimings>,
76 pub graph: Option<graph::ModuleGraph>,
77 pub modules: Option<Vec<extract::ModuleInfo>>,
81 pub files: Option<Vec<discover::DiscoveredFile>>,
83 pub script_used_packages: rustc_hash::FxHashSet<String>,
88 pub trace_provenance: fallow_types::trace::TraceProvenance,
91 pub file_hashes: rustc_hash::FxHashMap<std::path::PathBuf, u64>,
100}
101
102#[derive(Debug, Clone, Copy)]
105#[doc(hidden)]
106pub struct AnalysisParseMetrics {
107 parse_ms: f64,
108 cache_ms: f64,
109 cache_hits: usize,
110 cache_misses: usize,
111 parse_cpu_ms: f64,
112 cache_rejection: Option<CacheRejection>,
113}
114
115fn update_cache(
127 store: &mut cache::CacheStore,
128 modules: &[extract::ModuleInfo],
129 files: &[discover::DiscoveredFile],
130 need_complexity: bool,
131 need_call_facts: bool,
132 read_started_ns: u64,
133) -> bool {
134 let mut dirty = false;
135 for module in modules {
136 if let Some(file) = files.get(module.file_id.0 as usize) {
137 let fingerprint = file_fingerprint(&file.path).for_content_read_at(read_started_ns);
138 dirty |= store.record_module(
139 &file.path,
140 module,
141 fingerprint,
142 need_complexity,
143 need_call_facts,
144 );
145 }
146 }
147 let removed_stale_paths = store.retain_paths(files);
148 dirty || removed_stale_paths
149}
150
151#[must_use]
159fn resolve_cache_max_size_bytes(config: &ResolvedConfig) -> usize {
160 config
161 .cache_max_size_mb
162 .map_or(cache::DEFAULT_CACHE_MAX_SIZE, |mb| {
163 (mb as usize).saturating_mul(1024 * 1024)
164 })
165}
166
167fn file_fingerprint(path: &std::path::Path) -> fallow_types::source_fingerprint::SourceFingerprint {
169 std::fs::metadata(path).map_or(
170 fallow_types::source_fingerprint::SourceFingerprint::new(0, 0),
171 |metadata| fallow_types::source_fingerprint::SourceFingerprint::from_metadata(&metadata),
172 )
173}
174
175fn format_undeclared_workspace_warning(
176 root: &Path,
177 undeclared: &[fallow_config::WorkspaceDiagnostic],
178) -> Option<String> {
179 if undeclared.is_empty() {
180 return None;
181 }
182
183 let preview = undeclared
184 .iter()
185 .take(UNDECLARED_WORKSPACE_WARNING_PREVIEW)
186 .map(|diag| {
187 diag.path
188 .strip_prefix(root)
189 .unwrap_or(&diag.path)
190 .display()
191 .to_string()
192 .replace('\\', "/")
193 })
194 .collect::<Vec<_>>();
195 let remaining = undeclared
196 .len()
197 .saturating_sub(UNDECLARED_WORKSPACE_WARNING_PREVIEW);
198 let tail = if remaining > 0 {
199 format!(" (and {remaining} more)")
200 } else {
201 String::new()
202 };
203 let noun = if undeclared.len() == 1 {
204 "directory with package.json is"
205 } else {
206 "directories with package.json are"
207 };
208 let guidance = if undeclared.len() == 1 {
209 "Add that path to package.json workspaces or pnpm-workspace.yaml if it should be analyzed as a workspace."
210 } else {
211 "Add those paths to package.json workspaces or pnpm-workspace.yaml if they should be analyzed as workspaces."
212 };
213
214 Some(format!(
215 "{} {} not declared as {}: {}{}. {}",
216 undeclared.len(),
217 noun,
218 if undeclared.len() == 1 {
219 "a workspace"
220 } else {
221 "workspaces"
222 },
223 preview.join(", "),
224 tail,
225 guidance
226 ))
227}
228
229fn warn_undeclared_workspaces(
230 root: &Path,
231 workspaces_vec: &[fallow_config::WorkspaceInfo],
232 ignore_patterns: &fallow_config::IgnorePatternSet,
233 quiet: bool,
234) {
235 let undeclared = find_undeclared_workspaces_with_ignores(root, workspaces_vec, ignore_patterns);
236 if undeclared.is_empty() {
237 return;
238 }
239
240 let existing = fallow_config::workspace_diagnostics_for(root);
241 let already_flagged: rustc_hash::FxHashSet<PathBuf> = existing
242 .iter()
243 .map(|d| dunce::canonicalize(&d.path).unwrap_or_else(|_| d.path.clone()))
244 .collect();
245 let undeclared: Vec<_> = undeclared
246 .into_iter()
247 .filter(|diag| {
248 let canonical = dunce::canonicalize(&diag.path).unwrap_or_else(|_| diag.path.clone());
249 !already_flagged.contains(&canonical)
250 })
251 .collect();
252 if undeclared.is_empty() {
253 return;
254 }
255
256 fallow_config::append_workspace_diagnostics(root, undeclared.clone());
257
258 if !quiet && let Some(message) = format_undeclared_workspace_warning(root, &undeclared) {
259 tracing::warn!("{message}");
260 }
261}
262
263#[doc(hidden)]
269#[deprecated(
270 since = "2.76.0",
271 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."
272)]
273pub fn analyze(config: &ResolvedConfig) -> Result<AnalysisResults, FallowError> {
274 let output = analyze_full(config, false, false, false, false)?;
275 Ok(output.results)
276}
277
278#[doc(hidden)]
284#[deprecated(
285 since = "2.76.0",
286 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."
287)]
288pub fn analyze_with_usages(config: &ResolvedConfig) -> Result<AnalysisResults, FallowError> {
289 let output = analyze_full(config, false, true, false, false)?;
290 Ok(output.results)
291}
292
293#[doc(hidden)]
299#[deprecated(
300 since = "2.76.0",
301 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."
302)]
303pub fn analyze_with_trace(config: &ResolvedConfig) -> Result<AnalysisOutput, FallowError> {
304 analyze_full(config, true, false, false, false)
305}
306
307#[doc(hidden)]
317#[deprecated(
318 since = "2.76.0",
319 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."
320)]
321pub fn analyze_retaining_modules(
322 config: &ResolvedConfig,
323 need_complexity: bool,
324 retain_graph: bool,
325) -> Result<AnalysisOutput, FallowError> {
326 analyze_full(config, retain_graph, false, need_complexity, true)
327}
328
329fn new_analysis_progress(config: &ResolvedConfig) -> progress::AnalysisProgress {
330 let show_progress = !config.quiet
331 && std::io::IsTerminal::is_terminal(&std::io::stderr())
332 && matches!(
333 config.output,
334 fallow_config::OutputFormat::Human
335 | fallow_config::OutputFormat::Compact
336 | fallow_config::OutputFormat::Markdown
337 );
338 progress::AnalysisProgress::new(show_progress)
339}
340
341fn discover_analysis_workspaces(
342 config: &ResolvedConfig,
343) -> Result<(Vec<fallow_config::WorkspaceInfo>, f64), FallowError> {
344 let t = Instant::now();
345 let (workspaces, diagnostics) =
346 fallow_config::discover_workspaces_with_diagnostics_and_patterns(
347 &config.root,
348 &config.ignore_patterns,
349 &config.workspace_patterns,
350 )
351 .map_err(|error| FallowError::config(error.to_string()))?;
352 fallow_config::stash_workspace_diagnostics(&config.root, diagnostics);
353 let workspaces_ms = t.elapsed().as_secs_f64() * 1000.0;
354 if !workspaces.is_empty() {
355 tracing::info!(count = workspaces.len(), "workspaces discovered");
356 }
357
358 warn_undeclared_workspaces(
359 &config.root,
360 &workspaces,
361 &config.ignore_patterns,
362 config.quiet,
363 );
364
365 Ok((workspaces, workspaces_ms))
366}
367
368struct AnalysisSetup {
372 progress: progress::AnalysisProgress,
373 project: project::ProjectState,
374 root_pkg: Option<PackageJson>,
375 config_candidates: Vec<std::path::PathBuf>,
378 discover_ms: f64,
379 workspaces_ms: f64,
380}
381
382#[derive(Debug, Clone)]
388#[doc(hidden)]
389pub struct AnalysisDiscovery {
390 files: Vec<discover::DiscoveredFile>,
391 workspaces: Vec<fallow_config::WorkspaceInfo>,
392 root_pkg: Option<PackageJson>,
393 config_candidates: Vec<std::path::PathBuf>,
394 discover_ms: f64,
395 workspaces_ms: f64,
396}
397
398impl AnalysisDiscovery {
399 #[must_use]
401 pub fn from_parts(
402 files: Vec<discover::DiscoveredFile>,
403 workspaces: Vec<fallow_config::WorkspaceInfo>,
404 root_pkg: Option<PackageJson>,
405 config_candidates: Vec<std::path::PathBuf>,
406 discover_ms: f64,
407 workspaces_ms: f64,
408 ) -> Self {
409 Self {
410 files,
411 workspaces,
412 root_pkg,
413 config_candidates,
414 discover_ms,
415 workspaces_ms,
416 }
417 }
418
419 #[must_use]
421 fn files(&self) -> &[discover::DiscoveredFile] {
422 &self.files
423 }
424
425 #[must_use]
427 pub fn workspaces(&self) -> &[fallow_config::WorkspaceInfo] {
428 &self.workspaces
429 }
430
431 #[must_use]
433 pub fn into_files(self) -> Vec<discover::DiscoveredFile> {
434 self.files
435 }
436}
437
438pub(crate) struct AnalysisSession<'a> {
443 config: &'a ResolvedConfig,
444 pipeline_start: Instant,
445 progress: progress::AnalysisProgress,
446 project: project::ProjectState,
447 root_pkg: Option<PackageJson>,
448 config_candidates: Vec<std::path::PathBuf>,
449 discover_ms: f64,
450 workspaces_ms: f64,
451}
452
453impl<'a> AnalysisSession<'a> {
454 fn new(config: &'a ResolvedConfig) -> Result<Self, FallowError> {
455 let pipeline_start = Instant::now();
456 let AnalysisSetup {
457 progress,
458 project,
459 root_pkg,
460 config_candidates,
461 discover_ms,
462 workspaces_ms,
463 } = run_analysis_setup(config)?;
464
465 Ok(Self {
466 config,
467 pipeline_start,
468 progress,
469 project,
470 root_pkg,
471 config_candidates,
472 discover_ms,
473 workspaces_ms,
474 })
475 }
476
477 fn files(&self) -> &[discover::DiscoveredFile] {
478 self.project.files()
479 }
480
481 fn workspaces(&self) -> &[fallow_config::WorkspaceInfo] {
482 self.project.workspaces()
483 }
484
485 fn load_workspace_packages(&self) -> Vec<LoadedWorkspacePackage> {
486 load_workspace_packages(self.workspaces())
487 }
488
489 fn run_plugins_and_scripts(
490 &self,
491 workspace_pkgs: &[LoadedWorkspacePackage],
492 ) -> Result<(plugins::AggregatedPluginResult, f64, f64), FallowError> {
493 run_plugins_and_scripts(&PluginScriptInput {
494 config: self.config,
495 progress: &self.progress,
496 files: self.files(),
497 workspaces: self.workspaces(),
498 root_pkg: self.root_pkg.as_ref(),
499 workspace_pkgs,
500 config_candidates: &self.config_candidates,
501 })
502 }
503
504 fn prelude_timings(&self, plugins_ms: f64, scripts_ms: f64) -> PreludeTimings {
505 PreludeTimings {
506 discover_ms: self.discover_ms,
507 workspaces_ms: self.workspaces_ms,
508 plugins_ms,
509 scripts_ms,
510 }
511 }
512
513 fn parse_modules(&self, need_complexity: bool) -> AnalysisParseOutput {
514 let t = Instant::now();
515 self.progress
516 .set_stage(&format!("parsing {} files...", self.files().len()));
517 parse_analysis_modules(self.config, self.files(), need_complexity, t)
518 }
519
520 fn run_owned_core(
521 &self,
522 workspace_pkgs: &[LoadedWorkspacePackage],
523 plugin_result: &plugins::AggregatedPluginResult,
524 mut modules: Vec<extract::ModuleInfo>,
525 collect_usages: bool,
526 ) -> OwnedAnalysisCore {
527 let shared = AnalysisCoreSharedInput {
528 config: self.config,
529 progress: &self.progress,
530 files: self.files(),
531 workspaces: self.workspaces(),
532 root_pkg: self.root_pkg.as_ref(),
533 workspace_pkgs,
534 plugin_result,
535 };
536
537 let entry_points = discover_analysis_entry_points(&shared);
538 let mut graph_cache_rejection = None;
539 let (resolved, graph) =
540 match try_load_analysis_graph_cache(&shared, &entry_points, &modules) {
541 Ok(hit) => (
542 TimedResolvedModules {
543 project: hit.project,
544 elapsed_ms: 0.0,
545 },
546 TimedGraph {
547 graph: hit.graph,
548 elapsed_ms: hit.elapsed_ms,
549 },
550 ),
551 Err(rejection) => {
552 graph_cache_rejection = rejection;
553 let mut resolved = resolve_analysis_imports_timed(&shared, &modules);
554 let graph = build_analysis_graph_timed(
555 &shared,
556 &mut resolved.project,
557 &entry_points,
558 &modules,
559 );
560 (resolved, graph)
561 }
562 };
563 analyze::release_resolution_payloads(&mut modules, self.config);
564 let analysis = analyze_dead_code_timed(
565 &shared,
566 &graph.graph,
567 &resolved.project.modules,
568 &modules,
569 collect_usages,
570 &entry_points,
571 );
572
573 OwnedAnalysisCore {
574 result: analysis.result,
575 graph: graph.graph,
576 modules,
577 entry_point_count: entry_points.count,
578 entry_points_ms: entry_points.elapsed_ms,
579 entry_point_spans: entry_points.spans,
580 resolve_ms: resolved.elapsed_ms,
581 graph_ms: graph.elapsed_ms,
582 analyze_ms: analysis.elapsed_ms,
583 graph_cache_rejection,
584 resolve_work: resolved.project.work,
585 }
586 }
587
588 fn run_full(
589 self,
590 retain: bool,
591 collect_usages: bool,
592 need_complexity: bool,
593 retain_modules: bool,
594 ) -> Result<AnalysisOutput, FallowError> {
595 let workspace_pkgs = self.load_workspace_packages();
596 let (plugin_result, plugins_ms, scripts_ms) =
597 self.run_plugins_and_scripts(&workspace_pkgs)?;
598
599 let AnalysisParseOutput { modules, metrics } = self.parse_modules(need_complexity);
600 let core = self.run_owned_core(&workspace_pkgs, &plugin_result, modules, collect_usages);
601 self.progress.finish();
602
603 let profile = full_analysis_pipeline_profile(
604 &self.prelude_timings(plugins_ms, scripts_ms),
605 self.pipeline_start,
606 self.files(),
607 self.workspaces(),
608 &core,
609 &metrics,
610 );
611 trace_pipeline_profile(&profile);
612
613 let trace_provenance = plugins::trace_provenance::build_trace_provenance(
614 &self.config.root,
615 self.files(),
616 self.workspaces(),
617 &core.modules,
618 &plugin_result,
619 plugins::ExportCredits::for_run(retain, self.config),
620 );
621 let mut output = assemble_full_output(
622 core,
623 plugin_result,
624 &profile,
625 self.files(),
626 retain,
627 retain_modules,
628 );
629 output.trace_provenance = trace_provenance;
630 Ok(output)
631 }
632}
633
634fn run_analysis_setup(config: &ResolvedConfig) -> Result<AnalysisSetup, FallowError> {
637 let progress = new_analysis_progress(config);
638
639 let (workspaces_vec, workspaces_ms) = discover_analysis_workspaces(config)?;
640 let root_pkg = fallow_config::load_dir_package_json(&config.root);
641 let discovery_hidden_dir_scopes =
642 discover::collect_hidden_dir_scopes(config, root_pkg.as_ref(), &workspaces_vec);
643
644 let t = Instant::now();
645 progress.set_stage("discovering files...");
646 let (discovered_files, config_candidates) =
647 discover::discover_files_and_config_candidates(config, &discovery_hidden_dir_scopes);
648 let discover_ms = t.elapsed().as_secs_f64() * 1000.0;
649
650 let project = project::ProjectState::new(discovered_files, workspaces_vec);
651
652 Ok(AnalysisSetup {
653 progress,
654 project,
655 root_pkg,
656 config_candidates,
657 discover_ms,
658 workspaces_ms,
659 })
660}
661
662struct PluginScriptInput<'a> {
664 config: &'a ResolvedConfig,
665 progress: &'a progress::AnalysisProgress,
666 files: &'a [discover::DiscoveredFile],
667 workspaces: &'a [fallow_config::WorkspaceInfo],
668 root_pkg: Option<&'a PackageJson>,
669 workspace_pkgs: &'a [LoadedWorkspacePackage],
670 config_candidates: &'a [std::path::PathBuf],
671}
672
673fn run_plugins_and_scripts(
676 input: &PluginScriptInput<'_>,
677) -> Result<(plugins::AggregatedPluginResult, f64, f64), FallowError> {
678 let t = Instant::now();
679 input.progress.set_stage("detecting plugins...");
680 let mut plugin_result = run_plugins(
681 input.config,
682 input.files,
683 input.workspaces,
684 input.root_pkg,
685 input.workspace_pkgs,
686 input.config_candidates,
687 )?;
688 let plugins_ms = t.elapsed().as_secs_f64() * 1000.0;
689
690 let t = Instant::now();
691 analyze_all_scripts(
692 input.config,
693 input.workspaces,
694 input.root_pkg,
695 input.workspace_pkgs,
696 &mut plugin_result,
697 );
698 let scripts_ms = t.elapsed().as_secs_f64() * 1000.0;
699
700 Ok((plugin_result, plugins_ms, scripts_ms))
701}
702
703#[derive(Debug, Clone, Copy)]
705#[doc(hidden)]
706pub struct DeadCodePreludeTimings {
707 pub discover_ms: f64,
708 pub workspaces_ms: f64,
709 pub plugins_ms: f64,
710 pub scripts_ms: f64,
711}
712
713#[doc(hidden)]
718pub struct DeadCodeBackendPrelude<'a> {
719 config: &'a ResolvedConfig,
720 pipeline_start: Instant,
721 progress: progress::AnalysisProgress,
722 discovery: AnalysisDiscovery,
723 workspace_pkgs: Vec<LoadedWorkspacePackage>,
724 plugin_result: plugins::AggregatedPluginResult,
725 plugins_ms: f64,
726 scripts_ms: f64,
727}
728
729impl DeadCodeBackendPrelude<'_> {
730 #[must_use]
731 pub fn timings(&self) -> DeadCodePreludeTimings {
732 DeadCodePreludeTimings {
733 discover_ms: self.discovery.discover_ms,
734 workspaces_ms: self.discovery.workspaces_ms,
735 plugins_ms: self.plugins_ms,
736 scripts_ms: self.scripts_ms,
737 }
738 }
739
740 #[must_use]
741 pub fn elapsed_ms(&self) -> f64 {
742 self.pipeline_start.elapsed().as_secs_f64() * 1000.0
743 }
744
745 #[must_use]
746 pub fn script_used_packages(&self) -> FxHashSet<String> {
747 self.plugin_result.script_used_packages.clone()
748 }
749
750 #[must_use]
753 pub fn trace_provenance(
754 &self,
755 modules: &[extract::ModuleInfo],
756 retain_graph: bool,
757 ) -> fallow_types::trace::TraceProvenance {
758 plugins::trace_provenance::build_trace_provenance(
759 &self.config.root,
760 self.discovery.files(),
761 self.discovery.workspaces(),
762 modules,
763 &self.plugin_result,
764 plugins::ExportCredits::for_run(retain_graph, self.config),
765 )
766 }
767
768 #[must_use]
771 pub const fn plugin_result(&self) -> &plugins::AggregatedPluginResult {
772 &self.plugin_result
773 }
774
775 pub fn finish(&self) {
776 self.progress.finish();
777 }
778}
779
780#[doc(hidden)]
782pub struct DeadCodeEntryPoints {
783 inner: TimedEntryPoints,
784}
785
786impl DeadCodeEntryPoints {
787 #[must_use]
788 pub fn count(&self) -> usize {
789 self.inner.count
790 }
791
792 #[must_use]
793 pub fn elapsed_ms(&self) -> f64 {
794 self.inner.elapsed_ms
795 }
796
797 #[must_use]
799 pub fn spans(&self) -> EntryPointSpans {
800 self.inner.spans
801 }
802
803 #[must_use]
805 pub fn all(&self) -> &[discover::EntryPoint] {
806 &self.inner.entry_points.all
807 }
808}
809
810#[doc(hidden)]
812pub struct DeadCodeResolvedModules {
813 pub project: resolve::ResolvedProject,
814 pub elapsed_ms: f64,
815}
816
817#[doc(hidden)]
819pub struct DeadCodeGraphRun {
820 pub graph: graph::ModuleGraph,
821 pub elapsed_ms: f64,
822}
823
824#[doc(hidden)]
826pub struct DeadCodeDetectorRun {
827 pub results: AnalysisResults,
828 pub elapsed_ms: f64,
829}
830
831pub fn prepare_dead_code_backend_prelude(
837 config: &ResolvedConfig,
838 discovery: AnalysisDiscovery,
839) -> Result<DeadCodeBackendPrelude<'_>, FallowError> {
840 let progress = new_analysis_progress(config);
841 let pipeline_start = Instant::now();
842 let workspace_pkgs = load_workspace_packages(&discovery.workspaces);
843 let (plugin_result, plugins_ms, scripts_ms) = run_plugins_and_scripts(&PluginScriptInput {
844 config,
845 progress: &progress,
846 files: discovery.files(),
847 workspaces: &discovery.workspaces,
848 root_pkg: discovery.root_pkg.as_ref(),
849 workspace_pkgs: &workspace_pkgs,
850 config_candidates: &discovery.config_candidates,
851 })?;
852
853 Ok(DeadCodeBackendPrelude {
854 config,
855 pipeline_start,
856 progress,
857 discovery,
858 workspace_pkgs,
859 plugin_result,
860 plugins_ms,
861 scripts_ms,
862 })
863}
864
865#[must_use]
867pub fn discover_dead_code_entry_points(
868 prelude: &DeadCodeBackendPrelude<'_>,
869) -> DeadCodeEntryPoints {
870 let shared = prelude.shared_input();
871 DeadCodeEntryPoints {
872 inner: discover_analysis_entry_points(&shared),
873 }
874}
875
876pub fn try_load_dead_code_graph_cache(
886 prelude: &DeadCodeBackendPrelude<'_>,
887 entry_points: &DeadCodeEntryPoints,
888 modules: &[extract::ModuleInfo],
889) -> Result<(DeadCodeResolvedModules, DeadCodeGraphRun), Option<CacheRejection>> {
890 let shared = prelude.shared_input();
891 try_load_analysis_graph_cache(&shared, &entry_points.inner, modules).map(|hit| {
892 (
893 DeadCodeResolvedModules {
894 project: hit.project,
895 elapsed_ms: 0.0,
896 },
897 DeadCodeGraphRun {
898 graph: hit.graph,
899 elapsed_ms: hit.elapsed_ms,
900 },
901 )
902 })
903}
904
905#[must_use]
907pub fn resolve_dead_code_imports(
908 prelude: &DeadCodeBackendPrelude<'_>,
909 modules: &[extract::ModuleInfo],
910) -> DeadCodeResolvedModules {
911 let shared = prelude.shared_input();
912 let resolved = resolve_analysis_imports_timed(&shared, modules);
913 DeadCodeResolvedModules {
914 project: resolved.project,
915 elapsed_ms: resolved.elapsed_ms,
916 }
917}
918
919#[must_use]
921pub fn build_dead_code_graph(
922 prelude: &DeadCodeBackendPrelude<'_>,
923 project: &mut resolve::ResolvedProject,
924 entry_points: &DeadCodeEntryPoints,
925 modules: &[extract::ModuleInfo],
926) -> DeadCodeGraphRun {
927 let shared = prelude.shared_input();
928 let graph = build_analysis_graph_timed(&shared, project, &entry_points.inner, modules);
929 DeadCodeGraphRun {
930 graph: graph.graph,
931 elapsed_ms: graph.elapsed_ms,
932 }
933}
934
935#[must_use]
937pub fn run_dead_code_detectors(
938 prelude: &DeadCodeBackendPrelude<'_>,
939 graph: &graph::ModuleGraph,
940 resolved: &[resolve::ResolvedModule],
941 modules: &[extract::ModuleInfo],
942 collect_usages: bool,
943 entry_points: &DeadCodeEntryPoints,
944) -> DeadCodeDetectorRun {
945 let shared = prelude.shared_input();
946 let analysis = analyze_dead_code_timed(
947 &shared,
948 graph,
949 resolved,
950 modules,
951 collect_usages,
952 &entry_points.inner,
953 );
954 DeadCodeDetectorRun {
955 results: analysis.result,
956 elapsed_ms: analysis.elapsed_ms,
957 }
958}
959
960impl<'a> DeadCodeBackendPrelude<'a> {
961 fn shared_input(&'a self) -> AnalysisCoreSharedInput<'a> {
962 AnalysisCoreSharedInput {
963 config: self.config,
964 progress: &self.progress,
965 files: self.discovery.files(),
966 workspaces: &self.discovery.workspaces,
967 root_pkg: self.discovery.root_pkg.as_ref(),
968 workspace_pkgs: &self.workspace_pkgs,
969 plugin_result: &self.plugin_result,
970 }
971 }
972}
973
974struct PreludeMetrics {
977 discover_ms: f64,
978 workspaces_ms: f64,
979 plugins_ms: f64,
980 scripts_ms: f64,
981 total_ms: f64,
982 file_count: usize,
983 workspace_count: usize,
984 module_count: usize,
985}
986
987#[expect(
989 clippy::struct_field_names,
990 reason = "timings are all milliseconds; the _ms suffix is the unit"
991)]
992struct PreludeTimings {
993 discover_ms: f64,
994 workspaces_ms: f64,
995 plugins_ms: f64,
996 scripts_ms: f64,
997}
998
999fn prelude_metrics(
1002 timings: &PreludeTimings,
1003 pipeline_start: Instant,
1004 files: &[discover::DiscoveredFile],
1005 workspaces: &[fallow_config::WorkspaceInfo],
1006 module_count: usize,
1007) -> PreludeMetrics {
1008 PreludeMetrics {
1009 discover_ms: timings.discover_ms,
1010 workspaces_ms: timings.workspaces_ms,
1011 plugins_ms: timings.plugins_ms,
1012 scripts_ms: timings.scripts_ms,
1013 total_ms: pipeline_start.elapsed().as_secs_f64() * 1000.0,
1014 file_count: files.len(),
1015 workspace_count: workspaces.len(),
1016 module_count,
1017 }
1018}
1019
1020struct AnalysisCoreSharedInput<'a> {
1021 config: &'a ResolvedConfig,
1022 progress: &'a progress::AnalysisProgress,
1023 files: &'a [discover::DiscoveredFile],
1024 workspaces: &'a [fallow_config::WorkspaceInfo],
1025 root_pkg: Option<&'a PackageJson>,
1026 workspace_pkgs: &'a [LoadedWorkspacePackage],
1027 plugin_result: &'a plugins::AggregatedPluginResult,
1028}
1029
1030struct TimedEntryPoints {
1031 entry_points: discover::CategorizedEntryPoints,
1032 summary: results::EntryPointSummary,
1033 count: usize,
1034 elapsed_ms: f64,
1035 spans: EntryPointSpans,
1036}
1037
1038struct TimedResolvedModules {
1039 project: resolve::ResolvedProject,
1040 elapsed_ms: f64,
1041}
1042
1043struct TimedGraph {
1044 graph: graph::ModuleGraph,
1045 elapsed_ms: f64,
1046}
1047
1048struct GraphCacheHit {
1049 graph: graph::ModuleGraph,
1050 project: resolve::ResolvedProject,
1051 elapsed_ms: f64,
1052}
1053
1054#[derive(Clone, Copy)]
1055struct DiscoverAllEntryPointsInput<'a> {
1056 config: &'a ResolvedConfig,
1057 files: &'a [discover::DiscoveredFile],
1058 workspaces: &'a [fallow_config::WorkspaceInfo],
1059 root_pkg: Option<&'a PackageJson>,
1060 workspace_pkgs: &'a [LoadedWorkspacePackage],
1061 plugin_result: &'a plugins::AggregatedPluginResult,
1062}
1063
1064struct TimedAnalysis {
1065 result: AnalysisResults,
1066 elapsed_ms: f64,
1067}
1068
1069fn discover_analysis_entry_points(input: &AnalysisCoreSharedInput<'_>) -> TimedEntryPoints {
1070 let t = Instant::now();
1071 let (entry_points, spans) = discover_all_entry_points(DiscoverAllEntryPointsInput {
1072 config: input.config,
1073 files: input.files,
1074 workspaces: input.workspaces,
1075 root_pkg: input.root_pkg,
1076 workspace_pkgs: input.workspace_pkgs,
1077 plugin_result: input.plugin_result,
1078 });
1079 let elapsed_ms = t.elapsed().as_secs_f64() * 1000.0;
1080 let summary = discover::summarize_entry_points(&entry_points.all);
1081 let count = entry_points.all.len();
1082
1083 TimedEntryPoints {
1084 entry_points,
1085 summary,
1086 count,
1087 elapsed_ms,
1088 spans,
1089 }
1090}
1091
1092fn try_load_analysis_graph_cache(
1102 input: &AnalysisCoreSharedInput<'_>,
1103 entry_points: &TimedEntryPoints,
1104 modules: &[extract::ModuleInfo],
1105) -> Result<GraphCacheHit, Option<CacheRejection>> {
1106 if input.config.no_cache {
1107 return Err(None);
1108 }
1109
1110 let t = Instant::now();
1111 input.progress.set_stage("loading module graph cache...");
1112 let unseeded_declaration_files = orphan_module_declaration_files(input, modules);
1113 let current = build_graph_cache_manifest(&GraphCacheManifestInput {
1114 config: input.config,
1115 plugin_result: input.plugin_result,
1116 entry_points: &entry_points.entry_points,
1117 files: input.files,
1118 workspaces: input.workspaces,
1119 modules,
1120 unseeded_declaration_files: &unseeded_declaration_files,
1121 });
1122 let store = graph_cache::GraphCacheStore::load(&input.config.cache_dir).map_err(Some)?;
1123 if store.manifest.matches_inputs(¤t) {
1124 let mut project = restore_cached_resolved_project(input, modules, &store.resolved_project)?;
1125 tracing::debug!("Graph cache hit: skipping import resolution and graph build");
1126 let excluded = production_scope::excluded_file_ids(
1127 &entry_points.entry_points,
1128 input.files,
1129 &project.modules,
1130 );
1131 production_scope::neutralize(&mut project.modules, &excluded);
1132 let mut graph = store.graph;
1133 let bins = &input.plugin_result.dependency_binaries;
1134 credit_bin_path_references(&mut graph, modules, bins, &excluded);
1135
1136 return Ok(GraphCacheHit {
1137 graph,
1138 project,
1139 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1140 });
1141 }
1142
1143 if let Some(rejection) = store.manifest.classify_resolution_mismatch(¤t) {
1144 if rejection.discarded_existing_work() {
1148 tracing::warn!(
1149 target: fallow_types::ANALYSIS_DIAGNOSTIC_LOG_TARGET,
1150 "Graph cache decoded but not reused: {}",
1151 rejection.describe()
1152 );
1153 } else {
1154 tracing::debug!(
1155 "Graph cache decoded but not reused: {}",
1156 rejection.describe()
1157 );
1158 }
1159 return Err(Some(rejection));
1160 }
1161
1162 let mut project = restore_cached_resolved_project(input, modules, &store.resolved_project)?;
1163 tracing::debug!("Graph resolver cache hit: skipping import resolution and rebuilding graph");
1164 let graph = build_analysis_graph_timed(input, &mut project, entry_points, modules);
1165
1166 Ok(GraphCacheHit {
1167 graph: graph.graph,
1168 project,
1169 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1170 })
1171}
1172
1173fn restore_cached_resolved_project(
1179 input: &AnalysisCoreSharedInput<'_>,
1180 modules: &[extract::ModuleInfo],
1181 resolved_project: &graph_cache::CachedResolvedProject,
1182) -> Result<resolve::ResolvedProject, Option<CacheRejection>> {
1183 graph_cache::restore_resolved_project(
1184 &input.config.root,
1185 modules,
1186 input.files,
1187 resolved_project,
1188 )
1189 .inspect(|project| {
1190 record_unreadable_auto_import_reads(
1191 project,
1192 input.files,
1193 input.plugin_result,
1194 input.config,
1195 );
1196 })
1197 .ok_or_else(|| {
1198 tracing::debug!(
1202 "Graph cache decoded but its resolver payload no longer maps to the project files"
1203 );
1204 Some(CacheRejection::FileSetChanged)
1205 })
1206}
1207
1208fn resolve_analysis_imports_timed(
1209 input: &AnalysisCoreSharedInput<'_>,
1210 modules: &[extract::ModuleInfo],
1211) -> TimedResolvedModules {
1212 let t = Instant::now();
1213 input.progress.set_stage("resolving imports...");
1214 let project = resolve_analysis_imports(
1215 modules,
1216 input.files,
1217 input.workspaces,
1218 input.plugin_result,
1219 input.config,
1220 );
1221 TimedResolvedModules {
1222 project,
1223 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1224 }
1225}
1226
1227fn build_analysis_graph_timed(
1228 input: &AnalysisCoreSharedInput<'_>,
1229 project: &mut resolve::ResolvedProject,
1230 entry_points: &TimedEntryPoints,
1231 modules: &[extract::ModuleInfo],
1232) -> TimedGraph {
1233 let t = Instant::now();
1234 input.progress.set_stage("building module graph...");
1235 let unseeded_declaration_files = orphan_module_declaration_files(input, modules);
1236 let excluded = production_scope::excluded_file_ids(
1237 &entry_points.entry_points,
1238 input.files,
1239 &project.modules,
1240 );
1241 let mut graph = build_analysis_graph(&mut BuildAnalysisGraphInput {
1242 config: input.config,
1243 plugin_result: input.plugin_result,
1244 project,
1245 entry_points: &entry_points.entry_points,
1246 files: input.files,
1247 modules,
1248 workspaces: input.workspaces,
1249 unseeded_declaration_files: &unseeded_declaration_files,
1250 excluded: &excluded,
1251 });
1252 let bins = &input.plugin_result.dependency_binaries;
1253 credit_bin_path_references(&mut graph, modules, bins, &excluded);
1254 TimedGraph {
1255 graph,
1256 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1257 }
1258}
1259
1260fn orphan_module_declaration_files(
1263 input: &AnalysisCoreSharedInput<'_>,
1264 modules: &[extract::ModuleInfo],
1265) -> FxHashSet<discover::FileId> {
1266 discover::find_orphan_module_declaration_files(&input.config.root, input.files, modules)
1267}
1268
1269fn analyze_dead_code_timed(
1270 input: &AnalysisCoreSharedInput<'_>,
1271 graph: &graph::ModuleGraph,
1272 resolved: &[resolve::ResolvedModule],
1273 modules: &[extract::ModuleInfo],
1274 collect_usages: bool,
1275 entry_points: &TimedEntryPoints,
1276) -> TimedAnalysis {
1277 let t = Instant::now();
1278 input.progress.set_stage("analyzing...");
1279 let excluded =
1280 production_scope::excluded_file_ids(&entry_points.entry_points, input.files, resolved);
1281 let mut result = analyze::find_dead_code_full(
1282 graph,
1283 input.config,
1284 resolved,
1285 Some(input.plugin_result),
1286 input.workspaces,
1287 modules,
1288 collect_usages,
1289 &excluded,
1290 );
1291 production_scope::hide_findings(&mut result, input.files, &excluded);
1292 result.entry_point_summary = Some(entry_points.summary.clone());
1293 TimedAnalysis {
1294 result,
1295 elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1296 }
1297}
1298
1299fn analyze_full(
1300 config: &ResolvedConfig,
1301 retain: bool,
1302 collect_usages: bool,
1303 need_complexity: bool,
1304 retain_modules: bool,
1305) -> Result<AnalysisOutput, FallowError> {
1306 let _span = tracing::info_span!("fallow_analyze").entered();
1307 AnalysisSession::new(config)?.run_full(retain, collect_usages, need_complexity, retain_modules)
1308}
1309
1310fn full_analysis_pipeline_profile(
1311 timings: &PreludeTimings,
1312 pipeline_start: Instant,
1313 files: &[discover::DiscoveredFile],
1314 workspaces: &[fallow_config::WorkspaceInfo],
1315 core: &OwnedAnalysisCore,
1316 metrics: &ParseMetrics,
1317) -> PipelineProfile {
1318 let prelude = prelude_metrics(
1319 timings,
1320 pipeline_start,
1321 files,
1322 workspaces,
1323 core.modules.len(),
1324 );
1325 full_pipeline_profile(&prelude, core, metrics)
1326}
1327
1328fn assemble_full_output(
1331 core: OwnedAnalysisCore,
1332 plugin_result: plugins::AggregatedPluginResult,
1333 profile: &PipelineProfile,
1334 files: &[discover::DiscoveredFile],
1335 retain: bool,
1336 retain_modules: bool,
1337) -> AnalysisOutput {
1338 let file_hashes = collect_file_hashes(&core.modules, files);
1339 AnalysisOutput {
1340 results: core.result,
1341 timings: retained_pipeline_timings(retain, profile),
1342 graph: if retain { Some(core.graph) } else { None },
1343 modules: if retain_modules {
1344 Some(core.modules)
1345 } else {
1346 None
1347 },
1348 files: if retain_modules {
1349 Some(files.to_vec())
1350 } else {
1351 None
1352 },
1353 script_used_packages: plugin_result.script_used_packages,
1354 trace_provenance: fallow_types::trace::TraceProvenance::default(),
1355 file_hashes,
1356 }
1357}
1358
1359struct OwnedAnalysisCore {
1362 result: AnalysisResults,
1363 graph: graph::ModuleGraph,
1364 modules: Vec<extract::ModuleInfo>,
1365 entry_point_count: usize,
1366 entry_points_ms: f64,
1367 entry_point_spans: EntryPointSpans,
1368 resolve_ms: f64,
1369 graph_ms: f64,
1370 analyze_ms: f64,
1371 graph_cache_rejection: Option<CacheRejection>,
1372 resolve_work: resolve::ResolveWork,
1373}
1374
1375fn full_pipeline_profile(
1377 prelude: &PreludeMetrics,
1378 core: &OwnedAnalysisCore,
1379 parse: &ParseMetrics,
1380) -> PipelineProfile {
1381 PipelineProfile {
1382 discover_ms: prelude.discover_ms,
1383 workspaces_ms: prelude.workspaces_ms,
1384 plugins_ms: prelude.plugins_ms,
1385 scripts_ms: prelude.scripts_ms,
1386 parse_ms: parse.parse_ms,
1387 cache_ms: parse.cache_ms,
1388 entry_points_ms: core.entry_points_ms,
1389 entry_point_spans: core.entry_point_spans,
1390 resolve_ms: core.resolve_ms,
1391 graph_ms: core.graph_ms,
1392 analyze_ms: core.analyze_ms,
1393 total_ms: prelude.total_ms,
1394 file_count: prelude.file_count,
1395 workspace_count: prelude.workspace_count,
1396 module_count: prelude.module_count,
1397 entry_point_count: core.entry_point_count,
1398 cache_hits: parse.cache_hits,
1399 cache_misses: parse.cache_misses,
1400 parse_cpu_ms: parse.parse_cpu_ms,
1401 parse_cache_load_ms: parse.parse_cache_load_ms,
1402 cache_rejection: parse.cache_rejection,
1403 graph_cache_rejection: core.graph_cache_rejection,
1404 counters: PipelineCounters {
1405 files_read: parse.files_read,
1406 source_bytes_read: parse.source_bytes_read,
1407 parse_cache_bytes_read: parse.parse_cache_bytes_read,
1408 css_masked_bytes: parse.css_masked_bytes,
1409 resolve_specifier_calls: core.resolve_work.specifier_calls,
1410 unique_specifiers: core.resolve_work.unique_specifiers,
1411 oxc_resolve_calls: core.resolve_work.oxc_resolve_calls,
1412 canonicalize_calls: core.resolve_work.canonicalize_calls,
1413 },
1414 }
1415}
1416
1417#[derive(Clone, Copy)]
1418struct PipelineProfile {
1419 discover_ms: f64,
1420 workspaces_ms: f64,
1421 plugins_ms: f64,
1422 scripts_ms: f64,
1423 parse_ms: f64,
1424 cache_ms: f64,
1425 entry_points_ms: f64,
1426 entry_point_spans: EntryPointSpans,
1427 resolve_ms: f64,
1428 graph_ms: f64,
1429 analyze_ms: f64,
1430 total_ms: f64,
1431 file_count: usize,
1432 workspace_count: usize,
1433 module_count: usize,
1434 entry_point_count: usize,
1435 cache_hits: usize,
1436 cache_misses: usize,
1437 parse_cpu_ms: f64,
1438 parse_cache_load_ms: f64,
1439 cache_rejection: Option<CacheRejection>,
1440 graph_cache_rejection: Option<CacheRejection>,
1441 counters: PipelineCounters,
1442}
1443
1444struct AnalysisParseOutput {
1445 modules: Vec<extract::ModuleInfo>,
1446 metrics: ParseMetrics,
1447}
1448
1449struct ParseMetrics {
1451 parse_ms: f64,
1452 cache_ms: f64,
1453 cache_hits: usize,
1454 cache_misses: usize,
1455 parse_cpu_ms: f64,
1456 cache_rejection: Option<CacheRejection>,
1458 files_read: u64,
1459 source_bytes_read: u64,
1460 parse_cache_bytes_read: u64,
1461 css_masked_bytes: u64,
1462 parse_cache_load_ms: f64,
1463}
1464
1465impl From<AnalysisParseMetrics> for ParseMetrics {
1466 fn from(metrics: AnalysisParseMetrics) -> Self {
1467 Self {
1468 parse_ms: metrics.parse_ms,
1469 cache_ms: metrics.cache_ms,
1470 cache_hits: metrics.cache_hits,
1471 cache_misses: metrics.cache_misses,
1472 parse_cpu_ms: metrics.parse_cpu_ms,
1473 cache_rejection: metrics.cache_rejection,
1474 files_read: 0,
1475 source_bytes_read: 0,
1476 parse_cache_bytes_read: 0,
1477 css_masked_bytes: 0,
1478 parse_cache_load_ms: 0.0,
1479 }
1480 }
1481}
1482
1483fn parse_analysis_modules(
1484 config: &ResolvedConfig,
1485 files: &[discover::DiscoveredFile],
1486 need_complexity: bool,
1487 start: Instant,
1488) -> AnalysisParseOutput {
1489 let cache_max_size_bytes = resolve_cache_max_size_bytes(config);
1490 let mut cache_rejection = None;
1491 let mut parse_cache_bytes_read = 0;
1492 let mut parse_cache_load_ms = 0.0;
1493 let mut cache_store = if config.no_cache {
1494 None
1495 } else {
1496 let load_start = Instant::now();
1497 let (loaded, bytes_read) = cache::CacheStore::load_counting_bytes(
1498 &config.cache_dir,
1499 &config.root,
1500 config.cache_config_hash,
1501 cache_max_size_bytes,
1502 );
1503 parse_cache_bytes_read = bytes_read;
1504 parse_cache_load_ms = load_start.elapsed().as_secs_f64() * 1000.0;
1505 match loaded {
1506 Ok(store) => Some(store),
1507 Err(rejection) => {
1508 cache_rejection = Some(rejection);
1509 None
1510 }
1511 }
1512 };
1513
1514 let read_started_ns = fallow_types::source_fingerprint::now_ns();
1515 let parse_result = extract::parse_all_files_with_mode(
1516 files,
1517 cache_store.as_ref(),
1518 extract::ParseNeeds {
1519 complexity: need_complexity,
1520 call_facts: config.reads_call_facts(),
1521 },
1522 None,
1523 &config.flags.patterns(),
1524 fallow_types::shared_state::ExtractionMode::Standard,
1525 );
1526 let _ = fallow_config::record_source_read_failures(&config.root, &parse_result.read_failures);
1527 let _ =
1528 fallow_config::record_source_parse_degradations(config, &parse_result.parse_degradations);
1529 let modules = parse_result.modules;
1530 let parse_ms = start.elapsed().as_secs_f64() * 1000.0;
1531 let cache_ms = update_parse_cache_if_enabled(
1532 config,
1533 &mut cache_store,
1534 &modules,
1535 files,
1536 need_complexity,
1537 read_started_ns,
1538 );
1539
1540 AnalysisParseOutput {
1541 modules,
1542 metrics: ParseMetrics {
1543 parse_ms,
1544 cache_ms,
1545 cache_hits: parse_result.cache_hits,
1546 cache_misses: parse_result.cache_misses,
1547 parse_cpu_ms: parse_result.parse_cpu_ms,
1548 cache_rejection,
1549 files_read: parse_result.files_read,
1550 source_bytes_read: parse_result.source_bytes_read,
1551 parse_cache_bytes_read,
1552 css_masked_bytes: parse_result.css_masked_bytes,
1553 parse_cache_load_ms,
1554 },
1555 }
1556}
1557
1558fn retained_pipeline_timings(retain: bool, profile: &PipelineProfile) -> Option<PipelineTimings> {
1559 retain.then_some(PipelineTimings {
1560 discover_files_ms: profile.discover_ms,
1561 file_count: profile.file_count,
1562 workspaces_ms: profile.workspaces_ms,
1563 workspace_count: profile.workspace_count,
1564 plugins_ms: profile.plugins_ms,
1565 script_analysis_ms: profile.scripts_ms,
1566 parse_extract_ms: profile.parse_ms,
1567 parse_cpu_ms: profile.parse_cpu_ms,
1568 parse_cache_load_ms: profile.parse_cache_load_ms,
1569 module_count: profile.module_count,
1570 cache_hits: profile.cache_hits,
1571 cache_misses: profile.cache_misses,
1572 cache_rejection: profile.cache_rejection,
1573 graph_cache_rejection: profile.graph_cache_rejection,
1574 cache_update_ms: profile.cache_ms,
1575 entry_points_ms: profile.entry_points_ms,
1576 entry_point_spans: profile.entry_point_spans,
1577 entry_point_count: profile.entry_point_count,
1578 resolve_imports_ms: profile.resolve_ms,
1579 build_graph_ms: profile.graph_ms,
1580 analyze_ms: profile.analyze_ms,
1581 duplication_ms: None,
1582 total_ms: profile.total_ms,
1583 counters: profile.counters,
1584 })
1585}
1586
1587fn update_parse_cache_if_enabled(
1588 config: &ResolvedConfig,
1589 cache_store: &mut Option<cache::CacheStore>,
1590 modules: &[extract::ModuleInfo],
1591 files: &[discover::DiscoveredFile],
1592 need_complexity: bool,
1593 read_started_ns: u64,
1594) -> f64 {
1595 let t = Instant::now();
1596 if !config.no_cache {
1597 let cache_max_size_bytes = resolve_cache_max_size_bytes(config);
1598 let store = cache_store.get_or_insert_with(|| cache::CacheStore::new(&config.root));
1599 if update_cache(
1600 store,
1601 modules,
1602 files,
1603 need_complexity,
1604 config.reads_call_facts(),
1605 read_started_ns,
1606 ) && let Err(error) = store.save(
1607 config.cache_target(),
1608 config.cache_config_hash,
1609 cache_max_size_bytes,
1610 ) {
1611 tracing::warn!("Failed to save cache: {error}");
1612 }
1613 }
1614 t.elapsed().as_secs_f64() * 1000.0
1615}
1616
1617fn resolve_analysis_imports(
1618 modules: &[extract::ModuleInfo],
1619 files: &[discover::DiscoveredFile],
1620 workspaces: &[fallow_config::WorkspaceInfo],
1621 plugin_result: &plugins::AggregatedPluginResult,
1622 config: &ResolvedConfig,
1623) -> resolve::ResolvedProject {
1624 let mut project = resolve::resolve_all_imports(&resolve::ResolveAllImportsInput {
1625 modules,
1626 files,
1627 workspaces,
1628 ..graph_cache_key::plugin_resolve_input(
1629 plugin_result,
1630 &config.root,
1631 &config.resolve.conditions,
1632 )
1633 });
1634 external_style_usage::augment_external_style_package_usage(
1635 &mut project.modules,
1636 config,
1637 workspaces,
1638 plugin_result,
1639 );
1640 record_unreadable_auto_import_reads(&project, files, plugin_result, config);
1641 project
1642}
1643
1644fn record_unreadable_auto_import_reads(
1656 project: &resolve::ResolvedProject,
1657 files: &[discover::DiscoveredFile],
1658 plugin_result: &plugins::AggregatedPluginResult,
1659 config: &ResolvedConfig,
1660) {
1661 if !config.auto_imports
1662 || plugin_result.auto_imports.is_empty()
1663 || !plugin_result
1664 .active_plugins
1665 .iter()
1666 .any(|name| name == "nuxt")
1667 {
1668 return;
1669 }
1670 let diagnostics: Vec<fallow_config::WorkspaceDiagnostic> =
1671 resolve::unreadable_auto_import_reads(&project.modules)
1672 .into_iter()
1673 .filter_map(|read| {
1674 let file = files.get(read.file_id.0 as usize)?;
1675 let diagnostic = plugins::PluginConfigDiagnostic::not_modeled(
1676 &file.path,
1677 "nuxt",
1678 read.module,
1679 AUTO_IMPORT_KEY_NOT_MODELED,
1680 );
1681 Some(diagnostic.into_workspace_diagnostic(&config.root))
1682 })
1683 .collect();
1684 fallow_config::append_workspace_diagnostics(&config.root, diagnostics);
1685}
1686
1687struct BuildAnalysisGraphInput<'a> {
1688 config: &'a ResolvedConfig,
1689 plugin_result: &'a plugins::AggregatedPluginResult,
1690 project: &'a mut resolve::ResolvedProject,
1691 entry_points: &'a discover::CategorizedEntryPoints,
1692 files: &'a [discover::DiscoveredFile],
1693 modules: &'a [extract::ModuleInfo],
1694 workspaces: &'a [fallow_config::WorkspaceInfo],
1695 unseeded_declaration_files: &'a FxHashSet<discover::FileId>,
1696 excluded: &'a FxHashSet<discover::FileId>,
1699}
1700
1701fn build_analysis_graph(input: &mut BuildAnalysisGraphInput<'_>) -> graph::ModuleGraph {
1709 let caching_enabled = !input.config.no_cache;
1710 let current_manifest = caching_enabled.then(|| {
1711 build_graph_cache_manifest(&GraphCacheManifestInput {
1712 config: input.config,
1713 plugin_result: input.plugin_result,
1714 entry_points: input.entry_points,
1715 files: input.files,
1716 workspaces: input.workspaces,
1717 modules: input.modules,
1718 unseeded_declaration_files: input.unseeded_declaration_files,
1719 })
1720 });
1721 let resolved_payload = current_manifest.as_ref().and_then(|_| {
1722 graph_cache::cache_resolved_project(&input.config.root, input.files, input.project)
1723 });
1724 production_scope::neutralize(&mut input.project.modules, input.excluded);
1725
1726 let mut graph = graph_build::build_module_graph(
1727 input.config,
1728 input.project,
1729 input.entry_points,
1730 input.files,
1731 input.workspaces,
1732 input.unseeded_declaration_files,
1733 );
1734 graph.set_support_entry_points(&input.entry_points.support);
1735 credit_package_path_references(&mut graph, input.modules, input.excluded);
1736 credit_workspace_package_usage(&mut graph, &input.project.modules, input.workspaces);
1737
1738 if let Some(manifest) = current_manifest {
1739 let Some(resolved_project) = resolved_payload else {
1740 return graph;
1741 };
1742 let store = graph_cache::GraphCacheStore {
1743 version: graph_cache::GRAPH_CACHE_VERSION,
1744 manifest,
1745 graph,
1746 resolved_project,
1747 };
1748 store.save(input.config.cache_target());
1749 return store.graph;
1753 }
1754
1755 graph
1756}
1757
1758struct GraphCacheManifestInput<'a> {
1760 config: &'a ResolvedConfig,
1761 plugin_result: &'a plugins::AggregatedPluginResult,
1762 entry_points: &'a discover::CategorizedEntryPoints,
1763 files: &'a [discover::DiscoveredFile],
1764 workspaces: &'a [fallow_config::WorkspaceInfo],
1765 modules: &'a [extract::ModuleInfo],
1766 unseeded_declaration_files: &'a FxHashSet<discover::FileId>,
1767}
1768
1769fn build_graph_cache_manifest(
1772 input: &GraphCacheManifestInput<'_>,
1773) -> graph_cache::GraphCacheManifest {
1774 let GraphCacheManifestInput {
1775 config,
1776 plugin_result,
1777 entry_points,
1778 files,
1779 workspaces,
1780 modules,
1781 unseeded_declaration_files,
1782 } = *input;
1783 let mode = graph_cache::GraphCacheMode::new(
1784 graph_cache_key::resolver_options_hash(config, workspaces, files),
1785 graph_cache_key::entry_points_hash(
1786 entry_points,
1787 files,
1788 unseeded_declaration_files,
1789 &graph_build::consumer_checked_entries(config, entry_points, files, workspaces),
1790 &config.root,
1791 ),
1792 graph_cache_key::plugin_config_hash(plugin_result, &config.root),
1793 );
1794 let mut content_hashes = vec![0u64; files.len()];
1799 for module in modules {
1800 if let Some(slot) = content_hashes.get_mut(module.file_id.0 as usize) {
1801 *slot = module.content_hash;
1802 }
1803 }
1804 graph_cache::GraphCacheManifest::from_discovered_files(&config.root, files, mode, |file| {
1805 content_hashes
1806 .get(file.id.0 as usize)
1807 .copied()
1808 .unwrap_or_default()
1809 })
1810}
1811
1812fn collect_file_hashes(
1813 modules: &[extract::ModuleInfo],
1814 files: &[discover::DiscoveredFile],
1815) -> rustc_hash::FxHashMap<std::path::PathBuf, u64> {
1816 modules
1817 .iter()
1818 .filter_map(|module| {
1819 files
1820 .get(module.file_id.0 as usize)
1821 .map(|file| (file.path.clone(), module.content_hash))
1822 })
1823 .collect()
1824}
1825
1826fn trace_pipeline_profile(profile: &PipelineProfile) {
1827 let PipelineProfile {
1828 discover_ms,
1829 workspaces_ms,
1830 plugins_ms,
1831 scripts_ms,
1832 parse_ms,
1833 cache_ms,
1834 entry_points_ms,
1835 resolve_ms,
1836 graph_ms,
1837 analyze_ms,
1838 total_ms,
1839 file_count,
1840 module_count,
1841 entry_point_count,
1842 cache_hits,
1843 cache_misses,
1844 cache_rejection,
1845 ..
1846 } = *profile;
1847 let cache_summary = cache_rejection.map_or_else(
1848 || format!(" ({cache_hits} cached, {cache_misses} parsed)"),
1849 |rejection| {
1850 format!(
1851 " ({cache_hits} cached, {cache_misses} parsed, cache refused: {})",
1852 rejection.describe()
1853 )
1854 },
1855 );
1856
1857 tracing::debug!(
1858 "\n┌─ Pipeline Profile ─────────────────────────────\n\
1859 │ discover files: {:>8.1}ms ({} files)\n\
1860 │ workspaces: {:>8.1}ms\n\
1861 │ plugin detection: {:>8.1}ms\n\
1862 │ script analysis: {:>8.1}ms\n\
1863 │ parse/extract: {:>8.1}ms ({} modules{})\n\
1864 │ cache update: {:>8.1}ms\n\
1865 │ entry points: {:>8.1}ms ({} entries)\n\
1866 │ resolve imports: {:>8.1}ms\n\
1867 │ build graph: {:>8.1}ms\n\
1868 │ analyze: {:>8.1}ms\n\
1869 │ ────────────────────────────────────────────\n\
1870 │ TOTAL: {:>8.1}ms\n\
1871 └─────────────────────────────────────────────────",
1872 discover_ms,
1873 file_count,
1874 workspaces_ms,
1875 plugins_ms,
1876 scripts_ms,
1877 parse_ms,
1878 module_count,
1879 cache_summary,
1880 cache_ms,
1881 entry_points_ms,
1882 entry_point_count,
1883 resolve_ms,
1884 graph_ms,
1885 analyze_ms,
1886 total_ms,
1887 );
1888}
1889
1890fn load_workspace_packages(
1891 workspaces: &[fallow_config::WorkspaceInfo],
1892) -> Vec<LoadedWorkspacePackage> {
1893 workspaces
1894 .iter()
1895 .filter_map(|ws| {
1896 fallow_config::load_dir_package_json(&ws.root).map(|pkg| (ws.clone(), pkg))
1897 })
1898 .collect()
1899}
1900
1901fn analyze_all_scripts(
1906 config: &ResolvedConfig,
1907 workspaces: &[fallow_config::WorkspaceInfo],
1908 root_pkg: Option<&PackageJson>,
1909 workspace_pkgs: &[LoadedWorkspacePackage],
1910 plugin_result: &mut plugins::AggregatedPluginResult,
1911) {
1912 let manifests: Vec<&PackageJson> = root_pkg
1913 .into_iter()
1914 .chain(workspace_pkgs.iter().map(|(_, ws_pkg)| ws_pkg))
1915 .collect();
1916 let all_dep_names = scripts::all_dependency_names(&manifests);
1917 let all_dep_set: FxHashSet<String> = all_dep_names.iter().cloned().collect();
1918 let workspace_packages =
1919 discover::collect_workspace_packages(&config.root, root_pkg, workspace_pkgs);
1920 let all_scripts = collect_all_scripts(root_pkg, workspace_pkgs, &workspace_packages);
1921 let nm_roots = collect_node_modules_roots(config, workspaces);
1922 let ws_manifests = workspace_pkgs.iter().map(|(_, pkg)| pkg);
1923 let bin_map = scripts::project_bin_map(&nm_roots, &all_dep_names, ws_manifests, &all_dep_set);
1924 let registry = plugins::PluginRegistry::new(config.external_plugins.clone());
1925 let deps = ScriptDependencyContext {
1926 bin_map: &bin_map,
1927 all_dep_set: &all_dep_set,
1928 workspace_packages: &workspace_packages,
1929 registry: ®istry,
1930 };
1931
1932 analyze_root_scripts(config, root_pkg, &deps, plugin_result);
1933 analyze_workspace_scripts(config, workspace_pkgs, &deps, plugin_result);
1934 analyze_ci_scripts(config, &bin_map, &all_dep_set, &all_scripts, plugin_result);
1935 analyze_hook_scripts(
1936 config,
1937 workspaces,
1938 &scripts::hooks::HookContext {
1939 bin_map: &bin_map,
1940 declared_packages: &all_dep_set,
1941 scripts: &all_scripts,
1942 ignored: scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
1943 },
1944 plugin_result,
1945 );
1946 scripts::credit_npm_aliases(&mut plugin_result.script_used_packages, &manifests, config);
1947 plugin_result.dependency_binaries =
1948 scripts::DependencyBinaries::new(config.root.clone(), bin_map, all_dep_set);
1949 plugin_result.dev_dependency_names = manifests
1950 .iter()
1951 .flat_map(|pkg| pkg.dev_dependency_names())
1952 .collect();
1953
1954 plugin_result
1955 .entry_point_roles
1956 .entry("scripts".to_string())
1957 .or_insert(EntryPointRole::Support);
1958 plugin_result
1959 .entry_point_roles
1960 .entry(script_entries::SCRIPT_TEST_ENTRY_SOURCE.to_string())
1961 .or_insert(EntryPointRole::Test);
1962}
1963
1964struct ScriptDependencyContext<'a> {
1967 bin_map: &'a rustc_hash::FxHashMap<String, String>,
1968 all_dep_set: &'a FxHashSet<String>,
1969 workspace_packages: &'a std::sync::Arc<scripts::WorkspacePackages>,
1970 registry: &'a plugins::PluginRegistry,
1971}
1972
1973fn collect_all_scripts(
1975 root_pkg: Option<&PackageJson>,
1976 workspace_pkgs: &[LoadedWorkspacePackage],
1977 workspace_packages: &std::sync::Arc<scripts::WorkspacePackages>,
1978) -> scripts::ScriptCatalog {
1979 let mut catalog = scripts::ScriptCatalog::default();
1980 if let Some(pkg) = root_pkg
1981 && let Some(ref pkg_scripts) = pkg.scripts
1982 {
1983 catalog.merge_scripts(pkg_scripts);
1984 }
1985 for (_, ws_pkg) in workspace_pkgs {
1986 if let Some(ref ws_scripts) = ws_pkg.scripts {
1987 catalog.merge_workspace_scripts(ws_scripts);
1988 }
1989 }
1990 catalog.with_workspaces(std::sync::Arc::clone(workspace_packages), "")
1991}
1992
1993fn collect_node_modules_roots<'a>(
1995 config: &'a ResolvedConfig,
1996 workspaces: &'a [fallow_config::WorkspaceInfo],
1997) -> Vec<&'a std::path::Path> {
1998 let mut nm_roots: Vec<&std::path::Path> = Vec::new();
1999 if config.root.join("node_modules").is_dir() {
2000 nm_roots.push(&config.root);
2001 }
2002 for ws in workspaces {
2003 if ws.root.join("node_modules").is_dir() {
2004 nm_roots.push(&ws.root);
2005 }
2006 }
2007 nm_roots
2008}
2009
2010fn analyze_root_scripts(
2012 config: &ResolvedConfig,
2013 root_pkg: Option<&PackageJson>,
2014 deps: &ScriptDependencyContext<'_>,
2015 plugin_result: &mut plugins::AggregatedPluginResult,
2016) {
2017 let pkg_scripts = root_pkg
2018 .and_then(|pkg| pkg.scripts.clone())
2019 .unwrap_or_default();
2020 let mut scripts_to_analyze = if config.production {
2021 scripts::filter_production_scripts(&pkg_scripts)
2022 } else {
2023 pkg_scripts.clone()
2024 };
2025 scripts_to_analyze.extend(scripts::config_task_scripts(
2026 &config.root,
2027 "",
2028 config.production,
2029 ));
2030 if scripts_to_analyze.is_empty() {
2031 return;
2032 }
2033 let pkg_scripts = &pkg_scripts;
2034 let catalog =
2035 scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze)
2036 .with_workspaces(std::sync::Arc::clone(deps.workspace_packages), "");
2037 let script_analysis = scripts::analyze_scripts_with_dependency_context(
2038 &scripts_to_analyze,
2039 &config.root,
2040 deps.bin_map,
2041 deps.all_dep_set,
2042 &catalog,
2043 scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
2044 );
2045 plugin_result.script_used_packages = script_analysis.used_packages;
2046 plugin_result.merge_into(deps.registry.resolve_script_config_files(
2047 &script_analysis.binary_config_files,
2048 &config.root,
2049 &config.root,
2050 "",
2051 ));
2052
2053 for config_file in &script_analysis.config_files {
2054 if let Some(path) = scripts::normalize_script_entry_pattern("", config_file) {
2055 plugin_result
2056 .discovered_always_used
2057 .push((path, "scripts".to_string()));
2058 }
2059 }
2060 script_entries::push_script_entry_patterns(
2061 &mut plugin_result.entry_patterns,
2062 "",
2063 &script_analysis.entry_files,
2064 &script_analysis.test_entry_files,
2065 None,
2066 );
2067}
2068
2069type WsScriptOut = (
2071 Vec<String>,
2072 Vec<(String, String)>,
2073 Vec<(plugins::PathRule, String)>,
2074 plugins::AggregatedPluginResult,
2075);
2076
2077fn analyze_workspace_scripts(
2078 config: &ResolvedConfig,
2079 workspace_pkgs: &[LoadedWorkspacePackage],
2080 deps: &ScriptDependencyContext<'_>,
2081 plugin_result: &mut plugins::AggregatedPluginResult,
2082) {
2083 let ws_results: Vec<WsScriptOut> = workspace_pkgs
2084 .par_iter()
2085 .map(|(ws, ws_pkg)| analyze_one_workspace_scripts(config, ws, ws_pkg, deps))
2086 .collect();
2087 for (used_packages, discovered_always_used, entry_patterns, config_result) in ws_results {
2088 plugin_result.script_used_packages.extend(used_packages);
2089 plugin_result.merge_into(config_result);
2090 plugin_result
2091 .discovered_always_used
2092 .extend(discovered_always_used);
2093 plugin_result.entry_patterns.extend(entry_patterns);
2094 }
2095}
2096
2097fn analyze_one_workspace_scripts(
2101 config: &ResolvedConfig,
2102 ws: &fallow_config::WorkspaceInfo,
2103 ws_pkg: &PackageJson,
2104 deps: &ScriptDependencyContext<'_>,
2105) -> WsScriptOut {
2106 let mut used_packages = Vec::new();
2107 let mut discovered_always_used: Vec<(String, String)> = Vec::new();
2108 let mut entry_patterns: Vec<(plugins::PathRule, String)> = Vec::new();
2109 let ws_prefix = workspace_prefix(&config.root, &ws.root);
2110 let ws_scripts = ws_pkg.scripts.clone().unwrap_or_default();
2111 let mut scripts_to_analyze = if config.production {
2112 scripts::filter_production_scripts(&ws_scripts)
2113 } else {
2114 ws_scripts.clone()
2115 };
2116 scripts_to_analyze.extend(scripts::config_task_scripts(
2117 &ws.root,
2118 &ws_prefix,
2119 config.production,
2120 ));
2121 if scripts_to_analyze.is_empty() {
2122 return (
2123 used_packages,
2124 discovered_always_used,
2125 entry_patterns,
2126 plugins::AggregatedPluginResult::default(),
2127 );
2128 }
2129 let catalog =
2130 scripts::ScriptCatalog::from_scripts_with_bodies(&ws_scripts, &scripts_to_analyze)
2131 .with_workspaces(std::sync::Arc::clone(deps.workspace_packages), &ws_prefix);
2132 let ws_analysis = scripts::analyze_scripts_with_dependency_context(
2133 &scripts_to_analyze,
2134 &ws.root,
2135 deps.bin_map,
2136 deps.all_dep_set,
2137 &catalog,
2138 scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
2139 );
2140 used_packages.extend(ws_analysis.used_packages);
2141 let config_result = deps.registry.resolve_script_config_files(
2142 &ws_analysis.binary_config_files,
2143 &ws.root,
2144 &config.root,
2145 &ws_prefix,
2146 );
2147
2148 for config_file in &ws_analysis.config_files {
2149 if let Some(path) = scripts::normalize_script_entry_pattern(&ws_prefix, config_file) {
2150 discovered_always_used.push((path, "scripts".to_string()));
2151 }
2152 }
2153 script_entries::push_script_entry_patterns(
2154 &mut entry_patterns,
2155 &ws_prefix,
2156 &ws_analysis.entry_files,
2157 &ws_analysis.test_entry_files,
2158 None,
2159 );
2160 (
2161 used_packages,
2162 discovered_always_used,
2163 entry_patterns,
2164 config_result,
2165 )
2166}
2167
2168fn analyze_ci_scripts(
2170 config: &ResolvedConfig,
2171 bin_map: &rustc_hash::FxHashMap<String, String>,
2172 all_dep_set: &FxHashSet<String>,
2173 all_scripts: &scripts::ScriptCatalog,
2174 plugin_result: &mut plugins::AggregatedPluginResult,
2175) {
2176 let ci_analysis = scripts::ci::analyze_ci_files(
2177 &config.root,
2178 bin_map,
2179 all_dep_set,
2180 all_scripts,
2181 scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
2182 );
2183 plugin_result
2184 .script_used_packages
2185 .extend(ci_analysis.used_packages);
2186 script_entries::push_script_entry_patterns(
2187 &mut plugin_result.entry_patterns,
2188 "",
2189 &ci_analysis.entry_files,
2190 &ci_analysis.test_entry_files,
2191 Some(&ci_analysis.entry_file_sources),
2192 );
2193}
2194
2195fn analyze_hook_scripts(
2201 config: &ResolvedConfig,
2202 workspaces: &[fallow_config::WorkspaceInfo],
2203 context: &scripts::hooks::HookContext<'_>,
2204 plugin_result: &mut plugins::AggregatedPluginResult,
2205) {
2206 if config.production {
2207 return;
2208 }
2209 let roots = std::iter::once(config.root.as_path()).chain(
2210 workspaces
2211 .iter()
2212 .map(|ws| ws.root.as_path())
2213 .filter(|root| *root != config.root.as_path()),
2214 );
2215 for root in roots {
2216 plugin_result
2217 .script_used_packages
2218 .extend(scripts::hooks::analyze_hook_files(root, context));
2219 }
2220}
2221
2222fn discover_all_entry_points(
2224 input: DiscoverAllEntryPointsInput<'_>,
2225) -> (discover::CategorizedEntryPoints, EntryPointSpans) {
2226 let mut spans = EntryPointSpans::default();
2227 let mut mark = Instant::now();
2228 let mut entry_points = discover::CategorizedEntryPoints::default();
2229 let workspace_packages = discover::collect_workspace_packages(
2232 &input.config.root,
2233 input.root_pkg,
2234 input.workspace_pkgs,
2235 );
2236 let runtime_seeds = discover::workspace_runtime_script_seeds(&workspace_packages);
2237 let discovered = discover::DiscoveredPaths::new(input.files);
2238 let is_discovered = |path: &std::path::Path| discovered.contains(path);
2239 let script_workspaces = discover::ScriptWorkspaces {
2240 packages: &workspace_packages,
2241 project_root: &input.config.root,
2242 runtime_seeds: &runtime_seeds,
2243 discovered: Some(&is_discovered),
2244 };
2245 let root_discovery = discover::discover_root_entry_points(
2246 input.config,
2247 input.files,
2248 input.root_pkg,
2249 input.workspaces.is_empty(),
2250 script_workspaces,
2251 );
2252 spans.root_ms = split_ms(&mut mark);
2253
2254 let workspace_pkg_by_root: rustc_hash::FxHashMap<std::path::PathBuf, &PackageJson> = input
2255 .workspace_pkgs
2256 .iter()
2257 .map(|(ws, pkg)| (ws.root.clone(), pkg))
2258 .collect();
2259 let workspace_discovery: Vec<discover::EntryPointDiscovery> = input
2260 .workspaces
2261 .par_iter()
2262 .map(|ws| {
2263 let pkg = workspace_pkg_by_root.get(&ws.root).copied();
2264 discover::discover_workspace_package_entry_points(
2265 &ws.root,
2266 input.files,
2267 pkg,
2268 scripts::IgnoredCommandEntries::new(&input.config.ignore_command_entries),
2269 script_workspaces,
2270 )
2271 })
2272 .collect();
2273 let (other_sources, mut skipped_entries) = entry_points.extend_root(root_discovery);
2274 let mut ws_entries = Vec::new();
2275 let mut ws_support_entries = Vec::new();
2276 for workspace in workspace_discovery {
2277 ws_entries.extend(workspace.entries);
2278 ws_support_entries.extend(workspace.support_entries);
2279 for (path, count) in workspace.skipped_entries {
2280 *skipped_entries.entry(path).or_insert(0) += count;
2281 }
2282 }
2283 discover::warn_skipped_entry_summary(&skipped_entries);
2284 entry_points.extend_runtime(ws_entries);
2285 entry_points.extend_support(ws_support_entries);
2286 spans.workspaces_ms = split_ms(&mut mark);
2287
2288 let plugin_entries = discover::discover_plugin_entry_point_sets_timed(
2289 input.plugin_result,
2290 input.config,
2291 input.files,
2292 );
2293 spans.plugin_glob_build_ms = plugin_entries.build_ms;
2294 spans.plugin_glob_match_ms = plugin_entries.match_ms;
2295 entry_points.extend(plugin_entries.entries);
2296 spans.plugins_ms = split_ms(&mut mark);
2297
2298 let all_scripts =
2301 collect_all_scripts(input.root_pkg, input.workspace_pkgs, &workspace_packages);
2302 let infra_entries = discover::discover_infrastructure_entry_points(
2303 &input.config.root,
2304 discover::CommandRefContext {
2305 ignored: scripts::IgnoredCommandEntries::new(&input.config.ignore_command_entries),
2306 scripts: &all_scripts,
2307 },
2308 );
2309 entry_points.extend_runtime(infra_entries);
2310 spans.infrastructure_ms = split_ms(&mut mark);
2311
2312 if !input.config.dynamically_loaded.is_empty() {
2313 let dynamic_entries =
2314 discover::discover_dynamically_loaded_entry_points(input.config, input.files);
2315 entry_points.extend_runtime(dynamic_entries);
2316 }
2317 spans.dynamic_ms = split_ms(&mut mark);
2318 discover::record_entry_pattern_effect(input.config, input.files, &entry_points, other_sources);
2319
2320 let deduped = entry_points.dedup();
2321 spans.dedup_ms = split_ms(&mut mark);
2322 (deduped, spans)
2323}
2324
2325fn split_ms(mark: &mut Instant) -> f64 {
2330 let now = Instant::now();
2331 let elapsed = now.duration_since(*mark).as_secs_f64() * 1000.0;
2332 *mark = now;
2333 elapsed
2334}
2335
2336fn append_package_file_asset_patterns(
2337 result: &mut plugins::AggregatedPluginResult,
2338 prefix: &str,
2339 pkg: &PackageJson,
2340) {
2341 let prefix = prefix.trim_matches('/');
2342 for pattern in package_assets::scaffold_template_asset_patterns(pkg) {
2343 let pattern = if prefix.is_empty() {
2344 pattern
2345 } else {
2346 format!("{prefix}/{pattern}")
2347 };
2348 result
2349 .discovered_always_used
2350 .push((pattern, package_assets::PACKAGE_FILES_SOURCE.to_string()));
2351 }
2352}
2353
2354fn append_workspace_package_file_asset_patterns(
2355 result: &mut plugins::AggregatedPluginResult,
2356 config: &ResolvedConfig,
2357 workspace_pkgs: &[LoadedWorkspacePackage],
2358) {
2359 for (ws, ws_pkg) in workspace_pkgs {
2360 let ws_prefix = ws
2361 .root
2362 .strip_prefix(&config.root)
2363 .unwrap_or(&ws.root)
2364 .to_string_lossy()
2365 .replace('\\', "/");
2366 append_package_file_asset_patterns(result, &ws_prefix, ws_pkg);
2367 }
2368}
2369
2370fn run_plugins(
2372 config: &ResolvedConfig,
2373 files: &[discover::DiscoveredFile],
2374 workspaces: &[fallow_config::WorkspaceInfo],
2375 root_pkg: Option<&PackageJson>,
2376 workspace_pkgs: &[LoadedWorkspacePackage],
2377 config_candidates: &[std::path::PathBuf],
2378) -> Result<plugins::AggregatedPluginResult, FallowError> {
2379 let registry = plugins::PluginRegistry::new(config.external_plugins.clone());
2380 let file_paths: Vec<std::path::PathBuf> = files.iter().map(|f| f.path.clone()).collect();
2381
2382 let candidate_index = (!config.production).then(|| {
2387 plugins::registry::ConfigCandidateIndex::build(
2388 file_paths
2389 .iter()
2390 .map(std::path::PathBuf::as_path)
2391 .chain(config_candidates.iter().map(std::path::PathBuf::as_path)),
2392 )
2393 });
2394
2395 let mut result = run_root_plugins(
2396 ®istry,
2397 config,
2398 root_pkg,
2399 &file_paths,
2400 candidate_index.as_ref(),
2401 )?;
2402
2403 if workspaces.is_empty() {
2404 share_auto_imports_across_layers(&mut result, config, workspaces);
2405 gate_auto_import_entry_patterns(&mut result, config, workspaces);
2406 record_plugin_config_diagnostics(&result, &config.root);
2407 return Ok(result);
2408 }
2409
2410 append_workspace_package_file_asset_patterns(&mut result, config, workspace_pkgs);
2411
2412 let ws_results = run_workspace_plugins(
2413 ®istry,
2414 config,
2415 &plugins::registry::RootPluginContext::new(root_pkg, &result.active_plugins),
2416 workspace_pkgs,
2417 &file_paths,
2418 candidate_index.as_ref(),
2419 );
2420 merge_workspace_plugin_results(&mut result, ws_results)?;
2421
2422 share_auto_imports_across_layers(&mut result, config, workspaces);
2423 gate_auto_import_entry_patterns(&mut result, config, workspaces);
2424 record_plugin_config_diagnostics(&result, &config.root);
2425
2426 Ok(result)
2427}
2428
2429fn record_plugin_config_diagnostics(result: &plugins::AggregatedPluginResult, root: &Path) {
2441 let diagnostics = result
2442 .config_diagnostics
2443 .iter()
2444 .cloned()
2445 .map(|diagnostic| diagnostic.into_workspace_diagnostic(root))
2446 .collect();
2447 let _ = fallow_config::record_plugin_config_diagnostics(root, diagnostics);
2448}
2449
2450type WorkspacePluginResult = Result<
2451 (plugins::AggregatedPluginResult, String),
2452 Vec<plugins::registry::PluginRegexValidationError>,
2453>;
2454
2455fn run_root_plugins(
2457 registry: &plugins::PluginRegistry,
2458 config: &ResolvedConfig,
2459 root_pkg: Option<&PackageJson>,
2460 file_paths: &[std::path::PathBuf],
2461 candidate_index: Option<&plugins::registry::ConfigCandidateIndex>,
2462) -> Result<plugins::AggregatedPluginResult, FallowError> {
2463 let root_config_search_roots = collect_config_search_roots(&config.root, file_paths);
2464 let root_config_search_root_refs: Vec<&Path> = root_config_search_roots
2465 .iter()
2466 .map(std::path::PathBuf::as_path)
2467 .collect();
2468
2469 let mut result = if let Some(pkg) = root_pkg {
2470 registry
2471 .try_run_with_search_roots(
2472 pkg,
2473 &config.root,
2474 file_paths,
2475 &root_config_search_root_refs,
2476 config.production,
2477 candidate_index,
2478 )
2479 .map_err(|errors| {
2480 FallowError::config(plugins::registry::format_plugin_regex_errors(&errors))
2481 })?
2482 } else {
2483 plugins::AggregatedPluginResult::default()
2484 };
2485 if let Some(pkg) = root_pkg {
2486 append_package_file_asset_patterns(&mut result, "", pkg);
2487 }
2488 Ok(result)
2489}
2490
2491fn run_workspace_plugins(
2494 registry: &plugins::PluginRegistry,
2495 config: &ResolvedConfig,
2496 root: &plugins::registry::RootPluginContext<'_>,
2497 workspace_pkgs: &[LoadedWorkspacePackage],
2498 file_paths: &[std::path::PathBuf],
2499 candidate_index: Option<&plugins::registry::ConfigCandidateIndex>,
2500) -> Vec<WorkspacePluginResult> {
2501 let precompiled_matchers = registry.precompile_config_matchers();
2502 let workspace_relative_files = bucket_files_by_workspace(workspace_pkgs, file_paths);
2503
2504 workspace_pkgs
2505 .par_iter()
2506 .zip(workspace_relative_files.par_iter())
2507 .filter_map(|((ws, ws_pkg), relative_files)| {
2508 let ws_result =
2509 match registry.try_run_workspace_fast(&plugins::registry::WorkspacePluginRunInput {
2510 pkg: ws_pkg,
2511 root: &ws.root,
2512 project_root: &config.root,
2513 root_dependencies: &root.dependencies,
2514 precompiled_config_matchers: &precompiled_matchers,
2515 relative_files,
2516 skip_config_plugins: &root.active_plugins,
2517 production_mode: config.production,
2518 candidate_index,
2519 }) {
2520 Ok(result) => result,
2521 Err(errors) => return Some(Err(errors)),
2522 };
2523 if ws_result.active_plugins.is_empty() {
2524 return None;
2525 }
2526 Some(Ok((ws_result, workspace_prefix(&config.root, &ws.root))))
2527 })
2528 .collect::<Vec<_>>()
2529}
2530
2531fn merge_workspace_plugin_results(
2534 result: &mut plugins::AggregatedPluginResult,
2535 ws_results: Vec<WorkspacePluginResult>,
2536) -> Result<(), FallowError> {
2537 let mut regex_errors = Vec::new();
2538 for ws_result in ws_results {
2539 match ws_result {
2540 Ok((mut ws_result, ws_prefix)) => {
2541 ws_result.apply_workspace_prefix(&ws_prefix);
2542 ws_result.config_patterns.clear();
2543 ws_result.script_used_packages.clear();
2544 result.merge_into(ws_result);
2545 }
2546 Err(mut errors) => regex_errors.append(&mut errors),
2547 }
2548 }
2549 if !regex_errors.is_empty() {
2550 return Err(FallowError::config(
2551 plugins::registry::format_plugin_regex_errors(®ex_errors),
2552 ));
2553 }
2554 Ok(())
2555}
2556
2557fn workspace_prefix(root: &Path, workspace_root: &Path) -> String {
2562 workspace_root
2563 .strip_prefix(root)
2564 .unwrap_or(workspace_root)
2565 .to_string_lossy()
2566 .replace('\\', "/")
2567}
2568
2569fn share_auto_imports_across_layers(
2585 result: &mut plugins::AggregatedPluginResult,
2586 config: &ResolvedConfig,
2587 workspaces: &[fallow_config::WorkspaceInfo],
2588) {
2589 if result.auto_imports.is_empty() || !result.active_plugins.iter().any(|name| name == "nuxt") {
2590 return;
2591 }
2592 let links = layer_links(config, workspaces);
2593 if links.is_empty() {
2594 return;
2595 }
2596 let mut related: rustc_hash::FxHashMap<PathBuf, Vec<PathBuf>> =
2597 rustc_hash::FxHashMap::default();
2598 for rule in &mut result.auto_imports {
2599 let declared = rule.scope.clone();
2600 for root in &declared {
2601 let roots = related.entry(root.clone()).or_insert_with(|| {
2602 let mut roots = reachable_roots(root, &links, |(app, layer)| (app, layer));
2603 roots.extend(reachable_roots(root, &links, |(app, layer)| (layer, app)));
2604 roots
2605 });
2606 for extra in roots.iter() {
2607 if !rule.scope.contains(extra) {
2608 rule.scope.push(extra.clone());
2609 }
2610 }
2611 }
2612 }
2613}
2614
2615fn reachable_roots<'a>(
2619 start: &Path,
2620 links: &'a [(PathBuf, PathBuf)],
2621 direction: impl Fn(&'a (PathBuf, PathBuf)) -> (&'a PathBuf, &'a PathBuf),
2622) -> Vec<PathBuf> {
2623 let mut found: Vec<PathBuf> = Vec::new();
2624 let mut pending: Vec<&Path> = vec![start];
2625 while let Some(current) = pending.pop() {
2626 for link in links {
2627 let (from, to) = direction(link);
2628 if from.as_path() == current && to.as_path() != start && !found.contains(to) {
2629 found.push(to.clone());
2630 pending.push(to.as_path());
2631 }
2632 }
2633 }
2634 found
2635}
2636
2637fn layer_links(
2641 config: &ResolvedConfig,
2642 workspaces: &[fallow_config::WorkspaceInfo],
2643) -> Vec<(PathBuf, PathBuf)> {
2644 let roots_by_name: rustc_hash::FxHashMap<&str, &Path> = workspaces
2645 .iter()
2646 .map(|ws| (ws.name.as_str(), ws.root.as_path()))
2647 .collect();
2648 let app_roots =
2649 std::iter::once(config.root.as_path()).chain(workspaces.iter().map(|ws| ws.root.as_path()));
2650 let mut links: Vec<(PathBuf, PathBuf)> = Vec::new();
2651 for app in app_roots {
2652 let package_layers = plugins::nuxt::package_layer_names(app)
2653 .into_iter()
2654 .filter_map(|name| {
2655 roots_by_name
2656 .get(name.as_str())
2657 .map(|root| root.to_path_buf())
2658 });
2659 for layer in plugins::nuxt::outside_layer_roots(app)
2660 .into_iter()
2661 .chain(package_layers)
2662 {
2663 let link = (app.to_path_buf(), layer);
2664 if link.0 != link.1 && !links.contains(&link) {
2665 links.push(link);
2666 }
2667 }
2668 }
2669 links
2670}
2671
2672fn gate_auto_import_entry_patterns(
2691 result: &mut plugins::AggregatedPluginResult,
2692 config: &ResolvedConfig,
2693 workspaces: &[fallow_config::WorkspaceInfo],
2694) {
2695 if !config.auto_imports {
2696 return;
2697 }
2698 if !result.active_plugins.iter().any(|name| name == "nuxt") {
2699 return;
2700 }
2701 let root_settings = plugins::nuxt::auto_import_settings(&config.root);
2702 let workspace_settings: Vec<_> = workspaces
2703 .iter()
2704 .map(|ws| {
2705 (
2706 workspace_prefix(&config.root, &ws.root),
2707 plugins::nuxt::auto_import_settings(&ws.root),
2708 )
2709 })
2710 .collect();
2711 let mut retained: Vec<plugins::PluginConfigDiagnostic> = Vec::new();
2712 result.entry_patterns.retain(|(rule, plugin)| {
2713 if plugin != "nuxt" {
2714 return true;
2715 }
2716 let setting =
2717 settings_for_entry_pattern(&root_settings, &workspace_settings, &rule.pattern);
2718 if plugins::nuxt::is_component_entry_pattern(&rule.pattern) {
2719 if !setting.components.is_custom() {
2720 return false;
2721 }
2722 record_retained_auto_import_surface(
2723 &mut retained,
2724 &setting.components_origin,
2725 "components",
2726 );
2727 return true;
2728 }
2729 if plugins::nuxt::is_script_auto_import_entry_pattern(&rule.pattern) {
2730 if !setting.scripts.is_custom() {
2731 return false;
2732 }
2733 record_retained_auto_import_surface(&mut retained, &setting.scripts_origin, "imports");
2734 return true;
2735 }
2736 true
2737 });
2738 result.config_diagnostics.extend(retained);
2739}
2740
2741const AUTO_IMPORT_PROPERTY_UNREADABLE: &str = "config-property-unreadable";
2746const AUTO_IMPORT_KEY_NOT_MODELED: &str = "key-effect-not-modeled";
2747
2748fn record_retained_auto_import_surface(
2751 retained: &mut Vec<plugins::PluginConfigDiagnostic>,
2752 origin: &plugins::nuxt::SurfaceOrigin,
2753 key: &str,
2754) {
2755 let Some(config_path) = origin.config_path.as_deref() else {
2756 return;
2757 };
2758 let reason = if origin.unreadable_property {
2759 AUTO_IMPORT_PROPERTY_UNREADABLE
2760 } else {
2761 AUTO_IMPORT_KEY_NOT_MODELED
2762 };
2763 let diagnostic = plugins::PluginConfigDiagnostic::not_modeled(config_path, "nuxt", key, reason);
2764 if !retained.contains(&diagnostic) {
2765 retained.push(diagnostic);
2766 }
2767}
2768
2769fn settings_for_entry_pattern<'a>(
2774 root: &'a plugins::nuxt::AutoImportSettings,
2775 workspaces: &'a [(String, plugins::nuxt::AutoImportSettings)],
2776 pattern: &str,
2777) -> &'a plugins::nuxt::AutoImportSettings {
2778 workspaces
2779 .iter()
2780 .filter(|(prefix, _)| {
2781 !prefix.is_empty()
2782 && pattern
2783 .strip_prefix(prefix.as_str())
2784 .is_some_and(|rest| rest.starts_with('/'))
2785 })
2786 .max_by_key(|(prefix, _)| prefix.len())
2787 .map_or(root, |(_, setting)| setting)
2788}
2789
2790fn bucket_files_by_workspace(
2791 workspace_pkgs: &[LoadedWorkspacePackage],
2792 file_paths: &[std::path::PathBuf],
2793) -> Vec<Vec<(std::path::PathBuf, String)>> {
2794 let workspace_roots: Vec<_> = workspace_pkgs
2795 .iter()
2796 .map(|(workspace, _)| workspace.root.as_path())
2797 .collect();
2798 bucket_files_by_workspace_roots(&workspace_roots, file_paths)
2799}
2800
2801fn bucket_files_by_workspace_roots(
2802 workspace_roots: &[&Path],
2803 file_paths: &[std::path::PathBuf],
2804) -> Vec<Vec<(std::path::PathBuf, String)>> {
2805 use rayon::prelude::*;
2806
2807 let mut workspace_by_root: rustc_hash::FxHashMap<&Path, usize> =
2811 rustc_hash::FxHashMap::default();
2812 for (idx, root) in workspace_roots.iter().enumerate() {
2813 workspace_by_root.entry(root).or_insert(idx);
2814 }
2815
2816 let assignments: Vec<Option<(usize, std::path::PathBuf, String)>> = file_paths
2817 .par_iter()
2818 .map(|file_path| {
2819 let idx = file_path
2820 .ancestors()
2821 .filter_map(|ancestor| workspace_by_root.get(ancestor).copied())
2822 .min()?;
2823 let relative = file_path.strip_prefix(workspace_roots[idx]).ok()?;
2824 Some((
2825 idx,
2826 file_path.clone(),
2827 relative.to_string_lossy().into_owned(),
2828 ))
2829 })
2830 .collect();
2831
2832 let mut buckets = vec![Vec::new(); workspace_roots.len()];
2833 for (idx, file_path, relative) in assignments.into_iter().flatten() {
2834 buckets[idx].push((file_path, relative));
2835 }
2836
2837 buckets
2838}
2839
2840#[doc(hidden)]
2842pub fn benchmark_bucket_files_by_workspace(
2843 workspace_roots: &[std::path::PathBuf],
2844 file_paths: &[std::path::PathBuf],
2845) -> Vec<Vec<(std::path::PathBuf, String)>> {
2846 let workspace_roots: Vec<_> = workspace_roots
2847 .iter()
2848 .map(std::path::PathBuf::as_path)
2849 .collect();
2850 bucket_files_by_workspace_roots(&workspace_roots, file_paths)
2851}
2852
2853fn collect_config_search_roots(
2854 root: &Path,
2855 file_paths: &[std::path::PathBuf],
2856) -> Vec<std::path::PathBuf> {
2857 let mut roots: rustc_hash::FxHashSet<std::path::PathBuf> = rustc_hash::FxHashSet::default();
2858 roots.insert(root.to_path_buf());
2859
2860 for file_path in file_paths {
2861 let mut current = file_path.parent();
2862 while let Some(dir) = current {
2863 if !dir.starts_with(root) {
2864 break;
2865 }
2866 roots.insert(dir.to_path_buf());
2867 if dir == root {
2868 break;
2869 }
2870 current = dir.parent();
2871 }
2872 }
2873
2874 let mut roots_vec: Vec<_> = roots.into_iter().collect();
2875 roots_vec.sort();
2876 roots_vec
2877}
2878
2879#[cfg(test)]
2880mod tests {
2881 use super::{
2882 AnalysisSession, bucket_files_by_workspace, bucket_files_by_workspace_roots,
2883 collect_config_search_roots, credit_workspace_package_usage,
2884 format_undeclared_workspace_warning, gate_auto_import_entry_patterns,
2885 parse_analysis_modules, settings_for_entry_pattern, warn_undeclared_workspaces,
2886 workspace_prefix,
2887 };
2888 use crate::graph_cache_key::{plugin_config_hash, resolver_options_hash};
2889 use crate::test_config::default_config;
2890 use std::path::{Path, PathBuf};
2891 use std::time::Instant;
2892
2893 use fallow_config::{
2894 AutoImportKind, AutoImportRule, WorkspaceDiagnostic, WorkspaceDiagnosticKind,
2895 };
2896 use fallow_types::discover::{DiscoveredFile, FileId};
2897 use fallow_types::extract::{ImportInfo, ImportedName};
2898
2899 fn plugin_result() -> crate::plugins::AggregatedPluginResult {
2900 let mut result = crate::plugins::AggregatedPluginResult::default();
2901 result.active_plugins.push("nuxt".to_string());
2902 result
2903 .path_aliases
2904 .push(("@/".to_string(), "src/".to_string()));
2905 result
2906 }
2907
2908 fn auto_import_settings(
2909 components: crate::plugins::nuxt::AutoImportSetting,
2910 ) -> crate::plugins::nuxt::AutoImportSettings {
2911 crate::plugins::nuxt::AutoImportSettings {
2912 components,
2913 scripts: crate::plugins::nuxt::AutoImportSetting::Default,
2914 components_origin: crate::plugins::nuxt::SurfaceOrigin {
2915 config_path: Some(std::path::PathBuf::from("nuxt.config.ts")),
2916 unreadable_property: false,
2917 },
2918 scripts_origin: crate::plugins::nuxt::SurfaceOrigin::default(),
2919 }
2920 }
2921
2922 #[test]
2923 fn entry_pattern_settings_prefer_the_longest_workspace_prefix() {
2924 let root = auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Default);
2925 let workspaces = vec![
2926 (
2927 "packages/web".to_string(),
2928 auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Custom),
2929 ),
2930 (
2931 "packages/web-admin".to_string(),
2932 auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Disabled),
2933 ),
2934 ];
2935
2936 let admin = settings_for_entry_pattern(
2937 &root,
2938 &workspaces,
2939 "packages/web-admin/components/**/*.{vue,ts,tsx,js,jsx}",
2940 );
2941 assert_eq!(
2942 admin.components,
2943 crate::plugins::nuxt::AutoImportSetting::Disabled,
2944 "a sibling whose name starts with another workspace name is its own"
2945 );
2946
2947 let web = settings_for_entry_pattern(
2948 &root,
2949 &workspaces,
2950 "packages/web/components/**/*.{vue,ts,tsx,js,jsx}",
2951 );
2952 assert_eq!(
2953 web.components,
2954 crate::plugins::nuxt::AutoImportSetting::Custom
2955 );
2956 }
2957
2958 #[test]
2959 fn entry_pattern_without_a_workspace_prefix_belongs_to_the_project_root() {
2960 let root = auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Custom);
2961 let workspaces = vec![(
2962 "packages/web".to_string(),
2963 auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Default),
2964 )];
2965
2966 let setting = settings_for_entry_pattern(
2967 &root,
2968 &workspaces,
2969 "app/components/**/*.{vue,ts,tsx,js,jsx}",
2970 );
2971 assert_eq!(
2972 setting.components,
2973 crate::plugins::nuxt::AutoImportSetting::Custom
2974 );
2975 }
2976
2977 fn nuxt_gate_fixture(
2980 config_source: &str,
2981 ) -> (tempfile::TempDir, crate::plugins::AggregatedPluginResult) {
2982 let dir = tempfile::tempdir().expect("temp project");
2983 std::fs::write(dir.path().join("nuxt.config.ts"), config_source).expect("nuxt config");
2984 let mut result = crate::plugins::AggregatedPluginResult::default();
2985 result.active_plugins.push("nuxt".to_string());
2986 for pattern in [
2987 "app/components/**/*.{vue,ts,tsx,js,jsx}",
2988 "app/composables/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}",
2989 ] {
2990 result.entry_patterns.push((
2991 crate::plugins::PathRule::new(pattern.to_string()),
2992 "nuxt".to_string(),
2993 ));
2994 }
2995 (dir, result)
2996 }
2997
2998 fn gate(root: &Path, result: &mut crate::plugins::AggregatedPluginResult) {
2999 let config = fallow_config::FallowConfig {
3000 auto_imports: true,
3001 ..fallow_config::FallowConfig::default()
3002 };
3003 let resolved = config.resolve(
3004 root.to_path_buf(),
3005 fallow_config::OutputFormat::Json,
3006 1,
3007 false,
3008 true,
3009 None,
3010 );
3011 assert!(resolved.auto_imports, "the gate only runs when opted in");
3012 gate_auto_import_entry_patterns(result, &resolved, &[]);
3013 }
3014
3015 #[test]
3019 fn a_retained_auto_import_surface_records_one_advisory_per_surface() {
3020 let (project, mut result) =
3021 nuxt_gate_fixture("export default { components: { dirs: ['~/ui'] } };\n");
3022 gate(project.path(), &mut result);
3023
3024 let recorded: Vec<(&str, &str, &str)> = result
3025 .config_diagnostics
3026 .iter()
3027 .map(|diagnostic| {
3028 (
3029 diagnostic.plugin.as_str(),
3030 diagnostic.key.as_str(),
3031 diagnostic.reason.as_str(),
3032 )
3033 })
3034 .collect();
3035 assert_eq!(
3036 recorded,
3037 vec![("nuxt", "components", "key-effect-not-modeled")],
3038 "only the surface that kept its patterns is reported: {:?}",
3039 result.config_diagnostics
3040 );
3041 assert_eq!(
3042 result.config_diagnostics[0].config_path,
3043 project.path().join("nuxt.config.ts")
3044 );
3045 assert_eq!(
3046 result.entry_patterns.len(),
3047 1,
3048 "the modeled surface still loses its patterns: {:?}",
3049 result.entry_patterns
3050 );
3051 }
3052
3053 #[test]
3057 fn an_unreadable_top_level_property_reports_both_surfaces_with_its_own_reason() {
3058 let (project, mut result) =
3059 nuxt_gate_fixture("export default { ...baseConfig, modules: [] };\n");
3060 gate(project.path(), &mut result);
3061
3062 let recorded: Vec<(&str, &str)> = result
3063 .config_diagnostics
3064 .iter()
3065 .map(|diagnostic| (diagnostic.key.as_str(), diagnostic.reason.as_str()))
3066 .collect();
3067 assert_eq!(
3068 recorded,
3069 vec![
3070 ("components", "config-property-unreadable"),
3071 ("imports", "config-property-unreadable"),
3072 ],
3073 "{:?}",
3074 result.config_diagnostics
3075 );
3076 assert_eq!(
3077 result.entry_patterns.len(),
3078 2,
3079 "a spread keeps every gated pattern"
3080 );
3081 }
3082
3083 #[test]
3086 fn a_modeled_nuxt_config_records_no_advisory() {
3087 let (project, mut result) = nuxt_gate_fixture("export default { modules: [] };\n");
3088 gate(project.path(), &mut result);
3089 assert!(
3090 result.config_diagnostics.is_empty(),
3091 "{:?}",
3092 result.config_diagnostics
3093 );
3094 assert!(
3095 result.entry_patterns.is_empty(),
3096 "both modeled surfaces lose their patterns: {:?}",
3097 result.entry_patterns
3098 );
3099 }
3100
3101 #[test]
3102 fn a_workspace_outside_the_project_keeps_its_own_prefix() {
3103 let project_root = Path::new("/repo");
3104 let outside = Path::new("/elsewhere/app");
3105 let prefix = workspace_prefix(project_root, outside);
3106 assert_eq!(prefix, "/elsewhere/app");
3107
3108 let root = auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Default);
3109 let workspaces = vec![(
3110 prefix,
3111 auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Custom),
3112 )];
3113 let setting = settings_for_entry_pattern(
3114 &root,
3115 &workspaces,
3116 "/elsewhere/app/components/**/*.{vue,ts,tsx,js,jsx}",
3117 );
3118 assert_eq!(
3119 setting.components,
3120 crate::plugins::nuxt::AutoImportSetting::Custom,
3121 "an out-of-tree workspace is classified on its own config"
3122 );
3123 }
3124
3125 #[test]
3126 fn commonjs_internal_import_credits_workspace_package_usage() {
3127 let workspace = fallow_config::WorkspaceInfo {
3128 root: PathBuf::from("/repo/packages/shared"),
3129 name: "@repo/shared".to_string(),
3130 is_internal_dependency: true,
3131 };
3132 let resolved = vec![crate::resolve::ResolvedModule {
3133 file_id: FileId(0),
3134 resolved_imports: vec![crate::resolve::ResolvedImport {
3135 info: ImportInfo {
3136 source: "@repo/shared".to_string(),
3137 imported_name: ImportedName::Namespace,
3138 local_name: "shared".to_string(),
3139 is_type_only: false,
3140 is_type_only_star: false,
3141 from_style: false,
3142 span: oxc_span::Span::new(0, 20),
3143 source_span: oxc_span::Span::new(8, 20),
3144 },
3145 target: crate::resolve::ResolveResult::CommonJsInternalModule(FileId(1)),
3146 }],
3147 ..crate::resolve::ResolvedModule::default()
3148 }];
3149 let mut graph = crate::graph::ModuleGraph::build(&[], &[], &[]);
3150
3151 credit_workspace_package_usage(&mut graph, &resolved, &[workspace]);
3152
3153 assert_eq!(
3154 graph.package_usage.get("@repo/shared"),
3155 Some(&vec![FileId(0)])
3156 );
3157 }
3158
3159 #[test]
3162 fn graph_cache_resolver_hash_is_independent_of_the_project_root() {
3163 let dir_a = tempfile::tempdir().expect("create temp dir a");
3164 let dir_b = tempfile::tempdir().expect("create temp dir b");
3165 let config_a = session_config(dir_a.path());
3166 let config_b = session_config(dir_b.path());
3167
3168 assert_eq!(
3169 resolver_options_hash(&config_a, &[], &[]),
3170 resolver_options_hash(&config_b, &[], &[]),
3171 "root identity is handled separately from resolver options"
3172 );
3173 }
3174
3175 #[test]
3178 fn graph_cache_manifest_still_rejects_a_different_file_set() {
3179 let dir_a = tempfile::tempdir().expect("create temp dir a");
3180 let mode = crate::graph_cache::GraphCacheMode::new(1, 2, 3);
3181 let files_a = [crate::discover::DiscoveredFile {
3182 id: crate::discover::FileId(0),
3183 path: dir_a.path().join("src/a.ts"),
3184 size_bytes: 1,
3185 }];
3186 let files_b = [crate::discover::DiscoveredFile {
3187 id: crate::discover::FileId(0),
3188 path: dir_a.path().join("src/b.ts"),
3189 size_bytes: 1,
3190 }];
3191
3192 let manifest_a = crate::graph_cache::GraphCacheManifest::from_discovered_files(
3193 dir_a.path(),
3194 &files_a,
3195 mode,
3196 |_| 7,
3197 );
3198 let manifest_b = crate::graph_cache::GraphCacheManifest::from_discovered_files(
3199 dir_a.path(),
3200 &files_b,
3201 mode,
3202 |_| 7,
3203 );
3204
3205 assert_eq!(
3206 manifest_a.classify_resolution_mismatch(&manifest_b),
3207 Some(fallow_types::cache_rejection::CacheRejection::FileSetChanged)
3208 );
3209 }
3210
3211 #[test]
3212 fn graph_cache_resolver_hash_includes_resolve_conditions() {
3213 let dir = tempfile::tempdir().expect("create temp dir");
3214 let config_a = session_config(dir.path());
3215 let mut config_b = session_config(dir.path());
3216 config_b.resolve.conditions.push("react-server".to_string());
3217
3218 assert_ne!(
3219 resolver_options_hash(&config_a, &[], &[]),
3220 resolver_options_hash(&config_b, &[], &[]),
3221 "resolve condition changes must invalidate the graph cache"
3222 );
3223 }
3224
3225 #[test]
3226 fn graph_cache_plugin_hash_includes_auto_imports() {
3227 let mut without_auto_import = plugin_result();
3228 let mut with_auto_import = plugin_result();
3229 with_auto_import.auto_imports.push(AutoImportRule::new(
3230 "useCounter".to_string(),
3231 PathBuf::from("/project/composables/useCounter.ts"),
3232 AutoImportKind::Named,
3233 ));
3234
3235 assert_ne!(
3236 plugin_config_hash(&without_auto_import, std::path::Path::new("")),
3237 plugin_config_hash(&with_auto_import, std::path::Path::new("")),
3238 "auto-import edge changes must invalidate the graph cache"
3239 );
3240
3241 without_auto_import.auto_imports.push(AutoImportRule::new(
3242 "useCounter".to_string(),
3243 PathBuf::from("/project/composables/useCounter.ts"),
3244 AutoImportKind::Default,
3245 ));
3246 assert_ne!(
3247 plugin_config_hash(&without_auto_import, std::path::Path::new("")),
3248 plugin_config_hash(&with_auto_import, std::path::Path::new("")),
3249 "auto-import kind changes must invalidate the graph cache"
3250 );
3251
3252 let mut scoped = with_auto_import.auto_imports.clone();
3253 scoped[0].scope = vec![PathBuf::from("/project/packages/a")];
3254 let mut with_scoped_auto_import = plugin_result();
3255 with_scoped_auto_import.auto_imports = scoped;
3256 assert_ne!(
3257 plugin_config_hash(&with_scoped_auto_import, std::path::Path::new("")),
3258 plugin_config_hash(&with_auto_import, std::path::Path::new("")),
3259 "auto-import scope changes must invalidate the graph cache"
3260 );
3261 }
3262
3263 #[test]
3264 fn graph_cache_plugin_hash_includes_framework_static_dir_mappings() {
3265 let base = plugin_result();
3266 let mut with_mount = plugin_result();
3267 with_mount
3268 .framework_static_dir_mappings
3269 .push((PathBuf::from("/project/public"), "/".to_string()));
3270 let mut tool_mount = plugin_result();
3271 tool_mount
3272 .static_dir_mappings
3273 .push((PathBuf::from("/project/public"), "/".to_string()));
3274 let root = std::path::Path::new("/project");
3275 assert_ne!(
3276 plugin_config_hash(&base, root),
3277 plugin_config_hash(&with_mount, root),
3278 "framework static mounts feed the resolver and must key the graph cache"
3279 );
3280 assert_ne!(
3281 plugin_config_hash(&tool_mount, root),
3282 plugin_config_hash(&with_mount, root),
3283 "a framework mount and a tool mount resolve differently"
3284 );
3285 }
3286
3287 #[test]
3288 fn graph_cache_plugin_hash_includes_jsx_import_sources() {
3289 let rule = fallow_config::JsxImportSourceRule {
3290 source: "./src/jsx".to_string(),
3291 config_dir: PathBuf::from("/project"),
3292 include: vec!["src/**/*.test.tsx".to_string()],
3293 exclude: vec![],
3294 };
3295 let base = plugin_result();
3296 let mut with_rule = plugin_result();
3297 with_rule.jsx_import_sources.push(rule.clone());
3298 assert_ne!(
3299 plugin_config_hash(&base, std::path::Path::new("")),
3300 plugin_config_hash(&with_rule, std::path::Path::new("")),
3301 "JSX import source changes must invalidate the graph cache"
3302 );
3303
3304 let mut other_source = plugin_result();
3305 other_source
3306 .jsx_import_sources
3307 .push(fallow_config::JsxImportSourceRule {
3308 source: "./src/jsx/dom".to_string(),
3309 ..rule.clone()
3310 });
3311 assert_ne!(
3312 plugin_config_hash(&with_rule, std::path::Path::new("")),
3313 plugin_config_hash(&other_source, std::path::Path::new("")),
3314 "a changed JSX import source must invalidate the graph cache"
3315 );
3316
3317 let mut with_exclude = plugin_result();
3318 with_exclude
3319 .jsx_import_sources
3320 .push(fallow_config::JsxImportSourceRule {
3321 exclude: vec!["src/skip/**".to_string()],
3322 ..rule
3323 });
3324 assert_ne!(
3325 plugin_config_hash(&with_rule, std::path::Path::new("")),
3326 plugin_config_hash(&with_exclude, std::path::Path::new("")),
3327 "a changed JSX exclude must invalidate the graph cache"
3328 );
3329 }
3330
3331 #[test]
3332 fn graph_cache_plugin_hash_includes_style_and_static_mappings() {
3333 let base = plugin_result();
3334 let mut with_scss = base.clone();
3335 with_scss
3336 .scss_include_paths
3337 .push(PathBuf::from("/project/styles"));
3338 assert_ne!(
3339 plugin_config_hash(&base, std::path::Path::new("")),
3340 plugin_config_hash(&with_scss, std::path::Path::new("")),
3341 "SCSS include path changes must invalidate the graph cache"
3342 );
3343
3344 let mut with_static_dir = base.clone();
3345 with_static_dir
3346 .static_dir_mappings
3347 .push((PathBuf::from("/project/public"), "/".to_string()));
3348 assert_ne!(
3349 plugin_config_hash(&base, std::path::Path::new("")),
3350 plugin_config_hash(&with_static_dir, std::path::Path::new("")),
3351 "static directory mapping changes must invalidate the graph cache"
3352 );
3353 }
3354
3355 fn diag(root: &Path, relative: &str) -> WorkspaceDiagnostic {
3356 WorkspaceDiagnostic::new(
3357 root,
3358 root.join(relative),
3359 WorkspaceDiagnosticKind::UndeclaredWorkspace,
3360 )
3361 }
3362
3363 fn session_config(root: &Path) -> fallow_config::ResolvedConfig {
3364 let mut config = default_config(root);
3365 config.no_cache = true;
3366 config.quiet = true;
3367 config
3368 }
3369
3370 fn write_session_fixture(root: &Path) {
3371 let src = root.join("src");
3372 std::fs::create_dir_all(&src).expect("create src");
3373 std::fs::write(
3374 root.join("package.json"),
3375 r#"{"name":"session-fixture","type":"module"}"#,
3376 )
3377 .expect("write package json");
3378 std::fs::write(
3379 src.join("index.ts"),
3380 "import { used } from './used';\nconsole.log(used);\n",
3381 )
3382 .expect("write index");
3383 std::fs::write(src.join("used.ts"), "export const used = 1;\n").expect("write used");
3384 }
3385
3386 #[test]
3387 fn analysis_session_discovers_project_files() {
3388 let dir = tempfile::tempdir().expect("create temp dir");
3389 write_session_fixture(dir.path());
3390 let config = session_config(dir.path());
3391
3392 let session = AnalysisSession::new(&config).expect("session setup should succeed");
3393
3394 assert!(
3395 session
3396 .files()
3397 .iter()
3398 .any(|file| file.path.ends_with("src/index.ts")),
3399 "session should own discovered project files"
3400 );
3401 assert_eq!(session.workspaces().len(), 0);
3402 }
3403
3404 #[test]
3405 fn direct_core_parse_surfaces_source_read_failure_diagnostic() {
3406 let project = tempfile::tempdir().expect("create project");
3407 let root = project.path();
3408 let paths = ["a.ts", "b.ts", "c.ts"].map(|name| root.join(name));
3409 for (index, path) in paths.iter().enumerate() {
3410 std::fs::write(path, format!("export const value{index} = {index};\n"))
3411 .expect("write source");
3412 }
3413 let files: Vec<DiscoveredFile> = paths
3414 .iter()
3415 .enumerate()
3416 .map(|(index, path)| DiscoveredFile {
3417 id: FileId(u32::try_from(index).expect("test index fits u32")),
3418 path: path.clone(),
3419 size_bytes: std::fs::metadata(path).expect("source metadata").len(),
3420 })
3421 .collect();
3422 std::fs::remove_file(&paths[1]).expect("remove source after discovery");
3423 let config = session_config(root);
3424
3425 let parsed = parse_analysis_modules(&config, &files, false, Instant::now());
3426
3427 assert_eq!(
3428 parsed
3429 .modules
3430 .iter()
3431 .map(|module| module.file_id)
3432 .collect::<Vec<_>>(),
3433 vec![FileId(0), FileId(2)]
3434 );
3435 let diagnostics = fallow_config::workspace_diagnostics_for(root);
3436 let diagnostic = diagnostics
3437 .iter()
3438 .find(|diagnostic| diagnostic.kind.id() == "source-read-failure")
3439 .expect("source read failure diagnostic");
3440 assert_eq!(diagnostic.path, paths[1]);
3441 assert!(matches!(
3442 diagnostic.kind,
3443 WorkspaceDiagnosticKind::SourceReadFailure { .. }
3444 ));
3445 }
3446
3447 #[test]
3448 fn analysis_session_parses_owned_modules() {
3449 let dir = tempfile::tempdir().expect("create temp dir");
3450 write_session_fixture(dir.path());
3451 let config = session_config(dir.path());
3452
3453 let session = AnalysisSession::new(&config).expect("session setup should succeed");
3454 let parsed = session.parse_modules(false);
3455
3456 assert!(
3457 parsed
3458 .modules
3459 .iter()
3460 .any(|module| session.files()[module.file_id.0 as usize]
3461 .path
3462 .ends_with("src/index.ts")),
3463 "session parsing should return modules keyed to session files"
3464 );
3465 }
3466
3467 #[test]
3468 fn undeclared_workspace_warning_is_singular_for_one_path() {
3469 let root = Path::new("/repo");
3470 let warning = format_undeclared_workspace_warning(root, &[diag(root, "packages/api")])
3471 .expect("warning should be rendered");
3472
3473 assert_eq!(
3474 warning,
3475 "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."
3476 );
3477 }
3478
3479 #[test]
3480 fn undeclared_workspace_warning_summarizes_many_paths() {
3481 let root = PathBuf::from("/repo");
3482 let diagnostics = [
3483 "examples/a",
3484 "examples/b",
3485 "examples/c",
3486 "examples/d",
3487 "examples/e",
3488 "examples/f",
3489 ]
3490 .into_iter()
3491 .map(|path| diag(&root, path))
3492 .collect::<Vec<_>>();
3493
3494 let warning = format_undeclared_workspace_warning(&root, &diagnostics)
3495 .expect("warning should be rendered");
3496
3497 assert_eq!(
3498 warning,
3499 "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."
3500 );
3501 }
3502
3503 #[test]
3504 fn collect_config_search_roots_includes_file_ancestors_once() {
3505 let root = PathBuf::from("/repo");
3506 let search_roots = collect_config_search_roots(
3507 &root,
3508 &[
3509 root.join("apps/query/src/main.ts"),
3510 root.join("packages/shared/lib/index.ts"),
3511 ],
3512 );
3513
3514 assert_eq!(
3515 search_roots,
3516 vec![
3517 root.clone(),
3518 root.join("apps"),
3519 root.join("apps/query"),
3520 root.join("apps/query/src"),
3521 root.join("packages"),
3522 root.join("packages/shared"),
3523 root.join("packages/shared/lib"),
3524 ]
3525 );
3526 }
3527
3528 #[test]
3529 fn bucket_files_by_workspace_uses_workspace_relative_paths() {
3530 let root = PathBuf::from("/repo");
3531 let ui = fallow_config::WorkspaceInfo {
3532 root: root.join("apps/ui"),
3533 name: "ui".to_string(),
3534 is_internal_dependency: false,
3535 };
3536 let api = fallow_config::WorkspaceInfo {
3537 root: root.join("apps/api"),
3538 name: "api".to_string(),
3539 is_internal_dependency: false,
3540 };
3541 let workspace_pkgs = vec![
3542 (
3543 ui,
3544 fallow_config::PackageJson {
3545 name: Some("ui".to_string()),
3546 ..Default::default()
3547 },
3548 ),
3549 (
3550 api,
3551 fallow_config::PackageJson {
3552 name: Some("api".to_string()),
3553 ..Default::default()
3554 },
3555 ),
3556 ];
3557 let files = vec![
3558 root.join("apps/ui/vite.config.ts"),
3559 root.join("apps/ui/src/main.ts"),
3560 root.join("apps/api/src/server.ts"),
3561 root.join("tools/build.ts"),
3562 ];
3563
3564 let buckets = bucket_files_by_workspace(&workspace_pkgs, &files);
3565
3566 assert_eq!(
3567 buckets[0],
3568 vec![
3569 (
3570 root.join("apps/ui/vite.config.ts"),
3571 "vite.config.ts".to_string()
3572 ),
3573 (root.join("apps/ui/src/main.ts"), "src/main.ts".to_string()),
3574 ]
3575 );
3576 assert_eq!(
3577 buckets[1],
3578 vec![(
3579 root.join("apps/api/src/server.ts"),
3580 "src/server.ts".to_string()
3581 )]
3582 );
3583 }
3584
3585 #[test]
3586 fn workspace_bucketing_preserves_first_declared_match_and_file_order() {
3587 let root = PathBuf::from("/repo");
3588 let parent = root.join("apps");
3589 let child = parent.join("web");
3590 let nested_first = child.join("src/first.ts");
3591 let nested_second = child.join("src/second.ts");
3592 let unmatched = root.join("tools/build.ts");
3593 let files = vec![nested_first.clone(), unmatched, nested_second.clone()];
3594
3595 let normalize = |bucket: &[(PathBuf, String)]| -> Vec<(PathBuf, String)> {
3600 bucket
3601 .iter()
3602 .map(|(path, rel)| (path.clone(), rel.replace('\\', "/")))
3603 .collect()
3604 };
3605
3606 let parent_first = bucket_files_by_workspace_roots(&[&parent, &child, &child], &files);
3607 assert_eq!(
3608 normalize(&parent_first[0]),
3609 vec![
3610 (nested_first.clone(), "web/src/first.ts".to_string()),
3611 (nested_second.clone(), "web/src/second.ts".to_string()),
3612 ]
3613 );
3614 assert!(parent_first[1].is_empty());
3615 assert!(parent_first[2].is_empty());
3616
3617 let child_first = bucket_files_by_workspace_roots(&[&child, &parent], &files);
3618 assert_eq!(
3619 normalize(&child_first[0]),
3620 vec![
3621 (nested_first, "src/first.ts".to_string()),
3622 (nested_second, "src/second.ts".to_string()),
3623 ]
3624 );
3625 assert!(child_first[1].is_empty());
3626 }
3627
3628 #[test]
3629 fn warn_undeclared_workspaces_suppresses_paths_already_flagged_as_malformed() {
3630 let dir = tempfile::tempdir().expect("create temp dir");
3631 let pkg_good = dir.path().join("packages").join("good");
3632 let pkg_bad = dir.path().join("packages").join("bad");
3633 std::fs::create_dir_all(&pkg_good).unwrap();
3634 std::fs::create_dir_all(&pkg_bad).unwrap();
3635 std::fs::write(
3636 dir.path().join("package.json"),
3637 r#"{"workspaces": ["packages/*"]}"#,
3638 )
3639 .unwrap();
3640 std::fs::write(pkg_good.join("package.json"), r#"{"name": "good"}"#).unwrap();
3641 std::fs::write(pkg_bad.join("package.json"), r"{,").unwrap();
3642
3643 let (workspaces, diagnostics) = fallow_config::discover_workspaces_with_diagnostics(
3644 dir.path(),
3645 &fallow_config::IgnorePatternSet::empty(),
3646 )
3647 .expect("root package.json is valid");
3648 assert_eq!(workspaces.len(), 1, "only the valid workspace discovers");
3649 fallow_config::stash_workspace_diagnostics(dir.path(), diagnostics);
3650
3651 warn_undeclared_workspaces(
3652 dir.path(),
3653 &workspaces,
3654 &fallow_config::IgnorePatternSet::empty(),
3655 false,
3656 );
3657
3658 let diagnostics = fallow_config::workspace_diagnostics_for(dir.path());
3659 let mut malformed = 0;
3660 let mut undeclared_for_bad = 0;
3661 for diag in &diagnostics {
3662 if matches!(
3663 diag.kind,
3664 WorkspaceDiagnosticKind::MalformedPackageJson { .. }
3665 ) && diag.path.ends_with("bad")
3666 {
3667 malformed += 1;
3668 }
3669 if matches!(diag.kind, WorkspaceDiagnosticKind::UndeclaredWorkspace)
3670 && diag.path.ends_with("bad")
3671 {
3672 undeclared_for_bad += 1;
3673 }
3674 }
3675 assert_eq!(
3676 malformed, 1,
3677 "expected one MalformedPackageJson for packages/bad: {diagnostics:?}"
3678 );
3679 assert_eq!(
3680 undeclared_for_bad, 0,
3681 "warn_undeclared_workspaces must NOT re-flag a path that already \
3682 carries MalformedPackageJson; got duplicates: {diagnostics:?}"
3683 );
3684 }
3685
3686 #[test]
3691 fn a_rewrite_after_the_parse_read_misses_the_next_run() {
3692 use fallow_types::discover::{DiscoveredFile, FileId};
3693
3694 let project = tempfile::tempdir().expect("create project");
3695 let path = project.path().join("api.ts");
3696 let before = "export const alpha = 1;\n";
3697 let after = "export const bravo = 1;\n";
3698 assert_eq!(before.len(), after.len());
3699 std::fs::write(&path, before).expect("write source");
3700 let discovered = [DiscoveredFile {
3701 id: FileId(0),
3702 path: path.clone(),
3703 size_bytes: u64::try_from(before.len()).expect("source length fits u64"),
3704 }];
3705
3706 let read_started_ns = fallow_types::source_fingerprint::now_ns();
3707 let first = super::extract::parse_all_files(&discovered, None, false);
3708 std::fs::write(&path, after).expect("rewrite source with equal-length content");
3709 let mut store = super::cache::CacheStore::new(project.path());
3710 super::update_cache(
3711 &mut store,
3712 &first.modules,
3713 &discovered,
3714 false,
3715 true,
3716 read_started_ns,
3717 );
3718
3719 let second = super::extract::parse_all_files(&discovered, Some(&store), false);
3720 let exports: Vec<String> = second
3721 .modules
3722 .first()
3723 .expect("second parse produces module")
3724 .exports
3725 .iter()
3726 .map(|export| export.name.to_string())
3727 .collect();
3728 assert_eq!(exports, vec!["bravo".to_string()]);
3729 }
3730
3731 #[test]
3732 fn workspace_prefix_uses_forward_slashes() {
3733 let prefix = super::workspace_prefix(Path::new("/r"), Path::new("/r/packages\\web"));
3734 assert_eq!(prefix, "packages/web");
3735 }
3736}