xstate 5.24.0 → 5.25.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 (50) hide show
  1. package/actions/dist/xstate-actions.cjs.js +3 -3
  2. package/actions/dist/xstate-actions.development.cjs.js +3 -3
  3. package/actions/dist/xstate-actions.development.esm.js +3 -3
  4. package/actions/dist/xstate-actions.esm.js +3 -3
  5. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  6. package/actors/dist/xstate-actors.cjs.js +1 -1
  7. package/actors/dist/xstate-actors.development.cjs.js +1 -1
  8. package/actors/dist/xstate-actors.development.esm.js +1 -1
  9. package/actors/dist/xstate-actors.esm.js +1 -1
  10. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  11. package/dist/{StateMachine-d6caf9f3.development.esm.js → StateMachine-53479528.development.esm.js} +4 -3
  12. package/dist/{StateMachine-37bc3882.esm.js → StateMachine-a6d25621.esm.js} +4 -3
  13. package/dist/{StateMachine-4f3286fa.development.cjs.js → StateMachine-e3bf357b.development.cjs.js} +4 -3
  14. package/dist/{StateMachine-30081029.cjs.js → StateMachine-f73271f9.cjs.js} +4 -3
  15. package/dist/{assign-9e730107.development.cjs.js → assign-97062f30.development.cjs.js} +1 -1
  16. package/dist/{assign-dea9f7c8.cjs.js → assign-ae103a72.cjs.js} +1 -1
  17. package/dist/{assign-445527dc.development.esm.js → assign-ef1b62f6.development.esm.js} +1 -1
  18. package/dist/{assign-ab9cc19e.esm.js → assign-fd69c737.esm.js} +1 -1
  19. package/dist/declarations/src/State.d.ts +5 -5
  20. package/dist/declarations/src/StateMachine.d.ts +10 -10
  21. package/dist/declarations/src/assert.d.ts +2 -4
  22. package/dist/declarations/src/setup.d.ts +13 -8
  23. package/dist/declarations/src/types.d.ts +1 -1
  24. package/dist/declarations/src/utils.d.ts +13 -0
  25. package/dist/{log-2aa3642a.development.esm.js → log-3eec9346.development.esm.js} +2 -2
  26. package/dist/{log-cbac1abc.development.cjs.js → log-bf2198dc.development.cjs.js} +2 -2
  27. package/dist/{log-ec8d4df4.cjs.js → log-ec818628.cjs.js} +2 -2
  28. package/dist/{log-7cbae384.esm.js → log-fbb00743.esm.js} +2 -2
  29. package/dist/{raise-c096f887.development.esm.js → raise-235fa0c7.development.esm.js} +46 -31
  30. package/dist/{raise-f777a9e8.development.cjs.js → raise-723edf2d.development.cjs.js} +46 -30
  31. package/dist/{raise-da5b247f.cjs.js → raise-ad4f12ad.cjs.js} +40 -24
  32. package/dist/{raise-9ad1c5c6.esm.js → raise-da2ff7ca.esm.js} +40 -25
  33. package/dist/xstate.cjs.js +10 -6
  34. package/dist/xstate.development.cjs.js +10 -6
  35. package/dist/xstate.development.esm.js +14 -10
  36. package/dist/xstate.esm.js +14 -10
  37. package/dist/xstate.umd.min.js +1 -1
  38. package/dist/xstate.umd.min.js.map +1 -1
  39. package/graph/dist/xstate-graph.cjs.js +3 -3
  40. package/graph/dist/xstate-graph.development.cjs.js +3 -3
  41. package/graph/dist/xstate-graph.development.esm.js +3 -3
  42. package/graph/dist/xstate-graph.esm.js +3 -3
  43. package/graph/dist/xstate-graph.umd.min.js +1 -1
  44. package/graph/dist/xstate-graph.umd.min.js.map +1 -1
  45. package/guards/dist/xstate-guards.cjs.js +1 -1
  46. package/guards/dist/xstate-guards.development.cjs.js +1 -1
  47. package/guards/dist/xstate-guards.development.esm.js +1 -1
  48. package/guards/dist/xstate-guards.esm.js +1 -1
  49. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  50. package/package.json +1 -1
@@ -283,6 +283,44 @@ function getAllOwnEventDescriptors(snapshot) {
283
283
  return [...new Set([...snapshot._nodes.flatMap(sn => sn.ownEvents)])];
284
284
  }
285
285
 
286
+ /**
287
+ * Checks if an event type matches an event descriptor, supporting wildcards.
288
+ * Event descriptors can be:
289
+ *
290
+ * - Exact matches: "event.type"
291
+ * - Wildcard: "*"
292
+ * - Partial matches: "event.*"
293
+ *
294
+ * @param eventType - The actual event type string
295
+ * @param descriptor - The event descriptor to match against
296
+ * @returns True if the event type matches the descriptor
297
+ */
298
+ function matchesEventDescriptor(eventType, descriptor) {
299
+ if (descriptor === eventType) {
300
+ return true;
301
+ }
302
+ if (descriptor === WILDCARD) {
303
+ return true;
304
+ }
305
+ if (!descriptor.endsWith('.*')) {
306
+ return false;
307
+ }
308
+ const partialEventTokens = descriptor.split('.');
309
+ const eventTokens = eventType.split('.');
310
+ for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
311
+ const partialEventToken = partialEventTokens[tokenIndex];
312
+ const eventToken = eventTokens[tokenIndex];
313
+ if (partialEventToken === '*') {
314
+ const isLastToken = tokenIndex === partialEventTokens.length - 1;
315
+ return isLastToken;
316
+ }
317
+ if (partialEventToken !== eventToken) {
318
+ return false;
319
+ }
320
+ }
321
+ return true;
322
+ }
323
+
286
324
  function createScheduledEventId(actorRef, id) {
287
325
  return `${actorRef.sessionId}.${id}`;
288
326
  }
@@ -1586,30 +1624,7 @@ function isInFinalState(stateNodeSet, stateNode) {
1586
1624
  }
1587
1625
  const isStateId = str => str[0] === STATE_IDENTIFIER;
1588
1626
  function getCandidates(stateNode, receivedEventType) {
1589
- const candidates = stateNode.transitions.get(receivedEventType) || [...stateNode.transitions.keys()].filter(eventDescriptor => {
1590
- // check if transition is a wildcard transition,
1591
- // which matches any non-transient events
1592
- if (eventDescriptor === WILDCARD) {
1593
- return true;
1594
- }
1595
- if (!eventDescriptor.endsWith('.*')) {
1596
- return false;
1597
- }
1598
- const partialEventTokens = eventDescriptor.split('.');
1599
- const eventTokens = receivedEventType.split('.');
1600
- for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
1601
- const partialEventToken = partialEventTokens[tokenIndex];
1602
- const eventToken = eventTokens[tokenIndex];
1603
- if (partialEventToken === '*') {
1604
- const isLastToken = tokenIndex === partialEventTokens.length - 1;
1605
- return isLastToken;
1606
- }
1607
- if (partialEventToken !== eventToken) {
1608
- return false;
1609
- }
1610
- }
1611
- return true;
1612
- }).sort((a, b) => b.length - a.length).flatMap(key => stateNode.transitions.get(key));
1627
+ const candidates = stateNode.transitions.get(receivedEventType) || [...stateNode.transitions.keys()].filter(eventDescriptor => matchesEventDescriptor(receivedEventType, eventDescriptor)).sort((a, b) => b.length - a.length).flatMap(key => stateNode.transitions.get(key));
1613
1628
  return candidates;
1614
1629
  }
1615
1630
 
@@ -2650,4 +2665,4 @@ function raise(eventOrExpr, options) {
2650
2665
  return raise;
2651
2666
  }
2652
2667
 
2653
- export { $$ACTOR_TYPE as $, Actor as A, getCandidates as B, resolveStateValue as C, getAllStateNodes as D, createMachineSnapshot as E, isInFinalState as F, macrostep as G, transitionNode as H, resolveActionsAndContext as I, createInitEvent as J, microstep as K, getInitialStateNodes as L, toStatePath as M, NULL_EVENT as N, isStateId as O, getStateNodeByPath as P, getPersistedSnapshot as Q, resolveReferencedActor as R, STATE_DELIMITER as S, XSTATE_ERROR as T, createErrorActorEvent as U, ProcessingStatus as V, cloneMachineSnapshot as W, XSTATE_STOP as X, cancel as a, spawnChild as b, createActor as c, and as d, stateIn as e, isMachineSnapshot as f, getStateNodes as g, getAllOwnEventDescriptors as h, interpret as i, toObserver as j, stop as k, mapValues as l, matchesState as m, not as n, or as o, pathToStateValue as p, formatTransitions as q, raise as r, stopChild as s, toArray as t, toTransitionConfigArray as u, formatTransition as v, evaluateGuard as w, createInvokeId as x, getDelayedTransitions as y, formatInitialTransition as z };
2668
+ export { $$ACTOR_TYPE as $, Actor as A, formatInitialTransition as B, getCandidates as C, resolveStateValue as D, getAllStateNodes as E, createMachineSnapshot as F, isInFinalState as G, macrostep as H, transitionNode as I, resolveActionsAndContext as J, createInitEvent as K, microstep as L, getInitialStateNodes as M, NULL_EVENT as N, toStatePath as O, isStateId as P, getStateNodeByPath as Q, getPersistedSnapshot as R, STATE_DELIMITER as S, resolveReferencedActor as T, XSTATE_ERROR as U, createErrorActorEvent as V, ProcessingStatus as W, XSTATE_STOP as X, cloneMachineSnapshot as Y, cancel as a, spawnChild as b, createActor as c, and as d, stateIn as e, isMachineSnapshot as f, getStateNodes as g, getAllOwnEventDescriptors as h, interpret as i, matchesState as j, toObserver as k, stop as l, matchesEventDescriptor as m, not as n, or as o, pathToStateValue as p, mapValues as q, raise as r, stopChild as s, toArray as t, formatTransitions as u, toTransitionConfigArray as v, formatTransition as w, evaluateGuard as x, createInvokeId as y, getDelayedTransitions as z };
@@ -3,10 +3,10 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var actors_dist_xstateActors = require('../actors/dist/xstate-actors.cjs.js');
6
- var guards_dist_xstateGuards = require('./raise-da5b247f.cjs.js');
7
- var StateMachine = require('./StateMachine-30081029.cjs.js');
8
- var assign = require('./assign-dea9f7c8.cjs.js');
9
- var log = require('./log-ec8d4df4.cjs.js');
6
+ var guards_dist_xstateGuards = require('./raise-ad4f12ad.cjs.js');
7
+ var StateMachine = require('./StateMachine-f73271f9.cjs.js');
8
+ var assign = require('./assign-ae103a72.cjs.js');
9
+ var log = require('./log-ec818628.cjs.js');
10
10
  require('../dev/dist/xstate-dev.cjs.js');
11
11
 
12
12
  /**
@@ -34,8 +34,9 @@ require('../dev/dist/xstate-dev.cjs.js');
34
34
  */
