xstate 5.0.0-beta.9 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +10 -8
  2. package/actions/dist/xstate-actions.cjs.js +19 -5
  3. package/actions/dist/xstate-actions.cjs.mjs +3 -15
  4. package/actions/dist/xstate-actions.development.cjs.js +21 -0
  5. package/actions/dist/xstate-actions.development.cjs.mjs +13 -0
  6. package/actions/dist/xstate-actions.development.esm.js +3 -0
  7. package/actions/dist/xstate-actions.esm.js +3 -2
  8. package/actions/dist/xstate-actions.umd.min.js +1 -1
  9. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  10. package/actors/dist/xstate-actors.cjs.js +621 -4
  11. package/actors/dist/xstate-actors.cjs.mjs +1 -8
  12. package/actors/dist/xstate-actors.development.cjs.js +624 -0
  13. package/actors/dist/xstate-actors.development.cjs.mjs +8 -0
  14. package/actors/dist/xstate-actors.development.esm.js +615 -0
  15. package/actors/dist/xstate-actors.esm.js +615 -2
  16. package/actors/dist/xstate-actors.umd.min.js +1 -1
  17. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  18. package/dev/dist/xstate-dev.cjs.js +45 -4
  19. package/{dist/index-0f3fdf0c.cjs.prod.js → dev/dist/xstate-dev.development.cjs.js} +6 -7
  20. package/dev/dist/xstate-dev.development.cjs.mjs +5 -0
  21. package/{dist/index-50bd0aff.esm.js → dev/dist/xstate-dev.development.esm.js} +6 -8
  22. package/dev/dist/xstate-dev.esm.js +42 -1
  23. package/dev/dist/xstate-dev.umd.min.js +1 -1
  24. package/dev/dist/xstate-dev.umd.min.js.map +1 -1
  25. package/dist/declarations/src/SimulatedClock.d.ts +1 -1
  26. package/dist/declarations/src/State.d.ts +47 -73
  27. package/dist/declarations/src/StateMachine.d.ts +29 -57
  28. package/dist/declarations/src/StateNode.d.ts +36 -33
  29. package/dist/declarations/src/actions/assign.d.ts +11 -2
  30. package/dist/declarations/src/actions/cancel.d.ts +7 -3
  31. package/dist/declarations/src/actions/enqueueActions.d.ts +32 -0
  32. package/dist/declarations/src/actions/log.d.ts +7 -3
  33. package/dist/declarations/src/actions/raise.d.ts +7 -2
  34. package/dist/declarations/src/actions/send.d.ts +14 -36
  35. package/dist/declarations/src/actions/spawnChild.d.ts +29 -0
  36. package/dist/declarations/src/actions/stopChild.d.ts +18 -0
  37. package/dist/declarations/src/actions.d.ts +8 -48
  38. package/dist/declarations/src/actors/callback.d.ts +91 -8
  39. package/dist/declarations/src/actors/index.d.ts +6 -28
  40. package/dist/declarations/src/actors/observable.d.ts +101 -18
  41. package/dist/declarations/src/actors/promise.d.ts +80 -10
  42. package/dist/declarations/src/actors/transition.d.ts +64 -9
  43. package/dist/declarations/src/constants.d.ts +3 -0
  44. package/dist/declarations/src/createMachine.d.ts +20 -0
  45. package/dist/declarations/src/dev/index.d.ts +6 -6
  46. package/dist/declarations/src/guards.d.ts +41 -8
  47. package/dist/declarations/src/index.d.ts +18 -23
  48. package/dist/declarations/src/interpreter.d.ts +149 -41
  49. package/dist/declarations/src/setup.d.ts +51 -0
  50. package/dist/declarations/src/spawn.d.ts +23 -2
  51. package/dist/declarations/src/stateUtils.d.ts +30 -45
  52. package/dist/declarations/src/system.d.ts +26 -2
  53. package/dist/declarations/src/typegenTypes.d.ts +34 -22
  54. package/dist/declarations/src/types.d.ts +527 -669
  55. package/dist/declarations/src/utils.d.ts +15 -52
  56. package/dist/declarations/src/waitFor.d.ts +2 -2
  57. package/dist/log-22e678c5.esm.js +364 -0
  58. package/dist/log-5e226275.cjs.js +372 -0
  59. package/dist/log-641cd926.development.cjs.js +394 -0
  60. package/dist/log-f196f85f.development.esm.js +386 -0
  61. package/dist/raise-34e25c2c.cjs.js +2368 -0
  62. package/dist/raise-62704519.development.cjs.js +2422 -0
  63. package/dist/raise-89c581c4.development.esm.js +2371 -0
  64. package/dist/raise-8bc422d1.esm.js +2317 -0
  65. package/dist/xstate.cjs.js +728 -4
  66. package/dist/xstate.cjs.mjs +9 -9
  67. package/dist/xstate.development.cjs.js +737 -0
  68. package/dist/xstate.development.cjs.mjs +39 -0
  69. package/dist/xstate.development.esm.js +699 -0
  70. package/dist/xstate.esm.js +561 -770
  71. package/dist/xstate.umd.min.js +1 -1
  72. package/dist/xstate.umd.min.js.map +1 -1
  73. package/guards/dist/xstate-guards.cjs.js +12 -5
  74. package/guards/dist/xstate-guards.cjs.mjs +1 -2
  75. package/guards/dist/xstate-guards.development.cjs.js +14 -0
  76. package/guards/dist/xstate-guards.development.cjs.mjs +7 -0
  77. package/guards/dist/xstate-guards.development.esm.js +2 -0
  78. package/guards/dist/xstate-guards.esm.js +2 -2
  79. package/guards/dist/xstate-guards.umd.min.js +1 -1
  80. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  81. package/package.json +53 -1
  82. package/actions/dist/xstate-actions.cjs.dev.js +0 -32
  83. package/actions/dist/xstate-actions.cjs.prod.js +0 -32
  84. package/actions/dynamicAction.ts +0 -42
  85. package/actors/dist/xstate-actors.cjs.dev.js +0 -22
  86. package/actors/dist/xstate-actors.cjs.prod.js +0 -22
  87. package/dev/dist/xstate-dev.cjs.dev.js +0 -11
  88. package/dev/dist/xstate-dev.cjs.prod.js +0 -11
  89. package/dist/actions-b6357569.cjs.dev.js +0 -4437
  90. package/dist/actions-bd4a184d.cjs.prod.js +0 -4423
  91. package/dist/actions-de434a04.esm.js +0 -4348
  92. package/dist/declarations/actions/dynamicAction.d.ts +0 -5
  93. package/dist/declarations/src/Machine.d.ts +0 -4
  94. package/dist/declarations/src/Mailbox.d.ts +0 -12
  95. package/dist/declarations/src/actionTypes.d.ts +0 -16
  96. package/dist/declarations/src/actions/choose.d.ts +0 -3
  97. package/dist/declarations/src/actions/invoke.d.ts +0 -3
  98. package/dist/declarations/src/actions/pure.d.ts +0 -6
  99. package/dist/declarations/src/actions/stop.d.ts +0 -7
  100. package/dist/declarations/src/environment.d.ts +0 -1
  101. package/dist/declarations/src/mapState.d.ts +0 -3
  102. package/dist/declarations/src/memo.d.ts +0 -2
  103. package/dist/index-ebaab3c9.cjs.dev.js +0 -52
  104. package/dist/xstate.cjs.dev.js +0 -950
  105. package/dist/xstate.cjs.prod.js +0 -947
  106. package/guards/dist/xstate-guards.cjs.dev.js +0 -15
  107. package/guards/dist/xstate-guards.cjs.prod.js +0 -15
