xstate 5.32.0 → 6.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +7 -8
  2. package/dist/StateMachine-47e60715.esm.js +720 -0
  3. package/dist/StateMachine-48dcad8f.cjs.js +723 -0
  4. package/dist/StateMachine-6e063ac1.development.cjs.js +740 -0
  5. package/dist/StateMachine-6ec50e21.development.esm.js +737 -0
  6. package/dist/declarations/src/State.d.ts +11 -13
  7. package/dist/declarations/src/StateMachine.d.ts +27 -21
  8. package/dist/declarations/src/StateNode.d.ts +18 -54
  9. package/dist/declarations/src/actions.d.ts +14 -9
  10. package/dist/declarations/src/actors/callback.d.ts +42 -16
  11. package/dist/declarations/src/actors/index.d.ts +9 -6
  12. package/dist/declarations/src/actors/listener.d.ts +18 -0
  13. package/dist/declarations/src/actors/logic.d.ts +105 -0
  14. package/dist/declarations/src/actors/observable.d.ts +72 -27
  15. package/dist/declarations/src/actors/promise.d.ts +133 -48
  16. package/dist/declarations/src/actors/subscription.d.ts +22 -0
  17. package/dist/declarations/src/atom.d.ts +81 -0
  18. package/dist/declarations/src/createActor.d.ts +31 -33
  19. package/dist/declarations/src/createMachine.d.ts +35 -7
  20. package/dist/declarations/src/createMachineFromConfig.d.ts +176 -0
  21. package/dist/declarations/src/graph/graph.d.ts +4 -2
  22. package/dist/declarations/src/index.d.ts +12 -8
  23. package/dist/declarations/src/inspection.d.ts +84 -30
  24. package/dist/declarations/src/mapState.d.ts +4 -2
  25. package/dist/declarations/src/schema.types.d.ts +90 -0
  26. package/dist/declarations/src/serialize.d.ts +44 -0
  27. package/dist/declarations/src/setup.d.ts +251 -123
  28. package/dist/declarations/src/spawn.d.ts +6 -31
  29. package/dist/declarations/src/stateUtils.d.ts +21 -19
  30. package/dist/declarations/src/system.d.ts +8 -7
  31. package/dist/declarations/src/transition.d.ts +5 -5
  32. package/dist/declarations/src/types.d.ts +407 -406
  33. package/dist/declarations/src/types.v6.d.ts +392 -0
  34. package/dist/declarations/src/utils.d.ts +4 -3
  35. package/dist/index-39259ea4.development.esm.js +4948 -0
  36. package/dist/index-688701ed.esm.js +4909 -0
  37. package/dist/index-c35824b4.development.cjs.js +5007 -0
  38. package/dist/index-f0d7107d.cjs.js +4968 -0
  39. package/dist/xstate-actors.cjs.js +12 -838
  40. package/dist/xstate-actors.cjs.mjs +10 -5
  41. package/dist/xstate-actors.development.cjs.js +12 -838
  42. package/dist/xstate-actors.development.cjs.mjs +10 -5
  43. package/dist/xstate-actors.development.esm.js +1 -836
  44. package/dist/xstate-actors.esm.js +1 -836
  45. package/dist/xstate-actors.umd.min.js +1 -1
  46. package/dist/xstate-actors.umd.min.js.map +1 -1
  47. package/dist/xstate-graph.cjs.js +18 -29
  48. package/dist/xstate-graph.development.cjs.js +18 -29
  49. package/dist/xstate-graph.development.esm.js +15 -26
  50. package/dist/xstate-graph.esm.js +15 -26
  51. package/dist/xstate-graph.umd.min.js +1 -1
  52. package/dist/xstate-graph.umd.min.js.map +1 -1
  53. package/dist/xstate.cjs.js +1316 -108
  54. package/dist/xstate.cjs.mjs +22 -22
  55. package/dist/xstate.development.cjs.js +1316 -108
  56. package/dist/xstate.development.cjs.mjs +22 -22
  57. package/dist/xstate.development.esm.js +1278 -72
  58. package/dist/xstate.esm.js +1278 -72
  59. package/dist/xstate.umd.min.js +1 -1
  60. package/dist/xstate.umd.min.js.map +1 -1
  61. package/package.json +3 -47
  62. package/dist/StateMachine-45e79c35.esm.js +0 -560
  63. package/dist/StateMachine-be2e51a3.development.cjs.js +0 -569
  64. package/dist/StateMachine-e0178d48.development.esm.js +0 -566
  65. package/dist/StateMachine-e6732977.cjs.js +0 -563
  66. package/dist/assign-2aa58daa.esm.js +0 -127
  67. package/dist/assign-927227d6.development.cjs.js +0 -135
  68. package/dist/assign-e8f2bd75.cjs.js +0 -129
  69. package/dist/assign-f338cee3.development.esm.js +0 -133
  70. package/dist/declarations/src/actions/assign.d.ts +0 -45
  71. package/dist/declarations/src/actions/cancel.d.ts +0 -39
  72. package/dist/declarations/src/actions/emit.d.ts +0 -44
  73. package/dist/declarations/src/actions/enqueueActions.d.ts +0 -57
  74. package/dist/declarations/src/actions/log.d.ts +0 -16
  75. package/dist/declarations/src/actions/raise.d.ts +0 -21
  76. package/dist/declarations/src/actions/send.d.ts +0 -42
  77. package/dist/declarations/src/actions/spawnChild.d.ts +0 -34
  78. package/dist/declarations/src/actions/stopChild.d.ts +0 -19
  79. package/dist/declarations/src/actors/transition.d.ts +0 -143
  80. package/dist/declarations/src/dev/index.d.ts +0 -14
  81. package/dist/declarations/src/guards.d.ts +0 -128
  82. package/dist/log-029f180b.development.cjs.js +0 -433
  83. package/dist/log-5a37e0ee.development.esm.js +0 -425
  84. package/dist/log-605ef461.esm.js +0 -397
  85. package/dist/log-fedf0966.cjs.js +0 -405
  86. package/dist/raise-74097812.development.esm.js +0 -2823
  87. package/dist/raise-7c948725.cjs.js +0 -2816
  88. package/dist/raise-964cd4e9.development.cjs.js +0 -2878
  89. package/dist/raise-e974d1c9.esm.js +0 -2761
  90. package/dist/xstate-actions.cjs.d.mts +0 -2
  91. package/dist/xstate-actions.cjs.d.ts +0 -2
  92. package/dist/xstate-actions.cjs.js +0 -23
  93. package/dist/xstate-actions.cjs.mjs +0 -14
  94. package/dist/xstate-actions.development.cjs.js +0 -23
  95. package/dist/xstate-actions.development.cjs.mjs +0 -14
  96. package/dist/xstate-actions.development.esm.js +0 -4
  97. package/dist/xstate-actions.esm.js +0 -4
  98. package/dist/xstate-actions.umd.min.js +0 -2
  99. package/dist/xstate-actions.umd.min.js.map +0 -1
  100. package/dist/xstate-dev.cjs.d.mts +0 -2
  101. package/dist/xstate-dev.cjs.d.ts +0 -2
  102. package/dist/xstate-dev.cjs.js +0 -48
  103. package/dist/xstate-dev.cjs.mjs +0 -5
  104. package/dist/xstate-dev.development.cjs.js +0 -51
  105. package/dist/xstate-dev.development.cjs.mjs +0 -5
  106. package/dist/xstate-dev.development.esm.js +0 -45
  107. package/dist/xstate-dev.esm.js +0 -42
  108. package/dist/xstate-dev.umd.min.js +0 -2
  109. package/dist/xstate-dev.umd.min.js.map +0 -1
  110. package/dist/xstate-guards.cjs.d.mts +0 -2
  111. package/dist/xstate-guards.cjs.d.ts +0 -2
  112. package/dist/xstate-guards.cjs.js +0 -14
  113. package/dist/xstate-guards.cjs.mjs +0 -7
  114. package/dist/xstate-guards.development.cjs.js +0 -14
  115. package/dist/xstate-guards.development.cjs.mjs +0 -7
  116. package/dist/xstate-guards.development.esm.js +0 -2
  117. package/dist/xstate-guards.esm.js +0 -2
  118. package/dist/xstate-guards.umd.min.js +0 -2
  119. package/dist/xstate-guards.umd.min.js.map +0 -1
