xstate 5.0.0-beta.39 → 5.0.0-beta.41

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 (45) hide show
  1. package/actions/dist/xstate-actions.cjs.js +3 -3
  2. package/actions/dist/xstate-actions.development.cjs.js +3 -3
  3. package/actions/dist/xstate-actions.development.esm.js +3 -3
  4. package/actions/dist/xstate-actions.esm.js +3 -3
  5. package/actions/dist/xstate-actions.umd.min.js +1 -1
  6. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  7. package/actors/dist/xstate-actors.cjs.js +2 -2
  8. package/actors/dist/xstate-actors.development.cjs.js +2 -2
  9. package/actors/dist/xstate-actors.development.esm.js +2 -2
  10. package/actors/dist/xstate-actors.esm.js +2 -2
  11. package/actors/dist/xstate-actors.umd.min.js +1 -1
  12. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  13. package/dist/declarations/src/State.d.ts +1 -1
  14. package/dist/declarations/src/StateMachine.d.ts +1 -1
  15. package/dist/declarations/src/actors/callback.d.ts +1 -1
  16. package/dist/declarations/src/index.d.ts +2 -2
  17. package/dist/declarations/src/interpreter.d.ts +2 -10
  18. package/dist/declarations/src/system.d.ts +7 -3
  19. package/dist/declarations/src/types.d.ts +4 -9
  20. package/dist/{interpreter-1e8c1c0c.esm.js → interpreter-480db258.esm.js} +28 -33
  21. package/dist/{interpreter-03a5c3f5.development.cjs.js → interpreter-70ed981b.development.cjs.js} +28 -34
  22. package/dist/{interpreter-70cd9217.development.esm.js → interpreter-936da690.development.esm.js} +28 -33
  23. package/dist/{interpreter-5dfcd203.cjs.js → interpreter-fb2829f1.cjs.js} +28 -34
  24. package/dist/{raise-17cb3d9d.development.cjs.js → raise-5ab465ed.development.cjs.js} +9 -9
  25. package/dist/{raise-62de3670.esm.js → raise-9d6921da.esm.js} +8 -8
  26. package/dist/{raise-291d2181.cjs.js → raise-beae3fd3.cjs.js} +8 -8
  27. package/dist/{raise-e044f460.development.esm.js → raise-f757be00.development.esm.js} +9 -9
  28. package/dist/{send-1249d4ac.esm.js → send-a931d1b8.esm.js} +4 -5
  29. package/dist/{send-f1a2a827.development.esm.js → send-b26e3812.development.esm.js} +4 -5
  30. package/dist/{send-af152aca.cjs.js → send-ca5f706c.cjs.js} +4 -5
  31. package/dist/{send-33433787.development.cjs.js → send-fb87a01a.development.cjs.js} +4 -5
  32. package/dist/xstate.cjs.js +8 -10
  33. package/dist/xstate.cjs.mjs +0 -2
  34. package/dist/xstate.development.cjs.js +8 -10
  35. package/dist/xstate.development.cjs.mjs +0 -2
  36. package/dist/xstate.development.esm.js +11 -11
  37. package/dist/xstate.esm.js +11 -11
  38. package/dist/xstate.umd.min.js +1 -1
  39. package/dist/xstate.umd.min.js.map +1 -1
  40. package/guards/dist/xstate-guards.cjs.js +2 -2
  41. package/guards/dist/xstate-guards.development.cjs.js +2 -2
  42. package/guards/dist/xstate-guards.development.esm.js +2 -2
  43. package/guards/dist/xstate-guards.esm.js +2 -2
  44. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  45. package/package.json +1 -1
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var interpreter = require('../../dist/interpreter-5dfcd203.cjs.js');
5
+ var interpreter = require('../../dist/interpreter-fb2829f1.cjs.js');
6
6
  require('../../dev/dist/xstate-dev.cjs.js');
7
7
 
