xstate 6.0.0-alpha.63 → 6.0.0-alpha.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +18 -1
  2. package/dist/{createActor-eba8226e.cjs.js → createActor-29adb8a4.cjs.js} +33 -5
  3. package/dist/{createActor-f71670cf.development.cjs.js → createActor-521c8805.development.cjs.js} +33 -5
  4. package/dist/{createActor-523a98c7.esm.js → createActor-8493caa9.esm.js} +29 -6
  5. package/dist/{createActor-48f753a9.development.esm.js → createActor-bd2527dc.development.esm.js} +29 -6
  6. package/dist/declarations/src/SimulatedClock.d.ts +1 -1
  7. package/dist/declarations/src/createMachine.d.ts +3 -3
  8. package/dist/declarations/src/durable/index.d.ts +13 -0
  9. package/dist/declarations/src/index.d.ts +2 -1
  10. package/dist/declarations/src/setup.d.ts +152 -15
  11. package/dist/declarations/src/systemTransition.d.ts +103 -0
  12. package/dist/declarations/src/types.d.ts +3 -3
  13. package/dist/declarations/src/types.v6.d.ts +12 -4
  14. package/dist/{effectDescriptor-8c87a3e7.development.cjs.js → effectDescriptor-62b53c6d.development.cjs.js} +1 -1
  15. package/dist/{effectDescriptor-bc9e3e81.cjs.js → effectDescriptor-6dbc400a.cjs.js} +1 -1
  16. package/dist/{effectDescriptor-ad75e430.esm.js → effectDescriptor-85ea06c9.esm.js} +1 -1
  17. package/dist/{effectDescriptor-eadf1b25.development.esm.js → effectDescriptor-f76948fc.development.esm.js} +1 -1
  18. package/dist/{index-83f11f07.cjs.js → index-2afc57c3.development.cjs.js} +9 -2
  19. package/dist/{index-3cb56f46.development.cjs.js → index-5587e13b.cjs.js} +9 -2
  20. package/dist/{index-2a4be1f2.development.esm.js → index-90ebf5ae.development.esm.js} +9 -2
  21. package/dist/{index-211a5dce.esm.js → index-b0dc2b39.esm.js} +9 -2
  22. package/dist/xstate-actors.cjs.js +2 -2
  23. package/dist/xstate-actors.development.cjs.js +2 -2
  24. package/dist/xstate-actors.development.esm.js +2 -2
  25. package/dist/xstate-actors.esm.js +2 -2
  26. package/dist/xstate-actors.umd.min.js +1 -1
  27. package/dist/xstate-actors.umd.min.js.map +1 -1
  28. package/dist/xstate-durable.cjs.js +36 -4
  29. package/dist/xstate-durable.development.cjs.js +36 -4
  30. package/dist/xstate-durable.development.esm.js +36 -4
  31. package/dist/xstate-durable.esm.js +36 -4
  32. package/dist/xstate-durable.umd.min.js +1 -1
  33. package/dist/xstate-durable.umd.min.js.map +1 -1
  34. package/dist/xstate-graph.cjs.js +2 -2
  35. package/dist/xstate-graph.development.cjs.js +2 -2
  36. package/dist/xstate-graph.development.esm.js +2 -2
  37. package/dist/xstate-graph.esm.js +2 -2
  38. package/dist/xstate-validation.cjs.js +1 -1
  39. package/dist/xstate-validation.development.cjs.js +1 -1
  40. package/dist/xstate-validation.development.esm.js +1 -1
  41. package/dist/xstate-validation.esm.js +1 -1
  42. package/dist/xstate.cjs.js +842 -35
  43. package/dist/xstate.cjs.mjs +3 -0
  44. package/dist/xstate.development.cjs.js +842 -35
  45. package/dist/xstate.development.cjs.mjs +3 -0
  46. package/dist/xstate.development.esm.js +842 -38
  47. package/dist/xstate.esm.js +842 -38
  48. package/dist/xstate.umd.min.js +1 -1
  49. package/dist/xstate.umd.min.js.map +1 -1
  50. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import { O as createInitEvent, y as createDeadLetterEffect, ao as XSTATE_STOP, ap as createCustomEffect, aq as XSTATE_LOGIC_EFFECT_START, ar as XSTATE_LOGIC_EFFECT_RESOLVE, as as XSTATE_LOGIC_EFFECT_REJECT, at as finalizeTransitionResult, au as createEmitEffect, av as createSendToEffect, aw as XSTATE_INIT, a2 as parseDelayToMilliseconds, al as runStep, a1 as createActor } from './createActor-523a98c7.esm.js';
1
+ import { O as createInitEvent, y as createDeadLetterEffect, au as XSTATE_STOP, av as createCustomEffect, aw as XSTATE_LOGIC_EFFECT_START, ax as XSTATE_LOGIC_EFFECT_RESOLVE, ay as XSTATE_LOGIC_EFFECT_REJECT, a9 as finalizeTransitionResult, az as createEmitEffect, aA as createSendToEffect, aB as XSTATE_INIT, a2 as parseDelayToMilliseconds, a7 as systemLogicMetadata, ar as runStep, a1 as createActor } from './createActor-8493caa9.esm.js';
2
2
 
