xstate 6.0.0-alpha.8 → 6.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +223 -78
- package/bin/agent.js +347 -0
- package/bin/xstate.js +52 -0
- package/dist/createActor-25900f76.cjs.js +7015 -0
- package/dist/createActor-551369be.development.esm.js +7175 -0
- package/dist/createActor-a49ae0ce.development.cjs.js +7289 -0
- package/dist/createActor-cbe3abac.esm.js +6902 -0
- package/dist/declarations/src/SimulatedClock.d.ts +2 -1
- package/dist/declarations/src/State.d.ts +66 -5
- package/dist/declarations/src/StateMachine.d.ts +107 -32
- package/dist/declarations/src/StateNode.d.ts +21 -16
- package/dist/declarations/src/actions.d.ts +11 -6
- package/dist/declarations/src/actors/callback.d.ts +11 -2
- package/dist/declarations/src/actors/index.d.ts +6 -5
- package/dist/declarations/src/actors/listener.d.ts +8 -3
- package/dist/declarations/src/actors/logic.d.ts +42 -52
- package/dist/declarations/src/actors/observable.d.ts +15 -2
- package/dist/declarations/src/actors/promise.d.ts +90 -22
- package/dist/declarations/src/actors/subscription.d.ts +9 -3
- package/dist/declarations/src/assert.d.ts +1 -0
- package/dist/declarations/src/base.types.d.ts +102 -0
- package/dist/declarations/src/createActor.d.ts +101 -27
- package/dist/declarations/src/createMachine.d.ts +38 -17
- package/dist/declarations/src/delay.d.ts +8 -0
- package/dist/declarations/src/durable/index.d.ts +231 -0
- package/dist/declarations/src/effectDescriptor.d.ts +95 -0
- package/dist/declarations/src/eventTypes.d.ts +9 -0
- package/dist/declarations/src/fsm/index.d.ts +2 -0
- package/dist/declarations/src/fsm.d.ts +169 -0
- package/dist/declarations/src/graph/adjacency.d.ts +6 -3
- package/dist/declarations/src/graph/graph.d.ts +6 -3
- package/dist/declarations/src/graph/index.d.ts +2 -3
- package/dist/declarations/src/graph/pathFromEvents.d.ts +5 -2
- package/dist/declarations/src/graph/shortestPaths.d.ts +5 -3
- package/dist/declarations/src/graph/simplePaths.d.ts +5 -3
- package/dist/declarations/src/graph/types.d.ts +113 -59
- package/dist/declarations/src/hotSwap.d.ts +18 -0
- package/dist/declarations/src/index.d.ts +28 -19
- package/dist/declarations/src/inspection.d.ts +24 -1
- package/dist/declarations/src/machineFromJSON.d.ts +171 -0
- package/dist/declarations/src/machineSchemas.d.ts +27 -0
- package/dist/declarations/src/machineVersion.types.d.ts +53 -0
- package/dist/declarations/src/machineVersions.d.ts +103 -0
- package/dist/declarations/src/mapState.d.ts +2 -0
- package/dist/declarations/src/persist/index.d.ts +36 -0
- package/dist/declarations/src/persistedSnapshotValidation.d.ts +18 -0
- package/dist/declarations/src/runtimeHelpers.d.ts +43 -0
- package/dist/declarations/src/schema.types.d.ts +31 -4
- package/dist/declarations/src/serialize.d.ts +39 -28
- package/dist/declarations/src/setup.d.ts +1086 -147
- package/dist/declarations/src/spawn.d.ts +6 -4
- package/dist/declarations/src/stateUtils.d.ts +57 -14
- package/dist/declarations/src/system.d.ts +178 -17
- package/dist/declarations/src/systemTransition.d.ts +108 -0
- package/dist/declarations/src/toPromise.d.ts +1 -0
- package/dist/declarations/src/transition.d.ts +48 -10
- package/dist/declarations/src/transitionActions.d.ts +22 -4
- package/dist/declarations/src/typeUtils.d.ts +51 -0
- package/dist/declarations/src/types.d.ts +835 -318
- package/dist/declarations/src/types.v6.d.ts +547 -104
- package/dist/declarations/src/utils.d.ts +38 -8
- package/dist/declarations/src/validation/index.d.ts +49 -0
- package/dist/declarations/src/validation.types.d.ts +29 -0
- package/dist/declarations/src/waitFor.d.ts +1 -0
- package/dist/effectDescriptor-2fa27c54.cjs.js +351 -0
- package/dist/effectDescriptor-321a8ce9.development.esm.js +343 -0
- package/dist/effectDescriptor-d8b0f749.esm.js +343 -0
- package/dist/effectDescriptor-f73da4ec.development.cjs.js +351 -0
- package/dist/machineSchemas-45c21bc2.esm.js +1292 -0
- package/dist/machineSchemas-6d96bef4.development.cjs.js +1379 -0
- package/dist/machineSchemas-88d01821.cjs.js +1300 -0
- package/dist/machineSchemas-b5736804.development.esm.js +1371 -0
- package/dist/schema.types-0ecd17b8.esm.js +71 -0
- package/dist/schema.types-15a68ddc.cjs.js +74 -0
- package/dist/schema.types-1c16f035.development.cjs.js +74 -0
- package/dist/schema.types-1cd4652e.development.esm.js +71 -0
- package/dist/validation-05f1d517.esm.js +8 -0
- package/dist/validation-4561b43c.cjs.js +10 -0
- package/dist/validation-e69470ad.development.esm.js +8 -0
- package/dist/validation-f2714a35.development.cjs.js +10 -0
- package/dist/xstate-actors.cjs.js +1068 -12
- package/dist/xstate-actors.cjs.mjs +2 -4
- package/dist/xstate-actors.development.cjs.js +1068 -12
- package/dist/xstate-actors.development.cjs.mjs +2 -4
- package/dist/xstate-actors.development.esm.js +1064 -1
- package/dist/xstate-actors.esm.js +1064 -1
- package/dist/xstate-actors.umd.min.js +1 -1
- package/dist/xstate-actors.umd.min.js.map +1 -1
- package/dist/xstate-durable.cjs.d.mts +2 -0
- package/dist/xstate-durable.cjs.d.ts +2 -0
- package/dist/xstate-durable.cjs.js +513 -0
- package/dist/xstate-durable.cjs.mjs +5 -0
- package/dist/xstate-durable.development.cjs.js +513 -0
- package/dist/xstate-durable.development.cjs.mjs +5 -0
- package/dist/xstate-durable.development.esm.js +507 -0
- package/dist/xstate-durable.esm.js +507 -0
- package/dist/xstate-durable.umd.min.js +2 -0
- package/dist/xstate-durable.umd.min.js.map +1 -0
- package/dist/xstate-fsm.cjs.d.mts +2 -0
- package/dist/xstate-fsm.cjs.d.ts +2 -0
- package/dist/xstate-fsm.cjs.js +111 -0
- package/dist/xstate-fsm.cjs.mjs +5 -0
- package/dist/xstate-fsm.development.cjs.js +111 -0
- package/dist/xstate-fsm.development.cjs.mjs +5 -0
- package/dist/xstate-fsm.development.esm.js +105 -0
- package/dist/xstate-fsm.esm.js +105 -0
- package/dist/xstate-fsm.umd.min.js +2 -0
- package/dist/xstate-fsm.umd.min.js.map +1 -0
- package/dist/xstate-graph.cjs.js +173 -457
- package/dist/xstate-graph.cjs.mjs +2 -5
- package/dist/xstate-graph.development.cjs.js +173 -457
- package/dist/xstate-graph.development.cjs.mjs +2 -5
- package/dist/xstate-graph.development.esm.js +171 -451
- package/dist/xstate-graph.esm.js +171 -451
- package/dist/xstate-graph.umd.min.js +1 -1
- package/dist/xstate-graph.umd.min.js.map +1 -1
- package/dist/xstate-persist.cjs.d.mts +2 -0
- package/dist/xstate-persist.cjs.d.ts +2 -0
- package/dist/xstate-persist.cjs.js +314 -0
- package/dist/xstate-persist.cjs.mjs +6 -0
- package/dist/xstate-persist.development.cjs.js +325 -0
- package/dist/xstate-persist.development.cjs.mjs +6 -0
- package/dist/xstate-persist.development.esm.js +319 -0
- package/dist/xstate-persist.esm.js +308 -0
- package/dist/xstate-persist.umd.min.js +2 -0
- package/dist/xstate-persist.umd.min.js.map +1 -0
- package/dist/xstate-validation.cjs.d.mts +2 -0
- package/dist/xstate-validation.cjs.d.ts +2 -0
- package/dist/xstate-validation.cjs.js +330 -0
- package/dist/xstate-validation.cjs.mjs +5 -0
- package/dist/xstate-validation.development.cjs.js +330 -0
- package/dist/xstate-validation.development.cjs.mjs +5 -0
- package/dist/xstate-validation.development.esm.js +324 -0
- package/dist/xstate-validation.esm.js +324 -0
- package/dist/xstate-validation.umd.min.js +2 -0
- package/dist/xstate-validation.umd.min.js.map +1 -0
- package/dist/xstate.cjs.js +2486 -1430
- package/dist/xstate.cjs.mjs +23 -13
- package/dist/xstate.development.cjs.js +2486 -1430
- package/dist/xstate.development.cjs.mjs +23 -13
- package/dist/xstate.development.esm.js +2445 -1398
- package/dist/xstate.esm.js +2445 -1398
- package/dist/xstate.umd.min.js +1 -1
- package/dist/xstate.umd.min.js.map +1 -1
- package/docs/actions.md +75 -0
- package/docs/actor-logic.md +250 -0
- package/docs/actors.md +64 -0
- package/docs/agents.md +132 -0
- package/docs/api-stability.json +4287 -0
- package/docs/async-logic.md +75 -0
- package/docs/async-requests.md +157 -0
- package/docs/backend-workflows.md +124 -0
- package/docs/cancellation.md +42 -0
- package/docs/cheatsheet.md +563 -0
- package/docs/choice-states.md +109 -0
- package/docs/choose-xstate.md +47 -0
- package/docs/configuration.md +161 -0
- package/docs/context.md +67 -0
- package/docs/create-actor.md +159 -0
- package/docs/data-and-effects.md +48 -0
- package/docs/delays.md +81 -0
- package/docs/durable-execution.md +520 -0
- package/docs/emitted-events.md +146 -0
- package/docs/errors.md +812 -0
- package/docs/examples.md +75 -0
- package/docs/faq.md +60 -0
- package/docs/final-states.md +149 -0
- package/docs/forms-and-wizards.md +166 -0
- package/docs/frameworks.md +69 -0
- package/docs/fsm.md +164 -0
- package/docs/glossary.md +68 -0
- package/docs/guards.md +137 -0
- package/docs/history-states.md +161 -0
- package/docs/how-xstate-runs-machines.md +86 -0
- package/docs/index.md +74 -0
- package/docs/input-output.md +69 -0
- package/docs/inspect-actor-systems.md +118 -0
- package/docs/inspection.md +75 -0
- package/docs/internal-events.md +156 -0
- package/docs/invoke.md +371 -0
- package/docs/lifecycle-and-errors.md +48 -0
- package/docs/listen-and-subscribe.md +126 -0
- package/docs/model-based-testing.md +321 -0
- package/docs/modeling.md +40 -0
- package/docs/parallel-states.md +182 -0
- package/docs/persist-and-restore-actors.md +120 -0
- package/docs/persistence.md +312 -0
- package/docs/quick-start.md +55 -0
- package/docs/retries-and-timeouts.md +122 -0
- package/docs/route-states.md +104 -0
- package/docs/scxml.md +92 -0
- package/docs/selectors.md +99 -0
- package/docs/serialization.md +127 -0
- package/docs/setup-and-provide.md +273 -0
- package/docs/snapshots.md +134 -0
- package/docs/spawn.md +212 -0
- package/docs/state-input.md +162 -0
- package/docs/statecharts.md +54 -0
- package/docs/states-events-transitions.md +82 -0
- package/docs/states.md +168 -0
- package/docs/system-transitions.md +172 -0
- package/docs/systems.md +166 -0
- package/docs/testing.md +152 -0
- package/docs/timeouts.md +125 -0
- package/docs/transition-functions.md +89 -0
- package/docs/transitions.md +187 -0
- package/docs/troubleshooting.md +56 -0
- package/docs/tutorial.md +481 -0
- package/docs/typescript.md +213 -0
- package/docs/typestates.md +112 -0
- package/docs/utilities.md +39 -0
- package/docs/why-state-machines.md +59 -0
- package/docs/xstate-v5-to-v6.md +1923 -0
- package/docs/your-first-machine.md +79 -0
- package/durable/package.json +8 -0
- package/fsm/package.json +8 -0
- package/package.json +72 -10
- package/persist/package.json +8 -0
- package/validation/package.json +8 -0
- package/actions/package.json +0 -8
- package/dev/package.json +0 -8
- package/dist/StateMachine-0aa98f54.development.esm.js +0 -746
- package/dist/StateMachine-aef700df.cjs.js +0 -732
- package/dist/StateMachine-d4931336.esm.js +0 -729
- package/dist/StateMachine-da872dde.development.cjs.js +0 -749
- package/dist/declarations/src/createMachineFromConfig.d.ts +0 -177
- package/dist/declarations/src/getNextSnapshot.d.ts +0 -37
- package/dist/declarations/src/graph/TestModel.d.ts +0 -70
- package/dist/declarations/src/graph/pathGenerators.d.ts +0 -4
- package/dist/index-219cb621.development.cjs.js +0 -4476
- package/dist/index-2f2fbd9b.development.esm.js +0 -4421
- package/dist/index-559ceab3.cjs.js +0 -4437
- package/dist/index-8828376f.esm.js +0 -4382
- package/guards/package.json +0 -8
- package/invoke/package.json +0 -4
package/docs/tutorial.md
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: 'Tutorial: build a media player'
|
|
3
|
+
description: Grow one machine from three states into a full media player with context, guards, async loading, statecharts, timers, emitted events and a UI.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
In this tutorial you build one machine, part by part. Each part adds a single concept, ends with code you can run, and lists the expected output.
|
|
7
|
+
|
|
8
|
+
Start from [your first machine](your-first-machine.md), which introduced states, transitions and actors. Everything after Part 1 is new.
|
|
9
|
+
|
|
10
|
+
You need a TypeScript project with `xstate` and `zod` installed. Run each part with `tsx`, `vite-node`, or another runner. Parts 3 to 6 show only what changes; Part 7 lists the complete machine.
|
|
11
|
+
|
|
12
|
+
## Part 1: States and transitions
|
|
13
|
+
|
|
14
|
+
A media player is stopped, playing, or paused. Events move it between them.
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { createActor, createMachine } from 'xstate';
|
|
18
|
+
|
|
19
|
+
const playerMachine = createMachine({
|
|
20
|
+
initial: 'stopped',
|
|
21
|
+
states: {
|
|
22
|
+
stopped: { on: { play: { target: 'playing' } } },
|
|
23
|
+
playing: {
|
|
24
|
+
on: { pause: { target: 'paused' }, stop: { target: 'stopped' } }
|
|
25
|
+
},
|
|
26
|
+
paused: {
|
|
27
|
+
on: { play: { target: 'playing' }, stop: { target: 'stopped' } }
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const player = createActor(playerMachine);
|
|
33
|
+
|
|
34
|
+
player.subscribe((snapshot) => console.log(snapshot.value));
|
|
35
|
+
player.start();
|
|
36
|
+
|
|
37
|
+
player.send({ type: 'play' });
|
|
38
|
+
player.send({ type: 'pause' });
|
|
39
|
+
player.send({ type: 'stop' });
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
**What you should see:** `stopped`, `playing`, `paused`, `stopped`.
|
|
43
|
+
|
|
44
|
+
Sending `pause` while stopped does nothing. A state only responds to the events it declares, so the machine cannot take a transition you did not define.
|
|
45
|
+
|
|
46
|
+
## Part 2: Context and events with data
|
|
47
|
+
|
|
48
|
+
States describe which mode the player is in. Context holds the data that goes with it: a playlist and the index of the current track.
|
|
49
|
+
|
|
50
|
+
Add `context`, and two new events for moving through the playlist. Declare event schemas so TypeScript knows the shape of every event, and so you get typed methods on `actor.trigger`.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { z } from 'zod';
|
|
54
|
+
import { createActor, createMachine } from 'xstate';
|
|
55
|
+
|
|
56
|
+
const tracks = [
|
|
57
|
+
{ id: 't1', title: 'Bloom' },
|
|
58
|
+
{ id: 't2', title: 'Ember' },
|
|
59
|
+
{ id: 't3', title: 'Harbor' }
|
|
60
|
+
];
|
|
61
|
+
|
|
62
|
+
const playerMachine = createMachine({
|
|
63
|
+
schemas: {
|
|
64
|
+
events: {
|
|
65
|
+
play: z.object({}),
|
|
66
|
+
pause: z.object({}),
|
|
67
|
+
stop: z.object({}),
|
|
68
|
+
next: z.object({}),
|
|
69
|
+
previous: z.object({})
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
context: { tracks, index: 0 },
|
|
73
|
+
initial: 'stopped',
|
|
74
|
+
on: {
|
|
75
|
+
next: ({ context }) => ({
|
|
76
|
+
context: { ...context, index: context.index + 1 }
|
|
77
|
+
}),
|
|
78
|
+
previous: ({ context }) => ({
|
|
79
|
+
context: { ...context, index: context.index - 1 }
|
|
80
|
+
})
|
|
81
|
+
},
|
|
82
|
+
states: {
|
|
83
|
+
// unchanged from Part 1
|
|
84
|
+
stopped: { on: { play: { target: 'playing' } } },
|
|
85
|
+
playing: {
|
|
86
|
+
on: { pause: { target: 'paused' }, stop: { target: 'stopped' } }
|
|
87
|
+
},
|
|
88
|
+
paused: {
|
|
89
|
+
on: { play: { target: 'playing' }, stop: { target: 'stopped' } }
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
const player = createActor(playerMachine).start();
|
|
95
|
+
|
|
96
|
+
player.trigger.play();
|
|
97
|
+
player.trigger.next();
|
|
98
|
+
|
|
99
|
+
console.log(player.getSnapshot().context.index); // 1
|
|
100
|
+
console.log(player.getSnapshot().value); // 'playing'
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`next` and `previous` live in the machine's root `on`, so they work in every state. Put an event on the root when every state should handle it.
|
|
104
|
+
|
|
105
|
+
A transition can be a function. It receives `{ context, event }` and returns a partial description of what happens next: a `target`, a new `context`, or both. Here there is no `target`, so the player stays put and only the context changes.
|
|
106
|
+
|
|
107
|
+
`player.trigger.next()` is the typed shortcut for `player.send({ type: 'next' })`. It exists because you declared the event in `schemas.events`.
|
|
108
|
+
|
|
109
|
+
**What you should see:** index `1`, value `playing`.
|
|
110
|
+
|
|
111
|
+
## Part 3: Guarding behavior
|
|
112
|
+
|
|
113
|
+
Run `player.trigger.next()` four times and the index runs off the end of the playlist. A guard prevents that.
|
|
114
|
+
|
|
115
|
+
In XState v6 a guard is not a separate property. It is a condition inside the transition function: return `undefined` before enqueuing anything and the event is not handled, with no state change, context change or effects. Enqueuing effects handles the event even when the function returns `undefined`.
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
on: {
|
|
119
|
+
next: ({ context }) => {
|
|
120
|
+
if (context.index === context.tracks.length - 1) return;
|
|
121
|
+
return { context: { ...context, index: context.index + 1 } };
|
|
122
|
+
},
|
|
123
|
+
previous: ({ context }) => {
|
|
124
|
+
if (context.index === 0) return;
|
|
125
|
+
return { context: { ...context, index: context.index - 1 } };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
The same technique branches to different targets. Return whichever transition you want:
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
play: ({ context }) => {
|
|
134
|
+
if (context.tracks.length === 0) return { target: 'empty' };
|
|
135
|
+
return { target: 'playing' };
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
There are no transition arrays and no `guard` property. One event maps to one transition function, and plain `if` statements decide what it does.
|
|
140
|
+
|
|
141
|
+
Swap the two handlers into Part 2's machine and run it:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
player.trigger.next();
|
|
145
|
+
player.trigger.next();
|
|
146
|
+
player.trigger.next(); // ignored: already the last track
|
|
147
|
+
console.log(player.getSnapshot().context.index); // 2
|
|
148
|
+
player.trigger.previous();
|
|
149
|
+
console.log(player.getSnapshot().context.index); // 1
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
**What you should see:** `2`, then `1`. The third `next` is ignored.
|
|
153
|
+
|
|
154
|
+
## Part 4: Async work
|
|
155
|
+
|
|
156
|
+
A real player fetches track metadata before it can play. Async work belongs in an actor, not in a transition.
|
|
157
|
+
|
|
158
|
+
`createAsyncLogic(...)` wraps one async operation. It receives `input` and an `AbortSignal` that XState aborts when the actor stops, so a request for a track you skipped past is canceled.
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
const loadTrack = createAsyncLogic({
|
|
162
|
+
run: async ({
|
|
163
|
+
input,
|
|
164
|
+
signal
|
|
165
|
+
}: {
|
|
166
|
+
input: { id: string };
|
|
167
|
+
signal: AbortSignal;
|
|
168
|
+
}) => {
|
|
169
|
+
const response = await fetch(`/tracks/${input.id}`, { signal });
|
|
170
|
+
if (!response.ok) throw new Error('Could not load track');
|
|
171
|
+
return (await response.json()) as { duration: number };
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
`invoke` runs that logic for the lifetime of a state. Add a `loading` state between `stopped` and `playing`, and an `error` state that offers `retry`. Add `duration: 0` to `context` and `retry: z.object({})` to `schemas.events`.
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
states: {
|
|
180
|
+
stopped: { on: { play: { target: 'loading' } } },
|
|
181
|
+
loading: {
|
|
182
|
+
invoke: {
|
|
183
|
+
src: loadTrack,
|
|
184
|
+
input: ({ context }) => ({ id: context.tracks[context.index].id }),
|
|
185
|
+
onDone: ({ context, event }) => ({
|
|
186
|
+
target: 'playing',
|
|
187
|
+
context: { ...context, duration: event.output.duration }
|
|
188
|
+
}),
|
|
189
|
+
onError: { target: 'error' }
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
error: { on: { retry: { target: 'loading' } } },
|
|
193
|
+
playing: {
|
|
194
|
+
on: { pause: { target: 'paused' }, stop: { target: 'stopped' } }
|
|
195
|
+
},
|
|
196
|
+
paused: {
|
|
197
|
+
on: { play: { target: 'playing' }, stop: { target: 'stopped' } }
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
`onDone` receives the resolved value on `event.output`; `onError` receives the rejection on `event.error`. Invoke belongs to the state, not to the transition that led there: entering `loading` starts the request, leaving it stops the request.
|
|
203
|
+
|
|
204
|
+
Changing tracks should reload metadata, so point `next` and `previous` at `loading` too:
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
next: ({ context }) => {
|
|
208
|
+
const index = context.index + 1;
|
|
209
|
+
if (index === context.tracks.length) return;
|
|
210
|
+
return { target: '.loading', context: { ...context, index, duration: 0 } };
|
|
211
|
+
}
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
The leading dot in `'.loading'` means "a child of the state this transition is defined on", which is the root here.
|
|
215
|
+
|
|
216
|
+
**What you should see:** subscribe to the actor and send `play`. The value logs `loading`, then `playing` with `context.duration` set. If the request fails, the value logs `error`, from which `player.trigger.retry()` tries again. Point the fetch at a URL that fails to see the error path.
|
|
217
|
+
|
|
218
|
+
## Part 5: Statecharts
|
|
219
|
+
|
|
220
|
+
`playing` and `paused` share a `stop` transition, and both mean "a track is loaded and active", so they belong under a common parent.
|
|
221
|
+
|
|
222
|
+
Nest them inside an `active` state and put `stop` on the parent. Any event handled by a parent is handled by all of its children.
|
|
223
|
+
|
|
224
|
+
Volume changes independently of playback. The player can be muted whether it is playing or paused, and muting should not disturb playback. Two independent concerns in one state means a **parallel** state: `active` becomes `type: 'parallel'` with a `playback` region and a `volume` region, both active at once.
|
|
225
|
+
|
|
226
|
+
Replace `playing` and `paused` with a single `active` state, and point the invoke's `onDone` at `'active'`. Add `mute` and `unmute` to `schemas.events`.
|
|
227
|
+
|
|
228
|
+
```ts
|
|
229
|
+
active: {
|
|
230
|
+
type: 'parallel',
|
|
231
|
+
on: { stop: { target: 'stopped' } },
|
|
232
|
+
states: {
|
|
233
|
+
playback: {
|
|
234
|
+
initial: 'playing',
|
|
235
|
+
states: {
|
|
236
|
+
playing: { on: { pause: { target: 'paused' } } },
|
|
237
|
+
paused: { on: { play: { target: 'playing' } } }
|
|
238
|
+
}
|
|
239
|
+
},
|
|
240
|
+
volume: {
|
|
241
|
+
initial: 'audible',
|
|
242
|
+
states: {
|
|
243
|
+
audible: { on: { mute: { target: 'muted' } } },
|
|
244
|
+
muted: { on: { unmute: { target: 'audible' } } }
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
A parallel state has no `initial` of its own. Every region is entered at once, and each region declares its own `initial`.
|
|
252
|
+
|
|
253
|
+
Run it and inspect the state value once loading finishes:
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
player.trigger.pause();
|
|
257
|
+
player.trigger.mute();
|
|
258
|
+
|
|
259
|
+
console.log(player.getSnapshot().value);
|
|
260
|
+
// { active: { playback: 'paused', volume: 'muted' } }
|
|
261
|
+
// prefix match: true
|
|
262
|
+
console.log(player.getSnapshot().matches({ active: { playback: 'paused' } }));
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
**What you should see:** a state value object with both regions. `matches(...)` is a prefix match, so you can ask about one region and ignore the other. `stop` still works from anywhere inside `active`, because it is declared on the parent.
|
|
266
|
+
|
|
267
|
+
## Part 6: Timers
|
|
268
|
+
|
|
269
|
+
Add a sleep timer: "stop the player in N milliseconds". Because a later event may cancel or replace it, this is a delayed event rather than an `after` transition.
|
|
270
|
+
|
|
271
|
+
`enq` is the enqueuer, the second argument of every transition function. It collects the effects a transition should run.
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
sleepAfter: ({ event }, enq) => {
|
|
275
|
+
enq.cancel('sleep');
|
|
276
|
+
enq.raise({ type: 'stop' }, { delay: event.delay, id: 'sleep' });
|
|
277
|
+
},
|
|
278
|
+
cancelSleep: (_, enq) => {
|
|
279
|
+
enq.cancel('sleep');
|
|
280
|
+
}
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
`enq.raise(...)` sends an event back into this machine, and `{ id: 'sleep' }` gives the pending event a name so `enq.cancel('sleep')` can remove it. Canceling first means a second `sleepAfter` replaces the pending timer instead of stacking one on top of it.
|
|
284
|
+
|
|
285
|
+
Put both handlers in the root `on`, next to `next` and `previous`, and declare the events in `schemas.events`:
|
|
286
|
+
|
|
287
|
+
```ts
|
|
288
|
+
sleepAfter: z.object({ delay: z.number() }),
|
|
289
|
+
cancelSleep: z.object({})
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
Try it:
|
|
293
|
+
|
|
294
|
+
```ts
|
|
295
|
+
player.trigger.sleepAfter({ delay: 5_000 }); // stops 5 seconds later
|
|
296
|
+
player.trigger.cancelSleep(); // cancels the pending stop
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
**What you should see:** without the cancel, the state value drops to `'stopped'` after five seconds. With it, the player stays in `active`. `event.delay` is typed as a number because of the event schema.
|
|
300
|
+
|
|
301
|
+
For a timer tied to a state instead of an event, use `after: { 5_000: { target: 'stopped' } }`. It starts when the state is entered and is canceled when the state is exited. See [delays](delays.md).
|
|
302
|
+
|
|
303
|
+
## Part 7: Actors and emitted events
|
|
304
|
+
|
|
305
|
+
The machine should tell the outside world when the track changes so the UI can show a toast. That is not state; it is something that happened once. Emit an event.
|
|
306
|
+
|
|
307
|
+
Declare it in `schemas.emitted`, emit it with `enq.emit(...)` inside `next` and `previous`, and handle it with `actor.on(...)`. Put the emit after the guard, so a `next` at the end of the playlist emits nothing.
|
|
308
|
+
|
|
309
|
+
Here is the complete machine:
|
|
310
|
+
|
|
311
|
+
```ts
|
|
312
|
+
import { z } from 'zod';
|
|
313
|
+
import { createActor, createAsyncLogic, createMachine } from 'xstate';
|
|
314
|
+
|
|
315
|
+
const tracks = [
|
|
316
|
+
{ id: 't1', title: 'Bloom' },
|
|
317
|
+
{ id: 't2', title: 'Ember' },
|
|
318
|
+
{ id: 't3', title: 'Harbor' }
|
|
319
|
+
];
|
|
320
|
+
|
|
321
|
+
const loadTrack = createAsyncLogic({
|
|
322
|
+
run: async ({
|
|
323
|
+
input,
|
|
324
|
+
signal
|
|
325
|
+
}: {
|
|
326
|
+
input: { id: string };
|
|
327
|
+
signal: AbortSignal;
|
|
328
|
+
}) => {
|
|
329
|
+
const response = await fetch(`/tracks/${input.id}`, { signal });
|
|
330
|
+
if (!response.ok) throw new Error('Could not load track');
|
|
331
|
+
return (await response.json()) as { duration: number };
|
|
332
|
+
}
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
export const playerMachine = createMachine({
|
|
336
|
+
schemas: {
|
|
337
|
+
events: {
|
|
338
|
+
play: z.object({}),
|
|
339
|
+
pause: z.object({}),
|
|
340
|
+
stop: z.object({}),
|
|
341
|
+
next: z.object({}),
|
|
342
|
+
previous: z.object({}),
|
|
343
|
+
retry: z.object({}),
|
|
344
|
+
mute: z.object({}),
|
|
345
|
+
unmute: z.object({}),
|
|
346
|
+
sleepAfter: z.object({ delay: z.number() }),
|
|
347
|
+
cancelSleep: z.object({})
|
|
348
|
+
},
|
|
349
|
+
emitted: {
|
|
350
|
+
trackChanged: z.object({ title: z.string() })
|
|
351
|
+
}
|
|
352
|
+
},
|
|
353
|
+
context: { tracks, index: 0, duration: 0 },
|
|
354
|
+
initial: 'stopped',
|
|
355
|
+
on: {
|
|
356
|
+
next: ({ context }, enq) => {
|
|
357
|
+
const index = context.index + 1;
|
|
358
|
+
if (index === context.tracks.length) return;
|
|
359
|
+
enq.emit({ type: 'trackChanged', title: context.tracks[index].title });
|
|
360
|
+
return { target: '.loading', context: { ...context, index, duration: 0 } };
|
|
361
|
+
},
|
|
362
|
+
previous: ({ context }, enq) => {
|
|
363
|
+
const index = context.index - 1;
|
|
364
|
+
if (index < 0) return;
|
|
365
|
+
enq.emit({ type: 'trackChanged', title: context.tracks[index].title });
|
|
366
|
+
return { target: '.loading', context: { ...context, index, duration: 0 } };
|
|
367
|
+
},
|
|
368
|
+
sleepAfter: ({ event }, enq) => {
|
|
369
|
+
enq.cancel('sleep');
|
|
370
|
+
enq.raise({ type: 'stop' }, { delay: event.delay, id: 'sleep' });
|
|
371
|
+
},
|
|
372
|
+
cancelSleep: (_, enq) => {
|
|
373
|
+
enq.cancel('sleep');
|
|
374
|
+
}
|
|
375
|
+
},
|
|
376
|
+
states: {
|
|
377
|
+
stopped: { on: { play: { target: 'loading' } } },
|
|
378
|
+
loading: {
|
|
379
|
+
invoke: {
|
|
380
|
+
src: loadTrack,
|
|
381
|
+
input: ({ context }) => ({ id: context.tracks[context.index].id }),
|
|
382
|
+
onDone: ({ context, event }) => ({
|
|
383
|
+
target: 'active',
|
|
384
|
+
context: { ...context, duration: event.output.duration }
|
|
385
|
+
}),
|
|
386
|
+
onError: { target: 'error' }
|
|
387
|
+
}
|
|
388
|
+
},
|
|
389
|
+
error: { on: { retry: { target: 'loading' } } },
|
|
390
|
+
active: {
|
|
391
|
+
type: 'parallel',
|
|
392
|
+
on: { stop: { target: 'stopped' } },
|
|
393
|
+
states: {
|
|
394
|
+
playback: {
|
|
395
|
+
initial: 'playing',
|
|
396
|
+
states: {
|
|
397
|
+
playing: { on: { pause: { target: 'paused' } } },
|
|
398
|
+
paused: { on: { play: { target: 'playing' } } }
|
|
399
|
+
}
|
|
400
|
+
},
|
|
401
|
+
volume: {
|
|
402
|
+
initial: 'audible',
|
|
403
|
+
states: {
|
|
404
|
+
audible: { on: { mute: { target: 'muted' } } },
|
|
405
|
+
muted: { on: { unmute: { target: 'audible' } } }
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
const player = createActor(playerMachine).start();
|
|
414
|
+
|
|
415
|
+
player.on('trackChanged', (event) => {
|
|
416
|
+
console.log(`Now playing: ${event.title}`);
|
|
417
|
+
});
|
|
418
|
+
|
|
419
|
+
player.trigger.play();
|
|
420
|
+
player.trigger.next();
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
**What you should see:** `Now playing: Ember` logged once, and no log at all when `next` is sent at the end of the playlist.
|
|
424
|
+
|
|
425
|
+
Use an emitted event when the outside world should react to something that happened. Use a snapshot when it should render the current state. See [emitted events](emitted-events.md).
|
|
426
|
+
|
|
427
|
+
## Part 8: Wire it to a UI
|
|
428
|
+
|
|
429
|
+
Nothing about the machine changes. A UI reads snapshots and sends events.
|
|
430
|
+
|
|
431
|
+
```html
|
|
432
|
+
<p id="status">stopped</p>
|
|
433
|
+
<p id="title">—</p>
|
|
434
|
+
<button id="play">Play</button> <button id="pause">Pause</button>
|
|
435
|
+
<button id="stop">Stop</button> <button id="previous">Previous</button>
|
|
436
|
+
<button id="next">Next</button> <button id="mute">Mute</button>
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
```ts
|
|
440
|
+
import { createActor } from 'xstate';
|
|
441
|
+
import { playerMachine } from './playerMachine';
|
|
442
|
+
|
|
443
|
+
const player = createActor(playerMachine).start();
|
|
444
|
+
|
|
445
|
+
const status = document.getElementById('status')!;
|
|
446
|
+
const title = document.getElementById('title')!;
|
|
447
|
+
|
|
448
|
+
const stateValue = player.select((snapshot) => JSON.stringify(snapshot.value));
|
|
449
|
+
const trackTitle = player.select(
|
|
450
|
+
(snapshot) => snapshot.context.tracks[snapshot.context.index].title
|
|
451
|
+
);
|
|
452
|
+
|
|
453
|
+
status.textContent = stateValue.get();
|
|
454
|
+
stateValue.subscribe((value) => (status.textContent = value));
|
|
455
|
+
|
|
456
|
+
title.textContent = trackTitle.get();
|
|
457
|
+
trackTitle.subscribe((value) => (title.textContent = value));
|
|
458
|
+
|
|
459
|
+
const buttons = ['play', 'pause', 'stop', 'next', 'previous', 'mute'] as const;
|
|
460
|
+
|
|
461
|
+
for (const type of buttons) {
|
|
462
|
+
document.getElementById(type)!.onclick = () => player.trigger[type]();
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
player.on('trackChanged', (event) => showToast(`Now playing: ${event.title}`));
|
|
466
|
+
```
|
|
467
|
+
|
|
468
|
+
`player.select(...)` returns a readable that notifies only when its value changes, so the title element is not touched when only playback state moves. Call `get()` for the initial render, since `subscribe(...)` does not replay the current value.
|
|
469
|
+
|
|
470
|
+
**What you should see:** clicking `Play` shows `"loading"` then `{"active":{"playback":"playing","volume":"audible"}}`. Clicking `Pause` updates the status but leaves the title alone. Buttons that the current state does not handle do nothing.
|
|
471
|
+
|
|
472
|
+
Frameworks work the same way, with a hook or store binding instead of manual subscriptions. See [frameworks](frameworks.md) for React, Vue, Svelte and Solid.
|
|
473
|
+
|
|
474
|
+
## What next?
|
|
475
|
+
|
|
476
|
+
You built one machine with context, guards, invoked async logic, hierarchy, parallel regions, delayed events, emitted events and a UI. From here:
|
|
477
|
+
|
|
478
|
+
- [Statecharts](statecharts.md) — nested, parallel and history states
|
|
479
|
+
- [Actors](actors.md) — spawning, communication and actor systems
|
|
480
|
+
- [Frameworks](frameworks.md) — bindings for React, Vue, Svelte and Solid
|
|
481
|
+
- [Testing](testing.md) — testing machines and the actors that run them
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: TypeScript
|
|
3
|
+
description: Define schemas and derive XState types.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Define schemas with `setup(...)`. XState infers context, events, input and output from them. State contracts can additionally declare state-node structure and defaults, including `type`, `initial`, `history`, `target` and `id`.
|
|
7
|
+
|
|
8
|
+
Enable TypeScript's `strict` mode. Keep schemas next to actor logic so runtime validation and inferred types describe the same contract.
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { z } from 'zod';
|
|
12
|
+
import { setup } from 'xstate';
|
|
13
|
+
|
|
14
|
+
const machine = setup({
|
|
15
|
+
schemas: {
|
|
16
|
+
context: z.object({ count: z.number() }),
|
|
17
|
+
events: {
|
|
18
|
+
increment: z.object({})
|
|
19
|
+
},
|
|
20
|
+
internalEvents: {
|
|
21
|
+
tick: z.object({ count: z.number() })
|
|
22
|
+
},
|
|
23
|
+
input: z.object({ initialCount: z.number() })
|
|
24
|
+
}
|
|
25
|
+
}).createMachine({
|
|
26
|
+
context: ({ input }) => ({ count: input.initialCount }),
|
|
27
|
+
initial: 'active',
|
|
28
|
+
states: { active: {} }
|
|
29
|
+
});
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
A declared input schema whose inferred type does not accept `undefined` makes `input` required: `createActor(machine)` is a type error until you pass `{ input }` (or restore a snapshot with `restoreActor(...)`). Framework hooks such as `useActor`, `useActorRef` and `useMachine` inherit the same requirement. `createActorContext` from `@xstate/react` is the exception: `input` stays optional because its options are merged from the context defaults and the `<Provider options>` prop, so a missing input surfaces at runtime as an initialization error instead.
|
|
33
|
+
|
|
34
|
+
<!-- state-contract typing and declaration emit from packages/core/src/setup.ts and packages/core/test/declarations.test.ts -->
|
|
35
|
+
|
|
36
|
+
Structural state contracts are checked only when declared. For example,
|
|
37
|
+
`type: 'parallel'` forbids `initial`, while `type: 'compound'` requires one.
|
|
38
|
+
`setup(...)` can supply those defaults, so the machine config may omit them.
|
|
39
|
+
Setups that declare only schemas do not impose these structural checks.
|
|
40
|
+
A state-level `schemas.context` is intersected with the root context
|
|
41
|
+
schema, so it can declare only the fields that state narrows.
|
|
42
|
+
|
|
43
|
+
XState infers `snapshot.value` and valid `snapshot.matches(...)` patterns
|
|
44
|
+
from nested and parallel states. Match a nested state with an object such as
|
|
45
|
+
`{ b: 'x' }` or a dot path such as `'b.x'`.
|
|
46
|
+
|
|
47
|
+
You can export machines and state configs with their inferred types, without
|
|
48
|
+
adding explicit type annotations.
|
|
49
|
+
|
|
50
|
+
For an actor used in one state, `invoke: s.createInvoke({ src, input, onDone })` infers input and completion output from `src`. Keep the helper inline in `s.createMachine(...)` to also infer that state's narrowed context, ancestor context, state input and transition target requirements. The helper works alongside named actor sources. See [typed inline invokes](invoke.md#typed-inline-invokes).
|
|
51
|
+
|
|
52
|
+
An async function can be used directly as `src`. Declare `schemas.input`, `schemas.output`, and `schemas.error` on the invoke to type the function and its lifecycle handlers together. Without `schemas.output`, `onDone.event.output` infers from the async return value.
|
|
53
|
+
|
|
54
|
+
Public schema event keys create typed methods on `actor.trigger`; internal
|
|
55
|
+
schema keys do not appear in the public trigger namespace.
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
actor.trigger.increment();
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Event types narrow inside transitions:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
on: {
|
|
65
|
+
search: ({ event }) => {
|
|
66
|
+
event.query; // string
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Use `assertEvent(...)` only when shared code must narrow a union to one or more known event types.
|
|
72
|
+
|
|
73
|
+
## Typestates
|
|
74
|
+
|
|
75
|
+
State-level `schemas.context` declarations describe the context valid in each
|
|
76
|
+
state. State functions receive the narrowed type, transitions into a state
|
|
77
|
+
must satisfy its context contract, and `snapshot.matches(...)` narrows context
|
|
78
|
+
when reading a snapshot. See [Typestates](typestates.md) for declaration,
|
|
79
|
+
transition and runtime validation examples.
|
|
80
|
+
|
|
81
|
+
## Checked event keys
|
|
82
|
+
|
|
83
|
+
When `schemas.events` is declared, each key in an `on` map must match a
|
|
84
|
+
declared event type. Matching wildcards (`'*'`, `'user.*'`) and known reserved
|
|
85
|
+
machine descriptors are allowed; misspelled or invented reserved prefixes are rejected. Without `schemas.events`, any key is accepted.
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
on: {
|
|
89
|
+
toggel: { target: 'active' }
|
|
90
|
+
// Type error: Event type 'toggel' is not declared in schemas.events.
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Known reserved descriptors in `on` carry their actual event payloads: actor completion, error and snapshot events; execution errors; state completion; delayed events; and state or actor timeouts. Bare `xstate.error.actor` handlers receive `event.error` and `event.actorId`. Suffixed v5 descriptors such as `xstate.done.actor.fetchUser` never match, because v6 lifecycle event types carry the id in a payload field; `createMachine` throws when `on` uses one. Wildcards over a category type, such as `xstate.done.actor.*`, still match. Use `xstate.error.actor` and filter `event.actorId` explicitly when handling a particular child.
|
|
95
|
+
|
|
96
|
+
## Child completion events
|
|
97
|
+
|
|
98
|
+
Children declared in `schemas.children` add their `xstate.done.actor` and
|
|
99
|
+
`xstate.error.actor` events to the event union seen by `entry`, `exit`, guards
|
|
100
|
+
and transition functions. `event.actorId` is the declared child id, and
|
|
101
|
+
`event.output` is that child's output type:
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
entry: ({ event }) => {
|
|
105
|
+
assertEvent(event, 'xstate.done.actor');
|
|
106
|
+
event.actorId; // 'fetch'
|
|
107
|
+
event.output; // output of the logic declared for `fetch`
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Without `schemas.children`, these events are not added. `on` handlers still
|
|
112
|
+
narrow to their own event type.
|
|
113
|
+
|
|
114
|
+
## Async logic errors
|
|
115
|
+
|
|
116
|
+
`createAsyncLogic({ schemas: { error } })` types the actor's `error` snapshot
|
|
117
|
+
field and `event.error` in the invoking machine's `onError`. The schema is
|
|
118
|
+
type-only. Without it, the error is `unknown`:
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
const fetchUser = createAsyncLogic({
|
|
122
|
+
schemas: { error: z.object({ code: z.string() }) },
|
|
123
|
+
run: async () => ({ name: 'David' })
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
// in an invoke of fetchUser
|
|
127
|
+
onError: ({ event }) => event.error.code; // string
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Checked delay names
|
|
131
|
+
|
|
132
|
+
When delays are declared with `setup({ delays })` or `createMachine({ delays })`,
|
|
133
|
+
each `after` key must be a declared delay name, a number of milliseconds, or a
|
|
134
|
+
duration string such as `'5s'`. Without declared delays, any key is accepted.
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
after: {
|
|
138
|
+
retryDelya: { target: 'retrying' }
|
|
139
|
+
// Type error: Delay 'retryDelya' is not declared in delays.
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Runtime validation
|
|
144
|
+
|
|
145
|
+
<!-- runtime validation API and boundaries from packages/core/src/validation.types.ts, packages/core/src/validation/index.ts, and packages/core/src/setup.ts -->
|
|
146
|
+
|
|
147
|
+
> **Experimental:** `standardSchemaValidator()`, `ActorValidationError` and the other `xstate/validation` exports may change in a minor release.
|
|
148
|
+
|
|
149
|
+
Runtime validation is opt-in. Install the Standard Schema validator from the
|
|
150
|
+
separate `xstate/validation` entry point:
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
import { setup } from 'xstate';
|
|
154
|
+
import { standardSchemaValidator } from 'xstate/validation';
|
|
155
|
+
import { z } from 'zod';
|
|
156
|
+
|
|
157
|
+
const machine = setup({
|
|
158
|
+
validator: standardSchemaValidator(),
|
|
159
|
+
schemas: {
|
|
160
|
+
input: z.object({ initialCount: z.number() }),
|
|
161
|
+
context: z.object({ count: z.number() }),
|
|
162
|
+
events: {
|
|
163
|
+
increment: z.object({ by: z.number() })
|
|
164
|
+
},
|
|
165
|
+
internalEvents: {
|
|
166
|
+
tick: z.object({ count: z.number() })
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}).createMachine({
|
|
170
|
+
context: ({ input }) => ({ count: input.initialCount })
|
|
171
|
+
});
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
The validator checks input and public or internal events before calculation, then checks
|
|
175
|
+
stable context, active state schemas, child slots, delayed raised events,
|
|
176
|
+
emitted events and final output before effects run. Invalid actor-produced
|
|
177
|
+
values error the actor; pure calculations throw an
|
|
178
|
+
`ActorValidationError`. Invalid incoming events are rejected without changing
|
|
179
|
+
or erroring the actor and reported through `onRejectedEvent`. See
|
|
180
|
+
[validation failures](setup-and-provide.md#validation-failures).
|
|
181
|
+
|
|
182
|
+
Validation is synchronous and assertion-only: async validation is rejected.
|
|
183
|
+
Parsed schema results are discarded. Type-changing transformations are rejected
|
|
184
|
+
by the types, but same-type transformations cannot be detected statically;
|
|
185
|
+
normalize values before sending them. Unknown incoming events are rejected, and
|
|
186
|
+
unknown emitted events error the actor, when a corresponding schema map exists; use
|
|
187
|
+
`unknownEvents: 'ignore'` or
|
|
188
|
+
`unknownEmitted: 'ignore'` for open protocols.
|
|
189
|
+
|
|
190
|
+
Derived setups inherit the validator. Replace it or use `validator: undefined`
|
|
191
|
+
to disable it. Persistence, restoration, immediate raised events, action and
|
|
192
|
+
guard parameters, static meta and tags, and `snapshot.can()` are not validation
|
|
193
|
+
boundaries.
|
|
194
|
+
|
|
195
|
+
## Type helpers
|
|
196
|
+
|
|
197
|
+
| Helper | Derives |
|
|
198
|
+
| --- | --- |
|
|
199
|
+
| `ActorRefFrom<T>` | Actor reference type. |
|
|
200
|
+
| `SnapshotFrom<T>` | Snapshot type. |
|
|
201
|
+
| `EventFromLogic<T>` | Accepted event type. |
|
|
202
|
+
| `InputFrom<T>` | Input type. |
|
|
203
|
+
| `OutputFrom<T>` | Final output type. |
|
|
204
|
+
|
|
205
|
+
## TypeScript cheatsheet
|
|
206
|
+
|
|
207
|
+
```ts
|
|
208
|
+
type Actor = ActorRefFrom<typeof machine>;
|
|
209
|
+
type Snapshot = SnapshotFrom<typeof machine>;
|
|
210
|
+
type Event = EventFromLogic<typeof machine>;
|
|
211
|
+
type Input = InputFrom<typeof machine>;
|
|
212
|
+
type Output = OutputFrom<typeof machine>;
|
|
213
|
+
```
|