hearth-graph 0.2.0

Standalone tree-sitter symbol index and module graph with injectable languages
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
//! JavaScript and TypeScript resolution through `oxc_resolver`.

#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
#[cfg(windows)]
use std::os::windows::{
    fs::{MetadataExt, OpenOptionsExt},
    io::AsRawHandle,
};
#[cfg(debug_assertions)]
use std::sync::atomic::{AtomicU32, Ordering};
use std::{
    collections::{HashMap, HashSet, VecDeque},
    env, io,
    io::Read,
    path::{Component, Path, PathBuf},
    sync::Arc,
};

use compact_str::CompactString;
use oxc_resolver::{
    FileSystem, FileSystemOs, ResolveContext, ResolveError, ResolveOptions, ResolverGeneric,
    TsconfigDiscovery, TsconfigOptions, TsconfigReferences,
};
use parking_lot::Mutex;
use serde_json::Value;
#[cfg(windows)]
use windows_sys::Win32::Storage::FileSystem::{
    FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, GetFileType, SECURITY_IDENTIFICATION,
};

use super::{
    FailedKind, ResolutionCompleteness, ResolutionOutcome, Resolve, Resolved, UnresolvedReason,
};
use crate::imports::{ImportKind, RawImport};

const MAX_TSCONFIG_BYTES: usize = 1024 * 1024;
const MAX_RESOLVER_FILE_BYTES: u64 = 1024 * 1024;
const REJECTED_PACKAGE_MANIFEST: &str = "{\"__hearth_rejected_package_manifest__\":";
const MAX_TSCONFIG_EXTENDS_ENTRIES: usize = 32;
const MAX_TSCONFIG_EXTENDS_VISITS: usize = 256;
const MAX_RESOLUTION_MEMO_ENTRIES: usize = 65_536;

#[cfg(any(windows, test))]
const WINDOWS_FILE_ATTRIBUTE_DIRECTORY: u32 = 0x0000_0010;
#[cfg(any(windows, test))]
const WINDOWS_FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
#[cfg(any(windows, test))]
const WINDOWS_FILE_TYPE_DISK: u32 = 1;

/// Configuration for JavaScript and TypeScript module resolution.
#[derive(Debug, Clone)]
pub struct JsResolveOptions {
    /// An optional manually selected tsconfig-format file, such as
    /// `tsconfig.json` or `jsconfig.json`.
    pub tsconfig: Option<PathBuf>,
    /// Conditions accepted while resolving package `exports`.
    pub condition_names: Vec<String>,
    /// File extensions probed in priority order.
    pub extensions: Vec<String>,
}

impl Default for JsResolveOptions {
    fn default() -> Self {
        Self {
            tsconfig: None,
            // These family conditions are split between the import and require
            // resolvers by `resolver_options`.
            condition_names: vec!["import".into(), "require".into()],
            extensions: vec![
                ".ts".into(),
                ".tsx".into(),
                ".mts".into(),
                ".cts".into(),
                ".js".into(),
                ".jsx".into(),
                ".mjs".into(),
                ".cjs".into(),
                ".vue".into(),
            ],
        }
    }
}

/// Build a JavaScript resolver backed by the operating system filesystem.
pub fn js_resolver(options: JsResolveOptions) -> Box<dyn Resolve> {
    build_js_resolver(SecureOsFileSystem::new(), options)
}

/// Build a JavaScript resolver backed by an injected filesystem.
pub fn js_resolver_with_fs<FS: FileSystem + 'static>(
    fs: FS,
    options: JsResolveOptions,
) -> Box<dyn Resolve> {
    build_js_resolver(fs, options)
}

fn build_js_resolver<FS: FileSystem + 'static>(
    fs: FS,
    options: JsResolveOptions,
) -> Box<dyn Resolve> {
    let (import_options, require_options, configured_tsconfig) = resolver_options(options);
    let file_system = SharedFileSystem::from_file_system(fs);
    let import_resolver =
        ResolverGeneric::new_with_file_system(file_system.clone(), import_options);
    let require_resolver = import_resolver.clone_with_options(require_options);
    Box::new(JsResolver {
        import_resolver,
        require_resolver,
        file_system,
        configured_tsconfig,
        dependency_memo: Mutex::new(HashMap::new()),
        #[cfg(debug_assertions)]
        in_flight: AtomicU32::new(0),
    })
}

