wunderactor
v0.0.12
Published
Actor definitions, contracts, servers, and live HTTP clients.
Readme
defineActor()
Start a named actor definition. Each builder call returns a new definition, so you can extend the same base with different handlers.
Remarks
A SchemaSource can be a Zod schema or a synchronous function that builds
one from the preceding definition. Its context exposes id, state,
stateSchema, schema, error, runtime, event, command, query,
task, and actor. Handler contexts expose state after a state schema
has been declared, and errors contains the available error factories.
Call signature
defineActor(name); // string literal Name → ActorDefinition<Name>Example
const Counter = defineActor("Counter").state(z.object({ count: z.number() }));
const counter = Counter.create({ count: 0 });Definition
.state()
Define the schema for an instance's state. Later handlers infer their state type from this schema.
Call signature
.state(stateSchema)Example
const Counter = defineActor("Counter").state(z.object({ count: z.number() }));
const counter = Counter.create({ count: 0 });Call signature
.state(({ schema, actor }) => stateSchema)Example
const Counter = defineActor("Counter")
.schema({ Count: z.number().int() })
.state(({ schema }) => z.object({ count: schema.Count }));Extend object state with new fields. Existing handlers are preserved, and each field name can be declared only once.
Call signature
.state(additionalFieldsSchema) // Zod object with new field namesExample
const Counter = defineActor("Counter").state(z.object({ count: z.number() }));
const NamedCounter = Counter.state(z.object({ label: z.string() }));
const counter = NamedCounter.create({ count: 0, label: "Clicks" });Call signature
.state<AdditionalFieldsSchema>(({ state }) => additionalFieldsSchema)Example
type UpperBound = z.ZodObject<{ upper: z.ZodNumber }>;
const Range = defineActor("Range")
.state(z.object({ lower: z.number() }))
.state<UpperBound>(({ state }) => z.object({ upper: state.lower }));
Range.create({ lower: 0, upper: 10 });.event()
Register event reducers that share a payload schema. Each reducer receives the parsed input, mutates state synchronously, and returns nothing.
Call signature
.event({
schema: inputSchema, // SchemaSource
description, // optional
[eventName]({ input, state, schema, errors }) {
// Update state synchronously.
},
})Example
const Counter = defineActor("Counter")
.state(z.object({ count: z.number() }))
.event({
schema: z.number(),
added({ state, input }) {
state.count += input;
},
});.command()
Register synchronous commands that share an input schema. Handlers read the current snapshot and return events or actor operations to apply. Errors declared in the batch are available only to its handlers.
Call signature
.command({
schema: inputSchema, // SchemaSource
description, // optional
errors, // optional map of codes to { message: string, retriable: boolean }
[commandName]({
input, state, self, caller, event, query, actor, runtime, schema, errors,
}) {
return operations; // readonly (ActorEvent | ActorOperation)[]
},
})Example
const Inbox = defineActor("Inbox")
.event({ schema: z.string(), received() {} })
.command({
schema: z.string(),
send: ({ input, event }) => [event.received(input)],
});
Inbox.create().send("Hello");.query()
Register synchronous, read-only queries with validated inputs and outputs. Pass a dependency before the batch to use its schemas in the input and output factories.
Call signature
.query({
input: inputSchema,
output: outputSchema,
[queryName]: ({ input, state, self, query, schema, errors }) => value,
})Example
const Counter = defineActor("Counter")
.state(z.object({ count: z.number() }))
.query({
input: z.number(),
output: z.boolean(),
atLeast: ({ state, input }) => state.count >= input,
});
Counter.create({ count: 5 }).atLeast(3); // trueCall signature
.query(dependency, {
input: inputSchema, // SchemaSource; factories can access actor[dependency.name]
output: outputSchema, // same extended schema context
[queryName]: ({ input, state, self, query, schema, errors }) => value,
})Example
const Player = defineActor("Player");
const Roster = defineActor("Roster").query(Player, {
input: ({ actor }) => actor.Player.id,
output: z.string(),
displayId: ({ input }) => input,
});.init()
Validate creation input with schema, then synchronously map the parsed
value to initial state. Declare the state schema first.
Call signature
.init({ schema: inputSchema, state: ({ input }) => initialState })Example
const Counter = defineActor("Counter")
.state(z.object({ count: z.number() }))
.init({ schema: z.number(), state: ({ input }) => ({ count: input }) });
Counter.create(5).toJSON().state.count; // 5.singleton()
Give each family one instance at singletonId. The family uses the supplied
creation input when it first provisions the instance. The options argument
can be omitted when the creation schema accepts undefined or {}.
With an explicit options object, input is optional only when the
creation schema accepts undefined. The family creates singleton instances.
Call signature
.singleton()Example
const Clock = defineActor("Clock").singleton();
const family = defineActorFamily({ Clock }).create();
const clock = family.actor.Clock.get(Clock.singletonId);Call signature
.singleton({ input })Example
const Settings = defineActor("Settings")
.state(z.object({ currency: z.string() }))
.singleton({ input: { currency: "SGD" } });
const family = defineActorFamily({ Settings }).create();
const settings = family.actor.Settings.get(Settings.singletonId);.actor()
Declare another actor as a dependency. Later schema factories can use it as a typed reference, and commands and tasks can address it by name.
Call signature
.actor(dependency)Example
const Player = defineActor("Player").state(z.object({ name: z.string() }));
const Team = defineActor("Team")
.actor(Player)
.state(({ actor }) => z.object({ captain: actor.Player }));.lifecycle()
Emit domain events on live creation or completion. The created hook
receives creation input and the done hook receives the completion result.
Snapshot restoration and event replay skip these hooks.
Call signature
.lifecycle({
created: ({ input, self, state, event, schema, errors }) => events,
done: ({ result, self, state, event, schema, errors }) => events,
}) // supply either or both hooksExample
const Session = defineActor("Session")
.event({ schema: z.void(), opened() {} })
.lifecycle({ created: ({ event }) => [event.opened()] });.listen()
React to a live event by returning events, commands, or tasks. Use an
event name for this instance, a state selector for related actors, or a
source definition with target and apply to route by recipient ID.
Call signature
// An event on this instance
.listen(eventName, ({
input, state, self, source, event, command, task, query, runtime, schema, errors,
}) => operations) // local events, commands, or tasksExample
const Queue = defineActor("Queue")
.event({ schema: z.string(), queued() {}, workRequested() {} })
.listen("queued", ({ event, input }) => [event.workRequested(input)]);Call signature
// Events on actors selected from state
.listen(({ state }) => selection, { // one actor reference, an array, null, or undefined
[eventName]: ({
input, state, self, source, event, command, task, query, runtime, schema, errors,
}) => operations, // also accepts commands addressed to declared dependencies
})Example
const Child = defineActor("Child").event({ schema: z.string(), changed() {} });
const Parent = defineActor("Parent")
.actor(Child)
.state(({ actor }) => z.object({ child: actor.Child }))
.event({ schema: z.string(), observed() {} })
.listen(({ state }) => state.child, {
changed: ({ event, input }) => [event.observed(input)],
});Call signature
// Events routed to a recipient ID
.listen(sourceActor, {
[eventName]: {
target: ({ source, input }) => recipientId, // return null to skip delivery
apply: ({
input, state, self, source, event, command, task, query, runtime, schema, errors,
}) => operations, // local events, commands, or tasks
},
})Example
const Inbox = defineActor("Inbox").event({ schema: z.void(), received() {} });
const Mail = defineActor("Mail").event({ schema: Inbox.id, delivered() {} });
const RoutedInbox = Inbox.listen(Mail, {
delivered: {
target: ({ input }) => input,
apply: ({ event }) => [event.received()],
},
});.task()
Register async tasks with a shared input schema and success schema.
Optional success and failure hooks synchronously return local events.
Concurrency accepts "reject", "replace", "parallel", or an object
with key(input) returning a string and policy set to "reject" or "replace".
Call signature
.task({
input: inputSchema, // SchemaSource
success: {
schema: successSchema,
// Optional hook returning local events.
apply: ({ result, input, state, self, schema, errors, event, query, runtime }) => events,
},
failure: { // optional
schema: failureSchema,
apply: ({ error, input, state, self, schema, errors, event, query, runtime }) => events,
},
description, // optional
concurrency, // optional
async [taskName]({
input, state, self, schema, errors, query, command, task, actor, runtime, signal, startedAt,
}) {
return result; // validated by success.schema
},
})Example
const Clock = defineActor("Clock")
.event({ schema: z.number(), sampled() {} })
.task({
input: z.void(),
success: {
schema: z.number(),
apply: ({ event, result }) => [event.sampled(result)],
},
async sample() {
return Date.now();
},
});
const timestamp = await Clock.create().sample();.declareTask()
Declare a task's contract so callers can use its types before an
implementation exists. Use success and failure for outcome hooks, or
result for just the success schema. Supply the body with implementTask.
Call signature
.declareTask(taskName, { input: inputSchema, result: resultSchema })Example
const Search = defineActor("Search").declareTask("suggest", {
input: z.string(),
result: z.array(z.string()),
});Call signature
.declareTask(taskName, {
input: inputSchema,
success: { schema: successSchema, apply: onSuccess }, // optional apply
failure: { schema: failureSchema, apply: onFailure }, // optional failure and apply
description, concurrency, // optional, as in .task()
})Example
const Jobs = defineActor("Jobs")
.event({ schema: z.string(), recorded() {} })
.declareTask("format", {
input: z.string(),
success: {
schema: z.string(),
apply: ({ event, result }) => [event.recorded(result)],
},
failure: {
schema: z.object({ message: z.string() }),
apply: ({ event, error }) => [event.recorded(error.message)],
},
});.implementTask()
Supply the async handler for a previously declared task. The returned
definition can execute it with the declared input and result schemas.
The body and outcome hooks receive the same contexts as in .task().
Either form accepts an optional third argument with an optional concurrency policy.
Call signature
.implementTask(taskName, async (context) => result)Example
const Search = defineActor("Search")
.declareTask("suggest", { input: z.string(), result: z.array(z.string()) })
.implementTask("suggest", async ({ input }) =>
["apple", "pear"].filter((fruit) => fruit.startsWith(input)),
);
await Search.create().suggest("ap"); // ["apple"]Call signature
.implementTask(taskName, {
async [taskName](context) { return result; },
success: { apply: onSuccess }, // optional
failure: { apply: onFailure }, // requires a declared failure schema
}, { concurrency })Example
const Jobs = defineActor("Jobs")
.event({ schema: z.string(), recorded() {} })
.declareTask("format", { input: z.string(), result: z.string() })
.implementTask(
"format",
{
async format({ input }) {
return input.trim();
},
success: { apply: ({ event, result }) => [event.recorded(result)] },
},
{ concurrency: "parallel" },
);
await Jobs.create().format(" hello "); // "hello".done()
Complete the actor when a synchronous predicate returns true. Pass
{ condition, result } to also save a result and resolve $done with it.
Call signature
.done(({ state, query }) => condition) // boolean predicate; $done resolves to voidExample
const Countdown = defineActor("Countdown")
.state(z.object({ remaining: z.number() }))
.done(({ state }) => state.remaining === 0);
await Countdown.create({ remaining: 0 }).$done; // voidCall signature
.done({
condition: ({ state, query }) => condition, // boolean
result: ({ state, query }) => value, // optional synchronous result for $done
})Example
const Game = defineActor("Game").state(z.object({ score: z.number() }));
const FinalScore = Game.done({
condition: ({ state }) => state.score >= 10,
result: ({ state }) => state.score,
});
await FinalScore.create({ score: 12 }).$done; // 12.error()
Define reusable errors by code, message, and retry policy. Call the matching factory in a handler to construct the error to throw.
Call signature
.error({ [code]: { message, retriable } }) // string message and boolean retriableExample
const Room = defineActor("Room")
.error({ Locked: { message: "Room is locked", retriable: false } })
.state(z.object({ locked: z.boolean() }))
.event({ schema: z.void(), entered() {} })
.command({
schema: z.void(),
enter({ state, errors, event }) {
if (state.locked) throw errors.Locked();
return [event.entered()];
},
});.schema()
Register named Zod schemas for reuse in later schema factories and
handlers. The definition also exposes them at schemas.named.
Call signature
.schema({ [schemaName]: schemaSource })Example
const Counter = defineActor("Counter")
.schema({ Count: z.number().int().nonnegative() })
.state(({ schema }) => z.object({ count: schema.Count }));Call signature
.schema({ [schemaName]: ({ schema }) => derivedSchema })Example
const Route = defineActor("Route")
.schema({ Meters: z.number().nonnegative() })
.schema({ Segments: ({ schema }) => z.array(schema.Meters) });.runtime()
Declare schemas for values injected through the instance's runtime
option. Commands, tasks, and listeners can read them via runtime.
Call signature
.runtime({ [fieldName]: runtimeSchema }) // SchemaSourceExample
const Clock = defineActor("Clock")
.runtime({ now: z.function().output(z.number()) })
.task({
input: z.void(),
success: { schema: z.number() },
async time({ runtime }) {
return runtime.now();
},
});
const clock = Clock.create(undefined, { runtime: { now: () => 42 } });
await clock.time(); // 42Call signature
.runtime({ [fieldName]: ({ schema }) => runtimeSchema })Example
const Service = defineActor("Service")
.schema({ Region: z.enum(["east", "west"]) })
.runtime({ region: ({ schema }) => schema.Region });
Service.create(undefined, { runtime: { region: "west" } });Extend
.with()
Merge another definition's state, handlers, and configuration into this one. The result keeps the receiving actor's name and rejects conflicts.
Call signature
.with(otherDefinition)Example
const Named = defineActor("Named").state(z.object({ name: z.string() }));
const Player = defineActor("Player").with(Named);
const player = Player.create({ name: "Alice" });Migration
.migration()
Append a synchronous migration that runs on every snapshot load. Each step receives the previous step's output. The final state schema validates the result.
Call signature
.migration(({ state }) => migratedState)Example
const Counter = defineActor("Counter")
.state(z.object({ count: z.number() }))
.migration(({ state }) => {
const saved = z.record(z.string(), z.unknown()).parse(state);
return { ...saved, count: z.number().parse(saved.count ?? saved.total) };
});Runtime
.client()
Open a client replica from a source's initial snapshot and keep it in sync with subsequent updates. Queries read from the replica.
Call signature
.client({
source, // required ActorSource
command, task, // optional remote executors
list, // optional task discovery callback
runtime, resolver, signal, onError, // optional local values, resolver, abort and error handling
shared, actorDefinitions, // optional shared definition and related definitions
}) // Promise<ActorClient>Example
const Counter = defineActor("Counter").state(z.object({ count: z.number() }));
const host = Counter.create({ count: 2 });
const client = await Counter.client({ source: host.$source });
client.toJSON().state.count; // 2
client.$close();.create()
StatefulActorDefinition
Create a standalone actor with a fresh ID. Creation validates the input,
runs any initializer, and applies the state schema's defaults.
Omit input when its schema accepts undefined and runtime values are
optional. With required runtime fields, supply both arguments, passing
undefined for input if its schema allows it. The family creates singletons.
Call signature
.create(input)Example
const Counter = defineActor("Counter").state(
z.object({ count: z.number().default(0) }),
);
const counter = Counter.create({});
counter.toJSON().state.count; // 0Call signature
.create()Example
const Counter = defineActor("Counter")
.state(z.object({ count: z.number() }))
.init({ schema: z.void(), state: () => ({ count: 0 }) });
const counter = Counter.create();Call signature
.create(input, { runtime, onLifecycle }) // onLifecycle is optionalExample
const Counter = defineActor("Counter")
.state(z.object({ count: z.number() }))
.runtime({ region: z.string() });
const counter = Counter.create({ count: 1 }, { runtime: { region: "west" } });ActorDefinition
Create a standalone stateless actor with a fresh ID. To supply runtime
options, pass undefined as the creation input. Required runtime fields
make the options argument and its runtime property mandatory.
Use the family to create a singleton.
Call signature
.create()Example
const Ping = defineActor("Ping");
const ping = Ping.create();Call signature
.create(undefined, { runtime, onLifecycle }) // onLifecycle is optionalExample
const Service = defineActor("Service").runtime({ region: z.string() });
const service = Service.create(undefined, { runtime: { region: "west" } });.fromJSON()
StatefulActorDefinition
Restore an instance from a snapshot, preserving its ID and revision.
Restoration runs registered state migrations and resumes pending tasks.
The snapshot requires id, revision, and state and accepts status: "done",
completion, and serialized tasks. Supply options when runtime fields are required.
Call signature
.fromJSON(snapshot)Example
const Counter = defineActor("Counter").state(z.object({ count: z.number() }));
const saved = Counter.create({ count: 3 }).toJSON();
const restored = Counter.fromJSON(saved);
restored.toJSON().state.count; // 3Call signature
.fromJSON(snapshot, { runtime, onLifecycle }) // onLifecycle is optionalExample
const Counter = defineActor("Counter")
.state(z.object({ count: z.number() }))
.runtime({ region: z.string() });
const options = { runtime: { region: "west" } };
const saved = Counter.create({ count: 3 }, options).toJSON();
const restored = Counter.fromJSON(saved, options);ActorDefinition
Restore a stateless actor with tasks from its snapshot. Restoration
preserves the actor's identity and revision and resumes pending tasks.
The snapshot requires id and revision and accepts status: "done",
completion, and serialized tasks. Supply options when runtime fields are required.
Call signature
.fromJSON(snapshot)Example
const Worker = defineActor("Worker").task({
input: z.string(),
success: { schema: z.string() },
async format({ input }) {
return input.trim();
},
});
const saved = Worker.create().toJSON();
const restored = Worker.fromJSON(saved);Call signature
.fromJSON(snapshot, { runtime, onLifecycle }) // onLifecycle is optionalExample
const Worker = defineActor("Worker")
.runtime({ queue: z.string() })
.task({
input: z.void(),
success: { schema: z.string() },
async queueName({ runtime }) {
return runtime.queue;
},
});
const options = { runtime: { queue: "mail" } };
const saved = Worker.create(undefined, options).toJSON();
const restored = Worker.fromJSON(saved, options);