v8go

package module
Version: v0.6.0 Latest Latest
Warning

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

Go to latest
Published: May 11, 2021 License: BSD-3-Clause Imports: 15 Imported by: 22

README

Execute JavaScript from Go

Github release Go Report Card Go Reference CI V8 Build codecov FOSSA Status

V8 Gopher based on original artwork from the amazing Renee French

Usage

import "rogchap.com/v8go"
Running a script
ctx, _ := v8go.NewContext() // creates a new V8 context with a new Isolate aka VM
ctx.RunScript("const add = (a, b) => a + b", "math.js") // executes a script on the global context
ctx.RunScript("const result = add(3, 4)", "main.js") // any functions previously added to the context can be called
val, _ := ctx.RunScript("result", "value.js") // return a value in JavaScript back to Go
fmt.Printf("addition result: %s", val)
One VM, many contexts
iso, _ := v8go.NewIsolate() // creates a new JavaScript VM
ctx1, _ := v8go.NewContext(iso) // new context within the VM
ctx1.RunScript("const multiply = (a, b) => a * b", "math.js")

ctx2, _ := v8go.NewContext(iso) // another context on the same VM
if _, err := ctx2.RunScript("multiply(3, 4)", "main.js"); err != nil {
  // this will error as multiply is not defined in this context
}
JavaScript function with Go callback
iso, _ := v8go.NewIsolate() // create a new VM
// a template that represents a JS function
printfn, _ := v8go.NewFunctionTemplate(iso, func(info *v8go.FunctionCallbackInfo) *v8go.Value {
    fmt.Printf("%v", info.Args()) // when the JS function is called this Go callback will execute
    return nil // you can return a value back to the JS caller if required
})
global, _ := v8go.NewObjectTemplate(iso) // a template that represents a JS Object
global.Set("print", printfn) // sets the "print" property of the Object to our function
ctx, _ := v8go.NewContext(iso, global) // new Context with the global Object set to our object template
ctx.RunScript("print('foo')", "print.js") // will execute the Go callback with a single argunent 'foo'
Update a JavaScript object from Go
ctx, _ := v8go.NewContext() // new context with a default VM
obj := ctx.Global() // get the global object from the context
obj.Set("version", "v1.0.0") // set the property "version" on the object
val, _ := ctx.RunScript("version", "version.js") // global object will have the property set within the JS VM
fmt.Printf("version: %s", val)

if obj.Has("version") { // check if a property exists on the object
    obj.Delete("version") // remove the property from the object
}
JavaScript errors
val, err := ctx.RunScript(src, filename)
if err != nil {
  e := err.(*v8go.JSError) // JavaScript errors will be returned as the JSError struct
  fmt.Println(e.Message) // the message of the exception thrown
  fmt.Println(e.Location) // the filename, line number and the column where the error occured
  fmt.Println(e.StackTrace) // the full stack trace of the error, if available

  fmt.Printf("javascript error: %v", e) // will format the standard error message
  fmt.Printf("javascript stack trace: %+v", e) // will format the full error stack trace
}
Terminate long running scripts
vals := make(chan *v8go.Value, 1)
errs := make(chan error, 1)

go func() {
    val, err := ctx.RunScript(script, "forever.js") // exec a long running script
    if err != nil {
        errs <- err
        return
    }
    vals <- val
}()

select {
case val := <- vals:
    // sucess
case err := <- errs:
    // javascript error
case <- time.After(200 * time.Milliseconds):
    vm, _ := ctx.Isolate() // get the Isolate from the context
    vm.TerminateExecution() // terminate the execution 
    err := <- errs // will get a termination error back from the running script
}

Documentation

Go Reference & more examples: https://pkg.go.dev/rogchap.com/v8go

Support

If you would like to ask questions about this library or want to keep up-to-date with the latest changes and releases, please join the #v8go channel on Gophers Slack. Click here to join the Gophers Slack community!

Windows

In order to build a project using v8go on Windows, Go requires a gcc compiler to be installed.

