oxc_resolver 11.19.1

ESM / CJS module resolution
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
use std::{
    borrow::Cow,
    cmp::Reverse,
    fmt::Debug,
    hash::BuildHasherDefault,
    path::{Path, PathBuf},
    sync::Arc,
};

use compact_str::CompactString;
use indexmap::IndexMap;
use rustc_hash::FxHasher;
use serde::Deserialize;

use crate::{TsconfigReferences, path::PathUtil, replace_bom_with_whitespace};

/// Template variable `${configDir}` for substitution of config files
/// directory path.
///
/// NOTE: All tests cases are just a head replacement of `${configDir}`, so
///       we are constrained as such.
///
/// See <https://github.com/microsoft/TypeScript/pull/58042>.
/// Allow list: <https://github.com/microsoft/TypeScript/issues/57485#issuecomment-2027787456>
const TEMPLATE_VARIABLE: &str = "${configDir}";

const GLOB_ALL_PATTERN: &str = "**/*";

pub type CompilerOptionsPathsMap = IndexMap<String, Vec<PathBuf>, BuildHasherDefault<FxHasher>>;

/// Project Reference
///
/// <https://www.typescriptlang.org/docs/handbook/project-references.html>
#[derive(Clone, Debug, Deserialize)]
pub struct ProjectReference {
    pub path: PathBuf,
}

#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TsConfig {
    /// Whether this is the caller tsconfig.
    /// Used for final template variable substitution when all configs are extended and merged.
    #[serde(skip)]
    pub root: bool,

    /// Whether `build()` should normalize paths.
    /// Set to true when caching to ensure paths are always normalized regardless of `root`.
    #[serde(skip)]
    should_build: bool,

    /// Path to `tsconfig.json`. Contains the `tsconfig.json` filename.
    #[serde(skip)]
    pub path: PathBuf,

    #[serde(default)]
    pub files: Option<Vec<PathBuf>>,

    #[serde(default)]
    pub include: Option<Vec<PathBuf>>,

    #[serde(default)]
    pub exclude: Option<Vec<PathBuf>>,

    #[serde(default)]
    pub extends: Option<ExtendsField>,

    #[serde(default)]
    pub compiler_options: CompilerOptions,

    #[serde(default)]
    pub references: Vec<ProjectReference>,

    /// Resolved project references.
    ///
    /// Corresponds to each item in [TsConfig::references].
    #[serde(skip)]
    pub references_resolved: Vec<Arc<Self>>,
}

impl TsConfig {
    /// Parses the tsconfig from a JSON string.
    ///
    /// # Errors
    ///
    /// * Any error that can be returned by `serde_json::from_str()`.
    pub fn parse(root: bool, path: &Path, json: String) -> Result<Self, serde_json::Error> {
        let mut json = json.into_bytes();
        replace_bom_with_whitespace(&mut json);
        _ = json_strip_comments::strip_slice(&mut json);
        let mut tsconfig: Self = if json.iter().all(u8::is_ascii_whitespace) {
            Self::default()
        } else {
            serde_json::from_slice(&json)?
        };
        tsconfig.root = root;
        tsconfig.path = path.to_path_buf();
        tsconfig.compiler_options.paths_base =
            tsconfig.compiler_options.base_url.as_ref().map_or_else(
                || tsconfig.directory().to_path_buf(),
                |base_url| {
                    if base_url.to_string_lossy().starts_with(TEMPLATE_VARIABLE) {
                        base_url.clone()
                    } else {
                        tsconfig.directory().normalize_with(base_url)
                    }
                },
            );
        Ok(tsconfig)
    }

    /// Whether this is the caller tsconfig.
    /// Used for final template variable substitution when all configs are extended and merged.
    #[must_use]
    pub fn root(&self) -> bool {
        self.root
    }

    /// Whether `build()` should normalize paths.
    #[must_use]
    pub fn should_build(&self) -> bool {
        self.should_build
    }

    /// Set whether `build()` should normalize paths.
    pub fn set_should_build(&mut self, should_build: bool) {
        self.should_build = should_build;
    }