@@ -1,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).XStateGraph={})}(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){return{type:s,input:t}}function c(t){setTimeout(()=>{throw t})}const h="function"==typeof Symbol&&Symbol.observable||"@@observable";function u(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&&u(s[t],n[t]))}function f(t){if(v(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(It(t))return t.value;if("string"!=typeof t)return t;return function(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}(f(t))}function d(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 l(t){return v(t)?t:[t]}function y(t){return void 0===t?[]:l(t)}function g(t,e,s,n){return"function"==typeof t?t({context:e,event:s,self:n}):t}function v(t){return Array.isArray(t)}function m(t){return l(t).map(t=>void 0===t||"string"==typeof t?{target:t}:t)}function _(t){if(void 0!==t&&""!==t)return y(t)}function S(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 x(t,e){return`${e}.${t}`}function w(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 b(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]}function E(t,e){return`${t.sessionId}.${e}`}let $=0;let k=!1;let I=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 j{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=I.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:h,systemId:u,inspect:f}=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,h={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);u._snapshot._scheduledEvents[c]=i;const h=a.setTimeout(()=>{delete r[c],delete u._snapshot._scheduledEvents[c],u._relay(t,e,s)},n);r[c]=h},cancel:(t,e)=>{const s=E(t,e),n=r[s];delete r[s],delete u._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in u._snapshot._scheduledEvents){const s=u._snapshot._scheduledEvents[e];s.source===t&&h.cancel(t,s.id)}}},u={_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=S(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)=>{u._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:e,event:s}),e._send(s)},scheduler:h,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{const t=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];h.schedule(s,n,o,i,r)}},_clock:a,_logger:c};return u}(this,{clock:o,logger:i}),f&&!r&&this.system.inspect(S(f)),this.sessionId=this.system._bookId(),this.id=h??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){c(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=k;try{k=!0,t.exec(t.info,t.params)}finally{k=e}};this._processingStatus===I.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),u&&(this.systemId=u,this.system._set(u,this)),this._initState(s?.snapshot??s?.state),u&&"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){c(t)}break;case"done":for(const e of this.observers)try{e.next?.(t)}catch(t){c(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=S(t,e,s);if(this._processingStatus!==I.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){c(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){c(t)}else c(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)}}}select(t,e=Object.is){return{subscribe:s=>{const n=S(s),o=this.getSnapshot();let i=t(o);return this.subscribe(s=>{const o=t(s);e(i,o)||(i=o,n.next?.(o))})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===I.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=I.Running;const t=a(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===I.Stopped?this:(this.mailbox.clear(),this._processingStatus===I.NotStarted?(this._processingStatus=I.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){c(t)}this.observers.clear(),this.eventListeners.clear()}_reportError(t){if(!this.observers.size)return this._parent||c(t),void this.eventListeners.clear();let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){c(t)}}this.observers.clear(),this.eventListeners.clear(),e&&c(t)}_error(t){var e;this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${e=this.id}`,error:t,actorId:e})}_stopProcedure(){return this._processingStatus!==I.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this._processingStatus=I.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==I.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 T(t,...[e]){return new j(t,e)}function M(t,e,s,n,{sendId:o}){return[e,{sendId:"function"==typeof o?o(s,n):o},void 0]}function N(t,e){t.defer(()=>{t.system.scheduler.cancel(t.self,e.sendId)})}function P(t,e,s,n,{id:o,systemId:i,src:r,input:a,syncSnapshot:c}){const h="string"==typeof r?w(e.machine,r):r,u="function"==typeof o?o(s):o;let f,p;return h&&(p="function"==typeof a?a({context:e.context,event:s.event,self:t.self}):a,f=T(h,{id:u,src:r,parent:t.self,syncSnapshot:c,systemId:i,input:p})),[zt(e,{children:{...e.children,[u]:f}}),{id:o,systemId:i,actorRef:f,src:r,input:p},void 0]}function z(t,{actorRef:e}){e&&t.defer(()=>{e._processingStatus!==I.Stopped&&e.start()})}function A(...[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=P,i.execute=z,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]),[zt(e,{children:a}),r,void 0]}function R(t,e){const s=e.getSnapshot();if(s&&"children"in s)for(const e of Object.values(s.children))R(t,e);t.system._unregister(e)}function D(t,e){e&&(R(t,e),e._processingStatus===I.Running?t.defer(()=>{t.stopChild(e)}):t.stopChild(e))}function C(t){function e(t,e){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=J,e.execute=D,e}function B(t,{context:e,event:s},{guards:n}){return n.every(n=>V(n,e,s,t))}function L(t){function e(t,e){return!1}return e.check=B,e.guards=t,e}function V(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 V(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)}function q(t){return"atomic"===t.type||"final"===t.type}function W(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function G(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 F(t){const e=new Set(t),s=K(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 W(t))if("history"!==s.type&&!e.has(s)){const t=st(s);for(const s of t)e.add(s)}}else st(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 U(t,e){const s=e.get(t);if(!s)return{};if("compound"===t.type){const t=s[0];if(!t)return{};if(q(t))return t.key}const n={};for(const t of s)n[t.key]=U(t,e);return n}function K(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 Q(t,e){return U(t,K(F(e)))}function X(t,e){return"compound"===e.type?W(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?W(e).every(e=>X(t,e)):"final"===e.type}const H=t=>"#"===t[0];function Y(t){const e=t.config.after;if(!e)return[];const s=e=>{const s=(n=e,o=t.id,{type:`xstate.after.${n}.${o}`});var n,o;const i=s.type;return t.entry.push(function(t,e){function s(t,e){}return s.type="xstate.raise",s.event=t,s.id=e?.id,s.delay=e?.delay,s.resolve=Bt,s.execute=Lt,s}(s,{id:i,delay:e})),t.exit.push(function(t){function e(t,e){}return e.type="xstate.cancel",e.sendId=t,e.resolve=M,e.execute=N,e}(i)),i};return Object.keys(e).flatMap(t=>{const n=e[t],o="string"==typeof n?{target:n}:n,i=Number.isNaN(+t)?t:+t,r=s(i);return y(o).map(t=>({...t,event:r,delay:i}))}).map(e=>{const{delay:s}=e;return{...Z(t,e.event,e),delay:s}})}function Z(t,e,s){const n=_(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(H(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return it(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 it(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}(t,n),r={...s,actions:y(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 tt(t){const e=_(t.config.target);return e?{target:e.map(e=>"string"==typeof e?it(t.parent,e):e)}:t.parent.initial}function et(t){return"history"===t.type}function st(t){const e=nt(t);for(const s of e)for(const n of G(s,t))e.add(n);return e}function nt(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 W(s))t(e)}(t),e}function ot(t,e){if(H(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 it(t,e){if("string"==typeof e&&H(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=ot(n,t)}return n}function rt(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=>ot(t,e)).filter(Boolean);return[t.machine.root,t].concat(n,s.reduce((s,n)=>{const o=ot(t,n);if(!o)return s;const i=rt(o,e[n]);return s.concat(i)},[]))}function at(t,e,s,n){return"string"==typeof e?function(t,e,s,n){const o=ot(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=at(ot(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=at(ot(t,i),r,s,n);a&&o.push(...a)}return o.length?o:t.next(s,n)}(t,e,s,n)}function ct(t){return Object.keys(t.states).map(e=>t.states[e]).filter(t=>"history"===t.type)}function ht(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function ut(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 ft(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(ut(lt([o],e,s),lt([r],e,s))){if(!ht(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 pt(t,e){if(!t.target)return[];const s=new Set;for(const n of t.target)if(et(n))if(e[n.id])for(const t of e[n.id])s.add(t);else for(const t of pt(tt(n),e))s.add(t);else s.add(n);return[...s]}function dt(t,e){const s=pt(t,e);if(!s)return;if(!t.reenter&&s.every(e=>e===t.source||ht(e,t.source)))return t.source;const n=function(t){const[e,...s]=t;for(const t of G(e,void 0))if(s.every(e=>ht(e,t)))return t}(s.concat(t.source));return n||(t.reenter?void 0:t.source.machine.root)}function lt(t,e,s){const n=new Set;for(const o of t)if(o.target?.length){const t=dt(o,s);o.reenter&&o.source===t&&n.add(t);for(const s of e)ht(s,t)&&n.add(s)}return[...n]}function yt(t,e,s,n,o,i){const a=[];if(!t.length)return[e,a];const c=s.actionExecutor;s.actionExecutor=t=>{a.push(t),c(t)};try{const c=new Set(e._nodes);let h=e.historyValue;const u=ft(t,c,h);let f=e;o||([f,h]=function(t,e,s,n,o,i,r){let a=t;const c=lt(n,o,i);let h;c.sort((t,e)=>e.order-t.order);for(const t of c)for(const e of ct(t)){let s;s="deep"===e.history?e=>q(e)&&ht(e,t):e=>e.parent===t,h??={...i},h[e.id]=Array.from(o).filter(s)}for(const t of c)a=wt(a,e,s,[...t.exit,...t.invoke.map(t=>C(t.id))],r,void 0),o.delete(t);return[a,h||i]}(f,n,s,u,c,h,i,s.actionExecutor)),f=wt(f,n,s,u.flatMap(t=>t.actions),i,void 0),f=function(t,e,s,n,o,i,a,c){let h=t;const u=new Set,f=new Set;(function(t,e,s,n){for(const o of t){const t=dt(o,e);for(const i of o.target||[])et(i)||o.source===i&&o.source===t&&!o.reenter||(n.add(i),s.add(i)),vt(i,e,s,n);const i=pt(o,e);for(const r of i){const i=G(r,t);"parallel"===t?.type&&i.push(t),mt(n,e,s,i,!o.source.parent&&o.reenter?void 0:t)}}})(n,a,f,u),c&&f.add(t.machine.root);const p=new Set;for(const t of[...u].sort((t,e)=>t.order-e.order)){o.add(t);const n=[];n.push(...t.entry);for(const e of t.invoke)n.push(A(e.src,{...e,syncSnapshot:!!e.onSnapshot}));if(f.has(t)){const e=t.initial.actions;n.push(...e)}if(h=wt(h,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?g(t.output,h.context,e,s.self):void 0));"parallel"===a?.type&&!p.has(a)&&X(o,a);)p.add(a),i.push(r(a.id)),c=a,a=a.parent;if(a)continue;h=zt(h,{status:"done",output:gt(h,e,s,h.machine.root,c)})}}return h}(f,n,s,u,c,i,h,o);const p=[...c];"done"===f.status&&(f=wt(f,n,s,p.sort((t,e)=>e.order-t.order).flatMap(t=>t.exit),i,void 0));try{return h===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,c)?[f,a]:[zt(f,{_nodes:p,historyValue:h}),a]}catch(t){throw t}}finally{s.actionExecutor=c}}function gt(t,e,s,n,o){if(void 0===n.output)return;const i=r(o.id,void 0!==o.output&&o.parent?g(o.output,t.context,e,s.self):void 0);return g(n.output,t.context,i,s.self)}function vt(t,e,s,n){if(et(t))if(e[t.id]){const o=e[t.id];for(const t of o)n.add(t),vt(t,e,s,n);for(const i of o)_t(i,t.parent,n,e,s)}else{const o=tt(t);for(const i of o.target)n.add(i),o===t.parent?.initial&&s.add(t.parent),vt(i,e,s,n);for(const i of o.target)_t(i,t.parent,n,e,s)}else if("compound"===t.type){const[o]=t.initial.target;et(o)||(n.add(o),s.add(o)),vt(o,e,s,n),_t(o,t,n,e,s)}else if("parallel"===t.type)for(const o of W(t).filter(t=>!et(t)))[...n].some(t=>ht(t,o))||(et(o)||(n.add(o),s.add(o)),vt(o,e,s,n))}function mt(t,e,s,n,o){for(const i of n)if(o&&!ht(i,o)||t.add(i),"parallel"===i.type)for(const n of W(i).filter(t=>!et(t)))[...t].some(t=>ht(t,n))||(t.add(n),vt(n,e,s,t))}function _t(t,e,s,n,o){mt(s,n,o,G(t,e))}function St(t,e){return t.implementations.actions[e]}function xt(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:St(r,"string"==typeof t?t:t.type),h={context:a.context,event:e,self:s.self,system:s.system},u=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:h,params:u,exec:c});continue}const f=c,[p,d,l]=f.resolve(s,a,h,u,c,o);a=p,"retryResolve"in f&&i?.push([f,d]),"execute"in f&&s.actionExecutor({type:f.type,info:h,params:d,exec:f.execute.bind(null,s,d)}),l&&(a=xt(a,e,s,l,o,i))}return a}function wt(t,e,s,n,o,i){const r=i?[]:void 0,a=xt(t,e,s,n,{internalQueue:o,deferredActorIds:i},r);return r?.forEach(([t,e])=>{t.retryResolve(s,a,e)}),a}function bt(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[0],_transitions:s}),a.push(t)}if(e.type===n)return r=zt(Et(r,e,o),{status:"stopped"}),c([r,[]],e,[]),{snapshot:r,microsteps:a};let h=e;if(h.type!==s){const e=h,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),n=$t(e,r);if(s&&!n.length)return r=zt(t,{status:"error",error:e.error}),c([r,[]],e,[]),{snapshot:r,microsteps:a};const u=yt(n,t,o,h,!1,i);r=u[0],c(u,e,n)}let u=!0;const f=t.machine.options?.maxIterations??1/0;let p=0;for(;"active"===r.status;){if(p++,p>f)throw new Error(`Infinite loop detected: the machine has processed more than ${f} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).`);let t=u?kt(r,h):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;h=i.shift(),t=$t(h,r)}const s=yt(t,r,o,h,!1,i);r=s[0],u=r!==e,c(s,h,t)}return"active"!==r.status&&Et(r,h,o),{snapshot:r,microsteps:a}}function Et(t,e,s){return wt(t,e,s,Object.values(t.children).map(t=>C(t)),[],void 0)}function $t(t,e){return e.machine.getTransitionData(e,t)}function kt(t,e){const s=new Set,n=t._nodes.filter(q);for(const o of n)t:for(const n of[o].concat(G(o,void 0)))if(n.always)for(const o of n.always)if(void 0===o.guard||V(o.guard,t.context,e,t)){s.add(o);break t}return ft(Array.from(s),new Set(t._nodes),t.historyValue)}function It(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const Ot=function(t){return u(t,this.value)},jt=function(t){return this.tags.has(t)},Tt=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some(t=>void 0!==t.target||t.actions.length)},Mt=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)}},Nt=function(){return this._nodes.reduce((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t),{})};function Pt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:Q(e.root,t._nodes),tags:new Set(t._nodes.flatMap(t=>t.tags)),children:t.children,historyValue:t.historyValue||{},matches:Ot,hasTag:jt,can:Tt,getMeta:Nt,toJSON:Mt}}function zt(t,e={}){return Pt({...t,...e},t.machine)}function At(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 Jt(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=Jt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function Rt(t,{machine:e,context:s},n,o){return(i,r)=>{const a=((i,r)=>{if("string"==typeof i){const a=w(e,i);if(!a)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const c=T(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 T(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!==I.Stopped&&a.start()}),a}}function Dt(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:Rt(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[zt(e,{context:Object.assign({},e.context,a),children:Object.keys(i).length?{...e.children,...i}:e.children}),void 0,void 0]}function Ct(t){function e(t,e){}return e.type="xstate.assign",e.assignment=t,e.resolve=Dt,e}function Bt(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 h="function"==typeof o?o(s,n):o;let u;if("string"==typeof r){const t=c&&c[r];u="function"==typeof t?t(s,n):t}else u="function"==typeof r?r(s,n):r;return"number"!=typeof u&&a.push(h),[e,{event:h,id:i,delay:u},void 0]}function Lt(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)})}const Vt=(Wt=void 0,{config:qt=t=>{},transition:(t,e,s)=>({...t,context:qt(t.context,e,s)}),getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof Wt?Wt({input:e}):Wt}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t});var qt,Wt;const Gt=new WeakMap;function Ft(t,e,s){let n=Gt.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Gt.set(t,n)),n[e]}const Ut={},Kt=t=>"string"==typeof t?{type:t}:"function"==typeof t?"resolve"in t?{type:t.type}:{type:t.name}:t;class Qt{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?d(this.config.states,(t,e)=>new Qt(t,{_parent:this,_key:e,_machine:this.machine})):Ut,"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=y(this.config.entry).slice(),this.exit=y(this.config.exit).slice(),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=y(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,m(n).map(e=>Z(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,m(t.config.onDone).map(e=>Z(t,s,e)))}for(const s of t.invoke){if(s.onDone){const n=`xstate.done.actor.${s.id}`;e.set(n,m(s.onDone).map(e=>Z(t,n,e)))}if(s.onError){const n=`xstate.error.actor.${s.id}`;e.set(n,m(s.onError).map(e=>Z(t,n,e)))}if(s.onSnapshot){const n=`xstate.snapshot.${s.id}`;e.set(n,m(s.onSnapshot).map(e=>Z(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=m(this.config.always).map(t=>Z(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(Kt),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Kt),eventType:null})}:void 0,history:this.history,states:d(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(Kt)})),entry:this.entry.map(Kt),exit:this.exit.map(Kt),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 Ft(this,"invoke",()=>y(this.config.invoke).map((t,e)=>{const{src:s,systemId:n}=t,o=t.id??x(this.id,e),i="string"==typeof s?s:`xstate.invoke.${x(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 Ft(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 Ft(this,"delayedTransitions",()=>Y(this))}get initial(){return Ft(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?y(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=Ft(this,`candidates-${s}`,()=>{return e=s,(t=this).transitions.get(e)||[...t.transitions.keys()].filter(t=>function(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}(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||V(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 Ft(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 Xt{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=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.options={maxIterations:1/0,...this.config.options},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 Qt(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const s=n.config.id,o=n.config.route.guard,i=({event:t})=>t.to===`#${s}`,r={...n.config.route,guard:o?L([i,o]):i,target:`#${s}`};e.push(Z(t,"xstate.route",r))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),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 Xt(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,Q(s,[...F(rt(s,n))]));var s,n;const o=F(rt(this.root,e));return Pt({_nodes:[...o],context:t.context||{},children:{},status:X(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return bt(t,e,s,[]).snapshot}microstep(t,e,s){return bt(t,e,s,[]).microsteps.map(([t])=>t)}getTransitionData(t,e){return at(this.root,t.value,t,e)||[]}_getPreInitialState(t,e,s){const{context:n}=this.config,o=Pt({context:"function"!=typeof n&&n?n:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof n){return wt(o,e,t,[Ct(({spawn:t,event:e,self:s})=>n({spawn:t,input:e.input,self:s}))],s,void 0)}return o}getInitialSnapshot(t,e){const s=a(e),n=[],o=this._getPreInitialState(t,s,n),[i]=function(t,e,s,n,o){return yt([{target:[...nt(t)],source:t,reenter:!0,actions:[],eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,o,t,s,n),{snapshot:r}=bt(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=H(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 it(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:h,getMeta:u,toJSON:f,...p}=t,d={};for(const t in i){const s=i[t];d[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s.systemId,syncSnapshot:s._syncSnapshot}}return{...p,context:Jt(r),children:d,historyValue:At(p.historyValue)}}(t,e)}restoreSnapshot(t,e){const s={},n=t.children;function o(t,e){if(e instanceof Qt)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?w(this,r):r;if(!a)return;const c=T(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=Pt({...t,children:s,_nodes:Array.from(F(rt(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 Ht(t){return JSON.stringify(t)}function Yt(t){const e=Object.keys(t.context).length?`(${JSON.stringify(t.context)})`:"",s=t._nodes.filter(t=>"atomic"===t.type||"final"===t.type).map(({id:e,path:s})=>{const n=t.getMeta()[e];if(!n)return`"${s.join(".")}"`;const{description:o}=n;return"function"==typeof o?o(t):o?`"${o}"`:JSON.stringify(t.value)});return`state${1===s.length?"":"s"} `+s.join(", ")+` ${e}`.trim()}const Zt=()=>(t,e)=>ge(t,e),te=()=>(t,e)=>ve(t,e),ee=t=>{if(t.invoke.length>0)throw new Error("Invocations on test machines are not supported");if(t.after.length>0)throw new Error("After events on test machines are not supported");[...t.entry,...t.exit,...[...t.transitions.values()].flatMap(t=>t.flatMap(t=>t.actions))].forEach(t=>{if("function"==typeof t&&"resolve"in t&&"number"==typeof t.delay)throw new Error("Delayed actions on test machines are not supported")});for(const e of Object.values(t.states))ee(e)};class se{getDefaultOptions(){return{serializeState:t=>Ht(t),serializeEvent:t=>Ht(t),serializeTransition:(t,e)=>`${Ht(t)}|${e?.type}`,events:[],stateMatcher:(t,e)=>"*"===e,logger:{log:console.log.bind(console),error:console.error.bind(console)}}}constructor(t,e){this.testLogic=t,this.options=void 0,this.defaultTraversalOptions=void 0,this._toTestPath=t=>{const e=t.steps.map(t=>function(t){const{type:e,...s}=t;return`${e}${Object.keys(s).length?` (${JSON.stringify(s)})`:""}`}(t.event)).join(" → ");return{...t,test:e=>this.testPath(t,e),description:It(t.state)?`Reaches ${Yt(t.state).trim()}: ${e}`:JSON.stringify(t.state)}},this.options={...this.getDefaultOptions(),...e}}getPaths(t,e){const s=e?.allowDuplicatePaths??!1,n=t(this.testLogic,this._resolveOptions(e));return(s?n:((t,e=Ht)=>{const s=[];t.forEach(t=>{s.push({path:t,eventSequence:t.steps.map(t=>e(t.event))})}),s.sort((t,e)=>e.path.steps.length-t.path.steps.length);const n=[];t:for(const t of s){e:for(const e of n){for(const s in t.eventSequence)if(t.eventSequence[s]!==e.eventSequence[s])continue e;continue t}n.push(t)}return n.map(t=>t.path)})(n)).map(this._toTestPath)}getShortestPaths(t){return this.getPaths(Zt(),t)}getShortestPathsFrom(t,e){const s=[];for(const n of t){const t=this.getShortestPaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(pe(n,e)))}return s}getSimplePaths(t){return this.getPaths(te(),t)}getSimplePathsFrom(t,e){const s=[];for(const n of t){const t=this.getSimplePaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(pe(n,e)))}return s}getPathsFromEvents(t,e){return ye(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return de(this.testLogic,this.options)}async testPath(t,e,s){const n={steps:[],state:{error:null}};try{for(const o of t.steps){const t={step:o,state:{error:null},event:{error:null}};n.steps.push(t);try{await this.testTransition(e,o)}catch(e){throw t.event.error=e,e}try{await this.testState(e,o.state,s)}catch(e){throw t.state.error=e,e}}}catch(e){throw e.message+=function(t,e,s){const n={formatColor:(t,e)=>e,serializeState:Ht,serializeEvent:Ht,...s},{formatColor:o,serializeState:i,serializeEvent:r}=n,{state:a}=t,c=i(a,t.steps.length?t.steps[t.steps.length-1].event:void 0);let h="",u=!1;return h+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=i(t.step.state,e>0?s[e-1].step.event:void 0),a=r(t.step.event);return[`\tState: ${u?o("gray",n):t.state.error?(u=!0,o("redBright",n)):o("greenBright",n)}`,`\tEvent: ${u?o("gray",a):t.event.error?(u=!0,o("red",a)):o("green",a)}`].join("\n")}).concat(`\tState: ${u?o("gray",c):e.state.error?o("red",c):o("green",c)}`).join("\n\n"),h}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),o=this._getStateTestKeys(t,e,n);for(const s of o)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},o=Object.keys(n).filter(t=>s.stateMatcher(e,t));return!o.length&&"*"in n&&o.push("*"),o}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function ne(t,e){if(t===e)return!0;if(void 0===t||void 0===e)return!1;if("string"==typeof t||"string"==typeof e)return t===e;const s=Object.keys(t),n=Object.keys(e);return s.length===n.length&&s.every(s=>ne(t[s],e[s]))}function oe(t,e,s,{serializeEvent:n}){if(!e||s&&ne(s.value,t.value))return"";const o=s?` from ${Ht(s.value)}`:"";return` via ${n(e)}${o}`}function ie(){const t=T(Vt);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function re(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function ae(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function ce(t){return JSON.stringify(t)}function he(t,e){const{events:s,...n}=e??{};return{serializeState:ae,serializeEvent:ce,events:t=>{const e="function"==typeof s?s(t):s??[];return b(t).flatMap(t=>{const s=e.filter(e=>e.type===t);return s.length?s:[{type:t}]})},fromState:t.getInitialSnapshot(ie(),e?.input),...n}}function ue(){return{serializeState:t=>JSON.stringify(t),serializeEvent:ce}}function fe(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?he(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:ce,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function pe(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}}function de(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:i,filterEvents:r,limit:a,fromState:c,stopWhen:h}=fe(t,e),u=ie(),f={};let p=0;const d=[{nextState:c??t.getInitialSnapshot(u,e.input),event:void 0,prevState:void 0}],l=new Map;for(;d.length;){const{nextState:t,event:e,prevState:c}=d.shift();if(p++>a)throw new Error("Traversal limit exceeded");const y=o(t,e,c);if(f[y])continue;if(l.set(y,t),f[y]={state:t,transitions:{}},h&&h(t))continue;const g="function"==typeof i?i(t):i;for(const e of g){if(r&&!r(t,e))continue;const o=s(t,e,u);f[y].transitions[n(e)]={event:e,state:o},d.push({nextState:o,event:e,prevState:t})}}return f}function le(t){let e=[];if(t.steps.length){for(let s=0;s<t.steps.length;s++){const n=t.steps[s];e.push({state:n.state,event:0===s?{type:"xstate.init"}:t.steps[s-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:"xstate.init"}}];return{...t,steps:e}}function ye(t,e,s){const n=fe(t,{events:e,...s},(o=t)&&"__xstatenode"in o?he(t):ue());var o;const i=ie(),r=n.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:a,serializeEvent:c}=n,h=de(t,n),u=new Map,f=[],p=a(r,void 0,void 0);u.set(p,r);let d=p,l=r;for(const t of e){f.push({state:u.get(d),event:t});const e=c(t),{state:s,event:n}=h[d].transitions[e];if(!s)throw new Error(`Invalid transition from ${d} with ${e}`);const o=a(s,t,u.get(d));u.set(o,s),d=o,l=s}return n.toState&&!n.toState(l)?[]:[le({state:l,steps:f,weight:f.length})]}function ge(t,e){const s=fe(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(ie(),e?.input),i=de(t,s),r=new Map,a=new Map,c=n(o,void 0,void 0);a.set(c,o),r.set(c,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(c);for(const t of h){const e=a.get(t),{weight:s}=r.get(t);for(const o of Object.keys(i[t].transitions)){const{state:c,event:f}=i[t].transitions[o],p=n(c,f,e);if(a.set(p,c),r.has(p)){const{weight:e}=r.get(p);e>s+1&&r.set(p,{weight:s+1,state:t,event:f})}else r.set(p,{weight:s+1,state:t,event:f});u.has(p)||h.add(p)}u.add(t),h.delete(t)}const f={},p=[];return r.forEach(({weight:t,state:e,event:s},n)=>{const o=a.get(n),i=e?f[e].paths[0].steps.concat({state:a.get(e),event:s}):[];p.push({state:o,steps:i,weight:t}),f[n]={state:o,paths:[{state:o,steps:i,weight:t}]}}),s.toState?p.filter(t=>s.toState(t.state)).map(le):p.map(le)}function ve(t,e){const s=fe(t,e),n=ie(),o=s.fromState??t.getInitialSnapshot(n,e?.input),i=s.serializeState,r=de(t,s),a=new Map,c={vertices:new Set,edges:new Set},h=[],u={};function f(t,e){const s=a.get(t);if(c.vertices.add(t),t===e){u[e]||(u[e]={state:a.get(e),paths:[]});const t=u[e],n={state:s,weight:h.length,steps:[...h]};t.paths.push(n)}else for(const s of Object.keys(r[t].transitions)){const{state:n,event:o}=r[t].transitions[s];if(!(s in r[t].transitions))continue;const u=a.get(t),p=i(n,o,u);a.set(p,n),c.vertices.has(p)||(c.edges.add(s),h.push({state:a.get(t),event:o}),f(p,e))}h.pop(),c.vertices.delete(t)}const p=i(o,void 0);a.set(p,o);for(const t of Object.keys(r))f(p,t);const d=Object.values(u).flatMap(t=>t.paths);return s.toState?d.filter(t=>s.toState(t.state)).map(le):d.map(le)}t.TestModel=se,t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.createShortestPathsGen=Zt,t.createSimplePathsGen=te,t.createTestModel=function(t,e){(t=>{ee(t.root)})(t);const s=e?.serializeEvent??Ht,n=e?.serializeTransition??oe,{events:o,...i}=e??{};return new se(t,{serializeState:(t,e,o)=>`${ae(t)}${n(t,e,o,{serializeEvent:s})}`,stateMatcher:(e,s)=>s.startsWith("#")?e._nodes.includes(t.getStateNodeById(s)):e.matches(s),events:t=>{const e="function"==typeof o?o(t):o??[];return b(t).flatMap(t=>e.some(e=>e.type===t)?e.filter(e=>e.type===t):[{type:t}])},...i})},t.getAdjacencyMap=de,t.getPathsFromEvents=ye,t.getShortestPaths=ge,t.getSimplePaths=ve,t.getStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,n)=>{const o=s[n],i=t(o);return e.push(o,...i),e},[])},t.joinPaths=pe,t.serializeSnapshot=ae,t.toDirectedGraph=function t(e){const s=e instanceof Xt?e.root:e,n=[...s.transitions.values()].flat().flatMap((t,e)=>(t.target?t.target:[s]).map((n,o)=>{const i={id:`${s.id}:${e}:${o}`,source:s,target:n,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=i;return{source:s.id,target:n.id,label:t}}};return i})),o={id:s.id,stateNode:s,children:re(s).map(t),edges:n,toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s}}};return o},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).XStateGraph={})}(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(t){return{type:`xstate.timeout.actor.${t}`}}function i(t,e){return{type:`xstate.done.state.${t}`,output:e}}function r(t){return{type:s,input:t}}function c(t){setTimeout(()=>{throw t})}const a="function"==typeof Symbol&&Symbol.observable||"@@observable",h={"@xstate.start":t=>{t.start()},"@xstate.raise":(t,e,s)=>{t.system.scheduler.schedule(t.self,t.self,e,s?.delay??0,s?.id)},"@xstate.sendTo":(t,e,s,n)=>{if("string"==typeof s)throw new Error("Only event objects may be used with sendTo");void 0!==n?.delay?t.system.scheduler.schedule(t.self,e,s,n?.delay??0,n?.id):t.defer(()=>{t.system._relay(t.self,e,s)})},"@xstate.cancel":(t,e)=>{t.system.scheduler.cancel(t.self,e)},"@xstate.stopChild":(t,e)=>{t.stopChild(e)}},u=new WeakMap;function f(t){return{start:(e,{self:s,system:n})=>{const o=e.input.actor;if(!o||"function"==typeof o.getSnapshot&&"stopped"===o.getSnapshot().status)return;const i=t(e.input,{self:s,system:n});if(!i)return;let r,c=!1;const a=()=>{c||(c=!0,i.unsubscribe(),r?.unsubscribe())},h=s._parent;h&&(r=h.subscribe({complete:a,error:a})),u.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===n?(u.get(s)?.unsubscribe(),u.delete(s),{...t,status:"stopped",error:void 0}):t,getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function p(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function d(){return f(({actor:t,eventType:e,mapper:s},{self:n,system:o})=>{const i="*"!==e&&e.endsWith(".*");return t.on(i?"*":e,t=>{i&&!Mt(t.type,e)||p(n,o,()=>s(t))})})}const l=d(),y=Symbol.for("xstate.atom");function g(){return f(({actor:t,mappers:e},{self:s,system:n})=>{const{done:o,error:i,snapshot:r}=e;if((c=t)&&"object"==typeof c&&y in c){if(!r)return;return t.subscribe(t=>p(s,n,()=>r(t)))}var c;return t.subscribe({next:t=>{"done"===t.status&&o?p(s,n,()=>o(t.output)):"error"===t.status&&i?p(s,n,()=>i(t.error)):"active"===t.status&&r&&p(s,n,()=>r(t))},error:t=>{i&&p(s,n,()=>i(t))},complete:()=>{}})})}const v=g();function m(t,e,...s){t.push({action:e,args:s})}function _(t,e,s){m(t,h["@xstate.start"],e),t.push(function(t,e){return Object.assign(function(s){return{children:{...s.children,[e]:t}}},{_special:!0})}(e,s??e.id))}function S(t,e,s,n=!1){const o={cancel:s=>{m(e,h["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{m(e,t.logger,...s)},raise:(n,o)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0!==o?.delay?m(e,h["@xstate.raise"],t,n,o):s.push(n)},spawn:(s,n)=>{const o=Wt(s,{...n,parent:t.self});return _(e,o,n?.id),o},sendTo:(s,n,o)=>{s&&m(e,h["@xstate.sendTo"],t,s,n,o)},stop:s=>{s&&(m(e,h["@xstate.stopChild"],t,s),e.push(function(t){return Object.assign(function(e){const s={...e.children};for(const e of Object.keys(s))s[e]===t&&delete s[e];return{children:s}},{_special:!0})}(s)))}};return n&&Object.assign(o,{listen:(s,n,o)=>{const i=Wt(l,{input:{actor:s,eventType:n,mapper:o},parent:t.self});return m(e,h["@xstate.start"],i),i},subscribeTo:(s,n)=>{const o=Wt(v,{input:{actor:s,mappers:"function"==typeof n?{snapshot:n}:n},parent:t.self});return m(e,h["@xstate.start"],o),o}}),b(o,(t,...s)=>{m(e,t,...s)})}function x(t,e,s,n){let o=t;for(const i of n){const n="function"==typeof i?i:"object"==typeof i&&"action"in i&&"function"==typeof i.action&&i.action.bind(null,...i.args);n||"object"!=typeof i||null===i||s.defer(()=>{s.emit(i)});const r={context:o.context,event:e,self:s.self,system:s.system,children:o.children,parent:s.self._parent,actions:t.machine.implementations.actions,actors:t.machine.implementations.actors};let c;if("object"==typeof i&&null!==i){const{type:t,...e}=i;c=e}if(n&&"_special"in n){s.actionExecutor({type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type??"(anonymous)":i.name||"(anonymous)",params:c,args:[],exec:void 0});const t=n(r,w);t&&("context"in t||"children"in t)&&(o=gt(o,{..."context"in t?{context:t.context}:{},..."children"in t?{children:t.children}:{}}));continue}n&&"resolve"in n||s.actionExecutor({type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type:i.name||"(anonymous)",params:c,args:"object"==typeof i&&"action"in i?i.args:[],exec:n})}return o}function b(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),s}const w=b({},()=>{});function E(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const n=e.match(/^(\d*)(\.?)(\d*)s$/i);if(n){const t=n[1]?parseInt(n[1],10):0,e=!!n[2],s=n[3]?parseInt(n[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:i,days:r,hours:c,minutes:a,seconds:h}=o.groups;if(!(i||r||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(i)*24*60*60*1e3+24*u(r)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)??t}function $(t,e,s){if("function"==typeof t)return t(s);const n=E(t,e);return"function"==typeof n?n(s):n}function k(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function I(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function j(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 O(t){const e=new Set(t),s=new Set;for(const t of e)t.parent&&s.add(t.parent);for(const t of e)if("compound"!==t.type||s.has(t)){if("parallel"===t.type)for(const s of I(t))if(!e.has(s)){const t=R(s);for(const s of t)e.add(s)}}else for(const s of R(t))e.add(s);for(const t of e){let s=t.parent;for(;s&&!e.has(s);)e.add(s),s=s.parent}return e}function T(t,e){const s=O(e),n=new Map;for(const t of s)n.has(t)||n.set(t,[]),t.parent&&(n.has(t.parent)||n.set(t.parent,[]),n.get(t.parent).push(t));const o=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(k(t))return t.key}const s={};for(const t of e)s[t.key]=o(t);return s};return o(t)}function M(t,e){return"compound"===e.type?I(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?I(e).every(e=>M(t,e)):"final"===e.type}const A=t=>"#"===t[0];function P(t,e,s){const n=e.type,o=t.entry;t.entry=(t,i)=>(i.raise(e,{id:n,delay:s(t)}),"function"==typeof o?o(t,i):void 0);const i=t.exit;return t.exit=(t,e)=>(e.cancel(n),"function"==typeof i?i(t,e):void 0),n}function N(t,e,s){const n=It(s.target),o=s.reenter??!1,i=z(t,n),r={...s,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 z(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(A(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return B(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return B(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}function D(t){const e=It(t.config.target);return e?{target:e.map(e=>"string"==typeof e?B(t.parent,e):e),source:t,reenter:!1,eventType:""}:t.parent.initial}function J(t){return"history"===t.type}function R(t){const e=new Set;!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 I(s))t(e)}(t);for(const s of e)for(const n of j(s,t))e.add(n);return e}function C(t,e){if(A(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 B(t,e){if("string"==typeof e&&A(e))try{return t.machine.getStateNodeById(e)}catch{}const s=St(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=C(n,t)}return n}function V(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=new Array(s.length),o=[t.machine.root,t];for(let e=0;e<s.length;e++){const i=C(t,s[e]);n[e]=i,o.push(i)}for(let t=0;t<s.length;t++)o.push(...V(n[t],e[s[t]]));return o}function L(t,e,s,n,o){if("string"==typeof e){const i=C(t,e).next(s,n,o);return i&&i.length?i:t.next(s,n,o)}const i=Object.keys(e),r=i[0];if(1===i.length){const i=L(C(t,r),e[r],s,n,o);return i&&i.length?i:t.next(s,n,o)}const c=[];for(const r of i){const i=e[r];if(!i)continue;const a=L(C(t,r),i,s,n,o);a&&c.push(...a)}return c.length?c:t.next(s,n,o)}function W(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function q(t,e){for(const s of t)if(W(s,e))return!0;return!1}function G(t,e){const s=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,n=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==s&&void 0!==n&&n<s&&([t,e]=[e,t]);const o=t instanceof Set?t:new Set(t);for(const t of e)if(o.has(t))return!0;return!1}function F(t,e,s,n,o){const i=new Set,r=new Map,c=t=>{let i=r.get(t);return i||(i=H([t],e,s,n,o),r.set(t,i)),i};for(const e of t){let t=!1;const s=new Set;for(const n of i)if(G(c(e),c(n))){if(!W(e.source,n.source)){t=!0;break}s.add(n)}if(!t){for(const t of s)i.delete(t);i.add(e)}}return Array.from(i)}function K(t,e,s,n){const o=e.historyValue,{targets:i}=Q(t,e,s,n);if(!i)return[];const r=new Set;for(const t of i)if(J(t))if(o[t.id])for(const e of o[t.id])r.add(e);else for(const o of K(D(t),e,s,n))r.add(o);else r.add(t);return[...r]}function U(t,e,s,n){const o=K(t,e,s,n),{reenter:i}=Q(t,e,s,n);if(!i&&o.every(e=>e===t.source||W(e,t.source)))return t.source;const[r,...c]=o.concat(t.source);for(const t of j(r,void 0))if(c.every(e=>W(e,t)))return t;return i?void 0:t.source.machine.root}function H(t,e,s,n,o){const i=new Set;for(const r of t){const{targets:t}=Q(r,s,n,o);if(t?.length){const t=U(r,s,n,o);r.reenter&&r.source===t&&i.add(t);for(const s of e)W(s,t)&&i.add(s)}}return[...i]}function X(t,e,s,n,o,r){const c=[];if(!t.length)return[e,c];const a=s.actionExecutor;s.actionExecutor=t=>{c.push(t),a(t)};try{const a=new Set(e._nodes);let u=e.historyValue;const f=e.context,p=F(t,a,e,n,s),d=t=>Q(t,e,n,s),l=(t,o,i,r)=>{if(2===t.length){const c=[],a=[];let h;const u=S(s,c,a,!0),f=t({context:o,event:n,parent:s.self._parent,self:s.self,children:i,system:s.system,actions:e.machine.implementations.actions,actors:e.machine.implementations.actors,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays,input:r},u);return f?.context&&(h=f.context),[c,h,a]}return[[Object.assign((e,s)=>t({...e,input:r},s),"_special"in t?{_special:!0}:{})],void 0,void 0]};let y=e;const g=()=>{const t=H(p,a,e,n,s);let o;t.sort((t,e)=>e.order-t.order);const i=[...a];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>k(t)&&W(t,e):t=>t.parent===e;o??={...u},o[t.id]=i.filter(s)}for(const o of t){const t=e._stateInputs?.[o.id],[i,c,h]=o.exit?l(o.exit,y.context,e.children,t):[[]];h?.length&&r.push(...h),c&&(y=gt(y,{context:c})),y=x(y,n,s,i);for(const t of o.invoke){const e=y.children[t.id];e&&!e._isExternal&&s.stopChild(e),delete y.children[t.id]}a.delete(o)}u=o||u};o||g();let v=y.context;const m=[],_=[];for(const t of p){t.actions&&m.push(...wt(t.actions));const e=d(t);e.context&&(v=e.context),e.actions&&m.push(...e.actions),e.internalEvents&&_.push(...e.internalEvents)}_.length&&r.push(..._);const b=()=>{const t=t=>{const e=y.machine.root;if(void 0===e.output)return;let o;if(void 0!==t.output&&t.parent)o=Et(t.output,y.context,n,s.self);else if("parallel"===t.type){const e=`xstate.done.state.${t.id}`,s=r.find(t=>t.type===e);o=s?.output}return Et(e.output,y.context,i(t.id,o),s.self)},c=new Set,f=new Set,g=(t,e)=>{for(const s of t)if(e&&!W(s,e)||c.add(s),"parallel"===s.type)for(const t of I(s))q(c,t)||(c.add(t),v(t))},v=t=>{if(J(t))if(u[t.id]){const e=u[t.id];for(const t of e)c.add(t),v(t);for(const s of e)g(j(s,t.parent),void 0)}else{const e=D(t),{targets:s}=d(e);for(const n of s??[])c.add(n),e===t.parent?.initial&&f.add(t.parent),v(n);for(const e of s??[])g(j(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=d(t.initial).targets;return J(e)||(c.add(e),f.add(e)),v(e),void g(j(e,t),void 0)}if("parallel"===t.type)for(const e of I(t))q(c,e)||(c.add(e),f.add(e),v(e))}};for(const t of p){const o=U(t,e,n,s),{targets:i,reenter:r}=d(t);for(const e of i??[])J(e)||t.source===e&&t.source===o&&!r||(c.add(e),f.add(e)),v(e);const a=K(t,e,n,s);for(const e of a){const s=j(e,o);"parallel"===o?.type&&s.push(o),g(s,!t.source.parent&&r?void 0:o)}}o&&f.add(e.machine.root);const m={...e._stateInputs};for(const t of p){const{targets:e,input:s}=d(t);if(s&&e)for(const t of e)m[t.id]=s}const _=new Set,S={...e.children};for(const o of[...c].sort((t,e)=>t.order-e.order)){a.add(o);const c=[];let u,p=!1;for(const t of o.invoke){p=!0;let o=t.logic;"function"==typeof o&&(o=o({actors:e.machine.implementations.actors,context:e.context,event:n,self:s.self}));const i="string"==typeof o?Ot(e.machine,o):o;if(!i)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented in machine '${e.machine.id}'`);const r="function"==typeof t.input?t.input({self:s.self,context:e.context,event:n}):t.input,a=Wt(i,{...t,input:r,parent:s.self,syncSnapshot:!!t.onSnapshot});c.push({action:h["@xstate.start"],args:[a]}),t.id&&(S[t.id]=a)}p&&(y=gt(y,{children:S}));const d=m[o.id];if(o.entry){const[t,e,s]=l(o.entry,y.context,S,d);c.push(...t),s?.length&&r.push(...s),e&&(u=e)}if(f.has(o)){const{actions:t,input:e}=Q(o.initial,y,n,s);if(t&&c.push(...t),e&&o.initial?.target)for(const t of o.initial.target)m[t.id]=e}if(y=x(y,n,s,c),u&&(y.context=u),"final"!==o.type)continue;const g=o.parent;let v="parallel"===g?.type?g:g?.parent,b=v||o;for("compound"===g?.type&&r.push(i(g.id,void 0!==o.output?Et(o.output,y.context,n,s.self):void 0));"parallel"===v?.type&&!_.has(v)&&M(a,v);){_.add(v);const t={};for(const e of I(v)){if("final"===e.type){t[e.key]=void 0!==e.output?Et(e.output,y.context,n,s.self):void 0;continue}if("parallel"===e.type){const s=`xstate.done.state.${e.id}`,n=r.find(t=>t.type===s);t[e.key]=n?.output;continue}const o=I(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==o?.output?Et(o.output,y.context,n,s.self):void 0}r.push(i(v.id,t)),b=v,v=v.parent}v||(y=gt(y,{status:"done",output:t(b)}))}JSON.stringify(m)!==JSON.stringify(e._stateInputs||{})&&(y=gt(y,{_stateInputs:m}))};y=x(y,n,s,m),v&&v!==e.context&&(y=gt(y,{context:v})),b();const w=[...a];if("done"===y.status){const t=[];w.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=y._stateInputs?.[e.id],[n,,o]=l(e.exit,y.context,y.children,s);t.push(...n),o?.length&&r.push(...o)}}),y=x(y,n,s,t)}return u===e.historyValue&&e._nodes.length===a.size&&e._nodes.every(t=>a.has(t))?y.context!==f?[gt(y),c]:[y,c]:[gt(y,{_nodes:w,historyValue:u}),c]}finally{s.actionExecutor=a}}function Q(t,e,s,n){if(t.to){const o=[],i=[],r=S(n,o,i),c=t.to({context:e.context,event:s,value:e.value,children:e.children,parent:n.self._parent,self:n.self,actions:e.machine.implementations.actions,actors:e.machine.implementations.actors,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays},r),a=c?.target?z(t.source,wt(c.target)):void 0,h="function"==typeof t.input?t.input({context:e.context,event:s}):t.input;return{targets:a,context:c?.context,reenter:c?.reenter,actions:o,internalEvents:i,input:h}}const o="function"==typeof t.input?t.input({context:e.context,event:s}):t.input;return{targets:t.target,context:void 0,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:o}}function Y(t,e,o,i){let r=t;const c=[];function a(t,e){const s=o.self._collectedMicrosteps||[];s.push(...e),o.self._collectedMicrosteps=s,c.push(t)}if(e.type===n)return r=gt(et(r,o),{status:"stopped"}),a([r,[]],[]),{snapshot:r,microsteps:c};let h=e;if(h.type!==s){const e=h,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),n=r.machine.getTransitionData(r,e,o.self);if(s&&!n.length)return r=gt(t,{status:"error",error:e.error}),a([r,[]],[]),{snapshot:r,microsteps:c};const u=X(n,t,o,h,!1,i);r=u[0],a(u,n)}let u=!0;const f=t.machine.options?.maxIterations??1/0;let p=0,d=0;for(;"active"===r.status;){if(d++,d>1e3)throw new Error("Microstep count exceeded 1000");if(p++,p>f)throw new Error(`Infinite loop detected (>${f} microsteps)`);let t=u?st(r,h,o):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;h=i.shift(),t=r.machine.getTransitionData(r,h,o.self)}const s=X(t,r,o,h,!1,i);r=s[0],u=r!==e,a(s,t)}return"active"!==r.status&&r.children&&et(r,o),{snapshot:r,microsteps:c}}function Z(t,e,s,n,o){return!!t.to&&tt(t.to,e,s,n,o,n.machine.implementations)}function tt(t,e,s,n,o,i){let r,c=!1;try{const a=()=>{throw c=!0,new Error("Effect triggered")};r=t({context:e,event:s,self:o,value:n.value,children:n.children,parent:{send:a},actions:i.actions,actors:i.actors,guards:i.guards,delays:i.delays},function(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),s}({emit:a,cancel:a,log:a,raise:a,spawn:a,sendTo:a,stop:a},a))}catch(t){if(c)return!0;throw t}return void 0!==r}function et(t,e){let s;if(!t.children||0===(s=Object.values(t.children).filter(Boolean)).length)return t;for(const t of s)e.stopChild(t);return gt(t,{children:{}})}function st(t,e,s){const n=new Set,o=t._nodes.filter(k);for(const i of o)t:for(let o=i;o;o=o.parent)if(o.always)for(const i of o.always)if(nt(i,e,t,o,s.self)){n.add(i);break t}return F(Array.from(n),new Set(t._nodes),t,e,s)}function nt(t,e,s,n,o){if(t.guard){const i={context:s.context,event:e,self:o,parent:o._parent,children:s.children,actions:n.machine.implementations.actions,actors:n.machine.implementations.actors,guards:n.machine.implementations.guards,delays:n.machine.implementations.delays,_snapshot:s},r=t.guard,c="function"==typeof r?.params?r.params({context:s.context,event:e}):r?.params;let a=!0;if("function"==typeof r)a=r(i,c);else if("string"==typeof r?.type){const t=n.machine.implementations.guards[r.type];if(!t)throw new Error(`Guard '${r.type}' is not implemented in machine '${n.machine.id}'.`);a=t(i,c)}if(!a)return!1}return!t.to||tt(t.to,s.context,e,s,o,n.machine.implementations)}function ot(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}let it,rt;function ct(){return it??=Gt()}const at=function(t){return _t(t,this.value)},ht=function(t){return this.tags.has(t)},ut=function(t){const e=ct(),s=function(){if(rt)return rt;const t=ct();return rt={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},rt}(),n=this.machine.getTransitionData(this,t,e);if(!n?.length)return!1;for(const o of n){if(void 0!==o.target)return!0;const n=Q(o,this,t,s);if(n.targets?.length||n.context||Z(o,this.context,t,this,e))return!0}return!1},ft=function(){const{_nodes:t,_stateInputs:e,tags:s,machine:n,getMeta:o,getInputs:i,toJSON:r,can:c,hasTag:a,matches:h,...u}=this;return{...u,tags:Array.from(s)}},pt=function(){const t={};for(const e of this._nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},dt=function(){return this._stateInputs};function lt(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function yt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:t.value??T(e.root,t._nodes),tags:lt(t._nodes),children:t.children,historyValue:t.historyValue||{},_stateInputs:t._stateInputs||{},matches:at,hasTag:ht,can:ut,getMeta:pt,getInputs:dt,toJSON:ft}}function gt(t,e={}){const s={...t,...e};return(e._nodes??t._nodes)===t._nodes?{status:s.status,output:s.output,error:s.error,machine:t.machine,context:s.context,_nodes:t._nodes,value:t.value,tags:t.tags,children:s.children,historyValue:s.historyValue||{},_stateInputs:s._stateInputs||{},matches:at,hasTag:ht,can:ut,getMeta:pt,getInputs:dt,toJSON:ft}:yt({...s,value:void 0},t.machine)}function vt(t){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 mt(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:Rt,id:n.id};else{const o=mt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function _t(t,e){const s=xt(t),n=xt(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&_t(s[t],n[t]))}function St(t){if($t(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 xt(t){if(ot(t))return t.value;if("string"!=typeof t)return t;return function(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}(St(t))}function bt(t){return $t(t)?t:[t]}function wt(t){return void 0===t?[]:bt(t)}function Et(t,e,s,n){return"function"==typeof t?t({context:e,event:s,self:n}):t}function $t(t){return Array.isArray(t)}function kt(t){return bt(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function It(t){if(void 0!==t&&""!==t)return wt(t)}function jt(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 Ot(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,r=(Array.isArray(i)?i[n]:i).src;return"string"==typeof r?t.implementations.actors[r]:r}function Tt(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]}function Mt(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 At(t,e){return`${t.sessionId}.${e}`}const Pt=new WeakMap;function Nt(t){let e=Pt.get(t);return e||(e=new Map,Pt.set(t,e)),e}function zt(t,e){if(t?.length)for(const s of t)switch(s.type){case"emit":e.emit(s.event);break;case"sendBack":{const t=e.self._parent;t&&e.system._relay(e.self,t,s.event);break}case"raise":e.system._relay(e.self,e.self,s.event);break;case"effect":{if(!s.key){const t=s.exec();"function"==typeof t&&Nt(e.self).set(Symbol(),{cleanup:t});break}const t=Nt(e.self);if(t.has(s.key))break;const n=s.exec();t.set(s.key,{cleanup:"function"==typeof n?n:void 0});break}case"cleanupEffects":{const t=Pt.get(e.self);if(!t)break;for(const{cleanup:e}of t.values())e?.();Pt.delete(e.self);break}}}function Dt(t){const e=(e,s,o)=>{if("active"!==e.status)return[e,[]];if(s.type===n)return[{...e,status:"stopped",input:void 0},[{type:"cleanupEffects"}]];if("xstate.logic.effect.start"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if("xstate.logic.effect.resolve"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if("xstate.logic.effect.reject"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const i=[],r={},c={emit:t=>{i.push({type:"emit",event:t})},sendBack:t=>{i.push({type:"sendBack",event:t})},raise:t=>{i.push({type:"raise",event:t})},effect:(t,s)=>{if("string"==typeof t)return n=t,o=s,void(e.effects?.[n]||(i.push({type:"effect",key:n,exec:o}),r[n]={status:"active"}));var n,o;i.push({type:"effect",exec:t})}},a=t.run({context:e.context,event:s,input:e.input,system:o.system,self:o.self,emit:o.emit},c),h={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(h.context=a?.context??e.context),(a?.effects||Object.keys(r).length)&&(h.effects={...e.effects,...a?.effects,...r}),[h,i]};return{id:t.id,config:t,transition:e,start:(t,s)=>{const[n,o]=e(t,r(t.input),s);Object.assign(t,n),zt(o,s)},getInitialSnapshot:(e,s)=>{const n=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,s),o={status:"active",output:void 0,error:void 0,input:s};return void 0!==n&&(o.context=n),{...o}},getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}let Jt=!1;const Rt=1;let Ct=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Bt={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)};class Vt{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=this._process.bind(this),this.mailbox=new e(this._boundProcess),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=Ct.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[],this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this.trigger=void 0,this.src=void 0,this._deferred=[],this._pendingEffects=void 0;const n={...Bt,...s},{clock:o,logger:i,parent:r,syncSnapshot:a,id:h,systemId:u,inspect:f}=n;this.system=r?r.system:function(t,e){let s=0;const n=new Map,o=new Map,i=new WeakMap,r=new Set,c={},{clock:a,logger:h}=e,u=(t,e,s,n,o)=>{r.size&&t&&(t._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:o})},f={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{u(t,e,s,n,o);const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},r=At(t,o);d._snapshot._scheduledEvents[r]=i;const h=a.setTimeout(()=>{delete c[r],delete d._snapshot._scheduledEvents[r],p(t,e,s)},n);c[r]=h},cancel:(t,e)=>{const s=At(t,e),n=c[s];delete c[s],delete d._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in d._snapshot._scheduledEvents){const s=d._snapshot._scheduledEvents[e];s.source===t&&f.cancel(t,s.id)}}},p=(t,e,s)=>{const n=e.logic;if("function"==typeof n?.isInternalEventType&&n.isInternalEventType(s.type)&&t!==e)throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`);e._lastSourceRef=t,e._send(s)},d={children:n,reverseKeyedActors:i,keyedActors:o,_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+s++,_register:(t,e)=>(n.set(t,e),t),_unregister:t=>{n.delete(t.sessionId);const e=i.get(t);void 0!==e&&(o.delete(e),i.delete(t))},get:t=>o.get(t),getAll:()=>Object.fromEntries(o.entries()),_set:(t,e)=>{const s=o.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);o.set(t,e),i.set(e,t)},inspect:t=>{const e=jt(t);return r.add(e),{unsubscribe(){r.delete(e)}}},_sendInspectionEvent:e=>{if(!r.size)return;const s={...e,rootId:t.sessionId};r.forEach(t=>t.next?.(s))},_relay:(t,e,s)=>{u(t,e,s),p(t,e,s)},scheduler:f,getSnapshot:()=>({_scheduledEvents:{...d._snapshot._scheduledEvents}}),start:()=>{const t=d._snapshot._scheduledEvents;d._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];f.schedule(s,n,o,i,r)}},_clock:a,_logger:h,_timerStrategy:e.timers};return d}(this,{clock:o,logger:i,timers:n.timers}),f&&!r&&this.system.inspect(jt(f)),this.sessionId=this.system._bookId(),this.id=h??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){if(e)for(const s of e)try{s(t)}catch(t){c(t)}if(s)for(const e of s)try{e(t)}catch(t){c(t)}}},actionExecutor:t=>{const e=()=>{if(this._collectedActions.push({type:t.type,params:t.params}),!t.exec)return;const e=Jt;try{Jt=!0,t.exec()}finally{Jt=e}};this._processingStatus===Ct.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.trigger=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}}),u&&(this.systemId=u,this.system._set(u,this)),this._collectedMicrosteps=[];let p=s?.snapshot??s?.state;if(p&&"object"==typeof p&&"_pendingEffects"in p){const{_pendingEffects:t,...e}=p;this._pendingEffects=t,p=e}try{this._snapshot=p?this.logic.restoreSnapshot?this.logic.restoreSnapshot(p,this._actorScope):p:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t},this._deferred.length=0}u&&"active"!==this._snapshot.status&&this.system._unregister(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_setErrorSnapshot(t,e=this._snapshot){this._snapshot={...e,status:"error",error:t}}_next(t){for(const e of this.observers)try{e.next?.(t)}catch(t){c(t)}}update(t,e){this._snapshot=t;for(let e=0;e<this._deferred.length;e++){const s=this._deferred[e];try{s()}catch(e){this._deferred.length=0,this._setErrorSnapshot(e,t);break}}switch(this._deferred.length=0,this._snapshot.status){case"active":this._next(t);break;case"done":{this._next(t),this._stopProcedure(),this._complete();const e=(s=this.id,n=this._snapshot.output,{type:`xstate.done.actor.${s}`,output:n,actorId:s});this._parent&&this.system._relay(this,this._parent,e);break}case"error":this._error(this._snapshot.error)}var s,n;this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps,actions:this._collectedActions,sent:this._collectedSent,eventType:e.type}),this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[]}subscribe(t,e,s){const n=jt(t,e,s);if(this._processingStatus!==Ct.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){c(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){c(t)}else c(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);return s||(s=new Set,this.eventListeners.set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,o)=>{const i=jt(s,n,o);let r=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(r,n)||(r=n,i.next?.(n))},error:i.error,complete:i.complete})},get:()=>t(this.get())}}start(){if(this._processingStatus===Ct.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=Ct.Running;const t=r(this.options.input);this._lastSourceRef=this._parent;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._setErrorSnapshot(t),this._error(t),this}if(this.update(this._snapshot,t),this._pendingEffects){const t=this.options.timers??this.system._timerStrategy??"resume";for(const e of this._pendingEffects)"@xstate.raise"===e.type&&this.system.scheduler.schedule(this,this,e.event,Lt(t,e),e.id);this._pendingEffects=void 0}return 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._setErrorSnapshot(t),void this._error(t)}const[o,i]=Array.isArray(e)?e:[e,void 0];this.update(o,t),zt(i,this._actorScope),t.type===n&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===Ct.Stopped?this:(this.mailbox.clear(),this._processingStatus===Ct.NotStarted?(this._processingStatus=Ct.Stopped,this):(this.mailbox.enqueue({type:n}),this.system._unregister(this),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){c(t)}this.observers.clear(),this.eventListeners.clear()}_error(t){if(this._stopProcedure(),this.observers.size){let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){c(t)}}this.observers.clear(),this.eventListeners.clear(),e&&c(t)}else this._parent||c(t),this.eventListeners.clear();var e;this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${e=this.id}`,error:t,actorId:e})}_stopProcedure(){this._processingStatus===Ct.Running&&(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._boundProcess),this._processingStatus=Ct.Stopped,this.system._unregister(this))}_send(t){this._processingStatus!==Ct.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$$type:Rt,id:this.id}}getPersistedSnapshot(t){const e=this.logic.getPersistedSnapshot(this._snapshot,t),s=this.system._snapshot._scheduledEvents;let n;const o=Date.now();for(const t in s){const e=s[t];e.source===this&&e.target===this&&(n??=[]).push({type:"@xstate.raise",event:e.event,id:e.id,delay:e.delay,startedAt:e.startedAt,elapsed:Math.max(0,o-e.startedAt)})}return n??=this._pendingEffects,n?{...e,_pendingEffects:n}:e}[a](){return this}getSnapshot(){return this.get()}get(){return this._snapshot}}function Lt(t,e){if("function"==typeof t)return t(e);switch(t){case"restart":return e.delay;case"absolute":return Math.max(0,e.startedAt+e.delay-Date.now());default:return Math.max(0,e.delay-e.elapsed)}}function Wt(t,e){return new Vt(t,e)}const qt=Dt({context:void 0,run:()=>{}});function Gt(){return Wt(qt)}function Ft(t,{machine:e,context:s},n,o){return(i,r)=>{const c=((i,r)=>{if("string"==typeof i){const c=Ot(e,i);if(!c)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const a=Wt(c,{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[a.id]=a,a}return Wt(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[c.id]=c,t.defer(()=>{c._processingStatus!==Ct.Stopped&&c.start()}),c}}const Kt=new WeakMap;function Ut(t,e,s){let n=Kt.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Kt.set(t,n)),n[e]}const Ht={},Xt=["invoke","after","on","entry","exit","always","states","initial","onDone","timeout","onTimeout","history","target","output"];class Qt{constructor(t,e){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.invoke=void 0,this.on=void 0,this.after=void 0,this.events=void 0,this.ownEvents=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[];const s=this.config.states?Object.keys(this.config.states)[0]:void 0;if(this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(void 0!==s?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,function(t){const e=t.config;if("choice"!==t.type){if(void 0!==e.choice)throw new Error(`State "${t.id}" has \`choice\`, but \`choice\` can only be used with \`type: 'choice'\`.`);return}if("function"!=typeof e.choice)throw new Error(`Choice state "${t.id}" must declare a \`choice\` function.`);for(const s of Xt)if(void 0!==e[s])throw new Error(`Choice state "${t.id}" cannot declare \`${s}\`.`)}(this),this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(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}(this.config.states,(t,e)=>new Qt(t,{_parent:this,_key:e,_machine:this.machine})):Ht,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}".`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.entry&&(this.entry._special=!0),this.exit&&(this.exit._special=!0),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=wt(t.tags).slice(),this.invoke=wt(this.config.invoke).map((t,e)=>{const{src:s,systemId:n}=t,o=(i=this.id,`${e}.${i}`);var i;const r=t.id??o,c="string"==typeof s?s:`xstate.invoke.${o}`;return{...t,src:c,logic:s,id:r,systemId:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,i=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===i.length)return[];const r=e=>{const s={type:`xstate.after.${e}.${t.id}`};return P(t,s,s=>$(e,s.delays,{context:s.context,event:s.event,stateNode:t}))},c=[],a=(t,e,s)=>{for(const n of kt(t))c.push({...n,event:e,delay:s})};if(e)for(const s of Object.keys(e)){const n=e[s],o=Number.isNaN(+s)?s:+s;a(n,r(o),E(o,t.machine.implementations.delays))}if(void 0!==s&&n){const e={type:`xstate.timeout.${t.id}`};a(n,P(t,e,e=>$(s,e.delays,{context:e.context,event:e.event,stateNode:t})),"function"==typeof s?s:E(s,t.machine.implementations.delays))}for(const e of i){const s=o(e.id),n=e.timeout,i=P(t,s,e=>$(n,{},{context:e.context,event:e.event,stateNode:t}));a(e.onTimeout,i,n)}return c.map(e=>({...N(t,e.event,e),delay:e.delay}))}(this),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,Yt(n,e=>N(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,Yt(t.config.onDone,e=>N(t,s,e)))}const s=(e,s)=>N(t,e,{to:(t,e)=>(e.cancel(s),{})}),n=(e,s,n)=>{const{target:o,to:i,reenter:r,...c}=s;return N(t,e,{...c,reenter:r,to:(t,e)=>{if(i){let s=!1;const o=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const o=Reflect.get(t,e,n);return"function"!=typeof o?o:(...e)=>(s=!0,o.apply(t,e))}}),r=i(t,o);return(void 0!==r||s)&&e.cancel(n),r}return e.cancel(n),{target:o,reenter:r}}})};for(const i of t.invoke){const r=void 0!==i.timeout?o(i.id).type:void 0;if(i.onDone){const o=`xstate.done.actor.${i.id}`,c=Yt(i.onDone,e=>r?n(o,e,r):N(t,o,e));r&&c.push(s(o,r)),e.set(o,c)}else if(r){const t=`xstate.done.actor.${i.id}`;e.set(t,[s(t,r)])}if(i.onError){const s=`xstate.error.actor.${i.id}`;e.set(s,Yt(i.onError,e=>r?n(s,e,r):N(t,s,e)))}if(i.onSnapshot){const s=`xstate.snapshot.${i.id}`;e.set(s,Yt(i.onSnapshot,e=>N(t,s,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),"choice"===this.type?this.always=function(t){const e=t.config.choice,s=e=>{if(!e||void 0===e.target)throw new Error(`Choice state "${t.id}" must resolve to a target.`);for(const s of["actions","to","context"])if(void 0!==e[s])throw new Error(`Choice state "${t.id}" cannot declare \`${s}\` on a choice.`);return e};return[N(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=Yt(this.config.always,t=>N(this,"",t)));for(const t of Object.keys(this.states))this.states[t]._initialize();this._refreshEventMetadata()}_refreshEventMetadata(){const t={},e=[];for(const[s,n]of this.transitions)t[s]=n.slice(),n.some(t=>t.target||t.reenter||t.to)&&e.push(s);this.on=t,this.ownEvents=e;const s=new Set(e);for(const t of Object.values(this.states))for(const e of t.events)s.add(e);this.events=Array.from(s)}get initial(){return Ut(this,"initial",()=>function(t,e){const s="object"==typeof e&&null!==e?e.target:e,n="object"==typeof e&&null!==e?e.input:void 0,o="string"==typeof s?t.states[s]:void 0;if(!o&&s)throw new Error(`Initial state node "${s}" not found on parent state node #${t.id}`);return{source:t,target:o?[o]:void 0,input:n}}(this,this.config.initial))}next(t,e,s){const n=e.type,o=Ut(this,`candidates-${n}`,()=>function(t,e){const s=t.transitions.get(e);if(s)return s;const n=[];for(const s of t.transitions.keys())Mt(e,s)&&n.push(s);n.sort((t,e)=>e.length-t.length);const o=[];for(const e of n)o.push(...t.transitions.get(e));return o}(this,n));for(const n of o){if(nt(n,e,t,this,s))return[n]}}}function Yt(t,e){const s=kt(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}class Zt{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._json=void 0,this.id=t.id||"(machine)",this.implementations={actors:t.actors??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...e},this.version=this.config.version,this.schemas=this.config.schemas,this.internalEventDescriptors=this.config.internalEvents??[],this.options={maxIterations:1/0,...this.config.options},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 Qt(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const o=n.config.id,i=n.config.route,r=({event:t})=>t.to===`#${o}`;if("function"==typeof i)return e.push(N(t,"xstate.route",{guard:r,to:t=>{const e=i(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(n.states&&s(n.states));if("$unserializable"in i)throw new Error(`State "${n.id}" has a route that is not serializable. Re-provide the route function when reviving this machine.`);const c=i.guard,a={...i,guard:c?e=>{if(!r(e))return!1;if("function"==typeof c)return c(e);if("string"==typeof c){const s=e.guards?.[c];if(!s)throw new Error(`Guard '${c}' is not implemented in machine '${t.machine.id}'.`);return s(e)}return!0}:r,target:`#${o}`};e.push(N(t,"xstate.route",a))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.root._refreshEventMetadata(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.implementations,i=new Zt(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}});return i._json=this._json,i}resolveState(t){const e=(s=this.root,n=t.value,T(s,O(V(s,n))));var s,n;const o=O(V(this.root,e));return yt({_nodes:[...o],value:e,context:t.context||{},children:{},status:M(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return Y(t,e,s,[]).snapshot}microstep(t,e,s){const{microsteps:n}=Y(t,e,s,[]),o=new Array(n.length);for(let t=0;t<n.length;t++)o[t]=n[t][0];return o}getTransitionData(t,e,s){return L(this.root,t.value,t,e,s)||[]}isInternalEventType(t){for(const e of this.internalEventDescriptors)if(Mt(t,e))return!0;return!1}_getPreInitialState(t,e){const{context:s}=this.config,n=yt({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const o={},i=s({spawn:Ft(t,n,e,o),input:e.input,self:t.self,actors:this.implementations.actors}),r=x(n,e,t,[]);return i&&(r.context=i),Object.keys(o).length>0&&(r.children={...r.children,...o}),r}return n}getInitialSnapshot(t,e){const s=r(e),n=[],o=this._getPreInitialState(t,s),[i]=function(t,e,s,n,o){return X([{target:[...R(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,o,t,s,n),{snapshot:c}=Y(i,s,t,n);return c}start(t){if(t?.children)for(const e of Object.values(t.children))e._rehydrated&&"active"===e.getSnapshot?.().status&&e.start()}getStateNodeById(t){const e=St(t),s=e.slice(1),n=A(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 B(o,s)}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,_stateInputs:n,tags:o,machine:i,children:r,context:c,can:a,hasTag:h,matches:u,getMeta:f,getInputs:p,toJSON:d,...l}=t,y={};for(const t in r){const s=r[t];y[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s.systemId,syncSnapshot:s._syncSnapshot}}const g={...l,context:mt(c),children:y,historyValue:vt(l.historyValue)};return void 0!==i.version&&(g.version=i.version),g}(t,e)}restoreSnapshot(t,e){const s=t.version;if(s!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${s}' does not match machine version '${this.version}'.`);t=e(t,s)}const n=t,o={},i=n.children;for(const t of Object.keys(i)){const s=i[t],n=s.snapshot,r=s.src,c="string"==typeof r?Ot(this,r):r;if(!c)continue;const a=Wt(c,{id:t,parent:e.self,syncSnapshot:s.syncSnapshot,snapshot:n,src:r,systemId:s.systemId});a._rehydrated=!0,o[t]=a}const r=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const s of Object.keys(t)){const n=t[s];for(const t of n){let n;if(t instanceof Qt)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(n.historyValue),c=Array.from(O(V(this.root,n.value))),{version:a,...h}=t,u=yt({...h,children:o,_nodes:c,value:n.value,historyValue:r},this),f=new WeakSet;return function t(e){if(!f.has(e)){f.add(e);for(const s of Object.keys(e)){const n=e[s];if(n&&"object"==typeof n){if("xstate$$type"in n&&n.xstate$$type===Rt){e[s]=o[n.id];continue}t(n)}}}}(u.context),u}}function te(t){return JSON.stringify(t)}function ee(t){const e=Object.keys(t.context).length?`(${JSON.stringify(t.context)})`:"",s=t._nodes.filter(t=>"atomic"===t.type||"final"===t.type).map(({id:e,path:s})=>{const n=t.getMeta()[e];if(!n)return`"${s.join(".")}"`;const{description:o}=n;return"function"==typeof o?o(t):o?`"${o}"`:JSON.stringify(t.value)});return`state${1===s.length?"":"s"} `+s.join(", ")+` ${e}`.trim()}const se=()=>(t,e)=>_e(t,e),ne=()=>(t,e)=>Se(t,e);class oe{getDefaultOptions(){return{serializeState:t=>te(t),serializeEvent:t=>te(t),serializeTransition:(t,e)=>`${te(t)}|${e?.type}`,events:[],stateMatcher:(t,e)=>"*"===e,logger:{log:console.log.bind(console),error:console.error.bind(console)}}}constructor(t,e){this.testLogic=t,this.options=void 0,this.defaultTraversalOptions=void 0,this._toTestPath=t=>{const e=t.steps.map(t=>function(t){const{type:e,...s}=t;return`${e}${Object.keys(s).length?` (${JSON.stringify(s)})`:""}`}(t.event)).join(" → ");return{...t,test:e=>this.testPath(t,e),description:ot(t.state)?`Reaches ${ee(t.state).trim()}: ${e}`:JSON.stringify(t.state)}},this.options={...this.getDefaultOptions(),...e}}getPaths(t,e){const s=e?.allowDuplicatePaths??!1,n=t(this.testLogic,this._resolveOptions(e));return(s?n:((t,e=te)=>{const s=[];t.forEach(t=>{s.push({path:t,eventSequence:t.steps.map(t=>e(t.event))})}),s.sort((t,e)=>e.path.steps.length-t.path.steps.length);const n=[];t:for(const t of s){e:for(const e of n){for(const s in t.eventSequence)if(t.eventSequence[s]!==e.eventSequence[s])continue e;continue t}n.push(t)}return n.map(t=>t.path)})(n)).map(this._toTestPath)}getShortestPaths(t){return this.getPaths(se(),t)}getShortestPathsFrom(t,e){const s=[];for(const n of t){const t=this.getShortestPaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(le(n,e)))}return s}getSimplePaths(t){return this.getPaths(ne(),t)}getSimplePathsFrom(t,e){const s=[];for(const n of t){const t=this.getSimplePaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(le(n,e)))}return s}getPathsFromEvents(t,e){return me(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return ge(this.testLogic,this.options)}async testPath(t,e,s){const n={steps:[],state:{error:null}};try{for(const o of t.steps){const t={step:o,state:{error:null},event:{error:null}};n.steps.push(t);try{await this.testTransition(e,o)}catch(e){throw t.event.error=e,e}try{await this.testState(e,o.state,s)}catch(e){throw t.state.error=e,e}}}catch(e){throw e.message+=function(t,e,s){const n={formatColor:(t,e)=>e,serializeState:te,serializeEvent:te,...s},{formatColor:o,serializeState:i,serializeEvent:r}=n,{state:c}=t,a=i(c,t.steps.length?t.steps[t.steps.length-1].event:void 0);let h="",u=!1;return h+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=i(t.step.state,e>0?s[e-1].step.event:void 0),c=r(t.step.event);return[`\tState: ${u?o("gray",n):t.state.error?(u=!0,o("redBright",n)):o("greenBright",n)}`,`\tEvent: ${u?o("gray",c):t.event.error?(u=!0,o("red",c)):o("green",c)}`].join("\n")}).concat(`\tState: ${u?o("gray",a):e.state.error?o("red",a):o("green",a)}`).join("\n\n"),h}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),o=this._getStateTestKeys(t,e,n);for(const s of o)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},o=Object.keys(n).filter(t=>s.stateMatcher(e,t));return!o.length&&"*"in n&&o.push("*"),o}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function ie(t,e){if(t===e)return!0;if(void 0===t||void 0===e)return!1;if("string"==typeof t||"string"==typeof e)return t===e;const s=Object.keys(t),n=Object.keys(e);return s.length===n.length&&s.every(s=>ie(t[s],e[s]))}function re(t,e,s,{serializeEvent:n}){if(!e||s&&ie(s.value,t.value))return"";const o=s?` from ${te(s.value)}`:"";return` via ${n(e)}${o}`}function ce(){const t=Gt();return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function ae(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function he(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function ue(t){return JSON.stringify(t)}function fe(t,e){const{events:s,...n}=e??{};return{serializeState:he,serializeEvent:ue,events:t=>{const e="function"==typeof s?s(t):s??[];return Tt(t).flatMap(t=>{const s=e.filter(e=>e.type===t);return s.length?s:[{type:t}]})},fromState:t.getInitialSnapshot(ce(),e?.input),...n}}function pe(){return{serializeState:t=>JSON.stringify(t),serializeEvent:ue}}function de(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?fe(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:ue,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function le(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}}function ye(t){return Array.isArray(t)?t[0]:t}function ge(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:i,filterEvents:r,limit:c,fromState:a,stopWhen:h}=de(t,e),u=ce(),f={};let p=0;const d=[{nextState:a??t.getInitialSnapshot(u,e.input),event:void 0,prevState:void 0}],l=new Map;for(;d.length;){const{nextState:t,event:e,prevState:a}=d.shift();if(p++>c)throw new Error("Traversal limit exceeded");const y=o(t,e,a);if(f[y])continue;if(l.set(y,t),f[y]={state:t,transitions:{}},h&&h(t))continue;const g="function"==typeof i?i(t):i;for(const e of g){if(r&&!r(t,e))continue;const o=ye(s(t,e,u));f[y].transitions[n(e)]={event:e,state:o},d.push({nextState:o,event:e,prevState:t})}}return f}function ve(t){let e=[];if(t.steps.length){for(let n=0;n<t.steps.length;n++){const o=t.steps[n];e.push({state:o.state,event:0===n?{type:s}:t.steps[n-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:s}}];return{...t,steps:e}}function me(t,e,s){const n=de(t,{events:e,...s},(o=t)&&o instanceof Zt?fe(t):pe());var o;const i=ce(),r=n.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:c,serializeEvent:a}=n,h=ge(t,n),u=new Map,f=[],p=c(r,void 0,void 0);u.set(p,r);let d=p,l=r;for(const t of e){f.push({state:u.get(d),event:t});const e=a(t),{state:s,event:n}=h[d].transitions[e];if(!s)throw new Error(`Invalid transition from ${d} with ${e}`);const o=c(s,t,u.get(d));u.set(o,s),d=o,l=s}return n.toState&&!n.toState(l)?[]:[ve({state:l,steps:f,weight:f.length})]}function _e(t,e){const s=de(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(ce(),e?.input),i=ge(t,s),r=new Map,c=new Map,a=n(o,void 0,void 0);c.set(a,o),r.set(a,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(a);for(const t of h){const e=c.get(t),{weight:s}=r.get(t);for(const o of Object.keys(i[t].transitions)){const{state:a,event:f}=i[t].transitions[o],p=n(a,f,e);if(c.set(p,a),r.has(p)){const{weight:e}=r.get(p);e>s+1&&r.set(p,{weight:s+1,state:t,event:f})}else r.set(p,{weight:s+1,state:t,event:f});u.has(p)||h.add(p)}u.add(t),h.delete(t)}const f={},p=[];return r.forEach(({weight:t,state:e,event:s},n)=>{const o=c.get(n),i=e?f[e].paths[0].steps.concat({state:c.get(e),event:s}):[];p.push({state:o,steps:i,weight:t}),f[n]={state:o,paths:[{state:o,steps:i,weight:t}]}}),s.toState?p.filter(t=>s.toState(t.state)).map(ve):p.map(ve)}function Se(t,e){const s=de(t,e),n=ce(),o=s.fromState??t.getInitialSnapshot(n,e?.input),i=s.serializeState,r=ge(t,s),c=new Map,a={vertices:new Set,edges:new Set},h=[],u={};function f(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){u[e]||(u[e]={state:c.get(e),paths:[]});const t=u[e],n={state:s,weight:h.length,steps:[...h]};t.paths.push(n)}else{if(!r[t])return;for(const s of Object.keys(r[t].transitions)){const{state:n,event:o}=r[t].transitions[s];if(!(s in r[t].transitions))continue;const u=c.get(t),p=i(n,o,u);c.set(p,n),a.vertices.has(p)||(a.edges.add(s),h.push({state:c.get(t),event:o}),f(p,e))}}h.pop(),a.vertices.delete(t)}const p=i(o,void 0);c.set(p,o);for(const t of Object.keys(r))f(p,t);const d=Object.values(u).flatMap(t=>t.paths);return s.toState?d.filter(t=>s.toState(t.state)).map(ve):d.map(ve)}t.TestModel=oe,t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.createShortestPathsGen=se,t.createSimplePathsGen=ne,t.createTestModel=function(t,e){(t=>{t.root})(t);const s=e?.serializeEvent??te,n=e?.serializeTransition??re,{events:o,...i}=e??{};return new oe(t,{serializeState:(t,e,o)=>`${he(t)}${n(t,e,o,{serializeEvent:s})}`,stateMatcher:(e,s)=>s.startsWith("#")?e._nodes.includes(t.getStateNodeById(s)):e.matches(s),events:t=>{const e="function"==typeof o?o(t):o??[];return Tt(t).flatMap(t=>e.some(e=>e.type===t)?e.filter(e=>e.type===t):[{type:t}])},...i})},t.getAdjacencyMap=ge,t.getPathsFromEvents=me,t.getShortestPaths=_e,t.getSimplePaths=Se,t.getStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,n)=>{const o=s[n],i=t(o);return e.push(o,...i),e},[])},t.joinPaths=le,t.serializeSnapshot=he,t.toDirectedGraph=function t(e){const s=e instanceof Zt?e.root:e,n=[...s.transitions.values()].flat().flatMap((t,e)=>(t.target?t.target:[s]).map((n,o)=>{const i={id:`${s.id}:${e}:${o}`,source:s,target:n,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=i;return{source:s.id,target:n.id,label:t}}};return i})),o={id:s.id,stateNode:s,children:ae(s).map(t),edges:n,toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s}}};return o},Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate-graph.umd.min.js.map