8
8
  /**
@@ -49,7 +49,7 @@ function fromTransition(transition, initialContext) {
49
49
  * - Send events to the parent actor via the `sendBack` function
50
50
  *
51
51
  * Callback actors are a bit different from other actors in that they:
52
- * - Do not work with `onDone` or `onError`
52
+ * - Do not work with `onDone`
53
53
  * - Do not produce a snapshot using `.getSnapshot()`
54
54
  * - Do not emit values when used with `.subscribe()`
55
55
  * - Can not be stopped with `.stop()`
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var interpreter = require('../../dist/interpreter-03a5c3f5.development.cjs.js');
5
+ var interpreter = require('../../dist/interpreter-70ed981b.development.cjs.js');
6
6
  require('../../dev/dist/xstate-dev.development.cjs.js');
7
7
 
8
8
  /**
@@ -49,7 +49,7 @@ function fromTransition(transition, initialContext) {
49
49
  * - Send events to the parent actor via the `sendBack` function
50
50
  *
51
51
  * Callback actors are a bit different from other actors in that they:
52
- * - Do not work with `onDone` or `onError`
52
+ * - Do not work with `onDone`
53
53
  * - Do not produce a snapshot using `.getSnapshot()`
54
54
  * - Do not emit values when used with `.subscribe()`
55
55
  * - Can not be stopped with `.stop()`
@@ -1,4 +1,4 @@
1
- import { X as XSTATE_STOP, d as createActor } from '../../dist/interpreter-70cd9217.development.esm.js';
1
+ import { X as XSTATE_STOP, d as createActor } from '../../dist/interpreter-936da690.development.esm.js';
2
2
  import '../../dev/dist/xstate-dev.development.esm.js';
3
3
 
4
4
  /**
@@ -45,7 +45,7 @@ function fromTransition(transition, initialContext) {
45
45
  * - Send events to the parent actor via the `sendBack` function
46
46
  *
47
47
  * Callback actors are a bit different from other actors in that they:
48
- * - Do not work with `onDone` or `onError`
48
+ * - Do not work with `onDone`
49
49
  * - Do not produce a snapshot using `.getSnapshot()`
50
50
  * - Do not emit values when used with `.subscribe()`
51
51
  * - Can not be stopped with `.stop()`
@@ -1,4 +1,4 @@
1
- import { X as XSTATE_STOP, d as createActor } from '../../dist/interpreter-1e8c1c0c.esm.js';
1
+ import { X as XSTATE_STOP, d as createActor } from '../../dist/interpreter-480db258.esm.js';
2
2
  import '../../dev/dist/xstate-dev.esm.js';
3
3
 
4
4
  /**
@@ -45,7 +45,7 @@ function fromTransition(transition, initialContext) {
45
45
  * - Send events to the parent actor via the `sendBack` function
46
46
  *
47
47
  * Callback actors are a bit different from other actors in that they:
48
- * - Do not work with `onDone` or `onError`
48
+ * - Do not work with `onDone`
49
49
  * - Do not produce a snapshot using `.getSnapshot()`
50
50
  * - Do not emit values when used with `.subscribe()`
51
51
  * - Can not be stopped with `.stop()`
@@ -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.stop";function i(t,e){return{type:`xstate.error.actor.${t}`,data:e}}function r(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const o=t=>{const e=r();e&&e.register(t)};function n(t){setTimeout((()=>{throw t}))}const a="function"==typeof Symbol&&Symbol.observable||"@@observable";let c=0;function h(t,e,s){const i="object"==typeof t,r=i?t:void 0;return{next:(i?t.next:t)?.bind(r),error:(i?t.error:e)?.bind(r),complete:(i?t.complete:s)?.bind(r)}}let u=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const d={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class p{constructor(t,s){this.logic=t,this._state=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new e(this._process.bind(this)),this.delayedEventsMap={},this.observers=new Set,this.logger=void 0,this.status=u.NotStarted,this._parent=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const i={...d,...s},{clock:r,logger:o,parent:n,id:a,systemId:p,inspect:l}=i;this.system=n?.system??function(t){const e=new Map,s=new Map,i=new WeakMap,r=new Set,o={_bookId:()=>"x:"+c++,_register:(t,s)=>(e.set(t,s),t),_unregister:t=>{e.delete(t.sessionId);const r=i.get(t);void 0!==r&&(s.delete(r),i.delete(t))},get:t=>s.get(t),_set:(t,e)=>{const r=s.get(t);if(r&&r!==e)throw new Error(`Actor with system ID '${t}' already exists.`);s.set(t,e),i.set(e,t)},inspect:t=>{r.add(t)},_sendInspectionEvent:e=>{const s={...e,rootId:t.sessionId};r.forEach((t=>t.next?.(s)))},_relay:(t,e,s)=>{o._sendInspectionEvent({type:"@xstate.event",sourceRef:t,targetRef:e,event:s}),e._send(s)}};return o}(this),l&&!n&&this.system.inspect(h(l)),this.sessionId=this.system._bookId(),this.id=a??this.sessionId,this.logger=o,this.clock=r,this._parent=n,this.options=i,this.src=i.src,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),this._initState(),p&&"active"===this._state.status&&(this._systemId=p,this.system._set(p,this))}_initState(){this._state=this.options.state?this.logic.restoreState?this.logic.restoreState(this.options.state,this._actorScope):this.options.state:this.logic.getInitialState(this._actorScope,this.options?.input)}update(t,e){let s;for(this._state=t;s=this._deferred.shift();)s();for(const e of this.observers)try{e.next?.(t)}catch(t){n(t)}switch(this._state.status){case"done":this._stopProcedure(),this._complete(),this._doneEvent=(r=this.id,o=this._state.output,{type:`xstate.done.actor.${r}`,output:o}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._stopProcedure(),this._error(this._state.error),this._parent&&this.system._relay(this,this._parent,i(this.id,this._state.error))}var r,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){const i=h(t,e,s);if(this.status!==u.Stopped)this.observers.add(i);else try{i.complete?.()}catch(t){n(t)}return{unsubscribe:()=>{this.observers.delete(i)}}}start(){if(this.status===u.Running)return this;this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this.status=u.Running;const t={type:"xstate.init",input:this.options.input};this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,targetRef:this,event:t});switch(this._state.status){case"done":this.update(this._state,t);case"error":return this}if(this.logic.start)try{this.logic.start(this._state,this._actorScope)}catch(t){return this._stopProcedure(),this._error(t),this._parent?.send(i(this.id,t)),this}return this.update(this._state,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,r;try{e=this.logic.transition(this._state,t,this._actorScope)}catch(t){r={err:t}}if(r){const{err:t}=r;return this._stopProcedure(),this._error(t),void this._parent?.send(i(this.id,t))}this.update(e,t),t.type===s&&(this._stopProcedure(),this._complete())}_stop(){return this.status===u.Stopped?this:(this.mailbox.clear(),this.status===u.NotStarted?(this.status=u.Stopped,this):(this.mailbox.enqueue({type:s}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){n(t)}this.observers.clear()}_error(t){if(!this.observers.size)return void(this._parent||n(t));let e=!1;for(const s of this.observers){const i=s.error;e||=!i;try{i?.(t)}catch(t){n(t)}}this.observers.clear(),e&&n(t)}_stopProcedure(){if(this.status!==u.Running)return this;for(const t of Object.keys(this.delayedEventsMap))this.clock.clearTimeout(this.delayedEventsMap[t]);return this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this.status=u.Stopped,this.system._unregister(this),this}_send(t){this.status!==u.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}delaySend(t){const{event:e,id:s,delay:i}=t,r=this.clock.setTimeout((()=>{this.system._relay(this,t.to??this,e)}),i);s&&(this.delayedEventsMap[s]=r)}cancel(t){this.clock.clearTimeout(this.delayedEventsMap[t]),delete this.delayedEventsMap[t]}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:o)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedState(){return this.logic.getPersistedState(this._state)}[a](){return this}getSnapshot(){return this._state}}function l(t,e){return{config:t,transition:(e,s,i)=>({...e,context:t(e.context,s,i)}),getInitialState:(t,s)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof e?e({input:s}):e}),getPersistedState:t=>t,restoreState:t=>t}}const _="$$xstate.resolve",v="$$xstate.reject";const f=l((t=>{}),void 0);t.createEmptyActor=function(){return new p(f,t);var t},t.fromCallback=function(t){return{config:t,start:(t,{self:e,system:s})=>{s._relay(e,e,{type:"xstate.create"})},transition:(e,i,{self:r,system:o})=>{if("xstate.create"===i.type){const s=t=>{"stopped"!==e.status&&r._parent&&o._relay(r,r._parent,t)},i=t=>{e._receivers.add(t)};return e._dispose=t({input:e.input,system:o,self:r,sendBack:s,receive:i}),e}return i.type===s?("function"==typeof(e={...e,status:"stopped",error:void 0})._dispose&&e._dispose(),e):(e._receivers.forEach((t=>t(i))),e)},getInitialState:(t,e)=>({status:"active",output:void 0,error:void 0,input:e,_receivers:new Set,_dispose:void 0}),getPersistedState:({_dispose:t,_receivers:e,...s})=>s,restoreState:t=>({_receivers:new Set,_dispose:void 0,...t})}},t.fromEventObservable=function(t){const e="$$xstate.error",i="$$xstate.complete";return{config:t,transition:(t,r)=>{if("active"!==t.status)return t;switch(r.type){case e:return{...t,status:"error",error:r.data,input:void 0,_subscription:void 0};case i:return{...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}},getInitialState:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(s,{self:r,system:o})=>{"done"!==s.status&&(s._subscription=t({input:s.input,system:o,self:r}).subscribe({next:t=>{r._parent&&o._relay(r,r._parent,t)},error:t=>{o._relay(r,r,{type:e,data:t})},complete:()=>{o._relay(r,r,{type:i})}}))},getPersistedState:({_subscription:t,...e})=>e,restoreState:t=>({...t,_subscription:void 0})}},t.fromObservable=function(t){const e="$$xstate.next",i="$$xstate.error",r="$$xstate.complete";return{config:t,transition:(t,o,{self:n,id:a,defer:c,system:h})=>{if("active"!==t.status)return t;switch(o.type){case e:return{...t,context:o.data};case i:return{...t,status:"error",error:o.data,input:void 0,_subscription:void 0};case r:return{...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}},getInitialState:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(s,{self:o,system:n})=>{"done"!==s.status&&(s._subscription=t({input:s.input,system:n,self:o}).subscribe({next:t=>{n._relay(o,o,{type:e,data:t})},error:t=>{n._relay(o,o,{type:i,data:t})},complete:()=>{n._relay(o,o,{type:r})}}))},getPersistedState:({_subscription:t,...e})=>e,restoreState:t=>({...t,_subscription:void 0})}},t.fromPromise=function(t){return{config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case _:{const s=e.data;return{...t,status:"done",output:s,input:void 0}}case v:return{...t,status:"error",error:e.data,input:void 0};case s:return{...t,status:"stopped",input:void 0};default:return t}},start:(e,{self:s,system:i})=>{if("active"!==e.status)return;Promise.resolve(t({input:e.input,system:i,self:s})).then((t=>{"active"===s.getSnapshot().status&&i._relay(s,s,{type:_,data:t})}),(t=>{"active"===s.getSnapshot().status&&i._relay(s,s,{type:v,data:t})}))},getInitialState:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedState:t=>t,restoreState:t=>t}},t.fromTransition=l,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.stop";function i(t,e){return{type:`xstate.error.actor.${t}`,data:e}}function r(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const o=t=>{const e=r();e&&e.register(t)};function n(t){setTimeout((()=>{throw t}))}const a="function"==typeof Symbol&&Symbol.observable||"@@observable";let c=0;function h(t,e,s){const i="object"==typeof t,r=i?t:void 0;return{next:(i?t.next:t)?.bind(r),error:(i?t.error:e)?.bind(r),complete:(i?t.complete:s)?.bind(r)}}let u=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const d={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class p{constructor(t,s){this.logic=t,this._state=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new e(this._process.bind(this)),this.delayedEventsMap={},this.observers=new Set,this.logger=void 0,this._processingStatus=u.NotStarted,this._parent=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const i={...d,...s},{clock:r,logger:o,parent:n,id:a,systemId:p,inspect:_}=i;this.system=n?.system??function(t){const e=new Map,s=new Map,i=new WeakMap,r=new Set,o={_bookId:()=>"x:"+c++,_register:(t,s)=>(e.set(t,s),t),_unregister:t=>{e.delete(t.sessionId);const r=i.get(t);void 0!==r&&(s.delete(r),i.delete(t))},get:t=>s.get(t),_set:(t,e)=>{const r=s.get(t);if(r&&r!==e)throw new Error(`Actor with system ID '${t}' already exists.`);s.set(t,e),i.set(e,t)},inspect:t=>{r.add(t)},_sendInspectionEvent:e=>{const s={...e,rootId:t.sessionId};r.forEach((t=>t.next?.(s)))},_relay:(t,e,s)=>{o._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:e,event:s}),e._send(s)}};return o}(this),_&&!n&&this.system.inspect(h(_)),this.sessionId=this.system._bookId(),this.id=a??this.sessionId,this.logger=o,this.clock=r,this._parent=n,this.options=i,this.src=i.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),this._initState(s?.state),p&&"active"===this._state.status&&(this._systemId=p,this.system._set(p,this))}_initState(t){this._state=t?this.logic.restoreState?this.logic.restoreState(t,this._actorScope):t:this.logic.getInitialState(this._actorScope,this.options?.input)}update(t,e){let s;for(this._state=t;s=this._deferred.shift();)s();for(const e of this.observers)try{e.next?.(t)}catch(t){n(t)}switch(this._state.status){case"done":this._stopProcedure(),this._complete(),this._doneEvent=(r=this.id,o=this._state.output,{type:`xstate.done.actor.${r}`,output:o}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._stopProcedure(),this._error(this._state.error),this._parent&&this.system._relay(this,this._parent,i(this.id,this._state.error))}var r,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){const i=h(t,e,s);if(this._processingStatus!==u.Stopped)this.observers.add(i);else try{i.complete?.()}catch(t){n(t)}return{unsubscribe:()=>{this.observers.delete(i)}}}start(){if(this._processingStatus===u.Running)return this;this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=u.Running;const t={type:"xstate.init",input:this.options.input};this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t});switch(this._state.status){case"done":this.update(this._state,t);case"error":return this}if(this.logic.start)try{this.logic.start(this._state,this._actorScope)}catch(t){return this._stopProcedure(),this._error(t),this._parent?.send(i(this.id,t)),this}return this.update(this._state,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,r;try{e=this.logic.transition(this._state,t,this._actorScope)}catch(t){r={err:t}}if(r){const{err:t}=r;return this._stopProcedure(),this._error(t),void this._parent?.send(i(this.id,t))}this.update(e,t),t.type===s&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===u.Stopped?this:(this.mailbox.clear(),this._processingStatus===u.NotStarted?(this._processingStatus=u.Stopped,this):(this.mailbox.enqueue({type:s}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){n(t)}this.observers.clear()}_error(t){if(!this.observers.size)return void(this._parent||n(t));let e=!1;for(const s of this.observers){const i=s.error;e||=!i;try{i?.(t)}catch(t){n(t)}}this.observers.clear(),e&&n(t)}_stopProcedure(){if(this._processingStatus!==u.Running)return this;for(const t of Object.keys(this.delayedEventsMap))this.clock.clearTimeout(this.delayedEventsMap[t]);return this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this._processingStatus=u.Stopped,this.system._unregister(this),this}_send(t){this._processingStatus!==u.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}delaySend(t){const{event:e,id:s,delay:i}=t,r=this.clock.setTimeout((()=>{this.system._relay(this,t.to??this,e)}),i);s&&(this.delayedEventsMap[s]=r)}cancel(t){this.clock.clearTimeout(this.delayedEventsMap[t]),delete this.delayedEventsMap[t]}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:o)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedState(t){return this.logic.getPersistedState(this._state,t)}[a](){return this}getSnapshot(){return this._state}}function _(t,e){return{config:t,transition:(e,s,i)=>({...e,context:t(e.context,s,i)}),getInitialState:(t,s)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof e?e({input:s}):e}),getPersistedState:t=>t,restoreState:t=>t}}const l="$$xstate.resolve",v="$$xstate.reject";const f=_((t=>{}),void 0);t.createEmptyActor=function(){return new p(f,t);var t},t.fromCallback=function(t){return{config:t,start:(t,{self:e,system:s})=>{s._relay(e,e,{type:"xstate.create"})},transition:(e,i,{self:r,system:o})=>{if("xstate.create"===i.type){const s=t=>{"stopped"!==e.status&&r._parent&&o._relay(r,r._parent,t)},i=t=>{e._receivers.add(t)};return e._dispose=t({input:e.input,system:o,self:r,sendBack:s,receive:i}),e}return i.type===s?("function"==typeof(e={...e,status:"stopped",error:void 0})._dispose&&e._dispose(),e):(e._receivers.forEach((t=>t(i))),e)},getInitialState:(t,e)=>({status:"active",output:void 0,error:void 0,input:e,_receivers:new Set,_dispose:void 0}),getPersistedState:({_dispose:t,_receivers:e,...s})=>s,restoreState:t=>({_receivers:new Set,_dispose:void 0,...t})}},t.fromEventObservable=function(t){const e="$$xstate.error",i="$$xstate.complete";return{config:t,transition:(t,r)=>{if("active"!==t.status)return t;switch(r.type){case e:return{...t,status:"error",error:r.data,input:void 0,_subscription:void 0};case i:return{...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}},getInitialState:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(s,{self:r,system:o})=>{"done"!==s.status&&(s._subscription=t({input:s.input,system:o,self:r}).subscribe({next:t=>{r._parent&&o._relay(r,r._parent,t)},error:t=>{o._relay(r,r,{type:e,data:t})},complete:()=>{o._relay(r,r,{type:i})}}))},getPersistedState:({_subscription:t,...e})=>e,restoreState:t=>({...t,_subscription:void 0})}},t.fromObservable=function(t){const e="$$xstate.next",i="$$xstate.error",r="$$xstate.complete";return{config:t,transition:(t,o,{self:n,id:a,defer:c,system:h})=>{if("active"!==t.status)return t;switch(o.type){case e:return{...t,context:o.data};case i:return{...t,status:"error",error:o.data,input:void 0,_subscription:void 0};case r:return{...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}},getInitialState:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(s,{self:o,system:n})=>{"done"!==s.status&&(s._subscription=t({input:s.input,system:n,self:o}).subscribe({next:t=>{n._relay(o,o,{type:e,data:t})},error:t=>{n._relay(o,o,{type:i,data:t})},complete:()=>{n._relay(o,o,{type:r})}}))},getPersistedState:({_subscription:t,...e})=>e,restoreState:t=>({...t,_subscription:void 0})}},t.fromPromise=function(t){return{config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case l:{const s=e.data;return{...t,status:"done",output:s,input:void 0}}case v:return{...t,status:"error",error:e.data,input:void 0};case s:return{...t,status:"stopped",input:void 0};default:return t}},start:(e,{self:s,system:i})=>{if("active"!==e.status)return;Promise.resolve(t({input:e.input,system:i,self:s})).then((t=>{"active"===s.getSnapshot().status&&i._relay(s,s,{type:l,data:t})}),(t=>{"active"===s.getSnapshot().status&&i._relay(s,s,{type:v,data:t})}))},getInitialState:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedState:t=>t,restoreState:t=>t}},t.fromTransition=_,Object.defineProperty(t,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=xstate-actors.umd.min.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"xstate-actors.umd.min.js","sources":["../../src/Mailbox.ts","../../src/constants.ts","../../src/eventUtils.ts","../../src/dev/index.ts","../../src/reportUnhandledError.ts","../../src/symbolObservable.ts","../../src/system.ts","../../src/utils.ts","../../src/interpreter.ts","../../src/actors/transition.ts","../../src/actors/promise.ts","../../src/actors/index.ts","../../src/actors/callback.ts","../../src/actors/observable.ts"],"sourcesContent":["interface MailboxItem<T> {\n value: T;\n next: MailboxItem<T> | null;\n}\n\nexport class Mailbox<T> {\n private _active: boolean = false;\n private _current: MailboxItem<T> | null = null;\n private _last: MailboxItem<T> | null = null;\n\n constructor(private _process: (ev: T) => void) {}\n\n public start() {\n this._active = true;\n this.flush();\n }\n\n public clear(): void {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldnt start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n\n public enqueue(event: T): void {\n const enqueued = {\n value: event,\n next: null\n };\n\n if (this._current) {\n this._last!.next = enqueued;\n this._last = enqueued;\n return;\n }\n\n this._current = enqueued;\n this._last = enqueued;\n\n if (this._active) {\n this.flush();\n }\n }\n\n private flush() {\n while (this._current) {\n // atm the given _process is responsible for implementing proper try/catch handling\n // we assume here that this won't throw in a way that can affect this mailbox\n const consumed = this._current;\n this._process(consumed.value);\n this._current = consumed.next;\n }\n this._last = null;\n }\n}\n","export const STATE_DELIMITER = '.';\nexport const TARGETLESS_KEY = '';\nexport const NULL_EVENT = '';\nexport const STATE_IDENTIFIER = '#';\nexport const WILDCARD = '*';\nexport const XSTATE_INIT = 'xstate.init';\nexport const XSTATE_ERROR = 'xstate.error';\nexport const XSTATE_STOP = 'xstate.stop';\n","import { XSTATE_INIT } from './constants.ts';\nimport { DoneActorEvent, DoneStateEvent, ErrorActorEvent } from './types.ts';\n\n/**\n * Returns an event that represents an implicit event that\n * is sent after the specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nexport function createAfterEvent(delayRef: number | string, id?: string) {\n const idSuffix = id ? `#${id}` : '';\n return { type: `xstate.after(${delayRef})${idSuffix}` } as const;\n}\n\n/**\n * Returns an event that represents that a final state node\n * has been reached in the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nexport function createDoneStateEvent(\n id: string,\n output?: unknown\n): DoneStateEvent {\n return {\n type: `xstate.done.state.${id}`,\n output\n };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state node,\n * but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n */\nexport function createDoneActorEvent(\n invokeId: string,\n output?: unknown\n): DoneActorEvent {\n return {\n type: `xstate.done.actor.${invokeId}`,\n output\n };\n}\n\nexport function createErrorActorEvent(\n id: string,\n data?: unknown\n): ErrorActorEvent {\n return { type: `xstate.error.actor.${id}`, data };\n}\n\nexport function createInitEvent(input: unknown) {\n return { type: XSTATE_INIT, input } as const;\n}\n","import isDevelopment from '#is-development';\nimport { AnyActor, DevToolsAdapter } from '../types.ts';\n\ninterface DevInterface {\n services: Set<AnyActor>;\n register(service: AnyActor): void;\n onRegister(listener: ServiceListener): void;\n}\ntype ServiceListener = (service: AnyActor) => void;\n\nexport interface XStateDevInterface {\n register: (service: AnyActor) => void;\n unregister: (service: AnyActor) => void;\n onRegister: (listener: ServiceListener) => {\n unsubscribe: () => void;\n };\n services: Set<AnyActor>;\n}\n\n// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\nexport function getGlobal(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (isDevelopment) {\n console.warn(\n 'XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues'\n );\n }\n}\n\nfunction getDevTools(): DevInterface | undefined {\n const w = getGlobal();\n if (!!(w as any).__xstate__) {\n return (w as any).__xstate__;\n }\n\n return undefined;\n}\n\nexport function registerService(service: AnyActor) {\n if (typeof window === 'undefined') {\n return;\n }\n\n const devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n}\n\nexport const devToolsAdapter: DevToolsAdapter = (service) => {\n if (typeof window === 'undefined') {\n return;\n }\n\n const devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n};\n","/**\n * This function makes sure that unhandled errors are thrown in a separate macrotask.\n * It allows those errors to be detected by global error handlers and reported to bug tracking services\n * without interrupting our own stack of execution.\n *\n * @param err error to be thrown\n */\nexport function reportUnhandledError(err: unknown) {\n setTimeout(() => {\n throw err;\n });\n}\n","export const symbolObservable: typeof Symbol.observable = (() =>\n (typeof Symbol === 'function' && Symbol.observable) ||\n '@@observable')() as any;\n","import {\n AnyEventObject,\n ActorSystem,\n ActorSystemInfo,\n AnyActorRef,\n Observer,\n Snapshot\n} from './types.ts';\n\nlet idCounter = 0;\nexport function createSystem<T extends ActorSystemInfo>(\n rootActor: AnyActorRef\n): ActorSystem<T> {\n const children = new Map<string, AnyActorRef>();\n const keyedActors = new Map<keyof T['actors'], AnyActorRef | undefined>();\n const reverseKeyedActors = new WeakMap<AnyActorRef, keyof T['actors']>();\n const observers = new Set<Observer<InspectionEvent>>();\n\n const system: ActorSystem<T> = {\n _bookId: () => `x:${idCounter++}`,\n _register: (sessionId, actorRef) => {\n children.set(sessionId, actorRef);\n return sessionId;\n },\n _unregister: (actorRef) => {\n children.delete(actorRef.sessionId);\n const systemId = reverseKeyedActors.get(actorRef);\n\n if (systemId !== undefined) {\n keyedActors.delete(systemId);\n reverseKeyedActors.delete(actorRef);\n }\n },\n get: (systemId) => {\n return keyedActors.get(systemId) as T['actors'][any];\n },\n _set: (systemId, actorRef) => {\n const existing = keyedActors.get(systemId);\n if (existing && existing !== actorRef) {\n throw new Error(\n `Actor with system ID '${systemId as string}' already exists.`\n );\n }\n\n keyedActors.set(systemId, actorRef);\n reverseKeyedActors.set(actorRef, systemId);\n },\n inspect: (observer) => {\n observers.add(observer);\n },\n _sendInspectionEvent: (event) => {\n const resolvedInspectionEvent: InspectionEvent = {\n ...event,\n rootId: rootActor.sessionId\n };\n observers.forEach((observer) => observer.next?.(resolvedInspectionEvent));\n },\n _relay: (source, target, event) => {\n system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: source,\n targetRef: target,\n event\n });\n\n target._send(event);\n }\n };\n\n return system;\n}\nexport interface BaseInspectionEventProperties {\n rootId: string; // the session ID of the root\n}\n\nexport interface InspectedSnapshotEvent extends BaseInspectionEventProperties {\n type: '@xstate.snapshot';\n actorRef: AnyActorRef; // Only available locally\n event: AnyEventObject; // { type: string, ... }\n snapshot: Snapshot<unknown>;\n}\n\nexport interface InspectedEventEvent extends BaseInspectionEventProperties {\n type: '@xstate.event';\n // The source might not exist, e.g. when:\n // - root init events\n // - events sent from external (non-actor) sources\n sourceRef: AnyActorRef | undefined;\n targetRef: AnyActorRef; // Session ID, required\n event: AnyEventObject; // { type: string, ... }\n}\n\nexport interface InspectedActorEvent extends BaseInspectionEventProperties {\n type: '@xstate.actor';\n actorRef: AnyActorRef;\n}\n\nexport type InspectionEvent =\n | InspectedSnapshotEvent\n | InspectedEventEvent\n | InspectedActorEvent;\n","import isDevelopment from '#is-development';\nimport { AnyActorLogic, AnyState } from './index.ts';\nimport { STATE_DELIMITER, TARGETLESS_KEY } from './constants.ts';\nimport type { StateNode } from './StateNode.ts';\nimport type {\n ActorLogic,\n AnyEventObject,\n EventObject,\n MachineContext,\n Mapper,\n Observer,\n ErrorActorEvent,\n SingleOrArray,\n StateLike,\n StateValue,\n Subscribable,\n TransitionConfigTarget,\n AnyActorRef,\n AnyTransitionConfig,\n NonReducibleUnknown,\n AnyStateMachine,\n InvokeConfig\n} from './types.ts';\n\nexport function keys<T extends object>(value: T): Array<keyof T & string> {\n return Object.keys(value) as Array<keyof T & string>;\n}\n\nexport function matchesState(\n parentStateId: StateValue,\n childStateId: StateValue\n): boolean {\n const parentStateValue = toStateValue(parentStateId);\n const childStateValue = toStateValue(childStateId);\n\n if (typeof childStateValue === 'string') {\n if (typeof parentStateValue === 'string') {\n return childStateValue === parentStateValue;\n }\n\n // Parent more specific than child\n return false;\n }\n\n if (typeof parentStateValue === 'string') {\n return parentStateValue in childStateValue;\n }\n\n return Object.keys(parentStateValue).every((key) => {\n if (!(key in childStateValue)) {\n return false;\n }\n\n return matchesState(parentStateValue[key], childStateValue[key]);\n });\n}\n\nexport function toStatePath(stateId: string | string[]): string[] {\n try {\n if (isArray(stateId)) {\n return stateId;\n }\n\n return stateId.toString().split(STATE_DELIMITER);\n } catch (e) {\n throw new Error(`'${stateId}' is not a valid state path.`);\n }\n}\n\nexport function isStateLike(state: any): state is AnyState {\n return (\n typeof state === 'object' &&\n 'value' in state &&\n 'context' in state &&\n 'event' in state\n );\n}\n\nexport function toStateValue(\n stateValue: StateLike<any> | StateValue | string[]\n): StateValue {\n if (isStateLike(stateValue)) {\n return stateValue.value;\n }\n\n if (isArray(stateValue)) {\n return pathToStateValue(stateValue);\n }\n\n if (typeof stateValue !== 'string') {\n return stateValue as StateValue;\n }\n\n const statePath = toStatePath(stateValue as string);\n\n return pathToStateValue(statePath);\n}\n\nexport function pathToStateValue(statePath: string[]): StateValue {\n if (statePath.length === 1) {\n return statePath[0];\n }\n\n const value: StateValue = {};\n let marker = value;\n\n for (let i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n const previous = marker;\n marker = {};\n previous[statePath[i]] = marker;\n }\n }\n\n return value;\n}\n\nexport function mapValues<P, O extends Record<string, unknown>>(\n collection: O,\n iteratee: (item: O[keyof O], key: keyof O, collection: O, i: number) => P\n): { [key in keyof O]: P };\nexport function mapValues(\n collection: Record<string, unknown>,\n iteratee: (\n item: unknown,\n key: string,\n collection: Record<string, unknown>,\n i: number\n ) => unknown\n) {\n const result: Record<string, unknown> = {};\n\n const collectionKeys = Object.keys(collection);\n for (let i = 0; i < collectionKeys.length; i++) {\n const key = collectionKeys[i];\n result[key] = iteratee(collection[key], key, collection, i);\n }\n\n return result;\n}\n\nexport function mapFilterValues<T, P>(\n collection: { [key: string]: T },\n iteratee: (item: T, key: string, collection: { [key: string]: T }) => P,\n predicate: (item: T) => boolean\n): { [key: string]: P } {\n const result: { [key: string]: P } = {};\n\n for (const key of Object.keys(collection)) {\n const item = collection[key];\n\n if (!predicate(item)) {\n continue;\n }\n\n result[key] = iteratee(item, key, collection);\n }\n\n return result;\n}\n\n/**\n * Retrieves a value at the given path.\n * @param props The deep path to the prop of the desired value\n */\nexport function path<T extends Record<string, any>>(props: string[]): any {\n return (object: T): any => {\n let result: T = object;\n\n for (const prop of props) {\n result = result[prop as keyof typeof result];\n }\n\n return result;\n };\n}\n\nexport function toStatePaths(stateValue: StateValue | undefined): string[][] {\n if (!stateValue) {\n return [[]];\n }\n\n if (typeof stateValue === 'string') {\n return [[stateValue]];\n }\n\n const result = flatten(\n Object.keys(stateValue).map((key) => {\n const subStateValue = stateValue[key];\n\n if (\n typeof subStateValue !== 'string' &&\n (!subStateValue || !Object.keys(subStateValue).length)\n ) {\n return [[key]];\n }\n\n return toStatePaths(stateValue[key]).map((subPath) => {\n return [key].concat(subPath);\n });\n })\n );\n\n return result;\n}\n\nexport function flatten<T>(array: Array<T | T[]>): T[] {\n return ([] as T[]).concat(...array);\n}\n\nexport function toArrayStrict<T>(value: readonly T[] | T): readonly T[] {\n if (isArray(value)) {\n return value;\n }\n return [value];\n}\n\nexport function toArray<T>(value: readonly T[] | T | undefined): readonly T[] {\n if (value === undefined) {\n return [];\n }\n return toArrayStrict(value);\n}\n\nexport function resolveOutput<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n>(\n mapper:\n | Mapper<TContext, TExpressionEvent, unknown, EventObject>\n | NonReducibleUnknown,\n context: TContext,\n event: TExpressionEvent,\n self: AnyActorRef\n): unknown {\n if (typeof mapper === 'function') {\n return mapper({ context, event, self });\n }\n\n if (\n isDevelopment &&\n !!mapper &&\n typeof mapper === 'object' &&\n Object.values(mapper).some((val) => typeof val === 'function')\n ) {\n console.warn(\n `Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.\\nFound object containing properties whose values are possibly mapping functions: ${Object.entries(\n mapper\n )\n .filter(([key, value]) => typeof value === 'function')\n .map(\n ([key, value]) =>\n `\\n - ${key}: ${(value as () => any)\n .toString()\n .replace(/\\n\\s*/g, '')}`\n )\n .join('')}`\n );\n }\n\n return mapper;\n}\n\nexport function isBuiltInEvent(eventType: string): boolean {\n return /^(done|error)\\./.test(eventType);\n}\n\nexport function isPromiseLike(value: any): value is PromiseLike<any> {\n if (value instanceof Promise) {\n return true;\n }\n // Check if shape matches the Promise/A+ specification for a \"thenable\".\n if (\n value !== null &&\n (typeof value === 'function' || typeof value === 'object') &&\n typeof value.then === 'function'\n ) {\n return true;\n }\n return false;\n}\n\nexport function isActorLogic(value: any): value is ActorLogic<any, any> {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'transition' in value &&\n typeof value.transition === 'function'\n );\n}\n\nexport function partition<T, A extends T, B extends T>(\n items: T[],\n predicate: (item: T) => item is A\n): [A[], B[]] {\n const [truthy, falsy] = [[], []] as [A[], B[]];\n\n for (const item of items) {\n if (predicate(item)) {\n truthy.push(item);\n } else {\n falsy.push(item as B);\n }\n }\n\n return [truthy, falsy];\n}\n\nexport function isArray(value: any): value is readonly any[] {\n return Array.isArray(value);\n}\n\nexport function isObservable<T>(value: any): value is Subscribable<T> {\n return (\n !!value && 'subscribe' in value && typeof value.subscribe === 'function'\n );\n}\n\nexport function isErrorActorEvent(\n event: AnyEventObject\n): event is ErrorActorEvent {\n return event.type.startsWith('xstate.error.actor');\n}\n\nexport function toTransitionConfigArray<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n configLike: SingleOrArray<AnyTransitionConfig | TransitionConfigTarget>\n): Array<AnyTransitionConfig> {\n return toArrayStrict(configLike).map((transitionLike) => {\n if (\n typeof transitionLike === 'undefined' ||\n typeof transitionLike === 'string'\n ) {\n return { target: transitionLike };\n }\n\n return transitionLike;\n });\n}\n\nexport function normalizeTarget<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n target: SingleOrArray<string | StateNode<TContext, TEvent>> | undefined\n): ReadonlyArray<string | StateNode<TContext, TEvent>> | undefined {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n return toArray(target);\n}\n\nexport function reportUnhandledExceptionOnInvocation(\n originalError: any,\n currentError: any,\n id: string\n) {\n if (isDevelopment) {\n const originalStackTrace = originalError.stack\n ? ` Stacktrace was '${originalError.stack}'`\n : '';\n if (originalError === currentError) {\n // tslint:disable-next-line:no-console\n console.error(\n `Missing onError handler for invocation '${id}', error was '${originalError}'.${originalStackTrace}`\n );\n } else {\n const stackTrace = currentError.stack\n ? ` Stacktrace was '${currentError.stack}'`\n : '';\n // tslint:disable-next-line:no-console\n console.error(\n `Missing onError handler and/or unhandled exception/promise rejection for invocation '${id}'. ` +\n `Original error: '${originalError}'. ${originalStackTrace} Current error is '${currentError}'.${stackTrace}`\n );\n }\n }\n}\n\nexport function toObserver<T>(\n nextHandler?: Observer<T> | ((value: T) => void),\n errorHandler?: (error: any) => void,\n completionHandler?: () => void\n): Observer<T> {\n const isObserver = typeof nextHandler === 'object';\n const self = isObserver ? nextHandler : undefined;\n\n return {\n next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(\n self\n )\n };\n}\n\nexport function createInvokeId(stateNodeId: string, index: number): string {\n return `${stateNodeId}[${index}]`;\n}\n\nexport function resolveReferencedActor(machine: AnyStateMachine, src: string) {\n if (src.startsWith('xstate#')) {\n const [, indexStr] = src.match(/\\[(\\d+)\\]$/)!;\n const node = machine.getStateNodeById(src.slice(7, -(indexStr.length + 2)));\n const invokeConfig = node.config.invoke!;\n return {\n src: (Array.isArray(invokeConfig)\n ? invokeConfig[indexStr as any]\n : (invokeConfig as InvokeConfig<any, any, any, any, any, any>)\n ).src,\n input: undefined\n };\n }\n const referenced = machine.implementations.actors[src];\n return referenced\n ? 'transition' in referenced\n ? { src: referenced, input: undefined }\n : referenced\n : undefined;\n}\n","import isDevelopment from '#is-development';\nimport { Mailbox } from './Mailbox.ts';\nimport {\n createDoneActorEvent,\n createErrorActorEvent,\n createInitEvent\n} from './eventUtils.ts';\nimport { XSTATE_STOP } from './constants.ts';\nimport { devToolsAdapter } from './dev/index.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { symbolObservable } from './symbolObservable.ts';\nimport { createSystem } from './system.ts';\nimport {\n AreAllImplementationsAssumedToBeProvided,\n MissingImplementationsError\n} from './typegenTypes.ts';\nimport type {\n ActorScope,\n ActorSystem,\n AnyActorLogic,\n AnyStateMachine,\n EventFromLogic,\n SnapshotFrom,\n AnyActorRef,\n DoneActorEvent,\n Snapshot\n} from './types.ts';\nimport {\n ActorRef,\n EventObject,\n InteropSubscribable,\n ActorOptions,\n Observer,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\n\nexport const $$ACTOR_TYPE = 1;\n\nexport type SnapshotListener<TLogic extends AnyActorLogic> = (\n state: SnapshotFrom<TLogic>\n) => void;\n\nexport type EventListener<TEvent extends EventObject = EventObject> = (\n event: TEvent\n) => void;\n\nexport type Listener = () => void;\nexport type ErrorListener = (error: any) => void;\n\nexport interface Clock {\n setTimeout(fn: (...args: any[]) => void, timeout: number): any;\n clearTimeout(id: any): void;\n}\n\nexport enum ActorStatus {\n NotStarted,\n Running,\n Stopped\n}\n\n/**\n * @deprecated Use `ActorStatus` instead.\n */\nexport const InterpreterStatus = ActorStatus;\n\nconst defaultOptions = {\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: (id) => {\n return clearTimeout(id);\n }\n } as Clock,\n logger: console.log.bind(console),\n devTools: false\n};\n\n/**\n * An Actor is a running process that can receive events, send events and change its behavior based on the events it receives, which can cause effects outside of the actor. When you run a state machine, it becomes an actor.\n */\nexport class Actor<TLogic extends AnyActorLogic>\n implements ActorRef<EventFromLogic<TLogic>, SnapshotFrom<TLogic>>\n{\n /**\n * The current internal state of the actor.\n */\n private _state!: SnapshotFrom<TLogic>;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.\n */\n public clock: Clock;\n public options: Readonly<ActorOptions<TLogic>>;\n\n /**\n * The unique identifier for this actor relative to its parent.\n */\n public id: string;\n\n private mailbox: Mailbox<EventFromLogic<TLogic>> = new Mailbox(\n this._process.bind(this)\n );\n\n private delayedEventsMap: Record<string, unknown> = {};\n\n private observers: Set<Observer<SnapshotFrom<TLogic>>> = new Set();\n private logger: (...args: any[]) => void;\n /**\n * Whether the service is started.\n */\n public status: ActorStatus = ActorStatus.NotStarted;\n\n // Actor Ref\n public _parent?: ActorRef<any, any>;\n public ref: ActorRef<EventFromLogic<TLogic>, SnapshotFrom<TLogic>>;\n // TODO: add typings for system\n private _actorScope: ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n any\n >;\n\n private _systemId: string | undefined;\n\n /**\n * The globally unique process ID for this invocation.\n */\n public sessionId: string;\n\n /**\n * The system to which this actor belongs.\n */\n public system: ActorSystem<any>;\n private _doneEvent?: DoneActorEvent;\n\n public src?: string;\n\n /**\n * Creates a new actor instance for the given logic with the provided options, if any.\n *\n * @param logic The logic to create an actor from\n * @param options Actor options\n */\n constructor(public logic: TLogic, options?: ActorOptions<TLogic>) {\n const resolvedOptions = {\n ...defaultOptions,\n ...options\n } as ActorOptions<TLogic> & typeof defaultOptions;\n\n const { clock, logger, parent, id, systemId, inspect } = resolvedOptions;\n\n this.system = parent?.system ?? createSystem(this);\n\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n\n this.sessionId = this.system._bookId();\n this.id = id ?? this.sessionId;\n this.logger = logger;\n this.clock = clock;\n this._parent = parent;\n this.options = resolvedOptions;\n this.src = resolvedOptions.src;\n this.ref = this;\n this._actorScope = {\n self: this,\n id: this.id,\n sessionId: this.sessionId,\n logger: this.logger,\n defer: (fn) => {\n this._deferred.push(fn);\n },\n system: this.system,\n stopChild: (child) => {\n if (child._parent !== this) {\n throw new Error(\n `Cannot stop child actor ${child.id} of ${this.id} because it is not a child`\n );\n }\n (child as any)._stop();\n }\n };\n\n // Ensure that the send method is bound to this Actor instance\n // if destructured\n this.send = this.send.bind(this);\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this\n });\n this._initState();\n\n if (systemId && (this._state as any).status === 'active') {\n this._systemId = systemId;\n this.system._set(systemId, this);\n }\n }\n\n private _initState() {\n this._state = this.options.state\n ? this.logic.restoreState\n ? this.logic.restoreState(this.options.state, this._actorScope)\n : this.options.state\n : this.logic.getInitialState(this._actorScope, this.options?.input);\n }\n\n // array of functions to defer\n private _deferred: Array<() => void> = [];\n\n private update(snapshot: SnapshotFrom<TLogic>, event: EventObject): void {\n // Update state\n this._state = snapshot;\n\n // Execute deferred effects\n let deferredFn: (typeof this._deferred)[number] | undefined;\n\n while ((deferredFn = this._deferred.shift())) {\n deferredFn();\n }\n\n for (const observer of this.observers) {\n // TODO: should observers be notified in case of the error?\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n\n switch ((this._state as any).status) {\n case 'done':\n this._stopProcedure();\n this._complete();\n this._doneEvent = createDoneActorEvent(\n this.id,\n (this._state as any).output\n );\n if (this._parent) {\n this.system._relay(this, this._parent, this._doneEvent);\n }\n\n break;\n case 'error':\n this._stopProcedure();\n this._error((this._state as any).error);\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createErrorActorEvent(this.id, (this._state as any).error)\n );\n }\n break;\n }\n this.system._sendInspectionEvent({\n type: '@xstate.snapshot',\n actorRef: this,\n event,\n snapshot\n });\n }\n\n /**\n * Subscribe an observer to an actor’s snapshot values.\n *\n * @remarks\n * The observer will receive the actor’s snapshot value when it is emitted. The observer can be:\n * - A plain function that receives the latest snapshot, or\n * - An observer object whose `.next(snapshot)` method receives the latest snapshot\n *\n * @example\n * ```ts\n * // Observer as a plain function\n * const subscription = actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * ```\n *\n * @example\n * ```ts\n * // Observer as an object\n * const subscription = actor.subscribe({\n * next(snapshot) {\n * console.log(snapshot);\n * },\n * error(err) {\n * // ...\n * },\n * complete() {\n * // ...\n * },\n * });\n * ```\n *\n * The return value of `actor.subscribe(observer)` is a subscription object that has an `.unsubscribe()` method. You can call `subscription.unsubscribe()` to unsubscribe the observer:\n *\n * @example\n * ```ts\n * const subscription = actor.subscribe((snapshot) => {\n * // ...\n * });\n *\n * // Unsubscribe the observer\n * subscription.unsubscribe();\n * ```\n *\n * When the actor is stopped, all of its observers will automatically be unsubscribed.\n *\n * @param observer - Either a plain function that receives the latest snapshot, or an observer object whose `.next(snapshot)` method receives the latest snapshot\n */\n public subscribe(observer: Observer<SnapshotFrom<TLogic>>): Subscription;\n public subscribe(\n nextListener?: (state: SnapshotFrom<TLogic>) => void,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription;\n public subscribe(\n nextListenerOrObserver?:\n | ((state: SnapshotFrom<TLogic>) => void)\n | Observer<SnapshotFrom<TLogic>>,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription {\n const observer = toObserver(\n nextListenerOrObserver,\n errorListener,\n completeListener\n );\n\n if (this.status !== ActorStatus.Stopped) {\n this.observers.add(observer);\n } else {\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n\n return {\n unsubscribe: () => {\n this.observers.delete(observer);\n }\n };\n }\n\n /**\n * Starts the Actor from the initial state\n */\n public start(): this {\n if (this.status === ActorStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n\n this.system._register(this.sessionId, this);\n if (this._systemId) {\n this.system._set(this._systemId, this);\n }\n this.status = ActorStatus.Running;\n\n const initEvent = createInitEvent(this.options.input);\n\n this.system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: this._parent,\n targetRef: this,\n event: initEvent\n });\n\n const status = (this._state as any).status;\n\n switch (status) {\n case 'done':\n // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n // we still need to complete observers, flush deferreds etc\n this.update(\n this._state,\n initEvent as unknown as EventFromLogic<TLogic>\n );\n // fallthrough\n case 'error':\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n }\n\n if (this.logic.start) {\n try {\n this.logic.start(this._state, this._actorScope);\n } catch (err) {\n this._stopProcedure();\n this._error(err);\n this._parent?.send(createErrorActorEvent(this.id, err));\n return this;\n }\n }\n\n // TODO: this notifies all subscribers but usually this is redundant\n // there is no real change happening here\n // we need to rethink if this needs to be refactored\n this.update(this._state, initEvent as unknown as EventFromLogic<TLogic>);\n\n if (this.options.devTools) {\n this.attachDevTools();\n }\n\n this.mailbox.start();\n\n return this;\n }\n\n private _process(event: EventFromLogic<TLogic>) {\n // TODO: reexamine what happens when an action (or a guard or smth) throws\n let nextState;\n let caughtError;\n try {\n nextState = this.logic.transition(this._state, event, this._actorScope);\n } catch (err) {\n // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n caughtError = { err };\n }\n\n if (caughtError) {\n const { err } = caughtError;\n\n this._stopProcedure();\n this._error(err);\n this._parent?.send(createErrorActorEvent(this.id, err));\n return;\n }\n\n this.update(nextState, event);\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n\n private _stop(): this {\n if (this.status === ActorStatus.Stopped) {\n return this;\n }\n this.mailbox.clear();\n if (this.status === ActorStatus.NotStarted) {\n this.status = ActorStatus.Stopped;\n return this;\n }\n this.mailbox.enqueue({ type: XSTATE_STOP } as any);\n\n return this;\n }\n\n /**\n * Stops the Actor and unsubscribe all listeners.\n */\n public stop(): this {\n if (this._parent) {\n throw new Error('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n private _complete(): void {\n for (const observer of this.observers) {\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n this.observers.clear();\n }\n private _error(err: unknown): void {\n if (!this.observers.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n return;\n }\n let reportError = false;\n\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n try {\n errorListener?.(err);\n } catch (err2) {\n reportUnhandledError(err2);\n }\n }\n this.observers.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n private _stopProcedure(): this {\n if (this.status !== ActorStatus.Running) {\n // Actor already stopped; do nothing\n return this;\n }\n\n // Cancel all delayed events\n for (const key of Object.keys(this.delayedEventsMap)) {\n this.clock.clearTimeout(this.delayedEventsMap[key]);\n }\n\n // TODO: mailbox.reset\n this.mailbox.clear();\n // TODO: after `stop` we must prepare ourselves for receiving events again\n // events sent *after* stop signal must be queued\n // it seems like this should be the common behavior for all of our consumers\n // so perhaps this should be unified somehow for all of them\n this.mailbox = new Mailbox(this._process.bind(this));\n\n this.status = ActorStatus.Stopped;\n this.system._unregister(this);\n\n return this;\n }\n\n /**\n * @internal\n */\n public _send(event: EventFromLogic<TLogic>) {\n if (this.status === ActorStatus.Stopped) {\n // do nothing\n if (isDevelopment) {\n const eventString = JSON.stringify(event);\n\n console.warn(\n `Event \"${event.type}\" was sent to stopped actor \"${this.id} (${this.sessionId})\". This actor has already reached its final state, and will not transition.\\nEvent: ${eventString}`\n );\n }\n return;\n }\n\n this.mailbox.enqueue(event);\n }\n\n /**\n * Sends an event to the running Actor to trigger a transition.\n *\n * @param event The event to send\n */\n public send(event: EventFromLogic<TLogic>) {\n if (isDevelopment && typeof event === 'string') {\n throw new Error(\n `Only event objects may be sent to actors; use .send({ type: \"${event}\" }) instead`\n );\n }\n this.system._relay(undefined, this, event);\n }\n\n /**\n * TODO: figure out a way to do this within the machine\n * @internal\n */\n public delaySend(params: {\n event: EventObject;\n id: string | undefined;\n delay: number;\n to?: AnyActorRef;\n }): void {\n const { event, id, delay } = params;\n const timerId = this.clock.setTimeout(() => {\n this.system._relay(\n this,\n params.to ?? this,\n event as EventFromLogic<TLogic>\n );\n }, delay);\n\n // TODO: consider the rehydration story here\n if (id) {\n this.delayedEventsMap[id] = timerId;\n }\n }\n\n /**\n * TODO: figure out a way to do this within the machine\n * @internal\n */\n public cancel(sendId: string | number): void {\n this.clock.clearTimeout(this.delayedEventsMap[sendId]);\n delete this.delayedEventsMap[sendId];\n }\n\n private attachDevTools(): void {\n const { devTools } = this.options;\n if (devTools) {\n const resolvedDevToolsAdapter =\n typeof devTools === 'function' ? devTools : devToolsAdapter;\n\n resolvedDevToolsAdapter(this);\n }\n }\n public toJSON() {\n return {\n xstate$$type: $$ACTOR_TYPE,\n id: this.id\n };\n }\n\n public getPersistedState(): Snapshot<unknown> {\n return this.logic.getPersistedState(this._state);\n }\n\n public [symbolObservable](): InteropSubscribable<SnapshotFrom<TLogic>> {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot represent an actor's last emitted value.\n *\n * When an actor receives an event, its internal state may change.\n * An actor may emit a snapshot when a state transition occurs.\n *\n * Note that some actors, such as callback actors generated with `fromCallback`, will not emit snapshots.\n *\n * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n * @see {@link Actor.getPersistedState} to persist the internal state of an actor (which is more than just a snapshot).\n */\n public getSnapshot(): SnapshotFrom<TLogic> {\n return this._state;\n }\n}\n\n/**\n * Creates a new `ActorRef` instance for the given machine with the provided options, if any.\n *\n * @param machine The machine to create an actor from\n * @param options `ActorRef` options\n */\nexport function createActor<TMachine extends AnyStateMachine>(\n machine: AreAllImplementationsAssumedToBeProvided<\n TMachine['__TResolvedTypesMeta']\n > extends true\n ? TMachine\n : MissingImplementationsError<TMachine['__TResolvedTypesMeta']>,\n options?: ActorOptions<TMachine>\n): Actor<TMachine>;\nexport function createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options?: ActorOptions<TLogic>\n): Actor<TLogic>;\nexport function createActor(logic: any, options?: ActorOptions<any>): any {\n const interpreter = new Actor(logic, options);\n\n return interpreter;\n}\n\n/**\n * Creates a new Interpreter instance for the given machine with the provided options, if any.\n *\n * @deprecated Use `createActor` instead\n */\nexport const interpret = createActor;\n\n/**\n * @deprecated Use `Actor` instead.\n */\nexport type Interpreter = typeof Actor;\n","import {\n ActorLogic,\n ActorScope,\n ActorSystem,\n EventObject,\n ActorRefFrom,\n AnyActorSystem,\n Snapshot\n} from '../types';\n\nexport type TransitionSnapshot<TContext> = Snapshot<undefined> & {\n context: TContext;\n};\n\nexport type TransitionActorLogic<\n TContext,\n TEvent extends EventObject,\n TInput\n> = ActorLogic<TransitionSnapshot<TContext>, TEvent, TInput, AnyActorSystem>;\n\nexport type TransitionActorRef<\n TContext,\n TEvent extends EventObject\n> = ActorRefFrom<\n TransitionActorLogic<TransitionSnapshot<TContext>, TEvent, unknown>\n>;\n\n/**\n * Returns actor logic from a transition function and its initial state.\n *\n * A transition function is a function that takes the current state and an event and returns the next state.\n *\n * @param transition The transition function that returns the next state given the current state and event.\n * @param initialContext The initial state of the transition function.\n * @returns Actor logic\n */\nexport function fromTransition<\n TContext,\n TEvent extends EventObject,\n TSystem extends ActorSystem<any>,\n TInput\n>(\n transition: (\n state: TContext,\n event: TEvent,\n actorScope: ActorScope<TransitionSnapshot<TContext>, TEvent, TSystem>\n ) => TContext,\n initialContext:\n | TContext\n | (({\n input,\n self\n }: {\n input: TInput;\n self: TransitionActorRef<TContext, TEvent>;\n }) => TContext) // TODO: type\n): TransitionActorLogic<TContext, TEvent, TInput> {\n return {\n config: transition,\n transition: (state, event, actorScope) => {\n return {\n ...state,\n context: transition(state.context, event as TEvent, actorScope as any)\n };\n },\n getInitialState: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context:\n typeof initialContext === 'function'\n ? (initialContext as any)({ input })\n : initialContext\n };\n },\n getPersistedState: (state) => state,\n restoreState: (state: any) => state\n };\n}\n","import {\n ActorLogic,\n ActorRefFrom,\n ActorSystem,\n AnyActorSystem,\n Snapshot\n} from '../types';\nimport { XSTATE_STOP } from '../constants';\n\nexport type PromiseSnapshot<TOutput, TInput> = Snapshot<TOutput> & {\n input: TInput | undefined;\n};\n\nconst resolveEventType = '$$xstate.resolve';\nconst rejectEventType = '$$xstate.reject';\n\nexport type PromiseActorEvents<T> =\n | {\n type: typeof resolveEventType;\n data: T;\n }\n | {\n type: typeof rejectEventType;\n data: any;\n }\n | {\n type: typeof XSTATE_STOP;\n };\n\nexport type PromiseActorLogic<TOutput, TInput = unknown> = ActorLogic<\n PromiseSnapshot<TOutput, TInput>,\n { type: string; [k: string]: unknown },\n TInput, // input\n ActorSystem<any>\n>;\n\nexport type PromiseActorRef<TOutput> = ActorRefFrom<\n PromiseActorLogic<TOutput, unknown>\n>;\n\nexport function fromPromise<TOutput, TInput = unknown>(\n // TODO: add types\n promiseCreator: ({\n input,\n system\n }: {\n input: TInput;\n system: AnyActorSystem;\n self: PromiseActorRef<TOutput>;\n }) => PromiseLike<TOutput>\n): PromiseActorLogic<TOutput, TInput> {\n // TODO: add event types\n const logic: PromiseActorLogic<TOutput, TInput> = {\n config: promiseCreator,\n transition: (state, event) => {\n if (state.status !== 'active') {\n return state;\n }\n\n switch (event.type) {\n case resolveEventType: {\n const resolvedValue = (event as any).data;\n return {\n ...state,\n status: 'done',\n output: resolvedValue,\n input: undefined\n };\n }\n case rejectEventType:\n return {\n ...state,\n status: 'error',\n error: (event as any).data,\n input: undefined\n };\n case XSTATE_STOP:\n return {\n ...state,\n status: 'stopped',\n input: undefined\n };\n default:\n return state;\n }\n },\n start: (state, { self, system }) => {\n // TODO: determine how to allow customizing this so that promises\n // can be restarted if necessary\n if (state.status !== 'active') {\n return;\n }\n\n const resolvedPromise = Promise.resolve(\n promiseCreator({ input: state.input!, system, self })\n );\n\n resolvedPromise.then(\n (response) => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n system._relay(self, self, { type: resolveEventType, data: response });\n },\n (errorData) => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n system._relay(self, self, { type: rejectEventType, data: errorData });\n }\n );\n },\n getInitialState: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n };\n },\n getPersistedState: (state) => state,\n restoreState: (state: any) => state\n };\n\n return logic;\n}\n","import { createActor } from '../interpreter.ts';\nimport type { ActorRef, AnyEventObject, Snapshot } from '../types.ts';\nimport { fromTransition } from './transition.ts';\nexport { fromCallback, type CallbackActorLogic } from './callback.ts';\nexport {\n fromEventObservable,\n fromObservable,\n type ObservableActorLogic\n} from './observable.ts';\nexport { fromPromise, type PromiseActorLogic } from './promise.ts';\nexport {\n fromTransition,\n type TransitionActorLogic,\n type TransitionSnapshot\n} from './transition.ts';\n\nconst emptyLogic = fromTransition((_) => undefined, undefined);\n\nexport function createEmptyActor(): ActorRef<\n AnyEventObject,\n Snapshot<undefined>\n> {\n return createActor(emptyLogic);\n}\n","import {\n ActorLogic,\n EventObject,\n AnyActorSystem,\n AnyEventObject,\n ActorSystem,\n ActorRefFrom,\n TODO,\n Snapshot\n} from '../types';\nimport { XSTATE_STOP } from '../constants.ts';\n\ntype CallbackSnapshot<TInput, TEvent> = Snapshot<undefined> & {\n input: TInput;\n _receivers: Set<(e: TEvent) => void>;\n _dispose: (() => void) | void;\n};\n\nexport type CallbackActorLogic<\n TEvent extends EventObject,\n TInput = unknown\n> = ActorLogic<\n CallbackSnapshot<TInput, TEvent>,\n TEvent,\n TInput,\n ActorSystem<any>\n>;\n\nexport type CallbackActorRef<\n TEvent extends EventObject,\n TInput = unknown\n> = ActorRefFrom<CallbackActorLogic<TEvent, TInput>>;\n\nexport type Receiver<TEvent extends EventObject> = (\n listener: {\n bivarianceHack(event: TEvent): void;\n }['bivarianceHack']\n) => void;\n\nexport type InvokeCallback<\n TEvent extends EventObject = AnyEventObject,\n TSentEvent extends EventObject = AnyEventObject,\n TInput = unknown\n> = ({\n input,\n system,\n self,\n sendBack,\n receive\n}: {\n /**\n * Data that was provided to the callback actor\n * @see {@link https://stately.ai/docs/input | Input docs}\n */\n input: TInput;\n /**\n * The actor system to which the callback actor belongs\n */\n system: AnyActorSystem;\n /**\n * The parent actor of the callback actor\n */\n self: CallbackActorRef<TEvent>;\n /**\n * A function that can send events back to the parent actor\n */\n sendBack: (event: TSentEvent) => void;\n /**\n * A function that can be called with a listener function argument;\n * the listener is then called whenever events are received by the callback actor\n */\n receive: Receiver<TEvent>;\n}) => (() => void) | void;\n\n/**\n * An actor logic creator which returns callback logic as defined by a callback function.\n *\n * @remarks\n * Useful for subscription-based or other free-form logic that can send events back to the parent actor.\n *\n * Actors created from callback logic (“callback actors”) can:\n * - Receive events via the `receive` function\n * - Send events to the parent actor via the `sendBack` function\n *\n * Callback actors are a bit different from other actors in that they:\n * - Do not work with `onDone` or `onError`\n * - Do not produce a snapshot using `.getSnapshot()`\n * - Do not emit values when used with `.subscribe()`\n * - Can not be stopped with `.stop()`\n *\n * @param invokeCallback - The callback function used to describe the callback logic\n * The callback function is passed an object with the following properties:\n * - `receive` - A function that can send events back to the parent actor; the listener is then called whenever events are received by the callback actor\n * - `sendBack` - A function that can send events back to the parent actor\n * - `input` - Data that was provided to the callback actor\n * - `self` - The parent actor of the callback actor\n * - `system` - The actor system to which the callback actor belongs\n * The callback function can (optionally) return a cleanup function, which is called when the actor is stopped.\n * @see {@link InvokeCallback} for more information about the callback function and its object argument\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n\n * @returns Callback logic\n *\n * @example\n * ```typescript\n * const callbackLogic = fromCallback(({ sendBack, receive }) => {\n * let lockStatus = 'unlocked';\n *\n * const handler = (event) => {\n * if (lockStatus === 'locked') {\n * return;\n * }\n * sendBack(event);\n * };\n *\n * receive((event) => {\n * if (event.type === 'lock') {\n * lockStatus = 'locked';\n * } else if (event.type === 'unlock') {\n * lockStatus = 'unlocked';\n * }\n * });\n *\n * document.body.addEventListener('click', handler);\n *\n * return () => {\n * document.body.removeEventListener('click', handler);\n * };\n * });\n * ```\n */\nexport function fromCallback<TEvent extends EventObject, TInput = unknown>(\n invokeCallback: InvokeCallback<TEvent, AnyEventObject, TInput>\n): CallbackActorLogic<TEvent, TInput> {\n const logic: CallbackActorLogic<TEvent, TInput> = {\n config: invokeCallback,\n start: (_state, { self, system }) => {\n system._relay(self, self, { type: 'xstate.create' });\n },\n transition: (state, event, { self, system }) => {\n if (event.type === 'xstate.create') {\n const sendBack = (eventForParent: AnyEventObject) => {\n if (state.status === 'stopped') {\n return;\n }\n\n if (self._parent) {\n system._relay(self, self._parent, eventForParent);\n }\n };\n\n const receive: Receiver<TEvent> = (newListener) => {\n state._receivers.add(newListener);\n };\n\n state._dispose = invokeCallback({\n input: state.input,\n system,\n self: self as TODO,\n sendBack,\n receive\n });\n\n return state;\n }\n\n if (event.type === XSTATE_STOP) {\n state = {\n ...state,\n status: 'stopped',\n error: undefined\n };\n\n if (typeof state._dispose === 'function') {\n state._dispose();\n }\n return state;\n }\n\n state._receivers.forEach((receiver) => receiver(event));\n\n return state;\n },\n getInitialState: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n input,\n _receivers: new Set(),\n _dispose: undefined\n };\n },\n getPersistedState: ({ _dispose, _receivers, ...rest }) => rest,\n restoreState: (state: any) => ({\n _receivers: new Set(),\n _dispose: undefined,\n ...state\n })\n };\n\n return logic;\n}\n","import { XSTATE_STOP } from '../constants';\nimport {\n Subscribable,\n ActorLogic,\n EventObject,\n Subscription,\n AnyActorSystem,\n ActorRefFrom,\n Snapshot\n} from '../types';\n\nexport type ObservableSnapshot<TContext, TInput> = Snapshot<undefined> & {\n context: TContext | undefined;\n input: TInput | undefined;\n _subscription: Subscription | undefined;\n};\n\nexport type ObservableActorLogic<TContext, TInput> = ActorLogic<\n ObservableSnapshot<TContext, TInput>,\n { type: string; [k: string]: unknown },\n TInput,\n AnyActorSystem\n>;\n\nexport type ObservableActorRef<TContext> = ActorRefFrom<\n ObservableActorLogic<TContext, any>\n>;\n\nexport function fromObservable<TContext, TInput>(\n observableCreator: ({\n input,\n system\n }: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActorRef<TContext>;\n }) => Subscribable<TContext>\n): ObservableActorLogic<TContext, TInput> {\n const nextEventType = '$$xstate.next';\n const errorEventType = '$$xstate.error';\n const completeEventType = '$$xstate.complete';\n\n // TODO: add event types\n const logic: ObservableActorLogic<TContext, TInput> = {\n config: observableCreator,\n transition: (snapshot, event, { self, id, defer, system }) => {\n if (snapshot.status !== 'active') {\n return snapshot;\n }\n\n switch (event.type) {\n case nextEventType: {\n const newSnapshot = {\n ...snapshot,\n context: event.data as TContext\n };\n return newSnapshot;\n }\n case errorEventType:\n return {\n ...snapshot,\n status: 'error',\n error: (event as any).data,\n input: undefined,\n _subscription: undefined\n };\n case completeEventType:\n return {\n ...snapshot,\n status: 'done',\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_STOP:\n snapshot._subscription!.unsubscribe();\n return {\n ...snapshot,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n };\n default:\n return snapshot;\n }\n },\n getInitialState: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n };\n },\n start: (state, { self, system }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n state._subscription = observableCreator({\n input: state.input!,\n system,\n self\n }).subscribe({\n next: (value) => {\n system._relay(self, self, { type: nextEventType, data: value });\n },\n error: (err) => {\n system._relay(self, self, { type: errorEventType, data: err });\n },\n complete: () => {\n system._relay(self, self, { type: completeEventType });\n }\n });\n },\n getPersistedState: ({ _subscription, ...state }) => state,\n restoreState: (state) => ({\n ...(state as any),\n _subscription: undefined\n })\n };\n\n return logic;\n}\n\n/**\n * Creates event observable logic that listens to an observable\n * that delivers event objects.\n *\n *\n * @param lazyObservable A function that creates an observable\n * @returns Event observable logic\n */\n\nexport function fromEventObservable<T extends EventObject, TInput>(\n lazyObservable: ({\n input,\n system\n }: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActorRef<T>;\n }) => Subscribable<T>\n): ObservableActorLogic<T, TInput> {\n const errorEventType = '$$xstate.error';\n const completeEventType = '$$xstate.complete';\n\n // TODO: event types\n const logic: ObservableActorLogic<T, TInput> = {\n config: lazyObservable,\n transition: (state, event) => {\n if (state.status !== 'active') {\n return state;\n }\n\n switch (event.type) {\n case errorEventType:\n return {\n ...state,\n status: 'error',\n error: (event as any).data,\n input: undefined,\n _subscription: undefined\n };\n case completeEventType:\n return {\n ...state,\n status: 'done',\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_STOP:\n state._subscription!.unsubscribe();\n return {\n ...state,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n };\n default:\n return state;\n }\n },\n getInitialState: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n };\n },\n start: (state, { self, system }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n\n state._subscription = lazyObservable({\n input: state.input!,\n system,\n self\n }).subscribe({\n next: (value) => {\n if (self._parent) {\n system._relay(self, self._parent, value);\n }\n },\n error: (err) => {\n system._relay(self, self, { type: errorEventType, data: err });\n },\n complete: () => {\n system._relay(self, self, { type: completeEventType });\n }\n });\n },\n getPersistedState: ({ _subscription, ...state }) => state,\n restoreState: (state: any) => ({\n ...state,\n _subscription: undefined\n })\n };\n\n return logic;\n}\n"],"names":["Mailbox","constructor","_process","this","_active","_current","_last","start","flush","clear","next","enqueue","event","enqueued","value","consumed","XSTATE_STOP","createErrorActorEvent","id","data","type","getDevTools","w","globalThis","self","window","__xstate__","devToolsAdapter","service","devTools","register","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","idCounter","toObserver","nextHandler","errorHandler","completionHandler","isObserver","undefined","bind","error","complete","ActorStatus","defaultOptions","clock","fn","ms","clearTimeout","logger","console","log","Actor","logic","options","_state","mailbox","delayedEventsMap","observers","Set","status","NotStarted","_parent","ref","_actorScope","_systemId","sessionId","system","_doneEvent","src","_deferred","resolvedOptions","parent","systemId","inspect","rootActor","children","Map","keyedActors","reverseKeyedActors","WeakMap","_bookId","_register","actorRef","set","_unregister","delete","get","_set","existing","Error","observer","add","_sendInspectionEvent","resolvedInspectionEvent","rootId","forEach","_relay","source","target","sourceRef","targetRef","_send","createSystem","defer","push","stopChild","child","_stop","send","_initState","state","restoreState","getInitialState","input","update","snapshot","deferredFn","shift","_stopProcedure","_complete","invokeId","output","_error","subscribe","nextListenerOrObserver","errorListener","completeListener","Stopped","unsubscribe","Running","initEvent","attachDevTools","nextState","caughtError","transition","stop","size","reportError","err2","key","Object","keys","delaySend","params","delay","timerId","to","cancel","sendId","toJSON","xstate$$type","getPersistedState","getSnapshot","fromTransition","initialContext","config","actorScope","context","_","resolveEventType","rejectEventType","emptyLogic","invokeCallback","sendBack","eventForParent","receive","newListener","_receivers","_dispose","receiver","rest","lazyObservable","errorEventType","completeEventType","_subscription","observableCreator","nextEventType","promiseCreator","resolvedValue","Promise","resolve","then","response","errorData"],"mappings":"oPAKO,MAAMA,EAKXC,YAAoBC,GAA2BC,KAA3BD,SAAAA,EAAyBC,KAJrCC,SAAmB,EAAKD,KACxBE,SAAkC,KAAIF,KACtCG,MAA+B,IAES,CAEzCC,QACLJ,KAAKC,SAAU,EACfD,KAAKK,OACP,CAEOC,QAGDN,KAAKE,WACPF,KAAKE,SAASK,KAAO,KACrBP,KAAKG,MAAQH,KAAKE,SAEtB,CAEOM,QAAQC,GACb,MAAMC,EAAW,CACfC,MAAOF,EACPF,KAAM,MAGR,GAAIP,KAAKE,SAGP,OAFAF,KAAKG,MAAOI,KAAOG,OACnBV,KAAKG,MAAQO,GAIfV,KAAKE,SAAWQ,EAChBV,KAAKG,MAAQO,EAETV,KAAKC,SACPD,KAAKK,OAET,CAEQA,QACN,KAAOL,KAAKE,UAAU,CAGpB,MAAMU,EAAWZ,KAAKE,SACtBF,KAAKD,SAASa,EAASD,OACvBX,KAAKE,SAAWU,EAASL,IAC3B,CACAP,KAAKG,MAAQ,IACf,EClDK,MAEMU,EAAc,cC4CpB,SAASC,EACdC,EACAC,GAEA,MAAO,CAAEC,KAAO,sBAAqBF,IAAMC,OAC7C,CChBA,SAASE,IACP,MAAMC,EApBoB,oBAAfC,WACFA,WAEW,oBAATC,KACFA,KAGAC,OAcT,GAAOH,EAAUI,WACf,OAAQJ,EAAUI,UAItB,CAcO,MAAMC,EAAoCC,IAK/C,MAAMC,EAAWR,IAEbQ,GACFA,EAASC,SAASF,EACpB,EC/DK,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,KAAMiJ,EAAiBlJ,KAAMyK,GAAY,GAExE,EAEHvE,gBAAiB,CAAC8C,EAAG7C,KACZ,CACLtD,OAAQ,SACR8D,YAAQnF,EACRE,WAAOF,EACP2E,UAGJsC,kBAAoBzC,GAAUA,EAC9BC,aAAeD,GAAeA,EAIlC"}
1
+ {"version":3,"file":"xstate-actors.umd.min.js","sources":["../../src/Mailbox.ts","../../src/constants.ts","../../src/eventUtils.ts","../../src/dev/index.ts","../../src/reportUnhandledError.ts","../../src/symbolObservable.ts","../../src/system.ts","../../src/utils.ts","../../src/interpreter.ts","../../src/actors/transition.ts","../../src/actors/promise.ts","../../src/actors/index.ts","../../src/actors/callback.ts","../../src/actors/observable.ts"],"sourcesContent":["interface MailboxItem<T> {\n value: T;\n next: MailboxItem<T> | null;\n}\n\nexport class Mailbox<T> {\n private _active: boolean = false;\n private _current: MailboxItem<T> | null = null;\n private _last: MailboxItem<T> | null = null;\n\n constructor(private _process: (ev: T) => void) {}\n\n public start() {\n this._active = true;\n this.flush();\n }\n\n public clear(): void {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldnt start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n\n public enqueue(event: T): void {\n const enqueued = {\n value: event,\n next: null\n };\n\n if (this._current) {\n this._last!.next = enqueued;\n this._last = enqueued;\n return;\n }\n\n this._current = enqueued;\n this._last = enqueued;\n\n if (this._active) {\n this.flush();\n }\n }\n\n private flush() {\n while (this._current) {\n // atm the given _process is responsible for implementing proper try/catch handling\n // we assume here that this won't throw in a way that can affect this mailbox\n const consumed = this._current;\n this._process(consumed.value);\n this._current = consumed.next;\n }\n this._last = null;\n }\n}\n","export const STATE_DELIMITER = '.';\nexport const TARGETLESS_KEY = '';\nexport const NULL_EVENT = '';\nexport const STATE_IDENTIFIER = '#';\nexport const WILDCARD = '*';\nexport const XSTATE_INIT = 'xstate.init';\nexport const XSTATE_ERROR = 'xstate.error';\nexport const XSTATE_STOP = 'xstate.stop';\n","import { XSTATE_INIT } from './constants.ts';\nimport { DoneActorEvent, DoneStateEvent, ErrorActorEvent } from './types.ts';\n\n/**\n * Returns an event that represents an implicit event that\n * is sent after the specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nexport function createAfterEvent(delayRef: number | string, id?: string) {\n const idSuffix = id ? `#${id}` : '';\n return { type: `xstate.after(${delayRef})${idSuffix}` } as const;\n}\n\n/**\n * Returns an event that represents that a final state node\n * has been reached in the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nexport function createDoneStateEvent(\n id: string,\n output?: unknown\n): DoneStateEvent {\n return {\n type: `xstate.done.state.${id}`,\n output\n };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state node,\n * but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n */\nexport function createDoneActorEvent(\n invokeId: string,\n output?: unknown\n): DoneActorEvent {\n return {\n type: `xstate.done.actor.${invokeId}`,\n output\n };\n}\n\nexport function createErrorActorEvent(\n id: string,\n data?: unknown\n): ErrorActorEvent {\n return { type: `xstate.error.actor.${id}`, data };\n}\n\nexport function createInitEvent(input: unknown) {\n return { type: XSTATE_INIT, input } as const;\n}\n","import isDevelopment from '#is-development';\nimport { AnyActor, DevToolsAdapter } from '../types.ts';\n\ninterface DevInterface {\n services: Set<AnyActor>;\n register(service: AnyActor): void;\n onRegister(listener: ServiceListener): void;\n}\ntype ServiceListener = (service: AnyActor) => void;\n\nexport interface XStateDevInterface {\n register: (service: AnyActor) => void;\n unregister: (service: AnyActor) => void;\n onRegister: (listener: ServiceListener) => {\n unsubscribe: () => void;\n };\n services: Set<AnyActor>;\n}\n\n// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\nexport function getGlobal(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (isDevelopment) {\n console.warn(\n 'XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues'\n );\n }\n}\n\nfunction getDevTools(): DevInterface | undefined {\n const w = getGlobal();\n if (!!(w as any).__xstate__) {\n return (w as any).__xstate__;\n }\n\n return undefined;\n}\n\nexport function registerService(service: AnyActor) {\n if (typeof window === 'undefined') {\n return;\n }\n\n const devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n}\n\nexport const devToolsAdapter: DevToolsAdapter = (service) => {\n if (typeof window === 'undefined') {\n return;\n }\n\n const devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n};\n","/**\n * This function makes sure that unhandled errors are thrown in a separate macrotask.\n * It allows those errors to be detected by global error handlers and reported to bug tracking services\n * without interrupting our own stack of execution.\n *\n * @param err error to be thrown\n */\nexport function reportUnhandledError(err: unknown) {\n setTimeout(() => {\n throw err;\n });\n}\n","export const symbolObservable: typeof Symbol.observable = (() =>\n (typeof Symbol === 'function' && Symbol.observable) ||\n '@@observable')() as any;\n","import {\n AnyEventObject,\n ActorSystem,\n ActorSystemInfo,\n AnyActorRef,\n Observer,\n Snapshot\n} from './types.ts';\n\nlet idCounter = 0;\nexport function createSystem<T extends ActorSystemInfo>(\n rootActor: AnyActorRef\n): ActorSystem<T> {\n const children = new Map<string, AnyActorRef>();\n const keyedActors = new Map<keyof T['actors'], AnyActorRef | undefined>();\n const reverseKeyedActors = new WeakMap<AnyActorRef, keyof T['actors']>();\n const observers = new Set<Observer<InspectionEvent>>();\n\n const system: ActorSystem<T> = {\n _bookId: () => `x:${idCounter++}`,\n _register: (sessionId, actorRef) => {\n children.set(sessionId, actorRef);\n return sessionId;\n },\n _unregister: (actorRef) => {\n children.delete(actorRef.sessionId);\n const systemId = reverseKeyedActors.get(actorRef);\n\n if (systemId !== undefined) {\n keyedActors.delete(systemId);\n reverseKeyedActors.delete(actorRef);\n }\n },\n get: (systemId) => {\n return keyedActors.get(systemId) as T['actors'][any];\n },\n _set: (systemId, actorRef) => {\n const existing = keyedActors.get(systemId);\n if (existing && existing !== actorRef) {\n throw new Error(\n `Actor with system ID '${systemId as string}' already exists.`\n );\n }\n\n keyedActors.set(systemId, actorRef);\n reverseKeyedActors.set(actorRef, systemId);\n },\n inspect: (observer) => {\n observers.add(observer);\n },\n _sendInspectionEvent: (event) => {\n const resolvedInspectionEvent: InspectionEvent = {\n ...event,\n rootId: rootActor.sessionId\n };\n observers.forEach((observer) => observer.next?.(resolvedInspectionEvent));\n },\n _relay: (source, target, event) => {\n system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: source,\n actorRef: target,\n event\n });\n\n target._send(event);\n }\n };\n\n return system;\n}\nexport interface BaseInspectionEventProperties {\n rootId: string; // the session ID of the root\n /**\n * The relevant actorRef for the inspection event.\n * - For snapshot events, this is the `actorRef` of the snapshot.\n * - For event events, this is the target `actorRef` (recipient of event).\n * - For actor events, this is the `actorRef` of the registered actor.\n */\n actorRef: AnyActorRef;\n}\n\nexport interface InspectedSnapshotEvent extends BaseInspectionEventProperties {\n type: '@xstate.snapshot';\n event: AnyEventObject; // { type: string, ... }\n snapshot: Snapshot<unknown>;\n}\n\nexport interface InspectedEventEvent extends BaseInspectionEventProperties {\n type: '@xstate.event';\n // The source might not exist, e.g. when:\n // - root init events\n // - events sent from external (non-actor) sources\n sourceRef: AnyActorRef | undefined;\n event: AnyEventObject; // { type: string, ... }\n}\n\nexport interface InspectedActorEvent extends BaseInspectionEventProperties {\n type: '@xstate.actor';\n}\n\nexport type InspectionEvent =\n | InspectedSnapshotEvent\n | InspectedEventEvent\n | InspectedActorEvent;\n","import isDevelopment from '#is-development';\nimport { AnyActorLogic, AnyState } from './index.ts';\nimport { STATE_DELIMITER, TARGETLESS_KEY } from './constants.ts';\nimport type { StateNode } from './StateNode.ts';\nimport type {\n ActorLogic,\n AnyEventObject,\n EventObject,\n MachineContext,\n Mapper,\n Observer,\n ErrorActorEvent,\n SingleOrArray,\n StateLike,\n StateValue,\n Subscribable,\n TransitionConfigTarget,\n AnyActorRef,\n AnyTransitionConfig,\n NonReducibleUnknown,\n AnyStateMachine,\n InvokeConfig\n} from './types.ts';\n\nexport function keys<T extends object>(value: T): Array<keyof T & string> {\n return Object.keys(value) as Array<keyof T & string>;\n}\n\nexport function matchesState(\n parentStateId: StateValue,\n childStateId: StateValue\n): boolean {\n const parentStateValue = toStateValue(parentStateId);\n const childStateValue = toStateValue(childStateId);\n\n if (typeof childStateValue === 'string') {\n if (typeof parentStateValue === 'string') {\n return childStateValue === parentStateValue;\n }\n\n // Parent more specific than child\n return false;\n }\n\n if (typeof parentStateValue === 'string') {\n return parentStateValue in childStateValue;\n }\n\n return Object.keys(parentStateValue).every((key) => {\n if (!(key in childStateValue)) {\n return false;\n }\n\n return matchesState(parentStateValue[key], childStateValue[key]);\n });\n}\n\nexport function toStatePath(stateId: string | string[]): string[] {\n try {\n if (isArray(stateId)) {\n return stateId;\n }\n\n return stateId.toString().split(STATE_DELIMITER);\n } catch (e) {\n throw new Error(`'${stateId}' is not a valid state path.`);\n }\n}\n\nexport function isStateLike(state: any): state is AnyState {\n return (\n typeof state === 'object' &&\n 'value' in state &&\n 'context' in state &&\n 'event' in state\n );\n}\n\nexport function toStateValue(\n stateValue: StateLike<any> | StateValue | string[]\n): StateValue {\n if (isStateLike(stateValue)) {\n return stateValue.value;\n }\n\n if (isArray(stateValue)) {\n return pathToStateValue(stateValue);\n }\n\n if (typeof stateValue !== 'string') {\n return stateValue as StateValue;\n }\n\n const statePath = toStatePath(stateValue as string);\n\n return pathToStateValue(statePath);\n}\n\nexport function pathToStateValue(statePath: string[]): StateValue {\n if (statePath.length === 1) {\n return statePath[0];\n }\n\n const value: StateValue = {};\n let marker = value;\n\n for (let i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n const previous = marker;\n marker = {};\n previous[statePath[i]] = marker;\n }\n }\n\n return value;\n}\n\nexport function mapValues<P, O extends Record<string, unknown>>(\n collection: O,\n iteratee: (item: O[keyof O], key: keyof O, collection: O, i: number) => P\n): { [key in keyof O]: P };\nexport function mapValues(\n collection: Record<string, unknown>,\n iteratee: (\n item: unknown,\n key: string,\n collection: Record<string, unknown>,\n i: number\n ) => unknown\n) {\n const result: Record<string, unknown> = {};\n\n const collectionKeys = Object.keys(collection);\n for (let i = 0; i < collectionKeys.length; i++) {\n const key = collectionKeys[i];\n result[key] = iteratee(collection[key], key, collection, i);\n }\n\n return result;\n}\n\nexport function mapFilterValues<T, P>(\n collection: { [key: string]: T },\n iteratee: (item: T, key: string, collection: { [key: string]: T }) => P,\n predicate: (item: T) => boolean\n): { [key: string]: P } {\n const result: { [key: string]: P } = {};\n\n for (const key of Object.keys(collection)) {\n const item = collection[key];\n\n if (!predicate(item)) {\n continue;\n }\n\n result[key] = iteratee(item, key, collection);\n }\n\n return result;\n}\n\n/**\n * Retrieves a value at the given path.\n * @param props The deep path to the prop of the desired value\n */\nexport function path<T extends Record<string, any>>(props: string[]): any {\n return (object: T): any => {\n let result: T = object;\n\n for (const prop of props) {\n result = result[prop as keyof typeof result];\n }\n\n return result;\n };\n}\n\nexport function toStatePaths(stateValue: StateValue | undefined): string[][] {\n if (!stateValue) {\n return [[]];\n }\n\n if (typeof stateValue === 'string') {\n return [[stateValue]];\n }\n\n const result = flatten(\n Object.keys(stateValue).map((key) => {\n const subStateValue = stateValue[key];\n\n if (\n typeof subStateValue !== 'string' &&\n (!subStateValue || !Object.keys(subStateValue).length)\n ) {\n return [[key]];\n }\n\n return toStatePaths(stateValue[key]).map((subPath) => {\n return [key].concat(subPath);\n });\n })\n );\n\n return result;\n}\n\nexport function flatten<T>(array: Array<T | T[]>): T[] {\n return ([] as T[]).concat(...array);\n}\n\nexport function toArrayStrict<T>(value: readonly T[] | T): readonly T[] {\n if (isArray(value)) {\n return value;\n }\n return [value];\n}\n\nexport function toArray<T>(value: readonly T[] | T | undefined): readonly T[] {\n if (value === undefined) {\n return [];\n }\n return toArrayStrict(value);\n}\n\nexport function resolveOutput<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n>(\n mapper:\n | Mapper<TContext, TExpressionEvent, unknown, EventObject>\n | NonReducibleUnknown,\n context: TContext,\n event: TExpressionEvent,\n self: AnyActorRef\n): unknown {\n if (typeof mapper === 'function') {\n return mapper({ context, event, self });\n }\n\n if (\n isDevelopment &&\n !!mapper &&\n typeof mapper === 'object' &&\n Object.values(mapper).some((val) => typeof val === 'function')\n ) {\n console.warn(\n `Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.\\nFound object containing properties whose values are possibly mapping functions: ${Object.entries(\n mapper\n )\n .filter(([key, value]) => typeof value === 'function')\n .map(\n ([key, value]) =>\n `\\n - ${key}: ${(value as () => any)\n .toString()\n .replace(/\\n\\s*/g, '')}`\n )\n .join('')}`\n );\n }\n\n return mapper;\n}\n\nexport function isBuiltInEvent(eventType: string): boolean {\n return /^(done|error)\\./.test(eventType);\n}\n\nexport function isPromiseLike(value: any): value is PromiseLike<any> {\n if (value instanceof Promise) {\n return true;\n }\n // Check if shape matches the Promise/A+ specification for a \"thenable\".\n if (\n value !== null &&\n (typeof value === 'function' || typeof value === 'object') &&\n typeof value.then === 'function'\n ) {\n return true;\n }\n return false;\n}\n\nexport function isActorLogic(value: any): value is ActorLogic<any, any> {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'transition' in value &&\n typeof value.transition === 'function'\n );\n}\n\nexport function partition<T, A extends T, B extends T>(\n items: T[],\n predicate: (item: T) => item is A\n): [A[], B[]] {\n const [truthy, falsy] = [[], []] as [A[], B[]];\n\n for (const item of items) {\n if (predicate(item)) {\n truthy.push(item);\n } else {\n falsy.push(item as B);\n }\n }\n\n return [truthy, falsy];\n}\n\nexport function isArray(value: any): value is readonly any[] {\n return Array.isArray(value);\n}\n\nexport function isObservable<T>(value: any): value is Subscribable<T> {\n return (\n !!value && 'subscribe' in value && typeof value.subscribe === 'function'\n );\n}\n\nexport function isErrorActorEvent(\n event: AnyEventObject\n): event is ErrorActorEvent {\n return event.type.startsWith('xstate.error.actor');\n}\n\nexport function toTransitionConfigArray<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n configLike: SingleOrArray<AnyTransitionConfig | TransitionConfigTarget>\n): Array<AnyTransitionConfig> {\n return toArrayStrict(configLike).map((transitionLike) => {\n if (\n typeof transitionLike === 'undefined' ||\n typeof transitionLike === 'string'\n ) {\n return { target: transitionLike };\n }\n\n return transitionLike;\n });\n}\n\nexport function normalizeTarget<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n target: SingleOrArray<string | StateNode<TContext, TEvent>> | undefined\n): ReadonlyArray<string | StateNode<TContext, TEvent>> | undefined {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n return toArray(target);\n}\n\nexport function reportUnhandledExceptionOnInvocation(\n originalError: any,\n currentError: any,\n id: string\n) {\n if (isDevelopment) {\n const originalStackTrace = originalError.stack\n ? ` Stacktrace was '${originalError.stack}'`\n : '';\n if (originalError === currentError) {\n // tslint:disable-next-line:no-console\n console.error(\n `Missing onError handler for invocation '${id}', error was '${originalError}'.${originalStackTrace}`\n );\n } else {\n const stackTrace = currentError.stack\n ? ` Stacktrace was '${currentError.stack}'`\n : '';\n // tslint:disable-next-line:no-console\n console.error(\n `Missing onError handler and/or unhandled exception/promise rejection for invocation '${id}'. ` +\n `Original error: '${originalError}'. ${originalStackTrace} Current error is '${currentError}'.${stackTrace}`\n );\n }\n }\n}\n\nexport function toObserver<T>(\n nextHandler?: Observer<T> | ((value: T) => void),\n errorHandler?: (error: any) => void,\n completionHandler?: () => void\n): Observer<T> {\n const isObserver = typeof nextHandler === 'object';\n const self = isObserver ? nextHandler : undefined;\n\n return {\n next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(\n self\n )\n };\n}\n\nexport function createInvokeId(stateNodeId: string, index: number): string {\n return `${stateNodeId}[${index}]`;\n}\n\nexport function resolveReferencedActor(machine: AnyStateMachine, src: string) {\n if (src.startsWith('xstate#')) {\n const [, indexStr] = src.match(/\\[(\\d+)\\]$/)!;\n const node = machine.getStateNodeById(src.slice(7, -(indexStr.length + 2)));\n const invokeConfig = node.config.invoke!;\n return {\n src: (Array.isArray(invokeConfig)\n ? invokeConfig[indexStr as any]\n : (invokeConfig as InvokeConfig<any, any, any, any, any, any>)\n ).src,\n input: undefined\n };\n }\n const referenced = machine.implementations.actors[src];\n return referenced\n ? 'transition' in referenced\n ? { src: referenced, input: undefined }\n : referenced\n : undefined;\n}\n","import isDevelopment from '#is-development';\nimport { Mailbox } from './Mailbox.ts';\nimport {\n createDoneActorEvent,\n createErrorActorEvent,\n createInitEvent\n} from './eventUtils.ts';\nimport { XSTATE_STOP } from './constants.ts';\nimport { devToolsAdapter } from './dev/index.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { symbolObservable } from './symbolObservable.ts';\nimport { createSystem } from './system.ts';\nimport {\n AreAllImplementationsAssumedToBeProvided,\n MissingImplementationsError\n} from './typegenTypes.ts';\nimport type {\n ActorScope,\n ActorSystem,\n AnyActorLogic,\n AnyStateMachine,\n EventFromLogic,\n SnapshotFrom,\n AnyActorRef,\n DoneActorEvent,\n Snapshot\n} from './types.ts';\nimport {\n ActorRef,\n EventObject,\n InteropSubscribable,\n ActorOptions,\n Observer,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\n\nexport const $$ACTOR_TYPE = 1;\n\nexport type SnapshotListener<TLogic extends AnyActorLogic> = (\n state: SnapshotFrom<TLogic>\n) => void;\n\nexport type EventListener<TEvent extends EventObject = EventObject> = (\n event: TEvent\n) => void;\n\nexport type Listener = () => void;\nexport type ErrorListener = (error: any) => void;\n\nexport interface Clock {\n setTimeout(fn: (...args: any[]) => void, timeout: number): any;\n clearTimeout(id: any): void;\n}\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nexport enum ProcessingStatus {\n NotStarted = 0,\n Running = 1,\n Stopped = 2\n}\n\nconst defaultOptions = {\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: (id) => {\n return clearTimeout(id);\n }\n } as Clock,\n logger: console.log.bind(console),\n devTools: false\n};\n\n/**\n * An Actor is a running process that can receive events, send events and change its behavior based on the events it receives, which can cause effects outside of the actor. When you run a state machine, it becomes an actor.\n */\nexport class Actor<TLogic extends AnyActorLogic>\n implements ActorRef<EventFromLogic<TLogic>, SnapshotFrom<TLogic>>\n{\n /**\n * The current internal state of the actor.\n */\n private _state!: SnapshotFrom<TLogic>;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.\n */\n public clock: Clock;\n public options: Readonly<ActorOptions<TLogic>>;\n\n /**\n * The unique identifier for this actor relative to its parent.\n */\n public id: string;\n\n private mailbox: Mailbox<EventFromLogic<TLogic>> = new Mailbox(\n this._process.bind(this)\n );\n\n private delayedEventsMap: Record<string, unknown> = {};\n\n private observers: Set<Observer<SnapshotFrom<TLogic>>> = new Set();\n private logger: (...args: any[]) => void;\n\n /** @internal */\n public _processingStatus: ProcessingStatus = ProcessingStatus.NotStarted;\n\n // Actor Ref\n public _parent?: ActorRef<any, any>;\n public ref: ActorRef<EventFromLogic<TLogic>, SnapshotFrom<TLogic>>;\n // TODO: add typings for system\n private _actorScope: ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n any\n >;\n\n private _systemId: string | undefined;\n\n /**\n * The globally unique process ID for this invocation.\n */\n public sessionId: string;\n\n /**\n * The system to which this actor belongs.\n */\n public system: ActorSystem<any>;\n private _doneEvent?: DoneActorEvent;\n\n public src: string | AnyActorLogic;\n\n /**\n * Creates a new actor instance for the given logic with the provided options, if any.\n *\n * @param logic The logic to create an actor from\n * @param options Actor options\n */\n constructor(public logic: TLogic, options?: ActorOptions<TLogic>) {\n const resolvedOptions = {\n ...defaultOptions,\n ...options\n } as ActorOptions<TLogic> & typeof defaultOptions;\n\n const { clock, logger, parent, id, systemId, inspect } = resolvedOptions;\n\n this.system = parent?.system ?? createSystem(this);\n\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n\n this.sessionId = this.system._bookId();\n this.id = id ?? this.sessionId;\n this.logger = logger;\n this.clock = clock;\n this._parent = parent;\n this.options = resolvedOptions;\n this.src = resolvedOptions.src ?? logic;\n this.ref = this;\n this._actorScope = {\n self: this,\n id: this.id,\n sessionId: this.sessionId,\n logger: this.logger,\n defer: (fn) => {\n this._deferred.push(fn);\n },\n system: this.system,\n stopChild: (child) => {\n if (child._parent !== this) {\n throw new Error(\n `Cannot stop child actor ${child.id} of ${this.id} because it is not a child`\n );\n }\n (child as any)._stop();\n }\n };\n\n // Ensure that the send method is bound to this Actor instance\n // if destructured\n this.send = this.send.bind(this);\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this\n });\n this._initState(options?.state);\n\n if (systemId && (this._state as any).status === 'active') {\n this._systemId = systemId;\n this.system._set(systemId, this);\n }\n }\n\n private _initState(persistedState?: Snapshot<unknown>) {\n this._state = persistedState\n ? this.logic.restoreState\n ? this.logic.restoreState(persistedState, this._actorScope)\n : persistedState\n : this.logic.getInitialState(this._actorScope, this.options?.input);\n }\n\n // array of functions to defer\n private _deferred: Array<() => void> = [];\n\n private update(snapshot: SnapshotFrom<TLogic>, event: EventObject): void {\n // Update state\n this._state = snapshot;\n\n // Execute deferred effects\n let deferredFn: (typeof this._deferred)[number] | undefined;\n\n while ((deferredFn = this._deferred.shift())) {\n deferredFn();\n }\n\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n\n switch ((this._state as any).status) {\n case 'done':\n this._stopProcedure();\n this._complete();\n this._doneEvent = createDoneActorEvent(\n this.id,\n (this._state as any).output\n );\n if (this._parent) {\n this.system._relay(this, this._parent, this._doneEvent);\n }\n\n break;\n case 'error':\n this._stopProcedure();\n this._error((this._state as any).error);\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createErrorActorEvent(this.id, (this._state as any).error)\n );\n }\n break;\n }\n this.system._sendInspectionEvent({\n type: '@xstate.snapshot',\n actorRef: this,\n event,\n snapshot\n });\n }\n\n /**\n * Subscribe an observer to an actor’s snapshot values.\n *\n * @remarks\n * The observer will receive the actor’s snapshot value when it is emitted. The observer can be:\n * - A plain function that receives the latest snapshot, or\n * - An observer object whose `.next(snapshot)` method receives the latest snapshot\n *\n * @example\n * ```ts\n * // Observer as a plain function\n * const subscription = actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * ```\n *\n * @example\n * ```ts\n * // Observer as an object\n * const subscription = actor.subscribe({\n * next(snapshot) {\n * console.log(snapshot);\n * },\n * error(err) {\n * // ...\n * },\n * complete() {\n * // ...\n * },\n * });\n * ```\n *\n * The return value of `actor.subscribe(observer)` is a subscription object that has an `.unsubscribe()` method. You can call `subscription.unsubscribe()` to unsubscribe the observer:\n *\n * @example\n * ```ts\n * const subscription = actor.subscribe((snapshot) => {\n * // ...\n * });\n *\n * // Unsubscribe the observer\n * subscription.unsubscribe();\n * ```\n *\n * When the actor is stopped, all of its observers will automatically be unsubscribed.\n *\n * @param observer - Either a plain function that receives the latest snapshot, or an observer object whose `.next(snapshot)` method receives the latest snapshot\n */\n public subscribe(observer: Observer<SnapshotFrom<TLogic>>): Subscription;\n public subscribe(\n nextListener?: (state: SnapshotFrom<TLogic>) => void,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription;\n public subscribe(\n nextListenerOrObserver?:\n | ((state: SnapshotFrom<TLogic>) => void)\n | Observer<SnapshotFrom<TLogic>>,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription {\n const observer = toObserver(\n nextListenerOrObserver,\n errorListener,\n completeListener\n );\n\n if (this._processingStatus !== ProcessingStatus.Stopped) {\n this.observers.add(observer);\n } else {\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n\n return {\n unsubscribe: () => {\n this.observers.delete(observer);\n }\n };\n }\n\n /**\n * Starts the Actor from the initial state\n */\n public start(): this {\n if (this._processingStatus === ProcessingStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n\n this.system._register(this.sessionId, this);\n if (this._systemId) {\n this.system._set(this._systemId, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n // TODO: this isn't correct when rehydrating\n const initEvent = createInitEvent(this.options.input);\n\n this.system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: this._parent,\n actorRef: this,\n event: initEvent\n });\n\n const status = (this._state as any).status;\n\n switch (status) {\n case 'done':\n // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n // we still need to complete observers, flush deferreds etc\n this.update(\n this._state,\n initEvent as unknown as EventFromLogic<TLogic>\n );\n // fallthrough\n case 'error':\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n }\n\n if (this.logic.start) {\n try {\n this.logic.start(this._state, this._actorScope);\n } catch (err) {\n this._stopProcedure();\n this._error(err);\n this._parent?.send(createErrorActorEvent(this.id, err));\n return this;\n }\n }\n\n // TODO: this notifies all subscribers but usually this is redundant\n // there is no real change happening here\n // we need to rethink if this needs to be refactored\n this.update(this._state, initEvent as unknown as EventFromLogic<TLogic>);\n\n if (this.options.devTools) {\n this.attachDevTools();\n }\n\n this.mailbox.start();\n\n return this;\n }\n\n private _process(event: EventFromLogic<TLogic>) {\n // TODO: reexamine what happens when an action (or a guard or smth) throws\n let nextState;\n let caughtError;\n try {\n nextState = this.logic.transition(this._state, event, this._actorScope);\n } catch (err) {\n // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n caughtError = { err };\n }\n\n if (caughtError) {\n const { err } = caughtError;\n\n this._stopProcedure();\n this._error(err);\n this._parent?.send(createErrorActorEvent(this.id, err));\n return;\n }\n\n this.update(nextState, event);\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n\n private _stop(): this {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n this.mailbox.clear();\n if (this._processingStatus === ProcessingStatus.NotStarted) {\n this._processingStatus = ProcessingStatus.Stopped;\n return this;\n }\n this.mailbox.enqueue({ type: XSTATE_STOP } as any);\n\n return this;\n }\n\n /**\n * Stops the Actor and unsubscribe all listeners.\n */\n public stop(): this {\n if (this._parent) {\n throw new Error('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n private _complete(): void {\n for (const observer of this.observers) {\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n this.observers.clear();\n }\n private _error(err: unknown): void {\n if (!this.observers.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n return;\n }\n let reportError = false;\n\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n try {\n errorListener?.(err);\n } catch (err2) {\n reportUnhandledError(err2);\n }\n }\n this.observers.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n private _stopProcedure(): this {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return this;\n }\n\n // Cancel all delayed events\n for (const key of Object.keys(this.delayedEventsMap)) {\n this.clock.clearTimeout(this.delayedEventsMap[key]);\n }\n\n // TODO: mailbox.reset\n this.mailbox.clear();\n // TODO: after `stop` we must prepare ourselves for receiving events again\n // events sent *after* stop signal must be queued\n // it seems like this should be the common behavior for all of our consumers\n // so perhaps this should be unified somehow for all of them\n this.mailbox = new Mailbox(this._process.bind(this));\n\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n\n return this;\n }\n\n /**\n * @internal\n */\n public _send(event: EventFromLogic<TLogic>) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n // do nothing\n if (isDevelopment) {\n const eventString = JSON.stringify(event);\n\n console.warn(\n `Event \"${event.type}\" was sent to stopped actor \"${this.id} (${this.sessionId})\". This actor has already reached its final state, and will not transition.\\nEvent: ${eventString}`\n );\n }\n return;\n }\n\n this.mailbox.enqueue(event);\n }\n\n /**\n * Sends an event to the running Actor to trigger a transition.\n *\n * @param event The event to send\n */\n public send(event: EventFromLogic<TLogic>) {\n if (isDevelopment && typeof event === 'string') {\n throw new Error(\n `Only event objects may be sent to actors; use .send({ type: \"${event}\" }) instead`\n );\n }\n this.system._relay(undefined, this, event);\n }\n\n /**\n * TODO: figure out a way to do this within the machine\n * @internal\n */\n public delaySend(params: {\n event: EventObject;\n id: string | undefined;\n delay: number;\n to?: AnyActorRef;\n }): void {\n const { event, id, delay } = params;\n const timerId = this.clock.setTimeout(() => {\n this.system._relay(\n this,\n params.to ?? this,\n event as EventFromLogic<TLogic>\n );\n }, delay);\n\n // TODO: consider the rehydration story here\n if (id) {\n this.delayedEventsMap[id] = timerId;\n }\n }\n\n /**\n * TODO: figure out a way to do this within the machine\n * @internal\n */\n public cancel(sendId: string | number): void {\n this.clock.clearTimeout(this.delayedEventsMap[sendId]);\n delete this.delayedEventsMap[sendId];\n }\n\n private attachDevTools(): void {\n const { devTools } = this.options;\n if (devTools) {\n const resolvedDevToolsAdapter =\n typeof devTools === 'function' ? devTools : devToolsAdapter;\n\n resolvedDevToolsAdapter(this);\n }\n }\n public toJSON() {\n return {\n xstate$$type: $$ACTOR_TYPE,\n id: this.id\n };\n }\n\n public getPersistedState(): Snapshot<unknown>;\n public getPersistedState(options?: unknown): Snapshot<unknown> {\n return this.logic.getPersistedState(this._state, options);\n }\n\n public [symbolObservable](): InteropSubscribable<SnapshotFrom<TLogic>> {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot represent an actor's last emitted value.\n *\n * When an actor receives an event, its internal state may change.\n * An actor may emit a snapshot when a state transition occurs.\n *\n * Note that some actors, such as callback actors generated with `fromCallback`, will not emit snapshots.\n *\n * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n * @see {@link Actor.getPersistedState} to persist the internal state of an actor (which is more than just a snapshot).\n */\n public getSnapshot(): SnapshotFrom<TLogic> {\n return this._state;\n }\n}\n\n/**\n * Creates a new `ActorRef` instance for the given machine with the provided options, if any.\n *\n * @param machine The machine to create an actor from\n * @param options `ActorRef` options\n */\nexport function createActor<TMachine extends AnyStateMachine>(\n machine: AreAllImplementationsAssumedToBeProvided<\n TMachine['__TResolvedTypesMeta']\n > extends true\n ? TMachine\n : MissingImplementationsError<TMachine['__TResolvedTypesMeta']>,\n options?: ActorOptions<TMachine>\n): Actor<TMachine>;\nexport function createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options?: ActorOptions<TLogic>\n): Actor<TLogic>;\nexport function createActor(logic: any, options?: ActorOptions<any>): any {\n const interpreter = new Actor(logic, options);\n\n return interpreter;\n}\n\n/**\n * Creates a new Interpreter instance for the given machine with the provided options, if any.\n *\n * @deprecated Use `createActor` instead\n */\nexport const interpret = createActor;\n\n/**\n * @deprecated Use `Actor` instead.\n */\nexport type Interpreter = typeof Actor;\n","import {\n ActorLogic,\n ActorScope,\n ActorSystem,\n EventObject,\n ActorRefFrom,\n AnyActorSystem,\n Snapshot\n} from '../types';\n\nexport type TransitionSnapshot<TContext> = Snapshot<undefined> & {\n context: TContext;\n};\n\nexport type TransitionActorLogic<\n TContext,\n TEvent extends EventObject,\n TInput\n> = ActorLogic<TransitionSnapshot<TContext>, TEvent, TInput, AnyActorSystem>;\n\nexport type TransitionActorRef<\n TContext,\n TEvent extends EventObject\n> = ActorRefFrom<\n TransitionActorLogic<TransitionSnapshot<TContext>, TEvent, unknown>\n>;\n\n/**\n * Returns actor logic from a transition function and its initial state.\n *\n * A transition function is a function that takes the current state and an event and returns the next state.\n *\n * @param transition The transition function that returns the next state given the current state and event.\n * @param initialContext The initial state of the transition function.\n * @returns Actor logic\n */\nexport function fromTransition<\n TContext,\n TEvent extends EventObject,\n TSystem extends ActorSystem<any>,\n TInput\n>(\n transition: (\n state: TContext,\n event: TEvent,\n actorScope: ActorScope<TransitionSnapshot<TContext>, TEvent, TSystem>\n ) => TContext,\n initialContext:\n | TContext\n | (({\n input,\n self\n }: {\n input: TInput;\n self: TransitionActorRef<TContext, TEvent>;\n }) => TContext) // TODO: type\n): TransitionActorLogic<TContext, TEvent, TInput> {\n return {\n config: transition,\n transition: (state, event, actorScope) => {\n return {\n ...state,\n context: transition(state.context, event as TEvent, actorScope as any)\n };\n },\n getInitialState: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context:\n typeof initialContext === 'function'\n ? (initialContext as any)({ input })\n : initialContext\n };\n },\n getPersistedState: (state) => state,\n restoreState: (state: any) => state\n };\n}\n","import {\n ActorLogic,\n ActorRefFrom,\n ActorSystem,\n AnyActorSystem,\n Snapshot\n} from '../types';\nimport { XSTATE_STOP } from '../constants';\n\nexport type PromiseSnapshot<TOutput, TInput> = Snapshot<TOutput> & {\n input: TInput | undefined;\n};\n\nconst resolveEventType = '$$xstate.resolve';\nconst rejectEventType = '$$xstate.reject';\n\nexport type PromiseActorEvents<T> =\n | {\n type: typeof resolveEventType;\n data: T;\n }\n | {\n type: typeof rejectEventType;\n data: any;\n }\n | {\n type: typeof XSTATE_STOP;\n };\n\nexport type PromiseActorLogic<TOutput, TInput = unknown> = ActorLogic<\n PromiseSnapshot<TOutput, TInput>,\n { type: string; [k: string]: unknown },\n TInput, // input\n ActorSystem<any>\n>;\n\nexport type PromiseActorRef<TOutput> = ActorRefFrom<\n PromiseActorLogic<TOutput, unknown>\n>;\n\nexport function fromPromise<TOutput, TInput = unknown>(\n // TODO: add types\n promiseCreator: ({\n input,\n system\n }: {\n input: TInput;\n system: AnyActorSystem;\n self: PromiseActorRef<TOutput>;\n }) => PromiseLike<TOutput>\n): PromiseActorLogic<TOutput, TInput> {\n // TODO: add event types\n const logic: PromiseActorLogic<TOutput, TInput> = {\n config: promiseCreator,\n transition: (state, event) => {\n if (state.status !== 'active') {\n return state;\n }\n\n switch (event.type) {\n case resolveEventType: {\n const resolvedValue = (event as any).data;\n return {\n ...state,\n status: 'done',\n output: resolvedValue,\n input: undefined\n };\n }\n case rejectEventType:\n return {\n ...state,\n status: 'error',\n error: (event as any).data,\n input: undefined\n };\n case XSTATE_STOP:\n return {\n ...state,\n status: 'stopped',\n input: undefined\n };\n default:\n return state;\n }\n },\n start: (state, { self, system }) => {\n // TODO: determine how to allow customizing this so that promises\n // can be restarted if necessary\n if (state.status !== 'active') {\n return;\n }\n\n const resolvedPromise = Promise.resolve(\n promiseCreator({ input: state.input!, system, self })\n );\n\n resolvedPromise.then(\n (response) => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n system._relay(self, self, { type: resolveEventType, data: response });\n },\n (errorData) => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n system._relay(self, self, { type: rejectEventType, data: errorData });\n }\n );\n },\n getInitialState: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n };\n },\n getPersistedState: (state) => state,\n restoreState: (state: any) => state\n };\n\n return logic;\n}\n","import { createActor } from '../interpreter.ts';\nimport type { ActorRef, AnyEventObject, Snapshot } from '../types.ts';\nimport { fromTransition } from './transition.ts';\nexport { fromCallback, type CallbackActorLogic } from './callback.ts';\nexport {\n fromEventObservable,\n fromObservable,\n type ObservableActorLogic\n} from './observable.ts';\nexport { fromPromise, type PromiseActorLogic } from './promise.ts';\nexport {\n fromTransition,\n type TransitionActorLogic,\n type TransitionSnapshot\n} from './transition.ts';\n\nconst emptyLogic = fromTransition((_) => undefined, undefined);\n\nexport function createEmptyActor(): ActorRef<\n AnyEventObject,\n Snapshot<undefined>\n> {\n return createActor(emptyLogic);\n}\n","import {\n ActorLogic,\n EventObject,\n AnyActorSystem,\n AnyEventObject,\n ActorSystem,\n ActorRefFrom,\n TODO,\n Snapshot\n} from '../types';\nimport { XSTATE_STOP } from '../constants.ts';\n\ntype CallbackSnapshot<TInput, TEvent> = Snapshot<undefined> & {\n input: TInput;\n _receivers: Set<(e: TEvent) => void>;\n _dispose: (() => void) | void;\n};\n\nexport type CallbackActorLogic<\n TEvent extends EventObject,\n TInput = unknown\n> = ActorLogic<\n CallbackSnapshot<TInput, TEvent>,\n TEvent,\n TInput,\n ActorSystem<any>\n>;\n\nexport type CallbackActorRef<\n TEvent extends EventObject,\n TInput = unknown\n> = ActorRefFrom<CallbackActorLogic<TEvent, TInput>>;\n\nexport type Receiver<TEvent extends EventObject> = (\n listener: {\n bivarianceHack(event: TEvent): void;\n }['bivarianceHack']\n) => void;\n\nexport type InvokeCallback<\n TEvent extends EventObject = AnyEventObject,\n TSentEvent extends EventObject = AnyEventObject,\n TInput = unknown\n> = ({\n input,\n system,\n self,\n sendBack,\n receive\n}: {\n /**\n * Data that was provided to the callback actor\n * @see {@link https://stately.ai/docs/input | Input docs}\n */\n input: TInput;\n /**\n * The actor system to which the callback actor belongs\n */\n system: AnyActorSystem;\n /**\n * The parent actor of the callback actor\n */\n self: CallbackActorRef<TEvent>;\n /**\n * A function that can send events back to the parent actor\n */\n sendBack: (event: TSentEvent) => void;\n /**\n * A function that can be called with a listener function argument;\n * the listener is then called whenever events are received by the callback actor\n */\n receive: Receiver<TEvent>;\n}) => (() => void) | void;\n\n/**\n * An actor logic creator which returns callback logic as defined by a callback function.\n *\n * @remarks\n * Useful for subscription-based or other free-form logic that can send events back to the parent actor.\n *\n * Actors created from callback logic (“callback actors”) can:\n * - Receive events via the `receive` function\n * - Send events to the parent actor via the `sendBack` function\n *\n * Callback actors are a bit different from other actors in that they:\n * - Do not work with `onDone`\n * - Do not produce a snapshot using `.getSnapshot()`\n * - Do not emit values when used with `.subscribe()`\n * - Can not be stopped with `.stop()`\n *\n * @param invokeCallback - The callback function used to describe the callback logic\n * The callback function is passed an object with the following properties:\n * - `receive` - A function that can send events back to the parent actor; the listener is then called whenever events are received by the callback actor\n * - `sendBack` - A function that can send events back to the parent actor\n * - `input` - Data that was provided to the callback actor\n * - `self` - The parent actor of the callback actor\n * - `system` - The actor system to which the callback actor belongs\n * The callback function can (optionally) return a cleanup function, which is called when the actor is stopped.\n * @see {@link InvokeCallback} for more information about the callback function and its object argument\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n\n * @returns Callback logic\n *\n * @example\n * ```typescript\n * const callbackLogic = fromCallback(({ sendBack, receive }) => {\n * let lockStatus = 'unlocked';\n *\n * const handler = (event) => {\n * if (lockStatus === 'locked') {\n * return;\n * }\n * sendBack(event);\n * };\n *\n * receive((event) => {\n * if (event.type === 'lock') {\n * lockStatus = 'locked';\n * } else if (event.type === 'unlock') {\n * lockStatus = 'unlocked';\n * }\n * });\n *\n * document.body.addEventListener('click', handler);\n *\n * return () => {\n * document.body.removeEventListener('click', handler);\n * };\n * });\n * ```\n */\nexport function fromCallback<TEvent extends EventObject, TInput = unknown>(\n invokeCallback: InvokeCallback<TEvent, AnyEventObject, TInput>\n): CallbackActorLogic<TEvent, TInput> {\n const logic: CallbackActorLogic<TEvent, TInput> = {\n config: invokeCallback,\n start: (_state, { self, system }) => {\n system._relay(self, self, { type: 'xstate.create' });\n },\n transition: (state, event, { self, system }) => {\n if (event.type === 'xstate.create') {\n const sendBack = (eventForParent: AnyEventObject) => {\n if (state.status === 'stopped') {\n return;\n }\n\n if (self._parent) {\n system._relay(self, self._parent, eventForParent);\n }\n };\n\n const receive: Receiver<TEvent> = (newListener) => {\n state._receivers.add(newListener);\n };\n\n state._dispose = invokeCallback({\n input: state.input,\n system,\n self: self as TODO,\n sendBack,\n receive\n });\n\n return state;\n }\n\n if (event.type === XSTATE_STOP) {\n state = {\n ...state,\n status: 'stopped',\n error: undefined\n };\n\n if (typeof state._dispose === 'function') {\n state._dispose();\n }\n return state;\n }\n\n state._receivers.forEach((receiver) => receiver(event));\n\n return state;\n },\n getInitialState: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n input,\n _receivers: new Set(),\n _dispose: undefined\n };\n },\n getPersistedState: ({ _dispose, _receivers, ...rest }) => rest,\n restoreState: (state: any) => ({\n _receivers: new Set(),\n _dispose: undefined,\n ...state\n })\n };\n\n return logic;\n}\n","import { XSTATE_STOP } from '../constants';\nimport {\n Subscribable,\n ActorLogic,\n EventObject,\n Subscription,\n AnyActorSystem,\n ActorRefFrom,\n Snapshot\n} from '../types';\n\nexport type ObservableSnapshot<TContext, TInput> = Snapshot<undefined> & {\n context: TContext | undefined;\n input: TInput | undefined;\n _subscription: Subscription | undefined;\n};\n\nexport type ObservableActorLogic<TContext, TInput> = ActorLogic<\n ObservableSnapshot<TContext, TInput>,\n { type: string; [k: string]: unknown },\n TInput,\n AnyActorSystem\n>;\n\nexport type ObservableActorRef<TContext> = ActorRefFrom<\n ObservableActorLogic<TContext, any>\n>;\n\nexport function fromObservable<TContext, TInput>(\n observableCreator: ({\n input,\n system\n }: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActorRef<TContext>;\n }) => Subscribable<TContext>\n): ObservableActorLogic<TContext, TInput> {\n const nextEventType = '$$xstate.next';\n const errorEventType = '$$xstate.error';\n const completeEventType = '$$xstate.complete';\n\n // TODO: add event types\n const logic: ObservableActorLogic<TContext, TInput> = {\n config: observableCreator,\n transition: (snapshot, event, { self, id, defer, system }) => {\n if (snapshot.status !== 'active') {\n return snapshot;\n }\n\n switch (event.type) {\n case nextEventType: {\n const newSnapshot = {\n ...snapshot,\n context: event.data as TContext\n };\n return newSnapshot;\n }\n case errorEventType:\n return {\n ...snapshot,\n status: 'error',\n error: (event as any).data,\n input: undefined,\n _subscription: undefined\n };\n case completeEventType:\n return {\n ...snapshot,\n status: 'done',\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_STOP:\n snapshot._subscription!.unsubscribe();\n return {\n ...snapshot,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n };\n default:\n return snapshot;\n }\n },\n getInitialState: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n };\n },\n start: (state, { self, system }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n state._subscription = observableCreator({\n input: state.input!,\n system,\n self\n }).subscribe({\n next: (value) => {\n system._relay(self, self, { type: nextEventType, data: value });\n },\n error: (err) => {\n system._relay(self, self, { type: errorEventType, data: err });\n },\n complete: () => {\n system._relay(self, self, { type: completeEventType });\n }\n });\n },\n getPersistedState: ({ _subscription, ...state }) => state,\n restoreState: (state) => ({\n ...(state as any),\n _subscription: undefined\n })\n };\n\n return logic;\n}\n\n/**\n * Creates event observable logic that listens to an observable\n * that delivers event objects.\n *\n *\n * @param lazyObservable A function that creates an observable\n * @returns Event observable logic\n */\n\nexport function fromEventObservable<T extends EventObject, TInput>(\n lazyObservable: ({\n input,\n system\n }: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActorRef<T>;\n }) => Subscribable<T>\n): ObservableActorLogic<T, TInput> {\n const errorEventType = '$$xstate.error';\n const completeEventType = '$$xstate.complete';\n\n // TODO: event types\n const logic: ObservableActorLogic<T, TInput> = {\n config: lazyObservable,\n transition: (state, event) => {\n if (state.status !== 'active') {\n return state;\n }\n\n switch (event.type) {\n case errorEventType:\n return {\n ...state,\n status: 'error',\n error: (event as any).data,\n input: undefined,\n _subscription: undefined\n };\n case completeEventType:\n return {\n ...state,\n status: 'done',\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_STOP:\n state._subscription!.unsubscribe();\n return {\n ...state,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n };\n default:\n return state;\n }\n },\n getInitialState: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n };\n },\n start: (state, { self, system }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n\n state._subscription = lazyObservable({\n input: state.input!,\n system,\n self\n }).subscribe({\n next: (value) => {\n if (self._parent) {\n system._relay(self, self._parent, value);\n }\n },\n error: (err) => {\n system._relay(self, self, { type: errorEventType, data: err });\n },\n complete: () => {\n system._relay(self, self, { type: completeEventType });\n }\n });\n },\n getPersistedState: ({ _subscription, ...state }) => state,\n restoreState: (state: any) => ({\n ...state,\n _subscription: undefined\n })\n };\n\n return logic;\n}\n"],"names":["Mailbox","constructor","_process","this","_active","_current","_last","start","flush","clear","next","enqueue","event","enqueued","value","consumed","XSTATE_STOP","createErrorActorEvent","id","data","type","getDevTools","w","globalThis","self","window","__xstate__","devToolsAdapter","service","devTools","register","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","idCounter","toObserver","nextHandler","errorHandler","completionHandler","isObserver","undefined","bind","error","complete","ProcessingStatus","defaultOptions","clock","fn","ms","clearTimeout","logger","console","log","Actor","logic","options","_state","mailbox","delayedEventsMap","observers","Set","_processingStatus","NotStarted","_parent","ref","_actorScope","_systemId","sessionId","system","_doneEvent","src","_deferred","resolvedOptions","parent","systemId","inspect","rootActor","children","Map","keyedActors","reverseKeyedActors","WeakMap","_bookId","_register","actorRef","set","_unregister","delete","get","_set","existing","Error","observer","add","_sendInspectionEvent","resolvedInspectionEvent","rootId","forEach","_relay","source","target","sourceRef","_send","createSystem","defer","push","stopChild","child","_stop","send","_initState","state","status","persistedState","restoreState","getInitialState","input","update","snapshot","deferredFn","shift","_stopProcedure","_complete","invokeId","output","_error","subscribe","nextListenerOrObserver","errorListener","completeListener","Stopped","unsubscribe","Running","initEvent","attachDevTools","nextState","caughtError","transition","stop","size","reportError","err2","key","Object","keys","delaySend","params","delay","timerId","to","cancel","sendId","toJSON","xstate$$type","getPersistedState","getSnapshot","fromTransition","initialContext","config","actorScope","context","_","resolveEventType","rejectEventType","emptyLogic","invokeCallback","sendBack","eventForParent","receive","newListener","_receivers","_dispose","receiver","rest","lazyObservable","errorEventType","completeEventType","_subscription","observableCreator","nextEventType","promiseCreator","resolvedValue","Promise","resolve","then","response","errorData"],"mappings":"oPAKO,MAAMA,EAKXC,YAAoBC,GAA2BC,KAA3BD,SAAAA,EAAyBC,KAJrCC,SAAmB,EAAKD,KACxBE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ACpBA,EACJkE,mBAAezI,IAKrB,gBHpFO,SAEL4I,GAkFA,MAxEkD,CAChDtB,OAAQsB,EACR3C,WAAY,CAAC1B,EAAOtG,KAClB,GAAqB,WAAjBsG,EAAMC,OACR,OAAOD,EAGT,OAAQtG,EAAMQ,MACZ,KAAKiJ,EAAkB,CACrB,MAAMmB,EAAiB5K,EAAcO,KACrC,MAAO,IACF+F,EACHC,OAAQ,OACRY,OAAQyD,EACRjE,WAAO5E,EAEX,CACA,KAAK2H,EACH,MAAO,IACFpD,EACHC,OAAQ,QACRtE,MAAQjC,EAAcO,KACtBoG,WAAO5E,GAEX,KAAK3B,EACH,MAAO,IACFkG,EACHC,OAAQ,UACRI,WAAO5E,GAEX,QACE,OAAOuE,EAAM,EAGnB3G,MAAO,CAAC2G,GAAS1F,OAAM+C,aAGrB,GAAqB,WAAjB2C,EAAMC,OACR,OAGsBsE,QAAQC,QAC9BH,EAAe,CAAEhE,MAAOL,EAAMK,MAAQhD,SAAQ/C,UAGhCmK,MACbC,IACmC,WAA9BpK,EAAKsI,cAAc3C,QAGvB5C,EAAO8B,OAAO7E,EAAMA,EAAM,CAAEJ,KAAMiJ,EAAkBlJ,KAAMyK,GAAW,IAEtEC,IACmC,WAA9BrK,EAAKsI,cAAc3C,QAGvB5C,EAAO8B,OAAO7E,EAAMA,EAAM,CAAEJ,KAAMkJ,EAAiBnJ,KAAM0K,GAAY,GAExE,EAEHvE,gBAAiB,CAAC8C,EAAG7C,KACZ,CACLJ,OAAQ,SACRY,YAAQpF,EACRE,WAAOF,EACP4E,UAGJsC,kBAAoB3C,GAAUA,EAC9BG,aAAeH,GAAeA,EAIlC"}
@@ -85,5 +85,5 @@ export declare class State<TContext extends MachineContext, TEvent extends Event
85
85
  get meta(): Record<string, any>;
