UNPKG

xstate

Version:

Finite State Machines and Statecharts for the Modern Web.

3 lines (2 loc) 44.9 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateGraph={})}(this,(function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="xstate.init",n="xstate.stop";function o(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const i=t=>{const e=o();e&&e.register(t)};function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function a(t){return{type:s,input:t}}function c(t){setTimeout((()=>{throw t}))}const h="function"==typeof Symbol&&Symbol.observable||"@@observable";function u(t,e){const s=p(t),n=p(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every((t=>t in n&&u(s[t],n[t])))}function f(t){if(v(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function p(t){if(Et(t))return t.value;if("string"!=typeof t)return t;return function(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}(f(t))}function d(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const i=n[o];s[i]=e(t[i],i,t,o)}return s}function l(t){return v(t)?t:[t]}function y(t){return void 0===t?[]:l(t)}function g(t,e,s,n){return"function"==typeof t?t({context:e,event:s,self:n}):t}function v(t){return Array.isArray(t)}function m(t){return l(t).map((t=>void 0===t||"string"==typeof t?{target:t}:t))}function _(t){if(void 0!==t&&""!==t)return y(t)}function S(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function w(t,e){return`${e}.${t}`}function x(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actors[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke;return(Array.isArray(i)?i[n]:i).src}function b(t){return[...new Set([...t._nodes.flatMap((t=>t.ownEvents))])]}function E(t,e){return`${t.sessionId}.${e}`}let $=0;let k=!1;let I=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const O={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class j{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new e(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=I.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const n={...O,...s},{clock:o,logger:i,parent:r,syncSnapshot:a,id:c,systemId:h,inspect:u}=n;this.system=r?r.system:function(t,e){const s=new Map,n=new Map,o=new WeakMap,i=new Set,r={},{clock:a,logger:c}=e,h={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},c=E(t,o);u._snapshot._scheduledEvents[c]=i;const h=a.setTimeout((()=>{delete r[c],delete u._snapshot._scheduledEvents[c],u._relay(t,e,s)}),n);r[c]=h},cancel:(t,e)=>{const s=E(t,e),n=r[s];delete r[s],delete u._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in u._snapshot._scheduledEvents){const s=u._snapshot._scheduledEvents[e];s.source===t&&h.cancel(t,s.id)}}},u={_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+$++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=o.get(t);void 0!==e&&(n.delete(e),o.delete(t))},get:t=>n.get(t),_set:(t,e)=>{const s=n.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);n.set(t,e),o.set(e,t)},inspect:t=>{const e=S(t);return i.add(e),{unsubscribe(){i.delete(e)}}},_sendInspectionEvent:e=>{if(!i.size)return;const s={...e,rootId:t.sessionId};i.forEach((t=>t.next?.(s)))},_relay:(t,e,s)=>{u._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:e,event:s}),e._send(s)},scheduler:h,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{const t=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];h.schedule(s,n,o,i,r)}},_clock:a,_logger:c};return u}(this,{clock:o,logger:i}),u&&!r&&this.system.inspect(S(u)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=r,this._syncSnapshot=a,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get("*");if(!e&&!s)return;const n=[...e?e.values():[],...s?s.values():[]];for(const e of n)e(t)},actionExecutor:t=>{const e=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:t.type,params:t.params}}),!t.exec)return;const e=k;try{k=!0,t.exec(t.info,t.params)}finally{k=e}};this._processingStatus===I.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),h&&(this._systemId=h,this.system._set(h,this)),this._initState(s?.snapshot??s?.state),h&&"active"!==this._snapshot.status&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(t,e){let s;for(this._snapshot=t;s=this._deferred.shift();)try{s()}catch(e){this._deferred.length=0,this._snapshot={...t,status:"error",error:e}}switch(this._snapshot.status){case"active":for(const e of this.observers)try{e.next?.(t)}catch(t){c(t)}break;case"done":for(const e of this.observers)try{e.next?.(t)}catch(t){c(t)}this._stopProcedure(),this._complete(),this._doneEvent=(n=this.id,o=this._snapshot.output,{type:`xstate.done.actor.${n}`,output:o,actorId:n}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error)}var n,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){const n=S(t,e,s);if(this._processingStatus!==I.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){c(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){c(t)}else c(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const n=e.bind(void 0);return s.add(n),{unsubscribe:()=>{s.delete(n)}}}start(){if(this._processingStatus===I.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=I.Running;const t=a(this.options.input);this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t});switch(this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._snapshot={...this._snapshot,status:"error",error:t},this._error(t),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._snapshot={...this._snapshot,status:"error",error:t},void this._error(t)}this.update(e,t),t.type===n&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===I.Stopped?this:(this.mailbox.clear(),this._processingStatus===I.NotStarted?(this._processingStatus=I.Stopped,this):(this.mailbox.enqueue({type:n}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){c(t)}this.observers.clear()}_reportError(t){if(!this.observers.size)return void(this._parent||c(t));let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){c(t)}}this.observers.clear(),e&&c(t)}_error(t){var e;this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${e=this.id}`,error:t,actorId:e})}_stopProcedure(){return this._processingStatus!==I.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this._processingStatus=I.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==I.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:i)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[h](){return this}getSnapshot(){return this._snapshot}}function T(t,...[e]){return new j(t,e)}function M(t,e,s,n,{sendId:o}){return[e,{sendId:"function"==typeof o?o(s,n):o},void 0]}function N(t,e){t.defer((()=>{t.system.scheduler.cancel(t.self,e.sendId)}))}function P(t,e,s,n,{id:o,systemId:i,src:r,input:a,syncSnapshot:c}){const h="string"==typeof r?x(e.machine,r):r,u="function"==typeof o?o(s):o;let f,p;return h&&(p="function"==typeof a?a({context:e.context,event:s.event,self:t.self}):a,f=T(h,{id:u,src:r,parent:t.self,syncSnapshot:c,systemId:i,input:p})),[Mt(e,{children:{...e.children,[u]:f}}),{id:o,systemId:i,actorRef:f,src:r,input:p},void 0]}function z(t,{actorRef:e}){e&&t.defer((()=>{e._processingStatus!==I.Stopped&&e.start()}))}function A(...[t,{id:e,systemId:s,input:n,syncSnapshot:o=!1}={}]){function i(t,e){}return i.type="xstate.spawnChild",i.id=e,i.systemId=s,i.src=t,i.input=n,i.syncSnapshot=o,i.resolve=P,i.execute=z,i}function J(t,e,s,n,{actorRef:o}){const i="function"==typeof o?o(s,n):o,r="string"==typeof i?e.children[i]:i;let a=e.children;return r&&(a={...a},delete a[r.id]),[Mt(e,{children:a}),r,void 0]}function R(t,e){e&&(t.system._unregister(e),e._processingStatus===I.Running?t.defer((()=>{t.stopChild(e)})):t.stopChild(e))}function D(t){function e(t,e){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=J,e.execute=R,e}function C(t,e,s,n){const{machine:o}=n,i="function"==typeof t,r=i?t:o.implementations.guards["string"==typeof t?t:t.type];if(!i&&!r)throw new Error(`Guard '${"string"==typeof t?t:t.type}' is not implemented.'.`);if("function"!=typeof r)return C(r,e,s,n);const a={context:e,event:s},c=i||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:e,event:s}):t.params:void 0;if(!("check"in r))return r(a,c);return r.check(n,a,r)}const V=t=>"atomic"===t.type||"final"===t.type;function B(t){return Object.values(t.states).filter((t=>"history"!==t.type))}function L(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 q(t){const e=new Set(t),s=G(e);for(const t of e)if("compound"!==t.type||s.get(t)&&s.get(t).length){if("parallel"===t.type)for(const s of B(t))if("history"!==s.type&&!e.has(s)){const t=Z(s);for(const s of t)e.add(s)}}else Z(t).forEach((t=>e.add(t)));for(const t of e){let s=t.parent;for(;s;)e.add(s),s=s.parent}return e}function W(t,e){const s=e.get(t);if(!s)return{};if("compound"===t.type){const t=s[0];if(!t)return{};if(V(t))return t.key}const n={};for(const t of s)n[t.key]=W(t,e);return n}function G(t){const e=new Map;for(const s of t)e.has(s)||e.set(s,[]),s.parent&&(e.has(s.parent)||e.set(s.parent,[]),e.get(s.parent).push(s));return e}function F(t,e){return W(t,G(q(e)))}function U(t,e){return"compound"===e.type?B(e).some((e=>"final"===e.type&&t.has(e))):"parallel"===e.type?B(e).every((e=>U(t,e))):"final"===e.type}const K=t=>"#"===t[0];function Q(t){const e=t.config.after;if(!e)return[];const s=e=>{const s=(n=e,o=t.id,{type:`xstate.after.${n}.${o}`});var n,o;const i=s.type;return t.entry.push(function(t,e){function s(t,e){}return s.type="xstate.raise",s.event=t,s.id=e?.id,s.delay=e?.delay,s.resolve=Rt,s.execute=Dt,s}(s,{id:i,delay:e})),t.exit.push(function(t){function e(t,e){}return e.type="xstate.cancel",e.sendId=t,e.resolve=M,e.execute=N,e}(i)),i};return Object.keys(e).flatMap((t=>{const n=e[t],o="string"==typeof n?{target:n}:n,i=Number.isNaN(+t)?t:+t,r=s(i);return y(o).map((t=>({...t,event:r,delay:i})))})).map((e=>{const{delay:s}=e;return{...X(t,e.event,e),delay:s}}))}function X(t,e,s){const n=_(s.target),o=s.reenter??!1,i=function(t,e){if(void 0===e)return;return e.map((e=>{if("string"!=typeof e)return e;if(K(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return st(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`);try{return st(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}}))}(t,n),r={...s,actions:y(s.actions),guard:s.guard,target:i,source:t,reenter:o,eventType:e,toJSON:()=>({...r,source:`#${t.id}`,target:i?i.map((t=>`#${t.id}`)):void 0})};return r}function H(t){const e=_(t.config.target);return e?{target:e.map((e=>"string"==typeof e?st(t.parent,e):e))}:t.parent.initial}function Y(t){return"history"===t.type}function Z(t){const e=tt(t);for(const s of e)for(const n of L(s,t))e.add(n);return e}function tt(t){const e=new Set;return function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of B(s))t(e)}(t),e}function et(t,e){if(K(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const s=t.states[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function st(t,e){if("string"==typeof e&&K(e))try{return t.machine.getStateNodeById(e)}catch{}const s=f(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=et(n,t)}return n}function nt(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=s.map((e=>et(t,e))).filter(Boolean);return[t.machine.root,t].concat(n,s.reduce(((s,n)=>{const o=et(t,n);if(!o)return s;const i=nt(o,e[n]);return s.concat(i)}),[]))}function ot(t,e,s,n){return"string"==typeof e?function(t,e,s,n){const o=et(t,e).next(s,n);return o&&o.length?o:t.next(s,n)}(t,e,s,n):1===Object.keys(e).length?function(t,e,s,n){const o=Object.keys(e),i=ot(et(t,o[0]),e[o[0]],s,n);return i&&i.length?i:t.next(s,n)}(t,e,s,n):function(t,e,s,n){const o=[];for(const i of Object.keys(e)){const r=e[i];if(!r)continue;const a=ot(et(t,i),r,s,n);a&&o.push(...a)}return o.length?o:t.next(s,n)}(t,e,s,n)}function it(t){return Object.keys(t.states).map((e=>t.states[e])).filter((t=>"history"===t.type))}function rt(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function at(t,e){const s=new Set(t),n=new Set(e);for(const t of s)if(n.has(t))return!0;for(const t of n)if(s.has(t))return!0;return!1}function ct(t,e,s){const n=new Set;for(const o of t){let t=!1;const i=new Set;for(const r of n)if(at(ft([o],e,s),ft([r],e,s))){if(!rt(o.source,r.source)){t=!0;break}i.add(r)}if(!t){for(const t of i)n.delete(t);n.add(o)}}return Array.from(n)}function ht(t,e){if(!t.target)return[];const s=new Set;for(const n of t.target)if(Y(n))if(e[n.id])for(const t of e[n.id])s.add(t);else for(const t of ht(H(n),e))s.add(t);else s.add(n);return[...s]}function ut(t,e){const s=ht(t,e);if(!s)return;if(!t.reenter&&s.every((e=>e===t.source||rt(e,t.source))))return t.source;const n=function(t){const[e,...s]=t;for(const t of L(e,void 0))if(s.every((e=>rt(e,t))))return t}(s.concat(t.source));return n||(t.reenter?void 0:t.source.machine.root)}function ft(t,e,s){const n=new Set;for(const o of t)if(o.target?.length){const t=ut(o,s);o.reenter&&o.source===t&&n.add(t);for(const s of e)rt(s,t)&&n.add(s)}return[...n]}function pt(t,e,s,n,o,i){if(!t.length)return e;const a=new Set(e._nodes);let c=e.historyValue;const h=ct(t,a,c);let u=e;o||([u,c]=function(t,e,s,n,o,i,r){let a=t;const c=ft(n,o,i);let h;c.sort(((t,e)=>e.order-t.order));for(const t of c)for(const e of it(t)){let s;s="deep"===e.history?e=>V(e)&&rt(e,t):e=>e.parent===t,h??={...i},h[e.id]=Array.from(o).filter(s)}for(const t of c)a=_t(a,e,s,[...t.exit,...t.invoke.map((t=>D(t.id)))],r,void 0),o.delete(t);return[a,h||i]}(u,n,s,h,a,c,i,s.actionExecutor)),u=_t(u,n,s,h.flatMap((t=>t.actions)),i,void 0),u=function(t,e,s,n,o,i,a,c){let h=t;const u=new Set,f=new Set;(function(t,e,s,n){for(const o of t){const t=ut(o,e);for(const i of o.target||[])Y(i)||o.source===i&&o.source===t&&!o.reenter||(n.add(i),s.add(i)),lt(i,e,s,n);const i=ht(o,e);for(const r of i){const i=L(r,t);"parallel"===t?.type&&i.push(t),yt(n,e,s,i,!o.source.parent&&o.reenter?void 0:t)}}})(n,a,f,u),c&&f.add(t.machine.root);const p=new Set;for(const t of[...u].sort(((t,e)=>t.order-e.order))){o.add(t);const n=[];n.push(...t.entry);for(const e of t.invoke)n.push(A(e.src,{...e,syncSnapshot:!!e.onSnapshot}));if(f.has(t)){const e=t.initial.actions;n.push(...e)}if(h=_t(h,e,s,n,i,t.invoke.map((t=>t.id))),"final"===t.type){const n=t.parent;let a="parallel"===n?.type?n:n?.parent,c=a||t;for("compound"===n?.type&&i.push(r(n.id,void 0!==t.output?g(t.output,h.context,e,s.self):void 0));"parallel"===a?.type&&!p.has(a)&&U(o,a);)p.add(a),i.push(r(a.id)),c=a,a=a.parent;if(a)continue;h=Mt(h,{status:"done",output:dt(h,e,s,h.machine.root,c)})}}return h}(u,n,s,h,a,i,c,o);const f=[...a];"done"===u.status&&(u=_t(u,n,s,f.sort(((t,e)=>e.order-t.order)).flatMap((t=>t.exit)),i,void 0));try{return c===e.historyValue&&function(t,e){if(t.length!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;return!0}(e._nodes,a)?u:Mt(u,{_nodes:f,historyValue:c})}catch(t){throw t}}function dt(t,e,s,n,o){if(void 0===n.output)return;const i=r(o.id,void 0!==o.output&&o.parent?g(o.output,t.context,e,s.self):void 0);return g(n.output,t.context,i,s.self)}function lt(t,e,s,n){if(Y(t))if(e[t.id]){const o=e[t.id];for(const t of o)n.add(t),lt(t,e,s,n);for(const i of o)gt(i,t.parent,n,e,s)}else{const o=H(t);for(const i of o.target)n.add(i),o===t.parent?.initial&&s.add(t.parent),lt(i,e,s,n);for(const i of o.target)gt(i,t.parent,n,e,s)}else if("compound"===t.type){const[o]=t.initial.target;Y(o)||(n.add(o),s.add(o)),lt(o,e,s,n),gt(o,t,n,e,s)}else if("parallel"===t.type)for(const o of B(t).filter((t=>!Y(t))))[...n].some((t=>rt(t,o)))||(Y(o)||(n.add(o),s.add(o)),lt(o,e,s,n))}function yt(t,e,s,n,o){for(const i of n)if(o&&!rt(i,o)||t.add(i),"parallel"===i.type)for(const n of B(i).filter((t=>!Y(t))))[...t].some((t=>rt(t,n)))||(t.add(n),lt(n,e,s,t))}function gt(t,e,s,n,o){yt(s,n,o,L(t,e))}function vt(t,e){return t.implementations.actions[e]}function mt(t,e,s,n,o,i){const{machine:r}=t;let a=t;for(const t of n){const n="function"==typeof t,c=n?t:vt(r,"string"==typeof t?t:t.type),h={context:a.context,event:e,self:s.self,system:s.system},u=n||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:a.context,event:e}):t.params:void 0;if(!c||!("resolve"in c)){s.actionExecutor({type:"string"==typeof t?t:"object"==typeof t?t.type:t.name||"(anonymous)",info:h,params:u,exec:c});continue}const f=c,[p,d,l]=f.resolve(s,a,h,u,c,o);a=p,"retryResolve"in f&&i?.push([f,d]),"execute"in f&&s.actionExecutor({type:f.type,info:h,params:d,exec:f.execute.bind(null,s,d)}),l&&(a=mt(a,e,s,l,o,i))}return a}function _t(t,e,s,n,o,i){const r=i?[]:void 0,a=mt(t,e,s,n,{internalQueue:o,deferredActorIds:i},r);return r?.forEach((([t,e])=>{t.retryResolve(s,a,e)})),a}function St(t,e,o,i){let r=t;const a=[];function c(t,e,s){o.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:o.self,event:e,snapshot:t,_transitions:s}),a.push(t)}if(e.type===n)return r=Mt(wt(r,e,o),{status:"stopped"}),c(r,e,[]),{snapshot:r,microstates:a};let h=e;if(h.type!==s){const e=h,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),n=xt(e,r);if(s&&!n.length)return r=Mt(t,{status:"error",error:e.error}),c(r,e,[]),{snapshot:r,microstates:a};r=pt(n,t,o,h,!1,i),c(r,e,n)}let u=!0;for(;"active"===r.status;){let t=u?bt(r,h):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;h=i.shift(),t=xt(h,r)}r=pt(t,r,o,h,!1,i),u=r!==e,c(r,h,t)}return"active"!==r.status&&wt(r,h,o),{snapshot:r,microstates:a}}function wt(t,e,s){return _t(t,e,s,Object.values(t.children).map((t=>D(t))),[],void 0)}function xt(t,e){return e.machine.getTransitionData(e,t)}function bt(t,e){const s=new Set,n=t._nodes.filter(V);for(const o of n)t:for(const n of[o].concat(L(o,void 0)))if(n.always)for(const o of n.always)if(void 0===o.guard||C(o.guard,t.context,e,t)){s.add(o);break t}return ct(Array.from(s),new Set(t._nodes),t.historyValue)}function Et(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const $t=function(t){return u(t,this.value)},kt=function(t){return this.tags.has(t)},It=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some((t=>void 0!==t.target||t.actions.length))},Ot=function(){const{_nodes:t,tags:e,machine:s,getMeta:n,toJSON:o,can:i,hasTag:r,matches:a,...c}=this;return{...c,tags:Array.from(e)}},jt=function(){return this._nodes.reduce(((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t)),{})};function Tt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:F(e.root,t._nodes),tags:new Set(t._nodes.flatMap((t=>t.tags))),children:t.children,historyValue:t.historyValue||{},matches:$t,hasTag:kt,can:It,getMeta:jt,toJSON:Ot}}function Mt(t,e={}){return Tt({...t,...e},t.machine)}function Nt(t){if("object"!=typeof t||null===t)return{};const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map((t=>({id:t.id}))))}return e}function Pt(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:1,id:n.id};else{const o=Pt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function zt(t,{machine:e,context:s},n,o){return(i,r)=>{const a=((i,r)=>{if("string"==typeof i){const a=x(e,i);if(!a)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const c=T(a,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:s,event:n,self:t.self}):r?.input,src:i,systemId:r?.systemId});return o[c.id]=c,c}return T(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[a.id]=a,t.defer((()=>{a._processingStatus!==I.Stopped&&a.start()})),a}}function At(t,e,s,n,{assignment:o}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},r={context:e.context,event:s.event,spawn:zt(t,e,s.event,i),self:t.self,system:t.system};let a={};if("function"==typeof o)a=o(r,n);else for(const t of Object.keys(o)){const e=o[t];a[t]="function"==typeof e?e(r,n):e}return[Mt(e,{context:Object.assign({},e.context,a),children:Object.keys(i).length?{...e.children,...i}:e.children}),void 0,void 0]}function Jt(t){function e(t,e){}return e.type="xstate.assign",e.assignment=t,e.resolve=At,e}function Rt(t,e,s,n,{event:o,id:i,delay:r},{internalQueue:a}){const c=e.machine.implementations.delays;if("string"==typeof o)throw new Error(`Only event objects may be used with raise; use raise({ type: "${o}" }) instead`);const h="function"==typeof o?o(s,n):o;let u;if("string"==typeof r){const t=c&&c[r];u="function"==typeof t?t(s,n):t}else u="function"==typeof r?r(s,n):r;return"number"!=typeof u&&a.push(h),[e,{event:h,id:i,delay:u},void 0]}function Dt(t,e){const{event:s,delay:n,id:o}=e;"number"!=typeof n||t.defer((()=>{const e=t.self;t.system.scheduler.schedule(e,e,s,n,o)}))}const Ct=(Bt=void 0,{config:Vt=t=>{},transition:(t,e,s)=>({...t,context:Vt(t.context,e,s)}),getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof Bt?Bt({input:e}):Bt}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t});var Vt,Bt;const Lt=new WeakMap;function qt(t,e,s){let n=Lt.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Lt.set(t,n)),n[e]}const Wt={},Gt=t=>"string"==typeof t?{type:t}:"function"==typeof t?"resolve"in t?{type:t.type}:{type:t.name}:t;class Ft{constructor(t,e){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?d(this.config.states,((t,e)=>new Ft(t,{_parent:this,_key:e,_machine:this.machine}))):Wt,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=y(this.config.entry).slice(),this.exit=y(this.config.exit).slice(),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=y(t.tags).slice()}_initialize(){this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=t.config.on[s];e.set(s,m(n).map((e=>X(t,s,e))))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,m(t.config.onDone).map((e=>X(t,s,e))))}for(const s of t.invoke){if(s.onDone){const n=`xstate.done.actor.${s.id}`;e.set(n,m(s.onDone).map((e=>X(t,n,e))))}if(s.onError){const n=`xstate.error.actor.${s.id}`;e.set(n,m(s.onError).map((e=>X(t,n,e))))}if(s.onSnapshot){const n=`xstate.snapshot.${s.id}`;e.set(n,m(s.onSnapshot).map((e=>X(t,n,e))))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),this.config.always&&(this.always=m(this.config.always).map((t=>X(this,"",t)))),Object.keys(this.states).forEach((t=>{this.states[t]._initialize()}))}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(Gt),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map((t=>`#${t.id}`)),source:`#${this.id}`,actions:this.initial.actions.map(Gt),eventType:null})}:void 0,history:this.history,states:d(this.states,(t=>t.definition)),on:this.on,transitions:[...this.transitions.values()].flat().map((t=>({...t,actions:t.actions.map(Gt)}))),entry:this.entry.map(Gt),exit:this.exit.map(Gt),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return qt(this,"invoke",(()=>y(this.config.invoke).map(((t,e)=>{const{src:s,systemId:n}=t,o=t.id??w(this.id,e),i="string"==typeof s?s:`xstate.invoke.${w(this.id,e)}`;return{...t,src:i,id:o,systemId:n,toJSON(){const{onDone:e,onError:s,...n}=t;return{...n,type:"xstate.invoke",src:i,id:o}}}}))))}get on(){return qt(this,"on",(()=>[...this.transitions].flatMap((([t,e])=>e.map((e=>[t,e])))).reduce(((t,[e,s])=>(t[e]=t[e]||[],t[e].push(s),t)),{})))}get after(){return qt(this,"delayedTransitions",(()=>Q(this)))}get initial(){return qt(this,"initial",(()=>function(t,e){const s="string"==typeof e?t.states[e]:e?t.states[e.target]:void 0;if(!s&&e)throw new Error(`Initial state node "${e}" not found on parent state node #${t.id}`);const n={source:t,actions:e&&"string"!=typeof e?y(e.actions):[],eventType:null,reenter:!1,target:s?[s]:[],toJSON:()=>({...n,source:`#${t.id}`,target:s?[`#${s.id}`]:[]})};return n}(this,this.config.initial)))}next(t,e){const s=e.type,n=[];let o;const i=qt(this,`candidates-${s}`,(()=>{return e=s,(t=this).transitions.get(e)||[...t.transitions.keys()].filter((t=>{if("*"===t)return!0;if(!t.endsWith(".*"))return!1;const s=t.split("."),n=e.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e)return t===s.length-1;if(e!==o)return!1}return!0})).sort(((t,e)=>e.length-t.length)).flatMap((e=>t.transitions.get(e)));var t,e}));for(const r of i){const{guard:i}=r,a=t.context;let c=!1;try{c=!i||C(i,a,e,t)}catch(t){const e="string"==typeof i?i:"object"==typeof i?i.type:void 0;throw new Error(`Unable to evaluate guard ${e?`'${e}' `:""}in transition for event '${s}' in state node '${this.id}':\n${t.message}`)}if(c){n.push(...r.actions),o=r;break}}return o?[o]:void 0}get events(){return qt(this,"events",(()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const n=t[s];if(n.states)for(const t of n.events)e.add(`${t}`)}return Array.from(e)}))}get ownEvents(){const t=new Set([...this.transitions.keys()].filter((t=>this.transitions.get(t).some((t=>!(!t.target&&!t.actions.length&&!t.reenter))))));return Array.from(t)}}class Ut{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:e?.actors??{},actions:e?.actions??{},delays:e?.delays??{},guards:e?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new Ft(t,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.implementations;return new Ut(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}})}resolveState(t){const e=(s=this.root,n=t.value,F(s,[...q(nt(s,n))]));var s,n;const o=q(nt(this.root,e));return Tt({_nodes:[...o],context:t.context||{},children:{},status:U(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return St(t,e,s,[]).snapshot}microstep(t,e,s){return St(t,e,s,[]).microstates}getTransitionData(t,e){return ot(this.root,t.value,t,e)||[]}getPreInitialState(t,e,s){const{context:n}=this.config,o=Tt({context:"function"!=typeof n&&n?n:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof n){return _t(o,e,t,[Jt((({spawn:t,event:e,self:s})=>n({spawn:t,input:e.input,self:s})))],s,void 0)}return o}getInitialSnapshot(t,e){const s=a(e),n=[],o=this.getPreInitialState(t,s,n),i=pt([{target:[...tt(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],o,t,s,!0,n),{snapshot:r}=St(i,s,t,n);return r}start(t){Object.values(t.children).forEach((t=>{"active"===t.getSnapshot().status&&t.start()}))}getStateNodeById(t){const e=f(t),s=e.slice(1),n=K(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 st(o,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,tags:n,machine:o,children:i,context:r,can:a,hasTag:c,matches:h,getMeta:u,toJSON:f,...p}=t,d={};for(const t in i){const s=i[t];d[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s._systemId,syncSnapshot:s._syncSnapshot}}return{...p,context:Pt(r),children:d,historyValue:Nt(p.historyValue)}}(t,e)}restoreSnapshot(t,e){const s={},n=t.children;function o(t,e){if(e instanceof Ft)return e;try{return t.machine.getStateNodeById(e.id)}catch{}}Object.keys(n).forEach((t=>{const o=n[t],i=o.snapshot,r=o.src,a="string"==typeof r?x(this,r):r;if(!a)return;const c=T(a,{id:t,parent:e.self,syncSnapshot:o.syncSnapshot,snapshot:i,src:r,systemId:o.systemId});s[t]=c}));const i=function(t,e){if(!e||"object"!=typeof e)return{};const s={};for(const n in e){const i=e[n];for(const e of i){const i=o(t,e);i&&(s[n]??=[],s[n].push(i))}}return s}(this.root,t.historyValue),r=Tt({...t,children:s,_nodes:Array.from(q(nt(this.root,t.value))),historyValue:i},this),a=new Set;return function t(e,s){if(!a.has(e)){a.add(e);for(const n in e){const o=e[n];if(o&&"object"==typeof o){if("xstate$$type"in o&&1===o.xstate$$type){e[n]=s[o.id];continue}t(o,s)}}}}(r.context,s),r}}function Kt(t){return JSON.stringify(t)}function Qt(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 Xt=()=>(t,e)=>de(t,e),Ht=()=>(t,e)=>le(t,e),Yt=t=>{if(t.invoke.length>0)throw new Error("Invocations on test machines are not supported");if(t.after.length>0)throw new Error("After events on test machines are not supported");[...t.entry,...t.exit,...[...t.transitions.values()].flatMap((t=>t.flatMap((t=>t.actions))))].forEach((t=>{if("function"==typeof t&&"resolve"in t&&"number"==typeof t.delay)throw new Error("Delayed actions on test machines are not supported")}));for(const e of Object.values(t.states))Yt(e)};class Zt{getDefaultOptions(){return{serializeState:t=>Kt(t),serializeEvent:t=>Kt(t),serializeTransition:(t,e)=>`${Kt(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:Et(t.state)?`Reaches ${Qt(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=Kt)=>{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(Xt(),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(he(n,e)))}return s}getSimplePaths(t){return this.getPaths(Ht(),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(he(n,e)))}return s}getPathsFromEvents(t,e){return pe(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return ue(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:Kt,serializeEvent:Kt,...s},{formatColor:o,serializeState:i,serializeEvent:r}=n,{state:a}=t,c=i(a,t.steps.length?t.steps[t.steps.length-1].event:void 0);let h="",u=!1;return h+="\nPath:\n"+e.steps.map(((t,e,s)=>{const n=i(t.step.state,e>0?s[e-1].step.event:void 0),a=r(t.step.event);return[`\tState: ${u?o("gray",n):t.state.error?(u=!0,o("redBright",n)):o("greenBright",n)}`,`\tEvent: ${u?o("gray",a):t.event.error?(u=!0,o("red",a)):o("green",a)}`].join("\n")})).concat(`\tState: ${u?o("gray",c):e.state.error?o("red",c):o("green",c)}`).join("\n\n"),h}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),o=this._getStateTestKeys(t,e,n);for(const s of o)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},o=Object.keys(n).filter((t=>s.stateMatcher(e,t)));return!o.length&&"*"in n&&o.push("*"),o}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function te(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=>te(t[s],e[s])))}function ee(t,e,s,{serializeEvent:n}){if(!e||s&&te(s.value,t.value))return"";const o=s?` from ${Kt(s.value)}`:"";return` via ${n(e)}${o}`}function se(){const t=T(Ct);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function ne(t){if(!t.states)return[];return Object.keys(t.states).map((e=>t.states[e]))}function oe(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function ie(t){return JSON.stringify(t)}function re(t,e){const{events:s,...n}=e??{};return{serializeState:oe,serializeEvent:ie,events:t=>{const e="function"==typeof s?s(t):s??[];return b(t).flatMap((t=>{const s=e.filter((e=>e.type===t));return s.length?s:[{type:t}]}))},fromState:t.getInitialSnapshot(se(),e?.input),...n}}function ae(){return{serializeState:t=>JSON.stringify(t),serializeEvent:ie}}function ce(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?re(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:ie,events:[],limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function he(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 ue(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:i,limit:r,fromState:a,stopWhen:c}=ce(t,e),h=se(),u={};let f=0;const p=[{nextState:a??t.getInitialSnapshot(h,e.input),event:void 0,prevState:void 0}],d=new Map;for(;p.length;){const{nextState:t,event:e,prevState:a}=p.shift();if(f++>r)throw new Error("Traversal limit exceeded");const l=o(t,e,a);if(u[l])continue;if(d.set(l,t),u[l]={state:t,transitions:{}},c&&c(t))continue;const y="function"==typeof i?i(t):i;for(const e of y){const o=s(t,e,h);u[l].transitions[n(e)]={event:e,state:o},p.push({nextState:o,event:e,prevState:t})}}return u}function fe(t){let e=[];if(t.steps.length){for(let s=0;s<t.steps.length;s++){const n=t.steps[s];e.push({state:n.state,event:0===s?{type:"xstate.init"}:t.steps[s-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:"xstate.init"}}];return{...t,steps:e}}function pe(t,e,s){const n=ce(t,{events:e,...s},(o=t)&&"__xstatenode"in o?re(t):ae());var o;const i=se(),r=n.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:a,serializeEvent:c}=n,h=ue(t,n),u=new Map,f=[],p=a(r,void 0,void 0);u.set(p,r);let d=p,l=r;for(const t of e){f.push({state:u.get(d),event:t});const e=c(t),{state:s,event:n}=h[d].transitions[e];if(!s)throw new Error(`Invalid transition from ${d} with ${e}`);const o=a(s,t,u.get(d));u.set(o,s),d=o,l=s}return n.toState&&!n.toState(l)?[]:[fe({state:l,steps:f,weight:f.length})]}function de(t,e){const s=ce(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(se(),e?.input),i=ue(t,s),r=new Map,a=new Map,c=n(o,void 0,void 0);a.set(c,o),r.set(c,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(c);for(const t of h){const e=a.get(t),{weight:s}=r.get(t);for(const o of Object.keys(i[t].transitions)){const{state:c,event:f}=i[t].transitions[o],p=n(c,f,e);if(a.set(p,c),r.has(p)){const{weight:e}=r.get(p);e>s+1&&r.set(p,{weight:s+1,state:t,event:f})}else r.set(p,{weight:s+1,state:t,event:f});u.has(p)||h.add(p)}u.add(t),h.delete(t)}const f={},p=[];return r.forEach((({weight:t,state:e,event:s},n)=>{const o=a.get(n),i=e?f[e].paths[0].steps.concat({state:a.get(e),event:s}):[];p.push({state:o,steps:i,weight:t}),f[n]={state:o,paths:[{state:o,steps:i,weight:t}]}})),s.toState?p.filter((t=>s.toState(t.state))).map(fe):p.map(fe)}function le(t,e){const s=ce(t,e),n=se(),o=s.fromState??t.getInitialSnapshot(n,e?.input),i=s.serializeState,r=ue(t,s),a=new Map,c={vertices:new Set,edges:new Set},h=[],u={};function f(t,e){const s=a.get(t);if(c.vertices.add(t),t===e){u[e]||(u[e]={state:a.get(e),paths:[]});const t=u[e],n={state:s,weight:h.length,steps:[...h]};t.paths.push(n)}else for(const s of Object.keys(r[t].transitions)){const{state:n,event:o}=r[t].transitions[s];if(!(s in r[t].transitions))continue;const u=a.get(t),p=i(n,o,u);a.set(p,n),c.vertices.has(p)||(c.edges.add(s),h.push({state:a.get(t),event:o}),f(p,e))}h.pop(),c.vertices.delete(t)}const p=i(o,void 0);a.set(p,o);for(const t of Object.keys(r))f(p,t);const d=Object.values(u).flatMap((t=>t.paths));return s.toState?d.filter((t=>s.toState(t.state))).map(fe):d.map(fe)}t.TestModel=Zt,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=Xt,t.createSimplePathsGen=Ht,t.createTestModel=function(t,e){(t=>{Yt(t.root)})(t);const s=e?.serializeEvent??Kt,n=e?.serializeTransition??ee,{events:o,...i}=e??{};return new Zt(t,{serializeState:(t,e,o)=>`${oe(t)}${n(t,e,o,{serializeEvent:s})}`,stateMatcher:(e,s)=>s.startsWith("#")?e._nodes.includes(t.getStateNodeById(s)):e.matches(s),events:t=>{const e="function"==typeof o?o(t):o??[];return b(t).flatMap((t=>e.some((e=>e.type===t))?e.filter((e=>e.type===t)):[{type:t}]))},...i})},t.getAdjacencyMap=ue,t.getPathsFromEvents=pe,t.getShortestPaths=de,t.getSimplePaths=le,t.getStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce(((e,n)=>{const o=s[n],i=t(o);return e.push(o,...i),e}),[])},t.joinPaths=he,t.serializeSnapshot=oe,t.toDirectedGraph=function t(e){const s=e instanceof Ut?e.root:e,n=[...s.transitions.values()].flat().flatMap(((t,e)=>(t.target?t.target:[s]).map(((n,o)=>{const i={id:`${s.id}:${e}:${o}`,source:s,target:n,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=i;return{source:s.id,target:n.id,label:t}}};return i})))),o={id:s.id,stateNode:s,children:ne(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})})); //# sourceMappingURL=xstate-graph.umd.min.js.map