struct JsResolver {
    import_resolver: ResolverGeneric<SharedFileSystem>,
    require_resolver: ResolverGeneric<SharedFileSystem>,
    file_system: SharedFileSystem,
    configured_tsconfig: Option<PathBuf>,
    dependency_memo: Mutex<HashMap<ResolutionMemoKey, Vec<CompactString>>>,
    #[cfg(debug_assertions)]
    in_flight: AtomicU32,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct ResolutionMemoKey {
    from_dir: PathBuf,
    specifier: CompactString,
    kind: ImportKind,
}

impl Resolve for JsResolver {
    fn resolve(&self, from_file: &str, import: &RawImport) -> ResolutionOutcome {
        #[cfg(debug_assertions)]
        let _in_flight = InFlightResolve::enter(&self.in_flight);

        if matches!(import.kind, ImportKind::RustUse | ImportKind::RustMod) {
            return unresolved(UnresolvedReason::Unsupported, Vec::new(), Vec::new());
        }

        let from_path = Path::new(from_file);
        if !from_path.is_absolute() {
            return unresolved(
                failed(FailedKind::InvalidSpecifier, "from_file must be absolute"),
                Vec::new(),
                Vec::new(),
            );
        }

        let Some(parent) = from_path.parent() else {
            return unresolved(
                failed(
                    FailedKind::InvalidSpecifier,
                    "from_file must have a parent directory",
                ),
                Vec::new(),
                Vec::new(),
            );
        };
        let memo_key = ResolutionMemoKey {
            from_dir: parent.to_path_buf(),
            specifier: import.specifier.clone(),
            kind: import.kind,
        };
        let resolver = self.resolver_for(import.kind);

        let mut dependency_paths: Vec<PathBuf> = self.configured_tsconfig.iter().cloned().collect();
        let mut notes = Vec::new();
        let mut tsconfig_tracking_truncated = false;
        let discovered = match &self.configured_tsconfig {
            Some(configured) => resolver.find_tsconfig(configured),
            None => resolver.find_tsconfig(from_path),
        };
        let tsconfig = match discovered {
            Ok(tsconfig) => tsconfig,
            Err(error) => {
                if let Some(configured_tsconfig) = &self.configured_tsconfig {
                    let tracking = self.track_tsconfig_chain(configured_tsconfig);
                    tsconfig_tracking_truncated |= tracking.truncated;
                    dependency_paths.extend(tracking.dependencies);
                    notes.extend(tracking.notes);
                }
                dependency_paths.extend(error_dependency_paths(&error));
                let mut outcome = unresolved(
                    classify_error(error),
                    collect_dependencies(ResolveContext::default(), dependency_paths),
                    notes,
                );
                if tsconfig_tracking_truncated {
                    outcome.completeness = ResolutionCompleteness::Partial;
                }
                return self.replay_dependencies(memo_key, outcome);
            }
        };
        if let Some(tsconfig) = &tsconfig {
            let tracking = self.track_tsconfig_chain(tsconfig.path());
            tsconfig_tracking_truncated |= tracking.truncated;
            dependency_paths.extend(tracking.dependencies);
            notes.extend(tracking.notes);
        }

        let mut context = ResolveContext::default();
        let resolution = resolver.resolve_with_context(
            parent,
            import.specifier.as_str(),
            tsconfig.as_deref(),
            &mut context,
        );

        let mut outcome = match resolution {
            Ok(resolution) => {
                let package_json = resolution.package_json();
                dependency_paths
                    .extend(package_json.map(|package_json| package_json.path().to_path_buf()));
                ResolutionOutcome {
                    resolved: classify_resolution(
                        import.specifier.as_str(),
                        resolution.path(),
                        package_json.and_then(|package_json| package_json.name()),
                    ),
                    dependencies: collect_dependencies(context, dependency_paths),
                    notes,
                    completeness: ResolutionCompleteness::Complete,
                }
            }
            Err(error) => {
                dependency_paths.extend(error_dependency_paths(&error));
                unresolved(
                    classify_error(error),
                    collect_dependencies(context, dependency_paths),
                    notes,
                )
            }
        };
        if tsconfig_tracking_truncated {
            outcome.completeness = ResolutionCompleteness::Partial;
        }
        self.replay_dependencies(memo_key, outcome)
    }

