beastjs

package module
v0.33.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 23 Imported by: ? modules, 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

beastjs

The fastest pure Go JavaScript engine for rendering React.

简体中文 · How fast · API · Benchmarks · Changelog

Go reference Go version CGO off License Not backed by Y Combinator Users unknown

Your Go server renders React pages itself, faster than C QuickJS on the same code, in one static binary with no cgo and no Node process beside it.

It is for Go programs that need to run JavaScript, such as rendering React on the server. The engine runs ES2023 with modules, async generators, proxies, BigInt, and Intl in every Chromium locale and Temporal, both built in. It is built for tifa, a Go framework for React pages.

It is an engine, not Node: there is no require, fs or process. Code from npm runs unchanged once it is bundled as for a browser, as React is.

How fast

CPU time of one render of the server bundles of tifa's apps, on one core, as a multiple of liustack/beastjs (lower is faster):

Engine Pure Go React bench pages MUI pages Shop pages
liustack/beastjs yes 1.00 1.00 1.00
liustack/beastjs, on polyfills yes 1.03 1.71 1.62
moejs yes 1.52 1.52 1.99
go-quickjs yes 2.31 2.12 3.11
C QuickJS 2026-06-04 no, C 2.06 3.63 2.59
Hermes V1 no, C++ 1.08 1.90 1.86
Node 26 --jitless no, C++ 0.99 1.11 0.90

Measured on v0.32.0 (the engine of v0.33.0, under the module path of then) on a GCP t2d-standard-4 (AMD EPYC 7B13), Go 1.27.4. The comparison is among interpreters: go-quickjs runs with its JIT off, as it comes, Hermes runs hermesc -O bytecode and Node runs with --jitless. Every engine runs as it comes, on its own Intl where it has one and on the FormatJS polyfill where it has none (C QuickJS and Hermes). The second row is liustack/beastjs without its built-in Intl, URL and Temporal, on the same polyfills as C QuickJS and Hermes: it shows how much of the lead on the MUI and shop pages comes from the interpreter and how much from Intl written in Go. The bench pages need no Intl, so that column is the same JavaScript on every engine.

It is not the fastest on everything: on the V8 benchmark suite go-quickjs and Node score higher, and Hermes about the same.

Engine Pure Go V8 suite score
go-quickjs yes 2308
Node 26 --jitless no, C++ 2240
liustack/beastjs yes 2160
Hermes V1 no, C++ 2096
moejs yes 1816
C QuickJS 2026-06-04 no, C 1172

It scores 1.85 times C QuickJS and 1.20 times moejs, and is ahead of each of them in every round. go-quickjs scores 1.07 times as much as it does, and leads on the RegExp, NavierStokes, Crypto and DeltaBlue benchmarks.

docs/use/benchmarks.md has both tables in full, what each engine was given to run, and how to run it all again.

Install

go get github.com/liustack/beastjs

Go 1.26.6 or later, up to Go 1.27. No cgo and no C compiler: it builds with CGO_ENABLED=0 and cross-compiles like any Go code. The Go assembly of the engine was checked against every patch release from Go 1.26.6 to 1.27.4, and a new patch release is checked every week. It leans on how Go starts a function and handles a fault, so a newer Go stops the build until liustack/beastjs has been checked with it and moves its limit in a patch release. -tags beastjs_anygo builds anyway (see Moving to a newer Go).

Platforms

linux, darwin and windows, on amd64 and arm64. A build for any other target stops with an error that names them.

A first VM

package main

import (
	"errors"
	"fmt"
	"time"

	"github.com/liustack/beastjs"
	"github.com/liustack/beastjs/intl"
)

func main() {
	vm, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	defer vm.Close()

	vm.SetMemoryLimit(64 << 20) // 64 MiB for this VM
	if err := vm.SetEvalTimeout(100 * time.Millisecond); err != nil {
		panic(err)
	}
	if err := intl.Register(vm); err != nil {
		panic(err)
	}

	v, err := vm.Eval(`new Date(0).toLocaleString('zh-CN', {timeZone: 'Asia/Shanghai'})`, beastjs.EvalGlobal)
	fmt.Println(v, err) // 1970/1/1 08:00:00 <nil>

	_, err = vm.Eval(`try { for (;;) {} } catch (e) { 'caught' }`, beastjs.EvalGlobal)
	var e *beastjs.Error
	if errors.As(err, &e) && e.Interrupted {
		fmt.Println("timed out, and no catch saw it")
	}
}

A VM is not safe for several goroutines at once: give each goroutine its own, or keep a pool. Intl and Temporal use embedded tz 2026e, so they need no host zoneinfo.

Beyond Eval and Call, the API has Go functions that JavaScript calls as built-ins, control of the GC and the memory of a VM, a clock per VM, Temporal, and parts of React's server renderer written in C. docs/use/api.md lists them, and pkg.go.dev documents each.

What changes for you

  • A limit ends the call. A script that runs past its eval timeout or its memory limit stops there, whatever it catches: no catch, finally, promise handler or Go function of the page gets to run on. *Error says whether it was a timeout or memory. A panic in a Go function you gave the VM comes back to your Go code, and a VM that ran out of memory still closes without a leak.
  • The same page on every machine. A script's local time is UTC in every VM, without setting TZ for the whole process. Intl formats in every locale Chromium has, compared with Chromium 156 on about 75,000 expressions.
  • Strings arrive whole. A Go string from JavaScript is always valid UTF-8, and a Go string with invalid bytes reads in JavaScript as Go itself decodes it.
  • Faster than C, without C. It renders faster than C QuickJS on the same pages, even though it runs as Go assembly (see the table above). Several VMs on several cores do not wait on one lock.

Why you can trust it

  • Every change can be traced. engine/ started from Bellard's QuickJS at one pinned commit, and every change since is written down. LLVM compiles it to Go assembly that is checked in, so building needs no C compiler, and make check-gen fails when the checked-in files are not what the generator makes from engine/ (how to check).
  • The generator refuses what it has not checked. It stops on an instruction, a call or a stack frame it has no rule for, and checks the linked code of a test binary, so a change of the C or of Go itself that breaks the engine shows up as a failed build or test, not as a wrong answer.
  • Every change is written down. docs/internals/changes gives each change with why it is safe, what it costs in memory, what it gains on which machine, and its tests.
  • The tests are upstream's and more. test262 gives 33 known failures, 25 fewer since the fixes taken from upstream QuickJS, and the same ones from run to run. On top come the recorded outputs of the engine, checks in C under AddressSanitizer and UndefinedBehaviorSanitizer, and the Go tests of the API.
  • Someone depends on it. It is kept for tifa, a Go framework that renders React pages in it, and each release is measured on tifa's pages before tifa takes it.

Documentation

Doc Read it when
API You want the Go API beyond Eval and Call
Changes You want to know why each change to the engine is safe, what it costs and what it gains
Performance You want to know how fast each release renders, or what was tried
Benchmarks You want to know how this engine compares with the other pure Go JavaScript engines
Changelog You are upgrading and want to know what changed
Architecture You are about to change the code
Testing You are about to commit, or want to check the engine
Upgrading You are taking a commit of upstream QuickJS, new locale data or a newer Go
Releasing, Commits You are making a release or a commit
Moving from modernc.org/quickjs You are moving a program from modernc.org/quickjs
Upstream You want to know where the code comes from

Where it comes from

The engine is QuickJS by Fabrice Bellard and Charlie Gordon, the release of 2026-06-04. docs/internals/upstream.md has the exact version, how new QuickJS commits are taken in, and what to expect when you move from modernc.org/quickjs.

Thanks to Fabrice Bellard and Charlie Gordon for QuickJS, and to Jan Mercl, Dan Kortschak and the other authors of modernc.org/quickjs and modernc.org/libquickjs. Their work showed that QuickJS can run inside a pure Go program, and it inspired liustack/beastjs.

Community

Issues are welcome any time: open one. Tell us what you run in it, where it is slow, and what should come next. Follow the liustack WeChat official account, and come find me on X: @liustack. What changes in liustack/beastjs and tifa is shared on WeChat and X.

The liustack WeChat official account: AI startup opportunities, indie-dev insights, and hands-on AI tooling, delivered as they happen. Scan the QR code in WeChat, or search for "liustack":

liustack WeChat official account

Contributing

liustack/beastjs does not accept pull requests. One maintainer reviews and owns every line, on purpose, so the engine stays dependable. Two ways that help:

  • Open an issue. A wrong answer, a slow render, a limit that did not hold, an unclear doc. Issues are read and decide what gets built next.
  • Fork it. Your copy is yours to change and publish.

A security problem goes in a private report, as SECURITY.md says. CONTRIBUTING.md has the rest.

License

liustack/beastjs is under the MIT license. Code that came from other projects keeps its own license: the C of QuickJS, the TLSF allocator, musl's libc functions, the Go side and the locale data of Intl and Temporal from go-intl, ICU and Chromium, the URL parser from nlnwa/whatwg-url and a few files of Go. NOTICE.md says which license covers which path, and which notices a program that ships this module has to carry.

Documentation

Overview

Package beastjs is a JavaScript engine written for Go programs that render pages on a server: pure Go, with no cgo and no shared library, so that it builds and cross-compiles as any Go package does. It runs ES2023, modules, async generators, Proxy and BigInt among it. The engine, which started from QuickJS, is written in C and ships as Go assembly that is checked in, so building the package needs no C compiler.

Intl and time zones

The engine has no Intl of its own, and its toLocale* methods look at no locale and no timeZone. The Register function of package github.com/liustack/beastjs/intl adds every Intl constructor to a VM and replaces toLocale* and localeCompare with ones that use them. The one of package github.com/liustack/beastjs/temporal adds Temporal. Without a locale they use en-US, and without a timeZone UTC. The time zone data is built in: the zoneinfo of the host is never read.

Platforms

The package builds for darwin/amd64, darwin/arm64, linux/amd64, linux/arm64, windows/amd64 and windows/arm64. A build for any other target stops with an error that names these.

