Skip to content

vjs #

VJS

V bindings to QuickJS javascript engine. Run JS in V.

Features

  • Evaluate js (code, file, module, etc).
  • Multi evaluate support.
  • Callback function support.
  • Set-Globals support.
  • Set-Module support.
  • Call V from JS.
  • Call JS from V.
  • Top-Level await support. using vjs.type_module.

Install

v install herudi.vjs

Basic Usage

Create file main.v and copy-paste this code.

import herudi.vjs

fn main() {
  rt := vjs.new_runtime()
  ctx := rt.new_context()

  value := ctx.eval('1 + 2') or { panic(err) }
  ctx.end()

  assert value.is_number() == true
  assert value.is_string() == false
  assert value.to_int() == 3

  println(value)
  // 3

  // free
  value.free()
  ctx.free()
  rt.free()
}

Run

v run main.v

Explore examples

Currently support linux/mac/win (x64).

in windows, requires -cc gcc.

Multi Evaluate

ctx.eval('const sum = (a, b) => a + b') or { panic(err) }
ctx.eval('const mul = (a, b) => a * b') or { panic(err) }

sum := ctx.eval('sum(${1}, ${2})') or { panic(err) }
mul := ctx.eval('mul(${1}, ${2})') or { panic(err) }

ctx.end()

println(sum)
// 3

println(mul)
// 2

Add Global

glob := ctx.js_global()
glob.set('foo', 'bar')

value := ctx.eval('foo') or { panic(err) }
ctx.end()

println(value)
// bar

Add Module

mut mod := ctx.js_module('my-module')
mod.export('foo', 'foo')
mod.export('bar', 'bar')
mod.export_default(mod.to_object())
mod.create()

code := '
  import mod, { foo, bar } from "my-module";

  console.log(foo, bar);

  console.log(mod);
'

ctx.eval(code, vjs.type_module) or { panic(err) }
ctx.end()

Web Platform APIs

Inject Web API to vjs.

import herudi.vjs
import herudi.vjs.web

fn main() {
  rt := vjs.new_runtime()
  ctx := rt.new_context()

  // inject all
  web.inject(ctx)

  // or inject one by one
  // web.console_api(ctx)
  // web.encoding_api(ctx)
  // more..

  ...
}

List Web Platform APIs

It's Fun Project. PRs Wellcome :)

Constants #

const type_global = C.JS_EVAL_TYPE_GLOBAL

Evaluate JS type global.

const type_module = C.JS_EVAL_TYPE_MODULE

Evaluate JS type module.

const type_direct = C.JS_EVAL_TYPE_DIRECT

Evaluate JS type direct.

const type_indirect = C.JS_EVAL_TYPE_INDIRECT

Evaluate JS type indirect.

const type_mask = C.JS_EVAL_TYPE_MASK

Evaluate JS type mask.

const type_strict = C.JS_EVAL_FLAG_STRICT

Evaluate JS type strict.

const type_strip = C.JS_EVAL_FLAG_STRIP

Evaluate JS type strip.

const type_compile_only = C.JS_EVAL_FLAG_COMPILE_ONLY

Evaluate JS type compile only.

const type_barrier = C.JS_EVAL_FLAG_BACKTRACE_BARRIER

Evaluate JS type barrier.

const type_async = C.JS_EVAL_FLAG_ASYNC

Evaluate JS type async.

fn new_runtime #

fn new_runtime() Runtime

Create new Runtime.

Example

rt := vjs.new_runtime()

type AnyValue #

type AnyValue = Value | bool | f64 | i64 | int | string | u32 | u64

type Anything Value in vjs

type AtomValue #

type AtomValue = int | string

type CallbackPromise #

type CallbackPromise = fn (Promise) Value

type Callback JS Promise.

type JSCFunction #

type JSCFunction = fn (&C.JSContext, JSValueConst, int, &JSValueConst) C.JSValue

Original type JS Callback function from qjs