    fn clear_cache(&self) {
        #[cfg(debug_assertions)]
        debug_assert_eq!(
            self.in_flight.load(Ordering::Acquire),
            0,
            "clear_cache must not overlap an in-flight resolve"
        );
        self.import_resolver.clear_cache();
        self.require_resolver.clear_cache();
        self.dependency_memo.lock().clear();
    }
}

impl JsResolver {
    fn resolver_for(&self, kind: ImportKind) -> &ResolverGeneric<SharedFileSystem> {
        match kind {
            ImportKind::CommonJs | ImportKind::TsImportRequire => &self.require_resolver,
            _ => &self.import_resolver,
        }
    }

    fn replay_dependencies(
        &self,
        key: ResolutionMemoKey,
        mut outcome: ResolutionOutcome,
    ) -> ResolutionOutcome {
        let mut memo = self.dependency_memo.lock();
        if let Some(dependencies) = memo.get(&key) {
            outcome.dependencies.extend(dependencies.iter().cloned());
        }
        normalize_dependencies(&mut outcome.dependencies);
        if memo.len() >= MAX_RESOLUTION_MEMO_ENTRIES && !memo.contains_key(&key) {
            memo.clear();
        }
        memo.insert(key, outcome.dependencies.clone());
        outcome
    }

    fn track_tsconfig_chain(&self, leaf: &Path) -> TsconfigTracking {
        let extends_resolver = self
            .import_resolver
            .clone_with_options(tsconfig_extends_options());
        let mut tracking = TsconfigTracking::default();
        let mut pending = VecDeque::from([(absolute_path(leaf), Vec::new())]);
        let mut visited = HashSet::new();

        while let Some((config_path, mut ancestry)) = pending.pop_front() {
            if ancestry.contains(&config_path) {
                tracking.notes.push(
                    format!(
                        "tsconfig extends cycle while tracking dependencies: {}",
                        config_path.display()
                    )
                    .into(),
                );
                continue;
            }
            if visited.contains(&config_path) {
                continue;
            }
            if visited.len() == MAX_TSCONFIG_EXTENDS_VISITS {
                tracking.truncated = true;
                tracking.notes.push(
                    format!(
                        "tsconfig extends visit budget of {MAX_TSCONFIG_EXTENDS_VISITS} configs \
                         exhausted while tracking dependencies; {} configs remain pending",
                        pending.len() + 1
                    )
                    .into(),
                );
                break;
            }
            visited.insert(config_path.clone());
            ancestry.push(config_path.clone());
            tracking.dependencies.push(config_path.clone());

            let mut source = match self.file_system.read_to_string(&config_path) {
                Ok(source) => source,
                Err(error) => {
                    tracking.notes.push(
                        format!(
                            "could not read tsconfig extends from {}: {error}",
                            config_path.display()
                        )
                        .into(),
                    );
                    continue;
                }
            };
            if source.len() > MAX_TSCONFIG_BYTES {
                tracking.truncated = true;
                tracking.notes.push(
                    format!(
                        "tsconfig extends file {} exceeds the size limit of \
                         {MAX_TSCONFIG_BYTES} bytes ({} bytes)",
                        config_path.display(),
                        source.len()
                    )
                    .into(),
                );
                continue;
            }
            if let Err(error) = json_strip_comments::strip(&mut source) {
                tracking.notes.push(
                    format!(
                        "could not strip JSONC syntax from tsconfig extends in {}: {error}",
                        config_path.display()
                    )
                    .into(),
                );
                continue;
            }
            let value: Value = match serde_json::from_str(&source) {
                Ok(value) => value,
                Err(error) => {
                    tracking.notes.push(
                        format!(
                            "could not parse tsconfig extends from {}: {error}",
                            config_path.display()
                        )
                        .into(),
                    );
                    continue;
                }
            };
            let specifiers = match extends_specifiers(&value) {
                Ok(specifiers) => specifiers,
                Err(detail) => {
                    tracking.notes.push(
                        format!(
                            "invalid tsconfig extends in {}: {detail}",
                            config_path.display()
                        )
                        .into(),
                    );
                    continue;
                }
            };
            let mut specifiers = specifiers;
            if specifiers.len() > MAX_TSCONFIG_EXTENDS_ENTRIES {
                tracking.truncated = true;
                tracking.notes.push(
                    format!(
                        "tsconfig extends entry limit of {MAX_TSCONFIG_EXTENDS_ENTRIES} exceeded \
                         in {}; only the first {MAX_TSCONFIG_EXTENDS_ENTRIES} of {} entries were \
                         tracked",
                        config_path.display(),
                        specifiers.len()
                    )
                    .into(),
                );
                specifiers.truncate(MAX_TSCONFIG_EXTENDS_ENTRIES);
            }
            if specifiers.is_empty() {
                continue;
            }
            let Some(directory) = config_path.parent() else {
                tracking.notes.push(
                    format!(
                        "tsconfig has no parent directory while tracking extends: {}",
                        config_path.display()
                    )
                    .into(),
                );
                continue;
            };
            for specifier in specifiers {
                let package_style = is_package_style_extends(&specifier);
                let target_path =
                    (!package_style).then(|| extends_target_path(directory, &specifier));
                let absolute_specifier = target_path.as_deref().map(Path::to_string_lossy);
                let resolution_specifier =
                    absolute_specifier.as_deref().unwrap_or(specifier.as_str());
                let mut context = ResolveContext::default();
                let resolution = extends_resolver.resolve_with_context(
                    directory,
                    resolution_specifier,
                    None,
                    &mut context,
                );
                if !package_style {
                    tracking.dependencies.extend(context.file_dependencies);
                    tracking.dependencies.extend(context.missing_dependencies);
                }

                match resolution {
                    Ok(resolution) => {
                        tracking.dependencies.extend(
                            resolution
                                .package_json()
                                .map(|package_json| package_json.path().to_path_buf()),
                        );
                        pending.push_back((absolute_path(resolution.path()), ancestry.clone()));
                    }
                    Err(error) => {
                        tracking.dependencies.extend(target_path);
                        let kind = if package_style { "package-style " } else { "" };
                        tracking.notes.push(
                            format!(
                                "{kind}tsconfig extends {specifier:?} from {} could not be resolved: {error}",
                                config_path.display()
                            )
                            .into(),
                        );
                    }
                }
            }
        }

        tracking
    }
}

fn resolver_options(
    options: JsResolveOptions,
) -> (ResolveOptions, ResolveOptions, Option<PathBuf>) {
    let JsResolveOptions {
        tsconfig,
        condition_names,
        extensions,
    } = options;
    let configured_tsconfig = tsconfig.map(|path| absolute_path(&path));
    let tsconfig = configured_tsconfig.clone().map(|config_file| {
        TsconfigDiscovery::Manual(TsconfigOptions {
            config_file,
            references: TsconfigReferences::Disabled,
        })
    });
    let common_conditions: Vec<String> = condition_names
        .into_iter()
        .filter(|condition| condition != "import" && condition != "require")
        .collect();
    let import_options = ResolveOptions {
        tsconfig: tsconfig.clone(),
        condition_names: family_conditions("import", &common_conditions),
        extensions: extensions.clone(),
        ..ResolveOptions::default()
    };
    let require_options = ResolveOptions {
        tsconfig,
        condition_names: family_conditions("require", &common_conditions),
        extensions,
        ..ResolveOptions::default()
    };
    (import_options, require_options, configured_tsconfig)
}

fn family_conditions(family: &str, common: &[String]) -> Vec<String> {
    std::iter::once(family.to_owned())
        .chain(common.iter().cloned())
        .collect()
}

fn tsconfig_extends_options() -> ResolveOptions {
    ResolveOptions {
        tsconfig: None,
        condition_names: vec!["node".into(), "import".into()],
        extensions: vec![".json".into()],
        main_files: vec!["tsconfig".into()],
        ..ResolveOptions::default()
    }
}

fn collect_dependencies(context: ResolveContext, additional: Vec<PathBuf>) -> Vec<CompactString> {
    let mut dependencies: Vec<CompactString> = context
        .file_dependencies
        .into_iter()
        .chain(context.missing_dependencies)
        .chain(additional)
        .map(|path| absolute_path(&path))
        .map(|path| path_string(&path))
        .collect();
    dependencies.sort_unstable();
    dependencies.dedup();
    dependencies
}

fn extends_specifiers(value: &Value) -> Result<Vec<String>, &'static str> {
    match value.get("extends") {
        None => Ok(Vec::new()),
        Some(Value::String(specifier)) => Ok(vec![specifier.clone()]),
        Some(Value::Array(specifiers)) => specifiers
            .iter()
            .map(|specifier| {
                specifier
                    .as_str()
                    .map(str::to_owned)
                    .ok_or("extends array entries must be strings")
            })
            .collect(),
        Some(_) => Err("extends must be a string or an array of strings"),
    }
}

