goya

package module
v0.0.0-...-ac25dc5 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 58 Imported by: 1 module, 0 packages

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

README ¶

goya — Native TypeScript interpreter in Go

goya is a TypeScript-only interpreter in Go, derived from Goja. Its Go module is github.com/totoer/goya. Parsing, type checking, compilation and execution run inside the Go process with CGO_ENABLED=0. Runtime operation requires no Node.js, external tsc, child process, network connection or compiler download. Go 1.27 or newer is required.

The pinned language version is TypeScript 7.0.2, with an ES2025 standard environment. The checked compiler, runtime and embedding compatibility gates have passed. Optional proposal libraries have separate availability; Temporal from esnext is checked but cannot execute. See the compatibility inventory and verification record. This is a breaking replacement of the former JavaScript API.

JavaScript input and the former JavaScript compilation API are not retained. The execution profile has no built-in eval or function construction from strings. Only the Go application compiles sources. import() selects prepared modules; it never loads or compiles a new source during execution.

Embed a typed Go API

Register an API once to provide both its TypeScript contract and implementation:

import (
    "context"

    "github.com/totoer/goya"
)

ctx := context.Background()
registry := goya.NewRegistry()
if err := registry.Register("add", func(a, b float64) float64 {
    return a + b
}); err != nil {
    return err
}
environment, err := registry.Freeze(ctx)
if err != nil { return err }

project := goya.Project{Files: map[string]string{
    "/main.ts": `const answer: number = add(20, 22); answer;`,
}}
program, diagnostics, err := goya.Compile(ctx, project, environment, nil)
if err != nil { return err }
if program == nil { return &goya.CompilationError{Diagnostics: diagnostics} }

runtime := goya.New()
if err := environment.Bind(runtime); err != nil { return err }
value, err := runtime.RunProgram(program)
// value.ToInteger() == 42

Check(ctx, project, environment, options) exposes the same type analysis without creating a VM or calling Go implementations. Compile always checks. Syntax, type, declaration, configuration or backend errors produce diagnostics and no Program. Before execution, RunProgram verifies the required host schemas; missing or incompatible bindings reject startup before user initializers run.

RunString and RunScript also check TypeScript, using the bound Environment. MustCompile takes the same arguments as Compile. The old Compile signature, Parse, CompileAST and SetParserOptions APIs have been removed. See the embedding and migration guide for reflection, explicit adapters, numeric conversion policies and diagnostics.

Embedded language service

lsp.NewSession provides editor operations directly over a virtual Project and frozen Environment. lsp.Serve exposes the same core through LSP on streams supplied by the application, for VS Code, Neovim and other clients. The pure-Go service handles incomplete TS/TSX without running the VM or an external tsserver; the host owns applying edits and reporting subsequent document changes.

Editor compatibility is verified against typescript-language-server 6.0.2 for the supported TypeScript/TSX profile. See the SDK and LSP guide, direct session example, stream example, and validation record.

Projects and external capabilities

Project paths are virtual identifiers. Supply TS/TSX files, declarations and package metadata through Project.Files or an application SourceResolver. The engine never searches the operating system filesystem for a module. Checked AST lowers directly to VM operations, without generated JavaScript text or a second JavaScript parser.

Static and dynamic imports, live bindings, module cycles, top-level await, CommonJS interop, deferred imports and explicit JSON modules use the internal linker. Supply extra computed-import targets through Project.ModuleRoots; static and literal dynamic dependencies are included automatically. Registered host modules share the typed binding contract. A Program can be reused across compatible runtimes; each runtime owns its module state.

The default environment provides language intrinsics and no DOM, Node, console, process, global require, filesystem, networking, load/readFile or timers. External capabilities come from the Go application's registry. A JSX factory/runtime or metadata hook is also supplied explicitly. See language options. The runtime guide covers ownership, promise jobs, interruption and source-level exceptions.

CLI

CGO_ENABLED=0 go build -o /tmp/goya-ts ./goya
printf 'const answer: number = 42; answer;\n' | /tmp/goya-ts -check -
printf 'const answer: number = 42; answer;\n' | /tmp/goya-ts -
/tmp/goya-ts -check -project-root ./project ./project/main.ts
/tmp/goya-ts -project-root ./project ./project/main.ts

For a file entry point, the Go CLI snapshots its containing directory, or the explicit -project-root, into a virtual source catalog. It reads TypeScript and JSON files, skips hidden subdirectories and symlinks, and exposes no file API to scripts. Imports cannot leave the supplied catalog. Stdin is a single virtual /stdin.ts. Checking errors print structured source locations and exit nonzero. The CLI runs without implicit external registrations. A pending module promise requires an application event loop and is reported as an error by this CLI.

Runnable embedding examples:

CGO_ENABLED=0 go run ./examples/typescript-check
CGO_ENABLED=0 go run ./examples/typescript-host
CGO_ENABLED=0 go run ./examples/typescript-language
CGO_ENABLED=0 go run ./examples/typescript-modules
CGO_ENABLED=0 go run ./examples/typescript-lifecycle

Development and provenance

CGO_ENABLED=0 go test ./...
CGO_ENABLED=0 go run ./internal/tsfrontend/cmd/inventory -check

The backend guide describes the checked-analysis boundary, IR, module runtime and conformance fixtures. Historical VM tests retain test-only helpers for original operation regressions; those helpers are absent from production builds.

The official TypeScript Go sources, declarations and generated assets are pinned with release provenance and checksums in manifest.json. Import/update instructions and license notices are in the frontend guide. The Goja base is MIT licensed; vendored TypeScript code retains its Apache 2.0 license and upstream notices. Intl data retains its Unicode V3 license, with CLDR provenance and generation instructions. Embedded IANA timezone data retains the distribution notice and Apache license. Unicode 17 segmentation/category data retains its Unicode V3 license; pure-Go uax29 retains its MIT license. Other Go dependencies and their versions are recorded in go.mod and go.sum.

Dependency license texts and their checksums are retained in the third-party notices.

Documentation ¶

Overview ¶

Promise/iterator algorithms adapted from the pinned TypeScript helpers. See internal/tsfrontend/LICENSE.typescript (Apache-2.0).

Module helper algorithms adapted from the pinned TypeScript helpers. See internal/tsfrontend/LICENSE.typescript (Apache-2.0).

Resource helper algorithms adapted from the pinned TypeScript helpers. See internal/tsfrontend/LICENSE.typescript (Apache-2.0).

Decorator algorithms adapted from the pinned Microsoft TypeScript helpers. See internal/tsfrontend/LICENSE.typescript (Apache-2.0).

Index ¶

Examples ¶

Constants ¶

This section is empty.

Variables ¶

View Source
var (
	SymAsyncIterator      = newSymbol(asciiString("Symbol.asyncIterator"))
	SymAsyncDispose       = newSymbol(asciiString("Symbol.asyncDispose"))
	SymDispose            = newSymbol(asciiString("Symbol.dispose"))
	SymMetadata           = newSymbol(asciiString("Symbol.metadata"))
	SymHasInstance        = newSymbol(asciiString("Symbol.hasInstance"))
	SymIsConcatSpreadable = newSymbol(asciiString("Symbol.isConcatSpreadable"))
	SymIterator           = newSymbol(asciiString("Symbol.iterator"))
	SymMatch              = newSymbol(asciiString("Symbol.match"))
	SymMatchAll           = newSymbol(asciiString("Symbol.matchAll"))
	SymReplace            = newSymbol(asciiString("Symbol.replace"))
	SymSearch             = newSymbol(asciiString("Symbol.search"))
	SymSpecies            = newSymbol(asciiString("Symbol.species"))
	SymSplit              = newSymbol(asciiString("Symbol.split"))
	SymToPrimitive        = newSymbol(asciiString("Symbol.toPrimitive"))
	SymToStringTag        = newSymbol(asciiString("Symbol.toStringTag"))
	SymUnscopables        = newSymbol(asciiString("Symbol.unscopables"))
)
View Source
var (
	InvalidRuneError = errors.New("invalid rune")
)

Functions ¶

func Compile ¶

func Compile(ctx stdcontext.Context, project Project, environment *Environment, options CompileOptions) (*Program, []Diagnostic, error)

Compile checks the captured TypeScript project and lowers it directly into VM operations. Any frontend or backend error returns no Program. This is the developing TypeScript path; its remaining language/module support is tracked by the compatibility matrix.

func CompileProject ¶

func CompileProject(ctx stdcontext.Context, project Project, environment *Environment, options CompileOptions) (*Program, []Diagnostic, error)

CompileProject is an alias for Compile.

func HasTypeErrors ¶

func HasTypeErrors(diagnostics []Diagnostic) bool

HasTypeErrors reports whether a diagnostic list contains any error severity.

func IsBigInt ¶

func IsBigInt(v Value) bool

func IsInfinity ¶

func IsInfinity(v Value) bool

IsInfinity returns true if the supplied is (+/-)Infinity

func IsNaN ¶

func IsNaN(v Value) bool

IsNaN returns true if the supplied value is NaN.

func IsNull ¶

func IsNull(v Value) bool

IsNull returns true if the supplied Value is null.

func IsNumber ¶

func IsNumber(v Value) bool

func IsString ¶

func IsString(v Value) bool

func IsUndefined ¶

func IsUndefined(v Value) bool

IsUndefined returns true if the supplied Value is undefined. Note, it checks against the real undefined, not against the global object's 'undefined' property.

func SetCompilationCacheLimits ¶

func SetCompilationCacheLimits(entries, maxSourceBytes int)

SetCompilationCacheLimits clears and configures bounded analysis retention. Defaults are two analyses and 16 MiB of captured sources. Either zero disables retention. Resolver snapshots and binding compatibility are checked each time.

func StartProfile ¶

func StartProfile(w io.Writer) error

StartProfile enables execution time profiling for all Runtimes within the current process. This works similar to pprof.StartCPUProfile and produces the same format which can be consumed by `go tool pprof`. There are, however, a few notable differences. Firstly, it's not a CPU profile, rather "execution time" profile. It measures the time the VM spends executing an instruction. If this instruction happens to be a call to a blocking Go function, the waiting time will be measured. Secondly, the 'cpu' sample isn't simply `count*period`, it's the time interval between when sampling was requested and when the instruction has finished. If a VM is still executing the same instruction when the time comes for the next sample, the sampling is skipped (i.e. `count` doesn't grow).

If there are multiple functions with the same name, their names get a '.N' suffix, where N is a unique number, because otherwise the graph view merges them together (even if they are in different mappings). This includes "<anonymous>" functions.

The sampling period is set to 10ms.

It returns an error if profiling is already active.

func StopProfile ¶

func StopProfile()

StopProfile stops the current profile initiated by StartProfile, if any.

func TypeScriptVersion ¶

func TypeScriptVersion() string

TypeScriptVersion reports the exact pinned TypeScript version. The default execution profile uses ES2025 standard declarations without external APIs.

Types ¶

type ArrayBuffer ¶

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

ArrayBuffer is a Go wrapper around ECMAScript ArrayBuffer. Calling Runtime.ToValue() on it returns the underlying ArrayBuffer. Calling Export() on an ECMAScript ArrayBuffer returns a wrapper. Use Runtime.NewArrayBuffer([]byte) to create one.