type JSConstructor #

type JSConstructor = fn (this Value, args []Value)

type Constructor Class function

type JSFunction #

type JSFunction = fn (args []Value) Value

type JS Callback function

type JSFunctionThis #

type JSFunctionThis = fn (this Value, args []Value) Value

type JS Callback function with this

type JSValueConst #

type JSValueConst = C.JSValue

type JSValueConst. this type is free.

type PropKey #

type PropKey = Atom | PropertyEnum | int | string

type property keys. to use get/set values.

enum JSPromiseStateEnum #

enum JSPromiseStateEnum {
	pending
	resolved
	rejected
}

enum Promise State

struct Atom #

struct Atom {
	ref C.JSAtom
	ctx Context
}

Atom structure based on JSAtom in qjs and implemented into ref.

fn (Atom) to_string #

fn (a Atom) to_string() string

Convert Atom to string.

fn (Atom) str #

fn (a Atom) str() string

Convert Atom to string.

fn (Atom) to_value #

fn (a Atom) to_value() Value

Convert Atom to Value.

Example

val := atom.to_value()
println(val)

fn (Atom) free #

fn (a &Atom) free()

Free Atom

struct ClassParams #

@[params]
struct ClassParams {
	id   ?u32
	name string
	ctor ?JSConstructor
}

struct Context #

struct Context {
	ref &C.JSContext
	rt  Runtime
}

Context structure based on JSContext in qjs and implemented into ref.

fn (Context) any_to_val #

fn (ctx &Context) any_to_val(val AnyValue) Value

Convert any to value.

fn (Context) call #

fn (ctx &Context) call(val Value, args ...AnyValue) !Value

Callback from Context

fn (Context) call_this #

fn (ctx &Context) call_this(this Value, val Value, args ...AnyValue) !Value

Callback this from Context

fn (Context) dump_error #

fn (ctx &Context) dump_error() Value

Dump std Error

fn (Context) dup_context #

fn (ctx &Context) dup_context() &Context

Duplicate context

fn (Context) end #

fn (ctx &Context) end()

Context end

fn (Context) eval #

fn (ctx &Context) eval(args ...EvalArgs) !Value

Evaluate JS

Example

val1 := ctx.eval('1 + 1')!

// or module
val2 := ctx.eval('1 + 1', vjs.type_module)!

fn (Context) eval_file #

fn (ctx &Context) eval_file(args ...EvalArgs) !Value

Evaluate File

Example

ctx.eval_file('./path/to/file.js')!

// or module
ctx.eval_file('./path/to/file.js', vjs.type_module)!

fn (Context) eval_function #

fn (ctx &Context) eval_function(val Value) Value

Evaluate Function

fn (Context) eval_module #

fn (ctx &Context) eval_module(input string, fname string) !Value

Evaluate JS module

Example

ctx.eval_module('1 + 1', 'index.js')!

fn (Context) free #

fn (ctx &Context) free()

Free the context

fn (Context) js_array #

fn (ctx &Context) js_array() Value

Create JS Array.

fn (Context) js_array_buffer #

fn (ctx &Context) js_array_buffer(data []u8) Value

Create JS ArrayBuffer.

fn (Context) js_await #

fn (ctx &Context) js_await(val Value) !Value

JS call await.

fn (Context) js_big_int #

fn (ctx &Context) js_big_int(data i64) Value

Create JS Bigint.

fn (Context) js_big_uint #

fn (ctx &Context) js_big_uint(data u64) Value

Create JS Big Uint.

fn (Context) js_bool #

fn (ctx &Context) js_bool(data bool) Value

Create JS Boolean.

fn (Context) js_class #

fn (ctx &Context) js_class(cls ClassParams) Value

Create JS Class

Example

foo_class := ctx.js_class(
	 name: 'Foo',
	 ctor: fn (this Value, args []Value) {
		 // constructor code here
	 }
)

foo := foo_class.new()

fn (Context) js_dump #

