js

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: BSD-3-Clause Imports: 21 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Go Reference

js

An experimental, pure Go embeddable JavaScript engine with a just-in-time compiler, no cgo. It is QuickJS, translated to Go with ccgo, plus a JIT tier that compiles hot JavaScript functions to machine code through modernc.org/jit/qbe.

The API follows modernc.org/quickjs: this package started as a copy of it (quickjs commit 80747b6), retargeted to its own build of QuickJS in internal/libquickjs, so code written for one runs on the other. Package intl is quickjs/intl, copied the same way: Intl.DateTimeFormat and Intl.NumberFormat for a VM that registers them.

modernc.org/webview runs on it unchanged but for its imports: its whole canvas test suite passes with the JIT on, including the pages built on jQuery, htmx, Chart.js, uPlot and KaTeX.

Status

Experimental. linux/amd64 only. The JIT needs Go 1.27 or a Go 1.28 development snapshot that qbe supports. The package builds with Go 1.26, the minimum in go.mod, but there qbe can't run code: the first function the JIT tries fails with qbe.ErrUnsupported, the tier stops, and every script runs interpreted.

The JIT is on by default: a VM compiles a function after 1000 calls, or when it runs a hot loop, in the background. VM.SetJIT(false) turns it off for a VM, and the environment switches below override the defaults.

  • With the JIT on at a threshold of 1, so that every function is compiled at its first call, test262 has the same 58 errors in 83,558 tests as the interpreter.
  • The JIT compiles every function of jQuery 3.7.1, Chart.js 4.5.1, uPlot 1.6.32 and htmx 1.9.12 and 2.0.4 without handing anything back to the interpreter. It also handles generators, async functions, classes with private fields, destructuring, try/catch/finally and eval.
  • Regular expressions compile too: a regexp that has run 100 times runs as machine code translated from libregexp's bytecode. It gives the results libregexp gives: a differential test compares the two on thousands of patterns, flags and subjects, and test262's RegExp and String tests pass with every regexp compiled at its first exec. With split searching for each match instead of trying each position, the V8 RegExp benchmark went from 0.785 of modernc.org/quickjs's time to 0.200 on one CPU.

Trust

This package is not a security boundary. Scripts run inside the host process: the interpreter is C QuickJS translated to Go, working on memory outside Go's heap, and the JIT's machine code runs on the host's goroutine stacks. A bug in either, or in qbe, can corrupt the host's memory instead of failing with a Go error. Run scripts you don't trust in a separate process, under the operating system's limits. JS_JIT_THRESHOLD=0 removes the generated code, but not the rest of that risk.

Usage

As for modernc.org/quickjs:

m, err := js.NewVM()
if err != nil {
	return err
}

defer m.Close()

v, err := m.Eval("1 + 2", js.EvalGlobal)

The JIT tier

The interpreter stays in charge. A function gets compiled after a number of calls, or when the interpreter finds it running a hot loop, in which case the compiled code takes over at the loop header (on-stack replacement). Generators and async functions resume in compiled code. Compiled code works on the interpreter's own frames and hands back to it for whatever it doesn't handle, so the two can switch at any instruction.

Compiling takes milliseconds per function (a median of 8 to 10 ms for the functions of jQuery and Chart.js), so the JIT can compile in the background while the interpreter goes on. One second after the last compile ends, the tier returns the compiler's idle memory (qbe.Trim).

Compiled code is shared by all the VMs of a process, keyed by a hash of its IL, and never freed, because qbe modules cannot be unloaded. A small function keeps about 40 KB for the rest of the process, a larger one more, so at the default budget of 10,000 compiled functions a process can keep 400 MB or more. Once the budget is used up, the functions not compiled by then stay interpreted. A long-running host that meets open-ended code, a browser for example, should set the budget to what it can afford to keep (JS_JIT_BUDGET). Compiled regexps count against the same budget. This is a hard limit, not a missing feature: see Compiled code is never freed for why, and for the uses it rules out.

Development switches, read once at program start:

Environment variable Meaning
JS_JIT_THRESHOLD the number of calls after which a function is compiled, 1000 by default; 0 turns the JIT off for every VM, also against SetJIT(true)
JS_JIT_ASYNC 0: compile and link on the calling thread, which waits; by default the interpreter goes on meanwhile
JS_JIT_BUDGET the number of functions compiled in the life of the process, 10,000 by default
JS_JIT_DIRECT 0: compiled code calls other compiled functions through their generic entries, not their direct-call entries
JS_JIT_MAX_BLOCKS the IL blocks a function's code may take before the rest of it hands over to the interpreter, 1200 by default
JS_JIT_TRIM_IDLE how long the tier waits after its last compile before it returns the compiler's idle memory, a duration such as 1s (the default); 0 never
JS_JIT_RE_THRESHOLD the number of execs after which a regexp is compiled, 100 by default; 0 keeps every regexp in libregexp's interpreter

Performance

The V8 benchmark suite (version 7) and the 58 QuickJS micro benchmarks, time as a fraction of modernc.org/quickjs's, which is the same QuickJS interpreted, so its column is what the JIT saves over the interpreter. make benchmark in compare, -benchtime 5s, at jit fa7a159 (2026-11-15, linux/amd64, AMD Ryzen 9 3900X, a shared host, load about 4 to 6). C QuickJS is a native qjs of QuickJS 2026-06-04 built by gcc 14.2 -O2, run by v8native.sh. moejs is a pure Go engine written from scratch, without a JIT; goja and Sobek are pure Go engines too.

