1use std::path::{Path, PathBuf};
7
8use rustc_hash::FxHashMap;
9use serde_json::Value;
10
11use fallow_types::discover::FileId;
12
13use super::path_info::{extract_package_name, is_bare_specifier, is_valid_package_name};
14use super::types::{OUTPUT_DIRS, PackageManifestInfo, ResolveContext, ResolveResult, SOURCE_EXTS};
15
16fn alias_match_remainder<'a>(specifier: &'a str, prefix: &str) -> Option<&'a str> {
25 let remainder = specifier.strip_prefix(prefix)?;
26 (remainder.is_empty() || prefix.ends_with('/') || remainder.starts_with('/'))
27 .then_some(remainder)
28}
29
30pub(super) fn try_path_alias_fallback(
37 ctx: &ResolveContext<'_>,
38 specifier: &str,
39) -> Option<ResolveResult> {
40 for (prefix, replacement) in ctx.path_aliases {
41 let Some(remainder) = alias_match_remainder(specifier, prefix) else {
42 continue;
43 };
44
45 let substituted = match (replacement.is_empty(), remainder.is_empty()) {
46 (true, _) => format!("./{remainder}"),
47 (false, true) => format!("./{replacement}"),
48 (false, false) => format!("./{replacement}/{remainder}"),
49 };
50
51 if let Ok(resolved) = ctx.resolver.resolve(ctx.root, &substituted) {
52 let resolved_path = resolved.path();
53 if let Some(&file_id) = ctx.raw_path_to_id.get(resolved_path) {
54 return Some(ResolveResult::InternalModule(file_id));
55 }
56 if let Ok(canonical) = dunce::canonicalize(resolved_path) {
57 if let Some(&file_id) = ctx.path_to_id.get(canonical.as_path()) {
58 return Some(ResolveResult::InternalModule(file_id));
59 }
60 if let Some(file_id) = try_source_fallback(&canonical, ctx.path_to_id) {
61 return Some(ResolveResult::InternalModule(file_id));
62 }
63 if let Some(file_id) =
64 try_pnpm_workspace_fallback(&canonical, ctx.path_to_id, ctx.workspace_roots)
65 {
66 return Some(ResolveResult::InternalModule(file_id));
67 }
68 if let Some(pkg_name) = extract_package_name_from_node_modules_path(&canonical) {
69 return Some(ResolveResult::NpmPackage(pkg_name));
70 }
71 return Some(ResolveResult::ExternalFile(canonical));
72 }
73 }
74 }
75 None
76}
77
78pub(super) fn try_scss_partial_fallback(
87 ctx: &ResolveContext<'_>,
88 from_file: &Path,
89 specifier: &str,
90) -> Option<ResolveResult> {
91 if specifier.contains(':') {
92 return None;
93 }
94
95 let spec_path = Path::new(specifier);
96 let filename = spec_path.file_name()?.to_str()?;
97
98 if filename.starts_with('_') {
99 return None;
100 }
101
102 let partial_filename = format!("_{filename}");
103 let partial_specifier = if let Some(parent) = spec_path.parent()
104 && !parent.as_os_str().is_empty()
105 {
106 format!("{}/{partial_filename}", parent.display())
107 } else {
108 partial_filename
109 };
110
111 if let Some(result) = try_resolve_scss(ctx, from_file, &partial_specifier) {
112 return Some(result);
113 }
114
115 let index_partial = format!("{specifier}/_index");
116 if let Some(result) = try_resolve_scss(ctx, from_file, &index_partial) {
117 return Some(result);
118 }
119
120 let index_plain = format!("{specifier}/index");
121 try_resolve_scss(ctx, from_file, &index_plain)
122}
123
124pub(super) fn try_css_extension_fallback(
134 ctx: &ResolveContext<'_>,
135 from_file: &Path,
136 specifier: &str,
137) -> Option<ResolveResult> {
138 if specifier.contains(':') {
139 return None;
140 }
141 let spec_path = Path::new(specifier);
142 let already_css_ext = spec_path
143 .extension()
144 .and_then(|e| e.to_str())
145 .is_some_and(|e| {
146 e.eq_ignore_ascii_case("css")
147 || e.eq_ignore_ascii_case("scss")
148 || e.eq_ignore_ascii_case("sass")
149 });
150 if already_css_ext {
151 return try_resolve_scss(ctx, from_file, specifier);
152 }
153 for ext in ["scss", "sass", "css"] {
154 let candidate = format!("{specifier}.{ext}");
155 if let Some(result) = try_resolve_scss(ctx, from_file, &candidate) {
156 return Some(result);
157 }
158 }
159 None
160}
161
162fn try_resolve_scss(
164 ctx: &ResolveContext<'_>,
165 from_file: &Path,
166 specifier: &str,
167) -> Option<ResolveResult> {
168 let resolved = ctx.resolver.resolve_file(from_file, specifier).ok()?;
169 let resolved_path = resolved.path();
170
171 if let Some(&file_id) = ctx.raw_path_to_id.get(resolved_path) {
172 return Some(ResolveResult::InternalModule(file_id));
173 }
174 if let Ok(canonical) = dunce::canonicalize(resolved_path)
175 && let Some(&file_id) = ctx.path_to_id.get(canonical.as_path())
176 {
177 return Some(ResolveResult::InternalModule(file_id));
178 }
179 None
180}
181
182pub(super) fn try_scss_include_path_fallback(
202 ctx: &ResolveContext<'_>,
203 from_file: &Path,
204 specifier: &str,
205 from_style: bool,
206) -> Option<ResolveResult> {
207 if ctx.scss_include_paths.is_empty() {
208 return None;
209 }
210 let is_scss_importer = from_file
211 .extension()
212 .is_some_and(|e| e == "scss" || e == "sass");
213 if !is_scss_importer && !from_style {
214 return None;
215 }
216 if specifier.contains(':') {
217 return None;
218 }
219 let bare = specifier.strip_prefix("./")?;
220 if bare.starts_with("..") || bare.starts_with('/') {
221 return None;
222 }
223
224 for include_dir in ctx.scss_include_paths {
225 if let Some(file_id) = find_scss_in_dir(include_dir, bare, ctx) {
226 return Some(ResolveResult::InternalModule(file_id));
227 }
228 }
229 None
230}
231
232fn find_scss_in_dir(include_dir: &Path, bare: &str, ctx: &ResolveContext<'_>) -> Option<FileId> {
236 let bare_path = Path::new(bare);
237 let has_scss_ext = matches!(
238 bare_path.extension().and_then(|e| e.to_str()),
239 Some(ext) if ext.eq_ignore_ascii_case("scss") || ext.eq_ignore_ascii_case("sass")
240 );
241
242 let parent = bare_path.parent();
243 let stem_with_ext = bare_path.file_name()?.to_str()?;
244 let stem_without_ext = bare_path.file_stem().and_then(|s| s.to_str())?;
245
246 let build = |rel: &Path| -> std::path::PathBuf { include_dir.join(rel) };
247 let join_with_parent = |name: &str| -> std::path::PathBuf {
248 parent.map_or_else(|| build(Path::new(name)), |p| build(&p.join(name)))
249 };
250
251 let exts: &[&str] = if has_scss_ext {
252 &[""]
253 } else {
254 &["scss", "sass"]
255 };
256
257 for ext in exts {
258 let suffix = if ext.is_empty() {
259 String::new()
260 } else {
261 format!(".{ext}")
262 };
263 let direct = if ext.is_empty() {
264 build(bare_path)
265 } else {
266 join_with_parent(&format!("{stem_with_ext}{suffix}"))
267 };
268 if let Some(fid) = lookup_scss_path(&direct, ctx) {
269 return Some(fid);
270 }
271 let partial_name = if ext.is_empty() {
272 format!("_{stem_with_ext}")
273 } else {
274 format!("_{stem_without_ext}{suffix}")
275 };
276 let partial = join_with_parent(&partial_name);
277 if let Some(fid) = lookup_scss_path(&partial, ctx) {
278 return Some(fid);
279 }
280 if ext.is_empty() {
281 continue;
282 }
283 let idx_partial = build(bare_path).join(format!("_index{suffix}"));
284 if let Some(fid) = lookup_scss_path(&idx_partial, ctx) {
285 return Some(fid);
286 }
287 let idx_plain = build(bare_path).join(format!("index{suffix}"));
288 if let Some(fid) = lookup_scss_path(&idx_plain, ctx) {
289 return Some(fid);
290 }
291 }
292 None
293}
294
295fn lookup_scss_path(candidate: &Path, ctx: &ResolveContext<'_>) -> Option<FileId> {
298 if let Some(&file_id) = ctx.raw_path_to_id.get(candidate) {
299 return Some(file_id);
300 }
301 if let Ok(canonical) = dunce::canonicalize(candidate) {
302 if let Some(&file_id) = ctx.path_to_id.get(canonical.as_path()) {
303 return Some(file_id);
304 }
305 if let Some(fallback) = ctx.canonical_fallback
306 && let Some(file_id) = fallback.get(&canonical)
307 {
308 return Some(file_id);
309 }
310 }
311 None
312}
313
314pub(super) fn try_scss_node_modules_fallback(
336 _ctx: &ResolveContext<'_>,
337 from_file: &Path,
338 specifier: &str,
339 from_style: bool,
340) -> Option<ResolveResult> {
341 if specifier.contains(':') {
342 return None;
343 }
344 let is_scss_importer = from_file
345 .extension()
346 .is_some_and(|e| e == "scss" || e == "sass");
347 if !is_scss_importer && !from_style {
348 return None;
349 }
350 let bare = specifier.strip_prefix("./")?;
351 if bare.starts_with("..") || bare.starts_with('/') {
352 return None;
353 }
354 if bare.is_empty() {
355 return None;
356 }
357
358 let mut dir = from_file.parent()?;
359 loop {
360 let nm_dir = dir.join("node_modules");
361 if nm_dir.is_dir()
362 && let Some(path) = find_scss_in_node_modules(&nm_dir, bare)
363 && let Some(pkg_name) = extract_package_name_from_node_modules_path(&path)
364 {
365 return Some(ResolveResult::NpmPackage(pkg_name));
366 }
367 let Some(parent) = dir.parent() else {
368 break;
369 };
370 dir = parent;
371 }
372 None
373}
374
375fn find_scss_in_node_modules(nm_dir: &Path, bare: &str) -> Option<PathBuf> {
384 let bare_path = Path::new(bare);
385 let file_name = bare_path.file_name()?.to_str()?;
386 let parent = bare_path.parent();
387 let join_with_parent = |name: &str| -> PathBuf {
388 parent.map_or_else(|| nm_dir.join(name), |p| nm_dir.join(p).join(name))
389 };
390
391 for ext in &["scss", "sass", "css"] {
392 let candidate = join_with_parent(&format!("{file_name}.{ext}"));
393 if candidate.is_file() {
394 return Some(candidate);
395 }
396 }
397 for ext in &["scss", "sass"] {
398 let candidate = join_with_parent(&format!("_{file_name}.{ext}"));
399 if candidate.is_file() {
400 return Some(candidate);
401 }
402 }
403 for ext in &["scss", "sass"] {
404 let idx_partial = nm_dir.join(bare).join(format!("_index.{ext}"));
405 if idx_partial.is_file() {
406 return Some(idx_partial);
407 }
408 let idx_plain = nm_dir.join(bare).join(format!("index.{ext}"));
409 if idx_plain.is_file() {
410 return Some(idx_plain);
411 }
412 }
413 let exact = nm_dir.join(bare);
414 if exact.is_file() {
415 return Some(exact);
416 }
417 None
418}
419
420pub(super) fn try_source_fallback(
432 resolved: &Path,
433 path_to_id: &FxHashMap<&Path, FileId>,
434) -> Option<FileId> {
435 let components: Vec<_> = resolved.components().collect();
436
437 let is_output_dir = |c: &std::path::Component| -> bool {
438 if let std::path::Component::Normal(s) = c
439 && let Some(name) = s.to_str()
440 {
441 return OUTPUT_DIRS.contains(&name);
442 }
443 false
444 };
445
446 let last_output_pos = components.iter().rposition(&is_output_dir)?;
447
448 let mut first_output_pos = last_output_pos;
449 while first_output_pos > 0 && is_output_dir(&components[first_output_pos - 1]) {
450 first_output_pos -= 1;
451 }
452
453 let prefix: PathBuf = components[..first_output_pos].iter().collect();
454
455 let suffix: PathBuf = components[last_output_pos + 1..].iter().collect();
456 suffix.file_stem()?; for ext in SOURCE_EXTS {
459 let source_candidate = prefix.join("src").join(suffix.with_extension(ext));
460 if let Some(&file_id) = path_to_id.get(source_candidate.as_path()) {
461 return Some(file_id);
462 }
463 }
464
465 None
466}
467
468pub(super) fn try_package_imports_fallback(
474 ctx: &ResolveContext<'_>,
475 from_file: &Path,
476 specifier: &str,
477) -> Option<ResolveResult> {
478 if !specifier.starts_with('#') {
479 return None;
480 }
481 let manifest = nearest_package_manifest(ctx.package_manifests, from_file)?;
482 let imports = manifest.package_json.imports.as_ref()?;
483 let PackageMapTarget::Targets(targets) =
484 package_map_target(imports, specifier, ctx.condition_names)
485 else {
486 return None;
487 };
488 let source_subpath = package_import_source_subpath(manifest, specifier);
489 resolve_package_import_targets(ctx, manifest, &targets, source_subpath.as_deref()).map(
490 |target| match target {
491 PackageImportTarget::Internal(file_id) => match &manifest.name {
492 Some(package_name) => ResolveResult::InternalPackageModule {
493 file_id,
494 package_name: package_name.clone(),
495 },
496 None => ResolveResult::InternalModule(file_id),
497 },
498 PackageImportTarget::ExternalPackage(package_name) => {
499 ResolveResult::NpmPackage(package_name)
500 }
501 },
502 )
503}
504
505pub(super) fn try_relative_package_root_source_fallback(
508 ctx: &ResolveContext<'_>,
509 from_file: &Path,
510 specifier: &str,
511) -> Option<ResolveResult> {
512 if !specifier.starts_with("./") && !specifier.starts_with("../") {
513 return None;
514 }
515
516 let from_dir = from_file.parent()?;
517 let candidate = from_dir.join(specifier);
518 let normalized_candidate = normalize_path_lexically(&candidate);
519 #[cfg(not(miri))]
520 let canonical_candidate = dunce::canonicalize(&candidate).ok();
521 #[cfg(miri)]
522 let canonical_candidate: Option<PathBuf> = None;
523
524 ctx.package_manifests.iter().find_map(|manifest| {
525 let matches_manifest = candidate == manifest.root
526 || normalized_candidate == manifest.root
527 || canonical_candidate
528 .as_deref()
529 .is_some_and(|canonical| canonical == manifest.canonical_root);
530 matches_manifest
531 .then(|| try_source_subpath(ctx, manifest, Path::new("")))
532 .flatten()
533 .map(ResolveResult::InternalModule)
534 })
535}
536
537fn normalize_path_lexically(path: &Path) -> PathBuf {
538 let mut normalized = PathBuf::new();
539 for component in path.components() {
540 match component {
541 std::path::Component::CurDir => {}
542 std::path::Component::ParentDir => {
543 if !normalized.pop() {
544 normalized.push(component.as_os_str());
545 }
546 }
547 std::path::Component::Prefix(_)
548 | std::path::Component::RootDir
549 | std::path::Component::Normal(_) => normalized.push(component.as_os_str()),
550 }
551 }
552 normalized
553}
554
555#[derive(Debug, Clone, PartialEq, Eq)]
556enum PackageMapTarget {
557 NoMatch,
558 Blocked,
559 Targets(Vec<String>),
560}
561
562enum PackageImportTarget {
563 Internal(FileId),
564 ExternalPackage(String),
565}
566
567fn package_map_match_value(
568 value: &Value,
569 condition_names: &[String],
570 capture: Option<&str>,
571) -> PackageMapTarget {
572 resolve_package_map_value(value, condition_names, capture)
573 .filter(|targets| !targets.is_empty())
574 .map_or(PackageMapTarget::Blocked, PackageMapTarget::Targets)
575}
576
577fn package_map_target(
578 map: &Value,
579 specifier_key: &str,
580 condition_names: &[String],
581) -> PackageMapTarget {
582 let Some(obj) = map.as_object() else {
583 if specifier_key == "." {
584 return package_map_match_value(map, condition_names, None);
585 }
586 return PackageMapTarget::NoMatch;
587 };
588
589 let has_subpath_keys = obj
590 .keys()
591 .any(|key| key == "." || key.starts_with("./") || key.starts_with('#'));
592 if !has_subpath_keys {
593 if specifier_key == "." {
594 return package_map_match_value(map, condition_names, None);
595 }
596 return PackageMapTarget::NoMatch;
597 }
598
599 if let Some(value) = obj.get(specifier_key) {
600 return package_map_match_value(value, condition_names, None);
601 }
602
603 let mut patterns: Vec<(&str, &Value, String)> = obj
604 .iter()
605 .filter_map(|(pattern, value)| {
606 package_map_pattern_capture(pattern, specifier_key)
607 .map(|capture| (pattern.as_str(), value, capture))
608 })
609 .collect();
610 patterns.sort_by(|(left, _, _), (right, _, _)| {
611 package_map_pattern_specificity(right).cmp(&package_map_pattern_specificity(left))
612 });
613
614 patterns
615 .first()
616 .map_or(PackageMapTarget::NoMatch, |(_, value, capture)| {
617 package_map_match_value(value, condition_names, Some(capture))
618 })
619}
620
621fn resolve_package_map_value(
622 value: &Value,
623 condition_names: &[String],
624 capture: Option<&str>,
625) -> Option<Vec<String>> {
626 match value {
627 Value::String(target) => Some(vec![match capture {
628 Some(capture) => target.replace('*', capture),
629 None => target.clone(),
630 }]),
631 Value::Object(map) => {
632 for (condition, value) in map {
633 if (condition == "default"
634 || condition_names
635 .iter()
636 .any(|active_condition| active_condition == condition))
637 && let Some(targets) =
638 resolve_package_map_value(value, condition_names, capture)
639 {
640 return Some(targets);
641 }
642 }
643 None
644 }
645 Value::Array(values) => {
646 let targets: Vec<String> = values
647 .iter()
648 .filter_map(|value| resolve_package_map_value(value, condition_names, capture))
649 .flatten()
650 .collect();
651 (!targets.is_empty()).then_some(targets)
652 }
653 Value::Bool(_) | Value::Null | Value::Number(_) => None,
654 }
655}
656
657fn package_map_pattern_capture(pattern: &str, specifier: &str) -> Option<String> {
658 let star = pattern.find('*')?;
659 if pattern[star + 1..].contains('*') {
660 return None;
661 }
662 let (prefix, suffix_with_star) = pattern.split_at(star);
663 let suffix = &suffix_with_star[1..];
664 let captured = specifier.strip_prefix(prefix)?.strip_suffix(suffix)?;
665 Some(captured.to_string())
666}
667
668fn package_map_pattern_specificity(pattern: &str) -> (usize, usize) {
669 let star = pattern.find('*').unwrap_or(pattern.len());
670 (star, pattern.len())
671}
672
673fn package_import_source_subpath(
674 manifest: &PackageManifestInfo,
675 specifier: &str,
676) -> Option<PathBuf> {
677 let stripped = specifier.strip_prefix('#')?;
678 let without_package_name = manifest
679 .name
680 .as_deref()
681 .and_then(|name| stripped.strip_prefix(name))
682 .and_then(|rest| rest.strip_prefix('/'))
683 .unwrap_or(stripped);
684 if without_package_name.is_empty() {
685 None
686 } else {
687 Some(PathBuf::from(without_package_name))
688 }
689}
690
691fn nearest_package_manifest<'a>(
692 manifests: &'a [PackageManifestInfo],
693 from_file: &Path,
694) -> Option<&'a PackageManifestInfo> {
695 manifests
696 .iter()
697 .filter(|manifest| {
698 from_file.starts_with(&manifest.root) || from_file.starts_with(&manifest.canonical_root)
699 })
700 .max_by_key(|manifest| manifest.root.components().count())
701}
702
703fn find_package_manifest<'a>(
704 manifests: &'a [PackageManifestInfo],
705 package_name: &str,
706) -> Option<&'a PackageManifestInfo> {
707 manifests
708 .iter()
709 .find(|manifest| manifest.name.as_deref() == Some(package_name))
710}
711
712fn resolve_package_map_target(
713 ctx: &ResolveContext<'_>,
714 manifest: &PackageManifestInfo,
715 target: &str,
716 source_subpath: Option<&Path>,
717) -> Option<FileId> {
718 let target = target.strip_prefix("./")?;
719 if target.starts_with("../") || target.starts_with('/') {
720 return None;
721 }
722 let target_path = manifest.root.join(target);
723
724 lookup_internal_file_id(ctx, &target_path)
725 .or_else(|| try_source_fallback(&target_path, ctx.raw_path_to_id))
726 .or_else(|| try_source_fallback(&target_path, ctx.path_to_id))
727 .or_else(|| source_subpath.and_then(|subpath| try_source_subpath(ctx, manifest, subpath)))
728}
729
730fn resolve_package_map_targets(
731 ctx: &ResolveContext<'_>,
732 manifest: &PackageManifestInfo,
733 targets: &[String],
734 source_subpath: Option<&Path>,
735) -> Option<FileId> {
736 targets
737 .iter()
738 .find_map(|target| resolve_package_map_target(ctx, manifest, target, source_subpath))
739}
740
741fn resolve_package_import_targets(
742 ctx: &ResolveContext<'_>,
743 manifest: &PackageManifestInfo,
744 targets: &[String],
745 source_subpath: Option<&Path>,
746) -> Option<PackageImportTarget> {
747 targets.iter().find_map(|target| {
748 resolve_package_map_target(ctx, manifest, target, source_subpath)
749 .map(PackageImportTarget::Internal)
750 .or_else(|| {
751 package_import_external_target(target).map(PackageImportTarget::ExternalPackage)
752 })
753 })
754}
755
756fn package_import_external_target(target: &str) -> Option<String> {
757 if is_bare_specifier(target) && is_valid_package_name(target) {
758 Some(extract_package_name(target))
759 } else {
760 None
761 }
762}
763
764fn try_source_subpath(
765 ctx: &ResolveContext<'_>,
766 manifest: &PackageManifestInfo,
767 subpath: &Path,
768) -> Option<FileId> {
769 if subpath.as_os_str().is_empty()
770 && let Some(source) = manifest.package_json.source.as_deref()
771 && let Some(source_path) = safe_relative_package_source_path(source)
772 && let Some(file_id) = lookup_internal_file_id(ctx, &manifest.root.join(source_path))
773 {
774 return Some(file_id);
775 }
776
777 for ext in SOURCE_EXTS {
778 let direct = if subpath.as_os_str().is_empty() {
779 manifest.root.join("src").join(format!("index.{ext}"))
780 } else {
781 manifest.root.join("src").join(subpath).with_extension(ext)
782 };
783 if let Some(file_id) = lookup_internal_file_id(ctx, &direct) {
784 return Some(file_id);
785 }
786
787 if !subpath.as_os_str().is_empty() {
788 let index = manifest
789 .root
790 .join("src")
791 .join(subpath)
792 .join(format!("index.{ext}"));
793 if let Some(file_id) = lookup_internal_file_id(ctx, &index) {
794 return Some(file_id);
795 }
796 }
797
798 if subpath.as_os_str().is_empty() {
799 let root_index = manifest.root.join(format!("index.{ext}"));
800 if let Some(file_id) = lookup_internal_file_id(ctx, &root_index) {
801 return Some(file_id);
802 }
803 }
804 }
805
806 None
807}
808
809fn safe_relative_package_source_path(source: &str) -> Option<&Path> {
810 let source = source.strip_prefix("./").unwrap_or(source);
811 let path = Path::new(source);
812 if path.as_os_str().is_empty()
813 || path.components().any(|component| {
814 matches!(
815 component,
816 std::path::Component::ParentDir
817 | std::path::Component::RootDir
818 | std::path::Component::Prefix(_)
819 )
820 })
821 {
822 None
823 } else {
824 Some(path)
825 }
826}
827
828fn lookup_internal_file_id(ctx: &ResolveContext<'_>, candidate: &Path) -> Option<FileId> {
829 if let Some(&file_id) = ctx.raw_path_to_id.get(candidate) {
830 return Some(file_id);
831 }
832 if let Some(&file_id) = ctx.path_to_id.get(candidate) {
833 return Some(file_id);
834 }
835 #[cfg(not(miri))]
836 if let Ok(canonical) = dunce::canonicalize(candidate) {
837 if let Some(&file_id) = ctx.path_to_id.get(canonical.as_path()) {
838 return Some(file_id);
839 }
840 if let Some(fallback) = ctx.canonical_fallback
841 && let Some(file_id) = fallback.get(&canonical)
842 {
843 return Some(file_id);
844 }
845 }
846 None
847}
848
849pub fn extract_package_name_from_node_modules_path(path: &Path) -> Option<String> {
855 let components: Vec<&str> = path
856 .components()
857 .filter_map(|c| match c {
858 std::path::Component::Normal(s) => s.to_str(),
859 _ => None,
860 })
861 .collect();
862
863 let nm_idx = components.iter().rposition(|&c| c == "node_modules")?;
864
865 let after = &components[nm_idx + 1..];
866 if after.is_empty() {
867 return None;
868 }
869
870 if after[0].starts_with('@') {
871 if after.len() >= 2 {
872 Some(format!("{}/{}", after[0], after[1]))
873 } else {
874 Some(after[0].to_string())
875 }
876 } else {
877 Some(after[0].to_string())
878 }
879}
880
881pub(super) fn try_pnpm_workspace_fallback(
890 path: &Path,
891 path_to_id: &FxHashMap<&Path, FileId>,
892 workspace_roots: &FxHashMap<&str, &Path>,
893) -> Option<FileId> {
894 let components: Vec<&str> = path
895 .components()
896 .filter_map(|c| match c {
897 std::path::Component::Normal(s) => s.to_str(),
898 _ => None,
899 })
900 .collect();
901
902 let pnpm_idx = components.iter().position(|&c| c == ".pnpm")?;
903
904 let after_pnpm = &components[pnpm_idx + 1..];
905
906 let inner_nm_idx = after_pnpm.iter().position(|&c| c == "node_modules")?;
907 let after_inner_nm = &after_pnpm[inner_nm_idx + 1..];
908
909 if after_inner_nm.is_empty() {
910 return None;
911 }
912
913 let (pkg_name, pkg_name_components) = if after_inner_nm[0].starts_with('@') {
914 if after_inner_nm.len() >= 2 {
915 (format!("{}/{}", after_inner_nm[0], after_inner_nm[1]), 2)
916 } else {
917 return None;
918 }
919 } else {
920 (after_inner_nm[0].to_string(), 1)
921 };
922
923 let ws_root = workspace_roots.get(pkg_name.as_str())?;
924
925 let relative_parts = &after_inner_nm[pkg_name_components..];
926 if relative_parts.is_empty() {
927 return None;
928 }
929
930 let relative_path: PathBuf = relative_parts.iter().collect();
931
932 let direct = ws_root.join(&relative_path);
933 if let Some(&file_id) = path_to_id.get(direct.as_path()) {
934 return Some(file_id);
935 }
936
937 try_source_fallback(&direct, path_to_id)
938}
939
940pub(super) fn try_workspace_package_fallback(
963 ctx: &ResolveContext<'_>,
964 specifier: &str,
965) -> Option<ResolveResult> {
966 if !super::path_info::is_bare_specifier(specifier) {
967 return None;
968 }
969 let pkg_name = super::path_info::extract_package_name(specifier);
970
971 let subpath = specifier
972 .strip_prefix(pkg_name.as_str())
973 .and_then(|s| s.strip_prefix('/'))
974 .unwrap_or("");
975 let source_subpath = PathBuf::from(subpath);
976
977 match try_manifest_workspace_resolution(ctx, &pkg_name, subpath, &source_subpath) {
978 ManifestWorkspaceResolution::Resolved(result) => return Some(result),
979 ManifestWorkspaceResolution::Blocked => return None,
980 ManifestWorkspaceResolution::Continue => {}
981 }
982
983 let ws_root =
984 if let Some(manifest) = find_package_manifest(ctx.package_manifests, pkg_name.as_str()) {
985 manifest.root.as_path()
986 } else {
987 *ctx.workspace_roots.get(pkg_name.as_str())?
988 };
989
990 resolve_workspace_self_reference(ctx, ws_root, subpath, pkg_name)
991}
992
993enum ManifestWorkspaceResolution {
996 Resolved(ResolveResult),
998 Blocked,
1000 Continue,
1002}
1003
1004fn try_manifest_workspace_resolution(
1007 ctx: &ResolveContext<'_>,
1008 pkg_name: &str,
1009 subpath: &str,
1010 source_subpath: &Path,
1011) -> ManifestWorkspaceResolution {
1012 let Some(manifest) = find_package_manifest(ctx.package_manifests, pkg_name) else {
1013 return ManifestWorkspaceResolution::Continue;
1014 };
1015
1016 if let Some(exports) = manifest.package_json.exports.as_ref() {
1017 let export_key = if subpath.is_empty() {
1018 ".".to_string()
1019 } else {
1020 format!("./{subpath}")
1021 };
1022 return match package_map_target(exports, &export_key, ctx.condition_names) {
1023 PackageMapTarget::Targets(targets) => {
1024 match resolve_package_map_targets(ctx, manifest, &targets, Some(source_subpath)) {
1025 Some(file_id) => ManifestWorkspaceResolution::Resolved(
1026 ResolveResult::InternalPackageModule {
1027 file_id,
1028 package_name: pkg_name.to_string(),
1029 },
1030 ),
1031 None => ManifestWorkspaceResolution::Continue,
1032 }
1033 }
1034 PackageMapTarget::NoMatch | PackageMapTarget::Blocked => {
1035 ManifestWorkspaceResolution::Blocked
1036 }
1037 };
1038 }
1039
1040 if let Some(file_id) = try_source_subpath(ctx, manifest, source_subpath) {
1041 return ManifestWorkspaceResolution::Resolved(ResolveResult::InternalPackageModule {
1042 file_id,
1043 package_name: pkg_name.to_string(),
1044 });
1045 }
1046
1047 ManifestWorkspaceResolution::Continue
1048}
1049
1050fn resolve_workspace_self_reference(
1054 ctx: &ResolveContext<'_>,
1055 ws_root: &Path,
1056 subpath: &str,
1057 package_name: String,
1058) -> Option<ResolveResult> {
1059 let root_file = ws_root.join("__fallow_ws_self_resolve__");
1060 let rel_spec = if subpath.is_empty() {
1061 "./".to_string()
1062 } else {
1063 format!("./{subpath}")
1064 };
1065
1066 let resolved = ctx.resolver.resolve_file(&root_file, &rel_spec).ok()?;
1067 let resolved_path = resolved.path();
1068
1069 if let Some(&file_id) = ctx.raw_path_to_id.get(resolved_path) {
1070 return Some(ResolveResult::InternalPackageModule {
1071 file_id,
1072 package_name,
1073 });
1074 }
1075 if let Ok(canonical) = dunce::canonicalize(resolved_path) {
1076 if let Some(&file_id) = ctx.path_to_id.get(canonical.as_path()) {
1077 return Some(ResolveResult::InternalPackageModule {
1078 file_id,
1079 package_name,
1080 });
1081 }
1082 if let Some(fallback) = ctx.canonical_fallback
1083 && let Some(file_id) = fallback.get(&canonical)
1084 {
1085 return Some(ResolveResult::InternalPackageModule {
1086 file_id,
1087 package_name,
1088 });
1089 }
1090 if let Some(file_id) = try_source_fallback(&canonical, ctx.path_to_id) {
1091 return Some(ResolveResult::InternalPackageModule {
1092 file_id,
1093 package_name,
1094 });
1095 }
1096 }
1097 None
1098}
1099
1100pub(super) fn make_glob_from_pattern(
1102 pattern: &fallow_types::extract::DynamicImportPattern,
1103) -> String {
1104 if pattern.prefix.contains('*') || pattern.prefix.contains('{') {
1105 return pattern.prefix.clone();
1106 }
1107 pattern.suffix.as_ref().map_or_else(
1108 || format!("{}*", pattern.prefix),
1109 |suffix| format!("{}*{}", pattern.prefix, suffix),
1110 )
1111}
1112
1113#[cfg(test)]
1114mod tests {
1115 use super::*;
1116 use crate::resolve::types::{CanonicalizeCache, TsconfigCache};
1117 use rustc_hash::FxHashSet;
1118
1119 fn with_package_map_ctx(
1120 root: PathBuf,
1121 name: Option<&str>,
1122 package_json: fallow_config::PackageJson,
1123 raw_files: &[(PathBuf, FileId)],
1124 f: impl FnOnce(&ResolveContext<'_>, &PackageManifestInfo, &Path),
1125 ) {
1126 let manifest = PackageManifestInfo {
1127 root: root.clone(),
1128 canonical_root: root,
1129 name: name.map(str::to_string),
1130 package_json,
1131 };
1132 let manifests = [manifest];
1133 let mut raw_path_to_id = FxHashMap::default();
1134 for (path, file_id) in raw_files {
1135 raw_path_to_id.insert(path.as_path(), *file_id);
1136 }
1137 let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
1138 let workspace_roots: FxHashMap<&str, &Path> = FxHashMap::default();
1139 let condition_names = conditions();
1140 let resolver = oxc_resolver::Resolver::new(oxc_resolver::ResolveOptions::default());
1141 let tsconfig_warned = std::sync::Mutex::new(FxHashSet::default());
1142 let tsconfig_cache = TsconfigCache::default();
1143 let canonicalize_cache = CanonicalizeCache::default();
1144 let ctx = ResolveContext {
1145 resolver: &resolver,
1146 style_resolver: &resolver,
1147 extensions: &[],
1148 path_to_id: &path_to_id,
1149 raw_path_to_id: &raw_path_to_id,
1150 workspace_roots: &workspace_roots,
1151 package_manifests: &manifests,
1152 condition_names: &condition_names,
1153 path_aliases: &[],
1154 scss_include_paths: &[],
1155 static_dir_mappings: &[],
1156 root: &manifests[0].root,
1157 canonical_fallback: None,
1158 tsconfig_warned: &tsconfig_warned,
1159 tsconfig_cache: &tsconfig_cache,
1160 canonicalize_cache: &canonicalize_cache,
1161 };
1162
1163 f(&ctx, &manifests[0], &manifests[0].root);
1164 }
1165
1166 #[test]
1167 fn alias_match_remainder_exact_key() {
1168 assert_eq!(alias_match_remainder("vscode", "vscode"), Some(""));
1169 assert_eq!(alias_match_remainder("@scope/sdk", "@scope/sdk"), Some(""));
1170 }
1171
1172 #[test]
1173 fn alias_match_remainder_slash_continuation() {
1174 assert_eq!(
1175 alias_match_remainder("@scope/sdk/sub", "@scope/sdk"),
1176 Some("/sub")
1177 );
1178 assert_eq!(alias_match_remainder("@/foo", "@/"), Some("foo"));
1179 assert_eq!(
1180 alias_match_remainder("~/components/x", "~/"),
1181 Some("components/x")
1182 );
1183 assert_eq!(alias_match_remainder("$lib/util", "$lib/"), Some("util"));
1184 }
1185
1186 #[test]
1187 fn alias_match_remainder_rejects_prefix_collision() {
1188 assert_eq!(
1189 alias_match_remainder("@scope/sdk-extra", "@scope/sdk"),
1190 None
1191 );
1192 assert_eq!(
1193 alias_match_remainder("vscode-languageserver", "vscode"),
1194 None
1195 );
1196 assert_eq!(alias_match_remainder("#shared-utils", "#shared"), None);
1197 }
1198
1199 #[test]
1200 fn alias_match_remainder_non_match() {
1201 assert_eq!(alias_match_remainder("react", "vscode"), None);
1202 }
1203
1204 #[test]
1205 fn test_extract_package_name_from_node_modules_path_regular() {
1206 let path = PathBuf::from("/project/node_modules/react/index.js");
1207 assert_eq!(
1208 extract_package_name_from_node_modules_path(&path),
1209 Some("react".to_string())
1210 );
1211 }
1212
1213 #[test]
1214 fn test_extract_package_name_from_node_modules_path_scoped() {
1215 let path = PathBuf::from("/project/node_modules/@babel/core/lib/index.js");
1216 assert_eq!(
1217 extract_package_name_from_node_modules_path(&path),
1218 Some("@babel/core".to_string())
1219 );
1220 }
1221
1222 #[test]
1223 fn test_extract_package_name_from_node_modules_path_nested() {
1224 let path = PathBuf::from("/project/node_modules/pkg-a/node_modules/pkg-b/dist/index.js");
1225 assert_eq!(
1226 extract_package_name_from_node_modules_path(&path),
1227 Some("pkg-b".to_string())
1228 );
1229 }
1230
1231 #[test]
1232 fn test_extract_package_name_from_node_modules_path_deep_subpath() {
1233 let path = PathBuf::from("/project/node_modules/react-dom/cjs/react-dom.production.min.js");
1234 assert_eq!(
1235 extract_package_name_from_node_modules_path(&path),
1236 Some("react-dom".to_string())
1237 );
1238 }
1239
1240 #[test]
1241 fn test_extract_package_name_from_node_modules_path_no_node_modules() {
1242 let path = PathBuf::from("/project/src/components/Button.tsx");
1243 assert_eq!(extract_package_name_from_node_modules_path(&path), None);
1244 }
1245
1246 #[test]
1247 fn test_extract_package_name_from_node_modules_path_just_node_modules() {
1248 let path = PathBuf::from("/project/node_modules");
1249 assert_eq!(extract_package_name_from_node_modules_path(&path), None);
1250 }
1251
1252 #[test]
1253 fn test_extract_package_name_from_node_modules_path_scoped_only_scope() {
1254 let path = PathBuf::from("/project/node_modules/@scope");
1255 assert_eq!(
1256 extract_package_name_from_node_modules_path(&path),
1257 Some("@scope".to_string())
1258 );
1259 }
1260
1261 #[test]
1262 fn test_resolve_specifier_node_modules_returns_npm_package() {
1263 let path =
1264 PathBuf::from("/project/node_modules/styled-components/dist/styled-components.esm.js");
1265 assert_eq!(
1266 extract_package_name_from_node_modules_path(&path),
1267 Some("styled-components".to_string())
1268 );
1269
1270 let path = PathBuf::from("/project/node_modules/next/dist/server/next.js");
1271 assert_eq!(
1272 extract_package_name_from_node_modules_path(&path),
1273 Some("next".to_string())
1274 );
1275 }
1276
1277 #[test]
1278 fn test_try_source_fallback_dist_to_src() {
1279 let src_path = PathBuf::from("/project/packages/ui/src/utils.ts");
1280 let mut path_to_id = FxHashMap::default();
1281 path_to_id.insert(src_path.as_path(), FileId(0));
1282
1283 let dist_path = PathBuf::from("/project/packages/ui/dist/utils.js");
1284 assert_eq!(
1285 try_source_fallback(&dist_path, &path_to_id),
1286 Some(FileId(0)),
1287 "dist/utils.js should fall back to src/utils.ts"
1288 );
1289 }
1290
1291 #[test]
1292 fn test_try_source_fallback_build_to_src() {
1293 let src_path = PathBuf::from("/project/packages/core/src/index.tsx");
1294 let mut path_to_id = FxHashMap::default();
1295 path_to_id.insert(src_path.as_path(), FileId(1));
1296
1297 let build_path = PathBuf::from("/project/packages/core/build/index.js");
1298 assert_eq!(
1299 try_source_fallback(&build_path, &path_to_id),
1300 Some(FileId(1)),
1301 "build/index.js should fall back to src/index.tsx"
1302 );
1303 }
1304
1305 #[test]
1306 fn test_try_source_fallback_no_match() {
1307 let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
1308
1309 let dist_path = PathBuf::from("/project/packages/ui/dist/utils.js");
1310 assert_eq!(
1311 try_source_fallback(&dist_path, &path_to_id),
1312 None,
1313 "should return None when no source file exists"
1314 );
1315 }
1316
1317 #[test]
1318 fn test_try_source_fallback_non_output_dir() {
1319 let src_path = PathBuf::from("/project/packages/ui/src/utils.ts");
1320 let mut path_to_id = FxHashMap::default();
1321 path_to_id.insert(src_path.as_path(), FileId(0));
1322
1323 let normal_path = PathBuf::from("/project/packages/ui/scripts/utils.js");
1324 assert_eq!(
1325 try_source_fallback(&normal_path, &path_to_id),
1326 None,
1327 "non-output directory path should not trigger fallback"
1328 );
1329 }
1330
1331 #[test]
1332 fn test_try_source_fallback_nested_path() {
1333 let src_path = PathBuf::from("/project/packages/ui/src/components/Button.ts");
1334 let mut path_to_id = FxHashMap::default();
1335 path_to_id.insert(src_path.as_path(), FileId(2));
1336
1337 let dist_path = PathBuf::from("/project/packages/ui/dist/components/Button.js");
1338 assert_eq!(
1339 try_source_fallback(&dist_path, &path_to_id),
1340 Some(FileId(2)),
1341 "nested dist path should fall back to nested src path"
1342 );
1343 }
1344
1345 #[test]
1346 fn test_try_source_fallback_nested_dist_esm() {
1347 let src_path = PathBuf::from("/project/packages/ui/src/utils.ts");
1348 let mut path_to_id = FxHashMap::default();
1349 path_to_id.insert(src_path.as_path(), FileId(0));
1350
1351 let dist_path = PathBuf::from("/project/packages/ui/dist/esm/utils.mjs");
1352 assert_eq!(
1353 try_source_fallback(&dist_path, &path_to_id),
1354 Some(FileId(0)),
1355 "dist/esm/utils.mjs should fall back to src/utils.ts"
1356 );
1357 }
1358
1359 #[test]
1360 fn test_try_source_fallback_nested_build_cjs() {
1361 let src_path = PathBuf::from("/project/packages/core/src/index.ts");
1362 let mut path_to_id = FxHashMap::default();
1363 path_to_id.insert(src_path.as_path(), FileId(1));
1364
1365 let build_path = PathBuf::from("/project/packages/core/build/cjs/index.cjs");
1366 assert_eq!(
1367 try_source_fallback(&build_path, &path_to_id),
1368 Some(FileId(1)),
1369 "build/cjs/index.cjs should fall back to src/index.ts"
1370 );
1371 }
1372
1373 #[test]
1374 fn test_try_source_fallback_nested_dist_esm_deep_path() {
1375 let src_path = PathBuf::from("/project/packages/ui/src/components/Button.ts");
1376 let mut path_to_id = FxHashMap::default();
1377 path_to_id.insert(src_path.as_path(), FileId(2));
1378
1379 let dist_path = PathBuf::from("/project/packages/ui/dist/esm/components/Button.mjs");
1380 assert_eq!(
1381 try_source_fallback(&dist_path, &path_to_id),
1382 Some(FileId(2)),
1383 "dist/esm/components/Button.mjs should fall back to src/components/Button.ts"
1384 );
1385 }
1386
1387 #[test]
1388 fn test_try_source_fallback_triple_nested_output_dirs() {
1389 let src_path = PathBuf::from("/project/packages/ui/src/utils.ts");
1390 let mut path_to_id = FxHashMap::default();
1391 path_to_id.insert(src_path.as_path(), FileId(0));
1392
1393 let dist_path = PathBuf::from("/project/packages/ui/out/dist/esm/utils.mjs");
1394 assert_eq!(
1395 try_source_fallback(&dist_path, &path_to_id),
1396 Some(FileId(0)),
1397 "out/dist/esm/utils.mjs should fall back to src/utils.ts"
1398 );
1399 }
1400
1401 #[test]
1402 fn test_try_source_fallback_parent_dir_named_build() {
1403 let src_path = PathBuf::from("/home/user/build/my-project/src/utils.ts");
1404 let mut path_to_id = FxHashMap::default();
1405 path_to_id.insert(src_path.as_path(), FileId(0));
1406
1407 let dist_path = PathBuf::from("/home/user/build/my-project/dist/utils.js");
1408 assert_eq!(
1409 try_source_fallback(&dist_path, &path_to_id),
1410 Some(FileId(0)),
1411 "should resolve dist/ within project, not match parent 'build' dir"
1412 );
1413 }
1414
1415 #[test]
1416 fn package_map_exact_entry_beats_pattern_entry() {
1417 let map = serde_json::json!({
1418 "#nitro/runtime/task": "./dist/special/task.mjs",
1419 "#nitro/runtime/*": "./dist/runtime/internal/*.mjs"
1420 });
1421 assert_eq!(
1422 package_map_target(&map, "#nitro/runtime/task", &conditions()),
1423 PackageMapTarget::Targets(vec!["./dist/special/task.mjs".to_string()])
1424 );
1425 }
1426
1427 #[test]
1428 fn package_map_wildcard_substitutes_capture() {
1429 let map = serde_json::json!({
1430 "#nitro/runtime/*": "./dist/runtime/internal/*.mjs"
1431 });
1432 assert_eq!(
1433 package_map_target(&map, "#nitro/runtime/task", &conditions()),
1434 PackageMapTarget::Targets(vec!["./dist/runtime/internal/task.mjs".to_string()])
1435 );
1436 }
1437
1438 #[test]
1439 fn package_map_exact_entry_with_no_target_blocks_pattern_entry() {
1440 let map = serde_json::json!({
1441 "#nitro/runtime/task": null,
1442 "#nitro/runtime/*": "./dist/runtime/internal/*.mjs"
1443 });
1444 assert_eq!(
1445 package_map_target(&map, "#nitro/runtime/task", &conditions()),
1446 PackageMapTarget::Blocked
1447 );
1448 }
1449
1450 #[test]
1451 fn package_map_best_pattern_with_no_target_blocks_broader_pattern() {
1452 let map = serde_json::json!({
1453 "#nitro/runtime/internal/*": null,
1454 "#nitro/runtime/*": "./dist/runtime/*.mjs"
1455 });
1456 assert_eq!(
1457 package_map_target(&map, "#nitro/runtime/internal/task", &conditions()),
1458 PackageMapTarget::Blocked
1459 );
1460 }
1461
1462 #[test]
1463 fn package_map_unmatched_subpath_is_not_a_target() {
1464 let map = serde_json::json!({
1465 "./query": "./dist/query/index.js"
1466 });
1467 assert_eq!(
1468 package_map_target(&map, "./private", &conditions()),
1469 PackageMapTarget::NoMatch
1470 );
1471 }
1472
1473 #[test]
1474 fn package_map_nested_conditions_follow_manifest_order() {
1475 let map = serde_json::json!({
1476 "./query/react": {
1477 "types": "./dist/query/react/index.d.ts",
1478 "import": {
1479 "development": "./src/query/react/index.ts",
1480 "default": "./dist/query/react/index.js"
1481 },
1482 "default": "./dist/query/react/index.cjs"
1483 }
1484 });
1485 assert_eq!(
1486 package_map_target(&map, "./query/react", &conditions()),
1487 PackageMapTarget::Targets(vec!["./dist/query/react/index.d.ts".to_string()])
1488 );
1489 }
1490
1491 #[test]
1492 fn package_map_import_before_types_selects_runtime_branch() {
1493 let map = serde_json::json!({
1494 ".": {
1495 "import": "./dist/index.js",
1496 "types": "./dist/index.d.ts"
1497 }
1498 });
1499 assert_eq!(
1500 package_map_target(&map, ".", &conditions()),
1501 PackageMapTarget::Targets(vec!["./dist/index.js".to_string()])
1502 );
1503 }
1504
1505 #[test]
1506 fn package_map_condition_order_follows_manifest_order() {
1507 let map = serde_json::json!({
1508 ".": {
1509 "node": "./dist/node.js",
1510 "import": "./dist/index.js"
1511 }
1512 });
1513 assert_eq!(
1514 package_map_target(&map, ".", &conditions()),
1515 PackageMapTarget::Targets(vec!["./dist/node.js".to_string()])
1516 );
1517 }
1518
1519 #[test]
1520 fn package_map_arrays_preserve_fallback_order() {
1521 let map = serde_json::json!({
1522 "#array": ["./dist/missing.js", "./src/array.ts"],
1523 "#null": null,
1524 "#false": false
1525 });
1526 assert_eq!(
1527 package_map_target(&map, "#array", &conditions()),
1528 PackageMapTarget::Targets(vec![
1529 "./dist/missing.js".to_string(),
1530 "./src/array.ts".to_string()
1531 ])
1532 );
1533 assert_eq!(
1534 package_map_target(&map, "#null", &conditions()),
1535 PackageMapTarget::Blocked
1536 );
1537 assert_eq!(
1538 package_map_target(&map, "#false", &conditions()),
1539 PackageMapTarget::Blocked
1540 );
1541 }
1542
1543 #[test]
1544 fn package_map_non_relative_target_does_not_trigger_source_fallback() {
1545 with_package_map_ctx(
1546 PathBuf::from("/project"),
1547 Some("pkg"),
1548 fallow_config::PackageJson::default(),
1549 &[],
1550 |ctx, manifest, _| {
1551 assert!(resolve_package_map_target(ctx, manifest, "lodash", None).is_none());
1552 assert!(
1553 resolve_package_map_target(ctx, manifest, "../dist/index.js", None).is_none()
1554 );
1555 },
1556 );
1557 }
1558
1559 #[test]
1560 fn package_map_targets_use_first_reachable_target() {
1561 let root = PathBuf::from("/project");
1562 let src_path = root.join("src/feature.ts");
1563 let targets = vec![
1564 "./dist/missing.js".to_string(),
1565 "./src/feature.ts".to_string(),
1566 ];
1567
1568 with_package_map_ctx(
1569 root,
1570 Some("pkg"),
1571 fallow_config::PackageJson::default(),
1572 &[(src_path, FileId(9))],
1573 |ctx, manifest, _| {
1574 assert_eq!(
1575 resolve_package_map_targets(ctx, manifest, &targets, None),
1576 Some(FileId(9))
1577 );
1578 },
1579 );
1580 }
1581
1582 #[test]
1583 fn package_imports_fallback_supports_external_package_targets() {
1584 let root = PathBuf::from("/project");
1585 with_package_map_ctx(
1586 root,
1587 Some("pkg"),
1588 fallow_config::PackageJson {
1589 imports: Some(serde_json::json!({
1590 "#pad": "left-pad",
1591 "#scoped": "@scope/pkg/subpath"
1592 })),
1593 ..Default::default()
1594 },
1595 &[],
1596 |ctx, _, root| {
1597 let pad = try_package_imports_fallback(ctx, &root.join("src/index.ts"), "#pad");
1598 assert!(matches!(pad, Some(ResolveResult::NpmPackage(pkg)) if pkg == "left-pad"));
1599
1600 let scoped =
1601 try_package_imports_fallback(ctx, &root.join("src/index.ts"), "#scoped");
1602 assert!(
1603 matches!(scoped, Some(ResolveResult::NpmPackage(pkg)) if pkg == "@scope/pkg")
1604 );
1605 },
1606 );
1607 }
1608
1609 #[test]
1610 fn package_imports_fallback_supports_unnamed_packages() {
1611 let root = PathBuf::from("/project");
1612 let src_path = root.join("src/runtime/task.ts");
1613 with_package_map_ctx(
1614 root,
1615 None,
1616 fallow_config::PackageJson {
1617 imports: Some(serde_json::json!({
1618 "#runtime/*": "./dist/runtime/*.mjs"
1619 })),
1620 ..Default::default()
1621 },
1622 &[(src_path, FileId(7))],
1623 |ctx, _, root| {
1624 let result =
1625 try_package_imports_fallback(ctx, &root.join("src/index.ts"), "#runtime/task");
1626 assert!(matches!(
1627 result,
1628 Some(ResolveResult::InternalModule(FileId(7)))
1629 ));
1630 },
1631 );
1632 }
1633
1634 #[test]
1635 #[cfg_attr(miri, ignore)]
1636 fn relative_package_root_source_fallback_uses_package_source_entry() {
1637 let root = PathBuf::from("/project");
1638 let source_path = root.join("custom/entry.js");
1639 with_package_map_ctx(
1640 root,
1641 Some("pkg"),
1642 fallow_config::PackageJson {
1643 source: Some("custom/entry.js".to_string()),
1644 ..Default::default()
1645 },
1646 &[(source_path, FileId(11))],
1647 |ctx, _, root| {
1648 let result = try_relative_package_root_source_fallback(
1649 ctx,
1650 &root.join("test/shared/exports.test.js"),
1651 "../../",
1652 );
1653 assert!(matches!(
1654 result,
1655 Some(ResolveResult::InternalModule(FileId(11)))
1656 ));
1657 },
1658 );
1659 }
1660
1661 #[test]
1662 fn package_source_path_accepts_relative_source_entries() {
1663 assert_eq!(
1664 safe_relative_package_source_path("src/index.js"),
1665 Some(Path::new("src/index.js"))
1666 );
1667 assert_eq!(
1668 safe_relative_package_source_path("./custom/entry.ts"),
1669 Some(Path::new("custom/entry.ts"))
1670 );
1671 }
1672
1673 #[test]
1674 fn package_source_path_rejects_unsafe_entries() {
1675 assert_eq!(safe_relative_package_source_path(""), None);
1676 assert_eq!(safe_relative_package_source_path("./"), None);
1677 assert_eq!(safe_relative_package_source_path("../src/index.js"), None);
1678 assert_eq!(safe_relative_package_source_path("src/../index.js"), None);
1679 assert_eq!(safe_relative_package_source_path("/src/index.js"), None);
1680
1681 #[cfg(windows)]
1682 assert_eq!(safe_relative_package_source_path("C:\\src\\index.js"), None);
1683 }
1684
1685 #[test]
1686 fn test_pnpm_store_path_extract_package_name() {
1687 let path =
1688 PathBuf::from("/project/node_modules/.pnpm/react@18.2.0/node_modules/react/index.js");
1689 assert_eq!(
1690 extract_package_name_from_node_modules_path(&path),
1691 Some("react".to_string())
1692 );
1693 }
1694
1695 #[test]
1696 fn test_pnpm_store_path_scoped_package() {
1697 let path = PathBuf::from(
1698 "/project/node_modules/.pnpm/@babel+core@7.24.0/node_modules/@babel/core/lib/index.js",
1699 );
1700 assert_eq!(
1701 extract_package_name_from_node_modules_path(&path),
1702 Some("@babel/core".to_string())
1703 );
1704 }
1705
1706 fn conditions() -> Vec<String> {
1707 vec![
1708 "development".to_string(),
1709 "import".to_string(),
1710 "require".to_string(),
1711 "default".to_string(),
1712 "types".to_string(),
1713 "node".to_string(),
1714 ]
1715 }
1716
1717 #[test]
1718 fn test_pnpm_store_path_with_peer_deps() {
1719 let path = PathBuf::from(
1720 "/project/node_modules/.pnpm/webpack@5.0.0_esbuild@0.19.0/node_modules/webpack/lib/index.js",
1721 );
1722 assert_eq!(
1723 extract_package_name_from_node_modules_path(&path),
1724 Some("webpack".to_string())
1725 );
1726 }
1727
1728 #[test]
1729 fn test_try_pnpm_workspace_fallback_dist_to_src() {
1730 let src_path = PathBuf::from("/project/packages/ui/src/utils.ts");
1731 let mut path_to_id = FxHashMap::default();
1732 path_to_id.insert(src_path.as_path(), FileId(0));
1733
1734 let mut workspace_roots = FxHashMap::default();
1735 let ws_root = PathBuf::from("/project/packages/ui");
1736 workspace_roots.insert("@myorg/ui", ws_root.as_path());
1737
1738 let pnpm_path = PathBuf::from(
1739 "/project/node_modules/.pnpm/@myorg+ui@1.0.0/node_modules/@myorg/ui/dist/utils.js",
1740 );
1741 assert_eq!(
1742 try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
1743 Some(FileId(0)),
1744 ".pnpm workspace path should fall back to src/utils.ts"
1745 );
1746 }
1747
1748 #[test]
1749 fn test_try_pnpm_workspace_fallback_direct_source() {
1750 let src_path = PathBuf::from("/project/packages/core/src/index.ts");
1751 let mut path_to_id = FxHashMap::default();
1752 path_to_id.insert(src_path.as_path(), FileId(1));
1753
1754 let mut workspace_roots = FxHashMap::default();
1755 let ws_root = PathBuf::from("/project/packages/core");
1756 workspace_roots.insert("@myorg/core", ws_root.as_path());
1757
1758 let pnpm_path = PathBuf::from(
1759 "/project/node_modules/.pnpm/@myorg+core@workspace/node_modules/@myorg/core/src/index.ts",
1760 );
1761 assert_eq!(
1762 try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
1763 Some(FileId(1)),
1764 ".pnpm workspace path with src/ should resolve directly"
1765 );
1766 }
1767
1768 #[test]
1769 fn test_try_pnpm_workspace_fallback_non_workspace_package() {
1770 let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
1771
1772 let mut workspace_roots = FxHashMap::default();
1773 let ws_root = PathBuf::from("/project/packages/ui");
1774 workspace_roots.insert("@myorg/ui", ws_root.as_path());
1775
1776 let pnpm_path =
1777 PathBuf::from("/project/node_modules/.pnpm/react@18.2.0/node_modules/react/index.js");
1778 assert_eq!(
1779 try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
1780 None,
1781 "non-workspace package in .pnpm should return None"
1782 );
1783 }
1784
1785 #[test]
1786 fn test_try_pnpm_workspace_fallback_unscoped_package() {
1787 let src_path = PathBuf::from("/project/packages/utils/src/index.ts");
1788 let mut path_to_id = FxHashMap::default();
1789 path_to_id.insert(src_path.as_path(), FileId(2));
1790
1791 let mut workspace_roots = FxHashMap::default();
1792 let ws_root = PathBuf::from("/project/packages/utils");
1793 workspace_roots.insert("my-utils", ws_root.as_path());
1794
1795 let pnpm_path = PathBuf::from(
1796 "/project/node_modules/.pnpm/my-utils@1.0.0/node_modules/my-utils/dist/index.js",
1797 );
1798 assert_eq!(
1799 try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
1800 Some(FileId(2)),
1801 "unscoped workspace package in .pnpm should resolve"
1802 );
1803 }
1804
1805 #[test]
1806 fn test_try_pnpm_workspace_fallback_nested_path() {
1807 let src_path = PathBuf::from("/project/packages/ui/src/components/Button.ts");
1808 let mut path_to_id = FxHashMap::default();
1809 path_to_id.insert(src_path.as_path(), FileId(3));
1810
1811 let mut workspace_roots = FxHashMap::default();
1812 let ws_root = PathBuf::from("/project/packages/ui");
1813 workspace_roots.insert("@myorg/ui", ws_root.as_path());
1814
1815 let pnpm_path = PathBuf::from(
1816 "/project/node_modules/.pnpm/@myorg+ui@1.0.0/node_modules/@myorg/ui/dist/components/Button.js",
1817 );
1818 assert_eq!(
1819 try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
1820 Some(FileId(3)),
1821 "nested .pnpm workspace path should resolve through source fallback"
1822 );
1823 }
1824
1825 #[test]
1826 fn test_try_pnpm_workspace_fallback_no_pnpm() {
1827 let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
1828 let workspace_roots: FxHashMap<&str, &Path> = FxHashMap::default();
1829
1830 let regular_path = PathBuf::from("/project/node_modules/react/index.js");
1831 assert_eq!(
1832 try_pnpm_workspace_fallback(®ular_path, &path_to_id, &workspace_roots),
1833 None,
1834 );
1835 }
1836
1837 #[test]
1838 fn test_try_pnpm_workspace_fallback_with_peer_deps() {
1839 let src_path = PathBuf::from("/project/packages/ui/src/index.ts");
1840 let mut path_to_id = FxHashMap::default();
1841 path_to_id.insert(src_path.as_path(), FileId(4));
1842
1843 let mut workspace_roots = FxHashMap::default();
1844 let ws_root = PathBuf::from("/project/packages/ui");
1845 workspace_roots.insert("@myorg/ui", ws_root.as_path());
1846
1847 let pnpm_path = PathBuf::from(
1848 "/project/node_modules/.pnpm/@myorg+ui@1.0.0_react@18.2.0/node_modules/@myorg/ui/dist/index.js",
1849 );
1850 assert_eq!(
1851 try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
1852 Some(FileId(4)),
1853 ".pnpm path with peer dep suffix should still resolve"
1854 );
1855 }
1856
1857 #[test]
1858 fn make_glob_prefix_only_no_suffix() {
1859 let pattern = fallow_types::extract::DynamicImportPattern {
1860 prefix: "./locales/".to_string(),
1861 suffix: None,
1862 span: oxc_span::Span::default(),
1863 };
1864 assert_eq!(make_glob_from_pattern(&pattern), "./locales/*");
1865 }
1866
1867 #[test]
1868 fn make_glob_prefix_with_suffix() {
1869 let pattern = fallow_types::extract::DynamicImportPattern {
1870 prefix: "./locales/".to_string(),
1871 suffix: Some(".json".to_string()),
1872 span: oxc_span::Span::default(),
1873 };
1874 assert_eq!(make_glob_from_pattern(&pattern), "./locales/*.json");
1875 }
1876
1877 #[test]
1878 fn make_glob_passthrough_star() {
1879 let pattern = fallow_types::extract::DynamicImportPattern {
1880 prefix: "./pages/**/*.tsx".to_string(),
1881 suffix: None,
1882 span: oxc_span::Span::default(),
1883 };
1884 assert_eq!(make_glob_from_pattern(&pattern), "./pages/**/*.tsx");
1885 }
1886
1887 #[test]
1888 fn make_glob_passthrough_brace() {
1889 let pattern = fallow_types::extract::DynamicImportPattern {
1890 prefix: "./i18n/{en,de,fr}.json".to_string(),
1891 suffix: None,
1892 span: oxc_span::Span::default(),
1893 };
1894 assert_eq!(make_glob_from_pattern(&pattern), "./i18n/{en,de,fr}.json");
1895 }
1896
1897 #[test]
1898 fn make_glob_empty_prefix_no_suffix() {
1899 let pattern = fallow_types::extract::DynamicImportPattern {
1900 prefix: String::new(),
1901 suffix: None,
1902 span: oxc_span::Span::default(),
1903 };
1904 assert_eq!(make_glob_from_pattern(&pattern), "*");
1905 }
1906
1907 #[test]
1908 fn make_glob_empty_prefix_with_suffix() {
1909 let pattern = fallow_types::extract::DynamicImportPattern {
1910 prefix: String::new(),
1911 suffix: Some(".ts".to_string()),
1912 span: oxc_span::Span::default(),
1913 };
1914 assert_eq!(make_glob_from_pattern(&pattern), "*.ts");
1915 }
1916
1917 #[test]
1918 fn make_glob_template_literal_prefix_only() {
1919 let pattern = fallow_types::extract::DynamicImportPattern {
1920 prefix: "./pages/".to_string(),
1921 suffix: None,
1922 span: oxc_span::Span::default(),
1923 };
1924 assert_eq!(make_glob_from_pattern(&pattern), "./pages/*");
1925 }
1926
1927 #[test]
1928 fn make_glob_template_literal_with_extension_suffix() {
1929 let pattern = fallow_types::extract::DynamicImportPattern {
1930 prefix: "./locales/".to_string(),
1931 suffix: Some(".json".to_string()),
1932 span: oxc_span::Span::default(),
1933 };
1934 assert_eq!(make_glob_from_pattern(&pattern), "./locales/*.json");
1935 }
1936
1937 #[test]
1938 fn make_glob_template_literal_deep_prefix() {
1939 let pattern = fallow_types::extract::DynamicImportPattern {
1940 prefix: "./modules/".to_string(),
1941 suffix: None,
1942 span: oxc_span::Span::default(),
1943 };
1944 assert_eq!(make_glob_from_pattern(&pattern), "./modules/*");
1945 }
1946
1947 #[test]
1948 fn make_glob_string_concat_prefix() {
1949 let pattern = fallow_types::extract::DynamicImportPattern {
1950 prefix: "./pages/".to_string(),
1951 suffix: None,
1952 span: oxc_span::Span::default(),
1953 };
1954 assert_eq!(make_glob_from_pattern(&pattern), "./pages/*");
1955 }
1956
1957 #[test]
1958 fn make_glob_string_concat_with_extension() {
1959 let pattern = fallow_types::extract::DynamicImportPattern {
1960 prefix: "./views/".to_string(),
1961 suffix: Some(".vue".to_string()),
1962 span: oxc_span::Span::default(),
1963 };
1964 assert_eq!(make_glob_from_pattern(&pattern), "./views/*.vue");
1965 }
1966
1967 #[test]
1968 fn make_glob_import_meta_glob_recursive() {
1969 let pattern = fallow_types::extract::DynamicImportPattern {
1970 prefix: "./components/**/*.vue".to_string(),
1971 suffix: None,
1972 span: oxc_span::Span::default(),
1973 };
1974 assert_eq!(
1975 make_glob_from_pattern(&pattern),
1976 "./components/**/*.vue",
1977 "import.meta.glob patterns with * should pass through as-is"
1978 );
1979 }
1980
1981 #[test]
1982 fn make_glob_import_meta_glob_brace_expansion() {
1983 let pattern = fallow_types::extract::DynamicImportPattern {
1984 prefix: "./plugins/{auth,analytics}.ts".to_string(),
1985 suffix: None,
1986 span: oxc_span::Span::default(),
1987 };
1988 assert_eq!(
1989 make_glob_from_pattern(&pattern),
1990 "./plugins/{auth,analytics}.ts",
1991 "import.meta.glob patterns with braces should pass through as-is"
1992 );
1993 }
1994
1995 #[test]
1996 fn make_glob_import_meta_glob_star_with_brace() {
1997 let pattern = fallow_types::extract::DynamicImportPattern {
1998 prefix: "./routes/**/*.{ts,tsx}".to_string(),
1999 suffix: None,
2000 span: oxc_span::Span::default(),
2001 };
2002 assert_eq!(
2003 make_glob_from_pattern(&pattern),
2004 "./routes/**/*.{ts,tsx}",
2005 "combined * and brace patterns should pass through"
2006 );
2007 }
2008
2009 #[test]
2010 fn make_glob_import_meta_glob_ignores_suffix_when_star_present() {
2011 let pattern = fallow_types::extract::DynamicImportPattern {
2012 prefix: "./*.ts".to_string(),
2013 suffix: Some(".extra".to_string()),
2014 span: oxc_span::Span::default(),
2015 };
2016 assert_eq!(
2017 make_glob_from_pattern(&pattern),
2018 "./*.ts",
2019 "when prefix has glob chars, suffix is ignored (prefix used as-is)"
2020 );
2021 }
2022
2023 #[test]
2024 fn make_glob_single_dot_prefix() {
2025 let pattern = fallow_types::extract::DynamicImportPattern {
2026 prefix: "./".to_string(),
2027 suffix: None,
2028 span: oxc_span::Span::default(),
2029 };
2030 assert_eq!(make_glob_from_pattern(&pattern), "./*");
2031 }
2032
2033 #[test]
2034 fn make_glob_prefix_without_trailing_slash() {
2035 let pattern = fallow_types::extract::DynamicImportPattern {
2036 prefix: "./config".to_string(),
2037 suffix: None,
2038 span: oxc_span::Span::default(),
2039 };
2040 assert_eq!(make_glob_from_pattern(&pattern), "./config*");
2041 }
2042
2043 #[test]
2044 fn make_glob_prefix_with_dotdot() {
2045 let pattern = fallow_types::extract::DynamicImportPattern {
2046 prefix: "../shared/".to_string(),
2047 suffix: Some(".ts".to_string()),
2048 span: oxc_span::Span::default(),
2049 };
2050 assert_eq!(make_glob_from_pattern(&pattern), "../shared/*.ts");
2051 }
2052
2053 #[test]
2054 fn test_extract_package_name_with_pnpm_plus_encoded_scope() {
2055 let path = PathBuf::from(
2056 "/project/node_modules/.pnpm/@mui+material@5.15.0/node_modules/@mui/material/index.js",
2057 );
2058 assert_eq!(
2059 extract_package_name_from_node_modules_path(&path),
2060 Some("@mui/material".to_string())
2061 );
2062 }
2063
2064 #[test]
2065 fn test_extract_package_name_windows_style_path() {
2066 let path = PathBuf::from("/project/node_modules/typescript/lib/tsc.js");
2067 assert_eq!(
2068 extract_package_name_from_node_modules_path(&path),
2069 Some("typescript".to_string())
2070 );
2071 }
2072
2073 #[test]
2074 fn test_try_source_fallback_out_dir() {
2075 let src_path = PathBuf::from("/project/packages/api/src/handler.ts");
2076 let mut path_to_id = FxHashMap::default();
2077 path_to_id.insert(src_path.as_path(), FileId(5));
2078
2079 let out_path = PathBuf::from("/project/packages/api/out/handler.js");
2080 assert_eq!(
2081 try_source_fallback(&out_path, &path_to_id),
2082 Some(FileId(5)),
2083 "out/handler.js should fall back to src/handler.ts"
2084 );
2085 }
2086
2087 #[test]
2088 fn test_try_source_fallback_mts_extension() {
2089 let src_path = PathBuf::from("/project/packages/lib/src/utils.mts");
2090 let mut path_to_id = FxHashMap::default();
2091 path_to_id.insert(src_path.as_path(), FileId(6));
2092
2093 let dist_path = PathBuf::from("/project/packages/lib/dist/utils.mjs");
2094 assert_eq!(
2095 try_source_fallback(&dist_path, &path_to_id),
2096 Some(FileId(6)),
2097 "dist/utils.mjs should fall back to src/utils.mts"
2098 );
2099 }
2100
2101 #[test]
2102 fn test_try_source_fallback_cts_extension() {
2103 let src_path = PathBuf::from("/project/packages/lib/src/config.cts");
2104 let mut path_to_id = FxHashMap::default();
2105 path_to_id.insert(src_path.as_path(), FileId(7));
2106
2107 let dist_path = PathBuf::from("/project/packages/lib/dist/config.cjs");
2108 assert_eq!(
2109 try_source_fallback(&dist_path, &path_to_id),
2110 Some(FileId(7)),
2111 "dist/config.cjs should fall back to src/config.cts"
2112 );
2113 }
2114
2115 #[test]
2116 fn test_try_source_fallback_jsx_extension() {
2117 let src_path = PathBuf::from("/project/packages/ui/src/App.jsx");
2118 let mut path_to_id = FxHashMap::default();
2119 path_to_id.insert(src_path.as_path(), FileId(8));
2120
2121 let build_path = PathBuf::from("/project/packages/ui/build/App.js");
2122 assert_eq!(
2123 try_source_fallback(&build_path, &path_to_id),
2124 Some(FileId(8)),
2125 "build/App.js should fall back to src/App.jsx"
2126 );
2127 }
2128
2129 #[test]
2130 fn test_try_source_fallback_no_file_stem() {
2131 let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
2132 let dist_path = PathBuf::from("/project/packages/ui/dist/");
2133 assert_eq!(
2134 try_source_fallback(&dist_path, &path_to_id),
2135 None,
2136 "directory path with no file should return None"
2137 );
2138 }
2139
2140 #[test]
2141 fn test_try_source_fallback_esm_subdir() {
2142 let src_path = PathBuf::from("/project/lib/src/index.ts");
2143 let mut path_to_id = FxHashMap::default();
2144 path_to_id.insert(src_path.as_path(), FileId(10));
2145
2146 let dist_path = PathBuf::from("/project/lib/esm/index.mjs");
2147 assert_eq!(
2148 try_source_fallback(&dist_path, &path_to_id),
2149 Some(FileId(10)),
2150 "standalone esm/ directory should fall back to src/"
2151 );
2152 }
2153
2154 #[test]
2155 fn test_try_source_fallback_cjs_subdir() {
2156 let src_path = PathBuf::from("/project/lib/src/index.ts");
2157 let mut path_to_id = FxHashMap::default();
2158 path_to_id.insert(src_path.as_path(), FileId(11));
2159
2160 let cjs_path = PathBuf::from("/project/lib/cjs/index.cjs");
2161 assert_eq!(
2162 try_source_fallback(&cjs_path, &path_to_id),
2163 Some(FileId(11)),
2164 "standalone cjs/ directory should fall back to src/"
2165 );
2166 }
2167
2168 #[test]
2169 fn test_try_pnpm_workspace_fallback_empty_after_pnpm() {
2170 let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
2171 let workspace_roots: FxHashMap<&str, &Path> = FxHashMap::default();
2172
2173 let pnpm_path = PathBuf::from("/project/node_modules/.pnpm/pkg@1.0.0/node_modules");
2174 assert_eq!(
2175 try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
2176 None,
2177 "path ending at node_modules with nothing after should return None"
2178 );
2179 }
2180
2181 #[test]
2182 fn test_try_pnpm_workspace_fallback_scoped_package_only_scope() {
2183 let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
2184 let workspace_roots: FxHashMap<&str, &Path> = FxHashMap::default();
2185
2186 let pnpm_path =
2187 PathBuf::from("/project/node_modules/.pnpm/@scope+pkg@1.0.0/node_modules/@scope");
2188 assert_eq!(
2189 try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
2190 None,
2191 "scoped package without full name and no matching workspace should return None"
2192 );
2193 }
2194
2195 #[test]
2196 fn test_try_pnpm_workspace_fallback_no_inner_node_modules() {
2197 let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
2198 let workspace_roots: FxHashMap<&str, &Path> = FxHashMap::default();
2199
2200 let pnpm_path = PathBuf::from("/project/node_modules/.pnpm/pkg@1.0.0/dist/index.js");
2201 assert_eq!(
2202 try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
2203 None,
2204 "path without inner node_modules after .pnpm should return None"
2205 );
2206 }
2207
2208 #[test]
2209 fn test_try_pnpm_workspace_fallback_package_without_relative_path() {
2210 let path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
2211 let mut workspace_roots = FxHashMap::default();
2212 let ws_root = PathBuf::from("/project/packages/ui");
2213 workspace_roots.insert("@myorg/ui", ws_root.as_path());
2214
2215 let pnpm_path =
2216 PathBuf::from("/project/node_modules/.pnpm/@myorg+ui@1.0.0/node_modules/@myorg/ui");
2217 assert_eq!(
2218 try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
2219 None,
2220 "path ending at package name with no relative file should return None"
2221 );
2222 }
2223
2224 #[test]
2225 fn test_try_pnpm_workspace_fallback_nested_dist_esm() {
2226 let src_path = PathBuf::from("/project/packages/ui/src/Button.ts");
2227 let mut path_to_id = FxHashMap::default();
2228 path_to_id.insert(src_path.as_path(), FileId(10));
2229
2230 let mut workspace_roots = FxHashMap::default();
2231 let ws_root = PathBuf::from("/project/packages/ui");
2232 workspace_roots.insert("@myorg/ui", ws_root.as_path());
2233
2234 let pnpm_path = PathBuf::from(
2235 "/project/node_modules/.pnpm/@myorg+ui@1.0.0/node_modules/@myorg/ui/dist/esm/Button.mjs",
2236 );
2237 assert_eq!(
2238 try_pnpm_workspace_fallback(&pnpm_path, &path_to_id, &workspace_roots),
2239 Some(FileId(10)),
2240 "pnpm path with nested dist/esm should resolve through source fallback"
2241 );
2242 }
2243
2244 #[test]
2247 fn package_map_target_string_value_dot_key() {
2248 let map = serde_json::Value::String("./src/index.ts".to_string());
2251 let conds = conditions();
2252 let result = package_map_target(&map, ".", &conds);
2254 assert!(
2255 matches!(result, PackageMapTarget::Targets(_)),
2256 "string map with '.' key should return Targets"
2257 );
2258 }
2259
2260 #[test]
2261 fn package_map_target_string_value_non_dot_key_no_match() {
2262 let map = serde_json::Value::String("./src/index.ts".to_string());
2264 let conds = conditions();
2265 let result = package_map_target(&map, "./sub", &conds);
2266 assert!(
2267 matches!(result, PackageMapTarget::NoMatch),
2268 "string map with non-dot key should return NoMatch"
2269 );
2270 }
2271
2272 #[test]
2273 fn package_map_target_null_value_dot_key() {
2274 let map = serde_json::Value::Null;
2276 let conds = conditions();
2277 let result = package_map_target(&map, ".", &conds);
2278 assert!(
2279 matches!(result, PackageMapTarget::Blocked),
2280 "null map with '.' key should return Blocked"
2281 );
2282 }
2283
2284 #[test]
2285 fn package_map_target_bool_value_non_dot_key() {
2286 let map = serde_json::Value::Bool(true);
2288 let conds = conditions();
2289 let result = package_map_target(&map, "./sub", &conds);
2290 assert!(
2291 matches!(result, PackageMapTarget::NoMatch),
2292 "bool map with non-dot key should return NoMatch"
2293 );
2294 }
2295
2296 #[test]
2299 fn package_map_target_condition_only_object_dot_key() {
2300 let map = serde_json::json!({
2303 "import": "./src/index.mjs",
2304 "require": "./src/index.cjs"
2305 });
2306 let conds = conditions();
2307 let result = package_map_target(&map, ".", &conds);
2308 assert!(
2309 matches!(result, PackageMapTarget::Targets(_)),
2310 "condition-only object with '.' key should return Targets"
2311 );
2312 }
2313
2314 #[test]
2315 fn package_map_target_condition_only_object_non_dot_key() {
2316 let map = serde_json::json!({
2319 "import": "./src/index.mjs",
2320 "require": "./src/index.cjs"
2321 });
2322 let conds = conditions();
2323 let result = package_map_target(&map, "./nonexistent", &conds);
2324 assert!(
2325 matches!(result, PackageMapTarget::NoMatch),
2326 "condition-only object with non-dot key should return NoMatch"
2327 );
2328 }
2329
2330 #[test]
2333 fn resolve_package_map_value_unmatched_conditions_returns_none() {
2334 let value = serde_json::json!({ "browser": "./src/browser.js" });
2336 let conds = conditions(); assert_eq!(
2338 resolve_package_map_value(&value, &conds, None),
2339 None,
2340 "unmatched condition should return None"
2341 );
2342 }
2343
2344 #[test]
2345 fn resolve_package_map_value_bool_returns_none() {
2346 let value = serde_json::Value::Bool(false);
2347 let conds = conditions();
2348 assert_eq!(
2349 resolve_package_map_value(&value, &conds, None),
2350 None,
2351 "bool value should return None"
2352 );
2353 }
2354
2355 #[test]
2356 fn resolve_package_map_value_number_returns_none() {
2357 let value = serde_json::Value::Number(42.into());
2358 let conds = conditions();
2359 assert_eq!(
2360 resolve_package_map_value(&value, &conds, None),
2361 None,
2362 "number value should return None"
2363 );
2364 }
2365
2366 #[test]
2367 fn resolve_package_map_value_null_returns_none() {
2368 let value = serde_json::Value::Null;
2369 let conds = conditions();
2370 assert_eq!(
2371 resolve_package_map_value(&value, &conds, None),
2372 None,
2373 "null value should return None"
2374 );
2375 }
2376
2377 #[test]
2378 fn resolve_package_map_value_array_all_null_returns_none() {
2379 let value = serde_json::json!([null, false, 42]);
2381 let conds = conditions();
2382 assert_eq!(
2383 resolve_package_map_value(&value, &conds, None),
2384 None,
2385 "array of unresolvable values should return None"
2386 );
2387 }
2388
2389 #[test]
2390 fn resolve_package_map_value_array_with_valid_entry() {
2391 let value = serde_json::json!([null, "./src/index.ts"]);
2393 let conds = conditions();
2394 let result = resolve_package_map_value(&value, &conds, None);
2395 assert_eq!(
2396 result,
2397 Some(vec!["./src/index.ts".to_string()]),
2398 "array with a valid string entry should return that entry"
2399 );
2400 }
2401
2402 #[test]
2405 fn package_map_pattern_capture_no_star_returns_none() {
2406 assert_eq!(
2408 package_map_pattern_capture("./exact", "./exact"),
2409 None,
2410 "pattern with no star should return None"
2411 );
2412 }
2413
2414 #[test]
2415 fn package_map_pattern_capture_two_stars_returns_none() {
2416 assert_eq!(
2418 package_map_pattern_capture("./*/*.js", "./foo/bar.js"),
2419 None,
2420 "pattern with two stars should return None"
2421 );
2422 }
2423
2424 #[test]
2425 fn package_map_pattern_capture_single_star_captures() {
2426 assert_eq!(
2428 package_map_pattern_capture("./dist/*/index.js", "./dist/utils/index.js"),
2429 Some("utils".to_string()),
2430 );
2431 }
2432
2433 #[test]
2434 fn package_map_pattern_capture_no_prefix_match_returns_none() {
2435 assert_eq!(
2437 package_map_pattern_capture("./lib/*.js", "./src/foo.js"),
2438 None,
2439 );
2440 }
2441
2442 #[test]
2445 fn resolve_package_map_target_no_dot_slash_prefix_returns_none() {
2446 let root = PathBuf::from("/project/packages/ui");
2448 let pj = fallow_config::PackageJson::default();
2449 with_package_map_ctx(root, Some("@myorg/ui"), pj, &[], |ctx, manifest, _root| {
2450 let result = resolve_package_map_target(ctx, manifest, "src/index.ts", None);
2451 assert_eq!(result, None, "target without './' should return None");
2452 });
2453 }
2454
2455 #[test]
2456 fn resolve_package_map_target_parent_dir_returns_none() {
2457 let root = PathBuf::from("/project/packages/ui");
2459 let pj = fallow_config::PackageJson::default();
2460 with_package_map_ctx(root, Some("@myorg/ui"), pj, &[], |ctx, manifest, _root| {
2461 let result = resolve_package_map_target(ctx, manifest, "./../outside/file.ts", None);
2462 assert_eq!(result, None, "parent-dir target should return None");
2463 });
2464 }
2465
2466 #[test]
2467 fn resolve_package_map_target_absolute_path_returns_none() {
2468 let root = PathBuf::from("/project/packages/ui");
2470 let pj = fallow_config::PackageJson::default();
2471 with_package_map_ctx(root, Some("@myorg/ui"), pj, &[], |ctx, manifest, _root| {
2472 let result = resolve_package_map_target(ctx, manifest, ".//abs/path.ts", None);
2475 assert_eq!(result, None, "absolute target should return None");
2476 });
2477 }
2478
2479 #[test]
2480 fn resolve_package_map_target_valid_target_hits_raw_path_map() {
2481 let root = PathBuf::from("/project/packages/ui");
2483 let src = root.join("src/index.ts");
2484 let pj = fallow_config::PackageJson::default();
2485 with_package_map_ctx(
2486 root,
2487 Some("@myorg/ui"),
2488 pj,
2489 &[(src, FileId(5))],
2490 |ctx, manifest, _root| {
2491 let result = resolve_package_map_target(ctx, manifest, "./src/index.ts", None);
2492 assert_eq!(
2493 result,
2494 Some(FileId(5)),
2495 "valid target in raw_path_to_id should resolve"
2496 );
2497 },
2498 );
2499 }
2500
2501 #[test]
2504 fn package_import_source_subpath_strips_hash_and_package_name() {
2505 let manifest = PackageManifestInfo {
2506 root: PathBuf::from("/project"),
2507 canonical_root: PathBuf::from("/project"),
2508 name: Some("my-pkg".to_string()),
2509 package_json: fallow_config::PackageJson::default(),
2510 };
2511 let result = package_import_source_subpath(&manifest, "#my-pkg/utils");
2512 assert_eq!(
2513 result,
2514 Some(PathBuf::from("utils")),
2515 "should strip '#', package name, and '/' separator"
2516 );
2517 }
2518
2519 #[test]
2520 fn package_import_source_subpath_no_package_name_match_keeps_full_subpath() {
2521 let manifest = PackageManifestInfo {
2524 root: PathBuf::from("/project"),
2525 canonical_root: PathBuf::from("/project"),
2526 name: Some("my-pkg".to_string()),
2527 package_json: fallow_config::PackageJson::default(),
2528 };
2529 let result = package_import_source_subpath(&manifest, "#utils");
2530 assert_eq!(
2531 result,
2532 Some(PathBuf::from("utils")),
2533 "without package-name prefix the full subpath should be kept"
2534 );
2535 }
2536
2537 #[test]
2538 fn package_import_source_subpath_empty_hash_returns_none() {
2539 let manifest = PackageManifestInfo {
2542 root: PathBuf::from("/project"),
2543 canonical_root: PathBuf::from("/project"),
2544 name: Some("my-pkg".to_string()),
2545 package_json: fallow_config::PackageJson::default(),
2546 };
2547 let result = package_import_source_subpath(&manifest, "#");
2549 assert_eq!(
2550 result, None,
2551 "specifier '#' with empty body should return None"
2552 );
2553 }
2554
2555 #[test]
2556 fn package_import_source_subpath_no_hash_returns_none() {
2557 let manifest = PackageManifestInfo {
2559 root: PathBuf::from("/project"),
2560 canonical_root: PathBuf::from("/project"),
2561 name: Some("my-pkg".to_string()),
2562 package_json: fallow_config::PackageJson::default(),
2563 };
2564 let result = package_import_source_subpath(&manifest, "no-hash");
2565 assert_eq!(result, None, "specifier without '#' should return None");
2566 }
2567
2568 #[test]
2569 fn package_import_source_subpath_no_manifest_name() {
2570 let manifest = PackageManifestInfo {
2572 root: PathBuf::from("/project"),
2573 canonical_root: PathBuf::from("/project"),
2574 name: None,
2575 package_json: fallow_config::PackageJson::default(),
2576 };
2577 let result = package_import_source_subpath(&manifest, "#internal/helper");
2578 assert_eq!(
2579 result,
2580 Some(PathBuf::from("internal/helper")),
2581 "manifest without name should return the full stripped specifier"
2582 );
2583 }
2584
2585 #[test]
2588 fn nearest_package_manifest_returns_deepest_match() {
2589 let root1 = PathBuf::from("/project");
2590 let root2 = PathBuf::from("/project/packages/ui");
2591 let m1 = PackageManifestInfo {
2592 root: root1.clone(),
2593 canonical_root: root1,
2594 name: Some("root".to_string()),
2595 package_json: fallow_config::PackageJson::default(),
2596 };
2597 let m2 = PackageManifestInfo {
2598 root: root2.clone(),
2599 canonical_root: root2,
2600 name: Some("@myorg/ui".to_string()),
2601 package_json: fallow_config::PackageJson::default(),
2602 };
2603 let manifests = [m1, m2];
2604 let from_file = Path::new("/project/packages/ui/src/index.ts");
2605 let result = nearest_package_manifest(&manifests, from_file);
2606 assert_eq!(
2607 result.and_then(|m| m.name.as_deref()),
2608 Some("@myorg/ui"),
2609 "should pick the deepest (longest path) manifest that contains the file"
2610 );
2611 }
2612
2613 #[test]
2614 fn nearest_package_manifest_no_match_returns_none() {
2615 let root = PathBuf::from("/project/packages/ui");
2616 let m = PackageManifestInfo {
2617 root: root.clone(),
2618 canonical_root: root,
2619 name: Some("@myorg/ui".to_string()),
2620 package_json: fallow_config::PackageJson::default(),
2621 };
2622 let manifests = [m];
2623 let from_file = Path::new("/other/project/src/index.ts");
2625 let result = nearest_package_manifest(&manifests, from_file);
2626 assert!(
2627 result.is_none(),
2628 "file outside all manifest roots should return None"
2629 );
2630 }
2631
2632 #[test]
2635 fn lookup_internal_file_id_uses_path_to_id_when_raw_misses() {
2636 let target = PathBuf::from("/project/src/index.ts");
2639 let mut path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
2640 path_to_id.insert(target.as_path(), FileId(99));
2641 let raw_path_to_id: FxHashMap<&Path, FileId> = FxHashMap::default();
2642 let workspace_roots: FxHashMap<&str, &Path> = FxHashMap::default();
2643 let condition_names = conditions();
2644 let resolver = oxc_resolver::Resolver::new(oxc_resolver::ResolveOptions::default());
2645 let tsconfig_warned = std::sync::Mutex::new(FxHashSet::default());
2646 let tsconfig_cache = TsconfigCache::default();
2647 let canonicalize_cache = CanonicalizeCache::default();
2648 let root = PathBuf::from("/project");
2649 let ctx = ResolveContext {
2650 resolver: &resolver,
2651 style_resolver: &resolver,
2652 extensions: &[],
2653 path_to_id: &path_to_id,
2654 raw_path_to_id: &raw_path_to_id,
2655 workspace_roots: &workspace_roots,
2656 package_manifests: &[],
2657 condition_names: &condition_names,
2658 path_aliases: &[],
2659 scss_include_paths: &[],
2660 static_dir_mappings: &[],
2661 root: &root,
2662 canonical_fallback: None,
2663 tsconfig_warned: &tsconfig_warned,
2664 tsconfig_cache: &tsconfig_cache,
2665 canonicalize_cache: &canonicalize_cache,
2666 };
2667 let result = lookup_internal_file_id(&ctx, &target);
2668 assert_eq!(
2669 result,
2670 Some(FileId(99)),
2671 "should fall back from raw_path_to_id to path_to_id"
2672 );
2673 }
2674
2675 #[test]
2678 fn try_scss_partial_fallback_rejects_colon_specifier() {
2679 let root = PathBuf::from("/project");
2682 let pj = fallow_config::PackageJson::default();
2683 with_package_map_ctx(root.clone(), None, pj, &[], |ctx, _manifest, _r| {
2684 let from_file = root.join("src/main.scss");
2685 let result = try_scss_partial_fallback(ctx, &from_file, "sass:math");
2686 assert!(
2687 result.is_none(),
2688 "specifier with ':' should short-circuit to None"
2689 );
2690 });
2691 }
2692
2693 #[test]
2694 fn try_scss_partial_fallback_rejects_already_partial_filename() {
2695 let root = PathBuf::from("/project");
2698 let pj = fallow_config::PackageJson::default();
2699 with_package_map_ctx(root.clone(), None, pj, &[], |ctx, _manifest, _r| {
2700 let from_file = root.join("src/main.scss");
2701 let result = try_scss_partial_fallback(ctx, &from_file, "./_variables");
2702 assert!(
2703 result.is_none(),
2704 "already-partial filename should short-circuit to None"
2705 );
2706 });
2707 }
2708
2709 #[test]
2712 fn try_workspace_package_fallback_rejects_relative_specifier() {
2713 let root = PathBuf::from("/project");
2716 let pj = fallow_config::PackageJson::default();
2717 with_package_map_ctx(root, None, pj, &[], |ctx, _manifest, _r| {
2718 let result = try_workspace_package_fallback(ctx, "./local/module");
2719 assert!(
2720 result.is_none(),
2721 "relative specifier should return None from workspace fallback"
2722 );
2723 });
2724 }
2725
2726 #[test]
2727 fn try_workspace_package_fallback_rejects_absolute_path() {
2728 let root = PathBuf::from("/project");
2730 let pj = fallow_config::PackageJson::default();
2731 with_package_map_ctx(root, None, pj, &[], |ctx, _manifest, _r| {
2732 let result = try_workspace_package_fallback(ctx, "/absolute/path");
2733 assert!(
2734 result.is_none(),
2735 "absolute path should return None from workspace fallback"
2736 );
2737 });
2738 }
2739}