-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
1845 lines (1742 loc) · 74.7 KB
/
lib.rs
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
//! # Oxc Resolver
//!
//! Node.js [CommonJS][cjs] and [ECMAScript][esm] Module Resolution.
//!
//! Released on [crates.io](https://crates.io/crates/oxc_resolver) and [npm](https://www.npmjs.com/package/oxc-resolver).
//!
//! A module resolution is the process of finding the file referenced by a module specifier in
//! `import "specifier"` or `require("specifier")`.
//!
//! All [configuration options](ResolveOptions) are aligned with webpack's [enhanced-resolve].
//!
//! ## Terminology
//!
//! ### Specifier
//!
//! For [CommonJS modules][cjs],
//! the specifier is the string passed to the `require` function. e.g. `"id"` in `require("id")`.
//!
//! For [ECMAScript modules][esm],
//! the specifier of an `import` statement is the string after the `from` keyword,
//! e.g. `'specifier'` in `import 'specifier'` or `import { sep } from 'specifier'`.
//! Specifiers are also used in export from statements, and as the argument to an `import()` expression.
//!
//! This is also named "request" in some places.
//!
//! ## References:
//!
//! * Algorithm adapted from Node.js [CommonJS Module Resolution Algorithm] and [ECMAScript Module Resolution Algorithm].
//! * Tests are ported from [enhanced-resolve].
//! * Some code is adapted from [parcel-resolver].
//! * The documentation is copied from [webpack's resolve configuration](https://webpack.js.org/configuration/resolve).
//!
//! [enhanced-resolve]: https://github.com/webpack/enhanced-resolve
//! [CommonJS Module Resolution Algorithm]: https://nodejs.org/api/modules.html#all-together
//! [ECMAScript Module Resolution Algorithm]: https://nodejs.org/api/esm.html#resolution-algorithm-specification
//! [parcel-resolver]: https://github.com/parcel-bundler/parcel/blob/v2/packages/utils/node-resolver-rs
//! [cjs]: https://nodejs.org/api/modules.html
//! [esm]: https://nodejs.org/api/esm.html
//!
//! ## Feature flags
#![cfg_attr(feature = "document-features", doc = document_features::document_features!())]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
//!
//! ## Example
//!
//! ```rust,ignore
#![doc = include_str!("../examples/resolver.rs")]
//! ```
mod builtins;
mod cache;
mod context;
mod error;
mod file_system;
mod options;
mod package_json;
mod path;
mod resolution;
mod specifier;
mod tsconfig;
#[cfg(test)]
mod tests;
use dashmap::{mapref::one::Ref, DashMap};
use rustc_hash::FxHashSet;
use serde_json::Value as JSONValue;
use std::{
borrow::Cow,
cmp::Ordering,
ffi::OsStr,
fmt,
path::{Component, Path, PathBuf},
sync::Arc,
};
pub use crate::{
builtins::NODEJS_BUILTINS,
error::{JSONError, ResolveError, SpecifierError},
file_system::{FileMetadata, FileSystem, FileSystemOs},
options::{
Alias, AliasValue, EnforceExtension, ResolveOptions, Restriction, TsconfigOptions,
TsconfigReferences,
},
package_json::PackageJson,
resolution::Resolution,
};
use crate::{
cache::{Cache, CachedPath},
context::ResolveContext as Ctx,
package_json::JSONMap,
path::{PathUtil, SLASH_START},
specifier::Specifier,
tsconfig::ExtendsField,
tsconfig::{ProjectReference, TsConfig},
};
type ResolveResult = Result<Option<CachedPath>, ResolveError>;
/// Context returned from the [Resolver::resolve_with_context] API
#[derive(Debug, Default, Clone)]
pub struct ResolveContext {
/// Files that was found on file system
pub file_dependencies: FxHashSet<PathBuf>,
/// Dependencies that was not found on file system
pub missing_dependencies: FxHashSet<PathBuf>,
}
/// Resolver with the current operating system as the file system
pub type Resolver = ResolverGeneric<FileSystemOs>;
/// Generic implementation of the resolver, can be configured by the [FileSystem] trait
pub struct ResolverGeneric<Fs> {
options: ResolveOptions,
cache: Arc<Cache<Fs>>,
#[cfg(feature = "yarn_pnp")]
pnp_cache: Arc<DashMap<CachedPath, Option<pnp::Manifest>>>,
}
impl<Fs> fmt::Debug for ResolverGeneric<Fs> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.options.fmt(f)
}
}
impl<Fs: FileSystem + Default> Default for ResolverGeneric<Fs> {
fn default() -> Self {
Self::new(ResolveOptions::default())
}
}
impl<Fs: FileSystem + Default> ResolverGeneric<Fs> {
pub fn new(options: ResolveOptions) -> Self {
Self {
options: options.sanitize(),
cache: Arc::new(Cache::new(Fs::default())),
#[cfg(feature = "yarn_pnp")]
pnp_cache: Arc::new(DashMap::default()),
}
}
}
impl<Fs: FileSystem> ResolverGeneric<Fs> {
pub fn new_with_file_system(file_system: Fs, options: ResolveOptions) -> Self {
Self {
options: options.sanitize(),
cache: Arc::new(Cache::new(file_system)),
#[cfg(feature = "yarn_pnp")]
pnp_cache: Arc::new(DashMap::default()),
}
}
/// Clone the resolver using the same underlying cache.
#[must_use]
pub fn clone_with_options(&self, options: ResolveOptions) -> Self {
Self {
options: options.sanitize(),
cache: Arc::clone(&self.cache),
#[cfg(feature = "yarn_pnp")]
pnp_cache: Arc::clone(&self.pnp_cache),
}
}
/// Returns the options.
pub fn options(&self) -> &ResolveOptions {
&self.options
}
/// Clear the underlying cache.
pub fn clear_cache(&self) {
self.cache.clear();
}
/// Resolve `specifier` at an absolute path to a `directory`.
///
/// A specifier is the string passed to require or import, i.e. `require("specifier")` or `import "specifier"`.
///
/// `directory` must be an **absolute** path to a directory where the specifier is resolved against.
/// For CommonJS modules, it is the `__dirname` variable that contains the absolute path to the folder containing current module.
/// For ECMAScript modules, it is the value of `import.meta.url`.
///
/// # Errors
///
/// * See [ResolveError]
pub fn resolve<P: AsRef<Path>>(
&self,
directory: P,
specifier: &str,
) -> Result<Resolution, ResolveError> {
let mut ctx = Ctx::default();
self.resolve_tracing(directory.as_ref(), specifier, &mut ctx)
}
/// Resolve `specifier` at absolute `path` with [ResolveContext]
///
/// # Errors
///
/// * See [ResolveError]
pub fn resolve_with_context<P: AsRef<Path>>(
&self,
directory: P,
specifier: &str,
resolve_context: &mut ResolveContext,
) -> Result<Resolution, ResolveError> {
let mut ctx = Ctx::default();
ctx.init_file_dependencies();
let result = self.resolve_tracing(directory.as_ref(), specifier, &mut ctx);
if let Some(deps) = &mut ctx.file_dependencies {
resolve_context.file_dependencies.extend(deps.drain(..));
}
if let Some(deps) = &mut ctx.missing_dependencies {
resolve_context.missing_dependencies.extend(deps.drain(..));
}
result
}
/// Wrap `resolve_impl` with `tracing` information
fn resolve_tracing(
&self,
directory: &Path,
specifier: &str,
ctx: &mut Ctx,
) -> Result<Resolution, ResolveError> {
let span = tracing::debug_span!("resolve", path = ?directory, specifier = specifier);
let _enter = span.enter();
let r = self.resolve_impl(directory, specifier, ctx);
match &r {
Ok(r) => {
tracing::debug!(options = ?self.options, path = ?directory, specifier = specifier, ret = ?r.path);
}
Err(err) => {
tracing::debug!(options = ?self.options, path = ?directory, specifier = specifier, err = ?err);
}
};
r
}
fn resolve_impl(
&self,
path: &Path,
specifier: &str,
ctx: &mut Ctx,
) -> Result<Resolution, ResolveError> {
ctx.with_fully_specified(self.options.fully_specified);
let cached_path = self.cache.value(path);
let cached_path = self.require(&cached_path, specifier, ctx)?;
let path = self.load_realpath(&cached_path)?;
// enhanced-resolve: restrictions
self.check_restrictions(&path)?;
let package_json = cached_path.find_package_json(&self.cache.fs, &self.options, ctx)?;
if let Some(package_json) = &package_json {
// path must be inside the package.
debug_assert!(path.starts_with(package_json.directory()));
}
Ok(Resolution {
path,
query: ctx.query.take(),
fragment: ctx.fragment.take(),
package_json,
})
}
/// require(X) from module at path Y
///
/// X: specifier
/// Y: path
///
/// <https://nodejs.org/api/modules.html#all-together>
fn require(
&self,
cached_path: &CachedPath,
specifier: &str,
ctx: &mut Ctx,
) -> Result<CachedPath, ResolveError> {
ctx.test_for_infinite_recursion()?;
// enhanced-resolve: parse
let (parsed, try_fragment_as_path) = self.load_parse(cached_path, specifier, ctx)?;
if let Some(path) = try_fragment_as_path {
return Ok(path);
}
self.require_without_parse(cached_path, parsed.path(), ctx)
}
fn require_without_parse(
&self,
cached_path: &CachedPath,
specifier: &str,
ctx: &mut Ctx,
) -> Result<CachedPath, ResolveError> {
// tsconfig-paths
if let Some(path) = self.load_tsconfig_paths(cached_path, specifier, &mut Ctx::default())? {
return Ok(path);
}
// enhanced-resolve: try alias
if let Some(path) = self.load_alias(cached_path, specifier, &self.options.alias, ctx)? {
return Ok(path);
}
let result = match Path::new(specifier).components().next() {
// 2. If X begins with '/'
Some(Component::RootDir | Component::Prefix(_)) => {
self.require_absolute(cached_path, specifier, ctx)
}
// 3. If X begins with './' or '/' or '../'
Some(Component::CurDir | Component::ParentDir) => {
self.require_relative(cached_path, specifier, ctx)
}
// 4. If X begins with '#'
Some(Component::Normal(_)) if specifier.as_bytes()[0] == b'#' => {
self.require_hash(cached_path, specifier, ctx)
}
_ => {
// 1. If X is a core module,
// a. return the core module
// b. STOP
self.require_core(specifier)?;
// (ESM) 5. Otherwise,
// Note: specifier is now a bare specifier.
// Set resolved the result of PACKAGE_RESOLVE(specifier, parentURL).
self.require_bare(cached_path, specifier, ctx)
}
};
result.or_else(|err| {
if err.is_ignore() {
return Err(err);
}
// enhanced-resolve: try fallback
self.load_alias(cached_path, specifier, &self.options.fallback, ctx)
.and_then(|value| value.ok_or(err))
})
}
// PACKAGE_RESOLVE(packageSpecifier, parentURL)
// 3. If packageSpecifier is a Node.js builtin module name, then
// 1. Return the string "node:" concatenated with packageSpecifier.
fn require_core(&self, specifier: &str) -> Result<(), ResolveError> {
if self.options.builtin_modules {
let starts_with_node = specifier.starts_with("node:");
if starts_with_node || NODEJS_BUILTINS.binary_search(&specifier).is_ok() {
let mut specifier = specifier.to_string();
if !starts_with_node {
specifier = format!("node:{specifier}");
}
return Err(ResolveError::Builtin(specifier));
}
}
Ok(())
}
fn require_absolute(
&self,
cached_path: &CachedPath,
specifier: &str,
ctx: &mut Ctx,
) -> Result<CachedPath, ResolveError> {
// Make sure only path prefixes gets called
debug_assert!(Path::new(specifier)
.components()
.next()
.is_some_and(|c| matches!(c, Component::RootDir | Component::Prefix(_))));
if !self.options.prefer_relative && self.options.prefer_absolute {
if let Ok(path) = self.load_package_self_or_node_modules(cached_path, specifier, ctx) {
return Ok(path);
}
}
if let Some(path) = self.load_roots(specifier, ctx) {
return Ok(path);
}
// 2. If X begins with '/'
// a. set Y to be the file system root
let path = self.cache.value(Path::new(specifier));
if let Some(path) = self.load_as_file_or_directory(&path, specifier, ctx)? {
return Ok(path);
}
Err(ResolveError::NotFound(specifier.to_string()))
}
// 3. If X begins with './' or '/' or '../'
fn require_relative(
&self,
cached_path: &CachedPath,
specifier: &str,
ctx: &mut Ctx,
) -> Result<CachedPath, ResolveError> {
// Make sure only relative or normal paths gets called
debug_assert!(Path::new(specifier).components().next().is_some_and(|c| matches!(
c,
Component::CurDir | Component::ParentDir | Component::Normal(_)
)));
let path = cached_path.path().normalize_with(specifier);
let cached_path = self.cache.value(&path);
// a. LOAD_AS_FILE(Y + X)
// b. LOAD_AS_DIRECTORY(Y + X)
if let Some(path) = self.load_as_file_or_directory(&cached_path, specifier, ctx)? {
return Ok(path);
}
// c. THROW "not found"
Err(ResolveError::NotFound(specifier.to_string()))
}
fn require_hash(
&self,
cached_path: &CachedPath,
specifier: &str,
ctx: &mut Ctx,
) -> Result<CachedPath, ResolveError> {
debug_assert_eq!(specifier.chars().next(), Some('#'));
// a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))
if let Some(path) = self.load_package_imports(cached_path, specifier, ctx)? {
return Ok(path);
}
self.load_package_self_or_node_modules(cached_path, specifier, ctx)
}
fn require_bare(
&self,
cached_path: &CachedPath,
specifier: &str,
ctx: &mut Ctx,
) -> Result<CachedPath, ResolveError> {
// Make sure no other path prefixes gets called
debug_assert!(Path::new(specifier)
.components()
.next()
.is_some_and(|c| matches!(c, Component::Normal(_))));
if self.options.prefer_relative {
if let Ok(path) = self.require_relative(cached_path, specifier, ctx) {
return Ok(path);
}
}
self.load_package_self_or_node_modules(cached_path, specifier, ctx)
}
/// enhanced-resolve: ParsePlugin.
///
/// It's allowed to escape # as \0# to avoid parsing it as fragment.
/// enhanced-resolve will try to resolve requests containing `#` as path and as fragment,
/// so it will automatically figure out if `./some#thing` means `.../some.js#thing` or `.../some#thing.js`.
/// When a # is resolved as path it will be escaped in the result. Here: `.../some\0#thing.js`.
///
/// <https://github.com/webpack/enhanced-resolve#escaping>
fn load_parse<'s>(
&self,
cached_path: &CachedPath,
specifier: &'s str,
ctx: &mut Ctx,
) -> Result<(Specifier<'s>, Option<CachedPath>), ResolveError> {
let parsed = Specifier::parse(specifier).map_err(ResolveError::Specifier)?;
ctx.with_query_fragment(parsed.query, parsed.fragment);
// There is an edge-case where a request with # can be a path or a fragment -> try both
if ctx.fragment.is_some() && ctx.query.is_none() {
let specifier = parsed.path();
let fragment = ctx.fragment.take().unwrap();
let path = format!("{specifier}{fragment}");
if let Ok(path) = self.require_without_parse(cached_path, &path, ctx) {
return Ok((parsed, Some(path)));
}
ctx.fragment.replace(fragment);
}
Ok((parsed, None))
}
fn load_package_self_or_node_modules(
&self,
cached_path: &CachedPath,
specifier: &str,
ctx: &mut Ctx,
) -> Result<CachedPath, ResolveError> {
let (_, subpath) = Self::parse_package_specifier(specifier);
if subpath.is_empty() {
ctx.with_fully_specified(false);
}
// 5. LOAD_PACKAGE_SELF(X, dirname(Y))
if let Some(path) = self.load_package_self(cached_path, specifier, ctx)? {
return Ok(path);
}
// 6. LOAD_NODE_MODULES(X, dirname(Y))
if let Some(path) = self.load_node_modules(cached_path, specifier, ctx)? {
return Ok(path);
}
// 7. THROW "not found"
Err(ResolveError::NotFound(specifier.to_string()))
}
/// LOAD_PACKAGE_IMPORTS(X, DIR)
fn load_package_imports(
&self,
cached_path: &CachedPath,
specifier: &str,
ctx: &mut Ctx,
) -> ResolveResult {
// 1. Find the closest package scope SCOPE to DIR.
// 2. If no scope was found, return.
let Some(package_json) =
cached_path.find_package_json(&self.cache.fs, &self.options, ctx)?
else {
return Ok(None);
};
// 3. If the SCOPE/package.json "imports" is null or undefined, return.
// 4. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE), ["node", "require"]) defined in the ESM resolver.
if let Some(path) = self.package_imports_resolve(specifier, &package_json, ctx)? {
// 5. RESOLVE_ESM_MATCH(MATCH).
return self.resolve_esm_match(specifier, &path, ctx);
}
Ok(None)
}
fn load_as_file(&self, cached_path: &CachedPath, ctx: &mut Ctx) -> ResolveResult {
// enhanced-resolve feature: extension_alias
if let Some(path) = self.load_extension_alias(cached_path, ctx)? {
return Ok(Some(path));
}
if self.options.enforce_extension.is_disabled() {
// 1. If X is a file, load X as its file extension format. STOP
if let Some(path) = self.load_alias_or_file(cached_path, ctx)? {
return Ok(Some(path));
}
}
// 2. If X.js is a file, load X.js as JavaScript text. STOP
// 3. If X.json is a file, parse X.json to a JavaScript Object. STOP
// 4. If X.node is a file, load X.node as binary addon. STOP
if let Some(path) = self.load_extensions(cached_path, &self.options.extensions, ctx)? {
return Ok(Some(path));
}
Ok(None)
}
fn load_as_directory(&self, cached_path: &CachedPath, ctx: &mut Ctx) -> ResolveResult {
// TODO: Only package.json is supported, so warn about having other values
// Checking for empty files is needed for omitting checks on package.json
// 1. If X/package.json is a file,
if !self.options.description_files.is_empty() {
// a. Parse X/package.json, and look for "main" field.
if let Some(package_json) =
cached_path.package_json(&self.cache.fs, &self.options, ctx)?
{
// b. If "main" is a falsy value, GOTO 2.
for main_field in package_json.main_fields(&self.options.main_fields) {
// ref https://github.com/webpack/enhanced-resolve/blob/main/lib/MainFieldPlugin.js#L66-L67
let main_field =
if main_field.starts_with("./") || main_field.starts_with("../") {
Cow::Borrowed(main_field)
} else {
Cow::Owned(format!("./{main_field}"))
};
// c. let M = X + (json main field)
let main_field_path = cached_path.path().normalize_with(main_field.as_ref());
// d. LOAD_AS_FILE(M)
let cached_path = self.cache.value(&main_field_path);
if let Ok(Some(path)) = self.load_as_file(&cached_path, ctx) {
return Ok(Some(path));
}
// e. LOAD_INDEX(M)
if let Some(path) = self.load_index(&cached_path, ctx)? {
return Ok(Some(path));
}
}
// f. LOAD_INDEX(X) DEPRECATED
// g. THROW "not found"
}
}
// 2. LOAD_INDEX(X)
self.load_index(cached_path, ctx)
}
fn load_as_file_or_directory(
&self,
cached_path: &CachedPath,
specifier: &str,
ctx: &mut Ctx,
) -> ResolveResult {
if self.options.resolve_to_context {
return Ok(cached_path.is_dir(&self.cache.fs, ctx).then(|| cached_path.clone()));
}
if !specifier.ends_with('/') {
if let Some(path) = self.load_as_file(cached_path, ctx)? {
return Ok(Some(path));
}
}
if cached_path.is_dir(&self.cache.fs, ctx) {
if let Some(path) = self.load_as_directory(cached_path, ctx)? {
return Ok(Some(path));
}
}
Ok(None)
}
fn load_extensions(
&self,
path: &CachedPath,
extensions: &[String],
ctx: &mut Ctx,
) -> ResolveResult {
if ctx.fully_specified {
return Ok(None);
}
let path = path.path().as_os_str();
for extension in extensions {
let mut path_with_extension = path.to_os_string();
path_with_extension.reserve_exact(extension.len());
path_with_extension.push(extension);
let cached_path = self.cache.value(Path::new(&path_with_extension));
if let Some(path) = self.load_alias_or_file(&cached_path, ctx)? {
return Ok(Some(path));
}
}
Ok(None)
}
fn load_realpath(&self, cached_path: &CachedPath) -> Result<PathBuf, ResolveError> {
if self.options.symlinks {
cached_path.realpath(&self.cache.fs).map_err(ResolveError::from)
} else {
Ok(cached_path.to_path_buf())
}
}
fn check_restrictions(&self, path: &Path) -> Result<(), ResolveError> {
// https://github.com/webpack/enhanced-resolve/blob/a998c7d218b7a9ec2461fc4fddd1ad5dd7687485/lib/RestrictionsPlugin.js#L19-L24
fn is_inside(path: &Path, parent: &Path) -> bool {
if !path.starts_with(parent) {
return false;
}
if path.as_os_str().len() == parent.as_os_str().len() {
return true;
}
path.strip_prefix(parent).is_ok_and(|p| p == Path::new("./"))
}
for restriction in &self.options.restrictions {
match restriction {
Restriction::Path(restricted_path) => {
if !is_inside(path, restricted_path) {
return Err(ResolveError::Restriction(
path.to_path_buf(),
restricted_path.clone(),
));
}
}
Restriction::RegExp(_) => {
return Err(ResolveError::Unimplemented("Restriction with regex"))
}
}
}
Ok(())
}
fn load_index(&self, cached_path: &CachedPath, ctx: &mut Ctx) -> ResolveResult {
for main_file in &self.options.main_files {
let main_path = cached_path.path().normalize_with(main_file);
let cached_path = self.cache.value(&main_path);
if self.options.enforce_extension.is_disabled() {
if let Some(path) = self.load_alias_or_file(&cached_path, ctx)? {
return Ok(Some(path));
}
}
// 1. If X/index.js is a file, load X/index.js as JavaScript text. STOP
// 2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
// 3. If X/index.node is a file, load X/index.node as binary addon. STOP
if let Some(path) = self.load_extensions(&cached_path, &self.options.extensions, ctx)? {
return Ok(Some(path));
}
}
Ok(None)
}
fn load_alias_or_file(&self, cached_path: &CachedPath, ctx: &mut Ctx) -> ResolveResult {
if !self.options.alias_fields.is_empty() {
if let Some(package_json) =
cached_path.find_package_json(&self.cache.fs, &self.options, ctx)?
{
if let Some(path) =
self.load_browser_field(cached_path, None, &package_json, ctx)?
{
return Ok(Some(path));
}
}
}
// enhanced-resolve: try file as alias
let alias_specifier = cached_path.path().to_string_lossy();
if let Some(path) =
self.load_alias(cached_path, &alias_specifier, &self.options.alias, ctx)?
{
return Ok(Some(path));
}
if cached_path.is_file(&self.cache.fs, ctx) {
return Ok(Some(cached_path.clone()));
}
Ok(None)
}
fn load_node_modules(
&self,
cached_path: &CachedPath,
specifier: &str,
ctx: &mut Ctx,
) -> ResolveResult {
#[cfg(feature = "yarn_pnp")]
{
if self.options.enable_pnp {
if let Some(resolved_path) = self.load_pnp(cached_path, specifier, ctx)? {
return Ok(Some(resolved_path));
}
}
}
let (package_name, subpath) = Self::parse_package_specifier(specifier);
// 1. let DIRS = NODE_MODULES_PATHS(START)
// 2. for each DIR in DIRS:
for module_name in &self.options.modules {
for cached_path in std::iter::successors(Some(cached_path), |p| p.parent()) {
// Skip if /path/to/node_modules does not exist
if !cached_path.is_dir(&self.cache.fs, ctx) {
continue;
}
let Some(cached_path) = self.get_module_directory(cached_path, module_name, ctx)
else {
continue;
};
// Optimize node_modules lookup by inspecting whether the package exists
// From LOAD_PACKAGE_EXPORTS(X, DIR)
// 1. Try to interpret X as a combination of NAME and SUBPATH where the name
// may have a @scope/ prefix and the subpath begins with a slash (`/`).
if !package_name.is_empty() {
let package_path = cached_path.path().normalize_with(package_name);
let cached_path = self.cache.value(&package_path);
// Try foo/node_modules/package_name
if cached_path.is_dir(&self.cache.fs, ctx) {
// a. LOAD_PACKAGE_EXPORTS(X, DIR)
if let Some(path) =
self.load_package_exports(specifier, subpath, &cached_path, ctx)?
{
return Ok(Some(path));
}
} else {
// foo/node_modules/package_name is not a directory, so useless to check inside it
if !subpath.is_empty() {
continue;
}
// Skip if the directory lead to the scope package does not exist
// i.e. `foo/node_modules/@scope` is not a directory for `foo/node_modules/@scope/package`
if package_name.starts_with('@') {
if let Some(path) = cached_path.parent() {
if !path.is_dir(&self.cache.fs, ctx) {
continue;
}
}
}
}
}
// Try as file or directory for all other cases
// b. LOAD_AS_FILE(DIR/X)
// c. LOAD_AS_DIRECTORY(DIR/X)
let node_module_file = cached_path.path().normalize_with(specifier);
let cached_path = self.cache.value(&node_module_file);
if let Some(path) = self.load_as_file_or_directory(&cached_path, specifier, ctx)? {
return Ok(Some(path));
}
}
}
Ok(None)
}
#[cfg(feature = "yarn_pnp")]
fn find_pnp_manifest(
&self,
cached_path: &CachedPath,
) -> Ref<'_, CachedPath, Option<pnp::Manifest>> {
let entry = self
.pnp_cache
.entry(cached_path.clone())
.or_insert_with(|| pnp::find_pnp_manifest(cached_path.path()).unwrap());
entry.downgrade()
}
#[cfg(feature = "yarn_pnp")]
fn load_pnp(
&self,
cached_path: &CachedPath,
specifier: &str,
ctx: &mut Ctx,
) -> Result<Option<CachedPath>, ResolveError> {
let pnp_manifest = self.find_pnp_manifest(cached_path);
if let Some(pnp_manifest) = pnp_manifest.as_ref() {
// `resolve_to_unqualified` requires a trailing slash
let mut path = cached_path.to_path_buf();
path.push("");
let resolution =
pnp::resolve_to_unqualified_via_manifest(pnp_manifest, specifier, path);
match resolution {
Ok(pnp::Resolution::Resolved(path, subpath)) => {
let cached_path = self.cache.value(&path);
let export_resolution = self.load_package_self(&cached_path, specifier, ctx)?;
// can be found in pnp cached folder
if export_resolution.is_some() {
return Ok(export_resolution);
}
let inner_request = subpath.map_or_else(
|| ".".to_string(),
|mut p| {
p.insert_str(0, "./");
p
},
);
let inner_resolver = self.clone_with_options(self.options().clone());
// try as file or directory `path` in the pnp folder
let Ok(inner_resolution) = inner_resolver.resolve(&path, &inner_request) else {
return Err(ResolveError::NotFound(specifier.to_string()));
};
Ok(Some(self.cache.value(inner_resolution.path())))
}
Ok(pnp::Resolution::Skipped) => Ok(None),
Err(_) => Err(ResolveError::NotFound(specifier.to_string())),
}
} else {
Ok(None)
}
}
fn get_module_directory(
&self,
cached_path: &CachedPath,
module_name: &str,
ctx: &mut Ctx,
) -> Option<CachedPath> {
if module_name == "node_modules" {
cached_path.cached_node_modules(&self.cache, ctx)
} else if cached_path.path().components().next_back()
== Some(Component::Normal(OsStr::new(module_name)))
{
Some(cached_path.clone())
} else {
cached_path.module_directory(module_name, &self.cache, ctx)
}
}
fn load_package_exports(
&self,
specifier: &str,
subpath: &str,
cached_path: &CachedPath,
ctx: &mut Ctx,
) -> ResolveResult {
// 2. If X does not match this pattern or DIR/NAME/package.json is not a file,
// return.
let Some(package_json) = cached_path.package_json(&self.cache.fs, &self.options, ctx)?
else {
return Ok(None);
};
// 3. Parse DIR/NAME/package.json, and look for "exports" field.
// 4. If "exports" is null or undefined, return.
// 5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH,
// `package.json` "exports", ["node", "require"]) defined in the ESM resolver.
// Note: The subpath is not prepended with a dot on purpose
for exports in package_json.exports_fields(&self.options.exports_fields) {
if let Some(path) = self.package_exports_resolve(
cached_path.path(),
&format!(".{subpath}"),
exports,
ctx,
)? {
// 6. RESOLVE_ESM_MATCH(MATCH)
return self.resolve_esm_match(specifier, &path, ctx);
};
}
Ok(None)
}
fn load_package_self(
&self,
cached_path: &CachedPath,
specifier: &str,
ctx: &mut Ctx,
) -> ResolveResult {
// 1. Find the closest package scope SCOPE to DIR.
// 2. If no scope was found, return.
let Some(package_json) =
cached_path.find_package_json(&self.cache.fs, &self.options, ctx)?
else {
return Ok(None);
};
// 3. If the SCOPE/package.json "exports" is null or undefined, return.
// 4. If the SCOPE/package.json "name" is not the first segment of X, return.
if let Some(subpath) = package_json
.name
.as_ref()
.and_then(|package_name| Self::strip_package_name(specifier, package_name))
{
// 5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE),
// "." + X.slice("name".length), `package.json` "exports", ["node", "require"])
// defined in the ESM resolver.
let package_url = package_json.directory();
// Note: The subpath is not prepended with a dot on purpose
// because `package_exports_resolve` matches subpath without the leading dot.
for exports in package_json.exports_fields(&self.options.exports_fields) {
if let Some(cached_path) =
self.package_exports_resolve(package_url, &format!(".{subpath}"), exports, ctx)?
{
// 6. RESOLVE_ESM_MATCH(MATCH)
return self.resolve_esm_match(specifier, &cached_path, ctx);
}
}
}
self.load_browser_field(cached_path, Some(specifier), &package_json, ctx)
}
/// RESOLVE_ESM_MATCH(MATCH)
fn resolve_esm_match(
&self,
specifier: &str,
cached_path: &CachedPath,
ctx: &mut Ctx,
) -> ResolveResult {
// 1. let RESOLVED_PATH = fileURLToPath(MATCH)
// 2. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension format. STOP
//
// Non-compliant ESM can result in a directory, so directory is tried as well.
if let Some(path) = self.load_as_file_or_directory(cached_path, "", ctx)? {
return Ok(Some(path));
}
let mut path_str = cached_path.path().to_str();
// 3. If the RESOLVED_PATH contains `?``, it could be a path with query
// so try to resolve it as a file or directory without the query,
// but also `?` is a valid character in a path, so we should try from right to left.
while let Some(s) = path_str {
if let Some((before, _)) = s.rsplit_once('?') {
if (self.load_as_file_or_directory(
&self.cache.value(Path::new(before)),
"",
ctx,
)?)
.is_some()
{
return Ok(Some(cached_path.clone()));
}
path_str = Some(before);
} else {
break;
}
}
// 3. THROW "not found"
Err(ResolveError::NotFound(specifier.to_string()))
}
/// enhanced-resolve: AliasFieldPlugin for [ResolveOptions::alias_fields]
fn load_browser_field(
&self,
cached_path: &CachedPath,
module_specifier: Option<&str>,
package_json: &PackageJson,
ctx: &mut Ctx,
) -> ResolveResult {
let path = cached_path.path();
let Some(new_specifier) = package_json.resolve_browser_field(
path,
module_specifier,
&self.options.alias_fields,
)?
else {
return Ok(None);
};
// Abort when resolving recursive module
if module_specifier.is_some_and(|s| s == new_specifier) {
return Ok(None);
}
if ctx.resolving_alias.as_ref().is_some_and(|s| s == new_specifier) {
// Complete when resolving to self `{"./a.js": "./a.js"}`
if new_specifier.strip_prefix("./").filter(|s| path.ends_with(Path::new(s))).is_some() {
return if cached_path.is_file(&self.cache.fs, ctx) {
Ok(Some(cached_path.clone()))
} else {
Err(ResolveError::NotFound(new_specifier.to_string()))
};
}
return Err(ResolveError::Recursion);
}
ctx.with_resolving_alias(new_specifier.to_string());
ctx.with_fully_specified(false);
let cached_path = self.cache.value(package_json.directory());