xstate 6.0.0-alpha.72 → 6.0.0-alpha.73
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/{index-31b3c878.cjs.js → index-2c15e088.cjs.js} +2 -2
- package/dist/{index-5ce9cbf9.development.cjs.js → index-7317cefe.development.cjs.js} +2 -2
- package/dist/{index-74b77771.esm.js → index-94aac758.esm.js} +2 -2
- package/dist/{index-6923de25.development.esm.js → index-dcba439c.development.esm.js} +2 -2
- package/dist/xstate-actors.cjs.js +1 -1
- package/dist/xstate-actors.development.cjs.js +1 -1
- package/dist/xstate-actors.development.esm.js +1 -1
- package/dist/xstate-actors.esm.js +1 -1
- package/dist/xstate-actors.umd.min.js +1 -1
- package/dist/xstate-actors.umd.min.js.map +1 -1
- package/dist/xstate-graph.cjs.js +1 -1
- package/dist/xstate-graph.development.cjs.js +1 -1
- package/dist/xstate-graph.development.esm.js +1 -1
- package/dist/xstate-graph.esm.js +1 -1
- package/dist/xstate.cjs.js +1 -1
- package/dist/xstate.development.cjs.js +1 -1
- package/dist/xstate.development.esm.js +2 -2
- package/dist/xstate.esm.js +2 -2
- package/dist/xstate.umd.min.js +1 -1
- package/dist/xstate.umd.min.js.map +1 -1
- package/docs/api-stability.json +555 -1
- package/docs/index.md +1 -1
- package/package.json +1 -1
|
@@ -930,7 +930,7 @@ function createAsyncLogic(asyncLogic) {
|
|
|
930
930
|
switch (event.type) {
|
|
931
931
|
case XSTATE_ASYNC_RESOLVE:
|
|
932
932
|
{
|
|
933
|
-
const resolvedValue = event.data
|
|
933
|
+
const resolvedValue = 'data' in event ? event.data : event.output;
|
|
934
934
|
return {
|
|
935
935
|
status: 'done',
|
|
936
936
|
output: resolvedValue,
|
|
@@ -945,7 +945,7 @@ function createAsyncLogic(asyncLogic) {
|
|
|
945
945
|
}
|
|
946
946
|
case XSTATE_ASYNC_REJECT:
|
|
947
947
|
{
|
|
948
|
-
const error = event.data
|
|
948
|
+
const error = 'data' in event ? event.data : event.error;
|
|
949
949
|
return {
|
|
950
950
|
status: 'error',
|
|
951
951
|
error,
|
|
@@ -930,7 +930,7 @@ function createAsyncLogic(asyncLogic) {
|
|
|
930
930
|
switch (event.type) {
|
|
931
931
|
case XSTATE_ASYNC_RESOLVE:
|
|
932
932
|
{
|
|
933
|
-
const resolvedValue = event.data
|
|
933
|
+
const resolvedValue = 'data' in event ? event.data : event.output;
|
|
934
934
|
return {
|
|
935
935
|
status: 'done',
|
|
936
936
|
output: resolvedValue,
|
|
@@ -945,7 +945,7 @@ function createAsyncLogic(asyncLogic) {
|
|
|
945
945
|
}
|
|
946
946
|
case XSTATE_ASYNC_REJECT:
|
|
947
947
|
{
|
|
948
|
-
const error = event.data
|
|
948
|
+
const error = 'data' in event ? event.data : event.error;
|
|
949
949
|
return {
|
|
950
950
|
status: 'error',
|
|
951
951
|
error,
|
|
@@ -928,7 +928,7 @@ function createAsyncLogic(asyncLogic) {
|
|
|
928
928
|
switch (event.type) {
|
|
929
929
|
case XSTATE_ASYNC_RESOLVE:
|
|
930
930
|
{
|
|
931
|
-
const resolvedValue = event.data
|
|
931
|
+
const resolvedValue = 'data' in event ? event.data : event.output;
|
|
932
932
|
return {
|
|
933
933
|
status: 'done',
|
|
934
934
|
output: resolvedValue,
|
|
@@ -943,7 +943,7 @@ function createAsyncLogic(asyncLogic) {
|
|
|
943
943
|
}
|
|
944
944
|
case XSTATE_ASYNC_REJECT:
|
|
945
945
|
{
|
|
946
|
-
const error = event.data
|
|
946
|
+
const error = 'data' in event ? event.data : event.error;
|
|
947
947
|
return {
|
|
948
948
|
status: 'error',
|
|
949
949
|
error,
|
|
@@ -928,7 +928,7 @@ function createAsyncLogic(asyncLogic) {
|
|
|
928
928
|
switch (event.type) {
|
|
929
929
|
case XSTATE_ASYNC_RESOLVE:
|
|
930
930
|
{
|
|
931
|
-
const resolvedValue = event.data
|
|
931
|
+
const resolvedValue = 'data' in event ? event.data : event.output;
|
|
932
932
|
return {
|
|
933
933
|
status: 'done',
|
|
934
934
|
output: resolvedValue,
|
|
@@ -943,7 +943,7 @@ function createAsyncLogic(asyncLogic) {
|
|
|
943
943
|
}
|
|
944
944
|
case XSTATE_ASYNC_REJECT:
|
|
945
945
|
{
|
|
946
|
-
const error = event.data
|
|
946
|
+
const error = 'data' in event ? event.data : event.error;
|
|
947
947
|
return {
|
|
948
948
|
status: 'error',
|
|
949
949
|
error,
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
5
|
var createActor = require('./createActor-2136a8ad.development.cjs.js');
|
|
6
|
-
var dist_xstateActors = require('./index-
|
|
6
|
+
var dist_xstateActors = require('./index-7317cefe.development.cjs.js');
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export { an as createListenerLogic, ao as createSubscriptionLogic } from './createActor-286a0dbb.development.esm.js';
|
|
2
|
-
export { T as TimeoutError, c as createAsyncLogic, b as createCallbackLogic, d as createEmptyActor, e as createEventObservableLogic, g as createObservableLogic, f as createStepLogic } from './index-
|
|
2
|
+
export { T as TimeoutError, c as createAsyncLogic, b as createCallbackLogic, d as createEmptyActor, e as createEventObservableLogic, g as createObservableLogic, f as createStepLogic } from './index-dcba439c.development.esm.js';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export { am as createListenerLogic, an as createSubscriptionLogic } from './createActor-22a0534b.esm.js';
|
|
2
|
-
export { T as TimeoutError, c as createAsyncLogic, b as createCallbackLogic, d as createEmptyActor, e as createEventObservableLogic, g as createObservableLogic, f as createStepLogic } from './index-
|
|
2
|
+
export { T as TimeoutError, c as createAsyncLogic, b as createCallbackLogic, d as createEmptyActor, e as createEventObservableLogic, g as createObservableLogic, f as createStepLogic } from './index-94aac758.esm.js';
|
|
@@ -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).XStateActors={})}(this,function(t){"use strict";const e="xstate.init",s="xstate.stop",r="@xstate.terminate",i="xstate.timer",n="xstate.logic.effect.resolve",o="xstate.logic.effect.reject",c="xstate.logic.effect.start";function a(t){if("object"!=typeof t||null===t||Array.isArray(t)||"string"!=typeof t.$actor)return!1;for(const e in t)if("$actor"!==e&&"incarnation"!==e)return!1;const e=t.incarnation;return void 0===e||"string"==typeof e}function h(t){const e=t.slice(t.lastIndexOf("/")+1);return e.includes("%")?e.replaceAll("%2F","/").replaceAll("%25","%"):e}function u(t){return new Error(void 0===t.incarnation?`Unable to send event to actor '${t.$actor}': no live actor has that address`:`Unable to send event to actor '${t.$actor}' (incarnation '${t.incarnation}'): no live actor has that address and incarnation`)}function d(t,e){const s=t._getByAddress?.(e.$actor);return!s||void 0!==e.incarnation&&s.sessionId!==e.incarnation?void 0:s}function p(t,e,s){return t.system._notifyEmitted(t,e),s.emitEvent(t,e)}Object.freeze({status:"active",output:void 0,error:void 0});const l=new WeakMap;async function f(t,e,s,r=e=>{t.system.sendEvent(t,t,e)}){const i=function(t,e){const s=t.getSnapshot().effects;return s&&Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0}(t,e);if("done"===i?.status)return i.output;if("error"===i?.status)throw i.error;const a=l.get(t)?.get(e);if(a)return a;if("active"!==t.getSnapshot().status)throw new Error(`Actor terminated before step "${e}" completed`);let h,u;const d=new Promise((t,e)=>{h=t,u=e});let p,f=l.get(t);f||(f=new Map,l.set(t,f)),f.set(e,d);const _=()=>{p?.unsubscribe(),f.delete(e),f.size||l.delete(t)};return d.then(_,_),p=t.subscribe({error:u,complete:()=>u(new Error(`Actor terminated before step "${e}" completed`))}),(async()=>{try{r({type:c,key:e});const i=await s();"active"===t.getSnapshot().status&&(r({type:n,key:e,output:i}),h(i))}catch(s){"active"===t.getSnapshot().status&&r({type:o,key:e,error:s}),u(s)}})().catch(u),d}function _(t,e,s){const r=function(t,e,s){const r=e;if(t!==e&&r.logic?.isInternalEventType?.(s.type))return new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`)}(t,e,s);return!!r&&(e.system.deadLetter(t,e,s,"internalEvent",{error:r}),!0)}class v{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}function y(t){return{type:e,input:t}}function m(t){setTimeout(()=>{throw t})}const g="function"==typeof Symbol&&Symbol.observable||"@@observable",b=[],S=new Error("Transition effect");function x(t){const{stateId:e,delay:s,actorId:r}=t;switch(t.type){case"xstate.after":return{type:t.type,delay:s,stateId:e};case"xstate.timeout.state":return{type:t.type,stateId:e};case"xstate.timeout.actor":return{type:t.type,actorId:r}}}function A(t){return void 0!==t.id?{id:t.id}:void 0!==t.seq?{seq:t.seq}:{event:x(t.event)??t.event}}function w(t,e){return`${t.sessionId}|${function(t){return"id"in t?JSON.stringify(["id",t.id]):"seq"in t?JSON.stringify(["seq",t.seq]):JSON.stringify(["event",x(t.event)??t.event])}(e)}`}const E=Symbol("xstate.systemLogicMetadata"),k=new WeakMap;function I(t,e){const r=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]],i={id:e,start:(e,{self:s,system:r})=>{const i=e.input.actor;if(!i||"stopped"===i.getSnapshot().status)return;const n=t(e.input,{self:s,system:r});if(!n)return;let o,c=!1;const a=()=>{c||(c=!0,n.unsubscribe(),o?.unsubscribe())},h=s._parent;h&&(o=h.subscribe({complete:a,error:a})),k.set(s,{unsubscribe:a})},transition:(t,e,{self:r})=>e.type===s?(k.get(r)?.unsubscribe(),k.delete(r),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:r,getInitialSnapshot:(t,e)=>r(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return Object.defineProperty(i,E,{value:{kind:e}}),i}function T(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function O(t=this.source.system){return p(this.source,this.event,t)}function R(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function M(t,e,s,r,i){return{kind:"builtin",type:"@xstate.deadLetter",exec:R,source:e,target:t.self,event:s,reason:r,detail:i,params:void 0,args:[]}}function j(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function $(t=this.actor.system){const e="done"===this.status?{status:"done",output:this.output,error:void 0}:{status:"error",output:void 0,error:this.error};return t.terminateActor(this.actor,e)}function P(t=this.source.system){return function(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}(this.event),void 0!==this.delay?t.scheduleTimer(this.source,A(this),this.delay):t.sendEvent(this.source,this.target,this.event)}function L(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:P,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function z(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},i=[t.self,s];return{kind:"builtin",exec:$,type:r,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:i}}function C(t,e,[s,i]){const n="done"===s.status||"error"===s.status,o="done"===e?.status||"error"===e?.status,c=i.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===r);return!n||o||c?[s,i]:[s,[...i,z(t,s)]]}function K(t){if(void 0!==t)return"number"==typeof t?t:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const r=e.match(/^(\d*)(\.?)(\d*)s$/i);if(r){const t=r[1]?parseInt(r[1],10):0,e=!!r[2],s=r[3]?parseInt(r[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const i=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(!i?.groups)return;const{weeks:n,days:o,hours:c,minutes:a,seconds:h}=i.groups;if(!(n||o||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(n)*24*60*60*1e3+24*u(o)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)}const q=new WeakMap,U=new WeakMap,D=new Map;function N(t){t._snapshotVersion++}function W(t){return t._snapshotVersion}function V(t){const e=q.get(t);if(e)return e;const s=U.get(t);if(!s)return;const r=s();return q.set(t,r),U.delete(t),r}function B(t,e,s=e.system,r){U.delete(t);const i=W(s),n=r?V(r):void 0,o=n?.actor===e?n:V(t);if(o?.actor===e&&o.systemState.sourceSystem===s&&o.systemState.sourceVersion===i)return void q.set(t,o);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 h=function(t){const e=t._peekKeyedActors;return e?e.call(t)??D:t.keyedActors}(s);let u=h.size?new Map(h):D;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&&(u===D&&(u=new Map),u.set(t,e))}q.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function H(t,e,s){const r="object"==typeof t,i=r?t:void 0;return{next:(r?t.next:t)?.bind(i),error:(r?t.error:e)?.bind(i),complete:(r?t.complete:s)?.bind(i),...r&&t.passive?{passive:!0}:{}}}let J,F=0;function X(){return J??=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)}`}(),`${J}:${(F++).toString(36)}`}function G(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function Q(t,e){return`${t?t.address:""}|${e}`}function Y(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},N(t))}function Z(t,e,s){if(void 0!==e){const r=function(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}(e);return r?Y(t,Q(s?.parent,r.prefix),r.index+1):s?.parent||Y(t,Q(void 0,e),1),e}const r=function(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length?e:"x"}(s?.src),i=Q(s?.parent,r),n=t._snapshot._nextActorIds[i]??0;return Y(t,i,n+1),s?.parent||"x"===r||0!==n?`${r}:${n}`:r}const tt=Object.freeze({});function et(t,e){return w(t,e)}function st(t,e){return t.getSnapshot()?.timers?.find(t=>function(t,e){if("id"in e)return t.id===e.id;if(void 0!==t.id)return!1;if("seq"in e)return t.seq===e.seq;if(void 0!==t.seq)return!1;const s=t.event,r=e.event;for(const t in r)if(s[t]!==r[t])return!1;return!0}(t,e))}class rt{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={executionId:X(),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 r=void 0;this._snapshot={_scheduledTimers:s?.scheduler??tt,_nextActorIds:{}}}_recordSent(t,e,s,r,i){if(!this._inspectionObservers?.size||!t)return;const n=t;(n._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:i})}schedule(t,e,s){const r=et(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const n=st(t,e);if(n){const e="self"===n.target?t:n.target;this._recordSent(t,e,n.event,s,n.id)}const o=this._clock.now?.()??Date.now(),c={source:t,delay:s,key:e,scheduledAt:o,dueAt:o+s};this._snapshot._scheduledTimers===tt&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[r]=c,N(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[r],delete this._snapshot._scheduledTimers[r],N(this),this._deliver(t,t,{type:i,...e})},s);(this._timerMap??={})[r]=a}cancel(t,e){const s=et(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==tt&&delete this._snapshot._scheduledTimers[s],N(this),void 0!==r&&this._clock.clearTimeout(r)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.key)}}_deliver(t,e,s){!function(t,e,s){if(a(e)){const r=e,i=t?.system,n=i&&d(i,r);if(!n){const e=u(r);if(!i)throw e;return void i.deadLetter(t,void 0,s,"missingTarget",{targetId:h(r.$actor),error:e})}e=n}if(_(t,e,s))return;e._send(s,t)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),N(this),t}_getByAddress(t){const e=this._getRootActor();if(e?.address===t)return e;for(const e of this._children?.values()??[])if(e.address===t&&e._isRunning())return e}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1);const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&N(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&&N(this)}inspect(t){const e=H(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}onRejectedEvent(t){const e=e=>t(e);return(this._rejectionListeners??=new Set).add(e),{unsubscribe:()=>{this._rejectionListeners?.delete(e)}}}onEmitted(t){const e=e=>t(e);return(this._emissionListeners??=new Set).add(e),{unsubscribe:()=>{this._emissionListeners?.delete(e)}}}_notifyEmitted(t,e){const s=this._emissionListeners;if(!s?.size)return;const r={actorRef:t,event:e};for(const t of Array.from(s))try{t(r)}catch(t){m(t)}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>{try{t.next?.(e)}catch(t){m(t)}})}spawnActor(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);!function(t){t._stop()}(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);!function(t,e){t._terminate(e)}(t,e)}sendEvent(t,e,s){if(a(e)){const r=d(this,e);if(r)e=r;else if(this._getByAddress(e.$actor)||!this.runtime?.sendEvent)return this.deadLetter(t,void 0,s,"missingTarget",{targetId:h(e.$actor),error:u(e)})}if(_(t,e,s))return;this._recordSent(t,e,s);const r=this.runtime?.sendEvent;if(r)return r(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,r,i){const n=this._rejectionListeners;if(n?.size){const o={event:s,targetRef:e,targetId:e?.id??i?.targetId,sourceRef:t,eventOrigin:t?"actor":"external",reason:r,issues:i?.issues,error:i?.error};for(const t of[...n])try{t(o)}catch(t){m(t)}}const o=this.runtime?.deadLetter;if(o)return o(t,e,s,r,i)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):f(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const r=this.runtime?.scheduleTimer;if(r){const i=st(t,e);if(i){const e="self"===i.target?t:i.target;this._recordSent(t,e,i.event,s,i.id)}return r(t,e,s)}this.schedule(t,e,s)}cancelTimer(t,e){const s=this.runtime?.cancelTimer;if(s)return s(t,e);this.cancel(t,e)}cancelAllTimers(t){const e=this.runtime?.cancelAllTimers;if(e)return e(t);this.cancelAll(t)}_relay(t,e,s){if(!function(t){let e=!1,s=!1;for(const r of b)r.parent===t&&(r.requiresReevaluation=!0,e=!0,s||="abort"===r.mode);if(s)throw S;return e}(e))return this.sendEvent(t,e,s)}getSnapshot(){return{_scheduledTimers:{...this._snapshot._scheduledTimers}}}start(){const t=this._snapshot._scheduledTimers;let e=!0;for(const s in t){e&&(this._snapshot._scheduledTimers={},e=!1);const{source:r,dueAt:i,key:n}=t[s];this.scheduleTimer(r,n,Math.max(0,i-(this._clock.now?.()??Date.now())))}}}let it=!1;const nt=Object.freeze([]),ot={"xstate.done.actor":!0,"xstate.error.actor":!0,"xstate.error.execution":!0,"xstate.snapshot.actor":!0,"xstate.done.state":!0,"xstate.after":!0,"xstate.timeout.state":!0,"xstate.timeout.actor":!0,[i]:!0};let ct=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const at=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function ht(t,e){try{t?.(e)}catch(t){m(t)}}function ut(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function dt(t,e){return new pt(t,e)}class pt{get address(){return this._address??=this._parent?`${this._parent.address}/${G(this.id)}`:G(this.id)}get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this._errorObserved=!1,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=ct.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=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,this._warnedUnhandledTypes=void 0;const s=e?{...at,...e}:at,{clock:r,logger:i,parent:n,syncSnapshot:o,id:c,registryKey:a,inspect:h}=s;var u;this.system=n?n.system:s._systemRef?.current??function(t,e){return new rt(t,e)}(this,{clock:r,logger:i,snapshot:s.snapshot,createActorRef:dt}),n||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system,s._systemRef.initialize?.()),h&&!n&&this.system.inspect(H(h)),s.onRejectedEvent&&!n&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(u=this.system)._identity.executionId}:${u._identity.nextSessionId++}`,this.id=Z(this.system,c,{parent:n,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=n,this._syncSnapshot=o,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;this._restored=void 0!==d;try{if(void 0!==d){if(!this.logic.restoreSnapshot&&null===d)throw new Error("Persisted snapshot must be an object.");this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(d,this._actorScope):d)}else if(e?._inert);else{const[t,e]=C(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}}catch(t){const e=void 0===d?void 0:this.logic._createRestoreErrorSnapshot?.(d,t);this._setSnapshot(e??{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=>p(this,t,this.system);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===ct.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=it;try{it=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==ct.Stopped&&this._recoverOrError(t)})}finally{it=e}};this._processingStatus!==ct.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,B(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e,s){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t,s),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,r]=C(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),ut(r,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??nt)ht(e.next,t)}update(t,e){this._setSnapshot(t);const s=this._deferred;for(let e=0;e<(s?.length??0);e++){const r=s[e];try{r()}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??nt,actions:this._collectedActions??nt,sent:this._collectedSent??nt,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 ut(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 r=H(t,e,s);if(this._processingStatus!==ct.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":ht(r.complete);break;case"error":{const t=this._snapshot.error;r.error?(r.passive||(this._errorObserved=!0),ht(r.error,t)):m(t);break}}return{unsubscribe:()=>{this.observers?.delete(r)}}}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,r,i)=>{const n=H(s,r,i);let o=t(this.getSnapshot());return this.subscribe({next:s=>{const r=t(s);e(o,r)||(o=r,n.next?.(r))},error:n.error,complete:n.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===ct.Running)return this;if(this._processingStatus===ct.Stopped){const t=this._snapshot.status;if("done"===t||"error"===t)return this;throw new Error(`Actor ${this.id} was stopped and cannot be restarted. Create a new actor with createActor().`)}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=ct.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,y(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this;case"stopped":return this._stopProcedure(),this._complete(),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,y(this.options.input)):(function(t,e,s){const r=q.get(t),i=W(s);return r?.actor===e&&r.systemState.sourceSystem===s&&r.systemState.sourceVersion+1===i&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(r.systemState.root=e,r.systemState.sourceVersion=i,!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 r of t){const t=e&&void 0!==r.scheduledAt?Math.min(r.delay,Math.max(0,r.scheduledAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,A(r),t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process({event:t,sourceRef:e}){this._lastSourceRef=e;const r=this._snapshot;let i,n;try{i=C(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){n={err:t}}if(n)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(n.err)||this._inspectTransition(this._snapshot,t));if(!i)return;let o=this._snapshot;try{const[n,c]=i;n!==r||c.length||!("machine"in r)||t.type===s||e&&Object.hasOwn(ot,t.type)||this._reportUnhandledEvent(t),o=n,this._setSnapshot(o),ut(c,this._actorScope),this.update(o,t)}catch(e){return void(this._recoverOrError(e,o,r)||this._inspectTransition(this._snapshot,t))}t.type===s&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){ht(()=>this.options.onUnhandledEvent?.(t,this._snapshot))}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)ht(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,r=this.sessionId,{type:"xstate.done.actor",output:s,actorId:e,sessionId:r})));var e,s,r;"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===ct.Stopped?this:(this.mailbox?.clear(),this._processingStatus===ct.NotStarted?(this._processingStatus=ct.Stopped,this.system._unregister(this),this):(this._send({type:s}),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??nt)ht(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||m(t)})}_error(t,e){this._stopProcedure();const s=new Set;for(const t of[this._snapshot,e]){const e=t?.children;for(const t of Object.values(e??{}))t?._parent===this&&"function"==typeof t.getSnapshot&&s.add(t)}for(const t of this.system._peekChildren?.()?.values()??[])t._parent===this&&s.add(t);for(const t of s)try{if("active"!==t.getSnapshot().status)continue;const e=this.system.stopActor(t);e&&Promise.resolve(e).catch(m)}catch(i){m(i)}if(this.observers?.size){let e=!1,s=!1;for(const r of this.observers){const i=r.error;r.passive||(e||=!i,s||=!!i),ht(i,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);var r,i,n;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(r=this.id,i=t,n=this.sessionId,{type:"xstate.error.actor",error:i,actorId:r,sessionId:n}))}_stopProcedure(){this._processingStatus===ct.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=ct.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===ct.Stopped)return void this.system.deadLetter(e,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new v(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue({event:t,sourceRef:e})}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{$actor:this.address}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[g](){return this}getSnapshot(){return this._snapshot}}function lt(t,e){const s=t.check(e);if(s)throw s}const ft=new WeakMap;function _t(t,e,s){const r=function(t){let e=ft.get(t);return e||(e=new Map,ft.set(t,e)),e}(t);if(void 0!==e&&r.has(e))return;const i=s();r.set(e??Symbol(),{cleanup:"function"==typeof i?i:void 0})}function vt(t){const r=(r,i,a)=>{if("active"!==r.status)return[r,[]];if(i.type===s)return[{...r,status:"stopped",input:void 0},[j("@xstate.cleanup",()=>function(t){const e=ft.get(t);if(!e)return;let s;ft.delete(t);for(const{cleanup:t}of e.values())try{t?.()}catch(t){s??={error:t}}if(s)throw s.error}(a.self))]];if(i.type===c)return[{...r,effects:{...r.effects,[i.key]:{status:"active"}}},[]];if(i.type===n)return[{...r,effects:{...r.effects,[i.key]:{status:"done",output:i.output}}},[]];if(i.type===o)return[{...r,effects:{...r.effects,[i.key]:{status:"error",error:i.error}}},[]];const h=[],u=Object.create(null),d={emit:t=>{h.push(function(t,e){return{kind:"emit",exec:O,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(a,t))},sendBack:t=>{const e=a.self._parent;e&&h.push(L(a,e,t))},raise:t=>{h.push(L(a,a.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{const n=r.effects&&Object.prototype.hasOwnProperty.call(r.effects,t)?r.effects[t]:void 0;(!n||i.type===e&&"active"===n.status)&&(h.push(j("@xstate.effect",(e=a.self.system)=>_t(a.self,t,()=>s(e)),{key:t})),u[t]={status:"active"})})(t,s);const n=t;h.push(j("@xstate.effect",(t=a.self.system)=>_t(a.self,void 0,()=>n(t))))}},p=t.run({context:r.context,event:i,input:r.input,system:a.system,self:a.self,emit:a.emit},d),l={...r,...p||{}};return("context"in r||void 0!==p?.context)&&(l.context=p?.context??r.context),(p?.effects||Object.keys(u).length)&&(l.effects={...r.effects,...p?.effects,...u}),C(a,r,[l,h])},i=(e,s,i)=>{if(t.validator){const r=i.self._lastSourceRef,n=r?"actor":"external",o=t.validator.check({kind:"event",logic:a,event:s,eventOrigin:n});if(o)return[e,[M(i,r,s,"invalidEvent",{issues:o.issues,error:o})]]}const n=r(e,s,i);return t.validator&<(t.validator,{kind:"result",logic:a,snapshot:n[0],effects:n[1]}),n},a={id:t.id,config:t,validator:t.validator,transition:i,start:(t,e,s)=>{if(!s?.restored)return;const[r,n]=i(t,y(t.input),e);Object.assign(t,r);for(const t of n)e.actionExecutor(t)},initialTransition:(e,s)=>{t.validator&<(t.validator,{kind:"input",logic:a,input:e});const r=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),n={status:"active",output:void 0,error:void 0,input:e};return void 0!==r&&(n.context=r),i({...n},y(e),s)},getInitialSnapshot:(t,e)=>a.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return a}const yt=new WeakMap;const mt="xstate.observable.next",gt="xstate.observable.error",bt="xstate.observable.complete";const St="xstate.async.resolve",xt="xstate.async.reject";class At extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const wt=vt({context:void 0,run:()=>{}});t.TimeoutError=At,t.createAsyncLogic=function(t){const s=t,r=vt({id:s.id,validator:s.validator,schemas:s.schemas,context:void 0,run:({event:t,input:r,self:i,system:n},o)=>{switch(t.type){case St:{const e=t.data??t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case xt:{const e=t.data??t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===e)return o.effect((t=n)=>{const e=i,o=s=>{t.sendEvent(e,e,s)},c=new AbortController,a=s.timeout,h=K(a),u=void 0===h?void 0:n._clock.setTimeout(()=>{"active"===i.getSnapshot().status&&(c.abort(),o({type:xt,data:new At(a)}))},h),d=()=>{void 0!==u&&n._clock.clearTimeout(u)},l=()=>{try{return Promise.resolve(s.run({input:r,system:n,self:i,signal:c.signal},{emit:s=>{p(e,s,t)},step:(s,r)=>t.runStep?Promise.resolve(t.runStep(e,s,r)):f(e,s,r,o)}))}catch(t){return Promise.reject(t)}};return(t.runLogic?Promise.resolve(t.runLogic(e,l)):l()).then(t=>{d(),"active"===i.getSnapshot().status&&o({type:St,data:t})},t=>{d(),"active"===i.getSnapshot().status&&o({type:xt,data:t})}),()=>{c.abort(),d()}}),{effects:{async:{status:"active"}}}}});return Object.defineProperty(r,E,{value:{kind:"async",timeout:s.timeout}}),r},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return vt({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:r,input:i,self:n,system:o}=t,c=t.emit,a=yt.get(n);a?.receivers?.forEach(t=>t(r)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return yt.set(n,t),t.dispose=e({input:i,system:o,self:n,sendBack:t=>{if("stopped"===n.getSnapshot().status)return;const e=n._parent;e&&o._relay(n,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{yt.delete(n),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return function(t,...[e]){if(e&&"parent"in e)throw new Error('The "parent" actor option was removed. Create child actors through invoke, spawn, or enq.spawn instead.');return new pt(t,e)}(wt)},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,r="function"==typeof t?void 0:t.validator,i={config:t,validator:r,transition:(t,e,r)=>{if("active"!==t.status)return[t,[]];switch(e.type){case gt:return C(r,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case bt:return C(r,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case s:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{r&<(r,{kind:"input",logic:i,input:t});return[{status:"active",output:void 0,error:void 0,context:void 0,input:t,_subscription:void 0},[]]},getInitialSnapshot:(t,e)=>i.initialTransition(e,t)[0],start:(t,{self:s,system:r,emit:i})=>{"done"!==t.status&&(t._subscription=e({input:t.input,system:r,self:s,emit:t=>{i(t)}}).subscribe({next:t=>{s._parent&&r._relay(s,s._parent,t)},error:t=>{r._relay(s,s,{type:gt,data:t})},complete:()=>{r._relay(s,s,{type:bt})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return i},t.createListenerLogic=function(){return I(({actor:t,eventType:e,mapper:s},{self:r,system:i})=>{const n="*"!==e&&e.endsWith(".*");return t.on(n?"*":e,t=>{n&&!function(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),r=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],i=r[t];if("*"===e){return t===s.length-1}if(e!==i)return!1}return!0}(t.type,e)||T(r,i,()=>s(t))})},"@xstate.listener")},t.createObservableLogic=function(t){const s="function"==typeof t?t:t.run,r="function"==typeof t?void 0:t.schemas;return vt({validator:"function"==typeof t?void 0:t.validator,schemas:r,context:void 0,run:(t,r)=>{const{event:i,input:n,self:o,system:c}=t;switch(i.type){case mt:return{context:i.data};case gt:return{status:"error",error:i.data,input:void 0,effects:{observable:{status:"error",error:i.data}}};case bt:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}i.type===e&&r.effect((t=c)=>{const e=o,r=s=>{t.sendEvent(e,e,s)},i=s({input:n,system:c,self:o,emit:s=>{p(e,s,t)}}).subscribe({next:t=>{r({type:mt,data:t})},error:t=>{r({type:gt,data:t})},complete:()=>{r({type:bt})}});return()=>i.unsubscribe()})}})},t.createStepLogic=vt,t.createSubscriptionLogic=function(){return I(({actor:t,mappers:e},{self:s,system:r})=>{const{done:i,error:n,snapshot:o}=e;return t.subscribe({next:t=>{"done"===t.status&&i?T(s,r,()=>i(t.output)):"error"===t.status&&n?T(s,r,()=>n(t.error)):"active"===t.status&&o&&T(s,r,()=>o(t))},error:t=>{n&&T(s,r,()=>n(t))},complete:()=>{}})},"@xstate.subscription")},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).XStateActors={})}(this,function(t){"use strict";const e="xstate.init",s="xstate.stop",r="@xstate.terminate",i="xstate.timer",n="xstate.logic.effect.resolve",o="xstate.logic.effect.reject",c="xstate.logic.effect.start";function a(t){if("object"!=typeof t||null===t||Array.isArray(t)||"string"!=typeof t.$actor)return!1;for(const e in t)if("$actor"!==e&&"incarnation"!==e)return!1;const e=t.incarnation;return void 0===e||"string"==typeof e}function h(t){const e=t.slice(t.lastIndexOf("/")+1);return e.includes("%")?e.replaceAll("%2F","/").replaceAll("%25","%"):e}function u(t){return new Error(void 0===t.incarnation?`Unable to send event to actor '${t.$actor}': no live actor has that address`:`Unable to send event to actor '${t.$actor}' (incarnation '${t.incarnation}'): no live actor has that address and incarnation`)}function d(t,e){const s=t._getByAddress?.(e.$actor);return!s||void 0!==e.incarnation&&s.sessionId!==e.incarnation?void 0:s}function p(t,e,s){return t.system._notifyEmitted(t,e),s.emitEvent(t,e)}Object.freeze({status:"active",output:void 0,error:void 0});const l=new WeakMap;async function f(t,e,s,r=e=>{t.system.sendEvent(t,t,e)}){const i=function(t,e){const s=t.getSnapshot().effects;return s&&Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0}(t,e);if("done"===i?.status)return i.output;if("error"===i?.status)throw i.error;const a=l.get(t)?.get(e);if(a)return a;if("active"!==t.getSnapshot().status)throw new Error(`Actor terminated before step "${e}" completed`);let h,u;const d=new Promise((t,e)=>{h=t,u=e});let p,f=l.get(t);f||(f=new Map,l.set(t,f)),f.set(e,d);const _=()=>{p?.unsubscribe(),f.delete(e),f.size||l.delete(t)};return d.then(_,_),p=t.subscribe({error:u,complete:()=>u(new Error(`Actor terminated before step "${e}" completed`))}),(async()=>{try{r({type:c,key:e});const i=await s();"active"===t.getSnapshot().status&&(r({type:n,key:e,output:i}),h(i))}catch(s){"active"===t.getSnapshot().status&&r({type:o,key:e,error:s}),u(s)}})().catch(u),d}function _(t,e,s){const r=function(t,e,s){const r=e;if(t!==e&&r.logic?.isInternalEventType?.(s.type))return new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`)}(t,e,s);return!!r&&(e.system.deadLetter(t,e,s,"internalEvent",{error:r}),!0)}class v{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}function y(t){return{type:e,input:t}}function m(t){setTimeout(()=>{throw t})}const g="function"==typeof Symbol&&Symbol.observable||"@@observable",b=[],S=new Error("Transition effect");function x(t){const{stateId:e,delay:s,actorId:r}=t;switch(t.type){case"xstate.after":return{type:t.type,delay:s,stateId:e};case"xstate.timeout.state":return{type:t.type,stateId:e};case"xstate.timeout.actor":return{type:t.type,actorId:r}}}function A(t){return void 0!==t.id?{id:t.id}:void 0!==t.seq?{seq:t.seq}:{event:x(t.event)??t.event}}function w(t,e){return`${t.sessionId}|${function(t){return"id"in t?JSON.stringify(["id",t.id]):"seq"in t?JSON.stringify(["seq",t.seq]):JSON.stringify(["event",x(t.event)??t.event])}(e)}`}const E=Symbol("xstate.systemLogicMetadata"),k=new WeakMap;function I(t,e){const r=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]],i={id:e,start:(e,{self:s,system:r})=>{const i=e.input.actor;if(!i||"stopped"===i.getSnapshot().status)return;const n=t(e.input,{self:s,system:r});if(!n)return;let o,c=!1;const a=()=>{c||(c=!0,n.unsubscribe(),o?.unsubscribe())},h=s._parent;h&&(o=h.subscribe({complete:a,error:a})),k.set(s,{unsubscribe:a})},transition:(t,e,{self:r})=>e.type===s?(k.get(r)?.unsubscribe(),k.delete(r),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:r,getInitialSnapshot:(t,e)=>r(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return Object.defineProperty(i,E,{value:{kind:e}}),i}function T(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function O(t=this.source.system){return p(this.source,this.event,t)}function R(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function M(t,e,s,r,i){return{kind:"builtin",type:"@xstate.deadLetter",exec:R,source:e,target:t.self,event:s,reason:r,detail:i,params:void 0,args:[]}}function j(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function $(t=this.actor.system){const e="done"===this.status?{status:"done",output:this.output,error:void 0}:{status:"error",output:void 0,error:this.error};return t.terminateActor(this.actor,e)}function P(t=this.source.system){return function(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}(this.event),void 0!==this.delay?t.scheduleTimer(this.source,A(this),this.delay):t.sendEvent(this.source,this.target,this.event)}function L(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:P,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function z(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},i=[t.self,s];return{kind:"builtin",exec:$,type:r,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:i}}function C(t,e,[s,i]){const n="done"===s.status||"error"===s.status,o="done"===e?.status||"error"===e?.status,c=i.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===r);return!n||o||c?[s,i]:[s,[...i,z(t,s)]]}function K(t){if(void 0!==t)return"number"==typeof t?t:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const r=e.match(/^(\d*)(\.?)(\d*)s$/i);if(r){const t=r[1]?parseInt(r[1],10):0,e=!!r[2],s=r[3]?parseInt(r[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const i=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(!i?.groups)return;const{weeks:n,days:o,hours:c,minutes:a,seconds:h}=i.groups;if(!(n||o||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(n)*24*60*60*1e3+24*u(o)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)}const q=new WeakMap,U=new WeakMap,D=new Map;function N(t){t._snapshotVersion++}function W(t){return t._snapshotVersion}function V(t){const e=q.get(t);if(e)return e;const s=U.get(t);if(!s)return;const r=s();return q.set(t,r),U.delete(t),r}function B(t,e,s=e.system,r){U.delete(t);const i=W(s),n=r?V(r):void 0,o=n?.actor===e?n:V(t);if(o?.actor===e&&o.systemState.sourceSystem===s&&o.systemState.sourceVersion===i)return void q.set(t,o);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 h=function(t){const e=t._peekKeyedActors;return e?e.call(t)??D:t.keyedActors}(s);let u=h.size?new Map(h):D;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&&(u===D&&(u=new Map),u.set(t,e))}q.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function H(t,e,s){const r="object"==typeof t,i=r?t:void 0;return{next:(r?t.next:t)?.bind(i),error:(r?t.error:e)?.bind(i),complete:(r?t.complete:s)?.bind(i),...r&&t.passive?{passive:!0}:{}}}let J,F=0;function X(){return J??=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)}`}(),`${J}:${(F++).toString(36)}`}function G(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function Q(t,e){return`${t?t.address:""}|${e}`}function Y(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},N(t))}function Z(t,e,s){if(void 0!==e){const r=function(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}(e);return r?Y(t,Q(s?.parent,r.prefix),r.index+1):s?.parent||Y(t,Q(void 0,e),1),e}const r=function(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length?e:"x"}(s?.src),i=Q(s?.parent,r),n=t._snapshot._nextActorIds[i]??0;return Y(t,i,n+1),s?.parent||"x"===r||0!==n?`${r}:${n}`:r}const tt=Object.freeze({});function et(t,e){return w(t,e)}function st(t,e){return t.getSnapshot()?.timers?.find(t=>function(t,e){if("id"in e)return t.id===e.id;if(void 0!==t.id)return!1;if("seq"in e)return t.seq===e.seq;if(void 0!==t.seq)return!1;const s=t.event,r=e.event;for(const t in r)if(s[t]!==r[t])return!1;return!0}(t,e))}class rt{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={executionId:X(),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 r=void 0;this._snapshot={_scheduledTimers:s?.scheduler??tt,_nextActorIds:{}}}_recordSent(t,e,s,r,i){if(!this._inspectionObservers?.size||!t)return;const n=t;(n._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:i})}schedule(t,e,s){const r=et(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const n=st(t,e);if(n){const e="self"===n.target?t:n.target;this._recordSent(t,e,n.event,s,n.id)}const o=this._clock.now?.()??Date.now(),c={source:t,delay:s,key:e,scheduledAt:o,dueAt:o+s};this._snapshot._scheduledTimers===tt&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[r]=c,N(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[r],delete this._snapshot._scheduledTimers[r],N(this),this._deliver(t,t,{type:i,...e})},s);(this._timerMap??={})[r]=a}cancel(t,e){const s=et(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==tt&&delete this._snapshot._scheduledTimers[s],N(this),void 0!==r&&this._clock.clearTimeout(r)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.key)}}_deliver(t,e,s){!function(t,e,s){if(a(e)){const r=e,i=t?.system,n=i&&d(i,r);if(!n){const e=u(r);if(!i)throw e;return void i.deadLetter(t,void 0,s,"missingTarget",{targetId:h(r.$actor),error:e})}e=n}if(_(t,e,s))return;e._send(s,t)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),N(this),t}_getByAddress(t){const e=this._getRootActor();if(e?.address===t)return e;for(const e of this._children?.values()??[])if(e.address===t&&e._isRunning())return e}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1);const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&N(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&&N(this)}inspect(t){const e=H(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}onRejectedEvent(t){const e=e=>t(e);return(this._rejectionListeners??=new Set).add(e),{unsubscribe:()=>{this._rejectionListeners?.delete(e)}}}onEmitted(t){const e=e=>t(e);return(this._emissionListeners??=new Set).add(e),{unsubscribe:()=>{this._emissionListeners?.delete(e)}}}_notifyEmitted(t,e){const s=this._emissionListeners;if(!s?.size)return;const r={actorRef:t,event:e};for(const t of Array.from(s))try{t(r)}catch(t){m(t)}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>{try{t.next?.(e)}catch(t){m(t)}})}spawnActor(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);!function(t){t._stop()}(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);!function(t,e){t._terminate(e)}(t,e)}sendEvent(t,e,s){if(a(e)){const r=d(this,e);if(r)e=r;else if(this._getByAddress(e.$actor)||!this.runtime?.sendEvent)return this.deadLetter(t,void 0,s,"missingTarget",{targetId:h(e.$actor),error:u(e)})}if(_(t,e,s))return;this._recordSent(t,e,s);const r=this.runtime?.sendEvent;if(r)return r(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,r,i){const n=this._rejectionListeners;if(n?.size){const o={event:s,targetRef:e,targetId:e?.id??i?.targetId,sourceRef:t,eventOrigin:t?"actor":"external",reason:r,issues:i?.issues,error:i?.error};for(const t of[...n])try{t(o)}catch(t){m(t)}}const o=this.runtime?.deadLetter;if(o)return o(t,e,s,r,i)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):f(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const r=this.runtime?.scheduleTimer;if(r){const i=st(t,e);if(i){const e="self"===i.target?t:i.target;this._recordSent(t,e,i.event,s,i.id)}return r(t,e,s)}this.schedule(t,e,s)}cancelTimer(t,e){const s=this.runtime?.cancelTimer;if(s)return s(t,e);this.cancel(t,e)}cancelAllTimers(t){const e=this.runtime?.cancelAllTimers;if(e)return e(t);this.cancelAll(t)}_relay(t,e,s){if(!function(t){let e=!1,s=!1;for(const r of b)r.parent===t&&(r.requiresReevaluation=!0,e=!0,s||="abort"===r.mode);if(s)throw S;return e}(e))return this.sendEvent(t,e,s)}getSnapshot(){return{_scheduledTimers:{...this._snapshot._scheduledTimers}}}start(){const t=this._snapshot._scheduledTimers;let e=!0;for(const s in t){e&&(this._snapshot._scheduledTimers={},e=!1);const{source:r,dueAt:i,key:n}=t[s];this.scheduleTimer(r,n,Math.max(0,i-(this._clock.now?.()??Date.now())))}}}let it=!1;const nt=Object.freeze([]),ot={"xstate.done.actor":!0,"xstate.error.actor":!0,"xstate.error.execution":!0,"xstate.snapshot.actor":!0,"xstate.done.state":!0,"xstate.after":!0,"xstate.timeout.state":!0,"xstate.timeout.actor":!0,[i]:!0};let ct=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const at=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function ht(t,e){try{t?.(e)}catch(t){m(t)}}function ut(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function dt(t,e){return new pt(t,e)}class pt{get address(){return this._address??=this._parent?`${this._parent.address}/${G(this.id)}`:G(this.id)}get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this._errorObserved=!1,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=ct.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=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,this._warnedUnhandledTypes=void 0;const s=e?{...at,...e}:at,{clock:r,logger:i,parent:n,syncSnapshot:o,id:c,registryKey:a,inspect:h}=s;var u;this.system=n?n.system:s._systemRef?.current??function(t,e){return new rt(t,e)}(this,{clock:r,logger:i,snapshot:s.snapshot,createActorRef:dt}),n||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system,s._systemRef.initialize?.()),h&&!n&&this.system.inspect(H(h)),s.onRejectedEvent&&!n&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(u=this.system)._identity.executionId}:${u._identity.nextSessionId++}`,this.id=Z(this.system,c,{parent:n,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=n,this._syncSnapshot=o,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;this._restored=void 0!==d;try{if(void 0!==d){if(!this.logic.restoreSnapshot&&null===d)throw new Error("Persisted snapshot must be an object.");this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(d,this._actorScope):d)}else if(e?._inert);else{const[t,e]=C(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}}catch(t){const e=void 0===d?void 0:this.logic._createRestoreErrorSnapshot?.(d,t);this._setSnapshot(e??{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=>p(this,t,this.system);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===ct.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=it;try{it=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==ct.Stopped&&this._recoverOrError(t)})}finally{it=e}};this._processingStatus!==ct.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,B(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e,s){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t,s),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,r]=C(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),ut(r,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??nt)ht(e.next,t)}update(t,e){this._setSnapshot(t);const s=this._deferred;for(let e=0;e<(s?.length??0);e++){const r=s[e];try{r()}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??nt,actions:this._collectedActions??nt,sent:this._collectedSent??nt,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 ut(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 r=H(t,e,s);if(this._processingStatus!==ct.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":ht(r.complete);break;case"error":{const t=this._snapshot.error;r.error?(r.passive||(this._errorObserved=!0),ht(r.error,t)):m(t);break}}return{unsubscribe:()=>{this.observers?.delete(r)}}}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,r,i)=>{const n=H(s,r,i);let o=t(this.getSnapshot());return this.subscribe({next:s=>{const r=t(s);e(o,r)||(o=r,n.next?.(r))},error:n.error,complete:n.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===ct.Running)return this;if(this._processingStatus===ct.Stopped){const t=this._snapshot.status;if("done"===t||"error"===t)return this;throw new Error(`Actor ${this.id} was stopped and cannot be restarted. Create a new actor with createActor().`)}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=ct.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,y(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this;case"stopped":return this._stopProcedure(),this._complete(),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,y(this.options.input)):(function(t,e,s){const r=q.get(t),i=W(s);return r?.actor===e&&r.systemState.sourceSystem===s&&r.systemState.sourceVersion+1===i&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(r.systemState.root=e,r.systemState.sourceVersion=i,!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 r of t){const t=e&&void 0!==r.scheduledAt?Math.min(r.delay,Math.max(0,r.scheduledAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,A(r),t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process({event:t,sourceRef:e}){this._lastSourceRef=e;const r=this._snapshot;let i,n;try{i=C(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){n={err:t}}if(n)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(n.err)||this._inspectTransition(this._snapshot,t));if(!i)return;let o=this._snapshot;try{const[n,c]=i;n!==r||c.length||!("machine"in r)||t.type===s||e&&Object.hasOwn(ot,t.type)||this._reportUnhandledEvent(t),o=n,this._setSnapshot(o),ut(c,this._actorScope),this.update(o,t)}catch(e){return void(this._recoverOrError(e,o,r)||this._inspectTransition(this._snapshot,t))}t.type===s&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){ht(()=>this.options.onUnhandledEvent?.(t,this._snapshot))}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)ht(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,r=this.sessionId,{type:"xstate.done.actor",output:s,actorId:e,sessionId:r})));var e,s,r;"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===ct.Stopped?this:(this.mailbox?.clear(),this._processingStatus===ct.NotStarted?(this._processingStatus=ct.Stopped,this.system._unregister(this),this):(this._send({type:s}),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??nt)ht(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||m(t)})}_error(t,e){this._stopProcedure();const s=new Set;for(const t of[this._snapshot,e]){const e=t?.children;for(const t of Object.values(e??{}))t?._parent===this&&"function"==typeof t.getSnapshot&&s.add(t)}for(const t of this.system._peekChildren?.()?.values()??[])t._parent===this&&s.add(t);for(const t of s)try{if("active"!==t.getSnapshot().status)continue;const e=this.system.stopActor(t);e&&Promise.resolve(e).catch(m)}catch(i){m(i)}if(this.observers?.size){let e=!1,s=!1;for(const r of this.observers){const i=r.error;r.passive||(e||=!i,s||=!!i),ht(i,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);var r,i,n;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(r=this.id,i=t,n=this.sessionId,{type:"xstate.error.actor",error:i,actorId:r,sessionId:n}))}_stopProcedure(){this._processingStatus===ct.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=ct.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===ct.Stopped)return void this.system.deadLetter(e,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new v(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue({event:t,sourceRef:e})}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{$actor:this.address}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[g](){return this}getSnapshot(){return this._snapshot}}function lt(t,e){const s=t.check(e);if(s)throw s}const ft=new WeakMap;function _t(t,e,s){const r=function(t){let e=ft.get(t);return e||(e=new Map,ft.set(t,e)),e}(t);if(void 0!==e&&r.has(e))return;const i=s();r.set(e??Symbol(),{cleanup:"function"==typeof i?i:void 0})}function vt(t){const r=(r,i,a)=>{if("active"!==r.status)return[r,[]];if(i.type===s)return[{...r,status:"stopped",input:void 0},[j("@xstate.cleanup",()=>function(t){const e=ft.get(t);if(!e)return;let s;ft.delete(t);for(const{cleanup:t}of e.values())try{t?.()}catch(t){s??={error:t}}if(s)throw s.error}(a.self))]];if(i.type===c)return[{...r,effects:{...r.effects,[i.key]:{status:"active"}}},[]];if(i.type===n)return[{...r,effects:{...r.effects,[i.key]:{status:"done",output:i.output}}},[]];if(i.type===o)return[{...r,effects:{...r.effects,[i.key]:{status:"error",error:i.error}}},[]];const h=[],u=Object.create(null),d={emit:t=>{h.push(function(t,e){return{kind:"emit",exec:O,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(a,t))},sendBack:t=>{const e=a.self._parent;e&&h.push(L(a,e,t))},raise:t=>{h.push(L(a,a.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{const n=r.effects&&Object.prototype.hasOwnProperty.call(r.effects,t)?r.effects[t]:void 0;(!n||i.type===e&&"active"===n.status)&&(h.push(j("@xstate.effect",(e=a.self.system)=>_t(a.self,t,()=>s(e)),{key:t})),u[t]={status:"active"})})(t,s);const n=t;h.push(j("@xstate.effect",(t=a.self.system)=>_t(a.self,void 0,()=>n(t))))}},p=t.run({context:r.context,event:i,input:r.input,system:a.system,self:a.self,emit:a.emit},d),l={...r,...p||{}};return("context"in r||void 0!==p?.context)&&(l.context=p?.context??r.context),(p?.effects||Object.keys(u).length)&&(l.effects={...r.effects,...p?.effects,...u}),C(a,r,[l,h])},i=(e,s,i)=>{if(t.validator){const r=i.self._lastSourceRef,n=r?"actor":"external",o=t.validator.check({kind:"event",logic:a,event:s,eventOrigin:n});if(o)return[e,[M(i,r,s,"invalidEvent",{issues:o.issues,error:o})]]}const n=r(e,s,i);return t.validator&<(t.validator,{kind:"result",logic:a,snapshot:n[0],effects:n[1]}),n},a={id:t.id,config:t,validator:t.validator,transition:i,start:(t,e,s)=>{if(!s?.restored)return;const[r,n]=i(t,y(t.input),e);Object.assign(t,r);for(const t of n)e.actionExecutor(t)},initialTransition:(e,s)=>{t.validator&<(t.validator,{kind:"input",logic:a,input:e});const r=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),n={status:"active",output:void 0,error:void 0,input:e};return void 0!==r&&(n.context=r),i({...n},y(e),s)},getInitialSnapshot:(t,e)=>a.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return a}const yt=new WeakMap;const mt="xstate.observable.next",gt="xstate.observable.error",bt="xstate.observable.complete";const St="xstate.async.resolve",xt="xstate.async.reject";class At extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const wt=vt({context:void 0,run:()=>{}});t.TimeoutError=At,t.createAsyncLogic=function(t){const s=t,r=vt({id:s.id,validator:s.validator,schemas:s.schemas,context:void 0,run:({event:t,input:r,self:i,system:n},o)=>{switch(t.type){case St:{const e="data"in t?t.data:t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case xt:{const e="data"in t?t.data:t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===e)return o.effect((t=n)=>{const e=i,o=s=>{t.sendEvent(e,e,s)},c=new AbortController,a=s.timeout,h=K(a),u=void 0===h?void 0:n._clock.setTimeout(()=>{"active"===i.getSnapshot().status&&(c.abort(),o({type:xt,data:new At(a)}))},h),d=()=>{void 0!==u&&n._clock.clearTimeout(u)},l=()=>{try{return Promise.resolve(s.run({input:r,system:n,self:i,signal:c.signal},{emit:s=>{p(e,s,t)},step:(s,r)=>t.runStep?Promise.resolve(t.runStep(e,s,r)):f(e,s,r,o)}))}catch(t){return Promise.reject(t)}};return(t.runLogic?Promise.resolve(t.runLogic(e,l)):l()).then(t=>{d(),"active"===i.getSnapshot().status&&o({type:St,data:t})},t=>{d(),"active"===i.getSnapshot().status&&o({type:xt,data:t})}),()=>{c.abort(),d()}}),{effects:{async:{status:"active"}}}}});return Object.defineProperty(r,E,{value:{kind:"async",timeout:s.timeout}}),r},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return vt({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:r,input:i,self:n,system:o}=t,c=t.emit,a=yt.get(n);a?.receivers?.forEach(t=>t(r)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return yt.set(n,t),t.dispose=e({input:i,system:o,self:n,sendBack:t=>{if("stopped"===n.getSnapshot().status)return;const e=n._parent;e&&o._relay(n,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{yt.delete(n),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return function(t,...[e]){if(e&&"parent"in e)throw new Error('The "parent" actor option was removed. Create child actors through invoke, spawn, or enq.spawn instead.');return new pt(t,e)}(wt)},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,r="function"==typeof t?void 0:t.validator,i={config:t,validator:r,transition:(t,e,r)=>{if("active"!==t.status)return[t,[]];switch(e.type){case gt:return C(r,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case bt:return C(r,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case s:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{r&<(r,{kind:"input",logic:i,input:t});return[{status:"active",output:void 0,error:void 0,context:void 0,input:t,_subscription:void 0},[]]},getInitialSnapshot:(t,e)=>i.initialTransition(e,t)[0],start:(t,{self:s,system:r,emit:i})=>{"done"!==t.status&&(t._subscription=e({input:t.input,system:r,self:s,emit:t=>{i(t)}}).subscribe({next:t=>{s._parent&&r._relay(s,s._parent,t)},error:t=>{r._relay(s,s,{type:gt,data:t})},complete:()=>{r._relay(s,s,{type:bt})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return i},t.createListenerLogic=function(){return I(({actor:t,eventType:e,mapper:s},{self:r,system:i})=>{const n="*"!==e&&e.endsWith(".*");return t.on(n?"*":e,t=>{n&&!function(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),r=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],i=r[t];if("*"===e){return t===s.length-1}if(e!==i)return!1}return!0}(t.type,e)||T(r,i,()=>s(t))})},"@xstate.listener")},t.createObservableLogic=function(t){const s="function"==typeof t?t:t.run,r="function"==typeof t?void 0:t.schemas;return vt({validator:"function"==typeof t?void 0:t.validator,schemas:r,context:void 0,run:(t,r)=>{const{event:i,input:n,self:o,system:c}=t;switch(i.type){case mt:return{context:i.data};case gt:return{status:"error",error:i.data,input:void 0,effects:{observable:{status:"error",error:i.data}}};case bt:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}i.type===e&&r.effect((t=c)=>{const e=o,r=s=>{t.sendEvent(e,e,s)},i=s({input:n,system:c,self:o,emit:s=>{p(e,s,t)}}).subscribe({next:t=>{r({type:mt,data:t})},error:t=>{r({type:gt,data:t})},complete:()=>{r({type:bt})}});return()=>i.unsubscribe()})}})},t.createStepLogic=vt,t.createSubscriptionLogic=function(){return I(({actor:t,mappers:e},{self:s,system:r})=>{const{done:i,error:n,snapshot:o}=e;return t.subscribe({next:t=>{"done"===t.status&&i?T(s,r,()=>i(t.output)):"error"===t.status&&n?T(s,r,()=>n(t.error)):"active"===t.status&&o&&T(s,r,()=>o(t))},error:t=>{n&&T(s,r,()=>n(t))},complete:()=>{}})},"@xstate.subscription")},Object.defineProperty(t,"__esModule",{value:!0})});
|
|
2
2
|
//# sourceMappingURL=xstate-actors.umd.min.js.map
|