xstate 6.0.0-beta.2 → 6.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +4 -2
  2. package/dist/{createActor-20a97166.esm.js → createActor-49ea55ba.esm.js} +17 -8
  3. package/dist/{createActor-c91c9ffe.cjs.js → createActor-73aa92ba.cjs.js} +17 -7
  4. package/dist/{createActor-0250284a.development.esm.js → createActor-a085b20b.development.esm.js} +17 -8
  5. package/dist/{createActor-c029d29f.development.cjs.js → createActor-dfb6b790.development.cjs.js} +17 -7
  6. package/dist/declarations/src/fsm.d.ts +7 -7
  7. package/dist/{effectDescriptor-47f73e7e.cjs.js → effectDescriptor-3402f63e.cjs.js} +1 -1
  8. package/dist/{effectDescriptor-e93df910.esm.js → effectDescriptor-65821048.development.esm.js} +1 -1
  9. package/dist/{effectDescriptor-5ac7dccb.development.esm.js → effectDescriptor-72c62058.esm.js} +1 -1
  10. package/dist/{effectDescriptor-3fff5c51.development.cjs.js → effectDescriptor-d0ea44ad.development.cjs.js} +1 -1
  11. package/dist/{legacySnapshot-ae6594a7.development.esm.js → legacySnapshot-11aba2d2.development.esm.js} +1 -1
  12. package/dist/{legacySnapshot-ebf0b2b8.development.cjs.js → legacySnapshot-2e2c1d3b.development.cjs.js} +1 -1
  13. package/dist/{legacySnapshot-8d595687.cjs.js → legacySnapshot-a85dfbe2.cjs.js} +1 -1
  14. package/dist/{legacySnapshot-9e06feb4.esm.js → legacySnapshot-fffe81a0.esm.js} +1 -1
  15. package/dist/xstate-actors.cjs.js +30 -5
  16. package/dist/xstate-actors.development.cjs.js +30 -5
  17. package/dist/xstate-actors.development.esm.js +31 -6
  18. package/dist/xstate-actors.esm.js +31 -6
  19. package/dist/xstate-actors.umd.min.js +1 -1
  20. package/dist/xstate-actors.umd.min.js.map +1 -1
  21. package/dist/xstate-durable.cjs.js +3 -3
  22. package/dist/xstate-durable.development.cjs.js +3 -3
  23. package/dist/xstate-durable.development.esm.js +3 -3
  24. package/dist/xstate-durable.esm.js +3 -3
  25. package/dist/xstate-durable.umd.min.js +1 -1
  26. package/dist/xstate-durable.umd.min.js.map +1 -1
  27. package/dist/xstate-fsm.cjs.js +61 -31
  28. package/dist/xstate-fsm.development.cjs.js +61 -31
  29. package/dist/xstate-fsm.development.esm.js +61 -31
  30. package/dist/xstate-fsm.esm.js +61 -31
  31. package/dist/xstate-fsm.umd.min.js +1 -1
  32. package/dist/xstate-fsm.umd.min.js.map +1 -1
  33. package/dist/xstate-graph.cjs.js +1 -1
  34. package/dist/xstate-graph.development.cjs.js +1 -1
  35. package/dist/xstate-graph.development.esm.js +2 -2
  36. package/dist/xstate-graph.esm.js +2 -2
  37. package/dist/xstate-persist.cjs.js +2 -2
  38. package/dist/xstate-persist.development.cjs.js +2 -2
  39. package/dist/xstate-persist.development.esm.js +3 -3
  40. package/dist/xstate-persist.esm.js +3 -3
  41. package/dist/xstate-persist.umd.min.js +1 -1
  42. package/dist/xstate-persist.umd.min.js.map +1 -1
  43. package/dist/xstate-validation.cjs.js +1 -1
  44. package/dist/xstate-validation.development.cjs.js +1 -1
  45. package/dist/xstate-validation.development.esm.js +1 -1
  46. package/dist/xstate-validation.esm.js +1 -1
  47. package/dist/xstate.cjs.js +26 -8
  48. package/dist/xstate.development.cjs.js +26 -8
  49. package/dist/xstate.development.esm.js +28 -10
  50. package/dist/xstate.esm.js +28 -10
  51. package/dist/xstate.umd.min.js +1 -1
  52. package/dist/xstate.umd.min.js.map +1 -1
  53. package/docs/actor-logic.md +1 -1
  54. package/docs/api-stability.json +93 -81
  55. package/docs/faq.md +1 -1
  56. package/docs/fsm.md +53 -10
  57. package/docs/index.md +2 -1
  58. package/docs/inspect-actor-systems.md +20 -3
  59. package/docs/inspection.md +5 -1
  60. package/docs/invoke.md +2 -2
  61. package/docs/migrate-inspector.md +141 -0
  62. package/docs/system-transitions.md +2 -0
  63. package/docs/transitions.md +5 -1
  64. package/docs/xstate-v5-to-v6.md +6 -4
  65. package/package.json +1 -1
@@ -3,9 +3,9 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var dist_xstatePersist = require('./xstate-persist.cjs.js');
6
- var createActor = require('./createActor-c91c9ffe.cjs.js');
7
- var effectDescriptor = require('./effectDescriptor-47f73e7e.cjs.js');
8
- require('./legacySnapshot-8d595687.cjs.js');
6
+ var createActor = require('./createActor-73aa92ba.cjs.js');
7
+ var effectDescriptor = require('./effectDescriptor-3402f63e.cjs.js');
8
+ require('./legacySnapshot-a85dfbe2.cjs.js');
9
9
  require('./validation-4561b43c.cjs.js');
10
10
 
11
11
  /** @experimental */
@@ -3,9 +3,9 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var dist_xstatePersist = require('./xstate-persist.development.cjs.js');
6
- var createActor = require('./createActor-c029d29f.development.cjs.js');
7
- var effectDescriptor = require('./effectDescriptor-3fff5c51.development.cjs.js');
8
- require('./legacySnapshot-ebf0b2b8.development.cjs.js');
6
+ var createActor = require('./createActor-dfb6b790.development.cjs.js');
7
+ var effectDescriptor = require('./effectDescriptor-d0ea44ad.development.cjs.js');
8
+ require('./legacySnapshot-2e2c1d3b.development.cjs.js');
9
9
  require('./validation-f2714a35.development.cjs.js');
10
10
 
11
11
  /** @experimental */
@@ -1,7 +1,7 @@
1
1
  import { restoreLogicSnapshot } from './xstate-persist.development.esm.js';
2
- import { j as encodeAddressSegment, aL as getRootActorId, aM as RUNTIME_OPERATIONS, aI as isRemoteActorRef, aB as createStartEffect, aN as createTimerEffect, aO as getSnapshotActorRef, z as isMachineSnapshot, aP as withExecutionOwner, y as matchesTimerKey, aQ as getTimerStart, aR as recordTimerStart, K as deliverEvent, aS as withSystemInspector, aT as adoptSystem, aU as withExecutionIdentity, ah as createInertActorScope, ai as setInertActorScopeSnapshot, ak as attachSnapshotActorRef } from './createActor-0250284a.development.esm.js';
3
- import { d as describeExecutableEffect, a as initialTransition, t as transition } from './effectDescriptor-5ac7dccb.development.esm.js';
4
- import './legacySnapshot-ae6594a7.development.esm.js';
2
+ import { j as encodeAddressSegment, aM as getRootActorId, aN as RUNTIME_OPERATIONS, aJ as isRemoteActorRef, aC as createStartEffect, aO as createTimerEffect, aP as getSnapshotActorRef, A as isMachineSnapshot, aQ as withExecutionOwner, z as matchesTimerKey, aR as getTimerStart, aS as recordTimerStart, L as deliverEvent, aT as withSystemInspector, aU as adoptSystem, aV as withExecutionIdentity, ai as createInertActorScope, aj as setInertActorScopeSnapshot, al as attachSnapshotActorRef } from './createActor-a085b20b.development.esm.js';
3
+ import { d as describeExecutableEffect, a as initialTransition, t as transition } from './effectDescriptor-65821048.development.esm.js';
4
+ import './legacySnapshot-11aba2d2.development.esm.js';
5
5
  import './validation-e69470ad.development.esm.js';
6
6
 
7
7
  /** @experimental */
@@ -1,7 +1,7 @@
1
1
  import { restoreLogicSnapshot } from './xstate-persist.esm.js';
2
- import { j as encodeAddressSegment, aK as getRootActorId, aL as RUNTIME_OPERATIONS, aH as isRemoteActorRef, aB as createStartEffect, aM as createTimerEffect, aN as getSnapshotActorRef, A as isMachineSnapshot, aO as withExecutionOwner, z as matchesTimerKey, aP as getTimerStart, aQ as recordTimerStart, L as deliverEvent, aR as withSystemInspector, aS as adoptSystem, aT as withExecutionIdentity, ai as createInertActorScope, aj as setInertActorScopeSnapshot, al as attachSnapshotActorRef } from './createActor-20a97166.esm.js';
3
- import { d as describeExecutableEffect, a as initialTransition, t as transition } from './effectDescriptor-e93df910.esm.js';
4
- import './legacySnapshot-9e06feb4.esm.js';
2
+ import { j as encodeAddressSegment, aL as getRootActorId, aM as RUNTIME_OPERATIONS, aI as isRemoteActorRef, aC as createStartEffect, aN as createTimerEffect, aO as getSnapshotActorRef, B as isMachineSnapshot, aP as withExecutionOwner, A as matchesTimerKey, aQ as getTimerStart, aR as recordTimerStart, M as deliverEvent, aS as withSystemInspector, aT as adoptSystem, aU as withExecutionIdentity, aj as createInertActorScope, ak as setInertActorScopeSnapshot, am as attachSnapshotActorRef } from './createActor-49ea55ba.esm.js';
3
+ import { d as describeExecutableEffect, a as initialTransition, t as transition } from './effectDescriptor-72c62058.esm.js';
4
+ import './legacySnapshot-fffe81a0.esm.js';
5
5
  import './validation-05f1d517.esm.js';
6
6
 
7
7
  /** @experimental */
