Skip to main content

StaticJsRealm

The top-level construct for sandboxed JavaScript execution. Each realm has its own prototypes, globals, and task queue.

Import

import { StaticJsRealm } from "@suntime-js/core";

StaticJsRealm(opts?)

Creates a new realm. Can be called with or without new.

const realm = StaticJsRealm();
const realm = new StaticJsRealm();
const realm = StaticJsRealm({ global: { properties: { ... } } });

Options

global

Type: StaticJsRealmGlobalOption

Sets the global object for the realm. All built-in intrinsics (Array, Object, Promise, etc.) are installed here, and top-level var declarations and function declarations are added to it at evaluation time. Accepts a global option.

You can add your own properties before construction via the properties form, or override intrinsics after construction:

realm.global.defineOwnPropertySync("myApi", {
value: realm.types.toStaticJsValue({ greet: () => "hello" }),
});

globalThis

Type: StaticJsRealmGlobalOption

Sets the value that sandboxed code sees when it reads globalThis. Accepts a global option.

When omitted, globalThis inside the sandbox refers to the same object as global. Setting this option lets the two diverge; the global object still backs the environment and holds intrinsics, but globalThis evaluates to a different value. This mirrors the ECMAScript spec, which keeps the global object and [[GlobalThisValue]] as separate slots.

const realm = StaticJsRealm({
globalThis: {
value: realm.types.proxy(backingGlobal, handlerObject),
},
});

In most cases you only need global, not globalThis.

modules

Type: Record<string, StaticJsModuleResolution>

A static map of module specifiers to module implementations. Consulted first during import resolution. See StaticJsModuleResolution.

const realm = StaticJsRealm({
modules: {
"my-lib": {
exports: { add: (a, b) => a + b },
},
},
});

resolveImportedModule

Type: (specifier: string, referencingModule: StaticJsModule) => Promise<StaticJsModuleResolution>

Called for module specifiers not found in modules. Return a StaticJsModuleResolution or a Promise that resolves to one. See StaticJsModuleResolver for the full type signature and an example.

runTask

Type: StaticJsTaskRunner

Default task runner used by evaluateExpression, evaluateScript, and evaluateModule. Overridable per-call via opts.runTask. See Task Runners.

runTaskSync

Type: StaticJsTaskRunner

Default task runner used by evaluateExpressionSync and evaluateScriptSync, and for synchronous sub-task evaluation (e.g. StaticJsValue.toNative, StaticJsModule.getExportSync). The runner must drive the task iterator to completion before returning. Overridable per-call via opts.runTask.

If the task is not completed synchronously, a StaticJsSynchronousTaskIncompleteError is thrown. See Task Runners.

hooks

Type: StaticJsRealmHookOptions

Partial overrides for engine-internal behavior. All hooks receive the realm as their first argument.

hooks.math

Override individual Math.* implementations. Useful for deterministic behavior across engines, since many Math functions are implementation-defined by the spec.

The signature will match the same signature from the Math[key] set of functions. All arguments will be converted to javascript numbers before being passed to the hook. For variadic functions, they can accept any number of arguments. Otherwise, you will get exactly Math[key].length arguments.

You are expected to return a native javascript number, which will be converted back to the sandboxed representation by the realm.

Supported keys: acos, acosh, asin, asinh, atan, atan2, atanh, cbrt, cos, cosh, exp, expm1, hypot, log, log10, log1p, log2, random, sin, sinh, sqrt, tan, tanh

const realm = StaticJsRealm({
hooks: {
math: {
random: () => 0.5, // deterministic
},
},
});

Properties

types

Type: StaticJsTypeFactory

The type factory for this realm. Use it to create and coerce values.

global

Type: StaticJsObject

The global object for this realm. Equivalent to globalThis in most host environments. You can add properties to it after construction:

realm.global.defineOwnPropertySync("myApi", {
value: realm.types.toStaticJsValue({ greet: () => "hello" }),
});

globalThis

Type: StaticJsValue

The value of globalThis as seen inside the sandbox.

config

Type: StaticJsConfig

The configuration the realm was created with.

intrinsics

Type: Intrinsics

The built-in objects of the realm (e.g. Array.prototype, Function.prototype).


Methods

evaluateExpression(expression, opts?)

evaluateExpression(
expression: string,
opts?: StaticJsRealmEvaluateSourceOptions,
): Promise<StaticJsValue>

