### Get Version Source: https://context7.com/cznic/quickjs/llms.txt Returns the version string of the embedded QuickJS C library. Useful for diagnostics and compatibility checks. ```APIDOC ## `Version() string` ### Description Returns the version string of the embedded QuickJS C library. Useful for diagnostics and compatibility checks. ### Method `Version` ### Returns - `string` - The version string of the QuickJS library. ### Example ```go fmt.Println(quickjs.Version()) // Output example: 2025-09-13 ``` ``` -------------------------------- ### Expose Go Function to JavaScript (Multiple Returns) Source: https://context7.com/cznic/quickjs/llms.txt Registers a Go function that returns multiple values, which are then exposed as a JavaScript array. This example demonstrates a division and modulo operation. ```go vm, _ := quickjs.NewVM() deffer vm.Close() // Multiple return values → JS array vm.RegisterFunc("divmod", func(a, b int) (int, int) { return a / b, a % b }, false) dm, _ := vm.Eval("divmod(17, 5)", quickjs.EvalGlobal) fmt.Println(dm) // Output: [3,2] ``` -------------------------------- ### Expose Go Function to JavaScript (Single Return) Source: https://context7.com/cznic/quickjs/llms.txt Registers a Go function under a global JavaScript name. This example shows a function with a single integer return value. ```go vm, _ := quickjs.NewVM() deffer vm.Close() // Single return value vm.RegisterFunc("double", func(n int) int { return n * 2 }, false) result, _ := vm.Eval("double(21)", quickjs.EvalGlobal) fmt.Println(result) // Output: 42 ``` -------------------------------- ### Expose Variadic Go Function to JavaScript Source: https://context7.com/cznic/quickjs/llms.txt Registers a variadic Go function that accepts a variable number of arguments, which are then passed as a slice to the Go function. This example sums a list of integers. ```go vm, _ := quickjs.NewVM() deffer vm.Close() // Variadic Go function vm.RegisterFunc("sum", func(vals ...int) int { total := 0 for _, v := range vals { total += v } return total }, false) total, _ := vm.Eval("sum(1, 2, 3, 4, 5)", quickjs.EvalGlobal) fmt.Println(total) // Output: 15 ``` -------------------------------- ### Get QuickJS Library Version Source: https://context7.com/cznic/quickjs/llms.txt Retrieve the version string of the embedded QuickJS C library using the Version function for diagnostics. ```Go fmt.Println(quickjs.Version()) // Output example: 2025-09-13 ``` -------------------------------- ### Expose Go Function to JavaScript (Error Handling) Source: https://context7.com/cznic/quickjs/llms.txt Registers a Go function that can return an error. A non-nil Go error is converted to a JavaScript string, while a nil error becomes JavaScript null. This example shows safe square root calculation. ```go vm, _ := quickjs.NewVM() deffer vm.Close() // Error return: non-nil error becomes a JS string, nil becomes JS null vm.RegisterFunc("safeSqrt", func(n float64) (float64, error) { if n < 0 { return 0, fmt.Errorf("negative input") } return math.Sqrt(n), nil }, false) ok, _ := vm.Eval("safeSqrt(9)", quickjs.EvalGlobal) fmt.Println(ok) // Output: [3,null] bad, _ := vm.Eval("safeSqrt(-1)", quickjs.EvalGlobal) fmt.Println(bad) // Output: [0,negative input] ``` -------------------------------- ### Get JS Object Property into Go Source: https://context7.com/cznic/quickjs/llms.txt Use `GetProperty` to retrieve JavaScript object properties as native Go values. The conversion follows the same rules as `Eval`. This is useful for reading configuration or state from JavaScript objects. ```go vm, _ := quickjs.NewVM() defers vm.Close() obj, _ := vm.EvalValue(`var user = {name: "Alice", age: 30}; user;`, quickjs.EvalGlobal) defers obj.Free() nameAtom, _ := vm.NewAtom("name") ageAtom, _ := vm.NewAtom("age") name, _ := vm.GetProperty(obj, nameAtom) age, _ := vm.GetProperty(obj, ageAtom) fmt.Println(name, age) // Output: Alice 30 ``` -------------------------------- ### Create and Close a JavaScript VM in Go Source: https://context7.com/cznic/quickjs/llms.txt Demonstrates the basic lifecycle of a JavaScript virtual machine. Always ensure to close the VM using `defer vm.Close()` to release resources. ```go package main import ( "fmt" "modernc.org/quickjs" ) func main() { vm, err := quickjs.NewVM() if err != nil { panic(err) } defer vm.Close() result, err := vm.Eval("1 + 2", quickjs.EvalGlobal) if err != nil { panic(err) } fmt.Println(result) // Output: 3 } ``` -------------------------------- ### Enable Filesystem Module Loading with Go Source: https://context7.com/cznic/quickjs/llms.txt Call `SetDefaultModuleLoader` to enable QuickJS's built-in file-system module loader. This allows `import` statements in JavaScript to resolve `.js` files from the local filesystem. Must be called before `EvalModule`. ```go vm, _ := quickjs.NewVM() defers vm.Close() vm.SetDefaultModuleLoader() // testdata/power.js exports: square(x), cube(x), name vm.Eval("import * as Power from './testdata/power.js'; globalThis.Power = Power;", quickjs.EvalModule) result, _ := vm.Eval("[Power.square(3), Power.cube(3)];", quickjs.EvalGlobal) fmt.Println(result) // Output: [9,27] ``` -------------------------------- ### Add Standard JavaScript Globals to VM Source: https://context7.com/cznic/quickjs/llms.txt Use StdAddHelpers to include standard JavaScript globals like print and console.log in the VM, useful for debugging scripts. ```Go vm, _ := quickjs.NewVM() defer vm.Close() vm.StdAddHelpers() vm.Eval(" console.log(\"Hello from JS console!\"); print(\"And from print()!\"); ", quickjs.EvalGlobal) // Output (to stdout): // Hello from JS console! // And from print()! ``` -------------------------------- ### Add Standard Helpers Source: https://context7.com/cznic/quickjs/llms.txt Adds standard QuickJS helper globals (`print`, `console.log`, etc.) to the VM. Useful for scripts that rely on console output during development or debugging. ```APIDOC ## `(*VM).StdAddHelpers() error` ### Description Adds standard QuickJS helper globals (`print`, `console.log`, etc.) to the VM. Useful for scripts that rely on console output during development or debugging. ### Method `StdAddHelpers` ### Returns - `error` - An error if adding helpers fails. ### Example ```go vm, _ := quickjs.NewVM() defer vm.Close() vm.StdAddHelpers() vm.Eval(` console.log("Hello from JS console!"); print("And from print()!"); `, quickjs.EvalGlobal) // Output (to stdout): // Hello from JS console! // And from print()! ``` ``` -------------------------------- ### NewVM() (*VM, error) Source: https://context7.com/cznic/quickjs/llms.txt Creates a new isolated JavaScript virtual machine (VM) context. Each VM has its own global object and garbage collector. Remember to close the VM using vm.Close() when it's no longer needed to release resources. ```APIDOC ## NewVM() ### Description Creates a new isolated JavaScript VM (context + runtime). Each call allocates a fresh JavaScript heap. The returned `*VM` must be closed with `defer vm.Close()` when no longer needed. ### Method `NewVM()` ### Returns - `*VM`: A pointer to the newly created JavaScript virtual machine. - `error`: An error if the VM creation fails. ``` -------------------------------- ### Communicate Between VMs via Go Channels Source: https://context7.com/cznic/quickjs/llms.txt Demonstrates inter-VM communication using Go channels. A client VM sends a message to a server VM, which processes it and sends a reply back. This showcases asynchronous communication patterns. ```go vm, _ := quickjs.NewVM() deffer vm.Close() // Communicate between VMs via Go channels tx, rx := make(chan string, 1), make(chan string, 1) client, _ := quickjs.NewVM() deffer client.Close() client.RegisterFunc("send", func(s string) { tx <- s }, false) client.RegisterFunc("receive", func() string { return <-rx }, false) go func() { server, _ := quickjs.NewVM() defer server.Close() server.RegisterFunc("send", func(s string) { rx <- s }, false) server.RegisterFunc("receive", func() string { return <-tx }, false) server.Eval("send(receive() + ' reply');", quickjs.EvalGlobal) }() msg, _ := client.Eval("send('ping'); receive();", quickjs.EvalGlobal) fmt.Println(msg) // Output: ping reply ``` -------------------------------- ### Execute precompiled QuickJS bytecode Source: https://context7.com/cznic/quickjs/llms.txt Executes QuickJS bytecode that was previously produced by the `Compile` method. The execution context for `EvalBytecode` is always the global object. ```APIDOC ## Execute precompiled bytecode ### Description Executes QuickJS bytecode previously produced by `Compile`. Returns the same Go types as `Eval`. The `this` context is always the global object. ### Method Signature `(*VM).EvalBytecode(bytecode []byte) (any, error)` ### Parameters - `bytecode` ([]byte): The QuickJS bytecode to execute. ### Returns - `any`: The result of the bytecode execution. - `error`: An error if execution fails. ### Example ```go vm, _ := quickjs.NewVM() defer vm.Close() bytecode, _ := vm.Compile(` function greet(name) { return "Hello, " + name + "!"; } greet("World"); `, quickjs.EvalGlobal) result, err := vm.EvalBytecode(bytecode) if err != nil { panic(err) } fmt.Println(result) // Output: Hello, World! ``` ``` -------------------------------- ### Compile JavaScript to QuickJS Bytecode Source: https://context7.com/cznic/quickjs/llms.txt Compiles JavaScript source code into QuickJS bytecode without executing it. The resulting bytecode can be stored and later executed using `EvalBytecode`. Note that the bytecode format is version-specific and should not be loaded from untrusted sources. ```Go vm, _ := quickjs.NewVM() defer vm.Close() // Compile a script to bytecode bytecode, err := vm.Compile("42 * 314;", quickjs.EvalGlobal) if err != nil { panic(err) } fmt.Printf("bytecode length: %d bytes\n", len(bytecode)) // Execute the precompiled bytecode result, err := vm.EvalBytecode(bytecode) if err != nil { panic(err) } fmt.Println(result) // Output: 13188 ``` -------------------------------- ### Custom Module Resolution with Go Callbacks Source: https://context7.com/cznic/quickjs/llms.txt Register custom Go functions for module resolution and normalization using `SetModuleLoader`. This enables loading modules from memory, databases, or networks. Pass `nil` to remove the custom loader. ```go vm, _ := quickjs.NewVM() defers vm.Close() modules := map[string]string{ "math_utils": `export function add(a, b) { return a + b; }`, "greet": `export const hello = "Hello from Go!";`, } vm.SetModuleLoader( func(m *quickjs.VM, name string) (string, error) { src, ok := modules[name] if !ok { return "", fmt.Errorf("module not found: %s", name) } return src, nil }, func(m *quickjs.VM, baseName, name string) (string, error) { return name, nil // pass-through normalizer }, ) _, err := vm.Eval(` import { add } from "math_utils"; import { hello } from "greet"; globalThis.result = add(10, 32); globalThis.greeting = hello; `, quickjs.EvalModule) if err != nil { panic(err) } r, _ := vm.Eval("result", quickjs.EvalGlobal) g, _ := vm.Eval("greeting", quickjs.EvalGlobal) fmt.Println(r, g) // Output: 42 Hello from Go! // Teardown: remove the custom loader vm.SetModuleLoader(nil, nil) ``` -------------------------------- ### SetDefaultModuleLoader Source: https://context7.com/cznic/quickjs/llms.txt Enables the built-in QuickJS file-system module loader for resolving import statements. ```APIDOC ## SetDefaultModuleLoader (*VM) SetDefaultModuleLoader() ### Description Enables the built-in QuickJS file-system module loader, which resolves `import` statements by reading `.js` files from the local file system. Must be called before executing any `EvalModule` script that uses `import`. ### Method `SetDefaultModuleLoader` ### Parameters None ### Request Example ```go vm, _ := quickjs.NewVM() defer vm.Close() vim.SetDefaultModuleLoader() // testdata/power.js exports: square(x), cube(x), name vim.Eval("import * as Power from './testdata/power.js'; globalThis.Power = Power;", quickjs.EvalModule) result, _ := vm.Eval("[Power.square(3), Power.cube(3)];", quickjs.EvalGlobal) fmt.Println(result) // Output: [9,27] ``` ### Response #### Success Response (200) None #### Response Example None provided. ``` -------------------------------- ### (*VM).RegisterFunc Source: https://context7.com/cznic/quickjs/llms.txt Exposes a Go function to JavaScript under a specified global name. Supports various Go function signatures and return types, including multiple return values and error handling. Can optionally expose the JavaScript `this` value to the Go function. ```APIDOC ## (*VM).RegisterFunc(name string, f any, wantThis bool) error ### Description Registers a Go function under a global JavaScript name. The function `f` can have any signature with parameters of supported types (`int`, `string`, `bool`, `float64`, `*big.Int`, `*Object`, `Value`, or `any`). If `wantThis` is `true`, the first parameter receives the JavaScript `this` value. Multiple return values are returned as a JavaScript array. Go `error` return values are converted to JavaScript strings (non-nil) or `null` (nil). ### Method `(*VM).RegisterFunc` ### Parameters #### Path Parameters - `name` (string) - The global JavaScript name for the function. - `f` (any) - The Go function to register. - `wantThis` (bool) - If true, the first parameter of `f` will receive the JavaScript `this` value. ### Request Example ```go vm, _ := quickjs.NewVM() defers vm.Close() // Single return value vm.RegisterFunc("double", func(n int) int { return n * 2 }, false) result, _ := vm.Eval("double(21)", quickjs.EvalGlobal) fmt.Println(result) // Output: 42 // Multiple return values → JS array vm.RegisterFunc("divmod", func(a, b int) (int, int) { return a / b, a % b }, false) dm, _ := vm.Eval("divmod(17, 5)", quickjs.EvalGlobal) fmt.Println(dm) // Output: [3,2] // Error return: non-nil error becomes a JS string, nil becomes JS null vm.RegisterFunc("safeSqrt", func(n float64) (float64, error) { if n < 0 { return 0, fmt.Errorf("negative input") } return math.Sqrt(n), nil }, false) ok, _ := vm.Eval("safeSqrt(9)", quickjs.EvalGlobal) fmt.Println(ok) // Output: [3,null] bad, _ := vm.Eval("safeSqrt(-1)", quickjs.EvalGlobal) fmt.Println(bad) // Output: [0,negative input] // Variadic Go function vm.RegisterFunc("sum", func(vals ...int) int { total := 0 for _, v := range vals { total += v } return total }, false) total, _ := vm.Eval("sum(1, 2, 3, 4, 5)", quickjs.EvalGlobal) fmt.Println(total) // Output: 15 // Access JavaScript `this` via wantThis=true vm.RegisterFunc("getX", func(this any) any { return this }, true) x, _ := vm.Eval("var obj = {x: 99, getX: getX}; obj.getX()", quickjs.EvalGlobal) fmt.Println(x) // Output: {"x":99} // Communicate between VMs via Go channels tx, rx := make(chan string, 1), make(chan string, 1) client, _ := quickjs.NewVM() defers client.Close() client.RegisterFunc("send", func(s string) { tx <- s }, false) client.RegisterFunc("receive", func() string { return <-rx }, false) go func() { server, _ := quickjs.NewVM() defers server.Close() server.RegisterFunc("send", func(s string) { rx <- s }, false) server.RegisterFunc("receive", func() string { return <-tx }, false) server.Eval("send(receive() + ' reply');", quickjs.EvalGlobal) }() msg, _ := client.Eval("send('ping'); receive();", quickjs.EvalGlobal) fmt.Println(msg) // Output: ping reply ``` ### Response #### Success Response - `nil` - Indicates the function was registered successfully. #### Error Response - `error` - An error if the function registration fails. ``` -------------------------------- ### Evaluate JavaScript Expressions and Scripts in Go Source: https://context7.com/cznic/quickjs/llms.txt Shows how to evaluate various JavaScript expressions, including arithmetic, string operations, booleans, objects, BigInts, null, and undefined. Exceptions thrown in JavaScript are returned as Go errors. ```go vm, _ := quickjs.NewVM() deffer vm.Close() // Arithmetic n, err := vm.Eval("42 * 314", quickjs.EvalGlobal) fmt.Println(n, err) // Output: 13188 // String operations s, _ := vm.Eval("'foo' + 'bar'", quickjs.EvalGlobal) fmt.Println(s) // Output: foobar // Boolean b, _ := vm.Eval("42 < 314", quickjs.EvalGlobal) fmt.Println(b) // Output: true // Objects are returned as *quickjs.Object (JSON-backed) obj, _ := vm.Eval("obj = {a: 42+314, b: 'foo'}; obj;", quickjs.EvalGlobal) fmt.Println(obj) // Output: {"a":356,"b":"foo"} // BigInt big, _ := vm.Eval("1234567890123456789n", quickjs.EvalGlobal) fmt.Println(big) // Output: 1234567890123456789 // Null and undefined nulVal, _ := vm.Eval("null;", quickjs.EvalGlobal) fmt.Println(nulVal) // Output: undefVal, _ := vm.Eval("undefined;", quickjs.EvalGlobal) fmt.Println(undefVal) // Output: undefined // Exception handling _, err = vm.Eval("throw new Error('failed');", quickjs.EvalGlobal) fmt.Println(err) // Output: Error: failed ``` -------------------------------- ### Compile JavaScript to QuickJS bytecode Source: https://context7.com/cznic/quickjs/llms.txt Compiles JavaScript source code into QuickJS bytecode without executing it. The resulting bytecode can be stored and later executed using `EvalBytecode`. Note that the bytecode format is version-specific and should not be loaded from untrusted sources. ```APIDOC ## Compile JavaScript to QuickJS bytecode ### Description Compiles JavaScript source to QuickJS bytecode without executing it. The resulting `[]byte` can be stored, transferred, and later executed with `EvalBytecode`. The bytecode format is version-specific and must not be loaded from untrusted sources. ### Method Signature `(*VM).Compile(javascript string, flags int) ([]byte, error)` ### Parameters - `javascript` (string): The JavaScript source code to compile. - `flags` (int): Flags to control compilation behavior (e.g., `quickjs.EvalGlobal`). ### Returns - `[]byte`: The compiled QuickJS bytecode. - `error`: An error if compilation fails. ### Example ```go vm, _ := quickjs.NewVM() defer vm.Close() bytecode, err := vm.Compile("42 * 314;", quickjs.EvalGlobal) if err != nil { panic(err) } fmt.Printf("bytecode length: %d bytes\n", len(bytecode)) ``` ``` -------------------------------- ### Execute Precompiled QuickJS Bytecode Source: https://context7.com/cznic/quickjs/llms.txt Executes QuickJS bytecode that was previously generated by the `Compile` function. This method returns the same Go types as `Eval`. The `this` context is always set to the global object. ```Go vm, _ := quickjs.NewVM() defer vm.Close() // Assume bytecode was compiled and saved previously bytecode, _ := vm.Compile(" function greet(name) { return \"Hello, \" + name + \"!\"; } greet(\"World\"); ", quickjs.EvalGlobal) result, err := vm.EvalBytecode(bytecode) if err != nil { panic(err) } fmt.Println(result) // Output: Hello, World! ``` -------------------------------- ### Configure VM Blocking Mode Source: https://context7.com/cznic/quickjs/llms.txt Controls whether the JavaScript engine is permitted to block, which is relevant for `Atomics.wait`. Set to `true` to allow blocking; `false` (the default) disallows it. This setting must be applied before any blocking JavaScript operations are attempted. ```Go vm, _ := quickjs.NewVM() defer vm.Close() v.SetCanBlock(true) // Now Atomics.wait() calls will be permitted in this VM. ``` -------------------------------- ### Value Construction Source: https://context7.com/cznic/quickjs/llms.txt Factory methods for creating JavaScript primitive `Value` objects from Go values. All returned `Value`s must be freed by the caller. ```APIDOC ## `(*VM).NewString(s string) (Value, error)` / `(*VM).NewInt(n int) Value` / `(*VM).NewFloat64(n float64) Value` / `(*VM).NewObjectValue() (Value, error)` ### Description Factory methods for creating JavaScript primitive `Value` objects from Go values. These are for low-level use when you need a raw `Value` (e.g., to pass to `SetPropertyValue`). All returned `Value`s must be freed by the caller. ### Method `NewString`, `NewInt`, `NewFloat64`, `NewObjectValue` ### Parameters - `s` (string) - The string to convert to a JavaScript Value. - `n` (int) - The integer to convert to a JavaScript Value. - `n` (float64) - The float64 to convert to a JavaScript Value. ### Returns - `Value` - The created JavaScript Value. - `error` - An error if the value creation fails (for `NewString` and `NewObjectValue`). ### Example ```go vm, _ := quickjs.NewVM() defer vm.Close() obj, _ := vm.NewObjectValue() defer obj.Free() keyAtom, _ := vm.NewAtom("greeting") strVal, _ := vm.NewString("Hello, World!") defer strVal.Free() vm.SetPropertyValue(obj, keyAtom, strVal.Dup()) numAtom, _ := vm.NewAtom("count") numVal := vm.NewInt(42) defer numVal.Free() vm.SetPropertyValue(obj, numAtom, numVal.Dup()) // Make the object available in JS as `myObj` global := vm.GlobalObject() defer global.Free() myObjAtom, _ := vm.NewAtom("myObj") vm.SetPropertyValue(global, myObjAtom, obj.Dup()) result, _ := vm.Eval("JSON.stringify(myObj)", quickjs.EvalGlobal) fmt.Println(result) // Output: {"greeting":"Hello, World!","count":42} ``` ``` -------------------------------- ### Create Property Key Atom with Go Source: https://context7.com/cznic/quickjs/llms.txt Use `NewAtom` to create an interned identifier for property names. Atoms improve efficiency when repeatedly accessing object properties with `SetProperty` or `GetProperty`. ```go vm, _ := quickjs.NewVM() defer vm.Close() obj, _ := vm.EvalValue("var obj = {}; obj;", quickjs.EvalGlobal) defers obj.Free() atom, err := vm.NewAtom("score") if err != nil { panic(err) } // Set obj.score = 100 if err := vm.SetProperty(obj, atom, 100); err != nil { panic(err) } // Read obj.score back v, _ := vm.GetProperty(obj, atom) fmt.Println(v) // Output: 100 ``` -------------------------------- ### Create Primitive JavaScript Values in Go Source: https://context7.com/cznic/quickjs/llms.txt Use factory methods to create primitive JavaScript Value objects from Go types. Remember to free all returned Values after use. ```Go vm, _ := quickjs.NewVM() defer vm.Close() obj, _ := vm.NewObjectValue() defer obj.Free() keyAtom, _ := vm.NewAtom("greeting") strVal, _ := vm.NewString("Hello, World!") defer strVal.Free() vm.SetPropertyValue(obj, keyAtom, strVal.Dup()) numAtom, _ := vm.NewAtom("count") numVal := vm.NewInt(42) defer numVal.Free() vm.SetPropertyValue(obj, numAtom, numVal.Dup()) // Make the object available in JS as `myObj` global := vm.GlobalObject() defer global.Free() myObjAtom, _ := vm.NewAtom("myObj") vm.SetPropertyValue(global, myObjAtom, obj.Dup()) result, _ := vm.Eval("JSON.stringify(myObj)", quickjs.EvalGlobal) fmt.Println(result) // Output: {"greeting":"Hello, World!","count":42} ``` -------------------------------- ### (*VM).Call Source: https://context7.com/cznic/quickjs/llms.txt Evaluates a JavaScript function expression and calls it with provided Go arguments. Arguments are automatically converted between Go and JavaScript types. Supports built-in functions, methods, user-defined functions, and Go structs marshalled to JS objects. ```APIDOC ## (*VM).Call(function string, args ...any) (any, error) ### Description Evaluates `function` as a JavaScript expression (which must resolve to a callable), then calls it with the provided Go arguments. Arguments are automatically converted from Go to JavaScript types. Any Go struct is marshalled to a JS object via JSON; `*big.Int` becomes a BigInt; `nil` becomes null. ### Method `(*VM).Call` ### Parameters #### Path Parameters - `function` (string) - The JavaScript function expression to call. - `args` (...any) - The arguments to pass to the JavaScript function. ### Request Example ```go vm, _ := quickjs.NewVM() defer vm.Close() // Call a built-in function result, _ := vm.Call("parseInt", "1234") fmt.Println(result) // Output: 1234 // Call a built-in method abs, _ := vm.Call("Math.abs", -42) fmt.Println(abs) // Output: 42 // Call a user-defined function (define it first, then pass the expression) vm.Eval("function add(a, b) { return a + b; }", quickjs.EvalGlobal) sum, _ := vm.Call("add", 10, 32) fmt.Println(sum) // Output: 42 // Pass a Go struct as a JS object argument type Point struct{ X, Y int } vm.Eval("function describePoint(p) { return `(${p.X}, ${p.Y})`; }", quickjs.EvalGlobal) desc, _ := vm.Call("describePoint", Point{3, 4}) fmt.Println(desc) // Output: (3, 4) // Multiple return values from JS array vm.Eval("function minmax(a, b) { return [Math.min(a,b), Math.max(a,b)]; }", quickjs.EvalGlobal) pair, _ := vm.Call("minmax", 7, 3) fmt.Println(pair) // Output: [3,7] ``` ### Response #### Success Response - `any` - The result of the JavaScript function call. - `error` - An error if the function call fails. ``` -------------------------------- ### SetModuleLoader Source: https://context7.com/cznic/quickjs/llms.txt Registers custom Go callbacks for resolving and loading JavaScript modules. ```APIDOC ## SetModuleLoader (*VM) SetModuleLoader(loader ModuleLoaderFunc, normalize ModuleNormalizeFunc) ### Description Registers Go callbacks for resolving and loading JavaScript modules. `loader` receives a module name and returns its source code; `normalize` transforms a (base, requested) name pair into a canonical name. Pass `nil` for `loader` to remove the custom loader. Supports in-memory module systems, databases, network-fetched modules, etc. ### Method `SetModuleLoader` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **loader** (ModuleLoaderFunc) - A function that loads module source code given a module name. - **normalize** (ModuleNormalizeFunc) - A function that normalizes module names. ### Request Example ```go vm, _ := quickjs.NewVM() defer vm.Close() modules := map[string]string{ "math_utils": `export function add(a, b) { return a + b; }`, "greet": `export const hello = "Hello from Go!";`, } vim.SetModuleLoader( func(m *quickjs.VM, name string) (string, error) { src, ok := modules[name] if !ok { return "", fmt.Errorf("module not found: %s", name) } return src, nil }, func(m *quickjs.VM, baseName, name string) (string, error) { return name, nil // pass-through normalizer }, ) _, err := vm.Eval(` import { add } from "math_utils"; import { hello } from "greet"; globalThis.result = add(10, 32); globalThis.greeting = hello; `, quickjs.EvalModule) if err != nil { panic(err) } r, _ := vm.Eval("result", quickjs.EvalGlobal) g, _ := vm.Eval("greeting", quickjs.EvalGlobal) fmt.Println(r, g) // Output: 42 Hello from Go! // Teardown: remove the custom loader vim.SetModuleLoader(nil, nil) ``` ### Response #### Success Response (200) None #### Response Example None provided. ``` -------------------------------- ### (*VM).Eval(javascript string, flags int) (any, error) Source: https://context7.com/cznic/quickjs/llms.txt Evaluates a JavaScript expression or script. The `flags` parameter determines the evaluation context (`quickjs.EvalGlobal` for scripts or `quickjs.EvalModule` for ES modules). It returns a Go representation of the JavaScript result, mapping JS types to Go types. ```APIDOC ## (*VM).Eval(javascript string, flags int) ### Description Evaluates a JavaScript expression or script and returns a native Go value. The `flags` parameter is either `quickjs.EvalGlobal` for scripts or `quickjs.EvalModule` for ES modules. Return type mapping: JS `int` → Go `int`, JS `string` → Go `string`, JS `bool` → Go `bool`, JS `float64` → Go `float64`, JS `BigInt` → Go `*big.Int`, JS object/array → Go `*quickjs.Object`, JS `null` → Go `nil`, JS `undefined` → Go `quickjs.Undefined{}`. Exceptions are returned as Go errors. ### Method `Eval(javascript string, flags int)` ### Parameters #### Path Parameters - `javascript` (string) - Required - The JavaScript code to evaluate. - `flags` (int) - Required - Evaluation flags, e.g., `quickjs.EvalGlobal` or `quickjs.EvalModule`. ### Returns - `any`: The evaluated result as a Go type. - `error`: An error if the evaluation fails or an exception occurs. ``` -------------------------------- ### Configure Garbage Collection Threshold Source: https://context7.com/cznic/quickjs/llms.txt Sets the memory allocation threshold that triggers a new garbage collection cycle. Lowering this threshold results in more frequent but shorter GC pauses. Raising it allows for more allocation between collections. ```Go vm, _ := quickjs.NewVM() defer vm.Close() // Trigger GC every 512 KiB of allocation v.SetGCThreshold(512 * 1024) v.Eval(" for (let i = 0; i < 100000; i++) { let obj = { value: i, data: new Array(10).fill(i) }; } ", quickjs.EvalGlobal) ``` -------------------------------- ### SetProperty Source: https://context7.com/cznic/quickjs/llms.txt Sets a property on a JavaScript object to a Go value, performing automatic type conversion. ```APIDOC ## SetProperty (*VM) SetProperty(this Value, prop Atom, val any) error ### Description Sets a property on a JavaScript object to a Go value. The Go value is automatically converted using the same rules as function argument conversion. Returns an error if the property cannot be set. ### Method `SetProperty` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **this** (Value) - The JavaScript object to set the property on. - **prop** (Atom) - The atom representing the property key. - **val** (any) - The Go value to set as the property value. ### Request Example ```go vm, _ := quickjs.NewVM() defer vm.Close() obj, _ := vm.EvalValue("var config = {}; config;", quickjs.EvalGlobal) deffer obj.Free() nameAtom, _ := vm.NewAtom("host") portAtom, _ := vm.NewAtom("port") tlsAtom, _ := vm.NewAtom("tls") vim.SetProperty(obj, nameAtom, "localhost") vim.SetProperty(obj, portAtom, 8080) vim.SetProperty(obj, tlsAtom, true) result, _ := vm.Eval("JSON.stringify(config)", quickjs.EvalGlobal) fmt.Println(result) // Output: {"host":"localhost","port":8080,"tls":true} ``` ### Response #### Success Response (200) None #### Response Example None provided. ### Error Handling Returns an error if the property cannot be set. ``` -------------------------------- ### GetProperty Source: https://context7.com/cznic/quickjs/llms.txt Reads a property from a JavaScript object and returns it as a native Go value. ```APIDOC ## GetProperty (*VM) GetProperty(this Value, prop Atom) (any, error) ### Description Reads a property from a JavaScript object and returns it as a native Go value (same type mapping as `Eval`). ### Method `GetProperty` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **this** (Value) - The JavaScript object to read the property from. - **prop** (Atom) - The atom representing the property key. ### Request Example ```go vm, _ := quickjs.NewVM() defer vm.Close() obj, _ := vm.EvalValue(`var user = {name: "Alice", age: 30}; user;`, quickjs.EvalGlobal) deffer obj.Free() nameAtom, _ := vm.NewAtom("name") ageAtom, _ := vm.NewAtom("age") name, _ := vm.GetProperty(obj, nameAtom) age, _ := vm.GetProperty(obj, ageAtom) fmt.Println(name, age) // Output: Alice 30 ``` ### Response #### Success Response (200) - **any** (any) - The value of the property as a Go type. - **error** (error) - An error if the property cannot be read. #### Response Example None provided. ``` -------------------------------- ### Limit VM Memory Usage Source: https://context7.com/cznic/quickjs/llms.txt Sets the maximum number of bytes the JavaScript heap can allocate. Exceeding this limit will cause JavaScript code attempting to allocate memory to throw an out-of-memory exception. Very small limits are automatically increased to a minimum required for exception objects. ```Go vm, _ := quickjs.NewVM() defer vm.Close() v.SetMemoryLimit(1 * 1024 * 1024) // 1 MiB _, err := vm.Eval(" var a = []; while (true) { a.push(new Array(1000)); } ", quickjs.EvalGlobal) fmt.Println(err) // Output: RangeError: cannot allocate memory (or similar OOM error) ``` -------------------------------- ### Configure blocking mode Source: https://context7.com/cznic/quickjs/llms.txt Controls whether the JavaScript engine is permitted to block, which is relevant for operations like `Atomics.wait`. Setting this to `true` allows blocking operations, while `false` (the default) disallows them. This setting must be configured before any blocking JavaScript operations are attempted. ```APIDOC ## Configure blocking mode ### Description Controls whether the JavaScript engine is allowed to block (relevant for `Atomics.wait`). Pass `true` to allow blocking; `false` to disallow it (the default). This must be set before any blocking JS operations are attempted. ### Method Signature `(*VM).SetCanBlock(value bool)` ### Parameters - `value` (bool): `true` to allow blocking operations, `false` to disallow them. ### Example ```go vm, _ := quickjs.NewVM() defer vm.Close() vm.SetCanBlock(true) // Now Atomics.wait() calls will be permitted in this VM. ``` ``` -------------------------------- ### Expose Go Function Accessing JavaScript 'this' Source: https://context7.com/cznic/quickjs/llms.txt Registers a Go function that can access the JavaScript 'this' context by setting `wantThis` to true. The 'this' value is passed as the first parameter to the Go function. ```go vm, _ := quickjs.NewVM() deffer vm.Close() // Access JavaScript `this` via wantThis=true vm.RegisterFunc("getX", func(this any) any { return this }, true) x, _ := vm.Eval("var obj = {x: 99, getX: getX}; obj.getX()", quickjs.EvalGlobal) fmt.Println(x) // Output: {"x":99} ``` -------------------------------- ### Limit VM memory usage Source: https://context7.com/cznic/quickjs/llms.txt Sets a maximum limit on the number of bytes the JavaScript heap can allocate. If this limit is exceeded, any JavaScript code attempting to allocate more memory will result in an out-of-memory exception. Very small limits are automatically adjusted to an internal minimum required for exception object construction. ```APIDOC ## Limit VM memory usage ### Description Sets the maximum number of bytes the JS heap may allocate. When the limit is exceeded, JS code that tries to allocate will receive an out-of-memory exception. Very small values (below ~128 KiB) are silently raised to an internal minimum needed to construct exception objects. ### Method Signature `(*VM).SetMemoryLimit(limit uintptr)` ### Parameters - `limit` (uintptr): The maximum number of bytes for the JS heap. ### Example ```go vm, _ := quickjs.NewVM() defer vm.Close() vm.SetMemoryLimit(1 * 1024 * 1024) // 1 MiB _, err := vm.Eval(` var a = []; while (true) { a.push(new Array(1000)); } `, quickjs.EvalGlobal) fmt.Println(err) // Output: RangeError: cannot allocate memory (or similar OOM error) ``` ``` -------------------------------- ### Set JS Object Property from Go Source: https://context7.com/cznic/quickjs/llms.txt Use `SetProperty` to assign Go values to JavaScript object properties. The Go value is automatically converted to its JavaScript equivalent. This is useful for configuring JavaScript objects from Go. ```go vm, _ := quickjs.NewVM() defers vm.Close() obj, _ := vm.EvalValue("var config = {}; config;", quickjs.EvalGlobal) defers obj.Free() nameAtom, _ := vm.NewAtom("host") portAtom, _ := vm.NewAtom("port") tlsAtom, _ := vm.NewAtom("tls") vm.SetProperty(obj, nameAtom, "localhost") vm.SetProperty(obj, portAtom, 8080) vm.SetProperty(obj, tlsAtom, true) result, _ := vm.Eval("JSON.stringify(config)", quickjs.EvalGlobal) fmt.Println(result) // Output: {"host":"localhost","port":8080,"tls":true} ``` -------------------------------- ### NewAtom Source: https://context7.com/cznic/quickjs/llms.txt Creates an interned identifier for a property name, used for efficient property access. ```APIDOC ## NewAtom (*VM) NewAtom(s string) (Atom, error) ### Description Returns an interned identifier for a property name. Atoms are used with `SetProperty`, `SetPropertyValue`, `GetProperty`, and `GetPropertyValue` to read or write object properties efficiently without repeated string allocation. ### Method `NewAtom` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go vm, _ := quickjs.NewVM() defer vm.Close() obj, _ := vm.EvalValue("var obj = {}; obj;", quickjs.EvalGlobal) deffer obj.Free() atom, err := vm.NewAtom("score") if err != nil { panic(err) } // Set obj.score = 100 if err := vm.SetProperty(obj, atom, 100); err != nil { panic(err) } // Read obj.score back v, _ := vm.GetProperty(obj, atom) fmt.Println(v) // Output: 100 ``` ### Response #### Success Response (200) - **Atom** (Atom) - The interned identifier. - **error** (error) - An error if the atom creation fails. #### Response Example None provided. ``` -------------------------------- ### Configure garbage collection threshold Source: https://context7.com/cznic/quickjs/llms.txt Sets the amount of memory that must be allocated since the last garbage collection (GC) cycle before a new GC cycle is triggered. Lowering this threshold leads to more frequent but shorter GC pauses, while raising it allows for more allocation between collections. ```APIDOC ## Configure garbage collection threshold ### Description Sets the amount of memory that must be allocated since the last GC before a new GC cycle is triggered. Lowering the threshold causes more frequent but shorter GC pauses; raising it allows more allocation between collections. ### Method Signature `(*VM).SetGCThreshold(threshold uintptr)` ### Parameters - `threshold` (uintptr): The amount of memory allocation in bytes that triggers a GC cycle. ### Example ```go vm, _ := quickjs.NewVM() defer vm.Close() // Trigger GC every 512 KiB of allocation vm.SetGCThreshold(512 * 1024) vm.Eval(` for (let i = 0; i < 100000; i++) { let obj = { value: i, data: new Array(10).fill(i) }; } `, quickjs.EvalGlobal) ``` ``` -------------------------------- ### (*VM).EvalValue(javascript string, flags int) (Value, error) Source: https://context7.com/cznic/quickjs/llms.txt Similar to `Eval`, but returns a reference-counted `Value`. This is useful for passing JavaScript values between Go and JS contexts, such as setting object properties or reusing values in subsequent JS calls. The caller must ensure `v.Free()` is called exactly once. ```APIDOC ## (*VM).EvalValue(javascript string, flags int) ### Description Like `Eval` but returns a reference-counted `Value` instead of a plain Go value. The caller is responsible for calling `v.Free()` exactly once. Use this when you need to pass the result back into further JS calls, set object properties, or avoid the overhead of JSON serialization for objects. ### Method `EvalValue(javascript string, flags int)` ### Parameters #### Path Parameters - `javascript` (string) - Required - The JavaScript code to evaluate. - `flags` (int) - Required - Evaluation flags, e.g., `quickjs.EvalGlobal` or `quickjs.EvalModule`. ### Returns - `Value`: A reference-counted JavaScript value. - `error`: An error if the evaluation fails or an exception occurs. ``` -------------------------------- ### Deserialize JavaScript Object to Go Struct Source: https://context7.com/cznic/quickjs/llms.txt Use the Into method to unmarshal a JavaScript object into a Go struct, leveraging encoding/json.Unmarshal for structured data extraction. ```Go vm, _ := quickjs.NewVM() defer vm.Close() type User struct { Name string `json:"name"` Age int `json:"age"` Admin bool `json:"admin"` } raw, _ := vm.Eval(`({name: "Bob", age: 25, admin: false})`, quickjs.EvalGlobal) var user User if err := raw.(*quickjs.Object).Into(&user); err != nil { panic(err) } fmt.Printf("%+v\n", user) // Output: {Name:Bob Age:25 Admin:false} ``` -------------------------------- ### (*VM).EvalThis Source: https://context7.com/cznic/quickjs/llms.txt Evaluates a JavaScript script with a custom `this` binding. The provided `obj` Value is freed automatically after the call. ```APIDOC ## (*VM).EvalThis(obj Value, javascript string, flags int) (any, error) ### Description Evaluates a JavaScript script with the JavaScript `this` binding set to a given `Value`. The `obj` Value is freed automatically after the call. ### Method `(*VM).EvalThis` ### Parameters #### Path Parameters - `obj` (Value) - The JavaScript `Value` to be used as `this`. - `javascript` (string) - The JavaScript script to evaluate. - `flags` (int) - Evaluation flags. ### Request Example ```go vm, _ := quickjs.NewVM() defer vm.Close() // Create an object and evaluate a script with it as `this` obj, _ := vm.EvalValue("var target = {count: 10}; target;", quickjs.EvalGlobal) // obj.Dup() is passed so obj can still be freed separately result, err := vm.EvalThis(obj.Dup(), "this.count * 2", quickjs.EvalGlobal) if err != nil { panic(err) } fmt.Println(result) // Output: 20 defer obj.Free() ``` ### Response #### Success Response - `any` - The result of the JavaScript evaluation. - `error` - An error if the evaluation fails. ``` -------------------------------- ### Evaluate JavaScript and Return Raw Value in Go Source: https://context7.com/cznic/quickjs/llms.txt Use `EvalValue` to obtain a reference-counted `Value` for JavaScript objects, allowing them to be passed back into JS calls or used for property manipulation. Remember to call `v.Free()` exactly once on the returned value. ```go vm, _ := quickjs.NewVM() deffer vm.Close() // Obtain a raw JS object Value v, err := vm.EvalValue("var obj = {x: 10, y: 20}; obj;", quickjs.EvalGlobal) if err != nil { panic(err) } deffer v.Free() // Pass the Value back into another JS call result, err := vm.Call("function(o) { return o.x + o.y; }", v.Dup()) if err != nil { panic(err) } fmt.Println(result) // Output: 30 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.