Bytecode across versions

The bytecode of VM.Compile belongs to the release of QuickJS the engine is. Moving to QuickJS 2026-06-04 changed its format, so bytecode an older version compiled no longer loads, and so did the move to 2025-09-13 before it. Compile again after an upgrade.

Example (Ping)

Two VMs run at once, each on a goroutine of its own, and talk over Go channels. A VM is used by one goroutine at a time, and VMs share nothing.

package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// pipe is a VM with a send and a receive over two Go channels.
func pipe(out chan<- string, in <-chan string) *beastjs.VM {
	m := newVM()
	if err := m.RegisterFunc("send", func(s string) { out <- s }, false); err != nil {
		panic(err)
	}
	if err := m.RegisterFunc("receive", func() string { return <-in }, false); err != nil {
		panic(err)
	}
	return m
}

// Two VMs run at once, each on a goroutine of its own, and talk over Go
// channels. A VM is used by one goroutine at a time, and VMs share nothing.
func main() {
	toServer := make(chan string, 1)
	toClient := make(chan string, 1)

	go func() {
		server := pipe(toClient, toServer)
		defer server.Close()
		if _, err := server.Eval(`send(receive() + ' reply')`, beastjs.EvalGlobal); err != nil {
			panic(err)
		}
	}()

	client := pipe(toServer, toClient)
	defer client.Close()
	fmt.Println(client.Eval(`send('ping'); receive();`, beastjs.EvalGlobal))
}
Output:
ping reply <nil>

Index

Examples

Constants

View Source
const (
	EvalGlobal = 0
	EvalModule = 1
)

The flags of the eval methods: a script, or an ES module. A program may add other flag bits of QuickJS, which the engine is given as they are.

View Source
const (
	DefaultRegExpCache      = 512
	DefaultRegExpCacheBytes = 1 << 20
)

DefaultRegExpCache and DefaultRegExpCacheBytes are how many compiled regexps a new VM keeps at most, and in how many bytes (see VM.SetRegExpCache).

View Source
const DefaultShapeCache = 2048

DefaultShapeCache is how many shapes a new VM keeps (see VM.SetShapeCache).

View Source
const MaxTrackedRejections = 1024

MaxTrackedRejections is the most rejections VM.TrackRejections keeps. A host logs the few a script and its jobs left, and a read holds up to five texts of 8 KiB of each in Go (see VM.UnhandledRejections).

Variables

View Source
var (
	// GetAsyncContext returns the async context of the VM, undefined when it
	// has none.
	GetAsyncContext = NewBuiltin("getAsyncContext", 0, func(a Args) (Value, error) {
		return Value{vm: a.vm, v: a.vm.jsGetAsyncContext()}, nil
	})
	// SetAsyncContext sets the async context of the VM to its first argument
	// when it is an object, and to none for any other value.
	SetAsyncContext = NewBuiltin("setAsyncContext", 1, func(a Args) (Value, error) {
		a.vm.jsSetAsyncContext(a.arg(0))
		return UndefinedValue, nil
	})
)

The async context of a VM is an object javascript sets with SetAsyncContext and reads with GetAsyncContext, which promise jobs keep: a reaction, what then, catch, finally and await register, runs with the context the VM had when it was registered, and the VM gets back the context it had when the reaction ends. That is what an AsyncLocalStorage needs to follow an async function across await, and what V8 keeps for Node as the continuation preserved embedder data. A VM starts with no context, and promises then cost what they did before it.

The context is an object or none. An AsyncLocalStorage keeps the stores of each of its instances in the object, as a Map from the instance to its store, and makes a new object for each run, so the object of a context is not changed once it is set.

View Source
var ErrKilled = errors.New("beastjs: the script did not stop in time and was killed")

ErrKilled matches the error of a call whose script did not stop in time after the eval timeout or VM.Interrupt and was killed, with errors.Is. Such a VM is good only for VM.Close.

View Source
var UndefinedValue = Value{/* contains filtered or unexported fields */}

UndefinedValue is javascript's undefined as a Value. It belongs to no VM, so every VM takes it, it holds no reference, and freeing it does nothing. The zero Value is undefined too.

Functions

func Version

func Version() string

Version returns the release of QuickJS the engine is, such as "2026-06-04".

Types

type Args

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

Args are the arguments of a call of a Builtin, and the VM that called it. What they return is borrowed: a Value is valid for the duration of the call (see Value.Dup to keep one longer).

func (Args) Bool

func (a Args) Bool(i int) (bool, bool)

Bool returns argument i when it is a boolean.

func (Args) Latin1

func (a Args) Latin1(i int) (b []byte, ok bool)

Latin1 returns the characters of argument i, one byte each, when it is a string the engine holds that way: all its characters are below U+0100 and it was not left in pieces by concatenation (a rope). Nothing is copied: the bytes are the engine's, valid until the Builtin returns, and must not be changed. ok is false for any other argument, which Args.UTF16 or Args.String reads. A Builtin that looks at the characters of short strings, and often returns its argument as it is, reads them this way.

func (Args) Len

func (a Args) Len() int

Len returns the number of arguments of the call.

func (Args) Number

func (a Args) Number(i int) (float64, bool)

Number returns argument i when it is a number. It converts nothing: a string or a Number object is not a number.

func (Args) String

func (a Args) String(i int) (s string, ok bool)

String returns argument i when it is a string, as UTF-8 with U+FFFD for each lone surrogate. It converts nothing else. ok is false too when there is no memory for the conversion, and the call then fails with the out of memory error whatever the Builtin returns. A long string ends the same way at Interrupt, the eval timeout or an uncatchable error of the call, as a loop of the engine does: ok is false, and the call fails with that error.

func (Args) StringLen

func (a Args) StringLen(i int) (n int, ok bool)

StringLen returns the length of argument i, in UTF-16 code units as javascript counts it, when it is a string, without reading the string: a rope, a string the engine keeps as the pieces it was joined from, is not joined. A Builtin can so refuse a string too long for it before it converts any of it. It takes the same time for a string of any length and allocates nothing.

func (Args) This

func (a Args) This() Value

This returns the this value of the call.

func (Args) UTF16

func (a Args) UTF16(i int) (u []uint16, ok bool)

UTF16 returns the 16-bit units of argument i when it is a string the engine holds that way, lone surrogates as they are: a string with a character from U+0100 on, not left in pieces by concatenation (a rope). Nothing is copied: the units are the engine's, valid until the Builtin returns, and must not be changed. ok is false for any other argument, which Args.Latin1 or Args.String reads.

func (Args) VM

func (a Args) VM() *VM

VM returns the VM that called the Builtin. The Builtin may evaluate more javascript on it, which runs inside the time left to the call that got there (see VM.SetEvalTimeout).

func (Args) Value

func (a Args) Value(i int) Value

Value returns argument i, undefined when the call has no argument i.

func (Args) WTF8

func (a Args) WTF8(i int) (s string, ok bool)

WTF8 is String, but with each lone surrogate as the three bytes of its code point (0xED, then 0xA0 to 0xBF, then a continuation byte), the form the engine writes it in, which is not UTF-8. A surrogate pair is its one character in UTF-8, as in String. A Builtin that has to tell lone surrogates apart, as a collator orders them, reads its string this way. It ends at the limits of the call as String does.

type Atom

type Atom = uint32

Atom is the number by which a VM knows a property name (see VM.NewAtom). It is a uint32.

type Builtin

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

A Builtin is a Go function that javascript calls as a built-in function: VM.NewBuiltinFunction makes it a function object shaped like the engine's own built-ins, such as Math.max. It has a name and a length and no other property of its own, no prototype property, it cannot be called with new, and its toString shows [native code] rather than source.

Unlike VM.RegisterFunc and VM.RegisterHostFunc, nothing is converted on the way in and no reflection is involved: the Go function reads the arguments it wants from Args, which give a number only for a number and a string only for a string, and returns a Value. That makes a call about as cheap as a call of a javascript function, which suits functions called once per row of a table, as the formatters of package intl are.

A Builtin belongs to no VM. It is made once, typically into a package level variable, and every VM makes its own function objects of it: Args says which VM called. So a process can have at most 32768 Builtins, and they are never released. VMs on several goroutines call the same Builtin at once, so its function has to be safe for concurrent use, and state it keeps for each VM is found by Args.VM.

func NewBuiltin

func NewBuiltin(name string, length int, fn func(Args) (Value, error)) *Builtin

NewBuiltin returns a Builtin calling fn, for function objects named name whose length property is length.

fn owns the Value it returns, which goes to javascript: a Value fn did not make itself, such as an argument, is returned as its Dup. UndefinedValue and the zero Value return undefined. A Value of another VM is neither returned nor freed: the call throws a TypeError.

A non-nil error is thrown instead, and a Value of the VM returned with it is freed. An *Error, found with errors.As, is thrown as a new error of the constructor its Name says when that is one of Error, TypeError, RangeError, SyntaxError, ReferenceError and InternalError, and as an Error for any other name, with its Message. Any other error is thrown as a TypeError with the error's text, as RegisterHostFunc throws it. The engine cuts the message of a TypeError, RangeError, SyntaxError, ReferenceError or InternalError to 255 bytes. The stack of each starts at the Builtin, as that of an error a built-in of the engine throws does.

A panic in fn goes on in the Go code that called javascript, as one in a function of RegisterHostFunc does.

NewBuiltin panics when name has a NUL byte, when length is not in 0 to 255, when fn is nil, and when the process already has 32768 Builtins: all mistakes of the code making them, which runs once.

type Error

type Error struct {

	// Name and Message are the name and message properties of the exception,
	// empty when it has none, as for throw 42. Stack is its stack property.
	Name    string
	Message string
	Stack   string
	// LineNumber, ColumnNumber and FileName are set for a syntax error only.
	// The error of a script that ran has its place in Stack alone.
	LineNumber   int
	ColumnNumber int
	FileName     string

	// Uncatchable reports that the call ended with an exception that no
	// catch or finally of the script got to see: the VM ran out of memory
	// (OutOfMemory is set too), Interrupt or the eval timeout stopped the
	// script (Interrupted is set too), or a Go function that javascript
	// called panicked (neither is set). Nothing a script throws is
	// uncatchable, whatever its name and message.
	Uncatchable bool
	OutOfMemory bool
	Interrupted bool
	// contains filtered or unexported fields
}