The V8 suite, GOMAXPROCS=4:

Richards DeltaBlue Encrypt Decrypt RayTrace Earley Boyer RegExp Splay NavierStokes geomean
this package 0.327 0.367 0.095 0.086 0.334 0.401 0.252 0.210 0.464 0.149 0.233
C QuickJS 0.304 0.353 0.240 0.235 0.350 0.346 0.292 0.405 0.415 0.324 0.321
moejs 0.220 0.263 0.142 0.140 0.235 0.209 0.176 0.139 0.236 0.154 0.186

Geomeans, also with the V8 suite on one pinned CPU (GOMAXPROCS=1, the same commit):

V8 suite, GOMAXPROCS=4 V8 suite, GOMAXPROCS=1 micro benchmarks, GOMAXPROCS=4
modernc.org/quickjs 1 1 1
this package 0.233 0.237 0.345
C QuickJS 0.321 0.322 not run
moejs 0.186 0.226 0.300
goja 1.727 2.137 1.553
Sobek 1.748 2.212 1.539

This package is faster than native C QuickJS on the V8 suite, and faster than moejs on Encrypt, Decrypt, NavierStokes and 28 of the 58 micro benchmarks: the loops, integer and float arithmetic, number formatting, function calls, property reads and writes, array and typed array reads and writes, global reads, string building and regexps on UTF-16 strings. Since fa7a159, reading a local variable or an argument takes no reference where nothing but the function itself can change it: NavierStokes went from 0.229 to 0.149, Encrypt and Decrypt by about a fifth. RegExp was 0.811 at 599d852 (2026-11-12), when QuickJS's regular expression engine, libregexp, ran as C translated to Go. Regexps compile now, and split searches for each match: 0.210, against moejs's 0.139 (one CPU: 0.224 and 0.180).

Compiling happens in the background, so starting cold costs little. The whole suite in a new VM, setup and one run of each benchmark, then a second run, in seconds (2026-11-09, load about 9):

first run second run
interpreter 2.70 1.51
JIT, threshold 1000, background compiles (the default) 2.55 1.10
JIT, threshold 10, background compiles 2.79 1.20
JIT, threshold 1, compiles on the calling thread 12.6 0.99

make benchmark in compare runs the V8 suite and the QuickJS micro benchmarks on this package, modernc.org/quickjs, goja, Sobek and moejs; make benchmark-qjs there adds native C QuickJS on the V8 suite.

Development

  • go test -short ./... runs the quick tests. A plain go test ./... also runs test262, which is heavy: several minutes on one core. go test -run Test262 . -args -test262.jit 1 runs it with the JIT on, every function compiled at its first call: about 6 to 7 minutes and up to 2.4 GB of memory. -race needs -gcflags=all=-d=checkptr=0, because libqbe's translated C trips Go's checkptr. make shorttest and make test run the same on the main package, with -vet=off, which only saves time.
  • FuzzJIT (in every go test) compares the interpreter and the JIT on random programs; go test -run FuzzJIT . -args -fuzzjit.seeds 600 -fuzzjit.rand N runs a batch of 600, about a minute on one core.
  • make leak runs the tests under libc's memory audit, with the JIT tests.
  • internal/libquickjs is generated from QuickJS by make generate; see CLAUDE.md for the patches and the generator.
  • PLAN.md records the design, the decisions and every step with its measurements. HANDOFF.md is the backend's contract.

License

BSD-style, see LICENSE. QuickJS is under the MIT license, see LICENSE-QUICKJS.

Documentation

Overview

Package js is a pure Go embeddable JavaScript engine with a JIT tier in development. Its API follows modernc.org/quickjs, from which this code was copied on 2026-11-06 (quickjs commit 80747b6). It runs on its own ccgo build of QuickJS in internal/libquickjs.

Status

Experimental. The JIT tier compiles hot functions with modernc.org/jit/qbe. It is on by default: a VM compiles a function after 1000 calls, or when it runs a hot loop, in the background while the interpreter goes on. VM.SetJIT turns it off and on for a VM. See README.md and PLAN.md in the module root.

Supported platforms and architectures

linux/amd64 only, for now.

Example (Ping)

Multiple concurrent Javascript virtual machines communicating via Go channels.

package main // import "modernc.org/jit/js"

import (
	"fmt"
)

// Multiple concurrent Javascript virtual machines communicating via Go channels.
func main() {
	tx := make(chan string, 1)
	rx := make(chan string, 1)
	client, _ := NewVM()
	defer client.Close()
	registerFuncs(client, tx, rx)
	go func() { // Start the server.
		server, _ := NewVM()
		defer server.Close()
		registerFuncs(server, rx, tx)
		server.Eval("send(receive()+' reply');", EvalGlobal)
	}()
	fmt.Println(client.Eval("send('ping'); receive();", EvalGlobal)) // Ping the server.
}