    /// Returns the path where the `tsconfig.json` was found.
    ///
    /// Contains the `tsconfig.json` filename.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Directory to `tsconfig.json`.
    ///
    /// # Panics
    ///
    /// * When the `tsconfig.json` path is misconfigured.
    #[must_use]
    pub fn directory(&self) -> &Path {
        debug_assert!(self.path.file_name().is_some());
        self.path.parent().unwrap()
    }

    /// Returns any paths to tsconfigs that should be extended by this tsconfig.
    pub(crate) fn extends(&self) -> impl Iterator<Item = &str> {
        let specifiers = match &self.extends {
            Some(ExtendsField::Single(specifier)) => {
                vec![specifier.as_str()]
            }
            Some(ExtendsField::Multiple(specifiers)) => {
                specifiers.iter().map(String::as_str).collect()
            }
            None => Vec::new(),
        };
        specifiers.into_iter()
    }

    /// Loads the given references into this tsconfig.
    ///
    /// Returns whether any references are defined in the tsconfig.
    pub(crate) fn load_references(&mut self, references: TsconfigReferences) -> bool {
        match references {
            TsconfigReferences::Disabled => {
                self.references.drain(..);
            }
            TsconfigReferences::Auto => {}
        }
        !self.references.is_empty()
    }

    /// Inherits settings from the given tsconfig into `self`.
    #[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
    pub(crate) fn extend_tsconfig(&mut self, tsconfig: &Self) {
        if self.files.is_none()
            && let Some(files) = &tsconfig.files
        {
            self.files = Some(files.clone());
        }

        if self.include.is_none()
            && let Some(include) = &tsconfig.include
        {
            self.include = Some(include.clone());
        }

        if self.exclude.is_none()
            && let Some(exclude) = &tsconfig.exclude
        {
            self.exclude = Some(exclude.clone());
        }

        let compiler_options = &mut self.compiler_options;

        if compiler_options.base_url.is_none() {
            compiler_options.base_url.clone_from(&tsconfig.compiler_options.base_url);
            if tsconfig.compiler_options.base_url.is_some() {
                compiler_options.paths_base.clone_from(&tsconfig.compiler_options.paths_base);
            }
        }
        if compiler_options.paths.is_none() {
            if compiler_options.base_url.is_none() && tsconfig.compiler_options.base_url.is_none() {
                compiler_options.paths_base.clone_from(&tsconfig.compiler_options.paths_base);
            }
            compiler_options.paths.clone_from(&tsconfig.compiler_options.paths);
        }

        if compiler_options.experimental_decorators.is_none()
            && let Some(experimental_decorators) =
                &tsconfig.compiler_options.experimental_decorators
        {
            compiler_options.experimental_decorators = Some(*experimental_decorators);
        }

        if compiler_options.emit_decorator_metadata.is_none()
            && let Some(emit_decorator_metadata) =
                &tsconfig.compiler_options.emit_decorator_metadata
        {
            compiler_options.emit_decorator_metadata = Some(*emit_decorator_metadata);
        }

        if compiler_options.use_define_for_class_fields.is_none()
            && let Some(use_define_for_class_fields) =
                &tsconfig.compiler_options.use_define_for_class_fields
        {
            compiler_options.use_define_for_class_fields = Some(*use_define_for_class_fields);
        }

        if compiler_options.rewrite_relative_import_extensions.is_none()
            && let Some(rewrite_relative_import_extensions) =
                &tsconfig.compiler_options.rewrite_relative_import_extensions
        {
            compiler_options.rewrite_relative_import_extensions =
                Some(*rewrite_relative_import_extensions);
        }

        if compiler_options.jsx.is_none()
            && let Some(jsx) = &tsconfig.compiler_options.jsx
        {
            compiler_options.jsx = Some(jsx.clone());
        }

        if compiler_options.jsx_factory.is_none()
            && let Some(jsx_factory) = &tsconfig.compiler_options.jsx_factory
        {
            compiler_options.jsx_factory = Some(jsx_factory.clone());
        }

        if compiler_options.jsx_fragment_factory.is_none()
            && let Some(jsx_fragment_factory) = &tsconfig.compiler_options.jsx_fragment_factory
        {
            compiler_options.jsx_fragment_factory = Some(jsx_fragment_factory.clone());
        }

        if compiler_options.jsx_import_source.is_none()
            && let Some(jsx_import_source) = &tsconfig.compiler_options.jsx_import_source
        {
            compiler_options.jsx_import_source = Some(jsx_import_source.clone());
        }

        if compiler_options.verbatim_module_syntax.is_none()
            && let Some(verbatim_module_syntax) = &tsconfig.compiler_options.verbatim_module_syntax
        {
            compiler_options.verbatim_module_syntax = Some(*verbatim_module_syntax);
        }

        if compiler_options.preserve_value_imports.is_none()
            && let Some(preserve_value_imports) = &tsconfig.compiler_options.preserve_value_imports
        {
            compiler_options.preserve_value_imports = Some(*preserve_value_imports);
        }

        if compiler_options.imports_not_used_as_values.is_none()
            && let Some(imports_not_used_as_values) =
                &tsconfig.compiler_options.imports_not_used_as_values
        {
            compiler_options.imports_not_used_as_values = Some(imports_not_used_as_values.clone());
        }

        if compiler_options.target.is_none()
            && let Some(target) = &tsconfig.compiler_options.target
        {
            compiler_options.target = Some(target.clone());
        }

        if compiler_options.module.is_none()
            && let Some(module) = &tsconfig.compiler_options.module
        {
            compiler_options.module = Some(module.clone());
        }

        if compiler_options.allow_js.is_none()
            && let Some(allow_js) = &tsconfig.compiler_options.allow_js
        {
            compiler_options.allow_js = Some(*allow_js);
        }

        if compiler_options.root_dirs.is_none()
            && let Some(root_dirs) = &tsconfig.compiler_options.root_dirs
        {
            compiler_options.root_dirs = Some(root_dirs.clone());
        }
    }
    /// "Build" the root tsconfig, resolve:
    ///
    /// * `{configDir}` template variable
    /// * `paths_base` for resolving paths alias
    /// * `baseUrl` to absolute path
    #[must_use]
    pub(crate) fn build(mut self) -> Self {
        // Only build if should_build is true.
        // This is controlled separately from `root` to avoid cache pollution.
        if !self.should_build {
            return self;
        }

        let config_dir = self.directory().to_path_buf();

        // Substitute template variable in `tsconfig.files`.
        if let Some(files) = self.files.take() {
            self.files = Some(files.into_iter().map(|p| self.adjust_path(p)).collect());
        }

        // Substitute template variable in `tsconfig.include`.
        if let Some(includes) = self.include.take() {
            self.include = Some(includes.into_iter().map(|p| self.adjust_path(p)).collect());
        }

        // Substitute template variable in `tsconfig.exclude`.
        if let Some(excludes) = self.exclude.take() {
            self.exclude = Some(excludes.into_iter().map(|p| self.adjust_path(p)).collect());
        }

        if let Some(base_url) = &self.compiler_options.base_url {
            self.compiler_options.base_url = Some(self.adjust_path(base_url.clone()));
        }

        if let Some(stripped_path) =
            self.compiler_options.paths_base.to_string_lossy().strip_prefix(TEMPLATE_VARIABLE)
        {
            self.compiler_options.paths_base =
                config_dir.join(stripped_path.trim_start_matches('/'));
        }

        if let Some(root_dirs) = &mut self.compiler_options.root_dirs {
            for root_dir in root_dirs.iter_mut() {
                *root_dir = config_dir.normalize_with(&root_dir);
            }
        }

        if let Some(paths_map) = &mut self.compiler_options.paths {
            // Substitute template variable in `tsconfig.compilerOptions.paths`.
            for paths in paths_map.values_mut() {
                for path in paths {
                    *path = if let Some(stripped_path) =
                        path.to_string_lossy().strip_prefix(TEMPLATE_VARIABLE)
                    {
                        config_dir.join(stripped_path.trim_start_matches('/'))
                    } else {
                        self.compiler_options.paths_base.normalize_with(&path)
                    };
                }
            }
            self.compiler_options.compiled_paths =
                Some(Arc::new(CompiledTsconfigPaths::new(paths_map)));
        } else {
            self.compiler_options.compiled_paths = None;
        }

        self
    }

