-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathbundler.go
3374 lines (3033 loc) · 118 KB
/
bundler.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 bundler
// The bundler is the core of the "build" and "transform" API calls. Each
// operation has two phases. The first phase scans the module graph, and is
// represented by the "ScanBundle" function. The second phase generates the
// output files from the module graph, and is implemented by the "Compile"
// function.
import (
"bytes"
"encoding/base32"
"encoding/base64"
"fmt"
"math/rand"
"net/http"
"net/url"
"sort"
"strings"
"sync"
"syscall"
"time"
"unicode"
"unicode/utf8"
"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/css_parser"
"github.com/evanw/esbuild/internal/fs"
"github.com/evanw/esbuild/internal/graph"
"github.com/evanw/esbuild/internal/helpers"
"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"
"github.com/evanw/esbuild/internal/resolver"
"github.com/evanw/esbuild/internal/runtime"
"github.com/evanw/esbuild/internal/sourcemap"
"github.com/evanw/esbuild/internal/xxhash"
)
type scannerFile struct {
// If "AbsMetadataFile" is present, this will be filled out with information
// about this file in JSON format. This is a partial JSON file that will be
// fully assembled later.
jsonMetadataChunk string
pluginData interface{}
inputFile graph.InputFile
}
// This is data related to source maps. It's computed in parallel with linking
// and must be ready by the time printing happens. This is beneficial because
// it is somewhat expensive to produce.
type DataForSourceMap struct {
// This data is for the printer. It maps from byte offsets in the file (which
// are stored at every AST node) to UTF-16 column offsets (required by source
// maps).
LineOffsetTables []sourcemap.LineOffsetTable
// This contains the quoted contents of the original source file. It's what
// needs to be embedded in the "sourcesContent" array in the final source
// map. Quoting is precomputed because it's somewhat expensive.
QuotedContents [][]byte
}
type Bundle struct {
// The unique key prefix is a random string that is unique to every bundling
// operation. It is used as a prefix for the unique keys assigned to every
// chunk during linking. These unique keys are used to identify each chunk
// before the final output paths have been computed.
uniqueKeyPrefix string
fs fs.FS
res *resolver.Resolver
files []scannerFile
entryPoints []graph.EntryPoint
options config.Options
}
type parseArgs struct {
fs fs.FS
log logger.Log
res *resolver.Resolver
caches *cache.CacheSet
prettyPath string
importSource *logger.Source
importWith *ast.ImportAssertOrWith
sideEffects graph.SideEffects
pluginData interface{}
results chan parseResult
inject chan config.InjectedFile
uniqueKeyPrefix string
keyPath logger.Path
options config.Options
importPathRange logger.Range
sourceIndex uint32
skipResolve bool
}
type parseResult struct {
resolveResults []*resolver.ResolveResult
globResolveResults map[uint32]globResolveResult
file scannerFile
tlaCheck tlaCheck
ok bool
}
type globResolveResult struct {
resolveResults map[string]resolver.ResolveResult
absPath string
prettyPath string
exportAlias string
}
type tlaCheck struct {
parent ast.Index32
depth uint32
importRecordIndex uint32
}
func parseFile(args parseArgs) {
pathForIdentifierName := args.keyPath.Text
// Identifier name generation may use the name of the parent folder if the
// file name starts with "index". However, this is problematic when the
// parent folder includes the parent directory of what the developer
// considers to be the root of the source tree. If that happens, strip the
// parent folder to avoid including it in the generated name.
if relative, ok := args.fs.Rel(args.options.AbsOutputBase, pathForIdentifierName); ok {
for {
next := strings.TrimPrefix(strings.TrimPrefix(relative, "../"), "..\\")
if relative == next {
break
}
relative = next
}
pathForIdentifierName = relative
}
source := logger.Source{
Index: args.sourceIndex,
KeyPath: args.keyPath,
PrettyPath: args.prettyPath,
IdentifierName: js_ast.GenerateNonUniqueNameFromPath(pathForIdentifierName),
}
var loader config.Loader
var absResolveDir string
var pluginName string
var pluginData interface{}
if stdin := args.options.Stdin; stdin != nil {
// Special-case stdin
source.Contents = stdin.Contents
loader = stdin.Loader
if loader == config.LoaderNone {
loader = config.LoaderJS
}
absResolveDir = args.options.Stdin.AbsResolveDir
} else {
result, ok := runOnLoadPlugins(
args.options.Plugins,
args.fs,
&args.caches.FSCache,
args.log,
&source,
args.importSource,
args.importPathRange,
args.pluginData,
args.options.WatchMode,
)
if !ok {
if args.inject != nil {
args.inject <- config.InjectedFile{
Source: source,
}
}
args.results <- parseResult{}
return
}
loader = result.loader
absResolveDir = result.absResolveDir
pluginName = result.pluginName
pluginData = result.pluginData
}
_, base, ext := logger.PlatformIndependentPathDirBaseExt(source.KeyPath.Text)
// The special "default" loader determines the loader from the file path
if loader == config.LoaderDefault {
loader = config.LoaderFromFileExtension(args.options.ExtensionToLoader, base+ext)
}
// Reject unsupported import attributes when the loader isn't "copy" (since
// "copy" is kind of like "external"). But only do this if this file was not
// loaded by a plugin. Plugins are allowed to assign whatever semantics they
// want to import attributes.
if loader != config.LoaderCopy && pluginName == "" {
for _, attr := range source.KeyPath.ImportAttributes.DecodeIntoArray() {
var errorText string
var errorRange js_lexer.KeyOrValue
// We only currently handle "type: json"
if attr.Key != "type" {
errorText = fmt.Sprintf("Importing with the %q attribute is not supported", attr.Key)
errorRange = js_lexer.KeyRange
} else if attr.Value == "json" {
loader = config.LoaderWithTypeJSON
continue
} else {
errorText = fmt.Sprintf("Importing with a type attribute of %q is not supported", attr.Value)
errorRange = js_lexer.ValueRange
}
// Everything else is an error
r := args.importPathRange
if args.importWith != nil {
r = js_lexer.RangeOfImportAssertOrWith(*args.importSource, *ast.FindAssertOrWithEntry(args.importWith.Entries, attr.Key), errorRange)
}
tracker := logger.MakeLineColumnTracker(args.importSource)
args.log.AddError(&tracker, r, errorText)
if args.inject != nil {
args.inject <- config.InjectedFile{
Source: source,
}
}
args.results <- parseResult{}
return
}
}
if loader == config.LoaderEmpty {
source.Contents = ""
}
result := parseResult{
file: scannerFile{
inputFile: graph.InputFile{
Source: source,
Loader: loader,
SideEffects: args.sideEffects,
},
pluginData: pluginData,
},
}
defer func() {
r := recover()
if r != nil {
args.log.AddErrorWithNotes(nil, logger.Range{},
fmt.Sprintf("panic: %v (while parsing %q)", r, source.PrettyPath),
[]logger.MsgData{{Text: helpers.PrettyPrintedStack()}})
args.results <- result
}
}()
switch loader {
case config.LoaderJS, config.LoaderEmpty:
ast, ok := args.caches.JSCache.Parse(args.log, source, js_parser.OptionsFromConfig(&args.options))
if len(ast.Parts) <= 1 { // Ignore the implicitly-generated namespace export part
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_EmptyAST
}
result.file.inputFile.Repr = &graph.JSRepr{AST: ast}
result.ok = ok
case config.LoaderJSX:
args.options.JSX.Parse = true
ast, ok := args.caches.JSCache.Parse(args.log, source, js_parser.OptionsFromConfig(&args.options))
if len(ast.Parts) <= 1 { // Ignore the implicitly-generated namespace export part
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_EmptyAST
}
result.file.inputFile.Repr = &graph.JSRepr{AST: ast}
result.ok = ok
case config.LoaderTS, config.LoaderTSNoAmbiguousLessThan:
args.options.TS.Parse = true
args.options.TS.NoAmbiguousLessThan = loader == config.LoaderTSNoAmbiguousLessThan
ast, ok := args.caches.JSCache.Parse(args.log, source, js_parser.OptionsFromConfig(&args.options))
if len(ast.Parts) <= 1 { // Ignore the implicitly-generated namespace export part
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_EmptyAST
}
result.file.inputFile.Repr = &graph.JSRepr{AST: ast}
result.ok = ok
case config.LoaderTSX:
args.options.TS.Parse = true
args.options.JSX.Parse = true
ast, ok := args.caches.JSCache.Parse(args.log, source, js_parser.OptionsFromConfig(&args.options))
if len(ast.Parts) <= 1 { // Ignore the implicitly-generated namespace export part
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_EmptyAST
}
result.file.inputFile.Repr = &graph.JSRepr{AST: ast}
result.ok = ok
case config.LoaderCSS, config.LoaderGlobalCSS, config.LoaderLocalCSS:
ast := args.caches.CSSCache.Parse(args.log, source, css_parser.OptionsFromConfig(loader, &args.options))
result.file.inputFile.Repr = &graph.CSSRepr{AST: ast}
result.ok = true
case config.LoaderJSON, config.LoaderWithTypeJSON:
expr, ok := args.caches.JSONCache.Parse(args.log, source, js_parser.JSONOptions{
UnsupportedJSFeatures: args.options.UnsupportedJSFeatures,
})
ast := js_parser.LazyExportAST(args.log, source, js_parser.OptionsFromConfig(&args.options), expr, "")
if loader == config.LoaderWithTypeJSON {
// The exports kind defaults to "none", in which case the linker picks
// either ESM or CommonJS depending on the situation. Dynamic imports
// causes the linker to pick CommonJS which uses "require()" and then
// converts the return value to ESM, which adds extra properties that
// aren't supposed to be there when "{ with: { type: 'json' } }" is
// present. So if there's an import attribute, we force the type to
// be ESM to avoid this.
ast.ExportsKind = js_ast.ExportsESM
}
if pluginName != "" {
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_PureData_FromPlugin
} else {
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_PureData
}
result.file.inputFile.Repr = &graph.JSRepr{AST: ast}
result.ok = ok
case config.LoaderText:
source.Contents = strings.TrimPrefix(source.Contents, "\xEF\xBB\xBF") // Strip any UTF-8 BOM from the text
encoded := base64.StdEncoding.EncodeToString([]byte(source.Contents))
expr := js_ast.Expr{Data: &js_ast.EString{Value: helpers.StringToUTF16(source.Contents)}}
ast := js_parser.LazyExportAST(args.log, source, js_parser.OptionsFromConfig(&args.options), expr, "")
ast.URLForCSS = "data:text/plain;base64," + encoded
if pluginName != "" {
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_PureData_FromPlugin
} else {
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_PureData
}
result.file.inputFile.Repr = &graph.JSRepr{AST: ast}
result.ok = true
case config.LoaderBase64:
mimeType := guessMimeType(ext, source.Contents)
encoded := base64.StdEncoding.EncodeToString([]byte(source.Contents))
expr := js_ast.Expr{Data: &js_ast.EString{Value: helpers.StringToUTF16(encoded)}}
ast := js_parser.LazyExportAST(args.log, source, js_parser.OptionsFromConfig(&args.options), expr, "")
ast.URLForCSS = "data:" + mimeType + ";base64," + encoded
if pluginName != "" {
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_PureData_FromPlugin
} else {
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_PureData
}
result.file.inputFile.Repr = &graph.JSRepr{AST: ast}
result.ok = true
case config.LoaderBinary:
encoded := base64.StdEncoding.EncodeToString([]byte(source.Contents))
expr := js_ast.Expr{Data: &js_ast.EString{Value: helpers.StringToUTF16(encoded)}}
helper := "__toBinary"
if args.options.Platform == config.PlatformNode {
helper = "__toBinaryNode"
}
ast := js_parser.LazyExportAST(args.log, source, js_parser.OptionsFromConfig(&args.options), expr, helper)
ast.URLForCSS = "data:application/octet-stream;base64," + encoded
if pluginName != "" {
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_PureData_FromPlugin
} else {
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_PureData
}
result.file.inputFile.Repr = &graph.JSRepr{AST: ast}
result.ok = true
case config.LoaderDataURL:
mimeType := guessMimeType(ext, source.Contents)
url := helpers.EncodeStringAsShortestDataURL(mimeType, source.Contents)
expr := js_ast.Expr{Data: &js_ast.EString{Value: helpers.StringToUTF16(url)}}
ast := js_parser.LazyExportAST(args.log, source, js_parser.OptionsFromConfig(&args.options), expr, "")
ast.URLForCSS = url
if pluginName != "" {
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_PureData_FromPlugin
} else {
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_PureData
}
result.file.inputFile.Repr = &graph.JSRepr{AST: ast}
result.ok = true
case config.LoaderFile:
uniqueKey := fmt.Sprintf("%sA%08d", args.uniqueKeyPrefix, args.sourceIndex)
uniqueKeyPath := uniqueKey + source.KeyPath.IgnoredSuffix
expr := js_ast.Expr{Data: &js_ast.EString{
Value: helpers.StringToUTF16(uniqueKeyPath),
ContainsUniqueKey: true,
}}
ast := js_parser.LazyExportAST(args.log, source, js_parser.OptionsFromConfig(&args.options), expr, "")
ast.URLForCSS = uniqueKeyPath
if pluginName != "" {
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_PureData_FromPlugin
} else {
result.file.inputFile.SideEffects.Kind = graph.NoSideEffects_PureData
}
result.file.inputFile.Repr = &graph.JSRepr{AST: ast}
result.ok = true
// Mark that this file is from the "file" loader
result.file.inputFile.UniqueKeyForAdditionalFile = uniqueKey
case config.LoaderCopy:
uniqueKey := fmt.Sprintf("%sA%08d", args.uniqueKeyPrefix, args.sourceIndex)
uniqueKeyPath := uniqueKey + source.KeyPath.IgnoredSuffix
result.file.inputFile.Repr = &graph.CopyRepr{
URLForCode: uniqueKeyPath,
}
result.ok = true
// Mark that this file is from the "copy" loader
result.file.inputFile.UniqueKeyForAdditionalFile = uniqueKey
default:
var message string
if source.KeyPath.Namespace == "file" && ext != "" {
message = fmt.Sprintf("No loader is configured for %q files: %s", ext, source.PrettyPath)
} else {
message = fmt.Sprintf("Do not know how to load path: %s", source.PrettyPath)
}
tracker := logger.MakeLineColumnTracker(args.importSource)
args.log.AddError(&tracker, args.importPathRange, message)
}
// Only continue now if parsing was successful
if result.ok {
// Run the resolver on the parse thread so it's not run on the main thread.
// That way the main thread isn't blocked if the resolver takes a while.
if recordsPtr := result.file.inputFile.Repr.ImportRecords(); args.options.Mode == config.ModeBundle && !args.skipResolve && recordsPtr != nil {
// Clone the import records because they will be mutated later
records := append([]ast.ImportRecord{}, *recordsPtr...)
*recordsPtr = records
result.resolveResults = make([]*resolver.ResolveResult, len(records))
if len(records) > 0 {
type cacheEntry struct {
resolveResult *resolver.ResolveResult
debug resolver.DebugMeta
didLogError bool
}
type cacheKey struct {
kind ast.ImportKind
path string
attrs logger.ImportAttributes
}
resolverCache := make(map[cacheKey]cacheEntry)
tracker := logger.MakeLineColumnTracker(&source)
for importRecordIndex := range records {
// Don't try to resolve imports that are already resolved
record := &records[importRecordIndex]
if record.SourceIndex.IsValid() {
continue
}
// Encode the import attributes
var attrs logger.ImportAttributes
if record.AssertOrWith != nil && record.AssertOrWith.Keyword == ast.WithKeyword {
data := make(map[string]string, len(record.AssertOrWith.Entries))
for _, entry := range record.AssertOrWith.Entries {
data[helpers.UTF16ToString(entry.Key)] = helpers.UTF16ToString(entry.Value)
}
attrs = logger.EncodeImportAttributes(data)
}
// Special-case glob pattern imports
if record.GlobPattern != nil {
prettyPath := helpers.GlobPatternToString(record.GlobPattern.Parts)
switch record.GlobPattern.Kind {
case ast.ImportRequire:
prettyPath = fmt.Sprintf("require(%q)", prettyPath)
case ast.ImportDynamic:
prettyPath = fmt.Sprintf("import(%q)", prettyPath)
}
if results, msg := args.res.ResolveGlob(absResolveDir, record.GlobPattern.Parts, record.GlobPattern.Kind, prettyPath); results != nil {
if msg != nil {
args.log.AddID(msg.ID, msg.Kind, &tracker, record.Range, msg.Data.Text)
}
if result.globResolveResults == nil {
result.globResolveResults = make(map[uint32]globResolveResult)
}
for key, result := range results {
result.PathPair.Primary.ImportAttributes = attrs
if result.PathPair.HasSecondary() {
result.PathPair.Secondary.ImportAttributes = attrs
}
results[key] = result
}
result.globResolveResults[uint32(importRecordIndex)] = globResolveResult{
resolveResults: results,
absPath: args.fs.Join(absResolveDir, "(glob)"),
prettyPath: fmt.Sprintf("%s in %s", prettyPath, result.file.inputFile.Source.PrettyPath),
exportAlias: record.GlobPattern.ExportAlias,
}
} else {
args.log.AddError(&tracker, record.Range, fmt.Sprintf("Could not resolve %s", prettyPath))
}
continue
}
// Ignore records that the parser has discarded. This is used to remove
// type-only imports in TypeScript files.
if record.Flags.Has(ast.IsUnused) {
continue
}
// Cache the path in case it's imported multiple times in this file
cacheKey := cacheKey{
kind: record.Kind,
path: record.Path.Text,
attrs: attrs,
}
entry, ok := resolverCache[cacheKey]
if ok {
result.resolveResults[importRecordIndex] = entry.resolveResult
} else {
// Run the resolver and log an error if the path couldn't be resolved
resolveResult, didLogError, debug := RunOnResolvePlugins(
args.options.Plugins,
args.res,
args.log,
args.fs,
&args.caches.FSCache,
&source,
record.Range,
source.KeyPath,
record.Path.Text,
attrs,
record.Kind,
absResolveDir,
pluginData,
)
if resolveResult != nil {
resolveResult.PathPair.Primary.ImportAttributes = attrs
if resolveResult.PathPair.HasSecondary() {
resolveResult.PathPair.Secondary.ImportAttributes = attrs
}
}
entry = cacheEntry{
resolveResult: resolveResult,
debug: debug,
didLogError: didLogError,
}
resolverCache[cacheKey] = entry
// All "require.resolve()" imports should be external because we don't
// want to waste effort traversing into them
if record.Kind == ast.ImportRequireResolve {
if resolveResult != nil && resolveResult.PathPair.IsExternal {
// Allow path substitution as long as the result is external
result.resolveResults[importRecordIndex] = resolveResult
} else if !record.Flags.Has(ast.HandlesImportErrors) {
args.log.AddID(logger.MsgID_Bundler_RequireResolveNotExternal, logger.Warning, &tracker, record.Range,
fmt.Sprintf("%q should be marked as external for use with \"require.resolve\"", record.Path.Text))
}
continue
}
}
// Check whether we should log an error every time the result is nil,
// even if it's from the cache. Do this because the error may not
// have been logged for nil entries if the previous instances had
// the "HandlesImportErrors" flag.
if entry.resolveResult == nil {
// Failed imports inside a try/catch are silently turned into
// external imports instead of causing errors. This matches a common
// code pattern for conditionally importing a module with a graceful
// fallback.
if !entry.didLogError && !record.Flags.Has(ast.HandlesImportErrors) {
// Report an error
text, suggestion, notes := ResolveFailureErrorTextSuggestionNotes(args.res, record.Path.Text, record.Kind,
pluginName, args.fs, absResolveDir, args.options.Platform, source.PrettyPath, entry.debug.ModifiedImportPath)
entry.debug.LogErrorMsg(args.log, &source, record.Range, text, suggestion, notes)
// Only report this error once per unique import path in the file
entry.didLogError = true
resolverCache[cacheKey] = entry
} else if !entry.didLogError && record.Flags.Has(ast.HandlesImportErrors) {
// Report a debug message about why there was no error
args.log.AddIDWithNotes(logger.MsgID_Bundler_IgnoredDynamicImport, logger.Debug, &tracker, record.Range,
fmt.Sprintf("Importing %q was allowed even though it could not be resolved because dynamic import failures appear to be handled here:",
record.Path.Text), []logger.MsgData{tracker.MsgData(js_lexer.RangeOfIdentifier(source, record.ErrorHandlerLoc),
"The handler for dynamic import failures is here:")})
}
continue
}
result.resolveResults[importRecordIndex] = entry.resolveResult
}
}
}
// Attempt to parse the source map if present
if loader.CanHaveSourceMap() && args.options.SourceMap != config.SourceMapNone {
var sourceMapComment logger.Span
switch repr := result.file.inputFile.Repr.(type) {
case *graph.JSRepr:
sourceMapComment = repr.AST.SourceMapComment
case *graph.CSSRepr:
sourceMapComment = repr.AST.SourceMapComment
}
if sourceMapComment.Text != "" {
tracker := logger.MakeLineColumnTracker(&source)
if path, contents := extractSourceMapFromComment(args.log, args.fs, &args.caches.FSCache,
&source, &tracker, sourceMapComment, absResolveDir); contents != nil {
prettyPath := resolver.PrettyPath(args.fs, path)
log := logger.NewDeferLog(logger.DeferLogNoVerboseOrDebug, args.log.Overrides)
sourceMap := js_parser.ParseSourceMap(log, logger.Source{
KeyPath: path,
PrettyPath: prettyPath,
Contents: *contents,
})
if msgs := log.Done(); len(msgs) > 0 {
var text string
if path.Namespace == "file" {
text = fmt.Sprintf("The source map %q was referenced by the file %q here:", prettyPath, args.prettyPath)
} else {
text = fmt.Sprintf("This source map came from the file %q here:", args.prettyPath)
}
note := tracker.MsgData(sourceMapComment.Range, text)
for _, msg := range msgs {
msg.Notes = append(msg.Notes, note)
args.log.AddMsg(msg)
}
}
// If "sourcesContent" entries aren't present, try filling them in
// using the file system. This includes both generating the entire
// "sourcesContent" array if it's absent as well as filling in
// individual null entries in the array if the array is present.
if sourceMap != nil && !args.options.ExcludeSourcesContent {
// Make sure "sourcesContent" is big enough
if len(sourceMap.SourcesContent) < len(sourceMap.Sources) {
slice := make([]sourcemap.SourceContent, len(sourceMap.Sources))
copy(slice, sourceMap.SourcesContent)
sourceMap.SourcesContent = slice
}
// Attempt to fill in null entries using the file system
for i, source := range sourceMap.Sources {
if sourceMap.SourcesContent[i].Value == nil {
if sourceURL, err := url.Parse(source); err == nil && helpers.IsFileURL(sourceURL) {
if contents, err, _ := args.caches.FSCache.ReadFile(args.fs, helpers.FilePathFromFileURL(args.fs, sourceURL)); err == nil {
sourceMap.SourcesContent[i].Value = helpers.StringToUTF16(contents)
}
}
}
}
}
result.file.inputFile.InputSourceMap = sourceMap
}
}
}
}
// Note: We must always send on the "inject" channel before we send on the
// "results" channel to avoid deadlock
if args.inject != nil {
var exports []config.InjectableExport
if repr, ok := result.file.inputFile.Repr.(*graph.JSRepr); ok {
aliases := make([]string, 0, len(repr.AST.NamedExports))
for alias := range repr.AST.NamedExports {
aliases = append(aliases, alias)
}
sort.Strings(aliases) // Sort for determinism
exports = make([]config.InjectableExport, len(aliases))
for i, alias := range aliases {
exports[i] = config.InjectableExport{
Alias: alias,
Loc: repr.AST.NamedExports[alias].AliasLoc,
}
}
}
// Once we send on the "inject" channel, the main thread may mutate the
// "options" object to populate the "InjectedFiles" field. So we must
// only send on the "inject" channel after we're done using the "options"
// object so we don't introduce a data race.
isCopyLoader := loader == config.LoaderCopy
if isCopyLoader && args.skipResolve {
// This is not allowed because the import path would have to be rewritten,
// but import paths are not rewritten when bundling isn't enabled.
args.log.AddError(nil, logger.Range{},
fmt.Sprintf("Cannot inject %q with the \"copy\" loader without bundling enabled", source.PrettyPath))
}
args.inject <- config.InjectedFile{
Source: source,
Exports: exports,
IsCopyLoader: isCopyLoader,
}
}
args.results <- result
}
func ResolveFailureErrorTextSuggestionNotes(
res *resolver.Resolver,
path string,
kind ast.ImportKind,
pluginName string,
fs fs.FS,
absResolveDir string,
platform config.Platform,
originatingFilePath string,
modifiedImportPath string,
) (text string, suggestion string, notes []logger.MsgData) {
if modifiedImportPath != "" {
text = fmt.Sprintf("Could not resolve %q (originally %q)", modifiedImportPath, path)
notes = append(notes, logger.MsgData{Text: fmt.Sprintf(
"The path %q was remapped to %q using the alias feature, which then couldn't be resolved. "+
"Keep in mind that import path aliases are resolved in the current working directory.",
path, modifiedImportPath)})
path = modifiedImportPath
} else {
text = fmt.Sprintf("Could not resolve %q", path)
}
hint := ""
if resolver.IsPackagePath(path) && !fs.IsAbs(path) {
hint = fmt.Sprintf("You can mark the path %q as external to exclude it from the bundle, which will remove this error and leave the unresolved path in the bundle.", path)
if kind == ast.ImportRequire {
hint += " You can also surround this \"require\" call with a try/catch block to handle this failure at run-time instead of bundle-time."
} else if kind == ast.ImportDynamic {
hint += " You can also add \".catch()\" here to handle this failure at run-time instead of bundle-time."
}
if pluginName == "" && !fs.IsAbs(path) {
if query, _ := res.ProbeResolvePackageAsRelative(absResolveDir, path, kind); query != nil {
hint = fmt.Sprintf("Use the relative path %q to reference the file %q. "+
"Without the leading \"./\", the path %q is being interpreted as a package path instead.",
"./"+path, resolver.PrettyPath(fs, query.PathPair.Primary), path)
suggestion = string(helpers.QuoteForJSON("./"+path, false))
}
}
}
if platform != config.PlatformNode {
pkg := strings.TrimPrefix(path, "node:")
if resolver.BuiltInNodeModules[pkg] {
var how string
switch logger.API {
case logger.CLIAPI:
how = "--platform=node"
case logger.JSAPI:
how = "platform: 'node'"
case logger.GoAPI:
how = "Platform: api.PlatformNode"
}
hint = fmt.Sprintf("The package %q wasn't found on the file system but is built into node. "+
"Are you trying to bundle for node? You can use %q to do that, which will remove this error.", path, how)
}
}
if absResolveDir == "" && pluginName != "" {
where := ""
if originatingFilePath != "" {
where = fmt.Sprintf(" for the file %q", originatingFilePath)
}
hint = fmt.Sprintf("The plugin %q didn't set a resolve directory%s, "+
"so esbuild did not search for %q on the file system.", pluginName, where, path)
}
if hint != "" {
if modifiedImportPath != "" {
// Add a newline if there's already a paragraph of text
notes = append(notes, logger.MsgData{})
// Don't add a suggestion if the path was rewritten using an alias
suggestion = ""
}
notes = append(notes, logger.MsgData{Text: hint})
}
return
}
func isASCIIOnly(text string) bool {
for _, c := range text {
if c < 0x20 || c > 0x7E {
return false
}
}
return true
}
func guessMimeType(extension string, contents string) string {
mimeType := helpers.MimeTypeByExtension(extension)
if mimeType == "" {
mimeType = http.DetectContentType([]byte(contents))
}
// Turn "text/plain; charset=utf-8" into "text/plain;charset=utf-8"
return strings.ReplaceAll(mimeType, "; ", ";")
}
func extractSourceMapFromComment(
log logger.Log,
fs fs.FS,
fsCache *cache.FSCache,
source *logger.Source,
tracker *logger.LineColumnTracker,
comment logger.Span,
absResolveDir string,
) (logger.Path, *string) {
// Support data URLs
if parsed, ok := resolver.ParseDataURL(comment.Text); ok {
contents, err := parsed.DecodeData()
if err != nil {
log.AddID(logger.MsgID_SourceMap_UnsupportedSourceMapComment, logger.Warning, tracker, comment.Range,
fmt.Sprintf("Unsupported source map comment: %s", err.Error()))
return logger.Path{}, nil
}
return logger.Path{Text: source.PrettyPath, IgnoredSuffix: "#sourceMappingURL"}, &contents
}
// Support file URLs of two forms:
//
// Relative: "./foo.js.map"
// Absolute: "file:///Users/User/Desktop/foo.js.map"
//
var absPath string
if commentURL, err := url.Parse(comment.Text); err != nil {
// Show a warning if the comment can't be parsed as a URL
log.AddID(logger.MsgID_SourceMap_UnsupportedSourceMapComment, logger.Warning, tracker, comment.Range,
fmt.Sprintf("Unsupported source map comment: %s", err.Error()))
return logger.Path{}, nil
} else if commentURL.Scheme != "" && commentURL.Scheme != "file" {
// URLs with schemes other than "file" are unsupported (e.g. "https"),
// but don't warn the user about this because it's not a bug they can fix
log.AddID(logger.MsgID_SourceMap_UnsupportedSourceMapComment, logger.Debug, tracker, comment.Range,
fmt.Sprintf("Unsupported source map comment: Unsupported URL scheme %q", commentURL.Scheme))
return logger.Path{}, nil
} else if commentURL.Host != "" && commentURL.Host != "localhost" {
// File URLs with hosts are unsupported (e.g. "file://foo.js.map")
log.AddID(logger.MsgID_SourceMap_UnsupportedSourceMapComment, logger.Warning, tracker, comment.Range,
fmt.Sprintf("Unsupported source map comment: Unsupported host %q in file URL", commentURL.Host))
return logger.Path{}, nil
} else if helpers.IsFileURL(commentURL) {
// Handle absolute file URLs
absPath = helpers.FilePathFromFileURL(fs, commentURL)
} else if absResolveDir == "" {
// Fail if plugins don't set a resolve directory
log.AddID(logger.MsgID_SourceMap_UnsupportedSourceMapComment, logger.Debug, tracker, comment.Range,
"Unsupported source map comment: Cannot resolve relative URL without a resolve directory")
return logger.Path{}, nil
} else {
// Join the (potentially relative) URL path from the comment text
// to the resolve directory path to form the final absolute path
absResolveURL := helpers.FileURLFromFilePath(absResolveDir)
if !strings.HasSuffix(absResolveURL.Path, "/") {
absResolveURL.Path += "/"
}
absPath = helpers.FilePathFromFileURL(fs, absResolveURL.ResolveReference(commentURL))
}
// Try to read the file contents
path := logger.Path{Text: absPath, Namespace: "file"}
if contents, err, _ := fsCache.ReadFile(fs, absPath); err == syscall.ENOENT {
log.AddID(logger.MsgID_SourceMap_MissingSourceMap, logger.Debug, tracker, comment.Range,
fmt.Sprintf("Cannot read file: %s", absPath))
return logger.Path{}, nil
} else if err != nil {
log.AddID(logger.MsgID_SourceMap_MissingSourceMap, logger.Warning, tracker, comment.Range,
fmt.Sprintf("Cannot read file %q: %s", resolver.PrettyPath(fs, path), err.Error()))
return logger.Path{}, nil
} else {
return path, &contents
}
}
func sanitizeLocation(fs fs.FS, loc *logger.MsgLocation) {
if loc != nil {
if loc.Namespace == "" {
loc.Namespace = "file"
}
if loc.File != "" {
loc.File = resolver.PrettyPath(fs, logger.Path{Text: loc.File, Namespace: loc.Namespace})
}
}
}
func logPluginMessages(
fs fs.FS,
log logger.Log,
name string,
msgs []logger.Msg,
thrown error,
importSource *logger.Source,
importPathRange logger.Range,
) bool {
didLogError := false
tracker := logger.MakeLineColumnTracker(importSource)
// Report errors and warnings generated by the plugin
for _, msg := range msgs {
if msg.PluginName == "" {
msg.PluginName = name
}
if msg.Kind == logger.Error {
didLogError = true
}
// Sanitize the locations
for _, note := range msg.Notes {
sanitizeLocation(fs, note.Location)
}
if msg.Data.Location == nil {
msg.Data.Location = tracker.MsgLocationOrNil(importPathRange)
} else {
sanitizeLocation(fs, msg.Data.Location)
if importSource != nil {
if msg.Data.Location.File == "" {
msg.Data.Location.File = importSource.PrettyPath
}
msg.Notes = append(msg.Notes, tracker.MsgData(importPathRange,
fmt.Sprintf("The plugin %q was triggered by this import", name)))
}
}
log.AddMsg(msg)
}
// Report errors thrown by the plugin itself
if thrown != nil {
didLogError = true
text := thrown.Error()
log.AddMsg(logger.Msg{
PluginName: name,
Kind: logger.Error,
Data: logger.MsgData{
Text: text,
Location: tracker.MsgLocationOrNil(importPathRange),
UserDetail: thrown,
},
})
}
return didLogError
}
func RunOnResolvePlugins(
plugins []config.Plugin,
res *resolver.Resolver,
log logger.Log,
fs fs.FS,
fsCache *cache.FSCache,
importSource *logger.Source,
importPathRange logger.Range,
importer logger.Path,
path string,
importAttributes logger.ImportAttributes,
kind ast.ImportKind,
absResolveDir string,
pluginData interface{},
) (*resolver.ResolveResult, bool, resolver.DebugMeta) {
resolverArgs := config.OnResolveArgs{
Path: path,
ResolveDir: absResolveDir,
Kind: kind,
PluginData: pluginData,
Importer: importer,
With: importAttributes,
}
applyPath := logger.Path{
Text: path,
Namespace: importer.Namespace,
}
tracker := logger.MakeLineColumnTracker(importSource)
// Apply resolver plugins in order until one succeeds
for _, plugin := range plugins {
for _, onResolve := range plugin.OnResolve {
if !config.PluginAppliesToPath(applyPath, onResolve.Filter, onResolve.Namespace) {
continue
}
result := onResolve.Callback(resolverArgs)
pluginName := result.PluginName
if pluginName == "" {
pluginName = plugin.Name
}
didLogError := logPluginMessages(fs, log, pluginName, result.Msgs, result.ThrownError, importSource, importPathRange)
// Plugins can also provide additional file system paths to watch
for _, file := range result.AbsWatchFiles {
fsCache.ReadFile(fs, file)
}
for _, dir := range result.AbsWatchDirs {
if entries, err, _ := fs.ReadDirectory(dir); err == nil {
entries.SortedKeys()
}
}
// Stop now if there was an error