3
3
  function assertValid(validator, request) {
4
4
  const error = validator.check(request);
@@ -898,7 +898,7 @@ class TimeoutError extends Error {
898
898
 
899
899
  function createAsyncLogic(asyncLogic) {
900
900
  const config = asyncLogic;
901
- return createLogic({
901
+ const logic = createLogic({
902
902
  id: config.id,
903
903
  validator: config.validator,
904
904
  schemas: config.schemas,
@@ -1016,6 +1016,13 @@ function createAsyncLogic(asyncLogic) {
1016
1016
  };
1017
1017
  }
1018
1018
  });
1019
+ Object.defineProperty(logic, systemLogicMetadata, {
1020
+ value: {
1021
+ kind: 'async',
1022
+ timeout: config.timeout
1023
+ }
1024
+ });
1025
+ return logic;
1019
1026
  }
1020
1027
 
1021
1028
  const emptyLogic = /* #__PURE__ */createLogic({
@@ -2,8 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var createActor = require('./createActor-eba8226e.cjs.js');
6
- var dist_xstateActors = require('./index-83f11f07.cjs.js');
5
+ var createActor = require('./createActor-29adb8a4.cjs.js');
6
+ var dist_xstateActors = require('./index-5587e13b.cjs.js');
7
7
 
8
8
 
9
9
 
@@ -2,8 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var createActor = require('./createActor-f71670cf.development.cjs.js');
6
- var dist_xstateActors = require('./index-3cb56f46.development.cjs.js');
5
+ var createActor = require('./createActor-521c8805.development.cjs.js');
6
+ var dist_xstateActors = require('./index-2afc57c3.development.cjs.js');
7
7
 
8
8
 
9
9
 
@@ -1,2 +1,2 @@
1
- export { a6 as createListenerLogic, a7 as createSubscriptionLogic, a8 as listenerLogic, a9 as subscriptionLogic } from './createActor-48f753a9.development.esm.js';
2
- export { T as TimeoutError, c as createAsyncLogic, b as createCallbackLogic, d as createEmptyActor, e as createEventObservableLogic, f as createLogic, g as createObservableLogic } from './index-2a4be1f2.development.esm.js';
1
+ export { af as createListenerLogic, ag as createSubscriptionLogic, ad as listenerLogic, ae as subscriptionLogic } from './createActor-bd2527dc.development.esm.js';
2
+ export { T as TimeoutError, c as createAsyncLogic, b as createCallbackLogic, d as createEmptyActor, e as createEventObservableLogic, f as createLogic, g as createObservableLogic } from './index-90ebf5ae.development.esm.js';
@@ -1,2 +1,2 @@
1
- export { a6 as createListenerLogic, a7 as createSubscriptionLogic, a8 as listenerLogic, a9 as subscriptionLogic } from './createActor-523a98c7.esm.js';
2
- export { T as TimeoutError, c as createAsyncLogic, b as createCallbackLogic, d as createEmptyActor, e as createEventObservableLogic, f as createLogic, g as createObservableLogic } from './index-211a5dce.esm.js';
1
+ export { af as createListenerLogic, ag as createSubscriptionLogic, ad as listenerLogic, ae as subscriptionLogic } from './createActor-8493caa9.esm.js';
2
+ export { T as TimeoutError, c as createAsyncLogic, b as createCallbackLogic, d as createEmptyActor, e as createEventObservableLogic, f as createLogic, g as createObservableLogic } from './index-b0dc2b39.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";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",r="@xstate.stop",i="@xstate.terminate",o="xstate.logic.effect.resolve",n="xstate.logic.effect.reject",c="xstate.logic.effect.start";function a(t){return{type:s,input:t}}function h(t){setTimeout(()=>{throw t})}const u="function"==typeof Symbol&&Symbol.observable||"@@observable";const d=new WeakMap;function p(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{id:e,start:(e,{self:s,system:r})=>{const i=e.input.actor;if(!i||"stopped"===i.getSnapshot().status)return;const o=t(e.input,{self:s,system:r});if(!o)return;let n,c=!1;const a=()=>{c||(c=!0,o.unsubscribe(),n?.unsubscribe())},h=s._parent;h&&(n=h.subscribe({complete:a,error:a})),d.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===r?(d.get(s)?.unsubscribe(),d.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function l(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function f(){return p(({actor:t,eventType:e,mapper:s},{self:r,system:i})=>{const o="*"!==e&&e.endsWith(".*");return t.on(o?"*":e,t=>{o&&!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)||l(r,i,()=>s(t))})},"xstate.listener")}const _=f();function v(){return p(({actor:t,mappers:e},{self:s,system:r})=>{const{done:i,error:o,snapshot:n}=e;return t.subscribe({next:t=>{"done"===t.status&&i?l(s,r,()=>i(t.output)):"error"===t.status&&o?l(s,r,()=>o(t.error)):"active"===t.status&&n&&l(s,r,()=>n(t))},error:t=>{o&&l(s,r,()=>o(t))},complete:()=>{}})},"xstate.subscription")}const y=v();function m(t=this.source.system){return t.emitEvent(this.source,this.event)}function g(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function b(t,e,s,r,i){return{kind:"builtin",type:"@xstate.deadLetter",exec:g,source:e,target:t.self,event:s,reason:r,detail:i,params:void 0,args:[]}}function S(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function x(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 A(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,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function w(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:A,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function E(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},r=[t.self,s];return{kind:"builtin",exec:x,type:i,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:r}}function k(t,e,[s,r]){const o="done"===s.status||"error"===s.status,n="done"===e?.status||"error"===e?.status,c=r.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===i);return!o||n||c?[s,r]:[s,[...r,E(t,s)]]}const T=()=>{},I=()=>({});function O(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:o,days:n,hours:c,minutes:a,seconds:h}=i.groups;if(!(o||n||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(o)*24*60*60*1e3+24*u(n)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)}!function(t,e){const s=(t,...s)=>{e(t,...s)};Object.assign(s,{cancel:T,emit:T,log:T,raise:T,spawn:I,sendTo:T,stop:T,listen:I,subscribeTo:I,...t})}({},T);const R=new WeakMap,M=new WeakMap,j=new Map;function P(t){t._snapshotVersion++}function L(t){return t._snapshotVersion}function $(t){const e=R.get(t);if(e)return e;const s=M.get(t);if(!s)return;const r=s();return R.set(t,r),M.delete(t),r}function K(t,e,s=e.system,r){M.delete(t);const i=L(s),o=r?$(r):void 0,n=o?.actor===e?o:$(t);if(n?.actor===e&&n.systemState.sourceSystem===s&&n.systemState.sourceVersion===i)return void R.set(t,n);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)??j:t.keyedActors}(s);let u=h.size?new Map(h):j;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===j&&(u=new Map),u.set(t,e))}R.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function C(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}:{}}}const z=new WeakMap;async function U(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=z.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,l=z.get(t);l||(l=new Map,z.set(t,l)),l.set(e,d);const f=()=>{p?.unsubscribe(),l.delete(e),l.size||z.delete(t)};return d.then(f,f),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:o,key:e,output:i}),h(i))}catch(s){"active"===t.getSnapshot().status&&r({type:n,key:e,error:s}),u(s)}})().catch(u),d}function W(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)}let D,V=0;const N=new Error("Transition effect"),H=[];function q(){return D??=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)}`}(),`${D}:${(V++).toString(36)}`}function B(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function F(t,e){return`${t?t.address:""}|${e}`}function J(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},P(t))}function X(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?J(t,F(s?.parent,r.prefix),r.index+1):s?.parent||J(t,F(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&&"(machine)"!==e?e:"x"}(s?.src),i=F(s?.parent,r),o=t._snapshot._nextActorIds[i]??0;return J(t,i,o+1),s?.parent||"x"===r||0!==o?`${r}:${o}`:r}const G=Object.freeze({});function Q(t,e){return`${t.sessionId}.${e}`}class Y{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:q(),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??G,_nextActorIds:{}}}_recordSent(t,e,s,r,i){if(!this._inspectionObservers?.size||!t)return;const o=t;(o._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:i})}schedule(t,e,s){const r=Q(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const i=t.getSnapshot()?.timers?.[e];if(i){const r="self"===i.target?t:i.target;this._recordSent(t,r,i.event,s,e)}const o=this._clock.now?.()??Date.now(),n={source:t,delay:s,id:e,scheduledAt:o,dueAt:o+s},c=Q(t,e);this._snapshot._scheduledTimers===G&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[c]=n,P(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[c],delete this._snapshot._scheduledTimers[c],P(this),this._deliver(t,t,{type:"xstate.timer",id:e})},s);(this._timerMap??={})[c]=a}cancel(t,e){const s=Q(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==G&&delete this._snapshot._scheduledTimers[s],P(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.id)}}_deliver(t,e,s){!function(t,e,s){if(W(t,e,s))return;const r=e;r._lastSourceRef=t,r._send(s)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),P(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&&P(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&&P(this)}inspect(t){const e=C(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)}}}_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(W(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 o=this._rejectionListeners;if(o?.size){const n={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[...o])try{t(n)}catch(t){h(t)}}const n=this.runtime?.deadLetter;if(n)return n(t,e,s,r,i)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):U(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=t.getSnapshot()?.timers?.[e];if(i){const r="self"===i.target?t:i.target;this._recordSent(t,r,i.event,s,e)}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(H.length&&H.includes(e))throw N;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,id:o}=t[s];this.scheduleTimer(r,o,Math.max(0,i-(this._clock.now?.()??Date.now())))}}}let Z=!1;const tt=Object.freeze([]);let et=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const st=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function rt(t,e){try{t?.(e)}catch(t){h(t)}}function it(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function ot(t,e){return new nt(t,e)}class nt{get address(){return this._address??=this._parent?`${this._parent.address}/${B(this.id)}`:B(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=et.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?{...st,...e}:st,{clock:r,logger:i,parent:o,syncSnapshot:n,id:c,registryKey:a,inspect:h}=s;var u;this.system=o?o.system:s._systemRef?.current??function(t,e){return new Y(t,e)}(this,{clock:r,logger:i,snapshot:s.snapshot,createActorRef:ot}),o||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system),h&&!o&&this.system.inspect(C(h)),s.onRejectedEvent&&!o&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(u=this.system)._identity.systemId}:${u._identity.nextSessionId++}`,this.id=X(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=n,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(d)this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(d,this._actorScope):d);else if(e?._inert);else{const[t,e]=k(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=d&&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=>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===et.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=Z;try{Z=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==et.Stopped&&this._recoverOrError(t)})}finally{Z=e}};this._processingStatus!==et.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,K(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]=k(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),it(r,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??tt)rt(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??tt,actions:this._collectedActions??tt,sent:this._collectedSent??tt,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 it(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=C(t,e,s);if(this._processingStatus!==et.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":rt(r.complete);break;case"error":{const t=this._snapshot.error;r.error?(r.passive||(this._errorObserved=!0),rt(r.error,t)):h(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 o=C(s,r,i);let n=t(this.getSnapshot());return this.subscribe({next:s=>{const r=t(s);e(n,r)||(n=r,o.next?.(r))},error:o.error,complete:o.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===et.Running)return this;if(this._processingStatus===et.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=et.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,a(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,a(this.options.input)):(function(t,e,s){const r=R.get(t),i=L(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 Object.values(t)){const t=e&&void 0!==r.startedAt?Math.min(r.delay,Math.max(0,r.startedAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,r.id,t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){const e=this._snapshot;let s,i;try{s=k(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){i={err:t}}if(i)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(i.err)||this._inspectTransition(this._snapshot,t));if(!s)return;let o=this._snapshot;try{const[r,i]=s;r!==e||i.length||!("machine"in e)||t.type.startsWith("xstate.")||this._reportUnhandledEvent(t),o=r,this._setSnapshot(o),it(i,this._actorScope),this.update(o,t)}catch(s){return void(this._recoverOrError(s,o,e)||this._inspectTransition(this._snapshot,t))}t.type===r&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){rt(()=>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)rt(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===et.Stopped?this:(this.mailbox?.clear(),this._processingStatus===et.NotStarted?(this._processingStatus=et.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??tt)rt(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||h(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(h)}catch(i){h(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),rt(i,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);var r,i,o;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(r=this.id,i=t,o=this.sessionId,{type:"xstate.error.actor",error:i,actorId:r,sessionId:o}))}_stopProcedure(){this._processingStatus===et.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=et.Stopped,this.system._unregister(this))}_send(t){if(this._processingStatus===et.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:"actorRef",id:this.id,address:this.address,src:"string"==typeof this.src?this.src:void 0}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[u](){return this}getSnapshot(){return this._snapshot}}function ct(t,e){const s=t.check(e);if(s)throw s}const at=new WeakMap;function ht(t,e,s){const r=function(t){let e=at.get(t);return e||(e=new Map,at.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 ut(t){const e=(e,i,a)=>{if("active"!==e.status)return[e,[]];if(i.type===r)return[{...e,status:"stopped",input:void 0},[S("xstate.logic.cleanup",()=>function(t){const e=at.get(t);if(!e)return;let s;at.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[{...e,effects:{...e.effects,[i.key]:{status:"active"}}},[]];if(i.type===o)return[{...e,effects:{...e.effects,[i.key]:{status:"done",output:i.output}}},[]];if(i.type===n)return[{...e,effects:{...e.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:m,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(a,t))},sendBack:t=>{const e=a.self._parent;e&&h.push(w(a,e,t))},raise:t=>{h.push(w(a,a.self,t))},effect:(t,r)=>{if("string"==typeof t)return void((t,r)=>{const o=e.effects&&Object.prototype.hasOwnProperty.call(e.effects,t)?e.effects[t]:void 0;(!o||i.type===s&&"active"===o.status)&&(h.push(S("xstate.logic.effect",(e=a.self.system)=>ht(a.self,t,()=>r(e)),{key:t})),u[t]={status:"active"})})(t,r);const o=t;h.push(S("xstate.logic.effect",(t=a.self.system)=>ht(a.self,void 0,()=>o(t))))}},p=t.run({context:e.context,event:i,input:e.input,system:a.system,self:a.self,emit:a.emit},d),l={...e,...p||{}};return("context"in e||void 0!==p?.context)&&(l.context=p?.context??e.context),(p?.effects||Object.keys(u).length)&&(l.effects={...e.effects,...p?.effects,...u}),k(a,e,[l,h])},i=(s,r,i)=>{if(t.validator){const e=i.self._lastSourceRef,o=e?"actor":"external",n=t.validator.check({kind:"event",logic:h,event:r,eventOrigin:o});if(n)return[s,[b(i,e,r,"invalidEvent",{issues:n.issues,error:n})]]}const o=e(s,r,i);return t.validator&&ct(t.validator,{kind:"result",logic:h,snapshot:o[0],effects:o[1]}),o},h={id:t.id,config:t,validator:t.validator,transition:i,start:(t,e,s)=>{if(!s?.restored)return;const[r,o]=i(t,a(t.input),e);Object.assign(t,r);for(const t of o)e.actionExecutor(t)},initialTransition:(e,s)=>{t.validator&&ct(t.validator,{kind:"input",logic:h,input:e});const r=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),o={status:"active",output:void 0,error:void 0,input:e};return void 0!==r&&(o.context=r),i({...o},a(e),s)},getInitialSnapshot:(t,e)=>h.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return h}const dt=new WeakMap;const pt="xstate.observable.next",lt="xstate.observable.error",ft="xstate.observable.complete";const _t="xstate.async.resolve",vt="xstate.async.reject";class yt extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const mt=ut({context:void 0,run:()=>{}});t.TimeoutError=yt,t.createAsyncLogic=function(t){const e=t;return ut({id:e.id,validator:e.validator,schemas:e.schemas,context:void 0,run:({event:t,input:r,self:i,system:o},n)=>{switch(t.type){case _t:{const e=t.data??t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case vt:{const e=t.data??t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===s)return n.effect((t=o)=>{const s=i,n=e=>{t.sendEvent(s,s,e)},c=new AbortController,a=e.timeout,h=O(a),u=void 0===h?void 0:o._clock.setTimeout(()=>{"active"===i.getSnapshot().status&&(c.abort(),n({type:vt,data:new yt(a)}))},h),d=()=>{void 0!==u&&o._clock.clearTimeout(u)},p=()=>Promise.resolve(e.run({input:r,system:o,self:i,signal:c.signal},{emit:e=>{t.emitEvent(s,e)},step:(e,r)=>t.runStep?Promise.resolve(t.runStep(s,e,r)):U(s,e,r,n)}));return(t.runLogic?Promise.resolve(t.runLogic(s,p)):p()).then(t=>{d(),"active"===i.getSnapshot().status&&n({type:_t,data:t})},t=>{d(),"active"===i.getSnapshot().status&&n({type:vt,data:t})}),()=>{c.abort(),d()}}),{effects:{async:{status:"active"}}}}})},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return ut({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:r,input:i,self:o,system:n}=t,c=t.emit,a=dt.get(o);a?.receivers?.forEach(t=>t(r)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return dt.set(o,t),t.dispose=e({input:i,system:n,self:o,sendBack:t=>{if("stopped"===o.getSnapshot().status)return;const e=o._parent;e&&n._relay(o,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{dt.delete(o),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return function(t,...[e]){return new nt(t,e)}(mt)},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.validator,i={config:t,validator:s,transition:(t,e,s)=>{if("active"!==t.status)return[t,[]];switch(e.type){case lt:return k(s,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case ft:return k(s,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case r:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{s&&ct(s,{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:lt,data:t})},complete:()=>{r._relay(s,s,{type:ft})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return i},t.createListenerLogic=f,t.createLogic=ut,t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run,r="function"==typeof t?void 0:t.schemas;return ut({validator:"function"==typeof t?void 0:t.validator,schemas:r,context:void 0,run:(t,r)=>{const{event:i,input:o,self:n,system:c}=t;switch(i.type){case pt:return{context:i.data};case lt:return{status:"error",error:i.data,input:void 0,effects:{observable:{status:"error",error:i.data}}};case ft:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}i.type===s&&r.effect((t=c)=>{const s=n,r=e=>{t.sendEvent(s,s,e)},i=e({input:o,system:c,self:n,emit:e=>{t.emitEvent(s,e)}}).subscribe({next:t=>{r({type:pt,data:t})},error:t=>{r({type:lt,data:t})},complete:()=>{r({type:ft})}});return()=>i.unsubscribe()})}})},t.createSubscriptionLogic=v,t.listenerLogic=_,t.subscriptionLogic=y,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";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",r="@xstate.stop",i="@xstate.terminate",o="xstate.logic.effect.resolve",n="xstate.logic.effect.reject",c="xstate.logic.effect.start";function a(t){return{type:s,input:t}}function h(t){setTimeout(()=>{throw t})}const u="function"==typeof Symbol&&Symbol.observable||"@@observable";const d=Symbol("xstate.systemLogicMetadata"),p=new WeakMap;function l(t,e){const s=(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 o=t(e.input,{self:s,system:r});if(!o)return;let n,c=!1;const a=()=>{c||(c=!0,o.unsubscribe(),n?.unsubscribe())},h=s._parent;h&&(n=h.subscribe({complete:a,error:a})),p.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===r?(p.get(s)?.unsubscribe(),p.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return Object.defineProperty(i,d,{value:{kind:e}}),i}function f(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function _(){return l(({actor:t,eventType:e,mapper:s},{self:r,system:i})=>{const o="*"!==e&&e.endsWith(".*");return t.on(o?"*":e,t=>{o&&!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)||f(r,i,()=>s(t))})},"xstate.listener")}const v=_();function y(){return l(({actor:t,mappers:e},{self:s,system:r})=>{const{done:i,error:o,snapshot:n}=e;return t.subscribe({next:t=>{"done"===t.status&&i?f(s,r,()=>i(t.output)):"error"===t.status&&o?f(s,r,()=>o(t.error)):"active"===t.status&&n&&f(s,r,()=>n(t))},error:t=>{o&&f(s,r,()=>o(t))},complete:()=>{}})},"xstate.subscription")}const m=y();function g(t=this.source.system){return t.emitEvent(this.source,this.event)}function b(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function S(t,e,s,r,i){return{kind:"builtin",type:"@xstate.deadLetter",exec:b,source:e,target:t.self,event:s,reason:r,detail:i,params:void 0,args:[]}}function x(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function A(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 w(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,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function E(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:w,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function k(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},r=[t.self,s];return{kind:"builtin",exec:A,type:i,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:r}}function T(t,e,[s,r]){const o="done"===s.status||"error"===s.status,n="done"===e?.status||"error"===e?.status,c=r.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===i);return!o||n||c?[s,r]:[s,[...r,k(t,s)]]}const I=()=>{},O=()=>({});function R(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:o,days:n,hours:c,minutes:a,seconds:h}=i.groups;if(!(o||n||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(o)*24*60*60*1e3+24*u(n)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)}!function(t,e){const s=(t,...s)=>{e(t,...s)};Object.assign(s,{cancel:I,emit:I,log:I,raise:I,spawn:O,sendTo:I,stop:I,listen:O,subscribeTo:O,...t})}({},I);const M=new WeakMap,j=new WeakMap,P=new Map;function L(t){t._snapshotVersion++}function $(t){return t._snapshotVersion}function K(t){const e=M.get(t);if(e)return e;const s=j.get(t);if(!s)return;const r=s();return M.set(t,r),j.delete(t),r}function C(t,e,s=e.system,r){j.delete(t);const i=$(s),o=r?K(r):void 0,n=o?.actor===e?o:K(t);if(n?.actor===e&&n.systemState.sourceSystem===s&&n.systemState.sourceVersion===i)return void M.set(t,n);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)??P:t.keyedActors}(s);let u=h.size?new Map(h):P;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===P&&(u=new Map),u.set(t,e))}M.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function z(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}:{}}}const U=new WeakMap;async function W(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=U.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,l=U.get(t);l||(l=new Map,U.set(t,l)),l.set(e,d);const f=()=>{p?.unsubscribe(),l.delete(e),l.size||U.delete(t)};return d.then(f,f),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:o,key:e,output:i}),h(i))}catch(s){"active"===t.getSnapshot().status&&r({type:n,key:e,error:s}),u(s)}})().catch(u),d}function D(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)}let V,N=0;const H=new Error("Transition effect"),q=[];function B(){return V??=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)}`}(),`${V}:${(N++).toString(36)}`}function F(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function J(t,e){return`${t?t.address:""}|${e}`}function X(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},L(t))}function G(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?X(t,J(s?.parent,r.prefix),r.index+1):s?.parent||X(t,J(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&&"(machine)"!==e?e:"x"}(s?.src),i=J(s?.parent,r),o=t._snapshot._nextActorIds[i]??0;return X(t,i,o+1),s?.parent||"x"===r||0!==o?`${r}:${o}`:r}const Q=Object.freeze({});function Y(t,e){return`${t.sessionId}.${e}`}class Z{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:B(),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??Q,_nextActorIds:{}}}_recordSent(t,e,s,r,i){if(!this._inspectionObservers?.size||!t)return;const o=t;(o._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:i})}schedule(t,e,s){const r=Y(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const i=t.getSnapshot()?.timers?.[e];if(i){const r="self"===i.target?t:i.target;this._recordSent(t,r,i.event,s,e)}const o=this._clock.now?.()??Date.now(),n={source:t,delay:s,id:e,scheduledAt:o,dueAt:o+s},c=Y(t,e);this._snapshot._scheduledTimers===Q&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[c]=n,L(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[c],delete this._snapshot._scheduledTimers[c],L(this),this._deliver(t,t,{type:"xstate.timer",id:e})},s);(this._timerMap??={})[c]=a}cancel(t,e){const s=Y(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==Q&&delete this._snapshot._scheduledTimers[s],L(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.id)}}_deliver(t,e,s){!function(t,e,s){if(D(t,e,s))return;const r=e;r._lastSourceRef=t,r._send(s)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),L(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&&L(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&&L(this)}inspect(t){const e=z(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)}}}_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(D(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 o=this._rejectionListeners;if(o?.size){const n={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[...o])try{t(n)}catch(t){h(t)}}const n=this.runtime?.deadLetter;if(n)return n(t,e,s,r,i)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):W(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=t.getSnapshot()?.timers?.[e];if(i){const r="self"===i.target?t:i.target;this._recordSent(t,r,i.event,s,e)}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(q.length&&q.includes(e))throw H;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,id:o}=t[s];this.scheduleTimer(r,o,Math.max(0,i-(this._clock.now?.()??Date.now())))}}}let tt=!1;const et=Object.freeze([]);let st=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const rt=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function it(t,e){try{t?.(e)}catch(t){h(t)}}function ot(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function nt(t,e){return new ct(t,e)}class ct{get address(){return this._address??=this._parent?`${this._parent.address}/${F(this.id)}`:F(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=st.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?{...rt,...e}:rt,{clock:r,logger:i,parent:o,syncSnapshot:n,id:c,registryKey:a,inspect:h}=s;var u;this.system=o?o.system:s._systemRef?.current??function(t,e){return new Z(t,e)}(this,{clock:r,logger:i,snapshot:s.snapshot,createActorRef:nt}),o||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system),h&&!o&&this.system.inspect(z(h)),s.onRejectedEvent&&!o&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(u=this.system)._identity.systemId}:${u._identity.nextSessionId++}`,this.id=G(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=n,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(d)this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(d,this._actorScope):d);else if(e?._inert);else{const[t,e]=T(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=d&&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=>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===st.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=tt;try{tt=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==st.Stopped&&this._recoverOrError(t)})}finally{tt=e}};this._processingStatus!==st.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,C(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]=T(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),ot(r,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??et)it(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??et,actions:this._collectedActions??et,sent:this._collectedSent??et,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 ot(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=z(t,e,s);if(this._processingStatus!==st.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":it(r.complete);break;case"error":{const t=this._snapshot.error;r.error?(r.passive||(this._errorObserved=!0),it(r.error,t)):h(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 o=z(s,r,i);let n=t(this.getSnapshot());return this.subscribe({next:s=>{const r=t(s);e(n,r)||(n=r,o.next?.(r))},error:o.error,complete:o.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===st.Running)return this;if(this._processingStatus===st.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=st.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,a(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,a(this.options.input)):(function(t,e,s){const r=M.get(t),i=$(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 Object.values(t)){const t=e&&void 0!==r.startedAt?Math.min(r.delay,Math.max(0,r.startedAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,r.id,t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){const e=this._snapshot;let s,i;try{s=T(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){i={err:t}}if(i)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(i.err)||this._inspectTransition(this._snapshot,t));if(!s)return;let o=this._snapshot;try{const[r,i]=s;r!==e||i.length||!("machine"in e)||t.type.startsWith("xstate.")||this._reportUnhandledEvent(t),o=r,this._setSnapshot(o),ot(i,this._actorScope),this.update(o,t)}catch(s){return void(this._recoverOrError(s,o,e)||this._inspectTransition(this._snapshot,t))}t.type===r&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){it(()=>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)it(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===st.Stopped?this:(this.mailbox?.clear(),this._processingStatus===st.NotStarted?(this._processingStatus=st.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??et)it(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||h(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(h)}catch(i){h(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),it(i,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);var r,i,o;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(r=this.id,i=t,o=this.sessionId,{type:"xstate.error.actor",error:i,actorId:r,sessionId:o}))}_stopProcedure(){this._processingStatus===st.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=st.Stopped,this.system._unregister(this))}_send(t){if(this._processingStatus===st.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:"actorRef",id:this.id,address:this.address,src:"string"==typeof this.src?this.src:void 0}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[u](){return this}getSnapshot(){return this._snapshot}}function at(t,e){const s=t.check(e);if(s)throw s}const ht=new WeakMap;function ut(t,e,s){const r=function(t){let e=ht.get(t);return e||(e=new Map,ht.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 dt(t){const e=(e,i,a)=>{if("active"!==e.status)return[e,[]];if(i.type===r)return[{...e,status:"stopped",input:void 0},[x("xstate.logic.cleanup",()=>function(t){const e=ht.get(t);if(!e)return;let s;ht.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[{...e,effects:{...e.effects,[i.key]:{status:"active"}}},[]];if(i.type===o)return[{...e,effects:{...e.effects,[i.key]:{status:"done",output:i.output}}},[]];if(i.type===n)return[{...e,effects:{...e.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:g,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(a,t))},sendBack:t=>{const e=a.self._parent;e&&h.push(E(a,e,t))},raise:t=>{h.push(E(a,a.self,t))},effect:(t,r)=>{if("string"==typeof t)return void((t,r)=>{const o=e.effects&&Object.prototype.hasOwnProperty.call(e.effects,t)?e.effects[t]:void 0;(!o||i.type===s&&"active"===o.status)&&(h.push(x("xstate.logic.effect",(e=a.self.system)=>ut(a.self,t,()=>r(e)),{key:t})),u[t]={status:"active"})})(t,r);const o=t;h.push(x("xstate.logic.effect",(t=a.self.system)=>ut(a.self,void 0,()=>o(t))))}},p=t.run({context:e.context,event:i,input:e.input,system:a.system,self:a.self,emit:a.emit},d),l={...e,...p||{}};return("context"in e||void 0!==p?.context)&&(l.context=p?.context??e.context),(p?.effects||Object.keys(u).length)&&(l.effects={...e.effects,...p?.effects,...u}),T(a,e,[l,h])},i=(s,r,i)=>{if(t.validator){const e=i.self._lastSourceRef,o=e?"actor":"external",n=t.validator.check({kind:"event",logic:h,event:r,eventOrigin:o});if(n)return[s,[S(i,e,r,"invalidEvent",{issues:n.issues,error:n})]]}const o=e(s,r,i);return t.validator&&at(t.validator,{kind:"result",logic:h,snapshot:o[0],effects:o[1]}),o},h={id:t.id,config:t,validator:t.validator,transition:i,start:(t,e,s)=>{if(!s?.restored)return;const[r,o]=i(t,a(t.input),e);Object.assign(t,r);for(const t of o)e.actionExecutor(t)},initialTransition:(e,s)=>{t.validator&&at(t.validator,{kind:"input",logic:h,input:e});const r=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),o={status:"active",output:void 0,error:void 0,input:e};return void 0!==r&&(o.context=r),i({...o},a(e),s)},getInitialSnapshot:(t,e)=>h.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return h}const pt=new WeakMap;const lt="xstate.observable.next",ft="xstate.observable.error",_t="xstate.observable.complete";const vt="xstate.async.resolve",yt="xstate.async.reject";class mt extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const gt=dt({context:void 0,run:()=>{}});t.TimeoutError=mt,t.createAsyncLogic=function(t){const e=t,r=dt({id:e.id,validator:e.validator,schemas:e.schemas,context:void 0,run:({event:t,input:r,self:i,system:o},n)=>{switch(t.type){case vt:{const e=t.data??t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case yt:{const e=t.data??t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===s)return n.effect((t=o)=>{const s=i,n=e=>{t.sendEvent(s,s,e)},c=new AbortController,a=e.timeout,h=R(a),u=void 0===h?void 0:o._clock.setTimeout(()=>{"active"===i.getSnapshot().status&&(c.abort(),n({type:yt,data:new mt(a)}))},h),d=()=>{void 0!==u&&o._clock.clearTimeout(u)},p=()=>Promise.resolve(e.run({input:r,system:o,self:i,signal:c.signal},{emit:e=>{t.emitEvent(s,e)},step:(e,r)=>t.runStep?Promise.resolve(t.runStep(s,e,r)):W(s,e,r,n)}));return(t.runLogic?Promise.resolve(t.runLogic(s,p)):p()).then(t=>{d(),"active"===i.getSnapshot().status&&n({type:vt,data:t})},t=>{d(),"active"===i.getSnapshot().status&&n({type:yt,data:t})}),()=>{c.abort(),d()}}),{effects:{async:{status:"active"}}}}});return Object.defineProperty(r,d,{value:{kind:"async",timeout:e.timeout}}),r},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return dt({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:r,input:i,self:o,system:n}=t,c=t.emit,a=pt.get(o);a?.receivers?.forEach(t=>t(r)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return pt.set(o,t),t.dispose=e({input:i,system:n,self:o,sendBack:t=>{if("stopped"===o.getSnapshot().status)return;const e=o._parent;e&&n._relay(o,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{pt.delete(o),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return function(t,...[e]){return new ct(t,e)}(gt)},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.validator,i={config:t,validator:s,transition:(t,e,s)=>{if("active"!==t.status)return[t,[]];switch(e.type){case ft:return T(s,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case _t:return T(s,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case r:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{s&&at(s,{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:ft,data:t})},complete:()=>{r._relay(s,s,{type:_t})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return i},t.createListenerLogic=_,t.createLogic=dt,t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run,r="function"==typeof t?void 0:t.schemas;return dt({validator:"function"==typeof t?void 0:t.validator,schemas:r,context:void 0,run:(t,r)=>{const{event:i,input:o,self:n,system:c}=t;switch(i.type){case lt:return{context:i.data};case ft:return{status:"error",error:i.data,input:void 0,effects:{observable:{status:"error",error:i.data}}};case _t:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}i.type===s&&r.effect((t=c)=>{const s=n,r=e=>{t.sendEvent(s,s,e)},i=e({input:o,system:c,self:n,emit:e=>{t.emitEvent(s,e)}}).subscribe({next:t=>{r({type:lt,data:t})},error:t=>{r({type:ft,data:t})},complete:()=>{r({type:_t})}});return()=>i.unsubscribe()})}})},t.createSubscriptionLogic=y,t.listenerLogic=v,t.subscriptionLogic=m,Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate-actors.umd.min.js.map