To set this up:

  1. Install MSYS2 (https://www.msys2.org/)
  2. Add the Mingw-w64 bin to your PATH environment variable (C:\msys64\mingw64\bin by default)
  3. Open MSYS2 MSYS and execute pacman -S mingw-w64-x86_64-toolchain

V8 requires 64-bit on Windows, therefore it will not work on 32-bit systems.

V8 dependency

V8 version: 9.0.257.18 (April 2021)

In order to make v8go usable as a standard Go package, prebuilt static libraries of V8 are included for Linux, macOS and Windows ie. you should not require to build V8 yourself.

Due to security concerns of binary blobs hiding malicious code, the V8 binary is built via CI ONLY.

Project Goals

To provide a high quality, idiomatic, Go binding to the V8 C++ API.

The API should match the original API as closely as possible, but with an API that Gophers (Go enthusiasts) expect. For example: using multiple return values to return both result and error from a function, rather than throwing an exception.

This project also aims to keep up-to-date with the latest (stable) release of V8.

License

FOSSA Status

Development

Upgrading the V8 binaries

This process is non-trivial, and hopefully we can automate more of this in the future.

  1. Make sure to clone the projects submodules (ie. the V8's depot_tools project): git submodule update --init --recursive
  2. Add the depot_tools folder to your PATH eg: export PATH=~/Development/rogchap/v8go/deps/depot_tools:$PATH
  3. From the deps folder run fetch v8; you only need to do this once, if you don't already have the V8 source.
  4. Find the current stable release (v8_version) here: https://omahaproxy.appspot.com
  5. Create a new git branch from master eg. git checkout -b v8_7_upgrade
  6. Enter the v8 folder and fetch all the latest git branches: cd deps/v8 && git fetch
  7. Find the right branch-heads/** to checkout, for example if the v8_version is 8.7.220.31 then you want to git checkout branch-heads/8.7. You can check all the branch-heads with git branch --remotes | grep branch-heads/
  8. Copy all the contents of deps/v8/include to deps/include making sure not to delete any of the vendor.go files, which are required for users that are using go mod vendor. If there are any new folders added, make sure to create new vendor.go files in each folder within deps/include and update cgo.go.
  9. Optionally build the V8 binary for your OS: cd deps && ./build.py. V8 is a large project, and building the binary can take up to 30 minutes. Once built all the tests should still pass via go test -v .
  10. Commit your changes, making sure that the git submodules have been updated to the new checksum for the version of V8. Make sure NOT to add your build of the binary, as this will be build via CI.
  11. Because the build is so long, this is not automatically triggered. Go to the V8 Build Github Action, Select "Run workflow", and select your pushed branch eg. v8_7_upgrade.
  12. Once built, this should open 3 PRs against your branch to add the libv8.a for Linux, macOS and Windows; merge these PRs into your branch. You are now ready to raise the PR against master with the latest version of V8.
Formatting

Go has go fmt, C has clang-format. Any changes to the v8go.h|cc should be formated with clang-format with the "Chromium" Coding style. This can be done easily by running the go generate command.

brew install clang-format to install on macOS.


V8 Gopher image based on original artwork from the amazing Renee French.

Documentation

Overview

Package v8go provides an API to execute JavaScript.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func JSONStringify

func JSONStringify(ctx *Context, val Valuer) (string, error)

JSONStringify tries to stringify the JSON-serializable object value and returns it as string.

Example
package main

import (
	"fmt"

	"rogchap.com/v8go"
)

func main() {
	ctx, _ := v8go.NewContext()
	val, _ := v8go.JSONParse(ctx, `{
		"a": 1,
		"b": "foo"
	}`)
	jsonStr, _ := v8go.JSONStringify(ctx, val)
	fmt.Println(jsonStr)
}
Output:

{"a":1,"b":"foo"}

func SetFlags

func SetFlags(flags ...string)

SetFlags sets flags for V8. For possible flags: https://github.com/v8/v8/blob/master/src/flags/flag-definitions.h Flags are expected to be prefixed with `--`, for example: `--harmony`. Flags can be reverted using the `--no` prefix equivalent, for example: `--use_strict` vs `--nouse_strict`. Flags will affect all Isolates created, even after creation.

func Version

func Version() string

Version returns the version of the V8 Engine with the -v8go suffix

Types

type Context

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

Context is a global root execution environment that allows separate, unrelated, JavaScript applications to run in a single instance of V8.

Example
package main

import (
	"fmt"

	"rogchap.com/v8go"
)

func main() {
	ctx, _ := v8go.NewContext()
	ctx.RunScript("const add = (a, b) => a + b", "math.js")
	ctx.RunScript("const result = add(3, 4)", "main.js")
	val, _ := ctx.RunScript("result", "value.js")
	fmt.Println(val)
}
Output:

7
Example (GlobalTemplate)
package main

import (
	"fmt"

	"rogchap.com/v8go"
)

func main() {
	iso, _ := v8go.NewIsolate()
	obj, _ := v8go.NewObjectTemplate(iso)
	obj.Set("version", "v1.0.0")
	ctx, _ := v8go.NewContext(iso, obj)
	val, _ := ctx.RunScript("version", "main.js")
	fmt.Println(val)
}
Output:

v1.0.0
Example (Isolate)
package main

import (
	"fmt"

	"rogchap.com/v8go"
)

func main() {
	iso, _ := v8go.NewIsolate()
	ctx1, _ := v8go.NewContext(iso)
	ctx1.RunScript("const foo = 'bar'", "context_one.js")
	val, _ := ctx1.RunScript("foo", "foo.js")
	fmt.Println(val)

	ctx2, _ := v8go.NewContext(iso)
	_, err := ctx2.RunScript("foo", "context_two.js")
	fmt.Println(err)
}
Output:

bar
ReferenceError: foo is not defined

func NewContext

func NewContext(opt ...ContextOption) (*Context, error)

NewContext creates a new JavaScript context; if no Isolate is passed as a ContextOption than a new Isolate will be created.

func (*Context) Close

func (c *Context) Close()

Close will dispose the context and free the memory. Access to any values assosiated with the context after calling Close may panic.

func (*Context) Global

func (c *Context) Global() *Object

Global returns the global proxy object. Global proxy object is a thin wrapper whose prototype points to actual context's global object with the properties like Object, etc. This is done that way for security reasons. Please note that changes to global proxy object prototype most probably would break the VM — V8 expects only global object as a prototype of global proxy object.

func (*Context) Isolate

func (c *Context) Isolate() (*Isolate, error)

Isolate gets the current context's parent isolate.An error is returned if the isolate has been terninated.

func (*Context) PerformMicrotaskCheckpoint

func (c *Context) PerformMicrotaskCheckpoint()

PerformMicrotaskCheckpoint runs the default MicrotaskQueue until empty. This is used to make progress on Promises.

func (*Context) RunScript

func (c *Context) RunScript(source string, origin string) (*Value, error)

RunScript executes the source JavaScript; origin or filename provides a reference for the script and used in the stack trace if there is an error. error will be of type `JSError` of not nil.

type ContextOption

type ContextOption interface {
	// contains filtered or unexported methods
}

ContextOption sets options such as Isolate and Global Template to the NewContext

type Function

type Function struct {
	*Value
}

Function is a JavaScript function.

func (*Function) Call

func (fn *Function) Call(args ...Valuer) (*Value, error)

Call this JavaScript function with the given arguments.

type FunctionCallback

type FunctionCallback func(info *FunctionCallbackInfo) *Value

FunctionCallback is a callback that is executed in Go when a function is executed in JS.

type FunctionCallbackInfo

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

FunctionCallbackInfo is the argument that is passed to a FunctionCallback.

func (*FunctionCallbackInfo) Args

func (i *FunctionCallbackInfo) Args() []*Value

Args returns a slice of the value arguments that are passed to the JS function.

func (*FunctionCallbackInfo) Context

func (i *FunctionCallbackInfo) Context() *Context

Context is the current context that the callback is being executed in.

type FunctionTemplate

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

FunctionTemplate is used to create functions at runtime. There can only be one function created from a FunctionTemplate in a context. The lifetime of the created function is equal to the lifetime of the context.

Example
package main

import (
	"fmt"

	"rogchap.com/v8go"
)

func main() {
	iso, _ := v8go.NewIsolate()
	global, _ := v8go.NewObjectTemplate(iso)
	printfn, _ := v8go.NewFunctionTemplate(iso, func(info *v8go.FunctionCallbackInfo) *v8go.Value {
		fmt.Printf("%+v\n", info.Args())
		return nil
	})
	global.Set("print", printfn, v8go.ReadOnly)
	ctx, _ := v8go.NewContext(iso, global)
	ctx.RunScript("print('foo', 'bar', 0, 1)", "")
}
Output:

[foo bar 0 1]
Example (Fetch)
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"

	"rogchap.com/v8go"
)

func main() {
	iso, _ := v8go.NewIsolate()
	global, _ := v8go.NewObjectTemplate(iso)

	fetchfn, _ := v8go.NewFunctionTemplate(iso, func(info *v8go.FunctionCallbackInfo) *v8go.Value {
		args := info.Args()
		url := args[0].String()

		resolver, _ := v8go.NewPromiseResolver(info.Context())

		go func() {
			res, _ := http.Get(url)
			body, _ := ioutil.ReadAll(res.Body)
			val, _ := v8go.NewValue(iso, string(body))
			resolver.Resolve(val)
		}()
		return resolver.GetPromise().Value
	})
	global.Set("fetch", fetchfn, v8go.ReadOnly)

	ctx, _ := v8go.NewContext(iso, global)
	val, _ := ctx.RunScript("fetch('https://rogchap.com/v8go')", "")
	prom, _ := val.AsPromise()

	// wait for the promise to resolve
	for prom.State() == v8go.Pending {
		continue
	}
	fmt.Printf("%s\n", strings.Split(prom.Result().String(), "\n")[0])
}
Output:

<!DOCTYPE html>

func NewFunctionTemplate

func NewFunctionTemplate(iso *Isolate, callback FunctionCallback) (*FunctionTemplate, error)

NewFunctionTemplate creates a FunctionTemplate for a given callback.

func (*FunctionTemplate) GetFunction

func (tmpl *FunctionTemplate) GetFunction(ctx *Context) *Function

GetFunction returns an instance of this function template bound to the given context.

func (FunctionTemplate) Set

func (t FunctionTemplate) Set(name string, val interface{}, attributes ...PropertyAttribute) error

Set adds a property to each instance created by this template. The property must be defined either as a primitive value, or a template. If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a value will be created and set as the value property.

type HeapStatistics

type HeapStatistics struct {
	TotalHeapSize            uint64
	TotalHeapSizeExecutable  uint64
	TotalPhysicalSize        uint64
	TotalAvailableSize       uint64
	UsedHeapSize             uint64
	HeapSizeLimit            uint64
	MallocedMemory           uint64
	ExternalMemory           uint64
	PeakMallocedMemory       uint64
	NumberOfNativeContexts   uint64
	NumberOfDetachedContexts uint64
}

HeapStatistics represents V8 isolate heap statistics

type Isolate

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

Isolate is a JavaScript VM instance with its own heap and garbage collector. Most applications will create one isolate with many V8 contexts for execution.

func NewIsolate

func NewIsolate() (*Isolate, error)

NewIsolate creates a new V8 isolate. Only one thread may access a given isolate at a time, but different threads may access different isolates simultaneously. When an isolate is no longer used its resources should be freed by calling iso.Dispose(). An *Isolate can be used as a v8go.ContextOption to create a new Context, rather than creating a new default Isolate.

func (*Isolate) Close deprecated

This method has been deprecated.
func (i *Isolate) Close()

Deprecated: use `iso.Dispose()`.

func (*Isolate) Dispose

func (i *Isolate) Dispose()

Dispose will dispose the Isolate VM; subsequent calls will panic.

func (*Isolate) GetHeapStatistics

func (i *Isolate) GetHeapStatistics() HeapStatistics

GetHeapStatistics returns heap statistics for an isolate.

func (*Isolate) TerminateExecution

func (i *Isolate) TerminateExecution()

TerminateExecution terminates forcefully the current thread of JavaScript execution in the given isolate.

type JSError

type JSError struct {
	Message    string
	Location   string
	StackTrace string
}

JSError is an error that is returned if there is are any JavaScript exceptions handled in the context. When used with the fmt verb `%+v`, will output the JavaScript stack trace, if available.

func (*JSError) Error

func (e *JSError) Error() string

func (*JSError) Format

func (e *JSError) Format(s fmt.State, verb rune)

Format implements the fmt.Formatter interface to provide a custom formatter primarily to output the javascript stack trace with %+v

type Object

type Object struct {
	*Value
}

Object is a JavaScript object (ECMA-262, 4.3.3)

Example (Global)
package main

import (
	"fmt"

	"rogchap.com/v8go"
)

func main() {
	iso, _ := v8go.NewIsolate()
	ctx, _ := v8go.NewContext(iso)
	global := ctx.Global()

	console, _ := v8go.NewObjectTemplate(iso)
	logfn, _ := v8go.NewFunctionTemplate(iso, func(info *v8go.FunctionCallbackInfo) *v8go.Value {
		fmt.Println(info.Args()[0])
		return nil
	})
	console.Set("log", logfn)
	consoleObj, _ := console.NewInstance(ctx)

	global.Set("console", consoleObj)
	ctx.RunScript("console.log('foo')", "")
}
Output:

foo

func (*Object) Delete

func (o *Object) Delete(key string) bool

Delete returns true if successful in deleting a named property on the object.

func (*Object) DeleteIdx

func (o *Object) DeleteIdx(idx uint32) bool

DeleteIdx returns true if successful in deleting a value at a given index of the object.

func (*Object) Get

func (o *Object) Get(key string) (*Value, error)

Get tries to get a Value for a given Object property key.

func (*Object) GetIdx

func (o *Object) GetIdx(idx uint32) (*Value, error)

GetIdx tries to get a Value at a give Object index.

func (*Object) Has

func (o *Object) Has(key string) bool

Has calls the abstract operation HasProperty(O, P) described in ECMA-262, 7.3.10. Returns true, if the object has the property, either own or on the prototype chain.

func (*Object) HasIdx

func (o *Object) HasIdx(idx uint32) bool

HasIdx returns true if the object has a value at the given index.

func (*Object) Set

func (o *Object) Set(key string, val interface{}) error

Set will set a property on the Object to a given value. Supports all value types, eg: Object, Array, Date, Set, Map etc If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a *Value will be created and set as the value property.

func (*Object) SetIdx

func (o *Object) SetIdx(idx uint32, val interface{}) error

Set will set a given index on the Object to a given value. Supports all value types, eg: Object, Array, Date, Set, Map etc If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a *Value will be created and set as the value property.

type ObjectTemplate

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

ObjectTemplate is used to create objects at runtime. Properties added to an ObjectTemplate are added to each object created from the ObjectTemplate.

func NewObjectTemplate

func NewObjectTemplate(iso *Isolate) (*ObjectTemplate, error)

NewObjectTemplate creates a new ObjectTemplate. The *ObjectTemplate can be used as a v8go.ContextOption to create a global object in a Context.

func (*ObjectTemplate) NewInstance

func (o *ObjectTemplate) NewInstance(ctx *Context) (*Object, error)

NewInstance creates a new Object based on the template.

func (ObjectTemplate) Set

func (t ObjectTemplate) Set(name string, val interface{}, attributes ...PropertyAttribute) error

Set adds a property to each instance created by this template. The property must be defined either as a primitive value, or a template. If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a value will be created and set as the value property.

type Promise

type Promise struct {
	*Object
}

Promise is the JavaScript promise object defined in ES6

func (*Promise) Catch

func (p *Promise) Catch(cb FunctionCallback) *Promise

Catch invokes the given function if the promise is rejected. See Then for other details.

func (*Promise) Result

func (p *Promise) Result() *Value

Result is the value result of the Promise. The Promise must NOT be in a Pending state, otherwise may panic. Call promise.State() to validate state before calling for the result.

func (*Promise) State

func (p *Promise) State() PromiseState

State returns the current state of the Promise.

func (*Promise) Then

func (p *Promise) Then(cbs ...FunctionCallback) *Promise

Then accepts 1 or 2 callbacks. The first is invoked when the promise has been fulfilled. The second is invoked when the promise has been rejected. The returned Promise resolves after the callback finishes execution.

V8 only invokes the callback when processing "microtasks". The default MicrotaskPolicy processes them when the call depth decreases to 0. Call (*Context).PerformMicrotaskCheckpoint to trigger it manually.

type PromiseResolver

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

PromiseResolver is the resolver object for the promise. Most cases will create a new PromiseResolver and return the associated Promise from the resolver.

func NewPromiseResolver

func NewPromiseResolver(ctx *Context) (*PromiseResolver, error)

MewPromiseResolver creates a new Promise resolver for the given context. The associated Promise will be in a Pending state.

func (*PromiseResolver) GetPromise

func (r *PromiseResolver) GetPromise() *Promise

GetPromise returns the associated Promise object for this resolver. The Promise object is unique to the resolver and returns the same object on multiple calls.

func (*PromiseResolver) Reject

func (r *PromiseResolver) Reject(err *Value) bool

Reject invokes the Promise reject state with the given value. The Promise state will transition from Pending to Rejected.

func (*PromiseResolver) Resolve

func (r *PromiseResolver) Resolve(val Valuer) bool

Resolve invokes the Promise resolve state with the given value. The Promise state will transition from Pending to Fulfilled.

type PromiseState

type PromiseState int

PromiseState is the state of the Promise.

const (
	Pending PromiseState = iota
	Fulfilled
	Rejected
)

type PropertyAttribute

type PropertyAttribute uint8

PropertyAttribute are the attribute flags for a property on an Object. Typical usage when setting an Object or TemplateObject property, and can also be validated when accessing a property.

const (
	// None.
	None PropertyAttribute = 0
	// ReadOnly, ie. not writable.
	ReadOnly PropertyAttribute = 1 << iota
	// DontEnum, ie. not enumerable.
	DontEnum
	// DontDelete, ie. not configurable.
	DontDelete
)

type Value

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

Value represents all Javascript values and objects

func JSONParse

func JSONParse(ctx *Context, str string) (*Value, error)

JSONParse tries to parse the string and returns it as *Value if successful. Any JS errors will be returned as `JSError`.

Example
package main

import (
	"fmt"

	"rogchap.com/v8go"
)

func main() {
	ctx, _ := v8go.NewContext()
	val, _ := v8go.JSONParse(ctx, `{"foo": "bar"}`)
	fmt.Println(val)
}
Output:

[object Object]

func NewValue

func NewValue(iso *Isolate, val interface{}) (*Value, error)

NewValue will create a primitive value. Supported values types to create are:

string -> V8::String
int32 -> V8::Integer
uint32 -> V8::Integer
bool -> V8::Boolean
int64 -> V8::BigInt
uint64 -> V8::BigInt
bool -> V8::Boolean
*big.Int -> V8::BigInt

func (*Value) ArrayIndex

func (v *Value) ArrayIndex() (idx uint32, ok bool)

ArrayIndex attempts to converts a string to an array index. Returns ok false if conversion fails.

func (*Value) AsFunction

func (v *Value) AsFunction() (*Function, error)

func (*Value) AsObject

func (v *Value) AsObject() (*Object, error)

AsObject will cast the value to the Object type. If the value is not an Object then an error is returned. Use `value.Object()` to do the JS equivalent of `Object(value)`.

func (*Value) AsPromise

func (v *Value) AsPromise() (*Promise, error)

func (*Value) BigInt

func (v *Value) BigInt() *big.Int

BigInt perform the equivalent of `BigInt(value)` in JS.

func (*Value) Boolean

func (v *Value) Boolean() bool

Boolean perform the equivalent of `Boolean(value)` in JS. This can never fail.

func (*Value) DetailString

func (v *Value) DetailString() string

DetailString provide a string representation of this value usable for debugging.

func (*Value) Format

func (v *Value) Format(s fmt.State, verb rune)

Format implements the fmt.Formatter interface to provide a custom formatter primarily to output the detail string (for debugging) with `%+v` verb.

func (*Value) Int32

func (v *Value) Int32() int32

Int32 perform the equivalent of `Number(value)` in JS and convert the result to a signed 32-bit integer by performing the steps in https://tc39.es/ecma262/#sec-toint32.

func (*Value) Integer

func (v *Value) Integer() int64

Integer perform the equivalent of `Number(value)` in JS and convert the result to an integer. Negative values are rounded up, positive values are rounded down. NaN is converted to 0. Infinite values yield undefined results.

func (*Value) IsArgumentsObject

func (v *Value) IsArgumentsObject() bool

IsArgumentsObject returns true if this value is an Arguments object.

func (*Value) IsArray

func (v *Value) IsArray() bool

IsArray returns true if this value is an array. Note that it will return false for a `Proxy` of an array.

func (*Value) IsArrayBuffer

func (v *Value) IsArrayBuffer() bool

IsArrayBuffer returns true if this value is an `ArrayBuffer`.

func (*Value) IsArrayBufferView

func (v *Value) IsArrayBufferView() bool

IsArrayBufferView returns true if this value is an `ArrayBufferView`.

func (*Value) IsAsyncFunction

func (v *Value) IsAsyncFunction() bool

IsAsyncFunc returns true if this value is an async function.

func (*Value) IsBigInt

func (v *Value) IsBigInt() bool

IsBigInt returns true if this value is a bigint. This is equivalent to `typeof value === 'bigint'` in JS.

func (*Value) IsBigInt64Array

func (v *Value) IsBigInt64Array() bool

IsBigInt64Array returns true if this value is a `BigInt64Array`.

func (*Value) IsBigIntObject

func (v *Value) IsBigIntObject() bool

IsBigIntObject returns true if this value is a BigInt object.

func (*Value) IsBigUint64Array

func (v *Value) IsBigUint64Array() bool

IsBigUint64Array returns true if this value is a BigUint64Array`.

func (*Value) IsBoolean

func (v *Value) IsBoolean() bool

IsBoolean returns true if this value is boolean. This is equivalent to `typeof value === 'boolean'` in JS.

func (*Value) IsDataView

func (v *Value) IsDataView() bool

IsDataView returns true if this value is a `DataView`.

func (*Value) IsDate

func (v *Value) IsDate() bool

IsDate returns true if this value is a `Date`.

func (*Value) IsExternal

func (v *Value) IsExternal() bool

IsExternal returns true if this value is an `External` object.

func (*Value) IsFalse

func (v *Value) IsFalse() bool

IsFalse returns true if this value is false. This is not the same as `!BooleanValue()`. The latter performs a conversion to boolean, i.e. the result of `!Boolean(value)` in JS, whereas this checks `value === false`.

func (*Value) IsFloat32Array

func (v *Value) IsFloat32Array() bool

IsFloat32Array returns true if this value is a `Float32Array`.

func (*Value) IsFloat64Array

func (v *Value) IsFloat64Array() bool

IsFloat64Array returns true if this value is a `Float64Array`.

func (*Value) IsFunction

func (v *Value) IsFunction() bool

IsFunction returns true if this value is a function. This is equivalent to `typeof value === 'function'` in JS.

func (*Value) IsGeneratorFunction

func (v *Value) IsGeneratorFunction() bool

Is IsGeneratorFunc returns true if this value is a Generator function.

func (*Value) IsGeneratorObject

func (v *Value) IsGeneratorObject() bool

IsGeneratorObject returns true if this value is a Generator object (iterator).

func (*Value) IsInt16Array

func (v *Value) IsInt16Array() bool

IsInt16Array returns true if this value is an `Int16Array`.

func (*Value) IsInt32

func (v *Value) IsInt32() bool

IsInt32 returns true if this value is a 32-bit signed integer.

func (*Value) IsInt32Array

func (v *Value) IsInt32Array() bool

IsInt32Array returns true if this value is an `Int32Array`.

func (*Value) IsInt8Array

func (v *Value) IsInt8Array() bool

IsInt8Array returns true if this value is an `Int8Array`.

func (*Value) IsMap

func (v *Value) IsMap() bool

IsMap returns true if this value is a `Map`.

func (*Value) IsMapIterator

func (v *Value) IsMapIterator() bool

IsMapIterator returns true if this value is a `Map` Iterator.

func (*Value) IsModuleNamespaceObject

func (v *Value) IsModuleNamespaceObject() bool

IsModuleNamespaceObject returns true if the value is a `Module` Namespace `Object`.

func (*Value) IsName

func (v *Value) IsName() bool

IsName returns true if this value is a symbol or a string. This is equivalent to `typeof value === 'string' || typeof value === 'symbol'` in JS.

func (*Value) IsNativeError

func (v *Value) IsNativeError() bool

IsNativeError returns true if this value is a NativeError.

func (*Value) IsNull

func (v *Value) IsNull() bool

IsNull returns true if this value is the null value. See ECMA-262 4.3.11.

func (*Value) IsNullOrUndefined

func (v *Value) IsNullOrUndefined() bool

IsNullOrUndefined returns true if this value is either the null or the undefined value. See ECMA-262 4.3.11. and 4.3.12 This is equivalent to `value == null` in JS.

func (*Value) IsNumber

func (v *Value) IsNumber() bool

IsNumber returns true if this value is a number. This is equivalent to `typeof value === 'number'` in JS.

func (*Value) IsNumberObject

func (v *Value) IsNumberObject() bool

IsNumberObject returns true if this value is a `Number` object.

func (*Value) IsObject

func (v *Value) IsObject() bool

IsObject returns true if this value is an object.

func (*Value) IsPromise

func (v *Value) IsPromise() bool

IsPromise returns true if this value is a `Promise`.

func (*Value) IsProxy

func (v *Value) IsProxy() bool

IsProxy returns true if this value is a JavaScript `Proxy`.

func (*Value) IsRegExp

func (v *Value) IsRegExp() bool

IsRegExp returns true if this value is a `RegExp`.

func (*Value) IsSet

func (v *Value) IsSet() bool

IsSet returns true if this value is a `Set`.

func (*Value) IsSetIterator

func (v *Value) IsSetIterator() bool

IsSetIterator returns true if this value is a `Set` Iterator.

func (*Value) IsSharedArrayBuffer

func (v *Value) IsSharedArrayBuffer() bool

IsSharedArrayBuffer returns true if this value is a `SharedArrayBuffer`.

func (*Value) IsString

func (v *Value) IsString() bool

IsString returns true if this value is an instance of the String type. See ECMA-262 8.4. This is equivalent to `typeof value === 'string'` in JS.

func (*Value) IsStringObject

func (v *Value) IsStringObject() bool

IsStringObject returns true if this value is a `String` object.

func (*Value) IsSymbol

func (v *Value) IsSymbol() bool

IsSymbol returns true if this value is a symbol. This is equivalent to `typeof value === 'symbol'` in JS.

func (*Value) IsSymbolObject

func (v *Value) IsSymbolObject() bool

IsSymbolObject returns true if this value is a `Symbol` object.

func (*Value) IsTrue

func (v *Value) IsTrue() bool

IsTrue returns true if this value is true. This is not the same as `BooleanValue()`. The latter performs a conversion to boolean, i.e. the result of `Boolean(value)` in JS, whereas this checks `value === true`.

func (*Value) IsTypedArray

func (v *Value) IsTypedArray() bool

IsTypedArray returns true if this value is one of TypedArrays.

func (*Value) IsUint16Array

func (v *Value) IsUint16Array() bool

IsUint16Array returns true if this value is an `Uint16Array`.

func (*Value) IsUint32

func (v *Value) IsUint32() bool

IsUint32 returns true if this value is a 32-bit unsigned integer.

func (*Value) IsUint32Array

func (v *Value) IsUint32Array() bool

IsUint32Array returns true if this value is an `Uint32Array`.

func (*Value) IsUint8Array

func (v *Value) IsUint8Array() bool

IsUint8Array returns true if this value is an `Uint8Array`.

func (*Value) IsUint8ClampedArray

func (v *Value) IsUint8ClampedArray() bool

IsUint8ClampedArray returns true if this value is an `Uint8ClampedArray`.

func (*Value) IsUndefined

func (v *Value) IsUndefined() bool

IsUndefined returns true if this value is the undefined value. See ECMA-262 4.3.10.

func (*Value) IsWasmModuleObject

func (v *Value) IsWasmModuleObject() bool

IsWasmModuleObject returns true if this value is a `WasmModuleObject`.

func (*Value) IsWeakMap

func (v *Value) IsWeakMap() bool

IsWeakMap returns true if this value is a `WeakMap`.

func (*Value) IsWeakSet

func (v *Value) IsWeakSet() bool

IsWeakSet returns true if this value is a `WeakSet`.

func (*Value) MarshalJSON

func (v *Value) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*Value) Number

func (v *Value) Number() float64

Number perform the equivalent of `Number(value)` in JS.

func (*Value) Object

func (v *Value) Object() *Object

Object perform the equivalent of Object(value) in JS. To just cast this value as an Object use AsObject() instead.

func (*Value) String

func (v *Value) String() string

String perform the equivalent of `String(value)` in JS. Primitive values are returned as-is, objects will return `[object Object]` and functions will print their definition.

func (*Value) Uint32

func (v *Value) Uint32() uint32

Uint32 perform the equivalent of `Number(value)` in JS and convert the result to an unsigned 32-bit integer by performing the steps in https://tc39.es/ecma262/#sec-touint32.

type Valuer

type Valuer interface {
	// contains filtered or unexported methods
}

Valuer is an interface that reperesents anything that extends from a Value eg. Object, Array, Date etc

Directories

Path Synopsis
deps
darwin_x86_64
Package darwin_x86_64 is required to provide support for vendoring modules DO NOT REMOVE
Package darwin_x86_64 is required to provide support for vendoring modules DO NOT REMOVE
include
Package include is required to provide support for vendoring modules DO NOT REMOVE
Package include is required to provide support for vendoring modules DO NOT REMOVE
include/cppgc
Package cppgc is required to provide support for vendoring modules DO NOT REMOVE
Package cppgc is required to provide support for vendoring modules DO NOT REMOVE
include/libplatform
Package libplatform is required to provide support for vendoring modules DO NOT REMOVE
Package libplatform is required to provide support for vendoring modules DO NOT REMOVE
linux_x86_64
Package linux_x86_64 is required to provide support for vendoring modules DO NOT REMOVE
Package linux_x86_64 is required to provide support for vendoring modules DO NOT REMOVE
windows_x86_64
Package windows_x86_64 is required to provide support for vendoring modules DO NOT REMOVE
Package windows_x86_64 is required to provide support for vendoring modules DO NOT REMOVE

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to