xstate 6.0.0-alpha.3 → 6.0.0-alpha.31

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 (75) hide show
  1. package/README.md +19 -17
  2. package/bin/xstate.js +36 -0
  3. package/dist/StateMachine-4e86e818.cjs.js +1079 -0
  4. package/dist/StateMachine-54d3cf7a.development.esm.js +1103 -0
  5. package/dist/{StateMachine-0770ac71.development.cjs.js → StateMachine-73b20de0.development.cjs.js} +491 -120
  6. package/dist/StateMachine-cc0c34dd.esm.js +1071 -0
  7. package/dist/declarations/src/State.d.ts +16 -3
  8. package/dist/declarations/src/StateMachine.d.ts +28 -15
  9. package/dist/declarations/src/StateNode.d.ts +4 -2
  10. package/dist/declarations/src/actions.d.ts +10 -7
  11. package/dist/declarations/src/actors/callback.d.ts +2 -0
  12. package/dist/declarations/src/actors/logic.d.ts +7 -21
  13. package/dist/declarations/src/actors/observable.d.ts +3 -0
  14. package/dist/declarations/src/actors/promise.d.ts +6 -2
  15. package/dist/declarations/src/createActor.d.ts +21 -14
  16. package/dist/declarations/src/createMachine.d.ts +24 -13
  17. package/dist/declarations/src/createMachineFromConfig.d.ts +64 -30
  18. package/dist/declarations/src/fsm.d.ts +76 -0
  19. package/dist/declarations/src/graph/graph.d.ts +3 -3
  20. package/dist/declarations/src/graph/shortestPaths.d.ts +2 -2
  21. package/dist/declarations/src/graph/simplePaths.d.ts +2 -2
  22. package/dist/declarations/src/index.d.ts +9 -4
  23. package/dist/declarations/src/machineVersions.d.ts +51 -0
  24. package/dist/declarations/src/schema.types.d.ts +5 -0
  25. package/dist/declarations/src/serialize.d.ts +9 -22
  26. package/dist/declarations/src/setup.d.ts +361 -70
  27. package/dist/declarations/src/spawn.d.ts +5 -5
  28. package/dist/declarations/src/stateUtils.d.ts +8 -3
  29. package/dist/declarations/src/system.d.ts +38 -11
  30. package/dist/declarations/src/transition.d.ts +8 -5
  31. package/dist/declarations/src/transitionActions.d.ts +16 -0
  32. package/dist/declarations/src/types.d.ts +346 -144
  33. package/dist/declarations/src/types.v6.d.ts +294 -58
  34. package/dist/declarations/src/utils.d.ts +5 -3
  35. package/dist/declarations/src/validation/index.d.ts +37 -0
  36. package/dist/declarations/src/validation.types.d.ts +22 -0
  37. package/dist/{index-269d256d.development.cjs.js → index-0317dbd5.development.cjs.js} +2220 -1041
  38. package/dist/{index-a7e3d8b3.esm.js → index-2b16671f.esm.js} +2195 -1038
  39. package/dist/{index-dda021d5.cjs.js → index-85c48a0a.cjs.js} +2218 -1039
  40. package/dist/{index-66ff64a6.development.esm.js → index-fbe9e986.development.esm.js} +2197 -1040
  41. package/dist/xstate-actors.cjs.js +1 -1
  42. package/dist/xstate-actors.development.cjs.js +1 -1
  43. package/dist/xstate-actors.development.esm.js +1 -1
  44. package/dist/xstate-actors.esm.js +1 -1
  45. package/dist/xstate-actors.umd.min.js +1 -1
  46. package/dist/xstate-actors.umd.min.js.map +1 -1
  47. package/dist/xstate-graph.cjs.js +10 -14
  48. package/dist/xstate-graph.development.cjs.js +10 -14
  49. package/dist/xstate-graph.development.esm.js +10 -14
  50. package/dist/xstate-graph.esm.js +10 -14
  51. package/dist/xstate-graph.umd.min.js +1 -1
  52. package/dist/xstate-graph.umd.min.js.map +1 -1
  53. package/dist/xstate-validation.cjs.d.mts +2 -0
  54. package/dist/xstate-validation.cjs.d.ts +2 -0
  55. package/dist/xstate-validation.cjs.js +277 -0
  56. package/dist/xstate-validation.cjs.mjs +5 -0
  57. package/dist/xstate-validation.development.cjs.js +277 -0
  58. package/dist/xstate-validation.development.cjs.mjs +5 -0
  59. package/dist/xstate-validation.development.esm.js +271 -0
  60. package/dist/xstate-validation.esm.js +271 -0
  61. package/dist/xstate-validation.umd.min.js +2 -0
  62. package/dist/xstate-validation.umd.min.js.map +1 -0
  63. package/dist/xstate.cjs.js +1299 -294
  64. package/dist/xstate.cjs.mjs +6 -0
  65. package/dist/xstate.development.cjs.js +1299 -294
  66. package/dist/xstate.development.cjs.mjs +6 -0
  67. package/dist/xstate.development.esm.js +1293 -294
  68. package/dist/xstate.esm.js +1293 -294
  69. package/dist/xstate.umd.min.js +1 -1
  70. package/dist/xstate.umd.min.js.map +1 -1
  71. package/package.json +23 -3
  72. package/validation/package.json +8 -0
  73. package/dist/StateMachine-8249d511.esm.js +0 -720
  74. package/dist/StateMachine-e1048cd6.cjs.js +0 -723
  75. package/dist/StateMachine-e6ad61d0.development.esm.js +0 -737
