asset

package
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 29, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

Package asset handles CSS/JS bundling, image optimization, and content-hashed asset pipelines.

Index

Constants

This section is empty.

Variables

View Source
var ErrAVIFNotAvailable = errors.New("AVIF encoding not available: rebuild with -tags avif")

ErrAVIFNotAvailable is returned when AVIF encoding is requested but the build was not compiled with the avif build tag. Declared in an untagged file so both build modes compile (image.go references it unconditionally).

Functions

func Fingerprint

func Fingerprint(data []byte) string

Fingerprint computes a content hash for the given data. Returns the first 8 hex characters of the SHA-256 hash.

func FingerprintFile

func FingerprintFile(path string) (string, error)

FingerprintFile reads a file and returns its content fingerprint.

func FingerprintedName

func FingerprintedName(name, hash string) string

FingerprintedName inserts a hash into a filename before the extension. Example: FingerprintedName("main.css", "a1b2c3d4") → "main.a1b2c3d4.css"

func GetResource

func GetResource(resources []engine.Resource, name string) *engine.Resource

GetResource returns the first resource matching the given name (exact match).

func ImageSize added in v1.1.0

func ImageSize(path string) (width, height int, err error)

ImageSize reads image dimensions without decoding the full image.

func IsImage

func IsImage(name string) bool

IsImage returns true if the file extension indicates an image format.

func MatchResources

func MatchResources(resources []engine.Resource, pattern string) []engine.Resource

MatchResources returns all resources whose Name matches the glob pattern.

func MediaTypeFromExt

func MediaTypeFromExt(ext string) string

MediaTypeFromExt returns the MIME type for a file extension. The extension should include the leading dot (e.g., ".jpg").

func RenderPicture

func RenderPicture(src, alt string, width, height int, variants []ImageVariant, lqip string, lazy bool, opts ...PictureOptions) string

RenderPicture generates HTML for a responsive <picture> element. If no variants are provided, falls back to a simple <img> tag.

func RenderSrcset

func RenderSrcset(variants []ImageVariant) string

RenderSrcset generates the srcset attribute value from a list of variants.

func ResourcesByType

func ResourcesByType(resources []engine.Resource, mediaType string) []engine.Resource

ResourcesByType returns all resources whose MediaType starts with the given prefix. For example, ResourcesByType(resources, "image") matches "image/jpeg", "image/png", etc.

func TransformCSS

func TransformCSS(content string, minify bool) (string, error)

TransformCSS runs esbuild's Transform API on a raw CSS string. When minify is true, whitespace and syntax are minified. When minify is false, the input is returned unchanged.

Types

type BundleResult

type BundleResult struct {
	OutputFiles []BundledFile
	Errors      []string
}

BundleResult holds the output of a bundle operation.

type BundledFile

type BundledFile struct {
	Name         string // output filename (potentially fingerprinted)
	OriginalPath string // original entry point path as referenced
	OutputURL    string // URL path (e.g., "/assets/css/main.a1b2c3d4.css")
	Content      []byte
}

BundledFile represents a single bundled output file.

type Bundler

type Bundler struct {
	Resolver  *Resolver
	DevMode   bool
	Minify    bool
	OutputDir string // absolute path to output directory
}

Bundler handles CSS/JS bundling and minification via esbuild.

func (*Bundler) BundleCSS

func (b *Bundler) BundleCSS(entryPoint string) (*BundleResult, error)

BundleCSS bundles a CSS entry point, resolving @import through the 3-layer resolver.

func (*Bundler) BundleJS

func (b *Bundler) BundleJS(entryPoint string) (*BundleResult, error)

BundleJS bundles a JS entry point, resolving imports through the 3-layer resolver.

type Cache

type Cache struct {
	Dir string // e.g., {ProjectDir}/.cache/images
}

Cache stores processed asset results keyed by source hash + processing params. Entries are stored as JSON files in the .cache/ directory.

func NewCache

func NewCache(projectDir string) *Cache

NewCache creates a cache rooted at {projectDir}/.cache/images.

func (*Cache) Get

func (c *Cache) Get(key string) (*CacheEntry, error)

Get retrieves a cached entry. Returns nil if the entry does not exist.

func (*Cache) Key

func (c *Cache) Key(sourceHash, params string) string

Key generates a cache key from a source hash and processing parameters.

func (*Cache) Put

func (c *Cache) Put(key string, entry *CacheEntry) error

Put stores a processing result in the cache.

type CacheEntry

type CacheEntry struct {
	SourceHash string         `json:"source_hash"`
	Params     string         `json:"params"`
	Variants   []ImageVariant `json:"variants"`
	LQIP       string         `json:"lqip"` // base64 data URI
}

