xstate 6.0.0-alpha.49 → 6.0.0-alpha.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{StateMachine-0adb3a70.cjs.js → StateMachine-1e6ee14a.cjs.js} +18 -6
- package/dist/{StateMachine-29450e6d.development.cjs.js → StateMachine-70df737c.development.cjs.js} +18 -6
- package/dist/{StateMachine-2af31c11.esm.js → StateMachine-8cea8974.esm.js} +18 -6
- package/dist/{StateMachine-faf50c5c.development.esm.js → StateMachine-bc28e207.development.esm.js} +18 -6
- package/dist/{createActor-b4dd05ae.cjs.js → createActor-27fd819f.cjs.js} +80 -10
- package/dist/{createActor-88709f74.development.esm.js → createActor-74e185ee.development.esm.js} +80 -11
- package/dist/{createActor-268165d4.esm.js → createActor-ad3a1abe.esm.js} +80 -11
- package/dist/{createActor-a1e0dffb.development.cjs.js → createActor-ea9a560c.development.cjs.js} +80 -10
- package/dist/declarations/src/effectDescriptor.d.ts +9 -0
- package/dist/declarations/src/index.d.ts +1 -1
- package/dist/declarations/src/inspection.d.ts +24 -7
- package/dist/declarations/src/runtimeHelpers.d.ts +6 -3
- package/dist/declarations/src/system.d.ts +38 -3
- package/dist/declarations/src/types.d.ts +35 -2
- package/dist/{effectDescriptor-7ff6802f.development.cjs.js → effectDescriptor-16b6f3b4.cjs.js} +12 -1
- package/dist/{effectDescriptor-39d22100.development.esm.js → effectDescriptor-38598bd3.development.esm.js} +12 -1
- package/dist/{effectDescriptor-be348e50.cjs.js → effectDescriptor-40ca302f.development.cjs.js} +12 -1
- package/dist/{effectDescriptor-30c9a744.esm.js → effectDescriptor-7dac431a.esm.js} +12 -1
- package/dist/{fsm-e18a7cb4.development.esm.js → fsm-25f10f50.development.esm.js} +1 -1
- package/dist/{fsm-c1316948.development.cjs.js → fsm-697ffd89.development.cjs.js} +1 -1
- package/dist/{fsm-7a2e9697.cjs.js → fsm-7adaf0ea.cjs.js} +1 -1
- package/dist/{fsm-b804b3e9.esm.js → fsm-dc1bb88b.esm.js} +1 -1
- package/dist/{types-fbabaeee.cjs.js → types-a14db10c.development.cjs.js} +6 -1
- package/dist/{types-3c3455f7.esm.js → types-a313e7e2.esm.js} +6 -1
- package/dist/{types-b3fea5bd.development.cjs.js → types-bc22b358.cjs.js} +6 -1
- package/dist/{types-adda3842.development.esm.js → types-c37714eb.development.esm.js} +6 -1
- package/dist/xstate-actors.cjs.js +12 -3
- package/dist/xstate-actors.development.cjs.js +12 -3
- package/dist/xstate-actors.development.esm.js +13 -4
- package/dist/xstate-actors.esm.js +13 -4
- package/dist/xstate-actors.umd.min.js +1 -1
- package/dist/xstate-actors.umd.min.js.map +1 -1
- package/dist/xstate-durable.cjs.js +2 -2
- package/dist/xstate-durable.development.cjs.js +2 -2
- package/dist/xstate-durable.development.esm.js +2 -2
- package/dist/xstate-durable.esm.js +2 -2
- package/dist/xstate-durable.umd.min.js +1 -1
- package/dist/xstate-durable.umd.min.js.map +1 -1
- package/dist/xstate-fsm.cjs.js +2 -2
- package/dist/xstate-fsm.development.cjs.js +2 -2
- package/dist/xstate-fsm.development.esm.js +2 -2
- package/dist/xstate-fsm.esm.js +2 -2
- package/dist/xstate-graph.cjs.js +2 -2
- package/dist/xstate-graph.development.cjs.js +2 -2
- package/dist/xstate-graph.development.esm.js +2 -2
- package/dist/xstate-graph.esm.js +2 -2
- package/dist/xstate-graph.umd.min.js +1 -1
- package/dist/xstate-graph.umd.min.js.map +1 -1
- package/dist/xstate-scxml.cjs.js +3 -3
- package/dist/xstate-scxml.development.cjs.js +3 -3
- package/dist/xstate-scxml.development.esm.js +3 -3
- package/dist/xstate-scxml.esm.js +3 -3
- package/dist/xstate-scxml.umd.min.js +1 -1
- package/dist/xstate-scxml.umd.min.js.map +1 -1
- package/dist/xstate-validation.cjs.js +1 -1
- package/dist/xstate-validation.development.cjs.js +1 -1
- package/dist/xstate-validation.development.esm.js +1 -1
- package/dist/xstate-validation.esm.js +1 -1
- package/dist/xstate.cjs.js +5 -5
- package/dist/xstate.development.cjs.js +5 -5
- package/dist/xstate.development.esm.js +8 -8
- package/dist/xstate.esm.js +8 -8
- package/dist/xstate.umd.min.js +1 -1
- package/dist/xstate.umd.min.js.map +1 -1
- package/package.json +1 -1
package/dist/xstate-fsm.cjs.js
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
|
-
var fsm = require('./fsm-
|
|
6
|
-
require('./createActor-
|
|
5
|
+
var fsm = require('./fsm-7adaf0ea.cjs.js');
|
|
6
|
+
require('./createActor-27fd819f.cjs.js');
|
|
7
7
|
|
|
8
8
|
var FSMActorStatus = /*#__PURE__*/function (FSMActorStatus) {
|
|
9
9
|
FSMActorStatus[FSMActorStatus["NotStarted"] = 0] = "NotStarted";
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
|
-
var fsm = require('./fsm-
|
|
6
|
-
require('./createActor-
|
|
5
|
+
var fsm = require('./fsm-697ffd89.development.cjs.js');
|
|
6
|
+
require('./createActor-ea9a560c.development.cjs.js');
|
|
7
7
|
|
|
8
8
|
var FSMActorStatus = /*#__PURE__*/function (FSMActorStatus) {
|
|
9
9
|
FSMActorStatus[FSMActorStatus["NotStarted"] = 0] = "NotStarted";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { c as createFSM } from './fsm-
|
|
2
|
-
import './createActor-
|
|
1
|
+
export { c as createFSM } from './fsm-25f10f50.development.esm.js';
|
|
2
|
+
import './createActor-74e185ee.development.esm.js';
|
|
3
3
|
|
|
4
4
|
var FSMActorStatus = /*#__PURE__*/function (FSMActorStatus) {
|
|
5
5
|
FSMActorStatus[FSMActorStatus["NotStarted"] = 0] = "NotStarted";
|
package/dist/xstate-fsm.esm.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { c as createFSM } from './fsm-
|
|
2
|
-
import './createActor-
|
|
1
|
+
export { c as createFSM } from './fsm-dc1bb88b.esm.js';
|
|
2
|
+
import './createActor-ad3a1abe.esm.js';
|
|
3
3
|
|
|
4
4
|
var FSMActorStatus = /*#__PURE__*/function (FSMActorStatus) {
|
|
5
5
|
FSMActorStatus[FSMActorStatus["NotStarted"] = 0] = "NotStarted";
|
package/dist/xstate-graph.cjs.js
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
|
-
var createActor = require('./createActor-
|
|
5
|
+
var createActor = require('./createActor-27fd819f.cjs.js');
|
|
6
6
|
var dist_xstateActors = require('./xstate-actors.cjs.js');
|
|
7
|
-
var StateMachine = require('./StateMachine-
|
|
7
|
+
var StateMachine = require('./StateMachine-1e6ee14a.cjs.js');
|
|
8
8
|
require('./validation-4561b43c.cjs.js');
|
|
9
9
|
|
|
10
10
|
function simpleStringify(value) {
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
|
-
var createActor = require('./createActor-
|
|
5
|
+
var createActor = require('./createActor-ea9a560c.development.cjs.js');
|
|
6
6
|
var dist_xstateActors = require('./xstate-actors.development.cjs.js');
|
|
7
|
-
var StateMachine = require('./StateMachine-
|
|
7
|
+
var StateMachine = require('./StateMachine-70df737c.development.cjs.js');
|
|
8
8
|
require('./validation-f2714a35.development.cjs.js');
|
|
9
9
|
|
|
10
10
|
function simpleStringify(value) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { e as isMachineSnapshot,
|
|
1
|
+
import { e as isMachineSnapshot, aB as getAllOwnEvents, aC as matchesEvent, I as XSTATE_INIT } from './createActor-74e185ee.development.esm.js';
|
|
2
2
|
import { createEmptyActor } from './xstate-actors.development.esm.js';
|
|
3
|
-
import { S as StateMachine } from './StateMachine-
|
|
3
|
+
import { S as StateMachine } from './StateMachine-bc28e207.development.esm.js';
|
|
4
4
|
import './validation-e69470ad.development.esm.js';
|
|
5
5
|
|
|
6
6
|
function simpleStringify(value) {
|
package/dist/xstate-graph.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { e as isMachineSnapshot,
|
|
1
|
+
import { e as isMachineSnapshot, aB as getAllOwnEvents, aC as matchesEvent, I as XSTATE_INIT } from './createActor-ad3a1abe.esm.js';
|
|
2
2
|
import { createEmptyActor } from './xstate-actors.esm.js';
|
|
3
|
-
import { S as StateMachine } from './StateMachine-
|
|
3
|
+
import { S as StateMachine } from './StateMachine-8cea8974.esm.js';
|
|
4
4
|
import './validation-05f1d517.esm.js';
|
|
5
5
|
|
|
6
6
|
function simpleStringify(value) {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateGraph={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="@xstate.init",n="@xstate.spawn",o="@xstate.stop",r="@xstate.terminate",i="xstate.timer",c="xstate.logic.effect.resolve",a="xstate.logic.effect.reject",u="xstate.logic.effect.start";function h(t,e){return{type:"xstate.after",delay:t,stateId:e}}function d(t,e){return`xstate.after.${t}.${e}`}function f(t){return`xstate.timeout.${t}`}function l(t,e){return{type:"xstate.timeout.actor",actorId:t,sessionId:e}}function p(t){return`xstate.timeout.actor.${t}`}function y(t,e){return{type:"xstate.done.state",stateId:t,output:e}}function g(t,e){return{type:`xstate.error.${t}`,error:e}}function v(t){return{type:s,input:t}}function m(t){setTimeout(()=>{throw t})}const _="function"==typeof Symbol&&Symbol.observable||"@@observable";function x(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}const S={"@xstate.spawn":t=>t.system.spawnActor(t._parent,t),"@xstate.start":t=>t.system.startActor(t),"@xstate.raise":(t,e,s)=>t.system.scheduleTimer(t.self,s.id,s?.delay??0),"@xstate.sendTo":(t,e,s,n)=>(x(s),void 0!==n?.delay?t.system.scheduleTimer(t.self,n.id,n?.delay??0):t.system._relay(t.self,e,s)),"@xstate.cancel":(t,e)=>t.system.cancelTimer(t.self,e),"@xstate.stop":(t,e)=>t.system.stopActor(e),"@xstate.terminate":(t,e)=>t.system.terminateActor(t,e)},b=new WeakMap;function w(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 I=new WeakMap;function E(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{id:e,start:(e,{self:s,system:n})=>{const o=e.input.actor;if(!o||"stopped"===o.getSnapshot().status)return;const r=t(e.input,{self:s,system:n});if(!r)return;let i,c=!1;const a=()=>{c||(c=!0,r.unsubscribe(),i?.unsubscribe())},u=s._parent;u&&(i=u.subscribe({complete:a,error:a})),I.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===o?(I.get(s)?.unsubscribe(),I.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function A(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function k(){return E(({actor:t,eventType:e,mapper:s},{self:n,system:o})=>{const r="*"!==e&&e.endsWith(".*");return t.on(r?"*":e,t=>{r&&!as(t.type,e)||A(n,o,()=>s(t))})},"xstate.listener")}const O=k();function $(){return E(({actor:t,mappers:e},{self:s,system:n})=>{const{done:o,error:r,snapshot:i}=e;return t.subscribe({next:t=>{"done"===t.status&&o?A(s,n,()=>o(t.output)):"error"===t.status&&r?A(s,n,()=>r(t.error)):"active"===t.status&&i&&A(s,n,()=>i(t))},error:t=>{r&&A(s,n,()=>r(t))},complete:()=>{}})},"xstate.subscription")}const j=$(),T=Symbol();function M(t){return!!t[T]}function P(t){return M(t)?t._parent:t.self._parent}function R(t,e){if(!M(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:()=>P(e)}}),t}function z(){return this.action?.(...this.args)}function N(t=this.source.system){return t.emitEvent(this.source,this.event)}function D(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function K(t=this.actor.system){return t.spawnActor(this.source,this.actor)}function C(t=this.actor.system){return t.startActor(this.actor)}function V(t=this.source.system){return t.stopActor(this.actor)}function W(t=this.actor.system){const e="done"===this.status?{status:"done",output:this.output,error:void 0}:{status:"error",output:void 0,error:this.error};return t.terminateActor(this.actor,e)}function J(t=this.source.system){return t.scheduleTimer(this.source,this.id,this.delay??0)}function U(t=this.source.system){return x(this.event),void 0!==this.delay?t.scheduleTimer(this.source,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function L(t=this.source.system){return t.cancelTimer(this.source,this.id)}function B(t,e,s){if(!dt(e))return t;if("@xstate.cancel"===e.type){if(!t.timers?.[e.id])return t;const s={...t.timers};return delete s[e.id],{...t,timers:s}}if("@xstate.raise"!==e.type&&"@xstate.sendTo"!==e.type||void 0===e.delay)return t;let n=t._nextTimerId??0;const o=e.id??"xstate.timer.auto."+n++;e.id=o;const r="@xstate.raise"===e.type||e.target===s.self?"self":e.target;return{...t,timers:{...t.timers,[o]:{id:o,delay:e.delay,type:e.type,event:e.event,target:r}},_nextTimerId:n}}function q(t,e){return{...t,...e}}function F(t,e,...s){const n={action:e,args:s};return t.push(n),n}function G(t,e){const s={...t};for(const t of Object.keys(e))s[t]=Math.max(s[t]??0,e[t]);return s}function H(t,e,s){if("add"===e.type)return{...t,children:{...t.children,[e.id]:e.actor},...e.counters&&{_nextActorIds:G(t._nextActorIds,e.counters)}};const n={...t.children};let o=e.actor._parent===s.self;for(const t of Object.keys(n))n[t]===e.actor&&(o=!0,delete n[t]);if(!o)throw new Error(`Cannot stop non-child actor ${e.actor.id}`);return s.system._unregister(e.actor),{...t,children:n}}function X(t){if("object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action)return t}const Q=new WeakMap,Y=()=>({counters:new Map,explicitIds:new Set,stoppedIds:new Set});function Z(t){Q.set(t,Y())}function tt(t){return t.self._snapshot}function et(t,e,s){return Math.max(e.counters.get(s)??0,tt(t)?._nextActorIds?.[s]??0)}function st(t,e,s){const n=Q.get(t)??s??Y(),o=gs(e),r=et(t,n,o);return n.counters.set(o,r+1),{id:`${o}:${r}`,counters:{[o]:r+1}}}function nt(t,e,s){const n=Q.get(t)??s??Y(),o=tt(t)?.children?.[e],r=void 0!==o&&!n.stoppedIds.has(e)&&"active"===o.getSnapshot().status;if(n.explicitIds.has(e)||r)throw new Error(`Child actor id '${e}' is already in use`);n.explicitIds.add(e)}function ot(t,e,s){const n=ms(e);if(!n)return;n.prefix;const o=Q.get(t)??s??Y(),r=Math.max(et(t,o,n.prefix),n.index+1);return o.counters.set(n.prefix,r),{[n.prefix]:r}}function rt(t,e,s,n=!1,o=!0){const r=Q.get(t)??Y(),i={cancel:s=>{F(e,S["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{F(e,t.logger,...s)},raise:(n,o)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0!==o?.delay?F(e,S["@xstate.raise"],t,n,o):s.push(n)},spawn:(s,n)=>{const{logic:i,src:c}=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(`Actor source '${e}' is not provided`);return{logic:t,src:e}}return s?{logic:e,src:w(s,e)}:{logic:e,src:void 0}}(t,s);if(!o)return{id:n?.id??n?.registryKey??c??i.id};let a,u=n?.id;void 0===u?({id:u,counters:a}=st(t,c??i,r)):(nt(t,u,r),a=ot(t,u,r));const h=t.system.createActorRef(i,{...n,...void 0!==c&&{src:c},id:u,parent:t.self});return function(t,e,s,n){F(t,S["@xstate.spawn"],e).childUpdate={type:"add",actor:e,id:s,counters:n}}(e,h,u,a),h},sendTo:(n,o,r)=>{n?F(e,S["@xstate.sendTo"],t,n,o,r):s.push(g("communication",{message:"Unable to send event to an undefined actor",event:o}))},stop:s=>{if(s){const n=s;F(e,S["@xstate.stop"],t,n).childUpdate={type:"remove",actor:n},function(t,e){const s=Q.get(t);s&&(s.stoppedIds.add(e.id),s.explicitIds.delete(e.id))}(t,n)}}};return n&&Object.assign(i,{listen:(s,n,r)=>{if(!o)return{id:void 0};const i={actor:s,eventType:n,mapper:r},c=t.system.createActorRef(O,{input:i,parent:t.self});return F(e,S["@xstate.spawn"],c),c},subscribeTo:(s,n)=>{if(!o)return{id:void 0};const r={actor:s,mappers:"function"==typeof n?{snapshot:n}:n},i=t.system.createActorRef(j,{input:r,parent:t.self});return F(e,S["@xstate.spawn"],i),i}}),lt(i,(t,...s)=>{F(e,t,...s)})}function it(t,e){switch(t){case S["@xstate.spawn"]:{const[t]=e;return{kind:"builtin",exec:K,source:t._parent,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case S["@xstate.raise"]:{const[,t,s]=e;return{kind:"builtin",exec:J,source:e[0].self,event:t,id:s?.id,delay:s?.delay}}case S["@xstate.sendTo"]:{const[,t,s,n]=e;return{kind:"builtin",exec:U,source:e[0].self,target:t,event:s,id:n?.id,delay:n?.delay}}case S["@xstate.cancel"]:{const[,t]=e;return{kind:"builtin",exec:L,source:e[0].self,id:t}}case S["@xstate.stop"]:{const[,t]=e;return{kind:"builtin",exec:V,source:e[0].self,actor:t,id:t.id}}default:return}}function ct(t){const e=[t];return{kind:"builtin",exec:C,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function at(t,e,s){const n=[t,e,s,{}];return{kind:"builtin",exec:U,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:n}}function ut(t,e){if("done"!==e.status&&"error"!==e.status)throw new Error("Cannot terminate an active or stopped actor");const s="done"===e.status?{status:"done",output:e.output,error:void 0}:{status:"error",output:void 0,error:e.error},n=[t.self,s];return{kind:"builtin",exec:W,type:r,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:n}}function ht(t,e,[s,n]){const o="done"===s.status||"error"===s.status,i="done"===e?.status||"error"===e?.status,c=n.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===r);return!o||i||c?[s,n]:[s,[...n,ut(t,s)]]}function dt(t){return"builtin"===t.kind}function ft(t,e,s,n){let o=t;const r=[];for(const i of n){const n=M(s)?R({context:o.context,event:e,output:ts(e),children:o.children,actions:t.machine.sources.actions,actors:t.machine.sources.actors},s):{context:o.context,event:e,output:ts(e),self:s.self,system:s.system,parent:s.self._parent,children:o.children,actions:t.machine.sources.actions,actors:t.machine.sources.actors},c="function"==typeof i,a=X(i),u=c?i:!!a&&a.action.bind(null,...a.args);let h;if("object"==typeof i&&null!==i){const{type:t,childUpdate:e,...s}=i;h=s}if(a?.childUpdate&&(o=H(o,a.childUpdate,s)),u&&"_special"in u){r.push({kind:"action",exec:z,type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type??"(anonymous)":i.name||"(anonymous)",params:h,args:[],action:void 0});const t=u(n,gt);t&&("context"in t||"children"in t)&&(o={...o,...void 0!==t.context?{context:q(o.context,t.context)}:{},..."children"in t?{children:t.children}:{}});continue}if(!u||!("resolve"in u)){const t="object"==typeof i&&null!==i&&"action"in i&&"function"==typeof i.action?it(i.action,i.args):void 0,e="object"==typeof i&&null!==i&&!a,n={kind:t?"builtin":e?"emit":"action",type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type:i.name||"(anonymous)",params:t?void 0:h,args:"object"==typeof i&&"action"in i?i.args:[],...t?{}:e?{source:s.self,event:i}:{action:a?.action??(c?i:void 0)},...t?{}:{exec:e?N:z},...t};o=B(o,n,s),r.push(n);continue}}return[o,r]}function lt(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:pt,emit:pt,log:pt,raise:pt,spawn:yt,sendTo:pt,stop:pt,listen:yt,subscribeTo:yt,...t}),s}const pt=()=>{},yt=()=>({}),gt=lt({},pt);const vt=new WeakMap,mt=new WeakMap,_t=new Map;function xt(t){const e=t._peekKeyedActors;return e?e.call(t)??_t:t.keyedActors}function St(t){t._snapshotVersion++}function bt(t){return t._snapshotVersion}function wt(t,e,s){const n=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),o=new Map(s?.keyedActors??xt(t)),r=new WeakMap,i=Object.assign(Object.create(t),{children:n,keyedActors:o,reverseKeyedActors:r,_snapshot:{...s?.snapshot??t._snapshot},_snapshotVersion:s?.sourceVersion??t._snapshotVersion,_register:(t,e)=>(n.set(t,e),St(i),t),_unregister:t=>{t.sessionId&&n.delete(t.sessionId);const e=r.get(t);void 0!==e&&o.get(e)===t&&o.delete(e),r.delete(t),St(i)},_set:(t,e)=>{const s=o.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${String(t)}' already exists.`);o.set(t,e),r.set(e,t),St(i)},get:t=>o.get(t),getAll:()=>Object.fromEntries(o),_hasInspectionObservers:()=>!1,_sendInspectionEvent:()=>{}});for(const[t,e]of o)e&&r.set(e,t);for(const t of Object.values(e)){if(!t)continue;t.sessionId&&n.set(t.sessionId,t);const e=t.registryKey;e&&(o.set(e,t),r.set(t,e))}return i}function It(t){const e=vt.get(t);if(e)return e;const s=mt.get(t);if(!s)return;const n=s();return vt.set(t,n),mt.delete(t),n}function Et(t,e){const s=vt.get(t);if(s)return vt.set(e,s),!0;const n=mt.get(t);return!!n&&(mt.set(e,n),!0)}function At(t,e,s=e.system,n){mt.delete(t);const o=bt(s),r=n?It(n):void 0,i=r?.actor===e?r:It(t);if(i?.actor===e&&i.systemState.sourceSystem===s&&i.systemState.sourceVersion===o)return void vt.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=xt(s);let h=u.size?new Map(u):_t;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&&(h===_t&&(h=new Map),h.set(t,e))}vt.set(t,{actor:e,systemState:{...c,children:a,keyedActors:h,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:o}})}function kt(t,e,s=!0){const n=Mt(t);return n?(n.snapshot=e,n.materialized&&(n.materialized.self._snapshot=e)):t.self._snapshot=e,s&&e&&"object"==typeof e&&At(e,t.self),e}function Ot(t){return!!Mt(t)||!!t.self.options?._inert}function $t(t,e){kt(t,e,!1);const s=Mt(t);Tt.set(e,t);const n=()=>(At(e,t.self,t.system),It(e));return s&&(s.materialized?s.identityProvider=n:s.identityProvider??=n),function(t,e){vt.delete(t),mt.set(t,e)}(e,n),e}const jt=Symbol(),Tt=new WeakMap;function Mt(t){return t[jt]}function Pt(t){return Mt(t).materialize()}const Rt={[T]:!0,get _parent(){const t=Mt(this);return t.parentKnown?t.parent:Pt(this).self._parent},get self(){return Pt(this).self},get defer(){return Pt(this).defer},get id(){return Pt(this).id},get logger(){return Pt(this).logger},get sessionId(){return Pt(this).sessionId},get stopChild(){return Pt(this).stopChild},get system(){return Pt(this).system},get emit(){return Pt(this).emit},get actionExecutor(){return Pt(this).actionExecutor}};function zt(t,e,s,n,o){const r=e?.(),i=o??r?.actor,c=i?.system,a=i&&c?wt(c,s,o?void 0:r?.systemState):void 0,u=Ps(t,{_inert:!0,...i?{id:i.id,_sessionId:i.sessionId}:{},...a?{_systemRef:{current:a}}:{}});return i?._parent&&(u._parent=i._parent,u._address=void 0),n&&(u._snapshot=n),Object.create(u._actorScope,{defer:{value:()=>{}},stopChild:{value:t=>t._stop()},actionExecutor:{value:()=>{}}})}function Nt(t,e,s,n){const o=n??(e&&"object"==typeof e?Tt.get(e):void 0),r=o?Mt(o):void 0,i=e&&"object"==typeof e?function(t){return vt.get(t)}(e):void 0,c=r?.identityProvider??(e&&"object"==typeof e?function(t){const e=vt.get(t);return e?()=>e:mt.get(t)}(e):void 0),a={snapshot:e,sourceRef:c,sourceChildren:Ne(e)?e.children:{},identityProvider:r?.identityProvider??c,parent:s?._parent??r?.parent??i?.actor._parent,parentKnown:!(!s&&!r?.parentKnown&&!i&&e),materialize:()=>a.materialized??=zt(t,a.sourceRef,a.sourceChildren,a.snapshot,s)};if(!a.identityProvider&&!e){const e={},n=a.sourceRef,o=a.sourceChildren;let r,i;const c=()=>r??=zt(t,n,o,void 0,s);a.materialize=()=>{const t=c();return void 0!==a.snapshot&&(t.self._snapshot=a.snapshot),a.materialized=t},a.identityProvider=()=>{if(i)return i;const t=c();return At(e,t.self,t.system),i=It(e)}}const u=Object.create(Rt);return u[jt]=a,u}function Dt(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const n=e.match(/^(\d*)(\.?)(\d*)s$/i);if(n){const t=n[1]?parseInt(n[1],10):0,e=!!n[2],s=n[3]?parseInt(n[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:r,days:i,hours:c,minutes:a,seconds:u}=o.groups;if(!(r||i||c||a||u))return;const h=t=>t?Number(t.replace(",",".")):0;return 7*h(r)*24*60*60*1e3+24*h(i)*60*60*1e3+60*h(c)*60*1e3+60*h(a)*1e3+1e3*h(u)}(t)??t}function Kt(t,e,s){if("function"==typeof t)return t(s);const n=Dt(t,e);return"function"==typeof n?n(s):n}function Ct(t,e){return t._stateInputs?.[e]}function Vt(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function Wt(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Jt(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 Ut(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 Wt(t))if(!e.has(s)){const t=oe(s);for(const s of t)e.add(s)}}else for(const s of oe(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 Lt(t,e){const s=Ut(e),n=new Map;for(const t of s)n.has(t)||n.set(t,[]),t.parent&&(n.has(t.parent)||n.set(t.parent,[]),n.get(t.parent).push(t));const o=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(Vt(t))return t.key}const s={};for(const t of e)s[t.key]=o(t);return s};return o(t)}function Bt(t,e){return"compound"===e.type?Wt(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?Wt(e).every(e=>Bt(t,e)):"final"===e.type}const qt=t=>"#"===t[0];function Ft(t){switch(t.type){case"xstate.done.actor":case"xstate.error.actor":return`${t.type}.${t.actorId}`;case"xstate.snapshot.actor":return`xstate.snapshot.${t.actorId}`;case"xstate.done.state":return`xstate.done.state.${t.stateId}`;case"xstate.after":return`xstate.after.${t.delay}.${t.stateId}`;case"xstate.timeout":return`xstate.timeout.${t.stateId}`;case"xstate.timeout.actor":return`xstate.timeout.actor.${t.actorId}`;default:return}}function Gt(t,e,s){const n=e.children[s];return!n||!("sessionId"in t)||(void 0===n.sessionId||n.sessionId===t.sessionId)}function Ht(t,e){const s=function(t){const e=Ft(t);return e?[t.type,e]:[t.type]}(e),n=s.flatMap(e=>t.transitions.get(e)??[]),o=[...t.transitions.keys()].filter(t=>!s.includes(t)&&s.some(e=>as(e,t))).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return n.length?[...n,...o]:o}function Xt(t,e,s,n){const o=t.entry;t.entry=(t,r)=>(r.raise(s(t),{id:e,delay:n(t)}),"function"==typeof o?o(t,r):void 0);const r=t.exit;t.exit=(t,s)=>(s.cancel(e),"function"==typeof r?r(t,s):void 0)}function Qt(t,e,s){const n=ns(s.target),o=s.reenter??!1,r=ee(t,n);te(t,r);const i={...s,target:r,source:t,reenter:o,eventType:e,toJSON:()=>({...i,source:`#${t.id}`,target:r?r.map(t=>`#${t.id}`):void 0})};return i}function Yt(t,e){for(let s=t.parent;s;s=s.parent)if(s===e)return!0;return!1}function Zt(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 te(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 o=e[s],r=e[n],i=Zt(o,r);if(o===r||Yt(o,r)||Yt(r,o)||"parallel"!==i?.type)throw new Error(`Invalid target set for '${t.id}'`)}}function ee(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(qt(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return ie(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return ie(t.parent,n)}catch(e){throw new Error(`Invalid transition for '${t.id}': ${e.message}`)}})}function se(t){const e=ns(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?ie(t.parent,e):e);return te(t,s),{target:s,source:t,reenter:!1,eventType:"",to:t.config._historyDefaultTransition}}function ne(t){return"history"===t.type}function oe(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 Wt(s))t(e)}(t);for(const s of e)for(const n of Jt(s,t))e.add(n);return e}function re(t,e){if(qt(e))return t.machine.getStateNodeById(e);const s=t.states?.[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function ie(t,e){if("string"==typeof e&&qt(e))try{return t.machine.getStateNodeById(e)}catch{}const s=He(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=re(n,t)}return n}function ce(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=new Array(s.length),o=[t.machine.root,t];for(let e=0;e<s.length;e++){const r=re(t,s[e]);n[e]=r,o.push(r)}for(let t=0;t<s.length;t++)o.push(...ce(n[t],e[s[t]]));return o}function ae(t,e,s,n,o,r){if("string"==typeof e){const i=re(t,e).next(s,n,o,r);return i&&i.length?i:t.next(s,n,o,r)}const i=Object.keys(e),c=i[0];if(1===i.length){const i=ae(re(t,c),e[c],s,n,o,r);return i&&i.length?i:t.next(s,n,o,r)}const a=[];for(const c of i){const i=e[c];if(!i)continue;const u=ae(re(t,c),i,s,n,o,r);u&&a.push(...u)}return a.length?a:t.next(s,n,o,r)}function ue(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function he(t,e){for(const s of t)if(ue(s,e))return!0;return!1}function de(t,e){const s=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,n=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==s&&void 0!==n&&n<s&&([t,e]=[e,t]);const o=t instanceof Set?t:new Set(t);for(const t of e)if(o.has(t))return!0;return!1}function fe(t,e,s,n){const o=new Set,r=new Map,i=t=>{let o=r.get(t);return o||(o=ve([t],e,s,n),r.set(t,o)),o};for(const e of t){let t=!1;const s=new Set;for(const n of o)if(de(i(e),i(n)))if(ue(e.source,n.source))s.add(n);else{if("final"!==n.source.type||"final"===e.source.type){t=!0;break}s.add(n)}if(!t){for(const t of s)o.delete(t);o.add(e)}}return Array.from(o)}function le(t,e,s,n,o){let r;return i=>{if(!i.to)return _e(i,t,e,s,{resolveActions:n,selectionResult:o?.get(i)});let c=r?.get(i);return c||(c=_e(i,t,e,s,{resolveActions:n,selectionResult:o?.get(i)}),(r??=new Map).set(i,c)),c}}function pe(t,e,s){const n=e.historyValue,{targets:o}=s(t);if(!o)return[];const r=new Set;for(const t of o)if(ne(t))if(n[t.id])for(const e of n[t.id])r.add(e);else for(const n of pe(se(t),e,s))r.add(n);else r.add(t);return[...r]}function ye(t,e){let s=t;for(;"parallel"===s.type;){const t=Wt(s).find(t=>e.every(e=>e===t||ue(e,t)));if(!t)break;s=t}return s}function ge(t,e,s){const n=pe(t,e,s),{targets:o,reenter:r}=s(t);if(t._transitionDomain){if("internal"===t._transitionDomain&&"compound"===t.source.type&&n.every(e=>ue(e,t.source)))return t.source;const[e,...s]=n.concat(t.source);for(const t of Jt(e,void 0))if("compound"===t.type&&s.every(e=>ue(e,t)))return t;return}if(!(o?.some(ne)&&n.some(e=>e===t.source))&&n.every(e=>e===t.source||ue(e,t.source)))return r?t.source:ye(t.source,n);const[i,...c]=n.concat(t.source);for(const t of Jt(i,void 0))if(c.every(e=>ue(e,t)))return r?t:ye(t,n);return r?void 0:ye(t.source.machine.root,n)}function ve(t,e,s,n){const o=new Set;for(const r of t){const{targets:t,reenter:i}=n(r);if(t?.length){const t=ge(r,s,n);i&&r.source===t&&o.add(t);for(const s of e)ue(s,t)&&o.add(s)}}return[...o]}function me(t,e,s,n,o,r,i){const c=[];if(!t.length)return[e,c];{const a=new Set(e.nodes);let u=e.historyValue;const h=e.context,d=1===t.length?t:fe(t,a,e,le(e,n,s,!1,i)),f=le(e,n,s,!0,i),l=d.some(t=>{const{targets:e,reenter:s}=f(t);return!!e?.length||!!s}),p=(t,o,r,i)=>{if(2===t.length){const c=[],a=[];let u;const h=rt(s,c,a,!0),d=M(s)?R({context:o,event:n,children:r,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:i},s):{context:o,event:n,parent:s.self._parent,self:s.self,children:r,system:s.system,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:i},f=t(d,h);return void 0!==f?.context&&(u=q(o,f.context)),[c,u,a]}return[[Object.assign((e,n)=>t(M(s)?R({context:e.context,event:e.event,output:e.output,children:e.children,actions:e.actions,actors:e.actors,input:i},s):{...e,input:i},n),"_special"in t?{_special:!0}:{})],void 0,void 0]};let g=e;const v=(t,e)=>{const n=[],o=rt(s,n,[]);for(const s of t.invoke){const t=e[s.id];t&&o.stop(t)}return n},m=()=>{const t=ve(d,a,e,f);let o;t.sort((t,e)=>e.order-t.order);const i=[...a];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>Vt(t)&&ue(t,e):t=>t.parent===e;o??={...u},o[t.id]=i.filter(s)}for(const o of t){const t=Ct(e,o.id),[i,u,h]=o.exit?p(o.exit,g.context,e.children,t):[[],void 0,void 0];h?.length&&r.push(...h),u&&(g=Be(g,{context:u}));const[d,f]=ft(g,n,s,i);g=d,c.push(...f);const l=v(o,g.children);if(l.length){const[t,e]=ft(g,n,s,l);g=t,c.push(...e)}a.delete(o)}u=o||u};!o&&l&&m();let _=g.context;const x=[],b=[];for(const t of d){t.actions&&x.push(...Ye(t.actions));const e=f(t);void 0!==e.context&&(_=q(_,e.context)),e.actions&&x.push(...e.actions),e.internalEvents&&b.push(...e.internalEvents)}b.length&&r.push(...b);const w=()=>{const t=t=>{const e=g.machine.root;let o;if(void 0!==t.output&&t.parent){const i=r.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);o=i&&t.parent===e?i.output:Ze(t.output,g.context,n,s.self,_[t.id])}else if("parallel"===t.type){const e=r.find(e=>"xstate.done.state"===e.type&&e.stateId===t.id);o=e?.output}return void 0===e.output?t.parent===e?o:void 0:Ze(e.output,g.context,y(t.id,o),s.self)},i=new Set,h=new Set,l=new Map,v=(t,e)=>{for(const s of t)if(e&&!ue(s,e)||i.add(s),"parallel"===s.type)for(const t of Wt(s))he(i,t)||(i.add(t),m(t))},m=t=>{if(ne(t))if(u[t.id]){const e=u[t.id];for(const t of e)i.add(t),m(t);for(const s of e)v(Jt(s,t.parent),void 0)}else{const e=se(t),s=t.parent;h.add(s);const n=l.get(s)??[];n.push(e),l.set(s,n);const{targets:o}=f(e);for(const s of o??[])i.add(s),e===t.parent?.initial&&h.add(t.parent),m(s);for(const e of o??[])v(Jt(e,t.parent),void 0)}else{if("compound"===t.type){const e=f(t.initial).targets??[];for(const t of e)ne(t)||i.add(t);h.add(t);for(const t of e)m(t);for(const s of e)v(Jt(s,t),void 0);return}if("parallel"===t.type)for(const e of Wt(t))he(i,e)||(i.add(e),h.add(e),m(e))}};for(const t of d){const s=ge(t,e,f),{targets:n,reenter:o}=f(t);for(const e of n??[])ne(e)||t.source===e&&t.source===s&&!o||(i.add(e),h.add(e)),m(e);const r=pe(t,e,f);for(const e of r){const n=Jt(e,s);"parallel"===s?.type&&n.push(s),v(n,!t.source.parent&&o?void 0:s)}o&&s===t.source&&i.add(t.source)}if(o)for(const t of d[0]._statesForDefaultEntry??[e.machine.root])h.add(t);const _={...e._stateInputs};let x=!1;for(const t of d){const{targets:e,input:s}=f(t);if(s&&e)for(const t of e)_[t.id]=s,x=!0}const b=new Set,w={...g.children};for(const o of[...i].sort((t,e)=>t.order-e.order)){a.add(o);const i=[];let u=!1;for(const t of o.invoke){u=!0;let o=t.logic;"function"==typeof o&&(o=o({actors:e.machine.sources.actors,context:g.context,event:n,self:s.self}));const r="string"==typeof o?rs(e.machine,o):o;if(!r)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented`);const c="function"==typeof t.input?t.input({self:s.self,context:g.context,event:n,output:ts(n)}):t.input;nt(s,t.id);const a=s.system.createActorRef(r,{...t,input:c,parent:s.self,syncSnapshot:!!t.onSnapshot});i.push({action:S["@xstate.spawn"],args:[a]}),t.id&&(w[t.id]=a)}u&&(g=Be(g,{children:w}));let d=g.context,f=!1;const v=_[o.id];if(o.entry){const[t,e,s]=p(o.entry,d,w,v);i.push(...t),s?.length&&r.push(...s),e&&(d=e,f=!0)}if(f&&(g.context=d),h.has(o)){const t=[o.initial,...l.get(o)??[]].filter(Boolean);for(const e of t){const{actions:t,context:o,input:c,internalEvents:a}=_e(e,g,n,s);if(t&&i.push(...t),a?.length&&r.push(...a),void 0!==o&&(g.context=q(g.context,o)),c&&e.target)for(const t of e.target)_[t.id]=c,x=!0}}const[m,I]=ft(g,n,s,i);if(g=m,i.length=0,c.push(...I),"final"!==o.type)continue;const E=o.parent;let A="parallel"===E?.type?E:E?.parent,k=A||o;for("compound"===E?.type&&r.push(y(E.id,void 0!==o.output?Ze(o.output,g.context,n,s.self,v):void 0));"parallel"===A?.type&&!b.has(A)&&Bt(a,A);){b.add(A);const t={};for(const e of Wt(A)){if("final"===e.type){t[e.key]=void 0!==e.output?Ze(e.output,g.context,n,s.self,_[e.id]):void 0;continue}if("parallel"===e.type){const s=r.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);t[e.key]=s?.output;continue}const o=Wt(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==o?.output?Ze(o.output,g.context,n,s.self,_[o.id]):void 0}r.push(y(A.id,t)),k=A,A=A.parent}A||(g=Be(g,{status:"done",output:t(k)}))}x&&(g=Be(g,{_stateInputs:_}))},[I,E]=ft(g,n,s,x);g=I,c.push(...E),_&&_!==e.context&&(g=Be(g,{context:_})),(o||l)&&w();const A=[...a];if("done"===g.status){const t=[];A.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=Ct(g,e.id),[n,,o]=p(e.exit,g.context,g.children,s);t.push(...n),o?.length&&r.push(...o)}});const[e,o]=ft(g,n,s,t);g=e,c.push(...o);const[i,a]=Ee(g,n,s);g=i,c.push(...a);const[u,h]=Ae(g,n,s);g=u,c.push(...h)}return u===e.historyValue&&e.nodes.length===a.size&&e.nodes.every(t=>a.has(t))?g.context!==h?[g===e?Be(g):g,c]:[g,c]:[Be(g,{_nodes:A,historyValue:u}),c]}}function _e(t,e,s,n,o){let r;const i=()=>r??=M(n)?R({context:e.context,event:s,output:ts(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:Ct(e,t.source.id)},n):{context:e.context,event:s,output:ts(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:Ct(e,t.source.id)};if(t.to){const r=[],c=[],a=o?.selectionResult?.reusable?o.selectionResult.result:t.to(i(),rt(n,r,c,!0,o?.resolveActions??!0)),u=a?.target?ee(t.source,Ye(a.target)):void 0,h=a?.input??("function"==typeof t.input?t.input({context:e.context,event:s,output:ts(s)}):t.input);return{targets:u,context:a?.context,reenter:a?.reenter,actions:r,internalEvents:c,input:h}}const c="function"==typeof t.input?t.input({context:e.context,event:s,output:ts(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}}function xe(t,e,r,c,a=[]){let u=t;const h=a.slice();function d(t){if("xstate.done.actor"!==t.type&&"xstate.error.actor"!==t.type)return;const{actorId:e,sessionId:s}=t;if(!e)return;const n=u.children[e];if(!n)return;if(void 0!==n.sessionId&&n.sessionId!==s)return;const o={...u.children};if(delete o[e],r.system._unregister(n),u=Be(u,{children:o}),h.length){const[,t]=h.at(-1);h[h.length-1]=[u,t]}else h.push([u,[]])}function f(){const e=function(t){const e=[],s=[];for(const o of t){if(!dt(o)||o.type!==n)continue;const{actor:t,logic:r}=o,i=ct(t);r===O||r===j?e.push(i):s.push(i)}return[...e,...s]}(h.flatMap(([,t])=>t)),s=("active"===t.status||a.length>0)&&("done"===u.status||"error"===u.status);if(e.length||s){const t=s?[...e,ut(r,u)]:e;if(h.length){const[e,s]=h.at(-1);h[h.length-1]=[e,[...s,...t]]}else h.push([u,t])}return{snapshot:u,microsteps:h}}function l(t,n){if(!Ot(r)&&(e.type===s||(r.system._hasInspectionObservers?.()??1))){const t=r.self._collectedMicrosteps||[];t.push(...n),r.self._collectedMicrosteps=t}h.push(t)}if(e.type===o){const[t,s]=Ee(u,e,r),[n,o]=Ae(t,e,r);return u=Be(n,{status:"stopped"}),l([u,[...s,...o]],[]),f()}let p=function(t,e){if("xstate.done.actor"===t.type||"xstate.error.actor"===t.type||"xstate.snapshot.actor"===t.type||"xstate.done.state"===t.type||"xstate.after"===t.type||"xstate.timeout"===t.type||"xstate.timeout.actor"===t.type)return t;const s=(e,s,n)=>t.type.startsWith(e)?{...t,type:s,[n]:t[n]??t.type.slice(e.length)}:void 0,n=s("xstate.done.actor.","xstate.done.actor","actorId")??s("xstate.error.actor.","xstate.error.actor","actorId")??s("xstate.snapshot.","xstate.snapshot.actor","actorId")??s("xstate.done.state.","xstate.done.state","stateId")??s("xstate.timeout.actor.","xstate.timeout.actor","actorId")??s("xstate.timeout.","xstate.timeout","stateId");if(n)return n;const o="xstate.after.";if(!t.type.startsWith(o))return t;const r=[...e.idMap.keys()].sort((t,e)=>e.length-t.length).find(e=>t.type.endsWith(`.${e}`));if(!r)return t;const i=t.type.slice(13,-r.length-1);return{...t,type:"xstate.after",delay:Number.isNaN(+i)?i:+i,stateId:r}}(e,t.machine);if(e.type===i){const t=u.timers[e.id];if(!t)return f();const s={...u.timers};if(delete s[t.id],u=Be(u,{timers:s}),"@xstate.raise"===t.type)c.push(t.event),l([u,[]],[]);else{const e="self"===t.target?r.self:t.target;l([u,[at(r,e,t.event)]],[])}}if(p.type!==s&&p.type!==i){const e=p,s=function(t){return t.type.startsWith("xstate.error.")}(e),n=new Map,o=u.machine.getTransitionData(u,e,r,n);if(s&&!o.length)return"xstate.error.actor"!==e.type||Gt(e,u,e.actorId)?(u=Be(t,{status:"error",error:e.error}),l([u,[]],[]),d(e),f()):f();const i=me(o,t,r,p,!1,c,n);u=i[0],l(i,o),d(e)}if(!c.length&&!1===t.machine._hasEventlessTransitions)return f();let y=!0;const g=t.machine.options?.maxIterations??1/0;let v=0,m=0;for(;"active"===u.status;){if(m++,m>1e3)throw new Error("Microstep count exceeded 1000");if(v++,v>g)throw new Error(`Infinite loop detected (>${g} microsteps)`);let t,e=y?ke(u,p,r):[];const s=e.length?u:void 0;if(!e.length){if(!c.length)break;p=c.shift(),t=new Map,e=u.machine.getTransitionData(u,p,r,t)}const n=me(e,u,r,p,!1,c,t);u=n[0],y=u!==s,l(n,e),d(p)}return f()}function Se(t,e,s,n,o){return!!t.to&&Ie(t.to,e,s,n,o,n.machine.sources,t.source.id).enabled}const be=()=>{throw ls};let we;function Ie(t,e,s,n,o,r,i){let c;const a=P(o);a&&ps.push(a);try{c=t(R({context:e,event:s,output:ts(s),value:n.value,children:n.children,actions:r.actions,actors:r.actors,guards:r.guards,delays:r.delays,input:Ct(n,i)},o),we??=lt({emit:be,cancel:be,log:be,raise:be,spawn:be,sendTo:be,stop:be,listen:be,subscribeTo:be},be))}catch(t){if(t===ls)return{enabled:!0,result:void 0,reusable:!1};throw t}finally{a&&ps.pop()}return{enabled:void 0!==c,result:c,reusable:!0}}function Ee(t,e,s){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return[t,[]];const o=[],r=rt(s,o,[]);for(const t of n)r.stop(t);return ft(t,e,s,o)}function Ae(t,e,s){const n=Object.keys(t.timers);if(!n.length)return[t,[]];const o=[],r=rt(s,o,[]);for(const t of n)r.cancel(t);return ft(t,e,s,o)}function ke(t,e,s){const n=new Set,o=t.nodes.filter(Vt);for(const r of o)t:for(let o=r;o;o=o.parent)if(o.always)for(const r of o.always)if(Oe(r,e,t,o,s)){n.add(r);break t}return fe(Array.from(n),new Set(t.nodes),t,le(t,e,s,!1))}function Oe(t,e,s,n,o,r){if(t.matches&&!cs(e,t.matches))return!1;if(t._eventMatcher&&!t._eventMatcher(e,s))return!1;if(t.guard){const r=function(t,e){if(!M(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:()=>P(e)}}),t}({context:s.context,event:e,output:ts(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},o);if(!t.guard(r))return!1}if(t.to){const i=Ie(t.to,s.context,e,s,o,n.machine.sources,t.source.id);return r?.set(t,i),i.enabled}return!0}const $e={unsubscribe(){}},je="or restore this snapshot with embedded children on the runtime that owns them.";function Te(t){return!0===t._remote}const Me=Object.freeze({status:"active",output:void 0,error:void 0});function Pe(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(`Remote actor '${e.address}' has no local mailbox to receive "${t.type}". Its state lives with another runtime; install a runtime that can reach it (via \`createDurable\`'s adapter runtime operations, or \`system.runtime\`) before sending, ${je}`)},getSnapshot:()=>Me,getPersistedSnapshot(){throw new Error(`Cannot persist remote actor '${e.address}' from here: its state lives with the runtime that owns it. Persist it there, ${je}`)},start(){},_stop(){},stop(){throw new Error(`Cannot stop remote actor '${e.address}' directly: stopping is a co-located operation. Stop it through the system runtime that owns it (\`system.stopActor(ref)\`), ${je}`)},select(){throw new Error(`Cannot select from remote actor '${e.address}': its snapshot is not synchronously readable because its state lives with another runtime. Read it on the runtime that owns it, ${je}`)},get trigger(){throw new Error(`Remote actor '${e.address}' has no \`trigger\` shorthand: it requires a co-located actor. Use \`send(...)\`, which routes through the system runtime.`)},subscribe:()=>$e,on:()=>$e,_isRunning:()=>!1,toJSON:()=>({xstate$type:Es,id:e.id,address:e.address,src:e.src})},n=s;return s.ref=n,n}const Re=Object.freeze({});function ze(t){return t===Re||t&&Object.keys(t).length?t:Re}function Ne(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const De=function(t){return Ge(t,this.value)},Ke=function(t){return this.tags.has(t)},Ce=function(t){return this.machine?._canTransition(this,t)??!1},Ve=function(){const{nodes:t,_stateInputs:e,tags:s,machine:n,getMeta:o,getInputs:r,toJSON:i,can:c,hasTag:a,matches:u,...h}=this;return{...h,tags:Array.from(s)}},We=function(){const t={};for(const e of this.nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},Je=function(){return this._stateInputs};function Ue(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function Le(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??Lt(e.root,t._nodes),tags:Ue(t._nodes),children:ze(t.children),timers:ze(t.timers),historyValue:ze(t.historyValue),_stateInputs:ze(t._stateInputs),_nextTimerId:t._nextTimerId??0,_nextActorIds:t._nextActorIds,matches:De,hasTag:Ke,can:Ce,getMeta:We,getInputs:Je,toJSON:Ve};return s&&At(n,s),n}function Be(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:ze(s.children),timers:ze(s.timers),historyValue:ze(s.historyValue),_stateInputs:ze(s._stateInputs),_nextTimerId:s._nextTimerId??0,_nextActorIds:s._nextActorIds,matches:De,hasTag:Ke,can:Ce,getMeta:We,getInputs:Je,toJSON:Ve};return Et(t,e),e}const n=Le({...s,value:void 0},t.machine);return Et(t,n),n}function qe(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 Fe(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$type:Es,id:n.id};else{const o=Fe(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function Ge(t,e){const s=Xe(t),n=Xe(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&Ge(s[t],n[t]))}function He(t){if(es(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function Xe(t){if(Ne(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}(He(t))}function Qe(t){return es(t)?t:[t]}function Ye(t){return void 0===t?[]:Qe(t)}function Ze(t,e,s,n,o){if("function"==typeof t){return t({context:e,event:s,output:ts(s),self:n,input:o})}return t}function ts(t){if(function(t){return"xstate.done.actor"===t.type||"xstate.done.state"===t.type}(t)){return t.output}}function es(t){return Array.isArray(t)}function ss(t){return Qe(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function ns(t){if(void 0!==t&&""!==t)return Ye(t)}function os(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function rs(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.sources.actors[e];const[,n,o]=s,r=t.getStateNodeById(o).config.invoke,i=(Array.isArray(r)?r[n]:r).src;return"string"==typeof i?t.sources.actors[i]:i}function is(t){const e=t.nodes.flatMap(e=>[...e.transitions.values()].flatMap(e=>e.map(e=>{const s={type:e.eventType,...e.matches};return!("actorId"in s)||"xstate.done.actor"!==s.type&&"xstate.error.actor"!==s.type&&"xstate.snapshot.actor"!==s.type&&"xstate.timeout.actor"!==s.type||(s.sessionId=t.children[s.actorId]?.sessionId),s})));return e.filter((t,s)=>e.findIndex(e=>{const s=Object.keys(t);return s.length===Object.keys(e).length&&s.every(s=>Object.is(t[s],e[s]))})===s)}function cs(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}function as(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}async function us(t,e,s,n=e=>{t.system.sendEvent(t,t,e)}){const o=function(t,e){return t.getSnapshot().effects?.[e]}(t,e);if("done"===o?.status)return o.output;if("error"===o?.status)throw o.error;if("active"===o?.status)return function(t,e){return new Promise((s,n)=>{const o=t.subscribe(t=>{const r=t.effects?.[e];"done"===r?.status?(o.unsubscribe(),s(r.output)):"error"===r?.status&&(o.unsubscribe(),n(r.error))})})}(t,e);n({type:u,key:e});try{const t=await s();return n({type:c,key:e,output:t}),t}catch(t){throw n({type:a,key:e,error:t}),t}}function hs(t,e,s){const n=e;if(t!==e&&n.logic?.isInternalEventType?.(s.type))throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`)}let ds,fs=0;const ls=new Error("Transition effect"),ps=[];function ys(){return ds??=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)}`}(),`${ds}:${(fs++).toString(36)}`}function gs(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length&&"(machine)"!==e?e:"x"}function vs(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function ms(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 _s(t,e){return`${t?t.address:""}|${e}`}function xs(t,e,s){const n=t._snapshot._nextActorIds;(n[e]??0)>=s||(t._snapshot._nextActorIds={...n,[e]:s},St(t))}const Ss=Object.freeze({});function bs(t,e){return`${t.sessionId}.${e}`}class ws{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={systemId: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;const s="object"==typeof e.snapshot&&null!==e.snapshot?e.snapshot:void 0;this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef;const n=void 0;this._snapshot={_scheduledTimers:s?.scheduler??Ss,_nextActorIds:{}}}_recordSent(t,e,s,n,o){if(!this._inspectionObservers?.size||!t)return;const r=t;(r._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:o})}schedule(t,e,s){const n=bs(t,e);void 0!==this._timerMap?.[n]&&this.cancel(t,e);const o=t.getSnapshot()?.timers?.[e];if(o){const n="self"===o.target?t:o.target;this._recordSent(t,n,o.event,s,e)}const r=this._clock.now?.()??Date.now(),c={source:t,delay:s,id:e,scheduledAt:r,dueAt:r+s},a=bs(t,e);this._snapshot._scheduledTimers===Ss&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[a]=c,St(this);const u=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[a],delete this._snapshot._scheduledTimers[a],St(this),this._deliver(t,t,{type:i,id:e})},s);(this._timerMap??={})[a]=u}cancel(t,e){const s=bs(t,e),n=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==Ss&&delete this._snapshot._scheduledTimers[s],St(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.id)}}_deliver(t,e,s){!function(t,e,s){hs(t,e,s);const n=e;n._lastSourceRef=t,n._send(s)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),St(this),t}_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&&St(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(`Actor with registry key '${t}' already exists.`);(this._keyedActors??=new Map).set(t,e),(this._reverseKeyedActors??=new WeakMap).set(e,t),s!==e&&St(this)}inspect(t){const e=os(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>t.next?.(e))}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){hs(t,e,s),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){this._sendInspectionEvent({type:"@xstate.deadletter",actorRef:e,sourceRef:t,event:s,reason:n});const o=this.runtime?.deadLetter;if(o)return o(t,e,s,n)}runStep(t,e,s){const n=this.runtime?.runStep;return n?n(t,e,s):us(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 o=t.getSnapshot()?.timers?.[e];if(o){const n="self"===o.target?t:o.target;this._recordSent(t,n,o.event,s,e)}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(ps.length&&ps.includes(e))throw ls;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:o,id:r}=t[s];this.scheduleTimer(n,r,Math.max(0,o-(this._clock.now?.()??Date.now())))}}}let Is=!1;const Es="actorRef",As=Object.freeze([]);let ks=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Os=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function $s(t,e){try{t?.(e)}catch(t){m(t)}}function js(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function Ts(t,e){return new Ms(t,e)}class Ms{get address(){return this._address??=this._parent?`${this._parent.address}/${vs(this.id)}`:vs(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.eventListeners=void 0,this.logger=void 0,this._processingStatus=ks.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._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;const s=e?{...Os,...e}:Os,{clock:n,logger:o,parent:r,syncSnapshot:i,id:c,registryKey:a,inspect:u}=s;var h;this.system=r?r.system:s._systemRef?.current??function(t,e){return new ws(t,e)}(this,{clock:n,logger:o,snapshot:s.snapshot??s.state,createActorRef:Ts}),r||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system),u&&!r&&this.system.inspect(os(u)),this.sessionId=s._sessionId??`${(h=this.system)._identity.systemId}:${h._identity.nextSessionId++}`,this.id=function(t,e,s){if(void 0!==e){const n=ms(e);return n?xs(t,_s(s?.parent,n.prefix),n.index+1):s?.parent||xs(t,_s(void 0,e),1),e}const n=gs(s?.src),o=_s(s?.parent,n),r=t._snapshot._nextActorIds[o]??0;return xs(t,o,r+1),s?.parent||"x"===n||0!==r?`${n}:${r}`:n}(this.system,c,{parent:r,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=r,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 d=e?.snapshot??e?.state;this._restored=void 0!==d;try{if(d)this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(d,this._actorScope):d);else if(e?._inert);else{const[t,e]=ht(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}}catch(t){this._setSnapshot({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=>this.system.emitEvent(this,t);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===ks.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(`Cannot stop non-child actor ${t.id}`);t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=Is;try{Is=!0,t.exec()}finally{Is=e}};this._processingStatus!==ks.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,At(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,n]=ht(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),js(n,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??As)$s(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??As,actions:this._collectedActions??As,sent:this._collectedSent??As,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 js(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=os(t,e,s);if(this._processingStatus!==ks.Stopped)(this.observers??=new Set).add(n);else switch(this._snapshot.status){case"done":$s(n.complete);break;case"error":{const t=this._snapshot.error;n.error?$s(n.error,t):m(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,o)=>{const r=os(s,n,o);let i=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(i,n)||(i=n,r.next?.(n))},error:r.error,complete:r.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===ks.Running)return this;if(this._processingStatus===ks.Stopped)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=ks.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,v(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,v(this.options.input)):(function(t,e,s){const n=vt.get(t),o=bt(s);return n?.actor===e&&n.systemState.sourceSystem===s&&n.systemState.sourceVersion+1===o&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(n.systemState.root=e,n.systemState.sourceVersion=o,!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 Object.values(t)){const t=e&&void 0!==n.startedAt?Math.min(n.delay,Math.max(0,n.startedAt+n.delay-s)):n.delay;this.system.scheduleTimer(this,n.id,t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){let e,s;try{e=ht(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){s={err:t}}if(s)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(s.err)||this._inspectTransition(this._snapshot,t));if(!e)return;let n=this._snapshot;try{const[s,o]=e;n=s,this._setSnapshot(n),js(o,this._actorScope),this.update(n,t)}catch(e){return void(this._recoverOrError(e,n)||this._inspectTransition(this._snapshot,t))}t.type===o&&(this._stopProcedure(),this._complete())}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)$s(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===ks.Stopped?this:(this.mailbox?.clear(),this._processingStatus===ks.NotStarted?(this._processingStatus=ks.Stopped,this.system._unregister(this),this):(this._send({type:o}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers??As)$s(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_error(t){if(this._stopProcedure(),this.observers?.size){let e=!1;for(const s of this.observers){const n=s.error;e||=!n,$s(n,t)}this.observers.clear(),e&&m(t)}else this._parent||m(t);var e,s,n;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t,n=this.sessionId,{type:"xstate.error.actor",error:s,actorId:e,sessionId:n}))}_stopProcedure(){this._processingStatus===ks.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=ks.Stopped,this.system._unregister(this))}_send(t){if(this._processingStatus===ks.Stopped)return void this.system.deadLetter(this._lastSourceRef,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new e(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue(t)}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$type:Es,id:this.id,address:this.address,src:"string"==typeof this.src?this.src:void 0}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[_](){return this}getSnapshot(){return this._snapshot}}function Ps(t,e){return new Ms(t,e)}function Rs(t,e){const s=t.check(e);if(s)throw s}const zs=new WeakMap;function Ns(t,e,s){const n=function(t){let e=zs.get(t);return e||(e=new Map,zs.set(t,e)),e}(t);if(void 0!==e&&n.has(e))return;const o=s();n.set(e??Symbol(),{cleanup:"function"==typeof o?o:void 0})}function Ds(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===o)return[{...e,status:"stopped",input:void 0},[D("xstate.logic.cleanup",()=>function(t){const e=zs.get(t);if(e){for(const{cleanup:t}of e.values())t?.();zs.delete(t)}}(n.self))]];if(s.type===u)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if(s.type===c)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if(s.type===a)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const r=[],i={},h={emit:t=>{r.push(function(t,e){return{kind:"emit",exec:N,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&r.push(at(n,e,t))},raise:t=>{r.push(at(n,n.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{e.effects?.[t]||(r.push(D("xstate.logic.effect",(e=n.self.system)=>Ns(n.self,t,()=>s(e)),{key:t})),i[t]={status:"active"})})(t,s);const o=t;r.push(D("xstate.logic.effect",(t=n.self.system)=>Ns(n.self,void 0,()=>o(t))))}},d=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},h),f={...e,...d||{}};return("context"in e||void 0!==d?.context)&&(f.context=d?.context??e.context),(d?.effects||Object.keys(i).length)&&(f.effects={...e.effects,...d?.effects,...i}),ht(n,e,[f,r])},s=(s,o,r)=>{t.validator&&Rs(t.validator,{kind:"event",logic:n,event:o,eventOrigin:r.self._lastSourceRef?"actor":"external"});const i=e(s,o,r);return t.validator&&Rs(t.validator,{kind:"result",logic:n,snapshot:i[0],effects:i[1]}),i},n={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,n)=>{if(!n?.restored)return;const[o,r]=s(t,v(t.input),e);Object.assign(t,o);for(const t of r)e.actionExecutor(t)},initialTransition:(e,o)=>{t.validator&&Rs(t.validator,{kind:"input",logic:n,input:e});const r=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),i={status:"active",output:void 0,error:void 0,input:e};return void 0!==r&&(i.context=r),s({...i},v(e),o)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const Ks=Ds({context:void 0,run:()=>{}});const Cs=new WeakMap;const Vs={};class Ws{constructor(t,e){this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.schemas=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.invoke=void 0,this.on=void 0,this.after=void 0,this.events=void 0,this.ownEvents=void 0,this._candidateCache=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[];const s=this.config.states?Object.keys(this.config.states)[0]:void 0;if(this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(void 0!==s?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.schemas=this.config.schemas,function(t){const e=t.config;if("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(`Missing history target on "${t.id}"`);if("choice"!==t.type)return;if("function"!=typeof e.choice)throw new Error(`Missing \`choice\` function on "${t.id}"`)}(this),this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const r=n[o];s[r]=e(t[r],r,t,o)}return s}(this.config.states,(t,e)=>new Ws(t,{_parent:this,_key:e,_machine:this.machine})):Vs,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}".`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.entry&&(this.entry._special=!0),this.exit&&(this.exit._special=!0),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=Ye(t.tags).slice(),this.invoke=Ye(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,o=(r=this.id,`${e}.${r}`);var r;const i=t.id??o,c="string"==typeof s?s:`xstate.invoke.${o}`;return{...t,src:c,logic:s,id:i,registryKey:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,o=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===o.length)return[];const r=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;r.push({event:h(n,t.id),timerId:d(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0})}var i;void 0!==s&&n&&r.push({event:(i=t.id,{type:"xstate.timeout",stateId:i}),timerId:f(t.id),delay:s,transitions:n,fromDelaysMap:!0});for(const t of o)r.push({event:l(t.id),timerId:p(t.id),resolveEvent:({children:e})=>l(t.id,e[t.id]?.sessionId),eventMatcher:(e,s)=>Gt(e,s,t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1});const c=[];for(const{event:e,timerId:s,resolveEvent:n,eventMatcher:o,delay:i,transitions:a,fromDelaysMap:u}of r){Xt(t,s,n??(()=>e),e=>Kt(i,u?e.delays:{},{context:e.context,event:e.event,stateNode:t,input:e.input}));const{type:r,...h}=e;for(const t of ss(a))c.push({...t,matches:{...t.matches,...Object.fromEntries(Object.entries(h).filter(([,t])=>void 0!==t))},event:r,delay:i,_eventMatcher:o})}return c.map(e=>({...Qt(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map,s=(t,s)=>{e.set(t,[...e.get(t)??[],...s])};if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error("Null event transition key");const n=t.config.on[s];e.set(s,Js(n,e=>Qt(t,s,e)))}if(t.config.onDone){const e="xstate.done.state";s(e,Js(t.config.onDone,s=>Qt(t,e,{...s,matches:{...s.matches,stateId:t.id}})))}if(t.config.onError){const s="xstate.error.*";e.set(s,Js(t.config.onError,e=>Qt(t,s,e)))}const n=(e,s,n)=>Qt(t,e,{matches:{actorId:n},_eventMatcher:(t,e)=>Gt(t,e,n),to:(t,e)=>(e.cancel(s),{})}),o=(e,s,n)=>{const{target:o,to:r,reenter:i,...c}=s;return Qt(t,e,{...c,reenter:i,to:(t,e)=>{if(r){let s=!1;const o=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const o=Reflect.get(t,e,n);return"function"!=typeof o?o:(...e)=>(s=!0,o.apply(t,e))}}),i=r(t,o);return(void 0!==i||s)&&e.cancel(n),i}return e.cancel(n),{target:o,reenter:i}}})};for(const e of t.invoke){const r=t=>({...t,matches:{...t.matches,actorId:e.id},_eventMatcher:(t,s)=>Gt(t,s,e.id)}),i=void 0!==e.timeout?p(e.id):void 0;if(e.onDone){const c="xstate.done.actor",a=Js(e.onDone,e=>{const s=r(e);return i?o(c,s,i):Qt(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,Js(e.onError,e=>{const s=r(e);return i?o(n,s,i):Qt(t,n,s)}))}if(e.onSnapshot){const n="xstate.snapshot.actor";s(n,Js(e.onSnapshot,e=>Qt(t,n,r(e))))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),"choice"===this.type?this.always=function(t){const e=t.config.choice,s=e=>{if(!e||void 0===e.target)throw new Error(`Choice "${t.id}" has no target`);return e};return[Qt(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=Js(this.config.always,t=>Qt(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=Cs.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Cs.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,o="object"==typeof e&&null!==e?e.to:void 0,r=(Array.isArray(s)?s:s?[s]:[]).map(e=>e.startsWith("#")?t.machine.getStateNodeById(e.slice(1)):t.states[e]);if(r.some(t=>!t))throw new Error(`Initial state not found on "#${t.id}"`);return{source:t,target:r.length?r:void 0,input:n,to:o}}(this,this.config.initial))}next(t,e,s,n){const o=function(t){const e=Ft(t);return e?`${t.type}|${e}`:t.type}(e);let r=this._candidateCache?.get(o);r||(r=Ht(this,e),(this._candidateCache??=new Map).set(o,r));for(const o of r){if(Oe(o,e,t,this,s,n))return[o]}}}function Js(t,e){const s=ss(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}function Us(t,e){if(!t)return;if(Object.hasOwn(t,e))return t[e];const s=Object.keys(t).find(t=>as(e,t));return void 0===s?void 0:t[s]}let Ls,Bs;function qs(){if(Bs)return Bs;const t=Ls??=Ps({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 Bs={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},Bs}class Fs{constructor(t,e,s){this.config=t,this.validator=s,this._internalEventType=void 0,this.version=void 0,this.schemas=void 0,this.snapshotSchema=void 0,this.eventSchema=void 0,this.sources=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._hasEventlessTransitions=void 0,this._json=void 0,this.id=t.id||"(machine)",this.sources={actors:t.actors??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...e},this.version=this.config.version,this.schemas=this.config.schemas,this.snapshotSchema={"~standard":{version:1,vendor:"xstate",validate:async t=>{if(null===t||"object"!=typeof t)return{issues:[{message:"Expected a persisted snapshot."}]};const e={historyValue:{},timers:{},...t},s=this.schemas?.context;let n=e.context;if(s){const t=await s["~standard"].validate(n);if(t.issues)return{issues:[{message:`Invalid context for machine '${this.id}' version '${this.version}': ${t.issues[0]?.message}`}]};n=t.value}for(const t of["value","children"])if(!(t in e))return{issues:[{message:`Persisted snapshot is missing '${t}'.`}]};if(!["active","done","error","stopped"].includes(e.status))return{issues:[{message:"Persisted snapshot has invalid status."}]};for(const t of["children","historyValue","timers"])if(null===e[t]||"object"!=typeof e[t]||Array.isArray(e[t]))return{issues:[{message:`Persisted snapshot has invalid '${t}'.`}]};try{this.resolveState({value:e.value,context:n})}catch(t){return{issues:[{message:t instanceof Error?t.message:"Persisted snapshot has invalid state value."}]}}return{value:{...e,context:n}}}}},this.eventSchema={"~standard":{version:1,vendor:"xstate",validate:async t=>{if(null===t||"object"!=typeof t||"string"!=typeof t.type)return{issues:[{message:"Expected an event object."}]};const e=t,s=this.schemas?.events,n=this.schemas?.internalEvents,o=e.type.startsWith("xstate.")||e.type.startsWith("@xstate."),r=Us(n,e.type)??Us(s,e.type);if((s||n)&&!r&&!o)return{issues:[{message:`Unknown event '${e.type}' for machine '${this.id}' version '${this.version}'.`}]};if(!r)return{value:e};const{type:i,...c}=e,a=await r["~standard"].validate(c);return a.issues?a:null===a.value||"object"!=typeof a.value?{issues:[{message:"Expected an event payload."}]}:{value:{...a.value,type:i}}}}},this.internalEventDescriptors=[...Object.keys(this.schemas?.internalEvents??{}),...this.config.internalEvents??[]],this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.initialTransition=this.initialTransition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new Ws(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const o=n.config.id,r=n.config.route,i=({event:t})=>t.to===`#${o}`;if("function"==typeof r)return e.push(Qt(t,"xstate.route",{guard:i,to:t=>{const e=r(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(n.states&&s(n.states));const{guard:c,...a}=r,u={...a,guard:i,target:`#${o}`};e.push(Qt(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:o}=this.sources,r=new Fs(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}},this.validator);return r._json=this._json,r}resolveState(t){const e=(s=this.root,n=t.value,Lt(s,Ut(ce(s,n))));var s,n;const o=Ut(ce(this.root,e));return Le({_nodes:[...o],value:e,context:t.context||{},children:{},status:Bt(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const n=!s,o=s??Nt(this,t);this.validator&&Rs(this.validator,{kind:"event",logic:this,event:e,eventOrigin:s&&s.self._lastSourceRef?"actor":"external"}),n&&kt(o,t,!1),Z(o);const r=this._transitionFast(t,e,o);if(r){n&&kt(o,r,!1);const e=n&&r!==t?$t(o,r):this._attachPureActorRef(r,o);return this.validator&&Rs(this.validator,{kind:"result",logic:this,snapshot:e,effects:[]}),[e,[]]}const{snapshot:i,microsteps:c}=xe(t,e,o,[]);n&&kt(o,i,!1);const a=n?i===t?i:$t(o,i):this._attachPureActorRef(i,o),u=this._collectEffects(c);return this.validator&&Rs(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 Ot(e)||s&&e.self._actorScope===e&&void 0===e.self._snapshot||At(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 o=n.transitions.get(e.type);if(1!==o?.length)return;const r=o[0];if(r.guard||r.actions||r.to||r.reenter||r.input||"function"==typeof r.context||r.target&&1!==r.target.length)return;const i=r.target?.[0]??n,c=i!==n;if(i.parent!==this.root||"atomic"!==i.type||c&&(i.entry||i.invoke.length||i.always?.length||i.after?.length))return;const a=void 0!==r.context?{...t.context,...r.context}:t.context;if(!Ot(s)&&(s.system._hasInspectionObservers?.()??1)){const t=s.self._collectedMicrosteps||[];t.push(r),s.self._collectedMicrosteps=t}return Be(t,{...a!==t.context?{context:a}:{},...c?{_nodes:[this.root,i]}:{}})}microstep(t,e,s){const{microsteps:n}=xe(t,e,s,[]),o=new Array(n.length);for(let t=0;t<n.length;t++)o[t]=n[t][0];return o}getTransitionData(t,e,s,n){return ae(this.root,t.value,t,e,s,n)||[]}isInternalEventType(t){if(t===i)return!0;for(const e of this.internalEventDescriptors)if(as(t,e))return!0;return!1}_canTransition(t,e){const s=qs(),n=this.getTransitionData(t,e,s);if(!n?.length)return!1;for(const o of n){if(void 0!==o.target)return!0;const n=_e(o,t,e,s,{resolveActions:!1});if(n.targets?.length||n.context||Se(o,t.context,e,t,s))return!0}return!1}getExecutionErrorEvent(t,e){if("active"===t?.status&&t.nodes?.some(t=>t.config.onError))return g("execution",e)}_getPreInitialState(t,e){const{context:s}=this.config,n=Le({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const o={},r=function(t,e,s){return(n,o)=>{const r=w(e,n),i=o?.id??st(t,r??n).id;void 0!==o?.id&&(nt(t,o.id),ot(t,o.id));const c=t.system.createActorRef(n,{id:i,parent:t.self,syncSnapshot:o?.syncSnapshot,input:o?.input,src:r??n,registryKey:o?.registryKey});return s[c.id]=c,c}}(t,this.sources.actors,o),i=s(function(t,e){return M(e)?(Object.defineProperty(t,"self",{enumerable:!0,get:()=>e.self}),t):Object.assign(t,{self:e.self})}({spawn:r,input:e.input,actors:this.sources.actors},t)),[c]=ft(n,e,t,[]);if(i&&(c.context=i),Object.keys(o).length>0){c.children={...c.children,...o};const e=function(t){const e=Q.get(t)?.counters;if(e?.size)return Object.fromEntries(e)}(t);e&&(c._nextActorIds=G(c._nextActorIds,e))}return c}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){this.validator&&Rs(this.validator,{kind:"input",logic:this,input:t});const s=!e,o=e??Nt(this);Z(o);const r=v(t),i=[],c=this._getPreInitialState(o,r),a=Object.values(c.children).filter(Boolean).map(t=>function(t){const e=[t];return{kind:"builtin",exec:K,type:n,source:t._parent,params:void 0,args:e,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}(t)),u=(t,e)=>{s&&kt(o,t,!1);const n=s?$t(o,t):this._attachPureActorRef(t,o,!0),r=this._collectEffects(e);return this.validator&&Rs(this.validator,{kind:"result",logic:this,snapshot:n,effects:r}),[n,r]};try{const[t,e]=function(t,e,s,n,o){const r=[...oe(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 Wt(t))c(e)};return c(t),me([{target:r.filter(t=>!r.some(e=>e!==t&&ue(e,t))),source:t,reenter:!0,eventType:null,toJSON:null,_statesForDefaultEntry:[...i]}],e,s,n,!0,o)}(this.root,c,o,r,i),{snapshot:s,microsteps:n}=xe(t,r,o,i,[[t,[...a,...e]]]);return u(s,n)}catch(t){if(!this.root.config.onError)throw t;const e=xe(c,g("execution",t),o,[],[[c,a]]);return u(e.snapshot,e.microsteps)}}start(t){if(!t?.children)return;const e=t.children;for(const t in e){if(!Object.hasOwn(e,t))continue;const s=e[t];s._rehydrated&&"active"===s.getSnapshot?.().status&&s.start()}}getStateNodeById(t){const e=He(t),s=e.slice(1),n=qt(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return ie(o,s)}getPersistedSnapshot(t,e){return function(t,e){const{nodes:s,_stateInputs:n,tags:o,machine:r,children:i,timers:c,context:a,can:u,hasTag:h,matches:d,getMeta:f,getInputs:l,toJSON:p,...y}=t,g={},v={},m=!1!==e?.embedChildren;for(const t in i){const s=i[t];if(!("string"==typeof s.src||e&&"__unsafeAllowInlineActors"in e))throw new Error("An inline child actor cannot be persisted.");const n=m&&!Te(s);if(!n&&"string"!=typeof s.src)throw new Error(`Unable to persist child '${t}' by address: it requires a registered source key.`);g[t]={address:s.address,...n?{snapshot:s.getPersistedSnapshot(e)}:{remote:!0,incarnation:Te(s)?s.sessionId:void 0},src:s.src,registryKey:s.registryKey,syncSnapshot:s._syncSnapshot}}const _=It(t)?.actor,x=_?.system?._clock?.now?void 0:_?.system?._snapshot?._scheduledTimers;for(const e in c){const s=c[e];let n,o=s.event;if("xstate.timeout.actor"===o.type&&(o={...o},delete o.sessionId),"self"===s.target)n="self";else{const o=Object.entries(i).find(([,t])=>t===s.target)?.[0];if(o)n=o;else{if(s.target!==It(t)?.actor._parent)throw new Error(`Unable to persist timer '${e}': target actor '${s.target.id}' is no longer addressable from this snapshot.`);n={type:"parent"}}}const r=x?.[`${_.sessionId}.${e}`],a=r?r.dueAt-s.delay:s.startedAt;v[e]={id:s.id,delay:s.delay,type:s.type,event:o,target:n,...void 0!==a&&{startedAt:a}}}const S={...y,context:Fe(a),children:g,timers:v,historyValue:qe(y.historyValue)};return n&&Object.keys(n).length>0&&(S.stateInputs=n),void 0!==r.version&&(S.machine={id:r.id,version:r.version},S.version=r.version),S}(t,e)}restoreSnapshot(t,e){const s=!e,n=e??Nt(this),o=t.machine,r=o&&"object"==typeof o&&"function"==typeof o.transition&&"root"in o?void 0:o,i=t.version,c="string"==typeof r?.version?r.version:i;if(void 0!==i&&void 0!==r?.version&&r.version!==i)throw new Error(`Persisted snapshot version '${i}' conflicts with machine version '${r.version}'.`);if(r&&"string"==typeof r.id&&r.id!==this.id)throw new Error(`Machine ID mismatch: persisted snapshot machine '${r.id}' does not match '${this.id}'.`);if(c!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${c}' does not match machine version '${this.version}'.`);t=e(t,c)}const a=t,u={},h=a.children;for(const t of Object.keys(h)){const e=h[t];if(!0===e.remote&&void 0!==e.address){if("string"!=typeof e.src)throw new Error(`Unable to restore remote child '${t}': a child referenced by address requires a registered source key.`);const s=Pe(n.system,{id:t,address:e.address,src:e.src,parent:n.self,registryKey:e.registryKey,syncSnapshot:e.syncSnapshot,incarnation:e.incarnation});e.registryKey&&n.system._set(e.registryKey,s),u[t]=s;continue}const s=e.snapshot,o=e.src,r="string"==typeof o?rs(this,o):o;if(!r){throw new Error(`Unable to restore child actor '${t}': child source '${"string"==typeof o?o:"<unknown>"}' is not provided in machine '${this.id}'.`)}const i=n.system.createActorRef(r,{id:t,parent:n.self,syncSnapshot:e.syncSnapshot,snapshot:s,src:o,registryKey:e.registryKey});i._rehydrated=!0,u[t]=i}const d={},f=a.timers??{};for(const[t,e]of Object.entries(f)){let s=e.event;if("xstate.timeout.actor"===s.type){const t=s.actorId,e=u[t];e&&(s=l(t,e.sessionId))}const o="string"==typeof e.target?"self"===e.target?"self":u[e.target]:n.self._parent;if(!o){const s="string"==typeof e.target?e.target:e.target.type;throw new Error(`Unable to restore timer '${t}': target actor '${s}' is unavailable.`)}d[t]={...e,event:s,target:o}}const p=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const s of Object.keys(t)){const n=t[s];for(const t of n){let n;if(t instanceof Ws)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(a.historyValue),y=(t,e,s)=>{const n=t=>new Error(`Persisted snapshot references state '${t.join(".")}' which does not exist on machine '${this.id}'.`);if("string"!=typeof t){if(t&&"object"==typeof t)for(const o of Object.keys(t)){const r=e.states[o];if(!r)throw n(s.concat(o));y(t[o],r,s.concat(o))}}else if(!e.states[t])throw n(s.concat(t))};y(a.value,this.root,[]);const g=Array.from(Ut(ce(this.root,a.value))),{version:v,_nextActorId:m,..._}=t;let x=_._nextActorIds;for(const t of Object.keys(h)){const e=ms(t);e&&(x?.[e.prefix]??0)<=e.index&&(x={...x,[e.prefix]:e.index+1})}const S=Le({..._,children:u,timers:d,_nextActorIds:x,_nodes:g,value:a.value,historyValue:p,_stateInputs:a.stateInputs??{}},this,n.self),b=new WeakSet;return function t(e){if(!b.has(e)){b.add(e);for(const s of Object.keys(e)){const n=e[s];if(n&&"object"==typeof n){if("xstate$type"in n&&n.xstate$type===Es){e[s]=u[n.id];continue}t(n)}}}}(S.context),s?(kt(n,S,!1),$t(n,S)):this._attachPureActorRef(S,n)}}function Gs(t){return JSON.stringify(t)}function Hs(t){const e=Object.keys(t.context).length?`(${JSON.stringify(t.context)})`:"",s=t.nodes.filter(t=>"atomic"===t.type||"final"===t.type).map(({id:e,path:s})=>{const n=t.getMeta()[e];if(!n)return`"${s.join(".")}"`;const{description:o}=n;return"function"==typeof o?o(t):o?`"${o}"`:JSON.stringify(t.value)});return`state${1===s.length?"":"s"} `+s.join(", ")+` ${e}`.trim()}const Xs=()=>(t,e)=>pn(t,e),Qs=()=>(t,e)=>yn(t,e);class Ys{getDefaultOptions(){return{serializeState:t=>Gs(t),serializeEvent:t=>Gs(t),serializeTransition:(t,e)=>`${Gs(t)}|${e?.type}`,events:[],stateMatcher:(t,e)=>"*"===e,logger:{log:console.log.bind(console),error:console.error.bind(console)}}}constructor(t,e){this.testLogic=t,this.options=void 0,this.defaultTraversalOptions=void 0,this._toTestPath=t=>{const e=t.steps.map(t=>function(t){const{type:e,...s}=t;return`${e}${Object.keys(s).length?` (${JSON.stringify(s)})`:""}`}(t.event)).join(" → ");return{...t,test:e=>this.testPath(t,e),description:Ne(t.state)?`Reaches ${Hs(t.state).trim()}: ${e}`:JSON.stringify(t.state)}},this.options={...this.getDefaultOptions(),...e}}getPaths(t,e){const s=e?.allowDuplicatePaths??!1,n=t(this.testLogic,this._resolveOptions(e));return(s?n:((t,e=Gs)=>{const s=[];t.forEach(t=>{s.push({path:t,eventSequence:t.steps.map(t=>e(t.event))})}),s.sort((t,e)=>e.path.steps.length-t.path.steps.length);const n=[];t:for(const t of s){e:for(const e of n){for(const s in t.eventSequence)if(t.eventSequence[s]!==e.eventSequence[s])continue e;continue t}n.push(t)}return n.map(t=>t.path)})(n)).map(this._toTestPath)}getShortestPaths(t){return this.getPaths(Xs(),t)}getShortestPathsFrom(t,e){const s=[];for(const n of t){const t=this.getShortestPaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(un(n,e)))}return s}getSimplePaths(t){return this.getPaths(Qs(),t)}getSimplePathsFrom(t,e){const s=[];for(const n of t){const t=this.getSimplePaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(un(n,e)))}return s}getPathsFromEvents(t,e){return ln(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return dn(this.testLogic,this.options)}async testPath(t,e,s){const n={steps:[],state:{error:null}};try{for(const o of t.steps){const t={step:o,state:{error:null},event:{error:null}};n.steps.push(t);try{await this.testTransition(e,o)}catch(e){throw t.event.error=e,e}try{await this.testState(e,o.state,s)}catch(e){throw t.state.error=e,e}}}catch(e){throw e.message+=function(t,e,s){const n={formatColor:(t,e)=>e,serializeState:Gs,serializeEvent:Gs,...s},{formatColor:o,serializeState:r,serializeEvent:i}=n,{state:c}=t,a=r(c,t.steps.length?t.steps[t.steps.length-1].event:void 0);let u="",h=!1;return u+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=r(t.step.state,e>0?s[e-1].step.event:void 0),c=i(t.step.event);return[`\tState: ${h?o("gray",n):t.state.error?(h=!0,o("redBright",n)):o("greenBright",n)}`,`\tEvent: ${h?o("gray",c):t.event.error?(h=!0,o("red",c)):o("green",c)}`].join("\n")}).concat(`\tState: ${h?o("gray",a):e.state.error?o("red",a):o("green",a)}`).join("\n\n"),u}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),o=this._getStateTestKeys(t,e,n);for(const s of o)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},o=Object.keys(n).filter(t=>s.stateMatcher(e,t));return!o.length&&"*"in n&&o.push("*"),o}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function Zs(t,e){if(t===e)return!0;if(void 0===t||void 0===e)return!1;if("string"==typeof t||"string"==typeof e)return t===e;const s=Object.keys(t),n=Object.keys(e);return s.length===n.length&&s.every(s=>Zs(t[s],e[s]))}function tn(t,e,s,{serializeEvent:n}){if(!e||s&&Zs(s.value,t.value))return"";const o=s?` from ${Gs(s.value)}`:"";return` via ${n(e)}${o}`}function en(){const t=Ps(Ks);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function sn(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function nn(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function on(t){return JSON.stringify(t)}function rn(t,e){const{events:s,...n}=e??{};return{serializeState:nn,serializeEvent:on,events:t=>{const e="function"==typeof s?s(t):s??[];return is(t).flatMap(t=>{const s=e.filter(e=>cs(e,t));return s.length?s:[t]})},fromState:t.getInitialSnapshot(en(),e?.input),...n}}function cn(){return{serializeState:t=>JSON.stringify(t),serializeEvent:on}}function an(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?rn(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:on,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function un(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}}function hn(t){return Array.isArray(t)?t[0]:t}function dn(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:r,filterEvents:i,limit:c,fromState:a,stopWhen:u}=an(t,e),h=en(),d={};let f=0;const l=[{nextState:a??t.getInitialSnapshot(h,e.input),event:void 0,prevState:void 0}],p=new Map;for(;l.length;){const{nextState:t,event:e,prevState:a}=l.shift();if(f++>c)throw new Error("Traversal limit exceeded");const y=o(t,e,a);if(d[y])continue;if(p.set(y,t),d[y]={state:t,transitions:{}},u&&u(t))continue;const g="function"==typeof r?r(t):r;for(const e of g){if(i&&!i(t,e))continue;const o=hn(s(t,e,h));d[y].transitions[n(e)]={event:e,state:o},l.push({nextState:o,event:e,prevState:t})}}return d}function fn(t){let e=[];if(t.steps.length){for(let n=0;n<t.steps.length;n++){const o=t.steps[n];e.push({state:o.state,event:0===n?{type:s}:t.steps[n-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:s}}];return{...t,steps:e}}function ln(t,e,s){const n=an(t,{events:e,...s},(o=t)&&o instanceof Fs?rn(t):cn());var o;const r=en(),i=n.fromState??t.getInitialSnapshot(r,s?.input),{serializeState:c,serializeEvent:a}=n,u=dn(t,n),h=new Map,d=[],f=c(i,void 0,void 0);h.set(f,i);let l=f,p=i;for(const t of e){d.push({state:h.get(l),event:t});const e=a(t),{state:s,event:n}=u[l].transitions[e];if(!s)throw new Error(`Invalid transition from ${l} with ${e}`);const o=c(s,t,h.get(l));h.set(o,s),l=o,p=s}return n.toState&&!n.toState(p)?[]:[fn({state:p,steps:d,weight:d.length})]}function pn(t,e){const s=an(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(en(),e?.input),r=dn(t,s),i=new Map,c=new Map,a=n(o,void 0,void 0);c.set(a,o),i.set(a,{weight:0,state:void 0,event:void 0});const u=new Set,h=new Set;u.add(a);for(const t of u){const e=c.get(t),{weight:s}=i.get(t);for(const o of Object.keys(r[t].transitions)){const{state:a,event:d}=r[t].transitions[o],f=n(a,d,e);if(c.set(f,a),i.has(f)){const{weight:e}=i.get(f);e>s+1&&i.set(f,{weight:s+1,state:t,event:d})}else i.set(f,{weight:s+1,state:t,event:d});h.has(f)||u.add(f)}h.add(t),u.delete(t)}const d={},f=[];return i.forEach(({weight:t,state:e,event:s},n)=>{const o=c.get(n),r=e?d[e].paths[0].steps.concat({state:c.get(e),event:s}):[];f.push({state:o,steps:r,weight:t}),d[n]={state:o,paths:[{state:o,steps:r,weight:t}]}}),s.toState?f.filter(t=>s.toState(t.state)).map(fn):f.map(fn)}function yn(t,e){const s=an(t,e),n=en(),o=s.fromState??t.getInitialSnapshot(n,e?.input),r=s.serializeState,i=dn(t,s),c=new Map,a={vertices:new Set,edges:new Set},u=[],h={};function d(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){h[e]||(h[e]={state:c.get(e),paths:[]});const t=h[e],n={state:s,weight:u.length,steps:[...u]};t.paths.push(n)}else{if(!i[t])return;for(const s of Object.keys(i[t].transitions)){const{state:n,event:o}=i[t].transitions[s];if(!(s in i[t].transitions))continue;const h=c.get(t),f=r(n,o,h);c.set(f,n),a.vertices.has(f)||(a.edges.add(s),u.push({state:c.get(t),event:o}),d(f,e))}}u.pop(),a.vertices.delete(t)}const f=r(o,void 0);c.set(f,o);for(const t of Object.keys(i))d(f,t);const l=Object.values(h).flatMap(t=>t.paths);return s.toState?l.filter(t=>s.toState(t.state)).map(fn):l.map(fn)}t.TestModel=Ys,t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.createShortestPathsGen=Xs,t.createSimplePathsGen=Qs,t.createTestModel=function(t,e){(t=>{t.root})(t);const s=e?.serializeEvent??Gs,n=e?.serializeTransition??tn,{events:o,...r}=e??{};return new Ys(t,{serializeState:(t,e,o)=>`${nn(t)}${n(t,e,o,{serializeEvent:s})}`,stateMatcher:(e,s)=>s.startsWith("#")?e.nodes.includes(t.getStateNodeById(s)):e.matches(s),events:t=>{const e="function"==typeof o?o(t):o??[];return is(t).flatMap(t=>e.some(e=>cs(e,t))?e.filter(e=>cs(e,t)):[t])},...r})},t.getAdjacencyMap=dn,t.getPathsFromEvents=ln,t.getShortestPaths=pn,t.getSimplePaths=yn,t.getStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,n)=>{const o=s[n],r=t(o);return e.push(o,...r),e},[])},t.joinPaths=un,t.serializeSnapshot=nn,t.toDirectedGraph=function t(e){const s=e instanceof Fs?e.root:e,n=[...s.transitions.values()].flat().flatMap((t,e)=>(t.target?t.target:[s]).map((n,o)=>{const r={id:`${s.id}:${e}:${o}`,source:s,target:n,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=r;return{source:s.id,target:n.id,label:t}}};return r})),o={id:s.id,stateNode:s,children:sn(s).map(t),edges:n,toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s}}};return o},Object.defineProperty(t,"__esModule",{value:!0})});
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateGraph={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="@xstate.init",n="@xstate.spawn",r="@xstate.stop",o="@xstate.terminate",i="xstate.timer",c="xstate.logic.effect.resolve",a="xstate.logic.effect.reject",u="xstate.logic.effect.start";function h(t,e){return{type:"xstate.after",delay:t,stateId:e}}function d(t,e){return`xstate.after.${t}.${e}`}function f(t){return`xstate.timeout.${t}`}function l(t,e){return{type:"xstate.timeout.actor",actorId:t,sessionId:e}}function p(t){return`xstate.timeout.actor.${t}`}function y(t,e){return{type:"xstate.done.state",stateId:t,output:e}}function g(t,e){return{type:`xstate.error.${t}`,error:e}}function v(t){return{type:s,input:t}}function m(t){setTimeout(()=>{throw t})}const _="function"==typeof Symbol&&Symbol.observable||"@@observable";function x(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}const b={"@xstate.spawn":t=>t.system.spawnActor(t._parent,t),"@xstate.start":t=>t.system.startActor(t),"@xstate.raise":(t,e,s)=>t.system.scheduleTimer(t.self,s.id,s?.delay??0),"@xstate.sendTo":(t,e,s,n)=>(x(s),void 0!==n?.delay?t.system.scheduleTimer(t.self,n.id,n?.delay??0):t.system._relay(t.self,e,s)),"@xstate.cancel":(t,e)=>t.system.cancelTimer(t.self,e),"@xstate.stop":(t,e)=>t.system.stopActor(e),"@xstate.terminate":(t,e)=>t.system.terminateActor(t,e)},S=new WeakMap;function w(t,e){let s=S.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)}S.set(t,s)}return s.get(e)}const I=new WeakMap;function E(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{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})),I.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===r?(I.get(s)?.unsubscribe(),I.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function A(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function k(){return E(({actor:t,eventType:e,mapper:s},{self:n,system:r})=>{const o="*"!==e&&e.endsWith(".*");return t.on(o?"*":e,t=>{o&&!hs(t.type,e)||A(n,r,()=>s(t))})},"xstate.listener")}const j=k();function O(){return E(({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?A(s,n,()=>r(t.output)):"error"===t.status&&o?A(s,n,()=>o(t.error)):"active"===t.status&&i&&A(s,n,()=>i(t))},error:t=>{o&&A(s,n,()=>o(t))},complete:()=>{}})},"xstate.subscription")}const $=O(),T=Symbol();function M(t){return!!t[T]}function P(t){return M(t)?t._parent:t.self._parent}function R(t,e){if(!M(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:()=>P(e)}}),t}function z(){return this.action?.(...this.args)}function N(t=this.source.system){return t.emitEvent(this.source,this.event)}function D(t=this.target.system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function K(t,e,s,n,r){return{kind:"builtin",type:"@xstate.deadLetter",exec:D,source:e,target:t.self,event:s,reason:n,detail:r,params:void 0,args:[]}}function C(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function V(t=this.actor.system){return t.spawnActor(this.source,this.actor)}function W(t=this.actor.system){return t.startActor(this.actor)}function J(t=this.source.system){return t.stopActor(this.actor)}function L(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 U(t=this.source.system){return t.scheduleTimer(this.source,this.id,this.delay??0)}function B(t=this.source.system){return x(this.event),void 0!==this.delay?t.scheduleTimer(this.source,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function q(t=this.source.system){return t.cancelTimer(this.source,this.id)}function F(t,e,s){if(!lt(e))return t;if("@xstate.cancel"===e.type){if(!t.timers?.[e.id])return t;const s={...t.timers};return delete s[e.id],{...t,timers:s}}if("@xstate.raise"!==e.type&&"@xstate.sendTo"!==e.type||void 0===e.delay)return t;let n=t._nextTimerId??0;const r=e.id??"xstate.timer.auto."+n++;e.id=r;const o="@xstate.raise"===e.type||e.target===s.self?"self":e.target;return{...t,timers:{...t.timers,[r]:{id:r,delay:e.delay,type:e.type,event:e.event,target:o}},_nextTimerId:n}}function G(t,e){return{...t,...e}}function H(t,e,...s){const n={action:e,args:s};return t.push(n),n}function X(t,e){const s={...t};for(const t of Object.keys(e))s[t]=Math.max(s[t]??0,e[t]);return s}function Q(t,e,s){if("add"===e.type)return{...t,children:{...t.children,[e.id]:e.actor},...e.counters&&{_nextActorIds:X(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(`Cannot stop non-child actor ${e.actor.id}`);return s.system._unregister(e.actor),{...t,children:n}}function Y(t){if("object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action)return t}const Z=new WeakMap,tt=()=>({counters:new Map,explicitIds:new Set,stoppedIds:new Set});function et(t){Z.set(t,tt())}function st(t){return t.self._snapshot}function nt(t,e,s){return Math.max(e.counters.get(s)??0,st(t)?._nextActorIds?.[s]??0)}function rt(t,e,s){const n=Z.get(t)??s??tt(),r=ms(e),o=nt(t,n,r);return n.counters.set(r,o+1),{id:`${r}:${o}`,counters:{[r]:o+1}}}function ot(t,e,s){const n=Z.get(t)??s??tt(),r=st(t)?.children?.[e],o=void 0!==r&&!n.stoppedIds.has(e)&&"active"===r.getSnapshot().status;if(n.explicitIds.has(e)||o)throw new Error(`Child actor id '${e}' is already in use`);n.explicitIds.add(e)}function it(t,e,s){const n=xs(e);if(!n)return;n.prefix;const r=Z.get(t)??s??tt(),o=Math.max(nt(t,r,n.prefix),n.index+1);return r.counters.set(n.prefix,o),{[n.prefix]:o}}function ct(t,e,s,n=!1,r=!0){const o=Z.get(t)??tt(),i={cancel:s=>{H(e,b["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{H(e,t.logger,...s)},raise:(n,r)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0!==r?.delay?H(e,b["@xstate.raise"],t,n,r):s.push(n)},spawn:(s,n)=>{const{logic:i,src:c}=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(`Actor source '${e}' is not provided`);return{logic:t,src:e}}return s?{logic:e,src:w(s,e)}:{logic:e,src:void 0}}(t,s);if(!r)return{id:n?.id??n?.registryKey??c??i.id};let a,u=n?.id;void 0===u?({id:u,counters:a}=rt(t,c??i,o)):(ot(t,u,o),a=it(t,u,o));const h=t.system.createActorRef(i,{...n,...void 0!==c&&{src:c},id:u,parent:t.self});return function(t,e,s,n){H(t,b["@xstate.spawn"],e).childUpdate={type:"add",actor:e,id:s,counters:n}}(e,h,u,a),h},sendTo:(n,r,o)=>{n?H(e,b["@xstate.sendTo"],t,n,r,o):s.push(g("communication",{message:"Unable to send event to an undefined actor",event:r}))},stop:s=>{if(s){const n=s;H(e,b["@xstate.stop"],t,n).childUpdate={type:"remove",actor:n},function(t,e){const s=Z.get(t);s&&(s.stoppedIds.add(e.id),s.explicitIds.delete(e.id))}(t,n)}}};return n&&Object.assign(i,{listen:(s,n,o)=>{if(!r)return{id:void 0};const i={actor:s,eventType:n,mapper:o},c=t.system.createActorRef(j,{input:i,parent:t.self});return H(e,b["@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($,{input:o,parent:t.self});return H(e,b["@xstate.spawn"],i),i}}),yt(i,(t,...s)=>{H(e,t,...s)})}function at(t,e){switch(t){case b["@xstate.spawn"]:{const[t]=e;return{kind:"builtin",exec:V,source:t._parent,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case b["@xstate.raise"]:{const[,t,s]=e;return{kind:"builtin",exec:U,source:e[0].self,event:t,id:s?.id,delay:s?.delay}}case b["@xstate.sendTo"]:{const[,t,s,n]=e;return{kind:"builtin",exec:B,source:e[0].self,target:t,event:s,id:n?.id,delay:n?.delay}}case b["@xstate.cancel"]:{const[,t]=e;return{kind:"builtin",exec:q,source:e[0].self,id:t}}case b["@xstate.stop"]:{const[,t]=e;return{kind:"builtin",exec:J,source:e[0].self,actor:t,id:t.id}}default:return}}function ut(t){const e=[t];return{kind:"builtin",exec:W,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function ht(t,e,s){const n=[t,e,s,{}];return{kind:"builtin",exec:B,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:n}}function dt(t,e){if("done"!==e.status&&"error"!==e.status)throw new Error("Cannot terminate an active or stopped actor");const s="done"===e.status?{status:"done",output:e.output,error:void 0}:{status:"error",output:void 0,error:e.error},n=[t.self,s];return{kind:"builtin",exec:L,type:o,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:n}}function ft(t,e,[s,n]){const r="done"===s.status||"error"===s.status,i="done"===e?.status||"error"===e?.status,c=n.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===o);return!r||i||c?[s,n]:[s,[...n,dt(t,s)]]}function lt(t){return"builtin"===t.kind}function pt(t,e,s,n){let r=t;const o=[];for(const i of n){const n=M(s)?R({context:r.context,event:e,output:ss(e),children:r.children,actions:t.machine.sources.actions,actors:t.machine.sources.actors},s):{context:r.context,event:e,output:ss(e),self:s.self,system:s.system,parent:s.self._parent,children:r.children,actions:t.machine.sources.actions,actors:t.machine.sources.actors},c="function"==typeof i,a=Y(i),u=c?i:!!a&&a.action.bind(null,...a.args);let h;if("object"==typeof i&&null!==i){const{type:t,childUpdate:e,...s}=i;h=s}if(a?.childUpdate&&(r=Q(r,a.childUpdate,s)),u&&"_special"in u){o.push({kind:"action",exec:z,type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type??"(anonymous)":i.name||"(anonymous)",params:h,args:[],action:void 0});const t=u(n,mt);t&&("context"in t||"children"in t)&&(r={...r,...void 0!==t.context?{context:G(r.context,t.context)}:{},..."children"in t?{children:t.children}:{}});continue}if(!u||!("resolve"in u)){const t="object"==typeof i&&null!==i&&"action"in i&&"function"==typeof i.action?at(i.action,i.args):void 0,e="object"==typeof i&&null!==i&&!a,n={kind:t?"builtin":e?"emit":"action",type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type:i.name||"(anonymous)",params:t?void 0:h,args:"object"==typeof i&&"action"in i?i.args:[],...t?{}:e?{source:s.self,event:i}:{action:a?.action??(c?i:void 0)},...t?{}:{exec:e?N:z},...t};r=F(r,n,s),o.push(n);continue}}return[r,o]}function yt(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:gt,emit:gt,log:gt,raise:gt,spawn:vt,sendTo:gt,stop:gt,listen:vt,subscribeTo:vt,...t}),s}const gt=()=>{},vt=()=>({}),mt=yt({},gt);const _t=new WeakMap,xt=new WeakMap,bt=new Map;function St(t){const e=t._peekKeyedActors;return e?e.call(t)??bt:t.keyedActors}function wt(t){t._snapshotVersion++}function It(t){return t._snapshotVersion}function Et(t,e,s){const n=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),r=new Map(s?.keyedActors??St(t)),o=new WeakMap,i=Object.assign(Object.create(t),{children:n,keyedActors:r,reverseKeyedActors:o,_snapshot:{...s?.snapshot??t._snapshot},_snapshotVersion:s?.sourceVersion??t._snapshotVersion,_register:(t,e)=>(n.set(t,e),wt(i),t),_unregister:t=>{t.sessionId&&n.delete(t.sessionId);const e=o.get(t);void 0!==e&&r.get(e)===t&&r.delete(e),o.delete(t),wt(i)},_set:(t,e)=>{const s=r.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${String(t)}' already exists.`);r.set(t,e),o.set(e,t),wt(i)},get:t=>r.get(t),getAll:()=>Object.fromEntries(r),_hasInspectionObservers:()=>!1,_sendInspectionEvent:()=>{}});for(const[t,e]of r)e&&o.set(e,t);for(const t of Object.values(e)){if(!t)continue;t.sessionId&&n.set(t.sessionId,t);const e=t.registryKey;e&&(r.set(e,t),o.set(t,e))}return i}function At(t){const e=_t.get(t);if(e)return e;const s=xt.get(t);if(!s)return;const n=s();return _t.set(t,n),xt.delete(t),n}function kt(t,e){const s=_t.get(t);if(s)return _t.set(e,s),!0;const n=xt.get(t);return!!n&&(xt.set(e,n),!0)}function jt(t,e,s=e.system,n){xt.delete(t);const r=It(s),o=n?At(n):void 0,i=o?.actor===e?o:At(t);if(i?.actor===e&&i.systemState.sourceSystem===s&&i.systemState.sourceVersion===r)return void _t.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=St(s);let h=u.size?new Map(u):bt;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&&(h===bt&&(h=new Map),h.set(t,e))}_t.set(t,{actor:e,systemState:{...c,children:a,keyedActors:h,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:r}})}function Ot(t,e,s=!0){const n=Rt(t);return n?(n.snapshot=e,n.materialized&&(n.materialized.self._snapshot=e)):t.self._snapshot=e,s&&e&&"object"==typeof e&&jt(e,t.self),e}function $t(t){return!!Rt(t)||!!t.self.options?._inert}function Tt(t,e){Ot(t,e,!1);const s=Rt(t);Pt.set(e,t);const n=()=>(jt(e,t.self,t.system),At(e));return s&&(s.materialized?s.identityProvider=n:s.identityProvider??=n),function(t,e){_t.delete(t),xt.set(t,e)}(e,n),e}const Mt=Symbol(),Pt=new WeakMap;function Rt(t){return t[Mt]}function zt(t){return Rt(t).materialize()}const Nt={[T]:!0,get _parent(){const t=Rt(this);return t.parentKnown?t.parent:zt(this).self._parent},get self(){return zt(this).self},get defer(){return zt(this).defer},get id(){return zt(this).id},get logger(){return zt(this).logger},get sessionId(){return zt(this).sessionId},get stopChild(){return zt(this).stopChild},get system(){return zt(this).system},get emit(){return zt(this).emit},get actionExecutor(){return zt(this).actionExecutor}};function Dt(t,e,s,n,r){const o=e?.(),i=r??o?.actor,c=i?.system,a=i&&c?Et(c,s,r?void 0:o?.systemState):void 0,u=zs(t,{_inert:!0,...i?{id:i.id,_sessionId:i.sessionId}:{},...a?{_systemRef:{current:a}}:{}});return i?._parent&&(u._parent=i._parent,u._address=void 0),n&&(u._snapshot=n),Object.create(u._actorScope,{defer:{value:()=>{}},stopChild:{value:t=>t._stop()},actionExecutor:{value:()=>{}}})}function Kt(t,e,s,n){const r=n??(e&&"object"==typeof e?Pt.get(e):void 0),o=r?Rt(r):void 0,i=e&&"object"==typeof e?function(t){return _t.get(t)}(e):void 0,c=o?.identityProvider??(e&&"object"==typeof e?function(t){const e=_t.get(t);return e?()=>e:xt.get(t)}(e):void 0),a={snapshot:e,sourceRef:c,sourceChildren:Ke(e)?e.children:{},identityProvider:o?.identityProvider??c,parent:s?._parent??o?.parent??i?.actor._parent,parentKnown:!(!s&&!o?.parentKnown&&!i&&e),materialize:()=>a.materialized??=Dt(t,a.sourceRef,a.sourceChildren,a.snapshot,s)};if(!a.identityProvider&&!e){const e={},n=a.sourceRef,r=a.sourceChildren;let o,i;const c=()=>o??=Dt(t,n,r,void 0,s);a.materialize=()=>{const t=c();return void 0!==a.snapshot&&(t.self._snapshot=a.snapshot),a.materialized=t},a.identityProvider=()=>{if(i)return i;const t=c();return jt(e,t.self,t.system),i=At(e)}}const u=Object.create(Nt);return u[Mt]=a,u}function Ct(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const n=e.match(/^(\d*)(\.?)(\d*)s$/i);if(n){const t=n[1]?parseInt(n[1],10):0,e=!!n[2],s=n[3]?parseInt(n[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const 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 h=t=>t?Number(t.replace(",",".")):0;return 7*h(o)*24*60*60*1e3+24*h(i)*60*60*1e3+60*h(c)*60*1e3+60*h(a)*1e3+1e3*h(u)}(t)??t}function Vt(t,e,s){if("function"==typeof t)return t(s);const n=Ct(t,e);return"function"==typeof n?n(s):n}function Wt(t,e){return t._stateInputs?.[e]}function Jt(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function Lt(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Ut(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 Bt(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 Lt(t))if(!e.has(s)){const t=ie(s);for(const s of t)e.add(s)}}else for(const s of ie(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 qt(t,e){const s=Bt(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(Jt(t))return t.key}const s={};for(const t of e)s[t.key]=r(t);return s};return r(t)}function Ft(t,e){return"compound"===e.type?Lt(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?Lt(e).every(e=>Ft(t,e)):"final"===e.type}const Gt=t=>"#"===t[0];function Ht(t){switch(t.type){case"xstate.done.actor":case"xstate.error.actor":return`${t.type}.${t.actorId}`;case"xstate.snapshot.actor":return`xstate.snapshot.${t.actorId}`;case"xstate.done.state":return`xstate.done.state.${t.stateId}`;case"xstate.after":return`xstate.after.${t.delay}.${t.stateId}`;case"xstate.timeout":return`xstate.timeout.${t.stateId}`;case"xstate.timeout.actor":return`xstate.timeout.actor.${t.actorId}`;default:return}}function Xt(t,e,s){const n=e.children[s];return!n||!("sessionId"in t)||(void 0===n.sessionId||n.sessionId===t.sessionId)}function Qt(t,e){const s=function(t){const e=Ht(t);return e?[t.type,e]:[t.type]}(e),n=s.flatMap(e=>t.transitions.get(e)??[]),r=[...t.transitions.keys()].filter(t=>!s.includes(t)&&s.some(e=>hs(e,t))).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return n.length?[...n,...r]:r}function Yt(t,e,s,n){const r=t.entry;t.entry=(t,o)=>(o.raise(s(t),{id:e,delay:n(t)}),"function"==typeof r?r(t,o):void 0);const o=t.exit;t.exit=(t,s)=>(s.cancel(e),"function"==typeof o?o(t,s):void 0)}function Zt(t,e,s){const n=os(s.target),r=s.reenter??!1,o=ne(t,n);se(t,o);const i={...s,target:o,source:t,reenter:r,eventType:e,toJSON:()=>({...i,source:`#${t.id}`,target:o?o.map(t=>`#${t.id}`):void 0})};return i}function te(t,e){for(let s=t.parent;s;s=s.parent)if(s===e)return!0;return!1}function ee(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 se(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],i=ee(r,o);if(r===o||te(r,o)||te(o,r)||"parallel"!==i?.type)throw new Error(`Invalid target set for '${t.id}'`)}}function ne(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(Gt(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return ae(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return ae(t.parent,n)}catch(e){throw new Error(`Invalid transition for '${t.id}': ${e.message}`)}})}function re(t){const e=os(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?ae(t.parent,e):e);return se(t,s),{target:s,source:t,reenter:!1,eventType:"",to:t.config._historyDefaultTransition}}function oe(t){return"history"===t.type}function ie(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 Lt(s))t(e)}(t);for(const s of e)for(const n of Ut(s,t))e.add(n);return e}function ce(t,e){if(Gt(e))return t.machine.getStateNodeById(e);const s=t.states?.[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function ae(t,e){if("string"==typeof e&&Gt(e))try{return t.machine.getStateNodeById(e)}catch{}const s=Qe(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=ce(n,t)}return n}function ue(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=new Array(s.length),r=[t.machine.root,t];for(let e=0;e<s.length;e++){const o=ce(t,s[e]);n[e]=o,r.push(o)}for(let t=0;t<s.length;t++)r.push(...ue(n[t],e[s[t]]));return r}function he(t,e,s,n,r,o){if("string"==typeof e){const i=ce(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=he(ce(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=he(ce(t,c),i,s,n,r,o);u&&a.push(...u)}return a.length?a:t.next(s,n,r,o)}function de(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function fe(t,e){for(const s of t)if(de(s,e))return!0;return!1}function le(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 pe(t,e,s,n){const r=new Set,o=new Map,i=t=>{let r=o.get(t);return r||(r=_e([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(le(i(e),i(n)))if(de(e.source,n.source))s.add(n);else{if("final"!==n.source.type||"final"===e.source.type){t=!0;break}s.add(n)}if(!t){for(const t of s)r.delete(t);r.add(e)}}return Array.from(r)}function ye(t,e,s,n,r){let o;return i=>{if(!i.to)return be(i,t,e,s,{resolveActions:n,selectionResult:r?.get(i)});let c=o?.get(i);return c||(c=be(i,t,e,s,{resolveActions:n,selectionResult:r?.get(i)}),(o??=new Map).set(i,c)),c}}function ge(t,e,s){const n=e.historyValue,{targets:r}=s(t);if(!r)return[];const o=new Set;for(const t of r)if(oe(t))if(n[t.id])for(const e of n[t.id])o.add(e);else for(const n of ge(re(t),e,s))o.add(n);else o.add(t);return[...o]}function ve(t,e){let s=t;for(;"parallel"===s.type;){const t=Lt(s).find(t=>e.every(e=>e===t||de(e,t)));if(!t)break;s=t}return s}function me(t,e,s){const n=ge(t,e,s),{targets:r,reenter:o}=s(t);if(t._transitionDomain){if("internal"===t._transitionDomain&&"compound"===t.source.type&&n.every(e=>de(e,t.source)))return t.source;const[e,...s]=n.concat(t.source);for(const t of Ut(e,void 0))if("compound"===t.type&&s.every(e=>de(e,t)))return t;return}if(!(r?.some(oe)&&n.some(e=>e===t.source))&&n.every(e=>e===t.source||de(e,t.source)))return o?t.source:ve(t.source,n);const[i,...c]=n.concat(t.source);for(const t of Ut(i,void 0))if(c.every(e=>de(e,t)))return o?t:ve(t,n);return o?void 0:ve(t.source.machine.root,n)}function _e(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=me(o,s,n);i&&o.source===t&&r.add(t);for(const s of e)de(s,t)&&r.add(s)}}return[...r]}function xe(t,e,s,n,r,o,i){const c=[];if(!t.length)return[e,c];{const a=new Set(e.nodes);let u=e.historyValue;const h=e.context,d=1===t.length?t:pe(t,a,e,ye(e,n,s,!1,i)),f=ye(e,n,s,!0,i),l=d.some(t=>{const{targets:e,reenter:s}=f(t);return!!e?.length||!!s}),p=(t,r,o,i)=>{if(2===t.length){const c=[],a=[];let u;const h=ct(s,c,a,!0),d=M(s)?R({context:r,event: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},s):{context:r,event: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},f=t(d,h);return void 0!==f?.context&&(u=G(r,f.context)),[c,u,a]}return[[Object.assign((e,n)=>t(M(s)?R({context:e.context,event:e.event,output:e.output,children:e.children,actions:e.actions,actors:e.actors,input:i},s):{...e,input:i},n),"_special"in t?{_special:!0}:{})],void 0,void 0]};let g=e;const v=(t,e)=>{const n=[],r=ct(s,n,[]);for(const s of t.invoke){const t=e[s.id];t&&r.stop(t)}return n},m=()=>{const t=_e(d,a,e,f);let r;t.sort((t,e)=>e.order-t.order);const i=[...a];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>Jt(t)&&de(t,e):t=>t.parent===e;r??={...u},r[t.id]=i.filter(s)}for(const r of t){const t=Wt(e,r.id),[i,u,h]=r.exit?p(r.exit,g.context,e.children,t):[[],void 0,void 0];h?.length&&o.push(...h),u&&(g=Fe(g,{context:u}));const[d,f]=pt(g,n,s,i);g=d,c.push(...f);const l=v(r,g.children);if(l.length){const[t,e]=pt(g,n,s,l);g=t,c.push(...e)}a.delete(r)}u=r||u};!r&&l&&m();let _=g.context;const x=[],S=[];for(const t of d){t.actions&&x.push(...ts(t.actions));const e=f(t);void 0!==e.context&&(_=G(_,e.context)),e.actions&&x.push(...e.actions),e.internalEvents&&S.push(...e.internalEvents)}S.length&&o.push(...S);const w=()=>{const t=t=>{const e=g.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:es(t.output,g.context,n,s.self,_[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:es(e.output,g.context,y(t.id,r),s.self)},i=new Set,h=new Set,l=new Map,v=(t,e)=>{for(const s of t)if(e&&!de(s,e)||i.add(s),"parallel"===s.type)for(const t of Lt(s))fe(i,t)||(i.add(t),m(t))},m=t=>{if(oe(t))if(u[t.id]){const e=u[t.id];for(const t of e)i.add(t),m(t);for(const s of e)v(Ut(s,t.parent),void 0)}else{const e=re(t),s=t.parent;h.add(s);const n=l.get(s)??[];n.push(e),l.set(s,n);const{targets:r}=f(e);for(const s of r??[])i.add(s),e===t.parent?.initial&&h.add(t.parent),m(s);for(const e of r??[])v(Ut(e,t.parent),void 0)}else{if("compound"===t.type){const e=f(t.initial).targets??[];for(const t of e)oe(t)||i.add(t);h.add(t);for(const t of e)m(t);for(const s of e)v(Ut(s,t),void 0);return}if("parallel"===t.type)for(const e of Lt(t))fe(i,e)||(i.add(e),h.add(e),m(e))}};for(const t of d){const s=me(t,e,f),{targets:n,reenter:r}=f(t);for(const e of n??[])oe(e)||t.source===e&&t.source===s&&!r||(i.add(e),h.add(e)),m(e);const o=ge(t,e,f);for(const e of o){const n=Ut(e,s);"parallel"===s?.type&&n.push(s),v(n,!t.source.parent&&r?void 0:s)}r&&s===t.source&&i.add(t.source)}if(r)for(const t of d[0]._statesForDefaultEntry??[e.machine.root])h.add(t);const _={...e._stateInputs};let x=!1;for(const t of d){const{targets:e,input:s}=f(t);if(s&&e)for(const t of e)_[t.id]=s,x=!0}const S=new Set,w={...g.children};for(const r of[...i].sort((t,e)=>t.order-e.order)){a.add(r);const i=[];let u=!1;for(const t of r.invoke){u=!0;let r=t.logic;"function"==typeof r&&(r=r({actors:e.machine.sources.actors,context:g.context,event:n,self:s.self}));const o="string"==typeof r?cs(e.machine,r):r;if(!o)throw new Error(`Actor logic '${"string"==typeof r?r:"inline"}' not implemented`);const c="function"==typeof t.input?t.input({self:s.self,context:g.context,event:n,output:ss(n)}):t.input;ot(s,t.id);const a=s.system.createActorRef(o,{...t,input:c,parent:s.self,syncSnapshot:!!t.onSnapshot});i.push({action:b["@xstate.spawn"],args:[a]}),t.id&&(w[t.id]=a)}u&&(g=Fe(g,{children:w}));let d=g.context,f=!1;const v=_[r.id];if(r.entry){const[t,e,s]=p(r.entry,d,w,v);i.push(...t),s?.length&&o.push(...s),e&&(d=e,f=!0)}if(f&&(g.context=d),h.has(r)){const t=[r.initial,...l.get(r)??[]].filter(Boolean);for(const e of t){const{actions:t,context:r,input:c,internalEvents:a}=be(e,g,n,s);if(t&&i.push(...t),a?.length&&o.push(...a),void 0!==r&&(g.context=G(g.context,r)),c&&e.target)for(const t of e.target)_[t.id]=c,x=!0}}const[m,I]=pt(g,n,s,i);if(g=m,i.length=0,c.push(...I),"final"!==r.type)continue;const E=r.parent;let A="parallel"===E?.type?E:E?.parent,k=A||r;for("compound"===E?.type&&o.push(y(E.id,void 0!==r.output?es(r.output,g.context,n,s.self,v):void 0));"parallel"===A?.type&&!S.has(A)&&Ft(a,A);){S.add(A);const t={};for(const e of Lt(A)){if("final"===e.type){t[e.key]=void 0!==e.output?es(e.output,g.context,n,s.self,_[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=Lt(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==r?.output?es(r.output,g.context,n,s.self,_[r.id]):void 0}o.push(y(A.id,t)),k=A,A=A.parent}A||(g=Fe(g,{status:"done",output:t(k)}))}x&&(g=Fe(g,{_stateInputs:_}))},[I,E]=pt(g,n,s,x);g=I,c.push(...E),_&&_!==e.context&&(g=Fe(g,{context:_})),(r||l)&&w();const A=[...a];if("done"===g.status){const t=[];A.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=Wt(g,e.id),[n,,r]=p(e.exit,g.context,g.children,s);t.push(...n),r?.length&&o.push(...r)}});const[e,r]=pt(g,n,s,t);g=e,c.push(...r);const[i,a]=ke(g,n,s);g=i,c.push(...a);const[u,h]=je(g,n,s);g=u,c.push(...h)}return u===e.historyValue&&e.nodes.length===a.size&&e.nodes.every(t=>a.has(t))?g.context!==h?[g===e?Fe(g):g,c]:[g,c]:[Fe(g,{_nodes:A,historyValue:u}),c]}}function be(t,e,s,n,r){let o;const i=()=>o??=M(n)?R({context:e.context,event:s,output:ss(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:Wt(e,t.source.id)},n):{context:e.context,event:s,output:ss(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:Wt(e,t.source.id)};if(t.to){const o=[],c=[],a=r?.selectionResult?.reusable?r.selectionResult.result:t.to(i(),ct(n,o,c,!0,r?.resolveActions??!0)),u=a?.target?ne(t.source,ts(a.target)):void 0,h=a?.input??("function"==typeof t.input?t.input({context:e.context,event:s,output:ss(s)}):t.input);return{targets:u,context:a?.context,reenter:a?.reenter,actions:o,internalEvents:c,input:h}}const c="function"==typeof t.input?t.input({context:e.context,event:s,output:ss(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}}function Se(t,e,o,c,a=[]){let u=t;const h=a.slice();function d(t){if("xstate.done.actor"!==t.type&&"xstate.error.actor"!==t.type)return;const{actorId:e,sessionId:s}=t;if(!e)return;const n=u.children[e];if(!n)return;if(void 0!==n.sessionId&&n.sessionId!==s)return;const r={...u.children};if(delete r[e],o.system._unregister(n),u=Fe(u,{children:r}),h.length){const[,t]=h.at(-1);h[h.length-1]=[u,t]}else h.push([u,[]])}function f(){const e=function(t){const e=[],s=[];for(const r of t){if(!lt(r)||r.type!==n)continue;const{actor:t,logic:o}=r,i=ut(t);o===j||o===$?e.push(i):s.push(i)}return[...e,...s]}(h.flatMap(([,t])=>t)),s=("active"===t.status||a.length>0)&&("done"===u.status||"error"===u.status);if(e.length||s){const t=s?[...e,dt(o,u)]:e;if(h.length){const[e,s]=h.at(-1);h[h.length-1]=[e,[...s,...t]]}else h.push([u,t])}return{snapshot:u,microsteps:h}}function l(t,n){if(!$t(o)&&(e.type===s||(o.system._hasInspectionObservers?.()??1))){const t=o.self._collectedMicrosteps||[];t.push(...n),o.self._collectedMicrosteps=t}h.push(t)}if(e.type===r){const[t,s]=ke(u,e,o),[n,r]=je(t,e,o);return u=Fe(n,{status:"stopped"}),l([u,[...s,...r]],[]),f()}let p=function(t,e){if("xstate.done.actor"===t.type||"xstate.error.actor"===t.type||"xstate.snapshot.actor"===t.type||"xstate.done.state"===t.type||"xstate.after"===t.type||"xstate.timeout"===t.type||"xstate.timeout.actor"===t.type)return t;const s=(e,s,n)=>t.type.startsWith(e)?{...t,type:s,[n]:t[n]??t.type.slice(e.length)}:void 0,n=s("xstate.done.actor.","xstate.done.actor","actorId")??s("xstate.error.actor.","xstate.error.actor","actorId")??s("xstate.snapshot.","xstate.snapshot.actor","actorId")??s("xstate.done.state.","xstate.done.state","stateId")??s("xstate.timeout.actor.","xstate.timeout.actor","actorId")??s("xstate.timeout.","xstate.timeout","stateId");if(n)return n;const r="xstate.after.";if(!t.type.startsWith(r))return t;const o=[...e.idMap.keys()].sort((t,e)=>e.length-t.length).find(e=>t.type.endsWith(`.${e}`));if(!o)return t;const i=t.type.slice(13,-o.length-1);return{...t,type:"xstate.after",delay:Number.isNaN(+i)?i:+i,stateId:o}}(e,t.machine);if(e.type===i){const t=u.timers[e.id];if(!t)return f();const s={...u.timers};if(delete s[t.id],u=Fe(u,{timers:s}),"@xstate.raise"===t.type)c.push(t.event),l([u,[]],[]);else{const e="self"===t.target?o.self:t.target;l([u,[ht(o,e,t.event)]],[])}}if(p.type!==s&&p.type!==i){const e=p,s=function(t){return t.type.startsWith("xstate.error.")}(e),n=new Map,r=u.machine.getTransitionData(u,e,o,n);if(s&&!r.length)return"xstate.error.actor"!==e.type||Xt(e,u,e.actorId)?(u=Fe(t,{status:"error",error:e.error}),l([u,[]],[]),d(e),f()):f();const i=xe(r,t,o,p,!1,c,n);u=i[0],l(i,r),d(e)}if(!c.length&&!1===t.machine._hasEventlessTransitions)return f();let y=!0;const g=t.machine.options?.maxIterations??1/0;let v=0,m=0;for(;"active"===u.status;){if(m++,m>1e3)throw new Error("Microstep count exceeded 1000");if(v++,v>g)throw new Error(`Infinite loop detected (>${g} microsteps)`);let t,e=y?Oe(u,p,o):[];const s=e.length?u:void 0;if(!e.length){if(!c.length)break;p=c.shift(),t=new Map,e=u.machine.getTransitionData(u,p,o,t)}const n=xe(e,u,o,p,!1,c,t);u=n[0],y=u!==s,l(n,e),d(p)}return f()}function we(t,e,s,n,r){return!!t.to&&Ae(t.to,e,s,n,r,n.machine.sources,t.source.id).enabled}const Ie=()=>{throw ys};let Ee;function Ae(t,e,s,n,r,o,i){let c;const a=P(r);a&&gs.push(a);try{c=t(R({context:e,event:s,output:ss(s),value:n.value,children:n.children,actions:o.actions,actors:o.actors,guards:o.guards,delays:o.delays,input:Wt(n,i)},r),Ee??=yt({emit:Ie,cancel:Ie,log:Ie,raise:Ie,spawn:Ie,sendTo:Ie,stop:Ie,listen:Ie,subscribeTo:Ie},Ie))}catch(t){if(t===ys)return{enabled:!0,result:void 0,reusable:!1};throw t}finally{a&&gs.pop()}return{enabled:void 0!==c,result:c,reusable:!0}}function ke(t,e,s){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return[t,[]];const r=[],o=ct(s,r,[]);for(const t of n)o.stop(t);return pt(t,e,s,r)}function je(t,e,s){const n=Object.keys(t.timers);if(!n.length)return[t,[]];const r=[],o=ct(s,r,[]);for(const t of n)o.cancel(t);return pt(t,e,s,r)}function Oe(t,e,s){const n=new Set,r=t.nodes.filter(Jt);for(const o of r)t:for(let r=o;r;r=r.parent)if(r.always)for(const o of r.always)if($e(o,e,t,r,s)){n.add(o);break t}return pe(Array.from(n),new Set(t.nodes),t,ye(t,e,s,!1))}function $e(t,e,s,n,r,o){if(t.matches&&!us(e,t.matches))return!1;if(t._eventMatcher&&!t._eventMatcher(e,s))return!1;if(t.guard){const o=function(t,e){if(!M(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:()=>P(e)}}),t}({context:s.context,event:e,output:ss(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=Ae(t.to,s.context,e,s,r,n.machine.sources,t.source.id);return o?.set(t,i),i.enabled}return!0}const Te={unsubscribe(){}},Me="or restore this snapshot with embedded children on the runtime that owns them.";function Pe(t){return!0===t._remote}const Re=Object.freeze({status:"active",output:void 0,error:void 0});function ze(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(`Remote actor '${e.address}' has no local mailbox to receive "${t.type}". Its state lives with another runtime; install a runtime that can reach it (via \`createDurable\`'s adapter runtime operations, or \`system.runtime\`) before sending, ${Me}`)},getSnapshot:()=>Re,getPersistedSnapshot(){throw new Error(`Cannot persist remote actor '${e.address}' from here: its state lives with the runtime that owns it. Persist it there, ${Me}`)},start(){},_stop(){},stop(){throw new Error(`Cannot stop remote actor '${e.address}' directly: stopping is a co-located operation. Stop it through the system runtime that owns it (\`system.stopActor(ref)\`), ${Me}`)},select(){throw new Error(`Cannot select from remote actor '${e.address}': its snapshot is not synchronously readable because its state lives with another runtime. Read it on the runtime that owns it, ${Me}`)},get trigger(){throw new Error(`Remote actor '${e.address}' has no \`trigger\` shorthand: it requires a co-located actor. Use \`send(...)\`, which routes through the system runtime.`)},subscribe:()=>Te,on:()=>Te,_isRunning:()=>!1,toJSON:()=>({xstate$type:ks,id:e.id,address:e.address,src:e.src})},n=s;return s.ref=n,n}const Ne=Object.freeze({});function De(t){return t===Ne||t&&Object.keys(t).length?t:Ne}function Ke(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const Ce=function(t){return Xe(t,this.value)},Ve=function(t){return this.tags.has(t)},We=function(t){return this.machine?._canTransition(this,t)??!1},Je=function(){const{nodes:t,_stateInputs:e,tags:s,machine:n,getMeta:r,getInputs:o,toJSON:i,can:c,hasTag:a,matches:u,...h}=this;return{...h,tags:Array.from(s)}},Le=function(){const t={};for(const e of this.nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},Ue=function(){return this._stateInputs};function Be(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function qe(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??qt(e.root,t._nodes),tags:Be(t._nodes),children:De(t.children),timers:De(t.timers),historyValue:De(t.historyValue),_stateInputs:De(t._stateInputs),_nextTimerId:t._nextTimerId??0,_nextActorIds:t._nextActorIds,matches:Ce,hasTag:Ve,can:We,getMeta:Le,getInputs:Ue,toJSON:Je};return s&&jt(n,s),n}function Fe(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:De(s.children),timers:De(s.timers),historyValue:De(s.historyValue),_stateInputs:De(s._stateInputs),_nextTimerId:s._nextTimerId??0,_nextActorIds:s._nextActorIds,matches:Ce,hasTag:Ve,can:We,getMeta:Le,getInputs:Ue,toJSON:Je};return kt(t,e),e}const n=qe({...s,value:void 0},t.machine);return kt(t,n),n}function Ge(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 He(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$type:ks,id:n.id};else{const r=He(n);r!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=r)}}return e??t}function Xe(t,e){const s=Ye(t),n=Ye(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&Xe(s[t],n[t]))}function Qe(t){if(ns(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function Ye(t){if(Ke(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}(Qe(t))}function Ze(t){return ns(t)?t:[t]}function ts(t){return void 0===t?[]:Ze(t)}function es(t,e,s,n,r){if("function"==typeof t){return t({context:e,event:s,output:ss(s),self:n,input:r})}return t}function ss(t){if(function(t){return"xstate.done.actor"===t.type||"xstate.done.state"===t.type}(t)){return t.output}}function ns(t){return Array.isArray(t)}function rs(t){return Ze(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function os(t){if(void 0!==t&&""!==t)return ts(t)}function is(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)}}function cs(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.sources.actors[e];const[,n,r]=s,o=t.getStateNodeById(r).config.invoke,i=(Array.isArray(o)?o[n]:o).src;return"string"==typeof i?t.sources.actors[i]:i}function as(t){const e=t.nodes.flatMap(e=>[...e.transitions.values()].flatMap(e=>e.map(e=>{const s={type:e.eventType,...e.matches};return!("actorId"in s)||"xstate.done.actor"!==s.type&&"xstate.error.actor"!==s.type&&"xstate.snapshot.actor"!==s.type&&"xstate.timeout.actor"!==s.type||(s.sessionId=t.children[s.actorId]?.sessionId),s})));return e.filter((t,s)=>e.findIndex(e=>{const s=Object.keys(t);return s.length===Object.keys(e).length&&s.every(s=>Object.is(t[s],e[s]))})===s)}function us(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}function hs(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}async function ds(t,e,s,n=e=>{t.system.sendEvent(t,t,e)}){const r=function(t,e){return t.getSnapshot().effects?.[e]}(t,e);if("done"===r?.status)return r.output;if("error"===r?.status)throw r.error;if("active"===r?.status)return function(t,e){return new Promise((s,n)=>{const r=t.subscribe(t=>{const o=t.effects?.[e];"done"===o?.status?(r.unsubscribe(),s(o.output)):"error"===o?.status&&(r.unsubscribe(),n(o.error))})})}(t,e);n({type:u,key:e});try{const t=await s();return n({type:c,key:e,output:t}),t}catch(t){throw n({type:a,key:e,error:t}),t}}function fs(t,e,s){const n=function(t,e,s){const n=e;if(t!==e&&n.logic?.isInternalEventType?.(s.type))return new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`)}(t,e,s);return!!n&&(e.system.deadLetter(t,e,s,"internalEvent",{error:n}),!0)}let ls,ps=0;const ys=new Error("Transition effect"),gs=[];function vs(){return ls??=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)}`}(),`${ls}:${(ps++).toString(36)}`}function ms(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length&&"(machine)"!==e?e:"x"}function _s(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function xs(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 bs(t,e){return`${t?t.address:""}|${e}`}function Ss(t,e,s){const n=t._snapshot._nextActorIds;(n[e]??0)>=s||(t._snapshot._nextActorIds={...n,[e]:s},wt(t))}const ws=Object.freeze({});function Is(t,e){return`${t.sessionId}.${e}`}class Es{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={systemId:vs(),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._onRejectedEvent=e.onRejectedEvent;const s="object"==typeof e.snapshot&&null!==e.snapshot?e.snapshot:void 0;this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef;const n=void 0;this._snapshot={_scheduledTimers:s?.scheduler??ws,_nextActorIds:{}}}_recordSent(t,e,s,n,r){if(!this._inspectionObservers?.size||!t)return;const o=t;(o._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:r})}schedule(t,e,s){const n=Is(t,e);void 0!==this._timerMap?.[n]&&this.cancel(t,e);const r=t.getSnapshot()?.timers?.[e];if(r){const n="self"===r.target?t:r.target;this._recordSent(t,n,r.event,s,e)}const o=this._clock.now?.()??Date.now(),c={source:t,delay:s,id:e,scheduledAt:o,dueAt:o+s},a=Is(t,e);this._snapshot._scheduledTimers===ws&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[a]=c,wt(this);const u=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[a],delete this._snapshot._scheduledTimers[a],wt(this),this._deliver(t,t,{type:i,id:e})},s);(this._timerMap??={})[a]=u}cancel(t,e){const s=Is(t,e),n=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==ws&&delete this._snapshot._scheduledTimers[s],wt(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.id)}}_deliver(t,e,s){!function(t,e,s){if(fs(t,e,s))return;const n=e;n._lastSourceRef=t,n._send(s)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),wt(this),t}_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&&wt(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(`Actor with registry key '${t}' already exists.`);(this._keyedActors??=new Map).set(t,e),(this._reverseKeyedActors??=new WeakMap).set(e,t),s!==e&&wt(this)}inspect(t){const e=is(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>t.next?.(e))}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(fs(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){this._sendInspectionEvent({type:"@xstate.deadletter",actorRef:e,sourceRef:t,event:s,reason:n,issues:r?.issues,error:r?.error}),this._onRejectedEvent?.({event:s,targetRef:e,targetId:e.id,sourceRef:t,eventOrigin:t?"actor":"external",reason:n,issues:r?.issues,error:r?.error});const o=this.runtime?.deadLetter;if(o)return o(t,e,s,n,r)}runStep(t,e,s){const n=this.runtime?.runStep;return n?n(t,e,s):ds(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=t.getSnapshot()?.timers?.[e];if(r){const n="self"===r.target?t:r.target;this._recordSent(t,n,r.event,s,e)}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(gs.length&&gs.includes(e))throw ys;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,id:o}=t[s];this.scheduleTimer(n,o,Math.max(0,r-(this._clock.now?.()??Date.now())))}}}let As=!1;const ks="actorRef",js=Object.freeze([]);let Os=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const $s=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function Ts(t,e){try{t?.(e)}catch(t){m(t)}}function Ms(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function Ps(t,e){return new Rs(t,e)}class Rs{get address(){return this._address??=this._parent?`${this._parent.address}/${_s(this.id)}`:_s(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.eventListeners=void 0,this.logger=void 0,this._processingStatus=Os.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._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;const s=e?{...$s,...e}:$s,{clock:n,logger:r,parent:o,syncSnapshot:i,id:c,registryKey:a,inspect:u}=s;var h;this.system=o?o.system:s._systemRef?.current??function(t,e){return new Es(t,e)}(this,{clock:n,logger:r,snapshot:s.snapshot??s.state,createActorRef:Ps,onRejectedEvent:s.onRejectedEvent}),o||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system),u&&!o&&this.system.inspect(is(u)),this.sessionId=s._sessionId??`${(h=this.system)._identity.systemId}:${h._identity.nextSessionId++}`,this.id=function(t,e,s){if(void 0!==e){const n=xs(e);return n?Ss(t,bs(s?.parent,n.prefix),n.index+1):s?.parent||Ss(t,bs(void 0,e),1),e}const n=ms(s?.src),r=bs(s?.parent,n),o=t._snapshot._nextActorIds[r]??0;return Ss(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 d=e?.snapshot??e?.state;this._restored=void 0!==d;try{if(d)this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(d,this._actorScope):d);else if(e?._inert);else{const[t,e]=ft(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}}catch(t){this._setSnapshot({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=>this.system.emitEvent(this,t);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===Os.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(`Cannot stop non-child actor ${t.id}`);t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=As;try{As=!0,t.exec()}finally{As=e}};this._processingStatus!==Os.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,jt(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,n]=ft(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),Ms(n,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??js)Ts(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??js,actions:this._collectedActions??js,sent:this._collectedSent??js,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 Ms(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=is(t,e,s);if(this._processingStatus!==Os.Stopped)(this.observers??=new Set).add(n);else switch(this._snapshot.status){case"done":Ts(n.complete);break;case"error":{const t=this._snapshot.error;n.error?Ts(n.error,t):m(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=is(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(){if(this._processingStatus===Os.Running)return this;if(this._processingStatus===Os.Stopped)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=Os.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,v(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,v(this.options.input)):(function(t,e,s){const n=_t.get(t),r=It(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 Object.values(t)){const t=e&&void 0!==n.startedAt?Math.min(n.delay,Math.max(0,n.startedAt+n.delay-s)):n.delay;this.system.scheduleTimer(this,n.id,t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){let e,s;try{e=ft(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){s={err:t}}if(s)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(s.err)||this._inspectTransition(this._snapshot,t));if(!e)return;let n=this._snapshot;try{const[s,r]=e;n=s,this._setSnapshot(n),Ms(r,this._actorScope),this.update(n,t)}catch(e){return void(this._recoverOrError(e,n)||this._inspectTransition(this._snapshot,t))}t.type===r&&(this._stopProcedure(),this._complete())}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)Ts(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===Os.Stopped?this:(this.mailbox?.clear(),this._processingStatus===Os.NotStarted?(this._processingStatus=Os.Stopped,this.system._unregister(this),this):(this._send({type:r}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers??js)Ts(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_error(t){if(this._stopProcedure(),this.observers?.size){let e=!1;for(const s of this.observers){const n=s.error;e||=!n,Ts(n,t)}this.observers.clear(),e&&m(t)}else this._parent||m(t);var e,s,n;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t,n=this.sessionId,{type:"xstate.error.actor",error:s,actorId:e,sessionId:n}))}_stopProcedure(){this._processingStatus===Os.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=Os.Stopped,this.system._unregister(this))}_send(t){if(this._processingStatus===Os.Stopped)return void this.system.deadLetter(this._lastSourceRef,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new e(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue(t)}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$type:ks,id:this.id,address:this.address,src:"string"==typeof this.src?this.src:void 0}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[_](){return this}getSnapshot(){return this._snapshot}}function zs(t,e){return new Rs(t,e)}function Ns(t,e){const s=t.check(e);if(s)throw s}const Ds=new WeakMap;function Ks(t,e,s){const n=function(t){let e=Ds.get(t);return e||(e=new Map,Ds.set(t,e)),e}(t);if(void 0!==e&&n.has(e))return;const r=s();n.set(e??Symbol(),{cleanup:"function"==typeof r?r:void 0})}function Cs(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===r)return[{...e,status:"stopped",input:void 0},[C("xstate.logic.cleanup",()=>function(t){const e=Ds.get(t);if(e){for(const{cleanup:t}of e.values())t?.();Ds.delete(t)}}(n.self))]];if(s.type===u)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if(s.type===c)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if(s.type===a)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const o=[],i={},h={emit:t=>{o.push(function(t,e){return{kind:"emit",exec:N,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&o.push(ht(n,e,t))},raise:t=>{o.push(ht(n,n.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{e.effects?.[t]||(o.push(C("xstate.logic.effect",(e=n.self.system)=>Ks(n.self,t,()=>s(e)),{key:t})),i[t]={status:"active"})})(t,s);const r=t;o.push(C("xstate.logic.effect",(t=n.self.system)=>Ks(n.self,void 0,()=>r(t))))}},d=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},h),f={...e,...d||{}};return("context"in e||void 0!==d?.context)&&(f.context=d?.context??e.context),(d?.effects||Object.keys(i).length)&&(f.effects={...e.effects,...d?.effects,...i}),ft(n,e,[f,o])},s=(s,r,o)=>{if(t.validator){const e=o.self._lastSourceRef,i=e?"actor":"external",c=t.validator.check({kind:"event",logic:n,event:r,eventOrigin:i});if(c)return[s,[K(o,e,r,"invalidEvent",{issues:c.issues,error:c})]]}const i=e(s,r,o);return t.validator&&Ns(t.validator,{kind:"result",logic:n,snapshot:i[0],effects:i[1]}),i},n={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,n)=>{if(!n?.restored)return;const[r,o]=s(t,v(t.input),e);Object.assign(t,r);for(const t of o)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&Ns(t.validator,{kind:"input",logic:n,input:e});const o=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),i={status:"active",output:void 0,error:void 0,input:e};return void 0!==o&&(i.context=o),s({...i},v(e),r)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const Vs=Cs({context:void 0,run:()=>{}});const Ws=new WeakMap;const Js={};class Ls{constructor(t,e){this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.schemas=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.invoke=void 0,this.on=void 0,this.after=void 0,this.events=void 0,this.ownEvents=void 0,this._candidateCache=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[];const s=this.config.states?Object.keys(this.config.states)[0]:void 0;if(this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(void 0!==s?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.schemas=this.config.schemas,function(t){const e=t.config;if("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(`Missing history target on "${t.id}"`);if("choice"!==t.type)return;if("function"!=typeof e.choice)throw new Error(`Missing \`choice\` function on "${t.id}"`)}(this),this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const s={},n=Object.keys(t);for(let r=0;r<n.length;r++){const o=n[r];s[o]=e(t[o],o,t,r)}return s}(this.config.states,(t,e)=>new Ls(t,{_parent:this,_key:e,_machine:this.machine})):Js,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}".`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.entry&&(this.entry._special=!0),this.exit&&(this.exit._special=!0),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=ts(t.tags).slice(),this.invoke=ts(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,r=(o=this.id,`${e}.${o}`);var o;const i=t.id??r,c="string"==typeof s?s:`xstate.invoke.${r}`;return{...t,src:c,logic:s,id:i,registryKey:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,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:h(n,t.id),timerId:d(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0})}var i;void 0!==s&&n&&o.push({event:(i=t.id,{type:"xstate.timeout",stateId:i}),timerId:f(t.id),delay:s,transitions:n,fromDelaysMap:!0});for(const t of r)o.push({event:l(t.id),timerId:p(t.id),resolveEvent:({children:e})=>l(t.id,e[t.id]?.sessionId),eventMatcher:(e,s)=>Xt(e,s,t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1});const c=[];for(const{event:e,timerId:s,resolveEvent:n,eventMatcher:r,delay:i,transitions:a,fromDelaysMap:u}of o){Yt(t,s,n??(()=>e),e=>Vt(i,u?e.delays:{},{context:e.context,event:e.event,stateNode:t,input:e.input}));const{type:o,...h}=e;for(const t of rs(a))c.push({...t,matches:{...t.matches,...Object.fromEntries(Object.entries(h).filter(([,t])=>void 0!==t))},event:o,delay:i,_eventMatcher:r})}return c.map(e=>({...Zt(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map,s=(t,s)=>{e.set(t,[...e.get(t)??[],...s])};if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error("Null event transition key");const n=t.config.on[s];e.set(s,Us(n,e=>Zt(t,s,e)))}if(t.config.onDone){const e="xstate.done.state";s(e,Us(t.config.onDone,s=>Zt(t,e,{...s,matches:{...s.matches,stateId:t.id}})))}if(t.config.onError){const s="xstate.error.*";e.set(s,Us(t.config.onError,e=>Zt(t,s,e)))}const n=(e,s,n)=>Zt(t,e,{matches:{actorId:n},_eventMatcher:(t,e)=>Xt(t,e,n),to:(t,e)=>(e.cancel(s),{})}),r=(e,s,n)=>{const{target:r,to:o,reenter:i,...c}=s;return Zt(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)=>Xt(t,s,e.id)}),i=void 0!==e.timeout?p(e.id):void 0;if(e.onDone){const c="xstate.done.actor",a=Us(e.onDone,e=>{const s=o(e);return i?r(c,s,i):Zt(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,Us(e.onError,e=>{const s=o(e);return i?r(n,s,i):Zt(t,n,s)}))}if(e.onSnapshot){const n="xstate.snapshot.actor";s(n,Us(e.onSnapshot,e=>Zt(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(`Choice "${t.id}" has no target`);return e};return[Zt(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=Us(this.config.always,t=>Zt(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=Ws.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Ws.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=(Array.isArray(s)?s:s?[s]:[]).map(e=>e.startsWith("#")?t.machine.getStateNodeById(e.slice(1)):t.states[e]);if(o.some(t=>!t))throw new Error(`Initial state not found on "#${t.id}"`);return{source:t,target:o.length?o:void 0,input:n,to:r}}(this,this.config.initial))}next(t,e,s,n){const r=function(t){const e=Ht(t);return e?`${t.type}|${e}`:t.type}(e);let o=this._candidateCache?.get(r);o||(o=Qt(this,e),(this._candidateCache??=new Map).set(r,o));for(const r of o){if($e(r,e,t,this,s,n))return[r]}}}function Us(t,e){const s=rs(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}function Bs(t,e){if(!t)return;if(Object.hasOwn(t,e))return t[e];const s=Object.keys(t).find(t=>hs(e,t));return void 0===s?void 0:t[s]}let qs,Fs;function Gs(){if(Fs)return Fs;const t=qs??=zs({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 Fs={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},Fs}class Hs{constructor(t,e,s){this.config=t,this.validator=s,this._internalEventType=void 0,this.version=void 0,this.schemas=void 0,this.snapshotSchema=void 0,this.eventSchema=void 0,this.sources=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._hasEventlessTransitions=void 0,this._json=void 0,this.id=t.id||"(machine)",this.sources={actors:t.actors??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...e},this.version=this.config.version,this.schemas=this.config.schemas,this.snapshotSchema={"~standard":{version:1,vendor:"xstate",validate:async t=>{if(null===t||"object"!=typeof t)return{issues:[{message:"Expected a persisted snapshot."}]};const e={historyValue:{},timers:{},...t},s=this.schemas?.context;let n=e.context;if(s){const t=await s["~standard"].validate(n);if(t.issues)return{issues:[{message:`Invalid context for machine '${this.id}' version '${this.version}': ${t.issues[0]?.message}`}]};n=t.value}for(const t of["value","children"])if(!(t in e))return{issues:[{message:`Persisted snapshot is missing '${t}'.`}]};if(!["active","done","error","stopped"].includes(e.status))return{issues:[{message:"Persisted snapshot has invalid status."}]};for(const t of["children","historyValue","timers"])if(null===e[t]||"object"!=typeof e[t]||Array.isArray(e[t]))return{issues:[{message:`Persisted snapshot has invalid '${t}'.`}]};try{this.resolveState({value:e.value,context:n})}catch(t){return{issues:[{message:t instanceof Error?t.message:"Persisted snapshot has invalid state value."}]}}return{value:{...e,context:n}}}}},this.eventSchema={"~standard":{version:1,vendor:"xstate",validate:async t=>{if(null===t||"object"!=typeof t||"string"!=typeof t.type)return{issues:[{message:"Expected an event object."}]};const e=t,s=this.schemas?.events,n=this.schemas?.internalEvents,r=e.type.startsWith("xstate.")||e.type.startsWith("@xstate."),o=Bs(n,e.type)??Bs(s,e.type);if((s||n)&&!o&&!r)return{issues:[{message:`Unknown event '${e.type}' for machine '${this.id}' version '${this.version}'.`}]};if(!o)return{value:e};const{type:i,...c}=e,a=await o["~standard"].validate(c);return a.issues?a:null===a.value||"object"!=typeof a.value?{issues:[{message:"Expected an event payload."}]}:{value:{...a.value,type:i}}}}},this.internalEventDescriptors=[...Object.keys(this.schemas?.internalEvents??{}),...this.config.internalEvents??[]],this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.initialTransition=this.initialTransition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new Ls(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(Zt(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(Zt(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 Hs(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}resolveState(t){const e=(s=this.root,n=t.value,qt(s,Bt(ue(s,n))));var s,n;const r=Bt(ue(this.root,e));return qe({_nodes:[...r],value:e,context:t.context||{},children:{},status:Ft(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??Kt(this,t);if(n&&Ot(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,[K(r,n,e,"invalidEvent",{issues:i.issues,error:i})]]}et(r);const o=this._transitionFast(t,e,r);if(o){n&&Ot(r,o,!1);const e=n&&o!==t?Tt(r,o):this._attachPureActorRef(o,r);return this.validator&&Ns(this.validator,{kind:"result",logic:this,snapshot:e,effects:[]}),[e,[]]}const{snapshot:i,microsteps:c}=Se(t,e,r,[]);n&&Ot(r,i,!1);const a=n?i===t?i:Tt(r,i):this._attachPureActorRef(i,r),u=this._collectEffects(c);return this.validator&&Ns(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 $t(e)||s&&e.self._actorScope===e&&void 0===e.self._snapshot||jt(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(!$t(s)&&(s.system._hasInspectionObservers?.()??1)){const t=s.self._collectedMicrosteps||[];t.push(o),s.self._collectedMicrosteps=t}return Fe(t,{...a!==t.context?{context:a}:{},...c?{_nodes:[this.root,i]}:{}})}microstep(t,e,s){const{microsteps:n}=Se(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 he(this.root,t.value,t,e,s,n)||[]}isInternalEventType(t){if(t===i)return!0;for(const e of this.internalEventDescriptors)if(hs(t,e))return!0;return!1}_canTransition(t,e){const s=Gs(),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=be(r,t,e,s,{resolveActions:!1});if(n.targets?.length||n.context||we(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 g("execution",e)}_getPreInitialState(t,e){const{context:s}=this.config,n=qe({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=w(e,n),i=r?.id??rt(t,o??n).id;void 0!==r?.id&&(ot(t,r.id),it(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 M(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]=pt(n,e,t,[]);if(i&&(c.context=i),Object.keys(r).length>0){c.children={...c.children,...r};const e=function(t){const e=Z.get(t)?.counters;if(e?.size)return Object.fromEntries(e)}(t);e&&(c._nextActorIds=X(c._nextActorIds,e))}return c}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){this.validator&&Ns(this.validator,{kind:"input",logic:this,input:t});const s=!e,r=e??Kt(this);et(r);const o=v(t),i=[],c=this._getPreInitialState(r,o),a=Object.values(c.children).filter(Boolean).map(t=>function(t){const e=[t];return{kind:"builtin",exec:V,type:n,source:t._parent,params:void 0,args:e,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}(t)),u=(t,e)=>{s&&Ot(r,t,!1);const n=s?Tt(r,t):this._attachPureActorRef(t,r,!0),o=this._collectEffects(e);return this.validator&&Ns(this.validator,{kind:"result",logic:this,snapshot:n,effects:o}),[n,o]};try{const[t,e]=function(t,e,s,n,r){const o=[...ie(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 Lt(t))c(e)};return c(t),xe([{target:o.filter(t=>!o.some(e=>e!==t&&de(e,t))),source:t,reenter:!0,eventType:null,toJSON:null,_statesForDefaultEntry:[...i]}],e,s,n,!0,r)}(this.root,c,r,o,i),{snapshot:s,microsteps:n}=Se(t,o,r,i,[[t,[...a,...e]]]);return u(s,n)}catch(t){if(!this.root.config.onError)throw t;const e=Se(c,g("execution",t),r,[],[[c,a]]);return u(e.snapshot,e.microsteps)}}start(t){if(!t?.children)return;const e=t.children;for(const t in e){if(!Object.hasOwn(e,t))continue;const s=e[t];s._rehydrated&&"active"===s.getSnapshot?.().status&&s.start()}}getStateNodeById(t){const e=Qe(t),s=e.slice(1),n=Gt(e[0])?e[0].slice(1):e[0],r=this.idMap.get(n);if(!r)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return ae(r,s)}getPersistedSnapshot(t,e){return function(t,e){const{nodes:s,_stateInputs:n,tags:r,machine:o,children:i,timers:c,context:a,can:u,hasTag:h,matches:d,getMeta:f,getInputs:l,toJSON:p,...y}=t,g={},v={},m=!1!==e?.embedChildren;for(const t in i){const s=i[t];if(!("string"==typeof s.src||e&&"__unsafeAllowInlineActors"in e))throw new Error("An inline child actor cannot be persisted.");const n=m&&!Pe(s);if(!n&&"string"!=typeof s.src)throw new Error(`Unable to persist child '${t}' by address: it requires a registered source key.`);g[t]={address:s.address,...n?{snapshot:s.getPersistedSnapshot(e)}:{remote:!0,incarnation:Pe(s)?s.sessionId:void 0},src:s.src,registryKey:s.registryKey,syncSnapshot:s._syncSnapshot}}const _=At(t)?.actor,x=_?.system?._clock?.now?void 0:_?.system?._snapshot?._scheduledTimers;for(const e in c){const s=c[e];let n,r=s.event;if("xstate.timeout.actor"===r.type&&(r={...r},delete r.sessionId),"self"===s.target)n="self";else{const r=Object.entries(i).find(([,t])=>t===s.target)?.[0];if(r)n=r;else{if(s.target!==At(t)?.actor._parent)throw new Error(`Unable to persist timer '${e}': target actor '${s.target.id}' is no longer addressable from this snapshot.`);n={type:"parent"}}}const o=x?.[`${_.sessionId}.${e}`],a=o?o.dueAt-s.delay:s.startedAt;v[e]={id:s.id,delay:s.delay,type:s.type,event:r,target:n,...void 0!==a&&{startedAt:a}}}const b={...y,context:He(a),children:g,timers:v,historyValue:Ge(y.historyValue)};return n&&Object.keys(n).length>0&&(b.stateInputs=n),void 0!==o.version&&(b.machine={id:o.id,version:o.version},b.version=o.version),b}(t,e)}restoreSnapshot(t,e){const s=!e,n=e??Kt(this),r=t.machine,o=r&&"object"==typeof r&&"function"==typeof r.transition&&"root"in r?void 0:r,i=t.version,c="string"==typeof o?.version?o.version:i;if(void 0!==i&&void 0!==o?.version&&o.version!==i)throw new Error(`Persisted snapshot version '${i}' conflicts with machine version '${o.version}'.`);if(o&&"string"==typeof o.id&&o.id!==this.id)throw new Error(`Machine ID mismatch: persisted snapshot machine '${o.id}' does not match '${this.id}'.`);if(c!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${c}' does not match machine version '${this.version}'.`);t=e(t,c)}const a=t,u={},h=a.children;for(const t of Object.keys(h)){const e=h[t];if(!0===e.remote&&void 0!==e.address){if("string"!=typeof e.src)throw new Error(`Unable to restore remote child '${t}': a child referenced by address requires a registered source key.`);const s=ze(n.system,{id:t,address:e.address,src:e.src,parent:n.self,registryKey:e.registryKey,syncSnapshot:e.syncSnapshot,incarnation:e.incarnation});e.registryKey&&n.system._set(e.registryKey,s),u[t]=s;continue}const s=e.snapshot,r=e.src,o="string"==typeof r?cs(this,r):r;if(!o){throw new Error(`Unable to restore child actor '${t}': child source '${"string"==typeof r?r:"<unknown>"}' is not provided in machine '${this.id}'.`)}const i=n.system.createActorRef(o,{id:t,parent:n.self,syncSnapshot:e.syncSnapshot,snapshot:s,src:r,registryKey:e.registryKey});i._rehydrated=!0,u[t]=i}const d={},f=a.timers??{};for(const[t,e]of Object.entries(f)){let s=e.event;if("xstate.timeout.actor"===s.type){const t=s.actorId,e=u[t];e&&(s=l(t,e.sessionId))}const r="string"==typeof e.target?"self"===e.target?"self":u[e.target]:n.self._parent;if(!r){const s="string"==typeof e.target?e.target:e.target.type;throw new Error(`Unable to restore timer '${t}': target actor '${s}' is unavailable.`)}d[t]={...e,event:s,target:r}}const p=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const s of Object.keys(t)){const n=t[s];for(const t of n){let n;if(t instanceof Ls)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(a.historyValue),y=(t,e,s)=>{const n=t=>new Error(`Persisted snapshot references state '${t.join(".")}' which does not exist on machine '${this.id}'.`);if("string"!=typeof t){if(t&&"object"==typeof t)for(const r of Object.keys(t)){const o=e.states[r];if(!o)throw n(s.concat(r));y(t[r],o,s.concat(r))}}else if(!e.states[t])throw n(s.concat(t))};y(a.value,this.root,[]);const g=Array.from(Bt(ue(this.root,a.value))),{version:v,_nextActorId:m,..._}=t;let x=_._nextActorIds;for(const t of Object.keys(h)){const e=xs(t);e&&(x?.[e.prefix]??0)<=e.index&&(x={...x,[e.prefix]:e.index+1})}const b=qe({..._,children:u,timers:d,_nextActorIds:x,_nodes:g,value:a.value,historyValue:p,_stateInputs:a.stateInputs??{}},this,n.self),S=new WeakSet;return function t(e){if(!S.has(e)){S.add(e);for(const s of Object.keys(e)){const n=e[s];if(n&&"object"==typeof n){if("xstate$type"in n&&n.xstate$type===ks){e[s]=u[n.id];continue}t(n)}}}}(b.context),s?(Ot(n,b,!1),Tt(n,b)):this._attachPureActorRef(b,n)}}function Xs(t){return JSON.stringify(t)}function Qs(t){const e=Object.keys(t.context).length?`(${JSON.stringify(t.context)})`:"",s=t.nodes.filter(t=>"atomic"===t.type||"final"===t.type).map(({id:e,path:s})=>{const n=t.getMeta()[e];if(!n)return`"${s.join(".")}"`;const{description:r}=n;return"function"==typeof r?r(t):r?`"${r}"`:JSON.stringify(t.value)});return`state${1===s.length?"":"s"} `+s.join(", ")+` ${e}`.trim()}const Ys=()=>(t,e)=>gn(t,e),Zs=()=>(t,e)=>vn(t,e);class tn{getDefaultOptions(){return{serializeState:t=>Xs(t),serializeEvent:t=>Xs(t),serializeTransition:(t,e)=>`${Xs(t)}|${e?.type}`,events:[],stateMatcher:(t,e)=>"*"===e,logger:{log:console.log.bind(console),error:console.error.bind(console)}}}constructor(t,e){this.testLogic=t,this.options=void 0,this.defaultTraversalOptions=void 0,this._toTestPath=t=>{const e=t.steps.map(t=>function(t){const{type:e,...s}=t;return`${e}${Object.keys(s).length?` (${JSON.stringify(s)})`:""}`}(t.event)).join(" → ");return{...t,test:e=>this.testPath(t,e),description:Ke(t.state)?`Reaches ${Qs(t.state).trim()}: ${e}`:JSON.stringify(t.state)}},this.options={...this.getDefaultOptions(),...e}}getPaths(t,e){const s=e?.allowDuplicatePaths??!1,n=t(this.testLogic,this._resolveOptions(e));return(s?n:((t,e=Xs)=>{const s=[];t.forEach(t=>{s.push({path:t,eventSequence:t.steps.map(t=>e(t.event))})}),s.sort((t,e)=>e.path.steps.length-t.path.steps.length);const n=[];t:for(const t of s){e:for(const e of n){for(const s in t.eventSequence)if(t.eventSequence[s]!==e.eventSequence[s])continue e;continue t}n.push(t)}return n.map(t=>t.path)})(n)).map(this._toTestPath)}getShortestPaths(t){return this.getPaths(Ys(),t)}getShortestPathsFrom(t,e){const s=[];for(const n of t){const t=this.getShortestPaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(dn(n,e)))}return s}getSimplePaths(t){return this.getPaths(Zs(),t)}getSimplePathsFrom(t,e){const s=[];for(const n of t){const t=this.getSimplePaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(dn(n,e)))}return s}getPathsFromEvents(t,e){return yn(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return ln(this.testLogic,this.options)}async testPath(t,e,s){const n={steps:[],state:{error:null}};try{for(const r of t.steps){const t={step:r,state:{error:null},event:{error:null}};n.steps.push(t);try{await this.testTransition(e,r)}catch(e){throw t.event.error=e,e}try{await this.testState(e,r.state,s)}catch(e){throw t.state.error=e,e}}}catch(e){throw e.message+=function(t,e,s){const n={formatColor:(t,e)=>e,serializeState:Xs,serializeEvent:Xs,...s},{formatColor:r,serializeState:o,serializeEvent:i}=n,{state:c}=t,a=o(c,t.steps.length?t.steps[t.steps.length-1].event:void 0);let u="",h=!1;return u+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=o(t.step.state,e>0?s[e-1].step.event:void 0),c=i(t.step.event);return[`\tState: ${h?r("gray",n):t.state.error?(h=!0,r("redBright",n)):r("greenBright",n)}`,`\tEvent: ${h?r("gray",c):t.event.error?(h=!0,r("red",c)):r("green",c)}`].join("\n")}).concat(`\tState: ${h?r("gray",a):e.state.error?r("red",a):r("green",a)}`).join("\n\n"),u}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),r=this._getStateTestKeys(t,e,n);for(const s of r)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},r=Object.keys(n).filter(t=>s.stateMatcher(e,t));return!r.length&&"*"in n&&r.push("*"),r}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function en(t,e){if(t===e)return!0;if(void 0===t||void 0===e)return!1;if("string"==typeof t||"string"==typeof e)return t===e;const s=Object.keys(t),n=Object.keys(e);return s.length===n.length&&s.every(s=>en(t[s],e[s]))}function sn(t,e,s,{serializeEvent:n}){if(!e||s&&en(s.value,t.value))return"";const r=s?` from ${Xs(s.value)}`:"";return` via ${n(e)}${r}`}function nn(){const t=zs(Vs);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function rn(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function on(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function cn(t){return JSON.stringify(t)}function an(t,e){const{events:s,...n}=e??{};return{serializeState:on,serializeEvent:cn,events:t=>{const e="function"==typeof s?s(t):s??[];return as(t).flatMap(t=>{const s=e.filter(e=>us(e,t));return s.length?s:[t]})},fromState:t.getInitialSnapshot(nn(),e?.input),...n}}function un(){return{serializeState:t=>JSON.stringify(t),serializeEvent:cn}}function hn(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?an(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:cn,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function dn(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}}function fn(t){return Array.isArray(t)?t[0]:t}function ln(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:r,events:o,filterEvents:i,limit:c,fromState:a,stopWhen:u}=hn(t,e),h=nn(),d={};let f=0;const l=[{nextState:a??t.getInitialSnapshot(h,e.input),event:void 0,prevState:void 0}],p=new Map;for(;l.length;){const{nextState:t,event:e,prevState:a}=l.shift();if(f++>c)throw new Error("Traversal limit exceeded");const y=r(t,e,a);if(d[y])continue;if(p.set(y,t),d[y]={state:t,transitions:{}},u&&u(t))continue;const g="function"==typeof o?o(t):o;for(const e of g){if(i&&!i(t,e))continue;const r=fn(s(t,e,h));d[y].transitions[n(e)]={event:e,state:r},l.push({nextState:r,event:e,prevState:t})}}return d}function pn(t){let e=[];if(t.steps.length){for(let n=0;n<t.steps.length;n++){const r=t.steps[n];e.push({state:r.state,event:0===n?{type:s}:t.steps[n-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:s}}];return{...t,steps:e}}function yn(t,e,s){const n=hn(t,{events:e,...s},(r=t)&&r instanceof Hs?an(t):un());var r;const o=nn(),i=n.fromState??t.getInitialSnapshot(o,s?.input),{serializeState:c,serializeEvent:a}=n,u=ln(t,n),h=new Map,d=[],f=c(i,void 0,void 0);h.set(f,i);let l=f,p=i;for(const t of e){d.push({state:h.get(l),event:t});const e=a(t),{state:s,event:n}=u[l].transitions[e];if(!s)throw new Error(`Invalid transition from ${l} with ${e}`);const r=c(s,t,h.get(l));h.set(r,s),l=r,p=s}return n.toState&&!n.toState(p)?[]:[pn({state:p,steps:d,weight:d.length})]}function gn(t,e){const s=hn(t,e),n=s.serializeState,r=s.fromState??t.getInitialSnapshot(nn(),e?.input),o=ln(t,s),i=new Map,c=new Map,a=n(r,void 0,void 0);c.set(a,r),i.set(a,{weight:0,state:void 0,event:void 0});const u=new Set,h=new Set;u.add(a);for(const t of u){const e=c.get(t),{weight:s}=i.get(t);for(const r of Object.keys(o[t].transitions)){const{state:a,event:d}=o[t].transitions[r],f=n(a,d,e);if(c.set(f,a),i.has(f)){const{weight:e}=i.get(f);e>s+1&&i.set(f,{weight:s+1,state:t,event:d})}else i.set(f,{weight:s+1,state:t,event:d});h.has(f)||u.add(f)}h.add(t),u.delete(t)}const d={},f=[];return i.forEach(({weight:t,state:e,event:s},n)=>{const r=c.get(n),o=e?d[e].paths[0].steps.concat({state:c.get(e),event:s}):[];f.push({state:r,steps:o,weight:t}),d[n]={state:r,paths:[{state:r,steps:o,weight:t}]}}),s.toState?f.filter(t=>s.toState(t.state)).map(pn):f.map(pn)}function vn(t,e){const s=hn(t,e),n=nn(),r=s.fromState??t.getInitialSnapshot(n,e?.input),o=s.serializeState,i=ln(t,s),c=new Map,a={vertices:new Set,edges:new Set},u=[],h={};function d(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){h[e]||(h[e]={state:c.get(e),paths:[]});const t=h[e],n={state:s,weight:u.length,steps:[...u]};t.paths.push(n)}else{if(!i[t])return;for(const s of Object.keys(i[t].transitions)){const{state:n,event:r}=i[t].transitions[s];if(!(s in i[t].transitions))continue;const h=c.get(t),f=o(n,r,h);c.set(f,n),a.vertices.has(f)||(a.edges.add(s),u.push({state:c.get(t),event:r}),d(f,e))}}u.pop(),a.vertices.delete(t)}const f=o(r,void 0);c.set(f,r);for(const t of Object.keys(i))d(f,t);const l=Object.values(h).flatMap(t=>t.paths);return s.toState?l.filter(t=>s.toState(t.state)).map(pn):l.map(pn)}t.TestModel=tn,t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.createShortestPathsGen=Ys,t.createSimplePathsGen=Zs,t.createTestModel=function(t,e){(t=>{t.root})(t);const s=e?.serializeEvent??Xs,n=e?.serializeTransition??sn,{events:r,...o}=e??{};return new tn(t,{serializeState:(t,e,r)=>`${on(t)}${n(t,e,r,{serializeEvent:s})}`,stateMatcher:(e,s)=>s.startsWith("#")?e.nodes.includes(t.getStateNodeById(s)):e.matches(s),events:t=>{const e="function"==typeof r?r(t):r??[];return as(t).flatMap(t=>e.some(e=>us(e,t))?e.filter(e=>us(e,t)):[t])},...o})},t.getAdjacencyMap=ln,t.getPathsFromEvents=yn,t.getShortestPaths=gn,t.getSimplePaths=vn,t.getStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,n)=>{const r=s[n],o=t(r);return e.push(r,...o),e},[])},t.joinPaths=dn,t.serializeSnapshot=on,t.toDirectedGraph=function t(e){const s=e instanceof Hs?e.root:e,n=[...s.transitions.values()].flat().flatMap((t,e)=>(t.target?t.target:[s]).map((n,r)=>{const o={id:`${s.id}:${e}:${r}`,source:s,target:n,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=o;return{source:s.id,target:n.id,label:t}}};return o})),r={id:s.id,stateNode:s,children:rn(s).map(t),edges:n,toJSON:()=>{const{id:t,children:e,edges:s}=r;return{id:t,children:e,edges:s}}};return r},Object.defineProperty(t,"__esModule",{value:!0})});
|
|
2
2
|
//# sourceMappingURL=xstate-graph.umd.min.js.map
|