Error is a javascript exception that ended a call, read into Go. Get it from the error of a call with errors.As:

if _, err := m.Eval(js, beastjs.EvalGlobal); err != nil {
	var e *beastjs.Error
	if errors.As(err, &e) && e.Interrupted {
		// the eval timeout or Interrupt stopped the script
	}
}

The text of Error() is what the engine has always given for the exception, such as "TypeError: x is not a function", or the string of a value that is not an error, such as "42" for throw 42.

func ErrorFromValue

func ErrorFromValue(v Value) *Error

ErrorFromValue reads the error value v, such as an exception a script caught, as the error of a call is read. It borrows v. Reading it runs javascript, a getter of its message or a toString of the page, inside the eval timeout (see VM.SetEvalTimeout). A field it cannot read stays empty. It panics when v belongs to no VM, and on a VM a kill left good only for Close.

func (*Error) Error

func (e *Error) Error() string

Error returns the text of the exception. For an Error made in Go, which was not read from javascript, it is what Error.prototype.toString makes of Name and Message: Name, "Error" when Name is empty, followed by ": " and Message unless Message is empty.

func (*Error) Is

func (e *Error) Is(target error) bool

Is reports whether target is ErrKilled and e is the error of a call whose script was killed.

type HostFunc

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

HostFunc is a Go function for VM.RegisterHostFunc: it gets the arguments of the call as Go values, and returns the one value of the call, or an error to throw.

type MemoryUsage

type MemoryUsage struct {
	// MallocSize is what the VM's allocations take, which [VM.MemorySize]
	// returns too, and MallocCount how many there are. MallocLimit is the
	// limit of [VM.SetMemoryLimit], -1 for none.
	MallocSize, MallocLimit, MallocCount int64
	// MemoryUsedSize and MemoryUsedCount are what the objects below take,
	// counted one by one.
	MemoryUsedSize, MemoryUsedCount int64

	AtomCount, AtomSize int64
	StrCount, StrSize   int64
	ObjCount, ObjSize   int64
	PropCount, PropSize int64
	ShapeCount          int64
	ShapeSize           int64
	// The functions of javascript, their bytecode and their line tables.
	JSFuncCount, JSFuncSize, JSFuncCodeSize int64
	JSFuncPC2LineCount, JSFuncPC2LineSize   int64
	// Functions of the engine and of Go.
	CFuncCount int64
	// ArrayCount counts the arrays, FastArrayCount those that keep their
	// elements in a plain list, and FastArrayElements those elements.
	ArrayCount, FastArrayCount, FastArrayElements int64
	// ArrayBuffers and typed arrays.
	BinaryObjectCount, BinaryObjectSize int64

	// What the VM took from the system, its limit (0 for none), in how many
	// chunks, and the bytes [VM.ReleaseMemory] offered back so far.
	Footprint, FootprintLimit, Chunks, ReleaseCandidate int64

	// The register code the engine made for the functions that ran, at the
	// first call of each, kept as long as the function: how many functions
	// and its bytes. JSFuncCodeSize is the bytecode alone. MemoryUsedSize
	// counts both.
	RegisterCodeCount, RegisterCodeSize int64
	// FreeSize is [VM.MemoryFree]: the bytes of MallocSize no block in use
	// holds.
	FreeSize int64
}

MemoryUsage is what a VM holds, as its engine counts it (see VM.MemoryUsage). Sizes are in bytes.

type Object

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

Object is the Go value of a javascript object, array or function: the JSON that JSON.stringify made of it when it was converted. It is a copy of what the object held then, not the object, so two Objects of one object are not the same and comparing them tells nothing. A value JSON.stringify gives undefined for, such as a function, has the JSON text undefined, which is not JSON.

The zero Object has no JSON at all: passed to javascript, as an argument or a result, it fails to parse.

func (*Object) Into

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

Into decodes the JSON of o into v, as encoding/json.Unmarshal does.

Example
package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

// object is the result of an object literal, as the examples of Object use it.
func object() *beastjs.Object {
	m := newVM()
	defer m.Close()
	v, err := m.Eval(`({a: 42 + 314, b: 'foo'})`, beastjs.EvalGlobal)
	if err != nil {
		panic(err)
	}
	return v.(*beastjs.Object)
}

func main() {
	var s struct {
		A int    `json:"a"`
		B string `json:"b"`
	}
	if err := object().Into(&s); err != nil {
		panic(err)
	}
	fmt.Printf("%#v\n", s)
}
Output:
struct { A int "json:\"a\""; B string "json:\"b\"" }{A:356, B:"foo"}

func (*Object) MarshalJSON

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

MarshalJSON returns the JSON of o. Its error is always nil.

Example
package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

// object is the result of an object literal, as the examples of Object use it.
func object() *beastjs.Object {
	m := newVM()
	defer m.Close()
	v, err := m.Eval(`({a: 42 + 314, b: 'foo'})`, beastjs.EvalGlobal)
	if err != nil {
		panic(err)
	}
	return v.(*beastjs.Object)
}

func main() {
	b, err := object().MarshalJSON()
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))
}
Output:
{"a":356,"b":"foo"}

func (*Object) String

func (o *Object) String() string

String returns the JSON of o.

Example
package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

// object is the result of an object literal, as the examples of Object use it.
func object() *beastjs.Object {
	m := newVM()
	defer m.Close()
	v, err := m.Eval(`({a: 42 + 314, b: 'foo'})`, beastjs.EvalGlobal)
	if err != nil {
		panic(err)
	}
	return v.(*beastjs.Object)
}

func main() {
	fmt.Printf("%s\n", object())
}
Output:
{"a":356,"b":"foo"}

type PromiseCapability

type PromiseCapability struct {
	Promise Value
	Resolve Value
	Reject  Value
}

PromiseCapability is a promise and the two functions that settle it. Each of the three is a reference, which Free gives up.

func (*PromiseCapability) Dup

Dup returns a new PromiseCapability with a Dup of each value of pc, which is freed on its own.

func (*PromiseCapability) Free

func (pc *PromiseCapability) Free()

Free frees the three values of pc.

type SharedBytecode

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

SharedBytecode is bytecode of VM.Compile that several VMs load with VM.EvalSharedBytecode from one copy. The source text of each function, which its toString returns, and the table that maps its bytecode to lines, which error stacks read, stay in that copy: a VM that loads it does not copy them into its own memory, as VM.EvalBytecode does. So they count once for the process, outside the memory of every VM: VM.SetMemoryLimit and VM.MemorySize do not count them. Everything else a VM reads from the bytecode, the code of its functions among it, is still its own.

The copy lives outside Go's heap. It stays while the SharedBytecode is open or a VM that loaded it is: Close gives up the hold of the SharedBytecode, and each VM gives up its own when it is closed. The last of them frees it.

A SharedBytecode is safe for use by several goroutines at once, and so several VMs on several goroutines can load it at the same time.

func NewSharedBytecode

func NewSharedBytecode(bytecode []byte) (*SharedBytecode, error)

NewSharedBytecode copies bytecode, which VM.Compile returned, once, for VMs to load with VM.EvalSharedBytecode. As with VM.EvalBytecode, the bytecode is not checked, so it must not come from an untrusted source.

func (*SharedBytecode) Close

func (b *SharedBytecode) Close() error

Close gives up the hold of b on its bytes: they are freed now if no VM that loaded them is open, or else when the last of them is closed. Loading b after Close fails. Closing b again does nothing.

func (*SharedBytecode) Len

func (b *SharedBytecode) Len() int

Len returns the size of the bytecode in bytes, the memory it takes once for the process.

type Strip

type Strip int

Strip says what the functions a VM compiles leave out (see VM.SetStrip).

const (
	// StripSource leaves out the source text of each function, so that its
	// toString shows [native code].
	StripSource Strip = 1
	// StripDebug leaves out the file names and the line and column numbers,
	// so that a stack frame shows only the name of its function, and the
	// source text too.
	StripDebug Strip = 2
)

type Undefined

type Undefined struct{}

Undefined is the Go value of javascript's undefined. As an argument it is undefined again.

func (Undefined) String

func (u Undefined) String() string

String returns "undefined".

type Unsupported

type Unsupported struct{}

Unsupported is the Go value of a javascript value that has no Go form, such as a symbol.

func (Unsupported) String

func (u Unsupported) String() string

String returns "unsupported Javascript type".

type VM

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

VM is a javascript realm, with its global object, and the runtime that runs it. Each VM has its own memory and its own globals.

A VM is not safe for use by several goroutines at once: one goroutine uses it at a time. VM.Interrupt is the exception, and may be called from any goroutine at any time.

func NewVM

func NewVM() (*VM, error)

NewVM returns a new VM.

func (*VM) Call

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

Call evaluates function, source that gives a function, such as "parseInt" or "obj.method", calls it with args and returns its value as VM.Eval does. this is the global object, also for "obj.method". function is run as a script: "var a = 42; a" runs, and the call fails as 42 is not a function. What function throws is the error, such as a ReferenceError for a name that is not defined.

Each argument becomes a javascript value by its dynamic Go type:

Go                                         javascript
--                                         ----------
nil                                        null
Value                                      the value, borrowed
Undefined                                  undefined
int8, uint8, int16, uint16, int32          a number
int, int64, uint, uint32, uint64           a number, a float when
                                           outside int32 (past 2^53
                                           it loses precision)
float64                                    a number
bool                                       a boolean
string                                     a string, U+FFFD for each
                                           byte of invalid UTF-8
*big.Int                                   a BigInt, null for nil
anything else                              the JSON of encoding/json

