js/realm

js/realm/index.ts

fino:realm - Realm construction and management.

A Realm is an isolated V8 Context with its own global object, module graph, microtask queue, and event loop. The parent's import rule list governs every module resolution in the child; the child can layer overrides on top.

Every ordinary realm is hosted by a reactor thread selected by the node scheduler. process: true adds an OS-process isolation boundary while preserving the same Realm API.

The import rule list uses last-match-wins semantics. Declare a wildcard first as the baseline and more specific patterns afterwards as overrides. CLI OpenTelemetry bootstrap metadata follows realm construction separately from user data: children inherit a fino run --otlp-endpoint endpoint by default, otlpEndpoint overrides it for one subtree, and false disables it.

import { Realm, ImportMap } from 'fino:realm';

const realm = new Realm({
  entry: './worker.ts',
  overrides: ImportMap.inherit([
    { pattern: 'fino:process', directive: 'block' },
  ]),
});
const result = await realm.call('job-1');
await realm.terminate();

Types

type ImportDirectiveSer = 'inherit' | 'block' | { type: 'inherit'; } | { type: 'block'; } | { type: 'remap'; target: string; } | { type: 'source'; code: string; source_map: string; } | { type: 'facade'; specifier: string; exports: string[]; streams?: string[]; sinks?: string[]; }

Wire-format representation of an import directive.

Directives control how a child realm resolves an import that matches an ImportRule. String forms are accepted for convenience and normalized to the Rust serde layout before crossing the native bridge. source injects an in-memory module, remap redirects to another specifier, and facade exposes parent-side RPC handlers.

import type { ImportDirectiveSer } from 'fino:realm';

const directive: ImportDirectiveSer = {
  type: 'remap',
  target: './sandboxed-logger.ts',
};

type RealmFn = (...args: any[]) => any

Function shape used by Realm.call().

A child entry module should default-export a function compatible with this type when the parent intends to call it. Arguments and return values must be supported by the active transport serializer.

import type { RealmFn } from 'fino:realm';

const worker: RealmFn = (name: string) => `hello ${name}`;
export default worker;

Interfaces