func registerFuncs(m *VM, tx, rx chan string) {
	m.RegisterFunc("send", func(s string) { tx <- s }, false)
	m.RegisterFunc("receive", func() string { return <-rx }, false)
}
Output:
ping reply <nil>

Index

Examples

Constants

View Source
const (
	EvalGlobal = lib.MJS_EVAL_TYPE_GLOBAL // global code
	EvalModule = lib.MJS_EVAL_TYPE_MODULE // module code
)

Eval flags.

Variables

View Source
var (

	// UndefinedValue is a Value representing Javascript value 'undefined'. It is
	// not associated with any particular VM.
	UndefinedValue = Value{/* contains filtered or unexported fields */}
)

Functions

func Version

func Version() string

Version returns the underlying QuickJS version.

Types

type Atom

type Atom = lib.TJSAtom

Atom is an unique identifier of, for example, a string value. Atom values are VM-specific.

type Error

type Error struct {
	Name         string // e.g. "ReferenceError", "TypeError"
	Message      string // the error message
	Stack        string // stack trace, one "    at ...\n" frame per line
	LineNumber   int    // line where the error occurred (parse errors only)
	ColumnNumber int    // column where the error occurred (parse errors only)
	FileName     string // file name where the error occurred (parse errors only)
	// contains filtered or unexported fields
}

Error holds structured information from a JavaScript exception. The error returned by VM.Eval, VM.Call and the other eval-family methods is an *Error; recover the fields with errors.As:

var e *quickjs.Error
if errors.As(err, &e) {
	fmt.Println(e.Stack)
}

Its Error method reports the same message string the engine has always returned, so existing code comparing the error text keeps working.

Only parse/syntax errors carry the FileName, LineNumber and ColumnNumber properties. For runtime errors those fields are zero and the source location is available only from Stack.

func ErrorFromValue

func ErrorFromValue(v Value) *Error

ErrorFromValue extracts structured error information from JavaScript error value 'v', typically an Error instance caught from a JS exception.

'v' is borrowed: ErrorFromValue does not free it and the caller remains responsible for its lifetime. Like all VM operations it must be called from the VM's own goroutine. See Error for which fields are populated.

A field that cannot be read stays empty: the result of the Error method when the toString of 'v' throws, a property whose getter throws, any property of a value that has none, such as null, and a string when there is no memory to convert it. ErrorFromValue drops the exceptions that reading throws, so it leaves none pending.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface. It returns the same string the engine produces for the exception, unchanged from earlier releases.

type HostFunc

type HostFunc func(args []any) (any, error)

HostFunc is a Go function exposed to JavaScript by RegisterHostFunc. It receives the call arguments already converted to Go values and returns a single value to convert back to JS, or a non-nil error which is thrown as a JavaScript exception.

type ModuleLoaderFunc

type ModuleLoaderFunc func(vm *VM, moduleName string) (string, error)

ModuleLoaderFunc defines the signature for a custom module loader. It must return the module's source code (Javascript).

type ModuleNormalizeFunc

type ModuleNormalizeFunc func(vm *VM, moduleBaseName, moduleName string) (string, error)

ModuleNormalizeFunc defines the signature for a custom module normalizer. It receives the base name (the module making the import) and the requested name, and should return the normalized, absolute module name.

type Object

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

Object represents the value of a Javascript object, but not the javascript object instance itself. Do not compare instances of Object.

func (*Object) Into

func (o *Object) Into(v any) error

Into helps you quickly deserialize an Object into a native Go type. This uses encoding/json.Unmarshal internally, so the target type must be compatible with that package.

Example

JSON unmarshalling into native Go struct.

m, _ := NewVM()
defer m.Close()
obj, _ := m.Eval("obj = {a: 42+314, b: 'foo'}; obj;", EvalGlobal)
var dst struct {
	A int    `json:"a"`
	B string `json:"b"`
}
obj.(*Object).Into(&dst)
fmt.Printf("%#v\n", dst)
Output:
struct { A int "json:\"a\""; B string "json:\"b\"" }{A:356, B:"foo"}

func (*Object) MarshalJSON

func (o *Object) MarshalJSON() (r []byte, err error)

MarshalJSON implements encoding/json.Marshaler.

Example

JSON marshalling.

m, _ := NewVM()
defer m.Close()
obj, _ := m.Eval("obj = {a: 42+314, b: 'foo'}; obj;", EvalGlobal)
s, _ := (obj.(*Object).MarshalJSON())
fmt.Printf("%s\n", s)
Output:
{"a":356,"b":"foo"}

func (*Object) String

func (o *Object) String() string

String implements fmt.Stringer.

Example

JSON marshalling.

m, _ := NewVM()
defer m.Close()
obj, _ := m.Eval("obj = {a: 42+314, b: 'foo'}; obj;", EvalGlobal)
fmt.Printf("%s\n", obj)
Output:
{"a":356,"b":"foo"}

type PromiseCapability

type PromiseCapability struct {
	Promise Value
	Resolve Value
	Reject  Value
}

PromiseCapability holds a Promise along with its resolve and reject functions, obtained without evaluating JS source.

func (*PromiseCapability) Dup

Dup duplicates the capability — its promise and both resolving functions — returning a new PromiseCapability that must itself be released via Free.

func (*PromiseCapability) Free

func (pc *PromiseCapability) Free()

