| 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 |
"os" |
| 20 |
"path/filepath" |
| 21 |
"slices" |
| 22 |
"sort" |
| 23 |
"strings" |
| 24 |
|
| 25 |
"github.com/evanw/esbuild/pkg/api" |
| 26 |
"github.com/gohugoio/hugo/common/hmaps" |
| 27 |
"github.com/gohugoio/hugo/common/types/css" |
| 28 |
"github.com/gohugoio/hugo/hugofs" |
| 29 |
"github.com/gohugoio/hugo/identity" |
| 30 |
"github.com/gohugoio/hugo/resources" |
| 31 |
"github.com/gohugoio/hugo/resources/resource" |
| 32 |
"github.com/gohugoio/hugo/resources/resource_transformers/tocss/sass" |
| 33 |
"github.com/spf13/afero" |
| 34 |
) |
| 35 |
|
| 36 |
const ( |
| 37 |
NsHugoImport = "ns-hugo-imp" |
| 38 |
NsHugoImportResolveFunc = "ns-hugo-imp-func" |
| 39 |
nsHugoParams = "ns-hugo-params" |
| 40 |
nsHugoVars = "ns-hugo-vars" |
| 41 |
pathHugoConfigParams = "@params/config" |
| 42 |
|
| 43 |
stdinImporter = "<stdin>" |
| 44 |
) |
| 45 |
|
| 46 |
var hugoNamespaces = []string{NsHugoImport, NsHugoImportResolveFunc, nsHugoParams, nsHugoVars} |
| 47 |
|
| 48 |
const ( |
| 49 |
PrefixHugoVirtual = "__hu_v" |
| 50 |
PrefixHugoMemory = "__hu_m" |
| 51 |
) |
| 52 |
|
| 53 |
var extensionToLoaderMapJS = map[string]api.Loader{ |
| 54 |
".js": api.LoaderJS, |
| 55 |
".mjs": api.LoaderJS, |
| 56 |
".cjs": api.LoaderJS, |
| 57 |
".jsx": api.LoaderJSX, |
| 58 |
".ts": api.LoaderTS, |
| 59 |
".tsx": api.LoaderTSX, |
| 60 |
".json": api.LoaderJSON, |
| 61 |
".txt": api.LoaderText, |
| 62 |
".css": api.LoaderCSS, |
| 63 |
} |
| 64 |
|
| 65 |
var extensionToLoaderMapCSS = map[string]api.Loader{ |
| 66 |
".css": api.LoaderCSS, |
| 67 |
|
| 68 |
// Common static file extensions that should use the file loader in CSS builds. |
| 69 |
".png": api.LoaderFile, |
| 70 |
".jpg": api.LoaderFile, |
| 71 |
".jpeg": api.LoaderFile, |
| 72 |
".gif": api.LoaderFile, |
| 73 |
".svg": api.LoaderFile, |
| 74 |
".webp": api.LoaderFile, |
| 75 |
".avif": api.LoaderFile, |
| 76 |
|
| 77 |
".woff": api.LoaderFile, |
| 78 |
".woff2": api.LoaderFile, |
| 79 |
".ttf": api.LoaderFile, |
| 80 |
".eot": api.LoaderFile, |
| 81 |
".otf": api.LoaderFile, |
| 82 |
} |
| 83 |
|
| 84 |
// This is a common sub-set of ESBuild's default extensions. |
| 85 |
// We assume that imports of JSON, CSS etc. will be using their full |
| 86 |
// name with extension. |
| 87 |
var commonExtensions = []string{".js", ".ts", ".tsx", ".jsx"} |
| 88 |
|
| 89 |
// ResolveComponent resolves a component using the given resolver. |
| 90 |
func ResolveComponent[T any](impPath string, resolve func(string) (v T, found, isDir bool)) (v T, found bool) { |
| 91 |
findFirst := func(base string) (v T, found, isDir bool) { |
| 92 |
for _, ext := range commonExtensions { |
| 93 |
if strings.HasSuffix(impPath, ext) { |
| 94 |
// Import of foo.js.js need the full name. |
| 95 |
continue |
| 96 |
} |
| 97 |
if v, found, isDir = resolve(base + ext); found { |
| 98 |
return |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
// Not found. |
| 103 |
return |
| 104 |
} |
| 105 |
|
| 106 |
// We need to check if this is a regular file imported without an extension. |
| 107 |
// There may be ambiguous situations where both foo.js and foo/index.js exists. |
| 108 |
// This import order is in line with both how Node and ESBuild's native |
| 109 |
// import resolver works. |
| 110 |
|
| 111 |
// It may be a regular file imported without an extension, e.g. |
| 112 |
// foo or foo/index. |
| 113 |
v, found, _ = findFirst(impPath) |
| 114 |
if found { |
| 115 |
return v, found |
| 116 |
} |
| 117 |
|
| 118 |
base := filepath.Base(impPath) |
| 119 |
|
| 120 |
if base == "index" { |
| 121 |
// try index.esm.js etc. |
| 122 |
v, found, _ = findFirst(impPath + ".esm") |
| 123 |
if found { |
| 124 |
return v, found |
| 125 |
} |
| 126 |
} |
| 127 |
|
| 128 |
// Check the path as is. |
| 129 |
var isDir bool |
| 130 |
v, found, isDir = resolve(impPath) |
| 131 |
if found && isDir { |
| 132 |
v, found, _ = findFirst(filepath.Join(impPath, "index")) |
| 133 |
if !found { |
| 134 |
v, found, _ = findFirst(filepath.Join(impPath, "index.esm")) |
| 135 |
} |
| 136 |
} |
| 137 |
|
| 138 |
if !found && strings.HasSuffix(base, ".js") { |
| 139 |
v, found, _ = findFirst(strings.TrimSuffix(impPath, ".js")) |
| 140 |
} |
| 141 |
|
| 142 |
return |
| 143 |
} |
| 144 |
|
| 145 |
// ResolveResource resolves a resource using the given resourceGetter. |
| 146 |
func ResolveResource(impPath string, resourceGetter resource.ResourceGetter) (r resource.Resource) { |
| 147 |
resolve := func(name string) (v resource.Resource, found, isDir bool) { |
| 148 |
r := resourceGetter.Get(name) |
| 149 |
return r, r != nil, false |
| 150 |
} |
| 151 |
r, found := ResolveComponent(impPath, resolve) |
| 152 |
if !found { |
| 153 |
return nil |
| 154 |
} |
| 155 |
return r |
| 156 |
} |
| 157 |
|
| 158 |
func newFSResolver(fs afero.Fs) *fsResolver { |
| 159 |
return &fsResolver{fs: fs, resolved: hmaps.NewCache[string, *hugofs.FileMeta]()} |
| 160 |
} |
| 161 |
|
| 162 |
type fsResolver struct { |
| 163 |
fs afero.Fs |
| 164 |
resolved *hmaps.Cache[string, *hugofs.FileMeta] |
| 165 |
} |
| 166 |
|
| 167 |
func (r *fsResolver) resolveComponent(impPath string, direct bool) *hugofs.FileMeta { |
| 168 |
v, _ := r.resolved.GetOrCreate(impPath, func() (*hugofs.FileMeta, error) { |
| 169 |
resolve := func(name string) (*hugofs.FileMeta, bool, bool) { |
| 170 |
if fi, err := r.fs.Stat(name); err == nil { |
| 171 |
return fi.(hugofs.FileMetaInfo).Meta(), true, fi.IsDir() |
| 172 |
} |
| 173 |
return nil, false, false |
| 174 |
} |
| 175 |
if direct { |
| 176 |
// Only resolve the path as is, without trying to add extensions etc. |
| 177 |
v, found, isDir := resolve(impPath) |
| 178 |
if found && !isDir { |
| 179 |
return v, nil |
| 180 |
} |
| 181 |
return nil, nil |
| 182 |
} |
| 183 |
v, _ := ResolveComponent(impPath, resolve) |
| 184 |
return v, nil |
| 185 |
}) |
| 186 |
return v |
| 187 |
} |
| 188 |
|
| 189 |
func createBuildPlugins(rs *resources.Spec, assetsResolver *fsResolver, depsManager identity.Manager, opts Options) ([]api.Plugin, error) { |
| 190 |
fs := rs.Assets |
| 191 |
|
| 192 |
resolveImport := func(args api.OnResolveArgs) (api.OnResolveResult, error) { |
| 193 |
impPath := args.Path |
| 194 |
isCSSToken := args.Kind == api.ResolveCSSImportRule || args.Kind == api.ResolveCSSURLToken |
| 195 |
|
| 196 |
shimmed := false |
| 197 |
if opts.Shims != nil { |
| 198 |
override, found := opts.Shims[impPath] |
| 199 |
if found { |
| 200 |
impPath = override |
| 201 |
shimmed = true |
| 202 |
} |
| 203 |
} |
| 204 |
|
| 205 |
if slices.Contains(opts.Externals, impPath) { |
| 206 |
return api.OnResolveResult{ |
| 207 |
Path: impPath, |
| 208 |
External: true, |
| 209 |
}, nil |
| 210 |
} |
| 211 |
|
| 212 |
if opts.ImportOnResolveFunc != nil { |
| 213 |
if s := opts.ImportOnResolveFunc(impPath, args); s != "" { |
| 214 |
return api.OnResolveResult{Path: s, Namespace: NsHugoImportResolveFunc}, nil |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
importer := args.Importer |
| 219 |
isStdin := importer == stdinImporter |
| 220 |
var relDir string |
| 221 |
|
| 222 |
if !isStdin { |
| 223 |
if after, ok := strings.CutPrefix(importer, PrefixHugoVirtual); ok { |
| 224 |
relDir = filepath.Dir(after) |
| 225 |
} else { |
| 226 |
rel, found := fs.MakePathRelative(importer, true) |
| 227 |
|
| 228 |
if !found { |
| 229 |
if shimmed { |
| 230 |
relDir = opts.SourceDir |
| 231 |
} else { |
| 232 |
// Not in any of the /assets folders. |
| 233 |
// This is an import from a node_modules, let |
| 234 |
// ESBuild resolve this. |
| 235 |
return api.OnResolveResult{}, nil |
| 236 |
} |
| 237 |
} else { |
| 238 |
relDir = filepath.Dir(rel) |
| 239 |
} |
| 240 |
} |
| 241 |
} else { |
| 242 |
relDir = opts.SourceDir |
| 243 |
} |
| 244 |
|
| 245 |
var pathsToTry []string |
| 246 |
|
| 247 |
if relDir != "" { |
| 248 |
// For JS imports not starting with a "." is assumed to live relative to /assets. |
| 249 |
// Hugo makes no assumptions about the directory structure below /assets. |
| 250 |
if strings.HasPrefix(impPath, ".") { |
| 251 |
pathsToTry = append(pathsToTry, filepath.Join(relDir, impPath)) |
| 252 |
} else if isCSSToken && !strings.HasPrefix(impPath, "/") { |
| 253 |
// Follow the logic of both ESBuild and WebKit for CSS @import and url() tokens. |
| 254 |
// First try the relativ path, then the assets relative path. |
| 255 |
// See https://github.com/evanw/esbuild/issues/469 |
| 256 |
pathsToTry = append(pathsToTry, filepath.Join(relDir, impPath), impPath) |
| 257 |
} else { |
| 258 |
// Try only the assets relative path. |
| 259 |
pathsToTry = append(pathsToTry, impPath) |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
if opts.ImportOnResolveFunc != nil { |
| 264 |
// Relative imports resolved against the importing file's directory, |
| 265 |
// e.g. "./foo.css". The path as written was tried above. |
| 266 |
for _, p := range pathsToTry { |
| 267 |
if p == impPath { |
| 268 |
continue |
| 269 |
} |
| 270 |
if s := opts.ImportOnResolveFunc(filepath.ToSlash(p), args); s != "" { |
| 271 |
return api.OnResolveResult{Path: s, Namespace: NsHugoImportResolveFunc}, nil |
| 272 |
} |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
var m *hugofs.FileMeta |
| 277 |
for _, p := range pathsToTry { |
| 278 |
m = assetsResolver.resolveComponent(p, isCSSToken) |
| 279 |
if m != nil { |
| 280 |
break |
| 281 |
} |
| 282 |
} |
| 283 |
|
| 284 |
if m != nil { |
| 285 |
depsManager.AddIdentity(m.PathInfo) |
| 286 |
|
| 287 |
// jsconfig.json path mapping has no effect for CSS imports, so skip those. |
| 288 |
if !isCSSToken { |
| 289 |
// Store the source root so we can create a jsconfig.json |
| 290 |
// to help IntelliSense when the build is done. |
| 291 |
// This should be a small number of elements, and when |
| 292 |
// in server mode, we may get stale entries on renames etc., |
| 293 |
// but that shouldn't matter too much. |
| 294 |
rs.JSConfigBuilder.AddSourceRoot(m.SourceRoot) |
| 295 |
} |
| 296 |
|
| 297 |
return api.OnResolveResult{Path: m.Filename, Namespace: NsHugoImport}, nil |
| 298 |
} |
| 299 |
|
| 300 |
// Fall back to ESBuild's resolve. |
| 301 |
return api.OnResolveResult{}, nil |
| 302 |
} |
| 303 |
|
| 304 |
importResolver := api.Plugin{ |
| 305 |
Name: "hugo-import-resolver", |
| 306 |
Setup: func(build api.PluginBuild) { |
| 307 |
build.OnResolve(api.OnResolveOptions{Filter: `.*`}, |
| 308 |
func(args api.OnResolveArgs) (api.OnResolveResult, error) { |
| 309 |
return resolveImport(args) |
| 310 |
}) |
| 311 |
// Files not found in /assets are resolved and read by ESBuild, which follows |
| 312 |
// symlinks and knows nothing about the project boundary. |
| 313 |
build.OnLoad(api.OnLoadOptions{Filter: `.*`, Namespace: "file"}, |
| 314 |
func(args api.OnLoadArgs) (api.OnLoadResult, error) { |
| 315 |
if err := rs.ExecHelper.CheckReadPath(args.Path); err != nil { |
| 316 |
return api.OnLoadResult{}, err |
| 317 |
} |
| 318 |
// Let ESBuild load it. |
| 319 |
return api.OnLoadResult{}, nil |
| 320 |
}) |
| 321 |
build.OnLoad(api.OnLoadOptions{Filter: `.*`, Namespace: NsHugoImport}, |
| 322 |
func(args api.OnLoadArgs) (api.OnLoadResult, error) { |
| 323 |
b, err := os.ReadFile(args.Path) |
| 324 |
if err != nil { |
| 325 |
return api.OnLoadResult{}, fmt.Errorf("failed to read %q: %w", args.Path, err) |
| 326 |
} |
| 327 |
c := string(b) |
| 328 |
|
| 329 |
return api.OnLoadResult{ |
| 330 |
// See https://github.com/evanw/esbuild/issues/502 |
| 331 |
// This allows all modules to resolve dependencies |
| 332 |
// in the main project's node_modules. |
| 333 |
ResolveDir: opts.ResolveDir, |
| 334 |
Contents: &c, |
| 335 |
Loader: opts.loaderFromFilename(args.Path), |
| 336 |
}, nil |
| 337 |
}) |
| 338 |
build.OnLoad(api.OnLoadOptions{Filter: `.*`, Namespace: NsHugoImportResolveFunc}, |
| 339 |
func(args api.OnLoadArgs) (api.OnLoadResult, error) { |
| 340 |
c, err := opts.ImportOnLoadFunc(args) |
| 341 |
if err != nil { |
| 342 |
return api.OnLoadResult{}, err |
| 343 |
} |
| 344 |
if c == "" { |
| 345 |
return api.OnLoadResult{}, fmt.Errorf("ImportOnLoadFunc failed to resolve %q", args.Path) |
| 346 |
} |
| 347 |
|
| 348 |
return api.OnLoadResult{ |
| 349 |
ResolveDir: opts.ResolveDir, |
| 350 |
Contents: &c, |
| 351 |
Loader: opts.loaderFromFilename(args.Path), |
| 352 |
}, nil |
| 353 |
}) |
| 354 |
}, |
| 355 |
} |
| 356 |
|
| 357 |
params := opts.Params |
| 358 |
if params == nil { |
| 359 |
// This way @params will always resolve to something. |
| 360 |
params = make(map[string]any) |
| 361 |
} |
| 362 |
|
| 363 |
b, err := json.Marshal(params) |
| 364 |
if err != nil { |
| 365 |
return nil, fmt.Errorf("failed to marshal params: %w", err) |
| 366 |
} |
| 367 |
|
| 368 |
paramsPlugin := api.Plugin{ |
| 369 |
Name: "hugo-params-plugin", |
| 370 |
Setup: func(build api.PluginBuild) { |
| 371 |
build.OnResolve(api.OnResolveOptions{Filter: `^@params(/config)?$`}, |
| 372 |
func(args api.OnResolveArgs) (api.OnResolveResult, error) { |
| 373 |
resolvedPath := args.Importer |
| 374 |
|
| 375 |
if args.Path == pathHugoConfigParams { |
| 376 |
resolvedPath = pathHugoConfigParams |
| 377 |
} |
| 378 |
|
| 379 |
return api.OnResolveResult{ |
| 380 |
Path: resolvedPath, |
| 381 |
Namespace: nsHugoParams, |
| 382 |
}, nil |
| 383 |
}) |
| 384 |
build.OnLoad(api.OnLoadOptions{Filter: `.*`, Namespace: nsHugoParams}, |
| 385 |
func(args api.OnLoadArgs) (api.OnLoadResult, error) { |
| 386 |
bb := b |
| 387 |
if args.Path != pathHugoConfigParams && opts.ImportParamsOnLoadFunc != nil { |
| 388 |
bb = opts.ImportParamsOnLoadFunc(args) |
| 389 |
} |
| 390 |
s := string(bb) |
| 391 |
|
| 392 |
if s == "" { |
| 393 |
s = "{}" |
| 394 |
} |
| 395 |
|
| 396 |
return api.OnLoadResult{ |
| 397 |
Contents: &s, |
| 398 |
Loader: api.LoaderJSON, |
| 399 |
}, nil |
| 400 |
}) |
| 401 |
}, |
| 402 |
} |
| 403 |
|
| 404 |
varsPlugin := api.Plugin{ |
| 405 |
Name: "hugo-vars-plugin", |
| 406 |
Setup: func(build api.PluginBuild) { |
| 407 |
build.OnResolve(api.OnResolveOptions{Filter: `^hugo:vars(/|$)`}, |
| 408 |
func(args api.OnResolveArgs) (api.OnResolveResult, error) { |
| 409 |
return api.OnResolveResult{ |
| 410 |
Path: args.Path, |
| 411 |
Namespace: nsHugoVars, |
| 412 |
}, nil |
| 413 |
}) |
| 414 |
build.OnLoad(api.OnLoadOptions{Filter: `.*`, Namespace: nsHugoVars}, |
| 415 |
func(args api.OnLoadArgs) (api.OnLoadResult, error) { |
| 416 |
subPath, _ := sass.HugoVarsSubPath(args.Path) |
| 417 |
return api.OnLoadResult{ |
| 418 |
Contents: createCSSVarsStyleSheet(opts.Vars, subPath), |
| 419 |
Loader: api.LoaderCSS, |
| 420 |
}, nil |
| 421 |
}) |
| 422 |
}, |
| 423 |
} |
| 424 |
|
| 425 |
return []api.Plugin{importResolver, paramsPlugin, varsPlugin}, nil |
| 426 |
} |
| 427 |
|
| 428 |
// createCSSVarsStyleSheet creates a CSS custom properties stylesheet from the given vars. |
| 429 |
// The result is a :root block with CSS custom properties. If subPath is non-empty, |
| 430 |
// vars is navigated using the slash-separated path before emitting properties; nested |
| 431 |
// map values are skipped at the resolved level. |
| 432 |
func createCSSVarsStyleSheet(vars map[string]any, subPath string) *string { |
| 433 |
resolved := sass.ResolveVars(vars, subPath) |
| 434 |
if len(resolved) == 0 { |
| 435 |
// We need to return a non-nil pointer to an empty string to avoid ESBuild treating this as a missing file. |
| 436 |
s := "" |
| 437 |
return &s |
| 438 |
} |
| 439 |
|
| 440 |
var varsSlice []string |
| 441 |
for k, v := range resolved { |
| 442 |
if !strings.HasPrefix(k, "--") { |
| 443 |
k = "--" + k |
| 444 |
} |
| 445 |
|
| 446 |
switch v.(type) { |
| 447 |
case css.QuotedString: |
| 448 |
// E.g. Arial, sans-serif. |
| 449 |
varsSlice = append(varsSlice, fmt.Sprintf(" %s: %q;", k, v)) |
| 450 |
default: |
| 451 |
varsSlice = append(varsSlice, fmt.Sprintf(" %s: %v;", k, v)) |
| 452 |
} |
| 453 |
} |
| 454 |
sort.Strings(varsSlice) |
| 455 |
s := ":root {\n" + strings.Join(varsSlice, "\n") + "\n}\n" |
| 456 |
|
| 457 |
return &s |
| 458 |
} |