func (ArrayBuffer) Bytes ¶

func (a ArrayBuffer) Bytes() []byte

Bytes returns the underlying []byte for this ArrayBuffer. For detached ArrayBuffers returns nil.

func (ArrayBuffer) Detach ¶

func (a ArrayBuffer) Detach() bool

Detach the ArrayBuffer. After this, the underlying []byte becomes unreferenced and any attempt to use this ArrayBuffer results in a TypeError. Returns false if it was already detached, true otherwise. Note, this method may only be called from the goroutine that 'owns' the Runtime, it may not be called concurrently.

func (ArrayBuffer) Detached ¶

func (a ArrayBuffer) Detached() bool

Detached returns true if the ArrayBuffer is detached.

type AsyncContextTracker ¶

type AsyncContextTracker interface {
	Grab() (trackingObject interface{})
	Resumed(trackingObject interface{})
	Exited()
}

AsyncContextTracker is a handler that allows to track an async execution context to ensure it remains consistent across all callback invocations. Whenever a Promise reaction job is scheduled the Grab method is called. It is supposed to return the current context. The same context will be supplied to the Resumed method before the reaction job is executed. The Exited method is called after the reaction job is finished. This means that for each invocation of the Grab method there will be exactly one subsequent invocation of Resumed and then Exited methods (assuming the Promise is fulfilled or rejected). Also, the Resumed/Exited calls cannot be nested, so Exited can simply clear the current context instead of popping from a stack. Note, this works for both async functions and regular Promise.then()/Promise.catch() callbacks. See TestAsyncContextTracker for more insight.

To register it call Runtime.SetAsyncContextTracker().

type BindingCompatibilityError ¶

type BindingCompatibilityError struct{ Name, Reason string }

BindingCompatibilityError reports a failed startup check before instructions or user initializers execute. A compatible schema may use different Go values.

func (*BindingCompatibilityError) Error ¶

func (e *BindingCompatibilityError) Error() string

type Callable ¶

type Callable func(this Value, args ...Value) (Value, error)

Callable represents a JavaScript function that can be called from Go.

func AssertFunction ¶

func AssertFunction(v Value) (Callable, bool)

AssertFunction checks if the Value is a function and returns a Callable. Note, for classes this returns a callable and a 'true', however calling it will always result in a TypeError. For classes use AssertConstructor().

Example ¶
vm := New()
_, err := vm.runVMString(`
	function sum(a, b) {
		return a+b;
	}
	`)
if err != nil {
	panic(err)
}
sum, ok := AssertFunction(vm.Get("sum"))
if !ok {
	panic("Not a function")
}

res, err := sum(Undefined(), vm.ToValue(40), vm.ToValue(2))
if err != nil {
	panic(err)
}
fmt.Println(res)
Output:
42

type CompilationError ¶

type CompilationError struct{ Diagnostics []Diagnostic }

CompilationError is the Go error returned by convenience APIs when checking rejects a source. Compile and Check return the same diagnostics directly.

func (*CompilationError) Error ¶

func (e *CompilationError) Error() string

type CompileOptions ¶

type CompileOptions = tsfrontend.Options

CompileOptions contains compilerOptions settings for the pinned TypeScript version. Checking is strict by default and cannot be disabled.

type CompilerError ¶

type CompilerError struct {
	Message string
	File    *file.File
	Offset  int
}

type CompilerReferenceError ¶

type CompilerReferenceError struct {
	CompilerError
}

func (*CompilerReferenceError) Error ¶

func (e *CompilerReferenceError) Error() string

type CompilerSyntaxError ¶

type CompilerSyntaxError struct {
	CompilerError
}

func (*CompilerSyntaxError) Error ¶

func (e *CompilerSyntaxError) Error() string

type Constructor ¶

type Constructor func(newTarget *Object, args ...Value) (*Object, error)

Constructor is a type that can be used to call constructors. The first argument (newTarget) can be nil which sets it to the constructor function itself.

func AssertConstructor ¶

func AssertConstructor(v Value) (Constructor, bool)

AssertConstructor checks if the Value is a constructor and returns a Constructor.

Example ¶
vm := New()
res, err := vm.runVMString(`
		(class C {
			constructor(x) {
				this.x = x;
			}
		})
	`)
if err != nil {
	panic(err)
}
if ctor, ok := AssertConstructor(res); ok {
	obj, err := ctor(nil, vm.ToValue("Test"))
	if err != nil {
		panic(err)
	}
	fmt.Print(obj.Get("x"))
} else {
	panic("Not a constructor")
}
Output:
Test

type ConstructorCall ¶

type ConstructorCall struct {
	This      *Object
	Arguments []Value
	NewTarget *Object
}

func (ConstructorCall) Argument ¶

func (f ConstructorCall) Argument(idx int) Value

type Diagnostic ¶

type Diagnostic = tsfrontend.Diagnostic

Diagnostic describes a compiler error, warning, or related source location. TypeScript diagnostics retain their original integer code in the "typescript" namespace; integration diagnostics use the separate "goya" namespace.

func Check ¶

func Check(ctx stdcontext.Context, project Project, environment *Environment, options CompileOptions) ([]Diagnostic, error)

Check performs TypeScript analysis without creating a runtime or executing script or registered host functions. Error diagnostics are returned as data; err is reserved for failures such as cancellation. The returned source columns are one-based UTF-16 positions; offsets are UTF-8 byte offsets.

type DynamicArray ¶

type DynamicArray interface {
	// Len returns the current array length.
	Len() int
	// Get an item at index idx. Note that idx may be any integer, negative or beyond the current length.
	// The handler should return nil in such cases as the property is considering as not existing.
	// The GetBinding flow which fuses HasProperty and Get treats such properties as missing and walks the
	// prototype chain instead of calling Get.
	Get(idx int) Value
	// Set an item at index idx. Note that idx may be any integer, negative or beyond the current length.
	// The expected behaviour when it's beyond length is that the array's length is increased to accommodate
	// the item. All elements in the 'new' section of the array should be zeroed.
	Set(idx int, val Value) bool
	// SetLen is called when the array's 'length' property is changed. If the length is increased all elements in the
	// 'new' section of the array should be zeroed.
	SetLen(int) bool
}

DynamicArray is an interface representing a handler for a dynamic array Object. Such an object can be created using the Runtime.NewDynamicArray() method.

Any integer property key or a string property key that can be parsed into an int value (including negative ones) is treated as an index and passed to the trap methods of the DynamicArray. Note this is different from the regular ECMAScript arrays which only support positive indexes up to 2^32-1.

DynamicArray cannot be sparse, i.e. hasOwnProperty(num) will return true for num >= 0 && num < Len(). Deleting such a property is equivalent to setting it to undefined. Note that this creates a slight peculiarity because hasOwnProperty() will still return true, even after deletion.

Note that Runtime.ToValue() does not have any special treatment for DynamicArray. The only way to create a dynamic array is by using the Runtime.NewDynamicArray() method. This is done deliberately to avoid silent code breaks when this interface changes.

type DynamicObject ¶

type DynamicObject interface {
	// Get a property value for the key. Must return nil if the property does not exist.
	// Note that this handler is also used for the GetBinding flow instead of 2 separate calls to Has and Get.
	Get(key string) Value
	// Set a property value for the key. Return true if success, false otherwise.
	Set(key string, val Value) bool
	// Has should return true if and only if the property exists.
	Has(key string) bool
	// Delete the property for the key. Returns true on success (note, that includes missing property).
	Delete(key string) bool
	// Keys returns a list of all existing property keys. There are no checks for duplicates or to make sure
	// that the order conforms to https://262.ecma-international.org/#sec-ordinaryownpropertykeys
	Keys() []string
}

DynamicObject is an interface representing a handler for a dynamic Object. Such an object can be created using the Runtime.NewDynamicObject() method.

Note that Runtime.ToValue() does not have any special treatment for DynamicObject. The only way to create a dynamic object is by using the Runtime.NewDynamicObject() method. This is done deliberately to avoid silent code breaks when this interface changes.

type Environment ¶

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

Environment is a frozen set of host type declarations and binding contracts. A nil or zero Environment exposes no host API. Registry construction supplies declarations and bindings together; applications do not mutate this value.

func (*Environment) Bind ¶

func (e *Environment) Bind(r *Runtime) error

Bind installs the frozen implementations into a runtime. Type checking does not call this method. Module values are kept separate from global bindings.

func (*Environment) SchemaID ¶

func (e *Environment) SchemaID() string

func (*Environment) TypeDeclarations ¶

func (e *Environment) TypeDeclarations() map[string]string

type Exception ¶

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

func (*Exception) Error ¶

func (e *Exception) Error() string

func (*Exception) Stack ¶

func (e *Exception) Stack() []StackFrame

func (*Exception) String ¶

func (e *Exception) String() string

func (*Exception) Unwrap ¶

func (e *Exception) Unwrap() error

func (*Exception) Value ¶

func (e *Exception) Value() Value

type FieldNameMapper ¶

type FieldNameMapper interface {
	// FieldName returns a JavaScript name for the given struct field in the given type.
	// If this method returns "" the field becomes hidden.
	FieldName(t reflect.Type, f reflect.StructField) string

	// MethodName returns a JavaScript name for the given method in the given type.
	// If this method returns "" the method becomes hidden.
	MethodName(t reflect.Type, m reflect.Method) string
}

FieldNameMapper provides custom mapping between Go and JavaScript property names.

func TagFieldNameMapper ¶

func TagFieldNameMapper(tagName string, uncapMethods bool) FieldNameMapper

TagFieldNameMapper returns a FieldNameMapper that uses the given tagName for struct fields and optionally uncapitalises (making the first letter lower case) method names. The common tag value syntax is supported (name[,options]), however options are ignored. Setting name to anything other than a valid ECMAScript identifier makes the field hidden.

Example ¶
vm := New()
vm.SetFieldNameMapper(TagFieldNameMapper("json", true))
type S struct {
	Field int `json:"field"`
}
vm.Set("s", S{Field: 42})
res, _ := vm.runVMString(`s.field`)
fmt.Println(res.Export())
Output:
42

func UncapFieldNameMapper ¶

func UncapFieldNameMapper() FieldNameMapper

UncapFieldNameMapper returns a FieldNameMapper that uncapitalises struct field and method names making the first letter lower case.

Example ¶
vm := New()
s := testGoReflectMethod_O{
	Test: "passed",
}
vm.SetFieldNameMapper(UncapFieldNameMapper())
vm.Set("s", s)
res, _ := vm.runVMString(`s.test + " and " + s.method("passed too")`)
fmt.Println(res.Export())
Output:
passed and passed too

type Flag ¶

type Flag int
const (
	FLAG_NOT_SET Flag = iota
	FLAG_FALSE
	FLAG_TRUE
)

func ToFlag ¶

func ToFlag(b bool) Flag

func (Flag) Bool ¶

func (f Flag) Bool() bool

type Float32Conversion ¶

type Float32Conversion string
const (
	Float32Exact Float32Conversion = "exact"
	Float32Round Float32Conversion = "round-to-nearest"
)

type FunctionCall ¶

type FunctionCall struct {
	This      Value
	Arguments []Value
}

func (FunctionCall) Argument ¶

func (f FunctionCall) Argument(idx int) Value

type HostAdapter ¶

type HostAdapter interface {
	SchemaID() string
	Bind(*Runtime, any) (Value, error)
}

HostAdapter supplies a runtime value for an explicit TypeScript contract. Bind is never called by Check or Registry.Freeze. Implementations must enforce their declared argument, property and result conversions at runtime boundaries. SchemaID identifies those conversion rules and must remain stable after freeze.

type HostAdapterFuncs ¶

type HostAdapterFuncs struct {
	ID        string
	BindValue func(*Runtime, any) (Value, error)
}

HostAdapterFuncs is a function-based explicit adapter. ID describes the contract's conversion rules, including all runtime argument/result checks.

func (HostAdapterFuncs) Bind ¶

func (a HostAdapterFuncs) Bind(r *Runtime, value any) (Value, error)

func (HostAdapterFuncs) SchemaID ¶

func (a HostAdapterFuncs) SchemaID() string

type HostBinding ¶

type HostBinding struct {
	Value      any
	TypeScript string
	Adapter    HostAdapter
	// Mutable enables writes through pointer views. Copies remain independent.
	Mutable bool
	Numbers NumericPolicy
}

HostBinding specifies the explicit contract for a value reflection cannot describe. Register and RegisterModule also accept ordinary Go values directly.

type IntegerRepresentation ¶

type IntegerRepresentation string
const (
	IntegerBigInt     IntegerRepresentation = "bigint"
	IntegerSafeNumber IntegerRepresentation = "safe-number"
)

type InterruptedError ¶

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

func (*InterruptedError) Error ¶

func (e *InterruptedError) Error() string

func (*InterruptedError) String ¶

func (e *InterruptedError) String() string

func (*InterruptedError) Unwrap ¶

func (e *InterruptedError) Unwrap() error

func (*InterruptedError) Value ¶

func (e *InterruptedError) Value() interface{}

type JsonEncodable ¶

type JsonEncodable interface {
	JsonEncodable() interface{}
}

JsonEncodable allows custom JSON encoding by JSON.stringify() Note that if the returned value itself also implements JsonEncodable, it won't have any effect.

type Now ¶

type Now func() time.Time

type NumericPolicy ¶

type NumericPolicy struct {
	Integers IntegerRepresentation
	IntBits  int
	Float32  Float32Conversion
}

NumericPolicy makes potentially lossy Go representations explicit. IntBits fixes the contract of int, uint and uintptr to 32 or 64 bits; registration rejects a contract wider than the current Go target can represent.

type Object ¶

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

func NewSharedDynamicArray ¶

func NewSharedDynamicArray(a DynamicArray) *Object

NewSharedDynamicArray is similar to Runtime.NewDynamicArray but the resulting Object can be shared across multiple Runtimes. The Object's prototype will be null. If you need to run Array's methods on it, use Array.prototype.[...].call(a, ...). The provided DynamicArray must be goroutine-safe.

func NewSharedDynamicObject ¶

func NewSharedDynamicObject(d DynamicObject) *Object

NewSharedDynamicObject is similar to Runtime.NewDynamicObject but the resulting Object can be shared across multiple Runtimes. The Object's prototype will be null. The provided DynamicObject must be goroutine-safe.

func (*Object) ClassName ¶

func (o *Object) ClassName() string

ClassName returns the class name

func (*Object) DefineAccessorProperty ¶

func (o *Object) DefineAccessorProperty(name string, getter, setter Value, configurable, enumerable Flag) error

DefineAccessorProperty is a Go equivalent of Object.defineProperty(o, name, {get: getter, set: setter, configurable: configurable, enumerable: enumerable})

func (*Object) DefineAccessorPropertySymbol ¶

func (o *Object) DefineAccessorPropertySymbol(name *Symbol, getter, setter Value, configurable, enumerable Flag) error

DefineAccessorPropertySymbol is a Go equivalent of Object.defineProperty(o, name, {get: getter, set: setter, configurable: configurable, enumerable: enumerable})

func (*Object) DefineDataProperty ¶

func (o *Object) DefineDataProperty(name string, value Value, writable, configurable, enumerable Flag) error

DefineDataProperty is a Go equivalent of Object.defineProperty(o, name, {value: value, writable: writable, configurable: configurable, enumerable: enumerable})

func (*Object) DefineDataPropertySymbol ¶

func (o *Object) DefineDataPropertySymbol(name *Symbol, value Value, writable, configurable, enumerable Flag) error

DefineDataPropertySymbol is a Go equivalent of Object.defineProperty(o, name, {value: value, writable: writable, configurable: configurable, enumerable: enumerable})

func (*Object) Delete ¶

func (o *Object) Delete(name string) error
Example ¶
vm := New()
obj := vm.NewObject()
_ = obj.Set("test", true)
before := obj.Get("test")
_ = obj.Delete("test")
after := obj.Get("test")
fmt.Printf("before: %v, after: %v", before, after)
Output:
before: true, after: <nil>

func (*Object) DeleteSymbol ¶

func (o *Object) DeleteSymbol(name *Symbol) error

func (*Object) Equals ¶

func (o *Object) Equals(other Value) bool

func (*Object) Export ¶

func (o *Object) Export() interface{}

Export the Object to a plain Go type. If the Object is a wrapped Go value (created using ToValue()) returns the original value.

If the Object is a class function, returns func(ConstructorCall) *Object. See the note about exceptions below.

If the Object is a function, returns func(FunctionCall) Value. Note that exceptions thrown inside the function result in panics, which can also leave the Runtime in an unusable state. Therefore, these values should only be used inside another ES function implemented in Go. For calling a function from Go, use AssertFunction() or Runtime.ExportTo() as described in the README.

For a Map, returns the list of entries as [][2]interface{}.

For a Set, returns the list of elements as []interface{}.

For a Proxy, returns Proxy.

For a Promise, returns Promise.

For a DynamicObject or a DynamicArray, returns the underlying handler.

For typed arrays it returns a slice of the corresponding type backed by the original data (i.e. it does not copy).

For an untyped array, returns its items exported into a newly created []interface{}.

In all other cases returns own enumerable non-symbol properties as map[string]interface{}.

This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these.

Example (Map) ¶
vm := New()
m, err := vm.runVMString(`
	new Map([[1, true], [2, false]]);
	`)
if err != nil {
	panic(err)
}
exp := m.Export()
fmt.Printf("%T, %v\n", exp, exp)
Output:
[][2]interface {}, [[1 true] [2 false]]

func (*Object) ExportType ¶

func (o *Object) ExportType() reflect.Type

ExportType returns the type of the value that is returned by Export().

func (*Object) Get ¶

func (o *Object) Get(name string) Value

Get an object's property by name. This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these.

func (*Object) GetIdx ¶

func (o *Object) GetIdx(idx int64) Value

GetIdx returns an object's property by a numeric key. This is mostly useful if the object is an Array to avoid converting the index into a string. This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these.

func (*Object) GetOwnPropertyNames ¶

func (o *Object) GetOwnPropertyNames() (keys []string)

GetOwnPropertyNames returns a list of all own string properties of the Object, similar to Object.getOwnPropertyNames() This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these.

Example ¶
vm := New()
obj := vm.NewObject()
obj.DefineDataProperty("test", vm.ToValue(true), FLAG_TRUE, FLAG_TRUE, FLAG_FALSE) // define a non-enumerable property that Keys() would not return
fmt.Print(obj.GetOwnPropertyNames())
Output:
[test]

func (*Object) GetSymbol ¶

func (o *Object) GetSymbol(sym *Symbol) Value

GetSymbol returns the value of a symbol property. Use one of the Sym* values for well-known symbols (such as SymIterator, SymToStringTag, etc...). This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these.

func (*Object) Keys ¶

func (o *Object) Keys() (keys []string)

Keys returns a list of Object's enumerable keys. This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these.

func (*Object) MarshalJSON ¶

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

MarshalJSON returns JSON representation of the Object. It is equivalent to JSON.stringify(o). Note, this implements json.Marshaler so that json.Marshal() can be used without the need to Export().

func (*Object) Prototype ¶

func (o *Object) Prototype() *Object

Prototype returns the Object's prototype, same as Object.getPrototypeOf(). If the prototype is null returns nil.

func (*Object) SameAs ¶

func (o *Object) SameAs(other Value) bool

func (*Object) Set ¶

func (o *Object) Set(name string, value interface{}) error

func (*Object) SetPrototype ¶

func (o *Object) SetPrototype(proto *Object) error

SetPrototype sets the Object's prototype, same as Object.setPrototypeOf(). Setting proto to nil is an equivalent of Object.setPrototypeOf(null).

func (*Object) SetSymbol ¶

func (o *Object) SetSymbol(name *Symbol, value interface{}) error
Example ¶
type IterResult struct {
	Done  bool
	Value Value
}

vm := New()
vm.SetFieldNameMapper(UncapFieldNameMapper()) // to use IterResult

o := vm.NewObject()
o.SetSymbol(SymIterator, func() *Object {
	count := 0
	iter := vm.NewObject()
	iter.Set("next", func() IterResult {
		if count < 10 {
			count++
			return IterResult{
				Value: vm.ToValue(count),
			}
		}
		return IterResult{
			Done: true,
		}
	})
	return iter
})
vm.Set("o", o)

res, err := vm.runVMString(`
	var acc = "";
	for (var v of o) {
		acc += v + " ";
	}
	acc;
	`)
if err != nil {
	panic(err)
}
fmt.Println(res)
Output:
1 2 3 4 5 6 7 8 9 10

func (*Object) StrictEquals ¶

func (o *Object) StrictEquals(other Value) bool

func (*Object) String ¶

func (o *Object) String() string

func (*Object) Symbols ¶

func (o *Object) Symbols() []*Symbol

Symbols returns a list of Object's enumerable symbol properties. This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these.

func (*Object) ToBoolean ¶

func (o *Object) ToBoolean() bool

func (*Object) ToFloat ¶

func (o *Object) ToFloat() float64

func (*Object) ToInteger ¶

func (o *Object) ToInteger() int64

func (*Object) ToNumber ¶

func (o *Object) ToNumber() Value

func (*Object) ToObject ¶

func (o *Object) ToObject(*Runtime) *Object

func (*Object) ToString ¶

func (o *Object) ToString() Value

func (*Object) UnmarshalJSON ¶

func (o *Object) UnmarshalJSON([]byte) error

UnmarshalJSON implements the json.Unmarshaler interface. It is added to compliment MarshalJSON, because some alternative JSON encoders refuse to use MarshalJSON unless UnmarshalJSON is also present. It is a no-op and always returns nil.

type Optional ¶

type Optional[T any] struct {
	Value   T
	Present bool
}

Optional distinguishes an omitted/undefined argument from a supplied Go zero value. Optional parameters must follow required parameters, before any rest. A supplied null remains present when T itself accepts null.

type Program ¶

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

Program is an internal, compiled representation of code which is produced by the Compile function. This representation is not linked to a runtime in any way and can be used concurrently. It is always preferable to use a Program over a string when running code as it skips the compilation step.

func MustCompile ¶

func MustCompile(ctx stdcontext.Context, project Project, environment *Environment, options CompileOptions) *Program

MustCompile is like Compile but panics if the code cannot be compiled.

func (*Program) Manifest ¶

func (p *Program) Manifest() ProgramManifest

type ProgramManifest ¶

type ProgramManifest struct {
	TypeScriptVersion string
	ProfileID         string
	AnalysisID        string
	EntryPoints       []string
	Sources           []ProgramSource
	HostBindings      []RequiredHostBinding
}

ProgramManifest describes the immutable compilation profile and the exact registered contracts required before execution. Values and Go addresses are deliberately absent. Each call returns detached slices.

type ProgramSource ¶

type ProgramSource struct{ ID, SHA256 string }

type Project ¶

type Project = tsfrontend.Project

Project is an in-memory TypeScript project. Names are virtual paths, not OS paths. Files and entry points are copied for each analysis. ConfigFile optionally selects a configuration from that catalog, including extends/references. Empty ConfigFile preserves entry-point selection without config discovery.

type Promise ¶

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

Promise is a Go wrapper around ECMAScript Promise. Calling Runtime.ToValue() on it returns the underlying Object. Calling Export() on a Promise Object returns a Promise.

Use Runtime.NewPromise() to create one. Calling Runtime.ToValue() on a zero object or nil returns null Value.

WARNING: Instances of Promise are not goroutine-safe. See Runtime.NewPromise() for more details.

func (*Promise) Result ¶

func (p *Promise) Result() Value

func (*Promise) State ¶

func (p *Promise) State() PromiseState

type PromiseRejectionOperation ¶

type PromiseRejectionOperation int
const (
	PromiseRejectionReject PromiseRejectionOperation = iota
	PromiseRejectionHandle
)

type PromiseRejectionTracker ¶

type PromiseRejectionTracker func(p *Promise, operation PromiseRejectionOperation)

type PromiseState ¶

type PromiseState int
const (
	PromiseStatePending PromiseState = iota
	PromiseStateFulfilled
	PromiseStateRejected
)

type PropertyDescriptor ¶

type PropertyDescriptor struct {
	Value Value

	Writable, Configurable, Enumerable Flag

	Getter, Setter Value
	// contains filtered or unexported fields
}

func (*PropertyDescriptor) Empty ¶

func (p *PropertyDescriptor) Empty() bool

func (*PropertyDescriptor) IsAccessor ¶

func (p *PropertyDescriptor) IsAccessor() bool

func (*PropertyDescriptor) IsData ¶

func (p *PropertyDescriptor) IsData() bool

func (*PropertyDescriptor) IsGeneric ¶

func (p *PropertyDescriptor) IsGeneric() bool

type Proxy ¶

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

Proxy is a Go wrapper around ECMAScript Proxy. Calling Runtime.ToValue() on it returns the underlying Proxy. Calling Export() on an ECMAScript Proxy returns a wrapper. Use Runtime.NewProxy() to create one.

func (Proxy) Handler ¶

func (p Proxy) Handler() *Object

func (Proxy) Revoke ¶

func (p Proxy) Revoke()

func (Proxy) Target ¶

func (p Proxy) Target() *Object

type ProxyTrapConfig ¶

type ProxyTrapConfig struct {
	// A trap for Object.getPrototypeOf, Reflect.getPrototypeOf, __proto__, Object.prototype.isPrototypeOf, instanceof
	GetPrototypeOf func(target *Object) (prototype *Object)

	// A trap for Object.setPrototypeOf, Reflect.setPrototypeOf
	SetPrototypeOf func(target *Object, prototype *Object) (success bool)

	// A trap for Object.isExtensible, Reflect.isExtensible
	IsExtensible func(target *Object) (success bool)

	// A trap for Object.preventExtensions, Reflect.preventExtensions
	PreventExtensions func(target *Object) (success bool)

	// A trap for Object.getOwnPropertyDescriptor, Reflect.getOwnPropertyDescriptor (string properties)
	GetOwnPropertyDescriptor func(target *Object, prop string) (propertyDescriptor PropertyDescriptor)

	// A trap for Object.getOwnPropertyDescriptor, Reflect.getOwnPropertyDescriptor (integer properties)
	GetOwnPropertyDescriptorIdx func(target *Object, prop int) (propertyDescriptor PropertyDescriptor)

	// A trap for Object.getOwnPropertyDescriptor, Reflect.getOwnPropertyDescriptor (Symbol properties)
	GetOwnPropertyDescriptorSym func(target *Object, prop *Symbol) (propertyDescriptor PropertyDescriptor)

	// A trap for Object.defineProperty, Reflect.defineProperty (string properties)
	DefineProperty func(target *Object, key string, propertyDescriptor PropertyDescriptor) (success bool)

	// A trap for Object.defineProperty, Reflect.defineProperty (integer properties)
	DefinePropertyIdx func(target *Object, key int, propertyDescriptor PropertyDescriptor) (success bool)

	// A trap for Object.defineProperty, Reflect.defineProperty (Symbol properties)
	DefinePropertySym func(target *Object, key *Symbol, propertyDescriptor PropertyDescriptor) (success bool)

	// A trap for the in operator, with operator, Reflect.has (string properties)
	Has func(target *Object, property string) (available bool)

	// A trap for the in operator, with operator, Reflect.has (integer properties)
	HasIdx func(target *Object, property int) (available bool)

	// A trap for the in operator, with operator, Reflect.has (Symbol properties)
	HasSym func(target *Object, property *Symbol) (available bool)

	// A trap for getting property values, Reflect.get (string properties)
	Get func(target *Object, property string, receiver Value) (value Value)

	// A combined has+get trap equivalent to calling the Has and Get traps separately (e.g. for
	// resolving bindings in a 'with' statement). It allows implementing the two steps in a single
	// Go call. Returning nil means the property does not exist; a property with the value
	// undefined must be returned as goya.Undefined() rather than nil. The same invariant checks
	// are applied to the result as to the separate Has and Get traps. If not set, the Has and Get
	// traps are used separately.
	HasAndGet func(target *Object, property string, receiver Value) (value Value)

	// A trap for getting property values, Reflect.get (integer properties)
	GetIdx func(target *Object, property int, receiver Value) (value Value)

	// A trap for getting property values, Reflect.get (Symbol properties)
	GetSym func(target *Object, property *Symbol, receiver Value) (value Value)

	// A trap for setting property values, Reflect.set (string properties)
	Set func(target *Object, property string, value Value, receiver Value) (success bool)

	// A trap for setting property values, Reflect.set (integer properties)
	SetIdx func(target *Object, property int, value Value, receiver Value) (success bool)

	// A trap for setting property values, Reflect.set (Symbol properties)
	SetSym func(target *Object, property *Symbol, value Value, receiver Value) (success bool)

	// A trap for the delete operator, Reflect.deleteProperty (string properties)
	DeleteProperty func(target *Object, property string) (success bool)

	// A trap for the delete operator, Reflect.deleteProperty (integer properties)
	DeletePropertyIdx func(target *Object, property int) (success bool)

	// A trap for the delete operator, Reflect.deleteProperty (Symbol properties)
	DeletePropertySym func(target *Object, property *Symbol) (success bool)

	// A trap for Object.getOwnPropertyNames, Object.getOwnPropertySymbols, Object.keys, Reflect.ownKeys
	OwnKeys func(target *Object) (object *Object)

	// A trap for a function call, Function.prototype.apply, Function.prototype.call, Reflect.apply
	Apply func(target *Object, this Value, argumentsList []Value) (value Value)

	// A trap for the new operator, Reflect.construct
	Construct func(target *Object, argumentsList []Value, newTarget *Object) (value *Object)
}

ProxyTrapConfig provides a simplified Go-friendly API for implementing Proxy traps. If an *Idx trap is defined it gets called for integer property keys, including negative ones. Note that this only includes string property keys that represent a canonical integer (i.e. "0", "123", but not "00", "01", " 1" or "-0"). For efficiency strings representing integers exceeding 2^53 are not checked to see if they are canonical, i.e. the *Idx traps will receive "9007199254740993" as well as "9007199254740994", even though the former is not a canonical representation in ECMAScript (Number("9007199254740993") === 9007199254740992). See https://262.ecma-international.org/#sec-canonicalnumericindexstring If an *Idx trap is not set, the corresponding string one is used.

type RandSource ¶

type RandSource func() float64

type Registry ¶

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

Registry builds a host API. Freeze copies its descriptors and declarations; later additions to the builder do not change previously frozen environments.

func NewRegistry ¶

func NewRegistry() *Registry

func (*Registry) DeclareTypes ¶

func (b *Registry) DeclareTypes(name, source string) error

DeclareTypes adds caller-owned declaration source needed by explicit host contracts. Definitions are checked when freezing and again in each project.

func (*Registry) Freeze ¶

func (b *Registry) Freeze(ctx stdcontext.Context, options ...CompileOptions) (*Environment, error)

func (*Registry) Register ¶

func (b *Registry) Register(name string, value any) error

func (*Registry) RegisterModule ¶

func (b *Registry) RegisterModule(specifier string, exports map[string]any) error

func (*Registry) SetFieldNameMapper ¶

func (b *Registry) SetFieldNameMapper(mapper FieldNameMapper)

SetFieldNameMapper selects the mapper captured by subsequent registrations. Existing descriptors and frozen environments retain their mapped names.

type RequiredHostBinding ¶

type RequiredHostBinding struct{ Module, Name, SchemaID string }

type ResolverFunc ¶

type ResolverFunc = tsfrontend.ResolverFunc

type Runtime ¶

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

func New ¶

func New() *Runtime

New creates a TypeScript runtime. Independent runtimes may execute a shared checked Program concurrently; script values belong to their creating runtime.

func (*Runtime) CaptureCallStack ¶

func (r *Runtime) CaptureCallStack(depth int, stack []StackFrame) []StackFrame

CaptureCallStack appends the current call stack frames to the stack slice (which may be nil) up to the specified depth. The most recent frame will be the first one. If depth <= 0 or more than the number of available frames, returns the entire stack. This method is not safe for concurrent use and should only be called by a Go function that is called from a running script.

func (*Runtime) ClearInterrupt ¶

func (r *Runtime) ClearInterrupt()

ClearInterrupt resets the interrupt flag. Typically this needs to be called before the runtime is made available for re-use if there is a chance it could have been interrupted with Interrupt(). Otherwise if Interrupt() was called when runtime was not running (e.g. if it had already finished) so that Interrupt() didn't actually trigger, an attempt to use the runtime will immediately cause an interruption. It is up to the user to ensure proper synchronisation so that ClearInterrupt() is only called when the runtime has finished and there is no chance of a concurrent Interrupt() call.

func (*Runtime) CreateObject ¶

func (r *Runtime) CreateObject(proto *Object) *Object

CreateObject creates an object with given prototype. Equivalent of Object.create(proto).

func (*Runtime) ExportTo ¶

func (r *Runtime) ExportTo(v Value, target interface{}) error

ExportTo converts a JavaScript value into the specified Go value. The second parameter must be a non-nil pointer. Returns error if conversion is not possible.

Notes on specific cases:

Empty interface ¶

Exporting to an interface{} results in a value of the same type as Value.Export() would produce.

Numeric types ¶

Exporting to numeric types uses the standard ECMAScript conversion operations, same as used when assigning values to non-clamped typed array items, e.g. https://262.ecma-international.org/#sec-toint32.

Functions ¶

Exporting to a 'func' creates a strictly typed 'gateway' into an ES function which can be called from Go. The arguments are converted into ES values using Runtime.ToValue(). If the func has no return values, the return value is ignored. If the func has exactly one return value, it is converted to the appropriate type using ExportTo(). If the last return value is 'error', exceptions are caught and returned as *Exception (instances of GoError are unwrapped, i.e. their 'value' is returned instead). In all other cases exceptions result in a panic. Any extra return values are zeroed.

'this' value will always be set to 'undefined'.

For a more low-level mechanism see AssertFunction().

Map types ¶

An ES Map can be exported into a Go map type. If any exported key value is non-hashable, the operation panics (as reflect.Value.SetMapIndex() would). Symbol.iterator is ignored.

Exporting an ES Set into a map type results in the map being populated with (element) -> (zero value) key/value pairs. If any value is non-hashable, the operation panics (as reflect.Value.SetMapIndex() would). Symbol.iterator is ignored.

Any other Object populates the map with own enumerable non-symbol properties.

Slice types ¶

Exporting an ES Set into a slice type results in its elements being exported.

Exporting any Object that implements the iterable protocol (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) into a slice type results in the slice being populated with the results of the iteration.

Array is treated as iterable (i.e. overwriting Symbol.iterator affects the result).

If an object has a 'length' property and is not a function it is treated as array-like. The resulting slice will contain obj[0], ... obj[length-1].

ArrayBuffer and ArrayBuffer-backed types (i.e. typed arrays and DataView) can be exported into []byte. The result is backed by the original data, no copy is performed.

For any other Object an error is returned.

Array types ¶

Anything that can be exported to a slice type can also be exported to an array type, as long as the lengths match. If they do not, an error is returned.

Proxy ¶

Proxy objects are treated the same way as if they were accessed from ES code in regard to their properties (such as 'length' or [Symbol.iterator]). This means exporting them to slice types works, however exporting a proxied Map into a map type does not produce its contents, because the Proxy is not recognised as a Map. Same applies to a proxied Set.

Example (ArrayLikeToSlice) ¶
vm := New()
v, err := vm.runVMString(`
	({
		length: 3,
		0: 1,
		1: 2,
		2: 3
	});
	`)
if err != nil {
	panic(err)
}

var arr []int
err = vm.ExportTo(v, &arr)
if err != nil {
	panic(err)
}

fmt.Println(arr)
Output:
[1 2 3]
Example (Func) ¶
const SCRIPT = `
	function f(param) {
		return +param + 2;
	}
	`

vm := New()
_, err := vm.runVMString(SCRIPT)
if err != nil {
	panic(err)
}

var fn func(string) string
err = vm.ExportTo(vm.Get("f"), &fn)
if err != nil {
	panic(err)
}

fmt.Println(fn("40")) // note, _this_ value in the function will be undefined.
Output:
42
Example (FuncThrow) ¶
const SCRIPT = `
	function f(param) {
		throw new Error("testing");
	}
	`

vm := New()
_, err := vm.runVMString(SCRIPT)
if err != nil {
	panic(err)
}

var fn func(string) (string, error)
err = vm.ExportTo(vm.Get("f"), &fn)
if err != nil {
	panic(err)
}
_, err = fn("")

fmt.Println(err)
Output:
Error: testing at f (<eval>:3:9(3))
Example (FuncVariadic) ¶
const SCRIPT = `
	function f(...args) {
		return args.join("#");
	}
	`
vm := New()
_, err := vm.runVMString(SCRIPT)
if err != nil {
	panic(err)
}

var fn func(args ...interface{}) string
err = vm.ExportTo(vm.Get("f"), &fn)
if err != nil {
	panic(err)
}
fmt.Println(fn("a", "b", 42))
Output:
a#b#42
Example (IterableToSlice) ¶
vm := New()
v, err := vm.runVMString(`
	function reverseIterator() {
	    const arr = this;
	    let idx = arr.length;
	    return {
			next: () => idx > 0 ? {value: arr[--idx]} : {done: true}
	    }
	}
	const arr = [1,2,3];
	arr[Symbol.iterator] = reverseIterator;
	arr;
	`)
if err != nil {
	panic(err)
}

var arr []int
err = vm.ExportTo(v, &arr)
if err != nil {
	panic(err)
}

fmt.Println(arr)
Output:
[3 2 1]
Example (MapToMap) ¶
vm := New()
m, err := vm.runVMString(`
	new Map([[1, true], [2, false]]);
	`)
if err != nil {
	panic(err)
}
exp := make(map[int]bool)
err = vm.ExportTo(m, &exp)
if err != nil {
	panic(err)
}
fmt.Println(exp)
Output:
map[1:true 2:false]
Example (MapToSlice) ¶
vm := New()
m, err := vm.runVMString(`
	new Map([[1, true], [2, false]]);
	`)
if err != nil {
	panic(err)
}
exp := make([][]interface{}, 0)
err = vm.ExportTo(m, &exp)
if err != nil {
	panic(err)
}
fmt.Println(exp)
Output:
[[1 true] [2 false]]
Example (MapToTypedSlice) ¶
vm := New()
m, err := vm.runVMString(`
	new Map([[1, true], [2, false]]);
	`)
if err != nil {
	panic(err)
}
exp := make([][2]interface{}, 0)
err = vm.ExportTo(m, &exp)
if err != nil {
	panic(err)
}
fmt.Println(exp)
Output:
[[1 true] [2 false]]
Example (SetToMap) ¶
vm := New()
s, err := vm.runVMString(`
	new Set([1, 2, 3])
	`)
if err != nil {
	panic(err)
}
m := make(map[int]struct{})
err = vm.ExportTo(s, &m)
if err != nil {
	panic(err)
}
fmt.Println(m)
Output:
map[1:{} 2:{} 3:{}]
Example (SetToSlice) ¶
vm := New()
s, err := vm.runVMString(`
	new Set([1, 2, 3])
	`)
if err != nil {
	panic(err)
}
var a []int
err = vm.ExportTo(s, &a)
if err != nil {
	panic(err)
}
fmt.Println(a)
Output:
[1 2 3]

func (*Runtime) ForOf ¶

func (r *Runtime) ForOf(iterable Value, step func(curValue Value) (continueIteration bool))

ForOf is a Go equivalent of for-of loop. The function panics if an exception is thrown at any point while iterating, including if the supplied value is not iterable (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol). When using outside of Runtime.Run (i.e. when calling directly from Go code, not from a JS function implemented in Go) it must be enclosed in Try. See the example.

Example ¶
r := New()
v, err := r.runVMString(`
		new Map().set("a", 1).set("b", 2);
	`)
if err != nil {
	panic(err)
}

var sb strings.Builder
ex := r.Try(func() {
	r.ForOf(v, func(v Value) bool {
		o := v.ToObject(r)
		key := o.Get("0")
		value := o.Get("1")

		sb.WriteString(key.String())
		sb.WriteString("=")
		sb.WriteString(value.String())
		sb.WriteString(",")

		return true
	})
})
if ex != nil {
	panic(ex)
}
fmt.Println(sb.String())
Output:
a=1,b=2,

func (*Runtime) Get ¶

func (r *Runtime) Get(name string) Value

Get the specified variable in the global context. Equivalent to dereferencing a variable by name in non-strict mode. If variable is not defined returns nil. Note, this is not the same as GlobalObject().Get(name), because if a global lexical binding (let or const) exists, it is used instead. This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these.

func (*Runtime) GlobalObject ¶

func (r *Runtime) GlobalObject() *Object

GlobalObject returns the global object.

func (*Runtime) InstanceOf ¶

func (r *Runtime) InstanceOf(left Value, right *Object) (res bool)

InstanceOf is an equivalent of "left instanceof right". This method will panic with an *Exception if a JavaScript exception is thrown in the process. Use Runtime.Try to catch these.

func (*Runtime) Interrupt ¶

func (r *Runtime) Interrupt(v interface{})

Interrupt running TypeScript. The corresponding Go call returns an *InterruptedError containing v. If the interrupt propagates until the stack is empty the currently queued promise resolve/reject jobs will be cleared without being executed. This is the same time they would be executed otherwise. Interrupt also stops backtracking RegExp matching and wakes a blocking Atomics.wait. Other native Go functions must cooperate with cancellation. If the runtime is currently not running, it will be immediately interrupted on the next Run*() call. To avoid that use ClearInterrupt()

func (*Runtime) New ¶

func (r *Runtime) New(construct Value, args ...Value) (o *Object, err error)

New is an equivalent of the 'new' operator allowing to call it directly from Go.

func (*Runtime) NewArray ¶

func (r *Runtime) NewArray(items ...interface{}) *Object
Example ¶
vm := New()
array := vm.NewArray(1, 2, true)
vm.Set("array", array)
res, err := vm.runVMString(`
	var acc = "";
	for (var v of array) {
		acc += v + " ";
	}
	acc;
	`)
if err != nil {
	panic(err)
}
fmt.Println(res)
Output:
1 2 true

func (*Runtime) NewArrayBuffer ¶

func (r *Runtime) NewArrayBuffer(data []byte) ArrayBuffer

NewArrayBuffer creates a new instance of ArrayBuffer backed by the provided byte slice.

Warning: be careful when using unaligned slices (sub-slices that do not start at word boundaries). If later a typed array of a multibyte type (uint16, uint32, etc.) is created from a buffer backed by an unaligned slice, using this typed array will result in unaligned access which may cause performance degradation or runtime panics on some architectures or configurations.

func (*Runtime) NewDynamicArray ¶

func (r *Runtime) NewDynamicArray(a DynamicArray) *Object

NewDynamicArray creates an array Object backed by the provided DynamicArray handler. It is similar to NewDynamicObject, the differences are:

- the Object is an array (i.e. Array.isArray() will return true and it will have the length property).

- the prototype will be initially set to Array.prototype.

- the Object cannot have any own string properties except for the 'length'.

func (*Runtime) NewDynamicObject ¶

func (r *Runtime) NewDynamicObject(d DynamicObject) *Object

NewDynamicObject creates an Object backed by the provided DynamicObject handler.

All properties of this Object are Writable, Enumerable and Configurable data properties. Any attempt to define a property that does not conform to this will fail.

The Object is always extensible and cannot be made non-extensible. Object.preventExtensions() will fail.

The Object's prototype is initially set to Object.prototype, but can be changed using regular mechanisms (Object.SetPrototype() in Go or Object.setPrototypeOf() in JS).

The Object cannot have own Symbol properties, however its prototype can. If you need an iterator support for example, you could create a regular object, set Symbol.iterator on that object and then use it as a prototype. See TestDynamicObjectCustomProto for more details.

Export() returns the original DynamicObject.

This mechanism is similar to ECMAScript Proxy, however because all properties are enumerable and the object is always extensible there is no need for invariant checks which removes the need to have a target object and makes it a lot more efficient.

func (*Runtime) NewGoError ¶

func (r *Runtime) NewGoError(err error) *Object

func (*Runtime) NewObject ¶

func (r *Runtime) NewObject() (v *Object)

func (*Runtime) NewPromise ¶

func (r *Runtime) NewPromise() (promise *Promise, resolve, reject func(reason interface{}) error)

NewPromise creates and returns a Promise and resolving functions for it. The returned errors will be uncatchable errors, such as InterruptedError or StackOverflowError, which should be propagated upwards. Exceptions are handled through PromiseRejectionTracker.

WARNING: The returned values are not goroutine-safe and must not be called in parallel with VM running. In order to make use of this method you need an event loop such as the one in goya_nodejs (https://github.com/totoer/goya_nodejs) where it can be used like this:

loop := NewEventLoop()
loop.Start()
defer loop.Stop()
loop.RunOnLoop(func(vm *goya.Runtime) {
    p, resolve, _ := vm.NewPromise()
    vm.Set("p", p)
    go func() {
        time.Sleep(500 * time.Millisecond)   // or perform any other blocking operation
        loop.RunOnLoop(func(*goya.Runtime) { // resolve() must be called on the loop, cannot call it here
            err := resolve(result)
            // Handle uncatchable errors (e.g. by stopping the loop, panicking or setting a flag)
        })
    }()
}

func (*Runtime) NewProxy ¶

func (r *Runtime) NewProxy(target *Object, nativeHandler *ProxyTrapConfig) Proxy

func (*Runtime) NewTypeError ¶

func (r *Runtime) NewTypeError(args ...interface{}) *Object

func (*Runtime) RunJobs ¶

func (r *Runtime) RunJobs() error

RunJobs delivers shared-wait notifications, garbage-collection cleanup callbacks and promise continuations on the runtime's owner goroutine. It creates no event loop and does not force garbage collection. Call it only while Runtime is idle. A cleanup exception is returned; later notifications remain pending.

func (*Runtime) RunProgram ¶

func (r *Runtime) RunProgram(p *Program) (result Value, err error)

RunProgram executes a pre-compiled (see Compile()) code in the global context.

func (*Runtime) RunScript ¶

func (r *Runtime) RunScript(name, src string) (Value, error)

RunScript checks and executes a single TypeScript source. Use Compile with a Project to provide imports or custom options. Names must be TypeScript paths.

func (*Runtime) RunString ¶

func (r *Runtime) RunString(str string) (Value, error)

RunString checks and executes a TypeScript source using the bound Environment.

func (*Runtime) Set ¶

func (r *Runtime) Set(name string, value interface{}) error

Set the specified variable in the global context. Equivalent to running "name = value" in non-strict mode. The value is first converted using ToValue(). Note, this is not the same as GlobalObject().Set(name, value), because if a global lexical binding (let or const) exists, it is set instead.

Example (Lexical) ¶
r := New()
_, err := r.runVMString("let x")
if err != nil {
	panic(err)
}
err = r.Set("x", 1)
if err != nil {
	panic(err)
}
fmt.Print(r.Get("x"), r.GlobalObject().Get("x"))
Output:
1 <nil>

func (*Runtime) SetAsyncContextTracker ¶

func (r *Runtime) SetAsyncContextTracker(tracker AsyncContextTracker)

SetAsyncContextTracker registers a handler that allows to track async execution contexts. See AsyncContextTracker documentation for more details. Setting it to nil disables the functionality. This method (as Runtime in general) is not goroutine-safe.

func (*Runtime) SetFieldNameMapper ¶

func (r *Runtime) SetFieldNameMapper(mapper FieldNameMapper)

SetFieldNameMapper sets a custom field name mapper for Go types. It can be called at any time, however the mapping for any given value is fixed at the point of creation. Setting this to nil restores the default behaviour which is all exported fields and methods are mapped to their original unchanged names.

func (*Runtime) SetGlobalObject ¶

func (r *Runtime) SetGlobalObject(object *Object)

SetGlobalObject sets the global object to the given object. Note, any existing references to the previous global object will continue to reference that object.

func (*Runtime) SetMaxCallStackSize ¶

func (r *Runtime) SetMaxCallStackSize(size int)

SetMaxCallStackSize sets the maximum function call depth. When exceeded, a *StackOverflowError is thrown and returned by RunProgram or by a Callable call. This is useful to prevent memory exhaustion caused by an infinite recursion. The default value is math.MaxInt32. Array.prototype.flat and flatMap also use this limit for their traversal stack, with an additional maximum of 10000 nested arrays to bound native memory use. This method (as the rest of the Set* methods) is not safe for concurrent use and may only be called from the vm goroutine or when the vm is not running.

func (*Runtime) SetPromiseRejectionTracker ¶

func (r *Runtime) SetPromiseRejectionTracker(tracker PromiseRejectionTracker)

SetPromiseRejectionTracker registers a function that will be called in two scenarios: when a promise is rejected without any handlers (with operation argument set to PromiseRejectionReject), and when a handler is added to a rejected promise for the first time (with operation argument set to PromiseRejectionHandle).

Setting a tracker replaces any existing one. Setting it to nil disables the functionality.

See https://tc39.es/ecma262/#sec-host-promise-rejection-tracker for more details.

func (*Runtime) SetRandSource ¶

func (r *Runtime) SetRandSource(source RandSource)

SetRandSource sets random source for this Runtime. If not called, the default math/rand is used.

func (*Runtime) SetTimeSource ¶

func (r *Runtime) SetTimeSource(now Now)

SetTimeSource sets the current time source for this Runtime. If not called, the default time.Now() is used.

func (*Runtime) SetTimeZone ¶

func (r *Runtime) SetTimeZone(identifier string) error

SetTimeZone selects the shared Date/Intl default timezone from the embedded IANA catalog or an ISO minute offset (for example "+05:30"). New runtimes use UTC, independently of the operating system. Call this on the Runtime owner, like SetTimeSource. An invalid identifier leaves the setting unchanged.

func (*Runtime) ToValue ¶

func (r *Runtime) ToValue(i interface{}) Value

ToValue converts a Go value into a JavaScript value of a most appropriate type. Structural types (such as structs, maps and slices) are wrapped so that changes are reflected on the original value which can be retrieved using Value.Export().

WARNING! These wrapped Go values do not behave in the same way as native ECMAScript values. If you plan to modify them in ECMAScript, bear in mind the following caveats:

1. If a regular JavaScript Object is assigned as an element of a wrapped Go struct, map or array, it is Export()'ed and therefore copied. This may result in an unexpected behaviour in JavaScript:

m := map[string]interface{}{}
vm.Set("m", m)
vm.RunString(`
var obj = {test: false};
m.obj = obj; // obj gets Export()'ed, i.e. copied to a new map[string]interface{} and then this map is set as m["obj"]
obj.test = true; // note, m.obj.test is still false
`)
fmt.Println(m["obj"].(map[string]interface{})["test"]) // prints "false"

2. Be careful with nested non-pointer compound types (structs, slices and arrays) if you modify them in ECMAScript. Better avoid it at all if possible. One of the fundamental differences between ECMAScript and Go is in the former all Objects are references whereas in Go you can have a literal struct or array. Consider the following example:

type S struct {
    Field int
}

a := []S{{1}, {2}} // slice of literal structs
vm.Set("a", &a)
vm.RunString(`
    let tmp = {Field: 1};
    a[0] = tmp;
    a[1] = tmp;
    tmp.Field = 2;
`)

In ECMAScript one would expect a[0].Field and a[1].Field to be equal to 2, but this is really not possible (or at least non-trivial without some complex reference tracking).

To cover the most common use cases and to avoid excessive memory allocation, the following 'copy-on-change' mechanism is implemented (for both arrays and structs):

* When a nested compound value is accessed, the returned ES value becomes a reference to the literal value. This ensures that things like 'a[0].Field = 1' work as expected and simple access to 'a[0].Field' does not result in copying of a[0].

* The original container ('a' in our case) keeps track of the returned reference value and if a[0] is reassigned (e.g. by direct assignment, deletion or shrinking the array) the old a[0] is copied and the earlier returned value becomes a reference to the copy:

let tmp = a[0];                      // no copy, tmp is a reference to a[0]
tmp.Field = 1;                       // a[0].Field === 1 after this
a[0] = {Field: 2};                   // tmp is now a reference to a copy of the old value (with Field === 1)
a[0].Field === 2 && tmp.Field === 1; // true

* Array value swaps caused by in-place sort (using Array.prototype.sort()) do not count as re-assignments, instead the references are adjusted to point to the new indices.

* Assignment to an inner compound value always does a copy (and sometimes type conversion):

a[1] = tmp;    // a[1] is now a copy of tmp
tmp.Field = 3; // does not affect a[1].Field

3. Non-addressable structs, slices and arrays get copied. This sometimes may lead to a confusion as assigning to inner fields does not appear to work:

a1 := []interface{}{S{1}, S{2}}
vm.Set("a1", &a1)
vm.RunString(`
   a1[0].Field === 1; // true
   a1[0].Field = 2;
   a1[0].Field === 2; // FALSE, because what it really did was copy a1[0] set its Field to 2 and immediately drop it
`)

An alternative would be making a1[0].Field a non-writable property which would probably be more in line with ECMAScript, however it would require to manually copy the value if it does need to be modified which may be impractical.

Note, the same applies to slices. If a slice is passed by value (not as a pointer), resizing the slice does not reflect on the original value. Moreover, extending the slice may result in the underlying array being re-allocated and copied. For example:

a := []interface{}{1}
vm.Set("a", a)
vm.RunString(`a.push(2); a[0] = 0;`)
fmt.Println(a[0]) // prints "1"

Notes on individual types:

Primitive types ¶

Primitive types (numbers, string, bool) are converted to the corresponding JavaScript primitives. These values are goroutine-safe and can be transferred between runtimes.

*big.Int ¶

A *big.Int value is converted to a BigInt value. Note, because BigInt is immutable, but *big.Int isn't, the value is copied. Export()'ing this value returns a *big.Int which is also a copy.

If the pointer value is nil, the resulting BigInt is 0n.

Strings ¶

Because of the difference in internal string representation between ECMAScript (which uses UTF-16) and Go (which uses UTF-8) conversion from JS to Go may be lossy. In particular, code points that can be part of UTF-16 surrogate pairs (0xD800-0xDFFF) cannot be represented in UTF-8 unless they form a valid surrogate pair and are replaced with utf8.RuneError.

The string value must be a valid UTF-8. If it is not, invalid characters are replaced with utf8.RuneError, but the behaviour of a subsequent Export() is unspecified (it may return the original value, or a value with replaced invalid characters).

Nil ¶

Nil is converted to null. This includes nil pointers, nil interfaces, nil slices, and nil functions. Note that they lose their type as a result and exported as plain nil interface (nil type and nil value).

Pointers ¶

Pointers are de-referenced and the referenced object dictates the shape of the Value. The Value keeps referring to the same object, so any changes made to it will be reflected. If the referenced value is a nil map without methods, setting a property creates a map. Same applies to slices.

Note, the indirection only goes one level, i.e. a pointer to a pointer becomes a generic empty Object. As with any Object wrapper it can have Symbol properties, but no string or index properties. It exports to the original pointer value.

Functions ¶

func(FunctionCall) Value is treated as a native JavaScript function. This increases performance because there are no automatic argument and return value type conversions (which involves reflect). Attempting to use the function as a constructor will result in a TypeError. Note: implementations must not retain and use references to FunctionCall.Arguments after the function returns.

func(FunctionCall, *Runtime) Value is treated as above, except the *Runtime is also passed as a parameter.

func(ConstructorCall) *Object is treated as a native constructor, allowing to use it with the new operator:

func MyObject(call goya.ConstructorCall) *goya.Object {
   // call.This contains the newly created object as per http://www.ecma-international.org/ecma-262/5.1/index.html#sec-13.2.2
   // call.Arguments contain arguments passed to the function

   call.This.Set("method", method)

   //...

   // If return value is a non-nil *Object, it will be used instead of call.This
   // This way it is possible to return a Go struct or a map converted
   // into goya.Value using ToValue(), however in this case
   // instanceof will not work as expected, unless you set the prototype:
   //
   // instance := &myCustomStruct{}
   // instanceValue := vm.ToValue(instance).(*Object)
   // instanceValue.SetPrototype(call.This.Prototype())
   // return instanceValue
   return nil
}

runtime.Set("MyObject", MyObject)

Then it can be used in JS as follows:

var o = new MyObject(arg);
var o1 = MyObject(arg); // same thing
o instanceof MyObject && o1 instanceof MyObject; // true

When a native constructor is called directly (without the new operator) its behavior depends on this value: if it's an Object, it is passed through, otherwise a new one is created exactly as if it was called with the new operator. In either case call.NewTarget will be nil.

func(ConstructorCall, *Runtime) *Object is treated as above, except the *Runtime is also passed as a parameter.

Any other Go function is wrapped so that the arguments are automatically converted into the required Go types and the return value is converted to a JavaScript value (using this method). If conversion is not possible, a TypeError is thrown.

Functions with multiple return values return an Array. If the last return value is an `error` it is not returned but converted into a JS exception. If the error is *Exception, it is thrown as is, otherwise it's wrapped in a GoEerror. Note that if there are exactly two return values and the last is an `error`, the function returns the first value as is, not an Array.

Iterator functions (https://pkg.go.dev/iter) have Symbol.iterator property and therefore can be iterated over using for-of loops. Both single-value and 2-value iterators are supported. In case of 2-value iterators the yielded value is a 2-element array, unless the second value's type is `error`. If the second value is error, and the iterator yields a non-nil value for it, it is thrown as an exception (and iteration stops), otherwise a single value is yielded.

See ExampleRuntime_ToValue_seq, ExampleRuntime_ToValue_seq2 and ExampleRuntime_ToValue_seq2err.

Structs ¶

Structs are converted to Object-like values. Fields and methods are available as properties, their values are results of this method (ToValue()) applied to the corresponding Go value.

Field properties are writable and non-configurable. Method properties are non-writable and non-configurable.

Attempt to define a new property or delete an existing property will fail (throw in strict mode) unless it's a Symbol property. Symbol properties only exist in the wrapper and do not affect the underlying Go value. Note that because a wrapper is created every time a property is accessed it may lead to unexpected results such as this:

 type Field struct{
 }
 type S struct {
	Field *Field
 }
 var s = S{
	Field: &Field{},
 }
 vm := New()
 vm.Set("s", &s)
 res, err := vm.RunString(`
 var sym = Symbol(66);
 var field1 = s.Field;
 field1[sym] = true;
 var field2 = s.Field;
 field1 === field2; // true, because the equality operation compares the wrapped values, not the wrappers
 field1[sym] === true; // true
 field2[sym] === undefined; // also true
 `)

The same applies to values from maps and slices as well.

Handling of time.Time ¶

time.Time does not get special treatment and therefore is converted just like any other `struct` providing access to all its methods. This is done deliberately instead of converting it to a `Date` because these two types are not fully compatible: `time.Time` includes zone, whereas JS `Date` doesn't. Doing the conversion implicitly therefore would result in a loss of information.

If you need to convert it to a `Date`, it can be done either in JS:

var d = new Date(goval.UnixNano()/1e6);

... or in Go:

 now := time.Now()
 vm := New()
 val, err := vm.New(vm.Get("Date").ToObject(vm), vm.ToValue(now.UnixNano()/1e6))
 if err != nil {
	...
 }
 vm.Set("d", val)

Note that Value.Export() for a `Date` value returns time.Time in local timezone.

Maps ¶

Maps with string, integer, or float key types are converted into host objects that largely behave like a JavaScript Object. One noticeable difference is that the key order is not stable, as with maps in Go. Keys are converted to strings following the fmt.Sprintf("%v") convention.

Maps with methods ¶

If a map type has at least one method defined, the properties of the resulting Object represent methods, not map keys. This is because in JavaScript there is no distinction between 'object.key` and `object[key]`, unlike Go. If access to the map values is required, it can be achieved by defining another method or, if it's not possible, by defining an external getter function.

Slices ¶

Slices are converted into host objects that behave largely like JavaScript Array. It has the appropriate prototype and all the usual methods should work. There is, however, a caveat: converted Arrays may not contain holes (because Go slices cannot). This means that hasOwnProperty(n) always returns `true` if n < length. Deleting an item with an index < length will set it to a zero value (but the property will remain). Nil slice elements are be converted to `null`. Accessing an element beyond `length` returns `undefined`. Also see the warning above about passing slices as values (as opposed to pointers).

Arrays ¶

Arrays are converted similarly to slices, except the resulting Arrays are not resizable (and therefore the 'length' property is non-writable).

Any other type is converted to a generic reflect based host object. Depending on the underlying type it behaves similar to a Number, String, Boolean or Object.

Note that the underlying type is not lost, calling Export() returns the original Go value. This applies to all reflect based types.

Example (Seq) ¶
iterSeq := func(yield func(int) bool) {
	for i := range 3 {
		if !yield(i) {
			return
		}
	}
}

vm := New()
vm.Set("iterSeq", iterSeq)
res, err := vm.runVMString(`
		let res = "";
		for (const label of iterSeq) {
			res += label;
		}
	`)
if err != nil {
	panic(err)
}
fmt.Print(res.String())
Output:
012
Example (Seq2) ¶
iterSeq := func(yield func(string, string) bool) {
	vals := [][2]string{
		{"admin", "full access"},
		{"user", "minimal access"},
	}
	for _, val := range vals {
		if !yield(val[0], val[1]) {
			return
		}
	}
}

vm := New()
vm.Set("iterSeq", iterSeq)
res, err := vm.runVMString(`
		let res = "";
		for (const [role, level] of iterSeq) {
			res += "{role: "+role+", level: "+level+"}";
		}
	`)
if err != nil {
	panic(err)
}
fmt.Print(res.String())
Output:
{role: admin, level: full access}{role: user, level: minimal access}
Example (Seq2err) ¶
vm := New()
iterSeq := func(yield func(string, error) bool) {
	if !yield("1", nil) {
		return
	}
	if !yield("", errors.New("error")) {
		return
	}
}

vm.Set("iterSeq", iterSeq)
res, err := vm.runVMString(`
		let res = "";
		try {
			for (const label of iterSeq) {
				res += label;
			}
		} catch(e) {
			res += "!"+e.toString();
		}
	`)
if err != nil {
	panic(err)
}
fmt.Print(res.String())
Output:
1!GoError: error

func (*Runtime) Try ¶

func (r *Runtime) Try(f func()) *Exception

Try runs a given function catching and returning any JS exception. Use this method to run any code that may throw exceptions (such as Object.Get, Object.String, Object.ToInteger, Object.Export, Runtime.Get, Runtime.InstanceOf, etc.) outside the Runtime execution context (i.e. when calling directly from Go, not from a JS function implemented in Go).

type SharedArrayBuffer ¶

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

SharedArrayBuffer is a Go-owned shared byte store. ToValue creates a separate realm object in each Runtime; the storage alone is shared. Its Go operations are safe concurrently with independently owned runtimes. Reads/writes through Go are byte operations; use script Atomics for atomic integer modifications.

func NewSharedArrayBuffer ¶

func NewSharedArrayBuffer(byteLength int, maxByteLength ...int) (buffer SharedArrayBuffer, err error)

NewSharedArrayBuffer allocates a fixed store, or a growable one when a maximum is supplied. It reserves the maximum storage; allocation errors are returned.

func (SharedArrayBuffer) ByteLength ¶

func (buffer SharedArrayBuffer) ByteLength() int

func (SharedArrayBuffer) Grow ¶

func (buffer SharedArrayBuffer) Grow(length int) error

func (SharedArrayBuffer) Growable ¶

func (buffer SharedArrayBuffer) Growable() bool

func (SharedArrayBuffer) MaxByteLength ¶

func (buffer SharedArrayBuffer) MaxByteLength() int

func (SharedArrayBuffer) ReadAt ¶

func (buffer SharedArrayBuffer) ReadAt(destination []byte, offset int64) (int, error)

func (SharedArrayBuffer) WriteAt ¶

func (buffer SharedArrayBuffer) WriteAt(source []byte, offset int64) (int, error)

type SourcePosition ¶

type SourcePosition = tsfrontend.Position

type SourceRange ¶

type SourceRange = tsfrontend.Range

type SourceResolver ¶

type SourceResolver = tsfrontend.SourceResolver

type StackFrame ¶

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

func (*StackFrame) FuncName ¶

func (f *StackFrame) FuncName() string

func (*StackFrame) Position ¶

func (f *StackFrame) Position() file.Position

func (*StackFrame) SrcName ¶

func (f *StackFrame) SrcName() string

func (*StackFrame) Write ¶

func (f *StackFrame) Write(b *bytes.Buffer)

func (*StackFrame) WriteToValueBuilder ¶

func (f *StackFrame) WriteToValueBuilder(b *StringBuilder)

type StackOverflowError ¶

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

type String ¶

type String interface {
	Value
	CharAt(int) uint16
	Length() int
	Concat(String) String
	Substring(start, end int) String
	CompareTo(String) int
	Reader() io.RuneReader
	// contains filtered or unexported methods
}

String represents an ECMAScript string Value. Its internal representation depends on the contents of the string, but in any case it is capable of holding any UTF-16 string, either valid or invalid. Instances of this type, as any other primitive values, are goroutine-safe and can be passed between runtimes. Strings can be created using Runtime.ToValue(goString) or StringFromUTF16.

func StringFromUTF16 ¶

func StringFromUTF16(chars []uint16) String

StringFromUTF16 creates a string value from an array of UTF-16 code units. The result is a copy, so the initial slice can be modified after calling this function (but it must not be modified while the function is running). No validation of any kind is performed.

type StringBuilder ¶

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

StringBuilder serves similar purpose to strings.Builder, except it works with ECMAScript String. Use it to efficiently build 'native' ECMAScript values that either contain invalid UTF-16 surrogate pairs (and therefore cannot be represented as UTF-8) or never expected to be exported to Go. See also StringFromUTF16.

func (*StringBuilder) Grow ¶

func (b *StringBuilder) Grow(n int)

func (*StringBuilder) LikelyUnicode ¶

func (b *StringBuilder) LikelyUnicode(extraLen int)

LikelyUnicode hints to the builder that the resulting string is likely to contain Unicode (non-ASCII) characters. The argument is an extra capacity (in characters) to reserve on top of the current length (it's like calling Grow() afterwards). This method may be called at any point (not just when the buffer is empty), although for efficiency it should be called as early as possible.

func (*StringBuilder) String ¶

func (b *StringBuilder) String() String

func (*StringBuilder) WriteRune ¶

func (b *StringBuilder) WriteRune(r rune)

func (*StringBuilder) WriteString ¶

func (b *StringBuilder) WriteString(s String)

func (*StringBuilder) WriteSubstring ¶

func (b *StringBuilder) WriteSubstring(source String, start int, end int)

func (*StringBuilder) WriteUTF8String ¶

func (b *StringBuilder) WriteUTF8String(s string)

type Symbol ¶

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

Symbol is a Value containing ECMAScript Symbol primitive. Symbols must only be created using NewSymbol(). Zero values and copying of values (i.e. *s1 = *s2) are not permitted. Well-known Symbols can be accessed using Sym* package variables (SymIterator, etc...) Symbols can be shared by multiple Runtimes.

func NewSymbol ¶

func NewSymbol(s string) *Symbol
Example ¶
sym1 := NewSymbol("66")
sym2 := NewSymbol("66")
fmt.Printf("%s %s %v", sym1, sym2, sym1.Equals(sym2))
Output:
66 66 false

func (*Symbol) Equals ¶

func (s *Symbol) Equals(o Value) bool

func (*Symbol) Export ¶

func (s *Symbol) Export() interface{}

func (*Symbol) ExportType ¶

func (s *Symbol) ExportType() reflect.Type

func (*Symbol) SameAs ¶

func (s *Symbol) SameAs(other Value) bool

func (*Symbol) StrictEquals ¶

func (s *Symbol) StrictEquals(o Value) bool

func (*Symbol) String ¶

func (s *Symbol) String() string

func (*Symbol) ToBoolean ¶

func (s *Symbol) ToBoolean() bool

func (*Symbol) ToFloat ¶

func (s *Symbol) ToFloat() float64

func (*Symbol) ToInteger ¶

func (s *Symbol) ToInteger() int64

func (*Symbol) ToNumber ¶

func (s *Symbol) ToNumber() Value

func (*Symbol) ToObject ¶

func (s *Symbol) ToObject(r *Runtime) *Object

func (*Symbol) ToString ¶

func (s *Symbol) ToString() Value

type TypeCheckError ¶

type TypeCheckError struct{ Diagnostics []Diagnostic }

TypeCheckError is returned when generated or explicitly supplied host types fail TypeScript validation. Diagnostics remain available without text parsing.

func (*TypeCheckError) Error ¶

func (e *TypeCheckError) Error() string

type Value ¶

type Value interface {
	ToInteger() int64

	ToString() Value
	String() string
	ToFloat() float64
	ToNumber() Value
	ToBoolean() bool
	ToObject(*Runtime) *Object
	SameAs(Value) bool
	Equals(Value) bool
	StrictEquals(Value) bool
	Export() interface{}
	ExportType() reflect.Type
	// contains filtered or unexported methods
}

Value represents an ECMAScript value.

Export returns a "plain" Go value which type depends on the type of the Value.

For integer numbers it's int64.

For any other numbers (including Infinities, NaN and negative zero) it's float64.

For string it's a string. Note that unicode strings are converted into UTF-8 with invalid code points replaced with utf8.RuneError.

For boolean it's bool.

For null and undefined it's nil.

For Object it depends on the Object type, see Object.Export() for more details.

func NaN ¶

func NaN() Value

NaN returns a JS NaN value.

func NegativeInf ¶

func NegativeInf() Value

NegativeInf returns a JS -Inf value.

func Null ¶

func Null() Value

Null returns JS null value.

func PositiveInf ¶

func PositiveInf() Value

PositiveInf returns a JS +Inf value.

func Undefined ¶

func Undefined() Value

Undefined returns JS undefined value. Note if global 'undefined' property is changed this still returns the original value.

Source Files ¶

Directories ¶

Path Synopsis
Package ast declares types representing a JavaScript AST.
Package ast declares types representing a JavaScript AST.
examples
typescript-host command
typescript-intl command
typescript-lsp-completion command
This example resolves an auto-import and applies the proposed edits to a caller-owned buffer before reporting the new version to the editor session.
This example resolves an auto-import and applies the proposed edits to a caller-owned buffer before reporting the new version to the editor session.
typescript-lsp-serve command
Serve a complete lifecycle transcript through application-owned memory IO.
Serve a complete lifecycle transcript through application-owned memory IO.
typescript-lsp-session command
This example uses editor session state directly, without a protocol client, runtime, external compiler or calls to a registered Go function.
This example uses editor session state directly, without a protocol client, runtime, external compiler or calls to a registered Go function.
Package file encapsulates the file abstractions used by the ast & parser.
Package file encapsulates the file abstractions used by the ast & parser.
Package ftoa provides ECMAScript-compliant floating point number conversion to string.
Package ftoa provides ECMAScript-compliant floating point number conversion to string.
internal/fast
Package fast contains code ported from V8 (https://github.com/v8/v8/blob/master/src/numbers/fast-dtoa.cc)
Package fast contains code ported from V8 (https://github.com/v8/v8/blob/master/src/numbers/fast-dtoa.cc)
internal
lspfixture
Package lspfixture replays committed editor fixtures against either a direct API adapter or a protocol client.
Package lspfixture replays committed editor fixtures against either a direct API adapter or a protocol client.
lspfixture/embedded
Package embedded runs shared fixtures against public direct and in-memory wire APIs.
Package embedded runs shared fixtures against public direct and in-memory wire APIs.
regexp2
Package regexp2 is a regexp package that has an interface similar to Go's framework regexp engine but uses a more feature full regex engine behind the scenes.
Package regexp2 is a regexp package that has an interface similar to Go's framework regexp engine but uses a more feature full regex engine behind the scenes.
tsfrontend/cmd/importupstream command
Command importupstream imports the pinned TypeScript Go frontend without invoking npm, Node.js, code generators, or a network client.
Command importupstream imports the pinned TypeScript Go frontend without invoking npm, Node.js, code generators, or a network client.
tsfrontend/cmd/inventory command
Command inventory records the exact declarations shipped by the pinned TypeScript frontend.
Command inventory records the exact declarations shipped by the pinned TypeScript frontend.
tsfrontend/cmd/lspparity command
Command lspparity maintains the pinned editor compatibility inventory.
Command lspparity maintains the pinned editor compatibility inventory.
tsfrontend/editor
Package editor adapts the pinned native project system to host-owned sources.
Package editor adapts the pinned native project system to host-owned sources.
tsfrontend/editorcollation
Package editorcollation implements the pinned editor's import comparers.
Package editorcollation implements the pinned editor's import comparers.
tsfrontend/editorregex
Package editorregex evaluates TypeScript editor exclusion patterns using the same ECMAScript grammar and pure-Go engines as the embedding runtime.
Package editorregex evaluates TypeScript editor exclusion patterns using the same ECMAScript grammar and pure-Go engines as the embedding runtime.
tsfrontend/refactor
Package refactor implements the pinned editor refactors over borrowed native programs.
Package refactor implements the pinned editor refactors over borrowed native programs.
tsfrontend/upstream/bundled
Package bundled provides access to files bundled with TypeScript.
Package bundled provides access to files bundled with TypeScript.
tsfrontend/upstream/compiler
Package compiler implements the TypeScript compiler.
Package compiler implements the TypeScript compiler.
tsfrontend/upstream/diagnostics
Package diagnostics contains generated localizable diagnostic messages.
Package diagnostics contains generated localizable diagnostic messages.
tsfrontend/upstream/jsnum
Package jsnum provides JS-like number handling.
Package jsnum provides JS-like number handling.
tsfrontend/upstream/jsonrpc
Package jsonrpc provides generic JSON-RPC 2.0 types and utilities that can be shared between LSP and other JSON-RPC based protocols.
Package jsonrpc provides generic JSON-RPC 2.0 types and utilities that can be shared between LSP and other JSON-RPC based protocols.
tsfrontend/upstream/lsp/lspwatcher
Package lspwatcher implements an in-process file watcher used as a drop-in replacement for LSP-based file watching when the client does not support dynamic registration of file watchers.
Package lspwatcher implements an in-process file watcher used as a drop-in replacement for LSP-based file watching when the client does not support dynamic registration of file watchers.
tsfrontend/upstream/nodebuilder
Exports interfaces and types defining the node builder - concrete implementations are on top of the checker, but these types and interfaces are used by the emit resolver in the printer
Exports interfaces and types defining the node builder - concrete implementations are on top of the checker, but these types and interfaces are used by the emit resolver in the printer
tsfrontend/upstream/printer
Package printer exports a Printer for pretty-printing TS ASTs and writer interfaces and implementations for using them Intended ultimate usage:
Package printer exports a Printer for pretty-printing TS ASTs and writer interfaces and implementations for using them Intended ultimate usage:
tsfrontend/upstream/pseudochecker
pseudochecker is a limited "checker" that returns pseudo-"types" of expressions - mostly those which trivially have type nodes
pseudochecker is a limited "checker" that returns pseudo-"types" of expressions - mostly those which trivially have type nodes
tsfrontend/upstream/stringutil
Package stringutil Exports common rune utilities for parsing and emitting javascript
Package stringutil Exports common rune utilities for parsing and emitting javascript
tzdata
Package tzdata loads only the embedded, pinned IANA timezone catalog.
Package tzdata loads only the embedded, pinned IANA timezone catalog.
tzdata/cmd/importtz command
importtz selects TZif assets from the checksum-verified PSF tzdata wheel.
importtz selects TZif assets from the checksum-verified PSF tzdata wheel.
lsp
Package lsp provides embedded TypeScript editor sessions and their LSP facade.
Package lsp provides embedded TypeScript editor sessions and their LSP facade.
protocol
Package protocol defines the public editor data types owned by Goya.
Package protocol defines the public editor data types owned by Goya.
Package parser implements a parser for JavaScript.
Package parser implements a parser for JavaScript.
Package token defines constants representing the lexical tokens of JavaScript (ECMA5).
Package token defines constants representing the lexical tokens of JavaScript (ECMA5).
Package unistring contains an implementation of a hybrid ASCII/UTF-16 string.
Package unistring contains an implementation of a hybrid ASCII/UTF-16 string.

Jump to

Keyboard shortcuts

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