xstate 6.0.0-alpha.21 → 6.0.0-alpha.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/{StateMachine-3c17fe3e.esm.js → StateMachine-022864fd.esm.js} +183 -64
  2. package/dist/{StateMachine-550ff7f2.development.cjs.js → StateMachine-53114dce.development.cjs.js} +187 -63
  3. package/dist/{StateMachine-1b155670.cjs.js → StateMachine-aad57180.cjs.js} +187 -63
  4. package/dist/{StateMachine-e25dd61f.development.esm.js → StateMachine-d2247245.development.esm.js} +183 -64
  5. package/dist/declarations/src/State.d.ts +4 -2
  6. package/dist/declarations/src/StateMachine.d.ts +5 -4
  7. package/dist/declarations/src/actions.d.ts +10 -8
  8. package/dist/declarations/src/actors/logic.d.ts +5 -21
  9. package/dist/declarations/src/createActor.d.ts +3 -1
  10. package/dist/declarations/src/fsm.d.ts +3 -1
  11. package/dist/declarations/src/index.d.ts +2 -2
  12. package/dist/declarations/src/spawn.d.ts +3 -3
  13. package/dist/declarations/src/stateUtils.d.ts +1 -1
  14. package/dist/declarations/src/system.d.ts +34 -9
  15. package/dist/declarations/src/transitionActions.d.ts +5 -1
  16. package/dist/declarations/src/types.d.ts +70 -51
  17. package/dist/{index-3f87408c.esm.js → index-3609e096.esm.js} +782 -389
  18. package/dist/{index-ec7c7a2d.development.cjs.js → index-41c0375c.development.cjs.js} +790 -390
  19. package/dist/{index-e694228c.cjs.js → index-434fac23.cjs.js} +789 -389
  20. package/dist/{index-d39fb138.development.esm.js → index-f5407323.development.esm.js} +783 -390
  21. package/dist/xstate-actors.cjs.js +1 -1
  22. package/dist/xstate-actors.development.cjs.js +1 -1
  23. package/dist/xstate-actors.development.esm.js +1 -1
  24. package/dist/xstate-actors.esm.js +1 -1
  25. package/dist/xstate-actors.umd.min.js +1 -1
  26. package/dist/xstate-actors.umd.min.js.map +1 -1
  27. package/dist/xstate-graph.cjs.js +2 -2
  28. package/dist/xstate-graph.development.cjs.js +2 -2
  29. package/dist/xstate-graph.development.esm.js +2 -2
  30. package/dist/xstate-graph.esm.js +2 -2
  31. package/dist/xstate-graph.umd.min.js +1 -1
  32. package/dist/xstate-graph.umd.min.js.map +1 -1
  33. package/dist/xstate.cjs.js +82 -103
  34. package/dist/xstate.cjs.mjs +1 -0
  35. package/dist/xstate.development.cjs.js +82 -103
  36. package/dist/xstate.development.cjs.mjs +1 -0
  37. package/dist/xstate.development.esm.js +80 -102
  38. package/dist/xstate.esm.js +80 -102
  39. package/dist/xstate.umd.min.js +1 -1
  40. package/dist/xstate.umd.min.js.map +1 -1
  41. package/package.json +1 -1
@@ -2,8 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var dist_xstateActors = require('./index-e694228c.cjs.js');
6
- var StateMachine = require('./StateMachine-1b155670.cjs.js');
5
+ var dist_xstateActors = require('./index-434fac23.cjs.js');
6
+ var StateMachine = require('./StateMachine-aad57180.cjs.js');
7
7
 
