Documentation
¶
Index ¶
- Variables
- type Config
- type Error
- type EvalOption
- type FS
- type FSBackend
- type File
- type Function
- type FunctionCall
- type Lstater
- type Pool
- type Runtime
- func (r *Runtime) Close() (err error)
- func (r *Runtime) Compile(name, src string, opts ...EvalOption) ([]byte, error)
- func (r *Runtime) CompileFile(path string, opts ...EvalOption) ([]byte, error)
- func (r *Runtime) Eval(ctx context.Context, name, src string, opts ...EvalOption) (*Value, error)
- func (r *Runtime) EvalBytecode(ctx context.Context, bytecode []byte, opts ...EvalOption) (*Value, error)
- func (r *Runtime) EvalFile(ctx context.Context, path string, opts ...EvalOption) (*Value, error)
- func (r *Runtime) Get(name string) (*Value, error)
- func (r *Runtime) Global() *Value
- func (r *Runtime) LoadModule(ctx context.Context, name, src string) error
- func (r *Runtime) LoadModuleBytecode(ctx context.Context, bytecode []byte) error
- func (r *Runtime) LoadModuleFile(ctx context.Context, path string) error
- func (r *Runtime) NewArray() *Value
- func (r *Runtime) NewArrayBuffer(data []byte) *Value
- func (r *Runtime) NewAsyncFunction(fn Function) *Value
- func (r *Runtime) NewBigInt64(v int64) *Value
- func (r *Runtime) NewBigUint64(v uint64) *Value
- func (r *Runtime) NewBool(b bool) *Value
- func (r *Runtime) NewDate(t time.Time) *Value
- func (r *Runtime) NewError(err error) *Value
- func (r *Runtime) NewFloat64(v float64) *Value
- func (r *Runtime) NewFunction(fn Function) *Value
- func (r *Runtime) NewInt32(v int32) *Value
- func (r *Runtime) NewInt64(v int64) *Value
- func (r *Runtime) NewMap() *Value
- func (r *Runtime) NewNull() *Value
- func (r *Runtime) NewObject() *Value
- func (r *Runtime) NewProxyValue(v any) *Value
- func (r *Runtime) NewSet() *Value
- func (r *Runtime) NewString(s string) *Value
- func (r *Runtime) NewUint32(v uint32) *Value
- func (r *Runtime) NewUndefined() *Value
- func (r *Runtime) ParseJSON(s string) (_ *Value, err error)
- func (r *Runtime) Set(name string, v any) error
- func (r *Runtime) SetAsyncFunc(name string, fn Function) error
- func (r *Runtime) SetFunc(name string, fn Function) error
- func (r *Runtime) String() string
- func (r *Runtime) ToValue(v any) (*Value, error)
- type Value
- func (v *Value) As[T any]() (T, error)
- func (v *Value) Await(ctx context.Context) (_ *Value, err error)
- func (v *Value) BigInt() *big.Int
- func (v *Value) Bool() bool
- func (v *Value) Bytes() ([]byte, error)
- func (v *Value) Call(ctx context.Context, this *Value, args ...any) (_ *Value, err error)
- func (v *Value) Clone() *Value
- func (v *Value) Delete(name string) (_ bool, err error)
- func (v *Value) Float64() float64
- func (v *Value) Free()
- func (v *Value) Get(name string) (_ *Value, err error)
- func (v *Value) GetKey(key *Value) (_ *Value, err error)
- func (v *Value) Has(name string) (_ bool, err error)
- func (v *Value) Index(i uint32) (_ *Value, err error)
- func (v *Value) Int32() int32
- func (v *Value) Int64() int64
- func (v *Value) Invoke(ctx context.Context, name string, args ...any) (*Value, error)
- func (v *Value) IsArray() bool
- func (v *Value) IsArrayBuffer() bool
- func (v *Value) IsBigInt() bool
- func (v *Value) IsBool() bool
- func (v *Value) IsConstructor() bool
- func (v *Value) IsDate() bool
- func (v *Value) IsError() bool
- func (v *Value) IsFunction() bool
- func (v *Value) IsInfinity() bool
- func (v *Value) IsMap() bool
- func (v *Value) IsNaN() bool
- func (v *Value) IsNull() bool
- func (v *Value) IsNumber() bool
- func (v *Value) IsObject() bool
- func (v *Value) IsPromise() bool
- func (v *Value) IsSet() bool
- func (v *Value) IsString() bool
- func (v *Value) IsSymbol() bool
- func (v *Value) IsUndefined() bool
- func (v *Value) Keys() (_ []string, err error)
- func (v *Value) Len() int64
- func (v *Value) MarshalJSON() ([]byte, error)
- func (v *Value) New(ctx context.Context, args ...any) (_ *Value, err error)
- func (v *Value) Runtime() *Runtime
- func (v *Value) Set(name string, val any) error
- func (v *Value) SetIndex(i uint32, val any) error
- func (v *Value) SetKey(key *Value, val any) (err error)
- func (v *Value) String() string
- func (v *Value) Time() (time.Time, error)
- func (v *Value) Type() string
- func (v *Value) Uint32() uint32
Constants ¶
This section is empty.
Variables ¶
var ( // ErrRuntimeClosed is returned when a closed runtime, or a value that // belongs to one, is used. ErrRuntimeClosed = errors.New("runtime is closed") // ErrInterrupted is returned when the context of a call is done while // JavaScript is running. The runtime is left in an undefined state: // every later call fails with this error, and it must be closed. ErrInterrupted = errors.New("javascript interrupted") // ErrFreed is returned when a value is used after Free. ErrFreed = errors.New("value is freed") // ErrInvalidFileName is returned when an empty name is evaluated. ErrInvalidFileName = errors.New("file name is required") )
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// CWD is a host directory exposed to JavaScript as "/", used for module
// loading, EvalFile and the qjs:std/qjs:os file APIs. Empty means
// JavaScript has no filesystem access at all. The directory is read-only
// unless WritableCWD is set.
CWD string
// WritableCWD lets JavaScript create, modify and delete files under CWD.
WritableCWD bool
// FS exposes a filesystem to JavaScript as "/", including module
// loading and qjs:std/qjs:os file APIs. FS and CWD are mutually exclusive.
// Nil leaves filesystem access controlled by CWD. Symbolic links are not
// supported through FS. The caller owns FS; closing a runtime only closes
// file handles opened by that runtime.
// Use AdaptFS to wrap a backend such as afero.Fs.
FS FS
// WritableFS allows JavaScript to modify FS. The default is read-only,
// and the backend's own permissions still apply.
WritableFS bool
// Stdout and Stderr receive console.log/console.error and std.out/std.err
// output. Nil discards it.
Stdout io.Writer
Stderr io.Writer
// MemoryLimit, MaxStackSize and GCThreshold configure the QuickJS heap
// limit, stack limit and GC trigger threshold, in bytes. Zero keeps the
// QuickJS default.
MemoryLimit int
MaxStackSize int
GCThreshold int
// DisableInterruption compiles QuickJS without interruption checks,
// which makes compute-heavy JavaScript about 30% faster. Contexts passed
// to calls are then only checked before the call starts, so a runaway
// script can no longer be stopped.
DisableInterruption bool
// CacheDir is a directory where the compiled QuickJS module is cached
// across processes. Empty disables the on-disk cache.
CacheDir string
// DisableBuildCache recompiles the QuickJS module instead of reusing the
// in-memory compilation of earlier runtimes.
DisableBuildCache bool
// contains filtered or unexported fields
}
Config configures a Runtime. The zero value is a sandboxed runtime: no filesystem, no output, no resource limits beyond those of WebAssembly, and interruptible calls.
type Error ¶
type Error struct {
// Name is the error's constructor name, such as "TypeError", or empty
// if a non-Error value was thrown.
Name string
Message string
Stack string
}
Error is a JavaScript exception. Evaluation returns it when JavaScript throws, and a Function that returns it throws an error with its Name, such as "TypeError", into JavaScript.
type EvalOption ¶
type EvalOption func(*evalConfig)
EvalOption configures how code is evaluated or compiled.
func AsModule ¶
func AsModule() EvalOption
AsModule evaluates the code as an ES module rather than a script. Eval then returns the module's default export, or undefined.
func TopLevelAwait ¶
func TopLevelAwait() EvalOption
TopLevelAwait allows `await` at the top level of a script. Modules always allow it.
type FS ¶
FS is a filesystem exposed through Config.FS. Paths use the host's path separators, with the filesystem root addressed as "/" ("\\" on Windows). Implementations shared by several runtimes must support concurrent use.
func AdaptFS ¶
AdaptFS adapts a backend such as afero.Fs without requiring an afero dependency in qngg. Every operation is delegated to the original backend; returned files are the original handles, and optional lstat support is preserved. The caller retains ownership of the backend.
qngg.Config{FS: qngg.AdaptFS(afero.NewMemMapFs()), WritableFS: true}
type FSBackend ¶
type FSBackend[F File] interface { Create(name string) (F, error) Mkdir(name string, perm os.FileMode) error MkdirAll(path string, perm os.FileMode) error Open(name string) (F, error) OpenFile(name string, flag int, perm os.FileMode) (F, error) Remove(name string) error RemoveAll(path string) error Rename(oldname, newname string) error Stat(name string) (os.FileInfo, error) Name() string Chmod(name string, mode os.FileMode) error Chown(name string, uid, gid int) error Chtimes(name string, atime, mtime time.Time) error }
FSBackend describes a filesystem whose open methods return F. Its method set matches afero.Fs; AdaptFS bridges the differing file return types.
type File ¶
type File interface {
io.Closer
io.Reader
io.ReaderAt
io.Seeker
io.Writer
io.WriterAt
Name() string
Readdir(count int) ([]os.FileInfo, error)
Readdirnames(n int) ([]string, error)
Stat() (os.FileInfo, error)
Sync() error
Truncate(size int64) error
WriteString(s string) (int, error)
}
File is an open file in a filesystem. It has the same method set as afero.File, using only standard-library types.
type Function ¶
type Function func(call *FunctionCall) (*Value, error)
Function is a Go function callable from JavaScript. A returned error is thrown as an Error; return an *Error to throw a TypeError, RangeError and so on. A nil value returns undefined. The returned value is handed over to JavaScript: do not use or free it afterwards.
type FunctionCall ¶
type FunctionCall struct {
// contains filtered or unexported fields
}
FunctionCall describes a call of a Function from JavaScript. Its values belong to the caller and are only valid until the Function returns; Clone them to keep them longer.
func (*FunctionCall) Arg ¶
func (c *FunctionCall) Arg(i int) *Value
Arg returns the i-th argument, or undefined if there are fewer arguments.
func (*FunctionCall) Args ¶
func (c *FunctionCall) Args() []*Value
Args returns the arguments of the call.
func (*FunctionCall) Context ¶
func (c *FunctionCall) Context() context.Context
Context returns the context of the call into JavaScript that led to this call, such as the one passed to Runtime.Eval, or context.Background() outside of one.
func (*FunctionCall) Runtime ¶
func (c *FunctionCall) Runtime() *Runtime
Runtime returns the runtime the function was called in.
func (*FunctionCall) This ¶
func (c *FunctionCall) This() *Value
This returns the this value of the call.
type Lstater ¶
Lstater optionally exposes symbolic-link metadata. The boolean reports whether lstat was supported; false means Stat was used instead. Backends that support symbolic links should implement this or Lstat(string).
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool runs JavaScript from several goroutines by handing each one a runtime of its own. Runtimes are created on demand and reused; up to size idle runtimes are kept.
func NewPool ¶
NewPool returns a pool keeping up to size idle runtimes created with config. setup, if not nil, prepares each new runtime, for example by defining globals.
func (*Pool) Close ¶
Close closes the idle runtimes. Runtimes in use are closed when their Do returns.
func (*Pool) Do ¶
Do runs fn with ctx and a runtime that no other goroutine uses until fn returns. Values created in fn must not be used after it returns. The runtime is returned to the pool unless fn panics or the runtime was interrupted or closed, in which case it is discarded. Globals fn defines stay in the runtime for later calls of Do: only what setup defines is guaranteed to be there.
type Runtime ¶
type Runtime struct {
// contains filtered or unexported fields
}
Runtime is a QuickJS runtime with its JavaScript context, running in its own WebAssembly instance. A Runtime is not safe for concurrent use; use a Pool to run JavaScript from several goroutines.
func (*Runtime) Close ¶
Close frees the runtime and everything it owns, including values that were not freed. Calling Close more than once is a no-op; using the runtime or its values afterwards fails with ErrRuntimeClosed.
func (*Runtime) Compile ¶
func (r *Runtime) Compile(name, src string, opts ...EvalOption) ([]byte, error)
Compile compiles src, like Eval would, into bytecode for EvalBytecode or LoadModuleBytecode, without running it. Since no JavaScript runs, it takes no context and cannot be interrupted.
func (*Runtime) CompileFile ¶
func (r *Runtime) CompileFile(path string, opts ...EvalOption) ([]byte, error)
CompileFile is like Compile for the file at path, in Config.FS or relative to Config.CWD.
func (*Runtime) Eval ¶
Eval runs src, a script (or module with AsModule) named `name` for stack traces and relative imports, and returns its completion value. Promises are awaited, and pending jobs and timers run before Eval returns. A JavaScript exception is returned as an *Error.
Cancelling ctx, or reaching its deadline, interrupts the code, after which the runtime fails every call with ErrInterrupted and must be closed.
func (*Runtime) EvalBytecode ¶
func (r *Runtime) EvalBytecode(ctx context.Context, bytecode []byte, opts ...EvalOption) (*Value, error)
EvalBytecode is like Eval for bytecode from Compile. Pass AsModule for bytecode compiled with it.
func (*Runtime) EvalFile ¶
EvalFile is like Eval for the file at path, in Config.FS or relative to Config.CWD. Path separators are converted to "/", the separator module names use.
func (*Runtime) LoadModule ¶
LoadModule compiles the module src and registers it as `name`, so that later code can import it, without running it.
func (*Runtime) LoadModuleBytecode ¶
LoadModuleBytecode is like LoadModule for module bytecode from Compile with AsModule. The module keeps the name it was compiled with.
func (*Runtime) LoadModuleFile ¶
LoadModuleFile is like LoadModule for the file at path, in Config.FS or relative to Config.CWD, registered under that path.
func (*Runtime) NewArrayBuffer ¶
NewArrayBuffer returns an ArrayBuffer holding a copy of data.
func (*Runtime) NewAsyncFunction ¶
NewAsyncFunction returns a JavaScript async function that calls fn: it returns a promise that resolves to fn's result, or rejects with its error.
func (*Runtime) NewBigInt64 ¶
NewBigInt64 returns a BigInt.
func (*Runtime) NewBigUint64 ¶
NewBigUint64 returns a BigInt.
func (*Runtime) NewError ¶
NewError returns an Error whose message is err's message. An *Error keeps its name, so it becomes a TypeError, RangeError and so on.
func (*Runtime) NewFloat64 ¶
NewFloat64 returns a number.
func (*Runtime) NewFunction ¶
NewFunction returns a JavaScript function that calls fn. To expose a typed Go function, with its arguments and results converted, pass it to Set or ToValue instead; a Function is for direct access to the values.
func (*Runtime) NewProxyValue ¶
NewProxyValue wraps a Go value so it can be passed through JavaScript unchanged: converting the result back with Value.As returns v itself.
func (*Runtime) NewUndefined ¶
NewUndefined returns undefined.
func (*Runtime) SetAsyncFunc ¶
SetAsyncFunc assigns a Go function that JavaScript sees as an async function to the global variable `name`.
func (*Runtime) ToValue ¶
ToValue converts a Go value to a JavaScript value: numbers, strings, booleans, nil, time.Time, []byte (as an ArrayBuffer), *big.Int (as a BigInt), errors, slices, arrays, maps, structs (exported fields, using json tags, and methods), functions and channels. A *Value is cloned.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value is a JavaScript value.
Ownership follows one rule: every Value returned to you is yours and must be released with Free, and passing a Value to any method never takes it over. The exceptions are values you do not own, whose Free is a no-op: Runtime.Global, and the arguments and this value of a Function, which are only valid until it returns (Clone them to keep them). Values returned from a Function are handed to JavaScript.
Using a Value after Free, or after its runtime is closed, fails with ErrFreed or ErrRuntimeClosed, or panics with it in methods without an error result.
func (*Value) As ¶
As converts the value to a Go value of type T. Objects convert to maps, structs (matching fields by their json tag or name) and slices; functions convert to Go functions that call them; BigInts convert to *big.Int or to integer types they fit in; ProxyValues convert back to the Go value they wrap.
func (*Value) Await ¶
Await waits for a promise to settle, running pending jobs and timers, and returns its result. A rejection is returned as an error.
func (*Value) Bytes ¶
Bytes returns a copy of the contents of an ArrayBuffer, typed array or DataView.
func (*Value) Call ¶
Call calls the function value with the given this value, which may be nil for undefined, and arguments. Arguments that are not *Value are converted with Runtime.ToValue.
func (*Value) Delete ¶
Delete deletes the own property `name`. It reports false if the property exists but cannot be deleted.
func (*Value) Float64 ¶
Float64 converts the value to a number like JavaScript's Number(). It returns 0 if the conversion throws.
func (*Value) Free ¶
func (v *Value) Free()
Free releases the value. It is a no-op for values you do not own, for values already freed, and once the runtime is closed.
func (*Value) Get ¶
Get returns the property `name`. Getters may run, and their exceptions are returned.
func (*Value) Int32 ¶
Int32 converts the value to a 32-bit integer like JavaScript's `x | 0`. It returns 0 if the conversion throws.
func (*Value) Int64 ¶
Int64 converts the value to a 64-bit integer, truncating fractions and clamping out-of-range numbers. It returns 0 if the conversion throws.
func (*Value) IsArrayBuffer ¶
IsArrayBuffer reports whether the value is an ArrayBuffer.
func (*Value) IsConstructor ¶
IsConstructor reports whether the value is a constructor.
func (*Value) IsFunction ¶
IsFunction reports whether the value is a function.
func (*Value) IsInfinity ¶
IsInfinity reports whether the value is the number Infinity or -Infinity.
func (*Value) IsNumber ¶
IsNumber reports whether the value is a number, including NaN and Infinity.
func (*Value) IsObject ¶
IsObject reports whether the value is an object, including functions and arrays.
func (*Value) IsUndefined ¶
IsUndefined reports whether the value is undefined.
func (*Value) Len ¶
Len returns the value of the `length` property as an integer, or 0 if it has none.
func (*Value) MarshalJSON ¶
MarshalJSON returns the JSON.stringify representation of the value. Values that JSON cannot represent, such as undefined and functions, are encoded as null.
func (*Value) Set ¶
Set sets the property `name` to val, converted with ToValue unless it is a *Value. Setters may run, and their exceptions are returned.
func (*Value) SetKey ¶
SetKey sets the property whose key is the given value to val, converted like in Set.
func (*Value) String ¶
String converts the value to a string like JavaScript's String(). It returns "" if the conversion throws.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
atomicfile
Package atomicfile writes files so that readers, including other processes, never observe partially written content.
|
Package atomicfile writes files so that readers, including other processes, never observe partially written content. |