35
35
  function assertEvent(event, type) {
36
36
  const types = guards_dist_xstateGuards.toArray(type);
37
- if (!types.includes(event.type)) {
38
- const typesText = types.length === 1 ? `type "${types[0]}"` : `one of types "${types.join('", "')}"`;
37
+ const matches = types.some(descriptor => guards_dist_xstateGuards.matchesEventDescriptor(event.type, descriptor));
38
+ if (!matches) {
39
+ const typesText = types.length === 1 ? `type matching "${types[0]}"` : `one of types matching "${types.join('", "')}"`;
39
40
  throw new Error(`Expected event ${JSON.stringify(event)} to have ${typesText}`);
40
41
  }
41
42
  }
@@ -151,6 +152,9 @@ function getNextSnapshot(actorLogic, snapshot, event) {
151
152
  // at the moment we allow extra actors - ones that are not specified by `children`
152
153
  // this could be reconsidered in the future
153
154
 
155
+ // used to keep only StateSchema relevant keys
156
+ // this helps with type serialization as it makes the inferred type much shorter when dealing with huge configs
157
+
154
158
  function setup({
155
159
  schemas,
156
160
  actors,
@@ -3,10 +3,10 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var actors_dist_xstateActors = require('../actors/dist/xstate-actors.development.cjs.js');
6
- var guards_dist_xstateGuards = require('./raise-f777a9e8.development.cjs.js');
7
- var StateMachine = require('./StateMachine-4f3286fa.development.cjs.js');
8
- var assign = require('./assign-9e730107.development.cjs.js');
9
- var log = require('./log-cbac1abc.development.cjs.js');
6
+ var guards_dist_xstateGuards = require('./raise-723edf2d.development.cjs.js');
7
+ var StateMachine = require('./StateMachine-e3bf357b.development.cjs.js');
8
+ var assign = require('./assign-97062f30.development.cjs.js');
9
+ var log = require('./log-bf2198dc.development.cjs.js');
10
10
  require('../dev/dist/xstate-dev.development.cjs.js');
11
11
 
12
12
  /**
@@ -34,8 +34,9 @@ require('../dev/dist/xstate-dev.development.cjs.js');
34
34
  */
35
35
  function assertEvent(event, type) {
36
36
  const types = guards_dist_xstateGuards.toArray(type);
37
- if (!types.includes(event.type)) {
38
- const typesText = types.length === 1 ? `type "${types[0]}"` : `one of types "${types.join('", "')}"`;
37
+ const matches = types.some(descriptor => guards_dist_xstateGuards.matchesEventDescriptor(event.type, descriptor));
38
+ if (!matches) {
39
+ const typesText = types.length === 1 ? `type matching "${types[0]}"` : `one of types matching "${types.join('", "')}"`;
39
40
  throw new Error(`Expected event ${JSON.stringify(event)} to have ${typesText}`);
40
41
  }
41
42
  }
@@ -151,6 +152,9 @@ function getNextSnapshot(actorLogic, snapshot, event) {
151
152
  // at the moment we allow extra actors - ones that are not specified by `children`
152
153
  // this could be reconsidered in the future
153
154
 
155
+ // used to keep only StateSchema relevant keys
156
+ // this helps with type serialization as it makes the inferred type much shorter when dealing with huge configs
157
+
154
158
  function setup({
155
159
  schemas,
156
160
  actors,
@@ -1,12 +1,12 @@
1
1
  export { createEmptyActor, fromCallback, fromEventObservable, fromObservable, fromPromise, fromTransition } from '../actors/dist/xstate-actors.development.esm.js';
2
- import { t as toArray, c as createActor, r as raise, a as cancel, s as stopChild, b as spawnChild } from './raise-c096f887.development.esm.js';
3
- export { A as Actor, h as __unsafe_getAllOwnEventDescriptors, d as and, a as cancel, c as createActor, g as getStateNodes, i as interpret, f as isMachineSnapshot, m as matchesState, n as not, o as or, p as pathToStateValue, r as raise, b as spawnChild, e as stateIn, k as stop, s as stopChild, j as toObserver } from './raise-c096f887.development.esm.js';
4
- import { S as StateMachine } from './StateMachine-d6caf9f3.development.esm.js';
5
- export { S as StateMachine, a as StateNode } from './StateMachine-d6caf9f3.development.esm.js';
6
- import { a as assign } from './assign-445527dc.development.esm.js';
7
- export { a as assign } from './assign-445527dc.development.esm.js';
8
- import { s as sendTo, l as log, e as enqueueActions, a as emit } from './log-2aa3642a.development.esm.js';
9
- export { S as SpecialTargets, a as emit, e as enqueueActions, f as forwardTo, l as log, b as sendParent, s as sendTo } from './log-2aa3642a.development.esm.js';
2
+ import { m as matchesEventDescriptor, t as toArray, c as createActor, r as raise, a as cancel, s as stopChild, b as spawnChild } from './raise-235fa0c7.development.esm.js';
3
+ export { A as Actor, h as __unsafe_getAllOwnEventDescriptors, d as and, a as cancel, c as createActor, g as getStateNodes, i as interpret, f as isMachineSnapshot, j as matchesState, n as not, o as or, p as pathToStateValue, r as raise, b as spawnChild, e as stateIn, l as stop, s as stopChild, k as toObserver } from './raise-235fa0c7.development.esm.js';
4
+ import { S as StateMachine } from './StateMachine-53479528.development.esm.js';
5
+ export { S as StateMachine, a as StateNode } from './StateMachine-53479528.development.esm.js';
6
+ import { a as assign } from './assign-ef1b62f6.development.esm.js';
7
+ export { a as assign } from './assign-ef1b62f6.development.esm.js';
8
+ import { s as sendTo, l as log, e as enqueueActions, a as emit } from './log-3eec9346.development.esm.js';
9
+ export { S as SpecialTargets, a as emit, e as enqueueActions, f as forwardTo, l as log, b as sendParent, s as sendTo } from './log-3eec9346.development.esm.js';
10
10
  import '../dev/dist/xstate-dev.development.esm.js';
11
11
 
12
12
  /**
@@ -34,8 +34,9 @@ import '../dev/dist/xstate-dev.development.esm.js';
34
34
  */
35
35
  function assertEvent(event, type) {
36
36
  const types = toArray(type);
37
- if (!types.includes(event.type)) {
38
- const typesText = types.length === 1 ? `type "${types[0]}"` : `one of types "${types.join('", "')}"`;
37
+ const matches = types.some(descriptor => matchesEventDescriptor(event.type, descriptor));
38
+ if (!matches) {
39
+ const typesText = types.length === 1 ? `type matching "${types[0]}"` : `one of types matching "${types.join('", "')}"`;
39
40
  throw new Error(`Expected event ${JSON.stringify(event)} to have ${typesText}`);
40
41
  }
41
42
  }
@@ -151,6 +152,9 @@ function getNextSnapshot(actorLogic, snapshot, event) {
151
152
  // at the moment we allow extra actors - ones that are not specified by `children`
152
153
  // this could be reconsidered in the future
153
154
 
155
+ // used to keep only StateSchema relevant keys
156
+ // this helps with type serialization as it makes the inferred type much shorter when dealing with huge configs
157
+
154
158
  function setup({
155
159
  schemas,
156
160
  actors,
@@ -1,12 +1,12 @@
1
1
  export { createEmptyActor, fromCallback, fromEventObservable, fromObservable, fromPromise, fromTransition } from '../actors/dist/xstate-actors.esm.js';
2
- import { t as toArray, c as createActor, r as raise, a as cancel, s as stopChild, b as spawnChild } from './raise-9ad1c5c6.esm.js';
3
- export { A as Actor, h as __unsafe_getAllOwnEventDescriptors, d as and, a as cancel, c as createActor, g as getStateNodes, i as interpret, f as isMachineSnapshot, m as matchesState, n as not, o as or, p as pathToStateValue, r as raise, b as spawnChild, e as stateIn, k as stop, s as stopChild, j as toObserver } from './raise-9ad1c5c6.esm.js';
4
- import { S as StateMachine } from './StateMachine-37bc3882.esm.js';
5
- export { S as StateMachine, a as StateNode } from './StateMachine-37bc3882.esm.js';
6
- import { a as assign } from './assign-ab9cc19e.esm.js';
7
- export { a as assign } from './assign-ab9cc19e.esm.js';
8
- import { s as sendTo, l as log, e as enqueueActions, a as emit } from './log-7cbae384.esm.js';
9
- export { S as SpecialTargets, a as emit, e as enqueueActions, f as forwardTo, l as log, b as sendParent, s as sendTo } from './log-7cbae384.esm.js';
2
+ import { m as matchesEventDescriptor, t as toArray, c as createActor, r as raise, a as cancel, s as stopChild, b as spawnChild } from './raise-da2ff7ca.esm.js';
3
+ export { A as Actor, h as __unsafe_getAllOwnEventDescriptors, d as and, a as cancel, c as createActor, g as getStateNodes, i as interpret, f as isMachineSnapshot, j as matchesState, n as not, o as or, p as pathToStateValue, r as raise, b as spawnChild, e as stateIn, l as stop, s as stopChild, k as toObserver } from './raise-da2ff7ca.esm.js';
4
+ import { S as StateMachine } from './StateMachine-a6d25621.esm.js';
5
+ export { S as StateMachine, a as StateNode } from './StateMachine-a6d25621.esm.js';
6
+ import { a as assign } from './assign-fd69c737.esm.js';
7
+ export { a as assign } from './assign-fd69c737.esm.js';
8
+ import { s as sendTo, l as log, e as enqueueActions, a as emit } from './log-fbb00743.esm.js';
9
+ export { S as SpecialTargets, a as emit, e as enqueueActions, f as forwardTo, l as log, b as sendParent, s as sendTo } from './log-fbb00743.esm.js';
10
10
  import '../dev/dist/xstate-dev.esm.js';
11
11
 
12
12
  /**
@@ -34,8 +34,9 @@ import '../dev/dist/xstate-dev.esm.js';
34
34
  */
35
35
  function assertEvent(event, type) {
36
36
  const types = toArray(type);
37
- if (!types.includes(event.type)) {
38
- const typesText = types.length === 1 ? `type "${types[0]}"` : `one of types "${types.join('", "')}"`;
37
+ const matches = types.some(descriptor => matchesEventDescriptor(event.type, descriptor));
38
+ if (!matches) {
39
+ const typesText = types.length === 1 ? `type matching "${types[0]}"` : `one of types matching "${types.join('", "')}"`;
39
40
  throw new Error(`Expected event ${JSON.stringify(event)} to have ${typesText}`);
40
41
  }
41
42
  }
@@ -151,6 +152,9 @@ function getNextSnapshot(actorLogic, snapshot, event) {
151
152
  // at the moment we allow extra actors - ones that are not specified by `children`
152
153
  // this could be reconsidered in the future
153
154
 
155
+ // used to keep only StateSchema relevant keys
156
+ // this helps with type serialization as it makes the inferred type much shorter when dealing with huge configs
157
+
154
158
  function setup({
155
159
  schemas,
156
160
  actors,
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XState={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="xstate.init",n="xstate.stop";function o(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const i=t=>{const e=o();e&&e.register(t)};function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function a(t,e){return{type:`xstate.error.actor.${t}`,error:e,actorId:t}}function c(t){return{type:s,input:t}}function u(t){setTimeout(()=>{throw t})}const h="function"==typeof Symbol&&Symbol.observable||"@@observable";function d(t,e){const s=p(t),n=p(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&d(s[t],n[t]))}function f(t){if(_(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function p(t){if(Mt(t))return t.value;if("string"!=typeof t)return t;return l(f(t))}function l(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}function y(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const i=n[o];s[i]=e(t[i],i,t,o)}return s}function v(t){return _(t)?t:[t]}function g(t){return void 0===t?[]:v(t)}function m(t,e,s,n){return"function"==typeof t?t({context:e,event:s,self:n}):t}function _(t){return Array.isArray(t)}function b(t){return v(t).map(t=>void 0===t||"string"==typeof t?{target:t}:t)}function S(t){if(void 0!==t&&""!==t)return g(t)}function x(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function w(t,e){return`${e}.${t}`}function I(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actors[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke;return(Array.isArray(i)?i[n]:i).src}function k(t,e){return`${t.sessionId}.${e}`}let E=0;let $=!1;let T=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const O={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class A{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new e(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=T.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const n={...O,...s},{clock:o,logger:i,parent:r,syncSnapshot:a,id:c,systemId:h,inspect:d}=n;this.system=r?r.system:function(t,e){const s=new Map,n=new Map,o=new WeakMap,i=new Set,r={},{clock:a,logger:c}=e,u={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},c=k(t,o);h._snapshot._scheduledEvents[c]=i;const u=a.setTimeout(()=>{delete r[c],delete h._snapshot._scheduledEvents[c],h._relay(t,e,s)},n);r[c]=u},cancel:(t,e)=>{const s=k(t,e),n=r[s];delete r[s],delete h._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in h._snapshot._scheduledEvents){const s=h._snapshot._scheduledEvents[e];s.source===t&&u.cancel(t,s.id)}}},h={_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+E++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=o.get(t);void 0!==e&&(n.delete(e),o.delete(t))},get:t=>n.get(t),getAll:()=>Object.fromEntries(n.entries()),_set:(t,e)=>{const s=n.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);n.set(t,e),o.set(e,t)},inspect:t=>{const e=x(t);return i.add(e),{unsubscribe(){i.delete(e)}}},_sendInspectionEvent:e=>{if(!i.size)return;const s={...e,rootId:t.sessionId};i.forEach(t=>t.next?.(s))},_relay:(t,e,s)=>{h._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:e,event:s}),e._send(s)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...h._snapshot._scheduledEvents}}),start:()=>{const t=h._snapshot._scheduledEvents;h._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];u.schedule(s,n,o,i,r)}},_clock:a,_logger:c};return h}(this,{clock:o,logger:i}),d&&!r&&this.system.inspect(x(d)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=r,this._syncSnapshot=a,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get("*");if(!e&&!s)return;const n=[...e?e.values():[],...s?s.values():[]];for(const e of n)try{e(t)}catch(t){u(t)}},actionExecutor:t=>{const e=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:t.type,params:t.params}}),!t.exec)return;const e=$;try{$=!0,t.exec(t.info,t.params)}finally{$=e}};this._processingStatus===T.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),h&&(this.systemId=h,this.system._set(h,this)),this._initState(s?.snapshot??s?.state),h&&"active"!==this._snapshot.status&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(t,e){let s;for(this._snapshot=t;s=this._deferred.shift();)try{s()}catch(e){this._deferred.length=0,this._snapshot={...t,status:"error",error:e}}switch(this._snapshot.status){case"active":for(const e of this.observers)try{e.next?.(t)}catch(t){u(t)}break;case"done":for(const e of this.observers)try{e.next?.(t)}catch(t){u(t)}this._stopProcedure(),this._complete(),this._doneEvent=(n=this.id,o=this._snapshot.output,{type:`xstate.done.actor.${n}`,output:o,actorId:n}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error)}var n,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){const n=x(t,e,s);if(this._processingStatus!==T.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){u(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){u(t)}else u(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const n=e.bind(void 0);return s.add(n),{unsubscribe:()=>{s.delete(n)}}}start(){if(this._processingStatus===T.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=T.Running;const t=c(this.options.input);this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t});switch(this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._snapshot={...this._snapshot,status:"error",error:t},this._error(t),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._snapshot={...this._snapshot,status:"error",error:t},void this._error(t)}this.update(e,t),t.type===n&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===T.Stopped?this:(this.mailbox.clear(),this._processingStatus===T.NotStarted?(this._processingStatus=T.Stopped,this):(this.mailbox.enqueue({type:n}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){u(t)}this.observers.clear()}_reportError(t){if(!this.observers.size)return void(this._parent||u(t));let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){u(t)}}this.observers.clear(),e&&u(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,a(this.id,t))}_stopProcedure(){return this._processingStatus!==T.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this._processingStatus=T.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==T.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:i)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[h](){return this}getSnapshot(){return this._snapshot}}function j(t,...[e]){return new A(t,e)}const M=j;function N(t,e,s,n,{sendId:o}){return[e,{sendId:"function"==typeof o?o(s,n):o},void 0]}function P(t,e){t.defer(()=>{t.system.scheduler.cancel(t.self,e.sendId)})}function R(t){function e(t,e){}return e.type="xstate.cancel",e.sendId=t,e.resolve=N,e.execute=P,e}function C(t,e,s,n,{id:o,systemId:i,src:r,input:a,syncSnapshot:c}){const u="string"==typeof r?I(e.machine,r):r,h="function"==typeof o?o(s):o;let d,f;return u&&(f="function"==typeof a?a({context:e.context,event:s.event,self:t.self}):a,d=j(u,{id:h,src:r,parent:t.self,syncSnapshot:c,systemId:i,input:f})),[Jt(e,{children:{...e.children,[h]:d}}),{id:o,systemId:i,actorRef:d,src:r,input:f},void 0]}function V(t,{actorRef:e}){e&&t.defer(()=>{e._processingStatus!==T.Stopped&&e.start()})}function D(...[t,{id:e,systemId:s,input:n,syncSnapshot:o=!1}={}]){function i(t,e){}return i.type="xstate.spawnChild",i.id=e,i.systemId=s,i.src=t,i.input=n,i.syncSnapshot=o,i.resolve=C,i.execute=V,i}function J(t,e,s,n,{actorRef:o}){const i="function"==typeof o?o(s,n):o,r="string"==typeof i?e.children[i]:i;let a=e.children;return r&&(a={...a},delete a[r.id]),[Jt(e,{children:a}),r,void 0]}function B(t,e){e&&(t.system._unregister(e),e._processingStatus===T.Running?t.defer(()=>{t.stopChild(e)}):t.stopChild(e))}function q(t){function e(t,e){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=J,e.execute=B,e}const z=q;function L(t,e,{stateValue:s}){if("string"==typeof s&&st(s)){const e=t.machine.getStateNodeById(s);return t._nodes.some(t=>t===e)}return t.matches(s)}function W(t,{context:e,event:s},{guards:n}){return!F(n[0],e,s,t)}function U(t,{context:e,event:s},{guards:n}){return n.every(n=>F(n,e,s,t))}function Q(t,{context:e,event:s},{guards:n}){return n.some(n=>F(n,e,s,t))}function F(t,e,s,n){const{machine:o}=n,i="function"==typeof t,r=i?t:o.implementations.guards["string"==typeof t?t:t.type];if(!i&&!r)throw new Error(`Guard '${"string"==typeof t?t:t.type}' is not implemented.'.`);if("function"!=typeof r)return F(r,e,s,n);const a={context:e,event:s},c=i||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:e,event:s}):t.params:void 0;if(!("check"in r))return r(a,c);return r.check(n,a,r)}const G=t=>"atomic"===t.type||"final"===t.type;function X(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function H(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function K(t){const e=new Set(t),s=Z(e);for(const t of e)if("compound"!==t.type||s.get(t)&&s.get(t).length){if("parallel"===t.type)for(const s of X(t))if("history"!==s.type&&!e.has(s)){const t=at(s);for(const s of t)e.add(s)}}else at(t).forEach(t=>e.add(t));for(const t of e){let s=t.parent;for(;s;)e.add(s),s=s.parent}return e}function Y(t,e){const s=e.get(t);if(!s)return{};if("compound"===t.type){const t=s[0];if(!t)return{};if(G(t))return t.key}const n={};for(const t of s)n[t.key]=Y(t,e);return n}function Z(t){const e=new Map;for(const s of t)e.has(s)||e.set(s,[]),s.parent&&(e.has(s.parent)||e.set(s.parent,[]),e.get(s.parent).push(s));return e}function tt(t,e){return Y(t,Z(K(e)))}function et(t,e){return"compound"===e.type?X(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?X(e).every(e=>et(t,e)):"final"===e.type}const st=t=>"#"===t[0];function nt(t){const e=t.config.after;if(!e)return[];const s=Object.keys(e).flatMap(s=>{const n=e[s],o="string"==typeof n?{target:n}:n,i=Number.isNaN(+s)?s:+s,r=(e=>{const s=(n=e,o=t.id,{type:`xstate.after.${n}.${o}`});var n,o;const i=s.type;return t.entry.push(Ht(s,{id:i,delay:e})),t.exit.push(R(i)),i})(i);return g(o).map(t=>({...t,event:r,delay:i}))});return s.map(e=>{const{delay:s}=e;return{...ot(t,e.event,e),delay:s}})}function ot(t,e,s){const n=S(s.target),o=s.reenter??!1,i=function(t,e){if(void 0===e)return;return e.map(e=>{if("string"!=typeof e)return e;if(st(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return ht(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`);try{return ht(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}(t,n),r={...s,actions:g(s.actions),guard:s.guard,target:i,source:t,reenter:o,eventType:e,toJSON:()=>({...r,source:`#${t.id}`,target:i?i.map(t=>`#${t.id}`):void 0})};return r}function it(t){const e=S(t.config.target);return e?{target:e.map(e=>"string"==typeof e?ht(t.parent,e):e)}:t.parent.initial}function rt(t){return"history"===t.type}function at(t){const e=ct(t);for(const s of e)for(const n of H(s,t))e.add(n);return e}function ct(t){const e=new Set;return function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of X(s))t(e)}(t),e}function ut(t,e){if(st(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const s=t.states[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function ht(t,e){if("string"==typeof e&&st(e))try{return t.machine.getStateNodeById(e)}catch{}const s=f(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=ut(n,t)}return n}function dt(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=s.map(e=>ut(t,e)).filter(Boolean);return[t.machine.root,t].concat(n,s.reduce((s,n)=>{const o=ut(t,n);if(!o)return s;const i=dt(o,e[n]);return s.concat(i)},[]))}function ft(t,e,s,n){return"string"==typeof e?function(t,e,s,n){const o=ut(t,e).next(s,n);return o&&o.length?o:t.next(s,n)}(t,e,s,n):1===Object.keys(e).length?function(t,e,s,n){const o=Object.keys(e),i=ft(ut(t,o[0]),e[o[0]],s,n);return i&&i.length?i:t.next(s,n)}(t,e,s,n):function(t,e,s,n){const o=[];for(const i of Object.keys(e)){const r=e[i];if(!r)continue;const a=ft(ut(t,i),r,s,n);a&&o.push(...a)}return o.length?o:t.next(s,n)}(t,e,s,n)}function pt(t){return Object.keys(t.states).map(e=>t.states[e]).filter(t=>"history"===t.type)}function lt(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function yt(t,e){const s=new Set(t),n=new Set(e);for(const t of s)if(n.has(t))return!0;for(const t of n)if(s.has(t))return!0;return!1}function vt(t,e,s){const n=new Set;for(const o of t){let t=!1;const i=new Set;for(const r of n)if(yt(_t([o],e,s),_t([r],e,s))){if(!lt(o.source,r.source)){t=!0;break}i.add(r)}if(!t){for(const t of i)n.delete(t);n.add(o)}}return Array.from(n)}function gt(t,e){if(!t.target)return[];const s=new Set;for(const n of t.target)if(rt(n))if(e[n.id])for(const t of e[n.id])s.add(t);else for(const t of gt(it(n),e))s.add(t);else s.add(n);return[...s]}function mt(t,e){const s=gt(t,e);if(!s)return;if(!t.reenter&&s.every(e=>e===t.source||lt(e,t.source)))return t.source;const n=function(t){const[e,...s]=t;for(const t of H(e,void 0))if(s.every(e=>lt(e,t)))return t}(s.concat(t.source));return n||(t.reenter?void 0:t.source.machine.root)}function _t(t,e,s){const n=new Set;for(const o of t)if(o.target?.length){const t=mt(o,s);o.reenter&&o.source===t&&n.add(t);for(const s of e)lt(s,t)&&n.add(s)}return[...n]}function bt(t,e,s,n,o,i){if(!t.length)return e;const a=new Set(e._nodes);let c=e.historyValue;const u=vt(t,a,c);let h=e;o||([h,c]=function(t,e,s,n,o,i,r){let a=t;const c=_t(n,o,i);let u;c.sort((t,e)=>e.order-t.order);for(const t of c)for(const e of pt(t)){let s;s="deep"===e.history?e=>G(e)&&lt(e,t):e=>e.parent===t,u??={...i},u[e.id]=Array.from(o).filter(s)}for(const t of c)a=$t(a,e,s,[...t.exit,...t.invoke.map(t=>q(t.id))],r,void 0),o.delete(t);return[a,u||i]}(h,n,s,u,a,c,i,s.actionExecutor)),h=$t(h,n,s,u.flatMap(t=>t.actions),i,void 0),h=function(t,e,s,n,o,i,a,c){let u=t;const h=new Set,d=new Set;(function(t,e,s,n){for(const o of t){const t=mt(o,e);for(const i of o.target||[])rt(i)||o.source===i&&o.source===t&&!o.reenter||(n.add(i),s.add(i)),xt(i,e,s,n);const i=gt(o,e);for(const r of i){const i=H(r,t);"parallel"===t?.type&&i.push(t),wt(n,e,s,i,!o.source.parent&&o.reenter?void 0:t)}}})(n,a,d,h),c&&d.add(t.machine.root);const f=new Set;for(const t of[...h].sort((t,e)=>t.order-e.order)){o.add(t);const n=[];n.push(...t.entry);for(const e of t.invoke)n.push(D(e.src,{...e,syncSnapshot:!!e.onSnapshot}));if(d.has(t)){const e=t.initial.actions;n.push(...e)}if(u=$t(u,e,s,n,i,t.invoke.map(t=>t.id)),"final"===t.type){const n=t.parent;let a="parallel"===n?.type?n:n?.parent,c=a||t;for("compound"===n?.type&&i.push(r(n.id,void 0!==t.output?m(t.output,u.context,e,s.self):void 0));"parallel"===a?.type&&!f.has(a)&&et(o,a);)f.add(a),i.push(r(a.id)),c=a,a=a.parent;if(a)continue;u=Jt(u,{status:"done",output:St(u,e,s,u.machine.root,c)})}}return u}(h,n,s,u,a,i,c,o);const d=[...a];"done"===h.status&&(h=$t(h,n,s,d.sort((t,e)=>e.order-t.order).flatMap(t=>t.exit),i,void 0));try{return c===e.historyValue&&function(t,e){if(t.length!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;return!0}(e._nodes,a)?h:Jt(h,{_nodes:d,historyValue:c})}catch(t){throw t}}function St(t,e,s,n,o){if(void 0===n.output)return;const i=r(o.id,void 0!==o.output&&o.parent?m(o.output,t.context,e,s.self):void 0);return m(n.output,t.context,i,s.self)}function xt(t,e,s,n){if(rt(t))if(e[t.id]){const o=e[t.id];for(const t of o)n.add(t),xt(t,e,s,n);for(const i of o)It(i,t.parent,n,e,s)}else{const o=it(t);for(const i of o.target)n.add(i),o===t.parent?.initial&&s.add(t.parent),xt(i,e,s,n);for(const i of o.target)It(i,t.parent,n,e,s)}else if("compound"===t.type){const[o]=t.initial.target;rt(o)||(n.add(o),s.add(o)),xt(o,e,s,n),It(o,t,n,e,s)}else if("parallel"===t.type)for(const o of X(t).filter(t=>!rt(t)))[...n].some(t=>lt(t,o))||(rt(o)||(n.add(o),s.add(o)),xt(o,e,s,n))}function wt(t,e,s,n,o){for(const i of n)if(o&&!lt(i,o)||t.add(i),"parallel"===i.type)for(const n of X(i).filter(t=>!rt(t)))[...t].some(t=>lt(t,n))||(t.add(n),xt(n,e,s,t))}function It(t,e,s,n,o){wt(s,n,o,H(t,e))}function kt(t,e){return t.implementations.actions[e]}function Et(t,e,s,n,o,i){const{machine:r}=t;let a=t;for(const t of n){const n="function"==typeof t,c=n?t:kt(r,"string"==typeof t?t:t.type),u={context:a.context,event:e,self:s.self,system:s.system},h=n||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:a.context,event:e}):t.params:void 0;if(!c||!("resolve"in c)){s.actionExecutor({type:"string"==typeof t?t:"object"==typeof t?t.type:t.name||"(anonymous)",info:u,params:h,exec:c});continue}const d=c,[f,p,l]=d.resolve(s,a,u,h,c,o);a=f,"retryResolve"in d&&i?.push([d,p]),"execute"in d&&s.actionExecutor({type:d.type,info:u,params:p,exec:d.execute.bind(null,s,p)}),l&&(a=Et(a,e,s,l,o,i))}return a}function $t(t,e,s,n,o,i){const r=i?[]:void 0,a=Et(t,e,s,n,{internalQueue:o,deferredActorIds:i},r);return r?.forEach(([t,e])=>{t.retryResolve(s,a,e)}),a}function Tt(t,e,o,i){let r=t;const a=[];function c(t,e,s){o.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:o.self,event:e,snapshot:t,_transitions:s}),a.push(t)}if(e.type===n)return r=Jt(Ot(r,e,o),{status:"stopped"}),c(r,e,[]),{snapshot:r,microstates:a};let u=e;if(u.type!==s){const e=u,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),n=At(e,r);if(s&&!n.length)return r=Jt(t,{status:"error",error:e.error}),c(r,e,[]),{snapshot:r,microstates:a};r=bt(n,t,o,u,!1,i),c(r,e,n)}let h=!0;for(;"active"===r.status;){let t=h?jt(r,u):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;u=i.shift(),t=At(u,r)}r=bt(t,r,o,u,!1,i),h=r!==e,c(r,u,t)}return"active"!==r.status&&Ot(r,u,o),{snapshot:r,microstates:a}}function Ot(t,e,s){return $t(t,e,s,Object.values(t.children).map(t=>q(t)),[],void 0)}function At(t,e){return e.machine.getTransitionData(e,t)}function jt(t,e){const s=new Set,n=t._nodes.filter(G);for(const o of n)t:for(const n of[o].concat(H(o,void 0)))if(n.always)for(const o of n.always)if(void 0===o.guard||F(o.guard,t.context,e,t)){s.add(o);break t}return vt(Array.from(s),new Set(t._nodes),t.historyValue)}function Mt(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const Nt=function(t){return d(t,this.value)},Pt=function(t){return this.tags.has(t)},Rt=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some(t=>void 0!==t.target||t.actions.length)},Ct=function(){const{_nodes:t,tags:e,machine:s,getMeta:n,toJSON:o,can:i,hasTag:r,matches:a,...c}=this;return{...c,tags:Array.from(e)}},Vt=function(){return this._nodes.reduce((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t),{})};function Dt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:tt(e.root,t._nodes),tags:new Set(t._nodes.flatMap(t=>t.tags)),children:t.children,historyValue:t.historyValue||{},matches:Nt,hasTag:Pt,can:Rt,getMeta:Vt,toJSON:Ct}}function Jt(t,e={}){return Dt({...t,...e},t.machine)}function Bt(t){if("object"!=typeof t||null===t)return{};const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map(t=>({id:t.id})))}return e}function qt(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:1,id:n.id};else{const o=qt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function zt(t,{machine:e,context:s},n,o){return(i,r)=>{const a=((i,r)=>{if("string"==typeof i){const a=I(e,i);if(!a)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const c=j(a,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:s,event:n,self:t.self}):r?.input,src:i,systemId:r?.systemId});return o[c.id]=c,c}return j(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[a.id]=a,t.defer(()=>{a._processingStatus!==T.Stopped&&a.start()}),a}}function Lt(t,e,s,n,{assignment:o}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},r={context:e.context,event:s.event,spawn:zt(t,e,s.event,i),self:t.self,system:t.system};let a={};if("function"==typeof o)a=o(r,n);else for(const t of Object.keys(o)){const e=o[t];a[t]="function"==typeof e?e(r,n):e}return[Jt(e,{context:Object.assign({},e.context,a),children:Object.keys(i).length?{...e.children,...i}:e.children}),void 0,void 0]}function Wt(t){function e(t,e){}return e.type="xstate.assign",e.assignment=t,e.resolve=Lt,e}function Ut(t,e,s,n,{event:o}){return[e,{event:"function"==typeof o?o(s,n):o},void 0]}function Qt(t,{event:e}){t.defer(()=>t.emit(e))}function Ft(t){function e(t,e){}return e.type="xstate.emit",e.event=t,e.resolve=Ut,e.execute=Qt,e}function Gt(t,e,s,n,{event:o,id:i,delay:r},{internalQueue:a}){const c=e.machine.implementations.delays;if("string"==typeof o)throw new Error(`Only event objects may be used with raise; use raise({ type: "${o}" }) instead`);const u="function"==typeof o?o(s,n):o;let h;if("string"==typeof r){const t=c&&c[r];h="function"==typeof t?t(s,n):t}else h="function"==typeof r?r(s,n):r;return"number"!=typeof h&&a.push(u),[e,{event:u,id:i,delay:h},void 0]}function Xt(t,e){const{event:s,delay:n,id:o}=e;"number"!=typeof n||t.defer(()=>{const e=t.self;t.system.scheduler.schedule(e,e,s,n,o)})}function Ht(t,e){function s(t,e){}return s.type="xstate.raise",s.event=t,s.id=e?.id,s.delay=e?.delay,s.resolve=Gt,s.execute=Xt,s}let Kt=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function Yt(t,e,s,n,{to:o,event:i,id:r,delay:a},c){const u=e.machine.implementations.delays;if("string"==typeof i)throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${i}" }) instead`);const h="function"==typeof i?i(s,n):i;let d;if("string"==typeof a){const t=u&&u[a];d="function"==typeof t?t(s,n):t}else d="function"==typeof a?a(s,n):a;const f="function"==typeof o?o(s,n):o;let p;if("string"==typeof f){if(p=f===Kt.Parent?t.self._parent:f===Kt.Internal?t.self:f.startsWith("#_")?e.children[f.slice(2)]:c.deferredActorIds?.includes(f)?f:e.children[f],!p)throw new Error(`Unable to send event to actor '${f}' from machine '${e.machine.id}'.`)}else p=f||t.self;return[e,{to:p,targetId:"string"==typeof f?f:void 0,event:h,id:r,delay:d},void 0]}function Zt(t,e,s){"string"==typeof s.to&&(s.to=e.children[s.to])}function te(t,e){t.defer(()=>{const{to:s,event:n,delay:o,id:i}=e;"number"!=typeof o?t.system._relay(t.self,s,"xstate.error"===n.type?a(t.self.id,n.data):n):t.system.scheduler.schedule(t.self,s,n,o,i)})}function ee(t,e,s){function n(t,e){}return n.type="xstate.sendTo",n.to=t,n.event=e,n.id=s?.id,n.delay=s?.delay,n.resolve=Yt,n.retryResolve=Zt,n.execute=te,n}function se(t,e){return ee(Kt.Parent,t,e)}function ne(t,e,s,n,{collect:o}){const i=[],r=function(t){i.push(t)};return r.assign=(...t)=>{i.push(Wt(...t))},r.cancel=(...t)=>{i.push(R(...t))},r.raise=(...t)=>{i.push(Ht(...t))},r.sendTo=(...t)=>{i.push(ee(...t))},r.sendParent=(...t)=>{i.push(se(...t))},r.spawnChild=(...t)=>{i.push(D(...t))},r.stopChild=(...t)=>{i.push(q(...t))},r.emit=(...t)=>{i.push(Ft(...t))},o({context:s.context,event:s.event,enqueue:r,check:t=>F(t,e.context,s.event,e),self:t.self,system:t.system},n),[e,void 0,i]}function oe(t){function e(t,e){}return e.type="xstate.enqueueActions",e.collect=t,e.resolve=ne,e}function ie(t,e,s,n,{value:o,label:i}){return[e,{value:"function"==typeof o?o(s,n):o,label:i},void 0]}function re({logger:t},{value:e,label:s}){s?t(s,e):t(e)}function ae(t=({context:t,event:e})=>({context:t,event:e}),e){function s(t,e){}return s.type="xstate.log",s.value=t,s.label=e,s.resolve=ie,s.execute=re,s}function ce(t,e){return{config:t,transition:(e,s,n)=>({...e,context:t(e.context,s,n)}),getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof e?e({input:s}):e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}const ue=new WeakMap;const he="xstate.observable.next",de="xstate.observable.error",fe="xstate.observable.complete";const pe="xstate.promise.resolve",le="xstate.promise.reject",ye=new WeakMap;const ve=ce(t=>{},void 0);const ge=new WeakMap;function me(t,e,s){let n=ge.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},ge.set(t,n)),n[e]}const _e={},be=t=>"string"==typeof t?{type:t}:"function"==typeof t?"resolve"in t?{type:t.type}:{type:t.name}:t;class Se{constructor(t,e){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?y(this.config.states,(t,e)=>new Se(t,{_parent:this,_key:e,_machine:this.machine})):_e,"compound"===this.type&&!this.config.initial)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.`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=g(this.config.entry).slice(),this.exit=g(this.config.exit).slice(),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=g(t.tags).slice()}_initialize(){this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=t.config.on[s];e.set(s,b(n).map(e=>ot(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,b(t.config.onDone).map(e=>ot(t,s,e)))}for(const s of t.invoke){if(s.onDone){const n=`xstate.done.actor.${s.id}`;e.set(n,b(s.onDone).map(e=>ot(t,n,e)))}if(s.onError){const n=`xstate.error.actor.${s.id}`;e.set(n,b(s.onError).map(e=>ot(t,n,e)))}if(s.onSnapshot){const n=`xstate.snapshot.${s.id}`;e.set(n,b(s.onSnapshot).map(e=>ot(t,n,e)))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),this.config.always&&(this.always=b(this.config.always).map(t=>ot(this,"",t))),Object.keys(this.states).forEach(t=>{this.states[t]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(be),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(be),eventType:null})}:void 0,history:this.history,states:y(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(be)})),entry:this.entry.map(be),exit:this.exit.map(be),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return me(this,"invoke",()=>g(this.config.invoke).map((t,e)=>{const{src:s,systemId:n}=t,o=t.id??w(this.id,e),i="string"==typeof s?s:`xstate.invoke.${w(this.id,e)}`;return{...t,src:i,id:o,systemId:n,toJSON(){const{onDone:e,onError:s,...n}=t;return{...n,type:"xstate.invoke",src:i,id:o}}}}))}get on(){return me(this,"on",()=>[...this.transitions].flatMap(([t,e])=>e.map(e=>[t,e])).reduce((t,[e,s])=>(t[e]=t[e]||[],t[e].push(s),t),{}))}get after(){return me(this,"delayedTransitions",()=>nt(this))}get initial(){return me(this,"initial",()=>function(t,e){const s="string"==typeof e?t.states[e]:e?t.states[e.target]:void 0;if(!s&&e)throw new Error(`Initial state node "${e}" not found on parent state node #${t.id}`);const n={source:t,actions:e&&"string"!=typeof e?g(e.actions):[],eventType:null,reenter:!1,target:s?[s]:[],toJSON:()=>({...n,source:`#${t.id}`,target:s?[`#${s.id}`]:[]})};return n}(this,this.config.initial))}next(t,e){const s=e.type,n=[];let o;const i=me(this,`candidates-${s}`,()=>{return e=s,(t=this).transitions.get(e)||[...t.transitions.keys()].filter(t=>{if("*"===t)return!0;if(!t.endsWith(".*"))return!1;const s=t.split("."),n=e.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e)return t===s.length-1;if(e!==o)return!1}return!0}).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));var t,e});for(const r of i){const{guard:i}=r,a=t.context;let c=!1;try{c=!i||F(i,a,e,t)}catch(t){const e="string"==typeof i?i:"object"==typeof i?i.type:void 0;throw new Error(`Unable to evaluate guard ${e?`'${e}' `:""}in transition for event '${s}' in state node '${this.id}':\n${t.message}`)}if(c){n.push(...r.actions),o=r;break}}return o?[o]:void 0}get events(){return me(this,"events",()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const n=t[s];if(n.states)for(const t of n.events)e.add(`${t}`)}return Array.from(e)})}get ownEvents(){const t=new Set([...this.transitions.keys()].filter(t=>this.transitions.get(t).some(t=>!(!t.target&&!t.actions.length&&!t.reenter))));return Array.from(t)}}class xe{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:e?.actors??{},actions:e?.actions??{},delays:e?.delays??{},guards:e?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new Se(t,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.implementations;return new xe(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}})}resolveState(t){const e=(s=this.root,n=t.value,tt(s,[...K(dt(s,n))]));var s,n;const o=K(dt(this.root,e));return Dt({_nodes:[...o],context:t.context||{},children:{},status:et(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return Tt(t,e,s,[]).snapshot}microstep(t,e,s){return Tt(t,e,s,[]).microstates}getTransitionData(t,e){return ft(this.root,t.value,t,e)||[]}getPreInitialState(t,e,s){const{context:n}=this.config,o=Dt({context:"function"!=typeof n&&n?n:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof n){return $t(o,e,t,[Wt(({spawn:t,event:e,self:s})=>n({spawn:t,input:e.input,self:s}))],s,void 0)}return o}getInitialSnapshot(t,e){const s=c(e),n=[],o=this.getPreInitialState(t,s,n),i=bt([{target:[...ct(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],o,t,s,!0,n),{snapshot:r}=Tt(i,s,t,n);return r}start(t){Object.values(t.children).forEach(t=>{"active"===t.getSnapshot().status&&t.start()})}getStateNodeById(t){const e=f(t),s=e.slice(1),n=st(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return ht(o,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,tags:n,machine:o,children:i,context:r,can:a,hasTag:c,matches:u,getMeta:h,toJSON:d,...f}=t,p={};for(const t in i){const s=i[t];p[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s.systemId,syncSnapshot:s._syncSnapshot}}return{...f,context:qt(r),children:p,historyValue:Bt(f.historyValue)}}(t,e)}restoreSnapshot(t,e){const s={},n=t.children;function o(t,e){if(e instanceof Se)return e;try{return t.machine.getStateNodeById(e.id)}catch{}}Object.keys(n).forEach(t=>{const o=n[t],i=o.snapshot,r=o.src,a="string"==typeof r?I(this,r):r;if(!a)return;const c=j(a,{id:t,parent:e.self,syncSnapshot:o.syncSnapshot,snapshot:i,src:r,systemId:o.systemId});s[t]=c});const i=function(t,e){if(!e||"object"!=typeof e)return{};const s={};for(const n in e){const i=e[n];for(const e of i){const i=o(t,e);i&&(s[n]??=[],s[n].push(i))}}return s}(this.root,t.historyValue),r=Dt({...t,children:s,_nodes:Array.from(K(dt(this.root,t.value))),historyValue:i},this),a=new Set;return function t(e,s){if(!a.has(e)){a.add(e);for(const n in e){const o=e[n];if(o&&"object"==typeof o){if("xstate$$type"in o&&1===o.xstate$$type){e[n]=s[o.id];continue}t(o,s)}}}}(r.context,s),r}}function we(t,e){return new xe(t,e)}function Ie(t){const e=j(t);return{self:e,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:e.system,emit:()=>{},actionExecutor:()=>{}}}const ke={timeout:1/0};t.Actor=A,t.SimulatedClock=class{constructor(){this.timeouts=new Map,this._now=0,this._id=0,this._flushing=!1,this._flushingInvalidated=!1}now(){return this._now}getId(){return this._id++}setTimeout(t,e){this._flushingInvalidated=this._flushing;const s=this.getId();return this.timeouts.set(s,{start:this.now(),timeout:e,fn:t}),s}clearTimeout(t){this._flushingInvalidated=this._flushing,this.timeouts.delete(t)}set(t){if(this._now>t)throw new Error("Unable to travel back in time");this._now=t,this.flushTimeouts()}flushTimeouts(){if(this._flushing)return void(this._flushingInvalidated=!0);this._flushing=!0;const t=[...this.timeouts].sort(([t,e],[s,n])=>{const o=e.start+e.timeout;return n.start+n.timeout>o?-1:1});for(const[e,s]of t){if(this._flushingInvalidated)return this._flushingInvalidated=!1,this._flushing=!1,void this.flushTimeouts();this.now()-s.start>=s.timeout&&(this.timeouts.delete(e),s.fn.call(null))}this._flushing=!1}increment(t){this._now+=t,this.flushTimeouts()}},t.SpecialTargets=Kt,t.StateMachine=xe,t.StateNode=Se,t.__unsafe_getAllOwnEventDescriptors=function(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]},t.and=function(t){function e(t,e){return!1}return e.check=U,e.guards=t,e},t.assertEvent=function(t,e){const s=g(e);if(!s.includes(t.type)){const e=1===s.length?`type "${s[0]}"`:`one of types "${s.join('", "')}"`;throw new Error(`Expected event ${JSON.stringify(t)} to have ${e}`)}},t.assign=Wt,t.cancel=R,t.createActor=j,t.createEmptyActor=function(){return j(ve)},t.createMachine=we,t.emit=Ft,t.enqueueActions=oe,t.forwardTo=function(t,e){return ee(t,({event:t})=>t,e)},t.fromCallback=function(t){const e={config:t,start:(e,s)=>{const{self:n,system:o,emit:i}=s,r={receivers:void 0,dispose:void 0};ue.set(n,r),r.dispose=t({input:e.input,system:o,self:n,sendBack:t=>{"stopped"!==n.getSnapshot().status&&n._parent&&o._relay(n,n._parent,t)},receive:t=>{r.receivers??=new Set,r.receivers.add(t)},emit:i})},transition:(t,e,s)=>{const o=ue.get(s.self);return e.type===n?(t={...t,status:"stopped",error:void 0},o.dispose?.(),t):(o.receivers?.forEach(t=>t(e)),t)},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e},t.fromEventObservable=function(t){const e={config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case de:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case fe:return{...t,status:"done",input:void 0,_subscription:void 0};case n:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{"done"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{s._parent&&n._relay(s,s._parent,t)},error:t=>{n._relay(s,s,{type:de,data:t})},complete:()=>{n._relay(s,s,{type:fe})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e},t.fromObservable=function(t){const e={config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case he:return{...t,context:e.data};case de:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case fe:return{...t,status:"done",input:void 0,_subscription:void 0};case n:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{"done"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{n._relay(s,s,{type:he,data:t})},error:t=>{n._relay(s,s,{type:de,data:t})},complete:()=>{n._relay(s,s,{type:fe})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e},t.fromPromise=function(t){const e={config:t,transition:(t,e,s)=>{if("active"!==t.status)return t;switch(e.type){case pe:{const s=e.data;return{...t,status:"done",output:s,input:void 0}}case le:return{...t,status:"error",error:e.data,input:void 0};case n:return ye.get(s.self)?.abort(),{...t,status:"stopped",input:void 0};default:return t}},start:(e,{self:s,system:n,emit:o})=>{if("active"!==e.status)return;const i=new AbortController;ye.set(s,i);Promise.resolve(t({input:e.input,system:n,self:s,signal:i.signal,emit:o})).then(t=>{"active"===s.getSnapshot().status&&(ye.delete(s),n._relay(s,s,{type:pe,data:t}))},t=>{"active"===s.getSnapshot().status&&(ye.delete(s),n._relay(s,s,{type:le,data:t}))})},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e},t.fromTransition=ce,t.getInitialSnapshot=function(t,...[e]){const s=Ie(t);return t.getInitialSnapshot(s,e)},t.getNextSnapshot=function(t,e,s){const n=Ie(t);return n.self._snapshot=e,t.transition(e,s,n)},t.getStateNodes=dt,t.initialTransition=function(t,...[e]){const s=[],n=Ie(t);return n.actionExecutor=t=>{s.push(t)},[t.getInitialSnapshot(n,e),s]},t.interpret=M,t.isMachineSnapshot=Mt,t.log=ae,t.matchesState=d,t.not=function(t){function e(t,e){return!1}return e.check=W,e.guards=[t],e},t.or=function(t){function e(t,e){return!1}return e.check=Q,e.guards=t,e},t.pathToStateValue=l,t.raise=Ht,t.sendParent=se,t.sendTo=ee,t.setup=function t({schemas:e,actors:s,actions:n,guards:o,delays:i}){return{assign:Wt,sendTo:ee,raise:Ht,log:ae,cancel:R,stopChild:q,enqueueActions:oe,emit:Ft,spawnChild:D,createStateConfig:t=>t,createAction:t=>t,createMachine:t=>we({...t,schemas:e},{actors:s,actions:n,guards:o,delays:i}),extend:r=>t({schemas:e,actors:s,actions:{...n,...r.actions},guards:{...o,...r.guards},delays:{...i,...r.delays}})}},t.spawnChild=D,t.stateIn=function(t){function e(){return!1}return e.check=L,e.stateValue=t,e},t.stop=z,t.stopChild=q,t.toObserver=x,t.toPromise=function(t){return new Promise((e,s)=>{t.subscribe({complete:()=>{e(t.getSnapshot().output)},error:s})})},t.transition=function(t,e,s){const n=[],o=Ie(t);return o.actionExecutor=t=>{n.push(t)},[t.transition(e,s,o),n]},t.waitFor=function(t,e,s){const n={...ke,...s};return new Promise((s,o)=>{const{signal:i}=n;if(i?.aborted)return void o(i.reason);let r=!1;const a=n.timeout===1/0?void 0:setTimeout(()=>{c(),o(new Error(`Timeout of ${n.timeout} ms exceeded`))},n.timeout),c=()=>{clearTimeout(a),r=!0,d?.unsubscribe(),h&&i.removeEventListener("abort",h)};function u(t){e(t)&&(c(),s(t))}let h,d;u(t.getSnapshot()),r||(i&&(h=()=>{c(),o(i.reason)},i.addEventListener("abort",h)),d=t.subscribe({next:u,error:t=>{c(),o(t)},complete:()=>{c(),o(new Error("Actor terminated without satisfying predicate"))}}),r&&d.unsubscribe())})},Object.defineProperty(t,"__esModule",{value:!0})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XState={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="xstate.init",n="xstate.stop";function o(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const i=t=>{const e=o();e&&e.register(t)};function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function a(t,e){return{type:`xstate.error.actor.${t}`,error:e,actorId:t}}function c(t){return{type:s,input:t}}function u(t){setTimeout(()=>{throw t})}const h="function"==typeof Symbol&&Symbol.observable||"@@observable";function d(t,e){const s=p(t),n=p(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&d(s[t],n[t]))}function f(t){if(_(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function p(t){if(Nt(t))return t.value;if("string"!=typeof t)return t;return l(f(t))}function l(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}function y(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const i=n[o];s[i]=e(t[i],i,t,o)}return s}function g(t){return _(t)?t:[t]}function v(t){return void 0===t?[]:g(t)}function m(t,e,s,n){return"function"==typeof t?t({context:e,event:s,self:n}):t}function _(t){return Array.isArray(t)}function b(t){return g(t).map(t=>void 0===t||"string"==typeof t?{target:t}:t)}function S(t){if(void 0!==t&&""!==t)return v(t)}function x(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function w(t,e){return`${e}.${t}`}function I(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actors[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke;return(Array.isArray(i)?i[n]:i).src}function k(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}function E(t,e){return`${t.sessionId}.${e}`}let $=0;let T=!1;let O=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const j={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class A{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new e(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=O.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const n={...j,...s},{clock:o,logger:i,parent:r,syncSnapshot:a,id:c,systemId:h,inspect:d}=n;this.system=r?r.system:function(t,e){const s=new Map,n=new Map,o=new WeakMap,i=new Set,r={},{clock:a,logger:c}=e,u={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},c=E(t,o);h._snapshot._scheduledEvents[c]=i;const u=a.setTimeout(()=>{delete r[c],delete h._snapshot._scheduledEvents[c],h._relay(t,e,s)},n);r[c]=u},cancel:(t,e)=>{const s=E(t,e),n=r[s];delete r[s],delete h._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in h._snapshot._scheduledEvents){const s=h._snapshot._scheduledEvents[e];s.source===t&&u.cancel(t,s.id)}}},h={_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+$++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=o.get(t);void 0!==e&&(n.delete(e),o.delete(t))},get:t=>n.get(t),getAll:()=>Object.fromEntries(n.entries()),_set:(t,e)=>{const s=n.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);n.set(t,e),o.set(e,t)},inspect:t=>{const e=x(t);return i.add(e),{unsubscribe(){i.delete(e)}}},_sendInspectionEvent:e=>{if(!i.size)return;const s={...e,rootId:t.sessionId};i.forEach(t=>t.next?.(s))},_relay:(t,e,s)=>{h._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:e,event:s}),e._send(s)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...h._snapshot._scheduledEvents}}),start:()=>{const t=h._snapshot._scheduledEvents;h._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];u.schedule(s,n,o,i,r)}},_clock:a,_logger:c};return h}(this,{clock:o,logger:i}),d&&!r&&this.system.inspect(x(d)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=r,this._syncSnapshot=a,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get("*");if(!e&&!s)return;const n=[...e?e.values():[],...s?s.values():[]];for(const e of n)try{e(t)}catch(t){u(t)}},actionExecutor:t=>{const e=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:t.type,params:t.params}}),!t.exec)return;const e=T;try{T=!0,t.exec(t.info,t.params)}finally{T=e}};this._processingStatus===O.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),h&&(this.systemId=h,this.system._set(h,this)),this._initState(s?.snapshot??s?.state),h&&"active"!==this._snapshot.status&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(t,e){let s;for(this._snapshot=t;s=this._deferred.shift();)try{s()}catch(e){this._deferred.length=0,this._snapshot={...t,status:"error",error:e}}switch(this._snapshot.status){case"active":for(const e of this.observers)try{e.next?.(t)}catch(t){u(t)}break;case"done":for(const e of this.observers)try{e.next?.(t)}catch(t){u(t)}this._stopProcedure(),this._complete(),this._doneEvent=(n=this.id,o=this._snapshot.output,{type:`xstate.done.actor.${n}`,output:o,actorId:n}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error)}var n,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){const n=x(t,e,s);if(this._processingStatus!==O.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){u(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){u(t)}else u(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const n=e.bind(void 0);return s.add(n),{unsubscribe:()=>{s.delete(n)}}}start(){if(this._processingStatus===O.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=O.Running;const t=c(this.options.input);this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t});switch(this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._snapshot={...this._snapshot,status:"error",error:t},this._error(t),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._snapshot={...this._snapshot,status:"error",error:t},void this._error(t)}this.update(e,t),t.type===n&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===O.Stopped?this:(this.mailbox.clear(),this._processingStatus===O.NotStarted?(this._processingStatus=O.Stopped,this):(this.mailbox.enqueue({type:n}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){u(t)}this.observers.clear()}_reportError(t){if(!this.observers.size)return void(this._parent||u(t));let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){u(t)}}this.observers.clear(),e&&u(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,a(this.id,t))}_stopProcedure(){return this._processingStatus!==O.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this._processingStatus=O.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==O.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:i)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[h](){return this}getSnapshot(){return this._snapshot}}function M(t,...[e]){return new A(t,e)}const N=M;function P(t,e,s,n,{sendId:o}){return[e,{sendId:"function"==typeof o?o(s,n):o},void 0]}function R(t,e){t.defer(()=>{t.system.scheduler.cancel(t.self,e.sendId)})}function C(t){function e(t,e){}return e.type="xstate.cancel",e.sendId=t,e.resolve=P,e.execute=R,e}function V(t,e,s,n,{id:o,systemId:i,src:r,input:a,syncSnapshot:c}){const u="string"==typeof r?I(e.machine,r):r,h="function"==typeof o?o(s):o;let d,f;return u&&(f="function"==typeof a?a({context:e.context,event:s.event,self:t.self}):a,d=M(u,{id:h,src:r,parent:t.self,syncSnapshot:c,systemId:i,input:f})),[Bt(e,{children:{...e.children,[h]:d}}),{id:o,systemId:i,actorRef:d,src:r,input:f},void 0]}function D(t,{actorRef:e}){e&&t.defer(()=>{e._processingStatus!==O.Stopped&&e.start()})}function J(...[t,{id:e,systemId:s,input:n,syncSnapshot:o=!1}={}]){function i(t,e){}return i.type="xstate.spawnChild",i.id=e,i.systemId=s,i.src=t,i.input=n,i.syncSnapshot=o,i.resolve=V,i.execute=D,i}function B(t,e,s,n,{actorRef:o}){const i="function"==typeof o?o(s,n):o,r="string"==typeof i?e.children[i]:i;let a=e.children;return r&&(a={...a},delete a[r.id]),[Bt(e,{children:a}),r,void 0]}function q(t,e){e&&(t.system._unregister(e),e._processingStatus===O.Running?t.defer(()=>{t.stopChild(e)}):t.stopChild(e))}function z(t){function e(t,e){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=B,e.execute=q,e}const L=z;function W(t,e,{stateValue:s}){if("string"==typeof s&&nt(s)){const e=t.machine.getStateNodeById(s);return t._nodes.some(t=>t===e)}return t.matches(s)}function U(t,{context:e,event:s},{guards:n}){return!G(n[0],e,s,t)}function Q(t,{context:e,event:s},{guards:n}){return n.every(n=>G(n,e,s,t))}function F(t,{context:e,event:s},{guards:n}){return n.some(n=>G(n,e,s,t))}function G(t,e,s,n){const{machine:o}=n,i="function"==typeof t,r=i?t:o.implementations.guards["string"==typeof t?t:t.type];if(!i&&!r)throw new Error(`Guard '${"string"==typeof t?t:t.type}' is not implemented.'.`);if("function"!=typeof r)return G(r,e,s,n);const a={context:e,event:s},c=i||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:e,event:s}):t.params:void 0;if(!("check"in r))return r(a,c);return r.check(n,a,r)}const X=t=>"atomic"===t.type||"final"===t.type;function H(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function K(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function Y(t){const e=new Set(t),s=tt(e);for(const t of e)if("compound"!==t.type||s.get(t)&&s.get(t).length){if("parallel"===t.type)for(const s of H(t))if("history"!==s.type&&!e.has(s)){const t=ct(s);for(const s of t)e.add(s)}}else ct(t).forEach(t=>e.add(t));for(const t of e){let s=t.parent;for(;s;)e.add(s),s=s.parent}return e}function Z(t,e){const s=e.get(t);if(!s)return{};if("compound"===t.type){const t=s[0];if(!t)return{};if(X(t))return t.key}const n={};for(const t of s)n[t.key]=Z(t,e);return n}function tt(t){const e=new Map;for(const s of t)e.has(s)||e.set(s,[]),s.parent&&(e.has(s.parent)||e.set(s.parent,[]),e.get(s.parent).push(s));return e}function et(t,e){return Z(t,tt(Y(e)))}function st(t,e){return"compound"===e.type?H(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?H(e).every(e=>st(t,e)):"final"===e.type}const nt=t=>"#"===t[0];function ot(t){const e=t.config.after;if(!e)return[];const s=Object.keys(e).flatMap(s=>{const n=e[s],o="string"==typeof n?{target:n}:n,i=Number.isNaN(+s)?s:+s,r=(e=>{const s=(n=e,o=t.id,{type:`xstate.after.${n}.${o}`});var n,o;const i=s.type;return t.entry.push(Kt(s,{id:i,delay:e})),t.exit.push(C(i)),i})(i);return v(o).map(t=>({...t,event:r,delay:i}))});return s.map(e=>{const{delay:s}=e;return{...it(t,e.event,e),delay:s}})}function it(t,e,s){const n=S(s.target),o=s.reenter??!1,i=function(t,e){if(void 0===e)return;return e.map(e=>{if("string"!=typeof e)return e;if(nt(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return dt(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`);try{return dt(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}(t,n),r={...s,actions:v(s.actions),guard:s.guard,target:i,source:t,reenter:o,eventType:e,toJSON:()=>({...r,source:`#${t.id}`,target:i?i.map(t=>`#${t.id}`):void 0})};return r}function rt(t){const e=S(t.config.target);return e?{target:e.map(e=>"string"==typeof e?dt(t.parent,e):e)}:t.parent.initial}function at(t){return"history"===t.type}function ct(t){const e=ut(t);for(const s of e)for(const n of K(s,t))e.add(n);return e}function ut(t){const e=new Set;return function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of H(s))t(e)}(t),e}function ht(t,e){if(nt(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const s=t.states[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function dt(t,e){if("string"==typeof e&&nt(e))try{return t.machine.getStateNodeById(e)}catch{}const s=f(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=ht(n,t)}return n}function ft(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=s.map(e=>ht(t,e)).filter(Boolean);return[t.machine.root,t].concat(n,s.reduce((s,n)=>{const o=ht(t,n);if(!o)return s;const i=ft(o,e[n]);return s.concat(i)},[]))}function pt(t,e,s,n){return"string"==typeof e?function(t,e,s,n){const o=ht(t,e).next(s,n);return o&&o.length?o:t.next(s,n)}(t,e,s,n):1===Object.keys(e).length?function(t,e,s,n){const o=Object.keys(e),i=pt(ht(t,o[0]),e[o[0]],s,n);return i&&i.length?i:t.next(s,n)}(t,e,s,n):function(t,e,s,n){const o=[];for(const i of Object.keys(e)){const r=e[i];if(!r)continue;const a=pt(ht(t,i),r,s,n);a&&o.push(...a)}return o.length?o:t.next(s,n)}(t,e,s,n)}function lt(t){return Object.keys(t.states).map(e=>t.states[e]).filter(t=>"history"===t.type)}function yt(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function gt(t,e){const s=new Set(t),n=new Set(e);for(const t of s)if(n.has(t))return!0;for(const t of n)if(s.has(t))return!0;return!1}function vt(t,e,s){const n=new Set;for(const o of t){let t=!1;const i=new Set;for(const r of n)if(gt(bt([o],e,s),bt([r],e,s))){if(!yt(o.source,r.source)){t=!0;break}i.add(r)}if(!t){for(const t of i)n.delete(t);n.add(o)}}return Array.from(n)}function mt(t,e){if(!t.target)return[];const s=new Set;for(const n of t.target)if(at(n))if(e[n.id])for(const t of e[n.id])s.add(t);else for(const t of mt(rt(n),e))s.add(t);else s.add(n);return[...s]}function _t(t,e){const s=mt(t,e);if(!s)return;if(!t.reenter&&s.every(e=>e===t.source||yt(e,t.source)))return t.source;const n=function(t){const[e,...s]=t;for(const t of K(e,void 0))if(s.every(e=>yt(e,t)))return t}(s.concat(t.source));return n||(t.reenter?void 0:t.source.machine.root)}function bt(t,e,s){const n=new Set;for(const o of t)if(o.target?.length){const t=_t(o,s);o.reenter&&o.source===t&&n.add(t);for(const s of e)yt(s,t)&&n.add(s)}return[...n]}function St(t,e,s,n,o,i){if(!t.length)return e;const a=new Set(e._nodes);let c=e.historyValue;const u=vt(t,a,c);let h=e;o||([h,c]=function(t,e,s,n,o,i,r){let a=t;const c=bt(n,o,i);let u;c.sort((t,e)=>e.order-t.order);for(const t of c)for(const e of lt(t)){let s;s="deep"===e.history?e=>X(e)&&yt(e,t):e=>e.parent===t,u??={...i},u[e.id]=Array.from(o).filter(s)}for(const t of c)a=Tt(a,e,s,[...t.exit,...t.invoke.map(t=>z(t.id))],r,void 0),o.delete(t);return[a,u||i]}(h,n,s,u,a,c,i,s.actionExecutor)),h=Tt(h,n,s,u.flatMap(t=>t.actions),i,void 0),h=function(t,e,s,n,o,i,a,c){let u=t;const h=new Set,d=new Set;(function(t,e,s,n){for(const o of t){const t=_t(o,e);for(const i of o.target||[])at(i)||o.source===i&&o.source===t&&!o.reenter||(n.add(i),s.add(i)),wt(i,e,s,n);const i=mt(o,e);for(const r of i){const i=K(r,t);"parallel"===t?.type&&i.push(t),It(n,e,s,i,!o.source.parent&&o.reenter?void 0:t)}}})(n,a,d,h),c&&d.add(t.machine.root);const f=new Set;for(const t of[...h].sort((t,e)=>t.order-e.order)){o.add(t);const n=[];n.push(...t.entry);for(const e of t.invoke)n.push(J(e.src,{...e,syncSnapshot:!!e.onSnapshot}));if(d.has(t)){const e=t.initial.actions;n.push(...e)}if(u=Tt(u,e,s,n,i,t.invoke.map(t=>t.id)),"final"===t.type){const n=t.parent;let a="parallel"===n?.type?n:n?.parent,c=a||t;for("compound"===n?.type&&i.push(r(n.id,void 0!==t.output?m(t.output,u.context,e,s.self):void 0));"parallel"===a?.type&&!f.has(a)&&st(o,a);)f.add(a),i.push(r(a.id)),c=a,a=a.parent;if(a)continue;u=Bt(u,{status:"done",output:xt(u,e,s,u.machine.root,c)})}}return u}(h,n,s,u,a,i,c,o);const d=[...a];"done"===h.status&&(h=Tt(h,n,s,d.sort((t,e)=>e.order-t.order).flatMap(t=>t.exit),i,void 0));try{return c===e.historyValue&&function(t,e){if(t.length!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;return!0}(e._nodes,a)?h:Bt(h,{_nodes:d,historyValue:c})}catch(t){throw t}}function xt(t,e,s,n,o){if(void 0===n.output)return;const i=r(o.id,void 0!==o.output&&o.parent?m(o.output,t.context,e,s.self):void 0);return m(n.output,t.context,i,s.self)}function wt(t,e,s,n){if(at(t))if(e[t.id]){const o=e[t.id];for(const t of o)n.add(t),wt(t,e,s,n);for(const i of o)kt(i,t.parent,n,e,s)}else{const o=rt(t);for(const i of o.target)n.add(i),o===t.parent?.initial&&s.add(t.parent),wt(i,e,s,n);for(const i of o.target)kt(i,t.parent,n,e,s)}else if("compound"===t.type){const[o]=t.initial.target;at(o)||(n.add(o),s.add(o)),wt(o,e,s,n),kt(o,t,n,e,s)}else if("parallel"===t.type)for(const o of H(t).filter(t=>!at(t)))[...n].some(t=>yt(t,o))||(at(o)||(n.add(o),s.add(o)),wt(o,e,s,n))}function It(t,e,s,n,o){for(const i of n)if(o&&!yt(i,o)||t.add(i),"parallel"===i.type)for(const n of H(i).filter(t=>!at(t)))[...t].some(t=>yt(t,n))||(t.add(n),wt(n,e,s,t))}function kt(t,e,s,n,o){It(s,n,o,K(t,e))}function Et(t,e){return t.implementations.actions[e]}function $t(t,e,s,n,o,i){const{machine:r}=t;let a=t;for(const t of n){const n="function"==typeof t,c=n?t:Et(r,"string"==typeof t?t:t.type),u={context:a.context,event:e,self:s.self,system:s.system},h=n||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:a.context,event:e}):t.params:void 0;if(!c||!("resolve"in c)){s.actionExecutor({type:"string"==typeof t?t:"object"==typeof t?t.type:t.name||"(anonymous)",info:u,params:h,exec:c});continue}const d=c,[f,p,l]=d.resolve(s,a,u,h,c,o);a=f,"retryResolve"in d&&i?.push([d,p]),"execute"in d&&s.actionExecutor({type:d.type,info:u,params:p,exec:d.execute.bind(null,s,p)}),l&&(a=$t(a,e,s,l,o,i))}return a}function Tt(t,e,s,n,o,i){const r=i?[]:void 0,a=$t(t,e,s,n,{internalQueue:o,deferredActorIds:i},r);return r?.forEach(([t,e])=>{t.retryResolve(s,a,e)}),a}function Ot(t,e,o,i){let r=t;const a=[];function c(t,e,s){o.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:o.self,event:e,snapshot:t,_transitions:s}),a.push(t)}if(e.type===n)return r=Bt(jt(r,e,o),{status:"stopped"}),c(r,e,[]),{snapshot:r,microstates:a};let u=e;if(u.type!==s){const e=u,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),n=At(e,r);if(s&&!n.length)return r=Bt(t,{status:"error",error:e.error}),c(r,e,[]),{snapshot:r,microstates:a};r=St(n,t,o,u,!1,i),c(r,e,n)}let h=!0;for(;"active"===r.status;){let t=h?Mt(r,u):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;u=i.shift(),t=At(u,r)}r=St(t,r,o,u,!1,i),h=r!==e,c(r,u,t)}return"active"!==r.status&&jt(r,u,o),{snapshot:r,microstates:a}}function jt(t,e,s){return Tt(t,e,s,Object.values(t.children).map(t=>z(t)),[],void 0)}function At(t,e){return e.machine.getTransitionData(e,t)}function Mt(t,e){const s=new Set,n=t._nodes.filter(X);for(const o of n)t:for(const n of[o].concat(K(o,void 0)))if(n.always)for(const o of n.always)if(void 0===o.guard||G(o.guard,t.context,e,t)){s.add(o);break t}return vt(Array.from(s),new Set(t._nodes),t.historyValue)}function Nt(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const Pt=function(t){return d(t,this.value)},Rt=function(t){return this.tags.has(t)},Ct=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some(t=>void 0!==t.target||t.actions.length)},Vt=function(){const{_nodes:t,tags:e,machine:s,getMeta:n,toJSON:o,can:i,hasTag:r,matches:a,...c}=this;return{...c,tags:Array.from(e)}},Dt=function(){return this._nodes.reduce((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t),{})};function Jt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:et(e.root,t._nodes),tags:new Set(t._nodes.flatMap(t=>t.tags)),children:t.children,historyValue:t.historyValue||{},matches:Pt,hasTag:Rt,can:Ct,getMeta:Dt,toJSON:Vt}}function Bt(t,e={}){return Jt({...t,...e},t.machine)}function qt(t){if("object"!=typeof t||null===t)return{};const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map(t=>({id:t.id})))}return e}function zt(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:1,id:n.id};else{const o=zt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function Lt(t,{machine:e,context:s},n,o){return(i,r)=>{const a=((i,r)=>{if("string"==typeof i){const a=I(e,i);if(!a)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const c=M(a,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:s,event:n,self:t.self}):r?.input,src:i,systemId:r?.systemId});return o[c.id]=c,c}return M(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[a.id]=a,t.defer(()=>{a._processingStatus!==O.Stopped&&a.start()}),a}}function Wt(t,e,s,n,{assignment:o}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},r={context:e.context,event:s.event,spawn:Lt(t,e,s.event,i),self:t.self,system:t.system};let a={};if("function"==typeof o)a=o(r,n);else for(const t of Object.keys(o)){const e=o[t];a[t]="function"==typeof e?e(r,n):e}return[Bt(e,{context:Object.assign({},e.context,a),children:Object.keys(i).length?{...e.children,...i}:e.children}),void 0,void 0]}function Ut(t){function e(t,e){}return e.type="xstate.assign",e.assignment=t,e.resolve=Wt,e}function Qt(t,e,s,n,{event:o}){return[e,{event:"function"==typeof o?o(s,n):o},void 0]}function Ft(t,{event:e}){t.defer(()=>t.emit(e))}function Gt(t){function e(t,e){}return e.type="xstate.emit",e.event=t,e.resolve=Qt,e.execute=Ft,e}function Xt(t,e,s,n,{event:o,id:i,delay:r},{internalQueue:a}){const c=e.machine.implementations.delays;if("string"==typeof o)throw new Error(`Only event objects may be used with raise; use raise({ type: "${o}" }) instead`);const u="function"==typeof o?o(s,n):o;let h;if("string"==typeof r){const t=c&&c[r];h="function"==typeof t?t(s,n):t}else h="function"==typeof r?r(s,n):r;return"number"!=typeof h&&a.push(u),[e,{event:u,id:i,delay:h},void 0]}function Ht(t,e){const{event:s,delay:n,id:o}=e;"number"!=typeof n||t.defer(()=>{const e=t.self;t.system.scheduler.schedule(e,e,s,n,o)})}function Kt(t,e){function s(t,e){}return s.type="xstate.raise",s.event=t,s.id=e?.id,s.delay=e?.delay,s.resolve=Xt,s.execute=Ht,s}let Yt=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function Zt(t,e,s,n,{to:o,event:i,id:r,delay:a},c){const u=e.machine.implementations.delays;if("string"==typeof i)throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${i}" }) instead`);const h="function"==typeof i?i(s,n):i;let d;if("string"==typeof a){const t=u&&u[a];d="function"==typeof t?t(s,n):t}else d="function"==typeof a?a(s,n):a;const f="function"==typeof o?o(s,n):o;let p;if("string"==typeof f){if(p=f===Yt.Parent?t.self._parent:f===Yt.Internal?t.self:f.startsWith("#_")?e.children[f.slice(2)]:c.deferredActorIds?.includes(f)?f:e.children[f],!p)throw new Error(`Unable to send event to actor '${f}' from machine '${e.machine.id}'.`)}else p=f||t.self;return[e,{to:p,targetId:"string"==typeof f?f:void 0,event:h,id:r,delay:d},void 0]}function te(t,e,s){"string"==typeof s.to&&(s.to=e.children[s.to])}function ee(t,e){t.defer(()=>{const{to:s,event:n,delay:o,id:i}=e;"number"!=typeof o?t.system._relay(t.self,s,"xstate.error"===n.type?a(t.self.id,n.data):n):t.system.scheduler.schedule(t.self,s,n,o,i)})}function se(t,e,s){function n(t,e){}return n.type="xstate.sendTo",n.to=t,n.event=e,n.id=s?.id,n.delay=s?.delay,n.resolve=Zt,n.retryResolve=te,n.execute=ee,n}function ne(t,e){return se(Yt.Parent,t,e)}function oe(t,e,s,n,{collect:o}){const i=[],r=function(t){i.push(t)};return r.assign=(...t)=>{i.push(Ut(...t))},r.cancel=(...t)=>{i.push(C(...t))},r.raise=(...t)=>{i.push(Kt(...t))},r.sendTo=(...t)=>{i.push(se(...t))},r.sendParent=(...t)=>{i.push(ne(...t))},r.spawnChild=(...t)=>{i.push(J(...t))},r.stopChild=(...t)=>{i.push(z(...t))},r.emit=(...t)=>{i.push(Gt(...t))},o({context:s.context,event:s.event,enqueue:r,check:t=>G(t,e.context,s.event,e),self:t.self,system:t.system},n),[e,void 0,i]}function ie(t){function e(t,e){}return e.type="xstate.enqueueActions",e.collect=t,e.resolve=oe,e}function re(t,e,s,n,{value:o,label:i}){return[e,{value:"function"==typeof o?o(s,n):o,label:i},void 0]}function ae({logger:t},{value:e,label:s}){s?t(s,e):t(e)}function ce(t=({context:t,event:e})=>({context:t,event:e}),e){function s(t,e){}return s.type="xstate.log",s.value=t,s.label=e,s.resolve=re,s.execute=ae,s}function ue(t,e){return{config:t,transition:(e,s,n)=>({...e,context:t(e.context,s,n)}),getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof e?e({input:s}):e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}const he=new WeakMap;const de="xstate.observable.next",fe="xstate.observable.error",pe="xstate.observable.complete";const le="xstate.promise.resolve",ye="xstate.promise.reject",ge=new WeakMap;const ve=ue(t=>{},void 0);const me=new WeakMap;function _e(t,e,s){let n=me.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},me.set(t,n)),n[e]}const be={},Se=t=>"string"==typeof t?{type:t}:"function"==typeof t?"resolve"in t?{type:t.type}:{type:t.name}:t;class xe{constructor(t,e){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?y(this.config.states,(t,e)=>new xe(t,{_parent:this,_key:e,_machine:this.machine})):be,"compound"===this.type&&!this.config.initial)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.`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=v(this.config.entry).slice(),this.exit=v(this.config.exit).slice(),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=v(t.tags).slice()}_initialize(){this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=t.config.on[s];e.set(s,b(n).map(e=>it(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,b(t.config.onDone).map(e=>it(t,s,e)))}for(const s of t.invoke){if(s.onDone){const n=`xstate.done.actor.${s.id}`;e.set(n,b(s.onDone).map(e=>it(t,n,e)))}if(s.onError){const n=`xstate.error.actor.${s.id}`;e.set(n,b(s.onError).map(e=>it(t,n,e)))}if(s.onSnapshot){const n=`xstate.snapshot.${s.id}`;e.set(n,b(s.onSnapshot).map(e=>it(t,n,e)))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),this.config.always&&(this.always=b(this.config.always).map(t=>it(this,"",t))),Object.keys(this.states).forEach(t=>{this.states[t]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(Se),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Se),eventType:null})}:void 0,history:this.history,states:y(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(Se)})),entry:this.entry.map(Se),exit:this.exit.map(Se),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return _e(this,"invoke",()=>v(this.config.invoke).map((t,e)=>{const{src:s,systemId:n}=t,o=t.id??w(this.id,e),i="string"==typeof s?s:`xstate.invoke.${w(this.id,e)}`;return{...t,src:i,id:o,systemId:n,toJSON(){const{onDone:e,onError:s,...n}=t;return{...n,type:"xstate.invoke",src:i,id:o}}}}))}get on(){return _e(this,"on",()=>[...this.transitions].flatMap(([t,e])=>e.map(e=>[t,e])).reduce((t,[e,s])=>(t[e]=t[e]||[],t[e].push(s),t),{}))}get after(){return _e(this,"delayedTransitions",()=>ot(this))}get initial(){return _e(this,"initial",()=>function(t,e){const s="string"==typeof e?t.states[e]:e?t.states[e.target]:void 0;if(!s&&e)throw new Error(`Initial state node "${e}" not found on parent state node #${t.id}`);const n={source:t,actions:e&&"string"!=typeof e?v(e.actions):[],eventType:null,reenter:!1,target:s?[s]:[],toJSON:()=>({...n,source:`#${t.id}`,target:s?[`#${s.id}`]:[]})};return n}(this,this.config.initial))}next(t,e){const s=e.type,n=[];let o;const i=_e(this,`candidates-${s}`,()=>{return e=s,(t=this).transitions.get(e)||[...t.transitions.keys()].filter(t=>k(e,t)).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));var t,e});for(const r of i){const{guard:i}=r,a=t.context;let c=!1;try{c=!i||G(i,a,e,t)}catch(t){const e="string"==typeof i?i:"object"==typeof i?i.type:void 0;throw new Error(`Unable to evaluate guard ${e?`'${e}' `:""}in transition for event '${s}' in state node '${this.id}':\n${t.message}`)}if(c){n.push(...r.actions),o=r;break}}return o?[o]:void 0}get events(){return _e(this,"events",()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const n=t[s];if(n.states)for(const t of n.events)e.add(`${t}`)}return Array.from(e)})}get ownEvents(){const t=Object.keys(Object.fromEntries(this.transitions)),e=new Set(t.filter(t=>this.transitions.get(t).some(t=>!(!t.target&&!t.actions.length&&!t.reenter))));return Array.from(e)}}class we{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:e?.actors??{},actions:e?.actions??{},delays:e?.delays??{},guards:e?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new xe(t,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.implementations;return new we(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}})}resolveState(t){const e=(s=this.root,n=t.value,et(s,[...Y(ft(s,n))]));var s,n;const o=Y(ft(this.root,e));return Jt({_nodes:[...o],context:t.context||{},children:{},status:st(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return Ot(t,e,s,[]).snapshot}microstep(t,e,s){return Ot(t,e,s,[]).microstates}getTransitionData(t,e){return pt(this.root,t.value,t,e)||[]}getPreInitialState(t,e,s){const{context:n}=this.config,o=Jt({context:"function"!=typeof n&&n?n:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof n){return Tt(o,e,t,[Ut(({spawn:t,event:e,self:s})=>n({spawn:t,input:e.input,self:s}))],s,void 0)}return o}getInitialSnapshot(t,e){const s=c(e),n=[],o=this.getPreInitialState(t,s,n),i=St([{target:[...ut(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],o,t,s,!0,n),{snapshot:r}=Ot(i,s,t,n);return r}start(t){Object.values(t.children).forEach(t=>{"active"===t.getSnapshot().status&&t.start()})}getStateNodeById(t){const e=f(t),s=e.slice(1),n=nt(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return dt(o,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,tags:n,machine:o,children:i,context:r,can:a,hasTag:c,matches:u,getMeta:h,toJSON:d,...f}=t,p={};for(const t in i){const s=i[t];p[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s.systemId,syncSnapshot:s._syncSnapshot}}return{...f,context:zt(r),children:p,historyValue:qt(f.historyValue)}}(t,e)}restoreSnapshot(t,e){const s={},n=t.children;function o(t,e){if(e instanceof xe)return e;try{return t.machine.getStateNodeById(e.id)}catch{}}Object.keys(n).forEach(t=>{const o=n[t],i=o.snapshot,r=o.src,a="string"==typeof r?I(this,r):r;if(!a)return;const c=M(a,{id:t,parent:e.self,syncSnapshot:o.syncSnapshot,snapshot:i,src:r,systemId:o.systemId});s[t]=c});const i=function(t,e){if(!e||"object"!=typeof e)return{};const s={};for(const n in e){const i=e[n];for(const e of i){const i=o(t,e);i&&(s[n]??=[],s[n].push(i))}}return s}(this.root,t.historyValue),r=Jt({...t,children:s,_nodes:Array.from(Y(ft(this.root,t.value))),historyValue:i},this),a=new Set;return function t(e,s){if(!a.has(e)){a.add(e);for(const n in e){const o=e[n];if(o&&"object"==typeof o){if("xstate$$type"in o&&1===o.xstate$$type){e[n]=s[o.id];continue}t(o,s)}}}}(r.context,s),r}}function Ie(t,e){return new we(t,e)}function ke(t){const e=M(t);return{self:e,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:e.system,emit:()=>{},actionExecutor:()=>{}}}const Ee={timeout:1/0};t.Actor=A,t.SimulatedClock=class{constructor(){this.timeouts=new Map,this._now=0,this._id=0,this._flushing=!1,this._flushingInvalidated=!1}now(){return this._now}getId(){return this._id++}setTimeout(t,e){this._flushingInvalidated=this._flushing;const s=this.getId();return this.timeouts.set(s,{start:this.now(),timeout:e,fn:t}),s}clearTimeout(t){this._flushingInvalidated=this._flushing,this.timeouts.delete(t)}set(t){if(this._now>t)throw new Error("Unable to travel back in time");this._now=t,this.flushTimeouts()}flushTimeouts(){if(this._flushing)return void(this._flushingInvalidated=!0);this._flushing=!0;const t=[...this.timeouts].sort(([t,e],[s,n])=>{const o=e.start+e.timeout;return n.start+n.timeout>o?-1:1});for(const[e,s]of t){if(this._flushingInvalidated)return this._flushingInvalidated=!1,this._flushing=!1,void this.flushTimeouts();this.now()-s.start>=s.timeout&&(this.timeouts.delete(e),s.fn.call(null))}this._flushing=!1}increment(t){this._now+=t,this.flushTimeouts()}},t.SpecialTargets=Yt,t.StateMachine=we,t.StateNode=xe,t.__unsafe_getAllOwnEventDescriptors=function(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]},t.and=function(t){function e(t,e){return!1}return e.check=Q,e.guards=t,e},t.assertEvent=function(t,e){const s=v(e);if(!s.some(e=>k(t.type,e))){const e=1===s.length?`type matching "${s[0]}"`:`one of types matching "${s.join('", "')}"`;throw new Error(`Expected event ${JSON.stringify(t)} to have ${e}`)}},t.assign=Ut,t.cancel=C,t.createActor=M,t.createEmptyActor=function(){return M(ve)},t.createMachine=Ie,t.emit=Gt,t.enqueueActions=ie,t.forwardTo=function(t,e){return se(t,({event:t})=>t,e)},t.fromCallback=function(t){const e={config:t,start:(e,s)=>{const{self:n,system:o,emit:i}=s,r={receivers:void 0,dispose:void 0};he.set(n,r),r.dispose=t({input:e.input,system:o,self:n,sendBack:t=>{"stopped"!==n.getSnapshot().status&&n._parent&&o._relay(n,n._parent,t)},receive:t=>{r.receivers??=new Set,r.receivers.add(t)},emit:i})},transition:(t,e,s)=>{const o=he.get(s.self);return e.type===n?(t={...t,status:"stopped",error:void 0},o.dispose?.(),t):(o.receivers?.forEach(t=>t(e)),t)},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e},t.fromEventObservable=function(t){const e={config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case fe:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case pe:return{...t,status:"done",input:void 0,_subscription:void 0};case n:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{"done"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{s._parent&&n._relay(s,s._parent,t)},error:t=>{n._relay(s,s,{type:fe,data:t})},complete:()=>{n._relay(s,s,{type:pe})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e},t.fromObservable=function(t){const e={config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case de:return{...t,context:e.data};case fe:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case pe:return{...t,status:"done",input:void 0,_subscription:void 0};case n:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{"done"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{n._relay(s,s,{type:de,data:t})},error:t=>{n._relay(s,s,{type:fe,data:t})},complete:()=>{n._relay(s,s,{type:pe})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e},t.fromPromise=function(t){const e={config:t,transition:(t,e,s)=>{if("active"!==t.status)return t;switch(e.type){case le:{const s=e.data;return{...t,status:"done",output:s,input:void 0}}case ye:return{...t,status:"error",error:e.data,input:void 0};case n:return ge.get(s.self)?.abort(),{...t,status:"stopped",input:void 0};default:return t}},start:(e,{self:s,system:n,emit:o})=>{if("active"!==e.status)return;const i=new AbortController;ge.set(s,i);Promise.resolve(t({input:e.input,system:n,self:s,signal:i.signal,emit:o})).then(t=>{"active"===s.getSnapshot().status&&(ge.delete(s),n._relay(s,s,{type:le,data:t}))},t=>{"active"===s.getSnapshot().status&&(ge.delete(s),n._relay(s,s,{type:ye,data:t}))})},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e},t.fromTransition=ue,t.getInitialSnapshot=function(t,...[e]){const s=ke(t);return t.getInitialSnapshot(s,e)},t.getNextSnapshot=function(t,e,s){const n=ke(t);return n.self._snapshot=e,t.transition(e,s,n)},t.getStateNodes=ft,t.initialTransition=function(t,...[e]){const s=[],n=ke(t);return n.actionExecutor=t=>{s.push(t)},[t.getInitialSnapshot(n,e),s]},t.interpret=N,t.isMachineSnapshot=Nt,t.log=ce,t.matchesState=d,t.not=function(t){function e(t,e){return!1}return e.check=U,e.guards=[t],e},t.or=function(t){function e(t,e){return!1}return e.check=F,e.guards=t,e},t.pathToStateValue=l,t.raise=Kt,t.sendParent=ne,t.sendTo=se,t.setup=function t({schemas:e,actors:s,actions:n,guards:o,delays:i}){return{assign:Ut,sendTo:se,raise:Kt,log:ce,cancel:C,stopChild:z,enqueueActions:ie,emit:Gt,spawnChild:J,createStateConfig:t=>t,createAction:t=>t,createMachine:t=>Ie({...t,schemas:e},{actors:s,actions:n,guards:o,delays:i}),extend:r=>t({schemas:e,actors:s,actions:{...n,...r.actions},guards:{...o,...r.guards},delays:{...i,...r.delays}})}},t.spawnChild=J,t.stateIn=function(t){function e(){return!1}return e.check=W,e.stateValue=t,e},t.stop=L,t.stopChild=z,t.toObserver=x,t.toPromise=function(t){return new Promise((e,s)=>{t.subscribe({complete:()=>{e(t.getSnapshot().output)},error:s})})},t.transition=function(t,e,s){const n=[],o=ke(t);return o.actionExecutor=t=>{n.push(t)},[t.transition(e,s,o),n]},t.waitFor=function(t,e,s){const n={...Ee,...s};return new Promise((s,o)=>{const{signal:i}=n;if(i?.aborted)return void o(i.reason);let r=!1;const a=n.timeout===1/0?void 0:setTimeout(()=>{c(),o(new Error(`Timeout of ${n.timeout} ms exceeded`))},n.timeout),c=()=>{clearTimeout(a),r=!0,d?.unsubscribe(),h&&i.removeEventListener("abort",h)};function u(t){e(t)&&(c(),s(t))}let h,d;u(t.getSnapshot()),r||(i&&(h=()=>{c(),o(i.reason)},i.addEventListener("abort",h)),d=t.subscribe({next:u,error:t=>{c(),o(t)},complete:()=>{c(),o(new Error("Actor terminated without satisfying predicate"))}}),r&&d.unsubscribe())})},Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate.umd.min.js.map