-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
resolver.go
2180 lines (1916 loc) · 79.3 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"
"path"
"sort"
"strings"
"sync"
"syscall"
"github.com/evanw/esbuild/internal/ast"
"github.com/evanw/esbuild/internal/cache"
"github.com/evanw/esbuild/internal/compat"
"github.com/evanw/esbuild/internal/config"
"github.com/evanw/esbuild/internal/fs"
"github.com/evanw/esbuild/internal/helpers"
"github.com/evanw/esbuild/internal/js_ast"
"github.com/evanw/esbuild/internal/js_printer"
"github.com/evanw/esbuild/internal/logger"
)
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: {"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: {"main", "module"},
// The neutral platform is for people that don't want esbuild to try to
// pick good defaults for their platform. In that case, the list of main
// fields is empty by default. You must explicitly configure it yourself.
config.PlatformNeutral: {},
}
// These are the main fields to use when the "main fields" setting is configured
// to something unusual, such as something without the "main" field.
var mainFieldsForFailure = []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 SideEffectsData struct {
Source *logger.Source
// If non-empty, this false value came from a plugin
PluginName string
Range logger.Range
// If true, "sideEffects" was an array. If false, "sideEffects" was false.
IsSideEffectsArrayInJSON bool
}
type ResolveResult struct {
PathPair PathPair
// If non-empty, this was the result of an "onResolve" plugin
PluginName string
// If this was resolved by a plugin, the plugin gets to store its data here
PluginData interface{}
// If not empty, these should override the default values
JSXFactory []string // Default if empty: "React.createElement"
JSXFragment []string // Default if empty: "React.Fragment"
DifferentCase *fs.DifferentCase
// If present, any ES6 imports to this file can be considered to have no side
// effects. This means they should be removed if unused.
PrimarySideEffectsData *SideEffectsData
TSTarget *config.TSTarget
// This is the "type" field from "package.json"
ModuleTypeData js_ast.ModuleTypeData
IsExternal bool
// If true, the class field transform should use Object.defineProperty().
UseDefineForClassFieldsTS config.MaybeBool
// This is the "importsNotUsedAsValues" and "preserveValueImports" fields from "package.json"
UnusedImportsTS config.UnusedImportsTS
}
func prettyPrintPluginName(prefix string, key string, value string) string {
if value == "" {
return fmt.Sprintf("%s %q: null,", prefix, key)
}
return fmt.Sprintf("%s %q: %q,", prefix, key, value)
}
func prettyPrintPath(prefix string, key string, value logger.Path) string {
lines := []string{
fmt.Sprintf("%s %q: {", prefix, key),
fmt.Sprintf("%s \"text\": %q,", prefix, value.Text),
fmt.Sprintf("%s \"namespace\": %q,", prefix, value.Namespace),
}
if value.IgnoredSuffix != "" {
lines = append(lines, fmt.Sprintf("%s \"suffix\": %q,", prefix, value.IgnoredSuffix))
}
if value.IsDisabled() {
lines = append(lines, fmt.Sprintf("%s \"disabled\": true,", prefix))
}
lines = append(lines, fmt.Sprintf("%s },", prefix))
return strings.Join(lines, "\n")
}
func prettyPrintStringArray(prefix string, key string, value []string) string {
return fmt.Sprintf("%s %q: [%s],", prefix, key, helpers.StringArrayToQuotedCommaSeparatedString(value))
}
func prettyPrintTSTarget(prefix string, key string, value *config.TSTarget) string {
if value == nil {
return fmt.Sprintf("%s %q: null,", prefix, key)
}
return fmt.Sprintf("%s %q: %q,", prefix, key, value.Target)
}
func prettyPrintModuleType(prefix string, key string, value js_ast.ModuleType) string {
kind := "null"
if value.IsCommonJS() {
kind = "\"commonjs\""
} else if value.IsESM() {
kind = "\"module\""
}
return fmt.Sprintf("%s %q: %s,", prefix, key, kind)
}
func prettyPrintUnusedImports(prefix string, key string, value config.UnusedImportsTS) string {
source := "null"
switch value {
case config.UnusedImportsKeepStmtRemoveValues:
source = "{ \"importsNotUsedAsValues\": \"preserve\" }"
case config.UnusedImportsKeepValues:
source = "{ \"preserveValueImports\": true }"
}
return fmt.Sprintf("%s %q: %s,", prefix, key, source)
}
func (old *ResolveResult) Compare(new *ResolveResult) (diff []string) {
var oldDiff []string
var newDiff []string
if old.PluginName != new.PluginName {
oldDiff = append(oldDiff, prettyPrintPluginName("-", "pluginName", old.PluginName))
newDiff = append(newDiff, prettyPrintPluginName("+", "pluginName", new.PluginName))
}
if !old.PathPair.Primary.IsEquivalentTo(new.PathPair.Primary) {
oldDiff = append(oldDiff, prettyPrintPath("-", "path", old.PathPair.Primary))
newDiff = append(newDiff, prettyPrintPath("+", "path", new.PathPair.Primary))
}
if !old.PathPair.Secondary.IsEquivalentTo(new.PathPair.Secondary) {
oldDiff = append(oldDiff, prettyPrintPath("-", "secondaryPath", old.PathPair.Secondary))
newDiff = append(newDiff, prettyPrintPath("+", "secondaryPath", new.PathPair.Secondary))
}
if !helpers.StringArraysEqual(old.JSXFactory, new.JSXFactory) {
oldDiff = append(oldDiff, prettyPrintStringArray("-", "jsxFactory", old.JSXFactory))
newDiff = append(newDiff, prettyPrintStringArray("+", "jsxFactory", new.JSXFactory))
}
if !helpers.StringArraysEqual(old.JSXFragment, new.JSXFragment) {
oldDiff = append(oldDiff, prettyPrintStringArray("-", "jsxFragment", old.JSXFragment))
newDiff = append(newDiff, prettyPrintStringArray("+", "jsxFragment", new.JSXFragment))
}
if (old.PrimarySideEffectsData != nil) != (new.PrimarySideEffectsData != nil) {
oldDiff = append(oldDiff, fmt.Sprintf("- \"sideEffects\": %v,", old.PrimarySideEffectsData != nil))
newDiff = append(newDiff, fmt.Sprintf("+ \"sideEffects\": %v,", new.PrimarySideEffectsData != nil))
}
if !old.TSTarget.IsEquivalentTo(new.TSTarget) {
oldDiff = append(oldDiff, prettyPrintTSTarget("-", "tsTarget", old.TSTarget))
newDiff = append(newDiff, prettyPrintTSTarget("+", "tsTarget", new.TSTarget))
}
if !old.ModuleTypeData.Type.IsEquivalentTo(new.ModuleTypeData.Type) {
oldDiff = append(oldDiff, prettyPrintModuleType("-", "type", old.ModuleTypeData.Type))
newDiff = append(newDiff, prettyPrintModuleType("+", "type", new.ModuleTypeData.Type))
}
if old.IsExternal != new.IsExternal {
oldDiff = append(oldDiff, fmt.Sprintf("- \"external\": %v,", old.IsExternal))
newDiff = append(newDiff, fmt.Sprintf("+ \"external\": %v,", new.IsExternal))
}
if old.UseDefineForClassFieldsTS != new.UseDefineForClassFieldsTS {
oldDiff = append(oldDiff, fmt.Sprintf("- \"useDefineForClassFields\": %v,", old.UseDefineForClassFieldsTS))
newDiff = append(newDiff, fmt.Sprintf("+ \"useDefineForClassFields\": %v,", new.UseDefineForClassFieldsTS))
}
if old.UnusedImportsTS != new.UnusedImportsTS {
oldDiff = append(oldDiff, prettyPrintUnusedImports("-", "unusedImports", old.UnusedImportsTS))
newDiff = append(newDiff, prettyPrintUnusedImports("+", "unusedImports", new.UnusedImportsTS))
}
if oldDiff != nil {
diff = make([]string, 0, 2+len(oldDiff)+len(newDiff))
diff = append(diff, " {")
diff = append(diff, oldDiff...)
diff = append(diff, newDiff...)
diff = append(diff, " }")
}
return
}
type DebugMeta struct {
suggestionText string
suggestionMessage string
notes []logger.MsgData
}
func (dm DebugMeta) LogErrorMsg(log logger.Log, source *logger.Source, r logger.Range, text string, suggestion string, notes []logger.MsgData) {
tracker := logger.MakeLineColumnTracker(source)
if source != nil && dm.suggestionMessage != "" {
data := tracker.MsgData(r, dm.suggestionMessage)
data.Location.Suggestion = dm.suggestionText
dm.notes = append(dm.notes, data)
}
msg := logger.Msg{
Kind: logger.Error,
Data: tracker.MsgData(r, text),
Notes: append(dm.notes, notes...),
}
if msg.Data.Location != nil && suggestion != "" {
msg.Data.Location.Suggestion = suggestion
}
log.AddMsg(msg)
}
type Resolver interface {
Resolve(sourceDir string, importPath string, kind ast.ImportKind) (result *ResolveResult, debug DebugMeta)
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
// These are sets that represent various conditions for the "exports" field
// in package.json.
esmConditionsDefault map[string]bool
esmConditionsImport map[string]bool
esmConditionsRequire map[string]bool
// 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
options config.Options
// This mutex serves two purposes. First of all, it guards access to "dirCache"
// which is potentially mutated during path resolution. But this mutex is also
// necessary for performance. The "React admin" benchmark mysteriously runs
// twice as fast when this mutex is locked around the whole resolve operation
// instead of around individual accesses to "dirCache". For some reason,
// reducing parallelism in the resolver helps the rest of the bundler go
// faster. I'm not sure why this is but please don't change this unless you
// do a lot of testing with various benchmarks and there aren't any regressions.
mutex sync.Mutex
}
type resolverQuery struct {
*resolver
debugMeta *DebugMeta
debugLogs *debugLogs
kind ast.ImportKind
}
func NewResolver(fs fs.FS, log logger.Log, caches *cache.CacheSet, options config.Options) Resolver {
// 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)
}
// Generate the condition sets for interpreting the "exports" field
esmConditionsDefault := map[string]bool{"default": true}
esmConditionsImport := map[string]bool{"import": true}
esmConditionsRequire := map[string]bool{"require": true}
for _, condition := range options.Conditions {
esmConditionsDefault[condition] = true
}
switch options.Platform {
case config.PlatformBrowser:
esmConditionsDefault["browser"] = true
case config.PlatformNode:
esmConditionsDefault["node"] = true
}
for key := range esmConditionsDefault {
esmConditionsImport[key] = true
esmConditionsRequire[key] = true
}
return &resolver{
fs: fs,
log: log,
options: options,
caches: caches,
dirCache: make(map[string]*dirInfo),
atImportExtensionOrder: atImportExtensionOrder,
esmConditionsDefault: esmConditionsDefault,
esmConditionsImport: esmConditionsImport,
esmConditionsRequire: esmConditionsRequire,
}
}
func (rr *resolver) Resolve(sourceDir string, importPath string, kind ast.ImportKind) (*ResolveResult, DebugMeta) {
var debugMeta DebugMeta
r := resolverQuery{
resolver: rr,
debugMeta: &debugMeta,
kind: kind,
}
if r.log.Level <= logger.LevelDebug {
r.debugLogs = &debugLogs{what: fmt.Sprintf(
"Resolving import %q in directory %q of type %q",
importPath, sourceDir, kind.StringForMetafile())}
}
// Certain types of URLs default to being external for convenience
if isExplicitlyExternal := r.isExternal(r.options.ExternalSettings.PreResolve, importPath); isExplicitlyExternal ||
// "fill: url(#filter);"
(kind == ast.ImportURL && 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(//example.com/images/image.png);"
strings.HasPrefix(importPath, "//") {
if r.debugLogs != nil {
if isExplicitlyExternal {
r.debugLogs.addNote(fmt.Sprintf("The path %q was marked as external by the user", importPath))
} else {
r.debugLogs.addNote("Marking this path as implicitly external")
}
}
r.flushDebugLogs(flushDueToSuccess)
return &ResolveResult{
PathPair: PathPair{Primary: logger.Path{Text: importPath}},
IsExternal: true,
}, debugMeta
}
// "import fs from 'fs'"
if r.options.Platform == config.PlatformNode && BuiltInNodeModules[importPath] {
if r.debugLogs != nil {
r.debugLogs.addNote("Marking this path as implicitly external due to it being a node built-in")
}
r.flushDebugLogs(flushDueToSuccess)
return &ResolveResult{
PathPair: PathPair{Primary: logger.Path{Text: importPath}},
IsExternal: true,
PrimarySideEffectsData: &SideEffectsData{}, // Mark this with "sideEffects: false"
}, debugMeta
}
// "import fs from 'node:fs'"
// "require('node:fs')"
if r.options.Platform == config.PlatformNode && strings.HasPrefix(importPath, "node:") {
if r.debugLogs != nil {
r.debugLogs.addNote("Marking this path as implicitly external due to the \"node:\" prefix")
}
// If this is a known node built-in module, mark it with "sideEffects: false"
var sideEffects *SideEffectsData
if BuiltInNodeModules[strings.TrimPrefix(importPath, "node:")] {
sideEffects = &SideEffectsData{}
}
// Check whether the path will end up as "import" or "require"
convertImportToRequire := !r.options.OutputFormat.KeepES6ImportExportSyntax()
isImport := !convertImportToRequire && (kind == ast.ImportStmt || kind == ast.ImportDynamic)
isRequire := kind == ast.ImportRequire || kind == ast.ImportRequireResolve ||
(convertImportToRequire && (kind == ast.ImportStmt || kind == ast.ImportDynamic))
// Check for support with "import"
if isImport && r.options.UnsupportedJSFeatures.Has(compat.NodeColonPrefixImport) {
if r.debugLogs != nil {
r.debugLogs.addNote("Removing the \"node:\" prefix because the target environment doesn't support it with \"import\" statements")
}
// Automatically strip the prefix if it's not supported
importPath = importPath[5:]
}
// Check for support with "require"
if isRequire && r.options.UnsupportedJSFeatures.Has(compat.NodeColonPrefixRequire) {
if r.debugLogs != nil {
r.debugLogs.addNote("Removing the \"node:\" prefix because the target environment doesn't support it with \"require\" calls")
}
// Automatically strip the prefix if it's not supported
importPath = importPath[5:]
}
r.flushDebugLogs(flushDueToSuccess)
return &ResolveResult{
PathPair: PathPair{Primary: logger.Path{Text: importPath}},
IsExternal: true,
PrimarySideEffectsData: sideEffects,
}, debugMeta
}
if parsed, ok := ParseDataURL(importPath); ok {
// "import 'data:text/javascript,console.log(123)';"
// "@import 'data:text/css,body{background:white}';"
if parsed.DecodeMIMEType() != MIMETypeUnsupported {
if r.debugLogs != nil {
r.debugLogs.addNote("Putting this path in the \"dataurl\" namespace")
}
r.flushDebugLogs(flushDueToSuccess)
return &ResolveResult{
PathPair: PathPair{Primary: logger.Path{Text: importPath, Namespace: "dataurl"}},
}, debugMeta
}
// "background: url(data:image/png;base64,iVBORw0KGgo=);"
if r.debugLogs != nil {
r.debugLogs.addNote("Marking this data URL as external")
}
r.flushDebugLogs(flushDueToSuccess)
return &ResolveResult{
PathPair: PathPair{Primary: logger.Path{Text: importPath}},
IsExternal: true,
}, debugMeta
}
// 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 == "" {
if r.debugLogs != nil {
r.debugLogs.addNote("Cannot resolve this path without a directory")
}
r.flushDebugLogs(flushDueToFailure)
return nil, debugMeta
}
r.mutex.Lock()
defer r.mutex.Unlock()
result := r.resolveWithoutSymlinks(sourceDir, importPath)
if result == nil {
// If resolution failed, try again with the URL query and/or hash removed
suffix := strings.IndexAny(importPath, "?#")
if suffix < 1 {
r.flushDebugLogs(flushDueToFailure)
return nil, debugMeta
}
if r.debugLogs != nil {
r.debugLogs.addNote(fmt.Sprintf("Retrying resolution after removing the suffix %q", importPath[suffix:]))
}
if result2 := r.resolveWithoutSymlinks(sourceDir, importPath[:suffix]); result2 == nil {
r.flushDebugLogs(flushDueToFailure)
return nil, debugMeta
} else {
result = result2
result.PathPair.Primary.IgnoredSuffix = importPath[suffix:]
if result.PathPair.HasSecondary() {
result.PathPair.Secondary.IgnoredSuffix = importPath[suffix:]
}
}
}
// If successful, resolve symlinks using the directory info cache
r.finalizeResolve(result)
r.flushDebugLogs(flushDueToSuccess)
return result, debugMeta
}
func (r resolverQuery) isExternal(matchers config.ExternalMatchers, path string) bool {
if _, ok := matchers.Exact[path]; ok {
return true
}
for _, pattern := range matchers.Patterns {
if r.debugLogs != nil {
r.debugLogs.addNote(fmt.Sprintf("Checking %q against the external pattern %q", path, pattern.Prefix+"*"+pattern.Suffix))
}
if len(path) >= len(pattern.Prefix)+len(pattern.Suffix) &&
strings.HasPrefix(path, pattern.Prefix) &&
strings.HasSuffix(path, pattern.Suffix) {
return true
}
}
return false
}
func (rr *resolver) ResolveAbs(absPath string) *ResolveResult {
r := resolverQuery{resolver: rr}
if r.log.Level <= logger.LevelDebug {
r.debugLogs = &debugLogs{what: fmt.Sprintf("Getting metadata for absolute path %s", absPath)}
}
r.mutex.Lock()
defer r.mutex.Unlock()
// Just decorate the absolute path with information from parent directories
result := &ResolveResult{PathPair: PathPair{Primary: logger.Path{Text: absPath, Namespace: "file"}}}
r.finalizeResolve(result)
r.flushDebugLogs(flushDueToSuccess)
return result
}
func (rr *resolver) ProbeResolvePackageAsRelative(sourceDir string, importPath string, kind ast.ImportKind) *ResolveResult {
r := resolverQuery{
resolver: rr,
kind: kind,
}
absPath := r.fs.Join(sourceDir, importPath)
r.mutex.Lock()
defer r.mutex.Unlock()
if pair, ok, diffCase := r.loadAsFileOrDirectory(absPath); ok {
result := &ResolveResult{PathPair: pair, DifferentCase: diffCase}
r.finalizeResolve(result)
r.flushDebugLogs(flushDueToSuccess)
return result
}
return nil
}
type debugLogs struct {
what string
indent string
notes []logger.MsgData
}
func (d *debugLogs) addNote(text string) {
if d.indent != "" {
text = d.indent + text
}
d.notes = append(d.notes, logger.MsgData{Text: text, DisableMaximumWidth: true})
}
func (d *debugLogs) increaseIndent() {
d.indent += " "
}
func (d *debugLogs) decreaseIndent() {
d.indent = d.indent[2:]
}
type flushMode uint8
const (
flushDueToFailure flushMode = iota
flushDueToSuccess
)
func (r resolverQuery) flushDebugLogs(mode flushMode) {
if r.debugLogs != nil {
if mode == flushDueToFailure {
r.log.AddWithNotes(logger.Debug, nil, logger.Range{}, r.debugLogs.what, r.debugLogs.notes)
} else if r.log.Level <= logger.LevelVerbose {
r.log.AddWithNotes(logger.Verbose, nil, logger.Range{}, r.debugLogs.what, r.debugLogs.notes)
}
}
}
func (r resolverQuery) finalizeResolve(result *ResolveResult) {
if !result.IsExternal && r.isExternal(r.options.ExternalSettings.PostResolve, result.PathPair.Primary.Text) {
if r.debugLogs != nil {
r.debugLogs.addNote(fmt.Sprintf("The path %q was marked as external by the user", result.PathPair.Primary.Text))
}
result.IsExternal = true
return
}
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)
// 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 pkgJSON := dirInfo.enclosingPackageJSON; pkgJSON != nil && *path == result.PathPair.Primary {
if pkgJSON.sideEffectsMap != nil {
hasSideEffects := false
if pkgJSON.sideEffectsMap[path.Text] {
// Fast path: map lookup
hasSideEffects = true
} else {
// Slow path: glob tests
for _, re := range pkgJSON.sideEffectsRegexps {
if re.MatchString(path.Text) {
hasSideEffects = true
break
}
}
}
if !hasSideEffects {
if r.debugLogs != nil {
r.debugLogs.addNote(fmt.Sprintf("Marking this file as having no side effects due to %q",
pkgJSON.source.KeyPath.Text))
}
result.PrimarySideEffectsData = pkgJSON.sideEffectsData
}
}
// Also copy over the "type" field
result.ModuleTypeData = pkgJSON.moduleTypeData
}
// Copy various fields from the nearest enclosing "tsconfig.json" file if present
if path == &result.PathPair.Primary && dirInfo.enclosingTSConfigJSON != nil {
// Except don't do this if we're inside a "node_modules" directory. Package
// authors often publish their "tsconfig.json" files to npm because of
// npm's default-include publishing model and because these authors
// probably don't know about ".npmignore" files.
//
// People trying to use these packages with esbuild have historically
// complained that esbuild is respecting "tsconfig.json" in these cases.
// The assumption is that the package author published these files by
// accident.
//
// Ignoring "tsconfig.json" files inside "node_modules" directories breaks
// the use case of publishing TypeScript code and having it be transpiled
// for you, but that's the uncommon case and likely doesn't work with
// many other tools anyway. So now these files are ignored.
if helpers.IsInsideNodeModules(result.PathPair.Primary.Text) {
if r.debugLogs != nil {
r.debugLogs.addNote(fmt.Sprintf("Ignoring %q because %q is inside \"node_modules\"",
dirInfo.enclosingTSConfigJSON.AbsPath,
result.PathPair.Primary.Text))
}
} else {
result.JSXFactory = dirInfo.enclosingTSConfigJSON.JSXFactory
result.JSXFragment = dirInfo.enclosingTSConfigJSON.JSXFragmentFactory
result.UseDefineForClassFieldsTS = dirInfo.enclosingTSConfigJSON.UseDefineForClassFields
result.UnusedImportsTS = config.UnusedImportsFromTsconfigValues(
dirInfo.enclosingTSConfigJSON.PreserveImportsNotUsedAsValues,
dirInfo.enclosingTSConfigJSON.PreserveValueImports,
)
result.TSTarget = dirInfo.enclosingTSConfigJSON.TSTarget
if r.debugLogs != nil {
r.debugLogs.addNote(fmt.Sprintf("This import is under the effect of %q",
dirInfo.enclosingTSConfigJSON.AbsPath))
if result.JSXFactory != nil {
r.debugLogs.addNote(fmt.Sprintf("\"jsxFactory\" is %q due to %q",
strings.Join(result.JSXFactory, "."),
dirInfo.enclosingTSConfigJSON.AbsPath))
}
if result.JSXFragment != nil {
r.debugLogs.addNote(fmt.Sprintf("\"jsxFragment\" is %q due to %q",
strings.Join(result.JSXFragment, "."),
dirInfo.enclosingTSConfigJSON.AbsPath))
}
}
}
}
if !r.options.PreserveSymlinks {
if entry, _ := dirInfo.entries.Get(base); entry != nil {
if symlink := entry.Symlink(r.fs); symlink != "" {
// Is this entry itself a symlink?
if r.debugLogs != nil {
r.debugLogs.addNote(fmt.Sprintf("Resolved symlink %q to %q", path.Text, symlink))
}
path.Text = symlink
} else if dirInfo.absRealPath != "" {
// Is there at least one parent directory with a symlink?
symlink := r.fs.Join(dirInfo.absRealPath, base)
if r.debugLogs != nil {
r.debugLogs.addNote(fmt.Sprintf("Resolved symlink %q to %q", path.Text, symlink))
}
path.Text = symlink
}
}
}
}
}
}
if r.debugLogs != nil {
r.debugLogs.addNote(fmt.Sprintf("Primary path is %q in namespace %q", result.PathPair.Primary.Text, result.PathPair.Primary.Namespace))
if result.PathPair.HasSecondary() {
r.debugLogs.addNote(fmt.Sprintf("Secondary path is %q in namespace %q", result.PathPair.Secondary.Text, result.PathPair.Secondary.Namespace))
}
}
}
func (r resolverQuery) resolveWithoutSymlinks(sourceDir string, importPath string) *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 ResolveResult
// Return early if this is already an absolute path. In addition to asking
// the file system whether this is an absolute path, we also explicitly check
// whether it starts with a "/" and consider that an absolute path too. This
// is because relative paths can technically start with a "/" on Windows
// because it's not an absolute path on Windows. Then people might write code
// with imports that start with a "/" that works fine on Windows only to
// experience unexpected build failures later on other operating systems.
// Treating these paths as absolute paths on all platforms means Windows
// users will not be able to accidentally make use of these paths.
if strings.HasPrefix(importPath, "/") || r.fs.IsAbs(importPath) {
if r.debugLogs != nil {
r.debugLogs.addNote(fmt.Sprintf("The import %q is being treated as an absolute path", importPath))
}
// First, check path overrides from the nearest enclosing TypeScript "tsconfig.json" file
if dirInfo := r.dirInfoCached(sourceDir); dirInfo != nil && dirInfo.enclosingTSConfigJSON != nil && dirInfo.enclosingTSConfigJSON.Paths != nil {
if absolute, ok, diffCase := r.matchTSConfigPaths(dirInfo.enclosingTSConfigJSON, importPath); ok {
return &ResolveResult{PathPair: absolute, DifferentCase: diffCase}
}
}
// Run node's resolution rules (e.g. adding ".js")
if absolute, ok, diffCase := r.loadAsFileOrDirectory(importPath); ok {
return &ResolveResult{PathPair: absolute, DifferentCase: diffCase}
} else {
return nil
}
}
// 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 || r.kind == ast.ImportURL || r.kind == ast.ImportAt
checkPackage := isPackagePath
if checkRelative {
absPath := r.fs.Join(sourceDir, importPath)
// Check for external packages first
if r.isExternal(r.options.ExternalSettings.PostResolve, absPath) {
if r.debugLogs != nil {
r.debugLogs.addNote(fmt.Sprintf("The path %q was marked as external by the user", absPath))
}
return &ResolveResult{PathPair: PathPair{Primary: logger.Path{Text: absPath, Namespace: "file"}}, IsExternal: true}
}
// Check the "browser" map
if importDirInfo := r.dirInfoCached(r.fs.Dir(absPath)); importDirInfo != nil {
if remapped, ok := r.checkBrowserMap(importDirInfo, absPath, absolutePathKind); ok {
if remapped == nil {
return &ResolveResult{PathPair: PathPair{Primary: logger.Path{Text: absPath, Namespace: "file", Flags: logger.PathDisabled}}}
}
if remappedResult, ok, diffCase := r.resolveWithoutRemapping(importDirInfo.enclosingBrowserScope, *remapped); ok {
result = ResolveResult{PathPair: remappedResult, DifferentCase: diffCase}
checkRelative = false
checkPackage = false
}
}
}
if checkRelative {
if absolute, ok, diffCase := r.loadAsFileOrDirectory(absPath); ok {
checkPackage = false
result = ResolveResult{PathPair: absolute, DifferentCase: diffCase}
} else if !checkPackage {
return nil
}
}
}
if checkPackage {
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 remapped, ok := r.checkBrowserMap(sourceDirInfo, importPath, packagePathKind); ok {
if remapped == nil {
// "browser": {"module": false}
if absolute, ok, diffCase := r.loadNodeModules(importPath, sourceDirInfo, false /* forbidImports */); ok {
absolute.Primary = logger.Path{Text: absolute.Primary.Text, Namespace: "file", Flags: logger.PathDisabled}
if absolute.HasSecondary() {
absolute.Secondary = logger.Path{Text: absolute.Secondary.Text, Namespace: "file", Flags: logger.PathDisabled}
}
return &ResolveResult{PathPair: absolute, DifferentCase: diffCase}
} else {
return &ResolveResult{PathPair: PathPair{Primary: logger.Path{Text: importPath, Flags: logger.PathDisabled}}, DifferentCase: diffCase}
}
}
// "browser": {"module": "./some-file"}
// "browser": {"module": "another-module"}
importPath = *remapped
sourceDirInfo = sourceDirInfo.enclosingBrowserScope
}
if absolute, ok, diffCase := r.resolveWithoutRemapping(sourceDirInfo, importPath); ok {
result = ResolveResult{PathPair: absolute, DifferentCase: diffCase}
} else {
// Note: node's "self references" are not currently supported
return nil
}
}
return &result
}
func (r resolverQuery) resolveWithoutRemapping(sourceDirInfo *dirInfo, importPath string) (PathPair, bool, *fs.DifferentCase) {
if IsPackagePath(importPath) {
return r.loadNodeModules(importPath, sourceDirInfo, false /* forbidImports */)
} else {
return r.loadAsFileOrDirectory(r.fs.Join(sourceDirInfo.absPath, importPath))
}
}
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.
path.Text = strings.ReplaceAll(path.Text, "\\", "/")
} else if path.Namespace != "" {
path.Text = fmt.Sprintf("%s:%s", path.Namespace, path.Text)
}
if path.IsDisabled() {
path.Text = "(disabled):" + path.Text
}
return path.Text + path.IgnoredSuffix
}
////////////////////////////////////////////////////////////////////////////////
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 fs.DirEntries
packageJSON *packageJSON // Is there a "package.json" file in this directory?
enclosingPackageJSON *packageJSON // Is there a "package.json" file in this directory or a parent directory?
enclosingTSConfigJSON *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
isNodeModules bool // Is the base name "node_modules"?
hasNodeModules bool // Is there a "node_modules" subdirectory?
}
func (r resolverQuery) dirInfoCached(path string) *dirInfo {
// First, check the cache
cached, ok := r.dirCache[path]
// Cache hit: stop now
if !ok {
// Cache miss: read the info
cached = 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] = cached
}
if r.debugLogs != nil {
if cached == nil {
r.debugLogs.addNote(fmt.Sprintf("Failed to read directory %q", path))
} else {
count := len(cached.entries.SortedKeys())
entries := "entries"
if count == 1 {
entries = "entry"
}
r.debugLogs.addNote(fmt.Sprintf("Read %d %s for directory %q", count, entries, path))
}
}
return cached
}
var errParseErrorImportCycle = errors.New("(import cycle)")
var errParseErrorAlreadyLogged = 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 resolverQuery) 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, errParseErrorImportCycle
}
isExtends := len(visited) != 0
visited[file] = true
contents, err, originalError := r.caches.FSCache.ReadFile(r.fs, file)
if r.debugLogs != nil && originalError != nil {
r.debugLogs.addNote(fmt.Sprintf("Failed to read file %q: %s", file, originalError.Error()))
}