CacheEntry holds cached image processing results.

type ImageOptions

type ImageOptions struct {
	Op      ResizeOp
	Width   int
	Height  int
	Quality int
	Formats []string
}

ImageOptions controls per-image processing parameters. Zero values mean "use config defaults".

func ParseImageOptionsFromQuery

func ParseImageOptionsFromQuery(s string) ImageOptions

ParseImageOptionsFromQuery parses a query string like "width=800&op=fill&format=webp" into ImageOptions. Used by the resize_image template function.

type ImageProcessor

type ImageProcessor struct {
	Config  *config.ImageSettings
	Cache   *Cache
	DevMode bool
}

ImageProcessor handles image resize, LQIP generation, and variant production.

func (*ImageProcessor) ProcessImage

func (p *ImageProcessor) ProcessImage(srcPath string, opts ImageOptions) ([]ImageVariant, string, error)

ProcessImage generates responsive variants and LQIP for a source image. Variant image files are saved to the cache directory (not the output directory). Use WriteProcessedImages to copy cached variants to the output directory after the writer runs. Returns variants, LQIP base64 string, and error. In DevMode, returns empty results (dimensions are already set by the enhancer).

func (*ImageProcessor) WriteProcessedImages

func (p *ImageProcessor) WriteProcessedImages(outputDir string, trackFn func(string)) (int, error)

WriteProcessedImages copies all cached image variants to the output directory. Call this after the writer has cleaned and written HTML files.

func (*ImageProcessor) WriteProcessedImagesWithOptions

func (p *ImageProcessor) WriteProcessedImagesWithOptions(outputDir string, trackFn func(string), opts WriteOptions) (int, error)

WriteProcessedImagesWithOptions copies all cached image variants to the output directory. Call this after the writer has cleaned and written HTML files.

type ImageVariant

type ImageVariant struct {
	Width    int    `json:"width"`
	Height   int    `json:"height"`   // output height (computed from resize op)
	Format   string `json:"format"`   // "jpeg", "png", "webp"
	URL      string `json:"url"`      // output URL path
	FileSize int64  `json:"fileSize"` // bytes
}

ImageVariant represents a single processed image variant (width + format).

type Manifest

type Manifest struct {
	// contains filtered or unexported fields
}

Manifest maps original asset paths to their output (potentially fingerprinted) paths.

func NewManifest

func NewManifest() *Manifest

NewManifest creates an empty asset manifest.

func (*Manifest) Add

func (m *Manifest) Add(original string, entry ManifestEntry)

Add registers an asset mapping in the manifest.

func (*Manifest) Len

func (m *Manifest) Len() int

Len returns the number of entries in the manifest.

func (*Manifest) Lookup

func (m *Manifest) Lookup(original string) (ManifestEntry, bool)

Lookup retrieves the manifest entry for an original asset path.

type ManifestEntry

type ManifestEntry struct {
	OriginalPath string         // original asset path as referenced
	OutputPath   string         // relative to output dir (e.g., "assets/main.a1b2c3d4.css")
	OutputURL    string         // URL path (e.g., "/assets/main.a1b2c3d4.css")
	Hash         string         // content hash
	Variants     []ImageVariant // image variants (Phase 10b)
	LQIP         string         // base64 LQIP data URI (Phase 10b)
}

ManifestEntry maps an original asset path to its processed output.

type PictureOptions

type PictureOptions struct {
	IncludeDimensions bool  // when false, omit width/height from <img>
	Widths            []int // configured widths for dynamic sizes attribute
}

PictureOptions controls optional rendering behavior for <picture> elements.

type Pipeline

type Pipeline struct {
	// contains filtered or unexported fields
}

Pipeline orchestrates all asset processing.

func NewPipeline

func NewPipeline(opts PipelineOptions) *Pipeline

NewPipeline creates and initializes the asset pipeline.

func (*Pipeline) BundleGlobalAssets

func (p *Pipeline) BundleGlobalAssets() error

BundleGlobalAssets processes CSS/JS entry points from the site config (head.custom_css, head.custom_js). Bundled files are written to the output directory and registered in the manifest.

func (*Pipeline) EnhanceResources

func (p *Pipeline) EnhanceResources(page *engine.Page) error

EnhanceResources populates resource metadata for a page's bundle assets.

func (*Pipeline) GlobalCSSURLs

func (p *Pipeline) GlobalCSSURLs() []string

GlobalCSSURLs returns the output URLs of all CSS files bundled from head.custom_css.

func (*Pipeline) ImageProcessor

func (p *Pipeline) ImageProcessor() *ImageProcessor