Queues a JavaScript expression for evaluation. Returns a promise that resolves to the result. If the realm is idle the expression begins in the next macrotask; otherwise it runs after all queued tasks complete.

Options are documented at StaticJsRealmEvaluateSourceOptions.

evaluateExpressionSync(expression, opts?)

evaluateExpressionSync(
expression: string,
opts?: StaticJsRealmEvaluateSourceOptions,
): StaticJsValue

Evaluates a JavaScript expression synchronously and returns the result.

Must not be called while the realm is already evaluating asynchronously, unless the call originates from within that evaluation (e.g. a host function called by sandboxed code). Violating this throws StaticJsConcurrentEvaluationError.

Options are documented at StaticJsRealmEvaluateSourceOptions.

evaluateScript(script, opts?)

evaluateScript(
script: string,
opts?: StaticJsRealmEvaluateScriptOptions,
): Promise<StaticJsValue>

Queues a script for evaluation. Returns a promise that resolves to the script's completion value.

Options are documented at StaticJsRealmEvaluateSourceOptions.

evaluateScriptSync(script, opts?)

evaluateScriptSync(
script: string,
opts?: StaticJsEvaluateScriptSyncOptions,
): StaticJsValue

Evaluates a script synchronously. Same concurrency constraints as evaluateExpressionSync.

Options are documented at StaticJsRealmEvaluateSourceOptions. topLevelAwait is not supported in the sync variant.

evaluateModule(code, opts?)

evaluateModule(
code: string,
opts?: StaticJsRealmEvaluateSourceOptions,
): Promise<StaticJsModule>

Links and evaluates an ECMAScript module. Returns a promise that resolves to the resulting StaticJsModule.

Module linking happens immediately; declaration and evaluation are queued. If the module (or any dependency) uses top-level await, the promise waits for the full module graph to settle before resolving.

There is no synchronous equivalent.

Options are documented at StaticJsRealmEvaluateSourceOptions.

awaitCurrentTask()

awaitCurrentTask(): Promise<void>

Returns a promise that resolves when the current macrotask and all its microtasks have finished. Other queued macrotasks may still be pending.

awaitIdle()

awaitIdle(): Promise<void>

Returns a promise that resolves when there are no remaining macrotasks or microtasks.

Guarantees:

  • awaitIdle promises taken before a new task is queued resolve before that task begins.
  • awaitIdle called after a task is queued still awaits that task, even if earlier awaitIdle calls are still resolving.

Option types

StaticJsRealmGlobalOption

Three forms are accepted for global and globalThis:

Property declarations

{
properties: {
answer: { value: 42, writable: false },
computed: {
get() { return Date.now(); },
},
},
}

Each property is either a data descriptor (value, writable?, enumerable?, configurable?) or an accessor descriptor (get?, set?, enumerable?, configurable?). Accessor get/set may return a StaticJsValue, a native value to coerce, or be an EvaluationGenerator.

Values and accessors may either be StaticJsValue instances, or native host values and functions. If native, they will be coerced according to the Type Coercion Rules.

Native value

A fixed value can be specified:

{
value: myObject;
}

The value is coerced to a StaticJsObject via Type Coercion. Must be object-like.

Factory function

Factory functions receive the type factory and return a StaticJsObject:

(types) =>
types.object({
myProp: {
value: types.number(42),
},
});

StaticJsRunTaskOptions

PropertyTypeDescription
runTaskStaticJsTaskRunnerOverride the task runner for this single invocation.

StaticJsRealmEvaluateSourceOptions

Extends StaticJsRunTaskOptions.

PropertyTypeDescription
sourceNamestringName shown in stack traces and debugger output.

StaticJsRealmEvaluateScriptOptions

Extends StaticJsRealmEvaluateSourceOptions.

PropertyTypeDefaultDescription
topLevelAwaitboolean | "auto"falseAllow await at the top level. true always returns a promise; "auto" returns a promise only if await is present; false throws a syntax error if await is used. Not available on evaluateScriptSync.
strictbooleanfalseForce strict mode regardless of "use strict" directives.

StaticJsModuleResolution

See StaticJsModuleResolution in the Modules reference.


Type guard

isStaticJsRealm(value)

import { isStaticJsRealm } from "@suntime-js/core";

isStaticJsRealm(value: unknown): value is StaticJsRealm

Returns true if value is a StaticJsRealm instance. Useful when accepting realm references from untrusted or loosely-typed sources.