xstate 5.32.1 → 6.0.0-alpha.2

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 (119) hide show
  1. package/README.md +7 -8
  2. package/dist/StateMachine-2dcdb1f5.esm.js +720 -0
  3. package/dist/StateMachine-2ea0a7fa.development.esm.js +737 -0
  4. package/dist/StateMachine-64813f46.cjs.js +723 -0
  5. package/dist/StateMachine-8d22a79c.development.cjs.js +740 -0
  6. package/dist/declarations/src/State.d.ts +11 -13
  7. package/dist/declarations/src/StateMachine.d.ts +27 -21
  8. package/dist/declarations/src/StateNode.d.ts +18 -54
  9. package/dist/declarations/src/actions.d.ts +14 -9
  10. package/dist/declarations/src/actors/callback.d.ts +42 -16
  11. package/dist/declarations/src/actors/index.d.ts +9 -6
  12. package/dist/declarations/src/actors/listener.d.ts +18 -0
  13. package/dist/declarations/src/actors/logic.d.ts +105 -0
  14. package/dist/declarations/src/actors/observable.d.ts +72 -27
  15. package/dist/declarations/src/actors/promise.d.ts +133 -48
  16. package/dist/declarations/src/actors/subscription.d.ts +22 -0
  17. package/dist/declarations/src/atom.d.ts +81 -0
  18. package/dist/declarations/src/createActor.d.ts +31 -33
  19. package/dist/declarations/src/createMachine.d.ts +35 -7
  20. package/dist/declarations/src/createMachineFromConfig.d.ts +176 -0
  21. package/dist/declarations/src/graph/graph.d.ts +4 -2
  22. package/dist/declarations/src/index.d.ts +12 -8
  23. package/dist/declarations/src/inspection.d.ts +84 -30
  24. package/dist/declarations/src/mapState.d.ts +4 -2
  25. package/dist/declarations/src/schema.types.d.ts +90 -0
  26. package/dist/declarations/src/serialize.d.ts +44 -0
  27. package/dist/declarations/src/setup.d.ts +251 -135
  28. package/dist/declarations/src/spawn.d.ts +6 -31
  29. package/dist/declarations/src/stateUtils.d.ts +21 -19
  30. package/dist/declarations/src/system.d.ts +8 -7
  31. package/dist/declarations/src/transition.d.ts +5 -5
  32. package/dist/declarations/src/types.d.ts +405 -405
  33. package/dist/declarations/src/types.v6.d.ts +392 -0
  34. package/dist/declarations/src/utils.d.ts +4 -3
  35. package/dist/index-93edd3bd.esm.js +4909 -0
  36. package/dist/index-9cb3b3a0.cjs.js +4968 -0
  37. package/dist/index-e61170ba.development.esm.js +4948 -0
  38. package/dist/index-f6ef20d1.development.cjs.js +5007 -0
  39. package/dist/xstate-actors.cjs.js +12 -838
  40. package/dist/xstate-actors.cjs.mjs +10 -5
  41. package/dist/xstate-actors.development.cjs.js +12 -838
  42. package/dist/xstate-actors.development.cjs.mjs +10 -5
  43. package/dist/xstate-actors.development.esm.js +1 -836
  44. package/dist/xstate-actors.esm.js +1 -836
  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 +18 -29
  48. package/dist/xstate-graph.development.cjs.js +18 -29
  49. package/dist/xstate-graph.development.esm.js +15 -26
  50. package/dist/xstate-graph.esm.js +15 -26
  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.cjs.js +1316 -112
  54. package/dist/xstate.cjs.mjs +22 -22
  55. package/dist/xstate.development.cjs.js +1316 -112
  56. package/dist/xstate.development.cjs.mjs +22 -22
  57. package/dist/xstate.development.esm.js +1278 -76
  58. package/dist/xstate.esm.js +1278 -76
  59. package/dist/xstate.umd.min.js +1 -1
  60. package/dist/xstate.umd.min.js.map +1 -1
  61. package/package.json +3 -47
  62. package/dist/StateMachine-45e79c35.esm.js +0 -560
  63. package/dist/StateMachine-be2e51a3.development.cjs.js +0 -569
  64. package/dist/StateMachine-e0178d48.development.esm.js +0 -566
  65. package/dist/StateMachine-e6732977.cjs.js +0 -563
  66. package/dist/assign-2aa58daa.esm.js +0 -127
  67. package/dist/assign-927227d6.development.cjs.js +0 -135
  68. package/dist/assign-e8f2bd75.cjs.js +0 -129
  69. package/dist/assign-f338cee3.development.esm.js +0 -133
  70. package/dist/declarations/src/actions/assign.d.ts +0 -45
  71. package/dist/declarations/src/actions/cancel.d.ts +0 -39
  72. package/dist/declarations/src/actions/emit.d.ts +0 -44
  73. package/dist/declarations/src/actions/enqueueActions.d.ts +0 -57
  74. package/dist/declarations/src/actions/log.d.ts +0 -16
  75. package/dist/declarations/src/actions/raise.d.ts +0 -21
  76. package/dist/declarations/src/actions/send.d.ts +0 -42
  77. package/dist/declarations/src/actions/spawnChild.d.ts +0 -34
  78. package/dist/declarations/src/actions/stopChild.d.ts +0 -19
  79. package/dist/declarations/src/actors/transition.d.ts +0 -143
  80. package/dist/declarations/src/dev/index.d.ts +0 -14
  81. package/dist/declarations/src/guards.d.ts +0 -128
  82. package/dist/log-410e5e55.development.esm.js +0 -429
  83. package/dist/log-7776fcf2.cjs.js +0 -409
  84. package/dist/log-c2e11c01.development.cjs.js +0 -437
  85. package/dist/log-fa75ec2d.esm.js +0 -401
  86. package/dist/raise-74097812.development.esm.js +0 -2823
  87. package/dist/raise-7c948725.cjs.js +0 -2816
  88. package/dist/raise-964cd4e9.development.cjs.js +0 -2878
  89. package/dist/raise-e974d1c9.esm.js +0 -2761
  90. package/dist/xstate-actions.cjs.d.mts +0 -2
  91. package/dist/xstate-actions.cjs.d.ts +0 -2
  92. package/dist/xstate-actions.cjs.js +0 -23
  93. package/dist/xstate-actions.cjs.mjs +0 -14
  94. package/dist/xstate-actions.development.cjs.js +0 -23
  95. package/dist/xstate-actions.development.cjs.mjs +0 -14
  96. package/dist/xstate-actions.development.esm.js +0 -4
  97. package/dist/xstate-actions.esm.js +0 -4
  98. package/dist/xstate-actions.umd.min.js +0 -2
  99. package/dist/xstate-actions.umd.min.js.map +0 -1
  100. package/dist/xstate-dev.cjs.d.mts +0 -2
  101. package/dist/xstate-dev.cjs.d.ts +0 -2
  102. package/dist/xstate-dev.cjs.js +0 -48
  103. package/dist/xstate-dev.cjs.mjs +0 -5
  104. package/dist/xstate-dev.development.cjs.js +0 -51
  105. package/dist/xstate-dev.development.cjs.mjs +0 -5
  106. package/dist/xstate-dev.development.esm.js +0 -45
  107. package/dist/xstate-dev.esm.js +0 -42
  108. package/dist/xstate-dev.umd.min.js +0 -2
  109. package/dist/xstate-dev.umd.min.js.map +0 -1
  110. package/dist/xstate-guards.cjs.d.mts +0 -2
  111. package/dist/xstate-guards.cjs.d.ts +0 -2
  112. package/dist/xstate-guards.cjs.js +0 -14
  113. package/dist/xstate-guards.cjs.mjs +0 -7
  114. package/dist/xstate-guards.development.cjs.js +0 -14
  115. package/dist/xstate-guards.development.cjs.mjs +0 -7
  116. package/dist/xstate-guards.development.esm.js +0 -2
  117. package/dist/xstate-guards.esm.js +0 -2
  118. package/dist/xstate-guards.umd.min.js +0 -2
  119. package/dist/xstate-guards.umd.min.js.map +0 -1