fn is_package_style_extends(specifier: &str) -> bool {
    !Path::new(specifier).is_absolute() && !specifier.starts_with('.')
}

fn extends_target_path(directory: &Path, specifier: &str) -> PathBuf {
    let target = Path::new(specifier);
    if target.is_absolute() {
        target.to_path_buf()
    } else {
        normalize_path(&absolute_path(&directory.join(target)))
    }
}

fn normalize_path(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                normalized.pop();
            }
            Component::Prefix(_) | Component::RootDir | Component::Normal(_) => {
                normalized.push(component.as_os_str());
            }
        }
    }
    normalized
}

fn classify_error(error: ResolveError) -> UnresolvedReason {
    if is_not_found_error(&error) {
        UnresolvedReason::NotFound
    } else {
        let kind = match &error {
            ResolveError::TsconfigNotFound(_)
            | ResolveError::TsconfigSelfReference(_)
            | ResolveError::TsconfigCircularExtend(_)
            | ResolveError::TsconfigLoadFailed { .. }
            | ResolveError::Json(_)
            | ResolveError::InvalidPackageTarget(_, _, _)
            | ResolveError::InvalidPackageConfig(_)
            | ResolveError::InvalidPackageConfigDefault(_)
            | ResolveError::InvalidPackageConfigDirectory(_) => FailedKind::Config,
            ResolveError::IOError(_) => FailedKind::Io,
            ResolveError::PathNotSupported(_)
            | ResolveError::Specifier(_)
            | ResolveError::InvalidModuleSpecifier(_, _) => FailedKind::InvalidSpecifier,
            _ => FailedKind::Other,
        };
        failed(kind, error.to_string())
    }
}

