-
-
Notifications
You must be signed in to change notification settings - Fork 151
/
build.go
1314 lines (1227 loc) · 41.4 KB
/
build.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 server
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/esm-dev/esm.sh/server/storage"
esbuild "github.com/evanw/esbuild/pkg/api"
"github.com/ije/gox/utils"
)
type BundleMode uint8
const (
BundleDefault BundleMode = iota
BundleAll
BundleFalse
)
type BuildContext struct {
zoneId string
npmrc *NpmRC
packageJson *PackageJSON
esmPath ESMPath
args BuildArgs
bundleMode BundleMode
target string
pinedTarget bool
dev bool
wd string
pkgDir string
pnpmPkgDir string
path string
stage string
deprecated string
importMap [][2]string
cjsRequires [][3]string
smOffset int
subBuilds *StringSet
wg sync.WaitGroup
}
type BuildMeta struct {
CSS bool `json:"css,omitempty"`
FromCJS bool `json:"fromCJS,omitempty"`
TypesOnly bool `json:"typesOnly,omitempty"`
Dts string `json:"dts,omitempty"`
Deps []string `json:"deps,omitempty"`
HasDefaultExport bool `json:"hasDefaultExport,omitempty"`
NamedExports []string `json:"-"`
}
var loaders = map[string]esbuild.Loader{
".js": esbuild.LoaderJS,
".mjs": esbuild.LoaderJS,
".cjs": esbuild.LoaderJS,
".jsx": esbuild.LoaderJSX,
".ts": esbuild.LoaderTS,
".mts": esbuild.LoaderTS,
".cts": esbuild.LoaderTS,
".tsx": esbuild.LoaderTSX,
".vue": esbuild.LoaderJS,
".svelte": esbuild.LoaderJS,
".css": esbuild.LoaderCSS,
".json": esbuild.LoaderJSON,
".txt": esbuild.LoaderText,
".html": esbuild.LoaderText,
".md": esbuild.LoaderText,
".svg": esbuild.LoaderDataURL,
".png": esbuild.LoaderDataURL,
".webp": esbuild.LoaderDataURL,
".gif": esbuild.LoaderDataURL,
".ttf": esbuild.LoaderDataURL,
".eot": esbuild.LoaderDataURL,
".woff": esbuild.LoaderDataURL,
".woff2": esbuild.LoaderDataURL,
}
func NewBuildContext(zoneId string, npmrc *NpmRC, esm ESMPath, args BuildArgs, target string, pinedTarget bool, bundleMode BundleMode, dev bool) *BuildContext {
return &BuildContext{
zoneId: zoneId,
npmrc: npmrc,
esmPath: esm,
args: args,
target: target,
pinedTarget: pinedTarget,
dev: dev,
bundleMode: bundleMode,
subBuilds: NewStringSet(),
}
}
func (ctx *BuildContext) Query() (*BuildMeta, error) {
key := ctx.getSavepath() + ".meta"
r, _, err := buildStorage.Get(key)
if err != nil && err != storage.ErrNotFound {
return nil, err
}
if err == nil {
var b BuildMeta
err = json.NewDecoder(r).Decode(&b)
r.Close()
if err == nil {
return &b, nil
}
// delete the invalid build meta
buildStorage.Delete(key)
}
return nil, nil
}
func (ctx *BuildContext) Build() (ret *BuildMeta, err error) {
if ctx.target == "types" {
return ctx.buildTypes()
}
// query previous build
ret, err = ctx.Query()
if err != nil || ret != nil {
return
}
// check if the package is deprecated
if ctx.deprecated == "" && !ctx.esmPath.GhPrefix && !ctx.esmPath.PrPrefix && !strings.HasPrefix(ctx.esmPath.PkgName, "@jsr/") {
var info *PackageJSON
info, err = ctx.npmrc.fetchPackageInfo(ctx.esmPath.PkgName, ctx.esmPath.PkgVersion)
if err != nil {
return
}
ctx.deprecated = info.Deprecated
}
// install the package
ctx.stage = "install"
err = ctx.install()
if err != nil {
return
}
// query again after installation (in case the sub-module path has been changed by the `normalizePackageJSON` function)
ret, err = ctx.Query()
if err != nil || ret != nil {
return
}
// build the module
ctx.stage = "build"
ret, err = ctx.buildModule()
if err != nil {
return
}
// save the build result into db
key := ctx.getSavepath() + ".meta"
buf := bytes.NewBuffer(nil)
err = json.NewEncoder(buf).Encode(ret)
if err != nil {
return
}
if e := buildStorage.Put(key, buf); e != nil {
log.Errorf("db: %v", e)
}
return
}
func (ctx *BuildContext) install() (err error) {
if ctx.wd == "" || ctx.packageJson == nil {
ctx.packageJson, err = ctx.npmrc.installPackage(ctx.esmPath)
if err != nil {
return
}
ctx.normalizePackageJSON(ctx.packageJson)
ctx.wd = path.Join(ctx.npmrc.StoreDir(), ctx.esmPath.PackageName())
ctx.pkgDir = path.Join(ctx.wd, "node_modules", ctx.esmPath.PkgName)
if rp, e := os.Readlink(ctx.pkgDir); e == nil {
ctx.pnpmPkgDir = path.Join(path.Dir(ctx.pkgDir), rp)
} else {
ctx.pnpmPkgDir = ctx.pkgDir
}
}
return
}
func (ctx *BuildContext) buildModule() (result *BuildMeta, err error) {
// build json
if strings.HasSuffix(ctx.esmPath.SubBareName, ".json") {
nmDir := path.Join(ctx.wd, "node_modules")
jsonPath := path.Join(nmDir, ctx.esmPath.PkgName, ctx.esmPath.SubBareName)
if existsFile(jsonPath) {
var jsonData []byte
jsonData, err = os.ReadFile(jsonPath)
if err != nil {
return
}
buffer := bytes.NewBufferString("export default ")
buffer.Write(jsonData)
err = buildStorage.Put(ctx.getSavepath(), buffer)
if err != nil {
return
}
result = &BuildMeta{
HasDefaultExport: true,
}
return
}
}
entry := ctx.resolveEntry(ctx.esmPath)
if entry.isEmpty() {
err = fmt.Errorf("could not resolve the build entry")
return
}
log.Debugf("build(%s): Entry%+v", ctx.esmPath, entry)
typesOnly := strings.HasPrefix(ctx.packageJson.Name, "@types/") || (entry.esm == "" && entry.cjs == "" && entry.dts != "")
if typesOnly {
result = &BuildMeta{
TypesOnly: true,
Dts: "/" + ctx.esmPath.PackageName() + entry.dts[1:],
}
ctx.transformDTS(entry.dts)
return
}
result, reexport, err := ctx.lexer(&entry, false)
if err != nil && !strings.HasPrefix(err.Error(), "cjsLexer: Can't resolve") {
return
}
// cjs reexport
if reexport != "" {
mod, _, e := ctx.lookupDep(reexport, false)
if e != nil {
err = e
return
}
// create a new build context to check if the reexported module has default export
b := NewBuildContext(ctx.zoneId, ctx.npmrc, mod, ctx.args, ctx.target, ctx.pinedTarget, BundleFalse, ctx.dev)
err = b.install()
if err != nil {
return
}
entry := b.resolveEntry(mod)
result, _, err = b.lexer(&entry, false)
if err != nil {
return
}
importUrl := ctx.getImportPath(mod, ctx.getBuildArgsPrefix(false))
buf := bytes.NewBuffer(nil)
fmt.Fprintf(buf, `export * from "%s";`, importUrl)
if result.HasDefaultExport {
fmt.Fprintf(buf, "\n")
fmt.Fprintf(buf, `export { default } from "%s";`, importUrl)
}
err = buildStorage.Put(ctx.getSavepath(), buf)
if err != nil {
return
}
result.Dts, err = ctx.resloveDTS(entry)
return
}
var entryPoint string
var input *esbuild.StdinOptions
entryModuleSpecifier := ctx.esmPath.PkgName
if ctx.esmPath.SubBareName != "" {
entryModuleSpecifier += "/" + ctx.esmPath.SubBareName
}
if entry.esm == "" {
buf := bytes.NewBuffer(nil)
fmt.Fprintf(buf, `import * as __module from "%s";`, entryModuleSpecifier)
if len(result.NamedExports) > 0 {
fmt.Fprintf(buf, `export const { %s } = __module;`, strings.Join(result.NamedExports, ","))
}
fmt.Fprintf(buf, "const { default: __default, ...__rest } = __module;")
fmt.Fprintf(buf, "export default (__default !== undefined ? __default : __rest);")
// Default reexport all members from original module to prevent missing named exports members
fmt.Fprintf(buf, `export * from "%s";`, entryModuleSpecifier)
input = &esbuild.StdinOptions{
Contents: buf.String(),
ResolveDir: ctx.wd,
Sourcefile: "entry.js",
}
} else {
if ctx.args.exports.Len() > 0 {
input = &esbuild.StdinOptions{
Contents: fmt.Sprintf(`export { %s } from "%s";`, strings.Join(ctx.args.exports.Values(), ","), entryModuleSpecifier),
ResolveDir: ctx.wd,
Sourcefile: "entry.js",
}
} else {
entryPoint = path.Join(ctx.pkgDir, entry.esm)
}
}
pkgSideEffects := esbuild.SideEffectsTrue
if ctx.packageJson.SideEffectsFalse {
pkgSideEffects = esbuild.SideEffectsFalse
}
noBundle := ctx.bundleMode == BundleFalse || (ctx.packageJson.SideEffects != nil && ctx.packageJson.SideEffects.Len() > 0)
if ctx.packageJson.Esmsh != nil {
if v, ok := ctx.packageJson.Esmsh["bundle"]; ok {
if b, ok := v.(bool); ok && !b {
noBundle = true
}
}
}
browserExclude := map[string]*StringSet{}
implicitExternal := NewStringSet()
deps := NewStringSet()
nodeEnv := ctx.getNodeEnv()
filename := ctx.Path()
dirname, _ := utils.SplitByLastByte(filename, '/')
define := map[string]string{
"__filename": fmt.Sprintf(`"%s"`, filename),
"__dirname": fmt.Sprintf(`"%s"`, dirname),
"Buffer": "__Buffer$",
"process": "__Process$",
"setImmediate": "__setImmediate$",
"clearImmediate": "clearTimeout",
"require.resolve": "__rResolve$",
"process.env.NODE_ENV": fmt.Sprintf(`"%s"`, nodeEnv),
}
if ctx.target == "node" {
define = map[string]string{
"process.env.NODE_ENV": fmt.Sprintf(`"%s"`, nodeEnv),
"global.process.env.NODE_ENV": fmt.Sprintf(`"%s"`, nodeEnv),
}
} else {
for k, v := range define {
define["global."+k] = v
}
define["global"] = "__global$"
}
conditions := ctx.args.conditions
if ctx.dev {
conditions = append(conditions, "development")
}
if ctx.isDenoTarget() {
conditions = append(conditions, "deno")
}
options := esbuild.BuildOptions{
Bundle: true,
Format: esbuild.FormatESModule,
Target: targets[ctx.target],
Platform: esbuild.PlatformBrowser,
Define: define,
JSX: esbuild.JSXAutomatic,
JSXImportSource: "react",
MinifyWhitespace: config.Minify,
MinifyIdentifiers: config.Minify,
MinifySyntax: config.Minify,
KeepNames: ctx.args.keepNames, // prevent class/function names erasing
IgnoreAnnotations: ctx.args.ignoreAnnotations, // some libs maybe use wrong side-effect annotations
Conditions: conditions,
Loader: loaders,
Outdir: "/esbuild",
Write: false,
}
if input != nil {
options.Stdin = input
} else if entryPoint != "" {
options.EntryPoints = []string{entryPoint}
}
if ctx.target == "node" {
options.Platform = esbuild.PlatformNode
}
// support features that can not be polyfilled
options.Supported = map[string]bool{
"bigint": true,
"top-level-await": true,
}
if config.SourceMap {
options.Sourcemap = esbuild.SourceMapExternal
}
for _, pkgName := range []string{"preact", "react", "solid-js", "mono-jsx", "vue", "hono"} {
_, ok1 := ctx.packageJson.Dependencies[pkgName]
_, ok2 := ctx.packageJson.PeerDependencies[pkgName]
if ok1 || ok2 {
options.JSXImportSource = pkgName
if pkgName == "hono" {
options.JSXImportSource += "/jsx"
}
break
}
}
options.Plugins = []esbuild.Plugin{{
Name: "esm",
Setup: func(build esbuild.PluginBuild) {
build.OnResolve(
esbuild.OnResolveOptions{Filter: ".*"},
func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) {
// if it's the entry module
if args.Path == entryPoint || args.Path == entryModuleSpecifier {
path := args.Path
if path == entryModuleSpecifier {
if entry.esm != "" {
path = filepath.Join(ctx.pnpmPkgDir, entry.esm)
} else if entry.cjs != "" {
path = filepath.Join(ctx.pnpmPkgDir, entry.cjs)
}
}
if strings.HasSuffix(path, ".svelte") {
return esbuild.OnResolveResult{Path: path, Namespace: "svelte"}, nil
}
if strings.HasSuffix(path, ".vue") {
return esbuild.OnResolveResult{Path: path, Namespace: "vue"}, nil
}
return esbuild.OnResolveResult{Path: path}, nil
}
// ban file urls
if strings.HasPrefix(args.Path, "file:") {
return esbuild.OnResolveResult{
Path: fmt.Sprintf("/error.js?type=unsupported-file-dependency&name=%s&importer=%s", strings.TrimPrefix(args.Path, "file:"), ctx.esmPath),
External: true,
}, nil
}
// skip dataurl/http modules
if strings.HasPrefix(args.Path, "data:") || strings.HasPrefix(args.Path, "https:") || strings.HasPrefix(args.Path, "http:") {
return esbuild.OnResolveResult{
Path: args.Path,
External: true,
}, nil
}
// if `?ignore-require` present, ignore specifier that is a require call
if ctx.args.externalRequire && args.Kind == esbuild.ResolveJSRequireCall && entry.esm != "" {
return esbuild.OnResolveResult{
Path: args.Path,
External: true,
}, nil
}
// ignore yarn PnP API
if args.Path == "pnpapi" {
return esbuild.OnResolveResult{
Path: args.Path,
Namespace: "browser-exclude",
}, nil
}
// it's implicit external
if implicitExternal.Has(args.Path) {
externalPath, err := ctx.resolveExternalModule(args.Path, args.Kind)
if err != nil {
return esbuild.OnResolveResult{}, err
}
return esbuild.OnResolveResult{
Path: externalPath,
External: true,
}, nil
}
// normalize specifier
specifier := normalizeImportSpecifier(args.Path)
// resolve specifier by checking `?alias` query
if len(ctx.args.alias) > 0 && !isRelPathSpecifier(specifier) {
pkgName, _, subpath, _ := splitESMPath(specifier)
if name, ok := ctx.args.alias[pkgName]; ok {
specifier = name
if subpath != "" {
specifier += "/" + subpath
}
}
}
// resolve specifier with package `imports` field
if len(ctx.packageJson.Imports) > 0 {
if v, ok := ctx.packageJson.Imports[specifier]; ok {
if s, ok := v.(string); ok {
specifier = s
} else if m, ok := v.(map[string]interface{}); ok {
targets := []string{"browser", "module", "import", "default"}
if ctx.isDenoTarget() {
targets = []string{"deno", "module", "import", "default"}
} else if ctx.target == "node" {
targets = []string{"node", "module", "import", "default"}
}
for _, t := range targets {
if v, ok := m[t]; ok {
if s, ok := v.(string); ok {
specifier = s
break
}
}
}
}
}
}
// resolve specifier with package `browser` field
if !isRelPathSpecifier(specifier) && len(ctx.packageJson.Browser) > 0 && ctx.isBrowserTarget() {
if name, ok := ctx.packageJson.Browser[specifier]; ok {
if name == "" {
return esbuild.OnResolveResult{
Path: args.Path,
Namespace: "browser-exclude",
}, nil
}
specifier = name
}
}
// force to use `npm:` specifier for `denonext` target
if forceNpmSpecifiers[specifier] && ctx.target == "denonext" {
version := ""
pkgName, _, subPath, _ := splitESMPath(specifier)
if pkgName == ctx.esmPath.PkgName {
version = ctx.esmPath.PkgVersion
} else if v, ok := ctx.packageJson.Dependencies[pkgName]; ok && regexpVersionStrict.MatchString(v) {
version = v
} else if v, ok := ctx.packageJson.PeerDependencies[pkgName]; ok && regexpVersionStrict.MatchString(v) {
version = v
}
p := pkgName
if version != "" {
p += "@" + version
}
if subPath != "" {
p += "/" + subPath
}
return esbuild.OnResolveResult{
Path: fmt.Sprintf("npm:%s", p),
External: true,
}, nil
}
var fullFilepath string
if strings.HasPrefix(specifier, "/") {
fullFilepath = specifier
} else if isRelPathSpecifier(specifier) {
fullFilepath = path.Join(args.ResolveDir, specifier)
} else {
fullFilepath = path.Join(ctx.wd, "node_modules", ".pnpm", "node_modules", specifier)
}
// node native modules do not work via http import
if strings.HasSuffix(fullFilepath, ".node") && existsFile(fullFilepath) {
return esbuild.OnResolveResult{
Path: fmt.Sprintf("/error.js?type=unsupported-node-native-module&name=%s&importer=%s", path.Base(args.Path), ctx.esmPath),
External: true,
}, nil
}
// bundles json module
if strings.HasSuffix(fullFilepath, ".json") {
return esbuild.OnResolveResult{}, nil
}
// embed wasm as WebAssembly.Module
if strings.HasSuffix(fullFilepath, ".wasm") {
return esbuild.OnResolveResult{
Path: fullFilepath,
Namespace: "wasm",
}, nil
}
// transfrom svelte component
if strings.HasSuffix(fullFilepath, ".svelte") {
return esbuild.OnResolveResult{
Path: fullFilepath,
Namespace: "svelte",
}, nil
}
// transfrom Vue SFC
if strings.HasSuffix(fullFilepath, ".vue") {
return esbuild.OnResolveResult{
Path: fullFilepath,
Namespace: "vue",
}, nil
}
// externalize parent module
// e.g. "react/jsx-runtime" imports "react"
if ctx.esmPath.SubBareName != "" && specifier == ctx.esmPath.PkgName && ctx.bundleMode != BundleAll {
externalPath, err := ctx.resolveExternalModule(ctx.esmPath.PkgName, args.Kind)
if err != nil {
return esbuild.OnResolveResult{}, err
}
return esbuild.OnResolveResult{
Path: externalPath,
External: true,
SideEffects: pkgSideEffects,
}, nil
}
// it's nodejs builtin module
if isNodeBuiltInModule(specifier) {
externalPath, err := ctx.resolveExternalModule(specifier, args.Kind)
if err != nil {
return esbuild.OnResolveResult{}, err
}
return esbuild.OnResolveResult{
Path: externalPath,
External: true,
}, nil
}
// bundles all dependencies in `bundle` mode, apart from peer dependencies and `?external` query]
if ctx.bundleMode == BundleAll && !ctx.args.external.Has(toPackageName(specifier)) && !implicitExternal.Has(specifier) {
pkgName := toPackageName(specifier)
_, ok := ctx.packageJson.PeerDependencies[pkgName]
if !ok {
return esbuild.OnResolveResult{}, nil
}
}
// bundle "@babel/runtime/*"
if (args.Kind != esbuild.ResolveJSDynamicImport && !noBundle) && ctx.packageJson.Name != "@babel/runtime" && (strings.HasPrefix(specifier, "@babel/runtime/") || strings.Contains(args.Importer, "/@babel/runtime/")) {
return esbuild.OnResolveResult{}, nil
}
if strings.HasPrefix(specifier, "/") || isRelPathSpecifier(specifier) {
specifier = strings.TrimPrefix(fullFilepath, path.Join(ctx.wd, "node_modules")+"/")
if strings.HasPrefix(specifier, ".pnpm") {
a := strings.Split(specifier, "/node_modules/")
if len(a) > 1 {
specifier = a[1]
}
}
pkgName := ctx.packageJson.Name
isInternalModule := strings.HasPrefix(specifier, pkgName+"/")
if !isInternalModule && ctx.packageJson.PkgName != "" {
// github packages may have different package name with the repository name
pkgName = ctx.packageJson.PkgName
isInternalModule = strings.HasPrefix(specifier, pkgName+"/")
}
if isInternalModule {
// if meets scenarios of "./index.mjs" importing "./index.c?js"
// let esbuild to handle it
if stripModuleExt(fullFilepath) == stripModuleExt(args.Importer) {
return esbuild.OnResolveResult{}, nil
}
moduleSpecifier := "." + strings.TrimPrefix(specifier, pkgName)
if path.Ext(fullFilepath) == "" || !existsFile(fullFilepath) {
subPath := utils.NormalizePathname(moduleSpecifier)[1:]
entry := ctx.resolveEntry(ESMPath{
PkgName: ctx.esmPath.PkgName,
PkgVersion: ctx.esmPath.PkgVersion,
SubBareName: toModuleBareName(subPath, true),
SubPath: subPath,
})
if args.Kind == esbuild.ResolveJSImportStatement || args.Kind == esbuild.ResolveJSDynamicImport {
if entry.esm != "" {
moduleSpecifier = entry.esm
} else if entry.cjs != "" {
moduleSpecifier = entry.cjs
}
} else if args.Kind == esbuild.ResolveJSRequireCall || args.Kind == esbuild.ResolveJSRequireResolve {
if entry.cjs != "" {
moduleSpecifier = entry.cjs
} else if entry.esm != "" {
moduleSpecifier = entry.esm
}
}
}
// resolve specifier with package `browser` field
if len(ctx.packageJson.Browser) > 0 && ctx.isBrowserTarget() {
if path, ok := ctx.packageJson.Browser[moduleSpecifier]; ok {
if path == "" {
return esbuild.OnResolveResult{
Path: args.Path,
Namespace: "browser-exclude",
}, nil
}
if !isRelPathSpecifier(path) {
externalPath, err := ctx.resolveExternalModule(path, args.Kind)
if err != nil {
return esbuild.OnResolveResult{}, err
}
return esbuild.OnResolveResult{
Path: externalPath,
External: true,
}, nil
}
moduleSpecifier = path
}
}
bareName := stripModuleExt(moduleSpecifier)
// split modules based on the `exports` field of package.json
if om, ok := ctx.packageJson.Exports.(*OrderedMap); ok {
for _, exportName := range om.keys {
v := om.Get(exportName)
if !(exportName == "." || strings.HasPrefix(exportName, "./")) {
continue
}
if strings.ContainsRune(exportName, '*') {
var (
match bool
prefix string
suffix string
)
if s, ok := v.(string); ok {
// exports: "./*": "./dist/*.js"
prefix, suffix = utils.SplitByLastByte(s, '*')
match = strings.HasPrefix(bareName, prefix) && (suffix == "" || strings.HasSuffix(moduleSpecifier, suffix))
} else if m, ok := v.(*OrderedMap); ok {
// exports: "./*": { "import": "./dist/*.js" }
// exports: "./*": { "import": { default: "./dist/*.js" } }
// ...
paths := getAllExportsPaths(m)
for _, path := range paths {
prefix, suffix = utils.SplitByLastByte(path, '*')
match = strings.HasPrefix(bareName, prefix) && (suffix == "" || strings.HasSuffix(moduleSpecifier, suffix))
if match {
break
}
}
}
if match {
exportPrefix, _ := utils.SplitByLastByte(exportName, '*')
exportModuleName := path.Join(ctx.packageJson.Name, exportPrefix+strings.TrimPrefix(bareName, prefix))
if exportModuleName != entryModuleSpecifier && exportModuleName != entryModuleSpecifier+"/index" {
externalPath, err := ctx.resolveExternalModule(exportModuleName, args.Kind)
if err != nil {
return esbuild.OnResolveResult{}, err
}
return esbuild.OnResolveResult{
Path: externalPath,
External: true,
SideEffects: pkgSideEffects,
}, nil
}
}
} else {
match := false
if s, ok := v.(string); ok && stripModuleExt(s) == bareName {
// exports: "./foo": "./foo.js"
match = true
} else if m, ok := v.(*OrderedMap); ok {
// exports: "./foo": { "import": "./foo.js" }
// exports: "./foo": { "import": { default: "./foo.js" } }
// ...
paths := getAllExportsPaths(m)
for _, path := range paths {
if stripModuleExt(path) == bareName {
match = true
break
}
}
}
if match {
exportModuleName := path.Join(ctx.packageJson.Name, stripModuleExt(exportName))
if exportModuleName != entryModuleSpecifier && exportModuleName != entryModuleSpecifier+"/index" {
externalPath, err := ctx.resolveExternalModule(exportModuleName, args.Kind)
if err != nil {
return esbuild.OnResolveResult{}, err
}
return esbuild.OnResolveResult{
Path: externalPath,
External: true,
SideEffects: pkgSideEffects,
}, nil
}
}
}
}
}
// module file path
moduleFilepath := path.Join(ctx.pnpmPkgDir, moduleSpecifier)
// if it's the entry module
if moduleSpecifier == entry.cjs || moduleSpecifier == entry.esm {
return esbuild.OnResolveResult{Path: moduleFilepath}, nil
}
// split the module that is an alias of a dependency
// means this file just include a single line(js): `export * from "dep"`
fi, ioErr := os.Lstat(moduleFilepath)
if ioErr == nil && fi.Size() < 128 {
data, ioErr := os.ReadFile(moduleFilepath)
if ioErr == nil {
out, esbErr := minify(string(data), esbuild.LoaderJS, esbuild.ESNext)
if esbErr == nil {
p := bytes.Split(out, []byte("\""))
if len(p) == 3 && string(p[0]) == "export*from" && string(p[2]) == ";\n" {
url := string(p[1])
if !isRelPathSpecifier(url) {
externalPath, err := ctx.resolveExternalModule(url, args.Kind)
if err != nil {
return esbuild.OnResolveResult{}, err
}
return esbuild.OnResolveResult{
Path: externalPath,
External: true,
SideEffects: pkgSideEffects,
}, nil
}
}
}
}
}
// bundle the internal module if it's not a dynamic import or `?bundle=false` query present
if args.Kind != esbuild.ResolveJSDynamicImport && !noBundle {
if existsFile(moduleFilepath) {
return esbuild.OnResolveResult{Path: moduleFilepath}, nil
}
// let esbuild to handle it
return esbuild.OnResolveResult{}, nil
}
}
}
// replace some npm modules with browser native APIs
if specifier != "fsevents" || ctx.isBrowserTarget() {
replacement, ok := npmReplacements[specifier+"_"+ctx.target]
if !ok {
replacement, ok = npmReplacements[specifier]
}
if ok {
if args.Kind == esbuild.ResolveJSRequireCall || args.Kind == esbuild.ResolveJSRequireResolve {
ctx.cjsRequires = append(ctx.cjsRequires, [3]string{
"npm:" + specifier,
string(replacement.cjs),
"",
})
return esbuild.OnResolveResult{
Path: "npm:" + specifier,
External: true,
}, nil
}
return esbuild.OnResolveResult{
Path: specifier,
PluginData: replacement.esm,
Namespace: "npm-replacement",
}, nil
}
}
// dynamic external
sideEffects := esbuild.SideEffectsFalse
if specifier == ctx.packageJson.Name || specifier == ctx.packageJson.PkgName || strings.HasPrefix(specifier, ctx.packageJson.Name+"/") || strings.HasPrefix(specifier, ctx.packageJson.Name+"/") {
sideEffects = pkgSideEffects
}
externalPath, err := ctx.resolveExternalModule(specifier, args.Kind)
if err != nil {
return esbuild.OnResolveResult{}, err
}
return esbuild.OnResolveResult{
Path: externalPath,
External: true,
SideEffects: sideEffects,
}, nil
},
)
// npm replacement loader
build.OnLoad(
esbuild.OnLoadOptions{Filter: ".*", Namespace: "npm-replacement"},
func(args esbuild.OnLoadArgs) (ret esbuild.OnLoadResult, err error) {
contents := string(args.PluginData.([]byte))
return esbuild.OnLoadResult{Contents: &contents, Loader: esbuild.LoaderJS}, nil
},
)
// browser exclude loader
build.OnLoad(
esbuild.OnLoadOptions{Filter: ".*", Namespace: "browser-exclude"},
func(args esbuild.OnLoadArgs) (ret esbuild.OnLoadResult, err error) {
contents := "export default {};"
if exports, ok := browserExclude[args.Path]; ok {
for _, name := range exports.Values() {
contents = fmt.Sprintf("%sexport const %s = {};", contents, name)
}
}
return esbuild.OnLoadResult{Contents: &contents, Loader: esbuild.LoaderJS}, nil
},
)
// wasm module exclude loader
build.OnLoad(
esbuild.OnLoadOptions{Filter: ".*", Namespace: "wasm"},
func(args esbuild.OnLoadArgs) (ret esbuild.OnLoadResult, err error) {
wasm, err := os.ReadFile(args.Path)
if err != nil {
return
}
wasm64 := base64.StdEncoding.EncodeToString(wasm)
code := fmt.Sprintf("export default Uint8Array.from(atob('%s'), c => c.charCodeAt(0))", wasm64)
return esbuild.OnLoadResult{Contents: &code, Loader: esbuild.LoaderJS}, nil
},
)
// svelte component loader
build.OnLoad(
esbuild.OnLoadOptions{Filter: ".*", Namespace: "svelte"},
func(args esbuild.OnLoadArgs) (esbuild.OnLoadResult, error) {
code, err := os.ReadFile(args.Path)
if err != nil {
return esbuild.OnLoadResult{}, err
}
svelteVersion := "5"
if version, ok := ctx.args.deps["svelte"]; ok {
svelteVersion = version
} else if version, ok := ctx.packageJson.Dependencies["svelte"]; ok {
svelteVersion = version
} else if version, ok := ctx.packageJson.PeerDependencies["svelte"]; ok {
svelteVersion = version
}
if !regexpVersionStrict.MatchString(svelteVersion) {
info, err := ctx.npmrc.getPackageInfo("svelte", svelteVersion)
if err != nil {
return esbuild.OnLoadResult{}, errors.New("failed to get svelte package info")
}
svelteVersion = info.Version
}
if semverLessThan(svelteVersion, "4.0.0") {
return esbuild.OnLoadResult{}, errors.New("svelte version must be greater than 4.0.0")
}
out, err := transformSvelte(ctx.npmrc, svelteVersion, []string{ctx.esmPath.String(), string(code)})
if err != nil {
return esbuild.OnLoadResult{}, err
}
return esbuild.OnLoadResult{Contents: &out.Code, Loader: esbuild.LoaderJS}, nil
},
)
// vue component loader
build.OnLoad(
esbuild.OnLoadOptions{Filter: ".*", Namespace: "vue"},
func(args esbuild.OnLoadArgs) (esbuild.OnLoadResult, error) {
code, err := os.ReadFile(args.Path)
if err != nil {
return esbuild.OnLoadResult{}, err
}
vueVersion := "3"
if version, ok := ctx.args.deps["vue"]; ok {
vueVersion = version
} else if version, ok := ctx.packageJson.Dependencies["vue"]; ok {
vueVersion = version
} else if version, ok := ctx.packageJson.PeerDependencies["vue"]; ok {
vueVersion = version
}
if !regexpVersionStrict.MatchString(vueVersion) {
info, err := ctx.npmrc.getPackageInfo("vue", vueVersion)
if err != nil {
return esbuild.OnLoadResult{}, errors.New("failed to get vue package info")
}
vueVersion = info.Version
}
if semverLessThan(vueVersion, "3.0.0") {
return esbuild.OnLoadResult{}, errors.New("vue version must be greater than 3.0.0")
}
out, err := transformVue(ctx.npmrc, vueVersion, []string{ctx.esmPath.String(), string(code)})
if err != nil {
return esbuild.OnLoadResult{}, err
}
if out.Lang == "ts" {
return esbuild.OnLoadResult{Contents: &out.Code, Loader: esbuild.LoaderTS}, nil
}
return esbuild.OnLoadResult{Contents: &out.Code, Loader: esbuild.LoaderJS}, nil
},
)
},
}}
rebuild:
ret := esbuild.Build(options)
if len(ret.Errors) > 0 {
// mark the missing module as external to exclude it from the bundle
msg := ret.Errors[0].Text
if strings.HasPrefix(msg, "Could not resolve \"") {
// current module can not be marked as an external
if strings.HasPrefix(msg, fmt.Sprintf("Could not resolve \"%s\"", entryModuleSpecifier)) {
err = fmt.Errorf("could not resolve \"%s\"", entryModuleSpecifier)
return
}
name := strings.Split(msg, "\"")[1]
if !implicitExternal.Has(name) {
log.Warnf("build(%s): implicit external '%s'", ctx.Path(), name)
implicitExternal.Add(name)
goto rebuild
}