fn (ctx &Context) js_dump(err IError) Value

js dump IError.

fn (Context) js_error #

fn (ctx &Context) js_error(err JSError) Value

create JS new Error.

fn (Context) js_eval #

fn (ctx &Context) js_eval(input string, fname string, flag int) !Value

Evaluate JS with complete params

Example

ctx.js_eval(code, filename, flag)!

fn (Context) js_eval_core #

fn (ctx &Context) js_eval_core(input &char, len usize, fname &char, flag int, from_file bool) !Value

Core evaluate JS

fn (Context) js_exception #

fn (ctx &Context) js_exception() &JSError

Create JS Exception.

Example

if val.is_exception() {
  return ctx.js_exception()
}

fn (Context) js_float #

fn (ctx &Context) js_float(data f64) Value

Create JS Float.

fn (Context) js_function #

fn (ctx &Context) js_function(cb JSFunction) Value

JS Callback function

Example

my_fn := ctx.js_function(fn [ctx](args []Value) Value {
  return ctx.js_string('foo')	
})

fn (Context) js_function_this #

fn (ctx &Context) js_function_this(cb JSFunctionThis) Value

JS Callback function with this

Example

my_fn := ctx.js_function_this(fn (this Value, args []Value) Value {
  return this.ctx.js_string('foo')	
})

fn (Context) js_global #

fn (ctx &Context) js_global(keys ...string) Value

Define JS Global (globalThis).

fn (Context) js_i64 #

fn (ctx &Context) js_i64(data i64) Value

Create JS int64.

fn (Context) js_int #

fn (ctx &Context) js_int(data int) Value

Create JS Int.

fn (Context) js_module #

fn (ctx &Context) js_module(name string) Module

Initial js_module.

Example

mod := ctx.js_module('my-module')

fn (Context) js_new_class #

fn (ctx &Context) js_new_class(val Value, args ...AnyValue) !Value

JS call new class.

fn (Context) js_null #

fn (ctx &Context) js_null() Value

Create JS Null.

fn (Context) js_object #

fn (ctx &Context) js_object() Value

Create JS Object.

fn (Context) js_only_function #

fn (ctx &Context) js_only_function(cb JSFunction) JSCFunction

JS Callback only function

fn (Context) js_only_function_this #

fn (ctx &Context) js_only_function_this(cb JSFunctionThis) JSCFunction

JS Callback only function this

fn (Context) js_promise #

fn (ctx &Context) js_promise() Promise

Same as new_promise, but without callback.

fn (Context) js_string #

fn (ctx &Context) js_string(data string) Value

Create JS String.

fn (Context) js_throw #

fn (ctx &Context) js_throw(any AnyValue) Value

JS Throw Error.

fn (Context) js_type_error #

fn (ctx &Context) js_type_error(err JSError) Value

create JS new TypeError.

fn (Context) js_u32 #

fn (ctx &Context) js_u32(data u32) Value

Create JS u32.

fn (Context) js_undefined #

fn (ctx &Context) js_undefined() Value

Create JS Undefined.

fn (Context) js_uninitialized #

fn (ctx &Context) js_uninitialized() Value

Create JS Uninitialized.

fn (Context) json_parse #

fn (ctx &Context) json_parse(str string) Value

Convert value string to js_object.

fn (Context) json_stringify #

fn (ctx &Context) json_stringify(val Value) string

Convert value js_object to json string.

fn (Context) json_stringify_op #

fn (ctx &Context) json_stringify_op(val Value, rep Value, ind AnyValue) string

Convert value js_object to json string with optionals.

fn (Context) loop #

fn (ctx &Context) loop()

std loop form qjs

fn (Context) new_atom #

fn (ctx &Context) new_atom(val AtomValue) Atom

Create new Atom support int | string.

Example

atom := ctx.new_atom('my_atom')

fn (Context) new_promise #

fn (ctx &Context) new_promise(cb CallbackPromise) Value