fn is_not_found_error(error: &ResolveError) -> bool {
    matches!(
        error,
        ResolveError::NotFound(_)
            | ResolveError::MatchedAliasNotFound(_, _)
            | ResolveError::ExtensionAlias(_, _, _)
    )
}

fn error_dependency_paths(error: &ResolveError) -> Vec<PathBuf> {
    match error {
        ResolveError::TsconfigLoadFailed { path, source } => {
            let mut paths = vec![path.clone()];
            paths.extend(error_dependency_paths(source));
            paths
        }
        ResolveError::TsconfigCircularExtend(paths) => paths.paths().to_vec(),
        ResolveError::Json(error) => vec![error.path.clone()],
        ResolveError::InvalidModuleSpecifier(_, path)
        | ResolveError::InvalidPackageTarget(_, _, path)
        | ResolveError::InvalidPackageConfig(path)
        | ResolveError::InvalidPackageConfigDefault(path)
        | ResolveError::InvalidPackageConfigDirectory(path)
        | ResolveError::PackageImportNotDefined(_, path) => vec![path.clone()],
        ResolveError::PackagePathNotExported {
            package_json_path, ..
        } => vec![package_json_path.clone()],
        _ => Vec::new(),
    }
}

fn absolute_path(path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        env::current_dir().map_or_else(|_| path.to_path_buf(), |cwd| cwd.join(path))
    }
}

fn path_string(path: &Path) -> CompactString {
    CompactString::from(path.to_string_lossy().as_ref())
}

fn is_node_modules_path(path: &Path) -> bool {
    path.components()
        .any(|component| matches!(component, Component::Normal(name) if name == "node_modules"))
}

fn is_path_specifier(specifier: &str) -> bool {
    specifier.starts_with("./")
        || specifier.starts_with("../")
        || Path::new(specifier).is_absolute()
}

fn classify_resolution(specifier: &str, path: &Path, manifest_name: Option<&str>) -> Resolved {
    let path = absolute_path(path);
    if is_path_specifier(specifier) || !is_node_modules_path(&path) {
        Resolved::Path(path_string(&path))
    } else {
        // Aliased specifiers (`#dep`) say nothing about the installed package,
        // so a missing manifest name falls back to the directory name under
        // the last node_modules component before the specifier text.
        let name = manifest_name
            .map(CompactString::from)
            .or_else(|| package_name_from_path(&path))
            .unwrap_or_else(|| package_name(specifier));
        Resolved::External(name)
    }
}

