jsengine

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package jsengine provides a QJS-based JavaScript execution engine for server-side rendering Lit components with full expression fidelity.

Index

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

func BundlePreload(modulePath string, name string) (string, error)

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

func BundleStandaloneModule(modulePath string) (string, error)

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

func DiscoverTagName(source string) (string, error)

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

func ExtractDynamicImportTargets(modules map[string]string) []string

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

func ExtractUnrewrittenImports(modules map[string]string) []string

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

func FindAllNodeModules(fromPath string) []string

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

func ResolveModulePath(specifier string, fromDir string) (string, error)

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

func RewriteModuleImports(modules map[string]string, externals []string) map[string]string

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

func SaveBundle(bundle string, path string) error

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 NewEngine

func NewEngine() (*Engine, error)

NewEngine creates a new QJS engine instance.

func (*Engine) Close

func (e *Engine) Close()

Close releases the QJS runtime resources.

func (*Engine) CompileModule

func (e *Engine) CompileModule(name string, source string) ([]byte, error)

CompileModule compiles an ES module to bytecode without executing it.

func (*Engine) EvalModule

func (e *Engine) EvalModule(name string, source string) error

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

func (e *Engine) EvalModuleBytecode(name string, bc []byte) error

EvalModuleBytecode loads and executes a pre-compiled ES module from bytecode.

func (*Engine) IsRegistered

func (e *Engine) IsRegistered(tagName string) bool

IsRegistered checks if a tag name is registered in the QJS custom elements registry.

func (*Engine) LoadBundle

func (e *Engine) LoadBundle(bundle string) error

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

func (e *Engine) LoadBundleForTag(tagName string, registry *Registry) (bool, error)

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

func (e *Engine) LoadModule(name string, source string) error

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

func (e *Engine) LoadModuleBytecode(name string, bc []byte) error

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

func (e *Engine) RenderElement(tagName string, attrs map[string]string) (*RenderResult, error)

RenderElement creates an instance of a custom element, sets attributes on it, calls render(), and returns the rendered HTML and CSS.

func (*Engine) Reset

func (e *Engine) Reset() error

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

func (e *Engine) SetPreloadModules(modules []string)

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

func (e *Engine) SetRuntimeExternals(externals []string)

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) Close

func (p *EnginePool) Close()

Close releases all engines 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) Put

func (p *EnginePool) Put(e *Engine)

Put returns an engine to the pool.

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

func LoadImportMapFile(path string) (*ImportMap, error)

LoadImportMapFile reads and parses an import map from a JSON file.

func ParseImportMap

func ParseImportMap(jsonStr string, baseDir string) (*ImportMap, error)

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

func (im *ImportMap) Resolve(specifier string) string

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

func (im *ImportMap) ResolveAll(specifiers []string) []string

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) BaseDir

func (r *Registry) BaseDir() string

BaseDir returns the directory from which modules were loaded.

func (*Registry) DynamicImportTargets

func (r *Registry) DynamicImportTargets() []string

DynamicImportTargets returns a copy of the module specifiers found in dynamic import() calls within thin modules.

func (*Registry) DynamicModules

func (r *Registry) DynamicModules() map[string]string

DynamicModules returns a copy of the specifier -> ESM source map for modules that should be registered as named QJS modules.

func (*Registry) Has

func (r *Registry) Has(tagName string) bool

Has returns true if a module is registered for the given tag name.

func (*Registry) HasBytecode

func (r *Registry) HasBytecode() bool

HasBytecode returns true if any bytecode has been cached.

func (*Registry) HasPath

func (r *Registry) HasPath(path string) bool

HasPath returns true if a source file path has already been processed.

func (*Registry) IsUnregistered

func (r *Registry) IsUnregistered(tagName string) bool

IsUnregistered returns true if the tag has already been marked unregistered.

func (*Registry) LoadCompiled

func (r *Registry) LoadCompiled(path string) error

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

func (r *Registry) LoadDir(dir string) error

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

func (r *Registry) LoadFile(path string) error

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

func (r *Registry) LoadSourceDir(dir string) error

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) Lookup

func (r *Registry) Lookup(tagName string) string

Lookup returns the ES module JS for a given tag name, or "" if not found.

func (*Registry) LookupBytecode

func (r *Registry) LookupBytecode(name string) []byte

LookupBytecode returns pre-compiled bytecode for a module name, or nil.

func (*Registry) LookupModule

func (r *Registry) LookupModule(tagName string) string

LookupModule returns the ES module JS for a given tag name, or "" if not found. Alias for Lookup.

func (*Registry) MarkPath

func (r *Registry) MarkPath(path string)

MarkPath records a source file path as processed.

func (*Registry) MarkUnregistered

func (r *Registry) MarkUnregistered(tagName string)

MarkUnregistered records a custom element tag that was encountered but not found in the registry.

func (*Registry) ProcessedPaths

func (r *Registry) ProcessedPaths() []string

ProcessedPaths returns all source file paths that have been processed.

func (*Registry) Register

func (r *Registry) Register(tagName string, source string)

Register adds a module by tag name directly (for programmatic use).

func (*Registry) RegisterModule

func (r *Registry) RegisterModule(tagName string, source string)

RegisterModule adds a thin ES module by tag name (alias for Register).

func (*Registry) RuntimeExternals

func (r *Registry) RuntimeExternals() []string

RuntimeExternals returns a copy of the package prefixes bundled into the shared runtime.

func (*Registry) SetBaseDir

func (r *Registry) SetBaseDir(dir string)

SetBaseDir stores the base directory for module resolution.

func (*Registry) SetBytecode

func (r *Registry) SetBytecode(name string, bc []byte)

SetBytecode stores pre-compiled bytecode for a module name.

func (*Registry) SetDynamicImportTargets

func (r *Registry) SetDynamicImportTargets(targets []string)

SetDynamicImportTargets stores the dynamic import target specifiers.

func (*Registry) SetDynamicModule

func (r *Registry) SetDynamicModule(specifier, source string)

SetDynamicModule registers a standalone ES module under its specifier name.

func (*Registry) SetRuntimeExternals

func (r *Registry) SetRuntimeExternals(externals []string)

SetRuntimeExternals stores the package prefixes bundled into the shared runtime.

func (*Registry) SetSharedRuntime

func (r *Registry) SetSharedRuntime(source string)

SetSharedRuntime sets the shared runtime module source.

func (*Registry) SharedRuntime

func (r *Registry) SharedRuntime() string

SharedRuntime returns the shared runtime module source, or "" if not set.

func (*Registry) TagNames

func (r *Registry) TagNames() []string

TagNames returns all registered tag names.

func (*Registry) Unregistered

func (r *Registry) Unregistered() []string

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.

Jump to

Keyboard shortcuts

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