Documentation
¶
Overview ¶
Package ramune provides Go bindings for JavaScriptCore via purego — no Cgo required. The JSC runtime is dynamically loaded at startup and works with the system framework on macOS and libjavascriptcoregtk on Linux.
Basic Usage ¶
Evaluate JavaScript and read results:
rt, err := ramune.New()
if err != nil {
log.Fatal(err)
}
defer rt.Close()
val, err := rt.Eval("1 + 2")
if err != nil {
log.Fatal(err)
}
defer val.Close()
fmt.Println(val.Float64()) // 3
Constructing Objects ¶
Create JS objects and arrays directly from Go:
obj, _ := rt.NewObject(map[string]any{"name": "Alice", "age": 30})
arr, _ := rt.NewArray(1, "two", true)
obj.SetAttr("tags", arr)
Go Callbacks ¶
Register Go functions callable from JavaScript:
rt.RegisterFunc("add", func(args []any) (any, error) {
return args[0].(float64) + args[1].(float64), nil
})
val, _ := rt.Eval("add(3, 4)") // 7
npm Packages ¶
Use npm packages via automatic esbuild bundling:
rt, _ := ramune.New(
ramune.NodeCompat(),
ramune.Dependencies("lodash@4"),
)
val, _ := rt.Eval(`lodash.chunk([1,2,3,4,5,6], 2)`)
Event Loop and Async ¶
setTimeout, setInterval, and Promises work with the built-in event loop:
val, _ := rt.EvalAsync(`
new Promise(resolve => setTimeout(() => resolve(42), 100))
`)
fmt.Println(val.Float64()) // 42
Fetch ¶
HTTP requests via globalThis.fetch backed by Go's net/http:
rt, _ := ramune.New(ramune.WithFetch())
val, _ := rt.EvalAsync(`
fetch("https://api.example.com/data").then(r => r.json())
`)
Index ¶
- Variables
- func ClearCache() error
- func DrainWebViewMain(done <-chan struct{})
- func HandleSandboxWorker(s *SandboxRuntime) bool
- func InitWebViewMain()
- func InstallNpmPackages(specs []string, destDir string) error
- func Register[F any](rt *Runtime, name string, fn F) error
- func RunFile(rt *Runtime, path string, opts RunFileOptions) error
- func SandboxAvailable() bool
- type CallbackContext
- func (cc *CallbackContext) Eval(code string) (any, error)
- func (cc *CallbackContext) EvalBool(code string) (bool, error)
- func (cc *CallbackContext) EvalFloat64(code string) (float64, error)
- func (cc *CallbackContext) EvalString(code string) (string, error)
- func (cc *CallbackContext) Exec(code string) error
- func (cc *CallbackContext) GetProperty(name string) (any, error)
- func (cc *CallbackContext) SetProperty(name string, value any) error
- type GCConfig
- type GoFunc
- type GoFuncWithContext
- type JSError
- type JSFunc
- type LibraryNotFoundError
- type Module
- type Option
- func Dependencies(pkgs ...string) Option
- func DockerModule() Option
- func NodeCompat() Option
- func PreloadJS(code string) Option
- func WithFetch() Option
- func WithGC(gc GCConfig) Option
- func WithLibraryPath(path string) Option
- func WithModule(m Module) Option
- func WithPermissions(p *Permissions) Option
- func WithResourceLimits(l ResourceLimits) Option
- func WithStderr(w io.Writer) Option
- func WithStdout(w io.Writer) Option
- func WithTickManager(m TickManager) Option
- func WithWinterTC() Option
- type PermissionState
- type Permissions
- type ResourceLimits
- type RunFileOptions
- type Runtime
- func (r *Runtime) Bind(name string, v any) error
- func (r *Runtime) Close() error
- func (r *Runtime) Engine() string
- func (r *Runtime) Eval(code string) (*Value, error)
- func (r *Runtime) EvalAsync(code string) (*Value, error)
- func (r *Runtime) EvalAsyncWithContext(ctx context.Context, code string) (*Value, error)
- func (r *Runtime) EvalWithContext(ctx context.Context, code string) (*Value, error)
- func (r *Runtime) Exec(code string) error
- func (r *Runtime) GlobalObject() *Value
- func (r *Runtime) LoadModule(m Module) error
- func (r *Runtime) NativeInstanceCount() int
- func (r *Runtime) NewArray(items ...any) (*Value, error)
- func (r *Runtime) NewObject(props map[string]any) (*Value, error)
- func (r *Runtime) NewUint8Array(data []byte) (*Value, error)
- func (r *Runtime) OnReady(fn func())
- func (r *Runtime) RegisterFunc(name string, fn GoFunc) error
- func (r *Runtime) RegisterFuncWithContext(name string, fn GoFuncWithContext) error
- func (r *Runtime) RunEventLoop() error
- func (r *Runtime) RunEventLoopFor(timeout time.Duration) error
- func (r *Runtime) RunEventLoopWithContext(ctx context.Context) error
- func (r *Runtime) Tick() (bool, error)
- func (r *Runtime) Wake()
- type RuntimePool
- func (p *RuntimePool) Addr() string
- func (p *RuntimePool) Broadcast(code string) error
- func (p *RuntimePool) Close() error
- func (p *RuntimePool) Eval(code string) (*Value, error)
- func (p *RuntimePool) Exec(code string) error
- func (p *RuntimePool) ListenAndServe(addr string, jsHandler string) error
- func (p *RuntimePool) Size() int
- func (p *RuntimePool) StopHTTP()
- type SandboxConfig
- type SandboxResult
- type SandboxRuntime
- type TickManager
- type Value
- func (v *Value) Attr(name string) *Value
- func (v *Value) AttrErr(name string) (*Value, error)
- func (v *Value) Bool() (bool, error)
- func (v *Value) Bytes() ([]byte, error)
- func (v *Value) Call(args ...any) (*Value, error)
- func (v *Value) Close() error
- func (v *Value) Delete(name string) error
- func (v *Value) Float64() (float64, error)
- func (v *Value) GoString() (string, error)
- func (v *Value) Has(name string) bool
- func (v *Value) Index(i int) *Value
- func (v *Value) Int64() (int64, error)
- func (v *Value) IsArray() bool
- func (v *Value) IsFunction() bool
- func (v *Value) IsNull() bool
- func (v *Value) IsUndefined() bool
- func (v *Value) Keys() ([]string, error)
- func (v *Value) Len() (int, error)
- func (v *Value) Ptr() uintptr
- func (v *Value) SetAttr(name string, val any) error
- func (v *Value) String() string
- func (v *Value) ToMap() (map[string]any, error)
- func (v *Value) ToSlice() ([]any, error)
Constants ¶
This section is empty.
Variables ¶
var ErrAlreadyClosed = errors.New("ramune: runtime already closed")
ErrAlreadyClosed is returned when operations are attempted on a closed Runtime.
var ErrJSCNotFound = errors.New("ramune: shared library not found")
ErrJSCNotFound is returned when no suitable JavaScriptCore shared library can be located on the system.
var ErrNilValue = errors.New("ramune: operation on nil Value")
ErrNilValue is returned when an operation is attempted on a nil Value.
var NodeBuiltins = []string{
"child_process", "fs", "path", "os", "net", "http", "https", "tls",
"stream", "events", "util", "buffer", "crypto", "url", "querystring",
"zlib", "string_decoder", "assert", "readline", "dns", "worker_threads",
"dgram", "module", "process", "tty", "timers", "timers/promises",
"perf_hooks", "node:*",
}
NodeBuiltins lists Node.js built-in modules that are provided by the NodeCompat polyfill layer and should be marked as external during bundling.
Functions ¶
func ClearCache ¶
func ClearCache() error
ClearCache removes all cached JS bundles created by Dependencies().
func DrainWebViewMain ¶ added in v0.8.0
func DrainWebViewMain(done <-chan struct{})
DrainWebViewMain processes WebView operations on the main thread. Blocks until done is closed or all work is complete. Must be called from the main goroutine (pinned to thread 0 via runtime.LockOSThread in init).
func HandleSandboxWorker ¶ added in v0.8.0
func HandleSandboxWorker(s *SandboxRuntime) bool
HandleSandboxWorker checks if the current process is a sandbox worker and returns true if so. The caller should pass the SandboxRuntime that was set up with RegisterFunc calls, then exit.
Usage:
rt := ramune.NewSandboxRuntime(ramune.NodeCompat())
rt.RegisterFunc("add", func(a, b float64) float64 { return a + b })
if ramune.HandleSandboxWorker(rt) {
return
}
func InitWebViewMain ¶ added in v0.8.0
func InitWebViewMain()
InitWebViewMain enables WebView support by creating the main-thread dispatch channel. Must be called before any WebView is created. The caller must drain the channel on the main goroutine, e.g.:
ramune.InitWebViewMain()
go func() { /* run engine */ }()
ramune.DrainWebViewMain(done)
func InstallNpmPackages ¶ added in v0.5.0
InstallNpmPackages downloads npm packages to destDir/node_modules/. Packages are specified as "name" or "name@version" (e.g., "preact", "lodash@4"). Packages are fetched directly from the npm registry — no npm or bun required.
func Register ¶
Register registers a typed Go function as a global JavaScript function. Unlike RegisterFunc, which requires manual args[]any casting, Register uses reflection to automatically convert JS arguments to the function's parameter types and convert return values back.
Supported parameter types: float64, float32, int, int8/16/32/64, uint, uint8/16/32/64, string, bool, map[string]any, []any.
Supported return signatures:
- func(...) → no return value
- func(...) T → single return value (non-error)
- func(...) error → single error return
- func(...) (T, error) → value + error
Example:
ramune.Register(rt, "add", func(a, b float64) float64 {
return a + b
})
func RunFile ¶ added in v0.20.0
func RunFile(rt *Runtime, path string, opts RunFileOptions) error
RunFile executes a JS or TypeScript file in rt with the same setup the `ramune run` CLI applies: __filename / __dirname / process.argv globals, tsgo TS transpile (with experimental decorators), esbuild ESM bundling when the source has import/export, IIFE wrap.
path must be a real on-disk file (relative or absolute); RunFile reads it directly so esbuild's bundler can resolve sibling imports the same way the CLI does.
rt is expected to have been built with NodeCompat() — RunFile relies on the Node-compat layer for require()/process/__filename/__dirname. Without it, process.argv is silently skipped and require() in the loaded source will fail. WithFetch() is similarly recommended if the script does network I/O.
RunFile drives the event loop to completion before returning, so any timeout from rt.RunEventLoop (30s default for non-server scripts) is surfaced to the caller as the return value.
Use this when embedding Ramune as a library and you need to run a TS entrypoint that pulls in its own dependency graph (e.g. pyright-internal reached via vendored `./src/...` imports). For a JS string with no imports, Runtime.Exec is enough.
func SandboxAvailable ¶ added in v0.8.0
func SandboxAvailable() bool
SandboxAvailable checks whether Docker is reachable.
Types ¶
type CallbackContext ¶
type CallbackContext struct {
// contains filtered or unexported fields
}
CallbackContext provides safe access to the JS engine from within a GoFunc. Value methods like Attr() and Call() dispatch to the engine goroutine, which deadlocks inside a callback (already on the engine goroutine). CallbackContext calls engine functions directly and returns Go values.
func (*CallbackContext) Eval ¶
func (cc *CallbackContext) Eval(code string) (any, error)
Eval evaluates JS code and returns the result as any (Go value).
func (*CallbackContext) EvalBool ¶
func (cc *CallbackContext) EvalBool(code string) (bool, error)
EvalBool evaluates JS code and returns the result as bool.
func (*CallbackContext) EvalFloat64 ¶
func (cc *CallbackContext) EvalFloat64(code string) (float64, error)
EvalFloat64 evaluates JS code and returns the result as float64.
func (*CallbackContext) EvalString ¶
func (cc *CallbackContext) EvalString(code string) (string, error)
EvalString evaluates JS code and returns the result as string.
func (*CallbackContext) Exec ¶
func (cc *CallbackContext) Exec(code string) error
Exec executes JavaScript code, discarding the result.
func (*CallbackContext) GetProperty ¶
func (cc *CallbackContext) GetProperty(name string) (any, error)
GetProperty reads a property from the global object.
func (*CallbackContext) SetProperty ¶
func (cc *CallbackContext) SetProperty(name string, value any) error
SetProperty sets a property on the global object.
type GCConfig ¶
type GCConfig struct {
// GCInterval is the number of HTTP requests between manual JSC GC cycles.
// Lower values use more CPU but prevent JS memory growth.
// Default: 2000. Set to 0 to disable manual JSC GC.
GCInterval int
// GCPercent sets the Go GC target percentage (same as GOGC env var).
// Applied when the HTTP server starts. Default: 100 (Go's default).
GCPercent int
}
GCConfig configures garbage collection behavior for a Runtime.
func DefaultGCConfig ¶
func DefaultGCConfig() GCConfig
DefaultGCConfig returns the default GC configuration.
type GoFunc ¶
GoFunc is a Go function that can be called from JavaScript. Arguments are converted to Go types: bool, float64, string, nil, map[string]any (for objects), []any (for arrays), or *JSFunc (for functions).
type GoFuncWithContext ¶
type GoFuncWithContext func(ctx *CallbackContext, args []any) (any, error)
GoFuncWithContext is a callback that receives a CallbackContext for safe engine access. Use RegisterFuncWithContext to register these.
type JSError ¶
type JSError struct {
Context string
Message string
Stack string // JavaScript stack trace, if available
}
JSError represents an error that originated in the JavaScript runtime.
type JSFunc ¶ added in v0.4.0
type JSFunc struct {
// contains filtered or unexported fields
}
JSFunc wraps a JavaScript function reference, allowing it to be called from Go. Created automatically when a JS function is passed as an argument to a GoFunc callback. Call Close() when done to release the JS reference.
type LibraryNotFoundError ¶
type LibraryNotFoundError struct {
Searched []string
}
LibraryNotFoundError provides detailed information about which paths were searched when JavaScriptCore could not be found.
func (*LibraryNotFoundError) Error ¶
func (e *LibraryNotFoundError) Error() string
func (*LibraryNotFoundError) Unwrap ¶
func (e *LibraryNotFoundError) Unwrap() error
type Module ¶
type Module struct {
// Name is the module name used with require('name').
Name string
// Exports maps JS property names to Go functions.
// Each function becomes a property on the module object.
Exports map[string]GoFunc
// Init is called after exports are registered, allowing
// additional setup such as evaluating JS code.
// The Runtime's JSC lock is held — use execLocked/evalLocked only.
Init func(rt *Runtime) error
}
Module defines a custom module that can be loaded via require() in JS.
func NativeModuleFromFuncs ¶ added in v0.4.0
NativeModuleFromFuncs creates a Module from a map of typed Go functions. Each function is automatically wrapped with reflection-based argument conversion, similar to Register[F]. This is used to expose transpiled Go code as a JS module.
Example:
mod := ramune.NativeModuleFromFuncs("native:math", map[string]any{
"fibonacci": mymath.Fibonacci, // func(float64) float64
"isPrime": mymath.IsPrime, // func(float64) bool
})
rt, _ := ramune.New(ramune.WithModule(mod))
rt.Eval(`require('native:math').fibonacci(10)`) // 55
type Option ¶
type Option func(*config)
Option configures a Runtime.
func Dependencies ¶
Dependencies declares npm package dependencies that are automatically installed, bundled with esbuild, and evaluated in the JSC context. Packages are specified as "name" or "name@version" (e.g., "lodash@4"). Subpath imports are also supported (e.g., "react-dom/server"); the base package is installed and the subpath is imported separately in the bundle. The bundle is cached in ~/.cache/ramune/jsbundles/<hash>/. Packages are fetched directly from the npm registry — no npm or bun required.
func DockerModule ¶ added in v0.8.0
func DockerModule() Option
DockerModule returns an Option that installs the Docker native module. The module is lazy-initialized on first require('dockerode').
func NodeCompat ¶
func NodeCompat() Option
NodeCompat installs a minimal Node.js compatibility layer into the JSC context. This enables npm packages that depend on Node.js built-ins to run in JSC with Go providing the native functionality.
Supported polyfills:
- require() — returns polyfilled modules
- process.env, process.cwd(), process.platform, process.arch
- child_process.spawnSync / execSync (synchronous only)
- fs.readFileSync, fs.existsSync, fs.writeFileSync, fs.mkdirSync
- path.join, path.resolve, path.dirname, path.basename, path.sep
- Buffer.from (basic)
- console.log, console.error, console.warn
- setTimeout (immediate execution, no real delay)
func PreloadJS ¶ added in v0.6.0
PreloadJS sets JavaScript code that will be executed before loading dependency bundles. This is useful for providing polyfills required by bundled packages (e.g., MessageChannel for React).
func WithFetch ¶
func WithFetch() Option
WithFetch installs a globalThis.fetch polyfill backed by Go's net/http. This is also automatically enabled when NodeCompat() is used.
func WithGC ¶
WithGC configures garbage collection behavior. See GCConfig for details on each setting.
func WithLibraryPath ¶
WithLibraryPath sets an explicit path to the JavaScriptCore shared library. Ignored when using the QuickJS backend.
func WithModule ¶
WithModule returns an Option that registers a module during Runtime creation. The module is available via require('name') if NodeCompat is enabled.
func WithPermissions ¶
func WithPermissions(p *Permissions) Option
WithPermissions sets the permission policy for the Runtime.
func WithResourceLimits ¶ added in v0.13.0
func WithResourceLimits(l ResourceLimits) Option
WithResourceLimits caps runtime resources. See ResourceLimits for the per-backend applicability matrix.
func WithStderr ¶ added in v0.8.0
WithStderr sets the writer for console.error/warn output. Defaults to os.Stderr if not set.
func WithStdout ¶ added in v0.8.0
WithStdout sets the writer for console.log/info/debug output. Defaults to os.Stdout if not set.
func WithTickManager ¶ added in v0.8.0
func WithTickManager(m TickManager) Option
WithTickManager registers a custom event loop manager. The manager's ProcessEvents method is called during each event loop tick, and HasActive is checked to determine if the event loop should keep running.
func WithWinterTC ¶ added in v0.10.0
func WithWinterTC() Option
WithWinterTC installs the WinterTC (ECMA-429) Minimum Common Web API surface. This includes CompressionStream, DecompressionStream, MessageChannel, MessagePort, MessageEvent, ErrorEvent, PromiseRejectionEvent, and URLPattern.
When used with NodeCompat(), these APIs are installed automatically. Use WithWinterTC() for standalone WinterTC compliance without the full Node.js compatibility layer.
type PermissionState ¶
type PermissionState int
PermissionState represents the state of a permission.
const ( PermGranted PermissionState = iota PermDenied )
type Permissions ¶
type Permissions struct {
Read PermissionState
Write PermissionState
Net PermissionState
Env PermissionState
Run PermissionState
ReadPaths []string // allowed read paths (empty = all if granted)
WritePaths []string // allowed write paths
NetHosts []string // allowed network hosts
EnvVars []string // allowed env var names
RunCmds []string // allowed commands
}
Permissions controls access to system resources. Default is all granted (Bun-compatible). Use WithSandbox() to deny by default.
func AllPermissions ¶
func AllPermissions() *Permissions
AllPermissions returns permissions with everything granted.
func SandboxPermissions ¶
func SandboxPermissions() *Permissions
SandboxPermissions returns permissions with everything denied.
func (*Permissions) CheckEnv ¶
func (p *Permissions) CheckEnv(name string) error
CheckEnv checks if accessing the given env var is allowed.
func (*Permissions) CheckNet ¶
func (p *Permissions) CheckNet(host string) error
CheckNet checks if network access to the given host is allowed.
func (*Permissions) CheckRead ¶
func (p *Permissions) CheckRead(path string) error
CheckRead checks if reading the given path is allowed.
func (*Permissions) CheckRun ¶
func (p *Permissions) CheckRun(cmd string) error
CheckRun checks if running the given command is allowed.
func (*Permissions) CheckWrite ¶
func (p *Permissions) CheckWrite(path string) error
CheckWrite checks if writing to the given path is allowed.
func (*Permissions) DeniesFS ¶ added in v0.13.0
func (p *Permissions) DeniesFS() bool
DeniesFS reports whether the policy forbids filesystem access in either direction. Callers use this to decide whether to close ambient FS surfaces that bypass CheckRead/CheckWrite (e.g. WASI FS mounts on the qjswasm backend). WASI mounts can't be read-only without read-only being granular at the mount layer, so denying either side closes the whole mount.
type ResourceLimits ¶ added in v0.13.0
type ResourceLimits struct {
// MaxMemoryBytes caps total JS heap in bytes. When exceeded, the engine
// aborts the current operation with an OOM-like error.
MaxMemoryBytes int64
// MaxStackBytes caps the JS stack in bytes. When exceeded, the engine
// throws a stack overflow error (recoverable).
MaxStackBytes int64
// GCThresholdBytes tunes when the GC kicks in. Lower = more aggressive.
GCThresholdBytes int64
}
ResourceLimits caps the resources a Runtime may consume. Only qjswasm honors these today (mapping to QuickJS-NG's JS_SetMemoryLimit / JS_SetMaxStackSize / JS_SetGCThreshold); other backends silently ignore them. Zero means "unlimited" (backend default).
type RunFileOptions ¶ added in v0.20.0
type RunFileOptions struct {
// Argv supplies the script arguments visible as process.argv inside the
// script. RunFile follows Node.js convention: process.argv is always set
// to [runner, scriptPath, ...Argv], so callers should pass only the
// script-side args. If Argv[0] is exactly "ramune", RunFile treats Argv
// as a fully-formed process.argv and uses it verbatim instead.
//
// Examples (script path "/abs/foo.ts"):
// Argv: nil -> process.argv = ["ramune", "/abs/foo.ts"]
// Argv: []string{"--flag"} -> process.argv = ["ramune", "/abs/foo.ts", "--flag"]
// Argv: []string{"ramune","X"} -> process.argv = ["ramune", "X"] (verbatim)
Argv []string
}
RunFileOptions tunes RunFile. The zero value is fine.
type Runtime ¶
type Runtime struct {
// contains filtered or unexported fields
}
Runtime holds a loaded JavaScriptCore library and a global JS context. Multiple Runtimes can coexist in the same process — each gets a dedicated OS thread for JSC access. All JSC operations are dispatched to this thread via a channel, ensuring thread identity across calls (required by JSC). The Runtime is safe for concurrent use from multiple goroutines.
func New ¶
New creates a new JavaScriptCore runtime with a fresh global context. Each Runtime gets a dedicated OS thread for all JSC operations, ensuring thread identity across calls. Multiple Runtimes can coexist safely.
func (*Runtime) Bind ¶
Bind exposes a Go struct as a JavaScript object on globalThis. Exported struct fields become JS properties (read from current Go state), and methods on the pointer receiver become callable JS functions.
Field naming: if a field has a `js:"name"` tag, that name is used; otherwise the first letter is lowercased (e.g. Name → name).
Method naming: Go method names are converted to camelCase (e.g. Greet → greet, SetAge → setAge).
Fields are backed by the Go struct: reading a property in JS always returns the current Go value. Setting a property in JS updates the Go struct. Methods that mutate the struct are reflected on subsequent property reads.
func (*Runtime) EvalAsync ¶
EvalAsync evaluates JavaScript code that may return a Promise, runs the event loop until the Promise resolves, and returns the result.
func (*Runtime) EvalAsyncWithContext ¶
EvalAsyncWithContext evaluates JavaScript code that may return a Promise, runs the event loop until the Promise resolves or the context is cancelled/expired, and returns the result.
func (*Runtime) EvalWithContext ¶
EvalWithContext evaluates JavaScript code and returns the result, respecting the provided context for cancellation and deadlines. Since JSC cannot be interrupted mid-execution, the context is checked before evaluation begins. For timeout control over async operations, use EvalAsyncWithContext instead.
func (*Runtime) GlobalObject ¶
GlobalObject returns the global object for this context.
func (*Runtime) LoadModule ¶
LoadModule registers a module on an existing Runtime.
func (*Runtime) NativeInstanceCount ¶ added in v0.4.0
NativeInstanceCount returns the number of live native struct instances. Useful for testing and debugging instance lifecycle.
func (*Runtime) NewUint8Array ¶
NewUint8Array creates a JavaScript Uint8Array containing a copy of the given bytes.
func (*Runtime) OnReady ¶ added in v0.19.0
func (r *Runtime) OnReady(fn func())
OnReady registers fn to be invoked once when the event loop first observes no pending work during a Runtime.RunEventLoop or Runtime.RunEventLoopFor call. Intended for platforms that need a deterministic "runtime has finished top-level initialization" signal — notably openworkers' Firecracker guest, which forwards a pending HTTP request only after the worker module's top-level awaits have resolved and event loop returns to idle.
Calling OnReady again before the first fire replaces the callback. Calls after the first fire are no-ops. fn panics are recovered so they do not propagate into the event loop driver.
OnReady does NOT fire at registration time or from Runtime.Tick; only from the RunEventLoop[For] paths. This avoids accidental fire when a caller registers before any JS has been evaluated and the runtime happens to be idle.
func (*Runtime) RegisterFunc ¶
RegisterFunc registers a Go function as a global JavaScript function.
func (*Runtime) RegisterFuncWithContext ¶
func (r *Runtime) RegisterFuncWithContext(name string, fn GoFuncWithContext) error
RegisterFuncWithContext registers a Go function that receives a CallbackContext, allowing safe JSC access from within the callback without deadlocking.
func (*Runtime) RunEventLoop ¶
RunEventLoop processes the event loop until all pending operations complete. For short-lived scripts (timers, promises), the default timeout is 30 seconds. If an HTTP server (Ramune.serve) is active, the loop runs indefinitely.
func (*Runtime) RunEventLoopFor ¶
RunEventLoopFor processes the event loop until all timers complete or the timeout is reached.
func (*Runtime) RunEventLoopWithContext ¶
RunEventLoopWithContext processes the event loop until all timers complete or the context is cancelled/expired.
type RuntimePool ¶
type RuntimePool struct {
// contains filtered or unexported fields
}
RuntimePool manages multiple Runtimes for parallel JS execution. Each Runtime has its own dedicated OS thread and independent JSC VM.
func NewPool ¶
func NewPool(n int, opts ...Option) (*RuntimePool, error)
NewPool creates a pool of n Runtimes, each configured with the given options.
func (*RuntimePool) Addr ¶
func (p *RuntimePool) Addr() string
Addr returns the listener address, or "" if not listening.
func (*RuntimePool) Broadcast ¶
func (p *RuntimePool) Broadcast(code string) error
Broadcast executes JavaScript code on all workers in parallel.
func (*RuntimePool) Close ¶
func (p *RuntimePool) Close() error
Close stops the HTTP server (if running) and closes all Runtimes.
func (*RuntimePool) Eval ¶
func (p *RuntimePool) Eval(code string) (*Value, error)
Eval evaluates JavaScript code on the next available worker.
func (*RuntimePool) Exec ¶
func (p *RuntimePool) Exec(code string) error
Exec executes JavaScript code on the next available worker, discarding the result.
func (*RuntimePool) ListenAndServe ¶
func (p *RuntimePool) ListenAndServe(addr string, jsHandler string) error
ListenAndServe starts an HTTP server that dispatches requests round-robin across pool workers via per-worker channels.
func (*RuntimePool) Size ¶
func (p *RuntimePool) Size() int
Size returns the number of workers in the pool.
func (*RuntimePool) StopHTTP ¶
func (p *RuntimePool) StopHTTP()
StopHTTP stops the HTTP server and drains in-flight requests.
type SandboxConfig ¶ added in v0.8.0
type SandboxConfig struct {
// Image is the Docker image to use. Default: "ubuntu:24.04".
Image string
// Mounts are additional bind mounts in "host:container[:ro]" format.
Mounts []string
// Env is additional environment variables for the container.
Env map[string]string
// Timeout is the maximum execution time. Default: 60s.
Timeout time.Duration
// SocketPath overrides the Docker socket path.
SocketPath string
// Network is the Docker network to connect the container to.
// Use this to give the sandbox access to other services on the same network.
Network string
// ExtraHosts adds custom host-to-IP mappings (like --add-host).
// Format: "hostname:ip" (e.g. "api-server:192.168.1.100").
ExtraHosts []string
// MemoryMB sets the container memory limit in megabytes. 0 = unlimited.
MemoryMB int
// CPUs sets the CPU limit (e.g. 1.5 = 1.5 cores). 0 = unlimited.
CPUs float64
// NoNetwork disables all network access from the container.
NoNetwork bool
}
SandboxConfig configures Docker sandbox execution.
type SandboxResult ¶ added in v0.8.0
SandboxResult holds the result of a sandboxed execution.
func SandboxEval ¶ added in v0.8.0
func SandboxEval(code string, cfg SandboxConfig) (*SandboxResult, error)
SandboxEval evaluates a JS expression inside a Docker container.
func SandboxRun ¶ added in v0.8.0
func SandboxRun(scriptPath string, cfg SandboxConfig) (*SandboxResult, error)
SandboxRun executes a ramune script inside a Docker container.
type SandboxRuntime ¶ added in v0.8.0
type SandboxRuntime struct {
// contains filtered or unexported fields
}
SandboxRuntime holds Go function registrations for sandbox execution. When the binary is re-invoked inside Docker, the same functions are available because they are compiled into the binary.
func NewSandboxRuntime ¶ added in v0.8.0
func NewSandboxRuntime(opts ...Option) *SandboxRuntime
NewSandboxRuntime creates a new SandboxRuntime with the given options.
func (*SandboxRuntime) RegisterFunc ¶ added in v0.8.0
func (s *SandboxRuntime) RegisterFunc(name string, fn GoFunc)
RegisterFunc registers a Go function that will be available to JS code in the sandbox. The function is compiled into the binary, so it works both on the host and inside the Docker container.
func (*SandboxRuntime) SandboxEval ¶ added in v0.8.0
func (s *SandboxRuntime) SandboxEval(code string, cfg SandboxConfig) (*SandboxResult, error)
SandboxEval evaluates JS code inside a Docker container.
func (*SandboxRuntime) SandboxRun ¶ added in v0.8.0
func (s *SandboxRuntime) SandboxRun(scriptPath string, cfg SandboxConfig) (*SandboxResult, error)
SandboxRun executes a ramune script inside a Docker container.
type TickManager ¶ added in v0.8.0
type TickManager interface {
// ProcessEvents drains pending events and delivers them to JavaScript.
// Called on the dedicated engine goroutine during each event loop tick.
ProcessEvents(r *Runtime)
// HasActive returns true if there are pending operations that should
// keep the event loop running.
HasActive() bool
// Close releases resources held by the manager.
Close()
}
TickManager is the interface for custom event loop managers. External packages implement this to integrate async I/O with ramune's event loop.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value wraps a JavaScriptCore JSValueRef with lifecycle management. Call Close() to unprotect the value.
func (*Value) Attr ¶
Attr returns a property by name from the JS object. Returns nil if this is not an object or the property doesn't exist.
func (*Value) Close ¶
Close queues the JSValueRef for unprotection at the next safe point. Uses the unprotectQueue to avoid deadlock when called from GoFunc callbacks (which already run on the dedicated JSC goroutine). Safe to call multiple times or on nil.
func (*Value) Int64 ¶
Int64 returns the value as an int64 (truncated from float64, since JS has no integer type).
func (*Value) IsFunction ¶
IsFunction reports whether this value is a JavaScript function.
func (*Value) IsUndefined ¶
IsUndefined reports whether this value is JavaScript undefined.
func (*Value) Len ¶
Len returns the "length" property as an integer. Works for arrays, strings, and any object with a length property.
Source Files
¶
- archive.go
- asyncfs.go
- asyncnet.go
- asyncspawn.go
- bind.go
- buncompat.go
- buncompat_jsc.go
- bundle.go
- callback_jsc.go
- callbackctx_jsc.go
- console.go
- convert_jsc.go
- cron.go
- csrf.go
- detect_jsc.go
- detect_jsc_linux.go
- dgram.go
- dns.go
- docker.go
- engine_jsc.go
- errors.go
- eventloop.go
- eventloop_jsc.go
- fetch.go
- fswatch.go
- goid.go
- http2.go
- jsfunc_jsc.go
- markdown.go
- module.go
- native_instance.go
- native_instance_fr.go
- nodecompat.go
- nodecompat_crypto.go
- nodecompat_esm.go
- nodecompat_fs.go
- nodecompat_misc.go
- nodecompat_path.go
- nodecompat_signals_unix.go
- nodecompat_tty.go
- onready.go
- permissions.go
- pool.go
- pool_jsc.go
- register.go
- runfile.go
- sandbox.go
- sharedbuf.go
- signal_jsc_linux_cgo.go
- sqlite.go
- streambridge.go
- target_default.go
- tcpserver.go
- types.go
- value_jsc.go
- vm_jsc.go
- webcrypto.go
- websocket.go
- websocket_jsc.go
- webstreams.go
- webview.go
- webview_cdp.go
- wintercompat.go
- worker.go
Directories
¶
| Path | Synopsis |
|---|---|
|
bench
|
|
|
pool
command
|
|
|
cmd
|
|
|
ramune
command
Command ramune is a JavaScript runtime powered by JavaScriptCore via purego.
|
Command ramune is a JavaScript runtime powered by JavaScriptCore via purego. |
|
ramune-toolchain
command
Command ramune-toolchain is the development toolchain for ramune: check, fmt, lint, transpile, typegen, compile.
|
Command ramune-toolchain is the development toolchain for ramune: check, fmt, lint, transpile, typegen, compile. |
|
examples
|
|
|
workers/custom-binding
command
A runnable demonstration of a custom env binding.
|
A runnable demonstration of a custom env binding. |
|
Package hybrid exposes the read-only analysis side of Ramune's TS→Go hybrid transpiler.
|
Package hybrid exposes the read-only analysis side of Ramune's TS→Go hybrid transpiler. |
|
internal
|
|
|
gotranspiler
Package gotranspiler implements TypeScript to Go source code transpilation.
|
Package gotranspiler implements TypeScript to Go source code transpilation. |
|
gotranspiler/composer
Package composer orchestrates the hybrid TS→Go extraction pipeline.
|
Package composer orchestrates the hybrid TS→Go extraction pipeline. |
|
gotranspiler/picker
Package picker decides which top-level TypeScript declarations are safe to extract as native Go code in the hybrid TS→Go transpile pipeline.
|
Package picker decides which top-level TypeScript declarations are safe to extract as native Go code in the hybrid TS→Go transpile pipeline. |
|
rslint/plugins/react/rules/no_unknown_property
cspell:disable — this file enumerates HTML / SVG / ARIA attribute names verbatim from React and the WHATWG / W3C specs, so it contains many attribute-name tokens (aria-*, SVG presentation attributes, popover / shadowroot attrs, …) that are not in a general English dictionary.
|
cspell:disable — this file enumerates HTML / SVG / ARIA attribute names verbatim from React and the WHATWG / W3C specs, so it contains many attribute-name tokens (aria-*, SVG presentation attributes, popover / shadowroot attrs, …) that are not in a general English dictionary. |
|
rslint/rules/no_implied_eval
cspell:ignore sctx
|
cspell:ignore sctx |
|
rslint/rules/no_misleading_character_class
Package no_misleading_character_class implements ESLint's no-misleading-character-class rule on top of the layered regex / JS string utilities in `internal/utils`.
|
Package no_misleading_character_class implements ESLint's no-misleading-character-class rule on top of the layered regex / JS string utilities in `internal/utils`. |
|
rslint/tsgo_pinned/bundled
Package bundled provides access to files bundled with TypeScript.
|
Package bundled provides access to files bundled with TypeScript. |
|
rslint/tsgo_pinned/compiler
Package compiler implements the TypeScript compiler.
|
Package compiler implements the TypeScript compiler. |
|
rslint/tsgo_pinned/diagnostics
Package diagnostics contains generated localizable diagnostic messages.
|
Package diagnostics contains generated localizable diagnostic messages. |
|
rslint/tsgo_pinned/jsnum
Package jsnum provides JS-like number handling.
|
Package jsnum provides JS-like number handling. |
|
rslint/tsgo_pinned/nodebuilder
Exports interfaces and types defining the node builder - concrete implementations are on top of the checker, but these types and interfaces are used by the emit resolver in the printer
|
Exports interfaces and types defining the node builder - concrete implementations are on top of the checker, but these types and interfaces are used by the emit resolver in the printer |
|
rslint/tsgo_pinned/printer
Package printer exports a Printer for pretty-printing TS ASTs and writer interfaces and implementations for using them Intended ultimate usage:
|
Package printer exports a Printer for pretty-printing TS ASTs and writer interfaces and implementations for using them Intended ultimate usage: |
|
rslint/tsgo_pinned/stringutil
Package stringutil Exports common rune utilities for parsing and emitting javascript
|
Package stringutil Exports common rune utilities for parsing and emitting javascript |
|
rslint/utils
cspell:ignore octals
|
cspell:ignore octals |
|
tsgo/bundled
Package bundled provides access to files bundled with TypeScript.
|
Package bundled provides access to files bundled with TypeScript. |
|
tsgo/compiler
Package compiler implements the TypeScript compiler.
|
Package compiler implements the TypeScript compiler. |
|
tsgo/diagnostics
Package diagnostics contains generated localizable diagnostic messages.
|
Package diagnostics contains generated localizable diagnostic messages. |
|
tsgo/jsnum
Package jsnum provides JS-like number handling.
|
Package jsnum provides JS-like number handling. |
|
tsgo/nodebuilder
Exports interfaces and types defining the node builder - concrete implementations are on top of the checker, but these types and interfaces are used by the emit resolver in the printer
|
Exports interfaces and types defining the node builder - concrete implementations are on top of the checker, but these types and interfaces are used by the emit resolver in the printer |
|
tsgo/printer
Package printer exports a Printer for pretty-printing TS ASTs and writer interfaces and implementations for using them Intended ultimate usage:
|
Package printer exports a Printer for pretty-printing TS ASTs and writer interfaces and implementations for using them Intended ultimate usage: |
|
tsgo/pseudochecker
pseudochecker is a limited "checker" that returns pseudo-"types" of expressions - mostly those which trivially have type nodes
|
pseudochecker is a limited "checker" that returns pseudo-"types" of expressions - mostly those which trivially have type nodes |
|
tsgo/stringutil
Package stringutil Exports common rune utilities for parsing and emitting javascript
|
Package stringutil Exports common rune utilities for parsing and emitting javascript |
|
Package jsrt provides runtime support for TypeScript-to-Go transpiled code.
|
Package jsrt provides runtime support for TypeScript-to-Go transpiled code. |
|
array
Package array provides JavaScript Array.prototype method equivalents using Go generics.
|
Package array provides JavaScript Array.prototype method equivalents using Go generics. |
|
compat/lodash
Package lodash provides Go adapters for commonly used lodash/lodash-es functions.
|
Package lodash provides Go adapters for commonly used lodash/lodash-es functions. |
|
compat/uuid
Package uuid provides a Go adapter for the npm "uuid" package.
|
Package uuid provides a Go adapter for the npm "uuid" package. |
|
compat/zod
Package zod provides a Go adapter for the npm "zod" schema validation library.
|
Package zod provides a Go adapter for the npm "zod" schema validation library. |
|
console
Package console provides console.log/error/warn for transpiled TypeScript code.
|
Package console provides console.log/error/warn for transpiled TypeScript code. |
|
fetch
Package fetch provides the fetch() API for transpiled TypeScript code.
|
Package fetch provides the fetch() API for transpiled TypeScript code. |
|
node/crypto
Package crypto provides Node.js crypto module equivalents for transpiled TypeScript code.
|
Package crypto provides Node.js crypto module equivalents for transpiled TypeScript code. |
|
node/fs
Package fs provides Node.js fs module equivalents for transpiled TypeScript code.
|
Package fs provides Node.js fs module equivalents for transpiled TypeScript code. |
|
node/http
Package http provides Node.js http module equivalents for transpiled TypeScript code.
|
Package http provides Node.js http module equivalents for transpiled TypeScript code. |
|
node/path
Package path provides Node.js path module equivalents for transpiled TypeScript code.
|
Package path provides Node.js path module equivalents for transpiled TypeScript code. |
|
promise
Package promise provides a Promise[T] type for transpiled async/await TypeScript code.
|
Package promise provides a Promise[T] type for transpiled async/await TypeScript code. |
|
web
Package web provides Go struct definitions for Web API types used by transpiled TypeScript code.
|
Package web provides Go struct definitions for Web API types used by transpiled TypeScript code. |
|
third_party
|
|
|
Package tsgotranspile wraps tsgo's compiler.Program.Emit for in-memory TypeScript -> JavaScript transpilation.
|
Package tsgotranspile wraps tsgo's compiler.Program.Emit for in-memory TypeScript -> JavaScript transpilation. |
|
Package workers provides a Cloudflare-Workers-style handler runtime on top of Ramune.
|
Package workers provides a Cloudflare-Workers-style handler runtime on top of Ramune. |