    #[expect(clippy::option_if_let_else)]
    fn adjust_path(&self, path: PathBuf) -> PathBuf {
        if let Some(stripped) = path.to_string_lossy().strip_prefix(TEMPLATE_VARIABLE) {
            self.directory().join(stripped.trim_start_matches('/'))
        } else {
            self.directory().normalize_with(path)
        }
    }

    /// Resolves the given `specifier` within project references and then [CompilerOptions::paths].
    ///
    /// `specifier` can be either a real path or an alias.
    #[must_use]
    pub(crate) fn resolve_references_then_self_paths(
        &self,
        path: &Path,
        specifier: &str,
    ) -> Vec<PathBuf> {
        for tsconfig in &self.references_resolved {
            if path.starts_with(&tsconfig.compiler_options.paths_base) {
                return tsconfig.resolve_path_alias(specifier);
            }
        }
        self.resolve_path_alias(specifier)
    }

    /// Resolves the given `specifier` within the project configured by this
    /// tsconfig.
    ///
    /// `specifier` is expected to be a path alias.
    // Copied from parcel
    // <https://github.com/parcel-bundler/parcel/blob/b6224fd519f95e68d8b93ba90376fd94c8b76e69/packages/utils/node-resolver-rs/src/tsconfig.rs#L93>
    #[must_use]
    pub(crate) fn resolve_path_alias(&self, specifier: &str) -> Vec<PathBuf> {
        if specifier.starts_with('.') {
            return Vec::new();
        }

        let compiler_options = &self.compiler_options;

        let Some(paths_map) = &compiler_options.paths else {
            return vec![];
        };

        if let Some(paths) = paths_map.get(specifier) {
            return paths.clone();
        }

        if let Some(compiled_paths) = &compiler_options.compiled_paths
            && let Some(paths) = compiled_paths.resolve(specifier)
        {
            return paths;
        }

        Vec::new()
    }

