xstate 5.32.2 → 6.0.0-alpha.10
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 +25 -24
- package/dist/StateMachine-0aa98f54.development.esm.js +746 -0
- package/dist/StateMachine-aef700df.cjs.js +732 -0
- package/dist/StateMachine-d4931336.esm.js +729 -0
- package/dist/StateMachine-da872dde.development.cjs.js +749 -0
- package/dist/declarations/src/State.d.ts +11 -13
- package/dist/declarations/src/StateMachine.d.ts +40 -26
- package/dist/declarations/src/StateNode.d.ts +18 -54
- package/dist/declarations/src/actions.d.ts +14 -9
- package/dist/declarations/src/actors/callback.d.ts +42 -16
- package/dist/declarations/src/actors/index.d.ts +9 -6
- package/dist/declarations/src/actors/listener.d.ts +18 -0
- package/dist/declarations/src/actors/logic.d.ts +105 -0
- package/dist/declarations/src/actors/observable.d.ts +72 -27
- package/dist/declarations/src/actors/promise.d.ts +133 -48
- package/dist/declarations/src/actors/subscription.d.ts +22 -0
- package/dist/declarations/src/createActor.d.ts +33 -34
- package/dist/declarations/src/createMachine.d.ts +38 -7
- package/dist/declarations/src/createMachineFromConfig.d.ts +177 -0
- package/dist/declarations/src/graph/graph.d.ts +6 -4
- package/dist/declarations/src/graph/shortestPaths.d.ts +2 -2
- package/dist/declarations/src/graph/simplePaths.d.ts +2 -2
- package/dist/declarations/src/index.d.ts +13 -9
- package/dist/declarations/src/inspection.d.ts +84 -30
- package/dist/declarations/src/mapState.d.ts +4 -2
- package/dist/declarations/src/schema.types.d.ts +90 -0
- package/dist/declarations/src/serialize.d.ts +50 -0
- package/dist/declarations/src/setup.d.ts +396 -136
- package/dist/declarations/src/spawn.d.ts +7 -32
- package/dist/declarations/src/stateUtils.d.ts +22 -19
- package/dist/declarations/src/system.d.ts +8 -7
- package/dist/declarations/src/transition.d.ts +8 -5
- package/dist/declarations/src/transitionActions.d.ts +4 -0
- package/dist/declarations/src/types.d.ts +494 -429
- package/dist/declarations/src/types.v6.d.ts +423 -0
- package/dist/declarations/src/utils.d.ts +5 -3
- package/dist/index-219cb621.development.cjs.js +4476 -0
- package/dist/index-2f2fbd9b.development.esm.js +4421 -0
- package/dist/index-559ceab3.cjs.js +4437 -0
- package/dist/index-8828376f.esm.js +4382 -0
- package/dist/xstate-actors.cjs.js +12 -838
- package/dist/xstate-actors.cjs.mjs +10 -5
- package/dist/xstate-actors.development.cjs.js +12 -838
- package/dist/xstate-actors.development.cjs.mjs +10 -5
- package/dist/xstate-actors.development.esm.js +1 -836
- package/dist/xstate-actors.esm.js +1 -836
- package/dist/xstate-actors.umd.min.js +1 -1
- package/dist/xstate-actors.umd.min.js.map +1 -1
- package/dist/xstate-graph.cjs.js +18 -29
- package/dist/xstate-graph.development.cjs.js +18 -29
- package/dist/xstate-graph.development.esm.js +15 -26
- package/dist/xstate-graph.esm.js +15 -26
- package/dist/xstate-graph.umd.min.js +1 -1
- package/dist/xstate-graph.umd.min.js.map +1 -1
- package/dist/xstate.cjs.js +1477 -122
- package/dist/xstate.cjs.mjs +19 -22
- package/dist/xstate.development.cjs.js +1477 -122
- package/dist/xstate.development.cjs.mjs +19 -22
- package/dist/xstate.development.esm.js +1442 -86
- package/dist/xstate.esm.js +1442 -86
- package/dist/xstate.umd.min.js +1 -1
- package/dist/xstate.umd.min.js.map +1 -1
- package/package.json +3 -47
- package/dist/StateMachine-23c204bb.development.esm.js +0 -566
- package/dist/StateMachine-67a0f463.development.cjs.js +0 -569
- package/dist/StateMachine-94d215e3.cjs.js +0 -563
- package/dist/StateMachine-d1d80308.esm.js +0 -560
- package/dist/assign-43b1b558.development.esm.js +0 -133
- package/dist/assign-54b312bc.esm.js +0 -127
- package/dist/assign-b5bc78f7.cjs.js +0 -129
- package/dist/assign-f8f66278.development.cjs.js +0 -135
- package/dist/declarations/src/actions/assign.d.ts +0 -45
- package/dist/declarations/src/actions/cancel.d.ts +0 -39
- package/dist/declarations/src/actions/emit.d.ts +0 -44
- package/dist/declarations/src/actions/enqueueActions.d.ts +0 -57
- package/dist/declarations/src/actions/log.d.ts +0 -16
- package/dist/declarations/src/actions/raise.d.ts +0 -21
- package/dist/declarations/src/actions/send.d.ts +0 -42
- package/dist/declarations/src/actions/spawnChild.d.ts +0 -34
- package/dist/declarations/src/actions/stopChild.d.ts +0 -19
- package/dist/declarations/src/actors/transition.d.ts +0 -143
- package/dist/declarations/src/dev/index.d.ts +0 -14
- package/dist/declarations/src/guards.d.ts +0 -128
- package/dist/log-9b02c355.esm.js +0 -401
- package/dist/log-c94995c7.cjs.js +0 -409
- package/dist/log-d9f3f459.development.cjs.js +0 -437
- package/dist/log-db444cad.development.esm.js +0 -429
- package/dist/raise-235108c6.esm.js +0 -2762
- package/dist/raise-45f11c00.development.esm.js +0 -2824
- package/dist/raise-c445379d.cjs.js +0 -2817
- package/dist/raise-eca73993.development.cjs.js +0 -2879
- package/dist/xstate-actions.cjs.d.mts +0 -2
- package/dist/xstate-actions.cjs.d.ts +0 -2
- package/dist/xstate-actions.cjs.js +0 -23
- package/dist/xstate-actions.cjs.mjs +0 -14
- package/dist/xstate-actions.development.cjs.js +0 -23
- package/dist/xstate-actions.development.cjs.mjs +0 -14
- package/dist/xstate-actions.development.esm.js +0 -4
- package/dist/xstate-actions.esm.js +0 -4
- package/dist/xstate-actions.umd.min.js +0 -2
- package/dist/xstate-actions.umd.min.js.map +0 -1
- package/dist/xstate-dev.cjs.d.mts +0 -2
- package/dist/xstate-dev.cjs.d.ts +0 -2
- package/dist/xstate-dev.cjs.js +0 -48
- package/dist/xstate-dev.cjs.mjs +0 -5
- package/dist/xstate-dev.development.cjs.js +0 -51
- package/dist/xstate-dev.development.cjs.mjs +0 -5
- package/dist/xstate-dev.development.esm.js +0 -45
- package/dist/xstate-dev.esm.js +0 -42
- package/dist/xstate-dev.umd.min.js +0 -2
- package/dist/xstate-dev.umd.min.js.map +0 -1
- package/dist/xstate-guards.cjs.d.mts +0 -2
- package/dist/xstate-guards.cjs.d.ts +0 -2
- package/dist/xstate-guards.cjs.js +0 -14
- package/dist/xstate-guards.cjs.mjs +0 -7
- package/dist/xstate-guards.development.cjs.js +0 -14
- package/dist/xstate-guards.development.cjs.mjs +0 -7
- package/dist/xstate-guards.development.esm.js +0 -2
- package/dist/xstate-guards.esm.js +0 -2
- package/dist/xstate-guards.umd.min.js +0 -2
- package/dist/xstate-guards.umd.min.js.map +0 -1
|
@@ -0,0 +1,729 @@
|
|
|
1
|
+
import { P as ProcessingStatus, C as resolveReferencedActor, c as createActor, S as STATE_DELIMITER, D as mapValues, t as toArray, E as createInvokeId, F as getDelayedTransitions, G as evaluateCandidate, H as formatTransition, N as NULL_EVENT, I as toTransitionConfigArray, J as createInvokeTimeoutEvent, K as getCandidates, L as formatRouteTransitions, M as resolveStateValue, O as getAllStateNodes, f as getStateNodes, Q as createMachineSnapshot, R as isInFinalState, a as macrostep, U as transitionNode, m as matchesEventDescriptor, V as resolveActionsWithContext, b as createInitEvent, d as initialMicrostep, W as toStatePath, X as isStateId, Y as getStateNodeByPath, Z as getPersistedSnapshot, $ as $$ACTOR_TYPE } from './index-8828376f.esm.js';
|
|
2
|
+
|
|
3
|
+
function createSpawner(actorScope, {
|
|
4
|
+
machine,
|
|
5
|
+
context
|
|
6
|
+
}, event, spawnedChildren) {
|
|
7
|
+
const spawn = (src, options) => {
|
|
8
|
+
if (typeof src === 'string') {
|
|
9
|
+
const logic = resolveReferencedActor(machine, src);
|
|
10
|
+
if (!logic) {
|
|
11
|
+
throw new Error(`Actor logic '${src}' not implemented in machine '${machine.id}'`);
|
|
12
|
+
}
|
|
13
|
+
const actor = createActor(logic, {
|
|
14
|
+
id: options?.id,
|
|
15
|
+
parent: actorScope.self,
|
|
16
|
+
syncSnapshot: options?.syncSnapshot,
|
|
17
|
+
input: typeof options?.input === 'function' ? options.input({
|
|
18
|
+
context,
|
|
19
|
+
event,
|
|
20
|
+
self: actorScope.self
|
|
21
|
+
}) : options?.input,
|
|
22
|
+
src,
|
|
23
|
+
registryKey: options?.registryKey
|
|
24
|
+
});
|
|
25
|
+
spawnedChildren[actor.id] = actor;
|
|
26
|
+
return actor;
|
|
27
|
+
} else {
|
|
28
|
+
const actor = createActor(src, {
|
|
29
|
+
id: options?.id,
|
|
30
|
+
parent: actorScope.self,
|
|
31
|
+
syncSnapshot: options?.syncSnapshot,
|
|
32
|
+
input: options?.input,
|
|
33
|
+
src,
|
|
34
|
+
registryKey: options?.registryKey
|
|
35
|
+
});
|
|
36
|
+
return actor;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
return (src, options) => {
|
|
40
|
+
const actor = spawn(src, options); // TODO: fix types
|
|
41
|
+
spawnedChildren[actor.id] = actor;
|
|
42
|
+
actorScope.defer(() => {
|
|
43
|
+
if (actor._processingStatus === ProcessingStatus.Stopped) {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
actor.start();
|
|
47
|
+
});
|
|
48
|
+
return actor;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const cache = new WeakMap();
|
|
53
|
+
function memo(object, key, fn) {
|
|
54
|
+
let memoizedData = cache.get(object);
|
|
55
|
+
if (!memoizedData) {
|
|
56
|
+
memoizedData = {
|
|
57
|
+
[key]: fn()
|
|
58
|
+
};
|
|
59
|
+
cache.set(object, memoizedData);
|
|
60
|
+
} else if (!(key in memoizedData)) {
|
|
61
|
+
memoizedData[key] = fn();
|
|
62
|
+
}
|
|
63
|
+
return memoizedData[key];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const EMPTY_OBJECT = {};
|
|
67
|
+
const CHOICE_CONFIG_KEYS = ['invoke', 'after', 'on', 'entry', 'exit', 'always', 'states', 'initial', 'onDone', 'timeout', 'onTimeout', 'history', 'target', 'output'];
|
|
68
|
+
class StateNode {
|
|
69
|
+
constructor(/** The raw config used to create the machine. */
|
|
70
|
+
config, options) {
|
|
71
|
+
this.config = config;
|
|
72
|
+
/**
|
|
73
|
+
* The relative key of the state node, which represents its location in the
|
|
74
|
+
* overall state value.
|
|
75
|
+
*/
|
|
76
|
+
this.key = void 0;
|
|
77
|
+
/** The unique ID of the state node. */
|
|
78
|
+
this.id = void 0;
|
|
79
|
+
/**
|
|
80
|
+
* The type of this state node:
|
|
81
|
+
*
|
|
82
|
+
* - `'atomic'` - no child state nodes
|
|
83
|
+
* - `'compound'` - nested child state nodes (XOR)
|
|
84
|
+
* - `'parallel'` - orthogonal nested child state nodes (AND)
|
|
85
|
+
* - `'history'` - history state node
|
|
86
|
+
* - `'choice'` - pure routing decision state node
|
|
87
|
+
* - `'final'` - final state node
|
|
88
|
+
*/
|
|
89
|
+
this.type = void 0;
|
|
90
|
+
/** The string path from the root machine node to this node. */
|
|
91
|
+
this.path = void 0;
|
|
92
|
+
/** The child state nodes. */
|
|
93
|
+
this.states = void 0;
|
|
94
|
+
/**
|
|
95
|
+
* The type of history on this state node. Can be:
|
|
96
|
+
*
|
|
97
|
+
* - `'shallow'` - recalls only top-level historical state value
|
|
98
|
+
* - `'deep'` - recalls historical state value at all levels
|
|
99
|
+
*/
|
|
100
|
+
this.history = void 0;
|
|
101
|
+
/** The action(s) to be executed upon entering the state node. */
|
|
102
|
+
this.entry = void 0;
|
|
103
|
+
/** The action(s) to be executed upon exiting the state node. */
|
|
104
|
+
this.exit = void 0;
|
|
105
|
+
/** The parent state node. */
|
|
106
|
+
this.parent = void 0;
|
|
107
|
+
/** The root machine node. */
|
|
108
|
+
this.machine = void 0;
|
|
109
|
+
/**
|
|
110
|
+
* The meta data associated with this state node, which will be returned in
|
|
111
|
+
* State instances.
|
|
112
|
+
*/
|
|
113
|
+
this.meta = void 0;
|
|
114
|
+
/**
|
|
115
|
+
* The output data sent with the "xstate.done.state._id_" event if this is a
|
|
116
|
+
* final state node.
|
|
117
|
+
*/
|
|
118
|
+
this.output = void 0;
|
|
119
|
+
/**
|
|
120
|
+
* The order this state node appears. Corresponds to the implicit document
|
|
121
|
+
* order.
|
|
122
|
+
*/
|
|
123
|
+
this.order = -1;
|
|
124
|
+
this.description = void 0;
|
|
125
|
+
this.tags = [];
|
|
126
|
+
this.transitions = void 0;
|
|
127
|
+
this.always = void 0;
|
|
128
|
+
this.invoke = void 0;
|
|
129
|
+
this.on = void 0;
|
|
130
|
+
this.after = void 0;
|
|
131
|
+
this.events = void 0;
|
|
132
|
+
this.ownEvents = void 0;
|
|
133
|
+
this.parent = options._parent;
|
|
134
|
+
this.key = options._key;
|
|
135
|
+
this.machine = options._machine;
|
|
136
|
+
this.path = this.parent ? this.parent.path.concat(this.key) : [];
|
|
137
|
+
const firstStateKey = this.config.states ? Object.keys(this.config.states)[0] : undefined;
|
|
138
|
+
this.id = this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);
|
|
139
|
+
this.type = this.config.type || (firstStateKey !== undefined ? 'compound' : this.config.history ? 'history' : 'atomic');
|
|
140
|
+
this.description = this.config.description;
|
|
141
|
+
validateStateNodeConfig(this);
|
|
142
|
+
this.order = this.machine.idMap.size;
|
|
143
|
+
this.machine.idMap.set(this.id, this);
|
|
144
|
+
this.states = this.config.states ? mapValues(this.config.states, (stateConfig, key) => {
|
|
145
|
+
const stateNode = new StateNode(stateConfig, {
|
|
146
|
+
_parent: this,
|
|
147
|
+
_key: key,
|
|
148
|
+
_machine: this.machine
|
|
149
|
+
});
|
|
150
|
+
return stateNode;
|
|
151
|
+
}) : EMPTY_OBJECT;
|
|
152
|
+
if (this.type === 'compound' && !this.config.initial) {
|
|
153
|
+
throw new Error(`No initial state specified for compound state node "#${this.id}".`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// History config
|
|
157
|
+
this.history = this.config.history === true ? 'shallow' : this.config.history || false;
|
|
158
|
+
this.entry = this.config.entry;
|
|
159
|
+
this.exit = this.config.exit;
|
|
160
|
+
if (this.entry) {
|
|
161
|
+
// @ts-expect-error _special is an internal marker not on the Action type
|
|
162
|
+
this.entry._special = true;
|
|
163
|
+
}
|
|
164
|
+
if (this.exit) {
|
|
165
|
+
// @ts-expect-error _special is an internal marker not on the Action type
|
|
166
|
+
this.exit._special = true;
|
|
167
|
+
}
|
|
168
|
+
this.meta = this.config.meta;
|
|
169
|
+
this.output = this.type === 'final' || !this.parent ? this.config.output : undefined;
|
|
170
|
+
this.tags = toArray(config.tags).slice();
|
|
171
|
+
this.invoke = toArray(this.config.invoke).map((invokeConfig, i) => {
|
|
172
|
+
const {
|
|
173
|
+
src,
|
|
174
|
+
registryKey
|
|
175
|
+
} = invokeConfig;
|
|
176
|
+
const invokeId = createInvokeId(this.id, i);
|
|
177
|
+
const resolvedId = invokeConfig.id ?? invokeId;
|
|
178
|
+
// Referenced (string) actors keep their logical name so persisted
|
|
179
|
+
// snapshots reference `src: 'fetchUser'` rather than a positional id;
|
|
180
|
+
// only inline logic gets the synthetic source name.
|
|
181
|
+
const sourceName = typeof src === 'string' ? src : `xstate.invoke.${invokeId}`;
|
|
182
|
+
return {
|
|
183
|
+
...invokeConfig,
|
|
184
|
+
src: sourceName,
|
|
185
|
+
logic: src,
|
|
186
|
+
id: resolvedId,
|
|
187
|
+
registryKey
|
|
188
|
+
};
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** @internal */
|
|
193
|
+
_initialize() {
|
|
194
|
+
this.after = getDelayedTransitions(this);
|
|
195
|
+
this.transitions = formatTransitions(this);
|
|
196
|
+
if (this.type === 'choice') {
|
|
197
|
+
this.always = formatChoiceTransitions(this);
|
|
198
|
+
} else if (this.config.always) {
|
|
199
|
+
this.always = mapTransitionConfigs(this.config.always, transition => formatTransition(this, NULL_EVENT, transition));
|
|
200
|
+
}
|
|
201
|
+
for (const key of Object.keys(this.states)) {
|
|
202
|
+
this.states[key]._initialize();
|
|
203
|
+
}
|
|
204
|
+
this._refreshEventMetadata();
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** @internal */
|
|
208
|
+
_refreshEventMetadata() {
|
|
209
|
+
const on = {};
|
|
210
|
+
const ownEvents = [];
|
|
211
|
+
for (const [descriptor, transitions] of this.transitions) {
|
|
212
|
+
on[descriptor] = transitions.slice();
|
|
213
|
+
if (transitions.some(transition => transition.target || transition.reenter || transition.to)) {
|
|
214
|
+
ownEvents.push(descriptor);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
this.on = on;
|
|
218
|
+
this.ownEvents = ownEvents;
|
|
219
|
+
const events = new Set(ownEvents);
|
|
220
|
+
for (const state of Object.values(this.states)) {
|
|
221
|
+
for (const event of state.events) {
|
|
222
|
+
events.add(event);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
this.events = Array.from(events);
|
|
226
|
+
}
|
|
227
|
+
get initial() {
|
|
228
|
+
return memo(this, 'initial', () => formatInitialTransition(this, this.config.initial));
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** @internal */
|
|
232
|
+
next(snapshot, event, self) {
|
|
233
|
+
const eventType = event.type;
|
|
234
|
+
const candidates = memo(this, `candidates-${eventType}`, () => getCandidates(this, eventType));
|
|
235
|
+
for (const candidate of candidates) {
|
|
236
|
+
const guardPassed = evaluateCandidate(candidate, event, snapshot, this, self);
|
|
237
|
+
if (guardPassed) {
|
|
238
|
+
return [candidate];
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return undefined;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
function validateStateNodeConfig(stateNode) {
|
|
245
|
+
const config = stateNode.config;
|
|
246
|
+
if (stateNode.type !== 'choice') {
|
|
247
|
+
if (config.choice !== undefined) {
|
|
248
|
+
throw new Error(`State "${stateNode.id}" has \`choice\`, but \`choice\` can only be used with \`type: 'choice'\`.`);
|
|
249
|
+
}
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
if (typeof config.choice !== 'function') {
|
|
253
|
+
throw new Error(`Choice state "${stateNode.id}" must declare a \`choice\` function.`);
|
|
254
|
+
}
|
|
255
|
+
for (const key of CHOICE_CONFIG_KEYS) {
|
|
256
|
+
if (config[key] !== undefined) {
|
|
257
|
+
throw new Error(`Choice state "${stateNode.id}" cannot declare \`${key}\`.`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
function formatChoiceTransitions(stateNode) {
|
|
262
|
+
const choice = stateNode.config.choice;
|
|
263
|
+
const validateChoiceResult = result => {
|
|
264
|
+
if (!result || result.target === undefined) {
|
|
265
|
+
throw new Error(`Choice state "${stateNode.id}" must resolve to a target.`);
|
|
266
|
+
}
|
|
267
|
+
for (const key of ['actions', 'to', 'context']) {
|
|
268
|
+
if (result[key] !== undefined) {
|
|
269
|
+
throw new Error(`Choice state "${stateNode.id}" cannot declare \`${key}\` on a choice.`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return result;
|
|
273
|
+
};
|
|
274
|
+
return [formatTransition(stateNode, NULL_EVENT, {
|
|
275
|
+
to: args => validateChoiceResult(choice(args))
|
|
276
|
+
})];
|
|
277
|
+
}
|
|
278
|
+
function mapTransitionConfigs(transitionsConfig, mapper) {
|
|
279
|
+
const transitionConfigs = toTransitionConfigArray(transitionsConfig);
|
|
280
|
+
const transitions = new Array(transitionConfigs.length);
|
|
281
|
+
for (let i = 0; i < transitionConfigs.length; i++) {
|
|
282
|
+
transitions[i] = mapper(transitionConfigs[i]);
|
|
283
|
+
}
|
|
284
|
+
return transitions;
|
|
285
|
+
}
|
|
286
|
+
function formatTransitions(stateNode) {
|
|
287
|
+
const transitions = new Map();
|
|
288
|
+
if (stateNode.config.on) {
|
|
289
|
+
for (const descriptor of Object.keys(stateNode.config.on)) {
|
|
290
|
+
if (descriptor === NULL_EVENT) {
|
|
291
|
+
throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');
|
|
292
|
+
}
|
|
293
|
+
const transitionsConfig = stateNode.config.on[descriptor];
|
|
294
|
+
transitions.set(descriptor, mapTransitionConfigs(transitionsConfig, transition => formatTransition(stateNode, descriptor, transition)));
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
if (stateNode.config.onDone) {
|
|
298
|
+
const descriptor = `xstate.done.state.${stateNode.id}`;
|
|
299
|
+
transitions.set(descriptor, mapTransitionConfigs(stateNode.config.onDone, transition => formatTransition(stateNode, descriptor, transition)));
|
|
300
|
+
}
|
|
301
|
+
const createCancelInvokeTimeoutTransition = (descriptor, timeoutEventType) => formatTransition(stateNode, descriptor, {
|
|
302
|
+
to: (_args, enq) => {
|
|
303
|
+
enq.cancel(timeoutEventType);
|
|
304
|
+
return {};
|
|
305
|
+
}
|
|
306
|
+
});
|
|
307
|
+
const formatInvokeCompletionTransition = (descriptor, transitionConfig, timeoutEventType) => {
|
|
308
|
+
const {
|
|
309
|
+
target,
|
|
310
|
+
to,
|
|
311
|
+
reenter,
|
|
312
|
+
...rest
|
|
313
|
+
} = transitionConfig;
|
|
314
|
+
return formatTransition(stateNode, descriptor, {
|
|
315
|
+
...rest,
|
|
316
|
+
reenter,
|
|
317
|
+
to: (args, enq) => {
|
|
318
|
+
if (to) {
|
|
319
|
+
let didEnqueue = false;
|
|
320
|
+
const trackingEnqueue = new Proxy(enq, {
|
|
321
|
+
apply(target, thisArg, argArray) {
|
|
322
|
+
didEnqueue = true;
|
|
323
|
+
return Reflect.apply(target, thisArg, argArray);
|
|
324
|
+
},
|
|
325
|
+
get(target, prop, receiver) {
|
|
326
|
+
const value = Reflect.get(target, prop, receiver);
|
|
327
|
+
if (typeof value !== 'function') {
|
|
328
|
+
return value;
|
|
329
|
+
}
|
|
330
|
+
return (...argArray) => {
|
|
331
|
+
didEnqueue = true;
|
|
332
|
+
return value.apply(target, argArray);
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
const result = to(args, trackingEnqueue);
|
|
337
|
+
if (result !== undefined || didEnqueue) {
|
|
338
|
+
enq.cancel(timeoutEventType);
|
|
339
|
+
}
|
|
340
|
+
return result;
|
|
341
|
+
}
|
|
342
|
+
enq.cancel(timeoutEventType);
|
|
343
|
+
return {
|
|
344
|
+
target,
|
|
345
|
+
reenter
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
};
|
|
350
|
+
for (const invokeDef of stateNode.invoke) {
|
|
351
|
+
const invokeTimeoutEventType = invokeDef.timeout !== undefined ? createInvokeTimeoutEvent(invokeDef.id).type : undefined;
|
|
352
|
+
if (invokeDef.onDone) {
|
|
353
|
+
const descriptor = `xstate.done.actor.${invokeDef.id}`;
|
|
354
|
+
const invokeDoneTransitions = mapTransitionConfigs(invokeDef.onDone, transition => invokeTimeoutEventType ? formatInvokeCompletionTransition(descriptor, transition, invokeTimeoutEventType) : formatTransition(stateNode, descriptor, transition));
|
|
355
|
+
if (invokeTimeoutEventType) {
|
|
356
|
+
invokeDoneTransitions.push(createCancelInvokeTimeoutTransition(descriptor, invokeTimeoutEventType));
|
|
357
|
+
}
|
|
358
|
+
transitions.set(descriptor, invokeDoneTransitions);
|
|
359
|
+
} else if (invokeTimeoutEventType) {
|
|
360
|
+
const descriptor = `xstate.done.actor.${invokeDef.id}`;
|
|
361
|
+
transitions.set(descriptor, [createCancelInvokeTimeoutTransition(descriptor, invokeTimeoutEventType)]);
|
|
362
|
+
}
|
|
363
|
+
if (invokeDef.onError) {
|
|
364
|
+
const descriptor = `xstate.error.actor.${invokeDef.id}`;
|
|
365
|
+
transitions.set(descriptor, mapTransitionConfigs(invokeDef.onError, transition => invokeTimeoutEventType ? formatInvokeCompletionTransition(descriptor, transition, invokeTimeoutEventType) : formatTransition(stateNode, descriptor, transition)));
|
|
366
|
+
}
|
|
367
|
+
if (invokeDef.onSnapshot) {
|
|
368
|
+
const descriptor = `xstate.snapshot.${invokeDef.id}`;
|
|
369
|
+
transitions.set(descriptor, mapTransitionConfigs(invokeDef.onSnapshot, transition => formatTransition(stateNode, descriptor, transition)));
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
for (const delayedTransition of stateNode.after) {
|
|
373
|
+
let existing = transitions.get(delayedTransition.eventType);
|
|
374
|
+
if (!existing) {
|
|
375
|
+
existing = [];
|
|
376
|
+
transitions.set(delayedTransition.eventType, existing);
|
|
377
|
+
}
|
|
378
|
+
existing.push(delayedTransition);
|
|
379
|
+
}
|
|
380
|
+
return transitions;
|
|
381
|
+
}
|
|
382
|
+
function formatInitialTransition(stateNode, _target) {
|
|
383
|
+
const targetString = typeof _target === 'object' && _target !== null ? _target.target : _target;
|
|
384
|
+
const input = typeof _target === 'object' && _target !== null ? _target.input : undefined;
|
|
385
|
+
const resolvedTarget = typeof targetString === 'string' ? stateNode.states[targetString] : undefined;
|
|
386
|
+
if (!resolvedTarget && targetString) {
|
|
387
|
+
throw new Error(`Initial state node "${targetString}" not found on parent state node #${stateNode.id}`);
|
|
388
|
+
}
|
|
389
|
+
const transition = {
|
|
390
|
+
source: stateNode,
|
|
391
|
+
target: resolvedTarget ? [resolvedTarget] : undefined,
|
|
392
|
+
input
|
|
393
|
+
};
|
|
394
|
+
return transition;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const STATE_IDENTIFIER = '#';
|
|
398
|
+
class StateMachine {
|
|
399
|
+
constructor(/** The raw config used to create the machine. */
|
|
400
|
+
config, implementations) {
|
|
401
|
+
this.config = config;
|
|
402
|
+
/** The machine's own version. */
|
|
403
|
+
this.version = void 0;
|
|
404
|
+
this.schemas = void 0;
|
|
405
|
+
this.implementations = void 0;
|
|
406
|
+
/** Runtime options for machine execution. */
|
|
407
|
+
this.options = void 0;
|
|
408
|
+
/** @internal */
|
|
409
|
+
this.idMap = new Map();
|
|
410
|
+
this.root = void 0;
|
|
411
|
+
this.id = void 0;
|
|
412
|
+
this.states = void 0;
|
|
413
|
+
this.events = void 0;
|
|
414
|
+
this.internalEventDescriptors = void 0;
|
|
415
|
+
/**
|
|
416
|
+
* The original JSON definition this machine was created from (set by
|
|
417
|
+
* `createMachineFromConfig`), if any. Used by `serializeMachine` for lossless
|
|
418
|
+
* round-trips.
|
|
419
|
+
*
|
|
420
|
+
* @internal
|
|
421
|
+
*/
|
|
422
|
+
this._json = void 0;
|
|
423
|
+
this.id = config.id || '(machine)';
|
|
424
|
+
this.implementations = {
|
|
425
|
+
actorSources: config.actorSources ?? {},
|
|
426
|
+
actions: config.actions ?? {},
|
|
427
|
+
delays: config.delays ?? {},
|
|
428
|
+
guards: config.guards ?? {},
|
|
429
|
+
...implementations
|
|
430
|
+
};
|
|
431
|
+
this.version = this.config.version;
|
|
432
|
+
this.schemas = this.config.schemas;
|
|
433
|
+
this.internalEventDescriptors = this.config.internalEvents ?? [];
|
|
434
|
+
this.options = {
|
|
435
|
+
maxIterations: Infinity,
|
|
436
|
+
...this.config.options
|
|
437
|
+
};
|
|
438
|
+
this.transition = this.transition.bind(this);
|
|
439
|
+
this.initialTransition = this.initialTransition.bind(this);
|
|
440
|
+
this.getInitialSnapshot = this.getInitialSnapshot.bind(this);
|
|
441
|
+
this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);
|
|
442
|
+
this.restoreSnapshot = this.restoreSnapshot.bind(this);
|
|
443
|
+
this.start = this.start.bind(this);
|
|
444
|
+
this.root = new StateNode(config, {
|
|
445
|
+
_key: this.id,
|
|
446
|
+
_machine: this
|
|
447
|
+
});
|
|
448
|
+
this.root._initialize();
|
|
449
|
+
formatRouteTransitions(this.root);
|
|
450
|
+
this.root._refreshEventMetadata();
|
|
451
|
+
this.states = this.root.states; // TODO: remove!
|
|
452
|
+
this.events = this.root.events;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Clones this state machine with the provided implementations.
|
|
457
|
+
*
|
|
458
|
+
* @param implementations Options (`actions`, `guards`, `actorSources`,
|
|
459
|
+
* `delays`) to recursively merge with the existing options.
|
|
460
|
+
* @returns A new `StateMachine` instance with the provided implementations.
|
|
461
|
+
*/
|
|
462
|
+
provide(implementations) {
|
|
463
|
+
const {
|
|
464
|
+
actions,
|
|
465
|
+
guards,
|
|
466
|
+
actorSources,
|
|
467
|
+
delays
|
|
468
|
+
} = this.implementations;
|
|
469
|
+
const provided = new StateMachine(this.config, {
|
|
470
|
+
actions: {
|
|
471
|
+
...actions,
|
|
472
|
+
...implementations.actions
|
|
473
|
+
},
|
|
474
|
+
guards: {
|
|
475
|
+
...guards,
|
|
476
|
+
...implementations.guards
|
|
477
|
+
},
|
|
478
|
+
actorSources: {
|
|
479
|
+
...actorSources,
|
|
480
|
+
...implementations.actorSources
|
|
481
|
+
},
|
|
482
|
+
delays: {
|
|
483
|
+
...delays,
|
|
484
|
+
...implementations.delays
|
|
485
|
+
}
|
|
486
|
+
});
|
|
487
|
+
// Providing implementations does not change the serializable definition.
|
|
488
|
+
provided._json = this._json;
|
|
489
|
+
return provided;
|
|
490
|
+
}
|
|
491
|
+
resolveState(config) {
|
|
492
|
+
const resolvedStateValue = resolveStateValue(this.root, config.value);
|
|
493
|
+
const nodeSet = getAllStateNodes(getStateNodes(this.root, resolvedStateValue));
|
|
494
|
+
const nodes = [...nodeSet];
|
|
495
|
+
return createMachineSnapshot({
|
|
496
|
+
_nodes: nodes,
|
|
497
|
+
value: resolvedStateValue,
|
|
498
|
+
context: config.context || {},
|
|
499
|
+
children: {},
|
|
500
|
+
status: isInFinalState(nodeSet, this.root) ? 'done' : config.status || 'active',
|
|
501
|
+
output: config.output,
|
|
502
|
+
error: config.error,
|
|
503
|
+
historyValue: config.historyValue
|
|
504
|
+
}, this);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Determines the next snapshot given the current `snapshot` and received
|
|
509
|
+
* `event`. Calculates a full macrostep from all microsteps.
|
|
510
|
+
*
|
|
511
|
+
* @param snapshot The current snapshot
|
|
512
|
+
* @param event The received event
|
|
513
|
+
*/
|
|
514
|
+
transition(snapshot, event, actorScope) {
|
|
515
|
+
const {
|
|
516
|
+
snapshot: nextSnapshot,
|
|
517
|
+
microsteps
|
|
518
|
+
} = macrostep(snapshot, event, actorScope, []);
|
|
519
|
+
return [nextSnapshot, microsteps.flatMap(([, actions]) => actions)];
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Determines the next state given the current `state` and `event`. Calculates
|
|
524
|
+
* a microstep.
|
|
525
|
+
*
|
|
526
|
+
* @param state The current state
|
|
527
|
+
* @param event The received event
|
|
528
|
+
*/
|
|
529
|
+
microstep(snapshot, event, actorScope) {
|
|
530
|
+
const {
|
|
531
|
+
microsteps
|
|
532
|
+
} = macrostep(snapshot, event, actorScope, []);
|
|
533
|
+
const snapshots = new Array(microsteps.length);
|
|
534
|
+
for (let i = 0; i < microsteps.length; i++) {
|
|
535
|
+
snapshots[i] = microsteps[i][0];
|
|
536
|
+
}
|
|
537
|
+
return snapshots;
|
|
538
|
+
}
|
|
539
|
+
getTransitionData(snapshot, event, self) {
|
|
540
|
+
return transitionNode(this.root, snapshot.value, snapshot, event, self) || [];
|
|
541
|
+
}
|
|
542
|
+
isInternalEventType(eventType) {
|
|
543
|
+
for (const descriptor of this.internalEventDescriptors) {
|
|
544
|
+
if (matchesEventDescriptor(eventType, descriptor)) {
|
|
545
|
+
return true;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
return false;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* The initial state _before_ evaluating any microsteps. This "pre-initial"
|
|
553
|
+
* state is provided to initial actions executed in the initial state.
|
|
554
|
+
*
|
|
555
|
+
* @internal
|
|
556
|
+
*/
|
|
557
|
+
_getPreInitialState(actorScope, initEvent) {
|
|
558
|
+
const {
|
|
559
|
+
context
|
|
560
|
+
} = this.config;
|
|
561
|
+
const preInitial = createMachineSnapshot({
|
|
562
|
+
context: typeof context !== 'function' && context ? context : {},
|
|
563
|
+
_nodes: [this.root],
|
|
564
|
+
children: {},
|
|
565
|
+
status: 'active'
|
|
566
|
+
}, this);
|
|
567
|
+
if (typeof context === 'function') {
|
|
568
|
+
const children = {};
|
|
569
|
+
const spawn = createSpawner(actorScope, preInitial, initEvent, children);
|
|
570
|
+
const resolvedContext = context({
|
|
571
|
+
spawn,
|
|
572
|
+
input: initEvent.input,
|
|
573
|
+
self: actorScope.self,
|
|
574
|
+
actorSources: this.implementations.actorSources
|
|
575
|
+
});
|
|
576
|
+
const [nextState] = resolveActionsWithContext(preInitial, initEvent, actorScope, []);
|
|
577
|
+
if (resolvedContext) {
|
|
578
|
+
nextState.context = resolvedContext;
|
|
579
|
+
}
|
|
580
|
+
if (Object.keys(children).length > 0) {
|
|
581
|
+
nextState.children = {
|
|
582
|
+
...nextState.children,
|
|
583
|
+
...children
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
return nextState;
|
|
587
|
+
}
|
|
588
|
+
return preInitial;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* Returns the initial `State` instance, with reference to `self` as an
|
|
593
|
+
* `ActorRef`.
|
|
594
|
+
*/
|
|
595
|
+
getInitialSnapshot(actorScope, input) {
|
|
596
|
+
return this.initialTransition(input, actorScope)[0];
|
|
597
|
+
}
|
|
598
|
+
initialTransition(input, actorScope) {
|
|
599
|
+
const initEvent = createInitEvent(input); // TODO: fix;
|
|
600
|
+
const internalQueue = [];
|
|
601
|
+
const preInitialState = this._getPreInitialState(actorScope, initEvent);
|
|
602
|
+
const [nextState, initialActions] = initialMicrostep(this.root, preInitialState, actorScope, initEvent, internalQueue);
|
|
603
|
+
const {
|
|
604
|
+
snapshot: macroState,
|
|
605
|
+
microsteps
|
|
606
|
+
} = macrostep(nextState, initEvent, actorScope, internalQueue);
|
|
607
|
+
return [macroState, [...initialActions, ...microsteps.flatMap(([, actions]) => actions)]];
|
|
608
|
+
}
|
|
609
|
+
start(snapshot) {
|
|
610
|
+
// Start rehydrated children that were active when persisted. Freshly
|
|
611
|
+
// invoked/spawned children are NOT started here — they start via deferred
|
|
612
|
+
// `@xstate.start` actions so sync start errors route to `onError`.
|
|
613
|
+
if (!snapshot?.children) {
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
for (const child of Object.values(snapshot.children)) {
|
|
617
|
+
if (child._rehydrated && child.getSnapshot?.().status === 'active') {
|
|
618
|
+
child.start();
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
getStateNodeById(stateId) {
|
|
623
|
+
const fullPath = toStatePath(stateId);
|
|
624
|
+
const relativePath = fullPath.slice(1);
|
|
625
|
+
const resolvedStateId = isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER.length) : fullPath[0];
|
|
626
|
+
const stateNode = this.idMap.get(resolvedStateId);
|
|
627
|
+
if (!stateNode) {
|
|
628
|
+
throw new Error(`Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`);
|
|
629
|
+
}
|
|
630
|
+
return getStateNodeByPath(stateNode, relativePath);
|
|
631
|
+
}
|
|
632
|
+
getPersistedSnapshot(snapshot, options) {
|
|
633
|
+
return getPersistedSnapshot(snapshot, options);
|
|
634
|
+
}
|
|
635
|
+
restoreSnapshot(snapshot, _actorScope) {
|
|
636
|
+
const persistedVersion = snapshot.version;
|
|
637
|
+
if (persistedVersion !== this.version) {
|
|
638
|
+
const migrate = this.config.migrate;
|
|
639
|
+
if (typeof migrate !== 'function') {
|
|
640
|
+
throw new Error(`Persisted snapshot version '${persistedVersion}' does not match machine version '${this.version}'.`);
|
|
641
|
+
}
|
|
642
|
+
snapshot = migrate(snapshot, persistedVersion);
|
|
643
|
+
}
|
|
644
|
+
const snapshotData = snapshot;
|
|
645
|
+
const children = {};
|
|
646
|
+
const snapshotChildren = snapshotData.children;
|
|
647
|
+
for (const actorId of Object.keys(snapshotChildren)) {
|
|
648
|
+
const actorData = snapshotChildren[actorId];
|
|
649
|
+
const childState = actorData.snapshot;
|
|
650
|
+
const src = actorData.src;
|
|
651
|
+
const logic = typeof src === 'string' ? resolveReferencedActor(this, src) : src;
|
|
652
|
+
if (!logic) {
|
|
653
|
+
continue;
|
|
654
|
+
}
|
|
655
|
+
const actor = createActor(logic, {
|
|
656
|
+
id: actorId,
|
|
657
|
+
parent: _actorScope.self,
|
|
658
|
+
syncSnapshot: actorData.syncSnapshot,
|
|
659
|
+
snapshot: childState,
|
|
660
|
+
src,
|
|
661
|
+
registryKey: actorData.registryKey
|
|
662
|
+
});
|
|
663
|
+
// Mark so `start()` knows to start this child (freshly invoked/spawned
|
|
664
|
+
// children are started via deferred `@xstate.start` actions instead).
|
|
665
|
+
actor._rehydrated = true;
|
|
666
|
+
children[actorId] = actor;
|
|
667
|
+
}
|
|
668
|
+
const reviveHistoryValue = historyValue => {
|
|
669
|
+
if (!historyValue || typeof historyValue !== 'object') {
|
|
670
|
+
return {};
|
|
671
|
+
}
|
|
672
|
+
const revived = {};
|
|
673
|
+
for (const key of Object.keys(historyValue)) {
|
|
674
|
+
const arr = historyValue[key];
|
|
675
|
+
for (const item of arr) {
|
|
676
|
+
let resolved;
|
|
677
|
+
if (item instanceof StateNode) {
|
|
678
|
+
resolved = item;
|
|
679
|
+
} else {
|
|
680
|
+
try {
|
|
681
|
+
resolved = this.root.machine.getStateNodeById(item.id);
|
|
682
|
+
} catch {
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
if (!resolved) {
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
revived[key] ??= [];
|
|
689
|
+
revived[key].push(resolved);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
return revived;
|
|
693
|
+
};
|
|
694
|
+
const revivedHistoryValue = reviveHistoryValue(snapshotData.historyValue);
|
|
695
|
+
const nodes = Array.from(getAllStateNodes(getStateNodes(this.root, snapshotData.value)));
|
|
696
|
+
const {
|
|
697
|
+
version: _persistedSnapshotVersion,
|
|
698
|
+
...persistedRest
|
|
699
|
+
} = snapshot;
|
|
700
|
+
const restoredSnapshot = createMachineSnapshot({
|
|
701
|
+
...persistedRest,
|
|
702
|
+
children,
|
|
703
|
+
_nodes: nodes,
|
|
704
|
+
value: snapshotData.value,
|
|
705
|
+
historyValue: revivedHistoryValue
|
|
706
|
+
}, this);
|
|
707
|
+
const seen = new WeakSet();
|
|
708
|
+
function reviveContext(contextPart) {
|
|
709
|
+
if (seen.has(contextPart)) {
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
seen.add(contextPart);
|
|
713
|
+
for (const key of Object.keys(contextPart)) {
|
|
714
|
+
const value = contextPart[key];
|
|
715
|
+
if (value && typeof value === 'object') {
|
|
716
|
+
if ('xstate$$type' in value && value.xstate$$type === $$ACTOR_TYPE) {
|
|
717
|
+
contextPart[key] = children[value.id];
|
|
718
|
+
continue;
|
|
719
|
+
}
|
|
720
|
+
reviveContext(value);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
reviveContext(restoredSnapshot.context);
|
|
725
|
+
return restoredSnapshot;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
export { StateMachine as S, StateNode as a };
|