Debian Codegraph @

internal/js/esbuild/options.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package esbuild
15
16 import (
17 "encoding/json"
18 "fmt"
19 "maps"
20 "path/filepath"
21 "sort"
22 "strings"
23
24 "github.com/gohugoio/hugo/common/hmaps"
25 "github.com/gohugoio/hugo/common/hugio"
26 "github.com/gohugoio/hugo/common/paths"
27 "github.com/gohugoio/hugo/identity"
28 "github.com/gohugoio/hugo/resources/resource_transformers/tocss/sass"
29
30 "github.com/evanw/esbuild/pkg/api"
31
32 "github.com/gohugoio/hugo/media"
33 "github.com/mitchellh/mapstructure"
34 )
35
36 var (
37 nameTarget = map[string]api.Target{
38 "": api.ESNext,
39 "esnext": api.ESNext,
40 "es5": api.ES5,
41 "es6": api.ES2015,
42 "es2015": api.ES2015,
43 "es2016": api.ES2016,
44 "es2017": api.ES2017,
45 "es2018": api.ES2018,
46 "es2019": api.ES2019,
47 "es2020": api.ES2020,
48 "es2021": api.ES2021,
49 "es2022": api.ES2022,
50 "es2023": api.ES2023,
51 "es2024": api.ES2024,
52 "es2025": api.ES2025,
53 }
54
55 engineName = map[string]api.EngineName{
56 "chrome": api.EngineChrome,
57 "deno": api.EngineDeno,
58 "edge": api.EngineEdge,
59 "firefox": api.EngineFirefox,
60 "hermes": api.EngineHermes,
61 "ie": api.EngineIE,
62 "ios": api.EngineIOS,
63 "node": api.EngineNode,
64 "opera": api.EngineOpera,
65 "rhino": api.EngineRhino,
66 "safari": api.EngineSafari,
67 }
68
69 engineKeysSorted []string
70
71 // source names: https://github.com/evanw/esbuild/blob/9eca46464ed5615cb36a3beb3f7a7b9a8ffbe7cf/internal/config/config.go#L208
72 nameLoader = map[string]api.Loader{
73 "none": api.LoaderNone,
74 "base64": api.LoaderBase64,
75 "binary": api.LoaderBinary,
76 "copy": api.LoaderFile,
77 "css": api.LoaderCSS,
78 "dataurl": api.LoaderDataURL,
79 "default": api.LoaderDefault,
80 "empty": api.LoaderEmpty,
81 "file": api.LoaderFile,
82 "global-css": api.LoaderGlobalCSS,
83 "js": api.LoaderJS,
84 "json": api.LoaderJSON,
85 "jsx": api.LoaderJSX,
86 "local-css": api.LoaderLocalCSS,
87 "text": api.LoaderText,
88 "ts": api.LoaderTS,
89 "tsx": api.LoaderTSX,
90 }
91 )
92
93 func init() {
94 for k := range engineName {
95 engineKeysSorted = append(engineKeysSorted, k)
96 }
97 // Sort by length descending to match longest prefix first.
98 sort.Slice(engineKeysSorted, func(i, j int) bool {
99 return len(engineKeysSorted[i]) > len(engineKeysSorted[j])
100 })
101 }
102
103 // DecodeExternalOptions decodes the given map into ExternalOptions.
104 func DecodeExternalOptions(m map[string]any) (ExternalOptions, error) {
105 opts := ExternalOptions{
106 SourcesContent: true,
107 }
108
109 if err := mapstructure.WeakDecode(m, &opts); err != nil {
110 return opts, err
111 }
112
113 if opts.TargetPath != "" {
114 opts.TargetPath = paths.ToSlashTrimLeading(opts.TargetPath)
115 }
116
117 for i, t := range opts.Target {
118 opts.Target[i] = strings.ToLower(t)
119 }
120 opts.Format = strings.ToLower(opts.Format)
121
122 return opts, nil
123 }
124
125 // ErrorMessageResolved holds a resolved error message.
126 type ErrorMessageResolved struct {
127 Path string
128 Message string
129 Content hugio.ReadSeekCloser
130 }
131
132 // ExternalOptions holds user facing options for the js.Build template function.
133 type ExternalOptions struct {
134 // If not set, the source path will be used as the base target path.
135 // Note that the target path's extension may change if the target MIME type
136 // is different, e.g. when the source is TypeScript.
137 TargetPath string
138
139 // Whether to minify to output.
140 Minify bool
141
142 // One of "inline", "external", "linked" or "none".
143 SourceMap string
144
145 SourcesContent bool
146
147 // This sets the target environment for the generated JavaScript and/or CSS code.
148 // It can specify the JavaScript language version to target (es2015, es2016, es2017, es2018, es2019, es2020 or esnext; default is esnext),
149 // in addition to a set of environments to support, as slice of environment name followed by a version number. e.g. "chrome80", "firefox73", "safari13" or "edge80".
150 // See https://esbuild.github.io/api/#target
151 Target []string
152
153 // The output format.
154 // One of: iife, cjs, esm
155 // Default is to esm.
156 Format string
157
158 // One of browser, node, neutral.
159 // Default is browser.
160 // See https://esbuild.github.io/api/#platform
161 Platform string
162
163 // When you import a package in node, the main field in that package's package.json file
164 // determines which file is imported (along with a lot of other rules).
165 // The default main fields is controlled by ESBuild and depend on the current platform setting.
166 // See https://esbuild.github.io/api/#main-fields
167 MainFields []string
168
169 // External dependencies, e.g. "react".
170 Externals []string
171
172 // This option allows you to automatically replace a global variable with an import from another file.
173 // The filenames must be relative to /assets.
174 // See https://esbuild.github.io/api/#inject
175 Inject []string
176
177 // User defined symbols.
178 Defines map[string]any
179
180 // This tells esbuild to edit your source code before building to drop certain constructs.
181 // See https://esbuild.github.io/api/#drop
182 Drop string
183
184 // Maps a component import to another.
185 Shims map[string]string
186
187 // User provided import context. If set, we will look here first.
188 ImportContext any
189
190 // Configuring a loader for a given file type lets you load that file type with an
191 // import statement or a require call. For example, configuring the .png file extension
192 // to use the data URL loader means importing a .png file gives you a data URL
193 // containing the contents of that image
194 //
195 // See https://esbuild.github.io/api/#loader
196 Loaders map[string]string
197
198 // User defined params. Will be marshaled to JSON and available as "@params", e.g.
199 // import * as params from '@params';
200 Params any
201
202 // What to use instead of React.createElement.
203 JSXFactory string
204
205 // What to use instead of React.Fragment.
206 JSXFragment string
207
208 // What to do about JSX syntax.
209 // See https://esbuild.github.io/api/#jsx
210 JSX string
211
212 // Which library to use to automatically import JSX helper functions from. Only works if JSX is set to automatic.
213 // See https://esbuild.github.io/api/#jsx-import-source
214 JSXImportSource string
215
216 // User defined CSS variables. Will be available as CSS global scope CSS variables via @import "hugo:vars".
217 Vars map[string]any
218
219 // There is/was a bug in WebKit with severe performance issue with the tracking
220 // of TDZ checks in JavaScriptCore.
221 //
222 // Enabling this flag removes the TDZ and `const` assignment checks and
223 // may improve performance of larger JS codebases until the WebKit fix
224 // is in widespread use.
225 //
226 // See https://bugs.webkit.org/show_bug.cgi?id=199866
227 // Deprecated: This no longer have any effect and will be removed.
228 // TODO(bep) remove. See https://github.com/evanw/esbuild/commit/869e8117b499ca1dbfc5b3021938a53ffe934dba
229 AvoidTDZ bool
230 }
231
232 // InternalOptions holds internal options for the js.Build template function.
233 type InternalOptions struct {
234 MediaType media.Type
235 OutDir string
236 Contents string
237 SourceDir string
238 ResolveDir string
239 AbsWorkingDir string
240 Metafile bool
241
242 // Used as a prefix for asset references that go through the file loader.
243 // See https://esbuild.github.io/api/#public-path
244 PublicPath string
245
246 StdinSourcePath string
247
248 DependencyManager identity.Manager
249
250 Stdin bool // Set to true to pass in the entry point as a byte slice.
251 Splitting bool
252 IsCSS bool // Entry point is CSS.
253 TsConfig string
254 EntryPoints []string
255 ImportOnResolveFunc func(string, api.OnResolveArgs) string
256 ImportOnLoadFunc func(api.OnLoadArgs) (string, error)
257 ImportParamsOnLoadFunc func(args api.OnLoadArgs) json.RawMessage
258 ErrorMessageResolveFunc func(api.Message) *ErrorMessageResolved
259 ResolveSourceMapSource func(string) string // Used to resolve paths in error source maps.
260 }
261
262 // Options holds the options passed to Build.
263 type Options struct {
264 ExternalOptions
265 InternalOptions
266
267 compiled api.BuildOptions
268 }
269
270 func (opts *Options) compile() (err error) {
271 var target api.Target
272 for _, value := range opts.Target {
273 if v, found := nameTarget[value]; found {
274 if v > target {
275 target = v
276 }
277 }
278 }
279
280 var engines []api.Engine
281
282 OUTER:
283 for _, value := range opts.Target {
284 for _, engine := range engineKeysSorted {
285 if strings.HasPrefix(value, engine) {
286 version := value[len(engine):]
287 if version == "" {
288 return fmt.Errorf("invalid engine version: %q", value)
289 }
290 engines = append(engines, api.Engine{Name: engineName[engine], Version: version})
291 continue OUTER
292 }
293 }
294 }
295
296 if target == 0 && len(engines) == 0 && len(opts.Target) > 0 {
297 return fmt.Errorf("unsupported target: %v", opts.Target)
298 }
299
300 if target == 0 {
301 target = api.ESNext
302 }
303
304 var loaders map[string]api.Loader
305 if opts.IsCSS {
306 loaders = make(map[string]api.Loader)
307 // Add default CSS file loaders.
308 // May be overridden by opts.Loaders.
309 maps.Copy(loaders, extensionToLoaderMapCSS)
310 }
311 if opts.Loaders != nil {
312 if loaders == nil {
313 loaders = make(map[string]api.Loader)
314 }
315
316 for k, v := range opts.Loaders {
317 loader, found := nameLoader[v]
318 if !found {
319 err = fmt.Errorf("invalid loader: %q", v)
320 return
321 }
322 loaders[k] = loader
323 }
324 }
325
326 mediaType := opts.MediaType
327 if mediaType.IsZero() {
328 mediaType = media.Builtin.JavascriptType
329 }
330
331 var loader api.Loader
332 switch mediaType.SubType {
333 case media.Builtin.JavascriptType.SubType:
334 loader = api.LoaderJS
335 case media.Builtin.TypeScriptType.SubType:
336 loader = api.LoaderTS
337 case media.Builtin.TSXType.SubType:
338 loader = api.LoaderTSX
339 case media.Builtin.JSXType.SubType:
340 loader = api.LoaderJSX
341 case media.Builtin.CSSType.SubType:
342 loader = api.LoaderCSS
343 default:
344 err = fmt.Errorf("unsupported Media Type: %q", opts.MediaType)
345 return
346 }
347
348 var format api.Format
349 // One of: iife, cjs, esm
350 switch opts.Format {
351 case "", "iife":
352 format = api.FormatIIFE
353 case "esm":
354 format = api.FormatESModule
355 case "cjs":
356 format = api.FormatCommonJS
357 default:
358 err = fmt.Errorf("unsupported script output format: %q", opts.Format)
359 return
360 }
361
362 var jsx api.JSX
363 switch opts.JSX {
364 case "", "transform":
365 jsx = api.JSXTransform
366 case "preserve":
367 jsx = api.JSXPreserve
368 case "automatic":
369 jsx = api.JSXAutomatic
370 default:
371 err = fmt.Errorf("unsupported jsx type: %q", opts.JSX)
372 return
373 }
374
375 var platform api.Platform
376 switch opts.Platform {
377 case "", "browser":
378 platform = api.PlatformBrowser
379 case "node":
380 platform = api.PlatformNode
381 case "neutral":
382 platform = api.PlatformNeutral
383 default:
384 err = fmt.Errorf("unsupported platform type: %q", opts.Platform)
385 return
386 }
387
388 var defines map[string]string
389 if opts.Defines != nil {
390 defines = hmaps.ToStringMapString(opts.Defines)
391 }
392
393 var drop api.Drop
394 switch opts.Drop {
395 case "":
396 case "console":
397 drop = api.DropConsole
398 case "debugger":
399 drop = api.DropDebugger
400 default:
401 err = fmt.Errorf("unsupported drop type: %q", opts.Drop)
402 }
403
404 // By default we only need to specify outDir and no outFile
405 outDir := opts.OutDir
406 outFile := ""
407 var sourceMap api.SourceMap
408 switch opts.SourceMap {
409 case "inline":
410 sourceMap = api.SourceMapInline
411 case "external":
412 sourceMap = api.SourceMapExternal
413 case "linked":
414 sourceMap = api.SourceMapLinked
415 case "", "none":
416 sourceMap = api.SourceMapNone
417 default:
418 err = fmt.Errorf("unsupported sourcemap type: %q", opts.SourceMap)
419 return
420 }
421
422 sourcesContent := api.SourcesContentInclude
423 if !opts.SourcesContent {
424 sourcesContent = api.SourcesContentExclude
425 }
426
427 if opts.IsCSS && opts.MainFields == nil {
428 opts.MainFields = []string{"style", "main"}
429 }
430
431 opts.Vars = sass.PrepareVars(opts.Vars)
432
433 opts.compiled = api.BuildOptions{
434 Outfile: outFile,
435 Bundle: true,
436 Metafile: opts.Metafile,
437 AbsWorkingDir: opts.AbsWorkingDir,
438
439 Target: target,
440 Engines: engines,
441 Format: format,
442 MainFields: opts.MainFields,
443 Platform: platform,
444 Sourcemap: sourceMap,
445 SourcesContent: sourcesContent,
446
447 Loader: loaders,
448
449 MinifyWhitespace: opts.Minify,
450 MinifyIdentifiers: opts.Minify,
451 MinifySyntax: opts.Minify,
452
453 Outdir: outDir,
454 PublicPath: opts.PublicPath,
455 Splitting: opts.Splitting,
456
457 Define: defines,
458 External: opts.Externals,
459 Drop: drop,
460
461 JSXFactory: opts.JSXFactory,
462 JSXFragment: opts.JSXFragment,
463
464 JSX: jsx,
465 JSXImportSource: opts.JSXImportSource,
466
467 Tsconfig: opts.TsConfig,
468
469 EntryPoints: opts.EntryPoints,
470 }
471
472 if opts.Stdin {
473 // This makes ESBuild pass `stdin` as the Importer to the import.
474 opts.compiled.Stdin = &api.StdinOptions{
475 Contents: opts.Contents,
476 ResolveDir: opts.ResolveDir,
477 Loader: loader,
478 }
479 }
480 return
481 }
482
483 func (o Options) loaderFromFilename(filename string) api.Loader {
484 ext := filepath.Ext(filename)
485 if optsLoaders := o.compiled.Loader; optsLoaders != nil {
486 if l, found := optsLoaders[ext]; found {
487 return l
488 }
489 }
490 if !o.IsCSS {
491 if l, found := extensionToLoaderMapJS[ext]; found {
492 return l
493 }
494 }
495 return api.LoaderDefault
496 }
497
498 func (opts *Options) validate() error {
499 if opts.ImportOnResolveFunc != nil && opts.ImportOnLoadFunc == nil {
500 return fmt.Errorf("ImportOnLoadFunc must be set if ImportOnResolveFunc is set")
501 }
502 if opts.ImportOnResolveFunc == nil && opts.ImportOnLoadFunc != nil {
503 return fmt.Errorf("ImportOnResolveFunc must be set if ImportOnLoadFunc is set")
504 }
505 if opts.AbsWorkingDir == "" {
506 return fmt.Errorf("AbsWorkingDir must be set")
507 }
508 return nil
509 }