NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
npm
npm, #4208 most downloaded on npm
Finite State Machines and Statecharts for the Modern Web.
Latest stable
5.33.4
Last release 15 days ago
07 Nov 2026
Ships on a steady schedule
a new release about every 1 weeks
Nearly every release is documented
notes for 60 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
9 years old
352 releases · first in 2017
Drag across the ruler to compare, or tap a release to open it.
599ec3c: Unknown transition targets are now type errors in setup().createMachine(...), not only in createMachine(...). Targets returned from transitio
599ec3c: Unknown transition targets are now type errors in setup().createMachine(...), not only in createMachine(...). Targets returned from transition functions are also checked:
setup({}).createMachine({
initial: 'a',
states: {
a: {
on: {
// Type error: 'bb' is not a state
GO: () => ({ target: 'bb' })
}
},
b: {}
}
});
Dynamic (non-literal) string targets are still accepted.
6cf6982: XState v6 enters beta. No further breaking changes are planned for APIs tagged @public; any that are needed will be called out with a migrati…
81dd3dd: Restoring a persisted snapshot moved out of createActor into restoreActor, exported from the new xstate/persist entry point. createActor only starts fresh actors; passing snapshot throws with the replacement.
// Before
const actor = createActor(machine, { snapshot: persisted });
// After
import { restoreActor } from 'xstate/persist';
const actor = restoreActor(machine, persisted);
restoreActor(logic, snapshot, options?) works for any actor logic and accepts the createActor options except input. Pass system to restore into a system from createSystem():
const actor = restoreActor(machine, persisted, { system });
Machine snapshots are validated and migrated, and invoked and spawned children are restored. A snapshot that cannot be restored produces an actor with an 'error' snapshot. machine.restoreSnapshot() is removed.
machine.snapshotSchema and machine.eventSchema are now functions:
// Before
await machine.snapshotSchema['~standard'].validate(value);
await machine.eventSchema['~standard'].validate(input);
// After
import { eventSchema } from 'xstate';
import { snapshotSchema } from 'xstate/persist';
await snapshotSchema(machine)['~standard'].validate(value);
await eventSchema(machine)['~standard'].validate(input);
machineVersions([...]) accepts machines and { id, version, snapshotSchema, eventSchema } descriptors as before.
047cfb5: Leftover v5 configuration now throws in every build instead of only in development, so it cannot be silently ignored:
createMachine(config, implementations) and setup(...).createMachine(config, implementations) throw. Declare implementations in setup({ ... }) or pass them to machine.provide({ ... }).services, activities and devTools in a machine config throw. They previously only warned in development.createActor(...) throws on an option it does not read. Removed options (systemId, state, devTools, parent, deferEvents, execute) throw with their replacement; any other unknown option throws with the list of supported options.createActor(machine, { systemId: 'payments' });
// Error: The "systemId" actor option was renamed. Use "registryKey": createActor(logic, { registryKey }), and look the actor up with system.get(registryKey).
predictableActionArguments, preserveActionOrder and strict change nothing in v6 and still only warn in development.
965c250: Macrosteps are unbounded by default, as in v5. options.maxIterations no longer defaults to 1000, so a machine whose eventless transitions or raised events take more than 1000 microsteps for one event keeps running instead of erroring. In development builds, a macrostep that passes 1000 microsteps logs a warning once per machine. Set maxIterations to turn a runaway macrostep into an InfiniteTransitionError:
const machine = createMachine({
options: { maxIterations: 5000 },
// ...
});
6cf6982: XState v6 enters beta. No further breaking changes are planned for APIs tagged @public; any that are needed will be called out with a migration path. APIs tagged @experimental may still change.
308c52d: self in actions, transition functions, context factories, input mappers and delay functions is typed as a machine actor ref instead of any in its children and meta positions. Delay and after functions now receive the machine's emitted event type.
a2e4161: Production builds report errors and diagnostics as short codes. Each message names the code, the values that identify the failing state, event, or actor, and a link to its entry in the error code reference:
XState error E1 ("services"). See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e1
Development messages are unchanged. Error classes and names are the same in both builds.
59fc7cd: createMachine throws when an on key is a v5 suffixed lifecycle event type such as 'xstate.done.actor.job', 'xstate.error.actor.job', 'xstate.done.state.form' or 'xstate.after.1000.loading'. v6 never sends these types, so the transition never fired. The error names the replacement:
// Throws: Transition "xstate.done.actor.job" in state "loading" never fires ...
on: { 'xstate.done.actor.job': { target: 'done' } }
// Use the category type and select the child with `matches`
on: { 'xstate.done.actor': { matches: { actorId: 'job' }, target: 'done' } }
Wildcards such as 'xstate.done.actor.*' and the 'xstate.snapshot.actor' type are unaffected.
Your coding agent can read these notes before it upgrades. Set up the MCP server →
81dd3dd: useActorRef, useActor and useMachine accept an already-created actor, such as one from restoreActor. The snapshot option is removed; restore the actor with restoreActor from xstate/persist and pass it to the hook. The hook starts the actor on mount and stops it on unmount, as it does for actors it creates. Create the actor once per component instance.
import { useActor } from '@xstate/vue';
import { restoreActor } from 'xstate/persist';
// in setup()
const { snapshot, send } = useActor(restoreActor(machine, persisted));
@public; any that are needed will be called out with a migration path. APIs tagged @experimental may still change.81dd3dd: useActorRef, useActor and useMachine accept an already-created actor, such as one from restoreActor. The snapshot option is removed; restore the actor with restoreActor from xstate/persist and pass it to the hook. The hook starts the actor and stops it when the component is destroyed, as it does for actors it creates. Create the actor once per component instance.
<script lang="ts">
import { useActor } from '@xstate/svelte';
import { restoreActor } from 'xstate/persist';
const { snapshot, send } = useActor(restoreActor(machine, persisted));
</script>
@public; any that are needed will be called out with a migration path. APIs tagged @experimental may still change.6ef5f1f: Async logic that resolves null now reports null as its output instead of undefined. Rejecting with null likewise reports null as the error.
6ef5f1f: Async logic that resolves null now reports null as its output instead of undefined. Rejecting with null likewise reports null as the error.
const logic = createAsyncLogic({ run: async () => null });
// snapshot.output === null
// parent receives { type: 'xstate.done.actor', output: null, ... }
129fd6b: Events sent by a child actor to a parent started with createEffectActor now retain their send order, including bursts from promise continuati
129fd6b: Events sent by a child actor to a parent started with createEffectActor now retain their send order, including bursts from promise continuations.
Durable hosts with a single FIFO mailbox can route all root events through their adapter:
const durable = createDurable(machine, adapter, { captureRootEvents: false });
749955a: Observe emitted events from every actor in a system with createSystem({ onEmitted }). The callback receives the source actor and original eve
749955a: Observe emitted events from every actor in a system with createSystem({ onEmitted }). The callback receives the source actor and original event, including emissions from invoked and spawned children.
const system = createSystem({
onEmitted: ({ actorRef, event }) => {
analytics.track(`${actorRef.id}.${event.type}`, event);
}
});
const root = system.createActor(applicationMachine);
root.start();
Use system.onEmitted(listener) for a subscription you can remove with .unsubscribe(). Existing actor.on(...) handlers continue to observe only that actor's emissions.
2cac9ae: Keep model traversal paths distinct when state inputs or remembered history differ, and fix published declarations for consumers using exact optional properties with library checking enabled.
Directed graphs now include static eventless transitions and report function-based destinations that cannot be extracted. The experimental getMachineSerializationDiagnostics(machine) helper identifies values that need runtime bindings or cannot be preserved by machine JSON, including omitted undefined object properties and array entries.
Add JSON CLI commands for version-matched documentation, inspection, definition validation, effect-free simulation, bounded state assertions, counterexample replay, and structural diffs. Run npx xstate docs --json to find the installed agent guide and API stability manifest. The data-only CLI refuses code expressions and does not execute external effects or claim formal proofs.
2672ea8: Preserve the context of previously captured machine snapshots when entry functions return context patches.
29ead0b: Clarify how imported SCXML machines differ from native XState v6 machines, including transition domains, event matching, error handling, and the supported execution profile.
Fix SCXML executable content ordering: all state exits finish before selected transition content runs, and all transition content finishes before state entry. Scripts can mutate declared arrays and plain objects while preserving previous snapshots.
0cd2e26: Reject malformed persisted state values, children, and timers consistently during snapshot parsing and restoration. Invalid snapshots now produce an InvalidSnapshotError instead of an incidental TypeError or plain Error.
Report unhandled public xstate.* events through onUnhandledEvent and development warnings, including obsolete suffixed lifecycle names such as xstate.done.actor.save.
Reject the removed parent option passed to createActor with migration guidance. Create child actors through invoke, spawn, or enq.spawn.
ceeebb0: ActorRefFrom accepts actor logic only, and ActorRefFromLogic is removed. Replace ActorRefFromLogic with ActorRefFrom . Pass the logic type in
ceeebb0: ActorRefFrom<T> accepts actor logic only, and ActorRefFromLogic<T> is removed. Replace ActorRefFromLogic<T> with ActorRefFrom<T>. Pass the logic type instead of a promise, an actor ref, or a function returning logic:
// Before
type Ref = ActorRefFromLogic<typeof machine>;
type AsyncRef = ActorRefFrom<Promise<User>>;
// After
type Ref = ActorRefFrom<typeof machine>;
type AsyncRef = ActorRefFrom<typeof loadUser>;
ActorRefFrom<typeof machine> refs return the fully typed machine snapshot from getSnapshot(), including context, value and matches('#id').
ceeebb0: State keys cannot contain an unescaped ., which separates path segments. Creating a machine with such a key throws State key "foo.bar" contains "." — nest the states or escape it as "foo\\.bar". To use a literal dot, write the key escaped. The escaped form is then the key everywhere: state values, implicit ids, matches(...), targets and persisted snapshots. It never collides with a nested foo → bar.
// Before
states: { 'foo.bar': {} }, on: { GO: { target: 'foo\\.bar' } }
// After
states: { 'foo\\.bar': {} }, on: { GO: { target: 'foo\\.bar' } }
// snapshot.value === 'foo\\.bar'
Two implicit state ids can no longer coincide, and any duplicate state id now throws.
39d3b5c: # targets, snapshot.matches('#…') and @xstate.stateIn guards resolve by exact state id. The text after # is a state's whole id, either its explicit id or its implicit id (the path from the root, prefixed by the machine id). It is no longer split into an id followed by a relative path. Dots in explicit ids are matched as written, without escaping.
// `wizard` has `id: 'flow'` in a machine with `id: 'shop'`
// Before
browsing: { on: { review: { target: '#flow.review' } } }
// After: the target's full implicit id, or give it its own `id`
browsing: { on: { review: { target: '#shop.wizard.review' } } }
An unknown id throws when the machine is created. When the old id-plus-path form resolves, the error names the target's id:
No state has id "flow.review". Use "#shop.wizard.review", or give that state an id.
Typed # targets and matches('#…') accept only whole ids.
ceeebb0: The root xstate entry no longer exports type-level helpers: TODO, IsAny, IsNever, Equals, Cast, Compute, Prop, HomomorphicOmit, LowInfer, DoNotInfer, SingleOrArray, MaybeLazy and AnyFunction. Define equivalents in your own code if you used them. ConditionalRequired, IsNotNever and NonReducibleUnknown remain exported because emitted declarations reference them, and are marked @experimental.
ActorOptions no longer has the undocumented parent option. Create child actors with invoke, spawn(...) or enq.spawn(...).
ceeebb0: Implicit state and invoke ids no longer use the (machine) placeholder.
., prefixed by the machine id when there is one: shop.checkout.payment for id: 'shop', and checkout.payment without an id (previously (machine).checkout.payment).machine.id and the root state's id are '' for a machine without an id. # cannot reference that root; give the machine an id to target it as #shop.<stateId>:<index>: loading:0, loading:1, shop.checkout:0. A root invoke is :0, or shop:0 with a machine id (previously 0.(machine).loading). Anonymous spawned actors keep x:<n>, and generated spawn ids skip ids already held by an invoke.id that equals another state's id throws when the machine is created.the machine instead of machine '(machine)'.const machine = createMachine({
initial: 'loading',
states: { loading: { invoke: { src: fetchUser } } }
});
createActor(machine).getSnapshot().children; // { 'loading:0': ... }
machine.getStateNodeById('#loading').id; // 'loading'
Persisted snapshots that reference (machine).… state ids or 0.(machine).… child ids do not restore; migrate them with machineVersions.
ceeebb0: Children invoked with inline logic no longer get a synthetic source name (xstate.invoke.<index>.<stateId>). Their persisted entries omit src, and restoring resolves them through the invoke definition with the same id among the restored active states. Restoring fails with a descriptive error when no active state, or more than one, invokes that id. Children invoked with a registered name (src: 'fetchUser') keep persisting that key, and remote children still require one.
const machine = createMachine({
id: 'shop',
initial: 'loading',
states: {
loading: { invoke: { id: 'fetch', src: fetchUser } }
}
});
createActor(machine).start().getPersistedSnapshot().children.fetch;
// { address: 'shop/fetch', snapshot: {...} }, with no `src`
Snapshots persisted by earlier alphas that carry src: 'xstate.invoke.…' no longer restore; remove that src or migrate them with machineVersions.
ceeebb0: Bare string transition values throw when the machine is created, in every build. This matches the types and machineFromJSON, which already rejected them. It covers on, after, always, onDone, onError, onTimeout, and invoke onDone/onError/onSnapshot/onTimeout. initial stays a string key, and xstate/fsm still accepts string targets.
// Throws: Transition for "GO" in state "idle" is the string "next". Use { target: 'next' }.
on: { GO: 'next' }
// Use
on: { GO: { target: 'next' } }
xstate-codemod migrate (the string-targets transform) rewrites these.
ceeebb0: invoke requires input when the invoked actor logic requires input, matching createActor(logic, { input }) and enq.spawn(logic, { input }). This applies to logic values, registered source names and src functions, in createMachine, setup(...).createMachine and setup(...).createStateConfig. Logic whose input type accepts undefined (no schemas.input, or an optional input schema) can still omit it.
const child = createMachine({
schemas: { input: z.object({ userId: z.string() }) }
});
createMachine({
// Type error: This actor logic requires input. Add an `input` to this invoke.
invoke: { src: child }
});
createMachine({
invoke: { src: child, input: ({ context }) => ({ userId: context.userId }) }
});
enq.spawn(logic) without required input now reports Expected 2 arguments instead of a mismatch against the source-name overload.
ceeebb0: A machine that declares version must also declare id, because persisted snapshots record the machine as { id, version }. createMachine, setup(...).createMachine and MachineJSON report a missing id as a type error, and creating such a machine throws Machine with version '2' must declare an id. Machines without a version keep id optional.
// Before
createMachine({ version: '2', initial: 'idle', states: { idle: {} } });
// After
createMachine({
id: 'order',
version: '2',
initial: 'idle',
states: { idle: {} }
});
ceeebb0: # transition targets type-check against implicit state ids as well as explicit ones: target: '#checkout.payment', or '#shop.checkout.payment' for a machine with id: 'shop'. Unknown ids are still type errors. At runtime, a # target can name a whole implicit id below a state with an explicit id, such as '#wizard.step' when wizard has id: 'flow'.
ceeebb0: enq.spawn(...) returns an inert actor ref while a transition is only evaluated, such as by snapshot.can(event) or when resolving conflicting transitions in parallel states. The ref has the id (and, when the parent is known, the address) the real spawn would get, an undefined sessionId, a stable getSnapshot(), a no-op send(), and toJSON() returning { $actor: address }. Previously it was a bare { id } object.
ceeebb0: createActor(machine, { snapshot }) reports a persisted snapshot that cannot represent a state as an 'error' snapshot with an InvalidSnapshotError, instead of starting an unusable actor. This covers snapshots that are not objects, have no value or an invalid one (not a state name or an object of state values, or several active children of a non-parallel state), and values naming states the machine does not have. Unknown fields are still ignored.
import { createActor, InvalidSnapshotError } from 'xstate';
const actor = createActor(machine, { snapshot: stored });
const snapshot = actor.getSnapshot();
if (snapshot.status === 'error' && snapshot.error instanceof InvalidSnapshotError) {
// fall back to a fresh actor
}
73b2edf: Fix several v6 alpha transition, typing, and inspection issues:
enq calls in try/catch, and avoid reevaluating ordinary effect-only transitions during selection.unknown or any input.cause when graph transition evaluation fails. Supply representative payloads through the graph traversal events option when transition functions require them.05f1e0f: Ship version-matched XState v6 documentation with the xstate package. Start with README.md or docs/index.md after installation for v6 examples and migration guidance.
8773a22: Require payload samples for known event types with required fields in getShortestPaths, getSimplePaths, and getAdjacencyMap. Use an events map to explore multiple payloads while retaining default payload-free events, invoke completions, errors, and delays:
getShortestPaths(machine, {
events: {
'item.add': [{ item: { qty: 1 } }, { item: { qty: 0 } }]
}
});
Each map entry also accepts a snapshot callback returning nonempty payload cases. Event arrays and callbacks returning events still replace defaults, but their types must cover every required payload event. Fixed-sequence replay with getPathsFromEvents requires only the supplied events. Coverage remains sample-based.
Unconfigured wildcard descriptors retain their default samples alongside concrete event cases. Use an event array to restrict traversal to supplied concrete events.
aaa891a: createAsyncLogic no longer rejects a run that returns a literal matching schemas.output. Previously a parameterless run widened { kind: 'a' }
aaa891a: createAsyncLogic no longer rejects a run that returns a literal matching schemas.output. Previously a parameterless run widened { kind: 'a' } to { kind: string }, so the call failed with "not assignable to type 'never'", including inside machine.provide({ actors }). A run that does not match schemas.output now reports the output mismatch.
type Outcome = { kind: 'a' } | { kind: 'b'; n: number };
const load = createAsyncLogic({
schemas: { input: types<{ id: string }>(), output: types<Outcome>() },
run: async () => ({ kind: 'a' }) // OK, output is `Outcome`
});
A parameterless run now keeps literal return types whenever schemas is provided, including input-only and error-only schemas. Without schemas, outputs still widen ({ ok: true } is { ok: boolean }).
d2c518b: Public names are consistent before the beta. The old names are not kept as aliases.
d2c518b: Public names are consistent before the beta. The old names are not kept as aliases.
| Before | After |
|---|---|
serializeMachine(machine) |
machineToJSON(machine) (returns MachineJSON) |
createMachineFromConfig(json, sources) |
machineFromJSON(json, sources) |
createLogic |
createStepLogic |
LogicActorLogic, LogicActorRef, LogicSnapshot |
StepActorLogic, StepActorRef, StepSnapshot |
LogicConfig, LogicArgs, LogicEnqueue, LogicFunction |
StepLogicConfig, StepLogicArgs, StepLogicEnqueue, StepLogicFunction |
LogicPatch, LogicEffectState |
StepPatch, StepEffectState |
LogicEffect |
ExecutableEffect |
EffectDescriptor, getEffectDescriptor |
ExecutableEffectDescriptor, describeExecutableEffect |
checkStateIn(snapshot, value) |
snapshot.matches(value) |
state node contextSchema |
state node schemas: { context } |
StrictSetupStateTargetsFlag, StrictSetupStateTargetsMarker |
StrictSetupStateTargetsMarker, StrictSetupStateMarkers |
machineConfigToJSON(config) is unchanged and now returns MachineJSON.
Removed exports: listenerLogic, subscriptionLogic (use createListenerLogic()/createSubscriptionLogic()), __unsafe_getAllOwnEventDescriptors (use getAllOwnEvents from xstate/graph), toObserver, pathToStateValue, SpecialTargets, and the devTools actor option type.
The report-removed-apis codemod reports toObserver, pathToStateValue and SpecialTargets, and its stateIn hint suggests snapshot.matches(...).
- import { createLogic, serializeMachine } from 'xstate';
+ import { createStepLogic, machineToJSON } from 'xstate';
d2c518b: Built-in event and effect type strings follow one rule: events delivered to logic use the xstate. prefix, and effect types use the @xstate. prefix. Inspection records (@xstate.actor, @xstate.transition) are unchanged.
| Before | After | Kind |
|---|---|---|
@xstate.init |
xstate.init |
event |
@xstate.stop (sent to a stopping actor) |
xstate.stop |
event |
xstate.timeout |
xstate.timeout.state |
event |
xstate.system.cancelEffect |
@xstate.cancelEffect |
effect |
xstate.logic.cleanup |
@xstate.cleanup |
effect |
xstate.logic.effect |
@xstate.effect |
effect |
xstate.log (system effect) |
@xstate.log |
effect |
Built-in guard types in MachineJSON are source keys, not events, so they use the @xstate. prefix:
| Before | After |
|---|---|
xstate.not |
@xstate.not |
xstate.stateIn |
@xstate.stateIn |
In development, action, guard, actor and delay source names that start with xstate. or @xstate. throw. machineFromJSON also rejects JSON-defined actions, guards and delays with those names.
The stop-child effect stays @xstate.stop. Helper actors created by enq.listen() and enq.subscribeTo() use the @xstate.listener and @xstate.subscription source keys, so their ids look like @xstate.listener:0. In development, spawned sources whose id starts with xstate. or @xstate. throw.
Suffixed lifecycle event types are no longer matched. Key transitions by the category type and select the payload with matches:
on: {
- 'xstate.done.actor.job': { target: 'complete' }
+ 'xstate.done.actor': { matches: { actorId: 'job' }, target: 'complete' }
}
This applies to xstate.done.actor.<id>, xstate.error.actor.<id>, xstate.snapshot.<id> (now xstate.snapshot.actor), xstate.done.state.<id>, xstate.after.<delay>.<id>, xstate.timeout.<id> and xstate.timeout.actor.<id>, both as transition keys and as sent event types.
d2c518b: Serialized actor identity uses one shape everywhere: { $actor: address }, with an optional string incarnation.
| Where | Before | After |
|---|---|---|
actor.toJSON(), SerializedActorRef |
{ xstate$type: 'actorRef', id, address, src } |
{ $actor: address } |
Actor refs in persisted context |
{ xstate$type: 'actorRef', id, address? } |
{ $actor: address } |
Effect descriptor source/actor/target |
address string (+ incarnation on sendTo) |
{ $actor: address, incarnation? } |
System snapshot incarnation |
number |
string |
SystemActorState.logic |
logic |
src |
System dead-letter effect kind |
'deadLetter' |
'builtin' (type @xstate.deadLetter) |
| Persisted timer start | startedAt |
scheduledAt |
Persisted snapshot top-level version |
mirror of machine.version |
removed; use machine.version |
The old shapes are not read on restore. Convert or discard snapshots persisted with xstate$type actor refs or startedAt timers before restoring them.
d2c518b: Pending timers are a list, and no generated timer ids exist.
| Where | Before | After |
|---|---|---|
snapshot.timers (in memory and persisted) |
record keyed by id | list in scheduling order |
after, state timeout, invoke timeout timers |
generated id (xstate.after.<delay>.<stateId>, xstate.timeout.state.<stateId>, …) |
no id; identified by their event |
delayed raise/send without an id |
generated xstate.timer.auto.<n> |
seq (the actor's sequence number) |
ActorSystemRuntime.scheduleTimer / cancelTimer |
(source, id, delay) / (source, id) |
(source, timer, delay) / (source, timer) with a TimerKey |
| timer firing input | { type: 'xstate.timer', id } |
{ type: 'xstate.timer', ...timer } |
@xstate.cancel effect and descriptor |
id |
the cancelled TimerKey fields (id, seq or event) |
system snapshot timers |
record; SystemTimer.id |
list; SystemTimer.event is the firing input; select by occurrence |
A TimerKey is { id }, { seq } or, for a built-in timer, { event } with the event identity ({ type, stateId, delay } for xstate.after, { type, stateId } for xstate.timeout.state, { type, actorId } for xstate.timeout.actor). Durable hosts key timers by source.address plus the key.
enq.cancel(...) also accepts a TimerKey, which cancels a built-in timer:
enq.cancel({
event: { type: 'xstate.after', stateId: 'machine.waiting', delay: 1000 }
});
Snapshots persisted with the old timers record are not read on restore.
d2c518b: snapshot.matches('#id') is true while the state node with that id is active. This replaces the removed checkStateIn(snapshot, '#id').
const machine = createMachine({
initial: 'editing',
states: {
editing: {
initial: 'draft',
states: { draft: { id: 'draft' }, review: {} }
},
done: {}
}
});
const snapshot = createActor(machine).start().getSnapshot();
snapshot.matches('#draft'); // true
snapshot.matches('#nope'); // type error: not a state id of this machine
When the machine's state ids are statically known, only those ids are accepted. Unlike state-value checks, an #id check does not narrow context. The @xstate.stateIn JSON guard uses the same check.
37b3c73: The persisted snapshot JSON schema now accepts unknown fields on the envelope, on children entries and on timers entries. Readers should ignore fields they don't recognize; future 6.x releases may add optional fields.
b8edbab: enq.sendTo(...) accepts a serialized actor ref — the { $actor: address } value an actor ref becomes after JSON.stringify, e.g. a replyTo in an event payload after persistence or a remote hop. The event is delivered to whichever actor is live at that address when the send executes (for a delayed send, when its timer fires), or reported as a 'missingTarget' dead letter (via onRejectedEvent) when no live actor has it. Previously this threw a TypeError and the event was lost. Serialized refs held in context also keep their address across persistence and restore. Use the new SerializedActorRef type to type such fields.
const server = createMachine({
schemas: {
events: {
ping: types<{ replyTo: SerializedActorRef; requestId: string }>()
}
},
on: {
ping: ({ event }, enq) => {
enq.sendTo(event.replyTo, { type: 'pong', requestId: event.requestId });
}
}
});
Actor refs stored in context now persist with their address, so a ref to an actor that isn't a child (such as a stored replyTo) still routes after restore.
A pending delayed send to a serialized ref persists with that ref as its timer target and resolves it by address after restore.
A serialized ref that carries an incarnation reaches only that incarnation: if a different actor is live at the address when the send executes, the event is reported as a 'missingTarget' dead letter.
5d7dfb3: snapshot.matches(...) accepts a state value whose leaves are not literals, such as { checkout: string }, as it accepts string and StateValue. Values are checked per position: a non-literal leaf is accepted at its own position, and every literal key and child beside it must still name a state, so { nope: 'payment', checkout: step } is rejected.
d175de9: Fix declaration generation for exported machine.provide({ actions }) variants and createStateConfig() fragments with invoke input mappers.
d175de9: Fix declaration generation for exported machine.provide({ actions }) variants and createStateConfig() fragments with invoke input mappers.
Entry and exit functions now receive a working enq regardless of their parameter count, including default/rest parameters and forwarding wrappers. Returned context and child patches are applied consistently. Functions that enqueue no effects no longer add placeholder effects to pure transition results.
import { createMachine } from 'xstate';
const machine = createMachine({
initial: 'loading',
states: {
loading: {
entry: (...[, enq]) => enq.raise({ type: 'ready' }),
on: { ready: { target: 'ready' } }
},
ready: {}
}
});
32487c8: Fix nested and parallel state value inference for machines declaring setup({ states }) when exactOptionalPropertyTypes is enabled. Both forms of snapshot.matches(...) now accept valid nested states:
snapshot.matches({ b: 'x' });
snapshot.matches('b.x');
7bb5f0c: Change machine.eventSchema to validate complete public input events. It now rejects declared internal events and reserved runtime events, whi
7bb5f0c: Change machine.eventSchema to validate complete public input events. It now rejects declared internal events and reserved runtime events, while allowing explicitly configured xstate.route destinations.
const result = await machine.eventSchema['~standard'].validate(input);
if (!result.issues) {
actor.send(result.value);
}
This changes the previous alpha schema contract. Use actual machines with machineVersions().adaptEvents() to keep validating complete internal/runtime histories. Historical descriptors should provide their own complete history schema. actor.send() remains unchanged for trusted runtime delivery and replay. Payload validation requires runtime schemas; types<T>() supplies types only.
dd5eb47: createMachine() without schemas.context now infers the context type from the return value of a context function, as it already did from a context object:
snapshot.context.count was a type error.spawn were typed any. They now have the type of the spawned logic.invoke whose src is an unregistered machine, the call failed with TS2769 ("… is not assignable to type 'never'") against the published declarations.const machine = createMachine({
actors: { connection },
context: ({ spawn, actors }) => ({
count: 0,
connection: spawn(actors.connection, { id: 'connection' })
})
});
const { context } = createActor(machine).getSnapshot();
context.count; // number
context.connection; // ActorRefFromLogic<typeof connection>, was `any`
dd5eb47: Development builds now warn when a function passed to enq(...) returns { context } or { children }. Enqueued functions run as effects after the transition, so that value has always been ignored, and nothing said so. To update context from a named action, call it directly in the transition, entry or exit function and return its result:
const formSetup = setup({
schemas: { events: { pick: z.object({ country: z.string() }) } },
actions: {
applyDefaults: (country: string) => ({
context: { currency: country === 'FR' ? 'EUR' : 'USD' }
})
}
});
// Applied: the transition function returns the patch
pick: ({ actions, event }) => actions.applyDefaults(event.country);
// Ignored, and now reported in development
pick: ({ actions, event }, enq) => {
enq(actions.applyDefaults, event.country);
};
dd5eb47: Enqueueing a value that is not a function, such as a named action that has no implementation, now enqueues nothing, and development builds log a warning. Before, it showed up as an event without a type: actor.on('*') listeners received it, inspection listed it as an action, and pure transition() returned it as an emit effect. A validated machine that declares schemas.emitted errored with "Unknown emitted event".
const machine = setup({
schemas: { actions: { track: { params: z.object({ key: z.string() }) } } }
}).createMachine({
on: {
// `actions.track` is undefined until an implementation is provided
submit: ({ actions }, enq) => {
enq(actions.track, { key: 'submit' });
}
}
});
dd5eb47: Entry and exit functions now behave the same in more cases, whatever the number of parameters they declare:
guards and delays, as one declared with (args, enq) already did. Calling a named guard from it no longer throws.context returned by one declared with (args, enq) is now applied, as it already was for other exit functions.(args, enq) receives the current children, without the invoked children of the states exited before it.enq. Development builds now warn when any other entry or exit function calls enq, because the call is ignored. This catches wrappers that forward (...args) and an enq parameter with a default value.dd5eb47: Children spawned or stopped by an entry function are no longer undone when a later state with an invoke is entered in the same microstep, such as the entered state's initial child. Before, a child spawned with enq.spawn(...) was dropped from snapshot.children, so enq.sendTo(...) dead-lettered events to it and stopping the parent left it running, and a child stopped with enq.stop(...) came back. The entry functions of states entered later in the microstep also receive the current children.
dd5eb47: machine.provide({ actions }) now checks a replacement action's result, not only its parameters. When the declared action returns a result, such as a context patch that a transition returns, the replacement must return a compatible one. Before, a replacement that returned a mistyped patch, another value or nothing at all compiled, and the transition applied whatever it returned. An action declared to return nothing can still be replaced by one that returns any value, such as an Effect. A replacement is checked against the declared action, not against an earlier replacement.
const machine = setup({
schemas: { events: { pick: z.object({ country: z.string() }) } },
actions: {
applyDefaults: (country: string) => ({
context: { currency: country === 'FR' ? 'EUR' : 'USD' }
})
}
}).createMachine({
context: { currency: 'USD' },
on: { pick: ({ actions, event }) => actions.applyDefaults(event.country) }
});
machine.provide({
// now a type error: `applyDefaults` returns a context patch
actions: { applyDefaults: () => {} }
});
dd5eb47: transition(machine, snapshot, event) and getMicrosteps(...) no longer process events on a done, error or stopped snapshot. Every event is unhandled there, as it is for an actor with that status: the same snapshot comes back with no effects. Before, the machine's transitions still ran, so a done snapshot could leave its final state while keeping status: 'done', an error snapshot could become done, and a stopped snapshot could emit @xstate.terminate.
dd5eb47: Reduce unnecessary typechecking work for validated setups with many invoke sites and registered actors when internal events are absent.
dd5eb47: Return false from snapshot.can() on terminal snapshots without evaluating transitions. Active snapshot dry runs still propagate evaluation errors; document that they do not execute state error recovery. Narrow known reserved machine-event handlers to their actual payloads and reject misspelled or unknown reserved prefixes when event schemas close the union.
dd5eb47: Export getAllOwnEvents() from xstate/graph so custom traversal events can retain invoke and delay events. Accept synthesized internal events in traversal options. Omit unknown function targets from static directed graphs and expose resolved targets in microstep inspection. Validate event schemas that explicitly declare their type discriminator.
dd5eb47: Make JSON machine loading reject unknown structural keys, string transitions, invalid initial states, unresolved nested guards, and cyclic guard definitions. Apply action lists sequentially, evaluate nested output expressions, and report precise evaluator paths. Restore runtime sources and support runtime schemas plus a validator when reviving machines. Copy loaded and serialized definitions so callers cannot mutate the machine. Accept payloads on raised JSON events.
dd5eb47: Evaluate applied transition context and input mappers once. Clean up async actor timeouts when run() throws synchronously. Report unsuccessful route events as unhandled. Reject obsolete v5 transition keys in production and development, and diagnose misplaced setup internal-event declarations and enqueue-before-rejection mistakes.
dd5eb47: Preserve context, internal-event, transition metadata, emitted-event, and concrete schema types in public helpers and provided machines. Fix declaration emit for state configurations with parameterized callbacks and registered actors. Reject incompatible extend() source replacements and nonexistent literal matches() states. Widen schema-free async outputs using ordinary TypeScript inference. Reduce validator state-constraint cost and check transforming schemas independently in every state.
26378e5: Add experimental pure actor-system transitions with immutable system snapshots, external effects as data, and chronological virtual time acro
26378e5: Add experimental pure actor-system transitions with immutable system snapshots, external effects as data, and chronological virtual time across actors.
const systemLogic = { root: machine };
const [snapshot] = initialSystemTransition(systemLogic, { input });
const [nextSnapshot, effects] = systemTransition(systemLogic, snapshot, snapshot.root, event);
const [laterSnapshot] = advanceSystemTime(systemLogic, nextSnapshot, { time: 4000 });
SimulatedClock now runs callbacks at each timer's deadline before reaching the
requested time, including intermediate timers created during those callbacks.
Large timer batches advance efficiently while preserving deadline and insertion
order. Subscription completion/error mappings arrive before native child
notifications, matching live actors.
295a705: Durable executions preserve timer deadlines in checkpoints persisted after executeEffects() succeeds. Adapters can provide an absolute now() clock shared across restores and replay. Root error snapshots no longer also trigger an unhandled global throw; explicit hosts handle the snapshot, while run() rejects with its error.
createMachineFromConfig() retains named actor sources so .provide({ actors }) can replace them, including when restoring children.
Reserved xstate.* transition descriptors are accepted without losing exact declared event payload types. Machines created from never configs no longer trigger excessive type instantiation in generic consumers.
await execution.executeEffects(effects);
const checkpoint = machine.getPersistedSnapshot(snapshot);
8e509ae: Add setup(...).createInvoke(...) for typed inline invocations. The helper infers actor input, completion output, errors and snapshots from its src logic. Async functions can be authored directly in src, with optional schemas.input, schemas.output and schemas.error. Without an output schema, completion output is inferred from the async return value. Inline calls also infer the enclosing state's narrowed context, state input and transition targets, including alongside registered actor sources.
Actors whose input excludes undefined require an input value or mapper. Invokes check their child IDs and source compatibility against schemas.children declared in either the setup or machine.
invoke: s.createInvoke({
schemas: { input: types<{ userId: string }>() },
input: ({ context }) => ({ userId: context.userId }),
src: async ({ input }) => ({ name: input.userId }),
onDone: ({ event }) => ({
context: { name: event.output.name }
})
})
d6dbf41: Add experimental execution.restore(persistedSnapshot) to xstate/durable for resuming checkpoints without sending a synthetic event or replayi
d6dbf41: Add experimental execution.restore(persistedSnapshot) to xstate/durable for
resuming checkpoints without sending a synthetic event or replaying entry
actions. Execute the returned effects to resume active embedded children and
pending timers. Restored child startup uses the host adapter, including nested
children. Timers with a persisted wall-clock start keep their original deadline,
including time spent waiting to execute effects or starting children.
const execution = createDurable(machine, {
...adapter,
transitionIndex: checkpoint.nextTransitionIndex
});
const [snapshot, effects] = execution.restore(checkpoint.snapshot);
await execution.executeEffects(effects);
The deprecated top-level internalEvents machine config key and the deprecated state actor option are removed.
9003cf1: ### Removed
The deprecated top-level internalEvents machine config key and the deprecated state actor option are removed.
Declare private events in schemas.internalEvents:
// Before
createMachine({
schemas: { events: { start: z.object({}), tick: z.object({}) } },
internalEvents: ['tick'] as const
// ...
});
// After
createMachine({
schemas: {
events: { start: z.object({}) },
internalEvents: { tick: z.object({}) }
}
// ...
});
Restore a persisted snapshot with the snapshot option:
// Before
createActor(machine, { state: persistedSnapshot });
// After
createActor(machine, { snapshot: persistedSnapshot });
In development builds, a config with a top-level internalEvents key throws an error naming schemas.internalEvents, and passing state to createActor(...) throws an error naming snapshot.
5228c00: Infer the current service requirements of actions and actors replaced with machine.provide. Require declared actor input in createActorAtoms, consistently with createEffectActor.
Effect tasks and streams now release their resources when they complete, fail or are cancelled. Actor shutdown waits for task cleanup before releasing resources shared for the actor's lifetime. Use withActorScope around an acquisition to keep its resource until the owning Effect actor stops:
import { Effect } from 'effect';
import { withActorScope } from '@xstate/effect';
const session = Effect.acquireRelease(
Effect.succeed({ id: 'session' }),
() => Effect.log('Session closed')
).pipe(withActorScope);
Improve XState Effect guides with complete, tested workflow, stream, inspection and React examples.
77cad04: Resolve after delays and state timeout functions with context updated by the same state's entry function.
State timers are scheduled after the entry function's queued actions. Entry cancellation runs before scheduling; cancellation from a later event handler still cancels an active timer.
waiting: {
entry: () => ({ context: { ms: 300 } }),
after: { d: { target: 'done' } }
}
// With delays: { d: ({ context }) => context.ms }, waits 300ms.
The deprecated type aliases NoInfer (use the built-in NoInfer), AnyInterpreter (use AnyActor), and ResolvedStateMachineTypes.
3e024f9: createAsyncLogic accepts schemas.error. It types the actor's error snapshot field and event.error in the invoking machine's onError. Without it, the error stays unknown, so reading properties from it is a type error.
const fetchUser = createAsyncLogic({
schemas: {
output: z.object({ name: z.string() }),
error: z.object({ code: z.string() }),
},
run: async () => ({ name: "David" }),
});
setup({ actors: { fetchUser } }).createMachine({
invoke: {
src: "fetchUser",
onError: ({ event }) => {
event.error.code; // string
},
},
});
Without schemas.error, narrow event.error before reading from it.
With a timeout, the error type also includes TimeoutError, so narrow before reading schema fields:
onError: ({ event }) => {
if (event.error instanceof TimeoutError) return;
event.error.code; // string
};
3e024f9: Children declared in schemas.children now contribute their completion events to the event union seen by entry, exit, guards and transition functions. assertEvent(event, 'xstate.done.actor') narrows event.output to the child's output type, and event.actorId to the declared ids.
setup({
actors: { fetchUser },
schemas: {
children: { fetch: z.custom<ActorRefFromLogic<typeof fetchUser>>() }
}
}).createMachine({
invoke: { id: 'fetch', src: 'fetchUser' },
entry: ({ event }) => {
assertEvent(event, 'xstate.done.actor');
event.output.name; // string
}
});
Code that assumed every event in these positions is a declared public event may need a narrowing check first.
73fa80b: Entry and exit functions now receive stateNode, the state node being entered or exited.
createMachine({
initial: 'a',
states: {
a: {
entry: ({ stateNode }, enq) => {
enq(() => console.log('Entered', stateNode.id));
}
}
}
});
11c6f52: createFSM from xstate/fsm now follows the (snapshot, event) => [snapshot, effects] protocol used by all actor logic. fsm.transition(...) returns a [nextSnapshot, effects] tuple, where effects is always empty, and snapshots include status: 'active'. An FSM can now run in createActor and be passed to transition() and initialTransition().
Before:
let state = fsm.initialState;
state = fsm.transition(state, { type: 'toggle' });
After:
let state = fsm.initialState;
[state] = fsm.transition(state, { type: 'toggle' });
// Run it as an actor
import { createActor } from 'xstate';
const actor = createActor(fsm).start();
actor.send({ type: 'toggle' });
actor.getSnapshot().value; // 'active'
97e9166: getMicrosteps() and getInitialMicrosteps() now return the transitions taken in each microstep as a third tuple element, including eventless transitions and transitions for raised events.
import { getMicrosteps } from 'xstate';
for (const [snapshot, actions, transitions] of getMicrosteps(
machine,
snapshot,
event
)) {
console.log(transitions.map((t) => `${t.source.id} -> ${t.eventType}`));
}
d62cdc7: One event now has a single microstep bound: options.maxIterations, which defaults to 1000. Exceeding it throws the new exported InfiniteTransitionError, whose message names the actor id, the event and the last five states visited. Previously a hard-coded limit of 1000 applied regardless of maxIterations, so raising the limit had no effect.
import { createMachine, InfiniteTransitionError } from 'xstate';
const machine = createMachine({
options: { maxIterations: 5000 },
// ...
});
aa49aee: ### Removed
createFSM and the FSM* types are no longer exported from the root xstate entry. Import them from xstate/fsm.xstate/actions, xstate/guards, xstate/invoke, and xstate/dev folders are no longer published.xstate/graph: getStateNodes(stateNode) is renamed to getDescendantStateNodes(stateNode) so it no longer shares a name with the root getStateNodes(stateNode, stateValue).import { createFSM } from 'xstate/fsm';
import { getDescendantStateNodes } from 'xstate/graph';
8576291: Remove the @xstate.deadletter inspection event; observe undelivered events with the onRejectedEvent option. The inspection protocol is now exactly @xstate.actor and @xstate.transition. In @xstate/effect, deadLetters(actor) now streams EventRejection objects.
createActor(machine, {
onRejectedEvent: (rejection) => {
console.log(rejection.event.type, rejection.reason, rejection.issues);
}
});
Undelivered events are also available through system.onRejectedEvent(listener), which accepts any number of listeners added at any time and returns a subscription. The onRejectedEvent option registers a listener the same way.
const subscription = actor.system.onRejectedEvent((rejection) => {
console.log(rejection.event.type, rejection.reason);
});
subscription.unsubscribe();
aa49aee: ### Removed
getInitialSnapshot(logic, input?) and getNextSnapshot(logic, snapshot, event). Use initialTransition(...) and transition(...), which return [snapshot, effects].NoInfer (use the built-in NoInfer), AnyInterpreter (use AnyActor), and ResolvedStateMachineTypes.import { initialTransition, transition } from 'xstate';
const [initial] = initialTransition(machine, input);
const [next] = transition(machine, initial, { type: 'NEXT' });
97e9166: Removed createTestModel and TestModel from xstate/graph; use @xstate/test. The types used only by them (TestModelOptions, TestParam, TestPath, TestPathResult, TestStepResult, TestMeta, EventExecutor) and createShortestPathsGen/createSimplePathsGen are removed too. xstate/graph keeps its path traversal functions.
// Before
const model = createTestModel(machine, {
events: [
{ type: 'SUBMIT', zip: '12345' },
{ type: 'SUBMIT', zip: 'abc' },
{ type: 'CANCEL' }
]
});
for (const path of model.getShortestPaths()) await path.test(params);
// After: `events` is keyed by event type; each payload becomes a named case
import * as fc from 'fast-check';
import { testPaths } from '@xstate/test';
await testPaths(machine, {
events: {
SUBMIT: [
{ case: 'valid', generate: fc.constant({ zip: '12345' }) },
{ case: 'invalid', generate: fc.constant({ zip: 'abc' }) }
]
},
samples: 1,
sut
});
Event types without a payload, such as CANCEL, need no entry.
73fa80b: createActor(machine) now requires input when the machine declares an input schema whose type does not accept undefined. Restoring from a persisted snapshot does not require input.
const machine = setup({
schemas: { input: z.object({ id: z.string() }) }
}).createMachine({});
createActor(machine); // type error
createActor(machine, { input: { id: 'a' } }); // ok
createActor(machine, { snapshot: persisted }); // ok
aa49aee: ### Removed
xstate/scxml entry point moved to the new @xstate/scxml package. xstate no longer depends on saxes.// Before
import { createMachineFromSCXML } from 'xstate/scxml';
// After (npm i @xstate/scxml)
import { createMachineFromSCXML } from '@xstate/scxml';
d62cdc7: enq.sendTo(...) to a missing target no longer errors the sending actor. Sending to an undefined ref, to a child id with no running child, or to parent from a root actor now produces a dead letter with reason 'missingTarget': the actor stays active, onRejectedEvent receives the event (with targetId and sourceRef), and development builds log a warning naming the sender and the target. State onError handlers no longer receive xstate.error.communication for these sends.
const actor = createActor(machine, {
onRejectedEvent: (rejection) => {
if (rejection.reason === 'missingTarget') {
console.log(rejection.event, rejection.targetId);
}
}
});
d62cdc7: Actors are single-use. Calling start() on an actor after stop() now throws Actor <id> was stopped and cannot be restarted. Create a new actor with createActor(). in all builds, instead of silently doing nothing. Calling start() on a running actor, or on an actor that already completed or errored, is still a no-op.
actor.stop();
actor.start(); // throws
const next = createActor(machine).start();
3e024f9: When delays are declared (setup({ delays }) or createMachine({ delays })), each after key must be a declared delay name, a number of milliseconds or a duration string such as '5s'. The error now names the offending key. Duration strings are no longer rejected when named delays are declared. Duration keys are checked against the forms the runtime parses: integer milliseconds ('250ms'), decimal seconds ('1.5s') and ISO 8601 durations ('PT1M30S'). Malformed keys such as 'Pfoo' or '1.5ms' are type errors.
setup({ delays: { retryDelay: 1_000 } }).createMachine({
initial: 'waiting',
states: {
waiting: {
after: {
// Type error: Delay 'retryDelya' is not declared in delays.
retryDelya: { target: 'retrying' }
}
},
retrying: {}
}
});
Fix the name, or declare the delay in delays.
At runtime, a delay that is neither a configured delay name nor a valid duration string now errors the actor with Invalid delay "…" instead of firing immediately.
3e024f9: When schemas.events is declared, every key in a state's on map must match a declared event type. Wildcards ('*', 'user.*') and reserved xstate.* event types remain allowed. Machines without schemas.events are unchanged.
setup({
schemas: { events: { toggle: z.object({}) } }
}).createMachine({
on: {
// Type error: Event type 'toggel' is not declared in schemas.events.
toggel: { target: '.active' }
}
});
Fix the typo, or declare the event in schemas.events.
d62cdc7: Unhandled events are now observable.
transition(logic, snapshot, event) returns the same snapshot object and no effects when no transition handles the event. A handled event always returns a new snapshot object, including a transition function that returns {}.isUnhandled(previousSnapshot, result) helper.onUnhandledEvent(event, snapshot) option for createActor(...).xstate.* events are not reported.import { createActor, isUnhandled, transition } from 'xstate';
const result = transition(machine, snapshot, { type: 'unknown' });
isUnhandled(snapshot, result); // true
createActor(machine, {
onUnhandledEvent: (event, snapshot) => {
console.log(`${event.type} not handled in`, snapshot.value);
}
});
ef251fa: Development builds now report leftover v5 configuration (cond, types, string actions, …) with the v6 replacement instead of ignoring it.
// Before: `cond` was silently ignored, so the transition was always taken
createMachine({
initial: 'idle',
states: {
idle: {
on: { submit: { target: 'sending', cond: ({ context }) => context.valid } }
},
sending: {}
}
});
// Now throws: Transition "submit" in state "(machine).idle" uses "cond",
// which was removed. Use an inline transition function instead: ...
// After
createMachine({
initial: 'idle',
states: {
idle: {
on: {
submit: ({ context }) => {
if (!context.valid) return;
return { target: 'sending' };
}
}
},
sending: {}
}
});
cond, object-form guard, transition actions, non-function entry/exit, types, tsTypes and schema throw. services, activities, predictableActionArguments, preserveActionOrder, strict and devTools log a warning. Machines built with createMachineFromConfig or createMachineFromSCXML are not checked.
0fe9afe: React Fast Refresh keeps the running actor and its state when you edit a machine. In development builds, useActorRef(), useActor() and useMachine() switch the running actor to the edited machine, so the current state and context are kept, including context that holds DOM elements or cyclic objects. If the edited machine cannot represent the current state, the actor restarts from the edited machine. Production builds are unaffected.
73fa80b: Final states are now inert everywhere, including final regions of a parallel state, matching SCXML: they take no transitions and their invoked actors are not created or started. In development, createMachine warns when any final state declares invoke, on or after.
Move transitions off a final region onto a non-final state:
region: {
initial: 'active',
states: {
active: { on: { NEXT: { target: 'done' } } },
done: { type: 'final' }
}
}
8576291: Persisting a snapshot whose context contains a circular reference now throws a descriptive error instead of a RangeError (maximum call stack size exceeded). Shared references that are not circular still persist.
const node: Record<string, unknown> = {};
node.self = node;
const machine = createMachine({ id: 'tree', context: { node } });
createActor(machine).getPersistedSnapshot();
// Error: Cannot persist actor "tree": circular reference at context.node.self
8576291: In development builds, getPersistedSnapshot() warns when context, output, error or state inputs contain a value that does not survive a JSON round-trip: a function, symbol, BigInt, NaN or Infinity, Map, Set or circular reference. The warning names the path of the first such value.
d62cdc7: Restoring a snapshot whose state has always transitions or is a choice state now logs a development warning: restored snapshots are not re-evaluated, so those eventless transitions do not run until the next event.
d62cdc7: A persisted snapshot that fails to restore (for example, an unknown state in value or a machine id mismatch) now produces a full machine snapshot with status: 'error' and the failure as error, instead of a bare { status, output, error } object. snapshot.matches(...), snapshot.can(...) and the other snapshot methods keep working.
d62cdc7: Restoring a persisted snapshot with status: 'stopped' now yields a stopped actor. Previously the restored actor kept processing events, running transitions and actions while reporting status: 'stopped'.
d62cdc7: A transition function that returns a promise now throws a descriptive execution error (recoverable with a state onError) instead of leaving the actor unchanged with an internal error. The returned promise's rejection is observed, so no unhandled rejection is reported. Calling enq.* after the transition function returned now throws in development and does nothing in production.
6b1a631: Machine snapshots keep their machine-specific methods, such as snapshot.matches(...), when initialization fails (for example, when the contex
snapshot.matches(...), when initialization fails (for example, when the context factory throws).69b6663: Stop child actors and their timers and subscriptions when an unhandled parent error occurs, including when a stop action has not executed yet
69b6663: Stop child actors and their timers and subscriptions when an unhandled parent error occurs, including when a stop action has not executed yet.
Keep useActorRef observers subscribed when the actor is replaced, and subscribe before the replacement starts.
69b6663: Support state names and effect keys such as __proto__, constructor, and toString, including persisted effect restoration. Run every attachment cleanup when an earlier cleanup throws, while preserving the original error.
69b6663: Fix published TypeScript declarations so applications can check XState with skipLibCheck: false.
69b6663: Restore callback subscriptions and active keyed effects. Retry interrupted local async steps while reusing completed outcomes and sharing concurrent same-key work. Pending step callers reject when their actor terminates. Interrupted external side effects require idempotency keys.
Keep SCXML condition errors and transition evaluation isolated between actors, and process condition errors without waiting for state entry.
Replay finite graph event sequences without exploring every reachable state, initialize graph traversal once, and support arbitrary serialized state and event keys. Improve adjacency traversal for large graphs. Keep simulated clocks usable after a timer callback throws.
69b6663: Events declared in schemas.internalEvents are now excluded from actor.send and actor.trigger in the published type declarations, matching the behavior already available when building against source. Both exact keys and wildcard keys are excluded.
const uploadMachine = setup({
schemas: {
events: { start: types<{}>() },
internalEvents: {
tick: types<{}>(),
'progress.*': types<{ bytes: number }>()
}
}
}).createMachine({
/* ... */
});
const actor = createActor(uploadMachine);
actor.send({ type: 'start' }); // ok
actor.send({ type: 'tick' }); // type error
actor.send({ type: 'progress.chunk', bytes: 256 }); // type error
actor.trigger.tick(); // type error: `tick` is not on `trigger`
69b6663: A persisted snapshot's children is now typed, so reading a persisted child no longer needs a cast. The new PersistedActorRef type describes both forms: an embedded child carries its own snapshot, while a child persisted by address carries remote: true and leaves its state with the runtime that owns it.
const persisted = actor.getPersistedSnapshot({ embedChildren: false });
persisted.children.auditor.address; // string | undefined
persisted.children.auditor.src; // string
69b6663: A leftover v5 types key in a machine config is now a compile error instead of being accepted and silently ignored. The error names the replacement:
createMachine({
// Error: `types` was replaced by `schemas` in v6. Declare `context`,
// `events` and the other contracts under `schemas`, or run
// `xstate-codemod migrate --transform types-to-schemas`.
types: {} as { context: { count: number } },
context: { count: 0 }
});
Declare the contracts under schemas instead:
createMachine({
schemas: { context: types<{ count: number }>() },
context: { count: 0 }
});
a50ea84: Machine output is now inferred as the union of the top-level final states' output types when no schemas.output or root output is declared. Pr
a50ea84: Machine output is now inferred as the union of the top-level final states' output types when no schemas.output or root output is declared. Previously, declaring schemas.output was required to get a typed result from toPromise(actor) or snapshot.output.
const machine = setup({}).createMachine({
initial: 'working',
states: {
working: {
on: {
resolve: { target: 'succeeded' },
reject: { target: 'failed' }
}
},
succeeded: {
type: 'final',
output: () => ({ status: 'ok' as const })
},
failed: {
type: 'final',
output: { status: 'error' as const }
}
}
});
// OutputFrom<typeof machine> is
// { status: 'ok' } | { status: 'error' }
98160ed: Importing only xstate/fsm now typechecks on its own. Previously, an fsm-only program failed with Property 'observable' does not exist on type 'SymbolConstructor' errors because the Symbol.observable type augmentation lived in the main entry. The xstate/fsm entry also no longer pulls the main entry's full type surface into the program, so editors and tsc check far less code for fsm-only consumers.
50184a8: Fixed declaration emit for machines and setups created with setup({ states }). A package that exported one could not be built with declaratio
50184a8: Fixed declaration emit for machines and setups created with setup({ states }).
A package that exported one could not be built with declaration: true: the
emitted types reached for ActiveStateContext and a handful of private marker
types that were never exported from the package entry point, so consumers saw
TS2742 ("cannot be named without a reference to xstate/dist/...") or TS4023 on
xstate's internal unique symbols.
The types declaration emit needs are now public — ActiveStateContext,
RootContextMarker, ChoiceStateNodeConfig, RegularStateNodeConfig, and the
strict-target markers — and the private state-schema symbols live behind named
marker types instead of inline computed keys, so emit references a name rather
than expanding a symbol it cannot write down.
f7642bf: Fixed generic type helpers that accidentally restricted invocation transition metadata, state input, and transition children. AnyInvokeDefini
AnyInvokeDefinition, AnyStateNodeConfig, and AnyTransitionConfigFunction now preserve arbitrary types in these positions when inspecting or accepting configurations from different machines.dcc21df: Route rejected promises returned from custom actions to the actor's error handling, so a state's onError catches a failed async action instea
dcc21df: Route rejected promises returned from custom actions to the actor's error handling, so a state's onError catches a failed async action instead of leaving an unhandled rejection. A rejection that was previously ignored now errors the actor when no onError handles it.
const machine = createMachine({
initial: 'active',
states: {
active: {
on: {
SAVE: (_, enq) => {
enq(() => saveToServer()); // returns a Promise
}
},
onError: { target: 'failed' }
},
failed: {}
}
});
Add the ErrorFrom type helper. invoke.onError events are typed from the invoked actor's error type when the actor logic declares one.
Add an optional passive flag to Observer. A passive observer only tracks the actor's lifecycle and does not count as an error handler, so an unhandled actor error is still reported when every observer with an error callback is passive.
An unhandled actor error is now reported one macrotask later than before, and a subscriber with an error callback that attaches in that window takes the error instead. Tests that advance fake timers by a single tick to observe the report need one more tick.
8b0d3e7: State and transition metadata can now use separate schemas:
8b0d3e7: State and transition metadata can now use separate schemas:
const machine = createMachine({
schemas: {
meta: z.object({ label: z.string() }),
transitionMeta: z.object({ trackingId: z.number() })
},
meta: { label: 'Root' },
on: {
NEXT: { meta: { trackingId: 42 } }
}
});
When transitionMeta is omitted, schemas.meta continues to apply its type to
both state and transition metadata.
384e5d6: actor.getPersistedSnapshot() is now assignable to PersistedSnapshotFrom<typeof machine>, so persisted snapshots can be annotated with the public type instead of ReturnType<Actor<typeof machine>['getPersistedSnapshot']>:
import { createActor, type PersistedSnapshotFrom } from 'xstate';
const snapshot: PersistedSnapshotFrom<typeof machine> =
createActor(machine).getPersistedSnapshot();
snapshot.context; // typed from the machine
Event executors passed to path.test() from xstate/graph now receive the full event, payload included, instead of just { type }:
await path.test({
events: {
// `event.card` used to require an `Extract<...>` cast
pay: ({ event }) => ui.pay(event.card)
}
});
cd98aed: Preserve a state's existing input when a transition targets that state without reentering it. Reentering transitions continue to replace the state input.
2044d05: Send events to statically declared children by id. Events are checked against
the actor-ref protocol declared in schemas.children.
createMachine({
schemas: {
children: {
worker: types<ActorRefFromLogic<typeof workerLogic>>()
}
},
on: {
notify: (_, enq) => {
enq.sendTo('worker', { type: 'notify' });
}
}
});
010298e: Named guards are now plain predicate functions. A guard receives only the arguments you pass it — the transition args object is no longer inj
010298e: Named guards are now plain predicate functions. A guard receives only the arguments you pass it — the transition args object is no longer injected first. Pass values from context or the event explicitly:
const machine = createMachine({
context: { count: 0 },
guards: {
// Previously: isAbove: (args, threshold) => args.context.count > threshold
isAbove: (count: number, threshold: number) => count > threshold,
isEnabled: () => true
},
initial: 'a',
states: {
a: {
on: {
NEXT: ({ context, guards }) => {
if (guards.isAbove(context.count, 3) && guards.isEnabled()) {
return { target: 'b' };
}
}
}
},
b: {}
}
});
Exception: guards referenced declaratively from serialized JSON or SCXML machines (guard: { type, params }) are invoked by the runtime and still receive the transition args object first, then params — the runtime is the caller there and has nothing else to pass.
c405428: Fixed framework adapter snapshot inference in projects that enable exactOptionalPropertyTypes.
const actor = createActor(machine);
const count = useSelector(actor, (snapshot) => snapshot.context.count);
069aadf: Fixed delayed transitions and other built-in effects in minified bundles, preserved hook-owned actors across React StrictMode effect reconnec
29dae8c: Improve setup(...) state contracts with typed structural metadata, recursive state input requirements for composite and parallel entry, histo
29dae8c: Improve setup(...) state contracts with typed structural metadata, recursive
state input requirements for composite and parallel entry, history-default
validation, strongly typed relative targets, and shared input requirements for
literal target sets.
b44d9cb: State-level context schemas now refine the root context schema instead of
replacing it. Declare only the fields narrowed by a state while retaining all
root context fields in state actions, transitions, and narrowed snapshots.
Nested states retain active ancestor refinements, and xstate/fsm uses the
same refinement semantics.
const machine = setup({
schemas: {
context: z.object({
requestId: z.string(),
draft: z.string().optional()
})
},
states: {
reviewing: {
schemas: { context: z.object({ draft: z.string() }) }
}
}
}).createMachine({
context: { requestId: 'req-1' },
// ...
});
7f9fc4f: Invalid external events are now rejected at the delivery boundary instead of erroring the actor or throwing. This covers events whose payload
7f9fc4f: Invalid external events are now rejected at the delivery boundary instead of erroring the actor or throwing. This covers events whose payload fails a declared runtime validator schema and internal event types (internalEvents) sent from outside their owning actor. A rejected event is never delivered: the actor does not transition, does not error, and no API throws.
Rejections are reported through:
onRejectedEvent dead-letter hook on createActor(...) options, which receives an EventRejection describing the event, target, source, origin, reason and validation issues;@xstate.deadletter inspection event, which now also carries the validation issues and underlying error for boundary rejections;const actor = createActor(machine, {
onRejectedEvent: (rejection) => {
console.log(rejection.event, rejection.reason, rejection.issues);
}
});
Pure transition(...) calls no longer throw for invalid external events: the snapshot is returned unchanged with a @xstate.deadLetter effect carrying the rejection, so durable hosts can journal rejections and replay stays total even with poisoned queued events. The effect executes through the deadLetter runtime operation, so createDurable(...) adapters journal rejections by implementing deadLetter like any other runtime operation.
Internal faults are unchanged: values the machine produces itself (input, context, output, emitted events and delayed raised events) that fail their schema still error the actor, and pure transitions still throw for them.
501c5e3: Add the self-contained xstate/fsm entry point for compact flat finite state machines. It exports createFSM and createFSMActor without includi
501c5e3: Add the self-contained xstate/fsm entry point for compact flat finite state
machines. It exports createFSM and createFSMActor without including the full
statechart actor runtime.
import { createFSM, createFSMActor } from 'xstate/fsm';
const logic = createFSM({
initial: 'inactive',
states: {
inactive: { on: { toggle: { target: 'active' } } },
active: { on: { toggle: { target: 'inactive' } } }
}
});
const actor = createFSMActor(logic).start();
The FSM runtime also supports guarded transitions, context, actions, eventless transitions, final states, child actors, delayed events, and snapshot persistence for state, context, and self-directed timers. Live inline children and timers targeting other actors are rejected at the persistence boundary because the compact runtime has no registered actor-source registry.
7601447: Add createMachineFromSCXML(...) through the xstate/scxml entry point. Converted machines follow strict SCXML behavior for transition selectio
7601447: Add createMachineFromSCXML(...) through the xstate/scxml entry point. Converted machines follow strict SCXML behavior for transition selection, executable content, datamodel evaluation, invocation, event metadata, and completion.
import { createMachineFromSCXML } from 'xstate/scxml';
const machine = createMachineFromSCXML(scxml);
72938f8: Guard and delay source functions are now contextually typed from schemas — in setup({ ... }), .extend({ ... }), and createMachine({ ... }) —
72938f8: Guard and delay source functions are now contextually typed from schemas — in setup({ ... }), .extend({ ... }), and createMachine({ ... }) — so inline functions get typed context and event without hand annotations:
const s = setup({
schemas: {
context: z.object({ count: z.number() }),
events: { INC: z.object({ by: z.number() }) }
},
guards: {
// context: { count: number }, event: { type: 'INC'; by: number }
isPositive: ({ context }) => context.count > 0,
// additional params after the args object are free-form
isAbove: ({ context }, threshold: number) => context.count > threshold
},
delays: {
backoff: ({ context }) => context.count * 100
}
});
Guard sources receive the transition args object first ({ context, event, self, parent, value, children }), followed by any caller-supplied params — matching how the runtime invokes referenced guards. Delay sources receive { context, event, stateNode }.
Additionally, enq.stop(...), enq.listen(...), and enq.subscribeTo(...) now accept any ActorRef (such as values typed with ActorRefFrom<typeof machine>), instead of requiring the full actor instance type returned by enq.spawn(...).
6ecc2df: Document durable timer semantics for event-journal hosts.
fc7454f: Restoring an externally migrated live snapshot now treats its machine property as a runtime association rather than persisted version metadata. Persisted snapshots continue validating their nested { id, version } identity and legacy top-level version together.
getNextTransitions(snapshot) returns an empty array for completed or errored snapshots.
Setup-created machines whose input schema accepts undefined no longer require a meaningless input property when other actor options are provided, including after machine.provide(...).
Durable adapters can implement enqueueRootEvent when the host owns only the execution root's mailbox, without overriding delivery for co-located actors:
const durable = createDurable(machine, {
enqueueRootEvent: (_source, event) => host.enqueue(event),
executeAction,
waitForEvent
});
Implement sendEvent only when the host owns routing for every target; use deliverEvent for co-located delivery. Durable replay guidance now explicitly covers inline entry and exit callbacks.
30eb784: Transition spawning accepts typed registered actor names so durable source identity can be explicit:
30eb784: Transition spawning accepts typed registered actor names so durable source identity can be explicit:
const machine = createMachine({
actors: { worker },
on: {
start: (_, enq) => {
enq.spawn('worker', { id: 'worker' });
}
}
});
The name determines required input and the returned actor reference type. It is resolved immediately and persisted exactly, so duplicate names may share one logic value and later diverge safely. Logic-value spawning remains supported and uses the first matching registered key; unregistered inline children cannot be persisted.
e0dc812: Durable execution DX improvements:
e0dc812: Durable execution DX improvements:
The drive loop no longer routes root events by hand. executeEffects retains the root-addressed events it captures, and execution.waitForEvent() hands them out before deferring to the adapter, so the canonical loop is:
let [state, effects] = execution.initialTransition(input);
await execution.executeEffects(effects);
while (state.status === 'active') {
[state, effects] = execution.transition(state, await execution.waitForEvent());
await execution.executeEffects(effects);
}
(executeEffects now resolves with void.)
createDurable(logic, adapter, { inspect }) observes the execution's inspection events (@xstate.actor / @xstate.transition) across the whole live actor tree, including transitions computed by the pure path — the host-side home for operation logs and instrumentation.
execution.getActorRef(snapshot, address) resolves a logical address against the snapshot's live actor tree, for hosts whose durable mailbox stores addresses as strings.
Machine output types infer from the config's output function when no schemas.output schema is declared; a declared schema stays authoritative.
DurableSnapshot keeps the status/output/error discriminant visible when TLogic is an unresolved type parameter, and adapter waitForEvent implementations may return plain event objects — generic host libraries no longer need casts.
e0dc812: A machine's output type is now inferred from its output config when no schemas.output is declared. A declared schemas.output stays authoritative.
const machine = setup({}).createMachine({
context: { shipped: ['sku-1'] },
initial: 'done',
states: { done: { type: 'final' } },
output: ({ context }) => ({
status: 'shipped' as const,
skus: context.shipped
})
});
// OutputFrom<typeof machine> is now
// { status: 'shipped'; skus: string[] } instead of {}
7156ad5: Add setup state-local output schemas for typed final-state output and nested completion contracts.
39f8431: Durable executions can pin a deterministic identity: createDurable(machine, { executionId, ... }) makes session ids : , a deterministic funct
39f8431: Durable executions can pin a deterministic identity: createDurable(machine, { executionId, ... }) makes session ids <executionId>:<n>, a deterministic function of actor-creation order, so hosts that journal the execution's own events can replay them — a journaled completion event still matches the child a replay re-creates.
const durable = createDurable(machine, {
executionId: orderId,
executeAction,
waitForEvent
});
The new runLogic runtime operation makes the invoked async actor the primary durable unit: a developer writes a normal promise and the host journals the whole body as one entry — wrapping the provided thunk in its own step primitive, or re-running the registered logic on a remote executor from the actor's serializable (src, input) identity alone. enq.step remains for opt-in finer granularity.
runLogic: (actor, exec) => ctx.run(actor.address, exec)
A remote handle now carries its host-supplied incarnation token as its sessionId — one incarnation identity with one staleness rule (a ref that knows its incarnation compares it; one that does not defers to the owning runtime). The persisted incarnation field is unchanged.
Docs reposition enq.step as the hostless-durability tool (the snapshot is the journal; durable hosts use plain promise actors + runLogic), document the portable-action rule (named function + serializable args ships to a remote executor; closures run in-process), and add a "Driving effects yourself" section: createDurable is sugar over the pure transition() APIs, and hosts may execute the effect objects themselves.
Durable-execution docs now also cover quiescing in-flight steps before registering a durable wait, the ordered-effect replay guarantee, and that runStep's exec closure must run in-process.
14cfdc3: Actors now have deterministic, location-transparent identity.
14cfdc3: Actors now have deterministic, location-transparent identity.
address: the /-joined path of actor ids from the root. Root actors are named after their logic's id, and children spawned without an explicit id get deterministic per-parent counters keyed by their actor source (worker:0, worker:1). Addresses are stable across persistence and restore; sessionId identifies one incarnation of an address, and completions from a previous incarnation of a local child are dropped.enq.spawn(actors.x) records the registered source key so spawned children persist by key.getEffectDescriptor(effect) returns a serializable view of any executable effect, with actor references replaced by addresses and actor sources by source keys (payload fields pass through by reference).system.runtime; the built-in local runtime is the default. The new deliverEvent, stopActor and terminateActor helpers expose the local behaviors for custom runtimes to delegate to.createDurable (from xstate/durable) adapters carry their runtime operations directly (sendEvent, scheduleTimer, …), and the execution installs them on every snapshot's actor system; it exposes rootAddress and getActorRef(snapshot), tags every effect with a serializable descriptor, and executeEffects resolves only when every transitively initiated runtime operation has been accepted — returning the events addressed to the root actor for the durable loop. Breaking for existing adapters: during executeEffects, root-addressed events no longer reach any runtime sendEvent (including per-effect runtime() implementations) — drain them from the executeEffects result instead. While the loop is parked in waitForEvent, a root-addressed event reaches sendEvent like any other target, and the host should enqueue it in its own mailbox. Runtime objects are also wrapped before effects see them, so identity comparisons and extra non-runtime properties on the returned object are not preserved.getPersistedSnapshot(snapshot, { embedChildren: false }) persists children by logical address, leaving each child's state with the runtime that owns it; restoring an address-only child produces a location-transparent handle whose sends route through the system runtime.deadLetter runtime operation and a @xstate.deadletter inspection event. Delivery stays at-most-once — this is observability, not retry.incarnation token. XState never stamps one, but when a host does, completions from a different incarnation of the address are dropped and sendTo effect descriptors journal the target's token.createDurable exposes machineId and machineVersion so hosts can pin an execution's journal to the machine version that produced it.enq.step) route through the new runStep runtime operation. The built-in behavior memoizes results in the actor's own snapshot as before; a durable host implements runStep to own the step journal, replaying memoized results without re-running the step. The runStep helper export exposes the built-in behavior.Actor.toJSON, persisted context refs) carry xstate$type: 'actorRef' instead of the v5 xstate$$type: 1 marker. Migrate v5-persisted context refs with machineVersions if you restore them.startedAt); restoring the snapshot schedules the remaining time toward the original deadline (clamped to the declared delay), so a timer past due fires immediately instead of restarting its full delay. Pure-transition snapshots carry no timestamp and restart the declared delay.const durable = createDurable(machine, {
sendEvent: (source, target, event) =>
host.send(source?.address, target.address, event),
executeAction: (action, { id }, runtime) =>
host.runAction(id, () => action.exec(runtime)),
waitForEvent: ({ id }) => host.waitForEvent(id)
});
107d0c2: Represent historical machine versions with Standard Schema snapshot and event descriptors instead of retaining their executable machines. Ver
107d0c2: Represent historical machine versions with Standard Schema snapshot and event
descriptors instead of retaining their executable machines. Versioned machines
expose the same snapshotSchema and eventSchema interface. Machine-backed
snapshot schemas default omitted history and timer records during migration.
const versions = machineVersions([
{
id: 'checkout',
version: '1',
snapshotSchema: checkoutV1Snapshot,
eventSchema: checkoutV1Event
},
checkoutV2
]);
const snapshot = await versions.migrateSnapshot(persisted, {
to: '2',
migrations: {
'1': (snapshot) => ({
...snapshot,
context: { total: snapshot.context.count }
})
}
});
2e77ff6: actor.getPersistedSnapshot() is now typed to the actor’s logic, so persist/restore round-trips through createActor(logic, { snapshot }) no longer require a cast. Restoring a snapshot into a machine with a different id is a type error, while snapshots from other versions of the same machine remain assignable (for runtime migration via migrate).
const actor = createActor(machine).start();
const snapshot = actor.getPersistedSnapshot();
// No cast needed:
const restored = createActor(machine, { snapshot }).start();
7a7e564: Fixed a bug where enq.subscribeTo(…) and enq.listen(…) silently did nothing when called inside a transition function. They now work the same
7a7e564: Fixed a bug where enq.subscribeTo(…) and enq.listen(…) silently did nothing when called inside a transition function. They now work the same as in entry actions:
const machine = createMachine({
on: {
start: (_, enq) => {
const child = enq.spawn(childLogic);
enq.subscribeTo(child, {
done: (output) => ({ type: 'childDone', output })
});
},
childDone: ({ event }) => {
// event.output is the child's output
}
}
});
4e6dbfd: Named imports from the root xstate entry (such as the actor logic creators and SpecialTargets) now work in all environments, including tools that load the package as CommonJS.
import { createAsyncLogic } from 'xstate'; // now works everywhere
20a52b9: Optional event payload fields declared with types() are now preserved instead of being made required:
const machine = setup({
schemas: {
events: {
submit: types<{ email: string; referrer?: string }>()
}
}
}).createMachine({
// ...
});
// referrer can now be omitted
actor.send({ type: 'submit', email: 'a@b.co' });
Payloads inferred from validator libraries (e.g. Zod) are still wrapped in Required<>.
20a52b9: snapshot.value is now structurally typed from the machine config instead of the generic StateValue type. Flat machines get a union of state keys, and parallel machines get an object type with a key per region:
const machine = createMachine({
type: 'parallel',
states: {
bold: { initial: 'off', states: { off: {}, on: {} } },
italic: { initial: 'off', states: { off: {}, on: {} } }
}
});
const value = createActor(machine).getSnapshot().value;
// { bold: 'off' | 'on'; italic: 'off' | 'on' }
90a173a: Fixed createSystem(...).setup(...) to preserve runtime validator types alongside typed actor registries. Validated setups now reject unsupported transforming schemas and carry validation into derived setups.
Runtime validation can now also be installed on a derived setup when its inherited schemas are compatible:
import { setup } from 'xstate';
import { standardSchemaValidator } from 'xstate/validation';
import { z } from 'zod';
const validated = setup({
schemas: { input: z.object({ id: z.string() }) }
}).extend({ validator: standardSchemaValidator() });
8aaac46: Restoring a persisted snapshot whose state value references a state that no longer exists on the machine now throws a descriptive error, e.g.
8aaac46: Restoring a persisted snapshot whose state value references a state that no longer exists on the machine now throws a descriptive error, e.g.:
Persisted snapshot references state 'reviewing' which does not exist on machine 'order-approval'.
Nested state values report the full state path (e.g. 'active.reviewing'), and parallel state regions are validated as well.
86f7303: Add an experimental, host-neutral durable execution helper at xstate/durable. It assigns stable IDs to effects and event waits from pure tran
86f7303: Add an experimental, host-neutral durable execution helper at xstate/durable.
It assigns stable IDs to effects and event waits from pure transitions while
leaving durable execution, timers, messaging and child actors to the host.
Hosts can read nextTransitionIndex after every transition for checkpointing.
const durable = createDurable(machine, adapter);
const output = await durable.run(input);
86f7303: Add experimental durable execution adapters for Inngest and Rivet workflows. Host runtime mappings now receive the complete built-in effect, allowing them to map timers, sends and child actors without coupling XState to either host.
import { createDurable } from '@xstate/inngest';
const output = await createDurable(machine, options).run(input);
6df07b8: Fixed invoke.onDone transition argument inference when actor logic is passed directly as src in a machine with two or more differently-typed registered actors. Previously, the transition function's arguments collapsed to any (event.output was unusable without annotations); now event.output is inferred from the invoked actor's output type.
const fetchUser = createAsyncLogic({ run: async () => ({ name: 'David' }) });
const fetchCount = createAsyncLogic({ run: async () => 42 });
setup({
actors: { fetchUser, fetchCount }
}).createMachine({
initial: 'loading',
states: {
loading: {
invoke: {
src: fetchUser,
onDone: ({ event }) => {
event.output.name; // string
return { target: 'done' };
}
}
},
done: {}
}
});
Note: when actors are registered, invoking unregistered inline logic now only supports the object/target forms of onDone (not the transition function form). Register the actor to get fully-typed function-form transitions.
af31f22: Add machineVersions().adaptEvents() for adapting complete event histories between machine versions. Exact retained-version adapters infer sou
af31f22: Add machineVersions().adaptEvents() for adapting complete event histories
between machine versions. Exact retained-version adapters infer source and
target event types, while an async '*' adapter can handle unknown histories.
const events = await versions.adaptEvents(storedEvents, {
from: { id: 'checkout', version: '1' },
to: '2',
adapters: {
'1': (events) => events.map(toV2Event)
}
});
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
e410f24: Add state-level onError transitions for handling xstate.error.* events.
e410f24: Add state-level onError transitions for handling xstate.error.* events.
State onError catches actor, execution, and communication errors while the state is active. The caught error is available on event.error.
const machine = createMachine({
initial: 'active',
states: {
active: {
onError: ({ event }) => ({
target: 'failed',
context: {
message:
event.error instanceof Error
? event.error.message
: String(event.error)
}
})
},
failed: {}
}
});
f6edec7: Allow machines with no external events to be used anywhere AnyActorLogic or AnyStateMachine is expected.
const machine = setup({
schemas: {
events: {}
}
}).createMachine({});
const logic: AnyActorLogic = machine;
const anyMachine: AnyStateMachine = machine;
Machines with empty event schemas still reject external events sent to their actors.
37d3254: Setup-bound invoke transition callbacks now validate target state context requirements for onDone, onError, onSnapshot, and onTimeout. onDone
37d3254: Setup-bound invoke transition callbacks now validate target state context requirements for onDone, onError, onSnapshot, and onTimeout. onDone also infers output from the invoked actor logic.
import { createAsyncLogic, setup } from 'xstate';
import { z } from 'zod';
const machine = setup({
actorSources: {
loadUser: createAsyncLogic({
run: async () => ({ name: 'Ada' })
})
},
states: {
loading: {},
success: {
schemas: {
context: z.object({
user: z.object({ name: z.string() })
})
}
}
}
}).createMachine({
context: {},
initial: 'loading',
states: {
loading: {
invoke: {
src: 'loadUser',
// Type-safe return value for invoke callbacks
onDone: ({ event }) => ({
target: 'success',
context: { user: event.output }
})
}
},
success: {}
}
});
c0c21d0: Add a path-bound overload to setup(...).createStateConfig(path, config).
c0c21d0: Add a path-bound overload to setup(...).createStateConfig(path, config).
When a state declares its own input schema, the anonymous createStateConfig(config) form types input as a broad union across all states. This makes the resulting config incompatible with the specific state it's meant for — assigning it inside createMachine produces a type error because the input types don't match.
The new createStateConfig(path, config) overload binds the config to a specific setup-declared state by dotted path (e.g. 'loading' or 'parent.child'). The addressed state's own input schema is used inside entry/exit args, and bare transition targets are validated against the state's siblings.
const s = setup({
states: {
idle: {},
active: {
schemas: { input: z.object({ userId: z.string() }) }
}
}
});
// Before: anonymous form — `input` is typed broadly, and assigning this
// config to the `active` state in createMachine fails with a type error.
const active = s.createStateConfig({
entry: ({ input }) => {
// input is not narrowed to { userId: string }
}
});
// After: path-bound form — `input` is narrowed to `active`'s own schema.
const active = s.createStateConfig('active', {
entry: ({ input }) => {
input.userId; // string
}
});
// Works for nested states too:
const child = s.createStateConfig('parent.child', { ... });
8e3cce6: Fix snapshot.matches(...) narrowing so repeated checks like snapshot.matches('loaded') || snapshot.matches('failed') compile correctly, and make StateFrom<typeof machine> preserve the machine's concrete state value.
0c2a6e5: Fix function-syntax transitions not passing input to target state entry actions.
on: {
FETCH: ({ context, event }) => ({
target: 'fetching',
input: { url: event.url, token: context.authToken }
});
}
Previously, input returned from function-syntax transitions was silently ignored. Now it is correctly forwarded to the target state's entry action.
bdc54dd: Added createFSM(...) for flat, actor-compatible finite state machines.
bdc54dd: Added createFSM(...) for flat, actor-compatible finite state machines.
import { createActor, createFSM } from 'xstate';
const toggleLogic = createFSM({
initial: 'inactive',
context: { count: 0 },
states: {
inactive: {
on: {
toggle: {
target: 'active',
context: { count: 1 }
}
}
},
active: {
on: {
toggle: ({ context }, enq) => {
enq(() => console.log('toggled'));
return {
target: 'inactive',
context: { count: context.count + 1 }
};
}
}
}
}
});
const actor = createActor(toggleLogic).start();
actor.send({ type: 'toggle' });
createFSM(...) supports XState-style object transitions, function transitions, enq actions, initial input, state input, entry actions, and exit actions. Plain string targets are intentionally not supported; use object targets such as { target: 'active' }.
Simple FSM transitions preserve immutable public snapshots while using structural sharing and a lighter transition path for common { target }, { context }, and { target, context } transitions.
e297115: Object transition configs now support dynamic context patches with a context mapper.
onDone: {
target: 'done',
context: ({ context, output }) => ({
answer: output,
memory: [...context.memory, output]
})
}
4d9ba1c: Spawning a child with enq.spawn(...) from a transition function now creates and starts the child actor exactly once for the committed transit
4d9ba1c: Spawning a child with enq.spawn(...) from a transition function now creates and starts the child actor exactly once for the committed transition.
const machine = createMachine({
on: {
spawn: (_, enq) => {
enq.spawn(childMachine, { registryKey: 'child' });
}
}
});
6798cb1: serializeMachine(...) and createMachineFromConfig(...) now represent inline functions (guards, actions, transitions, delays, route functions) as { '@code': string, '@lang': 'ts' }. Non-portable values such as actor logic, runtime schemas, class instances, symbols, and bigints are omitted from the serialized JSON.
import { serializeMachine } from 'xstate';
serializeMachine(machine);
// inline functions → { '@code': '() => true', '@lang': 'ts' }
Type-only refinements: void and undefined are accepted as type-only schemas, async logic output is inferred from an input-only schema, actions/guards can be typed via schemas, and trigger is correctly typed on spawned actors.
57e8d85: Machines that declare schemas.output now type-check top-level final state output values against the machine output type.
57e8d85: Machines that declare schemas.output now type-check top-level final state
output values against the machine output type.
createMachine({
schemas: {
output: types<{ status: 'ok' }>()
},
initial: 'done',
states: {
done: {
type: 'final',
output: { status: 'ok' }
}
},
output: ({ event }) => event.output
});
One column per quarter.