1use std::path::Path;
4
5use oxc_resolver::ResolveOptions;
6use rustc_hash::FxHashMap;
7
8use super::types::{RN_PLATFORM_PREFIXES, ResolveResult, ResolvedImport, ResolvedModule};
9use fallow_types::discover::{DiscoveredFile, FileId};
10use fallow_types::extract::{ImportInfo, ImportedName};
11
12pub fn has_react_native_plugin(active_plugins: &[String]) -> bool {
15 active_plugins
16 .iter()
17 .any(|p| p == "react-native" || p == "expo")
18}
19
20const RN_SOURCE_EXTS: &[&str] = &[".ts", ".tsx", ".js", ".jsx"];
22
23fn split_source_ext(name: &str) -> (&str, Option<&str>) {
26 for ext in RN_SOURCE_EXTS {
27 if let Some(stem) = name.strip_suffix(ext) {
28 return (stem, Some(ext));
29 }
30 }
31 (name, None)
32}
33
34fn strip_platform_segment(stem: &str) -> (&str, bool) {
37 for platform in RN_PLATFORM_PREFIXES {
38 if let Some(base) = stem.strip_suffix(platform) {
39 return (base, true);
40 }
41 }
42 (stem, false)
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub struct PlatformFamilyKey<'a> {
50 pub parent: &'a Path,
52 pub base: &'a str,
54 pub is_platform_variant: bool,
56}
57
58pub fn platform_family_key(path: &Path) -> Option<PlatformFamilyKey<'_>> {
65 let name = path.file_name()?.to_str()?;
66 let (stem, ext) = split_source_ext(name);
67 ext?;
68 let (base, is_platform_variant) = strip_platform_segment(stem);
69 if base.is_empty() {
70 return None;
71 }
72 let parent = path.parent()?;
73 Some(PlatformFamilyKey {
74 parent,
75 base,
76 is_platform_variant,
77 })
78}
79
80fn specifier_names_platform_variant(specifier: &str) -> bool {
84 let basename = specifier.rsplit('/').next().unwrap_or(specifier);
85 let (stem, _) = split_source_ext(basename);
86 strip_platform_segment(stem).1
87}
88
89struct PlatformFamilies {
94 family_of: FxHashMap<FileId, usize>,
95 members: Vec<Vec<FileId>>,
96}
97
98impl PlatformFamilies {
99 fn build(files: &[DiscoveredFile]) -> Self {
100 let mut grouped: FxHashMap<(&Path, &str), Vec<(FileId, bool)>> = FxHashMap::default();
101 for file in files {
102 let Some(key) = platform_family_key(&file.path) else {
103 continue;
104 };
105 grouped
106 .entry((key.parent, key.base))
107 .or_default()
108 .push((file.id, key.is_platform_variant));
109 }
110
111 let mut family_of = FxHashMap::default();
112 let mut members = Vec::new();
113 for group in grouped.into_values() {
114 if group.len() < 2 || !group.iter().any(|(_, is_platform)| *is_platform) {
115 continue;
116 }
117 let mut ids: Vec<FileId> = group.into_iter().map(|(id, _)| id).collect();
118 ids.sort_unstable_by_key(|id| id.0);
119 let index = members.len();
120 for id in &ids {
121 family_of.insert(*id, index);
122 }
123 members.push(ids);
124 }
125 Self { family_of, members }
126 }
127
128 fn siblings(&self, target: FileId) -> Option<&[FileId]> {
129 self.family_of
130 .get(&target)
131 .map(|index| self.members[*index].as_slice())
132 }
133}
134
135pub(super) fn retarget(result: &ResolveResult, sibling: FileId) -> Option<ResolveResult> {
138 match result {
139 ResolveResult::InternalModule(_) => Some(ResolveResult::InternalModule(sibling)),
140 ResolveResult::CommonJsInternalModule(_) => {
141 Some(ResolveResult::CommonJsInternalModule(sibling))
142 }
143 ResolveResult::SyntheticAutoImport(_) => Some(ResolveResult::SyntheticAutoImport(sibling)),
144 ResolveResult::InternalPackageModule { package_name, .. } => {
145 Some(ResolveResult::InternalPackageModule {
146 file_id: sibling,
147 package_name: package_name.clone(),
148 })
149 }
150 ResolveResult::CommonJsInternalPackageModule { package_name, .. } => {
151 Some(ResolveResult::CommonJsInternalPackageModule {
152 file_id: sibling,
153 package_name: package_name.clone(),
154 })
155 }
156 ResolveResult::ExternalFile(_)
157 | ResolveResult::NpmPackage(_)
158 | ResolveResult::CommonJsNpmPackage(_)
159 | ResolveResult::Unresolvable(_) => None,
160 }
161}
162
163fn expand_family_imports(
166 importer: FileId,
167 imports: &[ResolvedImport],
168 families: &PlatformFamilies,
169 extra: &mut Vec<ResolvedImport>,
170) {
171 for import in imports {
172 if specifier_names_platform_variant(&import.info.source) {
173 continue;
174 }
175 let Some(target) = import.target.internal_file_id() else {
176 continue;
177 };
178 let Some(siblings) = families.siblings(target) else {
179 continue;
180 };
181 for sibling in siblings {
182 if *sibling == target || *sibling == importer {
183 continue;
184 }
185 if let Some(retargeted) = retarget(&import.target, *sibling) {
186 extra.push(ResolvedImport {
187 info: import.info.clone(),
188 target: retargeted,
189 });
190 }
191 }
192 }
193}
194
195pub(super) fn synthesize_platform_family_edges(
207 resolved: &mut [ResolvedModule],
208 files: &[DiscoveredFile],
209 active_plugins: &[String],
210) {
211 if !has_react_native_plugin(active_plugins) {
212 return;
213 }
214 let families = PlatformFamilies::build(files);
215 if families.members.is_empty() {
216 return;
217 }
218
219 for module in resolved.iter_mut() {
220 let mut extra = Vec::new();
221 expand_family_imports(
222 module.file_id,
223 &module.resolved_imports,
224 &families,
225 &mut extra,
226 );
227 expand_family_imports(
228 module.file_id,
229 &module.resolved_dynamic_imports,
230 &families,
231 &mut extra,
232 );
233
234 for re_export in &module.re_exports {
235 if specifier_names_platform_variant(&re_export.info.source) {
236 continue;
237 }
238 let Some(target) = re_export.target.internal_file_id() else {
239 continue;
240 };
241 let Some(siblings) = families.siblings(target) else {
242 continue;
243 };
244 for sibling in siblings {
245 if *sibling == target || *sibling == module.file_id {
246 continue;
247 }
248 extra.push(ResolvedImport {
251 info: ImportInfo {
252 source: re_export.info.source.clone(),
253 imported_name: ImportedName::SideEffect,
254 local_name: String::new(),
255 is_type_only: re_export.info.is_type_only,
256 is_type_only_star: false,
257 from_style: false,
258 span: oxc_span::Span::default(),
259 source_span: oxc_span::Span::default(),
260 },
261 target: ResolveResult::InternalModule(*sibling),
262 });
263 }
264 }
265
266 module.resolved_imports.extend(extra);
267 }
268}
269
270pub(super) fn may_be_platform_self_resolution(
277 from_file: &Path,
278 specifier: &str,
279 resolved: &Path,
280) -> bool {
281 resolved.file_name() == from_file.file_name()
282 && platform_family_key(resolved).is_some_and(|key| key.is_platform_variant)
283 && !specifier_names_platform_variant(specifier)
284}
285
286pub(super) fn without_platform_extensions(mut options: ResolveOptions) -> ResolveOptions {
292 options.extensions.retain(|extension| {
293 !RN_PLATFORM_PREFIXES
294 .iter()
295 .any(|platform| extension.starts_with(platform))
296 });
297 options
298}
299
300pub(super) fn build_extensions(active_plugins: &[String]) -> Vec<String> {
303 let base: Vec<String> = vec![
304 ".ts".into(),
305 ".tsx".into(),
306 ".mts".into(),
307 ".cts".into(),
308 ".gts".into(),
309 ".js".into(),
310 ".jsx".into(),
311 ".mjs".into(),
312 ".cjs".into(),
313 ".gjs".into(),
314 ".d.ts".into(),
315 ".d.mts".into(),
316 ".d.cts".into(),
317 ".json".into(),
318 ".vue".into(),
319 ".svelte".into(),
320 ".astro".into(),
321 ".mdx".into(),
322 ".css".into(),
323 ".scss".into(),
324 ".graphql".into(),
325 ".gql".into(),
326 ];
327
328 if has_react_native_plugin(active_plugins) {
329 let source_exts = [".ts", ".tsx", ".js", ".jsx"];
330 let mut rn_extensions: Vec<String> = Vec::new();
331 for platform in RN_PLATFORM_PREFIXES {
332 for ext in &source_exts {
333 rn_extensions.push(format!("{platform}{ext}"));
334 }
335 }
336 rn_extensions.extend(base);
337 rn_extensions
338 } else {
339 base
340 }
341}
342
343pub(super) fn build_condition_names(
357 active_plugins: &[String],
358 extra_conditions: &[String],
359) -> Vec<String> {
360 let mut names = vec![
361 "development".into(),
362 "import".into(),
363 "require".into(),
364 "default".into(),
365 "types".into(),
366 "node".into(),
367 ];
368 if has_react_native_plugin(active_plugins) {
369 names.insert(0, "react-native".into());
370 names.insert(1, "browser".into());
371 }
372 for extra in extra_conditions.iter().rev() {
373 names.insert(0, extra.clone());
374 }
375 let mut seen: rustc_hash::FxHashSet<String> = rustc_hash::FxHashSet::default();
376 names.retain(|name| seen.insert(name.clone()));
377 names
378}
379
380#[cfg(test)]
381mod tests {
382 use super::*;
383
384 #[test]
385 fn test_has_react_native_plugin_active() {
386 let plugins = vec!["react-native".to_string(), "typescript".to_string()];
387 assert!(has_react_native_plugin(&plugins));
388 }
389
390 #[test]
391 fn test_has_expo_plugin_active() {
392 let plugins = vec!["expo".to_string(), "typescript".to_string()];
393 assert!(has_react_native_plugin(&plugins));
394 }
395
396 #[test]
397 fn test_has_react_native_plugin_inactive() {
398 let plugins = vec!["nextjs".to_string(), "typescript".to_string()];
399 assert!(!has_react_native_plugin(&plugins));
400 }
401
402 #[test]
403 fn test_rn_platform_extensions_prepended() {
404 let no_rn = build_extensions(&[]);
405 let rn_plugins = vec!["react-native".to_string()];
406 let with_rn = build_extensions(&rn_plugins);
407
408 assert_eq!(no_rn[0], ".ts");
409
410 assert_eq!(with_rn[0], ".web.ts");
411 assert_eq!(with_rn[1], ".web.tsx");
412 assert_eq!(with_rn[2], ".web.js");
413 assert_eq!(with_rn[3], ".web.jsx");
414
415 assert!(with_rn.len() > no_rn.len());
416 assert_eq!(
417 with_rn.len(),
418 no_rn.len() + 16,
419 "should add 16 platform extensions (4 platforms x 4 exts)"
420 );
421 }
422
423 #[test]
424 fn test_rn_condition_names_prepended() {
425 let no_rn = build_condition_names(&[], &[]);
426 let rn_plugins = vec!["react-native".to_string()];
427 let with_rn = build_condition_names(&rn_plugins, &[]);
428
429 assert_eq!(no_rn[0], "development");
430
431 assert_eq!(with_rn[0], "react-native");
432 assert_eq!(with_rn[1], "browser");
433 assert_eq!(with_rn[2], "development");
434 }
435
436 #[test]
437 fn test_development_condition_in_baseline() {
438 let names = build_condition_names(&[], &[]);
439 assert!(
440 names.contains(&"development".to_string()),
441 "`development` must be part of the default condition set"
442 );
443 }
444
445 #[test]
446 fn test_extra_conditions_prepended_before_baseline() {
447 let names = build_condition_names(&[], &["worker".to_string(), "edge-light".to_string()]);
448 assert_eq!(names[0], "worker");
449 assert_eq!(names[1], "edge-light");
450 assert_eq!(names[2], "development");
451 }
452
453 #[test]
454 fn test_extra_conditions_prepended_before_rn() {
455 let rn_plugins = vec!["react-native".to_string()];
456 let names = build_condition_names(&rn_plugins, &["worker".to_string()]);
457 assert_eq!(names[0], "worker");
458 assert_eq!(names[1], "react-native");
459 assert_eq!(names[2], "browser");
460 assert_eq!(names[3], "development");
461 }
462
463 #[test]
464 fn test_duplicate_baseline_condition_from_user_is_deduped() {
465 let names = build_condition_names(&[], &["development".to_string()]);
466 let dev_count = names.iter().filter(|n| *n == "development").count();
467 assert_eq!(dev_count, 1, "`development` should appear exactly once");
468 assert_eq!(
469 names[0], "development",
470 "user-supplied entry keeps its position"
471 );
472 }
473
474 #[test]
475 fn test_specifier_names_platform_variant() {
476 assert!(specifier_names_platform_variant("./UserMenu.ios"));
477 assert!(specifier_names_platform_variant("./UserMenu.android.tsx"));
478 assert!(specifier_names_platform_variant("../deep/UserMenu.native"));
479 assert!(!specifier_names_platform_variant("./UserMenu"));
480 assert!(!specifier_names_platform_variant("./UserMenu.tsx"));
481 assert!(!specifier_names_platform_variant("./ios/UserMenu"));
482 }
483
484 #[test]
485 fn test_platform_family_key_marks_platform_variants() {
486 let key = platform_family_key(Path::new("src/components/UserMenu.ios.tsx"))
487 .expect("source file has a family key");
488 assert_eq!(key.parent, Path::new("src/components"));
489 assert_eq!(key.base, "UserMenu");
490 assert!(key.is_platform_variant);
491
492 let key = platform_family_key(Path::new("src/components/UserMenu.tsx"))
493 .expect("source file has a family key");
494 assert_eq!(key.parent, Path::new("src/components"));
495 assert_eq!(key.base, "UserMenu");
496 assert!(!key.is_platform_variant);
497 }
498
499 #[test]
500 fn test_platform_family_key_covers_every_platform_and_source_extension() {
501 for platform in RN_PLATFORM_PREFIXES {
502 for ext in RN_SOURCE_EXTS {
503 let path = format!("src/Button{platform}{ext}");
504 let key = platform_family_key(Path::new(&path)).expect("family key");
505 assert_eq!(key.base, "Button", "{path}");
506 assert!(key.is_platform_variant, "{path}");
507 }
508 }
509 }
510
511 #[test]
512 fn test_platform_family_key_rejects_non_source_files() {
513 assert_eq!(platform_family_key(Path::new("src/UserMenu.css")), None);
514 assert_eq!(
515 platform_family_key(Path::new("src/UserMenu.ios.json")),
516 None
517 );
518 assert_eq!(platform_family_key(Path::new("src/UserMenu.ios")), None);
519 assert_eq!(
520 platform_family_key(Path::new("src/.ios.tsx")),
521 None,
522 "a bare platform segment has no base stem"
523 );
524 }
525
526 fn discovered(id: u32, path: &str) -> DiscoveredFile {
527 DiscoveredFile {
528 id: FileId(id),
529 path: std::path::PathBuf::from(path),
530 size_bytes: 0,
531 }
532 }
533
534 #[test]
535 fn test_platform_families_group_base_and_variants() {
536 let files = vec![
537 discovered(0, "src/UserMenu.tsx"),
538 discovered(1, "src/UserMenu.ios.tsx"),
539 discovered(2, "src/UserMenu.android.tsx"),
540 discovered(3, "src/Other.tsx"),
541 discovered(4, "src/nested/UserMenu.tsx"),
542 ];
543 let families = PlatformFamilies::build(&files);
544
545 assert_eq!(families.members.len(), 1);
546 assert_eq!(
547 families.siblings(FileId(0)),
548 Some([FileId(0), FileId(1), FileId(2)].as_slice())
549 );
550 assert_eq!(families.siblings(FileId(1)), families.siblings(FileId(0)));
551 assert_eq!(families.siblings(FileId(3)), None);
552 assert_eq!(
553 families.siblings(FileId(4)),
554 None,
555 "same stem in a different directory is not part of the family"
556 );
557 }
558
559 #[test]
560 fn test_family_edges_skip_the_importing_member() {
561 let files = vec![
562 discovered(0, "src/Badge.tsx"),
563 discovered(1, "src/Badge.ios.tsx"),
564 discovered(2, "src/Badge.android.tsx"),
565 ];
566 let ios_import = ResolvedImport {
567 info: ImportInfo {
568 source: "./Badge".to_string(),
569 imported_name: ImportedName::Named("BadgeProps".to_string()),
570 local_name: "BadgeProps".to_string(),
571 is_type_only: true,
572 is_type_only_star: false,
573 from_style: false,
574 span: oxc_span::Span::default(),
575 source_span: oxc_span::Span::default(),
576 },
577 target: ResolveResult::InternalModule(FileId(0)),
578 };
579 let android_re_export = super::super::types::ResolvedReExport {
580 info: fallow_types::extract::ReExportInfo {
581 source: "./Badge".to_string(),
582 imported_name: "BadgeProps".to_string(),
583 exported_name: "BadgeProps".to_string(),
584 is_type_only: true,
585 span: oxc_span::Span::default(),
586 statement_span: oxc_span::Span::default(),
587 source_span: oxc_span::Span::default(),
588 },
589 target: ResolveResult::InternalModule(FileId(0)),
590 };
591 let mut resolved = vec![
592 ResolvedModule {
593 file_id: FileId(1),
594 path: std::path::PathBuf::from("src/Badge.ios.tsx"),
595 resolved_imports: vec![ios_import],
596 ..ResolvedModule::default()
597 },
598 ResolvedModule {
599 file_id: FileId(2),
600 path: std::path::PathBuf::from("src/Badge.android.tsx"),
601 re_exports: vec![android_re_export],
602 ..ResolvedModule::default()
603 },
604 ];
605
606 synthesize_platform_family_edges(&mut resolved, &files, &["expo".to_string()]);
607
608 let targets = |module: &ResolvedModule| -> Vec<Option<FileId>> {
609 module
610 .resolved_imports
611 .iter()
612 .map(|import| import.target.internal_file_id())
613 .collect()
614 };
615 assert_eq!(
616 targets(&resolved[0]),
617 vec![Some(FileId(0)), Some(FileId(2))],
618 "an import must not give the importing member an edge to itself"
619 );
620 assert_eq!(
621 targets(&resolved[1]),
622 vec![Some(FileId(1))],
623 "a re-export must not give the importing member an edge to itself"
624 );
625 }
626
627 #[test]
628 fn test_platform_families_require_a_platform_variant() {
629 let files = vec![
630 discovered(0, "src/Button.ts"),
631 discovered(1, "src/Button.tsx"),
632 ];
633 let families = PlatformFamilies::build(&files);
634 assert!(
635 families.members.is_empty(),
636 "same-stem files without a platform variant are not a Metro family"
637 );
638 }
639
640 #[test]
641 fn test_duplicate_user_conditions_are_deduped_preserving_first() {
642 let names = build_condition_names(
643 &[],
644 &[
645 "worker".to_string(),
646 "edge-light".to_string(),
647 "worker".to_string(),
648 ],
649 );
650 let worker_count = names.iter().filter(|n| *n == "worker").count();
651 assert_eq!(worker_count, 1);
652 assert_eq!(names[0], "worker");
653 assert_eq!(names[1], "edge-light");
654 }
655}