Documentation
¶
Overview ¶
Package gojs is an embeddable, sandbox-first JavaScript (ECMAScript) runtime for Go applications. It is pure Go with no cgo and no external dependencies, and runs modern JavaScript at high conformance — around 99.99% of the runnable Test262 suite, including Proxy/Reflect, the TypedArray/ArrayBuffer family, SharedArrayBuffer with multi-agent Atomics, BigInt, generators, async/await, and a conformant regular-expression engine.
gojs is organized as a layered pipeline, mirroring a conventional engine. Each stage lives in its own sub-package:
Source → lexer → parser → ast → interp → bytecode compiler → VM - [github.com/iceisfun/gojs/token] — token kinds, source positions, and spans - [github.com/iceisfun/gojs/lexer] — lexical scanner producing tokens - [github.com/iceisfun/gojs/parser] — recursive-descent parser producing an AST - [github.com/iceisfun/gojs/ast] — abstract syntax tree node types - [github.com/iceisfun/gojs/interp] — the runtime: a bytecode compiler + VM (with a tree-walking evaluator as an always-correct fallback and differential oracle), the value model, providers, and the host API - [github.com/iceisfun/gojs/jsregexp] — a standalone, ECMAScript-conformant regular-expression engine (the default RegExp backend; usable on its own)
The optional github.com/iceisfun/gojs/ts package adds TypeScript: it transpiles .ts/.tsx in-process and runs the result. Importing it is what pulls the transpiler dependency into a build; embeddings that only run JavaScript keep the zero-dependency core.
Capability model ¶
Host access (console output, wall-clock time, timers, module loading) is gated behind capability providers, so the default configuration is a closed sandbox: scripts cannot print, read the clock, schedule timers, or require modules unless the embedder opts in. A caller enables each capability explicitly by passing a provider at construction:
vm := gojs.New(
gojs.WithPrintProvider(gojs.NewDefaultPrintProvider()),
)
defer vm.Close()
if _, err := vm.RunString("example.js", `console.log(1 + 2)`); err != nil {
log.Fatal(err)
}
Execution model ¶
A VM runs JavaScript on a single logical thread with an event loop. Host operations may execute concurrently, but they hand results back to the VM by enqueuing exactly one continuation (see github.com/iceisfun/gojs/interp's Enqueue, QueueMicrotask, ResolvePromise, and RejectPromise), preserving the single-threaded invariant that JavaScript itself never runs on two goroutines at once. [VM.Close] cancels the underlying context and drains any outstanding timers and coroutines.
Resource limits ¶
Untrusted code can be bounded with Limits (maximum call depth, evaluation steps, and more) and with a context deadline, so a hostile or buggy script cannot exhaust host resources.
The root package re-exports the most common surface of the interp package so simple embeddings need only import gojs; reach into the sub-packages directly for lower-level access such as custom AST walking or provider implementations.
The gojs package overview and the layered-package map live in doc.go. This file holds the re-exported public surface (types and constructors) that lets simple embeddings depend only on the root package.
Index ¶
- Constants
- Variables
- func BriefValue(v Value) string
- func NewThrow(v Value) error
- type Boolean
- type EvalInfo
- type EvalKind
- type EvalObserver
- type HostFunc
- type Limits
- type ModuleProvider
- type NetProvider
- type Number
- type Object
- type Option
- type OsProvider
- type RegExpEngine
- type Security
- type SourceMapper
- type String
- type VM
- type Value
Constants ¶
const ( EvalIndirect = interp.EvalIndirect // an indirect eval(str) EvalDirect = interp.EvalDirect // a direct eval(str) EvalFunction = interp.EvalFunction // Function(...) / fn.constructor(...) )
Eval compilation kinds delivered to a WithDumpEval observer.
const ( RegExpCompat = interp.RegExpCompat RegExpRE2 = interp.RegExpRE2 )
RegExp backend choices. RegExpCompat (the default) is the ECMAScript-conformant jsregexp engine; RegExpRE2 is the faster, non-conformant RE2 engine.
Variables ¶
var ( WithModuleProvider = interp.WithModuleProvider NewMapModuleProvider = interp.NewMapModuleProvider NewDirModuleProvider = interp.NewDirModuleProvider )
Module provider option and default implementations, re-exported.
var ( WithOsProvider = interp.WithOsProvider NewDefaultOsProvider = interp.NewDefaultOsProvider NewFilteredOsProvider = interp.NewFilteredOsProvider )
OS provider option and default implementations, re-exported.
var ( WithNetProvider = interp.WithNetProvider NewDefaultNetProvider = interp.NewDefaultNetProvider )
Net provider option and default (pass-through) implementation, re-exported.
var ( // Undefined is the JavaScript undefined value. Undefined = interp.Undef // Null is the JavaScript null value. Null = interp.Nul // True and False are the JavaScript boolean values. True = interp.True False = interp.False )
Interned primitive values.
var ( WithContext = interp.WithContext WithPrintProvider = interp.WithPrintProvider WithTimeProvider = interp.WithTimeProvider WithTimerProvider = interp.WithTimerProvider WithSecurity = interp.WithSecurity WithRegExpEngine = interp.WithRegExpEngine NewDefaultPrintProvider = interp.NewDefaultPrintProvider NewDefaultTimeProvider = interp.NewDefaultTimeProvider NewDefaultTimerProvider = interp.NewDefaultTimerProvider )
Provider constructors and options, re-exported for convenience.
var WithDumpEval = interp.WithDumpEval
WithDumpEval installs an observer called for every eval() and Function() compilation, with the source text and parsed AST. See interp.WithDumpEval.
var WithErrorColor = interp.WithErrorColor
WithErrorColor toggles ANSI color in FormatError's rich stack rendering (default on).
var WithLimits = interp.WithLimits
WithLimits sets resource limits at construction.
var WithSourceMapper = interp.WithSourceMapper
WithSourceMapper installs a source mapper for error-stack positions.
Functions ¶
func BriefValue ¶
BriefValue renders a value for host-facing display (e.g. an uncaught exception) without running user toString methods.
Types ¶
type EvalObserver ¶
type EvalObserver = interp.EvalObserver
EvalObserver receives one EvalInfo per dynamic compilation.
type Limits ¶
Limits bounds script resource usage (call depth, step budget). Alias for interp.Limits.
type ModuleProvider ¶
type ModuleProvider = interp.ModuleProvider
ModuleProvider is the interface a host implements to intercept require() and serve module source (e.g. from game data files). Alias for interp.ModuleProvider.
type NetProvider ¶
type NetProvider = interp.NetProvider
NetProvider is the single wall for outbound network dialing by the networking host packages (fetch/sse/websocket). Alias for interp.NetProvider.
type Option ¶
Option configures a VM at construction. Alias for interp.Option.
type OsProvider ¶
type OsProvider = interp.OsProvider
OsProvider gates host OS access (env, cwd, exit, platform/arch/pid) — the capability backing the `process` global. Alias for interp.OsProvider.
type RegExpEngine ¶
type RegExpEngine = interp.RegExpEngine
RegExpEngine selects the RegExp backend passed to WithRegExpEngine.
type Security ¶
Security holds the opt-in hardening switches. Alias for interp.Security.
type SourceMapper ¶
type SourceMapper = interp.SourceMapper
SourceMapper maps transpiled positions in error stacks back to their original source (e.g. TypeScript). Alias for interp.SourceMapper.
type VM ¶
type VM = interp.Interpreter
VM is a JavaScript runtime instance. It is an alias for interp.Interpreter so callers can use the root package without importing interp directly.
type Value ¶
Value is a JavaScript runtime value. Alias for interp.Value.
func ThrownValue ¶
ThrownValue extracts the JavaScript value from an uncaught-exception error returned by RunString/RunProgram.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package ast defines the abstract syntax tree (AST) node types produced by the parser and consumed by the interpreter.
|
Package ast defines the abstract syntax tree (AST) node types produced by the parser and consumed by the interpreter. |
|
cmd
|
|
|
gojs
command
Command gojs runs JavaScript or TypeScript files on the gojs VM with no external tooling: TypeScript is transpiled in-process via the embedded typescript-go hoisting (see package github.com/iceisfun/gojs/ts).
|
Command gojs runs JavaScript or TypeScript files on the gojs VM with no external tooling: TypeScript is transpiled in-process via the embedded typescript-go hoisting (see package github.com/iceisfun/gojs/ts). |
|
examples
|
|
|
basic
command
Example: basic script execution.
|
Example: basic script execution. |
|
call_js
command
Example: calling JavaScript functions from Go.
|
Example: calling JavaScript functions from Go. |
|
expose_go
command
Example: exposing Go functions and data to JavaScript.
|
Example: exposing Go functions and data to JavaScript. |
|
fetch
command
Example: the Fetch API (host/fetch).
|
Example: the Fetch API (host/fetch). |
|
limits
command
Example: resource limits for untrusted code.
|
Example: resource limits for untrusted code. |
|
modules
command
Example: intercepting require() with a ModuleProvider.
|
Example: intercepting require() with a ModuleProvider. |
|
providers
command
Example: capability providers.
|
Example: capability providers. |
|
regexp_engine
command
Example: choosing the RegExp backend.
|
Example: choosing the RegExp backend. |
|
sandbox
command
Example: a hardened sandbox running untrusted code.
|
Example: a hardened sandbox running untrusted code. |
|
sse
command
Example: Server-Sent Events (EventSource) in gojs.
|
Example: Server-Sent Events (EventSource) in gojs. |
|
typescript
command
Example: running TypeScript on the gojs VM, with no external tooling.
|
Example: running TypeScript on the gojs VM, with no external tooling. |
|
websocket
command
Example: a browser-compatible WebSocket client in gojs.
|
Example: a browser-compatible WebSocket client in gojs. |
|
host
|
|
|
fetch
Package fetch installs a WHATWG Fetch API — fetch, Headers, Request, Response, AbortController/AbortSignal — into a gojs VM.
|
Package fetch installs a WHATWG Fetch API — fetch, Headers, Request, Response, AbortController/AbortSignal — into a gojs VM. |
|
process
Package process installs a Node-like `process` global on a gojs VM.
|
Package process installs a Node-like `process` global on a gojs VM. |
|
sse
Package sse installs a WHATWG-compatible Server-Sent Events client (the EventSource web API) into a gojs VM.
|
Package sse installs a WHATWG-compatible Server-Sent Events client (the EventSource web API) into a gojs VM. |
|
websocket
Package websocket provides a browser-compatible WebSocket client for the gojs JavaScript engine.
|
Package websocket provides a browser-compatible WebSocket client for the gojs JavaScript engine. |
|
Package interp is the heart of gojs: a tree-walking evaluator for the AST produced by github.com/iceisfun/gojs/parser, together with the JavaScript value model, the intrinsic prototypes (the "realm"), the capability providers, and the host-facing embedding API.
|
Package interp is the heart of gojs: a tree-walking evaluator for the AST produced by github.com/iceisfun/gojs/parser, together with the JavaScript value model, the intrinsic prototypes (the "realm"), the capability providers, and the host-facing embedding API. |
|
Package jsregexp implements an ECMAScript-conformant regular-expression engine in pure Go.
|
Package jsregexp implements an ECMAScript-conformant regular-expression engine in pure Go. |
|
Package lexer implements a lexical scanner for JavaScript (ECMAScript) source text.
|
Package lexer implements a lexical scanner for JavaScript (ECMAScript) source text. |
|
Package parser implements a recursive-descent parser for JavaScript (ECMAScript), producing an ast.Program from source text.
|
Package parser implements a recursive-descent parser for JavaScript (ECMAScript), producing an ast.Program from source text. |
|
tests
|
|
|
harness
Package harness provides reusable infrastructure for running JavaScript snippets and fixtures against the gojs engine under test.
|
Package harness provides reusable infrastructure for running JavaScript snippets and fixtures against the gojs engine under test. |
|
test262
Package test262 provides a runner for the official ECMAScript conformance suite (Test262), located under reference/test262.
|
Package test262 provides a runner for the official ECMAScript conformance suite (Test262), located under reference/test262. |
|
Package token defines the lexical token types, keywords, and source positions for the gojs JavaScript engine.
|
Package token defines the lexical token types, keywords, and source positions for the gojs JavaScript engine. |
|
Package ts adds TypeScript support to gojs.
|
Package ts adds TypeScript support to gojs. |