A type of its own, such as time.Duration, and float32, []byte (base64), structs, maps and *Object go through JSON. So does an error, which most often has no exported field and becomes {}: pass err.Error() instead. A Value of another VM is an error.

Example (Function)
package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	m := newVM()
	defer m.Close()
	fmt.Println(m.Call("parseInt", "1234"))
}
Output:
1234 <nil>
Example (Method)
package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	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 VM.Call that returns the value as a Value, which the caller frees.

func (*VM) Close

func (m *VM) Close() (err error)

Close frees m and all it holds, then runs the functions of VM.OnClose.

Close of a closed VM does nothing and returns nil, so a deferred Close after an explicit one is fine. When the OS refuses to take some memory back, Close returns an error, and a Close after it tries what is left again: the error only says that some memory was not given back when Close returned.

A step of Close that panics does not keep the others from running: the other functions of OnClose run too. Close then panics with the first panic. Close from a function of OnClose returns nil. Close during a call into m, such as from a Go function that javascript called, returns an error and changes nothing: a Close after the call closes m.

func (*VM) Compile

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

Compile compiles javascript, a script or with EvalModule a module, to bytecode, which VM.EvalBytecode or VM.EvalBytecodeValue runs. The format of the bytecode belongs to the release of QuickJS the engine is. Compiling is inside the eval timeout.

func (*VM) Eval

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

Eval evaluates javascript, a script or, with EvalModule in flags, a module, and returns its value as a Go value:

javascript              Go
----------              --
null                    nil
undefined               Undefined{}
a boolean               bool
a number that is int32  int
any other number        float64
a string                string, a lone surrogate as U+FFFD
a BigInt                *big.Int
an object, an array     *Object, its JSON
a symbol and the rest   Unsupported{}

A number the engine holds as a float, such as the result of some arithmetic, is a float64 even when its value is whole. A module's value is the promise of its evaluation, which Eval does not wait for. An exception is returned as an *Error.

flags are given to the engine as they are, so other flag bits of QuickJS work too.

Example (Exception)
package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	m := newVM()
	defer m.Close()
	fmt.Println(m.Eval(`throw new Error('failed')`, beastjs.EvalGlobal))
}
Output:
<nil> Error: failed
Example (Expression)
package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	m := newVM()
	defer m.Close()
	fmt.Println(m.Eval(`1 + 2`, beastjs.EvalGlobal))
}
Output:
3 <nil>
Example (Object)
package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	m := newVM()
	defer m.Close()
	fmt.Println(m.Eval(`({a: 42 + 314, b: 'foo'})`, beastjs.EvalGlobal))
}
Output:
{"a":356,"b":"foo"} <nil>

func (*VM) EvalBytecode

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

EvalBytecode loads bytecode that VM.Compile made, runs it and returns its value as VM.Eval does. this is the global object. A module's top-level await is waited for. Loading, running and converting the value are one call, inside the eval timeout.

The format of bytecode belongs to the release of QuickJS the engine is, and nothing in it is checked: never load bytecode from a source you do not trust.

func (*VM) EvalBytecodeValue

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

EvalBytecodeValue is VM.EvalBytecode that returns the value as a Value, which the caller frees.

func (*VM) EvalFile

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

EvalFile is VM.EvalValue with name as the file of the script: its stack frames and its syntax errors show name where those of the other Eval methods show <eval>, and a module has name as its module name. No file is read. name is cleaned first: to valid UTF-8 of one line, with no control character, U+2028 or U+2029 (each becomes U+FFFD), of at most 1,024 bytes (cut where a character starts). An empty name is <eval>.

The name of a module is what tells it apart, so a module name the cleaning would change is an error, and nothing runs. Two modules of the same name both run, and import.meta and an import of that name find the first.

func (*VM) EvalSharedBytecode

func (m *VM) EvalSharedBytecode(b *SharedBytecode) (r any, err error)

EvalSharedBytecode is like VM.EvalBytecode, but loads b without copying the source text and line tables of its functions into m (see SharedBytecode). m holds b until it is closed.

func (*VM) EvalSharedBytecodeValue

func (m *VM) EvalSharedBytecodeValue(b *SharedBytecode) (r Value, err error)

EvalSharedBytecodeValue is like VM.EvalBytecodeValue, but loads b as VM.EvalSharedBytecode does.

func (*VM) EvalThis

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

EvalThis is VM.Eval with obj as this. It takes obj and frees it when it returns, whatever happens. A Value of another VM is an error, and is neither used nor freed.

func (*VM) EvalThisValue

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

EvalThisValue is VM.EvalThis that returns the value as a Value, which the caller frees. It takes obj as EvalThis does.

func (*VM) EvalValue

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

EvalValue is VM.Eval that returns the value as a Value, which the caller frees.

func (*VM) ExecutePendingJobs

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

ExecutePendingJobs runs the jobs queued in m, the reactions of promises and what follows an await, until the queue is empty, and returns how many it ran. Nothing runs them on its own: a program that uses promises calls it, such as at the end of each turn of its event loop.

A job that throws does not stop the others, and the first such exception is the error. A throw in a then callback is no such job: it rejects the promise then returned. An uncatchable error, such as the eval timeout, ends the call at once, and the jobs after it stay queued. A queue that keeps feeding itself is cut after 1,048,576 jobs, with an error.

func (*VM) GCThreshold

func (m *VM) GCThreshold() uintptr

GCThreshold returns the threshold of the next collection the engine runs by itself. It counts the memory a collection can free: MemorySize without the stack of the register loop. After each full collection, of the engine or of VM.RunGC, the threshold is 1.5 times what that memory is then, unless it is ^uintptr(0): so a threshold other than the one SetGCThreshold set says a full collection ran since.

As every method of m, it is not for use by other goroutines at the same time. After Close it panics. After a kill it still answers.

func (*VM) GetProperty

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

GetProperty returns the property prop of this as a Go value, as VM.Eval converts it. Reading it and converting it run inside one eval timeout.

func (*VM) GetPropertyValue

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

GetPropertyValue returns the property prop of this, which the caller frees. A getter runs, inside the eval timeout. A Value of another VM is an error.

func (*VM) GlobalObject

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

GlobalObject returns the global object of m, which the caller frees.

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 outermost call into javascript returns, so javascript a host function evaluates on m meanwhile does not clear it. Interrupt is also safe while m closes and after Close, where it does nothing, so a watchdog need not know whether the script it guards has finished. A script that keeps the engine working past the grace of the host after it is killed (see ErrKilled): the call returns an interrupted error, and the VM is good only for Close.

Example

Another goroutine stops a script that would run for ever.

package main

import (
	"fmt"
	"time"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	m := newVM()
	defer m.Close()
	start := time.Now()
	go func() {
		time.Sleep(time.Second)
		m.Interrupt()
	}()
	v, err := m.Eval(`for (;;) {}`, beastjs.EvalGlobal)
	fmt.Println(v, err, time.Since(start).Truncate(200*time.Millisecond))
}
Output:
<nil> InternalError: interrupted 1s

func (*VM) MemoryFree

func (m *VM) MemoryFree() uintptr

MemoryFree returns the bytes of MemorySize that no block in use holds: holes in the arenas, the free end of an arena, and the free blocks the caches keep. After VM.RunGC, MemorySize minus MemoryFree is what the objects javascript reaches and the structures of the runtime take, a figure that stays put while the same objects are kept: it is the one to judge when to replace a VM. It walks the arenas, some tens of microseconds for thousands of them, and may be read at any time, from a Go function javascript called and after a kill too.

func (*VM) MemorySize

func (m *VM) MemorySize() uintptr

MemorySize returns the memory m takes, in bytes, as VM.SetMemoryLimit counts it. VM.MemoryFree says how much of it no block in use holds.

func (*VM) MemoryUsage

func (m *VM) MemoryUsage() MemoryUsage

MemoryUsage returns what m holds, in more detail than VM.MemorySize. It walks every object, so it is for measurements, not for a hot path. Run VM.RunGC first to leave out what javascript can no longer reach.

As with SetGCThreshold, no other goroutine may use m meanwhile (see VM), and a call after Close panics.

func (*VM) NewArray

func (m *VM) NewArray(vals ...Value) (Value, error)

NewArray returns a new array of vals, made as an array literal makes one: its elements are own properties, which no setter a page put on Array.prototype sees. It borrows vals, as VM.SetPropertyValue and Value.Call do: the caller still owns them. The zero Value is undefined. A Value of another VM, a number too, is an error, as it is for a Builtin to return one. In a Builtin, a long array ends at Interrupt, the eval timeout or an uncatchable error of the call, with that error, as a loop of the engine does.

func (*VM) NewAtom

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

NewAtom returns the atom of the property name s, a number the VM knows the name by, the same for the same name. Invalid UTF-8 in s is U+FFFD a byte. An atom is never freed.

func (*VM) NewBuiltinFunction

func (m *VM) NewBuiltinFunction(b *Builtin) (Value, error)

NewBuiltinFunction returns a new function object of b. The caller owns it: it passes it to javascript, for example as an argument of Value.Call or with VM.SetPropertyValue, and then frees it.

func (*VM) NewFloat64

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

NewFloat64 returns the number n.

func (*VM) NewInt

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

NewInt returns the number n. Outside int32 it is a float, which loses precision past 2^53.

func (*VM) NewMurmur2Function

func (m *VM) NewMurmur2Function() (Value, error)

NewMurmur2Function returns a function of javascript, written in C inside the engine, that hashes a string as murmur2 of @emotion/hash 0.9 does, which emotion takes of every style it serializes: the low byte of each UTF-16 code unit, a lone surrogate as the unit it is, and the hash in base 36. It answers undefined for anything but a string. A rope, a string the engine keeps as the pieces it was joined from, is joined first, under the memory limit, and an interrupt or the eval timeout stops it on a long string. emotion's own function calls String.prototype.charCodeAt and Number.prototype.toString: a host that calls this one in its place checks that a page has not replaced them (package tifa does). The function is named murmur2 and its length is 1.

func (*VM) NewObjectValue

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

NewObjectValue returns a new empty object, which the caller frees.