86
86
  }
87
87
  export declare function cloneState<TState extends AnyState>(state: TState, config?: Partial<StateConfig<any, any>>): TState;
88
- export declare function getPersistedState<TContext extends MachineContext, TEvent extends EventObject, TActor extends ProvidedActor, TTag extends string, TOutput, TResolvedTypesMeta = TypegenDisabled>(state: MachineSnapshot<TContext, TEvent, TActor, TTag, TOutput, TResolvedTypesMeta>): Snapshot<unknown>;
88
+ export declare function getPersistedState<TContext extends MachineContext, TEvent extends EventObject, TActor extends ProvidedActor, TTag extends string, TOutput, TResolvedTypesMeta = TypegenDisabled>(state: MachineSnapshot<TContext, TEvent, TActor, TTag, TOutput, TResolvedTypesMeta>, options?: unknown): Snapshot<unknown>;
89
89
  export {};
@@ -92,7 +92,7 @@ export declare class StateMachine<TContext extends MachineContext, TEvent extend
92
92
  getStateNodeById(stateId: string): StateNode<TContext, TEvent>;
93
93
  get definition(): StateMachineDefinition<TContext, TEvent>;
94
94
  toJSON(): StateMachineDefinition<TContext, TEvent>;
95
- getPersistedState(state: MachineSnapshot<TContext, TEvent, TActor, TTag, TOutput, TResolvedTypesMeta>): Snapshot<unknown>;
95
+ getPersistedState(state: MachineSnapshot<TContext, TEvent, TActor, TTag, TOutput, TResolvedTypesMeta>, options?: unknown): Snapshot<unknown>;
96
96
  createState(stateConfig: MachineSnapshot<TContext, TEvent, TActor, TTag, TOutput, TResolvedTypesMeta> | StateConfig<TContext, TEvent>): MachineSnapshot<TContext, TEvent, TActor, TTag, TOutput, TResolvedTypesMeta>;