Create new Promise.

Example

promise := ctx.new_promise(fn [ctx](p Promise) Value {
	 if err {
		 return p.reject(ctx.js_error(message: 'rejected'))
	 }
	 return p.resolve(ctx.js_string('resolved'))
})

value := promise.await()
println(value)

fn (Context) promise_result #

fn (ctx &Context) promise_result(val Value) Value

Get Promise Result

fn (Context) promise_state #

fn (ctx &Context) promise_state(val Value) Value

Get Promise State

fn (Context) runtime #

fn (ctx &Context) runtime() Runtime

Get runtime from context

struct ContextConfig #

@[params]
struct ContextConfig {
	unhandled_rejection bool = true
	bignum              bool = true
	module_std          bool
}

ContextConfig structure params.

struct JSError #

@[params]
struct JSError {
	Error
pub mut:
	name    string = 'Error'
	stack   string
	message string
}

JSError structure.

fn (JSError) msg #

fn (err &JSError) msg() string

lookup/print JSError message.

struct Module #

struct Module {
	ctx  Context
	name string
mut:
	exports_str []string
	exports     []&char
	values      []Value
}

Module structure.

fn (Module) export #

fn (mut m Module) export(name string, any AnyValue)

Export module.

Example

mod.export('foo', 'bar')

fn (Module) set #

fn (mut m Module) set(name string, any AnyValue)

Same as Export.

fn (Module) get #

fn (mut m Module) get(name string) Value

Get value from export/set.

fn (Module) to_object #

fn (mut m Module) to_object() Value

Convert module to JS object.

fn (Module) export_default #

fn (mut m Module) export_default(any AnyValue)

Export default.

Example

mod.export_default(mod.to_object())

fn (Module) create #

fn (mut m Module) create() &C.JSModuleDef

Create module.

Example

mod := ctx.js_module('my-module')
mod.export('foo', 'bar')
mod.export_default(mod.to_object())
mod.create()

struct Promise #

struct Promise {
	ctx Context
}

Promise structure.

fn (Promise) resolve #

fn (p Promise) resolve(any AnyValue) Value

Promise resolve

fn (Promise) reject #

fn (p Promise) reject(any AnyValue) Value

Promise reject

struct PropertyEnum #

struct PropertyEnum {
pub:
	atom          Atom
	is_enumerable bool
}

PropertyEnum structure based on JSPropertyEnum in qjs.

struct Runtime #

struct Runtime {
	ref &C.JSRuntime
}

Runtime structure based on JSRuntime in qjs and implemented into ref.

fn (Runtime) free #

fn (rt &Runtime) free()

Free runtime

fn (Runtime) is_job_pending #

fn (rt Runtime) is_job_pending() bool

Check if job is pending

fn (Runtime) new_context #

fn (rt Runtime) new_context(config ContextConfig) &Context

Create new Context from Runtime.

Example

rt := vjs.new_runtime()
ctx := rt.new_context(opts_config)

fn (Runtime) promise_rejection_tracker #

fn (rt Runtime) promise_rejection_tracker()

Promise rejection tracker (default true)

fn (Runtime) run_gc #

fn (rt Runtime) run_gc()

Run qjs garbage collector

fn (Runtime) set_gc_threshold #

fn (rt Runtime) set_gc_threshold(th i64)

Set gc threshold.

fn (Runtime) set_max_stack_size #

fn (rt Runtime) set_max_stack_size(stack_size u32)

Set maximum stack size. (default to 255)

fn (Runtime) set_memory_limit #

fn (rt Runtime) set_memory_limit(limit u32)

Set limit memory. (default to unlimited)

struct Value #

struct Value {
	ref C.JSValue
pub:
	ctx Context
}

Value structure based on JSValue in qjs and implemented into ref.

fn (Value) await #

fn (v Value) await() Value

Awaited from Promise

Example

val := my_promise.await()

fn (Value) byte_len #

fn (v Value) byte_len() int

