xstate 6.0.0-alpha.1 → 6.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { P as ProcessingStatus, G as resolveReferencedActor, c as createActor, S as STATE_DELIMITER, H as mapValues, t as toArray, I as createInvokeId, J as getDelayedTransitions, K as evaluateCandidate, L as formatTransition, N as NULL_EVENT, M as toTransitionConfigArray, O as createInvokeTimeoutEvent, Q as getCandidates, R as formatRouteTransitions, U as resolveStateValue, V as getAllStateNodes, n as getStateNodes, W as createMachineSnapshot, X as isInFinalState, a as macrostep, Y as transitionNode, m as matchesEventDescriptor, Z as resolveAndExecuteActionsWithContext, b as createInitEvent, d as initialMicrostep, _ as toStatePath, $ as isStateId, a0 as getStateNodeByPath, a1 as getPersistedSnapshot, a2 as $$ACTOR_TYPE } from './index-688701ed.esm.js';
1
+ import { P as ProcessingStatus, G as resolveReferencedActor, c as createActor, S as STATE_DELIMITER, H as mapValues, t as toArray, I as createInvokeId, J as getDelayedTransitions, K as evaluateCandidate, L as formatTransition, N as NULL_EVENT, M as toTransitionConfigArray, O as createInvokeTimeoutEvent, Q as getCandidates, R as formatRouteTransitions, U as resolveStateValue, V as getAllStateNodes, n as getStateNodes, W as createMachineSnapshot, X as isInFinalState, a as macrostep, Y as transitionNode, m as matchesEventDescriptor, Z as resolveAndExecuteActionsWithContext, b as createInitEvent, d as initialMicrostep, _ as toStatePath, $ as isStateId, a0 as getStateNodeByPath, a1 as getPersistedSnapshot, a2 as $$ACTOR_TYPE } from './index-93edd3bd.esm.js';
2
2
 