97
97
  restoreState(snapshot: Snapshot<unknown>, _actorScope: ActorScope<MachineSnapshot<TContext, TEvent, TActor, TTag, TOutput, TResolvedTypesMeta>, TEvent>): MachineSnapshot<TContext, TEvent, TActor, TTag, TOutput, TResolvedTypesMeta>;
98
98
  /**@deprecated an internal property acting as a "phantom" type, not meant to be used at runtime */
@@ -44,7 +44,7 @@ export type InvokeCallback<TEvent extends EventObject = AnyEventObject, TSentEve
44
44
  * - Send events to the parent actor via the `sendBack` function
45
45
  *
46
46
  * Callback actors are a bit different from other actors in that they:
47
- * - Do not work with `onDone` or `onError`
47
+ * - Do not work with `onDone`
48
48
  * - Do not produce a snapshot using `.getSnapshot()`
49
49
  * - Do not emit values when used with `.subscribe()`
50
50
  * - Can not be stopped with `.stop()`
@@ -7,13 +7,13 @@ export { getStateNodes } from "./stateUtils.js";
7
7
  export * from "./typegenTypes.js";
8
8
  export * from "./types.js";
9
9
  export { waitFor } from "./waitFor.js";
10
- import { Actor, ActorStatus, createActor, interpret, Interpreter, InterpreterStatus } from "./interpreter.js";
10
+ import { Actor, createActor, interpret, Interpreter } from "./interpreter.js";
11
11
  import { createMachine } from "./Machine.js";
