xstate 6.0.0-alpha.25 → 6.0.0-alpha.26
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.
- package/dist/{StateMachine-b20d5a53.cjs.js → StateMachine-1a51a14a.cjs.js} +2 -0
- package/dist/{StateMachine-bf4ec0f1.development.esm.js → StateMachine-70bbb88f.development.esm.js} +2 -0
- package/dist/{StateMachine-ac1167f3.development.cjs.js → StateMachine-89f725ff.development.cjs.js} +2 -0
- package/dist/{StateMachine-69278d2c.esm.js → StateMachine-bfbf8d6e.esm.js} +2 -0
- package/dist/declarations/src/StateNode.d.ts +2 -0
- package/dist/declarations/src/schema.types.d.ts +5 -0
- package/dist/declarations/src/setup.d.ts +9 -8
- package/dist/declarations/src/types.v6.d.ts +6 -4
- package/dist/xstate-graph.cjs.js +1 -1
- package/dist/xstate-graph.development.cjs.js +1 -1
- package/dist/xstate-graph.development.esm.js +1 -1
- package/dist/xstate-graph.esm.js +1 -1
- package/dist/xstate-graph.umd.min.js +1 -1
- package/dist/xstate-graph.umd.min.js.map +1 -1
- package/dist/xstate.cjs.js +34 -1
- package/dist/xstate.development.cjs.js +34 -1
- package/dist/xstate.development.esm.js +35 -2
- package/dist/xstate.esm.js +35 -2
- package/dist/xstate.umd.min.js +1 -1
- package/dist/xstate.umd.min.js.map +1 -1
- 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).XStateGraph={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="@xstate.init",n="@xstate.spawn",o="@xstate.stop",r="@xstate.terminate",i="xstate.timer";function c(t,e){return{type:"xstate.after",delay:t,stateId:e}}function a(t,e){return`xstate.after.${t}.${e}`}function u(t){return`xstate.timeout.${t}`}function h(t,e){return{type:"xstate.timeout.actor",actorId:t,sessionId:e}}function f(t){return`xstate.timeout.actor.${t}`}function d(t,e){return{type:"xstate.done.state",stateId:t,output:e}}function l(t,e){return{type:`xstate.error.${t}`,error:e}}function p(t){return{type:s,input:t}}function y(t){setTimeout(()=>{throw t})}const g="function"==typeof Symbol&&Symbol.observable||"@@observable";function v(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}const m={"@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,s.id,s?.delay??0),"@xstate.sendTo":(t,e,s,n)=>(v(s),void 0!==n?.delay?t.system.scheduleTimer(t.self,n.id,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)},_=new WeakMap;function x(t){const e=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{start:(e,{self:s,system:n})=>{const o=e.input.actor;if(!o||"stopped"===o.getSnapshot().status)return;const r=t(e.input,{self:s,system:n});if(!r)return;let i,c=!1;const a=()=>{c||(c=!0,r.unsubscribe(),i?.unsubscribe())},u=s._parent;u&&(i=u.subscribe({complete:a,error:a})),_.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===o?(_.get(s)?.unsubscribe(),_.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:e,getInitialSnapshot:(t,s)=>e(s)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function S(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function b(){return x(({actor:t,eventType:e,mapper:s},{self:n,system:o})=>{const r="*"!==e&&e.endsWith(".*");return t.on(r?"*":e,t=>{r&&!le(t.type,e)||S(n,o,()=>s(t))})})}const w=b();function I(){return x(({actor:t,mappers:e},{self:s,system:n})=>{const{done:o,error:r,snapshot:i}=e;return t.subscribe({next:t=>{"done"===t.status&&o?S(s,n,()=>o(t.output)):"error"===t.status&&r?S(s,n,()=>r(t.error)):"active"===t.status&&i&&S(s,n,()=>i(t))},error:t=>{r&&S(s,n,()=>r(t))},complete:()=>{}})})}const E=I();function k(){return this.action?.(...this.args)}function T(t=this.source.system){return t.emitEvent(this.source,this.event)}function A(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function $(t=this.actor.system){return t.spawnActor(this.source,this.actor)}function j(t=this.actor.system){return t.startActor(this.actor)}function O(t=this.source.system){return t.stopActor(this.actor)}function M(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 P(t=this.source.system){return t.scheduleTimer(this.source,this.id,this.delay??0)}function N(t=this.source.system){return v(this.event),void 0!==this.delay?t.scheduleTimer(this.source,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function R(t=this.source.system){return t.cancelTimer(this.source,this.id)}function z(t,e,s){if(!F(e))return t;if("@xstate.cancel"===e.type){if(!t.timers?.[e.id])return t;const s={...t.timers};return delete s[e.id],{...t,timers:s}}if("@xstate.raise"!==e.type&&"@xstate.sendTo"!==e.type||void 0===e.delay)return t;let n=t._nextTimerId??0;const o=e.id??"xstate.timer.auto."+n++;e.id=o;const r="@xstate.raise"===e.type||e.target===s.self?"self":e.target;return{...t,timers:{...t.timers,[o]:{id:o,delay:e.delay,type:e.type,event:e.event,target:r}},_nextTimerId:n}}function D(t,e){return{...t,...e}}function J(t,e,...s){const n={action:e,args:s};return t.push(n),n}function K(t,e,s){if("add"===e.type)return{...t,children:{...t.children,[e.id]:e.actor}};const n={...t.children};let o=e.actor._parent===s.self;for(const t of Object.keys(n))n[t]===e.actor&&(o=!0,delete n[t]);if(!o)throw new Error(`Cannot stop non-child actor ${e.actor.id}`);return s.system._unregister(e.actor),{...t,children:n}}function V(t){if("object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action)return t}function W(t,e,s,n=!1,o=!0){const r={cancel:s=>{J(e,m["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{J(e,t.logger,...s)},raise:(n,o)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0!==o?.delay?J(e,m["@xstate.raise"],t,n,o):s.push(n)},spawn:(s,n)=>{if(!o)return{id:n?.id??n?.registryKey??s.id};const r=t.system.createActorRef(s,{...n,parent:t.self});return function(t,e,s){J(t,m["@xstate.spawn"],e).childUpdate={type:"add",actor:e,id:s??e.id}}(e,r,n?.id),r},sendTo:(n,o,r)=>{n?J(e,m["@xstate.sendTo"],t,n,o,r):s.push(l("communication",{message:"Unable to send event to an undefined actor",event:o}))},stop:s=>{if(s){J(e,m["@xstate.stop"],t,s).childUpdate={type:"remove",actor:s}}}};return n&&Object.assign(r,{listen:(s,n,o)=>{const r={actor:s,eventType:n,mapper:o},i=t.system.createActorRef(w,{input:r,parent:t.self});return J(e,m["@xstate.spawn"],i),i},subscribeTo:(s,n)=>{const o={actor:s,mappers:"function"==typeof n?{snapshot:n}:n},r=t.system.createActorRef(E,{input:o,parent:t.self});return J(e,m["@xstate.spawn"],r),r}}),H(r,(t,...s)=>{J(e,t,...s)})}function U(t,e){switch(t){case m["@xstate.spawn"]:{const[t]=e;return{kind:"builtin",exec:$,source:t._parent,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case m["@xstate.raise"]:{const[,t,s]=e;return{kind:"builtin",exec:P,source:e[0].self,event:t,id:s?.id,delay:s?.delay}}case m["@xstate.sendTo"]:{const[,t,s,n]=e;return{kind:"builtin",exec:N,source:e[0].self,target:t,event:s,id:n?.id,delay:n?.delay}}case m["@xstate.cancel"]:{const[,t]=e;return{kind:"builtin",exec:R,source:e[0].self,id:t}}case m["@xstate.stop"]:{const[,t]=e;return{kind:"builtin",exec:O,source:e[0].self,actor:t,id:t.id}}default:return}}function B(t){const e=[t];return{kind:"builtin",exec:j,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function C(t,e,s){const n=[t,e,s,{}];return{kind:"builtin",exec:N,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:n}}function L(t,e){if("done"!==e.status&&"error"!==e.status)throw new Error("Cannot terminate an active or stopped actor");const s="done"===e.status?{status:"done",output:e.output,error:void 0}:{status:"error",output:void 0,error:e.error},n=[t.self,s];return{kind:"builtin",exec:M,type:r,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:n}}function q(t,e,[s,n]){const o="done"===s.status||"error"===s.status,i="done"===e?.status||"error"===e?.status,c=n.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===r);return!o||i||c?[s,n]:[s,[...n,L(t,s)]]}function F(t){return"builtin"===t.kind}function G(t,e,s,n){let o=t;const r=[];for(const i of n){const n={context:o.context,event:e,output:re(e),self:s.self,system:s.system,children:o.children,parent:s.self._parent,actions:t.machine.sources.actions,actors:t.machine.sources.actors},c="function"==typeof i,a=V(i),u=c?i:!!a&&a.action.bind(null,...a.args);let h;if("object"==typeof i&&null!==i){const{type:t,childUpdate:e,...s}=i;h=s}if(a?.childUpdate&&(o=K(o,a.childUpdate,s)),u&&"_special"in u){r.push({kind:"action",exec:k,type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type??"(anonymous)":i.name||"(anonymous)",params:h,args:[],action:void 0});const t=u(n,X);t&&("context"in t||"children"in t)&&(o={...o,...void 0!==t.context?{context:D(o.context,t.context)}:{},..."children"in t?{children:t.children}:{}});continue}if(!u||!("resolve"in u)){const t="object"==typeof i&&null!==i&&"action"in i&&"function"==typeof i.action?U(i.action,i.args):void 0,e="object"==typeof i&&null!==i&&!a,n={kind:t?"builtin":e?"emit":"action",type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type:i.name||"(anonymous)",params:t?void 0:h,args:"object"==typeof i&&"action"in i?i.args:[],...t?{}:e?{source:s.self,event:i}:{action:a?.action??(c?i:void 0)},...t?{}:{exec:e?T:k},...t};o=z(o,n,s),r.push(n);continue}}return[o,r]}function H(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),s}const X=H({},()=>{});function Q(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const n=e.match(/^(\d*)(\.?)(\d*)s$/i);if(n){const t=n[1]?parseInt(n[1],10):0,e=!!n[2],s=n[3]?parseInt(n[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:r,days:i,hours:c,minutes:a,seconds:u}=o.groups;if(!(r||i||c||a||u))return;const h=t=>t?Number(t.replace(",",".")):0;return 7*h(r)*24*60*60*1e3+24*h(i)*60*60*1e3+60*h(c)*60*1e3+60*h(a)*1e3+1e3*h(u)}(t)??t}function Y(t,e,s){if("function"==typeof t)return t(s);const n=Q(t,e);return"function"==typeof n?n(s):n}function Z(t,e){return t._stateInputs?.[e]}function tt(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function et(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function st(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 nt(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 et(t))if(!e.has(s)){const t=pt(s);for(const s of t)e.add(s)}}else for(const s of pt(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 ot(t,e){const s=nt(e),n=new Map;for(const t of s)n.has(t)||n.set(t,[]),t.parent&&(n.has(t.parent)||n.set(t.parent,[]),n.get(t.parent).push(t));const o=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(tt(t))return t.key}const s={};for(const t of e)s[t.key]=o(t);return s};return o(t)}function rt(t,e){return"compound"===e.type?et(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?et(e).every(e=>rt(t,e)):"final"===e.type}const it=t=>"#"===t[0];function ct(t){const e=function(t){switch(t.type){case"xstate.done.actor":case"xstate.error.actor":return`${t.type}.${t.actorId}`;case"xstate.snapshot.actor":return`xstate.snapshot.${t.actorId}`;case"xstate.done.state":return`xstate.done.state.${t.stateId}`;case"xstate.after":return`xstate.after.${t.delay}.${t.stateId}`;case"xstate.timeout":return`xstate.timeout.${t.stateId}`;case"xstate.timeout.actor":return`xstate.timeout.actor.${t.actorId}`;default:return}}(t);return e?[t.type,e]:[t.type]}function at(t,e,s){return!e.children[s]||!("sessionId"in t)||e.children[s]?.sessionId===t.sessionId}function ut(t,e,s,n){const o=t.entry;t.entry=(t,r)=>(r.raise(s(t),{id:e,delay:n(t)}),"function"==typeof o?o(t,r):void 0);const r=t.exit;t.exit=(t,s)=>(s.cancel(e),"function"==typeof r?r(t,s):void 0)}function ht(t,e,s){const n=ae(s.target),o=s.reenter??!1,r=ft(t,n),i={...s,target:r,source:t,reenter:o,eventType:e,toJSON:()=>({...i,source:`#${t.id}`,target:r?r.map(t=>`#${t.id}`):void 0})};return i}function ft(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(it(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return gt(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return gt(t.parent,n)}catch(e){throw new Error(`Invalid transition for '${t.id}': ${e.message}`)}})}function dt(t){const e=ae(t.config.target);return e?{target:e.map(e=>"string"==typeof e?gt(t.parent,e):e),source:t,reenter:!1,eventType:""}:"parallel"===t.parent.type?{target:[t.parent],source:t,reenter:!1,eventType:""}:t.parent.initial}function lt(t){return"history"===t.type}function pt(t){const e=new Set;!function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of et(s))t(e)}(t);for(const s of e)for(const n of st(s,t))e.add(n);return e}function yt(t,e){if(it(e))return t.machine.getStateNodeById(e);const s=t.states?.[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function gt(t,e){if("string"==typeof e&&it(e))try{return t.machine.getStateNodeById(e)}catch{}const s=te(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=yt(n,t)}return n}function vt(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=new Array(s.length),o=[t.machine.root,t];for(let e=0;e<s.length;e++){const r=yt(t,s[e]);n[e]=r,o.push(r)}for(let t=0;t<s.length;t++)o.push(...vt(n[t],e[s[t]]));return o}function mt(t,e,s,n,o){if("string"==typeof e){const r=yt(t,e).next(s,n,o);return r&&r.length?r:t.next(s,n,o)}const r=Object.keys(e),i=r[0];if(1===r.length){const r=mt(yt(t,i),e[i],s,n,o);return r&&r.length?r:t.next(s,n,o)}const c=[];for(const i of r){const r=e[i];if(!r)continue;const a=mt(yt(t,i),r,s,n,o);a&&c.push(...a)}return c.length?c:t.next(s,n,o)}function _t(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function xt(t,e){for(const s of t)if(_t(s,e))return!0;return!1}function St(t,e){const s=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,n=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==s&&void 0!==n&&n<s&&([t,e]=[e,t]);const o=t instanceof Set?t:new Set(t);for(const t of e)if(o.has(t))return!0;return!1}function bt(t,e,s,n,o){const r=new Set,i=new Map,c=t=>{let r=i.get(t);return r||(r=kt([t],e,s,n,o),i.set(t,r)),r};for(const e of t){let t=!1;const s=new Set;for(const n of r)if(St(c(e),c(n)))if(_t(e.source,n.source))s.add(n);else{if("final"!==n.source.type||"final"===e.source.type){t=!0;break}s.add(n)}if(!t){for(const t of s)r.delete(t);r.add(e)}}return Array.from(r)}function wt(t,e,s,n){const o=e.historyValue,{targets:r}=At(t,e,s,n,{resolveActions:!1});if(!r)return[];const i=new Set;for(const t of r)if(lt(t))if(o[t.id])for(const e of o[t.id])i.add(e);else for(const o of wt(dt(t),e,s,n))i.add(o);else i.add(t);return[...i]}function It(t,e){let s=t;for(;"parallel"===s.type;){const t=et(s).find(t=>e.every(e=>e===t||_t(e,t)));if(!t)break;s=t}return s}function Et(t,e,s,n){const o=wt(t,e,s,n),{reenter:r}=At(t,e,s,n,{resolveActions:!1});if(o.every(e=>e===t.source||_t(e,t.source)))return r?t.source:It(t.source,o);const[i,...c]=o.concat(t.source);for(const t of st(i,void 0))if(c.every(e=>_t(e,t)))return r?t:It(t,o);return r?void 0:It(t.source.machine.root,o)}function kt(t,e,s,n,o){const r=new Set;for(const i of t){const{targets:t,reenter:c}=At(i,s,n,o,{resolveActions:!1});if(t?.length){const t=Et(i,s,n,o);c&&i.source===t&&r.add(t);for(const s of e)_t(s,t)&&r.add(s)}}return[...r]}function Tt(t,e,s,n,o,r){const i=[];if(!t.length)return[e,i];{const c=new Set(e._nodes);let a=e.historyValue;const u=e.context,h=bt(t,c,e,n,s),f=t=>At(t,e,n,s),l=(t,o,r,i)=>{if(2===t.length){const c=[],a=[];let u;const h=W(s,c,a,!0),f=t({context:o,event:n,parent:s.self._parent,self:s.self,children:r,system:s.system,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:i},h);return void 0!==f?.context&&(u=D(o,f.context)),[c,u,a]}return[[Object.assign((e,s)=>t({...e,input:i},s),"_special"in t?{_special:!0}:{})],void 0,void 0]};let p=e;const y=(t,e)=>{const n=[],o=W(s,n,[]);for(const s of t.invoke){const t=e[s.id];t&&o.stop(t)}return n},g=()=>{const t=kt(h,c,e,n,s);let o;t.sort((t,e)=>e.order-t.order);const u=[...c];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>tt(t)&&_t(t,e):t=>t.parent===e;o??={...a},o[t.id]=u.filter(s)}for(const o of t){const t=Z(e,o.id),[a,u,h]=o.exit?l(o.exit,p.context,e.children,t):[[],void 0,void 0];h?.length&&r.push(...h),u&&(p=Xt(p,{context:u}));const[f,d]=G(p,n,s,a);p=f,i.push(...d);const g=y(o,p.children);if(g.length){const[t,e]=G(p,n,s,g);p=t,i.push(...e)}c.delete(o)}a=o||a};o||g();let v=p.context;const _=[],x=[];for(const t of h){t.actions&&_.push(...ne(t.actions));const e=f(t);void 0!==e.context&&(v=D(v,e.context)),e.actions&&_.push(...e.actions),e.internalEvents&&x.push(...e.internalEvents)}x.length&&r.push(...x);const S=()=>{const t=t=>{const e=p.machine.root;let o;if(void 0!==t.output&&t.parent){const i=r.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);o=i&&t.parent===e?i.output:oe(t.output,p.context,n,s.self,_[t.id])}else if("parallel"===t.type){const e=r.find(e=>"xstate.done.state"===e.type&&e.stateId===t.id);o=e?.output}return void 0===e.output?t.parent===e?o:void 0:oe(e.output,p.context,d(t.id,o),s.self)},u=new Set,y=new Set,g=(t,e)=>{for(const s of t)if(e&&!_t(s,e)||u.add(s),"parallel"===s.type)for(const t of et(s))xt(u,t)||(u.add(t),v(t))},v=t=>{if(lt(t))if(a[t.id]){const e=a[t.id];for(const t of e)u.add(t),v(t);for(const s of e)g(st(s,t.parent),void 0)}else{const e=dt(t),{targets:s}=f(e);for(const n of s??[])u.add(n),e===t.parent?.initial&&y.add(t.parent),v(n);for(const e of s??[])g(st(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=f(t.initial).targets;return lt(e)||(u.add(e),y.add(e)),v(e),void g(st(e,t),void 0)}if("parallel"===t.type)for(const e of et(t))xt(u,e)||(u.add(e),y.add(e),v(e))}};for(const t of h){const o=Et(t,e,n,s),{targets:r,reenter:i}=At(t,e,n,s,{resolveActions:!1});for(const e of r??[])lt(e)||t.source===e&&t.source===o&&!i||(u.add(e),y.add(e)),v(e);const c=wt(t,e,n,s);for(const e of c){const s=st(e,o);"parallel"===o?.type&&s.push(o),g(s,!t.source.parent&&i?void 0:o)}i&&o===t.source&&u.add(t.source)}o&&y.add(e.machine.root);const _={...e._stateInputs};let x=!1;for(const t of h){const{targets:o,input:r}=At(t,e,n,s,{resolveActions:!1});if(r&&o)for(const t of o)_[t.id]=r,x=!0}const S=new Set,b={...p.children};for(const o of[...u].sort((t,e)=>t.order-e.order)){c.add(o);const a=[];let u=!1;for(const t of o.invoke){u=!0;let o=t.logic;"function"==typeof o&&(o=o({actors:e.machine.sources.actors,context:p.context,event:n,self:s.self}));const r="string"==typeof o?he(e.machine,o):o;if(!r)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented`);const i="function"==typeof t.input?t.input({self:s.self,context:p.context,event:n,output:re(n)}):t.input,c=s.system.createActorRef(r,{...t,input:i,parent:s.self,syncSnapshot:!!t.onSnapshot});a.push({action:m["@xstate.spawn"],args:[c]}),t.id&&(b[t.id]=c)}u&&(p=Xt(p,{children:b}));let h=p.context,f=!1;const g=_[o.id];if(o.entry){const[t,e,s]=l(o.entry,h,b,g);a.push(...t),s?.length&&r.push(...s),e&&(h=e,f=!0)}if(f&&(p.context=h),y.has(o)){const{actions:t,input:e}=At(o.initial,p,n,s);if(t&&a.push(...t),e&&o.initial?.target)for(const t of o.initial.target)_[t.id]=e,x=!0}const[v,w]=G(p,n,s,a);if(p=v,a.length=0,i.push(...w),"final"!==o.type)continue;const I=o.parent;let E="parallel"===I?.type?I:I?.parent,k=E||o;for("compound"===I?.type&&r.push(d(I.id,void 0!==o.output?oe(o.output,p.context,n,s.self,g):void 0));"parallel"===E?.type&&!S.has(E)&&rt(c,E);){S.add(E);const t={};for(const e of et(E)){if("final"===e.type){t[e.key]=void 0!==e.output?oe(e.output,p.context,n,s.self,_[e.id]):void 0;continue}if("parallel"===e.type){const s=r.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);t[e.key]=s?.output;continue}const o=et(e).find(t=>"final"===t.type&&c.has(t));t[e.key]=void 0!==o?.output?oe(o.output,p.context,n,s.self,_[o.id]):void 0}r.push(d(E.id,t)),k=E,E=E.parent}E||(p=Xt(p,{status:"done",output:t(k)}))}x&&(p=Xt(p,{_stateInputs:_}))},[b,w]=G(p,n,s,_);p=b,i.push(...w),v&&v!==e.context&&(p=Xt(p,{context:v})),S();const I=[...c];if("done"===p.status){const t=[];I.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=Z(p,e.id),[n,,o]=l(e.exit,p.context,p.children,s);t.push(...n),o?.length&&r.push(...o)}});const[e,o]=G(p,n,s,t);p=e,i.push(...o);const[c,a]=Mt(p,n,s);p=c,i.push(...a);const[u,h]=Pt(p,n,s);p=u,i.push(...h)}return a===e.historyValue&&e._nodes.length===c.size&&e._nodes.every(t=>c.has(t))?p.context!==u?[Xt(p),i]:[p,i]:[Xt(p,{_nodes:I,historyValue:a}),i]}}function At(t,e,s,n,o){const r={context:e.context,event:s,output:re(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:Z(e,t.source.id)};if(t.to){const i=[],c=[],a=W(n,i,c,!1,o?.resolveActions??!0),u=t.to(r,a),h=u?.target?ft(t.source,ne(u.target)):void 0,f=u?.input??("function"==typeof t.input?t.input({context:e.context,event:s,output:re(s)}):t.input);return{targets:h,context:u?.context,reenter:u?.reenter,actions:i,internalEvents:c,input:f}}const i="function"==typeof t.input?t.input({context:e.context,event:s,output:re(s)}):t.input,c="function"==typeof t.context?t.context(r):t.context;return{targets:t.target,context:c,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:i}}function $t(t,e,r,c,a=[]){let u=t;const h=a.slice();function f(t){if("xstate.done.actor"!==t.type&&"xstate.error.actor"!==t.type)return;const{actorId:e,sessionId:s}=t;if(!e)return;const n=u.children[e];if(!n||n.sessionId!==s)return;const o={...u.children};if(delete o[e],r.system._unregister(n),u=Xt(u,{children:o}),h.length){const[,t]=h.at(-1);h[h.length-1]=[u,t]}else h.push([u,[]])}function d(){const e=function(t){const e=[],s=[];for(const o of t){if(!F(o)||o.type!==n)continue;const{actor:t,logic:r}=o,i=B(t);r===w||r===E?e.push(i):s.push(i)}return[...e,...s]}(h.flatMap(([,t])=>t)),s=("active"===t.status||a.length>0)&&("done"===u.status||"error"===u.status);if(e.length||s){const t=s?[...e,L(r,u)]:e;if(h.length){const[e,s]=h.at(-1);h[h.length-1]=[e,[...s,...t]]}else h.push([u,t])}return{snapshot:u,microsteps:h}}function l(t,e){const s=r.self._collectedMicrosteps||[];s.push(...e),r.self._collectedMicrosteps=s,h.push(t)}if(e.type===o){const[t,s]=Mt(u,e,r),[n,o]=Pt(t,e,r);return u=Xt(n,{status:"stopped"}),l([u,[...s,...o]],[]),d()}let p=function(t,e){if("xstate.done.actor"===t.type||"xstate.error.actor"===t.type||"xstate.snapshot.actor"===t.type||"xstate.done.state"===t.type||"xstate.after"===t.type||"xstate.timeout"===t.type||"xstate.timeout.actor"===t.type)return t;const s=(e,s,n)=>t.type.startsWith(e)?{...t,type:s,[n]:t[n]??t.type.slice(e.length)}:void 0,n=s("xstate.done.actor.","xstate.done.actor","actorId")??s("xstate.error.actor.","xstate.error.actor","actorId")??s("xstate.snapshot.","xstate.snapshot.actor","actorId")??s("xstate.done.state.","xstate.done.state","stateId")??s("xstate.timeout.actor.","xstate.timeout.actor","actorId")??s("xstate.timeout.","xstate.timeout","stateId");if(n)return n;const o="xstate.after.";if(!t.type.startsWith(o))return t;const r=[...e.idMap.keys()].sort((t,e)=>e.length-t.length).find(e=>t.type.endsWith(`.${e}`));if(!r)return t;const i=t.type.slice(13,-r.length-1);return{...t,type:"xstate.after",delay:Number.isNaN(+i)?i:+i,stateId:r}}(e,t.machine);if(e.type===i){const t=u.timers[e.id];if(!t)return d();const s={...u.timers};if(delete s[t.id],u=Xt(u,{timers:s}),"@xstate.raise"===t.type)c.push(t.event),l([u,[]],[]);else{const e="self"===t.target?r.self:t.target;l([u,[C(r,e,t.event)]],[])}}if(p.type!==s&&p.type!==i){const e=p,s=function(t){return t.type.startsWith("xstate.error.")}(e),n=u.machine.getTransitionData(u,e,r.self);if(s&&!n.length)return"xstate.error.actor"!==e.type||at(e,u,e.actorId)?(u=Xt(t,{status:"error",error:e.error}),l([u,[]],[]),f(e),d()):d();const o=Tt(n,t,r,p,!1,c);u=o[0],l(o,n),f(e)}let y=!0;const g=t.machine.options?.maxIterations??1/0;let v=0,m=0;for(;"active"===u.status;){if(m++,m>1e3)throw new Error("Microstep count exceeded 1000");if(v++,v>g)throw new Error(`Infinite loop detected (>${g} microsteps)`);let t=y?Nt(u,p,r):[];const e=t.length?u:void 0;if(!t.length){if(!c.length)break;p=c.shift(),t=u.machine.getTransitionData(u,p,r.self)}const s=Tt(t,u,r,p,!1,c);u=s[0],y=u!==e,l(s,t),f(p)}return d()}function jt(t,e,s,n,o){return!!t.to&&Ot(t.to,e,s,n,o,n.machine.sources,t.source.id)}function Ot(t,e,s,n,o,r,i){let c,a=!1;try{const u=()=>{throw a=!0,new Error("Effect triggered")};c=t({context:e,event:s,output:re(s),self:o,system:o.system,value:n.value,children:n.children,parent:{send:u},actions:r.actions,actors:r.actors,guards:r.guards,delays:r.delays,input:Z(n,i)},H({emit:u,cancel:u,log:u,raise:u,spawn:u,sendTo:u,stop:u},u))}catch(t){if(a)return!0;throw t}return void 0!==c}function Mt(t,e,s){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return[t,[]];const o=[],r=W(s,o,[]);for(const t of n)r.stop(t);return G(t,e,s,o)}function Pt(t,e,s){const n=Object.keys(t.timers);if(!n.length)return[t,[]];const o=[],r=W(s,o,[]);for(const t of n)r.cancel(t);return G(t,e,s,o)}function Nt(t,e,s){const n=new Set,o=t._nodes.filter(tt);for(const r of o)t:for(let o=r;o;o=o.parent)if(o.always)for(const r of o.always)if(Rt(r,e,t,o,s.self)){n.add(r);break t}return bt(Array.from(n),new Set(t._nodes),t,e,s)}function Rt(t,e,s,n,o){if(t.matches&&!de(e,t.matches))return!1;if(t._eventMatcher&&!t._eventMatcher(e,s))return!1;if(t.guard){const r={context:s.context,event:e,output:re(e),self:o,parent:o._parent,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};if(!t.guard(r))return!1}return!t.to||Ot(t.to,s.context,e,s,o,n.machine.sources,t.source.id)}const zt=Symbol("xstate.snapshotActorRef");function Dt(t,e,s,n){const o=new Map(n?.children??t.children),r=new Map(n?.keyedActors??Object.entries(t.getAll()).filter(t=>!!t[1])),i=new WeakMap,c={...t,children:o,keyedActors:r,reverseKeyedActors:i,_snapshot:{...n?.snapshot??t._snapshot},_register:(t,e)=>(o.set(t,e),t),_unregister:t=>{t.sessionId&&o.delete(t.sessionId);const e=i.get(t);void 0!==e&&r.get(e)===t&&r.delete(e),i.delete(t)},_set:(t,e)=>{const s=r.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${String(t)}' already exists.`);r.set(t,e),i.set(e,t)},get:t=>r.get(t),getAll:()=>Object.fromEntries(r),_sendInspectionEvent:()=>{}};for(const[t,e]of r)i.set(e,t);for(const t of Object.values(s)){if(!t)continue;t.sessionId&&o.set(t.sessionId,t);const e=t.registryKey;e&&(r.set(e,t),i.set(t,e))}return c}function Jt(t){return t[zt]}function Kt(t,e){const s=Jt(t);s&&Object.defineProperty(e,zt,{configurable:!0,value:s})}function Vt(t,e,s=e.system){const n=Dt(s,0,function(t){return"children"in t&&t.children?t.children:{}}(t));Object.defineProperty(t,zt,{configurable:!0,value:{actor:e,systemState:{children:n.children,keyedActors:n.keyedActors,snapshot:n._snapshot}}})}function Wt(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const Ut=function(t){return Zt(t,this.value)},Bt=function(t){return this.tags.has(t)},Ct=function(t){return this.machine?._canTransition(this,t)??!1},Lt=function(){const{_nodes:t,_stateInputs:e,[zt]:s,tags:n,machine:o,getMeta:r,getInputs:i,toJSON:c,can:a,hasTag:u,matches:h,...f}=this;return{...f,tags:Array.from(n)}},qt=function(){const t={};for(const e of this._nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},Ft=function(){return this._stateInputs};function Gt(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function Ht(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??ot(e.root,t._nodes),tags:Gt(t._nodes),children:t.children,timers:t.timers??{},historyValue:t.historyValue||{},_stateInputs:t._stateInputs||{},_nextTimerId:t._nextTimerId??0,matches:Ut,hasTag:Bt,can:Ct,getMeta:qt,getInputs:Ft,toJSON:Lt};return s&&Vt(n,s),n}function Xt(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:s.children,timers:s.timers??{},historyValue:s.historyValue||{},_stateInputs:s._stateInputs||{},_nextTimerId:s._nextTimerId??0,matches:Ut,hasTag:Bt,can:Ct,getMeta:qt,getInputs:Ft,toJSON:Lt};return Kt(t,e),e}const n=Ht({...s,value:void 0},t.machine);return Kt(t,n),n}function Qt(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 Yt(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:me,id:n.id};else{const o=Yt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function Zt(t,e){const s=ee(t),n=ee(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&Zt(s[t],n[t]))}function te(t){if(ie(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function ee(t){if(Wt(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}(te(t))}function se(t){return ie(t)?t:[t]}function ne(t){return void 0===t?[]:se(t)}function oe(t,e,s,n,o){if("function"==typeof t){return t({context:e,event:s,output:re(s),self:n,input:o})}return t}function re(t){if(function(t){return"xstate.done.actor"===t.type||"xstate.done.state"===t.type}(t)){return t.output}}function ie(t){return Array.isArray(t)}function ce(t){return se(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function ae(t){if(void 0!==t&&""!==t)return ne(t)}function ue(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function he(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.sources.actors[e];const[,n,o]=s,r=t.getStateNodeById(o).config.invoke,i=(Array.isArray(r)?r[n]:r).src;return"string"==typeof i?t.sources.actors[i]:i}function fe(t){const e=t._nodes.flatMap(e=>[...e.transitions.values()].flatMap(e=>e.map(e=>{const s={type:e.eventType,...e.matches};return!("actorId"in s)||"xstate.done.actor"!==s.type&&"xstate.error.actor"!==s.type&&"xstate.snapshot.actor"!==s.type&&"xstate.timeout.actor"!==s.type||(s.sessionId=t.children[s.actorId]?.sessionId),s})));return e.filter((t,s)=>e.findIndex(e=>{const s=Object.keys(t);return s.length===Object.keys(e).length&&s.every(s=>Object.is(t[s],e[s]))})===s)}function de(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}function le(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}let pe=0;function ye(){let t;try{t=globalThis.crypto}catch{}if(t?.randomUUID)try{return t.randomUUID()}catch{}if(t?.getRandomValues)try{const e=new Uint32Array(4);return t.getRandomValues(e),Array.from(e,t=>t.toString(36)).join("-")}catch{}return`xstate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${pe++}`}function ge(t,e){return`${t.sessionId}.${e}`}let ve=!1;const me=1;let _e=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const xe={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)};function Se(t,e){try{t?.(e)}catch(t){y(t)}}function be(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}class we{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=this._process.bind(this),this.mailbox=new e(this._boundProcess),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=_e.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=[],this._collectedActions=[],this._collectedSent=[],this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this.system=void 0,this.trigger=void 0,this.src=void 0,this._deferred=[],this._restored=!1;const n={...xe,...s},{clock:o,logger:r,parent:c,syncSnapshot:a,id:u,registryKey:h,inspect:f}=n;var d;this.system=c?c.system:n._systemRef?.current??function(t,e){const s=new Map,n=new Map,o=new WeakMap,r=new Set,c={},{clock:a,logger:u}=e,h=(t,e,s,n,o)=>{r.size&&t&&(t._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:o})},f={schedule:(t,e,s)=>{const n=ge(t,e);void 0!==c[n]&&f.cancel(t,e);const o=t.getSnapshot()?.timers?.[e];if(o){const n="self"===o.target?t:o.target;h(t,n,o.event,s,e)}const r=Date.now(),u={source:t,delay:s,id:e,scheduledAt:r,dueAt:r+s},p=ge(t,e);l._snapshot._scheduledTimers[p]=u;const y=a.setTimeout(()=>{delete c[p],delete l._snapshot._scheduledTimers[p],d(t,t,{type:i,id:e})},s);c[p]=y},cancel:(t,e)=>{const s=ge(t,e),n=c[s];delete c[s],delete l._snapshot._scheduledTimers[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in l._snapshot._scheduledTimers){const s=l._snapshot._scheduledTimers[e];s.source===t&&f.cancel(t,s.id)}}},d=(t,e,s)=>{const n=e.logic;if("function"==typeof n?.isInternalEventType&&n.isInternalEventType(s.type)&&t!==e)throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`);e._lastSourceRef=t,e._send(s)},l={children:s,reverseKeyedActors:o,keyedActors:n,_identity:{systemId:ye(),nextSessionId:0},_snapshot:{_scheduledTimers:(e?.snapshot&&e.snapshot.scheduler)??{},_nextActorId:e?.snapshot?._nextActorId??0},_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=o.get(t);void 0!==e&&(n.get(e)===t&&n.delete(e),o.delete(t))},get:t=>n.get(t),getAll:()=>Object.fromEntries(n.entries()),_set:(t,e)=>{const s=n.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${t}' already exists.`);n.set(t,e),o.set(e,t)},inspect:t=>{const e=ue(t);return r.add(e),{unsubscribe(){r.delete(e)}}},_sendInspectionEvent:e=>{if(!r.size)return;const s={...e,rootId:t.sessionId};r.forEach(t=>t.next?.(s))},createActorRef:e.createActorRef,spawnActor:()=>{},startActor:t=>{t.start()},stopActor:t=>{t._stop()},terminateActor:(t,e)=>{t._terminate(e)},sendEvent:(t,e,s)=>{h(t,e,s),d(t,e,s)},emitEvent:(t,e)=>t._emit(e),scheduleTimer:(t,e,s)=>f.schedule(t,e,s),cancelTimer:(t,e)=>f.cancel(t,e),cancelAllTimers:t=>f.cancelAll(t),_relay:(t,e,s)=>l.sendEvent(t,e,s),scheduler:f,getSnapshot:()=>({_scheduledTimers:{...l._snapshot._scheduledTimers}}),start:()=>{const t=l._snapshot._scheduledTimers;l._snapshot._scheduledTimers={};for(const e in t){const{source:s,dueAt:n,id:o}=t[e];l.scheduleTimer(s,o,Math.max(0,n-Date.now()))}},_clock:a,_logger:u};return l}(this,{clock:o,logger:r,snapshot:n.snapshot??n.state,createActorRef:(t,e)=>Ie(t,e)}),c||!n._systemRef||n._systemRef.current||(n._systemRef.current=this.system),f&&!c&&this.system.inspect(ue(f)),this.sessionId=n._sessionId??`${(d=this.system)._identity.systemId}:${d._identity.nextSessionId++}`,this.id=function(t,e){if(void 0!==e){const s=/^x:(\d+)$/.exec(e),n=s?Number(s[1]):void 0;return void 0!==n&&Number.isSafeInteger(n)&&(t._snapshot._nextActorId=Math.max(t._snapshot._nextActorId,n+1)),e}return"x:"+t._snapshot._nextActorId++}(this.system,u),this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=c,this._syncSnapshot=a,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop non-child actor ${t.id}`);t._stop()},emit:t=>this.system.emitEvent(this,t),actionExecutor:t=>{const e=()=>{this._collectedActions.push({type:t.type,params:t.params});const e=ve;try{ve=!0,t.exec()}finally{ve=e}};this._processingStatus!==_e.Running||this._forceDeferredActions?this._deferred.push(e):e()}},this.send=this.send.bind(this),this.trigger=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}}),h&&(this.registryKey=h,this.system._set(h,this)),this._collectedMicrosteps=[];const l=s?.snapshot??s?.state;this._restored=void 0!==l;try{if(l)this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(l,this._actorScope):l);else if(s?._inert);else{const[t,e]=q(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e}}catch(t){this._setSnapshot({status:"error",output:void 0,error:t}),this._deferred.length=0}h&&"active"!==this._snapshot.status&&this.system._unregister(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_setSnapshot(t){this._snapshot=t,Vt(t,this)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e){this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t))}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,n]=q(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),be(n,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers)Se(e.next,t)}update(t,e){this._setSnapshot(t);for(let e=0;e<this._deferred.length;e++){const s=this._deferred[e];try{s()}catch(e){if(this._deferred.length=0,this._tryHandleExecutionError(e,t))return;this._setErrorSnapshot(e,t),this._error(e);break}}if(this._deferred.length=0,"active"===this._snapshot.status)this._next(t);this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps,actions:this._collectedActions,sent:this._collectedSent,eventType:e.type}),this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[]}_flushInitialEffects(){if(!this._initialEffects)return!0;this._forceDeferredActions=!0;try{return be(this._initialEffects,this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred.length=0,this._recoverOrError(t),"active"===this._snapshot.status}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const n=ue(t,e,s);if(this._processingStatus!==_e.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":Se(n.complete);break;case"error":{const t=this._snapshot.error;n.error?Se(n.error,t):y(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);return s||(s=new Set,this.eventListeners.set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,o)=>{const r=ue(s,n,o);let i=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(i,n)||(i=n,r.next?.(n))},error:r.error,complete:r.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===_e.Running)return this;if(this._processingStatus===_e.Stopped)return this;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=_e.Running;const t=p(this.options.input);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,t),this):this;case"error":return this._error(this._snapshot.error),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.update(this._snapshot,t),this._restored){const t=this._snapshot.timers??{};for(const e of Object.values(t))this.system.scheduleTimer(this,e.id,e.delay);this._restored=!1}return this.mailbox.start(),this}_process(t){let e,s;try{e=q(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){s={err:t}}if(s)return void this._recoverOrError(s.err);let n=this._snapshot;try{const[s,o]=e;n=s,this._setSnapshot(n),be(o,this._actorScope),this.update(n,t)}catch(t){return void this._recoverOrError(t,n)}t.type===o&&(this._stopProcedure(),this._complete())}_emit(t){for(const e of[this.eventListeners.get(t.type),this.eventListeners.get("*")])if(e)for(const s of e)Se(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,(e=this.id,s=t.output,n=this.sessionId,{type:"xstate.done.actor",output:s,actorId:e,sessionId:n})));var e,s,n;"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===_e.Stopped?this:(this.mailbox.clear(),this._processingStatus===_e.NotStarted?(this._processingStatus=_e.Stopped,this.system._unregister(this),this):(this.mailbox.enqueue({type:o}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)Se(t.complete);this.observers.clear(),this.eventListeners.clear()}_error(t){if(this._stopProcedure(),this.observers.size){let e=!1;for(const s of this.observers){const n=s.error;e||=!n,Se(n,t)}this.observers.clear(),e&&y(t)}else this._parent||y(t);var e,s,n;this.eventListeners.clear(),this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t,n=this.sessionId,{type:"xstate.error.actor",error:s,actorId:e,sessionId:n}))}_stopProcedure(){this._processingStatus===_e.Running&&(this.system.cancelAllTimers(this),this.mailbox.clear(),this.mailbox=new e(this._boundProcess),this._processingStatus=_e.Stopped,this.system._unregister(this))}_send(t){this._processingStatus!==_e.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$$type:me,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[g](){return this}getSnapshot(){return this._snapshot}}function Ie(t,e){return new we(t,e)}const Ee=new WeakMap;function ke(t,e,s){const n=function(t){let e=Ee.get(t);return e||(e=new Map,Ee.set(t,e)),e}(t);if(void 0!==e&&n.has(e))return;const o=s();n.set(e??Symbol(),{cleanup:"function"==typeof o?o:void 0})}function Te(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===o)return[{...e,status:"stopped",input:void 0},[A("xstate.logic.cleanup",()=>function(t){const e=Ee.get(t);if(e){for(const{cleanup:t}of e.values())t?.();Ee.delete(t)}}(n.self))]];if("xstate.logic.effect.start"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if("xstate.logic.effect.resolve"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if("xstate.logic.effect.reject"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const r=[],i={},c={emit:t=>{r.push(function(t,e){return{kind:"emit",exec:T,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&r.push(C(n,e,t))},raise:t=>{r.push(C(n,n.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{e.effects?.[t]||(r.push(A("xstate.logic.effect",(e=n.self.system)=>ke(n.self,t,()=>s(e)),{key:t})),i[t]={status:"active"})})(t,s);const o=t;r.push(A("xstate.logic.effect",(t=n.self.system)=>ke(n.self,void 0,()=>o(t))))}},a=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},c),u={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(u.context=a?.context??e.context),(a?.effects||Object.keys(i).length)&&(u.effects={...e.effects,...a?.effects,...i}),q(n,e,[u,r])},s={id:t.id,config:t,transition:e,start:(t,s,n)=>{if(!n?.restored)return;const[o,r]=e(t,p(t.input),s);Object.assign(t,o);for(const t of r)s.actionExecutor(t)},initialTransition:(s,n)=>{const o=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,s),r={status:"active",output:void 0,error:void 0,input:s};return void 0!==o&&(r.context=o),e({...r},p(s),n)},getInitialSnapshot:(t,e)=>s.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return s}const Ae=Te({context:void 0,run:()=>{}});function $e(t,e,s=!0){return t.self._snapshot=e,s&&e&&"object"==typeof e&&Vt(e,t.self),e}function je(t,e,s){return $e(Oe(t,s,e.self),s)}function Oe(t,e,s){const n=e?Jt(e):void 0,o=s??n?.actor,r=o?.system,i=o&&r?Dt(r,0,Wt(e)?e.children:{},s?void 0:n?.systemState):void 0,c=Ie(t,{_inert:!0,...o?{id:o.id,_sessionId:o.sessionId}:{},...i?{_systemRef:{current:i}}:{}});o?._parent&&(c._parent=o._parent),e&&(c._snapshot=e);return{self:c,defer:()=>{},id:c.id,logger:c.system._logger,sessionId:c.sessionId,stopChild:t=>t._stop(),system:c.system,emit:t=>c.system.emitEvent(c,t),actionExecutor:()=>{}}}const Me=new WeakMap;function Pe(t,e,s){let n=Me.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Me.set(t,n)),n[e]}const Ne={};class Re{constructor(t,e){this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.invoke=void 0,this.on=void 0,this.after=void 0,this.events=void 0,this.ownEvents=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[];const s=this.config.states?Object.keys(this.config.states)[0]:void 0;if(this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(void 0!==s?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,function(t){const e=t.config;if("choice"!==t.type)return;if("function"!=typeof e.choice)throw new Error(`Missing \`choice\` function on "${t.id}"`)}(this),this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const r=n[o];s[r]=e(t[r],r,t,o)}return s}(this.config.states,(t,e)=>new Re(t,{_parent:this,_key:e,_machine:this.machine})):Ne,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}".`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.entry&&(this.entry._special=!0),this.exit&&(this.exit._special=!0),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=ne(t.tags).slice(),this.invoke=ne(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,o=(r=this.id,`${e}.${r}`);var r;const i=t.id??o,c="string"==typeof s?s:`xstate.invoke.${o}`;return{...t,src:c,logic:s,id:i,registryKey:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,o=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===o.length)return[];const r=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;r.push({event:c(n,t.id),timerId:a(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0})}var i;void 0!==s&&n&&r.push({event:(i=t.id,{type:"xstate.timeout",stateId:i}),timerId:u(t.id),delay:s,transitions:n,fromDelaysMap:!0});for(const t of o)r.push({event:h(t.id),timerId:f(t.id),resolveEvent:({children:e})=>h(t.id,e[t.id]?.sessionId),eventMatcher:(e,s)=>at(e,s,t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1});const d=[];for(const{event:e,timerId:s,resolveEvent:n,eventMatcher:o,delay:i,transitions:c,fromDelaysMap:a}of r){ut(t,s,n??(()=>e),e=>Y(i,a?e.delays:{},{context:e.context,event:e.event,stateNode:t,input:e.input}));const{type:r,...u}=e;for(const t of ce(c))d.push({...t,matches:{...t.matches,...Object.fromEntries(Object.entries(u).filter(([,t])=>void 0!==t))},event:r,delay:i,_eventMatcher:o})}return d.map(e=>({...ht(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map,s=(t,s)=>{e.set(t,[...e.get(t)??[],...s])};if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error("Null event transition key");const n=t.config.on[s];e.set(s,ze(n,e=>ht(t,s,e)))}if(t.config.onDone){const e="xstate.done.state";s(e,ze(t.config.onDone,s=>ht(t,e,{...s,matches:{...s.matches,stateId:t.id}})))}if(t.config.onError){const s="xstate.error.*";e.set(s,ze(t.config.onError,e=>ht(t,s,e)))}const n=(e,s,n)=>ht(t,e,{matches:{actorId:n},_eventMatcher:(t,e)=>at(t,e,n),to:(t,e)=>(e.cancel(s),{})}),o=(e,s,n)=>{const{target:o,to:r,reenter:i,...c}=s;return ht(t,e,{...c,reenter:i,to:(t,e)=>{if(r){let s=!1;const o=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const o=Reflect.get(t,e,n);return"function"!=typeof o?o:(...e)=>(s=!0,o.apply(t,e))}}),i=r(t,o);return(void 0!==i||s)&&e.cancel(n),i}return e.cancel(n),{target:o,reenter:i}}})};for(const e of t.invoke){const r=t=>({...t,matches:{...t.matches,actorId:e.id},_eventMatcher:(t,s)=>at(t,s,e.id)}),i=void 0!==e.timeout?f(e.id):void 0;if(e.onDone){const c="xstate.done.actor",a=ze(e.onDone,e=>{const s=r(e);return i?o(c,s,i):ht(t,c,s)});i&&a.push(n(c,i,e.id)),s(c,a)}else if(i){const t="xstate.done.actor";s(t,[n(t,i,e.id)])}if(e.onError){const n="xstate.error.actor";s(n,ze(e.onError,e=>{const s=r(e);return i?o(n,s,i):ht(t,n,s)}))}if(e.onSnapshot){const n="xstate.snapshot.actor";s(n,ze(e.onSnapshot,e=>ht(t,n,r(e))))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),"choice"===this.type?this.always=function(t){const e=t.config.choice,s=e=>{if(!e||void 0===e.target)throw new Error(`Choice "${t.id}" has no target`);return e};return[ht(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=ze(this.config.always,t=>ht(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 Pe(this,"initial",()=>function(t,e){const s="object"==typeof e&&null!==e?e.target:e,n="object"==typeof e&&null!==e?e.input:void 0,o="string"==typeof s?t.states[s]:void 0;if(!o&&s)throw new Error(`Initial state "${s}" not found on "#${t.id}"`);return{source:t,target:o?[o]:void 0,input:n}}(this,this.config.initial))}next(t,e,s){const n=Pe(this,`candidates-${function(t){return ct(t).join("|")}(e)}`,()=>function(t,e){const s=ct(e),n=s.flatMap(e=>t.transitions.get(e)??[]),o=[...t.transitions.keys()].filter(t=>!s.includes(t)&&s.some(e=>le(e,t))).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return n.length?[...n,...o]:o}(this,e));for(const o of n){if(Rt(o,e,t,this,s))return[o]}}}function ze(t,e){const s=ce(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}let De,Je;function Ke(){return De??=Ie({transition:t=>[t,[]],initialTransition:()=>[{status:"active",output:void 0,error:void 0},[]],getInitialSnapshot:()=>({status:"active",output:void 0,error:void 0}),getPersistedSnapshot:t=>t})}class Ve{constructor(t,e){this.config=t,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._json=void 0,this.id=t.id||"(machine)",this.sources={actors:t.actors??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...e},this.version=this.config.version,this.schemas=this.config.schemas,this.internalEventDescriptors=this.config.internalEvents??[],this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.initialTransition=this.initialTransition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new Re(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const o=n.config.id,r=n.config.route,i=({event:t})=>t.to===`#${o}`;if("function"==typeof r)return e.push(ht(t,"xstate.route",{guard:i,to:t=>{const e=r(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(n.states&&s(n.states));const{guard:c,...a}=r,u={...a,guard:i,target:`#${o}`};e.push(ht(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.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.sources,r=new Ve(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}});return r._json=this._json,r}resolveState(t){const e=(s=this.root,n=t.value,ot(s,nt(vt(s,n))));var s,n;const o=nt(vt(this.root,e));return Ht({_nodes:[...o],value:e,context:t.context||{},children:{},status:rt(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const n=!s,o=s??Oe(this,t);n&&$e(o,t,!1);const r=this._transitionFast(t,e,o);if(r){n&&$e(o,r,!1);return[n&&r!==t?je(this,o,r):this._attachPureActorRef(r,o),[]]}const{snapshot:i,microsteps:c}=$t(t,e,o,[]);n&&$e(o,i,!1);return[n?i===t?i:je(this,o,i):this._attachPureActorRef(i,o),this._collectEffects(c)]}_collectEffects(t){return t.flatMap(([,t])=>t)}_attachPureActorRef(t,e){return function(t){return!!t.self.options?._inert}(e)?t:je(this,e,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 o=n.transitions.get(e.type);if(1!==o?.length)return;const r=o[0];if(r.guard||r.actions||r.to||r.reenter||r.input||"function"==typeof r.context||r.target&&1!==r.target.length)return;const i=r.target?.[0]??n,c=i!==n;if(i.parent!==this.root||"atomic"!==i.type||c&&(i.entry||i.invoke.length||i.always?.length||i.after?.length))return;const a=void 0!==r.context?{...t.context,...r.context}:t.context,u=s.self._collectedMicrosteps||[];return u.push(r),s.self._collectedMicrosteps=u,Xt(t,{...a!==t.context?{context:a}:{},...c?{_nodes:[this.root,i]}:{}})}microstep(t,e,s){const{microsteps:n}=$t(t,e,s,[]),o=new Array(n.length);for(let t=0;t<n.length;t++)o[t]=n[t][0];return o}getTransitionData(t,e,s){return mt(this.root,t.value,t,e,s)||[]}isInternalEventType(t){if(t===i)return!0;for(const e of this.internalEventDescriptors)if(le(t,e))return!0;return!1}_canTransition(t,e){const s=Ke(),n=function(){if(Je)return Je;const t=Ke();return Je={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},Je}(),o=this.getTransitionData(t,e,s);if(!o?.length)return!1;for(const r of o){if(void 0!==r.target)return!0;const o=At(r,t,e,n,{resolveActions:!1});if(o.targets?.length||o.context||jt(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 l("execution",e)}_getPreInitialState(t,e){const{context:s}=this.config,n=Ht({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this,t.self);if("function"==typeof s){const o={},r=function(t,e,s){return(n,o)=>{const r=Object.entries(e).find(([,t])=>t===n)?.[0],i=t.system.createActorRef(n,{id:o?.id,parent:t.self,syncSnapshot:o?.syncSnapshot,input:o?.input,src:r??n,registryKey:o?.registryKey});return s[i.id]=i,i}}(t,this.sources.actors,o),i=s({spawn:r,input:e.input,self:t.self,actors:this.sources.actors}),[c]=G(n,e,t,[]);return i&&(c.context=i),Object.keys(o).length>0&&(c.children={...c.children,...o}),c}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){const s=!e,o=e??Oe(this),r=p(t),i=[],c=this._getPreInitialState(o,r),a=Object.values(c.children).filter(Boolean).map(t=>function(t){const e=[t];return{kind:"builtin",exec:$,type:n,source:t._parent,params:void 0,args:e,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}(t));let u,h,f=[],d=[];try{[u,f]=function(t,e,s,n,o){return Tt([{target:[...pt(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,c,o,r,i),({snapshot:h,microsteps:d}=$t(u,r,o,i,[[u,[...a,...f]]]))}catch(t){if(!this.root.config.onError)throw t;const e=$t(c,l("execution",t),o,[],[[c,a]]);h=e.snapshot,d=e.microsteps,f=[]}s&&$e(o,h,!1);return[s?je(this,o,h):this._attachPureActorRef(h,o),this._collectEffects(d)]}start(t){if(t?.children)for(const e of Object.values(t.children))e._rehydrated&&"active"===e.getSnapshot?.().status&&e.start()}getStateNodeById(t){const e=te(t),s=e.slice(1),n=it(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return gt(o,s)}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,_stateInputs:n,tags:o,machine:r,children:i,timers:c,context:a,can:u,hasTag:h,matches:f,getMeta:d,getInputs:l,toJSON:p,...y}=t,g={},v={};for(const t in i){const s=i[t];g[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,registryKey:s.registryKey,syncSnapshot:s._syncSnapshot}}for(const e in c){const s=c[e];let n,o=s.event;if("xstate.timeout.actor"===o.type&&(o={...o},delete o.sessionId),"self"===s.target)n="self";else{const o=Object.entries(i).find(([,t])=>t===s.target)?.[0];if(o)n=o;else{if(s.target!==Jt(t)?.actor._parent)throw new Error(`Unable to persist timer '${e}': target actor '${s.target.id}' is no longer addressable from this snapshot.`);n={type:"parent"}}}v[e]={id:s.id,delay:s.delay,type:s.type,event:o,target:n}}const m={...y,_nextActorId:Jt(t)?.systemState.snapshot._nextActorId,context:Yt(a),children:g,timers:v,historyValue:Qt(y.historyValue)};return n&&Object.keys(n).length>0&&(m.stateInputs=n),void 0!==r.version&&(m.version=r.version),m}(t,e)}restoreSnapshot(t,e){const s=!e,n=e??Oe(this),o=t.version;if(o!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${o}' does not match machine version '${this.version}'.`);t=e(t,o)}const r=t,i={},c=r.children;for(const t of Object.keys(c)){const e=c[t],s=e.snapshot,o=e.src,r="string"==typeof o?he(this,o):o;if(!r){throw new Error(`Unable to restore child actor '${t}': child source '${"string"==typeof o?o:"<unknown>"}' is not provided in machine '${this.id}'.`)}const a=n.system.createActorRef(r,{id:t,parent:n.self,syncSnapshot:e.syncSnapshot,snapshot:s,src:o,registryKey:e.registryKey});a._rehydrated=!0,i[t]=a}const a={},u=r.timers??{};for(const[t,e]of Object.entries(u)){let s=e.event;if("xstate.timeout.actor"===s.type){const t=s.actorId,e=i[t];e&&(s=h(t,e.sessionId))}const o="string"==typeof e.target?"self"===e.target?"self":i[e.target]:n.self._parent;if(!o){const s="string"==typeof e.target?e.target:e.target.type;throw new Error(`Unable to restore timer '${t}': target actor '${s}' is unavailable.`)}a[t]={...e,event:s,target:o}}const f=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const s of Object.keys(t)){const n=t[s];for(const t of n){let n;if(t instanceof Re)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(r.historyValue),d=Array.from(nt(vt(this.root,r.value))),{version:l,...p}=t,y=Ht({...p,children:i,timers:a,_nodes:d,value:r.value,historyValue:f,_stateInputs:r.stateInputs??{}},this,n.self),g=new WeakSet;return function t(e){if(!g.has(e)){g.add(e);for(const s of Object.keys(e)){const n=e[s];if(n&&"object"==typeof n){if("xstate$$type"in n&&n.xstate$$type===me){e[s]=i[n.id];continue}t(n)}}}}(y.context),s?($e(n,y,!1),je(this,n,y)):this._attachPureActorRef(y,n)}}function We(t){return JSON.stringify(t)}function Ue(t){const e=Object.keys(t.context).length?`(${JSON.stringify(t.context)})`:"",s=t._nodes.filter(t=>"atomic"===t.type||"final"===t.type).map(({id:e,path:s})=>{const n=t.getMeta()[e];if(!n)return`"${s.join(".")}"`;const{description:o}=n;return"function"==typeof o?o(t):o?`"${o}"`:JSON.stringify(t.value)});return`state${1===s.length?"":"s"} `+s.join(", ")+` ${e}`.trim()}const Be=()=>(t,e)=>is(t,e),Ce=()=>(t,e)=>cs(t,e);class Le{getDefaultOptions(){return{serializeState:t=>We(t),serializeEvent:t=>We(t),serializeTransition:(t,e)=>`${We(t)}|${e?.type}`,events:[],stateMatcher:(t,e)=>"*"===e,logger:{log:console.log.bind(console),error:console.error.bind(console)}}}constructor(t,e){this.testLogic=t,this.options=void 0,this.defaultTraversalOptions=void 0,this._toTestPath=t=>{const e=t.steps.map(t=>function(t){const{type:e,...s}=t;return`${e}${Object.keys(s).length?` (${JSON.stringify(s)})`:""}`}(t.event)).join(" → ");return{...t,test:e=>this.testPath(t,e),description:Wt(t.state)?`Reaches ${Ue(t.state).trim()}: ${e}`:JSON.stringify(t.state)}},this.options={...this.getDefaultOptions(),...e}}getPaths(t,e){const s=e?.allowDuplicatePaths??!1,n=t(this.testLogic,this._resolveOptions(e));return(s?n:((t,e=We)=>{const s=[];t.forEach(t=>{s.push({path:t,eventSequence:t.steps.map(t=>e(t.event))})}),s.sort((t,e)=>e.path.steps.length-t.path.steps.length);const n=[];t:for(const t of s){e:for(const e of n){for(const s in t.eventSequence)if(t.eventSequence[s]!==e.eventSequence[s])continue e;continue t}n.push(t)}return n.map(t=>t.path)})(n)).map(this._toTestPath)}getShortestPaths(t){return this.getPaths(Be(),t)}getShortestPathsFrom(t,e){const s=[];for(const n of t){const t=this.getShortestPaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(es(n,e)))}return s}getSimplePaths(t){return this.getPaths(Ce(),t)}getSimplePathsFrom(t,e){const s=[];for(const n of t){const t=this.getSimplePaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(es(n,e)))}return s}getPathsFromEvents(t,e){return rs(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return ns(this.testLogic,this.options)}async testPath(t,e,s){const n={steps:[],state:{error:null}};try{for(const o of t.steps){const t={step:o,state:{error:null},event:{error:null}};n.steps.push(t);try{await this.testTransition(e,o)}catch(e){throw t.event.error=e,e}try{await this.testState(e,o.state,s)}catch(e){throw t.state.error=e,e}}}catch(e){throw e.message+=function(t,e,s){const n={formatColor:(t,e)=>e,serializeState:We,serializeEvent:We,...s},{formatColor:o,serializeState:r,serializeEvent:i}=n,{state:c}=t,a=r(c,t.steps.length?t.steps[t.steps.length-1].event:void 0);let u="",h=!1;return u+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=r(t.step.state,e>0?s[e-1].step.event:void 0),c=i(t.step.event);return[`\tState: ${h?o("gray",n):t.state.error?(h=!0,o("redBright",n)):o("greenBright",n)}`,`\tEvent: ${h?o("gray",c):t.event.error?(h=!0,o("red",c)):o("green",c)}`].join("\n")}).concat(`\tState: ${h?o("gray",a):e.state.error?o("red",a):o("green",a)}`).join("\n\n"),u}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),o=this._getStateTestKeys(t,e,n);for(const s of o)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},o=Object.keys(n).filter(t=>s.stateMatcher(e,t));return!o.length&&"*"in n&&o.push("*"),o}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function qe(t,e){if(t===e)return!0;if(void 0===t||void 0===e)return!1;if("string"==typeof t||"string"==typeof e)return t===e;const s=Object.keys(t),n=Object.keys(e);return s.length===n.length&&s.every(s=>qe(t[s],e[s]))}function Fe(t,e,s,{serializeEvent:n}){if(!e||s&&qe(s.value,t.value))return"";const o=s?` from ${We(s.value)}`:"";return` via ${n(e)}${o}`}function Ge(){const t=Ie(Ae);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function He(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function Xe(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function Qe(t){return JSON.stringify(t)}function Ye(t,e){const{events:s,...n}=e??{};return{serializeState:Xe,serializeEvent:Qe,events:t=>{const e="function"==typeof s?s(t):s??[];return fe(t).flatMap(t=>{const s=e.filter(e=>de(e,t));return s.length?s:[t]})},fromState:t.getInitialSnapshot(Ge(),e?.input),...n}}function Ze(){return{serializeState:t=>JSON.stringify(t),serializeEvent:Qe}}function ts(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?Ye(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:Qe,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function es(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}}function ss(t){return Array.isArray(t)?t[0]:t}function ns(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:r,filterEvents:i,limit:c,fromState:a,stopWhen:u}=ts(t,e),h=Ge(),f={};let d=0;const l=[{nextState:a??t.getInitialSnapshot(h,e.input),event:void 0,prevState:void 0}],p=new Map;for(;l.length;){const{nextState:t,event:e,prevState:a}=l.shift();if(d++>c)throw new Error("Traversal limit exceeded");const y=o(t,e,a);if(f[y])continue;if(p.set(y,t),f[y]={state:t,transitions:{}},u&&u(t))continue;const g="function"==typeof r?r(t):r;for(const e of g){if(i&&!i(t,e))continue;const o=ss(s(t,e,h));f[y].transitions[n(e)]={event:e,state:o},l.push({nextState:o,event:e,prevState:t})}}return f}function os(t){let e=[];if(t.steps.length){for(let n=0;n<t.steps.length;n++){const o=t.steps[n];e.push({state:o.state,event:0===n?{type:s}:t.steps[n-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:s}}];return{...t,steps:e}}function rs(t,e,s){const n=ts(t,{events:e,...s},(o=t)&&o instanceof Ve?Ye(t):Ze());var o;const r=Ge(),i=n.fromState??t.getInitialSnapshot(r,s?.input),{serializeState:c,serializeEvent:a}=n,u=ns(t,n),h=new Map,f=[],d=c(i,void 0,void 0);h.set(d,i);let l=d,p=i;for(const t of e){f.push({state:h.get(l),event:t});const e=a(t),{state:s,event:n}=u[l].transitions[e];if(!s)throw new Error(`Invalid transition from ${l} with ${e}`);const o=c(s,t,h.get(l));h.set(o,s),l=o,p=s}return n.toState&&!n.toState(p)?[]:[os({state:p,steps:f,weight:f.length})]}function is(t,e){const s=ts(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(Ge(),e?.input),r=ns(t,s),i=new Map,c=new Map,a=n(o,void 0,void 0);c.set(a,o),i.set(a,{weight:0,state:void 0,event:void 0});const u=new Set,h=new Set;u.add(a);for(const t of u){const e=c.get(t),{weight:s}=i.get(t);for(const o of Object.keys(r[t].transitions)){const{state:a,event:f}=r[t].transitions[o],d=n(a,f,e);if(c.set(d,a),i.has(d)){const{weight:e}=i.get(d);e>s+1&&i.set(d,{weight:s+1,state:t,event:f})}else i.set(d,{weight:s+1,state:t,event:f});h.has(d)||u.add(d)}h.add(t),u.delete(t)}const f={},d=[];return i.forEach(({weight:t,state:e,event:s},n)=>{const o=c.get(n),r=e?f[e].paths[0].steps.concat({state:c.get(e),event:s}):[];d.push({state:o,steps:r,weight:t}),f[n]={state:o,paths:[{state:o,steps:r,weight:t}]}}),s.toState?d.filter(t=>s.toState(t.state)).map(os):d.map(os)}function cs(t,e){const s=ts(t,e),n=Ge(),o=s.fromState??t.getInitialSnapshot(n,e?.input),r=s.serializeState,i=ns(t,s),c=new Map,a={vertices:new Set,edges:new Set},u=[],h={};function f(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){h[e]||(h[e]={state:c.get(e),paths:[]});const t=h[e],n={state:s,weight:u.length,steps:[...u]};t.paths.push(n)}else{if(!i[t])return;for(const s of Object.keys(i[t].transitions)){const{state:n,event:o}=i[t].transitions[s];if(!(s in i[t].transitions))continue;const h=c.get(t),d=r(n,o,h);c.set(d,n),a.vertices.has(d)||(a.edges.add(s),u.push({state:c.get(t),event:o}),f(d,e))}}u.pop(),a.vertices.delete(t)}const d=r(o,void 0);c.set(d,o);for(const t of Object.keys(i))f(d,t);const l=Object.values(h).flatMap(t=>t.paths);return s.toState?l.filter(t=>s.toState(t.state)).map(os):l.map(os)}t.TestModel=Le,t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.createShortestPathsGen=Be,t.createSimplePathsGen=Ce,t.createTestModel=function(t,e){(t=>{t.root})(t);const s=e?.serializeEvent??We,n=e?.serializeTransition??Fe,{events:o,...r}=e??{};return new Le(t,{serializeState:(t,e,o)=>`${Xe(t)}${n(t,e,o,{serializeEvent:s})}`,stateMatcher:(e,s)=>s.startsWith("#")?e._nodes.includes(t.getStateNodeById(s)):e.matches(s),events:t=>{const e="function"==typeof o?o(t):o??[];return fe(t).flatMap(t=>e.some(e=>de(e,t))?e.filter(e=>de(e,t)):[t])},...r})},t.getAdjacencyMap=ns,t.getPathsFromEvents=rs,t.getShortestPaths=is,t.getSimplePaths=cs,t.getStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,n)=>{const o=s[n],r=t(o);return e.push(o,...r),e},[])},t.joinPaths=es,t.serializeSnapshot=Xe,t.toDirectedGraph=function t(e){const s=e instanceof Ve?e.root:e,n=[...s.transitions.values()].flat().flatMap((t,e)=>(t.target?t.target:[s]).map((n,o)=>{const r={id:`${s.id}:${e}:${o}`,source:s,target:n,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=r;return{source:s.id,target:n.id,label:t}}};return r})),o={id:s.id,stateNode:s,children:He(s).map(t),edges:n,toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s}}};return o},Object.defineProperty(t,"__esModule",{value:!0})});
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateGraph={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="@xstate.init",n="@xstate.spawn",o="@xstate.stop",r="@xstate.terminate",i="xstate.timer";function c(t,e){return{type:"xstate.after",delay:t,stateId:e}}function a(t,e){return`xstate.after.${t}.${e}`}function u(t){return`xstate.timeout.${t}`}function h(t,e){return{type:"xstate.timeout.actor",actorId:t,sessionId:e}}function f(t){return`xstate.timeout.actor.${t}`}function d(t,e){return{type:"xstate.done.state",stateId:t,output:e}}function l(t,e){return{type:`xstate.error.${t}`,error:e}}function p(t){return{type:s,input:t}}function y(t){setTimeout(()=>{throw t})}const g="function"==typeof Symbol&&Symbol.observable||"@@observable";function v(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}const m={"@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,s.id,s?.delay??0),"@xstate.sendTo":(t,e,s,n)=>(v(s),void 0!==n?.delay?t.system.scheduleTimer(t.self,n.id,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)},_=new WeakMap;function x(t){const e=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{start:(e,{self:s,system:n})=>{const o=e.input.actor;if(!o||"stopped"===o.getSnapshot().status)return;const r=t(e.input,{self:s,system:n});if(!r)return;let i,c=!1;const a=()=>{c||(c=!0,r.unsubscribe(),i?.unsubscribe())},u=s._parent;u&&(i=u.subscribe({complete:a,error:a})),_.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===o?(_.get(s)?.unsubscribe(),_.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:e,getInitialSnapshot:(t,s)=>e(s)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function S(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function b(){return x(({actor:t,eventType:e,mapper:s},{self:n,system:o})=>{const r="*"!==e&&e.endsWith(".*");return t.on(r?"*":e,t=>{r&&!le(t.type,e)||S(n,o,()=>s(t))})})}const w=b();function I(){return x(({actor:t,mappers:e},{self:s,system:n})=>{const{done:o,error:r,snapshot:i}=e;return t.subscribe({next:t=>{"done"===t.status&&o?S(s,n,()=>o(t.output)):"error"===t.status&&r?S(s,n,()=>r(t.error)):"active"===t.status&&i&&S(s,n,()=>i(t))},error:t=>{r&&S(s,n,()=>r(t))},complete:()=>{}})})}const E=I();function k(){return this.action?.(...this.args)}function T(t=this.source.system){return t.emitEvent(this.source,this.event)}function A(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function $(t=this.actor.system){return t.spawnActor(this.source,this.actor)}function j(t=this.actor.system){return t.startActor(this.actor)}function O(t=this.source.system){return t.stopActor(this.actor)}function M(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 P(t=this.source.system){return t.scheduleTimer(this.source,this.id,this.delay??0)}function N(t=this.source.system){return v(this.event),void 0!==this.delay?t.scheduleTimer(this.source,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function R(t=this.source.system){return t.cancelTimer(this.source,this.id)}function z(t,e,s){if(!F(e))return t;if("@xstate.cancel"===e.type){if(!t.timers?.[e.id])return t;const s={...t.timers};return delete s[e.id],{...t,timers:s}}if("@xstate.raise"!==e.type&&"@xstate.sendTo"!==e.type||void 0===e.delay)return t;let n=t._nextTimerId??0;const o=e.id??"xstate.timer.auto."+n++;e.id=o;const r="@xstate.raise"===e.type||e.target===s.self?"self":e.target;return{...t,timers:{...t.timers,[o]:{id:o,delay:e.delay,type:e.type,event:e.event,target:r}},_nextTimerId:n}}function D(t,e){return{...t,...e}}function J(t,e,...s){const n={action:e,args:s};return t.push(n),n}function K(t,e,s){if("add"===e.type)return{...t,children:{...t.children,[e.id]:e.actor}};const n={...t.children};let o=e.actor._parent===s.self;for(const t of Object.keys(n))n[t]===e.actor&&(o=!0,delete n[t]);if(!o)throw new Error(`Cannot stop non-child actor ${e.actor.id}`);return s.system._unregister(e.actor),{...t,children:n}}function V(t){if("object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action)return t}function W(t,e,s,n=!1,o=!0){const r={cancel:s=>{J(e,m["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{J(e,t.logger,...s)},raise:(n,o)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0!==o?.delay?J(e,m["@xstate.raise"],t,n,o):s.push(n)},spawn:(s,n)=>{if(!o)return{id:n?.id??n?.registryKey??s.id};const r=t.system.createActorRef(s,{...n,parent:t.self});return function(t,e,s){J(t,m["@xstate.spawn"],e).childUpdate={type:"add",actor:e,id:s??e.id}}(e,r,n?.id),r},sendTo:(n,o,r)=>{n?J(e,m["@xstate.sendTo"],t,n,o,r):s.push(l("communication",{message:"Unable to send event to an undefined actor",event:o}))},stop:s=>{if(s){J(e,m["@xstate.stop"],t,s).childUpdate={type:"remove",actor:s}}}};return n&&Object.assign(r,{listen:(s,n,o)=>{const r={actor:s,eventType:n,mapper:o},i=t.system.createActorRef(w,{input:r,parent:t.self});return J(e,m["@xstate.spawn"],i),i},subscribeTo:(s,n)=>{const o={actor:s,mappers:"function"==typeof n?{snapshot:n}:n},r=t.system.createActorRef(E,{input:o,parent:t.self});return J(e,m["@xstate.spawn"],r),r}}),H(r,(t,...s)=>{J(e,t,...s)})}function U(t,e){switch(t){case m["@xstate.spawn"]:{const[t]=e;return{kind:"builtin",exec:$,source:t._parent,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case m["@xstate.raise"]:{const[,t,s]=e;return{kind:"builtin",exec:P,source:e[0].self,event:t,id:s?.id,delay:s?.delay}}case m["@xstate.sendTo"]:{const[,t,s,n]=e;return{kind:"builtin",exec:N,source:e[0].self,target:t,event:s,id:n?.id,delay:n?.delay}}case m["@xstate.cancel"]:{const[,t]=e;return{kind:"builtin",exec:R,source:e[0].self,id:t}}case m["@xstate.stop"]:{const[,t]=e;return{kind:"builtin",exec:O,source:e[0].self,actor:t,id:t.id}}default:return}}function B(t){const e=[t];return{kind:"builtin",exec:j,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function C(t,e,s){const n=[t,e,s,{}];return{kind:"builtin",exec:N,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:n}}function L(t,e){if("done"!==e.status&&"error"!==e.status)throw new Error("Cannot terminate an active or stopped actor");const s="done"===e.status?{status:"done",output:e.output,error:void 0}:{status:"error",output:void 0,error:e.error},n=[t.self,s];return{kind:"builtin",exec:M,type:r,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:n}}function q(t,e,[s,n]){const o="done"===s.status||"error"===s.status,i="done"===e?.status||"error"===e?.status,c=n.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===r);return!o||i||c?[s,n]:[s,[...n,L(t,s)]]}function F(t){return"builtin"===t.kind}function G(t,e,s,n){let o=t;const r=[];for(const i of n){const n={context:o.context,event:e,output:re(e),self:s.self,system:s.system,children:o.children,parent:s.self._parent,actions:t.machine.sources.actions,actors:t.machine.sources.actors},c="function"==typeof i,a=V(i),u=c?i:!!a&&a.action.bind(null,...a.args);let h;if("object"==typeof i&&null!==i){const{type:t,childUpdate:e,...s}=i;h=s}if(a?.childUpdate&&(o=K(o,a.childUpdate,s)),u&&"_special"in u){r.push({kind:"action",exec:k,type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type??"(anonymous)":i.name||"(anonymous)",params:h,args:[],action:void 0});const t=u(n,X);t&&("context"in t||"children"in t)&&(o={...o,...void 0!==t.context?{context:D(o.context,t.context)}:{},..."children"in t?{children:t.children}:{}});continue}if(!u||!("resolve"in u)){const t="object"==typeof i&&null!==i&&"action"in i&&"function"==typeof i.action?U(i.action,i.args):void 0,e="object"==typeof i&&null!==i&&!a,n={kind:t?"builtin":e?"emit":"action",type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type:i.name||"(anonymous)",params:t?void 0:h,args:"object"==typeof i&&"action"in i?i.args:[],...t?{}:e?{source:s.self,event:i}:{action:a?.action??(c?i:void 0)},...t?{}:{exec:e?T:k},...t};o=z(o,n,s),r.push(n);continue}}return[o,r]}function H(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),s}const X=H({},()=>{});function Q(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const n=e.match(/^(\d*)(\.?)(\d*)s$/i);if(n){const t=n[1]?parseInt(n[1],10):0,e=!!n[2],s=n[3]?parseInt(n[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:r,days:i,hours:c,minutes:a,seconds:u}=o.groups;if(!(r||i||c||a||u))return;const h=t=>t?Number(t.replace(",",".")):0;return 7*h(r)*24*60*60*1e3+24*h(i)*60*60*1e3+60*h(c)*60*1e3+60*h(a)*1e3+1e3*h(u)}(t)??t}function Y(t,e,s){if("function"==typeof t)return t(s);const n=Q(t,e);return"function"==typeof n?n(s):n}function Z(t,e){return t._stateInputs?.[e]}function tt(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function et(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function st(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 nt(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 et(t))if(!e.has(s)){const t=pt(s);for(const s of t)e.add(s)}}else for(const s of pt(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 ot(t,e){const s=nt(e),n=new Map;for(const t of s)n.has(t)||n.set(t,[]),t.parent&&(n.has(t.parent)||n.set(t.parent,[]),n.get(t.parent).push(t));const o=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(tt(t))return t.key}const s={};for(const t of e)s[t.key]=o(t);return s};return o(t)}function rt(t,e){return"compound"===e.type?et(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?et(e).every(e=>rt(t,e)):"final"===e.type}const it=t=>"#"===t[0];function ct(t){const e=function(t){switch(t.type){case"xstate.done.actor":case"xstate.error.actor":return`${t.type}.${t.actorId}`;case"xstate.snapshot.actor":return`xstate.snapshot.${t.actorId}`;case"xstate.done.state":return`xstate.done.state.${t.stateId}`;case"xstate.after":return`xstate.after.${t.delay}.${t.stateId}`;case"xstate.timeout":return`xstate.timeout.${t.stateId}`;case"xstate.timeout.actor":return`xstate.timeout.actor.${t.actorId}`;default:return}}(t);return e?[t.type,e]:[t.type]}function at(t,e,s){return!e.children[s]||!("sessionId"in t)||e.children[s]?.sessionId===t.sessionId}function ut(t,e,s,n){const o=t.entry;t.entry=(t,r)=>(r.raise(s(t),{id:e,delay:n(t)}),"function"==typeof o?o(t,r):void 0);const r=t.exit;t.exit=(t,s)=>(s.cancel(e),"function"==typeof r?r(t,s):void 0)}function ht(t,e,s){const n=ae(s.target),o=s.reenter??!1,r=ft(t,n),i={...s,target:r,source:t,reenter:o,eventType:e,toJSON:()=>({...i,source:`#${t.id}`,target:r?r.map(t=>`#${t.id}`):void 0})};return i}function ft(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(it(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return gt(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return gt(t.parent,n)}catch(e){throw new Error(`Invalid transition for '${t.id}': ${e.message}`)}})}function dt(t){const e=ae(t.config.target);return e?{target:e.map(e=>"string"==typeof e?gt(t.parent,e):e),source:t,reenter:!1,eventType:""}:"parallel"===t.parent.type?{target:[t.parent],source:t,reenter:!1,eventType:""}:t.parent.initial}function lt(t){return"history"===t.type}function pt(t){const e=new Set;!function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of et(s))t(e)}(t);for(const s of e)for(const n of st(s,t))e.add(n);return e}function yt(t,e){if(it(e))return t.machine.getStateNodeById(e);const s=t.states?.[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function gt(t,e){if("string"==typeof e&&it(e))try{return t.machine.getStateNodeById(e)}catch{}const s=te(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=yt(n,t)}return n}function vt(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=new Array(s.length),o=[t.machine.root,t];for(let e=0;e<s.length;e++){const r=yt(t,s[e]);n[e]=r,o.push(r)}for(let t=0;t<s.length;t++)o.push(...vt(n[t],e[s[t]]));return o}function mt(t,e,s,n,o){if("string"==typeof e){const r=yt(t,e).next(s,n,o);return r&&r.length?r:t.next(s,n,o)}const r=Object.keys(e),i=r[0];if(1===r.length){const r=mt(yt(t,i),e[i],s,n,o);return r&&r.length?r:t.next(s,n,o)}const c=[];for(const i of r){const r=e[i];if(!r)continue;const a=mt(yt(t,i),r,s,n,o);a&&c.push(...a)}return c.length?c:t.next(s,n,o)}function _t(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function xt(t,e){for(const s of t)if(_t(s,e))return!0;return!1}function St(t,e){const s=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,n=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==s&&void 0!==n&&n<s&&([t,e]=[e,t]);const o=t instanceof Set?t:new Set(t);for(const t of e)if(o.has(t))return!0;return!1}function bt(t,e,s,n,o){const r=new Set,i=new Map,c=t=>{let r=i.get(t);return r||(r=kt([t],e,s,n,o),i.set(t,r)),r};for(const e of t){let t=!1;const s=new Set;for(const n of r)if(St(c(e),c(n)))if(_t(e.source,n.source))s.add(n);else{if("final"!==n.source.type||"final"===e.source.type){t=!0;break}s.add(n)}if(!t){for(const t of s)r.delete(t);r.add(e)}}return Array.from(r)}function wt(t,e,s,n){const o=e.historyValue,{targets:r}=At(t,e,s,n,{resolveActions:!1});if(!r)return[];const i=new Set;for(const t of r)if(lt(t))if(o[t.id])for(const e of o[t.id])i.add(e);else for(const o of wt(dt(t),e,s,n))i.add(o);else i.add(t);return[...i]}function It(t,e){let s=t;for(;"parallel"===s.type;){const t=et(s).find(t=>e.every(e=>e===t||_t(e,t)));if(!t)break;s=t}return s}function Et(t,e,s,n){const o=wt(t,e,s,n),{reenter:r}=At(t,e,s,n,{resolveActions:!1});if(o.every(e=>e===t.source||_t(e,t.source)))return r?t.source:It(t.source,o);const[i,...c]=o.concat(t.source);for(const t of st(i,void 0))if(c.every(e=>_t(e,t)))return r?t:It(t,o);return r?void 0:It(t.source.machine.root,o)}function kt(t,e,s,n,o){const r=new Set;for(const i of t){const{targets:t,reenter:c}=At(i,s,n,o,{resolveActions:!1});if(t?.length){const t=Et(i,s,n,o);c&&i.source===t&&r.add(t);for(const s of e)_t(s,t)&&r.add(s)}}return[...r]}function Tt(t,e,s,n,o,r){const i=[];if(!t.length)return[e,i];{const c=new Set(e._nodes);let a=e.historyValue;const u=e.context,h=bt(t,c,e,n,s),f=t=>At(t,e,n,s),l=(t,o,r,i)=>{if(2===t.length){const c=[],a=[];let u;const h=W(s,c,a,!0),f=t({context:o,event:n,parent:s.self._parent,self:s.self,children:r,system:s.system,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:i},h);return void 0!==f?.context&&(u=D(o,f.context)),[c,u,a]}return[[Object.assign((e,s)=>t({...e,input:i},s),"_special"in t?{_special:!0}:{})],void 0,void 0]};let p=e;const y=(t,e)=>{const n=[],o=W(s,n,[]);for(const s of t.invoke){const t=e[s.id];t&&o.stop(t)}return n},g=()=>{const t=kt(h,c,e,n,s);let o;t.sort((t,e)=>e.order-t.order);const u=[...c];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>tt(t)&&_t(t,e):t=>t.parent===e;o??={...a},o[t.id]=u.filter(s)}for(const o of t){const t=Z(e,o.id),[a,u,h]=o.exit?l(o.exit,p.context,e.children,t):[[],void 0,void 0];h?.length&&r.push(...h),u&&(p=Xt(p,{context:u}));const[f,d]=G(p,n,s,a);p=f,i.push(...d);const g=y(o,p.children);if(g.length){const[t,e]=G(p,n,s,g);p=t,i.push(...e)}c.delete(o)}a=o||a};o||g();let v=p.context;const _=[],x=[];for(const t of h){t.actions&&_.push(...ne(t.actions));const e=f(t);void 0!==e.context&&(v=D(v,e.context)),e.actions&&_.push(...e.actions),e.internalEvents&&x.push(...e.internalEvents)}x.length&&r.push(...x);const S=()=>{const t=t=>{const e=p.machine.root;let o;if(void 0!==t.output&&t.parent){const i=r.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);o=i&&t.parent===e?i.output:oe(t.output,p.context,n,s.self,_[t.id])}else if("parallel"===t.type){const e=r.find(e=>"xstate.done.state"===e.type&&e.stateId===t.id);o=e?.output}return void 0===e.output?t.parent===e?o:void 0:oe(e.output,p.context,d(t.id,o),s.self)},u=new Set,y=new Set,g=(t,e)=>{for(const s of t)if(e&&!_t(s,e)||u.add(s),"parallel"===s.type)for(const t of et(s))xt(u,t)||(u.add(t),v(t))},v=t=>{if(lt(t))if(a[t.id]){const e=a[t.id];for(const t of e)u.add(t),v(t);for(const s of e)g(st(s,t.parent),void 0)}else{const e=dt(t),{targets:s}=f(e);for(const n of s??[])u.add(n),e===t.parent?.initial&&y.add(t.parent),v(n);for(const e of s??[])g(st(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=f(t.initial).targets;return lt(e)||(u.add(e),y.add(e)),v(e),void g(st(e,t),void 0)}if("parallel"===t.type)for(const e of et(t))xt(u,e)||(u.add(e),y.add(e),v(e))}};for(const t of h){const o=Et(t,e,n,s),{targets:r,reenter:i}=At(t,e,n,s,{resolveActions:!1});for(const e of r??[])lt(e)||t.source===e&&t.source===o&&!i||(u.add(e),y.add(e)),v(e);const c=wt(t,e,n,s);for(const e of c){const s=st(e,o);"parallel"===o?.type&&s.push(o),g(s,!t.source.parent&&i?void 0:o)}i&&o===t.source&&u.add(t.source)}o&&y.add(e.machine.root);const _={...e._stateInputs};let x=!1;for(const t of h){const{targets:o,input:r}=At(t,e,n,s,{resolveActions:!1});if(r&&o)for(const t of o)_[t.id]=r,x=!0}const S=new Set,b={...p.children};for(const o of[...u].sort((t,e)=>t.order-e.order)){c.add(o);const a=[];let u=!1;for(const t of o.invoke){u=!0;let o=t.logic;"function"==typeof o&&(o=o({actors:e.machine.sources.actors,context:p.context,event:n,self:s.self}));const r="string"==typeof o?he(e.machine,o):o;if(!r)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented`);const i="function"==typeof t.input?t.input({self:s.self,context:p.context,event:n,output:re(n)}):t.input,c=s.system.createActorRef(r,{...t,input:i,parent:s.self,syncSnapshot:!!t.onSnapshot});a.push({action:m["@xstate.spawn"],args:[c]}),t.id&&(b[t.id]=c)}u&&(p=Xt(p,{children:b}));let h=p.context,f=!1;const g=_[o.id];if(o.entry){const[t,e,s]=l(o.entry,h,b,g);a.push(...t),s?.length&&r.push(...s),e&&(h=e,f=!0)}if(f&&(p.context=h),y.has(o)){const{actions:t,input:e}=At(o.initial,p,n,s);if(t&&a.push(...t),e&&o.initial?.target)for(const t of o.initial.target)_[t.id]=e,x=!0}const[v,w]=G(p,n,s,a);if(p=v,a.length=0,i.push(...w),"final"!==o.type)continue;const I=o.parent;let E="parallel"===I?.type?I:I?.parent,k=E||o;for("compound"===I?.type&&r.push(d(I.id,void 0!==o.output?oe(o.output,p.context,n,s.self,g):void 0));"parallel"===E?.type&&!S.has(E)&&rt(c,E);){S.add(E);const t={};for(const e of et(E)){if("final"===e.type){t[e.key]=void 0!==e.output?oe(e.output,p.context,n,s.self,_[e.id]):void 0;continue}if("parallel"===e.type){const s=r.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);t[e.key]=s?.output;continue}const o=et(e).find(t=>"final"===t.type&&c.has(t));t[e.key]=void 0!==o?.output?oe(o.output,p.context,n,s.self,_[o.id]):void 0}r.push(d(E.id,t)),k=E,E=E.parent}E||(p=Xt(p,{status:"done",output:t(k)}))}x&&(p=Xt(p,{_stateInputs:_}))},[b,w]=G(p,n,s,_);p=b,i.push(...w),v&&v!==e.context&&(p=Xt(p,{context:v})),S();const I=[...c];if("done"===p.status){const t=[];I.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=Z(p,e.id),[n,,o]=l(e.exit,p.context,p.children,s);t.push(...n),o?.length&&r.push(...o)}});const[e,o]=G(p,n,s,t);p=e,i.push(...o);const[c,a]=Mt(p,n,s);p=c,i.push(...a);const[u,h]=Pt(p,n,s);p=u,i.push(...h)}return a===e.historyValue&&e._nodes.length===c.size&&e._nodes.every(t=>c.has(t))?p.context!==u?[Xt(p),i]:[p,i]:[Xt(p,{_nodes:I,historyValue:a}),i]}}function At(t,e,s,n,o){const r={context:e.context,event:s,output:re(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:Z(e,t.source.id)};if(t.to){const i=[],c=[],a=W(n,i,c,!1,o?.resolveActions??!0),u=t.to(r,a),h=u?.target?ft(t.source,ne(u.target)):void 0,f=u?.input??("function"==typeof t.input?t.input({context:e.context,event:s,output:re(s)}):t.input);return{targets:h,context:u?.context,reenter:u?.reenter,actions:i,internalEvents:c,input:f}}const i="function"==typeof t.input?t.input({context:e.context,event:s,output:re(s)}):t.input,c="function"==typeof t.context?t.context(r):t.context;return{targets:t.target,context:c,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:i}}function $t(t,e,r,c,a=[]){let u=t;const h=a.slice();function f(t){if("xstate.done.actor"!==t.type&&"xstate.error.actor"!==t.type)return;const{actorId:e,sessionId:s}=t;if(!e)return;const n=u.children[e];if(!n||n.sessionId!==s)return;const o={...u.children};if(delete o[e],r.system._unregister(n),u=Xt(u,{children:o}),h.length){const[,t]=h.at(-1);h[h.length-1]=[u,t]}else h.push([u,[]])}function d(){const e=function(t){const e=[],s=[];for(const o of t){if(!F(o)||o.type!==n)continue;const{actor:t,logic:r}=o,i=B(t);r===w||r===E?e.push(i):s.push(i)}return[...e,...s]}(h.flatMap(([,t])=>t)),s=("active"===t.status||a.length>0)&&("done"===u.status||"error"===u.status);if(e.length||s){const t=s?[...e,L(r,u)]:e;if(h.length){const[e,s]=h.at(-1);h[h.length-1]=[e,[...s,...t]]}else h.push([u,t])}return{snapshot:u,microsteps:h}}function l(t,e){const s=r.self._collectedMicrosteps||[];s.push(...e),r.self._collectedMicrosteps=s,h.push(t)}if(e.type===o){const[t,s]=Mt(u,e,r),[n,o]=Pt(t,e,r);return u=Xt(n,{status:"stopped"}),l([u,[...s,...o]],[]),d()}let p=function(t,e){if("xstate.done.actor"===t.type||"xstate.error.actor"===t.type||"xstate.snapshot.actor"===t.type||"xstate.done.state"===t.type||"xstate.after"===t.type||"xstate.timeout"===t.type||"xstate.timeout.actor"===t.type)return t;const s=(e,s,n)=>t.type.startsWith(e)?{...t,type:s,[n]:t[n]??t.type.slice(e.length)}:void 0,n=s("xstate.done.actor.","xstate.done.actor","actorId")??s("xstate.error.actor.","xstate.error.actor","actorId")??s("xstate.snapshot.","xstate.snapshot.actor","actorId")??s("xstate.done.state.","xstate.done.state","stateId")??s("xstate.timeout.actor.","xstate.timeout.actor","actorId")??s("xstate.timeout.","xstate.timeout","stateId");if(n)return n;const o="xstate.after.";if(!t.type.startsWith(o))return t;const r=[...e.idMap.keys()].sort((t,e)=>e.length-t.length).find(e=>t.type.endsWith(`.${e}`));if(!r)return t;const i=t.type.slice(13,-r.length-1);return{...t,type:"xstate.after",delay:Number.isNaN(+i)?i:+i,stateId:r}}(e,t.machine);if(e.type===i){const t=u.timers[e.id];if(!t)return d();const s={...u.timers};if(delete s[t.id],u=Xt(u,{timers:s}),"@xstate.raise"===t.type)c.push(t.event),l([u,[]],[]);else{const e="self"===t.target?r.self:t.target;l([u,[C(r,e,t.event)]],[])}}if(p.type!==s&&p.type!==i){const e=p,s=function(t){return t.type.startsWith("xstate.error.")}(e),n=u.machine.getTransitionData(u,e,r.self);if(s&&!n.length)return"xstate.error.actor"!==e.type||at(e,u,e.actorId)?(u=Xt(t,{status:"error",error:e.error}),l([u,[]],[]),f(e),d()):d();const o=Tt(n,t,r,p,!1,c);u=o[0],l(o,n),f(e)}let y=!0;const g=t.machine.options?.maxIterations??1/0;let v=0,m=0;for(;"active"===u.status;){if(m++,m>1e3)throw new Error("Microstep count exceeded 1000");if(v++,v>g)throw new Error(`Infinite loop detected (>${g} microsteps)`);let t=y?Nt(u,p,r):[];const e=t.length?u:void 0;if(!t.length){if(!c.length)break;p=c.shift(),t=u.machine.getTransitionData(u,p,r.self)}const s=Tt(t,u,r,p,!1,c);u=s[0],y=u!==e,l(s,t),f(p)}return d()}function jt(t,e,s,n,o){return!!t.to&&Ot(t.to,e,s,n,o,n.machine.sources,t.source.id)}function Ot(t,e,s,n,o,r,i){let c,a=!1;try{const u=()=>{throw a=!0,new Error("Effect triggered")};c=t({context:e,event:s,output:re(s),self:o,system:o.system,value:n.value,children:n.children,parent:{send:u},actions:r.actions,actors:r.actors,guards:r.guards,delays:r.delays,input:Z(n,i)},H({emit:u,cancel:u,log:u,raise:u,spawn:u,sendTo:u,stop:u},u))}catch(t){if(a)return!0;throw t}return void 0!==c}function Mt(t,e,s){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return[t,[]];const o=[],r=W(s,o,[]);for(const t of n)r.stop(t);return G(t,e,s,o)}function Pt(t,e,s){const n=Object.keys(t.timers);if(!n.length)return[t,[]];const o=[],r=W(s,o,[]);for(const t of n)r.cancel(t);return G(t,e,s,o)}function Nt(t,e,s){const n=new Set,o=t._nodes.filter(tt);for(const r of o)t:for(let o=r;o;o=o.parent)if(o.always)for(const r of o.always)if(Rt(r,e,t,o,s.self)){n.add(r);break t}return bt(Array.from(n),new Set(t._nodes),t,e,s)}function Rt(t,e,s,n,o){if(t.matches&&!de(e,t.matches))return!1;if(t._eventMatcher&&!t._eventMatcher(e,s))return!1;if(t.guard){const r={context:s.context,event:e,output:re(e),self:o,parent:o._parent,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};if(!t.guard(r))return!1}return!t.to||Ot(t.to,s.context,e,s,o,n.machine.sources,t.source.id)}const zt=Symbol("xstate.snapshotActorRef");function Dt(t,e,s,n){const o=new Map(n?.children??t.children),r=new Map(n?.keyedActors??Object.entries(t.getAll()).filter(t=>!!t[1])),i=new WeakMap,c={...t,children:o,keyedActors:r,reverseKeyedActors:i,_snapshot:{...n?.snapshot??t._snapshot},_register:(t,e)=>(o.set(t,e),t),_unregister:t=>{t.sessionId&&o.delete(t.sessionId);const e=i.get(t);void 0!==e&&r.get(e)===t&&r.delete(e),i.delete(t)},_set:(t,e)=>{const s=r.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${String(t)}' already exists.`);r.set(t,e),i.set(e,t)},get:t=>r.get(t),getAll:()=>Object.fromEntries(r),_sendInspectionEvent:()=>{}};for(const[t,e]of r)i.set(e,t);for(const t of Object.values(s)){if(!t)continue;t.sessionId&&o.set(t.sessionId,t);const e=t.registryKey;e&&(r.set(e,t),i.set(t,e))}return c}function Jt(t){return t[zt]}function Kt(t,e){const s=Jt(t);s&&Object.defineProperty(e,zt,{configurable:!0,value:s})}function Vt(t,e,s=e.system){const n=Dt(s,0,function(t){return"children"in t&&t.children?t.children:{}}(t));Object.defineProperty(t,zt,{configurable:!0,value:{actor:e,systemState:{children:n.children,keyedActors:n.keyedActors,snapshot:n._snapshot}}})}function Wt(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const Ut=function(t){return Zt(t,this.value)},Bt=function(t){return this.tags.has(t)},Ct=function(t){return this.machine?._canTransition(this,t)??!1},Lt=function(){const{_nodes:t,_stateInputs:e,[zt]:s,tags:n,machine:o,getMeta:r,getInputs:i,toJSON:c,can:a,hasTag:u,matches:h,...f}=this;return{...f,tags:Array.from(n)}},qt=function(){const t={};for(const e of this._nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},Ft=function(){return this._stateInputs};function Gt(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function Ht(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??ot(e.root,t._nodes),tags:Gt(t._nodes),children:t.children,timers:t.timers??{},historyValue:t.historyValue||{},_stateInputs:t._stateInputs||{},_nextTimerId:t._nextTimerId??0,matches:Ut,hasTag:Bt,can:Ct,getMeta:qt,getInputs:Ft,toJSON:Lt};return s&&Vt(n,s),n}function Xt(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:s.children,timers:s.timers??{},historyValue:s.historyValue||{},_stateInputs:s._stateInputs||{},_nextTimerId:s._nextTimerId??0,matches:Ut,hasTag:Bt,can:Ct,getMeta:qt,getInputs:Ft,toJSON:Lt};return Kt(t,e),e}const n=Ht({...s,value:void 0},t.machine);return Kt(t,n),n}function Qt(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 Yt(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:me,id:n.id};else{const o=Yt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function Zt(t,e){const s=ee(t),n=ee(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&Zt(s[t],n[t]))}function te(t){if(ie(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function ee(t){if(Wt(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}(te(t))}function se(t){return ie(t)?t:[t]}function ne(t){return void 0===t?[]:se(t)}function oe(t,e,s,n,o){if("function"==typeof t){return t({context:e,event:s,output:re(s),self:n,input:o})}return t}function re(t){if(function(t){return"xstate.done.actor"===t.type||"xstate.done.state"===t.type}(t)){return t.output}}function ie(t){return Array.isArray(t)}function ce(t){return se(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function ae(t){if(void 0!==t&&""!==t)return ne(t)}function ue(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function he(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.sources.actors[e];const[,n,o]=s,r=t.getStateNodeById(o).config.invoke,i=(Array.isArray(r)?r[n]:r).src;return"string"==typeof i?t.sources.actors[i]:i}function fe(t){const e=t._nodes.flatMap(e=>[...e.transitions.values()].flatMap(e=>e.map(e=>{const s={type:e.eventType,...e.matches};return!("actorId"in s)||"xstate.done.actor"!==s.type&&"xstate.error.actor"!==s.type&&"xstate.snapshot.actor"!==s.type&&"xstate.timeout.actor"!==s.type||(s.sessionId=t.children[s.actorId]?.sessionId),s})));return e.filter((t,s)=>e.findIndex(e=>{const s=Object.keys(t);return s.length===Object.keys(e).length&&s.every(s=>Object.is(t[s],e[s]))})===s)}function de(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}function le(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}let pe=0;function ye(){let t;try{t=globalThis.crypto}catch{}if(t?.randomUUID)try{return t.randomUUID()}catch{}if(t?.getRandomValues)try{const e=new Uint32Array(4);return t.getRandomValues(e),Array.from(e,t=>t.toString(36)).join("-")}catch{}return`xstate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${pe++}`}function ge(t,e){return`${t.sessionId}.${e}`}let ve=!1;const me=1;let _e=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const xe={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)};function Se(t,e){try{t?.(e)}catch(t){y(t)}}function be(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}class we{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=this._process.bind(this),this.mailbox=new e(this._boundProcess),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=_e.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=[],this._collectedActions=[],this._collectedSent=[],this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this.system=void 0,this.trigger=void 0,this.src=void 0,this._deferred=[],this._restored=!1;const n={...xe,...s},{clock:o,logger:r,parent:c,syncSnapshot:a,id:u,registryKey:h,inspect:f}=n;var d;this.system=c?c.system:n._systemRef?.current??function(t,e){const s=new Map,n=new Map,o=new WeakMap,r=new Set,c={},{clock:a,logger:u}=e,h=(t,e,s,n,o)=>{r.size&&t&&(t._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:o})},f={schedule:(t,e,s)=>{const n=ge(t,e);void 0!==c[n]&&f.cancel(t,e);const o=t.getSnapshot()?.timers?.[e];if(o){const n="self"===o.target?t:o.target;h(t,n,o.event,s,e)}const r=Date.now(),u={source:t,delay:s,id:e,scheduledAt:r,dueAt:r+s},p=ge(t,e);l._snapshot._scheduledTimers[p]=u;const y=a.setTimeout(()=>{delete c[p],delete l._snapshot._scheduledTimers[p],d(t,t,{type:i,id:e})},s);c[p]=y},cancel:(t,e)=>{const s=ge(t,e),n=c[s];delete c[s],delete l._snapshot._scheduledTimers[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in l._snapshot._scheduledTimers){const s=l._snapshot._scheduledTimers[e];s.source===t&&f.cancel(t,s.id)}}},d=(t,e,s)=>{const n=e.logic;if("function"==typeof n?.isInternalEventType&&n.isInternalEventType(s.type)&&t!==e)throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`);e._lastSourceRef=t,e._send(s)},l={children:s,reverseKeyedActors:o,keyedActors:n,_identity:{systemId:ye(),nextSessionId:0},_snapshot:{_scheduledTimers:(e?.snapshot&&e.snapshot.scheduler)??{},_nextActorId:e?.snapshot?._nextActorId??0},_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=o.get(t);void 0!==e&&(n.get(e)===t&&n.delete(e),o.delete(t))},get:t=>n.get(t),getAll:()=>Object.fromEntries(n.entries()),_set:(t,e)=>{const s=n.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${t}' already exists.`);n.set(t,e),o.set(e,t)},inspect:t=>{const e=ue(t);return r.add(e),{unsubscribe(){r.delete(e)}}},_sendInspectionEvent:e=>{if(!r.size)return;const s={...e,rootId:t.sessionId};r.forEach(t=>t.next?.(s))},createActorRef:e.createActorRef,spawnActor:()=>{},startActor:t=>{t.start()},stopActor:t=>{t._stop()},terminateActor:(t,e)=>{t._terminate(e)},sendEvent:(t,e,s)=>{h(t,e,s),d(t,e,s)},emitEvent:(t,e)=>t._emit(e),scheduleTimer:(t,e,s)=>f.schedule(t,e,s),cancelTimer:(t,e)=>f.cancel(t,e),cancelAllTimers:t=>f.cancelAll(t),_relay:(t,e,s)=>l.sendEvent(t,e,s),scheduler:f,getSnapshot:()=>({_scheduledTimers:{...l._snapshot._scheduledTimers}}),start:()=>{const t=l._snapshot._scheduledTimers;l._snapshot._scheduledTimers={};for(const e in t){const{source:s,dueAt:n,id:o}=t[e];l.scheduleTimer(s,o,Math.max(0,n-Date.now()))}},_clock:a,_logger:u};return l}(this,{clock:o,logger:r,snapshot:n.snapshot??n.state,createActorRef:(t,e)=>Ie(t,e)}),c||!n._systemRef||n._systemRef.current||(n._systemRef.current=this.system),f&&!c&&this.system.inspect(ue(f)),this.sessionId=n._sessionId??`${(d=this.system)._identity.systemId}:${d._identity.nextSessionId++}`,this.id=function(t,e){if(void 0!==e){const s=/^x:(\d+)$/.exec(e),n=s?Number(s[1]):void 0;return void 0!==n&&Number.isSafeInteger(n)&&(t._snapshot._nextActorId=Math.max(t._snapshot._nextActorId,n+1)),e}return"x:"+t._snapshot._nextActorId++}(this.system,u),this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=c,this._syncSnapshot=a,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop non-child actor ${t.id}`);t._stop()},emit:t=>this.system.emitEvent(this,t),actionExecutor:t=>{const e=()=>{this._collectedActions.push({type:t.type,params:t.params});const e=ve;try{ve=!0,t.exec()}finally{ve=e}};this._processingStatus!==_e.Running||this._forceDeferredActions?this._deferred.push(e):e()}},this.send=this.send.bind(this),this.trigger=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}}),h&&(this.registryKey=h,this.system._set(h,this)),this._collectedMicrosteps=[];const l=s?.snapshot??s?.state;this._restored=void 0!==l;try{if(l)this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(l,this._actorScope):l);else if(s?._inert);else{const[t,e]=q(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e}}catch(t){this._setSnapshot({status:"error",output:void 0,error:t}),this._deferred.length=0}h&&"active"!==this._snapshot.status&&this.system._unregister(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_setSnapshot(t){this._snapshot=t,Vt(t,this)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e){this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t))}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,n]=q(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),be(n,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers)Se(e.next,t)}update(t,e){this._setSnapshot(t);for(let e=0;e<this._deferred.length;e++){const s=this._deferred[e];try{s()}catch(e){if(this._deferred.length=0,this._tryHandleExecutionError(e,t))return;this._setErrorSnapshot(e,t),this._error(e);break}}if(this._deferred.length=0,"active"===this._snapshot.status)this._next(t);this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps,actions:this._collectedActions,sent:this._collectedSent,eventType:e.type}),this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[]}_flushInitialEffects(){if(!this._initialEffects)return!0;this._forceDeferredActions=!0;try{return be(this._initialEffects,this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred.length=0,this._recoverOrError(t),"active"===this._snapshot.status}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const n=ue(t,e,s);if(this._processingStatus!==_e.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":Se(n.complete);break;case"error":{const t=this._snapshot.error;n.error?Se(n.error,t):y(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);return s||(s=new Set,this.eventListeners.set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,o)=>{const r=ue(s,n,o);let i=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(i,n)||(i=n,r.next?.(n))},error:r.error,complete:r.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===_e.Running)return this;if(this._processingStatus===_e.Stopped)return this;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=_e.Running;const t=p(this.options.input);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,t),this):this;case"error":return this._error(this._snapshot.error),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.update(this._snapshot,t),this._restored){const t=this._snapshot.timers??{};for(const e of Object.values(t))this.system.scheduleTimer(this,e.id,e.delay);this._restored=!1}return this.mailbox.start(),this}_process(t){let e,s;try{e=q(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){s={err:t}}if(s)return void this._recoverOrError(s.err);let n=this._snapshot;try{const[s,o]=e;n=s,this._setSnapshot(n),be(o,this._actorScope),this.update(n,t)}catch(t){return void this._recoverOrError(t,n)}t.type===o&&(this._stopProcedure(),this._complete())}_emit(t){for(const e of[this.eventListeners.get(t.type),this.eventListeners.get("*")])if(e)for(const s of e)Se(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,(e=this.id,s=t.output,n=this.sessionId,{type:"xstate.done.actor",output:s,actorId:e,sessionId:n})));var e,s,n;"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===_e.Stopped?this:(this.mailbox.clear(),this._processingStatus===_e.NotStarted?(this._processingStatus=_e.Stopped,this.system._unregister(this),this):(this.mailbox.enqueue({type:o}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)Se(t.complete);this.observers.clear(),this.eventListeners.clear()}_error(t){if(this._stopProcedure(),this.observers.size){let e=!1;for(const s of this.observers){const n=s.error;e||=!n,Se(n,t)}this.observers.clear(),e&&y(t)}else this._parent||y(t);var e,s,n;this.eventListeners.clear(),this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t,n=this.sessionId,{type:"xstate.error.actor",error:s,actorId:e,sessionId:n}))}_stopProcedure(){this._processingStatus===_e.Running&&(this.system.cancelAllTimers(this),this.mailbox.clear(),this.mailbox=new e(this._boundProcess),this._processingStatus=_e.Stopped,this.system._unregister(this))}_send(t){this._processingStatus!==_e.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$$type:me,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[g](){return this}getSnapshot(){return this._snapshot}}function Ie(t,e){return new we(t,e)}const Ee=new WeakMap;function ke(t,e,s){const n=function(t){let e=Ee.get(t);return e||(e=new Map,Ee.set(t,e)),e}(t);if(void 0!==e&&n.has(e))return;const o=s();n.set(e??Symbol(),{cleanup:"function"==typeof o?o:void 0})}function Te(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===o)return[{...e,status:"stopped",input:void 0},[A("xstate.logic.cleanup",()=>function(t){const e=Ee.get(t);if(e){for(const{cleanup:t}of e.values())t?.();Ee.delete(t)}}(n.self))]];if("xstate.logic.effect.start"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if("xstate.logic.effect.resolve"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if("xstate.logic.effect.reject"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const r=[],i={},c={emit:t=>{r.push(function(t,e){return{kind:"emit",exec:T,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&r.push(C(n,e,t))},raise:t=>{r.push(C(n,n.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{e.effects?.[t]||(r.push(A("xstate.logic.effect",(e=n.self.system)=>ke(n.self,t,()=>s(e)),{key:t})),i[t]={status:"active"})})(t,s);const o=t;r.push(A("xstate.logic.effect",(t=n.self.system)=>ke(n.self,void 0,()=>o(t))))}},a=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},c),u={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(u.context=a?.context??e.context),(a?.effects||Object.keys(i).length)&&(u.effects={...e.effects,...a?.effects,...i}),q(n,e,[u,r])},s={id:t.id,config:t,transition:e,start:(t,s,n)=>{if(!n?.restored)return;const[o,r]=e(t,p(t.input),s);Object.assign(t,o);for(const t of r)s.actionExecutor(t)},initialTransition:(s,n)=>{const o=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,s),r={status:"active",output:void 0,error:void 0,input:s};return void 0!==o&&(r.context=o),e({...r},p(s),n)},getInitialSnapshot:(t,e)=>s.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return s}const Ae=Te({context:void 0,run:()=>{}});function $e(t,e,s=!0){return t.self._snapshot=e,s&&e&&"object"==typeof e&&Vt(e,t.self),e}function je(t,e,s){return $e(Oe(t,s,e.self),s)}function Oe(t,e,s){const n=e?Jt(e):void 0,o=s??n?.actor,r=o?.system,i=o&&r?Dt(r,0,Wt(e)?e.children:{},s?void 0:n?.systemState):void 0,c=Ie(t,{_inert:!0,...o?{id:o.id,_sessionId:o.sessionId}:{},...i?{_systemRef:{current:i}}:{}});o?._parent&&(c._parent=o._parent),e&&(c._snapshot=e);return{self:c,defer:()=>{},id:c.id,logger:c.system._logger,sessionId:c.sessionId,stopChild:t=>t._stop(),system:c.system,emit:t=>c.system.emitEvent(c,t),actionExecutor:()=>{}}}const Me=new WeakMap;function Pe(t,e,s){let n=Me.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Me.set(t,n)),n[e]}const Ne={};class Re{constructor(t,e){this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.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.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[];const s=this.config.states?Object.keys(this.config.states)[0]:void 0;if(this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(void 0!==s?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.schemas=this.config.schemas,function(t){const e=t.config;if("choice"!==t.type)return;if("function"!=typeof e.choice)throw new Error(`Missing \`choice\` function on "${t.id}"`)}(this),this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const r=n[o];s[r]=e(t[r],r,t,o)}return s}(this.config.states,(t,e)=>new Re(t,{_parent:this,_key:e,_machine:this.machine})):Ne,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}".`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.entry&&(this.entry._special=!0),this.exit&&(this.exit._special=!0),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=ne(t.tags).slice(),this.invoke=ne(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,o=(r=this.id,`${e}.${r}`);var r;const i=t.id??o,c="string"==typeof s?s:`xstate.invoke.${o}`;return{...t,src:c,logic:s,id:i,registryKey:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,o=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===o.length)return[];const r=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;r.push({event:c(n,t.id),timerId:a(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0})}var i;void 0!==s&&n&&r.push({event:(i=t.id,{type:"xstate.timeout",stateId:i}),timerId:u(t.id),delay:s,transitions:n,fromDelaysMap:!0});for(const t of o)r.push({event:h(t.id),timerId:f(t.id),resolveEvent:({children:e})=>h(t.id,e[t.id]?.sessionId),eventMatcher:(e,s)=>at(e,s,t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1});const d=[];for(const{event:e,timerId:s,resolveEvent:n,eventMatcher:o,delay:i,transitions:c,fromDelaysMap:a}of r){ut(t,s,n??(()=>e),e=>Y(i,a?e.delays:{},{context:e.context,event:e.event,stateNode:t,input:e.input}));const{type:r,...u}=e;for(const t of ce(c))d.push({...t,matches:{...t.matches,...Object.fromEntries(Object.entries(u).filter(([,t])=>void 0!==t))},event:r,delay:i,_eventMatcher:o})}return d.map(e=>({...ht(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map,s=(t,s)=>{e.set(t,[...e.get(t)??[],...s])};if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error("Null event transition key");const n=t.config.on[s];e.set(s,ze(n,e=>ht(t,s,e)))}if(t.config.onDone){const e="xstate.done.state";s(e,ze(t.config.onDone,s=>ht(t,e,{...s,matches:{...s.matches,stateId:t.id}})))}if(t.config.onError){const s="xstate.error.*";e.set(s,ze(t.config.onError,e=>ht(t,s,e)))}const n=(e,s,n)=>ht(t,e,{matches:{actorId:n},_eventMatcher:(t,e)=>at(t,e,n),to:(t,e)=>(e.cancel(s),{})}),o=(e,s,n)=>{const{target:o,to:r,reenter:i,...c}=s;return ht(t,e,{...c,reenter:i,to:(t,e)=>{if(r){let s=!1;const o=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const o=Reflect.get(t,e,n);return"function"!=typeof o?o:(...e)=>(s=!0,o.apply(t,e))}}),i=r(t,o);return(void 0!==i||s)&&e.cancel(n),i}return e.cancel(n),{target:o,reenter:i}}})};for(const e of t.invoke){const r=t=>({...t,matches:{...t.matches,actorId:e.id},_eventMatcher:(t,s)=>at(t,s,e.id)}),i=void 0!==e.timeout?f(e.id):void 0;if(e.onDone){const c="xstate.done.actor",a=ze(e.onDone,e=>{const s=r(e);return i?o(c,s,i):ht(t,c,s)});i&&a.push(n(c,i,e.id)),s(c,a)}else if(i){const t="xstate.done.actor";s(t,[n(t,i,e.id)])}if(e.onError){const n="xstate.error.actor";s(n,ze(e.onError,e=>{const s=r(e);return i?o(n,s,i):ht(t,n,s)}))}if(e.onSnapshot){const n="xstate.snapshot.actor";s(n,ze(e.onSnapshot,e=>ht(t,n,r(e))))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),"choice"===this.type?this.always=function(t){const e=t.config.choice,s=e=>{if(!e||void 0===e.target)throw new Error(`Choice "${t.id}" has no target`);return e};return[ht(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=ze(this.config.always,t=>ht(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 Pe(this,"initial",()=>function(t,e){const s="object"==typeof e&&null!==e?e.target:e,n="object"==typeof e&&null!==e?e.input:void 0,o="string"==typeof s?t.states[s]:void 0;if(!o&&s)throw new Error(`Initial state "${s}" not found on "#${t.id}"`);return{source:t,target:o?[o]:void 0,input:n}}(this,this.config.initial))}next(t,e,s){const n=Pe(this,`candidates-${function(t){return ct(t).join("|")}(e)}`,()=>function(t,e){const s=ct(e),n=s.flatMap(e=>t.transitions.get(e)??[]),o=[...t.transitions.keys()].filter(t=>!s.includes(t)&&s.some(e=>le(e,t))).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return n.length?[...n,...o]:o}(this,e));for(const o of n){if(Rt(o,e,t,this,s))return[o]}}}function ze(t,e){const s=ce(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}let De,Je;function Ke(){return De??=Ie({transition:t=>[t,[]],initialTransition:()=>[{status:"active",output:void 0,error:void 0},[]],getInitialSnapshot:()=>({status:"active",output:void 0,error:void 0}),getPersistedSnapshot:t=>t})}class Ve{constructor(t,e){this.config=t,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._json=void 0,this.id=t.id||"(machine)",this.sources={actors:t.actors??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...e},this.version=this.config.version,this.schemas=this.config.schemas,this.internalEventDescriptors=this.config.internalEvents??[],this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.initialTransition=this.initialTransition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new Re(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const o=n.config.id,r=n.config.route,i=({event:t})=>t.to===`#${o}`;if("function"==typeof r)return e.push(ht(t,"xstate.route",{guard:i,to:t=>{const e=r(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(n.states&&s(n.states));const{guard:c,...a}=r,u={...a,guard:i,target:`#${o}`};e.push(ht(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.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.sources,r=new Ve(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}});return r._json=this._json,r}resolveState(t){const e=(s=this.root,n=t.value,ot(s,nt(vt(s,n))));var s,n;const o=nt(vt(this.root,e));return Ht({_nodes:[...o],value:e,context:t.context||{},children:{},status:rt(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const n=!s,o=s??Oe(this,t);n&&$e(o,t,!1);const r=this._transitionFast(t,e,o);if(r){n&&$e(o,r,!1);return[n&&r!==t?je(this,o,r):this._attachPureActorRef(r,o),[]]}const{snapshot:i,microsteps:c}=$t(t,e,o,[]);n&&$e(o,i,!1);return[n?i===t?i:je(this,o,i):this._attachPureActorRef(i,o),this._collectEffects(c)]}_collectEffects(t){return t.flatMap(([,t])=>t)}_attachPureActorRef(t,e){return function(t){return!!t.self.options?._inert}(e)?t:je(this,e,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 o=n.transitions.get(e.type);if(1!==o?.length)return;const r=o[0];if(r.guard||r.actions||r.to||r.reenter||r.input||"function"==typeof r.context||r.target&&1!==r.target.length)return;const i=r.target?.[0]??n,c=i!==n;if(i.parent!==this.root||"atomic"!==i.type||c&&(i.entry||i.invoke.length||i.always?.length||i.after?.length))return;const a=void 0!==r.context?{...t.context,...r.context}:t.context,u=s.self._collectedMicrosteps||[];return u.push(r),s.self._collectedMicrosteps=u,Xt(t,{...a!==t.context?{context:a}:{},...c?{_nodes:[this.root,i]}:{}})}microstep(t,e,s){const{microsteps:n}=$t(t,e,s,[]),o=new Array(n.length);for(let t=0;t<n.length;t++)o[t]=n[t][0];return o}getTransitionData(t,e,s){return mt(this.root,t.value,t,e,s)||[]}isInternalEventType(t){if(t===i)return!0;for(const e of this.internalEventDescriptors)if(le(t,e))return!0;return!1}_canTransition(t,e){const s=Ke(),n=function(){if(Je)return Je;const t=Ke();return Je={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},Je}(),o=this.getTransitionData(t,e,s);if(!o?.length)return!1;for(const r of o){if(void 0!==r.target)return!0;const o=At(r,t,e,n,{resolveActions:!1});if(o.targets?.length||o.context||jt(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 l("execution",e)}_getPreInitialState(t,e){const{context:s}=this.config,n=Ht({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this,t.self);if("function"==typeof s){const o={},r=function(t,e,s){return(n,o)=>{const r=Object.entries(e).find(([,t])=>t===n)?.[0],i=t.system.createActorRef(n,{id:o?.id,parent:t.self,syncSnapshot:o?.syncSnapshot,input:o?.input,src:r??n,registryKey:o?.registryKey});return s[i.id]=i,i}}(t,this.sources.actors,o),i=s({spawn:r,input:e.input,self:t.self,actors:this.sources.actors}),[c]=G(n,e,t,[]);return i&&(c.context=i),Object.keys(o).length>0&&(c.children={...c.children,...o}),c}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){const s=!e,o=e??Oe(this),r=p(t),i=[],c=this._getPreInitialState(o,r),a=Object.values(c.children).filter(Boolean).map(t=>function(t){const e=[t];return{kind:"builtin",exec:$,type:n,source:t._parent,params:void 0,args:e,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}(t));let u,h,f=[],d=[];try{[u,f]=function(t,e,s,n,o){return Tt([{target:[...pt(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,c,o,r,i),({snapshot:h,microsteps:d}=$t(u,r,o,i,[[u,[...a,...f]]]))}catch(t){if(!this.root.config.onError)throw t;const e=$t(c,l("execution",t),o,[],[[c,a]]);h=e.snapshot,d=e.microsteps,f=[]}s&&$e(o,h,!1);return[s?je(this,o,h):this._attachPureActorRef(h,o),this._collectEffects(d)]}start(t){if(t?.children)for(const e of Object.values(t.children))e._rehydrated&&"active"===e.getSnapshot?.().status&&e.start()}getStateNodeById(t){const e=te(t),s=e.slice(1),n=it(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return gt(o,s)}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,_stateInputs:n,tags:o,machine:r,children:i,timers:c,context:a,can:u,hasTag:h,matches:f,getMeta:d,getInputs:l,toJSON:p,...y}=t,g={},v={};for(const t in i){const s=i[t];g[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,registryKey:s.registryKey,syncSnapshot:s._syncSnapshot}}for(const e in c){const s=c[e];let n,o=s.event;if("xstate.timeout.actor"===o.type&&(o={...o},delete o.sessionId),"self"===s.target)n="self";else{const o=Object.entries(i).find(([,t])=>t===s.target)?.[0];if(o)n=o;else{if(s.target!==Jt(t)?.actor._parent)throw new Error(`Unable to persist timer '${e}': target actor '${s.target.id}' is no longer addressable from this snapshot.`);n={type:"parent"}}}v[e]={id:s.id,delay:s.delay,type:s.type,event:o,target:n}}const m={...y,_nextActorId:Jt(t)?.systemState.snapshot._nextActorId,context:Yt(a),children:g,timers:v,historyValue:Qt(y.historyValue)};return n&&Object.keys(n).length>0&&(m.stateInputs=n),void 0!==r.version&&(m.version=r.version),m}(t,e)}restoreSnapshot(t,e){const s=!e,n=e??Oe(this),o=t.version;if(o!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${o}' does not match machine version '${this.version}'.`);t=e(t,o)}const r=t,i={},c=r.children;for(const t of Object.keys(c)){const e=c[t],s=e.snapshot,o=e.src,r="string"==typeof o?he(this,o):o;if(!r){throw new Error(`Unable to restore child actor '${t}': child source '${"string"==typeof o?o:"<unknown>"}' is not provided in machine '${this.id}'.`)}const a=n.system.createActorRef(r,{id:t,parent:n.self,syncSnapshot:e.syncSnapshot,snapshot:s,src:o,registryKey:e.registryKey});a._rehydrated=!0,i[t]=a}const a={},u=r.timers??{};for(const[t,e]of Object.entries(u)){let s=e.event;if("xstate.timeout.actor"===s.type){const t=s.actorId,e=i[t];e&&(s=h(t,e.sessionId))}const o="string"==typeof e.target?"self"===e.target?"self":i[e.target]:n.self._parent;if(!o){const s="string"==typeof e.target?e.target:e.target.type;throw new Error(`Unable to restore timer '${t}': target actor '${s}' is unavailable.`)}a[t]={...e,event:s,target:o}}const f=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const s of Object.keys(t)){const n=t[s];for(const t of n){let n;if(t instanceof Re)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(r.historyValue),d=Array.from(nt(vt(this.root,r.value))),{version:l,...p}=t,y=Ht({...p,children:i,timers:a,_nodes:d,value:r.value,historyValue:f,_stateInputs:r.stateInputs??{}},this,n.self),g=new WeakSet;return function t(e){if(!g.has(e)){g.add(e);for(const s of Object.keys(e)){const n=e[s];if(n&&"object"==typeof n){if("xstate$$type"in n&&n.xstate$$type===me){e[s]=i[n.id];continue}t(n)}}}}(y.context),s?($e(n,y,!1),je(this,n,y)):this._attachPureActorRef(y,n)}}function We(t){return JSON.stringify(t)}function Ue(t){const e=Object.keys(t.context).length?`(${JSON.stringify(t.context)})`:"",s=t._nodes.filter(t=>"atomic"===t.type||"final"===t.type).map(({id:e,path:s})=>{const n=t.getMeta()[e];if(!n)return`"${s.join(".")}"`;const{description:o}=n;return"function"==typeof o?o(t):o?`"${o}"`:JSON.stringify(t.value)});return`state${1===s.length?"":"s"} `+s.join(", ")+` ${e}`.trim()}const Be=()=>(t,e)=>is(t,e),Ce=()=>(t,e)=>cs(t,e);class Le{getDefaultOptions(){return{serializeState:t=>We(t),serializeEvent:t=>We(t),serializeTransition:(t,e)=>`${We(t)}|${e?.type}`,events:[],stateMatcher:(t,e)=>"*"===e,logger:{log:console.log.bind(console),error:console.error.bind(console)}}}constructor(t,e){this.testLogic=t,this.options=void 0,this.defaultTraversalOptions=void 0,this._toTestPath=t=>{const e=t.steps.map(t=>function(t){const{type:e,...s}=t;return`${e}${Object.keys(s).length?` (${JSON.stringify(s)})`:""}`}(t.event)).join(" → ");return{...t,test:e=>this.testPath(t,e),description:Wt(t.state)?`Reaches ${Ue(t.state).trim()}: ${e}`:JSON.stringify(t.state)}},this.options={...this.getDefaultOptions(),...e}}getPaths(t,e){const s=e?.allowDuplicatePaths??!1,n=t(this.testLogic,this._resolveOptions(e));return(s?n:((t,e=We)=>{const s=[];t.forEach(t=>{s.push({path:t,eventSequence:t.steps.map(t=>e(t.event))})}),s.sort((t,e)=>e.path.steps.length-t.path.steps.length);const n=[];t:for(const t of s){e:for(const e of n){for(const s in t.eventSequence)if(t.eventSequence[s]!==e.eventSequence[s])continue e;continue t}n.push(t)}return n.map(t=>t.path)})(n)).map(this._toTestPath)}getShortestPaths(t){return this.getPaths(Be(),t)}getShortestPathsFrom(t,e){const s=[];for(const n of t){const t=this.getShortestPaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(es(n,e)))}return s}getSimplePaths(t){return this.getPaths(Ce(),t)}getSimplePathsFrom(t,e){const s=[];for(const n of t){const t=this.getSimplePaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(es(n,e)))}return s}getPathsFromEvents(t,e){return rs(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return ns(this.testLogic,this.options)}async testPath(t,e,s){const n={steps:[],state:{error:null}};try{for(const o of t.steps){const t={step:o,state:{error:null},event:{error:null}};n.steps.push(t);try{await this.testTransition(e,o)}catch(e){throw t.event.error=e,e}try{await this.testState(e,o.state,s)}catch(e){throw t.state.error=e,e}}}catch(e){throw e.message+=function(t,e,s){const n={formatColor:(t,e)=>e,serializeState:We,serializeEvent:We,...s},{formatColor:o,serializeState:r,serializeEvent:i}=n,{state:c}=t,a=r(c,t.steps.length?t.steps[t.steps.length-1].event:void 0);let u="",h=!1;return u+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=r(t.step.state,e>0?s[e-1].step.event:void 0),c=i(t.step.event);return[`\tState: ${h?o("gray",n):t.state.error?(h=!0,o("redBright",n)):o("greenBright",n)}`,`\tEvent: ${h?o("gray",c):t.event.error?(h=!0,o("red",c)):o("green",c)}`].join("\n")}).concat(`\tState: ${h?o("gray",a):e.state.error?o("red",a):o("green",a)}`).join("\n\n"),u}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),o=this._getStateTestKeys(t,e,n);for(const s of o)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},o=Object.keys(n).filter(t=>s.stateMatcher(e,t));return!o.length&&"*"in n&&o.push("*"),o}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function qe(t,e){if(t===e)return!0;if(void 0===t||void 0===e)return!1;if("string"==typeof t||"string"==typeof e)return t===e;const s=Object.keys(t),n=Object.keys(e);return s.length===n.length&&s.every(s=>qe(t[s],e[s]))}function Fe(t,e,s,{serializeEvent:n}){if(!e||s&&qe(s.value,t.value))return"";const o=s?` from ${We(s.value)}`:"";return` via ${n(e)}${o}`}function Ge(){const t=Ie(Ae);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function He(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function Xe(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function Qe(t){return JSON.stringify(t)}function Ye(t,e){const{events:s,...n}=e??{};return{serializeState:Xe,serializeEvent:Qe,events:t=>{const e="function"==typeof s?s(t):s??[];return fe(t).flatMap(t=>{const s=e.filter(e=>de(e,t));return s.length?s:[t]})},fromState:t.getInitialSnapshot(Ge(),e?.input),...n}}function Ze(){return{serializeState:t=>JSON.stringify(t),serializeEvent:Qe}}function ts(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?Ye(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:Qe,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function es(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}}function ss(t){return Array.isArray(t)?t[0]:t}function ns(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:r,filterEvents:i,limit:c,fromState:a,stopWhen:u}=ts(t,e),h=Ge(),f={};let d=0;const l=[{nextState:a??t.getInitialSnapshot(h,e.input),event:void 0,prevState:void 0}],p=new Map;for(;l.length;){const{nextState:t,event:e,prevState:a}=l.shift();if(d++>c)throw new Error("Traversal limit exceeded");const y=o(t,e,a);if(f[y])continue;if(p.set(y,t),f[y]={state:t,transitions:{}},u&&u(t))continue;const g="function"==typeof r?r(t):r;for(const e of g){if(i&&!i(t,e))continue;const o=ss(s(t,e,h));f[y].transitions[n(e)]={event:e,state:o},l.push({nextState:o,event:e,prevState:t})}}return f}function os(t){let e=[];if(t.steps.length){for(let n=0;n<t.steps.length;n++){const o=t.steps[n];e.push({state:o.state,event:0===n?{type:s}:t.steps[n-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:s}}];return{...t,steps:e}}function rs(t,e,s){const n=ts(t,{events:e,...s},(o=t)&&o instanceof Ve?Ye(t):Ze());var o;const r=Ge(),i=n.fromState??t.getInitialSnapshot(r,s?.input),{serializeState:c,serializeEvent:a}=n,u=ns(t,n),h=new Map,f=[],d=c(i,void 0,void 0);h.set(d,i);let l=d,p=i;for(const t of e){f.push({state:h.get(l),event:t});const e=a(t),{state:s,event:n}=u[l].transitions[e];if(!s)throw new Error(`Invalid transition from ${l} with ${e}`);const o=c(s,t,h.get(l));h.set(o,s),l=o,p=s}return n.toState&&!n.toState(p)?[]:[os({state:p,steps:f,weight:f.length})]}function is(t,e){const s=ts(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(Ge(),e?.input),r=ns(t,s),i=new Map,c=new Map,a=n(o,void 0,void 0);c.set(a,o),i.set(a,{weight:0,state:void 0,event:void 0});const u=new Set,h=new Set;u.add(a);for(const t of u){const e=c.get(t),{weight:s}=i.get(t);for(const o of Object.keys(r[t].transitions)){const{state:a,event:f}=r[t].transitions[o],d=n(a,f,e);if(c.set(d,a),i.has(d)){const{weight:e}=i.get(d);e>s+1&&i.set(d,{weight:s+1,state:t,event:f})}else i.set(d,{weight:s+1,state:t,event:f});h.has(d)||u.add(d)}h.add(t),u.delete(t)}const f={},d=[];return i.forEach(({weight:t,state:e,event:s},n)=>{const o=c.get(n),r=e?f[e].paths[0].steps.concat({state:c.get(e),event:s}):[];d.push({state:o,steps:r,weight:t}),f[n]={state:o,paths:[{state:o,steps:r,weight:t}]}}),s.toState?d.filter(t=>s.toState(t.state)).map(os):d.map(os)}function cs(t,e){const s=ts(t,e),n=Ge(),o=s.fromState??t.getInitialSnapshot(n,e?.input),r=s.serializeState,i=ns(t,s),c=new Map,a={vertices:new Set,edges:new Set},u=[],h={};function f(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){h[e]||(h[e]={state:c.get(e),paths:[]});const t=h[e],n={state:s,weight:u.length,steps:[...u]};t.paths.push(n)}else{if(!i[t])return;for(const s of Object.keys(i[t].transitions)){const{state:n,event:o}=i[t].transitions[s];if(!(s in i[t].transitions))continue;const h=c.get(t),d=r(n,o,h);c.set(d,n),a.vertices.has(d)||(a.edges.add(s),u.push({state:c.get(t),event:o}),f(d,e))}}u.pop(),a.vertices.delete(t)}const d=r(o,void 0);c.set(d,o);for(const t of Object.keys(i))f(d,t);const l=Object.values(h).flatMap(t=>t.paths);return s.toState?l.filter(t=>s.toState(t.state)).map(os):l.map(os)}t.TestModel=Le,t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.createShortestPathsGen=Be,t.createSimplePathsGen=Ce,t.createTestModel=function(t,e){(t=>{t.root})(t);const s=e?.serializeEvent??We,n=e?.serializeTransition??Fe,{events:o,...r}=e??{};return new Le(t,{serializeState:(t,e,o)=>`${Xe(t)}${n(t,e,o,{serializeEvent:s})}`,stateMatcher:(e,s)=>s.startsWith("#")?e._nodes.includes(t.getStateNodeById(s)):e.matches(s),events:t=>{const e="function"==typeof o?o(t):o??[];return fe(t).flatMap(t=>e.some(e=>de(e,t))?e.filter(e=>de(e,t)):[t])},...r})},t.getAdjacencyMap=ns,t.getPathsFromEvents=rs,t.getShortestPaths=is,t.getSimplePaths=cs,t.getStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,n)=>{const o=s[n],r=t(o);return e.push(o,...r),e},[])},t.joinPaths=es,t.serializeSnapshot=Xe,t.toDirectedGraph=function t(e){const s=e instanceof Ve?e.root:e,n=[...s.transitions.values()].flat().flatMap((t,e)=>(t.target?t.target:[s]).map((n,o)=>{const r={id:`${s.id}:${e}:${o}`,source:s,target:n,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=r;return{source:s.id,target:n.id,label:t}}};return r})),o={id:s.id,stateNode:s,children:He(s).map(t),edges:n,toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s}}};return o},Object.defineProperty(t,"__esModule",{value:!0})});
|
|
2
2
|
//# sourceMappingURL=xstate-graph.umd.min.js.map
|