transform

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Jan 7, 2026 License: GPL-3.0 Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultTarget = "ES2022"

DefaultTarget is the default TypeScript transformation target.

Variables

View Source
var (
	// ErrPoolQueueFull is returned when the work queue is at capacity
	ErrPoolQueueFull = errors.New("transform pool queue is full")
	// ErrPoolClosed is returned when attempting to submit to a closed pool
	ErrPoolClosed = errors.New("transform pool is closed")
)

Functions

func IsValidTarget

func IsValidTarget(target string) bool

IsValidTarget checks if a target string is valid

func NewCSS

func NewCSS(config CSSConfig) middleware.Middleware

NewCSS creates a middleware that transforms CSS files to JavaScript modules

func NewTypeScript

func NewTypeScript(config TypeScriptConfig) middleware.Middleware

NewTypeScript creates a middleware that transforms TypeScript files to JavaScript

func ParseConfigFileURLRewrites added in v0.8.0

func ParseConfigFileURLRewrites(configPath string, fs platform.FileSystem) ([]cfg.URLRewrite, []string, error)

ParseConfigFileURLRewrites reads a cem.yaml config file and extracts URL rewrites. Returns URL rewrites and the absolute path of the config file (for change tracking). Returns empty slice if config file doesn't exist or has no URL rewrites.

Example config file:

serve:
  urlRewrites:
    - urlPattern: "/dist/:path*"
      urlTemplate: "/src/{{.path}}"

func ParseTsConfig added in v0.8.0

func ParseTsConfig(path string, fs platform.FileSystem) ([]cfg.URLRewrite, []string, error)

ParseTsConfig reads a tsconfig.json file and extracts URL rewrites. Returns a slice of URLRewrite objects for src/dist separation and a list of all visited tsconfig files (for dependency tracking).

Handles tsconfig inheritance via the "extends" field (max depth: 5). Missing rootDir or outDir default to ".". Relative paths are normalized to the tsconfig directory.

Example: rootDir="./src", outDir="./dist" produces:

URLRewrite{URLPattern: "/dist/:path*", URLTemplate: "/src/{{.path}}"}

func RewriteImportAttributes

func RewriteImportAttributes(source []byte) ([]byte, error)

RewriteImportAttributes rewrites TypeScript/JavaScript source to convert import attributes into query parameters that can be preserved through esbuild transformation.

Example transformation:

import styles from './foo.css' with { type: 'css' }
  becomes:
import styles from './foo.css?__cem-import-attrs[type]=css'

This allows the dev server to detect and handle these imports appropriately.

func TransformCSS

func TransformCSS(source []byte, path string) string

TransformCSS transforms CSS to a JavaScript module exporting a CSSStyleSheet

func ValidateURLRewrites added in v0.8.0

func ValidateURLRewrites(urlRewrites []config.URLRewrite) error

ValidateURLRewrites validates all URL rewrites to ensure they can be compiled. This should be called during server initialization to fail fast on invalid patterns/templates.

Types

type CSSConfig

type CSSConfig struct {
	WatchDirFunc     func() string // Function to get current watch directory
	Logger           types.Logger
	ErrorBroadcaster types.ErrorBroadcaster  // Sends errors to browser error overlay
	ConfigFile       string                  // Path to config file (for error reporting)
	Enabled          bool                    // Enable/disable CSS transformation
	Include          []string                // Glob patterns to include (empty means all .css files)
	Exclude          []string                // Glob patterns to exclude
	FS               platform.FileSystem     // Filesystem abstraction for testability
	PathResolver     middleware.PathResolver // Cached path resolver for efficient URL rewriting
}

CSSConfig holds configuration for CSS transformation

type Cache

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

Cache provides thread-safe caching of transformed files with LRU eviction

func NewCache

func NewCache(maxSizeBytes int64) *Cache

NewCache creates a new transform cache with the given max size

func NewCacheWithLogger

func NewCacheWithLogger(maxSizeBytes int64, log logger.Logger) *Cache

NewCacheWithLogger creates a new transform cache with a logger

func (*Cache) Clear

func (c *Cache) Clear()

Clear removes all entries from the cache

func (*Cache) Get

func (c *Cache) Get(key CacheKey) (*CacheEntry, bool)

Get retrieves a cached entry if it exists

func (*Cache) Invalidate

func (c *Cache) Invalidate(path string) []string

Invalidate removes a file and all its transitive dependents from cache Returns list of invalidated paths

func (*Cache) LogStats

func (c *Cache) LogStats()

LogStats logs cache statistics if a logger is configured

func (*Cache) Set

func (c *Cache) Set(key CacheKey, code []byte, dependencies []string)

Set adds or updates a cache entry

func (*Cache) Stats

func (c *Cache) Stats() CacheStats

Stats returns cache statistics

type CacheEntry

type CacheEntry struct {
	Code         []byte
	Dependencies []string
	Size         int64
	AccessTime   time.Time
}

CacheEntry stores transformed code and its dependencies

type CacheKey

type CacheKey struct {
	Path    string
	ModTime time.Time
	Size    int64
}

CacheKey uniquely identifies a cached transform based on file metadata

type CacheStats

type CacheStats struct {
	Hits      int64
	Misses    int64
	Evictions int64
	Entries   int
	SizeBytes int64
	MaxSize   int64
	HitRate   float64
}

CacheStats represents cache metrics

type ImportAttribute

type ImportAttribute struct {
	Key   string
	Value string
}

ImportAttribute represents a single import attribute key-value pair

type ImportRewrite

type ImportRewrite struct {
	OriginalSource string            // The original import path (e.g., './foo.css')
	Attributes     []ImportAttribute // The import attributes
	SourceNode     *ts.Node          // The source string node for rewriting
	StartByte      uint              // Start byte of the source string
	EndByte        uint              // End byte of the source string
}