func (*VM) NewPromiseCapability

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

NewPromiseCapability returns a new pending promise with its resolve and reject, without evaluating any source, for Go to settle later. It runs no javascript.

A Go function of VM.RegisterFunc that is to give javascript a promise returns pc.Promise, which hands its reference to the call, and keeps pc.Resolve and pc.Reject, which it frees once it has called one:

var waiting *beastjs.PromiseCapability
m.RegisterFunc("later", func() beastjs.Value {
	pc, err := m.NewPromiseCapability()
	if err != nil {
		return beastjs.UndefinedValue
	}
	waiting = pc
	return pc.Promise // the call takes this reference
}, false)
m.Eval(`later().then(v => globalThis.got = v)`, beastjs.EvalGlobal)
// Later, on the goroutine that uses m:
waiting.Resolve.Call(beastjs.UndefinedValue, "done")
waiting.Resolve.Free()
waiting.Reject.Free()
m.ExecutePendingJobs()

Only a function that returns pc.Promise.Dup(), and so keeps the promise, frees pc.Promise too.

func (*VM) NewString

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

NewString returns the string s, with U+FFFD for each byte of invalid UTF-8, which the caller frees. In a Go function that javascript called, a long string stops at Interrupt, the eval timeout or an uncatchable error of the call, and NewString returns that error, as a loop of the engine stops.

func (*VM) NewStringLatin1

func (m *VM) NewStringLatin1(b []byte) (Value, error)

NewStringLatin1 returns a new string of the characters b, one byte each: a byte is the character of its value, U+0000 to U+00FF. Unlike VM.NewString it decodes no UTF-8, so a Builtin that read its argument with Args.Latin1 returns what it made of it this way, as one copy. It ends at the limits of the call as NewString does.

func (*VM) NewStringUTF16

func (m *VM) NewStringUTF16(u []uint16) (Value, error)

NewStringUTF16 returns a new string of the 16-bit units u, lone surrogates as they are. A Builtin that read its argument with Args.UTF16 returns what it made of it this way, as one copy. It ends at the limits of the call as NewString does.

func (*VM) Now

func (m *VM) Now() time.Time

Now reads the VM's wall clock with time.Time precision. Date and Intl use whole milliseconds, while Temporal preserves nanoseconds. Like the VM, Now is not safe for concurrent use.

func (*VM) OnClose

func (m *VM) OnClose(f func())

OnClose makes Close run f once m is freed, so f must not use m. Each function runs once, in the order given. Nothing else runs them: not the GC, and not for a VM that is never closed. A package that keeps something for each VM in a table of its own drops it here, so that the table does not keep the VM alive.

func (*VM) RegisterCopyProps

func (m *VM) RegisterCopyProps(name string) error

RegisterCopyProps defines a function named name on the global object that does the work of the loop with which React's createElement and cloneElement copy the keys of their config into the props of an element:

for (propName in config)
  hasOwnProperty.call(config, propName) && "key" !== propName &&
    "__self" !== propName && "__source" !== propName &&
    (props[propName] = config[propName])

(and for cloneElement also "ref" when config.ref is undefined). It is written in C inside the engine and copies all the keys in one call, a few times faster than the loop.

The function takes four arguments: config, props, React's hasOwnProperty (the Object.prototype.hasOwnProperty it took when it loaded) and whether the call is cloneElement's. It answers true when it copied, and false when it changed nothing and the script has to run its loop. It copies only where its result and the loop's cannot differ in anything a script can see: config an ordinary object whose prototype is Object.prototype, with no more than 32 own keys, none of them an array index, __proto__ or stack, and every key the loop reads a plain data property (a getter, a setter, a proxy, a symbol key and a key that is not enumerable never change the result, or send it to the loop); props an ordinary object that can be extended, with the same prototype and only plain writable data properties; Object.prototype with no setter and no read-only property but __proto__; and hasOwnProperty.call the built-in function calling the built-in. It throws only when the engine has no memory, with the error that adding the keys would have thrown.

A page that replaces any of these after React has loaded, or gives Object.prototype a setter or a read-only property, only sends the next calls to the loop. The function is not on the global object unless a host calls this. The property is writable, configurable and not enumerable, and it replaces a configurable property of that name, as RegisterFunc does. A property that is not configurable (undefined, NaN, Infinity, a var or function of a script) is kept and RegisterCopyProps returns an error, as it does when the global object is not extensible. The name is the one javascript sees: invalid UTF-8 is replaced as Go decodes it (see Eval), and a NUL byte in it is an error. Each call makes a function of its own, and calling it again with the same name makes another one that takes the place of the first.

func (*VM) RegisterEndTag

func (m *VM) RegisterEndTag(name string) error

RegisterEndTag defines a function named name on the global object that gives the end tag of an element the way React DOM's server renderer does in endChunkForTag: "</" + tag + ">" for its argument tag. It is written in C inside the engine and keeps the end tag of each string it was given, so that the same string gives the same end tag again without making it. An argument that is not a string becomes one as in "</" + tag, and the function throws what that throws. The rules of the name and of the property are those of RegisterStartTag.

func (*VM) RegisterEscapeText

func (m *VM) RegisterEscapeText(name string) error

RegisterEscapeText defines a function named name on the global object that escapes text for HTML the way React DOM's string renderer does (escapeTextForBrowser in react-dom-server-legacy.browser.production.js). It is written in C inside the engine, so a call costs about what a call of an empty JavaScript function costs, and it does the work of the whole function of React: a script that calls it in place of the function of React gets the same text.

The argument becomes a string as in "" + text: a string stays as it is, numbers, booleans and bigints become their text, an object goes through valueOf and toString (or Symbol.toPrimitive) with the hint "default", and a symbol or a toString that throws makes the call throw the same error. Then each of & < > " and ' becomes &amp; &lt; &gt; &quot; or &#x27;, one UTF-16 code unit at a time, so a lone surrogate goes through as it is. The string it was given comes back when it has none of the five. Called with no argument it answers "undefined". A string of more than 1,073,741,823 units once escaped throws a RangeError, as the function of React does when it builds that string. An interrupt or the eval timeout stops it on a long string.

The function is not on the global object unless a host calls this. The property is writable, configurable and not enumerable, and it replaces a configurable property of that name, as RegisterFunc does. A property that is not configurable (undefined, NaN, Infinity, a var or function of a script) is kept and RegisterEscapeText returns an error, as it does when the global object is not extensible. The name is the one javascript sees: invalid UTF-8 is replaced as Go decodes it (see Eval), and a NUL byte in it is an error. Each call makes a function of its own, and calling it again with the same name makes another one that takes the place of the first.

func (*VM) RegisterFunc

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

RegisterFunc makes the Go function f a function of the global object named name, which javascript calls.

f is any Go function: a function, a closure, a method expression or a method value, with any number of parameters, variadic or not. With wantThis, its first parameter gets the this of the call, which may be null or undefined: it is not replaced by the global object.

Each argument is converted to the type of its parameter, as VM.Eval converts a value: a number that is int32 is an int, other numbers float64, an object an *Object, null a nil of a parameter that takes one. A parameter of type Value gets the argument itself, valid only during the call: to keep it, such as a resolve to call later, keep a Dup. An argument that does not convert to its parameter, or a call with too few or too many arguments, throws a TypeError.

The result becomes a javascript value; several results become an array of them. A nil error is null, and a non-nil one the string of its Error: RegisterFunc throws nothing for an error. A result that fails to convert throws a TypeError, as do a Value of another VM in a result and a result that contains itself, such as a slice that is its own element. How the results convert:

  • nil, a nil pointer, interface or map is null, a nil slice []. UndefinedValue and the zero Value are undefined, and so is Undefined.
  • A bool, an integer, a float and a string become their javascript value, an integer outside int32 a float. *big.Int is a BigInt. *Object is its JSON parsed.
  • A slice is an array. A map with string or integer keys is an object of own data properties, in the order of the keys as strings.
  • A struct converts through encoding/json, and a value whose type has an Error method is the string of Error. A String method changes nothing.
  • A Value of the VM in a result is handed to the call: the result, an element of a slice or an array, a key or a value of a map and the target of a pointer each hand over one reference, which the call frees when it is done, whether the conversion succeeds, fails or panics. A copy of a Value is no new reference, only a Dup is, and a slice, map or pointer the results reach twice is still one. So a Go function that returns one of its Value arguments returns its Dup. The Values inside a struct or a value with an Error method stay the caller's.

The results are looked at, for the Values they hold, a cycle and a Value of another VM, before the conversion runs any code of the program, such as an Error or a MarshalJSON method, which then cannot change which references are taken and freed. Results whose types can hold no Value are not looked at first: they are read as they convert.

A long string argument or result, and a result of many elements or properties, stops converting at Interrupt, the eval timeout or an uncatchable error of the call, which then ends with that error.

The function becomes the property name of the global object, writable and configurable, not enumerable. It replaces a configurable property, one a script set or a built-in such as Array. A property that is not configurable, such as undefined, NaN, Infinity or a var or function of a script, is kept, and RegisterFunc returns an error, as it does when the global object is not extensible. The length of the function is the number of parameters of f less one, and at least 0.

name is the name javascript sees: invalid UTF-8 in it is U+FFFD a byte, so two Go strings can name one function. A NUL byte is an error. name should be an identifier: it is not checked yet, and may be later. A name is registered once per VM, even after a script deleted or replaced its function. A VM holds about a billion Go functions at a time at most.

For a host object prefer VM.RegisterHostFunc. A function called often, or one that is to look like a built-in, is better as a Builtin, which converts nothing and uses no reflection, and costs far less.

Example (Error)

A Go error a function returns is a string to javascript, not a throw.

package main

import (
	"errors"
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	m := newVM()
	defer m.Close()
	if err := m.RegisterFunc("check", func(a int) error {
		if a < 0 {
			return errors.New("negative")
		}
		return nil
	}, false); err != nil {
		panic(err)
	}
	fmt.Println(m.Eval(`check(-1)`, beastjs.EvalGlobal))
	fmt.Println(m.Eval(`check(1)`, beastjs.EvalGlobal))
}
Output:
negative <nil>
<nil> <nil>
Example (MultipleReturn)

