xstate 6.0.0-beta.1 → 6.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/{createActor-551369be.development.esm.js → createActor-0250284a.development.esm.js} +244 -41
  2. package/dist/{createActor-cbe3abac.esm.js → createActor-20a97166.esm.js} +243 -40
  3. package/dist/{createActor-a49ae0ce.development.cjs.js → createActor-c029d29f.development.cjs.js} +245 -40
  4. package/dist/{createActor-25900f76.cjs.js → createActor-c91c9ffe.cjs.js} +244 -39
  5. package/dist/declarations/src/createActor.d.ts +3 -1
  6. package/dist/declarations/src/createMachine.d.ts +6 -3
  7. package/dist/declarations/src/durable/index.d.ts +43 -8
  8. package/dist/declarations/src/effectDescriptor.d.ts +2 -2
  9. package/dist/declarations/src/machineVersion.types.d.ts +2 -2
  10. package/dist/declarations/src/setup.d.ts +2 -2
  11. package/dist/declarations/src/systemTransition.d.ts +1 -1
  12. package/dist/declarations/src/types.d.ts +4 -2
  13. package/dist/declarations/src/types.v6.d.ts +37 -2
  14. package/dist/{effectDescriptor-f73da4ec.development.cjs.js → effectDescriptor-3fff5c51.development.cjs.js} +5 -5
  15. package/dist/{effectDescriptor-2fa27c54.cjs.js → effectDescriptor-47f73e7e.cjs.js} +5 -5
  16. package/dist/{effectDescriptor-321a8ce9.development.esm.js → effectDescriptor-5ac7dccb.development.esm.js} +5 -5
  17. package/dist/{effectDescriptor-d8b0f749.esm.js → effectDescriptor-e93df910.esm.js} +5 -5
  18. package/dist/{machineSchemas-88d01821.cjs.js → legacySnapshot-8d595687.cjs.js} +117 -1
  19. package/dist/{machineSchemas-45c21bc2.esm.js → legacySnapshot-9e06feb4.esm.js} +116 -2
  20. package/dist/{machineSchemas-b5736804.development.esm.js → legacySnapshot-ae6594a7.development.esm.js} +117 -3
  21. package/dist/{machineSchemas-6d96bef4.development.cjs.js → legacySnapshot-ebf0b2b8.development.cjs.js} +118 -2
  22. package/dist/xstate-actors.cjs.js +1 -1
  23. package/dist/xstate-actors.development.cjs.js +1 -1
  24. package/dist/xstate-actors.development.esm.js +2 -2
  25. package/dist/xstate-actors.esm.js +2 -2
  26. package/dist/xstate-actors.umd.min.js +1 -1
  27. package/dist/xstate-actors.umd.min.js.map +1 -1
  28. package/dist/xstate-durable.cjs.js +120 -10
  29. package/dist/xstate-durable.development.cjs.js +120 -10
  30. package/dist/xstate-durable.development.esm.js +120 -10
  31. package/dist/xstate-durable.esm.js +120 -10
  32. package/dist/xstate-durable.umd.min.js +1 -1
  33. package/dist/xstate-durable.umd.min.js.map +1 -1
  34. package/dist/xstate-fsm.cjs.js +4 -4
  35. package/dist/xstate-fsm.development.cjs.js +4 -4
  36. package/dist/xstate-fsm.development.esm.js +4 -4
  37. package/dist/xstate-fsm.esm.js +4 -4
  38. package/dist/xstate-fsm.umd.min.js +1 -1
  39. package/dist/xstate-fsm.umd.min.js.map +1 -1
  40. package/dist/xstate-graph.cjs.js +1 -1
  41. package/dist/xstate-graph.development.cjs.js +1 -1
  42. package/dist/xstate-graph.development.esm.js +2 -2
  43. package/dist/xstate-graph.esm.js +2 -2
  44. package/dist/xstate-graph.umd.min.js +1 -1
  45. package/dist/xstate-graph.umd.min.js.map +1 -1
  46. package/dist/xstate-persist.cjs.js +23 -12
  47. package/dist/xstate-persist.development.cjs.js +23 -12
  48. package/dist/xstate-persist.development.esm.js +17 -6
  49. package/dist/xstate-persist.esm.js +17 -6
  50. package/dist/xstate-persist.umd.min.js +1 -1
  51. package/dist/xstate-persist.umd.min.js.map +1 -1
  52. package/dist/xstate-validation.cjs.js +1 -1
  53. package/dist/xstate-validation.development.cjs.js +1 -1
  54. package/dist/xstate-validation.development.esm.js +1 -1
  55. package/dist/xstate-validation.esm.js +1 -1
  56. package/dist/xstate.cjs.js +63 -51
  57. package/dist/xstate.development.cjs.js +63 -51
  58. package/dist/xstate.development.esm.js +53 -41
  59. package/dist/xstate.esm.js +53 -41
  60. package/dist/xstate.umd.min.js +1 -1
  61. package/dist/xstate.umd.min.js.map +1 -1
  62. package/docs/api-stability.json +267 -249
  63. package/docs/backend-workflows.md +3 -3
  64. package/docs/durable-execution.md +72 -48
  65. package/docs/errors.md +2 -2
  66. package/docs/examples.md +34 -34
  67. package/docs/fsm.md +2 -1
  68. package/docs/guards.md +1 -1
  69. package/docs/index.md +1 -1
  70. package/docs/invoke.md +34 -2
  71. package/docs/persistence.md +16 -10
  72. package/docs/serialization.md +1 -1
  73. package/docs/setup-and-provide.md +3 -3
  74. package/docs/spawn.md +1 -1
  75. package/docs/system-transitions.md +6 -6
  76. package/docs/tutorial.md +5 -5
  77. package/docs/typescript.md +9 -0
  78. package/docs/xstate-v5-to-v6.md +17 -17
  79. package/package.json +1 -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).XState={})}(this,function(t){"use strict";function e(t,...e){return`XState error E${t}${e.length?` (${e.map(t=>"string"==typeof t?JSON.stringify(t):String(t)).join(", ")})`:""}. See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e${t}`}const s=["types","tsTypes","schema","internalEvents","services","devTools"],n=["onDone","onError","onTimeout","always"],r=["onDone","onError","onSnapshot","onTimeout"],o=/^xstate\.(done\.actor|error\.actor|snapshot|done\.state|after)\.(.+)$/;function i(t,s){const n=o.exec(t);if(n&&"*"!==n[2]&&("snapshot"!==n[1]||"actor"!==n[2]&&"actor.*"!==n[2]))throw new Error(e(3,t,s))}function a(t,s,n){if(t)for(const r of Array.isArray(t)?t:[t])if(r&&"object"==typeof r){if(void 0!==r.cond)throw new Error(e(4,s,n,"cond"));if(void 0!==r.guard)throw new Error(e(4,s,n,"guard"));if(void 0!==r.actions)throw new Error(e(4,s,n,"actions"))}}function c(t,s){if(function(t,s){if(t&&"object"==typeof t){if(void 0!==t.cond)throw new Error(e(5,s,"cond"));if(void 0!==t.guard)throw new Error(e(5,s,"guard"));if(void 0!==t.actions)throw new Error(e(5,s,"actions"))}}(t.initial,s),void 0!==t.activities)throw new Error(e(6,s));for(const n of["entry","exit"]){const r=t[n];if(void 0!==r&&"function"!=typeof r)throw new Error(e(7,s,n))}if(t.on)for(const e of Object.keys(t.on))i(e,s),a(t.on[e],e,s);if(t.after)for(const e of Object.keys(t.after))a(t.after[e],`after.${e}`,s);for(const e of n)a(t[e],e,s);if(t.invoke)for(const e of Array.isArray(t.invoke)?t.invoke:[t.invoke])if(e&&"object"==typeof e)for(const t of r)a(e[t],`invoke.${t}`,s);if(t.states)for(const e of Object.keys(t.states)){const n=t.states[e];n&&"object"==typeof n&&c(n,n.id??(s?`${s}.${e}`:e))}}function u(t){if(t&&"object"==typeof t){for(const n of s)if(void 0!==t[n])throw new Error(e(1,n));c(t,t.id??"")}}const d=new Set(["clock","logger","syncSnapshot","id","registryKey","input","src","inspect","onRejectedEvent","onUnhandledEvent","_systemRef","_sessionId","_inert","_restore"]);const h="xstate.init",f="@xstate.spawn",p="xstate.stop",l="@xstate.terminate",y="xstate.timer",v="xstate.logic.effect.resolve",m="xstate.logic.effect.reject",g="xstate.logic.effect.start",_={unsubscribe(){}};function w(t){return!0===t._remote}function b(t){if("object"!=typeof t||null===t||Array.isArray(t)||"string"!=typeof t.$actor)return!1;for(const e in t)if("$actor"!==e&&"incarnation"!==e)return!1;const e=t.incarnation;return void 0===e||"string"==typeof e}function x(t){const e=t.slice(t.lastIndexOf("/")+1);return e.includes("%")?e.replaceAll("%2F","/").replaceAll("%25","%"):e}function E(t){return new Error(e(50,...void 0===t.incarnation?[t.$actor]:[t.$actor,t.incarnation]))}function $(t,e){const s=t._getByAddress?.(e.$actor);return!s||void 0!==e.incarnation&&s.sessionId!==e.incarnation?void 0:s}const S=Object.freeze({status:"active",output:void 0,error:void 0});function k(t,e,s){return t.system._notifyEmitted(t,e),s.emitEvent(t,e)}const A=new WeakMap;async function j(t,s,n,r=e=>{t.system.sendEvent(t,t,e)}){const o=function(t,e){const s=t.getSnapshot().effects;return s&&Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0}(t,s);if("done"===o?.status)return o.output;if("error"===o?.status)throw o.error;const i=A.get(t)?.get(s);if(i)return i;if("active"!==t.getSnapshot().status)throw new Error(e(72,s));let a,c;const u=new Promise((t,e)=>{a=t,c=e});let d,h=A.get(t);h||(h=new Map,A.set(t,h)),h.set(s,u);const f=()=>{d?.unsubscribe(),h.delete(s),h.size||A.delete(t)};return u.then(f,f),d=t.subscribe({error:c,complete:()=>c(new Error(e(72,s)))}),(async()=>{try{r({type:g,key:s});const e=await n();"active"===t.getSnapshot().status&&(r({type:v,key:s,output:e}),a(e))}catch(e){"active"===t.getSnapshot().status&&r({type:m,key:s,error:e}),c(e)}})().catch(c),u}function O(t,e,s){if(b(e)){const n=e,r=t?.system,o=r&&$(r,n);if(!o){const e=E(n);if(!r)throw e;return void r.deadLetter(t,void 0,s,"missingTarget",{targetId:x(n.$actor),error:e})}e=o}if(I(t,e,s))return;e._send(s,t)}function I(t,s,n){const r=function(t,s,n){const r=s;if(t!==s&&r.logic?.isInternalEventType?.(n.type))return new Error(e(73,n.type,s.id))}(t,s,n);return!!r&&(s.system.deadLetter(t,s,n,"internalEvent",{error:r}),!0)}function T(t,e){t._terminate(e)}function M(t){t._stop()}class R{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}}function P(t,e){return{type:"xstate.after",delay:t,stateId:e}}function N(t,e){return{type:"xstate.timeout.actor",actorId:t,sessionId:e}}function q(t,e){return{type:"xstate.done.state",stateId:t,output:e}}function D(t,e,s){return{type:"xstate.done.actor",output:e,actorId:t,sessionId:s}}function L(t,e,s){return{type:"xstate.error.actor",error:e,actorId:t,sessionId:s}}function C(t,e){return{type:`xstate.error.${t}`,error:e}}function K(t){return{type:h,input:t}}function z(t){setTimeout(()=>{throw t})}const W="function"==typeof Symbol&&Symbol.observable||"@@observable",V=[],U=new Error("Transition effect");function J(t,e="abort"){const s={mode:e,parent:t,requiresReevaluation:!1};return V.push(s),{frame:s,close(){V.pop()}}}function F(t){const{stateId:e,delay:s,actorId:n}=t;switch(t.type){case"xstate.after":return{type:t.type,delay:s,stateId:e};case"xstate.timeout.state":return{type:t.type,stateId:e};case"xstate.timeout.actor":return{type:t.type,actorId:n}}}function B(t){return void 0!==t.id?{id:t.id}:void 0!==t.seq?{seq:t.seq}:{event:F(t.event)??t.event}}function H(t){const e=t;return"string"==typeof e.id?{id:e.id}:"number"==typeof e.seq?{seq:e.seq}:e.event&&"object"==typeof e.event&&"string"==typeof e.event.type?{event:e.event}:void 0}function X(t,e){if("id"in e)return t.id===e.id;if(void 0!==t.id)return!1;if("seq"in e)return t.seq===e.seq;if(void 0!==t.seq)return!1;const s=t.event,n=e.event;for(const t in n)if(s[t]!==n[t])return!1;return!0}function G(t){return"id"in t?JSON.stringify(["id",t.id]):"seq"in t?JSON.stringify(["seq",t.seq]):JSON.stringify(["event",F(t.event)??t.event])}function Q(t,e){return`${t.sessionId}|${G(e)}`}const Y=new WeakMap;function Z(t){return Y.get(t)??t.scheduledAt}function tt(t){if("string"==typeof t)throw new Error(e(70,t))}const et={"@xstate.spawn":t=>t.system.spawnActor(t._parent,t),"@xstate.start":t=>t.system.startActor(t),"@xstate.raise":(t,e,s)=>t.system.scheduleTimer(t.self,B({id:s.id,seq:s.seq,event:e}),s?.delay??0),"@xstate.sendTo":(t,e,s,n)=>(tt(s),void 0!==n?.delay?t.system.scheduleTimer(t.self,B({id:n.id,seq:n.seq,event:s}),n?.delay??0):t.system._relay(t.self,e,s)),"@xstate.cancel":(t,e)=>t.system.cancelTimer(t.self,e),"@xstate.stop":(t,e)=>t.system.stopActor(e),"@xstate.terminate":(t,e)=>t.system.terminateActor(t,e)},st=new WeakMap;function nt(t,e){let s=st.get(t);if(!s){s=new Map;for(const e of Object.keys(t)){const n=t[e];s.has(n)||s.set(n,e)}st.set(t,s)}return s.get(e)}const rt=Symbol("xstate.systemLogicMetadata"),ot=new WeakMap;function it(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]],n={id:e,start:(e,{self:s,system:n})=>{const r=e.input.actor;if(!r||"stopped"===r.getSnapshot().status)return;const o=t(e.input,{self:s,system:n});if(!o)return;let i,a=!1;const c=()=>{a||(a=!0,o.unsubscribe(),i?.unsubscribe())},u=s._parent;u&&(i=u.subscribe({complete:c,error:c})),ot.set(s,{unsubscribe:c})},transition:(t,e,{self:s})=>e.type===p?(ot.get(s)?.unsubscribe(),ot.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return Object.defineProperty(n,rt,{value:{kind:e}}),n}function at(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function ct(){return it(({actor:t,eventType:e,mapper:s},{self:n,system:r})=>{const o="*"!==e&&e.endsWith(".*");return t.on(o?"*":e,t=>{o&&!Gs(t.type,e)||at(n,r,()=>s(t))})},"@xstate.listener")}const ut=ct();function dt(){return it(({actor:t,mappers:e},{self:s,system:n})=>{const{done:r,error:o,snapshot:i}=e;return t.subscribe({next:t=>{"done"===t.status&&r?at(s,n,()=>r(t.output)):"error"===t.status&&o?at(s,n,()=>o(t.error)):"active"===t.status&&i&&at(s,n,()=>i(t))},error:t=>{o&&at(s,n,()=>o(t))},complete:()=>{}})},"@xstate.subscription")}const ht=dt();function ft(){const t=this.action?.(...this.args);return t}function pt(t=this.source.system){return k(this.source,this.event,t)}function lt(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function yt(t,e,s,n,r){return{kind:"builtin",type:"@xstate.deadLetter",exec:lt,source:e,target:t.self,event:s,reason:n,detail:r,params:void 0,args:[]}}function vt(t,s,n){return{kind:"builtin",type:"@xstate.deadLetter",exec:lt,source:t.self,target:void 0,event:s,reason:"missingTarget",detail:{targetId:n,error:new Error(e(65,n))},params:void 0,args:[]}}function mt(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function gt(t=this.actor.system){return t.spawnActor(this.source,this.actor)}function _t(t=this.actor.system){if(2!==this.actor._processingStatus)return t.startActor(this.actor)}function wt(t=this.source.system){return t.stopActor(this.actor)}function bt(t=this.actor.system){const e="done"===this.status?{status:"done",output:this.output,error:void 0}:{status:"error",output:void 0,error:this.error};return t.terminateActor(this.actor,e)}function xt(t=this.source.system){return t.scheduleTimer(this.source,B(this),this.delay??0)}function Et(t=this.source.system){return tt(this.event),void 0!==this.delay?t.scheduleTimer(this.source,B(this),this.delay):t.sendEvent(this.source,this.target,this.event)}function $t(t=this.source.system){return t.cancelTimer(this.source,H(this))}function St(t,e,s){if(!Yt(e))return t;if("@xstate.cancel"===e.type){const s=H(e);return t.timers?.some(t=>X(t,s))?{...t,timers:t.timers.filter(t=>!X(t,s))}:t}if("@xstate.raise"!==e.type&&"@xstate.sendTo"!==e.type||void 0===e.delay)return t;let n=t._nextTimerId??0;if(void 0===e.id&&!F(e.event)){e.seq=n++;const t=e.args;t[t.length-1]={...t[t.length-1],seq:e.seq}}const r="@xstate.raise"===e.type||e.target===s.self?"self":e.target,o={...void 0!==e.id&&{id:e.id},...void 0!==e.seq&&{seq:e.seq},delay:e.delay,type:e.type,event:e.event,target:r},i=B(o),a=t.timers??[],c=a.findIndex(t=>X(t,i));return{...t,timers:-1===c?[...a,o]:a.map((t,e)=>e===c?o:t),_nextTimerId:n}}function kt(t,e){return{...t,...e}}function At(t,e,...s){const n={action:e,args:s};return t.push(n),n}function jt(t,e){const s={...t};for(const t of Object.keys(e))s[t]=Math.max(s[t]??0,e[t]);return s}function Ot(t,s,n){if("add"===s.type)return{...t,children:{...t.children,[s.id]:s.actor},...s.counters&&{_nextActorIds:jt(t._nextActorIds,s.counters)}};const r={...t.children};let o=s.actor._parent===n.self;for(const t of Object.keys(r))r[t]===s.actor&&(o=!0,delete r[t]);if(!o)throw new Error(e(47,s.actor.id,n.self.id));return n.system._unregister(s.actor),{...t,children:r}}function It(t){if("object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action)return t}const Tt=new WeakMap,Mt=()=>({counters:new Map,explicitIds:new Set,stoppedIds:new Set});function Rt(t){Tt.set(t,Mt())}function Pt(t){return t.self._snapshot}function Nt(t,e,s){return Math.max(e.counters.get(s)??0,Pt(t)?._nextActorIds?.[s]??0)}function qt(t,e,s){let n=Nt(t,e,s);const r=Pt(t)?.children;for(;e.explicitIds.has(`${s}:${n}`)||r?.[`${s}:${n}`];)n++;return n}function Dt(t,e,s){const n=Tt.get(t)??s??Mt(),r=tn(e),o=qt(t,n,r);return n.counters.set(r,o+1),{id:`${r}:${o}`,counters:{[r]:o+1}}}function Lt(t,s,n){const r=Tt.get(t)??n??Mt(),o=Pt(t)?.children?.[s],i=void 0!==o&&!r.stoppedIds.has(s)&&"active"===o.getSnapshot().status;if(r.explicitIds.has(s)||i)throw new Error(e(67,s,t.self.id));r.explicitIds.add(s)}function Ct(t,e,s){const n=sn(e);if(!n)return;n.prefix;const r=Tt.get(t)??s??Mt(),o=Math.max(Nt(t,r,n.prefix),n.index+1);return r.counters.set(n.prefix,o),{[n.prefix]:o}}const Kt=new WeakSet;function zt(t){if("string"==typeof t)throw new Error(e(68,t))}function Wt(t,s,n,r=!1,o=!0){const i=Tt.get(t)??Mt(),a={cancel:e=>{At(s,et["@xstate.cancel"],t,"string"==typeof e?{id:e}:e)},emit:t=>{s.push(t)},log:(...e)=>{At(s,t.logger,...e)},raise:(e,r)=>{zt(e),void 0!==r?.delay?At(s,et["@xstate.raise"],t,e,r):n.push(e)},spawn:(n,r)=>{const{logic:a,src:c}=function(t,s){const n=function(t){return t.self.logic?.sources?.actors}(t);if("string"==typeof s){const t=n?.[s];if(!t)throw new Error(e(66,s));return{logic:t,src:s}}return n?{logic:s,src:nt(n,s)}:{logic:s,src:void 0}}(t,n);if(!o){const s=tn(c??a),n=r?.id??`${s}:${qt(t,Tt.get(t)??i,s)}`;return function(t){const{id:s,address:n}=t,r={ref:void 0,id:s,address:n,src:t.src,sessionId:void 0,send(){},getSnapshot:()=>S,subscribe:()=>_,on:()=>_,toJSON(){if(void 0===n)throw new Error(e(51,s));return{$actor:n}}},o=r;return r.ref=o,o}({id:n,address:Kt.has(t)?void 0:`${t.self.address}/${en(n)}`,src:c})}let u,d=r?.id;void 0===d?({id:d,counters:u}=Dt(t,c??a,i)):(Lt(t,d,i),u=Ct(t,d,i));const h=t.system.createActorRef(a,{...r,...void 0!==c&&{src:c},id:d,parent:t.self});return function(t,e,s,n){At(t,et["@xstate.spawn"],e).childUpdate={type:"add",actor:e,id:s,counters:n}}(s,h,d,u),h},sendTo:(e,n,r)=>{At(s,et["@xstate.sendTo"],t,e,n,r)},stop:e=>{if(e){const n=e;At(s,et["@xstate.stop"],t,n).childUpdate={type:"remove",actor:n},function(t,e){const s=Tt.get(t);s&&(s.stoppedIds.add(e.id),s.explicitIds.delete(e.id))}(t,n)}}};r&&Object.assign(a,{listen:(e,n,r)=>{if(!o)return{id:void 0};const i={actor:e,eventType:n,mapper:r},a=t.system.createActorRef(ut,{input:i,parent:t.self});return At(s,et["@xstate.spawn"],a),a},subscribeTo:(e,n)=>{if(!o)return{id:void 0};const r={actor:e,mappers:"function"==typeof n?{snapshot:n}:n},i=t.system.createActorRef(ht,{input:r,parent:t.self});return At(s,et["@xstate.spawn"],i),i}});let c=!1;const u=t=>(...e)=>c?Jt():t(...e);for(const t of Object.keys(a))a[t]=u(a[t]);const d=te(a,u((t,...e)=>{"function"==typeof t&&At(s,t,...e)}));return Vt.set(d,()=>{c=!0}),d}const Vt=new WeakMap;function Ut(t){Vt.get(t)?.()}function Jt(){}function Ft(t,e){switch(t){case et["@xstate.spawn"]:{const[t]=e;return{type:"@xstate.spawn",kind:"builtin",exec:gt,source:t._parent,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case et["@xstate.raise"]:{const[,t,s]=e;return{type:"@xstate.raise",kind:"builtin",exec:xt,source:e[0].self,event:t,id:s?.id,delay:s?.delay}}case et["@xstate.sendTo"]:{const[,t,s,n]=e;return{type:"@xstate.sendTo",kind:"builtin",exec:Et,source:e[0].self,target:t,event:s,id:n?.id,delay:n?.delay}}case et["@xstate.cancel"]:{const[,t]=e;return{type:"@xstate.cancel",kind:"builtin",exec:$t,source:e[0].self,...t}}case et["@xstate.stop"]:{const[,t]=e;return{type:"@xstate.stop",kind:"builtin",exec:wt,source:e[0].self,actor:t,id:t.id}}default:return}}function Bt(t){const e=[t];return{kind:"builtin",exec:_t,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function Ht(t){const e=[t];return{kind:"builtin",exec:gt,type:f,source:t._parent,params:void 0,args:e,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}function Xt(t,e,s){const n=[t,e,s,{}];return{kind:"builtin",exec:Et,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:n}}function Gt(t,s){if("done"!==s.status&&"error"!==s.status)throw new Error(e(69,t.self.id,s.status));const n="done"===s.status?{status:"done",output:s.output,error:void 0}:{status:"error",output:void 0,error:s.error},r=[t.self,n];return{kind:"builtin",exec:bt,type:l,source:t.self,actor:t.self,id:t.self.id,...n,params:void 0,args:r}}function Qt(t,e,[s,n]){const r="done"===s.status||"error"===s.status,o="done"===e?.status||"error"===e?.status,i=n.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===l);return!r||o||i?[s,n]:[s,[...n,Gt(t,s)]]}function Yt(t){return"builtin"===t.kind}function Zt(t,e,s,n){let r=t;const o=[];for(const t of n){const e="function"==typeof t,n=It(t);let i=n?.args;if(n?.action===et["@xstate.sendTo"]&&(void 0===n.args[1]||"string"==typeof n.args[1])){const t=n.args[1],e=void 0!==t&&Object.hasOwn(r.children,t)?r.children[t]:void 0;if(!e){o.push(vt(s,n.args[2],t));continue}i=[n.args[0],e,...n.args.slice(2)]}const a=e?t:!!n&&n.action.bind(null,...i);let c;if("object"==typeof t&&null!==t){const{type:e,childUpdate:s,...n}=t;c=n}if(n?.childUpdate&&(r=Ot(r,n.childUpdate,s)),!a||!("resolve"in a)){const a="object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action?Ft(t.action,i):void 0,u="object"==typeof t&&null!==t&&!n,d={kind:a?"builtin":u?"emit":"action",type:"object"==typeof t?"action"in t&&"function"==typeof t.action?t.action.name??"(anonymous)":t.type:t.name||"(anonymous)",params:a?void 0:c,args:"object"==typeof t&&"action"in t?i:[],...a?{}:u?{source:s.self,event:t}:{action:n?.action??(e?t:void 0)},...a?{}:{exec:u?pt:ft},...a};r=St(r,d,s),o.push(d);continue}}return[r,o]}function te(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:ee,emit:ee,log:ee,raise:ee,spawn:se,sendTo:ee,stop:ee,listen:se,subscribeTo:se,...t}),s}const ee=()=>{},se=()=>({});function ne(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 r=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(!r?.groups)return;const{weeks:o,days:i,hours:a,minutes:c,seconds:u}=r.groups;if(!(o||i||a||c||u))return;const d=t=>t?Number(t.replace(",",".")):0;return 7*d(o)*24*60*60*1e3+24*d(i)*60*60*1e3+60*d(a)*60*1e3+60*d(c)*1e3+1e3*d(u)}function re(t){if(void 0!==t)return"number"==typeof t?t:ne(t)}const oe=new WeakMap,ie=new WeakMap,ae=new Map;function ce(t){const e=t._peekKeyedActors;return e?e.call(t)??ae:t.keyedActors}function ue(t){t._snapshotVersion++}function de(t){return t._snapshotVersion}function he(t,s,n){const r=function(t,e){if(e){const t=new Map(e.children);return e.root?.sessionId&&t.set(e.root.sessionId,e.root),t}return new Map(t.children)}(t,n),o=new Map(n?.keyedActors??ce(t)),i=new WeakMap,a=Object.assign(Object.create(t),{children:r,keyedActors:o,reverseKeyedActors:i,_snapshot:{...n?.snapshot??t._snapshot},_snapshotVersion:n?.sourceVersion??t._snapshotVersion,_register:(t,e)=>(r.set(t,e),ue(a),t),_unregister:t=>{t.sessionId&&r.delete(t.sessionId);const e=i.get(t);void 0!==e&&o.get(e)===t&&o.delete(e),i.delete(t),ue(a)},_set:(t,s)=>{const n=o.get(t);if(n&&n!==s)throw new Error(e(45,String(t)));o.set(t,s),i.set(s,t),ue(a)},get:t=>o.get(t),getAll:()=>Object.fromEntries(o),onEmitted:e=>t.onEmitted(e),_notifyEmitted:(e,s)=>t._notifyEmitted(e,s),_hasInspectionObservers:()=>!1,_sendInspectionEvent:()=>{}});for(const[t,e]of o)e&&i.set(e,t);for(const t of Object.values(s)){if(!t)continue;t.sessionId&&r.set(t.sessionId,t);const e=t.registryKey;e&&(o.set(e,t),i.set(t,e))}return a}function fe(t){const e=oe.get(t);if(e)return e;const s=ie.get(t);if(!s)return;const n=s();return oe.set(t,n),ie.delete(t),n}function pe(t,e){const s=oe.get(t);if(s)return oe.set(e,s),!0;const n=ie.get(t);return!!n&&(ie.set(e,n),!0)}function le(t,e,s=e.system,n){ie.delete(t);const r=de(s),o=n?fe(n):void 0,i=o?.actor===e?o:fe(t);if(i?.actor===e&&i.systemState.sourceSystem===s&&i.systemState.sourceVersion===r)return void oe.set(t,i);const a=function(t){const e=t._getRootActor?.(),s=t._peekChildren?.();if(!e&&!s){if(t._getRootActor&&t._peekChildren)return{};const e=new Map(t.children);return e.size?{children:e}:{}}return s?.size?{children:new Map(t.children)}:e?{root:e}:{}}(s);let c=a.children;const u=ce(s);let d=u.size?new Map(u):ae;for(const e of Object.values(function(t){return"children"in t&&t.children?t.children:{}}(t))){if(!e)continue;e.sessionId&&(c??=new Map).set(e.sessionId,e);const t=e.registryKey;t&&(d===ae&&(d=new Map),d.set(t,e))}oe.set(t,{actor:e,systemState:{...a,children:c,keyedActors:d,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:r}})}const ye=Symbol();function ve(t){return!!t[ye]}function me(t){return ve(t)?t._parent:t.self._parent}function ge(t,e){if(!ve(e)){const s=t,n=e.self;return s.self=n,s.system=e.system,s.parent=n._parent,s}return Object.defineProperties(t,{self:{enumerable:!0,get:()=>e.self},system:{enumerable:!0,get:()=>e.system},parent:{enumerable:!0,get:()=>me(e)}}),t}function _e(t,e,s=!0){const n=$e(t);return n?(n.snapshot=e,n.materialized&&(n.materialized.self._snapshot=e)):t.self._snapshot=e,s&&e&&"object"==typeof e&&le(e,t.self),e}function we(t){return!!$e(t)||!!t.self.options?._inert}function be(t,e){_e(t,e,!1);const s=$e(t);Ee.set(e,t);const n=()=>(le(e,t.self,t.system),fe(e));return s&&(s.materialized?s.identityProvider=n:s.identityProvider??=n),function(t,e){oe.delete(t),ie.set(t,e)}(e,n),e}const xe=Symbol(),Ee=new WeakMap;function $e(t){return t[xe]}function Se(t){return $e(t).materialize()}const ke={[ye]:!0,get _parent(){const t=$e(this);return t.parentKnown?t.parent:Se(this).self._parent},get self(){return Se(this).self},get defer(){return Se(this).defer},get id(){return Se(this).id},get logger(){return Se(this).logger},get sessionId(){return Se(this).sessionId},get stopChild(){return Se(this).stopChild},get system(){return Se(this).system},get emit(){return Se(this).emit},get actionExecutor(){return Se(this).actionExecutor}};function Ae(t,e,s,n,r){const o=e?.(),i=r??o?.actor,a=i?.system,c=i&&a?he(a,s,r?void 0:o?.systemState):void 0,u=_n(t,{_inert:!0,...i?{id:i.id,_sessionId:i.sessionId}:{},...c?{_systemRef:{current:c}}:{}});return i?._parent&&(u._parent=i._parent,u._address=void 0),n&&(u._snapshot=n),Object.create(u._actorScope,{defer:{value:()=>{}},stopChild:{value:t=>t._stop()},actionExecutor:{value:()=>{}}})}function je(t,e,s,n){const r=n??(e&&"object"==typeof e?Ee.get(e):void 0),o=r?$e(r):void 0,i=e&&"object"==typeof e?function(t){return oe.get(t)}(e):void 0,a=o?.identityProvider??(e&&"object"==typeof e?function(t){const e=oe.get(t);return e?()=>e:ie.get(t)}(e):void 0),c={snapshot:e,sourceRef:a,sourceChildren:$s(e)?e.children:{},identityProvider:o?.identityProvider??a,parent:s?._parent??o?.parent??i?.actor._parent,parentKnown:!(!s&&!o?.parentKnown&&!i&&e),materialize:()=>c.materialized??=Ae(t,c.sourceRef,c.sourceChildren,c.snapshot,s)};if(!c.identityProvider&&!e){const e={},n=c.sourceRef,r=c.sourceChildren;let o,i;const a=()=>o??=Ae(t,n,r,void 0,s);c.materialize=()=>{const t=a();return void 0!==c.snapshot&&(t.self._snapshot=c.snapshot),c.materialized=t},c.identityProvider=()=>{if(i)return i;const t=a();return le(e,t.self,t.system),i=fe(e)}}const u=Object.create(ke);return u[xe]=c,u}function Oe(t,s,n){if("function"==typeof t)return t(n);const r=function(t,s){if("string"!=typeof t)return t;const n=s[t];if(void 0!==n)return n;const r=ne(t);if(void 0===r)throw new Error(e(9,t));return r}(t,s);return"function"==typeof r?r(n):r}function Ie(t,e){return t._stateInputs?.[e]}function Te(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function Me(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Re(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 Pe(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 Me(t))if(!e.has(s)){const t=He(s);for(const s of t)e.add(s)}}else for(const s of He(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 Ne(t,e){const s=Pe(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 r=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(Te(t))return t.key}const s={};for(const t of e)s[t.key]=r(t);return s};return r(t)}function qe(t,e){return"compound"===e.type?Me(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?Me(e).every(e=>qe(t,e)):"final"===e.type}const De=t=>"#"===t[0];function Le(t,e,s){const n=e.children[s];return!n||!("sessionId"in t)||(void 0===n.sessionId||n.sessionId===t.sessionId)}function Ce(t,e,s,n){const r=t.entry;t.entry=(t,e)=>{const o="function"==typeof r?r(t,e):void 0,i=void 0!==o?.context?kt(t.context,o.context):t.context;return e.raise(s(t),{delay:n({context:i,event:t.event,delays:t.delays,input:t.input})}),o};const o=t.exit;t.exit=(t,s)=>(s.cancel({event:F(e)}),"function"==typeof o?o(t,s):void 0)}function Ke(t,s,n){const r=function(t){const{cond:e,actions:s,guard:n}=t;if(void 0!==e)return'"cond"';if(void 0!==s)return'"actions"';if(void 0!==n&&"function"!=typeof n)return'an object-form "guard"';return}(n);if(r)throw new Error(e(10,s||"always",t.id,r));const o=Fs(n.target),i=n.reenter??!1,a=Je(t,o);Ue(t,a);const c={...n,target:a,source:t,reenter:i,eventType:s,toJSON:()=>ze(c)};return c}function ze(t){const{definition:e,...s}=t;return{...s,source:`#${t.source.id}`,target:t.target?.map(t=>`#${t.id}`)}}function We(t,e){for(let s=t.parent;s;s=s.parent)if(s===e)return!0;return!1}function Ve(t,e){const s=new Set;for(let e=t;e;e=e.parent)s.add(e);for(let t=e;t;t=t.parent)if(s.has(t))return t}function Ue(t,s){if(s&&!(s.length<2))for(let n=0;n<s.length;n++)for(let r=n+1;r<s.length;r++){const o=s[n],i=s[r],a=Ve(o,i);if(o===i||We(o,i)||We(i,o)||"parallel"!==a?.type)throw new Error(e(11,t.id))}}function Je(t,s){if(void 0!==s)return s.map(s=>{if("string"!=typeof s)return s;if(De(s))return t.machine.getStateNodeById(s);const n="."===s[0];if(n&&!t.parent)return Ge(t,s.slice(1));const r=n?t.key+s:s;if(!t.parent)throw new Error(e(13,s));try{return Ge(t.parent,r)}catch(s){throw new Error(e(12,t.id,s.message))}})}function Fe(t){const e=Fs(t.config.target);if(!e)return"parallel"===t.parent.type?{target:[t.parent],source:t,reenter:!1,eventType:""}:t.parent.initial;const s=e.map(e=>"string"==typeof e?Ge(t.parent,e):e);return Ue(t,s),{target:s,source:t,reenter:!1,eventType:"",to:t.config._historyDefaultTransition}}function Be(t){return"history"===t.type}function He(t){const e=new Set;!function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)for(const e of s.initial.target??[])t(e);else if("parallel"===s.type)for(const e of Me(s))t(e)}(t);for(const s of e)for(const n of Re(s,t))e.add(n);return e}function Xe(t,s){const n=t.states?.[s];if(!n)throw new Error(e(14,s,t.id));return n}function Ge(t,e){if("string"==typeof e&&De(e))return t.machine.getStateNodeById(e);const s=Ls(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=Xe(n,t)}return n}function Qe(t,s){if("string"==typeof s){const n=t.states[s];if(!n)throw new Error(e(14,s,t.id));return[t,n]}const n=Object.keys(s),r=new Array(n.length),o=[t.machine.root,t];for(let e=0;e<n.length;e++){const s=Xe(t,n[e]);r[e]=s,o.push(s)}for(let t=0;t<n.length;t++)o.push(...Qe(r[t],s[n[t]]));return o}function Ye(t,e,s,n,r,o){if("string"==typeof e){const i=Xe(t,e).next(s,n,r,o);return i&&i.length?i:t.next(s,n,r,o)}const i=Object.keys(e),a=i[0];if(1===i.length){const i=Ye(Xe(t,a),e[a],s,n,r,o);return i&&i.length?i:t.next(s,n,r,o)}const c=[];for(const a of i){const i=e[a];if(!i)continue;const u=Ye(Xe(t,a),i,s,n,r,o);u&&c.push(...u)}return c.length?c:t.next(s,n,r,o)}function Ze(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function ts(t,e){for(const s of t)if(Ze(s,e))return!0;return!1}function es(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 r=t instanceof Set?t:new Set(t);for(const t of e)if(r.has(t))return!0;return!1}function ss(t,e,s,n){const r=new Set,o=new Map,i=t=>{let r=o.get(t);return r||(r=as([t],e,s,n),o.set(t,r)),r};for(const e of t){let t=!1;const s=new Set;for(const n of r)if(es(i(e),i(n))){if(!Ze(e.source,n.source)){t=!0;break}s.add(n)}if(!t){for(const t of s)r.delete(t);r.add(e)}}return Array.from(r)}function ns(t,e,s,n,r){let o;return(i,a)=>{if(!i.to&&!a)return{targets:i.target,context:void 0,reenter:i.reenter,actions:void 0,internalEvents:void 0,input:void 0};let c=o?.get(i);return c||(c=ds(i,t,e,s,{resolveActions:n,selectionResult:r?.get(i)}),(o??=new Map).set(i,c)),c}}function rs(t,e,s){const n=e.historyValue,{targets:r}=s(t);if(!r)return[];const o=new Set;for(const t of r)if(Be(t))if(n[t.id])for(const e of n[t.id])o.add(e);else for(const n of rs(Fe(t),e,s))o.add(n);else o.add(t);return[...o]}function os(t,e){let s=t;for(;"parallel"===s.type;){const t=Me(s).find(t=>e.every(e=>e===t||Ze(e,t)));if(!t)break;s=t}return s}function is(t,e,s){const n=rs(t,e,s),{targets:r,reenter:o}=s(t);if(t._transitionDomain){if("internal"===t._transitionDomain&&"compound"===t.source.type&&n.every(e=>Ze(e,t.source)))return t.source;const[e,...s]=n.concat(t.source);for(const t of Re(e,void 0))if("compound"===t.type&&s.every(e=>Ze(e,t)))return t;return}if(!(r?.some(Be)&&n.some(e=>e===t.source))&&n.every(e=>e===t.source||Ze(e,t.source)))return o?t.source:os(t.source,n);const[i,...a]=n.concat(t.source);for(const t of Re(i,void 0))if(a.every(e=>Ze(e,t)))return o?t:os(t,n);return o?void 0:os(t.source.machine.root,n)}function as(t,e,s,n){const r=new Set;for(const o of t){const{targets:t,reenter:i}=n(o);if(t?.length){const t=is(o,s,n);i&&o.source===t&&r.add(t);for(const s of e)Ze(s,t)&&r.add(s)}}return[...r]}function cs(t,e,s,n,r){t.machine._microstepHooks?.begin(s.self);const o=[...He(t)],i=new Set,a=t=>{if("compound"===t.type){i.add(t);for(const e of t.initial.target??[])a(e)}else if("parallel"===t.type)for(const e of Me(t))a(e)};return a(t),us([{target:o.filter(t=>!o.some(e=>e!==t&&Ze(e,t))),source:t,reenter:!0,eventType:null,toJSON:null,_statesForDefaultEntry:[...i]}],e,s,n,!0,r)}function us(t,s,n,r,o,i,a){const c=[],u=s.machine._microstepHooks?.drain(n.self);if(u?.length&&i.push(...u),!t.length)return[s,c];{const u=new Set(s.nodes);let d=s.historyValue;const h=s.context,f=1===t.length?t:ss(t,u,s,ns(s,r,n,!1,a)),p=ns(s,r,n,!0,a),l=f.some(t=>{const{targets:e,reenter:s}=p(t);return!!e?.length||!!s}),y=(t,e,o,i,a,c)=>{const u=[],d=[];let h;const f=Wt(n,u,d,!0),p=ve(n)?ge({context:e,event:r,output:Vs(r),children:o,actions:s.machine.sources.actions,actors:s.machine.sources.actors,guards:s.machine.sources.guards,delays:s.machine.sources.delays,input:i,stateNode:c},n):{context:e,event:r,output:Vs(r),parent:n.self._parent,self:n.self,children:o,system:n.system,actions:s.machine.sources.actions,actors:s.machine.sources.actors,guards:s.machine.sources.guards,delays:s.machine.sources.delays,input:i,stateNode:c};let l;try{l=t(p,f)}finally{Ut(f)}return ls(l,r,c.id,a),void 0!==l?.context&&(h=kt(e,l.context)),[u,h,d,l?.children]};let v=s;const m=(t,e)=>{const s=[],r=Wt(n,s,[]);for(const s of t.invoke){const t=e[s.id];t&&r.stop(t)}return s},g=()=>{const t=as(f,u,s,p);let e;t.sort((t,e)=>e.order-t.order);const r=[...u];for(const s of t)for(const t of Object.values(s.states)){if("history"!==t.type)continue;const n="deep"===t.history?t=>Te(t)&&Ze(t,s):t=>t.parent===s;e??={...d},e[t.id]=r.filter(n)}for(const e of t){const t=Ie(s,e.id),[r,o,a,d]=e.exit?y(e.exit,v.context,v.children,t,"exit",e):[[],void 0,void 0,void 0];a?.length&&i.push(...a),(o||d)&&(v=Rs(v,{...o?{context:o}:{},...d?{children:d}:{}}));const[h,f]=Zt(v,0,n,r);v=h,c.push(...f);const p=m(e,v.children);if(p.length){const[t,e]=Zt(v,0,n,p);v=t,c.push(...e)}u.delete(e)}d=e||d};!o&&l&&g();let _=v.context;const w=[],b=[],x=[];for(const t of f){const e=p(t,!0);if(t.to){const s={...t,target:e.targets,definition:t};s.toJSON=()=>ze(s),x.push(s)}else x.push(t);void 0!==e.context&&(_=kt(_,e.context)),e.actions&&w.push(...e.actions),e.internalEvents&&b.push(...e.internalEvents)}b.length&&i.push(...b);const E=()=>{const t=t=>{const e=v.machine.root;let s;if(void 0!==t.output&&t.parent){const o=i.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);s=o&&t.parent===e?o.output:Ws(t.output,v.context,r,n.self,w[t.id])}else if("parallel"===t.type){const e=i.find(e=>"xstate.done.state"===e.type&&e.stateId===t.id);s=e?.output}return void 0===e.output?t.parent===e?s:void 0:Ws(e.output,v.context,q(t.id,s),n.self)},a=new Set,h=new Set,l=new Map,m=(t,e)=>{for(const s of t)if(e&&!Ze(s,e)||a.add(s),"parallel"===s.type)for(const t of Me(s))ts(a,t)||(a.add(t),g(t))},g=t=>{if(Be(t))if(d[t.id]){const e=d[t.id];for(const t of e)a.add(t),g(t);for(const s of e)m(Re(s,t.parent),void 0)}else{const e=Fe(t),s=t.parent;h.add(s);const n=l.get(s)??[];n.push(e),l.set(s,n);const{targets:r}=p(e);for(const s of r??[])a.add(s),e===t.parent?.initial&&h.add(t.parent),g(s);for(const e of r??[])m(Re(e,t.parent),void 0)}else{if("compound"===t.type){const e=p(t.initial).targets??[];for(const t of e)Be(t)||a.add(t);h.add(t);for(const t of e)g(t);for(const s of e)m(Re(s,t),void 0);return}if("parallel"===t.type)for(const e of Me(t))ts(a,e)||(a.add(e),h.add(e),g(e))}},_=new Map;for(const t of f){const e=is(t,s,p),{targets:n,reenter:r}=p(t),o=new Set;_.set(t,o);for(const s of n??[])Be(s)||t.source===s&&t.source===e&&!r||(o.add(s),a.add(s),h.add(s)),g(s);const i=rs(t,s,p);for(const s of i){const n=Re(s,e);"parallel"===e?.type&&n.push(e),m(n,!t.source.parent&&r?void 0:e)}r&&e===t.source&&a.add(t.source)}if(o)for(const t of f[0]._statesForDefaultEntry??[s.machine.root])h.add(t);const w={};let b=!1;const x=new Set([...u].map(t=>t.id));for(const[t,e]of Object.entries(s._stateInputs??{}))x.has(t)?w[t]=e:b=!0;for(const t of f){const{targets:e,input:s}=p(t,!0);if(s&&e)for(const n of e.filter(e=>_.get(t)?.has(e)))w[n.id]=s,b=!0}const E=new Set;for(const o of[...a].sort((t,e)=>t.order-e.order)){u.add(o);const a=[];let d=v.children,f=!1;for(const t of"final"===o.type?[]:o.invoke){f=!0;let i=t.logic;"function"==typeof i&&(i=i({actors:s.machine.sources.actors,context:v.context,event:r,self:n.self}));const c="string"==typeof i?s.machine.sources.actors[i]:i;if(!c)throw new Error(e(15,"string"==typeof i?i:"inline"));const u="function"==typeof t.input?t.input({self:n.self,context:v.context,event:r,input:w[o.id],output:Vs(r)}):t.input;Lt(n,t.id);const h=n.system.createActorRef(c,{...t,src:"string"==typeof i?i:void 0,input:u,parent:n.self,syncSnapshot:!!t.onSnapshot});h._invoked=!0,a.push({action:et["@xstate.spawn"],args:[h]}),t.id&&(d={...d,[t.id]:h})}f&&(v=Rs(v,{children:d}));let p=v.context,m=!1;const g=w[o.id];if(o.entry){const[t,e,s,n]=y(o.entry,p,d,g,"entry",o);a.push(...t),s?.length&&i.push(...s),e&&(p=e,m=!0),n&&(v=Rs(v,{children:n}))}if(m&&(v=Rs(v,{context:p})),h.has(o)){const t=[o.initial,...l.get(o)??[]].filter(Boolean);for(const e of t){const{actions:t,context:s,input:o,internalEvents:c}=ds(e,v,r,n);if(t&&a.push(...t),c?.length&&i.push(...c),void 0!==s&&(v=Rs(v,{context:kt(v.context,s)})),o&&e.target)for(const t of e.target)w[t.id]=o,b=!0}}const[_,x]=Zt(v,0,n,a);if(v=_,a.length=0,c.push(...x),"final"!==o.type)continue;const $=o.parent;let S="parallel"===$?.type?$:$?.parent,k=S||o;for("compound"===$?.type&&i.push(q($.id,void 0!==o.output?Ws(o.output,v.context,r,n.self,g):void 0));"parallel"===S?.type&&!E.has(S)&&qe(u,S);){E.add(S);const t={};for(const e of Me(S)){if("final"===e.type){t[e.key]=void 0!==e.output?Ws(e.output,v.context,r,n.self,w[e.id]):void 0;continue}if("parallel"===e.type){const s=i.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);t[e.key]=s?.output;continue}const s=Me(e).find(t=>"final"===t.type&&u.has(t));t[e.key]=void 0!==s?.output?Ws(s.output,v.context,r,n.self,w[s.id]):void 0}i.push(q(S.id,t)),k=S,S=S.parent}S||(v=Rs(v,{status:"done",output:t(k)}))}b&&(v=Rs(v,{_stateInputs:w}))},[$,S]=Zt(v,0,n,w);v=$,c.push(...S),_&&_!==s.context&&(v=Rs(v,{context:_}));const k=v.machine._microstepHooks?.transitionContent?.(f,[...u]);if(k){const t=f[0].source,[e,s,r,o]=y(k,v.context,v.children,Ie(v,t.id),"transition",t);r?.length&&i.push(...r),(s||o)&&(v=Rs(v,{...s?{context:s}:{},...o?{children:o}:{}}));const[a,u]=Zt(v,0,n,e);v=a,c.push(...u)}(o||l)&&E();const A=[...u];if("done"===v.status){const t=[];A.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=Ie(v,e.id),[n,r,o,a]=y(e.exit,v.context,v.children,s,"exit",e);(r||a)&&(v=Rs(v,{...r?{context:r}:{},...a?{children:a}:{}})),t.push(...n),o?.length&&i.push(...o)}});const[e,s]=Zt(v,0,n,t);v=e,c.push(...s);const[o,a]=vs(v,r,n);v=o,c.push(...a);const[u,d]=ms(v,r,n);v=u,c.push(...d)}return d===s.historyValue&&s.nodes.length===u.size&&s.nodes.every(t=>u.has(t))?v.context!==h?[v===s?Rs(v):v,c,x]:[v,c,x]:[Rs(v,{_nodes:A,historyValue:d}),c,x]}}function ds(t,e,s,n,r){let o;const i=()=>o??=ve(n)?ge({context:e.context,event:s,output:Vs(s),value:e.value,children:e.children,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:Ie(e,t.source.id)},n):{context:e.context,event:s,output:Vs(s),value:e.value,children:e.children,system:n.system,parent:n.self._parent,self:n.self,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:Ie(e,t.source.id)};if(t.to){const o=[],a=[];let c;if(!r?.selectionResult?.reusable||!1!==r.resolveActions&&0!==r.selectionResult.operations.length){const e=Wt(n,o,a,!0,r?.resolveActions??!0),u=!1===r?.resolveActions?J(me(n),"suppress"):void 0;try{if(r?.selectionResult?.reusable){c=r.selectionResult.result;for(const t of r.selectionResult.operations)t(e)}else c=t.to(i(),e),ls(c,s,t.source.id)}finally{u?.close(),Ut(e)}}else c=r.selectionResult.result;const u=c?.target?Je(t.source,zs(c.target)):void 0,d=c?.input??("function"==typeof t.input?t.input({context:e.context,event:s,output:Vs(s)}):t.input);return{targets:u,context:c?.context,reenter:c?.reenter,actions:o,internalEvents:a,input:d}}const a="function"==typeof t.input?t.input({context:e.context,event:s,output:Vs(s)}):t.input,c="function"==typeof t.context?t.context(i()):t.context;return{targets:t.target,context:c,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:a}}class hs extends Error{constructor(t,s,n,r){super(e(16,t,s.type,n)),this.actorId=void 0,this.event=void 0,this.maxIterations=void 0,this.states=void 0,this.name="InfiniteTransitionError",this.actorId=t,this.event=s,this.maxIterations=n,this.states=r.slice()}}function fs(t,e,s,n,r=[]){if("active"!==t.status&&!r.length)return{snapshot:t,microsteps:[[t,[],[]]]};let o=t;const i=r.slice();let a=!1;function c(t){if("xstate.done.actor"!==t.type&&"xstate.error.actor"!==t.type)return;const{actorId:e,sessionId:n}=t;if(!e)return;const r=o.children[e];if(!r)return;if(void 0!==r.sessionId&&r.sessionId!==n)return;const a={...o.children};if(delete a[e],s.system._unregister(r),o=Rs(o,{children:a}),i.length){const[,t,e]=i.at(-1);i[i.length-1]=[o,t,e]}else i.push([o,[],[]])}function u(){if(a&&o===t&&(o=Rs(t,{}),i.at(-1)?.[0]===t)){const[,t,e]=i.at(-1);i[i.length-1]=[o,t,e]}const e=function(t){const e=[],s=[];for(const n of t){if(!Yt(n)||n.type!==f)continue;const{actor:t,logic:r}=n,o=Bt(t);r===ut||r===ht?e.push(o):s.push(o)}return[...e,...s]}(i.flatMap(([,t])=>t)),n=("active"===t.status||r.length>0)&&("done"===o.status||"error"===o.status);if(e.length||n){const t=n?[...e,Gt(s,o)]:e;if(i.length){const[e,s,n]=i.at(-1);i[i.length-1]=[e,[...s,...t],n]}else i.push([o,t,[]])}return{snapshot:o,microsteps:i}}function d(t,n){if(n=t[2]??n,!we(s)&&(e.type===h||(s.system._hasInspectionObservers?.()??1))){const t=s.self._collectedMicrosteps||[];t.push(...n),s.self._collectedMicrosteps=t}i.push([t[0],t[1],n])}if(e.type===p){const[t,n]=vs(o,e,s),[r,i]=ms(t,e,s);return o=Rs(r,{status:"stopped"}),d([o,[...n,...i]],[]),u()}let l=e;if(e.type===y){const t=H(e),r=t?o.timers.findIndex(e=>X(e,t)):-1;if(-1===r)return u();const i=o.timers[r],a=o.timers.filter((t,e)=>e!==r);if(o=Rs(o,{timers:a}),"@xstate.raise"===i.type)n.push(i.event),d([o,[]],[]);else{const t="self"===i.target?s.self:i.target;d([o,[Xt(s,t,i.event)]],[])}}if(l.type!==h&&l.type!==y){const e=l,r=function(t){return t.type.startsWith("xstate.error.")}(e),i=new Map,h=o.machine.getTransitionData(o,e,s,i);if(r&&!h.length)return"xstate.error.actor"!==e.type||Le(e,o,e.actorId)?(o=Rs(t,{status:"error",error:e.error}),d([o,[]],[]),c(e),u()):u();a=h.length>0;const f=us(h,t,s,l,!1,n,i);o=f[0],d(f,h),c(e)}if(!n.length&&!1===t.machine._hasEventlessTransitions)return u();let v=!0;const m=t.machine.options?.maxIterations??1/0;let g=0;const _=[];for(;"active"===o.status;){if(g++,g>m)throw new hs(s.self?.id,e,m,_);let t;_.push(o.value),_.length>5&&_.shift();let r=v?gs(o,l,s):[];const i=r.length?o:void 0,a=o.machine._microstepHooks?.drain(s.self);if(a?.length&&n.push(...a),!r.length){if(!n.length)break;l=n.shift(),t=new Map,r=o.machine.getTransitionData(o,l,s,t)}const u=us(r,o,s,l,!1,n,t);o=u[0],v=o!==i,d(u,r),c(l)}return u()}function ps(t,e,s,n,r){return!!t.to&&ys(t.to,e,s,n,r,n.machine.sources,t.source.id).enabled}function ls(t,s,n,r){if(t&&"function"==typeof t.then)throw Promise.resolve(t).catch(()=>{}),new Error(e(17,r??"transition",n,s.type))}function ys(t,e,s,n,r,o,i){let a;const c=function(t){const e=J(t),{frame:s}=e,n=[];let r=!1;const o=t=>{r||n.push(t)},i=()=>{if(!r)throw s.requiresReevaluation=!0,U},a=te({cancel:(...t)=>o(e=>e.cancel(...t)),emit:(...t)=>o(e=>e.emit(...t)),log:(...t)=>o(e=>e.log(...t)),raise:(t,e)=>{r||(zt(t),o(s=>s.raise(t,e)))},sendTo:(...t)=>o(e=>e.sendTo(...t)),stop:(...t)=>o(e=>e.stop(...t)),spawn:i,listen:i,subscribeTo:i},(...t)=>o(e=>e(...t)));return{frame:s,enqueue:a,operations:n,close(){r=!0,e.close()}}}(me(r));try{a=t(ge({context:e,event:s,output:Vs(s),value:n.value,children:n.children,actions:o.actions,actors:o.actors,guards:o.guards,delays:o.delays,input:Ie(n,i)},r),c.enqueue)}catch(t){if(t===U)return{enabled:!0,result:void 0,reusable:!1};throw t}finally{c.close()}return ls(a,s,i),c.frame.requiresReevaluation?{enabled:!0,result:void 0,reusable:!1}:{enabled:void 0!==a||c.operations.length>0,result:a,reusable:!0,operations:c.operations}}function vs(t,e,s){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return[t,[]];const r=[],o=Wt(s,r,[]);for(const t of n)o.stop(t);return Zt(t,0,s,r)}function ms(t,e,s){if(!t.timers.length)return[t,[]];const n=[],r=Wt(s,n,[]);for(const e of t.timers)r.cancel(B(e));return Zt(t,0,s,n)}function gs(t,e,s){t.machine._microstepHooks?.begin(s.self);const n=new Set,r=t.nodes.filter(Te);for(const o of r)t:for(let r=o;r;r=r.parent)if(r.always)for(const o of r.always)if(_s(o,e,t,r,s)){n.add(o);break t}return ss(Array.from(n),new Set(t.nodes),t,ns(t,e,s,!1))}function _s(t,e,s,n,r,o){if(t.matches&&!function(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}(e,t.matches))return!1;if(t._eventMatcher&&!t._eventMatcher(e,s))return!1;if(t.guard){const o=function(t,e){if(!ve(e)){const s=e.self;return Object.assign(t,{self:s,parent:s._parent})}return Object.defineProperties(t,{self:{enumerable:!0,get:()=>e.self},parent:{enumerable:!0,get:()=>me(e)}}),t}({context:s.context,event:e,output:Vs(e),children:s.children,actions:n.machine.sources.actions,actors:n.machine.sources.actors,guards:n.machine.sources.guards,delays:n.machine.sources.delays,_snapshot:s},r);if(!t.guard(o))return!1}if(t.to){const i=ys(t.to,s.context,e,s,r,n.machine.sources,t.source.id);return o?.set(t,i),i.enabled}return!0}const ws=Object.freeze({}),bs=Object.freeze([]);function xs(t){return t?.length?t:bs}function Es(t){return t===ws||t&&Object.keys(t).length?t:ws}function $s(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const Ss=function(t){if("string"==typeof t&&De(t)){const e=this.machine.getStateNodeById(t);return this.nodes.includes(e)}return qs(t,this.value)},ks=function(t){return this.tags.has(t)},As=function(t){return this.machine?._canTransition(this,t)??!1},js=function(){const{nodes:t,_stateInputs:e,tags:s,machine:n,getMeta:r,getInputs:o,toJSON:i,can:a,hasTag:c,matches:u,...d}=this;return{...d,tags:Array.from(s)}},Os=function(){const t={};for(const e of this.nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},Is=function(){return this._stateInputs};function Ts(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function Ms(t,e,s){const n={status:t.status,output:t.output,error:t.error,machine:e,context:t.context,nodes:t._nodes,value:t.value??Ne(e.root,t._nodes),tags:Ts(t._nodes),children:Es(t.children),timers:xs(t.timers),historyValue:Es(t.historyValue),_stateInputs:Es(t._stateInputs),_nextTimerId:t._nextTimerId??0,_nextActorIds:t._nextActorIds,matches:Ss,hasTag:ks,can:As,getMeta:Os,getInputs:Is,toJSON:js};return s&&le(n,s),n}function Rs(t,e={}){const s={...t,...e};if((e._nodes??t.nodes)===t.nodes){const e={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:Es(s.children),timers:xs(s.timers),historyValue:Es(s.historyValue),_stateInputs:Es(s._stateInputs),_nextTimerId:s._nextTimerId??0,_nextActorIds:s._nextActorIds,matches:Ss,hasTag:ks,can:As,getMeta:Os,getInputs:Is,toJSON:js};return pe(t,e),e}const n=Ms({...s,value:void 0},t.machine);return pe(t,n),n}function Ps(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 Ns(t,s,n="context",r=[]){let o;r.push(t);for(const i in t){const a=t[i];if(a&&"object"==typeof a)if(Hs(a))o??=Array.isArray(t)?t.slice():{...t},o[i]={$actor:a.address};else{const c=Array.isArray(t)?`${n}[${i}]`:`${n}.${i}`;if(r.includes(a))throw new Error(e(44,s(),c));const u=Ns(a,s,c,r);u!==a&&(o??=Array.isArray(t)?t.slice():{...t},o[i]=u)}}return r.pop(),o??t}function qs(t,e){const s=Cs(t),n=Cs(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&qs(s[t],n[t]))}function Ds(t,s){if(s.startsWith("xstate.")||s.startsWith("@xstate."))throw new Error(e(37,t,s))}function Ls(t){if(Us(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]?"\\.":t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function Cs(t){if($s(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}(Ls(t))}function Ks(t){return Us(t)?t:[t]}function zs(t){return void 0===t?[]:Ks(t)}function Ws(t,e,s,n,r){if("function"==typeof t){return t({context:e,event:s,output:Vs(s),self:n,input:r})}return t}function Vs(t){if(function(t){return"xstate.done.actor"===t.type||"xstate.done.state"===t.type}(t)){return t.output}}function Us(t){return Array.isArray(t)}function Js(t,s,n){return Ks(t).map(t=>{if("string"==typeof t)throw new Error(e(38,s,n,t));return void 0===t?{target:void 0}:"function"==typeof t?{to:t}:t})}function Fs(t){if(void 0!==t&&""!==t)return zs(t)}function Bs(t,e,s){const n="object"==typeof t,r=n?t:void 0;return{next:(n?t.next:t)?.bind(r),error:(n?t.error:e)?.bind(r),complete:(n?t.complete:s)?.bind(r),...n&&t.passive?{passive:!0}:{}}}function Hs(t){return"sessionId"in t&&"send"in t&&"ref"in t}function Xs(t,s,n){const r=[];for(const t of s)for(const e of t.invoke)e.id===n&&r.push(e);if(1!==r.length)throw new Error(e(39,n));const o=r[0].logic;if("string"==typeof o){const s=t.sources.actors[o];if(!s)throw new Error(e(29,n,o));return s}if("function"==typeof o)throw new Error(e(40,n));return o}function Gs(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],r=n[t];if("*"===e){return t===s.length-1}if(e!==r)return!1}return!0}let Qs,Ys=0;function Zs(){return Qs??=function(){let t;try{t=globalThis.crypto}catch{}if(t?.getRandomValues)try{const e=new Uint32Array(4);return t.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(7,"0")).join("")}catch{}if(t?.randomUUID)try{return t.randomUUID().replaceAll("-","")}catch{}return`xstate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}(),`${Qs}:${(Ys++).toString(36)}`}function tn(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length?e:"x"}function en(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function sn(t){const e=t.lastIndexOf(":");if(e<=0||e===t.length-1)return;const s=Number(t.slice(e+1));return Number.isSafeInteger(s)&&s>=0?{prefix:t.slice(0,e),index:s}:void 0}function nn(t,e){return`${t?t.address:""}|${e}`}function rn(t,e,s){const n=t._snapshot._nextActorIds;(n[e]??0)>=s||(t._snapshot._nextActorIds={...n,[e]:s},ue(t))}const on=Object.freeze({});function an(t,e){return Q(t,e)}function cn(t,e){return t.getSnapshot()?.timers?.find(t=>X(t,e))}class un{get children(){const t=this._children??=new Map;return this._getRootActor()&&t.set(this._rootActor.sessionId,this._rootActor),t}set children(t){this._children=t}_getRootActor(){return this._rootActor._isRunning()?this._rootActor:void 0}_peekChildren(){return this._children}get keyedActors(){return this._keyedActors??=new Map}set keyedActors(t){this._keyedActors=t}get reverseKeyedActors(){return this._reverseKeyedActors??=new WeakMap}set reverseKeyedActors(t){this._reverseKeyedActors=t}_peekKeyedActors(){return this._keyedActors}constructor(t,e){this._rootActor=t,this._identity={executionId:Zs(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0,this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef,this._snapshot={_scheduledTimers:on,_nextActorIds:{}}}_recordSent(t,e,s,n,r){if(!this._inspectionObservers?.size||!t)return;const o=t;(o._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:r})}schedule(t,e,s){const n=an(t,e);void 0!==this._timerMap?.[n]&&this.cancel(t,e);const r=cn(t,e);if(r){const e="self"===r.target?t:r.target;this._recordSent(t,e,r.event,s,r.id)}const o=this._clock.now?.()??Date.now(),i={source:t,delay:s,key:e,scheduledAt:o,dueAt:o+s};this._snapshot._scheduledTimers===on&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[n]=i,ue(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[n],delete this._snapshot._scheduledTimers[n],ue(this),this._deliver(t,t,{type:y,...e})},s);(this._timerMap??={})[n]=a}cancel(t,e){const s=an(t,e),n=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==on&&delete this._snapshot._scheduledTimers[s],ue(this),void 0!==n&&this._clock.clearTimeout(n)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.key)}}_deliver(t,e,s){O(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),ue(this),t}_getByAddress(t){const e=this._getRootActor();if(e?.address===t)return e;for(const e of this._children?.values()??[])if(e.address===t&&e._isRunning())return e}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1);const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&ue(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,s){const n=this._keyedActors?.get(t);if(n&&n!==s)throw new Error(e(45,String(t)));(this._keyedActors??=new Map).set(t,s),(this._reverseKeyedActors??=new WeakMap).set(s,t),n!==s&&ue(this)}inspect(t){const e=Bs(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}onRejectedEvent(t){const e=e=>t(e);return(this._rejectionListeners??=new Set).add(e),{unsubscribe:()=>{this._rejectionListeners?.delete(e)}}}onEmitted(t){const e=e=>t(e);return(this._emissionListeners??=new Set).add(e),{unsubscribe:()=>{this._emissionListeners?.delete(e)}}}_notifyEmitted(t,e){const s=this._emissionListeners;if(!s?.size)return;const n={actorRef:t,event:e};for(const t of Array.from(s))try{t(n)}catch(t){z(t)}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>{try{t.next?.(e)}catch(t){z(t)}})}spawnActor(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);M(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);T(t,e)}sendEvent(t,e,s){if(b(e)){const n=$(this,e);if(n)e=n;else if(this._getByAddress(e.$actor)||!this.runtime?.sendEvent)return this.deadLetter(t,void 0,s,"missingTarget",{targetId:x(e.$actor),error:E(e)})}if(I(t,e,s))return;this._recordSent(t,e,s);const n=this.runtime?.sendEvent;if(n)return n(t,e,s);this._deliver(t,e,s)}emitEvent(t,e){const s=this.runtime?.emitEvent;if(s)return s(t,e);t._emit(e)}deadLetter(t,e,s,n,r){const o=this._rejectionListeners;if(o?.size){const i={event:s,targetRef:e,targetId:e?.id??r?.targetId,sourceRef:t,eventOrigin:t?"actor":"external",reason:n,issues:r?.issues,error:r?.error};for(const t of[...o])try{t(i)}catch(t){z(t)}}const i=this.runtime?.deadLetter;if(i)return i(t,e,s,n,r)}runStep(t,e,s){const n=this.runtime?.runStep;return n?n(t,e,s):j(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const n=this.runtime?.scheduleTimer;if(n){const r=cn(t,e);if(r){const e="self"===r.target?t:r.target;this._recordSent(t,e,r.event,s,r.id)}return n(t,e,s)}this.schedule(t,e,s)}cancelTimer(t,e){const s=this.runtime?.cancelTimer;if(s)return s(t,e);this.cancel(t,e)}cancelAllTimers(t){const e=this.runtime?.cancelAllTimers;if(e)return e(t);this.cancelAll(t)}_relay(t,e,s){if(!function(t){let e=!1,s=!1;for(const n of V)n.parent===t&&(n.requiresReevaluation=!0,e=!0,s||="abort"===n.mode);if(s)throw U;return e}(e))return this.sendEvent(t,e,s)}getSnapshot(){return{_scheduledTimers:{...this._snapshot._scheduledTimers}}}start(){const t=this._snapshot._scheduledTimers;let e=!0;for(const s in t){e&&(this._snapshot._scheduledTimers={},e=!1);const{source:n,dueAt:r,key:o}=t[s];this.scheduleTimer(n,o,Math.max(0,r-(this._clock.now?.()??Date.now())))}}}let dn=!1;const hn=Object.freeze([]),fn={"xstate.done.actor":!0,"xstate.error.actor":!0,"xstate.error.execution":!0,"xstate.snapshot.actor":!0,"xstate.done.state":!0,"xstate.after":!0,"xstate.timeout.state":!0,"xstate.timeout.actor":!0,[y]:!0};let pn=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const ln=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function yn(t,e){try{t?.(e)}catch(t){z(t)}}function vn(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function mn(t,e){return new gn(t,e)}class gn{get address(){return this._address??=this._parent?`${this._parent.address}/${en(this.id)}`:en(this.id)}get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this._errorObserved=!1,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=pn.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this._address=void 0,this.system=void 0,this._trigger=void 0,this._boundSend=void 0,this.src=void 0,this._deferred=void 0,this._restored=!1,this._warnedUnhandledTypes=void 0;const s=e?{...ln,...e}:ln,{clock:n,logger:r,parent:o,syncSnapshot:i,id:a,registryKey:c,inspect:u}=s;var d;this.system=o?o.system:s._systemRef?.current??function(t,e){return new un(t,e)}(this,{clock:n,logger:r,createActorRef:mn}),o||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system,s._systemRef.initialize?.()),u&&!o&&this.system.inspect(Bs(u)),s.onRejectedEvent&&!o&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(d=this.system)._identity.executionId}:${d._identity.nextSessionId++}`,this.id=function(t,e,s){if(void 0!==e){const n=sn(e);return n?rn(t,nn(s?.parent,n.prefix),n.index+1):s?.parent||rn(t,nn(void 0,e),1),e}const n=tn(s?.src),r=nn(s?.parent,n),o=t._snapshot._nextActorIds[r]??0;return rn(t,r,o+1),s?.parent||"x"===n||0!==o?`${n}:${o}`:n}(this.system,a,{parent:o,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=o,this._syncSnapshot=i,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope=this,c&&(this.registryKey=c,this.system._set(c,this)),this._collectedMicrosteps=void 0;const h=s._restore;this._restored=void 0!==h;try{if(h)this._setSnapshot(h.restore(this._actorScope));else if(e?._inert);else{const[t,e]=Qt(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}}catch(t){this._setSnapshot(h?.error?.(t)??{status:"error",output:void 0,error:t}),this._deferred&&(this._deferred.length=0)}c&&"active"!==this._snapshot.status&&this.system._unregister(this),(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_getLogger(){return this.logger}get self(){return this}get defer(){const t=t=>this._defer(t);return Object.defineProperty(this,"defer",{value:t}),t}get stopChild(){const t=t=>this._stopChild(t);return Object.defineProperty(this,"stopChild",{value:t}),t}get emit(){const t=t=>k(this,t,this.system);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===pn.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(e(47,t.id,this.id));t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=dn;try{dn=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==pn.Stopped&&this._recoverOrError(t)})}finally{dn=e}};this._processingStatus!==pn.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,le(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e,s){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t,s),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,n]=Qt(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),vn(n,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??hn)yn(e.next,t)}update(t,e){this._setSnapshot(t);const s=this._deferred;for(let e=0;e<(s?.length??0);e++){const n=s[e];try{n()}catch(e){if(s.length=0,this._tryHandleExecutionError(e,t))return;this._setErrorSnapshot(e,t),this._error(e);break}}if(s&&(s.length=0),"active"===this._snapshot.status)this._next(t);this._inspectTransition(this._snapshot,e)}_inspectTransition(t,e){(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps??hn,actions:this._collectedActions??hn,sent:this._collectedSent??hn,eventType:e.type}),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0}_flushInitialEffects(){if(!this._initialEffects?.length)return!0;this._forceDeferredActions=!0;try{return vn(this._initialEffects,this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred&&(this._deferred.length=0),this._recoverOrError(t),"active"===this._snapshot.status}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const n=Bs(t,e,s);if(this._processingStatus!==pn.Stopped)(this.observers??=new Set).add(n);else switch(this._snapshot.status){case"done":yn(n.complete);break;case"error":{const t=this._snapshot.error;n.error?(n.passive||(this._errorObserved=!0),yn(n.error,t)):z(t);break}}return{unsubscribe:()=>{this.observers?.delete(n)}}}on(t,e){let s=this.eventListeners?.get(t);return s||(s=new Set,(this.eventListeners??=new Map).set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,r)=>{const o=Bs(s,n,r);let i=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(i,n)||(i=n,o.next?.(n))},error:o.error,complete:o.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===pn.Running)return this;if(this._processingStatus===pn.Stopped){const t=this._snapshot.status;if("done"===t||"error"===t)return this;throw new Error(e(48,this.id))}this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=pn.Running,this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this._restored?(this._next(this._snapshot),this._stopProcedure(),this._complete(),this):this._flushInitialEffects()?(this.update(this._snapshot,K(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this;case"stopped":return this._stopProcedure(),this._complete(),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,K(this.options.input)):(function(t,e,s){const n=oe.get(t),r=de(s);return n?.actor===e&&n.systemState.sourceSystem===s&&n.systemState.sourceVersion+1===r&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(n.systemState.root=e,n.systemState.sourceVersion=r,!0)}(this._snapshot,this,this.system)||this._setSnapshot(this._snapshot),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0),this._restored){const t=this._snapshot.timers??[],e=!this.system._clock.now,s=Date.now();for(const n of t){const t=e&&void 0!==n.scheduledAt?Math.min(n.delay,Math.max(0,n.scheduledAt+n.delay-s)):n.delay;this.system.scheduleTimer(this,B(n),t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process({event:t,sourceRef:e}){this._lastSourceRef=e;const s=this._snapshot;let n,r;try{n=Qt(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){r={err:t}}if(r)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(r.err)||this._inspectTransition(this._snapshot,t));if(!n)return;let o=this._snapshot;try{const[r,i]=n;r!==s||i.length||!("machine"in s)||t.type===p||e&&Object.hasOwn(fn,t.type)||this._reportUnhandledEvent(t),o=r,this._setSnapshot(o),vn(i,this._actorScope),this.update(o,t)}catch(e){return void(this._recoverOrError(e,o,s)||this._inspectTransition(this._snapshot,t))}t.type===p&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){yn(()=>this.options.onUnhandledEvent?.(t,this._snapshot))}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)yn(s,t)}_terminate(t){if("done"===t.status)return this._next(this._snapshot),this._stopProcedure(),this._complete(),void(this._parent&&this.system._relay(this,this._parent,D(this.id,t.output,this.sessionId)));"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===pn.Stopped?this:(this.mailbox?.clear(),this._processingStatus===pn.NotStarted?(this._processingStatus=pn.Stopped,this.system._unregister(this),this):(this._send({type:p}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error(e(49,this.id));return this._stop()}_complete(){for(const t of this.observers??hn)yn(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||z(t)})}_error(t,e){this._stopProcedure();const s=new Set;for(const t of[this._snapshot,e]){const e=t?.children;for(const t of Object.values(e??{}))t?._parent===this&&"function"==typeof t.getSnapshot&&s.add(t)}for(const t of this.system._peekChildren?.()?.values()??[])t._parent===this&&s.add(t);for(const t of s)try{if("active"!==t.getSnapshot().status)continue;const e=this.system.stopActor(t);e&&Promise.resolve(e).catch(z)}catch(t){z(t)}if(this.observers?.size){let e=!1,s=!1;for(const n of this.observers){const r=n.error;n.passive||(e||=!r,s||=!!r),yn(r,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,L(this.id,t,this.sessionId))}_stopProcedure(){this._processingStatus===pn.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=pn.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===pn.Stopped)return void this.system.deadLetter(e,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new R(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue({event:t,sourceRef:e})}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{$actor:this.address}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[W](){return this}getSnapshot(){return this._snapshot}}function _n(t,...[s]){return function(t){if(t&&"object"==typeof t)for(const s of Object.keys(t))if(!d.has(s))throw new Error(e(8,s))}(s),new gn(t,s)}function wn(t,e){const s=t.check(e);if(s)throw s}const bn=new WeakMap;function xn(t,e,s){const n=function(t){let e=bn.get(t);return e||(e=new Map,bn.set(t,e)),e}(t);if(void 0!==e&&n.has(e))return;const r=s();n.set(e??Symbol(),{cleanup:"function"==typeof r?r:void 0})}function En(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===p)return[{...e,status:"stopped",input:void 0},[mt("@xstate.cleanup",()=>function(t){const e=bn.get(t);if(!e)return;let s;bn.delete(t);for(const{cleanup:t}of e.values())try{t?.()}catch(t){s??={error:t}}if(s)throw s.error}(n.self))]];if(s.type===g)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if(s.type===v)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if(s.type===m)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const r=[],o=Object.create(null),i={emit:t=>{r.push(function(t,e){return{kind:"emit",exec:pt,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&r.push(Xt(n,e,t))},raise:t=>{r.push(Xt(n,n.self,t))},effect:(t,i)=>{if("string"==typeof t)return void((t,i)=>{const a=e.effects&&Object.prototype.hasOwnProperty.call(e.effects,t)?e.effects[t]:void 0;(!a||s.type===h&&"active"===a.status)&&(r.push(mt("@xstate.effect",(e=n.self.system)=>xn(n.self,t,()=>i(e)),{key:t})),o[t]={status:"active"})})(t,i);const a=t;r.push(mt("@xstate.effect",(t=n.self.system)=>xn(n.self,void 0,()=>a(t))))}},a=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},i),c={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(c.context=a?.context??e.context),(a?.effects||Object.keys(o).length)&&(c.effects={...e.effects,...a?.effects,...o}),Qt(n,e,[c,r])},s=(s,r,o)=>{if(t.validator){const e=o.self._lastSourceRef,i=e?"actor":"external",a=t.validator.check({kind:"event",logic:n,event:r,eventOrigin:i});if(a)return[s,[yt(o,e,r,"invalidEvent",{issues:a.issues,error:a})]]}const i=e(s,r,o);return t.validator&&wn(t.validator,{kind:"result",logic:n,snapshot:i[0],effects:i[1]}),i},n={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,n)=>{if(!n?.restored)return;const[r,o]=s(t,K(t.input),e);Object.assign(t,r);for(const t of o)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&wn(t.validator,{kind:"input",logic:n,input:e});const o=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),i={status:"active",output:void 0,error:void 0,input:e};return void 0!==o&&(i.context=o),s({...i},K(e),r)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const $n=new WeakMap;const Sn="xstate.observable.next",kn="xstate.observable.error",An="xstate.observable.complete";const jn="xstate.async.resolve",On="xstate.async.reject";class In extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}function Tn(t){const e=t,s=En({id:e.id,validator:e.validator,schemas:e.schemas,context:void 0,run:({event:t,input:s,self:n,system:r},o)=>{switch(t.type){case jn:{const e="data"in t?t.data:t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case On:{const e="data"in t?t.data:t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===h)return o.effect((t=r)=>{const o=n,i=e=>{t.sendEvent(o,o,e)},a=new AbortController,c=e.timeout,u=re(c),d=void 0===u?void 0:r._clock.setTimeout(()=>{"active"===n.getSnapshot().status&&(a.abort(),i({type:On,data:new In(c)}))},u),h=()=>{void 0!==d&&r._clock.clearTimeout(d)},f=()=>{try{return Promise.resolve(e.run({input:s,system:r,self:n,signal:a.signal},{emit:e=>{k(o,e,t)},step:(e,s)=>t.runStep?Promise.resolve(t.runStep(o,e,s)):j(o,e,s,i)}))}catch(t){return Promise.reject(t)}};return(t.runLogic?Promise.resolve(t.runLogic(o,f)):f()).then(t=>{h(),"active"===n.getSnapshot().status&&i({type:jn,data:t})},t=>{h(),"active"===n.getSnapshot().status&&i({type:On,data:t})}),()=>{a.abort(),h()}}),{effects:{async:{status:"active"}}}}});return Object.defineProperty(s,rt,{value:{kind:"async",timeout:e.timeout}}),s}const Mn=En({context:void 0,run:()=>{}});const Rn=new WeakMap;const Pn={};class Nn{constructor(t,s){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.schemas=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._candidateCache=void 0,this.parent=s._parent,this.key=s._key,this.machine=s._machine,this.parent&&function(t){for(let e=0;e<t.length;e++)if("\\"===t[e])e++;else if("."===t[e])return!0;return!1}(this.key))throw new Error(e(57,this.key));this.path=this.parent?this.parent.path.concat(this.key):[];const n=this.config.states?Object.keys(this.config.states)[0]:void 0;this.id=this.config.id||(this.machine.id?[this.machine.id,...this.path]:this.path).join("."),this.type=this.config.type||(void 0!==n?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.schemas=this.config.schemas,function(t){const s=t.config;if("history"===t.type&&!("string"==typeof s.target&&s.target.trim().length>0||Array.isArray(s.target)&&s.target.length>0&&s.target.every(t=>"string"==typeof t&&t.trim().length>0)))throw new Error(e(60,t.id));if("choice"!==t.type)return;if("function"!=typeof s.choice)throw new Error(e(61,t.id))}(this);if(this.machine.idMap.get(this.id))throw new Error(e(58,this.id));if(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 r=0;r<n.length;r++){const o=n[r],i=e(t[o],o,t,r);"__proto__"===o?Object.defineProperty(s,o,{value:i,enumerable:!0,configurable:!0,writable:!0}):s[o]=i}return s}(this.config.states,(t,e)=>new Nn(t,{_parent:this,_key:e,_machine:this.machine})):Pn,"compound"===this.type&&!this.config.initial)throw new Error(e(59,this.id));this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=zs(t.tags).slice(),this.invoke=zs(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,r=`${this.id}:${e}`;const o=t.id??r;return{...t,src:"string"==typeof s?s:void 0,logic:s,id:o,registryKey:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,r=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===r.length)return[];const o=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;o.push({event:P(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0,name:`after.${s}`})}var i;void 0!==s&&n&&o.push({event:(i=t.id,{type:"xstate.timeout.state",stateId:i}),delay:s,transitions:n,fromDelaysMap:!0,name:"onTimeout"});for(const t of r)o.push({event:N(t.id),resolveEvent:({children:e})=>N(t.id,e[t.id]?.sessionId),eventMatcher:(e,s)=>Le(e,s,t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1,name:"invoke.onTimeout"});const a=[];for(const{event:e,resolveEvent:s,eventMatcher:n,delay:r,transitions:i,fromDelaysMap:c,name:u}of o){Ce(t,e,s??(()=>e),e=>Oe(r,c?e.delays:{},{context:e.context,event:e.event,stateNode:t,input:e.input}));const{type:o,...d}=e;for(const e of Js(i,u,t.id))a.push({...e,matches:{...e.matches,...Object.fromEntries(Object.entries(d).filter(([,t])=>void 0!==t))},event:o,delay:r,_eventMatcher:n})}return a.map(e=>({...Ke(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const s=new Map,n=(t,e)=>{s.set(t,[...s.get(t)??[],...e])};if(t.config.on)for(const n of Object.keys(t.config.on)){if(""===n)throw new Error(e(63,t.id));const r=t.config.on[n];s.set(n,qn(t,n,r,e=>Ke(t,n,e)))}if(t.config.onDone){const e="xstate.done.state";n(e,qn(t,"onDone",t.config.onDone,s=>Ke(t,e,{...s,matches:{...s.matches,stateId:t.id}})))}if(t.config.onError){const e="xstate.error.*";s.set(e,qn(t,"onError",t.config.onError,s=>Ke(t,e,s)))}const r=(e,s,n)=>Ke(t,e,{matches:{actorId:n},_eventMatcher:(t,e)=>Le(t,e,n),to:(t,e)=>(e.cancel(s),{})}),o=(e,s,n)=>{const{target:r,to:o,reenter:i,...a}=s;return Ke(t,e,{...a,reenter:i,to:(t,e)=>{if(o){let s=!1;const r=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const r=Reflect.get(t,e,n);return"function"!=typeof r?r:(...e)=>(s=!0,r.apply(t,e))}}),i=o(t,r);return(void 0!==i||s)&&e.cancel(n),i}return e.cancel(n),{target:r,reenter:i}}})};for(const e of t.invoke){const s=t=>({...t,matches:{...t.matches,actorId:e.id},_eventMatcher:(t,s)=>Le(t,s,e.id)}),i=void 0!==e.timeout?{event:{type:"xstate.timeout.actor",actorId:e.id}}:void 0;if(e.onDone){const a="xstate.done.actor",c=qn(t,"invoke.onDone",e.onDone,e=>{const n=s(e);return i?o(a,n,i):Ke(t,a,n)});i&&c.push(r(a,i,e.id)),n(a,c)}else if(i){const t="xstate.done.actor";n(t,[r(t,i,e.id)])}if(e.onError){const r="xstate.error.actor";n(r,qn(t,"invoke.onError",e.onError,e=>{const n=s(e);return i?o(r,n,i):Ke(t,r,n)}))}if(e.onSnapshot){const r="xstate.snapshot.actor";n(r,qn(t,"invoke.onSnapshot",e.onSnapshot,e=>Ke(t,r,s(e))))}}for(const e of t.after){let t=s.get(e.eventType);t||(t=[],s.set(e.eventType,t)),t.push(e)}return s}(this),"choice"===this.type?this.always=function(t){const s=t.config.choice,n=s=>{if(!s||void 0===s.target)throw new Error(e(62,t.id));return s};return[Ke(t,"",{to:t=>n(s(t))})]}(this):this.config.always&&(this.always=qn(this,"always",this.config.always,t=>Ke(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 function(t,e,s){let n=Rn.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Rn.set(t,n)),n[e]}(this,"initial",()=>function(t,s){const n="object"==typeof s&&null!==s?s.target:s,r="object"==typeof s&&null!==s?s.input:void 0,o="object"==typeof s&&null!==s?s.to:void 0,i="object"==typeof s&&null!==s?s.meta:void 0,a="object"==typeof s&&null!==s?s.description:void 0,c=Array.isArray(n)?n:n?[n]:[],u=c.map(e=>e.startsWith("#")?t.machine.getStateNodeById(e.slice(1)):t.states[e]);if(u.some(t=>!t))throw new Error(e(64,c.find((t,e)=>!u[e]),t.id));const d={source:t,target:u.length?u:void 0,input:r,to:o,meta:i,description:a};return d}(this,this.config.initial))}next(t,e,s,n){if("final"===this.type)return;let r=this._candidateCache?.get(e.type);r||(r=function(t,e){const s=t.transitions.get(e.type)??[],n=[...t.transitions.keys()].filter(t=>t!==e.type&&Gs(e.type,t)).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return s.length?[...s,...n]:n}(this,e),(this._candidateCache??=new Map).set(e.type,r));for(const o of r){if(_s(o,e,t,this,s,n))return[o]}}}function qn(t,e,s,n){const r=Js(s,e,t.id),o=new Array(r.length);for(let t=0;t<r.length;t++)o[t]=n(r[t]);return o}class Dn extends Error{constructor(t){super(t),this.name="InvalidSnapshotError"}}function Ln(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function Cn(t){return Ln(t)&&"function"==typeof t.transition&&"function"==typeof t.getInitialSnapshot}function Kn(t,s,n,r){if("string"==typeof s){if(!n.states[s])throw new Dn(e(21,r.concat(s).join(".")));return}const o=t=>new Dn(e(22===t?22:23,r.join(".")));if(!s||"object"!=typeof s||Array.isArray(s))throw o(22);const i=Object.keys(s);if(i.length>1&&"parallel"!==n.type)throw o(23);for(const o of i){const i=n.states[o];if(!i)throw new Dn(e(21,r.concat(o).join(".")));Kn(t,s[o],i,r.concat(o))}}function zn(t,s){if(!Ln(s))throw new Dn(e(24,t.id));if(void 0===s.value)throw new Dn(e(25,t.id));Kn(t,s.value,t.root,[]);const n=Array.from(Pe(Qe(t.root,s.value)));if(!Ln(s.children))throw new Dn(e(26));const r=new Map;for(const[o,i]of Object.entries(s.children)){if(!Ln(i)||void 0!==i.remote&&"boolean"!=typeof i.remote||void 0!==i.address&&"string"!=typeof i.address||void 0!==i.syncSnapshot&&"boolean"!=typeof i.syncSnapshot||void 0!==i.registryKey&&"string"!=typeof i.registryKey||void 0!==i.incarnation&&"string"!=typeof i.incarnation||void 0!==i.snapshot&&!Ln(i.snapshot))throw new Dn(e(27,o));if(!0!==i.remote){if(void 0!==i.src&&"string"!=typeof i.src&&!Cn(i.src))throw new Dn(e(27,o));try{const s=void 0===i.src?Xs(t,n,o):"string"==typeof i.src?Object.hasOwn(t.sources.actors,i.src)?t.sources.actors[i.src]:void 0:i.src;if(!s)throw new Dn(e(29,o,"string"==typeof i.src?i.src:"<inline>"));r.set(o,s)}catch(t){if(t instanceof Dn)throw t;throw new Dn(t instanceof Error?t.message:e(30,o))}}else if("string"!=typeof i.address||"string"!=typeof i.src)throw new Dn(e(28,o))}if(void 0!==s.timers&&!Array.isArray(s.timers))throw new Dn(e(31));for(const t of s.timers??[]){if(!Ln(t)||"number"!=typeof t.delay||"@xstate.raise"!==t.type&&"@xstate.sendTo"!==t.type||!Ln(t.event)||"string"!=typeof t.event.type||void 0!==t.id&&"string"!=typeof t.id||void 0!==t.seq&&"number"!=typeof t.seq||void 0!==t.scheduledAt&&"number"!=typeof t.scheduledAt||!("string"==typeof t.target||Ln(t.target)&&"parent"===t.target.type||b(t.target)))throw new Dn(e(32));if("string"==typeof t.target&&"self"!==t.target&&!Object.hasOwn(s.children,t.target))throw new Dn(e(33,t.target))}return{nodes:n,childLogics:r}}let Wn,Vn;function Un(){if(Vn)return Vn;const t=Wn??=_n({transition:t=>[t,[]],initialTransition:()=>[{status:"active",output:void 0,error:void 0},[]],getInitialSnapshot:()=>({status:"active",output:void 0,error:void 0}),getPersistedSnapshot:t=>t});return Vn={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},Kt.add(Vn),Vn}class Jn{constructor(t,s,n){if(this.config=t,this.validator=n,this._internalEventType=void 0,this._transitionMetaType=void 0,this._inputType=void 0,this._actionMap=void 0,this._actorMap=void 0,this._stateSchema=void 0,this.version=void 0,this.schemas=void 0,this.sources=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._hasEventlessTransitions=void 0,this._microstepHooks=void 0,this._json=void 0,void 0!==t.version&&!t.id)throw new Error(e(18,t.version));this.id=t.id??"",this.sources={actors:t.actors??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...s},this.version=this.config.version,this.schemas=this.config.schemas,this.internalEventDescriptors=Object.keys(this.schemas?.internalEvents??{}),this.options={...this.config.options},this.transition=this.transition.bind(this),this.initialTransition=this.initialTransition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.start=this.start.bind(this),this.root=new Nn(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 r=n.config.id,o=n.config.route,i=({event:t})=>t.to===`#${r}`;if("function"==typeof o)return e.push(Ke(t,"xstate.route",{guard:i,to:t=>{const e=o(t);if(e)return{...!0===e?{}:e,target:`#${r}`}}})),void(n.states&&s(n.states));const{guard:a,...c}=o,u={...c,guard:i,target:`#${r}`};e.push(Ke(t,"xstate.route",u))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.root._refreshEventMetadata(),this._hasEventlessTransitions=Array.from(this.idMap.values()).some(t=>!!t.always?.length),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:r}=this.sources,o=new Jn(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...r,...t.delays}},this.validator);return o._json=this._json,o.internalEventDescriptors=this.internalEventDescriptors,o._microstepHooks=this._microstepHooks,o}resolveState(t){const e=(s=this.root,n=t.value,Ne(s,Pe(Qe(s,n))));var s,n;const r=Pe(Qe(this.root,e));return Ms({_nodes:[...r],value:e,context:t.context||{},children:{},status:qe(r,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const n=!s,r=s??je(this,t);if(n&&_e(r,t,!1),this.validator){const n=s&&s.self._lastSourceRef,o=n?"actor":"external",i=this.validator.check({kind:"event",logic:this,event:e,eventOrigin:o});if(i)return[t,[yt(r,n,e,"invalidEvent",{issues:i.issues,error:i})]]}Rt(r);const o=this._transitionFast(t,e,r);if(o){n&&_e(r,o,!1);const e=n&&o!==t?be(r,o):this._attachPureActorRef(o,r);return this.validator&&wn(this.validator,{kind:"result",logic:this,snapshot:e,effects:[]}),[e,[]]}const{snapshot:i,microsteps:a}=fs(t,e,r,[]);n&&_e(r,i,!1);const c=n?i===t?i:be(r,i):this._attachPureActorRef(i,r),u=this._collectEffects(a);return this.validator&&wn(this.validator,{kind:"result",logic:this,snapshot:c,effects:u}),[c,u]}_collectEffects(t){return t.flatMap(([,t])=>t)}_attachPureActorRef(t,e,s=!1){return we(e)||s&&e.self._actorScope===e&&void 0===e.self._snapshot||le(t,e.self,e.system),t}_transitionFast(t,e,s){if("active"!==t.status||"string"!=typeof t.value||this.root.always?.length)return;const n=this.root.states[t.value];if(!n||"atomic"!==n.type||n.exit||n.invoke.length||n.always?.length||n.after?.length)return;const r=n.transitions.get(e.type);if(1!==r?.length)return;const o=r[0];if(o.guard||o.actions||o.to||o.reenter||o.input||"function"==typeof o.context||o.target&&1!==o.target.length)return;const i=o.target?.[0]??n,a=i!==n;if(i.parent!==this.root||"atomic"!==i.type||a&&(i.entry||i.invoke.length||i.always?.length||i.after?.length))return;const c=void 0!==o.context?{...t.context,...o.context}:t.context;if(!we(s)&&(s.system._hasInspectionObservers?.()??1)){const t=s.self._collectedMicrosteps||[];t.push(o),s.self._collectedMicrosteps=t}const u=t._stateInputs[this.root.id];return Rs(t,{...c!==t.context?{context:c}:{},...a?{_nodes:[this.root,i],_stateInputs:u?{[this.root.id]:u}:{}}:{}})}microstep(t,e,s){const{microsteps:n}=fs(t,e,s,[]),r=new Array(n.length);for(let t=0;t<n.length;t++)r[t]=n[t][0];return r}getTransitionData(t,e,s,n){return this._microstepHooks?.begin(s.self),Ye(this.root,t.value,t,e,s,n)||[]}isInternalEventType(t){if(t===y)return!0;for(const e of this.internalEventDescriptors)if(Gs(t,e))return!0;return!1}_canTransition(t,e){if("active"!==t.status)return!1;const s=Un(),n=this.getTransitionData(t,e,s);if(!n?.length)return!1;for(const r of n){if(void 0!==r.target)return!0;const n=ds(r,t,e,s,{resolveActions:!1});if(n.targets?.length||n.context||ps(r,t.context,e,t,s))return!0}return!1}getExecutionErrorEvent(t,e){if("active"===t?.status&&t.nodes?.some(t=>t.config.onError))return C("execution",e)}_getPreInitialState(t,e){const{context:s}=this.config,n=Ms({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const r={},o=function(t,e,s){return(n,r)=>{const o=nt(e,n),i=r?.id??Dt(t,o??n).id;void 0!==r?.id&&(Lt(t,r.id),Ct(t,r.id));const a=t.system.createActorRef(n,{id:i,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:o??n,registryKey:r?.registryKey});return s[a.id]=a,a}}(t,this.sources.actors,r),i=s(function(t,e){return ve(e)?(Object.defineProperty(t,"self",{enumerable:!0,get:()=>e.self}),t):Object.assign(t,{self:e.self})}({spawn:o,input:e.input,actors:this.sources.actors},t)),[a]=Zt(n,0,t,[]);if(i&&(a.context=i),Object.keys(r).length>0){a.children={...a.children,...r};const e=function(t){const e=Tt.get(t)?.counters;if(e?.size)return Object.fromEntries(e)}(t);e&&(a._nextActorIds=jt(a._nextActorIds,e))}return a}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){this.validator&&wn(this.validator,{kind:"input",logic:this,input:t});const s=!e,n=e??je(this);Rt(n);const r=K(t),o=[],i=(t,e)=>{s&&_e(n,t,!1);const r=s?be(n,t):this._attachPureActorRef(t,n,!0),o=this._collectEffects(e);return this.validator&&"error"!==t.status&&wn(this.validator,{kind:"result",logic:this,snapshot:r,effects:o}),[r,o]};let a;try{a=this._getPreInitialState(n,r)}catch(t){return i(Rs(Ms({context:"function"!=typeof this.config.context&&this.config.context?this.config.context:{},_nodes:[this.root],children:{},status:"active"},this),{status:"error",error:t}),[])}const c=Object.values(a.children).filter(Boolean).map(t=>Ht(t));try{const[t,e]=cs(this.root,a,n,r,o),{snapshot:s,microsteps:u}=fs(t,r,n,o,[[t,[...c,...e]]]);return i(s,u)}catch(t){if(!this.root.config.onError)throw t;const e=fs(a,C("execution",t),n,[],[[a,c]]);return i(e.snapshot,e.microsteps)}}start(t,e){if(!t?.children)return;const s=t.children;for(const t in s){if(!Object.hasOwn(s,t))continue;const n=s[t];n._rehydrated&&"active"===n.getSnapshot?.().status&&(e?e.actionExecutor(Bt(n)):n.system.startActor(n))}}getStateNodeById(t){const s=De(t),n=s?t.slice(1):t;if(""===n&&s)throw new Error(e(19,this.id));const r=this.idMap.get(n);if(r)return r;throw new Error(e(20,n))}getPersistedSnapshot(t,s){return function(t,s){const{nodes:n,_stateInputs:r,tags:o,machine:i,children:a,timers:c,context:u,can:d,hasTag:h,matches:f,getMeta:p,getInputs:l,toJSON:y,...v}=t,m={},g=[],_=!1!==s?.embedChildren;for(const t in a){const r=a[t],o="string"==typeof r.src?r.src:void 0,i=void 0===o&&!0===r._invoked&&n.some(e=>e.invoke.some(e=>e.id===t));if(!(void 0!==o||i||s&&"__unsafeAllowInlineActors"in s))throw new Error(e(41,t));const c=_&&!w(r);if(!c&&void 0===o)throw new Error(e(42,t));m[t]={address:r.address,...c?{snapshot:r.getPersistedSnapshot(s)}:{remote:!0,incarnation:w(r)?r.sessionId:void 0},...i?{}:{src:r.src},registryKey:r.registryKey,syncSnapshot:r._syncSnapshot}}const x=fe(t)?.actor,E=x?.system?._clock?.now?void 0:x?.system?._snapshot?._scheduledTimers;for(const s of c){let n,r=s.event;if("xstate.timeout.actor"===r.type&&(r={...r},delete r.sessionId),"self"===s.target)n="self";else if(b(s.target))n={...s.target};else{const r=Object.entries(a).find(([,t])=>t===s.target)?.[0];if(r)n=r;else{if(s.target!==fe(t)?.actor._parent)throw new Error(e(43,s.target.id));n={type:"parent"}}}const o=E?.[Q(x,B(s))],i=o?o.dueAt-s.delay:Z(s);g.push({...void 0!==s.id&&{id:s.id},...void 0!==s.seq&&{seq:s.seq},delay:s.delay,type:s.type,event:r,target:n,...void 0!==i&&{scheduledAt:i}})}const $={...v,context:Ns(u,()=>fe(t)?.actor.id??i.id),children:m,timers:g,historyValue:Ps(v.historyValue)};return r&&Object.keys(r).length>0&&($.stateInputs=r),void 0!==i.version&&($.machine={id:i.id,version:i.version}),$}(t,s)}}function Fn(t,e){return new Jn(t,void 0,e)}function Bn(t){return Array.isArray(t)?t.map(Bn):null===t||"object"!=typeof t||Object.getPrototypeOf(t)!==Object.prototype&&null!==Object.getPrototypeOf(t)?t:Object.fromEntries(Object.entries(t).map(([t,e])=>[t,Bn(e)]))}function Hn(t){return!!t&&"object"==typeof t&&"function"==typeof t.transition&&"function"==typeof t.getInitialSnapshot}function Xn(t){return!!t&&"object"==typeof t&&"~standard"in t}function Gn(t){if("function"==typeof t)return{"@code":t.toString(),"@lang":"ts"};if(null===t||"object"!=typeof t)return"bigint"==typeof t||"symbol"==typeof t?void 0:t;if(Hn(t))return;if(Xn(t))return;if(Array.isArray(t))return t.map(Gn).filter(t=>void 0!==t);if(Object.getPrototypeOf(t)!==Object.prototype&&null!==Object.getPrototypeOf(t))return;const e={};for(const s of Object.keys(t)){const n=t[s];if(void 0!==n){const t=Gn(n);void 0!==t&&Object.defineProperty(e,s,{value:t,enumerable:!0,writable:!0,configurable:!0})}}return e}function Qn(t){if(Array.isArray(t)){const e=t.map(Qn).filter(t=>void 0!==t);return e.length?e:void 0}const e=t,s={};for(const t of Object.keys(e)){const n=e[t];void 0!==n&&(s[t]="src"===t&&"string"!=typeof n?n.id:Gn(n),void 0===s[t]&&delete s[t])}return void 0===s.src?void 0:s}function Yn(t){if(!t)return;const e={};for(const s of Object.keys(t)){const n=t[s];e[s]="function"==typeof n?void 0:Gn(n),void 0===e[s]&&delete e[s]}return e}function Zn(t){const e={};for(const s of Object.keys(t)){if("states"===s||"invoke"===s)continue;const n=t[s];void 0!==n&&(e[s]=Gn(n))}if(void 0!==t.invoke){const s=Qn(t.invoke);void 0!==s&&(e.invoke=s)}if(t.states){const s={};for(const e of Object.keys(t.states))s[e]=Zn(t.states[e]);e.states=s}return e}function tr(t){const e=Zn(t),s=Object.keys(t.schemas?.internalEvents??{});if(delete e.internalEvents,s.length&&(e.internalEvents=s),t.schemas){const s={};for(const e of Object.keys(t.schemas)){const n=t.schemas[e];s[e]=n&&"object"==typeof n&&!("~standard"in n)?Yn(n):Gn(n),void 0===s[e]&&delete s[e]}e.schemas=s}for(const s of["actions","guards","actors","delays"])if(t[s]){const n=Yn(t[s]);n&&Object.keys(n).length?e[s]=n:delete e[s]}return e}function er(t){const e=re(t);return void 0!==e?e:"string"==typeof t?parseFloat(t)||0:t}function sr(t){return!!t&&"object"==typeof t&&"string"==typeof t["@expr"]}function nr(t){return sr(t)||function(t){return!!t&&"object"==typeof t&&"string"==typeof t["@code"]}(t)}function rr(t){return nr(t)||!!t&&"object"==typeof t&&Object.values(t).some(rr)}function or(t,e){return"number"==typeof e?`${t}[${e}]`:`${t}.${e}`}function ir(t){const e={};if(!t)return e;for(const s of Object.keys(t)){const n=t[s];"number"==typeof n?e[s]=n:n&&"object"==typeof n&&"number"==typeof n.duration&&(e[s]=n.duration)}return e}function ar(t){return void 0===t?[]:Array.isArray(t)?t:[t]}function cr(t,e){Array.isArray(t)&&t.forEach((s,n)=>{if(void 0===s.when&&n!==t.length-1)throw new Error(`Choice fallback branch at ${e}[${n}] must be last.`)})}const ur=["target","matches","context","actions","guard","description","reenter","meta","input"],dr=["id","key","type","initial","states","on","onError","after","always","choice","route","invoke","entry","exit","meta","description","tags","input","timeout","onTimeout","history","target","output","context"],hr=["@exprLang","version","actions","guards","actors","delays","schemas","internalEvents"];function fr(t,e,s){for(const n of Object.keys(t))if(!e.includes(n))throw new Error(`Unknown key "${n}" at ${s}`)}function pr(t,e){if("compound"===t.type)try{t.initial}catch(t){throw new Error(`Invalid initial state at ${e}.initial: ${t.message}`)}for(const s of Object.keys(t.states))pr(t.states[s],`${e}.states.${s}`)}function lr(t){return!nr(t)&&t.type.startsWith("@xstate.")}function yr(t,e){if(!t)return;if(Object.hasOwn(t,e))return t[e];const s=Object.keys(t).find(t=>Gs(e,t));return void 0===s?void 0:t[s]}function vr(t,e,s){let n=t.get(e);return n||t.set(e,n=s()),n}const mr=new WeakMap,gr=new WeakMap,_r=new WeakMap;function wr(t){return vr(mr,t,()=>({"~standard":{version:1,vendor:"xstate",validate:async e=>{if(null===e||"object"!=typeof e)return{issues:[{message:"Expected a persisted snapshot."}]};const s={historyValue:{},timers:[],...e},n=t.schemas?.context;let r=s.context;if(n){const e=await n["~standard"].validate(r);if(e.issues)return{issues:[{message:`Invalid context for machine '${t.id}' version '${t.version}': ${e.issues[0]?.message}`}]};r=e.value}for(const t of["value","children"])if(!(t in s))return{issues:[{message:`Persisted snapshot is missing '${t}'.`}]};if(!["active","done","error","stopped"].includes(s.status))return{issues:[{message:"Persisted snapshot has invalid status."}]};if(!Ln(s.historyValue))return{issues:[{message:"Persisted snapshot has invalid 'historyValue'."}]};try{zn(t,s)}catch(t){return{issues:[{message:t instanceof Error?t.message:"Persisted snapshot has invalid state value."}]}}return{value:{...s,context:r}}}}}))}function br(t){return vr(gr,t,()=>({"~standard":{version:1,vendor:"xstate",validate:async e=>{if(null===e||"object"!=typeof e||"string"!=typeof e.type)return{issues:[{message:"Expected an event object."}]};const s=e,n=t.schemas?.events,r=t.schemas?.internalEvents,o=s.type.startsWith("xstate.")||s.type.startsWith("@xstate."),i=yr(r,s.type)??yr(n,s.type);if((n||r)&&!i&&!o)return{issues:[{message:`Unknown event '${s.type}' for machine '${t.id}' version '${t.version}'.`}]};if(!i)return{value:s};const{type:a,...c}=s,u=await i["~standard"].validate(c);return u.issues?u:null===u.value||"object"!=typeof u.value?{issues:[{message:"Expected an event payload."}]}:{value:{...u.value,type:a}}}}}))}function xr(t){return null!==t&&"object"==typeof t}function Er(t){return"transition"in t&&"function"==typeof t.transition}async function $r(t,e,s){if(!t)return e;const n=await t["~standard"].validate(e);if(n.issues)throw new Error(`Invalid ${s}: ${n.issues[0]?.message}`);return n.value}async function Sr(t,e){return await $r(wr(e),{...t,machine:{id:e.id,version:e.version}},`snapshot for machine '${e.id}' version '${e.version}'`)}async function kr(t,e,s){return Promise.all(t.map(async(t,e)=>{const n=await s["~standard"].validate(t);if(n.issues){const s=n.issues[0]?.message;if(s?.startsWith("Unknown event "))throw new Error(s);const r=xr(t)?t.type:void 0;throw new Error("string"==typeof r?`Invalid event '${r}' at index ${e}${s?`: ${s}`:"."}`:`Invalid event at index ${e}${s?`: ${s}`:"."}`)}const r=n.value;if(!xr(r)||"string"!=typeof r.type)throw new Error(`Invalid event at index ${e}.`);return r}))}function Ar(t,e,s=new Set){if(!t||"object"!=typeof t||s.has(t))return!1;if(s.add(t),Hs(t))return e.has(t);const n=Object.getPrototypeOf(t);return(t instanceof Map||t instanceof Set?[...t.values()]:Array.isArray(t)||n===Object.prototype||null===n?Object.values(t):[]).some(t=>Ar(t,e,s))}const jr=function(t={}){!function(t){if(t&&"object"==typeof t&&void 0!==t.internalEvents)throw new Error(e(2))}(t);const{validator:s,states:n={},schemas:r,actions:o,actors:i,guards:a,delays:c}=t;return{extend:e=>jr(function(t,e){return{...t,...e,schemas:Tr(t.schemas,e.schemas),states:Ir(t.states,e.states),actions:Or(t.actions,e.actions),actors:Or(t.actors,e.actors),guards:Or(t.guards,e.guards),delays:Or(t.delays,e.delays)}}(t,e)),createMachine(t,...d){if(void 0!==d[0])throw new Error(e(71));const h=Tr(t.schemas,r),f=Mr(t.states,n),p=Or(o,t.actions),l=Or(i,t.actors),y=Or(a,t.guards),v=Or(c,t.delays),m={...t,...h?{schemas:h}:void 0,...f?{states:f}:void 0,...p?{actions:p}:void 0,...l?{actors:l}:void 0,...y?{guards:y}:void 0,...v?{delays:v}:void 0};return u(m),new Jn(m,void 0,s)},createInvoke:(t,...e)=>"function"==typeof t.src?{...t,src:Tn({schemas:t.schemas,run:t.src})}:t,createStateConfig:(...t)=>t.length>1?t[1]:t[0],states:n,schemas:r??{}}};function Or(t,e){return t||e?{...t,...e}:void 0}function Ir(t,e){if(t||e)return t?e?Object.fromEntries(Array.from(new Set([...Object.keys(t),...Object.keys(e)])).map(s=>{const n=t[s],r=e[s];if(!n)return[s,r];if(!r)return[s,n];const o=Tr(n.schemas,r.schemas),i=Ir(n.states,r.states);return[s,{...n,...r,...o?{schemas:o}:void 0,...i?{states:i}:void 0}]})):t:e}function Tr(t,e){if(t||e)return{...t,...e,events:Or(t?.events,e?.events),internalEvents:Or(t?.internalEvents,e?.internalEvents),actions:Or(t?.actions,e?.actions),guards:Or(t?.guards,e?.guards),emitted:Or(t?.emitted,e?.emitted),children:Or(t?.children,e?.children)}}function Mr(t,e){return t&&e?Object.fromEntries(Object.entries(t).map(([t,s])=>{const n=e[t];if(!n)return[t,s];const r=Or(s.schemas,n.schemas),o=Mr(s.states,n.states),i=Object.fromEntries(["type","id","initial","history","target","route"].flatMap(t=>void 0===s[t]&&void 0!==n[t]?[[t,n[t]]]:[]));return[t,{...s,...i,...r?{schemas:r}:void 0,...o?{states:o}:void 0}]})):t}class Rr{constructor(t){this.before=t,this.entries=[],this.indices=new Map}push(t){this.entries.push(t),this.up(this.entries.length-1,t)}peek(){return this.entries[0]}pop(){const t=this.peek();return t&&this.remove(t),t}remove(t){const e=this.indices.get(t);if(void 0===e)return;const s=this.entries.pop();this.indices.delete(t),e!==this.entries.length&&(e>0&&this.before(s,this.entries[e-1>>1])?this.up(e,s):this.down(e,s))}up(t,e){for(;t>0;){const s=t-1>>1;if(!this.before(e,this.entries[s]))break;this.place(t,this.entries[s]),t=s}this.place(t,e)}down(t,e){for(;2*t+1<this.entries.length;){let s=2*t+1;if(s+1<this.entries.length&&this.before(this.entries[s+1],this.entries[s])&&s++,!this.before(this.entries[s],e))break;this.place(t,this.entries[s]),t=s}this.place(t,e)}place(t,e){this.entries[t]=e,this.indices.set(e,t)}}function Pr(t,e){const s="xstate.timer"===e.type?H(e):void 0;return JSON.stringify([t.$actor,t.incarnation,s?G(s):e.type])}function Nr(t,e){return(t.timers??[]).some(t=>X(t,e))}const qr=Symbol("xstate.systemActorHandle"),Dr=()=>{};function Lr(t,e=new Set,s){if("function"==typeof t&&s?.has(t))return{$systemMapper:s.get(t)};if(function(t){return!!t&&"string"==typeof t.address&&"function"==typeof t.getSnapshot}(t)){if(!t[qr])throw new Error("Live actors cannot be stored in a pure system snapshot.");return{$actor:t.address,incarnation:t.sessionId}}if(!t||"object"!=typeof t){if("function"==typeof t||"symbol"==typeof t||"bigint"==typeof t||"number"==typeof t&&!Number.isFinite(t))throw new Error("System snapshots require data, not executable capabilities.");return t}if(e.has(t))throw new Error("System snapshots cannot contain cyclic data.");let n;if(e.add(t),t.machine&&"function"==typeof t.machine.transition&&"string"==typeof t.id&&Array.isArray(t.path))n={$stateNode:t.id};else if(t instanceof Error)n={$error:t.name,message:t.message};else if(Array.isArray(t))n=t.map(t=>Lr(t,e,s));else{if(Object.getPrototypeOf(t)!==Object.prototype&&null!==Object.getPrototypeOf(t))throw new Error("System snapshot values must be plain data.");n=Object.fromEntries(Object.entries(t).map(([t,n])=>[t,Lr(n,e,s)]))}return e.delete(t),n}function Cr(t,e){if(!$s(t))return Lr(t,new Set,e);const{machine:s,nodes:n,tags:r,matches:o,can:i,hasTag:a,getMeta:c,getInputs:u,toJSON:d,...h}=t;return Lr({...h,nodeIds:n.map(t=>t.id)},new Set,e)}class Kr{constructor(t,e,s=1e4){if(this.snapshot=void 0,this.effects=[],this.logic=void 0,this.handles=new Map,this.snapshots=new Map,this.initialEffects=new Map,this.stopping=new Set,this.deadlines=new Rr((t,e)=>t.dueAt<e.dueAt||t.dueAt===e.dueAt&&t.sequence<e.sequence),this.effectNames=new Map([[Dr,"@xstate.log"]]),this.mapperNames=void 0,this.mappers=void 0,this.remaining=void 0,!Number.isSafeInteger(s)||s<1)throw new Error("maxSteps must be a positive integer.");this.logic=function(t){const e=new Map,s=new Set;function n(t,r){if(e.set(t,r),s.has(r))return;s.add(r);const o=r;for(const[e,s]of Object.entries(o.sources?.actors??{}))n(`${t}/actors/${en(e)}`,s);o.root&&function e(s){for(const e of s.invoke??[])"object"==typeof e.logic&&n(`${t}/invoke/${en(s.id)}/${en(e.id)}`,e.logic);for(const t of Object.values(s.states??{}))e(t)}(o.root)}n("root",t.root);for(const[e,s]of Object.entries(t.actors??{}))n(`actors/${en(e)}`,s);return n("@xstate.listener",ut),n("@xstate.subscription",ht),e}(t),this.mappers=t.mappers??{},this.mapperNames=new Map(Object.entries(this.mappers).map(([t,e])=>[e,t]));for(const[e,s]of Object.entries(t.effects??{}))this.effectNames.set(s,e);for(const[t,e]of this.logic)for(const[s,n]of Object.entries(e.sources?.actions??{}))"function"!=typeof n||this.effectNames.has(n)||this.effectNames.set(n,`${t}/actions/${en(s)}`);this.snapshot={...e,actors:Object.assign(Object.create(null),e.actors),registry:Object.assign(Object.create(null),e.registry),messages:[...e.messages],timers:Object.fromEntries(e.timers.map(t=>[Pr(t.source,t.event),t])),externalEffects:{...e.externalEffects},counters:{...e.counters}},this.remaining=s;for(const t of e.timers)this.deadlines.push(t)}step(){if(--this.remaining<0)throw new Error("System transition exceeded maxSteps; the input snapshot is unchanged.")}reference(t){return{$actor:t.address,incarnation:t.sessionId}}current(t){const e=this.snapshot.actors[t.$actor];return e?.incarnation===t.incarnation?e:void 0}decode(t,e){if(function(t){return!!t&&"string"==typeof t.$actor&&"string"==typeof t.incarnation}(t))return this.handle(t);if(!t||"object"!=typeof t)return t;if("string"==typeof t.$systemMapper){const e=Object.hasOwn(this.mappers,t.$systemMapper)&&this.mappers[t.$systemMapper];if(!e)throw new Error(`Missing pure mapper '${t.$systemMapper}'.`);return e}if("string"==typeof t.$stateNode)return e.getStateNodeById(t.$stateNode);if("string"==typeof t.$error){const e=new Error(t.message);return e.name=t.$error,"TimeoutError"===e.name&&Object.setPrototypeOf(e,In.prototype),e}return Array.isArray(t)?t.map(t=>this.decode(t,e)):Object.fromEntries(Object.entries(t).map(([t,s])=>[t,this.decode(s,e)]))}encode(t){return Lr(t,new Set,this.mapperNames)}attachedKind(t){return this.logic.get(t.src)?.[rt]?.kind}relayAttachments(t,e){for(const s of Object.values(this.snapshot.actors)){const n=this.attachedKind(s);if(!s.started||"active"!==s.snapshot.status||"@xstate.listener"!==n&&"@xstate.subscription"!==n)continue;const r=s.input.actor;if(!r||r.$actor!==t.$actor||r.incarnation!==t.incarnation||!s.parent||"active"!==this.current(s.parent)?.snapshot.status)continue;const o=this.decode(s.input);let i;if("@xstate.listener"===n)e&&Gs(e.type,o.eventType)&&(i=o.mapper(this.decode(this.encode(e))));else if(!e){const e=this.hydrate(t),s=o.mappers["active"===e.status?"snapshot":"done"===e.status?"done":"error"===e.status?"error":""];s&&(i=s("done"===e.status?e.output:"error"===e.status?e.error:e))}i&&this.enqueue({$actor:s.address,incarnation:s.incarnation},s.parent,i)}}stopAttachments(t){for(const e of Object.values(this.snapshot.actors)){const s=this.attachedKind(e);"@xstate.listener"!==s&&"@xstate.subscription"!==s||e.parent?.$actor!==t.$actor||e.parent.incarnation!==t.incarnation||this.stop({$actor:e.address,incarnation:e.incarnation})}}hydrate(t){const e=JSON.stringify(t);if(this.snapshots.has(e))return this.snapshots.get(e);const s=this.current(t);if(!s)return{status:"stopped",output:void 0,error:void 0};const n=this.logic.get(s.src);if(!n||n.version!==s.logicVersion)throw new Error(`Actor definition/version mismatch for '${s.address}'.`);const r=this.decode(s.snapshot,n),o="function"==typeof n.getStateNodeById&&r.nodeIds?Ms({...r,_nodes:r.nodeIds.map(t=>n.getStateNodeById(t))},n):r;return this.snapshots.set(e,o),o}handle(t){const e=JSON.stringify(t),s=this.handles.get(e);if(s)return s;const n=this.current(t),r=()=>this.current(t)??n,o=()=>this.logic.get(r()?.src??""),i=()=>{const t=r()?.parent;return t&&this.handle(t)},a=()=>this.hydrate(t),c=()=>{throw new Error("Use enqueue operations and systemTransition; live actor capabilities are unavailable in a pure snapshot.")},u={[qr]:!0,id:n?.id??t.$actor.split("/").at(-1),address:t.$actor,sessionId:t.incarnation,options:{_inert:!0,input:n?.input},get logic(){return o()},get src(){return r()?.src},get registryKey(){return r()?.registryKey},get _parent(){return i()},get _snapshot(){return a()},getSnapshot:a,send:c,start:c,stop:c,subscribe:c,on:c,system:void 0};return this.handles.set(e,u),u.system=this.system(),u}system(){return{createActorRef:(t,e)=>this.allocate(t,e),_unregister:t=>{this.stopping.add(JSON.stringify(this.reference(t)));for(const[e,s]of Object.entries(this.snapshot.registry))s.$actor===t.address&&s.incarnation===t.sessionId&&delete this.snapshot.registry[e]},_getByAddress:t=>{const e=this.snapshot.actors[t];return"active"===e?.snapshot.status?this.handle({$actor:t,incarnation:e.incarnation}):void 0},get:t=>this.snapshot.registry[t]&&this.handle(this.snapshot.registry[t]),getAll:()=>Object.fromEntries(Object.entries(this.snapshot.registry).map(([t,e])=>[t,this.handle(e)])),_hasInspectionObservers:()=>!1,_sendInspectionEvent:()=>{},_clock:{now:()=>this.snapshot.now,setTimeout:()=>{throw new Error("Timers must be declared as logical effects.")},clearTimeout:()=>{throw new Error("Timers must be canceled as logical effects.")}}}}scope(t,e){const s=this.handle(t);return s._lastSourceRef=e&&this.handle(e),{self:s,system:s.system,id:s.id,sessionId:s.sessionId,logger:Dr,defer:()=>{},emit:()=>{throw new Error("Emit events through enqueue operations.")},actionExecutor:()=>{throw new Error("Execute external effects outside system transitions.")},stopChild:()=>{throw new Error("Stop children through enqueue operations.")}}}allocate(t,e={}){this.step();const s=[...this.logic].find(([,e])=>e===t);if(!s)throw new Error("Register dynamically spawned logic in systemLogic.actors.");const n=e.parent&&this.reference(e.parent),r=e.id??`${tn(e.src??t)}:${this.snapshot.counters.actor}`,o=`${n?n.$actor+"/":""}${en(r)}`,i=this.snapshot.actors[o];if("active"===i?.snapshot.status){const t={$actor:o,incarnation:i.incarnation};if(!this.stopping.has(JSON.stringify(t)))throw new Error(`Actor address '${o}' is already occupied.`);this.stop(t)}const a=String(this.snapshot.counters.actor++),c={$actor:o,incarnation:a},u={id:r,address:o,incarnation:a,src:s[0],...void 0!==t.version&&{logicVersion:t.version},parent:n,registryKey:e.registryKey,syncSnapshot:e.syncSnapshot,started:!1,input:this.encode(e.input),snapshot:{status:"active",output:void 0,error:void 0}};if(this.snapshot.actors[o]=u,e.registryKey){if(this.snapshot.registry[e.registryKey])throw new Error(`Registry key '${e.registryKey}' is already occupied.`);this.snapshot.registry[e.registryKey]=c}const d=this.scope(c),h=t.initialTransition(this.decode(u.input),d),[f,p]=Qt(d,void 0,h);return this.store(c,f),this.initialEffects.set(JSON.stringify(c),p),this.handle(c)}store(t,e){const s=this.current(t);s&&(this.snapshots.set(JSON.stringify(t),e),this.snapshot.actors[t.$actor]={...s,snapshot:Cr(e,this.mapperNames)})}external(t,e){const s=e;if("action"===s.kind&&void 0===s.action)return;const n="action"===s.kind&&"@xstate.effect"!==s.type&&"@xstate.cleanup"!==s.type?this.effectNames.get(s.action):s.type;if(void 0===n)throw new Error("Register callable external actions in systemLogic.effects or the machine action sources.");const r=`${this.snapshot.executionId}:${this.snapshot.counters.effect++}`,o="function"==typeof s.params?.action?Object.fromEntries(Object.entries(s.params).filter(([t])=>"action"!==t&&"args"!==t)):s.params,i={id:r,source:t,type:n,kind:"emit"===s.kind?"emit":"@xstate.deadLetter"===s.type?"builtin":"action",...void 0!==o&&{params:this.encode(o)},args:this.encode(s.args??[]),...s.event&&{event:this.encode(s.event)},...s.reason&&{reason:s.reason}};this.effects.push(i),this.snapshot.externalEffects[r]=i,"emit"===s.kind&&this.relayAttachments(t,s.event)}enqueue(t,e,s,n){this.snapshot.messages.push({source:t,target:e,event:this.encode(s),sequence:this.snapshot.counters.sequence++,...void 0!==n&&{timerOccurrence:n}})}cancel(t,e){const s=e&&Pr(t,{type:"xstate.timer",...e});for(const[e,n]of Object.entries(this.snapshot.timers))n.source.$actor!==t.$actor||n.source.incarnation!==t.incarnation||void 0!==s&&e!==s||delete this.snapshot.timers[e]}effectsFor(t,e){for(const s of e){const e=s;if("builtin"===e.kind)switch(e.type){case"@xstate.spawn":break;case"@xstate.start":this.start(this.reference(e.actor));break;case"@xstate.stop":this.stop(this.reference(e.actor));break;case"@xstate.cancel":this.cancel(t,H(e));break;case"@xstate.raise":case"@xstate.sendTo":if(void 0!==e.delay){if(!Number.isFinite(e.delay)||e.delay<0)throw new Error("System timer delays must be finite and nonnegative.");const s=B(e),n=this.current(t);if(!n||!Nr(n.snapshot,s))break;this.schedule(t,e.delay,{type:"xstate.timer",...s})}else if(b(e.target)){const s=this.snapshot.actors[e.target.$actor];"active"!==s?.snapshot.status||void 0!==e.target.incarnation&&e.target.incarnation!==s.incarnation?this.external(t,{kind:"builtin",type:"@xstate.deadLetter",event:e.event,reason:"missingTarget",args:[]}):this.enqueue(t,{$actor:s.address,incarnation:s.incarnation},e.event)}else e.target&&this.enqueue(t,this.reference(e.target),e.event);break;case"@xstate.terminate":this.terminate(t);break;default:this.external(t,s)}else this.external(t,s)}}schedule(t,e,s){const n=this.snapshot.now+e;if(!Number.isFinite(e)||e<0||!Number.isFinite(n))throw new Error("System timer deadlines must be finite and delays nonnegative.");const r={source:t,occurrence:this.snapshot.counters.timer++,scheduledAt:this.snapshot.now,dueAt:n,sequence:this.snapshot.counters.sequence++,event:this.encode(s)},o=Pr(t,s);delete this.snapshot.timers[o],this.snapshot.timers[o]=r,this.deadlines.push(r)}start(t){const e=this.current(t);if(!e||e.started||"stopped"===e.snapshot.status)return;if(this.snapshot.actors[t.$actor]={...e,started:!0},this.effectsFor(t,this.initialEffects.get(JSON.stringify(t))??[]),this.initialEffects.delete(JSON.stringify(t)),"@xstate.subscription"===this.attachedKind(e)){const s=this.decode(e.input),n=this.reference(s.actor),r=this.current(n);r?.started&&"error"===r.snapshot.status&&s.mappers.error&&e.parent&&this.enqueue(t,e.parent,s.mappers.error(this.hydrate(n).error))}"active"===this.current(t)?.snapshot.status&&this.relayAttachments(t);const s=this.logic.get(e.src)[rt];if(void 0!==s?.timeout&&"active"===this.current(t)?.snapshot.status){const e=re(s.timeout);if(void 0===e)throw new Error("Unable to resolve async actor timeout.");this.schedule(t,e,{type:"xstate.async.reject",data:new In(s.timeout)})}}stop(t){const e=this.current(t);e&&"active"===e.snapshot.status&&(this.process({source:t,target:t,event:{type:p},sequence:this.snapshot.counters.sequence++}),this.cancel(t),this.handle(t).system._unregister(this.handle(t)),this.snapshot.messages=this.snapshot.messages.filter(e=>e.target.$actor!==t.$actor||e.target.incarnation!==t.incarnation),this.cancelExternal(t),this.stopAttachments(t))}cancelExternal(t){for(const[e,s]of Object.entries(this.snapshot.externalEffects)){if("action"!==s.kind||"@xstate.cancelEffect"===s.type||"@xstate.cleanup"===s.type||s.source.$actor!==t.$actor||s.source.incarnation!==t.incarnation)continue;delete this.snapshot.externalEffects[e];const n={id:`${this.snapshot.executionId}:${this.snapshot.counters.effect++}`,source:t,kind:"action",type:"@xstate.cancelEffect",params:{effectId:e}};this.effects.push(n),this.snapshot.externalEffects[n.id]=n}}terminate(t){const e=this.current(t);if(e&&(this.relayAttachments(t),this.cancel(t),this.cancelExternal(t),this.stopAttachments(t),e.parent)){const s="done"===e.snapshot.status?D(e.id,this.decode(e.snapshot.output),e.incarnation):L(e.id,this.decode(e.snapshot.error),e.incarnation);this.enqueue(t,e.parent,s)}}process(t){this.step();const e=this.current(t.target);if(!e||"active"!==e.snapshot.status)return;if("xstate.timer"===t.event.type&&void 0===t.timerOccurrence)throw new Error("Only the system scheduler may deliver a timer occurrence.");const s=this.logic.get(e.src);if(!s)throw new Error(`Missing actor definition '${e.src}'.`);if(s.isInternalEventType?.(t.event.type)&&(!t.source||t.source.$actor!==e.address||t.source.incarnation!==e.incarnation))throw new Error(`Internal event '${t.event.type}' cannot be injected into a pure system.`);if(!t.source&&/^(xstate\.after(?:\.|$)|xstate\.timeout(?:\.|$))/.test(t.event.type))throw new Error("Select a pending timer instead of injecting its internal event.");const n=this.scope(t.target,t.source),r=this.hydrate(t.target),[o,i]=Qt(n,r,s.transition(r,this.decode(t.event),n));this.store(t.target,o),this.effectsFor(t.target,i),"active"===o.status&&this.relayAttachments(t.target),e.syncSnapshot&&e.parent&&"active"===o.status&&this.enqueue(t.target,e.parent,{type:"xstate.snapshot.actor",actorId:e.id,sessionId:e.incarnation,snapshot:Cr(o,this.mapperNames)})}result(){return{...this.snapshot,timers:Object.values(this.snapshot.timers)}}settle(){for(;this.snapshot.messages.length;){const t=this.snapshot.messages.shift();this.process(t)}}advance(t){if(!Number.isFinite(t)||t<this.snapshot.now)throw new Error("System time must be finite and cannot move backwards.");for(this.settle();;){const e=this.deadlines.peek();if(e&&this.snapshot.timers[Pr(e.source,e.event)]!==e){this.deadlines.pop();continue}if(!e||e.dueAt>t)break;this.step(),this.deadlines.pop(),delete this.snapshot.timers[Pr(e.source,e.event)],this.snapshot.now=Math.max(this.snapshot.now,e.dueAt);const s=this.current(e.source),n="xstate.timer"===e.event.type?H(e.event):void 0;!s||"active"!==s.snapshot.status||n&&!Nr(s.snapshot,n)||(this.enqueue(e.source,e.source,e.event,e.occurrence),this.settle())}this.snapshot.now=t}send(t,e){if("xstate.timer"===e.type){const s=this.snapshot.actors[t];if(!s)throw new Error(`Unknown actor address '${t}'.`);const n=Object.values(this.snapshot.timers).find(n=>n.source.$actor===t&&n.source.incarnation===s.incarnation&&n.occurrence===e.occurrence);if(!n)throw new Error("Select a current timer occurrence.");return void this.advance(n.dueAt)}this.advance(this.snapshot.now);const s=this.snapshot.actors[t];if(!s)throw new Error(`Unknown actor address '${t}'.`);const n={$actor:t,incarnation:s.incarnation};if("xstate.system.effect.result"===e.type){const r=this.snapshot.externalEffects[e.effectId];if(!r||r.source.$actor!==t||e.event&&(r.source.incarnation!==s.incarnation||"active"!==s.snapshot.status||"@xstate.cancelEffect"===r.type||"@xstate.cleanup"===r.type))throw new Error("External effect result does not match its owner or is stale.");return delete this.snapshot.externalEffects[e.effectId],void(e.event&&(this.enqueue(n,n,e.event),this.settle()))}if(e.type===p)return this.stop(n),void this.settle();if(e.type.startsWith("xstate.async.")||e.type.startsWith("xstate.logic.effect."))throw new Error("Deliver external work results with xstate.system.effect.result.");this.enqueue(void 0,n,e),this.settle()}initialize(t,e,s){const n=this.allocate(this.logic.get("root"),{id:e,input:t,registryKey:s});this.snapshot.root=n.address,this.start(this.reference(n)),this.settle()}}function zr(t,e,s){const n=t.map(([t,e,s])=>[t,e,s??[]]);if(!n.length)return n;const r=n.at(-1)[0];_e(e,r,!1),r!==s&&be(e,r);for(const[t]of n)if(t!==s&&t!==r){be(je(t.machine,t,void 0,e),t)}return n}function Wr(t,e,s){}function Vr(t){if(b(t))return{...t};const e=w(t)?t.sessionId:void 0;return void 0===e?{$actor:t.address}:{$actor:t.address,incarnation:e}}const Ur={timeout:1/0};t.Actor=gn,t.InfiniteTransitionError=hs,t.InvalidSnapshotError=Dn,t.SimulatedClock=class{constructor(){this.timeouts=new Map,this.deadlines=new Rr((t,e)=>{const s=t.start+t.timeout,n=e.start+e.timeout;return s<n||s===n&&t.id<e.id}),this._now=0,this._id=0,this._flushing=!1}now(){return this._now}getId(){return this._id++}setTimeout(t,e){if(!Number.isFinite(e))throw new Error("Timer delay must be finite");const s=this.getId(),n={id:s,start:this.now(),timeout:Math.max(0,e),fn:t};return this.timeouts.set(s,n),this.deadlines.push(n),s}clearTimeout(t){const e=this.timeouts.get(t);e&&this.deadlines.remove(e),this.timeouts.delete(t)}set(t){if(!Number.isFinite(t)||this._now>t)throw new Error("Clock time must be finite; unable to travel back in time");if(this._flushing)throw new Error("Cannot advance a clock during a timer callback");this.flushTimeouts(t)}flushTimeouts(t){this._flushing=!0;try{let e=0;for(;;){const s=this.deadlines.peek();if(!s||s.start+s.timeout>t)break;if(++e>1e4)throw new Error("Clock exceeded 10,000 timer callbacks; check for a zero-delay loop");this.deadlines.pop(),this._now=Math.max(this._now,s.start+s.timeout),this.timeouts.delete(s.id),s.fn.call(null)}this._now=t}finally{this._flushing=!1}}increment(t){this.set(this._now+t)}},t.StateMachine=Jn,t.StateNode=Nn,t.TimeoutError=In,t._createMachineFromCompiledConfig=Fn,t._hotSwapActorLogic=function(t,e){const s=t,n=s.getSnapshot();if(s._processingStatus!==pn.Running||"active"!==n.status||n.machine?.id!==e.id)return!1;let r;const o={};try{r=[...Pe(Qe(e.root,n.value))];for(const[t,s]of Object.entries(n.historyValue??{})){if("history"!==e.getStateNodeById(t).type)return!1;o[t]=s.map(t=>e.getStateNodeById(t.id))}}catch{return!1}const i={},a=[];for(const[t,s]of Object.entries(n.children)){if(!s)continue;const o="string"!=typeof s.src&&!0===s._invoked&&n.nodes.some(e=>e.invoke.some(e=>e.id===t));if("string"!=typeof s.src&&!o){i[t]=s;continue}let c;try{c="string"==typeof s.src?e.sources.actors[s.src]:Xs(e,r,t)}catch{}if(!c||"function"==typeof c)return!1;c===s.logic?i[t]=s:a.push([t,s,c])}const c=new Set(a.map(([,t])=>t));if(c.size&&((n.timers??[]).some(t=>c.has(t.target))||Ar(n.context,c)))return!1;const u=()=>Ms({...n,_nodes:r,value:void 0,children:i,historyValue:o},e);if(e.validator?.check({kind:"result",logic:e,snapshot:u(),effects:[]}))return!1;for(const[t,e,n]of a)s._stopChild(e),i[t]=s.system.createActorRef(n,{id:t,parent:s,syncSnapshot:e._syncSnapshot,src:"string"==typeof e.src?e.src:void 0,registryKey:e.registryKey,input:e.options?.input}),i[t]._invoked=e._invoked;s.src===s.logic&&(s.src=e),s.logic=e;const d=u();s._setSnapshot(d),s._next(d);for(const[t]of a)i[t].start();return!0},t._parseDelayToMilliseconds=re,t._toObserver=Bs,t.advanceSystemTime=function(t,e,s){const n=new Kr(t,e,s.maxSteps);return n.advance(s.time),[n.result(),n.effects]},t.assertEvent=function(t,s){const n=zs(s);if(!n.some(e=>Gs(t.type,e)))throw new Error(e(74,t.type,n.join(", ")))},t.createActor=_n,t.createAsyncLogic=Tn,t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return En({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:n,input:r,self:o,system:i}=t,a=t.emit,c=$n.get(o);c?.receivers?.forEach(t=>t(n)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return $n.set(o,t),t.dispose=e({input:r,system:i,self:o,sendBack:t=>{if("stopped"===o.getSnapshot().status)return;const e=o._parent;e&&i._relay(o,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:a}),()=>{$n.delete(o),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return _n(Mn)},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.validator,n={config:t,validator:s,transition:(t,e,s)=>{if("active"!==t.status)return[t,[]];switch(e.type){case kn:return Qt(s,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case An:return Qt(s,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case p:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{s&&wn(s,{kind:"input",logic:n,input:t});return[{status:"active",output:void 0,error:void 0,context:void 0,input:t,_subscription:void 0},[]]},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],start:(t,{self:s,system:n,emit:r})=>{"done"!==t.status&&(t._subscription=e({input:t.input,system:n,self:s,emit:t=>{r(t)}}).subscribe({next:t=>{s._parent&&n._relay(s,s._parent,t)},error:t=>{n._relay(s,s,{type:kn,data:t})},complete:()=>{n._relay(s,s,{type:An})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return n},t.createListenerLogic=ct,t.createMachine=function(t,...s){if(void 0!==s[0])throw new Error(e(71));return u(t),new Jn(t)},t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return En({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:n,input:r,self:o,system:i}=t;switch(n.type){case Sn:return{context:n.data};case kn:return{status:"error",error:n.data,input:void 0,effects:{observable:{status:"error",error:n.data}}};case An:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}n.type===h&&s.effect((t=i)=>{const s=o,n=e=>{t.sendEvent(s,s,e)},a=e({input:r,system:i,self:o,emit:e=>{k(s,e,t)}}).subscribe({next:t=>{n({type:Sn,data:t})},error:t=>{n({type:kn,data:t})},complete:()=>{n({type:An})}});return()=>a.unsubscribe()})}})},t.createStateConfig=function(t){return t},t.createStepLogic=En,t.createSubscriptionLogic=dt,t.createSystem=function(t={}){const e={initialize:()=>n()},s=new Set,n=()=>{const t=e.current;if(t)for(const e of s){const n=e.subscribe(t);s.delete(e)?e.subscription=n:n.unsubscribe()}},r=t=>{const n=e.current;if(n)return t(n);const r={subscribe:t};return s.add(r),{unsubscribe(){s.delete(r),r.subscription?.unsubscribe()}}};if(t.onEmitted){const e=t.onEmitted;r(t=>t.onEmitted(e))}return{createActor:(t,...[s])=>_n(t,{...s,_systemRef:e}),get:t=>e.current?.get(t),getAll:()=>e.current?.getAll()??{},inspect:t=>r(e=>e.inspect(t)),onEmitted:t=>r(e=>e.onEmitted(t)),onRejectedEvent:t=>r(e=>e.onRejectedEvent(t)),setup:jr}},t.deliverEvent=O,t.describeExecutableEffect=function(t){if("action"===t.kind)return{kind:"action",type:t.type,params:t.params};if("emit"===t.kind)return{kind:"emit",type:t.type,source:Vr(t.source),event:t.event};switch(t.type){case"@xstate.spawn":return{kind:"builtin",type:"@xstate.spawn",source:t.source&&Vr(t.source),actor:Vr(t.actor),id:t.id,src:tn(t.src),input:t.input};case"@xstate.start":return{kind:"builtin",type:"@xstate.start",source:t.source&&Vr(t.source),actor:Vr(t.actor),id:t.id};case"@xstate.raise":return{kind:"builtin",type:"@xstate.raise",source:Vr(t.source),event:t.event,id:t.id,...void 0!==t.seq&&{seq:t.seq},delay:t.delay};case"@xstate.sendTo":return{kind:"builtin",type:"@xstate.sendTo",source:Vr(t.source),target:t.target&&Vr(t.target),event:t.event,id:t.id,...void 0!==t.seq&&{seq:t.seq},delay:t.delay};case"@xstate.cancel":return{kind:"builtin",type:"@xstate.cancel",source:Vr(t.source),...H(t)};case"@xstate.stop":return{kind:"builtin",type:"@xstate.stop",source:Vr(t.source),actor:Vr(t.actor),id:t.id};case"@xstate.terminate":return{kind:"builtin",type:"@xstate.terminate",source:Vr(t.source),actor:Vr(t.actor),id:t.id,status:t.status,output:t.output,error:t.error};case"@xstate.deadLetter":return{kind:"builtin",type:"@xstate.deadLetter",source:t.source&&Vr(t.source),target:t.target&&Vr(t.target),event:t.event,reason:t.reason,issues:t.detail?.issues,error:t.detail?.error}}},t.eventSchema=function(t){return vr(_r,t,()=>({"~standard":{version:1,vendor:"xstate",validate:async e=>{const s=e;if(s&&"string"==typeof s.type){const n=yr(t.schemas?.internalEvents,s.type),r=s.type.startsWith("xstate.")||s.type.startsWith("@xstate.");if(n||r){if(!n&&"xstate.route"===s.type){const s=await br(t)["~standard"].validate(e);if(s.issues)return s;const n=s.value.to,r="string"==typeof n&&n.startsWith("#")?t.idMap.get(n.slice(1)):void 0;if(r&&r!==t.root&&r.config.id&&r.config.route)return{value:s.value}}return{issues:[{message:`Event '${s.type}' is not a public input event.`}]}}}return br(t)["~standard"].validate(e)}}}))},t.executeEffects=async function(t,e){for(const s of t)await s.exec(e)},t.getInitialMicrosteps=function(t,...[e]){const s=je(t);Rt(s);const n=K(e),r=[],o=t._getPreInitialState(s,n),i=Object.values(o.children).filter(Boolean).map(t=>Ht(t)),a=cs(t.root,o,s,n,r),{microsteps:c}=fs(a[0],n,s,r,[[a[0],[...i,...a[1]],[]]]);return zr(c,s)},t.getMachineSerializationDiagnostics=function(t){const e=[],s=new Set,n=(t,r,o=!1)=>{const i=(t,s)=>e.push({code:t,path:r,message:s});if("function"!=typeof t)if(void 0!==t&&"bigint"!=typeof t&&"symbol"!=typeof t)if("number"!=typeof t||Number.isFinite(t)){if(t&&"object"==typeof t){if(Hn(t)){const e="string"==typeof t.id;return void i(e?"runtime-source":"omitted-value",e?"Supply the actor implementation under its source ID when reviving.":"This actor has no named source; an invocation using it is omitted.")}if(Xn(t))i("omitted-value","Runtime schemas are omitted; supply runtime schemas again when reviving.");else if(s.has(t))i("unsupported-value","Cyclic data cannot be exported as a JSON definition.");else if(Array.isArray(t)||Object.getPrototypeOf(t)===Object.prototype||null===Object.getPrototypeOf(t))if(Object.hasOwn(t,"@code"))i("code-expression","This source expression requires an evaluator and its dependencies.");else{s.add(t);for(const[e,s]of Object.entries(t)){const t=`${r}/${e.replaceAll("~","~0").replaceAll("/","~1")}`,o=/^\/(actions|guards|actors|delays)$/.test(r);n(s,t,o)}s.delete(t)}else i("omitted-value","Class instances are omitted from the exported definition.")}}else i("unsupported-value","Nonfinite numbers do not retain their value in JSON.");else i("omitted-value","This value is omitted from the exported definition.");else i(o?"runtime-source":"code-expression",o?"Supply this named implementation when reviving the definition.":"This function becomes source text and requires an evaluator and its dependencies.")};return n(t._json??t.config,""),e},t.getMicrosteps=function(t,e,s){const n=je(t,e);Rt(n);const{microsteps:r}=fs(e,s,n,[]);return zr(r,n,e)},t.getNextTransitions=function(t){if("active"!==t.status)return[];const e=[],s=t.nodes.filter(Te),n=new Set;for(const t of s)for(const s of[t].concat(Re(t,void 0)))if(!n.has(s.id)){n.add(s.id);for(const[,t]of s.transitions.entries())e.push(...t);s.always&&e.push(...s.always)}return e},t.getStateNodes=Qe,t.initialSystemTransition=function(t,e={}){const s=e.time??0;if(!Number.isFinite(s)||s<0)throw new Error("Initial system time must be finite and nonnegative.");const n=new Kr(t,{root:"",executionId:e.executionId??"system",now:s,actors:{},registry:{},messages:[],timers:[],externalEffects:{},counters:{actor:0,timer:0,sequence:0,effect:0}},e.maxSteps);return n.initialize(e.input,e.id??t.root.id??"root",e.registryKey),[n.result(),n.effects]},t.initialTransition=function(t,...[e]){const s=je(t),[n,r]=Qt(s,void 0,t.initialTransition(e,s));_e(s,n,!1);const o=be(s,n);return Wr(s,o,K(e)),[o,r]},t.isBuiltInExecutableEffect=Yt,t.isMachineSnapshot=$s,t.isTypeSchema=function(t){return!!t&&"object"==typeof t&&"~standard"in t&&"xstate.types"===t["~standard"].vendor},t.isUnhandled=function(t,e){return e[0]===t&&0===e[1].length},t.machineConfigToJSON=tr,t.machineFromJSON=function(t,e={}){const s=function(t,e){return{actions:e.actions??{},guards:e.guards??{},actors:e.actors??{},delays:{...ir(t.delays),...e.delays??{}},evaluators:e.evaluators??{}}}(t=Bn(t),e),n=function(t,e){function s(s,n){const r=s["@lang"]??t;if(!r)throw new Error(`Missing @exprLang for expression at ${n}`);const o=e.evaluators[r];if(!o)throw new Error(`Missing evaluator for @lang '${r}' at ${n}`);return o}function n(t,e,n,r){const o=sr(t)?"expr":"code",i=sr(t)?t["@expr"]:t["@code"];return s(t,r)({source:i,kind:o,slot:e,scope:n,path:r})}function r(t,e,s,o){if(nr(t))return n(t,e,s,o);if(Array.isArray(t))return t.map((t,n)=>r(t,e,s,or(o,n)));if(!t||"object"!=typeof t)return t;const i={};for(const n of Object.keys(t))i[n]=r(t[n],e,s,or(o,n));return i}function o(t,e){return{context:t.context,event:t.event,input:t.input,self:t.self,children:t.children,params:t.params,actions:t.actions,actors:t.actors,guards:t.guards,delays:t.delays,...e}}return{evaluateResolvable:n,resolveValue:r,makeScope:o,getDurationConfig:function(t,e){return nr(t)?s=>er(r(t,"delay",o(s),e)):t},assertResolvable:function t(e,n){if(nr(e))s(e,n);else if(Array.isArray(e))e.forEach((e,s)=>t(e,or(n,s)));else if(e&&"object"==typeof e)for(const s of Object.keys(e))t(e[s],or(n,s))}}}(t["@exprLang"],s),{evaluateResolvable:r,resolveValue:o,makeScope:i,getDurationConfig:a}=n;function c(e,s,n){if(e){if(nr(e))return t=>!!r(e,s,i(t),n);if("@xstate.not"===e.type){const t=c(e.params?.guard,s,`${n}.params.guard`);return e=>!t?.(e)}return"@xstate.stateIn"===e.type?t=>{const r=o(e.params,s,i(t),`${n}.params`),a=r?.stateId;return"string"==typeof a&&!!t._snapshot?.matches(`#${a.replace(/^#/,"")}`)}:r=>{const a=o(e.params,s,i(r),`${n}.params`),u=t.guards?.[e.type];if(u){const t=c(u.when,"guard",`$.guards.${e.type}.when`);return!!t?.({...r,params:a})}const d=r.guards?.[e.type];if(!d)throw new Error((h=e.type,f=r.guards??{},`Guard '${h}' is not implemented in ${t.id?`machine '${t.id}'`:"the machine"}. Available guards: ${Object.keys(f).map(t=>`'${t}'`).join(", ")||"(none)"}.`));var h,f;return d(r,a)}}}function u(t,e){if(t)return nr(t)?s=>r(t,"choice",i(s),e):(cr(t,e),s=>{for(let n=0;n<t.length;n++){const r=t[n],a=c(r.when,"choice",`${e}[${n}].when`);if(!a||a(s))return{target:r.target,context:r.context?o(r.context,"transitionContext",i(s),`${e}[${n}].context`):void 0,input:void 0!==r.input?o(r.input,"input",i(s),`${e}[${n}].input`):void 0,description:r.description,reenter:r.reenter,meta:r.meta}}throw new Error(`Choice state at ${e} did not match any branch.`)})}function d(t,e){if(!t||"function"==typeof t)return t;if(nr(t))return s=>r(t,"transition",i(s),e);const{guard:s,...n}=t;if(!s)return n;const o=c({type:s},"guard",e);return t=>o(t)?n:void 0}function h(e,s,n,a,c=[]){let u;const d=()=>u?{...s,context:{...s.context,...u}}:s;for(let f=0;f<e.length;f++){const p=e[f],l=`${a}[${f}]`;if(nr(p)){const t=r(p,"action",i(d(),{params:s.params,enq:n}),l);t&&"object"==typeof t&&"context"in t&&t.context&&(u??={},Object.assign(u,t.context));continue}if(lr(p)){switch(p.type){case"@xstate.raise":n.raise(o(p.event,"actionParams",i(d(),{params:s.params}),`${l}.event`),{id:p.id,delay:p.delay});break;case"@xstate.cancel":n.cancel(p.id);break;case"@xstate.log":n.log(...p.args);break;case"@xstate.emit":n.emit(o(p.event,"actionParams",i(d(),{params:s.params}),`${l}.event`));break;case"@xstate.assign":u??={},Object.assign(u,o(p.context,"transitionContext",i(d(),{params:s.params}),`${l}.context`))}continue}const y=o(p.params,"actionParams",i(d(),{params:s.params}),`${l}.params`),v=t.actions?.[p.type];if(!v){n(s.actions[p.type],y);continue}if(c.includes(p.type))throw new Error(`Circular action reference: ${c.concat(p.type).join(" -> ")}`);const m=h(Array.isArray(v)?v:[v],{...s,context:{...s.context,...u},params:y},n,`${l}.actions.${p.type}`,c.concat(p.type));m.context&&(u=m.context)}return{context:u?{...s.context,...u}:void 0}}function f(t,e){const s=ar(t);return(t,n)=>h(s,t,n,e)}function p(t,e){return(Array.isArray(t)?t:[t]).map((s,n)=>{const a=Array.isArray(t)?`${e}[${n}]`:e;if(nr(s))return(t,e)=>r(s,"transition",i(t,{enq:e}),a);const u=s.context?t=>o(s.context,"transitionContext",i(t),`${a}.context`):void 0,d=void 0!==s.input?t=>o(s.input,"input",i(t),`${a}.input`):void 0,f=!!u||!!s.actions?.length;return{matches:s.matches,target:f?void 0:s.target,to:f?(t,e)=>{const n=u?.(t),r=s.actions?.length?h(s.actions,n?{...t,context:{...t.context,...n}}:t,e,`${a}.actions`):void 0;return{target:s.target,context:r?.context??n,reenter:s.reenter}}:void 0,guard:c(s.guard,"guard",`${a}.guard`),description:s.description,reenter:s.reenter,meta:s.meta,input:d}})}function l(t,e){return(Array.isArray(t)?t:[t]).map((s,n)=>{const r=`${e}.invoke${Array.isArray(t)?`[${n}]`:""}`;return{src:s.src,id:s.id,registryKey:s.registryKey,input:void 0!==s.input?t=>o(s.input,"input",i(t),`${r}.input`):void 0,onDone:s.onDone?p(s.onDone,`${r}.onDone`):void 0,onError:s.onError?p(s.onError,`${r}.onError`):void 0,onSnapshot:s.onSnapshot?p(s.onSnapshot,`${r}.onSnapshot`):void 0,timeout:a(s.timeout,`${r}.timeout`),onTimeout:s.onTimeout?p(s.onTimeout,`${r}.onTimeout`):void 0}})}if(t.delays)for(const[e,n]of Object.entries(t.delays))"number"==typeof n?s.delays[e]=n:"string"==typeof n?s.delays[e]=er(n):n&&"object"==typeof n&&(s.delays[e]=t=>er(o(n.duration,"delay",i(t),`$.delays.${e}.duration`)));const y=function(t,e,s){const{assertResolvable:n}=s,r=[];function o(s,i,a=[]){if(!s)return;if(nr(s))return void n(s,i);if(n(s.params,`${i}.params`),t.guards?.[s.type]){if(a.includes(s.type))throw new Error(`Circular guard reference: ${a.concat(s.type).join(" -> ")}`);return void o(t.guards[s.type].when,`$.guards.${s.type}.when`,a.concat(s.type))}if(e.guards[s.type])return;const c=s.params;if("@xstate.not"!==s.type){if("@xstate.stateIn"!==s.type)throw new Error(`Missing guard source "${s.type}"`);if("string"==typeof c?.stateId)r.push({stateId:c.stateId,path:`${i}.params.stateId`});else if(!nr(c?.stateId))throw new Error(`Missing state ID at ${i}.params.stateId`)}else{if(!c?.guard)throw new Error(`Missing guard at ${i}.params.guard`);o(c.guard,`${i}.params.guard`,a)}}function i(s,r,o=[]){if(nr(s))return void n(s,r);if(!s||"string"!=typeof s.type)throw new Error(`Invalid action at ${r}`);if(n(s.params,`${r}.params`),s.type.startsWith("@xstate."))return void n(s,r);const a=t.actions?.[s.type];if(a){if(o.includes(s.type))throw new Error(`Circular action reference: ${o.concat(s.type).join(" -> ")}`);const t=Array.isArray(a)?a:[a];return void t.forEach((e,n)=>i(e,`${r}.actions.${s.type}${t.length>1?`[${n}]`:""}`,o.concat(s.type)))}if(!e.actions[s.type])throw new Error(`Missing action source "${s.type}"`)}function a(t,e){ar(t).forEach((t,s)=>i(t,`${e}[${s}]`))}function c(t,e){(Array.isArray(t)?t:t?[t]:[]).forEach((s,r)=>{const i=Array.isArray(t)?`${e}[${r}]`:e;if(nr(s))n(s,i);else{if(!s||"object"!=typeof s)throw new Error("string"==typeof s?`Invalid transition at ${i}: use { "target": ${JSON.stringify(s)} } instead of a string`:`Invalid transition at ${i}`);fr(s,ur,i),o(s.guard,`${i}.guard`),a(s.actions,`${i}.actions`),n(s.context,`${i}.context`),n(s.input,`${i}.input`)}})}for(const e of["actions","guards","delays"])for(const s of Object.keys(t[e]??{}))Ds(e,s);if(t.actions)for(const e of Object.keys(t.actions)){const s=Array.isArray(t.actions[e])?t.actions[e]:[t.actions[e]];s.forEach((t,n)=>i(t,`$.actions.${e}${s.length>1?`[${n}]`:""}`,[e]))}if(t.guards)for(const e of Object.keys(t.guards))o(t.guards[e].when,`$.guards.${e}.when`,[e]);if(t.delays)for(const e of Object.keys(t.delays)){const s=t.delays[e];n(s&&"object"==typeof s&&"duration"in s?s.duration:s,`$.delays.${e}`)}return function s(r,i){if(fr(r,"$"===i?[...dr,...hr]:dr,i),("history"===r.type||void 0!==r.history)&&!("string"==typeof r.target&&r.target.trim().length>0||Array.isArray(r.target)&&r.target.length>0&&r.target.every(t=>t.trim().length>0)))throw new Error(`History state at ${i} must declare a non-empty target.`);if(n(r.context,`${i}.context`),n(r.input,`${i}.input`),n(r.output,`${i}.output`),n(r.timeout,`${i}.timeout`),a(r.entry,`${i}.entry`),a(r.exit,`${i}.exit`),"choice"===r.type){if(!r.choice)throw new Error(`Choice state at ${i} must declare choice.`);Array.isArray(r.choice)?(cr(r.choice,`${i}.choice`),r.choice.forEach((t,e)=>{o(t.when,`${i}.choice[${e}].when`),n(t.context,`${i}.choice[${e}].context`),n(t.input,`${i}.choice[${e}].input`)})):n(r.choice,`${i}.choice`)}if(nr(r.route)&&n(r.route,`${i}.route`),r.invoke&&(Array.isArray(r.invoke)?r.invoke:[r.invoke]).forEach((t,s)=>{const o=`${i}.invoke${Array.isArray(r.invoke)?`[${s}]`:""}`;if(!e.actors[t.src])throw new Error(`Missing actor source "${t.src}"`);n(t.input,`${o}.input`),n(t.timeout,`${o}.timeout`),c(t.onDone,`${o}.onDone`),c(t.onError,`${o}.onError`),c(t.onSnapshot,`${o}.onSnapshot`),c(t.onTimeout,`${o}.onTimeout`)}),r.on)for(const t of Object.keys(r.on))c(r.on[t],`${i}.on.${t}`);if(r.after)for(const s of Object.keys(r.after)){if(Number.isNaN(Number(s))&&void 0===re(s)&&!t.delays?.[s]&&!e.delays[s])throw new Error(`Missing delay source "${s}"`);c(r.after[s],`${i}.after.${s}`)}if(c(r.always,`${i}.always`),c(r.onError,`${i}.onError`),c(r.onTimeout,`${i}.onTimeout`),r.states)for(const t of Object.keys(r.states))s(r.states[t],`${i}.states.${t}`)}(t,"$"),r}(t,s,n),v=t.context?{context:e=>o(t.context,"context",e,"$.context")}:{},m=Fn({...function t(e,s){return{id:e.id,initial:e.initial,type:e.type,history:e.history,target:e.target,description:e.description,tags:e.tags,input:e.input,timeout:a(e.timeout,`${s}.timeout`),states:e.states?Object.fromEntries(Object.entries(e.states).map(([e,n])=>[e,t(n,`${s}.states.${e}`)])):void 0,on:e.on?Object.fromEntries(Object.entries(e.on).map(([t,e])=>[t,p(e,`${s}.on.${t}`)])):void 0,always:e.always?p(e.always,`${s}.always`):void 0,onError:e.onError?p(e.onError,`${s}.onError`):void 0,choice:u(e.choice,`${s}.choice`),route:d(e.route,`${s}.route`),after:e.after?Object.fromEntries(Object.entries(e.after).map(([t,e])=>[t,p(e,`${s}.after.${t}`)])):void 0,onTimeout:e.onTimeout?p(e.onTimeout,`${s}.onTimeout`):void 0,entry:e.entry?f(e.entry,`${s}.entry`):void 0,exit:e.exit?f(e.exit,`${s}.exit`):void 0,invoke:e.invoke?l(e.invoke,s):void 0,meta:e.meta,output:rr(e.output)?({context:t,event:n,self:r,input:i})=>o(e.output,"output",{context:t,event:n,self:r,input:i},`${s}.output`):e.output}}(t,"$"),...v,version:t.version,...e.schemas&&{schemas:e.schemas}},e.validator);pr(m.root,"$");for(const{stateId:t,path:e}of y)if(!m.idMap.has(t.replace(/^#/,"")))throw new Error(`Unknown state ID "${t}" at ${e}`);t.internalEvents?.length&&(m.internalEventDescriptors=[...m.internalEventDescriptors,...t.internalEvents]);const g=m.provide({actions:s.actions,actors:s.actors,guards:s.guards,delays:s.delays});return g._json=t,g},t.machineToJSON=function(t){const e=t._json;return e?Bn(e):tr(t.config)},t.machineVersions=function(t,e){const s=new Map,n=new Map,r=t[0].id;for(const e of t){if(void 0===e.version)throw new Error(`Machine '${e.id}' must define a version.`);if("*"===e.version)throw new Error("Machine version '*' is reserved for wildcard migrations.");if(e.id!==r)throw new Error(`Machine '${e.id}' does not match machine ID '${r}'.`);const t=`${e.id}\0${e.version}`;if(s.has(t))throw new Error(`Duplicate machine identity '${e.id}' version '${e.version}'.`);s.set(t,e),Er(e)&&n.set(t,e)}if(void 0!==e?.unversioned&&!s.has(`${r}\0${e.unversioned}`))throw new Error(`Unversioned snapshot version '${e.unversioned}' is not retained for machine '${r}'.`);const o=async t=>{if(!xr(t))throw new Error("Persisted snapshot is missing machine identity.");let n,o;if(xr(t.machine)){if(({id:n,version:o}=t.machine),"string"!=typeof n||"string"!=typeof o)throw new Error("Persisted snapshot has an invalid machine identity.")}else if("string"==typeof t.version)n=r,o=t.version;else{if(void 0!==t.version||void 0===e?.unversioned)throw new Error("Persisted snapshot is missing machine identity.");n=r,o=e.unversioned}if(void 0!==t.version&&"string"!=typeof t.version)throw new Error("Persisted snapshot has an invalid version.");if(void 0!==t.version&&t.version!==o)throw new Error(`Persisted snapshot version '${t.version}' conflicts with machine version '${o}'.`);const i=s.get(`${n}\0${o}`);if(!i)throw new Error(`Unknown machine identity '${n}' version '${o}'.`);const a=Er(c=i)?wr(c):c.snapshotSchema;var c;if(!a)throw new Error(`Machine version '${o}' does not define a snapshot schema.`);const u=await $r(a,t,`snapshot for machine '${n}' version '${o}'`);return{source:i,...Er(i)&&{machine:i},snapshot:{...u,machine:{id:n,version:o}}}};return{parseSnapshot:o,async adaptEvents(t,e){const o=n.get(`${r}\0${e.to}`);if(!o)throw new Error(`Target version '${e.to}' is not backed by a machine for '${r}'.`);const i=e.from.id??r,a=s.get(`${i}\0${e.from.version}`);let c,u=!1;const d=a&&(Er(h=a)?br(h):h.eventSchema);var h;const f=!!a&&!!d;if(a&&d){let s;try{s=await kr(t,0,d)}catch(t){c=t,u=!0}if(s){if(a===o)return s;const t=e.adapters[a.version];if(t)return kr(await t(s),0,br(o))}}const p=e.adapters["*"];if(p)return kr(await p(t,e.from),0,br(o));if(f){if(u)throw c instanceof Error?c:new Error(`Unable to validate event history for machine '${a.id}' version '${a.version}'.`,{cause:c});throw new Error(`No event adapter from version '${a.version}' to '${o.version}' for machine '${o.id}'.`)}if(a)throw new Error(`Machine version '${a.version}' does not define an event schema; only the '*' adapter can handle its event history.`);throw new Error(`Unknown event history source '${i}' version '${e.from.version}'.`)},async migrateSnapshot(t,e){const s=n.get(`${r}\0${e.to}`);if(!s)throw new Error(`Target version '${e.to}' is not backed by a machine for '${r}'.`);let i,a;try{i=await o(t)}catch(t){a=t}if(i){if(i.source.version===s.version)return Sr(i.snapshot,s);const t=e.migrations[i.source.version];if(t)return Sr(await t(i.snapshot),s)}const c=e.migrations["*"];if(!c){if(i)throw new Error(`No snapshot migration from version '${i.source.version}' to '${s.version}' for machine '${s.id}'.`);throw a}const u=await c(t,function(t){return xr(t)&&xr(t.machine)?{id:"string"==typeof t.machine.id?t.machine.id:void 0,version:"string"==typeof t.machine.version?t.machine.version:void 0}:{}}(t));return Sr(u,s)}}},t.mapState=function(t,e){const s=[],n=(t,e)=>{let s=t;for(const t of e){if(!s?.states)return;const e=s.states;if(!(t in e))return;s=e[t]}return s},r=new Set;for(const o of t.nodes.filter(Te)){let i=o;for(;i&&!r.has(i);){r.add(i);const o=n(e,i.path);o?.map&&s.push({stateNode:i,result:o.map(t)}),i=i.parent}}return s},t.matchesState=qs,t.runStep=j,t.setup=jr,t.stopActor=M,t.systemTransition=function(t,e,s,n){const r=new Kr(t,e);return r.send(s,n),[r.result(),r.effects]},t.terminateActor=T,t.toPromise=function(t){return new Promise((e,s)=>{t.subscribe({complete:()=>{e(t.getSnapshot().output)},error:s})})},t.transition=function(t,e,s){const n=je(t,e);_e(n,e,!1);const[r,o]=Qt(n,e,t.transition(e,s,n));_e(n,r,!1);const i=r===e?r:be(n,r);return Wr(n,i,s),[i,o]},t.types=function(){return{"~standard":{version:1,vendor:"xstate.types",validate:t=>({value:t})}}},t.waitFor=function(t,s,n){const r={...Ur,...n};return new Promise((n,o)=>{const{signal:i}=r;if(i?.aborted)return void o(i.reason);let a=!1;const c=r.timeout===1/0?void 0:setTimeout(()=>{u(),o(new Error(e(75,r.timeout)))},r.timeout),u=()=>{clearTimeout(c),a=!0,f?.unsubscribe(),h&&i.removeEventListener("abort",h)};function d(t){s(t)&&(u(),n(t))}let h,f;d(t.getSnapshot()),a||(i&&(h=()=>{u(),o(i.reason)},i.addEventListener("abort",h)),f=t.subscribe({next:d,error:t=>{u(),o(t)},complete:()=>{u(),o(new Error(e(76)))}}),a&&f.unsubscribe())})},Object.defineProperty(t,"__esModule",{value:!0})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XState={})}(this,function(t){"use strict";function e(t,...e){return`XState error E${t}${e.length?` (${e.map(t=>"string"==typeof t?JSON.stringify(t):String(t)).join(", ")})`:""}. See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e${t}`}const s=["types","tsTypes","schema","internalEvents","services","devTools"],n=["onDone","onError","onTimeout","always"],r=["onDone","onError","onSnapshot","onTimeout"],o=/^xstate\.(done\.actor|error\.actor|snapshot|done\.state|after)\.(.+)$/;function i(t,s){const n=o.exec(t);if(n&&"*"!==n[2]&&("snapshot"!==n[1]||"actor"!==n[2]&&"actor.*"!==n[2]))throw new Error(e(3,t,s))}function a(t,s,n){if(t)for(const r of Array.isArray(t)?t:[t])if(r&&"object"==typeof r){if(void 0!==r.cond)throw new Error(e(4,s,n,"cond"));if(void 0!==r.guard)throw new Error(e(4,s,n,"guard"));if(void 0!==r.actions)throw new Error(e(4,s,n,"actions"))}}function c(t,s){if(function(t,s){if(t&&"object"==typeof t){if(void 0!==t.cond)throw new Error(e(5,s,"cond"));if(void 0!==t.guard)throw new Error(e(5,s,"guard"));if(void 0!==t.actions)throw new Error(e(5,s,"actions"))}}(t.initial,s),void 0!==t.activities)throw new Error(e(6,s));for(const n of["entry","exit"]){const r=t[n];if(void 0!==r&&"function"!=typeof r)throw new Error(e(7,s,n))}if(t.on)for(const e of Object.keys(t.on))i(e,s),a(t.on[e],e,s);if(t.after)for(const e of Object.keys(t.after))a(t.after[e],`after.${e}`,s);for(const e of n)a(t[e],e,s);if(t.invoke)for(const e of Array.isArray(t.invoke)?t.invoke:[t.invoke])if(e&&"object"==typeof e)for(const t of r)a(e[t],`invoke.${t}`,s);if(t.states)for(const e of Object.keys(t.states)){const n=t.states[e];n&&"object"==typeof n&&c(n,n.id??(s?`${s}.${e}`:e))}}function u(t){if(t&&"object"==typeof t){for(const n of s)if(void 0!==t[n])throw new Error(e(1,n));c(t,t.id??"")}}const d=new Set(["clock","logger","syncSnapshot","id","registryKey","input","src","inspect","onRejectedEvent","onUnhandledEvent","_systemRef","_sessionId","_inert","_restore"]);const h="xstate.init",f="@xstate.spawn",p="xstate.stop",l="@xstate.terminate",y="xstate.timer",v="xstate.logic.effect.resolve",m="xstate.logic.effect.reject",g="xstate.logic.effect.start",_={unsubscribe(){}};function w(t){return!0===t._remote}function b(t){if("object"!=typeof t||null===t||Array.isArray(t)||"string"!=typeof t["@actor"])return!1;for(const e in t)if("@actor"!==e&&"incarnation"!==e)return!1;const e=t.incarnation;return void 0===e||"string"==typeof e}function x(t){const e=t.slice(t.lastIndexOf("/")+1);return e.includes("%")?e.replaceAll("%2F","/").replaceAll("%25","%"):e}function E(t){return new Error(e(50,...void 0===t.incarnation?[t["@actor"]]:[t["@actor"],t.incarnation]))}function S(t,e){const s=t._getByAddress?.(e["@actor"]);return!s||void 0!==e.incarnation&&s.sessionId!==e.incarnation?void 0:s}const k=Object.freeze({status:"active",output:void 0,error:void 0});function $(t,e,s){return t.system._notifyEmitted(t,e),s.emitEvent(t,e)}const A=new WeakMap;async function j(t,s,n,r=e=>{t.system.sendEvent(t,t,e)}){const o=function(t,e){const s=t.getSnapshot().effects;return s&&Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0}(t,s);if("done"===o?.status)return o.output;if("error"===o?.status)throw o.error;const i=A.get(t)?.get(s);if(i)return i;if("active"!==t.getSnapshot().status)throw new Error(e(72,s));let a,c;const u=new Promise((t,e)=>{a=t,c=e});let d,h=A.get(t);h||(h=new Map,A.set(t,h)),h.set(s,u);const f=()=>{d?.unsubscribe(),h.delete(s),h.size||A.delete(t)};return u.then(f,f),d=t.subscribe({error:c,complete:()=>c(new Error(e(72,s)))}),(async()=>{try{r({type:g,key:s});const e=await n();"active"===t.getSnapshot().status&&(r({type:v,key:s,output:e}),a(e))}catch(e){"active"===t.getSnapshot().status&&r({type:m,key:s,error:e}),c(e)}})().catch(c),u}function O(t,e,s){if(b(e)){const n=e,r=t?.system,o=r&&S(r,n);if(!o){const e=E(n);if(!r)throw e;return void r.deadLetter(t,void 0,s,"missingTarget",{targetId:x(n["@actor"]),error:e})}e=o}if(I(t,e,s))return;e._send(s,t)}function I(t,s,n){const r=function(t,s,n){const r=s;if(t!==s&&r.logic?.isInternalEventType?.(n.type))return new Error(e(73,n.type,s.id))}(t,s,n);return!!r&&(s.system.deadLetter(t,s,n,"internalEvent",{error:r}),!0)}function T(t,e){t._terminate(e)}function M(t){t._stop()}class R{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}}function P(t,e){return{type:"xstate.after",delay:t,stateId:e}}function N(t,e){return{type:"xstate.timeout.actor",actorId:t,sessionId:e}}function q(t,e){return{type:"xstate.done.state",stateId:t,output:e}}function D(t,e,s){return{type:"xstate.done.actor",output:e,actorId:t,sessionId:s}}function L(t,e,s){return{type:"xstate.error.actor",error:e,actorId:t,sessionId:s}}function C(t,e){return{type:`xstate.error.${t}`,error:e}}function K(t){return{type:h,input:t}}function z(t){setTimeout(()=>{throw t})}const W="function"==typeof Symbol&&Symbol.observable||"@@observable",V=[],U=new Error("Transition effect");function J(t,e="abort"){const s={mode:e,parent:t,requiresReevaluation:!1};return V.push(s),{frame:s,close(){V.pop()}}}function F(t){const{stateId:e,delay:s,actorId:n}=t;switch(t.type){case"xstate.after":return{type:t.type,delay:s,stateId:e};case"xstate.timeout.state":return{type:t.type,stateId:e};case"xstate.timeout.actor":return{type:t.type,actorId:n}}}function B(t){return void 0!==t.id?{id:t.id}:void 0!==t.seq?{seq:t.seq}:{event:F(t.event)??t.event}}function H(t){const e=t;return"string"==typeof e.id?{id:e.id}:"number"==typeof e.seq?{seq:e.seq}:e.event&&"object"==typeof e.event&&"string"==typeof e.event.type?{event:e.event}:void 0}function X(t,e){if("id"in e)return t.id===e.id;if(void 0!==t.id)return!1;if("seq"in e)return t.seq===e.seq;if(void 0!==t.seq)return!1;const s=t.event,n=e.event;for(const t in n)if(s[t]!==n[t])return!1;return!0}function G(t){return"id"in t?JSON.stringify(["id",t.id]):"seq"in t?JSON.stringify(["seq",t.seq]):JSON.stringify(["event",F(t.event)??t.event])}function Q(t,e){return`${t.sessionId}|${G(e)}`}const Y=new WeakMap;function Z(t){return Y.get(t)??t.scheduledAt}function tt(t){if("string"==typeof t)throw new Error(e(70,t))}const et={"@xstate.spawn":t=>t.system.spawnActor(t._parent,t),"@xstate.start":t=>t.system.startActor(t),"@xstate.raise":(t,e,s)=>t.system.scheduleTimer(t.self,B({id:s.id,seq:s.seq,event:e}),s?.delay??0),"@xstate.sendTo":(t,e,s,n)=>(tt(s),void 0!==n?.delay?t.system.scheduleTimer(t.self,B({id:n.id,seq:n.seq,event:s}),n?.delay??0):t.system._relay(t.self,e,s)),"@xstate.cancel":(t,e)=>t.system.cancelTimer(t.self,e),"@xstate.stop":(t,e)=>t.system.stopActor(e),"@xstate.terminate":(t,e)=>t.system.terminateActor(t,e)},st=new WeakMap;function nt(t,e){let s=st.get(t);if(!s){s=new Map;for(const e of Object.keys(t)){const n=t[e];s.has(n)||s.set(n,e)}st.set(t,s)}return s.get(e)}const rt=Symbol("xstate.systemLogicMetadata"),ot=new WeakMap;function it(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]],n={id:e,start:(e,{self:s,system:n})=>{const r=e.input.actor;if(!r||"stopped"===r.getSnapshot().status)return;const o=t(e.input,{self:s,system:n});if(!o)return;let i,a=!1;const c=()=>{a||(a=!0,o.unsubscribe(),i?.unsubscribe())},u=s._parent;u&&(i=u.subscribe({complete:c,error:c})),ot.set(s,{unsubscribe:c})},transition:(t,e,{self:s})=>e.type===p?(ot.get(s)?.unsubscribe(),ot.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return Object.defineProperty(n,rt,{value:{kind:e}}),n}function at(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function ct(){return it(({actor:t,eventType:e,mapper:s},{self:n,system:r})=>{const o="*"!==e&&e.endsWith(".*");return t.on(o?"*":e,t=>{o&&!sn(t.type,e)||at(n,r,()=>s(t))})},"@xstate.listener")}const ut=ct();function dt(){return it(({actor:t,mappers:e},{self:s,system:n})=>{const{done:r,error:o,snapshot:i}=e;return t.subscribe({next:t=>{"done"===t.status&&r?at(s,n,()=>r(t.output)):"error"===t.status&&o?at(s,n,()=>o(t.error)):"active"===t.status&&i&&at(s,n,()=>i(t))},error:t=>{o&&at(s,n,()=>o(t))},complete:()=>{}})},"@xstate.subscription")}const ht=dt();function ft(){const t=this.action?.(...this.args);return t}function pt(t=this.source.system){return $(this.source,this.event,t)}function lt(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function yt(t,e,s,n,r){return{kind:"builtin",type:"@xstate.deadLetter",exec:lt,source:e,target:t.self,event:s,reason:n,detail:r,params:void 0,args:[]}}function vt(t,s,n){return{kind:"builtin",type:"@xstate.deadLetter",exec:lt,source:t.self,target:void 0,event:s,reason:"missingTarget",detail:{targetId:n,error:new Error(e(65,n))},params:void 0,args:[]}}function mt(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function gt(t=this.actor.system){return t.spawnActor(this.source,this.actor)}function _t(t=this.actor.system){if(2!==this.actor._processingStatus)return t.startActor(this.actor)}function wt(t=this.source.system){return t.stopActor(this.actor)}function bt(t=this.actor.system){const e="done"===this.status?{status:"done",output:this.output,error:void 0}:{status:"error",output:void 0,error:this.error};return t.terminateActor(this.actor,e)}function xt(t=this.source.system){return t.scheduleTimer(this.source,B(this),this.delay??0)}function Et(t=this.source.system){return tt(this.event),void 0!==this.delay?t.scheduleTimer(this.source,B(this),this.delay):t.sendEvent(this.source,this.target,this.event)}function St(t=this.source.system){return t.cancelTimer(this.source,H(this))}function kt(t,e,s){if(!Yt(e))return t;if("@xstate.cancel"===e.type){const s=H(e);return t.timers?.some(t=>X(t,s))?{...t,timers:t.timers.filter(t=>!X(t,s))}:t}if("@xstate.raise"!==e.type&&"@xstate.sendTo"!==e.type||void 0===e.delay)return t;let n=t._nextTimerId??0;if(void 0===e.id&&!F(e.event)){e.seq=n++;const t=e.args;t[t.length-1]={...t[t.length-1],seq:e.seq}}const r="@xstate.raise"===e.type||e.target===s.self?"self":e.target,o={...void 0!==e.id&&{id:e.id},...void 0!==e.seq&&{seq:e.seq},delay:e.delay,type:e.type,event:e.event,target:r},i=B(o),a=t.timers??[],c=a.findIndex(t=>X(t,i));return{...t,timers:-1===c?[...a,o]:a.map((t,e)=>e===c?o:t),_nextTimerId:n}}function $t(t,e){return{...t,...e}}function At(t,e,...s){const n={action:e,args:s};return t.push(n),n}function jt(t,e){const s={...t};for(const t of Object.keys(e))s[t]=Math.max(s[t]??0,e[t]);return s}function Ot(t,s,n){if("add"===s.type)return{...t,children:{...t.children,[s.id]:s.actor},...s.counters&&{_nextActorIds:jt(t._nextActorIds,s.counters)}};const r={...t.children};let o=s.actor._parent===n.self;for(const t of Object.keys(r))r[t]===s.actor&&(o=!0,delete r[t]);if(!o)throw new Error(e(47,s.actor.id,n.self.id));return n.system._unregister(s.actor),{...t,children:r}}function It(t){if("object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action)return t}const Tt=new WeakMap,Mt=()=>({counters:new Map,explicitIds:new Set,stoppedIds:new Set});function Rt(t){Tt.set(t,Mt())}function Pt(t){return t.self._snapshot}function Nt(t,e,s){return Math.max(e.counters.get(s)??0,Pt(t)?._nextActorIds?.[s]??0)}function qt(t,e,s){let n=Nt(t,e,s);const r=Pt(t)?.children;for(;e.explicitIds.has(`${s}:${n}`)||r?.[`${s}:${n}`];)n++;return n}function Dt(t,e,s){const n=Tt.get(t)??s??Mt(),r=an(e),o=qt(t,n,r);return n.counters.set(r,o+1),{id:`${r}:${o}`,counters:{[r]:o+1}}}function Lt(t,s,n){const r=Tt.get(t)??n??Mt(),o=Pt(t)?.children?.[s],i=void 0!==o&&!r.stoppedIds.has(s)&&"active"===o.getSnapshot().status;if(r.explicitIds.has(s)||i)throw new Error(e(67,s,t.self.id));r.explicitIds.add(s)}function Ct(t,e,s){const n=un(e);if(!n)return;n.prefix;const r=Tt.get(t)??s??Mt(),o=Math.max(Nt(t,r,n.prefix),n.index+1);return r.counters.set(n.prefix,o),{[n.prefix]:o}}const Kt=new WeakSet;function zt(t){if("string"==typeof t)throw new Error(e(68,t))}function Wt(t,s,n,r=!1,o=!0){const i=Tt.get(t)??Mt(),a={cancel:e=>{At(s,et["@xstate.cancel"],t,"string"==typeof e?{id:e}:e)},emit:t=>{s.push(t)},log:(...e)=>{At(s,t.logger,...e)},raise:(e,r)=>{zt(e),void 0!==r?.delay?At(s,et["@xstate.raise"],t,e,r):n.push(e)},spawn:(n,r)=>{const{logic:a,src:c}=function(t,s){const n=function(t){return t.self.logic?.sources?.actors}(t);if("string"==typeof s){const t=n?.[s];if(!t)throw new Error(e(66,s));return{logic:t,src:s}}return n?{logic:s,src:nt(n,s)}:{logic:s,src:void 0}}(t,n);if(!o){const s=an(c??a),n=r?.id??`${s}:${qt(t,Tt.get(t)??i,s)}`;return function(t){const{id:s,address:n}=t,r={ref:void 0,id:s,address:n,src:t.src,sessionId:void 0,send(){},getSnapshot:()=>k,subscribe:()=>_,on:()=>_,toJSON(){if(void 0===n)throw new Error(e(51,s));return{"@actor":n}}},o=r;return r.ref=o,o}({id:n,address:Kt.has(t)?void 0:`${t.self.address}/${cn(n)}`,src:c})}let u,d=r?.id;void 0===d?({id:d,counters:u}=Dt(t,c??a,i)):(Lt(t,d,i),u=Ct(t,d,i));const h=t.system.createActorRef(a,{...r,...void 0!==c&&{src:c},id:d,parent:t.self});return function(t,e,s,n){At(t,et["@xstate.spawn"],e).childUpdate={type:"add",actor:e,id:s,counters:n}}(s,h,d,u),h},sendTo:(e,n,r)=>{At(s,et["@xstate.sendTo"],t,e,n,r)},stop:e=>{if(e){const n=e;At(s,et["@xstate.stop"],t,n).childUpdate={type:"remove",actor:n},function(t,e){const s=Tt.get(t);s&&(s.stoppedIds.add(e.id),s.explicitIds.delete(e.id))}(t,n)}}};r&&Object.assign(a,{listen:(e,n,r)=>{if(!o)return{id:void 0};const i={actor:e,eventType:n,mapper:r},a=t.system.createActorRef(ut,{input:i,parent:t.self});return At(s,et["@xstate.spawn"],a),a},subscribeTo:(e,n)=>{if(!o)return{id:void 0};const r={actor:e,mappers:"function"==typeof n?{snapshot:n}:n},i=t.system.createActorRef(ht,{input:r,parent:t.self});return At(s,et["@xstate.spawn"],i),i}});let c=!1;const u=t=>(...e)=>c?Jt():t(...e);for(const t of Object.keys(a))a[t]=u(a[t]);const d=te(a,u((t,...e)=>{"function"==typeof t&&At(s,t,...e)}));return Vt.set(d,()=>{c=!0}),d}const Vt=new WeakMap;function Ut(t){Vt.get(t)?.()}function Jt(){}function Ft(t,e){switch(t){case et["@xstate.spawn"]:{const[t]=e;return{type:"@xstate.spawn",kind:"builtin",exec:gt,source:t._parent,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case et["@xstate.raise"]:{const[,t,s]=e;return{type:"@xstate.raise",kind:"builtin",exec:xt,source:e[0].self,event:t,id:s?.id,delay:s?.delay}}case et["@xstate.sendTo"]:{const[,t,s,n]=e;return{type:"@xstate.sendTo",kind:"builtin",exec:Et,source:e[0].self,target:t,event:s,id:n?.id,delay:n?.delay}}case et["@xstate.cancel"]:{const[,t]=e;return{type:"@xstate.cancel",kind:"builtin",exec:St,source:e[0].self,...t}}case et["@xstate.stop"]:{const[,t]=e;return{type:"@xstate.stop",kind:"builtin",exec:wt,source:e[0].self,actor:t,id:t.id}}default:return}}function Bt(t){const e=[t];return{kind:"builtin",exec:_t,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function Ht(t){const e=[t];return{kind:"builtin",exec:gt,type:f,source:t._parent,params:void 0,args:e,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}function Xt(t,e,s){const n=[t,e,s,{}];return{kind:"builtin",exec:Et,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:n}}function Gt(t,s){if("done"!==s.status&&"error"!==s.status)throw new Error(e(69,t.self.id,s.status));const n="done"===s.status?{status:"done",output:s.output,error:void 0}:{status:"error",output:void 0,error:s.error},r=[t.self,n];return{kind:"builtin",exec:bt,type:l,source:t.self,actor:t.self,id:t.self.id,...n,params:void 0,args:r}}function Qt(t,e,[s,n]){const r="done"===s.status||"error"===s.status,o="done"===e?.status||"error"===e?.status,i=n.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===l);return!r||o||i?[s,n]:[s,[...n,Gt(t,s)]]}function Yt(t){return"builtin"===t.kind}function Zt(t,e,s,n){let r=t;const o=[];for(const t of n){const e="function"==typeof t,n=It(t);let i=n?.args;if(n?.action===et["@xstate.sendTo"]&&(void 0===n.args[1]||"string"==typeof n.args[1])){const t=n.args[1],e=void 0!==t&&Object.hasOwn(r.children,t)?r.children[t]:void 0;if(!e){o.push(vt(s,n.args[2],t));continue}i=[n.args[0],e,...n.args.slice(2)]}const a=e?t:!!n&&n.action.bind(null,...i);let c;if("object"==typeof t&&null!==t){const{type:e,childUpdate:s,...n}=t;c=n}if(n?.childUpdate&&(r=Ot(r,n.childUpdate,s)),!a||!("resolve"in a)){const a="object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action?Ft(t.action,i):void 0,u="object"==typeof t&&null!==t&&!n,d={kind:a?"builtin":u?"emit":"action",type:"object"==typeof t?"action"in t&&"function"==typeof t.action?t.action.name??"(anonymous)":t.type:t.name||"(anonymous)",params:a?void 0:c,args:"object"==typeof t&&"action"in t?i:[],...a?{}:u?{source:s.self,event:t}:{action:n?.action??(e?t:void 0)},...a?{}:{exec:u?pt:ft},...a};r=kt(r,d,s),o.push(d);continue}}return[r,o]}function te(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:ee,emit:ee,log:ee,raise:ee,spawn:se,sendTo:ee,stop:ee,listen:se,subscribeTo:se,...t}),s}const ee=()=>{},se=()=>({});function ne(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 r=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(!r?.groups)return;const{weeks:o,days:i,hours:a,minutes:c,seconds:u}=r.groups;if(!(o||i||a||c||u))return;const d=t=>t?Number(t.replace(",",".")):0;return 7*d(o)*24*60*60*1e3+24*d(i)*60*60*1e3+60*d(a)*60*1e3+60*d(c)*1e3+1e3*d(u)}function re(t){if(void 0!==t)return"number"==typeof t?t:ne(t)}const oe=new WeakMap,ie=["runtime","_timerMap","_rejectionListeners","_inspectionObservers","_emissionListeners"],ae=new WeakMap;let ce;const ue=new WeakMap,de=new WeakMap,he=new Map;function fe(t){const e=t._peekKeyedActors;return e?e.call(t)??he:t.keyedActors}function pe(t){t._snapshotVersion++}function le(t){return t._snapshotVersion}function ye(t,s,n,r){const o=oe.get(t),i=o?.executionSystem??t,a=o?.rootSystem??t,c=void 0!==r&&ae.get(i)!==r,u=!!r&&!!r.inspect,d=function(t,e){if(e){const t=new Map(e.children);return e.root?.sessionId&&t.set(e.root.sessionId,e.root),t}return new Map(t.children)}(t,n),h=new Map(n?.keyedActors??fe(t)),f=new WeakMap,p=()=>oe.get(y).executionSystem,l=()=>oe.get(y).forwardInspection,y=Object.assign(Object.create(i),{children:d,keyedActors:h,reverseKeyedActors:f,_snapshot:{...n?.snapshot??t._snapshot},_snapshotVersion:n?.sourceVersion??t._snapshotVersion,_register:(t,e)=>(d.set(t,e),pe(y),t),_unregister:t=>{t.sessionId&&d.delete(t.sessionId);const e=f.get(t);void 0!==e&&h.get(e)===t&&h.delete(e),f.delete(t),pe(y)},_set:(t,s)=>{const n=h.get(t);if(n&&n!==s)throw new Error(e(45,String(t)));h.set(t,s),f.set(s,t),pe(y)},get:t=>h.get(t),getAll:()=>Object.fromEntries(h),onEmitted:t=>a.onEmitted.call(p(),t),_notifyEmitted:(t,e)=>a._notifyEmitted.call(p(),t,e),_hasInspectionObservers:()=>l()&&(a._hasInspectionObservers?.call(p())??!1),_sendInspectionEvent:t=>{l()&&a._sendInspectionEvent.call(p(),t)}}),v=c?y:i;if(c)!function(t,e,s){const n=e._timerMap;for(const e of ie)Object.defineProperty(t,e,{configurable:!0,writable:!0,value:"runtime"===e?s.runtime:"_timerMap"===e&&n?{...n}:void 0});ae.set(t,s),s.inspect&&t.inspect(s.inspect)}(y,i,r);else for(const t of ie)Object.defineProperty(y,t,{configurable:!0,get:()=>p()[t],set:e=>{p()[t]=e}});oe.set(y,{executionSystem:v,rootSystem:a,forwardInspection:u});for(const[t,e]of h)e&&f.set(e,t);for(const t of Object.values(s)){if(!t)continue;t.sessionId&&d.set(t.sessionId,t);const e=t.registryKey;e&&(h.set(e,t),f.set(t,e))}return y}function ve(){const t=ce;return ce=void 0,t}function me(t){const e=ue.get(t);if(e)return e;const s=de.get(t);if(!s)return;const n=s();return ue.set(t,n),de.delete(t),n}function ge(t,e){const s=ue.get(t);if(s)return ue.set(e,s),!0;const n=de.get(t);return!!n&&(de.set(e,n),!0)}function _e(t,e,s=e.system,n){de.delete(t);const r=le(s),o=n?me(n):void 0,i=o?.actor===e?o:me(t);if(i?.actor===e&&i.systemState.sourceSystem===s&&i.systemState.sourceVersion===r)return void ue.set(t,i);const a=function(t){const e=t._getRootActor?.(),s=t._peekChildren?.();if(!e&&!s){if(t._getRootActor&&t._peekChildren)return{};const e=new Map(t.children);return e.size?{children:e}:{}}return s?.size?{children:new Map(t.children)}:e?{root:e}:{}}(s);let c=a.children;const u=fe(s);let d=u.size?new Map(u):he;for(const e of Object.values(function(t){return"children"in t&&t.children?t.children:{}}(t))){if(!e)continue;e.sessionId&&(c??=new Map).set(e.sessionId,e);const t=e.registryKey;t&&(d===he&&(d=new Map),d.set(t,e))}ue.set(t,{actor:e,systemState:{...a,children:c,keyedActors:d,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:r}})}const we=Symbol();function be(t){return!!t[we]}function xe(t){return be(t)?t._parent:t.self._parent}function Ee(t,e){if(!be(e)){const s=t,n=e.self;return s.self=n,s.system=e.system,s.parent=n._parent,s}return Object.defineProperties(t,{self:{enumerable:!0,get:()=>e.self},system:{enumerable:!0,get:()=>e.system},parent:{enumerable:!0,get:()=>xe(e)}}),t}function Se(t,e,s=!0){const n=Ie(t);if(n){n.snapshot=e;const t=n.materialized??n.identityScope;t&&(t.self._snapshot=e)}else t.self._snapshot=e;return s&&e&&"object"==typeof e&&_e(e,t.self),e}function ke(t){return!!Ie(t)||!!t.self.options?._inert}function $e(t,e){Se(t,e,!1);const s=Ie(t);Oe.set(e,t);const n=()=>(_e(e,t.self,t.system),me(e));return s&&(s.materialized?s.identityProvider=n:s.identityProvider??=n),function(t,e){ue.delete(t),de.set(t,e)}(e,n),e}function Ae(t,e){return t.sourceRef=void 0,t.sourceChildren={},t.materialized=e,t.materialize=()=>e,e}const je=Symbol(),Oe=new WeakMap;function Ie(t){return t[je]}function Te(t){return Ie(t).materialize()}const Me={[we]:!0,get _parent(){const t=Ie(this);return t.parentKnown?t.parent:Te(this).self._parent},get self(){return Te(this).self},get defer(){return Te(this).defer},get id(){return Te(this).id},get logger(){return Te(this).logger},get sessionId(){return Te(this).sessionId},get stopChild(){return Te(this).stopChild},get system(){return Te(this).system},get emit(){return Te(this).emit},get actionExecutor(){return Te(this).actionExecutor}};function Re(t,e,s,n,r,o){const i=e?.(),a=r??i?.actor,c=a?.system,u=a&&c?ye(c,s,r?void 0:i?.systemState,o):void 0,d=kn(t,{_inert:!0,...a?{id:a.id,_sessionId:a.sessionId}:{},...u?{_systemRef:{current:u}}:{}});a?._parent&&(d._parent=a._parent,d._address=void 0);const h=Object.create(d._actorScope,{defer:{value:()=>{}},stopChild:{value:t=>t._stop()},actionExecutor:{value:()=>{}},_snapshot:{enumerable:!0,configurable:!0,get:()=>d._snapshot,set:t=>{d._snapshot=t}}});return n&&(h._snapshot=n),h}function Pe(t,e,s,n){const r=n??(e&&"object"==typeof e?Oe.get(e):void 0),o=r?Ie(r):void 0,i=e&&"object"==typeof e?function(t){return ue.get(t)}(e):void 0,a=o?.identityProvider??(e&&"object"==typeof e?function(t){const e=ue.get(t);return e?()=>e:de.get(t)}(e):void 0),c={snapshot:e,sourceRef:a,sourceChildren:Is(e)?e.children:{},identityProvider:o?.identityProvider??a,parent:s?._parent??o?.parent??i?.actor._parent,owner:n?o?.owner:ve(),parentKnown:!(!s&&!o?.parentKnown&&!i&&e),materialize:()=>{const e=Re(t,c.sourceRef,c.sourceChildren,c.snapshot,s,c.owner);return Ae(c,e)}};if(!c.identityProvider&&!e){const e={};let n;const r=()=>(c.identityScope||(c.identityScope=Re(t,c.sourceRef,c.sourceChildren,void 0,s,c.owner),void 0!==c.snapshot&&(c.identityScope.self._snapshot=c.snapshot)),c.identityScope);c.materialize=()=>{const t=r();return void 0!==c.snapshot&&(t.self._snapshot=c.snapshot),Ae(c,t)},c.identityProvider=()=>{if(n)return n;const t=r();return _e(e,t.self,t.system),n=me(e)}}const u=Object.create(Me);return u[je]=c,u}function Ne(t,s,n){if("function"==typeof t)return t(n);const r=function(t,s){if("string"!=typeof t)return t;const n=s[t];if(void 0!==n)return n;const r=ne(t);if(void 0===r)throw new Error(e(9,t));return r}(t,s);return"function"==typeof r?r(n):r}function qe(t,e){return t._stateInputs?.[e]}function De(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function Le(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Ce(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 Ke(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 Le(t))if(!e.has(s)){const t=ts(s);for(const s of t)e.add(s)}}else for(const s of ts(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 ze(t,e){const s=Ke(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 r=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(De(t))return t.key}const s={};for(const t of e)s[t.key]=r(t);return s};return r(t)}function We(t,e){return"compound"===e.type?Le(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?Le(e).every(e=>We(t,e)):"final"===e.type}const Ve=t=>"#"===t[0];function Ue(t,e,s){const n=e.children[s];return!n||!("sessionId"in t)||(void 0===n.sessionId||n.sessionId===t.sessionId)}function Je(t,e,s,n){const r=t.entry;t.entry=(t,e)=>{const o="function"==typeof r?r(t,e):void 0,i=void 0!==o?.context?$t(t.context,o.context):t.context;return e.raise(s(t),{delay:n({context:i,event:t.event,delays:t.delays,input:t.input})}),o};const o=t.exit;t.exit=(t,s)=>(s.cancel({event:F(e)}),"function"==typeof o?o(t,s):void 0)}function Fe(t,s,n){const r=function(t){const{cond:e,actions:s,guard:n}=t;if(void 0!==e)return'"cond"';if(void 0!==s)return'"actions"';if(void 0!==n&&"function"!=typeof n)return'an object-form "guard"';return}(n);if(r)throw new Error(e(10,s||"always",t.id,r));const o=Ys(n.target),i=n.reenter??!1,a=Qe(t,o);Ge(t,a);const c={...n,target:a,source:t,reenter:i,eventType:s,toJSON:()=>Be(c)};return c}function Be(t){const{definition:e,...s}=t;return{...s,source:`#${t.source.id}`,target:t.target?.map(t=>`#${t.id}`)}}function He(t,e){for(let s=t.parent;s;s=s.parent)if(s===e)return!0;return!1}function Xe(t,e){const s=new Set;for(let e=t;e;e=e.parent)s.add(e);for(let t=e;t;t=t.parent)if(s.has(t))return t}function Ge(t,s){if(s&&!(s.length<2))for(let n=0;n<s.length;n++)for(let r=n+1;r<s.length;r++){const o=s[n],i=s[r],a=Xe(o,i);if(o===i||He(o,i)||He(i,o)||"parallel"!==a?.type)throw new Error(e(11,t.id))}}function Qe(t,s){if(void 0!==s)return s.map(s=>{if("string"!=typeof s)return s;if(Ve(s))return t.machine.getStateNodeById(s);const n="."===s[0];if(n&&!t.parent)return ss(t,s.slice(1));const r=n?t.key+s:s;if(!t.parent)throw new Error(e(13,s));try{return ss(t.parent,r)}catch(s){throw new Error(e(12,t.id,s.message))}})}function Ye(t){const e=Ys(t.config.target);if(!e)return"parallel"===t.parent.type?{target:[t.parent],source:t,reenter:!1,eventType:""}:t.parent.initial;const s=e.map(e=>"string"==typeof e?ss(t.parent,e):e);return Ge(t,s),{target:s,source:t,reenter:!1,eventType:"",to:t.config._historyDefaultTransition}}function Ze(t){return"history"===t.type}function ts(t){const e=new Set;!function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)for(const e of s.initial.target??[])t(e);else if("parallel"===s.type)for(const e of Le(s))t(e)}(t);for(const s of e)for(const n of Ce(s,t))e.add(n);return e}function es(t,s){const n=t.states?.[s];if(!n)throw new Error(e(14,s,t.id));return n}function ss(t,e){if("string"==typeof e&&Ve(e))return t.machine.getStateNodeById(e);const s=Us(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=es(n,t)}return n}function ns(t,s){if("string"==typeof s){const n=t.states[s];if(!n)throw new Error(e(14,s,t.id));return[t,n]}const n=Object.keys(s),r=new Array(n.length),o=[t.machine.root,t];for(let e=0;e<n.length;e++){const s=es(t,n[e]);r[e]=s,o.push(s)}for(let t=0;t<n.length;t++)o.push(...ns(r[t],s[n[t]]));return o}function rs(t,e,s,n,r,o){if("string"==typeof e){const i=es(t,e).next(s,n,r,o);return i&&i.length?i:t.next(s,n,r,o)}const i=Object.keys(e),a=i[0];if(1===i.length){const i=rs(es(t,a),e[a],s,n,r,o);return i&&i.length?i:t.next(s,n,r,o)}const c=[];for(const a of i){const i=e[a];if(!i)continue;const u=rs(es(t,a),i,s,n,r,o);u&&c.push(...u)}return c.length?c:t.next(s,n,r,o)}function os(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function is(t,e){for(const s of t)if(os(s,e))return!0;return!1}function as(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 r=t instanceof Set?t:new Set(t);for(const t of e)if(r.has(t))return!0;return!1}function cs(t,e,s,n){const r=new Set,o=new Map,i=t=>{let r=o.get(t);return r||(r=ps([t],e,s,n),o.set(t,r)),r};for(const e of t){let t=!1;const s=new Set;for(const n of r)if(as(i(e),i(n))){if(!os(e.source,n.source)){t=!0;break}s.add(n)}if(!t){for(const t of s)r.delete(t);r.add(e)}}return Array.from(r)}function us(t,e,s,n,r){let o;return(i,a)=>{if(!i.to&&!a)return{targets:i.target,context:void 0,reenter:i.reenter,actions:void 0,internalEvents:void 0,input:void 0};let c=o?.get(i);return c||(c=vs(i,t,e,s,{resolveActions:n,selectionResult:r?.get(i)}),(o??=new Map).set(i,c)),c}}function ds(t,e,s){const n=e.historyValue,{targets:r}=s(t);if(!r)return[];const o=new Set;for(const t of r)if(Ze(t))if(n[t.id])for(const e of n[t.id])o.add(e);else for(const n of ds(Ye(t),e,s))o.add(n);else o.add(t);return[...o]}function hs(t,e){let s=t;for(;"parallel"===s.type;){const t=Le(s).find(t=>e.every(e=>e===t||os(e,t)));if(!t)break;s=t}return s}function fs(t,e,s){const n=ds(t,e,s),{targets:r,reenter:o}=s(t);if(t._transitionDomain){if("internal"===t._transitionDomain&&"compound"===t.source.type&&n.every(e=>os(e,t.source)))return t.source;const[e,...s]=n.concat(t.source);for(const t of Ce(e,void 0))if("compound"===t.type&&s.every(e=>os(e,t)))return t;return}if(!(r?.some(Ze)&&n.some(e=>e===t.source))&&n.every(e=>e===t.source||os(e,t.source)))return o?t.source:hs(t.source,n);const[i,...a]=n.concat(t.source);for(const t of Ce(i,void 0))if(a.every(e=>os(e,t)))return o?t:hs(t,n);return o?void 0:hs(t.source.machine.root,n)}function ps(t,e,s,n){const r=new Set;for(const o of t){const{targets:t,reenter:i}=n(o);if(t?.length){const t=fs(o,s,n);i&&o.source===t&&r.add(t);for(const s of e)os(s,t)&&r.add(s)}}return[...r]}function ls(t,e,s,n,r){t.machine._microstepHooks?.begin(s.self);const o=[...ts(t)],i=new Set,a=t=>{if("compound"===t.type){i.add(t);for(const e of t.initial.target??[])a(e)}else if("parallel"===t.type)for(const e of Le(t))a(e)};return a(t),ys([{target:o.filter(t=>!o.some(e=>e!==t&&os(e,t))),source:t,reenter:!0,eventType:null,toJSON:null,_statesForDefaultEntry:[...i]}],e,s,n,!0,r)}function ys(t,s,n,r,o,i,a){const c=[],u=s.machine._microstepHooks?.drain(n.self);if(u?.length&&i.push(...u),!t.length)return[s,c];{const u=new Set(s.nodes);let d=s.historyValue;const h=s.context,f=1===t.length?t:cs(t,u,s,us(s,r,n,!1,a)),p=us(s,r,n,!0,a),l=f.some(t=>{const{targets:e,reenter:s}=p(t);return!!e?.length||!!s}),y=(t,e,o,i,a,c)=>{const u=[],d=[];let h;const f=Wt(n,u,d,!0),p=be(n)?Ee({context:e,event:r,output:Xs(r),children:o,actions:s.machine.sources.actions,actors:s.machine.sources.actors,guards:s.machine.sources.guards,delays:s.machine.sources.delays,input:i,stateNode:c},n):{context:e,event:r,output:Xs(r),parent:n.self._parent,self:n.self,children:o,system:n.system,actions:s.machine.sources.actions,actors:s.machine.sources.actors,guards:s.machine.sources.guards,delays:s.machine.sources.delays,input:i,stateNode:c};let l;try{l=t(p,f)}finally{Ut(f)}return ws(l,r,c.id,a),void 0!==l?.context&&(h=$t(e,l.context)),[u,h,d,l?.children]};let v=s;const m=(t,e)=>{const s=[],r=Wt(n,s,[]);for(const s of t.invoke){const t=e[s.id];t&&r.stop(t)}return s},g=()=>{const t=ps(f,u,s,p);let e;t.sort((t,e)=>e.order-t.order);const r=[...u];for(const s of t)for(const t of Object.values(s.states)){if("history"!==t.type)continue;const n="deep"===t.history?t=>De(t)&&os(t,s):t=>t.parent===s;e??={...d},e[t.id]=r.filter(n)}for(const e of t){const t=qe(s,e.id),[r,o,a,d]=e.exit?y(e.exit,v.context,v.children,t,"exit",e):[[],void 0,void 0,void 0];a?.length&&i.push(...a),(o||d)&&(v=Cs(v,{...o?{context:o}:{},...d?{children:d}:{}}));const[h,f]=Zt(v,0,n,r);v=h,c.push(...f);const p=m(e,v.children);if(p.length){const[t,e]=Zt(v,0,n,p);v=t,c.push(...e)}u.delete(e)}d=e||d};!o&&l&&g();let _=v.context;const w=[],b=[],x=[];for(const t of f){const e=p(t,!0);if(t.to){const s={...t,target:e.targets,definition:t};s.toJSON=()=>Be(s),x.push(s)}else x.push(t);void 0!==e.context&&(_=$t(_,e.context)),e.actions&&w.push(...e.actions),e.internalEvents&&b.push(...e.internalEvents)}b.length&&i.push(...b);const E=()=>{const t=t=>{const e=v.machine.root;let s;if(void 0!==t.output&&t.parent){const o=i.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);s=o&&t.parent===e?o.output:Hs(t.output,v.context,r,n.self,w[t.id])}else if("parallel"===t.type){const e=i.find(e=>"xstate.done.state"===e.type&&e.stateId===t.id);s=e?.output}return void 0===e.output?t.parent===e?s:void 0:Hs(e.output,v.context,q(t.id,s),n.self)},a=new Set,h=new Set,l=new Map,m=(t,e)=>{for(const s of t)if(e&&!os(s,e)||a.add(s),"parallel"===s.type)for(const t of Le(s))is(a,t)||(a.add(t),g(t))},g=t=>{if(Ze(t))if(d[t.id]){const e=d[t.id];for(const t of e)a.add(t),g(t);for(const s of e)m(Ce(s,t.parent),void 0)}else{const e=Ye(t),s=t.parent;h.add(s);const n=l.get(s)??[];n.push(e),l.set(s,n);const{targets:r}=p(e);for(const s of r??[])a.add(s),e===t.parent?.initial&&h.add(t.parent),g(s);for(const e of r??[])m(Ce(e,t.parent),void 0)}else{if("compound"===t.type){const e=p(t.initial).targets??[];for(const t of e)Ze(t)||a.add(t);h.add(t);for(const t of e)g(t);for(const s of e)m(Ce(s,t),void 0);return}if("parallel"===t.type)for(const e of Le(t))is(a,e)||(a.add(e),h.add(e),g(e))}},_=new Map;for(const t of f){const e=fs(t,s,p),{targets:n,reenter:r}=p(t),o=new Set;_.set(t,o);for(const s of n??[])Ze(s)||t.source===s&&t.source===e&&!r||(o.add(s),a.add(s),h.add(s)),g(s);const i=ds(t,s,p);for(const s of i){const n=Ce(s,e);"parallel"===e?.type&&n.push(e),m(n,!t.source.parent&&r?void 0:e)}r&&e===t.source&&a.add(t.source)}if(o)for(const t of f[0]._statesForDefaultEntry??[s.machine.root])h.add(t);const w={};let b=!1;const x=new Set([...u].map(t=>t.id));for(const[t,e]of Object.entries(s._stateInputs??{}))x.has(t)?w[t]=e:b=!0;for(const t of f){const{targets:e,input:s}=p(t,!0);if(s&&e)for(const n of e.filter(e=>_.get(t)?.has(e)))w[n.id]=s,b=!0}const E=new Set;for(const o of[...a].sort((t,e)=>t.order-e.order)){u.add(o);const a=[];let d=v.children,f=!1;for(const t of"final"===o.type?[]:o.invoke){f=!0;let i=t.logic;"function"==typeof i&&(i=i({actors:s.machine.sources.actors,context:v.context,event:r,self:n.self}));const c="string"==typeof i?s.machine.sources.actors[i]:i;if(!c)throw new Error(e(15,"string"==typeof i?i:"inline"));const u="function"==typeof t.input?t.input({self:n.self,context:v.context,event:r,input:w[o.id],output:Xs(r)}):t.input;Lt(n,t.id);const h=n.system.createActorRef(c,{...t,src:"string"==typeof i?i:void 0,input:u,parent:n.self,syncSnapshot:!!t.onSnapshot});h._invoked=!0,a.push({action:et["@xstate.spawn"],args:[h]}),t.id&&(d={...d,[t.id]:h})}f&&(v=Cs(v,{children:d}));let p=v.context,m=!1;const g=w[o.id];if(o.entry){const[t,e,s,n]=y(o.entry,p,d,g,"entry",o);a.push(...t),s?.length&&i.push(...s),e&&(p=e,m=!0),n&&(v=Cs(v,{children:n}))}if(m&&(v=Cs(v,{context:p})),h.has(o)){const t=[o.initial,...l.get(o)??[]].filter(Boolean);for(const e of t){const{actions:t,context:s,input:o,internalEvents:c}=vs(e,v,r,n);if(t&&a.push(...t),c?.length&&i.push(...c),void 0!==s&&(v=Cs(v,{context:$t(v.context,s)})),o&&e.target)for(const t of e.target)w[t.id]=o,b=!0}}const[_,x]=Zt(v,0,n,a);if(v=_,a.length=0,c.push(...x),"final"!==o.type)continue;const S=o.parent;let k="parallel"===S?.type?S:S?.parent,$=k||o;for("compound"===S?.type&&i.push(q(S.id,void 0!==o.output?Hs(o.output,v.context,r,n.self,g):void 0));"parallel"===k?.type&&!E.has(k)&&We(u,k);){E.add(k);const t={};for(const e of Le(k)){if("final"===e.type){t[e.key]=void 0!==e.output?Hs(e.output,v.context,r,n.self,w[e.id]):void 0;continue}if("parallel"===e.type){const s=i.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);t[e.key]=s?.output;continue}const s=Le(e).find(t=>"final"===t.type&&u.has(t));t[e.key]=void 0!==s?.output?Hs(s.output,v.context,r,n.self,w[s.id]):void 0}i.push(q(k.id,t)),$=k,k=k.parent}k||(v=Cs(v,{status:"done",output:t($)}))}b&&(v=Cs(v,{_stateInputs:w}))},[S,k]=Zt(v,0,n,w);v=S,c.push(...k),_&&_!==s.context&&(v=Cs(v,{context:_}));const $=v.machine._microstepHooks?.transitionContent?.(f,[...u]);if($){const t=f[0].source,[e,s,r,o]=y($,v.context,v.children,qe(v,t.id),"transition",t);r?.length&&i.push(...r),(s||o)&&(v=Cs(v,{...s?{context:s}:{},...o?{children:o}:{}}));const[a,u]=Zt(v,0,n,e);v=a,c.push(...u)}(o||l)&&E();const A=[...u];if("done"===v.status){const t=[];A.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=qe(v,e.id),[n,r,o,a]=y(e.exit,v.context,v.children,s,"exit",e);(r||a)&&(v=Cs(v,{...r?{context:r}:{},...a?{children:a}:{}})),t.push(...n),o?.length&&i.push(...o)}});const[e,s]=Zt(v,0,n,t);v=e,c.push(...s);const[o,a]=xs(v,r,n);v=o,c.push(...a);const[u,d]=Es(v,r,n);v=u,c.push(...d)}return d===s.historyValue&&s.nodes.length===u.size&&s.nodes.every(t=>u.has(t))?v.context!==h?[v===s?Cs(v):v,c,x]:[v,c,x]:[Cs(v,{_nodes:A,historyValue:d}),c,x]}}function vs(t,e,s,n,r){let o;const i=()=>o??=be(n)?Ee({context:e.context,event:s,output:Xs(s),value:e.value,children:e.children,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:qe(e,t.source.id)},n):{context:e.context,event:s,output:Xs(s),value:e.value,children:e.children,system:n.system,parent:n.self._parent,self:n.self,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:qe(e,t.source.id)};if(t.to){const o=[],a=[];let c;if(!r?.selectionResult?.reusable||!1!==r.resolveActions&&0!==r.selectionResult.operations.length){const e=Wt(n,o,a,!0,r?.resolveActions??!0),u=!1===r?.resolveActions?J(xe(n),"suppress"):void 0;try{if(r?.selectionResult?.reusable){c=r.selectionResult.result;for(const t of r.selectionResult.operations)t(e)}else c=t.to(i(),e),ws(c,s,t.source.id)}finally{u?.close(),Ut(e)}}else c=r.selectionResult.result;const u=c?.target?Qe(t.source,Bs(c.target)):void 0,d=c?.input??("function"==typeof t.input?t.input({context:e.context,event:s,output:Xs(s)}):t.input);return{targets:u,context:c?.context,reenter:c?.reenter,actions:o,internalEvents:a,input:d}}const a="function"==typeof t.input?t.input({context:e.context,event:s,output:Xs(s)}):t.input,c="function"==typeof t.context?t.context(i()):t.context;return{targets:t.target,context:c,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:a}}class ms extends Error{constructor(t,s,n,r){super(e(16,t,s.type,n)),this.actorId=void 0,this.event=void 0,this.maxIterations=void 0,this.states=void 0,this.name="InfiniteTransitionError",this.actorId=t,this.event=s,this.maxIterations=n,this.states=r.slice()}}function gs(t,e,s,n,r=[]){if("active"!==t.status&&!r.length)return{snapshot:t,microsteps:[[t,[],[]]]};let o=t;const i=r.slice();let a=!1;function c(t){if("xstate.done.actor"!==t.type&&"xstate.error.actor"!==t.type)return;const{actorId:e,sessionId:n}=t;if(!e)return;const r=o.children[e];if(!r)return;if(void 0!==r.sessionId&&r.sessionId!==n)return;const a={...o.children};if(delete a[e],s.system._unregister(r),o=Cs(o,{children:a}),i.length){const[,t,e]=i.at(-1);i[i.length-1]=[o,t,e]}else i.push([o,[],[]])}function u(){if(a&&o===t&&(o=Cs(t,{}),i.at(-1)?.[0]===t)){const[,t,e]=i.at(-1);i[i.length-1]=[o,t,e]}const e=function(t){const e=[],s=[];for(const n of t){if(!Yt(n)||n.type!==f)continue;const{actor:t,logic:r}=n,o=Bt(t);r===ut||r===ht?e.push(o):s.push(o)}return[...e,...s]}(i.flatMap(([,t])=>t)),n=("active"===t.status||r.length>0)&&("done"===o.status||"error"===o.status);if(e.length||n){const t=n?[...e,Gt(s,o)]:e;if(i.length){const[e,s,n]=i.at(-1);i[i.length-1]=[e,[...s,...t],n]}else i.push([o,t,[]])}return{snapshot:o,microsteps:i}}function d(t,n){if(n=t[2]??n,!ke(s)&&(e.type===h||(s.system._hasInspectionObservers?.()??1))){const t=s.self._collectedMicrosteps||[];t.push(...n),s.self._collectedMicrosteps=t}i.push([t[0],t[1],n])}if(e.type===p){const[t,n]=xs(o,e,s),[r,i]=Es(t,e,s);return o=Cs(r,{status:"stopped"}),d([o,[...n,...i]],[]),u()}let l=e;if(e.type===y){const t=H(e),r=t?o.timers.findIndex(e=>X(e,t)):-1;if(-1===r)return u();const i=o.timers[r],a=o.timers.filter((t,e)=>e!==r);if(o=Cs(o,{timers:a}),"@xstate.raise"===i.type)n.push(i.event),d([o,[]],[]);else{const t="self"===i.target?s.self:i.target;d([o,[Xt(s,t,i.event)]],[])}}if(l.type!==h&&l.type!==y){const e=l,r=function(t){return t.type.startsWith("xstate.error.")}(e),i=new Map,h=o.machine.getTransitionData(o,e,s,i);if(r&&!h.length)return"xstate.error.actor"!==e.type||Ue(e,o,e.actorId)?(o=Cs(t,{status:"error",error:e.error}),d([o,[]],[]),c(e),u()):u();a=h.length>0;const f=ys(h,t,s,l,!1,n,i);o=f[0],d(f,h),c(e)}if(!n.length&&!1===t.machine._hasEventlessTransitions)return u();let v=!0;const m=t.machine.options?.maxIterations??1/0;let g=0;const _=[];for(;"active"===o.status;){if(g++,g>m)throw new ms(s.self?.id,e,m,_);let t;_.push(o.value),_.length>5&&_.shift();let r=v?Ss(o,l,s):[];const i=r.length?o:void 0,a=o.machine._microstepHooks?.drain(s.self);if(a?.length&&n.push(...a),!r.length){if(!n.length)break;l=n.shift(),t=new Map,r=o.machine.getTransitionData(o,l,s,t)}const u=ys(r,o,s,l,!1,n,t);o=u[0],v=o!==i,d(u,r),c(l)}return u()}function _s(t,e,s,n,r){return!!t.to&&bs(t.to,e,s,n,r,n.machine.sources,t.source.id).enabled}function ws(t,s,n,r){if(t&&"function"==typeof t.then)throw Promise.resolve(t).catch(()=>{}),new Error(e(17,r??"transition",n,s.type))}function bs(t,e,s,n,r,o,i){let a;const c=function(t){const e=J(t),{frame:s}=e,n=[];let r=!1;const o=t=>{r||n.push(t)},i=()=>{if(!r)throw s.requiresReevaluation=!0,U},a=te({cancel:(...t)=>o(e=>e.cancel(...t)),emit:(...t)=>o(e=>e.emit(...t)),log:(...t)=>o(e=>e.log(...t)),raise:(t,e)=>{r||(zt(t),o(s=>s.raise(t,e)))},sendTo:(...t)=>o(e=>e.sendTo(...t)),stop:(...t)=>o(e=>e.stop(...t)),spawn:i,listen:i,subscribeTo:i},(...t)=>o(e=>e(...t)));return{frame:s,enqueue:a,operations:n,close(){r=!0,e.close()}}}(xe(r));try{a=t(Ee({context:e,event:s,output:Xs(s),value:n.value,children:n.children,actions:o.actions,actors:o.actors,guards:o.guards,delays:o.delays,input:qe(n,i)},r),c.enqueue)}catch(t){if(t===U)return{enabled:!0,result:void 0,reusable:!1};throw t}finally{c.close()}return ws(a,s,i),c.frame.requiresReevaluation?{enabled:!0,result:void 0,reusable:!1}:{enabled:void 0!==a||c.operations.length>0,result:a,reusable:!0,operations:c.operations}}function xs(t,e,s){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return[t,[]];const r=[],o=Wt(s,r,[]);for(const t of n)o.stop(t);return Zt(t,0,s,r)}function Es(t,e,s){if(!t.timers.length)return[t,[]];const n=[],r=Wt(s,n,[]);for(const e of t.timers)r.cancel(B(e));return Zt(t,0,s,n)}function Ss(t,e,s){t.machine._microstepHooks?.begin(s.self);const n=new Set,r=t.nodes.filter(De);for(const o of r)t:for(let r=o;r;r=r.parent)if(r.always)for(const o of r.always)if(ks(o,e,t,r,s)){n.add(o);break t}return cs(Array.from(n),new Set(t.nodes),t,us(t,e,s,!1))}function ks(t,e,s,n,r,o){if(t.matches&&!function(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}(e,t.matches))return!1;if(t._eventMatcher&&!t._eventMatcher(e,s))return!1;if(t.guard){const o=function(t,e){if(!be(e)){const s=e.self;return Object.assign(t,{self:s,parent:s._parent})}return Object.defineProperties(t,{self:{enumerable:!0,get:()=>e.self},parent:{enumerable:!0,get:()=>xe(e)}}),t}({context:s.context,event:e,output:Xs(e),children:s.children,actions:n.machine.sources.actions,actors:n.machine.sources.actors,guards:n.machine.sources.guards,delays:n.machine.sources.delays,_snapshot:s},r);if(!t.guard(o))return!1}if(t.to){const i=bs(t.to,s.context,e,s,r,n.machine.sources,t.source.id);return o?.set(t,i),i.enabled}return!0}const $s=Object.freeze({}),As=Object.freeze([]);function js(t){return t?.length?t:As}function Os(t){return t===$s||t&&Object.keys(t).length?t:$s}function Is(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const Ts=function(t){if("string"==typeof t&&Ve(t)){const e=this.machine.getStateNodeById(t);return this.nodes.includes(e)}return Ws(t,this.value)},Ms=function(t){return this.tags.has(t)},Rs=function(t){return this.machine?._canTransition(this,t)??!1},Ps=function(){const{nodes:t,_stateInputs:e,_nextTimerId:s,_nextActorIds:n,tags:r,machine:o,getMeta:i,getInputs:a,toJSON:c,can:u,hasTag:d,matches:h,...f}=this;return{...f,tags:Array.from(r)}},Ns=function(){const t={};for(const e of this.nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},qs=function(){return this._stateInputs};function Ds(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function Ls(t,e,s){const n={status:t.status,output:t.output,error:t.error,machine:e,context:t.context,nodes:t._nodes,value:t.value??ze(e.root,t._nodes),tags:Ds(t._nodes),children:Os(t.children),timers:js(t.timers),historyValue:Os(t.historyValue),_stateInputs:Os(t._stateInputs),_nextTimerId:t._nextTimerId??0,_nextActorIds:t._nextActorIds,matches:Ts,hasTag:Ms,can:Rs,getMeta:Ns,getInputs:qs,toJSON:Ps};return s&&_e(n,s),n}function Cs(t,e={}){const s={...t,...e};if((e._nodes??t.nodes)===t.nodes){const e={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:Os(s.children),timers:js(s.timers),historyValue:Os(s.historyValue),_stateInputs:Os(s._stateInputs),_nextTimerId:s._nextTimerId??0,_nextActorIds:s._nextActorIds,matches:Ts,hasTag:Ms,can:Rs,getMeta:Ns,getInputs:qs,toJSON:Ps};return ge(t,e),e}const n=Ls({...s,value:void 0},t.machine);return ge(t,n),n}function Ks(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 zs(t,s,n="context",r=[]){let o;r.push(t);for(const i in t){const a=t[i];if(a&&"object"==typeof a)if(tn(a))o??=Array.isArray(t)?t.slice():{...t},o[i]={"@actor":a.address};else{const c=Array.isArray(t)?`${n}[${i}]`:`${n}.${i}`;if(r.includes(a))throw new Error(e(44,s(),c));const u=zs(a,s,c,r);u!==a&&(o??=Array.isArray(t)?t.slice():{...t},o[i]=u)}}return r.pop(),o??t}function Ws(t,e){const s=Js(t),n=Js(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&Ws(s[t],n[t]))}function Vs(t,s){if(s.startsWith("xstate.")||s.startsWith("@xstate."))throw new Error(e(37,t,s))}function Us(t){if(Gs(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]?"\\.":t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function Js(t){if(Is(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}(Us(t))}function Fs(t){return Gs(t)?t:[t]}function Bs(t){return void 0===t?[]:Fs(t)}function Hs(t,e,s,n,r){if("function"==typeof t){return t({context:e,event:s,output:Xs(s),self:n,input:r})}return t}function Xs(t){if(function(t){return"xstate.done.actor"===t.type||"xstate.done.state"===t.type}(t)){return t.output}}function Gs(t){return Array.isArray(t)}function Qs(t,s,n){return Fs(t).map(t=>{if("string"==typeof t)throw new Error(e(38,s,n,t));return void 0===t?{target:void 0}:"function"==typeof t?{to:t}:t})}function Ys(t){if(void 0!==t&&""!==t)return Bs(t)}function Zs(t,e,s){const n="object"==typeof t,r=n?t:void 0;return{next:(n?t.next:t)?.bind(r),error:(n?t.error:e)?.bind(r),complete:(n?t.complete:s)?.bind(r),...n&&t.passive?{passive:!0}:{}}}function tn(t){return"sessionId"in t&&"send"in t&&"ref"in t}function en(t,s,n){const r=[];for(const t of s)for(const e of t.invoke)e.id===n&&r.push(e);if(1!==r.length)throw new Error(e(39,n));const o=r[0].logic;if("string"==typeof o){const s=t.sources.actors[o];if(!s)throw new Error(e(29,n,o));return s}if("function"==typeof o)throw new Error(e(40,n));return o}function sn(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],r=n[t];if("*"===e){return t===s.length-1}if(e!==r)return!1}return!0}let nn,rn=0;function on(){return nn??=function(){let t;try{t=globalThis.crypto}catch{}if(t?.getRandomValues)try{const e=new Uint32Array(4);return t.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(7,"0")).join("")}catch{}if(t?.randomUUID)try{return t.randomUUID().replaceAll("-","")}catch{}return`xstate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}(),`${nn}:${(rn++).toString(36)}`}function an(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length?e:"x"}function cn(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function un(t){const e=t.lastIndexOf(":");if(e<=0||e===t.length-1)return;const s=Number(t.slice(e+1));return Number.isSafeInteger(s)&&s>=0?{prefix:t.slice(0,e),index:s}:void 0}function dn(t,e){return`${t?t.address:""}|${e}`}function hn(t,e,s){const n=t._snapshot._nextActorIds;(n[e]??0)>=s||(t._snapshot._nextActorIds={...n,[e]:s},pe(t))}const fn=Object.freeze({});function pn(t,e){return Q(t,e)}function ln(t,e){return t.getSnapshot()?.timers?.find(t=>X(t,e))}class yn{get children(){const t=this._children??=new Map;return this._getRootActor()&&t.set(this._rootActor.sessionId,this._rootActor),t}set children(t){this._children=t}_getRootActor(){return this._rootActor._isRunning()?this._rootActor:void 0}_peekChildren(){return this._children}get keyedActors(){return this._keyedActors??=new Map}set keyedActors(t){this._keyedActors=t}get reverseKeyedActors(){return this._reverseKeyedActors??=new WeakMap}set reverseKeyedActors(t){this._reverseKeyedActors=t}_peekKeyedActors(){return this._keyedActors}constructor(t,e){this._rootActor=t,this._identity={executionId:on(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0,this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef,this._snapshot={_scheduledTimers:fn,_nextActorIds:{}}}_recordSent(t,e,s,n,r){if(!this._inspectionObservers?.size||!t)return;const o=t;if(!o._inTransition)return;(o._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:r})}schedule(t,e,s){const n=pn(t,e);void 0!==this._timerMap?.[n]&&this.cancel(t,e);const r=ln(t,e);if(r){const e="self"===r.target?t:r.target;this._recordSent(t,e,r.event,s,r.id)}const o=this._clock.now?.()??Date.now(),i={source:t,delay:s,key:e,scheduledAt:o,dueAt:o+s};this._snapshot._scheduledTimers===fn&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[n]=i,pe(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[n],delete this._snapshot._scheduledTimers[n],pe(this),this._deliver(t,t,{type:y,...e})},s);(this._timerMap??={})[n]=a}cancel(t,e){const s=pn(t,e),n=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==fn&&delete this._snapshot._scheduledTimers[s],pe(this),void 0!==n&&this._clock.clearTimeout(n)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.key)}}_deliver(t,e,s){O(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),pe(this),t}_getByAddress(t){const e=this._getRootActor();if(e?.address===t)return e;for(const e of this._children?.values()??[])if(e.address===t&&e._isRunning())return e}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1);const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&pe(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,s){const n=this._keyedActors?.get(t);if(n&&n!==s)throw new Error(e(45,String(t)));(this._keyedActors??=new Map).set(t,s),(this._reverseKeyedActors??=new WeakMap).set(s,t),n!==s&&pe(this)}inspect(t){const e=Zs(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}onRejectedEvent(t){const e=e=>t(e);return(this._rejectionListeners??=new Set).add(e),{unsubscribe:()=>{this._rejectionListeners?.delete(e)}}}onEmitted(t){const e=e=>t(e);return(this._emissionListeners??=new Set).add(e),{unsubscribe:()=>{this._emissionListeners?.delete(e)}}}_notifyEmitted(t,e){const s=this._emissionListeners;if(!s?.size)return;const n={actorRef:t,event:e};for(const t of Array.from(s))try{t(n)}catch(t){z(t)}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>{try{t.next?.(e)}catch(t){z(t)}})}spawnActor(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);M(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);T(t,e)}sendEvent(t,e,s){if(b(e)){const n=S(this,e);if(n)e=n;else if(this._getByAddress(e["@actor"])||!this.runtime?.sendEvent)return this.deadLetter(t,void 0,s,"missingTarget",{targetId:x(e["@actor"]),error:E(e)})}if(I(t,e,s))return;this._recordSent(t,e,s);const n=this.runtime?.sendEvent;if(n)return n(t,e,s);this._deliver(t,e,s)}emitEvent(t,e){const s=this.runtime?.emitEvent;if(s)return s(t,e);t._emit(e)}deadLetter(t,e,s,n,r){const o=this._rejectionListeners;if(o?.size){const i={event:s,targetRef:e,targetId:e?.id??r?.targetId,sourceRef:t,eventOrigin:t?"actor":"external",reason:n,issues:r?.issues,error:r?.error};for(const t of[...o])try{t(i)}catch(t){z(t)}}const i=this.runtime?.deadLetter;if(i)return i(t,e,s,n,r)}runStep(t,e,s){const n=this.runtime?.runStep;return n?n(t,e,s):j(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const n=this.runtime?.scheduleTimer;if(n){const r=ln(t,e);if(r){const e="self"===r.target?t:r.target;this._recordSent(t,e,r.event,s,r.id)}return n(t,e,s)}this.schedule(t,e,s)}cancelTimer(t,e){const s=this.runtime?.cancelTimer;if(s)return s(t,e);this.cancel(t,e)}cancelAllTimers(t){const e=this.runtime?.cancelAllTimers;if(e)return e(t);this.cancelAll(t)}_relay(t,e,s){if(!function(t){let e=!1,s=!1;for(const n of V)n.parent===t&&(n.requiresReevaluation=!0,e=!0,s||="abort"===n.mode);if(s)throw U;return e}(e))return this.sendEvent(t,e,s)}getSnapshot(){return{_scheduledTimers:{...this._snapshot._scheduledTimers}}}start(){const t=this._snapshot._scheduledTimers;let e=!0;for(const s in t){e&&(this._snapshot._scheduledTimers={},e=!1);const{source:n,dueAt:r,key:o}=t[s];this.scheduleTimer(n,o,Math.max(0,r-(this._clock.now?.()??Date.now())))}}}let vn=!1;const mn=Object.freeze([]),gn={"xstate.done.actor":!0,"xstate.error.actor":!0,"xstate.error.execution":!0,"xstate.snapshot.actor":!0,"xstate.done.state":!0,"xstate.after":!0,"xstate.timeout.state":!0,"xstate.timeout.actor":!0,[y]:!0};let _n=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const wn=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function bn(t,e){try{t?.(e)}catch(t){z(t)}}function xn(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function En(t,e){return new Sn(t,e)}class Sn{get address(){return this._address??=this._parent?`${this._parent.address}/${cn(this.id)}`:cn(this.id)}get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this._errorObserved=!1,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=_n.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,this._inTransition=!1,this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this._address=void 0,this.system=void 0,this._trigger=void 0,this._boundSend=void 0,this.src=void 0,this._deferred=void 0,this._restored=!1,this._warnedUnhandledTypes=void 0;const s=e?{...wn,...e}:wn,{clock:n,logger:r,parent:o,syncSnapshot:i,id:a,registryKey:c,inspect:u}=s;var d;this.system=o?o.system:s._systemRef?.current??function(t,e){return new yn(t,e)}(this,{clock:n,logger:r,createActorRef:En}),o||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system,s._systemRef.initialize?.()),u&&!o&&this.system.inspect(Zs(u)),s.onRejectedEvent&&!o&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(d=this.system)._identity.executionId}:${d._identity.nextSessionId++}`,this.id=function(t,e,s){if(void 0!==e){const n=un(e);return n?hn(t,dn(s?.parent,n.prefix),n.index+1):s?.parent||hn(t,dn(void 0,e),1),e}const n=an(s?.src),r=dn(s?.parent,n),o=t._snapshot._nextActorIds[r]??0;return hn(t,r,o+1),s?.parent||"x"===n||0!==o?`${n}:${o}`:n}(this.system,a,{parent:o,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=o,this._syncSnapshot=i,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope=this,c&&(this.registryKey=c,this.system._set(c,this)),this._collectedMicrosteps=void 0;const h=s._restore;this._restored=void 0!==h;try{if(h)this._setSnapshot(h.restore(this._actorScope));else if(e?._inert);else{this._inTransition=!0;try{const[t,e]=Qt(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}finally{this._inTransition=!1}}}catch(t){this._setSnapshot(h?.error?.(t)??{status:"error",output:void 0,error:t}),this._deferred&&(this._deferred.length=0)}c&&"active"!==this._snapshot.status&&this.system._unregister(this),(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_getLogger(){return this.logger}get self(){return this}get defer(){const t=t=>this._defer(t);return Object.defineProperty(this,"defer",{value:t}),t}get stopChild(){const t=t=>this._stopChild(t);return Object.defineProperty(this,"stopChild",{value:t}),t}get emit(){const t=t=>$(this,t,this.system);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===_n.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(e(47,t.id,this.id));t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=vn;try{vn=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==_n.Stopped&&this._recoverOrError(t)})}finally{vn=e}};this._processingStatus!==_n.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,_e(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e,s){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t,s),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;const n=this._inTransition;this._inTransition=!0;try{const[t,n]=Qt(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),xn(n,this._actorScope),this.update(t,s),!0}catch{return!1}finally{this._inTransition=n}}_next(t){for(const e of this.observers??mn)bn(e.next,t)}update(t,e){this._setSnapshot(t);const s=this._deferred;for(let e=0;e<(s?.length??0);e++){const n=s[e];try{n()}catch(e){if(s.length=0,this._tryHandleExecutionError(e,t))return;this._setErrorSnapshot(e,t),this._error(e);break}}if(s&&(s.length=0),"active"===this._snapshot.status)this._next(t);this._inspectTransition(this._snapshot,e)}_inspectTransition(t,e){(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps??mn,actions:this._collectedActions??mn,sent:this._collectedSent??mn,eventType:e.type}),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0}_flushInitialEffects(){if(!this._initialEffects?.length)return!0;this._forceDeferredActions=!0;try{return xn(this._initialEffects,this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred&&(this._deferred.length=0),this._recoverOrError(t),"active"===this._snapshot.status}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const n=Zs(t,e,s);if(this._processingStatus!==_n.Stopped)(this.observers??=new Set).add(n);else switch(this._snapshot.status){case"done":bn(n.complete);break;case"error":{const t=this._snapshot.error;n.error?(n.passive||(this._errorObserved=!0),bn(n.error,t)):z(t);break}}return{unsubscribe:()=>{this.observers?.delete(n)}}}on(t,e){let s=this.eventListeners?.get(t);return s||(s=new Set,(this.eventListeners??=new Map).set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,r)=>{const o=Zs(s,n,r);let i=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(i,n)||(i=n,o.next?.(n))},error:o.error,complete:o.complete})},get:()=>t(this.getSnapshot())}}start(){const t=this._inTransition;this._inTransition=!0;try{return this._start()}finally{this._inTransition=t}}_start(){if(this._processingStatus===_n.Running)return this;if(this._processingStatus===_n.Stopped){const t=this._snapshot.status;if("done"===t||"error"===t)return this;throw new Error(e(48,this.id))}this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=_n.Running,this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this._restored?(this._next(this._snapshot),this._stopProcedure(),this._complete(),this):this._flushInitialEffects()?(this.update(this._snapshot,K(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this;case"stopped":return this._stopProcedure(),this._complete(),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,K(this.options.input)):(function(t,e,s){const n=ue.get(t),r=le(s);return n?.actor===e&&n.systemState.sourceSystem===s&&n.systemState.sourceVersion+1===r&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(n.systemState.root=e,n.systemState.sourceVersion=r,!0)}(this._snapshot,this,this.system)||this._setSnapshot(this._snapshot),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0),this._restored){const t=this._snapshot.timers??[],e=!this.system._clock.now,s=Date.now();for(const n of t){const t=e&&void 0!==n.scheduledAt?Math.min(n.delay,Math.max(0,n.scheduledAt+n.delay-s)):n.delay;this.system.scheduleTimer(this,B(n),t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){const e=this._inTransition;this._inTransition=!0;try{this._processEvent(t)}finally{this._inTransition=e}}_processEvent({event:t,sourceRef:e}){this._lastSourceRef=e;const s=this._snapshot;let n,r;try{n=Qt(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){r={err:t}}if(r)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(r.err)||this._inspectTransition(this._snapshot,t));if(!n)return;let o=this._snapshot;try{const[r,i]=n;r!==s||i.length||!("machine"in s)||t.type===p||e&&Object.hasOwn(gn,t.type)||this._reportUnhandledEvent(t),o=r,this._setSnapshot(o),xn(i,this._actorScope),this.update(o,t)}catch(e){return void(this._recoverOrError(e,o,s)||this._inspectTransition(this._snapshot,t))}t.type===p&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){bn(()=>this.options.onUnhandledEvent?.(t,this._snapshot))}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)bn(s,t)}_terminate(t){if("done"===t.status)return this._next(this._snapshot),this._stopProcedure(),this._complete(),void(this._parent&&this.system._relay(this,this._parent,D(this.id,t.output,this.sessionId)));"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===_n.Stopped?this:(this.mailbox?.clear(),this._processingStatus===_n.NotStarted?(this._processingStatus=_n.Stopped,this.system._unregister(this),this):(this._send({type:p}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error(e(49,this.id));return this._stop()}_complete(){for(const t of this.observers??mn)bn(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||z(t)})}_error(t,e){this._stopProcedure();const s=new Set;for(const t of[this._snapshot,e]){const e=t?.children;for(const t of Object.values(e??{}))t?._parent===this&&"function"==typeof t.getSnapshot&&s.add(t)}for(const t of this.system._peekChildren?.()?.values()??[])t._parent===this&&s.add(t);for(const t of s)try{if("active"!==t.getSnapshot().status)continue;const e=this.system.stopActor(t);e&&Promise.resolve(e).catch(z)}catch(t){z(t)}if(this.observers?.size){let e=!1,s=!1;for(const n of this.observers){const r=n.error;n.passive||(e||=!r,s||=!!r),bn(r,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,L(this.id,t,this.sessionId))}_stopProcedure(){this._processingStatus===_n.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=_n.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===_n.Stopped)return void this.system.deadLetter(e,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new R(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue({event:t,sourceRef:e})}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{"@actor":this.address}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[W](){return this}getSnapshot(){return this._snapshot}}function kn(t,...[s]){return function(t){if(t&&"object"==typeof t)for(const s of Object.keys(t))if(!d.has(s))throw new Error(e(8,s))}(s),new Sn(t,s)}function $n(t,e){const s=t.check(e);if(s)throw s}const An=new WeakMap;function jn(t,e,s){const n=function(t){let e=An.get(t);return e||(e=new Map,An.set(t,e)),e}(t);if(void 0!==e&&n.has(e))return;const r=s();n.set(e??Symbol(),{cleanup:"function"==typeof r?r:void 0})}function On(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===p)return[{...e,status:"stopped",input:void 0},[mt("@xstate.cleanup",()=>function(t){const e=An.get(t);if(!e)return;let s;An.delete(t);for(const{cleanup:t}of e.values())try{t?.()}catch(t){s??={error:t}}if(s)throw s.error}(n.self))]];if(s.type===g)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if(s.type===v)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if(s.type===m)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const r=[],o=Object.create(null),i={emit:t=>{r.push(function(t,e){return{kind:"emit",exec:pt,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&r.push(Xt(n,e,t))},raise:t=>{r.push(Xt(n,n.self,t))},effect:(t,i)=>{if("string"==typeof t)return void((t,i)=>{const a=e.effects&&Object.prototype.hasOwnProperty.call(e.effects,t)?e.effects[t]:void 0;(!a||s.type===h&&"active"===a.status)&&(r.push(mt("@xstate.effect",(e=n.self.system)=>jn(n.self,t,()=>i(e)),{key:t})),o[t]={status:"active"})})(t,i);const a=t;r.push(mt("@xstate.effect",(t=n.self.system)=>jn(n.self,void 0,()=>a(t))))}},a=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},i),c={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(c.context=a?.context??e.context),(a?.effects||Object.keys(o).length)&&(c.effects={...e.effects,...a?.effects,...o}),Qt(n,e,[c,r])},s=(s,r,o)=>{if(t.validator){const e=o.self._lastSourceRef,i=e?"actor":"external",a=t.validator.check({kind:"event",logic:n,event:r,eventOrigin:i});if(a)return[s,[yt(o,e,r,"invalidEvent",{issues:a.issues,error:a})]]}const i=e(s,r,o);return t.validator&&$n(t.validator,{kind:"result",logic:n,snapshot:i[0],effects:i[1]}),i},n={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,n)=>{if(!n?.restored)return;const[r,o]=s(t,K(t.input),e);Object.assign(t,r);for(const t of o)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&$n(t.validator,{kind:"input",logic:n,input:e});const o=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),i={status:"active",output:void 0,error:void 0,input:e};return void 0!==o&&(i.context=o),s({...i},K(e),r)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const In=new WeakMap;const Tn="xstate.observable.next",Mn="xstate.observable.error",Rn="xstate.observable.complete";const Pn="xstate.async.resolve",Nn="xstate.async.reject";class qn extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}function Dn(t){const e=t,s=On({id:e.id,validator:e.validator,schemas:e.schemas,context:void 0,run:({event:t,input:s,self:n,system:r},o)=>{switch(t.type){case Pn:{const e="data"in t?t.data:t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case Nn:{const e="data"in t?t.data:t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===h)return o.effect((t=r)=>{const o=n,i=e=>{t.sendEvent(o,o,e)},a=new AbortController,c=e.timeout,u=re(c),d=void 0===u?void 0:r._clock.setTimeout(()=>{"active"===n.getSnapshot().status&&(a.abort(),i({type:Nn,data:new qn(c)}))},u),h=()=>{void 0!==d&&r._clock.clearTimeout(d)},f=()=>{try{return Promise.resolve(e.run({input:s,system:r,self:n,signal:a.signal},{emit:e=>{$(o,e,t)},step:(e,s)=>t.runStep?Promise.resolve(t.runStep(o,e,s)):j(o,e,s,i)}))}catch(t){return Promise.reject(t)}};return(t.runLogic?Promise.resolve(t.runLogic(o,f)):f()).then(t=>{h(),"active"===n.getSnapshot().status&&i({type:Pn,data:t})},t=>{h(),"active"===n.getSnapshot().status&&i({type:Nn,data:t})}),()=>{a.abort(),h()}}),{effects:{async:{status:"active"}}}}});return Object.defineProperty(s,rt,{value:{kind:"async",timeout:e.timeout}}),s}const Ln=On({context:void 0,run:()=>{}});const Cn=new WeakMap;const Kn={};class zn{constructor(t,s){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.schemas=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._candidateCache=void 0,this.parent=s._parent,this.key=s._key,this.machine=s._machine,this.parent&&function(t){for(let e=0;e<t.length;e++)if("\\"===t[e])e++;else if("."===t[e])return!0;return!1}(this.key))throw new Error(e(57,this.key));this.path=this.parent?this.parent.path.concat(this.key):[];const n=this.config.states?Object.keys(this.config.states)[0]:void 0;this.id=this.config.id||(this.machine.id?[this.machine.id,...this.path]:this.path).join("."),this.type=this.config.type||(void 0!==n?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.schemas=this.config.schemas,function(t){const s=t.config;if("history"===t.type&&!("string"==typeof s.target&&s.target.trim().length>0||Array.isArray(s.target)&&s.target.length>0&&s.target.every(t=>"string"==typeof t&&t.trim().length>0)))throw new Error(e(60,t.id));if("choice"!==t.type)return;if("function"!=typeof s.choice)throw new Error(e(61,t.id))}(this);if(this.machine.idMap.get(this.id))throw new Error(e(58,this.id));if(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 r=0;r<n.length;r++){const o=n[r],i=e(t[o],o,t,r);"__proto__"===o?Object.defineProperty(s,o,{value:i,enumerable:!0,configurable:!0,writable:!0}):s[o]=i}return s}(this.config.states,(t,e)=>new zn(t,{_parent:this,_key:e,_machine:this.machine})):Kn,"compound"===this.type&&!this.config.initial)throw new Error(e(59,this.id));this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=Bs(t.tags).slice(),this.invoke=Bs(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,r=`${this.id}:${e}`;const o=t.id??r;return{...t,src:"string"==typeof s?s:void 0,logic:s,id:o,registryKey:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,r=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===r.length)return[];const o=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;o.push({event:P(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0,name:`after.${s}`})}var i;void 0!==s&&n&&o.push({event:(i=t.id,{type:"xstate.timeout.state",stateId:i}),delay:s,transitions:n,fromDelaysMap:!0,name:"onTimeout"});for(const t of r)o.push({event:N(t.id),resolveEvent:({children:e})=>N(t.id,e[t.id]?.sessionId),eventMatcher:(e,s)=>Ue(e,s,t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1,name:"invoke.onTimeout"});const a=[];for(const{event:e,resolveEvent:s,eventMatcher:n,delay:r,transitions:i,fromDelaysMap:c,name:u}of o){Je(t,e,s??(()=>e),e=>Ne(r,c?e.delays:{},{context:e.context,event:e.event,stateNode:t,input:e.input}));const{type:o,...d}=e;for(const e of Qs(i,u,t.id))a.push({...e,matches:{...e.matches,...Object.fromEntries(Object.entries(d).filter(([,t])=>void 0!==t))},event:o,delay:r,_eventMatcher:n})}return a.map(e=>({...Fe(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const s=new Map,n=(t,e)=>{s.set(t,[...s.get(t)??[],...e])};if(t.config.on)for(const n of Object.keys(t.config.on)){if(""===n)throw new Error(e(63,t.id));const r=t.config.on[n];s.set(n,Wn(t,n,r,e=>Fe(t,n,e)))}if(t.config.onDone){const e="xstate.done.state";n(e,Wn(t,"onDone",t.config.onDone,s=>Fe(t,e,{...s,matches:{...s.matches,stateId:t.id}})))}if(t.config.onError){const e="xstate.error.*";s.set(e,Wn(t,"onError",t.config.onError,s=>Fe(t,e,s)))}const r=(e,s,n)=>Fe(t,e,{matches:{actorId:n},_eventMatcher:(t,e)=>Ue(t,e,n),to:(t,e)=>(e.cancel(s),{})}),o=(e,s,n)=>{const{target:r,to:o,reenter:i,...a}=s;return Fe(t,e,{...a,reenter:i,to:(t,e)=>{if(o){let s=!1;const r=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const r=Reflect.get(t,e,n);return"function"!=typeof r?r:(...e)=>(s=!0,r.apply(t,e))}}),i=o(t,r);return(void 0!==i||s)&&e.cancel(n),i}return e.cancel(n),{target:r,reenter:i}}})};for(const e of t.invoke){const s=t=>({...t,matches:{...t.matches,actorId:e.id},_eventMatcher:(t,s)=>Ue(t,s,e.id)}),i=void 0!==e.timeout?{event:{type:"xstate.timeout.actor",actorId:e.id}}:void 0;if(e.onDone){const a="xstate.done.actor",c=Wn(t,"invoke.onDone",e.onDone,e=>{const n=s(e);return i?o(a,n,i):Fe(t,a,n)});i&&c.push(r(a,i,e.id)),n(a,c)}else if(i){const t="xstate.done.actor";n(t,[r(t,i,e.id)])}if(e.onError){const r="xstate.error.actor";n(r,Wn(t,"invoke.onError",e.onError,e=>{const n=s(e);return i?o(r,n,i):Fe(t,r,n)}))}if(e.onSnapshot){const r="xstate.snapshot.actor";n(r,Wn(t,"invoke.onSnapshot",e.onSnapshot,e=>Fe(t,r,s(e))))}}for(const e of t.after){let t=s.get(e.eventType);t||(t=[],s.set(e.eventType,t)),t.push(e)}return s}(this),"choice"===this.type?this.always=function(t){const s=t.config.choice,n=s=>{if(!s||void 0===s.target)throw new Error(e(62,t.id));return s};return[Fe(t,"",{to:t=>n(s(t))})]}(this):this.config.always&&(this.always=Wn(this,"always",this.config.always,t=>Fe(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 function(t,e,s){let n=Cn.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Cn.set(t,n)),n[e]}(this,"initial",()=>function(t,s){const n="object"==typeof s&&null!==s?s.target:s,r="object"==typeof s&&null!==s?s.input:void 0,o="object"==typeof s&&null!==s?s.to:void 0,i="object"==typeof s&&null!==s?s.meta:void 0,a="object"==typeof s&&null!==s?s.description:void 0,c=Array.isArray(n)?n:n?[n]:[],u=c.map(e=>e.startsWith("#")?t.machine.getStateNodeById(e.slice(1)):t.states[e]);if(u.some(t=>!t))throw new Error(e(64,c.find((t,e)=>!u[e]),t.id));const d={source:t,target:u.length?u:void 0,input:r,to:o,meta:i,description:a};return d}(this,this.config.initial))}next(t,e,s,n){if("final"===this.type)return;let r=this._candidateCache?.get(e.type);r||(r=function(t,e){const s=t.transitions.get(e.type)??[],n=[...t.transitions.keys()].filter(t=>t!==e.type&&sn(e.type,t)).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return s.length?[...s,...n]:n}(this,e),(this._candidateCache??=new Map).set(e.type,r));for(const o of r){if(ks(o,e,t,this,s,n))return[o]}}}function Wn(t,e,s,n){const r=Qs(s,e,t.id),o=new Array(r.length);for(let t=0;t<r.length;t++)o[t]=n(r[t]);return o}class Vn extends Error{constructor(t){super(t),this.name="InvalidSnapshotError"}}function Un(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function Jn(t){return Un(t)&&"function"==typeof t.transition&&"function"==typeof t.getInitialSnapshot}function Fn(t,s,n,r){if("string"==typeof s){if(!n.states[s])throw new Vn(e(21,r.concat(s).join(".")));return}const o=t=>new Vn(e(22===t?22:23,r.join(".")));if(!s||"object"!=typeof s||Array.isArray(s))throw o(22);const i=Object.keys(s);if(i.length>1&&"parallel"!==n.type)throw o(23);for(const o of i){const i=n.states[o];if(!i)throw new Vn(e(21,r.concat(o).join(".")));Fn(t,s[o],i,r.concat(o))}}function Bn(t,s){if(!Un(s))throw new Vn(e(24,t.id));if(void 0===s.value)throw new Vn(e(25,t.id));Fn(t,s.value,t.root,[]);const n=Array.from(Ke(ns(t.root,s.value)));if(!Un(s.children))throw new Vn(e(26));const r=new Map;for(const[o,i]of Object.entries(s.children)){if(!Un(i)||void 0!==i.remote&&"boolean"!=typeof i.remote||void 0!==i.address&&"string"!=typeof i.address||void 0!==i.syncSnapshot&&"boolean"!=typeof i.syncSnapshot||void 0!==i.registryKey&&"string"!=typeof i.registryKey||void 0!==i.incarnation&&"string"!=typeof i.incarnation||void 0!==i.snapshot&&!Un(i.snapshot))throw new Vn(e(27,o));if(!0!==i.remote){if(void 0!==i.src&&"string"!=typeof i.src&&!Jn(i.src))throw new Vn(e(27,o));try{const s=void 0===i.src?en(t,n,o):"string"==typeof i.src?Object.hasOwn(t.sources.actors,i.src)?t.sources.actors[i.src]:void 0:i.src;if(!s)throw new Vn(e(29,o,"string"==typeof i.src?i.src:"<inline>"));r.set(o,s)}catch(t){if(t instanceof Vn)throw t;throw new Vn(t instanceof Error?t.message:e(30,o))}}else if("string"!=typeof i.address||"string"!=typeof i.src)throw new Vn(e(28,o))}if(void 0!==s.timers&&!Array.isArray(s.timers))throw new Vn(e(31));for(const t of s.timers??[]){if(!Un(t)||"number"!=typeof t.delay||"@xstate.raise"!==t.type&&"@xstate.sendTo"!==t.type||!Un(t.event)||"string"!=typeof t.event.type||void 0!==t.id&&"string"!=typeof t.id||void 0!==t.seq&&"number"!=typeof t.seq||void 0!==t.scheduledAt&&"number"!=typeof t.scheduledAt||!("string"==typeof t.target||Un(t.target)&&"parent"===t.target.type||b(t.target)))throw new Vn(e(32));if("string"==typeof t.target&&"self"!==t.target&&!Object.hasOwn(s.children,t.target))throw new Vn(e(33,t.target))}return{nodes:n,childLogics:r}}let Hn,Xn;function Gn(){if(Xn)return Xn;const t=Hn??=kn({transition:t=>[t,[]],initialTransition:()=>[{status:"active",output:void 0,error:void 0},[]],getInitialSnapshot:()=>({status:"active",output:void 0,error:void 0}),getPersistedSnapshot:t=>t});return Xn={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},Kt.add(Xn),Xn}class Qn{constructor(t,s,n){if(this.config=t,this.validator=n,this._internalEventType=void 0,this._transitionMetaType=void 0,this._inputType=void 0,this._actionMap=void 0,this._actorMap=void 0,this._stateSchema=void 0,this.version=void 0,this.schemas=void 0,this.sources=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this._raw=()=>this,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._hasEventlessTransitions=void 0,this._microstepHooks=void 0,this._json=void 0,void 0!==t.version&&!t.id)throw new Error(e(18,t.version));this.id=t.id??"",this.sources={actors:t.actors??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...s},this.version=this.config.version,this.schemas=this.config.schemas,this.internalEventDescriptors=Object.keys(this.schemas?.internalEvents??{}),this.options={...this.config.options},this.transition=this.transition.bind(this),this.initialTransition=this.initialTransition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.start=this.start.bind(this),this.root=new zn(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 r=n.config.id,o=n.config.route,i=({event:t})=>t.to===`#${r}`;if("function"==typeof o)return e.push(Fe(t,"xstate.route",{guard:i,to:t=>{const e=o(t);if(e)return{...!0===e?{}:e,target:`#${r}`}}})),void(n.states&&s(n.states));const{guard:a,...c}=o,u={...c,guard:i,target:`#${r}`};e.push(Fe(t,"xstate.route",u))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.root._refreshEventMetadata(),this._hasEventlessTransitions=Array.from(this.idMap.values()).some(t=>!!t.always?.length),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:r}=this.sources,o=new Qn(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...r,...t.delays}},this.validator);return o._json=this._json,o.internalEventDescriptors=this.internalEventDescriptors,o._microstepHooks=this._microstepHooks,o}resolveState(t){const e=(s=this.root,n=t.value,ze(s,Ke(ns(s,n))));var s,n;const r=Ke(ns(this.root,e));return Ls({_nodes:[...r],value:e,context:t.context||{},children:{},status:We(r,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const n=!s,r=s??Pe(this,t);if(n&&Se(r,t,!1),this.validator){const n=s&&s.self._lastSourceRef,o=n?"actor":"external",i=this.validator.check({kind:"event",logic:this,event:e,eventOrigin:o});if(i)return[t,[yt(r,n,e,"invalidEvent",{issues:i.issues,error:i})]]}Rt(r);const o=this._transitionFast(t,e,r);if(o){n&&Se(r,o,!1);const e=n&&o!==t?$e(r,o):this._attachPureActorRef(o,r);return this.validator&&$n(this.validator,{kind:"result",logic:this,snapshot:e,effects:[]}),[e,[]]}const{snapshot:i,microsteps:a}=gs(t,e,r,[]);n&&Se(r,i,!1);const c=n?i===t?i:$e(r,i):this._attachPureActorRef(i,r),u=this._collectEffects(a);return this.validator&&$n(this.validator,{kind:"result",logic:this,snapshot:c,effects:u}),[c,u]}_collectEffects(t){return t.flatMap(([,t])=>t)}_attachPureActorRef(t,e,s=!1){return ke(e)||s&&e.self._actorScope===e&&void 0===e.self._snapshot||_e(t,e.self,e.system),t}_transitionFast(t,e,s){if("active"!==t.status||"string"!=typeof t.value||this.root.always?.length)return;const n=this.root.states[t.value];if(!n||"atomic"!==n.type||n.exit||n.invoke.length||n.always?.length||n.after?.length)return;const r=n.transitions.get(e.type);if(1!==r?.length)return;const o=r[0];if(o.guard||o.actions||o.to||o.reenter||o.input||"function"==typeof o.context||o.target&&1!==o.target.length)return;const i=o.target?.[0]??n,a=i!==n;if(i.parent!==this.root||"atomic"!==i.type||a&&(i.entry||i.invoke.length||i.always?.length||i.after?.length))return;const c=void 0!==o.context?{...t.context,...o.context}:t.context;if(!ke(s)&&(s.system._hasInspectionObservers?.()??1)){const t=s.self._collectedMicrosteps||[];t.push(o),s.self._collectedMicrosteps=t}const u=t._stateInputs[this.root.id];return Cs(t,{...c!==t.context?{context:c}:{},...a?{_nodes:[this.root,i],_stateInputs:u?{[this.root.id]:u}:{}}:{}})}microstep(t,e,s){const{microsteps:n}=gs(t,e,s,[]),r=new Array(n.length);for(let t=0;t<n.length;t++)r[t]=n[t][0];return r}getTransitionData(t,e,s,n){return this._microstepHooks?.begin(s.self),rs(this.root,t.value,t,e,s,n)||[]}isInternalEventType(t){if(t===y)return!0;for(const e of this.internalEventDescriptors)if(sn(t,e))return!0;return!1}_canTransition(t,e){if("active"!==t.status)return!1;const s=Gn(),n=this.getTransitionData(t,e,s);if(!n?.length)return!1;for(const r of n){if(void 0!==r.target)return!0;const n=vs(r,t,e,s,{resolveActions:!1});if(n.targets?.length||n.context||_s(r,t.context,e,t,s))return!0}return!1}getExecutionErrorEvent(t,e){if("active"===t?.status&&t.nodes?.some(t=>t.config.onError))return C("execution",e)}_getPreInitialState(t,e){const{context:s}=this.config,n=Ls({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const r={},o=function(t,e,s){return(n,r)=>{const o=nt(e,n),i=r?.id??Dt(t,o??n).id;void 0!==r?.id&&(Lt(t,r.id),Ct(t,r.id));const a=t.system.createActorRef(n,{id:i,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:o??n,registryKey:r?.registryKey});return s[a.id]=a,a}}(t,this.sources.actors,r),i=s(function(t,e){return be(e)?(Object.defineProperty(t,"self",{enumerable:!0,get:()=>e.self}),t):Object.assign(t,{self:e.self})}({spawn:o,input:e.input,actors:this.sources.actors},t)),[a]=Zt(n,0,t,[]);if(i&&(a.context=i),Object.keys(r).length>0){a.children={...a.children,...r};const e=function(t){const e=Tt.get(t)?.counters;if(e?.size)return Object.fromEntries(e)}(t);e&&(a._nextActorIds=jt(a._nextActorIds,e))}return a}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){this.validator&&$n(this.validator,{kind:"input",logic:this,input:t});const s=!e,n=e??Pe(this);Rt(n);const r=K(t),o=[],i=(t,e)=>{s&&Se(n,t,!1);const r=s?$e(n,t):this._attachPureActorRef(t,n,!0),o=this._collectEffects(e);return this.validator&&"error"!==t.status&&$n(this.validator,{kind:"result",logic:this,snapshot:r,effects:o}),[r,o]};let a;try{a=this._getPreInitialState(n,r)}catch(t){return i(Cs(Ls({context:"function"!=typeof this.config.context&&this.config.context?this.config.context:{},_nodes:[this.root],children:{},status:"active"},this),{status:"error",error:t}),[])}const c=Object.values(a.children).filter(Boolean).map(t=>Ht(t));try{const[t,e]=ls(this.root,a,n,r,o),{snapshot:s,microsteps:u}=gs(t,r,n,o,[[t,[...c,...e]]]);return i(s,u)}catch(t){if(!this.root.config.onError)throw t;const e=gs(a,C("execution",t),n,[],[[a,c]]);return i(e.snapshot,e.microsteps)}}start(t,e){if(!t?.children)return;const s=t.children;for(const t in s){if(!Object.hasOwn(s,t))continue;const n=s[t];n._rehydrated&&"active"===n.getSnapshot?.().status&&(e?e.actionExecutor(Bt(n)):n.system.startActor(n))}}getStateNodeById(t){const s=Ve(t),n=s?t.slice(1):t;if(""===n&&s)throw new Error(e(19,this.id));const r=this.idMap.get(n);if(r)return r;throw new Error(e(20,n))}getPersistedSnapshot(t,s){return function(t,s){const{nodes:n,_stateInputs:r,_nextTimerId:o,_nextActorIds:i,tags:a,machine:c,children:u,timers:d,context:h,can:f,hasTag:p,matches:l,getMeta:y,getInputs:v,toJSON:m,...g}=t,_={},x=[],E=!1!==s?.embedChildren;for(const t in u){const r=u[t],o="string"==typeof r.src?r.src:void 0,i=void 0===o&&!0===r._invoked&&n.some(e=>e.invoke.some(e=>e.id===t));if(!(void 0!==o||i||s&&"__unsafeAllowInlineActors"in s))throw new Error(e(41,t));const a=E&&!w(r);if(!a&&void 0===o)throw new Error(e(42,t));_[t]={address:r.address,...a?{snapshot:r.getPersistedSnapshot(s)}:{remote:!0,incarnation:w(r)?r.sessionId:void 0},...i?{}:{src:r.src},registryKey:r.registryKey,syncSnapshot:r._syncSnapshot}}const S=me(t)?.actor,k=S?.system?._clock?.now?void 0:S?.system?._snapshot?._scheduledTimers;for(const s of d){let n,r=s.event;if("xstate.timeout.actor"===r.type&&(r={...r},delete r.sessionId),"self"===s.target)n="self";else if(b(s.target))n={...s.target};else{const r=Object.entries(u).find(([,t])=>t===s.target)?.[0];if(r)n=r;else{if(s.target!==me(t)?.actor._parent)throw new Error(e(43,s.target.id));n={type:"parent"}}}const o=k?.[Q(S,B(s))],i=o?o.dueAt-s.delay:Z(s);x.push({...void 0!==s.id&&{id:s.id},...void 0!==s.seq&&{seq:s.seq},delay:s.delay,type:s.type,event:r,target:n,...void 0!==i&&{scheduledAt:i}})}const $={...g,context:zs(h,()=>me(t)?.actor.id??c.id),children:_,timers:x,historyValue:Ks(g.historyValue)};return r&&Object.keys(r).length>0&&($.stateInputs=r),$.nextTimerId=o,i&&Object.keys(i).length>0&&($.nextActorIds=i),void 0!==c.version&&($.machine={id:c.id,version:c.version}),$}(t,s)}}function Yn(t,e){return new Qn(t,void 0,e)}function Zn(t){return Array.isArray(t)?t.map(Zn):null===t||"object"!=typeof t||Object.getPrototypeOf(t)!==Object.prototype&&null!==Object.getPrototypeOf(t)?t:Object.fromEntries(Object.entries(t).map(([t,e])=>[t,Zn(e)]))}function tr(t){return!!t&&"object"==typeof t&&"function"==typeof t.transition&&"function"==typeof t.getInitialSnapshot}function er(t){return!!t&&"object"==typeof t&&"~standard"in t}function sr(t){if("function"==typeof t)return{"@code":t.toString(),"@lang":"ts"};if(null===t||"object"!=typeof t)return"bigint"==typeof t||"symbol"==typeof t?void 0:t;if(tr(t))return;if(er(t))return;if(Array.isArray(t))return t.map(sr).filter(t=>void 0!==t);if(Object.getPrototypeOf(t)!==Object.prototype&&null!==Object.getPrototypeOf(t))return;const e={};for(const s of Object.keys(t)){const n=t[s];if(void 0!==n){const t=sr(n);void 0!==t&&Object.defineProperty(e,s,{value:t,enumerable:!0,writable:!0,configurable:!0})}}return e}function nr(t){if(Array.isArray(t)){const e=t.map(nr).filter(t=>void 0!==t);return e.length?e:void 0}const e=t,s={};for(const t of Object.keys(e)){const n=e[t];void 0!==n&&(s[t]="src"===t&&"string"!=typeof n?n.id:sr(n),void 0===s[t]&&delete s[t])}return void 0===s.src?void 0:s}function rr(t){if(!t)return;const e={};for(const s of Object.keys(t)){const n=t[s];e[s]="function"==typeof n?void 0:sr(n),void 0===e[s]&&delete e[s]}return e}function or(t){const e={};for(const s of Object.keys(t)){if("states"===s||"invoke"===s)continue;const n=t[s];void 0!==n&&(e[s]=sr(n))}if(void 0!==t.invoke){const s=nr(t.invoke);void 0!==s&&(e.invoke=s)}if(t.states){const s={};for(const e of Object.keys(t.states))s[e]=or(t.states[e]);e.states=s}return e}function ir(t){const e=or(t),s=Object.keys(t.schemas?.internalEvents??{});if(delete e.internalEvents,s.length&&(e.internalEvents=s),t.schemas){const s={};for(const e of Object.keys(t.schemas)){const n=t.schemas[e];s[e]=n&&"object"==typeof n&&!("~standard"in n)?rr(n):sr(n),void 0===s[e]&&delete s[e]}e.schemas=s}for(const s of["actions","guards","actors","delays"])if(t[s]){const n=rr(t[s]);n&&Object.keys(n).length?e[s]=n:delete e[s]}return e}function ar(t){const e=re(t);return void 0!==e?e:"string"==typeof t?parseFloat(t)||0:t}function cr(t){return!!t&&"object"==typeof t&&"string"==typeof t["@expr"]}function ur(t){return cr(t)||function(t){return!!t&&"object"==typeof t&&"string"==typeof t["@code"]}(t)}function dr(t){return ur(t)||!!t&&"object"==typeof t&&Object.values(t).some(dr)}function hr(t,e){return"number"==typeof e?`${t}[${e}]`:`${t}.${e}`}function fr(t){const e={};if(!t)return e;for(const s of Object.keys(t)){const n=t[s];"number"==typeof n?e[s]=n:n&&"object"==typeof n&&"number"==typeof n.duration&&(e[s]=n.duration)}return e}function pr(t){return void 0===t?[]:Array.isArray(t)?t:[t]}function lr(t,e){Array.isArray(t)&&t.forEach((s,n)=>{if(void 0===s.when&&n!==t.length-1)throw new Error(`Choice fallback branch at ${e}[${n}] must be last.`)})}const yr=["target","matches","context","actions","guard","description","reenter","meta","input"],vr=["id","key","type","initial","states","on","onError","after","always","choice","route","invoke","entry","exit","meta","description","tags","input","timeout","onTimeout","history","target","output","context"],mr=["@exprLang","version","actions","guards","actors","delays","schemas","internalEvents"];function gr(t,e,s){for(const n of Object.keys(t))if(!e.includes(n))throw new Error(`Unknown key "${n}" at ${s}`)}function _r(t,e){if("compound"===t.type)try{t.initial}catch(t){throw new Error(`Invalid initial state at ${e}.initial: ${t.message}`)}for(const s of Object.keys(t.states))_r(t.states[s],`${e}.states.${s}`)}function wr(t){return!ur(t)&&t.type.startsWith("@xstate.")}function br(t,e){if(!t)return;if(Object.hasOwn(t,e))return t[e];const s=Object.keys(t).find(t=>sn(e,t));return void 0===s?void 0:t[s]}function xr(t,e,s){let n=t.get(e);return n||t.set(e,n=s()),n}const Er=new WeakMap,Sr=new WeakMap,kr=new WeakMap;function $r(t){return xr(Er,t,()=>({"~standard":{version:1,vendor:"xstate",validate:async e=>{if(null===e||"object"!=typeof e)return{issues:[{message:"Expected a persisted snapshot."}]};const s={historyValue:{},timers:[],...e},n=t.schemas?.context;let r=s.context;if(n){const e=await n["~standard"].validate(r);if(e.issues)return{issues:[{message:`Invalid context for machine '${t.id}' version '${t.version}': ${e.issues[0]?.message}`}]};r=e.value}for(const t of["value","children"])if(!(t in s))return{issues:[{message:`Persisted snapshot is missing '${t}'.`}]};if(!["active","done","error","stopped"].includes(s.status))return{issues:[{message:"Persisted snapshot has invalid status."}]};if(!Un(s.historyValue))return{issues:[{message:"Persisted snapshot has invalid 'historyValue'."}]};try{Bn(t,s)}catch(t){return{issues:[{message:t instanceof Error?t.message:"Persisted snapshot has invalid state value."}]}}return{value:{...s,context:r}}}}}))}function Ar(t){return xr(Sr,t,()=>({"~standard":{version:1,vendor:"xstate",validate:async e=>{if(null===e||"object"!=typeof e||"string"!=typeof e.type)return{issues:[{message:"Expected an event object."}]};const s=e,n=t.schemas?.events,r=t.schemas?.internalEvents,o=s.type.startsWith("xstate.")||s.type.startsWith("@xstate."),i=br(r,s.type)??br(n,s.type);if((n||r)&&!i&&!o)return{issues:[{message:`Unknown event '${s.type}' for machine '${t.id}' version '${t.version}'.`}]};if(!i)return{value:s};const{type:a,...c}=s,u=await i["~standard"].validate(c);return u.issues?u:null===u.value||"object"!=typeof u.value?{issues:[{message:"Expected an event payload."}]}:{value:{...u.value,type:a}}}}}))}function jr(t){return null!==t&&"object"==typeof t}function Or(t){return"transition"in t&&"function"==typeof t.transition}async function Ir(t,e,s){if(!t)return e;const n=await t["~standard"].validate(e);if(n.issues)throw new Error(`Invalid ${s}: ${n.issues[0]?.message}`);return n.value}async function Tr(t,e){return await Ir($r(e),{...t,machine:{id:e.id,version:e.version}},`snapshot for machine '${e.id}' version '${e.version}'`)}async function Mr(t,e,s){return Promise.all(t.map(async(t,e)=>{const n=await s["~standard"].validate(t);if(n.issues){const s=n.issues[0]?.message;if(s?.startsWith("Unknown event "))throw new Error(s);const r=jr(t)?t.type:void 0;throw new Error("string"==typeof r?`Invalid event '${r}' at index ${e}${s?`: ${s}`:"."}`:`Invalid event at index ${e}${s?`: ${s}`:"."}`)}const r=n.value;if(!jr(r)||"string"!=typeof r.type)throw new Error(`Invalid event at index ${e}.`);return r}))}function Rr(t,e,s=new Set){if(!t||"object"!=typeof t||s.has(t))return!1;if(s.add(t),tn(t))return e.has(t);const n=Object.getPrototypeOf(t);return(t instanceof Map||t instanceof Set?[...t.values()]:Array.isArray(t)||n===Object.prototype||null===n?Object.values(t):[]).some(t=>Rr(t,e,s))}const Pr=function(t={}){!function(t){if(t&&"object"==typeof t&&void 0!==t.internalEvents)throw new Error(e(2))}(t);const{validator:s,states:n={},schemas:r,actions:o,actors:i,guards:a,delays:c}=t;return{extend:e=>Pr(function(t,e){return{...t,...e,schemas:Dr(t.schemas,e.schemas),states:qr(t.states,e.states),actions:Nr(t.actions,e.actions),actors:Nr(t.actors,e.actors),guards:Nr(t.guards,e.guards),delays:Nr(t.delays,e.delays)}}(t,e)),createMachine(t,...d){if(void 0!==d[0])throw new Error(e(71));const h=Dr(t.schemas,r),f=Lr(t.states,n),p=Nr(o,t.actions),l=Nr(i,t.actors),y=Nr(a,t.guards),v=Nr(c,t.delays),m={...t,...h?{schemas:h}:void 0,...f?{states:f}:void 0,...p?{actions:p}:void 0,...l?{actors:l}:void 0,...y?{guards:y}:void 0,...v?{delays:v}:void 0};return u(m),new Qn(m,void 0,s)},createInvoke:(t,...e)=>"function"==typeof t.src?{...t,src:Dn({schemas:t.schemas,run:t.src})}:t,createStateConfig:(...t)=>t.length>1?t[1]:t[0],states:n,schemas:r??{}}};function Nr(t,e){return t||e?{...t,...e}:void 0}function qr(t,e){if(t||e)return t?e?Object.fromEntries(Array.from(new Set([...Object.keys(t),...Object.keys(e)])).map(s=>{const n=t[s],r=e[s];if(!n)return[s,r];if(!r)return[s,n];const o=Dr(n.schemas,r.schemas),i=qr(n.states,r.states);return[s,{...n,...r,...o?{schemas:o}:void 0,...i?{states:i}:void 0}]})):t:e}function Dr(t,e){if(t||e)return{...t,...e,events:Nr(t?.events,e?.events),internalEvents:Nr(t?.internalEvents,e?.internalEvents),actions:Nr(t?.actions,e?.actions),guards:Nr(t?.guards,e?.guards),emitted:Nr(t?.emitted,e?.emitted),children:Nr(t?.children,e?.children)}}function Lr(t,e){return t&&e?Object.fromEntries(Object.entries(t).map(([t,s])=>{const n=e[t];if(!n)return[t,s];const r=Nr(s.schemas,n.schemas),o=Lr(s.states,n.states),i=Object.fromEntries(["type","id","initial","history","target","route"].flatMap(t=>void 0===s[t]&&void 0!==n[t]?[[t,n[t]]]:[]));return[t,{...s,...i,...r?{schemas:r}:void 0,...o?{states:o}:void 0}]})):t}class Cr{constructor(t){this.before=t,this.entries=[],this.indices=new Map}push(t){this.entries.push(t),this.up(this.entries.length-1,t)}peek(){return this.entries[0]}pop(){const t=this.peek();return t&&this.remove(t),t}remove(t){const e=this.indices.get(t);if(void 0===e)return;const s=this.entries.pop();this.indices.delete(t),e!==this.entries.length&&(e>0&&this.before(s,this.entries[e-1>>1])?this.up(e,s):this.down(e,s))}up(t,e){for(;t>0;){const s=t-1>>1;if(!this.before(e,this.entries[s]))break;this.place(t,this.entries[s]),t=s}this.place(t,e)}down(t,e){for(;2*t+1<this.entries.length;){let s=2*t+1;if(s+1<this.entries.length&&this.before(this.entries[s+1],this.entries[s])&&s++,!this.before(this.entries[s],e))break;this.place(t,this.entries[s]),t=s}this.place(t,e)}place(t,e){this.entries[t]=e,this.indices.set(e,t)}}const Kr={$actor:["@actor",["incarnation"]],$error:["@error",["message"]],$stateNode:["@stateNode",[]],$systemMapper:["@systemMapper",[]]},zr={_stateInputs:"stateInputs",_nextTimerId:"nextTimerId",_nextActorIds:"nextActorIds"};function Wr(t){if(!t||"object"!=typeof t)return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e||Array.isArray(t)}function Vr(t,e){if(!Wr(t))return t;if(Array.isArray(t)){const s=t.map(t=>Vr(t,e));return s.some((e,s)=>e!==t[s])?s:t}const s=Object.keys(t),n=s.find(t=>e.includes(t));if(n&&"string"==typeof t[n]&&s.every(t=>t===n||Kr[n][1].includes(t))){const{[n]:e,...s}=t;return{[Kr[n][0]]:e,...s}}let r;for(const n of s){const s=Vr(t[n],e);s!==t[n]&&((r??={...t})[n]=s)}return r??t}function Ur(t){if(!Wr(t)||"function"==typeof t.matches)return t;let e;for(const[s,n]of Object.entries(zr))if(s in t&&!(n in t)){const{[s]:r,...o}=e??t;e={...o,[n]:r}}return e??t}function Jr(t){if(!Object.values(t?.actors??{}).some(t=>{return e=t?.snapshot,Wr(e)&&"_nextTimerId"in e&&!("nextTimerId"in e);var e}))return t;const e=Vr(t,Object.keys(Kr));if(!e?.actors)return e;let s;for(const[t,n]of Object.entries(e.actors)){const r=Ur(n?.snapshot);r!==n?.snapshot&&((s??={...e.actors})[t]={...n,snapshot:r})}return s?{...e,actors:s}:e}function Fr(t,e){const s="xstate.timer"===e.type?H(e):void 0;return JSON.stringify([t["@actor"],t.incarnation,s?G(s):e.type])}function Br(t,e){return(t.timers??[]).some(t=>X(t,e))}const Hr=Symbol("xstate.systemActorHandle"),Xr=()=>{};function Gr(t,e=new Set,s){if("function"==typeof t&&s?.has(t))return{"@systemMapper":s.get(t)};if(function(t){return!!t&&"string"==typeof t.address&&"function"==typeof t.getSnapshot}(t)){if(!t[Hr])throw new Error("Live actors cannot be stored in a pure system snapshot.");return{"@actor":t.address,incarnation:t.sessionId}}if(!t||"object"!=typeof t){if("function"==typeof t||"symbol"==typeof t||"bigint"==typeof t||"number"==typeof t&&!Number.isFinite(t))throw new Error("System snapshots require data, not executable capabilities.");return t}if(e.has(t))throw new Error("System snapshots cannot contain cyclic data.");let n;if(e.add(t),t.machine&&"function"==typeof t.machine.transition&&"string"==typeof t.id&&Array.isArray(t.path))n={"@stateNode":t.id};else if(t instanceof Error)n={"@error":t.name,message:t.message};else if(Array.isArray(t))n=t.map(t=>Gr(t,e,s));else{if(Object.getPrototypeOf(t)!==Object.prototype&&null!==Object.getPrototypeOf(t))throw new Error("System snapshot values must be plain data.");n=Object.fromEntries(Object.entries(t).map(([t,n])=>[t,Gr(n,e,s)]))}return e.delete(t),n}function Qr(t,e){if(!Is(t))return Gr(t,new Set,e);const{machine:s,nodes:n,tags:r,matches:o,can:i,hasTag:a,getMeta:c,getInputs:u,toJSON:d,_stateInputs:h,_nextTimerId:f,_nextActorIds:p,...l}=t;return Gr({...l,stateInputs:h,nextTimerId:f,nextActorIds:p,nodeIds:n.map(t=>t.id)},new Set,e)}class Yr{constructor(t,e,s=1e4){if(this.snapshot=void 0,this.effects=[],this.logic=void 0,this.handles=new Map,this.snapshots=new Map,this.initialEffects=new Map,this.stopping=new Set,this.deadlines=new Cr((t,e)=>t.dueAt<e.dueAt||t.dueAt===e.dueAt&&t.sequence<e.sequence),this.effectNames=new Map([[Xr,"@xstate.log"]]),this.mapperNames=void 0,this.mappers=void 0,this.remaining=void 0,!Number.isSafeInteger(s)||s<1)throw new Error("maxSteps must be a positive integer.");e=Jr(e),this.logic=function(t){const e=new Map,s=new Set;function n(t,r){if(e.set(t,r),s.has(r))return;s.add(r);const o=r;for(const[e,s]of Object.entries(o.sources?.actors??{}))n(`${t}/actors/${cn(e)}`,s);o.root&&function e(s){for(const e of s.invoke??[])"object"==typeof e.logic&&n(`${t}/invoke/${cn(s.id)}/${cn(e.id)}`,e.logic);for(const t of Object.values(s.states??{}))e(t)}(o.root)}n("root",t.root);for(const[e,s]of Object.entries(t.actors??{}))n(`actors/${cn(e)}`,s);return n("@xstate.listener",ut),n("@xstate.subscription",ht),e}(t),this.mappers=t.mappers??{},this.mapperNames=new Map(Object.entries(this.mappers).map(([t,e])=>[e,t]));for(const[e,s]of Object.entries(t.effects??{}))this.effectNames.set(s,e);for(const[t,e]of this.logic)for(const[s,n]of Object.entries(e.sources?.actions??{}))"function"!=typeof n||this.effectNames.has(n)||this.effectNames.set(n,`${t}/actions/${cn(s)}`);this.snapshot={...e,actors:Object.assign(Object.create(null),e.actors),registry:Object.assign(Object.create(null),e.registry),messages:[...e.messages],timers:Object.fromEntries(e.timers.map(t=>[Fr(t.source,t.event),t])),externalEffects:{...e.externalEffects},counters:{...e.counters}},this.remaining=s;for(const t of e.timers)this.deadlines.push(t)}step(){if(--this.remaining<0)throw new Error("System transition exceeded maxSteps; the input snapshot is unchanged.")}reference(t){return{"@actor":t.address,incarnation:t.sessionId}}current(t){const e=this.snapshot.actors[t["@actor"]];return e?.incarnation===t.incarnation?e:void 0}decode(t,e){if(function(t){return!!t&&"string"==typeof t["@actor"]&&"string"==typeof t.incarnation}(t))return this.handle(t);if(!t||"object"!=typeof t)return t;if("string"==typeof t["@systemMapper"]){const e=Object.hasOwn(this.mappers,t["@systemMapper"])&&this.mappers[t["@systemMapper"]];if(!e)throw new Error(`Missing pure mapper '${t["@systemMapper"]}'.`);return e}if("string"==typeof t["@stateNode"])return e.getStateNodeById(t["@stateNode"]);if("string"==typeof t["@error"]){const e=new Error(t.message);return e.name=t["@error"],"TimeoutError"===e.name&&Object.setPrototypeOf(e,qn.prototype),e}return Array.isArray(t)?t.map(t=>this.decode(t,e)):Object.fromEntries(Object.entries(t).map(([t,s])=>[t,this.decode(s,e)]))}encode(t){return Gr(t,new Set,this.mapperNames)}attachedKind(t){return this.logic.get(t.src)?.[rt]?.kind}relayAttachments(t,e){for(const s of Object.values(this.snapshot.actors)){const n=this.attachedKind(s);if(!s.started||"active"!==s.snapshot.status||"@xstate.listener"!==n&&"@xstate.subscription"!==n)continue;const r=s.input.actor;if(!r||r["@actor"]!==t["@actor"]||r.incarnation!==t.incarnation||!s.parent||"active"!==this.current(s.parent)?.snapshot.status)continue;const o=this.decode(s.input);let i;if("@xstate.listener"===n)e&&sn(e.type,o.eventType)&&(i=o.mapper(this.decode(this.encode(e))));else if(!e){const e=this.hydrate(t),s=o.mappers["active"===e.status?"snapshot":"done"===e.status?"done":"error"===e.status?"error":""];s&&(i=s("done"===e.status?e.output:"error"===e.status?e.error:e))}i&&this.enqueue({"@actor":s.address,incarnation:s.incarnation},s.parent,i)}}stopAttachments(t){for(const e of Object.values(this.snapshot.actors)){const s=this.attachedKind(e);"@xstate.listener"!==s&&"@xstate.subscription"!==s||e.parent?.["@actor"]!==t["@actor"]||e.parent.incarnation!==t.incarnation||this.stop({"@actor":e.address,incarnation:e.incarnation})}}hydrate(t){const e=JSON.stringify(t);if(this.snapshots.has(e))return this.snapshots.get(e);const s=this.current(t);if(!s)return{status:"stopped",output:void 0,error:void 0};const n=this.logic.get(s.src);if(!n||n.version!==s.logicVersion)throw new Error(`Actor definition/version mismatch for '${s.address}'.`);const r=this.decode(s.snapshot,n),o="function"==typeof n.getStateNodeById&&r.nodeIds?Ls({...r,_stateInputs:r.stateInputs,_nextTimerId:r.nextTimerId,_nextActorIds:r.nextActorIds,_nodes:r.nodeIds.map(t=>n.getStateNodeById(t))},n):r;return this.snapshots.set(e,o),o}handle(t){const e=JSON.stringify(t),s=this.handles.get(e);if(s)return s;const n=this.current(t),r=()=>this.current(t)??n,o=()=>this.logic.get(r()?.src??""),i=()=>{const t=r()?.parent;return t&&this.handle(t)},a=()=>this.hydrate(t),c=()=>{throw new Error("Use enqueue operations and systemTransition; live actor capabilities are unavailable in a pure snapshot.")},u={[Hr]:!0,id:n?.id??t["@actor"].split("/").at(-1),address:t["@actor"],sessionId:t.incarnation,options:{_inert:!0,input:n?.input},get logic(){return o()},get src(){return r()?.src},get registryKey(){return r()?.registryKey},get _parent(){return i()},get _snapshot(){return a()},getSnapshot:a,send:c,start:c,stop:c,subscribe:c,on:c,system:void 0};return this.handles.set(e,u),u.system=this.system(),u}system(){return{createActorRef:(t,e)=>this.allocate(t,e),_unregister:t=>{this.stopping.add(JSON.stringify(this.reference(t)));for(const[e,s]of Object.entries(this.snapshot.registry))s["@actor"]===t.address&&s.incarnation===t.sessionId&&delete this.snapshot.registry[e]},_getByAddress:t=>{const e=this.snapshot.actors[t];return"active"===e?.snapshot.status?this.handle({"@actor":t,incarnation:e.incarnation}):void 0},get:t=>this.snapshot.registry[t]&&this.handle(this.snapshot.registry[t]),getAll:()=>Object.fromEntries(Object.entries(this.snapshot.registry).map(([t,e])=>[t,this.handle(e)])),_hasInspectionObservers:()=>!1,_sendInspectionEvent:()=>{},_clock:{now:()=>this.snapshot.now,setTimeout:()=>{throw new Error("Timers must be declared as logical effects.")},clearTimeout:()=>{throw new Error("Timers must be canceled as logical effects.")}}}}scope(t,e){const s=this.handle(t);return s._lastSourceRef=e&&this.handle(e),{self:s,system:s.system,id:s.id,sessionId:s.sessionId,logger:Xr,defer:()=>{},emit:()=>{throw new Error("Emit events through enqueue operations.")},actionExecutor:()=>{throw new Error("Execute external effects outside system transitions.")},stopChild:()=>{throw new Error("Stop children through enqueue operations.")}}}allocate(t,e={}){this.step();const s=[...this.logic].find(([,e])=>e===t);if(!s)throw new Error("Register dynamically spawned logic in systemLogic.actors.");const n=e.parent&&this.reference(e.parent),r=e.id??`${an(e.src??t)}:${this.snapshot.counters.actor}`,o=`${n?n["@actor"]+"/":""}${cn(r)}`,i=this.snapshot.actors[o];if("active"===i?.snapshot.status){const t={"@actor":o,incarnation:i.incarnation};if(!this.stopping.has(JSON.stringify(t)))throw new Error(`Actor address '${o}' is already occupied.`);this.stop(t)}const a=String(this.snapshot.counters.actor++),c={"@actor":o,incarnation:a},u={id:r,address:o,incarnation:a,src:s[0],...void 0!==t.version&&{logicVersion:t.version},parent:n,registryKey:e.registryKey,syncSnapshot:e.syncSnapshot,started:!1,input:this.encode(e.input),snapshot:{status:"active",output:void 0,error:void 0}};if(this.snapshot.actors[o]=u,e.registryKey){if(this.snapshot.registry[e.registryKey])throw new Error(`Registry key '${e.registryKey}' is already occupied.`);this.snapshot.registry[e.registryKey]=c}const d=this.scope(c),h=t.initialTransition(this.decode(u.input),d),[f,p]=Qt(d,void 0,h);return this.store(c,f),this.initialEffects.set(JSON.stringify(c),p),this.handle(c)}store(t,e){const s=this.current(t);s&&(this.snapshots.set(JSON.stringify(t),e),this.snapshot.actors[t["@actor"]]={...s,snapshot:Qr(e,this.mapperNames)})}external(t,e){const s=e;if("action"===s.kind&&void 0===s.action)return;const n="action"===s.kind&&"@xstate.effect"!==s.type&&"@xstate.cleanup"!==s.type?this.effectNames.get(s.action):s.type;if(void 0===n)throw new Error("Register callable external actions in systemLogic.effects or the machine action sources.");const r=`${this.snapshot.executionId}:${this.snapshot.counters.effect++}`,o="function"==typeof s.params?.action?Object.fromEntries(Object.entries(s.params).filter(([t])=>"action"!==t&&"args"!==t)):s.params,i={id:r,source:t,type:n,kind:"emit"===s.kind?"emit":"@xstate.deadLetter"===s.type?"builtin":"action",...void 0!==o&&{params:this.encode(o)},args:this.encode(s.args??[]),...s.event&&{event:this.encode(s.event)},...s.reason&&{reason:s.reason}};this.effects.push(i),this.snapshot.externalEffects[r]=i,"emit"===s.kind&&this.relayAttachments(t,s.event)}enqueue(t,e,s,n){this.snapshot.messages.push({source:t,target:e,event:this.encode(s),sequence:this.snapshot.counters.sequence++,...void 0!==n&&{timerOccurrence:n}})}cancel(t,e){const s=e&&Fr(t,{type:"xstate.timer",...e});for(const[e,n]of Object.entries(this.snapshot.timers))n.source["@actor"]!==t["@actor"]||n.source.incarnation!==t.incarnation||void 0!==s&&e!==s||delete this.snapshot.timers[e]}effectsFor(t,e){for(const s of e){const e=s;if("builtin"===e.kind)switch(e.type){case"@xstate.spawn":break;case"@xstate.start":this.start(this.reference(e.actor));break;case"@xstate.stop":this.stop(this.reference(e.actor));break;case"@xstate.cancel":this.cancel(t,H(e));break;case"@xstate.raise":case"@xstate.sendTo":if(void 0!==e.delay){if(!Number.isFinite(e.delay)||e.delay<0)throw new Error("System timer delays must be finite and nonnegative.");const s=B(e),n=this.current(t);if(!n||!Br(n.snapshot,s))break;this.schedule(t,e.delay,{type:"xstate.timer",...s})}else if(b(e.target)){const s=this.snapshot.actors[e.target["@actor"]];"active"!==s?.snapshot.status||void 0!==e.target.incarnation&&e.target.incarnation!==s.incarnation?this.external(t,{kind:"builtin",type:"@xstate.deadLetter",event:e.event,reason:"missingTarget",args:[]}):this.enqueue(t,{"@actor":s.address,incarnation:s.incarnation},e.event)}else e.target&&this.enqueue(t,this.reference(e.target),e.event);break;case"@xstate.terminate":this.terminate(t);break;default:this.external(t,s)}else this.external(t,s)}}schedule(t,e,s){const n=this.snapshot.now+e;if(!Number.isFinite(e)||e<0||!Number.isFinite(n))throw new Error("System timer deadlines must be finite and delays nonnegative.");const r={source:t,occurrence:this.snapshot.counters.timer++,scheduledAt:this.snapshot.now,dueAt:n,sequence:this.snapshot.counters.sequence++,event:this.encode(s)},o=Fr(t,s);delete this.snapshot.timers[o],this.snapshot.timers[o]=r,this.deadlines.push(r)}start(t){const e=this.current(t);if(!e||e.started||"stopped"===e.snapshot.status)return;if(this.snapshot.actors[t["@actor"]]={...e,started:!0},this.effectsFor(t,this.initialEffects.get(JSON.stringify(t))??[]),this.initialEffects.delete(JSON.stringify(t)),"@xstate.subscription"===this.attachedKind(e)){const s=this.decode(e.input),n=this.reference(s.actor),r=this.current(n);r?.started&&"error"===r.snapshot.status&&s.mappers.error&&e.parent&&this.enqueue(t,e.parent,s.mappers.error(this.hydrate(n).error))}"active"===this.current(t)?.snapshot.status&&this.relayAttachments(t);const s=this.logic.get(e.src)[rt];if(void 0!==s?.timeout&&"active"===this.current(t)?.snapshot.status){const e=re(s.timeout);if(void 0===e)throw new Error("Unable to resolve async actor timeout.");this.schedule(t,e,{type:"xstate.async.reject",data:new qn(s.timeout)})}}stop(t){const e=this.current(t);e&&"active"===e.snapshot.status&&(this.process({source:t,target:t,event:{type:p},sequence:this.snapshot.counters.sequence++}),this.cancel(t),this.handle(t).system._unregister(this.handle(t)),this.snapshot.messages=this.snapshot.messages.filter(e=>e.target["@actor"]!==t["@actor"]||e.target.incarnation!==t.incarnation),this.cancelExternal(t),this.stopAttachments(t))}cancelExternal(t){for(const[e,s]of Object.entries(this.snapshot.externalEffects)){if("action"!==s.kind||"@xstate.cancelEffect"===s.type||"@xstate.cleanup"===s.type||s.source["@actor"]!==t["@actor"]||s.source.incarnation!==t.incarnation)continue;delete this.snapshot.externalEffects[e];const n={id:`${this.snapshot.executionId}:${this.snapshot.counters.effect++}`,source:t,kind:"action",type:"@xstate.cancelEffect",params:{effectId:e}};this.effects.push(n),this.snapshot.externalEffects[n.id]=n}}terminate(t){const e=this.current(t);if(e&&(this.relayAttachments(t),this.cancel(t),this.cancelExternal(t),this.stopAttachments(t),e.parent)){const s="done"===e.snapshot.status?D(e.id,this.decode(e.snapshot.output),e.incarnation):L(e.id,this.decode(e.snapshot.error),e.incarnation);this.enqueue(t,e.parent,s)}}process(t){this.step();const e=this.current(t.target);if(!e||"active"!==e.snapshot.status)return;if("xstate.timer"===t.event.type&&void 0===t.timerOccurrence)throw new Error("Only the system scheduler may deliver a timer occurrence.");const s=this.logic.get(e.src);if(!s)throw new Error(`Missing actor definition '${e.src}'.`);if(s.isInternalEventType?.(t.event.type)&&(!t.source||t.source["@actor"]!==e.address||t.source.incarnation!==e.incarnation))throw new Error(`Internal event '${t.event.type}' cannot be injected into a pure system.`);if(!t.source&&/^(xstate\.after(?:\.|$)|xstate\.timeout(?:\.|$))/.test(t.event.type))throw new Error("Select a pending timer instead of injecting its internal event.");const n=this.scope(t.target,t.source),r=this.hydrate(t.target),[o,i]=Qt(n,r,s.transition(r,this.decode(t.event),n));this.store(t.target,o),this.effectsFor(t.target,i),"active"===o.status&&this.relayAttachments(t.target),e.syncSnapshot&&e.parent&&"active"===o.status&&this.enqueue(t.target,e.parent,{type:"xstate.snapshot.actor",actorId:e.id,sessionId:e.incarnation,snapshot:Qr(o,this.mapperNames)})}result(){return{...this.snapshot,timers:Object.values(this.snapshot.timers)}}settle(){for(;this.snapshot.messages.length;){const t=this.snapshot.messages.shift();this.process(t)}}advance(t){if(!Number.isFinite(t)||t<this.snapshot.now)throw new Error("System time must be finite and cannot move backwards.");for(this.settle();;){const e=this.deadlines.peek();if(e&&this.snapshot.timers[Fr(e.source,e.event)]!==e){this.deadlines.pop();continue}if(!e||e.dueAt>t)break;this.step(),this.deadlines.pop(),delete this.snapshot.timers[Fr(e.source,e.event)],this.snapshot.now=Math.max(this.snapshot.now,e.dueAt);const s=this.current(e.source),n="xstate.timer"===e.event.type?H(e.event):void 0;!s||"active"!==s.snapshot.status||n&&!Br(s.snapshot,n)||(this.enqueue(e.source,e.source,e.event,e.occurrence),this.settle())}this.snapshot.now=t}send(t,e){if("xstate.timer"===e.type){const s=this.snapshot.actors[t];if(!s)throw new Error(`Unknown actor address '${t}'.`);const n=Object.values(this.snapshot.timers).find(n=>n.source["@actor"]===t&&n.source.incarnation===s.incarnation&&n.occurrence===e.occurrence);if(!n)throw new Error("Select a current timer occurrence.");return void this.advance(n.dueAt)}this.advance(this.snapshot.now);const s=this.snapshot.actors[t];if(!s)throw new Error(`Unknown actor address '${t}'.`);const n={"@actor":t,incarnation:s.incarnation};if("xstate.system.effect.result"===e.type){const r=this.snapshot.externalEffects[e.effectId];if(!r||r.source["@actor"]!==t||e.event&&(r.source.incarnation!==s.incarnation||"active"!==s.snapshot.status||"@xstate.cancelEffect"===r.type||"@xstate.cleanup"===r.type))throw new Error("External effect result does not match its owner or is stale.");return delete this.snapshot.externalEffects[e.effectId],void(e.event&&(this.enqueue(n,n,e.event),this.settle()))}if(e.type===p)return this.stop(n),void this.settle();if(e.type.startsWith("xstate.async.")||e.type.startsWith("xstate.logic.effect."))throw new Error("Deliver external work results with xstate.system.effect.result.");this.enqueue(void 0,n,e),this.settle()}initialize(t,e,s){const n=this.allocate(this.logic.get("root"),{id:e,input:t,registryKey:s});this.snapshot.root=n.address,this.start(this.reference(n)),this.settle()}}function Zr(t,e,s){const n=t.map(([t,e,s])=>[t,e,s??[]]);if(!n.length)return n;const r=n.at(-1)[0];Se(e,r,!1),r!==s&&$e(e,r);for(const[t]of n)if(t!==s&&t!==r){$e(Pe(t.machine,t,void 0,e),t)}return n}function to(t,e,s){}function eo(t){if(b(t))return{...t};const e=w(t)?t.sessionId:void 0;return void 0===e?{"@actor":t.address}:{"@actor":t.address,incarnation:e}}const so={timeout:1/0};t.Actor=Sn,t.InfiniteTransitionError=ms,t.InvalidSnapshotError=Vn,t.SimulatedClock=class{constructor(){this.timeouts=new Map,this.deadlines=new Cr((t,e)=>{const s=t.start+t.timeout,n=e.start+e.timeout;return s<n||s===n&&t.id<e.id}),this._now=0,this._id=0,this._flushing=!1}now(){return this._now}getId(){return this._id++}setTimeout(t,e){if(!Number.isFinite(e))throw new Error("Timer delay must be finite");const s=this.getId(),n={id:s,start:this.now(),timeout:Math.max(0,e),fn:t};return this.timeouts.set(s,n),this.deadlines.push(n),s}clearTimeout(t){const e=this.timeouts.get(t);e&&this.deadlines.remove(e),this.timeouts.delete(t)}set(t){if(!Number.isFinite(t)||this._now>t)throw new Error("Clock time must be finite; unable to travel back in time");if(this._flushing)throw new Error("Cannot advance a clock during a timer callback");this.flushTimeouts(t)}flushTimeouts(t){this._flushing=!0;try{let e=0;for(;;){const s=this.deadlines.peek();if(!s||s.start+s.timeout>t)break;if(++e>1e4)throw new Error("Clock exceeded 10,000 timer callbacks; check for a zero-delay loop");this.deadlines.pop(),this._now=Math.max(this._now,s.start+s.timeout),this.timeouts.delete(s.id),s.fn.call(null)}this._now=t}finally{this._flushing=!1}}increment(t){this.set(this._now+t)}},t.StateMachine=Qn,t.StateNode=zn,t.TimeoutError=qn,t._createMachineFromCompiledConfig=Yn,t._hotSwapActorLogic=function(t,e){const s=t,n=s.getSnapshot();if(s._processingStatus!==_n.Running||"active"!==n.status||n.machine?.id!==e.id)return!1;let r;const o={};try{r=[...Ke(ns(e.root,n.value))];for(const[t,s]of Object.entries(n.historyValue??{})){if("history"!==e.getStateNodeById(t).type)return!1;o[t]=s.map(t=>e.getStateNodeById(t.id))}}catch{return!1}const i={},a=[];for(const[t,s]of Object.entries(n.children)){if(!s)continue;const o="string"!=typeof s.src&&!0===s._invoked&&n.nodes.some(e=>e.invoke.some(e=>e.id===t));if("string"!=typeof s.src&&!o){i[t]=s;continue}let c;try{c="string"==typeof s.src?e.sources.actors[s.src]:en(e,r,t)}catch{}if(!c||"function"==typeof c)return!1;c===s.logic?i[t]=s:a.push([t,s,c])}const c=new Set(a.map(([,t])=>t));if(c.size&&((n.timers??[]).some(t=>c.has(t.target))||Rr(n.context,c)))return!1;const u=()=>Ls({...n,_nodes:r,value:void 0,children:i,historyValue:o},e);if(e.validator?.check({kind:"result",logic:e,snapshot:u(),effects:[]}))return!1;for(const[t,e,n]of a)s._stopChild(e),i[t]=s.system.createActorRef(n,{id:t,parent:s,syncSnapshot:e._syncSnapshot,src:"string"==typeof e.src?e.src:void 0,registryKey:e.registryKey,input:e.options?.input}),i[t]._invoked=e._invoked;s.src===s.logic&&(s.src=e),s.logic=e;const d=u();s._setSnapshot(d),s._next(d);for(const[t]of a)i[t].start();return!0},t._parseDelayToMilliseconds=re,t._toObserver=Zs,t.advanceSystemTime=function(t,e,s){const n=new Yr(t,e,s.maxSteps);return n.advance(s.time),[n.result(),n.effects]},t.assertEvent=function(t,s){const n=Bs(s);if(!n.some(e=>sn(t.type,e)))throw new Error(e(74,t.type,n.join(", ")))},t.createActor=kn,t.createAsyncLogic=Dn,t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return On({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:n,input:r,self:o,system:i}=t,a=t.emit,c=In.get(o);c?.receivers?.forEach(t=>t(n)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return In.set(o,t),t.dispose=e({input:r,system:i,self:o,sendBack:t=>{if("stopped"===o.getSnapshot().status)return;const e=o._parent;e&&i._relay(o,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:a}),()=>{In.delete(o),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return kn(Ln)},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.validator,n={config:t,validator:s,transition:(t,e,s)=>{if("active"!==t.status)return[t,[]];switch(e.type){case Mn:return Qt(s,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case Rn:return Qt(s,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case p:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{s&&$n(s,{kind:"input",logic:n,input:t});return[{status:"active",output:void 0,error:void 0,context:void 0,input:t,_subscription:void 0},[]]},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],start:(t,{self:s,system:n,emit:r})=>{"done"!==t.status&&(t._subscription=e({input:t.input,system:n,self:s,emit:t=>{r(t)}}).subscribe({next:t=>{s._parent&&n._relay(s,s._parent,t)},error:t=>{n._relay(s,s,{type:Mn,data:t})},complete:()=>{n._relay(s,s,{type:Rn})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return n},t.createListenerLogic=ct,t.createMachine=function(t,...s){if(void 0!==s[0])throw new Error(e(71));return u(t),new Qn(t)},t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return On({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:n,input:r,self:o,system:i}=t;switch(n.type){case Tn:return{context:n.data};case Mn:return{status:"error",error:n.data,input:void 0,effects:{observable:{status:"error",error:n.data}}};case Rn:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}n.type===h&&s.effect((t=i)=>{const s=o,n=e=>{t.sendEvent(s,s,e)},a=e({input:r,system:i,self:o,emit:e=>{$(s,e,t)}}).subscribe({next:t=>{n({type:Tn,data:t})},error:t=>{n({type:Mn,data:t})},complete:()=>{n({type:Rn})}});return()=>a.unsubscribe()})}})},t.createStateConfig=function(t){return t},t.createStepLogic=On,t.createSubscriptionLogic=dt,t.createSystem=function(t={}){const e={initialize:()=>n()},s=new Set,n=()=>{const t=e.current;if(t)for(const e of s){const n=e.subscribe(t);s.delete(e)?e.subscription=n:n.unsubscribe()}},r=t=>{const n=e.current;if(n)return t(n);const r={subscribe:t};return s.add(r),{unsubscribe(){s.delete(r),r.subscription?.unsubscribe()}}};if(t.onEmitted){const e=t.onEmitted;r(t=>t.onEmitted(e))}return{createActor:(t,...[s])=>kn(t,{...s,_systemRef:e}),get:t=>e.current?.get(t),getAll:()=>e.current?.getAll()??{},inspect:t=>r(e=>e.inspect(t)),onEmitted:t=>r(e=>e.onEmitted(t)),onRejectedEvent:t=>r(e=>e.onRejectedEvent(t)),setup:Pr}},t.deliverEvent=O,t.describeExecutableEffect=function(t){if("action"===t.kind)return{kind:"action",type:t.type,params:t.params};if("emit"===t.kind)return{kind:"emit",type:t.type,source:eo(t.source),event:t.event};switch(t.type){case"@xstate.spawn":return{kind:"builtin",type:"@xstate.spawn",source:t.source&&eo(t.source),actor:eo(t.actor),id:t.id,src:an(t.src),input:t.input};case"@xstate.start":return{kind:"builtin",type:"@xstate.start",source:t.source&&eo(t.source),actor:eo(t.actor),id:t.id};case"@xstate.raise":return{kind:"builtin",type:"@xstate.raise",source:eo(t.source),event:t.event,id:t.id,...void 0!==t.seq&&{seq:t.seq},delay:t.delay};case"@xstate.sendTo":return{kind:"builtin",type:"@xstate.sendTo",source:eo(t.source),target:t.target&&eo(t.target),event:t.event,id:t.id,...void 0!==t.seq&&{seq:t.seq},delay:t.delay};case"@xstate.cancel":return{kind:"builtin",type:"@xstate.cancel",source:eo(t.source),...H(t)};case"@xstate.stop":return{kind:"builtin",type:"@xstate.stop",source:eo(t.source),actor:eo(t.actor),id:t.id};case"@xstate.terminate":return{kind:"builtin",type:"@xstate.terminate",source:eo(t.source),actor:eo(t.actor),id:t.id,status:t.status,output:t.output,error:t.error};case"@xstate.deadLetter":return{kind:"builtin",type:"@xstate.deadLetter",source:t.source&&eo(t.source),target:t.target&&eo(t.target),event:t.event,reason:t.reason,issues:t.detail?.issues,error:t.detail?.error}}},t.eventSchema=function(t){return xr(kr,t,()=>({"~standard":{version:1,vendor:"xstate",validate:async e=>{const s=e;if(s&&"string"==typeof s.type){const n=br(t.schemas?.internalEvents,s.type),r=s.type.startsWith("xstate.")||s.type.startsWith("@xstate.");if(n||r){if(!n&&"xstate.route"===s.type){const s=await Ar(t)["~standard"].validate(e);if(s.issues)return s;const n=s.value.to,r="string"==typeof n&&n.startsWith("#")?t.idMap.get(n.slice(1)):void 0;if(r&&r!==t.root&&r.config.id&&r.config.route)return{value:s.value}}return{issues:[{message:`Event '${s.type}' is not a public input event.`}]}}}return Ar(t)["~standard"].validate(e)}}}))},t.executeEffects=async function(t,e){for(const s of t)await s.exec(e)},t.getInitialMicrosteps=function(t,...[e]){const s=Pe(t);Rt(s);const n=K(e),r=[],o=t._getPreInitialState(s,n),i=Object.values(o.children).filter(Boolean).map(t=>Ht(t)),a=ls(t.root,o,s,n,r),{microsteps:c}=gs(a[0],n,s,r,[[a[0],[...i,...a[1]],[]]]);return Zr(c,s)},t.getMachineSerializationDiagnostics=function(t){const e=[],s=new Set,n=(t,r,o=!1)=>{const i=(t,s)=>e.push({code:t,path:r,message:s});if("function"!=typeof t)if(void 0!==t&&"bigint"!=typeof t&&"symbol"!=typeof t)if("number"!=typeof t||Number.isFinite(t)){if(t&&"object"==typeof t){if(tr(t)){const e="string"==typeof t.id;return void i(e?"runtime-source":"omitted-value",e?"Supply the actor implementation under its source ID when reviving.":"This actor has no named source; an invocation using it is omitted.")}if(er(t))i("omitted-value","Runtime schemas are omitted; supply runtime schemas again when reviving.");else if(s.has(t))i("unsupported-value","Cyclic data cannot be exported as a JSON definition.");else if(Array.isArray(t)||Object.getPrototypeOf(t)===Object.prototype||null===Object.getPrototypeOf(t))if(Object.hasOwn(t,"@code"))i("code-expression","This source expression requires an evaluator and its dependencies.");else{s.add(t);for(const[e,s]of Object.entries(t)){const t=`${r}/${e.replaceAll("~","~0").replaceAll("/","~1")}`,o=/^\/(actions|guards|actors|delays)$/.test(r);n(s,t,o)}s.delete(t)}else i("omitted-value","Class instances are omitted from the exported definition.")}}else i("unsupported-value","Nonfinite numbers do not retain their value in JSON.");else i("omitted-value","This value is omitted from the exported definition.");else i(o?"runtime-source":"code-expression",o?"Supply this named implementation when reviving the definition.":"This function becomes source text and requires an evaluator and its dependencies.")};return n(t._json??t.config,""),e},t.getMicrosteps=function(t,e,s){const n=Pe(t,e);Rt(n);const{microsteps:r}=gs(e,s,n,[]);return Zr(r,n,e)},t.getNextTransitions=function(t){if("active"!==t.status)return[];const e=[],s=t.nodes.filter(De),n=new Set;for(const t of s)for(const s of[t].concat(Ce(t,void 0)))if(!n.has(s.id)){n.add(s.id);for(const[,t]of s.transitions.entries())e.push(...t);s.always&&e.push(...s.always)}return e},t.getStateNodes=ns,t.initialSystemTransition=function(t,e={}){const s=e.time??0;if(!Number.isFinite(s)||s<0)throw new Error("Initial system time must be finite and nonnegative.");const n=new Yr(t,{root:"",executionId:e.executionId??"system",now:s,actors:{},registry:{},messages:[],timers:[],externalEffects:{},counters:{actor:0,timer:0,sequence:0,effect:0}},e.maxSteps);return n.initialize(e.input,e.id??t.root.id??"root",e.registryKey),[n.result(),n.effects]},t.initialTransition=function(t,...[e]){const s=Pe(t),[n,r]=Qt(s,void 0,t.initialTransition(e,s));Se(s,n,!1);const o=$e(s,n);return to(s,o,K(e)),[o,r]},t.isBuiltInExecutableEffect=Yt,t.isMachineSnapshot=Is,t.isTypeSchema=function(t){return!!t&&"object"==typeof t&&"~standard"in t&&"xstate.types"===t["~standard"].vendor},t.isUnhandled=function(t,e){return e[0]===t&&0===e[1].length},t.machineConfigToJSON=ir,t.machineFromJSON=function(t,e={}){const s=function(t,e){return{actions:e.actions??{},guards:e.guards??{},actors:e.actors??{},delays:{...fr(t.delays),...e.delays??{}},evaluators:e.evaluators??{}}}(t=Zn(t),e),n=function(t,e){function s(s,n){const r=s["@lang"]??t;if(!r)throw new Error(`Missing @exprLang for expression at ${n}`);const o=e.evaluators[r];if(!o)throw new Error(`Missing evaluator for @lang '${r}' at ${n}`);return o}function n(t,e,n,r){const o=cr(t)?"expr":"code",i=cr(t)?t["@expr"]:t["@code"];return s(t,r)({source:i,kind:o,slot:e,scope:n,path:r})}function r(t,e,s,o){if(ur(t))return n(t,e,s,o);if(Array.isArray(t))return t.map((t,n)=>r(t,e,s,hr(o,n)));if(!t||"object"!=typeof t)return t;const i={};for(const n of Object.keys(t))i[n]=r(t[n],e,s,hr(o,n));return i}function o(t,e){return{context:t.context,event:t.event,input:t.input,self:t.self,children:t.children,params:t.params,actions:t.actions,actors:t.actors,guards:t.guards,delays:t.delays,...e}}return{evaluateResolvable:n,resolveValue:r,makeScope:o,getDurationConfig:function(t,e){return ur(t)?s=>ar(r(t,"delay",o(s),e)):t},assertResolvable:function t(e,n){if(ur(e))s(e,n);else if(Array.isArray(e))e.forEach((e,s)=>t(e,hr(n,s)));else if(e&&"object"==typeof e)for(const s of Object.keys(e))t(e[s],hr(n,s))}}}(t["@exprLang"],s),{evaluateResolvable:r,resolveValue:o,makeScope:i,getDurationConfig:a}=n;function c(e,s,n){if(e){if(ur(e))return t=>!!r(e,s,i(t),n);if("@xstate.not"===e.type){const t=c(e.params?.guard,s,`${n}.params.guard`);return e=>!t?.(e)}return"@xstate.stateIn"===e.type?t=>{const r=o(e.params,s,i(t),`${n}.params`),a=r?.stateId;return"string"==typeof a&&!!t._snapshot?.matches(`#${a.replace(/^#/,"")}`)}:r=>{const a=o(e.params,s,i(r),`${n}.params`),u=t.guards?.[e.type];if(u){const t=c(u.when,"guard",`$.guards.${e.type}.when`);return!!t?.({...r,params:a})}const d=r.guards?.[e.type];if(!d)throw new Error((h=e.type,f=r.guards??{},`Guard '${h}' is not implemented in ${t.id?`machine '${t.id}'`:"the machine"}. Available guards: ${Object.keys(f).map(t=>`'${t}'`).join(", ")||"(none)"}.`));var h,f;return d(r,a)}}}function u(t,e){if(t)return ur(t)?s=>r(t,"choice",i(s),e):(lr(t,e),s=>{for(let n=0;n<t.length;n++){const r=t[n],a=c(r.when,"choice",`${e}[${n}].when`);if(!a||a(s))return{target:r.target,context:r.context?o(r.context,"transitionContext",i(s),`${e}[${n}].context`):void 0,input:void 0!==r.input?o(r.input,"input",i(s),`${e}[${n}].input`):void 0,description:r.description,reenter:r.reenter,meta:r.meta}}throw new Error(`Choice state at ${e} did not match any branch.`)})}function d(t,e){if(!t||"function"==typeof t)return t;if(ur(t))return s=>r(t,"transition",i(s),e);const{guard:s,...n}=t;if(!s)return n;const o=c({type:s},"guard",e);return t=>o(t)?n:void 0}function h(e,s,n,a,c=[]){let u;const d=()=>u?{...s,context:{...s.context,...u}}:s;for(let f=0;f<e.length;f++){const p=e[f],l=`${a}[${f}]`;if(ur(p)){const t=r(p,"action",i(d(),{params:s.params,enq:n}),l);t&&"object"==typeof t&&"context"in t&&t.context&&(u??={},Object.assign(u,t.context));continue}if(wr(p)){switch(p.type){case"@xstate.raise":n.raise(o(p.event,"actionParams",i(d(),{params:s.params}),`${l}.event`),{id:p.id,delay:p.delay});break;case"@xstate.cancel":n.cancel(p.id);break;case"@xstate.log":n.log(...p.args);break;case"@xstate.emit":n.emit(o(p.event,"actionParams",i(d(),{params:s.params}),`${l}.event`));break;case"@xstate.assign":u??={},Object.assign(u,o(p.context,"transitionContext",i(d(),{params:s.params}),`${l}.context`))}continue}const y=o(p.params,"actionParams",i(d(),{params:s.params}),`${l}.params`),v=t.actions?.[p.type];if(!v){n(s.actions[p.type],y);continue}if(c.includes(p.type))throw new Error(`Circular action reference: ${c.concat(p.type).join(" -> ")}`);const m=h(Array.isArray(v)?v:[v],{...s,context:{...s.context,...u},params:y},n,`${l}.actions.${p.type}`,c.concat(p.type));m.context&&(u=m.context)}return{context:u?{...s.context,...u}:void 0}}function f(t,e){const s=pr(t);return(t,n)=>h(s,t,n,e)}function p(t,e){return(Array.isArray(t)?t:[t]).map((s,n)=>{const a=Array.isArray(t)?`${e}[${n}]`:e;if(ur(s))return(t,e)=>r(s,"transition",i(t,{enq:e}),a);const u=s.context?t=>o(s.context,"transitionContext",i(t),`${a}.context`):void 0,d=void 0!==s.input?t=>o(s.input,"input",i(t),`${a}.input`):void 0,f=!!u||!!s.actions?.length;return{matches:s.matches,target:f?void 0:s.target,to:f?(t,e)=>{const n=u?.(t),r=s.actions?.length?h(s.actions,n?{...t,context:{...t.context,...n}}:t,e,`${a}.actions`):void 0;return{target:s.target,context:r?.context??n,reenter:s.reenter}}:void 0,guard:c(s.guard,"guard",`${a}.guard`),description:s.description,reenter:s.reenter,meta:s.meta,input:d}})}function l(t,e){return(Array.isArray(t)?t:[t]).map((s,n)=>{const r=`${e}.invoke${Array.isArray(t)?`[${n}]`:""}`;return{src:s.src,id:s.id,registryKey:s.registryKey,input:void 0!==s.input?t=>o(s.input,"input",i(t),`${r}.input`):void 0,onDone:s.onDone?p(s.onDone,`${r}.onDone`):void 0,onError:s.onError?p(s.onError,`${r}.onError`):void 0,onSnapshot:s.onSnapshot?p(s.onSnapshot,`${r}.onSnapshot`):void 0,timeout:a(s.timeout,`${r}.timeout`),onTimeout:s.onTimeout?p(s.onTimeout,`${r}.onTimeout`):void 0}})}if(t.delays)for(const[e,n]of Object.entries(t.delays))"number"==typeof n?s.delays[e]=n:"string"==typeof n?s.delays[e]=ar(n):n&&"object"==typeof n&&(s.delays[e]=t=>ar(o(n.duration,"delay",i(t),`$.delays.${e}.duration`)));const y=function(t,e,s){const{assertResolvable:n}=s,r=[];function o(s,i,a=[]){if(!s)return;if(ur(s))return void n(s,i);if(n(s.params,`${i}.params`),t.guards?.[s.type]){if(a.includes(s.type))throw new Error(`Circular guard reference: ${a.concat(s.type).join(" -> ")}`);return void o(t.guards[s.type].when,`$.guards.${s.type}.when`,a.concat(s.type))}if(e.guards[s.type])return;const c=s.params;if("@xstate.not"!==s.type){if("@xstate.stateIn"!==s.type)throw new Error(`Missing guard source "${s.type}"`);if("string"==typeof c?.stateId)r.push({stateId:c.stateId,path:`${i}.params.stateId`});else if(!ur(c?.stateId))throw new Error(`Missing state ID at ${i}.params.stateId`)}else{if(!c?.guard)throw new Error(`Missing guard at ${i}.params.guard`);o(c.guard,`${i}.params.guard`,a)}}function i(s,r,o=[]){if(ur(s))return void n(s,r);if(!s||"string"!=typeof s.type)throw new Error(`Invalid action at ${r}`);if(n(s.params,`${r}.params`),s.type.startsWith("@xstate."))return void n(s,r);const a=t.actions?.[s.type];if(a){if(o.includes(s.type))throw new Error(`Circular action reference: ${o.concat(s.type).join(" -> ")}`);const t=Array.isArray(a)?a:[a];return void t.forEach((e,n)=>i(e,`${r}.actions.${s.type}${t.length>1?`[${n}]`:""}`,o.concat(s.type)))}if(!e.actions[s.type])throw new Error(`Missing action source "${s.type}"`)}function a(t,e){pr(t).forEach((t,s)=>i(t,`${e}[${s}]`))}function c(t,e){(Array.isArray(t)?t:t?[t]:[]).forEach((s,r)=>{const i=Array.isArray(t)?`${e}[${r}]`:e;if(ur(s))n(s,i);else{if(!s||"object"!=typeof s)throw new Error("string"==typeof s?`Invalid transition at ${i}: use { "target": ${JSON.stringify(s)} } instead of a string`:`Invalid transition at ${i}`);gr(s,yr,i),o(s.guard,`${i}.guard`),a(s.actions,`${i}.actions`),n(s.context,`${i}.context`),n(s.input,`${i}.input`)}})}for(const e of["actions","guards","delays"])for(const s of Object.keys(t[e]??{}))Vs(e,s);if(t.actions)for(const e of Object.keys(t.actions)){const s=Array.isArray(t.actions[e])?t.actions[e]:[t.actions[e]];s.forEach((t,n)=>i(t,`$.actions.${e}${s.length>1?`[${n}]`:""}`,[e]))}if(t.guards)for(const e of Object.keys(t.guards))o(t.guards[e].when,`$.guards.${e}.when`,[e]);if(t.delays)for(const e of Object.keys(t.delays)){const s=t.delays[e];n(s&&"object"==typeof s&&"duration"in s?s.duration:s,`$.delays.${e}`)}return function s(r,i){if(gr(r,"$"===i?[...vr,...mr]:vr,i),("history"===r.type||void 0!==r.history)&&!("string"==typeof r.target&&r.target.trim().length>0||Array.isArray(r.target)&&r.target.length>0&&r.target.every(t=>t.trim().length>0)))throw new Error(`History state at ${i} must declare a non-empty target.`);if(n(r.context,`${i}.context`),n(r.input,`${i}.input`),n(r.output,`${i}.output`),n(r.timeout,`${i}.timeout`),a(r.entry,`${i}.entry`),a(r.exit,`${i}.exit`),"choice"===r.type){if(!r.choice)throw new Error(`Choice state at ${i} must declare choice.`);Array.isArray(r.choice)?(lr(r.choice,`${i}.choice`),r.choice.forEach((t,e)=>{o(t.when,`${i}.choice[${e}].when`),n(t.context,`${i}.choice[${e}].context`),n(t.input,`${i}.choice[${e}].input`)})):n(r.choice,`${i}.choice`)}if(ur(r.route)&&n(r.route,`${i}.route`),r.invoke&&(Array.isArray(r.invoke)?r.invoke:[r.invoke]).forEach((t,s)=>{const o=`${i}.invoke${Array.isArray(r.invoke)?`[${s}]`:""}`;if(!e.actors[t.src])throw new Error(`Missing actor source "${t.src}"`);n(t.input,`${o}.input`),n(t.timeout,`${o}.timeout`),c(t.onDone,`${o}.onDone`),c(t.onError,`${o}.onError`),c(t.onSnapshot,`${o}.onSnapshot`),c(t.onTimeout,`${o}.onTimeout`)}),r.on)for(const t of Object.keys(r.on))c(r.on[t],`${i}.on.${t}`);if(r.after)for(const s of Object.keys(r.after)){if(Number.isNaN(Number(s))&&void 0===re(s)&&!t.delays?.[s]&&!e.delays[s])throw new Error(`Missing delay source "${s}"`);c(r.after[s],`${i}.after.${s}`)}if(c(r.always,`${i}.always`),c(r.onError,`${i}.onError`),c(r.onTimeout,`${i}.onTimeout`),r.states)for(const t of Object.keys(r.states))s(r.states[t],`${i}.states.${t}`)}(t,"$"),r}(t,s,n),v=t.context?{context:e=>o(t.context,"context",e,"$.context")}:{},m=Yn({...function t(e,s){return{id:e.id,initial:e.initial,type:e.type,history:e.history,target:e.target,description:e.description,tags:e.tags,input:e.input,timeout:a(e.timeout,`${s}.timeout`),states:e.states?Object.fromEntries(Object.entries(e.states).map(([e,n])=>[e,t(n,`${s}.states.${e}`)])):void 0,on:e.on?Object.fromEntries(Object.entries(e.on).map(([t,e])=>[t,p(e,`${s}.on.${t}`)])):void 0,always:e.always?p(e.always,`${s}.always`):void 0,onError:e.onError?p(e.onError,`${s}.onError`):void 0,choice:u(e.choice,`${s}.choice`),route:d(e.route,`${s}.route`),after:e.after?Object.fromEntries(Object.entries(e.after).map(([t,e])=>[t,p(e,`${s}.after.${t}`)])):void 0,onTimeout:e.onTimeout?p(e.onTimeout,`${s}.onTimeout`):void 0,entry:e.entry?f(e.entry,`${s}.entry`):void 0,exit:e.exit?f(e.exit,`${s}.exit`):void 0,invoke:e.invoke?l(e.invoke,s):void 0,meta:e.meta,output:dr(e.output)?({context:t,event:n,self:r,input:i})=>o(e.output,"output",{context:t,event:n,self:r,input:i},`${s}.output`):e.output}}(t,"$"),...v,version:t.version,...e.schemas&&{schemas:e.schemas}},e.validator);_r(m.root,"$");for(const{stateId:t,path:e}of y)if(!m.idMap.has(t.replace(/^#/,"")))throw new Error(`Unknown state ID "${t}" at ${e}`);t.internalEvents?.length&&(m.internalEventDescriptors=[...m.internalEventDescriptors,...t.internalEvents]);const g=m.provide({actions:s.actions,actors:s.actors,guards:s.guards,delays:s.delays});return g._json=t,g},t.machineToJSON=function(t){const e=t._json;return e?Zn(e):ir(t.config)},t.machineVersions=function(t,e){const s=new Map,n=new Map,r=t[0].id;for(const e of t){if(void 0===e.version)throw new Error(`Machine '${e.id}' must define a version.`);if("*"===e.version)throw new Error("Machine version '*' is reserved for wildcard migrations.");if(e.id!==r)throw new Error(`Machine '${e.id}' does not match machine ID '${r}'.`);const t=`${e.id}\0${e.version}`;if(s.has(t))throw new Error(`Duplicate machine identity '${e.id}' version '${e.version}'.`);s.set(t,e),Or(e)&&n.set(t,e)}if(void 0!==e?.unversioned&&!s.has(`${r}\0${e.unversioned}`))throw new Error(`Unversioned snapshot version '${e.unversioned}' is not retained for machine '${r}'.`);const o=async t=>{if(!jr(t))throw new Error("Persisted snapshot is missing machine identity.");let n,o;if(jr(t.machine)){if(({id:n,version:o}=t.machine),"string"!=typeof n||"string"!=typeof o)throw new Error("Persisted snapshot has an invalid machine identity.")}else if("string"==typeof t.version)n=r,o=t.version;else{if(void 0!==t.version||void 0===e?.unversioned)throw new Error("Persisted snapshot is missing machine identity.");n=r,o=e.unversioned}if(void 0!==t.version&&"string"!=typeof t.version)throw new Error("Persisted snapshot has an invalid version.");if(void 0!==t.version&&t.version!==o)throw new Error(`Persisted snapshot version '${t.version}' conflicts with machine version '${o}'.`);const i=s.get(`${n}\0${o}`);if(!i)throw new Error(`Unknown machine identity '${n}' version '${o}'.`);const a=Or(c=i)?$r(c):c.snapshotSchema;var c;if(!a)throw new Error(`Machine version '${o}' does not define a snapshot schema.`);const u=await Ir(a,t,`snapshot for machine '${n}' version '${o}'`);return{source:i,...Or(i)&&{machine:i},snapshot:{...u,machine:{id:n,version:o}}}};return{parseSnapshot:o,async adaptEvents(t,e){const o=n.get(`${r}\0${e.to}`);if(!o)throw new Error(`Target version '${e.to}' is not backed by a machine for '${r}'.`);const i=e.from.id??r,a=s.get(`${i}\0${e.from.version}`);let c,u=!1;const d=a&&(Or(h=a)?Ar(h):h.eventSchema);var h;const f=!!a&&!!d;if(a&&d){let s;try{s=await Mr(t,0,d)}catch(t){c=t,u=!0}if(s){if(a===o)return s;const t=e.adapters[a.version];if(t)return Mr(await t(s),0,Ar(o))}}const p=e.adapters["*"];if(p)return Mr(await p(t,e.from),0,Ar(o));if(f){if(u)throw c instanceof Error?c:new Error(`Unable to validate event history for machine '${a.id}' version '${a.version}'.`,{cause:c});throw new Error(`No event adapter from version '${a.version}' to '${o.version}' for machine '${o.id}'.`)}if(a)throw new Error(`Machine version '${a.version}' does not define an event schema; only the '*' adapter can handle its event history.`);throw new Error(`Unknown event history source '${i}' version '${e.from.version}'.`)},async migrateSnapshot(t,e){const s=n.get(`${r}\0${e.to}`);if(!s)throw new Error(`Target version '${e.to}' is not backed by a machine for '${r}'.`);let i,a;try{i=await o(t)}catch(t){a=t}if(i){if(i.source.version===s.version)return Tr(i.snapshot,s);const t=e.migrations[i.source.version];if(t)return Tr(await t(i.snapshot),s)}const c=e.migrations["*"];if(!c){if(i)throw new Error(`No snapshot migration from version '${i.source.version}' to '${s.version}' for machine '${s.id}'.`);throw a}const u=await c(t,function(t){return jr(t)&&jr(t.machine)?{id:"string"==typeof t.machine.id?t.machine.id:void 0,version:"string"==typeof t.machine.version?t.machine.version:void 0}:{}}(t));return Tr(u,s)}}},t.mapState=function(t,e){const s=[],n=(t,e)=>{let s=t;for(const t of e){if(!s?.states)return;const e=s.states;if(!(t in e))return;s=e[t]}return s},r=new Set;for(const o of t.nodes.filter(De)){let i=o;for(;i&&!r.has(i);){r.add(i);const o=n(e,i.path);o?.map&&s.push({stateNode:i,result:o.map(t)}),i=i.parent}}return s},t.matchesState=Ws,t.runStep=j,t.setup=Pr,t.stopActor=M,t.systemTransition=function(t,e,s,n){const r=new Yr(t,e);return r.send(s,n),[r.result(),r.effects]},t.terminateActor=T,t.toPromise=function(t){return new Promise((e,s)=>{t.subscribe({complete:()=>{e(t.getSnapshot().output)},error:s})})},t.transition=function(t,e,s){const n=Pe(t,e);Se(n,e,!1);const[r,o]=Qt(n,e,t.transition(e,s,n));Se(n,r,!1);const i=r===e?r:$e(n,r);return to(n,i,s),[i,o]},t.types=function(){return{"~standard":{version:1,vendor:"xstate.types",validate:t=>({value:t})}}},t.waitFor=function(t,s,n){const r={...so,...n};return new Promise((n,o)=>{const{signal:i}=r;if(i?.aborted)return void o(i.reason);let a=!1;const c=r.timeout===1/0?void 0:setTimeout(()=>{u(),o(new Error(e(75,r.timeout)))},r.timeout),u=()=>{clearTimeout(c),a=!0,f?.unsubscribe(),h&&i.removeEventListener("abort",h)};function d(t){s(t)&&(u(),n(t))}let h,f;d(t.getSnapshot()),a||(i&&(h=()=>{u(),o(i.reason)},i.addEventListener("abort",h)),f=t.subscribe({next:d,error:t=>{u(),o(t)},complete:()=>{u(),o(new Error(e(76)))}}),a&&f.unsubscribe())})},Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate.umd.min.js.map