-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
bundler.go
471 lines (400 loc) · 12.9 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
package bundler
import (
"crypto/sha1"
"encoding/base64"
"fmt"
"io/ioutil"
"mime"
"net/http"
"os"
"path"
"sync"
"github.com/evanw/esbuild/internal/ast"
"github.com/evanw/esbuild/internal/fs"
"github.com/evanw/esbuild/internal/lexer"
"github.com/evanw/esbuild/internal/logging"
"github.com/evanw/esbuild/internal/parser"
"github.com/evanw/esbuild/internal/printer"
"github.com/evanw/esbuild/internal/resolver"
"github.com/evanw/esbuild/internal/runtime"
)
type file struct {
ast ast.AST
// This maps the non-unique import path present in the source file to the
// unique source index for that module. This isn't unique because two paths
// in the source file may refer to the same module:
//
// import "../lib/util";
// import "./util";
//
// This is used by the printer to write out the source index for modules that
// are referenced in the AST.
resolvedImports map[string]uint32
// If this file ends up being used in the bundle, this is an additional file
// that must be written to the output directory. It's used by the "file"
// loader.
additionalFile *OutputFile
// If true, this file was listed as not having side effects by a package.json
// file in one of our containing directories with a "sideEffects" field.
ignoreIfUnused bool
}
func (f *file) resolveImport(path ast.Path) (uint32, bool) {
if path.UseSourceIndex {
return path.SourceIndex, true
}
sourceIndex, ok := f.resolvedImports[path.Text]
return sourceIndex, ok
}
type Bundle struct {
fs fs.FS
sources []logging.Source
files []file
entryPoints []uint32
}
type parseFlags struct {
isEntryPoint bool
isDisabled bool
ignoreIfUnused bool
}
type parseArgs struct {
fs fs.FS
log logging.Log
res resolver.Resolver
sourcePath string
sourceIndex uint32
isStdin bool
importSource logging.Source
flags parseFlags
pathRange ast.Range
parseOptions parser.ParseOptions
bundleOptions BundleOptions
results chan parseResult
}
type parseResult struct {
source logging.Source
file file
ok bool
}
func parseFile(args parseArgs) {
prettyPath := args.sourcePath
if !args.isStdin {
prettyPath = args.res.PrettyPath(args.sourcePath)
}
contents := ""
// Disabled files are left empty
if !args.flags.isDisabled {
if args.isStdin {
bytes, err := ioutil.ReadAll(os.Stdin)
if err != nil {
args.log.AddRangeError(args.importSource, args.pathRange,
fmt.Sprintf("Could not read from stdin: %s", err.Error()))
args.results <- parseResult{}
return
}
contents = string(bytes)
} else {
var ok bool
contents, ok = args.res.Read(args.sourcePath)
if !ok {
args.log.AddRangeError(args.importSource, args.pathRange,
fmt.Sprintf("Could not read from file: %s", args.sourcePath))
args.results <- parseResult{}
return
}
}
}
source := logging.Source{
Index: args.sourceIndex,
IsStdin: args.isStdin,
AbsolutePath: args.sourcePath,
PrettyPath: prettyPath,
Contents: contents,
}
// Get the file extension
extension := path.Ext(args.sourcePath)
// Pick the loader based on the file extension
loader := args.bundleOptions.ExtensionToLoader[extension]
// Special-case reading from stdin
if args.bundleOptions.LoaderForStdin != LoaderNone && source.IsStdin {
loader = args.bundleOptions.LoaderForStdin
}
result := parseResult{
source: source,
file: file{
ignoreIfUnused: args.flags.ignoreIfUnused,
},
ok: true,
}
switch loader {
case LoaderJS:
result.file.ast, result.ok = parser.Parse(args.log, source, args.parseOptions)
case LoaderJSX:
args.parseOptions.JSX.Parse = true
result.file.ast, result.ok = parser.Parse(args.log, source, args.parseOptions)
case LoaderTS:
args.parseOptions.TS.Parse = true
result.file.ast, result.ok = parser.Parse(args.log, source, args.parseOptions)
case LoaderTSX:
args.parseOptions.TS.Parse = true
args.parseOptions.JSX.Parse = true
result.file.ast, result.ok = parser.Parse(args.log, source, args.parseOptions)
case LoaderJSON:
var expr ast.Expr
expr, result.ok = parser.ParseJSON(args.log, source, parser.ParseJSONOptions{})
result.file.ast = parser.ModuleExportsAST(args.log, source, args.parseOptions, expr)
case LoaderText:
expr := ast.Expr{Data: &ast.EString{lexer.StringToUTF16(source.Contents)}}
result.file.ast = parser.ModuleExportsAST(args.log, source, args.parseOptions, expr)
case LoaderBase64:
encoded := base64.StdEncoding.EncodeToString([]byte(source.Contents))
expr := ast.Expr{Data: &ast.EString{lexer.StringToUTF16(encoded)}}
result.file.ast = parser.ModuleExportsAST(args.log, source, args.parseOptions, expr)
case LoaderDataURL:
mimeType := mime.TypeByExtension(extension)
if mimeType == "" {
mimeType = http.DetectContentType([]byte(source.Contents))
}
encoded := base64.StdEncoding.EncodeToString([]byte(source.Contents))
url := "data:" + mimeType + ";base64," + encoded
expr := ast.Expr{Data: &ast.EString{lexer.StringToUTF16(url)}}
result.file.ast = parser.ModuleExportsAST(args.log, source, args.parseOptions, expr)
case LoaderFile:
// Get the file name, making sure to use the "fs" interface so we do the
// right thing on Windows (Windows-style paths for the command-line
// interface and Unix-style paths for tests, even on Windows)
baseName := args.fs.Base(args.sourcePath)
// Add a hash to the file name to prevent multiple files with the same name
// but different contents from colliding
bytes := []byte(source.Contents)
hashBytes := sha1.Sum(bytes)
hash := base64.URLEncoding.EncodeToString(hashBytes[:])[:8]
baseName = baseName[:len(baseName)-len(extension)] + "." + hash + extension
// Determine the destination folder
targetFolder := args.bundleOptions.AbsOutputDir
if targetFolder == "" {
targetFolder = args.fs.Dir(args.bundleOptions.AbsOutputFile)
}
// Export the resulting relative path as a string
expr := ast.Expr{ast.Loc{0}, &ast.EString{lexer.StringToUTF16(baseName)}}
result.file.ast = parser.ModuleExportsAST(args.log, source, args.parseOptions, expr)
// Copy the file using an additional file payload to make sure we only copy
// the file if the module isn't removed due to tree shaking.
result.file.additionalFile = &OutputFile{
AbsPath: args.fs.Join(targetFolder, baseName),
Contents: bytes,
}
default:
result.ok = false
args.log.AddRangeError(args.importSource, args.pathRange,
fmt.Sprintf("File extension not supported: %s", args.sourcePath))
}
args.results <- result
}
func ScanBundle(
log logging.Log, fs fs.FS, res resolver.Resolver, entryPaths []string,
parseOptions parser.ParseOptions, bundleOptions BundleOptions,
) Bundle {
sources := []logging.Source{}
files := []file{}
visited := make(map[string]uint32)
results := make(chan parseResult)
remaining := 0
if bundleOptions.ExtensionToLoader == nil {
bundleOptions.ExtensionToLoader = DefaultExtensionToLoaderMap()
}
// Always start by parsing the runtime file
{
source := logging.Source{
Index: ast.RuntimeSourceIndex,
AbsolutePath: "<runtime>",
PrettyPath: "<runtime>",
Contents: runtime.Code,
}
sources = append(sources, source)
files = append(files, file{})
remaining++
go func() {
runtimeParseOptions := parseOptions
// Always do tree shaking for the runtime because we never want to
// include unnecessary runtime code
runtimeParseOptions.IsBundling = true
ast, ok := parser.Parse(log, source, runtimeParseOptions)
results <- parseResult{source: source, file: file{ast: ast}, ok: ok}
}()
}
maybeParseFile := func(path string, importSource logging.Source, pathRange ast.Range, flags parseFlags) uint32 {
sourceIndex, ok := visited[path]
if !ok {
sourceIndex = uint32(len(sources))
isStdin := bundleOptions.LoaderForStdin != LoaderNone && flags.isEntryPoint
if !isStdin {
visited[path] = sourceIndex
}
sources = append(sources, logging.Source{})
files = append(files, file{})
remaining++
go parseFile(parseArgs{
fs: fs,
log: log,
res: res,
sourcePath: path,
sourceIndex: sourceIndex,
isStdin: isStdin,
importSource: importSource,
flags: flags,
pathRange: pathRange,
parseOptions: parseOptions,
bundleOptions: bundleOptions,
results: results,
})
}
return sourceIndex
}
entryPoints := []uint32{}
for _, path := range entryPaths {
flags := parseFlags{isEntryPoint: true}
sourceIndex := maybeParseFile(path, logging.Source{}, ast.Range{}, flags)
entryPoints = append(entryPoints, sourceIndex)
}
for remaining > 0 {
result := <-results
remaining--
if !result.ok {
continue
}
source := result.source
result.file.resolvedImports = make(map[string]uint32)
// Don't try to resolve paths if we're not bundling
if bundleOptions.IsBundling {
for _, part := range result.file.ast.Parts {
for _, importPath := range part.ImportPaths {
// Don't try to resolve imports of the special runtime path
if importPath.Path.UseSourceIndex && importPath.Path.SourceIndex == ast.RuntimeSourceIndex {
continue
}
sourcePath := source.AbsolutePath
pathText := importPath.Path.Text
pathRange := source.RangeOfString(importPath.Path.Loc)
resolveResult := res.Resolve(sourcePath, pathText)
switch resolveResult.Status {
case resolver.ResolveEnabled, resolver.ResolveDisabled:
flags := parseFlags{
isDisabled: resolveResult.Status == resolver.ResolveDisabled,
ignoreIfUnused: resolveResult.IgnoreIfUnused,
}
sourceIndex := maybeParseFile(resolveResult.AbsolutePath, source, pathRange, flags)
result.file.resolvedImports[pathText] = sourceIndex
case resolver.ResolveMissing:
log.AddRangeError(source, pathRange, fmt.Sprintf("Could not resolve %q", pathText))
}
}
}
}
sources[source.Index] = source
files[source.Index] = result.file
}
return Bundle{fs, sources, files, entryPoints}
}
type Loader int
const (
LoaderNone Loader = iota
LoaderJS
LoaderJSX
LoaderTS
LoaderTSX
LoaderJSON
LoaderText
LoaderBase64
LoaderDataURL
LoaderFile
)
func DefaultExtensionToLoaderMap() map[string]Loader {
return map[string]Loader{
".js": LoaderJS,
".mjs": LoaderJS,
".cjs": LoaderJS,
".jsx": LoaderJSX,
".ts": LoaderTS,
".tsx": LoaderTSX,
".json": LoaderJSON,
".txt": LoaderText,
}
}
type SourceMap uint8
const (
SourceMapNone SourceMap = iota
SourceMapInline
SourceMapLinkedWithComment
SourceMapExternalWithoutComment
)
type BundleOptions struct {
// true: imports are scanned and bundled along with the file
// false: imports are left alone and the file is passed through as-is
IsBundling bool
AbsOutputFile string
AbsOutputDir string
RemoveWhitespace bool
MinifyIdentifiers bool
MangleSyntax bool
ModuleName string
ExtensionToLoader map[string]Loader
OutputFormat printer.Format
SourceMap SourceMap
SourceFile string // The "original file path" for the source map
// If this isn't LoaderNone, all entry point contents are assumed to come
// from stdin and must be loaded with this loader
LoaderForStdin Loader
// If true, make sure to generate a single file that can be written to stdout
WriteToStdout bool
omitRuntimeForTests bool
}
type OutputFile struct {
AbsPath string
Contents []byte
}
type lineColumnOffset struct {
lines int
columns int
}
type compileResult struct {
printer.PrintResult
// If this is an entry point, this is optional code to stick on the end of
// the chunk. This is used to for example trigger the lazily-evaluated
// CommonJS wrapper for the entry point.
entryPointTail *printer.PrintResult
sourceIndex uint32
// This is the line and column offset since the previous JavaScript string
// or the start of the file if this is the first JavaScript string.
generatedOffset lineColumnOffset
// The source map contains the original source code, which is quoted in
// parallel for speed. This is only filled in if the SourceMap option is
// enabled.
quotedSource string
}
func (b *Bundle) Compile(log logging.Log, options BundleOptions) []OutputFile {
if options.ExtensionToLoader == nil {
options.ExtensionToLoader = DefaultExtensionToLoaderMap()
}
// The format can't be "preserve" while bundling
if options.IsBundling && options.OutputFormat == printer.FormatPreserve {
options.OutputFormat = printer.FormatESModule
}
waitGroup := sync.WaitGroup{}
resultGroups := make([][]OutputFile, len(b.entryPoints))
// Link each file with the runtime file separately in parallel
for i, entryPoint := range b.entryPoints {
waitGroup.Add(1)
go func(i int, entryPoint uint32) {
c := newLinkerContext(&options, log, b.fs, b.sources, b.files, []uint32{entryPoint})
resultGroups[i] = c.link()
waitGroup.Done()
}(i, entryPoint)
}
waitGroup.Wait()
// Join the results in entry point order for determinism
var results []OutputFile
for _, group := range resultGroups {
results = append(results, group...)
}
return results
}