@@ -0,0 +1,1079 @@
1
+ 'use strict';
2
+
3
+ var dist_xstateActors = require('./index-85c48a0a.cjs.js');
4
+
5
+ function createSpawner(actorScope, actors, spawnedChildren) {
6
+ return (src, options) => {
7
+ const referencedSrc = Object.entries(actors).find(([, logic]) => logic === src)?.[0];
8
+ const actor = actorScope.system.createActorRef(src, {
9
+ id: options?.id,
10
+ parent: actorScope.self,
11
+ syncSnapshot: options?.syncSnapshot,
12
+ input: options?.input,
13
+ src: referencedSrc ?? src,
14
+ registryKey: options?.registryKey
15
+ });
16
+ spawnedChildren[actor.id] = actor;
17
+ return actor;
18
+ };
19
+ }
20
+
21
+ /** @internal */
22
+ function setInertActorScopeSnapshot(actorScope, snapshot, attachActorRef = true) {
23
+ actorScope.self._snapshot = snapshot;
24
+ if (attachActorRef && snapshot && typeof snapshot === 'object') {
25
+ dist_xstateActors.setSnapshotActorRef(snapshot, actorScope.self);
26
+ }
27
+ return snapshot;
28
+ }
29
+
30
+ /** @internal */
31
+ function isInertActorScope(actorScope) {
32
+ return !!actorScope.self.options?._inert;
33
+ }
34
+
35
+ /** @internal */
36
+ function attachSnapshotActorRef(actorLogic, actorScope, snapshot) {
37
+ const snapshotScope = createInertActorScope(actorLogic, snapshot, actorScope.self);
38
+ return setInertActorScopeSnapshot(snapshotScope, snapshot);
39
+ }
40
+
41
+ /** @internal */
42
+ function createInertActorScope(actorLogic, snapshot, sourceSelf) {
43
+ const snapshotRef = snapshot ? dist_xstateActors.getSnapshotActorRef(snapshot) : undefined;
44
+ const previousSelf = sourceSelf ?? snapshotRef?.actor;
45
+ const baseSystem = previousSelf?.system;
46
+ const system = previousSelf && baseSystem ? dist_xstateActors.createSnapshotSystem(baseSystem, dist_xstateActors.isMachineSnapshot(snapshot) ? snapshot.children : {}, sourceSelf ? undefined : snapshotRef?.systemState) : undefined;
47
+ const self = dist_xstateActors.createActor(actorLogic, {
48
+ _inert: true,
49
+ ...(previousSelf ? {
50
+ id: previousSelf.id,
51
+ _sessionId: previousSelf.sessionId
52
+ } : {}),
53
+ ...(system ? {
54
+ _systemRef: {
55
+ current: system
56
+ }
57
+ } : {})
58
+ });
59
+ if (previousSelf?._parent) {
60
+ self._parent = previousSelf._parent;
61
+ }
62
+ if (snapshot) {
63
+ self._snapshot = snapshot;
64
+ }
65
+ const actorScope = {
66
+ self: self,
67
+ defer: () => {},
68
+ id: self.id,
69
+ logger: self.system._logger,
70
+ sessionId: self.sessionId,
71
+ stopChild: child => child._stop(),
72
+ system: self.system,
73
+ emit: event => self.system.emitEvent(self, event),
74
+ actionExecutor: () => {}
75
+ };
76
+ return actorScope;
77
+ }
78
+
79
+ /** @deprecated Use `initialTransition(…)` instead. */
80
+ function getInitialSnapshot(actorLogic, ...[input]) {
81
+ const actorScope = createInertActorScope(actorLogic);
82
+ return actorLogic.initialTransition(input, actorScope)[0];
83
+ }
84
+
85
+ /**
86
+ * Determines the next snapshot for the given `actorLogic` based on the given
87
+ * `snapshot` and `event`.
88
+ *
89
+ * If the `snapshot` is `undefined`, the initial snapshot of the `actorLogic` is
90
+ * used.
91
+ *
92
+ * @deprecated Use `transition(…)` instead.
93
+ * @example
94
+ *
95
+ * ```ts
96
+ * import { getNextSnapshot } from 'xstate';
97
+ * import { trafficLightMachine } from './trafficLightMachine.ts';
98
+ *
99
+ * const nextSnapshot = getNextSnapshot(
100
+ * trafficLightMachine, // actor logic
101
+ * undefined, // snapshot (or initial state if undefined)
102
+ * { type: 'TIMER' }
103
+ * ); // event object
104
+ *
105
+ * console.log(nextSnapshot.value);
106
+ * // => 'yellow'
107
+ *
108
+ * const nextSnapshot2 = getNextSnapshot(
109
+ * trafficLightMachine, // actor logic
110
+ * nextSnapshot, // snapshot
111
+ * { type: 'TIMER' }
112
+ * ); // event object
113
+ *
114
+ * console.log(nextSnapshot2.value);
115
+ * // =>'red'
116
+ * ```
117
+ */
118
+ function getNextSnapshot(actorLogic, snapshot, event) {
119
+ const actorScope = createInertActorScope(actorLogic, snapshot);
120
+ const transitionResult = actorLogic.transition(snapshot, event, actorScope);
121
+ const nextSnapshot = Array.isArray(transitionResult) ? transitionResult[0] : transitionResult;
122
+ setInertActorScopeSnapshot(actorScope, nextSnapshot, false);
123
+ return nextSnapshot === snapshot ? nextSnapshot : attachSnapshotActorRef(actorLogic, actorScope, nextSnapshot);
124
+ }
125
+
126
+ const cache = new WeakMap();
127
+ function memo(object, key, fn) {
128
+ let memoizedData = cache.get(object);
129
+ if (!memoizedData) {
130
+ memoizedData = {
131
+ [key]: fn()
132
+ };
133
+ cache.set(object, memoizedData);
134
+ } else if (!(key in memoizedData)) {
135
+ memoizedData[key] = fn();
136
+ }
137
+ return memoizedData[key];
138
+ }
139
+
140
+ const EMPTY_OBJECT = {};
141
+ class StateNode {
142
+ constructor(/** The raw config used to create the machine. */
143
+ config, options) {
144
+ this.config = config;
145
+ /**
146
+ * The relative key of the state node, which represents its location in the
147
+ * overall state value.
148
+ */
149
+ this.key = void 0;
150
+ /** The unique ID of the state node. */
151
+ this.id = void 0;
152
+ /**
153
+ * The type of this state node:
154
+ *
155
+ * - `'atomic'` - no child state nodes
156
+ * - `'compound'` - nested child state nodes (XOR)
157
+ * - `'parallel'` - orthogonal nested child state nodes (AND)
158
+ * - `'history'` - history state node
159
+ * - `'choice'` - pure routing decision state node
160
+ * - `'final'` - final state node
161
+ */
162
+ this.type = void 0;
163
+ /** The string path from the root machine node to this node. */
164
+ this.path = void 0;
165
+ /** The child state nodes. */
166
+ this.states = void 0;
167
+ /**
168
+ * The type of history on this state node. Can be:
169
+ *
170
+ * - `'shallow'` - recalls only top-level historical state value
171
+ * - `'deep'` - recalls historical state value at all levels
172
+ */
173
+ this.history = void 0;
174
+ /** The action(s) to be executed upon entering the state node. */
175
+ this.entry = void 0;
176
+ /** The action(s) to be executed upon exiting the state node. */
177
+ this.exit = void 0;
178
+ /** The parent state node. */
179
+ this.parent = void 0;
180
+ /** The root machine node. */
181
+ this.machine = void 0;
182
+ /**
183
+ * The meta data associated with this state node, which will be returned in
184
+ * State instances.
185
+ */
186
+ this.meta = void 0;
187
+ /**
188
+ * The output data sent with the `xstate.done.state` event if this is a final
189
+ * state node.
190
+ */
191
+ this.output = void 0;
192
+ /**
193
+ * The order this state node appears. Corresponds to the implicit document
194
+ * order.
195
+ */
196
+ this.order = -1;
197
+ this.description = void 0;
198
+ this.schemas = void 0;
199
+ this.tags = [];
200
+ this.transitions = void 0;
201
+ this.always = void 0;
202
+ this.invoke = void 0;
203
+ this.on = void 0;
204
+ this.after = void 0;
205
+ this.events = void 0;
206
+ this.ownEvents = void 0;
207
+ this.parent = options._parent;
208
+ this.key = options._key;
209
+ this.machine = options._machine;
210
+ this.path = this.parent ? this.parent.path.concat(this.key) : [];
211
+ const firstStateKey = this.config.states ? Object.keys(this.config.states)[0] : undefined;
212
+ this.id = this.config.id || [this.machine.id, ...this.path].join(dist_xstateActors.STATE_DELIMITER);
213
+ this.type = this.config.type || (firstStateKey !== undefined ? 'compound' : this.config.history ? 'history' : 'atomic');
214
+ this.description = this.config.description;
215
+ this.schemas = this.config.schemas;
216
+ validateStateNodeConfig(this);
217
+ this.order = this.machine.idMap.size;
218
+ this.machine.idMap.set(this.id, this);
219
+ this.states = this.config.states ? dist_xstateActors.mapValues(this.config.states, (stateConfig, key) => {
220
+ const stateNode = new StateNode(stateConfig, {
221
+ _parent: this,
222
+ _key: key,
223
+ _machine: this.machine
224
+ });
225
+ return stateNode;
226
+ }) : EMPTY_OBJECT;
227
+ if (this.type === 'compound' && !this.config.initial) {
228
+ throw new Error(`No initial state specified for compound state node "#${this.id}".`);
229
+ }
230
+
231
+ // History config
232
+ this.history = this.config.history === true ? 'shallow' : this.config.history || false;
233
+ this.entry = this.config.entry;
234
+ this.exit = this.config.exit;
235
+ if (this.entry) {
236
+ // @ts-expect-error _special is an internal marker not on the Action type
237
+ this.entry._special = true;
238
+ }
239
+ if (this.exit) {
240
+ // @ts-expect-error _special is an internal marker not on the Action type
241
+ this.exit._special = true;
242
+ }
243
+ this.meta = this.config.meta;
244
+ this.output = this.type === 'final' || !this.parent ? this.config.output : undefined;
245
+ this.tags = dist_xstateActors.toArray(config.tags).slice();
246
+ this.invoke = dist_xstateActors.toArray(this.config.invoke).map((invokeConfig, i) => {
247
+ const {
248
+ src,
249
+ registryKey
250
+ } = invokeConfig;
251
+ const invokeId = dist_xstateActors.createInvokeId(this.id, i);
252
+ const resolvedId = invokeConfig.id ?? invokeId;
253
+ // Referenced (string) actors keep their logical name so persisted
254
+ // snapshots reference `src: 'fetchUser'` rather than a positional id;
255
+ // only inline logic gets the synthetic source name.
256
+ const sourceName = typeof src === 'string' ? src : `xstate.invoke.${invokeId}`;
257
+ return {
258
+ ...invokeConfig,
259
+ src: sourceName,
260
+ logic: src,
261
+ id: resolvedId,
262
+ registryKey
263
+ };
264
+ });
265
+ }
266
+
267
+ /** @internal */
268
+ _initialize() {
269
+ this.after = dist_xstateActors.getDelayedTransitions(this);
270
+ this.transitions = formatTransitions(this);
271
+ if (this.type === 'choice') {
272
+ this.always = formatChoiceTransitions(this);
273
+ } else if (this.config.always) {
274
+ this.always = mapTransitionConfigs(this.config.always, transition => dist_xstateActors.formatTransition(this, dist_xstateActors.NULL_EVENT, transition));
275
+ }
276
+ for (const key of Object.keys(this.states)) {
277
+ this.states[key]._initialize();
278
+ }
279
+ this._refreshEventMetadata();
280
+ }
281
+
282
+ /** @internal */
283
+ _refreshEventMetadata() {
284
+ const on = {};
285
+ const ownEvents = [];
286
+ for (const [descriptor, transitions] of this.transitions) {
287
+ on[descriptor] = transitions.slice();
288
+ if (transitions.some(transition => transition.target || transition.reenter || transition.to)) {
289
+ ownEvents.push(descriptor);
290
+ }
291
+ }
292
+ this.on = on;
293
+ this.ownEvents = ownEvents;
294
+ const events = new Set(ownEvents);
295
+ for (const state of Object.values(this.states)) {
296
+ for (const event of state.events) {
297
+ events.add(event);
298
+ }
299
+ }
300
+ this.events = Array.from(events);
301
+ }
302
+ get initial() {
303
+ return memo(this, 'initial', () => formatInitialTransition(this, this.config.initial));
304
+ }
305
+
306
+ /** @internal */
307
+ next(snapshot, event, self) {
308
+ const candidates = memo(this, `candidates-${dist_xstateActors.getEventDescriptorKey(event)}`, () => dist_xstateActors.getCandidates(this, event));
309
+ for (const candidate of candidates) {
310
+ const guardPassed = dist_xstateActors.evaluateCandidate(candidate, event, snapshot, this, self);
311
+ if (guardPassed) {
312
+ return [candidate];
313
+ }
314
+ }
315
+ return undefined;
316
+ }
317
+ }
318
+ function validateStateNodeConfig(stateNode) {
319
+ const config = stateNode.config;
320
+ if (stateNode.type === 'history' && !(typeof config.target === 'string' && config.target.trim().length > 0 || Array.isArray(config.target) && config.target.length > 0 && config.target.every(target => typeof target === 'string' && target.trim().length > 0))) {
321
+ throw new Error(`Missing history target on "${stateNode.id}"`);
322
+ }
323
+ if (stateNode.type !== 'choice') {
324
+ return;
325
+ }
326
+ if (typeof config.choice !== 'function') {
327
+ throw new Error(`Missing \`choice\` function on "${stateNode.id}"`);
328
+ }
329
+ }
330
+ function formatChoiceTransitions(stateNode) {
331
+ const choice = stateNode.config.choice;
332
+ const validateChoiceResult = result => {
333
+ if (!result || result.target === undefined) {
334
+ throw new Error(`Choice "${stateNode.id}" has no target`);
335
+ }
336
+ return result;
337
+ };
338
+ return [dist_xstateActors.formatTransition(stateNode, dist_xstateActors.NULL_EVENT, {
339
+ to: args => validateChoiceResult(choice(args))
340
+ })];
341
+ }
342
+ function mapTransitionConfigs(transitionsConfig, mapper) {
343
+ const transitionConfigs = dist_xstateActors.toTransitionConfigArray(transitionsConfig);
344
+ const transitions = new Array(transitionConfigs.length);
345
+ for (let i = 0; i < transitionConfigs.length; i++) {
346
+ transitions[i] = mapper(transitionConfigs[i]);
347
+ }
348
+ return transitions;
349
+ }
350
+ function formatTransitions(stateNode) {
351
+ const transitions = new Map();
352
+ const addTransitions = (descriptor, additions) => {
353
+ transitions.set(descriptor, [...(transitions.get(descriptor) ?? []), ...additions]);
354
+ };
355
+ if (stateNode.config.on) {
356
+ for (const descriptor of Object.keys(stateNode.config.on)) {
357
+ if (descriptor === dist_xstateActors.NULL_EVENT) {
358
+ throw new Error('Null event transition key');
359
+ }
360
+ const transitionsConfig = stateNode.config.on[descriptor];
361
+ transitions.set(descriptor, mapTransitionConfigs(transitionsConfig, transition => dist_xstateActors.formatTransition(stateNode, descriptor, transition)));
362
+ }
363
+ }
364
+ if (stateNode.config.onDone) {
365
+ const descriptor = 'xstate.done.state';
366
+ addTransitions(descriptor, mapTransitionConfigs(stateNode.config.onDone, transition => dist_xstateActors.formatTransition(stateNode, descriptor, {
367
+ ...transition,
368
+ matches: {
369
+ ...transition.matches,
370
+ stateId: stateNode.id
371
+ }
372
+ })));
373
+ }
374
+ if (stateNode.config.onError) {
375
+ const descriptor = 'xstate.error.*';
376
+ transitions.set(descriptor, mapTransitionConfigs(stateNode.config.onError, transition => dist_xstateActors.formatTransition(stateNode, descriptor, transition)));
377
+ }
378
+ const createCancelInvokeTimeoutTransition = (descriptor, timeoutEventId, actorId) => dist_xstateActors.formatTransition(stateNode, descriptor, {
379
+ matches: {
380
+ actorId
381
+ },
382
+ _eventMatcher: (event, snapshot) => dist_xstateActors.matchesActorSession(event, snapshot, actorId),
383
+ to: (_args, enq) => {
384
+ enq.cancel(timeoutEventId);
385
+ return {};
386
+ }
387
+ });
388
+ const formatInvokeCompletionTransition = (descriptor, transitionConfig, timeoutEventId) => {
389
+ const {
390
+ target,
391
+ to,
392
+ reenter,
393
+ ...rest
394
+ } = transitionConfig;
395
+ return dist_xstateActors.formatTransition(stateNode, descriptor, {
396
+ ...rest,
397
+ reenter,
398
+ to: (args, enq) => {
399
+ if (to) {
400
+ let didEnqueue = false;
401
+ const trackingEnqueue = new Proxy(enq, {
402
+ apply(target, thisArg, argArray) {
403
+ didEnqueue = true;
404
+ return Reflect.apply(target, thisArg, argArray);
405
+ },
406
+ get(target, prop, receiver) {
407
+ const value = Reflect.get(target, prop, receiver);
408
+ if (typeof value !== 'function') {
409
+ return value;
410
+ }
411
+ return (...argArray) => {
412
+ didEnqueue = true;
413
+ return value.apply(target, argArray);
414
+ };
415
+ }
416
+ });
417
+ const result = to(args, trackingEnqueue);
418
+ if (result !== undefined || didEnqueue) {
419
+ enq.cancel(timeoutEventId);
420
+ }
421
+ return result;
422
+ }
423
+ enq.cancel(timeoutEventId);
424
+ return {
425
+ target,
426
+ reenter
427
+ };
428
+ }
429
+ });
430
+ };
431
+ for (const invokeDef of stateNode.invoke) {
432
+ const withInvokeMatch = transition => ({
433
+ ...transition,
434
+ matches: {
435
+ ...transition.matches,
436
+ actorId: invokeDef.id
437
+ },
438
+ _eventMatcher: (event, snapshot) => dist_xstateActors.matchesActorSession(event, snapshot, invokeDef.id)
439
+ });
440
+ const invokeTimeoutEventId = invokeDef.timeout !== undefined ? dist_xstateActors.createInvokeTimeoutEventId(invokeDef.id) : undefined;
441
+ if (invokeDef.onDone) {
442
+ const descriptor = 'xstate.done.actor';
443
+ const invokeDoneTransitions = mapTransitionConfigs(invokeDef.onDone, rawTransition => {
444
+ const transition = withInvokeMatch(rawTransition);
445
+ return invokeTimeoutEventId ? formatInvokeCompletionTransition(descriptor, transition, invokeTimeoutEventId) : dist_xstateActors.formatTransition(stateNode, descriptor, transition);
446
+ });
447
+ if (invokeTimeoutEventId) {
448
+ invokeDoneTransitions.push(createCancelInvokeTimeoutTransition(descriptor, invokeTimeoutEventId, invokeDef.id));
449
+ }
450
+ addTransitions(descriptor, invokeDoneTransitions);
451
+ } else if (invokeTimeoutEventId) {
452
+ const descriptor = 'xstate.done.actor';
453
+ addTransitions(descriptor, [createCancelInvokeTimeoutTransition(descriptor, invokeTimeoutEventId, invokeDef.id)]);
454
+ }
455
+ if (invokeDef.onError) {
456
+ const descriptor = 'xstate.error.actor';
457
+ addTransitions(descriptor, mapTransitionConfigs(invokeDef.onError, rawTransition => {
458
+ const transition = withInvokeMatch(rawTransition);
459
+ return invokeTimeoutEventId ? formatInvokeCompletionTransition(descriptor, transition, invokeTimeoutEventId) : dist_xstateActors.formatTransition(stateNode, descriptor, transition);
460
+ }));
461
+ }
462
+ if (invokeDef.onSnapshot) {
463
+ const descriptor = 'xstate.snapshot.actor';
464
+ addTransitions(descriptor, mapTransitionConfigs(invokeDef.onSnapshot, transition => dist_xstateActors.formatTransition(stateNode, descriptor, withInvokeMatch(transition))));
465
+ }
466
+ }
467
+ for (const delayedTransition of stateNode.after) {
468
+ let existing = transitions.get(delayedTransition.eventType);
469
+ if (!existing) {
470
+ existing = [];
471
+ transitions.set(delayedTransition.eventType, existing);
472
+ }
473
+ existing.push(delayedTransition);
474
+ }
475
+ return transitions;
476
+ }
477
+ function formatInitialTransition(stateNode, _target) {
478
+ const targetString = typeof _target === 'object' && _target !== null ? _target.target : _target;
479
+ const input = typeof _target === 'object' && _target !== null ? _target.input : undefined;
480
+ const resolvedTarget = typeof targetString === 'string' ? stateNode.states[targetString] : undefined;
481
+ if (!resolvedTarget && targetString) {
482
+ throw new Error(`Initial state "${targetString}" not found on "#${stateNode.id}"`);
483
+ }
484
+ const transition = {
485
+ source: stateNode,
486
+ target: resolvedTarget ? [resolvedTarget] : undefined,
487
+ input
488
+ };
489
+ return transition;
490
+ }
491
+
492
+ const STATE_IDENTIFIER = '#';
493
+ let emptyCanActor;
494
+ let emptyCanActorScope;
495
+ function getEmptyCanActor() {
496
+ // A minimal inert actor used purely as the `self`/`parent` argument when
497
+ // dry-running transitions for `snapshot.can(...)`. Intentionally not built
498
+ // on `createLogic` so `can()` does not pull that machinery into bundles.
499
+ return emptyCanActor ??= dist_xstateActors.createActor({
500
+ transition: snapshot => [snapshot, []],
501
+ initialTransition: () => [{
502
+ status: 'active',
503
+ output: undefined,
504
+ error: undefined
505
+ }, []],
506
+ getInitialSnapshot: () => ({
507
+ status: 'active',
508
+ output: undefined,
509
+ error: undefined
510
+ }),
511
+ getPersistedSnapshot: snapshot => snapshot
512
+ });
513
+ }
514
+ function getEmptyCanActorScope() {
515
+ if (emptyCanActorScope) {
516
+ return emptyCanActorScope;
517
+ }
518
+ const actor = getEmptyCanActor();
519
+ emptyCanActorScope = {
520
+ self: actor,
521
+ logger: () => {},
522
+ id: '',
523
+ sessionId: '',
524
+ defer: () => {},
525
+ system: actor.system,
526
+ stopChild: () => {},
527
+ emit: () => {},
528
+ actionExecutor: () => {}
529
+ };
530
+ return emptyCanActorScope;
531
+ }
532
+ class StateMachine {
533
+ constructor(/** The raw config used to create the machine. */
534
+ config, sources, validator) {
535
+ this.config = config;
536
+ this.validator = validator;
537
+ /** The machine's own version. */
538
+ this.version = void 0;
539
+ this.schemas = void 0;
540
+ this.sources = void 0;
541
+ /** Runtime options for machine execution. */
542
+ this.options = void 0;
543
+ /** @internal */
544
+ this.idMap = new Map();
545
+ this.root = void 0;
546
+ this.id = void 0;
547
+ this.states = void 0;
548
+ this.events = void 0;
549
+ this.internalEventDescriptors = void 0;
550
+ /**
551
+ * The original JSON definition this machine was created from (set by
552
+ * `createMachineFromConfig`), if any. Used by `serializeMachine` for lossless
553
+ * round-trips.
554
+ *
555
+ * @internal
556
+ */
557
+ this._json = void 0;
558
+ this.id = config.id || '(machine)';
559
+ this.sources = {
560
+ actors: config.actors ?? {},
561
+ actions: config.actions ?? {},
562
+ delays: config.delays ?? {},
563
+ guards: config.guards ?? {},
564
+ ...sources
565
+ };
566
+ this.version = this.config.version;
567
+ this.schemas = this.config.schemas;
568
+ this.internalEventDescriptors = this.config.internalEvents ?? [];
569
+ this.options = {
570
+ maxIterations: Infinity,
571
+ ...this.config.options
572
+ };
573
+ this.transition = this.transition.bind(this);
574
+ this.initialTransition = this.initialTransition.bind(this);
575
+ this.getInitialSnapshot = this.getInitialSnapshot.bind(this);
576
+ this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);
577
+ this.restoreSnapshot = this.restoreSnapshot.bind(this);
578
+ this.start = this.start.bind(this);
579
+ this.root = new StateNode(config, {
580
+ _key: this.id,
581
+ _machine: this
582
+ });
583
+ this.root._initialize();
584
+ dist_xstateActors.formatRouteTransitions(this.root);
585
+ this.root._refreshEventMetadata();
586
+ this.states = this.root.states; // TODO: remove!
587
+ this.events = this.root.events;
588
+ }
589
+
590
+ /**
591
+ * Clones this state machine with the provided sources.
592
+ *
593
+ * @param sources Options (`actions`, `guards`, `actors`, `delays`) to
594
+ * recursively merge with the existing options.
595
+ * @returns A new `StateMachine` instance with the provided sources.
596
+ */
597
+ provide(sources) {
598
+ const {
599
+ actions,
600
+ guards,
601
+ actors,
602
+ delays
603
+ } = this.sources;
604
+ const provided = new StateMachine(this.config, {
605
+ actions: {
606
+ ...actions,
607
+ ...sources.actions
608
+ },
609
+ guards: {
610
+ ...guards,
611
+ ...sources.guards
612
+ },
613
+ actors: {
614
+ ...actors,
615
+ ...sources.actors
616
+ },
617
+ delays: {
618
+ ...delays,
619
+ ...sources.delays
620
+ }
621
+ }, this.validator);
622
+ // Providing sources does not change the serializable definition.
623
+ provided._json = this._json;
624
+ return provided;
625
+ }
626
+ resolveState(config) {
627
+ const resolvedStateValue = dist_xstateActors.resolveStateValue(this.root, config.value);
628
+ const nodeSet = dist_xstateActors.getAllStateNodes(dist_xstateActors.getStateNodes(this.root, resolvedStateValue));
629
+ const nodes = [...nodeSet];
630
+ return dist_xstateActors.createMachineSnapshot({
631
+ _nodes: nodes,
632
+ value: resolvedStateValue,
633
+ context: config.context || {},
634
+ children: {},
635
+ status: dist_xstateActors.isInFinalState(nodeSet, this.root) ? 'done' : config.status || 'active',
636
+ output: config.output,
637
+ error: config.error,
638
+ historyValue: config.historyValue
639
+ }, this);
640
+ }
641
+
642
+ /**
643
+ * Determines the next snapshot given the current `snapshot` and received
644
+ * `event`. Calculates a full macrostep from all microsteps.
645
+ *
646
+ * @param snapshot The current snapshot
647
+ * @param event The received event
648
+ */
649
+ transition(snapshot, event, actorScope) {
650
+ const usesInertScope = !actorScope;
651
+ const resolvedActorScope = actorScope ?? createInertActorScope(this, snapshot);
652
+ if (this.validator) {
653
+ dist_xstateActors.assertValid(this.validator, {
654
+ kind: 'event',
655
+ logic: this,
656
+ event,
657
+ eventOrigin: actorScope && actorScope.self._lastSourceRef ? 'actor' : 'external'
658
+ });
659
+ }
660
+ if (usesInertScope) {
661
+ setInertActorScopeSnapshot(resolvedActorScope, snapshot, false);
662
+ }
663
+ const fastSnapshot = this._transitionFast(snapshot, event, resolvedActorScope);
664
+ if (fastSnapshot) {
665
+ if (usesInertScope) {
666
+ setInertActorScopeSnapshot(resolvedActorScope, fastSnapshot, false);
667
+ }
668
+ const returnedSnapshot = usesInertScope && fastSnapshot !== snapshot ? attachSnapshotActorRef(this, resolvedActorScope, fastSnapshot) : this._attachPureActorRef(fastSnapshot, resolvedActorScope);
669
+ if (this.validator) {
670
+ dist_xstateActors.assertValid(this.validator, {
671
+ kind: 'result',
672
+ logic: this,
673
+ snapshot: returnedSnapshot,
674
+ effects: []
675
+ });
676
+ }
677
+ return [returnedSnapshot, []];
678
+ }
679
+ const {
680
+ snapshot: nextSnapshot,
681
+ microsteps
682
+ } = dist_xstateActors.macrostep(snapshot, event, resolvedActorScope, []);
683
+ if (usesInertScope) {
684
+ setInertActorScopeSnapshot(resolvedActorScope, nextSnapshot, false);
685
+ }
686
+ const returnedSnapshot = usesInertScope ? nextSnapshot === snapshot ? nextSnapshot : attachSnapshotActorRef(this, resolvedActorScope, nextSnapshot) : this._attachPureActorRef(nextSnapshot, resolvedActorScope);
687
+ const effects = this._collectEffects(microsteps);
688
+ if (this.validator) {
689
+ dist_xstateActors.assertValid(this.validator, {
690
+ kind: 'result',
691
+ logic: this,
692
+ snapshot: returnedSnapshot,
693
+ effects
694
+ });
695
+ }
696
+ return [returnedSnapshot, effects];
697
+ }
698
+ _collectEffects(microsteps) {
699
+ return microsteps.flatMap(([, actions]) => actions);
700
+ }
701
+ _attachPureActorRef(snapshot, actorScope) {
702
+ if (isInertActorScope(actorScope)) {
703
+ return snapshot;
704
+ }
705
+ dist_xstateActors.setSnapshotActorRef(snapshot, actorScope.self, actorScope.system);
706
+ return snapshot;
707
+ }
708
+ _transitionFast(snapshot, event, actorScope) {
709
+ if (snapshot.status !== 'active' || typeof snapshot.value !== 'string' || this.root.always?.length) {
710
+ return undefined;
711
+ }
712
+ const sourceNode = this.root.states[snapshot.value];
713
+ if (!sourceNode || sourceNode.type !== 'atomic' || sourceNode.exit || sourceNode.invoke.length || sourceNode.always?.length || sourceNode.after?.length) {
714
+ return undefined;
715
+ }
716
+ const transitions = sourceNode.transitions.get(event.type);
717
+ if (transitions?.length !== 1) {
718
+ return undefined;
719
+ }
720
+ const selected = transitions[0];
721
+ if (selected.guard || selected.actions || selected.to || selected.reenter || selected.input || typeof selected.context === 'function' || selected.target && selected.target.length !== 1) {
722
+ return undefined;
723
+ }
724
+ const targetNode = selected.target?.[0] ?? sourceNode;
725
+ const stateChanged = targetNode !== sourceNode;
726
+ if (targetNode.parent !== this.root || targetNode.type !== 'atomic' || stateChanged && (targetNode.entry || targetNode.invoke.length || targetNode.always?.length || targetNode.after?.length)) {
727
+ return undefined;
728
+ }
729
+ const context = selected.context !== undefined ? {
730
+ ...snapshot.context,
731
+ ...selected.context
732
+ } : snapshot.context;
733
+ const collectedMicrosteps = actorScope.self._collectedMicrosteps || [];
734
+ collectedMicrosteps.push(selected);
735
+ actorScope.self._collectedMicrosteps = collectedMicrosteps;
736
+ return dist_xstateActors.cloneMachineSnapshot(snapshot, {
737
+ ...(context !== snapshot.context ? {
738
+ context
739
+ } : {}),
740
+ ...(stateChanged ? {
741
+ _nodes: [this.root, targetNode]
742
+ } : {})
743
+ });
744
+ }
745
+
746
+ /**
747
+ * Determines the next state given the current `state` and `event`. Calculates
748
+ * a microstep.
749
+ *
750
+ * @param state The current state
751
+ * @param event The received event
752
+ */
753
+ microstep(snapshot, event, actorScope) {
754
+ const {
755
+ microsteps
756
+ } = dist_xstateActors.macrostep(snapshot, event, actorScope, []);
757
+ const snapshots = new Array(microsteps.length);
758
+ for (let i = 0; i < microsteps.length; i++) {
759
+ snapshots[i] = microsteps[i][0];
760
+ }
761
+ return snapshots;
762
+ }
763
+ getTransitionData(snapshot, event, self) {
764
+ return dist_xstateActors.transitionNode(this.root, snapshot.value, snapshot, event, self) || [];
765
+ }
766
+ isInternalEventType(eventType) {
767
+ if (eventType === dist_xstateActors.XSTATE_TIMER) {
768
+ return true;
769
+ }
770
+ for (const descriptor of this.internalEventDescriptors) {
771
+ if (dist_xstateActors.matchesEventDescriptor(eventType, descriptor)) {
772
+ return true;
773
+ }
774
+ }
775
+ return false;
776
+ }
777
+
778
+ /**
779
+ * Determines whether sending the `event` to the given snapshot would select a
780
+ * non-forbidden transition. Backs `snapshot.can(...)`; lives here so that
781
+ * non-machine bundles don't pay for the transition-resolution machinery.
782
+ *
783
+ * @internal
784
+ */
785
+ _canTransition(snapshot, event) {
786
+ const emptyActor = getEmptyCanActor();
787
+ const emptyActorScope = getEmptyCanActorScope();
788
+ const transitionData = this.getTransitionData(snapshot, event, emptyActor);
789
+ if (!transitionData?.length) {
790
+ return false;
791
+ }
792
+
793
+ // Check that at least one transition is not forbidden
794
+ for (const transition of transitionData) {
795
+ if (transition.target !== undefined) {
796
+ return true;
797
+ }
798
+ const res = dist_xstateActors.getTransitionResult(transition, snapshot, event, emptyActorScope, {
799
+ resolveActions: false
800
+ });
801
+ if (res.targets?.length || res.context || dist_xstateActors.hasEffect(transition, snapshot.context, event, snapshot, emptyActor)) {
802
+ return true;
803
+ }
804
+ }
805
+ return false;
806
+ }
807
+
808
+ /**
809
+ * Returns the error event that the actor should transition with to recover
810
+ * from an execution error, if any active state node declares `onError`.
811
+ *
812
+ * @internal
813
+ */
814
+ getExecutionErrorEvent(snapshot, error) {
815
+ if (snapshot?.status !== 'active' || !snapshot._nodes?.some(stateNode => stateNode.config.onError)) {
816
+ return undefined;
817
+ }
818
+ return dist_xstateActors.createErrorPlatformEvent('execution', error);
819
+ }
820
+
821
+ /**
822
+ * The initial state _before_ evaluating any microsteps. This "pre-initial"
823
+ * state is provided to initial actions executed in the initial state.
824
+ *
825
+ * @internal
826
+ */
827
+ _getPreInitialState(actorScope, initEvent) {
828
+ const {
829
+ context
830
+ } = this.config;
831
+ const preInitial = dist_xstateActors.createMachineSnapshot({
832
+ context: typeof context !== 'function' && context ? context : {},
833
+ _nodes: [this.root],
834
+ children: {},
835
+ status: 'active'
836
+ }, this, actorScope.self);
837
+ if (typeof context === 'function') {
838
+ const children = {};
839
+ const spawn = createSpawner(actorScope, this.sources.actors, children);
840
+ const resolvedContext = context({
841
+ spawn,
842
+ input: initEvent.input,
843
+ self: actorScope.self,
844
+ actors: this.sources.actors
845
+ });
846
+ const [nextState] = dist_xstateActors.resolveActionsWithContext(preInitial, initEvent, actorScope, []);
847
+ if (resolvedContext) {
848
+ nextState.context = resolvedContext;
849
+ }
850
+ if (Object.keys(children).length > 0) {
851
+ nextState.children = {
852
+ ...nextState.children,
853
+ ...children
854
+ };
855
+ }
856
+ return nextState;
857
+ }
858
+ return preInitial;
859
+ }
860
+
861
+ /**
862
+ * Returns the initial `State` instance, with reference to `self` as an
863
+ * `ActorRef`.
864
+ */
865
+ getInitialSnapshot(actorScope, input) {
866
+ return this.initialTransition(input, actorScope)[0];
867
+ }
868
+ initialTransition(input, actorScope) {
869
+ if (this.validator) {
870
+ dist_xstateActors.assertValid(this.validator, {
871
+ kind: 'input',
872
+ logic: this,
873
+ input
874
+ });
875
+ }
876
+ const usesInertScope = !actorScope;
877
+ const resolvedActorScope = actorScope ?? createInertActorScope(this);
878
+ const initEvent = dist_xstateActors.createInitEvent(input); // TODO: fix;
879
+ const internalQueue = [];
880
+ const preInitialState = this._getPreInitialState(resolvedActorScope, initEvent);
881
+ const contextSpawnEffects = Object.values(preInitialState.children).filter(Boolean).map(actor => dist_xstateActors.createSpawnEffect(actor));
882
+ const finalizeInitialResult = (macroState, microsteps) => {
883
+ if (usesInertScope) {
884
+ setInertActorScopeSnapshot(resolvedActorScope, macroState, false);
885
+ }
886
+ const returnedSnapshot = usesInertScope ? attachSnapshotActorRef(this, resolvedActorScope, macroState) : this._attachPureActorRef(macroState, resolvedActorScope);
887
+ const effects = this._collectEffects(microsteps);
888
+ if (this.validator) {
889
+ dist_xstateActors.assertValid(this.validator, {
890
+ kind: 'result',
891
+ logic: this,
892
+ snapshot: returnedSnapshot,
893
+ effects
894
+ });
895
+ }
896
+ return [returnedSnapshot, effects];
897
+ };
898
+ try {
899
+ const [nextState, initialActions] = dist_xstateActors.initialMicrostep(this.root, preInitialState, resolvedActorScope, initEvent, internalQueue);
900
+ const {
901
+ snapshot: macroState,
902
+ microsteps
903
+ } = dist_xstateActors.macrostep(nextState, initEvent, resolvedActorScope, internalQueue, [[nextState, [...contextSpawnEffects, ...initialActions]]]);
904
+ return finalizeInitialResult(macroState, microsteps);
905
+ } catch (err) {
906
+ if (!this.root.config.onError) {
907
+ throw err;
908
+ }
909
+ const errorEvent = dist_xstateActors.createErrorPlatformEvent('execution', err);
910
+ const errorMacrostep = dist_xstateActors.macrostep(preInitialState, errorEvent, resolvedActorScope, [], [[preInitialState, contextSpawnEffects]]);
911
+ return finalizeInitialResult(errorMacrostep.snapshot, errorMacrostep.microsteps);
912
+ }
913
+ }
914
+ start(snapshot) {
915
+ // Start rehydrated children that were active when persisted. Freshly
916
+ // invoked/spawned children are NOT started here — they start via deferred
917
+ // `@xstate.start` actions so sync start errors route to `onError`.
918
+ if (!snapshot?.children) {
919
+ return;
920
+ }
921
+ for (const child of Object.values(snapshot.children)) {
922
+ if (child._rehydrated && child.getSnapshot?.().status === 'active') {
923
+ child.start();
924
+ }
925
+ }
926
+ }
927
+ getStateNodeById(stateId) {
928
+ const fullPath = dist_xstateActors.toStatePath(stateId);
929
+ const relativePath = fullPath.slice(1);
930
+ const resolvedStateId = dist_xstateActors.isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER.length) : fullPath[0];
931
+ const stateNode = this.idMap.get(resolvedStateId);
932
+ if (!stateNode) {
933
+ throw new Error(`Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`);
934
+ }
935
+ return dist_xstateActors.getStateNodeByPath(stateNode, relativePath);
936
+ }
937
+ getPersistedSnapshot(snapshot, options) {
938
+ return dist_xstateActors.getPersistedSnapshot(snapshot, options);
939
+ }
940
+ restoreSnapshot(snapshot, actorScope) {
941
+ const usesInertScope = !actorScope;
942
+ const resolvedActorScope = actorScope ?? createInertActorScope(this);
943
+ const persistedMachine = snapshot.machine;
944
+ const legacyPersistedVersion = snapshot.version;
945
+ const persistedVersion = typeof persistedMachine?.version === 'string' ? persistedMachine.version : legacyPersistedVersion;
946
+ if (legacyPersistedVersion !== undefined && persistedMachine?.version !== undefined && persistedMachine.version !== legacyPersistedVersion) {
947
+ throw new Error(`Persisted snapshot version '${legacyPersistedVersion}' conflicts with machine version '${persistedMachine.version}'.`);
948
+ }
949
+ if (persistedMachine && typeof persistedMachine.id === 'string' && persistedMachine.id !== this.id) {
950
+ throw new Error(`Machine ID mismatch: persisted snapshot machine '${persistedMachine.id}' does not match '${this.id}'.`);
951
+ }
952
+ if (persistedVersion !== this.version) {
953
+ const migrate = this.config.migrate;
954
+ if (typeof migrate !== 'function') {
955
+ throw new Error(`Persisted snapshot version '${persistedVersion}' does not match machine version '${this.version}'.`);
956
+ }
957
+ snapshot = migrate(snapshot, persistedVersion);
958
+ }
959
+ const snapshotData = snapshot;
960
+ const children = {};
961
+ const snapshotChildren = snapshotData.children;
962
+ for (const actorId of Object.keys(snapshotChildren)) {
963
+ const actorData = snapshotChildren[actorId];
964
+ const childState = actorData.snapshot;
965
+ const src = actorData.src;
966
+ const logic = typeof src === 'string' ? dist_xstateActors.resolveReferencedActor(this, src) : src;
967
+ if (!logic) {
968
+ const sourceId = typeof src === 'string' ? src : '<unknown>';
969
+ throw new Error(`Unable to restore child actor '${actorId}': child source '${sourceId}' is not provided in machine '${this.id}'.`);
970
+ }
971
+ const actor = resolvedActorScope.system.createActorRef(logic, {
972
+ id: actorId,
973
+ parent: resolvedActorScope.self,
974
+ syncSnapshot: actorData.syncSnapshot,
975
+ snapshot: childState,
976
+ src,
977
+ registryKey: actorData.registryKey
978
+ });
979
+ // Mark so `start()` knows to start this child (freshly invoked/spawned
980
+ // children are started via deferred `@xstate.start` actions instead).
981
+ actor._rehydrated = true;
982
+ children[actorId] = actor;
983
+ }
984
+ const timers = {};
985
+ const persistedTimers = snapshotData.timers ?? {};
986
+ for (const [id, timer] of Object.entries(persistedTimers)) {
987
+ let event = timer.event;
988
+ if (event.type === 'xstate.timeout.actor') {
989
+ const actorId = event.actorId;
990
+ const child = children[actorId];
991
+ if (child) {
992
+ event = dist_xstateActors.createInvokeTimeoutEvent(actorId, child.sessionId);
993
+ }
994
+ }
995
+ const target = typeof timer.target === 'string' ? timer.target === 'self' ? 'self' : children[timer.target] : resolvedActorScope.self._parent;
996
+ if (!target) {
997
+ const targetDescription = typeof timer.target === 'string' ? timer.target : timer.target.type;
998
+ throw new Error(`Unable to restore timer '${id}': target actor '${targetDescription}' is unavailable.`);
999
+ }
1000
+ timers[id] = {
1001
+ ...timer,
1002
+ event,
1003
+ target
1004
+ };
1005
+ }
1006
+ const reviveHistoryValue = historyValue => {
1007
+ if (!historyValue || typeof historyValue !== 'object') {
1008
+ return {};
1009
+ }
1010
+ const revived = {};
1011
+ for (const key of Object.keys(historyValue)) {
1012
+ const arr = historyValue[key];
1013
+ for (const item of arr) {
1014
+ let resolved;
1015
+ if (item instanceof StateNode) {
1016
+ resolved = item;
1017
+ } else {
1018
+ try {
1019
+ resolved = this.root.machine.getStateNodeById(item.id);
1020
+ } catch {
1021
+ }
1022
+ }
1023
+ if (!resolved) {
1024
+ continue;
1025
+ }
1026
+ revived[key] ??= [];
1027
+ revived[key].push(resolved);
1028
+ }
1029
+ }
1030
+ return revived;
1031
+ };
1032
+ const revivedHistoryValue = reviveHistoryValue(snapshotData.historyValue);
1033
+ const nodes = Array.from(dist_xstateActors.getAllStateNodes(dist_xstateActors.getStateNodes(this.root, snapshotData.value)));
1034
+ const {
1035
+ version: _persistedSnapshotVersion,
1036
+ ...persistedRest
1037
+ } = snapshot;
1038
+ const restoredSnapshot = dist_xstateActors.createMachineSnapshot({
1039
+ ...persistedRest,
1040
+ children,
1041
+ timers,
1042
+ _nodes: nodes,
1043
+ value: snapshotData.value,
1044
+ historyValue: revivedHistoryValue,
1045
+ _stateInputs: snapshotData.stateInputs ?? {}
1046
+ }, this, resolvedActorScope.self);
1047
+ const seen = new WeakSet();
1048
+ function reviveContext(contextPart) {
1049
+ if (seen.has(contextPart)) {
1050
+ return;
1051
+ }
1052
+ seen.add(contextPart);
1053
+ for (const key of Object.keys(contextPart)) {
1054
+ const value = contextPart[key];
1055
+ if (value && typeof value === 'object') {
1056
+ if ('xstate$$type' in value && value.xstate$$type === dist_xstateActors.$$ACTOR_TYPE) {
1057
+ contextPart[key] = children[value.id];
1058
+ continue;
1059
+ }
1060
+ reviveContext(value);
1061
+ }
1062
+ }
1063
+ }
1064
+ reviveContext(restoredSnapshot.context);
1065
+ if (usesInertScope) {
1066
+ setInertActorScopeSnapshot(resolvedActorScope, restoredSnapshot, false);
1067
+ return attachSnapshotActorRef(this, resolvedActorScope, restoredSnapshot);
1068
+ }
1069
+ return this._attachPureActorRef(restoredSnapshot, resolvedActorScope);
1070
+ }
1071
+ }
1072
+
1073
+ exports.StateMachine = StateMachine;
1074
+ exports.StateNode = StateNode;
1075
+ exports.attachSnapshotActorRef = attachSnapshotActorRef;
1076
+ exports.createInertActorScope = createInertActorScope;
1077
+ exports.getInitialSnapshot = getInitialSnapshot;
1078
+ exports.getNextSnapshot = getNextSnapshot;
1079
+ exports.setInertActorScopeSnapshot = setInertActorScopeSnapshot;