Documentation
¶
Index ¶
- Constants
- Variables
- func DefaultAPIWorkers() int
- func EvaluateExpr(code string) (string, error)
- func MiddlewarePath(root string) string
- func ToMap(v any) (map[string]any, bool)
- func ToNative(v any) any
- type APIFailure
- type APIRequest
- type APIResult
- type APIRouteRuntime
- func (a *APIRouteRuntime) Close()
- func (a *APIRouteRuntime) Execute(req APIRequest) APIResult
- func (a *APIRouteRuntime) ResolveFile(reqPath string) string
- func (a *APIRouteRuntime) Serve(ctx context.Context, req APIRequest, sink APISink) *APIFailure
- func (a *APIRouteRuntime) SetCacheHooks(h *CacheHooks)
- func (a *APIRouteRuntime) SetEnv(env map[string]string)
- func (a *APIRouteRuntime) SetPool(workers int, isolation bool)
- type APISink
- type CacheHooks
- type DataCache
- type MiddlewareRequest
- type MiddlewareResult
- type MiddlewareRuntime
- func (m *MiddlewareRuntime) Close()
- func (m *MiddlewareRuntime) Execute(req MiddlewareRequest) MiddlewareResult
- func (m *MiddlewareRuntime) ExecuteContext(ctx context.Context, req MiddlewareRequest) MiddlewareResult
- func (m *MiddlewareRuntime) HasMatcher() bool
- func (m *MiddlewareRuntime) SetEnv(env map[string]string)
- func (m *MiddlewareRuntime) SetHot(hot bool)
- type Runtime
- func (r *Runtime) Call(function string, args ...any) (any, error)
- func (r *Runtime) CallValue(function string, args ...any) (quickjs.Value, error)
- func (r *Runtime) Close() error
- func (r *Runtime) Compile(code string, flags int) ([]byte, error)
- func (r *Runtime) DrainJobs()
- func (r *Runtime) Error(args []any)
- func (r *Runtime) EvalBytecode(bytecode []byte) (any, error)
- func (r *Runtime) Execute(code string) (any, error)
- func (r *Runtime) ExecuteModule(code string) (any, error)
- func (r *Runtime) GetGlobal(name string) (any, error)
- func (r *Runtime) Log(args []any)
- func (r *Runtime) LogPrefix() string
- func (r *Runtime) RegisterFunc(name string, f func(args []any) (any, error)) error
- func (r *Runtime) RegisterFuncWithThis(name string, f func(this quickjs.Value, args []any) (any, error)) error
- func (r *Runtime) SetEnv(env map[string]string) error
- func (r *Runtime) SetGlobal(name string, value any) error
- func (r *Runtime) SetLogPrefix(prefix string)
- func (r *Runtime) VM() *quickjs.VM
- func (r *Runtime) Warn(args []any)
Constants ¶
const ( // EvalGlobal evaluates in the global scope EvalGlobal = quickjs.EvalGlobal // EvalModule evaluates as an ES module EvalModule = quickjs.EvalModule )
const ( MiddlewareContinue = "continue" MiddlewareResponse = "response" MiddlewareSkip = "skip" MiddlewareError = "error" )
Middleware actions.
Variables ¶
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") )
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 ¶
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 ¶
MiddlewarePath returns the conventional compiled middleware location, or "" when the project has none.
Types ¶
type APIFailure ¶
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).
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 ¶
NewDataCache returns a data cache bounded to max entries (<= 0: 1000).
func (*DataCache) InvalidateTags ¶
InvalidateTags removes every entry carrying one of tags and returns how many.
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 ¶
func (m *MiddlewareRuntime) Execute(req MiddlewareRequest) MiddlewareResult
Execute runs the middleware for one request.
func (*MiddlewareRuntime) ExecuteContext ¶
func (m *MiddlewareRuntime) ExecuteContext(ctx context.Context, req MiddlewareRequest) MiddlewareResult
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 (*Runtime) Compile ¶ added in v0.4.0
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) EvalBytecode ¶ added in v0.4.0
EvalBytecode evaluates previously compiled quickjs bytecode.
func (*Runtime) ExecuteModule ¶
ExecuteModule evaluates JavaScript code as an ES module
func (*Runtime) RegisterFunc ¶
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 ¶
SetEnv sets environment variables for the runtime. Values are JSON-encoded so keys/values containing quotes or backslashes are safe.
func (*Runtime) SetLogPrefix ¶ added in v0.4.0
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.