fn package_name_from_path(path: &Path) -> Option<CompactString> {
    let components: Vec<&str> = path
        .components()
        .filter_map(|component| match component {
            Component::Normal(name) => name.to_str(),
            _ => None,
        })
        .collect();
    let base = components
        .iter()
        .rposition(|name| *name == "node_modules")?;
    let first = components.get(base + 1)?;
    if first.starts_with('@') {
        let second = components.get(base + 2)?;
        Some(CompactString::from(format!("{first}/{second}")))
    } else {
        Some(CompactString::from(*first))
    }
}

fn package_name(specifier: &str) -> CompactString {
    let segment_count = usize::from(specifier.starts_with('@')) + 1;
    CompactString::from(
        specifier
            .split('/')
            .take(segment_count)
            .collect::<Vec<_>>()
            .join("/"),
    )
}

fn unresolved(
    reason: UnresolvedReason,
    dependencies: Vec<CompactString>,
    notes: Vec<CompactString>,
) -> ResolutionOutcome {
    let completeness = if matches!(&reason, UnresolvedReason::Failed { .. }) {
        ResolutionCompleteness::Partial
    } else {
        ResolutionCompleteness::Complete
    };
    ResolutionOutcome {
        resolved: Resolved::Unresolved(reason),
        dependencies,
        notes,
        completeness,
    }
}

fn failed(kind: FailedKind, detail: impl Into<CompactString>) -> UnresolvedReason {
    UnresolvedReason::Failed {
        kind,
        detail: detail.into(),
    }
}

fn normalize_dependencies(dependencies: &mut Vec<CompactString>) {
    dependencies.sort_unstable();
    dependencies.dedup();
}

#[derive(Default)]
struct TsconfigTracking {
    dependencies: Vec<PathBuf>,
    notes: Vec<CompactString>,
    truncated: bool,
}

#[cfg(unix)]
fn open_resolver_file(path: &Path) -> io::Result<std::fs::File> {
    // O_NOFOLLOW binds final-component symlink rejection to this open, while
    // O_NONBLOCK prevents a hostile FIFO from blocking before fstat rejects it.
    std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_NONBLOCK | libc::O_CLOEXEC | libc::O_NOFOLLOW)
        .open(path)
}

#[cfg(windows)]
fn open_resolver_file(path: &Path) -> io::Result<std::fs::File> {
    // Open the named object rather than traversing a reparse point. Backup
    // semantics lets the same handle-based validation reject directories too.
    // Identification QoS prevents a named-pipe server from impersonating this
    // process before the opened handle can be classified and rejected.
    std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
        .security_qos_flags(SECURITY_IDENTIFICATION)
        .open(path)
}

#[cfg(not(any(unix, windows)))]
fn open_resolver_file(_path: &Path) -> io::Result<std::fs::File> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "secure resolver config reads are unsupported on this target",
    ))
}

fn invalid_resolver_file() -> io::Error {
    io::Error::new(
        io::ErrorKind::InvalidData,
        "resolver config must be a regular file no larger than 1 MiB",
    )
}

#[cfg(unix)]
fn opened_resolver_file_metadata(file: &std::fs::File) -> io::Result<std::fs::Metadata> {
    let metadata = file.metadata()?;
    if !metadata.is_file() {
        return Err(invalid_resolver_file());
    }
    Ok(metadata)
}

#[cfg(windows)]
fn opened_resolver_file_metadata(file: &std::fs::File) -> io::Result<std::fs::Metadata> {
    // SAFETY: the handle remains owned by `file` for the duration of this call.
    let file_type = unsafe { GetFileType(file.as_raw_handle()) };
    if file_type != WINDOWS_FILE_TYPE_DISK {
        return Err(invalid_resolver_file());
    }

    let metadata = file.metadata()?;
    if !windows_handle_is_regular(file_type, metadata.file_attributes()) {
        return Err(invalid_resolver_file());
    }
    Ok(metadata)
}

#[cfg(not(any(unix, windows)))]
fn opened_resolver_file_metadata(_file: &std::fs::File) -> io::Result<std::fs::Metadata> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "secure resolver config reads are unsupported on this target",
    ))
}

#[cfg(any(windows, test))]
fn windows_handle_is_regular(file_type: u32, attributes: u32) -> bool {
    file_type == WINDOWS_FILE_TYPE_DISK
        && attributes & (WINDOWS_FILE_ATTRIBUTE_DIRECTORY | WINDOWS_FILE_ATTRIBUTE_REPARSE_POINT)
            == 0
}

fn resolver_file_capacity(file_len: u64) -> io::Result<usize> {
    if file_len > MAX_RESOLVER_FILE_BYTES {
        return Err(invalid_resolver_file());
    }
    Ok(file_len as usize)
}

fn read_resolver_contents(reader: &mut impl Read, initial_capacity: usize) -> io::Result<Vec<u8>> {
    let mut bytes = Vec::with_capacity(initial_capacity);
    reader
        .take(MAX_RESOLVER_FILE_BYTES + 1)
        .read_to_end(&mut bytes)?;
    if bytes.len() as u64 > MAX_RESOLVER_FILE_BYTES {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "resolver config exceeds 1 MiB",
        ));
    }
    Ok(bytes)
}

fn read_resolver_file(path: &Path) -> io::Result<Vec<u8>> {
    let mut file = open_resolver_file(path)?;
    let metadata = opened_resolver_file_metadata(&file)?;
    let capacity = resolver_file_capacity(metadata.len())?;
    read_resolver_contents(&mut file, capacity)
}

fn rejected_package_manifest(path: &Path, error: &io::Error) -> bool {
    path.file_name().is_some_and(|name| name == "package.json")
        && error.kind() != io::ErrorKind::NotFound
}

fn fail_closed_package_manifest_bytes(
    path: &Path,
    result: io::Result<Vec<u8>>,
) -> io::Result<Vec<u8>> {
    match result {
        Err(error) if rejected_package_manifest(path, &error) => {
            // oxc_resolver interprets every package-manifest read error as
            // "missing" and may fall back to index.js. Returning a malformed
            // marker makes its JSON parser propagate a configuration failure
            // instead of silently accepting a rejected existing manifest.
            Ok(REJECTED_PACKAGE_MANIFEST.as_bytes().to_vec())
        }
        result => result,
    }
}

fn fail_closed_package_manifest_string(
    path: &Path,
    result: io::Result<String>,
) -> io::Result<String> {
    match result {
        Err(error) if rejected_package_manifest(path, &error) => {
            Ok(REJECTED_PACKAGE_MANIFEST.to_owned())
        }
        result => result,
    }
}

#[derive(Clone)]
struct SecureOsFileSystem(FileSystemOs);

impl FileSystem for SecureOsFileSystem {
    fn new() -> Self {
        Self(FileSystemOs::new())
    }

    fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
        read_resolver_file(path)
    }

    fn read_to_string(&self, path: &Path) -> io::Result<String> {
        let bytes = self.read(path)?;
        String::from_utf8(bytes).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
    }

    fn metadata(&self, path: &Path) -> io::Result<oxc_resolver::FileMetadata> {
        self.0.metadata(path)
    }

    fn symlink_metadata(&self, path: &Path) -> io::Result<oxc_resolver::FileMetadata> {
        self.0.symlink_metadata(path)
    }

    fn read_link(&self, path: &Path) -> Result<PathBuf, ResolveError> {
        self.0.read_link(path)
    }

    fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
        self.0.canonicalize(path)
    }
}

#[derive(Clone)]
struct SharedFileSystem(Arc<dyn FileSystem>);

impl SharedFileSystem {
    fn from_file_system(file_system: impl FileSystem + 'static) -> Self {
        Self(Arc::new(file_system))
    }
}

impl FileSystem for SharedFileSystem {
    fn new() -> Self {
        Self::from_file_system(SecureOsFileSystem::new())
    }

    fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
        fail_closed_package_manifest_bytes(path, self.0.read(path))
    }

    fn read_to_string(&self, path: &Path) -> io::Result<String> {
        fail_closed_package_manifest_string(path, self.0.read_to_string(path))
    }

    fn metadata(&self, path: &Path) -> io::Result<oxc_resolver::FileMetadata> {
        self.0.metadata(path)
    }

    fn symlink_metadata(&self, path: &Path) -> io::Result<oxc_resolver::FileMetadata> {
        self.0.symlink_metadata(path)
    }

    fn read_link(&self, path: &Path) -> Result<PathBuf, ResolveError> {
        self.0.read_link(path)
    }

    fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
        self.0.canonicalize(path)
    }
}

#[cfg(debug_assertions)]
struct InFlightResolve<'a> {
    counter: &'a AtomicU32,
}