byteLength value

fn (Value) call #

fn (v Value) call(key string, args ...AnyValue) Value

Call fn.

Example

array.call('push', ...args)

fn (Value) callback #

fn (v Value) callback(args ...AnyValue) Value

Callback function self

Example

val := my_fn.callback(...args)

fn (Value) delete #

fn (v Value) delete(key PropKey) bool

Delete property

Example

obj.delete('foo')

fn (Value) dup_value #

fn (v Value) dup_value() Value

Duplicate value

fn (Value) free #

fn (v &Value) free()

Free Value

fn (Value) get #

fn (v Value) get(key PropKey) Value

Get property

Example

foo := obj.get('foo')

fn (Value) has #

fn (v Value) has(key PropKey) bool

Has property

Example

has := obj.has('foo')

fn (Value) instanceof #

fn (v Value) instanceof(key string) bool

Check value with instanceof.

Example

assert val.instanceof('Promise') == true

fn (Value) is_array #

fn (v Value) is_array() bool

Check value is array.

fn (Value) is_big_decimal #

fn (v Value) is_big_decimal() bool

Check value is big decimal.

fn (Value) is_big_float #

fn (v Value) is_big_float() bool

Check value is bigfloat.

fn (Value) is_big_int #

fn (v Value) is_big_int() bool

Check value is bigint.

fn (Value) is_bool #

fn (v Value) is_bool() bool

Check value is boolean.

fn (Value) is_error #

fn (v Value) is_error() bool

Check value is error.

fn (Value) is_exception #

fn (v Value) is_exception() bool

Check value is exception.

fn (Value) is_function #

fn (v Value) is_function() bool

Check value is function.

fn (Value) is_null #

fn (v Value) is_null() bool

Check value is null.

fn (Value) is_number #

fn (v Value) is_number() bool

Check value is number.

fn (Value) is_object #

fn (v Value) is_object() bool

Check value is object.

fn (Value) is_string #

fn (v Value) is_string() bool

Check value is string.

fn (Value) is_symbol #

fn (v Value) is_symbol() bool

Check value is symbol.

fn (Value) is_undefined #

fn (v Value) is_undefined() bool

Check value is undefined.

fn (Value) is_uninitialized #

fn (v Value) is_uninitialized() bool

Check value is uninitialized.

fn (Value) json_stringify #

fn (v Value) json_stringify() string

Convert Value object to V string json

fn (Value) len #

fn (v Value) len() int

Length value

fn (Value) new #

fn (v Value) new(args ...AnyValue) Value

New from classes

Example

val := my_class.new(...args)

fn (Value) property_names #

fn (v Value) property_names() ![]PropertyEnum

arrays property_names []PropertyEnum.

Example

props := val.property_names() or { panic(err) }
println(props)

for prop in props {
  println(prop.atom)
	 println(prop.is_enumerable)
}

fn (Value) set #

fn (v Value) set(key PropKey, any AnyValue)

Set property

Example

obj := ctx.js_object()
obj.set('foo', 'foo')

fn (Value) str #

fn (v Value) str() string

Convert Value to V String

fn (Value) to_bool #

fn (v Value) to_bool() bool

Convert Value to V bool

fn (Value) to_bytes #

fn (v Value) to_bytes() []u8

Convert Value to V []u8

fn (Value) to_error #

fn (v Value) to_error() &JSError

Convert Value to V JSError

fn (Value) to_f64 #

fn (v Value) to_f64() f64

Convert Value to V f64

fn (Value) to_i64 #

fn (v Value) to_i64() i64

Convert Value to V i64

fn (Value) to_int #

fn (v Value) to_int() int

Convert Value to V int

fn (Value) to_string #

fn (v Value) to_string() string

Convert Value to V String

fn (Value) to_u32 #

fn (v Value) to_u32() u32

Convert Value to V u32

fn (Value) typeof_name #

fn (v Value) typeof_name() string

Check typeof name value.