ImageProcessor returns the image processor for use in markdown rendering.

func (*Pipeline) Manifest

func (p *Pipeline) Manifest() *Manifest

Manifest returns the asset manifest for template function use.

func (*Pipeline) OutputDir

func (p *Pipeline) OutputDir() string

OutputDir returns the configured output directory.

func (*Pipeline) Resolver

func (p *Pipeline) Resolver() *Resolver

Resolver returns the asset resolver for template function use.

func (*Pipeline) WriteBundleAssets

func (p *Pipeline) WriteBundleAssets(pages []*engine.Page, outputDir string, trackFn func(string)) error

WriteBundleAssets copies bundle assets from their source locations to the output directory. If trackFn is non-nil, each written path is reported for orphan tracking.

func (*Pipeline) WriteBundleAssetsWithOptions

func (p *Pipeline) WriteBundleAssetsWithOptions(pages []*engine.Page, outputDir string, trackFn func(string), opts WriteOptions) error

WriteBundleAssetsWithOptions copies bundle assets from their source locations to the output directory.

func (*Pipeline) WriteBundledFiles

func (p *Pipeline) WriteBundledFiles(outputDir string, trackFn func(string)) error

WriteBundledFiles writes bundled CSS/JS files to the output directory. If trackFn is non-nil, each written path is reported for orphan tracking.

func (*Pipeline) WriteBundledFilesWithOptions

func (p *Pipeline) WriteBundledFilesWithOptions(outputDir string, trackFn func(string), opts WriteOptions) error

WriteBundledFilesWithOptions writes bundled CSS/JS files to the output directory.

func (*Pipeline) WriteProcessedImages

func (p *Pipeline) WriteProcessedImages(outputDir string, trackFn func(string)) (int, error)

WriteProcessedImages copies cached image variants to the output directory. If trackFn is non-nil, each written path is reported for orphan tracking. Returns the number of image variants written.

func (*Pipeline) WriteProcessedImagesWithOptions

func (p *Pipeline) WriteProcessedImagesWithOptions(outputDir string, trackFn func(string), opts WriteOptions) (int, error)

WriteProcessedImagesWithOptions copies cached image variants to the output directory.

type PipelineOptions

type PipelineOptions struct {
	ProjectDir string
	OutputDir  string
	Config     *config.SiteConfig
	ThemeName  string
	EmbeddedFS fs.FS
	DevMode    bool
}

PipelineOptions configures the asset pipeline.

type ProcessedImage

type ProcessedImage struct {
	Src      string         // original/fallback src URL
	Alt      string         // alt text
	Width    int            // original width
	Height   int            // original height
	LQIP     string         // base64 data URI for blur-up placeholder
	Variants []ImageVariant // responsive variants with srcset
	Loading  string         // "lazy" or "eager"
}

ProcessedImage holds all data needed to render a responsive image.

type ResizeOp

type ResizeOp string

ResizeOp specifies how an image should be resized.

const (
	ResizeOpScale     ResizeOp = "scale"
	ResizeOpFitWidth  ResizeOp = "fit_width"
	ResizeOpFitHeight ResizeOp = "fit_height"
	ResizeOpFit       ResizeOp = "fit"
	ResizeOpFill      ResizeOp = "fill"
)

type Resolver

type Resolver struct {
	ProjectDir string
	ThemeName  string
	EmbeddedFS fs.FS
}

Resolver implements 3-layer asset lookup: user assets/ → theme assets/ → embedded.

func (*Resolver) Resolve

func (r *Resolver) Resolve(assetPath string) (string, error)

Resolve returns the absolute filesystem path for a named asset. Lookup order:

  1. {ProjectDir}/assets/{path}
  2. {ProjectDir}/themes/{ThemeName}/assets/{path}
  3. embedded FS assets/{path}

For embedded assets, returns "embedded:{path}" since there is no filesystem path.

func (*Resolver) ResolveContent

func (r *Resolver) ResolveContent(assetPath string) ([]byte, error)

ResolveContent returns the file contents for a named asset. Uses the same 3-layer lookup as Resolve.

type ResourceEnhancer

type ResourceEnhancer struct {
	DevMode bool
}

ResourceEnhancer populates Resource metadata for page bundles.

func (*ResourceEnhancer) EnhancePageResources

func (e *ResourceEnhancer) EnhancePageResources(page *engine.Page) error

EnhancePageResources populates MediaType, Title, RelPermalink, Width, and Height for all resources attached to a page bundle.

type WriteOptions

type WriteOptions struct {
	Parallel    bool
	WorkerCount int
}

WriteOptions controls bounded parallel asset writes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL