quickjs

package module
v0.5.13 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2025 License: MIT Imports: 16 Imported by: 18

README

quickjs-go

English | 简体中文

Test codecov Go Report Card GoDoc FOSSA Status

Go bindings to QuickJS: a fast, small, and embeddable ES2020 JavaScript interpreter.

⚠️ This project is not ready for production use yet. Use at your own risk. APIs may change without notice.

Platform Support

we prebuilt quickjs static library for the following platforms:

Platform Arch Static Library
Linux x64 libquickjs.a
Linux arm64 libquickjs.a
Windows x64 libquickjs.a
Windows x86 libquickjs.a
MacOS x64 libquickjs.a
MacOS arm64 libquickjs.a

* for build on windows, ples see: https://github.com/buke/quickjs-go/issues/151#issuecomment-2134307728

Version Notes

quickjs-go QuickJS
v0.5.x v2025-04-26
v0.4.x v2024-02-14
v0.3.x v2024-01-13
v0.2.x v2023-12-09
v0.1.x v2021-03-27

Features

  • Evaluate script
  • Compile script into bytecode and Eval from bytecode
  • Operate JavaScript values and objects in Go
  • Bind Go function to JavaScript async/sync function
  • Simple exception throwing and catching
  • Marshal/Unmarshal Go values to/from JavaScript values
  • Full TypedArray support (Int8Array, Uint8Array, Float32Array, etc.)
  • Create JavaScript Classes from Go with ClassBuilder
  • Create JavaScript Modules from Go with ModuleBuilder

Breaking Changes

v0.5.11
  • API Simplification: Removed error return values from JavaScript execution methods
    • Context.Eval(), Context.EvalFile(), Context.LoadModule(), Context.LoadModuleBytecode() now return only *Value
    • Context.EvalBytecode(), Context.Await() now return only *Value
    • Context.BindClass(), ClassBuilder.Build() now return only (*Value, uint32)
    • Tips: Use Value.IsException() to check for exceptions and Use Context.Exception() to get exception as Go error
v0.5.10
  • *Value Type Changed from Value to Value
    • All Value parameters and return values have been changed from value types to pointer types (*Value)
    • Context.Function(fn func(*Context, Value, []Value) Value)Context.Function(fn func(*Context, *Value, []*Value) *Value)
    • All value creation methods now return *Value instead of Value
    • Class struct signatures updated to use *Value parameters

Guidelines

Error Handling
  • Use Value.IsException() or Context.HasException() to check for exceptions
  • Use Context.Exception() to get the exception as a Go error
  • Always call defer value.Free() for returned values to prevent memory leaks
  • Check Context.HasException() after operations that might throw
Memory Management
  • Call value.Free() for *Value objects you create or receive. QuickJS uses reference counting for memory management, so if a value is referenced by other objects, you only need to ensure the referencing objects are properly freed.
  • Runtime and Context objects have their own cleanup methods (Close()). Close them once you are done using them.
  • Use runtime.SetFinalizer() cautiously as it may interfere with QuickJS's GC.
Performance Tips
  • QuickJS is not thread-safe. Ensure execution in a single thread or use a thread pool pattern with pre-initialized runtimes
  • Reuse Runtime and Context objects when possible
  • Avoid frequent conversion between Go and JS values
  • Consider using bytecode compilation for frequently executed scripts
Best Practices
  • Keep JavaScript execution isolated to prevent interference - Create separate Runtime/Context instances for different tasks or users
  • Use appropriate EvalOptions for different script types
  • Handle both JavaScript exceptions and Go errors appropriately
  • Test memory usage under load to prevent leaks

Usage

import "github.com/buke/quickjs-go"
Run a script
package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    ret := ctx.Eval("'Hello ' + 'QuickJS!'")
    defer ret.Free()
    
    if ret.IsException() {
        err := ctx.Exception()
        println(err.Error())
        return
    }
    
    fmt.Println(ret.ToString())
}
Get/Set Javascript Object
package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    test := ctx.NewObject()
    test.Set("A", ctx.NewString("String A"))
    test.Set("B", ctx.NewString("String B"))
    test.Set("C", ctx.NewString("String C"))
    ctx.Globals().Set("test", test)

    ret := ctx.Eval(`Object.keys(test).map(key => test[key]).join(" ")`)
    defer ret.Free()
    
    if ret.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }
    
    fmt.Println(ret.ToString())
}

Bind Go Funtion to Javascript async/sync function
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create a new object
    test := ctx.NewObject()
    // bind properties to the object
    test.Set("A", ctx.NewString("String A"))
    test.Set("B", ctx.NewInt32(0))
    test.Set("C", ctx.NewBool(false))
    // bind go function to js object
    test.Set("hello", ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
        return ctx.NewString("Hello " + args[0].ToString())
    }))

    // bind "test" object to global object
    ctx.Globals().Set("test", test)

    // call js function by js
    js_ret := ctx.Eval(`test.hello("Javascript!")`)
    defer js_ret.Free()
    
    if js_ret.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }
    
    fmt.Println(js_ret.ToString())

    // call js function by go
    go_ret := test.Call("hello", ctx.NewString("Golang!"))
    defer go_ret.Free()
    
    if go_ret.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }
    
    fmt.Println(go_ret.ToString())

    // bind go function to Javascript async function using Function + Promise
    ctx.Globals().Set("testAsync", ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
        return ctx.Promise(func(resolve, reject func(*quickjs.Value)) {
            resolve(ctx.NewString("Hello Async Function!"))
        })
    }))

    ret := ctx.Eval(`
            var ret;
            testAsync().then(v => ret = v)
        `)
    defer ret.Free()

    if ret.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }

    // wait for promise resolve
    ctx.Loop()

    //get promise result
    asyncRet := ctx.Eval("ret")
    defer asyncRet.Free()

    if asyncRet.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }

    fmt.Println(asyncRet.ToString())

    // Output:
    // Hello Javascript!
    // Hello Golang!
    // Hello Async Function!
}
Error Handling
package main

import (
    "fmt"
    "errors"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    ctx.Globals().SetFunction("A", func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
        // raise error
        return ctx.ThrowError(errors.New("expected error"))
    })

    result := ctx.Eval("A()")
    defer result.Free()
    
    if result.IsException() {
        actual := ctx.Exception()
        fmt.Println(actual.Error())
    }
}
TypedArray Support

QuickJS-Go provides support for JavaScript TypedArrays, enabling binary data processing between Go and JavaScript.

Creating TypedArrays from Go
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create various TypedArrays from Go slices
    int8Data := []int8{-128, -1, 0, 1, 127}
    int8Array := ctx.NewInt8Array(int8Data)

    uint8Data := []uint8{0, 128, 255}
    uint8Array := ctx.NewUint8Array(uint8Data)

    float32Data := []float32{-3.14, 0.0, 2.718, 100.5}
    float32Array := ctx.NewFloat32Array(float32Data)

    int64Data := []int64{-9223372036854775808, 0, 9223372036854775807}
    bigInt64Array := ctx.NewBigInt64Array(int64Data)

    // Set TypedArrays as global variables
    ctx.Globals().Set("int8Array", int8Array)
    ctx.Globals().Set("uint8Array", uint8Array)
    ctx.Globals().Set("float32Array", float32Array)
    ctx.Globals().Set("bigInt64Array", bigInt64Array)

    // Use in JavaScript
    result := ctx.Eval(`
        // Check types
        const results = {
            int8Type: int8Array instanceof Int8Array,
            uint8Type: uint8Array instanceof Uint8Array,
            float32Type: float32Array instanceof Float32Array,
            bigInt64Type: bigInt64Array instanceof BigInt64Array,
            // Calculate sum of float32 array
            float32Sum: float32Array.reduce((sum, val) => sum + val, 0)
        };
        results;
    `)
    defer result.Free()

    if result.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }

    fmt.Println("Results:", result.JSONStringify())
}
Converting JavaScript TypedArrays to Go
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create TypedArrays in JavaScript
    jsTypedArrays := ctx.Eval(`
        ({
            int8: new Int8Array([-128, -1, 0, 1, 127]),
            uint16: new Uint16Array([0, 32768, 65535]),
            float64: new Float64Array([Math.PI, Math.E, 42.5]),
            bigUint64: new BigUint64Array([0n, 18446744073709551615n])
        })
    `)
    defer jsTypedArrays.Free()

    if jsTypedArrays.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }

    // Convert to Go slices
    int8Array := jsTypedArrays.Get("int8")
    defer int8Array.Free()
    if int8Array.IsInt8Array() {
        goInt8Slice, err := int8Array.ToInt8Array()
        if err == nil {
            fmt.Printf("Int8Array: %v\n", goInt8Slice)
        }
    }

    uint16Array := jsTypedArrays.Get("uint16")
    defer uint16Array.Free()
    if uint16Array.IsUint16Array() {
        goUint16Slice, err := uint16Array.ToUint16Array()
        if err == nil {
            fmt.Printf("Uint16Array: %v\n", goUint16Slice)
        }
    }

    float64Array := jsTypedArrays.Get("float64")
    defer float64Array.Free()
    if float64Array.IsFloat64Array() {
        goFloat64Slice, err := float64Array.ToFloat64Array()
        if err == nil {
            fmt.Printf("Float64Array: %v\n", goFloat64Slice)
        }
    }

    bigUint64Array := jsTypedArrays.Get("bigUint64")
    defer bigUint64Array.Free()
    if bigUint64Array.IsBigUint64Array() {
        goBigUint64Slice, err := bigUint64Array.ToBigUint64Array()
        if err == nil {
            fmt.Printf("BigUint64Array: %v\n", goBigUint64Slice)
        }
    }
}
TypedArray Types Support
Go Type JavaScript TypedArray Context Method Value Method
[]int8 Int8Array ctx.NewInt8Array() val.ToInt8Array()
[]uint8 Uint8Array ctx.NewUint8Array() val.ToUint8Array()
[]uint8 Uint8ClampedArray ctx.NewUint8ClampedArray() val.ToUint8Array()
[]int16 Int16Array ctx.NewInt16Array() val.ToInt16Array()
[]uint16 Uint16Array ctx.NewUint16Array() val.ToUint16Array()
[]int32 Int32Array ctx.NewInt32Array() val.ToInt32Array()
[]uint32 Uint32Array ctx.NewUint32Array() val.ToUint32Array()
[]float32 Float32Array ctx.NewFloat32Array() val.ToFloat32Array()
[]float64 Float64Array ctx.NewFloat64Array() val.ToFloat64Array()
[]int64 BigInt64Array ctx.NewBigInt64Array() val.ToBigInt64Array()
[]uint64 BigUint64Array ctx.NewBigUint64Array() val.ToBigUint64Array()
[]byte ArrayBuffer ctx.NewArrayBuffer() val.ToByteArray()
TypedArray Detection
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create various arrays
    regularArray := ctx.Eval(`[1, 2, 3]`)
    defer regularArray.Free()

    int32Array := ctx.NewInt32Array([]int32{1, 2, 3})
    float64Array := ctx.NewFloat64Array([]float64{1.1, 2.2, 3.3})

    // Set arrays as global variables to be referenced by globals
    ctx.Globals().Set("int32Array", int32Array)
    ctx.Globals().Set("float64Array", float64Array)

    // Detect array types
    fmt.Printf("Regular array IsArray: %v\n", regularArray.IsArray())
    fmt.Printf("Regular array IsTypedArray: %v\n", regularArray.IsTypedArray())

    fmt.Printf("Int32Array IsTypedArray: %v\n", int32Array.IsTypedArray())
    fmt.Printf("Int32Array IsInt32Array: %v\n", int32Array.IsInt32Array())
    fmt.Printf("Int32Array IsFloat64Array: %v\n", int32Array.IsFloat64Array())

    fmt.Printf("Float64Array IsTypedArray: %v\n", float64Array.IsTypedArray())
    fmt.Printf("Float64Array IsFloat64Array: %v\n", float64Array.IsFloat64Array())
    fmt.Printf("Float64Array IsInt32Array: %v\n", float64Array.IsInt32Array())
}
Binary Data Processing Example
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Process image-like data (simulate RGB pixels)
    imageData := []uint8{
        255, 0, 0,    // Red pixel
        0, 255, 0,    // Green pixel  
        0, 0, 255,    // Blue pixel
        255, 255, 0,  // Yellow pixel
    }

    // Send to JavaScript as Uint8Array
    imageArray := ctx.NewUint8Array(imageData)
    ctx.Globals().Set("imageData", imageArray)

    // Process in JavaScript
    result := ctx.Eval(`
        // Convert RGB to grayscale
        const grayscale = new Uint8Array(imageData.length / 3);
        for (let i = 0; i < imageData.length; i += 3) {
            const r = imageData[i];
            const g = imageData[i + 1];
            const b = imageData[i + 2];
            grayscale[i / 3] = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
        }
        grayscale;
    `)
    defer result.Free()

    if result.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }

    // Convert back to Go
    if result.IsUint8Array() {
        grayscaleData, err := result.ToUint8Array()
        if err == nil {
            fmt.Printf("Original RGB: %v\n", imageData)
            fmt.Printf("Grayscale: %v\n", grayscaleData)
        }
    }
}
Marshal/Unmarshal Go Values

QuickJS-Go provides conversion between Go and JavaScript values through the Marshal and Unmarshal methods.

Basic Types
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Marshal Go values to JavaScript
    data := map[string]interface{}{
        "name":    "John Doe",
        "age":     30,
        "active":  true,
        "scores":  []int{85, 92, 78},
        "address": map[string]string{
            "city":    "New York",
            "country": "USA",
        },
        // TypedArray will be automatically created for typed slices
        "floatData": []float32{1.1, 2.2, 3.3},
        "intData":   []int32{100, 200, 300},
        "byteData":  []byte{0x48, 0x65, 0x6C, 0x6C, 0x6F}, // "Hello" in bytes
    }

    jsVal, err := ctx.Marshal(data)
    if err != nil {
        panic(err)
    }
    defer jsVal.Free()

    // Use the marshaled value in JavaScript
    ctx.Globals().Set("user", jsVal)
    result := ctx.Eval(`
        const info = user.name + " is " + user.age + " years old";
        const floatArrayType = user.floatData instanceof Float32Array;
        const intArrayType = user.intData instanceof Int32Array;
        const byteArrayType = user.byteData instanceof ArrayBuffer;
        
        ({
            info: info,
            floatArrayType: floatArrayType,
            intArrayType: intArrayType,
            byteArrayType: byteArrayType,
            byteString: new TextDecoder().decode(user.byteData)
        });
    `)
    defer result.Free()
    
    if result.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }
    
    fmt.Println("Result:", result.JSONStringify())

    // Unmarshal JavaScript values back to Go
    var userData map[string]interface{}
    err = ctx.Unmarshal(jsVal, &userData)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Unmarshaled: %+v\n", userData)
}
Struct Marshaling with Tags
package main

import (
    "fmt"
    "time"
    "github.com/buke/quickjs-go"
)

type User struct {
    ID        int64     `js:"id"`
    Name      string    `js:"name"`
    Email     string    `json:"email_address"`
    CreatedAt time.Time `js:"created_at"`
    IsActive  bool      `js:"is_active"`
    Tags      []string  `js:"tags"`
    // TypedArray fields
    Scores    []float32 `js:"scores"`    // Will become Float32Array
    Data      []int32   `js:"data"`      // Will become Int32Array
    Binary    []byte    `js:"binary"`    // Will become ArrayBuffer
    // unexported fields are ignored
    password  string
    // Fields with "-" tag are skipped
    Secret    string `js:"-"`
}

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    user := User{
        ID:        123,
        Name:      "Alice",
        Email:     "alice@example.com",
        CreatedAt: time.Now(),
        IsActive:  true,
        Tags:      []string{"admin", "user"},
        Scores:    []float32{95.5, 87.2, 92.0},
        Data:      []int32{1000, 2000, 3000},
        Binary:    []byte{0x41, 0x42, 0x43}, // "ABC"
        password:  "secret123",
        Secret:    "top-secret",
    }

    // Marshal struct to JavaScript
    jsVal, err := ctx.Marshal(user)
    if err != nil {
        panic(err)
    }
    defer jsVal.Free()

    // Check TypedArray types in JavaScript
    ctx.Globals().Set("user", jsVal)
    result := ctx.Eval(`
        ({
            scoresType: user.scores instanceof Float32Array,
            dataType: user.data instanceof Int32Array,
            binaryType: user.binary instanceof ArrayBuffer,
            binaryString: new TextDecoder().decode(user.binary),
            avgScore: user.scores.reduce((sum, score) => sum + score) / user.scores.length
        });
    `)
    defer result.Free()

    if result.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }

    // Modify in JavaScript
    modifyResult := ctx.Eval(`
        user.name = "Alice Smith";
        user.tags.push("moderator");
        // Modify TypedArray data
        user.scores[0] = 98.5;
        user;
    `)
    defer modifyResult.Free()

    if modifyResult.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }

    // Unmarshal back to Go struct
    var updatedUser User
    err = ctx.Unmarshal(modifyResult, &updatedUser)
    if err != nil {
        panic(err)
    }

    fmt.Printf("Updated user: %+v\n", updatedUser)
    // Note: password and Secret fields remain unchanged (not serialized)
}
Custom Marshal/Unmarshal
package main

import (
    "fmt"
    "strings"
    "github.com/buke/quickjs-go"
)

type CustomType struct {
    Value string
}

// Implement Marshaler interface
func (c CustomType) MarshalJS(ctx *quickjs.Context) (*quickjs.Value, error) {
    return ctx.NewString("custom:" + c.Value), nil
}

// Implement Unmarshaler interface
func (c *CustomType) UnmarshalJS(ctx *quickjs.Context, val *quickjs.Value) error {
    if val.IsString() {
        str := val.ToString()
        if strings.HasPrefix(str, "custom:") {
            c.Value = str[7:] // Remove "custom:" prefix
        } else {
            c.Value = str
        }
    }
    return nil
}

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Marshal custom type
    custom := CustomType{Value: "hello"}
    jsVal, err := ctx.Marshal(custom)
    if err != nil {
        panic(err)
    }
    defer jsVal.Free()

    fmt.Println("Marshaled:", jsVal.ToString()) // Output: custom:hello

    // Unmarshal back
    var result CustomType
    err = ctx.Unmarshal(jsVal, &result)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Unmarshaled: %+v\n", result) // Output: {Value:hello}
}
Type Mappings

Go to JavaScript:

  • bool → JavaScript boolean
  • int, int8, int16, int32 → JavaScript number (32-bit)
  • int64 → JavaScript number (64-bit)
  • uint, uint8, uint16, uint32 → JavaScript number (32-bit unsigned)
  • uint64 → JavaScript BigInt
  • float32, float64 → JavaScript number
  • string → JavaScript string
  • []byte → JavaScript ArrayBuffer
  • []int8 → JavaScript Int8Array
  • []uint8 → JavaScript Uint8Array
  • []int16 → JavaScript Int16Array
  • []uint16 → JavaScript Uint16Array
  • []int32 → JavaScript Int32Array
  • []uint32 → JavaScript Uint32Array
  • []float32 → JavaScript Float32Array
  • []float64 → JavaScript Float64Array
  • []int64 → JavaScript BigInt64Array
  • []uint64 → JavaScript BigUint64Array
  • slice/array → JavaScript Array (for non-typed arrays)
  • map → JavaScript Object
  • struct → JavaScript Object
  • pointer → recursively marshal pointed value (nil becomes null)