Free releases all values held by the capability.

type Undefined

type Undefined struct{}

Undefined represents the Javascript value "undefined".

func (Undefined) String

func (u Undefined) String() string

String implements fmt.Stringer.

type Unsupported

type Unsupported struct{}

Unsupported represents an unsupported Javascript value.

func (Unsupported) String

func (u Unsupported) String() string

String implements fmt.Stringer.

type VM

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

VM represents a Javascript context (or Realm). Each VM has its own global objects and system objects.

Note: VM is not safe for concurrent use by multiple goroutines, except for VM.Interrupt.

A Go function that Javascript calls may panic: the Javascript stops, without running its catch or finally blocks, and the panic goes on in the Go code that called that Javascript. runtime.Goexit, which t.Fatal calls, cannot be stopped that way. It goes up through the engine and abandons the Javascript it was running, as does a panic in the engine itself. Such a VM can only be closed: every later method that uses the engine panics, Value.Free does nothing, and Close leaks the engine's memory.

func NewVM

func NewVM() (*VM, error)

NewVM returns a newly created VM.

func (*VM) Call

func (m *VM) Call(function string, args ...any) (r any, err error)

Call evaluates 'function(args...)' and returns the resulting (value, error).

Argument types must be one of:

Go argument type                        Javascript argument type
----------------------------------------------------------------
nil                                     null
Undefined                               undefined
string                                  string
int*/uint* (value in int32 range)       int
int*/uint* (value out of int32 range)   float
bool                                    bool
float64                                 float64
*math/big.Int                           BigInt
*Object                                 object
Value                                   native Javascript Value
any other type                          object from JSON produced by encoding.json/Marshall(arg)
Example (Function)

Call a Javascript function.

m, _ := NewVM()
defer m.Close()
fmt.Println(m.Call("parseInt", "1234"))
Output:
1234 <nil>
Example (Method)

Call a Javascript method.

m, _ := NewVM()
defer m.Close()
fmt.Println(m.Call("Math.abs", -1234))
Output:
1234 <nil>

func (*VM) CallValue

func (m *VM) CallValue(function string, args ...any) (r Value, err error)

CallValue is like Call but returns (Value, error) like EvalValue

Note: See the Value documentation for details about manual memory management of Value objects.

func (*VM) Close

func (m *VM) Close() error

Close releases the resources held by 'm'. That includes the module loader and normalizer set by VM.SetModuleLoader: Close removes them, so a closed VM keeps nothing they close over reachable.

func (*VM) Compile

func (m *VM) Compile(javascript string, flags int) ([]byte, error)

Compile compiles the bytecode representation of the passed script.

The returned bytecode can be later executed using EvalBytecode or EvalBytecodeValue.

Note: The bytecode format is linked to a given QuickJS version.

func (*VM) Eval

func (m *VM) Eval(javascript string, flags int) (r any, err error)

Eval evaluates a script or module source in 'javascript'.

Javascript result type  Go result type                          Go result error
-------------------------------------------------------------------------------
exception               nil                                     non-nil
null                    nil                                     nil
undefined               Undefined                               nil
string                  string                                  nil
int                     int                                     nil
bool                    bool                                    nil
float64                 float64                                 nil
BigInt                  *math/big.Int                           nil
object                  *Object                                 nil
any other type          Unsupported                             nil
Example (Exception)

Getting exception.

m, _ := NewVM()
defer m.Close()
fmt.Println(m.Eval("throw new Error('failed');", EvalGlobal))
Output:
<nil> Error: failed
Example (Expression)

Evaluate a simple Javascript expression.

m, _ := NewVM()
defer m.Close()
fmt.Println(m.Eval("1+2", EvalGlobal))
Output:
3 <nil>
Example (Object)

Object example.

m, _ := NewVM()
defer m.Close()
fmt.Println(m.Eval("obj = {a: 42+314, b: 'foo'}; obj;", EvalGlobal))
Output:
{"a":356,"b":"foo"} <nil>

func (*VM) EvalBytecode

func (m *VM) EvalBytecode(bytecode []byte) (r any, err error)

EvalBytecode is like Eval but uses QuickJS bytecode.

Note: The bytecode format is linked to a given QuickJS version. Moreover, no security check is done before its execution. Hence the bytecode should not be loaded from untrusted sources.

Note: Javascript 'this' is always set to the global context.

func (*VM) EvalBytecodeValue

func (m *VM) EvalBytecodeValue(bytecode []byte) (r Value, err error)

EvalBytecodeValue is like EvalValue but operates on QuickJS bytecode.

Exceptions thrown during evaluation of the script are returned as Go errors.

If no error is returned, the caller must properly handle the returned Value using Dup/Free.

Note: See the Value documentation for details about manual memory management of Value objects.

func (*VM) EvalThis

func (m *VM) EvalThis(obj Value, javascript string, flags int) (r any, err error)

EvalThis is like eval but sets javascript 'this' to 'obj'.

func (*VM) EvalThisValue

func (m *VM) EvalThisValue(obj Value, javascript string, flags int) (r Value, err error)

EvalThisValue is like EvalValue but sets javascript 'this' to obj.

func (*VM) EvalValue

func (m *VM) EvalValue(javascript string, flags int) (r Value, err error)