@@ -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).XStateDurable={})}(this,function(t){"use strict";const e={$actor:["@actor",["incarnation"]],$error:["@error",["message"]],$stateNode:["@stateNode",[]],$systemMapper:["@systemMapper",[]]},s={_stateInputs:"stateInputs",_nextTimerId:"nextTimerId",_nextActorIds:"nextActorIds"};function n(t){if(!t||"object"!=typeof t)return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e||Array.isArray(t)}function r(t,s){if(!n(t))return t;if(Array.isArray(t)){const e=t.map(t=>r(t,s));return e.some((e,s)=>e!==t[s])?e:t}const o=Object.keys(t),i=o.find(t=>s.includes(t));if(i&&"string"==typeof t[i]&&o.every(t=>t===i||e[i][1].includes(t))){const{[i]:s,...n}=t;return{[e[i][0]]:s,...n}}let c;for(const e of o){const n=r(t[e],s);n!==t[e]&&((c??={...t})[e]=n)}return c??t}function o(t){return t?.machine&&"function"==typeof t.matches?t:n(e=t)&&"_nextTimerId"in e&&!("nextTimerId"in e)?r(function(t){if(!n(t)||"function"==typeof t.matches)return t;let e;for(const[n,r]of Object.entries(s))if(n in t&&!(r in t)){const{[n]:s,...o}=e??t;e={...o,[r]:s}}return e??t}(t),["$actor"]):t;var e}function i(t,...e){return`XState error E${t}${e.length?` (${e.map(t=>"string"==typeof t?JSON.stringify(t):String(t)).join(", ")})`:""}. See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e${t}`}const c=new Set(["clock","logger","syncSnapshot","id","registryKey","input","src","inspect","onRejectedEvent","onUnhandledEvent","_systemRef","_sessionId","_inert","_restore"]);const a="xstate.init",u="@xstate.spawn",d="xstate.stop",h="@xstate.terminate",f="xstate.timer",l={unsubscribe(){}};function p(t){return!0===t._remote}function y(t){if("object"!=typeof t||null===t||Array.isArray(t)||"string"!=typeof t["@actor"])return!1;for(const e in t)if("@actor"!==e&&"incarnation"!==e)return!1;const e=t.incarnation;return void 0===e||"string"==typeof e}function v(t){const e=t.slice(t.lastIndexOf("/")+1);return e.includes("%")?e.replaceAll("%2F","/").replaceAll("%25","%"):e}function g(t){return new Error(i(50,...void 0===t.incarnation?[t["@actor"]]:[t["@actor"],t.incarnation]))}function m(t,e){const s=t._getByAddress?.(e["@actor"]);return!s||void 0!==e.incarnation&&s.sessionId!==e.incarnation?void 0:s}const _=Object.freeze({status:"active",output:void 0,error:void 0});function x(t,e){const s={_remote:!0,ref:void 0,id:e.id,address:e.address,src:e.src,registryKey:e.registryKey,sessionId:e.incarnation,system:t,_parent:e.parent,_syncSnapshot:e.syncSnapshot,send(e){t.sendEvent(void 0,n,e)},_send(t){throw new Error(i(52,e.address,t.type))},getSnapshot:()=>_,getPersistedSnapshot(){throw new Error(i(53,e.address))},start(){},_stop(){},stop(){throw new Error(i(54,e.address))},select(){throw new Error(i(55,e.address))},get trigger(){throw new Error(i(56,e.address))},subscribe:()=>l,on:()=>l,_isRunning:()=>!1,toJSON:()=>({"@actor":e.address})},n=s;return s.ref=n,n}function w(t,e,s){return t.system._notifyEmitted(t,e),s.emitEvent(t,e)}const b=new WeakMap;async function S(t,e,s,n=e=>{t.system.sendEvent(t,t,e)}){const r=function(t,e){const s=t.getSnapshot().effects;return s&&Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0}(t,e);if("done"===r?.status)return r.output;if("error"===r?.status)throw r.error;const o=b.get(t)?.get(e);if(o)return o;if("active"!==t.getSnapshot().status)throw new Error(i(72,e));let c,a;const u=new Promise((t,e)=>{c=t,a=e});let d,h=b.get(t);h||(h=new Map,b.set(t,h)),h.set(e,u);const f=()=>{d?.unsubscribe(),h.delete(e),h.size||b.delete(t)};return u.then(f,f),d=t.subscribe({error:a,complete:()=>a(new Error(i(72,e)))}),(async()=>{try{n({type:"xstate.logic.effect.start",key:e});const r=await s();"active"===t.getSnapshot().status&&(n({type:"xstate.logic.effect.resolve",key:e,output:r}),c(r))}catch(s){"active"===t.getSnapshot().status&&n({type:"xstate.logic.effect.reject",key:e,error:s}),a(s)}})().catch(a),u}function I(t,e,s){if(y(e)){const n=e,r=t?.system,o=r&&m(r,n);if(!o){const e=g(n);if(!r)throw e;return void r.deadLetter(t,void 0,s,"missingTarget",{targetId:v(n["@actor"]),error:e})}e=o}if(E(t,e,s))return;e._send(s,t)}function E(t,e,s){const n=function(t,e,s){const n=e;if(t!==e&&n.logic?.isInternalEventType?.(s.type))return new Error(i(73,s.type,e.id))}(t,e,s);return!!n&&(e.system.deadLetter(t,e,s,"internalEvent",{error:n}),!0)}class A{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}function k(t,e){return{type:"xstate.after",delay:t,stateId:e}}function T(t,e){return{type:"xstate.timeout.actor",actorId:t,sessionId:e}}function O(t,e){return{type:"xstate.done.state",stateId:t,output:e}}function j(t,e){return{type:`xstate.error.${t}`,error:e}}function M(t){return{type:a,input:t}}function R(t){setTimeout(()=>{throw t})}const P="function"==typeof Symbol&&Symbol.observable||"@@observable",$=[],q=new Error("Transition effect");function D(t,e="abort"){const s={mode:e,parent:t,requiresReevaluation:!1};return $.push(s),{frame:s,close(){$.pop()}}}function K(t){const{stateId:e,delay:s,actorId:n}=t;switch(t.type){case"xstate.after":return{type:t.type,delay:s,stateId:e};case"xstate.timeout.state":return{type:t.type,stateId:e};case"xstate.timeout.actor":return{type:t.type,actorId:n}}}function L(t){return void 0!==t.id?{id:t.id}:void 0!==t.seq?{seq:t.seq}:{event:K(t.event)??t.event}}function N(t){const e=t;return"string"==typeof e.id?{id:e.id}:"number"==typeof e.seq?{seq:e.seq}:e.event&&"object"==typeof e.event&&"string"==typeof e.event.type?{event:e.event}:void 0}function z(t,e){if("id"in e)return t.id===e.id;if(void 0!==t.id)return!1;if("seq"in e)return t.seq===e.seq;if(void 0!==t.seq)return!1;const s=t.event,n=e.event;for(const t in n)if(s[t]!==n[t])return!1;return!0}function V(t,e){return`${t.sessionId}|${function(t){return"id"in t?JSON.stringify(["id",t.id]):"seq"in t?JSON.stringify(["seq",t.seq]):JSON.stringify(["event",K(t.event)??t.event])}(e)}`}const C=new WeakMap;function W(t){return C.get(t)??t.scheduledAt}function U(t,e){C.set(t,e)}function J(t){if("string"==typeof t)throw new Error(i(70,t))}const H={"@xstate.spawn":t=>t.system.spawnActor(t._parent,t),"@xstate.start":t=>t.system.startActor(t),"@xstate.raise":(t,e,s)=>t.system.scheduleTimer(t.self,L({id:s.id,seq:s.seq,event:e}),s?.delay??0),"@xstate.sendTo":(t,e,s,n)=>(J(s),void 0!==n?.delay?t.system.scheduleTimer(t.self,L({id:n.id,seq:n.seq,event:s}),n?.delay??0):t.system._relay(t.self,e,s)),"@xstate.cancel":(t,e)=>t.system.cancelTimer(t.self,e),"@xstate.stop":(t,e)=>t.system.stopActor(e),"@xstate.terminate":(t,e)=>t.system.terminateActor(t,e)},B=new WeakMap;function F(t,e){let s=B.get(t);if(!s){s=new Map;for(const e of Object.keys(t)){const n=t[e];s.has(n)||s.set(n,e)}B.set(t,s)}return s.get(e)}const X=Symbol("xstate.systemLogicMetadata"),G=new WeakMap;function Q(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]],n={id:e,start:(e,{self:s,system:n})=>{const r=e.input.actor;if(!r||"stopped"===r.getSnapshot().status)return;const o=t(e.input,{self:s,system:n});if(!o)return;let i,c=!1;const a=()=>{c||(c=!0,o.unsubscribe(),i?.unsubscribe())},u=s._parent;u&&(i=u.subscribe({complete:a,error:a})),G.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===d?(G.get(s)?.unsubscribe(),G.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return Object.defineProperty(n,X,{value:{kind:e}}),n}function Y(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function Z(){return Q(({actor:t,eventType:e,mapper:s},{self:n,system:r})=>{const o="*"!==e&&e.endsWith(".*");return t.on(o?"*":e,t=>{o&&!Bs(t.type,e)||Y(n,r,()=>s(t))})},"@xstate.listener")}const tt=Z();function et(){return Q(({actor:t,mappers:e},{self:s,system:n})=>{const{done:r,error:o,snapshot:i}=e;return t.subscribe({next:t=>{"done"===t.status&&r?Y(s,n,()=>r(t.output)):"error"===t.status&&o?Y(s,n,()=>o(t.error)):"active"===t.status&&i&&Y(s,n,()=>i(t))},error:t=>{o&&Y(s,n,()=>o(t))},complete:()=>{}})},"@xstate.subscription")}const st=et();function nt(){const t=this.action?.(...this.args);return t}function rt(t=this.source.system){return w(this.source,this.event,t)}function ot(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function it(t,e,s,n,r){return{kind:"builtin",type:"@xstate.deadLetter",exec:ot,source:e,target:t.self,event:s,reason:n,detail:r,params:void 0,args:[]}}function ct(t,e,s){return{kind:"builtin",type:"@xstate.deadLetter",exec:ot,source:t.self,target:void 0,event:e,reason:"missingTarget",detail:{targetId:s,error:new Error(i(65,s))},params:void 0,args:[]}}function at(t=this.actor.system){return t.spawnActor(this.source,this.actor)}function ut(t=this.actor.system){if(2!==this.actor._processingStatus)return t.startActor(this.actor)}function dt(t=this.source.system){return t.stopActor(this.actor)}function ht(t=this.actor.system){const e="done"===this.status?{status:"done",output:this.output,error:void 0}:{status:"error",output:void 0,error:this.error};return t.terminateActor(this.actor,e)}function ft(t=this.source.system){return t.scheduleTimer(this.source,L(this),this.delay??0)}function lt(t=this.source.system){return J(this.event),void 0!==this.delay?t.scheduleTimer(this.source,L(this),this.delay):t.sendEvent(this.source,this.target,this.event)}function pt(t=this.source.system){return t.cancelTimer(this.source,N(this))}function yt(t,e,s){if(!Ct(e))return t;if("@xstate.cancel"===e.type){const s=N(e);return t.timers?.some(t=>z(t,s))?{...t,timers:t.timers.filter(t=>!z(t,s))}:t}if("@xstate.raise"!==e.type&&"@xstate.sendTo"!==e.type||void 0===e.delay)return t;let n=t._nextTimerId??0;if(void 0===e.id&&!K(e.event)){e.seq=n++;const t=e.args;t[t.length-1]={...t[t.length-1],seq:e.seq}}const r="@xstate.raise"===e.type||e.target===s.self?"self":e.target,o={...void 0!==e.id&&{id:e.id},...void 0!==e.seq&&{seq:e.seq},delay:e.delay,type:e.type,event:e.event,target:r},i=L(o),c=t.timers??[],a=c.findIndex(t=>z(t,i));return{...t,timers:-1===a?[...c,o]:c.map((t,e)=>e===a?o:t),_nextTimerId:n}}function vt(t,e){return{...t,...e}}function gt(t,e,...s){const n={action:e,args:s};return t.push(n),n}function mt(t,e){const s={...t};for(const t of Object.keys(e))s[t]=Math.max(s[t]??0,e[t]);return s}function _t(t,e,s){if("add"===e.type)return{...t,children:{...t.children,[e.id]:e.actor},...e.counters&&{_nextActorIds:mt(t._nextActorIds,e.counters)}};const n={...t.children};let r=e.actor._parent===s.self;for(const t of Object.keys(n))n[t]===e.actor&&(r=!0,delete n[t]);if(!r)throw new Error(i(47,e.actor.id,s.self.id));return s.system._unregister(e.actor),{...t,children:n}}function xt(t){if("object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action)return t}const wt=new WeakMap,bt=()=>({counters:new Map,explicitIds:new Set,stoppedIds:new Set});function St(t){wt.set(t,bt())}function It(t){return t.self._snapshot}function Et(t,e,s){return Math.max(e.counters.get(s)??0,It(t)?._nextActorIds?.[s]??0)}function At(t,e,s){let n=Et(t,e,s);const r=It(t)?.children;for(;e.explicitIds.has(`${s}:${n}`)||r?.[`${s}:${n}`];)n++;return n}function kt(t,e,s){const n=wt.get(t)??s??bt(),r=Zs(e),o=At(t,n,r);return n.counters.set(r,o+1),{id:`${r}:${o}`,counters:{[r]:o+1}}}function Tt(t,e,s){const n=wt.get(t)??s??bt(),r=It(t)?.children?.[e],o=void 0!==r&&!n.stoppedIds.has(e)&&"active"===r.getSnapshot().status;if(n.explicitIds.has(e)||o)throw new Error(i(67,e,t.self.id));n.explicitIds.add(e)}function Ot(t,e,s){const n=en(e);if(!n)return;n.prefix;const r=wt.get(t)??s??bt(),o=Math.max(Et(t,r,n.prefix),n.index+1);return r.counters.set(n.prefix,o),{[n.prefix]:o}}const jt=new WeakSet;function Mt(t){if("string"==typeof t)throw new Error(i(68,t))}function Rt(t,e,s,n=!1,r=!0){const o=wt.get(t)??bt(),c={cancel:s=>{gt(e,H["@xstate.cancel"],t,"string"==typeof s?{id:s}:s)},emit:t=>{e.push(t)},log:(...s)=>{gt(e,t.logger,...s)},raise:(n,r)=>{Mt(n),void 0!==r?.delay?gt(e,H["@xstate.raise"],t,n,r):s.push(n)},spawn:(s,n)=>{const{logic:c,src:a}=function(t,e){const s=function(t){return t.self.logic?.sources?.actors}(t);if("string"==typeof e){const t=s?.[e];if(!t)throw new Error(i(66,e));return{logic:t,src:e}}return s?{logic:e,src:F(s,e)}:{logic:e,src:void 0}}(t,s);if(!r){const e=Zs(a??c),s=n?.id??`${e}:${At(t,wt.get(t)??o,e)}`;return function(t){const{id:e,address:s}=t,n={ref:void 0,id:e,address:s,src:t.src,sessionId:void 0,send(){},getSnapshot:()=>_,subscribe:()=>l,on:()=>l,toJSON(){if(void 0===s)throw new Error(i(51,e));return{"@actor":s}}},r=n;return n.ref=r,r}({id:s,address:jt.has(t)?void 0:`${t.self.address}/${tn(s)}`,src:a})}let u,d=n?.id;void 0===d?({id:d,counters:u}=kt(t,a??c,o)):(Tt(t,d,o),u=Ot(t,d,o));const h=t.system.createActorRef(c,{...n,...void 0!==a&&{src:a},id:d,parent:t.self});return function(t,e,s,n){gt(t,H["@xstate.spawn"],e).childUpdate={type:"add",actor:e,id:s,counters:n}}(e,h,d,u),h},sendTo:(s,n,r)=>{gt(e,H["@xstate.sendTo"],t,s,n,r)},stop:s=>{if(s){const n=s;gt(e,H["@xstate.stop"],t,n).childUpdate={type:"remove",actor:n},function(t,e){const s=wt.get(t);s&&(s.stoppedIds.add(e.id),s.explicitIds.delete(e.id))}(t,n)}}};n&&Object.assign(c,{listen:(s,n,o)=>{if(!r)return{id:void 0};const i={actor:s,eventType:n,mapper:o},c=t.system.createActorRef(tt,{input:i,parent:t.self});return gt(e,H["@xstate.spawn"],c),c},subscribeTo:(s,n)=>{if(!r)return{id:void 0};const o={actor:s,mappers:"function"==typeof n?{snapshot:n}:n},i=t.system.createActorRef(st,{input:o,parent:t.self});return gt(e,H["@xstate.spawn"],i),i}});let a=!1;const u=t=>(...e)=>a?qt():t(...e);for(const t of Object.keys(c))c[t]=u(c[t]);const d=Ut(c,u((t,...s)=>{"function"==typeof t&&gt(e,t,...s)}));return Pt.set(d,()=>{a=!0}),d}const Pt=new WeakMap;function $t(t){Pt.get(t)?.()}function qt(){}function Dt(t,e){switch(t){case H["@xstate.spawn"]:{const[t]=e;return{type:"@xstate.spawn",kind:"builtin",exec:at,source:t._parent,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case H["@xstate.raise"]:{const[,t,s]=e;return{type:"@xstate.raise",kind:"builtin",exec:ft,source:e[0].self,event:t,id:s?.id,delay:s?.delay}}case H["@xstate.sendTo"]:{const[,t,s,n]=e;return{type:"@xstate.sendTo",kind:"builtin",exec:lt,source:e[0].self,target:t,event:s,id:n?.id,delay:n?.delay}}case H["@xstate.cancel"]:{const[,t]=e;return{type:"@xstate.cancel",kind:"builtin",exec:pt,source:e[0].self,...t}}case H["@xstate.stop"]:{const[,t]=e;return{type:"@xstate.stop",kind:"builtin",exec:dt,source:e[0].self,actor:t,id:t.id}}default:return}}function Kt(t){const e=[t];return{kind:"builtin",exec:ut,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function Lt(t,e,s){const n=t.self,r={id:e.id,seq:e.seq,delay:s};if("@xstate.raise"===e.type)return{kind:"builtin",type:e.type,source:n,event:e.event,id:e.id,...void 0!==e.seq&&{seq:e.seq},delay:s,params:void 0,args:[t,e.event,r],exec:ft};const o="self"===e.target?n:e.target;return{kind:"builtin",type:e.type,source:n,target:o,event:e.event,id:e.id,...void 0!==e.seq&&{seq:e.seq},delay:s,params:void 0,args:[t,o,e.event,r],exec:lt}}function Nt(t,e,s){const n=[t,e,s,{}];return{kind:"builtin",exec:lt,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:n}}function zt(t,e){if("done"!==e.status&&"error"!==e.status)throw new Error(i(69,t.self.id,e.status));const s="done"===e.status?{status:"done",output:e.output,error:void 0}:{status:"error",output:void 0,error:e.error},n=[t.self,s];return{kind:"builtin",exec:ht,type:h,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:n}}function Vt(t,e,[s,n]){const r="done"===s.status||"error"===s.status,o="done"===e?.status||"error"===e?.status,i=n.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===h);return!r||o||i?[s,n]:[s,[...n,zt(t,s)]]}function Ct(t){return"builtin"===t.kind}function Wt(t,e,s,n){let r=t;const o=[];for(const t of n){const e="function"==typeof t,n=xt(t);let i=n?.args;if(n?.action===H["@xstate.sendTo"]&&(void 0===n.args[1]||"string"==typeof n.args[1])){const t=n.args[1],e=void 0!==t&&Object.hasOwn(r.children,t)?r.children[t]:void 0;if(!e){o.push(ct(s,n.args[2],t));continue}i=[n.args[0],e,...n.args.slice(2)]}const c=e?t:!!n&&n.action.bind(null,...i);let a;if("object"==typeof t&&null!==t){const{type:e,childUpdate:s,...n}=t;a=n}if(n?.childUpdate&&(r=_t(r,n.childUpdate,s)),!c||!("resolve"in c)){const c="object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action?Dt(t.action,i):void 0,u="object"==typeof t&&null!==t&&!n,d={kind:c?"builtin":u?"emit":"action",type:"object"==typeof t?"action"in t&&"function"==typeof t.action?t.action.name??"(anonymous)":t.type:t.name||"(anonymous)",params:c?void 0:a,args:"object"==typeof t&&"action"in t?i:[],...c?{}:u?{source:s.self,event:t}:{action:n?.action??(e?t:void 0)},...c?{}:{exec:u?rt:nt},...c};r=yt(r,d,s),o.push(d);continue}}return[r,o]}function Ut(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:Jt,emit:Jt,log:Jt,raise:Jt,spawn:Ht,sendTo:Jt,stop:Jt,listen:Ht,subscribeTo:Ht,...t}),s}const Jt=()=>{},Ht=()=>({});let Bt;function Ft(){return void 0!==Bt}function Xt(){return Bt}const Gt=new WeakMap,Qt=["runtime","_timerMap","_rejectionListeners","_inspectionObservers","_emissionListeners"],Yt=new WeakMap;let Zt;const te=new WeakMap,ee=new WeakMap,se=new Map;function ne(t){const e=t._peekKeyedActors;return e?e.call(t)??se:t.keyedActors}function re(t){t._snapshotVersion++}function oe(t){return t._snapshotVersion}function ie(t,e,s,n){const r=Gt.get(t),o=r?.executionSystem??t,c=r?.rootSystem??t,a=void 0!==n&&Yt.get(o)!==n,u=n?!!n.inspect:Ft()&&(r?.forwardInspection??!0),d=function(t,e){if(e){const t=new Map(e.children);return e.root?.sessionId&&t.set(e.root.sessionId,e.root),t}return new Map(t.children)}(t,s),h=new Map(s?.keyedActors??ne(t)),f=new WeakMap,l=()=>Gt.get(y).executionSystem,p=()=>Gt.get(y).forwardInspection,y=Object.assign(Object.create(o),{children:d,keyedActors:h,reverseKeyedActors:f,_snapshot:{...s?.snapshot??t._snapshot},_snapshotVersion:s?.sourceVersion??t._snapshotVersion,_register:(t,e)=>(d.set(t,e),re(y),t),_unregister:t=>{t.sessionId&&d.delete(t.sessionId);const e=f.get(t);void 0!==e&&h.get(e)===t&&h.delete(e),f.delete(t),re(y)},_set:(t,e)=>{const s=h.get(t);if(s&&s!==e)throw new Error(i(45,String(t)));h.set(t,e),f.set(e,t),re(y)},get:t=>h.get(t),getAll:()=>Object.fromEntries(h),onEmitted:t=>c.onEmitted.call(l(),t),_notifyEmitted:(t,e)=>c._notifyEmitted.call(l(),t,e),_hasInspectionObservers:()=>p()&&(c._hasInspectionObservers?.call(l())??!1),_sendInspectionEvent:t=>{p()&&c._sendInspectionEvent.call(l(),t)}}),v=a?y:o;if(a)ce(y,o,n);else for(const t of Qt)Object.defineProperty(y,t,{configurable:!0,get:()=>l()[t],set:e=>{l()[t]=e}});Gt.set(y,{executionSystem:v,rootSystem:c,forwardInspection:u});for(const[t,e]of h)e&&f.set(e,t);for(const t of Object.values(e)){if(!t)continue;t.sessionId&&d.set(t.sessionId,t);const e=t.registryKey;e&&(h.set(e,t),f.set(t,e))}return y}function ce(t,e,s){const n=e._timerMap;for(const e of Qt)Object.defineProperty(t,e,{configurable:!0,writable:!0,value:"runtime"===e?s.runtime:"_timerMap"===e&&n?{...n}:void 0});Yt.set(t,s),s.inspect&&t.inspect(s.inspect)}function ae(){const t=Zt;return Zt=void 0,t}function ue(t){const e=te.get(t);if(e)return e;const s=ee.get(t);if(!s)return;const n=s();return te.set(t,n),ee.delete(t),n}function de(t,e){const s=te.get(t);if(s)return te.set(e,s),!0;const n=ee.get(t);return!!n&&(ee.set(e,n),!0)}function he(t,e,s=e.system,n){ee.delete(t);const r=oe(s),o=n?ue(n):void 0,i=o?.actor===e?o:ue(t);if(i?.actor===e&&i.systemState.sourceSystem===s&&i.systemState.sourceVersion===r)return void te.set(t,i);const c=function(t){const e=t._getRootActor?.(),s=t._peekChildren?.();if(!e&&!s){if(t._getRootActor&&t._peekChildren)return{};const e=new Map(t.children);return e.size?{children:e}:{}}return s?.size?{children:new Map(t.children)}:e?{root:e}:{}}(s);let a=c.children;const u=ne(s);let d=u.size?new Map(u):se;for(const e of Object.values(function(t){return"children"in t&&t.children?t.children:{}}(t))){if(!e)continue;e.sessionId&&(a??=new Map).set(e.sessionId,e);const t=e.registryKey;t&&(d===se&&(d=new Map),d.set(t,e))}te.set(t,{actor:e,systemState:{...c,children:a,keyedActors:d,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:r}})}const fe=Symbol();function le(t){return!!t[fe]}function pe(t){return le(t)?t._parent:t.self._parent}function ye(t,e){if(!le(e)){const s=t,n=e.self;return s.self=n,s.system=e.system,s.parent=n._parent,s}return Object.defineProperties(t,{self:{enumerable:!0,get:()=>e.self},system:{enumerable:!0,get:()=>e.system},parent:{enumerable:!0,get:()=>pe(e)}}),t}function ve(t,e,s=!0){const n=be(t);if(n){n.snapshot=e;const t=n.materialized??n.identityScope;t&&(t.self._snapshot=e)}else t.self._snapshot=e;return s&&e&&"object"==typeof e&&he(e,t.self),e}function ge(t){return!!be(t)||!!t.self.options?._inert}function me(t,e){ve(t,e,!1);const s=be(t);we.set(e,t);const n=()=>(he(e,t.self,t.system),ue(e));return s&&(s.materialized?s.identityProvider=n:s.identityProvider??=n),function(t,e){te.delete(t),ee.set(t,e)}(e,n),e}function _e(t,e){return t.sourceRef=void 0,t.sourceChildren={},t.materialized=e,t.materialize=()=>e,e}const xe=Symbol(),we=new WeakMap;function be(t){return t[xe]}function Se(t){return be(t).materialize()}const Ie={[fe]:!0,get _parent(){const t=be(this);return t.parentKnown?t.parent:Se(this).self._parent},get self(){return Se(this).self},get defer(){return Se(this).defer},get id(){return Se(this).id},get logger(){return Se(this).logger},get sessionId(){return Se(this).sessionId},get stopChild(){return Se(this).stopChild},get system(){return Se(this).system},get emit(){return Se(this).emit},get actionExecutor(){return Se(this).actionExecutor}};function Ee(t,e,s,n,r,o){const i=e?.(),c=r??i?.actor,a=c?.system,u=c&&a?ie(a,s,r?void 0:i?.systemState,o):void 0,d=_n(t,{_inert:!0,...c?{id:c.id,_sessionId:c.sessionId}:{},...u?{_systemRef:{current:u}}:{}});c?._parent&&(d._parent=c._parent,d._address=void 0);const h=Object.create(d._actorScope,{defer:{value:()=>{}},stopChild:{value:t=>t._stop()},actionExecutor:{value:()=>{}},_snapshot:{enumerable:!0,configurable:!0,get:()=>d._snapshot,set:t=>{d._snapshot=t}}});return n&&(h._snapshot=n),h}function Ae(t,e,s,n){const r=n??(e&&"object"==typeof e?we.get(e):void 0),o=r?be(r):void 0,i=e&&"object"==typeof e?function(t){return te.get(t)}(e):void 0,c=o?.identityProvider??(e&&"object"==typeof e?function(t){const e=te.get(t);return e?()=>e:ee.get(t)}(e):void 0),a={snapshot:e,sourceRef:c,sourceChildren:bs(e)?e.children:{},identityProvider:o?.identityProvider??c,parent:s?._parent??o?.parent??i?.actor._parent,owner:n?o?.owner:ae(),parentKnown:!(!s&&!o?.parentKnown&&!i&&e),materialize:()=>{const e=Ee(t,a.sourceRef,a.sourceChildren,a.snapshot,s,a.owner);return _e(a,e)}};if(!a.identityProvider&&!e){const e={};let n;const r=()=>(a.identityScope||(a.identityScope=Ee(t,a.sourceRef,a.sourceChildren,void 0,s,a.owner),void 0!==a.snapshot&&(a.identityScope.self._snapshot=a.snapshot)),a.identityScope);a.materialize=()=>{const t=r();return void 0!==a.snapshot&&(t.self._snapshot=a.snapshot),_e(a,t)},a.identityProvider=()=>{if(n)return n;const t=r();return he(e,t.self,t.system),n=ue(e)}}const u=Object.create(Ie);return u[xe]=a,u}function ke(t,e){if("string"!=typeof t)return t;const s=e[t];if(void 0!==s)return s;const n=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 r=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!r?.groups)return;const{weeks:o,days:i,hours:c,minutes:a,seconds:u}=r.groups;if(!(o||i||c||a||u))return;const d=t=>t?Number(t.replace(",",".")):0;return 7*d(o)*24*60*60*1e3+24*d(i)*60*60*1e3+60*d(c)*60*1e3+60*d(a)*1e3+1e3*d(u)}(t);if(void 0===n)throw new Error(i(9,t));return n}function Te(t,e,s){if("function"==typeof t)return t(s);const n=ke(t,e);return"function"==typeof n?n(s):n}function Oe(t,e){return t._stateInputs?.[e]}function je(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function Me(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Re(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function Pe(t){const e=new Set(t),s=new Set;for(const t of e)t.parent&&s.add(t.parent);for(const t of e)if("compound"!==t.type||s.has(t)){if("parallel"===t.type)for(const s of Me(t))if(!e.has(s)){const t=Be(s);for(const s of t)e.add(s)}}else for(const s of Be(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 $e(t,e){const s=Pe(e),n=new Map;for(const t of s)n.has(t)||n.set(t,[]),t.parent&&(n.has(t.parent)||n.set(t.parent,[]),n.get(t.parent).push(t));const r=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(je(t))return t.key}const s={};for(const t of e)s[t.key]=r(t);return s};return r(t)}function qe(t,e){return"compound"===e.type?Me(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?Me(e).every(e=>qe(t,e)):"final"===e.type}const De=t=>"#"===t[0];function Ke(t,e,s){const n=e.children[s];return!n||!("sessionId"in t)||(void 0===n.sessionId||n.sessionId===t.sessionId)}function Le(t,e,s,n){const r=t.entry;t.entry=(t,e)=>{const o="function"==typeof r?r(t,e):void 0,i=void 0!==o?.context?vt(t.context,o.context):t.context;return e.raise(s(t),{delay:n({context:i,event:t.event,delays:t.delays,input:t.input})}),o};const o=t.exit;t.exit=(t,s)=>(s.cancel({event:K(e)}),"function"==typeof o?o(t,s):void 0)}function Ne(t,e,s){const n=function(t){const{cond:e,actions:s,guard:n}=t;if(void 0!==e)return'"cond"';if(void 0!==s)return'"actions"';if(void 0!==n&&"function"!=typeof n)return'an object-form "guard"';return}(s);if(n)throw new Error(i(10,e||"always",t.id,n));const r=Ws(s.target),o=s.reenter??!1,c=Ue(t,r);We(t,c);const a={...s,target:c,source:t,reenter:o,eventType:e,toJSON:()=>ze(a)};return a}function ze(t){const{definition:e,...s}=t;return{...s,source:`#${t.source.id}`,target:t.target?.map(t=>`#${t.id}`)}}function Ve(t,e){for(let s=t.parent;s;s=s.parent)if(s===e)return!0;return!1}function Ce(t,e){const s=new Set;for(let e=t;e;e=e.parent)s.add(e);for(let t=e;t;t=t.parent)if(s.has(t))return t}function We(t,e){if(e&&!(e.length<2))for(let s=0;s<e.length;s++)for(let n=s+1;n<e.length;n++){const r=e[s],o=e[n],c=Ce(r,o);if(r===o||Ve(r,o)||Ve(o,r)||"parallel"!==c?.type)throw new Error(i(11,t.id))}}function Ue(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(De(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return Xe(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(i(13,e));try{return Xe(t.parent,n)}catch(e){throw new Error(i(12,t.id,e.message))}})}function Je(t){const e=Ws(t.config.target);if(!e)return"parallel"===t.parent.type?{target:[t.parent],source:t,reenter:!1,eventType:""}:t.parent.initial;const s=e.map(e=>"string"==typeof e?Xe(t.parent,e):e);return We(t,s),{target:s,source:t,reenter:!1,eventType:"",to:t.config._historyDefaultTransition}}function He(t){return"history"===t.type}function Be(t){const e=new Set;!function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)for(const e of s.initial.target??[])t(e);else if("parallel"===s.type)for(const e of Me(s))t(e)}(t);for(const s of e)for(const n of Re(s,t))e.add(n);return e}function Fe(t,e){const s=t.states?.[e];if(!s)throw new Error(i(14,e,t.id));return s}function Xe(t,e){if("string"==typeof e&&De(e))return t.machine.getStateNodeById(e);const s=qs(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=Fe(n,t)}return n}function Ge(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(i(14,e,t.id));return[t,s]}const s=Object.keys(e),n=new Array(s.length),r=[t.machine.root,t];for(let e=0;e<s.length;e++){const o=Fe(t,s[e]);n[e]=o,r.push(o)}for(let t=0;t<s.length;t++)r.push(...Ge(n[t],e[s[t]]));return r}function Qe(t,e,s,n,r,o){if("string"==typeof e){const i=Fe(t,e).next(s,n,r,o);return i&&i.length?i:t.next(s,n,r,o)}const i=Object.keys(e),c=i[0];if(1===i.length){const i=Qe(Fe(t,c),e[c],s,n,r,o);return i&&i.length?i:t.next(s,n,r,o)}const a=[];for(const c of i){const i=e[c];if(!i)continue;const u=Qe(Fe(t,c),i,s,n,r,o);u&&a.push(...u)}return a.length?a:t.next(s,n,r,o)}function Ye(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function Ze(t,e){for(const s of t)if(Ye(s,e))return!0;return!1}function ts(t,e){const s=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,n=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==s&&void 0!==n&&n<s&&([t,e]=[e,t]);const r=t instanceof Set?t:new Set(t);for(const t of e)if(r.has(t))return!0;return!1}function es(t,e,s,n){const r=new Set,o=new Map,i=t=>{let r=o.get(t);return r||(r=is([t],e,s,n),o.set(t,r)),r};for(const e of t){let t=!1;const s=new Set;for(const n of r)if(ts(i(e),i(n))){if(!Ye(e.source,n.source)){t=!0;break}s.add(n)}if(!t){for(const t of s)r.delete(t);r.add(e)}}return Array.from(r)}function ss(t,e,s,n,r){let o;return(i,c)=>{if(!i.to&&!c)return{targets:i.target,context:void 0,reenter:i.reenter,actions:void 0,internalEvents:void 0,input:void 0};let a=o?.get(i);return a||(a=as(i,t,e,s,{resolveActions:n,selectionResult:r?.get(i)}),(o??=new Map).set(i,a)),a}}function ns(t,e,s){const n=e.historyValue,{targets:r}=s(t);if(!r)return[];const o=new Set;for(const t of r)if(He(t))if(n[t.id])for(const e of n[t.id])o.add(e);else for(const n of ns(Je(t),e,s))o.add(n);else o.add(t);return[...o]}function rs(t,e){let s=t;for(;"parallel"===s.type;){const t=Me(s).find(t=>e.every(e=>e===t||Ye(e,t)));if(!t)break;s=t}return s}function os(t,e,s){const n=ns(t,e,s),{targets:r,reenter:o}=s(t);if(t._transitionDomain){if("internal"===t._transitionDomain&&"compound"===t.source.type&&n.every(e=>Ye(e,t.source)))return t.source;const[e,...s]=n.concat(t.source);for(const t of Re(e,void 0))if("compound"===t.type&&s.every(e=>Ye(e,t)))return t;return}if(!(r?.some(He)&&n.some(e=>e===t.source))&&n.every(e=>e===t.source||Ye(e,t.source)))return o?t.source:rs(t.source,n);const[i,...c]=n.concat(t.source);for(const t of Re(i,void 0))if(c.every(e=>Ye(e,t)))return o?t:rs(t,n);return o?void 0:rs(t.source.machine.root,n)}function is(t,e,s,n){const r=new Set;for(const o of t){const{targets:t,reenter:i}=n(o);if(t?.length){const t=os(o,s,n);i&&o.source===t&&r.add(t);for(const s of e)Ye(s,t)&&r.add(s)}}return[...r]}function cs(t,e,s,n,r,o,c){const a=[],u=e.machine._microstepHooks?.drain(s.self);if(u?.length&&o.push(...u),!t.length)return[e,a];{const u=new Set(e.nodes);let d=e.historyValue;const h=e.context,f=1===t.length?t:es(t,u,e,ss(e,n,s,!1,c)),l=ss(e,n,s,!0,c),p=f.some(t=>{const{targets:e,reenter:s}=l(t);return!!e?.length||!!s}),y=(t,r,o,i,c,a)=>{const u=[],d=[];let h;const f=Rt(s,u,d,!0),l=le(s)?ye({context:r,event:n,output:zs(n),children:o,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:i,stateNode:a},s):{context:r,event:n,output:zs(n),parent:s.self._parent,self:s.self,children:o,system:s.system,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:i,stateNode:a};let p;try{p=t(l,f)}finally{$t(f)}return fs(p,n,a.id,c),void 0!==p?.context&&(h=vt(r,p.context)),[u,h,d,p?.children]};let v=e;const g=(t,e)=>{const n=[],r=Rt(s,n,[]);for(const s of t.invoke){const t=e[s.id];t&&r.stop(t)}return n},m=()=>{const t=is(f,u,e,l);let n;t.sort((t,e)=>e.order-t.order);const r=[...u];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>je(t)&&Ye(t,e):t=>t.parent===e;n??={...d},n[t.id]=r.filter(s)}for(const n of t){const t=Oe(e,n.id),[r,i,c,d]=n.exit?y(n.exit,v.context,v.children,t,"exit",n):[[],void 0,void 0,void 0];c?.length&&o.push(...c),(i||d)&&(v=Ms(v,{...i?{context:i}:{},...d?{children:d}:{}}));const[h,f]=Wt(v,0,s,r);v=h,a.push(...f);const l=g(n,v.children);if(l.length){const[t,e]=Wt(v,0,s,l);v=t,a.push(...e)}u.delete(n)}d=n||d};!r&&p&&m();let _=v.context;const x=[],w=[],b=[];for(const t of f){const e=l(t,!0);if(t.to){const s={...t,target:e.targets,definition:t};s.toJSON=()=>ze(s),b.push(s)}else b.push(t);void 0!==e.context&&(_=vt(_,e.context)),e.actions&&x.push(...e.actions),e.internalEvents&&w.push(...e.internalEvents)}w.length&&o.push(...w);const S=()=>{const t=t=>{const e=v.machine.root;let r;if(void 0!==t.output&&t.parent){const i=o.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);r=i&&t.parent===e?i.output:Ns(t.output,v.context,n,s.self,x[t.id])}else if("parallel"===t.type){const e=o.find(e=>"xstate.done.state"===e.type&&e.stateId===t.id);r=e?.output}return void 0===e.output?t.parent===e?r:void 0:Ns(e.output,v.context,O(t.id,r),s.self)},c=new Set,h=new Set,p=new Map,g=(t,e)=>{for(const s of t)if(e&&!Ye(s,e)||c.add(s),"parallel"===s.type)for(const t of Me(s))Ze(c,t)||(c.add(t),m(t))},m=t=>{if(He(t))if(d[t.id]){const e=d[t.id];for(const t of e)c.add(t),m(t);for(const s of e)g(Re(s,t.parent),void 0)}else{const e=Je(t),s=t.parent;h.add(s);const n=p.get(s)??[];n.push(e),p.set(s,n);const{targets:r}=l(e);for(const s of r??[])c.add(s),e===t.parent?.initial&&h.add(t.parent),m(s);for(const e of r??[])g(Re(e,t.parent),void 0)}else{if("compound"===t.type){const e=l(t.initial).targets??[];for(const t of e)He(t)||c.add(t);h.add(t);for(const t of e)m(t);for(const s of e)g(Re(s,t),void 0);return}if("parallel"===t.type)for(const e of Me(t))Ze(c,e)||(c.add(e),h.add(e),m(e))}},_=new Map;for(const t of f){const s=os(t,e,l),{targets:n,reenter:r}=l(t),o=new Set;_.set(t,o);for(const e of n??[])He(e)||t.source===e&&t.source===s&&!r||(o.add(e),c.add(e),h.add(e)),m(e);const i=ns(t,e,l);for(const e of i){const n=Re(e,s);"parallel"===s?.type&&n.push(s),g(n,!t.source.parent&&r?void 0:s)}r&&s===t.source&&c.add(t.source)}if(r)for(const t of f[0]._statesForDefaultEntry??[e.machine.root])h.add(t);const x={};let w=!1;const b=new Set([...u].map(t=>t.id));for(const[t,s]of Object.entries(e._stateInputs??{}))b.has(t)?x[t]=s:w=!0;for(const t of f){const{targets:e,input:s}=l(t,!0);if(s&&e)for(const n of e.filter(e=>_.get(t)?.has(e)))x[n.id]=s,w=!0}const S=new Set;for(const r of[...c].sort((t,e)=>t.order-e.order)){u.add(r);const c=[];let d=v.children,f=!1;for(const t of"final"===r.type?[]:r.invoke){f=!0;let o=t.logic;"function"==typeof o&&(o=o({actors:e.machine.sources.actors,context:v.context,event:n,self:s.self}));const a="string"==typeof o?e.machine.sources.actors[o]:o;if(!a)throw new Error(i(15,"string"==typeof o?o:"inline"));const u="function"==typeof t.input?t.input({self:s.self,context:v.context,event:n,input:x[r.id],output:zs(n)}):t.input;Tt(s,t.id);const h=s.system.createActorRef(a,{...t,src:"string"==typeof o?o:void 0,input:u,parent:s.self,syncSnapshot:!!t.onSnapshot});h._invoked=!0,c.push({action:H["@xstate.spawn"],args:[h]}),t.id&&(d={...d,[t.id]:h})}f&&(v=Ms(v,{children:d}));let l=v.context,g=!1;const m=x[r.id];if(r.entry){const[t,e,s,n]=y(r.entry,l,d,m,"entry",r);c.push(...t),s?.length&&o.push(...s),e&&(l=e,g=!0),n&&(v=Ms(v,{children:n}))}if(g&&(v=Ms(v,{context:l})),h.has(r)){const t=[r.initial,...p.get(r)??[]].filter(Boolean);for(const e of t){const{actions:t,context:r,input:i,internalEvents:a}=as(e,v,n,s);if(t&&c.push(...t),a?.length&&o.push(...a),void 0!==r&&(v=Ms(v,{context:vt(v.context,r)})),i&&e.target)for(const t of e.target)x[t.id]=i,w=!0}}const[_,b]=Wt(v,0,s,c);if(v=_,c.length=0,a.push(...b),"final"!==r.type)continue;const I=r.parent;let E="parallel"===I?.type?I:I?.parent,A=E||r;for("compound"===I?.type&&o.push(O(I.id,void 0!==r.output?Ns(r.output,v.context,n,s.self,m):void 0));"parallel"===E?.type&&!S.has(E)&&qe(u,E);){S.add(E);const t={};for(const e of Me(E)){if("final"===e.type){t[e.key]=void 0!==e.output?Ns(e.output,v.context,n,s.self,x[e.id]):void 0;continue}if("parallel"===e.type){const s=o.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);t[e.key]=s?.output;continue}const r=Me(e).find(t=>"final"===t.type&&u.has(t));t[e.key]=void 0!==r?.output?Ns(r.output,v.context,n,s.self,x[r.id]):void 0}o.push(O(E.id,t)),A=E,E=E.parent}E||(v=Ms(v,{status:"done",output:t(A)}))}w&&(v=Ms(v,{_stateInputs:x}))},[I,E]=Wt(v,0,s,x);v=I,a.push(...E),_&&_!==e.context&&(v=Ms(v,{context:_}));const A=v.machine._microstepHooks?.transitionContent?.(f,[...u]);if(A){const t=f[0].source,[e,n,r,i]=y(A,v.context,v.children,Oe(v,t.id),"transition",t);r?.length&&o.push(...r),(n||i)&&(v=Ms(v,{...n?{context:n}:{},...i?{children:i}:{}}));const[c,u]=Wt(v,0,s,e);v=c,a.push(...u)}(r||p)&&S();const k=[...u];if("done"===v.status){const t=[];k.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=Oe(v,e.id),[n,r,i,c]=y(e.exit,v.context,v.children,s,"exit",e);(r||c)&&(v=Ms(v,{...r?{context:r}:{},...c?{children:c}:{}})),t.push(...n),i?.length&&o.push(...i)}});const[e,r]=Wt(v,0,s,t);v=e,a.push(...r);const[i,c]=ps(v,n,s);v=i,a.push(...c);const[u,d]=ys(v,n,s);v=u,a.push(...d)}return d===e.historyValue&&e.nodes.length===u.size&&e.nodes.every(t=>u.has(t))?v.context!==h?[v===e?Ms(v):v,a,b]:[v,a,b]:[Ms(v,{_nodes:k,historyValue:d}),a,b]}}function as(t,e,s,n,r){let o;const i=()=>o??=le(n)?ye({context:e.context,event:s,output:zs(s),value:e.value,children:e.children,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:Oe(e,t.source.id)},n):{context:e.context,event:s,output:zs(s),value:e.value,children:e.children,system:n.system,parent:n.self._parent,self:n.self,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:Oe(e,t.source.id)};if(t.to){const o=[],c=[];let a;if(!r?.selectionResult?.reusable||!1!==r.resolveActions&&0!==r.selectionResult.operations.length){const e=Rt(n,o,c,!0,r?.resolveActions??!0),u=!1===r?.resolveActions?D(pe(n),"suppress"):void 0;try{if(r?.selectionResult?.reusable){a=r.selectionResult.result;for(const t of r.selectionResult.operations)t(e)}else a=t.to(i(),e),fs(a,s,t.source.id)}finally{u?.close(),$t(e)}}else a=r.selectionResult.result;const u=a?.target?Ue(t.source,Ls(a.target)):void 0,d=a?.input??("function"==typeof t.input?t.input({context:e.context,event:s,output:zs(s)}):t.input);return{targets:u,context:a?.context,reenter:a?.reenter,actions:o,internalEvents:c,input:d}}const c="function"==typeof t.input?t.input({context:e.context,event:s,output:zs(s)}):t.input,a="function"==typeof t.context?t.context(i()):t.context;return{targets:t.target,context:a,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:c}}class us extends Error{constructor(t,e,s,n){super(i(16,t,e.type,s)),this.actorId=void 0,this.event=void 0,this.maxIterations=void 0,this.states=void 0,this.name="InfiniteTransitionError",this.actorId=t,this.event=e,this.maxIterations=s,this.states=n.slice()}}function ds(t,e,s,n,r=[]){if("active"!==t.status&&!r.length)return{snapshot:t,microsteps:[[t,[],[]]]};let o=t;const i=r.slice();let c=!1;function h(t){if("xstate.done.actor"!==t.type&&"xstate.error.actor"!==t.type)return;const{actorId:e,sessionId:n}=t;if(!e)return;const r=o.children[e];if(!r)return;if(void 0!==r.sessionId&&r.sessionId!==n)return;const c={...o.children};if(delete c[e],s.system._unregister(r),o=Ms(o,{children:c}),i.length){const[,t,e]=i.at(-1);i[i.length-1]=[o,t,e]}else i.push([o,[],[]])}function l(){if(c&&o===t&&(o=Ms(t,{}),i.at(-1)?.[0]===t)){const[,t,e]=i.at(-1);i[i.length-1]=[o,t,e]}const e=function(t){const e=[],s=[];for(const n of t){if(!Ct(n)||n.type!==u)continue;const{actor:t,logic:r}=n,o=Kt(t);r===tt||r===st?e.push(o):s.push(o)}return[...e,...s]}(i.flatMap(([,t])=>t)),n=("active"===t.status||r.length>0)&&("done"===o.status||"error"===o.status);if(e.length||n){const t=n?[...e,zt(s,o)]:e;if(i.length){const[e,s,n]=i.at(-1);i[i.length-1]=[e,[...s,...t],n]}else i.push([o,t,[]])}return{snapshot:o,microsteps:i}}function p(t,n){if(n=t[2]??n,!ge(s)&&(e.type===a||(s.system._hasInspectionObservers?.()??1))){const t=s.self._collectedMicrosteps||[];t.push(...n),s.self._collectedMicrosteps=t}i.push([t[0],t[1],n])}if(e.type===d){const[t,n]=ps(o,e,s),[r,i]=ys(t,e,s);return o=Ms(r,{status:"stopped"}),p([o,[...n,...i]],[]),l()}let y=e;if(e.type===f){const t=N(e),r=t?o.timers.findIndex(e=>z(e,t)):-1;if(-1===r)return l();const i=o.timers[r],c=o.timers.filter((t,e)=>e!==r);if(o=Ms(o,{timers:c}),"@xstate.raise"===i.type)n.push(i.event),p([o,[]],[]);else{const t="self"===i.target?s.self:i.target;p([o,[Nt(s,t,i.event)]],[])}}if(y.type!==a&&y.type!==f){const e=y,r=function(t){return t.type.startsWith("xstate.error.")}(e),i=new Map,a=o.machine.getTransitionData(o,e,s,i);if(r&&!a.length)return"xstate.error.actor"!==e.type||Ke(e,o,e.actorId)?(o=Ms(t,{status:"error",error:e.error}),p([o,[]],[]),h(e),l()):l();c=a.length>0;const u=cs(a,t,s,y,!1,n,i);o=u[0],p(u,a),h(e)}if(!n.length&&!1===t.machine._hasEventlessTransitions)return l();let v=!0;const g=t.machine.options?.maxIterations??1/0;let m=0;const _=[];for(;"active"===o.status;){if(m++,m>g)throw new us(s.self?.id,e,g,_);let t;_.push(o.value),_.length>5&&_.shift();let r=v?vs(o,y,s):[];const i=r.length?o:void 0,c=o.machine._microstepHooks?.drain(s.self);if(c?.length&&n.push(...c),!r.length){if(!n.length)break;y=n.shift(),t=new Map,r=o.machine.getTransitionData(o,y,s,t)}const a=cs(r,o,s,y,!1,n,t);o=a[0],v=o!==i,p(a,r),h(y)}return l()}function hs(t,e,s,n,r){return!!t.to&&ls(t.to,e,s,n,r,n.machine.sources,t.source.id).enabled}function fs(t,e,s,n){if(t&&"function"==typeof t.then)throw Promise.resolve(t).catch(()=>{}),new Error(i(17,n??"transition",s,e.type))}function ls(t,e,s,n,r,o,i){let c;const a=function(t){const e=D(t),{frame:s}=e,n=[];let r=!1;const o=t=>{r||n.push(t)},i=()=>{if(!r)throw s.requiresReevaluation=!0,q},c=Ut({cancel:(...t)=>o(e=>e.cancel(...t)),emit:(...t)=>o(e=>e.emit(...t)),log:(...t)=>o(e=>e.log(...t)),raise:(t,e)=>{r||(Mt(t),o(s=>s.raise(t,e)))},sendTo:(...t)=>o(e=>e.sendTo(...t)),stop:(...t)=>o(e=>e.stop(...t)),spawn:i,listen:i,subscribeTo:i},(...t)=>o(e=>e(...t)));return{frame:s,enqueue:c,operations:n,close(){r=!0,e.close()}}}(pe(r));try{c=t(ye({context:e,event:s,output:zs(s),value:n.value,children:n.children,actions:o.actions,actors:o.actors,guards:o.guards,delays:o.delays,input:Oe(n,i)},r),a.enqueue)}catch(t){if(t===q)return{enabled:!0,result:void 0,reusable:!1};throw t}finally{a.close()}return fs(c,s,i),a.frame.requiresReevaluation?{enabled:!0,result:void 0,reusable:!1}:{enabled:void 0!==c||a.operations.length>0,result:c,reusable:!0,operations:a.operations}}function ps(t,e,s){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return[t,[]];const r=[],o=Rt(s,r,[]);for(const t of n)o.stop(t);return Wt(t,0,s,r)}function ys(t,e,s){if(!t.timers.length)return[t,[]];const n=[],r=Rt(s,n,[]);for(const e of t.timers)r.cancel(L(e));return Wt(t,0,s,n)}function vs(t,e,s){t.machine._microstepHooks?.begin(s.self);const n=new Set,r=t.nodes.filter(je);for(const o of r)t:for(let r=o;r;r=r.parent)if(r.always)for(const o of r.always)if(gs(o,e,t,r,s)){n.add(o);break t}return es(Array.from(n),new Set(t.nodes),t,ss(t,e,s,!1))}function gs(t,e,s,n,r,o){if(t.matches&&!function(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}(e,t.matches))return!1;if(t._eventMatcher&&!t._eventMatcher(e,s))return!1;if(t.guard){const o=function(t,e){if(!le(e)){const s=e.self;return Object.assign(t,{self:s,parent:s._parent})}return Object.defineProperties(t,{self:{enumerable:!0,get:()=>e.self},parent:{enumerable:!0,get:()=>pe(e)}}),t}({context:s.context,event:e,output:zs(e),children:s.children,actions:n.machine.sources.actions,actors:n.machine.sources.actors,guards:n.machine.sources.guards,delays:n.machine.sources.delays,_snapshot:s},r);if(!t.guard(o))return!1}if(t.to){const i=ls(t.to,s.context,e,s,r,n.machine.sources,t.source.id);return o?.set(t,i),i.enabled}return!0}const ms=Object.freeze({}),_s=Object.freeze([]);function xs(t){return t?.length?t:_s}function ws(t){return t===ms||t&&Object.keys(t).length?t:ms}function bs(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const Ss=function(t){if("string"==typeof t&&De(t)){const e=this.machine.getStateNodeById(t);return this.nodes.includes(e)}return $s(t,this.value)},Is=function(t){return this.tags.has(t)},Es=function(t){return this.machine?._canTransition(this,t)??!1},As=function(){const{nodes:t,_stateInputs:e,_nextTimerId:s,_nextActorIds:n,tags:r,machine:o,getMeta:i,getInputs:c,toJSON:a,can:u,hasTag:d,matches:h,...f}=this;return{...f,tags:Array.from(r)}},ks=function(){const t={};for(const e of this.nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},Ts=function(){return this._stateInputs};function Os(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function js(t,e,s){const n={status:t.status,output:t.output,error:t.error,machine:e,context:t.context,nodes:t._nodes,value:t.value??$e(e.root,t._nodes),tags:Os(t._nodes),children:ws(t.children),timers:xs(t.timers),historyValue:ws(t.historyValue),_stateInputs:ws(t._stateInputs),_nextTimerId:t._nextTimerId??0,_nextActorIds:t._nextActorIds,matches:Ss,hasTag:Is,can:Es,getMeta:ks,getInputs:Ts,toJSON:As};return s&&he(n,s),n}function Ms(t,e={}){const s={...t,...e};if((e._nodes??t.nodes)===t.nodes){const e={status:s.status,output:s.output,error:s.error,machine:t.machine,context:s.context,nodes:t.nodes,value:t.value,tags:t.tags,children:ws(s.children),timers:xs(s.timers),historyValue:ws(s.historyValue),_stateInputs:ws(s._stateInputs),_nextTimerId:s._nextTimerId??0,_nextActorIds:s._nextActorIds,matches:Ss,hasTag:Is,can:Es,getMeta:ks,getInputs:Ts,toJSON:As};return de(t,e),e}const n=js({...s,value:void 0},t.machine);return de(t,n),n}function Rs(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 Ps(t,e,s="context",n=[]){let r;n.push(t);for(const o in t){const c=t[o];if(c&&"object"==typeof c)if(Js(c))r??=Array.isArray(t)?t.slice():{...t},r[o]={"@actor":c.address};else{const a=Array.isArray(t)?`${s}[${o}]`:`${s}.${o}`;if(n.includes(c))throw new Error(i(44,e(),a));const u=Ps(c,e,a,n);u!==c&&(r??=Array.isArray(t)?t.slice():{...t},r[o]=u)}}return n.pop(),r??t}function $s(t,e){const s=Ds(t),n=Ds(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&$s(s[t],n[t]))}function qs(t){if(Vs(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+="."===t[n+1]?"\\.":t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function Ds(t){if(bs(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}(qs(t))}function Ks(t){return Vs(t)?t:[t]}function Ls(t){return void 0===t?[]:Ks(t)}function Ns(t,e,s,n,r){if("function"==typeof t){return t({context:e,event:s,output:zs(s),self:n,input:r})}return t}function zs(t){if(function(t){return"xstate.done.actor"===t.type||"xstate.done.state"===t.type}(t)){return t.output}}function Vs(t){return Array.isArray(t)}function Cs(t,e,s){return Ks(t).map(t=>{if("string"==typeof t)throw new Error(i(38,e,s,t));return void 0===t?{target:void 0}:"function"==typeof t?{to:t}:t})}function Ws(t){if(void 0!==t&&""!==t)return Ls(t)}function Us(t,e,s){const n="object"==typeof t,r=n?t:void 0;return{next:(n?t.next:t)?.bind(r),error:(n?t.error:e)?.bind(r),complete:(n?t.complete:s)?.bind(r),...n&&t.passive?{passive:!0}:{}}}function Js(t){return"sessionId"in t&&"send"in t&&"ref"in t}function Hs(t,e,s){const n=[];for(const t of e)for(const e of t.invoke)e.id===s&&n.push(e);if(1!==n.length)throw new Error(i(39,s));const r=n[0].logic;if("string"==typeof r){const e=t.sources.actors[r];if(!e)throw new Error(i(29,s,r));return e}if("function"==typeof r)throw new Error(i(40,s));return r}function Bs(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],r=n[t];if("*"===e){return t===s.length-1}if(e!==r)return!1}return!0}let Fs,Xs,Gs=0;function Qs(){return Fs??=function(){let t;try{t=globalThis.crypto}catch{}if(t?.getRandomValues)try{const e=new Uint32Array(4);return t.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(7,"0")).join("")}catch{}if(t?.randomUUID)try{return t.randomUUID().replaceAll("-","")}catch{}return`xstate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}(),`${Fs}:${(Gs++).toString(36)}`}function Ys(t,e){if(!t)return e();const s=Xs;Xs=t;try{return e()}finally{Xs=s}}function Zs(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length?e:"x"}function tn(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function en(t){const e=t.lastIndexOf(":");if(e<=0||e===t.length-1)return;const s=Number(t.slice(e+1));return Number.isSafeInteger(s)&&s>=0?{prefix:t.slice(0,e),index:s}:void 0}function sn(t,e){return`${t?t.address:""}|${e}`}function nn(t,e,s){const n=t._snapshot._nextActorIds;(n[e]??0)>=s||(t._snapshot._nextActorIds={...n,[e]:s},re(t))}const rn=["spawnActor","startActor","stopActor","terminateActor","emitEvent","scheduleTimer","cancelTimer","cancelAllTimers","deadLetter"],on=Object.freeze({});function cn(t,e){return V(t,e)}function an(t,e){return t.getSnapshot()?.timers?.find(t=>z(t,e))}class un{get children(){const t=this._children??=new Map;return this._getRootActor()&&t.set(this._rootActor.sessionId,this._rootActor),t}set children(t){this._children=t}_getRootActor(){return this._rootActor._isRunning()?this._rootActor:void 0}_peekChildren(){return this._children}get keyedActors(){return this._keyedActors??=new Map}set keyedActors(t){this._keyedActors=t}get reverseKeyedActors(){return this._reverseKeyedActors??=new WeakMap}set reverseKeyedActors(t){this._reverseKeyedActors=t}_peekKeyedActors(){return this._keyedActors}constructor(t,e){this._rootActor=t,this._identity=Xs??{executionId:Qs(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0,this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef;const s=Xt();s&&this.inspect(s),this._snapshot={_scheduledTimers:on,_nextActorIds:{}}}_recordSent(t,e,s,n,r){if(!this._inspectionObservers?.size||!t)return;const o=t;if(!o._inTransition)return;(o._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:r})}schedule(t,e,s){const n=cn(t,e);void 0!==this._timerMap?.[n]&&this.cancel(t,e);const r=an(t,e);if(r){const e="self"===r.target?t:r.target;this._recordSent(t,e,r.event,s,r.id)}const o=this._clock.now?.()??Date.now(),i={source:t,delay:s,key:e,scheduledAt:o,dueAt:o+s};this._snapshot._scheduledTimers===on&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[n]=i,re(this);const c=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[n],delete this._snapshot._scheduledTimers[n],re(this),this._deliver(t,t,{type:f,...e})},s);(this._timerMap??={})[n]=c}cancel(t,e){const s=cn(t,e),n=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==on&&delete this._snapshot._scheduledTimers[s],re(this),void 0!==n&&this._clock.clearTimeout(n)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.key)}}_deliver(t,e,s){I(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),re(this),t}_getByAddress(t){const e=this._getRootActor();if(e?.address===t)return e;for(const e of this._children?.values()??[])if(e.address===t&&e._isRunning())return e}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1);const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&re(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,e){const s=this._keyedActors?.get(t);if(s&&s!==e)throw new Error(i(45,String(t)));(this._keyedActors??=new Map).set(t,e),(this._reverseKeyedActors??=new WeakMap).set(e,t),s!==e&&re(this)}inspect(t){const e=Us(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}onRejectedEvent(t){const e=e=>t(e);return(this._rejectionListeners??=new Set).add(e),{unsubscribe:()=>{this._rejectionListeners?.delete(e)}}}onEmitted(t){const e=e=>t(e);return(this._emissionListeners??=new Set).add(e),{unsubscribe:()=>{this._emissionListeners?.delete(e)}}}_notifyEmitted(t,e){const s=this._emissionListeners;if(!s?.size)return;const n={actorRef:t,event:e};for(const t of Array.from(s))try{t(n)}catch(t){R(t)}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>{try{t.next?.(e)}catch(t){R(t)}})}spawnActor(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);!function(t){t._stop()}(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);!function(t,e){t._terminate(e)}(t,e)}sendEvent(t,e,s){if(y(e)){const n=m(this,e);if(n)e=n;else if(this._getByAddress(e["@actor"])||!this.runtime?.sendEvent)return this.deadLetter(t,void 0,s,"missingTarget",{targetId:v(e["@actor"]),error:g(e)})}if(E(t,e,s))return;this._recordSent(t,e,s);const n=this.runtime?.sendEvent;if(n)return n(t,e,s);this._deliver(t,e,s)}emitEvent(t,e){const s=this.runtime?.emitEvent;if(s)return s(t,e);t._emit(e)}deadLetter(t,e,s,n,r){const o=this._rejectionListeners;if(o?.size){const i={event:s,targetRef:e,targetId:e?.id??r?.targetId,sourceRef:t,eventOrigin:t?"actor":"external",reason:n,issues:r?.issues,error:r?.error};for(const t of[...o])try{t(i)}catch(t){R(t)}}const i=this.runtime?.deadLetter;if(i)return i(t,e,s,n,r)}runStep(t,e,s){const n=this.runtime?.runStep;return n?n(t,e,s):S(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const n=this.runtime?.scheduleTimer;if(n){const r=an(t,e);if(r){const e="self"===r.target?t:r.target;this._recordSent(t,e,r.event,s,r.id)}return n(t,e,s)}this.schedule(t,e,s)}cancelTimer(t,e){const s=this.runtime?.cancelTimer;if(s)return s(t,e);this.cancel(t,e)}cancelAllTimers(t){const e=this.runtime?.cancelAllTimers;if(e)return e(t);this.cancelAll(t)}_relay(t,e,s){if(!function(t){let e=!1,s=!1;for(const n of $)n.parent===t&&(n.requiresReevaluation=!0,e=!0,s||="abort"===n.mode);if(s)throw q;return e}(e))return this.sendEvent(t,e,s)}getSnapshot(){return{_scheduledTimers:{...this._snapshot._scheduledTimers}}}start(){const t=this._snapshot._scheduledTimers;let e=!0;for(const s in t){e&&(this._snapshot._scheduledTimers={},e=!1);const{source:n,dueAt:r,key:o}=t[s];this.scheduleTimer(n,o,Math.max(0,r-(this._clock.now?.()??Date.now())))}}}let dn=!1;const hn=Object.freeze([]),fn={"xstate.done.actor":!0,"xstate.error.actor":!0,"xstate.error.execution":!0,"xstate.snapshot.actor":!0,"xstate.done.state":!0,"xstate.after":!0,"xstate.timeout.state":!0,"xstate.timeout.actor":!0,[f]:!0};let ln=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const pn=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function yn(t,e){try{t?.(e)}catch(t){R(t)}}function vn(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function gn(t,e){return new mn(t,e)}class mn{get address(){return this._address??=this._parent?`${this._parent.address}/${tn(this.id)}`:tn(this.id)}get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this._errorObserved=!1,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=ln.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,this._inTransition=!1,this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this._address=void 0,this.system=void 0,this._trigger=void 0,this._boundSend=void 0,this.src=void 0,this._deferred=void 0,this._restored=!1,this._warnedUnhandledTypes=void 0;const s=e?{...pn,...e}:pn,{clock:n,logger:r,parent:o,syncSnapshot:i,id:c,registryKey:a,inspect:u}=s;var d;this.system=o?o.system:s._systemRef?.current??function(t,e){return new un(t,e)}(this,{clock:n,logger:r,createActorRef:gn}),o||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system,s._systemRef.initialize?.()),u&&!o&&this.system.inspect(Us(u)),s.onRejectedEvent&&!o&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(d=this.system)._identity.executionId}:${d._identity.nextSessionId++}`,this.id=function(t,e,s){if(void 0!==e){const n=en(e);return n?nn(t,sn(s?.parent,n.prefix),n.index+1):s?.parent||nn(t,sn(void 0,e),1),e}const n=Zs(s?.src),r=sn(s?.parent,n),o=t._snapshot._nextActorIds[r]??0;return nn(t,r,o+1),s?.parent||"x"===n||0!==o?`${n}:${o}`:n}(this.system,c,{parent:o,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=o,this._syncSnapshot=i,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope=this,a&&(this.registryKey=a,this.system._set(a,this)),this._collectedMicrosteps=void 0;const h=s._restore;this._restored=void 0!==h;try{if(h)this._setSnapshot(h.restore(this._actorScope));else if(e?._inert);else{this._inTransition=!0;try{const[t,e]=Vt(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}finally{this._inTransition=!1}}}catch(t){this._setSnapshot(h?.error?.(t)??{status:"error",output:void 0,error:t}),this._deferred&&(this._deferred.length=0)}a&&"active"!==this._snapshot.status&&this.system._unregister(this),(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_getLogger(){return this.logger}get self(){return this}get defer(){const t=t=>this._defer(t);return Object.defineProperty(this,"defer",{value:t}),t}get stopChild(){const t=t=>this._stopChild(t);return Object.defineProperty(this,"stopChild",{value:t}),t}get emit(){const t=t=>w(this,t,this.system);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===ln.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(i(47,t.id,this.id));t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=dn;try{dn=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==ln.Stopped&&this._recoverOrError(t)})}finally{dn=e}};this._processingStatus!==ln.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,he(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e,s){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t,s),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;const n=this._inTransition;this._inTransition=!0;try{const[t,n]=Vt(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),vn(n,this._actorScope),this.update(t,s),!0}catch{return!1}finally{this._inTransition=n}}_next(t){for(const e of this.observers??hn)yn(e.next,t)}update(t,e){this._setSnapshot(t);const s=this._deferred;for(let e=0;e<(s?.length??0);e++){const n=s[e];try{n()}catch(e){if(s.length=0,this._tryHandleExecutionError(e,t))return;this._setErrorSnapshot(e,t),this._error(e);break}}if(s&&(s.length=0),"active"===this._snapshot.status)this._next(t);this._inspectTransition(this._snapshot,e)}_inspectTransition(t,e){(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps??hn,actions:this._collectedActions??hn,sent:this._collectedSent??hn,eventType:e.type}),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0}_flushInitialEffects(){if(!this._initialEffects?.length)return!0;this._forceDeferredActions=!0;try{return vn(this._initialEffects,this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred&&(this._deferred.length=0),this._recoverOrError(t),"active"===this._snapshot.status}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const n=Us(t,e,s);if(this._processingStatus!==ln.Stopped)(this.observers??=new Set).add(n);else switch(this._snapshot.status){case"done":yn(n.complete);break;case"error":{const t=this._snapshot.error;n.error?(n.passive||(this._errorObserved=!0),yn(n.error,t)):R(t);break}}return{unsubscribe:()=>{this.observers?.delete(n)}}}on(t,e){let s=this.eventListeners?.get(t);return s||(s=new Set,(this.eventListeners??=new Map).set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,r)=>{const o=Us(s,n,r);let i=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(i,n)||(i=n,o.next?.(n))},error:o.error,complete:o.complete})},get:()=>t(this.getSnapshot())}}start(){const t=this._inTransition;this._inTransition=!0;try{return this._start()}finally{this._inTransition=t}}_start(){if(this._processingStatus===ln.Running)return this;if(this._processingStatus===ln.Stopped){const t=this._snapshot.status;if("done"===t||"error"===t)return this;throw new Error(i(48,this.id))}this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=ln.Running,this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this._restored?(this._next(this._snapshot),this._stopProcedure(),this._complete(),this):this._flushInitialEffects()?(this.update(this._snapshot,M(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this;case"stopped":return this._stopProcedure(),this._complete(),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,M(this.options.input)):(function(t,e,s){const n=te.get(t),r=oe(s);return n?.actor===e&&n.systemState.sourceSystem===s&&n.systemState.sourceVersion+1===r&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(n.systemState.root=e,n.systemState.sourceVersion=r,!0)}(this._snapshot,this,this.system)||this._setSnapshot(this._snapshot),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0),this._restored){const t=this._snapshot.timers??[],e=!this.system._clock.now,s=Date.now();for(const n of t){const t=e&&void 0!==n.scheduledAt?Math.min(n.delay,Math.max(0,n.scheduledAt+n.delay-s)):n.delay;this.system.scheduleTimer(this,L(n),t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){const e=this._inTransition;this._inTransition=!0;try{this._processEvent(t)}finally{this._inTransition=e}}_processEvent({event:t,sourceRef:e}){this._lastSourceRef=e;const s=this._snapshot;let n,r;try{n=Vt(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){r={err:t}}if(r)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(r.err)||this._inspectTransition(this._snapshot,t));if(!n)return;let o=this._snapshot;try{const[r,i]=n;r!==s||i.length||!("machine"in s)||t.type===d||e&&Object.hasOwn(fn,t.type)||this._reportUnhandledEvent(t),o=r,this._setSnapshot(o),vn(i,this._actorScope),this.update(o,t)}catch(e){return void(this._recoverOrError(e,o,s)||this._inspectTransition(this._snapshot,t))}t.type===d&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){yn(()=>this.options.onUnhandledEvent?.(t,this._snapshot))}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)yn(s,t)}_terminate(t){if("done"===t.status)return this._next(this._snapshot),this._stopProcedure(),this._complete(),void(this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t.output,n=this.sessionId,{type:"xstate.done.actor",output:s,actorId:e,sessionId:n})));var e,s,n;"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===ln.Stopped?this:(this.mailbox?.clear(),this._processingStatus===ln.NotStarted?(this._processingStatus=ln.Stopped,this.system._unregister(this),this):(this._send({type:d}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error(i(49,this.id));return this._stop()}_complete(){for(const t of this.observers??hn)yn(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||R(t)})}_error(t,e){this._stopProcedure();const s=new Set;for(const t of[this._snapshot,e]){const e=t?.children;for(const t of Object.values(e??{}))t?._parent===this&&"function"==typeof t.getSnapshot&&s.add(t)}for(const t of this.system._peekChildren?.()?.values()??[])t._parent===this&&s.add(t);for(const t of s)try{if("active"!==t.getSnapshot().status)continue;const e=this.system.stopActor(t);e&&Promise.resolve(e).catch(R)}catch(r){R(r)}if(this.observers?.size){let e=!1,s=!1;for(const n of this.observers){const r=n.error;n.passive||(e||=!r,s||=!!r),yn(r,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);var n,r,o;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(n=this.id,r=t,o=this.sessionId,{type:"xstate.error.actor",error:r,actorId:n,sessionId:o}))}_stopProcedure(){this._processingStatus===ln.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=ln.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===ln.Stopped)return void this.system.deadLetter(e,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new A(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue({event:t,sourceRef:e})}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{"@actor":this.address}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[P](){return this}getSnapshot(){return this._snapshot}}function _n(t,...[e]){return function(t){if(t&&"object"==typeof t)for(const e of Object.keys(t))if(!c.has(e))throw new Error(i(8,e))}(e),new mn(t,e)}class xn extends Error{constructor(t){super(t),this.name="InvalidSnapshotError"}}function wn(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function bn(t){return wn(t)&&"function"==typeof t.transition&&"function"==typeof t.getInitialSnapshot}function Sn(t,e,s,n){if("string"==typeof e){if(!s.states[e])throw new xn(i(21,n.concat(e).join(".")));return}const r=t=>new xn(i(22===t?22:23,n.join(".")));if(!e||"object"!=typeof e||Array.isArray(e))throw r(22);const o=Object.keys(e);if(o.length>1&&"parallel"!==s.type)throw r(23);for(const r of o){const o=s.states[r];if(!o)throw new xn(i(21,n.concat(r).join(".")));Sn(t,e[r],o,n.concat(r))}}function In(t,e){if(!wn(e))throw new xn(i(24,t.id));if(void 0===e.value)throw new xn(i(25,t.id));Sn(t,e.value,t.root,[]);const s=Array.from(Pe(Ge(t.root,e.value)));if(!wn(e.children))throw new xn(i(26));const n=new Map;for(const[r,o]of Object.entries(e.children)){if(!wn(o)||void 0!==o.remote&&"boolean"!=typeof o.remote||void 0!==o.address&&"string"!=typeof o.address||void 0!==o.syncSnapshot&&"boolean"!=typeof o.syncSnapshot||void 0!==o.registryKey&&"string"!=typeof o.registryKey||void 0!==o.incarnation&&"string"!=typeof o.incarnation||void 0!==o.snapshot&&!wn(o.snapshot))throw new xn(i(27,r));if(!0!==o.remote){if(void 0!==o.src&&"string"!=typeof o.src&&!bn(o.src))throw new xn(i(27,r));try{const e=void 0===o.src?Hs(t,s,r):"string"==typeof o.src?Object.hasOwn(t.sources.actors,o.src)?t.sources.actors[o.src]:void 0:o.src;if(!e)throw new xn(i(29,r,"string"==typeof o.src?o.src:"<inline>"));n.set(r,e)}catch(t){if(t instanceof xn)throw t;throw new xn(t instanceof Error?t.message:i(30,r))}}else if("string"!=typeof o.address||"string"!=typeof o.src)throw new xn(i(28,r))}if(void 0!==e.timers&&!Array.isArray(e.timers))throw new xn(i(31));for(const t of e.timers??[]){if(!wn(t)||"number"!=typeof t.delay||"@xstate.raise"!==t.type&&"@xstate.sendTo"!==t.type||!wn(t.event)||"string"!=typeof t.event.type||void 0!==t.id&&"string"!=typeof t.id||void 0!==t.seq&&"number"!=typeof t.seq||void 0!==t.scheduledAt&&"number"!=typeof t.scheduledAt||!("string"==typeof t.target||wn(t.target)&&"parent"===t.target.type||y(t.target)))throw new xn(i(32));if("string"==typeof t.target&&"self"!==t.target&&!Object.hasOwn(e.children,t.target))throw new xn(i(33,t.target))}return{nodes:s,childLogics:n}}const En=new WeakMap;const An={};class kn{constructor(t,e){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.schemas=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.invoke=void 0,this.on=void 0,this.after=void 0,this.events=void 0,this.ownEvents=void 0,this._candidateCache=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.parent&&function(t){for(let e=0;e<t.length;e++)if("\\"===t[e])e++;else if("."===t[e])return!0;return!1}(this.key))throw new Error(i(57,this.key));this.path=this.parent?this.parent.path.concat(this.key):[];const s=this.config.states?Object.keys(this.config.states)[0]:void 0;this.id=this.config.id||(this.machine.id?[this.machine.id,...this.path]:this.path).join("."),this.type=this.config.type||(void 0!==s?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.schemas=this.config.schemas,function(t){const e=t.config;if("history"===t.type&&!("string"==typeof e.target&&e.target.trim().length>0||Array.isArray(e.target)&&e.target.length>0&&e.target.every(t=>"string"==typeof t&&t.trim().length>0)))throw new Error(i(60,t.id));if("choice"!==t.type)return;if("function"!=typeof e.choice)throw new Error(i(61,t.id))}(this);if(this.machine.idMap.get(this.id))throw new Error(i(58,this.id));if(this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const s={},n=Object.keys(t);for(let r=0;r<n.length;r++){const o=n[r],i=e(t[o],o,t,r);"__proto__"===o?Object.defineProperty(s,o,{value:i,enumerable:!0,configurable:!0,writable:!0}):s[o]=i}return s}(this.config.states,(t,e)=>new kn(t,{_parent:this,_key:e,_machine:this.machine})):An,"compound"===this.type&&!this.config.initial)throw new Error(i(59,this.id));this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=Ls(t.tags).slice(),this.invoke=Ls(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,r=`${this.id}:${e}`;const o=t.id??r;return{...t,src:"string"==typeof s?s:void 0,logic:s,id:o,registryKey:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,r=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===r.length)return[];const o=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;o.push({event:k(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0,name:`after.${s}`})}var i;void 0!==s&&n&&o.push({event:(i=t.id,{type:"xstate.timeout.state",stateId:i}),delay:s,transitions:n,fromDelaysMap:!0,name:"onTimeout"});for(const t of r)o.push({event:T(t.id),resolveEvent:({children:e})=>T(t.id,e[t.id]?.sessionId),eventMatcher:(e,s)=>Ke(e,s,t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1,name:"invoke.onTimeout"});const c=[];for(const{event:e,resolveEvent:s,eventMatcher:n,delay:r,transitions:i,fromDelaysMap:a,name:u}of o){Le(t,e,s??(()=>e),e=>Te(r,a?e.delays:{},{context:e.context,event:e.event,stateNode:t,input:e.input}));const{type:o,...d}=e;for(const e of Cs(i,u,t.id))c.push({...e,matches:{...e.matches,...Object.fromEntries(Object.entries(d).filter(([,t])=>void 0!==t))},event:o,delay:r,_eventMatcher:n})}return c.map(e=>({...Ne(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map,s=(t,s)=>{e.set(t,[...e.get(t)??[],...s])};if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error(i(63,t.id));const n=t.config.on[s];e.set(s,Tn(t,s,n,e=>Ne(t,s,e)))}if(t.config.onDone){const e="xstate.done.state";s(e,Tn(t,"onDone",t.config.onDone,s=>Ne(t,e,{...s,matches:{...s.matches,stateId:t.id}})))}if(t.config.onError){const s="xstate.error.*";e.set(s,Tn(t,"onError",t.config.onError,e=>Ne(t,s,e)))}const n=(e,s,n)=>Ne(t,e,{matches:{actorId:n},_eventMatcher:(t,e)=>Ke(t,e,n),to:(t,e)=>(e.cancel(s),{})}),r=(e,s,n)=>{const{target:r,to:o,reenter:i,...c}=s;return Ne(t,e,{...c,reenter:i,to:(t,e)=>{if(o){let s=!1;const r=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const r=Reflect.get(t,e,n);return"function"!=typeof r?r:(...e)=>(s=!0,r.apply(t,e))}}),i=o(t,r);return(void 0!==i||s)&&e.cancel(n),i}return e.cancel(n),{target:r,reenter:i}}})};for(const e of t.invoke){const o=t=>({...t,matches:{...t.matches,actorId:e.id},_eventMatcher:(t,s)=>Ke(t,s,e.id)}),i=void 0!==e.timeout?{event:{type:"xstate.timeout.actor",actorId:e.id}}:void 0;if(e.onDone){const c="xstate.done.actor",a=Tn(t,"invoke.onDone",e.onDone,e=>{const s=o(e);return i?r(c,s,i):Ne(t,c,s)});i&&a.push(n(c,i,e.id)),s(c,a)}else if(i){const t="xstate.done.actor";s(t,[n(t,i,e.id)])}if(e.onError){const n="xstate.error.actor";s(n,Tn(t,"invoke.onError",e.onError,e=>{const s=o(e);return i?r(n,s,i):Ne(t,n,s)}))}if(e.onSnapshot){const n="xstate.snapshot.actor";s(n,Tn(t,"invoke.onSnapshot",e.onSnapshot,e=>Ne(t,n,o(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(i(62,t.id));return e};return[Ne(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=Tn(this,"always",this.config.always,t=>Ne(this,"",t)));for(const t of Object.keys(this.states))this.states[t]._initialize();this._refreshEventMetadata()}_refreshEventMetadata(){const t={},e=[];for(const[s,n]of this.transitions)t[s]=n.slice(),n.some(t=>t.target||t.reenter||t.to)&&e.push(s);this.on=t,this.ownEvents=e;const s=new Set(e);for(const t of Object.values(this.states))for(const e of t.events)s.add(e);this.events=Array.from(s)}get initial(){return function(t,e,s){let n=En.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},En.set(t,n)),n[e]}(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,r="object"==typeof e&&null!==e?e.to:void 0,o="object"==typeof e&&null!==e?e.meta:void 0,c="object"==typeof e&&null!==e?e.description:void 0,a=Array.isArray(s)?s:s?[s]:[],u=a.map(e=>e.startsWith("#")?t.machine.getStateNodeById(e.slice(1)):t.states[e]);if(u.some(t=>!t))throw new Error(i(64,a.find((t,e)=>!u[e]),t.id));const d={source:t,target:u.length?u:void 0,input:n,to:r,meta:o,description:c};return d}(this,this.config.initial))}next(t,e,s,n){if("final"===this.type)return;let r=this._candidateCache?.get(e.type);r||(r=function(t,e){const s=t.transitions.get(e.type)??[],n=[...t.transitions.keys()].filter(t=>t!==e.type&&Bs(e.type,t)).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return s.length?[...s,...n]:n}(this,e),(this._candidateCache??=new Map).set(e.type,r));for(const o of r){if(gs(o,e,t,this,s,n))return[o]}}}function Tn(t,e,s,n){const r=Cs(s,e,t.id),o=new Array(r.length);for(let t=0;t<r.length;t++)o[t]=n(r[t]);return o}function On(t,e){const s=t.check(e);if(s)throw s}let jn,Mn;function Rn(){if(Mn)return Mn;const t=jn??=_n({transition:t=>[t,[]],initialTransition:()=>[{status:"active",output:void 0,error:void 0},[]],getInitialSnapshot:()=>({status:"active",output:void 0,error:void 0}),getPersistedSnapshot:t=>t});return Mn={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},jt.add(Mn),Mn}class Pn{constructor(t,e,s){if(this.config=t,this.validator=s,this._internalEventType=void 0,this._transitionMetaType=void 0,this._inputType=void 0,this._actionMap=void 0,this._actorMap=void 0,this._stateSchema=void 0,this.version=void 0,this.schemas=void 0,this.sources=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this._raw=()=>this,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._hasEventlessTransitions=void 0,this._microstepHooks=void 0,this._json=void 0,void 0!==t.version&&!t.id)throw new Error(i(18,t.version));this.id=t.id??"",this.sources={actors:t.actors??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...e},this.version=this.config.version,this.schemas=this.config.schemas,this.internalEventDescriptors=Object.keys(this.schemas?.internalEvents??{}),this.options={...this.config.options},this.transition=this.transition.bind(this),this.initialTransition=this.initialTransition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.start=this.start.bind(this),this.root=new kn(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const r=n.config.id,o=n.config.route,i=({event:t})=>t.to===`#${r}`;if("function"==typeof o)return e.push(Ne(t,"xstate.route",{guard:i,to:t=>{const e=o(t);if(e)return{...!0===e?{}:e,target:`#${r}`}}})),void(n.states&&s(n.states));const{guard:c,...a}=o,u={...a,guard:i,target:`#${r}`};e.push(Ne(t,"xstate.route",u))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.root._refreshEventMetadata(),this._hasEventlessTransitions=Array.from(this.idMap.values()).some(t=>!!t.always?.length),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:r}=this.sources,o=new Pn(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...r,...t.delays}},this.validator);return o._json=this._json,o.internalEventDescriptors=this.internalEventDescriptors,o._microstepHooks=this._microstepHooks,o}resolveState(t){const e=(s=this.root,n=t.value,$e(s,Pe(Ge(s,n))));var s,n;const r=Pe(Ge(this.root,e));return js({_nodes:[...r],value:e,context:t.context||{},children:{},status:qe(r,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const n=!s,r=s??Ae(this,t);if(n&&ve(r,t,!1),this.validator){const n=s&&s.self._lastSourceRef,o=n?"actor":"external",i=this.validator.check({kind:"event",logic:this,event:e,eventOrigin:o});if(i)return[t,[it(r,n,e,"invalidEvent",{issues:i.issues,error:i})]]}St(r);const o=this._transitionFast(t,e,r);if(o){n&&ve(r,o,!1);const e=n&&o!==t?me(r,o):this._attachPureActorRef(o,r);return this.validator&&On(this.validator,{kind:"result",logic:this,snapshot:e,effects:[]}),[e,[]]}const{snapshot:i,microsteps:c}=ds(t,e,r,[]);n&&ve(r,i,!1);const a=n?i===t?i:me(r,i):this._attachPureActorRef(i,r),u=this._collectEffects(c);return this.validator&&On(this.validator,{kind:"result",logic:this,snapshot:a,effects:u}),[a,u]}_collectEffects(t){return t.flatMap(([,t])=>t)}_attachPureActorRef(t,e,s=!1){return ge(e)||s&&e.self._actorScope===e&&void 0===e.self._snapshot||he(t,e.self,e.system),t}_transitionFast(t,e,s){if("active"!==t.status||"string"!=typeof t.value||this.root.always?.length)return;const n=this.root.states[t.value];if(!n||"atomic"!==n.type||n.exit||n.invoke.length||n.always?.length||n.after?.length)return;const r=n.transitions.get(e.type);if(1!==r?.length)return;const o=r[0];if(o.guard||o.actions||o.to||o.reenter||o.input||"function"==typeof o.context||o.target&&1!==o.target.length)return;const i=o.target?.[0]??n,c=i!==n;if(i.parent!==this.root||"atomic"!==i.type||c&&(i.entry||i.invoke.length||i.always?.length||i.after?.length))return;const a=void 0!==o.context?{...t.context,...o.context}:t.context;if(!ge(s)&&(s.system._hasInspectionObservers?.()??1)){const t=s.self._collectedMicrosteps||[];t.push(o),s.self._collectedMicrosteps=t}const u=t._stateInputs[this.root.id];return Ms(t,{...a!==t.context?{context:a}:{},...c?{_nodes:[this.root,i],_stateInputs:u?{[this.root.id]:u}:{}}:{}})}microstep(t,e,s){const{microsteps:n}=ds(t,e,s,[]),r=new Array(n.length);for(let t=0;t<n.length;t++)r[t]=n[t][0];return r}getTransitionData(t,e,s,n){return this._microstepHooks?.begin(s.self),Qe(this.root,t.value,t,e,s,n)||[]}isInternalEventType(t){if(t===f)return!0;for(const e of this.internalEventDescriptors)if(Bs(t,e))return!0;return!1}_canTransition(t,e){if("active"!==t.status)return!1;const s=Rn(),n=this.getTransitionData(t,e,s);if(!n?.length)return!1;for(const r of n){if(void 0!==r.target)return!0;const n=as(r,t,e,s,{resolveActions:!1});if(n.targets?.length||n.context||hs(r,t.context,e,t,s))return!0}return!1}getExecutionErrorEvent(t,e){if("active"===t?.status&&t.nodes?.some(t=>t.config.onError))return j("execution",e)}_getPreInitialState(t,e){const{context:s}=this.config,n=js({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const r={},o=function(t,e,s){return(n,r)=>{const o=F(e,n),i=r?.id??kt(t,o??n).id;void 0!==r?.id&&(Tt(t,r.id),Ot(t,r.id));const c=t.system.createActorRef(n,{id:i,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:o??n,registryKey:r?.registryKey});return s[c.id]=c,c}}(t,this.sources.actors,r),i=s(function(t,e){return le(e)?(Object.defineProperty(t,"self",{enumerable:!0,get:()=>e.self}),t):Object.assign(t,{self:e.self})}({spawn:o,input:e.input,actors:this.sources.actors},t)),[c]=Wt(n,0,t,[]);if(i&&(c.context=i),Object.keys(r).length>0){c.children={...c.children,...r};const e=function(t){const e=wt.get(t)?.counters;if(e?.size)return Object.fromEntries(e)}(t);e&&(c._nextActorIds=mt(c._nextActorIds,e))}return c}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){this.validator&&On(this.validator,{kind:"input",logic:this,input:t});const s=!e,n=e??Ae(this);St(n);const r=M(t),o=[],i=(t,e)=>{s&&ve(n,t,!1);const r=s?me(n,t):this._attachPureActorRef(t,n,!0),o=this._collectEffects(e);return this.validator&&"error"!==t.status&&On(this.validator,{kind:"result",logic:this,snapshot:r,effects:o}),[r,o]};let c;try{c=this._getPreInitialState(n,r)}catch(t){return i(Ms(js({context:"function"!=typeof this.config.context&&this.config.context?this.config.context:{},_nodes:[this.root],children:{},status:"active"},this),{status:"error",error:t}),[])}const a=Object.values(c.children).filter(Boolean).map(t=>function(t){const e=[t];return{kind:"builtin",exec:at,type:u,source:t._parent,params:void 0,args:e,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}(t));try{const[t,e]=function(t,e,s,n,r){t.machine._microstepHooks?.begin(s.self);const o=[...Be(t)],i=new Set,c=t=>{if("compound"===t.type){i.add(t);for(const e of t.initial.target??[])c(e)}else if("parallel"===t.type)for(const e of Me(t))c(e)};return c(t),cs([{target:o.filter(t=>!o.some(e=>e!==t&&Ye(e,t))),source:t,reenter:!0,eventType:null,toJSON:null,_statesForDefaultEntry:[...i]}],e,s,n,!0,r)}(this.root,c,n,r,o),{snapshot:s,microsteps:u}=ds(t,r,n,o,[[t,[...a,...e]]]);return i(s,u)}catch(t){if(!this.root.config.onError)throw t;const e=ds(c,j("execution",t),n,[],[[c,a]]);return i(e.snapshot,e.microsteps)}}start(t,e){if(!t?.children)return;const s=t.children;for(const t in s){if(!Object.hasOwn(s,t))continue;const n=s[t];n._rehydrated&&"active"===n.getSnapshot?.().status&&(e?e.actionExecutor(Kt(n)):n.system.startActor(n))}}getStateNodeById(t){const e=De(t),s=e?t.slice(1):t;if(""===s&&e)throw new Error(i(19,this.id));const n=this.idMap.get(s);if(n)return n;throw new Error(i(20,s))}getPersistedSnapshot(t,e){return function(t,e){const{nodes:s,_stateInputs:n,_nextTimerId:r,_nextActorIds:o,tags:c,machine:a,children:u,timers:d,context:h,can:f,hasTag:l,matches:v,getMeta:g,getInputs:m,toJSON:_,...x}=t,w={},b=[],S=!1!==e?.embedChildren;for(const t in u){const n=u[t],r="string"==typeof n.src?n.src:void 0,o=void 0===r&&!0===n._invoked&&s.some(e=>e.invoke.some(e=>e.id===t));if(!(void 0!==r||o||e&&"__unsafeAllowInlineActors"in e))throw new Error(i(41,t));const c=S&&!p(n);if(!c&&void 0===r)throw new Error(i(42,t));w[t]={address:n.address,...c?{snapshot:n.getPersistedSnapshot(e)}:{remote:!0,incarnation:p(n)?n.sessionId:void 0},...o?{}:{src:n.src},registryKey:n.registryKey,syncSnapshot:n._syncSnapshot}}const I=ue(t)?.actor,E=I?.system?._clock?.now?void 0:I?.system?._snapshot?._scheduledTimers;for(const e of d){let s,n=e.event;if("xstate.timeout.actor"===n.type&&(n={...n},delete n.sessionId),"self"===e.target)s="self";else if(y(e.target))s={...e.target};else{const n=Object.entries(u).find(([,t])=>t===e.target)?.[0];if(n)s=n;else{if(e.target!==ue(t)?.actor._parent)throw new Error(i(43,e.target.id));s={type:"parent"}}}const r=E?.[V(I,L(e))],o=r?r.dueAt-e.delay:W(e);b.push({...void 0!==e.id&&{id:e.id},...void 0!==e.seq&&{seq:e.seq},delay:e.delay,type:e.type,event:n,target:s,...void 0!==o&&{scheduledAt:o}})}const A={...x,context:Ps(h,()=>ue(t)?.actor.id??a.id),children:w,timers:b,historyValue:Rs(x.historyValue)};return n&&Object.keys(n).length>0&&(A.stateInputs=n),A.nextTimerId=r,o&&Object.keys(o).length>0&&(A.nextActorIds=o),void 0!==a.version&&(A.machine={id:a.id,version:a.version}),A}(t,e)}}function $n(t,e,s){if(t instanceof Pn)return function(t,e,s){t instanceof Pn&&(t=t._raw());e=o(e);const n=!s,r=s??Ae(t);if(!e||"object"!=typeof e||Array.isArray(e))throw new xn(i(24,t.id));const c=e.machine,a=c&&"object"==typeof c&&"function"==typeof c.transition&&"root"in c?void 0:c,u=e.version,d="string"==typeof a?.version?a.version:u;if(void 0!==u&&void 0!==a?.version&&a.version!==u)throw new Error(i(34,u,a.version));if(a&&"string"==typeof a.id&&a.id!==t.id)throw new Error(i(35,a.id,t.id));if(d!==t.version){const s=t.config.migrate;if("function"!=typeof s)throw new Error(i(36,d,t.version));e=s(e,d)}const h=e,{nodes:f,childLogics:l}=In(t,h),p={},v=h.children;for(const t of Object.keys(v)){const e=v[t];if(!0===e.remote&&void 0!==e.address){if("string"!=typeof e.src)throw new Error(i(28,t));const s=x(r.system,{id:t,address:e.address,src:e.src,parent:r.self,registryKey:e.registryKey,syncSnapshot:e.syncSnapshot,incarnation:e.incarnation});e.registryKey&&r.system._set(e.registryKey,s),p[t]=s;continue}const s=e.snapshot,n=e.src,o=l.get(t),c=r.system.createActorRef(o,{id:t,parent:r.self,syncSnapshot:e.syncSnapshot,...void 0!==s?{_restore:qn(o,s)}:{},src:n,registryKey:e.registryKey});c._rehydrated=!0,void 0===n&&(c._invoked=!0),p[t]=c}const g=[],m=h.timers??[];for(const t of m){let e=t.event;if("xstate.timeout.actor"===e.type){const t=e.actorId,s=p[t];s&&(e=T(t,s.sessionId))}const s="string"==typeof t.target?"self"===t.target?"self":p[t.target]:y(t.target)?t.target:r.self._parent;if(!s){const e="string"==typeof t.target?t.target:t.target.type;throw new xn(i(33,e))}g.push({...t,event:e,target:s})}const _=(e=>{if(!e||"object"!=typeof e)return{};const s={};for(const n of Object.keys(e)){const r=e[n];for(const e of r){let r;if(e instanceof kn)r=e;else try{r=t.getStateNodeById(e.id)}catch{}r&&(s[n]??=[],s[n].push(r))}}return s})(h.historyValue),{version:w,_nextActorId:b,nextTimerId:S,nextActorIds:I,stateInputs:E,...A}=e;let k=I;for(const t of Object.keys(v)){const e=en(t);e&&(k?.[e.prefix]??0)<=e.index&&(k={...k,[e.prefix]:e.index+1})}const O=new Map;function j(t,e=!1){if(!t||"object"!=typeof t)return t;if(!e&&y(t))return void 0!==t.incarnation?t:Object.values(p).find(e=>e.address===t["@actor"])??t;const s=Object.getPrototypeOf(t);if(!Array.isArray(t)&&s!==Object.prototype&&null!==s)return t;let n=O.get(t);if(!n){O.set(t,n=Array.isArray(t)?[]:Object.create(s));for(const e of Object.keys(t))Object.defineProperty(n,e,{value:j(t[e]),writable:!0,enumerable:!0,configurable:!0})}return n}const M=js({...A,context:j(A.context,!0),children:p,timers:g,_nextTimerId:S,_nextActorIds:k,_nodes:f,value:void 0,historyValue:_,_stateInputs:Object.fromEntries(Object.entries(h.stateInputs??{}).filter(([t])=>f.some(e=>e.id===t)))},t,r.self);if(n)return ve(r,M,!1),me(r,M);ge(r)||he(M,r.self,r.system);return M}(t,e,s);if(!t.restoreSnapshot&&null===e)throw new Error(i(46));return t.restoreSnapshot?t.restoreSnapshot(e,s):e}function qn(t,e){return{restore:s=>$n(t,e,s),error:s=>t instanceof Pn?function(t,e,s){const n=e?.context;return Ms(js({context:n&&"object"==typeof n?n:{},_nodes:[t.root],children:{},status:"active"},t),{status:"error",error:s})}(t,e,s):void 0}}function Dn(t){if(y(t))return{...t};const e=p(t)?t.sessionId:void 0;return void 0===e?{"@actor":t.address}:{"@actor":t.address,incarnation:e}}function Kn(t,e,s){if(!Ft())return;const n=t.self;n?.system._hasInspectionObservers?.()&&n._inspectTransition(e,s)}const Ln=new Set(["xstate.done.actor","xstate.error.actor","xstate.timeout.actor"]);function Nn(t){if(!t||"object"!=typeof t)return!1;const{event:e,source:s}=t;return!(!e||"string"!=typeof e.type||void 0!==s&&(!s||"string"!=typeof s["@actor"]||void 0!==s.incarnation&&"string"!=typeof s.incarnation))}class zn extends Error{constructor(){super("Durable execution was stopped"),this.name="DurableExecutionCancelledError"}}class Vn extends Error{constructor(){super("run() can only start a fresh durable execution; resume checkpoints with restore() and the explicit transition loop"),this.name="DurableExecutionResumeError"}}t.DurableExecutionCancelledError=zn,t.DurableExecutionResumeError=Vn,t.createDurable=function(t,e,s){let n=e.transitionIndex??0;const r=n;let o=!1;const i=()=>e.now?.()??Date.now(),c=new WeakSet;let a=0===n?void 0:n-1;const u=new WeakMap;if(!Number.isSafeInteger(n)||n<0)throw new RangeError("transitionIndex must be a non-negative safe integer");const d=(t,e=!1)=>{const s=e?n:n++;return a=e?a??s:s,t.map((t,n)=>{const r={id:`${e?"restore:":""}${s}:${n}`,transitionIndex:s,effectIndex:n,effect:t};let o;return Object.defineProperty(r,"descriptor",{enumerable:!0,get:()=>o??=function(t){if("action"===t.kind)return{kind:"action",type:t.type,params:t.params};if("emit"===t.kind)return{kind:"emit",type:t.type,source:Dn(t.source),event:t.event};switch(t.type){case"@xstate.spawn":return{kind:"builtin",type:"@xstate.spawn",source:t.source&&Dn(t.source),actor:Dn(t.actor),id:t.id,src:Zs(t.src),input:t.input};case"@xstate.start":return{kind:"builtin",type:"@xstate.start",source:t.source&&Dn(t.source),actor:Dn(t.actor),id:t.id};case"@xstate.raise":return{kind:"builtin",type:"@xstate.raise",source:Dn(t.source),event:t.event,id:t.id,...void 0!==t.seq&&{seq:t.seq},delay:t.delay};case"@xstate.sendTo":return{kind:"builtin",type:"@xstate.sendTo",source:Dn(t.source),target:t.target&&Dn(t.target),event:t.event,id:t.id,...void 0!==t.seq&&{seq:t.seq},delay:t.delay};case"@xstate.cancel":return{kind:"builtin",type:"@xstate.cancel",source:Dn(t.source),...N(t)};case"@xstate.stop":return{kind:"builtin",type:"@xstate.stop",source:Dn(t.source),actor:Dn(t.actor),id:t.id};case"@xstate.terminate":return{kind:"builtin",type:"@xstate.terminate",source:Dn(t.source),actor:Dn(t.actor),id:t.id,status:t.status,output:t.output,error:t.error};case"@xstate.deadLetter":return{kind:"builtin",type:"@xstate.deadLetter",source:t.source&&Dn(t.source),target:t.target&&Dn(t.target),event:t.event,reason:t.reason,issues:t.detail?.issues,error:t.detail?.error}}}(t)}),r})},h=tn(function(t){const e=Zs(t);return"x"===e?"x:0":e}(t)),f=t.id??h,l=t.version,y=e.executionId?{executionId:e.executionId,nextSessionId:0}:void 0,v={};for(const t of[...rn,"sendEvent","runStep","runLogic"]){const s=e[t];s&&(v[t]=s.bind(e))}const g=Object.keys(v).length>0||!!e.enqueueRootEvent;let m;const _=[],x=(t,e)=>{if(bs(t)&&Ln.has(e.type)&&"string"==typeof e.actorId)return t.children[e.actorId]??null};let w=Promise.resolve();const b=t=>m?((t,e)=>{const s=w.then(e).then(()=>{});return w=s.catch(()=>{}),((t,e)=>(t.pending.add(e),e.catch(e=>{t.failures.push(e)}).then(()=>t.pending.delete(e)),e))(t,s)})(m,t):t(),S=async t=>{for(;t.pending.size;)await Promise.allSettled([...t.pending])};function E(t,n,r=!1,o){const c={};for(const e of rn){const s=t[e]??(r?(...t)=>("spawnActor"===e?t[1]:t[0]).system[e](...t):void 0);s&&(c[e]=(...t)=>b(()=>{if("scheduleTimer"===e&&o&&(t[2]=Math.min(o.delay,Math.max(0,o.deadline-i()))),"scheduleTimer"===e){const e=t[0],n=t[1],r=e.getSnapshot()?.timers?.find(t=>z(t,n));if(r){const e=W(r);void 0===e||o||(t[2]=Math.min(r.delay,Math.max(0,e+r.delay-i())));const n=s(...t);return n?Promise.resolve(n).then(()=>{U(r,e??i())}):void U(r,e??i())}}return s(...t)}))}return t.runStep&&(c.runStep=t.runStep),t.runLogic&&(c.runLogic=t.runLogic),c.sendEvent=(r,o,i)=>{const c=!1!==s?.captureRootEvents?m:void 0;if(!c&&o.address===h&&!t.sendEvent&&e.enqueueRootEvent)return b(()=>e.enqueueRootEvent(r,i));if(!c&&o.address===h&&!t.sendEvent)throw new Error(`A root-addressed event ("${i.type}") was produced outside batch capture (for example, while the durable loop was parked), but the adapter has no enqueueRootEvent or sendEvent to receive it. Implement enqueueRootEvent to place root-addressed events in the host's mailbox.`);if(c&&o.address===h)return void c.rootEvents.push({event:i,source:r});const a=t.sendEvent;if(a)return b(()=>a(r,o,i));if(n)return b(()=>I(r,o,i));throw new TypeError(`The durable runtime does not support the sendEvent operation (target '${o.address}')`)},c}const A=g?E(v,!0):void 0;function k(t,e){if(t.address===e)return t;if(!e.startsWith(`${t.address}/`))return;const s=t.getSnapshot().children;for(const t of Object.values(s??{})){const s=t&&k(t,e);if(s)return s}}const T=s?.inspect,O={runtime:A,inspect:T};function j(t){return function(t,e){const s=Zt;Zt=t;try{return e()}finally{Zt=s}}(O,()=>function(t,e){if(!t)return e();const s=Bt;Bt=t;try{return e()}finally{Bt=s}}(T,t))}function R(t,e=!1){if("error"===t.status){const e=ue(t)?.actor;e&&!c.has(e)&&(e.subscribe({error(){}}),c.add(e))}if(A||T){const s=ue(t)?.actor,n=new Set,r=t=>{var s;if(n.has(t.system)||(n.add(t.system),function(t,e){const s=Gt.get(t),n=Yt.get(s?.executionSystem??t);return n===e?(s&&(s.forwardInspection=!!e.inspect),!0):!n&&(s?(ce(t,s.executionSystem,e),s.executionSystem=t,s.forwardInspection=!!e.inspect,!0):(Yt.set(t,e),!0))}(t.system,O)&&(A&&(t.system.runtime=A),s=t.system,T&&!s._hasInspectionObservers?.()&&s.inspect(T))),e){const e=t.getSnapshot().children;for(const t of Object.values(e??{}))t&&r(t)}};if(s&&r(s),!e||!s){const e=t.children;for(const t of Object.values(e??{}))t&&r(t)}}return t}const P={rootAddress:h,machineId:f,machineVersion:l,get nextTransitionIndex(){return n},checkpoint(e,s){const r=[];for(const{event:t,source:s}of _){const n=x(e,t);"xstate.snapshot.actor"===t.type||void 0!==n&&(!n||void 0!==t.sessionId&&void 0!==n.sessionId&&n.sessionId!==t.sessionId)||r.push({event:t,source:s&&{"@actor":s.address,...p(s)&&void 0!==s.sessionId?{incarnation:s.sessionId}:{}}})}return{snapshot:t.getPersistedSnapshot?.(e,s)??e,nextTransitionIndex:n,inbox:r}},restore(s){const i=(c=s)&&"object"==typeof c&&"inbox"in c&&"nextTransitionIndex"in c&&"snapshot"in c?s:void 0;var c;if(o||n!==r||m)throw new Error("restore() requires a fresh durable execution");if(i){if(!Array.isArray(i.inbox)||!i.inbox.every(Nn))throw new TypeError("The checkpoint inbox is invalid.");if(void 0!==e.transitionIndex&&e.transitionIndex!==i.nextTransitionIndex)throw new RangeError(`The adapter's transitionIndex (${e.transitionIndex}) does not match the checkpoint's nextTransitionIndex (${i.nextTransitionIndex}).`);if(!Number.isSafeInteger(i.nextTransitionIndex)||i.nextTransitionIndex<0)throw new RangeError("nextTransitionIndex must be a non-negative safe integer");n=i.nextTransitionIndex,a=0===n?void 0:n-1}const h=i?i.snapshot:s,{snapshot:f,scope:l}=j(()=>Ys(y,()=>{const e=Ae(t),s=$n(t,h,e);return ve(e,s,!1),{snapshot:R(me(e,s),!0),scope:e}}));for(const{event:t,source:e}of i?.inbox??[]){const s=x(f,t);null!==s&&_.push({event:s&&void 0!==s.sessionId&&"sessionId"in t?{...t,sessionId:s.sessionId}:t,source:e&&P.getActorRef(f,e["@actor"])})}const v=[];if("active"===f.status){const{children:t,timers:e}=f;for(const e of Object.values(t??{}))e&&!p(e)&&"active"===e.getSnapshot().status&&v.push(Kt(e));for(const t of e??[]){const e=Lt(l,t,t.delay);void 0!==t.scheduledAt&&u.set(e,{deadline:t.scheduledAt+t.delay,delay:t.delay}),v.push(e)}}return o=!0,[f,d(v,!0)]},initialTransition(...e){if(o)throw new Error("initialTransition() cannot initialize a restored execution");const[s,n]=j(()=>Ys(y,()=>function(t,...[e]){const s=Ae(t),[n,r]=Vt(s,void 0,t.initialTransition(e,s));ve(s,n,!1);const o=me(s,n);return Kn(s,o,M(e)),[o,r]}(t,...e)));return[R(s),d(n)]},transition(e,s){const[n,r]=j(()=>Ys(y,()=>function(t,e,s){const n=Ae(t,e);ve(n,e,!1);const[r,o]=Vt(n,e,t.transition(e,s,n));ve(n,r,!1);const i=r===e?r:me(n,r);return Kn(n,i,s),[i,o]}(t,e,s)));return[R(n),d(r)]},getActorRef(t,e){const s=ue(t)?.actor;return s&&void 0!==e?k(s,e):s},async executeEffects(t){if(m)throw new Error("executeEffects calls must not overlap: await the previous call before starting the next batch.");const s={rootEvents:[],failures:[],pending:new Set};m=s;const n=g?void 0:{};try{for(const s of t){const{effect:t}=s,r={id:s.id,transitionIndex:s.transitionIndex,effectIndex:s.effectIndex},o=e.runtime?.(r,t),i=u.get(t),c=o||i?E({...v,...o},g,!!o||g,i):n;"action"===t.kind?await e.executeAction(t,r,c??A??{}):await t.exec(c)}await(async t=>{if(await S(t),t.failures.length)throw t.failures[0]})(s),_.push(...s.rootEvents)}catch(t){throw await S(s),t}finally{m=void 0}},async waitForEvent(){if(void 0===a)throw new Error("Cannot wait for an event before the first transition or restore");const t=_.shift();return t?t.event:e.waitForEvent({id:o&&0===n?"event:restore:0":`event:${a}`,transitionIndex:a})},async run(...t){if(o||0!==r||n!==r)throw new Vn;let[e,s]=P.initialTransition(...t);for(await P.executeEffects(s);"active"===e.status;){const t=await P.waitForEvent();[e,s]=P.transition(e,t),await P.executeEffects(s)}const i=e;if("done"===i.status)return i.output;if("error"===i.status)throw i.error;throw new zn}};return P},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).XStateDurable={})}(this,function(t){"use strict";const e={$actor:["@actor",["incarnation"]],$error:["@error",["message"]],$stateNode:["@stateNode",[]],$systemMapper:["@systemMapper",[]]},s={_stateInputs:"stateInputs",_nextTimerId:"nextTimerId",_nextActorIds:"nextActorIds"};function n(t){if(!t||"object"!=typeof t)return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e||Array.isArray(t)}function r(t,s){if(!n(t))return t;if(Array.isArray(t)){const e=t.map(t=>r(t,s));return e.some((e,s)=>e!==t[s])?e:t}const o=Object.keys(t),i=o.find(t=>s.includes(t));if(i&&"string"==typeof t[i]&&o.every(t=>t===i||e[i][1].includes(t))){const{[i]:s,...n}=t;return{[e[i][0]]:s,...n}}let c;for(const e of o){const n=r(t[e],s);n!==t[e]&&((c??={...t})[e]=n)}return c??t}function o(t){return t?.machine&&"function"==typeof t.matches?t:n(e=t)&&"_nextTimerId"in e&&!("nextTimerId"in e)?r(function(t){if(!n(t)||"function"==typeof t.matches)return t;let e;for(const[n,r]of Object.entries(s))if(n in t&&!(r in t)){const{[n]:s,...o}=e??t;e={...o,[r]:s}}return e??t}(t),["$actor"]):t;var e}function i(t,...e){return`XState error E${t}${e.length?` (${e.map(t=>"string"==typeof t?JSON.stringify(t):String(t)).join(", ")})`:""}. See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e${t}`}const c=new Set(["clock","logger","syncSnapshot","id","registryKey","input","src","inspect","onRejectedEvent","onUnhandledEvent","_systemRef","_sessionId","_inert","_restore"]);const a="xstate.init",u="@xstate.spawn",d="xstate.stop",h="@xstate.terminate",f="xstate.timer",l={unsubscribe(){}};function p(t){return!0===t._remote}function y(t){if("object"!=typeof t||null===t||Array.isArray(t)||"string"!=typeof t["@actor"])return!1;for(const e in t)if("@actor"!==e&&"incarnation"!==e)return!1;const e=t.incarnation;return void 0===e||"string"==typeof e}function v(t){const e=t.slice(t.lastIndexOf("/")+1);return e.includes("%")?e.replaceAll("%2F","/").replaceAll("%25","%"):e}function g(t){return new Error(i(50,...void 0===t.incarnation?[t["@actor"]]:[t["@actor"],t.incarnation]))}function _(t,e){const s=t._getByAddress?.(e["@actor"]);return!s||void 0!==e.incarnation&&s.sessionId!==e.incarnation?void 0:s}const m=Object.freeze({status:"active",output:void 0,error:void 0});function x(t,e){const s={_remote:!0,ref:void 0,id:e.id,address:e.address,src:e.src,registryKey:e.registryKey,sessionId:e.incarnation,system:t,_parent:e.parent,_syncSnapshot:e.syncSnapshot,send(e){t.sendEvent(void 0,n,e)},_send(t){throw new Error(i(52,e.address,t.type))},getSnapshot:()=>m,getPersistedSnapshot(){throw new Error(i(53,e.address))},start(){},_stop(){},stop(){throw new Error(i(54,e.address))},select(){throw new Error(i(55,e.address))},get trigger(){throw new Error(i(56,e.address))},subscribe:()=>l,on:()=>l,_isRunning:()=>!1,toJSON:()=>({"@actor":e.address})},n=s;return s.ref=n,n}function w(t,e,s){return t.system._notifyEmitted(t,e),s.emitEvent(t,e)}const b=new WeakMap;async function S(t,e,s,n=e=>{t.system.sendEvent(t,t,e)}){const r=function(t,e){const s=t.getSnapshot().effects;return s&&Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0}(t,e);if("done"===r?.status)return r.output;if("error"===r?.status)throw r.error;const o=b.get(t)?.get(e);if(o)return o;if("active"!==t.getSnapshot().status)throw new Error(i(72,e));let c,a;const u=new Promise((t,e)=>{c=t,a=e});let d,h=b.get(t);h||(h=new Map,b.set(t,h)),h.set(e,u);const f=()=>{d?.unsubscribe(),h.delete(e),h.size||b.delete(t)};return u.then(f,f),d=t.subscribe({error:a,complete:()=>a(new Error(i(72,e)))}),(async()=>{try{n({type:"xstate.logic.effect.start",key:e});const r=await s();"active"===t.getSnapshot().status&&(n({type:"xstate.logic.effect.resolve",key:e,output:r}),c(r))}catch(s){"active"===t.getSnapshot().status&&n({type:"xstate.logic.effect.reject",key:e,error:s}),a(s)}})().catch(a),u}function I(t,e,s){if(y(e)){const n=e,r=t?.system,o=r&&_(r,n);if(!o){const e=g(n);if(!r)throw e;return void r.deadLetter(t,void 0,s,"missingTarget",{targetId:v(n["@actor"]),error:e})}e=o}if(E(t,e,s))return;e._send(s,t)}function E(t,e,s){const n=function(t,e,s){const n=e;if(t!==e&&n.logic?.isInternalEventType?.(s.type))return new Error(i(73,s.type,e.id))}(t,e,s);return!!n&&(e.system.deadLetter(t,e,s,"internalEvent",{error:n}),!0)}class A{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}function k(t,e){return{type:"xstate.after",delay:t,stateId:e}}function T(t,e){return{type:"xstate.timeout.actor",actorId:t,sessionId:e}}function O(t,e){return{type:"xstate.done.state",stateId:t,output:e}}function j(t,e){return{type:`xstate.error.${t}`,error:e}}function M(t){return{type:a,input:t}}function R(t){setTimeout(()=>{throw t})}const P="function"==typeof Symbol&&Symbol.observable||"@@observable",$=[],q=new Error("Transition effect");function D(t,e="abort"){const s={mode:e,parent:t,requiresReevaluation:!1};return $.push(s),{frame:s,close(){$.pop()}}}function K(t){const{stateId:e,delay:s,actorId:n}=t;switch(t.type){case"xstate.after":return{type:t.type,delay:s,stateId:e};case"xstate.timeout.state":return{type:t.type,stateId:e};case"xstate.timeout.actor":return{type:t.type,actorId:n}}}function L(t){return void 0!==t.id?{id:t.id}:void 0!==t.seq?{seq:t.seq}:{event:K(t.event)??t.event}}function N(t){const e=t;return"string"==typeof e.id?{id:e.id}:"number"==typeof e.seq?{seq:e.seq}:e.event&&"object"==typeof e.event&&"string"==typeof e.event.type?{event:e.event}:void 0}function z(t,e){if("id"in e)return t.id===e.id;if(void 0!==t.id)return!1;if("seq"in e)return t.seq===e.seq;if(void 0!==t.seq)return!1;const s=t.event,n=e.event;for(const t in n)if(s[t]!==n[t])return!1;return!0}function V(t,e){return`${t.sessionId}|${function(t){return"id"in t?JSON.stringify(["id",t.id]):"seq"in t?JSON.stringify(["seq",t.seq]):JSON.stringify(["event",K(t.event)??t.event])}(e)}`}const C=new WeakMap;function W(t){return C.get(t)??t.scheduledAt}function U(t,e){C.set(t,e)}function J(t){if("string"==typeof t)throw new Error(i(70,t))}const H={"@xstate.spawn":t=>t.system.spawnActor(t._parent,t),"@xstate.start":t=>t.system.startActor(t),"@xstate.raise":(t,e,s)=>t.system.scheduleTimer(t.self,L({id:s.id,seq:s.seq,event:e}),s?.delay??0),"@xstate.sendTo":(t,e,s,n)=>(J(s),void 0!==n?.delay?t.system.scheduleTimer(t.self,L({id:n.id,seq:n.seq,event:s}),n?.delay??0):t.system._relay(t.self,e,s)),"@xstate.cancel":(t,e)=>t.system.cancelTimer(t.self,e),"@xstate.stop":(t,e)=>t.system.stopActor(e),"@xstate.terminate":(t,e)=>t.system.terminateActor(t,e)},B=new WeakMap;function F(t,e){let s=B.get(t);if(!s){s=new Map;for(const e of Object.keys(t)){const n=t[e];s.has(n)||s.set(n,e)}B.set(t,s)}return s.get(e)}const X=Symbol("xstate.systemLogicMetadata"),G=new WeakMap,Q="xstate.attached.forward";function Y(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]],n={id:e,start:(e,{self:s,system:n})=>{const r=e.input.actor;if(!r||"stopped"===r.getSnapshot().status)return;const o=t(e.input,{self:s,system:n});if(!o)return;let i,c=!1;const a=()=>{c||(c=!0,o.unsubscribe(),i?.unsubscribe())},u=s._parent;u&&(i=u.subscribe({complete:a,error:a})),G.set(s,{unsubscribe:a})},transition:(t,e,s)=>{const n=s.self;return e.type===Q?[t,"active"===t.status&&n._parent?[zt(s,n._parent,e.event)]:[]]:e.type===d?(G.get(n)?.unsubscribe(),G.delete(n),[{...t,status:"stopped",error:void 0},[]]):[t,[]]},initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t,isInternalEventType:t=>t===Q};return Object.defineProperty(n,X,{value:{kind:e}}),n}function Z(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t,{type:Q,event:s()})}function tt(){return Y(({actor:t,eventType:e,mapper:s},{self:n,system:r})=>{const o="*"!==e&&e.endsWith(".*");return t.on(o?"*":e,t=>{o&&!Fs(t.type,e)||Z(n,r,()=>s(t))})},"@xstate.listener")}const et=tt();function st(){return Y(({actor:t,mappers:e},{self:s,system:n})=>{const{done:r,error:o,snapshot:i}=e;return t.subscribe({next:t=>{"done"===t.status&&r?Z(s,n,()=>r(t.output)):"error"===t.status&&o?Z(s,n,()=>o(t.error)):"active"===t.status&&i&&Z(s,n,()=>i(t))},error:t=>{o&&Z(s,n,()=>o(t))},complete:()=>{}})},"@xstate.subscription")}const nt=st();function rt(){const t=this.action?.(...this.args);return t}function ot(t=this.source.system){return w(this.source,this.event,t)}function it(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function ct(t,e,s,n,r){return{kind:"builtin",type:"@xstate.deadLetter",exec:it,source:e,target:t.self,event:s,reason:n,detail:r,params:void 0,args:[]}}function at(t,e,s){return{kind:"builtin",type:"@xstate.deadLetter",exec:it,source:t.self,target:void 0,event:e,reason:"missingTarget",detail:{targetId:s,error:new Error(i(65,s))},params:void 0,args:[]}}function ut(t=this.actor.system){return t.spawnActor(this.source,this.actor)}function dt(t=this.actor.system){if(2!==this.actor._processingStatus)return t.startActor(this.actor)}function ht(t=this.source.system){return t.stopActor(this.actor)}function ft(t=this.actor.system){const e="done"===this.status?{status:"done",output:this.output,error:void 0}:{status:"error",output:void 0,error:this.error};return t.terminateActor(this.actor,e)}function lt(t=this.source.system){return t.scheduleTimer(this.source,L(this),this.delay??0)}function pt(t=this.source.system){return J(this.event),void 0!==this.delay?t.scheduleTimer(this.source,L(this),this.delay):t.sendEvent(this.source,this.target,this.event)}function yt(t=this.source.system){return t.cancelTimer(this.source,N(this))}function vt(t,e,s){if(!Wt(e))return t;if("@xstate.cancel"===e.type){const s=N(e);return t.timers?.some(t=>z(t,s))?{...t,timers:t.timers.filter(t=>!z(t,s))}:t}if("@xstate.raise"!==e.type&&"@xstate.sendTo"!==e.type||void 0===e.delay)return t;let n=t._nextTimerId??0;if(void 0===e.id&&!K(e.event)){e.seq=n++;const t=e.args;t[t.length-1]={...t[t.length-1],seq:e.seq}}const r="@xstate.raise"===e.type||e.target===s.self?"self":e.target,o={...void 0!==e.id&&{id:e.id},...void 0!==e.seq&&{seq:e.seq},delay:e.delay,type:e.type,event:e.event,target:r},i=L(o),c=t.timers??[],a=c.findIndex(t=>z(t,i));return{...t,timers:-1===a?[...c,o]:c.map((t,e)=>e===a?o:t),_nextTimerId:n}}function gt(t,e){return{...t,...e}}function _t(t,e,...s){const n={action:e,args:s};return t.push(n),n}function mt(t,e){const s={...t};for(const t of Object.keys(e))s[t]=Math.max(s[t]??0,e[t]);return s}function xt(t,e,s){if("add"===e.type)return{...t,children:{...t.children,[e.id]:e.actor},...e.counters&&{_nextActorIds:mt(t._nextActorIds,e.counters)}};const n={...t.children};let r=e.actor._parent===s.self;for(const t of Object.keys(n))n[t]===e.actor&&(r=!0,delete n[t]);if(!r)throw new Error(i(47,e.actor.id,s.self.id));return s.system._unregister(e.actor),{...t,children:n}}function wt(t){if("object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action)return t}const bt=new WeakMap,St=()=>({counters:new Map,explicitIds:new Set,stoppedIds:new Set});function It(t){bt.set(t,St())}function Et(t){return t.self._snapshot}function At(t,e,s){return Math.max(e.counters.get(s)??0,Et(t)?._nextActorIds?.[s]??0)}function kt(t,e,s){let n=At(t,e,s);const r=Et(t)?.children;for(;e.explicitIds.has(`${s}:${n}`)||r?.[`${s}:${n}`];)n++;return n}function Tt(t,e,s){const n=bt.get(t)??s??St(),r=tn(e),o=kt(t,n,r);return n.counters.set(r,o+1),{id:`${r}:${o}`,counters:{[r]:o+1}}}function Ot(t,e,s){const n=bt.get(t)??s??St(),r=Et(t)?.children?.[e],o=void 0!==r&&!n.stoppedIds.has(e)&&"active"===r.getSnapshot().status;if(n.explicitIds.has(e)||o)throw new Error(i(67,e,t.self.id));n.explicitIds.add(e)}function jt(t,e,s){const n=sn(e);if(!n)return;n.prefix;const r=bt.get(t)??s??St(),o=Math.max(At(t,r,n.prefix),n.index+1);return r.counters.set(n.prefix,o),{[n.prefix]:o}}const Mt=new WeakSet;function Rt(t){if("string"==typeof t)throw new Error(i(68,t))}function Pt(t,e,s,n=!1,r=!0){const o=bt.get(t)??St(),c={cancel:s=>{_t(e,H["@xstate.cancel"],t,"string"==typeof s?{id:s}:s)},emit:t=>{e.push(t)},log:(...s)=>{_t(e,t.logger,...s)},raise:(n,r)=>{Rt(n),void 0!==r?.delay?_t(e,H["@xstate.raise"],t,n,r):s.push(n)},spawn:(s,n)=>{const{logic:c,src:a}=function(t,e){const s=function(t){return t.self.logic?.sources?.actors}(t);if("string"==typeof e){const t=s?.[e];if(!t)throw new Error(i(66,e));return{logic:t,src:e}}return s?{logic:e,src:F(s,e)}:{logic:e,src:void 0}}(t,s);if(!r){const e=tn(a??c),s=n?.id??`${e}:${kt(t,bt.get(t)??o,e)}`;return function(t){const{id:e,address:s}=t,n={ref:void 0,id:e,address:s,src:t.src,sessionId:void 0,send(){},getSnapshot:()=>m,subscribe:()=>l,on:()=>l,toJSON(){if(void 0===s)throw new Error(i(51,e));return{"@actor":s}}},r=n;return n.ref=r,r}({id:s,address:Mt.has(t)?void 0:`${t.self.address}/${en(s)}`,src:a})}let u,d=n?.id;void 0===d?({id:d,counters:u}=Tt(t,a??c,o)):(Ot(t,d,o),u=jt(t,d,o));const h=t.system.createActorRef(c,{...n,...void 0!==a&&{src:a},id:d,parent:t.self});return function(t,e,s,n){_t(t,H["@xstate.spawn"],e).childUpdate={type:"add",actor:e,id:s,counters:n}}(e,h,d,u),h},sendTo:(s,n,r)=>{_t(e,H["@xstate.sendTo"],t,s,n,r)},stop:s=>{if(s){const n=s;_t(e,H["@xstate.stop"],t,n).childUpdate={type:"remove",actor:n},function(t,e){const s=bt.get(t);s&&(s.stoppedIds.add(e.id),s.explicitIds.delete(e.id))}(t,n)}}};n&&Object.assign(c,{listen:(s,n,o)=>{if(!r)return{id:void 0};const i={actor:s,eventType:n,mapper:o},c=t.system.createActorRef(et,{input:i,parent:t.self});return _t(e,H["@xstate.spawn"],c),c},subscribeTo:(s,n)=>{if(!r)return{id:void 0};const o={actor:s,mappers:"function"==typeof n?{snapshot:n}:n},i=t.system.createActorRef(nt,{input:o,parent:t.self});return _t(e,H["@xstate.spawn"],i),i}});let a=!1;const u=t=>(...e)=>a?Dt():t(...e);for(const t of Object.keys(c))c[t]=u(c[t]);const d=Jt(c,u((t,...s)=>{"function"==typeof t&&_t(e,t,...s)}));return $t.set(d,()=>{a=!0}),d}const $t=new WeakMap;function qt(t){$t.get(t)?.()}function Dt(){}function Kt(t,e){switch(t){case H["@xstate.spawn"]:{const[t]=e;return{type:"@xstate.spawn",kind:"builtin",exec:ut,source:t._parent,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case H["@xstate.raise"]:{const[,t,s]=e;return{type:"@xstate.raise",kind:"builtin",exec:lt,source:e[0].self,event:t,id:s?.id,delay:s?.delay}}case H["@xstate.sendTo"]:{const[,t,s,n]=e;return{type:"@xstate.sendTo",kind:"builtin",exec:pt,source:e[0].self,target:t,event:s,id:n?.id,delay:n?.delay}}case H["@xstate.cancel"]:{const[,t]=e;return{type:"@xstate.cancel",kind:"builtin",exec:yt,source:e[0].self,...t}}case H["@xstate.stop"]:{const[,t]=e;return{type:"@xstate.stop",kind:"builtin",exec:ht,source:e[0].self,actor:t,id:t.id}}default:return}}function Lt(t){const e=[t];return{kind:"builtin",exec:dt,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function Nt(t,e,s){const n=t.self,r={id:e.id,seq:e.seq,delay:s};if("@xstate.raise"===e.type)return{kind:"builtin",type:e.type,source:n,event:e.event,id:e.id,...void 0!==e.seq&&{seq:e.seq},delay:s,params:void 0,args:[t,e.event,r],exec:lt};const o="self"===e.target?n:e.target;return{kind:"builtin",type:e.type,source:n,target:o,event:e.event,id:e.id,...void 0!==e.seq&&{seq:e.seq},delay:s,params:void 0,args:[t,o,e.event,r],exec:pt}}function zt(t,e,s){const n=[t,e,s,{}];return{kind:"builtin",exec:pt,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:n}}function Vt(t,e){if("done"!==e.status&&"error"!==e.status)throw new Error(i(69,t.self.id,e.status));const s="done"===e.status?{status:"done",output:e.output,error:void 0}:{status:"error",output:void 0,error:e.error},n=[t.self,s];return{kind:"builtin",exec:ft,type:h,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:n}}function Ct(t,e,[s,n]){const r="done"===s.status||"error"===s.status,o="done"===e?.status||"error"===e?.status,i=n.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===h);return!r||o||i?[s,n]:[s,[...n,Vt(t,s)]]}function Wt(t){return"builtin"===t.kind}function Ut(t,e,s,n){let r=t;const o=[];for(const t of n){const e="function"==typeof t,n=wt(t);let i=n?.args;if(n?.action===H["@xstate.sendTo"]&&(void 0===n.args[1]||"string"==typeof n.args[1])){const t=n.args[1],e=void 0!==t&&Object.hasOwn(r.children,t)?r.children[t]:void 0;if(!e){o.push(at(s,n.args[2],t));continue}i=[n.args[0],e,...n.args.slice(2)]}const c=e?t:!!n&&n.action.bind(null,...i);let a;if("object"==typeof t&&null!==t){const{type:e,childUpdate:s,...n}=t;a=n}if(n?.childUpdate&&(r=xt(r,n.childUpdate,s)),!c||!("resolve"in c)){const c="object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action?Kt(t.action,i):void 0,u="object"==typeof t&&null!==t&&!n,d={kind:c?"builtin":u?"emit":"action",type:"object"==typeof t?"action"in t&&"function"==typeof t.action?t.action.name??"(anonymous)":t.type:t.name||"(anonymous)",params:c?void 0:a,args:"object"==typeof t&&"action"in t?i:[],...c?{}:u?{source:s.self,event:t}:{action:n?.action??(e?t:void 0)},...c?{}:{exec:u?ot:rt},...c};r=vt(r,d,s),o.push(d);continue}}return[r,o]}function Jt(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:Ht,emit:Ht,log:Ht,raise:Ht,spawn:Bt,sendTo:Ht,stop:Ht,listen:Bt,subscribeTo:Bt,...t}),s}const Ht=()=>{},Bt=()=>({});let Ft;function Xt(){return void 0!==Ft}function Gt(){return Ft}const Qt=new WeakMap,Yt=["runtime","_timerMap","_rejectionListeners","_inspectionObservers","_emissionListeners"],Zt=new WeakMap;let te;const ee=new WeakMap,se=new WeakMap,ne=new Map;function re(t){const e=t._peekKeyedActors;return e?e.call(t)??ne:t.keyedActors}function oe(t){t._snapshotVersion++}function ie(t){return t._snapshotVersion}function ce(t,e,s,n){const r=Qt.get(t),o=r?.executionSystem??t,c=r?.rootSystem??t,a=void 0!==n&&Zt.get(o)!==n,u=n?!!n.inspect:Xt()&&(r?.forwardInspection??!0),d=function(t,e){if(e){const t=new Map(e.children);return e.root?.sessionId&&t.set(e.root.sessionId,e.root),t}return new Map(t.children)}(t,s),h=new Map(s?.keyedActors??re(t)),f=new WeakMap,l=()=>Qt.get(y).executionSystem,p=()=>Qt.get(y).forwardInspection,y=Object.assign(Object.create(o),{children:d,keyedActors:h,reverseKeyedActors:f,_snapshot:{...s?.snapshot??t._snapshot},_snapshotVersion:s?.sourceVersion??t._snapshotVersion,_register:(t,e)=>(d.set(t,e),oe(y),t),_unregister:t=>{t.sessionId&&d.delete(t.sessionId);const e=f.get(t);void 0!==e&&h.get(e)===t&&h.delete(e),f.delete(t),oe(y)},_set:(t,e)=>{const s=h.get(t);if(s&&s!==e)throw new Error(i(45,String(t)));h.set(t,e),f.set(e,t),oe(y)},get:t=>h.get(t),getAll:()=>Object.fromEntries(h),onEmitted:t=>c.onEmitted.call(l(),t),_notifyEmitted:(t,e)=>c._notifyEmitted.call(l(),t,e),_hasInspectionObservers:()=>p()&&(c._hasInspectionObservers?.call(l())??!1),_sendInspectionEvent:t=>{p()&&c._sendInspectionEvent.call(l(),t)}}),v=a?y:o;if(a)ae(y,o,n);else for(const t of Yt)Object.defineProperty(y,t,{configurable:!0,get:()=>l()[t],set:e=>{l()[t]=e}});Qt.set(y,{executionSystem:v,rootSystem:c,forwardInspection:u});for(const[t,e]of h)e&&f.set(e,t);for(const t of Object.values(e)){if(!t)continue;t.sessionId&&d.set(t.sessionId,t);const e=t.registryKey;e&&(h.set(e,t),f.set(t,e))}return y}function ae(t,e,s){const n=e._timerMap;for(const e of Yt)Object.defineProperty(t,e,{configurable:!0,writable:!0,value:"runtime"===e?s.runtime:"_timerMap"===e&&n?{...n}:void 0});Zt.set(t,s),s.inspect&&t.inspect(s.inspect)}function ue(){const t=te;return te=void 0,t}function de(t){const e=ee.get(t);if(e)return e;const s=se.get(t);if(!s)return;const n=s();return ee.set(t,n),se.delete(t),n}function he(t,e){const s=ee.get(t);if(s)return ee.set(e,s),!0;const n=se.get(t);return!!n&&(se.set(e,n),!0)}function fe(t,e,s=e.system,n){se.delete(t);const r=ie(s),o=n?de(n):void 0,i=o?.actor===e?o:de(t);if(i?.actor===e&&i.systemState.sourceSystem===s&&i.systemState.sourceVersion===r)return void ee.set(t,i);const c=function(t){const e=t._getRootActor?.(),s=t._peekChildren?.();if(!e&&!s){if(t._getRootActor&&t._peekChildren)return{};const e=new Map(t.children);return e.size?{children:e}:{}}return s?.size?{children:new Map(t.children)}:e?{root:e}:{}}(s);let a=c.children;const u=re(s);let d=u.size?new Map(u):ne;for(const e of Object.values(function(t){return"children"in t&&t.children?t.children:{}}(t))){if(!e)continue;e.sessionId&&(a??=new Map).set(e.sessionId,e);const t=e.registryKey;t&&(d===ne&&(d=new Map),d.set(t,e))}ee.set(t,{actor:e,systemState:{...c,children:a,keyedActors:d,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:r}})}const le=Symbol();function pe(t){return!!t[le]}function ye(t){return pe(t)?t._parent:t.self._parent}function ve(t,e){if(!pe(e)){const s=t,n=e.self;return s.self=n,s.system=e.system,s.parent=n._parent,s}return Object.defineProperties(t,{self:{enumerable:!0,get:()=>e.self},system:{enumerable:!0,get:()=>e.system},parent:{enumerable:!0,get:()=>ye(e)}}),t}function ge(t,e,s=!0){const n=Se(t);if(n){n.snapshot=e;const t=n.materialized??n.identityScope;t&&(t.self._snapshot=e)}else t.self._snapshot=e;return s&&e&&"object"==typeof e&&fe(e,t.self),e}function _e(t){return!!Se(t)||!!t.self.options?._inert}function me(t,e){ge(t,e,!1);const s=Se(t);be.set(e,t);const n=()=>(fe(e,t.self,t.system),de(e));return s&&(s.materialized?s.identityProvider=n:s.identityProvider??=n),function(t,e){ee.delete(t),se.set(t,e)}(e,n),e}function xe(t,e){return t.sourceRef=void 0,t.sourceChildren={},t.materialized=e,t.materialize=()=>e,e}const we=Symbol(),be=new WeakMap;function Se(t){return t[we]}function Ie(t){return Se(t).materialize()}const Ee={[le]:!0,get _parent(){const t=Se(this);return t.parentKnown?t.parent:Ie(this).self._parent},get self(){return Ie(this).self},get defer(){return Ie(this).defer},get id(){return Ie(this).id},get logger(){return Ie(this).logger},get sessionId(){return Ie(this).sessionId},get stopChild(){return Ie(this).stopChild},get system(){return Ie(this).system},get emit(){return Ie(this).emit},get actionExecutor(){return Ie(this).actionExecutor}};function Ae(t,e,s,n,r,o){const i=e?.(),c=r??i?.actor,a=c?.system,u=c&&a?ce(a,s,r?void 0:i?.systemState,o):void 0,d=xn(t,{_inert:!0,...c?{id:c.id,_sessionId:c.sessionId}:{},...u?{_systemRef:{current:u}}:{}});c?._parent&&(d._parent=c._parent,d._address=void 0);const h=Object.create(d._actorScope,{defer:{value:()=>{}},stopChild:{value:t=>t._stop()},actionExecutor:{value:()=>{}},_snapshot:{enumerable:!0,configurable:!0,get:()=>d._snapshot,set:t=>{d._snapshot=t}}});return n&&(h._snapshot=n),h}function ke(t,e,s,n){const r=n??(e&&"object"==typeof e?be.get(e):void 0),o=r?Se(r):void 0,i=e&&"object"==typeof e?function(t){return ee.get(t)}(e):void 0,c=o?.identityProvider??(e&&"object"==typeof e?function(t){const e=ee.get(t);return e?()=>e:se.get(t)}(e):void 0),a={snapshot:e,sourceRef:c,sourceChildren:Ss(e)?e.children:{},identityProvider:o?.identityProvider??c,parent:s?._parent??o?.parent??i?.actor._parent,owner:n?o?.owner:ue(),parentKnown:!(!s&&!o?.parentKnown&&!i&&e),materialize:()=>{const e=Ae(t,a.sourceRef,a.sourceChildren,a.snapshot,s,a.owner);return xe(a,e)}};if(!a.identityProvider&&!e){const e={};let n;const r=()=>(a.identityScope||(a.identityScope=Ae(t,a.sourceRef,a.sourceChildren,void 0,s,a.owner),void 0!==a.snapshot&&(a.identityScope.self._snapshot=a.snapshot)),a.identityScope);a.materialize=()=>{const t=r();return void 0!==a.snapshot&&(t.self._snapshot=a.snapshot),xe(a,t)},a.identityProvider=()=>{if(n)return n;const t=r();return fe(e,t.self,t.system),n=de(e)}}const u=Object.create(Ee);return u[we]=a,u}function Te(t,e){if("string"!=typeof t)return t;const s=e[t];if(void 0!==s)return s;const n=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 r=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!r?.groups)return;const{weeks:o,days:i,hours:c,minutes:a,seconds:u}=r.groups;if(!(o||i||c||a||u))return;const d=t=>t?Number(t.replace(",",".")):0;return 7*d(o)*24*60*60*1e3+24*d(i)*60*60*1e3+60*d(c)*60*1e3+60*d(a)*1e3+1e3*d(u)}(t);if(void 0===n)throw new Error(i(9,t));return n}function Oe(t,e,s){if("function"==typeof t)return t(s);const n=Te(t,e);return"function"==typeof n?n(s):n}function je(t,e){return t._stateInputs?.[e]}function Me(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function Re(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Pe(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 $e(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 Re(t))if(!e.has(s)){const t=Fe(s);for(const s of t)e.add(s)}}else for(const s of Fe(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 qe(t,e){const s=$e(e),n=new Map;for(const t of s)n.has(t)||n.set(t,[]),t.parent&&(n.has(t.parent)||n.set(t.parent,[]),n.get(t.parent).push(t));const r=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(Me(t))return t.key}const s={};for(const t of e)s[t.key]=r(t);return s};return r(t)}function De(t,e){return"compound"===e.type?Re(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?Re(e).every(e=>De(t,e)):"final"===e.type}const Ke=t=>"#"===t[0];function Le(t,e,s){const n=e.children[s];return!n||!("sessionId"in t)||(void 0===n.sessionId||n.sessionId===t.sessionId)}function Ne(t,e,s,n){const r=t.entry;t.entry=(t,e)=>{const o="function"==typeof r?r(t,e):void 0,i=void 0!==o?.context?gt(t.context,o.context):t.context;return e.raise(s(t),{delay:n({context:i,event:t.event,delays:t.delays,input:t.input})}),o};const o=t.exit;t.exit=(t,s)=>(s.cancel({event:K(e)}),"function"==typeof o?o(t,s):void 0)}function ze(t,e,s){const n=function(t){const{cond:e,actions:s,guard:n}=t;if(void 0!==e)return'"cond"';if(void 0!==s)return'"actions"';if(void 0!==n&&"function"!=typeof n)return'an object-form "guard"';return}(s);if(n)throw new Error(i(10,e||"always",t.id,n));const r=Us(s.target),o=s.reenter??!1,c=Je(t,r);Ue(t,c);const a={...s,target:c,source:t,reenter:o,eventType:e,toJSON:()=>Ve(a)};return a}function Ve(t){const{definition:e,...s}=t;return{...s,source:`#${t.source.id}`,target:t.target?.map(t=>`#${t.id}`)}}function Ce(t,e){for(let s=t.parent;s;s=s.parent)if(s===e)return!0;return!1}function We(t,e){const s=new Set;for(let e=t;e;e=e.parent)s.add(e);for(let t=e;t;t=t.parent)if(s.has(t))return t}function Ue(t,e){if(e&&!(e.length<2))for(let s=0;s<e.length;s++)for(let n=s+1;n<e.length;n++){const r=e[s],o=e[n],c=We(r,o);if(r===o||Ce(r,o)||Ce(o,r)||"parallel"!==c?.type)throw new Error(i(11,t.id))}}function Je(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(Ke(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return Ge(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(i(13,e));try{return Ge(t.parent,n)}catch(e){throw new Error(i(12,t.id,e.message))}})}function He(t){const e=Us(t.config.target);if(!e)return"parallel"===t.parent.type?{target:[t.parent],source:t,reenter:!1,eventType:""}:t.parent.initial;const s=e.map(e=>"string"==typeof e?Ge(t.parent,e):e);return Ue(t,s),{target:s,source:t,reenter:!1,eventType:"",to:t.config._historyDefaultTransition}}function Be(t){return"history"===t.type}function Fe(t){const e=new Set;!function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)for(const e of s.initial.target??[])t(e);else if("parallel"===s.type)for(const e of Re(s))t(e)}(t);for(const s of e)for(const n of Pe(s,t))e.add(n);return e}function Xe(t,e){const s=t.states?.[e];if(!s)throw new Error(i(14,e,t.id));return s}function Ge(t,e){if("string"==typeof e&&Ke(e))return t.machine.getStateNodeById(e);const s=Ds(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=Xe(n,t)}return n}function Qe(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(i(14,e,t.id));return[t,s]}const s=Object.keys(e),n=new Array(s.length),r=[t.machine.root,t];for(let e=0;e<s.length;e++){const o=Xe(t,s[e]);n[e]=o,r.push(o)}for(let t=0;t<s.length;t++)r.push(...Qe(n[t],e[s[t]]));return r}function Ye(t,e,s,n,r,o){if("string"==typeof e){const i=Xe(t,e).next(s,n,r,o);return i&&i.length?i:t.next(s,n,r,o)}const i=Object.keys(e),c=i[0];if(1===i.length){const i=Ye(Xe(t,c),e[c],s,n,r,o);return i&&i.length?i:t.next(s,n,r,o)}const a=[];for(const c of i){const i=e[c];if(!i)continue;const u=Ye(Xe(t,c),i,s,n,r,o);u&&a.push(...u)}return a.length?a:t.next(s,n,r,o)}function Ze(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function ts(t,e){for(const s of t)if(Ze(s,e))return!0;return!1}function es(t,e){const s=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,n=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==s&&void 0!==n&&n<s&&([t,e]=[e,t]);const r=t instanceof Set?t:new Set(t);for(const t of e)if(r.has(t))return!0;return!1}function ss(t,e,s,n){const r=new Set,o=new Map,i=t=>{let r=o.get(t);return r||(r=cs([t],e,s,n),o.set(t,r)),r};for(const e of t){let t=!1;const s=new Set;for(const n of r)if(es(i(e),i(n))){if(!Ze(e.source,n.source)){t=!0;break}s.add(n)}if(!t){for(const t of s)r.delete(t);r.add(e)}}return Array.from(r)}function ns(t,e,s,n,r){let o;return(i,c)=>{if(!i.to&&!c)return{targets:i.target,context:void 0,reenter:i.reenter,actions:void 0,internalEvents:void 0,input:void 0};let a=o?.get(i);return a||(a=us(i,t,e,s,{resolveActions:n,selectionResult:r?.get(i)}),(o??=new Map).set(i,a)),a}}function rs(t,e,s){const n=e.historyValue,{targets:r}=s(t);if(!r)return[];const o=new Set;for(const t of r)if(Be(t))if(n[t.id])for(const e of n[t.id])o.add(e);else for(const n of rs(He(t),e,s))o.add(n);else o.add(t);return[...o]}function os(t,e){let s=t;for(;"parallel"===s.type;){const t=Re(s).find(t=>e.every(e=>e===t||Ze(e,t)));if(!t)break;s=t}return s}function is(t,e,s){const n=rs(t,e,s),{targets:r,reenter:o}=s(t);if(t._transitionDomain){if("internal"===t._transitionDomain&&"compound"===t.source.type&&n.every(e=>Ze(e,t.source)))return t.source;const[e,...s]=n.concat(t.source);for(const t of Pe(e,void 0))if("compound"===t.type&&s.every(e=>Ze(e,t)))return t;return}if(!(r?.some(Be)&&n.some(e=>e===t.source))&&n.every(e=>e===t.source||Ze(e,t.source)))return o?t.source:os(t.source,n);const[i,...c]=n.concat(t.source);for(const t of Pe(i,void 0))if(c.every(e=>Ze(e,t)))return o?t:os(t,n);return o?void 0:os(t.source.machine.root,n)}function cs(t,e,s,n){const r=new Set;for(const o of t){const{targets:t,reenter:i}=n(o);if(t?.length){const t=is(o,s,n);i&&o.source===t&&r.add(t);for(const s of e)Ze(s,t)&&r.add(s)}}return[...r]}function as(t,e,s,n,r,o,c){const a=[],u=e.machine._microstepHooks?.drain(s.self);if(u?.length&&o.push(...u),!t.length)return[e,a];{const u=new Set(e.nodes);let d=e.historyValue;const h=e.context,f=1===t.length?t:ss(t,u,e,ns(e,n,s,!1,c)),l=ns(e,n,s,!0,c),p=f.some(t=>{const{targets:e,reenter:s}=l(t);return!!e?.length||!!s}),y=(t,r,o,i,c,a)=>{const u=[],d=[];let h;const f=Pt(s,u,d,!0),l=pe(s)?ve({context:r,event:n,output:Vs(n),children:o,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:i,stateNode:a},s):{context:r,event:n,output:Vs(n),parent:s.self._parent,self:s.self,children:o,system:s.system,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:i,stateNode:a};let p;try{p=t(l,f)}finally{qt(f)}return ls(p,n,a.id,c),void 0!==p?.context&&(h=gt(r,p.context)),[u,h,d,p?.children]};let v=e;const g=(t,e)=>{const n=[],r=Pt(s,n,[]);for(const s of t.invoke){const t=e[s.id];t&&r.stop(t)}return n},_=()=>{const t=cs(f,u,e,l);let n;t.sort((t,e)=>e.order-t.order);const r=[...u];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>Me(t)&&Ze(t,e):t=>t.parent===e;n??={...d},n[t.id]=r.filter(s)}for(const n of t){const t=je(e,n.id),[r,i,c,d]=n.exit?y(n.exit,v.context,v.children,t,"exit",n):[[],void 0,void 0,void 0];c?.length&&o.push(...c),(i||d)&&(v=Rs(v,{...i?{context:i}:{},...d?{children:d}:{}}));const[h,f]=Ut(v,0,s,r);v=h,a.push(...f);const l=g(n,v.children);if(l.length){const[t,e]=Ut(v,0,s,l);v=t,a.push(...e)}u.delete(n)}d=n||d};!r&&p&&_();let m=v.context;const x=[],w=[],b=[];for(const t of f){const e=l(t,!0);if(t.to){const s={...t,target:e.targets,definition:t};s.toJSON=()=>Ve(s),b.push(s)}else b.push(t);void 0!==e.context&&(m=gt(m,e.context)),e.actions&&x.push(...e.actions),e.internalEvents&&w.push(...e.internalEvents)}w.length&&o.push(...w);const S=()=>{const t=t=>{const e=v.machine.root;let r;if(void 0!==t.output&&t.parent){const i=o.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);r=i&&t.parent===e?i.output:zs(t.output,v.context,n,s.self,x[t.id])}else if("parallel"===t.type){const e=o.find(e=>"xstate.done.state"===e.type&&e.stateId===t.id);r=e?.output}return void 0===e.output?t.parent===e?r:void 0:zs(e.output,v.context,O(t.id,r),s.self)},c=new Set,h=new Set,p=new Map,g=(t,e)=>{for(const s of t)if(e&&!Ze(s,e)||c.add(s),"parallel"===s.type)for(const t of Re(s))ts(c,t)||(c.add(t),_(t))},_=t=>{if(Be(t))if(d[t.id]){const e=d[t.id];for(const t of e)c.add(t),_(t);for(const s of e)g(Pe(s,t.parent),void 0)}else{const e=He(t),s=t.parent;h.add(s);const n=p.get(s)??[];n.push(e),p.set(s,n);const{targets:r}=l(e);for(const s of r??[])c.add(s),e===t.parent?.initial&&h.add(t.parent),_(s);for(const e of r??[])g(Pe(e,t.parent),void 0)}else{if("compound"===t.type){const e=l(t.initial).targets??[];for(const t of e)Be(t)||c.add(t);h.add(t);for(const t of e)_(t);for(const s of e)g(Pe(s,t),void 0);return}if("parallel"===t.type)for(const e of Re(t))ts(c,e)||(c.add(e),h.add(e),_(e))}},m=new Map;for(const t of f){const s=is(t,e,l),{targets:n,reenter:r}=l(t),o=new Set;m.set(t,o);for(const e of n??[])Be(e)||t.source===e&&t.source===s&&!r||(o.add(e),c.add(e),h.add(e)),_(e);const i=rs(t,e,l);for(const e of i){const n=Pe(e,s);"parallel"===s?.type&&n.push(s),g(n,!t.source.parent&&r?void 0:s)}n?.length&&r&&s===t.source&&c.add(t.source)}if(r)for(const t of f[0]._statesForDefaultEntry??[e.machine.root])h.add(t);const x={};let w=!1;const b=new Set([...u].map(t=>t.id));for(const[t,s]of Object.entries(e._stateInputs??{}))b.has(t)?x[t]=s:w=!0;for(const t of f){const{targets:e,input:s}=l(t,!0);if(s&&e)for(const n of e.filter(e=>m.get(t)?.has(e)))x[n.id]=s,w=!0}const S=new Set;for(const r of[...c].sort((t,e)=>t.order-e.order)){u.add(r);const c=[];let d=v.children,f=!1;for(const t of"final"===r.type?[]:r.invoke){f=!0;let o=t.logic;"function"==typeof o&&(o=o({actors:e.machine.sources.actors,context:v.context,event:n,self:s.self}));const a="string"==typeof o?e.machine.sources.actors[o]:o;if(!a)throw new Error(i(15,"string"==typeof o?o:"inline"));const u="function"==typeof t.input?t.input({self:s.self,context:v.context,event:n,input:x[r.id],output:Vs(n)}):t.input;Ot(s,t.id);const h=s.system.createActorRef(a,{...t,src:"string"==typeof o?o:void 0,input:u,parent:s.self,syncSnapshot:!!t.onSnapshot});h._invoked=!0,c.push({action:H["@xstate.spawn"],args:[h]}),t.id&&(d={...d,[t.id]:h})}f&&(v=Rs(v,{children:d}));let l=v.context,g=!1;const _=x[r.id];if(r.entry){const[t,e,s,n]=y(r.entry,l,d,_,"entry",r);c.push(...t),s?.length&&o.push(...s),e&&(l=e,g=!0),n&&(v=Rs(v,{children:n}))}if(g&&(v=Rs(v,{context:l})),h.has(r)){const t=[r.initial,...p.get(r)??[]].filter(Boolean);for(const e of t){const{actions:t,context:r,input:i,internalEvents:a}=us(e,v,n,s);if(t&&c.push(...t),a?.length&&o.push(...a),void 0!==r&&(v=Rs(v,{context:gt(v.context,r)})),i&&e.target)for(const t of e.target)x[t.id]=i,w=!0}}const[m,b]=Ut(v,0,s,c);if(v=m,c.length=0,a.push(...b),"final"!==r.type)continue;const I=r.parent;let E="parallel"===I?.type?I:I?.parent,A=E||r;for("compound"===I?.type&&o.push(O(I.id,void 0!==r.output?zs(r.output,v.context,n,s.self,_):void 0));"parallel"===E?.type&&!S.has(E)&&De(u,E);){S.add(E);const t={};for(const e of Re(E)){if("final"===e.type){t[e.key]=void 0!==e.output?zs(e.output,v.context,n,s.self,x[e.id]):void 0;continue}if("parallel"===e.type){const s=o.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);t[e.key]=s?.output;continue}const r=Re(e).find(t=>"final"===t.type&&u.has(t));t[e.key]=void 0!==r?.output?zs(r.output,v.context,n,s.self,x[r.id]):void 0}o.push(O(E.id,t)),A=E,E=E.parent}E||(v=Rs(v,{status:"done",output:t(A)}))}w&&(v=Rs(v,{_stateInputs:x}))},[I,E]=Ut(v,0,s,x);v=I,a.push(...E),m&&m!==e.context&&(v=Rs(v,{context:m}));const A=v.machine._microstepHooks?.transitionContent?.(f,[...u]);if(A){const t=f[0].source,[e,n,r,i]=y(A,v.context,v.children,je(v,t.id),"transition",t);r?.length&&o.push(...r),(n||i)&&(v=Rs(v,{...n?{context:n}:{},...i?{children:i}:{}}));const[c,u]=Ut(v,0,s,e);v=c,a.push(...u)}(r||p)&&S();const k=[...u];if("done"===v.status){const t=[];k.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=je(v,e.id),[n,r,i,c]=y(e.exit,v.context,v.children,s,"exit",e);(r||c)&&(v=Rs(v,{...r?{context:r}:{},...c?{children:c}:{}})),t.push(...n),i?.length&&o.push(...i)}});const[e,r]=Ut(v,0,s,t);v=e,a.push(...r);const[i,c]=ys(v,n,s);v=i,a.push(...c);const[u,d]=vs(v,n,s);v=u,a.push(...d)}return d===e.historyValue&&e.nodes.length===u.size&&e.nodes.every(t=>u.has(t))?v.context!==h?[v===e?Rs(v):v,a,b]:[v,a,b]:[Rs(v,{_nodes:k,historyValue:d}),a,b]}}function us(t,e,s,n,r){let o;const i=()=>o??=pe(n)?ve({context:e.context,event:s,output:Vs(s),value:e.value,children:e.children,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:je(e,t.source.id)},n):{context:e.context,event:s,output:Vs(s),value:e.value,children:e.children,system:n.system,parent:n.self._parent,self:n.self,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:je(e,t.source.id)};if(t.to){const o=[],c=[];let a;if(!r?.selectionResult?.reusable||!1!==r.resolveActions&&0!==r.selectionResult.operations.length){const e=Pt(n,o,c,!0,r?.resolveActions??!0),u=!1===r?.resolveActions?D(ye(n),"suppress"):void 0;try{if(r?.selectionResult?.reusable){a=r.selectionResult.result;for(const t of r.selectionResult.operations)t(e)}else a=t.to(i(),e),ls(a,s,t.source.id)}finally{u?.close(),qt(e)}}else a=r.selectionResult.result;const u=a?.target?Je(t.source,Ns(a.target)):void 0,d=a?.input??("function"==typeof t.input?t.input({context:e.context,event:s,output:Vs(s)}):t.input);return{targets:u,context:a?.context,reenter:a?.reenter,actions:o,internalEvents:c,input:d}}const c="function"==typeof t.input?t.input({context:e.context,event:s,output:Vs(s)}):t.input,a="function"==typeof t.context?t.context(i()):t.context;return{targets:t.target,context:a,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:c}}class ds extends Error{constructor(t,e,s,n){super(i(16,t,e.type,s)),this.actorId=void 0,this.event=void 0,this.maxIterations=void 0,this.states=void 0,this.name="InfiniteTransitionError",this.actorId=t,this.event=e,this.maxIterations=s,this.states=n.slice()}}function hs(t,e,s,n,r=[]){if("active"!==t.status&&!r.length)return{snapshot:t,microsteps:[[t,[],[]]]};let o=t;const i=r.slice();let c=!1;function h(t){if("xstate.done.actor"!==t.type&&"xstate.error.actor"!==t.type)return;const{actorId:e,sessionId:n}=t;if(!e)return;const r=o.children[e];if(!r)return;if(void 0!==r.sessionId&&r.sessionId!==n)return;const c={...o.children};if(delete c[e],s.system._unregister(r),o=Rs(o,{children:c}),i.length){const[,t,e]=i.at(-1);i[i.length-1]=[o,t,e]}else i.push([o,[],[]])}function l(){if(c&&o===t&&(o=Rs(t,{}),i.at(-1)?.[0]===t)){const[,t,e]=i.at(-1);i[i.length-1]=[o,t,e]}const e=function(t){const e=[],s=[];for(const n of t){if(!Wt(n)||n.type!==u)continue;const{actor:t,logic:r}=n,o=Lt(t);r===et||r===nt?e.push(o):s.push(o)}return[...e,...s]}(i.flatMap(([,t])=>t)),n=("active"===t.status||r.length>0)&&("done"===o.status||"error"===o.status);if(e.length||n){const t=n?[...e,Vt(s,o)]:e;if(i.length){const[e,s,n]=i.at(-1);i[i.length-1]=[e,[...s,...t],n]}else i.push([o,t,[]])}return{snapshot:o,microsteps:i}}function p(t,n){if(n=t[2]??n,!_e(s)&&(e.type===a||(s.system._hasInspectionObservers?.()??1))){const t=s.self._collectedMicrosteps||[];t.push(...n),s.self._collectedMicrosteps=t}i.push([t[0],t[1],n])}if(e.type===d){const[t,n]=ys(o,e,s),[r,i]=vs(t,e,s);return o=Rs(r,{status:"stopped"}),p([o,[...n,...i]],[]),l()}let y=e;if(e.type===f){const t=N(e),r=t?o.timers.findIndex(e=>z(e,t)):-1;if(-1===r)return l();const i=o.timers[r],c=o.timers.filter((t,e)=>e!==r);if(o=Rs(o,{timers:c}),"@xstate.raise"===i.type)n.push(i.event),p([o,[]],[]);else{const t="self"===i.target?s.self:i.target;p([o,[zt(s,t,i.event)]],[])}}if(y.type!==a&&y.type!==f){const e=y,r=function(t){return t.type.startsWith("xstate.error.")}(e),i=new Map,a=o.machine.getTransitionData(o,e,s,i);if(r&&!a.length)return"xstate.error.actor"!==e.type||Le(e,o,e.actorId)?(o=Rs(t,{status:"error",error:e.error}),p([o,[]],[]),h(e),l()):l();c=a.length>0;const u=as(a,t,s,y,!1,n,i);o=u[0],p(u,a),h(e)}if(!n.length&&!1===t.machine._hasEventlessTransitions)return l();let v=e.type!==f;const g=t.machine.options?.maxIterations??1/0;let _=0;const m=[];for(;"active"===o.status;){if(_++,_>g)throw new ds(s.self?.id,e,g,m);let t;m.push(o.value),m.length>5&&m.shift();let r=v?gs(o,y,s):[];const i=r.length?o:void 0,c=o.machine._microstepHooks?.drain(s.self);if(c?.length&&n.push(...c),!r.length){if(!n.length)break;y=n.shift(),t=new Map,r=o.machine.getTransitionData(o,y,s,t)}const a=as(r,o,s,y,!1,n,t);o=a[0],v=o!==i,p(a,r),h(y)}return l()}function fs(t,e,s,n,r){return!!t.to&&ps(t.to,e,s,n,r,n.machine.sources,t.source.id).enabled}function ls(t,e,s,n){if(t&&"function"==typeof t.then)throw Promise.resolve(t).catch(()=>{}),new Error(i(17,n??"transition",s,e.type))}function ps(t,e,s,n,r,o,i){let c;const a=function(t){const e=D(t),{frame:s}=e,n=[];let r=!1;const o=t=>{r||n.push(t)},i=()=>{if(!r)throw s.requiresReevaluation=!0,q},c=Jt({cancel:(...t)=>o(e=>e.cancel(...t)),emit:(...t)=>o(e=>e.emit(...t)),log:(...t)=>o(e=>e.log(...t)),raise:(t,e)=>{r||(Rt(t),o(s=>s.raise(t,e)))},sendTo:(...t)=>o(e=>e.sendTo(...t)),stop:(...t)=>o(e=>e.stop(...t)),spawn:i,listen:i,subscribeTo:i},(...t)=>o(e=>e(...t)));return{frame:s,enqueue:c,operations:n,close(){r=!0,e.close()}}}(ye(r));try{c=t(ve({context:e,event:s,output:Vs(s),value:n.value,children:n.children,actions:o.actions,actors:o.actors,guards:o.guards,delays:o.delays,input:je(n,i)},r),a.enqueue)}catch(t){if(t===q)return{enabled:!0,result:void 0,reusable:!1};throw t}finally{a.close()}return ls(c,s,i),a.frame.requiresReevaluation?{enabled:!0,result:void 0,reusable:!1}:{enabled:void 0!==c||a.operations.length>0,result:c,reusable:!0,operations:a.operations}}function ys(t,e,s){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return[t,[]];const r=[],o=Pt(s,r,[]);for(const t of n)o.stop(t);return Ut(t,0,s,r)}function vs(t,e,s){if(!t.timers.length)return[t,[]];const n=[],r=Pt(s,n,[]);for(const e of t.timers)r.cancel(L(e));return Ut(t,0,s,n)}function gs(t,e,s){t.machine._microstepHooks?.begin(s.self);const n=new Set,r=t.nodes.filter(Me);for(const o of r)t:for(let r=o;r;r=r.parent)if(r.always)for(const o of r.always)if(_s(o,e,t,r,s)){n.add(o);break t}return ss(Array.from(n),new Set(t.nodes),t,ns(t,e,s,!1))}function _s(t,e,s,n,r,o){if(t.matches&&!function(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}(e,t.matches))return!1;if(t._eventMatcher&&!t._eventMatcher(e,s))return!1;if(t.guard){const o=function(t,e){if(!pe(e)){const s=e.self;return Object.assign(t,{self:s,parent:s._parent})}return Object.defineProperties(t,{self:{enumerable:!0,get:()=>e.self},parent:{enumerable:!0,get:()=>ye(e)}}),t}({context:s.context,event:e,output:Vs(e),children:s.children,actions:n.machine.sources.actions,actors:n.machine.sources.actors,guards:n.machine.sources.guards,delays:n.machine.sources.delays,_snapshot:s},r);if(!t.guard(o))return!1}if(t.to){const i=ps(t.to,s.context,e,s,r,n.machine.sources,t.source.id);return o?.set(t,i),i.enabled}return!0}const ms=Object.freeze({}),xs=Object.freeze([]);function ws(t){return t?.length?t:xs}function bs(t){return t===ms||t&&Object.keys(t).length?t:ms}function Ss(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const Is=function(t){if("string"==typeof t&&Ke(t)){const e=this.machine.getStateNodeById(t);return this.nodes.includes(e)}return qs(t,this.value)},Es=function(t){return this.tags.has(t)},As=function(t){return this.machine?._canTransition(this,t)??!1},ks=function(){const{nodes:t,_stateInputs:e,_nextTimerId:s,_nextActorIds:n,tags:r,machine:o,getMeta:i,getInputs:c,toJSON:a,can:u,hasTag:d,matches:h,...f}=this;return{...f,tags:Array.from(r)}},Ts=function(){const t={};for(const e of this.nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},Os=function(){return this._stateInputs};function js(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function Ms(t,e,s){const n={status:t.status,output:t.output,error:t.error,machine:e,context:t.context,nodes:t._nodes,value:t.value??qe(e.root,t._nodes),tags:js(t._nodes),children:bs(t.children),timers:ws(t.timers),historyValue:bs(t.historyValue),_stateInputs:bs(t._stateInputs),_nextTimerId:t._nextTimerId??0,_nextActorIds:t._nextActorIds,matches:Is,hasTag:Es,can:As,getMeta:Ts,getInputs:Os,toJSON:ks};return s&&fe(n,s),n}function Rs(t,e={}){const s={...t,...e};if((e._nodes??t.nodes)===t.nodes){const e={status:s.status,output:s.output,error:s.error,machine:t.machine,context:s.context,nodes:t.nodes,value:t.value,tags:t.tags,children:bs(s.children),timers:ws(s.timers),historyValue:bs(s.historyValue),_stateInputs:bs(s._stateInputs),_nextTimerId:s._nextTimerId??0,_nextActorIds:s._nextActorIds,matches:Is,hasTag:Es,can:As,getMeta:Ts,getInputs:Os,toJSON:ks};return he(t,e),e}const n=Ms({...s,value:void 0},t.machine);return he(t,n),n}function Ps(t){const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map(t=>({id:t.id})))}return e}function $s(t,e,s="context",n=[]){let r;n.push(t);for(const o in t){const c=t[o];if(c&&"object"==typeof c)if(Hs(c))r??=Array.isArray(t)?t.slice():{...t},r[o]={"@actor":c.address};else{const a=Array.isArray(t)?`${s}[${o}]`:`${s}.${o}`;if(n.includes(c))throw new Error(i(44,e(),a));const u=$s(c,e,a,n);u!==c&&(r??=Array.isArray(t)?t.slice():{...t},r[o]=u)}}return n.pop(),r??t}function qs(t,e){const s=Ks(t),n=Ks(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&qs(s[t],n[t]))}function Ds(t){if(Cs(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+="."===t[n+1]?"\\.":t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function Ks(t){if(Ss(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}(Ds(t))}function Ls(t){return Cs(t)?t:[t]}function Ns(t){return void 0===t?[]:Ls(t)}function zs(t,e,s,n,r){if("function"==typeof t){return t({context:e,event:s,output:Vs(s),self:n,input:r})}return t}function Vs(t){if(function(t){return"xstate.done.actor"===t.type||"xstate.done.state"===t.type}(t)){return t.output}}function Cs(t){return Array.isArray(t)}function Ws(t,e,s){return Ls(t).map(t=>{if("string"==typeof t)throw new Error(i(38,e,s,t));return void 0===t?{target:void 0}:"function"==typeof t?{to:t}:t})}function Us(t){if(void 0!==t&&""!==t)return Ns(t)}function Js(t,e,s){const n="object"==typeof t,r=n?t:void 0;return{next:(n?t.next:t)?.bind(r),error:(n?t.error:e)?.bind(r),complete:(n?t.complete:s)?.bind(r),...n&&t.passive?{passive:!0}:{}}}function Hs(t){return"sessionId"in t&&"send"in t&&"ref"in t}function Bs(t,e,s){const n=[];for(const t of e)for(const e of t.invoke)e.id===s&&n.push(e);if(1!==n.length)throw new Error(i(39,s));const r=n[0].logic;if("string"==typeof r){const e=t.sources.actors[r];if(!e)throw new Error(i(29,s,r));return e}if("function"==typeof r)throw new Error(i(40,s));return r}function Fs(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],r=n[t];if("*"===e){return t===s.length-1}if(e!==r)return!1}return!0}let Xs,Gs,Qs=0;function Ys(){return Xs??=function(){let t;try{t=globalThis.crypto}catch{}if(t?.getRandomValues)try{const e=new Uint32Array(4);return t.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(7,"0")).join("")}catch{}if(t?.randomUUID)try{return t.randomUUID().replaceAll("-","")}catch{}return`xstate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}(),`${Xs}:${(Qs++).toString(36)}`}function Zs(t,e){if(!t)return e();const s=Gs;Gs=t;try{return e()}finally{Gs=s}}function tn(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length?e:"x"}function en(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function sn(t){const e=t.lastIndexOf(":");if(e<=0||e===t.length-1)return;const s=Number(t.slice(e+1));return Number.isSafeInteger(s)&&s>=0?{prefix:t.slice(0,e),index:s}:void 0}function nn(t,e){return`${t?t.address:""}|${e}`}function rn(t,e,s){const n=t._snapshot._nextActorIds;(n[e]??0)>=s||(t._snapshot._nextActorIds={...n,[e]:s},oe(t))}const on=["spawnActor","startActor","stopActor","terminateActor","emitEvent","scheduleTimer","cancelTimer","cancelAllTimers","deadLetter"],cn=Object.freeze({});function an(t,e){return V(t,e)}function un(t,e){return t.getSnapshot()?.timers?.find(t=>z(t,e))}class dn{get children(){const t=this._children??=new Map;return this._getRootActor()&&t.set(this._rootActor.sessionId,this._rootActor),t}set children(t){this._children=t}_getRootActor(){return this._rootActor._isRunning()?this._rootActor:void 0}_peekChildren(){return this._children}get keyedActors(){return this._keyedActors??=new Map}set keyedActors(t){this._keyedActors=t}get reverseKeyedActors(){return this._reverseKeyedActors??=new WeakMap}set reverseKeyedActors(t){this._reverseKeyedActors=t}_peekKeyedActors(){return this._keyedActors}constructor(t,e){this._rootActor=t,this._identity=Gs??{executionId:Ys(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0,this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef;const s=Gt();s&&this.inspect(s),this._snapshot={_scheduledTimers:cn,_nextActorIds:{}}}_recordSent(t,e,s,n,r){if(!this._inspectionObservers?.size||!t)return;const o=t;if(!o._inTransition)return;(o._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:r})}schedule(t,e,s){const n=an(t,e);void 0!==this._timerMap?.[n]&&this.cancel(t,e);const r=un(t,e);if(r){const e="self"===r.target?t:r.target;this._recordSent(t,e,r.event,s,r.id)}const o=this._clock.now?.()??Date.now(),i={source:t,delay:s,key:e,scheduledAt:o,dueAt:o+s};this._snapshot._scheduledTimers===cn&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[n]=i,oe(this);const c=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[n],delete this._snapshot._scheduledTimers[n],oe(this),this._deliver(t,t,{type:f,...e})},s);(this._timerMap??={})[n]=c}cancel(t,e){const s=an(t,e),n=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==cn&&delete this._snapshot._scheduledTimers[s],oe(this),void 0!==n&&this._clock.clearTimeout(n)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.key)}}_deliver(t,e,s){I(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),oe(this),t}_getByAddress(t){const e=this._getRootActor();if(e?.address===t)return e;for(const e of this._children?.values()??[])if(e.address===t&&e._isRunning())return e}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1);const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&oe(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,e){const s=this._keyedActors?.get(t);if(s&&s!==e)throw new Error(i(45,String(t)));(this._keyedActors??=new Map).set(t,e),(this._reverseKeyedActors??=new WeakMap).set(e,t),s!==e&&oe(this)}inspect(t){const e=Js(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}onRejectedEvent(t){const e=e=>t(e);return(this._rejectionListeners??=new Set).add(e),{unsubscribe:()=>{this._rejectionListeners?.delete(e)}}}onEmitted(t){const e=e=>t(e);return(this._emissionListeners??=new Set).add(e),{unsubscribe:()=>{this._emissionListeners?.delete(e)}}}_notifyEmitted(t,e){const s=this._emissionListeners;if(!s?.size)return;const n={actorRef:t,event:e};for(const t of Array.from(s))try{t(n)}catch(t){R(t)}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>{try{t.next?.(e)}catch(t){R(t)}})}spawnActor(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);!function(t){t._stop()}(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);!function(t,e){t._terminate(e)}(t,e)}sendEvent(t,e,s){if(y(e)){const n=_(this,e);if(n)e=n;else if(this._getByAddress(e["@actor"])||!this.runtime?.sendEvent)return this.deadLetter(t,void 0,s,"missingTarget",{targetId:v(e["@actor"]),error:g(e)})}if(E(t,e,s))return;this._recordSent(t,e,s);const n=this.runtime?.sendEvent;if(n)return n(t,e,s);this._deliver(t,e,s)}emitEvent(t,e){const s=this.runtime?.emitEvent;if(s)return s(t,e);t._emit(e)}deadLetter(t,e,s,n,r){const o=this._rejectionListeners;if(o?.size){const i={event:s,targetRef:e,targetId:e?.id??r?.targetId,sourceRef:t,eventOrigin:t?"actor":"external",reason:n,issues:r?.issues,error:r?.error};for(const t of[...o])try{t(i)}catch(t){R(t)}}const i=this.runtime?.deadLetter;if(i)return i(t,e,s,n,r)}runStep(t,e,s){const n=this.runtime?.runStep;return n?n(t,e,s):S(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const n=this.runtime?.scheduleTimer;if(n){const r=un(t,e);if(r){const e="self"===r.target?t:r.target;this._recordSent(t,e,r.event,s,r.id)}return n(t,e,s)}this.schedule(t,e,s)}cancelTimer(t,e){const s=this.runtime?.cancelTimer;if(s)return s(t,e);this.cancel(t,e)}cancelAllTimers(t){const e=this.runtime?.cancelAllTimers;if(e)return e(t);this.cancelAll(t)}_relay(t,e,s){if(!function(t){let e=!1,s=!1;for(const n of $)n.parent===t&&(n.requiresReevaluation=!0,e=!0,s||="abort"===n.mode);if(s)throw q;return e}(e))return this.sendEvent(t,e,s)}getSnapshot(){return{_scheduledTimers:{...this._snapshot._scheduledTimers}}}start(){const t=this._snapshot._scheduledTimers;let e=!0;for(const s in t){e&&(this._snapshot._scheduledTimers={},e=!1);const{source:n,dueAt:r,key:o}=t[s];this.scheduleTimer(n,o,Math.max(0,r-(this._clock.now?.()??Date.now())))}}}let hn=!1;const fn=Object.freeze([]),ln={"xstate.done.actor":!0,"xstate.error.actor":!0,"xstate.error.execution":!0,"xstate.snapshot.actor":!0,"xstate.done.state":!0,"xstate.after":!0,"xstate.timeout.state":!0,"xstate.timeout.actor":!0,[f]:!0};let pn=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const yn=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function vn(t,e){try{t?.(e)}catch(t){R(t)}}function gn(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function _n(t,e){return new mn(t,e)}class mn{get address(){return this._address??=this._parent?`${this._parent.address}/${en(this.id)}`:en(this.id)}get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this._errorObserved=!1,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=pn.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,this._inTransition=!1,this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this._address=void 0,this.system=void 0,this._trigger=void 0,this._boundSend=void 0,this.src=void 0,this._deferred=void 0,this._restored=!1,this._warnedUnhandledTypes=void 0;const s=e?{...yn,...e}:yn,{clock:n,logger:r,parent:o,syncSnapshot:i,id:c,registryKey:a,inspect:u}=s;var d;this.system=o?o.system:s._systemRef?.current??function(t,e){return new dn(t,e)}(this,{clock:n,logger:r,createActorRef:_n}),o||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system,s._systemRef.initialize?.()),u&&!o&&this.system.inspect(Js(u)),s.onRejectedEvent&&!o&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(d=this.system)._identity.executionId}:${d._identity.nextSessionId++}`,this.id=function(t,e,s){if(void 0!==e){const n=sn(e);return n?rn(t,nn(s?.parent,n.prefix),n.index+1):s?.parent||rn(t,nn(void 0,e),1),e}const n=tn(s?.src),r=nn(s?.parent,n),o=t._snapshot._nextActorIds[r]??0;return rn(t,r,o+1),s?.parent||"x"===n||0!==o?`${n}:${o}`:n}(this.system,c,{parent:o,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=o,this._syncSnapshot=i,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope=this,a&&(this.registryKey=a,this.system._set(a,this)),this._collectedMicrosteps=void 0;const h=s._restore;this._restored=void 0!==h;try{if(h)this._setSnapshot(h.restore(this._actorScope));else if(e?._inert);else{this._inTransition=!0;try{const[t,e]=Ct(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}finally{this._inTransition=!1}}}catch(t){this._setSnapshot(h?.error?.(t)??{status:"error",output:void 0,error:t}),this._deferred&&(this._deferred.length=0)}a&&"active"!==this._snapshot.status&&this.system._unregister(this),(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_getLogger(){return this.logger}get self(){return this}get defer(){const t=t=>this._defer(t);return Object.defineProperty(this,"defer",{value:t}),t}get stopChild(){const t=t=>this._stopChild(t);return Object.defineProperty(this,"stopChild",{value:t}),t}get emit(){const t=t=>w(this,t,this.system);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===pn.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(i(47,t.id,this.id));t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=hn;try{hn=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==pn.Stopped&&this._recoverOrError(t)})}finally{hn=e}};this._processingStatus!==pn.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,fe(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e,s){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t,s),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;const n=this._inTransition;this._inTransition=!0;try{const[t,n]=Ct(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),gn(n,this._actorScope),this.update(t,s),!0}catch{return!1}finally{this._inTransition=n}}_next(t){for(const e of this.observers??fn)vn(e.next,t)}update(t,e){this._setSnapshot(t);const s=this._deferred;for(let e=0;e<(s?.length??0);e++){const n=s[e];try{n()}catch(e){if(s.length=0,this._tryHandleExecutionError(e,t))return;this._setErrorSnapshot(e,t),this._error(e);break}}if(s&&(s.length=0),"active"===this._snapshot.status)this._next(t);this._inspectTransition(this._snapshot,e)}_inspectTransition(t,e){(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps??fn,actions:this._collectedActions??fn,sent:this._collectedSent??fn,eventType:e.type}),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0}_flushInitialEffects(){if(!this._initialEffects?.length)return!0;this._forceDeferredActions=!0;try{return gn(this._initialEffects,this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred&&(this._deferred.length=0),this._recoverOrError(t),"active"===this._snapshot.status}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const n=Js(t,e,s);if(this._processingStatus!==pn.Stopped)(this.observers??=new Set).add(n);else switch(this._snapshot.status){case"done":vn(n.complete);break;case"error":{const t=this._snapshot.error;n.error?(n.passive||(this._errorObserved=!0),vn(n.error,t)):R(t);break}}return{unsubscribe:()=>{this.observers?.delete(n)}}}on(t,e){let s=this.eventListeners?.get(t);return s||(s=new Set,(this.eventListeners??=new Map).set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,r)=>{const o=Js(s,n,r);let i=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(i,n)||(i=n,o.next?.(n))},error:o.error,complete:o.complete})},get:()=>t(this.getSnapshot())}}start(){const t=this._inTransition;this._inTransition=!0;try{return this._start()}finally{this._inTransition=t}}_start(){if(this._processingStatus===pn.Running)return this;if(this._processingStatus===pn.Stopped){const t=this._snapshot.status;if("done"===t||"error"===t)return this;throw new Error(i(48,this.id))}this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=pn.Running,this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this._restored?(this._next(this._snapshot),this._stopProcedure(),this._complete(),this):this._flushInitialEffects()?(this.update(this._snapshot,M(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this;case"stopped":return this._stopProcedure(),this._complete(),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,M(this.options.input)):(function(t,e,s){const n=ee.get(t),r=ie(s);return n?.actor===e&&n.systemState.sourceSystem===s&&n.systemState.sourceVersion+1===r&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(n.systemState.root=e,n.systemState.sourceVersion=r,!0)}(this._snapshot,this,this.system)||this._setSnapshot(this._snapshot),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0),this._restored){const t=this._snapshot.timers??[],e=!this.system._clock.now,s=Date.now();for(const n of t){const t=e&&void 0!==n.scheduledAt?Math.min(n.delay,Math.max(0,n.scheduledAt+n.delay-s)):n.delay;this.system.scheduleTimer(this,L(n),t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){const e=this._inTransition;this._inTransition=!0;try{this._processEvent(t)}finally{this._inTransition=e}}_processEvent({event:t,sourceRef:e}){this._lastSourceRef=e;const s=this._snapshot;let n,r;try{n=Ct(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){r={err:t}}if(r)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(r.err)||this._inspectTransition(this._snapshot,t));if(!n)return;let o=this._snapshot;try{const[r,i]=n;r!==s||i.length||!("machine"in s)||t.type===d||e&&Object.hasOwn(ln,t.type)||this._reportUnhandledEvent(t),o=r,this._setSnapshot(o),gn(i,this._actorScope),this.update(o,t)}catch(e){return void(this._recoverOrError(e,o,s)||this._inspectTransition(this._snapshot,t))}t.type===d&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){vn(()=>this.options.onUnhandledEvent?.(t,this._snapshot))}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)vn(s,t)}_terminate(t){if("done"===t.status)return this._next(this._snapshot),this._stopProcedure(),this._complete(),void(this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t.output,n=this.sessionId,{type:"xstate.done.actor",output:s,actorId:e,sessionId:n})));var e,s,n;"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===pn.Stopped?this:(this.mailbox?.clear(),this._processingStatus===pn.NotStarted?(this._processingStatus=pn.Stopped,this.system._unregister(this),this):(this._send({type:d}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error(i(49,this.id));return this._stop()}_complete(){for(const t of this.observers??fn)vn(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||R(t)})}_error(t,e){this._stopProcedure();const s=new Set;for(const t of[this._snapshot,e]){const e=t?.children;for(const t of Object.values(e??{}))t?._parent===this&&"function"==typeof t.getSnapshot&&s.add(t)}for(const t of this.system._peekChildren?.()?.values()??[])t._parent===this&&s.add(t);for(const t of s)try{if("active"!==t.getSnapshot().status)continue;const e=this.system.stopActor(t);e&&Promise.resolve(e).catch(R)}catch(r){R(r)}if(this.observers?.size){let e=!1,s=!1;for(const n of this.observers){const r=n.error;n.passive||(e||=!r,s||=!!r),vn(r,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);var n,r,o;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(n=this.id,r=t,o=this.sessionId,{type:"xstate.error.actor",error:r,actorId:n,sessionId:o}))}_stopProcedure(){this._processingStatus===pn.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=pn.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===pn.Stopped)return void this.system.deadLetter(e,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new A(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue({event:t,sourceRef:e})}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{"@actor":this.address}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[P](){return this}getSnapshot(){return this._snapshot}}function xn(t,...[e]){return function(t){if(t&&"object"==typeof t)for(const e of Object.keys(t))if(!c.has(e))throw new Error(i(8,e))}(e),new mn(t,e)}class wn extends Error{constructor(t){super(t),this.name="InvalidSnapshotError"}}function bn(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function Sn(t){return bn(t)&&"function"==typeof t.transition&&"function"==typeof t.getInitialSnapshot}function In(t,e,s,n){if("string"==typeof e){if(!s.states[e])throw new wn(i(21,n.concat(e).join(".")));return}const r=t=>new wn(i(22===t?22:23,n.join(".")));if(!e||"object"!=typeof e||Array.isArray(e))throw r(22);const o=Object.keys(e);if(o.length>1&&"parallel"!==s.type)throw r(23);for(const r of o){const o=s.states[r];if(!o)throw new wn(i(21,n.concat(r).join(".")));In(t,e[r],o,n.concat(r))}}function En(t,e){if(!bn(e))throw new wn(i(24,t.id));if(void 0===e.value)throw new wn(i(25,t.id));In(t,e.value,t.root,[]);const s=Array.from($e(Qe(t.root,e.value)));if(!bn(e.children))throw new wn(i(26));const n=new Map;for(const[r,o]of Object.entries(e.children)){if(!bn(o)||void 0!==o.remote&&"boolean"!=typeof o.remote||void 0!==o.address&&"string"!=typeof o.address||void 0!==o.syncSnapshot&&"boolean"!=typeof o.syncSnapshot||void 0!==o.registryKey&&"string"!=typeof o.registryKey||void 0!==o.incarnation&&"string"!=typeof o.incarnation||void 0!==o.snapshot&&!bn(o.snapshot))throw new wn(i(27,r));if(!0!==o.remote){if(void 0!==o.src&&"string"!=typeof o.src&&!Sn(o.src))throw new wn(i(27,r));try{const e=void 0===o.src?Bs(t,s,r):"string"==typeof o.src?Object.hasOwn(t.sources.actors,o.src)?t.sources.actors[o.src]:void 0:o.src;if(!e)throw new wn(i(29,r,"string"==typeof o.src?o.src:"<inline>"));n.set(r,e)}catch(t){if(t instanceof wn)throw t;throw new wn(t instanceof Error?t.message:i(30,r))}}else if("string"!=typeof o.address||"string"!=typeof o.src)throw new wn(i(28,r))}if(void 0!==e.timers&&!Array.isArray(e.timers))throw new wn(i(31));for(const t of e.timers??[]){if(!bn(t)||"number"!=typeof t.delay||"@xstate.raise"!==t.type&&"@xstate.sendTo"!==t.type||!bn(t.event)||"string"!=typeof t.event.type||void 0!==t.id&&"string"!=typeof t.id||void 0!==t.seq&&"number"!=typeof t.seq||void 0!==t.scheduledAt&&"number"!=typeof t.scheduledAt||!("string"==typeof t.target||bn(t.target)&&"parent"===t.target.type||y(t.target)))throw new wn(i(32));if("string"==typeof t.target&&"self"!==t.target&&!Object.hasOwn(e.children,t.target))throw new wn(i(33,t.target))}return{nodes:s,childLogics:n}}const An=new WeakMap;const kn={};class Tn{constructor(t,e){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.schemas=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.invoke=void 0,this.on=void 0,this.after=void 0,this.events=void 0,this.ownEvents=void 0,this._candidateCache=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.parent&&function(t){for(let e=0;e<t.length;e++)if("\\"===t[e])e++;else if("."===t[e])return!0;return!1}(this.key))throw new Error(i(57,this.key));this.path=this.parent?this.parent.path.concat(this.key):[];const s=this.config.states?Object.keys(this.config.states)[0]:void 0;this.id=this.config.id||(this.machine.id?[this.machine.id,...this.path]:this.path).join("."),this.type=this.config.type||(void 0!==s?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.schemas=this.config.schemas,function(t){const e=t.config;if("history"===t.type&&!("string"==typeof e.target&&e.target.trim().length>0||Array.isArray(e.target)&&e.target.length>0&&e.target.every(t=>"string"==typeof t&&t.trim().length>0)))throw new Error(i(60,t.id));if("choice"!==t.type)return;if("function"!=typeof e.choice)throw new Error(i(61,t.id))}(this);if(this.machine.idMap.get(this.id))throw new Error(i(58,this.id));if(this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const s={},n=Object.keys(t);for(let r=0;r<n.length;r++){const o=n[r],i=e(t[o],o,t,r);"__proto__"===o?Object.defineProperty(s,o,{value:i,enumerable:!0,configurable:!0,writable:!0}):s[o]=i}return s}(this.config.states,(t,e)=>new Tn(t,{_parent:this,_key:e,_machine:this.machine})):kn,"compound"===this.type&&!this.config.initial)throw new Error(i(59,this.id));this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=Ns(t.tags).slice(),this.invoke=Ns(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,r=`${this.id}:${e}`;const o=t.id??r;return{...t,src:"string"==typeof s?s:void 0,logic:s,id:o,registryKey:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,r=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===r.length)return[];const o=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;o.push({event:k(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0,name:`after.${s}`})}var i;void 0!==s&&n&&o.push({event:(i=t.id,{type:"xstate.timeout.state",stateId:i}),delay:s,transitions:n,fromDelaysMap:!0,name:"onTimeout"});for(const t of r)o.push({event:T(t.id),resolveEvent:({children:e})=>T(t.id,e[t.id]?.sessionId),eventMatcher:(e,s)=>Le(e,s,t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1,name:"invoke.onTimeout"});const c=[];for(const{event:e,resolveEvent:s,eventMatcher:n,delay:r,transitions:i,fromDelaysMap:a,name:u}of o){Ne(t,e,s??(()=>e),e=>Oe(r,a?e.delays:{},{context:e.context,event:e.event,stateNode:t,input:e.input}));const{type:o,...d}=e;for(const e of Ws(i,u,t.id))c.push({...e,matches:{...e.matches,...Object.fromEntries(Object.entries(d).filter(([,t])=>void 0!==t))},event:o,delay:r,_eventMatcher:n})}return c.map(e=>({...ze(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map,s=(t,s)=>{e.set(t,[...e.get(t)??[],...s])};if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error(i(63,t.id));const n=t.config.on[s];e.set(s,On(t,s,n,e=>ze(t,s,e)))}if(t.config.onDone){const e="xstate.done.state";s(e,On(t,"onDone",t.config.onDone,s=>ze(t,e,{...s,matches:{...s.matches,stateId:t.id}})))}if(t.config.onError){const s="xstate.error.*";e.set(s,On(t,"onError",t.config.onError,e=>ze(t,s,e)))}const n=(e,s,n)=>ze(t,e,{matches:{actorId:n},_eventMatcher:(t,e)=>Le(t,e,n),to:(t,e)=>(e.cancel(s),{})}),r=(e,s,n)=>{const{target:r,to:o,reenter:i,...c}=s;return ze(t,e,{...c,reenter:i,to:(t,e)=>{if(o){let s=!1;const r=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const r=Reflect.get(t,e,n);return"function"!=typeof r?r:(...e)=>(s=!0,r.apply(t,e))}}),i=o(t,r);return(void 0!==i||s)&&e.cancel(n),i}return e.cancel(n),{target:r,reenter:i}}})};for(const e of t.invoke){const o=t=>({...t,matches:{...t.matches,actorId:e.id},_eventMatcher:(t,s)=>Le(t,s,e.id)}),i=void 0!==e.timeout?{event:{type:"xstate.timeout.actor",actorId:e.id}}:void 0;if(e.onDone){const c="xstate.done.actor",a=On(t,"invoke.onDone",e.onDone,e=>{const s=o(e);return i?r(c,s,i):ze(t,c,s)});i&&a.push(n(c,i,e.id)),s(c,a)}else if(i){const t="xstate.done.actor";s(t,[n(t,i,e.id)])}if(e.onError){const n="xstate.error.actor";s(n,On(t,"invoke.onError",e.onError,e=>{const s=o(e);return i?r(n,s,i):ze(t,n,s)}))}if(e.onSnapshot){const n="xstate.snapshot.actor";s(n,On(t,"invoke.onSnapshot",e.onSnapshot,e=>ze(t,n,o(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(i(62,t.id));return e};return[ze(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=On(this,"always",this.config.always,t=>ze(this,"",t)));for(const t of Object.keys(this.states))this.states[t]._initialize();this._refreshEventMetadata()}_refreshEventMetadata(){const t={},e=[];for(const[s,n]of this.transitions)t[s]=n.slice(),n.some(t=>t.target||t.reenter||t.to)&&e.push(s);this.on=t,this.ownEvents=e;const s=new Set(e);for(const t of Object.values(this.states))for(const e of t.events)s.add(e);this.events=Array.from(s)}get initial(){return function(t,e,s){let n=An.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},An.set(t,n)),n[e]}(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,r="object"==typeof e&&null!==e?e.to:void 0,o="object"==typeof e&&null!==e?e.meta:void 0,c="object"==typeof e&&null!==e?e.description:void 0,a=Array.isArray(s)?s:s?[s]:[],u=a.map(e=>e.startsWith("#")?t.machine.getStateNodeById(e.slice(1)):t.states[e]);if(u.some(t=>!t))throw new Error(i(64,a.find((t,e)=>!u[e]),t.id));const d={source:t,target:u.length?u:void 0,input:n,to:r,meta:o,description:c};return d}(this,this.config.initial))}next(t,e,s,n){if("final"===this.type)return;let r=this._candidateCache?.get(e.type);r||(r=function(t,e){const s=t.transitions.get(e.type)??[],n=[...t.transitions.keys()].filter(t=>t!==e.type&&Fs(e.type,t)).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return s.length?[...s,...n]:n}(this,e),(this._candidateCache??=new Map).set(e.type,r));for(const o of r){if(_s(o,e,t,this,s,n))return[o]}}}function On(t,e,s,n){const r=Ws(s,e,t.id),o=new Array(r.length);for(let t=0;t<r.length;t++)o[t]=n(r[t]);return o}function jn(t,e){const s=t.check(e);if(s)throw s}let Mn,Rn;function Pn(){if(Rn)return Rn;const t=Mn??=xn({transition:t=>[t,[]],initialTransition:()=>[{status:"active",output:void 0,error:void 0},[]],getInitialSnapshot:()=>({status:"active",output:void 0,error:void 0}),getPersistedSnapshot:t=>t});return Rn={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},Mt.add(Rn),Rn}class $n{constructor(t,e,s){if(this.config=t,this.validator=s,this._internalEventType=void 0,this._transitionMetaType=void 0,this._inputType=void 0,this._actionMap=void 0,this._actorMap=void 0,this._stateSchema=void 0,this.version=void 0,this.schemas=void 0,this.sources=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this._raw=()=>this,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._hasEventlessTransitions=void 0,this._microstepHooks=void 0,this._json=void 0,void 0!==t.version&&!t.id)throw new Error(i(18,t.version));this.id=t.id??"",this.sources={actors:t.actors??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...e},this.version=this.config.version,this.schemas=this.config.schemas,this.internalEventDescriptors=Object.keys(this.schemas?.internalEvents??{}),this.options={...this.config.options},this.transition=this.transition.bind(this),this.initialTransition=this.initialTransition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.start=this.start.bind(this),this.root=new Tn(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const r=n.config.id,o=n.config.route,i=({event:t})=>t.to===`#${r}`;if("function"==typeof o)return e.push(ze(t,"xstate.route",{guard:i,to:t=>{const e=o(t);if(e)return{...!0===e?{}:e,target:`#${r}`}}})),void(n.states&&s(n.states));const{guard:c,...a}=o,u={...a,guard:i,target:`#${r}`};e.push(ze(t,"xstate.route",u))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.root._refreshEventMetadata(),this._hasEventlessTransitions=Array.from(this.idMap.values()).some(t=>!!t.always?.length),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:r}=this.sources,o=new $n(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...r,...t.delays}},this.validator);return o._json=this._json,o.internalEventDescriptors=this.internalEventDescriptors,o._microstepHooks=this._microstepHooks,o}resolveState(t){const e=(s=this.root,n=t.value,qe(s,$e(Qe(s,n))));var s,n;const r=$e(Qe(this.root,e));return Ms({_nodes:[...r],value:e,context:t.context||{},children:{},status:De(r,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const n=!s,r=s??ke(this,t);if(n&&ge(r,t,!1),this.validator){const n=s&&s.self._lastSourceRef,o=n?"actor":"external",i=this.validator.check({kind:"event",logic:this,event:e,eventOrigin:o});if(i)return[t,[ct(r,n,e,"invalidEvent",{issues:i.issues,error:i})]]}It(r);const o=this._transitionFast(t,e,r);if(o){n&&ge(r,o,!1);const e=n&&o!==t?me(r,o):this._attachPureActorRef(o,r);return this.validator&&jn(this.validator,{kind:"result",logic:this,snapshot:e,effects:[]}),[e,[]]}const{snapshot:i,microsteps:c}=hs(t,e,r,[]);n&&ge(r,i,!1);const a=n?i===t?i:me(r,i):this._attachPureActorRef(i,r),u=this._collectEffects(c);return this.validator&&jn(this.validator,{kind:"result",logic:this,snapshot:a,effects:u}),[a,u]}_collectEffects(t){return t.flatMap(([,t])=>t)}_attachPureActorRef(t,e,s=!1){return _e(e)||s&&e.self._actorScope===e&&void 0===e.self._snapshot||fe(t,e.self,e.system),t}_transitionFast(t,e,s){if("active"!==t.status||"string"!=typeof t.value||this.root.always?.length)return;const n=this.root.states[t.value];if(!n||"atomic"!==n.type||n.exit||n.invoke.length||n.always?.length||n.after?.length)return;const r=n.transitions.get(e.type);if(1!==r?.length)return;const o=r[0];if(o.guard||o.actions||o.to||o.reenter||o.input||"function"==typeof o.context||o.target&&1!==o.target.length)return;const i=o.target?.[0]??n,c=i!==n;if(i.parent!==this.root||"atomic"!==i.type||c&&(i.entry||i.invoke.length||i.always?.length||i.after?.length))return;const a=void 0!==o.context?{...t.context,...o.context}:t.context;if(!_e(s)&&(s.system._hasInspectionObservers?.()??1)){const t=s.self._collectedMicrosteps||[];t.push(o),s.self._collectedMicrosteps=t}const u=t._stateInputs[this.root.id];return Rs(t,{...a!==t.context?{context:a}:{},...c?{_nodes:[this.root,i],_stateInputs:u?{[this.root.id]:u}:{}}:{}})}microstep(t,e,s){const{microsteps:n}=hs(t,e,s,[]),r=new Array(n.length);for(let t=0;t<n.length;t++)r[t]=n[t][0];return r}getTransitionData(t,e,s,n){return this._microstepHooks?.begin(s.self),Ye(this.root,t.value,t,e,s,n)||[]}isInternalEventType(t){if(t===f)return!0;for(const e of this.internalEventDescriptors)if(Fs(t,e))return!0;return!1}_canTransition(t,e){if("active"!==t.status)return!1;const s=Pn(),n=this.getTransitionData(t,e,s);if(!n?.length)return!1;for(const r of n){if(void 0!==r.target)return!0;const n=us(r,t,e,s,{resolveActions:!1});if(n.targets?.length||n.context||fs(r,t.context,e,t,s))return!0}return!1}getExecutionErrorEvent(t,e){if("active"===t?.status&&t.nodes?.some(t=>t.config.onError))return j("execution",e)}_getPreInitialState(t,e){const{context:s}=this.config,n=Ms({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const r={},o=function(t,e,s){return(n,r)=>{const o=F(e,n),i=r?.id??Tt(t,o??n).id;void 0!==r?.id&&(Ot(t,r.id),jt(t,r.id));const c=t.system.createActorRef(n,{id:i,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:o??n,registryKey:r?.registryKey});return s[c.id]=c,c}}(t,this.sources.actors,r),i=s(function(t,e){return pe(e)?(Object.defineProperty(t,"self",{enumerable:!0,get:()=>e.self}),t):Object.assign(t,{self:e.self})}({spawn:o,input:e.input,actors:this.sources.actors},t)),[c]=Ut(n,0,t,[]);if(i&&(c.context=i),Object.keys(r).length>0){c.children={...c.children,...r};const e=function(t){const e=bt.get(t)?.counters;if(e?.size)return Object.fromEntries(e)}(t);e&&(c._nextActorIds=mt(c._nextActorIds,e))}return c}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){this.validator&&jn(this.validator,{kind:"input",logic:this,input:t});const s=!e,n=e??ke(this);It(n);const r=M(t),o=[],i=(t,e)=>{s&&ge(n,t,!1);const r=s?me(n,t):this._attachPureActorRef(t,n,!0),o=this._collectEffects(e);return this.validator&&"error"!==t.status&&jn(this.validator,{kind:"result",logic:this,snapshot:r,effects:o}),[r,o]};let c;try{c=this._getPreInitialState(n,r)}catch(t){return i(Rs(Ms({context:"function"!=typeof this.config.context&&this.config.context?this.config.context:{},_nodes:[this.root],children:{},status:"active"},this),{status:"error",error:t}),[])}const a=Object.values(c.children).filter(Boolean).map(t=>function(t){const e=[t];return{kind:"builtin",exec:ut,type:u,source:t._parent,params:void 0,args:e,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}(t));try{const[t,e]=function(t,e,s,n,r){t.machine._microstepHooks?.begin(s.self);const o=[...Fe(t)],i=new Set,c=t=>{if("compound"===t.type){i.add(t);for(const e of t.initial.target??[])c(e)}else if("parallel"===t.type)for(const e of Re(t))c(e)};return c(t),as([{target:o.filter(t=>!o.some(e=>e!==t&&Ze(e,t))),source:t,reenter:!0,eventType:null,toJSON:null,_statesForDefaultEntry:[...i]}],e,s,n,!0,r)}(this.root,c,n,r,o),{snapshot:s,microsteps:u}=hs(t,r,n,o,[[t,[...a,...e]]]);return i(s,u)}catch(t){if(!this.root.config.onError)throw t;const e=hs(c,j("execution",t),n,[],[[c,a]]);return i(e.snapshot,e.microsteps)}}start(t,e){if(!t?.children)return;const s=t.children;for(const t in s){if(!Object.hasOwn(s,t))continue;const n=s[t];n._rehydrated&&"active"===n.getSnapshot?.().status&&(e?e.actionExecutor(Lt(n)):n.system.startActor(n))}}getStateNodeById(t){const e=Ke(t),s=e?t.slice(1):t;if(""===s&&e)throw new Error(i(19,this.id));const n=this.idMap.get(s);if(n)return n;throw new Error(i(20,s))}getPersistedSnapshot(t,e){return function(t,e){const{nodes:s,_stateInputs:n,_nextTimerId:r,_nextActorIds:o,tags:c,machine:a,children:u,timers:d,context:h,can:f,hasTag:l,matches:v,getMeta:g,getInputs:_,toJSON:m,...x}=t,w={},b=[],S=!1!==e?.embedChildren;for(const t in u){const n=u[t],r="string"==typeof n.src?n.src:void 0,o=void 0===r&&!0===n._invoked&&s.some(e=>e.invoke.some(e=>e.id===t));if(!(void 0!==r||o||e&&"__unsafeAllowInlineActors"in e))throw new Error(i(41,t));const c=S&&!p(n);if(!c&&void 0===r)throw new Error(i(42,t));w[t]={address:n.address,...c?{snapshot:n.getPersistedSnapshot(e)}:{remote:!0,incarnation:p(n)?n.sessionId:void 0},...o?{}:{src:n.src},registryKey:n.registryKey,syncSnapshot:n._syncSnapshot}}const I=de(t)?.actor,E=I?.system?._clock?.now?void 0:I?.system?._snapshot?._scheduledTimers;for(const e of d){let s,n=e.event;if("xstate.timeout.actor"===n.type&&(n={...n},delete n.sessionId),"self"===e.target)s="self";else if(y(e.target))s={...e.target};else{const n=Object.entries(u).find(([,t])=>t===e.target)?.[0];if(n)s=n;else{if(e.target!==de(t)?.actor._parent)throw new Error(i(43,e.target.id));s={type:"parent"}}}const r=E?.[V(I,L(e))],o=r?r.dueAt-e.delay:W(e);b.push({...void 0!==e.id&&{id:e.id},...void 0!==e.seq&&{seq:e.seq},delay:e.delay,type:e.type,event:n,target:s,...void 0!==o&&{scheduledAt:o}})}const A={...x,context:$s(h,()=>de(t)?.actor.id??a.id),children:w,timers:b,historyValue:Ps(x.historyValue)};return n&&Object.keys(n).length>0&&(A.stateInputs=n),A.nextTimerId=r,o&&Object.keys(o).length>0&&(A.nextActorIds=o),void 0!==a.version&&(A.machine={id:a.id,version:a.version}),A}(t,e)}}function qn(t,e,s){if(t instanceof $n)return function(t,e,s){t instanceof $n&&(t=t._raw());e=o(e);const n=!s,r=s??ke(t);if(!e||"object"!=typeof e||Array.isArray(e))throw new wn(i(24,t.id));const c=e.machine,a=c&&"object"==typeof c&&"function"==typeof c.transition&&"root"in c?void 0:c,u=e.version,d="string"==typeof a?.version?a.version:u;if(void 0!==u&&void 0!==a?.version&&a.version!==u)throw new Error(i(34,u,a.version));if(a&&"string"==typeof a.id&&a.id!==t.id)throw new Error(i(35,a.id,t.id));if(d!==t.version){const s=t.config.migrate;if("function"!=typeof s)throw new Error(i(36,d,t.version));e=s(e,d)}const h=e,{nodes:f,childLogics:l}=En(t,h),p={},v=h.children;for(const t of Object.keys(v)){const e=v[t];if(!0===e.remote&&void 0!==e.address){if("string"!=typeof e.src)throw new Error(i(28,t));const s=x(r.system,{id:t,address:e.address,src:e.src,parent:r.self,registryKey:e.registryKey,syncSnapshot:e.syncSnapshot,incarnation:e.incarnation});e.registryKey&&r.system._set(e.registryKey,s),p[t]=s;continue}const s=e.snapshot,n=e.src,o=l.get(t),c=r.system.createActorRef(o,{id:t,parent:r.self,syncSnapshot:e.syncSnapshot,...void 0!==s?{_restore:Dn(o,s)}:{},src:n,registryKey:e.registryKey});c._rehydrated=!0,void 0===n&&(c._invoked=!0),p[t]=c}const g=[],_=h.timers??[];for(const t of _){let e=t.event;if("xstate.timeout.actor"===e.type){const t=e.actorId,s=p[t];s&&(e=T(t,s.sessionId))}const s="string"==typeof t.target?"self"===t.target?"self":p[t.target]:y(t.target)?t.target:r.self._parent;if(!s){const e="string"==typeof t.target?t.target:t.target.type;throw new wn(i(33,e))}g.push({...t,event:e,target:s})}const m=(e=>{if(!e||"object"!=typeof e)return{};const s={};for(const n of Object.keys(e)){const r=e[n];for(const e of r){let r;if(e instanceof Tn)r=e;else try{r=t.getStateNodeById(e.id)}catch{}r&&(s[n]??=[],s[n].push(r))}}return s})(h.historyValue),{version:w,_nextActorId:b,nextTimerId:S,nextActorIds:I,stateInputs:E,...A}=e;let k=I;for(const t of Object.keys(v)){const e=sn(t);e&&(k?.[e.prefix]??0)<=e.index&&(k={...k,[e.prefix]:e.index+1})}const O=new Map;function j(t,e=!1){if(!t||"object"!=typeof t)return t;if(!e&&y(t))return void 0!==t.incarnation?t:Object.values(p).find(e=>e.address===t["@actor"])??t;const s=Object.getPrototypeOf(t);if(!Array.isArray(t)&&s!==Object.prototype&&null!==s)return t;let n=O.get(t);if(!n){O.set(t,n=Array.isArray(t)?[]:Object.create(s));for(const e of Object.keys(t))Object.defineProperty(n,e,{value:j(t[e]),writable:!0,enumerable:!0,configurable:!0})}return n}const M=Ms({...A,context:j(A.context,!0),children:p,timers:g,_nextTimerId:S,_nextActorIds:k,_nodes:f,value:void 0,historyValue:m,_stateInputs:Object.fromEntries(Object.entries(h.stateInputs??{}).filter(([t])=>f.some(e=>e.id===t)))},t,r.self);if(n)return ge(r,M,!1),me(r,M);_e(r)||fe(M,r.self,r.system);return M}(t,e,s);if(!t.restoreSnapshot&&null===e)throw new Error(i(46));return t.restoreSnapshot?t.restoreSnapshot(e,s):e}function Dn(t,e){return{restore:s=>qn(t,e,s),error:s=>t instanceof $n?function(t,e,s){const n=e?.context;return Rs(Ms({context:n&&"object"==typeof n?n:{},_nodes:[t.root],children:{},status:"active"},t),{status:"error",error:s})}(t,e,s):void 0}}function Kn(t){if(y(t))return{...t};const e=p(t)?t.sessionId:void 0;return void 0===e?{"@actor":t.address}:{"@actor":t.address,incarnation:e}}function Ln(t,e,s){if(!Xt())return;const n=t.self;n?.system._hasInspectionObservers?.()&&n._inspectTransition(e,s)}const Nn=new Set(["xstate.done.actor","xstate.error.actor","xstate.timeout.actor"]);function zn(t){if(!t||"object"!=typeof t)return!1;const{event:e,source:s}=t;return!(!e||"string"!=typeof e.type||void 0!==s&&(!s||"string"!=typeof s["@actor"]||void 0!==s.incarnation&&"string"!=typeof s.incarnation))}class Vn extends Error{constructor(){super("Durable execution was stopped"),this.name="DurableExecutionCancelledError"}}class Cn extends Error{constructor(){super("run() can only start a fresh durable execution; resume checkpoints with restore() and the explicit transition loop"),this.name="DurableExecutionResumeError"}}t.DurableExecutionCancelledError=Vn,t.DurableExecutionResumeError=Cn,t.createDurable=function(t,e,s){let n=e.transitionIndex??0;const r=n;let o=!1;const i=()=>e.now?.()??Date.now(),c=new WeakSet;let a=0===n?void 0:n-1;const u=new WeakMap;if(!Number.isSafeInteger(n)||n<0)throw new RangeError("transitionIndex must be a non-negative safe integer");const d=(t,e=!1)=>{const s=e?n:n++;return a=e?a??s:s,t.map((t,n)=>{const r={id:`${e?"restore:":""}${s}:${n}`,transitionIndex:s,effectIndex:n,effect:t};let o;return Object.defineProperty(r,"descriptor",{enumerable:!0,get:()=>o??=function(t){if("action"===t.kind)return{kind:"action",type:t.type,params:t.params};if("emit"===t.kind)return{kind:"emit",type:t.type,source:Kn(t.source),event:t.event};switch(t.type){case"@xstate.spawn":return{kind:"builtin",type:"@xstate.spawn",source:t.source&&Kn(t.source),actor:Kn(t.actor),id:t.id,src:tn(t.src),input:t.input};case"@xstate.start":return{kind:"builtin",type:"@xstate.start",source:t.source&&Kn(t.source),actor:Kn(t.actor),id:t.id};case"@xstate.raise":return{kind:"builtin",type:"@xstate.raise",source:Kn(t.source),event:t.event,id:t.id,...void 0!==t.seq&&{seq:t.seq},delay:t.delay};case"@xstate.sendTo":return{kind:"builtin",type:"@xstate.sendTo",source:Kn(t.source),target:t.target&&Kn(t.target),event:t.event,id:t.id,...void 0!==t.seq&&{seq:t.seq},delay:t.delay};case"@xstate.cancel":return{kind:"builtin",type:"@xstate.cancel",source:Kn(t.source),...N(t)};case"@xstate.stop":return{kind:"builtin",type:"@xstate.stop",source:Kn(t.source),actor:Kn(t.actor),id:t.id};case"@xstate.terminate":return{kind:"builtin",type:"@xstate.terminate",source:Kn(t.source),actor:Kn(t.actor),id:t.id,status:t.status,output:t.output,error:t.error};case"@xstate.deadLetter":return{kind:"builtin",type:"@xstate.deadLetter",source:t.source&&Kn(t.source),target:t.target&&Kn(t.target),event:t.event,reason:t.reason,issues:t.detail?.issues,error:t.detail?.error}}}(t)}),r})},h=en(function(t){const e=tn(t);return"x"===e?"x:0":e}(t)),f=t.id??h,l=t.version,y=e.executionId?{executionId:e.executionId,nextSessionId:0}:void 0,v={};for(const t of[...on,"sendEvent","runStep","runLogic"]){const s=e[t];s&&(v[t]=s.bind(e))}const g=Object.keys(v).length>0||!!e.enqueueRootEvent;let _;const m=[],x=(t,e)=>{if(Ss(t)&&Nn.has(e.type)&&"string"==typeof e.actorId)return t.children[e.actorId]??null};let w=Promise.resolve();const b=t=>_?((t,e)=>{const s=w.then(e).then(()=>{});return w=s.catch(()=>{}),((t,e)=>(t.pending.add(e),e.catch(e=>{t.failures.push(e)}).then(()=>t.pending.delete(e)),e))(t,s)})(_,t):t(),S=async t=>{for(;t.pending.size;)await Promise.allSettled([...t.pending])};function E(t,n,r=!1,o){const c={};for(const e of on){const s=t[e]??(r?(...t)=>("spawnActor"===e?t[1]:t[0]).system[e](...t):void 0);s&&(c[e]=(...t)=>b(()=>{if("scheduleTimer"===e&&o&&(t[2]=Math.min(o.delay,Math.max(0,o.deadline-i()))),"scheduleTimer"===e){const e=t[0],n=t[1],r=e.getSnapshot()?.timers?.find(t=>z(t,n));if(r){const e=W(r);void 0===e||o||(t[2]=Math.min(r.delay,Math.max(0,e+r.delay-i())));const n=s(...t);return n?Promise.resolve(n).then(()=>{U(r,e??i())}):void U(r,e??i())}}return s(...t)}))}return t.runStep&&(c.runStep=t.runStep),t.runLogic&&(c.runLogic=t.runLogic),c.sendEvent=(r,o,i)=>{const c=!1!==s?.captureRootEvents?_:void 0;if(!c&&o.address===h&&!t.sendEvent&&e.enqueueRootEvent)return b(()=>e.enqueueRootEvent(r,i));if(!c&&o.address===h&&!t.sendEvent)throw new Error(`A root-addressed event ("${i.type}") was produced outside batch capture (for example, while the durable loop was parked), but the adapter has no enqueueRootEvent or sendEvent to receive it. Implement enqueueRootEvent to place root-addressed events in the host's mailbox.`);if(c&&o.address===h)return void c.rootEvents.push({event:i,source:r});const a=t.sendEvent;if(a)return b(()=>a(r,o,i));if(n)return b(()=>I(r,o,i));throw new TypeError(`The durable runtime does not support the sendEvent operation (target '${o.address}')`)},c}const A=g?E(v,!0):void 0;function k(t,e){if(t.address===e)return t;if(!e.startsWith(`${t.address}/`))return;const s=t.getSnapshot().children;for(const t of Object.values(s??{})){const s=t&&k(t,e);if(s)return s}}const T=s?.inspect,O={runtime:A,inspect:T};function j(t){return function(t,e){const s=te;te=t;try{return e()}finally{te=s}}(O,()=>function(t,e){if(!t)return e();const s=Ft;Ft=t;try{return e()}finally{Ft=s}}(T,t))}function R(t,e=!1){if("error"===t.status){const e=de(t)?.actor;e&&!c.has(e)&&(e.subscribe({error(){}}),c.add(e))}if(A||T){const s=de(t)?.actor,n=new Set,r=t=>{var s;if(n.has(t.system)||(n.add(t.system),function(t,e){const s=Qt.get(t),n=Zt.get(s?.executionSystem??t);return n===e?(s&&(s.forwardInspection=!!e.inspect),!0):!n&&(s?(ae(t,s.executionSystem,e),s.executionSystem=t,s.forwardInspection=!!e.inspect,!0):(Zt.set(t,e),!0))}(t.system,O)&&(A&&(t.system.runtime=A),s=t.system,T&&!s._hasInspectionObservers?.()&&s.inspect(T))),e){const e=t.getSnapshot().children;for(const t of Object.values(e??{}))t&&r(t)}};if(s&&r(s),!e||!s){const e=t.children;for(const t of Object.values(e??{}))t&&r(t)}}return t}const P={rootAddress:h,machineId:f,machineVersion:l,get nextTransitionIndex(){return n},checkpoint(e,s){const r=[];for(const{event:t,source:s}of m){const n=x(e,t);"xstate.snapshot.actor"===t.type||void 0!==n&&(!n||void 0!==t.sessionId&&void 0!==n.sessionId&&n.sessionId!==t.sessionId)||r.push({event:t,source:s&&{"@actor":s.address,...p(s)&&void 0!==s.sessionId?{incarnation:s.sessionId}:{}}})}return{snapshot:t.getPersistedSnapshot?.(e,s)??e,nextTransitionIndex:n,inbox:r}},restore(s){const i=(c=s)&&"object"==typeof c&&"inbox"in c&&"nextTransitionIndex"in c&&"snapshot"in c?s:void 0;var c;if(o||n!==r||_)throw new Error("restore() requires a fresh durable execution");if(i){if(!Array.isArray(i.inbox)||!i.inbox.every(zn))throw new TypeError("The checkpoint inbox is invalid.");if(void 0!==e.transitionIndex&&e.transitionIndex!==i.nextTransitionIndex)throw new RangeError(`The adapter's transitionIndex (${e.transitionIndex}) does not match the checkpoint's nextTransitionIndex (${i.nextTransitionIndex}).`);if(!Number.isSafeInteger(i.nextTransitionIndex)||i.nextTransitionIndex<0)throw new RangeError("nextTransitionIndex must be a non-negative safe integer");n=i.nextTransitionIndex,a=0===n?void 0:n-1}const h=i?i.snapshot:s,{snapshot:f,scope:l}=j(()=>Zs(y,()=>{const e=ke(t),s=qn(t,h,e);return ge(e,s,!1),{snapshot:R(me(e,s),!0),scope:e}}));for(const{event:t,source:e}of i?.inbox??[]){const s=x(f,t);null!==s&&m.push({event:s&&void 0!==s.sessionId&&"sessionId"in t?{...t,sessionId:s.sessionId}:t,source:e&&P.getActorRef(f,e["@actor"])})}const v=[];if("active"===f.status){const{children:t,timers:e}=f;for(const e of Object.values(t??{}))e&&!p(e)&&"active"===e.getSnapshot().status&&v.push(Lt(e));for(const t of e??[]){const e=Nt(l,t,t.delay);void 0!==t.scheduledAt&&u.set(e,{deadline:t.scheduledAt+t.delay,delay:t.delay}),v.push(e)}}return o=!0,[f,d(v,!0)]},initialTransition(...e){if(o)throw new Error("initialTransition() cannot initialize a restored execution");const[s,n]=j(()=>Zs(y,()=>function(t,...[e]){const s=ke(t),[n,r]=Ct(s,void 0,t.initialTransition(e,s));ge(s,n,!1);const o=me(s,n);return Ln(s,o,M(e)),[o,r]}(t,...e)));return[R(s),d(n)]},transition(e,s){const[n,r]=j(()=>Zs(y,()=>function(t,e,s){const n=ke(t,e);ge(n,e,!1);const[r,o]=Ct(n,e,t.transition(e,s,n));ge(n,r,!1);const i=r===e?r:me(n,r);return Ln(n,i,s),[i,o]}(t,e,s)));return[R(n),d(r)]},getActorRef(t,e){const s=de(t)?.actor;return s&&void 0!==e?k(s,e):s},async executeEffects(t){if(_)throw new Error("executeEffects calls must not overlap: await the previous call before starting the next batch.");const s={rootEvents:[],failures:[],pending:new Set};_=s;const n=g?void 0:{};try{for(const s of t){const{effect:t}=s,r={id:s.id,transitionIndex:s.transitionIndex,effectIndex:s.effectIndex},o=e.runtime?.(r,t),i=u.get(t),c=o||i?E({...v,...o},g,!!o||g,i):n;"action"===t.kind?await e.executeAction(t,r,c??A??{}):await t.exec(c)}await(async t=>{if(await S(t),t.failures.length)throw t.failures[0]})(s),m.push(...s.rootEvents)}catch(t){throw await S(s),t}finally{_=void 0}},async waitForEvent(){if(void 0===a)throw new Error("Cannot wait for an event before the first transition or restore");const t=m.shift();return t?t.event:e.waitForEvent({id:o&&0===n?"event:restore:0":`event:${a}`,transitionIndex:a})},async run(...t){if(o||0!==r||n!==r)throw new Cn;let[e,s]=P.initialTransition(...t);for(await P.executeEffects(s);"active"===e.status;){const t=await P.waitForEvent();[e,s]=P.transition(e,t),await P.executeEffects(s)}const i=e;if("done"===i.status)return i.output;if("error"===i.status)throw i.error;throw new Vn}};return P},Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate-durable.umd.min.js.map