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.
Files changed (235) hide show
  1. package/README.md +223 -78
  2. package/bin/agent.js +347 -0
  3. package/bin/xstate.js +52 -0
  4. package/dist/createActor-25900f76.cjs.js +7015 -0
  5. package/dist/createActor-551369be.development.esm.js +7175 -0
  6. package/dist/createActor-a49ae0ce.development.cjs.js +7289 -0
  7. package/dist/createActor-cbe3abac.esm.js +6902 -0
  8. package/dist/declarations/src/SimulatedClock.d.ts +2 -1
  9. package/dist/declarations/src/State.d.ts +66 -5
  10. package/dist/declarations/src/StateMachine.d.ts +107 -32
  11. package/dist/declarations/src/StateNode.d.ts +21 -16
  12. package/dist/declarations/src/actions.d.ts +11 -6
  13. package/dist/declarations/src/actors/callback.d.ts +11 -2
  14. package/dist/declarations/src/actors/index.d.ts +6 -5
  15. package/dist/declarations/src/actors/listener.d.ts +8 -3
  16. package/dist/declarations/src/actors/logic.d.ts +42 -52
  17. package/dist/declarations/src/actors/observable.d.ts +15 -2
  18. package/dist/declarations/src/actors/promise.d.ts +90 -22
  19. package/dist/declarations/src/actors/subscription.d.ts +9 -3
  20. package/dist/declarations/src/assert.d.ts +1 -0
  21. package/dist/declarations/src/base.types.d.ts +102 -0
  22. package/dist/declarations/src/createActor.d.ts +101 -27
  23. package/dist/declarations/src/createMachine.d.ts +38 -17
  24. package/dist/declarations/src/delay.d.ts +8 -0
  25. package/dist/declarations/src/durable/index.d.ts +231 -0
  26. package/dist/declarations/src/effectDescriptor.d.ts +95 -0
  27. package/dist/declarations/src/eventTypes.d.ts +9 -0
  28. package/dist/declarations/src/fsm/index.d.ts +2 -0
  29. package/dist/declarations/src/fsm.d.ts +169 -0
  30. package/dist/declarations/src/graph/adjacency.d.ts +6 -3
  31. package/dist/declarations/src/graph/graph.d.ts +6 -3
  32. package/dist/declarations/src/graph/index.d.ts +2 -3
  33. package/dist/declarations/src/graph/pathFromEvents.d.ts +5 -2
  34. package/dist/declarations/src/graph/shortestPaths.d.ts +5 -3
  35. package/dist/declarations/src/graph/simplePaths.d.ts +5 -3
  36. package/dist/declarations/src/graph/types.d.ts +113 -59
  37. package/dist/declarations/src/hotSwap.d.ts +18 -0
  38. package/dist/declarations/src/index.d.ts +28 -19
  39. package/dist/declarations/src/inspection.d.ts +24 -1
  40. package/dist/declarations/src/machineFromJSON.d.ts +171 -0
  41. package/dist/declarations/src/machineSchemas.d.ts +27 -0
  42. package/dist/declarations/src/machineVersion.types.d.ts +53 -0
  43. package/dist/declarations/src/machineVersions.d.ts +103 -0
  44. package/dist/declarations/src/mapState.d.ts +2 -0
  45. package/dist/declarations/src/persist/index.d.ts +36 -0
  46. package/dist/declarations/src/persistedSnapshotValidation.d.ts +18 -0
  47. package/dist/declarations/src/runtimeHelpers.d.ts +43 -0
  48. package/dist/declarations/src/schema.types.d.ts +31 -4
  49. package/dist/declarations/src/serialize.d.ts +39 -28
  50. package/dist/declarations/src/setup.d.ts +1086 -147
  51. package/dist/declarations/src/spawn.d.ts +6 -4
  52. package/dist/declarations/src/stateUtils.d.ts +57 -14
  53. package/dist/declarations/src/system.d.ts +178 -17
  54. package/dist/declarations/src/systemTransition.d.ts +108 -0
  55. package/dist/declarations/src/toPromise.d.ts +1 -0
  56. package/dist/declarations/src/transition.d.ts +48 -10
  57. package/dist/declarations/src/transitionActions.d.ts +22 -4
  58. package/dist/declarations/src/typeUtils.d.ts +51 -0
  59. package/dist/declarations/src/types.d.ts +835 -318
  60. package/dist/declarations/src/types.v6.d.ts +547 -104
  61. package/dist/declarations/src/utils.d.ts +38 -8
  62. package/dist/declarations/src/validation/index.d.ts +49 -0
  63. package/dist/declarations/src/validation.types.d.ts +29 -0
  64. package/dist/declarations/src/waitFor.d.ts +1 -0
  65. package/dist/effectDescriptor-2fa27c54.cjs.js +351 -0
  66. package/dist/effectDescriptor-321a8ce9.development.esm.js +343 -0
  67. package/dist/effectDescriptor-d8b0f749.esm.js +343 -0
  68. package/dist/effectDescriptor-f73da4ec.development.cjs.js +351 -0
  69. package/dist/machineSchemas-45c21bc2.esm.js +1292 -0
  70. package/dist/machineSchemas-6d96bef4.development.cjs.js +1379 -0
  71. package/dist/machineSchemas-88d01821.cjs.js +1300 -0
  72. package/dist/machineSchemas-b5736804.development.esm.js +1371 -0
  73. package/dist/schema.types-0ecd17b8.esm.js +71 -0
  74. package/dist/schema.types-15a68ddc.cjs.js +74 -0
  75. package/dist/schema.types-1c16f035.development.cjs.js +74 -0
  76. package/dist/schema.types-1cd4652e.development.esm.js +71 -0
  77. package/dist/validation-05f1d517.esm.js +8 -0
  78. package/dist/validation-4561b43c.cjs.js +10 -0
  79. package/dist/validation-e69470ad.development.esm.js +8 -0
  80. package/dist/validation-f2714a35.development.cjs.js +10 -0
  81. package/dist/xstate-actors.cjs.js +1068 -12
  82. package/dist/xstate-actors.cjs.mjs +2 -4
  83. package/dist/xstate-actors.development.cjs.js +1068 -12
  84. package/dist/xstate-actors.development.cjs.mjs +2 -4
  85. package/dist/xstate-actors.development.esm.js +1064 -1
  86. package/dist/xstate-actors.esm.js +1064 -1
  87. package/dist/xstate-actors.umd.min.js +1 -1
  88. package/dist/xstate-actors.umd.min.js.map +1 -1
  89. package/dist/xstate-durable.cjs.d.mts +2 -0
  90. package/dist/xstate-durable.cjs.d.ts +2 -0
  91. package/dist/xstate-durable.cjs.js +513 -0
  92. package/dist/xstate-durable.cjs.mjs +5 -0
  93. package/dist/xstate-durable.development.cjs.js +513 -0
  94. package/dist/xstate-durable.development.cjs.mjs +5 -0
  95. package/dist/xstate-durable.development.esm.js +507 -0
  96. package/dist/xstate-durable.esm.js +507 -0
  97. package/dist/xstate-durable.umd.min.js +2 -0
  98. package/dist/xstate-durable.umd.min.js.map +1 -0
  99. package/dist/xstate-fsm.cjs.d.mts +2 -0
  100. package/dist/xstate-fsm.cjs.d.ts +2 -0
  101. package/dist/xstate-fsm.cjs.js +111 -0
  102. package/dist/xstate-fsm.cjs.mjs +5 -0
  103. package/dist/xstate-fsm.development.cjs.js +111 -0
  104. package/dist/xstate-fsm.development.cjs.mjs +5 -0
  105. package/dist/xstate-fsm.development.esm.js +105 -0
  106. package/dist/xstate-fsm.esm.js +105 -0
  107. package/dist/xstate-fsm.umd.min.js +2 -0
  108. package/dist/xstate-fsm.umd.min.js.map +1 -0
  109. package/dist/xstate-graph.cjs.js +173 -457
  110. package/dist/xstate-graph.cjs.mjs +2 -5
  111. package/dist/xstate-graph.development.cjs.js +173 -457
  112. package/dist/xstate-graph.development.cjs.mjs +2 -5
  113. package/dist/xstate-graph.development.esm.js +171 -451
  114. package/dist/xstate-graph.esm.js +171 -451
  115. package/dist/xstate-graph.umd.min.js +1 -1
  116. package/dist/xstate-graph.umd.min.js.map +1 -1
  117. package/dist/xstate-persist.cjs.d.mts +2 -0
  118. package/dist/xstate-persist.cjs.d.ts +2 -0
  119. package/dist/xstate-persist.cjs.js +314 -0
  120. package/dist/xstate-persist.cjs.mjs +6 -0
  121. package/dist/xstate-persist.development.cjs.js +325 -0
  122. package/dist/xstate-persist.development.cjs.mjs +6 -0
  123. package/dist/xstate-persist.development.esm.js +319 -0
  124. package/dist/xstate-persist.esm.js +308 -0
  125. package/dist/xstate-persist.umd.min.js +2 -0
  126. package/dist/xstate-persist.umd.min.js.map +1 -0
  127. package/dist/xstate-validation.cjs.d.mts +2 -0
  128. package/dist/xstate-validation.cjs.d.ts +2 -0
  129. package/dist/xstate-validation.cjs.js +330 -0
  130. package/dist/xstate-validation.cjs.mjs +5 -0
  131. package/dist/xstate-validation.development.cjs.js +330 -0
  132. package/dist/xstate-validation.development.cjs.mjs +5 -0
  133. package/dist/xstate-validation.development.esm.js +324 -0
  134. package/dist/xstate-validation.esm.js +324 -0
  135. package/dist/xstate-validation.umd.min.js +2 -0
  136. package/dist/xstate-validation.umd.min.js.map +1 -0
  137. package/dist/xstate.cjs.js +2486 -1430
  138. package/dist/xstate.cjs.mjs +23 -13
  139. package/dist/xstate.development.cjs.js +2486 -1430
  140. package/dist/xstate.development.cjs.mjs +23 -13
  141. package/dist/xstate.development.esm.js +2445 -1398
  142. package/dist/xstate.esm.js +2445 -1398
  143. package/dist/xstate.umd.min.js +1 -1
  144. package/dist/xstate.umd.min.js.map +1 -1
  145. package/docs/actions.md +75 -0
  146. package/docs/actor-logic.md +250 -0
  147. package/docs/actors.md +64 -0
  148. package/docs/agents.md +132 -0
  149. package/docs/api-stability.json +4287 -0
  150. package/docs/async-logic.md +75 -0
  151. package/docs/async-requests.md +157 -0
  152. package/docs/backend-workflows.md +124 -0
  153. package/docs/cancellation.md +42 -0
  154. package/docs/cheatsheet.md +563 -0
  155. package/docs/choice-states.md +109 -0
  156. package/docs/choose-xstate.md +47 -0
  157. package/docs/configuration.md +161 -0
  158. package/docs/context.md +67 -0
  159. package/docs/create-actor.md +159 -0
  160. package/docs/data-and-effects.md +48 -0
  161. package/docs/delays.md +81 -0
  162. package/docs/durable-execution.md +520 -0
  163. package/docs/emitted-events.md +146 -0
  164. package/docs/errors.md +812 -0
  165. package/docs/examples.md +75 -0
  166. package/docs/faq.md +60 -0
  167. package/docs/final-states.md +149 -0
  168. package/docs/forms-and-wizards.md +166 -0
  169. package/docs/frameworks.md +69 -0
  170. package/docs/fsm.md +164 -0
  171. package/docs/glossary.md +68 -0
  172. package/docs/guards.md +137 -0
  173. package/docs/history-states.md +161 -0
  174. package/docs/how-xstate-runs-machines.md +86 -0
  175. package/docs/index.md +74 -0
  176. package/docs/input-output.md +69 -0
  177. package/docs/inspect-actor-systems.md +118 -0
  178. package/docs/inspection.md +75 -0
  179. package/docs/internal-events.md +156 -0
  180. package/docs/invoke.md +371 -0
  181. package/docs/lifecycle-and-errors.md +48 -0
  182. package/docs/listen-and-subscribe.md +126 -0
  183. package/docs/model-based-testing.md +321 -0
  184. package/docs/modeling.md +40 -0
  185. package/docs/parallel-states.md +182 -0
  186. package/docs/persist-and-restore-actors.md +120 -0
  187. package/docs/persistence.md +312 -0
  188. package/docs/quick-start.md +55 -0
  189. package/docs/retries-and-timeouts.md +122 -0
  190. package/docs/route-states.md +104 -0
  191. package/docs/scxml.md +92 -0
  192. package/docs/selectors.md +99 -0
  193. package/docs/serialization.md +127 -0
  194. package/docs/setup-and-provide.md +273 -0
  195. package/docs/snapshots.md +134 -0
  196. package/docs/spawn.md +212 -0
  197. package/docs/state-input.md +162 -0
  198. package/docs/statecharts.md +54 -0
  199. package/docs/states-events-transitions.md +82 -0
  200. package/docs/states.md +168 -0
  201. package/docs/system-transitions.md +172 -0
  202. package/docs/systems.md +166 -0
  203. package/docs/testing.md +152 -0
  204. package/docs/timeouts.md +125 -0
  205. package/docs/transition-functions.md +89 -0
  206. package/docs/transitions.md +187 -0
  207. package/docs/troubleshooting.md +56 -0
  208. package/docs/tutorial.md +481 -0
  209. package/docs/typescript.md +213 -0
  210. package/docs/typestates.md +112 -0
  211. package/docs/utilities.md +39 -0
  212. package/docs/why-state-machines.md +59 -0
  213. package/docs/xstate-v5-to-v6.md +1923 -0
  214. package/docs/your-first-machine.md +79 -0
  215. package/durable/package.json +8 -0
  216. package/fsm/package.json +8 -0
  217. package/package.json +72 -10
  218. package/persist/package.json +8 -0
  219. package/validation/package.json +8 -0
  220. package/actions/package.json +0 -8
  221. package/dev/package.json +0 -8
  222. package/dist/StateMachine-0aa98f54.development.esm.js +0 -746
  223. package/dist/StateMachine-aef700df.cjs.js +0 -732
  224. package/dist/StateMachine-d4931336.esm.js +0 -729
  225. package/dist/StateMachine-da872dde.development.cjs.js +0 -749
  226. package/dist/declarations/src/createMachineFromConfig.d.ts +0 -177
  227. package/dist/declarations/src/getNextSnapshot.d.ts +0 -37
  228. package/dist/declarations/src/graph/TestModel.d.ts +0 -70
  229. package/dist/declarations/src/graph/pathGenerators.d.ts +0 -4
  230. package/dist/index-219cb621.development.cjs.js +0 -4476
  231. package/dist/index-2f2fbd9b.development.esm.js +0 -4421
  232. package/dist/index-559ceab3.cjs.js +0 -4437
  233. package/dist/index-8828376f.esm.js +0 -4382
  234. package/guards/package.json +0 -8
  235. package/invoke/package.json +0 -4
