-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
api_impl.go
2280 lines (2037 loc) · 70.7 KB
/
api_impl.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 api
import (
"fmt"
"io/ioutil"
"math"
"math/rand"
"os"
"path"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/evanw/esbuild/internal/api_helpers"
"github.com/evanw/esbuild/internal/ast"
"github.com/evanw/esbuild/internal/bundler"
"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/graph"
"github.com/evanw/esbuild/internal/helpers"
"github.com/evanw/esbuild/internal/js_ast"
"github.com/evanw/esbuild/internal/js_parser"
"github.com/evanw/esbuild/internal/linker"
"github.com/evanw/esbuild/internal/logger"
"github.com/evanw/esbuild/internal/resolver"
)
func validatePathTemplate(template string) []config.PathTemplate {
if template == "" {
return nil
}
template = "./" + strings.ReplaceAll(template, "\\", "/")
parts := make([]config.PathTemplate, 0, 4)
search := 0
// Split by placeholders
for search < len(template) {
// Jump to the next "["
if found := strings.IndexByte(template[search:], '['); found == -1 {
break
} else {
search += found
}
head, tail := template[:search], template[search:]
placeholder := config.NoPlaceholder
// Check for a placeholder
switch {
case strings.HasPrefix(tail, "[dir]"):
placeholder = config.DirPlaceholder
search += len("[dir]")
case strings.HasPrefix(tail, "[name]"):
placeholder = config.NamePlaceholder
search += len("[name]")
case strings.HasPrefix(tail, "[hash]"):
placeholder = config.HashPlaceholder
search += len("[hash]")
case strings.HasPrefix(tail, "[ext]"):
placeholder = config.ExtPlaceholder
search += len("[ext]")
default:
// Skip past the "[" so we don't find it again
search++
continue
}
// Add a part for everything up to and including this placeholder
parts = append(parts, config.PathTemplate{
Data: head,
Placeholder: placeholder,
})
// Reset the search after this placeholder
template = template[search:]
search = 0
}
// Append any remaining data as a part without a placeholder
if search < len(template) {
parts = append(parts, config.PathTemplate{
Data: template,
Placeholder: config.NoPlaceholder,
})
}
return parts
}
func validatePlatform(value Platform) config.Platform {
switch value {
case PlatformDefault, PlatformBrowser:
return config.PlatformBrowser
case PlatformNode:
return config.PlatformNode
case PlatformNeutral:
return config.PlatformNeutral
default:
panic("Invalid platform")
}
}
func validateFormat(value Format) config.Format {
switch value {
case FormatDefault:
return config.FormatPreserve
case FormatIIFE:
return config.FormatIIFE
case FormatCommonJS:
return config.FormatCommonJS
case FormatESModule:
return config.FormatESModule
default:
panic("Invalid format")
}
}
func validateSourceMap(value SourceMap) config.SourceMap {
switch value {
case SourceMapNone:
return config.SourceMapNone
case SourceMapLinked:
return config.SourceMapLinkedWithComment
case SourceMapInline:
return config.SourceMapInline
case SourceMapExternal:
return config.SourceMapExternalWithoutComment
case SourceMapInlineAndExternal:
return config.SourceMapInlineAndExternal
default:
panic("Invalid source map")
}
}
func validateLegalComments(value LegalComments, bundle bool) config.LegalComments {
switch value {
case LegalCommentsDefault:
if bundle {
return config.LegalCommentsEndOfFile
} else {
return config.LegalCommentsInline
}
case LegalCommentsNone:
return config.LegalCommentsNone
case LegalCommentsInline:
return config.LegalCommentsInline
case LegalCommentsEndOfFile:
return config.LegalCommentsEndOfFile
case LegalCommentsLinked:
return config.LegalCommentsLinkedWithComment
case LegalCommentsExternal:
return config.LegalCommentsExternalWithoutComment
default:
panic("Invalid source map")
}
}
func validateColor(value StderrColor) logger.UseColor {
switch value {
case ColorIfTerminal:
return logger.ColorIfTerminal
case ColorNever:
return logger.ColorNever
case ColorAlways:
return logger.ColorAlways
default:
panic("Invalid color")
}
}
func validateLogLevel(value LogLevel) logger.LogLevel {
switch value {
case LogLevelVerbose:
return logger.LevelVerbose
case LogLevelDebug:
return logger.LevelDebug
case LogLevelInfo:
return logger.LevelInfo
case LogLevelWarning:
return logger.LevelWarning
case LogLevelError:
return logger.LevelError
case LogLevelSilent:
return logger.LevelSilent
default:
panic("Invalid log level")
}
}
func validateASCIIOnly(value Charset) bool {
switch value {
case CharsetDefault, CharsetASCII:
return true
case CharsetUTF8:
return false
default:
panic("Invalid charset")
}
}
func validateTreeShaking(value TreeShaking, bundle bool, format Format) bool {
switch value {
case TreeShakingDefault:
// If we're in an IIFE then there's no way to concatenate additional code
// to the end of our output so we assume tree shaking is safe. And when
// bundling we assume that tree shaking is safe because if you want to add
// code to the bundle, you should be doing that by including it in the
// bundle instead of concatenating it afterward, so we also assume tree
// shaking is safe then. Otherwise we assume tree shaking is not safe.
return bundle || format == FormatIIFE
case TreeShakingFalse:
return false
case TreeShakingTrue:
return true
default:
panic("Invalid tree shaking")
}
}
func validateLoader(value Loader) config.Loader {
switch value {
case LoaderBase64:
return config.LoaderBase64
case LoaderBinary:
return config.LoaderBinary
case LoaderCopy:
return config.LoaderCopy
case LoaderCSS:
return config.LoaderCSS
case LoaderDataURL:
return config.LoaderDataURL
case LoaderDefault:
return config.LoaderDefault
case LoaderEmpty:
return config.LoaderEmpty
case LoaderFile:
return config.LoaderFile
case LoaderJS:
return config.LoaderJS
case LoaderJSON:
return config.LoaderJSON
case LoaderJSX:
return config.LoaderJSX
case LoaderNone:
return config.LoaderNone
case LoaderText:
return config.LoaderText
case LoaderTS:
return config.LoaderTS
case LoaderTSX:
return config.LoaderTSX
default:
panic("Invalid loader")
}
}
func validateEngine(value EngineName) compat.Engine {
switch value {
case EngineChrome:
return compat.Chrome
case EngineEdge:
return compat.Edge
case EngineFirefox:
return compat.Firefox
case EngineIOS:
return compat.IOS
case EngineNode:
return compat.Node
case EngineSafari:
return compat.Safari
default:
panic("Invalid loader")
}
}
var versionRegex = regexp.MustCompile(`^([0-9]+)(?:\.([0-9]+))?(?:\.([0-9]+))?$`)
func validateFeatures(log logger.Log, target Target, engines []Engine) (config.TargetFromAPI, compat.JSFeature, compat.CSSFeature, string) {
if target == DefaultTarget && len(engines) == 0 {
return config.TargetWasUnconfigured, 0, 0, ""
}
constraints := make(map[compat.Engine][]int)
targets := make([]string, 0, 1+len(engines))
targetFromAPI := config.TargetWasConfigured
switch target {
case ES5:
constraints[compat.ES] = []int{5}
case ES2015:
constraints[compat.ES] = []int{2015}
case ES2016:
constraints[compat.ES] = []int{2016}
case ES2017:
constraints[compat.ES] = []int{2017}
case ES2018:
constraints[compat.ES] = []int{2018}
case ES2019:
constraints[compat.ES] = []int{2019}
case ES2020:
constraints[compat.ES] = []int{2020}
case ES2021:
constraints[compat.ES] = []int{2021}
case ES2022:
constraints[compat.ES] = []int{2022}
targetFromAPI = config.TargetWasConfiguredAndAtLeastES2022
case ESNext:
targetFromAPI = config.TargetWasConfiguredAndAtLeastES2022
case DefaultTarget:
default:
panic("Invalid target")
}
for _, engine := range engines {
if match := versionRegex.FindStringSubmatch(engine.Version); match != nil {
if major, err := strconv.Atoi(match[1]); err == nil {
version := []int{major}
if minor, err := strconv.Atoi(match[2]); err == nil {
version = append(version, minor)
}
if patch, err := strconv.Atoi(match[3]); err == nil {
version = append(version, patch)
}
constraints[convertEngineName(engine.Name)] = version
continue
}
}
log.AddError(nil, logger.Range{}, fmt.Sprintf("Invalid version: %q", engine.Version))
}
for engine, version := range constraints {
var text string
switch len(version) {
case 1:
text = fmt.Sprintf("%s%d", engine.String(), version[0])
case 2:
text = fmt.Sprintf("%s%d.%d", engine.String(), version[0], version[1])
case 3:
text = fmt.Sprintf("%s%d.%d.%d", engine.String(), version[0], version[1], version[2])
}
targets = append(targets, text)
}
sort.Strings(targets)
targetEnv := helpers.StringArrayToQuotedCommaSeparatedString(targets)
return targetFromAPI, compat.UnsupportedJSFeatures(constraints), compat.UnsupportedCSSFeatures(constraints), targetEnv
}
func validateSupported(log logger.Log, supported map[string]bool) (
jsFeature compat.JSFeature,
jsMask compat.JSFeature,
cssFeature compat.CSSFeature,
cssMask compat.CSSFeature,
) {
for k, v := range supported {
if js, ok := compat.StringToJSFeature[k]; ok {
jsMask |= js
if !v {
jsFeature |= js
}
} else if css, ok := compat.StringToCSSFeature[k]; ok {
cssMask |= css
if !v {
cssFeature |= css
}
} else {
log.AddError(nil, logger.Range{}, fmt.Sprintf("%q is not a valid feature name for the \"supported\" setting", k))
}
}
return
}
func validateGlobalName(log logger.Log, text string) []string {
if text != "" {
source := logger.Source{
KeyPath: logger.Path{Text: "(global path)"},
PrettyPath: "(global name)",
Contents: text,
}
if result, ok := js_parser.ParseGlobalName(log, source); ok {
return result
}
}
return nil
}
func validateRegex(log logger.Log, what string, value string) *regexp.Regexp {
if value == "" {
return nil
}
regex, err := regexp.Compile(value)
if err != nil {
log.AddError(nil, logger.Range{},
fmt.Sprintf("The %q setting is not a valid Go regular expression: %s", what, value))
return nil
}
return regex
}
func validateExternals(log logger.Log, fs fs.FS, paths []string) config.ExternalSettings {
result := config.ExternalSettings{
PreResolve: config.ExternalMatchers{Exact: make(map[string]bool)},
PostResolve: config.ExternalMatchers{Exact: make(map[string]bool)},
}
for _, path := range paths {
if index := strings.IndexByte(path, '*'); index != -1 {
// Wildcard behavior
if strings.ContainsRune(path[index+1:], '*') {
log.AddError(nil, logger.Range{}, fmt.Sprintf("External path %q cannot have more than one \"*\" wildcard", path))
} else {
result.PreResolve.Patterns = append(result.PreResolve.Patterns, config.WildcardPattern{Prefix: path[:index], Suffix: path[index+1:]})
if !resolver.IsPackagePath(path) {
if absPath := validatePath(log, fs, path, "external path"); absPath != "" {
if absIndex := strings.IndexByte(absPath, '*'); absIndex != -1 && !strings.ContainsRune(absPath[absIndex+1:], '*') {
result.PostResolve.Patterns = append(result.PostResolve.Patterns, config.WildcardPattern{Prefix: absPath[:absIndex], Suffix: absPath[absIndex+1:]})
}
}
}
}
} else {
// Non-wildcard behavior
result.PreResolve.Exact[path] = true
if resolver.IsPackagePath(path) {
result.PreResolve.Patterns = append(result.PreResolve.Patterns, config.WildcardPattern{Prefix: path + "/"})
} else if absPath := validatePath(log, fs, path, "external path"); absPath != "" {
result.PostResolve.Exact[absPath] = true
}
}
}
return result
}
func esmParsePackageName(packageSpecifier string) (packageName string, packageSubpath string, ok bool) {
if packageSpecifier == "" {
return
}
slash := strings.IndexByte(packageSpecifier, '/')
if !strings.HasPrefix(packageSpecifier, "@") {
if slash == -1 {
slash = len(packageSpecifier)
}
packageName = packageSpecifier[:slash]
} else {
if slash == -1 {
return
}
slash2 := strings.IndexByte(packageSpecifier[slash+1:], '/')
if slash2 == -1 {
slash2 = len(packageSpecifier[slash+1:])
}
packageName = packageSpecifier[:slash+1+slash2]
}
if strings.HasPrefix(packageName, ".") || strings.ContainsAny(packageName, "\\%") {
return
}
packageSubpath = "." + packageSpecifier[len(packageName):]
ok = true
return
}
func validateAlias(log logger.Log, fs fs.FS, alias map[string]string) map[string]string {
valid := make(map[string]string, len(alias))
for old, new := range alias {
if new == "" {
log.AddError(nil, logger.Range{}, fmt.Sprintf("Invalid alias substitution: %q", new))
continue
}
// Valid alias names:
// "foo"
// "foo/bar"
// "@foo"
// "@foo/bar"
// "@foo/bar/baz"
//
// Invalid alias names:
// "./foo"
// "../foo"
// "/foo"
// "C:\\foo"
// ".foo"
// "foo/"
// "@foo/"
// "foo/../bar"
//
if !strings.HasPrefix(old, ".") && !strings.HasPrefix(old, "/") && !fs.IsAbs(old) && path.Clean(strings.ReplaceAll(old, "\\", "/")) == old {
valid[old] = new
continue
}
log.AddError(nil, logger.Range{}, fmt.Sprintf("Invalid alias name: %q", old))
}
return valid
}
func isValidExtension(ext string) bool {
return len(ext) >= 2 && ext[0] == '.' && ext[len(ext)-1] != '.'
}
func validateResolveExtensions(log logger.Log, order []string) []string {
if order == nil {
return []string{".tsx", ".ts", ".jsx", ".js", ".css", ".json"}
}
for _, ext := range order {
if !isValidExtension(ext) {
log.AddError(nil, logger.Range{}, fmt.Sprintf("Invalid file extension: %q", ext))
}
}
return order
}
func validateLoaders(log logger.Log, loaders map[string]Loader) map[string]config.Loader {
result := bundler.DefaultExtensionToLoaderMap()
if loaders != nil {
for ext, loader := range loaders {
if !isValidExtension(ext) {
log.AddError(nil, logger.Range{}, fmt.Sprintf("Invalid file extension: %q", ext))
}
result[ext] = validateLoader(loader)
}
}
return result
}
func validateJSXExpr(log logger.Log, text string, name string) config.DefineExpr {
if text != "" {
if expr, _ := js_parser.ParseDefineExprOrJSON(text); len(expr.Parts) > 0 || (name == "fragment" && expr.Constant != nil) {
return expr
}
log.AddError(nil, logger.Range{}, fmt.Sprintf("Invalid JSX %s: %q", name, text))
}
return config.DefineExpr{}
}
func validateDefines(
log logger.Log,
defines map[string]string,
pureFns []string,
platform config.Platform,
isBuildAPI bool,
minify bool,
drop Drop,
) (*config.ProcessedDefines, []config.InjectedDefine) {
rawDefines := make(map[string]config.DefineData)
var valueToInject map[string]config.InjectedDefine
var definesToInject []string
for key, value := range defines {
// The key must be a dot-separated identifier list
for _, part := range strings.Split(key, ".") {
if !js_ast.IsIdentifier(part) {
if part == key {
log.AddError(nil, logger.Range{}, fmt.Sprintf("The define key %q must be a valid identifier", key))
} else {
log.AddError(nil, logger.Range{}, fmt.Sprintf("The define key %q contains invalid identifier %q", key, part))
}
continue
}
}
// Parse the value
defineExpr, injectExpr := js_parser.ParseDefineExprOrJSON(value)
// Define simple expressions
if defineExpr.Constant != nil || len(defineExpr.Parts) > 0 {
rawDefines[key] = config.DefineData{DefineExpr: &defineExpr}
continue
}
// Inject complex expressions
if injectExpr != nil {
definesToInject = append(definesToInject, key)
if valueToInject == nil {
valueToInject = make(map[string]config.InjectedDefine)
}
valueToInject[key] = config.InjectedDefine{
Source: logger.Source{Contents: value},
Data: injectExpr,
Name: key,
}
continue
}
// Anything else is unsupported
log.AddError(nil, logger.Range{}, fmt.Sprintf("Invalid define value (must be an entity name or valid JSON syntax): %s", value))
}
// Sort injected defines for determinism, since the imports will be injected
// into every file in the order that we return them from this function
var injectedDefines []config.InjectedDefine
if len(definesToInject) > 0 {
injectedDefines = make([]config.InjectedDefine, len(definesToInject))
sort.Strings(definesToInject)
for i, key := range definesToInject {
injectedDefines[i] = valueToInject[key]
rawDefines[key] = config.DefineData{DefineExpr: &config.DefineExpr{InjectedDefineIndex: ast.MakeIndex32(uint32(i))}}
}
}
// If we're bundling for the browser, add a special-cased define for
// "process.env.NODE_ENV" that is "development" when not minifying and
// "production" when minifying. This is a convention from the React world
// that must be handled to avoid all React code crashing instantly. This
// is only done if it's not already defined so that you can override it if
// necessary.
if isBuildAPI && platform == config.PlatformBrowser {
if _, process := rawDefines["process"]; !process {
if _, processEnv := rawDefines["process.env"]; !processEnv {
if _, processEnvNodeEnv := rawDefines["process.env.NODE_ENV"]; !processEnvNodeEnv {
var value []uint16
if minify {
value = helpers.StringToUTF16("production")
} else {
value = helpers.StringToUTF16("development")
}
rawDefines["process.env.NODE_ENV"] = config.DefineData{DefineExpr: &config.DefineExpr{Constant: &js_ast.EString{Value: value}}}
}
}
}
}
// If we're dropping all console API calls, replace each one with undefined
if (drop & DropConsole) != 0 {
define := rawDefines["console"]
define.MethodCallsMustBeReplacedWithUndefined = true
rawDefines["console"] = define
}
for _, key := range pureFns {
// The key must be a dot-separated identifier list
for _, part := range strings.Split(key, ".") {
if !js_ast.IsIdentifier(part) {
log.AddError(nil, logger.Range{}, fmt.Sprintf("Invalid pure function: %q", key))
continue
}
}
// Merge with any previously-specified defines
define := rawDefines[key]
define.CallCanBeUnwrappedIfUnused = true
rawDefines[key] = define
}
// Processing defines is expensive. Process them once here so the same object
// can be shared between all parsers we create using these arguments.
processed := config.ProcessDefines(rawDefines)
return &processed, injectedDefines
}
func validateLogOverrides(input map[string]LogLevel) (output map[logger.MsgID]logger.LogLevel) {
output = make(map[uint8]logger.LogLevel)
for k, v := range input {
logger.StringToMsgIDs(k, validateLogLevel(v), output)
}
return
}
func validatePath(log logger.Log, fs fs.FS, relPath string, pathKind string) string {
if relPath == "" {
return ""
}
absPath, ok := fs.Abs(relPath)
if !ok {
log.AddError(nil, logger.Range{}, fmt.Sprintf("Invalid %s: %s", pathKind, relPath))
}
return absPath
}
func validateOutputExtensions(log logger.Log, outExtensions map[string]string) (js string, css string) {
for key, value := range outExtensions {
if !isValidExtension(value) {
log.AddError(nil, logger.Range{}, fmt.Sprintf("Invalid output extension: %q", value))
}
switch key {
case ".js":
js = value
case ".css":
css = value
default:
log.AddError(nil, logger.Range{}, fmt.Sprintf("Invalid output extension: %q (valid: .css, .js)", key))
}
}
return
}
func validateBannerOrFooter(log logger.Log, name string, values map[string]string) (js string, css string) {
for key, value := range values {
switch key {
case "js":
js = value
case "css":
css = value
default:
log.AddError(nil, logger.Range{}, fmt.Sprintf("Invalid %s file type: %q (valid: css, js)", name, key))
}
}
return
}
func convertLocationToPublic(loc *logger.MsgLocation) *Location {
if loc != nil {
return &Location{
File: loc.File,
Namespace: loc.Namespace,
Line: loc.Line,
Column: loc.Column,
Length: loc.Length,
LineText: loc.LineText,
Suggestion: loc.Suggestion,
}
}
return nil
}
func convertMessagesToPublic(kind logger.MsgKind, msgs []logger.Msg) []Message {
var filtered []Message
for _, msg := range msgs {
if msg.Kind == kind {
var notes []Note
for _, note := range msg.Notes {
notes = append(notes, Note{
Text: note.Text,
Location: convertLocationToPublic(note.Location),
})
}
filtered = append(filtered, Message{
ID: logger.MsgIDToString(msg.ID),
PluginName: msg.PluginName,
Text: msg.Data.Text,
Location: convertLocationToPublic(msg.Data.Location),
Notes: notes,
Detail: msg.Data.UserDetail,
})
}
}
return filtered
}
func convertLocationToInternal(loc *Location) *logger.MsgLocation {
if loc != nil {
namespace := loc.Namespace
if namespace == "" {
namespace = "file"
}
return &logger.MsgLocation{
File: loc.File,
Namespace: namespace,
Line: loc.Line,
Column: loc.Column,
Length: loc.Length,
LineText: loc.LineText,
Suggestion: loc.Suggestion,
}
}
return nil
}
func convertMessagesToInternal(msgs []logger.Msg, kind logger.MsgKind, messages []Message) []logger.Msg {
for _, message := range messages {
var notes []logger.MsgData
for _, note := range message.Notes {
notes = append(notes, logger.MsgData{
Text: note.Text,
Location: convertLocationToInternal(note.Location),
})
}
msgs = append(msgs, logger.Msg{
ID: logger.StringToMaximumMsgID(message.ID),
PluginName: message.PluginName,
Kind: kind,
Data: logger.MsgData{
Text: message.Text,
Location: convertLocationToInternal(message.Location),
UserDetail: message.Detail,
},
Notes: notes,
})
}
return msgs
}
func cloneMangleCache(log logger.Log, mangleCache map[string]interface{}) map[string]interface{} {
if mangleCache == nil {
return nil
}
clone := make(map[string]interface{}, len(mangleCache))
for k, v := range mangleCache {
if v == "__proto__" {
// This could cause problems for our binary serialization protocol. It's
// also unnecessary because we already avoid mangling this property name.
log.AddError(nil, logger.Range{},
fmt.Sprintf("Invalid identifier name %q in mangle cache", k))
} else if _, ok := v.(string); ok || v == false {
clone[k] = v
} else {
log.AddError(nil, logger.Range{},
fmt.Sprintf("Expected %q in mangle cache to map to either a string or false", k))
}
}
return clone
}
////////////////////////////////////////////////////////////////////////////////
// Build API
type internalBuildResult struct {
result BuildResult
watchData fs.WatchData
options config.Options
}
func buildImpl(buildOpts BuildOptions) internalBuildResult {
start := time.Now()
logOptions := logger.OutputOptions{
IncludeSource: true,
MessageLimit: buildOpts.LogLimit,
Color: validateColor(buildOpts.Color),
LogLevel: validateLogLevel(buildOpts.LogLevel),
Overrides: validateLogOverrides(buildOpts.LogOverride),
}
log := logger.NewStderrLog(logOptions)
// Validate that the current working directory is an absolute path
realFS, err := fs.RealFS(fs.RealFSOptions{
AbsWorkingDir: buildOpts.AbsWorkingDir,
// This is a long-lived file system object so do not cache calls to
// ReadDirectory() (they are normally cached for the duration of a build
// for performance).
DoNotCache: true,
})
if err != nil {
log.AddError(nil, logger.Range{}, err.Error())
return internalBuildResult{result: BuildResult{Errors: convertMessagesToPublic(logger.Error, log.Done())}}
}
// Do not re-evaluate plugins when rebuilding. Also make sure the working
// directory doesn't change, since breaking that invariant would break the
// validation that we just did above.
caches := cache.MakeCacheSet()
oldAbsWorkingDir := buildOpts.AbsWorkingDir
plugins, onEndCallbacks, finalizeBuildOptions := loadPlugins(&buildOpts, realFS, log, caches)
if buildOpts.AbsWorkingDir != oldAbsWorkingDir {
panic("Mutating \"AbsWorkingDir\" is not allowed")
}
internalResult := rebuildImpl(buildOpts, caches, plugins, finalizeBuildOptions, onEndCallbacks, logOptions, log, false /* isRebuild */)
// Print a summary of the generated files to stderr. Except don't do
// this if the terminal is already being used for something else.
if logOptions.LogLevel <= logger.LevelInfo && len(internalResult.result.OutputFiles) > 0 &&
buildOpts.Watch == nil && !buildOpts.Incremental && !internalResult.options.WriteToStdout {
printSummary(logOptions, internalResult.result.OutputFiles, start)
}
return internalResult
}
func prettyPrintByteCount(n int) string {
var size string
if n < 1024 {
size = fmt.Sprintf("%db ", n)
} else if n < 1024*1024 {
size = fmt.Sprintf("%.1fkb", float64(n)/(1024))
} else if n < 1024*1024*1024 {
size = fmt.Sprintf("%.1fmb", float64(n)/(1024*1024))
} else {
size = fmt.Sprintf("%.1fgb", float64(n)/(1024*1024*1024))
}
return size
}
func printSummary(logOptions logger.OutputOptions, outputFiles []OutputFile, start time.Time) {
var table logger.SummaryTable = make([]logger.SummaryTableEntry, len(outputFiles))
if len(outputFiles) > 0 {
if cwd, err := os.Getwd(); err == nil {
if realFS, err := fs.RealFS(fs.RealFSOptions{AbsWorkingDir: cwd}); err == nil {
for i, file := range outputFiles {
path, ok := realFS.Rel(realFS.Cwd(), file.Path)
if !ok {
path = file.Path
}
base := realFS.Base(path)
n := len(file.Contents)
table[i] = logger.SummaryTableEntry{
Dir: path[:len(path)-len(base)],
Base: base,
Size: prettyPrintByteCount(n),
Bytes: n,
IsSourceMap: strings.HasSuffix(base, ".map"),
}
}
}
}
}
// Don't print the time taken by the build if we're running under Yarn 1
// since Yarn 1 always prints its own copy of the time taken by each command
if userAgent, ok := os.LookupEnv("npm_config_user_agent"); ok {
if strings.Contains(userAgent, "yarn/1.") {
logger.PrintSummary(logOptions.Color, table, nil)
return
}
}
logger.PrintSummary(logOptions.Color, table, &start)
}
func rebuildImpl(
buildOpts BuildOptions,
caches *cache.CacheSet,
plugins []config.Plugin,
finalizeBuildOptions func(*config.Options),
onEndCallbacks []func(*BuildResult),
logOptions logger.OutputOptions,
log logger.Log,
isRebuild bool,
) internalBuildResult {
// Convert and validate the buildOpts
realFS, err := fs.RealFS(fs.RealFSOptions{
AbsWorkingDir: buildOpts.AbsWorkingDir,
WantWatchData: buildOpts.Watch != nil,
})
if err != nil {
// This should already have been checked above
panic(err.Error())
}
targetFromAPI, jsFeatures, cssFeatures, targetEnv := validateFeatures(log, buildOpts.Target, buildOpts.Engines)
jsOverrides, jsMask, cssOverrides, cssMask := validateSupported(log, buildOpts.Supported)
outJS, outCSS := validateOutputExtensions(log, buildOpts.OutExtension)
bannerJS, bannerCSS := validateBannerOrFooter(log, "banner", buildOpts.Banner)
footerJS, footerCSS := validateBannerOrFooter(log, "footer", buildOpts.Footer)
minify := buildOpts.MinifyWhitespace && buildOpts.MinifyIdentifiers && buildOpts.MinifySyntax
platform := validatePlatform(buildOpts.Platform)
defines, injectedDefines := validateDefines(log, buildOpts.Define, buildOpts.Pure, platform, true /* isBuildAPI */, minify, buildOpts.Drop)
mangleCache := cloneMangleCache(log, buildOpts.MangleCache)
options := config.Options{
TargetFromAPI: targetFromAPI,
UnsupportedJSFeatures: jsFeatures.ApplyOverrides(jsOverrides, jsMask),
UnsupportedCSSFeatures: cssFeatures.ApplyOverrides(cssOverrides, cssMask),
UnsupportedJSFeatureOverrides: jsOverrides,
UnsupportedJSFeatureOverridesMask: jsMask,
UnsupportedCSSFeatureOverrides: cssOverrides,
UnsupportedCSSFeatureOverridesMask: cssMask,
OriginalTargetEnv: targetEnv,
JSX: config.JSXOptions{
Preserve: buildOpts.JSX == JSXPreserve,
AutomaticRuntime: buildOpts.JSX == JSXAutomatic,
Factory: validateJSXExpr(log, buildOpts.JSXFactory, "factory"),
Fragment: validateJSXExpr(log, buildOpts.JSXFragment, "fragment"),
Development: buildOpts.JSXDev,
ImportSource: buildOpts.JSXImportSource,
SideEffects: buildOpts.JSXSideEffects,
},
Defines: defines,
InjectedDefines: injectedDefines,
Platform: platform,
SourceMap: validateSourceMap(buildOpts.Sourcemap),
LegalComments: validateLegalComments(buildOpts.LegalComments, buildOpts.Bundle),
SourceRoot: buildOpts.SourceRoot,
ExcludeSourcesContent: buildOpts.SourcesContent == SourcesContentExclude,
MinifySyntax: buildOpts.MinifySyntax,
MinifyWhitespace: buildOpts.MinifyWhitespace,
MinifyIdentifiers: buildOpts.MinifyIdentifiers,
MangleProps: validateRegex(log, "mangle props", buildOpts.MangleProps),
ReserveProps: validateRegex(log, "reserve props", buildOpts.ReserveProps),
MangleQuoted: buildOpts.MangleQuoted == MangleQuotedTrue,
DropDebugger: (buildOpts.Drop & DropDebugger) != 0,
AllowOverwrite: buildOpts.AllowOverwrite,
ASCIIOnly: validateASCIIOnly(buildOpts.Charset),
IgnoreDCEAnnotations: buildOpts.IgnoreAnnotations,
TreeShaking: validateTreeShaking(buildOpts.TreeShaking, buildOpts.Bundle, buildOpts.Format),
GlobalName: validateGlobalName(log, buildOpts.GlobalName),
CodeSplitting: buildOpts.Splitting,
OutputFormat: validateFormat(buildOpts.Format),
AbsOutputFile: validatePath(log, realFS, buildOpts.Outfile, "outfile path"),
AbsOutputDir: validatePath(log, realFS, buildOpts.Outdir, "outdir path"),