interface ImportRule {

Import rule applied to module resolution inside a child realm.

Rules are evaluated with last-match-wins semantics after the parent realm's inherited rules. A matching rule may inherit, block, remap, inject source, or expose a facade. Invalid patterns are rejected by the native loader when the child realm is created.

import type { ImportRule } from 'fino:realm';

const rule: ImportRule = {
  pattern: 'fino:process',
  directive: 'block',
};

Properties

from?: string

Optional pattern matching the importing module's specifier.

When omitted, the rule can apply regardless of which module performs the import. Use this for broad allow/deny lists, and provide from when only a specific importer should receive an override.

import type { ImportRule } from 'fino:realm';

const rule: ImportRule = {
  from: './plugin-host.ts',
  pattern: './plugin-api.ts',
  directive: 'inherit',
};
pattern: string

Pattern matching the specifier being imported.

This field is required. * is commonly used as a baseline rule, with more specific patterns appended later as overrides.

import type { ImportRule } from 'fino:realm';

const blockAll: ImportRule = { pattern: '*', directive: 'block' };
directive: ImportDirectiveSer

Resolution action to apply when the rule matches.

inherit falls back to the parent rule set, block rejects resolution, and object forms can remap, inject source, or expose a facade. Facade instances are accepted and normalized during realm construction.

import type { ImportRule } from 'fino:realm';

const rule: ImportRule = {
  pattern: 'virtual:config',
  directive: { type: 'source', code: 'export const port = 8080;', source_map: '' },
};

interface RealmProviders {

Legacy provider overrides installed in a child realm.

Prefer RealmOptions.overrides with explicit import rules for new code. Unspecified providers are inherited from the parent realm.

import { DiskFsConfig, type RealmProviders } from 'fino:realm';

const providers: RealmProviders = {
  fs: new DiskFsConfig({ root: '/srv/app' }),
};

Properties

fs?: DiskFsConfig

Filesystem provider override.

When omitted, filesystem bindings are inherited. This compatibility field currently supports the disk filesystem provider config.

import { DiskFsConfig, type RealmProviders } from 'fino:realm';

const providers: RealmProviders = { fs: new DiskFsConfig() };
net?: SystemNetConfig

Network provider override.

When omitted, network provider bindings are inherited.

import { SystemNetConfig, type RealmProviders } from 'fino:realm';

const providers: RealmProviders = { net: new SystemNetConfig() };
dns?: SystemDnsConfig

DNS provider override.

When omitted, DNS provider bindings are inherited.

import { SystemDnsConfig, type RealmProviders } from 'fino:realm';

const providers: RealmProviders = { dns: new SystemDnsConfig() };

interface RealmOptions {

Options for constructing and running a child realm.

process: true requests an OS-process isolation boundary. Without it, the allocator normally places the realm on the node's reactor pool and may fall back to a dedicated reactor when the pool cannot admit it. Same-isolate placement is reserved for configurations that require direct port coupling or REPL behavior.

import { Realm, type RealmOptions } from 'fino:realm';

const options: RealmOptions = { entry: './worker.ts' };
const realm = new Realm(options);

Properties

entry: string

Path to the entry module to evaluate in the child realm.

The path is resolved by the runtime loader using the realm root and import rules. The module may default-export a function for Realm.call().

import type { RealmOptions } from 'fino:realm';

const options: RealmOptions = { entry: './worker.ts' };
root?: string

Filesystem root for module resolution.

When omitted, the child inherits the parent's root. The root affects module lookup and any providers that consult realm root state.

import type { RealmOptions } from 'fino:realm';

const options: RealmOptions = { entry: './worker.ts', root: '/srv/app' };
overrides?: ImportMap | ImportRule[]

Import rules for this Realm. Appended after the parent's rules; last-match-wins. Use ImportMap.deny([...]) or ImportMap.inherit([...]).

import { ImportMap, type RealmOptions } from 'fino:realm';

const options: RealmOptions = {
  entry: './worker.ts',
  overrides: ImportMap.deny([{ pattern: './api.ts', directive: 'inherit' }]),
};
providers?: RealmProviders

Override specific I/O providers. Unspecified providers are inherited.

import { DiskFsConfig, type RealmOptions } from 'fino:realm';

const options: RealmOptions = {
  entry: './worker.ts',
  providers: { fs: new DiskFsConfig() },
};
blocked?: string[]

Module specifiers that should throw on import in the child Realm.

import type { RealmOptions } from 'fino:realm';

const options: RealmOptions = {
  entry: './worker.ts',
  blocked: ['fino:process'],
};
process?: boolean

If true, spawn the child Realm as a separate OS process for hard crash isolation and OS-level sandbox enforcement. Messaging uses framed binary over a Unix socketpair. This is an isolation boundary the allocator must honor, not a placement hint — plain realms are placed on a reactor by the allocator automatically.

import type { RealmOptions } from 'fino:realm';

const options: RealmOptions = { entry: './worker.ts', process: true };
watch?: boolean

If true, automatically restart the child Realm whenever any file it imported changes on disk. The JS Realm instance is stable across reloads; only the underlying V8 context / thread / process is replaced.

import type { RealmOptions } from 'fino:realm';

const options: RealmOptions = { entry: './worker.ts', watch: true };
repl?: boolean

If true, run this child Realm in REPL mode. The child listens for { __eval, id, code } messages on its port and responds with { __eval_result } or { __eval_error }. It is not compatible with process isolation or watch mode.

import type { RealmOptions } from 'fino:realm';

const options: RealmOptions = { entry: './repl-host.ts', repl: true };
data?: unknown

Arbitrary JSON-serializable configuration delivered to the child realm. The child reads it via internal:realm-bridge.getRealmData() before the entry module is imported, so it can shape application-specific worker configuration. Runtime bootstrap metadata such as otlpEndpoint is stored separately and does not appear here.

import type { RealmOptions } from 'fino:realm';

const options: RealmOptions = { entry: './worker.ts', data: { role: 'ingest' } };
otlpEndpoint?: string | false

OTLP/HTTP collector endpoint for CLI OpenTelemetry bootstrap in this realm.

When omitted, the child inherits the current realm's CLI endpoint, if one was seeded by fino run --otlp-endpoint or OTEL_EXPORTER_OTLP_ENDPOINT. Passing a non-empty string overrides that endpoint for this realm. Passing false disables CLI OpenTelemetry bootstrap for this realm even when the parent has an endpoint. The endpoint is runtime bootstrap metadata and does not appear in RealmOptions.data or getRealmData().

import { Realm, type RealmOptions } from 'fino:realm';

const options: RealmOptions = {
  entry: './worker.ts',
  otlpEndpoint: 'http://127.0.0.1:4318',
};
localMobility?: 'movable' | 'pinned'

Whether a pool-hosted realm may move between reactor threads on the same node. The default is movable; use pinned only for native integrations that intentionally depend on OS-thread affinity.

Local movement transfers the same V8 isolate at a pump boundary. It does not reconstruct the realm, reset module state, or change realm.port. Process-isolated realms ignore this option.

import { Realm } from 'fino:realm';

const realm = new Realm({
  entry: './thread-affine-worker.ts',
  localMobility: 'pinned',
});
scaling?: RealmScalingOptions

Isolate replication and availability policy.

Realms are replicated by default: the scheduler may construct independent isolates from the same entry, import rules, and initial data. Their heaps are not synchronized, so applications whose correctness depends on private mutable heap state must select bound.

min defaults to 1. max defaults to the live cluster reactor count and is always capped by eligible physical capacity. Bound realms require exactly one replica and run in the lower-priority isolated pool.

import { Realm } from 'fino:realm';

const worker = new Realm({
  entry: './request-worker.ts',
  scaling: { mode: 'replicated', min: 2 },
});

interface RealmScalingOptions {

Replication bounds for a logical Realm.

Properties

mode?: 'replicated' | 'bound'

Independent heaps may replicate; bound preserves one caller-bound heap. Defaults to replicated.

min?: number

Availability minimum. Defaults to one and must not exceed max.

max?: number

Optional ceiling; live eligible reactor count remains the hard maximum.

scaleUpWindowMs?: number

Queue-pressure stabilization window before adding a replica. Defaults to 1 second.

scaleDownBusyRatio?: number

Busy-ratio ceiling for scale-down eligibility. Defaults to 10 percent.

scaleDownWindowMs?: number

Quiet stabilization window before draining an excess replica. Defaults to 30 seconds.

loopDelayTargetMs?: number

Target runnable-loop delay used by cluster reconciliation. Defaults to 5 milliseconds.

interface RealmSourceOptions extends Omit<RealmOptions, 'entry' | 'watch'> {

Options for creating a Realm from in-memory entrypoint source.

Source realms run the provided text as a normal ESM entry module, so static imports, type imports, and top-level await behave the same as file-backed entries. watch is intentionally unavailable because there is no entry file to monitor; use a file-backed Realm when entrypoint reloads are required.

import { Realm } from 'fino:realm';

const realm = Realm.fromSource(`
  import { basename } from 'fino:file/path';

  if (basename('/tmp/example.ts') !== 'example.ts') {
    throw new Error('unexpected basename');
  }
`);
await realm.run();

Properties

specifier?: string

Module specifier assigned to the source entry.

When omitted, Fino generates a unique fino:realm/source/... specifier. Provide an absolute file path or file:// URL when relative imports inside the source should resolve from a specific directory.

sourceMap?: string

Optional source map JSON for the provided source text.

Invalid or empty source maps are ignored by the runtime. The value defaults to an empty string, matching other source import directives.

Classes

class ImportMap {

An ordered list of import rules to apply to a child Realm.

Rules are last-match-wins. Use ImportMap.deny([...overrides]) to start with a block-all baseline and punch specific exceptions, or ImportMap.inherit([...overrides]) to inherit all and restrict specifics.

The rules in this object are the child-specific overrides that are appended after the parent's rules. The parent's rules always form the baseline.

const documentedClass = 'ImportMap';
console.log(documentedClass);

Constructors

constructor(rules: ImportRule[])

Create an ordered import map from explicit rules.

The rules are stored as child-specific overrides and later appended after parent rules. The constructor does not add a wildcard baseline; use ImportMap.deny() or ImportMap.inherit() when you want that default.

import { ImportMap } from 'fino:realm';

const map = new ImportMap([{ pattern: 'fino:process', directive: 'block' }]);

Static Methods

static deny(overrides: ImportRule[]): ImportMap

Deny everything by default; allow/remap/facade specific specifiers.

The wildcard { pattern: '*', directive: 'block' } is prepended, then the caller's overrides follow (each overrides the wildcard for its pattern).

import { ImportMap, Realm } from 'fino:realm';

const overrides = ImportMap.deny([
  { pattern: './worker-api.ts', directive: 'inherit' },
]);
new Realm({ entry: './worker.ts', overrides });
static inherit(overrides: ImportRule[]): ImportMap

Inherit everything from the parent by default; restrict specific specifiers.

The wildcard { pattern: '*', directive: 'inherit' } is prepended; the caller's overrides follow. Effectively a no-op wildcard (Inherit is dropped on the Rust side), but makes the intent explicit in code.

import { ImportMap, Realm } from 'fino:realm';

const overrides = ImportMap.inherit([
  { pattern: 'fino:process', directive: 'block' },
]);
new Realm({ entry: './worker.ts', overrides });

class FacadeHandle {

A stateful object handle returned from a Facade handler.

When a scalar handler returns a FacadeHandle, the parent registers its methods under a unique ID and sends { __handle: id, streams?: [...] } to the child. The child receives a Proxy that routes subsequent method calls back through internal:parent-rpc using the handle ID as the specifier.

facade.handle('open', async (path) => {
  const fh = await realFs.open(path, 'r');
  return new FacadeHandle(
    { stat: () => fh.stat(), close: () => fh.close() },
    { read: (_size) => fh.reader() },   // streaming method
  );
});

Constructors

constructor( scalar: Record<string, ( ...args: unknown[] ) => unknown> = { }, streams: Record<string, ( ...args: unknown[] ) => AsyncIterable<unknown>> = { }, sinks: Record<string, ( args: unknown[], source: AsyncIterable<unknown> ) => Promise<unknown>> = { } )

Create a stateful handle with scalar, read-stream, and write-stream methods.

Scalar methods return one response, stream methods return an AsyncIterable, and sink methods receive chunks from the child as an AsyncIterable. Empty maps are allowed.

import { FacadeHandle } from 'fino:realm';

const handle = new FacadeHandle(
  { stat: () => ({ size: 10 }) },
  { read: async function* () { yield new Uint8Array([1, 2, 3]); } },
);

class Facade {

Public facade exposed to a child realm as a synthetic module.

A facade declares the names available to child imports and binds parent-side handlers for those names. Calls cross the realm boundary through RPC, so arguments and results must be serializable by the active realm transport unless they are represented as streams or FacadeHandle proxies.

import { Facade, ImportMap, Realm } from 'fino:realm';

const api = new Facade('app:api', ['version'])
  .handle('version', async () => '1.0.0');

new Realm({
  entry: './worker.ts',
  overrides: ImportMap.inherit([{ pattern: 'app:api', directive: api }]),
});

Constructors

constructor(specifier: string, exports: string[])

Create a facade for a synthetic module specifier.

exports declares the scalar method names visible in the child module. Register matching handlers with handle(). Stream and sink names are declared by stream() and sendStream().

import { Facade } from 'fino:realm';

const facade = new Facade('app:math', ['double'])
  .handle('double', async (value) => Number(value) * 2);

Static Methods

static from(obj: object, opts: { specifier: string; }): Facade

Create a facade from callable properties on an object or class instance.

Own functions and prototype methods are exported. Non-function properties are ignored. Each generated handler calls the original method with the original object as the receiver expression.

import { Facade } from 'fino:realm';

const service = { ping: async () => 'pong' };
const facade = Facade.from(service, { specifier: 'app:service' });

Methods

handle(method: string, fn: (...args: unknown[]) => Promise<unknown>): this

Register a scalar handler.

The handler receives the child call arguments and returns one result. A thrown error or rejected promise is sent back as an RPC error. Returning a FacadeHandle creates a stateful child-side proxy.

import { Facade } from 'fino:realm';

const facade = new Facade('app:math', ['add']);
facade.handle('add', async (a, b) => Number(a) + Number(b));
stream(method: string, fn: (...args: unknown[]) => AsyncIterable<unknown>): this

Register a read-stream handler - the AsyncIterable it returns is pumped as __rpc_chunk / __rpc_end / __rpc_err envelopes (parent->child).

The method name is added to the facade's stream export list if it is not already present. Errors thrown while creating or consuming the iterable are delivered to the child as stream errors.

import { Facade } from 'fino:realm';

const facade = new Facade('app:logs', []);
facade.stream('tail', async function* () {
  yield 'line one';
});
sendStream( method: string, fn: ( args: unknown[], source: AsyncIterable<unknown> ) => Promise<unknown> ): this

Register a write-stream (sink) handler - the child sends chunks to the parent via __rpc_send_chunk envelopes (child->parent, no per-chunk ack).

The handler receives (args, source: AsyncIterable<unknown>) and should drain source to completion before returning the final result.

Maps directly onto a QUIC client-initiated unidirectional stream when the cluster transport is later upgraded to QUIC.

import { Facade } from 'fino:realm';

const facade = new Facade('app:upload', []);
facade.sendStream('write', async (_args, source) => {
  let total = 0;
  for await (const chunk of source) total += (chunk as Uint8Array).byteLength;
  return { bytesWritten: total };
});

class DiskFsConfig {

Use the real on-disk filesystem for this realm.

This legacy provider config is kept for backwards compatibility. New code should prefer explicit import rules where possible.

import { DiskFsConfig, Realm } from 'fino:realm';

new Realm({
  entry: './worker.ts',
  providers: { fs: new DiskFsConfig({ root: '/srv/app' }) },
});

Readonly Properties

readonly type

Provider discriminator serialized by toJSON().

import { DiskFsConfig } from 'fino:realm';

console.log(new DiskFsConfig().type);
readonly options: DiskFsOptions

Options supplied to the disk filesystem provider.

The object is stored as provided by the constructor. Omitted options are represented by an empty object.

import { DiskFsConfig } from 'fino:realm';

const config = new DiskFsConfig({ root: '/tmp/app' });
console.log(config.options.root);

Constructors

constructor(options: DiskFsOptions = {})

Create a disk filesystem provider config.

The default options object is empty. Construction does not verify that the root exists; provider setup handles filesystem failures later.

import { DiskFsConfig } from 'fino:realm';

const config = new DiskFsConfig({ root: '/srv/app' });

Methods

toJSON(): Record<string, unknown>

Serialize this provider config.

The result includes the provider type and any configured options. It is suitable for legacy config persistence, not for direct import-rule use.

import { DiskFsConfig } from 'fino:realm';

const json = new DiskFsConfig({ root: '/srv/app' }).toJSON();

Static Methods

static fromJSON(json: Record<string, unknown>): DiskFsConfig

Recreate a disk provider config from serialized data.

Unknown keys are ignored. Missing root produces a config with default options.

import { DiskFsConfig } from 'fino:realm';

const config = DiskFsConfig.fromJSON({ type: 'disk', root: '/srv/app' });

class SystemNetConfig {

Use the system network stack for this realm.

This legacy provider config maps the network provider import back to the inherited system provider.

import { Realm, SystemNetConfig } from 'fino:realm';

new Realm({ entry: './worker.ts', providers: { net: new SystemNetConfig() } });

Readonly Properties

readonly type

Provider discriminator serialized by toJSON().

import { SystemNetConfig } from 'fino:realm';

console.log(new SystemNetConfig().type);

Methods

toJSON(): Record<string, unknown>

Serialize this provider config.

The result has no options because the system network provider has no JS-visible configuration in this compatibility layer.

import { SystemNetConfig } from 'fino:realm';

const json = new SystemNetConfig().toJSON();

Static Methods

static fromJSON(_json: Record<string, unknown>): SystemNetConfig

Recreate a system network provider config from serialized data.

The input is accepted for compatibility and otherwise ignored.

import { SystemNetConfig } from 'fino:realm';

const config = SystemNetConfig.fromJSON({ type: 'system-net' });

class SystemDnsConfig {

Use the system DNS resolver for this realm.

This legacy provider config maps DNS provider imports back to the inherited system resolver.

import { Realm, SystemDnsConfig } from 'fino:realm';

new Realm({ entry: './worker.ts', providers: { dns: new SystemDnsConfig() } });

Readonly Properties

readonly type

Provider discriminator serialized by toJSON().

import { SystemDnsConfig } from 'fino:realm';

console.log(new SystemDnsConfig().type);

Methods

toJSON(): Record<string, unknown>

Serialize this provider config.

The result has no options because the system DNS provider has no JS-visible configuration in this compatibility layer.

import { SystemDnsConfig } from 'fino:realm';

const json = new SystemDnsConfig().toJSON();

Static Methods

static fromJSON(_json: Record<string, unknown>): SystemDnsConfig

Recreate a system DNS provider config from serialized data.

The input is accepted for compatibility and otherwise ignored.

import { SystemDnsConfig } from 'fino:realm';

const config = SystemDnsConfig.fromJSON({ type: 'system-dns' });

class ProcessPort extends BaseTransportPort {

ProcessPort wraps the process realm native functions with the same event-loop integration as ThreadPort: register the wake-fd with loop.readable(), drain messages on each wake, dispatch as MessageEvents.

Process ports are created by new Realm({ process: true }); application code normally uses the port through realm.port. Posting to a closed port is a no-op. Only transferable ArrayBuffer values are extracted from transfer lists.

import { Realm } from 'fino:realm';

const realm = new Realm({ entry: './worker.ts', process: true });
realm.port.postMessage({ ready: true });
realm.port.start();

Readonly Properties

readonly finished: Promise<'released' | 'reload'>

Resolves when the process-hosted reactor exits or asks to reload.

Constructors

constructor(wakeReadFd: number, handle: number)

Create a process transport port from native process realm handles.

This constructor is part of the runtime bridge. Prefer constructing a process realm and using its port; invalid handles can break event-loop integration or fail native sends.

import { ProcessPort } from 'fino:realm';

const port = new ProcessPort(wakeReadFd, nativeHandle);
port.start();

Methods

postMessage(message: any, transferOrOpts?: Transferable[] | StructuredSerializeOptions): void

Serialize and send a message to the process realm.

Messages use the runtime serializer. Transfer lists may include ArrayBuffer instances. Other transferable values, including MessagePort, are rejected because process-realm transport cannot move live in-process handles across the process boundary. Calling after close() returns without sending.

import { Realm } from 'fino:realm';

const realm = new Realm({ entry: './worker.ts', process: true });
realm.port.postMessage({ job: 'start' });

class Realm<F extends RealmFn = RealmFn> {

Isolated child realm with its own module graph and communication port.

Ordinary realms run on a scheduler-owned reactor thread. Process-isolated realms use the same API with a separate OS process boundary. Use run() for entry modules with side effects and call() for callable entry modules.

import { Realm } from 'fino:realm';

const realm = new Realm<(name: string) => string>({ entry: './worker.ts' });
const message = await realm.call('Ana');
realm.terminate();

Readonly Properties

readonly port: MessagePort | BaseTransportPort

Parent-side port for general communication with the child realm.

Reactor realms expose a ThreadPort; process-isolated realms expose a ProcessPort. Start the port before listening for messages.

import { Realm } from 'fino:realm';

const realm = new Realm({ entry: './worker.ts' });
realm.port.addEventListener('message', (event) => console.log(event.data));
realm.port.start();

Static Methods

static fromSource<F extends RealmFn = RealmFn>( source: string, options: RealmSourceOptions = { } ): Realm<F>

Create a Realm whose entrypoint is in-memory module source.

The source is installed as an import-rule-backed entry module and then evaluated by the same Realm machinery used for file entries. Caller import rules, provider overrides, blocked specifiers, and execution mode options are preserved. Source entries cannot use watch because there is no entry file to monitor for changes.

import { Realm } from 'fino:realm';

const realm = Realm.fromSource(`
  await Promise.resolve();
  globalThis.value = 42;
`);
await realm.run();

Constructors

constructor(opts: RealmOptions)

Create a child realm and its parent-side communication port.

The constructor builds import rules, creates the selected execution mode, and binds facade RPC dispatchers. It throws for invalid option combinations or native creation failures.

import { ImportMap, Realm } from 'fino:realm';

const realm = new Realm({
  entry: './worker.ts',
  overrides: ImportMap.inherit([]),
});

Methods

run(): Promise<void>

Run the child realm to completion.

The returned promise resolves when the child exits cleanly and rejects when the child reports a runtime error. Watch-mode realms keep the promise pending across reloads until terminate() stops watching.

import { Realm } from 'fino:realm';

const realm = new Realm({ entry: './worker.ts' });
await realm.run();
call(...args: Parameters<F>): Promise<Awaited<ReturnType<F>>>

Call the child Realm's default-exported function with args.

The call starts the realm, sends { __call: true, args }, and resolves with the returned value. It rejects if the realm exits before returning, if the child serializes a call error, or if its reactor exits. The port is closed after the first response for non-streaming calls.

import { Realm } from 'fino:realm';

const realm = new Realm<(a: number, b: number) => number>({ entry: './add.ts' });
const sum = await realm.call(2, 3);
terminate(): void

Signal the child realm to stop.

Reactor and process-isolated realms receive a __terminate message. The method is synchronous and does not wait for run() to settle.

import { Realm } from 'fino:realm';

const realm = new Realm({ entry: './worker.ts' });
realm.terminate();
ref(): this

Keep this logical Realm deployment warm and make it contribute to its owner's liveness. Active calls and run() are referenced independently; this flag controls otherwise-idle capacity.

unref(): this

Allow an idle logical Realm deployment to drain without keeping its owner alive. In-flight calls and a pending run() still retain their own work.

hasRef(): boolean

Return whether this Realm has an explicit idle-liveness reference.