1use std::path::{Path, PathBuf};
4use std::sync::{Arc, Mutex};
5
6use dashmap::DashMap;
7use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
8use serde_json::Value;
9
10use fallow_config::TsconfigOutputMap;
11use fallow_types::discover::FileId;
12
13use crate::read_trace::Resolver;
14
15#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
17pub enum ResolveResult {
18 InternalModule(FileId),
20 CommonJsInternalModule(FileId),
22 SyntheticAutoImport(FileId),
24 InternalPackageModule {
27 file_id: FileId,
29 package_name: String,
31 },
32 CommonJsInternalPackageModule {
34 file_id: FileId,
36 package_name: String,
38 },
39 ExternalFile(PathBuf),
41 NpmPackage(String),
43 CommonJsNpmPackage(String),
45 Unresolvable(String),
47}
48
49impl ResolveResult {
50 #[must_use]
52 pub const fn internal_file_id(&self) -> Option<FileId> {
53 match self {
54 Self::InternalModule(file_id)
55 | Self::CommonJsInternalModule(file_id)
56 | Self::SyntheticAutoImport(file_id)
57 | Self::InternalPackageModule { file_id, .. }
58 | Self::CommonJsInternalPackageModule { file_id, .. } => Some(*file_id),
59 Self::ExternalFile(_)
60 | Self::NpmPackage(_)
61 | Self::CommonJsNpmPackage(_)
62 | Self::Unresolvable(_) => None,
63 }
64 }
65
66 #[must_use]
68 pub const fn is_synthetic_auto_import(&self) -> bool {
69 matches!(self, Self::SyntheticAutoImport(_))
70 }
71
72 #[must_use]
74 pub const fn is_commonjs_require(&self) -> bool {
75 matches!(
76 self,
77 Self::CommonJsInternalModule(_)
78 | Self::CommonJsInternalPackageModule { .. }
79 | Self::CommonJsNpmPackage(_)
80 )
81 }
82
83 #[must_use]
85 pub const fn is_bare_package(&self) -> bool {
86 matches!(self, Self::NpmPackage(_) | Self::CommonJsNpmPackage(_))
87 }
88
89 #[must_use]
91 pub fn into_commonjs_require(self) -> Self {
92 match self {
93 Self::InternalModule(file_id) => Self::CommonJsInternalModule(file_id),
94 Self::InternalPackageModule {
95 file_id,
96 package_name,
97 } => Self::CommonJsInternalPackageModule {
98 file_id,
99 package_name,
100 },
101 Self::NpmPackage(package_name) => Self::CommonJsNpmPackage(package_name),
102 other => other,
103 }
104 }
105
106 #[must_use]
108 pub fn into_es_module(self) -> Self {
109 match self {
110 Self::CommonJsInternalModule(file_id) => Self::InternalModule(file_id),
111 Self::CommonJsInternalPackageModule {
112 file_id,
113 package_name,
114 } => Self::InternalPackageModule {
115 file_id,
116 package_name,
117 },
118 Self::CommonJsNpmPackage(package_name) => Self::NpmPackage(package_name),
119 other => other,
120 }
121 }
122
123 #[must_use]
125 pub fn package_usage_name(&self) -> Option<&str> {
126 match self {
127 Self::InternalPackageModule { package_name, .. }
128 | Self::CommonJsInternalPackageModule { package_name, .. }
129 | Self::NpmPackage(package_name)
130 | Self::CommonJsNpmPackage(package_name) => Some(package_name),
131 Self::InternalModule(_)
132 | Self::CommonJsInternalModule(_)
133 | Self::SyntheticAutoImport(_)
134 | Self::ExternalFile(_)
135 | Self::Unresolvable(_) => None,
136 }
137 }
138}
139
140#[derive(Debug, Default)]
142pub struct ResolvedProject {
143 pub modules: Vec<ResolvedModule>,
145 pub replaced_module_targets: Vec<ResolvedReplacedModuleTarget>,
147 pub work: super::ResolveWork,
150}
151
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub struct ResolvedReplacedModuleTarget {
155 pub source_file: FileId,
157 pub target_file: FileId,
159}
160
161#[derive(Debug, Clone)]
163pub struct ResolvedImport {
164 pub info: fallow_types::extract::ImportInfo,
166 pub target: ResolveResult,
168}
169
170#[derive(Debug, Clone)]
172pub struct ResolvedReExport {
173 pub info: fallow_types::extract::ReExportInfo,
175 pub target: ResolveResult,
177}
178
179pub enum ResolvedSourceEdge<'a> {
181 Import(&'a ResolvedImport),
183 ReExport(&'a ResolvedReExport),
185}
186
187impl<'a> ResolvedSourceEdge<'a> {
188 #[must_use]
190 pub fn source_specifier(&self) -> &'a str {
191 match self {
192 Self::Import(import) => &import.info.source,
193 Self::ReExport(re_export) => &re_export.info.source,
194 }
195 }
196
197 #[must_use]
199 pub const fn target(&self) -> &'a ResolveResult {
200 match self {
201 Self::Import(import) => &import.target,
202 Self::ReExport(re_export) => &re_export.target,
203 }
204 }
205
206 #[must_use]
208 pub const fn is_type_only(&self) -> bool {
209 match self {
210 Self::Import(import) => import.info.is_type_only,
211 Self::ReExport(re_export) => re_export.info.is_type_only,
212 }
213 }
214
215 #[must_use]
217 pub const fn span(&self) -> oxc_span::Span {
218 match self {
219 Self::Import(import) => import.info.span,
220 Self::ReExport(re_export) => re_export.info.span,
221 }
222 }
223
224 #[must_use]
226 pub const fn source_span(&self) -> oxc_span::Span {
227 match self {
228 Self::Import(import) => import.info.source_span,
229 Self::ReExport(re_export) => re_export.info.source_span,
230 }
231 }
232
233 #[must_use]
238 pub const fn statement_span(&self) -> oxc_span::Span {
239 match self {
240 Self::Import(import) => import.info.span,
241 Self::ReExport(re_export) => re_export.info.statement_span,
242 }
243 }
244}
245
246#[derive(Debug, Clone)]
252pub struct ResolvedModule {
253 pub file_id: FileId,
255 pub path: PathBuf,
257 pub exports: Arc<[fallow_types::extract::ExportInfo]>,
259 pub re_exports: Vec<ResolvedReExport>,
261 pub resolved_imports: Vec<ResolvedImport>,
263 pub resolved_dynamic_imports: Vec<ResolvedImport>,
265 pub resolved_dynamic_patterns: Vec<(fallow_types::extract::DynamicImportPattern, Vec<FileId>)>,
267 pub member_accesses: Arc<[fallow_types::extract::MemberAccess]>,
269 pub semantic_facts: Arc<[fallow_types::extract::SemanticFact]>,
271 pub whole_object_uses: Arc<[String]>,
273 pub has_cjs_exports: bool,
275 pub has_angular_component_template_url: bool,
279 pub unused_import_bindings: FxHashSet<String>,
281 pub type_referenced_import_bindings: Vec<String>,
283 pub value_referenced_import_bindings: Vec<String>,
285 pub namespace_object_aliases: Vec<fallow_types::extract::NamespaceObjectAlias>,
288 pub exported_factory_returns: Arc<[fallow_types::extract::FactoryReturnExport]>,
291 pub exported_factory_return_object_shapes:
295 Arc<[fallow_types::extract::FactoryReturnObjectShapeExport]>,
296 pub type_member_types: Arc<[fallow_types::extract::TypeMemberTypeEntry]>,
300 pub missing_export_targets: Vec<MissingExportTarget>,
305}
306
307#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
310pub struct MissingExportTarget {
311 pub specifier: String,
313 pub paths: Vec<PathBuf>,
315}
316
317impl Default for ResolvedModule {
318 fn default() -> Self {
319 Self {
320 file_id: FileId(0),
321 path: PathBuf::new(),
322 exports: Arc::default(),
323 re_exports: vec![],
324 resolved_imports: vec![],
325 resolved_dynamic_imports: vec![],
326 resolved_dynamic_patterns: vec![],
327 member_accesses: Arc::default(),
328 semantic_facts: Arc::default(),
329 whole_object_uses: Arc::default(),
330 has_cjs_exports: false,
331 has_angular_component_template_url: false,
332 unused_import_bindings: FxHashSet::default(),
333 type_referenced_import_bindings: vec![],
334 value_referenced_import_bindings: vec![],
335 namespace_object_aliases: vec![],
336 exported_factory_returns: Arc::default(),
337 exported_factory_return_object_shapes: Arc::default(),
338 type_member_types: Arc::default(),
339 missing_export_targets: vec![],
340 }
341 }
342}
343
344impl ResolvedModule {
345 pub fn all_resolved_imports(&self) -> impl Iterator<Item = &ResolvedImport> {
351 self.resolved_imports
352 .iter()
353 .chain(self.resolved_dynamic_imports.iter())
354 }
355
356 pub fn all_resolved_source_edges(&self) -> impl Iterator<Item = ResolvedSourceEdge<'_>> {
362 self.resolved_imports
363 .iter()
364 .map(ResolvedSourceEdge::Import)
365 .chain(
366 self.resolved_dynamic_imports
367 .iter()
368 .map(ResolvedSourceEdge::Import),
369 )
370 .chain(self.re_exports.iter().map(ResolvedSourceEdge::ReExport))
371 }
372}
373
374pub(super) struct ResolveContext<'a> {
379 pub resolver: &'a Resolver,
381 pub script_resolver: &'a Resolver,
384 pub style_resolver: &'a Resolver,
388 pub extensions: &'a [String],
390 pub path_to_id: &'a FxHashMap<&'a Path, FileId>,
392 pub raw_path_to_id: &'a FxHashMap<&'a Path, FileId>,
394 pub workspace_roots: &'a FxHashMap<&'a str, &'a Path>,
396 pub package_manifests: &'a [PackageManifestInfo],
398 pub has_deno_import_maps: bool,
401 pub condition_names: &'a [String],
403 pub path_aliases: &'a [(String, String)],
405 pub scss_include_paths: &'a [PathBuf],
409 pub static_dir_mappings: &'a [(PathBuf, String)],
412 pub framework_static_dir_mappings: &'a [(PathBuf, String)],
416 pub root: &'a Path,
418 pub canonical_fallback: Option<&'a CanonicalFallback<'a>>,
422 pub tsconfig_warned: &'a Mutex<FxHashSet<String>>,
427 pub tsconfig_cache: &'a TsconfigCache,
432 pub canonicalize_cache: &'a CanonicalizeCache,
439}
440
441#[derive(Default)]
443pub(super) struct CanonicalizeCache {
444 map: DashMap<PathBuf, Option<PathBuf>, FxBuildHasher>,
445}
446
447impl CanonicalizeCache {
448 pub fn get(&self, path: &Path) -> Option<PathBuf> {
452 if let Some(value) = self.map.get(path) {
453 return value.clone();
454 }
455 let value = crate::read_trace::canonicalize(path).ok();
456 self.map.insert(path.to_path_buf(), value.clone());
457 value
458 }
459
460 pub fn distinct_paths(&self) -> usize {
464 self.map.len()
465 }
466}
467
468#[derive(Default)]
470pub(super) struct TsconfigCache {
471 json: DashMap<PathBuf, Option<Arc<Value>>, FxBuildHasher>,
472 chains: DashMap<PathBuf, Arc<[PathBuf]>, FxBuildHasher>,
473 output_maps: DashMap<PathBuf, Arc<TsconfigOutputMap>, FxBuildHasher>,
474}
475
476impl TsconfigCache {
477 pub fn json(
484 &self,
485 path: &Path,
486 load: impl FnOnce(&Path) -> Option<Value>,
487 ) -> Option<Arc<Value>> {
488 if let Some(value) = self.json.get(path) {
489 return value.clone();
490 }
491
492 let value = load(path).map(Arc::new);
493 self.json.insert(path.to_path_buf(), value.clone());
494 value
495 }
496
497 pub fn chain(&self, from_file: &Path) -> Option<Arc<[PathBuf]>> {
499 self.chains.get(from_file).map(|entry| Arc::clone(&entry))
500 }
501
502 pub fn store_chain(&self, from_file: &Path, chain: Arc<[PathBuf]>) {
504 self.chains.insert(from_file.to_path_buf(), chain);
505 }
506
507 pub fn output_map(&self, package_root: &Path) -> Arc<TsconfigOutputMap> {
510 if let Some(map) = self.output_maps.get(package_root) {
511 return Arc::clone(&map);
512 }
513 let map = Arc::new(TsconfigOutputMap::from_project(package_root));
514 self.output_maps
515 .insert(package_root.to_path_buf(), Arc::clone(&map));
516 map
517 }
518}
519
520#[derive(Debug, Clone)]
522pub(super) struct PackageManifestInfo {
523 pub root: PathBuf,
525 pub canonical_root: PathBuf,
527 pub name: Option<String>,
529 pub package_json: fallow_config::PackageJson,
531 pub deno_import_map: Vec<DenoImportMapEntry>,
533}
534
535#[derive(Debug, Clone)]
537pub(super) struct DenoImportMapEntry {
538 pub key: String,
539 pub target: String,
540 pub declaring_dir: PathBuf,
541}
542
543pub(super) struct CanonicalFallback<'a> {
545 files: &'a [fallow_types::discover::DiscoveredFile],
546 map: std::sync::OnceLock<FxHashMap<std::path::PathBuf, FileId>>,
547}
548
549impl<'a> CanonicalFallback<'a> {
550 pub const fn new(files: &'a [fallow_types::discover::DiscoveredFile]) -> Self {
551 Self {
552 files,
553 map: std::sync::OnceLock::new(),
554 }
555 }
556
557 pub fn get(&self, canonical: &Path) -> Option<FileId> {
559 let map = self.map.get_or_init(|| {
560 super::work::note_canonicalize(self.files.len() as u64);
561 tracing::debug!(
562 "intra-project symlinks detected, building canonical path index ({} files)",
563 self.files.len()
564 );
565 self.files
566 .iter()
567 .filter_map(|f| {
568 crate::read_trace::canonicalize(&f.path)
569 .ok()
570 .map(|canonical| (canonical, f.id))
571 })
572 .collect()
573 });
574 map.get(canonical).copied()
575 }
576}
577
578#[cfg(all(test, not(miri)))]
579mod tests {
580 use super::*;
581 use fallow_types::discover::DiscoveredFile;
582
583 #[test]
584 fn canonical_fallback_returns_none_for_empty_files() {
585 let files: Vec<DiscoveredFile> = vec![];
586 let fallback = CanonicalFallback::new(&files);
587 assert!(fallback.get(Path::new("/nonexistent")).is_none());
588 }
589
590 #[test]
591 fn canonical_fallback_finds_existing_file() {
592 let temp = std::env::temp_dir().join("fallow-test-canonical-fallback");
593 let _ = std::fs::create_dir_all(&temp);
594 let test_file = temp.join("test.ts");
595 std::fs::write(&test_file, "").unwrap();
596
597 let files = vec![DiscoveredFile {
598 id: FileId(42),
599 path: test_file.clone(),
600 size_bytes: 0,
601 }];
602 let fallback = CanonicalFallback::new(&files);
603
604 let canonical = dunce::canonicalize(&test_file).unwrap();
605 assert_eq!(fallback.get(&canonical), Some(FileId(42)));
606
607 assert_eq!(fallback.get(&canonical), Some(FileId(42)));
608
609 let _ = std::fs::remove_dir_all(&temp);
610 }
611
612 #[test]
613 fn canonical_fallback_returns_none_for_missing_path() {
614 let temp = std::env::temp_dir().join("fallow-test-canonical-miss");
615 let _ = std::fs::create_dir_all(&temp);
616 let test_file = temp.join("exists.ts");
617 std::fs::write(&test_file, "").unwrap();
618
619 let files = vec![DiscoveredFile {
620 id: FileId(1),
621 path: test_file,
622 size_bytes: 0,
623 }];
624 let fallback = CanonicalFallback::new(&files);
625 assert!(fallback.get(Path::new("/nonexistent/file.ts")).is_none());
626
627 let _ = std::fs::remove_dir_all(&temp);
628 }
629
630 #[test]
631 fn tsconfig_cache_loads_once_and_shares_the_parsed_document() {
632 let cache = TsconfigCache::default();
633 let path = Path::new("/project/tsconfig.json");
634 let loads = std::sync::atomic::AtomicUsize::new(0);
635 let load = |_: &Path| {
636 loads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
637 Some(serde_json::json!({ "compilerOptions": {} }))
638 };
639
640 let first = cache.json(path, load).unwrap();
641 let second = cache.json(path, load).unwrap();
642
643 assert_eq!(loads.load(std::sync::atomic::Ordering::SeqCst), 1);
644 assert!(
645 Arc::ptr_eq(&first, &second),
646 "repeat reads must share one allocation rather than deep-copy"
647 );
648 }
649
650 #[test]
652 fn tsconfig_cache_caches_a_failed_load() {
653 let cache = TsconfigCache::default();
654 let path = Path::new("/project/missing.json");
655 let loads = std::sync::atomic::AtomicUsize::new(0);
656 let load = |_: &Path| {
657 loads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
658 None
659 };
660
661 assert!(cache.json(path, load).is_none());
662 assert!(cache.json(path, load).is_none());
663 assert_eq!(loads.load(std::sync::atomic::Ordering::SeqCst), 1);
664 }
665
666 #[test]
667 fn tsconfig_cache_round_trips_a_chain() {
668 let cache = TsconfigCache::default();
669 let from_file = Path::new("/project/src/index.ts");
670 assert!(cache.chain(from_file).is_none());
671
672 let chain: Arc<[PathBuf]> = vec![PathBuf::from("/project/tsconfig.json")].into();
673 cache.store_chain(from_file, Arc::clone(&chain));
674
675 assert!(Arc::ptr_eq(&cache.chain(from_file).unwrap(), &chain));
676 }
677
678 #[test]
680 fn tsconfig_cache_is_consistent_under_concurrent_access() {
681 const THREADS: usize = 8;
682 const PATHS: usize = 32;
683
684 let cache = TsconfigCache::default();
685 std::thread::scope(|scope| {
686 for _ in 0..THREADS {
687 scope.spawn(|| {
688 for index in 0..PATHS {
689 let path = PathBuf::from(format!("/project/{index}/tsconfig.json"));
690 let json = cache
691 .json(&path, |_| Some(serde_json::json!({ "index": index })))
692 .unwrap();
693 assert_eq!(json["index"], index);
694 }
695 });
696 }
697 });
698 }
699
700 #[test]
701 fn canonicalize_cache_returns_the_same_result_on_repeat_lookups() {
702 let temp = tempfile::tempdir().expect("create temp dir");
703 let file = temp.path().join("file.ts");
704 std::fs::write(&file, "").unwrap();
705
706 let cache = CanonicalizeCache::default();
707 let expected = dunce::canonicalize(&file).ok();
708 assert_eq!(cache.get(&file), expected);
709 assert_eq!(cache.get(&file), expected);
710 assert!(cache.get(&temp.path().join("missing.ts")).is_none());
711 }
712
713 #[test]
714 fn commonjs_provenance_wraps_internal_and_bare_package_targets() {
715 assert!(matches!(
716 ResolveResult::InternalModule(FileId(4)).into_commonjs_require(),
717 ResolveResult::CommonJsInternalModule(FileId(4))
718 ));
719 assert!(matches!(
720 ResolveResult::InternalPackageModule {
721 file_id: FileId(5),
722 package_name: "pkg".to_string(),
723 }
724 .into_commonjs_require(),
725 ResolveResult::CommonJsInternalPackageModule {
726 file_id: FileId(5),
727 package_name,
728 } if package_name == "pkg"
729 ));
730 assert!(matches!(
731 ResolveResult::NpmPackage("pkg".to_string()).into_commonjs_require(),
732 ResolveResult::CommonJsNpmPackage(package_name) if package_name == "pkg"
733 ));
734 }
735}
736
737pub const OUTPUT_DIRS: &[&str] = &["dist", "build", "out", "esm", "cjs"];
742
743pub const MISSING_ONLY_OUTPUT_DIRS: &[&str] = &["lib"];
752
753pub const SOURCE_EXTS: &[&str] = &["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
755
756pub const RN_PLATFORM_PREFIXES: &[&str] = &[".web", ".ios", ".android", ".native"];