JavaScript to Go:

  • JavaScript null/undefined → Go nil pointer or zero value
  • JavaScript boolean → Go bool
  • JavaScript number → Go numeric types (with appropriate conversion)
  • JavaScript BigInt → Go uint64/int64/*big.Int
  • JavaScript string → Go string
  • JavaScript Array → Go slice/array
  • JavaScript Object → Go map/struct
  • JavaScript ArrayBuffer → Go []byte
  • JavaScript Int8Array → Go []int8
  • JavaScript Uint8Array/Uint8ClampedArray → Go []uint8
  • JavaScript Int16Array → Go []int16
  • JavaScript Uint16Array → Go []uint16
  • JavaScript Int32Array → Go []int32
  • JavaScript Uint32Array → Go []uint32
  • JavaScript Float32Array → Go []float32
  • JavaScript Float64Array → Go []float64
  • JavaScript BigInt64Array → Go []int64
  • JavaScript BigUint64Array → Go []uint64

When unmarshaling into interface{}, the following types are used:

  • nil for null/undefined
  • bool for boolean
  • int64 for integer numbers
  • float64 for floating-point numbers
  • string for string
  • []interface{} for Array
  • map[string]interface{} for Object
  • *big.Int for BigInt
  • []byte for ArrayBuffer
Create JavaScript Modules from Go with ModuleBuilder

The ModuleBuilder API allows you to create JavaScript modules from Go code, making Go functions, values, and objects available for standard ES6 import syntax in JavaScript applications.

Basic Module Creation
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create a math module with Go functions and values
    addFunc := ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
        if len(args) >= 2 {
            return ctx.NewFloat64(args[0].ToFloat64() + args[1].ToFloat64())
        }
        return ctx.NewFloat64(0)
    })
    defer addFunc.Free()

    // Build the module using fluent API
    module := quickjs.NewModuleBuilder("math").
        Export("PI", ctx.NewFloat64(3.14159)).
        Export("add", addFunc).
        Export("version", ctx.NewString("1.0.0")).
        Export("default", ctx.NewString("Math Module"))

    err := module.Build(ctx)
    if err != nil {
        panic(err)
    }

    // Use the module in JavaScript with standard ES6 import
    result := ctx.Eval(`
        (async function() {
            // Named imports
            const { PI, add, version } = await import('math');
            
            // Use imported functions and values
            const sum = add(PI, 1.0);
            return { sum, version };
        })()
    `, quickjs.EvalAwait(true))
    defer result.Free()

    if result.IsException() {
        err := ctx.Exception()
        panic(err)
    }

    fmt.Println("Module result:", result.JSONStringify())
    // Output: Module result: {"sum":4.14159,"version":"1.0.0"}
}
Advanced Module Features
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create a utilities module with complex objects
    config := ctx.NewObject()
    config.Set("appName", ctx.NewString("MyApp"))
    config.Set("version", ctx.NewString("2.0.0"))
    config.Set("debug", ctx.NewBool(true))

    greetFunc := ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
        name := "World"
        if len(args) > 0 {
            name = args[0].ToString()
        }
        return ctx.NewString(fmt.Sprintf("Hello, %s!", name))
    })
    defer greetFunc.Free()

    jsonVal := ctx.ParseJSON(`{"MAX": 100, "MIN": 1}`)
    defer jsonVal.Free()

    // Create module with various export types
    module := quickjs.NewModuleBuilder("utils").
        Export("config", config).                    // Object export
        Export("greet", greetFunc).                  // Function export
        Export("constants", jsonVal).                // JSON export
        Export("default", ctx.NewString("Utils Library"))  // Default export

    err := module.Build(ctx)
    if err != nil {
        panic(err)
    }

    // Use mixed imports in JavaScript
    result := ctx.Eval(`
        (async function() {
            // Import from utils module
            const { greet, config, constants } = await import('utils');
            
            // Combine functionality
            const message = greet("JavaScript");
            const info = config.appName + " v" + config.version;
            const limits = "Max: " + constants.MAX + ", Min: " + constants.MIN;
            
            return { message, info, limits };
        })()
    `, quickjs.EvalAwait(true))
    defer result.Free()

    if result.IsException() {
        err := ctx.Exception()
        panic(err)
    }

    fmt.Println("Advanced module result:", result.JSONStringify())
}
Multiple Module Integration
package main

import (
    "fmt"
    "strings"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create math module
    addFunc := ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
        if len(args) >= 2 {
            return ctx.NewFloat64(args[0].ToFloat64() + args[1].ToFloat64())
        }
        return ctx.NewFloat64(0)
    })
    defer addFunc.Free()

    mathModule := quickjs.NewModuleBuilder("math").
        Export("add", addFunc).
        Export("PI", ctx.NewFloat64(3.14159))

    // Create string utilities module
    upperFunc := ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
        if len(args) > 0 {
            return ctx.NewString(strings.ToUpper(args[0].ToString()))
        }
        return ctx.NewString("")
    })
    defer upperFunc.Free()

    stringModule := quickjs.NewModuleBuilder("strings").
        Export("upper", upperFunc)

    // Build both modules
    err := mathModule.Build(ctx)
    if err != nil {
        panic(err)
    }

    err = stringModule.Build(ctx)
    if err != nil {
        panic(err)
    }

    // Use multiple modules together
    result := ctx.Eval(`
        (async function() {
            // Import from multiple modules
            const { add, PI } = await import('math');
            const { upper } = await import('strings');
            
            // Combine functionality
            const sum = add(PI, 1);
            const message = "Result: " + sum.toFixed(2);
            const finalMessage = upper(message);
            
            return finalMessage;
        })()
    `, quickjs.EvalAwait(true))
    defer result.Free()

    if result.IsException() {
        err := ctx.Exception()
        panic(err)
    }

    fmt.Println("Multiple modules result:", result.ToString())
    // Output: Multiple modules result: RESULT: 4.14
}
ModuleBuilder API Reference

Core Methods:

  • NewModuleBuilder(name) - Create a new module builder with the specified name
  • Export(name, value) - Add a named export to the module (chainable method)
  • Build(ctx) - Register the module in the JavaScript context
Create JavaScript Classes from Go with ClassBuilder

The ClassBuilder API allows you to create JavaScript classes from Go code.

Manual Class Creation

Create JavaScript classes manually with control over methods, properties, and accessors:

package main

import (
    "fmt"
    "math"
    "github.com/buke/quickjs-go"
)

type Point struct {
    X, Y float64
    Name string
}

func (p *Point) Distance() float64 {
    return math.Sqrt(p.X*p.X + p.Y*p.Y)
}

func (p *Point) Move(dx, dy float64) {
    p.X += dx
    p.Y += dy
}

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create Point class using ClassBuilder
    pointConstructor, _ := quickjs.NewClassBuilder("Point").
        Constructor(func(ctx *quickjs.Context, instance *quickjs.Value, args []*quickjs.Value) (interface{}, error) {
            x, y := 0.0, 0.0
            name := "Unnamed Point"
            
            if len(args) > 0 { x = args[0].ToFloat64() }
            if len(args) > 1 { y = args[1].ToFloat64() }
            if len(args) > 2 { name = args[2].ToString() }
            
            // Return Go object for automatic association
            return &Point{X: x, Y: y, Name: name}, nil
        }).
        // Accessors provide getter/setter functionality with custom logic
        Accessor("x", 
            func(ctx *quickjs.Context, this *quickjs.Value) *quickjs.Value {
                point, _ := this.GetGoObject()
                return ctx.NewFloat64(point.(*Point).X)
            },
            func(ctx *quickjs.Context, this *quickjs.Value, value *quickjs.Value) *quickjs.Value {
                point, _ := this.GetGoObject()
                point.(*Point).X = value.ToFloat64()
                return ctx.NewUndefined()
            }).
        Accessor("y",
            func(ctx *quickjs.Context, this *quickjs.Value) *quickjs.Value {
                point, _ := this.GetGoObject()
                return ctx.NewFloat64(point.(*Point).Y)
            },
            func(ctx *quickjs.Context, this *quickjs.Value, value *quickjs.Value) *quickjs.Value {
                point, _ := this.GetGoObject()
                point.(*Point).Y = value.ToFloat64()
                return ctx.NewUndefined()
            }).
        // Properties are bound directly to each instance
        Property("version", ctx.NewString("1.0.0")).
        Property("type", ctx.NewString("Point")).
        // Read-only property
        Property("readOnly", ctx.NewBool(true), quickjs.PropertyConfigurable).
        // Instance methods
        Method("distance", func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
            point, _ := this.GetGoObject()
            return ctx.NewFloat64(point.(*Point).Distance())
        }).
        Method("move", func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
            point, _ := this.GetGoObject()
            dx, dy := 0.0, 0.0
            if len(args) > 0 { dx = args[0].ToFloat64() }
            if len(args) > 1 { dy = args[1].ToFloat64() }
            point.(*Point).Move(dx, dy)
            return ctx.NewUndefined()
        }).
        Method("getName", func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
            point, _ := this.GetGoObject()
            return ctx.NewString(point.(*Point).Name)
        }).
        // Static method
        StaticMethod("origin", func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
            // Create a new Point at origin
            origin := &Point{X: 0, Y: 0, Name: "Origin"}
            jsVal, _ := ctx.Marshal(origin)
            return jsVal
        }).
        Build(ctx)

    // Register the class
    ctx.Globals().Set("Point", pointConstructor)

    // Use in JavaScript
    result := ctx.Eval(`
        const p = new Point(3, 4, "My Point");
        const dist1 = p.distance();
        p.move(1, 1);
        const dist2 = p.distance();
        
        // Static method usage
        const origin = Point.origin();
        
        ({ 
            // Accessor usage
            x: p.x,
            y: p.y,
            // Property usage
            version: p.version,
            type: p.type,
            readOnly: p.readOnly,
            hasOwnProperty: p.hasOwnProperty('version'), // true for properties
            // Method results
            name: p.getName(),
            initialDistance: dist1,
            finalDistance: dist2,
            // Static method result
            originDistance: Math.sqrt(origin.x * origin.x + origin.y * origin.y)
        });
    `)
    defer result.Free()
    
    if result.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }
    
    fmt.Println("Result:", result.JSONStringify())
    
    // Demonstrate the difference between accessors and properties
    propertyTest := ctx.Eval(`
        const p1 = new Point(1, 1);
        const p2 = new Point(2, 2);
        
        // Properties are instance-specific values
        const sameVersion = p1.version === p2.version; // true, same static value
        
        // Accessors provide dynamic values from Go object
        const differentX = p1.x !== p2.x; // true, different values from Go objects
        
        ({ sameVersion, differentX });
    `)
    defer propertyTest.Free()
    
    if propertyTest.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }
    
    fmt.Println("Property vs Accessor:", propertyTest.JSONStringify())
}
Automatic Class Creation with Reflection

Automatically generate JavaScript classes from Go structs using reflection. Go struct fields are automatically converted to JavaScript class accessors, providing getter/setter functionality that directly maps to the underlying Go object fields.

package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

type User struct {
    ID        int64     `js:"id"`           // Becomes accessor: user.id
    Name      string    `js:"name"`         // Becomes accessor: user.name
    Email     string    `json:"email_address"` // Becomes accessor: user.email_address
    Age       int       `js:"age"`          // Becomes accessor: user.age
    IsActive  bool      `js:"is_active"`    // Becomes accessor: user.is_active
    Scores    []float32 `js:"scores"`       // Becomes accessor: user.scores (Float32Array)
    private   string    // Not accessible (unexported)
    Secret    string    `js:"-"`            // Explicitly ignored
}

func (u *User) GetFullInfo() string {
    return fmt.Sprintf("%s (%s) - Age: %d", u.Name, u.Email, u.Age)
}

func (u *User) UpdateEmail(newEmail string) {
    u.Email = newEmail
}

func (u *User) AddScore(score float32) {
    u.Scores = append(u.Scores, score)
}

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Automatically create User class from struct
    userConstructor, _ := ctx.BindClass(&User{})

    ctx.Globals().Set("User", userConstructor)

    // Use with positional arguments
    result1 := ctx.Eval(`
        const user1 = new User(1, "Alice", "alice@example.com", 25, true, [95.5, 87.2]);
        user1.GetFullInfo();
    `)
    defer result1.Free()
    
    if result1.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }
    
    fmt.Println("Positional:", result1.ToString())

    // Use with named arguments (object parameter)
    result2 := ctx.Eval(`
        const user2 = new User({
            id: 2,
            name: "Bob",
            email_address: "bob@example.com",
            age: 30,
            is_active: true,
            scores: [88.0, 92.5, 85.0]
        });
        
        // Call methods
        user2.UpdateEmail("bob.smith@example.com");
        user2.AddScore(95.0);
        
        // Access fields via accessors (directly map to Go struct fields)
        user2.age = 31;        // Setter: modifies the Go struct field
        const newAge = user2.age; // Getter: reads from the Go struct field
        
        ({
            info: user2.GetFullInfo(),
            email: user2.email_address,  // Accessor getter
            age: newAge,                 // Modified via accessor setter
            scoresType: user2.scores instanceof Float32Array,
            scoresLength: user2.scores.length
        });
    `)
    defer result2.Free()
    
    if result2.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }
    
    fmt.Println("Named:", result2.JSONStringify())

    // Demonstrate field accessor synchronization
    result3 := ctx.Eval(`
        const user3 = new User(3, "Charlie", "charlie@example.com", 35, true, []);
        
        // Field accessors provide direct access to Go struct fields
        const originalName = user3.name;  // Getter: reads Go struct field
        
        user3.name = "Charles";           // Setter: modifies Go struct field
        const newName = user3.name;       // Getter: reads modified field
        
        // Changes are synchronized with Go object
        const info = user3.GetFullInfo(); // Method sees the changed name
        
        // Verify synchronization by changing multiple fields
        user3.age = 36;
        user3.email_address = "charles.updated@example.com";
        const updatedInfo = user3.GetFullInfo();
        
        ({
            originalName: originalName,
            newName: newName,
            infoAfterNameChange: info,
            finalInfo: updatedInfo,
            // Demonstrate that Go object is synchronized
            goObjectAge: user3.age,
            goObjectEmail: user3.email_address
        });
    `)
    defer result3.Free()
    
    if result3.IsException() {
        err := ctx.Exception()
        fmt.Println("Error:", err.Error())
        return
    }
    
    fmt.Println("Synchronization demonstration:", result3.JSONStringify())
}
Bytecode Compiler
package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()
    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    jsStr := `
    function fib(n)
    {
        if (n <= 0)
            return 0;
        else if (n == 1)
            return 1;
        else
            return fib(n - 1) + fib(n - 2);
    }
    fib(10)
    `
    // Compile the script to bytecode
    buf, err := ctx.Compile(jsStr)
    if err != nil {
        panic(err)
    }

    // Create a new runtime
    rt2 := quickjs.NewRuntime()
    defer rt2.Close()

    // Create a new context
    ctx2 := rt2.NewContext()
    defer ctx2.Close()

    //Eval bytecode
    result := ctx2.EvalBytecode(buf)
    defer result.Free()
    
    if result.IsException() {
        err := ctx2.Exception()
        fmt.Println("Error:", err.Error())
        return
    }
    
    fmt.Println(result.ToInt32())
}
Runtime Options: memory, stack, GC, ...
package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()

    // set runtime options
    rt.SetExecuteTimeout(30) // Set execute timeout to 30 seconds
    rt.SetMemoryLimit(256 * 1024) // Set memory limit to 256KB
    rt.SetMaxStackSize(65534) // Set max stack size to 65534
    rt.SetGCThreshold(256 * 1024) // Set GC threshold to 256KB
    rt.SetCanBlock(true) // Set can block to true

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    result := ctx.Eval(`var array = []; while (true) { array.push(null) }`)
    defer result.Free()
    
    if result.IsException() {
        err := ctx.Exception()
        fmt.Println("Memory limit exceeded:", err.Error())
    }
}
ES6 Module Support
package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // enable module import
    rt := quickjs.NewRuntime(quickjs.WithModuleImport(true))
    defer rt.Close()

    ctx := rt.NewContext()
    defer ctx.Close()

    // eval module
    r1 := ctx.EvalFile("./test/hello_module.js")
    defer r1.Free()
    if r1.IsException() {
        err := ctx.Exception()
        panic(err)
    }

    // load module
    r2 := ctx.LoadModuleFile("./test/fib_module.js", "fib_foo")
    defer r2.Free()
    if r2.IsException() {
        err := ctx.Exception()
        panic(err)
    }

    // call module
    r3 := ctx.Eval(`
    import {fib} from 'fib_foo';
    globalThis.result = fib(9);
    `)
    defer r3.Free()
    if r3.IsException() {
        err := ctx.Exception()
        panic(err)
    }

    result := ctx.Globals().Get("result")
    defer result.Free()
    fmt.Println("Fibonacci result:", result.ToInt32())
}

Documentation

Overview

Package quickjs Go bindings to QuickJS: a fast, small, and embeddable ES2020 JavaScript interpreter

Example
package main

import (
	"fmt"

	"github.com/buke/quickjs-go"
)

// User represents a common user struct for demonstrating Marshal and Class features
type User struct {
	ID       int64     `js:"id"`
	Name     string    `js:"name"`
	Email    string    `js:"email"`
	Age      int       `js:"age"`
	IsActive bool      `js:"is_active"`
	Scores   []float32 `js:"scores"` // Demonstrates TypedArray support
}

// GetFullInfo returns the user's full information
func (u *User) GetFullInfo() string {
	return fmt.Sprintf("%s (%s) - Age: %d", u.Name, u.Email, u.Age)
}

// GetAverageScore calculates the average score
func (u *User) GetAverageScore() float64 {
	if len(u.Scores) == 0 {
		return 0
	}
	var sum float32
	for _, score := range u.Scores {
		sum += score
	}
	return float64(sum) / float64(len(u.Scores))
}

func main() {
	// Create a new runtime
	rt := quickjs.NewRuntime()
	defer rt.Close()

	// Create a new context
	ctx := rt.NewContext()
	defer ctx.Close()

	// Create a new object
	test := ctx.NewObject()
	defer test.Free()
	// bind properties to the object
	test.Set("A", ctx.NewString("String A"))
	test.Set("B", ctx.NewInt32(0))
	test.Set("C", ctx.NewBool(false))
	// bind go function to js object - UPDATED: function signature now uses pointers
	test.Set("hello", ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
		return ctx.NewString("Hello " + args[0].ToString())
	}))

	// bind "test" object to global object
	ctx.Globals().Set("test", test)

	// call js function by js - FIXED: removed error handling
	js_ret := ctx.Eval(`test.hello("Javascript!")`)
	defer js_ret.Free()
	// Check for exceptions instead of error
	if js_ret.IsException() {
		err := ctx.Exception()
		fmt.Printf("Error: %v\n", err)
		return
	}
	fmt.Println(js_ret.ToString())

	// call js function by go
	go_ret := ctx.Globals().Get("test").Call("hello", ctx.NewString("Golang!"))
	defer go_ret.Free()
	fmt.Println(go_ret.ToString())

	// bind go function to Javascript async function using Function + Promise - UPDATED: function signature now uses pointers
	ctx.Globals().Set("testAsync", ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
		return ctx.NewPromise(func(resolve, reject func(*quickjs.Value)) {
			resolve(ctx.NewString("Hello Async Function!"))
		})
	}))

	ret := ctx.Eval(`
        var ret;
        testAsync().then(v => ret = v)
    `)
	defer ret.Free()
	// Check for exceptions instead of error
	if ret.IsException() {
		err := ctx.Exception()
		fmt.Printf("Error: %v\n", err)
		return
	}

	// wait for promise resolve
	ctx.Loop()

	asyncRet := ctx.Eval("ret")
	defer asyncRet.Free()
	// Check for exceptions instead of error
	if asyncRet.IsException() {
		err := ctx.Exception()
		fmt.Printf("Error: %v\n", err)
		return
	}
	fmt.Println(asyncRet.ToString())

	// Demonstrate TypedArray functionality
	floatData := []float32{95.5, 87.2, 92.0}
	typedArray := ctx.NewFloat32Array(floatData)
	ctx.Globals().Set("floatData", typedArray)

	arrayResult := ctx.Eval(`floatData instanceof Float32Array`)
	defer arrayResult.Free()
	// Check for exceptions instead of error
	if arrayResult.IsException() {
		err := ctx.Exception()
		fmt.Printf("Error: %v\n", err)
		return
	}
	fmt.Println("TypedArray:", arrayResult.ToBool())

	// Demonstrate Marshal/Unmarshal functionality with User struct
	user := User{
		ID:       123,
		Name:     "Alice",
		Email:    "alice@example.com",
		Age:      25,
		IsActive: true,
		Scores:   []float32{95.5, 87.2, 92.0},
	}

	jsVal, err := ctx.Marshal(user)
	if err != nil {
		fmt.Printf("Marshal error: %v\n", err)
		return
	}
	ctx.Globals().Set("userData", jsVal)

	marshalResult := ctx.Eval(`userData.name + " avg: " + (userData.scores.reduce((s,v) => s+v) / userData.scores.length).toFixed(1)`)
	defer marshalResult.Free()
	// Check for exceptions instead of error
	if marshalResult.IsException() {
		err := ctx.Exception()
		fmt.Printf("Error: %v\n", err)
		return
	}
	fmt.Println("Marshal:", marshalResult.ToString())

	// Demonstrate Class Binding functionality with the same User struct
	userConstructor, _ := ctx.BindClass(&User{})
	if userConstructor.IsException() {
		defer userConstructor.Free()
		err := ctx.Exception()
		fmt.Printf("BindClass error: %v\n", err)
		return
	}

	ctx.Globals().Set("User", userConstructor)

	classResult := ctx.Eval(`
        const user = new User({
            id: 456,
            name: "Bob",
            email: "bob@example.com",
            age: 30,
            is_active: true,
            scores: [88.0, 92.5, 85.0]
        });
        user.GetAverageScore().toFixed(1)
    `)
	defer classResult.Free()
	// Check for exceptions instead of error
	if classResult.IsException() {
		err := ctx.Exception()
		fmt.Printf("Error: %v\n", err)
		return
	}
	fmt.Println("Class binding:", classResult.ToString())

}
Output:

Hello Javascript!
Hello Golang!
Hello Async Function!
TypedArray: true
Marshal: Alice avg: 91.6
Class binding: 88.5

Index

Examples

Constants

View Source
const (
	PropertyConfigurable = 1 << 0 // JS_PROP_CONFIGURABLE
	PropertyWritable     = 1 << 1 // JS_PROP_WRITABLE
	PropertyEnumerable   = 1 << 2 // JS_PROP_ENUMERABLE

	// Default property flags (writable, enumerable, configurable)
	PropertyDefault = PropertyConfigurable | PropertyWritable | PropertyEnumerable
)

Property flags constants matching QuickJS - unchanged

Variables

This section is empty.

Functions

This section is empty.

Types

type AccessorEntry added in v0.5.7

type AccessorEntry struct {
	Name   string          // Accessor name in JavaScript
	Getter ClassGetterFunc // Optional getter function
	Setter ClassSetterFunc // Optional setter function
	Static bool            // true for static accessors, false for instance accessors
}

AccessorEntry represents an accessor binding configuration - unchanged

type Atom

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

Atom represents a QuickJS atom - unique strings used for object property names. Object property names and some strings are stored as Atoms (unique strings) to save memory and allow fast comparison. Atoms are represented as a 32 bit integer. Half of the atom range is reserved for immediate integer literals from 0 to 2^{31}-1.

func (*Atom) Free

func (a *Atom) Free()

Free decrements the reference count of the atom.

func (*Atom) String

func (a *Atom) String() string

String returns the string representation of the atom. This method implements the fmt.Stringer interface. Deprecated: Use ToString() instead.

func (*Atom) ToString added in v0.5.12

func (a *Atom) ToString() string

ToString returns the string representation of the atom.

func (*Atom) ToValue added in v0.5.12

func (a *Atom) ToValue() *Value

ToValue returns the value representation of the atom.

func (*Atom) Value

func (a *Atom) Value() *Value

Value returns the value representation of the atom. Deprecated: Use ToValue() instead.

type ClassBuilder added in v0.5.6

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

ClassBuilder provides a fluent API for building JavaScript classes Uses builder pattern for easy and readable class definition MODIFIED FOR SCHEME C: Now stores complete class definition including instance properties

func NewClassBuilder added in v0.5.6

func NewClassBuilder(name string) *ClassBuilder

NewClassBuilder creates a new ClassBuilder with the specified name This is the entry point for building JavaScript classes

func (*ClassBuilder) Accessor added in v0.5.7

func (cb *ClassBuilder) Accessor(name string, getter ClassGetterFunc, setter ClassSetterFunc) *ClassBuilder

Accessor adds a read-write accessor to the class instance - unchanged Pass nil for getter to create write-only accessor Pass nil for setter to create read-only accessor

func (*ClassBuilder) Build added in v0.5.6

func (cb *ClassBuilder) Build(ctx *Context) (*Value, uint32)

Build creates and registers the JavaScript class in the given context Returns the constructor function and classID for NewInstance

func (*ClassBuilder) Constructor added in v0.5.6

func (cb *ClassBuilder) Constructor(fn ClassConstructorFunc) *ClassBuilder

Constructor sets the constructor function for the class MODIFIED FOR SCHEME C: Now uses new constructor signature The constructor function will be called with pre-created instance

func (*ClassBuilder) Method added in v0.5.6

func (cb *ClassBuilder) Method(name string, fn ClassMethodFunc) *ClassBuilder

Method adds an instance method to the class - unchanged Instance methods are called on object instances

func (*ClassBuilder) Property added in v0.5.6

func (cb *ClassBuilder) Property(name string, value *Value, flags ...int) *ClassBuilder

Property adds a data property to the class instance - changed to use pointer Default flags: writable, enumerable, configurable SCHEME C: Instance properties will be bound during instance creation

func (*ClassBuilder) StaticAccessor added in v0.5.7

func (cb *ClassBuilder) StaticAccessor(name string, getter ClassGetterFunc, setter ClassSetterFunc) *ClassBuilder

StaticAccessor adds a read-write static accessor to the class constructor - unchanged Pass nil for getter to create write-only accessor Pass nil for setter to create read-only accessor

func (*ClassBuilder) StaticMethod added in v0.5.6

func (cb *ClassBuilder) StaticMethod(name string, fn ClassMethodFunc) *ClassBuilder

StaticMethod adds a static method to the class - unchanged Static methods are called on the constructor function itself

func (*ClassBuilder) StaticProperty added in v0.5.6

func (cb *ClassBuilder) StaticProperty(name string, value *Value, flags ...int) *ClassBuilder

StaticProperty adds a data property to the class constructor - changed to use pointer Default flags: writable, enumerable, configurable

type ClassConstructorFunc added in v0.5.6

type ClassConstructorFunc func(ctx *Context, instance *Value, args []*Value) (interface{}, error)

MODIFIED FOR SCHEME C: ClassConstructorFunc signature changed Constructor now receives pre-created instance and returns Go object to associate This aligns with Scheme C design where instances are pre-created with bound properties

type ClassFinalizer added in v0.5.6

type ClassFinalizer interface {
	Finalize()
}

Optional cleanup interface for class instances Objects implementing this interface will have Finalize() called automatically when the JavaScript object is garbage collected

type ClassGetterFunc added in v0.5.6

type ClassGetterFunc func(ctx *Context, this *Value) *Value

ClassGetterFunc represents accessor getter functions - changed to use pointers Corresponds to QuickJS JSCFunctionType.getter_magic

type ClassMethodFunc added in v0.5.6

type ClassMethodFunc func(ctx *Context, this *Value, args []*Value) *Value

ClassMethodFunc represents both instance and static methods - changed to use pointers this parameter represents the object instance for instance methods, or the constructor function for static methods Corresponds to QuickJS JSCFunctionType.generic_magic

type ClassSetterFunc added in v0.5.6

type ClassSetterFunc func(ctx *Context, this *Value, value *Value) *Value

ClassSetterFunc represents accessor setter functions - changed to use pointers Returns the set value or an exception Corresponds to QuickJS JSCFunctionType.setter_magic

type Context

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

Context represents a Javascript context (or Realm). Each JSContext has its own global objects and system objects. There can be several JSContexts per JSRuntime and they can share objects, similar to frames of the same origin sharing Javascript objects in a web browser.

func (*Context) ArrayBuffer added in v0.1.13

func (ctx *Context) ArrayBuffer(binaryData []byte) *Value

ArrayBuffer returns a ArrayBuffer value with given binary data. Deprecated: Use NewArrayBuffer() instead.

func (*Context) AsyncFunction deprecated added in v0.1.2

func (ctx *Context) AsyncFunction(asyncFn func(ctx *Context, this *Value, promise *Value, args []*Value) *Value) *Value

AsyncFunction returns a js async function value with given function template

Deprecated: Use Context.NewFunction + Context.NewPromise instead for better memory management and thread safety. Example:

asyncFn := ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
    return ctx.NewPromise(func(resolve, reject func(*quickjs.Value)) {
        // async work here
        resolve(ctx.NewString("result"))
    })
})

func (*Context) Atom

func (ctx *Context) Atom(v string) *Atom

Atom returns a new Atom value with given string. Deprecated: Use NewAtom() instead.

func (*Context) AtomIdx

func (ctx *Context) AtomIdx(idx uint32) *Atom

AtomIdx returns a new Atom value with given idx. Deprecated: Use NewAtomIdx() instead.

func (*Context) Await added in v0.4.8

func (ctx *Context) Await(v *Value) *Value

Wait for a promise and execute pending jobs while waiting for it. Return the promise result or JS_EXCEPTION in case of promise rejection.

func (*Context) BigInt64

func (ctx *Context) BigInt64(v int64) *Value

BigInt64 returns a int64 value with given uint64. Deprecated: Use NewBigInt64() instead.

func (*Context) BigInt64Array added in v0.5.4

func (ctx *Context) BigInt64Array(data []int64) *Value

BigInt64Array returns a BigInt64Array value with given int64 slice. Deprecated: Use NewBigInt64Array() instead.

func (*Context) BigUint64

func (ctx *Context) BigUint64(v uint64) *Value

BigUint64 returns a uint64 value with given uint64. Deprecated: Use NewBigUint64() instead.

func (*Context) BigUint64Array added in v0.5.4

func (ctx *Context) BigUint64Array(data []uint64) *Value

BigUint64Array returns a BigUint64Array value with given uint64 slice. Deprecated: Use NewBigUint64Array() instead.

func (*Context) BindClass added in v0.5.6

func (ctx *Context) BindClass(structType interface{}, options ...ReflectOption) (*Value, uint32)

BindClass automatically creates and builds a JavaScript class from a Go struct type using reflection. This is a convenience method that combines BindClassBuilder and Build. Only exported fields and methods are bound to maintain Go encapsulation principles.

Example usage:

constructor, classID, err := ctx.BindClass(&MyStruct{})
if err != nil { return err }
ctx.Globals().Set("MyStruct", constructor)

func (*Context) BindClassBuilder added in v0.5.6

func (ctx *Context) BindClassBuilder(structType interface{}, options ...ReflectOption) (*ClassBuilder, error)

BindClassBuilder automatically creates a ClassBuilder from a Go struct type using reflection. Returns a ClassBuilder that can be further customized using chain methods before Build(). Only exported fields and methods are analyzed to maintain Go encapsulation principles.

Example usage:

builder, err := ctx.BindClassBuilder(&MyStruct{})
if err != nil { return err }
constructor, classID, err := builder.Build(ctx)

// Or with additional customization:
builder, err := ctx.BindClassBuilder(&MyStruct{})
if err != nil { return err }
constructor, classID, err := builder.
    StaticMethod("Create", myCreateFunc).
    ReadOnlyAccessor("version", myVersionGetter).
    Build(ctx)

func (*Context) Bool

func (ctx *Context) Bool(b bool) *Value

Bool returns a bool value with given bool. Deprecated: Use NewBool() instead.

func (*Context) Close

func (ctx *Context) Close()

Free will free context and all associated objects.

func (*Context) Compile

func (ctx *Context) Compile(code string, opts ...EvalOption) ([]byte, error)

Compile returns a compiled bytecode with given code.

func (*Context) CompileFile

func (ctx *Context) CompileFile(filePath string, opts ...EvalOption) ([]byte, error)

Compile returns a compiled bytecode with given filename.

func (*Context) CompileModule added in v0.4.14

func (ctx *Context) CompileModule(filePath string, moduleName string, opts ...EvalOption) ([]byte, error)

CompileModule returns a compiled bytecode with given code and module name.

func (*Context) Error

func (ctx *Context) Error(err error) *Value

Error returns a new exception value with given message. Deprecated: Use NewError() instead.

func (*Context) Eval

func (ctx *Context) Eval(code string, opts ...EvalOption) *Value

Eval returns a js value with given code. Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`. func (ctx *Context) Eval(code string) (*Value, error) { return ctx.EvalFile(code, "code") }

func (*Context) EvalBytecode

func (ctx *Context) EvalBytecode(buf []byte) *Value

EvalBytecode returns a js value with given bytecode. Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`.

func (*Context) EvalFile

func (ctx *Context) EvalFile(filePath string, opts ...EvalOption) *Value

EvalFile returns a js value with given code and filename. Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`.

func (*Context) Exception

func (ctx *Context) Exception() error

Exception returns a context's exception value.

func (*Context) Float32Array added in v0.5.4

func (ctx *Context) Float32Array(data []float32) *Value

Float32Array returns a Float32Array value with given float32 slice. Deprecated: Use NewFloat32Array() instead.

func (*Context) Float64

func (ctx *Context) Float64(v float64) *Value

Float64 returns a float64 value with given float64. Deprecated: Use NewFloat64() instead.

func (*Context) Float64Array added in v0.5.4

func (ctx *Context) Float64Array(data []float64) *Value

Float64Array returns a Float64Array value with given float64 slice. Deprecated: Use NewFloat64Array() instead.

func (*Context) Function

func (ctx *Context) Function(fn func(*Context, *Value, []*Value) *Value) *Value

Function returns a js function value with given function template New implementation using HandleStore and JS_NewCFunction2 with magic parameter Deprecated: Use NewFunction() instead.

func (*Context) Globals

func (ctx *Context) Globals() *Value

Global returns a context's global object.

func (*Context) HasException added in v0.5.3

func (ctx *Context) HasException() bool

HasException checks if the context has an exception set.

func (*Context) Int16Array added in v0.5.4

func (ctx *Context) Int16Array(data []int16) *Value

Int16Array returns a Int16Array value with given int16 slice. Deprecated: Use NewInt16Array() instead.

func (*Context) Int32

func (ctx *Context) Int32(v int32) *Value

Int32 returns a int32 value with given int32. Deprecated: Use NewInt32() instead.

func (*Context) Int32Array added in v0.5.4

func (ctx *Context) Int32Array(data []int32) *Value

Int32Array returns a Int32Array value with given int32 slice. Deprecated: Use NewInt32Array() instead.

func (*Context) Int64

func (ctx *Context) Int64(v int64) *Value

Int64 returns a int64 value with given int64. Deprecated: Use NewInt64() instead.

func (*Context) Int8Array added in v0.5.4

func (ctx *Context) Int8Array(data []int8) *Value

Int8Array returns a Int8Array value with given int8 slice. Deprecated: Use NewInt8Array() instead.

func (*Context) Invoke added in v0.1.3

func (ctx *Context) Invoke(fn *Value, this *Value, args ...*Value) *Value

Invoke invokes a function with given this value and arguments. Deprecated: Use Value.Execute() instead for better API consistency.

func (*Context) LoadModule added in v0.4.10

func (ctx *Context) LoadModule(code string, moduleName string, opts ...EvalOption) *Value

LoadModule returns a js value with given code and module name.

func (*Context) LoadModuleBytecode added in v0.4.10

func (ctx *Context) LoadModuleBytecode(buf []byte, opts ...EvalOption) *Value

LoadModuleByteCode returns a js value with given bytecode and module name.

func (*Context) LoadModuleFile added in v0.4.10

func (ctx *Context) LoadModuleFile(filePath string, moduleName string) *Value

LoadModuleFile returns a js value with given file path and module name.

func (*Context) Loop added in v0.3.3

func (ctx *Context) Loop()

Loop runs the context's event loop.

func (*Context) Marshal added in v0.5.3

func (ctx *Context) Marshal(v interface{}) (*Value, error)

Marshal returns the JavaScript value encoding of v. It traverses the value v recursively and creates corresponding JavaScript values.

Marshal uses the following type mappings:

  • bool -> JavaScript boolean
  • int, int8, int16, int32 -> JavaScript number (32-bit)
  • int64 -> JavaScript number (64-bit)
  • uint, uint8, uint16, uint32 -> JavaScript number (32-bit unsigned)
  • uint64 -> JavaScript BigInt
  • float32, float64 -> JavaScript number
  • string -> JavaScript string
  • []byte -> JavaScript ArrayBuffer
  • []int8 -> JavaScript Int8Array
  • []int16 -> JavaScript Int16Array
  • []uint16 -> JavaScript Uint16Array
  • []int32 -> JavaScript Int32Array
  • []uint32 -> JavaScript Uint32Array
  • []float32 -> JavaScript Float32Array
  • []float64 -> JavaScript Float64Array
  • []int64 -> JavaScript BigInt64Array
  • []uint64 -> JavaScript BigUint64Array
  • slice/array -> JavaScript Array
  • map -> JavaScript Object
  • struct -> JavaScript Object
  • pointer -> recursively marshal the pointed value (nil becomes null)

Struct fields are marshaled using their field names unless a tag is present. The "js" and "json" tags are supported. Fields with tag "-" are ignored.

Types implementing the Marshaler interface are marshaled using their MarshalJS method.

func (*Context) NewArrayBuffer added in v0.5.12

func (ctx *Context) NewArrayBuffer(binaryData []byte) *Value

NewArrayBuffer returns a ArrayBuffer value with given binary data.

func (*Context) NewAsyncFunction deprecated added in v0.5.12

func (ctx *Context) NewAsyncFunction(asyncFn func(ctx *Context, this *Value, promise *Value, args []*Value) *Value) *Value

NewAsyncFunction returns a js async function value with given function template

Deprecated: Use Context.NewFunction + Context.NewPromise instead for better memory management and thread safety. Example:

asyncFn := ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Value) *quickjs.Value {
    return ctx.NewPromise(func(resolve, reject func(*quickjs.Value)) {
        // async work here
        resolve(ctx.NewString("result"))
    })
})

func (*Context) NewAtom added in v0.5.12

func (ctx *Context) NewAtom(v string) *Atom

NewAtom returns a new Atom value with given string.

func (*Context) NewAtomIdx added in v0.5.12

func (ctx *Context) NewAtomIdx(idx uint32) *Atom

NewAtomIdx returns a new Atom value with given idx.

func (*Context) NewBigInt64 added in v0.5.12

func (ctx *Context) NewBigInt64(v int64) *Value

NewBigInt64 returns a int64 value with given uint64.

func (*Context) NewBigInt64Array added in v0.5.12

func (ctx *Context) NewBigInt64Array(data []int64) *Value

NewBigInt64Array returns a BigInt64Array value with given int64 slice.

func (*Context) NewBigUint64 added in v0.5.12

func (ctx *Context) NewBigUint64(v uint64) *Value

NewBigUint64 returns a uint64 value with given uint64.

func (*Context) NewBigUint64Array added in v0.5.12

func (ctx *Context) NewBigUint64Array(data []uint64) *Value

NewBigUint64Array returns a BigUint64Array value with given uint64 slice.

func (*Context) NewBool added in v0.5.12

func (ctx *Context) NewBool(b bool) *Value

NewBool returns a bool value with given bool.

func (*Context) NewError added in v0.5.12

func (ctx *Context) NewError(err error) *Value

NewError returns a new exception value with given message.

func (*Context) NewFloat32Array added in v0.5.12

func (ctx *Context) NewFloat32Array(data []float32) *Value

NewFloat32Array returns a Float32Array value with given float32 slice.

func (*Context) NewFloat64 added in v0.5.12

func (ctx *Context) NewFloat64(v float64) *Value

NewFloat64 returns a float64 value with given float64.

func (*Context) NewFloat64Array added in v0.5.12

func (ctx *Context) NewFloat64Array(data []float64) *Value

NewFloat64Array returns a Float64Array value with given float64 slice.

func (*Context) NewFunction added in v0.5.12

func (ctx *Context) NewFunction(fn func(*Context, *Value, []*Value) *Value) *Value

NewFunction returns a js function value with given function template New implementation using HandleStore and JS_NewCFunction2 with magic parameter

func (*Context) NewInt16Array added in v0.5.12

func (ctx *Context) NewInt16Array(data []int16) *Value

NewInt16Array returns a Int16Array value with given int16 slice.

func (*Context) NewInt32 added in v0.5.12

func (ctx *Context) NewInt32(v int32) *Value

NewInt32 returns a int32 value with given int32.

func (*Context) NewInt32Array added in v0.5.12

func (ctx *Context) NewInt32Array(data []int32) *Value

NewInt32Array returns a Int32Array value with given int32 slice.

func (*Context) NewInt64 added in v0.5.12

func (ctx *Context) NewInt64(v int64) *Value

NewInt64 returns a int64 value with given int64.

func (*Context) NewInt8Array added in v0.5.12

func (ctx *Context) NewInt8Array(data []int8) *Value

NewInt8Array returns a Int8Array value with given int8 slice.

func (*Context) NewNull added in v0.5.12

func (ctx *Context) NewNull() *Value

NewNull returns a null value.

func (*Context) NewObject added in v0.5.12

func (ctx *Context) NewObject() *Value

NewObject returns a new object value.

func (*Context) NewPromise added in v0.5.12

func (ctx *Context) NewPromise(executor func(resolve, reject func(*Value))) *Value

NewPromise creates a new Promise with executor function Executor runs synchronously in current thread for thread safety

func (*Context) NewString added in v0.5.12

func (ctx *Context) NewString(v string) *Value

NewString returns a string value with given string.

func (*Context) NewUint16Array added in v0.5.12

func (ctx *Context) NewUint16Array(data []uint16) *Value

NewUint16Array returns a Uint16Array value with given uint16 slice.

func (*Context) NewUint32 added in v0.5.12

func (ctx *Context) NewUint32(v uint32) *Value

NewUint32 returns a uint32 value with given uint32.

func (*Context) NewUint32Array added in v0.5.12

func (ctx *Context) NewUint32Array(data []uint32) *Value

NewUint32Array returns a Uint32Array value with given uint32 slice.

func (*Context) NewUint8Array added in v0.5.12

func (ctx *Context) NewUint8Array(data []uint8) *Value

NewUint8Array returns a Uint8Array value with given uint8 slice.

func (*Context) NewUint8ClampedArray added in v0.5.12

func (ctx *Context) NewUint8ClampedArray(data []uint8) *Value

NewUint8ClampedArray returns a Uint8ClampedArray value with given uint8 slice.

func (*Context) NewUndefined added in v0.5.12

func (ctx *Context) NewUndefined() *Value

NewUndefined returns a undefined value.

func (*Context) NewUninitialized added in v0.5.12

func (ctx *Context) NewUninitialized() *Value

NewUninitialized returns a uninitialized value.

func (*Context) Null

func (ctx *Context) Null() *Value

Null return a null value. Deprecated: Use NewNull() instead.

func (*Context) Object

func (ctx *Context) Object() *Value

Object returns a new object value. Deprecated: Use NewObject() instead.

func (*Context) ParseJSON added in v0.1.11

func (ctx *Context) ParseJSON(v string) *Value

ParseJson parses given json string and returns a object value.

func (*Context) Promise added in v0.5.5

func (ctx *Context) Promise(executor func(resolve, reject func(*Value))) *Value

Promise creates a new Promise with executor function Executor runs synchronously in current thread for thread safety Deprecated: Use NewPromise() instead.

func (*Context) Runtime added in v0.4.6

func (ctx *Context) Runtime() *Runtime

Runtime returns the runtime of the context.

func (*Context) SetInterruptHandler deprecated added in v0.1.14

func (ctx *Context) SetInterruptHandler(handler InterruptHandler)

SetInterruptHandler sets a interrupt handler.

Deprecated: Use SetInterruptHandler on runtime instead

func (*Context) String

func (ctx *Context) String(v string) *Value

String returns a string value with given string. Deprecated: Use NewString() instead.

func (*Context) Throw

func (ctx *Context) Throw(v *Value) *Value

Throw returns a context's exception value.

func (*Context) ThrowError

func (ctx *Context) ThrowError(err error) *Value

ThrowError returns a context's exception value with given error message.

func (*Context) ThrowInternalError

func (ctx *Context) ThrowInternalError(format string, args ...interface{}) *Value

ThrowInternalError returns a context's exception value with given error message.

func (*Context) ThrowRangeError

func (ctx *Context) ThrowRangeError(format string, args ...interface{}) *Value

ThrowRangeError returns a context's exception value with given error message.

func (*Context) ThrowReferenceError

func (ctx *Context) ThrowReferenceError(format string, args ...interface{}) *Value

ThrowReferenceError returns a context's exception value with given error message.

func (*Context) ThrowSyntaxError

func (ctx *Context) ThrowSyntaxError(format string, args ...interface{}) *Value

ThrowSyntaxError returns a context's exception value with given error message.

func (*Context) ThrowTypeError

func (ctx *Context) ThrowTypeError(format string, args ...interface{}) *Value

ThrowTypeError returns a context's exception value with given error message.

func (*Context) Uint16Array added in v0.5.4

func (ctx *Context) Uint16Array(data []uint16) *Value

Uint16Array returns a Uint16Array value with given uint16 slice. Deprecated: Use NewUint16Array() instead.

func (*Context) Uint32

func (ctx *Context) Uint32(v uint32) *Value

Uint32 returns a uint32 value with given uint32. Deprecated: Use NewUint32() instead.

func (*Context) Uint32Array added in v0.5.4

func (ctx *Context) Uint32Array(data []uint32) *Value

Uint32Array returns a Uint32Array value with given uint32 slice. Deprecated: Use NewUint32Array() instead.

func (*Context) Uint8Array added in v0.5.4

func (ctx *Context) Uint8Array(data []uint8) *Value

Uint8Array returns a Uint8Array value with given uint8 slice. Deprecated: Use NewUint8Array() instead.

func (*Context) Uint8ClampedArray added in v0.5.4

func (ctx *Context) Uint8ClampedArray(data []uint8) *Value

Uint8ClampedArray returns a Uint8ClampedArray value with given uint8 slice. Deprecated: Use NewUint8ClampedArray() instead.

func (*Context) Undefined

func (ctx *Context) Undefined() *Value

Undefined return a undefined value. Deprecated: Use NewUndefined() instead.

func (*Context) Uninitialized

func (ctx *Context) Uninitialized() *Value

Uninitialized returns a uninitialized value. Deprecated: Use NewUninitialized() instead.

func (*Context) Unmarshal added in v0.5.3

func (ctx *Context) Unmarshal(jsVal *Value, v interface{}) error

Unmarshal parses the JavaScript value and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an error.

Unmarshal uses the inverse of the encodings that Marshal uses, with the following additional rules:

  • JavaScript null/undefined -> Go nil pointer or zero value
  • JavaScript Array -> Go slice/array
  • JavaScript Object -> Go map/struct
  • JavaScript number -> Go numeric types (with appropriate conversion)
  • JavaScript BigInt -> Go uint64/int64/*big.Int
  • JavaScript ArrayBuffer -> Go []byte
  • JavaScript Int8Array -> Go []int8
  • JavaScript Int16Array -> Go []int16
  • JavaScript Uint16Array -> Go []uint16
  • JavaScript Int32Array -> Go []int32
  • JavaScript Uint32Array -> Go []uint32
  • JavaScript Float32Array -> Go []float32
  • JavaScript Float64Array -> Go []float64
  • JavaScript BigInt64Array -> Go []int64
  • JavaScript BigUint64Array -> Go []uint64

When unmarshaling into an interface{}, Unmarshal stores one of:

  • nil for JavaScript null/undefined
  • bool for JavaScript boolean
  • int64 for JavaScript integer numbers
  • float64 for JavaScript floating-point numbers
  • string for JavaScript string
  • []interface{} for JavaScript Array
  • map[string]interface{} for JavaScript Object

Types implementing the Unmarshaler interface are unmarshaled using their UnmarshalJS method.

type Error

type Error struct {
	Name       string // Error name (e.g., "TypeError", "ReferenceError")
	Message    string // Error message
	Cause      string // Error cause
	Stack      string // Stack trace
	JSONString string // Serialized JSON string
}

Error represents a JavaScript error with detailed information.

func (*Error) Error

func (err *Error) Error() string

Error implements the error interface.

type EvalOption added in v0.4.10

type EvalOption func(*EvalOptions)

func EvalAwait added in v0.4.10

func EvalAwait(await bool) EvalOption

func EvalFileName added in v0.4.10

func EvalFileName(filename string) EvalOption

func EvalFlagCompileOnly added in v0.4.10

func EvalFlagCompileOnly(compileOnly bool) EvalOption

func EvalFlagGlobal added in v0.4.10

func EvalFlagGlobal(global bool) EvalOption

func EvalFlagModule added in v0.4.10

func EvalFlagModule(module bool) EvalOption

func EvalFlagStrict added in v0.4.10

func EvalFlagStrict(strict bool) EvalOption

func EvalLoadOnly added in v0.5.3

func EvalLoadOnly(loadOnly bool) EvalOption

type EvalOptions added in v0.4.10

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

type FieldTagInfo added in v0.5.6

type FieldTagInfo struct {
	Name      string // JavaScript property name
	Skip      bool   // Whether to skip this field
	OmitEmpty bool   // Whether to omit empty values (for serialization)
}

FieldTagInfo contains parsed field tag information

type InterruptHandler added in v0.1.14

type InterruptHandler func() int

InterruptHandler is a function type for interrupt handler. Return != 0 if the JS code needs to be interrupted

type Marshaler added in v0.5.3

type Marshaler interface {
	MarshalJS(ctx *Context) (*Value, error)
}

Marshaler is the interface implemented by types that can marshal themselves into a JavaScript value.

type MethodEntry added in v0.5.6

type MethodEntry struct {
	Name   string          // Method name in JavaScript
	Func   ClassMethodFunc // Method implementation function
	Static bool            // true for static methods, false for instance methods
	Length int             // Expected parameter count, 0 for default
}

MethodEntry represents a method binding configuration - unchanged

type ModuleBuilder added in v0.5.8

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

ModuleBuilder provides a fluent API for building JavaScript modules Uses builder pattern for easy and readable module definition

func NewModuleBuilder added in v0.5.8

func NewModuleBuilder(name string) *ModuleBuilder

NewModuleBuilder creates a new ModuleBuilder with the specified name This is the entry point for building JavaScript modules

func (*ModuleBuilder) Build added in v0.5.8

func (mb *ModuleBuilder) Build(ctx *Context) error

Build creates and registers the JavaScript module in the given context The module will be available for import in JavaScript code

func (*ModuleBuilder) Export added in v0.5.8

func (mb *ModuleBuilder) Export(name string, value *Value) *ModuleBuilder

Export adds an export to the module This is the core method that handles all types of exports including default For default export, use name="default"

type ModuleExportEntry added in v0.5.8

type ModuleExportEntry struct {
	Name  string // Export name ("default" for default export)
	Value *Value // Export value - changed to pointer type
}

ModuleExportEntry represents a single module export

type Option added in v0.4.7

type Option func(*Options)

func WithCanBlock added in v0.4.7

func WithCanBlock(canBlock bool) Option

WithCanBlock will set the runtime's can block; default is true

func WithExecuteTimeout added in v0.4.7

func WithExecuteTimeout(timeout uint64) Option

WithExecuteTimeout will set the runtime's execute timeout; default is 0

func WithGCThreshold added in v0.4.7

func WithGCThreshold(gcThreshold int64) Option

WithGCThreshold will set the runtime's GC threshold; default is -1 to disable automatic GC.

func WithMaxStackSize added in v0.4.7

func WithMaxStackSize(maxStackSize uint64) Option

WithMaxStackSize will set max runtime's stack size; default is 0 disable maximum stack size check

func WithMemoryLimit added in v0.4.7

func WithMemoryLimit(memoryLimit uint64) Option

WithMemoryLimit will set the runtime memory limit; if not set, it will be unlimit.

func WithModuleImport added in v0.4.10

func WithModuleImport(moduleImport bool) Option

func WithStripInfo added in v0.5.0

func WithStripInfo(strip int) Option

type Options added in v0.4.7

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

type PromiseState added in v0.5.5

type PromiseState int

Promise state enumeration matching QuickJS

const (
	PromisePending PromiseState = iota
	PromiseFulfilled
	PromiseRejected
)

type PropertyEntry added in v0.5.6

type PropertyEntry struct {
	Name   string // Property name in JavaScript
	Value  *Value // Property value (JavaScript Value) - changed to pointer
	Static bool   // true for static properties, false for instance properties
	Flags  int    // Property flags (writable, enumerable, configurable)
}

PropertyEntry represents a property binding configuration - changed to use pointer

type ReflectOption added in v0.5.6

type ReflectOption func(*ReflectOptions)

ReflectOption configures ReflectOptions using functional options pattern

func WithIgnoredFields added in v0.5.6

func WithIgnoredFields(fields ...string) ReflectOption

WithIgnoredFields specifies field names to skip during binding

func WithIgnoredMethods added in v0.5.6

func WithIgnoredMethods(methods ...string) ReflectOption

WithIgnoredMethods specifies method names to skip during binding

func WithMethodPrefix added in v0.5.6

func WithMethodPrefix(prefix string) ReflectOption

WithMethodPrefix filters methods by name prefix

type ReflectOptions added in v0.5.6

type ReflectOptions struct {
	// MethodPrefix filters methods by prefix (empty = all methods)
	MethodPrefix string

	// IgnoredMethods lists method names to skip during binding
	IgnoredMethods []string

	// IgnoredFields lists field names to skip during binding
	IgnoredFields []string
}

ReflectOptions configures automatic class binding behavior

type Runtime

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

Runtime represents a Javascript runtime with simplified interrupt handling

func NewRuntime

func NewRuntime(opts ...Option) *Runtime

NewRuntime creates a new quickjs runtime with simplified interrupt handling.

func (*Runtime) ClearInterruptHandler added in v0.5.5

func (r *Runtime) ClearInterruptHandler()

ClearInterruptHandler clears the user interrupt handler

func (*Runtime) Close

func (r *Runtime) Close()

Close will free the runtime pointer with proper cleanup.

func (*Runtime) NewContext

func (r *Runtime) NewContext() *Context

NewContext creates a new JavaScript context.

func (*Runtime) RunGC

func (r *Runtime) RunGC()

RunGC will call quickjs's garbage collector.

func (*Runtime) SetCanBlock added in v0.4.7

func (r *Runtime) SetCanBlock(canBlock bool)

SetCanBlock will set the runtime's can block; default is true

func (*Runtime) SetExecuteTimeout added in v0.4.7

func (r *Runtime) SetExecuteTimeout(timeout uint64)

SetExecuteTimeout will set the runtime's execute timeout; This will override any user interrupt handler (expected behavior)

func (*Runtime) SetGCThreshold

func (r *Runtime) SetGCThreshold(threshold int64)

SetGCThreshold the runtime's GC threshold; use -1 to disable automatic GC.

func (*Runtime) SetInterruptHandler added in v0.5.0

func (r *Runtime) SetInterruptHandler(handler InterruptHandler)

SetInterruptHandler sets a user interrupt handler using simplified approach. This will override any timeout handler (expected behavior)

func (*Runtime) SetMaxStackSize

func (r *Runtime) SetMaxStackSize(stack_size uint64)

SetMaxStackSize will set max runtime's stack size;

func (*Runtime) SetMemoryLimit

func (r *Runtime) SetMemoryLimit(limit uint64)

SetMemoryLimit the runtime memory limit; if not set, it will be unlimit.

func (*Runtime) SetModuleImport added in v0.5.13

func (r *Runtime) SetModuleImport(moduleImport bool)

SetModuleImport sets whether the runtime supports module import.

func (*Runtime) SetStripInfo added in v0.5.0

func (r *Runtime) SetStripInfo(strip int)

SetStripInfo sets the strip info for the runtime.

type Unmarshaler added in v0.5.3

type Unmarshaler interface {
	UnmarshalJS(ctx *Context, val *Value) error
}

Unmarshaler is the interface implemented by types that can unmarshal a JavaScript value into themselves.

type Value

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

Value represents a Javascript value which can be a primitive type or an object. Reference counting is used, so it is important to explicitly duplicate (JS_DupValue(), increment the reference count) or free (JS_FreeValue(), decrement the reference count) JSValues.

func (*Value) Await added in v0.5.5

func (v *Value) Await() *Value

Await waits for promise resolution and executes pending jobs Similar to Context.Await but called on Value directly

func (*Value) BigInt deprecated

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

Deprecated: Use ToBigInt instead.

func (*Value) Bool deprecated

func (v *Value) Bool() bool

Deprecated: Use ToBool instead.

func (*Value) ByteLen added in v0.1.13

func (v *Value) ByteLen() int64

ByteLen returns the length of the ArrayBuffer.

func (*Value) Call

func (v *Value) Call(fname string, args ...*Value) *Value

Call calls the function with the given arguments.

func (*Value) CallConstructor added in v0.4.15

func (v *Value) CallConstructor(args ...*Value) *Value

CallConstructor calls the constructor with the given arguments. SCHEME C: For class instances, use this method to create instances. The class constructor function will receive a pre-created instance and initialize it. Instance properties declared in ClassBuilder.Property() are automatically bound to the instance.

Example usage:

constructor := ctx.Eval("MyClass")
instance := constructor.CallConstructor(arg1, arg2)

This replaces the previous NewInstance method and provides automatic property binding and simplified constructor semantics where constructors work with pre-created instances.

func (*Value) Context

func (v *Value) Context() *Context

Context returns the context of the value.

func (*Value) Delete

func (v *Value) Delete(name string) bool

Delete deletes the property with the given name.

func (*Value) DeleteIdx

func (v *Value) DeleteIdx(idx uint32) bool

DeleteIdx deletes the property with the given index.

func (*Value) Error deprecated

func (v *Value) Error() error

Deprecated: Use ToError() instead.

func (*Value) Execute added in v0.5.0

func (v *Value) Execute(this *Value, args ...*Value) *Value

Execute the function with the given arguments.

func (*Value) Float64 deprecated

func (v *Value) Float64() float64

Deprecated: Use ToFloat64 instead.

func (*Value) Free

func (v *Value) Free()

Free the value.

func (*Value) Get

func (v *Value) Get(name string) *Value

Get returns the value of the property with the given name.

func (*Value) GetClassID added in v0.5.6

func (v *Value) GetClassID() uint32

GetClassID returns the class ID of the value if it's a class instance Returns JS_INVALID_CLASS_ID (0) if not a class instance

func (*Value) GetGoObject added in v0.5.6

func (v *Value) GetGoObject() (interface{}, error)

GetGoObject retrieves Go object from JavaScript class instance This method extracts the opaque data stored by the constructor proxy

func (*Value) GetIdx

func (v *Value) GetIdx(idx int64) *Value

GetIdx returns the value of the property with the given index.

func (*Value) GlobalInstanceof added in v0.5.0

func (v *Value) GlobalInstanceof(name string) bool

GlobalInstanceof checks if the value is an instance of the given global constructor

func (*Value) Has

func (v *Value) Has(name string) bool

Has returns true if the value has the property with the given name.

func (*Value) HasIdx

func (v *Value) HasIdx(idx uint32) bool

HasIdx returns true if the value has the property with the given index.

func (*Value) HasInstanceData added in v0.5.6

func (v *Value) HasInstanceData() bool

HasInstanceData checks if the value has associated Go object data This is the most reliable way to identify our class instances

func (*Value) Int32 deprecated

func (v *Value) Int32() int32

Deprecated: Use ToInt32 instead.

func (*Value) Int64 deprecated

func (v *Value) Int64() int64

Deprecated: Use ToInt64 instead.

func (*Value) IsArray

func (v *Value) IsArray() bool

func (*Value) IsBigInt

func (v *Value) IsBigInt() bool

func (*Value) IsBigInt64Array added in v0.5.4

func (v *Value) IsBigInt64Array() bool

func (*Value) IsBigUint64Array added in v0.5.4

func (v *Value) IsBigUint64Array() bool

func (*Value) IsBool

func (v *Value) IsBool() bool

func (*Value) IsByteArray added in v0.1.13

func (v *Value) IsByteArray() bool

IsByteArray returns true if the value is array buffer

func (*Value) IsClassInstance added in v0.5.6

func (v *Value) IsClassInstance() bool

IsClassInstance checks if the value is an instance of any user-defined class This method uses opaque data validation for maximum reliability

func (*Value) IsConstructor added in v0.4.15

func (v *Value) IsConstructor() bool

func (*Value) IsError

func (v *Value) IsError() bool

func (*Value) IsException

func (v *Value) IsException() bool

func (*Value) IsFloat32Array added in v0.5.4

func (v *Value) IsFloat32Array() bool

func (*Value) IsFloat64Array added in v0.5.4

func (v *Value) IsFloat64Array() bool

func (*Value) IsFunction

func (v *Value) IsFunction() bool

func (*Value) IsInstanceOfClassID added in v0.5.6

func (v *Value) IsInstanceOfClassID(expectedClassID uint32) bool

IsInstanceOfClassID checks if the value is an instance of a specific class ID This provides type-safe class instance checking with double validation

func (*Value) IsInstanceOfConstructor added in v0.5.6

func (v *Value) IsInstanceOfConstructor(constructor *Value) bool

IsInstanceOfConstructor checks if the value is an instance of a specific constructor This uses JavaScript's instanceof operator semantics

func (*Value) IsInt16Array added in v0.5.4

func (v *Value) IsInt16Array() bool

func (*Value) IsInt32Array added in v0.5.4

func (v *Value) IsInt32Array() bool

func (*Value) IsInt8Array added in v0.5.4

func (v *Value) IsInt8Array() bool

func (*Value) IsNull

func (v *Value) IsNull() bool

func (*Value) IsNumber

func (v *Value) IsNumber() bool

func (*Value) IsObject

func (v *Value) IsObject() bool

func (*Value) IsPromise added in v0.4.9

func (v *Value) IsPromise() bool

func (*Value) IsString

func (v *Value) IsString() bool

func (*Value) IsSymbol

func (v *Value) IsSymbol() bool

func (*Value) IsTypedArray added in v0.5.4

func (v *Value) IsTypedArray() bool

TypedArray detection methods

func (*Value) IsUint16Array added in v0.5.4

func (v *Value) IsUint16Array() bool

func (*Value) IsUint32Array added in v0.5.4

func (v *Value) IsUint32Array() bool

func (*Value) IsUint8Array added in v0.5.4

func (v *Value) IsUint8Array() bool

func (*Value) IsUint8ClampedArray added in v0.5.4

func (v *Value) IsUint8ClampedArray() bool

func (*Value) IsUndefined

func (v *Value) IsUndefined() bool

func (*Value) IsUninitialized

func (v *Value) IsUninitialized() bool

func (*Value) JSONStringify added in v0.1.11

func (v *Value) JSONStringify() string

JSONStringify returns the JSON string representation of the value.

func (*Value) Len

func (v *Value) Len() int64

Len returns the length of the array.

func (*Value) New added in v0.4.15

func (v *Value) New(args ...*Value) *Value

New calls the constructor with the given arguments.

func (*Value) PromiseState added in v0.5.5

func (v *Value) PromiseState() PromiseState

PromiseState returns the state of the Promise

func (*Value) PropertyNames

func (v *Value) PropertyNames() ([]string, error)

PropertyNames returns the names of the properties of the value.

func (*Value) Set

func (v *Value) Set(name string, val *Value)

Set sets the value of the property with the given name.

func (*Value) SetIdx

func (v *Value) SetIdx(idx int64, val *Value)

SetIdx sets the value of the property with the given index.

func (*Value) String

func (v *Value) String() string

String returns the string representation of the value. This method implements the fmt.Stringer interface.

func (*Value) ToBigInt added in v0.5.0

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

ToBigInt returns the big.Int value of the value.

func (*Value) ToBigInt64Array added in v0.5.4

func (v *Value) ToBigInt64Array() ([]int64, error)

ToBigInt64Array converts the value to int64 slice if it's a BigInt64Array.

func (*Value) ToBigUint64Array added in v0.5.4

func (v *Value) ToBigUint64Array() ([]uint64, error)

ToBigUint64Array converts the value to uint64 slice if it's a BigUint64Array.

func (*Value) ToBool added in v0.5.0

func (v *Value) ToBool() bool

ToBool returns the boolean value of the value.

func (*Value) ToByteArray added in v0.1.13

func (v *Value) ToByteArray(size uint) ([]byte, error)

func (*Value) ToError added in v0.5.0

func (v *Value) ToError() error

ToError returns the error value of the value.

func (*Value) ToFloat32Array added in v0.5.4

func (v *Value) ToFloat32Array() ([]float32, error)

ToFloat32Array converts the value to float32 slice if it's a Float32Array.

func (*Value) ToFloat64 added in v0.5.0

func (v *Value) ToFloat64() float64

ToFloat64 returns the float64 value of the value.

func (*Value) ToFloat64Array added in v0.5.4

func (v *Value) ToFloat64Array() ([]float64, error)

ToFloat64Array converts the value to float64 slice if it's a Float64Array.

func (*Value) ToInt16Array added in v0.5.4

func (v *Value) ToInt16Array() ([]int16, error)

ToInt16Array converts the value to int16 slice if it's an Int16Array.

func (*Value) ToInt32 added in v0.5.0

func (v *Value) ToInt32() int32

ToInt32 returns the int32 value of the value.

func (*Value) ToInt32Array added in v0.5.4

func (v *Value) ToInt32Array() ([]int32, error)

ToInt32Array converts the value to int32 slice if it's an Int32Array.

func (*Value) ToInt64 added in v0.5.0

func (v *Value) ToInt64() int64

ToInt64 returns the int64 value of the value.

func (*Value) ToInt8Array added in v0.5.4

func (v *Value) ToInt8Array() ([]int8, error)

ToInt8Array converts the value to int8 slice if it's an Int8Array.

func (*Value) ToString added in v0.5.0

func (v *Value) ToString() string

ToString returns the string representation of the value.

func (*Value) ToUint16Array added in v0.5.4

func (v *Value) ToUint16Array() ([]uint16, error)

ToUint16Array converts the value to uint16 slice if it's a Uint16Array.

func (*Value) ToUint32 added in v0.5.0

func (v *Value) ToUint32() uint32

ToUint32 returns the uint32 value of the value.

func (*Value) ToUint32Array added in v0.5.4

func (v *Value) ToUint32Array() ([]uint32, error)

ToUint32Array converts the value to uint32 slice if it's a Uint32Array.

func (*Value) ToUint8Array added in v0.5.4

func (v *Value) ToUint8Array() ([]uint8, error)

ToUint8Array converts the value to uint8 slice if it's a Uint8Array or Uint8ClampedArray.

func (*Value) Uint32 deprecated

func (v *Value) Uint32() uint32

Deprecated: Use ToUint32 instead.

Jump to

Keyboard shortcuts

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