/
resolver.go
1314 lines (1150 loc) · 44.5 KB
/
resolver.go
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
package resolver
import (
"errors"
"fmt"
"regexp"
"strings"
"sync"
"syscall"
"github.com/evanw/esbuild/internal/ast"
"github.com/evanw/esbuild/internal/cache"
"github.com/evanw/esbuild/internal/config"
"github.com/evanw/esbuild/internal/fs"
"github.com/evanw/esbuild/internal/js_ast"
"github.com/evanw/esbuild/internal/js_lexer"
"github.com/evanw/esbuild/internal/js_parser"
"github.com/evanw/esbuild/internal/logger"
)
// This namespace is used when a module has been disabled by being mapped to
// "false" using the "browser" field of "package.json".
const BrowserFalseNamespace = "empty"
var defaultMainFields = map[config.Platform][]string{
// Note that this means if a package specifies "main", "module", and
// "browser" then "browser" will win out over "module". This is the
// same behavior as webpack: https://github.com/webpack/webpack/issues/4674.
//
// This is deliberate because the presence of the "browser" field is a
// good signal that the "module" field may have non-browser stuff in it,
// which will crash or fail to be bundled when targeting the browser.
config.PlatformBrowser: []string{"browser", "module", "main"},
// Note that this means if a package specifies "module" and "main", the ES6
// module will not be selected. This means tree shaking will not work when
// targeting node environments.
//
// This is unfortunately necessary for compatibility. Some packages
// incorrectly treat the "module" field as "code for the browser". It
// actually means "code for ES6 environments" which includes both node
// and the browser.
//
// For example, the package "@firebase/app" prints a warning on startup about
// the bundler incorrectly using code meant for the browser if the bundler
// selects the "module" field instead of the "main" field.
//
// If you want to enable tree shaking when targeting node, you will have to
// configure the main fields to be "module" and then "main". Keep in mind
// that some packages may break if you do this.
config.PlatformNode: []string{"main", "module"},
}
// Path resolution is a mess. One tricky issue is the "module" override for the
// "main" field in "package.json" files. Bundlers generally prefer "module" over
// "main" but that breaks packages that export a function in "main" for use with
// "require()", since resolving to "module" means an object will be returned. We
// attempt to handle this automatically by having import statements resolve to
// "module" but switch that out later for "main" if "require()" is used too.
type PathPair struct {
// Either secondary will be empty, or primary will be "module" and secondary
// will be "main"
Primary logger.Path
Secondary logger.Path
}
func (pp *PathPair) iter() []*logger.Path {
result := []*logger.Path{&pp.Primary, &pp.Secondary}
if !pp.HasSecondary() {
result = result[:1]
}
return result
}
func (pp *PathPair) HasSecondary() bool {
return pp.Secondary.Text != ""
}
type IgnoreIfUnusedData struct {
Source *logger.Source
Range logger.Range
// If true, "sideEffects" was an array. If false, "sideEffects" was false.
IsSideEffectsArrayInJSON bool
}
type ResolveResult struct {
PathPair PathPair
// If not empty, these should override the default values
JSXFactory []string // Default if empty: "React.createElement"
JSXFragment []string // Default if empty: "React.Fragment"
IsExternal bool
// If true, any ES6 imports to this file can be considered to have no side
// effects. This means they should be removed if unused.
IgnorePrimaryIfUnused *IgnoreIfUnusedData
// If true, the class field transform should use Object.defineProperty().
UseDefineForClassFieldsTS bool
// If true, unused imports are retained in TypeScript code. This matches the
// behavior of the "importsNotUsedAsValues" field in "tsconfig.json" when the
// value is not "remove".
PreserveUnusedImportsTS bool
// This is true if the file is inside a "node_modules" directory
SuppressWarningsAboutWeirdCode bool
}
type Resolver interface {
Resolve(sourceDir string, importPath string, kind ast.ImportKind) *ResolveResult
ResolveAbs(absPath string) *ResolveResult
PrettyPath(path logger.Path) string
// This tries to run "Resolve" on a package path as a relative path. If
// successful, the user just forgot a leading "./" in front of the path.
ProbeResolvePackageAsRelative(sourceDir string, importPath string, kind ast.ImportKind) *ResolveResult
}
type resolver struct {
fs fs.FS
log logger.Log
caches *cache.CacheSet
options config.Options
mutex sync.Mutex
// A special filtered import order for CSS "@import" imports.
//
// The "resolve extensions" setting determines the order of implicit
// extensions to try when resolving imports with the extension omitted.
// Sometimes people create a JavaScript/TypeScript file and a CSS file with
// the same name when they create a component. At a high level, users expect
// implicit extensions to resolve to the JS file when being imported from JS
// and to resolve to the CSS file when being imported from CSS.
//
// Different bundlers handle this in different ways. Parcel handles this by
// having the resolver prefer the same extension as the importing file in
// front of the configured "resolve extensions" order. Webpack's "css-loader"
// plugin just explicitly configures a special "resolve extensions" order
// consisting of only ".css" for CSS files.
//
// It's unclear what behavior is best here. What we currently do is to create
// a special filtered version of the configured "resolve extensions" order
// for CSS files that filters out any extension that has been explicitly
// configured with a non-CSS loader. This still gives users control over the
// order but avoids the scenario where we match an import in a CSS file to a
// JavaScript-related file. It's probably not perfect with plugins in the
// picture but it's better than some alternatives and probably pretty good.
atImportExtensionOrder []string
// This cache maps a directory path to information about that directory and
// all parent directories
dirCache map[string]*dirInfo
}
func NewResolver(fs fs.FS, log logger.Log, caches *cache.CacheSet, options config.Options) Resolver {
// Bundling for node implies allowing node's builtin modules
if options.Platform == config.PlatformNode {
externalNodeModules := make(map[string]bool)
if options.ExternalModules.NodeModules != nil {
for name := range options.ExternalModules.NodeModules {
externalNodeModules[name] = true
}
}
for name := range BuiltInNodeModules {
externalNodeModules[name] = true
}
options.ExternalModules.NodeModules = externalNodeModules
}
// Filter out non-CSS extensions for CSS "@import" imports
atImportExtensionOrder := make([]string, 0, len(options.ExtensionOrder))
for _, ext := range options.ExtensionOrder {
if loader, ok := options.ExtensionToLoader[ext]; ok && loader != config.LoaderCSS {
continue
}
atImportExtensionOrder = append(atImportExtensionOrder, ext)
}
return &resolver{
fs: fs,
log: log,
options: options,
caches: caches,
dirCache: make(map[string]*dirInfo),
atImportExtensionOrder: atImportExtensionOrder,
}
}
func (r *resolver) Resolve(sourceDir string, importPath string, kind ast.ImportKind) *ResolveResult {
// Certain types of URLs default to being external for convenience
if r.isExternalPattern(importPath) ||
// "fill: url(#filter);"
(kind.IsFromCSS() && strings.HasPrefix(importPath, "#")) ||
// "background: url(http://example.com/images/image.png);"
strings.HasPrefix(importPath, "http://") ||
// "background: url(https://example.com/images/image.png);"
strings.HasPrefix(importPath, "https://") ||
// "background: url(data:image/png;base64,iVBORw0KGgo=);"
strings.HasPrefix(importPath, "data:") ||
// "background: url(//example.com/images/image.png);"
strings.HasPrefix(importPath, "//") {
return &ResolveResult{
PathPair: PathPair{Primary: logger.Path{Text: importPath}},
IsExternal: true,
}
}
// Fail now if there is no directory to resolve in. This can happen for
// virtual modules (e.g. stdin) if a resolve directory is not specified.
if sourceDir == "" {
return nil
}
r.mutex.Lock()
defer r.mutex.Unlock()
result := r.resolveWithoutSymlinks(sourceDir, importPath, kind)
if result == nil {
return nil
}
// If successful, resolve symlinks using the directory info cache
return r.finalizeResolve(*result)
}
func (r *resolver) isExternalPattern(path string) bool {
for _, pattern := range r.options.ExternalModules.Patterns {
if len(path) >= len(pattern.Prefix)+len(pattern.Suffix) &&
strings.HasPrefix(path, pattern.Prefix) &&
strings.HasSuffix(path, pattern.Suffix) {
return true
}
}
return false
}
func (r *resolver) ResolveAbs(absPath string) *ResolveResult {
r.mutex.Lock()
defer r.mutex.Unlock()
// Just decorate the absolute path with information from parent directories
return r.finalizeResolve(ResolveResult{PathPair: PathPair{Primary: logger.Path{Text: absPath, Namespace: "file"}}})
}
func (r *resolver) ProbeResolvePackageAsRelative(sourceDir string, importPath string, kind ast.ImportKind) *ResolveResult {
absPath := r.fs.Join(sourceDir, importPath)
r.mutex.Lock()
defer r.mutex.Unlock()
if pair, ok := r.loadAsFileOrDirectory(absPath, kind); ok {
return r.finalizeResolve(ResolveResult{PathPair: pair})
}
return nil
}
func isInsideNodeModules(fs fs.FS, path string) bool {
dir := fs.Dir(path)
for {
if fs.Base(dir) == "node_modules" {
return true
}
parent := fs.Dir(dir)
if dir == parent {
return false
}
dir = parent
}
}
func (r *resolver) finalizeResolve(result ResolveResult) *ResolveResult {
for _, path := range result.PathPair.iter() {
if path.Namespace == "file" {
if dirInfo := r.dirInfoCached(r.fs.Dir(path.Text)); dirInfo != nil {
base := r.fs.Base(path.Text)
// Don't emit warnings for code inside a "node_modules" directory
if isInsideNodeModules(r.fs, path.Text) {
result.SuppressWarningsAboutWeirdCode = true
}
// Look up this file in the "sideEffects" map in the nearest enclosing
// directory with a "package.json" file.
//
// Only do this for the primary path. Some packages have the primary
// path marked as having side effects and the secondary path marked
// as not having side effects. This is likely a bug in the package
// definition but we don't want to consider the primary path as not
// having side effects just because the secondary path is marked as
// not having side effects.
if *path == result.PathPair.Primary {
for info := dirInfo; info != nil; info = info.parent {
if info.packageJSON != nil {
if info.packageJSON.sideEffectsMap != nil {
hasSideEffects := false
if info.packageJSON.sideEffectsMap[path.Text] {
// Fast path: map lookup
hasSideEffects = true
} else {
// Slow path: glob tests
for _, re := range info.packageJSON.sideEffectsRegexps {
if re.MatchString(path.Text) {
hasSideEffects = true
break
}
}
}
if !hasSideEffects {
result.IgnorePrimaryIfUnused = info.packageJSON.ignoreIfUnusedData
}
}
break
}
}
}
// Copy various fields from the nearest enclosing "tsconfig.json" file if present
if path == &result.PathPair.Primary && dirInfo.tsConfigJSON != nil {
result.JSXFactory = dirInfo.tsConfigJSON.JSXFactory
result.JSXFragment = dirInfo.tsConfigJSON.JSXFragmentFactory
result.UseDefineForClassFieldsTS = dirInfo.tsConfigJSON.UseDefineForClassFields
result.PreserveUnusedImportsTS = dirInfo.tsConfigJSON.PreserveImportsNotUsedAsValues
}
if entry, ok := dirInfo.entries[base]; ok {
if symlink := entry.Symlink(); symlink != "" {
// Is this entry itself a symlink?
path.Text = symlink
} else if dirInfo.absRealPath != "" {
// Is there at least one parent directory with a symlink?
path.Text = r.fs.Join(dirInfo.absRealPath, base)
}
}
}
}
}
return &result
}
func (r *resolver) resolveWithoutSymlinks(sourceDir string, importPath string, kind ast.ImportKind) *ResolveResult {
// This implements the module resolution algorithm from node.js, which is
// described here: https://nodejs.org/api/modules.html#modules_all_together
var result PathPair
// Return early if this is already an absolute path
if r.fs.IsAbs(importPath) {
// First, check path overrides from the nearest enclosing TypeScript "tsconfig.json" file
if dirInfo := r.dirInfoCached(sourceDir); dirInfo != nil && dirInfo.tsConfigJSON != nil && dirInfo.tsConfigJSON.Paths != nil {
if absolute, ok := r.matchTSConfigPaths(dirInfo.tsConfigJSON, importPath, kind); ok {
return &ResolveResult{PathPair: absolute}
}
}
if r.options.ExternalModules.AbsPaths != nil && r.options.ExternalModules.AbsPaths[importPath] {
// If the string literal in the source text is an absolute path and has
// been marked as an external module, mark it as *not* an absolute path.
// That way we preserve the literal text in the output and don't generate
// a relative path from the output directory to that path.
return &ResolveResult{PathPair: PathPair{Primary: logger.Path{Text: importPath}}, IsExternal: true}
}
return &ResolveResult{PathPair: PathPair{Primary: logger.Path{Text: importPath, Namespace: "file"}}}
}
// Check both relative and package paths for CSS URL tokens, with relative
// paths taking precedence over package paths to match Webpack behavior.
isPackagePath := IsPackagePath(importPath)
checkRelative := !isPackagePath || kind == ast.ImportURL
checkPackage := isPackagePath
if checkRelative {
absPath := r.fs.Join(sourceDir, importPath)
// Check for external packages first
if r.options.ExternalModules.AbsPaths != nil && r.options.ExternalModules.AbsPaths[absPath] {
return &ResolveResult{PathPair: PathPair{Primary: logger.Path{Text: absPath, Namespace: "file"}}, IsExternal: true}
}
if absolute, ok := r.loadAsFileOrDirectory(absPath, kind); ok {
checkPackage = false
result = absolute
} else if !checkPackage {
return nil
}
}
if checkPackage {
// Check for external packages first
if r.options.ExternalModules.NodeModules != nil {
query := importPath
for {
if r.options.ExternalModules.NodeModules[query] {
return &ResolveResult{PathPair: PathPair{Primary: logger.Path{Text: importPath}}, IsExternal: true}
}
// If the module "foo" has been marked as external, we also want to treat
// paths into that module such as "foo/bar" as external too.
slash := strings.LastIndexByte(query, '/')
if slash == -1 {
break
}
query = query[:slash]
}
}
sourceDirInfo := r.dirInfoCached(sourceDir)
if sourceDirInfo == nil {
// Bail if the directory is missing for some reason
return nil
}
// Support remapping one package path to another via the "browser" field
if sourceDirInfo.enclosingBrowserScope != nil {
packageJSON := sourceDirInfo.enclosingBrowserScope.packageJSON
if packageJSON.browserPackageMap != nil {
if remapped, ok := packageJSON.browserPackageMap[importPath]; ok {
if remapped == nil {
// "browser": {"module": false}
if absolute, ok := r.loadNodeModules(importPath, kind, sourceDirInfo); ok {
absolute.Primary = logger.Path{Text: absolute.Primary.Text, Namespace: BrowserFalseNamespace}
if absolute.HasSecondary() {
absolute.Secondary = logger.Path{Text: absolute.Secondary.Text, Namespace: BrowserFalseNamespace}
}
return &ResolveResult{PathPair: absolute}
} else {
return &ResolveResult{PathPair: PathPair{Primary: logger.Path{Text: importPath, Namespace: BrowserFalseNamespace}}}
}
} else {
// "browser": {"module": "./some-file"}
// "browser": {"module": "another-module"}
importPath = *remapped
sourceDirInfo = sourceDirInfo.enclosingBrowserScope
}
}
}
}
if absolute, ok := r.resolveWithoutRemapping(sourceDirInfo, importPath, kind); ok {
result = absolute
} else {
// Note: node's "self references" are not currently supported
return nil
}
}
// Check the directory that contains this file
for _, path := range result.iter() {
resultDir := r.fs.Dir(path.Text)
resultDirInfo := r.dirInfoCached(resultDir)
// Support remapping one non-module path to another via the "browser" field
if resultDirInfo != nil && resultDirInfo.enclosingBrowserScope != nil {
packageJSON := resultDirInfo.enclosingBrowserScope.packageJSON
if packageJSON.browserNonPackageMap != nil {
if remapped, ok := packageJSON.browserNonPackageMap[path.Text]; ok {
if remapped == nil {
path.Namespace = BrowserFalseNamespace
} else if remappedResult, ok := r.resolveWithoutRemapping(resultDirInfo.enclosingBrowserScope, *remapped, kind); ok {
*path = remappedResult.Primary
} else {
return nil
}
}
}
}
}
return &ResolveResult{PathPair: result}
}
func (r *resolver) resolveWithoutRemapping(sourceDirInfo *dirInfo, importPath string, kind ast.ImportKind) (PathPair, bool) {
if IsPackagePath(importPath) {
return r.loadNodeModules(importPath, kind, sourceDirInfo)
} else {
return r.loadAsFileOrDirectory(r.fs.Join(sourceDirInfo.absPath, importPath), kind)
}
}
func (r *resolver) PrettyPath(path logger.Path) string {
if path.Namespace == "file" {
if rel, ok := r.fs.Rel(r.fs.Cwd(), path.Text); ok {
path.Text = rel
}
// These human-readable paths are used in error messages, comments in output
// files, source names in source maps, and paths in the metadata JSON file.
// These should be platform-independent so our output doesn't depend on which
// operating system it was run. Replace Windows backward slashes with standard
// forward slashes.
return strings.ReplaceAll(path.Text, "\\", "/")
}
if path.Namespace != "" {
return fmt.Sprintf("%s:%s", path.Namespace, path.Text)
}
return path.Text
}
////////////////////////////////////////////////////////////////////////////////
type packageJSON struct {
absMainFields map[string]string
// Present if the "browser" field is present. This field is intended to be
// used by bundlers and lets you redirect the paths of certain 3rd-party
// modules that don't work in the browser to other modules that shim that
// functionality. That way you don't have to rewrite the code for those 3rd-
// party modules. For example, you might remap the native "util" node module
// to something like https://www.npmjs.com/package/util so it works in the
// browser.
//
// This field contains a mapping of absolute paths to absolute paths. Mapping
// to an empty path indicates that the module is disabled. As far as I can
// tell, the official spec is a GitHub repo hosted by a user account:
// https://github.com/defunctzombie/package-browser-field-spec. The npm docs
// say almost nothing: https://docs.npmjs.com/files/package.json.
browserNonPackageMap map[string]*string
browserPackageMap map[string]*string
// If this is non-nil, each entry in this map is the absolute path of a file
// with side effects. Any entry not in this map should be considered to have
// no side effects, which means import statements for these files can be
// removed if none of the imports are used. This is a convention from Webpack:
// https://webpack.js.org/guides/tree-shaking/.
//
// Note that if a file is included, all statements that can't be proven to be
// free of side effects must be included. This convention does not say
// anything about whether any statements within the file have side effects or
// not.
sideEffectsMap map[string]bool
sideEffectsRegexps []*regexp.Regexp
ignoreIfUnusedData *IgnoreIfUnusedData
}
type dirInfo struct {
// These objects are immutable, so we can just point to the parent directory
// and avoid having to lock the cache again
parent *dirInfo
// A pointer to the enclosing dirInfo with a valid "browser" field in
// package.json. We need this to remap paths after they have been resolved.
enclosingBrowserScope *dirInfo
// All relevant information about this directory
absPath string
entries map[string]*fs.Entry
hasNodeModules bool // Is there a "node_modules" subdirectory?
absPathIndex *string // Is there an "index.js" file?
packageJSON *packageJSON // Is there a "package.json" file?
tsConfigJSON *TSConfigJSON // Is there a "tsconfig.json" file in this directory or a parent directory?
absRealPath string // If non-empty, this is the real absolute path resolving any symlinks
}
func (r *resolver) dirInfoCached(path string) *dirInfo {
// First, check the cache
cached, ok := r.dirCache[path]
// Cache hit: stop now
if ok {
return cached
}
// Cache miss: read the info
info := r.dirInfoUncached(path)
// Update the cache unconditionally. Even if the read failed, we don't want to
// retry again later. The directory is inaccessible so trying again is wasted.
r.dirCache[path] = info
return info
}
var parseErrorImportCycle = errors.New("(import cycle)")
var parseErrorAlreadyLogged = errors.New("(error already logged)")
// This may return "parseErrorAlreadyLogged" in which case there was a syntax
// error, but it's already been reported. No further errors should be logged.
//
// Nested calls may also return "parseErrorImportCycle". In that case the
// caller is responsible for logging an appropriate error message.
func (r *resolver) parseTSConfig(file string, visited map[string]bool) (*TSConfigJSON, error) {
// Don't infinite loop if a series of "extends" links forms a cycle
if visited[file] {
return nil, parseErrorImportCycle
}
visited[file] = true
contents, err := r.caches.FSCache.ReadFile(r.fs, file)
if err != nil {
return nil, err
}
keyPath := logger.Path{Text: file, Namespace: "file"}
source := logger.Source{
KeyPath: keyPath,
PrettyPath: r.PrettyPath(keyPath),
Contents: contents,
}
fileDir := r.fs.Dir(file)
result := ParseTSConfigJSON(r.log, source, &r.caches.JSONCache, func(extends string, extendsRange logger.Range) *TSConfigJSON {
if IsPackagePath(extends) {
// If this is a package path, try to resolve it to a "node_modules"
// folder. This doesn't use the normal node module resolution algorithm
// both because it's different (e.g. we don't want to match a directory)
// and because it would deadlock since we're currently in the middle of
// populating the directory info cache.
current := fileDir
for {
// Skip "node_modules" folders
if r.fs.Base(current) != "node_modules" {
join := r.fs.Join(current, "node_modules", extends)
filesToCheck := []string{r.fs.Join(join, "tsconfig.json"), join, join + ".json"}
for _, fileToCheck := range filesToCheck {
base, err := r.parseTSConfig(fileToCheck, visited)
if err == nil {
return base
} else if err == syscall.ENOENT {
continue
} else if err == parseErrorImportCycle {
r.log.AddRangeWarning(&source, extendsRange,
fmt.Sprintf("Base config file %q forms cycle", extends))
} else if err != parseErrorAlreadyLogged {
r.log.AddRangeError(&source, extendsRange,
fmt.Sprintf("Cannot read file %q: %s",
r.PrettyPath(logger.Path{Text: fileToCheck, Namespace: "file"}), err.Error()))
}
return nil
}
}
// Go to the parent directory, stopping at the file system root
next := r.fs.Dir(current)
if current == next {
break
}
current = next
}
} else {
// If this is a regular path, search relative to the enclosing directory
extendsFile := r.fs.Join(fileDir, extends)
for _, fileToCheck := range []string{extendsFile, extendsFile + ".json"} {
base, err := r.parseTSConfig(fileToCheck, visited)
if err == nil {
return base
} else if err == syscall.ENOENT {
continue
} else if err == parseErrorImportCycle {
r.log.AddRangeWarning(&source, extendsRange,
fmt.Sprintf("Base config file %q forms cycle", extends))
} else if err != parseErrorAlreadyLogged {
r.log.AddRangeError(&source, extendsRange,
fmt.Sprintf("Cannot read file %q: %s",
r.PrettyPath(logger.Path{Text: fileToCheck, Namespace: "file"}), err.Error()))
}
return nil
}
}
// Suppress warnings about missing base config files inside "node_modules"
if !isInsideNodeModules(r.fs, file) {
r.log.AddRangeWarning(&source, extendsRange,
fmt.Sprintf("Cannot find base config file %q", extends))
}
return nil
})
if result == nil {
return nil, parseErrorAlreadyLogged
}
if result.BaseURL != nil && !r.fs.IsAbs(*result.BaseURL) {
*result.BaseURL = r.fs.Join(fileDir, *result.BaseURL)
}
if result.Paths != nil && !r.fs.IsAbs(result.BaseURLForPaths) {
result.BaseURLForPaths = r.fs.Join(fileDir, result.BaseURLForPaths)
}
return result, nil
}
func (r *resolver) dirInfoUncached(path string) *dirInfo {
// Get the info for the parent directory
var parentInfo *dirInfo
parentDir := r.fs.Dir(path)
if parentDir != path {
parentInfo = r.dirInfoCached(parentDir)
// Stop now if the parent directory doesn't exist
if parentInfo == nil {
return nil
}
}
// List the directories
entries, err := r.fs.ReadDirectory(path)
if err != nil {
if err != syscall.ENOENT {
r.log.AddError(nil, logger.Loc{},
fmt.Sprintf("Cannot read directory %q: %s",
r.PrettyPath(logger.Path{Text: path, Namespace: "file"}), err.Error()))
}
return nil
}
info := &dirInfo{
absPath: path,
parent: parentInfo,
entries: entries,
}
// A "node_modules" directory isn't allowed to directly contain another "node_modules" directory
base := r.fs.Base(path)
if base != "node_modules" {
if entry, ok := entries["node_modules"]; ok {
info.hasNodeModules = entry.Kind() == fs.DirEntry
}
}
// Propagate the browser scope into child directories
if parentInfo != nil {
info.enclosingBrowserScope = parentInfo.enclosingBrowserScope
// Make sure "absRealPath" is the real path of the directory (resolving any symlinks)
if entry, ok := parentInfo.entries[base]; ok {
if symlink := entry.Symlink(); symlink != "" {
info.absRealPath = symlink
} else if parentInfo.absRealPath != "" {
info.absRealPath = r.fs.Join(parentInfo.absRealPath, base)
}
}
}
// Record if this directory has a package.json file
if entry, ok := entries["package.json"]; ok && entry.Kind() == fs.FileEntry {
info.packageJSON = r.parsePackageJSON(path)
// Propagate this browser scope into child directories
if info.packageJSON != nil && (info.packageJSON.browserPackageMap != nil || info.packageJSON.browserNonPackageMap != nil) {
info.enclosingBrowserScope = info
}
}
// Record if this directory has a tsconfig.json or jsconfig.json file
{
var tsConfigPath string
if forceTsConfig := r.options.TsConfigOverride; forceTsConfig == "" {
if entry, ok := entries["tsconfig.json"]; ok && entry.Kind() == fs.FileEntry {
tsConfigPath = r.fs.Join(path, "tsconfig.json")
} else if entry, ok := entries["jsconfig.json"]; ok && entry.Kind() == fs.FileEntry {
tsConfigPath = r.fs.Join(path, "jsconfig.json")
}
} else if parentInfo == nil {
// If there is a tsconfig.json override, mount it at the root directory
tsConfigPath = forceTsConfig
}
if tsConfigPath != "" {
var err error
info.tsConfigJSON, err = r.parseTSConfig(tsConfigPath, make(map[string]bool))
if err != nil {
if err == syscall.ENOENT {
r.log.AddError(nil, logger.Loc{}, fmt.Sprintf("Cannot find tsconfig file %q",
r.PrettyPath(logger.Path{Text: tsConfigPath, Namespace: "file"})))
} else if err != parseErrorAlreadyLogged {
r.log.AddError(nil, logger.Loc{},
fmt.Sprintf("Cannot read file %q: %s",
r.PrettyPath(logger.Path{Text: tsConfigPath, Namespace: "file"}), err.Error()))
}
}
}
}
// Propagate the enclosing tsconfig.json from the parent directory
if info.tsConfigJSON == nil && parentInfo != nil {
info.tsConfigJSON = parentInfo.tsConfigJSON
}
// Look for an "index" file with known extensions
if absolute, ok := r.loadAsIndex(path, entries); ok {
info.absPathIndex = &absolute
}
return info
}
func (r *resolver) parsePackageJSON(path string) *packageJSON {
packageJsonPath := r.fs.Join(path, "package.json")
contents, err := r.caches.FSCache.ReadFile(r.fs, packageJsonPath)
if err != nil {
r.log.AddError(nil, logger.Loc{},
fmt.Sprintf("Cannot read file %q: %s",
r.PrettyPath(logger.Path{Text: packageJsonPath, Namespace: "file"}), err.Error()))
return nil
}
keyPath := logger.Path{Text: packageJsonPath, Namespace: "file"}
jsonSource := logger.Source{
KeyPath: keyPath,
PrettyPath: r.PrettyPath(keyPath),
Contents: contents,
}
json, ok := r.caches.JSONCache.Parse(r.log, jsonSource, js_parser.JSONOptions{})
if !ok {
return nil
}
toAbsPath := func(pathText string, pathRange logger.Range) *string {
// Is it a file?
if absolute, ok := r.loadAsFile(pathText, r.options.ExtensionOrder); ok {
return &absolute
}
// Is it a directory?
if mainEntries, err := r.fs.ReadDirectory(pathText); err == nil {
// Look for an "index" file with known extensions
if absolute, ok := r.loadAsIndex(pathText, mainEntries); ok {
return &absolute
}
} else if err != syscall.ENOENT {
r.log.AddRangeError(&jsonSource, pathRange,
fmt.Sprintf("Cannot read directory %q: %s",
r.PrettyPath(logger.Path{Text: pathText, Namespace: "file"}), err.Error()))
}
return nil
}
packageJSON := &packageJSON{}
// Read the "main" fields
mainFields := r.options.MainFields
if mainFields == nil {
mainFields = defaultMainFields[r.options.Platform]
}
for _, field := range mainFields {
if mainJson, _, ok := getProperty(json, field); ok {
if main, ok := getString(mainJson); ok {
if packageJSON.absMainFields == nil {
packageJSON.absMainFields = make(map[string]string)
}
if absPath := toAbsPath(r.fs.Join(path, main), jsonSource.RangeOfString(mainJson.Loc)); absPath != nil {
packageJSON.absMainFields[field] = *absPath
}
}
}
}
// Read the "browser" property, but only when targeting the browser
if browserJson, _, ok := getProperty(json, "browser"); ok && r.options.Platform == config.PlatformBrowser {
// We both want the ability to have the option of CJS vs. ESM and the
// option of having node vs. browser. The way to do this is to use the
// object literal form of the "browser" field like this:
//
// "main": "dist/index.node.cjs.js",
// "module": "dist/index.node.esm.js",
// "browser": {
// "./dist/index.node.cjs.js": "./dist/index.browser.cjs.js",
// "./dist/index.node.esm.js": "./dist/index.browser.esm.js"
// },
//
if browser, ok := browserJson.Data.(*js_ast.EObject); ok {
// The value is an object
browserPackageMap := make(map[string]*string)
browserNonPackageMap := make(map[string]*string)
// Remap all files in the browser field
for _, prop := range browser.Properties {
if key, ok := getString(prop.Key); ok && prop.Value != nil {
isPackagePath := IsPackagePath(key)
// Make this an absolute path if it's not a package
if !isPackagePath {
key = r.fs.Join(path, key)
}
if value, ok := getString(*prop.Value); ok {
// If this is a string, it's a replacement package
if isPackagePath {
browserPackageMap[key] = &value
} else {
browserNonPackageMap[key] = &value
}
} else if value, ok := getBool(*prop.Value); ok && !value {
// If this is false, it means the package is disabled
if isPackagePath {
browserPackageMap[key] = nil
} else {
browserNonPackageMap[key] = nil
}
}
}
}
packageJSON.browserPackageMap = browserPackageMap
packageJSON.browserNonPackageMap = browserNonPackageMap
}
}
// Read the "sideEffects" property
if sideEffectsJson, sideEffectsLoc, ok := getProperty(json, "sideEffects"); ok {
switch data := sideEffectsJson.Data.(type) {
case *js_ast.EBoolean:
if !data.Value {
// Make an empty map for "sideEffects: false", which indicates all
// files in this module can be considered to not have side effects.
packageJSON.sideEffectsMap = make(map[string]bool)
packageJSON.ignoreIfUnusedData = &IgnoreIfUnusedData{
IsSideEffectsArrayInJSON: false,
Source: &jsonSource,
Range: jsonSource.RangeOfString(sideEffectsLoc),
}
}
case *js_ast.EArray:
// The "sideEffects: []" format means all files in this module but not in
// the array can be considered to not have side effects.
packageJSON.sideEffectsMap = make(map[string]bool)
packageJSON.ignoreIfUnusedData = &IgnoreIfUnusedData{
IsSideEffectsArrayInJSON: true,
Source: &jsonSource,
Range: jsonSource.RangeOfString(sideEffectsLoc),
}
for _, itemJson := range data.Items {
item, ok := itemJson.Data.(*js_ast.EString)
if !ok || item.Value == nil {
r.log.AddWarning(&jsonSource, itemJson.Loc,
"Expected string in array for \"sideEffects\"")
continue
}
absPattern := r.fs.Join(path, js_lexer.UTF16ToString(item.Value))
re, hadWildcard := globToEscapedRegexp(absPattern)
// Wildcard patterns require more expensive matching
if hadWildcard {
packageJSON.sideEffectsRegexps = append(packageJSON.sideEffectsRegexps, regexp.MustCompile(re))
continue
}
// Normal strings can be matched with a map lookup
packageJSON.sideEffectsMap[absPattern] = true
}
default:
r.log.AddWarning(&jsonSource, sideEffectsJson.Loc,
"The value for \"sideEffects\" must be a boolean or an array")
}
}
return packageJSON
}
func globToEscapedRegexp(glob string) (string, bool) {
sb := strings.Builder{}
sb.WriteByte('^')
hadWildcard := false
for _, c := range glob {
switch c {
case '\\', '^', '$', '.', '+', '|', '(', ')', '[', ']', '{', '}':
sb.WriteByte('\\')
sb.WriteRune(c)
case '*':
sb.WriteString(".*")
hadWildcard = true
case '?':
sb.WriteByte('.')
hadWildcard = true
default:
sb.WriteRune(c)
}
}
sb.WriteByte('$')
return sb.String(), hadWildcard
}
func (r *resolver) loadAsFile(path string, extensionOrder []string) (string, bool) {
// Read the directory entries once to minimize locking
dirPath := r.fs.Dir(path)
entries, err := r.fs.ReadDirectory(dirPath)
if err != nil {
if err != syscall.ENOENT {
r.log.AddError(nil, logger.Loc{},
fmt.Sprintf("Cannot read directory %q: %s",
r.PrettyPath(logger.Path{Text: dirPath, Namespace: "file"}), err.Error()))