Several results are an array.

package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	m := newVM()
	defer m.Close()
	if err := m.RegisterFunc("scale", func(a, b int) (int, int) { return 10 * a, 100 * b }, false); err != nil {
		panic(err)
	}
	fmt.Println(m.Eval(`scale(2, 3)`, beastjs.EvalGlobal))
}
Output:
[20,300] <nil>
Example (SingleReturn)
package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	m := newVM()
	defer m.Close()
	if err := m.RegisterFunc("madd", func(a, b, c int) int { return a + b*c }, false); err != nil {
		panic(err)
	}
	fmt.Println(m.Eval(`madd(2, 3, 5)`, beastjs.EvalGlobal))
}
Output:
17 <nil>
Example (ThisNonNull)

Called as a method, it gets the object, here as its JSON.

package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	m := newVM()
	defer m.Close()
	if err := m.RegisterFunc("gofunc", func(this any) any { return this }, true); err != nil {
		panic(err)
	}
	fmt.Println(m.Eval(`({foo: 314, gofunc}).gofunc()`, beastjs.EvalGlobal))
}
Output:
{"foo":314} <nil>
Example (ThisNonNull2)
package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	m := newVM()
	defer m.Close()
	if err := m.RegisterFunc("gofunc", func(this any, a int) (any, int) { return this, 10 * a }, true); err != nil {
		panic(err)
	}
	fmt.Println(m.Eval(`({foo: 314, gofunc}).gofunc(42)`, beastjs.EvalGlobal))
}
Output:
[{"foo":314},420] <nil>
Example (ThisNull)

Called on its own, a function that wants this gets undefined.

package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	m := newVM()
	defer m.Close()
	if err := m.RegisterFunc("gofunc", func(this any) any { return this }, true); err != nil {
		panic(err)
	}
	fmt.Println(m.Eval(`gofunc()`, beastjs.EvalGlobal))
}
Output:
undefined <nil>
Example (ThisNull2)

Undefined in an array is null in its JSON.

package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	m := newVM()
	defer m.Close()
	if err := m.RegisterFunc("gofunc", func(this any, a int) (any, int) { return this, 10 * a }, true); err != nil {
		panic(err)
	}
	fmt.Println(m.Eval(`gofunc(42)`, beastjs.EvalGlobal))
}
Output:
[null,420] <nil>
Example (Void)

A function with no result returns undefined.

package main

import (
	"fmt"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	m := newVM()
	defer m.Close()
	if err := m.RegisterFunc("show", func(a, b, c int) { fmt.Println(a + b*c) }, false); err != nil {
		panic(err)
	}
	fmt.Println(m.Eval(`show(2, 3, 5)`, beastjs.EvalGlobal))
}
Output:
17
undefined <nil>

func (*VM) RegisterHostFunc

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

RegisterHostFunc makes fn a function of the global object named name, which javascript calls. Each argument of the call is converted to a Go value, as VM.Eval converts a value, into the slice fn gets. The value fn returns is converted back, by the rules of the results of VM.RegisterFunc, Values and their references too. A non-nil error is thrown as a TypeError with the text of the error, and the value is not converted: the references it holds are freed before the Error method of the error runs. Unlike RegisterFunc, which makes the array [value, error] of the two, fn returns one value or throws. name is as for RegisterFunc.

Each call converts every argument by reflection: a function called often is better as a Builtin.

func (*VM) RegisterStartTag

func (m *VM) RegisterStartTag(name string) error

RegisterStartTag defines a function named name on the global object that writes the start tag of an element the way React DOM's server renderer does in pushStartGenericElement (react-dom-server-legacy.browser.production.js of react-dom 19.3), with the functions it calls: startChunkForTag, pushAttribute, pushStyleAttribute, escapeTextForBrowser and the others. It is written in C inside the engine and writes the whole tag in one call, a few times faster than those functions.

The function takes seven arguments: target, props, type and formatContext, those of pushStartGenericElement, then React's hasOwnProperty (the Object.prototype.hasOwnProperty it took when it loaded) and decline, an object only the caller holds. It pushes onto target one string, the start tag with its attributes and, when props.children is a string, the escaped text after it, and returns what pushStartGenericElement returns: null when children is a string, else props.children, or null when there is none. React pushes the same text in several strings. A seventh argument, the mode, makes it stand in for another function of React: 1 for pushSelfClosing, which React DOM writes img (after its image preload) and the void elements such as br and hr with: the attributes, "/>" and no text, null returned, and a decline when children is set, where React throws. 2 is the case "input" of pushStartInstance: the same, with name, formAction, formEncType, formMethod, formTarget, checked and value (or defaultChecked and defaultValue) written after the other props, as React writes them, and a decline when formAction is a function. 3 is the branch of the case "style" of pushStartInstance that writes the element where it is, as emotion's style elements are written: the attributes, ">", the __html of dangerouslySetInnerHTML as it is and the end tag, null returned, and a decline for children and for an __html that is not a string, null or undefined. undefined and 0 are pushStartGenericElement, and any other mode declines, so that a script that asks for a mode the engine does not have gets React's function. When it cannot be sure to write what React writes it returns decline, having changed nothing, and the script runs React's function. That is the case for an unusual target (not a plain array, an index property ever put on Array.prototype or Object.prototype, where push would set it, or Array.prototype.push replaced), a tag React refuses, a formatContext whose viewTransition is not null, props or a style that are not plain objects of Object.prototype with at most 32 keys, a getter, an array index key, dangerouslySetInnerHTML, the rare attributes xlinkHref, capture, download, cols, rows, size, span, rowSpan and start, a value that React would turn into a string by calling its toString (an object) or a bigint, a javascript: URL, a name of the default branch that is not ASCII or is 64 characters or more, a style name that is not ASCII and does not start with --, a tag that would be too long, and hasOwnProperty.call that is not the built-in function calling the built-in. The built-ins are found by their C function, so one replaced before registering is not taken for them, and registering runs no script. It assumes that the built-in methods of String, RegExp, Map and Set that React's functions call are still those of the engine. It throws only when the engine has no memory, or when an interrupt or the eval timeout stops it on a long string, and target is then unchanged.

The function is not on the global object unless a host calls this. The property is writable, configurable and not enumerable, and it replaces a configurable property of that name, as RegisterFunc does. A property that is not configurable (undefined, NaN, Infinity, a var or function of a script) is kept and RegisterStartTag returns an error, as it does when the global object is not extensible. The name is the one javascript sees: invalid UTF-8 is replaced as Go decodes it (see Eval), and a NUL byte in it is an error. Each call makes a function of its own, and calling it again with the same name makes another one that takes the place of the first.

func (*VM) ReleaseMemory

func (m *VM) ReleaseMemory(keep uintptr) (uintptr, error)

ReleaseMemory gives memory that m keeps free back to the system, all but keep bytes of it, and returns how many bytes it gave back. The objects of m stay as they are. Call it when m has done a large piece of work, such as after loading a bundle or after VM.RunGC: the memory comes back when m needs it again.

It returns an error while m runs javascript, as from a Go function that javascript called. As with SetGCThreshold, no other goroutine may use m meanwhile (see VM).

func (*VM) RunGC

func (m *VM) RunGC()

RunGC frees what javascript can no longer reach, cycles too, and gives the small blocks the runtime keeps for reuse back to its arenas. The GC threshold is then 1.5 times what is left, unless it is ^uintptr(0). It runs no javascript: the callbacks of a FinalizationRegistry are queued for the next VM.ExecutePendingJobs.

func (*VM) RunYoungGC

func (m *VM) RunYoungGC()

RunYoungGC frees the cycles among the objects made since the last collection, young or full, and makes those it keeps old. It takes time in proportion to the young objects, which suits a run after each render.

It frees less than VM.RunGC: a cycle through an old object, and the value of a WeakMap entry whose map is reachable or old, wait for the next RunGC, so run RunGC now and then too. It treats weak references and FinalizationRegistry as RunGC does, and leaves the GC threshold as it is.

func (*VM) SetClock

func (m *VM) SetClock(now func() time.Time)

SetClock sets the wall clock of this VM. Date.now(), new Date(), Date(), Intl's current time and Temporal.Now (unless temporal.Clock overrides it) read now. nil restores time.Now. Set it only between calls into JavaScript, never concurrently with the VM or from a callback running inside it. The callback must not block. If several VMs share it, it must be safe for concurrent calls. Close releases it. It does not affect performance.now(), eval timeouts, Atomics.wait or the random seed.

func (*VM) SetEvalTimeout

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

SetEvalTimeout sets how long a call into javascript may run, d, from the next call on: each outermost call has d from when it starts, on the monotonic clock, so setting the system clock changes nothing. d of 0 or less is no timeout, and so is one longer than the clock can count, about 292 years. A call that runs out of time ends with an *Error whose Interrupted is set.

The timeout holds for every method that runs javascript: the Eval methods, Compile, the Call methods, ExecutePendingJobs, Value.Then, the property methods GetProperty, GetPropertyValue, SetProperty and SetPropertyValue and the methods of Value that call them, Value.MarshalJSON, Value.Any and ErrorFromValue. A method that runs no javascript, such as NewAtom or NewObjectValue, has none. A call a Go function makes from javascript, on the same VM, runs in the time left to the outer call.

Example

Each call has the whole timeout, and a loop that never ends stops when it runs out.

package main

import (
	"fmt"
	"time"

	"github.com/liustack/beastjs"
)

// newVM is NewVM for an example, which stops at an error.
func newVM() *beastjs.VM {
	m, err := beastjs.NewVM()
	if err != nil {
		panic(err)
	}
	return m
}