ImportRewrite represents a detected import with attributes that needs rewriting

type Loader

type Loader string

Loader specifies the file type for transformation

const (
	LoaderTS  Loader = "ts"
	LoaderTSX Loader = "tsx"
	LoaderJS  Loader = "js"
	LoaderJSX Loader = "jsx"
)

type PathResolver added in v0.8.0

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

PathResolver resolves TypeScript source files from JavaScript request paths. It handles both in-place compilation (co-located .ts/.js files) and pattern-based path mappings (e.g., /elements/:slug/:rest* -> /elements/rh-{{.slug}}/{{.rest}}).

func NewPathResolver added in v0.8.0

func NewPathResolver(watchDir string, urlRewrites []config.URLRewrite, fs platform.FileSystem, logger types.Logger) *PathResolver

NewPathResolver creates a new PathResolver with the given configuration. All URL rewrites are compiled as URLPattern + template pairs during initialization.

func (*PathResolver) ResolveSourcePath added in v0.8.0

func (pr *PathResolver) ResolveSourcePath(requestPath string, sourceExt string, requestExt string) string

ResolveSourcePath resolves a source file path using path mappings. This is the generic path resolution logic shared by TypeScript and CSS resolvers.

Parameters:

  • requestPath: The requested path (e.g., "/dist/components/button.js")
  • sourceExt: The source file extension to look for (e.g., ".ts" or ".css")
  • requestExt: The request extension to replace (e.g., ".js" or ".css")

Returns the resolved source path, or empty string if not found.

For extensionless files (requestExt == ""), the path is used as-is without modification. This allows pattern matching on paths like /README or /docs/guide.

Resolution strategy: 1. Try co-located file (in-place compilation) 2. Try pattern-based path mappings (URLPattern + templates)

func (*PathResolver) ResolveTsSource added in v0.8.0

func (pr *PathResolver) ResolveTsSource(requestedJsPath string) string

ResolveTsSource finds the .ts source file for a requested .js file. Returns the request path to the .ts file (relative to watchDir with leading slash), or empty string if not found.

type Pool

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

Pool manages concurrent transform operations with backpressure

func NewPool

func NewPool(maxWorkers, queueDepth int) *Pool

NewPool creates a worker pool with specified concurrency and queue depth maxWorkers: maximum number of concurrent transform operations queueDepth: maximum number of queued tasks before rejecting new submissions

func (*Pool) Close

func (p *Pool) Close()

Close stops the pool from accepting new tasks

func (*Pool) Submit

func (p *Pool) Submit(fn func() error) error

Submit adds a task to the pool (non-blocking) Returns an error if the queue is full or the pool is closed Task execution errors are not returned (handle within task function)

func (*Pool) SubmitSync added in v0.7.2

func (p *Pool) SubmitSync(fn func() error) error

SubmitSync adds a task to the pool and waits for completion Returns the result of the task function or a pool error This is a synchronous wrapper around Submit for HTTP handler use cases

type SourceMapMode

type SourceMapMode string

SourceMapMode specifies how source maps are generated

const (
	SourceMapInline   SourceMapMode = "inline"
	SourceMapExternal SourceMapMode = "external"
	SourceMapNone     SourceMapMode = "none"
)

type Target

type Target string

Target specifies the ECMAScript target version

const (
	ES2015 Target = "es2015"
	ES2016 Target = "es2016"
	ES2017 Target = "es2017"
	ES2018 Target = "es2018"
	ES2019 Target = "es2019"
	ES2020 Target = "es2020"
	ES2021 Target = "es2021"
	ES2022 Target = "es2022"
	ES2023 Target = "es2023"
	ESNext Target = "esnext"
)

func ValidTargets

func ValidTargets() []Target

ValidTargets returns all valid target values

type TransformOptions

type TransformOptions struct {
	Loader      Loader
	Target      Target
	Sourcemap   SourceMapMode
	TsconfigRaw string // Optional tsconfig.json content as JSON string
	Sourcefile  string // Original source file path for source maps
}

TransformOptions configures the transformation

type TransformResult

type TransformResult struct {
	Code         []byte
	Map          []byte
	Dependencies []string
}

TransformResult contains the transformed code and dependencies

func TransformTypeScript

func TransformTypeScript(source []byte, opts TransformOptions) (*TransformResult, error)

TransformTypeScript transforms TypeScript source code to JavaScript using esbuild

type TsConfig added in v0.8.0

type TsConfig struct {
	CompilerOptions *TsConfigCompilerOptions `json:"compilerOptions"`
	Extends         string                   `json:"extends"`
}

TsConfig represents the structure of a tsconfig.json file. We only parse the fields we need for path resolution.

type TsConfigCompilerOptions added in v0.8.0

type TsConfigCompilerOptions struct {
	RootDir string `json:"rootDir"`
	OutDir  string `json:"outDir"`
}

TsConfigCompilerOptions represents compiler options we care about

type TypeScriptConfig

type TypeScriptConfig struct {
	WatchDirFunc     func() string // Function to get current watch directory
	TsconfigRawFunc  func() string // Function to get current tsconfig.json content
	Cache            *Cache
	Pool             *Pool // Worker pool for limiting concurrent transforms
	Logger           types.Logger
	ErrorBroadcaster types.ErrorBroadcaster
	Target           string
	Enabled          bool                    // Enable/disable TypeScript transformation
	FS               platform.FileSystem     // Filesystem abstraction for testability
	PathResolver     middleware.PathResolver // Cached path resolver for efficient URL rewriting
}

TypeScriptConfig holds configuration for TypeScript transformation

Jump to

Keyboard shortcuts

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