Skip to main content

rust_anything/ts/
tsconfig.rs

1//! `compilerOptions.paths` from the nearest `tsconfig.json`: import aliases like `~/utils`.
2
3use std::path::Path;
4
5use serde_json::Value;
6
7/// Alias patterns, with targets as root-relative paths (`*` kept where the pattern had one).
8#[derive(Clone, Debug, Default, PartialEq, Eq)]
9pub struct PathAliases {
10    pub entries: Vec<(String, Vec<String>)>,
11}
12
13impl PathAliases {
14    /// The tsconfig closest to `dir` (root-relative), walking up to the root.
15    pub fn nearest(root: &Path, dir: &str) -> Self {
16        let mut current = dir.trim_end_matches('/').to_string();
17        loop {
18            let candidate = if current.is_empty() {
19                "tsconfig.json".to_string()
20            } else {
21                format!("{current}/tsconfig.json")
22            };
23            if root.join(&candidate).is_file() {
24                return load(root, &candidate, 0)
25                    .map(Config::into_aliases)
26                    .unwrap_or_default();
27            }
28            if current.is_empty() {
29                return Self::default();
30            }
31            current = current
32                .rsplit_once('/')
33                .map_or(String::new(), |(parent, _)| parent.to_string());
34        }
35    }
36
37    /// Root-relative base paths an import specifier may point at, in tsconfig order.
38    pub fn candidates(&self, specifier: &str) -> Vec<String> {
39        let mut best: Option<(usize, &Vec<String>, String)> = None;
40        for (pattern, targets) in &self.entries {
41            let matched = match pattern.split_once('*') {
42                Some((prefix, suffix)) => specifier
43                    .strip_prefix(prefix)
44                    .and_then(|rest| rest.strip_suffix(suffix))
45                    .map(|star| (prefix.len(), star.to_string())),
46                None => (pattern == specifier).then(|| (usize::MAX, String::new())),
47            };
48            // TS picks the pattern with the longest prefix.
49            if let Some((weight, star)) = matched
50                && best.as_ref().is_none_or(|(w, _, _)| weight > *w)
51            {
52                best = Some((weight, targets, star));
53            }
54        }
55        best.map(|(_, targets, star)| targets.iter().map(|t| t.replacen('*', &star, 1)).collect())
56            .unwrap_or_default()
57    }
58}
59
60#[derive(Default)]
61struct Config {
62    base_url: Option<String>,
63    paths: Option<Paths>,
64}
65
66struct Paths {
67    dir: String,
68    entries: Vec<(String, Vec<String>)>,
69}
70
71impl Config {
72    fn overlay(&mut self, later: Self) {
73        self.base_url = later.base_url.or(self.base_url.take());
74        self.paths = later.paths.or(self.paths.take());
75    }
76
77    fn into_aliases(self) -> PathAliases {
78        let Some(Paths { dir, mut entries }) = self.paths else {
79            return PathAliases::default();
80        };
81        let base = self.base_url.unwrap_or(dir);
82        for (_, targets) in &mut entries {
83            for target in targets {
84                *target = join(&base, target);
85            }
86        }
87        PathAliases { entries }
88    }
89}
90
91fn load(root: &Path, rel: &str, depth: usize) -> Option<Config> {
92    if depth > 8 {
93        return None;
94    }
95    let text = std::fs::read_to_string(root.join(rel)).ok()?;
96    let json: Value = json5::from_str(&text).ok()?;
97    let dir = rel.rsplit_once('/').map_or("", |(d, _)| d);
98    let extends: Vec<&str> = match &json["extends"] {
99        Value::String(s) => vec![s.as_str()],
100        Value::Array(items) => items.iter().filter_map(Value::as_str).collect(),
101        _ => Vec::new(),
102    };
103    let mut config = Config::default();
104    for parent in extends.into_iter().filter(|parent| parent.starts_with('.')) {
105        let mut target = join(dir, parent);
106        if !target.ends_with(".json") {
107            target.push_str(".json");
108        }
109        if let Some(parent) = load(root, &target, depth + 1) {
110            config.overlay(parent);
111        }
112    }
113    let options = &json["compilerOptions"];
114    let paths = options["paths"].as_object().map(|paths| {
115        let entries = paths
116            .iter()
117            .map(|(pattern, targets)| {
118                let targets = targets
119                    .as_array()
120                    .map(|items| {
121                        items
122                            .iter()
123                            .filter_map(Value::as_str)
124                            .map(str::to_owned)
125                            .collect()
126                    })
127                    .unwrap_or_default();
128                (pattern.clone(), targets)
129            })
130            .collect();
131        Paths {
132            dir: dir.to_string(),
133            entries,
134        }
135    });
136    config.overlay(Config {
137        base_url: options["baseUrl"].as_str().map(|base| join(dir, base)),
138        paths,
139    });
140    Some(config)
141}
142
143/// `dir/rel`, with `.` and `..` collapsed; root-relative.
144fn join(dir: &str, rel: &str) -> String {
145    let mut parts: Vec<&str> = dir.split('/').filter(|p| !p.is_empty()).collect();
146    for part in rel.split('/') {
147        match part {
148            "" | "." => {}
149            ".." => {
150                parts.pop();
151            }
152            _ => parts.push(part),
153        }
154    }
155    parts.join("/")
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    #[test]
163    fn matches_like_typescript() {
164        let aliases = PathAliases {
165            entries: vec![
166                ("~/*".into(), vec!["src/*".into()]),
167                (
168                    "@lib/*".into(),
169                    vec!["packages/lib/src/*".into(), "vendor/lib/*".into()],
170                ),
171                ("@lib/special".into(), vec!["src/special.ts".into()]),
172            ],
173        };
174        assert_eq!(aliases.candidates("~/util/strings"), ["src/util/strings"]);
175        assert_eq!(
176            aliases.candidates("@lib/a"),
177            ["packages/lib/src/a", "vendor/lib/a"]
178        );
179        assert_eq!(aliases.candidates("@lib/special"), ["src/special.ts"]);
180        assert!(aliases.candidates("lodash").is_empty());
181    }
182}