    pub(crate) fn resolve_base_url(&self, specifier: &str) -> Option<PathBuf> {
        self.compiler_options
            .base_url
            .is_some()
            .then(|| self.compiler_options.paths_base.normalize_with(specifier))
    }
}

/// Compiler Options
///
/// <https://www.typescriptlang.org/tsconfig#compilerOptions>
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CompilerOptions {
    pub base_url: Option<PathBuf>,

    /// Path aliases.
    pub paths: Option<CompilerOptionsPathsMap>,

    /// Pre-compiled wildcard path aliases for faster runtime matching.
    #[serde(skip)]
    compiled_paths: Option<Arc<CompiledTsconfigPaths>>,

    /// The "base_url" at which this tsconfig is defined.
    #[serde(skip)]
    pub(crate) paths_base: PathBuf,

    /// <https://www.typescriptlang.org/tsconfig/#experimentalDecorators>
    pub experimental_decorators: Option<bool>,

    /// <https://www.typescriptlang.org/tsconfig/#emitDecoratorMetadata>
    pub emit_decorator_metadata: Option<bool>,

    /// <https://www.typescriptlang.org/tsconfig/#useDefineForClassFields>
    pub use_define_for_class_fields: Option<bool>,

    /// <https://www.typescriptlang.org/tsconfig/#rewriteRelativeImportExtensions>
    pub rewrite_relative_import_extensions: Option<bool>,

    /// <https://www.typescriptlang.org/tsconfig/#jsx>
    pub jsx: Option<String>,

    /// <https://www.typescriptlang.org/tsconfig/#jsxFactory>
    pub jsx_factory: Option<String>,

    /// <https://www.typescriptlang.org/tsconfig/#jsxFragmentFactory>
    pub jsx_fragment_factory: Option<String>,

    /// <https://www.typescriptlang.org/tsconfig/#jsxImportSource>
    pub jsx_import_source: Option<String>,

    /// <https://www.typescriptlang.org/tsconfig/#verbatimModuleSyntax>
    pub verbatim_module_syntax: Option<bool>,

    /// <https://www.typescriptlang.org/tsconfig/#preserveValueImports>
    pub preserve_value_imports: Option<bool>,

    /// <https://www.typescriptlang.org/tsconfig/#importsNotUsedAsValues>
    pub imports_not_used_as_values: Option<String>,

    /// <https://www.typescriptlang.org/tsconfig/#target>
    pub target: Option<String>,

    /// <https://www.typescriptlang.org/tsconfig/#module>
    pub module: Option<String>,

    /// <https://www.typescriptlang.org/tsconfig/#allowJs>
    pub allow_js: Option<bool>,

    /// <https://www.typescriptlang.org/tsconfig/#rootDirs>
    pub root_dirs: Option<Vec<PathBuf>>,
}

