-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
bundler.go
2514 lines (2253 loc) · 84.2 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
import (
"bytes"
"encoding/base32"
"encoding/base64"
"fmt"
"math/rand"
"net/http"
"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/js_printer"
"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
}
type parseArgs struct {
fs fs.FS
log logger.Log
res resolver.Resolver
caches *cache.CacheSet
prettyPath string
importSource *logger.Source
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
file scannerFile
tlaCheck tlaCheck
ok bool
}
type tlaCheck struct {
parent ast.Index32
depth uint32
importRecordIndex uint32
}
func parseFile(args parseArgs) {
source := logger.Source{
Index: args.sourceIndex,
KeyPath: args.keyPath,
PrettyPath: args.prettyPath,
IdentifierName: js_ast.GenerateNonUniqueNameFromPath(args.keyPath.Text),
}
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.res,
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 = loaderFromFileExtension(args.options.ExtensionToLoader, base+ext)
}
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.AddWithNotes(logger.Error, 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:
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:
ast := args.caches.CSSCache.Parse(args.log, source, css_parser.Options{
MinifySyntax: args.options.MinifySyntax,
MinifyWhitespace: args.options.MinifyWhitespace,
UnsupportedCSSFeatures: args.options.UnsupportedCSSFeatures,
OriginalTargetEnv: args.options.OriginalTargetEnv,
})
result.file.inputFile.Repr = &graph.CSSRepr{AST: ast}
result.ok = true
case config.LoaderJSON:
expr, ok := args.caches.JSONCache.Parse(args.log, source, js_parser.JSONOptions{})
ast := js_parser.LazyExportAST(args.log, source, js_parser.OptionsFromConfig(&args.options), expr, "")
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:
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)
encoded := base64.StdEncoding.EncodeToString([]byte(source.Contents))
url := fmt.Sprintf("data:%s;base64,%s", mimeType, encoded)
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)}}
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.UniqueKeyForFileLoader = 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.Add(logger.Error, &tracker, args.importPathRange, message)
}
// This must come 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,
}
}
}
args.inject <- config.InjectedFile{
Source: source,
Exports: exports,
}
}
// Stop now if parsing failed
if !result.ok {
args.results <- result
return
}
// 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 args.options.Mode == config.ModeBundle && !args.skipResolve {
// Clone the import records because they will be mutated later
recordsPtr := result.file.inputFile.Repr.ImportRecords()
records := append([]ast.ImportRecord{}, *recordsPtr...)
*recordsPtr = records
result.resolveResults = make([]*resolver.ResolveResult, len(records))
if len(records) > 0 {
resolverCache := make(map[ast.ImportKind]map[string]*resolver.ResolveResult)
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
}
// 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
cache, ok := resolverCache[record.Kind]
if !ok {
cache = make(map[string]*resolver.ResolveResult)
resolverCache[record.Kind] = cache
}
if resolveResult, ok := cache[record.Path.Text]; ok {
result.resolveResults[importRecordIndex] = resolveResult
continue
}
// 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,
record.Kind,
absResolveDir,
pluginData,
)
cache[record.Path.Text] = resolveResult
// 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.IsExternal {
// Allow path substitution as long as the result is external
result.resolveResults[importRecordIndex] = resolveResult
} else if !record.Flags.Has(ast.HandlesImportErrors) {
args.log.Add(logger.Warning, &tracker, record.Range,
fmt.Sprintf("%q should be marked as external for use with \"require.resolve\"", record.Path.Text))
}
continue
}
if 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 !didLogError && !record.Flags.Has(ast.HandlesImportErrors) {
text, suggestion, notes := ResolveFailureErrorTextSuggestionNotes(args.res, record.Path.Text, record.Kind,
pluginName, args.fs, absResolveDir, args.options.Platform, source.PrettyPath)
debug.LogErrorMsg(args.log, &source, record.Range, text, suggestion, notes)
} else if args.log.Level <= logger.LevelDebug && !didLogError && record.Flags.Has(ast.HandlesImportErrors) {
args.log.AddWithNotes(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] = 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 != "" {
if path, contents := extractSourceMapFromComment(args.log, args.fs, &args.caches.FSCache,
args.res, &source, sourceMapComment, absResolveDir); contents != nil {
result.file.inputFile.InputSourceMap = js_parser.ParseSourceMap(args.log, logger.Source{
KeyPath: path,
PrettyPath: args.res.PrettyPath(path),
Contents: *contents,
})
}
}
}
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,
) (text string, suggestion string, notes []logger.MsgData) {
text = fmt.Sprintf("Could not resolve %q", path)
hint := ""
if resolver.IsPackagePath(path) {
hint = fmt.Sprintf("You can mark the path %q as external to exclude it from the bundle, which will remove this error.", 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, res.PrettyPath(query.PathPair.Primary), path)
suggestion = string(js_printer.QuoteForJSON("./"+path, false))
}
}
}
if platform != config.PlatformNode {
if _, ok := resolver.BuiltInNodeModules[path]; ok {
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 != "" {
notes = append(notes, logger.MsgData{Text: hint})
}
return
}
func joinWithPublicPath(publicPath string, relPath string) string {
if strings.HasPrefix(relPath, "./") {
relPath = relPath[2:]
// Strip any amount of further no-op slashes (i.e. ".///././/x/y" => "x/y")
for {
if strings.HasPrefix(relPath, "/") {
relPath = relPath[1:]
} else if strings.HasPrefix(relPath, "./") {
relPath = relPath[2:]
} else {
break
}
}
}
// Use a relative path if there is no public path
if publicPath == "" {
publicPath = "."
}
// Join with a slash
slash := "/"
if strings.HasSuffix(publicPath, "/") {
slash = ""
}
return fmt.Sprintf("%s%s%s", publicPath, slash, relPath)
}
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,
res resolver.Resolver,
source *logger.Source,
comment logger.Span,
absResolveDir string,
) (logger.Path, *string) {
tracker := logger.MakeLineColumnTracker(source)
// Support data URLs
if parsed, ok := resolver.ParseDataURL(comment.Text); ok {
if contents, err := parsed.DecodeData(); err == nil {
return logger.Path{Text: source.PrettyPath, IgnoredSuffix: "#sourceMappingURL"}, &contents
} else {
log.Add(logger.Warning, &tracker, comment.Range, fmt.Sprintf("Unsupported source map comment: %s", err.Error()))
return logger.Path{}, nil
}
}
// Relative path in a file with an absolute path
if absResolveDir != "" {
absPath := fs.Join(absResolveDir, comment.Text)
path := logger.Path{Text: absPath, Namespace: "file"}
contents, err, originalError := fsCache.ReadFile(fs, absPath)
if log.Level <= logger.LevelDebug && originalError != nil {
log.Add(logger.Debug, &tracker, comment.Range, fmt.Sprintf("Failed to read file %q: %s", res.PrettyPath(path), originalError.Error()))
}
if err != nil {
if err == syscall.ENOENT {
// Don't report a warning because this is likely unactionable
return logger.Path{}, nil
}
log.Add(logger.Warning, &tracker, comment.Range, fmt.Sprintf("Cannot read file %q: %s", res.PrettyPath(path), err.Error()))
return logger.Path{}, nil
}
return path, &contents
}
// Anything else is unsupported
return logger.Path{}, nil
}
func sanitizeLocation(res resolver.Resolver, loc *logger.MsgLocation) {
if loc != nil {
if loc.Namespace == "" {
loc.Namespace = "file"
}
if loc.File != "" {
loc.File = res.PrettyPath(logger.Path{Text: loc.File, Namespace: loc.Namespace})
}
}
}
func logPluginMessages(
res resolver.Resolver,
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(res, note.Location)
}
if msg.Data.Location == nil {
msg.Data.Location = tracker.MsgLocationOrNil(importPathRange)
} else {
sanitizeLocation(res, 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,
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,
}
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(res, 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
if didLogError {
return nil, true, resolver.DebugMeta{}
}
// The "file" namespace is the default for non-external paths, but not
// for external paths. External paths must explicitly specify the "file"
// namespace.
nsFromPlugin := result.Path.Namespace
if result.Path.Namespace == "" && !result.External {
result.Path.Namespace = "file"
}
// Otherwise, continue on to the next resolver if this loader didn't succeed
if result.Path.Text == "" {
if result.External {
result.Path = logger.Path{Text: path}
} else {
continue
}
}
// Paths in the file namespace must be absolute paths
if result.Path.Namespace == "file" && !fs.IsAbs(result.Path.Text) {
if nsFromPlugin == "file" {
log.Add(logger.Error, &tracker, importPathRange,
fmt.Sprintf("Plugin %q returned a path in the \"file\" namespace that is not an absolute path: %s", pluginName, result.Path.Text))
} else {
log.Add(logger.Error, &tracker, importPathRange,
fmt.Sprintf("Plugin %q returned a non-absolute path: %s (set a namespace if this is not a file path)", pluginName, result.Path.Text))
}
return nil, true, resolver.DebugMeta{}
}
var sideEffectsData *resolver.SideEffectsData
if result.IsSideEffectFree {
sideEffectsData = &resolver.SideEffectsData{
PluginName: pluginName,
}
}
return &resolver.ResolveResult{
PathPair: resolver.PathPair{Primary: result.Path},
IsExternal: result.External,
PluginName: pluginName,
PluginData: result.PluginData,
PrimarySideEffectsData: sideEffectsData,
}, false, resolver.DebugMeta{}
}
}
// Resolve relative to the resolve directory by default. All paths in the
// "file" namespace automatically have a resolve directory. Loader plugins
// can also configure a custom resolve directory for files in other namespaces.
result, debug := res.Resolve(absResolveDir, path, kind)
// Warn when the case used for importing differs from the actual file name
if result != nil && result.DifferentCase != nil && !helpers.IsInsideNodeModules(absResolveDir) {
diffCase := *result.DifferentCase
log.Add(logger.Warning, &tracker, importPathRange, fmt.Sprintf(
"Use %q instead of %q to avoid issues with case-sensitive file systems",
res.PrettyPath(logger.Path{Text: fs.Join(diffCase.Dir, diffCase.Actual), Namespace: "file"}),
res.PrettyPath(logger.Path{Text: fs.Join(diffCase.Dir, diffCase.Query), Namespace: "file"}),
))
}
return result, false, debug
}
type loaderPluginResult struct {
pluginData interface{}
absResolveDir string
pluginName string
loader config.Loader
}
func runOnLoadPlugins(
plugins []config.Plugin,
res resolver.Resolver,
fs fs.FS,
fsCache *cache.FSCache,
log logger.Log,
source *logger.Source,
importSource *logger.Source,
importPathRange logger.Range,
pluginData interface{},
isWatchMode bool,
) (loaderPluginResult, bool) {
loaderArgs := config.OnLoadArgs{
Path: source.KeyPath,
PluginData: pluginData,
}
tracker := logger.MakeLineColumnTracker(importSource)
// Apply loader plugins in order until one succeeds
for _, plugin := range plugins {
for _, onLoad := range plugin.OnLoad {
if !config.PluginAppliesToPath(source.KeyPath, onLoad.Filter, onLoad.Namespace) {
continue
}
result := onLoad.Callback(loaderArgs)
pluginName := result.PluginName
if pluginName == "" {
pluginName = plugin.Name
}
didLogError := logPluginMessages(res, 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
if didLogError {
if isWatchMode && source.KeyPath.Namespace == "file" {
fsCache.ReadFile(fs, source.KeyPath.Text) // Read the file for watch mode tracking
}
return loaderPluginResult{}, false
}
// Otherwise, continue on to the next loader if this loader didn't succeed
if result.Contents == nil {
continue
}
source.Contents = *result.Contents
loader := result.Loader
if loader == config.LoaderNone {
loader = config.LoaderJS
}
if result.AbsResolveDir == "" && source.KeyPath.Namespace == "file" {
result.AbsResolveDir = fs.Dir(source.KeyPath.Text)
}
if isWatchMode && source.KeyPath.Namespace == "file" {
fsCache.ReadFile(fs, source.KeyPath.Text) // Read the file for watch mode tracking
}
return loaderPluginResult{
loader: loader,
absResolveDir: result.AbsResolveDir,
pluginName: pluginName,
pluginData: result.PluginData,
}, true
}
}
// Force disabled modules to be empty
if source.KeyPath.IsDisabled() {
return loaderPluginResult{loader: config.LoaderJS}, true
}
// Read normal modules from disk
if source.KeyPath.Namespace == "file" {
if contents, err, originalError := fsCache.ReadFile(fs, source.KeyPath.Text); err == nil {
source.Contents = contents
return loaderPluginResult{
loader: config.LoaderDefault,
absResolveDir: fs.Dir(source.KeyPath.Text),
}, true
} else {
if log.Level <= logger.LevelDebug && originalError != nil {
log.Add(logger.Debug, nil, logger.Range{}, fmt.Sprintf("Failed to read file %q: %s", source.KeyPath.Text, originalError.Error()))
}
if err == syscall.ENOENT {
log.Add(logger.Error, &tracker, importPathRange,
fmt.Sprintf("Could not read from file: %s", source.KeyPath.Text))
return loaderPluginResult{}, false
} else {
log.Add(logger.Error, &tracker, importPathRange,
fmt.Sprintf("Cannot read file %q: %s", res.PrettyPath(source.KeyPath), err.Error()))
return loaderPluginResult{}, false
}
}
}
// Native support for data URLs. This is supported natively by node:
// https://nodejs.org/docs/latest/api/esm.html#esm_data_imports
if source.KeyPath.Namespace == "dataurl" {
if parsed, ok := resolver.ParseDataURL(source.KeyPath.Text); ok {
if mimeType := parsed.DecodeMIMEType(); mimeType != resolver.MIMETypeUnsupported {
if contents, err := parsed.DecodeData(); err != nil {
log.Add(logger.Error, &tracker, importPathRange,
fmt.Sprintf("Could not load data URL: %s", err.Error()))
return loaderPluginResult{loader: config.LoaderNone}, true
} else {
source.Contents = contents
switch mimeType {
case resolver.MIMETypeTextCSS:
return loaderPluginResult{loader: config.LoaderCSS}, true
case resolver.MIMETypeTextJavaScript:
return loaderPluginResult{loader: config.LoaderJS}, true
case resolver.MIMETypeApplicationJSON:
return loaderPluginResult{loader: config.LoaderJSON}, true
}
}
}
}
}
// Otherwise, fail to load the path
return loaderPluginResult{loader: config.LoaderNone}, true
}
func loaderFromFileExtension(extensionToLoader map[string]config.Loader, base string) config.Loader {
// Pick the loader with the longest matching extension. So if there's an
// extension for ".css" and for ".module.css", we want to match the one for
// ".module.css" before the one for ".css".
for {
i := strings.IndexByte(base, '.')
if i == -1 {
break
}
if loader, ok := extensionToLoader[base[i:]]; ok {
return loader
}
base = base[i+1:]
}
return config.LoaderNone
}
func hashForFileName(hashBytes []byte) string {
return base32.StdEncoding.EncodeToString(hashBytes)[:8]
}
type scanner struct {
log logger.Log
fs fs.FS
res resolver.Resolver
caches *cache.CacheSet
timer *helpers.Timer
uniqueKeyPrefix string
// These are not guarded by a mutex because it's only ever modified by a single
// thread. Note that not all results in the "results" array are necessarily
// valid. Make sure to check the "ok" flag before using them.
results []parseResult
visited map[logger.Path]visitedFile
resultChannel chan parseResult
options config.Options
// Also not guarded by a mutex for the same reason
remaining int
}
type visitedFile struct {
importSource *logger.Source
resolveResult resolver.ResolveResult
importPathRange logger.Range