xstate 6.0.0-alpha.3 → 6.0.0-alpha.32

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