@@ -0,0 +1,321 @@
1
+ ---
2
+ title: Model-based testing
3
+ description: Generate event sequences from a machine and check an implementation against it with @xstate/test.
4
+ ---
5
+
6
+ A machine describes what a feature should do. Model-based testing uses that machine to generate the tests: `@xstate/test` produces event sequences from the machine, sends each sequence to the machine and to your implementation, and fails when the two disagree.
7
+
8
+ This page tests a hand-written shopping cart against a cart machine. For every option, see the [`@xstate/test` README](https://github.com/statelyai/xstate/tree/next/packages/xstate-test#readme).
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ pnpm add -D @xstate/test@beta fast-check
14
+ ```
15
+
16
+ `@xstate/test` generates values with [fast-check](https://fast-check.dev), which is a required peer dependency.
17
+
18
+ ## Write the model
19
+
20
+ The model is an ordinary machine. It says what the cart must do: `ADD` adds one of a SKU, `REMOVE` takes a SKU out, and `CHECKOUT` finishes a cart that is not empty.
21
+
22
+ ```ts
23
+ import { createMachine, types } from 'xstate';
24
+
25
+ export const cartMachine = createMachine({
26
+ id: 'cart',
27
+ schemas: {
28
+ context: types<{ items: Record<string, number> }>(),
29
+ events: {
30
+ ADD: types<{ sku: string }>(),
31
+ REMOVE: types<{ sku: string }>(),
32
+ CHECKOUT: types<{}>()
33
+ }
34
+ },
35
+ context: { items: {} },
36
+ initial: 'shopping',
37
+ states: {
38
+ shopping: {
39
+ on: {
40
+ ADD: ({ context, event }) => ({
41
+ context: {
42
+ items: {
43
+ ...context.items,
44
+ [event.sku]: (context.items[event.sku] ?? 0) + 1
45
+ }
46
+ }
47
+ }),
48
+ REMOVE: ({ context, event }) => {
49
+ const { [event.sku]: _removed, ...items } = context.items;
50
+ return { context: { items } };
51
+ },
52
+ CHECKOUT: ({ context }) =>
53
+ Object.keys(context.items).length
54
+ ? { target: 'checkedOut' }
55
+ : undefined
56
+ }
57
+ },
58
+ checkedOut: { type: 'final' }
59
+ }
60
+ });
61
+ ```
62
+
63
+ The implementation under test is separate code:
64
+
65
+ ```ts
66
+ export function createCart() {
67
+ const items: Record<string, number> = {};
68
+ return {
69
+ add: (sku: string) => {
70
+ items[sku] = (items[sku] ?? 0) + 1;
71
+ },
72
+ remove: (sku: string) => {
73
+ delete items[sku];
74
+ },
75
+ items: () => ({ ...items })
76
+ };
77
+ }
78
+ ```
79
+
80
+ ## Describe the events and the system under test
81
+
82
+ `events` says how to generate each event's payload. The key is the event type, and the value is a fast-check arbitrary for the rest of the event.
83
+
84
+ `sut` connects the implementation. `create()` makes a fresh cart for every run. `send` performs each event on it, and `read()` returns what to compare. `projectModel` selects the matching part of the machine's snapshot.
85
+
86
+ ```ts
87
+ import * as fc from 'fast-check';
88
+ import type { EventFrom, SnapshotFrom } from 'xstate';
89
+ import type { TestSut } from '@xstate/test';
90
+
91
+ const sku = fc.constantFrom('apple', 'pear');
92
+ const events = {
93
+ ADD: fc.record({ sku }),
94
+ REMOVE: fc.record({ sku }),
95
+ CHECKOUT: fc.constant({})
96
+ };
97
+
98
+ const cartSut: TestSut<
99
+ SnapshotFrom<typeof cartMachine>,
100
+ EventFrom<typeof cartMachine>
101
+ > = {
102
+ create: () => {
103
+ const cart = createCart();
104
+ return {
105
+ send: (event) => {
106
+ if (event.type === 'ADD') {
107
+ cart.add(event.sku);
108
+ }
109
+ if (event.type === 'REMOVE') {
110
+ cart.remove(event.sku);
111
+ }
112
+ },
113
+ read: () => cart.items()
114
+ };
115
+ },
116
+ projectModel: (snapshot) => snapshot.context.items
117
+ };
118
+ ```
119
+
120
+ ## Generate random sequences
121
+
122
+ `propertyTest()` generates random sequences of events. For every step, it applies the event to the machine, sends it to the cart, and compares `read()` with `projectModel(snapshot)`.
123
+
124
+ ```ts
125
+ import { formatTestCoverage, propertyTest } from '@xstate/test';
126
+
127
+ test('the cart matches the model', async () => {
128
+ const { coverage } = await propertyTest(cartMachine, {
129
+ seed: 1,
130
+ numRuns: 100,
131
+ events,
132
+ sut: cartSut
133
+ });
134
+ console.log(formatTestCoverage(coverage));
135
+ });
136
+ ```
137
+
138
+ The coverage report starts with one line per dimension:
139
+
140
+ ```
141
+ states: 2/2 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown
142
+ stateNodes: 3/3 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown
143
+ configurations: 2/2 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown
144
+ statuses: 2/2 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown
145
+ eventTypes: 4/4 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown
146
+ transitions: 3/3 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown
147
+ ```
148
+
149
+ All three transitions were taken. `seed` makes the run repeatable.
150
+
151
+ ## Walk every path
152
+
153
+ `testPaths()` takes the same `events` and `sut`, and walks the machine's state graph instead of generating random sequences. Each arbitrary is sampled into three payloads before traversal.
154
+
155
+ ```ts
156
+ import { testPaths } from '@xstate/test';
157
+
158
+ test('every simple path matches the model', async () => {
159
+ const { results } = await testPaths(cartMachine, {
160
+ pathGenerator: 'simple',
161
+ events,
162
+ sut: cartSut,
163
+ stopWhen: (snapshot) =>
164
+ Object.values(snapshot.context.items).some((qty) => qty >= 2)
165
+ });
166
+ expect(results).toHaveLength(15);
167
+ });
168
+ ```
169
+
170
+ - `pathGenerator: 'simple'` walks every simple path. The default, `'shortest'`, keeps only the shortest path to each state, and removing the only item leads back to a state that is already reachable, so it never takes `REMOVE`.
171
+ - `stopWhen` stops expanding a state once a quantity reaches 2. Quantities grow without bound, so the graph needs a bound.
172
+
173
+ Use `testPaths()` when the reachable graph is finite and you want every path through it. Use `propertyTest()` when payloads, ordering, or timing matter.
174
+
175
+ ### Generate paths without running them
176
+
177
+ `xstate/graph` generates paths and does not run them. `getShortestPaths(logic, options)`, `getSimplePaths(logic, options)`, and `getPathsFromEvents(logic, events, options)` return `{ state, steps, weight }` objects. Pass any of them to `testPaths()` to run them against the implementation:
178
+
179
+ ```ts
180
+ import { getShortestPaths } from 'xstate/graph';
181
+
182
+ const paths = getShortestPaths(cartMachine, {
183
+ events: {
184
+ ADD: [{ sku: 'apple' }, { sku: 'pear' }],
185
+ REMOVE: [{ sku: 'apple' }, { sku: 'pear' }]
186
+ },
187
+ stopWhen: (snapshot) =>
188
+ Object.values(snapshot.context.items).some((qty) => qty >= 2)
189
+ });
190
+
191
+ await testPaths(cartMachine, { paths, sut: cartSut });
192
+ ```
193
+
194
+ `ADD` can be sent any number of times, so `stopWhen` bounds the traversal the same way it does for `testPaths()`.
195
+
196
+ For `getShortestPaths()`, `getSimplePaths()`, and `getAdjacencyMap()`, provide cases for every known event type with required payload fields. A keyed `events` map takes nonempty arrays of payloads, without `type`. Events without required payload fields retain their default samples. Map mode also retains invoke completions, errors, and delayed events.
197
+
198
+ Unconfigured wildcard descriptors retain their default samples alongside concrete event cases. Use an event array to restrict traversal to supplied concrete events.
199
+
200
+ A case generator receives the current snapshot and runs only where its event type matches an active transition. It must return at least one payload:
201
+
202
+ ```ts
203
+ import { getShortestPaths } from 'xstate/graph';
204
+
205
+ const paths = getShortestPaths(cartMachine, {
206
+ events: {
207
+ ADD: [{ sku: 'apple' }],
208
+ REMOVE: (snapshot) => [
209
+ { sku: Object.keys(snapshot.context.items)[0] ?? 'apple' }
210
+ ]
211
+ },
212
+ stopWhen: (snapshot) => Object.values(snapshot.context.items).some((quantity) => quantity >= 2)
213
+ });
214
+ ```
215
+
216
+ An event array or a callback returning events still replaces all defaults. Its element types must include every event type that requires a payload. Include synthetic events explicitly when using this mode, for example with `getAllOwnEvents(snapshot)`. A broadly annotated array can declare event variants it never returns; TypeScript cannot prove its runtime contents.
217
+
218
+ `getPathsFromEvents()` replays the supplied typed sequence and does not require cases for unrelated events.
219
+
220
+ Let discovery functions infer their type arguments when supplying event lists. Custom callbacks annotated as `PathGenerator` use the same required-case checks.
221
+
222
+ Traversal covers the supplied samples, not every possible payload. TypeScript event types are erased at runtime; JavaScript callers must supply payload cases explicitly. Traversal does not infer required fields from erased types or validate payloads against schemas. Empty case arrays throw when their event type is applicable. Transition exceptions abort path discovery with the failing state, event, and original error as `cause`.
223
+
224
+ The default traversal key includes state value, nonempty root context, state inputs and remembered history. A custom `serializeState` deliberately identifies snapshots as the same exploration state; preserve every distinction that can change the behavior being checked. Single-machine traversal does not explore child actor execution or timer interleavings.
225
+
226
+ Static directed graphs omit function transitions whose targets require execution and report them through `analysis.diagnostics`; `analysis.transitionTargetsComplete` is false. Microstep inspection records their resolved targets instead.
227
+
228
+ Graph traversal executes transition functions. If one throws, `getAdjacencyMap()`, `getShortestPaths()`, `getSimplePaths()` and `getPathsFromEvents()` throw an error that identifies the serialized source state and event. The original thrown value is available as `error.cause`. Payload-dependent transitions need representative events through the `events` option. A transition that returns `undefined` for a sample is refused; the returned paths only describe states reachable with the supplied samples.
229
+
230
+ `xstate/graph` in v5 also exported `createTestModel` and `TestModel`. v6 removes them; `testPaths()` replaces `path.test()`.
231
+
232
+ ## Read a failure
233
+
234
+ Change `remove` so that it sets the quantity of a SKU in the cart to zero instead of deleting it:
235
+
236
+ ```ts
237
+ remove: (sku: string) => {
238
+ if (sku in items) {
239
+ items[sku] = 0;
240
+ }
241
+ },
242
+ ```
243
+
244
+ `propertyTest()` now throws a `ModelTestFailureError`. fast-check shrinks the failing sequence to the shortest one it finds, and the message shows each step:
245
+
246
+ ```
247
+ Property observation diverged
248
+ Reproduce: seed 1, path "1:2:1:2:3", replayPath "N:B"
249
+ Fixture: failure.fixture (replayTest)
250
+ Shrunk 4 time(s)
251
+
252
+ start {"value":"shopping","context":{"items":{}}}
253
+ 1. generator ADD {"sku":"pear"} -> {"value":"shopping","context":{"items":{"pear":1}}}
254
+ 2. generator REMOVE {"sku":"pear"} -> {"value":"shopping","context":{"items":{}}}
255
+ sut diverged
256
+ model: {}
257
+ observed: {"pear":0}
258
+ ```
259
+
260
+ The first line is `failure.summary`. `Reproduce` lists the fast-check `seed`, `path`, and `replayPath` that rerun the same counterexample, and `Shrunk` counts the shrinking steps fast-check took to reach it. Each numbered line is a step: where the event came from (`generator` for a generated event), the event, and the model's `{ value, context }` after it. Step 2 is the divergence: after `REMOVE pear`, the machine's projection is `{}` and the cart's is `{"pear":0}`.
261
+
262
+ ## Replay a failure
263
+
264
+ `failure.fixture` is a JSON record of the failing sequence. Commit it, and replay it with `replayTest()` without generating anything:
265
+
266
+ ```ts
267
+ import { replayTest, type TestFixture } from '@xstate/test';
268
+ import fixture from './cart-remove.fixture.json';
269
+
270
+ test('regression: removing an item', async () => {
271
+ await replayTest(cartMachine, fixture as TestFixture, {
272
+ sut: cartSut,
273
+ expect: 'pass'
274
+ });
275
+ });
276
+ ```
277
+
278
+ With `expect: 'pass'`, the replay must complete without a failure. The default, `expect: 'failure'`, expects the recorded failure to happen again, and throws `ReplayNotReproducedError` when it does not.
279
+
280
+ To save failures without writing any code, pass `failures: true`. A failing campaign writes its fixture to `.xstate-test/`, and the next campaign replays the saved fixtures before it generates anything. A fixture that no longer fails is deleted.
281
+
282
+ ## Gate CI on coverage
283
+
284
+ `assertTestCoverage()` throws when a dimension's covered ratio is below a threshold. The error message contains the full report.
285
+
286
+ ```ts
287
+ import { assertTestCoverage } from '@xstate/test';
288
+
289
+ const { coverage } = await propertyTest(cartMachine, { events, sut: cartSut });
290
+ assertTestCoverage(coverage, { transitions: 1, stateNodes: 1 });
291
+ ```
292
+
293
+ To stop generating as soon as coverage is reached, pass `until: { transitions: 1 }` and a `maxRuns` budget. `formatTestCoverageJUnit()`, `formatTestCoverageHTML()`, and `testCoverageToJSON()` write the same coverage as CI artifacts.
294
+
295
+ ## Invoked actors and delays
296
+
297
+ By default the machine is stepped with [`transition()`](utilities.md), so invoked actors never start and `after` delays never fire. Set `mode: 'executed'` to run it as an actor on a simulated clock, and replace each service with a generated outcome. Here `orderMachine` invokes a `chargeCard` actor in its `charging` state and leaves that state `after` 5 seconds:
298
+
299
+ ```ts
300
+ await propertyTest(orderMachine, {
301
+ mode: 'executed',
302
+ outcomes: {
303
+ chargeCard: fc.oneof(
304
+ fc.record({ ok: fc.constant(true as const), output: fc.record({ id: fc.string() }) }),
305
+ fc.record({ ok: fc.constant(false as const), error: fc.constant('declined') })
306
+ )
307
+ },
308
+ events: { SUBMIT: fc.constant({}) },
309
+ commands: { advance: fc.integer({ min: 1_000, max: 10_000 }) }
310
+ });
311
+ ```
312
+
313
+ fast-check chooses whether each charge succeeds or fails, when the result arrives, and how far the clock moves, and shrinks all three. No real service is called.
314
+
315
+ ## What next?
316
+
317
+ - [Work through the full cart example](https://github.com/statelyai/xstate/tree/next/examples/property-testing-cart), including invoked actors and a replayed failure.
318
+ - [Test a web page with Playwright](https://github.com/statelyai/xstate/tree/next/packages/xstate-test#test-a-web-page-with-playwright).
319
+ - [Derive event generators from Zod or Effect schemas](https://github.com/statelyai/xstate/tree/next/packages/xstate-test#derive-event-generators-from-schemas).
320
+ - [Test transitions and actors directly](testing.md).
321
+ - [Work through the checkout example](https://github.com/statelyai/xstate/tree/next/examples/model-based-testing), which runs every simple path and random sequences against a plain class.
@@ -0,0 +1,40 @@
1
+ ---
2
+ title: Model application behavior
3
+ description: Turn requirements into states, events and transitions.
4
+ ---
5
+
6
+ Model the behavior before writing implementation code.
7
+
8
+ ## List the events
9
+
10
+ Write down the things that can happen: submit, succeed, fail, retry and cancel.
11
+
12
+ ## Identify meaningful states
13
+
14
+ Ask what changes how the system responds to an event. A form may be `editing`, `submitting`, `succeeded` or `failed`.
15
+
16
+ Avoid using context values as hidden states. If `isLoading` changes which events are allowed, `loading` is probably a state.
17
+
18
+ ## Connect states with events
19
+
20
+ ```text
21
+ editing --submit--> submitting
22
+ submitting --resolved--> succeeded
23
+ submitting --rejected--> failed
24
+ failed --retry--> submitting
25
+ submitting --cancel--> editing
26
+ ```
27
+
28
+ ## Check the model
29
+
30
+ Look for states with no way in or out, forbidden events, async work without failure behavior, boolean combinations, and behavior that needs another actor.
31
+
32
+ Implement the smallest useful model first. Add hierarchy and actors when the model needs those boundaries.
33
+
34
+ ## Real examples
35
+
36
+ For a support ticket, start with `open`, `waitingForCustomer`, `resolved` and `closed`. Events such as `requestInfo`, `reply`, `resolve` and `reopen` show which status changes are allowed.
37
+
38
+ For an order, start with `draft`, `submitted`, `paid`, `shipped` and `canceled`. Treat payment and shipping as child actors when they need separate retries, timeouts or persistence.
39
+
40
+ If two parts can change independently, consider parallel states. If one part has its own lifecycle, consider an actor.
@@ -0,0 +1,182 @@
1
+ ---
2
+ title: Parallel states
3
+ description: Keep independent regions of a state active at the same time.
4
+ ---
5
+
6
+ A parallel state is active in all of its regions at once. Each child of a `type: 'parallel'` state is a region, and every region is entered when the parallel state is entered.
7
+
8
+ ```ts
9
+ active: {
10
+ type: 'parallel',
11
+ states: {
12
+ playback: {
13
+ initial: 'stopped',
14
+ states: { stopped: { on: { play: { target: 'playing' } } }, playing: {} }
15
+ },
16
+ volume: {
17
+ initial: 'audible',
18
+ states: { audible: { on: { mute: { target: 'muted' } } }, muted: {} }
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ Muting audio does not change playback, and pausing playback does not change volume. Modeling these as one flat state would require `playingMuted`, `stoppedMuted`, `playingAudible` and `stoppedAudible`. Parallel states avoid that combinatorial growth.
25
+
26
+ A parallel state has no `initial`. Each region that has child states must declare its own `initial`, or machine creation throws.
27
+
28
+ ## State value
29
+
30
+ The state value of a parallel state is an object keyed by region.
31
+
32
+ ```ts
33
+ actor.getSnapshot().value;
34
+ // { active: { playback: 'playing', volume: 'muted' } }
35
+ ```
36
+
37
+ Nested parallel states nest further. A region with no child states appears as `{}` rather than a string.
38
+
39
+ `matches` is a prefix match, so a partial object matches while other regions are left unnamed.
40
+
41
+ ```ts
42
+ snapshot.matches({ active: { playback: 'playing' } }); // true
43
+ snapshot.matches('active.playback.playing'); // true
44
+ ```
45
+
46
+ > **Warning:** Because `matches` only checks the part you name, it cannot assert that nothing else is active. Compare `snapshot.value` when you need the whole configuration.
47
+
48
+ ## One event, every region
49
+
50
+ An event is offered to every active region. A single event can move several regions in the same step.
51
+
52
+ ```ts
53
+ active: {
54
+ type: 'parallel',
55
+ states: {
56
+ playback: { initial: 'playing', states: { playing: { on: { interrupt: { target: 'paused' } } }, paused: {} } },
57
+ volume: { initial: 'audible', states: { audible: { on: { interrupt: { target: 'muted' } } }, muted: {} } }
58
+ }
59
+ }
60
+ // after `interrupt`: { playback: 'paused', volume: 'muted' }
61
+ ```
62
+
63
+ Regions that do not handle the event are untouched, and an event no region handles changes nothing. A transition from one region into another exits only the target's region; the source region stays where it is.
64
+
65
+ ## Completion
66
+
67
+ A parallel state completes only when every region has reached a [final state](final-states.md). Its `onDone` transition is then taken, with an output object keyed by region.
68
+
69
+ ```ts
70
+ upload: {
71
+ type: 'parallel',
72
+ states: {
73
+ transfer: {
74
+ initial: 'sending',
75
+ states: { sending: {}, sent: { type: 'final', output: { url: '/file.png' } } }
76
+ },
77
+ scan: {
78
+ initial: 'scanning',
79
+ states: { scanning: {}, scanned: { type: 'final', output: { safe: true } } }
80
+ }
81
+ },
82
+ onDone: ({ event }) => ({
83
+ target: 'ready',
84
+ context: { url: event.output.transfer.url }
85
+ })
86
+ }
87
+ ```
88
+
89
+ Every region has a key in that object; regions whose final state declares no `output` contribute `undefined`.
90
+
91
+ ## Targeting several regions at once
92
+
93
+ A transition can name one target per region by passing an array of targets.
94
+
95
+ ```ts
96
+ on: {
97
+ reset: { target: ['#player.active.playback.stopped', '#player.active.volume.audible'] }
98
+ }
99
+ ```
100
+
101
+ Relative paths work the same way: `target: ['playback.stopped', 'volume.audible']`. Regions not named keep their current state.
102
+
103
+ The target set must be a legal configuration: the targets must be in different regions of a common parallel ancestor. Two targets in the same region throw at machine creation, not at send time.
104
+
105
+ With typed setup state schemas, one `input` value is shared by every target in
106
+ the set and must contain the fields required by each target. Inputs for
107
+ descendants entered through a composite or parallel state's normal `initial`
108
+ transitions remain declared on those initial transitions.
109
+
110
+ ## Cross-region conditions
111
+
112
+ Use `self.getSnapshot().matches(...)` inside a [transition function](guards.md) to read another region.
113
+
114
+ ```ts
115
+ play: ({ self }) => {
116
+ if (self.getSnapshot().matches({ volume: 'muted' })) return;
117
+ return { target: 'playing' };
118
+ }
119
+ ```
120
+
121
+ `matches(value)` accepts a path (`'volume.muted'`) or a state-value object. Keep these checks rare. Regions that constantly inspect each other are usually better modeled as a single region.
122
+
123
+ ## Parallel regions or spawned actors
124
+
125
+ Use parallel regions when the concerns are part of the same unit of behavior, react to the same events, and complete together: playback and volume of one player, or the transfer and virus scan of one upload.
126
+
127
+ Use [spawned actors](spawn.md) when the concerns have independent lifetimes, arrive in unknown numbers, or own their own data: one actor per file in an upload queue, or per row in an editable table. Regions are fixed at design time; actors are created and stopped at runtime.
128
+
129
+ Common uses: a media player with independent playback, volume and subtitle regions; a checkout tracking payment authorization and address validation before it can proceed; a multi-step form tracking the current step alongside autosave status.
130
+
131
+ ## TypeScript
132
+
133
+ Region keys are inferred from `states`, so `snapshot.value` and `matches` are typed against the real region structure and a misspelled region is a type error. `onDone` on a parallel state receives a done event whose `output` is an object keyed by region. With `setup({ states })`, declare the aggregate explicitly with the parallel state's `schemas.output` when the region contract needs to be available before the machine config is written.
134
+
135
+ You can declare the parallel shape in `setup(...)` and fill in behavior in
136
+ `createMachine(...)`:
137
+
138
+ ```ts
139
+ const playerSetup = setup({
140
+ states: {
141
+ active: {
142
+ type: 'parallel',
143
+ states: { playback: {}, volume: {} }
144
+ }
145
+ }
146
+ });
147
+
148
+ playerSetup.createMachine({
149
+ initial: 'active',
150
+ states: {
151
+ active: {
152
+ states: {
153
+ playback: { initial: 'playing', states: { playing: {} } },
154
+ volume: { initial: 'audible', states: { audible: {} } }
155
+ }
156
+ }
157
+ }
158
+ });
159
+ ```
160
+
161
+ The setup contract supplies `type: 'parallel'`, so `active` cannot define an
162
+ `initial` state and its state value is typed as an object of regions.
163
+
164
+ ## Parallel states cheatsheet
165
+
166
+ ```ts
167
+ // declaration
168
+ active: { type: 'parallel', states: { playback: { initial: 'stopped', states: {} }, volume: {} } }
169
+
170
+ // state value
171
+ snapshot.value; // { active: { playback: 'stopped', volume: 'audible' } }
172
+ snapshot.matches({ active: { volume: 'audible' } });
173
+
174
+ // completion
175
+ onDone: ({ event }) => ({ target: 'ready' }) // event.output === { region: output }
176
+
177
+ // multiple targets across regions
178
+ on: { reset: { target: ['playback.stopped', 'volume.audible'] } }
179
+
180
+ // cross-region condition
181
+ self.getSnapshot().matches('volume.muted');
182
+ ```
@@ -0,0 +1,120 @@
1
+ ---
2
+ title: Persist and restore actors
3
+ description: Save an actor's state as it changes and restore it on the next visit.
4
+ ---
5
+
6
+ This guide keeps a checkout actor alive across page reloads. It saves on every change, restores on startup, and discards stored state it cannot use.
7
+
8
+ ## 1. Save the snapshot when it changes
9
+
10
+ `actor.getPersistedSnapshot()` returns a serializable value that includes persisted child actors. Subscribe to the actor and write it out.
11
+
12
+ Writing on every snapshot is wasteful, so debounce the write with a timer.
13
+
14
+ ```ts
15
+ import { Actor, createActor } from 'xstate';
16
+
17
+ const STORAGE_KEY = 'checkout';
18
+ const VERSION = '2';
19
+
20
+ function saveOnChange(actor: Actor<typeof checkoutMachine>) {
21
+ let timeout: ReturnType<typeof setTimeout> | undefined;
22
+
23
+ const subscription = actor.subscribe(() => {
24
+ clearTimeout(timeout);
25
+
26
+ timeout = setTimeout(() => {
27
+ localStorage.setItem(
28
+ STORAGE_KEY,
29
+ JSON.stringify({
30
+ version: VERSION,
31
+ snapshot: actor.getPersistedSnapshot()
32
+ })
33
+ );
34
+ }, 250);
35
+ });
36
+
37
+ return () => {
38
+ clearTimeout(timeout);
39
+ subscription.unsubscribe();
40
+ };
41
+ }
42
+ ```
43
+
44
+ The version stamp is written alongside the snapshot, not inside it. The next step uses it to decide whether the stored data still fits the machine.
45
+
46
+ ## 2. Read and validate what was stored
47
+
48
+ Stored data is untrusted input. It may be missing, truncated, written by an older build, or edited by hand.
49
+
50
+ Validate it before restoring: parse inside `try`, then check the version. Return `undefined` when anything does not fit.
51
+
52
+ ```ts
53
+ function loadSnapshot() {
54
+ const stored = localStorage.getItem(STORAGE_KEY);
55
+
56
+ if (!stored) return undefined;
57
+
58
+ try {
59
+ const { version, snapshot } = JSON.parse(stored);
60
+
61
+ if (version !== VERSION) {
62
+ localStorage.removeItem(STORAGE_KEY);
63
+ return undefined;
64
+ }
65
+
66
+ return snapshot;
67
+ } catch {
68
+ localStorage.removeItem(STORAGE_KEY);
69
+ return undefined;
70
+ }
71
+ }
72
+ ```
73
+
74
+ > **Note:** A snapshot that cannot represent a state of the machine (not an object, no valid `value`, a `value` naming states the machine does not have, malformed children or timers, or a local child source that cannot be restored) restores to an actor whose snapshot has `status: 'error'` and an `InvalidSnapshotError` as `error`; `restoreActor(...)` does not throw. Unknown fields are ignored. Validating first lets you fall back to the initial state instead.
75
+
76
+ ## 3. Restore on startup
77
+
78
+ Pass the snapshot to `restoreActor(...)` from `xstate/persist`. When there is nothing to restore, create the actor with `createActor(...)` so it starts from its initial state.
79
+
80
+ ```ts
81
+ import { restoreActor } from 'xstate/persist';
82
+
83
+ const persisted = loadSnapshot();
84
+ const checkout = (
85
+ persisted
86
+ ? restoreActor(checkoutMachine, persisted)
87
+ : createActor(checkoutMachine)
88
+ ).start();
89
+
90
+ const stopSaving = saveOnChange(checkout);
91
+ ```
92
+
93
+ Clear the stored value when the flow finishes, so a completed checkout does not come back on the next visit.
94
+
95
+ ```ts
96
+ checkout.subscribe((snapshot) => {
97
+ if (snapshot.status === 'done') {
98
+ localStorage.removeItem(STORAGE_KEY);
99
+ }
100
+ });
101
+ ```
102
+
103
+ ## 4. Keep old snapshots working
104
+
105
+ Discarding an old snapshot is the right default for a cart or a wizard. When users must not lose their place, migrate instead of discarding: register the machine versions you retain and convert stored snapshots to the current one with [`machineVersions(...)`](persistence.md#migrate-machine-versions).
106
+
107
+ Two rules apply to either choice:
108
+
109
+ - Bump the version whenever states, context or child actor logic change.
110
+ - Keep live resources out of context. Database clients, sockets and DOM nodes do not serialize. Store an ID and look the resource up again after restoring.
111
+
112
+ ## On the server
113
+
114
+ The same two calls work outside the browser: read a snapshot from your database instead of `localStorage`, and save it back after handling a request. A server actor usually lives for one request, so save once at the end rather than on every change. See [run backend workflows](backend-workflows.md).
115
+
116
+ ## What next?
117
+
118
+ - [Persistence](persistence.md) for the full API, snapshot migration and event adaptation.
119
+ - [Run backend workflows](backend-workflows.md) to resume a workflow per request.
120
+ - [Serialization](serialization.md) for what can be stored in context.