func main() {
	m := newVM()
	defer m.Close()
	for _, d := range []time.Duration{100 * time.Millisecond, time.Second, 3 * time.Second} {
		m.SetEvalTimeout(d)
		start := time.Now()
		v, err := m.Eval(`for (;;) {}`, beastjs.EvalGlobal)
		took := time.Since(start)
		fmt.Println(v, err, d, took >= d/2 && took <= d*3/2)
	}
}
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 how much memory m may take before the engine runs a collection by itself (see VM.GCThreshold). ^uintptr(0) keeps the engine from running one.

func (*VM) SetMaxStackSize

func (m *VM) SetMaxStackSize(threshold uintptr)

SetMaxStackSize sets how deep javascript calls may nest, 0 for the default of 5000, at most 10000. A deeper recursion throws a RangeError the script can catch.

func (*VM) SetMemoryLimit

func (m *VM) SetMemoryLimit(limit uintptr)

SetMemoryLimit sets the most memory m may take, in bytes, as VM.MemorySize counts it. A limit below 128 KiB is taken as 128 KiB, 0 too: it is not "no limit". ^uintptr(0) is no limit. A call that would pass the limit ends with an *Error whose OutOfMemory is set.

A limit that is too small is not kept to, as m needs memory to make the error itself. How small that is is not promised.

func (*VM) SetProperty

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

SetProperty sets the property prop of this to val, converted as an argument of VM.Call is, as VM.SetPropertyValue does.

func (*VM) SetPropertyValue

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

SetPropertyValue sets the property prop of this to val, as an assignment in strict code does: a setter runs, and a write the object refuses, as a Proxy can, is a TypeError. val stays the caller's. UndefinedValue and the zero Value are undefined. A Value of another VM is an error.

func (*VM) SetRegExpCache

func (m *VM) SetRegExpCache(n, bytes int) error

SetRegExpCache sets how many compiled regexps m keeps at most, n, and in how many bytes, counting their patterns and flags. It lets go of the regexps kept so far. 0 for either keeps none. A new VM keeps DefaultRegExpCache in DefaultRegExpCacheBytes.

A regexp whose pattern and flags are strings, from a literal, new RegExp, RegExp, compile or the copy split makes, takes the bytecode kept for the same pattern and flags when it is compiled. The one used least recently goes when there is no room. What is kept counts toward the memory limit, and m does not let it go when an allocation fails, so a script that runs close to the limit can run out of memory with the cache on where it would not without it.

func (*VM) SetShapeCache

func (m *VM) SetShapeCache(n int) error

SetShapeCache sets how many shapes m keeps once nothing uses them, n from 0, which keeps none, to math.MaxInt32/8. A shape is the list of an object's keys in their order. m keeps the shapes of plain objects: whose prototype is Object.prototype, with at most 32 keys and no symbol key that is not registered. The next object made with the same keys then finds its shape kept. A new VM keeps DefaultShapeCache.

The kept shapes count toward the memory limit (see VM.SetMemoryLimit), and each holds the atoms of its keys: about 100 bytes for a few keys, and about 3 KiB for 32 keys of ten characters each that no other object has, so 2048 such shapes take about 6 MiB. The table of atoms does not shrink once it grew. An allocation that would pass the memory limit lets go of all the kept shapes first.

func (*VM) SetStrip

func (m *VM) SetStrip(s Strip)

SetStrip sets what the functions m compiles from now on leave out: those of the Eval methods and Compile, and those of a script's own eval and new Function. With StripSource the toString of a function shows [native code]. StripDebug leaves out file names and line and column numbers, so that a stack frame shows only the name of its function, and the source too. Functions compiled before stay as they are.

The bytecode of VM.Compile keeps what it left out in every VM that loads it. Compiled on a VM of its own with both, a polyfill looks like a built-in function.

func (*VM) TrackRejections

func (m *VM) TrackRejections(max int) (err error)

func (*VM) UnhandledRejections

func (m *VM) UnhandledRejections() (reasons []*Error, dropped int, err error)

UnhandledRejections takes the rejections m kept when it is called (see VM.TrackRejections), oldest first, at most MaxTrackedRejections, and forgets them. Each reason is read as the error of a call that threw it is: an Error gives its Name, Message and Stack, any other value its text. Each text is cut to its first 8 KiB of UTF-8, or up to three bytes fewer so that no character is cut, followed by " [cut]" when it was longer: a reason is for a log, and javascript can make a string of hundreds of MiB, or a thousand references to one. dropped is how many rejections were not kept since the last call, past the limit or with no memory: a handler may have been attached to some of them since.

Reading a reason runs javascript, such as a getter of its message, inside the eval timeout. A rejection that this javascript makes is kept for the next call, after its jobs could attach a handler to it. The timeout and VM.Interrupt are read before each reason too. When one ends the call, UnhandledRejections returns the reasons read before it and the interrupt, and the rejections after the one it was reading stay kept.

What Go allocates for the reasons is taken from the room m has under its memory limit (see VM.SetMemoryLimit): before each reason, the most it may take, about 50 KiB, and then each text before it is copied, after the getters that ran before it. When the room left is less, UnhandledRejections returns the reasons read before and the out of memory error, and the rejections after the one it was reading stay kept. So a read allocates at most about 50 MiB in Go for 1,024 reasons, of which it keeps at most 40 MiB of texts. Javascript a getter runs after a text was copied can still use the room it took, so m and the read together may pass the limit by what the read holds in Go.

The error a read ends with has its texts cut the same way, so that all it returns is bounded. The errors of the other calls are not cut.

A read is the only one on m while it runs: called from javascript it runs, UnhandledRejections returns an error and takes nothing, as TrackRejections does.

type Value

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

Value is a javascript value that Go holds a reference to. The value lives as long as a reference to it does, and the javascript GC frees it once none does, so Go code that holds a Value keeps to these rules:

  • Each Value is freed with Free once, and not used after. Dropping one unfreed leaks it, until the VM closes.
  • A copy of a Value, by an assignment, is not a new reference. Dup makes one, which is freed on its own. Hand a Value on as a Dup, which the receiver frees, typically with defer.
  • A Value does not outlive its VM.

Dup and Free pair up, and the pairs nest as calls do. That is easy to get wrong across goroutines or channels: say g1 hands a Value to g2 by assignment, not by Dup, and both free it when they are done. If g1 frees first, g2 then uses a value that may be gone, and frees it a second time. The fix is for g1 to wait until g2 is done before it frees, or to hand g2 a Dup.

Where a Go value does, as with Eval and Call, use it: it needs none of this.

UndefinedValue and the zero Value belong to no VM, hold no reference and are undefined to every VM: freeing one does nothing, and Dup of one panics, as that is most often a Value used after its Free.

func (Value) Any

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

Any returns v as a Go value, as VM.Eval converts it. v stays the caller's. Converting an object or a BigInt runs javascript, inside the eval timeout. UndefinedValue and the zero Value are Undefined{}.

func (Value) Call

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

Call calls v with this and args and returns its value as a Go value, as VM.Call does with the same arguments. this is used as it is, not replaced by the global object: UndefinedValue is undefined.

A Go error is not among the types an argument converts by, so it goes as its JSON, which for an error of the standard library is {}: pass err.Error(). A Value that a function of VM.RegisterFunc gets, such as the resolve of a promise, is valid only during the call it got it in: to call it later, keep a Dup and free it when done.

func (Value) CallValue

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

CallValue is Value.Call that returns the value as a Value, which the caller frees.

func (Value) Dup

func (v Value) Dup() Value

Dup returns a new reference to v, which is freed on its own. It panics for a Value of no VM, which is most often one used after its Free.

func (*Value) Free

func (v *Value) Free()

Free gives up the reference v holds, and makes v the zero Value. It does nothing for UndefinedValue and the zero Value.

func (Value) GetProperty deprecated

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

GetProperty returns the property prop of v as a Go value.

Deprecated: this is not used: the property is read on v. Use Value.Property.

func (Value) GetPropertyValue

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

GetPropertyValue returns the property prop of v (see VM.GetPropertyValue).

func (Value) IsUndefined

func (v Value) IsUndefined() bool

IsUndefined reports whether v is undefined. UndefinedValue and the zero Value are.

func (Value) MarshalJSON

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

MarshalJSON returns the JSON of v, as JSON.stringify makes it, so that encoding/json writes a Value as the javascript value. For a value JSON.stringify gives undefined for, such as a function, it is the text undefined, which is not JSON. It runs javascript, such as toJSON, inside the eval timeout.

func (Value) Property

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

Property returns the property prop of v as a Go value (see VM.GetProperty).

func (Value) SetProperty

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

SetProperty sets the property prop of v to val (see VM.SetProperty).

func (Value) SetPropertyValue

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

SetPropertyValue sets the property prop of v to val (see VM.SetPropertyValue).

func (Value) Then

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

Then attaches onFulfilled and onRejected to the promise v, as v.then does, and returns the promise then returns, which the caller frees. Either may be nil. A handler gets the value or the reason, valid only during its call. Each is held until the engine frees the function that calls it, even when it never ran, or the VM closes.

func (*Value) VM

func (v *Value) VM() *VM

VM returns the VM of v, nil for UndefinedValue and the zero Value.

Directories