/// Value for the "extends" field.
///
/// <https://www.typescriptlang.org/tsconfig/#extends>
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
#[serde(untagged)]
pub enum ExtendsField {
    Single(String),
    Multiple(Vec<String>),
}

#[derive(Clone, Copy)]
enum GlobPattern<'a> {
    Pattern(&'a [PathBuf]),
    All,
}

/// Tsconfig resolver
impl TsConfig {
    pub(crate) fn resolve_tsconfig_solution(tsconfig: Arc<Self>, path: &Path) -> Arc<Self> {
        if !tsconfig.references_resolved.is_empty()
            && tsconfig.is_file_extension_allowed_in_tsconfig(path)
            && !tsconfig.is_file_included_in_tsconfig(path)
            && let Some(solution_tsconfig) = tsconfig
                .references_resolved
                .iter()
                .find(|referenced| referenced.is_file_included_in_tsconfig(path))
                .map(Arc::clone)
        {
            return solution_tsconfig;
        }
        tsconfig
    }

    fn is_file_included_in_tsconfig(&self, path: &Path) -> bool {
        // 1. Check files array (highest priority - overrides exclude)
        if self.files.as_ref().is_some_and(|files| files.iter().any(|file| Path::new(file) == path))
        {
            return true;
        }
        // 2. Check include patterns
        let is_included = self.include.as_ref().map_or_else(
            || {
                if self.files.is_some() {
                    false
                } else {
                    self.is_glob_matches(path, GlobPattern::All)
                }
            },
            |include_patterns| self.is_glob_matches(path, GlobPattern::Pattern(include_patterns)),
        );
        // 3. Check exclude patterns
        if is_included {
            return self.exclude.as_ref().is_none_or(|exclude_patterns| {
                !self.is_glob_matches(path, GlobPattern::Pattern(exclude_patterns))
            });
        }
        false
    }

    fn is_glob_matches(&self, path: &Path, pattern: GlobPattern) -> bool {
        let path_str = path.to_string_lossy().replace('\\', "/");
        match pattern {
            GlobPattern::All => self.is_glob_match(GLOB_ALL_PATTERN, path, &path_str),
            GlobPattern::Pattern(patterns) => patterns.iter().any(|pattern| {
                let pattern = pattern.to_string_lossy().replace('\\', "/");
                self.is_glob_match(pattern.as_ref(), path, &path_str)
            }),
        }
    }

    fn is_glob_match(&self, pattern: &str, path: &Path, path_str: &str) -> bool {
        if pattern == path_str {
            return true;
        }
        // Special case: **/* matches everything
        if pattern == GLOB_ALL_PATTERN {
            return true;
        }
        // Normalize pattern: add implicit /**/* for directory patterns
        // Find the part after the last '/' to check if it looks like a directory
        let after_last_slash = pattern.rsplit('/').next().unwrap_or(pattern);
        let needs_implicit_glob = !after_last_slash.contains(['.', '*', '?']);
        let pattern = if needs_implicit_glob {
            Cow::Owned(format!(
                "{pattern}{}",
                if pattern.ends_with('/') { "**/*" } else { "/**/*" }
            ))
        } else {
            Cow::Borrowed(pattern)
        };
        // Fast check: if pattern ends with *, filename must have valid extension
        if pattern.ends_with('*') && !self.is_file_extension_allowed_in_tsconfig(path) {
            return false;
        }
        fast_glob::glob_match(pattern.as_ref(), path_str)
    }