8
8
  function simpleStringify(value) {
9
9
  return JSON.stringify(value);
@@ -2,8 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var dist_xstateActors = require('./index-ec7c7a2d.development.cjs.js');
6
- var StateMachine = require('./StateMachine-550ff7f2.development.cjs.js');
5
+ var dist_xstateActors = require('./index-41c0375c.development.cjs.js');
6
+ var StateMachine = require('./StateMachine-53114dce.development.cjs.js');
7
7
 
8
8
  function simpleStringify(value) {
9
9
  return JSON.stringify(value);
@@ -1,5 +1,5 @@
1
- import { k as isMachineSnapshot, n as getAllOwnEventDescriptors, w as createEmptyActor, X as XSTATE_INIT } from './index-d39fb138.development.esm.js';
2
- import { S as StateMachine } from './StateMachine-e25dd61f.development.esm.js';
1
+ import { q as isMachineSnapshot, u as getAllOwnEventDescriptors, C as createEmptyActor, X as XSTATE_INIT } from './index-f5407323.development.esm.js';
2
+ import { S as StateMachine } from './StateMachine-d2247245.development.esm.js';
3
3
 
4
4
  function simpleStringify(value) {
5
5
  return JSON.stringify(value);
@@ -1,5 +1,5 @@
1
- import { k as isMachineSnapshot, n as getAllOwnEventDescriptors, w as createEmptyActor, X as XSTATE_INIT } from './index-3f87408c.esm.js';
2
- import { S as StateMachine } from './StateMachine-3c17fe3e.esm.js';
1
+ import { q as isMachineSnapshot, u as getAllOwnEventDescriptors, C as createEmptyActor, X as XSTATE_INIT } from './index-3609e096.esm.js';
2
+ import { S as StateMachine } from './StateMachine-022864fd.esm.js';
3
3
 
4
4
  function simpleStringify(value) {
5
5
  return JSON.stringify(value);
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateGraph={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="@xstate.init",n="@xstate.stop";function o(t,e){return{type:`xstate.after.${t}.${e}`}}function i(t){return{type:`xstate.timeout.actor.${t}`}}function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function c(t,e){return{type:`xstate.error.${t}`,error:e}}function a(t){return{type:s,input:t}}function h(t){setTimeout(()=>{throw t})}const u="function"==typeof Symbol&&Symbol.observable||"@@observable",f={"@xstate.spawn":t=>{},"@xstate.start":t=>{t.start()},"@xstate.raise":(t,e,s)=>{t.system.scheduler.schedule(t.self,t.self,e,s?.delay??0,s?.id)},"@xstate.sendTo":(t,e,s,n)=>{if("string"==typeof s)throw new Error("Only event objects may be used with sendTo");void 0!==n?.delay?t.system.scheduler.schedule(t.self,e,s,n?.delay??0,n?.id):t.defer(()=>{t.system._relay(t.self,e,s)})},"@xstate.cancel":(t,e)=>{t.system.scheduler.cancel(t.self,e)},"@xstate.stop":(t,e)=>{t.stopChild(e)}},p=new WeakMap;function l(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 i=t(e.input,{self:s,system:n});if(!i)return;let r,c=!1;const a=()=>{c||(c=!0,i.unsubscribe(),r?.unsubscribe())},h=s._parent;h&&(r=h.subscribe({complete:a,error:a})),p.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===n?(p.get(s)?.unsubscribe(),p.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:e,getInitialSnapshot:(t,s)=>e(s)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function d(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function y(){return l(({actor:t,eventType:e,mapper:s},{self:n,system:o})=>{const i="*"!==e&&e.endsWith(".*");return t.on(i?"*":e,t=>{i&&!Kt(t.type,e)||d(n,o,()=>s(t))})})}const g=y();function v(){return l(({actor:t,mappers:e},{self:s,system:n})=>{const{done:o,error:i,snapshot:r}=e;return t.subscribe({next:t=>{"done"===t.status&&o?d(s,n,()=>o(t.output)):"error"===t.status&&i?d(s,n,()=>i(t.error)):"active"===t.status&&r&&d(s,n,()=>r(t))},error:t=>{i&&d(s,n,()=>i(t))},complete:()=>{}})})}const m=v(),_=Symbol("xstate.builtInExecutableAction");function S(t){return Object.defineProperty(t,_,{value:!0}),t}function x(t,e){return{...t,...e}}function b(t,e,...s){t.push({action:e,args:s})}function w(t,e,s){b(t,f["@xstate.spawn"],e),t.push(function(t,e){return Object.assign(function(s){return{children:{...s.children,[e]:t}}},{_special:!0})}(e,s??e.id))}function E(t,e,s,n=!1,o=!0){const i={cancel:s=>{b(e,f["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{b(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?b(e,f["@xstate.raise"],t,n,o):s.push(n)},spawn:(s,n)=>{if(!o)return{id:n?.id??n?.registryKey??s.id};const i=Xt(s,{...n,parent:t.self});return w(e,i,n?.id),i},sendTo:(n,o,i)=>{n?b(e,f["@xstate.sendTo"],t,n,o,i):s.push(c("communication",{message:"Unable to send event to an undefined actor",event:o}))},stop:s=>{s&&(b(e,f["@xstate.stop"],t,s),e.push(function(t){return Object.assign(function(e){const s={...e.children};for(const e of Object.keys(s))s[e]===t&&delete s[e];return{children:s}},{_special:!0})}(s)))}};return n&&Object.assign(i,{listen:(s,n,o)=>{const i=Xt(g,{input:{actor:s,eventType:n,mapper:o},parent:t.self});return b(e,f["@xstate.spawn"],i),i},subscribeTo:(s,n)=>{const o=Xt(m,{input:{actor:s,mappers:"function"==typeof n?{snapshot:n}:n},parent:t.self});return b(e,f["@xstate.spawn"],o),o}}),T(i,(t,...s)=>{b(e,t,...s)})}function k(t,e){switch(t){case f["@xstate.spawn"]:{const[t]=e;return{actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case f["@xstate.raise"]:{const[,t,s]=e;return{event:t,id:s?.id,delay:s?.delay}}case f["@xstate.sendTo"]:{const[,t,s,n]=e;return{target:t,event:s,id:n?.id,delay:n?.delay}}case f["@xstate.cancel"]:{const[,t]=e;return{id:t}}case f["@xstate.stop"]:{const[,t]=e;return{actor:t}}default:return}}function $(t){const e=f["@xstate.start"],s=[t];return S({type:"@xstate.start",params:{action:e,args:s},args:s,exec:e.bind(null,t),actor:t,id:t.id})}function j(t){const e=[],s=[];for(const n of t){if(!I(n)||"@xstate.spawn"!==n.type)continue;const{actor:t,logic:o}=n,i=$(t);o===g||o===m?e.push(i):s.push(i)}return[...e,...s]}function I(t){return!0===t[_]}function O(t,e,s,n){let o=t;const i=[];for(const r of n){const n="function"==typeof r?r:"object"==typeof r&&"action"in r&&"function"==typeof r.action&&r.action.bind(null,...r.args),c={context:o.context,event:e,output:At(e),self:s.self,system:s.system,children:o.children,parent:s.self._parent,actions:t.machine.implementations.actions,actorSources:t.machine.implementations.actorSources};let a;if("object"==typeof r&&null!==r){const{type:t,...e}=r;a=e}if(n&&"_special"in n){i.push({type:"object"==typeof r?"action"in r&&"function"==typeof r.action?r.action.name??"(anonymous)":r.type??"(anonymous)":r.name||"(anonymous)",params:a,args:[],exec:void 0});const t=n(c,M);t&&("context"in t||"children"in t)&&(o={...o,...void 0!==t.context?{context:x(o.context,t.context)}:{},..."children"in t?{children:t.children}:{}});continue}if(!n||!("resolve"in n)){const t="object"==typeof r&&null!==r&&"action"in r&&"function"==typeof r.action?k(r.action,r.args):void 0,e={type:"object"==typeof r?"action"in r&&"function"==typeof r.action?r.action.name??"(anonymous)":r.type:r.name||"(anonymous)",params:a,args:"object"==typeof r&&"action"in r?r.args:[],exec:n||("object"==typeof r&&null!==r?()=>s.defer(()=>s.emit(r)):void 0),...t};i.push(t?S(e):e);continue}}return[o,i]}function T(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 M=T({},()=>{});function A(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const n=e.match(/^(\d*)(\.?)(\d*)s$/i);if(n){const t=n[1]?parseInt(n[1],10):0,e=!!n[2],s=n[3]?parseInt(n[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:i,days:r,hours:c,minutes:a,seconds:h}=o.groups;if(!(i||r||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(i)*24*60*60*1e3+24*u(r)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)??t}function P(t,e,s){if("function"==typeof t)return t(s);const n=A(t,e);return"function"==typeof n?n(s):n}function N(t,e){return t._stateInputs?.[e]}function z(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function D(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function R(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 J(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 D(t))if(!e.has(s)){const t=G(s);for(const s of t)e.add(s)}}else for(const s of G(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 K(t,e){const s=J(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(z(t))return t.key}const s={};for(const t of e)s[t.key]=o(t);return s};return o(t)}function B(t,e){return"compound"===e.type?D(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?D(e).every(e=>B(t,e)):"final"===e.type}const V=t=>"#"===t[0];function W(t,e,s){const n=e.type,o=t.entry;t.entry=(t,i)=>(i.raise(e,{id:n,delay:s(t)}),"function"==typeof o?o(t,i):void 0);const i=t.exit;return t.exit=(t,e)=>(e.cancel(n),"function"==typeof i?i(t,e):void 0),n}function C(t,e,s){const n=zt(s.target),o=s.reenter??!1,i=L(t,n),r={...s,target:i,source:t,reenter:o,eventType:e,toJSON:()=>({...r,source:`#${t.id}`,target:i?i.map(t=>`#${t.id}`):void 0})};return r}function L(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(V(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return U(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return U(t.parent,n)}catch(e){throw new Error(`Invalid transition for '${t.id}': ${e.message}`)}})}function q(t){const e=zt(t.config.target);return e?{target:e.map(e=>"string"==typeof e?U(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 F(t){return"history"===t.type}function G(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 D(s))t(e)}(t);for(const s of e)for(const n of R(s,t))e.add(n);return e}function H(t,e){if(V(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 U(t,e){if("string"==typeof e&&V(e))try{return t.machine.getStateNodeById(e)}catch{}const s=jt(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=H(n,t)}return n}function X(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=new Array(s.length),o=[t.machine.root,t];for(let e=0;e<s.length;e++){const i=H(t,s[e]);n[e]=i,o.push(i)}for(let t=0;t<s.length;t++)o.push(...X(n[t],e[s[t]]));return o}function Q(t,e,s,n,o){if("string"==typeof e){const i=H(t,e).next(s,n,o);return i&&i.length?i:t.next(s,n,o)}const i=Object.keys(e),r=i[0];if(1===i.length){const i=Q(H(t,r),e[r],s,n,o);return i&&i.length?i:t.next(s,n,o)}const c=[];for(const r of i){const i=e[r];if(!i)continue;const a=Q(H(t,r),i,s,n,o);a&&c.push(...a)}return c.length?c:t.next(s,n,o)}function Y(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function Z(t,e){for(const s of t)if(Y(s,e))return!0;return!1}function tt(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 et(t,e,s,n,o){const i=new Set,r=new Map,c=t=>{let i=r.get(t);return i||(i=it([t],e,s,n,o),r.set(t,i)),i};for(const e of t){let t=!1;const s=new Set;for(const n of i)if(tt(c(e),c(n)))if(Y(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)i.delete(t);i.add(e)}}return Array.from(i)}function st(t,e,s,n){const o=e.historyValue,{targets:i}=ct(t,e,s,n,{resolveActions:!1});if(!i)return[];const r=new Set;for(const t of i)if(F(t))if(o[t.id])for(const e of o[t.id])r.add(e);else for(const o of st(q(t),e,s,n))r.add(o);else r.add(t);return[...r]}function nt(t,e){let s=t;for(;"parallel"===s.type;){const t=D(s).find(t=>e.every(e=>e===t||Y(e,t)));if(!t)break;s=t}return s}function ot(t,e,s,n){const o=st(t,e,s,n),{reenter:i}=ct(t,e,s,n,{resolveActions:!1});if(o.every(e=>e===t.source||Y(e,t.source)))return i?t.source:nt(t.source,o);const[r,...c]=o.concat(t.source);for(const t of R(r,void 0))if(c.every(e=>Y(e,t)))return i?t:nt(t,o);return i?void 0:nt(t.source.machine.root,o)}function it(t,e,s,n,o){const i=new Set;for(const r of t){const{targets:t,reenter:c}=ct(r,s,n,o,{resolveActions:!1});if(t?.length){const t=ot(r,s,n,o);c&&r.source===t&&i.add(t);for(const s of e)Y(s,t)&&i.add(s)}}return[...i]}function rt(t,e,s,n,o,i){const c=[];if(!t.length)return[e,c];{const a=new Set(e._nodes);let h=e.historyValue;const u=e.context,p=et(t,a,e,n,s),l=t=>ct(t,e,n,s),d=(t,o,i,r)=>{if(2===t.length){const c=[],a=[];let h;const u=E(s,c,a,!0),f=t({context:o,event:n,parent:s.self._parent,self:s.self,children:i,system:s.system,actions:e.machine.implementations.actions,actorSources:e.machine.implementations.actorSources,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays,input:r},u);return void 0!==f?.context&&(h=x(o,f.context)),[c,h,a]}return[[Object.assign((e,s)=>t({...e,input:r},s),"_special"in t?{_special:!0}:{})],void 0,void 0]};let y=e;const g=()=>{const t=it(p,a,e,n,s);let o;t.sort((t,e)=>e.order-t.order);const r=[...a];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>z(t)&&Y(t,e):t=>t.parent===e;o??={...h},o[t.id]=r.filter(s)}for(const o of t){const t=N(e,o.id),[r,h,u]=o.exit?d(o.exit,y.context,e.children,t):[[]];u?.length&&i.push(...u),h&&(y=wt(y,{context:h}));const[f,p]=O(y,n,s,r);y=f,c.push(...p);for(const t of o.invoke){const e=y.children[t.id];e&&!e._isExternal&&s.stopChild(e),delete y.children[t.id]}a.delete(o)}h=o||h};o||g();let v=y.context;const m=[],_=[];for(const t of p){t.actions&&m.push(...Tt(t.actions));const e=l(t);void 0!==e.context&&(v=x(v,e.context)),e.actions&&m.push(...e.actions),e.internalEvents&&_.push(...e.internalEvents)}_.length&&i.push(..._);const S=()=>{const t=t=>{const e=y.machine.root;let o;if(void 0!==t.output&&t.parent){const r=i.find(t=>t.type===`xstate.done.state.${e.id}`);o=r&&t.parent===e?r.output:Mt(t.output,y.context,n,s.self,_[t.id])}else if("parallel"===t.type){const e=`xstate.done.state.${t.id}`,s=i.find(t=>t.type===e);o=s?.output}return void 0===e.output?t.parent===e?o:void 0:Mt(e.output,y.context,r(t.id,o),s.self)},u=new Set,g=new Set,v=(t,e)=>{for(const s of t)if(e&&!Y(s,e)||u.add(s),"parallel"===s.type)for(const t of D(s))Z(u,t)||(u.add(t),m(t))},m=t=>{if(F(t))if(h[t.id]){const e=h[t.id];for(const t of e)u.add(t),m(t);for(const s of e)v(R(s,t.parent),void 0)}else{const e=q(t),{targets:s}=l(e);for(const n of s??[])u.add(n),e===t.parent?.initial&&g.add(t.parent),m(n);for(const e of s??[])v(R(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=l(t.initial).targets;return F(e)||(u.add(e),g.add(e)),m(e),void v(R(e,t),void 0)}if("parallel"===t.type)for(const e of D(t))Z(u,e)||(u.add(e),g.add(e),m(e))}};for(const t of p){const o=ot(t,e,n,s),{targets:i,reenter:r}=ct(t,e,n,s,{resolveActions:!1});for(const e of i??[])F(e)||t.source===e&&t.source===o&&!r||(u.add(e),g.add(e)),m(e);const c=st(t,e,n,s);for(const e of c){const s=R(e,o);"parallel"===o?.type&&s.push(o),v(s,!t.source.parent&&r?void 0:o)}r&&o===t.source&&u.add(t.source)}o&&g.add(e.machine.root);const _={...e._stateInputs};let S=!1;for(const t of p){const{targets:o,input:i}=ct(t,e,n,s,{resolveActions:!1});if(i&&o)for(const t of o)_[t.id]=i,S=!0}const x=new Set,b={...e.children};for(const o of[...u].sort((t,e)=>t.order-e.order)){a.add(o);const h=[];let u=!1;for(const t of o.invoke){u=!0;let o=t.logic;"function"==typeof o&&(o=o({actorSources:e.machine.implementations.actorSources,context:y.context,event:n,self:s.self}));const i="string"==typeof o?Rt(e.machine,o):o;if(!i)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented`);const r="function"==typeof t.input?t.input({self:s.self,context:y.context,event:n,output:At(n)}):t.input,c=Xt(i,{...t,input:r,parent:s.self,syncSnapshot:!!t.onSnapshot});h.push({action:f["@xstate.spawn"],args:[c]}),t.id&&(b[t.id]=c)}u&&(y=wt(y,{children:b}));let p=y.context,l=!1;const v=_[o.id];if(o.entry){const[t,e,s]=d(o.entry,p,b,v);h.push(...t),s?.length&&i.push(...s),e&&(p=e,l=!0)}if(l&&(y.context=p),g.has(o)){const{actions:t,input:e}=ct(o.initial,y,n,s);if(t&&h.push(...t),e&&o.initial?.target)for(const t of o.initial.target)_[t.id]=e,S=!0}const[m,w]=O(y,n,s,h);if(y=m,h.length=0,c.push(...w),"final"!==o.type)continue;const E=o.parent;let k="parallel"===E?.type?E:E?.parent,$=k||o;for("compound"===E?.type&&i.push(r(E.id,void 0!==o.output?Mt(o.output,y.context,n,s.self,v):void 0));"parallel"===k?.type&&!x.has(k)&&B(a,k);){x.add(k);const t={};for(const e of D(k)){if("final"===e.type){t[e.key]=void 0!==e.output?Mt(e.output,y.context,n,s.self,_[e.id]):void 0;continue}if("parallel"===e.type){const s=`xstate.done.state.${e.id}`,n=i.find(t=>t.type===s);t[e.key]=n?.output;continue}const o=D(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==o?.output?Mt(o.output,y.context,n,s.self,_[o.id]):void 0}i.push(r(k.id,t)),$=k,k=k.parent}k||(y=wt(y,{status:"done",output:t($)}))}S&&(y=wt(y,{_stateInputs:_}))},[b,w]=O(y,n,s,m);y=b,c.push(...w),v&&v!==e.context&&(y=wt(y,{context:v})),S();const k=[...a];if("done"===y.status){const t=[];k.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=N(y,e.id),[n,,o]=d(e.exit,y.context,y.children,s);t.push(...n),o?.length&&i.push(...o)}});const[e,o]=O(y,n,s,t);y=e,c.push(...o)}return h===e.historyValue&&e._nodes.length===a.size&&e._nodes.every(t=>a.has(t))?y.context!==u?[wt(y),c]:[y,c]:[wt(y,{_nodes:k,historyValue:h}),c]}}function ct(t,e,s,n,o){const i={context:e.context,event:s,output:At(s),value:e.value,children:e.children,system:n.system,parent:n.self._parent,self:n.self,actions:e.machine.implementations.actions,actorSources:e.machine.implementations.actorSources,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays,input:N(e,t.source.id)};if(t.to){const r=[],c=[],a=E(n,r,c,!1,o?.resolveActions??!0),h=t.to(i,a),u=h?.target?L(t.source,Tt(h.target)):void 0,f=h?.input??("function"==typeof t.input?t.input({context:e.context,event:s,output:At(s)}):t.input);return{targets:u,context:h?.context,reenter:h?.reenter,actions:r,internalEvents:c,input:f}}const r="function"==typeof t.input?t.input({context:e.context,event:s,output:At(s)}):t.input,c="function"==typeof t.context?t.context(i):t.context;return{targets:t.target,context:c,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:r}}function at(t,e,o,i){let r=t;const c=[];function a(t,e){const s=o.self._collectedMicrosteps||[];s.push(...e),o.self._collectedMicrosteps=s,c.push(t)}if(e.type===n)return r=wt(ft(r,o),{status:"stopped"}),a([r,[]],[]),{snapshot:r,microsteps:c};let h=e;if(h.type!==s){const e=h,s=function(t){return t.type.startsWith("xstate.error.")}(e),n=r.machine.getTransitionData(r,e,o.self);if(s&&!n.length)return r=wt(t,{status:"error",error:e.error}),a([r,[]],[]),{snapshot:r,microsteps:c};const u=rt(n,t,o,h,!1,i);r=u[0],a(u,n)}let u=!0;const f=t.machine.options?.maxIterations??1/0;let p=0,l=0;for(;"active"===r.status;){if(l++,l>1e3)throw new Error("Microstep count exceeded 1000");if(p++,p>f)throw new Error(`Infinite loop detected (>${f} microsteps)`);let t=u?pt(r,h,o):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;h=i.shift(),t=r.machine.getTransitionData(r,h,o.self)}const s=rt(t,r,o,h,!1,i);r=s[0],u=r!==e,a(s,t)}return"active"!==r.status&&r.children&&ft(r,o),{snapshot:r,microsteps:c}}function ht(t,e,s,n,o){return!!t.to&&ut(t.to,e,s,n,o,n.machine.implementations,t.source.id)}function ut(t,e,s,n,o,i,r){let c,a=!1;try{const h=()=>{throw a=!0,new Error("Effect triggered")};c=t({context:e,event:s,output:At(s),self:o,system:o.system,value:n.value,children:n.children,parent:{send:h},actions:i.actions,actorSources:i.actorSources,guards:i.guards,delays:i.delays,input:N(n,r)},T({emit:h,cancel:h,log:h,raise:h,spawn:h,sendTo:h,stop:h},h))}catch(t){if(a)return!0;throw t}return void 0!==c}function ft(t,e){let s;if(!t.children||0===(s=Object.values(t.children).filter(Boolean)).length)return t;for(const t of s)e.stopChild(t);return wt(t,{children:{}})}function pt(t,e,s){const n=new Set,o=t._nodes.filter(z);for(const i of o)t:for(let o=i;o;o=o.parent)if(o.always)for(const i of o.always)if(lt(i,e,t,o,s.self)){n.add(i);break t}return et(Array.from(n),new Set(t._nodes),t,e,s)}function lt(t,e,s,n,o){if(t.guard){const i={context:s.context,event:e,output:At(e),self:o,parent:o._parent,children:s.children,actions:n.machine.implementations.actions,actorSources:n.machine.implementations.actorSources,guards:n.machine.implementations.guards,delays:n.machine.implementations.delays,_snapshot:s};if(!t.guard(i))return!1}return!t.to||ut(t.to,s.context,e,s,o,n.machine.implementations,t.source.id)}function dt(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const yt=function(t){return $t(t,this.value)},gt=function(t){return this.tags.has(t)},vt=function(t){return this.machine?._canTransition(this,t)??!1},mt=function(){const{_nodes:t,_stateInputs:e,tags:s,machine:n,getMeta:o,getInputs:i,toJSON:r,can:c,hasTag:a,matches:h,...u}=this;return{...u,tags:Array.from(s)}},_t=function(){const t={};for(const e of this._nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},St=function(){return this._stateInputs};function xt(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function bt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:t.value??K(e.root,t._nodes),tags:xt(t._nodes),children:t.children,historyValue:t.historyValue||{},_stateInputs:t._stateInputs||{},matches:yt,hasTag:gt,can:vt,getMeta:_t,getInputs:St,toJSON:mt}}function wt(t,e={}){const s={...t,...e};return(e._nodes??t._nodes)===t._nodes?{status:s.status,output:s.output,error:s.error,machine:t.machine,context:s.context,_nodes:t._nodes,value:t.value,tags:t.tags,children:s.children,historyValue:s.historyValue||{},_stateInputs:s._stateInputs||{},matches:yt,hasTag:gt,can:vt,getMeta:_t,getInputs:St,toJSON:mt}:bt({...s,value:void 0},t.machine)}function Et(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 kt(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:Wt,id:n.id};else{const o=kt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function $t(t,e){const s=It(t),n=It(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&$t(s[t],n[t]))}function jt(t){if(Pt(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 It(t){if(dt(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}(jt(t))}function Ot(t){return Pt(t)?t:[t]}function Tt(t){return void 0===t?[]:Ot(t)}function Mt(t,e,s,n,o){if("function"==typeof t){return t({context:e,event:s,output:At(s),self:n,input:o})}return t}function At(t){if(function(t){return t.type.startsWith("xstate.done.actor.")||t.type.startsWith("xstate.done.state.")}(t)){return t.output}}function Pt(t){return Array.isArray(t)}function Nt(t){return Ot(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function zt(t){if(void 0!==t&&""!==t)return Tt(t)}function Dt(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 Rt(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actorSources[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke,r=(Array.isArray(i)?i[n]:i).src;return"string"==typeof r?t.implementations.actorSources[r]:r}function Jt(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]}function Kt(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}function Bt(t,e){return`${t.sessionId}.${e}`}let Vt=!1;const Wt=1;let Ct=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Lt={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)};function qt(t,e){try{t?.(e)}catch(t){h(t)}}function Ft(t){return"object"==typeof t&&null!==t&&"args"in t&&"exec"in t}function Gt(t,e){if(!t?.length)return[];const s=[];for(const n of t)Ft(n)?e.actionExecutor(n):s.push(n);return s}class Ht{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=this._process.bind(this),this.mailbox=new e(this._boundProcess),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=Ct.NotStarted,this._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._pendingEffects=void 0;const n={...Lt,...s},{clock:o,logger:i,parent:r,syncSnapshot:c,id:a,registryKey:h,inspect:u}=n;this.system=r?r.system:n._systemRef?.current??function(t,e){let s=0;const n=new Map,o=new Map,i=new WeakMap,r=new Set,c={},{clock:a,logger:h}=e,u=(t,e,s,n,o)=>{r.size&&t&&(t._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:o})},f={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{u(t,e,s,n,o);const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},r=Bt(t,o);l._snapshot._scheduledEvents[r]=i;const h=a.setTimeout(()=>{delete c[r],delete l._snapshot._scheduledEvents[r],p(t,e,s)},n);c[r]=h},cancel:(t,e)=>{const s=Bt(t,e),n=c[s];delete c[s],delete l._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in l._snapshot._scheduledEvents){const s=l._snapshot._scheduledEvents[e];s.source===t&&f.cancel(t,s.id)}}},p=(t,e,s)=>{const n=e.logic;if("function"==typeof n?.isInternalEventType&&n.isInternalEventType(s.type)&&t!==e)throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`);e._lastSourceRef=t,e._send(s)},l={children:n,reverseKeyedActors:i,keyedActors:o,_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+s++,_register:(t,e)=>(n.set(t,e),t),_unregister:t=>{n.delete(t.sessionId);const e=i.get(t);void 0!==e&&(o.delete(e),i.delete(t))},get:t=>o.get(t),getAll:()=>Object.fromEntries(o.entries()),_set:(t,e)=>{const s=o.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${t}' already exists.`);o.set(t,e),i.set(e,t)},inspect:t=>{const e=Dt(t);return r.add(e),{unsubscribe(){r.delete(e)}}},_sendInspectionEvent:e=>{if(!r.size)return;const s={...e,rootId:t.sessionId};r.forEach(t=>t.next?.(s))},_relay:(t,e,s)=>{u(t,e,s),p(t,e,s)},scheduler:f,getSnapshot:()=>({_scheduledEvents:{...l._snapshot._scheduledEvents}}),start:()=>{const t=l._snapshot._scheduledEvents;l._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];f.schedule(s,n,o,i,r)}},_clock:a,_logger:h,_timerStrategy:e.timers};return l}(this,{clock:o,logger:i,timers:n.timers}),r||!n._systemRef||n._systemRef.current||(n._systemRef.current=this.system),u&&!r&&this.system.inspect(Dt(u)),this.sessionId=this.system._bookId(),this.id=a??this.sessionId,this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=r,this._syncSnapshot=c,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=>{for(const e of[this.eventListeners.get(t.type),this.eventListeners.get("*")])if(e)for(const s of e)qt(s,t)},actionExecutor:t=>{const e=()=>{if(this._collectedActions.push({type:t.type,params:t.params}),!t.exec)return;const e=Vt;try{Vt=!0,t.exec()}finally{Vt=e}};this._processingStatus!==Ct.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=[];let f=s?.snapshot??s?.state;if(f&&"object"==typeof f&&"_pendingEffects"in f){const{_pendingEffects:t,...e}=f;this._pendingEffects=t,f=e}try{if(f)this._snapshot=this.logic.restoreSnapshot?this.logic.restoreSnapshot(f,this._actorScope):f;else if(s?._inert);else{const[t,e]=this.logic.initialTransition(this.options?.input,this._actorScope);this._snapshot=t,this._initialEffects=e}}catch(t){this._snapshot={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})}_setErrorSnapshot(t,e=this._snapshot){this._snapshot={...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]=this.logic.transition(e,s,this._actorScope);this._snapshot=t;const o=Gt(n,this._actorScope);return this.update(t,s),this.logic.executeEffects?.(o,this._actorScope),!0}catch{return!1}}_next(t){for(const e of this.observers)qt(e.next,t)}update(t,e){this._snapshot=t;for(let e=0;e<this._deferred.length;e++){const s=this._deferred[e];try{s()}catch(e){if(this._deferred.length=0,this._tryHandleExecutionError(e,t))return;this._setErrorSnapshot(e,t);break}}switch(this._deferred.length=0,this._snapshot.status){case"active":this._next(t);break;case"done":{this._next(t),this._stopProcedure(),this._complete();const e=(s=this.id,n=this._snapshot.output,{type:`xstate.done.actor.${s}`,output:n,actorId:s});this._parent&&this.system._relay(this,this._parent,e);break}case"error":this._error(this._snapshot.error)}var s,n;this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps,actions:this._collectedActions,sent:this._collectedSent,eventType:e.type}),this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[]}_flushInitialEffects(){if(!this._initialEffects)return!0;this._forceDeferredActions=!0;try{const t=Gt(this._initialEffects,this._actorScope);return this.logic.executeEffects?.(t,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=Dt(t,e,s);if(this._processingStatus!==Ct.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":qt(n.complete);break;case"error":{const t=this._snapshot.error;n.error?qt(n.error,t):h(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);return s||(s=new Set,this.eventListeners.set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,o)=>{const i=Dt(s,n,o);let r=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(r,n)||(r=n,i.next?.(n))},error:i.error,complete:i.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===Ct.Running)return this;if(this._processingStatus===Ct.Stopped)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.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=Ct.Running;const t=a(this.options.input);this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return 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.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(!this._flushInitialEffects())return this;if(this.update(this._snapshot,t),this._pendingEffects){const t=this.options.timers??this.system._timerStrategy??"resume";for(const e of this._pendingEffects)"@xstate.raise"===e.type&&this.system.scheduler.schedule(this,this,e.event,Ut(t,e),e.id);this._pendingEffects=void 0}return this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s)return void this._recoverOrError(s.err);let o=this._snapshot;try{const[s,n]=e;o=s,this._snapshot=o;const i=Gt(n,this._actorScope);this.update(o,t),this.logic.executeEffects?.(i,this._actorScope)}catch(t){return void this._recoverOrError(t,o)}t.type===n&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===Ct.Stopped?this:(this.mailbox.clear(),this._processingStatus===Ct.NotStarted?(this._processingStatus=Ct.Stopped,this):(this.mailbox.enqueue({type:n}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)qt(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,qt(n,t)}this.observers.clear(),e&&h(t)}else this._parent||h(t);var e;this.eventListeners.clear(),this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${e=this.id}`,error:t,actorId:e})}_stopProcedure(){this._processingStatus===Ct.Running&&(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._boundProcess),this._processingStatus=Ct.Stopped,this.system._unregister(this))}_send(t){this._processingStatus!==Ct.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$$type:Wt,id:this.id}}getPersistedSnapshot(t){const e=this.logic.getPersistedSnapshot(this._snapshot,t),s=this.system._snapshot._scheduledEvents;let n;const o=Date.now();for(const t in s){const e=s[t];e.source===this&&e.target===this&&(n??=[]).push({type:"@xstate.raise",event:e.event,id:e.id,delay:e.delay,startedAt:e.startedAt,elapsed:Math.max(0,o-e.startedAt)})}return n??=this._pendingEffects,n?{...e,_pendingEffects:n}:e}[u](){return this}getSnapshot(){return this._snapshot}}function Ut(t,e){if("function"==typeof t)return t(e);switch(t){case"restart":return e.delay;case"absolute":return Math.max(0,e.startedAt+e.delay-Date.now());default:return Math.max(0,e.delay-e.elapsed)}}function Xt(t,e){return new Ht(t,e)}const Qt=new WeakMap;function Yt(t){let e=Qt.get(t);return e||(e=new Map,Qt.set(t,e)),e}function Zt(t,e){if(t?.length)for(const s of t)switch(s.type){case"emit":e.emit(s.event);break;case"sendBack":{const t=e.self._parent;t&&e.system._relay(e.self,t,s.event);break}case"raise":e.system._relay(e.self,e.self,s.event);break;case"effect":{if(!s.key){const t=s.exec();"function"==typeof t&&Yt(e.self).set(Symbol(),{cleanup:t});break}const t=Yt(e.self);if(t.has(s.key))break;const n=s.exec();t.set(s.key,{cleanup:"function"==typeof n?n:void 0});break}case"cleanupEffects":{const t=Qt.get(e.self);if(!t)break;for(const{cleanup:e}of t.values())e?.();Qt.delete(e.self);break}}}function te(t){const e=(e,s,o)=>{if("active"!==e.status)return[e,[]];if(s.type===n)return[{...e,status:"stopped",input:void 0},[{type:"cleanupEffects"}]];if("xstate.logic.effect.start"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if("xstate.logic.effect.resolve"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if("xstate.logic.effect.reject"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const i=[],r={},c={emit:t=>{i.push({type:"emit",event:t})},sendBack:t=>{i.push({type:"sendBack",event:t})},raise:t=>{i.push({type:"raise",event:t})},effect:(t,s)=>{if("string"==typeof t)return n=t,o=s,void(e.effects?.[n]||(i.push({type:"effect",key:n,exec:o}),r[n]={status:"active"}));var n,o;i.push({type:"effect",exec:t})}},a=t.run({context:e.context,event:s,input:e.input,system:o.system,self:o.self,emit:o.emit},c),h={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(h.context=a?.context??e.context),(a?.effects||Object.keys(r).length)&&(h.effects={...e.effects,...a?.effects,...r}),[h,i]},s={id:t.id,config:t,transition:e,start:(t,s)=>{const[n,o]=e(t,a(t.input),s);Object.assign(t,n),Zt(o,s)},initialTransition:(e,s)=>{const n=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),o={status:"active",output:void 0,error:void 0,input:e};return void 0!==n&&(o.context=n),[{...o},[]]},getInitialSnapshot:(t,e)=>s.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t,executeEffects:Zt};return s}const ee=te({context:void 0,run:()=>{}});function se(t,{machine:e,context:s},n,o){return(i,r)=>{const c=((i,r)=>{if("string"==typeof i){const c=Rt(e,i);if(!c)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const a=Xt(c,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:s,event:n,self:t.self}):r?.input,src:i,registryKey:r?.registryKey});return o[a.id]=a,a}return Xt(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,registryKey:r?.registryKey})})(i,r);return o[c.id]=c,t.defer(()=>{c._processingStatus!==Ct.Stopped&&c.start()}),c}}const ne=new WeakMap;function oe(t,e,s){let n=ne.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},ne.set(t,n)),n[e]}const ie={};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 i=n[o];s[i]=e(t[i],i,t,o)}return s}(this.config.states,(t,e)=>new re(t,{_parent:this,_key:e,_machine:this.machine})):ie,"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=Tt(t.tags).slice(),this.invoke=Tt(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,o=(i=this.id,`${e}.${i}`);var i;const r=t.id??o,c="string"==typeof s?s:`xstate.invoke.${o}`;return{...t,src:c,logic:s,id:r,registryKey:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,r=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===r.length)return[];const c=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;c.push({event:o(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0})}var a;void 0!==s&&n&&c.push({event:(a=t.id,{type:`xstate.timeout.${a}`}),delay:s,transitions:n,fromDelaysMap:!0});for(const t of r)c.push({event:i(t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1});const h=[];for(const{event:e,delay:s,transitions:n,fromDelaysMap:o}of c){const i=W(t,e,e=>P(s,o?e.delays:{},{context:e.context,event:e.event,stateNode:t,input:e.input}));for(const t of Nt(n))h.push({...t,event:i,delay:s})}return h.map(e=>({...C(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error("Null event transition key");const n=t.config.on[s];e.set(s,ce(n,e=>C(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,ce(t.config.onDone,e=>C(t,s,e)))}if(t.config.onError){const s="xstate.error.*";e.set(s,ce(t.config.onError,e=>C(t,s,e)))}const s=(e,s)=>C(t,e,{to:(t,e)=>(e.cancel(s),{})}),n=(e,s,n)=>{const{target:o,to:i,reenter:r,...c}=s;return C(t,e,{...c,reenter:r,to:(t,e)=>{if(i){let s=!1;const o=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const o=Reflect.get(t,e,n);return"function"!=typeof o?o:(...e)=>(s=!0,o.apply(t,e))}}),r=i(t,o);return(void 0!==r||s)&&e.cancel(n),r}return e.cancel(n),{target:o,reenter:r}}})};for(const o of t.invoke){const r=void 0!==o.timeout?i(o.id).type:void 0;if(o.onDone){const i=`xstate.done.actor.${o.id}`,c=ce(o.onDone,e=>r?n(i,e,r):C(t,i,e));r&&c.push(s(i,r)),e.set(i,c)}else if(r){const t=`xstate.done.actor.${o.id}`;e.set(t,[s(t,r)])}if(o.onError){const s=`xstate.error.actor.${o.id}`;e.set(s,ce(o.onError,e=>r?n(s,e,r):C(t,s,e)))}if(o.onSnapshot){const s=`xstate.snapshot.${o.id}`;e.set(s,ce(o.onSnapshot,e=>C(t,s,e)))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),"choice"===this.type?this.always=function(t){const e=t.config.choice,s=e=>{if(!e||void 0===e.target)throw new Error(`Choice "${t.id}" has no target`);return e};return[C(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=ce(this.config.always,t=>C(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 oe(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=e.type,o=oe(this,`candidates-${n}`,()=>function(t,e){const s=t.transitions.get(e),n=[...t.transitions.keys()].filter(t=>t!==e&&Kt(e,t)).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return s?[...s,...n]:n}(this,n));for(const n of o){if(lt(n,e,t,this,s))return[n]}}}function ce(t,e){const s=Nt(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}let ae,he;function ue(){return ae??=Xt({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 fe{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._json=void 0,this.id=t.id||"(machine)",this.implementations={actorSources:t.actorSources??{},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,i=n.config.route,r=({event:t})=>t.to===`#${o}`;if("function"==typeof i)return e.push(C(t,"xstate.route",{guard:r,to:t=>{const e=i(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(n.states&&s(n.states));const{guard:c,...a}=i,h={...a,guard:r,target:`#${o}`};e.push(C(t,"xstate.route",h))}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,actorSources:n,delays:o}=this.implementations,i=new fe(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actorSources:{...n,...t.actorSources},delays:{...o,...t.delays}});return i._json=this._json,i}resolveState(t){const e=(s=this.root,n=t.value,K(s,J(X(s,n))));var s,n;const o=J(X(this.root,e));return bt({_nodes:[...o],value:e,context:t.context||{},children:{},status:B(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const n=this._transitionFast(t,e,s);if(n)return[n,[]];const{snapshot:o,microsteps:i}=at(t,e,s,[]);return[o,this._collectEffects(i)]}_collectEffects(t,e=[]){const s=[...e,...t.flatMap(([,t])=>t)];return[...s,...j(s)]}_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 i=o[0];if(i.guard||i.actions||i.to||i.reenter||i.input||"function"==typeof i.context||i.target&&1!==i.target.length)return;const r=i.target?.[0]??n,c=r!==n;if(r.parent!==this.root||"atomic"!==r.type||c&&(r.entry||r.invoke.length||r.always?.length||r.after?.length))return;const a=void 0!==i.context?{...t.context,...i.context}:t.context,h=s.self._collectedMicrosteps||[];return h.push(i),s.self._collectedMicrosteps=h,wt(t,{...a!==t.context?{context:a}:{},...c?{_nodes:[this.root,r]}:{}})}microstep(t,e,s){const{microsteps:n}=at(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 Q(this.root,t.value,t,e,s)||[]}isInternalEventType(t){for(const e of this.internalEventDescriptors)if(Kt(t,e))return!0;return!1}_canTransition(t,e){const s=ue(),n=function(){if(he)return he;const t=ue();return he={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},he}(),o=this.getTransitionData(t,e,s);if(!o?.length)return!1;for(const i of o){if(void 0!==i.target)return!0;const o=ct(i,t,e,n,{resolveActions:!1});if(o.targets?.length||o.context||ht(i,t.context,e,t,s))return!0}return!1}getExecutionErrorEvent(t,e){if("active"===t?.status&&t._nodes?.some(t=>t.config.onError))return c("execution",e)}_getPreInitialState(t,e){const{context:s}=this.config,n=bt({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const o={},i=s({spawn:se(t,n,e,o),input:e.input,self:t.self,actorSources:this.implementations.actorSources}),[r]=O(n,e,t,[]);return i&&(r.context=i),Object.keys(o).length>0&&(r.children={...r.children,...o}),r}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){const s=a(t),n=[],o=this._getPreInitialState(e,s);let i,r,h=[],u=[];try{[i,h]=function(t,e,s,n,o){return rt([{target:[...G(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,o,e,s,n),({snapshot:r,microsteps:u}=at(i,s,e,n))}catch(t){if(!this.root.config.onError)throw t;const s=at(o,c("execution",t),e,[]);r=s.snapshot,u=s.microsteps,h=[]}return[r,this._collectEffects(u,h)]}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=jt(t),s=e.slice(1),n=V(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 U(o,s)}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,_stateInputs:n,tags:o,machine:i,children:r,context:c,can:a,hasTag:h,matches:u,getMeta:f,getInputs:p,toJSON:l,...d}=t,y={};for(const t in r){const s=r[t];y[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,registryKey:s.registryKey,syncSnapshot:s._syncSnapshot}}const g={...d,context:kt(c),children:y,historyValue:Et(d.historyValue)};return n&&Object.keys(n).length>0&&(g.stateInputs=n),void 0!==i.version&&(g.version=i.version),g}(t,e)}restoreSnapshot(t,e){const s=t.version;if(s!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${s}' does not match machine version '${this.version}'.`);t=e(t,s)}const n=t,o={},i=n.children;for(const t of Object.keys(i)){const s=i[t],n=s.snapshot,r=s.src,c="string"==typeof r?Rt(this,r):r;if(!c)continue;const a=Xt(c,{id:t,parent:e.self,syncSnapshot:s.syncSnapshot,snapshot:n,src:r,registryKey:s.registryKey});a._rehydrated=!0,o[t]=a}const r=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const s of Object.keys(t)){const n=t[s];for(const t of n){let n;if(t instanceof re)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(n.historyValue),c=Array.from(J(X(this.root,n.value))),{version:a,...h}=t,u=bt({...h,children:o,_nodes:c,value:n.value,historyValue:r,_stateInputs:n.stateInputs??{}},this),f=new WeakSet;return function t(e){if(!f.has(e)){f.add(e);for(const s of Object.keys(e)){const n=e[s];if(n&&"object"==typeof n){if("xstate$$type"in n&&n.xstate$$type===Wt){e[s]=o[n.id];continue}t(n)}}}}(u.context),u}}function pe(t){return JSON.stringify(t)}function le(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 de=()=>(t,e)=>Me(t,e),ye=()=>(t,e)=>Ae(t,e);class ge{getDefaultOptions(){return{serializeState:t=>pe(t),serializeEvent:t=>pe(t),serializeTransition:(t,e)=>`${pe(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:dt(t.state)?`Reaches ${le(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=pe)=>{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(de(),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($e(n,e)))}return s}getSimplePaths(t){return this.getPaths(ye(),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($e(n,e)))}return s}getPathsFromEvents(t,e){return Te(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return Ie(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:pe,serializeEvent:pe,...s},{formatColor:o,serializeState:i,serializeEvent:r}=n,{state:c}=t,a=i(c,t.steps.length?t.steps[t.steps.length-1].event:void 0);let h="",u=!1;return h+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=i(t.step.state,e>0?s[e-1].step.event:void 0),c=r(t.step.event);return[`\tState: ${u?o("gray",n):t.state.error?(u=!0,o("redBright",n)):o("greenBright",n)}`,`\tEvent: ${u?o("gray",c):t.event.error?(u=!0,o("red",c)):o("green",c)}`].join("\n")}).concat(`\tState: ${u?o("gray",a):e.state.error?o("red",a):o("green",a)}`).join("\n\n"),h}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),o=this._getStateTestKeys(t,e,n);for(const s of o)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},o=Object.keys(n).filter(t=>s.stateMatcher(e,t));return!o.length&&"*"in n&&o.push("*"),o}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function ve(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=>ve(t[s],e[s]))}function me(t,e,s,{serializeEvent:n}){if(!e||s&&ve(s.value,t.value))return"";const o=s?` from ${pe(s.value)}`:"";return` via ${n(e)}${o}`}function _e(){const t=Xt(ee);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function Se(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 be(t){return JSON.stringify(t)}function we(t,e){const{events:s,...n}=e??{};return{serializeState:xe,serializeEvent:be,events:t=>{const e="function"==typeof s?s(t):s??[];return Jt(t).flatMap(t=>{const s=e.filter(e=>e.type===t);return s.length?s:[{type:t}]})},fromState:t.getInitialSnapshot(_e(),e?.input),...n}}function Ee(){return{serializeState:t=>JSON.stringify(t),serializeEvent:be}}function ke(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?we(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:be,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function $e(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 je(t){return Array.isArray(t)?t[0]:t}function Ie(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:i,filterEvents:r,limit:c,fromState:a,stopWhen:h}=ke(t,e),u=_e(),f={};let p=0;const l=[{nextState:a??t.getInitialSnapshot(u,e.input),event:void 0,prevState:void 0}],d=new Map;for(;l.length;){const{nextState:t,event:e,prevState:a}=l.shift();if(p++>c)throw new Error("Traversal limit exceeded");const y=o(t,e,a);if(f[y])continue;if(d.set(y,t),f[y]={state:t,transitions:{}},h&&h(t))continue;const g="function"==typeof i?i(t):i;for(const e of g){if(r&&!r(t,e))continue;const o=je(s(t,e,u));f[y].transitions[n(e)]={event:e,state:o},l.push({nextState:o,event:e,prevState:t})}}return f}function Oe(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 Te(t,e,s){const n=ke(t,{events:e,...s},(o=t)&&o instanceof fe?we(t):Ee());var o;const i=_e(),r=n.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:c,serializeEvent:a}=n,h=Ie(t,n),u=new Map,f=[],p=c(r,void 0,void 0);u.set(p,r);let l=p,d=r;for(const t of e){f.push({state:u.get(l),event:t});const e=a(t),{state:s,event:n}=h[l].transitions[e];if(!s)throw new Error(`Invalid transition from ${l} with ${e}`);const o=c(s,t,u.get(l));u.set(o,s),l=o,d=s}return n.toState&&!n.toState(d)?[]:[Oe({state:d,steps:f,weight:f.length})]}function Me(t,e){const s=ke(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(_e(),e?.input),i=Ie(t,s),r=new Map,c=new Map,a=n(o,void 0,void 0);c.set(a,o),r.set(a,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(a);for(const t of h){const e=c.get(t),{weight:s}=r.get(t);for(const o of Object.keys(i[t].transitions)){const{state:a,event:f}=i[t].transitions[o],p=n(a,f,e);if(c.set(p,a),r.has(p)){const{weight:e}=r.get(p);e>s+1&&r.set(p,{weight:s+1,state:t,event:f})}else r.set(p,{weight:s+1,state:t,event:f});u.has(p)||h.add(p)}u.add(t),h.delete(t)}const f={},p=[];return r.forEach(({weight:t,state:e,event:s},n)=>{const o=c.get(n),i=e?f[e].paths[0].steps.concat({state:c.get(e),event:s}):[];p.push({state:o,steps:i,weight:t}),f[n]={state:o,paths:[{state:o,steps:i,weight:t}]}}),s.toState?p.filter(t=>s.toState(t.state)).map(Oe):p.map(Oe)}function Ae(t,e){const s=ke(t,e),n=_e(),o=s.fromState??t.getInitialSnapshot(n,e?.input),i=s.serializeState,r=Ie(t,s),c=new Map,a={vertices:new Set,edges:new Set},h=[],u={};function f(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){u[e]||(u[e]={state:c.get(e),paths:[]});const t=u[e],n={state:s,weight:h.length,steps:[...h]};t.paths.push(n)}else{if(!r[t])return;for(const s of Object.keys(r[t].transitions)){const{state:n,event:o}=r[t].transitions[s];if(!(s in r[t].transitions))continue;const u=c.get(t),p=i(n,o,u);c.set(p,n),a.vertices.has(p)||(a.edges.add(s),h.push({state:c.get(t),event:o}),f(p,e))}}h.pop(),a.vertices.delete(t)}const p=i(o,void 0);c.set(p,o);for(const t of Object.keys(r))f(p,t);const l=Object.values(u).flatMap(t=>t.paths);return s.toState?l.filter(t=>s.toState(t.state)).map(Oe):l.map(Oe)}t.TestModel=ge,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=de,t.createSimplePathsGen=ye,t.createTestModel=function(t,e){(t=>{t.root})(t);const s=e?.serializeEvent??pe,n=e?.serializeTransition??me,{events:o,...i}=e??{};return new ge(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 Jt(t).flatMap(t=>e.some(e=>e.type===t)?e.filter(e=>e.type===t):[{type:t}])},...i})},t.getAdjacencyMap=Ie,t.getPathsFromEvents=Te,t.getShortestPaths=Me,t.getSimplePaths=Ae,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=$e,t.serializeSnapshot=xe,t.toDirectedGraph=function t(e){const s=e instanceof fe?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:Se(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",i="@xstate.terminate",r="xstate.timer";function c(t,e){return{type:`xstate.after.${t}.${e}`}}function a(t){return{type:`xstate.timeout.actor.${t}`}}function u(t,e){return{type:`xstate.done.state.${t}`,output:e}}function h(t,e){return{type:`xstate.error.${t}`,error:e}}function f(t){return{type:s,input:t}}function l(t){setTimeout(()=>{throw t})}const p="function"==typeof Symbol&&Symbol.observable||"@@observable";function d(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}const y={"@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)=>(d(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)},g=new WeakMap;function v(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 i=t(e.input,{self:s,system:n});if(!i)return;let r,c=!1;const a=()=>{c||(c=!0,i.unsubscribe(),r?.unsubscribe())},u=s._parent;u&&(r=u.subscribe({complete:a,error:a})),g.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===o?(g.get(s)?.unsubscribe(),g.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:e,getInitialSnapshot:(t,s)=>e(s)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function m(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function _(){return v(({actor:t,eventType:e,mapper:s},{self:n,system:o})=>{const i="*"!==e&&e.endsWith(".*");return t.on(i?"*":e,t=>{i&&!ce(t.type,e)||m(n,o,()=>s(t))})})}const x=_();function S(){return v(({actor:t,mappers:e},{self:s,system:n})=>{const{done:o,error:i,snapshot:r}=e;return t.subscribe({next:t=>{"done"===t.status&&o?m(s,n,()=>o(t.output)):"error"===t.status&&i?m(s,n,()=>i(t.error)):"active"===t.status&&r&&m(s,n,()=>r(t))},error:t=>{i&&m(s,n,()=>i(t))},complete:()=>{}})})}const b=S();function w(){return this.action?.(...this.args)}function E(t=this.source.system){return t.emitEvent(this.source,this.event)}function k(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function T(t=this.actor.system){return t.spawnActor(this.source,this.actor)}function A(t=this.actor.system){return t.startActor(this.actor)}function I(t=this.source.system){return t.stopActor(this.actor)}function $(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 j(t=this.source.system){return t.scheduleTimer(this.source,this.id,this.delay??0)}function O(t=this.source.system){return d(this.event),void 0!==this.delay?t.scheduleTimer(this.source,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function M(t=this.source.system){return t.cancelTimer(this.source,this.id)}function P(t,e,s){if(!L(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 i="@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:i}},_nextTimerId:n}}function N(t,e){return{...t,...e}}function R(t,e,...s){const n={action:e,args:s};return t.push(n),n}function z(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 D(t){if("object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action)return t}function J(t,e,s,n=!1,o=!0){const i={cancel:s=>{R(e,y["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{R(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?R(e,y["@xstate.raise"],t,n,o):s.push(n)},spawn:(s,n)=>{if(!o)return{id:n?.id??n?.registryKey??s.id};const i=t.system.createActorRef(s,{...n,parent:t.self});return function(t,e,s){R(t,y["@xstate.spawn"],e).childUpdate={type:"add",actor:e,id:s??e.id}}(e,i,n?.id),i},sendTo:(n,o,i)=>{n?R(e,y["@xstate.sendTo"],t,n,o,i):s.push(h("communication",{message:"Unable to send event to an undefined actor",event:o}))},stop:s=>{if(s){R(e,y["@xstate.stop"],t,s).childUpdate={type:"remove",actor:s}}}};return n&&Object.assign(i,{listen:(s,n,o)=>{const i={actor:s,eventType:n,mapper:o},r=t.system.createActorRef(x,{input:i,parent:t.self});return R(e,y["@xstate.spawn"],r),r},subscribeTo:(s,n)=>{const o={actor:s,mappers:"function"==typeof n?{snapshot:n}:n},i=t.system.createActorRef(b,{input:o,parent:t.self});return R(e,y["@xstate.spawn"],i),i}}),q(i,(t,...s)=>{R(e,t,...s)})}function K(t,e){switch(t){case y["@xstate.spawn"]:{const[t]=e;return{kind:"builtin",exec:T,source:t._parent,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case y["@xstate.raise"]:{const[,t,s]=e;return{kind:"builtin",exec:j,source:e[0].self,event:t,id:s?.id,delay:s?.delay}}case y["@xstate.sendTo"]:{const[,t,s,n]=e;return{kind:"builtin",exec:O,source:e[0].self,target:t,event:s,id:n?.id,delay:n?.delay}}case y["@xstate.cancel"]:{const[,t]=e;return{kind:"builtin",exec:M,source:e[0].self,id:t}}case y["@xstate.stop"]:{const[,t]=e;return{kind:"builtin",exec:I,source:e[0].self,actor:t,id:t.id}}default:return}}function W(t){const e=[t];return{kind:"builtin",exec:A,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function V(t,e,s){const n=[t,e,s,{}];return{kind:"builtin",exec:O,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:n}}function B(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:$,type:i,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:n}}function C(t,e,[s,n]){const o="done"===s.status||"error"===s.status,r="done"===e?.status||"error"===e?.status,c=n.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===i);return!o||r||c?[s,n]:[s,[...n,B(t,s)]]}function L(t){return"builtin"===t.kind}function U(t,e,s,n){let o=t;const i=[];for(const r of n){const n={context:o.context,event:e,output:te(e),self:s.self,system:s.system,children:o.children,parent:s.self._parent,actions:t.machine.implementations.actions,actorSources:t.machine.implementations.actorSources},c="function"==typeof r,a=D(r),u=c?r:!!a&&a.action.bind(null,...a.args);let h;if("object"==typeof r&&null!==r){const{type:t,childUpdate:e,...s}=r;h=s}if(a?.childUpdate&&(o=z(o,a.childUpdate,s)),u&&"_special"in u){i.push({kind:"action",exec:w,type:"object"==typeof r?"action"in r&&"function"==typeof r.action?r.action.name??"(anonymous)":r.type??"(anonymous)":r.name||"(anonymous)",params:h,args:[],action:void 0});const t=u(n,F);t&&("context"in t||"children"in t)&&(o={...o,...void 0!==t.context?{context:N(o.context,t.context)}:{},..."children"in t?{children:t.children}:{}});continue}if(!u||!("resolve"in u)){const t="object"==typeof r&&null!==r&&"action"in r&&"function"==typeof r.action?K(r.action,r.args):void 0,e="object"==typeof r&&null!==r&&!a,n={kind:t?"builtin":e?"emit":"action",type:"object"==typeof r?"action"in r&&"function"==typeof r.action?r.action.name??"(anonymous)":r.type:r.name||"(anonymous)",params:t?void 0:h,args:"object"==typeof r&&"action"in r?r.args:[],...t?{}:e?{source:s.self,event:r}:{action:a?.action??(c?r:void 0)},...t?{}:{exec:e?E:w},...t};o=P(o,n,s),i.push(n);continue}}return[o,i]}function q(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 F=q({},()=>{});function G(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const n=e.match(/^(\d*)(\.?)(\d*)s$/i);if(n){const t=n[1]?parseInt(n[1],10):0,e=!!n[2],s=n[3]?parseInt(n[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:i,days:r,hours:c,minutes:a,seconds:u}=o.groups;if(!(i||r||c||a||u))return;const h=t=>t?Number(t.replace(",",".")):0;return 7*h(i)*24*60*60*1e3+24*h(r)*60*60*1e3+60*h(c)*60*1e3+60*h(a)*1e3+1e3*h(u)}(t)??t}function H(t,e,s){if("function"==typeof t)return t(s);const n=G(t,e);return"function"==typeof n?n(s):n}function X(t,e){return t._stateInputs?.[e]}function Q(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function Y(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Z(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 tt(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 Y(t))if(!e.has(s)){const t=ut(s);for(const s of t)e.add(s)}}else for(const s of ut(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 et(t,e){const s=tt(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(Q(t))return t.key}const s={};for(const t of e)s[t.key]=o(t);return s};return o(t)}function st(t,e){return"compound"===e.type?Y(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?Y(e).every(e=>st(t,e)):"final"===e.type}const nt=t=>"#"===t[0];function ot(t,e,s){const n=e.type,o=t.entry;t.entry=(t,i)=>(i.raise(e,{id:n,delay:s(t)}),"function"==typeof o?o(t,i):void 0);const i=t.exit;return t.exit=(t,e)=>(e.cancel(n),"function"==typeof i?i(t,e):void 0),n}function it(t,e,s){const n=ne(s.target),o=s.reenter??!1,i=rt(t,n),r={...s,target:i,source:t,reenter:o,eventType:e,toJSON:()=>({...r,source:`#${t.id}`,target:i?i.map(t=>`#${t.id}`):void 0})};return r}function rt(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(nt(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return ft(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return ft(t.parent,n)}catch(e){throw new Error(`Invalid transition for '${t.id}': ${e.message}`)}})}function ct(t){const e=ne(t.config.target);return e?{target:e.map(e=>"string"==typeof e?ft(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 at(t){return"history"===t.type}function ut(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 Y(s))t(e)}(t);for(const s of e)for(const n of Z(s,t))e.add(n);return e}function ht(t,e){if(nt(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 ft(t,e){if("string"==typeof e&&nt(e))try{return t.machine.getStateNodeById(e)}catch{}const s=Ht(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=ht(n,t)}return n}function lt(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=new Array(s.length),o=[t.machine.root,t];for(let e=0;e<s.length;e++){const i=ht(t,s[e]);n[e]=i,o.push(i)}for(let t=0;t<s.length;t++)o.push(...lt(n[t],e[s[t]]));return o}function pt(t,e,s,n,o){if("string"==typeof e){const i=ht(t,e).next(s,n,o);return i&&i.length?i:t.next(s,n,o)}const i=Object.keys(e),r=i[0];if(1===i.length){const i=pt(ht(t,r),e[r],s,n,o);return i&&i.length?i:t.next(s,n,o)}const c=[];for(const r of i){const i=e[r];if(!i)continue;const a=pt(ht(t,r),i,s,n,o);a&&c.push(...a)}return c.length?c:t.next(s,n,o)}function dt(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function yt(t,e){for(const s of t)if(dt(s,e))return!0;return!1}function gt(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 vt(t,e,s,n,o){const i=new Set,r=new Map,c=t=>{let i=r.get(t);return i||(i=St([t],e,s,n,o),r.set(t,i)),i};for(const e of t){let t=!1;const s=new Set;for(const n of i)if(gt(c(e),c(n)))if(dt(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)i.delete(t);i.add(e)}}return Array.from(i)}function mt(t,e,s,n){const o=e.historyValue,{targets:i}=wt(t,e,s,n,{resolveActions:!1});if(!i)return[];const r=new Set;for(const t of i)if(at(t))if(o[t.id])for(const e of o[t.id])r.add(e);else for(const o of mt(ct(t),e,s,n))r.add(o);else r.add(t);return[...r]}function _t(t,e){let s=t;for(;"parallel"===s.type;){const t=Y(s).find(t=>e.every(e=>e===t||dt(e,t)));if(!t)break;s=t}return s}function xt(t,e,s,n){const o=mt(t,e,s,n),{reenter:i}=wt(t,e,s,n,{resolveActions:!1});if(o.every(e=>e===t.source||dt(e,t.source)))return i?t.source:_t(t.source,o);const[r,...c]=o.concat(t.source);for(const t of Z(r,void 0))if(c.every(e=>dt(e,t)))return i?t:_t(t,o);return i?void 0:_t(t.source.machine.root,o)}function St(t,e,s,n,o){const i=new Set;for(const r of t){const{targets:t,reenter:c}=wt(r,s,n,o,{resolveActions:!1});if(t?.length){const t=xt(r,s,n,o);c&&r.source===t&&i.add(t);for(const s of e)dt(s,t)&&i.add(s)}}return[...i]}function bt(t,e,s,n,o,i){const r=[];if(!t.length)return[e,r];{const c=new Set(e._nodes);let a=e.historyValue;const h=e.context,f=vt(t,c,e,n,s),l=t=>wt(t,e,n,s),p=(t,o,i,r)=>{if(2===t.length){const c=[],a=[];let u;const h=J(s,c,a,!0),f=t({context:o,event:n,parent:s.self._parent,self:s.self,children:i,system:s.system,actions:e.machine.implementations.actions,actorSources:e.machine.implementations.actorSources,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays,input:r},h);return void 0!==f?.context&&(u=N(o,f.context)),[c,u,a]}return[[Object.assign((e,s)=>t({...e,input:r},s),"_special"in t?{_special:!0}:{})],void 0,void 0]};let d=e;const g=(t,e)=>{const n=[],o=J(s,n,[]);for(const s of t.invoke){const t=e[s.id];t&&o.stop(t)}return n},v=()=>{const t=St(f,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=>Q(t)&&dt(t,e):t=>t.parent===e;o??={...a},o[t.id]=u.filter(s)}for(const o of t){const t=X(e,o.id),[a,u,h]=o.exit?p(o.exit,d.context,e.children,t):[[],void 0,void 0];h?.length&&i.push(...h),u&&(d=Ut(d,{context:u}));const[f,l]=U(d,n,s,a);d=f,r.push(...l);const y=g(o,d.children);if(y.length){const[t,e]=U(d,n,s,y);d=t,r.push(...e)}c.delete(o)}a=o||a};o||v();let m=d.context;const _=[],x=[];for(const t of f){t.actions&&_.push(...Yt(t.actions));const e=l(t);void 0!==e.context&&(m=N(m,e.context)),e.actions&&_.push(...e.actions),e.internalEvents&&x.push(...e.internalEvents)}x.length&&i.push(...x);const S=()=>{const t=t=>{const e=d.machine.root;let o;if(void 0!==t.output&&t.parent){const r=i.find(t=>t.type===`xstate.done.state.${e.id}`);o=r&&t.parent===e?r.output:Zt(t.output,d.context,n,s.self,_[t.id])}else if("parallel"===t.type){const e=`xstate.done.state.${t.id}`,s=i.find(t=>t.type===e);o=s?.output}return void 0===e.output?t.parent===e?o:void 0:Zt(e.output,d.context,u(t.id,o),s.self)},h=new Set,g=new Set,v=(t,e)=>{for(const s of t)if(e&&!dt(s,e)||h.add(s),"parallel"===s.type)for(const t of Y(s))yt(h,t)||(h.add(t),m(t))},m=t=>{if(at(t))if(a[t.id]){const e=a[t.id];for(const t of e)h.add(t),m(t);for(const s of e)v(Z(s,t.parent),void 0)}else{const e=ct(t),{targets:s}=l(e);for(const n of s??[])h.add(n),e===t.parent?.initial&&g.add(t.parent),m(n);for(const e of s??[])v(Z(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=l(t.initial).targets;return at(e)||(h.add(e),g.add(e)),m(e),void v(Z(e,t),void 0)}if("parallel"===t.type)for(const e of Y(t))yt(h,e)||(h.add(e),g.add(e),m(e))}};for(const t of f){const o=xt(t,e,n,s),{targets:i,reenter:r}=wt(t,e,n,s,{resolveActions:!1});for(const e of i??[])at(e)||t.source===e&&t.source===o&&!r||(h.add(e),g.add(e)),m(e);const c=mt(t,e,n,s);for(const e of c){const s=Z(e,o);"parallel"===o?.type&&s.push(o),v(s,!t.source.parent&&r?void 0:o)}r&&o===t.source&&h.add(t.source)}o&&g.add(e.machine.root);const _={...e._stateInputs};let x=!1;for(const t of f){const{targets:o,input:i}=wt(t,e,n,s,{resolveActions:!1});if(i&&o)for(const t of o)_[t.id]=i,x=!0}const S=new Set,b={...d.children};for(const o of[...h].sort((t,e)=>t.order-e.order)){c.add(o);const a=[];let h=!1;for(const t of o.invoke){h=!0;let o=t.logic;"function"==typeof o&&(o=o({actorSources:e.machine.implementations.actorSources,context:d.context,event:n,self:s.self}));const i="string"==typeof o?ie(e.machine,o):o;if(!i)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented`);const r="function"==typeof t.input?t.input({self:s.self,context:d.context,event:n,output:te(n)}):t.input,c=s.system.createActorRef(i,{...t,input:r,parent:s.self,syncSnapshot:!!t.onSnapshot});a.push({action:y["@xstate.spawn"],args:[c]}),t.id&&(b[t.id]=c)}h&&(d=Ut(d,{children:b}));let f=d.context,l=!1;const v=_[o.id];if(o.entry){const[t,e,s]=p(o.entry,f,b,v);a.push(...t),s?.length&&i.push(...s),e&&(f=e,l=!0)}if(l&&(d.context=f),g.has(o)){const{actions:t,input:e}=wt(o.initial,d,n,s);if(t&&a.push(...t),e&&o.initial?.target)for(const t of o.initial.target)_[t.id]=e,x=!0}const[m,w]=U(d,n,s,a);if(d=m,a.length=0,r.push(...w),"final"!==o.type)continue;const E=o.parent;let k="parallel"===E?.type?E:E?.parent,T=k||o;for("compound"===E?.type&&i.push(u(E.id,void 0!==o.output?Zt(o.output,d.context,n,s.self,v):void 0));"parallel"===k?.type&&!S.has(k)&&st(c,k);){S.add(k);const t={};for(const e of Y(k)){if("final"===e.type){t[e.key]=void 0!==e.output?Zt(e.output,d.context,n,s.self,_[e.id]):void 0;continue}if("parallel"===e.type){const s=`xstate.done.state.${e.id}`,n=i.find(t=>t.type===s);t[e.key]=n?.output;continue}const o=Y(e).find(t=>"final"===t.type&&c.has(t));t[e.key]=void 0!==o?.output?Zt(o.output,d.context,n,s.self,_[o.id]):void 0}i.push(u(k.id,t)),T=k,k=k.parent}k||(d=Ut(d,{status:"done",output:t(T)}))}x&&(d=Ut(d,{_stateInputs:_}))},[b,w]=U(d,n,s,_);d=b,r.push(...w),m&&m!==e.context&&(d=Ut(d,{context:m})),S();const E=[...c];if("done"===d.status){const t=[];E.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=X(d,e.id),[n,,o]=p(e.exit,d.context,d.children,s);t.push(...n),o?.length&&i.push(...o)}});const[e,o]=U(d,n,s,t);d=e,r.push(...o);const[c,a]=At(d,n,s);d=c,r.push(...a);const[u,h]=It(d,n,s);d=u,r.push(...h)}return a===e.historyValue&&e._nodes.length===c.size&&e._nodes.every(t=>c.has(t))?d.context!==h?[Ut(d),r]:[d,r]:[Ut(d,{_nodes:E,historyValue:a}),r]}}function wt(t,e,s,n,o){const i={context:e.context,event:s,output:te(s),value:e.value,children:e.children,system:n.system,parent:n.self._parent,self:n.self,actions:e.machine.implementations.actions,actorSources:e.machine.implementations.actorSources,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays,input:X(e,t.source.id)};if(t.to){const r=[],c=[],a=J(n,r,c,!1,o?.resolveActions??!0),u=t.to(i,a),h=u?.target?rt(t.source,Yt(u.target)):void 0,f=u?.input??("function"==typeof t.input?t.input({context:e.context,event:s,output:te(s)}):t.input);return{targets:h,context:u?.context,reenter:u?.reenter,actions:r,internalEvents:c,input:f}}const r="function"==typeof t.input?t.input({context:e.context,event:s,output:te(s)}):t.input,c="function"==typeof t.context?t.context(i):t.context;return{targets:t.target,context:c,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:r}}function Et(t,e,i,c,a=[]){let u=t;const h=a.slice();function f(){const e=function(t){const e=[],s=[];for(const o of t){if(!L(o)||o.type!==n)continue;const{actor:t,logic:i}=o,r=W(t);i===x||i===b?e.push(r):s.push(r)}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,B(i,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=i.self._collectedMicrosteps||[];s.push(...e),i.self._collectedMicrosteps=s,h.push(t)}if(e.type===o){const[t,s]=At(u,e,i),[n,o]=It(t,e,i);return u=Ut(n,{status:"stopped"}),l([u,[...s,...o]],[]),f()}let p=e;if(e.type===r){const t=u.timers[e.id];if(!t)return f();const s={...u.timers};if(delete s[t.id],u=Ut(u,{timers:s}),"@xstate.raise"===t.type)c.push(t.event),l([u,[]],[]);else{const e="self"===t.target?i.self:t.target;l([u,[V(i,e,t.event)]],[])}}if(p.type!==s&&p.type!==r){const e=p,s=function(t){return t.type.startsWith("xstate.error.")}(e),n=u.machine.getTransitionData(u,e,i.self);if(s&&!n.length)return u=Ut(t,{status:"error",error:e.error}),l([u,[]],[]),f();const o=bt(n,t,i,p,!1,c);u=o[0],l(o,n)}let d=!0;const y=t.machine.options?.maxIterations??1/0;let g=0,v=0;for(;"active"===u.status;){if(v++,v>1e3)throw new Error("Microstep count exceeded 1000");if(g++,g>y)throw new Error(`Infinite loop detected (>${y} microsteps)`);let t=d?$t(u,p,i):[];const e=t.length?u:void 0;if(!t.length){if(!c.length)break;p=c.shift(),t=u.machine.getTransitionData(u,p,i.self)}const s=bt(t,u,i,p,!1,c);u=s[0],d=u!==e,l(s,t)}return f()}function kt(t,e,s,n,o){return!!t.to&&Tt(t.to,e,s,n,o,n.machine.implementations,t.source.id)}function Tt(t,e,s,n,o,i,r){let c,a=!1;try{const u=()=>{throw a=!0,new Error("Effect triggered")};c=t({context:e,event:s,output:te(s),self:o,system:o.system,value:n.value,children:n.children,parent:{send:u},actions:i.actions,actorSources:i.actorSources,guards:i.guards,delays:i.delays,input:X(n,r)},q({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 At(t,e,s){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return[t,[]];const o=[],i=J(s,o,[]);for(const t of n)i.stop(t);return U(t,e,s,o)}function It(t,e,s){const n=Object.keys(t.timers);if(!n.length)return[t,[]];const o=[],i=J(s,o,[]);for(const t of n)i.cancel(t);return U(t,e,s,o)}function $t(t,e,s){const n=new Set,o=t._nodes.filter(Q);for(const i of o)t:for(let o=i;o;o=o.parent)if(o.always)for(const i of o.always)if(jt(i,e,t,o,s.self)){n.add(i);break t}return vt(Array.from(n),new Set(t._nodes),t,e,s)}function jt(t,e,s,n,o){if(t.guard){const i={context:s.context,event:e,output:te(e),self:o,parent:o._parent,children:s.children,actions:n.machine.implementations.actions,actorSources:n.machine.implementations.actorSources,guards:n.machine.implementations.guards,delays:n.machine.implementations.delays,_snapshot:s};if(!t.guard(i))return!1}return!t.to||Tt(t.to,s.context,e,s,o,n.machine.implementations,t.source.id)}const Ot=Symbol("xstate.snapshotActorRef");function Mt(t,e,s,n){const o=new Map(n?.children??t.children),i=new Map(n?.keyedActors??Object.entries(t.getAll()).filter(t=>!!t[1])),r=new WeakMap;let c=!0;const a={...t,children:o,keyedActors:i,reverseKeyedActors:r,_snapshot:{...n?.snapshot??t._snapshot},_bookId:()=>c?(c=!1,e.sessionId??e.id):"x:"+a._snapshot._nextActorId++,_register:(t,e)=>(o.set(t,e),t),_unregister:t=>{t.sessionId&&o.delete(t.sessionId);const e=r.get(t);void 0!==e&&i.get(e)===t&&i.delete(e),r.delete(t)},_set:(t,e)=>{const s=i.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${String(t)}' already exists.`);i.set(t,e),r.set(e,t)},get:t=>i.get(t),getAll:()=>Object.fromEntries(i),_sendInspectionEvent:()=>{}};for(const[t,e]of i)r.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&&(i.set(e,t),r.set(t,e))}return a}function Pt(t){return t[Ot]}function Nt(t,e){const s=Pt(t);s&&Object.defineProperty(e,Ot,{configurable:!0,value:s})}function Rt(t,e,s=e.system){const n=Mt(s,e,function(t){return"children"in t&&t.children?t.children:{}}(t));Object.defineProperty(t,Ot,{configurable:!0,value:{actor:e,systemState:{children:n.children,keyedActors:n.keyedActors,snapshot:n._snapshot}}})}function zt(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const Dt=function(t){return Gt(t,this.value)},Jt=function(t){return this.tags.has(t)},Kt=function(t){return this.machine?._canTransition(this,t)??!1},Wt=function(){const{_nodes:t,_stateInputs:e,[Ot]:s,tags:n,machine:o,getMeta:i,getInputs:r,toJSON:c,can:a,hasTag:u,matches:h,...f}=this;return{...f,tags:Array.from(n)}},Vt=function(){const t={};for(const e of this._nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},Bt=function(){return this._stateInputs};function Ct(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function Lt(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??et(e.root,t._nodes),tags:Ct(t._nodes),children:t.children,timers:t.timers??{},historyValue:t.historyValue||{},_stateInputs:t._stateInputs||{},_nextTimerId:t._nextTimerId??0,matches:Dt,hasTag:Jt,can:Kt,getMeta:Vt,getInputs:Bt,toJSON:Wt};return s&&Rt(n,s),n}function Ut(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:Dt,hasTag:Jt,can:Kt,getMeta:Vt,getInputs:Bt,toJSON:Wt};return Nt(t,e),e}const n=Lt({...s,value:void 0},t.machine);return Nt(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 Ft(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:he,id:n.id};else{const o=Ft(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function Gt(t,e){const s=Xt(t),n=Xt(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&Gt(s[t],n[t]))}function Ht(t){if(ee(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function Xt(t){if(zt(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}(Ht(t))}function Qt(t){return ee(t)?t:[t]}function Yt(t){return void 0===t?[]:Qt(t)}function Zt(t,e,s,n,o){if("function"==typeof t){return t({context:e,event:s,output:te(s),self:n,input:o})}return t}function te(t){if(function(t){return t.type.startsWith("xstate.done.actor.")||t.type.startsWith("xstate.done.state.")}(t)){return t.output}}function ee(t){return Array.isArray(t)}function se(t){return Qt(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function ne(t){if(void 0!==t&&""!==t)return Yt(t)}function oe(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 ie(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actorSources[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke,r=(Array.isArray(i)?i[n]:i).src;return"string"==typeof r?t.implementations.actorSources[r]:r}function re(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]}function ce(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}function ae(t,e){return`${t.sessionId}.${e}`}let ue=!1;const he=1;let fe=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const le={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)};function pe(t,e){try{t?.(e)}catch(t){l(t)}}function de(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}class ye{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=fe.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={...le,...s},{clock:o,logger:i,parent:c,syncSnapshot:a,id:u,registryKey:h,inspect:f}=n;this.system=c?c.system:n._systemRef?.current??function(t,e){const s=new Map,n=new Map,o=new WeakMap,i=new Set,c={},{clock:a,logger:u}=e,h=(t,e,s,n,o)=>{i.size&&t&&(t._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:o})},f={schedule:(t,e,s)=>{const n=ae(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 i=Date.now(),u={source:t,delay:s,id:e,scheduledAt:i,dueAt:i+s},d=ae(t,e);p._snapshot._scheduledTimers[d]=u;const y=a.setTimeout(()=>{delete c[d],delete p._snapshot._scheduledTimers[d],l(t,t,{type:r,id:e})},s);c[d]=y},cancel:(t,e)=>{const s=ae(t,e),n=c[s];delete c[s],delete p._snapshot._scheduledTimers[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in p._snapshot._scheduledTimers){const s=p._snapshot._scheduledTimers[e];s.source===t&&f.cancel(t,s.id)}}},l=(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)},p={children:s,reverseKeyedActors:o,keyedActors:n,_snapshot:{_scheduledTimers:(e?.snapshot&&e.snapshot.scheduler)??{},_nextActorId:0},_bookId:()=>"x:"+p._snapshot._nextActorId++,_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=oe(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))},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),l(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)=>p.sendEvent(t,e,s),scheduler:f,getSnapshot:()=>({_scheduledTimers:{...p._snapshot._scheduledTimers}}),start:()=>{const t=p._snapshot._scheduledTimers;p._snapshot._scheduledTimers={};for(const e in t){const{source:s,dueAt:n,id:o}=t[e];p.scheduleTimer(s,o,Math.max(0,n-Date.now()))}},_clock:a,_logger:u};return p}(this,{clock:o,logger:i,createActorRef:(t,e)=>ge(t,e)}),c||!n._systemRef||n._systemRef.current||(n._systemRef.current=this.system),f&&!c&&this.system.inspect(oe(f)),this.sessionId=this.system._bookId(),this.id=u??this.sessionId,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=ue;try{ue=!0,t.exec()}finally{ue=e}};this._processingStatus!==fe.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]=C(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,Rt(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]=C(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),de(n,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers)pe(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 de(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=oe(t,e,s);if(this._processingStatus!==fe.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":pe(n.complete);break;case"error":{const t=this._snapshot.error;n.error?pe(n.error,t):l(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);return s||(s=new Set,this.eventListeners.set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,o)=>{const i=oe(s,n,o);let r=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(r,n)||(r=n,i.next?.(n))},error:i.error,complete:i.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===fe.Running)return this;if(this._processingStatus===fe.Stopped)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.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=fe.Running;const t=f(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=C(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),de(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)pe(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,{type:`xstate.done.actor.${e}`,output:s,actorId:e})));var e,s;"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===fe.Stopped?this:(this.mailbox.clear(),this._processingStatus===fe.NotStarted?(this._processingStatus=fe.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)pe(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,pe(n,t)}this.observers.clear(),e&&l(t)}else this._parent||l(t);var e;this.eventListeners.clear(),this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${e=this.id}`,error:t,actorId:e})}_stopProcedure(){this._processingStatus===fe.Running&&(this.system.cancelAllTimers(this),this.mailbox.clear(),this.mailbox=new e(this._boundProcess),this._processingStatus=fe.Stopped,this.system._unregister(this))}_send(t){this._processingStatus!==fe.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$$type:he,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[p](){return this}getSnapshot(){return this._snapshot}}function ge(t,e){return new ye(t,e)}const ve=new WeakMap;function me(t,e,s){const n=function(t){let e=ve.get(t);return e||(e=new Map,ve.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 _e(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===o)return[{...e,status:"stopped",input:void 0},[k("xstate.logic.cleanup",()=>function(t){const e=ve.get(t);if(e){for(const{cleanup:t}of e.values())t?.();ve.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 i=[],r={},c={emit:t=>{i.push(function(t,e){return{kind:"emit",exec:E,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&i.push(V(n,e,t))},raise:t=>{i.push(V(n,n.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{e.effects?.[t]||(i.push(k("xstate.logic.effect",(e=n.self.system)=>me(n.self,t,()=>s(e)),{key:t})),r[t]={status:"active"})})(t,s);const o=t;i.push(k("xstate.logic.effect",(t=n.self.system)=>me(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(r).length)&&(u.effects={...e.effects,...a?.effects,...r}),C(n,e,[u,i])},s={id:t.id,config:t,transition:e,start:(t,s,n)=>{if(!n?.restored)return;const[o,i]=e(t,f(t.input),s);Object.assign(t,o);for(const t of i)s.actionExecutor(t)},initialTransition:(s,n)=>{const o=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,s),i={status:"active",output:void 0,error:void 0,input:s};return void 0!==o&&(i.context=o),e({...i},f(s),n)},getInitialSnapshot:(t,e)=>s.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return s}const xe=_e({context:void 0,run:()=>{}});function Se(t,e,s=!0){return t.self._snapshot=e,s&&e&&"object"==typeof e&&Rt(e,t.self),e}function be(t,e,s){return Se(we(t,s,e.self),s)}function we(t,e,s){const n=e?Pt(e):void 0,o=s??n?.actor,i=o?.system,r=o&&i?Mt(i,o,zt(e)?e.children:{},s?void 0:n?.systemState):void 0,c=ge(t,{_inert:!0,...o?{id:o.id}:{},...r?{_systemRef:{current:r}}:{}});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 Ee=new WeakMap;function ke(t,e,s){let n=Ee.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Ee.set(t,n)),n[e]}const Te={};class Ae{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 i=n[o];s[i]=e(t[i],i,t,o)}return s}(this.config.states,(t,e)=>new Ae(t,{_parent:this,_key:e,_machine:this.machine})):Te,"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=Yt(t.tags).slice(),this.invoke=Yt(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,o=(i=this.id,`${e}.${i}`);var i;const r=t.id??o,c="string"==typeof s?s:`xstate.invoke.${o}`;return{...t,src:c,logic:s,id:r,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 i=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;i.push({event:c(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0})}var r;void 0!==s&&n&&i.push({event:(r=t.id,{type:`xstate.timeout.${r}`}),delay:s,transitions:n,fromDelaysMap:!0});for(const t of o)i.push({event:a(t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1});const u=[];for(const{event:e,delay:s,transitions:n,fromDelaysMap:o}of i){const i=ot(t,e,e=>H(s,o?e.delays:{},{context:e.context,event:e.event,stateNode:t,input:e.input}));for(const t of se(n))u.push({...t,event:i,delay:s})}return u.map(e=>({...it(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error("Null event transition key");const n=t.config.on[s];e.set(s,Ie(n,e=>it(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,Ie(t.config.onDone,e=>it(t,s,e)))}if(t.config.onError){const s="xstate.error.*";e.set(s,Ie(t.config.onError,e=>it(t,s,e)))}const s=(e,s)=>it(t,e,{to:(t,e)=>(e.cancel(s),{})}),n=(e,s,n)=>{const{target:o,to:i,reenter:r,...c}=s;return it(t,e,{...c,reenter:r,to:(t,e)=>{if(i){let s=!1;const o=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const o=Reflect.get(t,e,n);return"function"!=typeof o?o:(...e)=>(s=!0,o.apply(t,e))}}),r=i(t,o);return(void 0!==r||s)&&e.cancel(n),r}return e.cancel(n),{target:o,reenter:r}}})};for(const o of t.invoke){const i=void 0!==o.timeout?a(o.id).type:void 0;if(o.onDone){const r=`xstate.done.actor.${o.id}`,c=Ie(o.onDone,e=>i?n(r,e,i):it(t,r,e));i&&c.push(s(r,i)),e.set(r,c)}else if(i){const t=`xstate.done.actor.${o.id}`;e.set(t,[s(t,i)])}if(o.onError){const s=`xstate.error.actor.${o.id}`;e.set(s,Ie(o.onError,e=>i?n(s,e,i):it(t,s,e)))}if(o.onSnapshot){const s=`xstate.snapshot.${o.id}`;e.set(s,Ie(o.onSnapshot,e=>it(t,s,e)))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),"choice"===this.type?this.always=function(t){const e=t.config.choice,s=e=>{if(!e||void 0===e.target)throw new Error(`Choice "${t.id}" has no target`);return e};return[it(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=Ie(this.config.always,t=>it(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 ke(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=e.type,o=ke(this,`candidates-${n}`,()=>function(t,e){const s=t.transitions.get(e),n=[...t.transitions.keys()].filter(t=>t!==e&&ce(e,t)).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return s?[...s,...n]:n}(this,n));for(const n of o){if(jt(n,e,t,this,s))return[n]}}}function Ie(t,e){const s=se(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}let $e,je;function Oe(){return $e??=ge({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 Me{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._json=void 0,this.id=t.id||"(machine)",this.implementations={actorSources:t.actorSources??{},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 Ae(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const o=n.config.id,i=n.config.route,r=({event:t})=>t.to===`#${o}`;if("function"==typeof i)return e.push(it(t,"xstate.route",{guard:r,to:t=>{const e=i(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(n.states&&s(n.states));const{guard:c,...a}=i,u={...a,guard:r,target:`#${o}`};e.push(it(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,actorSources:n,delays:o}=this.implementations,i=new Me(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actorSources:{...n,...t.actorSources},delays:{...o,...t.delays}});return i._json=this._json,i}resolveState(t){const e=(s=this.root,n=t.value,et(s,tt(lt(s,n))));var s,n;const o=tt(lt(this.root,e));return Lt({_nodes:[...o],value:e,context:t.context||{},children:{},status:st(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const n=!s,o=s??we(this,t);n&&Se(o,t,!1);const i=this._transitionFast(t,e,o);if(i){n&&Se(o,i,!1);return[n&&i!==t?be(this,o,i):this._attachPureActorRef(i,o),[]]}const{snapshot:r,microsteps:c}=Et(t,e,o,[]);n&&Se(o,r,!1);return[n?r===t?r:be(this,o,r):this._attachPureActorRef(r,o),this._collectEffects(c)]}_collectEffects(t){return t.flatMap(([,t])=>t)}_attachPureActorRef(t,e){return function(t){return!!t.self.options?._inert}(e)?t:be(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 i=o[0];if(i.guard||i.actions||i.to||i.reenter||i.input||"function"==typeof i.context||i.target&&1!==i.target.length)return;const r=i.target?.[0]??n,c=r!==n;if(r.parent!==this.root||"atomic"!==r.type||c&&(r.entry||r.invoke.length||r.always?.length||r.after?.length))return;const a=void 0!==i.context?{...t.context,...i.context}:t.context,u=s.self._collectedMicrosteps||[];return u.push(i),s.self._collectedMicrosteps=u,Ut(t,{...a!==t.context?{context:a}:{},...c?{_nodes:[this.root,r]}:{}})}microstep(t,e,s){const{microsteps:n}=Et(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 pt(this.root,t.value,t,e,s)||[]}isInternalEventType(t){if(t===r)return!0;for(const e of this.internalEventDescriptors)if(ce(t,e))return!0;return!1}_canTransition(t,e){const s=Oe(),n=function(){if(je)return je;const t=Oe();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 i of o){if(void 0!==i.target)return!0;const o=wt(i,t,e,n,{resolveActions:!1});if(o.targets?.length||o.context||kt(i,t.context,e,t,s))return!0}return!1}getExecutionErrorEvent(t,e){if("active"===t?.status&&t._nodes?.some(t=>t.config.onError))return h("execution",e)}_getPreInitialState(t,e){const{context:s}=this.config,n=Lt({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this,t.self);if("function"==typeof s){const o={},i=function(t,e,s){return(n,o)=>{const i=Object.entries(e).find(([,t])=>t===n)?.[0],r=t.system.createActorRef(n,{id:o?.id,parent:t.self,syncSnapshot:o?.syncSnapshot,input:o?.input,src:i??n,registryKey:o?.registryKey});return s[r.id]=r,r}}(t,this.implementations.actorSources,o),r=s({spawn:i,input:e.input,self:t.self,actorSources:this.implementations.actorSources}),[c]=U(n,e,t,[]);return r&&(c.context=r),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??we(this),i=f(t),r=[],c=this._getPreInitialState(o,i),a=Object.values(c.children).filter(Boolean).map(t=>function(t){const e=[t];return{kind:"builtin",exec:T,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,l,p=[],d=[];try{[u,p]=function(t,e,s,n,o){return bt([{target:[...ut(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,c,o,i,r),({snapshot:l,microsteps:d}=Et(u,i,o,r,[[u,[...a,...p]]]))}catch(t){if(!this.root.config.onError)throw t;const e=Et(c,h("execution",t),o,[],[[c,a]]);l=e.snapshot,d=e.microsteps,p=[]}s&&Se(o,l,!1);return[s?be(this,o,l):this._attachPureActorRef(l,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=Ht(t),s=e.slice(1),n=nt(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return ft(o,s)}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,_stateInputs:n,tags:o,machine:i,children:r,timers:c,context:a,can:u,hasTag:h,matches:f,getMeta:l,getInputs:p,toJSON:d,...y}=t,g={},v={};for(const t in r){const s=r[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;if("self"===s.target)n="self";else{const o=Object.entries(r).find(([,t])=>t===s.target)?.[0];if(o)n=o;else{if(s.target!==Pt(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:s.event,target:n}}const m={...y,context:Ft(a),children:g,timers:v,historyValue:qt(y.historyValue)};return n&&Object.keys(n).length>0&&(m.stateInputs=n),void 0!==i.version&&(m.version=i.version),m}(t,e)}restoreSnapshot(t,e){const s=!e,n=e??we(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 i=t,r={},c=i.children;for(const t of Object.keys(c)){const e=c[t],s=e.snapshot,o=e.src,i="string"==typeof o?ie(this,o):o;if(!i)continue;const a=n.system.createActorRef(i,{id:t,parent:n.self,syncSnapshot:e.syncSnapshot,snapshot:s,src:o,registryKey:e.registryKey});a._rehydrated=!0,r[t]=a}const a={},u=i.timers??{};for(const[t,e]of Object.entries(u)){const s="string"==typeof e.target?"self"===e.target?"self":r[e.target]:n.self._parent;if(!s){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,target:s}}const h=(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 Ae)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(i.historyValue),f=Array.from(tt(lt(this.root,i.value))),{version:l,...p}=t,d=Lt({...p,children:r,timers:a,_nodes:f,value:i.value,historyValue:h,_stateInputs:i.stateInputs??{}},this,n.self),y=new WeakSet;return function t(e){if(!y.has(e)){y.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===he){e[s]=r[n.id];continue}t(n)}}}}(d.context),s?(Se(n,d,!1),be(this,n,d)):this._attachPureActorRef(d,n)}}function Pe(t){return JSON.stringify(t)}function Ne(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 Re=()=>(t,e)=>Ye(t,e),ze=()=>(t,e)=>Ze(t,e);class De{getDefaultOptions(){return{serializeState:t=>Pe(t),serializeEvent:t=>Pe(t),serializeTransition:(t,e)=>`${Pe(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:zt(t.state)?`Reaches ${Ne(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=Pe)=>{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(Re(),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(Fe(n,e)))}return s}getSimplePaths(t){return this.getPaths(ze(),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(Fe(n,e)))}return s}getPathsFromEvents(t,e){return Qe(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return He(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:Pe,serializeEvent:Pe,...s},{formatColor:o,serializeState:i,serializeEvent:r}=n,{state:c}=t,a=i(c,t.steps.length?t.steps[t.steps.length-1].event:void 0);let u="",h=!1;return u+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=i(t.step.state,e>0?s[e-1].step.event:void 0),c=r(t.step.event);return[`\tState: ${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 Je(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=>Je(t[s],e[s]))}function Ke(t,e,s,{serializeEvent:n}){if(!e||s&&Je(s.value,t.value))return"";const o=s?` from ${Pe(s.value)}`:"";return` via ${n(e)}${o}`}function We(){const t=ge(xe);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function Ve(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function Be(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function Ce(t){return JSON.stringify(t)}function Le(t,e){const{events:s,...n}=e??{};return{serializeState:Be,serializeEvent:Ce,events:t=>{const e="function"==typeof s?s(t):s??[];return re(t).flatMap(t=>{const s=e.filter(e=>e.type===t);return s.length?s:[{type:t}]})},fromState:t.getInitialSnapshot(We(),e?.input),...n}}function Ue(){return{serializeState:t=>JSON.stringify(t),serializeEvent:Ce}}function qe(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?Le(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:Ce,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function Fe(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 Ge(t){return Array.isArray(t)?t[0]:t}function He(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:i,filterEvents:r,limit:c,fromState:a,stopWhen:u}=qe(t,e),h=We(),f={};let l=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(l++>c)throw new Error("Traversal limit exceeded");const y=o(t,e,a);if(f[y])continue;if(d.set(y,t),f[y]={state:t,transitions:{}},u&&u(t))continue;const g="function"==typeof i?i(t):i;for(const e of g){if(r&&!r(t,e))continue;const o=Ge(s(t,e,h));f[y].transitions[n(e)]={event:e,state:o},p.push({nextState:o,event:e,prevState:t})}}return f}function Xe(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 Qe(t,e,s){const n=qe(t,{events:e,...s},(o=t)&&o instanceof Me?Le(t):Ue());var o;const i=We(),r=n.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:c,serializeEvent:a}=n,u=He(t,n),h=new Map,f=[],l=c(r,void 0,void 0);h.set(l,r);let p=l,d=r;for(const t of e){f.push({state:h.get(p),event:t});const e=a(t),{state:s,event:n}=u[p].transitions[e];if(!s)throw new Error(`Invalid transition from ${p} with ${e}`);const o=c(s,t,h.get(p));h.set(o,s),p=o,d=s}return n.toState&&!n.toState(d)?[]:[Xe({state:d,steps:f,weight:f.length})]}function Ye(t,e){const s=qe(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(We(),e?.input),i=He(t,s),r=new Map,c=new Map,a=n(o,void 0,void 0);c.set(a,o),r.set(a,{weight:0,state:void 0,event:void 0});const u=new Set,h=new Set;u.add(a);for(const t of u){const e=c.get(t),{weight:s}=r.get(t);for(const o of Object.keys(i[t].transitions)){const{state:a,event:f}=i[t].transitions[o],l=n(a,f,e);if(c.set(l,a),r.has(l)){const{weight:e}=r.get(l);e>s+1&&r.set(l,{weight:s+1,state:t,event:f})}else r.set(l,{weight:s+1,state:t,event:f});h.has(l)||u.add(l)}h.add(t),u.delete(t)}const f={},l=[];return r.forEach(({weight:t,state:e,event:s},n)=>{const o=c.get(n),i=e?f[e].paths[0].steps.concat({state:c.get(e),event:s}):[];l.push({state:o,steps:i,weight:t}),f[n]={state:o,paths:[{state:o,steps:i,weight:t}]}}),s.toState?l.filter(t=>s.toState(t.state)).map(Xe):l.map(Xe)}function Ze(t,e){const s=qe(t,e),n=We(),o=s.fromState??t.getInitialSnapshot(n,e?.input),i=s.serializeState,r=He(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(!r[t])return;for(const s of Object.keys(r[t].transitions)){const{state:n,event:o}=r[t].transitions[s];if(!(s in r[t].transitions))continue;const h=c.get(t),l=i(n,o,h);c.set(l,n),a.vertices.has(l)||(a.edges.add(s),u.push({state:c.get(t),event:o}),f(l,e))}}u.pop(),a.vertices.delete(t)}const l=i(o,void 0);c.set(l,o);for(const t of Object.keys(r))f(l,t);const p=Object.values(h).flatMap(t=>t.paths);return s.toState?p.filter(t=>s.toState(t.state)).map(Xe):p.map(Xe)}t.TestModel=De,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=Re,t.createSimplePathsGen=ze,t.createTestModel=function(t,e){(t=>{t.root})(t);const s=e?.serializeEvent??Pe,n=e?.serializeTransition??Ke,{events:o,...i}=e??{};return new De(t,{serializeState:(t,e,o)=>`${Be(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 re(t).flatMap(t=>e.some(e=>e.type===t)?e.filter(e=>e.type===t):[{type:t}])},...i})},t.getAdjacencyMap=He,t.getPathsFromEvents=Qe,t.getShortestPaths=Ye,t.getSimplePaths=Ze,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=Fe,t.serializeSnapshot=Be,t.toDirectedGraph=function t(e){const s=e instanceof Me?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:Ve(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