12
12
  import { mapState } from "./mapState.js";
13
13
  import { State } from "./State.js";
14
14
  import { StateNode } from "./StateNode.js";
15
15
  export { matchesState, pathToStateValue, toObserver } from "./utils.js";
16
- export { Actor, ActorStatus, createActor, createMachine, interpret, InterpreterStatus, mapState, State, StateNode, type Interpreter };
16
+ export { Actor, createActor, createMachine, interpret, mapState, State, StateNode, type Interpreter };
17
17
  export type { InspectedActorEvent, InspectedEventEvent, InspectedSnapshotEvent, InspectionEvent } from "./system.js";
18
18
  export { and, not, or, stateIn } from "./guards.js";
19
19
  declare global {
@@ -11,15 +11,11 @@ export interface Clock {
11
11
  setTimeout(fn: (...args: any[]) => void, timeout: number): any;
12
12
  clearTimeout(id: any): void;
13
13
  }
14
- export declare enum ActorStatus {
14
+ export declare enum ProcessingStatus {
15
15
  NotStarted = 0,
16
16
  Running = 1,
17
17
  Stopped = 2
18
18
  }
19
- /**
20
- * @deprecated Use `ActorStatus` instead.
21
- */
22
- export declare const InterpreterStatus: typeof ActorStatus;
23
19
  /**
24
20
  * An Actor is a running process that can receive events, send events and change its behavior based on the events it receives, which can cause effects outside of the actor. When you run a state machine, it becomes an actor.
25
21
  */
@@ -42,10 +38,6 @@ export declare class Actor<TLogic extends AnyActorLogic> implements ActorRef<Eve
42
38
  private delayedEventsMap;
43
39
  private observers;
44
40
  private logger;
45
- /**
46
- * Whether the service is started.
47
- */
48
- status: ActorStatus;
49
41
  _parent?: ActorRef<any, any>;
50
42
  ref: ActorRef<EventFromLogic<TLogic>, SnapshotFrom<TLogic>>;
51
43
  private _actorScope;
@@ -59,7 +51,7 @@ export declare class Actor<TLogic extends AnyActorLogic> implements ActorRef<Eve
59
51
  */
60
52
  system: ActorSystem<any>;
61
53
  private _doneEvent?;
62
- src?: string;
54
+ src: string | AnyActorLogic;
63
55
  /**
64
56
  * Creates a new actor instance for the given logic with the provided options, if any.
65
57
  *
@@ -2,21 +2,25 @@ import { AnyEventObject, ActorSystem, ActorSystemInfo, AnyActorRef, Snapshot } f
2
2
  export declare function createSystem<T extends ActorSystemInfo>(rootActor: AnyActorRef): ActorSystem<T>;
3
3
  export interface BaseInspectionEventProperties {
4
4
  rootId: string;
5
+ /**
6
+ * The relevant actorRef for the inspection event.
7
+ * - For snapshot events, this is the `actorRef` of the snapshot.
8
+ * - For event events, this is the target `actorRef` (recipient of event).
9
+ * - For actor events, this is the `actorRef` of the registered actor.
10
+ */
11
+ actorRef: AnyActorRef;
5
12
  }
6
13
  export interface InspectedSnapshotEvent extends BaseInspectionEventProperties {
7
14
  type: '@xstate.snapshot';
8
- actorRef: AnyActorRef;
9
15
  event: AnyEventObject;
10
16
  snapshot: Snapshot<unknown>;
11
17
  }
12
18
  export interface InspectedEventEvent extends BaseInspectionEventProperties {
13
19
  type: '@xstate.event';
14
20
  sourceRef: AnyActorRef | undefined;
15
- targetRef: AnyActorRef;
16
21
  event: AnyEventObject;
17
22
  }
18
23
  export interface InspectedActorEvent extends BaseInspectionEventProperties {
19
24
  type: '@xstate.actor';
20
- actorRef: AnyActorRef;
21
25
  }
22
26
  export type InspectionEvent = InspectedSnapshotEvent | InspectedEventEvent | InspectedActorEvent;