Backtestshugorun-20261009-153657#15103

Issue #15103 Merged fix PR #15156 Run 9 Oct 2026 · run-20261009-153657 gohugoio/hugo

Add importContext to resources.Copy

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

The issue asks for `resources.Copy` to accept `[STRING or MAP] RESOURCE` with `targetPath` and `importContext` keys. The stored import context should then be honored by css.Build, js.Build/Batch, css.Sass and TailwindCSS.

Patch B implements exactly that design:
- `Namespace.Copy` accepts a string or an options map, with case-insensitive keys, unknown-key errors, and `targetPath` defaulting to the resource's own path.
- The `ImportContext` lives in an unexported field on `genericResource`, read through `InternalResourceImportContext`, which follows the `resources.Internal*` pattern the issue suggests.
- The context is included in `TransformationKey` and the copy cache key. The key covers content hashes, so two `FromString` resources with the same name but different content stay distinct.
- It flows into `ResourceTransformationCtx`, so every transformer picks it up: esbuild (css.Build/js.Build), js.Batch with fallback precedence, the PostCSS/Tailwind inline importer, Dart Sass and LibSass. Node_modules imports are correctly excluded.
- Tests cover the issue's exact scenario (`@import "foo.css" screen`), mounts, Page contexts with rebuild, same-name/different-content caching, Sass (nested relative imports), js.Batch precedence, option-validation errors, and unit tests for the resolvers. Docs are updated.

Patch A does not touch `resources.Copy` at all. It adds `importContext` as a per-transformer option (css.Build/js.Build opts, Sass opts, PostCSS/Tailwind InlineImports), which is not the API the issue requests. It also brings significant risky churn:
- It bumps the hashstructure dependency to a new major version.
- It rewrites global hashing (`UnwrapFunc` replacing `toHashable`), which affects every hash in Hugo.
- It removes `pageState.Key` and adds `pageOutput.Key`.
- It changes the `Color` hashing method and the `Resources.Mount` implementation.
- It removes func support from `unwrapResourceGetter`.
- It adds a new `testinginternal` template namespace.

Its hash-pinning test asserts exact magic numbers, which is brittle. The js.Build import context is only consulted through the relative-path fallback added in resolve.go, which looks fragile.

B matches the requested design, is broader in transformer coverage, and is better tested with less unrelated risk.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

1h 16m

Wall-clock time in the container

Full test suite

No new failures

3,696 passed · 100 skipped · 3,805 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

1,273vs 791 merged

Changed lines, ours vs merged

The example below (and variations of it) isn't possible in Hugo:

{{ $r := resources.FromString "foo.css" "body { color: blue; }" }}
{{/* How do I get $r to resolve as an import in main.css?  */}}
{{ $css := resources.Get "css/main.css" | css.Build }}

And in assets/css/main.js:

@import "foo.css" screen;
@import "bar.css" print;

The example above uses css.Build, but this is also relevant for (at least) css.Sass, js.Build and js.Batch. There are more or less ugly workardounds for the above (e.g. resources.Concat or passing in css vars in a map), but it would be nice to have a direct way that worked for all (I have a new proposal in mind that would need this).

I suggest we add importContext to resources.Copy and make the logic that's currently implemented in js.Batch also work for the other relevant funcs, e.g:

{{ $foo := resources.FromString "foo.css" "body { color: blue; }" }}
{{ $bar := resources.FromString "bar.css" "body { color: green; }" }}
{{ $main := resources.Get "css/main.css" | resources.Copy (dict "importContext" (slice $foo $bar)) }}
{{ $css := $main | css.Build }}

The current signature of resources.Copy is:

resources.Copy TARGETPATH RESOURCE

I suggest we

resources.Copy [STRING or MAP] RESOURCE

And make it optional (we can determine a path from RESOURCE). So for the MAP options it would look like:

{{ $opts := dict
   "targetPath" "foo.css"
   "importContext" (slice $foo $bar)
}}

In the above importContext is the same as described in inputContext -- which also allows constructs ala:

{{ $common := resources.Match "/js/headlessui/*.*" }}
{{ $importContext := (slice $.Page ($common.Mount "/js/headlessui" ".")) }}
{{ $opts := dict
   "importContext" $importContext
}}

Some implementation hints:

  • We would store this new importContext in some unexported field. I suggest we follow the pattern in the funcs resources.Internal* to access this internal state.
  • js.Batch takes importContext as an option. That import handling is more advanced than we need here, but we look at that for inspiriation/reuse.
  • I suggest that we start with css.Build and, once that looks good, implement it in js.Build/Batch, css.Sass and css.TailwindCSS.

The two patches