Path Synopsis
cmd
beastjs command
Command beastjs runs a JavaScript file in the engine of this module, set up as tifa sets it up, without writing Go:
Command beastjs runs a JavaScript file in the engine of this module, set up as tifa sets it up, without writing Go:
Package fmt gives a beastjs.VM some of Go's fmt: printf, println, sprint and sprintf.
Package fmt gives a beastjs.VM some of Go's fmt: printf, println, sprint and sprintf.
internal
cengine
Package cengine is the C engine of engine/ generated as Go assembly, with its Go host.
Package cengine is the C engine of engine/ generated as Go assembly, with its Go host.
cengine/cmd/gcpause command
Command gcpause measures how long the Go garbage collector waits to stop the world while VMs run a script that stays in the engine.
Command gcpause measures how long the Go garbage collector waits to stop the world while VMs run a script that stays in the engine.
cengine/cmd/interrupt command
Command interrupt times how long a script takes to stop after Interrupt, for the scripts of package scenarios, each of which stays inside one long operation of the engine.
Command interrupt times how long a script takes to stop after Interrupt, for the scripts of package scenarios, each of which stays inside one long operation of the engine.
cengine/cmd/jsrun command
Command jsrun evaluates a JavaScript file and prints its result, how long the evaluation took and what memory the VM held.
Command jsrun evaluates a JavaScript file and prints its result, how long the evaluation took and what memory the VM held.
cengine/cmd/scenarios
Package scenarios holds the scripts that the commands gcpause and interrupt run: each stays inside one long operation of the engine.
Package scenarios holds the scripts that the commands gcpause and interrupt run: each stays inside one long operation of the engine.
dtoatable command
Command dtoatable writes engine/dtoa-pow10.h, the table of powers of ten that the shortest conversion of a float64 to decimal in engine/dtoa.c uses (the Schubfach algorithm of Raffaello Giulietti, written from his paper "The Schubfach way to render doubles").
Command dtoatable writes engine/dtoa-pow10.h, the table of powers of ten that the shortest conversion of a float64 to decimal in engine/dtoa.c uses (the Schubfach algorithm of Raffaello Giulietti, written from his paper "The Schubfach way to render doubles").
faultstate
Package faultstate tells whether the state of the CPU that windows/arm64 writes below the stack pointer at a fault fits in the room Go keeps for it, so that a fault in the engine cannot write past a goroutine stack into the heap.
Package faultstate tells whether the state of the CPU that windows/arm64 writes below the stack pointer at a fault fits in the room Go keeps for it, so that a fault in the engine cannot write past a goroutine stack into the heap.
faulttest
Package faulttest is for the tests that make a memory fault on purpose: a read through a wild pointer, or a write to a guard page or to read-only memory.
Package faulttest is for the tests that make a memory fault on purpose: a read through a wild pointer, or a write to a guard page or to read-only memory.
goasm/cmd/cycles command
Command cycles lists the cycles of the engine's call graph that no counted depth cuts.
Command cycles lists the cycles of the engine's call graph that no counted depth cuts.
goasm/cmd/xform command
Command xform moves the code of generated Go assembly, to measure how much a speed result depends on where the code sits (see "Code positions" in docs/internals/performance.md).
Command xform moves the code of generated Go assembly, to measure how much a speed result depends on where the code sits (see "Code positions" in docs/internals/performance.md).
goasm/gen/cmd/gocalls command
Command gocalls writes internal/cengine/gocalls.txt, the engine functions the Go code of the module names (gen.GoCalls).
Command gocalls writes internal/cengine/gocalls.txt, the engine functions the Go code of the module names (gen.GoCalls).
gohost
Package gohost is the Go side of the callbacks the C engine asks of its host (engine/host.h and host_memory_grow in engine/heap.h), for the engine generated as Go assembly.
Package gohost is the Go side of the callbacks the C engine asks of its host (engine/host.h and host_memory_grow in engine/heap.h), for the engine generated as Go assembly.
goversion
Package goversion stops a build with a Go newer than the one the engine was checked with.
Package goversion stops a build with a Go newer than the one the engine was checked with.
hostmem
Package hostmem is the memory the Go host gives the C engine.
Package hostmem is the memory the Go host gives the C engine.
idtable
Package idtable gives things small ids, which the C engine passes back to the host on every callback, and finds a thing by its id with two atomic reads and no lock: callbacks of VMs on many goroutines do not wait for each other, and do not write to memory they share.
Package idtable gives things small ids, which the C engine passes back to the host on every callback, and finds a thing by its id with two atomic reads and no lock: callbacks of VMs on many goroutines do not wait for each other, and do not write to memory they share.
intlhook
Package intlhook connects the Intl and Temporal shims.
Package intlhook connects the Intl and Temporal shims.
measure
Package measure holds what the subcommands of go tool measure share: running a command with its output kept and timed.
Package measure holds what the subcommands of go tool measure share: running a command with its output kept and timed.
measure/bench
Package bench builds the code-position variants of a program, times them in turn, and reads the result by the protocol of docs/internals/measuring.md.
Package bench builds the code-position variants of a program, times them in turn, and reads the result by the protocol of docs/internals/measuring.md.
measure/cmd/measure command
Command measure times builds of the C engine against each other.
Command measure times builds of the C engine against each other.
measure/hwm
Package hwm reads the most memory the calling process held, from the process itself, for the programs that go tool measure times.
Package hwm reads the most memory the calling process held, from the process itself, for the programs that go tool measure times.
rvgen
Package rvgen makes small random JavaScript programs for testing the register loop of the engine (engine/regvm.h): against Node (rvgen node) and in the tests of the Go package.
Package rvgen makes small random JavaScript programs for testing the register loop of the engine (engine/regvm.h): against Node (rvgen node) and in the tests of the Go package.
rvgen/cmd/rvgen command
Command rvgen makes random programs (package rvgen) and runs them through rvdiff, the runner of the native test host that compares each run with its golden (engine/test/regvm/rvdiff.c, built by engine/test/regvm/build.sh):
Command rvgen makes random programs (package rvgen) and runs them through rvdiff, the runner of the native test host that compares each run with its golden (engine/test/regvm/rvdiff.c, built by engine/test/regvm/build.sh):
rvgen/v1
Package v1 is rvgen frozen as it was when the goldens of the fuzz seeds were recorded from the old loop (engine/test/regvm/golden/seeds, see rvgen check): the same seed must make the same program for good, so this copy is never changed.
Package v1 is rvgen frozen as it was when the goldens of the fuzz seeds were recorded from the old loop (engine/test/regvm/golden/seeds, see rvgen check): the same seed must make the same program for good, so this copy is never changed.
stopsweep
Package stopsweep is for the tests of the packages that give a VM functions written in Go (intl, temporal, fmt and url): it stops a long call at many eval timeouts, so that a part of the call that does not check the limits shows wherever it lies in the call, not only where one fixed timeout falls.
Package stopsweep is for the tests of the packages that give a VM functions written in Go (intl, temporal, fmt and url): it stops a long call at many eval timeouts, so that a part of the call that does not check the limits shows wherever it lies in the call, not only where one fixed timeout falls.
stress command
Command stress renders tifa's pinned pages for a set time on pools of VMs kept as tifa's pool keeps them, with memory limits, eval timeouts, Interrupts and kills landing at random points of the renders, and checks that every VM stays correct and bounded: each render gives the page's HTML or the error its stop documents, a VM goes on after a stop that was not a kill, the memory of the engine, of the host and of Go and the goroutines stay bounded with no drift after the warm-up, and closing every VM gives all its memory back.
Command stress renders tifa's pinned pages for a set time on pools of VMs kept as tifa's pool keeps them, with memory limits, eval timeouts, Interrupts and kills landing at random points of the renders, and checks that every VM stays correct and bounded: each render gives the page's HTML or the error its stop documents, a VM goes on after a stop that was not a kill, the memory of the engine, of the host and of Go and the goroutines stay bounded with no drift after the warm-up, and closing every VM gives all its memory back.
unsupported
Package unsupported stops a build on a target the C engine does not run on: it runs on linux, darwin and windows, on amd64 and arm64, only.
Package unsupported stops a build on a target the C engine does not run on: it runs on linux, darwin and windows, on amd64 and arm64, only.
vmhook
Package vmhook lets the packages of this module that give a VM functions written in Go (intl, temporal, fmt and url) hold the work those functions do in Go to the limits of the VM: its eval timeout, Interrupt and its memory limit, which the engine's polls and allocator see only for the work done in the engine.
Package vmhook lets the packages of this module that give a VM functions written in Go (intl, temporal, fmt and url) hold the work those functions do in Go to the limits of the VM: its eval timeout, Interrupt and its memory limit, which the engine's polls and allocator see only for the work done in the engine.
whatwgurl
Package whatwgurl is the URL parser of the WHATWG URL standard (https://url.spec.whatwg.org/), with the setters of its API and the serializer, for package url.
Package whatwgurl is the URL parser of the WHATWG URL standard (https://url.spec.whatwg.org/), with the setters of its API and the serializer, for package url.
whatwgurl/bidi
Package bidi has the Bidi class of a rune and implements the Bidi Rule defined by RFC 5893.
Package bidi has the Bidi class of a rune and implements the Bidi Rule defined by RFC 5893.
whatwgurl/idna
Package idna is the part of golang.org/x/net/idna v0.62.0 (IDNA2008 with the compatibility processing of UTS #46) that the URL standard needs: one profile, "domain to ASCII", which has Unicode 17's tables and the algorithm of UTS #46 revision 35.
Package idna is the part of golang.org/x/net/idna v0.62.0 (IDNA2008 with the compatibility processing of UTS #46) that the URL standard needs: one profile, "domain to ASCII", which has Unicode 17's tables and the algorithm of UTS #46 revision 35.
Package intl gives a beastjs.VM the ECMA-402 Intl API, computed in Go.
Package intl gives a beastjs.VM the ECMA-402 Intl API, computed in Go.
Package temporal implements Temporal, the ECMAScript date and time API, for a beastjs.VM.
Package temporal implements Temporal, the ECMAScript date and time API, for a beastjs.VM.
Package tifa gives a beastjs.VM what tifa (github.com/liustack/tifa) gives each VM of its pool before it runs a bundle: URL and URLSearchParams, Intl and Temporal, and the functions named __tifa_* that the bundles tifa builds ask for.
Package tifa gives a beastjs.VM what tifa (github.com/liustack/tifa) gives each VM of its pool before it runs a bundle: URL and URLSearchParams, Intl and Temporal, and the functions named __tifa_* that the bundles tifa builds ask for.
Package url gives a beastjs.VM the globals URL and URLSearchParams, as the URL standard (https://url.spec.whatwg.org/) defines them, with the parsing done in Go.
Package url gives a beastjs.VM the globals URL and URLSearchParams, as the URL standard (https://url.spec.whatwg.org/) defines them, with the parsing done in Go.

Jump to

Keyboard shortcuts

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