@@ -1,566 +0,0 @@
1
- import { S as STATE_DELIMITER, y as mapValues, t as toArray, z as formatTransitions, B as toTransitionConfigArray, C as formatTransition, N as NULL_EVENT, D as evaluateGuard, E as createInvokeId, F as getDelayedTransitions, G as formatInitialTransition, H as getCandidates, I as formatRouteTransitions, J as resolveStateValue, K as getAllStateNodes, p as getStateNodes, L as createMachineSnapshot, M as isInFinalState, d as macrostep, O as transitionNode, P as resolveActionsAndContext, e as createInitEvent, f as initialMicrostep, Q as toStatePath, R as isStateId, T as getStateNodeByPath, U as getPersistedSnapshot, V as resolveReferencedActor, c as createActor, $ as $$ACTOR_TYPE } from './raise-74097812.development.esm.js';
2
- import { a as assign } from './assign-f338cee3.development.esm.js';
3
-
4
- const cache = new WeakMap();
5
- function memo(object, key, fn) {
6
- let memoizedData = cache.get(object);
7
- if (!memoizedData) {
8
- memoizedData = {
9
- [key]: fn()
10
- };
11
- cache.set(object, memoizedData);
12
- } else if (!(key in memoizedData)) {
13
- memoizedData[key] = fn();
14
- }
15
- return memoizedData[key];
16
- }
17
-
18
- const EMPTY_OBJECT = {};
19
- const toSerializableAction = action => {
20
- if (typeof action === 'string') {
21
- return {
22
- type: action
23
- };
24
- }
25
- if (typeof action === 'function') {
26
- if ('resolve' in action) {
27
- return {
28
- type: action.type
29
- };
30
- }
31
- return {
32
- type: action.name
33
- };
34
- }
35
- return action;
36
- };
37
- class StateNode {
38
- constructor(/** The raw config used to create the machine. */
39
- config, options) {
40
- this.config = config;
41
- /**
42
- * The relative key of the state node, which represents its location in the
43
- * overall state value.
44
- */
45
- this.key = void 0;
46
- /** The unique ID of the state node. */
47
- this.id = void 0;
48
- /**
49
- * The type of this state node:
50
- *
51
- * - `'atomic'` - no child state nodes
52
- * - `'compound'` - nested child state nodes (XOR)
53
- * - `'parallel'` - orthogonal nested child state nodes (AND)
54
- * - `'history'` - history state node
55
- * - `'final'` - final state node
56
- */
57
- this.type = void 0;
58
- /** The string path from the root machine node to this node. */
59
- this.path = void 0;
60
- /** The child state nodes. */
61
- this.states = void 0;
62
- /**
63
- * The type of history on this state node. Can be:
64
- *
65
- * - `'shallow'` - recalls only top-level historical state value
66
- * - `'deep'` - recalls historical state value at all levels
67
- */
68
- this.history = void 0;
69
- /** The action(s) to be executed upon entering the state node. */
70
- this.entry = void 0;
71
- /** The action(s) to be executed upon exiting the state node. */
72
- this.exit = void 0;
73
- /** The parent state node. */
74
- this.parent = void 0;
75
- /** The root machine node. */
76
- this.machine = void 0;
77
- /**
78
- * The meta data associated with this state node, which will be returned in
79
- * State instances.
80
- */
81
- this.meta = void 0;
82
- /**
83
- * The output data sent with the "xstate.done.state._id_" event if this is a
84
- * final state node.
85
- */
86
- this.output = void 0;
87
- /**
88
- * The order this state node appears. Corresponds to the implicit document
89
- * order.
90
- */
91
- this.order = -1;
92
- this.description = void 0;
93
- this.tags = [];
94
- this.transitions = void 0;
95
- this.always = void 0;
96
- this.parent = options._parent;
97
- this.key = options._key;
98
- this.machine = options._machine;
99
- this.path = this.parent ? this.parent.path.concat(this.key) : [];
100
- this.id = this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);
101
- this.type = this.config.type || (this.config.states && Object.keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic');
102
- this.description = this.config.description;
103
- this.order = this.machine.idMap.size;
104
- this.machine.idMap.set(this.id, this);
105
- this.states = this.config.states ? mapValues(this.config.states, (stateConfig, key) => {
106
- const stateNode = new StateNode(stateConfig, {
107
- _parent: this,
108
- _key: key,
109
- _machine: this.machine
110
- });
111
- return stateNode;
112
- }) : EMPTY_OBJECT;
113
- if (this.type === 'compound' && !this.config.initial) {
114
- throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);
115
- }
116
-
117
- // History config
118
- this.history = this.config.history === true ? 'shallow' : this.config.history || false;
119
- this.entry = toArray(this.config.entry).slice();
120
- this.exit = toArray(this.config.exit).slice();
121
- this.meta = this.config.meta;
122
- this.output = this.type === 'final' || !this.parent ? this.config.output : undefined;
123
- this.tags = toArray(config.tags).slice();
124
- }
125
-
126
- /** @internal */
127
- _initialize() {
128
- this.transitions = formatTransitions(this);
129
- if (this.config.always) {
130
- this.always = toTransitionConfigArray(this.config.always).map(t => formatTransition(this, NULL_EVENT, t));
131
- }
132
- Object.keys(this.states).forEach(key => {
133
- this.states[key]._initialize();
134
- });
135
- }
136
-
137
- /** The well-structured state node definition. */
138
- get definition() {
139
- return {
140
- id: this.id,
141
- key: this.key,
142
- version: this.machine.version,
143
- type: this.type,
144
- initial: this.initial ? {
145
- target: this.initial.target,
146
- source: this,
147
- actions: this.initial.actions.map(toSerializableAction),
148
- eventType: null,
149
- reenter: false,
150
- toJSON: () => ({
151
- target: this.initial.target.map(t => `#${t.id}`),
152
- source: `#${this.id}`,
153
- actions: this.initial.actions.map(toSerializableAction),
154
- eventType: null
155
- })
156
- } : undefined,
157
- history: this.history,
158
- states: mapValues(this.states, state => {
159
- return state.definition;
160
- }),
161
- on: this.on,
162
- transitions: [...this.transitions.values()].flat().map(t => ({
163
- ...t,
164
- actions: t.actions.map(toSerializableAction)
165
- })),
166
- entry: this.entry.map(toSerializableAction),
167
- exit: this.exit.map(toSerializableAction),
168
- meta: this.meta,
169
- order: this.order || -1,
170
- output: this.output,
171
- invoke: this.invoke,
172
- description: this.description,
173
- tags: this.tags
174
- };
175
- }
176
-
177
- /** @internal */
178
- toJSON() {
179
- return this.definition;
180
- }
181
-
182
- /** The logic invoked as actors by this state node. */
183
- get invoke() {
184
- return memo(this, 'invoke', () => toArray(this.config.invoke).map((invokeConfig, i) => {
185
- const {
186
- src,
187
- systemId
188
- } = invokeConfig;
189
- const resolvedId = invokeConfig.id ?? createInvokeId(this.id, i);
190
- const sourceName = typeof src === 'string' ? src : `xstate.invoke.${createInvokeId(this.id, i)}`;
191
- return {
192
- ...invokeConfig,
193
- src: sourceName,
194
- id: resolvedId,
195
- systemId: systemId,
196
- toJSON() {
197
- const {
198
- onDone,
199
- onError,
200
- ...invokeDefValues
201
- } = invokeConfig;
202
- return {
203
- ...invokeDefValues,
204
- type: 'xstate.invoke',
205
- src: sourceName,
206
- id: resolvedId
207
- };
208
- }
209
- };
210
- }));
211
- }
212
-
213
- /** The mapping of events to transitions. */
214
- get on() {
215
- return memo(this, 'on', () => {
216
- const transitions = this.transitions;
217
- return [...transitions].flatMap(([descriptor, t]) => t.map(t => [descriptor, t])).reduce((map, [descriptor, transition]) => {
218
- map[descriptor] = map[descriptor] || [];
219
- map[descriptor].push(transition);
220
- return map;
221
- }, {});
222
- });
223
- }
224
- get after() {
225
- return memo(this, 'delayedTransitions', () => getDelayedTransitions(this));
226
- }
227
- get initial() {
228
- return memo(this, 'initial', () => formatInitialTransition(this, this.config.initial));
229
- }
230
-
231
- /** @internal */
232
- next(snapshot, event) {
233
- const eventType = event.type;
234
- const actions = [];
235
- let selectedTransition;
236
- const candidates = memo(this, `candidates-${eventType}`, () => getCandidates(this, eventType));
237
- for (const candidate of candidates) {
238
- const {
239
- guard
240
- } = candidate;
241
- const resolvedContext = snapshot.context;
242
- let guardPassed = false;
243
- try {
244
- guardPassed = !guard || evaluateGuard(guard, resolvedContext, event, snapshot);
245
- } catch (err) {
246
- const guardType = typeof guard === 'string' ? guard : typeof guard === 'object' ? guard.type : undefined;
247
- throw new Error(`Unable to evaluate guard ${guardType ? `'${guardType}' ` : ''}in transition for event '${eventType}' in state node '${this.id}':\n${err.message}`);
248
- }
249
- if (guardPassed) {
250
- actions.push(...candidate.actions);
251
- selectedTransition = candidate;
252
- break;
253
- }
254
- }
255
- return selectedTransition ? [selectedTransition] : undefined;
256
- }
257
-
258
- /** All the event types accepted by this state node and its descendants. */
259
- get events() {
260
- return memo(this, 'events', () => {
261
- const {
262
- states
263
- } = this;
264
- const events = new Set(this.ownEvents);
265
- if (states) {
266
- for (const stateId of Object.keys(states)) {
267
- const state = states[stateId];
268
- if (state.states) {
269
- for (const event of state.events) {
270
- events.add(`${event}`);
271
- }
272
- }
273
- }
274
- }
275
- return Array.from(events);
276
- });
277
- }
278
-
279
- /**
280
- * All the events that have transitions directly from this state node.
281
- *
282
- * Excludes any inert events.
283
- */
284
- get ownEvents() {
285
- const keys = Object.keys(Object.fromEntries(this.transitions));
286
- const events = new Set(keys.filter(descriptor => {
287
- return this.transitions.get(descriptor).some(transition => !(!transition.target && !transition.actions.length && !transition.reenter));
288
- }));
289
- return Array.from(events);
290
- }
291
- }
292
-
293
- const STATE_IDENTIFIER = '#';
294
- class StateMachine {
295
- constructor(/** The raw config used to create the machine. */
296
- config, implementations) {
297
- this.config = config;
298
- /** The machine's own version. */
299
- this.version = void 0;
300
- this.schemas = void 0;
301
- this.implementations = void 0;
302
- /** Runtime options for machine execution. */
303
- this.options = void 0;
304
- /** @internal */
305
- this.__xstatenode = true;
306
- /** @internal */
307
- this.idMap = new Map();
308
- this.root = void 0;
309
- this.id = void 0;
310
- this.states = void 0;
311
- this.events = void 0;
312
- this.id = config.id || '(machine)';
313
- this.implementations = {
314
- actors: implementations?.actors ?? {},
315
- actions: implementations?.actions ?? {},
316
- delays: implementations?.delays ?? {},
317
- guards: implementations?.guards ?? {}
318
- };
319
- this.version = this.config.version;
320
- this.schemas = this.config.schemas;
321
- this.options = {
322
- maxIterations: Infinity,
323
- ...this.config.options
324
- };
325
- this.transition = this.transition.bind(this);
326
- this.getInitialSnapshot = this.getInitialSnapshot.bind(this);
327
- this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);
328
- this.restoreSnapshot = this.restoreSnapshot.bind(this);
329
- this.start = this.start.bind(this);
330
- this.root = new StateNode(config, {
331
- _key: this.id,
332
- _machine: this
333
- });
334
- this.root._initialize();
335
- formatRouteTransitions(this.root);
336
- this.states = this.root.states; // TODO: remove!
337
- this.events = this.root.events;
338
- if (!('output' in this.root) && Object.values(this.states).some(state => state.type === 'final' && 'output' in state)) {
339
- console.warn('Missing `machine.output` declaration (top-level final state with output detected)');
340
- }
341
- }
342
-
343
- /**
344
- * Clones this state machine with the provided implementations.
345
- *
346
- * @param implementations Options (`actions`, `guards`, `actors`, `delays`) to
347
- * recursively merge with the existing options.
348
- * @returns A new `StateMachine` instance with the provided implementations.
349
- */
350
- provide(implementations) {
351
- const {
352
- actions,
353
- guards,
354
- actors,
355
- delays
356
- } = this.implementations;
357
- return new StateMachine(this.config, {
358
- actions: {
359
- ...actions,
360
- ...implementations.actions
361
- },
362
- guards: {
363
- ...guards,
364
- ...implementations.guards
365
- },
366
- actors: {
367
- ...actors,
368
- ...implementations.actors
369
- },
370
- delays: {
371
- ...delays,
372
- ...implementations.delays
373
- }
374
- });
375
- }
376
- resolveState(config) {
377
- const resolvedStateValue = resolveStateValue(this.root, config.value);
378
- const nodeSet = getAllStateNodes(getStateNodes(this.root, resolvedStateValue));
379
- return createMachineSnapshot({
380
- _nodes: [...nodeSet],
381
- context: config.context || {},
382
- children: {},
383
- status: isInFinalState(nodeSet, this.root) ? 'done' : config.status || 'active',
384
- output: config.output,
385
- error: config.error,
386
- historyValue: config.historyValue
387
- }, this);
388
- }
389
-
390
- /**
391
- * Determines the next snapshot given the current `snapshot` and received
392
- * `event`. Calculates a full macrostep from all microsteps.
393
- *
394
- * @param snapshot The current snapshot
395
- * @param event The received event
396
- */
397
- transition(snapshot, event, actorScope) {
398
- return macrostep(snapshot, event, actorScope, []).snapshot;
399
- }
400
-
401
- /**
402
- * Determines the next state given the current `state` and `event`. Calculates
403
- * a microstep.
404
- *
405
- * @param state The current state
406
- * @param event The received event
407
- */
408
- microstep(snapshot, event, actorScope) {
409
- return macrostep(snapshot, event, actorScope, []).microsteps.map(([s]) => s);
410
- }
411
- getTransitionData(snapshot, event) {
412
- return transitionNode(this.root, snapshot.value, snapshot, event) || [];
413
- }
414
-
415
- /**
416
- * The initial state _before_ evaluating any microsteps. This "pre-initial"
417
- * state is provided to initial actions executed in the initial state.
418
- *
419
- * @internal
420
- */
421
- _getPreInitialState(actorScope, initEvent, internalQueue) {
422
- const {
423
- context
424
- } = this.config;
425
- const preInitial = createMachineSnapshot({
426
- context: typeof context !== 'function' && context ? context : {},
427
- _nodes: [this.root],
428
- children: {},
429
- status: 'active'
430
- }, this);
431
- if (typeof context === 'function') {
432
- const assignment = ({
433
- spawn,
434
- event,
435
- self
436
- }) => context({
437
- spawn,
438
- input: event.input,
439
- self
440
- });
441
- return resolveActionsAndContext(preInitial, initEvent, actorScope, [assign(assignment)], internalQueue, undefined);
442
- }
443
- return preInitial;
444
- }
445
-
446
- /**
447
- * Returns the initial `State` instance, with reference to `self` as an
448
- * `ActorRef`.
449
- */
450
- getInitialSnapshot(actorScope, input) {
451
- const initEvent = createInitEvent(input); // TODO: fix;
452
- const internalQueue = [];
453
- const preInitialState = this._getPreInitialState(actorScope, initEvent, internalQueue);
454
- const [nextState] = initialMicrostep(this.root, preInitialState, actorScope, initEvent, internalQueue);
455
- const {
456
- snapshot: macroState
457
- } = macrostep(nextState, initEvent, actorScope, internalQueue);
458
- return macroState;
459
- }
460
- start(snapshot) {
461
- Object.values(snapshot.children).forEach(child => {
462
- if (child.getSnapshot().status === 'active') {
463
- child.start();
464
- }
465
- });
466
- }
467
- getStateNodeById(stateId) {
468
- const fullPath = toStatePath(stateId);
469
- const relativePath = fullPath.slice(1);
470
- const resolvedStateId = isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER.length) : fullPath[0];
471
- const stateNode = this.idMap.get(resolvedStateId);
472
- if (!stateNode) {
473
- throw new Error(`Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`);
474
- }
475
- return getStateNodeByPath(stateNode, relativePath);
476
- }
477
- get definition() {
478
- return this.root.definition;
479
- }
480
- toJSON() {
481
- return this.definition;
482
- }
483
- getPersistedSnapshot(snapshot, options) {
484
- return getPersistedSnapshot(snapshot, options);
485
- }
486
- restoreSnapshot(snapshot, _actorScope) {
487
- const children = {};
488
- const snapshotChildren = snapshot.children;
489
- Object.keys(snapshotChildren).forEach(actorId => {
490
- const actorData = snapshotChildren[actorId];
491
- const childState = actorData.snapshot;
492
- const src = actorData.src;
493
- const logic = typeof src === 'string' ? resolveReferencedActor(this, src) : src;
494
- if (!logic) {
495
- return;
496
- }
497
- const actorRef = createActor(logic, {
498
- id: actorId,
499
- parent: _actorScope.self,
500
- syncSnapshot: actorData.syncSnapshot,
501
- snapshot: childState,
502
- src,
503
- systemId: actorData.systemId
504
- });
505
- children[actorId] = actorRef;
506
- });
507
- function resolveHistoryReferencedState(root, referenced) {
508
- if (referenced instanceof StateNode) {
509
- return referenced;
510
- }
511
- try {
512
- return root.machine.getStateNodeById(referenced.id);
513
- } catch {
514
- {
515
- console.warn(`Could not resolve StateNode for id: ${referenced.id}`);
516
- }
517
- }
518
- }
519
- function reviveHistoryValue(root, historyValue) {
520
- if (!historyValue || typeof historyValue !== 'object') {
521
- return {};
522
- }
523
- const revived = {};
524
- for (const key in historyValue) {
525
- const arr = historyValue[key];
526
- for (const item of arr) {
527
- const resolved = resolveHistoryReferencedState(root, item);
528
- if (!resolved) {
529
- continue;
530
- }
531
- revived[key] ??= [];
532
- revived[key].push(resolved);
533
- }
534
- }
535
- return revived;
536
- }
537
- const revivedHistoryValue = reviveHistoryValue(this.root, snapshot.historyValue);
538
- const restoredSnapshot = createMachineSnapshot({
539
- ...snapshot,
540
- children,
541
- _nodes: Array.from(getAllStateNodes(getStateNodes(this.root, snapshot.value))),
542
- historyValue: revivedHistoryValue
543
- }, this);
544
- const seen = new Set();
545
- function reviveContext(contextPart, children) {
546
- if (seen.has(contextPart)) {
547
- return;
548
- }
549
- seen.add(contextPart);
550
- for (const key in contextPart) {
551
- const value = contextPart[key];
552
- if (value && typeof value === 'object') {
553
- if ('xstate$$type' in value && value.xstate$$type === $$ACTOR_TYPE) {
554
- contextPart[key] = children[value.id];
555
- continue;
556
- }
557
- reviveContext(value, children);
558
- }
559
- }
560
- }
561
- reviveContext(restoredSnapshot.context, children);
562
- return restoredSnapshot;
563
- }
564
- }
565
-
566
- export { StateMachine as S, StateNode as a };