#[cfg(debug_assertions)]
impl<'a> InFlightResolve<'a> {
    fn enter(counter: &'a AtomicU32) -> Self {
        let previous = counter.fetch_add(1, Ordering::AcqRel);
        debug_assert_ne!(previous, u32::MAX, "in-flight resolve counter overflowed");
        Self { counter }
    }
}

#[cfg(debug_assertions)]
impl Drop for InFlightResolve<'_> {
    fn drop(&mut self) {
        let previous = self.counter.fetch_sub(1, Ordering::AcqRel);
        debug_assert!(previous > 0, "in-flight resolve counter underflowed");
    }
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::*;

    #[cfg(any(unix, windows))]
    #[test]
    fn secure_resolver_read_accepts_a_regular_file_at_the_limit() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("config.json");
        std::fs::write(&path, vec![b'x'; MAX_RESOLVER_FILE_BYTES as usize]).unwrap();

        let contents = read_resolver_file(&path).unwrap();

        assert_eq!(contents.len() as u64, MAX_RESOLVER_FILE_BYTES);
    }

    #[cfg(any(unix, windows))]
    #[test]
    fn secure_resolver_read_rejects_an_oversized_file() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("config.json");
        std::fs::write(&path, vec![b'x'; MAX_RESOLVER_FILE_BYTES as usize + 1]).unwrap();

        let error = read_resolver_file(&path).unwrap_err();

        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn bounded_read_rejects_growth_after_opened_metadata_was_checked() {
        let mut contents = Cursor::new(vec![b'x'; MAX_RESOLVER_FILE_BYTES as usize + 1]);

        let error =
            read_resolver_contents(&mut contents, MAX_RESOLVER_FILE_BYTES as usize).unwrap_err();

        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
    }

    #[cfg(any(unix, windows))]
    #[test]
    fn secure_resolver_read_rejects_a_directory() {
        let directory = tempfile::tempdir().unwrap();

        let error = read_resolver_file(directory.path()).unwrap_err();

        assert!(matches!(
            error.kind(),
            io::ErrorKind::InvalidData | io::ErrorKind::PermissionDenied
        ));
    }

    #[cfg(unix)]
    #[test]
    fn secure_resolver_read_rejects_a_final_symlink() {
        use std::os::unix::fs::symlink;

        let directory = tempfile::tempdir().unwrap();
        let target = directory.path().join("target.json");
        let link = directory.path().join("link.json");
        std::fs::write(&target, b"{}").unwrap();
        symlink(&target, &link).unwrap();

        assert!(read_resolver_file(&link).is_err());
    }

    #[test]
    fn windows_handle_classification_rejects_devices_directories_and_reparse_points() {
        const FILE_ATTRIBUTE_ARCHIVE: u32 = 0x0000_0020;
        const FILE_ATTRIBUTE_NORMAL: u32 = 0x0000_0080;
        const FILE_TYPE_UNKNOWN: u32 = 0;
        const FILE_TYPE_CHAR: u32 = 2;
        const FILE_TYPE_PIPE: u32 = 3;

        assert!(windows_handle_is_regular(
            WINDOWS_FILE_TYPE_DISK,
            FILE_ATTRIBUTE_NORMAL
        ));
        assert!(windows_handle_is_regular(
            WINDOWS_FILE_TYPE_DISK,
            FILE_ATTRIBUTE_ARCHIVE
        ));
        assert!(!windows_handle_is_regular(
            FILE_TYPE_UNKNOWN,
            FILE_ATTRIBUTE_NORMAL
        ));
        assert!(!windows_handle_is_regular(
            FILE_TYPE_CHAR,
            FILE_ATTRIBUTE_NORMAL
        ));
        assert!(!windows_handle_is_regular(
            FILE_TYPE_PIPE,
            FILE_ATTRIBUTE_NORMAL
        ));
        assert!(!windows_handle_is_regular(
            WINDOWS_FILE_TYPE_DISK,
            WINDOWS_FILE_ATTRIBUTE_DIRECTORY
        ));
        assert!(!windows_handle_is_regular(
            WINDOWS_FILE_TYPE_DISK,
            WINDOWS_FILE_ATTRIBUTE_REPARSE_POINT
        ));
    }

    #[cfg(not(any(unix, windows)))]
    #[test]
    fn secure_resolver_reads_fail_closed_on_unsupported_targets() {
        let error = read_resolver_file(Path::new("config.json")).unwrap_err();

        assert_eq!(error.kind(), io::ErrorKind::Unsupported);
    }
}