@@ -0,0 +1,699 @@
1
+ export { createEmptyActor, fromCallback, fromEventObservable, fromObservable, fromPromise, fromTransition } from '../actors/dist/xstate-actors.development.esm.js';
2
+ import { S as STATE_DELIMITER, m as mapValues, t as toArray, f as formatTransitions, a as toTransitionConfigArray, b as formatTransition, N as NULL_EVENT, e as evaluateGuard, c as createInvokeId, g as getDelayedTransitions, d as formatInitialTransition, h as getCandidates, r as resolveStateValue, i as getAllStateNodes, j as getStateNodes, k as createMachineSnapshot, l as isInFinalState, n as macrostep, o as transitionNode, p as resolveActionsAndContext, q as createInitEvent, s as microstep, u as getInitialStateNodes, v as isStateId, w as getStateNodeByPath, x as getPersistedSnapshot, y as resolveReferencedActor, z as createActor, $ as $$ACTOR_TYPE } from './raise-89c581c4.development.esm.js';
3
+ export { A as Actor, G as __unsafe_getAllOwnEventDescriptors, H as and, L as cancel, z as createActor, j as getStateNodes, B as interpret, C as isMachineSnapshot, D as matchesState, I as not, J as or, E as pathToStateValue, M as raise, O as spawnChild, K as stateIn, P as stop, Q as stopChild, F as toObserver } from './raise-89c581c4.development.esm.js';
4
+ import { a as assign } from './log-f196f85f.development.esm.js';
5
+ export { S as SpecialTargets, a as assign, e as enqueueActions, f as forwardTo, l as log, s as sendParent, b as sendTo } from './log-f196f85f.development.esm.js';
6
+ import '../dev/dist/xstate-dev.development.esm.js';
7
+
8
+ class SimulatedClock {
9
+ constructor() {
10
+ this.timeouts = new Map();
11
+ this._now = 0;
12
+ this._id = 0;
13
+ }
14
+ now() {
15
+ return this._now;
16
+ }
17
+ getId() {
18
+ return this._id++;
19
+ }
20
+ setTimeout(fn, timeout) {
21
+ const id = this.getId();
22
+ this.timeouts.set(id, {
23
+ start: this.now(),
24
+ timeout,
25
+ fn
26
+ });
27
+ return id;
28
+ }
29
+ clearTimeout(id) {
30
+ this.timeouts.delete(id);
31
+ }
32
+ set(time) {
33
+ if (this._now > time) {
34
+ throw new Error('Unable to travel back in time');
35
+ }
36
+ this._now = time;
37
+ this.flushTimeouts();
38
+ }
39
+ flushTimeouts() {
40
+ [...this.timeouts].sort(([_idA, timeoutA], [_idB, timeoutB]) => {
41
+ const endA = timeoutA.start + timeoutA.timeout;
42
+ const endB = timeoutB.start + timeoutB.timeout;
43
+ return endB > endA ? -1 : 1;
44
+ }).forEach(([id, timeout]) => {
45
+ if (this.now() - timeout.start >= timeout.timeout) {
46
+ this.timeouts.delete(id);
47
+ timeout.fn.call(null);
48
+ }
49
+ });
50
+ }
51
+ increment(ms) {
52
+ this._now += ms;
53
+ this.flushTimeouts();
54
+ }
55
+ }
56
+
57
+ const cache = new WeakMap();
58
+ function memo(object, key, fn) {
59
+ let memoizedData = cache.get(object);
60
+ if (!memoizedData) {
61
+ memoizedData = {
62
+ [key]: fn()
63
+ };
64
+ cache.set(object, memoizedData);
65
+ } else if (!(key in memoizedData)) {
66
+ memoizedData[key] = fn();
67
+ }
68
+ return memoizedData[key];
69
+ }
70
+
71
+ const EMPTY_OBJECT = {};
72
+ const toSerializableAction = action => {
73
+ if (typeof action === 'string') {
74
+ return {
75
+ type: action
76
+ };
77
+ }
78
+ if (typeof action === 'function') {
79
+ if ('resolve' in action) {
80
+ return {
81
+ type: action.type
82
+ };
83
+ }
84
+ return {
85
+ type: action.name
86
+ };
87
+ }
88
+ return action;
89
+ };
90
+ class StateNode {
91
+ constructor(
92
+ /**
93
+ * The raw config used to create the machine.
94
+ */
95
+ config, options) {
96
+ this.config = config;
97
+ /**
98
+ * The relative key of the state node, which represents its location in the overall state value.
99
+ */
100
+ this.key = void 0;
101
+ /**
102
+ * The unique ID of the state node.
103
+ */
104
+ this.id = void 0;
105
+ /**
106
+ * The type of this state node:
107
+ *
108
+ * - `'atomic'` - no child state nodes
109
+ * - `'compound'` - nested child state nodes (XOR)
110
+ * - `'parallel'` - orthogonal nested child state nodes (AND)
111
+ * - `'history'` - history state node
112
+ * - `'final'` - final state node
113
+ */
114
+ this.type = void 0;
115
+ /**
116
+ * The string path from the root machine node to this node.
117
+ */
118
+ this.path = void 0;
119
+ /**
120
+ * The child state nodes.
121
+ */
122
+ this.states = void 0;
123
+ /**
124
+ * The type of history on this state node. Can be:
125
+ *
126
+ * - `'shallow'` - recalls only top-level historical state value
127
+ * - `'deep'` - recalls historical state value at all levels
128
+ */
129
+ this.history = void 0;
130
+ /**
131
+ * The action(s) to be executed upon entering the state node.
132
+ */
133
+ this.entry = void 0;
134
+ /**
135
+ * The action(s) to be executed upon exiting the state node.
136
+ */
137
+ this.exit = void 0;
138
+ /**
139
+ * The parent state node.
140
+ */
141
+ this.parent = void 0;
142
+ /**
143
+ * The root machine node.
144
+ */
145
+ this.machine = void 0;
146
+ /**
147
+ * The meta data associated with this state node, which will be returned in State instances.
148
+ */
149
+ this.meta = void 0;
150
+ /**
151
+ * The output data sent with the "xstate.done.state._id_" event if this is a final state node.
152
+ */
153
+ this.output = void 0;
154
+ /**
155
+ * The order this state node appears. Corresponds to the implicit document order.
156
+ */
157
+ this.order = -1;
158
+ this.description = void 0;
159
+ this.tags = [];
160
+ this.transitions = void 0;
161
+ this.always = void 0;
162
+ this.parent = options._parent;
163
+ this.key = options._key;
164
+ this.machine = options._machine;
165
+ this.path = this.parent ? this.parent.path.concat(this.key) : [];
166
+ this.id = this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);
167
+ this.type = this.config.type || (this.config.states && Object.keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic');
168
+ this.description = this.config.description;
169
+ this.order = this.machine.idMap.size;
170
+ this.machine.idMap.set(this.id, this);
171
+ this.states = this.config.states ? mapValues(this.config.states, (stateConfig, key) => {
172
+ const stateNode = new StateNode(stateConfig, {
173
+ _parent: this,
174
+ _key: key,
175
+ _machine: this.machine
176
+ });
177
+ return stateNode;
178
+ }) : EMPTY_OBJECT;
179
+ if (this.type === 'compound' && !this.config.initial) {
180
+ 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.`);
181
+ }
182
+
183
+ // History config
184
+ this.history = this.config.history === true ? 'shallow' : this.config.history || false;
185
+ this.entry = toArray(this.config.entry).slice();
186
+ this.exit = toArray(this.config.exit).slice();
187
+ this.meta = this.config.meta;
188
+ this.output = this.type === 'final' || !this.parent ? this.config.output : undefined;
189
+ this.tags = toArray(config.tags).slice();
190
+ }
191
+ _initialize() {
192
+ this.transitions = formatTransitions(this);
193
+ if (this.config.always) {
194
+ this.always = toTransitionConfigArray(this.config.always).map(t => formatTransition(this, NULL_EVENT, t));
195
+ }
196
+ Object.keys(this.states).forEach(key => {
197
+ this.states[key]._initialize();
198
+ });
199
+ }
200
+
201
+ /**
202
+ * The well-structured state node definition.
203
+ */
204
+ get definition() {
205
+ return {
206
+ id: this.id,
207
+ key: this.key,
208
+ version: this.machine.version,
209
+ type: this.type,
210
+ initial: this.initial ? {
211
+ target: this.initial.target,
212
+ source: this,
213
+ actions: this.initial.actions.map(toSerializableAction),
214
+ eventType: null,
215
+ reenter: false,
216
+ toJSON: () => ({
217
+ target: this.initial.target.map(t => `#${t.id}`),
218
+ source: `#${this.id}`,
219
+ actions: this.initial.actions.map(toSerializableAction),
220
+ eventType: null
221
+ })
222
+ } : undefined,
223
+ history: this.history,
224
+ states: mapValues(this.states, state => {
225
+ return state.definition;
226
+ }),
227
+ on: this.on,
228
+ transitions: [...this.transitions.values()].flat().map(t => ({
229
+ ...t,
230
+ actions: t.actions.map(toSerializableAction)
231
+ })),
232
+ entry: this.entry.map(toSerializableAction),
233
+ exit: this.exit.map(toSerializableAction),
234
+ meta: this.meta,
235
+ order: this.order || -1,
236
+ output: this.output,
237
+ invoke: this.invoke,
238
+ description: this.description,
239
+ tags: this.tags
240
+ };
241
+ }
242
+ toJSON() {
243
+ return this.definition;
244
+ }
245
+
246
+ /**
247
+ * The logic invoked as actors by this state node.
248
+ */
249
+ get invoke() {
250
+ return memo(this, 'invoke', () => toArray(this.config.invoke).map((invokeConfig, i) => {
251
+ const {
252
+ src,
253
+ systemId
254
+ } = invokeConfig;
255
+ const resolvedId = invokeConfig.id ?? createInvokeId(this.id, i);
256
+ const resolvedSrc = typeof src === 'string' ? src : `xstate.invoke.${createInvokeId(this.id, i)}`;
257
+ return {
258
+ ...invokeConfig,
259
+ src: resolvedSrc,
260
+ id: resolvedId,
261
+ systemId: systemId,
262
+ toJSON() {
263
+ const {
264
+ onDone,
265
+ onError,
266
+ ...invokeDefValues
267
+ } = invokeConfig;
268
+ return {
269
+ ...invokeDefValues,
270
+ type: 'xstate.invoke',
271
+ src: resolvedSrc,
272
+ id: resolvedId
273
+ };
274
+ }
275
+ };
276
+ }));
277
+ }
278
+
279
+ /**
280
+ * The mapping of events to transitions.
281
+ */
282
+ get on() {
283
+ return memo(this, 'on', () => {
284
+ const transitions = this.transitions;
285
+ return [...transitions].flatMap(([descriptor, t]) => t.map(t => [descriptor, t])).reduce((map, [descriptor, transition]) => {
286
+ map[descriptor] = map[descriptor] || [];
287
+ map[descriptor].push(transition);
288
+ return map;
289
+ }, {});
290
+ });
291
+ }
292
+ get after() {
293
+ return memo(this, 'delayedTransitions', () => getDelayedTransitions(this));
294
+ }
295
+ get initial() {
296
+ return memo(this, 'initial', () => formatInitialTransition(this, this.config.initial));
297
+ }
298
+ next(snapshot, event) {
299
+ const eventType = event.type;
300
+ const actions = [];
301
+ let selectedTransition;
302
+ const candidates = memo(this, `candidates-${eventType}`, () => getCandidates(this, eventType));
303
+ for (const candidate of candidates) {
304
+ const {
305
+ guard
306
+ } = candidate;
307
+ const resolvedContext = snapshot.context;
308
+ let guardPassed = false;
309
+ try {
310
+ guardPassed = !guard || evaluateGuard(guard, resolvedContext, event, snapshot);
311
+ } catch (err) {
312
+ const guardType = typeof guard === 'string' ? guard : typeof guard === 'object' ? guard.type : undefined;
313
+ throw new Error(`Unable to evaluate guard ${guardType ? `'${guardType}' ` : ''}in transition for event '${eventType}' in state node '${this.id}':\n${err.message}`);
314
+ }
315
+ if (guardPassed) {
316
+ actions.push(...candidate.actions);
317
+ selectedTransition = candidate;
318
+ break;
319
+ }
320
+ }
321
+ return selectedTransition ? [selectedTransition] : undefined;
322
+ }
323
+
324
+ /**
325
+ * All the event types accepted by this state node and its descendants.
326
+ */
327
+ get events() {
328
+ return memo(this, 'events', () => {
329
+ const {
330
+ states
331
+ } = this;
332
+ const events = new Set(this.ownEvents);
333
+ if (states) {
334
+ for (const stateId of Object.keys(states)) {
335
+ const state = states[stateId];
336
+ if (state.states) {
337
+ for (const event of state.events) {
338
+ events.add(`${event}`);
339
+ }
340
+ }
341
+ }
342
+ }
343
+ return Array.from(events);
344
+ });
345
+ }
346
+
347
+ /**
348
+ * All the events that have transitions directly from this state node.
349
+ *
350
+ * Excludes any inert events.
351
+ */
352
+ get ownEvents() {
353
+ const events = new Set([...this.transitions.keys()].filter(descriptor => {
354
+ return this.transitions.get(descriptor).some(transition => !(!transition.target && !transition.actions.length && !transition.reenter));
355
+ }));
356
+ return Array.from(events);
357
+ }
358
+ }
359
+
360
+ const STATE_IDENTIFIER = '#';
361
+ class StateMachine {
362
+ constructor(
363
+ /**
364
+ * The raw config used to create the machine.
365
+ */
366
+ config, implementations) {
367
+ this.config = config;
368
+ /**
369
+ * The machine's own version.
370
+ */
371
+ this.version = void 0;
372
+ this.implementations = void 0;
373
+ this.__xstatenode = true;
374
+ this.idMap = new Map();
375
+ this.root = void 0;
376
+ this.id = void 0;
377
+ this.states = void 0;
378
+ this.events = void 0;
379
+ /** @deprecated an internal property acting as a "phantom" type, not meant to be used at runtime */
380
+ this.__TResolvedTypesMeta = void 0;
381
+ this.id = config.id || '(machine)';
382
+ this.implementations = {
383
+ actors: implementations?.actors ?? {},
384
+ actions: implementations?.actions ?? {},
385
+ delays: implementations?.delays ?? {},
386
+ guards: implementations?.guards ?? {}
387
+ };
388
+ this.version = this.config.version;
389
+ this.transition = this.transition.bind(this);
390
+ this.getInitialSnapshot = this.getInitialSnapshot.bind(this);
391
+ this.restoreSnapshot = this.restoreSnapshot.bind(this);
392
+ this.start = this.start.bind(this);
393
+ this.root = new StateNode(config, {
394
+ _key: this.id,
395
+ _machine: this
396
+ });
397
+ this.root._initialize();
398
+ this.states = this.root.states; // TODO: remove!
399
+ this.events = this.root.events;
400
+ if (!this.root.output && Object.values(this.states).some(state => state.type === 'final' && !!state.output)) {
401
+ console.warn('Missing `machine.output` declaration (top-level final state with output detected)');
402
+ }
403
+ }
404
+
405
+ /**
406
+ * Clones this state machine with the provided implementations
407
+ * and merges the `context` (if provided).
408
+ *
409
+ * @param implementations Options (`actions`, `guards`, `actors`, `delays`, `context`)
410
+ * to recursively merge with the existing options.
411
+ *
412
+ * @returns A new `StateMachine` instance with the provided implementations.
413
+ */
414
+ provide(implementations) {
415
+ const {
416
+ actions,
417
+ guards,
418
+ actors,
419
+ delays
420
+ } = this.implementations;
421
+ return new StateMachine(this.config, {
422
+ actions: {
423
+ ...actions,
424
+ ...implementations.actions
425
+ },
426
+ guards: {
427
+ ...guards,
428
+ ...implementations.guards
429
+ },
430
+ actors: {
431
+ ...actors,
432
+ ...implementations.actors
433
+ },
434
+ delays: {
435
+ ...delays,
436
+ ...implementations.delays
437
+ }
438
+ });
439
+ }
440
+ resolveState(config) {
441
+ const resolvedStateValue = resolveStateValue(this.root, config.value);
442
+ const nodeSet = getAllStateNodes(getStateNodes(this.root, resolvedStateValue));
443
+ return createMachineSnapshot({
444
+ _nodes: [...nodeSet],
445
+ context: config.context || {},
446
+ children: {},
447
+ status: isInFinalState(nodeSet, this.root) ? 'done' : config.status || 'active',
448
+ output: config.output,
449
+ error: config.error,
450
+ historyValue: config.historyValue
451
+ }, this);
452
+ }
453
+
454
+ /**
455
+ * Determines the next snapshot given the current `snapshot` and received `event`.
456
+ * Calculates a full macrostep from all microsteps.
457
+ *
458
+ * @param snapshot The current snapshot
459
+ * @param event The received event
460
+ */
461
+ transition(snapshot, event, actorScope) {
462
+ return macrostep(snapshot, event, actorScope).snapshot;
463
+ }
464
+
465
+ /**
466
+ * Determines the next state given the current `state` and `event`.
467
+ * Calculates a microstep.
468
+ *
469
+ * @param state The current state
470
+ * @param event The received event
471
+ */
472
+ microstep(snapshot, event, actorScope) {
473
+ return macrostep(snapshot, event, actorScope).microstates;
474
+ }
475
+ getTransitionData(snapshot, event) {
476
+ return transitionNode(this.root, snapshot.value, snapshot, event) || [];
477
+ }
478
+
479
+ /**
480
+ * The initial state _before_ evaluating any microsteps.
481
+ * This "pre-initial" state is provided to initial actions executed in the initial state.
482
+ */
483
+ getPreInitialState(actorScope, initEvent, internalQueue) {
484
+ const {
485
+ context
486
+ } = this.config;
487
+ const preInitial = createMachineSnapshot({
488
+ context: typeof context !== 'function' && context ? context : {},
489
+ _nodes: [this.root],
490
+ children: {},
491
+ status: 'active'
492
+ }, this);
493
+ if (typeof context === 'function') {
494
+ const assignment = ({
495
+ spawn,
496
+ event
497
+ }) => context({
498
+ spawn,
499
+ input: event.input
500
+ });
501
+ return resolveActionsAndContext(preInitial, initEvent, actorScope, [assign(assignment)], internalQueue);
502
+ }
503
+ return preInitial;
504
+ }
505
+
506
+ /**
507
+ * Returns the initial `State` instance, with reference to `self` as an `ActorRef`.
508
+ */
509
+ getInitialSnapshot(actorScope, input) {
510
+ const initEvent = createInitEvent(input); // TODO: fix;
511
+ const internalQueue = [];
512
+ const preInitialState = this.getPreInitialState(actorScope, initEvent, internalQueue);
513
+ const nextState = microstep([{
514
+ target: [...getInitialStateNodes(this.root)],
515
+ source: this.root,
516
+ reenter: true,
517
+ actions: [],
518
+ eventType: null,
519
+ toJSON: null // TODO: fix
520
+ }], preInitialState, actorScope, initEvent, true, internalQueue);
521
+ const {
522
+ snapshot: macroState
523
+ } = macrostep(nextState, initEvent, actorScope, internalQueue);
524
+ return macroState;
525
+ }
526
+ start(snapshot) {
527
+ Object.values(snapshot.children).forEach(child => {
528
+ if (child.getSnapshot().status === 'active') {
529
+ child.start();
530
+ }
531
+ });
532
+ }
533
+ getStateNodeById(stateId) {
534
+ const fullPath = stateId.split(STATE_DELIMITER);
535
+ const relativePath = fullPath.slice(1);
536
+ const resolvedStateId = isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER.length) : fullPath[0];
537
+ const stateNode = this.idMap.get(resolvedStateId);
538
+ if (!stateNode) {
539
+ throw new Error(`Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`);
540
+ }
541
+ return getStateNodeByPath(stateNode, relativePath);
542
+ }
543
+ get definition() {
544
+ return this.root.definition;
545
+ }
546
+ toJSON() {
547
+ return this.definition;
548
+ }
549
+ getPersistedSnapshot(snapshot, options) {
550
+ return getPersistedSnapshot(snapshot, options);
551
+ }
552
+ restoreSnapshot(snapshot, _actorScope) {
553
+ const children = {};
554
+ const snapshotChildren = snapshot.children;
555
+ Object.keys(snapshotChildren).forEach(actorId => {
556
+ const actorData = snapshotChildren[actorId];
557
+ const childState = actorData.snapshot;
558
+ const src = actorData.src;
559
+ const logic = typeof src === 'string' ? resolveReferencedActor(this, src) : src;
560
+ if (!logic) {
561
+ return;
562
+ }
563
+ const actorRef = createActor(logic, {
564
+ id: actorId,
565
+ parent: _actorScope?.self,
566
+ syncSnapshot: actorData.syncSnapshot,
567
+ snapshot: childState,
568
+ src,
569
+ systemId: actorData.systemId
570
+ });
571
+ children[actorId] = actorRef;
572
+ });
573
+ const restoredSnapshot = createMachineSnapshot({
574
+ ...snapshot,
575
+ children,
576
+ _nodes: Array.from(getAllStateNodes(getStateNodes(this.root, snapshot.value)))
577
+ }, this);
578
+ let seen = new Set();
579
+ function reviveContext(contextPart, children) {
580
+ if (seen.has(contextPart)) {
581
+ return;
582
+ }
583
+ seen.add(contextPart);
584
+ for (let key in contextPart) {
585
+ const value = contextPart[key];
586
+ if (value && typeof value === 'object') {
587
+ if ('xstate$$type' in value && value.xstate$$type === $$ACTOR_TYPE) {
588
+ contextPart[key] = children[value.id];
589
+ continue;
590
+ }
591
+ reviveContext(value, children);
592
+ }
593
+ }
594
+ }
595
+ reviveContext(restoredSnapshot.context, children);
596
+ return restoredSnapshot;
597
+ }
598
+ }
599
+
600
+ const defaultWaitForOptions = {
601
+ timeout: Infinity // much more than 10 seconds
602
+ };
603
+
604
+ /**
605
+ * Subscribes to an actor ref and waits for its emitted value to satisfy
606
+ * a predicate, and then resolves with that value.
607
+ * Will throw if the desired state is not reached after a timeout
608
+ * (defaults to 10 seconds).
609
+ *
610
+ * @example
611
+ * ```js
612
+ * const state = await waitFor(someService, state => {
613
+ * return state.hasTag('loaded');
614
+ * });
615
+ *
616
+ * state.hasTag('loaded'); // true
617
+ * ```
618
+ *
619
+ * @param actorRef The actor ref to subscribe to
620
+ * @param predicate Determines if a value matches the condition to wait for
621
+ * @param options
622
+ * @returns A promise that eventually resolves to the emitted value
623
+ * that matches the condition
624
+ */
625
+ function waitFor(actorRef, predicate, options) {
626
+ const resolvedOptions = {
627
+ ...defaultWaitForOptions,
628
+ ...options
629
+ };
630
+ return new Promise((res, rej) => {
631
+ let done = false;
632
+ if (resolvedOptions.timeout < 0) {
633
+ console.error('`timeout` passed to `waitFor` is negative and it will reject its internal promise immediately.');
634
+ }
635
+ const handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(() => {
636
+ sub.unsubscribe();
637
+ rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));
638
+ }, resolvedOptions.timeout);
639
+ const dispose = () => {
640
+ clearTimeout(handle);
641
+ done = true;
642
+ sub?.unsubscribe();
643
+ };
644
+ function checkEmitted(emitted) {
645
+ if (predicate(emitted)) {
646
+ dispose();
647
+ res(emitted);
648
+ }
649
+ }
650
+ let sub; // avoid TDZ when disposing synchronously
651
+
652
+ // See if the current snapshot already matches the predicate
653
+ checkEmitted(actorRef.getSnapshot());
654
+ if (done) {
655
+ return;
656
+ }
657
+ sub = actorRef.subscribe({
658
+ next: checkEmitted,
659
+ error: err => {
660
+ dispose();
661
+ rej(err);
662
+ },
663
+ complete: () => {
664
+ dispose();
665
+ rej(new Error(`Actor terminated without satisfying predicate`));
666
+ }
667
+ });
668
+ if (done) {
669
+ sub.unsubscribe();
670
+ }
671
+ });
672
+ }
673
+
674
+ // this is not 100% accurate since we can't make parallel regions required in the result
675
+ // `TTestValue` doesn't encode this information anyhow for us to be able to do that
676
+ // this is fine for most practical use cases anyway though
677
+ function createMachine(config, implementations) {
678
+ return new StateMachine(config, implementations);
679
+ }
680
+
681
+ // at the moment we allow extra actors - ones that are not specified by `children`
682
+ // this could be reconsidered in the future
683
+ function setup({
684
+ actors,
685
+ actions,
686
+ guards,
687
+ delays
688
+ }) {
689
+ return {
690
+ createMachine: config => createMachine(config, {
691
+ actors,
692
+ actions,
693
+ guards,
694
+ delays
695
+ })
696
+ };
697
+ }
698
+
699
+ export { SimulatedClock, StateMachine, StateNode, createMachine, setup, waitFor };