3
3
  function createSpawner(actorScope, {
4
4
  machine,
@@ -1,4 +1,4 @@
1
- import { P as ProcessingStatus, G as resolveReferencedActor, c as createActor, S as STATE_DELIMITER, H as mapValues, t as toArray, I as createInvokeId, J as getDelayedTransitions, K as evaluateCandidate, L as formatTransition, N as NULL_EVENT, M as toTransitionConfigArray, O as createInvokeTimeoutEvent, Q as getCandidates, R as formatRouteTransitions, U as resolveStateValue, V as getAllStateNodes, n as getStateNodes, W as createMachineSnapshot, X as isInFinalState, a as macrostep, Y as transitionNode, m as matchesEventDescriptor, Z as resolveAndExecuteActionsWithContext, b as createInitEvent, d as initialMicrostep, _ as toStatePath, $ as isStateId, a0 as getStateNodeByPath, a1 as getPersistedSnapshot, a2 as $$ACTOR_TYPE } from './index-39259ea4.development.esm.js';
1
+ import { P as ProcessingStatus, G as resolveReferencedActor, c as createActor, S as STATE_DELIMITER, H as mapValues, t as toArray, I as createInvokeId, J as getDelayedTransitions, K as evaluateCandidate, L as formatTransition, N as NULL_EVENT, M as toTransitionConfigArray, O as createInvokeTimeoutEvent, Q as getCandidates, R as formatRouteTransitions, U as resolveStateValue, V as getAllStateNodes, n as getStateNodes, W as createMachineSnapshot, X as isInFinalState, a as macrostep, Y as transitionNode, m as matchesEventDescriptor, Z as resolveAndExecuteActionsWithContext, b as createInitEvent, d as initialMicrostep, _ as toStatePath, $ as isStateId, a0 as getStateNodeByPath, a1 as getPersistedSnapshot, a2 as $$ACTOR_TYPE } from './index-e61170ba.development.esm.js';
2
2
 
3
3
  function createSpawner(actorScope, {
4
4
  machine,
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var dist_xstateActors = require('./index-f0d7107d.cjs.js');
3
+ var dist_xstateActors = require('./index-9cb3b3a0.cjs.js');
4
4
 
5
5
  function createSpawner(actorScope, {
6
6
  machine,
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var dist_xstateActors = require('./index-c35824b4.development.cjs.js');
3
+ var dist_xstateActors = require('./index-f6ef20d1.development.cjs.js');
4
4
 
5
5
  function createSpawner(actorScope, {
6
6
  machine,
@@ -2113,7 +2113,7 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
2113
2113
  if (typeof src === 'function') {
2114
2114
  src = src({
2115
2115
  actors: currentSnapshot.machine.implementations.actors,
2116
- context: currentSnapshot.context,
2116
+ context: nextState.context,
2117
2117
  event,
2118
2118
  self: actorScope.self
2119
2119
  });
@@ -2124,7 +2124,7 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
2124
2124
  }
2125
2125
  const input = typeof invokeDef.input === 'function' ? invokeDef.input({
2126
2126
  self: actorScope.self,
2127
- context: currentSnapshot.context,
2127
+ context: nextState.context,
2128
2128
  event
2129
2129
  }) : invokeDef.input;
2130
2130
  const actor = createActor(logic, {
@@ -2115,7 +2115,7 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
2115
2115
  if (typeof src === 'function') {
2116
2116
  src = src({
2117
2117
  actors: currentSnapshot.machine.implementations.actors,
2118
- context: currentSnapshot.context,
2118
+ context: nextState.context,
2119
2119
  event,
2120
2120
  self: actorScope.self
2121
2121
  });
@@ -2126,7 +2126,7 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
2126
2126
  }
2127
2127
  const input = typeof invokeDef.input === 'function' ? invokeDef.input({
2128
2128
  self: actorScope.self,
2129
- context: currentSnapshot.context,
2129
+ context: nextState.context,
2130
2130
  event
2131
2131
  }) : invokeDef.input;
2132
2132
  const actor = createActor(logic, {
@@ -2124,7 +2124,7 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
2124
2124
  if (typeof src === 'function') {
2125
2125
  src = src({
2126
2126
  actors: currentSnapshot.machine.implementations.actors,
2127
- context: currentSnapshot.context,
2127
+ context: nextState.context,
2128
2128
  event,
2129
2129
  self: actorScope.self
2130
2130
  });
@@ -2135,7 +2135,7 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
2135
2135
  }
2136
2136
  const input = typeof invokeDef.input === 'function' ? invokeDef.input({
2137
2137
  self: actorScope.self,
2138
- context: currentSnapshot.context,
2138
+ context: nextState.context,
2139
2139
  event
2140
2140
  }) : invokeDef.input;
2141
2141
  const actor = createActor(logic, {
@@ -2126,7 +2126,7 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
2126
2126
  if (typeof src === 'function') {
2127
2127
  src = src({
2128
2128
  actors: currentSnapshot.machine.implementations.actors,
2129
- context: currentSnapshot.context,
2129
+ context: nextState.context,
2130
2130
  event,
2131
2131
  self: actorScope.self
2132
2132
  });
@@ -2137,7 +2137,7 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
2137
2137
  }
2138
2138
  const input = typeof invokeDef.input === 'function' ? invokeDef.input({
2139
2139
  self: actorScope.self,
2140
- context: currentSnapshot.context,
2140
+ context: nextState.context,
2141
2141
  event
2142
2142
  }) : invokeDef.input;
2143
2143
  const actor = createActor(logic, {
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var dist_xstateActors = require('./index-f0d7107d.cjs.js');
5
+ var dist_xstateActors = require('./index-9cb3b3a0.cjs.js');
6
6
 
7
7
 
8
8
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var dist_xstateActors = require('./index-c35824b4.development.cjs.js');
5
+ var dist_xstateActors = require('./index-f6ef20d1.development.cjs.js');
6
6
 
7
7
 
8
8
 
@@ -1 +1 @@
1
- export { T as TimeoutError, B as createAsyncLogic, w as createCallbackLogic, v as createEmptyActor, y as createEventObservableLogic, C as createListenerLogic, z as createLogic, x as createObservableLogic, E as createSubscriptionLogic, D as listenerLogic, F as subscriptionLogic } from './index-39259ea4.development.esm.js';
1
+ export { T as TimeoutError, B as createAsyncLogic, w as createCallbackLogic, v as createEmptyActor, y as createEventObservableLogic, C as createListenerLogic, z as createLogic, x as createObservableLogic, E as createSubscriptionLogic, D as listenerLogic, F as subscriptionLogic } from './index-e61170ba.development.esm.js';
@@ -1 +1 @@
1
- export { T as TimeoutError, B as createAsyncLogic, w as createCallbackLogic, v as createEmptyActor, y as createEventObservableLogic, C as createListenerLogic, z as createLogic, x as createObservableLogic, E as createSubscriptionLogic, D as listenerLogic, F as subscriptionLogic } from './index-688701ed.esm.js';
1
+ export { T as TimeoutError, B as createAsyncLogic, w as createCallbackLogic, v as createEmptyActor, y as createEventObservableLogic, C as createListenerLogic, z as createLogic, x as createObservableLogic, E as createSubscriptionLogic, D as listenerLogic, F as subscriptionLogic } from './index-93edd3bd.esm.js';
@@ -2,8 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var dist_xstateActors = require('./index-f0d7107d.cjs.js');
6
- var StateMachine = require('./StateMachine-48dcad8f.cjs.js');
5
+ var dist_xstateActors = require('./index-9cb3b3a0.cjs.js');
6
+ var StateMachine = require('./StateMachine-64813f46.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-c35824b4.development.cjs.js');
6
- var StateMachine = require('./StateMachine-6e063ac1.development.cjs.js');
5
+ var dist_xstateActors = require('./index-f6ef20d1.development.cjs.js');
6
+ var StateMachine = require('./StateMachine-8d22a79c.development.cjs.js');
7
7
 
8
8
  function simpleStringify(value) {
9
9
  return JSON.stringify(value);
@@ -1,5 +1,5 @@
1
- import { l as isMachineSnapshot, o as getAllOwnEventDescriptors, v as createEmptyActor, a3 as XSTATE_INIT } from './index-39259ea4.development.esm.js';
2
- import { S as StateMachine } from './StateMachine-6ec50e21.development.esm.js';
1
+ import { l as isMachineSnapshot, o as getAllOwnEventDescriptors, v as createEmptyActor, a3 as XSTATE_INIT } from './index-e61170ba.development.esm.js';
2
+ import { S as StateMachine } from './StateMachine-2ea0a7fa.development.esm.js';
3
3
 
4
4
  function simpleStringify(value) {
5
5
  return JSON.stringify(value);
@@ -1,5 +1,5 @@
1
- import { l as isMachineSnapshot, o as getAllOwnEventDescriptors, v as createEmptyActor, a3 as XSTATE_INIT } from './index-688701ed.esm.js';
2
- import { S as StateMachine } from './StateMachine-47e60715.esm.js';
1
+ import { l as isMachineSnapshot, o as getAllOwnEventDescriptors, v as createEmptyActor, a3 as XSTATE_INIT } from './index-93edd3bd.esm.js';
2
+ import { S as StateMachine } from './StateMachine-2dcdb1f5.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){return{type:`xstate.timeout.actor.${t}`}}function i(t,e){return{type:`xstate.done.state.${t}`,output:e}}function r(t){return{type:s,input:t}}function c(t){setTimeout(()=>{throw t})}const a="function"==typeof Symbol&&Symbol.observable||"@@observable",h={"@xstate.start":t=>{t.start()},"@xstate.raise":(t,e,s)=>{t.system.scheduler.schedule(t.self,t.self,e,s?.delay??0,s?.id)},"@xstate.sendTo":(t,e,s,n)=>{if("string"==typeof s)throw new Error("Only event objects may be used with sendTo");void 0!==n?.delay?t.system.scheduler.schedule(t.self,e,s,n?.delay??0,n?.id):t.defer(()=>{t.system._relay(t.self,e,s)})},"@xstate.cancel":(t,e)=>{t.system.scheduler.cancel(t.self,e)},"@xstate.stopChild":(t,e)=>{t.stopChild(e)}},u=new WeakMap;function f(t){return{start:(e,{self:s,system:n})=>{const o=e.input.actor;if(!o||"function"==typeof o.getSnapshot&&"stopped"===o.getSnapshot().status)return;const i=t(e.input,{self:s,system:n});if(!i)return;let r,c=!1;const a=()=>{c||(c=!0,i.unsubscribe(),r?.unsubscribe())},h=s._parent;h&&(r=h.subscribe({complete:a,error:a})),u.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===n?(u.get(s)?.unsubscribe(),u.delete(s),{...t,status:"stopped",error:void 0}):t,getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function p(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function d(){return f(({actor:t,eventType:e,mapper:s},{self:n,system:o})=>{const i="*"!==e&&e.endsWith(".*");return t.on(i?"*":e,t=>{i&&!Mt(t.type,e)||p(n,o,()=>s(t))})})}const l=d(),y=Symbol.for("xstate.atom");function g(){return f(({actor:t,mappers:e},{self:s,system:n})=>{const{done:o,error:i,snapshot:r}=e;if((c=t)&&"object"==typeof c&&y in c){if(!r)return;return t.subscribe(t=>p(s,n,()=>r(t)))}var c;return t.subscribe({next:t=>{"done"===t.status&&o?p(s,n,()=>o(t.output)):"error"===t.status&&i?p(s,n,()=>i(t.error)):"active"===t.status&&r&&p(s,n,()=>r(t))},error:t=>{i&&p(s,n,()=>i(t))},complete:()=>{}})})}const v=g();function m(t,e,...s){t.push({action:e,args:s})}function _(t,e,s){m(t,h["@xstate.start"],e),t.push(function(t,e){return Object.assign(function(s){return{children:{...s.children,[e]:t}}},{_special:!0})}(e,s??e.id))}function S(t,e,s,n=!1){const o={cancel:s=>{m(e,h["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{m(e,t.logger,...s)},raise:(n,o)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0!==o?.delay?m(e,h["@xstate.raise"],t,n,o):s.push(n)},spawn:(s,n)=>{const o=Wt(s,{...n,parent:t.self});return _(e,o,n?.id),o},sendTo:(s,n,o)=>{s&&m(e,h["@xstate.sendTo"],t,s,n,o)},stop:s=>{s&&(m(e,h["@xstate.stopChild"],t,s),e.push(function(t){return Object.assign(function(e){const s={...e.children};for(const e of Object.keys(s))s[e]===t&&delete s[e];return{children:s}},{_special:!0})}(s)))}};return n&&Object.assign(o,{listen:(s,n,o)=>{const i=Wt(l,{input:{actor:s,eventType:n,mapper:o},parent:t.self});return m(e,h["@xstate.start"],i),i},subscribeTo:(s,n)=>{const o=Wt(v,{input:{actor:s,mappers:"function"==typeof n?{snapshot:n}:n},parent:t.self});return m(e,h["@xstate.start"],o),o}}),b(o,(t,...s)=>{m(e,t,...s)})}function x(t,e,s,n){let o=t;for(const i of n){const n="function"==typeof i?i:"object"==typeof i&&"action"in i&&"function"==typeof i.action&&i.action.bind(null,...i.args);n||"object"!=typeof i||null===i||s.defer(()=>{s.emit(i)});const r={context:o.context,event:e,self:s.self,system:s.system,children:o.children,parent:s.self._parent,actions:t.machine.implementations.actions,actors:t.machine.implementations.actors};let c;if("object"==typeof i&&null!==i){const{type:t,...e}=i;c=e}if(n&&"_special"in n){s.actionExecutor({type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type??"(anonymous)":i.name||"(anonymous)",params:c,args:[],exec:void 0});const t=n(r,w);t&&("context"in t||"children"in t)&&(o=gt(o,{..."context"in t?{context:t.context}:{},..."children"in t?{children:t.children}:{}}));continue}n&&"resolve"in n||s.actionExecutor({type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type:i.name||"(anonymous)",params:c,args:"object"==typeof i&&"action"in i?i.args:[],exec:n})}return o}function b(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),s}const w=b({},()=>{});function E(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const n=e.match(/^(\d*)(\.?)(\d*)s$/i);if(n){const t=n[1]?parseInt(n[1],10):0,e=!!n[2],s=n[3]?parseInt(n[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:i,days:r,hours:c,minutes:a,seconds:h}=o.groups;if(!(i||r||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(i)*24*60*60*1e3+24*u(r)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)??t}function $(t,e,s){if("function"==typeof t)return t(s);const n=E(t,e);return"function"==typeof n?n(s):n}function k(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function I(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function j(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function O(t){const e=new Set(t),s=new Set;for(const t of e)t.parent&&s.add(t.parent);for(const t of e)if("compound"!==t.type||s.has(t)){if("parallel"===t.type)for(const s of I(t))if(!e.has(s)){const t=R(s);for(const s of t)e.add(s)}}else for(const s of R(t))e.add(s);for(const t of e){let s=t.parent;for(;s&&!e.has(s);)e.add(s),s=s.parent}return e}function T(t,e){const s=O(e),n=new Map;for(const t of s)n.has(t)||n.set(t,[]),t.parent&&(n.has(t.parent)||n.set(t.parent,[]),n.get(t.parent).push(t));const o=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(k(t))return t.key}const s={};for(const t of e)s[t.key]=o(t);return s};return o(t)}function M(t,e){return"compound"===e.type?I(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?I(e).every(e=>M(t,e)):"final"===e.type}const A=t=>"#"===t[0];function P(t,e,s){const n=e.type,o=t.entry;t.entry=(t,i)=>(i.raise(e,{id:n,delay:s(t)}),"function"==typeof o?o(t,i):void 0);const i=t.exit;return t.exit=(t,e)=>(e.cancel(n),"function"==typeof i?i(t,e):void 0),n}function N(t,e,s){const n=It(s.target),o=s.reenter??!1,i=z(t,n),r={...s,target:i,source:t,reenter:o,eventType:e,toJSON:()=>({...r,source:`#${t.id}`,target:i?i.map(t=>`#${t.id}`):void 0})};return r}function z(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(A(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return B(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return B(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}function D(t){const e=It(t.config.target);return e?{target:e.map(e=>"string"==typeof e?B(t.parent,e):e),source:t,reenter:!1,eventType:""}:t.parent.initial}function J(t){return"history"===t.type}function R(t){const e=new Set;!function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of I(s))t(e)}(t);for(const s of e)for(const n of j(s,t))e.add(n);return e}function C(t,e){if(A(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const s=t.states[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function B(t,e){if("string"==typeof e&&A(e))try{return t.machine.getStateNodeById(e)}catch{}const s=St(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=C(n,t)}return n}function V(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=new Array(s.length),o=[t.machine.root,t];for(let e=0;e<s.length;e++){const i=C(t,s[e]);n[e]=i,o.push(i)}for(let t=0;t<s.length;t++)o.push(...V(n[t],e[s[t]]));return o}function L(t,e,s,n,o){if("string"==typeof e){const i=C(t,e).next(s,n,o);return i&&i.length?i:t.next(s,n,o)}const i=Object.keys(e),r=i[0];if(1===i.length){const i=L(C(t,r),e[r],s,n,o);return i&&i.length?i:t.next(s,n,o)}const c=[];for(const r of i){const i=e[r];if(!i)continue;const a=L(C(t,r),i,s,n,o);a&&c.push(...a)}return c.length?c:t.next(s,n,o)}function W(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function q(t,e){for(const s of t)if(W(s,e))return!0;return!1}function G(t,e){const s=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,n=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==s&&void 0!==n&&n<s&&([t,e]=[e,t]);const o=t instanceof Set?t:new Set(t);for(const t of e)if(o.has(t))return!0;return!1}function F(t,e,s,n,o){const i=new Set,r=new Map,c=t=>{let i=r.get(t);return i||(i=H([t],e,s,n,o),r.set(t,i)),i};for(const e of t){let t=!1;const s=new Set;for(const n of i)if(G(c(e),c(n))){if(!W(e.source,n.source)){t=!0;break}s.add(n)}if(!t){for(const t of s)i.delete(t);i.add(e)}}return Array.from(i)}function K(t,e,s,n){const o=e.historyValue,{targets:i}=Q(t,e,s,n);if(!i)return[];const r=new Set;for(const t of i)if(J(t))if(o[t.id])for(const e of o[t.id])r.add(e);else for(const o of K(D(t),e,s,n))r.add(o);else r.add(t);return[...r]}function U(t,e,s,n){const o=K(t,e,s,n),{reenter:i}=Q(t,e,s,n);if(!i&&o.every(e=>e===t.source||W(e,t.source)))return t.source;const[r,...c]=o.concat(t.source);for(const t of j(r,void 0))if(c.every(e=>W(e,t)))return t;return i?void 0:t.source.machine.root}function H(t,e,s,n,o){const i=new Set;for(const r of t){const{targets:t}=Q(r,s,n,o);if(t?.length){const t=U(r,s,n,o);r.reenter&&r.source===t&&i.add(t);for(const s of e)W(s,t)&&i.add(s)}}return[...i]}function X(t,e,s,n,o,r){const c=[];if(!t.length)return[e,c];const a=s.actionExecutor;s.actionExecutor=t=>{c.push(t),a(t)};try{const a=new Set(e._nodes);let u=e.historyValue;const f=e.context,p=F(t,a,e,n,s),d=t=>Q(t,e,n,s),l=(t,o,i,r)=>{if(2===t.length){const c=[],a=[];let h;const u=S(s,c,a,!0),f=t({context:o,event:n,parent:s.self._parent,self:s.self,children:i,system:s.system,actions:e.machine.implementations.actions,actors:e.machine.implementations.actors,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays,input:r},u);return f?.context&&(h=f.context),[c,h,a]}return[[Object.assign((e,s)=>t({...e,input:r},s),"_special"in t?{_special:!0}:{})],void 0,void 0]};let y=e;const g=()=>{const t=H(p,a,e,n,s);let o;t.sort((t,e)=>e.order-t.order);const i=[...a];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>k(t)&&W(t,e):t=>t.parent===e;o??={...u},o[t.id]=i.filter(s)}for(const o of t){const t=e._stateInputs?.[o.id],[i,c,h]=o.exit?l(o.exit,y.context,e.children,t):[[]];h?.length&&r.push(...h),c&&(y=gt(y,{context:c})),y=x(y,n,s,i);for(const t of o.invoke){const e=y.children[t.id];e&&!e._isExternal&&s.stopChild(e),delete y.children[t.id]}a.delete(o)}u=o||u};o||g();let v=y.context;const m=[],_=[];for(const t of p){t.actions&&m.push(...wt(t.actions));const e=d(t);e.context&&(v=e.context),e.actions&&m.push(...e.actions),e.internalEvents&&_.push(...e.internalEvents)}_.length&&r.push(..._);const b=()=>{const t=t=>{const e=y.machine.root;if(void 0===e.output)return;let o;if(void 0!==t.output&&t.parent)o=Et(t.output,y.context,n,s.self);else if("parallel"===t.type){const e=`xstate.done.state.${t.id}`,s=r.find(t=>t.type===e);o=s?.output}return Et(e.output,y.context,i(t.id,o),s.self)},c=new Set,f=new Set,g=(t,e)=>{for(const s of t)if(e&&!W(s,e)||c.add(s),"parallel"===s.type)for(const t of I(s))q(c,t)||(c.add(t),v(t))},v=t=>{if(J(t))if(u[t.id]){const e=u[t.id];for(const t of e)c.add(t),v(t);for(const s of e)g(j(s,t.parent),void 0)}else{const e=D(t),{targets:s}=d(e);for(const n of s??[])c.add(n),e===t.parent?.initial&&f.add(t.parent),v(n);for(const e of s??[])g(j(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=d(t.initial).targets;return J(e)||(c.add(e),f.add(e)),v(e),void g(j(e,t),void 0)}if("parallel"===t.type)for(const e of I(t))q(c,e)||(c.add(e),f.add(e),v(e))}};for(const t of p){const o=U(t,e,n,s),{targets:i,reenter:r}=d(t);for(const e of i??[])J(e)||t.source===e&&t.source===o&&!r||(c.add(e),f.add(e)),v(e);const a=K(t,e,n,s);for(const e of a){const s=j(e,o);"parallel"===o?.type&&s.push(o),g(s,!t.source.parent&&r?void 0:o)}}o&&f.add(e.machine.root);const m={...e._stateInputs};for(const t of p){const{targets:e,input:s}=d(t);if(s&&e)for(const t of e)m[t.id]=s}const _=new Set,S={...e.children};for(const o of[...c].sort((t,e)=>t.order-e.order)){a.add(o);const c=[];let u,p=!1;for(const t of o.invoke){p=!0;let o=t.logic;"function"==typeof o&&(o=o({actors:e.machine.implementations.actors,context:e.context,event:n,self:s.self}));const i="string"==typeof o?Ot(e.machine,o):o;if(!i)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented in machine '${e.machine.id}'`);const r="function"==typeof t.input?t.input({self:s.self,context:e.context,event:n}):t.input,a=Wt(i,{...t,input:r,parent:s.self,syncSnapshot:!!t.onSnapshot});c.push({action:h["@xstate.start"],args:[a]}),t.id&&(S[t.id]=a)}p&&(y=gt(y,{children:S}));const d=m[o.id];if(o.entry){const[t,e,s]=l(o.entry,y.context,S,d);c.push(...t),s?.length&&r.push(...s),e&&(u=e)}if(f.has(o)){const{actions:t,input:e}=Q(o.initial,y,n,s);if(t&&c.push(...t),e&&o.initial?.target)for(const t of o.initial.target)m[t.id]=e}if(y=x(y,n,s,c),u&&(y.context=u),"final"!==o.type)continue;const g=o.parent;let v="parallel"===g?.type?g:g?.parent,b=v||o;for("compound"===g?.type&&r.push(i(g.id,void 0!==o.output?Et(o.output,y.context,n,s.self):void 0));"parallel"===v?.type&&!_.has(v)&&M(a,v);){_.add(v);const t={};for(const e of I(v)){if("final"===e.type){t[e.key]=void 0!==e.output?Et(e.output,y.context,n,s.self):void 0;continue}if("parallel"===e.type){const s=`xstate.done.state.${e.id}`,n=r.find(t=>t.type===s);t[e.key]=n?.output;continue}const o=I(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==o?.output?Et(o.output,y.context,n,s.self):void 0}r.push(i(v.id,t)),b=v,v=v.parent}v||(y=gt(y,{status:"done",output:t(b)}))}JSON.stringify(m)!==JSON.stringify(e._stateInputs||{})&&(y=gt(y,{_stateInputs:m}))};y=x(y,n,s,m),v&&v!==e.context&&(y=gt(y,{context:v})),b();const w=[...a];if("done"===y.status){const t=[];w.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=y._stateInputs?.[e.id],[n,,o]=l(e.exit,y.context,y.children,s);t.push(...n),o?.length&&r.push(...o)}}),y=x(y,n,s,t)}return u===e.historyValue&&e._nodes.length===a.size&&e._nodes.every(t=>a.has(t))?y.context!==f?[gt(y),c]:[y,c]:[gt(y,{_nodes:w,historyValue:u}),c]}finally{s.actionExecutor=a}}function Q(t,e,s,n){if(t.to){const o=[],i=[],r=S(n,o,i),c=t.to({context:e.context,event:s,value:e.value,children:e.children,parent:n.self._parent,self:n.self,actions:e.machine.implementations.actions,actors:e.machine.implementations.actors,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays},r),a=c?.target?z(t.source,wt(c.target)):void 0,h="function"==typeof t.input?t.input({context:e.context,event:s}):t.input;return{targets:a,context:c?.context,reenter:c?.reenter,actions:o,internalEvents:i,input:h}}const o="function"==typeof t.input?t.input({context:e.context,event:s}):t.input;return{targets:t.target,context:void 0,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:o}}function Y(t,e,o,i){let r=t;const c=[];function a(t,e){const s=o.self._collectedMicrosteps||[];s.push(...e),o.self._collectedMicrosteps=s,c.push(t)}if(e.type===n)return r=gt(et(r,o),{status:"stopped"}),a([r,[]],[]),{snapshot:r,microsteps:c};let h=e;if(h.type!==s){const e=h,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),n=r.machine.getTransitionData(r,e,o.self);if(s&&!n.length)return r=gt(t,{status:"error",error:e.error}),a([r,[]],[]),{snapshot:r,microsteps:c};const u=X(n,t,o,h,!1,i);r=u[0],a(u,n)}let u=!0;const f=t.machine.options?.maxIterations??1/0;let p=0,d=0;for(;"active"===r.status;){if(d++,d>1e3)throw new Error("Microstep count exceeded 1000");if(p++,p>f)throw new Error(`Infinite loop detected (>${f} microsteps)`);let t=u?st(r,h,o):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;h=i.shift(),t=r.machine.getTransitionData(r,h,o.self)}const s=X(t,r,o,h,!1,i);r=s[0],u=r!==e,a(s,t)}return"active"!==r.status&&r.children&&et(r,o),{snapshot:r,microsteps:c}}function Z(t,e,s,n,o){return!!t.to&&tt(t.to,e,s,n,o,n.machine.implementations)}function tt(t,e,s,n,o,i){let r,c=!1;try{const a=()=>{throw c=!0,new Error("Effect triggered")};r=t({context:e,event:s,self:o,value:n.value,children:n.children,parent:{send:a},actions:i.actions,actors:i.actors,guards:i.guards,delays:i.delays},function(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),s}({emit:a,cancel:a,log:a,raise:a,spawn:a,sendTo:a,stop:a},a))}catch(t){if(c)return!0;throw t}return void 0!==r}function et(t,e){let s;if(!t.children||0===(s=Object.values(t.children).filter(Boolean)).length)return t;for(const t of s)e.stopChild(t);return gt(t,{children:{}})}function st(t,e,s){const n=new Set,o=t._nodes.filter(k);for(const i of o)t:for(let o=i;o;o=o.parent)if(o.always)for(const i of o.always)if(nt(i,e,t,o,s.self)){n.add(i);break t}return F(Array.from(n),new Set(t._nodes),t,e,s)}function nt(t,e,s,n,o){if(t.guard){const i={context:s.context,event:e,self:o,parent:o._parent,children:s.children,actions:n.machine.implementations.actions,actors:n.machine.implementations.actors,guards:n.machine.implementations.guards,delays:n.machine.implementations.delays,_snapshot:s},r=t.guard,c="function"==typeof r?.params?r.params({context:s.context,event:e}):r?.params;let a=!0;if("function"==typeof r)a=r(i,c);else if("string"==typeof r?.type){const t=n.machine.implementations.guards[r.type];if(!t)throw new Error(`Guard '${r.type}' is not implemented in machine '${n.machine.id}'.`);a=t(i,c)}if(!a)return!1}return!t.to||tt(t.to,s.context,e,s,o,n.machine.implementations)}function ot(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}let it,rt;function ct(){return it??=Gt()}const at=function(t){return _t(t,this.value)},ht=function(t){return this.tags.has(t)},ut=function(t){const e=ct(),s=function(){if(rt)return rt;const t=ct();return rt={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},rt}(),n=this.machine.getTransitionData(this,t,e);if(!n?.length)return!1;for(const o of n){if(void 0!==o.target)return!0;const n=Q(o,this,t,s);if(n.targets?.length||n.context||Z(o,this.context,t,this,e))return!0}return!1},ft=function(){const{_nodes:t,_stateInputs:e,tags:s,machine:n,getMeta:o,getInputs:i,toJSON:r,can:c,hasTag:a,matches:h,...u}=this;return{...u,tags:Array.from(s)}},pt=function(){const t={};for(const e of this._nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},dt=function(){return this._stateInputs};function lt(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function yt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:t.value??T(e.root,t._nodes),tags:lt(t._nodes),children:t.children,historyValue:t.historyValue||{},_stateInputs:t._stateInputs||{},matches:at,hasTag:ht,can:ut,getMeta:pt,getInputs:dt,toJSON:ft}}function gt(t,e={}){const s={...t,...e};return(e._nodes??t._nodes)===t._nodes?{status:s.status,output:s.output,error:s.error,machine:t.machine,context:s.context,_nodes:t._nodes,value:t.value,tags:t.tags,children:s.children,historyValue:s.historyValue||{},_stateInputs:s._stateInputs||{},matches:at,hasTag:ht,can:ut,getMeta:pt,getInputs:dt,toJSON:ft}:yt({...s,value:void 0},t.machine)}function vt(t){const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map(t=>({id:t.id})))}return e}function mt(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:Rt,id:n.id};else{const o=mt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function _t(t,e){const s=xt(t),n=xt(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&_t(s[t],n[t]))}function St(t){if($t(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function xt(t){if(ot(t))return t.value;if("string"!=typeof t)return t;return function(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}(St(t))}function bt(t){return $t(t)?t:[t]}function wt(t){return void 0===t?[]:bt(t)}function Et(t,e,s,n){return"function"==typeof t?t({context:e,event:s,self:n}):t}function $t(t){return Array.isArray(t)}function kt(t){return bt(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function It(t){if(void 0!==t&&""!==t)return wt(t)}function jt(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function Ot(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actors[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke,r=(Array.isArray(i)?i[n]:i).src;return"string"==typeof r?t.implementations.actors[r]:r}function Tt(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]}function Mt(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}function At(t,e){return`${t.sessionId}.${e}`}const Pt=new WeakMap;function Nt(t){let e=Pt.get(t);return e||(e=new Map,Pt.set(t,e)),e}function zt(t,e){if(t?.length)for(const s of t)switch(s.type){case"emit":e.emit(s.event);break;case"sendBack":{const t=e.self._parent;t&&e.system._relay(e.self,t,s.event);break}case"raise":e.system._relay(e.self,e.self,s.event);break;case"effect":{if(!s.key){const t=s.exec();"function"==typeof t&&Nt(e.self).set(Symbol(),{cleanup:t});break}const t=Nt(e.self);if(t.has(s.key))break;const n=s.exec();t.set(s.key,{cleanup:"function"==typeof n?n:void 0});break}case"cleanupEffects":{const t=Pt.get(e.self);if(!t)break;for(const{cleanup:e}of t.values())e?.();Pt.delete(e.self);break}}}function Dt(t){const e=(e,s,o)=>{if("active"!==e.status)return[e,[]];if(s.type===n)return[{...e,status:"stopped",input:void 0},[{type:"cleanupEffects"}]];if("xstate.logic.effect.start"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if("xstate.logic.effect.resolve"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if("xstate.logic.effect.reject"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const i=[],r={},c={emit:t=>{i.push({type:"emit",event:t})},sendBack:t=>{i.push({type:"sendBack",event:t})},raise:t=>{i.push({type:"raise",event:t})},effect:(t,s)=>{if("string"==typeof t)return n=t,o=s,void(e.effects?.[n]||(i.push({type:"effect",key:n,exec:o}),r[n]={status:"active"}));var n,o;i.push({type:"effect",exec:t})}},a=t.run({context:e.context,event:s,input:e.input,system:o.system,self:o.self,emit:o.emit},c),h={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(h.context=a?.context??e.context),(a?.effects||Object.keys(r).length)&&(h.effects={...e.effects,...a?.effects,...r}),[h,i]};return{id:t.id,config:t,transition:e,start:(t,s)=>{const[n,o]=e(t,r(t.input),s);Object.assign(t,n),zt(o,s)},getInitialSnapshot:(e,s)=>{const n=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,s),o={status:"active",output:void 0,error:void 0,input:s};return void 0!==n&&(o.context=n),{...o}},getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}let Jt=!1;const Rt=1;let Ct=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Bt={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)};class Vt{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=this._process.bind(this),this.mailbox=new e(this._boundProcess),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=Ct.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[],this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this.trigger=void 0,this.src=void 0,this._deferred=[],this._pendingEffects=void 0;const n={...Bt,...s},{clock:o,logger:i,parent:r,syncSnapshot:a,id:h,systemId:u,inspect:f}=n;this.system=r?r.system:function(t,e){let s=0;const n=new Map,o=new Map,i=new WeakMap,r=new Set,c={},{clock:a,logger:h}=e,u=(t,e,s,n,o)=>{r.size&&t&&(t._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:o})},f={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{u(t,e,s,n,o);const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},r=At(t,o);d._snapshot._scheduledEvents[r]=i;const h=a.setTimeout(()=>{delete c[r],delete d._snapshot._scheduledEvents[r],p(t,e,s)},n);c[r]=h},cancel:(t,e)=>{const s=At(t,e),n=c[s];delete c[s],delete d._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in d._snapshot._scheduledEvents){const s=d._snapshot._scheduledEvents[e];s.source===t&&f.cancel(t,s.id)}}},p=(t,e,s)=>{const n=e.logic;if("function"==typeof n?.isInternalEventType&&n.isInternalEventType(s.type)&&t!==e)throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`);e._lastSourceRef=t,e._send(s)},d={children:n,reverseKeyedActors:i,keyedActors:o,_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+s++,_register:(t,e)=>(n.set(t,e),t),_unregister:t=>{n.delete(t.sessionId);const e=i.get(t);void 0!==e&&(o.delete(e),i.delete(t))},get:t=>o.get(t),getAll:()=>Object.fromEntries(o.entries()),_set:(t,e)=>{const s=o.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);o.set(t,e),i.set(e,t)},inspect:t=>{const e=jt(t);return r.add(e),{unsubscribe(){r.delete(e)}}},_sendInspectionEvent:e=>{if(!r.size)return;const s={...e,rootId:t.sessionId};r.forEach(t=>t.next?.(s))},_relay:(t,e,s)=>{u(t,e,s),p(t,e,s)},scheduler:f,getSnapshot:()=>({_scheduledEvents:{...d._snapshot._scheduledEvents}}),start:()=>{const t=d._snapshot._scheduledEvents;d._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];f.schedule(s,n,o,i,r)}},_clock:a,_logger:h,_timerStrategy:e.timers};return d}(this,{clock:o,logger:i,timers:n.timers}),f&&!r&&this.system.inspect(jt(f)),this.sessionId=this.system._bookId(),this.id=h??this.sessionId,this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=r,this._syncSnapshot=a,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get("*");if(e||s){if(e)for(const s of e)try{s(t)}catch(t){c(t)}if(s)for(const e of s)try{e(t)}catch(t){c(t)}}},actionExecutor:t=>{const e=()=>{if(this._collectedActions.push({type:t.type,params:t.params}),!t.exec)return;const e=Jt;try{Jt=!0,t.exec()}finally{Jt=e}};this._processingStatus===Ct.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.trigger=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}}),u&&(this.systemId=u,this.system._set(u,this)),this._collectedMicrosteps=[];let p=s?.snapshot??s?.state;if(p&&"object"==typeof p&&"_pendingEffects"in p){const{_pendingEffects:t,...e}=p;this._pendingEffects=t,p=e}try{this._snapshot=p?this.logic.restoreSnapshot?this.logic.restoreSnapshot(p,this._actorScope):p:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t},this._deferred.length=0}u&&"active"!==this._snapshot.status&&this.system._unregister(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_setErrorSnapshot(t,e=this._snapshot){this._snapshot={...e,status:"error",error:t}}_next(t){for(const e of this.observers)try{e.next?.(t)}catch(t){c(t)}}update(t,e){this._snapshot=t;for(let e=0;e<this._deferred.length;e++){const s=this._deferred[e];try{s()}catch(e){this._deferred.length=0,this._setErrorSnapshot(e,t);break}}switch(this._deferred.length=0,this._snapshot.status){case"active":this._next(t);break;case"done":{this._next(t),this._stopProcedure(),this._complete();const e=(s=this.id,n=this._snapshot.output,{type:`xstate.done.actor.${s}`,output:n,actorId:s});this._parent&&this.system._relay(this,this._parent,e);break}case"error":this._error(this._snapshot.error)}var s,n;this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps,actions:this._collectedActions,sent:this._collectedSent,eventType:e.type}),this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[]}subscribe(t,e,s){const n=jt(t,e,s);if(this._processingStatus!==Ct.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){c(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){c(t)}else c(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);return s||(s=new Set,this.eventListeners.set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,o)=>{const i=jt(s,n,o);let r=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(r,n)||(r=n,i.next?.(n))},error:i.error,complete:i.complete})},get:()=>t(this.get())}}start(){if(this._processingStatus===Ct.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=Ct.Running;const t=r(this.options.input);this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this.update(this._snapshot,t),this._pendingEffects){const t=this.options.timers??this.system._timerStrategy??"resume";for(const e of this._pendingEffects)"@xstate.raise"===e.type&&this.system.scheduler.schedule(this,this,e.event,Lt(t,e),e.id);this._pendingEffects=void 0}return this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._setErrorSnapshot(t),void this._error(t)}const[o,i]=Array.isArray(e)?e:[e,void 0];this.update(o,t),zt(i,this._actorScope),t.type===n&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===Ct.Stopped?this:(this.mailbox.clear(),this._processingStatus===Ct.NotStarted?(this._processingStatus=Ct.Stopped,this):(this.mailbox.enqueue({type:n}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){c(t)}this.observers.clear(),this.eventListeners.clear()}_error(t){if(this._stopProcedure(),this.observers.size){let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){c(t)}}this.observers.clear(),this.eventListeners.clear(),e&&c(t)}else this._parent||c(t),this.eventListeners.clear();var e;this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${e=this.id}`,error:t,actorId:e})}_stopProcedure(){this._processingStatus===Ct.Running&&(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._boundProcess),this._processingStatus=Ct.Stopped,this.system._unregister(this))}_send(t){this._processingStatus!==Ct.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$$type:Rt,id:this.id}}getPersistedSnapshot(t){const e=this.logic.getPersistedSnapshot(this._snapshot,t),s=this.system._snapshot._scheduledEvents;let n;const o=Date.now();for(const t in s){const e=s[t];e.source===this&&e.target===this&&(n??=[]).push({type:"@xstate.raise",event:e.event,id:e.id,delay:e.delay,startedAt:e.startedAt,elapsed:Math.max(0,o-e.startedAt)})}return n??=this._pendingEffects,n?{...e,_pendingEffects:n}:e}[a](){return this}getSnapshot(){return this.get()}get(){return this._snapshot}}function Lt(t,e){if("function"==typeof t)return t(e);switch(t){case"restart":return e.delay;case"absolute":return Math.max(0,e.startedAt+e.delay-Date.now());default:return Math.max(0,e.delay-e.elapsed)}}function Wt(t,e){return new Vt(t,e)}const qt=Dt({context:void 0,run:()=>{}});function Gt(){return Wt(qt)}function Ft(t,{machine:e,context:s},n,o){return(i,r)=>{const c=((i,r)=>{if("string"==typeof i){const c=Ot(e,i);if(!c)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const a=Wt(c,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:s,event:n,self:t.self}):r?.input,src:i,systemId:r?.systemId});return o[a.id]=a,a}return Wt(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[c.id]=c,t.defer(()=>{c._processingStatus!==Ct.Stopped&&c.start()}),c}}const Kt=new WeakMap;function Ut(t,e,s){let n=Kt.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Kt.set(t,n)),n[e]}const Ht={},Xt=["invoke","after","on","entry","exit","always","states","initial","onDone","timeout","onTimeout","history","target","output"];class Qt{constructor(t,e){this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.invoke=void 0,this.on=void 0,this.after=void 0,this.events=void 0,this.ownEvents=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[];const s=this.config.states?Object.keys(this.config.states)[0]:void 0;if(this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(void 0!==s?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,function(t){const e=t.config;if("choice"!==t.type){if(void 0!==e.choice)throw new Error(`State "${t.id}" has \`choice\`, but \`choice\` can only be used with \`type: 'choice'\`.`);return}if("function"!=typeof e.choice)throw new Error(`Choice state "${t.id}" must declare a \`choice\` function.`);for(const s of Xt)if(void 0!==e[s])throw new Error(`Choice state "${t.id}" cannot declare \`${s}\`.`)}(this),this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const i=n[o];s[i]=e(t[i],i,t,o)}return s}(this.config.states,(t,e)=>new Qt(t,{_parent:this,_key:e,_machine:this.machine})):Ht,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}".`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.entry&&(this.entry._special=!0),this.exit&&(this.exit._special=!0),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=wt(t.tags).slice(),this.invoke=wt(this.config.invoke).map((t,e)=>{const{src:s,systemId:n}=t,o=(i=this.id,`${e}.${i}`);var i;const r=t.id??o,c="string"==typeof s?s:`xstate.invoke.${o}`;return{...t,src:c,logic:s,id:r,systemId:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,i=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===i.length)return[];const r=e=>{const s={type:`xstate.after.${e}.${t.id}`};return P(t,s,s=>$(e,s.delays,{context:s.context,event:s.event,stateNode:t}))},c=[],a=(t,e,s)=>{for(const n of kt(t))c.push({...n,event:e,delay:s})};if(e)for(const s of Object.keys(e)){const n=e[s],o=Number.isNaN(+s)?s:+s;a(n,r(o),E(o,t.machine.implementations.delays))}if(void 0!==s&&n){const e={type:`xstate.timeout.${t.id}`};a(n,P(t,e,e=>$(s,e.delays,{context:e.context,event:e.event,stateNode:t})),"function"==typeof s?s:E(s,t.machine.implementations.delays))}for(const e of i){const s=o(e.id),n=e.timeout,i=P(t,s,e=>$(n,{},{context:e.context,event:e.event,stateNode:t}));a(e.onTimeout,i,n)}return c.map(e=>({...N(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=t.config.on[s];e.set(s,Yt(n,e=>N(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,Yt(t.config.onDone,e=>N(t,s,e)))}const s=(e,s)=>N(t,e,{to:(t,e)=>(e.cancel(s),{})}),n=(e,s,n)=>{const{target:o,to:i,reenter:r,...c}=s;return N(t,e,{...c,reenter:r,to:(t,e)=>{if(i){let s=!1;const o=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const o=Reflect.get(t,e,n);return"function"!=typeof o?o:(...e)=>(s=!0,o.apply(t,e))}}),r=i(t,o);return(void 0!==r||s)&&e.cancel(n),r}return e.cancel(n),{target:o,reenter:r}}})};for(const i of t.invoke){const r=void 0!==i.timeout?o(i.id).type:void 0;if(i.onDone){const o=`xstate.done.actor.${i.id}`,c=Yt(i.onDone,e=>r?n(o,e,r):N(t,o,e));r&&c.push(s(o,r)),e.set(o,c)}else if(r){const t=`xstate.done.actor.${i.id}`;e.set(t,[s(t,r)])}if(i.onError){const s=`xstate.error.actor.${i.id}`;e.set(s,Yt(i.onError,e=>r?n(s,e,r):N(t,s,e)))}if(i.onSnapshot){const s=`xstate.snapshot.${i.id}`;e.set(s,Yt(i.onSnapshot,e=>N(t,s,e)))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),"choice"===this.type?this.always=function(t){const e=t.config.choice,s=e=>{if(!e||void 0===e.target)throw new Error(`Choice state "${t.id}" must resolve to a target.`);for(const s of["actions","to","context"])if(void 0!==e[s])throw new Error(`Choice state "${t.id}" cannot declare \`${s}\` on a choice.`);return e};return[N(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=Yt(this.config.always,t=>N(this,"",t)));for(const t of Object.keys(this.states))this.states[t]._initialize();this._refreshEventMetadata()}_refreshEventMetadata(){const t={},e=[];for(const[s,n]of this.transitions)t[s]=n.slice(),n.some(t=>t.target||t.reenter||t.to)&&e.push(s);this.on=t,this.ownEvents=e;const s=new Set(e);for(const t of Object.values(this.states))for(const e of t.events)s.add(e);this.events=Array.from(s)}get initial(){return Ut(this,"initial",()=>function(t,e){const s="object"==typeof e&&null!==e?e.target:e,n="object"==typeof e&&null!==e?e.input:void 0,o="string"==typeof s?t.states[s]:void 0;if(!o&&s)throw new Error(`Initial state node "${s}" not found on parent state node #${t.id}`);return{source:t,target:o?[o]:void 0,input:n}}(this,this.config.initial))}next(t,e,s){const n=e.type,o=Ut(this,`candidates-${n}`,()=>function(t,e){const s=t.transitions.get(e);if(s)return s;const n=[];for(const s of t.transitions.keys())Mt(e,s)&&n.push(s);n.sort((t,e)=>e.length-t.length);const o=[];for(const e of n)o.push(...t.transitions.get(e));return o}(this,n));for(const n of o){if(nt(n,e,t,this,s))return[n]}}}function Yt(t,e){const s=kt(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}class Zt{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._json=void 0,this.id=t.id||"(machine)",this.implementations={actors:t.actors??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...e},this.version=this.config.version,this.schemas=this.config.schemas,this.internalEventDescriptors=this.config.internalEvents??[],this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new Qt(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const o=n.config.id,i=n.config.route,r=({event:t})=>t.to===`#${o}`;if("function"==typeof i)return e.push(N(t,"xstate.route",{guard:r,to:t=>{const e=i(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(n.states&&s(n.states));if("$unserializable"in i)throw new Error(`State "${n.id}" has a route that is not serializable. Re-provide the route function when reviving this machine.`);const c=i.guard,a={...i,guard:c?e=>{if(!r(e))return!1;if("function"==typeof c)return c(e);if("string"==typeof c){const s=e.guards?.[c];if(!s)throw new Error(`Guard '${c}' is not implemented in machine '${t.machine.id}'.`);return s(e)}return!0}:r,target:`#${o}`};e.push(N(t,"xstate.route",a))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.root._refreshEventMetadata(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.implementations,i=new Zt(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}});return i._json=this._json,i}resolveState(t){const e=(s=this.root,n=t.value,T(s,O(V(s,n))));var s,n;const o=O(V(this.root,e));return yt({_nodes:[...o],value:e,context:t.context||{},children:{},status:M(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return Y(t,e,s,[]).snapshot}microstep(t,e,s){const{microsteps:n}=Y(t,e,s,[]),o=new Array(n.length);for(let t=0;t<n.length;t++)o[t]=n[t][0];return o}getTransitionData(t,e,s){return L(this.root,t.value,t,e,s)||[]}isInternalEventType(t){for(const e of this.internalEventDescriptors)if(Mt(t,e))return!0;return!1}_getPreInitialState(t,e){const{context:s}=this.config,n=yt({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const o={},i=s({spawn:Ft(t,n,e,o),input:e.input,self:t.self,actors:this.implementations.actors}),r=x(n,e,t,[]);return i&&(r.context=i),Object.keys(o).length>0&&(r.children={...r.children,...o}),r}return n}getInitialSnapshot(t,e){const s=r(e),n=[],o=this._getPreInitialState(t,s),[i]=function(t,e,s,n,o){return X([{target:[...R(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,o,t,s,n),{snapshot:c}=Y(i,s,t,n);return c}start(t){if(t?.children)for(const e of Object.values(t.children))e._rehydrated&&"active"===e.getSnapshot?.().status&&e.start()}getStateNodeById(t){const e=St(t),s=e.slice(1),n=A(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return B(o,s)}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,_stateInputs:n,tags:o,machine:i,children:r,context:c,can:a,hasTag:h,matches:u,getMeta:f,getInputs:p,toJSON:d,...l}=t,y={};for(const t in r){const s=r[t];y[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s.systemId,syncSnapshot:s._syncSnapshot}}const g={...l,context:mt(c),children:y,historyValue:vt(l.historyValue)};return void 0!==i.version&&(g.version=i.version),g}(t,e)}restoreSnapshot(t,e){const s=t.version;if(s!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${s}' does not match machine version '${this.version}'.`);t=e(t,s)}const n=t,o={},i=n.children;for(const t of Object.keys(i)){const s=i[t],n=s.snapshot,r=s.src,c="string"==typeof r?Ot(this,r):r;if(!c)continue;const a=Wt(c,{id:t,parent:e.self,syncSnapshot:s.syncSnapshot,snapshot:n,src:r,systemId:s.systemId});a._rehydrated=!0,o[t]=a}const r=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const s of Object.keys(t)){const n=t[s];for(const t of n){let n;if(t instanceof Qt)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(n.historyValue),c=Array.from(O(V(this.root,n.value))),{version:a,...h}=t,u=yt({...h,children:o,_nodes:c,value:n.value,historyValue:r},this),f=new WeakSet;return function t(e){if(!f.has(e)){f.add(e);for(const s of Object.keys(e)){const n=e[s];if(n&&"object"==typeof n){if("xstate$$type"in n&&n.xstate$$type===Rt){e[s]=o[n.id];continue}t(n)}}}}(u.context),u}}function te(t){return JSON.stringify(t)}function ee(t){const e=Object.keys(t.context).length?`(${JSON.stringify(t.context)})`:"",s=t._nodes.filter(t=>"atomic"===t.type||"final"===t.type).map(({id:e,path:s})=>{const n=t.getMeta()[e];if(!n)return`"${s.join(".")}"`;const{description:o}=n;return"function"==typeof o?o(t):o?`"${o}"`:JSON.stringify(t.value)});return`state${1===s.length?"":"s"} `+s.join(", ")+` ${e}`.trim()}const se=()=>(t,e)=>_e(t,e),ne=()=>(t,e)=>Se(t,e);class oe{getDefaultOptions(){return{serializeState:t=>te(t),serializeEvent:t=>te(t),serializeTransition:(t,e)=>`${te(t)}|${e?.type}`,events:[],stateMatcher:(t,e)=>"*"===e,logger:{log:console.log.bind(console),error:console.error.bind(console)}}}constructor(t,e){this.testLogic=t,this.options=void 0,this.defaultTraversalOptions=void 0,this._toTestPath=t=>{const e=t.steps.map(t=>function(t){const{type:e,...s}=t;return`${e}${Object.keys(s).length?` (${JSON.stringify(s)})`:""}`}(t.event)).join(" → ");return{...t,test:e=>this.testPath(t,e),description:ot(t.state)?`Reaches ${ee(t.state).trim()}: ${e}`:JSON.stringify(t.state)}},this.options={...this.getDefaultOptions(),...e}}getPaths(t,e){const s=e?.allowDuplicatePaths??!1,n=t(this.testLogic,this._resolveOptions(e));return(s?n:((t,e=te)=>{const s=[];t.forEach(t=>{s.push({path:t,eventSequence:t.steps.map(t=>e(t.event))})}),s.sort((t,e)=>e.path.steps.length-t.path.steps.length);const n=[];t:for(const t of s){e:for(const e of n){for(const s in t.eventSequence)if(t.eventSequence[s]!==e.eventSequence[s])continue e;continue t}n.push(t)}return n.map(t=>t.path)})(n)).map(this._toTestPath)}getShortestPaths(t){return this.getPaths(se(),t)}getShortestPathsFrom(t,e){const s=[];for(const n of t){const t=this.getShortestPaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(le(n,e)))}return s}getSimplePaths(t){return this.getPaths(ne(),t)}getSimplePathsFrom(t,e){const s=[];for(const n of t){const t=this.getSimplePaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(le(n,e)))}return s}getPathsFromEvents(t,e){return me(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return ge(this.testLogic,this.options)}async testPath(t,e,s){const n={steps:[],state:{error:null}};try{for(const o of t.steps){const t={step:o,state:{error:null},event:{error:null}};n.steps.push(t);try{await this.testTransition(e,o)}catch(e){throw t.event.error=e,e}try{await this.testState(e,o.state,s)}catch(e){throw t.state.error=e,e}}}catch(e){throw e.message+=function(t,e,s){const n={formatColor:(t,e)=>e,serializeState:te,serializeEvent:te,...s},{formatColor:o,serializeState:i,serializeEvent:r}=n,{state:c}=t,a=i(c,t.steps.length?t.steps[t.steps.length-1].event:void 0);let h="",u=!1;return h+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=i(t.step.state,e>0?s[e-1].step.event:void 0),c=r(t.step.event);return[`\tState: ${u?o("gray",n):t.state.error?(u=!0,o("redBright",n)):o("greenBright",n)}`,`\tEvent: ${u?o("gray",c):t.event.error?(u=!0,o("red",c)):o("green",c)}`].join("\n")}).concat(`\tState: ${u?o("gray",a):e.state.error?o("red",a):o("green",a)}`).join("\n\n"),h}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),o=this._getStateTestKeys(t,e,n);for(const s of o)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},o=Object.keys(n).filter(t=>s.stateMatcher(e,t));return!o.length&&"*"in n&&o.push("*"),o}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function ie(t,e){if(t===e)return!0;if(void 0===t||void 0===e)return!1;if("string"==typeof t||"string"==typeof e)return t===e;const s=Object.keys(t),n=Object.keys(e);return s.length===n.length&&s.every(s=>ie(t[s],e[s]))}function re(t,e,s,{serializeEvent:n}){if(!e||s&&ie(s.value,t.value))return"";const o=s?` from ${te(s.value)}`:"";return` via ${n(e)}${o}`}function ce(){const t=Gt();return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function ae(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function he(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function ue(t){return JSON.stringify(t)}function fe(t,e){const{events:s,...n}=e??{};return{serializeState:he,serializeEvent:ue,events:t=>{const e="function"==typeof s?s(t):s??[];return Tt(t).flatMap(t=>{const s=e.filter(e=>e.type===t);return s.length?s:[{type:t}]})},fromState:t.getInitialSnapshot(ce(),e?.input),...n}}function pe(){return{serializeState:t=>JSON.stringify(t),serializeEvent:ue}}function de(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?fe(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:ue,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function le(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}}function ye(t){return Array.isArray(t)?t[0]:t}function ge(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:i,filterEvents:r,limit:c,fromState:a,stopWhen:h}=de(t,e),u=ce(),f={};let p=0;const d=[{nextState:a??t.getInitialSnapshot(u,e.input),event:void 0,prevState:void 0}],l=new Map;for(;d.length;){const{nextState:t,event:e,prevState:a}=d.shift();if(p++>c)throw new Error("Traversal limit exceeded");const y=o(t,e,a);if(f[y])continue;if(l.set(y,t),f[y]={state:t,transitions:{}},h&&h(t))continue;const g="function"==typeof i?i(t):i;for(const e of g){if(r&&!r(t,e))continue;const o=ye(s(t,e,u));f[y].transitions[n(e)]={event:e,state:o},d.push({nextState:o,event:e,prevState:t})}}return f}function ve(t){let e=[];if(t.steps.length){for(let n=0;n<t.steps.length;n++){const o=t.steps[n];e.push({state:o.state,event:0===n?{type:s}:t.steps[n-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:s}}];return{...t,steps:e}}function me(t,e,s){const n=de(t,{events:e,...s},(o=t)&&o instanceof Zt?fe(t):pe());var o;const i=ce(),r=n.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:c,serializeEvent:a}=n,h=ge(t,n),u=new Map,f=[],p=c(r,void 0,void 0);u.set(p,r);let d=p,l=r;for(const t of e){f.push({state:u.get(d),event:t});const e=a(t),{state:s,event:n}=h[d].transitions[e];if(!s)throw new Error(`Invalid transition from ${d} with ${e}`);const o=c(s,t,u.get(d));u.set(o,s),d=o,l=s}return n.toState&&!n.toState(l)?[]:[ve({state:l,steps:f,weight:f.length})]}function _e(t,e){const s=de(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(ce(),e?.input),i=ge(t,s),r=new Map,c=new Map,a=n(o,void 0,void 0);c.set(a,o),r.set(a,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(a);for(const t of h){const e=c.get(t),{weight:s}=r.get(t);for(const o of Object.keys(i[t].transitions)){const{state:a,event:f}=i[t].transitions[o],p=n(a,f,e);if(c.set(p,a),r.has(p)){const{weight:e}=r.get(p);e>s+1&&r.set(p,{weight:s+1,state:t,event:f})}else r.set(p,{weight:s+1,state:t,event:f});u.has(p)||h.add(p)}u.add(t),h.delete(t)}const f={},p=[];return r.forEach(({weight:t,state:e,event:s},n)=>{const o=c.get(n),i=e?f[e].paths[0].steps.concat({state:c.get(e),event:s}):[];p.push({state:o,steps:i,weight:t}),f[n]={state:o,paths:[{state:o,steps:i,weight:t}]}}),s.toState?p.filter(t=>s.toState(t.state)).map(ve):p.map(ve)}function Se(t,e){const s=de(t,e),n=ce(),o=s.fromState??t.getInitialSnapshot(n,e?.input),i=s.serializeState,r=ge(t,s),c=new Map,a={vertices:new Set,edges:new Set},h=[],u={};function f(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){u[e]||(u[e]={state:c.get(e),paths:[]});const t=u[e],n={state:s,weight:h.length,steps:[...h]};t.paths.push(n)}else{if(!r[t])return;for(const s of Object.keys(r[t].transitions)){const{state:n,event:o}=r[t].transitions[s];if(!(s in r[t].transitions))continue;const u=c.get(t),p=i(n,o,u);c.set(p,n),a.vertices.has(p)||(a.edges.add(s),h.push({state:c.get(t),event:o}),f(p,e))}}h.pop(),a.vertices.delete(t)}const p=i(o,void 0);c.set(p,o);for(const t of Object.keys(r))f(p,t);const d=Object.values(u).flatMap(t=>t.paths);return s.toState?d.filter(t=>s.toState(t.state)).map(ve):d.map(ve)}t.TestModel=oe,t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.createShortestPathsGen=se,t.createSimplePathsGen=ne,t.createTestModel=function(t,e){(t=>{t.root})(t);const s=e?.serializeEvent??te,n=e?.serializeTransition??re,{events:o,...i}=e??{};return new oe(t,{serializeState:(t,e,o)=>`${he(t)}${n(t,e,o,{serializeEvent:s})}`,stateMatcher:(e,s)=>s.startsWith("#")?e._nodes.includes(t.getStateNodeById(s)):e.matches(s),events:t=>{const e="function"==typeof o?o(t):o??[];return Tt(t).flatMap(t=>e.some(e=>e.type===t)?e.filter(e=>e.type===t):[{type:t}])},...i})},t.getAdjacencyMap=ge,t.getPathsFromEvents=me,t.getShortestPaths=_e,t.getSimplePaths=Se,t.getStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,n)=>{const o=s[n],i=t(o);return e.push(o,...i),e},[])},t.joinPaths=le,t.serializeSnapshot=he,t.toDirectedGraph=function t(e){const s=e instanceof Zt?e.root:e,n=[...s.transitions.values()].flat().flatMap((t,e)=>(t.target?t.target:[s]).map((n,o)=>{const i={id:`${s.id}:${e}:${o}`,source:s,target:n,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=i;return{source:s.id,target:n.id,label:t}}};return i})),o={id:s.id,stateNode:s,children:ae(s).map(t),edges:n,toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s}}};return o},Object.defineProperty(t,"__esModule",{value:!0})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateGraph={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="@xstate.init",n="@xstate.stop";function o(t){return{type:`xstate.timeout.actor.${t}`}}function i(t,e){return{type:`xstate.done.state.${t}`,output:e}}function r(t){return{type:s,input:t}}function c(t){setTimeout(()=>{throw t})}const a="function"==typeof Symbol&&Symbol.observable||"@@observable",h={"@xstate.start":t=>{t.start()},"@xstate.raise":(t,e,s)=>{t.system.scheduler.schedule(t.self,t.self,e,s?.delay??0,s?.id)},"@xstate.sendTo":(t,e,s,n)=>{if("string"==typeof s)throw new Error("Only event objects may be used with sendTo");void 0!==n?.delay?t.system.scheduler.schedule(t.self,e,s,n?.delay??0,n?.id):t.defer(()=>{t.system._relay(t.self,e,s)})},"@xstate.cancel":(t,e)=>{t.system.scheduler.cancel(t.self,e)},"@xstate.stopChild":(t,e)=>{t.stopChild(e)}},u=new WeakMap;function f(t){return{start:(e,{self:s,system:n})=>{const o=e.input.actor;if(!o||"function"==typeof o.getSnapshot&&"stopped"===o.getSnapshot().status)return;const i=t(e.input,{self:s,system:n});if(!i)return;let r,c=!1;const a=()=>{c||(c=!0,i.unsubscribe(),r?.unsubscribe())},h=s._parent;h&&(r=h.subscribe({complete:a,error:a})),u.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===n?(u.get(s)?.unsubscribe(),u.delete(s),{...t,status:"stopped",error:void 0}):t,getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function p(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function d(){return f(({actor:t,eventType:e,mapper:s},{self:n,system:o})=>{const i="*"!==e&&e.endsWith(".*");return t.on(i?"*":e,t=>{i&&!Mt(t.type,e)||p(n,o,()=>s(t))})})}const l=d(),y=Symbol.for("xstate.atom");function g(){return f(({actor:t,mappers:e},{self:s,system:n})=>{const{done:o,error:i,snapshot:r}=e;if((c=t)&&"object"==typeof c&&y in c){if(!r)return;return t.subscribe(t=>p(s,n,()=>r(t)))}var c;return t.subscribe({next:t=>{"done"===t.status&&o?p(s,n,()=>o(t.output)):"error"===t.status&&i?p(s,n,()=>i(t.error)):"active"===t.status&&r&&p(s,n,()=>r(t))},error:t=>{i&&p(s,n,()=>i(t))},complete:()=>{}})})}const v=g();function m(t,e,...s){t.push({action:e,args:s})}function _(t,e,s){m(t,h["@xstate.start"],e),t.push(function(t,e){return Object.assign(function(s){return{children:{...s.children,[e]:t}}},{_special:!0})}(e,s??e.id))}function S(t,e,s,n=!1){const o={cancel:s=>{m(e,h["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{m(e,t.logger,...s)},raise:(n,o)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0!==o?.delay?m(e,h["@xstate.raise"],t,n,o):s.push(n)},spawn:(s,n)=>{const o=Wt(s,{...n,parent:t.self});return _(e,o,n?.id),o},sendTo:(s,n,o)=>{s&&m(e,h["@xstate.sendTo"],t,s,n,o)},stop:s=>{s&&(m(e,h["@xstate.stopChild"],t,s),e.push(function(t){return Object.assign(function(e){const s={...e.children};for(const e of Object.keys(s))s[e]===t&&delete s[e];return{children:s}},{_special:!0})}(s)))}};return n&&Object.assign(o,{listen:(s,n,o)=>{const i=Wt(l,{input:{actor:s,eventType:n,mapper:o},parent:t.self});return m(e,h["@xstate.start"],i),i},subscribeTo:(s,n)=>{const o=Wt(v,{input:{actor:s,mappers:"function"==typeof n?{snapshot:n}:n},parent:t.self});return m(e,h["@xstate.start"],o),o}}),b(o,(t,...s)=>{m(e,t,...s)})}function x(t,e,s,n){let o=t;for(const i of n){const n="function"==typeof i?i:"object"==typeof i&&"action"in i&&"function"==typeof i.action&&i.action.bind(null,...i.args);n||"object"!=typeof i||null===i||s.defer(()=>{s.emit(i)});const r={context:o.context,event:e,self:s.self,system:s.system,children:o.children,parent:s.self._parent,actions:t.machine.implementations.actions,actors:t.machine.implementations.actors};let c;if("object"==typeof i&&null!==i){const{type:t,...e}=i;c=e}if(n&&"_special"in n){s.actionExecutor({type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type??"(anonymous)":i.name||"(anonymous)",params:c,args:[],exec:void 0});const t=n(r,w);t&&("context"in t||"children"in t)&&(o=gt(o,{..."context"in t?{context:t.context}:{},..."children"in t?{children:t.children}:{}}));continue}n&&"resolve"in n||s.actionExecutor({type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type:i.name||"(anonymous)",params:c,args:"object"==typeof i&&"action"in i?i.args:[],exec:n})}return o}function b(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),s}const w=b({},()=>{});function E(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const n=e.match(/^(\d*)(\.?)(\d*)s$/i);if(n){const t=n[1]?parseInt(n[1],10):0,e=!!n[2],s=n[3]?parseInt(n[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:i,days:r,hours:c,minutes:a,seconds:h}=o.groups;if(!(i||r||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(i)*24*60*60*1e3+24*u(r)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)??t}function $(t,e,s){if("function"==typeof t)return t(s);const n=E(t,e);return"function"==typeof n?n(s):n}function k(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function I(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function j(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function O(t){const e=new Set(t),s=new Set;for(const t of e)t.parent&&s.add(t.parent);for(const t of e)if("compound"!==t.type||s.has(t)){if("parallel"===t.type)for(const s of I(t))if(!e.has(s)){const t=R(s);for(const s of t)e.add(s)}}else for(const s of R(t))e.add(s);for(const t of e){let s=t.parent;for(;s&&!e.has(s);)e.add(s),s=s.parent}return e}function T(t,e){const s=O(e),n=new Map;for(const t of s)n.has(t)||n.set(t,[]),t.parent&&(n.has(t.parent)||n.set(t.parent,[]),n.get(t.parent).push(t));const o=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(k(t))return t.key}const s={};for(const t of e)s[t.key]=o(t);return s};return o(t)}function M(t,e){return"compound"===e.type?I(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?I(e).every(e=>M(t,e)):"final"===e.type}const A=t=>"#"===t[0];function P(t,e,s){const n=e.type,o=t.entry;t.entry=(t,i)=>(i.raise(e,{id:n,delay:s(t)}),"function"==typeof o?o(t,i):void 0);const i=t.exit;return t.exit=(t,e)=>(e.cancel(n),"function"==typeof i?i(t,e):void 0),n}function N(t,e,s){const n=It(s.target),o=s.reenter??!1,i=z(t,n),r={...s,target:i,source:t,reenter:o,eventType:e,toJSON:()=>({...r,source:`#${t.id}`,target:i?i.map(t=>`#${t.id}`):void 0})};return r}function z(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(A(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return B(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return B(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}function D(t){const e=It(t.config.target);return e?{target:e.map(e=>"string"==typeof e?B(t.parent,e):e),source:t,reenter:!1,eventType:""}:t.parent.initial}function J(t){return"history"===t.type}function R(t){const e=new Set;!function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of I(s))t(e)}(t);for(const s of e)for(const n of j(s,t))e.add(n);return e}function C(t,e){if(A(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const s=t.states[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function B(t,e){if("string"==typeof e&&A(e))try{return t.machine.getStateNodeById(e)}catch{}const s=St(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=C(n,t)}return n}function V(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=new Array(s.length),o=[t.machine.root,t];for(let e=0;e<s.length;e++){const i=C(t,s[e]);n[e]=i,o.push(i)}for(let t=0;t<s.length;t++)o.push(...V(n[t],e[s[t]]));return o}function L(t,e,s,n,o){if("string"==typeof e){const i=C(t,e).next(s,n,o);return i&&i.length?i:t.next(s,n,o)}const i=Object.keys(e),r=i[0];if(1===i.length){const i=L(C(t,r),e[r],s,n,o);return i&&i.length?i:t.next(s,n,o)}const c=[];for(const r of i){const i=e[r];if(!i)continue;const a=L(C(t,r),i,s,n,o);a&&c.push(...a)}return c.length?c:t.next(s,n,o)}function W(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function q(t,e){for(const s of t)if(W(s,e))return!0;return!1}function G(t,e){const s=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,n=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==s&&void 0!==n&&n<s&&([t,e]=[e,t]);const o=t instanceof Set?t:new Set(t);for(const t of e)if(o.has(t))return!0;return!1}function F(t,e,s,n,o){const i=new Set,r=new Map,c=t=>{let i=r.get(t);return i||(i=H([t],e,s,n,o),r.set(t,i)),i};for(const e of t){let t=!1;const s=new Set;for(const n of i)if(G(c(e),c(n))){if(!W(e.source,n.source)){t=!0;break}s.add(n)}if(!t){for(const t of s)i.delete(t);i.add(e)}}return Array.from(i)}function K(t,e,s,n){const o=e.historyValue,{targets:i}=Q(t,e,s,n);if(!i)return[];const r=new Set;for(const t of i)if(J(t))if(o[t.id])for(const e of o[t.id])r.add(e);else for(const o of K(D(t),e,s,n))r.add(o);else r.add(t);return[...r]}function U(t,e,s,n){const o=K(t,e,s,n),{reenter:i}=Q(t,e,s,n);if(!i&&o.every(e=>e===t.source||W(e,t.source)))return t.source;const[r,...c]=o.concat(t.source);for(const t of j(r,void 0))if(c.every(e=>W(e,t)))return t;return i?void 0:t.source.machine.root}function H(t,e,s,n,o){const i=new Set;for(const r of t){const{targets:t}=Q(r,s,n,o);if(t?.length){const t=U(r,s,n,o);r.reenter&&r.source===t&&i.add(t);for(const s of e)W(s,t)&&i.add(s)}}return[...i]}function X(t,e,s,n,o,r){const c=[];if(!t.length)return[e,c];const a=s.actionExecutor;s.actionExecutor=t=>{c.push(t),a(t)};try{const a=new Set(e._nodes);let u=e.historyValue;const f=e.context,p=F(t,a,e,n,s),d=t=>Q(t,e,n,s),l=(t,o,i,r)=>{if(2===t.length){const c=[],a=[];let h;const u=S(s,c,a,!0),f=t({context:o,event:n,parent:s.self._parent,self:s.self,children:i,system:s.system,actions:e.machine.implementations.actions,actors:e.machine.implementations.actors,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays,input:r},u);return f?.context&&(h=f.context),[c,h,a]}return[[Object.assign((e,s)=>t({...e,input:r},s),"_special"in t?{_special:!0}:{})],void 0,void 0]};let y=e;const g=()=>{const t=H(p,a,e,n,s);let o;t.sort((t,e)=>e.order-t.order);const i=[...a];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>k(t)&&W(t,e):t=>t.parent===e;o??={...u},o[t.id]=i.filter(s)}for(const o of t){const t=e._stateInputs?.[o.id],[i,c,h]=o.exit?l(o.exit,y.context,e.children,t):[[]];h?.length&&r.push(...h),c&&(y=gt(y,{context:c})),y=x(y,n,s,i);for(const t of o.invoke){const e=y.children[t.id];e&&!e._isExternal&&s.stopChild(e),delete y.children[t.id]}a.delete(o)}u=o||u};o||g();let v=y.context;const m=[],_=[];for(const t of p){t.actions&&m.push(...wt(t.actions));const e=d(t);e.context&&(v=e.context),e.actions&&m.push(...e.actions),e.internalEvents&&_.push(...e.internalEvents)}_.length&&r.push(..._);const b=()=>{const t=t=>{const e=y.machine.root;if(void 0===e.output)return;let o;if(void 0!==t.output&&t.parent)o=Et(t.output,y.context,n,s.self);else if("parallel"===t.type){const e=`xstate.done.state.${t.id}`,s=r.find(t=>t.type===e);o=s?.output}return Et(e.output,y.context,i(t.id,o),s.self)},c=new Set,f=new Set,g=(t,e)=>{for(const s of t)if(e&&!W(s,e)||c.add(s),"parallel"===s.type)for(const t of I(s))q(c,t)||(c.add(t),v(t))},v=t=>{if(J(t))if(u[t.id]){const e=u[t.id];for(const t of e)c.add(t),v(t);for(const s of e)g(j(s,t.parent),void 0)}else{const e=D(t),{targets:s}=d(e);for(const n of s??[])c.add(n),e===t.parent?.initial&&f.add(t.parent),v(n);for(const e of s??[])g(j(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=d(t.initial).targets;return J(e)||(c.add(e),f.add(e)),v(e),void g(j(e,t),void 0)}if("parallel"===t.type)for(const e of I(t))q(c,e)||(c.add(e),f.add(e),v(e))}};for(const t of p){const o=U(t,e,n,s),{targets:i,reenter:r}=d(t);for(const e of i??[])J(e)||t.source===e&&t.source===o&&!r||(c.add(e),f.add(e)),v(e);const a=K(t,e,n,s);for(const e of a){const s=j(e,o);"parallel"===o?.type&&s.push(o),g(s,!t.source.parent&&r?void 0:o)}}o&&f.add(e.machine.root);const m={...e._stateInputs};for(const t of p){const{targets:e,input:s}=d(t);if(s&&e)for(const t of e)m[t.id]=s}const _=new Set,S={...e.children};for(const o of[...c].sort((t,e)=>t.order-e.order)){a.add(o);const c=[];let u,p=!1;for(const t of o.invoke){p=!0;let o=t.logic;"function"==typeof o&&(o=o({actors:e.machine.implementations.actors,context:y.context,event:n,self:s.self}));const i="string"==typeof o?Ot(e.machine,o):o;if(!i)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented in machine '${e.machine.id}'`);const r="function"==typeof t.input?t.input({self:s.self,context:y.context,event:n}):t.input,a=Wt(i,{...t,input:r,parent:s.self,syncSnapshot:!!t.onSnapshot});c.push({action:h["@xstate.start"],args:[a]}),t.id&&(S[t.id]=a)}p&&(y=gt(y,{children:S}));const d=m[o.id];if(o.entry){const[t,e,s]=l(o.entry,y.context,S,d);c.push(...t),s?.length&&r.push(...s),e&&(u=e)}if(f.has(o)){const{actions:t,input:e}=Q(o.initial,y,n,s);if(t&&c.push(...t),e&&o.initial?.target)for(const t of o.initial.target)m[t.id]=e}if(y=x(y,n,s,c),u&&(y.context=u),"final"!==o.type)continue;const g=o.parent;let v="parallel"===g?.type?g:g?.parent,b=v||o;for("compound"===g?.type&&r.push(i(g.id,void 0!==o.output?Et(o.output,y.context,n,s.self):void 0));"parallel"===v?.type&&!_.has(v)&&M(a,v);){_.add(v);const t={};for(const e of I(v)){if("final"===e.type){t[e.key]=void 0!==e.output?Et(e.output,y.context,n,s.self):void 0;continue}if("parallel"===e.type){const s=`xstate.done.state.${e.id}`,n=r.find(t=>t.type===s);t[e.key]=n?.output;continue}const o=I(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==o?.output?Et(o.output,y.context,n,s.self):void 0}r.push(i(v.id,t)),b=v,v=v.parent}v||(y=gt(y,{status:"done",output:t(b)}))}JSON.stringify(m)!==JSON.stringify(e._stateInputs||{})&&(y=gt(y,{_stateInputs:m}))};y=x(y,n,s,m),v&&v!==e.context&&(y=gt(y,{context:v})),b();const w=[...a];if("done"===y.status){const t=[];w.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=y._stateInputs?.[e.id],[n,,o]=l(e.exit,y.context,y.children,s);t.push(...n),o?.length&&r.push(...o)}}),y=x(y,n,s,t)}return u===e.historyValue&&e._nodes.length===a.size&&e._nodes.every(t=>a.has(t))?y.context!==f?[gt(y),c]:[y,c]:[gt(y,{_nodes:w,historyValue:u}),c]}finally{s.actionExecutor=a}}function Q(t,e,s,n){if(t.to){const o=[],i=[],r=S(n,o,i),c=t.to({context:e.context,event:s,value:e.value,children:e.children,parent:n.self._parent,self:n.self,actions:e.machine.implementations.actions,actors:e.machine.implementations.actors,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays},r),a=c?.target?z(t.source,wt(c.target)):void 0,h="function"==typeof t.input?t.input({context:e.context,event:s}):t.input;return{targets:a,context:c?.context,reenter:c?.reenter,actions:o,internalEvents:i,input:h}}const o="function"==typeof t.input?t.input({context:e.context,event:s}):t.input;return{targets:t.target,context:void 0,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:o}}function Y(t,e,o,i){let r=t;const c=[];function a(t,e){const s=o.self._collectedMicrosteps||[];s.push(...e),o.self._collectedMicrosteps=s,c.push(t)}if(e.type===n)return r=gt(et(r,o),{status:"stopped"}),a([r,[]],[]),{snapshot:r,microsteps:c};let h=e;if(h.type!==s){const e=h,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),n=r.machine.getTransitionData(r,e,o.self);if(s&&!n.length)return r=gt(t,{status:"error",error:e.error}),a([r,[]],[]),{snapshot:r,microsteps:c};const u=X(n,t,o,h,!1,i);r=u[0],a(u,n)}let u=!0;const f=t.machine.options?.maxIterations??1/0;let p=0,d=0;for(;"active"===r.status;){if(d++,d>1e3)throw new Error("Microstep count exceeded 1000");if(p++,p>f)throw new Error(`Infinite loop detected (>${f} microsteps)`);let t=u?st(r,h,o):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;h=i.shift(),t=r.machine.getTransitionData(r,h,o.self)}const s=X(t,r,o,h,!1,i);r=s[0],u=r!==e,a(s,t)}return"active"!==r.status&&r.children&&et(r,o),{snapshot:r,microsteps:c}}function Z(t,e,s,n,o){return!!t.to&&tt(t.to,e,s,n,o,n.machine.implementations)}function tt(t,e,s,n,o,i){let r,c=!1;try{const a=()=>{throw c=!0,new Error("Effect triggered")};r=t({context:e,event:s,self:o,value:n.value,children:n.children,parent:{send:a},actions:i.actions,actors:i.actors,guards:i.guards,delays:i.delays},function(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),s}({emit:a,cancel:a,log:a,raise:a,spawn:a,sendTo:a,stop:a},a))}catch(t){if(c)return!0;throw t}return void 0!==r}function et(t,e){let s;if(!t.children||0===(s=Object.values(t.children).filter(Boolean)).length)return t;for(const t of s)e.stopChild(t);return gt(t,{children:{}})}function st(t,e,s){const n=new Set,o=t._nodes.filter(k);for(const i of o)t:for(let o=i;o;o=o.parent)if(o.always)for(const i of o.always)if(nt(i,e,t,o,s.self)){n.add(i);break t}return F(Array.from(n),new Set(t._nodes),t,e,s)}function nt(t,e,s,n,o){if(t.guard){const i={context:s.context,event:e,self:o,parent:o._parent,children:s.children,actions:n.machine.implementations.actions,actors:n.machine.implementations.actors,guards:n.machine.implementations.guards,delays:n.machine.implementations.delays,_snapshot:s},r=t.guard,c="function"==typeof r?.params?r.params({context:s.context,event:e}):r?.params;let a=!0;if("function"==typeof r)a=r(i,c);else if("string"==typeof r?.type){const t=n.machine.implementations.guards[r.type];if(!t)throw new Error(`Guard '${r.type}' is not implemented in machine '${n.machine.id}'.`);a=t(i,c)}if(!a)return!1}return!t.to||tt(t.to,s.context,e,s,o,n.machine.implementations)}function ot(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}let it,rt;function ct(){return it??=Gt()}const at=function(t){return _t(t,this.value)},ht=function(t){return this.tags.has(t)},ut=function(t){const e=ct(),s=function(){if(rt)return rt;const t=ct();return rt={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},rt}(),n=this.machine.getTransitionData(this,t,e);if(!n?.length)return!1;for(const o of n){if(void 0!==o.target)return!0;const n=Q(o,this,t,s);if(n.targets?.length||n.context||Z(o,this.context,t,this,e))return!0}return!1},ft=function(){const{_nodes:t,_stateInputs:e,tags:s,machine:n,getMeta:o,getInputs:i,toJSON:r,can:c,hasTag:a,matches:h,...u}=this;return{...u,tags:Array.from(s)}},pt=function(){const t={};for(const e of this._nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},dt=function(){return this._stateInputs};function lt(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function yt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:t.value??T(e.root,t._nodes),tags:lt(t._nodes),children:t.children,historyValue:t.historyValue||{},_stateInputs:t._stateInputs||{},matches:at,hasTag:ht,can:ut,getMeta:pt,getInputs:dt,toJSON:ft}}function gt(t,e={}){const s={...t,...e};return(e._nodes??t._nodes)===t._nodes?{status:s.status,output:s.output,error:s.error,machine:t.machine,context:s.context,_nodes:t._nodes,value:t.value,tags:t.tags,children:s.children,historyValue:s.historyValue||{},_stateInputs:s._stateInputs||{},matches:at,hasTag:ht,can:ut,getMeta:pt,getInputs:dt,toJSON:ft}:yt({...s,value:void 0},t.machine)}function vt(t){const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map(t=>({id:t.id})))}return e}function mt(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:Rt,id:n.id};else{const o=mt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function _t(t,e){const s=xt(t),n=xt(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&_t(s[t],n[t]))}function St(t){if($t(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function xt(t){if(ot(t))return t.value;if("string"!=typeof t)return t;return function(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}(St(t))}function bt(t){return $t(t)?t:[t]}function wt(t){return void 0===t?[]:bt(t)}function Et(t,e,s,n){return"function"==typeof t?t({context:e,event:s,self:n}):t}function $t(t){return Array.isArray(t)}function kt(t){return bt(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function It(t){if(void 0!==t&&""!==t)return wt(t)}function jt(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function Ot(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actors[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke,r=(Array.isArray(i)?i[n]:i).src;return"string"==typeof r?t.implementations.actors[r]:r}function Tt(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]}function Mt(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}function At(t,e){return`${t.sessionId}.${e}`}const Pt=new WeakMap;function Nt(t){let e=Pt.get(t);return e||(e=new Map,Pt.set(t,e)),e}function zt(t,e){if(t?.length)for(const s of t)switch(s.type){case"emit":e.emit(s.event);break;case"sendBack":{const t=e.self._parent;t&&e.system._relay(e.self,t,s.event);break}case"raise":e.system._relay(e.self,e.self,s.event);break;case"effect":{if(!s.key){const t=s.exec();"function"==typeof t&&Nt(e.self).set(Symbol(),{cleanup:t});break}const t=Nt(e.self);if(t.has(s.key))break;const n=s.exec();t.set(s.key,{cleanup:"function"==typeof n?n:void 0});break}case"cleanupEffects":{const t=Pt.get(e.self);if(!t)break;for(const{cleanup:e}of t.values())e?.();Pt.delete(e.self);break}}}function Dt(t){const e=(e,s,o)=>{if("active"!==e.status)return[e,[]];if(s.type===n)return[{...e,status:"stopped",input:void 0},[{type:"cleanupEffects"}]];if("xstate.logic.effect.start"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if("xstate.logic.effect.resolve"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if("xstate.logic.effect.reject"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const i=[],r={},c={emit:t=>{i.push({type:"emit",event:t})},sendBack:t=>{i.push({type:"sendBack",event:t})},raise:t=>{i.push({type:"raise",event:t})},effect:(t,s)=>{if("string"==typeof t)return n=t,o=s,void(e.effects?.[n]||(i.push({type:"effect",key:n,exec:o}),r[n]={status:"active"}));var n,o;i.push({type:"effect",exec:t})}},a=t.run({context:e.context,event:s,input:e.input,system:o.system,self:o.self,emit:o.emit},c),h={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(h.context=a?.context??e.context),(a?.effects||Object.keys(r).length)&&(h.effects={...e.effects,...a?.effects,...r}),[h,i]};return{id:t.id,config:t,transition:e,start:(t,s)=>{const[n,o]=e(t,r(t.input),s);Object.assign(t,n),zt(o,s)},getInitialSnapshot:(e,s)=>{const n=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,s),o={status:"active",output:void 0,error:void 0,input:s};return void 0!==n&&(o.context=n),{...o}},getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}let Jt=!1;const Rt=1;let Ct=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Bt={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)};class Vt{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=this._process.bind(this),this.mailbox=new e(this._boundProcess),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=Ct.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[],this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this.trigger=void 0,this.src=void 0,this._deferred=[],this._pendingEffects=void 0;const n={...Bt,...s},{clock:o,logger:i,parent:r,syncSnapshot:a,id:h,systemId:u,inspect:f}=n;this.system=r?r.system:function(t,e){let s=0;const n=new Map,o=new Map,i=new WeakMap,r=new Set,c={},{clock:a,logger:h}=e,u=(t,e,s,n,o)=>{r.size&&t&&(t._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:o})},f={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{u(t,e,s,n,o);const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},r=At(t,o);d._snapshot._scheduledEvents[r]=i;const h=a.setTimeout(()=>{delete c[r],delete d._snapshot._scheduledEvents[r],p(t,e,s)},n);c[r]=h},cancel:(t,e)=>{const s=At(t,e),n=c[s];delete c[s],delete d._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in d._snapshot._scheduledEvents){const s=d._snapshot._scheduledEvents[e];s.source===t&&f.cancel(t,s.id)}}},p=(t,e,s)=>{const n=e.logic;if("function"==typeof n?.isInternalEventType&&n.isInternalEventType(s.type)&&t!==e)throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`);e._lastSourceRef=t,e._send(s)},d={children:n,reverseKeyedActors:i,keyedActors:o,_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+s++,_register:(t,e)=>(n.set(t,e),t),_unregister:t=>{n.delete(t.sessionId);const e=i.get(t);void 0!==e&&(o.delete(e),i.delete(t))},get:t=>o.get(t),getAll:()=>Object.fromEntries(o.entries()),_set:(t,e)=>{const s=o.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);o.set(t,e),i.set(e,t)},inspect:t=>{const e=jt(t);return r.add(e),{unsubscribe(){r.delete(e)}}},_sendInspectionEvent:e=>{if(!r.size)return;const s={...e,rootId:t.sessionId};r.forEach(t=>t.next?.(s))},_relay:(t,e,s)=>{u(t,e,s),p(t,e,s)},scheduler:f,getSnapshot:()=>({_scheduledEvents:{...d._snapshot._scheduledEvents}}),start:()=>{const t=d._snapshot._scheduledEvents;d._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];f.schedule(s,n,o,i,r)}},_clock:a,_logger:h,_timerStrategy:e.timers};return d}(this,{clock:o,logger:i,timers:n.timers}),f&&!r&&this.system.inspect(jt(f)),this.sessionId=this.system._bookId(),this.id=h??this.sessionId,this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=r,this._syncSnapshot=a,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get("*");if(e||s){if(e)for(const s of e)try{s(t)}catch(t){c(t)}if(s)for(const e of s)try{e(t)}catch(t){c(t)}}},actionExecutor:t=>{const e=()=>{if(this._collectedActions.push({type:t.type,params:t.params}),!t.exec)return;const e=Jt;try{Jt=!0,t.exec()}finally{Jt=e}};this._processingStatus===Ct.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.trigger=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}}),u&&(this.systemId=u,this.system._set(u,this)),this._collectedMicrosteps=[];let p=s?.snapshot??s?.state;if(p&&"object"==typeof p&&"_pendingEffects"in p){const{_pendingEffects:t,...e}=p;this._pendingEffects=t,p=e}try{this._snapshot=p?this.logic.restoreSnapshot?this.logic.restoreSnapshot(p,this._actorScope):p:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t},this._deferred.length=0}u&&"active"!==this._snapshot.status&&this.system._unregister(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_setErrorSnapshot(t,e=this._snapshot){this._snapshot={...e,status:"error",error:t}}_next(t){for(const e of this.observers)try{e.next?.(t)}catch(t){c(t)}}update(t,e){this._snapshot=t;for(let e=0;e<this._deferred.length;e++){const s=this._deferred[e];try{s()}catch(e){this._deferred.length=0,this._setErrorSnapshot(e,t);break}}switch(this._deferred.length=0,this._snapshot.status){case"active":this._next(t);break;case"done":{this._next(t),this._stopProcedure(),this._complete();const e=(s=this.id,n=this._snapshot.output,{type:`xstate.done.actor.${s}`,output:n,actorId:s});this._parent&&this.system._relay(this,this._parent,e);break}case"error":this._error(this._snapshot.error)}var s,n;this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps,actions:this._collectedActions,sent:this._collectedSent,eventType:e.type}),this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[]}subscribe(t,e,s){const n=jt(t,e,s);if(this._processingStatus!==Ct.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){c(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){c(t)}else c(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);return s||(s=new Set,this.eventListeners.set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,o)=>{const i=jt(s,n,o);let r=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(r,n)||(r=n,i.next?.(n))},error:i.error,complete:i.complete})},get:()=>t(this.get())}}start(){if(this._processingStatus===Ct.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=Ct.Running;const t=r(this.options.input);this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this.update(this._snapshot,t),this._pendingEffects){const t=this.options.timers??this.system._timerStrategy??"resume";for(const e of this._pendingEffects)"@xstate.raise"===e.type&&this.system.scheduler.schedule(this,this,e.event,Lt(t,e),e.id);this._pendingEffects=void 0}return this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._setErrorSnapshot(t),void this._error(t)}const[o,i]=Array.isArray(e)?e:[e,void 0];this.update(o,t),zt(i,this._actorScope),t.type===n&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===Ct.Stopped?this:(this.mailbox.clear(),this._processingStatus===Ct.NotStarted?(this._processingStatus=Ct.Stopped,this):(this.mailbox.enqueue({type:n}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){c(t)}this.observers.clear(),this.eventListeners.clear()}_error(t){if(this._stopProcedure(),this.observers.size){let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){c(t)}}this.observers.clear(),this.eventListeners.clear(),e&&c(t)}else this._parent||c(t),this.eventListeners.clear();var e;this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${e=this.id}`,error:t,actorId:e})}_stopProcedure(){this._processingStatus===Ct.Running&&(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._boundProcess),this._processingStatus=Ct.Stopped,this.system._unregister(this))}_send(t){this._processingStatus!==Ct.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$$type:Rt,id:this.id}}getPersistedSnapshot(t){const e=this.logic.getPersistedSnapshot(this._snapshot,t),s=this.system._snapshot._scheduledEvents;let n;const o=Date.now();for(const t in s){const e=s[t];e.source===this&&e.target===this&&(n??=[]).push({type:"@xstate.raise",event:e.event,id:e.id,delay:e.delay,startedAt:e.startedAt,elapsed:Math.max(0,o-e.startedAt)})}return n??=this._pendingEffects,n?{...e,_pendingEffects:n}:e}[a](){return this}getSnapshot(){return this.get()}get(){return this._snapshot}}function Lt(t,e){if("function"==typeof t)return t(e);switch(t){case"restart":return e.delay;case"absolute":return Math.max(0,e.startedAt+e.delay-Date.now());default:return Math.max(0,e.delay-e.elapsed)}}function Wt(t,e){return new Vt(t,e)}const qt=Dt({context:void 0,run:()=>{}});function Gt(){return Wt(qt)}function Ft(t,{machine:e,context:s},n,o){return(i,r)=>{const c=((i,r)=>{if("string"==typeof i){const c=Ot(e,i);if(!c)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const a=Wt(c,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:s,event:n,self:t.self}):r?.input,src:i,systemId:r?.systemId});return o[a.id]=a,a}return Wt(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[c.id]=c,t.defer(()=>{c._processingStatus!==Ct.Stopped&&c.start()}),c}}const Kt=new WeakMap;function Ut(t,e,s){let n=Kt.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Kt.set(t,n)),n[e]}const Ht={},Xt=["invoke","after","on","entry","exit","always","states","initial","onDone","timeout","onTimeout","history","target","output"];class Qt{constructor(t,e){this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.invoke=void 0,this.on=void 0,this.after=void 0,this.events=void 0,this.ownEvents=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[];const s=this.config.states?Object.keys(this.config.states)[0]:void 0;if(this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(void 0!==s?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,function(t){const e=t.config;if("choice"!==t.type){if(void 0!==e.choice)throw new Error(`State "${t.id}" has \`choice\`, but \`choice\` can only be used with \`type: 'choice'\`.`);return}if("function"!=typeof e.choice)throw new Error(`Choice state "${t.id}" must declare a \`choice\` function.`);for(const s of Xt)if(void 0!==e[s])throw new Error(`Choice state "${t.id}" cannot declare \`${s}\`.`)}(this),this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const i=n[o];s[i]=e(t[i],i,t,o)}return s}(this.config.states,(t,e)=>new Qt(t,{_parent:this,_key:e,_machine:this.machine})):Ht,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}".`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.entry&&(this.entry._special=!0),this.exit&&(this.exit._special=!0),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=wt(t.tags).slice(),this.invoke=wt(this.config.invoke).map((t,e)=>{const{src:s,systemId:n}=t,o=(i=this.id,`${e}.${i}`);var i;const r=t.id??o,c="string"==typeof s?s:`xstate.invoke.${o}`;return{...t,src:c,logic:s,id:r,systemId:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,i=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===i.length)return[];const r=e=>{const s={type:`xstate.after.${e}.${t.id}`};return P(t,s,s=>$(e,s.delays,{context:s.context,event:s.event,stateNode:t}))},c=[],a=(t,e,s)=>{for(const n of kt(t))c.push({...n,event:e,delay:s})};if(e)for(const s of Object.keys(e)){const n=e[s],o=Number.isNaN(+s)?s:+s;a(n,r(o),E(o,t.machine.implementations.delays))}if(void 0!==s&&n){const e={type:`xstate.timeout.${t.id}`};a(n,P(t,e,e=>$(s,e.delays,{context:e.context,event:e.event,stateNode:t})),"function"==typeof s?s:E(s,t.machine.implementations.delays))}for(const e of i){const s=o(e.id),n=e.timeout,i=P(t,s,e=>$(n,{},{context:e.context,event:e.event,stateNode:t}));a(e.onTimeout,i,n)}return c.map(e=>({...N(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=t.config.on[s];e.set(s,Yt(n,e=>N(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,Yt(t.config.onDone,e=>N(t,s,e)))}const s=(e,s)=>N(t,e,{to:(t,e)=>(e.cancel(s),{})}),n=(e,s,n)=>{const{target:o,to:i,reenter:r,...c}=s;return N(t,e,{...c,reenter:r,to:(t,e)=>{if(i){let s=!1;const o=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const o=Reflect.get(t,e,n);return"function"!=typeof o?o:(...e)=>(s=!0,o.apply(t,e))}}),r=i(t,o);return(void 0!==r||s)&&e.cancel(n),r}return e.cancel(n),{target:o,reenter:r}}})};for(const i of t.invoke){const r=void 0!==i.timeout?o(i.id).type:void 0;if(i.onDone){const o=`xstate.done.actor.${i.id}`,c=Yt(i.onDone,e=>r?n(o,e,r):N(t,o,e));r&&c.push(s(o,r)),e.set(o,c)}else if(r){const t=`xstate.done.actor.${i.id}`;e.set(t,[s(t,r)])}if(i.onError){const s=`xstate.error.actor.${i.id}`;e.set(s,Yt(i.onError,e=>r?n(s,e,r):N(t,s,e)))}if(i.onSnapshot){const s=`xstate.snapshot.${i.id}`;e.set(s,Yt(i.onSnapshot,e=>N(t,s,e)))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),"choice"===this.type?this.always=function(t){const e=t.config.choice,s=e=>{if(!e||void 0===e.target)throw new Error(`Choice state "${t.id}" must resolve to a target.`);for(const s of["actions","to","context"])if(void 0!==e[s])throw new Error(`Choice state "${t.id}" cannot declare \`${s}\` on a choice.`);return e};return[N(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=Yt(this.config.always,t=>N(this,"",t)));for(const t of Object.keys(this.states))this.states[t]._initialize();this._refreshEventMetadata()}_refreshEventMetadata(){const t={},e=[];for(const[s,n]of this.transitions)t[s]=n.slice(),n.some(t=>t.target||t.reenter||t.to)&&e.push(s);this.on=t,this.ownEvents=e;const s=new Set(e);for(const t of Object.values(this.states))for(const e of t.events)s.add(e);this.events=Array.from(s)}get initial(){return Ut(this,"initial",()=>function(t,e){const s="object"==typeof e&&null!==e?e.target:e,n="object"==typeof e&&null!==e?e.input:void 0,o="string"==typeof s?t.states[s]:void 0;if(!o&&s)throw new Error(`Initial state node "${s}" not found on parent state node #${t.id}`);return{source:t,target:o?[o]:void 0,input:n}}(this,this.config.initial))}next(t,e,s){const n=e.type,o=Ut(this,`candidates-${n}`,()=>function(t,e){const s=t.transitions.get(e);if(s)return s;const n=[];for(const s of t.transitions.keys())Mt(e,s)&&n.push(s);n.sort((t,e)=>e.length-t.length);const o=[];for(const e of n)o.push(...t.transitions.get(e));return o}(this,n));for(const n of o){if(nt(n,e,t,this,s))return[n]}}}function Yt(t,e){const s=kt(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}class Zt{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._json=void 0,this.id=t.id||"(machine)",this.implementations={actors:t.actors??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...e},this.version=this.config.version,this.schemas=this.config.schemas,this.internalEventDescriptors=this.config.internalEvents??[],this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new Qt(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const o=n.config.id,i=n.config.route,r=({event:t})=>t.to===`#${o}`;if("function"==typeof i)return e.push(N(t,"xstate.route",{guard:r,to:t=>{const e=i(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(n.states&&s(n.states));if("$unserializable"in i)throw new Error(`State "${n.id}" has a route that is not serializable. Re-provide the route function when reviving this machine.`);const c=i.guard,a={...i,guard:c?e=>{if(!r(e))return!1;if("function"==typeof c)return c(e);if("string"==typeof c){const s=e.guards?.[c];if(!s)throw new Error(`Guard '${c}' is not implemented in machine '${t.machine.id}'.`);return s(e)}return!0}:r,target:`#${o}`};e.push(N(t,"xstate.route",a))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.root._refreshEventMetadata(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.implementations,i=new Zt(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}});return i._json=this._json,i}resolveState(t){const e=(s=this.root,n=t.value,T(s,O(V(s,n))));var s,n;const o=O(V(this.root,e));return yt({_nodes:[...o],value:e,context:t.context||{},children:{},status:M(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return Y(t,e,s,[]).snapshot}microstep(t,e,s){const{microsteps:n}=Y(t,e,s,[]),o=new Array(n.length);for(let t=0;t<n.length;t++)o[t]=n[t][0];return o}getTransitionData(t,e,s){return L(this.root,t.value,t,e,s)||[]}isInternalEventType(t){for(const e of this.internalEventDescriptors)if(Mt(t,e))return!0;return!1}_getPreInitialState(t,e){const{context:s}=this.config,n=yt({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const o={},i=s({spawn:Ft(t,n,e,o),input:e.input,self:t.self,actors:this.implementations.actors}),r=x(n,e,t,[]);return i&&(r.context=i),Object.keys(o).length>0&&(r.children={...r.children,...o}),r}return n}getInitialSnapshot(t,e){const s=r(e),n=[],o=this._getPreInitialState(t,s),[i]=function(t,e,s,n,o){return X([{target:[...R(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,o,t,s,n),{snapshot:c}=Y(i,s,t,n);return c}start(t){if(t?.children)for(const e of Object.values(t.children))e._rehydrated&&"active"===e.getSnapshot?.().status&&e.start()}getStateNodeById(t){const e=St(t),s=e.slice(1),n=A(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return B(o,s)}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,_stateInputs:n,tags:o,machine:i,children:r,context:c,can:a,hasTag:h,matches:u,getMeta:f,getInputs:p,toJSON:d,...l}=t,y={};for(const t in r){const s=r[t];y[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s.systemId,syncSnapshot:s._syncSnapshot}}const g={...l,context:mt(c),children:y,historyValue:vt(l.historyValue)};return void 0!==i.version&&(g.version=i.version),g}(t,e)}restoreSnapshot(t,e){const s=t.version;if(s!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${s}' does not match machine version '${this.version}'.`);t=e(t,s)}const n=t,o={},i=n.children;for(const t of Object.keys(i)){const s=i[t],n=s.snapshot,r=s.src,c="string"==typeof r?Ot(this,r):r;if(!c)continue;const a=Wt(c,{id:t,parent:e.self,syncSnapshot:s.syncSnapshot,snapshot:n,src:r,systemId:s.systemId});a._rehydrated=!0,o[t]=a}const r=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const s of Object.keys(t)){const n=t[s];for(const t of n){let n;if(t instanceof Qt)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(n.historyValue),c=Array.from(O(V(this.root,n.value))),{version:a,...h}=t,u=yt({...h,children:o,_nodes:c,value:n.value,historyValue:r},this),f=new WeakSet;return function t(e){if(!f.has(e)){f.add(e);for(const s of Object.keys(e)){const n=e[s];if(n&&"object"==typeof n){if("xstate$$type"in n&&n.xstate$$type===Rt){e[s]=o[n.id];continue}t(n)}}}}(u.context),u}}function te(t){return JSON.stringify(t)}function ee(t){const e=Object.keys(t.context).length?`(${JSON.stringify(t.context)})`:"",s=t._nodes.filter(t=>"atomic"===t.type||"final"===t.type).map(({id:e,path:s})=>{const n=t.getMeta()[e];if(!n)return`"${s.join(".")}"`;const{description:o}=n;return"function"==typeof o?o(t):o?`"${o}"`:JSON.stringify(t.value)});return`state${1===s.length?"":"s"} `+s.join(", ")+` ${e}`.trim()}const se=()=>(t,e)=>_e(t,e),ne=()=>(t,e)=>Se(t,e);class oe{getDefaultOptions(){return{serializeState:t=>te(t),serializeEvent:t=>te(t),serializeTransition:(t,e)=>`${te(t)}|${e?.type}`,events:[],stateMatcher:(t,e)=>"*"===e,logger:{log:console.log.bind(console),error:console.error.bind(console)}}}constructor(t,e){this.testLogic=t,this.options=void 0,this.defaultTraversalOptions=void 0,this._toTestPath=t=>{const e=t.steps.map(t=>function(t){const{type:e,...s}=t;return`${e}${Object.keys(s).length?` (${JSON.stringify(s)})`:""}`}(t.event)).join(" → ");return{...t,test:e=>this.testPath(t,e),description:ot(t.state)?`Reaches ${ee(t.state).trim()}: ${e}`:JSON.stringify(t.state)}},this.options={...this.getDefaultOptions(),...e}}getPaths(t,e){const s=e?.allowDuplicatePaths??!1,n=t(this.testLogic,this._resolveOptions(e));return(s?n:((t,e=te)=>{const s=[];t.forEach(t=>{s.push({path:t,eventSequence:t.steps.map(t=>e(t.event))})}),s.sort((t,e)=>e.path.steps.length-t.path.steps.length);const n=[];t:for(const t of s){e:for(const e of n){for(const s in t.eventSequence)if(t.eventSequence[s]!==e.eventSequence[s])continue e;continue t}n.push(t)}return n.map(t=>t.path)})(n)).map(this._toTestPath)}getShortestPaths(t){return this.getPaths(se(),t)}getShortestPathsFrom(t,e){const s=[];for(const n of t){const t=this.getShortestPaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(le(n,e)))}return s}getSimplePaths(t){return this.getPaths(ne(),t)}getSimplePathsFrom(t,e){const s=[];for(const n of t){const t=this.getSimplePaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(le(n,e)))}return s}getPathsFromEvents(t,e){return me(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return ge(this.testLogic,this.options)}async testPath(t,e,s){const n={steps:[],state:{error:null}};try{for(const o of t.steps){const t={step:o,state:{error:null},event:{error:null}};n.steps.push(t);try{await this.testTransition(e,o)}catch(e){throw t.event.error=e,e}try{await this.testState(e,o.state,s)}catch(e){throw t.state.error=e,e}}}catch(e){throw e.message+=function(t,e,s){const n={formatColor:(t,e)=>e,serializeState:te,serializeEvent:te,...s},{formatColor:o,serializeState:i,serializeEvent:r}=n,{state:c}=t,a=i(c,t.steps.length?t.steps[t.steps.length-1].event:void 0);let h="",u=!1;return h+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=i(t.step.state,e>0?s[e-1].step.event:void 0),c=r(t.step.event);return[`\tState: ${u?o("gray",n):t.state.error?(u=!0,o("redBright",n)):o("greenBright",n)}`,`\tEvent: ${u?o("gray",c):t.event.error?(u=!0,o("red",c)):o("green",c)}`].join("\n")}).concat(`\tState: ${u?o("gray",a):e.state.error?o("red",a):o("green",a)}`).join("\n\n"),h}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),o=this._getStateTestKeys(t,e,n);for(const s of o)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},o=Object.keys(n).filter(t=>s.stateMatcher(e,t));return!o.length&&"*"in n&&o.push("*"),o}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function ie(t,e){if(t===e)return!0;if(void 0===t||void 0===e)return!1;if("string"==typeof t||"string"==typeof e)return t===e;const s=Object.keys(t),n=Object.keys(e);return s.length===n.length&&s.every(s=>ie(t[s],e[s]))}function re(t,e,s,{serializeEvent:n}){if(!e||s&&ie(s.value,t.value))return"";const o=s?` from ${te(s.value)}`:"";return` via ${n(e)}${o}`}function ce(){const t=Gt();return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function ae(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function he(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function ue(t){return JSON.stringify(t)}function fe(t,e){const{events:s,...n}=e??{};return{serializeState:he,serializeEvent:ue,events:t=>{const e="function"==typeof s?s(t):s??[];return Tt(t).flatMap(t=>{const s=e.filter(e=>e.type===t);return s.length?s:[{type:t}]})},fromState:t.getInitialSnapshot(ce(),e?.input),...n}}function pe(){return{serializeState:t=>JSON.stringify(t),serializeEvent:ue}}function de(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?fe(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:ue,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function le(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}}function ye(t){return Array.isArray(t)?t[0]:t}function ge(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:i,filterEvents:r,limit:c,fromState:a,stopWhen:h}=de(t,e),u=ce(),f={};let p=0;const d=[{nextState:a??t.getInitialSnapshot(u,e.input),event:void 0,prevState:void 0}],l=new Map;for(;d.length;){const{nextState:t,event:e,prevState:a}=d.shift();if(p++>c)throw new Error("Traversal limit exceeded");const y=o(t,e,a);if(f[y])continue;if(l.set(y,t),f[y]={state:t,transitions:{}},h&&h(t))continue;const g="function"==typeof i?i(t):i;for(const e of g){if(r&&!r(t,e))continue;const o=ye(s(t,e,u));f[y].transitions[n(e)]={event:e,state:o},d.push({nextState:o,event:e,prevState:t})}}return f}function ve(t){let e=[];if(t.steps.length){for(let n=0;n<t.steps.length;n++){const o=t.steps[n];e.push({state:o.state,event:0===n?{type:s}:t.steps[n-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:s}}];return{...t,steps:e}}function me(t,e,s){const n=de(t,{events:e,...s},(o=t)&&o instanceof Zt?fe(t):pe());var o;const i=ce(),r=n.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:c,serializeEvent:a}=n,h=ge(t,n),u=new Map,f=[],p=c(r,void 0,void 0);u.set(p,r);let d=p,l=r;for(const t of e){f.push({state:u.get(d),event:t});const e=a(t),{state:s,event:n}=h[d].transitions[e];if(!s)throw new Error(`Invalid transition from ${d} with ${e}`);const o=c(s,t,u.get(d));u.set(o,s),d=o,l=s}return n.toState&&!n.toState(l)?[]:[ve({state:l,steps:f,weight:f.length})]}function _e(t,e){const s=de(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(ce(),e?.input),i=ge(t,s),r=new Map,c=new Map,a=n(o,void 0,void 0);c.set(a,o),r.set(a,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(a);for(const t of h){const e=c.get(t),{weight:s}=r.get(t);for(const o of Object.keys(i[t].transitions)){const{state:a,event:f}=i[t].transitions[o],p=n(a,f,e);if(c.set(p,a),r.has(p)){const{weight:e}=r.get(p);e>s+1&&r.set(p,{weight:s+1,state:t,event:f})}else r.set(p,{weight:s+1,state:t,event:f});u.has(p)||h.add(p)}u.add(t),h.delete(t)}const f={},p=[];return r.forEach(({weight:t,state:e,event:s},n)=>{const o=c.get(n),i=e?f[e].paths[0].steps.concat({state:c.get(e),event:s}):[];p.push({state:o,steps:i,weight:t}),f[n]={state:o,paths:[{state:o,steps:i,weight:t}]}}),s.toState?p.filter(t=>s.toState(t.state)).map(ve):p.map(ve)}function Se(t,e){const s=de(t,e),n=ce(),o=s.fromState??t.getInitialSnapshot(n,e?.input),i=s.serializeState,r=ge(t,s),c=new Map,a={vertices:new Set,edges:new Set},h=[],u={};function f(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){u[e]||(u[e]={state:c.get(e),paths:[]});const t=u[e],n={state:s,weight:h.length,steps:[...h]};t.paths.push(n)}else{if(!r[t])return;for(const s of Object.keys(r[t].transitions)){const{state:n,event:o}=r[t].transitions[s];if(!(s in r[t].transitions))continue;const u=c.get(t),p=i(n,o,u);c.set(p,n),a.vertices.has(p)||(a.edges.add(s),h.push({state:c.get(t),event:o}),f(p,e))}}h.pop(),a.vertices.delete(t)}const p=i(o,void 0);c.set(p,o);for(const t of Object.keys(r))f(p,t);const d=Object.values(u).flatMap(t=>t.paths);return s.toState?d.filter(t=>s.toState(t.state)).map(ve):d.map(ve)}t.TestModel=oe,t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.createShortestPathsGen=se,t.createSimplePathsGen=ne,t.createTestModel=function(t,e){(t=>{t.root})(t);const s=e?.serializeEvent??te,n=e?.serializeTransition??re,{events:o,...i}=e??{};return new oe(t,{serializeState:(t,e,o)=>`${he(t)}${n(t,e,o,{serializeEvent:s})}`,stateMatcher:(e,s)=>s.startsWith("#")?e._nodes.includes(t.getStateNodeById(s)):e.matches(s),events:t=>{const e="function"==typeof o?o(t):o??[];return Tt(t).flatMap(t=>e.some(e=>e.type===t)?e.filter(e=>e.type===t):[{type:t}])},...i})},t.getAdjacencyMap=ge,t.getPathsFromEvents=me,t.getShortestPaths=_e,t.getSimplePaths=Se,t.getStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,n)=>{const o=s[n],i=t(o);return e.push(o,...i),e},[])},t.joinPaths=le,t.serializeSnapshot=he,t.toDirectedGraph=function t(e){const s=e instanceof Zt?e.root:e,n=[...s.transitions.values()].flat().flatMap((t,e)=>(t.target?t.target:[s]).map((n,o)=>{const i={id:`${s.id}:${e}:${o}`,source:s,target:n,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=i;return{source:s.id,target:n.id,label:t}}};return i})),o={id:s.id,stateNode:s,children:ae(s).map(t),edges:n,toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s}}};return o},Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate-graph.umd.min.js.map