EvalValue evaluates a script or module source in 'javascript' and returns the resulting Value, or an error, if any.

Exceptions thrown during evaluation of the script are returned as Go errors.

If no error is returned, the caller must properly handle the returned Value using Dup/Free.

Note: See the Value documentation for details about manual memory management of Value objects.

func (*VM) ExecutePendingJobs

func (m *VM) ExecutePendingJobs() (n int, err error)

ExecutePendingJobs runs queued Javascript jobs — Promise reactions (the .then/.catch/.finally callbacks) and async/await continuations — until the queue is empty, returning the number of jobs executed. The runtime does not run these itself: an embedding event loop calls ExecutePendingJobs at the end of each turn to drain the microtask queue (so a resolved Promise's .then runs, a pending await resumes, etc.). An exception thrown by a job is returned as an error — the first one — while the remaining jobs still run; a self-feeding job queue is bounded so it cannot hang the host. An interrupt, by Interrupt or the eval timeout, ends the drain: the remaining jobs stay queued.

func (*VM) GetProperty

func (m *VM) GetProperty(this Value, prop Atom) (r any, err error)

GetProperty returns this.prop.

func (*VM) GetPropertyValue

func (m *VM) GetPropertyValue(this Value, prop Atom) (r Value, err error)

GetPropertyValue returns this.prop.

Note: See the Value documentation for details about manual memory management of Value objects.

func (*VM) GlobalObject

func (m *VM) GlobalObject() (r Value)

GlobalObject returns m's global object.

Note: See the Value documentation for details about manual memory management of Value objects.

func (*VM) Interrupt

func (m *VM) Interrupt()

Interrupt requests 'm' to interrupt Javascript evaluation. Interrupt can be called asynchronously, from any goroutine, at any time m is evaluating a script. The request stays pending until the Go call into Javascript returns: Javascript that a Go function called from Javascript evaluates on 'm' does not clear it. Interrupt can also be called while 'm' closes and after Close, where it does nothing.

Example
const timeout = time.Second
m, _ := NewVM()
defer m.Close()

go func() {
	time.Sleep(timeout)
	m.Interrupt()
}()

t0 := time.Now()
r, err := m.Eval(`
function f() {
	var sink;
	for (var i = 0; i < 10000; i++) {
		sink += 42;
		sink -= 42;
	}
}

(function() {
	for (;;) {
		f();
	}
})();
`, EvalGlobal)
d := time.Since(t0)
step := timeout / 5
d = d / step * step
fmt.Println(r, err, d)
Output:
<nil> InternalError: interrupted 1s

func (*VM) NewAtom

func (m *VM) NewAtom(s string) (r Atom, err error)

NewAtom returns an unique indentifier of 's' or an error, if any.

func (*VM) NewFloat64

func (m *VM) NewFloat64(n float64) Value

NewFloat64 returns a new Value from 'n'.

Note: See the Value documentation for details about manual memory management of Value objects.

func (*VM) NewInt

func (m *VM) NewInt(n int) Value

NewInt returns a new Value from 'n'.

Note: See the Value documentation for details about manual memory management of Value objects.

func (*VM) NewObjectValue

func (m *VM) NewObjectValue() (r Value, err error)

NewObjectValue returns a new Value representing '{}'.

func (*VM) NewPromiseCapability

func (m *VM) NewPromiseCapability() (*PromiseCapability, error)

NewPromiseCapability creates a new JavaScript Promise along with its resolve and reject functions.

The returned PromiseCapability must be freed via Free when no longer needed.

To expose a promise to JS from a Go function registered with RegisterFunc, return pc.Promise from the Go function. The resolve/reject values captured by the closure need no Dup because the C API already holds a reference for each:

m.RegisterFunc("delayed", func(delay int) Value {
    pc, err := m.NewPromiseCapability()
    if err != nil { panic(err) }
    youreventloop.Schedule(func() {
        time.Sleep(time.Duration(delay) * time.Millisecond)
        pc.Resolve.Call(UndefinedValue, "done")
        pc.Resolve.Free()
        pc.Reject.Free()
        // pc.Promise.Free() // <- only if returned pc.Promise.Dup()!
    })
    return pc.Promise
}, false)

func (*VM) NewString

func (m *VM) NewString(s string) (r Value, err error)

NewString returns a new Value from 's'.

Note: See the Value documentation for details about manual memory management of Value objects.

func (*VM) RegisterFunc

func (m *VM) RegisterFunc(name string, f any, wantThis bool) error

RegisterFunc registers a Go function 'f' and makes it callable from Javascript.

The 'f' argument can be a regular Go function, a closure, a method expression or a method value. All of them are called 'Go function' below.

The Go function can have zero or more parameters. If 'wantThis' is true then the first parameter of the Go function will get the Javascript value of 'this'. Depending on context, 'this' can be Javascript null or undefined.

Go functions with multiple results return them as an Javascript array.

Go nil errors are converted to Javascript null.

Go non-nil errors are converted to Javascript strings using the Error() method.

Any Go <-> Javascript failing type conversion between arguments/return values throws a Javascript type error exception.

There is a limit on the total number of currently registered Go functions.

The Go function becomes the property 'name' of the global object, writable, configurable and not enumerable. It replaces a configurable property of that name, such as one a script assigned or a built-in like Array. A property that is not configurable, such as undefined, NaN or one a script declared with var or function, stays, and RegisterFunc returns an error, as it does when the global object is not extensible. A name registered before on the same VM is an error too, even when a script has since deleted or replaced that function. 'name' is the string Javascript sees, with invalid UTF-8 replaced as for any other Go string, so two Go strings can be the same name. A NUL byte in 'name' is an error.

Note: The 'name' argument should be a valid Javascript identifier. It is not currently enforced but this may change later.

For binding host objects (a DOM, console, fetch, …) prefer RegisterHostFunc, which gives the more convenient single-return / error-throws-exception shape.

Example (Error)

Call error returning Go function from Javascript.

m, _ := NewVM()
defer m.Close()
m.RegisterFunc("gofunc", func(a int) error {
	if a < 0 {
		return fmt.Errorf("negative")
	}
	return nil
}, false)
fmt.Println(m.Eval("gofunc(-1)", EvalGlobal))
fmt.Println(m.Eval("gofunc(1)", EvalGlobal))
Output:
negative <nil>
<nil> <nil>
Example (MultipleReturn)

Call multiple return Go function from Javascript.

m, _ := NewVM()
defer m.Close()
m.RegisterFunc("gofunc", func(a, b int) (int, int) { return 10 * a, 100 * b }, false)
fmt.Println(m.Eval("gofunc(2, 3)", EvalGlobal))
Output:
[20,300] <nil>
Example (SingleReturn)

Call single return Go function from Javascript.

m, _ := NewVM()
defer m.Close()
m.RegisterFunc("gofunc", func(a, b, c int) int { return a + b*c }, false)
fmt.Println(m.Eval("gofunc(2, 3, 5)", EvalGlobal))
Output:
17 <nil>
Example (ThisNonNull)

Passing Javascript 'this' to a Go function.

m, _ := NewVM()
defer m.Close()
m.RegisterFunc("gofunc", func(this any) any { return this }, true)
fmt.Println(m.Eval("var obj = { foo: 314, method: gofunc }; obj.method()", EvalGlobal))
Output:
{"foo":314} <nil>
Example (ThisNonNull2)

Passing Javascript 'this' to a Go function.

m, _ := NewVM()
defer m.Close()
m.RegisterFunc("gofunc", func(this any, n int) (any, int) { return this, 10 * n }, true)
fmt.Println(m.Eval("var obj = { foo: 314, method: gofunc }; obj.method(42)", EvalGlobal))
Output:
[{"foo":314},420] <nil>
Example (ThisNull)

Passing undefined Javascript 'this' to a Go function.

m, _ := NewVM()
defer m.Close()
m.RegisterFunc("gofunc", func(this any) any { return this }, true)
fmt.Println(m.Eval("gofunc()", EvalGlobal))
Output:
undefined <nil>
Example (ThisNull2)

Passing undefined Javascript 'this' to a Go function.

m, _ := NewVM()
defer m.Close()
m.RegisterFunc("gofunc", func(this any, n int) (any, int) { return this, 10 * n }, true)
fmt.Println(m.Eval("gofunc(42)", EvalGlobal))
Output:
[null,420] <nil>
Example (Void)

Call void Go function from Javascript.

m, _ := NewVM()
defer m.Close()
m.RegisterFunc("gofunc", func(a, b, c int) { fmt.Println(a + b*c) }, false)
fmt.Println(m.Eval("gofunc(2, 3, 5)", EvalGlobal))
Output:
17
undefined <nil>

func (*VM) RegisterHostFunc

func (m *VM) RegisterHostFunc(name string, fn HostFunc) error

RegisterHostFunc exposes fn to JavaScript as a global function named name, using the calling convention an embedding host wants: every JS call argument arrives in the single []any slice (already converted to Go values), fn returns exactly one value to convert back to JS, and a non-nil error is thrown as a JavaScript exception.

This differs from RegisterFunc, whose reflection mapping turns a Go multiple-return into a JS array and converts a returned error like any other value (so a (value, error) pair becomes the array [value, error] rather than a value-or-throw). RegisterHostFunc is the better fit for binding host objects; RegisterFunc remains for direct, typed Go calls.

'name' is handled as by RegisterFunc, also when the global object already has it.

func (*VM) SetCanBlock

func (m *VM) SetCanBlock(value bool)

SetCanBlock configures m's blocking mode.

func (*VM) SetDefaultModuleLoader

func (m *VM) SetDefaultModuleLoader()

SetDefaultModuleLoader will enable loading module using the default module loader.

Example

Enabling the module loader.

m, _ := NewVM()
defer m.Close()
m.SetDefaultModuleLoader()
// testdata/power.js:
//  export const name = "Power";
//
//  export function square(x) {
//  	return x*x;
//  }
//
//  export function cube(x) {
//  	return x*x*x;
//  }
m.Eval("import * as Power from './testdata/power.js'; globalThis.Power = Power;", EvalModule)
fmt.Println(m.Eval("[Power.square(2), Power.cube(2)];", EvalGlobal))
Output:
[4,8] <nil>

func (*VM) SetEvalTimeout

func (m *VM) SetEvalTimeout(d time.Duration) error

SetEvalTimeout sets the timeout for the various eval functions. Passing zero 'd' disables timeouts.

The timeout starts when Go calls into Javascript. A Go function that Javascript called and that evaluates more Javascript on 'm' gets no new timeout, it runs in what is left of the outer one. The timeout runs on the monotonic clock, so setting the system clock does not move it.

Example
m, _ := NewVM()
defer m.Close()

for _, timeout := range []time.Duration{100 * time.Millisecond, time.Second, 3 * time.Second} {
	m.SetEvalTimeout(timeout)
	t0 := time.Now()
	r, err := m.Eval(`
function f() {
	var sink;
	for (var i = 0; i < 10000; i++) {
		sink += 42;
		sink -= 42;
	}
}

(function() {
	for (;;) {
		f();
	}
})();
`, EvalGlobal)
	d := time.Since(t0)
	min := timeout / 2
	max := timeout * 3 / 2
	fmt.Println(r, err, timeout, d >= min && d <= max)
}
Output:
<nil> InternalError: interrupted 100ms true
<nil> InternalError: interrupted 1s true
<nil> InternalError: interrupted 3s true

func (*VM) SetGCThreshold

func (m *VM) SetGCThreshold(threshold uintptr)

SetGCThreshold sets the memory threshold at which a GC will be performed, in bytes.

func (*VM) SetJIT

func (m *VM) SetJIT(on bool)

SetJIT turns the JIT tier on or off for m. It is on in a new VM. With it off, m runs all JavaScript in the interpreter, also functions compiled before: compiled code is shared by the VMs of the process and stays. JS_JIT_THRESHOLD=0 in the environment keeps it off.

func (*VM) SetMaxStackSize

func (m *VM) SetMaxStackSize(threshold uintptr)

SetMaxStackSize limits the JS call depth, in libc.TLS stack slots (~one per JS call frame in the CGo-free port). Deep recursion then throws a catchable "InternalError: stack overflow" instead of overflowing the Go goroutine stack, which would kill the process. 0 restores the default, the MaxStackSlots constant of modernc.org/libquickjs, which a new VM starts with.

func (*VM) SetMemoryLimit

func (m *VM) SetMemoryLimit(limit uintptr)

SetMemoryLimit limits m's maxmimum memory usage, in bytes. Small values of 'limit' are not honored because the VM needs to allocate memory also for the exception object itself. The particular value of "small" is unspecified and subject to change without notice.

func (*VM) SetModuleLoader

func (m *VM) SetModuleLoader(loader ModuleLoaderFunc, normalize ModuleNormalizeFunc)

SetModuleLoader configures custom Go functions to load and normalize Javascript modules. Passing nil for 'loader' removes the custom loader, and so does Close; until then the engine keeps 'loader' and 'normalize', and whatever they close over, reachable. If 'normalize' is nil, the engine falls back to the default QuickJS module normalizer.

func (*VM) SetProperty

func (m *VM) SetProperty(this Value, prop Atom, val any) (err error)

SetProperty sets this.prop = val.

func (*VM) SetPropertyValue

func (m *VM) SetPropertyValue(this Value, prop Atom, val Value) (err error)

SetPropertyValue sets this.prop = val.

func (*VM) SetWTF8

func (m *VM) SetWTF8(on bool)

SetWTF8 sets whether strings cross between Go and Javascript on 'm' as WTF-8, which keeps a lone surrogate. A Javascript string is a sequence of UTF-16 code units and can hold one half of a surrogate pair without the other, for example where code cut a string inside an emoji or built it one code unit at a time. UTF-8 cannot encode a lone surrogate, so by default it becomes U+FFFD on the way to Go, and each byte of a Go string that does not start a valid UTF-8 sequence becomes U+FFFD on the way to Javascript. A lone surrogate then does not survive a round trip through Go, and two halves of a pair kept apart in Go do not make the character again.

With 'on' true, a lone surrogate reaches Go as the three bytes of its code point, 0xED 0xA0-0xBF 0x80-0xBF, and a pair as the four bytes of the character it encodes. Go strings reach Javascript with those three bytes decoded as that code unit, so a high surrogate followed by a low one makes a pair, as when Go concatenates two strings that each hold one half. Any other byte that does not start a valid UTF-8 sequence still becomes U+FFFD. That applies to every string converted for 'm': values, arguments and results of Go functions, the keys and elements of the maps and slices they return, atoms, the names of functions registered after the call, the messages of errors and module names. Strings converted with encoding/json get U+FFFD either way: those in a struct a Go function returns, in a map, a slice or a struct passed to VM.Call, Value.Call, VM.SetProperty and the like, and in the result of Object.Into.

A Go string holding a lone surrogate is not valid UTF-8: a for range loop over it, utf8.ValidString and encoding/json see three invalid bytes.

func (*VM) StdAddHelpers

func (m *VM) StdAddHelpers() error

StdAddHelpers adds the 'print' and 'console' global objects to 'm'.

They write to the C stdout of the process, which this makes line buffered, so that every line goes out when printed, like the output of os.Stdout.

type Value

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

Value represents a native Javascript value. Values are reference counted and their lifetime is managed by an independent Javascript garbage collector. To avoid memory corruption/leaks caused by tripping the Javascript GC, a Value must not

  • be copied. Use the Dup method instead.
  • become unreachable without calling its Free method.
  • be used after its Free() method was called.
  • outlive its VM.

It is recommended to use native Go values instead of Value where possible.

When passing a Value down the call stack use Dup. For example in main

v, _ := EvalValue(someScript)
defer v.Free()
foo(v.Dup()) // Instead of foo(v)

In 'foo' Free must be used. For example

func foo(v Value) {
        defer v.Free()
        ...
}

This ensures the/only topmost Free marks 'v' eligible for garbage collection.

Beware that the correct setup/handling becomes more complicated when using closures, Values are sent through a channel etc. In particular, if a goroutine 1 passes a Dup of 'v' to goroutine 2 and goroutine 1 completes and thus frees 'v' before goroutine 2 completes, the reference counting mechanism will fail. In other words, every Free must be strictly paired with the Dup that preceded obtaining the Value and the Dup/Free calls must respect the original nesting. This is correct.

Dup             // in main
        Dup     // in foo
        Free    // in foo
Free            // in main

This will fail, for example in the above discussed goroutines scenario.

Dup            // in g1
        Dup    // in g2
Free           // in g1
        Free   // in g2

The fix might be in this case to arrange goroutine 1 to wait for goroutine 2 to complete before executing Free in goroutine 1.

See TestMemgrind for an example of how to detect memory leaks caused not only by improper Value use.

func (Value) Any

func (v Value) Any() (r any, err error)

Any attemtps to convert 'v' to any using the same rules as there are for the return value of VM.Eval.

func (Value) Call

func (v Value) Call(this Value, args ...any) (r any, err error)

Call evaluates 'v(args...)' with 'this' as the receiver and returns the resulting (value, error). 'v' must be a Javascript function. Pass UndefinedValue as 'this' when the function does not use it.

resolve.Call(quickjs.UndefinedValue, "done")
reject.Call(quickjs.UndefinedValue, err.Error())

Argument types are converted using the same rules as in VM.Call and the result is unpacked using the same rules as there are for the return value of VM.Eval. Note that a Go error is not one of the recognized types, so it is marshaled to JSON like any other value — and because the standard error types have no exported fields that yields '{}'. Pass err.Error() instead.

Note: A Value passed to a Go function registered by VM.RegisterFunc is valid only for the duration of that call. To call it later, for example to settle a promise after the Go function has returned, retain it using Value.Dup and release it using Value.Free when done.

Note: See the Value documentation for details about manual memory management of Value objects.

func (Value) CallValue

func (v Value) CallValue(this Value, args ...any) (r Value, err error)

CallValue is like Value.Call but returns (Value, error) like VM.EvalValue.

Note: See the Value documentation for details about manual memory management of Value objects.

func (Value) Dup

func (v Value) Dup() Value

Dup returns a copy of 'v' while updating its reference count.

func (*Value) Free

func (v *Value) Free()

Free marks 'v' as no longer used and updates its reference count. 'v' must not be used afterwards.

Free does nothing if the VM of 'v' was abandoned, see VM.

func (Value) GetProperty deprecated

func (v Value) GetProperty(this Value, prop Atom) (r any, err error)

GetProperty returns v.prop. The 'this' argument is ignored.

Deprecated: The 'this' argument is vestigial, the property is always looked up on 'v'. Use Value.Property instead.

func (Value) GetPropertyValue

func (v Value) GetPropertyValue(prop Atom) (r Value, err error)

GetPropertyValue returns v.prop.

func (Value) IsUndefined

func (v Value) IsUndefined() bool

IsUndefined reports whether 'v' represents the Javascript value 'undefined'.

func (Value) MarshalJSON

func (v Value) MarshalJSON() (r []byte, err error)

MarshalJSON implements encoding/json.Marshaler.

func (Value) Property

func (v Value) Property(prop Atom) (r any, err error)

Property returns v.prop. It is Value.GetProperty without the vestigial 'this' argument.

func (Value) SetProperty

func (v Value) SetProperty(prop Atom, val any) (err error)

SetProperty sets v.prop = val.

func (Value) SetPropertyValue

func (v Value) SetPropertyValue(prop Atom, val Value) (err error)

SetPropertyValue sets v.prop = val.

func (Value) Then

func (v Value) Then(onFulfilled, onRejected func(Value)) (_ Value, err error)

Then attaches fulfillment and rejection handlers to the Promise v, returning the new promise for chaining. Either onFulfilled or onRejected may be nil.

func (*Value) VM

func (v *Value) VM() *VM

VM returns the VM associated with 'v'.

Directories

Path Synopsis
internal
jit
Package jit is the JIT tier of modernc.org/jit/js.
Package jit is the JIT tier of modernc.org/jit/js.
libquickjs
Package libquickjs is the ccgo translation of [QuickJS] that modernc.org/jit/js runs on.
Package libquickjs is the ccgo translation of [QuickJS] that modernc.org/jit/js runs on.
run-test262 command
Package intl implements ECMA-402, the ECMAScript Internationalization API, for a quickjs.VM.
Package intl implements ECMA-402, the ECMAScript Internationalization API, for a quickjs.VM.

Jump to

Keyboard shortcuts

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