Skip to main content

Installation

Initialization

registerWorker

Register the worker with a iii instance, returns a connected worker client. The WebSocket connection is established automatically. Signature
string
required
WebSocket URL of the III engine (e.g. ws://localhost:49135).
InitOptions
Optional InitOptions for worker name, timeouts, and reconnection.

Methods

registerTrigger

Deprecated. Use ISdk.observe instead: iii.observe({ function_id, args, filters }, target, { metadata }). Logs a warning once per page. The http, cron, queue, state, stream, pubsub and database workers still publish trigger types: keep using registerTrigger for them until they ship source functions. Migration guide: https://iii.dev/docs/upgrading/from-0-24-x
Registers a new trigger. A trigger is a way to invoke a function when a certain event occurs. Signature
RegisterTriggerInput
required
The trigger to register

registerFunction

Registers a new function with a local async handler that runs in the browser session. HTTP invocation configs are a Node.js SDK feature. Signature
string
required
Unique function identifier
RemoteFunctionHandler
required
Async handler executed when the function is invoked
RegisterFunctionOptions
Optional function registration options (description, request/response formats, metadata)

trigger

Invokes a function using a request object. Signature
TriggerRequest<TInput>
required
The trigger request containing function_id, payload, and optional action/timeout

registerTriggerType

Deprecated. Register a function with an observe descriptor instead: registerFunction(id, handler, { observe: { delivery: 'owner', onObserverAdded, onObserverRemoved } }). Logs a warning once per page. Migration guide: https://iii.dev/docs/upgrading/from-0-24-x
Registers a new trigger type. A trigger type is a way to invoke a function when a certain event occurs. Signature
RegisterTriggerTypeInput
required
The trigger type to register
TriggerHandler<TConfig>
required
The handler for the trigger type

unregisterTriggerType

Deprecated. Trigger types are replaced by functions with an observe descriptor.
Unregisters a trigger type. Signature
RegisterTriggerTypeInput
required
The trigger type to unregister

addConnectionStateListener

Subscribe to connection-state transitions. The handler is fired immediately with the current state, then on every transition. Multiple listeners are supported. Returns an unsubscribe function. Signature
(state: IIIConnectionState) => void
required
Callback invoked with the new connection state whenever it changes.

currentInvocation

The invocation the calling code runs in (remote or local handler), or undefined outside any handler. Browsers have no AsyncLocalStorage: the SDK knows the invocation while the handler runs synchronously, up to its first await; after it this returns undefined. Read it before awaiting, and re-enter it with ISdk.withInvocation for calls made after. Code after an await, outside ISdk.withInvocation, runs outside any invocation, but its calls are not treated as new chains: they carry the observe_depth of the deepest invocation running on this page, so the engine’s loop guard (max_observe_depth) still stops an observer cycle whose target awaits before calling back. With several invocations running this over-counts, and a legitimate chain may stop early. They carry a caller and traceparent only when that is unambiguous (one invocation is running, and it is an observe activation); otherwise none. They never get an invocation’s metadata: obs.emit / obs.call filters on metadata.* see it only inside a real scope. An invocation that never settles stops counting as running after 10 minutes (a local call: at its timeout). Local calls nest the same way: a self-recursion that awaits before each call goes through the engine past 64 levels, while calls started together count as one level. A limitation: local calls started in separate ticks while earlier ones still run also look nested, so a long, wide fan-out may send some through the engine (same results). While the socket is closed none is: a function this worker hosts then runs here up to 256 local calls deep, and past that the call fails at once with LOCAL_DEPTH_EXCEEDED (a runaway recursion must not freeze the page). Signature

Example


getFatalError

The fatal registration rejection that terminated this connection, if any (e.g. a WORKER_NAMESPACE_CONFLICT); undefined while healthy. Mirrors the Node/Python/Rust SDKs. Signature

observe

Observes a function: every event of source that passes its filters invokes target, a registered function. Returns synchronously (also before the connection is up); the observer is replayed with the same id on reconnect. Errors show up as state error and reject ready(); against an engine without observe that is UNSUPPORTED. Signature
ObserveSource
required
What is observed: function_id, args (owner-delivered functions only), filters, on, capture, deliver.
Target
required
The function to invoke.
ObserverOptions
id, max_fires, expires_in_ms, max_in_flight, metadata.

shutdown

Gracefully shutdown the iii, cleaning up all resources. Signature

Example


withInvocation

Runs fn inside invocation (what ISdk.currentInvocation returned), and returns what fn returns. Calls fn makes before its own first await (trigger, obs.emit, obs.call, currentInvocation) belong to that invocation: they carry its caller, observe_depth and traceparent. When fn returns a promise, the invocation counts as running until it settles, so fn’s code after an await gets the fallback below. undefined runs fn outside any invocation. Code after an await, outside withInvocation, runs outside any invocation, but its calls are not treated as new chains: they carry the observe_depth of the deepest invocation running on this page, so the engine’s loop guard (max_observe_depth) still stops an observer cycle whose target awaits before calling back. With several invocations running this over-counts, and a legitimate chain may stop early. They carry a caller and traceparent only when that is unambiguous (one invocation is running, and it is an observe activation); otherwise none. They never get an invocation’s metadata: obs.emit / obs.call filters on metadata.* see it only inside a real scope. An invocation that never settles stops counting as running after 10 minutes (a local call: at its timeout). Local calls nest the same way: a self-recursion that awaits before each call goes through the engine past 64 levels, while calls started together count as one level. A limitation: local calls started in separate ticks while earlier ones still run also look nested, so a long, wide fan-out may send some through the engine (same results). While the socket is closed none is: a function this worker hosts then runs here up to 256 local calls deep, and past that the call fails at once with LOCAL_DEPTH_EXCEEDED (a runaway recursion must not freeze the page). Signature

Parameters

InvocationContext | undefined
() => T
required

Subpath Exports

The iii-browser-sdk package provides additional entry points:

Types

iii-browser-sdk

ApiRequest · ApiResponse · AuthInput · AuthResult · Caller · CallerInfo · Capture · Channel · ChannelReader · ChannelWriter · EngineFunctions · EngineTriggers · EnqueueResult · Filter · FunctionRef · IIIConnectionState · IIIReconnectionConfig · InitOptions · InvocationContext · InvocationError · InvocationErrorInit · MessageType · MiddlewareFunctionInput · Observed · ObserveDescriptorWire · ObserveDoc · ObserveHooks · Observer · ObserveReason · ObserveRejection · ObserverHandle · ObserverOptions · ObserverState · ObserveSource · OnFunctionRegistrationInput · OnFunctionRegistrationResult · OnTriggerRegistrationInput · OnTriggerRegistrationResult · OnTriggerTypeRegistrationInput · OnTriggerTypeRegistrationResult · OpenEnum · RegisterFunctionFormat · RegisterFunctionInput · RegisterFunctionMessage · RegisterFunctionOptions · RegistrationRejectedError · RegistrationRejectedInit · RemoteFunctionHandler · StreamChannelRef · Target · TriggerAction · TriggerRequest

ApiRequest

Incoming HTTP request received by a function registered with an HTTP trigger.

ApiResponse

Structured API response returned from HTTP function handlers.

AuthInput

Input passed to the RBAC auth function during WebSocket upgrade. Contains the HTTP headers, query parameters, and client IP from the connecting worker’s upgrade request.

AuthResult

Return value from the RBAC auth function. Controls which functions the authenticated worker can invoke and what context is forwarded to the middleware.

Caller

Who started an invocation: the worker (worker_id / worker_name, stamped by the engine), and the function and invocation the call was made from.

CallerInfo

A caller as the SDK knows it: every field may be missing (a top-level call has no function; a call made before WorkerRegistered has no worker id).

Capture

What an observer ships to its target. Default ['input', 'output', 'caller'].

Channel

A streaming channel pair for worker-to-worker data transfer. Created via the createChannel helper from iii-browser-sdk/helpers.

ChannelReader

Read end of a streaming channel. Uses native browser WebSocket.

ChannelWriter

Write end of a streaming channel. Uses native browser WebSocket.

EngineFunctions

Engine function paths for internal operations. Naming note: LIST_TRIGGERS / INFO_TRIGGERS cover trigger TYPES (templates). LIST_REGISTERED_TRIGGERS / INFO_REGISTERED_TRIGGERS cover trigger INSTANCES (subscriber rows). The old engine::trigger-types::list builtin has been removed and is now served by engine::triggers::list.

EngineTriggers

Engine trigger types

EnqueueResult

Result returned when a function is invoked with TriggerAction.Enqueue.

Filter

A declarative filter over input, output, error, caller and metadata, with explicit operators only: { 'input.amount': { $gte: 500 } }. See the filter language reference.

FunctionRef

Handle returned by ISdk.registerFunction. Contains the function’s id and an unregister() method.

IIIConnectionState

Connection state for the III WebSocket

IIIReconnectionConfig

Configuration for WebSocket reconnection behavior

InitOptions

Configuration options passed to registerWorker.

InvocationContext

The invocation the current code runs in, in every handler, remote or local (iii.currentInvocation()). Browsers have no AsyncLocalStorage, so the SDK knows it only while the handler runs synchronously: up to its first await. To keep it across an await, read it first and re-enter it with iii.withInvocation(inv, fn).

InvocationError

An error the SDK raises itself for an invocation, with a machine-readable code: observe delivery errors (NOT_OWNER_DELIVERED, OBSERVER_NOT_ACTIVE, FILTERS_NOT_MATCHED) and an invalid observe descriptor (INVALID_OBSERVE_DESCRIPTOR). Mirrors the Node SDK. A call the engine answers with an error still rejects with the engine’s error body ({ code, message, stacktrace? }), as in earlier releases, and so does a locally dispatched call whose handler throws: both paths reject with the same value.

InvocationErrorInit

Fields used to construct an InvocationError.

MessageType


MiddlewareFunctionInput

Input passed to the RBAC middleware function on every function invocation through the RBAC port. The middleware can inspect, modify, or reject the call before it reaches the target function.

Observed

What the target of an auto observer (or of obs.emit) receives with deliver: 'envelope' (the default). Fields not in the observer’s capture are absent.

ObserveDescriptorWire

RegisterFunction.observe: the part of the observe hooks that travels. Callbacks never do.

ObserveDoc

The document an observer’s filters read (filters.md §1).

ObserveHooks

The observe option of registerFunction: how the function’s observers are delivered, and the callbacks that run when one is added or removed. The callbacks of one function run one at a time, in revision order, with one exception: a callback still running after 30 s is treated as failed (OWNER_TIMEOUT) and the next one starts, so a hung callback cannot stall its function forever. It may then overlap with the callbacks after it, and if a timed-out onObserverAdded completes later, onObserverRemoved runs for that observer.

Observer

An observer as the function’s owner sees it (onObserverAdded, FunctionRef.observers()): its args, filters, target, capture and on. Never its metadata, policy or the observing worker.

ObserveReason

A state reason or an error: a machine-readable code and a message.

ObserveRejection

Thrown by an onObserverAdded hook to reject an observer with a code of its own (HTTP_ROUTE_CONFLICT, INVALID_CRON_EXPRESSION, …); any other error rejects it with OBSERVE_REJECTED. Also the error ObserverHandle.ready() rejects with when the observer turns error or disposed.

ObserverHandle

What iii.observe returns, synchronously.

ObserverOptions

The observer itself: its id, policy and metadata.

ObserverState

An observer’s lifecycle: pending (no owner yet, waiting for the owner’s ack, or no target yet) → active or error; suspended while its worker or target is away; disposed at the end.

ObserveSource

The left side of iii.observe: what is observed.

OnFunctionRegistrationInput

Input passed to the on_function_registration_function_id hook when a worker attempts to register a function through the RBAC port. Return an OnFunctionRegistrationResult with the (possibly mapped) fields, or throw to deny the registration.

OnFunctionRegistrationResult

Result returned from the on_function_registration_function_id hook. All fields are optional; omitted fields keep the original value from the registration request.

OnTriggerRegistrationInput

Input passed to the on_trigger_registration_function_id hook when a worker attempts to register a trigger through the RBAC port. Return an OnTriggerRegistrationResult with the (possibly mapped) fields, or throw to deny the registration.

OnTriggerRegistrationResult

Result returned from the on_trigger_registration_function_id hook. All fields are optional; omitted fields keep the original value from the registration request.

OnTriggerTypeRegistrationInput

Input passed to the on_trigger_type_registration_function_id hook when a worker attempts to register a new trigger type through the RBAC port. Return an OnTriggerTypeRegistrationResult with the (possibly mapped) fields, or throw to deny the registration.

OnTriggerTypeRegistrationResult

Result returned from the on_trigger_type_registration_function_id hook. All fields are optional; omitted fields keep the original value from the registration request.

OpenEnum

A wire enum that a newer peer may extend: decoders keep a value they do not know instead of failing the frame.

RegisterFunctionFormat


RegisterFunctionInput


RegisterFunctionMessage


RegisterFunctionOptions

Options of ISdk.registerFunction: description, request/response formats, metadata, and the observe hooks.

RegistrationRejectedError

A terminal registration rejection from the engine. Thrown into every pending invocation and exposed via getFatalError() when a worker-name collision (or other non-retryable rejection) closes the connection for good.

RegistrationRejectedInit


RemoteFunctionHandler

Async function handler for a registered function. Receives the invocation payload and its metadata (TriggerRequest.metadata of the call, or an observer’s metadata sidecar on an activation) and returns the result.

StreamChannelRef

Serializable reference to one end of a streaming channel. Can be included in invocation payloads to pass channel endpoints between workers.

Target

The right side of iii.observe: a registered function.

TriggerAction

Factory object that constructs routing actions for ISdk.trigger.

TriggerRequest

Request object passed to ISdk.trigger.

iii-browser-sdk/state

DeleteResult · IState · StateDeleteInput · StateDeleteResult · StateEventData · StateEventType · StateGetInput · StateListInput · StateSetInput · StateSetResult · StateUpdateInput · StateUpdateResult

DeleteResult

Result of a state delete operation.

IState

Interface for state management operations. Available via the iii-browser-sdk/state subpath export.

StateDeleteInput

Input for deleting a state value.

StateDeleteResult

Result of a state delete operation.

StateEventData

Payload for state change events.

StateEventType

Types of state change events.

StateGetInput

Input for retrieving a state value.

StateListInput

Input for listing all values in a state scope.

StateSetInput

Input for setting a state value.

StateSetResult

Result of a state set operation.

StateUpdateInput

Input for atomically updating a state value.

StateUpdateResult

Result of a state update operation.

iii-browser-sdk/stream

IStream · MergePath · StreamAuthInput · StreamAuthResult · StreamChangeEvent · StreamContext · StreamDeleteInput · StreamGetInput · StreamJoinLeaveEvent · StreamJoinLeaveTriggerConfig · StreamJoinResult · StreamListGroupsInput · StreamListInput · StreamSetInput · StreamSetResult · StreamTriggerConfig · StreamUpdateInput · StreamUpdateResult · UpdateAppend · UpdateDecrement · UpdateIncrement · UpdateMerge · UpdateOp · UpdateOpError · UpdateRemove · UpdateSet

IStream

Interface for custom stream implementations. Passed to ISdk.createStream to override the engine’s built-in stream storage.

MergePath

Path target for a UpdateMerge op. Accepts:
  • a single string (legacy / first-level field)
  • an array of literal segments (nested path; each element is one literal key, dots are NOT interpreted as separators)
Omit path, pass "", or pass [] to target the root value.

StreamAuthInput

Input for stream authentication.

StreamAuthResult

Result of stream authentication.

StreamChangeEvent

Handler input for stream triggers, fired when an item changes via stream::set, stream::update, or stream::delete.

StreamContext

Context type extracted from StreamAuthResult.

StreamDeleteInput

Input for deleting a stream item.

StreamGetInput

Input for retrieving a single stream item.

StreamJoinLeaveEvent

Event payload for stream join/leave events.

StreamJoinLeaveTriggerConfig

Trigger config for stream:join and stream:leave triggers.

StreamJoinResult

Result of a stream join request.

StreamListGroupsInput

Input for listing all groups in a stream.

StreamListInput

Input for listing all items in a stream group.

StreamSetInput

Input for setting a stream item.

StreamSetResult

Result of a stream set operation.

StreamTriggerConfig

Trigger config for stream triggers. Filters which item changes fire the handler.

StreamUpdateInput

Input for atomically updating a stream item.

StreamUpdateResult

Result of a stream update operation.

UpdateAppend

Append an element to an array, concatenate a string, or push a new value at a nested path. The target is the root (when path is omitted, empty, or []), a single first-level key (when path is a non-empty string), or an arbitrary nested location (when path is an array of literal segments). See MergePath. Engine semantics: missing/null intermediates along a nested path are auto-created; missing leaves on a nested path always become arrays (no string-concat tier); existing object/scalar leaves return append.type_mismatch. Each path segment is a literal key, ["a.b"] targets a single key named "a.b", not a → b.

UpdateDecrement

Decrement a numeric field by a given amount.

UpdateIncrement

Increment a numeric field by a given amount.

UpdateMerge

Shallow-merge an object into the target. The target is the root (when path is omitted/empty) or an arbitrary nested location specified by an array of literal segments. See MergePath. Validation: invalid paths/values (depth > 32, segment > 256 bytes, value depth > 16, > 1024 top-level keys, or any __proto__/constructor/prototype segment or top-level key) are rejected with a structured error in the response’s errors array.

UpdateOp

Union of all atomic update operations supported by streams.

UpdateOpError

Per-op error returned by state::update / stream::update.

UpdateRemove

Remove a field at the given path.

UpdateSet

Set a field at the given path to a value.