Our patch+1258 −15
docs/content/en/functions/resources/Copy.mdindex 208f6d65f..5e20d5ad6 100644@@ -6,7 +6,7 @@ params:   functions_and_methods:     aliases: []     returnType: resource.Resource-    signatures: [resources.Copy TARGETPATH RESOURCE]+    signatures: ['resources.Copy TARGETPATH RESOURCE', 'resources.Copy OPTIONS RESOURCE'] ---  ```go-html-template@@ -21,3 +21,32 @@ The `TARGETPATH` is relative to the server root. A leading slash is optional and  > [!NOTE] > Use the `resources.Copy` function with global, page, and remote resources.++## Options++Instead of a target path, you can pass an options map as the first argument:++targetPath+: (`string`) The target path of the copy. Defaults to the target path of the given resource.++importContext+: (`resource`, `resources`, `page`, or `slice`) Additional resources used to resolve imports when transforming the copy with [`css.Build`], [`js.Build`], [`js.Batch`], [`css.Sass`], [`css.PostCSS`] (with `inlineImports` enabled), or [`css.TailwindCSS`]. The import context is checked before the `assets` directory. This can be a resource, a slice of resources, a page (resolves the page's resources), the result of the `Mount` method on a slice of resources, or a slice of any of these. Imports from files in `node_modules` are not resolved using the import context.++For example, to resolve `@import "foo.css";` and `@import "bar.css";` in `assets/css/main.css` using resources created with [`resources.FromString`]:++```go-html-template+{{ $foo := resources.FromString "foo.css" "body { color: blue; }" }}+{{ $bar := resources.FromString "bar.css" "body { color: green; }" }}+{{ $opts := dict "importContext" (slice $foo $bar) }}+{{ with resources.Get "css/main.css" | resources.Copy $opts | css.Build }}+  <link rel="stylesheet" href="{{ .RelPermalink }}">+{{ end }}+```++[`css.Build`]: /functions/css/build/+[`js.Build`]: /functions/js/build/+[`js.Batch`]: /functions/js/batch/+[`css.Sass`]: /functions/css/sass/+[`css.PostCSS`]: /functions/css/postcss/+[`css.TailwindCSS`]: /functions/css/tailwindcss/+[`resources.FromString`]: /functions/resources/fromstring/internal/js/esbuild/batch.goindex 61c6b6d5c..aeb874ba9 100644@@ -1328,17 +1328,23 @@ func (s scriptOptions) compileOptions(m map[string]any, defaults defaultOptionVa 		v.Export = defaults.defaultExport 	} +	if v.Resource == nil {+		return scriptOptions{}, fmt.Errorf("resource not set")+	}++	importContexts := []any{v.ImportContext}+	if ic := resources.InternalResourceImportContext(v.Resource); ic != nil {+		// Fall back to the import context set on the resource itself (e.g. via resources.Copy).+		importContexts = append(importContexts, ic.Getter)+	}+ 	compiled := scriptOptions{ 		Resource:      v.Resource, 		Export:        v.Export,-		ImportContext: resource.NewCachedResourceGetter(v.ImportContext),+		ImportContext: resource.NewCachedResourceGetter(importContexts...), 		Params:        paramsJSON, 	} -	if compiled.Resource == nil {-		return scriptOptions{}, fmt.Errorf("resource not set")-	}- 	return compiled, nil } internal/js/esbuild/batch_integration_test.goindex ca85cb4a7..3fdbe1d22 100644@@ -733,3 +733,112 @@ console.log("config.params.id", id3); 	b.EditFileReplaceAll("assets/other/bar.css", ".bar-edit {", ".bar-edit2 {").Build() 	b.AssertFileContent("public/mybundle/reactbatch.css", ".bar-edit2 {") }++func TestBatchImportContextFromResourcesCopy(t *testing.T) {+	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "section", "page", "rss", "sitemap"]+disableLiveReload = true+-- assets/js/main.js --+import { hello } from "hello";+import { other } from "other";+console.log(hello, other);+-- assets/js/other.js --+export const other = "other-from-assets";+-- assets/js/hello.js --+export const hello = "hello-from-assets";+-- layouts/home.html --+Home.+{{ with (templates.Defer (dict "key" "global")) }}+{{ $batch := (js.Batch "mybatch") }}+{{ range $k, $v := $batch.Build.Groups }}+	{{ range $kk, $vv := . -}}+		{{ $k }}: {{ .RelPermalink }}+	{{ end }}+{{ end -}}+{{ end }}+{{ $hello := resources.FromString "hello.js" "export const hello = \"hello-from-copy-context\";" }}+{{ $other := resources.FromString "other.js" "export const other = \"other-from-script-context\";" }}+{{ $main := resources.Get "js/main.js" | resources.Copy (dict "importContext" (slice $hello $other)) }}+{{ $scriptContext := resources.FromString "ctx/other.js" "export const other = \"other-from-script-option\";" }}+{{ $batch := (js.Batch "mybatch") }}+{{ with $batch.Group "mygroup" }}+	{{ with .Script "main" }}+		{{ .SetOptions (dict "resource" $main "importContext" ((slice $scriptContext).Mount "/ctx" ".")) }}+	{{ end }}+{{ end }}+`+	b := hugolib.Test(t, files, hugolib.TestOptWithOSFs())++	b.AssertFileContent("public/mybatch/mygroup.js",+		"hello-from-copy-context",+		// The script's own importContext option takes precedence.+		"other-from-script-option",+		"! other-from-script-context",+		"! hello-from-assets",+		"! other-from-assets",+	)+}++func TestJSBuildImportContextFromResourcesCopy(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "section", "page", "rss", "sitemap"]+disableLiveReload = true+-- assets/js/main.js --+import { hello } from "hello";+import { nested } from "./nested";+import { mylib } from "mylib";+console.log(hello, nested, mylib);+-- assets/js/nested.js --+import { foo } from "foo";+export const nested = "nested-" + foo;+-- assets/js/foo.js --+export const foo = "foo-from-assets";+-- node_modules/mylib/index.js --+import { foo } from "foo";+export const mylib = "mylib-" + foo;+-- node_modules/foo/index.js --+export const foo = "foo-from-node-modules";+-- layouts/home.html --+{{ $hello := resources.FromString "hello.js" "export const hello = \"hello-from-context\";" }}+{{ $foo := resources.FromString "foo.js" "export const foo = \"foo-from-context\";" }}+{{ $main := resources.Get "js/main.js" | resources.Copy (dict "targetPath" "js/main-copy.js" "importContext" (slice $hello $foo)) }}+{{ with $main | js.Build }}{{ .RelPermalink }}|{{ end }}+`+	b := hugolib.Test(t, files, hugolib.TestOptWithOSFs())++	b.AssertFileContent("public/index.html", "/js/main-copy.js|")+	b.AssertFileContent("public/js/main-copy.js",+		"hello-from-context",+		"nested-",+		"foo-from-context",+		"! foo-from-assets",+		// Imports from node_modules are not resolved using the import context.+		"foo-from-node-modules",+	)+}++func TestJSBuildImportContextRebuild(t *testing.T) {+	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "section", "page", "rss", "sitemap"]+disableLiveReload = true+-- assets/js/main.js --+import { hello } from "hello";+console.log(hello);+-- assets/ctx/hello.js --+export const hello = "hello-v1";+-- layouts/home.html --+{{ $ctx := (resources.Match "ctx/*.js").Mount "/ctx" "." }}+{{ $main := resources.Get "js/main.js" | resources.Copy (dict "importContext" $ctx) }}+{{ with $main | js.Build }}{{ .RelPermalink }}|{{ end }}+`+	b := hugolib.TestRunning(t, files, hugolib.TestOptWithOSFs())++	b.AssertFileContent("public/js/main.js", "hello-v1")+	b.EditFileReplaceAll("assets/ctx/hello.js", "hello-v1", "hello-v2").Build()+	b.AssertFileContent("public/js/main.js", "hello-v2")+}internal/js/esbuild/importcontext.gonew file mode 100644index 000000000..926436a8a@@ -0,0 +1,111 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package esbuild++import (+	"context"+	"fmt"+	"strings"++	"github.com/evanw/esbuild/pkg/api"+	"github.com/gohugoio/hugo/common/hmaps"+	"github.com/gohugoio/hugo/common/hugio"+	"github.com/gohugoio/hugo/identity"+	"github.com/gohugoio/hugo/resources"+	"github.com/gohugoio/hugo/resources/resource"+)++// SetImportContext configures opts to resolve imports using the given import context+// (e.g. set via resources.Copy) before falling back to the regular /assets resolution.+// Imports in node_modules are not resolved using the import context.+func (opts *Options) SetImportContext(ctx context.Context, importContext resource.ResourceGetter, dm identity.Manager) {+	if importContext == nil {+		return+	}+	if dm == nil {+		dm = identity.NopManager+	}+	if ctx == nil {+		ctx = context.Background()+	}++	imported := hmaps.NewCache[string, resource.Resource]()++	opts.ImportOnResolveFunc = func(imp string, args api.OnResolveArgs) string {+		if r, found := imported.Get(imp); found {+			dm.AddIdentity(identity.FirstIdentity(r))+			return imp+		}++		switch {+		case args.Kind == api.ResolveEntryPoint:+		case args.Importer == stdinImporter:+		case args.Namespace == NsHugoImport, args.Namespace == NsHugoImportResolveFunc:+		default:+			// E.g. an import from node_modules.+			return ""+		}++		resolved := ResolveResource(imp, importContext)+		if resolved == nil {+			return ""+		}+		dm.AddIdentity(identity.FirstIdentity(resolved))+		resolvePath := PrefixHugoVirtual + resources.InternalResourceTargetPath(resolved)+		imported.Set(resolvePath, resolved)+		return resolvePath+	}++	opts.ImportOnLoadFunc = func(args api.OnLoadArgs) (string, error) {+		r, found := imported.Get(args.Path)+		if !found {+			return "", nil+		}+		content, err := resources.InternalResourceSourceContent(ctx, r)+		if err != nil {+			return "", fmt.Errorf("failed to read import %q: %w", resources.InternalResourceSourcePathBestEffort(r), err)+		}+		return content, nil+	}++	opts.ErrorMessageResolveFunc = func(msg api.Message) *ErrorMessageResolved {+		loc := msg.Location+		if loc == nil {+			return nil+		}+		r, found := imported.Get(strings.TrimPrefix(loc.File, NsHugoImportResolveFunc+":"))+		if !found {+			return nil+		}+		var contentr hugio.ReadSeekCloser+		if cp, ok := r.(hugio.ReadSeekCloserProvider); ok {+			contentr, _ = cp.ReadSeekCloser()+		}+		return &ErrorMessageResolved{+			Content: contentr,+			Path:    resources.InternalResourceSourcePathBestEffort(r),+			Message: msg.Text,+		}+	}++	opts.ResolveSourceMapSource = func(s string) string {+		if r, found := imported.Get(s); found {+			if ss := resources.InternalResourceSourcePath(r); ss != "" {+				return ss+			}+			return PrefixHugoMemory + s+		}+		return ""+	}+}resources/import_context.gonew file mode 100644index 000000000..10ad9eff8@@ -0,0 +1,135 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package resources++import (+	"errors"+	"fmt"+	"reflect"++	"github.com/gohugoio/hugo/common/hashing"+	"github.com/gohugoio/hugo/common/hreflect"+	"github.com/gohugoio/hugo/resources/resource"+)++// ImportContext is a set of resources used to resolve imports+// (e.g. CSS @import, JS import, Sass @use) in resource transformations+// such as css.Build, js.Build, js.Batch and css.Sass.+type ImportContext struct {+	// Getter resolves imports by name.+	Getter resource.ResourceGetter++	// key identifies this import context, used in cache keys.+	key string+}++// Key returns a key identifying this import context.+func (ic *ImportContext) Key() string {+	return ic.key+}++// NewImportContext creates a new ImportContext from v,+// which can be a Resource, Resources, a ResourceGetter (e.g. the result of Resources.Mount),+// something that provides Resources (e.g. a Page) or a slice of any of these.+func NewImportContext(v any) (*ImportContext, error) {+	if v == nil {+		return nil, errors.New("importContext must be set")+	}+	getter := resource.NewCachedResourceGetter(v)+	if !getter.HasDelegates() {+		return nil, fmt.Errorf("importContext: %T is not a valid import context; expected a Resource, Resources, a Page or a slice of these", v)+	}++	return &ImportContext{+		Getter: getter,+		key:    hashing.HashString(importContextKeyParts(v)),+	}, nil+}++// importContextKeyParts returns a hashable representation of v that+// identifies the resources in it.+func importContextKeyParts(v any) any {+	switch vv := v.(type) {+	case nil:+		return nil+	case resource.Resources:+		parts := make([]any, len(vv))+		for i, r := range vv {+			parts[i] = importContextKeyParts(r)+		}+		return parts+	case resource.ResourcesProvider:+		var self any+		if id, ok := v.(resource.Identifier); ok {+			self = id.Key()+		}+		return []any{self, importContextKeyParts(vv.Resources())}+	case resource.Identifier:+		// The key is not unique for resources with the same name but different content,+		// e.g. two resources.FromString "foo.css" with different content.+		if h, ok := importContextContentHash(v); ok {+			return []any{vv.Key(), h}+		}+		return vv.Key()+	case string:+		return vv+	}++	if items, ok := hreflect.ToSliceAny(v); ok {+		parts := make([]any, len(items))+		for i, item := range items {+			parts[i] = importContextKeyParts(item)+		}+		return parts+	}++	// Fall back to the identity of the value, e.g. a func.+	rv := reflect.ValueOf(v)+	switch rv.Kind() {+	case reflect.Func, reflect.Pointer, reflect.Map, reflect.Chan, reflect.UnsafePointer:+		return fmt.Sprintf("%T:%d", v, rv.Pointer())+	}+	return fmt.Sprintf("%T:%v", v, v)+}++// importContextContentHash returns the content hash of v if v is a resource.+func importContextContentHash(v any) (uint64, bool) {+	switch vv := v.(type) {+	case *resourceAdapter:+		vv.init(false, false)+		return vv.target.hash(), true+	case hashProvider:+		return vv.hash(), true+	}+	return 0, false+}++// importContextProvider is implemented by resources that may carry an ImportContext.+type importContextProvider interface {+	getImportContext() *ImportContext+}++// importContextSetter is implemented by resources that may carry an ImportContext.+type importContextSetter interface {+	setImportContext(*ImportContext)+}++// InternalResourceImportContext is used internally to get the import context set+// on a Resource (e.g. via resources.Copy), nil if not set.+func InternalResourceImportContext(r resource.Resource) *ImportContext {+	if p, ok := r.(importContextProvider); ok {+		return p.getImportContext()+	}+	return nil+}resources/resource.goindex cf6e1e597..9869e4af0 100644@@ -230,6 +230,25 @@ func Copy(r resource.Resource, targetPath string) resource.Resource { 	return r.(resourceCopier).cloneTo(targetPath) } +// CopyWithImportContext copies r to the targetPath given and sets the import context+// to use when resolving imports in transformations of the copy (e.g. css.Build).+// If importContext is nil, the import context of r (if any) is preserved.+func CopyWithImportContext(r resource.Resource, targetPath string, importContext *ImportContext) (resource.Resource, error) {+	rc, ok := r.(resourceCopier)+	if !ok {+		return nil, fmt.Errorf("%T can not be copied", r)+	}+	c := rc.cloneTo(targetPath)+	if importContext != nil {+		s, ok := c.(importContextSetter)+		if !ok {+			return nil, fmt.Errorf("%T does not support importContext", r)+		}+		s.setImportContext(importContext)+	}+	return c, nil+}+ type baseResourceResource interface { 	resource.Cloner 	resourceCopier@@ -259,6 +278,9 @@ type baseResourceInternal interface {  	getResourcePaths() internal.ResourcePaths +	importContextProvider+	importContextSetter+ 	specProvider 	openPublishFileForWriting(relTargetPath string) (io.WriteCloser, error) }@@ -379,9 +401,21 @@ type genericResource struct { 	name   string 	params map[string]any +	// Used to resolve imports in transformations, e.g. css.Build.+	// Set via resources.Copy.+	importContext *ImportContext+ 	spec *Spec } +func (l *genericResource) getImportContext() *ImportContext {+	return l.importContext+}++func (l *genericResource) setImportContext(ic *ImportContext) {+	l.importContext = ic+}+ func (l *genericResource) IdentifierBase() string { 	return l.sd.Path.IdentifierBase() }resources/resource/resources.goindex 28fbab42f..ceccf8ae4 100644@@ -37,6 +37,47 @@ type Resources []Resource // Note that leading slashes in target marks an absolute path. // This method is currently only useful in js.Batch. func (r Resources) Mount(base, target string) ResourceGetter {+	return mountedResources{+		base:   base,+		target: target,+		r:      r,+		get:    r.mountGetFunc(base, target),+	}+}++var _ Identifier = mountedResources{}++// mountedResources is the ResourceGetter returned from Resources.Mount.+type mountedResources struct {+	base   string+	target string+	r      Resources+	get    resourceGetterFunc+}++func (m mountedResources) Get(name any) Resource {+	return m.get(name)+}++// Key is for internal use and identifies the mounted resource set.+func (m mountedResources) Key() string {+	var sb strings.Builder+	sb.WriteString("mount:")+	sb.WriteString(m.base)+	sb.WriteString(":")+	sb.WriteString(m.target)+	for _, res := range m.r {+		sb.WriteString(":")+		if id, ok := res.(Identifier); ok {+			sb.WriteString(id.Key())+		} else {+			sb.WriteString(res.Name())+		}+	}+	return sb.String()+}++func (r Resources) mountGetFunc(base, target string) resourceGetterFunc { 	return resourceGetterFunc(func(namev any) Resource { 		name1, err := cast.ToStringE(namev) 		if err != nil {@@ -368,6 +409,12 @@ func (c *cachedResourceGetter) Get(name any) Resource { 	return v } +// HasDelegates reports whether any ResourceGetter could be created from the input objects.+func (c *cachedResourceGetter) HasDelegates() bool {+	m, ok := c.delegate.(multiResourceGetter)+	return !ok || len(m) > 0+}+ func (c *cachedResourceGetter) IsProbablySameResourceGetter(other ResourceGetter) bool { 	isProbablyEq := true 	c.cache.ForEeach(func(k string, v Resource) bool {@@ -390,6 +437,9 @@ func unwrapResourceGetter(v any) (ResourceGetter, bool) { 		return vv, true 	case ResourcesProvider: 		return vv.Resources(), true+	case Resource:+		// A single resource, e.g. one created by resources.FromString.+		return Resources{vv}, true 	case func(name any) Resource: 		return resourceGetterFunc(vv), true 	default:resources/resource_factories/create/create.goindex 4a4d14da6..765559021 100644@@ -154,6 +154,18 @@ func (c *Client) Copy(r resource.Resource, targetPath string) (resource.Resource 	}) } +// CopyWithImportContext copies r to the new targetPath and sets the import context+// used to resolve imports in transformations of the copy (e.g. css.Build).+func (c *Client) CopyWithImportContext(r resource.Resource, targetPath string, importContext *resources.ImportContext) (resource.Resource, error) {+	if importContext == nil {+		return c.Copy(r, targetPath)+	}+	key := dynacache.CleanKey(targetPath) + "_" + importContext.Key() + "__copy"+	return c.rs.ResourceCache.GetOrCreate(key, func() (resource.Resource, error) {+		return resources.CopyWithImportContext(r, targetPath, importContext)+	})+}+ // Get creates a new Resource by opening the given pathname in the assets filesystem. func (c *Client) Get(pathname string) (resource.Resource, error) { 	pathname = path.Clean(pathname)resources/resource_transformers/cssjs/inline_imports.goindex 44ae4b3c6..0690836ac 100644@@ -14,6 +14,7 @@ package cssjs  import (+	"context" 	"crypto/sha256" 	"encoding/hex" 	"errors"@@ -30,6 +31,7 @@ import ( 	"github.com/gohugoio/hugo/common/text" 	"github.com/gohugoio/hugo/hugofs" 	"github.com/gohugoio/hugo/identity"+	"github.com/gohugoio/hugo/resources" 	"github.com/spf13/afero" ) @@ -55,6 +57,50 @@ type importResolver struct { 	linemap           map[int]fileOffset 	fs                afero.Fs 	logger            loggers.Logger++	// Optional import context (e.g. set via resources.Copy), checked before fs.+	ctx           context.Context+	importContext *resources.ImportContext+}++// setImportContext sets the import context to resolve imports from before checking the file system.+func (imp *importResolver) setImportContext(ctx context.Context, ic *resources.ImportContext) *importResolver {+	if ctx == nil {+		ctx = context.Background()+	}+	imp.ctx = ctx+	imp.importContext = ic+	return imp+}++// importContextLinePrefix marks imports resolved from the import context in the line map.+const importContextLinePrefix = "importcontext:"++// resolveImportContext resolves the import path p, imported from inPath, in the import context.+// It returns the path of the resolved resource and its content, or an empty path if not found.+func (imp *importResolver) resolveImportContext(inPath, p string) (string, []byte, error) {+	if imp.importContext == nil {+		return "", nil, nil+	}+	var candidates []string+	if importerPath, ok := strings.CutPrefix(inPath, importContextLinePrefix); ok && !strings.HasPrefix(p, "/") {+		candidates = append(candidates, path.Join(path.Dir(importerPath), p))+	}+	candidates = append(candidates, p)++	for _, candidate := range candidates {+		r := imp.importContext.Getter.Get(candidate)+		if r == nil {+			continue+		}+		content, err := resources.InternalResourceSourceContent(imp.ctx, r)+		if err != nil {+			return "", nil, fmt.Errorf("failed to read import %q: %w", resources.InternalResourceSourcePathBestEffort(r), err)+		}+		imp.dependencyManager.AddIdentity(identity.FirstIdentity(r))+		return path.Join("/", strings.TrimPrefix(candidate, "./")), []byte(content), nil+	}+	return "", nil, nil }  func newImportResolver(r io.Reader, inPath string, opts InlineImports, fs afero.Fs, logger loggers.Logger, dependencyManager identity.Manager) *importResolver {@@ -73,9 +119,13 @@ func (imp *importResolver) contentHash(filename string) ([]byte, string) { 	if err != nil { 		return nil, "" 	}+	return b, contentHash(b)+}++func contentHash(b []byte) string { 	h := sha256.New() 	h.Write(b)-	return b, hex.EncodeToString(h.Sum(nil))+	return hex.EncodeToString(h.Sum(nil)) }  func (imp *importResolver) importRecursive(@@ -84,6 +134,10 @@ func (imp *importResolver) importRecursive( 	inPath string, ) (int, string, error) { 	basePath := path.Dir(inPath)+	if importerPath, ok := strings.CutPrefix(inPath, importContextLinePrefix); ok {+		// Imported from the import context, resolve file imports relative to /assets.+		basePath = strings.TrimPrefix(path.Dir(importerPath), "/")+	}  	var replacements []string 	lines := strings.Split(content, "\n")@@ -104,9 +158,25 @@ func (imp *importResolver) importRecursive( 			trackLine(i, offset, line) 		} else { 			path := strings.Trim(strings.TrimPrefix(line, importIdentifier), " \"';")-			filename := filepath.Join(basePath, path)-			imp.dependencyManager.AddIdentity(identity.CleanStringIdentity(filename))-			importContent, hash := imp.contentHash(filename)++			var (+				filename      string+				importContent []byte+				hash          string+			)++			icPath, icContent, err := imp.resolveImportContext(inPath, path)+			if err != nil {+				return 0, "", err+			}+			if icPath != "" {+				filename = importContextLinePrefix + icPath+				importContent, hash = icContent, contentHash(icContent)+			} else {+				filename = filepath.Join(basePath, path)+				imp.dependencyManager.AddIdentity(identity.CleanStringIdentity(filename))+				importContent, hash = imp.contentHash(filename)+			}  			if importContent == nil { 				if imp.opts.SkipInlineImportsNotFound {resources/resource_transformers/cssjs/inline_imports_test.goindex 3578e2612..78f571673 100644@@ -14,6 +14,7 @@ package cssjs  import (+	"context" 	"regexp" 	"strings" 	"testing"@@ -21,6 +22,8 @@ import ( 	"github.com/gohugoio/hugo/common/loggers" 	"github.com/gohugoio/hugo/htesting/hqt" 	"github.com/gohugoio/hugo/identity"+	"github.com/gohugoio/hugo/resources"+	"github.com/gohugoio/hugo/resources/resource"  	"github.com/gohugoio/hugo/helpers" @@ -177,3 +180,68 @@ LOCAL_STYLE  	} }++type importContextTestResource struct {+	resource.Resource+	content string+}++func (r importContextTestResource) Content(context.Context) (any, error) {+	return r.content, nil+}++type importContextTestGetter map[string]string++func (g importContextTestGetter) Get(name any) resource.Resource {+	if s, found := g[strings.TrimPrefix(name.(string), "/")]; found {+		return importContextTestResource{content: s}+	}+	return nil+}++func TestImportResolverImportContext(t *testing.T) {+	c := qt.New(t)+	fs := afero.NewMemMapFs()++	writeFile := func(name, content string) {+		c.Assert(afero.WriteFile(fs, name, []byte(content), 0o777), qt.IsNil)+	}++	writeFile("css/b.css", `B_STYLE_FROM_FS`)+	writeFile("css/c.css", `C_STYLE_FROM_FS`)+	writeFile("other/d.css", `D_STYLE_FROM_FS`)++	ic := &resources.ImportContext{+		Getter: importContextTestGetter{+			"b.css":      "B_STYLE_FROM_CONTEXT",+			"ctx/e.css":  "@import \"f.css\";\n@import \"../other/d.css\";\nE_STYLE_FROM_CONTEXT",+			"ctx/f.css":  "F_STYLE_FROM_CONTEXT",+			"unused.css": "UNUSED",+		},+	}++	mainStyles := strings.NewReader(`@import "b.css";+@import "c.css";+@import "ctx/e.css";+LOCAL_STYLE`)++	imp := newImportResolver(+		mainStyles,+		"css/styles.css",+		InlineImports{},+		fs, loggers.NewDefault(),+		identity.NopManager,+	).setImportContext(context.Background(), ic)++	r, err := imp.resolve()+	c.Assert(err, qt.IsNil)+	rs := helpers.ReaderToString(r)+	result := regexp.MustCompile(`\n+`).ReplaceAllString(rs, "\n")++	c.Assert(result, hqt.IsSameString, `B_STYLE_FROM_CONTEXT+C_STYLE_FROM_FS+F_STYLE_FROM_CONTEXT+D_STYLE_FROM_FS+E_STYLE_FROM_CONTEXT+LOCAL_STYLE`)+}resources/resource_transformers/cssjs/postcss.goindex 94295eea9..96bdec3ef 100644@@ -217,7 +217,7 @@ func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationC 		ctx.InPath, 		options.InlineImports, 		t.rs.Assets.Fs, t.rs.Logger, ctx.DependencyManager,-	)+	).setImportContext(ctx.Ctx, ctx.ImportContext)  	if options.InlineImports.InlineImports { 		var err errorresources/resource_transformers/cssjs/tailwindcss.goindex 539016dc2..6cab2d79c 100644@@ -128,7 +128,7 @@ func (t *tailwindcssTransformation) Transform(ctx *resources.ResourceTransformat 		ctx.InPath, 		options.InlineImports, 		t.rs.Assets.Fs, t.rs.Logger, ctx.DependencyManager,-	)+	).setImportContext(ctx.Ctx, ctx.ImportContext)  	if !options.InlineImports.DisableInlineImports { 		src, err = imp.resolve()resources/resource_transformers/js/build.goindex f0ea8ea8b..938f8ded0 100644@@ -55,6 +55,10 @@ func (c *Client) transform(opts esbuild.Options, transformCtx *resources.Resourc  	opts.StdinSourcePath = transformCtx.SourcePath +	if ic := transformCtx.ImportContext; ic != nil {+		opts.SetImportContext(transformCtx.Ctx, ic.Getter, opts.DependencyManager)+	}+ 	pathSpec := c.c.Spec().PathSpec 	outDir := path.Dir(transformCtx.OutPath) 	if opts.IsCSS && opts.PublicPath == "" {resources/resource_transformers/tocss/dartsass/dartsass_integration_test.goindex 72e012667..251ba7882 100644@@ -726,3 +726,56 @@ h2 { color: rgb(color.red(#ddd), 0, 0); } // deprecated 		"color.green() is deprecated", 	) }++func TestTransformImportContext(t *testing.T) {+	t.Parallel()+	if !dartsass.Supports() {+		t.Skip()+	}++	files := `+-- assets/scss/main.scss --+@use "vars";+@import "moo";+main { color: vars.$color; }+-- assets/scss/_vars.scss --+$color: red;+-- assets/scss/_moo.scss --+moo { color: green; }+-- hugo.toml --+-- layouts/home.html --+{{ $vars := resources.FromString "_vars.scss" "$color: blue;" }}+{{ $main := resources.Get "scss/main.scss" | resources.Copy (dict "importContext" $vars) }}+{{ $r := $main | css.Sass (dict "transpiler" "dartsass") | minify }}+T1: {{ $r.Content }}|+{{ $r2 := resources.Get "scss/main.scss" | css.Sass (dict "transpiler" "dartsass" "targetPath" "css/main2.css") | minify }}+T2: {{ $r2.Content }}|+	`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())+	// The import context takes precedence over /assets.+	b.AssertFileContent("public/index.html", "T1: moo{color:green}main{color:blue}|")+	b.AssertFileContent("public/index.html", "T2: moo{color:green}main{color:red}|")+}++func TestTransformImportContextNested(t *testing.T) {+	t.Parallel()+	if !dartsass.Supports() {+		t.Skip()+	}++	files := `+-- assets/scss/main.scss --+@use "components/button";+-- hugo.toml --+-- layouts/home.html --+{{ $button := resources.FromString "components/_button.scss" "@use \"shared\";\nbutton { color: orange; }" }}+{{ $shared := resources.FromString "components/_shared.scss" "shared { color: purple; }" }}+{{ $main := resources.Get "scss/main.scss" | resources.Copy (dict "importContext" (slice $button $shared)) }}+{{ $r := $main | css.Sass (dict "transpiler" "dartsass") | minify }}+T1: {{ $r.Content }}|+	`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())+	b.AssertFileContent("public/index.html", "T1: shared{color:purple}button{color:orange}|")+}resources/resource_transformers/tocss/dartsass/transform.goindex e3d5823e9..001fba90f 100644@@ -14,6 +14,7 @@ package dartsass  import (+	"context" 	"fmt" 	"io" 	"path"@@ -80,9 +81,11 @@ func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error { 		URL:          filename, 		IncludePaths: t.c.sfs.RealDirs(baseDir), 		ImportResolver: importResolver{+			ctx:               ctx.Ctx, 			baseDir:           baseDir, 			c:                 t.c, 			dependencyManager: ctx.DependencyManager,+			importContext:     ctx.ImportContext,  			vars: opts.Vars, 		},@@ -129,21 +132,44 @@ func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error { }  type importResolver struct {+	ctx               context.Context 	baseDir           string 	c                 *Client 	dependencyManager identity.Manager+	importContext     *resources.ImportContext 	vars              map[string]any } +// resolveImportContext resolves url relative to importerDir in the import context, if set.+func (t importResolver) resolveImportContext(importerDir, url string) (string, bool) {+	if t.importContext == nil {+		return "", false+	}+	p, r := sass.ResolveImportContext(t.importContext.Getter, importerDir, url)+	if r == nil {+		return "", false+	}+	t.dependencyManager.AddIdentity(identity.FirstIdentity(r))+	return sass.ImportContextURL(p), true+}+ func (t importResolver) CanonicalizeURL(url string) (string, error) { 	if _, ok := sass.HugoVarsSubPath(url); ok { 		return strings.ToLower(url), nil 	} -	filePath, isURL := paths.UrlStringToFilename(url) 	var prevDir string 	var pathDir string-	if isURL {++	if p, ok := sass.ImportContextPath(url); ok {+		// A relative import from a stylesheet loaded from the import context.+		if u, found := t.resolveImportContext("", p); found {+			return u, nil+		}+		// Not in the import context, try the path relative to /assets.+		url = strings.TrimPrefix(p, "/")+		pathDir = path.Dir(url)+	} else if filePath, isURL := paths.UrlStringToFilename(url); isURL { 		var found bool 		prevDir, found = t.c.sfs.MakePathRelative(filepath.Dir(filePath), true) @@ -151,11 +177,28 @@ func (t importResolver) CanonicalizeURL(url string) (string, error) { 			// Not a member of this filesystem, let Dart Sass handle it. 			return "", nil 		}++		if t.importContext != nil {+			// A relative import resolved by Dart Sass against the importer's file URL.+			// Check the import context first, using the path relative to the entry's directory.+			// Dart Sass will also try the import URL as written if this is not found.+			rel, err := filepath.Rel(filepath.FromSlash(t.baseDir), filepath.Join(prevDir, filepath.Base(filePath)))+			if err == nil && !strings.HasPrefix(rel, "..") {+				if u, found := t.resolveImportContext("", filepath.ToSlash(rel)); found {+					return u, nil+				}+			}+		} 	} else {+		if u, found := t.resolveImportContext("", url); found {+			return u, nil+		} 		prevDir = t.baseDir 		pathDir = path.Dir(url) 	} +	filePath, _ := paths.UrlStringToFilename(url)+ 	basePath := filepath.Join(prevDir, pathDir) 	name := filepath.Base(filePath) @@ -198,6 +241,9 @@ func (t importResolver) Load(url string) (godartsass.Import, error) { 			Content: sass.CreateVarsStyleSheet(sass.TranspilerDart, sass.ResolveVars(t.vars, subPath)), 		}, nil 	}+	if p, ok := sass.ImportContextPath(url); ok {+		return t.loadImportContext(p)+	} 	filename, _ := paths.UrlStringToFilename(url) 	b, err := afero.ReadFile(hugofs.Os, filename) @@ -210,3 +256,26 @@ func (t importResolver) Load(url string) (godartsass.Import, error) {  	return godartsass.Import{Content: string(b), SourceSyntax: sourceSyntax}, err }++func (t importResolver) loadImportContext(p string) (godartsass.Import, error) {+	if t.importContext == nil {+		return godartsass.Import{}, fmt.Errorf("import context not set, can not load %q", p)+	}+	r := t.importContext.Getter.Get(p)+	if r == nil {+		return godartsass.Import{}, fmt.Errorf("%q not found in import context", p)+	}+	content, err := resources.InternalResourceSourceContent(t.ctx, r)+	if err != nil {+		return godartsass.Import{}, fmt.Errorf("failed to read import %q: %w", resources.InternalResourceSourcePathBestEffort(r), err)+	}++	sourceSyntax := godartsass.SourceSyntaxSCSS+	if strings.HasSuffix(p, ".sass") {+		sourceSyntax = godartsass.SourceSyntaxSASS+	} else if strings.HasSuffix(p, ".css") {+		sourceSyntax = godartsass.SourceSyntaxCSS+	}++	return godartsass.Import{Content: content, SourceSyntax: sourceSyntax}, nil+}resources/resource_transformers/tocss/dartsass/transform_test.gonew file mode 100644index 000000000..1e5e09c02@@ -0,0 +1,89 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package dartsass++import (+	"context"+	"strings"+	"testing"++	"github.com/bep/godartsass/v2"+	qt "github.com/frankban/quicktest"+	"github.com/gohugoio/hugo/identity"+	"github.com/gohugoio/hugo/resources"+	"github.com/gohugoio/hugo/resources/resource"+)++type importContextTestResource struct {+	resource.Resource+	content string+}++func (r importContextTestResource) Content(context.Context) (any, error) {+	return r.content, nil+}++type importContextTestGetter map[string]string++func (g importContextTestGetter) Get(name any) resource.Resource {+	if s, found := g[strings.TrimPrefix(name.(string), "/")]; found {+		return importContextTestResource{content: s}+	}+	return nil+}++func TestImportResolverImportContext(t *testing.T) {+	c := qt.New(t)++	imp := importResolver{+		ctx:               context.Background(),+		baseDir:           "scss",+		dependencyManager: identity.NopManager,+		importContext: &resources.ImportContext{+			Getter: importContextTestGetter{+				"_vars.scss":         "$color: blue;",+				"components/_a.scss": "@use \"b\";",+				"components/b.css":   ".b { color: red; }",+			},+		},+	}++	u, err := imp.CanonicalizeURL("vars")+	c.Assert(err, qt.IsNil)+	c.Assert(u, qt.Equals, "hugo-importcontext:/_vars.scss")++	u, err = imp.CanonicalizeURL("components/a")+	c.Assert(err, qt.IsNil)+	c.Assert(u, qt.Equals, "hugo-importcontext:/components/_a.scss")++	// Relative import from components/_a.scss resolved by Dart Sass against its URL.+	u, err = imp.CanonicalizeURL("hugo-importcontext:/components/b")+	c.Assert(err, qt.IsNil)+	c.Assert(u, qt.Equals, "hugo-importcontext:/components/b.css")++	u, err = imp.CanonicalizeURL("hugo-importcontext:///components/b")+	c.Assert(err, qt.IsNil)+	c.Assert(u, qt.Equals, "hugo-importcontext:/components/b.css")++	res, err := imp.Load("hugo-importcontext:/_vars.scss")+	c.Assert(err, qt.IsNil)+	c.Assert(res, qt.DeepEquals, godartsass.Import{Content: "$color: blue;", SourceSyntax: godartsass.SourceSyntaxSCSS})++	res, err = imp.Load("hugo-importcontext:/components/b.css")+	c.Assert(err, qt.IsNil)+	c.Assert(res.SourceSyntax, qt.Equals, godartsass.SourceSyntaxCSS)++	_, err = imp.Load("hugo-importcontext:/notfound.scss")+	c.Assert(err, qt.IsNotNil)+}resources/resource_transformers/tocss/sass/importcontext.gonew file mode 100644index 000000000..c99cbb9be@@ -0,0 +1,96 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package sass++import (+	"fmt"+	"path"+	"strings"++	"github.com/gohugoio/hugo/resources/resource"+)++// ImportContextURLPrefix is the URL prefix used for imports resolved from an import context+// (e.g. set via resources.Copy).+const ImportContextURLPrefix = "hugo-importcontext:"++// ImportContextURL returns the URL for the given import context path.+func ImportContextURL(p string) string {+	return ImportContextURLPrefix + "/" + strings.TrimPrefix(p, "/")+}++// ImportContextPath returns the path for an URL created with ImportContextURL.+// The second return value is false if url is not an import context URL.+func ImportContextPath(url string) (string, bool) {+	p, ok := strings.CutPrefix(url, ImportContextURLPrefix)+	if !ok {+		return "", false+	}+	// Dart Sass may have resolved a relative import against the+	// importer's URL, which may add a "//" authority prefix.+	p = "/" + strings.TrimLeft(p, "/")+	return path.Clean(p), true+}++// ResolveImportContext resolves the Sass import url in the given import context.+// If importerDir is not empty, the url is first resolved relative to that directory.+// It returns the path of the resolved resource (to be used with ImportContextURL)+// and the resource, or nil if not found.+func ResolveImportContext(importContext resource.ResourceGetter, importerDir, url string) (string, resource.Resource) {+	if importContext == nil {+		return "", nil+	}++	url = strings.TrimPrefix(url, "./")+	if url == "" || strings.Contains(url, ":") {+		// E.g. hugo:vars, sass:math or an absolute URL.+		return "", nil+	}++	var dirs []string+	if importerDir != "" && importerDir != "." && importerDir != "/" && !strings.HasPrefix(url, "/") {+		dirs = append(dirs, importerDir)+	}+	dirs = append(dirs, "")++	name := path.Base(url)+	urlDir := path.Dir(url)++	var namePatterns []string+	if strings.Contains(name, ".") {+		namePatterns = []string{"_%s", "%s"}+	} else if strings.HasPrefix(name, "_") {+		namePatterns = []string{"_%s.scss", "_%s.sass", "_%s.css"}+	} else {+		namePatterns = []string{+			"_%s.scss", "%s.scss",+			"_%s.sass", "%s.sass",+			"_%s.css", "%s.css",+			"%s/_index.scss", "%s/_index.sass",+			"%s/index.scss", "%s/index.sass",+		}+	}+	name = strings.TrimPrefix(name, "_")++	for _, dir := range dirs {+		for _, namePattern := range namePatterns {+			p := path.Join("/", dir, urlDir, fmt.Sprintf(namePattern, name))+			if r := importContext.Get(p); r != nil {+				return p, r+			}+		}+	}++	return "", nil+}resources/resource_transformers/tocss/scss/scss_integration_test.goindex 93cc05bf0..5d465c6d1 100644@@ -437,3 +437,36 @@ body {  	b.AssertLogContains("deprecated: css.Sass: libsass was deprecated in Hugo v0.153.0") }++func TestTransformImportContext(t *testing.T) {+	t.Parallel()+	if !scss.Supports() {+		t.Skip()+	}++	files := `+-- assets/scss/main.scss --+@import "vars";+@import "components/button";+main { color: $color; }+-- assets/scss/_vars.scss --+$color: red;+-- assets/scss/components/_button.scss --+button { color: red; }+-- hugo.toml --+-- layouts/home.html --+{{ $vars := resources.FromString "_vars.scss" "$color: blue;" }}+{{ $button := resources.FromString "components/_button.scss" "@import \"shared\";\nbutton { color: orange; }" }}+{{ $shared := resources.FromString "components/_shared.scss" "shared { color: purple; }" }}+{{ $main := resources.Get "scss/main.scss" | resources.Copy (dict "importContext" (slice $vars $button $shared)) }}+{{ $r := $main | css.Sass | minify }}+T1: {{ $r.Content }}|+{{ $r2 := resources.Get "scss/main.scss" | css.Sass (dict "targetPath" "css/main2.css") | minify }}+T2: {{ $r2.Content }}|+	`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())+	// The import context takes precedence over /assets.+	b.AssertFileContent("public/index.html", "T1: shared{color:purple}button{color:orange}main{color:blue}|")+	b.AssertFileContent("public/index.html", "T2: button{color:red}main{color:red}|")+}resources/resource_transformers/tocss/scss/tocss.goindex ea8617140..27a3d343e 100644@@ -65,6 +65,9 @@ func (t *toCSSTransformation) Transform(ctx *resources.ResourceTransformationCtx  	varsStylesheet := sass.CreateVarsStyleSheet(sass.TranspilerLibSass, options.from.Vars) +	// Maps import URLs resolved from the import context to their path in the import context.+	importContextResolved := make(map[string]string)+ 	// To allow for overrides of SCSS files anywhere in the project/theme hierarchy, we need 	// to help libsass revolve the filename by looking in the composite filesystem first. 	// We add the entry directories for both project and themes to the include paths list, but@@ -74,6 +77,26 @@ func (t *toCSSTransformation) Transform(ctx *resources.ResourceTransformationCtx 			return url, varsStylesheet, true 		} +		// Check the import context (e.g. set via resources.Copy) first.+		// LibSass passes the import URL as written as prev for stylesheets not loaded from disk,+		// so we need to keep track of the import context paths resolved.+		prevImportContextPath, prevIsImportContext := importContextResolved[prev]+		if ctx.ImportContext != nil {+			var importerDir string+			if prevIsImportContext {+				importerDir = path.Dir(prevImportContextPath)+			}+			if p, r := sass.ResolveImportContext(ctx.ImportContext.Getter, importerDir, url); r != nil {+				content, err := resources.InternalResourceSourceContent(ctx.Ctx, r)+				if err == nil {+					ctx.DependencyManager.AddIdentity(identity.FirstIdentity(r))+					importContextResolved[url] = p+					return sass.ImportContextURL(p), content, true+				}+				t.c.rs.Logger.Errorf("failed to read import %q: %s", resources.InternalResourceSourcePathBestEffort(r), err)+			}+		}+ 		// We get URL paths from LibSASS, but we need file paths. 		url = filepath.FromSlash(url) 		prev = filepath.FromSlash(prev)@@ -84,6 +107,9 @@ func (t *toCSSTransformation) Transform(ctx *resources.ResourceTransformationCtx  		if prev == "stdin" { 			prevDir = baseDir+		} else if prevIsImportContext {+			// Imported from the import context, resolve relative to /assets.+			prevDir = filepath.FromSlash(strings.TrimPrefix(path.Dir(prevImportContextPath), "/")) 		} else { 			prevDir, _ = t.c.sfs.MakePathRelative(filepath.Dir(prev), true) resources/transform.goindex 5dc281f71..a26052500 100644@@ -133,6 +133,10 @@ type ResourceTransformationCtx struct { 	// to be simple types, as it needs to be serialized to JSON and back. 	Data map[string]any +	// The import context to use when resolving imports, e.g. CSS @import.+	// Set via resources.Copy. May be nil.+	ImportContext *ImportContext+ 	// This is used to publish additional artifacts, e.g. source hhmaps. 	// We may improve this. 	OpenResourcePublisher func(relTargetPath string) (io.WriteCloser, error)@@ -227,6 +231,14 @@ func (r *resourceAdapter) GetDependencyManager() identity.Manager { 	return r.target.GetDependencyManager() } +func (r *resourceAdapter) getImportContext() *ImportContext {+	return r.target.getImportContext()+}++func (r *resourceAdapter) setImportContext(ic *ImportContext) {+	r.target.setImportContext(ic)+}+ func (r resourceAdapter) cloneTo(targetPath string) resource.Resource { 	newtTarget := r.target.cloneTo(targetPath) 	newInner := &resourceAdapterInner{@@ -450,6 +462,9 @@ func (r *resourceAdapter) TransformationKey() string { 	for _, tr := range r.transformations { 		key = key + "_" + tr.Key().Value() 	}+	if ic := r.target.getImportContext(); ic != nil {+		key = key + "_importcontext_" + ic.Key()+	} 	return r.spec.ResourceCache.cleanKey(r.target.Key()) + "_" + hashing.MD5FromStringHexEncoded(key) } @@ -516,6 +531,7 @@ func (r *resourceAdapter) transform(key string, publish, setContent bool) (*reso 		Data:                  make(map[string]any), 		OpenResourcePublisher: r.target.openPublishFileForWriting, 		DependencyManager:     r.target.GetDependencyManager(),+		ImportContext:         r.target.getImportContext(), 	}  	tctx.InMediaType = r.target.MediaType()tpl/css/build_integration_test.goindex 31b692a8e..99cc1963e 100644@@ -731,3 +731,133 @@ body { 		"--text-color: #333;", 	) }++func TestCSSBuildImportContext(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+-- assets/css/main.css --+@import "foo.css" screen;+@import "bar.css" print;+@import "./common.css";+.main { color: black; }+-- assets/css/common.css --+.common { color: gray; }+-- assets/css/bar.css --+.bar-from-assets { color: red; }+-- assets/other/nested.css --+.nested { color: purple; }+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" "@import \"other/nested.css\";\n.foo { color: blue; }" }}+{{ $bar := resources.FromString "bar.css" ".bar { color: green; }" }}+{{ $bar2 := resources.FromString "bar2/bar.css" ".bar2 { color: orange; }" }}+{{ $bar2Mounted := (slice $bar2).Mount "/bar2" "." }}+{{ $main := resources.Get "css/main.css" }}+{{ $css1 := $main | resources.Copy (dict "importContext" (slice $foo $bar)) | css.Build }}+{{ $css2 := $main | resources.Copy (dict "targetPath" "css/main2.css" "importContext" (slice $foo $bar2Mounted)) | css.Build }}+{{ $css3 := $main | resources.Copy (dict "importContext" (slice $foo $bar2)) | css.Build }}+CSS1: {{ $css1.RelPermalink }}|{{ $css1.Content | safeCSS }}|+CSS2: {{ $css2.RelPermalink }}|{{ $css2.Content | safeCSS }}|+CSS3: {{ $css3.RelPermalink }}|{{ $css3.Content | safeCSS }}|+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/index.html",+		"CSS1: /css/main.css|",+		"@media screen {\n  .nested",+		"@media screen {\n  .foo",+		"@media print {\n  .bar {",+		".common {",+		"CSS2: /css/main2.css|",+		"@media print {\n  .bar2 {",+	)++	s := b.FileContent("public/index.html")+	css1 := s[strings.Index(s, "CSS1:"):strings.Index(s, "CSS2:")]+	css2 := s[strings.Index(s, "CSS2:"):strings.Index(s, "CSS3:")]+	css3 := s[strings.Index(s, "CSS3:"):]+	b.Assert(css1, qt.Contains, ".bar {")+	b.Assert(css1, qt.Not(qt.Contains), "bar-from-assets")+	b.Assert(css2, qt.Not(qt.Contains), ".bar {")+	// No bar.css in the import context, falls back to /assets/css/bar.css.+	b.Assert(css3, qt.Contains, "CSS3: /css/main.css|")+	b.Assert(css3, qt.Contains, "bar-from-assets")+	b.Assert(css3, qt.Not(qt.Contains), ".bar {")+}++func TestCSSBuildImportContextNotSet(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+-- assets/css/main.css --+@import "foo.css";+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" ".foo { color: blue; }" }}+{{ $css := resources.Get "css/main.css" | css.Build }}+CSS: {{ $css.Content | safeCSS }}|+`++	_, err := hugolib.TestE(t, files, hugolib.TestOptOsFs())+	qt.Assert(t, err, qt.IsNotNil)+	qt.Assert(t, err.Error(), qt.Contains, "foo.css")+}++func TestCSSBuildImportContextPage(t *testing.T) {+	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+disableLiveReload = true+-- content/_index.md --+---+title: Home+---+-- content/foo.css --+.foo-from-bundle { color: blue; }+-- assets/css/main.css --+@import "foo.css";+.main { color: black; }+-- layouts/home.html --+{{ $css := resources.Get "css/main.css" | resources.Copy (dict "importContext" .Page) | css.Build }}+CSS: {{ $css.Content | safeCSS }}|+`++	b := hugolib.TestRunning(t, files, hugolib.TestOptOsFs())+	b.AssertFileContent("public/index.html", ".foo-from-bundle {", ".main {")++	b.EditFileReplaceAll("content/foo.css", ".foo-from-bundle", ".foo-from-bundle-edited").Build()+	b.AssertFileContent("public/index.html", ".foo-from-bundle-edited {")+}++func TestCSSBuildImportContextSameNameDifferentContent(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "page", "section", "rss", "sitemap"]+-- assets/css/main.css --+@import "vars.css";+-- layouts/home.html --+{{ $blue := resources.FromString "vars.css" ".vars { color: blue; }" }}+{{ $green := resources.FromString "vars.css" ".vars { color: green; }" }}+{{ $main := resources.Get "css/main.css" }}+{{ $css1 := $main | resources.Copy (dict "targetPath" "css/blue.css" "importContext" $blue) | css.Build }}+{{ $css2 := $main | resources.Copy (dict "targetPath" "css/blue.css" "importContext" $green) | css.Build }}+CSS1: {{ $css1.Content | safeCSS }}|+CSS2: {{ $css2.Content | safeCSS }}|+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	s := b.FileContent("public/index.html")+	css1 := s[strings.Index(s, "CSS1:"):strings.Index(s, "CSS2:")]+	css2 := s[strings.Index(s, "CSS2:"):]+	b.Assert(css1, qt.Contains, "color: blue;")+	b.Assert(css1, qt.Not(qt.Contains), "color: green;")+	b.Assert(css2, qt.Contains, "color: green;")+	b.Assert(css2, qt.Not(qt.Contains), "color: blue;")+}tpl/resources/resources.goindex 2512b5ce9..6a3edf524 100644@@ -18,6 +18,7 @@ import ( 	"context" 	"errors" 	"fmt"+	"strings"  	"github.com/gohugoio/hugo/common/hmaps" 	"github.com/gohugoio/hugo/common/hugo"@@ -71,8 +72,24 @@ type Namespace struct { 	templatesClient *templates.Client } -// Copy copies r to the new targetPath in s.+// Copy copies r to a new target path.+// The first argument is either the target path or an options map with the keys:+//+//   - targetPath: the target path of the copy. Defaults to the target path of r.+//   - importContext: the resources used to resolve imports in transformations of+//     the copy, e.g. css.Build, js.Build, js.Batch and css.Sass. This can be a Resource,+//     a slice of Resources, a Page or the result of Resources.Mount, or a slice of these. func (ns *Namespace) Copy(s any, r resource.Resource) (resource.Resource, error) {+	if r == nil {+		return nil, errors.New("must provide a Resource object to copy")+	}++	if _, isString := s.(string); !isString {+		if m, err := hmaps.ToStringMapE(s); err == nil {+			return ns.copyWithOptions(m, r)+		}+	}+ 	targetPath, err := cast.ToStringE(s) 	if err != nil { 		panic(err)@@ -80,6 +97,37 @@ func (ns *Namespace) Copy(s any, r resource.Resource) (resource.Resource, error) 	return ns.createClient.Copy(r, targetPath) } +func (ns *Namespace) copyWithOptions(m map[string]any, r resource.Resource) (resource.Resource, error) {+	var (+		targetPath    string+		importContext *resources.ImportContext+		err           error+	)++	for k, v := range m {+		switch strings.ToLower(k) {+		case "targetpath":+			targetPath, err = cast.ToStringE(v)+			if err != nil {+				return nil, fmt.Errorf("resources.Copy: invalid targetPath: %w", err)+			}+		case "importcontext":+			importContext, err = resources.NewImportContext(v)+			if err != nil {+				return nil, fmt.Errorf("resources.Copy: %w", err)+			}+		default:+			return nil, fmt.Errorf("resources.Copy: unknown option %q", k)+		}+	}++	if targetPath == "" {+		targetPath = resources.InternalResourceTargetPath(r)+	}++	return ns.createClient.CopyWithImportContext(r, targetPath, importContext)+}+ // Get locates the filename given in Hugo's assets filesystem // and creates a Resource object that can be used for further transformations. func (ns *Namespace) Get(filename any) resource.Resource {tpl/resources/resources_integration_test.goindex b7f86111c..ceb4c641f 100644@@ -14,6 +14,7 @@ package resources_test  import (+	"strings" 	"testing"  	qt "github.com/frankban/quicktest"@@ -74,6 +75,60 @@ Copy3: /blog/js/copies/moo.a677329fc6c4ad947e0c7116d91f37a2.min.js|text/javascri 	b.AssertFileExists("public/images/copy3.png", false) } +func TestCopyWithOptions(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+baseURL = "http://example.com/blog"+-- assets/css/main.css --+body { color: red; }+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" "body { color: blue; }" }}+{{ $main := resources.Get "css/main.css" }}+{{ $copy1 := $main | resources.Copy (dict "targetPath" "css/copy1.css") }}+{{ $copy2 := $main | resources.Copy (dict "importContext" (slice $foo)) }}+{{ $copy3 := $main | resources.Copy (dict "TargetPath" "css/copy3.css" "ImportContext" $foo) | fingerprint "md5" }}+Copy1: {{ $copy1.RelPermalink }}|{{ $copy1.MediaType }}|{{ $copy1.Content }}|+Copy2: {{ $copy2.RelPermalink }}|{{ $copy2.MediaType }}|{{ $copy2.Content }}|+Copy3: {{ $copy3.RelPermalink }}|{{ $copy3.Content }}|+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html",+		"Copy1: /blog/css/copy1.css|text/css|body { color: red; }|",+		"Copy2: /blog/css/main.css|text/css|body { color: red; }|",+		"Copy3: /blog/css/copy3.",+	)+}++func TestCopyWithOptionsErrors(t *testing.T) {+	t.Parallel()++	for _, test := range []struct {+		opts   string+		expect string+	}{+		{`(dict "foo" "bar")`, `unknown option "foo"`},+		{`(dict "importContext" "notaresource")`, `is not a valid import context`},+		{`(dict "importContext" (slice 1 2))`, `is not a valid import context`},+	} {+		files := `+-- hugo.toml --+-- assets/css/main.css --+body { color: red; }+-- layouts/home.html --+{{ $copy := resources.Get "css/main.css" | resources.Copy OPTS }}+{{ $copy.RelPermalink }}+`+		files = strings.ReplaceAll(files, "OPTS", test.opts)+		b, err := hugolib.TestE(t, files)+		b.Assert(err, qt.IsNotNil)+		b.Assert(err.Error(), qt.Contains, test.expect)+	}+}+ func TestCopyPageShouldFail(t *testing.T) { 	t.Parallel()  
Merged fix · PR #15156+689 −102
common/hashing/hashing.goindex ad28bbce2..1b0ed2768 100644@@ -18,6 +18,7 @@ import ( 	"crypto/md5" 	"encoding/hex" 	"io"+	"reflect" 	"strconv" 	"sync" @@ -124,11 +125,38 @@ func HashStringHex(vs ...any) string { var hashOptsPool = sync.Pool{ 	New: func() any { 		return &hashstructure.HashOptions{-			Hasher: xxhash.New(),+			Hasher:     xxhash.New(),+			UnwrapFunc: unwrapForHashing, 		} 	}, } +// hashstructure only sees exported struct fields, so rewrite known identity types before hashing,+// e.g. a Resource or Page nested in an options map hashes by its Key.+func unwrapForHashing(v reflect.Value) (reflect.Value, error) {+	if v.Kind() != reflect.Struct {+		return v, nil+	}+	var in any+	if v.CanAddr() {+		// The common case; pointer receiver methods on a struct+		// reached through a pointer.+		in = v.Addr().Interface()+	} else {+		in = v.Interface()+	}+	switch t := in.(type) {+	case hashstructure.Hashable:+		// Let hashstructure handle it.+		return v, nil+	case keyer:+		return reflect.ValueOf(t.Key()), nil+	case identity.IdentityProvider:+		return reflect.ValueOf(t.GetIdentity()), nil+	}+	return v, nil+}+ func getHashOpts() *hashstructure.HashOptions { 	return hashOptsPool.Get().(*hashstructure.HashOptions) }@@ -145,15 +173,10 @@ func putHashOpts(opts *hashstructure.HashOptions) { func HashUint64(vs ...any) uint64 { 	var o any 	if len(vs) == 1 {-		o = toHashable(vs[0])+		o = vs[0] 	} else {-		elements := make([]any, len(vs))-		for i, e := range vs {-			elements[i] = toHashable(e)-		}-		o = elements+		o = vs 	}- 	hash, err := Hash(o) 	if err != nil { 		panic(err)@@ -176,19 +199,6 @@ type keyer interface { 	Key() string } -// For structs, hashstructure.Hash only works on the exported fields,-// so rewrite the input slice for known identity types.-func toHashable(v any) any {-	switch t := v.(type) {-	case keyer:-		return t.Key()-	case identity.IdentityProvider:-		return t.GetIdentity()-	default:-		return v-	}-}- type xxhashReadFrom struct { 	buff []byte 	*xxhash.Digestgo.modindex 6e4498c98..4c0250df0 100644@@ -39,7 +39,7 @@ require ( 	github.com/gohugoio/gift v0.2.0 	github.com/gohugoio/go-i18n/v2 v2.1.3-0.20251018145728-cfcc22d823c6 	github.com/gohugoio/go-radix v1.2.0-	github.com/gohugoio/hashstructure v0.6.0+	github.com/gohugoio/hashstructure v1.0.0 	github.com/gohugoio/httpcache v0.8.0 	github.com/gohugoio/hugo-goldmark-extensions/extras v0.7.0 	github.com/gohugoio/hugo-goldmark-extensions/passthrough v0.5.0go.sumindex 5401b44fa..f1dded847 100644@@ -274,6 +274,8 @@ github.com/gohugoio/go-radix v1.2.0 h1:D5GTk8jIoeXirBSc2P4E4NdHKDrenk9k9N0ctU5Yr github.com/gohugoio/go-radix v1.2.0/go.mod h1:k6vDa0ebpbpgtzSj9lPGJcA4AZwJ9xUNObUy2vczPFM= github.com/gohugoio/hashstructure v0.6.0 h1:7wMB/2CfXoThFYhdWRGv3u3rUM761Cq29CxUW+NltUg= github.com/gohugoio/hashstructure v0.6.0/go.mod h1:lapVLk9XidheHG1IQ4ZSbyYrXcaILU1ZEP/+vno5rBQ=+github.com/gohugoio/hashstructure v1.0.0 h1:vWYuyzs1n0LdI0F54TJQeYAiB44fHX7H9hCp9X6gHKg=+github.com/gohugoio/hashstructure v1.0.0/go.mod h1:FSbTK4QwxucJ2bC4Lvrs9a6x0DbQDXNoyBO+h4nlCgE= github.com/gohugoio/httpcache v0.8.0 h1:hNdsmGSELztetYCsPVgjA960zSa4dfEqqF/SficorCU= github.com/gohugoio/httpcache v0.8.0/go.mod h1:fMlPrdY/vVJhAriLZnrF5QpN3BNAcoBClgAyQd+lGFI= github.com/gohugoio/hugo-goldmark-extensions/extras v0.7.0 h1:I/n6v7VImJ3aISLnn73JAHXyjcQsMVvbguQPTk9Ehus=hugolib/page.goindex 46c7e5c07..af1d65f1f 100644@@ -19,7 +19,6 @@ import ( 	"iter" 	"path/filepath" 	"slices"-	"strconv" 	"strings" 	"sync/atomic" @@ -174,10 +173,6 @@ func (ps *pageState) Param(key any) (any, error) { 	return resource.Param(ps, ps.s.Params(), key) } -func (ps *pageState) Key() string {-	return "page-" + strconv.FormatUint(ps.pid, 10)-}- // RelatedKeywords implements the related.Document interface needed for fast page searches. func (ps *pageState) RelatedKeywords(cfg related.IndexConfig) ([]related.Keyword, error) { 	v, found, err := page.NamedPageMetaValue(ps, cfg.Name)hugolib/page__output.goindex 384ed5f9e..cafe012b7 100644@@ -149,6 +149,11 @@ func (po *pageOutput) Aliases() []string { 	return aliases } +// Key returns a unique key for this page output, used to e.g. hashing.+func (po *pageOutput) Key() string {+	return po.p.Path() + po.f.Name+}+ func (po *pageOutput) incrRenderState() { 	po.renderState++ 	po.renderOnce = trueinternal/js/esbuild/options.goindex 88a5405a1..4176438e8 100644@@ -183,6 +183,9 @@ type ExternalOptions struct { 	// Maps a component import to another. 	Shims map[string]string +	// User provided import context. If set, we will look here first.+	ImportContext any+ 	// Configuring a loader for a given file type lets you load that file type with an 	// import statement or a require call. For example, configuring the .png file extension 	// to use the data URL loader means importing a .png file gives you a data URLinternal/js/esbuild/resolve.goindex 3438af375..a0db7874d 100644@@ -260,6 +260,19 @@ func createBuildPlugins(rs *resources.Spec, assetsResolver *fsResolver, depsMana 			} 		} +		if opts.ImportOnResolveFunc != nil {+			// Relative imports resolved against the importing file's directory,+			// e.g. "./foo.css". The path as written was tried above.+			for _, p := range pathsToTry {+				if p == impPath {+					continue+				}+				if s := opts.ImportOnResolveFunc(filepath.ToSlash(p), args); s != "" {+					return api.OnResolveResult{Path: s, Namespace: NsHugoImportResolveFunc}, nil+				}+			}+		}+ 		var m *hugofs.FileMeta 		for _, p := range pathsToTry { 			m = assetsResolver.resolveComponent(p, isCSSToken)resources/images/color.goindex 47c2848b9..fe233c7b7 100644@@ -16,13 +16,12 @@ package images import ( 	"encoding/hex" 	"fmt"-	"hash/fnv" 	"image/color" 	"math"+	"slices" 	"strings"  	"github.com/gohugoio/hugo/common/hstrings"-	"slices" )  type colorGoProvider interface {@@ -65,10 +64,8 @@ func (c Color) String() string { // For hashstructure. This struct is used in template func options // that needs to be able to hash a Color. // For internal use only.-func (c Color) Hash() (uint64, error) {-	h := fnv.New64a()-	h.Write([]byte(c.hex))-	return h.Sum64(), nil+func (c Color) Key() string {+	return c.hex }  func (c *Color) init() error {resources/internal/key.goindex b0ac9703f..3f8926d0c 100644@@ -13,7 +13,9 @@  package internal -import "github.com/gohugoio/hugo/common/hashing"+import (+	"github.com/gohugoio/hugo/common/hashing"+)  // ResourceTransformationKey are provided by the different transformation implementations. // It identifies the transformation (name) and its configuration (elements).resources/resource.goindex cf6e1e597..69facb098 100644@@ -96,6 +96,9 @@ type ResourceSourceDescriptor struct { 	// Delay publishing until either Permalink or RelPermalink is called. Maybe never. 	LazyPublish bool +	// Whether to include the hash of the source content in the resource key.+	IncludeHashInKey bool+ 	// Set when its known up front, else it's resolved from the target filename. 	MediaType media.Type resources/resource/resources.goindex 28fbab42f..08ee0b7ac 100644@@ -20,6 +20,8 @@ import ( 	"slices" 	"strings" +	"github.com/gohugoio/hashstructure"+	"github.com/gohugoio/hugo/common/hashing" 	"github.com/gohugoio/hugo/common/hmaps" 	"github.com/gohugoio/hugo/common/hreflect" 	"github.com/gohugoio/hugo/common/paths"@@ -33,44 +35,56 @@ var _ ResourceFinder = (*Resources)(nil) // I.e. both pages and images etc. type Resources []Resource -// Mount mounts the given resources from base to the given target path.-// Note that leading slashes in target marks an absolute path.-// This method is currently only useful in js.Batch.-func (r Resources) Mount(base, target string) ResourceGetter {-	return resourceGetterFunc(func(namev any) Resource {-		name1, err := cast.ToStringE(namev)-		if err != nil {-			panic(err)-		}+type resourceMount struct {+	R      Resources+	Base   string+	Target string+} -		isTargetAbs := strings.HasPrefix(target, "/")+func (r resourceMount) Get(namev any) Resource {+	name1, err := cast.ToStringE(namev)+	if err != nil {+		panic(err)+	} -		if target != "" {-			name1 = strings.TrimPrefix(name1, target)-			if !isTargetAbs {-				name1 = paths.TrimLeading(name1)-			}-		}+	isTargetAbs := strings.HasPrefix(r.Target, "/") -		if base != "" && isTargetAbs {-			name1 = path.Join(base, name1)+	if r.Target != "" {+		name1 = strings.TrimPrefix(name1, r.Target)+		if !isTargetAbs {+			name1 = paths.TrimLeading(name1) 		}+	} -		for _, res := range r {-			name2 := res.Name()+	if r.Base != "" && isTargetAbs {+		name1 = path.Join(r.Base, name1)+	} -			if base != "" && !isTargetAbs {-				name2 = paths.TrimLeading(strings.TrimPrefix(name2, base))-			}+	for _, res := range r.R {+		name2 := res.Name() -			if strings.EqualFold(name1, name2) {-				return res-			}+		if r.Base != "" && !isTargetAbs {+			name2 = paths.TrimLeading(strings.TrimPrefix(name2, r.Base))+		} +		if strings.EqualFold(name1, name2) {+			return res 		} -		return nil-	})+	}++	return nil+}++// Mount mounts the given resources from base to the given target path.+// Note that leading slashes in target marks an absolute path.+// This method can be used in any of the template funcs that takes an importContext option, e.g. css.Build.+func (r Resources) Mount(base, target string) ResourceGetter {+	return resourceMount{+		R:      r,+		Base:   base,+		Target: target,+	} }  type ResourcesProvider interface {@@ -276,12 +290,6 @@ type StaleInfoResourceGetter interface { 	ResourceGetter } -type resourceGetterFunc func(name any) Resource--func (f resourceGetterFunc) Get(name any) Resource {-	return f(name)-}- // ResourceFinder provides methods to find Resources. // Note that GetRemote (as found in resources.GetRemote) is // not covered by this interface, as this is only available as a global template function.@@ -318,6 +326,8 @@ type ResourceFinder interface { 	ByType(typ any) Resources } +var _ hashstructure.Hashable = (*cachedResourceGetter)(nil)+ // NewCachedResourceGetter creates a new ResourceGetter from the given objects. // If multiple objects are provided, they are merged into one where // the first match wins.@@ -329,12 +339,19 @@ func NewCachedResourceGetter(os ...any) *cachedResourceGetter { 		} 	} +	hash := hashing.HashUint64(getters)+ 	return &cachedResourceGetter{ 		cache:    hmaps.NewCache[string, Resource](), 		delegate: getters,+		hash:     hash, 	} } +func (c *cachedResourceGetter) Hash() (uint64, error) {+	return c.hash, nil+}+ type multiResourceGetter []ResourceGetter  func (m multiResourceGetter) Get(name any) Resource {@@ -354,6 +371,7 @@ var ( type cachedResourceGetter struct { 	cache    *hmaps.Cache[string, Resource] 	delegate ResourceGetter+	hash     uint64 }  func (c *cachedResourceGetter) Get(name any) Resource {@@ -390,8 +408,6 @@ func unwrapResourceGetter(v any) (ResourceGetter, bool) { 		return vv, true 	case ResourcesProvider: 		return vv.Resources(), true-	case func(name any) Resource:-		return resourceGetterFunc(vv), true 	default: 		vvv, ok := hreflect.ToSliceAny(v) 		if !ok {resources/resource_factories/create/create.goindex 4a4d14da6..abea8c982 100644@@ -304,8 +304,9 @@ func (c *Client) FromOpts(opts Options) (resource.Resource, error) { 		} 		return c.rs.NewResource( 			resources.ResourceSourceDescriptor{-				LazyPublish:   true,-				GroupIdentity: identity.Anonymous, // All usage of this resource are tracked via its string content.+				LazyPublish:      true,+				IncludeHashInKey: !opts.TargetPathHasHash,+				GroupIdentity:    identity.Anonymous, // All usage of this resource are tracked via its string content. 				OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { 					return newReadSeeker() 				},resources/resource_spec.goindex 861cdc435..257edf1c3 100644@@ -201,7 +201,7 @@ func (r *Spec) NewResource(rd ResourceSourceDescriptor) (resource.Resource, erro 		h:                &resourceHash{}, 		publishInit:      &hsync.OnceMore{}, 		keyInit:          &sync.Once{},-		includeHashInKey: isImage,+		includeHashInKey: isImage || rd.IncludeHashInKey, 		paths:            rp, 		spec:             r, 		sd:               rd,resources/resource_transformers/cssjs/inline_imports.goindex 44ae4b3c6..230add6e6 100644@@ -14,6 +14,7 @@ package cssjs  import (+	"context" 	"crypto/sha256" 	"encoding/hex" 	"errors"@@ -30,6 +31,8 @@ import ( 	"github.com/gohugoio/hugo/common/text" 	"github.com/gohugoio/hugo/hugofs" 	"github.com/gohugoio/hugo/identity"+	"github.com/gohugoio/hugo/resources"+	"github.com/gohugoio/hugo/resources/resource" 	"github.com/spf13/afero" ) @@ -46,10 +49,12 @@ type fileOffset struct { }  type importResolver struct {+	ctx    context.Context 	r      io.Reader 	inPath string 	opts   InlineImports +	importContext     resource.ResourceGetter 	contentSeen       map[string]bool 	dependencyManager identity.Manager 	linemap           map[int]fileOffset@@ -57,8 +62,9 @@ type importResolver struct { 	logger            loggers.Logger } -func newImportResolver(r io.Reader, inPath string, opts InlineImports, fs afero.Fs, logger loggers.Logger, dependencyManager identity.Manager) *importResolver {-	return &importResolver{+func newImportResolver(ctx context.Context, r io.Reader, inPath string, opts InlineImports, fs afero.Fs, logger loggers.Logger, dependencyManager identity.Manager) *importResolver {+	imp := &importResolver{+		ctx:               ctx, 		r:                 r, 		dependencyManager: dependencyManager, 		inPath:            inPath,@@ -66,6 +72,10 @@ func newImportResolver(r io.Reader, inPath string, opts InlineImports, fs afero. 		linemap: make(map[int]fileOffset), contentSeen: make(map[string]bool), 		opts: opts, 	}+	if opts.ImportContext != nil {+		imp.importContext = resource.NewCachedResourceGetter(opts.ImportContext)+	}+	return imp }  func (imp *importResolver) contentHash(filename string) ([]byte, string) {@@ -73,9 +83,13 @@ func (imp *importResolver) contentHash(filename string) ([]byte, string) { 	if err != nil { 		return nil, "" 	}+	return b, hashBytes(b)+}++func hashBytes(b []byte) string { 	h := sha256.New() 	h.Write(b)-	return b, hex.EncodeToString(h.Sum(nil))+	return hex.EncodeToString(h.Sum(nil)) }  func (imp *importResolver) importRecursive(@@ -105,8 +119,35 @@ func (imp *importResolver) importRecursive( 		} else { 			path := strings.Trim(strings.TrimPrefix(line, importIdentifier), " \"';") 			filename := filepath.Join(basePath, path)-			imp.dependencyManager.AddIdentity(identity.CleanStringIdentity(filename))-			importContent, hash := imp.contentHash(filename)+			var (+				importContent []byte+				hash          string+				nestedInPath  string+			)+			if imp.importContext != nil {+				// Try first the path as written in the import statement,+				// then resolved relative to the importing file.+				for _, name := range []string{path, filepath.ToSlash(filename)} {+					r := imp.importContext.Get(name)+					if r == nil {+						continue+					}+					imp.dependencyManager.AddIdentity(identity.FirstIdentity(r))+					s, err := resources.InternalResourceSourceContent(imp.ctx, r)+					if err != nil {+						return 0, "", err+					}+					importContent, hash = []byte(s), hashBytes([]byte(s))+					nestedInPath = name+					break+				}+			}++			if importContent == nil {+				imp.dependencyManager.AddIdentity(identity.CleanStringIdentity(filename))+				importContent, hash = imp.contentHash(filename)+				nestedInPath = filepath.ToSlash(filename)+			}  			if importContent == nil { 				if imp.opts.SkipInlineImportsNotFound {@@ -135,7 +176,7 @@ func (imp *importResolver) importRecursive( 			imp.contentSeen[hash] = true  			// Handle recursive imports.-			l, nested, err := imp.importRecursive(i+lineNum, string(importContent), filepath.ToSlash(filename))+			l, nested, err := imp.importRecursive(i+lineNum, string(importContent), nestedInPath) 			if err != nil { 				return 0, "", err 			}resources/resource_transformers/cssjs/inline_imports_test.goindex 3578e2612..bfbef977a 100644@@ -14,6 +14,7 @@ package cssjs  import (+	"context" 	"regexp" 	"strings" 	"testing"@@ -21,10 +22,12 @@ import ( 	"github.com/gohugoio/hugo/common/loggers" 	"github.com/gohugoio/hugo/htesting/hqt" 	"github.com/gohugoio/hugo/identity"+	"github.com/gohugoio/hugo/resources/resource"  	"github.com/gohugoio/hugo/helpers"  	"github.com/spf13/afero"+	"github.com/spf13/cast"  	qt "github.com/frankban/quicktest" )@@ -103,6 +106,7 @@ LOCAL_STYLE @import "e.css";`)  	imp := newImportResolver(+		t.Context(), 		mainStyles, 		"styles.css", 		InlineImports{},@@ -130,6 +134,70 @@ E_STYLE`) 	}) } +func TestImportResolverImportContext(t *testing.T) {+	c := qt.New(t)+	fs := afero.NewMemMapFs()++	writeFile := func(name, content string) {+		c.Assert(afero.WriteFile(fs, name, []byte(content), 0o777), qt.IsNil)+	}++	// Loses to the import context entry with the same name.+	writeFile("css/a.css", "A_STYLE_FS")+	writeFile("css/b.css", "B_STYLE_FS")++	importContext := testImportContext{+		"a.css":     "@import \"c.css\";\nA_STYLE",+		"c.css":     "C_STYLE",+		"css/d.css": "D_STYLE",+	}++	mainStyles := strings.NewReader(`@import "a.css";+@import "b.css";+@import "./d.css";+LOCAL_STYLE`)++	imp := newImportResolver(+		t.Context(),+		mainStyles,+		"css/styles.css",+		InlineImports{ImportContext: importContext},+		fs, loggers.NewDefault(),+		identity.NopManager,+	)++	r, err := imp.resolve()+	c.Assert(err, qt.IsNil)+	rs := helpers.ReaderToString(r)+	result := regexp.MustCompile(`\n+`).ReplaceAllString(rs, "\n")++	c.Assert(result, hqt.IsSameString, `C_STYLE+A_STYLE+B_STYLE_FS+D_STYLE+LOCAL_STYLE`)+}++type testImportContext map[string]string++func (g testImportContext) Get(name any) resource.Resource {+	s := cast.ToString(name)+	if content, found := g[s]; found {+		return testImportContextResource{name: s, content: content}+	}+	return nil+}++type testImportContextResource struct {+	resource.Resource+	name    string+	content string+}++func (r testImportContextResource) Name() string { return r.name }++func (r testImportContextResource) Content(context.Context) (any, error) { return r.content, nil }+ func BenchmarkImportResolver(b *testing.B) { 	c := qt.New(b) 	fs := afero.NewMemMapFs()@@ -161,6 +229,7 @@ LOCAL_STYLE 	for b.Loop() { 		b.StopTimer() 		imp := newImportResolver(+			b.Context(), 			strings.NewReader(mainStyles), 			"styles.css", 			InlineImports{},resources/resource_transformers/cssjs/postcss.goindex 94295eea9..e1ca308b0 100644@@ -87,6 +87,10 @@ type InlineImports struct { 	// Note that the inline importer does not process url location or imports with media queries, 	// so those will be left as-is even without enabling this option. 	SkipInlineImportsNotFound bool++	// User provided import context. If set, imports are looked up here first,+	// by the path as written in the @import statement, then in the assets filesystem.+	ImportContext any }  // Some of the options from https://github.com/postcss/postcss-cli@@ -213,6 +217,7 @@ func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationC 	src := ctx.From  	imp := newImportResolver(+		ctx.Ctx, 		ctx.From, 		ctx.InPath, 		options.InlineImports,resources/resource_transformers/cssjs/tailwindcss.goindex 539016dc2..e7c690cd0 100644@@ -124,6 +124,7 @@ func (t *tailwindcssTransformation) Transform(ctx *resources.ResourceTransformat 	src := ctx.From  	imp := newImportResolver(+		ctx.Ctx, 		ctx.From, 		ctx.InPath, 		options.InlineImports,resources/resource_transformers/cssjs/tailwindcss_integration_test.goindex e2ce293e3..03cd1e07e 100644@@ -64,6 +64,45 @@ CSS: {{ $css.Content | safeCSS }}| 	b.AssertFileContent("public/index.html", "/*! tailwindcss v4.") } +// See issue 15103.+func TestTailwindCSSImportContext(t *testing.T) {+	t.Parallel()+	htesting.SkipSlowTestUnlessCI(t)++	files := `+-- hugo.toml --+disableKinds = ['page','rss','section','sitemap','taxonomy','term']+-- assets/css/main.css --+@import "tailwindcss";++@import "foo.css";+@import "bar.css";+-- assets/css/foo.css --+.foo {color: orange;}+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" ".foo {color: blue;}" }}+{{ $bar := resources.FromString "bar.css" ".bar {color: green;}" }}+{{ $opts := dict "importContext" (slice $foo $bar) }}+{{ $css := resources.Get "css/main.css" | css.TailwindCSS $opts }}+CSS: {{ $css.Content | safeCSS }}|+-- package.json --+{+  "devDependencies": {+    "@tailwindcss/cli": "^4.1.7",+    "tailwindcss": "^4.1.7"+  }+}+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall(), hugolib.TestOptInfo())++	// foo.css resolves in the import context before the assets filesystem.+	b.AssertFileContent("public/index.html",+		".foo {\n    color: blue;\n  }",+		".bar {\n    color: green;\n  }",+	)+}+ func TestTailwindCSSNoInlineImportsIssue13719(t *testing.T) { 	t.Parallel() 	htesting.SkipSlowTestUnlessCI(t)resources/resource_transformers/js/build.goindex f0ea8ea8b..0415b058a 100644@@ -42,6 +42,8 @@ func New(fs *filesystems.SourceFilesystem, rs *resources.Spec, cssMode bool) *Cl }  // Process processes a resource with the user provided options.+// If importContext is not nil, imports are resolved in it first,+// then in the assets filesystem (the same precedence as in js.Batch). func (c *Client) Process(res resources.ResourceTransformer, opts map[string]any) (resource.Resource, error) { 	return res.Transform( 		&buildTransformation{c: c, optsm: opts},resources/resource_transformers/js/transform.goindex 07933a92f..3da5f8e87 100644@@ -18,10 +18,14 @@ import ( 	"path" 	"path/filepath" +	"github.com/evanw/esbuild/pkg/api"+	"github.com/gohugoio/hugo/common/hmaps"+	"github.com/gohugoio/hugo/identity" 	"github.com/gohugoio/hugo/internal/js/esbuild" 	"github.com/gohugoio/hugo/media" 	"github.com/gohugoio/hugo/resources" 	"github.com/gohugoio/hugo/resources/internal"+	"github.com/gohugoio/hugo/resources/resource" )  type buildTransformation struct {@@ -69,6 +73,29 @@ func (t *buildTransformation) Transform(ctx *resources.ResourceTransformationCtx 	opts.MediaType = ctx.InMediaType 	opts.Stdin = true 	opts.IsCSS = t.c.c.CssMode+	var ic resource.ResourceGetter+	if opts.ImportContext != nil {+		ic = resource.NewCachedResourceGetter(opts.ImportContext)+	}++	if ic != nil {+		resolved := hmaps.NewCache[string, resource.Resource]()+		opts.ImportOnResolveFunc = func(imp string, args api.OnResolveArgs) string {+			if r := esbuild.ResolveResource(imp, ic); r != nil {+				p := esbuild.PrefixHugoVirtual + resources.InternalResourceTargetPath(r)+				resolved.Set(p, r)+				ctx.DependencyManager.AddIdentity(identity.FirstIdentity(r))+				return p+			}+			return ""+		}+		opts.ImportOnLoadFunc = func(args api.OnLoadArgs) (string, error) {+			if r, found := resolved.Get(args.Path); found {+				return resources.InternalResourceSourceContent(ctx.Ctx, r)+			}+			return "", nil+		}+	}  	_, err = t.c.transform(opts, ctx) resources/resource_transformers/tocss/dartsass/client.goindex cd01b12ee..02ff0bb94 100644@@ -158,6 +158,10 @@ type Options struct { 	//     $color: vars.$color; 	Vars map[string]any +	// User provided import context. If set, imports are looked up here first,+	// then in the assets filesystem.+	ImportContext any+ 	// Deprecations IDs in this slice will be silenced. 	// The IDs can be found in the Dart Sass log output, e.g. "import" in 	//    WARN  Dart Sass: DEPRECATED [import].resources/resource_transformers/tocss/dartsass/dartsass_integration_test.goindex 72e012667..2acbd8194 100644@@ -51,6 +51,35 @@ T1: {{ $r.Content }} 	b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } +// See issue 15103.+func TestTransformImportContext(t *testing.T) {+	t.Parallel()+	if !dartsass.Supports() {+		t.Skip()+	}++	files := `+-- hugo.toml --+-- assets/scss/_foo.scss --+body { color: orange; }+-- assets/scss/main.scss --+@import "foo";+@import "bar";+-- layouts/home.html --+{{ $foo := resources.FromString "foo.scss" "body { color: blue; }" }}+{{ $bar := resources.FromString "bar.scss" "@import \"baz\";\nbody { color: green; }" }}+{{ $baz := resources.FromString "baz.scss" "p { color: red; }" }}+{{ $opts := dict "transpiler" "dartsass" "outputStyle" "compressed" "importContext" (slice $foo $bar $baz) }}+{{ $r := resources.Get "scss/main.scss" | css.Sass $opts }}+T1: {{ $r.Content }}+	`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	// foo resolves in the import context before the assets filesystem.+	b.AssertFileContent("public/index.html", `T1: body{color:blue}p{color:red}body{color:green}`)+}+ func TestTransformImportRegularCSS(t *testing.T) { 	t.Parallel() 	if !dartsass.Supports() {resources/resource_transformers/tocss/dartsass/transform.goindex e3d5823e9..680301b20 100644@@ -14,6 +14,7 @@ package dartsass  import (+	"context" 	"fmt" 	"io" 	"path"@@ -27,6 +28,7 @@ import ( 	"github.com/gohugoio/hugo/media"  	"github.com/gohugoio/hugo/resources"+	"github.com/gohugoio/hugo/resources/resource"  	"github.com/gohugoio/hugo/resources/internal" 	"github.com/gohugoio/hugo/resources/resource_transformers/tocss/sass"@@ -38,6 +40,10 @@ import ( 	"github.com/bep/godartsass/v2" ) +// Prefix for canonical URLs of stylesheets resolved in the user provided import context.+// Note: This prefix must be all lower case.+const dartSassImportContextPrefix = "hugoimportcontext:"+ // Supports returns whether sass, dart-sass, or dart-sass-embedded is found in $PATH. func Supports() bool { 	if htesting.SupportsAll() {@@ -76,6 +82,11 @@ func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error { 		filename += t.c.sfs.RealFilename(ctx.SourcePath) 	} +	var ic resource.ResourceGetter+	if opts.ImportContext != nil {+		ic = resource.NewCachedResourceGetter(opts.ImportContext)+	}+ 	args := godartsass.Args{ 		URL:          filename, 		IncludePaths: t.c.sfs.RealDirs(baseDir),@@ -83,6 +94,8 @@ func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error { 			baseDir:           baseDir, 			c:                 t.c, 			dependencyManager: ctx.DependencyManager,+			importContext:     ic,+			ctx:               ctx.Ctx,  			vars: opts.Vars, 		},@@ -132,6 +145,8 @@ type importResolver struct { 	baseDir           string 	c                 *Client 	dependencyManager identity.Manager+	importContext     resource.ResourceGetter+	ctx               context.Context 	vars              map[string]any } @@ -140,6 +155,11 @@ func (t importResolver) CanonicalizeURL(url string) (string, error) { 		return strings.ToLower(url), nil 	} +	if r := t.resolveInImportContext(url); r != nil {+		t.dependencyManager.AddIdentity(identity.FirstIdentity(r))+		return dartSassImportContextPrefix + paths.ToSlashTrimLeading(resources.InternalResourceTargetPath(r)), nil+	}+ 	filePath, isURL := paths.UrlStringToFilename(url) 	var prevDir string 	var pathDir string@@ -160,21 +180,7 @@ func (t importResolver) CanonicalizeURL(url string) (string, error) { 	name := filepath.Base(filePath)  	// Pick the first match.-	var namePatterns []string-	if strings.Contains(name, ".") {-		namePatterns = []string{"_%s", "%s"}-	} else if strings.HasPrefix(name, "_") {-		namePatterns = []string{"_%s.scss", "_%s.sass", "_%s.css"}-	} else {-		namePatterns = []string{-			"_%s.scss", "%s.scss",-			"_%s.sass", "%s.sass",-			"_%s.css", "%s.css",-			"%s/_index.scss", "%s/_index.sass",-			"%s/index.scss", "%s/index.sass",-		}-	}-+	namePatterns := sassNamePatterns(name) 	name = strings.TrimPrefix(name, "_")  	for _, namePattern := range namePatterns {@@ -192,21 +198,72 @@ func (t importResolver) CanonicalizeURL(url string) (string, error) { 	return "", nil } +func sassNamePatterns(name string) []string {+	if strings.Contains(name, ".") {+		return []string{"_%s", "%s"}+	}+	if strings.HasPrefix(name, "_") {+		return []string{"_%s.scss", "_%s.sass", "_%s.css"}+	}+	return []string{+		"_%s.scss", "%s.scss",+		"_%s.sass", "%s.sass",+		"_%s.css", "%s.css",+		"%s/_index.scss", "%s/_index.sass",+		"%s/index.scss", "%s/index.sass",+	}+}++// resolveInImportContext resolves url in the user provided import context, if any,+// using the same name patterns as for the file system.+func (t importResolver) resolveInImportContext(url string) resource.Resource {+	if t.importContext == nil {+		return nil+	}+	url = strings.TrimPrefix(url, dartSassImportContextPrefix)+	if r := t.importContext.Get(url); r != nil {+		return r+	}+	dir, name := path.Split(url)+	namePatterns := sassNamePatterns(name)+	name = strings.TrimPrefix(name, "_")+	for _, namePattern := range namePatterns {+		if r := t.importContext.Get(path.Join(dir, fmt.Sprintf(namePattern, name))); r != nil {+			return r+		}+	}+	return nil+}+ func (t importResolver) Load(url string) (godartsass.Import, error) { 	if subPath, ok := sass.HugoVarsSubPath(url); ok { 		return godartsass.Import{ 			Content: sass.CreateVarsStyleSheet(sass.TranspilerDart, sass.ResolveVars(t.vars, subPath)), 		}, nil 	}++	if strings.HasPrefix(url, dartSassImportContextPrefix) {+		r := t.resolveInImportContext(url)+		if r == nil {+			return godartsass.Import{}, fmt.Errorf("could not find %q in the import context", url)+		}+		content, err := resources.InternalResourceSourceContent(t.ctx, r)+		return godartsass.Import{Content: content, SourceSyntax: sassSourceSyntax(url)}, err+	}+ 	filename, _ := paths.UrlStringToFilename(url) 	b, err := afero.ReadFile(hugofs.Os, filename) -	sourceSyntax := godartsass.SourceSyntaxSCSS-	if strings.HasSuffix(filename, ".sass") {-		sourceSyntax = godartsass.SourceSyntaxSASS-	} else if strings.HasSuffix(filename, ".css") {-		sourceSyntax = godartsass.SourceSyntaxCSS-	}+	return godartsass.Import{Content: string(b), SourceSyntax: sassSourceSyntax(filename)}, err+} -	return godartsass.Import{Content: string(b), SourceSyntax: sourceSyntax}, err+func sassSourceSyntax(name string) godartsass.SourceSyntax {+	switch {+	case strings.HasSuffix(name, ".sass"):+		return godartsass.SourceSyntaxSASS+	case strings.HasSuffix(name, ".css"):+		return godartsass.SourceSyntaxCSS+	default:+		return godartsass.SourceSyntaxSCSS+	} }tpl/css/build_integration_test.goindex 31b692a8e..1818bcf11 100644@@ -731,3 +731,181 @@ body { 		"--text-color: #333;", 	) }++func TestCSSBuildImportContext(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+-- assets/foo.css --+body { color: orange; }+-- assets/css/main.css --+@import "foo.css" screen;+@import "bar.css" print;+p {+  font-color: red;+}+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" "body { color: blue; }" }}+{{ $bar := resources.FromString "bar.css" "body { color: green; }" }}+{{/* resource.Resources implements the resources.ResourceGetter interface (the type of importContext). */}}+{{ $resources := slice  $foo $bar}}+{{ $opts := dict "minify" true "importContext" $resources }}+{{ $css := resources.Get "css/main.css" | css.Build $opts }}+CSS: {{ $css.RelPermalink }}|+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/css/main.css", `@media screen{body{color:#00f}}@media print{body{color:green}}p{font-color:red}`)+}++func TestCSSBuildImportContextChromaStyles(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["taxonomy", "term", "rss", "sitemap", "section", "page"]+[markup.highlight]+style = "monokai"+-- assets/css/components/all.css --+@import "./chroma-light.css";+@import "./chroma-dark.css" (prefers-color-scheme: dark);+-- assets/css/main.css --+@import "./components/all.css";++:root {+  color-scheme: light dark;+}++-- layouts/home.html --+{{ $light := css.ChromaStyles (dict "targetPath" "css/components/chroma-light.css" "style" "github" "mode" "light") }}+{{ $dark := css.ChromaStyles (dict "targetPath" "css/components/chroma-dark.css" "style" "github" "mode" "dark") }}+{{ $opts := dict "minify" true "importContext" (slice $light $dark) }}+{{ $css := resources.Get "css/main.css" | css.Build $opts }}+CSS: {{ $css.RelPermalink }}|+`++	b := hugolib.Test(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/index.html", "CSS: /css/main.css|")+	b.AssertFileContent("public/css/main.css", ".bg{background-color:#f7f7f7}.chroma", "@media(prefers-color-scheme:dark){.bg{color:#e6edf3")+}++func TestCSSBuildImportContextHashes(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+-- assets/foo.css --+body { color: orange; }+-- assets/css/main.css --+@import "foo.css" screen;+@import "bar.css" print;+p {+  font-color: red;+}+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" "body { color: blue; }" }}|+{{ $foo2 := resources.FromString "foo2.css" "body { color: blue; }" }}|+{{ $foo3 := resources.FromString "foo.css" "body { color: indigo; }" }}|+{{ $bar := resources.FromString "bar.css" "body { color: green; }" }}|+{{ $resources := slice $foo $bar}}+{{ $resourcesMount1 := $resources.Mount "a" "b"}}+{{ $resourcesMount2 := $resources.Mount "a" "c"}}+{{ $opts := dict "minify" true "importContext" $resources }}+foo: {{ $foo | testinginternal.HashString }}|+foo2: {{ $foo2 | testinginternal.HashString }}|+foo3: {{ $foo3 | testinginternal.HashString }}|+bar: {{ $bar | testinginternal.HashString }}|+resources: {{ $resources | testinginternal.HashString }}|+resourcesMount1: {{ $resourcesMount1 | testinginternal.HashString }}|+resourcesMount2: {{ $resourcesMount2 | testinginternal.HashString }}|+resources namespace: {{ resources | testinginternal.HashString }}|+opts: {{ $opts | testinginternal.HashString }}|+home: {{ . | testinginternal.HashString }}|{{ .Key }}|+slice with Page: {{ slice $foo $bar . | testinginternal.HashString }}|+map with Page: {{ dict "foo" $foo "bar" $bar "page" . | testinginternal.HashString }}|+{{ $css := resources.Get "css/main.css" | css.Build $opts -}}+css: {{ $css | testinginternal.HashString }}|+cached1: {{ testinginternal.NewCachedResourceGetter $resources resources | testinginternal.HashString}}+cached2: {{ testinginternal.NewCachedResourceGetter $resources | testinginternal.HashString}}+cached3: {{ testinginternal.NewCachedResourceGetter $resources resources $resourcesMount1 $resourcesMount2 | testinginternal.HashString}}+++`++	for range 2 {++		b := hugolib.Test(t, files, hugolib.TestOptOsFs())++		b.AssertFileContent("public/index.html", `+foo: 17610550322594361312|+foo2: 12741631597870435822|+foo3: 4488319114298108946|+bar: 11981658863051989001|+resources: 10963320145636139629|+resourcesMount1: 7843365040860281860|+resourcesMount2: 10632811173795339581|+resources namespace: 12714111578321948564|+opts: 7538269917289793785|+css: 8075855322897706813|+home: 166103792234269065|/html|+slice with Page: 7769684332502419906|+map with Page: 10393165700333352395|+cached1: 7064840587060576200+cached2: 6730658186132701788+cached3: 13761938017162285970+`)++	}+}++func TestCSSBuildImportContextEdit(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableLiveReload = true+-- assets/css/common/baz.css --+body { color: purple; }+-- assets/css/main.css --+@import "foo.css" screen;+@import "bar.css" print;+@import "baz.css" screen and (min-width: 768px);+p {+  font-color: red;+}+-- layouts/home.html --+{{ $foo := resources.FromString "foo.css" "body { color: blue; }" }}+{{ $bar := resources.FromString "bar.css" "body { color: green; }" }}+{{ $common := resources.Match "/css/common/*.css" }}+{{ $commonMount := ($common.Mount "/css/common" ".")}}+{{ $resources := slice $foo $bar }}+{{ $opts := dict "minify" true "importContext" (slice $resources $commonMount) }}+resources: {{ $resources | testinginternal.HashString }}|+{{ $css := resources.Get "css/main.css" | css.Build $opts }}+CSS: {{ $css.RelPermalink }}|+`++	b := hugolib.TestRunning(t, files, hugolib.TestOptOsFs())++	b.AssertFileContent("public/css/main.css", `+@media screen{body{color:#00f}}@media print{body{color:green}}+@media screen and (min-width:768px){body{color:purple}}+`)++	// Edit resource built with resources.FromString.+	b.EditFileReplaceAll("layouts/home.html", "color: green", "color: yellow").Build()+	b.AssertFileContent("public/css/main.css", `+@media screen{body{color:#00f}}@media print{body{color:#ff0}}+@media screen and (min-width:768px){body{color:purple}}+`)++	// Edit resource in the mounted slice.+	b.EditFileReplaceAll("assets/css/common/baz.css", "purple", "orange").Build()+	b.AssertFileContent("public/css/main.css", `+@media screen{body{color:#00f}}@media print{body{color:#ff0}}+@media screen and (min-width:768px){body{color:orange}}+`)+}tpl/resources/resources.goindex 2512b5ce9..aae6ac1f3 100644@@ -58,7 +58,10 @@ func New(deps *deps.Deps) (*Namespace, error) { 	}, nil } -var _ resource.ResourceFinder = (*Namespace)(nil)+var (+	_ resource.ResourceFinder = (*Namespace)(nil)+	_ resource.Identifier     = (*Namespace)(nil)+)  // Namespace provides template functions for the "resources" namespace. type Namespace struct {@@ -300,3 +303,8 @@ func (ns *Namespace) PostProcess(r resource.Resource) (postpub.PostPublishedReso 	hugo.DeprecateWithLogger("resources.PostProcess", "Use templates.Defer instead. See https://gohugo.io/functions/templates/defer/", "v0.164.0", ns.deps.Log.Logger()) 	return ns.deps.ResourceSpec.PostProcess(r) }++// For internal use only.+func (ns *Namespace) Key() string {+	return "tpl.resources"+}tpl/testinginternal/init.gonew file mode 100644index 000000000..213e81b79@@ -0,0 +1,38 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package testinginternal++import (+	"context"++	"github.com/gohugoio/hugo/deps"+	"github.com/gohugoio/hugo/tpl/internal"+)++const name = "testinginternal"++func init() {+	f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {+		ctx := New(d)++		ns := &internal.TemplateFuncsNamespace{+			Name:    name,+			Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil },+		}++		return ns+	}++	internal.AddTemplateFuncsNamespace(f)+}tpl/testinginternal/testinginternal.gonew file mode 100644index 000000000..80beb5939@@ -0,0 +1,41 @@+// Copyright 2026 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++// Package testinginternal provides template functions for internal use.+// //  These should not be used in user templates, as they are not guaranteed to be stable or even useful.+package testinginternal++import (+	"github.com/gohugoio/hugo/common/hashing"+	"github.com/gohugoio/hugo/deps"+	"github.com/gohugoio/hugo/resources/resource"+)++// New returns a new instance of the testinginternal-namespaced template functions.+func New(d *deps.Deps) *Namespace {+	ns := &Namespace{}++	return ns+}++// Namespace provides template functions for the "testinginternal" namespace.+type Namespace struct{}++// HashString wraps the core hashing func used for e.g. calculating resource transformation keys.+func (ns *Namespace) HashString(args ...any) string {+	return hashing.HashString(args...)+}++func (ns *Namespace) NewCachedResourceGetter(args ...any) resource.ResourceGetter {+	return resource.NewCachedResourceGetter(args...)+}tpl/tplimplinit/tplimplinit.goindex a958b0669..4dc844c7a 100644@@ -49,6 +49,7 @@ import ( 	_ "github.com/gohugoio/hugo/tpl/site" 	_ "github.com/gohugoio/hugo/tpl/strings" 	_ "github.com/gohugoio/hugo/tpl/templates"+	_ "github.com/gohugoio/hugo/tpl/testinginternal" 	_ "github.com/gohugoio/hugo/tpl/time" 	_ "github.com/gohugoio/hugo/tpl/transform" 	_ "github.com/gohugoio/hugo/tpl/urls"