    fn is_file_extension_allowed_in_tsconfig(&self, path: &Path) -> bool {
        const TS_EXTENSIONS: [&str; 4] = ["ts", "tsx", "mts", "cts"];
        const JS_EXTENSIONS: [&str; 4] = ["js", "jsx", "mjs", "cjs"];
        let allow_js = self.compiler_options.allow_js.is_some_and(|b| b);
        path.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| {
            TS_EXTENSIONS.contains(&ext)
                || if allow_js { JS_EXTENSIONS.contains(&ext) } else { false }
        })
    }
}

#[derive(Clone, Debug, Default)]
struct CompiledTsconfigPaths {
    wildcard_patterns: Vec<CompiledTsconfigPathPattern>,
}

#[derive(Clone, Debug)]
struct CompiledTsconfigPathPattern {
    prefix: CompactString,
    suffix: CompactString,
    prefix_len: usize,
    suffix_len: usize,
    targets: Vec<CompiledTsconfigPathTarget>,
}

#[derive(Clone, Debug)]
enum CompiledTsconfigPathTarget {
    Static(PathBuf),
    Wildcard { prefix: CompactString, suffix: CompactString },
}

impl CompiledTsconfigPaths {
    fn new(paths_map: &CompilerOptionsPathsMap) -> Self {
        let mut wildcard_patterns = paths_map
            .iter()
            .filter_map(|(key, paths)| {
                let (prefix, suffix) = key.split_once('*')?;
                let targets = paths
                    .iter()
                    .map(|path| {
                        let path_str = path.to_string_lossy();
                        path_str.split_once('*').map_or_else(
                            || CompiledTsconfigPathTarget::Static(path.clone()),
                            |(target_prefix, target_suffix)| CompiledTsconfigPathTarget::Wildcard {
                                prefix: CompactString::new(target_prefix),
                                suffix: CompactString::new(target_suffix),
                            },
                        )
                    })
                    .collect::<Vec<_>>();
                Some(CompiledTsconfigPathPattern {
                    prefix: CompactString::new(prefix),
                    suffix: CompactString::new(suffix),
                    prefix_len: prefix.len(),
                    suffix_len: suffix.len(),
                    targets,
                })
            })
            .collect::<Vec<_>>();

        // Match longer prefixes first. Equal-length prefixes keep insertion order.
        wildcard_patterns.sort_by_key(|pattern| Reverse(pattern.prefix_len));

        Self { wildcard_patterns }
    }

    fn resolve(&self, specifier: &str) -> Option<Vec<PathBuf>> {
        self.wildcard_patterns.iter().find_map(|pattern| {
            if !specifier.starts_with(pattern.prefix.as_str())
                || !specifier.ends_with(pattern.suffix.as_str())
                || specifier.len() < pattern.prefix_len + pattern.suffix_len
            {
                return None;
            }
            let wildcard = &specifier[pattern.prefix_len..specifier.len() - pattern.suffix_len];
            Some(pattern.targets.iter().map(|target| target.resolve(wildcard)).collect())
        })
    }
}

impl CompiledTsconfigPathTarget {
    fn resolve(&self, wildcard: &str) -> PathBuf {
        match self {
            Self::Static(path) => path.clone(),
            Self::Wildcard { prefix, suffix } => {
                let mut resolved =
                    String::with_capacity(prefix.len() + wildcard.len() + suffix.len());
                resolved.push_str(prefix.as_str());
                resolved.push_str(wildcard);
                resolved.push_str(suffix.as_str());
                PathBuf::from(resolved)
            }
        }
    }
}