jsruntime

package
v0.5.0-beta.2 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// EvalGlobal evaluates in the global scope
	EvalGlobal = quickjs.EvalGlobal
	// EvalModule evaluates as an ES module
	EvalModule = quickjs.EvalModule
)
View Source
const (
	MiddlewareContinue = "continue"
	MiddlewareResponse = "response"
	MiddlewareSkip     = "skip"
	MiddlewareError    = "error"
)

Middleware actions.

Variables

View Source
var (

	// ErrStopStream is returned by an APISink to end a response early without
	// it being treated as a failure (for example a HEAD request).
	ErrStopStream = errors.New("stop streaming")
)
View Source
var MatcherJS = matcherSource

MatcherJS is the Next-compatible middleware matcher compiler, shared with the Node/Bun sidecar scripts so every runtime scopes middleware identically.

Functions

func DefaultAPIWorkers added in v0.4.0

func DefaultAPIWorkers() int

DefaultAPIWorkers returns the default embedded API worker-pool size.

func EvaluateExpr

func EvaluateExpr(code string) (string, error)

EvaluateExpr evaluates a self-contained JS expression and returns its String() representation. Because QuickJS is a full ECMAScript engine, every built-in (Date, Math, String, Number, Array, Object, ...) is available - so SSR evaluation of globals like Date.now() produces a genuine JS-engine value rather than a Go approximation. Returns an error when the expression throws (e.g. it references an identifier that isn't defined).

The expression is evaluated inside a strict IIFE so it cannot leak implicit globals into the pooled VM (a fresh VM previously discarded any such state). The eval-timeout deadline is re-armed on every Execute by the bindings, so a VM is safe to reuse even after a thrown expression or a timeout.

func MiddlewarePath

func MiddlewarePath(root string) string

MiddlewarePath returns the conventional compiled middleware location, or "" when the project has none.

func ToMap

func ToMap(v any) (map[string]any, bool)

ToMap converts a quickjs object result to a Go map.

func ToNative

func ToNative(v any) any

ToNative converts a quickjs result to a native Go type. JS objects are JSON-deserialized; primitives pass through.

Types

type APIFailure

type APIFailure struct {
	Status  int
	Message string
	Stack   string
	Allow   []string
	Started bool
}

APIFailure describes a request that did not produce a response head (or a stream that broke afterwards, with Started set).

type APIRequest

type APIRequest struct {
	URL    string
	Method string
	Path   string
	// Headers are the request headers as received (multi-valued).
	Headers map[string][]string
	// Body is the raw request body; it crosses into the VM as base64.
	Body []byte
	// Params are the dynamic route segments ([id], [...slug]), matching the
	// second argument Next.js route handlers receive.
	Params map[string]string
	// RemoteAddr is the client address (host:port) for legacy handlers.
	RemoteAddr string
}

APIRequest is the input to an API route handler.

type APIResult

type APIResult struct {
	Status  int
	Headers map[string][]string
	Body    []byte
	Error   string
	Stack   string
	Allow   []string
}

APIResult is a fully buffered API response (used by tests and callers that do not stream).

func (APIResult) Header

func (r APIResult) Header(name string) string

Header returns the first value of a (lowercase) response header.

type APIRouteRuntime

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

APIRouteRuntime executes compiled API routes via embedded quickjs.

In the default (shared) mode it keeps a pool of long-lived VMs, each of which loads a route module once and reuses it, so a request costs one handler call rather than a fresh VM + full module re-evaluation. Module state persists per worker across requests, matching Node/Next semantics.

In isolation mode it creates a fresh VM per request (slower, but each request gets clean module state); this is also used in dev so file edits are picked up.

func NewAPIRouteRuntime

func NewAPIRouteRuntime(apiDir string) *APIRouteRuntime

NewAPIRouteRuntime creates a new API route runtime

func (*APIRouteRuntime) Close added in v0.4.0

func (a *APIRouteRuntime) Close()

Close releases all idle workers.

func (*APIRouteRuntime) Execute

func (a *APIRouteRuntime) Execute(req APIRequest) APIResult

Execute runs the API route handler for the given path and buffers the whole response.

func (*APIRouteRuntime) ResolveFile added in v0.4.0

func (a *APIRouteRuntime) ResolveFile(reqPath string) string

ResolveFile returns the out-dir-relative file name (slash-separated, e.g. "users/index.js") that would serve the given request path, or "" when none exists. The server uses it to decide whether a Node-only route must be forwarded to the sidecar.

func (*APIRouteRuntime) Serve

func (a *APIRouteRuntime) Serve(ctx context.Context, req APIRequest, sink APISink) *APIFailure

Serve runs the route and streams the response into sink. It returns nil on success, or a failure describing what went wrong.

func (*APIRouteRuntime) SetCacheHooks

func (a *APIRouteRuntime) SetCacheHooks(h *CacheHooks)

SetCacheHooks connects routes to the host's revalidation endpoint and data cache (revalidatePath/revalidateTag, unstable_cache, fetch caching). Call before serving.

func (*APIRouteRuntime) SetEnv added in v0.4.0

func (a *APIRouteRuntime) SetEnv(env map[string]string)

SetEnv injects environment variables into every worker created by the pool. Call before serving.

func (*APIRouteRuntime) SetPool added in v0.4.0

func (a *APIRouteRuntime) SetPool(workers int, isolation bool)

SetPool configures the pool size and whether each request runs in a fresh VM (isolation) instead of a shared, stateful worker. Call before serving.

type APISink

type APISink interface {
	// Start is called once, before any Write, with the response head.
	Start(status int, headers [][2]string) error
	// Write delivers one body chunk; an error means the client is gone.
	Write(p []byte) error
}

APISink receives a response as the handler produces it.

type CacheHooks

type CacheHooks struct {
	// Revalidate applies a {paths, tags} revalidation synchronously and
	// returns the host's JSON result (or {"error": "..."}).
	Revalidate func(payloadJSON string) string
	// Data backs unstable_cache and fetch caching; nil disables both.
	Data *DataCache
}

CacheHooks connects embedded API routes to the host's on-demand revalidation and data cache (see @krate/runtime/cache).

type DataCache

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

DataCache is the Go-side data cache behind unstable_cache and Next-style fetch caching in the embedded QuickJS runtime. It is shared by every VM worker (so a cached value survives worker reuse and isolation mode) and is invalidated by tag from the Krate host's revalidation endpoint.

func NewDataCache

func NewDataCache(max int) *DataCache

NewDataCache returns a data cache bounded to max entries (<= 0: 1000).

func (*DataCache) Clear

func (c *DataCache) Clear()

Clear drops every entry.

func (*DataCache) Get

func (c *DataCache) Get(key string) (string, bool)

Get returns a fresh cached value.

func (*DataCache) InvalidateTags

func (c *DataCache) InvalidateTags(tags []string) int

InvalidateTags removes every entry carrying one of tags and returns how many.

func (*DataCache) Len

func (c *DataCache) Len() int

Len returns the number of stored entries.

func (*DataCache) Set

func (c *DataCache) Set(key, value string, ttl time.Duration, tags []string)

Set stores value for ttl (ttl < 0: until invalidated; 0: not stored).

type MiddlewareRequest

type MiddlewareRequest struct {
	URL        string
	Method     string
	Path       string
	Headers    map[string][]string
	RemoteAddr string
}

MiddlewareRequest is the input to the middleware function.

type MiddlewareResult

type MiddlewareResult struct {
	Action     string
	Status     int
	StatusText string
	Headers    [][2]string
	Body       []byte
	Rewrite    string
	Error      string
	Stack      string
}

MiddlewareResult is the output of the middleware function. For MiddlewareContinue, Headers are added to the downstream response and Rewrite (when set) replaces the request path. For MiddlewareResponse the middleware's own response is served.

type MiddlewareRuntime

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

MiddlewareRuntime executes the compiled middleware.js in embedded QuickJS. It keeps a small pool of VMs (like the API runtime) so concurrent requests do not serialize on one VM, supports async middleware, and in hot mode reloads the module when the file changes.

func LoadMiddlewareRuntime

func LoadMiddlewareRuntime(root string) *MiddlewareRuntime

LoadMiddlewareRuntime loads the middleware.js and returns a runtime, or nil if there is no middleware or it failed to load (the error is reported).

func NewLazyMiddlewareRuntime

func NewLazyMiddlewareRuntime(middlewarePath string) *MiddlewareRuntime

NewLazyMiddlewareRuntime returns a runtime that loads middleware.js on first use and tolerates a missing or broken file (requests then skip the middleware or fail closed with the load error). Dev uses it so edits made after startup, including adding the file, take effect.

func NewMiddlewareRuntime

func NewMiddlewareRuntime(middlewarePath string) (*MiddlewareRuntime, error)

NewMiddlewareRuntime loads middleware.js and validates that it exports a middleware function.

func (*MiddlewareRuntime) Close

func (m *MiddlewareRuntime) Close()

Close releases the pooled VMs.

func (*MiddlewareRuntime) Execute

Execute runs the middleware for one request.

func (*MiddlewareRuntime) ExecuteContext

ExecuteContext runs the middleware, aborting if ctx is cancelled.

func (*MiddlewareRuntime) HasMatcher

func (m *MiddlewareRuntime) HasMatcher() bool

HasMatcher reports whether the module declares a matcher (config.matcher); without one the host skips static assets by default.

func (*MiddlewareRuntime) SetEnv

func (m *MiddlewareRuntime) SetEnv(env map[string]string)

SetEnv sets process.env for the middleware VMs.

func (*MiddlewareRuntime) SetHot

func (m *MiddlewareRuntime) SetHot(hot bool)

SetHot makes the runtime re-read middleware.js when it changes on disk.

type Runtime

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

Runtime wraps a quickjs VM with krate-specific Web API polyfills

func New

func New() (*Runtime, error)

New creates a new JS runtime with Web API polyfills

func (*Runtime) Call

func (r *Runtime) Call(function string, args ...any) (any, error)

Call calls a global function with the given arguments

func (*Runtime) CallValue

func (r *Runtime) CallValue(function string, args ...any) (quickjs.Value, error)

CallValue calls a global function and returns a Value

func (*Runtime) Close

func (r *Runtime) Close() error

Close releases all resources

func (*Runtime) Compile added in v0.4.0

func (r *Runtime) Compile(code string, flags int) ([]byte, error)

Compile compiles JavaScript to quickjs bytecode for later evaluation with EvalBytecode. Caching bytecode lets a long-lived VM skip re-parsing a script on every call.

func (*Runtime) DrainJobs

func (r *Runtime) DrainJobs()

DrainJobs executes pending promise jobs (microtasks). Call after Execute to resolve promises.

func (*Runtime) Error added in v0.4.0

func (r *Runtime) Error(args []any)

Error writes an error line to stderr.

func (*Runtime) EvalBytecode added in v0.4.0

func (r *Runtime) EvalBytecode(bytecode []byte) (any, error)

EvalBytecode evaluates previously compiled quickjs bytecode.

func (*Runtime) Execute

func (r *Runtime) Execute(code string) (any, error)

Execute evaluates JavaScript code and returns the result

func (*Runtime) ExecuteModule

func (r *Runtime) ExecuteModule(code string) (any, error)

ExecuteModule evaluates JavaScript code as an ES module

func (*Runtime) GetGlobal

func (r *Runtime) GetGlobal(name string) (any, error)

GetGlobal gets a global variable

func (*Runtime) Log added in v0.4.0

func (r *Runtime) Log(args []any)

Log writes a console-style line to stdout.

func (*Runtime) LogPrefix added in v0.4.0

func (r *Runtime) LogPrefix() string

LogPrefix returns the current console prefix.

func (*Runtime) RegisterFunc

func (r *Runtime) RegisterFunc(name string, f func(args []any) (any, error)) error

RegisterFunc registers a Go function as a global JS function. A panic in the host function is converted into a JS-catchable error rather than unwinding across the QuickJS FFI boundary.

func (*Runtime) RegisterFuncWithThis

func (r *Runtime) RegisterFuncWithThis(name string, f func(this quickjs.Value, args []any) (any, error)) error

RegisterFuncWithThis registers a Go function that receives the this object (with the same panic containment as RegisterFunc).

func (*Runtime) SetEnv

func (r *Runtime) SetEnv(env map[string]string) error

SetEnv sets environment variables for the runtime. Values are JSON-encoded so keys/values containing quotes or backslashes are safe.

func (*Runtime) SetGlobal

func (r *Runtime) SetGlobal(name string, value any) error

SetGlobal sets a global variable

func (*Runtime) SetLogPrefix added in v0.4.0

func (r *Runtime) SetLogPrefix(prefix string)

SetLogPrefix sets a prefix prepended to every console line. Plugin hosts set it so console.log/error/warn output is attributable to the plugin that ran.

func (*Runtime) VM

func (r *Runtime) VM() *quickjs.VM

VM returns the underlying quickjs VM

func (*Runtime) Warn added in v0.4.0

func (r *Runtime) Warn(args []any)

Warn writes a warning line to stderr.

Jump to

Keyboard shortcuts

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