Documentation
¶
Overview ¶
Package jsengine provides a QJS-based JavaScript execution engine for server-side rendering Lit components with full expression fidelity.
Index ¶
- func BundleComponent(componentPath string, opts ...BundleOptions) (string, error)
- func BundleComponentModule(componentPath string, opts ...BundleOptions) (string, error)
- func BundleComponentModules(componentPaths []string, opts ...BundleOptions) (map[string]string, error)
- func BundlePreload(modulePath string, name string) (string, error)
- func BundleSharedRuntime(nodePaths []string, modules map[string]string, opts ...BundleOptions) (string, error)
- func BundleSource(source string, opts ...BundleOptions) (string, error)
- func BundleStandaloneModule(modulePath string) (string, error)
- func DiscoverExternalPackages(componentPaths []string, nodePaths []string, opts ...BundleOptions) ([]string, error)
- func DiscoverTagName(source string) (string, error)
- func ExtractDynamicImportTargets(modules map[string]string) []string
- func ExtractUnrewrittenImports(modules map[string]string) []string
- func FindAllNodeModules(fromPath string) []string
- func ResolveModulePath(specifier string, fromDir string) (string, error)
- func RewriteModuleImports(modules map[string]string, externals []string) map[string]string
- func SaveBundle(bundle string, path string) error
- type BatchRequest
- type BatchResult
- type BundleOptions
- type Engine
- func (e *Engine) Close()
- func (e *Engine) CompileModule(name string, source string) ([]byte, error)
- func (e *Engine) EvalModule(name string, source string) error
- func (e *Engine) EvalModuleBytecode(name string, bc []byte) error
- func (e *Engine) IsRegistered(tagName string) bool
- func (e *Engine) LoadBundle(bundle string) error
- func (e *Engine) LoadBundleForTag(tagName string, registry *Registry) (bool, error)
- func (e *Engine) LoadModule(name string, source string) error
- func (e *Engine) LoadModuleBytecode(name string, bc []byte) error
- func (e *Engine) RenderBatch(requests []BatchRequest) ([]BatchResult, error)
- func (e *Engine) RenderElement(tagName string, attrs map[string]string) (*RenderResult, error)
- func (e *Engine) Reset() error
- func (e *Engine) SetPreloadModules(modules []string)
- func (e *Engine) SetRuntimeExternals(externals []string)
- type EnginePool
- type ImportMap
- type Registry
- func (r *Registry) BaseDir() string
- func (r *Registry) DynamicImportTargets() []string
- func (r *Registry) DynamicModules() map[string]string
- func (r *Registry) Has(tagName string) bool
- func (r *Registry) HasBytecode() bool
- func (r *Registry) HasPath(path string) bool
- func (r *Registry) IsUnregistered(tagName string) bool
- func (r *Registry) LoadCompiled(path string) error
- func (r *Registry) LoadDir(dir string) error
- func (r *Registry) LoadFile(path string) error
- func (r *Registry) LoadSourceDir(dir string) error
- func (r *Registry) Lookup(tagName string) string
- func (r *Registry) LookupBytecode(name string) []byte
- func (r *Registry) LookupModule(tagName string) string
- func (r *Registry) MarkPath(path string)
- func (r *Registry) MarkUnregistered(tagName string)
- func (r *Registry) ProcessedPaths() []string
- func (r *Registry) Register(tagName string, source string)
- func (r *Registry) RegisterModule(tagName string, source string)
- func (r *Registry) RuntimeExternals() []string
- func (r *Registry) SetBaseDir(dir string)
- func (r *Registry) SetBytecode(name string, bc []byte)
- func (r *Registry) SetDynamicImportTargets(targets []string)
- func (r *Registry) SetDynamicModule(specifier, source string)
- func (r *Registry) SetRuntimeExternals(externals []string)
- func (r *Registry) SetSharedRuntime(source string)
- func (r *Registry) SharedRuntime() string
- func (r *Registry) TagNames() []string
- func (r *Registry) Unregistered() []string
- type RenderResult
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BundleComponent ¶
func BundleComponent(componentPath string, opts ...BundleOptions) (string, error)
BundleComponent uses esbuild to bundle a Lit component source file along with its dependencies (lit, DOM shim) into a single JS string that can be executed in QJS.
func BundleComponentModule ¶
func BundleComponentModule(componentPath string, opts ...BundleOptions) (string, error)
BundleComponentModule produces an ES module for a component with shared dependencies marked as external. The output keeps import/export statements so it can be loaded via Engine.EvalModule. Callers should use RewriteModuleImports to rewrite external specifiers to "@golit/runtime" after extracting import specifiers for runtime building. The domshim and template collector are injected so the module works both with and without a shared runtime.
func BundleComponentModules ¶
func BundleComponentModules(componentPaths []string, opts ...BundleOptions) (map[string]string, error)
BundleComponentModules produces thin ES modules for multiple components in a single esbuild invocation. Returns a map from input path to module source.
func BundlePreload ¶
BundlePreload bundles a module and wraps it so its exports are registered in the __preloadedModules registry under the given name. Unlike BundleComponent, this captures ESM exports into the registry instead of stripping them.
func BundleSharedRuntime ¶
func BundleSharedRuntime(nodePaths []string, modules map[string]string, opts ...BundleOptions) (string, error)
BundleSharedRuntime produces a single ES module containing all shared dependencies that the thin component modules import. The output keeps ESM export syntax intact so it can be loaded via Engine.LoadModule("@golit/runtime", source). modules is the map of thin module sources (from BundleComponentModules) used to discover which external specifiers to include.
func BundleSource ¶
func BundleSource(source string, opts ...BundleOptions) (string, error)
BundleSource bundles a component from inline JS/TS source code (no file on disk). Uses esbuild's Stdin option instead of EntryPoints.
func BundleStandaloneModule ¶
BundleStandaloneModule bundles a module file into a self-contained ES module with exports preserved. Used for registering dynamic import targets as named QJS modules so import("specifier") resolves natively.
func DiscoverExternalPackages ¶
func DiscoverExternalPackages(componentPaths []string, nodePaths []string, opts ...BundleOptions) ([]string, error)
DiscoverExternalPackages runs esbuild with Metafile enabled on all component entry points to discover which node_modules packages they depend on. Returns esbuild-compatible external patterns (pkg + pkg/*).
func DiscoverTagName ¶
DiscoverTagName extracts the custom element tag name from a module source using a regex. Returns the tag name or an error if none found.
func ExtractDynamicImportTargets ¶
ExtractDynamicImportTargets scans thin module sources for dynamic import() calls and returns non-local, non-runtime specifiers. Matches patterns like: import("@rhds/tokens/css/default-theme.css.js")
func ExtractUnrewrittenImports ¶
ExtractUnrewrittenImports scans rewritten thin module sources for static imports that still reference external specifiers (not @golit/runtime, not relative). These are default imports that were intentionally not rewritten and need standalone module registration.
func FindAllNodeModules ¶
FindAllNodeModules walks up from the given path and returns all node_modules directories found. This handles nested node_modules where a package's dependencies are split across multiple levels.
func ResolveModulePath ¶
ResolveModulePath resolves a module specifier to a file path. Handles bare package names (e.g. "lit"), scoped packages ("@rhds/tokens"), and subpath specifiers ("@rhds/tokens/css/default-theme.css.js").
func RewriteModuleImports ¶
RewriteModuleImports rewrites import specifiers for shared packages in all module sources to "@golit/runtime". The externals list determines which specifiers are considered shared. Call this after extractExternalImports if you need the raw specifiers for runtime building.
func SaveBundle ¶
SaveBundle writes a bundle string to a file atomically.
Types ¶
type BatchRequest ¶
type BatchRequest struct {
ID int `json:"id"`
TagName string `json:"tagName"`
Attrs map[string]string `json:"attrs"`
}
BatchRequest describes a single element to render in a batch call.
type BatchResult ¶
type BatchResult struct {
ID int `json:"id"`
HTML string `json:"html"`
CSS string `json:"css"`
TagName string `json:"tagName"`
Error string `json:"error,omitempty"`
}
BatchResult contains the output of rendering a single element in a batch.
type BundleOptions ¶
type BundleOptions struct {
Minify bool
ExternalPackages []string
Format api.Format
Target api.Target
Platform api.Platform
MainFields []string
Conditions []string
}
BundleOptions configures the component bundling.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine executes Lit components in QJS for SSR rendering.
func (*Engine) CompileModule ¶
CompileModule compiles an ES module to bytecode without executing it.
func (*Engine) EvalModule ¶
EvalModule evaluates an ES module, executing its body and registering any custom elements it defines. Use for component modules that need their side-effects (like customElements.define) to run.
func (*Engine) EvalModuleBytecode ¶
EvalModuleBytecode loads and executes a pre-compiled ES module from bytecode.
func (*Engine) IsRegistered ¶
IsRegistered checks if a tag name is registered in the QJS custom elements registry.
func (*Engine) LoadBundle ¶
LoadBundle loads a pre-bundled component JS file into the engine as a script. Can be called multiple times to load multiple components. If preload modules are set, dynamic import() calls for those modules are replaced with synchronous lookups into __preloadedModules.
func (*Engine) LoadBundleForTag ¶
LoadBundleForTag loads a component from the registry for a specific tag name. Returns (true, nil) if loaded or already loaded, (false, nil) if the tag is not in the registry, or (false, err) if loading failed. If a shared runtime is present, it is loaded first. All registry content is evaluated as ES modules via EvalModule (registry stores .golit.module.js).
func (*Engine) LoadModule ¶
LoadModule pre-registers a named ES module in the QJS module cache without executing it. Other modules can then import from it by name.
func (*Engine) LoadModuleBytecode ¶
LoadModuleBytecode loads a pre-compiled module into the module cache from bytecode without executing it.
func (*Engine) RenderBatch ¶
func (e *Engine) RenderBatch(requests []BatchRequest) ([]BatchResult, error)
RenderBatch renders multiple custom elements in a single QJS call. Uses Go-side render result caching to skip JS execution for previously-seen (tagName, attrs) combinations, and calls a pre-registered JS function to avoid re-parsing the render loop.
func (*Engine) RenderElement ¶
RenderElement creates an instance of a custom element, sets attributes on it, calls render(), and returns the rendered HTML and CSS.
func (*Engine) Reset ¶
Reset tears down the current QJS runtime and creates a new one, clearing all global state. Previously loaded bundles must be re-loaded afterward.
func (*Engine) SetPreloadModules ¶
SetPreloadModules tells the engine which module names have been preloaded into globalThis.__preloadedModules. Dynamic import() calls for these modules will be shimmed to resolve from the preloaded registry.
func (*Engine) SetRuntimeExternals ¶
SetRuntimeExternals tells the engine which package prefixes are bundled into the @golit/runtime module. Dynamic import() calls for these packages will be rewritten to import("@golit/runtime").
type EnginePool ¶
type EnginePool struct {
// contains filtered or unexported fields
}
EnginePool manages a fixed set of QJS Engine instances for concurrent use. Each engine is an isolated WASM module instance (via wazero) and can safely run in its own goroutine.
func NewEnginePool ¶
func NewEnginePool(size int) (*EnginePool, error)
NewEnginePool creates a pool of size engines. Each engine is initialized with helpers but no bundles loaded yet — call PreloadAll before dispatch.
func (*EnginePool) Available ¶
func (p *EnginePool) Available() int
Available returns the number of idle engines currently in the pool.
func (*EnginePool) Get ¶
func (p *EnginePool) Get() *Engine
Get checks out an engine from the pool. Blocks if none are available.
func (*EnginePool) PreloadAll ¶
func (p *EnginePool) PreloadAll(registry *Registry, preloadModules []string, preloadBundles ...string) error
PreloadAll drains every engine from the pool, configures preload modules, loads any raw preload bundles, bundles dynamic import targets as preloads, loads the shared runtime (if present), then loads all registry component bundles/modules. A dedicated compiler engine compiles modules to bytecode and stores them in the registry; subsequent engines load from bytecode for faster initialization. After this call the registry must be treated as read-only.
func (*EnginePool) Size ¶
func (p *EnginePool) Size() int
Size returns the number of engines in the pool.
type ImportMap ¶
type ImportMap struct {
// Imports maps bare-module specifiers to resolved URLs/paths.
Imports map[string]string `json:"imports"`
// Scopes provides context-dependent import resolution overrides.
Scopes map[string]map[string]string `json:"scopes,omitempty"`
// BaseDir is the directory relative to which map values are resolved.
BaseDir string `json:"-"`
// contains filtered or unexported fields
}
ImportMap represents a parsed import map per the WICG specification. https://github.com/WICG/import-maps
func LoadImportMapFile ¶
LoadImportMapFile reads and parses an import map from a JSON file.
func ParseImportMap ¶
ParseImportMap parses an import map from a JSON string. baseDir is the directory relative to which paths in the map are resolved.
func (*ImportMap) Resolve ¶
Resolve resolves a bare-module specifier using the import map. Returns the resolved file path, or "" if the specifier doesn't match.
Resolution follows the import map spec:
- Exact match: "lit" -> "./node_modules/lit/index.js"
- Prefix match: "@rhds/elements/" -> "./node_modules/@rhds/elements/elements/" so "@rhds/elements/rh-badge/rh-badge.js" resolves to "./node_modules/@rhds/elements/elements/rh-badge/rh-badge.js"
func (*ImportMap) ResolveAll ¶
ResolveAll resolves a list of specifiers and returns the file paths that could be resolved. Unresolvable specifiers are silently skipped.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry manages loaded component modules and tracks which tag names are available for rendering. All methods are safe for concurrent use.
func NewRegistry ¶
func NewRegistry() *Registry
NewRegistry creates an empty registry for component modules and optional shared runtime state.
func (*Registry) DynamicImportTargets ¶
DynamicImportTargets returns a copy of the module specifiers found in dynamic import() calls within thin modules.
func (*Registry) DynamicModules ¶
DynamicModules returns a copy of the specifier -> ESM source map for modules that should be registered as named QJS modules.
func (*Registry) HasBytecode ¶
HasBytecode returns true if any bytecode has been cached.
func (*Registry) IsUnregistered ¶
IsUnregistered returns true if the tag has already been marked unregistered.
func (*Registry) LoadCompiled ¶
LoadCompiled loads a single pre-compiled .golit.compiled.js artifact that contains all components and a __golitRegistry manifest. The compiled artifact is treated as a single module that registers all components when evaluated.
func (*Registry) LoadDir ¶
LoadDir loads all .golit.module.js files from a directory. If a _runtime.golit.module.js file is present, it is loaded as the shared runtime. Tag names are discovered via a regex pre-pass. Dynamic import() targets in the thin modules are collected and stored as dynamic import targets.
func (*Registry) LoadFile ¶
LoadFile loads a single .golit.module.js file and discovers its tag name. Modules that don't register any custom elements are silently skipped.
func (*Registry) LoadSourceDir ¶
LoadSourceDir bundles all .js/.ts files in a directory tree as thin ES modules and registers them. Also builds and registers the shared runtime.
func (*Registry) LookupBytecode ¶
LookupBytecode returns pre-compiled bytecode for a module name, or nil.
func (*Registry) LookupModule ¶
LookupModule returns the ES module JS for a given tag name, or "" if not found. Alias for Lookup.
func (*Registry) MarkUnregistered ¶
MarkUnregistered records a custom element tag that was encountered but not found in the registry.
func (*Registry) ProcessedPaths ¶
ProcessedPaths returns all source file paths that have been processed.
func (*Registry) RegisterModule ¶
RegisterModule adds a thin ES module by tag name (alias for Register).
func (*Registry) RuntimeExternals ¶
RuntimeExternals returns a copy of the package prefixes bundled into the shared runtime.
func (*Registry) SetBaseDir ¶
SetBaseDir stores the base directory for module resolution.
func (*Registry) SetBytecode ¶
SetBytecode stores pre-compiled bytecode for a module name.
func (*Registry) SetDynamicImportTargets ¶
SetDynamicImportTargets stores the dynamic import target specifiers.
func (*Registry) SetDynamicModule ¶
SetDynamicModule registers a standalone ES module under its specifier name.
func (*Registry) SetRuntimeExternals ¶
SetRuntimeExternals stores the package prefixes bundled into the shared runtime.
func (*Registry) SetSharedRuntime ¶
SetSharedRuntime sets the shared runtime module source.
func (*Registry) SharedRuntime ¶
SharedRuntime returns the shared runtime module source, or "" if not set.
func (*Registry) Unregistered ¶
Unregistered returns all custom element tags that were encountered but not in the registry.
type RenderResult ¶
type RenderResult struct {
// HTML is the rendered shadow DOM content (the template output).
HTML string
// CSS is the component's scoped styles (from static styles).
CSS string
// TagName is the confirmed custom element tag name.
TagName string
}
RenderResult contains the output of rendering a custom element.